Skip to content

armgit / LEANN

Public Imported from GitHub
0

[MLsys2026 Best Paper]: https://arxiv.org/abs/2506.08276. RAG on Everything with LEANN. Enjoy 97% storage savings while running a fast, accurate, and 100% private RAG application on your personal device.

Initial commit

yichuan52003091032046f6cc100b31
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..898ed5c
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+paper_plot/data/big_graph_degree_data.npz filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
new file mode 100755
index 0000000..0ad5a54
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,72 @@
+raw_data/
+scaling_out/
+scaling_out_old/
+sanity_check/
+demo/indices/
+# .vscode/
+*.log
+*pycache*
+outputs/
+*.pkl
+.history/
+scripts/
+lm_eval.egg-info/
+demo/experiment_results/**/*.json
+*.jsonl
+*.sh
+*.txt
+!CMakeLists.txt
+latency_breakdown*.json
+experiment_results/eval_results/diskann/*.json
+aws/
+.venv/
+.cursor/rules/
+*.egg-info/
+skip_reorder_comparison/
+analysis_results/
+build/
+.cache/
+nprobe_logs/
+micro/results
+micro/contriever-INT8
+*.qdstrm
+benchmark_results/
+results/
+frac_*.png
+final_in_*.png
+embedding_comparison_results/
+*.ind
+*.gz
+*.fvecs
+*.ivecs
+*.index
+*.bin
+
+read_graph
+analyze_diskann_graph
+degree_distribution.png
+micro/degree_distribution.png
+
+policy_results_*
+results_*/
+experiment_results/
+.DS_Store
+
+# The above are inherited from old Power RAG repo
+
+# Python-generated files
+__pycache__/
+*.py[oc]
+build/
+dist/
+wheels/
+*.egg-info
+
+# Virtual environments
+.venv
+.env
+
+test_indices*/
+test_*.py
+!tests/**
+packages/leann-backend-diskann/third_party/DiskANN/_deps/
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..8c49b3e
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,6 @@
+[submodule "packages/leann-backend-diskann/third_party/DiskANN"]
+ path = packages/leann-backend-diskann/third_party/DiskANN
+ url = https://github.com/yichuan520030910320/DiskANN.git
+[submodule "packages/leann-backend-hnsw/third_party/faiss"]
+ path = packages/leann-backend-hnsw/third_party/faiss
+ url = https://github.com/yichuan520030910320/faiss.git
diff --git a/.python-version b/.python-version
new file mode 100644
index 0000000..2c07333
--- /dev/null
+++ b/.python-version
@@ -0,0 +1 @@
+3.11
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
new file mode 100644
index 0000000..e793901
--- /dev/null
+++ b/.vscode/extensions.json
@@ -0,0 +1,9 @@
+{
+ "recommendations": [
+ "llvm-vs-code-extensions.vscode-clangd",
+ "ms-python.python",
+ "ms-vscode.cmake-tools",
+ "vadimcn.vscode-lldb",
+ "eamodio.gitlens",
+ ]
+}
\ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100755
index 0000000..5f96fb2
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,283 @@
+{
+ // Use IntelliSense to learn about possible attributes.
+ // Hover to view descriptions of existing attributes.
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ // new emdedder
+ {
+ "name": "New Embedder",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "demo/main.py",
+ "console": "integratedTerminal",
+ "args": [
+ "--search",
+ "--use-original",
+ "--domain",
+ "dpr",
+ "--nprobe",
+ "5000",
+ "--load",
+ "flat",
+ "--embedder",
+ "intfloat/multilingual-e5-small"
+ ]
+ }
+ //python /home/ubuntu/Power-RAG/faiss/demo/simple_build.py
+ {
+ "name": "main.py",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "demo/main.py",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "--query",
+ "1000",
+ "--load",
+ "bm25"
+ ]
+ },
+ {
+ "name": "Simple Build",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "faiss/demo/simple_build.py"
+ ],
+ "env": {
+ "LD_PRELOAD": "/lib/x86_64-linux-gnu/libmkl_core.so:/lib/x86_64-linux-gnu/libmkl_intel_thread.so:/lib/x86_64-linux-gnu/libmkl_intel_lp64.so:/lib/x86_64-linux-gnu/libiomp5.so"
+ }
+ },
+ //# Fix for Intel MKL error
+ //export LD_PRELOAD=/lib/x86_64-linux-gnu/libmkl_core.so:/lib/x86_64-linux-gnu/libmkl_intel_thread.so:/lib/x86_64-linux-gnu/libmkl_intel_lp64.so:/lib/x86_64-linux-gnu/libiomp5.so
+ //python faiss/demo/build_demo.py
+ {
+ "name": "Build Demo",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "faiss/demo/build_demo.py"
+ ],
+ "env": {
+ "LD_PRELOAD": "/lib/x86_64-linux-gnu/libmkl_core.so:/lib/x86_64-linux-gnu/libmkl_intel_thread.so:/lib/x86_64-linux-gnu/libmkl_intel_lp64.so:/lib/x86_64-linux-gnu/libiomp5.so"
+ }
+ },
+ {
+ "name": "DiskANN Serve",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "demo/main.py",
+ "--mode",
+ "serve",
+ "--engine",
+ "sglang",
+ "--load-indices",
+ "diskann",
+ "--domain",
+ "rpj_wiki",
+ "--lazy-load",
+ "--recompute-beighbor-embeddings",
+ "--port",
+ "8082",
+ "--diskann-search-memory-maximum",
+ "2",
+ "--diskann-graph",
+ "240",
+ "--search-only"
+ ],
+ "env": {
+ "PYTHONPATH": "${workspaceFolder}/faiss_repo/build/faiss/python:$PYTHONPATH"
+ },
+ "preLaunchTask": "CMake: build",
+ },
+ {
+ "name": "DiskANN Serve MAC",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "demo/main.py",
+ "--mode",
+ "serve",
+ "--engine",
+ "ollama",
+ "--load-indices",
+ "diskann",
+ "--domain",
+ "rpj_wiki",
+ "--lazy-load",
+ "--recompute-beighbor-embeddings"
+ ],
+ "preLaunchTask": "CMake: build",
+ "env": {
+ "KMP_DUPLICATE_LIB_OK": "TRUE",
+ "OMP_NUM_THREADS": "1",
+ "MKL_NUM_THREADS": "1",
+ "DYLD_INSERT_LIBRARIES": "/Users/ec2-user/Power-RAG/.venv/lib/python3.10/site-packages/torch/lib/libomp.dylib",
+ "KMP_BLOCKTIME": "0"
+ }
+ },
+ {
+ "name": "Python Debugger: Current File with Arguments",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "ric/main_ric.py",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "--config-name",
+ "${input:configSelection}"
+ ],
+ "justMyCode": false
+ },
+ //python ./demo/validate_equivalence.py sglang
+ {
+ "name": "Validate Equivalence",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "demo/validate_equivalence.py",
+ "console": "integratedTerminal",
+ "args": [
+ "sglang"
+ ],
+ },
+ //python demo/retrieval_demo.py --engine sglang --skip-embeddings --domain dpr --load-indices flat ivf_flat
+ {
+ "name": "Retrieval Demo",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "demo/retrieval_demo.py",
+ "console": "integratedTerminal",
+ "args": [
+ "--engine",
+ "vllm",
+ "--skip-embeddings",
+ "--domain",
+ "dpr",
+ "--load-indices",
+ // "flat",
+ "ivf_flat"
+ ],
+ },
+ //python demo/retrieval_demo.py --engine sglang --skip-embeddings --domain dpr --load-indices diskann --hnsw-M 64 --hnsw-efConstruction 150 --hnsw-efSearch 128 --hnsw-sq-bits 8
+ {
+ "name": "Retrieval Demo DiskANN",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "demo/retrieval_demo.py",
+ "console": "integratedTerminal",
+ "args": [
+ "--engine",
+ "sglang",
+ "--skip-embeddings",
+ "--domain",
+ "dpr",
+ "--load-indices",
+ "diskann",
+ "--hnsw-M",
+ "64",
+ "--hnsw-efConstruction",
+ "150",
+ "--hnsw-efSearch",
+ "128",
+ "--hnsw-sq-bits",
+ "8"
+ ],
+ },
+ {
+ "name": "Find Probe",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "find_probe.py",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ },
+ {
+ "name": "Python: Attach",
+ "type": "debugpy",
+ "request": "attach",
+ "processId": "${command:pickProcess}",
+ "justMyCode": true
+ },
+ {
+ "name": "Edge RAG",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "edgerag_demo.py"
+ ],
+ "env": {
+ "LD_PRELOAD": "/lib/x86_64-linux-gnu/libiomp5.so /lib/x86_64-linux-gnu/libmkl_core.so /lib/x86_64-linux-gnu/libmkl_intel_lp64.so /lib/x86_64-linux-gnu/libmkl_intel_thread.so",
+ "MKL_NUM_THREADS": "1",
+ "OMP_NUM_THREADS": "1",
+ }
+ },
+ {
+ "name": "Launch Embedding Server",
+ "type": "debugpy",
+ "request": "launch",
+ "program": "demo/embedding_server.py",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "--domain",
+ "rpj_wiki",
+ "--zmq-port",
+ "5556",
+ ]
+ },
+ {
+ "name": "HNSW Serve",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "demo/main.py",
+ "--domain",
+ "rpj_wiki",
+ "--load",
+ "hnsw",
+ "--mode",
+ "serve",
+ "--search",
+ "--skip-pa",
+ "--recompute",
+ "--hnsw-old"
+ ],
+ "env": {
+ "LD_PRELOAD": "/lib/x86_64-linux-gnu/libmkl_core.so:/lib/x86_64-linux-gnu/libmkl_intel_thread.so:/lib/x86_64-linux-gnu/libmkl_intel_lp64.so:/lib/x86_64-linux-gnu/libiomp5.so"
+ }
+ },
+ ],
+ "inputs": [
+ {
+ "id": "configSelection",
+ "type": "pickString",
+ "description": "Select a configuration",
+ "options": [
+ "example_config",
+ "vllm_gritlm"
+ ],
+ "default": "example_config"
+ }
+ ],
+}
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100755
index 0000000..e2b5794
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,43 @@
+{
+ "python.analysis.extraPaths": [
+ "./sglang_repo/python"
+ ],
+ "cmake.sourceDirectory": "${workspaceFolder}/DiskANN",
+ "cmake.configureArgs": [
+ "-DPYBIND=True",
+ "-DUPDATE_EDITABLE_INSTALL=ON",
+ ],
+ "cmake.environment": {
+ "PATH": "/Users/ec2-user/Power-RAG/.venv/bin:${env:PATH}"
+ },
+ "cmake.buildDirectory": "${workspaceFolder}/build",
+ "files.associations": {
+ "*.tcc": "cpp",
+ "deque": "cpp",
+ "string": "cpp",
+ "unordered_map": "cpp",
+ "vector": "cpp",
+ "map": "cpp",
+ "unordered_set": "cpp",
+ "atomic": "cpp",
+ "inplace_vector": "cpp",
+ "*.ipp": "cpp",
+ "forward_list": "cpp",
+ "list": "cpp",
+ "any": "cpp",
+ "system_error": "cpp",
+ "__hash_table": "cpp",
+ "__split_buffer": "cpp",
+ "__tree": "cpp",
+ "ios": "cpp",
+ "set": "cpp",
+ "__string": "cpp",
+ "string_view": "cpp",
+ "ranges": "cpp",
+ "iosfwd": "cpp"
+ },
+ "lldb.displayFormat": "auto",
+ "lldb.showDisassembly": "auto",
+ "lldb.dereferencePointers": true,
+ "lldb.consoleMode": "commands",
+}
\ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 0000000..4edc48b
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,16 @@
+{
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "type": "cmake",
+ "label": "CMake: build",
+ "command": "build",
+ "targets": [
+ "all"
+ ],
+ "group": "build",
+ "problemMatcher": [],
+ "detail": "CMake template build task"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100755
index 0000000..0419215
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2024 Rulin Shao
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100755
index 0000000..5f85426
--- /dev/null
+++ b/README.md
@@ -0,0 +1,292 @@
+# 🚀 LEANN: A Low-Storage Vector Index
+
+<p align="center">
+ <img src="https://img.shields.io/badge/Python-3.9%2B-blue.svg" alt="Python 3.9+">
+ <img src="https://img.shields.io/badge/License-MIT-green.svg" alt="MIT License">
+ <img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs Welcome">
+ <img src="https://img.shields.io/badge/Platform-Linux%20%7C%20macOS%20%7C%20Windows-lightgrey" alt="Platform">
+</p>
+
+<p align="center">
+ <strong>⚡ Real-time embedding computation for large-scale RAG on consumer hardware</strong>
+</p>
+
+<p align="center">
+ <a href="#-quick-start">Quick Start</a> •
+ <a href="#-features">Features</a> •
+ <a href="#-benchmarks">Benchmarks</a> •
+ <a href="#-documentation">Documentation</a> •
+ <a href="#-paper">Paper</a>
+</p>
+
+---
+
+## 🌟 What is Leann?
+
+**Leann** revolutionizes Retrieval-Augmented Generation (RAG) by eliminating the storage bottleneck of traditional vector databases. Instead of pre-computing and storing billions of embeddings, Leann dynamically computes embeddings at query time using highly optimized graph-based search algorithms.
+
+### 🎯 Why Leann?
+
+Traditional RAG systems face a fundamental trade-off:
+- **💾 Storage**: Storing embeddings for millions of documents requires massive disk space
+- **🔄 Freshness**: Pre-computed embeddings become stale when documents change
+- **💰 Cost**: Vector databases are expensive to scale
+
+**Leann solves this by:**
+- ✅ **Zero embedding storage** - Only graph structure is persisted
+- ✅ **Real-time computation** - Embeddings computed on-demand with ms latency
+- ✅ **Memory efficient** - Runs on consumer hardware (8GB RAM)
+- ✅ **Always fresh** - No stale embeddings, ever
+
+## 🚀 Quick Start
+
+### Installation
+
+```bash
+git clone https://github.com/yichuan520030910320/Power-RAG.git leann
+cd leann
+uv sync
+```
+
+### 30-Second Example
+
+```python
+from leann.api import LeannBuilder, LeannSearcher
+
+# 1. Build index (no embeddings stored!)
+builder = LeannBuilder(backend_name="diskann")
+builder.add_text("Python is a powerful programming language")
+builder.add_text("Machine learning transforms industries")
+builder.add_text("Neural networks process complex data")
+builder.build_index("knowledge.leann")
+
+# 2. Search with real-time embeddings
+searcher = LeannSearcher("knowledge.leann")
+results = searcher.search("programming languages", top_k=2)
+
+for result in results:
+ print(f"Score: {result['score']:.3f} - {result['text']}")
+```
+
+### Run the Demo
+
+```bash
+uv run examples/document_search.py
+```
+
+**PDF RAG Demo (using LlamaIndex for document parsing and Leann for indexing/search)**
+
+This demo showcases how to build a RAG system for PDF documents using Leann.
+1. Place your PDF files (and other supported formats like .docx, .pptx, .xlsx) into the `examples/data/` directory.
+2. Ensure you have an `OPENAI_API_KEY` set in your environment variables or in a `.env` file for the LLM to function.
+
+```bash
+uv run examples/main_cli_example.py
+```
+
+## ✨ Features
+
+### 🔥 Core Features
+- **📊 Multiple Distance Functions**: L2, Cosine, MIPS (Maximum Inner Product Search)
+- **🏗️ Pluggable Backends**: DiskANN, HNSW/FAISS with unified API
+- **🔄 Real-time Embeddings**: Dynamic computation using optimized ZMQ servers
+- **📈 Scalable Architecture**: Handles millions of documents on consumer hardware
+- **🎯 Graph Pruning**: Advanced techniques for memory-efficient search
+
+### 🛠️ Technical Highlights
+- **Zero-copy operations** for maximum performance
+- **SIMD-optimized** distance computations (AVX2/AVX512)
+- **Async embedding pipeline** with batched processing
+- **Memory-mapped indices** for fast startup
+- **Recompute mode** for highest accuracy scenarios
+
+### 🎨 Developer Experience
+- **Simple Python API** - Get started in minutes
+- **Extensible backend system** - Easy to add new algorithms
+- **Comprehensive examples** - From basic usage to production deployment
+- **Rich debugging tools** - Built-in performance profiling
+
+## 📊 Benchmarks
+
+### Memory Usage Comparison
+
+| System | 1M Documents | 10M Documents | 100M Documents |
+|--------|-------------|---------------|----------------|
+| Traditional Vector DB | 3.1 GB | 31 GB | 310 GB |
+| **Leann** | **180 MB** | **1.2 GB** | **8.4 GB** |
+| **Reduction** | **94.2%** | **96.1%** | **97.3%** |
+
+### Query Performance
+
+| Backend | Index Size | Query Time | Recall@10 |
+|---------|------------|------------|-----------|
+| DiskANN | 1M docs | 12ms | 0.95 |
+| DiskANN + Recompute | 1M docs | 145ms | 0.98 |
+| HNSW | 1M docs | 8ms | 0.93 |
+
+*Benchmarks run on AMD Ryzen 7 with 32GB RAM*
+
+## 🏗️ Architecture
+
+```
+┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
+│ Query Text │───▶│ Embedding │───▶│ Graph-based │
+│ │ │ Computation │ │ Search │
+└─────────────────┘ └──────────────────┘ └─────────────────┘
+ │ │
+ ▼ ▼
+ ┌──────────────┐ ┌──────────────┐
+ │ ZMQ Server │ │ Pruned Graph │
+ │ (Cached) │ │ Index │
+ └──────────────┘ └──────────────┘
+```
+
+### Key Components
+
+1. **🧠 Embedding Engine**: Real-time transformer inference with caching
+2. **📊 Graph Index**: Memory-efficient navigation structures
+3. **🔄 Search Coordinator**: Orchestrates embedding + graph search
+4. **⚡ Backend Adapters**: Pluggable algorithm implementations
+
+## 🎓 Supported Models & Backends
+
+### 🤖 Embedding Models
+- **sentence-transformers/all-mpnet-base-v2** (default)
+- **sentence-transformers/all-MiniLM-L6-v2** (lightweight)
+- Any HuggingFace sentence-transformer model
+- Custom model support via API
+
+### 🔧 Search Backends
+- **DiskANN**: Microsoft's billion-scale ANN algorithm
+- **HNSW**: Hierarchical Navigable Small World graphs
+- **Coming soon**: ScaNN, Faiss-IVF, NGT
+
+### 📏 Distance Functions
+- **L2**: Euclidean distance for precise similarity
+- **Cosine**: Angular similarity for normalized vectors
+- **MIPS**: Maximum Inner Product Search for recommendation systems
+
+## 🔬 Paper
+
+If you find Leann useful, please cite:
+
+**[LEANN: A Low-Storage Vector Index](https://arxiv.org/abs/2506.08276)**
+
+```bibtex
+@misc{wang2025leannlowstoragevectorindex,
+ title={LEANN: A Low-Storage Vector Index},
+ author={Yichuan Wang and Shu Liu and Zhifei Li and Yongji Wu and Ziming Mao and Yilong Zhao and Xiao Yan and Zhiying Xu and Yang Zhou and Ion Stoica and Sewon Min and Matei Zaharia and Joseph E. Gonzalez},
+ year={2025},
+ eprint={2506.08276},
+ archivePrefix={arXiv},
+ primaryClass={cs.DB},
+ url={https://arxiv.org/abs/2506.08276},
+}
+```
+
+## 🌍 Use Cases
+
+### 💼 Enterprise RAG
+```python
+# Handle millions of documents with limited resources
+builder = LeannBuilder(
+ backend_name="diskann",
+ distance_metric="cosine",
+ graph_degree=64,
+ memory_budget="4GB"
+)
+```
+
+### 🔬 Research & Experimentation
+```python
+# Quick prototyping with different algorithms
+for backend in ["diskann", "hnsw"]:
+ searcher = LeannSearcher(index_path, backend=backend)
+ evaluate_recall(searcher, queries, ground_truth)
+```
+
+### 🚀 Real-time Applications
+```python
+# Sub-second response times
+chat = LeannChat("knowledge.leann")
+response = chat.ask("What is quantum computing?")
+# Returns in <100ms with recompute mode
+```
+
+## 🤝 Contributing
+
+We welcome contributions! Leann is built by the community, for the community.
+
+### Ways to Contribute
+- 🐛 **Bug Reports**: Found an issue? Let us know!
+- 💡 **Feature Requests**: Have an idea? We'd love to hear it!
+- 🔧 **Code Contributions**: PRs welcome for all skill levels
+- 📖 **Documentation**: Help make Leann more accessible
+- 🧪 **Benchmarks**: Share your performance results
+
+### Development Setup
+```bash
+git clone https://github.com/yourname/leann
+cd leann
+uv sync --dev
+uv run pytest tests/
+```
+
+### Quick Tests
+```bash
+# Sanity check all distance functions
+uv run python tests/sanity_checks/test_distance_functions.py
+
+# Verify L2 implementation
+uv run python tests/sanity_checks/test_l2_verification.py
+```
+
+## 📈 Roadmap
+
+### 🎯 Q1 2024
+- [x] DiskANN backend with MIPS/L2/Cosine support
+- [x] HNSW backend integration
+- [x] Real-time embedding pipeline
+- [x] Memory-efficient graph pruning
+
+### 🚀 Q2 2024
+- [ ] Distributed search across multiple nodes
+- [ ] ScaNN backend support
+- [ ] Advanced caching strategies
+- [ ] Kubernetes deployment guides
+
+### 🌟 Q3 2024
+- [ ] GPU-accelerated embedding computation
+- [ ] Approximate distance functions
+- [ ] Integration with LangChain/LlamaIndex
+- [ ] Visual similarity search
+
+## 💬 Community
+
+Join our growing community of researchers and engineers!
+
+- 🐦 **Twitter**: [@LeannAI](https://twitter.com/LeannAI)
+- 💬 **Discord**: [Join our server](https://discord.gg/leann)
+- 📧 **Email**: [email protected]
+- 🐙 **GitHub Discussions**: [Ask questions here](https://github.com/yourname/leann/discussions)
+
+## 📄 License
+
+MIT License - see [LICENSE](LICENSE) for details.
+
+## 🙏 Acknowledgments
+
+- **Microsoft Research** for the DiskANN algorithm
+- **Meta AI** for FAISS and optimization insights
+- **HuggingFace** for the transformer ecosystem
+- **Our amazing contributors** who make this possible
+
+---
+
+<p align="center">
+ <strong>⭐ Star us on GitHub if Leann is useful for your research or applications!</strong>
+</p>
+
+<p align="center">
+ Made with ❤️ by the Leann team
+</p>
\ No newline at end of file
diff --git a/demo.ipynb b/demo.ipynb
new file mode 100644
index 0000000..a27c93b
--- /dev/null
+++ b/demo.ipynb
@@ -0,0 +1,248 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "INFO: LeannBuilder initialized with 'diskann' backend.\n",
+ "INFO: Computing embeddings for 6 chunks using 'sentence-transformers/all-mpnet-base-v2'...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Batches: 100%|██████████| 1/1 [00:00<00:00, 77.61it/s]"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "INFO: Building DiskANN index for 6 vectors with metric Metric.INNER_PRODUCT...\n",
+ "Using Inner Product search, so need to pre-process base data into temp file. Please ensure there is additional (n*(d+1)*4) bytes for storing pre-processed base vectors, apart from the interim indices created by DiskANN and the final index.\n",
+ "Pre-processing base file by adding extra coordinate\n",
+ "✅ DiskANN index built successfully at 'knowledge'\n",
+ "Writing bin: knowledge_disk.index_max_base_norm.bin\n",
+ "bin: #pts = 1, #dims = 1, size = 12B\n",
+ "Finished writing bin.\n",
+ "Time for preprocessing data for inner product: 0.000165 seconds\n",
+ "Reading max_norm_of_base from knowledge_disk.index_max_base_norm.bin\n",
+ "Reading bin file knowledge_disk.index_max_base_norm.bin ...\n",
+ "Opening bin file knowledge_disk.index_max_base_norm.bin... \n",
+ "Metadata: #pts = 1, #dims = 1...\n",
+ "done.\n",
+ "max_norm_of_base: 1\n",
+ "! Using prepped_base file at knowledge_prepped_base.bin\n",
+ "Starting index build: R=32 L=64 Query RAM budget: 4.02653e+09 Indexing ram budget: 8 T: 8\n",
+ "getting bin metadata\n",
+ "Time for getting bin metadata: 0.000008 seconds\n",
+ "Compressing 769-dimensional data into 512 bytes per vector.\n",
+ "Opened: knowledge_prepped_base.bin, size: 18464, cache_size: 18464\n",
+ "Training data with 6 samples loaded.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 256, #dims = 769...\n",
+ "done.\n",
+ "PQ pivot file exists. Not generating again\n",
+ "Opened: knowledge_prepped_base.bin, size: 18464, cache_size: 18464\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 4, #dims = 1...\n",
+ "done.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 256, #dims = 769...\n",
+ "done.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 769, #dims = 1...\n",
+ "done.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 513, #dims = 1...\n",
+ "done.\n",
+ "Loaded PQ pivot information\n",
+ "Processing points [0, 6)...done.\n",
+ "Time for generating quantized data: 0.023918 seconds\n",
+ "Full index fits in RAM budget, should consume at most 2.03973e-05GiBs, so building in one shot\n",
+ "L2: Using AVX2 distance computation DistanceL2Float\n",
+ "Passed, empty search_params while creating index config\n",
+ "Using only first 6 from file.. \n",
+ "Starting index build with 6 points... \n",
+ "0% of index build completed.Starting final cleanup..done. Link time: 9e-05s\n",
+ "Index built with degree: max:5 avg:5 min:5 count(deg<2):0\n",
+ "Not saving tags as they are not enabled.\n",
+ "Time taken for save: 0.000178s.\n",
+ "Time for building merged vamana index: 0.000579 seconds\n",
+ "Opened: knowledge_prepped_base.bin, size: 18464, cache_size: 18464\n",
+ "Vamana index file size=168\n",
+ "Opened: knowledge_disk.index, cache_size: 67108864\n",
+ "medoid: 0B\n",
+ "max_node_len: 3100B\n",
+ "nnodes_per_sector: 1B\n",
+ "# sectors: 6\n",
+ "Sector #0written\n",
+ "Finished writing 28672B\n",
+ "Writing bin: knowledge_disk.index\n",
+ "bin: #pts = 9, #dims = 1, size = 80B\n",
+ "Finished writing bin.\n",
+ "Output disk index file written to knowledge_disk.index\n",
+ "Finished writing 28672B\n",
+ "Time for generating disk layout: 0.043488 seconds\n",
+ "Opened: knowledge_prepped_base.bin, size: 18464, cache_size: 18464\n",
+ "Loading base knowledge_prepped_base.bin. #points: 6. #dim: 769.\n",
+ "Wrote 1 points to sample file: knowledge_sample_data.bin\n",
+ "Indexing time: 0.0684344\n",
+ "INFO: Leann metadata saved to knowledge.leann.meta.json\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "\n",
+ "Opened file : knowledge_disk.index\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Since data is floating point, we assume that it has been appropriately pre-processed (normalization for cosine, and convert-to-l2 by adding extra dimension for MIPS). So we shall invoke an l2 distance function.\n",
+ "L2: Using AVX2 distance computation DistanceL2Float\n",
+ "L2: Using AVX2 distance computation DistanceL2Float\n",
+ "Before index load\n",
+ "✅ DiskANN index loaded successfully.\n",
+ "INFO: LeannSearcher initialized with 'diskann' backend using index 'knowledge.leann'.\n",
+ "Reading bin file knowledge_pq_compressed.bin ...\n",
+ "Opening bin file knowledge_pq_compressed.bin... \n",
+ "Metadata: #pts = 6, #dims = 512...\n",
+ "done.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 4, #dims = 1...\n",
+ "done.\n",
+ "Offsets: 4096 791560 794644 796704\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 256, #dims = 769...\n",
+ "done.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 769, #dims = 1...\n",
+ "done.\n",
+ "Reading bin file knowledge_pq_pivots.bin ...\n",
+ "Opening bin file knowledge_pq_pivots.bin... \n",
+ "Metadata: #pts = 513, #dims = 1...\n",
+ "done.\n",
+ "Loaded PQ Pivots: #ctrs: 256, #dims: 769, #chunks: 512\n",
+ "Loaded PQ centroids and in-memory compressed vectors. #points: 6 #dim: 769 #aligned_dim: 776 #chunks: 512\n",
+ "Loading index metadata from knowledge_disk.index\n",
+ "Disk-Index File Meta-data: # nodes per sector: 1, max node len (bytes): 3100, max node degree: 5\n",
+ "Disk-Index Meta: nodes per sector: 1, max node len: 3100, max node degree: 5\n",
+ "Setting up thread-specific contexts for nthreads: 8\n",
+ "allocating ctx: 0x78348f4de000 to thread-id:132170359560000\n",
+ "allocating ctx: 0x78348f4cd000 to thread-id:132158431693760\n",
+ "allocating ctx: 0x78348f4bc000 to thread-id:132158442179392\n",
+ "allocating ctx: 0x78348f4ab000 to thread-id:132158421208128\n",
+ "allocating ctx: 0x78348f49a000 to thread-id:132158452665024\n",
+ "allocating ctx: 0x78348f489000 to thread-id:132158389751232\n",
+ "allocating ctx: 0x78348f478000 to thread-id:132158410722496\n",
+ "allocating ctx: 0x78348f467000 to thread-id:132158400236864\n",
+ "Loading centroid data from medoids vector data of 1 medoid(s)\n",
+ "Reading bin file knowledge_disk.index_max_base_norm.bin ...\n",
+ "Opening bin file knowledge_disk.index_max_base_norm.bin... \n",
+ "Metadata: #pts = 1, #dims = 1...\n",
+ "done.\n",
+ "Setting re-scaling factor of base vectors to 1\n",
+ "load_from_separate_paths done.\n",
+ "Reading (with alignment) bin file knowledge_sample_data.bin ...Metadata: #pts = 1, #dims = 769, aligned_dim = 776... allocating aligned memory of 3104 bytes... done. Copying data to mem_aligned buffer... done.\n",
+ "reserve ratio: 1\n",
+ "Graph traversal completed, hops: 3\n",
+ "Loading the cache list into memory....done.\n",
+ "After index load\n",
+ "Clearing scratch\n",
+ "INFO: Computing embeddings for 1 chunks using 'sentence-transformers/all-mpnet-base-v2'...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Batches: 100%|██████████| 1/1 [00:00<00:00, 92.66it/s]"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Score: -0.481 - C++ is a powerful programming language\n",
+ "Score: -1.049 - Java is a powerful programming language\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "reserve ratio: 1\n",
+ "Graph traversal completed, hops: 3\n"
+ ]
+ }
+ ],
+ "source": [
+ "from leann.api import LeannBuilder, LeannSearcher\n",
+ "import leann_backend_diskann\n",
+ "# 1. Build index (no embeddings stored!)\n",
+ "builder = LeannBuilder(backend_name=\"diskann\")\n",
+ "builder.add_text(\"Python is a powerful programming language\")\n",
+ "builder.add_text(\"Machine learning transforms industries\") \n",
+ "builder.add_text(\"Neural networks process complex data\")\n",
+ "builder.add_text(\"Java is a powerful programming language\")\n",
+ "builder.add_text(\"C++ is a powerful programming language\")\n",
+ "builder.add_text(\"C# is a powerful programming language\")\n",
+ "builder.build_index(\"knowledge.leann\")\n",
+ "\n",
+ "# 2. Search with real-time embeddings\n",
+ "searcher = LeannSearcher(\"knowledge.leann\")\n",
+ "results = searcher.search(\"C++ programming languages\", top_k=2)\n",
+ "\n",
+ "for result in results:\n",
+ " print(f\"Score: {result['score']:.3f} - {result['text']}\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": ".venv",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.11"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/data/2506.08276v1.pdf b/examples/data/2506.08276v1.pdf
new file mode 100644
index 0000000..2756eef
--- /dev/null
+++ b/examples/data/2506.08276v1.pdf
@@ -0,0 +1,7905 @@
+%PDF-1.5
+%����
+1 0 obj
+<< /Lang (en) /Metadata 3 0 R /Names 4 0 R /OpenAction 5 0 R /Outlines 6 0 R /PageMode /UseOutlines /Pages 7 0 R /Type /Catalog /ViewerPreferences << /DisplayDocTitle true >> >>
+endobj
+2 0 obj
+<< /Author (Yichuan Wang; Shu Liu; Zhifei Li; Yongji Wu; Ziming Mao; Yilong Zhao; Xiao Yan; Zhiying Xu; Yang Zhou; Ion Stoica; Sewon Min; Matei Zaharia; Joseph E. Gonzalez) /CreationDate (D:20250611152430+00'00') /Creator (arXiv GenPDF \(tex2pdf:\)) /DOI (https://doi.org/10.48550/arXiv.2506.08276) /Keywords () /License (http://arxiv.org/licenses/nonexclusive-distrib/1.0/) /ModDate (D:20250611152430+00'00') /PTEX.Fullbanner (This is pdfTeX, Version 3.141592653-2.6-1.40.25 \(TeX Live 2023\) kpathsea version 6.3.5) /Producer (pikepdf 8.15.1) /Title (LEANN: A Low-Storage Vector Index) /Trapped /False /arXivID (https://arxiv.org/abs/2506.08276v1) >>
+endobj
+3 0 obj
+<< /Subtype /XML /Type /Metadata /Length 13436 >>
+stream
+<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
+<x:xmpmeta xmlns:x="adobe:ns:meta/">
+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
+ <rdf:Description xmlns:pdf="http://ns.adobe.com/pdf/1.3/" xmlns:xmpRights="http://ns.adobe.com/xap/1.0/rights/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/" xmlns:pdfuaid="http://www.aiim.org/pdfua/ns/id/" xmlns:pdfx="http://ns.adobe.com/pdfx/1.3/" xmlns:prism="http://prismstandard.org/namespaces/basic/3.0/" xmlns:jav="http://www.niso.org/schemas/jav/1.0/" xmlns:xmpTPg="http://ns.adobe.com/xap/1.0/t/pg/" xmlns:stFnt="http://ns.adobe.com/xap/1.0/sType/Font#" xmlns:Iptc4xmpCore="http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#" xmlns:pdfaType="http://www.aiim.org/pdfa/ns/type#" xmlns:pdfaField="http://www.aiim.org/pdfa/ns/field#" rdf:about="">
+ <pdfaExtension:schemas>
+ <rdf:Bag>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>
+ <pdfaSchema:prefix>pdf</pdfaSchema:prefix>
+ <pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>
+ <pdfaSchema:property>
+ <rdf:Seq>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>Trapped</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>Indication if the document has been modified to include trapping information</pdfaProperty:description>
+ </rdf:li>
+ </rdf:Seq>
+ </pdfaSchema:property>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>
+ <pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>
+ <pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>
+ <pdfaSchema:property>
+ <rdf:Seq>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>DocumentID</pdfaProperty:name>
+ <pdfaProperty:valueType>URI</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>UUID based identifier for all versions and renditions of a document</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>InstanceID</pdfaProperty:name>
+ <pdfaProperty:valueType>URI</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>VersionID</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>Document version identifier</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>RenditionClass</pdfaProperty:name>
+ <pdfaProperty:valueType>RenditionClass</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>The manner in which a document is rendered</pdfaProperty:description>
+ </rdf:li>
+ </rdf:Seq>
+ </pdfaSchema:property>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaSchema:schema>PRISM Basic Metadata</pdfaSchema:schema>
+ <pdfaSchema:prefix>prism</pdfaSchema:prefix>
+ <pdfaSchema:namespaceURI>http://prismstandard.org/namespaces/basic/3.0/</pdfaSchema:namespaceURI>
+ <pdfaSchema:property>
+ <rdf:Seq>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>complianceProfile</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>PRISM specification compliance profile to which this document adheres</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>publicationName</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Publication name</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>aggregationType</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Publication type</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>bookEdition</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Edition of the book in which the document was published</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>volume</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Publication volume number</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>number</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Publication issue number within a volume</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>pageRange</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Page range for the document within the print version of its publication</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>issn</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>ISSN for the printed publication in which the document was published</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>eIssn</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>ISSN for the electronic publication in which the document was published</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>isbn</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>ISBN for the publication in which the document was published</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>doi</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Digital Object Identifier for the document</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>url</pdfaProperty:name>
+ <pdfaProperty:valueType>URL</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>URL at which the document can be found</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>byteCount</pdfaProperty:name>
+ <pdfaProperty:valueType>Integer</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>Approximate file size in octets</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>pageCount</pdfaProperty:name>
+ <pdfaProperty:valueType>Integer</pdfaProperty:valueType>
+ <pdfaProperty:category>internal</pdfaProperty:category>
+ <pdfaProperty:description>Number of pages in the print version of the document</pdfaProperty:description>
+ </rdf:li>
+ <rdf:li rdf:parseType="Resource">
+ <pdfaProperty:name>subtitle</pdfaProperty:name>
+ <pdfaProperty:valueType>Text</pdfaProperty:valueType>
+ <pdfaProperty:category>external</pdfaProperty:category>
+ <pdfaProperty:description>Document's subtitle</pdfaProperty:description>
+ </rdf:li>
+ </rdf:Seq>
+ </pdfaSchema:property>
+ </rdf:li>
+ </rdf:Bag>
+ </pdfaExtension:schemas>
+ <pdf:Producer>pikepdf 8.15.1</pdf:Producer>
+ <pdf:Keywords/>
+ <pdf:PDFVersion>1.5</pdf:PDFVersion>
+ <dc:format>application/pdf</dc:format>
+ <dc:title>
+ <rdf:Alt><rdf:li xml:lang="x-default">LEANN: A Low-Storage Vector Index</rdf:li></rdf:Alt></dc:title>
+ <dc:publisher>arXiv</dc:publisher>
+ <dc:date>
+ <rdf:Seq>
+ <rdf:li>2025-06-11T15:24:30Z</rdf:li>
+ </rdf:Seq>
+ </dc:date>
+ <dc:type>
+ <rdf:Bag>
+ <rdf:li>Text</rdf:li>
+ </rdf:Bag>
+ </dc:type>
+ <dc:creator>
+ <rdf:Seq><rdf:li>Yichuan Wang</rdf:li><rdf:li>Shu Liu</rdf:li><rdf:li>Zhifei Li</rdf:li><rdf:li>Yongji Wu</rdf:li><rdf:li>Ziming Mao</rdf:li><rdf:li>Yilong Zhao</rdf:li><rdf:li>Xiao Yan</rdf:li><rdf:li>Zhiying Xu</rdf:li><rdf:li>Yang Zhou</rdf:li><rdf:li>Ion Stoica</rdf:li><rdf:li>Sewon Min</rdf:li><rdf:li>Matei Zaharia</rdf:li><rdf:li>Joseph E. Gonzalez</rdf:li></rdf:Seq></dc:creator>
+ <dc:source>main.tex</dc:source>
+ <dc:language>
+ <rdf:Bag>
+ <rdf:li>en</rdf:li>
+ </rdf:Bag>
+ </dc:language>
+ <dc:identifier>https://arxiv.org/abs/2506.08276v1</dc:identifier>
+ <xmp:CreateDate>2025-06-11T15:24:30Z</xmp:CreateDate>
+ <xmp:ModifyDate>2025-06-11T15:24:30Z</xmp:ModifyDate>
+ <xmp:MetadataDate>2025-06-11T15:24:36.250178+00:00</xmp:MetadataDate>
+ <xmp:CreatorTool>arXiv GenPDF (tex2pdf:)</xmp:CreatorTool>
+ <xmpMM:DocumentID>uuid:75fd75f2-b182-4bbb-ac9b-620a88d7aeae</xmpMM:DocumentID>
+ <xmpMM:InstanceID>uuid:8d18d13e-fdc9-4541-91dc-efd13959bb18</xmpMM:InstanceID>
+ <xmpMM:VersionID>1</xmpMM:VersionID>
+ <xmpMM:RenditionClass>default</xmpMM:RenditionClass>
+ <prism:complianceProfile>three</prism:complianceProfile>
+ <prism:publicationName xml:lang="en">Proceedings of Make sure to enter the correct conference title from your rights confirmation email (Conference acronym 'XX)</prism:publicationName>
+ <prism:aggregationType>book</prism:aggregationType>
+ <prism:volume>1</prism:volume>
+ <prism:number>1</prism:number>
+ <prism:doi>XXXXXXX.XXXXXXX</prism:doi>
+ <prism:pageCount>15</prism:pageCount>
+ <xmpTPg:NPages>15</xmpTPg:NPages>
+ </rdf:Description>
+ <rdf:Description rdf:about=""><dc:rights xmlns:dc="http://purl.org/dc/elements/1.1/"><rdf:Alt><rdf:li xml:lang="x-default">http://arxiv.org/licenses/nonexclusive-distrib/1.0/</rdf:li></rdf:Alt></dc:rights></rdf:Description><rdf:Description rdf:about=""><dc:subject xmlns:dc="http://purl.org/dc/elements/1.1/"><rdf:Seq><rdf:li>cs.DB</rdf:li><rdf:li>cs.LG</rdf:li></rdf:Seq></dc:subject></rdf:Description></rdf:RDF>
+</x:xmpmeta>
+
+<?xpacket end="w"?>
+
+endstream
+endobj
+4 0 obj
+<< /Dests 8 0 R >>
+endobj
+5 0 obj
+<< /D [ 9 0 R /Fit ] /S /GoTo >>
+endobj
+6 0 obj
+<< /Count 11 /First 10 0 R /Last 11 0 R /Type /Outlines >>
+endobj
+7 0 obj
+<< /Count 15 /Kids [ 12 0 R 13 0 R 14 0 R ] /Type /Pages >>
+endobj
+8 0 obj
+<< /Kids [ 15 0 R 16 0 R 17 0 R 18 0 R 19 0 R ] /Limits [ ([email protected]) (table.caption.9) ] >>
+endobj
+9 0 obj
+<< /Annots [ 20 0 R 21 0 R 22 0 R 23 0 R 24 0 R 25 0 R 26 0 R 27 0 R 28 0 R 29 0 R 30 0 R 31 0 R 32 0 R 33 0 R 34 0 R 35 0 R 36 0 R ] /Contents [ 37 0 R 38 0 R ] /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources 39 0 R /Type /Page >>
+endobj
+10 0 obj
+<< /A 40 0 R /Next 41 0 R /Parent 6 0 R /Title 42 0 R >>
+endobj
+11 0 obj
+<< /A 43 0 R /Parent 6 0 R /Prev 44 0 R /Title 45 0 R >>
+endobj
+12 0 obj
+<< /Count 6 /Kids [ 9 0 R 46 0 R 47 0 R 48 0 R 49 0 R 50 0 R ] /Parent 7 0 R /Type /Pages >>
+endobj
+13 0 obj
+<< /Count 6 /Kids [ 51 0 R 52 0 R 53 0 R 54 0 R 55 0 R 56 0 R ] /Parent 7 0 R /Type /Pages >>
+endobj
+14 0 obj
+<< /Count 3 /Kids [ 57 0 R 58 0 R 59 0 R ] /Parent 7 0 R /Type /Pages >>
+endobj
+15 0 obj
+<< /Kids [ 60 0 R 61 0 R 62 0 R 63 0 R 64 0 R 65 0 R ] /Limits [ ([email protected]) (cite.asai2023self) ] >>
+endobj
+16 0 obj
+<< /Kids [ 66 0 R 67 0 R 68 0 R 69 0 R 70 0 R 71 0 R ] /Limits [ (cite.aumuller2020ann) (cite.munyampirwa2024down) ] >>
+endobj
+17 0 obj
+<< /Kids [ 72 0 R 73 0 R 74 0 R 75 0 R 76 0 R 77 0 R ] /Limits [ (cite.nsg) (equation.5.1) ] >>
+endobj
+18 0 obj
+<< /Kids [ 78 0 R 79 0 R 80 0 R 81 0 R 82 0 R 83 0 R ] /Limits [ (figure.caption.10) (section.5) ] >>
+endobj
+19 0 obj
+<< /Kids [ 84 0 R 85 0 R 86 0 R ] /Limits [ (section.6) (table.caption.9) ] >>
+endobj
+20 0 obj
+<< /A << /D (Hfootnote.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 53.004 360.913 55.494 366.522 ] /Subtype /Link /Type /Annot >>
+endobj
+21 0 obj
+<< /A << /D (cite.izacard2021unsupervised) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 188.421 321.946 199.679 330.2 ] /Subtype /Link /Type /Annot >>
+endobj
+22 0 obj
+<< /A << /D (cite.lin2022pretrained) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 202.564 321.946 213.822 330.2 ] /Subtype /Link /Type /Annot >>
+endobj
+23 0 obj
+<< /A << /D (cite.karpukhin2020dense) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 150.818 298.036 162.075 306.29 ] /Subtype /Link /Type /Annot >>
+endobj
+24 0 obj
+<< /A << /D (cite.zamani2023conversational) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 165.19 298.036 176.448 306.29 ] /Subtype /Link /Type /Annot >>
+endobj
+25 0 obj
+<< /A << /D (cite.craswell2020overview) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 220.739 274.215 231.997 282.379 ] /Subtype /Link /Type /Annot >>
+endobj
+26 0 obj
+<< /A << /D (cite.zhang2018visual) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 234.667 274.125 245.925 282.379 ] /Subtype /Link /Type /Annot >>
+endobj
+27 0 obj
+<< /A << /D (cite.he2019streaming) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 201.078 190.529 212.336 198.693 ] /Subtype /Link /Type /Annot >>
+endobj
+28 0 obj
+<< /A << /D (cite.work-in-progress) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 215.026 190.439 226.284 198.693 ] /Subtype /Link /Type /Annot >>
+endobj
+29 0 obj
+<< /A << /D (cite.wang2024mememo) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 228.973 190.439 240.231 198.693 ] /Subtype /Link /Type /Annot >>
+endobj
+30 0 obj
+<< /A << /D (cite.yin2024devicers) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 242.921 190.439 254.179 198.693 ] /Subtype /Link /Type /Annot >>
+endobj
+31 0 obj
+<< /A << /D (cite.shao2024scaling) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 75.586 154.574 86.844 162.828 ] /Subtype /Link /Type /Annot >>
+endobj
+32 0 obj
+<< /A << /D (cite.wang2021comprehensive_survey) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 340.008 543.703 351.265 551.957 ] /Subtype /Link /Type /Annot >>
+endobj
+33 0 obj
+<< /A << /D (cite.pq) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 394.996 507.837 406.254 516.091 ] /Subtype /Link /Type /Annot >>
+endobj
+34 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 555.225 436.106 566.483 444.36 ] /Subtype /Link /Type /Annot >>
+endobj
+35 0 obj
+<< /A << /D (cite.shao2024scaling) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 434.339 113.317 445.596 121.571 ] /Subtype /Link /Type /Annot >>
+endobj
+36 0 obj
+<< /A << /S /URI /URI (https://arxiv.org/abs/2506.08276v1) >> /BS << /W 0 >> /NM (fitz-L0) /Rect [ 12 227.68 32 564.32 ] /Subtype /Link >>
+endobj
+37 0 obj
+<< /Filter /FlateDecode /Length 139 >>
+stream
+x�E�M
+1 ��9E.�1M�tą �;���E�*.���;*���{�L@��y�����9v֣�Ta�����x���L��������� ���#koC4�¢Bb\Z�mE��{&&=X�\B��鑁)�V�L��>m`�` o6�&�
+endstream
+endobj
+38 0 obj
+<< /Filter /FlateDecode /Length 5551 >>
+stream
+xڥ[[��ȱ~�_�G�O��ԅ�g��^l��2�g�ݙp�-��0�_2+��@h<=����K�����E�j��V_��f�/�^��+��+ kU��{XI�D��(*V�������^������lT�_��O�M�~�y�5�|_P��ݤ�������zW@�߼��ï�R�\I)�g~Xmb����JD�RZ�����5 ���F����f���}0:�"�ve�64����A/#���u�(�>Y�G�H&��\$5�ի͸�-���3C�~ij�E�&���'���?ʇ��+,.���� ��&������ Wf�/�;ND��Oa��~ۏ��*Cʪqp������Xe�ϑ���~:\]"�>��/aZf���ō̈́V��O]�AJ���p� �-���}_��Xd� �}Ezi��H�}�N�gJ&}މf�|�p+wbF�4Ϣ�<��o�W��m�H�E�ȼF-��&]���+��F"��g/�]�yu�S~����$p�3�I���E�д��@��]�n������\���^m��"�5pO��������%-�Eq~,��ۧ��"��*�>q�/�揋��
+i�pF��3��z��C3�������2^�+�E������Z� �g���w���G� �k��a�`�ܷ�9�v��d"���H��I8(+ [��U0�U�(X�v��6�yKOH�^�E~����=�pU���8>�} P벦k~:�veS󘶇YP�fER�?�C_ �?�i$��TUQ��<�*�wA��\���ˏ���C���]�E]���o�8���m�_í ��i&�a���h�Y�cAe�!��uw(�@�4�Zsz�#��#kM��rT�� ���鄓7�n�����)�/�G�Q�%������W7��;$
+��I�n���6u~��Ĝ޵!��;zylܗ�G��8_M}�t�/��7 k�b\1��4�*�ႎ��*/��W�T��x#�5s�ms:iO�NcW�~��L4��mK����8�}��(4��D�������c'���~|ĝ�k��5���"o��#Ϲ� z����t풔)RŜ9�{<^&qC��Z���w��r�n�ϫ, �}K�%{$y� ��n���H��s�~ +�Ke �#��N� ,����oI�8�N�ᚸ���[�rx���$�!�Q双��(|��+NG����d"2�e
+N&��p��?�8GA-tvw��������*܍�Y�m�����M�ס�:Y
+��-�3ZމG��1��Dz{�:�ps���h6�#i�lϥ�~:�a,jb��˴� N����t�|�G���@�j�&NIF2>���6����/zK�U�)�D�lK�
+�O�v�F����a���'��;��FM<+ڎ>�.@��-$ڙ���*1���1�5<:I�����:u�|�{)4&�D�1��:�źm�Z��-X*0�e=�E�3S�R�"tq\�[��{�t� �i��3|��� ��;�s~:L��\���lak8�<s�T�Z���7��RfFhhO}Ƕ���M�?�"��u�t�?�-���4m�������Bc<1�p�6B)���������
+4��uI����{^��o�Z�<��.6��!�<=.>ᙣ�P�&Z�΂��e�%�Od0^�N����\{x���B�k���\�K6�v��S�ed$�LG� GT�ɷb-�T���q�����s�t ޶��3?x��``I��zн�)��.h�=%���r�<E{K ^��Su���Wt�5����Q�>?']=�V���N�0Q��1Ir�c��� �s��ǝ�נ�J�'�[�σ�ʺ�����
+�瀞�V�q5}��u��O���{S0y�A���$ɖ�gć^�� �l��Sc#�,Bh� �����5�/<9����t����o`��l��L�P�ĉ �v���}ޚ*�o��)��%A%ʚ�{K��Q��5Cp
+]
+ S_X~��5ab���.A��m���r}ǖ�O���� �㟮�YFL���k��T����NJh2RbV|���@…����� nx&K���6[xH�i�gn��h��t�D^_3�����[��|�W�2;���^��K�<��3>���Y����� �*T��a�y���w�队V���KMKvQ�g)͟��'-8��%�O�|���t�Ľ{�(%�7�G��v���9��=�:֚���4Fd*�x+�k�رF�<��O�5pZ���]Q��6����]Q�t�\�0'�CF\=�����:��7���$ ��s�5`'�.Hy|� �q-��L�7t��������Q::� ��D3~7})7 ��]���?v����l-�y)3���_D� ���ݹ0&�������,�#6���xe�X���_��c��2fMv|�P$h*�PRڔ������X>�#�Ksj��,^�M�XkB��hϗ29#1_x�Y�hp������` �R��mK�]�ǚǞ��|˞|@hU<����ŇY=�����8��a� �� g���'����:Z�Wí��g��oǨf2 �$q�L_
+��!:C~�x~�+�2Z"vEwl�:��;��NJ����%#m",����%f�q� 7�rCmN�@C2���<@���p�7Q��Ė)���N������sTQ �ҡ7�a�-����w�����69�"0=�,N.,�_7�Ej�iwga��SS�P�YK���Zx������� h�㚩グF��SX��PqQ�� �|N2r�J�
+�;���e�����\�(��M�w�Xp8�G�98���!,I
+
+Z�d�� B{�#f�#7Ǡ��@mf *z g��נ����|4�d�E j��Q��+?.�cp޵ �E��-��c�KaX����p�o%.�������B�D�H�A��Ɔ��Y��:�F-dDYmy�5�C�ݍE ����a nsx�^ݽ��E`�28\V��Ջ��F�4�h8|�]�
+ IRW�q\�~�W� B�$"C6P�.��s� L-�,�
+�swRo�3|d0꬟��u������ȓ�T���)}��3�|鲠����2�Je�� �o@F�}�2N`�����9�Q!��ݐ��� �>#�W�͙Sz�
+���o|���*���>���g�7���� ����F��}��J��*�L~���xp��y�1�sU�5�*@[���/�(M@
+�Q��1�1GXt05���=ޒ�_<򐆮� %w U�Ih�`HL|�da��! 73Sf���|03�3�!ߘ��tY ��e�� ۼ�0��>߂aL�BJ�{W��V�'`�֪w0�̠&�3��9�TO�'�E��X��Qg
+l����[��৚?�D���B�c0}�I�0k��>pw洤��I����jK�R�}����e/@��� �1����L\��m
+��y���� nT�{��!;8/k�;�̔Y?P��(-nc3$��]kH_��wM;F�CѶ�]ű����@~��jv�8�:��zZ?Y� ��k�!�MOU��^ܓ��f�GƸh���}���Pe2��/�c��q$�b2�-'�'�]�:�Y�9��<�|�b����T]r=2Į�.Ƴ�^;ܱV"����:Y�˽_�ٲ��� ⻇�L7n�-)E�$�D���x�з.h³�,�@���H_��2����:�����е�w�5U&lu�1Cjc]%3���ԧIYi ���WQJ�XH�/=:X<V��_��G|̙>W��d����� �H3��9�xKkos&lf����V� !P��=v�p����v��:�L$Ǔ�hJ�I�E��ݟ��Eu����׺��^X����-��0g0'/��]*�t\�:���Be���RDA��J6 �F�, �����d, �������|3�#�Gr}��K�^2`vs~��Ų�t
+�����'��T �}�v���O���yF}��'`' x=2���<���Pգ*н��S=�t�B!�*�wNz��)0qM��%9W�E_;*]�%l΋q t��MMrE�#��}��(�">���i� x�7���������?����g* ��J�)�:����0�U�a��C���R�b��&��Ňy�5'.��+p�6̓+��ό5/�+`p
+��^�����iY@l)6jor�,����{a�9� w��#�T�2f�(a��M$��լj�u��A.:����h� [���4!f {Tn&h>&4?/����4�����>���A��$�KŇC�,�P�ϣ����P2�-ט��Ka�O�y%� 9$p-�֫�� 0{q� Z����~��k��$x��n���a�����d�S|�vA�5Ʊ�Β���Ao2&����Z.�ݽ��̑���&��Ny�@�9�rr
+1ud�7�x �=�ʡ�4eg�� �c�D�o��X1�O]��B'� ѕÉp8�фK�q�t��[js�A%k�'������nj�}��{�eB���O�{�v�
+��pE�LX�+w�D���U���!�эi�����A��s��I����T� � e4�Ęh����o���S� ���*���������.�H��;����T
+�����q ��͉��O�<� (��ǣ?�[_%�R7*�@�d3,����X�n���1ڿ&�*�"�).�^'e�����Y6(�4�[6�b�t V��m�-hl���|��7ؔ��I���cA�r摄)��)Z���8��n�KA�-Ϻs9�mqQ8:�e3��`�~�#�hG,&ђ��:g6Zv]�&��*����ؕ`ǼO[�׌�ŸXda�ǧA�A�G� +�?�o�>�c�,[׽?�g��̆�z��E^{�Ѐ��K�̀KĝF���"̢���AAc~l�0w�[��99u�=�yUn:.�\k����}���q�,Y���l+�-���]�wY�b�W4˚�re���AS
+v��oM��1�ʟh����МZ�9GY ��I����l`?~��t��nG��ۅk�vt(�ȇ�\-��׋m�nG�С�+���Iƙ�����&kz��ڦ���������y�R7
+����k��7�Ԃ{�y �� r�%2!P%�▚T��u�F�~?Qf�8�N���Y��䂺�����,��zȡ 6)6C} [� F��f�G��Ƙ��*��*�|$������$�V���ۈ�FƧ��(�G�dPSb � 79�Wkx��ȇ�?,�E{)r<U2��:��ë-=Z�W5�(�b,��X�X`�� ]8�C9�G8薺8�zE�K�
+�c0�r#�^��E 1�ytׇN�����N�e���i�k�E*+��Ӏc��u���W���θF��ۂ`�n L #
+'U>B='Ga|l8��G�ބ�W���~|f�ͼD!,W�+^�EJ_�w%�������D��z���U�S*��HCt�=:<>�ۤ�#�&�ϒӟH�O����z���#���,�'G�'�Ǒ=��qĹ����� ����C#��YrL�[a v6杕�l�����8
+endstream
+endobj
+39 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R /F246 95 0 R /Times-Roman 96 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+40 0 obj
+<< /D (section*.1) /S /GoTo >>
+endobj
+41 0 obj
+<< /A 98 0 R /Next 99 0 R /Parent 6 0 R /Prev 10 0 R /Title 100 0 R >>
+endobj
+42 0 obj
+<feff00410062007300740072006100630074>
+endobj
+43 0 obj
+<< /D (section*.17) /S /GoTo >>
+endobj
+44 0 obj
+<< /A 101 0 R /Next 11 0 R /Parent 6 0 R /Prev 102 0 R /Title 103 0 R >>
+endobj
+45 0 obj
+<feff005200650066006500720065006e006300650073>
+endobj
+46 0 obj
+<< /Annots [ 104 0 R 105 0 R 106 0 R 107 0 R 108 0 R 109 0 R 110 0 R 111 0 R 112 0 R 113 0 R 114 0 R 115 0 R 116 0 R 117 0 R 118 0 R 119 0 R 120 0 R 121 0 R 122 0 R 123 0 R ] /Contents 124 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources 125 0 R /Type /Page >>
+endobj
+47 0 obj
+<< /Annots [ 126 0 R 127 0 R 128 0 R 129 0 R 130 0 R 131 0 R 132 0 R 133 0 R 134 0 R 135 0 R 136 0 R 137 0 R 138 0 R 139 0 R 140 0 R 141 0 R 142 0 R 143 0 R 144 0 R 145 0 R 146 0 R 147 0 R 148 0 R 149 0 R 150 0 R 151 0 R ] /Contents 152 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources 153 0 R /Type /Page >>
+endobj
+48 0 obj
+<< /Annots [ 154 0 R 155 0 R 156 0 R 157 0 R 158 0 R 159 0 R 160 0 R 161 0 R 162 0 R 163 0 R 164 0 R 165 0 R 166 0 R 167 0 R 168 0 R 169 0 R ] /Contents 170 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources 171 0 R /Type /Page >>
+endobj
+49 0 obj
+<< /Annots [ 172 0 R 173 0 R 174 0 R 175 0 R 176 0 R 177 0 R 178 0 R ] /Contents 179 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources 180 0 R /Type /Page >>
+endobj
+50 0 obj
+<< /Annots [ 181 0 R 182 0 R 183 0 R 184 0 R 185 0 R 186 0 R 187 0 R 188 0 R 189 0 R 190 0 R ] /Contents 191 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources 192 0 R /Type /Page >>
+endobj
+51 0 obj
+<< /Annots [ 193 0 R 194 0 R 195 0 R 196 0 R 197 0 R 198 0 R 199 0 R 200 0 R 201 0 R 202 0 R 203 0 R 204 0 R 205 0 R 206 0 R 207 0 R 208 0 R 209 0 R 210 0 R 211 0 R 212 0 R 213 0 R 214 0 R 215 0 R 216 0 R 217 0 R 218 0 R 219 0 R 220 0 R 221 0 R 222 0 R ] /Contents 223 0 R /MediaBox [ 0 0 612 792 ] /Parent 13 0 R /Resources 224 0 R /Type /Page >>
+endobj
+52 0 obj
+<< /Annots [ 225 0 R 226 0 R 227 0 R 228 0 R 229 0 R 230 0 R 231 0 R 232 0 R 233 0 R 234 0 R 235 0 R 236 0 R 237 0 R ] /Contents 238 0 R /MediaBox [ 0 0 612 792 ] /Parent 13 0 R /Resources 239 0 R /Type /Page >>
+endobj
+53 0 obj
+<< /Annots [ 240 0 R 241 0 R 242 0 R 243 0 R 244 0 R 245 0 R 246 0 R 247 0 R 248 0 R 249 0 R 250 0 R 251 0 R 252 0 R 253 0 R 254 0 R ] /Contents 255 0 R /MediaBox [ 0 0 612 792 ] /Parent 13 0 R /Resources 256 0 R /Type /Page >>
+endobj
+54 0 obj
+<< /Annots [ 257 0 R 258 0 R 259 0 R 260 0 R 261 0 R 262 0 R 263 0 R 264 0 R 265 0 R 266 0 R 267 0 R 268 0 R 269 0 R 270 0 R 271 0 R ] /Contents 272 0 R /MediaBox [ 0 0 612 792 ] /Parent 13 0 R /Resources 273 0 R /Type /Page >>
+endobj
+55 0 obj
+<< /Annots [ 274 0 R 275 0 R 276 0 R 277 0 R 278 0 R 279 0 R 280 0 R 281 0 R 282 0 R 283 0 R 284 0 R 285 0 R 286 0 R 287 0 R 288 0 R 289 0 R 290 0 R 291 0 R ] /Contents 292 0 R /MediaBox [ 0 0 612 792 ] /Parent 13 0 R /Resources 293 0 R /Type /Page >>
+endobj
+56 0 obj
+<< /Annots [ 294 0 R 295 0 R 296 0 R 297 0 R 298 0 R 299 0 R 300 0 R 301 0 R 302 0 R 303 0 R 304 0 R 305 0 R 306 0 R 307 0 R 308 0 R 309 0 R ] /Contents 310 0 R /MediaBox [ 0 0 612 792 ] /Parent 13 0 R /Resources 311 0 R /Type /Page >>
+endobj
+57 0 obj
+<< /Annots [ 312 0 R 313 0 R 314 0 R 315 0 R 316 0 R 317 0 R 318 0 R 319 0 R 320 0 R 321 0 R 322 0 R 323 0 R 324 0 R 325 0 R 326 0 R 327 0 R 328 0 R 329 0 R 330 0 R 331 0 R 332 0 R 333 0 R 334 0 R 335 0 R 336 0 R 337 0 R 338 0 R 339 0 R ] /Contents 340 0 R /MediaBox [ 0 0 612 792 ] /Parent 14 0 R /Resources 341 0 R /Type /Page >>
+endobj
+58 0 obj
+<< /Annots [ 342 0 R 343 0 R 344 0 R 345 0 R 346 0 R 347 0 R 348 0 R 349 0 R 350 0 R 351 0 R 352 0 R 353 0 R 354 0 R 355 0 R 356 0 R 357 0 R 358 0 R 359 0 R 360 0 R 361 0 R 362 0 R 363 0 R 364 0 R 365 0 R 366 0 R 367 0 R 368 0 R 369 0 R 370 0 R 371 0 R ] /Contents 372 0 R /MediaBox [ 0 0 612 792 ] /Parent 14 0 R /Resources 373 0 R /Type /Page >>
+endobj
+59 0 obj
+<< /Annots [ 374 0 R 375 0 R 376 0 R 377 0 R ] /Contents 378 0 R /MediaBox [ 0 0 612 792 ] /Parent 14 0 R /Resources 379 0 R /Type /Page >>
+endobj
+60 0 obj
+<< /Limits [ ([email protected]) ([email protected]) ] /Names [ ([email protected]) 380 0 R ([email protected]) 381 0 R ([email protected]) 382 0 R ([email protected]) 383 0 R ([email protected]) 384 0 R ([email protected]) 385 0 R ] >>
+endobj
+61 0 obj
+<< /Limits [ ([email protected]) ([email protected]) ] /Names [ ([email protected]) 386 0 R ([email protected]) 387 0 R ([email protected]) 388 0 R ([email protected]) 389 0 R ([email protected]) 390 0 R ([email protected]) 391 0 R ] >>
+endobj
+62 0 obj
+<< /Limits [ ([email protected]) ([email protected]) ] /Names [ ([email protected]) 392 0 R ([email protected]) 393 0 R ([email protected]) 394 0 R ([email protected]) 395 0 R ([email protected]) 396 0 R ([email protected]) 397 0 R ] >>
+endobj
+63 0 obj
+<< /Limits [ ([email protected]) (Hfootnote.3) ] /Names [ ([email protected]) 398 0 R ([email protected]) 399 0 R (Doc-Start) 400 0 R (Hfootnote.1) 401 0 R (Hfootnote.2) 402 0 R (Hfootnote.3) 403 0 R ] >>
+endobj
+64 0 obj
+<< /Limits [ (Item.1) (algorithm.3) ] /Names [ (Item.1) 404 0 R (Item.2) 405 0 R (Item.3) 406 0 R (algorithm.1) 407 0 R (algorithm.2) 408 0 R (algorithm.3) 409 0 R ] >>
+endobj
+65 0 obj
+<< /Limits [ (cite.LM-DiskANN) (cite.asai2023self) ] /Names [ (cite.LM-DiskANN) 410 0 R (cite.ObjectBox2024EdgeAI) 411 0 R (cite.Totino2025PhoneStorage) 412 0 R (cite.Xue2024PowerInfer2) 413 0 R (cite.appleM1Ultra) 414 0 R (cite.asai2023self) 415 0 R ] >>
+endobj
+66 0 obj
+<< /Limits [ (cite.aumuller2020ann) (cite.choo2020k) ] /Names [ (cite.aumuller2020ann) 416 0 R (cite.azure2025vectorquota) 417 0 R (cite.baranchuk2019towards) 418 0 R (cite.cai2024recall) 419 0 R (cite.castro2024azure) 420 0 R (cite.choo2020k) 421 0 R ] >>
+endobj
+67 0 obj
+<< /Limits [ (cite.craswell2020overview) (cite.dubey2024llama) ] /Names [ (cite.craswell2020overview) 422 0 R (cite.cui2022dvabatch) 423 0 R (cite.diskann) 424 0 R (cite.douze2018link) 425 0 R (cite.douze2020faiss1t) 426 0 R (cite.dubey2024llama) 427 0 R ] >>
+endobj
+68 0 obj
+<< /Limits [ (cite.faiss) (cite.graph_better) ] /Names [ (cite.faiss) 428 0 R (cite.faissGuidelines) 429 0 R (cite.fast25) 430 0 R (cite.g5.48xlarge) 431 0 R (cite.gao2024rabitq_gps_ref15) 432 0 R (cite.graph_better) 433 0 R ] >>
+endobj
+69 0 obj
+<< /Limits [ (cite.hcnng) (cite.ivf_crtpt:2023/1438) ] /Names [ (cite.hcnng) 434 0 R (cite.he2019streaming) 435 0 R (cite.hmann) 436 0 R (cite.hnsw) 437 0 R (cite.ivf) 438 0 R (cite.ivf_crtpt:2023/1438) 439 0 R ] >>
+endobj
+70 0 obj
+<< /Limits [ (cite.izacard2021unsupervised) (cite.li2019approximate) ] /Names [ (cite.izacard2021unsupervised) 440 0 R (cite.joshi2017triviaqa) 441 0 R (cite.karpukhin2020dense) 442 0 R (cite.ktransformers2025) 443 0 R (cite.kwiatkowski-etal-2019-natural) 444 0 R (cite.li2019approximate) 445 0 R ] >>
+endobj
+71 0 obj
+<< /Limits [ (cite.li2023towardsgte) (cite.munyampirwa2024down) ] /Names [ (cite.li2023towardsgte) 446 0 R (cite.li2024svdqunat) 447 0 R (cite.lin2022pretrained) 448 0 R (cite.mac) 449 0 R (cite.msjimmy_bm25) 450 0 R (cite.munyampirwa2024down) 451 0 R ] >>
+endobj
+72 0 obj
+<< /Limits [ (cite.nsg) (cite.pineconeHNSW) ] /Names [ (cite.nsg) 452 0 R (cite.nssg) 453 0 R (cite.nvidia2024blackwell) 454 0 R (cite.nvidiaA10) 455 0 R (cite.optimum2025storage) 456 0 R (cite.pineconeHNSW) 457 0 R ] >>
+endobj
+73 0 obj
+<< /Limits [ (cite.pq) (cite.schuhmann2021laion) ] /Names [ (cite.pq) 458 0 R (cite.priximity_graph) 459 0 R (cite.rein2024gpqa) 460 0 R (cite.rekabsaz2021tripclick) 461 0 R (cite.ryan2024enronqa) 462 0 R (cite.schuhmann2021laion) 463 0 R ] >>
+endobj
+74 0 obj
+<< /Limits [ (cite.seemakhupt2024edgerag) (cite.snap_cvpr2023_tutorial) ] /Names [ (cite.seemakhupt2024edgerag) 464 0 R (cite.severo2025lossless) 465 0 R (cite.shao2024scaling) 466 0 R (cite.shen2024understandingsystemstradeoffsretrievalaugmented) 467 0 R (cite.skewmanohar2024parlayann) 468 0 R (cite.snap_cvpr2023_tutorial) 469 0 R ] >>
+endobj
+75 0 obj
+<< /Limits [ (cite.sptag) (cite.wang2024starling_sigmod) ] /Names [ (cite.sptag) 470 0 R (cite.tatsuno2024aisaq_gps_ref46) 471 0 R (cite.together2023redpajama) 472 0 R (cite.wang2021comprehensive_survey) 473 0 R (cite.wang2024mememo) 474 0 R (cite.wang2024starling_sigmod) 475 0 R ] >>
+endobj
+76 0 obj
+<< /Limits [ (cite.work-in-progress) (cite.zerhoudi2024personarag) ] /Names [ (cite.work-in-progress) 476 0 R (cite.yang2018hotpotqa) 477 0 R (cite.yin2024devicers) 478 0 R (cite.yu2025ragdoll) 479 0 R (cite.zamani2023conversational) 480 0 R (cite.zerhoudi2024personarag) 481 0 R ] >>
+endobj
+77 0 obj
+<< /Limits [ (cite.zhang2018visual) (equation.5.1) ] /Names [ (cite.zhang2018visual) 482 0 R (cite.zhang2020learning) 483 0 R (cite.zhu) 484 0 R (cite.zhu2024nanoflow) 485 0 R (cite.zilliz2025hnswoverhead) 486 0 R (equation.5.1) 487 0 R ] >>
+endobj
+78 0 obj
+<< /Limits [ (figure.caption.10) (figure.caption.15) ] /Names [ (figure.caption.10) 488 0 R (figure.caption.11) 489 0 R (figure.caption.12) 490 0 R (figure.caption.13) 491 0 R (figure.caption.14) 492 0 R (figure.caption.15) 493 0 R ] >>
+endobj
+79 0 obj
+<< /Limits [ (figure.caption.3) (page.1) ] /Names [ (figure.caption.3) 494 0 R (figure.caption.4) 495 0 R (figure.caption.6) 496 0 R (figure.caption.7) 497 0 R (figure.caption.8) 498 0 R (page.1) 499 0 R ] >>
+endobj
+80 0 obj
+<< /Limits [ (page.10) (page.15) ] /Names [ (page.10) 500 0 R (page.11) 501 0 R (page.12) 502 0 R (page.13) 503 0 R (page.14) 504 0 R (page.15) 505 0 R ] >>
+endobj
+81 0 obj
+<< /Limits [ (page.2) (page.7) ] /Names [ (page.2) 506 0 R (page.3) 507 0 R (page.4) 508 0 R (page.5) 509 0 R (page.6) 510 0 R (page.7) 511 0 R ] >>
+endobj
+82 0 obj
+<< /Limits [ (page.8) (section*.2) ] /Names [ (page.8) 512 0 R (page.9) 513 0 R (section*.1) 514 0 R (section*.16) 515 0 R (section*.17) 516 0 R (section*.2) 517 0 R ] >>
+endobj
+83 0 obj
+<< /Limits [ (section*.5) (section.5) ] /Names [ (section*.5) 518 0 R (section.1) 519 0 R (section.2) 520 0 R (section.3) 521 0 R (section.4) 522 0 R (section.5) 523 0 R ] >>
+endobj
+84 0 obj
+<< /Limits [ (section.6) (subsection.2.2) ] /Names [ (section.6) 524 0 R (section.7) 525 0 R (section.8) 526 0 R (section.9) 527 0 R (subsection.2.1) 528 0 R (subsection.2.2) 529 0 R ] >>
+endobj
+85 0 obj
+<< /Limits [ (subsection.2.3) (subsection.6.3) ] /Names [ (subsection.2.3) 530 0 R (subsection.4.1) 531 0 R (subsection.4.2) 532 0 R (subsection.6.1) 533 0 R (subsection.6.2) 534 0 R (subsection.6.3) 535 0 R ] >>
+endobj
+86 0 obj
+<< /Limits [ (subsection.6.4) (table.caption.9) ] /Names [ (subsection.6.4) 536 0 R (subsection.8.1) 537 0 R (subsection.8.2) 538 0 R (subsection.8.3) 539 0 R (table.caption.9) 540 0 R ] >>
+endobj
+87 0 obj
+<< /pgfprgb [ /Pattern /DeviceRGB ] >>
+endobj
+88 0 obj
+<< >>
+endobj
+89 0 obj
+<< /BaseFont /SVARXO+LinLibertineTB /Encoding 541 0 R /FirstChar 27 /FontDescriptor 542 0 R /LastChar 122 /Subtype /Type1 /ToUnicode 543 0 R /Type /Font /Widths 544 0 R >>
+endobj
+90 0 obj
+<< /BaseFont /DHRMAA+LinLibertineT /Encoding 545 0 R /FirstChar 16 /FontDescriptor 546 0 R /LastChar 252 /Subtype /Type1 /ToUnicode 547 0 R /Type /Font /Widths 548 0 R >>
+endobj
+91 0 obj
+<< /BaseFont /KLFPWG+txsys /FirstChar 1 /FontDescriptor 549 0 R /LastChar 188 /Subtype /Type1 /ToUnicode 550 0 R /Type /Font /Widths 551 0 R >>
+endobj
+92 0 obj
+<< /BaseFont /PEYUND+LibertineMathMI /FirstChar 22 /FontDescriptor 552 0 R /LastChar 149 /Subtype /Type1 /ToUnicode 553 0 R /Type /Font /Widths 554 0 R >>
+endobj
+93 0 obj
+<< /BaseFont /DHRMAA+LinLibertineT /Encoding 555 0 R /FirstChar 37 /FontDescriptor 546 0 R /LastChar 120 /Subtype /Type1 /ToUnicode 556 0 R /Type /Font /Widths 557 0 R >>
+endobj
+94 0 obj
+<< /BaseFont /TCFTCN+LinLibertineTI /Encoding 558 0 R /FirstChar 38 /FontDescriptor 559 0 R /LastChar 122 /Subtype /Type1 /ToUnicode 560 0 R /Type /Font /Widths 561 0 R >>
+endobj
+95 0 obj
+<< /BaseFont /DHRMAA+LinLibertineT /Encoding 562 0 R /FirstChar 132 /FontDescriptor 546 0 R /LastChar 132 /Subtype /Type1 /ToUnicode 563 0 R /Type /Font /Widths 564 0 R >>
+endobj
+96 0 obj
+<< /BaseFont /Times-Roman /Encoding /WinAnsiEncoding /Subtype /Type1 /Type /Font >>
+endobj
+97 0 obj
+<< >>
+endobj
+98 0 obj
+<< /D (section.1) /S /GoTo >>
+endobj
+99 0 obj
+<< /A 565 0 R /Count -3 /First 566 0 R /Last 567 0 R /Next 568 0 R /Parent 6 0 R /Prev 41 0 R /Title 569 0 R >>
+endobj
+100 0 obj
+<feff003100200049006e00740072006f00640075006300740069006f006e>
+endobj
+101 0 obj
+<< /D (section.9) /S /GoTo >>
+endobj
+102 0 obj
+<< /A 570 0 R /Count -3 /First 571 0 R /Last 572 0 R /Next 44 0 R /Parent 6 0 R /Prev 573 0 R /Title 574 0 R >>
+endobj
+103 0 obj
+<feff003900200043006f006e0063006c007500730069006f006e>
+endobj
+104 0 obj
+<< /A << /D (cite.faiss) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 226.768 625.24 238.026 633.494 ] /Subtype /Link /Type /Annot >>
+endobj
+105 0 obj
+<< /A << /D (cite.kwiatkowski-etal-2019-natural) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 74.439 601.33 85.696 609.584 ] /Subtype /Link /Type /Annot >>
+endobj
+106 0 obj
+<< /A << /D (cite.yang2018hotpotqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 143.671 601.33 154.929 609.584 ] /Subtype /Link /Type /Annot >>
+endobj
+107 0 obj
+<< /A << /D (cite.joshi2017triviaqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 208.326 601.33 219.584 609.584 ] /Subtype /Link /Type /Annot >>
+endobj
+108 0 obj
+<< /A << /D (cite.rein2024gpqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 279.464 601.33 290.722 609.584 ] /Subtype /Link /Type /Annot >>
+endobj
+109 0 obj
+<< /A << /D (cite.nvidiaA10) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 174.56 565.465 185.818 573.719 ] /Subtype /Link /Type /Annot >>
+endobj
+110 0 obj
+<< /A << /D (cite.mac) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 284.246 565.465 290.871 573.719 ] /Subtype /Link /Type /Annot >>
+endobj
+111 0 obj
+<< /A << /D (cite.ivf) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 245.633 75.303 256.891 83.557 ] /Subtype /Link /Type /Annot >>
+endobj
+112 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 259.472 75.303 270.73 83.557 ] /Subtype /Link /Type /Annot >>
+endobj
+113 0 obj
+<< /A << /D (cite.shen2024understandingsystemstradeoffsretrievalaugmented) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 471.419 565.302 482.677 573.556 ] /Subtype /Link /Type /Annot >>
+endobj
+114 0 obj
+<< /A << /D (cite.ivf) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 505.519 441.765 516.777 450.019 ] /Subtype /Link /Type /Annot >>
+endobj
+115 0 obj
+<< /A << /D (cite.choo2020k) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 357.828 417.855 364.453 426.109 ] /Subtype /Link /Type /Annot >>
+endobj
+116 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 504.771 378.004 516.029 386.258 ] /Subtype /Link /Type /Annot >>
+endobj
+117 0 obj
+<< /A << /D (cite.nsg) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 467.724 366.139 478.981 374.303 ] /Subtype /Link /Type /Annot >>
+endobj
+118 0 obj
+<< /A << /D (cite.priximity_graph) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 481.711 366.049 492.969 374.303 ] /Subtype /Link /Type /Annot >>
+endobj
+119 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 495.698 366.049 506.956 374.303 ] /Subtype /Link /Type /Annot >>
+endobj
+120 0 obj
+<< /A << /D (subsection.2.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 438.742 280.126 456.904 291.314 ] /Subtype /Link /Type /Annot >>
+endobj
+121 0 obj
+<< /A << /D (algorithm.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 372.991 240.438 379.649 251.626 ] /Subtype /Link /Type /Annot >>
+endobj
+122 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 429.675 191.776 436.393 203.99 ] /Subtype /Link /Type /Annot >>
+endobj
+123 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 439.969 191.776 446.687 203.99 ] /Subtype /Link /Type /Annot >>
+endobj
+124 0 obj
+<< /Filter /FlateDecode /Length 6513 >>
+stream
+xڵ<ۖ��q��
+���s2����N�d��J�o╎������ "�Y�,}���� 8#m�i�F_���^����X�~&���w���J ���*W����JfB�7��+kV������a��z�6�T롩�W�z{��r]o��c��re�uF=^�Cs�)�;z�;�9޷�� ��j#��S=�}wM���?�D=�ns��ݟYM�U��R1@F�:m���������~�k�����!��vw�~w��i���ԅ�a<�cs��#���`)�L*���z��Z��U��䖢�=6|ޜ�vߎ_��pt�|�o� =.B � ��å���
+�ɂ��^(q��R%�Y�uG�����ǧ�'��f�nl�=���Gz8�m7�?���^h� ڎ��i��V<�y��\eJ2��~@��z�d ��������>p0�����-���cݍ�}�s[�<AE�[������"�U���Q8�,'ڬ�C{׵�a�����%{L��DC�φ���p�D��2�"'X�n����!֟��?��2��#-�h�<�z����ŭu0��g�T�3(��"� �
+dA��$H�~���CC�U'���84��7�Rë�\�_�y����5���Z�z&���*}������m
+�,h�b��.@b��?$u�#x�'`�%��&ӕ?ة������OGz"�z8�knh;`��g�P̱M�� +�� �Kz�>��������@Be��^~�+���|# �mө�L��Z��H;��u�؏���W�\��M�Hc�</���"8�]j� ѻ+ ��~jk��"����D�i5[A]�H�2�e� �#4���o@*Efr�.a����x
+��ㅧ(���mӗL����)�jN�$8�k��Q�~:/�v����4�~xk���s�}���m��ҋ���P�1�S�_��98�o��,�N�:jm���i��P�l�c ک2y���5�7�vf��7?�yA /������ l����.��HW6�\�y(%�i�T: �v2������2l��� NU�L�ٲ����YB��@���Q��a"���}8��Z8�{gP�G6��9h${���m�c}�P�-������ܺ�F��b`o��E�>�<��*����J��)�5Z�s�Umb���,2[�t��B(?(6�#x�� �t7��K����V�n��v�SG��[ЋLNτ�αZd�`��'vc�� fU3�����=��m�Ћ��< ���KOs���ts�Ȃ�-,���P�] ���5K ���ff���{2����R������v�'V)�
+ع�� �Vy+,\c��D�U *A�*ȓ�)W�Ѹ;�:���z�r���=oEy��#��D��D[R��@v㏘��V�<\�ޑ�Y�}��/���&�
+ Uj;��~�<����(�c)5�R�M�c+6h��mG ��=zx�ҭ�m'iU>@S
+��X0���S#��݄kz���S:�\�T�E2�����<򸲰��J<N��谒�����v������*^��������d��t�6� 1`f+���O��gpY��.8| ��5u!M��ѷ��ڑhŒ�!2;v;h�,����r��1^�4��=���G�`� %ra��)��wW��pC�nr��'�7s+�C�t&���#3��Al8gsRc��==��}�()�_Gg�l�A���s�ϙ�BZFUu��Y�KW�-���#�������M�NWU��lW�0Τ�MP�f�4n�Ƴ@h�6�/�S����a�#��`����Ӏ4�L��,�b��OBGGO�w�w�7���[5 7�>"�Т8M��c���ouN`��-оSRU�8X�����f�7��=!����^�'��c�PM�c7��1<)�30t�a��t�3��^��O�k��`CV��B�<w��@���Dw�T�^I�
+Q������D�
+Wb���~t��?��º��xjo&>b�����PS���7�Ap�9� ���Cd�o�n�A��}o��nf`��5�T?8 �D�P�#����ȩ� �:�� kf��IM^�(���F�(�c��:L������ئ��['���{o�����2�,�c�(h��k�"i�p2�@�F0���(N�멥`,�~�֎�~xpv��p��
+f� F?2��#��܉�h�1&6�ыv�#�L2!�) �oc����,K�/ <f��]�
+�.=�Z'G���2� I�/���)֌~�в���E= �&��H��@me�8�ޙ�� ���U�[D_��3wR^O����|@y�^� �P��(0���� �u�r�
+]��;!�P�>��Q6���G�/�zpY.e���Ìc8
+�d��A!��,��yNv��Sp2�)�mƘu�)L24�E|����]����6��z���ųB������f|͖%��dСw��9?�b���7K�6ӕ� �G��2d�3� ������a���~�{Oe�䰾�f!�~;��i
+Y���pJ#�\�|���ҥ��e:��L0��"SȢN�|��)��q���Ʉ���kߣZ�=T`*�veA��0����^ri�YP�Q��JY@6�`q�2+����U�2m����S�O
+�-�Y���򨏦��
+�nk���"��5�A�)?oʳ�6��祥s�g�BY�S���P������O)�uf�I=%�bF܏������ʌO�~�LL:���w_fF���=�-� 0&�y����'Ķ����Jd@L�RN�6%��8 @�؉wbi�����zn@ɼʬ�d�RRgUQzt�E�j"��a�r��;o��OU��~QX����Y�"f�<� =��ɣ���K;�sn��
+T��������*c�ܣ>"��
+]�iՉ6a9]�H�U@�y��15���� ��h�b�f��m���Y�p����Β��$��[Zܰ7���Q�r���G���,͵�� ��L�L�d�2`�p4)3I8;��RS��a��a�i'�UqA�YLzj� /�\W�dRVѼ��4���0֑y�QD�L��a��b6�aլ�8�l,w�Ed��@�T����n&U1.m� Y�wM׏͐Z^���۲@�f� <*Z��
+<v �/*1p�dw����i�|@���v�s��X���d���- ������S� \�L�p��9�"���ەi�>ޝ�#�8���<})�TB�� 4���O��>����T,��H� l��l�F.۶?�c�`�輻=������&���<Ӱ��tg)3 t �"�c7���q��H4�{g�e �� ���{
+~r��[Ӗ&^L ��Y�`EY ΌM�_�9f��t���� `���fW^uL��5�/��1���1���z�l�Td����Ir >���'�v�j�l��O9���ם�o‡�soԃ��� ��L,+��)�),�-uj�b�)D�Q e���y�YG�I�D�Vs���1���L��B����a>���U l��_ڭ�8@��0 JT�q�C@����>(�i�˲���n��r [����Js�2�}�����֏z{h����digh�XPj����4v��U�K�拉o�öXm�n΀y��g�>�7*w�'������b���r�U�>����5�������� X�嗰/c2#���؍���j�;ג�ޤ��rđ���O�0�z ����0�}����3�:�T�!�Xp���M��1q��@.J�&���հ C�t1���Vˑ ˬ���������Y�fP=*c�b��T�E����M�düi[%�m�B���4�}�Bh���1d�ֱF2�"��� 3������uN��#���H�
+� ��2OE��'<1o�1t&��^|�h�i~=�lGAGr=-u z�WGM�}&���z�D��[��KJ+ڰ��At{rRZ�rɋ�=�G�Q� ҹ* [8 O��0A��ԧ;L)�b|��3���$lV�v���/��^�f�c咣��2�9�1({�k�Z��YҒ罒yj0_"T�5��E
+i,�K�� �LƉGcF�� 8v�J|{b%+\�J2�z"c�p�g��rQ�bI��*�S`1���/;g�`6����q���+��_�vf�ڸ��@�V�t�q�Q�8�*W� �X�<t$#����+�J��<�UViF�B���;�X�ʋ�gTf}��</�׌��0���kx��95q�i�����ಕd'����8 �� ��k�P{z�$ �>�v���+2��3��*.Շ7L��9�|/@�>,!��T�A��NnN���S7�u����)��5�I��SgI;s�eX<e�~S����fOW[59����(w]�M������})�W|�_�7�&�9B9+B�a [^r�8���,�BK=�__
+��]�YR.JV����i���w>\�A�ƛS�/�V*W��@;���jU*���B�Ӳ�q��;�v�A��Ŭ���˞Jv�ҽ���6Y���e��"��ሖ���Hߤ���s���ۍ ~wŵ���P(n-��!,uC+�@��4Cz�%�j@1����AvͰ�E�������|)=�.u>����*��߉:�B>p��0�ftT�Ԁ���dҿ���S/fm�� ՟���o � #[9��<C ��B�A��o��G����KbÀ��� bm)1�_1�t�S3s�@�ތ��]�+�נ��^a��g�z�9��γ�ۏ�E��[�B�?c�i�|7��KJiU�t��b���P�'�?\��\��n��B��[H���s �d^'��y�K�>�9�|�͋���Q�g�20Wf������@�z�{nƫ�X��x3���\/
+]�L����,8��v&�����~L%Gd ,�Ӌ.�LJ�����WV�q֏X橪���و��v-j�ǟ���Z��끉�"]�0$2��*�����x���/�>�V^d^v�!`��7��xi7�򢒱oܥ�Kз����~[���Ӈq�o��: /�t���%+�U3�u�
+,��$S���x�U�t�@G+���j��I3?J�`*e���l���L�����nn�kڑcHi���|��:��4Ohz��`t�+�l���������6� �{�MKW����H���H])��E�Tk���SF^zK�:\ޮ׷� ��c Q�J�8U3p���J�vh��c�;.)f��G]ͤ*
+�p���{E�q��)�J;_�<P�S�n4�-��?��?4S����Ҡ�t�o<�� ߵ�� ���v�+�ys�-�4z_�:�#��џ���!���j�
+]m��;���ҎMK;���嫷�[�I�}X�!��o)�m/�r��ӆ����D[�<[����/����7}J#�t8c�+��*]�L����)��K�����\QL�r����5x�E�X���B�H��,����  ��Q�6���|-F`���S���\j�G:�|(cNW�5l�3~�Bէk���1.�>�qҧ� %�E���+%Ҋ"�Yx�8�]�$N��B������*�<-�&����Ys/�籰 [X,�����{"��1�_�t9��!5���p��T:��v����F;5�'/�+�O�O�ot� �œq״��C��1��� ?�R�Le��vi�kQ��l�zkw ?z�ĮH%�tFf9H�x�5������E�e9]-k����n�� �b_�J&+l`�đ�u���r�|de''��reTi����$���hH27�������N�'�^��\�2�����*8��K����ru>��k�-�X �뀞�)k����[�ޑt��-����}O���?��ɘ[�:�.UU.���ı�PMKA�}"�X 1�ùA ���Y�(�RdN�Z �����'2��\޴ue�Ʉ�]�Qmسtט�Q״t�imh��/��ɴ?8_O?��F�>�;�s-YR7毕�%�T2?&�E�����( 4I��4 ��LS���@�6��Q���L�x��\���F[4��)=~�uJ;���x�k�x�y
+ksw�;A�RDG�2���y�L���h�/��T�x�w�"�;]�.���%|-�"R�4�Z(��k��������:��^ӯZT|� � ^AS�)�&��wWH*O���
+ڟ�S,��y�d���z��E*��1S�S���4*5l#�<�/,�Ŝ)�rR�gdc���d>+�}d�nS�$�-}[]���E�έ��.���Ѕq��d�i
+��aܙRl�f��)FVe��2���O��v?������0�r��H*d���E�伮j}{b|bsP��4�t� :�:��� A֯�zp)�~������'�� �>ŕ��>ևfl�Oi�R�3��!%�������i��˵!A�YaN�f�?��qp-0{Tuu�q�h�җ�2�;�ƒ7�;qة�a��7�ߌ���!v>��U`.����u��A��Ū�`&�@y�q�0�a����{
+�
+endstream
+endobj
+125 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R /F297 575 0 R /F301 576 0 R /F304 577 0 R /F311 578 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+126 0 obj
+<< /A << /D (cite.graph_better) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 137.083 345.77 148.341 353.934 ] /Subtype /Link /Type /Annot >>
+endobj
+127 0 obj
+<< /A << /D (cite.priximity_graph) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 151.07 345.68 162.328 353.934 ] /Subtype /Link /Type /Annot >>
+endobj
+128 0 obj
+<< /A << /D (cite.li2019approximate) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 165.057 345.68 176.315 353.934 ] /Subtype /Link /Type /Annot >>
+endobj
+129 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 179.044 345.68 190.302 353.934 ] /Subtype /Link /Type /Annot >>
+endobj
+130 0 obj
+<< /A << /D (figure.caption.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 218.443 331.488 225.068 342.676 ] /Subtype /Link /Type /Annot >>
+endobj
+131 0 obj
+<< /A << /D (cite.work-in-progress) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 91.661 266.585 102.918 274.839 ] /Subtype /Link /Type /Annot >>
+endobj
+132 0 obj
+<< /A << /D (cite.seemakhupt2024edgerag) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 105.825 266.585 117.083 274.839 ] /Subtype /Link /Type /Annot >>
+endobj
+133 0 obj
+<< /A << /D (cite.wang2024mememo) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 119.989 266.585 131.247 274.839 ] /Subtype /Link /Type /Annot >>
+endobj
+134 0 obj
+<< /A << /D (cite.yu2025ragdoll) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 134.154 266.585 145.412 274.839 ] /Subtype /Link /Type /Annot >>
+endobj
+135 0 obj
+<< /A << /D (cite.ObjectBox2024EdgeAI) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 93.715 254.63 104.972 262.884 ] /Subtype /Link /Type /Annot >>
+endobj
+136 0 obj
+<< /A << /D (cite.Totino2025PhoneStorage) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 107.85 254.63 119.108 262.884 ] /Subtype /Link /Type /Annot >>
+endobj
+137 0 obj
+<< /A << /D (cite.Xue2024PowerInfer2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 121.985 254.63 133.243 262.884 ] /Subtype /Link /Type /Annot >>
+endobj
+138 0 obj
+<< /A << /D (cite.azure2025vectorquota) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 148.157 206.809 159.415 215.063 ] /Subtype /Link /Type /Annot >>
+endobj
+139 0 obj
+<< /A << /D (cite.shao2024scaling) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 161.449 206.809 172.707 215.063 ] /Subtype /Link /Type /Annot >>
+endobj
+140 0 obj
+<< /A << /D (cite.zilliz2025hnswoverhead) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 174.741 206.809 185.999 215.063 ] /Subtype /Link /Type /Annot >>
+endobj
+141 0 obj
+<< /A << /D (cite.castro2024azure) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 212.483 182.899 219.108 191.153 ] /Subtype /Link /Type /Annot >>
+endobj
+142 0 obj
+<< /A << /D (cite.douze2020faiss1t) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 221.809 182.899 233.067 191.153 ] /Subtype /Link /Type /Annot >>
+endobj
+143 0 obj
+<< /A << /D (cite.optimum2025storage) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 234.715 158.989 245.973 167.243 ] /Subtype /Link /Type /Annot >>
+endobj
+144 0 obj
+<< /A << /D (cite.work-in-progress) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 229.826 111.168 241.084 119.422 ] /Subtype /Link /Type /Annot >>
+endobj
+145 0 obj
+<< /A << /D (cite.wang2024mememo) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 243.018 111.168 254.276 119.422 ] /Subtype /Link /Type /Annot >>
+endobj
+146 0 obj
+<< /A << /D (cite.cai2024recall) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 118.048 99.213 124.673 107.467 ] /Subtype /Link /Type /Annot >>
+endobj
+147 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 436.803 430.229 448.061 438.483 ] /Subtype /Link /Type /Annot >>
+endobj
+148 0 obj
+<< /A << /D (cite.wang2024starling_sigmod) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 450.777 430.229 462.035 438.483 ] /Subtype /Link /Type /Annot >>
+endobj
+149 0 obj
+<< /A << /D (cite.pq) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 508.335 370.453 519.593 378.707 ] /Subtype /Link /Type /Annot >>
+endobj
+150 0 obj
+<< /A << /D (section.6) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 353.261 261.053 364.701 271.992 ] /Subtype /Link /Type /Annot >>
+endobj
+151 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 543.471 262.856 554.729 271.11 ] /Subtype /Link /Type /Annot >>
+endobj
+152 0 obj
+<< /Filter /FlateDecode /Length 6061 >>
+stream
+xڵ\K��Ʊ��W��pN�0� �^�\ٖl%��r������!"��ɯOUW5� �1:� �F�����ɯ��o���������J\}�D��\\-��޼ͯ����<s����{m��γ\��\����~�/_?��(��2+��W�ﮌʬ0h����˫7���ݾ����4�L\�}���^J�1z�eVhӿ����/�}��+?���u1[��v���7��a=������͖���Y����w��_�ף-�&3ʍ��`'Om9�:n�e��؄�lqeK������ϓ����gpK�rp�����~�<�ϧ�(�<3@��MO��^ T�e���[��J?5����J��Nj�W�U����������Y�[��u&�h)zb2/3�G���I�Va�UeV��N��7�?X��7tV��E�KM���O�N����ꐕW�a�[���_g�|apU!3c�4���e/B7$ @�Ê.O�+͝ �i���gfj!���{���|j<X��S�P�(2�"��(�(�?jQy��xQb$p���E^d�u.DVC���R
+s[�9~8t��dC�~󯯭��擧 �(��$2�EO����f����Vj���׷@Њ�v��6S� ��� ��Y�R��'^:E�WM�����}TtV*�b�Fn������n��8� ��45��
+ٓ�~��:SZ �3%#pX:��1O;]^�h��Փ��O,:W&����,pt��WW}�լ�T�в�_"���f���� QN� ���z^��iFb��K=�jt]�,�(e����/z[7�'a3=��W�Ĥ��k^X�-'�v�ڲ,55�Μ�Ѽ8��Z.�u�A������ӛ1�25���N
+���?��ĉ�6N}�{�G�zk�Suh��a�|&�m� 9�R$m��6��칯�Q^�<�T&<i�W����`[m6�����U��ٺݤ:�%��~�Kp�y�;�J��e����?@p#z��j�6�7�X�D�-����x�w��n'Ռ�̘ڧ�V%��Ϋ�tgw��$��lp�VU�`0�z�w��/&�.<�M����r�s[~��I�9Q�$*Γ�4mzy�說d���2pl?H15�v��t!e, �z՜߫3Y x!�jy�ύ��]����W ��[:g�us?���Y󔴖$�&�ՙ�Ҁ0�,�����]���W�-@�iAE5PTM�D���M^�eT�u�p�sY̾��_M��"�)N0-���&�%t�z�4p��M ��2���]謄�ɰdρ2
+z$|)��#���d��p���>���l0Բ�����x*��h�K'�Ux��L�/��Y�c1N����u�Į
+ī��]���uɮJ�Ђ�+��B�
+�&y/B��A�=O���S)�
+�= ࣇ��-�m�R%|����K%2gP�)@��۟�H��8�8#�*���s:J"Jy֣�Z��0v��e�Ŵ
+,]H!�2r�0��.2av�(��������k�6k�⺛G���If0����CU�ͮ��m���9,mmf����\�g���F����A�z��ՠ��s�!��o&�N��]O�n�0)G��|2�d�;$�����Jpe/��S��p��,��0�ฒc����$cD�8��f���Ema� O�=��0:��Ҥ��bvzB��4K^G =�-�E.�il�ѯOvTۺY���#�'V�H8! t�Y���eխZ�e F��a]��o�g��i�g��UQS�<!J^�aX����31��l N���z�5��k+f�xu��K���ҋ3qvG8d=�� +��b�xWo�����z��� ��6�H�M��@��s��[���� �չt�w��E�����mU7t�|�kZ�"��r����ׇ=ѷ�CO`3m�?,�z�܄E��hH�9Z����֟R�fĬfQ�!~4$�1�mW,��ܠᣢ�7St�l$ӭ{|��qP��
+fٌ��~)���0�u[5]�r��7px��={uGO*���vj�9�)�4�Z���d���Hz����Pcݵ�mx�m���޴<�~�"���I��� -��J�Y!S���GIB�h���ϐ�����K�o��H�c���Ԃ�:�6u�؋h�A2���m�I��j3Jd!�K�s�f���zv�S���̦^�݆����j�l�YEM��b�S�Y���~�0�0������D�P���D Ԧg�X���ڇj��siի�%=']�f��G�����ް�m�� ۈ�љ�g(I��N*�ۙT�C{[�75R5�������uz-��h�'��V�m�J��/���^�[�"���}C6<|���wW��_�EN W�3���LV�Ob$/�\8)xt���I�I����O�,inT:�2g&��j|Ҥ�Kg�,0a��ft���9��lN��,��y�+W�R��Y��Z�`m` ��m��6#(m�6�G�m�^5=���/�����f('(����Q�x{��9J%3�8�g_��N}$�1eM3��|���]q��W9�6����x&�,�O7y�}�cH�o��߯�<�QU,���Ƕ[m��'�`�WR[�����/A0�*�Eī���Q�c/�t>���� & AizE�WU�-[оt��mW��T>z������� ��[P�����.�%/��*T��FV^��J4a.P+)�׀� �&����(�H�0�������9%�n��a��9�ŧͩ �$C����Zgz��� �j���z��~�� ��A2!� 44z�=[��~5�@ƀ1����x����4x�"P�9�|g��3P�z4�=ô����O�Sb�n4�ugHf`<�������a��V[���-�_�p?˒��w��S��AG�9�+��!+��9����w-5��ȩ�#Ƃ'^��y�4�=J�6x���d"�=ʊW�H���b ��(G�Q3<�v0�G��a�7'ߣ�|��݁gM�=l�O�3�
+g��J��9���MG��j��K��S��^KK�S|�f�7�5���vQZ�!�����Rrj�n�E "?Up�HJi�W�d�5�A�i�_�\>�.�퓗�R�% 6��b��KhQ��z�!��C���CU�i�R���3:��&��)���LX� %�Z��K��3��m`���>B��E�c8�� �!���)3�X���\x.�iI��۱��>4��d���������#;\zFxM���; ��:�[�D�(tev #���A>;4臒�=T7��8 �� YR
+�i���Ek�~��MK��B�`Y
+���ž�,K�D���Mߊ0�i+�aL�b �Ɗ a�!�#Ctl!�� (�?����Z� ٱ�� k@!� ;;��Eo�#����̨���A�wts�PC -ƪ��]N+��{�]/f���+��߯���j���SM�r9����;��qS��a�vï��VN@A ���k��1�Q�h �f� ��%kB�������ƤlN�T�[z@et!@�a�#(��{��^��޶c����}�ݞ+���w�}~JM,Hi��B@����U�-��p< �+z�$=l=�a ���Wy
+��b�}�h�Ʊ�����i�K����]�Q<���p��-�U�������~�gJ��p6&G�QRE\i ���$�w�9*�w���� RypG"���oz�Ƌ ���:���H`6�"�K�O��(2e�@�0O�c�I )ɓR��j�X=t�-�wF����m�!� ������~_-��������86d�?�W�!�@RF��Z ����XP�:�QlMC�w�ev6k��u���bQ��I�}�,�VR,/���{��٫���z����+��eƞG�O|��T�F�� ���&�q&-2��G~�b|�Sn�SnM�#%*–�����!K�$ڕ�-x+hB����;L�y=�̓1��1�Q��-���e�Y�/{�V���c�������x��=*h3���tȡ���2�X ��|@��$m9�.��#Q�Wf4�{q�fS�'S{��?h�8��Y�]H�RW��8�=�,ߩ�EGA���'�W �S��ip�$S���F��͗!�J-G�W >��tϹ#�_���|�ߴ-j�J*a���ªPNl���t�2��|P;Z'vYp1��!5��D�Ox��
+s��Ȑ�|�o�v=���:iEY�Xs�kC�/B��b]�����?Rd��A-�4`�~'��StɕG�~���3�,di��*��;���C/��;ě�n��g'�$���R�����;�0J9DJ�q�{ ��#���o�������i�������|r}\{?(��ܼ�X�8ʷzC)/��a_-c
+̓�����Or���dn�L�@�� �>�6>�P2��� )7�D|sX�~�ۻ�f3��nq�1.��dL&yI��f��v |k������_9�� I�l���<��ѷ�:���Y� �[�ք'N)u���&QM�/eǟ{۵j~��5�5�3yv�▓�j���8�����#w���?��
+^ �'Ն�?�n��Qq��Vj��e2�)Og���~����k#2�T2��g��p�����A���h���(L�H �6d&O]`�9�z�88�l��l�w�'��X��P�j� ��>��z�}5�R,�r�iɸ�O�f�����C�؇��Z�*/ �%�E�X{S`ձ��f�-#��Hx\���?�N�q�>(���0
+�W�;x冚���Tc/]�X5<�4����˂�[`n�Y_ �_�*���?���]r>Ƈ�XT9�˻���޿��Q����b`�Z���7G�����B�59~�%ӵ��d\�`�V���oyUAw*�B5�ıbW��dJs�'���jԠ�Nx$�\�c������t�P���^m���t� ��O2�P��r�j ����{�墨����6 F&�k(.�X75�L{
+(e2�;}�Y�}mנX��5r�ű�pg�j����풬'#� {�Mw
+!�7��P Z7p6[���jlv-ۏ;_
+N����C�+���(���qIB��?T|E�|6�!K�?4������ڡa��V p�q��=��n@��S��e >�
+z�\%z?�c�>��У��n��a[5�(���&����HSܜ\M���+���c9>L*�Ī:ϫ-�J����4U�#G�dG�a쯣ֱ�MAT�����Z"~�֗}�
+�Iki��!��g�; t�؎Lj���5���GA��B�m��1Y"�{��h���U_���j�F��7T�M���
+�n�7���u
+45���M������\^ug��ºt�S��S"��� o�IÎ�B+�Bj��Q NL�9�An����~��� ���6�y����~8��O�'T�L� ��\��nT��b�~�h��u�EtT����E&r&��k�L��T��s�����yy*�O�^�n酆Gx��;�e���ю�^|����#S�Q�o�]�@��&�D��P���@1��0����7� ��!s�,���S� ��:ظ�g,ǃ-U��-z����/6�7Pд��'��>8@ �~�#�������Ѹ�õ��g�t�P�(e&C�c��"D�𺢟��b����m(���b������=�z�,Tb�`�v8�\���
+���r��2 w�q�� j� ,
+��f�eT9��W ��� �)0mXdJ�>�aQ�|��#��'��>�9Қ�YF-�:MR��o.x-V�����o��{�E5Z\dJ����x��NI�1�D������>0�F�@8�^rS�# Ǘ����!mšlX���ʠt~J��P���u���� �ͥ����Ͽ��. �����t���mxN���51��E�5�L9N��꽮3�9- '���7��'{b��Í�b ��9�JF��y��0*E�)�z�E��)��(&�,�����o"
+�#혊��G��O�R�I0�� ��$F-ڬt�����+�,~�^L}v�����,+<
+endstream
+endobj
+153 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R /F293 579 0 R /F297 575 0 R /F301 576 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] /XObject << /Im1 580 0 R >> >>
+endobj
+154 0 obj
+<< /A << /D (algorithm.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 177.368 545.772 183.901 556.96 ] /Subtype /Link /Type /Annot >>
+endobj
+155 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 227.264 509.907 233.796 521.095 ] /Subtype /Link /Type /Annot >>
+endobj
+156 0 obj
+<< /A << /D (section.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 212.831 350.504 223.981 361.877 ] /Subtype /Link /Type /Annot >>
+endobj
+157 0 obj
+<< /A << /D (section.5) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 280.367 326.594 291.518 337.966 ] /Subtype /Link /Type /Annot >>
+endobj
+158 0 obj
+<< /A << /D (figure.caption.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 259.586 298.699 266.198 309.887 ] /Subtype /Link /Type /Annot >>
+endobj
+159 0 obj
+<< /A << /D (subsection.8.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 120.789 226.968 138.951 238.156 ] /Subtype /Link /Type /Annot >>
+endobj
+160 0 obj
+<< /A << /D (section.5) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 113.82 179.147 125.129 190.519 ] /Subtype /Link /Type /Annot >>
+endobj
+161 0 obj
+<< /A << /D (subsection.4.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 179.83 107.416 198.17 118.788 ] /Subtype /Link /Type /Annot >>
+endobj
+162 0 obj
+<< /A << /D (figure.caption.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 344.746 533.817 351.371 545.189 ] /Subtype /Link /Type /Annot >>
+endobj
+163 0 obj
+<< /A << /D (subsection.4.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 447.21 497.951 465.372 509.324 ] /Subtype /Link /Type /Annot >>
+endobj
+164 0 obj
+<< /A << /D (subsection.4.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 536.343 386.131 554.828 397.504 ] /Subtype /Link /Type /Annot >>
+endobj
+165 0 obj
+<< /A << /D (subsection.4.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 460.082 362.221 478.244 373.593 ] /Subtype /Link /Type /Annot >>
+endobj
+166 0 obj
+<< /A << /D (equation.5.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 391.263 324.125 397.981 335.497 ] /Subtype /Link /Type /Annot >>
+endobj
+167 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 371.239 204.573 377.809 215.761 ] /Subtype /Link /Type /Annot >>
+endobj
+168 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 544.04 180.663 555.344 192.035 ] /Subtype /Link /Type /Annot >>
+endobj
+169 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 487.024 85.021 498.18 96.394 ] /Subtype /Link /Type /Annot >>
+endobj
+170 0 obj
+<< /Filter /FlateDecode /Length 4583 >>
+stream
+xڭ;َ�ȑ����5(��a����9�]{`�k1�}`�,�h2����zGdD&�U�m heF̌�Ȋv�]���]t�+��h'v"R���.*TZ���� �����fȮc�7n������������������^��.�D&���]B����8�� ~��?����<쳠���� ����?�|/#��>ס��j��|���i���q�Zl��ۺ8 E���"����طOuW�4r�O�CY��}��q����հ?�8�Tw'��_�v��1\��@ں�ۢ!�8�Cq�C<��C��e�� ���8�U�(��T��9]��;qD�<<c��K2�R��e����;):�2�����T�4�����U�������+��H��b:��zУ�A��9R�XWp����(z������G���(�>L�e��8h�C�&F���;��4&��]c�$��~F@v���i�&j����Μ����s�>a����#,��s�8�f�Y����`�v��:��Õ��E�8�,S'S[�gq(⯅�D���R����P�� �4]�"xߜ�h���8�σ��>����}���Y,V�����i��� 3B�~��Re�:�"�H��H��g��x�,�� v��Ze ���S0���o�[�e(`��F�0p��M� �S#�,�Y@P�E� ��4�'By���eHS��wG�*�8 ^w�z�����A�G��kM_�t)X -R����(�װ0�6�쾔p~~��� klh�$T��+�QJ�^y�],���̩`G�%�p@K�-��i�kZ�V��ϋ�Ce��W�U�t���b�j'�o�񆅕6G��̣�NU�#��� 08�D��] G��6��Pq�u�ޑ� w�0ĩ�4T���X�$������y�6ܴ��Y4��s\՝� �L�0N؎���?�U�^߁�l�q����GPf�w�AY=�Wu��((�*�-�5��$��:���(�S�L���~ђӘg�p����L���'���A�XeVU�3~(�tX$�7�<��i� &����zA��в�Fnzx�oN��w:Pd�1�ӱ�4{������y,�l��U�-ޚ�������ZZ��������ՕH�P=�]p)��ְ�A �@���k��*(��~&7BY�B�U�y��c�l���V֕U�����IR��~*����0vEw�H�^�I�?�Q�'��}CK�Z��8���Lt�v
+�M*ҵ�K�+�+��0Rωm"��tBW��a=�eI~���Cc���x�4 �D�����
+b�r&�֦ ��&N)�$� 6�6K�h�p87N��1j�7�T�4���������GIm�}�bg�V��2
+��Z���Ō���ǖm�X�E��~��;�6L���LC��BC�,U�� -q��x��ps���u���!���A�}I��I3"�:|��W��f���L"���Wl�u0 �NK+�x�,����72\�e��1KCcZ����� �Xo���f����*�6U��}��W�}]H
+��}&Ao}�O�8/�%�mW��L����–UW��P�H/J�k����Uw�~`� < ����T$�H'++�&���p:��e=�q��1��$h� �s�v�j���?�bo�ˍ��?��݆��yF9� ������aN^=k��� ��’#1
+��왎�c�o97p��(i
+�ص���.��9�@�I�4� �
+�|r�g����[�{�`:4��Bg� w�6�T&I(2Ɩ�O��\5F+��܃ȕ�~Hs~:�ME#�E�B� 6��;ʠ8u=x�-��ڄċ�H�o��S����T��<Ј�R҈�-���5:;�4LM�ٚt�R� %+�y�y���tn�P�p�~"�Bg+�ж�Mr�`�c��KS�_1�Y��z�SQ�D���$be�!�����2T|����f5F��o���e��ϓq�t���Cs����=����w�7㰗��6_B�0�(���ئR@��:�J$k)Q�#<62����:�/���t����Ĺ/C)���h�2��"\)��{�|R�rp����nd�te��/�����줙2w�-�/2 �i �g�:ɿ��4{=Zrz ����Eݎ���� n��H�D�s uk������z�*/}�5�ߗ��b3]>�ӹ��;����-� b4�w �]kPg�Lǽ��µ9�q�t�&�q�(�0��
+ˎ��&�c��ؤl�ơtA[���
+1f������#�秽D�����|�c��\�^q� ���0�����<U{��;�!�c<~�ǚSa^���ش��Q�;G�?�n�'N1��^OSòD��(k�sZ\���#Z묭,)!%Dy�H��a7���N����l���gᄉf���tc F����P��-�G]~�S�AƠ_��E���L��G@���IPZ��M έi!�����?�z�p��y�d��Z]��>�z�OI#����ֿ�!*Z��u��{C��X��g ������GT�R������4��! <R���U����%x��[��6`��K����)�m�H���*�0���_i��`�"2�칠� �_m�8M~3v}G�"�S�8������ ���Tw�ʑۧD�glq)�<r3v�����u��#p�ž�n��%��,�a!��^�4v{@P�(���}�Jg�7\$kv��
+���<7|뮶.��1�R*�����: ��zDQ��4��(�Ұ��i�c�U��]���?K�:^�zD��+Ȕt��̧2� ��I��qSr�p�#{/�B<Tc����WAPt7�š�s�l]��~������>IF`��+�=P����Gj��)�M���OE�O��Պ�.=mѦ�4TY������-l�8��2;gC8gC�� <qy�J����7"��Z��$�R� }�oԞ��e��Yk��� pқ2��U�dR��3���S6k[�>,&R)�O����ə�u��b���u,=���{�Pk�RYټS�-����Çdj]N飗Zw�&�� ��Щ�oh�B�]�>�a�i�?nr�o��ܭ@Ƶb��3W�&.|�?mK!ƀ �]sl��vl��q��t�h��L�u ��(����������ܴ�$��nFB�l�c�d�� �А�ͧ͸"�����?�]�^�������%���o��:����<%����*�3��; �gz���5��=C3�`�L��q��p'�~�2�T��79�W1��)�IM���+-��� z܃-���/��>�{��ק�f���!�>V[2uE�$J�]�){r��eDwVd&;���0�j��X=d�~��p�ٔ�5�W�3A2�\nj?�oA��h��^�v�{��-��}\�X 2�j��/DL��&���R�d�p[�`��@���6m�Pq��T��e�/��I�{oG���M���2�|�•�%���3��[�}�Ow5�̅�s�sU��>�]R��D���@�U�0 ��m�7�9��] �i�f���!z������<LbN��V L쵒w^��P�6y�m�Vp���i�o�pŧb�� i���8�ɍ�Y4��l<r"��9�Q�TvF��j:�T���N�ع�J��&�݉�8L5c��][k�-�Lf����B�_궰��>��������qD7T�*L3ƌ�x�̴����^Y�˕[_�)���8N�h}X�[l�D�)�.2���2K�@�*ǐᮔmæ��f�(�� +�i���ٲSR�af���@�ݦɢ; 䛷�6 �^�:�+̭���G�H�k��Jqw�xŝH�����=�2�����SHݻ:G�10Fץ)"!�:Յ#����\�=�8��K?��l��H][,�h$�>O�C[��\.��A��w�^)��ξ+�Qf 72C� Js��~� A�C������"��HeŌ��)%E���G/���1'�����a0�37�gp�y�N�H��0���^����.���a�J�Zm� sN��7��:�-�i�݋��>���|��r�>�`��Z�Y#^���i�WUբ7�2�� ���X���ɼ�<(�� �B������$� O[1����J���*,@�����9<�"�+B�ࣃa�A� )�p�AJ�*~���^���B��Y�?�w��z�8 �q�5��:gB�Go�M�\b�=�V�N�4�a(���a1��7�@+���D��>�L�X/��WF�&�/�@d�*�4�˛�T:ԙ�s��2Unj>�E��9
+��g�E���� ��3����@y�ֽT��Z��m>�g�2X���r�>5�˦m�"}]R�s��9���6γ�$R��mx�����f.��_V�EX����;Ec|ʢ|]�� e�� �U%r�p�it�Y�k� ��� &Ҹ/��L�'�5١�j?��k�$Nv�o��gW���j#� �.i�/N�{�7v]���GߔR�2Y�w�.d��!�S�Z�Ֆ�&���ٳ5��J��Mym��ij��F�l��{��Q�����D�N�<ŗ�ϻ��6M��dm>�_�����Յ
+endstream
+endobj
+171 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F206 92 0 R /F209 93 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] /XObject << /Im2 581 0 R >> >>
+endobj
+172 0 obj
+<< /A << /D (cite.douze2018link) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 476.44 637.196 487.698 645.45 ] /Subtype /Link /Type /Annot >>
+endobj
+173 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 543.385 515.407 554.828 526.78 ] /Subtype /Link /Type /Annot >>
+endobj
+174 0 obj
+<< /A << /D (cite.cui2022dvabatch) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 448.993 422.002 460.25 430.257 ] /Subtype /Link /Type /Annot >>
+endobj
+175 0 obj
+<< /A << /D (cite.zhu2024nanoflow) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 463.161 422.002 474.419 430.257 ] /Subtype /Link /Type /Annot >>
+endobj
+176 0 obj
+<< /A << /D (algorithm.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 436.407 371.945 442.939 383.133 ] /Subtype /Link /Type /Annot >>
+endobj
+177 0 obj
+<< /A << /D (subsection.4.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 485.163 217.166 503.648 227.716 ] /Subtype /Link /Type /Annot >>
+endobj
+178 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 434.556 158.989 445.813 167.243 ] /Subtype /Link /Type /Annot >>
+endobj
+179 0 obj
+<< /Filter /FlateDecode /Length 6041 >>
+stream
+xڽ\[s�D�~?��A�.��P�taa��0�N��b���[�֞�����7�2�T%�����-�Ju��˗9�Z]eW_�����W~�+qe�U!�4���b�꧟��%���*K���z���WRgi� \o����狛W�UyU�U.󫛻+��\ 4K�������f�?��z;�K�%r���_?z+a��"ͅ�1�73]%�2����̊�W�l6���M}����� ys3�SfR���,�Ҟ���*��*�V��yy�W:5YIkG �#K�J�
+�Q���^�fw�?�"I��Ȳ���796��\��ѽ�o;Z��W�W?�8�p�� ��d��z7����͋d�����(u������2*8"�O.����ݻv�⦺o��V!s�*a��K��9���*���n������1�^��ߚɵ�2�q�$'+W^6�I :/������٭���Te�jQ��4��3bߘ㡋�{� ��u�W�y��7 &<�?�}���T�F��{�f���b��}�v���Md���Q[?y�p U����� +�R�� ������Va���Z'%��L��͕�k��/g�<C�K�(�N��6(�f:��2�ܝ�\�ΟM�g�Rzꮦ��S����55 ��VÒd>�&�ϩ�D���˪F �%L\]����pJZ�3=� ��s�� tˇ�85K ��g�� �W2U�d�Y�D���fR�I����cHq��>��U�MFt�����X��o�rQ�X��yі&���L-�Hu����4�<C �y���H�5�f F�n�P�﷓\l!�i1��Ĺﴚ�#�B<WM�1� �-� �������4)��|)^o���~�r"fy:���&H��$]!�2�����٧����u*P'���!c͏�c�Oga�\�`����;(}Y�I��l���U�A�x�O�i�J)�q�+�9�LP����KPw�^����S{5�g��� � GX��ʓ�'��f�s�A�垷�����-�8)ϳ�9��9n-b��E�����cL����^±w�ä(��`�z1 [%h�m>�����[�'p�?�9�33���*��4 (d`쌘:b���k���:2:_�]8`����n(���5u>����HK�\�̂\��́�x�r�z ˃뫲bDq�����c���Gyl�
+���x�F� ���oF��`Z����K�}��oE�q�]{�@CUpP�����,����>i�����#�i��y�v}�[4g}v--H��g
+*��Bh�5��md}�I�_8��3���!��ד��� 9m�Ԁt?�9.Z�f�[��'#��]�EZ � u�����xw��/��y,|�w"�!�R�
+�MI���j�����`r�"5��}ȿ��O�倄��UD�ay�1m�J�� ��+O��^�o��y6��ݞ���lC-Դ�rFy�����A*�m�A�J?9� B<� 1h��h~0ea9�%�P��R�5w~^s�`��������Y��yN7W��j����8�#e �OKP�����`�� '��������J��~�e�
+5�sEq^wh�3�_^Mk�2��=b��g��|]|2��UU��ca'`Vqa�l��}���J˩Q<M��jף�����I�{g�*���1"�ۤ*0�'=�j�u6w \ g�ÀU�����M�K+��Z̀q���m�{�%�]� ��F0西O a��",#K�򂇈}�U[[����)am���$: ��������]<y���)^Xh��O�[I3�c��Ak+��Rs������؝uR��Zů�Rô��`Ģ�W��m��<�Y%���8��J���������s]��b������dI��a> �*L�*�N����M���R���E���vQ��B%44�۵==k�æ�t4>�����ܕ4s�,��ܺ��bo���Bt�l�^j��~ s۴/��.���.anԿ��Tm�t)5�� �t<��l�]&���aU�]�/K@��<��J�aS��Z�Y���ʉ��@�li��iq<؅�Ƃp����M���R-�b�� d5�������#�\�Ng��_�O�"<y�L'�]��������8w�+�u����NfW) ��X��������΂���;y�"=��J��Wp�7O��䁮�B ` '{�E�������%��5��c.k]����jb43�S�h��xw6�>��F�pAwHPת����hƅ��Ŵ�0�04�%��LG���x���гn��l�����.���-b%����k��a�"��c~�2�VͿxvOw/+��^R6�n�.IN��kZ� ���h/��-1-���Т"��׻�ު��� ~�K=;fc���u�M� ���FТ8f�R����cT�8ɻ�5����_���˗�dE�v�-��5 O��sò\_^tf�y�����
+'Z��HsQ@� ��a�}y\Я�K, S���s��b�%2'�wOOHB�ֶvԮvtMm%�8g{����}{���H��(��o�.J�,I���uG��'�����4K:�p�q� �3�_Q��� S�,]�������5����q��k
+��t�(Įo� ��t� !s��^�##{�U��$_/Z�xF����z�/0�K0�]�捵05�[R�����r2�ͬ0v���@N:�����z}�aH�[<��x8�|�;��n C ��c��|B߈�3u����B� �=VʂdS|r�H-G��&�{����D���e"�2��ȜQ=�)(:ǃG\�G�:t�暎������
+�‡�UpP��ifL�Tl]���nÅ� O�c
+�=�O� ,�R�~x���1��8��V�Z�]�[�XM n 9A=xH�0�Ƿ�徭���*�iX:�8kX��T�?�٤������#];��#�����j�{��� Ȳ[����L@�����Z�gT҄Bk4���st����A˃��aDP����2�U�$����b)��g�p� 7K��GwpG`g�޵��zHl"��3Kr\���C��8Kh["��B�<i�NwO�
+6Na��@uj��i��פA�y[�vm\Zm�ҳov���@ ]����1�t���Xà*�n,7e�ȯ�� �^���ws"9D�|��):z�ji�@H�*�����O૲LUΤob�'�<�,�K�&����~P�mG���� �3����'�ݶ;����2�<������C�b-2Ⱥ��)5��x+w�{V����C1�)�P:�PQ�XӸx���Xu� 8j�\X�9Ow��:�'棗��ۆ�zxǞ!��K�5z��������B��|z��7���Fk�R2t ���&�~ܲ�3�{j�C�VE�Zژ]�@s�zϯ����YfP�r��k6����~N��T)t�i���s���V��� �
+現E��`P�;��� ܓ-��}���}{k?4��>�f����V�3'�&���_v��!�$S"M#|(�@����z�~�<j� ��Z�1���F`0�cM9�"f���ҹ]N9�چ1i�
+)��7;xJM�r '��P ��J�2 ��zP@�,�
+�4Ǫ�Fj�����Ubg�_@r��p ��ȑ�f��J�^����O$�) n�2���U|�?�<��H5�o�QF�.\c����?���p᷎7ή]�-��$A
+�6C��o��]z�*�q��J�f�k��71�Y��_XiH�C(����}_߶V�l˶~7�o9>&�S�Ekjl�f�����=�l��g�2�u}���jKQõ +U�i��D�:z�l�6Ӻ%��v�c��:|u{\����rY6�S� B�g���t*��a��.3$���e�W�tw��]�@_�=M�֬��߷�q�� '�و����� �'>W����V�3��3f�ބ�8�pM�8).�� �A�X&d�Km!];G.�;=Ǿ�O�1:uZ���.�w'��v��0�����+��$�c]�v�j�w!��I�b�L��I�xHN�Q4�xφ/G1��c(��PJ���}�x�.�)�n8�y<}�K�p'��_usJ���҂Y����#gG.Ϸ.�s.T�BJSE���ә�,|��s�l|���6��0$hi����%n�"7S�|N{W���q�ޢFduc�yx:'t�t� ���ݖ�
+�"�Ը�@ѳ �OvL�ǖ��E�O�.���wnw.��80�A�R)����n���x�I�2D�?�u�G�>�v��i�|Ԗ�+ ��[Tm���q�sA�꾠+\���������z�F�b����I��K���%�*�ø�8: �-�� �T�^E�0��5�����e�0��~�
+F�h?t���*]p8@+1�܀7�F����� n �I֖��C-� ve��*�S�L1W�u8��2z��1��4j��]dv�|iW_��?�)Hr�n�|L��.eS�|\8��Ȇ�-�~7^�Wcܪ��?w����c�֤�mbT�,mbe��s���.j�� ���G0��9��J��A�%�/� ��^> 4ņ�Xz��jP� ��"��3��ͯ���/�3���E~z�B��7��3m�X{��t�Z��ZiLc��3|�#�0@���bfU��3^�� ��\�rɁ�$m;ΗzUUMG(� ?��Utҁrc t=�գ�B֜謳��v
+���]�����v�)L ��'��!ҷ=);9���j�:]?��8t�8�������O�����L��/���Li�9�*+�Ց�ćfP�T�9%�Q������KI�/]��Tc� �\TofJ��B'���z�x�f�e�\Ї7�i5�p�>P ��%��F�r�6���[}6NO/ ��\>�MO�VTd���8 ���,���.3e�qP&*�����A&'jk���^�����!`���!�ǫ1��Z�(��w�֧��j��]��c6k��."Uv ��l��p�XoFI��I&J��}ZO �Ž~�4O*T����=*;��P>������
+��;kFv�*̷n<4E�6t��2YV��F�fU ���Z{3dm���lJ�����{p�d�K��b��y��f�NJ�X��~��M�C]?���E��u�鋄� `J�ܕ��S��(95D88z����U5g|�}> פgN�Y�yg5���&��>���7����.���L�O��$���{9����"� ~ o�6q�^"Nt�d`���D� ���߲�����Y�D��魧�Uaci� �\$����Ui���C�p��u��-Gl�]�m]t����@�X_��g��P�4C���,���t
+�d�FP����tUNϲ�%V�+��OY{x�㬠�\�X��{a��}wf�
+,�EQ����^�hHV�h�.���*���;A��.����Lc����V��xH6�T]�0��YX+��[�7˸&_��� ���2�O?�d(�as���DQ��R9[7D
+�d��dG�z�K#ޅ|��� �ნ�~nT���\�˦���\���v�nl� v�uIE���E���Ĩ�R�.�WS�*�U%D� Lj8�;�~�v�,X�Ɨ���H#�)Muڣ�:-,���Eq,aC؈��~X��pje�#���N�IQ�ik�����<�]a��b���yP���� � c�`)(�s΁�+�����d��z�҉%��� v��Ȝ[���>��4æ}���CN�F��!7��z;i|P�Gu��'�*B(}�\$�D"�Dxׅ�rW0�8vݝR�Q1��s!D��a��`c��Y�hk!��e�|?ZV����PP�3�>�~��2R��z��N�}Է�vU��Ĝ�{�W/�xS�ۓD
+�(,'J,°V��I)M��G��g��x�ܭ2^T�a���Q��؝>����?���߃����a��R��爡��L( �6��?T���`�w��=��{�H,Gx�qP�V�*C�2�*�\��E�������4��
+endstream
+endobj
+180 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F293 579 0 R /F297 575 0 R /F301 576 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+181 0 obj
+<< /A << /D (algorithm.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 288.645 595.519 295.27 606.892 ] /Subtype /Link /Type /Annot >>
+endobj
+182 0 obj
+<< /A << /D (section.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 131.491 312.169 143.016 323.357 ] /Subtype /Link /Type /Annot >>
+endobj
+183 0 obj
+<< /A << /D (cite.severo2025lossless) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 69.279 266.585 80.537 274.839 ] /Subtype /Link /Type /Annot >>
+endobj
+184 0 obj
+<< /A << /D (Hfootnote.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 361.053 569.59 366.926 582.038 ] /Subtype /Link /Type /Annot >>
+endobj
+185 0 obj
+<< /A << /D (algorithm.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 551.727 386.711 558.343 397.9 ] /Subtype /Link /Type /Annot >>
+endobj
+186 0 obj
+<< /A << /D (Hfootnote.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 536.728 362.801 542.601 375.249 ] /Subtype /Link /Type /Annot >>
+endobj
+187 0 obj
+<< /A << /D (figure.caption.15) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 526.941 326.936 538.384 338.124 ] /Subtype /Link /Type /Annot >>
+endobj
+188 0 obj
+<< /A << /D (subsection.6.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 507.569 255.205 525.407 266.393 ] /Subtype /Link /Type /Annot >>
+endobj
+189 0 obj
+<< /A << /D (figure.caption.6) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 499.567 219.339 506.211 230.527 ] /Subtype /Link /Type /Annot >>
+endobj
+190 0 obj
+<< /A << /D (section*.5) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 443.925 159.563 450.643 170.751 ] /Subtype /Link /Type /Annot >>
+endobj
+191 0 obj
+<< /Filter /FlateDecode /Length 5910 >>
+stream
+xڽ\[��6�~��P�jk5�#�� ]��Nvgo��xN�!�G�K�"Rv&��t��(�N�=�H�F��N�x^d��_e���W~�_�jax�t�����~�h��"c�4���~!T�2���n��տ�<|x��^���Z����"�LK�f�/6��_잻c3l�w+�gKy���_?#���(�4W0����yK�����wŲ�[���i��x����}�>S�����]N-�Ë�_=LV��,�f�j ����d���J?� 3�b�K����� !S�e�,��������= �K{8 ����Y�
+�ҡ�86�M[�+b�l����<�+\ &E���}&�͗�D1���^<lk���/�{�����ǡY��5„֌ ����[T ���t�=�x]�+��,�����`y.����T�������_ꫜ��IS�S)X����1\qf
+��������a=4]Km�i�SgK<�0l�wp\�m��\e+.8��}v�<���騧�h� n�o^:�o�`�r��l�-�o6
+�G�n� +g������ E$�$!���v ��I)��{���O�ګB*Y
+e��R�#8H����{!�ܼ%B�N��X�(H�L_~O>ُ�`Z�m;X����u;T�N�����v���\��5��ύ'?�h�Ti��R̀�Yg�\�q]m�}�u�_���pIKJ�p�M�]ņVqQ)�EʂE��` � �z�i t3U*��o,��.2������� �.U�ғR�R��_�����2�s3@�<��w�Z2����</#��yZ�2��ȹ�$,�\]�����*eoU٬
+�� �F�A���(Y)����rr8? b�L��R:��|?7��"��"9e�-`Q��� ;A����29:W�����v;�)Թ��z��LU�B{���x�3ya�%_���Wv(�D�P�d2�d�;����\'Zoz�r6���̑RX+�z��-ꀗ~���7��4�%����v֞$���{��|��OQ�����%��� -�)�v�]_m�,�M�� �P W���&�[��/F�� ����� �ͯ�$ԍ� U"ex�Ud
+v*�
+�� ��3�4�sik�]��On��D���h��� ���"��۫�wvP*�W0FɌ����,�E�aU��<L+G��j{�U�����d��ѫ�'����ke)L�Wq]��3��2�l�,�E�v(�d��KvH���Q�g7��R��]~�f׻���Kk��W��۔5���l�*h�����k4�p����r`'����a̬WR��/9 �;��m�s��U����>I�^b����%��e:u[��%'�;��W�� �p��JfQ��>Y��-W-��)�:�ǂ�vc�F��>�~h�W�1ĵ@,4� e9w^ ��+O7,��ˍ����c�i�w%��B\R�?6���#$���W}g@�`���_]bd�D�$�ЋaK�ٞB��]�<d%a:�v�����e+���?��B�n��w�iwt�n�M�� e��,�L���L��l� ncT��MR��gΌW�W���Dۅ0Hj##�*J�5�e :=�����0�Y�ir����f�ϻ�bĪ��ϙ(#S�! �����˹���qj�/���S��!.=�pN��'0?��V������04�����Xv�?�3���k�x�|�LΨZ��7-'����7�"��pdT�u�c� t���pl6���cC��q�XB���ޭ@����N��`�%"J� ���v��v��UMr��Y�"=�j����]^.و��� �Q���Y��>˖o��T� �PS��x;O���'�V����
+�~��)�o�!ՅsH���Lj�n����,�cxG��z��nIC��業�`Y��c5���ep�'#���(�%A�HpR�v6�ޚL��� @vպ�& ��i������J/���p�1��^P�[��ȱ�K�� �O��HQΙ,Q���V��Ά�0��˿��7�Ps"=�?�_O�H��\���mp`�شn�T�)&eɔ0q.��� ���զ*z�A{ؽӳ{�)�WG�fRa�K&�-8Ʊ��2d�����<k���>��W%Gll"@�c����^���n冚��c�7)3���>�\��a� V�nnװ�œQ�lzz��d��h� Z&K��i/>[bwo��֖��� \&� � dcO=��~:9ֻ� ��L}�nI��h?R (JЀ`(,]�8`����w��j�OͦvM[w�G�n�L���B��5if�;4�]6�zZ�8C���)'���c?T��Xė�0�p��m]m5��f?+�<�C���C�i�\/� qm�~}l��;�B�S�G��/��8��О0y:U�SYL����'o�ប����� �:$���y��Z�`��u���J�P��Y�]�\��~�<M�-�+�=Qdr L�E: n��Nw��v�t�/�C�}�N���&azI���}�X�i�Њ6[�m��ո j�φ�C��v�O@/A!�C���Xc���"_NglFc_�{�P� ��j{z���a�4�۹L��w�s��0��'˃]�K�2� ��}̮۪��|�RÞ�=5���1�ܻ���S����m����� f(H�tmC��LJŲ����W-pyj_Op������gȻ�?�)B��>O�����ぜ{�+�=������
+���4. wOO��;R�p]{�q#��N^AN�/˸O�FR�&3�^G[d�*9�(�A��"6��=�T@��>��N�������N ԮR��� Yjk�J{V�鑷l�k��@�u �n+>A��M���O/n= {�7���P��)�2���( ���~ES;�x�Ka��h��~��[
+W��"�@xg�*�ݟ��:�-z?� �E����q��*$fc��;����Chܽ��կ�d���>N����*"@jƋ�8�A�`´Z#��اW�G?D�|�b�U
+ =i2"M(&��M�l1��a�5)���S�U[���n���=�d\8��ӱZ�L4��fd|s�OL��ƃ����z�� 0��h�,Ʋ�WAĈ\Y�)� |g�%���h\�۴��3"pvіr�����i{�ޯ�rv?���D��R��:���ձw� � �l����v6]?��r| f �O������'a3��ੳ �J��+��;+�
+�ߪp�F�3Sb���X7�1��+pd(Ϛ-�K�ȏs ��e/_v�����.+?�*�|��Q*e��:P��i�c�!�l��B��w��AY;|�x�X=6��g�}i����9�YL��U�����,>b0�:"T����~��OJ�.N��ʅu��0�q�+ƒc0AN��YJ��~��n���}���i4�� ��W�� ��L�dD�ۆ����` ��M;mȎ�0��v�c �\�������c��Ԇ�Y9e�F��v���`O,!8~s��X�F��۸��m< K�u�s8�T<��/gZ1P�J�
+���-h�}5����l�T�L�y�V1^Ƃ��q��Є� ʜ��@%h��GK�Z()S�e-4z%�������W��Vi�����]!��Q���W;WS:K�� ���ƲE�i�Z������r=�:.ћ�|���%�r�Њ~F7 nO����0Є� >�B��t�#Pe��?�H��}1��o{MKh@�)P}3Q�"��X���P ��Ҋ�7I�����<Q�4��2����<��WfJ,"a��xli��Ҋ�*cV���"����i��S����br,��� TU�E��P�8[K�D)nga�L$Y�bi%�ċ}c��PFK�L�%�|���,��j����դF��H��w>�0��DH}��J
+�ML�=C�E{ afC��T0R�"��j�ᅹ"@+D��F�5�N�Ĭq&l����DD3$��� �#"�W��u�8�lnUL����rP`��T�q����+�.y�
+λX��Ǻ�<����h��`X��#�8h�gW.n�������?\��W��]2jS������'��d�D��zœ���R3·)�/(����9ΉΝ�����#+���5�h�wF]&��5���^���+T� �I*�����o�s��4c�U�q�]}mc��hWxi�3<�� �0se�cQ�N�SܨFQ@��E:�^R�&�{�3fx:�~�����e:�q�����V�p[����^�%��]p�˲�lU�KĘT��� ���:%��1B2MMlv��WT/�IՈ�+.�H��g�e_���x���~X�i��u���e���Y����t|�\��56��/�yʸ���Q��*����M���ϿT%wU����ۥ��f��(��@����_Q ��/Q��z#��'_��&�5Q�q�s}�+���(���W�Z�^qy(�9�?�G�ӒP�V��rƥ)A3����gb��qf���}�'V��/)z��z�3�۠k���T�[��B�>�F_ұ=K���(��_-�V�6� #���l`��NAЛ��֛k��4H�R�'0��ރ%^%x����pe�K��R�>�a5��ҡ��I U��VI0 �3 y�(���-�L���i����G�S[���E~��B�,m��>� nc4%
+�t��%�2ͤ�^������T=�&4�6lc�Wl��!�a�*�?kI6�֕=�$���5�A4)��ј������1���lM@TN"OE��!�=�_��8 �D3 ��{;��dJ z}>d���'���*��5� ��^��'-y���}�"\?K�y��߾晋�|����o4�{�ݯ�.�����;�v�Z�������EP(�ي2ґ(�T�}�\K� ���2>��Tٰ1��=�T�c����98=(�Ԍ*���ӑ^���'P�+U/�=XH��q�=����� J�k�0���r{z���愙Nc��wצ�A��D_�Dх'�64��A���9<q 4���y~�#�f��`9Us_�C4M%�l��1��L�����世c:31���yt��d=a��}�}����(cYmRRr�\� ��R�~�V�I�"�a�k�аh�w��0�x��捇˅��#���`���m��/AȁV��5��v���U�� +M�;/M�a[��rL�F�ih ��S9H>V�B�z������{*��Ʃ�=����j��,�B�k"��Rd�u#cc����q�C��Ǎb�vܴPE�qkt�.�/�}ETKD _LC�|d� �,F�wZ!�� �b�]�sq��_�(�cl��+[���:T�<�������� y��A;8�MZ�-��b�.0|wOϬ.�G�G;3�y�����D4=��-�c:�ޥt �`�����k������$6��npYN�עo_��A�/8B� lg���Kx�J�MѕBze�: 9���1&~2,���g�p�)�����M�xi[Ͼ�L�YȚ�0���F(�y�q�^ �!������#8�w�{�a�G���Z��(мÉ�&Mo�#��~�|�Z��-� +��}�B͑K �6��' ��F^����̗P9�Z����hĹ
+(�OF��{"m�R�Pel�Su��1�(�;8<��6n��K2����z0j�"Z�ޣ�j֨p}�K�����c��a9��}qԘ���2HO���…A=��+�H��sUf���O�L�c?�e'��=�Lvb\E�@u,��"�N�d��Ə���NBv���6�4MN�'�Q�/� /��=ֺ�)�����r4VGlT�_���!*���eq�c���լ���}����ug%O��,��-��I�Z�L�p��*����[�
+endstream
+endobj
+192 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F293 579 0 R /F297 575 0 R /F301 576 0 R /F311 578 0 R /F357 582 0 R /F70 583 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] /XObject << /Im3 584 0 R >> >>
+endobj
+193 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 154.261 670.824 165.334 682.197 ] /Subtype /Link /Type /Annot >>
+endobj
+194 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 131.318 646.914 137.851 658.286 ] /Subtype /Link /Type /Annot >>
+endobj
+195 0 obj
+<< /A << /D (cite.munyampirwa2024down) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 142.054 613.375 153.312 621.539 ] /Subtype /Link /Type /Annot >>
+endobj
+196 0 obj
+<< /A << /D (cite.hmann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 155.581 613.285 166.839 621.539 ] /Subtype /Link /Type /Annot >>
+endobj
+197 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 284.985 599.093 291.518 610.466 ] /Subtype /Link /Type /Annot >>
+endobj
+198 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 282.653 539.318 293.939 550.506 ] /Subtype /Link /Type /Annot >>
+endobj
+199 0 obj
+<< /A << /D ([email protected]) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 80.732 503.452 91.805 514.824 ] /Subtype /Link /Type /Annot >>
+endobj
+200 0 obj
+<< /A << /D (subsection.6.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 194.264 333.052 212.426 344.37 ] /Subtype /Link /Type /Annot >>
+endobj
+201 0 obj
+<< /A << /D (subsection.6.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 99.748 285.515 117.91 296.549 ] /Subtype /Link /Type /Annot >>
+endobj
+202 0 obj
+<< /A << /D (subsection.6.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 237.511 261.321 255.673 272.639 ] /Subtype /Link /Type /Annot >>
+endobj
+203 0 obj
+<< /A << /D (cite.together2023redpajama) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 229.036 199.836 240.294 208.09 ] /Subtype /Link /Type /Annot >>
+endobj
+204 0 obj
+<< /A << /D (cite.izacard2021unsupervised) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 233.011 152.015 244.269 160.269 ] /Subtype /Link /Type /Annot >>
+endobj
+205 0 obj
+<< /A << /D (cite.together2023redpajama) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 407.387 683.352 418.645 691.607 ] /Subtype /Link /Type /Annot >>
+endobj
+206 0 obj
+<< /A << /D (table.caption.9) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 402.158 657.206 408.876 668.578 ] /Subtype /Link /Type /Annot >>
+endobj
+207 0 obj
+<< /A << /D (cite.shao2024scaling) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 508.485 659.442 519.742 667.696 ] /Subtype /Link /Type /Annot >>
+endobj
+208 0 obj
+<< /A << /D (cite.izacard2021unsupervised) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 504.942 635.532 516.2 643.786 ] /Subtype /Link /Type /Annot >>
+endobj
+209 0 obj
+<< /A << /D (cite.dubey2024llama) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 531.888 563.801 543.145 572.055 ] /Subtype /Link /Type /Annot >>
+endobj
+210 0 obj
+<< /A << /D (cite.kwiatkowski-etal-2019-natural) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 516.126 539.89 527.384 548.144 ] /Subtype /Link /Type /Annot >>
+endobj
+211 0 obj
+<< /A << /D (cite.joshi2017triviaqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 341.178 527.935 352.436 536.189 ] /Subtype /Link /Type /Annot >>
+endobj
+212 0 obj
+<< /A << /D (cite.rein2024gpqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 390.553 527.935 401.811 536.189 ] /Subtype /Link /Type /Annot >>
+endobj
+213 0 obj
+<< /A << /D (cite.yang2018hotpotqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 474.05 527.935 485.307 536.189 ] /Subtype /Link /Type /Annot >>
+endobj
+214 0 obj
+<< /A << /D (cite.g5.48xlarge) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 443.478 488.174 450.103 496.339 ] /Subtype /Link /Type /Annot >>
+endobj
+215 0 obj
+<< /A << /D (cite.mac) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 505.583 452.219 512.208 460.473 ] /Subtype /Link /Type /Annot >>
+endobj
+216 0 obj
+<< /A << /D (section.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 352.699 350.356 364.224 361.544 ] /Subtype /Link /Type /Annot >>
+endobj
+217 0 obj
+<< /A << /D (cite.pq) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 395.757 328.683 407.015 336.937 ] /Subtype /Link /Type /Annot >>
+endobj
+218 0 obj
+<< /A << /D (cite.schuhmann2021laion) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 410.419 328.683 421.677 336.937 ] /Subtype /Link /Type /Annot >>
+endobj
+219 0 obj
+<< /A << /D (cite.zhu) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 425.081 328.683 436.339 336.937 ] /Subtype /Link /Type /Annot >>
+endobj
+220 0 obj
+<< /A << /D (cite.asai2023self) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 533.022 304.862 539.647 313.026 ] /Subtype /Link /Type /Annot >>
+endobj
+221 0 obj
+<< /A << /D (cite.shao2024scaling) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 542.981 304.772 554.239 313.026 ] /Subtype /Link /Type /Annot >>
+endobj
+222 0 obj
+<< /A << /D (algorithm.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 488.225 123.208 494.901 134.58 ] /Subtype /Link /Type /Annot >>
+endobj
+223 0 obj
+<< /Filter /FlateDecode /Length 5587 >>
+stream
+xڥ\ms�6���_1�W���4\�dj����v�g�X�|H\W� ��y�� 9R����� ��pd���@���~�Jw�d��E¿/�_���L�"�s+���v!�Dd�2Y��UP��H�D��������Rju� 6j�j6E�����Eqm��o���~O�)YT�]Ut�$��4̺�s/����p5�fy����nf<1�6��$�4�f�n�Ou ��Qݸ�K��)��c̙Z�"�U�mW��Sʢj�ǧ�����IS��{�e�pM�&��y6�`fc!�j�b T�I���b�p��P�㊫m�Pw7P *L��ҋUS#ٳh�UM�����@owM������DS��)Y�
+em�A7�U�{��1�m�mx<!u�������3�hB�X����I�,��Hbc��0�����/��I��Z3w�(yRf�æږ�� �����
+�iw�����‘�s^�<�T��:����0�*&�|�:�� �tN|�<<���4����Wsw�t���d������;z���S����j7���qT��,:��C9�v&�������e ��
+��˧�LH8�&��l6�Yfs\�
+�T�N��SA���Cq���渾+��V'U
+u'U�'(5��d�����~�Igŕ�b�q��DaEB���X���ݽ/�G_ ��v g���
+YkXE� T̓�KL�3��_Ha�T� '6ǻ /�V5/}�^�d �(m���7MmI�+׭m�qw�v���$xZ訮�����ꨡr�Fuy��O�3 U���<�X[K:V9/�u,4KB|LaY�|����G����NG��Z�Ȇ�j��F+a��������I�p �vg�iM�i��@KGs�>�%<}��T�A��实�H=�����IKd�5s���R����Y�tHC�c �m�%�ѱ��� ���Cg�<���f�Mp�@��N_}���L�ɩ��X��� r��'D�W���&�����&O@2�F����C5�d���\@ϭ�(w�����A��a1��cZ;1����7� ��6��sN��4��b�M�����JDmuW;�!�m�>�$[��a��-�u�DY&��M~i�;��O(G��cfX�0�2I�`���I��eR��á*A�ܻ@e�Z`=^�<:�-�:�ѱWbdt��h5�d0;�~F��o���0�U����+�ﱻk����I��Z�@�\��i� :�# OU L�-/M�T��q�[��g� �w��ϩ��8�V���1>��Ab���v�����Ͷj7�xS���9�-u8�5|�� ���7����Y����H���6�|S�I���9p����3��� �`���@]0��^(�.����)�[=#
+�#y� ��"� �@u�$�`�����$T���l�Ƀb����b�;��jW��Z1�)��H{B�h�F� ��=�F�j��lj9F��9�`�i���*)����=�:�U��o��f� VŒ����73;�3 �������n����j�u
+4���ꮸ��n�XC�� M��~C�ܜ�Ia~�i�q��@e��#��?mY�W,��8��O�lm�8Oy�?4��'9kP���Z�+�w����kG��_"�����P��kwx�^�P���)������K°��&z��u�z��b+���J��\�b�:��K�pW�F֫�d� 5$�D�-weo.��y)'6c��6�%Q�a$�M���dy����mY�=:.��ҹ�X��{%��@YV펚����M�]�p�&�7�V��<� ��+ /�2 9��pw��� ;#D�#�$Y�A����s�1I�Wh`� 3#~r3LXe:^/��I`4�S���vI/{��+h{_��%�yԛp'����=��J���܆���)�Xh�Y�רN<�X4��`�{m�7�t:::�4��G��w�N���S��]�ln���eqΐ��C��L�@�*�%'� �*�F�a�U�z ����_��;�jl!O���lXۚ�2�d�'T�.P��0x�u��� �?S�F�K��X�Y"a���t���t��d�m�p�UnF�O��X�œ!����+vT b�#�$�1LD7���@�a���PW�� �H�Y��e}��l�at���3�������D���0޼^i��� B��ߪ^���O����E���X���ǒ{96��G����y=��r�̰���Z�ڤg�/������?Q�� ��D��F�=��z�e���<����P�+/j����f9K-����^�:U�FO�߁��Ĝ���W1�� �ϗZ}��mӓ_J8�U,XU�/��>����?^x:� �J ������o���!�+�҃k�[c`�����?Q�.��HD,�(�BA�9�G�Hm"U���q���MpvbIؠ�Nlb���s^[�ڷi��i2j�8w�F�����y�>Vs�Ln��o���n���q�RH���Q��x`T�DI��\eQjߐt
+�}�9�ǍU��H�1�Dz�������@�aP�[8M6a�J���Ԥ�+��r�����(c�w({��P��'�y�}�L�� :��x<R�]�\�u�,!B��e��Y���E���#�Oq��ﯮ�8l�͂o| ��}w��Z9�#��מ�?H'�[w����0"� ��� H� ��^_�qp�=r"�[�#(�]1�?#v�3[$)\�o���辟����Z�[&�i ���մ`��׋,�XĶ)��9S��f�S�t�4��0t$cW�9%i�]s�6�d�<f��2�'��Q�X����c�0�V� O���?�}��+��)��s.:L����o<9 ��:;|`��-̇
+D ��q�Z$�al{ϧw�N�[�@
+;d]ԛ�"�D�7/�D�e*���"�:[W�A,�}tlû�9�e�����P�U Xm��Q��E�*�,�<8�Ck�-5���xe�a�g����A?1�1��:4-����q� �� t��D�2��52���u�ޱ��Ŷ�[��"؄&�ޕd+��j�SaT`I�mqG�bNP^wJҝ��E����\�U�&��� ,C�y=圦і9�J�P�b��c�7�ѥ� ���9Xr������k1�J��8�_p���n��wlG�q�;�����H[dsvyv���e�u[�k(��O#���k��nᱞ:`L���vl�3�2U���0���`Q�t��d�~ɼ��L�b��IӔ��l��g����D���^R��Q������ r�p�~0~�]U�kq�3L�L��g�t4l� �^�~��P:z�ӯ)m��u�G�_p�����;y�8�[���E�eR}�}��=�#x ��x��!|�r:I�j���[�w�qx ��5�q��1L%�ǩk���nJ�3�\�2��|�-v�R�r)^.�z40�+0�ݛ��?F��F���=�# �j_�l���y�u}�.�;��[�۰��u��k���U�6��>�<
+1�9�؉9 �j���QEo��m64��@�N���T��O��\I
+Spx�)*q^�aR���=
+R��5*�Cu_-�YP�q�}��O2���kJ�d�y����/P�����5��`�y��A�c��F�X�<*��T��X�ǟ'*cay8`xI�rt"JJ� {޴�mWH�d���5Uw�K�����rN(d0߄��z�.Nm�-:t���-�)�0��ω~�of�_�~���*�D™^A{�u���޴�3gV��y�,�_��@�_������I)WQՃ��?���`A�:��>{��ݖ͉w�>ҷ�z�%<���(��[kgԘN��{h���b ��� �]�A���<�g��J�x�E���=I�'���ȃn*ή_�'q4m<� M��;� {��[<�<�>�m!���*��a d]mDf>g� i"�� 1ۇjv��>�qX�&�9/c�c8ا�7x|W��P��.b��h\��W�b��v��7���3EĀ�?�ӫo$� jFs�䘱���`��� �'�(#��v\ ߽-��2��q*(%哪����jϙ�)� ����NU���*ۖ<����TW���>��w�����!��]�S�߾9էA�i�)%�J]��$�W/�S�U�=����a��'(�F>��C� �@h�0�9W\{N�zD�,�;��� Z�n�@5z�I#� �T>h�uʹ]E���n�2�G}�h�"G�M�5U��tI5>�j����#Dl�
+T!�<s�B[
+C�Ki�TH�݁��
+βpr���(���Vs�5c>������s\��ƒ�x��Dr���$��a+���=6Q�s�2a�g���G8��apN����7��G�τ:k�+w�D)�������?ak�s���ҥIP2��K�!�c.
+>�Q:|�^��䳡��rSn{�ȧ���|���MH� ^l�n!�?�(�B=�K &:��}Qm���_�2�g��A���w��m%%ҹ�?�����7Tn�Ԩ�2?��@� Ղ���~נ~��,�<��d�\�},�$M�1Rs��ʸ ^��Y`�O����3��^ >U�q�z_�:N�уs,�O�~3�y9�W�ƒJg}Jf1�ہ�>����+����0xbz��d��uB�n(ػ��@S���Li�*A��d���Z�ݿ�y:v�6��y�Y?+k]�k0�:���wJ5�Uv
+��pE��V��ۭ48��t��ņυmJ� ��L�p � &�~�I0Z�y:!�Sw��R����>E;��C���2 ԡ>�5j�kTL���}ǎ���D)�^G.�yu0�T�G:����2@��Eն1�h�| ��폳�5���g�f�#����Z�|�$�㤐��d�'@��c��?1��,�=��K�g����b�S�I�'3��4Y�����튎���_���c$r�F��7�j��b�8�M�T�ꝯ-�T�3�Sj F|��j���%��a��cz�- ��@ �4��A���܌�� ���lN�B.�@�lWZ
+�I���{r�l�\�����)>KP����1Us�ޟtR�X�`C����)��� ��]����gǑ�UE������(Hm��.\�e:/��(��u����q�� 2b9&�7��I�ʾ�1���[zp還�E�17v�@��9[
+��X�(� �p`n|#��&�m�{N����| ��v�VO.���.ٯ�͐&|o�̂�/Ʋ���N@4����l�4�I�y���0Rq�eq�e�R�<�(�a'5�,,�Z��}s�.>U?,-�����̯�0Ez�L�t_�t�ɛ����sJ�,{;��^`6�m��Fګ���bj��n�%ŊSm�#�>���;<kA"��`=xÈ���L����o�z���m�]}n�_�v�������� _�7>����|�-�;�΀�T��#h��L"s<��S��J��sxa
+#o�%�N��U��/񧧉��#��J�|k������{Ѣ,�,�F��+��Wm|��4=���.�Y
+endstream
+endobj
+224 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R /F297 575 0 R /F70 583 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+225 0 obj
+<< /A << /D (table.caption.9) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 548.941 457.93 555.473 469.303 ] /Subtype /Link /Type /Annot >>
+endobj
+226 0 obj
+<< /A << /D (figure.caption.8) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 355.91 422.065 362.627 433.253 ] /Subtype /Link /Type /Annot >>
+endobj
+227 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 157.187 123.123 168.445 131.377 ] /Subtype /Link /Type /Annot >>
+endobj
+228 0 obj
+<< /A << /D (cite.aumuller2020ann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 155.807 111.258 162.432 119.422 ] /Subtype /Link /Type /Annot >>
+endobj
+229 0 obj
+<< /A << /D (cite.pineconeHNSW) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 164.248 111.168 175.506 119.422 ] /Subtype /Link /Type /Annot >>
+endobj
+230 0 obj
+<< /A << /D (cite.faissGuidelines) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 544.185 359.943 555.442 368.197 ] /Subtype /Link /Type /Annot >>
+endobj
+231 0 obj
+<< /A << /D (cite.ivf_crtpt:2023/1438) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 396.283 347.988 407.541 356.242 ] /Subtype /Link /Type /Annot >>
+endobj
+232 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 374.836 311.33 386.094 319.584 ] /Subtype /Link /Type /Annot >>
+endobj
+233 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 492.239 263.509 503.497 271.763 ] /Subtype /Link /Type /Annot >>
+endobj
+234 0 obj
+<< /A << /D (cite.seemakhupt2024edgerag) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 483.895 179.823 495.153 188.077 ] /Subtype /Link /Type /Annot >>
+endobj
+235 0 obj
+<< /A << /D (cite.pq) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 406.159 132.002 417.417 140.257 ] /Subtype /Link /Type /Annot >>
+endobj
+236 0 obj
+<< /A << /D (cite.msjimmy_bm25) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 356.321 96.137 367.579 104.391 ] /Subtype /Link /Type /Annot >>
+endobj
+237 0 obj
+<< /A << /D (cite.rekabsaz2021tripclick) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 369.485 96.137 380.743 104.391 ] /Subtype /Link /Type /Annot >>
+endobj
+238 0 obj
+<< /Filter /FlateDecode /Length 3720 >>
+stream
+x��Zmo�6��_a�p8�U�U���v�n��u�A�a7�� �-ג7�����CJ�,'�b�"���<3T2��%��Β�/��d�fJ�t��<g���쏳�+�컾e_� ���79��>{��1�9��T_]�}}��l�Ź�rvu3�9�%�3��XK>�Z��G��3h������ �b<K��/Yb�t���nJ�$��x��ԣ�P����D�d��L�������Gv���o�m���i���6��8����T�\���$.����<�J��'�����ۢ�R�esX��/zv& 3��Z��OE[n�����n�v_,�y�!���n���BE��C�ۭ�E�V�� ��Xf��ͺ���m-��h���ۥ[�� �����]���.�-����]�8&6���<�hWW+��2���窡v������=�~H�m�Pc�Of���,�Թ, [ A���#*տ<��ѫ�?�L�j�,��gz�{\cS���� m���}q�x���+u�x>ۢZ�4gf~��D��(&}��"K��������f��<(/�?�O@�G�8K�h�X��g�nK��Sat@E�Q�ݡ�-��eKmw�i�(�k���_#�O��U%kRZz{�T��\VF_KKj;���+G�:����)��;{P/��k�]��&���m�qf�q��x�_�����i��X�$�&E ���@ŬS{K?q ��Ǧ���
+���윺���X{��.�ŊZ�|�6X����h�rY����U]�{ڱUo��Z�В�w�E��YzM�k[m�&f�/���Ӹ�z�-���n�j��� '1>W5�vt4��U�^�Y,�fW����#��� �eAݟ:Bp�ٖ���K�ui�2�+��(����-=���q�_nh��Ɔv��Gu��'�N��c�w^K�8& �|�r���{�YZ'�mZ���d<0�T^#��@9��@6�E"�D�x-�b�v�<���{@���}����8u�z8��)��.p���'�a} �*_쫦vS���ן�����E�����vՋ��I�f��uFӚEM*K�7���8:(K�D_i��5����.���ͪ��rl�� ��s=� � �9�vg<���6<۰l�ڗ6:�N��AF-M`��'f6"�&{Ʌ��K`0s��9B���,IŻuX�"Q3��;`�>>4m��i�?<�^F�l����1���r�5q!�9 Z���y,VU^\��Q}�C�ؑ�U0�ʓ?_P�~e����r����ø�u�u��{B��C�� o+�Ж`Q B��%�%�M�Z5 �]��,�CcUݮʦ�1�p�ʆF�:�j<�>��q2�����h�8l�X�����y�P��.6�Hw�^MٷB�R?�G�.ݖے'=oH/�����'N��9gi�� �#W�e���w�3�@)�T<�����'��ǡ�iƲeZƉ�>�������b��+'2=Y�!2h/2i�"ב�D�w# vs�Î ��y�@Zg�єWN��)�R�(O@3�Nna�t�)?�v��n�i�{tn����Y�^K�[���:s�d��mWsFf4�w���'�f� ��A�ǡ��,��!a�h�q�(�ajX�А�D"�������"�q��v�)7���,��|u�.S2ֹ ��2�Y&�F4D�`Q����d�c�]UM���+����0�/�b-�b>�}^ZPJ�:�R�̡�bo�T2�L�����ӳ�����pQ~,�N,�B��/���V1�2�!��k�2Vp���k�1*n3�ܭm���&C[w�8���yH��i�7�gs���[OT)�i% rI� �f�.7H�C6��W�Z��I�E�>��y����{�[o6�hy�ƺ�� )����K/�>^L9E��<�5r�����<�g�ʺ(�7O2I���X'�tErJ��,�U�4���)���w����<# � 0:���\(���W���������[�q8����0Gts&$�a*Y���\����gO��#�N���.|٠A�[�\�Ƣ�0/r�����ȅuB:�4'�dsr���Gf!� ��a4�e҅���q|aB�*�H2x ��(��,8��,2���7&HF�]����4飑�і��T�!�d��vgo�z��2$uk��,�ٱKNx��9��� 4���h*z�y$p1�B�� t�GQ���Y�y�z�R��T%:�b��������#5虏�����IW� Q��I<^���V�.Gu&b�Z�H�� �J*@2�FQr�#|"�'\�S�n�2��<��\$0�}e��4)��3칼�<�Q.X��#�y��:V����닞���hL�`��1��a�Nñm��]��AT��9�� 9�V�\���v���W�b���#�Zl��_'�%^�`"f�v�f�!�@c=���UdBWgH�XJ ��ПN9����`��W߯\R�H(@6�f���W�/RY8�z���+�+��_�����^�~m�’(��� �;��9>( b�4�wH6͘
+���L )t2%�C���I��b�w�i�!WԽ_U�̵���3Rֺ��P������\������s� �LL@��أ!�u����|r���b:����E@���Ӵ��D,�S�o���$�����M��s�}��JU�� �e�����)�@�X�1�� #�7��b�FG3��7�J'c0��̜�Sm���v@W��(�f UJM��mK���*���hk���MK�w����Qޮݴ�~~y��n��=�Yru���w.���!td�$�7�X��y�%>�J������ M�1�|_�tz�j��Sb�@�*u.}Yn��q?H�=1�A3�}�j���N=�S%bu��p�� N*���.�?����)���@�i8�G�kP�`��&Ájj��ȗ<��N�5����M_LV��d��l�b�:}S_\�8v�`�5��3]���[�t9���twtf�K��R��2D�v����]�F��CCeX4my Ma�;+���)0�%2�*� �6 =���_wJ潱�u���<�4H,��UI��D��ԉA=�Y�L�%M��,�C�ɬ+�v��,����T9��V�e\�)�Ɠ��a(l{�h{?O�'�O`!����a��4�Ȫ��8̓ >��Wc���eܐ�ӓآ�E��U���ꅯ ���C�<j�����0E ����Œ.��s������� ���D��[.���;@
+�����\�� �Er"�� "��Ŵ���.�B_�, �:�����f4�#C��N@�G��q���@�D�G�����z��<�Id(G�(u���.�I�H� �ˤ,�����kF�,��4��[w"����#�rUz2���X��^��4���}N��b;�:6l���f �.h��= }E���!��r�y7('O�'4J��34�w+4�� ��0_��ߌ|co�ssK����d"b����s58IѣB�8#��c�����P�m͵�n�v�z�=��HE����d=�����XhH;�' ��=\�K��>� ��&4�d �v����h^ ��|�lJ҈O��>���1��&N6�rX�j�����J��1�/�dc�Kz� �*�i�Mga�p� &N�o `n��`��sh������O���q*C�mU;7���-�ƶ0�!�^�����y_l��tt} ٮ6�nP�k�vS+���`�0ad���fH`R�Qe���+�9O�L8��_o�oC�
+endstream
+endobj
+239 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R /F297 575 0 R /F70 583 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] /XObject << /Im4 585 0 R /Im5 586 0 R /Im6 587 0 R >> >>
+endobj
+240 0 obj
+<< /A << /D (figure.caption.7) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 69.469 691.746 76.001 702.934 ] /Subtype /Link /Type /Annot >>
+endobj
+241 0 obj
+<< /A << /D (subsection.2.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 275.967 643.925 293.967 655.113 ] /Subtype /Link /Type /Annot >>
+endobj
+242 0 obj
+<< /A << /D (figure.caption.7) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 287.622 608.06 294.34 619.432 ] /Subtype /Link /Type /Annot >>
+endobj
+243 0 obj
+<< /A << /D (table.caption.9) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 236.761 177.903 243.479 188.07 ] /Subtype /Link /Type /Annot >>
+endobj
+244 0 obj
+<< /A << /D (figure.caption.7) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 80.074 141.016 86.672 152.204 ] /Subtype /Link /Type /Annot >>
+endobj
+245 0 obj
+<< /A << /D (cite.wang2021comprehensive_survey) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 376.11 696.971 387.367 705.225 ] /Subtype /Link /Type /Annot >>
+endobj
+246 0 obj
+<< /A << /D (subsection.2.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 429.027 623.059 447.512 634.376 ] /Subtype /Link /Type /Annot >>
+endobj
+247 0 obj
+<< /A << /D (cite.ktransformers2025) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 396.909 577.509 408.166 585.674 ] /Subtype /Link /Type /Annot >>
+endobj
+248 0 obj
+<< /A << /D (cite.li2024svdqunat) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 411.914 577.42 423.172 585.674 ] /Subtype /Link /Type /Annot >>
+endobj
+249 0 obj
+<< /A << /D (cite.appleM1Ultra) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 413.606 529.689 424.864 537.853 ] /Subtype /Link /Type /Annot >>
+endobj
+250 0 obj
+<< /A << /D (cite.nvidiaA10) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 427.554 529.599 438.812 537.853 ] /Subtype /Link /Type /Annot >>
+endobj
+251 0 obj
+<< /A << /D (figure.caption.8) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 420.899 463.601 427.441 474.79 ] /Subtype /Link /Type /Annot >>
+endobj
+252 0 obj
+<< /A << /D (subsection.6.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 349.543 403.826 367.381 415.014 ] /Subtype /Link /Type /Annot >>
+endobj
+253 0 obj
+<< /A << /D (figure.caption.8) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 411.666 367.96 418.291 379.148 ] /Subtype /Link /Type /Annot >>
+endobj
+254 0 obj
+<< /A << /D (section.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 520.816 96.976 532.125 108.164 ] /Subtype /Link /Type /Annot >>
+endobj
+255 0 obj
+<< /Filter /FlateDecode /Length 5942 >>
+stream
+xڥ\[s�6�~�_᪭��U��񒷙��l������!�-�6���T&ί�nt)���Ԕ �F�׍�ӫ����ݫ��ܼ��[YW�(3�]��]Ys��T�:���^��dB]�e�����i��ʦɏu� =���a��}M�����7�P����_o���[��h�T��)��8fVZ����fc�m�vy�
+k�=��^=^M��yu��Z�41Ԙ'�*er8^I�׭#Z 5=�Th�����? M��[����v=t��0����&�p�+)Ҵ��/��� �;�G`�M���ɓ��� ���=w;z���z״5���~����#������
+z���0!*�#�B�E�?/Ta�����X0��j�j�U�l�%q
+*�v�ĝE�5�54��:O��M�/dK�3f�;~���]�xQd�ٖ��g���M聊csߴՎJ��#��ab�|��On����@���2�P9siR=����G�U4�����vWS�_A[&+��Oo��x��ۦߜ�JE��*�2�*����s%�L�aP��h�
+-=[OD
+�.o�j�� K~�I�I�~Fa�6$zP��~��תL^S���S�Eq�GE?=���m/<w�N�4�o}�)-t����� �8�`ɮˤ> �#��2�T@a���M :VTt��; ���� �2,(�DcA�&͉�QhJ兦��/�M� �of�wo�$W�����8�<�;A�O8J���D'��Џ���P�"=��z.���Yڲ�2�?4��I�a]�zU�2�SQ[A̹��_⧅MU���/����CŶ*\C� ��e�`��"��5�q�8Ώ�����yl��}�V�asd�F����,�er‡ B��n�~.�HNn�5�,���j V�6K*���*�4K���؃̞�& s&`�D/��7����C� ��Oa,��w�W��`����~��
+�d�u��۞�T�oњ�oA?�Ԧ�u�+���"��c��ut}l�6&�E[t�\���f`������Ֆt�����q����+
+oq���g��eӥ��Hz��g%X�/��љ3 �D�t��E�?�һ�����Q��t�/Q��T�R�>6�X���cU.rż�v�}�J&a%z�A)������m�n;צ��Ϟ��Ȭ��;1��� :|�|1=Ar\�
+VZ�g�,�z<VFx,|�)�
+���}��Ҕ�qR��ҩ�I7���>�Ƞ�����P���'�ɫ�{�]�T�,�R�mk��cw�WA�ҩ����ϱF%�~1k�Њ</^�esX��sx/6���I�($����nc�v,j�U[��� �~��런3R�#
+e,bY�^�k�6v���ho�R����ܞ�ñ
+{��v�� ��
+��{;Q�c�U�s᡹m<i;YRF&�� �`*@t�jt��P��+�e�s�6����߱��2��K;��Ec�s
+W������lX"�Tw��B7�@�U��R�:��� � �h�6�7��LI�����{��F�œ1m�a���$����
+tIG�l����=�/���th��+��S�eM��j��`f�iXځ1-
+|�M��nuD���'=�[7M�]_B��<�Cs_޼��U�����b��e��f���_ӫ-��ځB}��5�Ç�
+�>����x�fQ�S�"18�?.9�a�E&��N��zA�ʰ���%|\�U�w0�WTt�u}8��0l86����]3 ;aj�Œ.3Z
+U0�o�#-���ʲ�AGMN/:o�P��h�-o@xT�aG����mv��Q* �Cs���$ȓ�9�� =}���>�N��,�P�lM�k��0�*�s��ݿ����w�� Ԓ�N!��=�-�̠?dQ��B� L�j�����x= �� * ~8���~������KԲT�~7��P��6.Vp��ti�Qʳ��a�Jn0����b�@i�'g
+�4�>�>��؉�<U���� ���+�ᡰ3d�P�{# �P�H�{�s�������$j�%�n�Υ����ڛFoL@J}ȩgM��ܠ$�-�0Ɛ��4T޳�c��c?~ޛ�H�4(Sk�K;
+D!#�Eпt�=�-��a�x���_9����t�[�y4E�\d��]�c9�+z ��ׁc,^'��ľ�;��ڊ�d�d�� �g��jwrLf��8z����O���~�z�oξyj��@LJ|���(ak7�*�����,|���^g4�{�3�9���E�S�W��EK)r�-Se<i*q��p�y;�P�sAe�8<xK��殧ۜ9R�J��� �ٱ�
+�x��E{��HZ�΍��{�"�����Գs��:r[�U�%����)`�2�:��E��c8%�#��;�lB��C n!5��v�<��;7��1�C�'|�\�w��o��tL.��'��ᷢ'E ��rL5�4n��7�4����n����v�U�1�������/�9`�� Ao^�R�鹢���WQy�-X�p� d�.y��a� #XX���:�I�N�wn���� f�Y�_��o���S_���ˍ��z�C�*��a(�X<�nf�}�X(�fO�Ex����?��#�0 OUPß�s����P
+а_ܽ�����0�@"f]n�ӊ������w��}���SVqt:v��T�.�َ@q]t��z���Y�M<ܝ�*�'�C�,��P ?6�Ō<,�^��챂��Ȋ��=rHе�H��F��x��rp�����w�3����4�����YT�N��2�E��
+[�%`��F.�'ˎ0���D'T��@p�&R��УG�?�~�ߠ�ZϗN�P*0*@�<䚢�:�K+���woV����C ��چo�A��/�e���8��q���}‚#�нt��;����W�3�1�XO�T�|���m�~��ݱ%9t#R+���V͎�E~�7�<� �I� -��#Y<Êû�Q��E����ձ�@Hs��&2M�f?֥��8i�Й�g�V-�U[9���ۗ�A�J<�h@�ہ& q�! G*�r{_/Ũ�V¤��I�Sb%qHc,V窸��Ui�5�<B�w� �H�J���o*����A`lv�
+FN��$Z��4
+�vnn����e��Q9V��N��I�(��.������Tj��%�g�G�JϺđ� ��C�N�����Z ���"M�e�I����)�1j��/��Vɗ�"3��3W$#蕔�+��'V�i!��wqRF����c�&;�:����67���D<p5K�e&������D���*��>�
+�V��? ��l�e��m�Z-/l�s*
+�U�Lt�9�� O�����d���m�*�n���8q�x�pj�i���X/��%�Ԑ�DF��<����v�=(��a���cg��p�a����p���2���uZ5 1pl��XuFq�?���� ���ԃ?�9[�e�rͲ��9v_ʧY`��6Y�_W1��l������l����s!���w3;��1`�\N������08[7$.D��H�4�T���y �=� �I�K���p�ܘ�F��[n*�=ԝ�mO厷k�`a������s��p�.���|,Er��Xp�3\�D^*<,� � ��� ����+:~�a3�D���,SBIf�O��35�a��-acw{n0N2�~��$djrv(缱��}JR_!B�W�2>��TEi3���r�\�kG=P�4�����M}��>��16sʎ>"���b�q�{}ij9B_
+���s�w�N+��^մ�F���2:q��7o������1�-#?��$� �u!��s���ҟ�(�l� 0� t� '���U���첚�����X�`.��4��������=GFu⏖�=�&�y�bzE�+��޷�)/��Y�����~˖\�~��ڳI�o�n�����'�o8�Ϫ�T�Y��K?OS$>�9f�A�}����Ʒ��,�G�=���gZރ��~�/�:�D���#�IGE�`� �A�V��1��R^�:x>jm�|��!�D3?��6�G�/����h����yF�CX���x����s�� �܆��|b�o�~�鄴̂
+��y-���Gg�jH5h;��w��.�Qb��z;>Y��9�s�7�^^˔��qЁ?P]�� lv0"�Р���g;�I�K.R���]�ZM�y6�ʂJ� =肃��(��ݖ}Ÿ�6P=����.� S/��J���g3.\fbf^ʅ Z0`����cȑS��'Q�QWY����fEO!HZP�_���*ǼU��M=��9^�,��NE����7�}����yd4�����@���$�O�b��93޿
+b��6 `.�Ơ�A�� %�…��}���R%�� 4>6�i�ŢD��� Ў�[K��ٍ{s킓�� �U h�25>��#����_��ĂA� �K#��j�E��
+�Y��>\4�N:�o^^ (e̳�3[�Ipft�9�Q��Z��� ��6�K�e�Nw�$��8��) �՜����X�mS���W�L��&p��踈(�ЙR���@3
+���;�O1Q�2�D�;����m��e48�eP��k~ft��И�V��w��L?S v� >"�f�9e��}�j�0�)��ا1�9��sd'e�cb�R5�t��.�C��;�����Jϭ�,�/����V�de� G���\bv<�֡52��OYUN1�7a5�t���K�h�~ ޏ;Ӥ�-d�F��q ��y� ��OI).����s r�@h~����QJN#���"B�WsRCY����S.)7�=w��PPܜ�B��=f��u�P8SX�rOQ�p�7Bq<֥8C��d&�������'�>J��2_��Z\���Nt�� �63zAJ1]J�;<�B���a�hb�P�+�⻾!��%>�< T���ĥ=�YR�_�!�Z����j:s(GGZP�5�f\���
+<:~��%���(�X}�Wں����m�;��RPmM���T$����e���.S��ںX�s��"�[����19|��,(� ?��{�^h8C� ������1�MY�|��J��EK�� ��y�x_Sb��'@�.X�aV�x��$�/γ��g/,fSY�R� �T�Y8�s\��n�J�a%��,WPj�A�:ˡM�Il��n�h0�*S!���+����YH>Sǚ�*8��Z�LY���¾����B:t�]|�_�����T�,��h�G�i7��<̈́#:{LD]? ���u�yC�D�3~3Z�cИi��8�薠�D���T�8;�.C�>6s9uLS����:�BpJh�� �S��ƈύ�)7��Q�o1P�#j�m
+�ʩU�r�����9-���!kf�lh;���{�%��>X̯<`4gx�����r��E��҅ }4���/|j��n�s\g5;�[�7�x�E���`zf�+^�xx�QI+�rr��e�+��y� V���f��'L{+�� ��ʆ�fƲ��}��r&3����d'��g�m�1�J���wd7G��k�t��߳�gK {f���E'zN��r�z� �����]��ƿ�p�^�� �@gWZx� ��S����� ��Az�����;���P9u����*"
+��i��>ͥ�����Il��?��M��������atK��n��?�y��y�����?�Qb�2Bi&0f�ts|�o��8��tןQ�ir� Rp��"e`�􌌛� ��ͳO��#XN��oK�s)OyF/��Gz{������$Uh�s��l ,�����h�� A��9����p~9(m���� ��}���M�(���1#?�����1��Cz�+�����[ü>����g��Ycd`�-
+B� �mo�����sw>�$�����[5�))9f&�q&��@�xj�_6���I�/o^�p��{
+endstream
+endobj
+256 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+257 0 obj
+<< /A << /D (section.4) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 213.123 580.237 224.648 591.425 ] /Subtype /Link /Type /Annot >>
+endobj
+258 0 obj
+<< /A << /D (subsection.4.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 226.869 556.327 244.707 567.61 ] /Subtype /Link /Type /Annot >>
+endobj
+259 0 obj
+<< /A << /D (subsection.4.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 115.698 543.136 133.86 555.56 ] /Subtype /Link /Type /Annot >>
+endobj
+260 0 obj
+<< /A << /D (table.caption.9) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 164.221 352.353 170.897 363.541 ] /Subtype /Link /Type /Annot >>
+endobj
+261 0 obj
+<< /A << /D (subsection.4.1) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 277.432 268.334 295.27 279.522 ] /Subtype /Link /Type /Annot >>
+endobj
+262 0 obj
+<< /A << /D (figure.caption.11) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 175.522 85.021 182.184 96.209 ] /Subtype /Link /Type /Annot >>
+endobj
+263 0 obj
+<< /A << /D (figure.caption.11) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 489.4 541.947 495.97 553.135 ] /Subtype /Link /Type /Annot >>
+endobj
+264 0 obj
+<< /A << /D (table.caption.9) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 349.085 352.02 355.803 363.208 ] /Subtype /Link /Type /Annot >>
+endobj
+265 0 obj
+<< /A << /D (figure.caption.11) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 390.24 256.379 396.958 267.567 ] /Subtype /Link /Type /Annot >>
+endobj
+266 0 obj
+<< /A << /D (section.5) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 547.472 256.379 558.996 267.567 ] /Subtype /Link /Type /Annot >>
+endobj
+267 0 obj
+<< /A << /D (section.5) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 529.801 144.797 540.951 155.985 ] /Subtype /Link /Type /Annot >>
+endobj
+268 0 obj
+<< /A << /D (figure.caption.12) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 386.257 120.887 392.818 132.075 ] /Subtype /Link /Type /Annot >>
+endobj
+269 0 obj
+<< /A << /D (cite.skewmanohar2024parlayann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 471.409 75.303 482.667 83.557 ] /Subtype /Link /Type /Annot >>
+endobj
+270 0 obj
+<< /A << /D (cite.munyampirwa2024down) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 485.357 75.392 496.615 83.557 ] /Subtype /Link /Type /Annot >>
+endobj
+271 0 obj
+<< /A << /D (cite.hmann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 499.305 75.303 510.563 83.557 ] /Subtype /Link /Type /Annot >>
+endobj
+272 0 obj
+<< /Filter /FlateDecode /Length 4154 >>
+stream
+xڥ[K��6��W�Z�j�/>�'g���d���r�s�H�+����ɯ�nt�(J�Ԗ���g�u��t�zZ%�o_%�����J��^���y�W��?^ř�"�/��}�p�����W�����|� ��������߈"_q��tu��J�"W�"Labx�Wo�o��Σj��FEiLϷki�����ۆ�����y-��/ֿ����od"��!2�B�9�7N�vÉ�-���Zg�{Z����gz��w�2�]d���+'��N�冦iO}}���u�4�z4�����c�:��U��\?�7"�T������Ɛ�caV�����z�zkGy'U��� �����n�< e��,,?q�x�(�,�[8[ڕ}�U}��LԷTk���_���BW+�θ-�{��) �@mh23u-�><Jo}��ӌO�۟��D����b�Bή���8����k���nt����}r� /�R�Hv���%��d�(�A&� ��Í��x�;�þ���޿��-�"\��eǶ�_$���L�a۞�V;�?m�� �aß�hM�����A�����]���*�Е� \�p��卹[�'��� �(�n%Q��-^L����?�� �T���x*�u��k�y:̈́WI�t.O{�?��֝fqjR폡<Խ�6�Oe�t=��Z���f��-�:V���Suܱ�q'{ݡ0�_� ��ڡG��4&�h=CW7O�G�<��s�։^� =�׺�ʇ�L��������ų������񾄵 =�Vӗ秪��9��뒷�B����3�F�X��t[F����()�r|�2jH�˛�68
+�Y��GA�i��q��J�8c-? ` Db����.
+��ۏ� ~�%{�ҡn����D ���� ў맺)������J�,.{��B��[�bW�Y�Q]�O>-�C��C7^��p��z[�z�cQykK�@�.�|b�����IfwTUڅ��&��i<�
+ڋP�@���2�Ą��� vQ���Π������ù�a�Թl��n�8�Vt�\��gj�x��?Uðˢ�
+�;�Iơ�:� ��
+���:���eK�e�s!#i"���L�S
+�)]0{"�q��a�wR�͔�X�,��K/MU��d�.�D^1n*��e39ޑ��CF`
+""Qel�ol@��y�|��$tf��J¡2�~��%*���I�����q����L�D_'c��.��&�� [6O�d���4_x����{��P��a|Tu���S����*pU���@C��C��݇j,Pݤ�=���E�7�_;ئ9,�j=/Y)Dt4��Q9(0��q ^@/w� g��i���hQ��뵐SCo��sS�����N��;��[��L �H�T�`M�8�HI�����!" �0�/�c����kwN��S��hF�iGeT�qmIɷQ�� ,�.:[�����v���<�*\�m��Lm��S4W�_�����ނ�'T8�'hm*b�fA�;�mn9z[�wyf}^��?��p$'h�T��������`+�{\c0�I�Ž�X��Ա���2�K%��gaǘ�����k���c���wT�]�S�������F�� �3J����� ��y(�km)�P�Z��Z�p��<g��nm}H�8�2�3��,%vu~0����Ѩ�����!"�q��&��?� �����0]�-C>��,kd���8vY��N#�y�3| �ȝ�x}M�}{���c@����K��Z��ȋ��R��'��C_��\ЂE���+m�'9 E���!P�����.K�wB/i�d
+K�A"�Id���i���'+������4��h
+b�y��)�t���|�g�3.���gX��E/�6��h�ƑAP�a�x!��S�%�;��
+�[ڌ hG �}�S�8t\��|n`+P�1v�LQ����C=��6n��w��<Vi�q_�*�)w&STVD�ުG��R'/
+޳�཈��q������e�9���ݦo7��{�0J �<p����b�vTq�7�<�I���a|=�ޓY���ٙ٘��?��R�Y���ə�2J�v���}��7��Wx��j \�� �H0��(��)��=V1 �� �y"�gbHL�#΄��'F�H��O��P�� �f�o.���#��pu�(������ka�Fl�����Do8��"�3u� �G�܍�t!d�d�}�? �䜠� ���XJ���z��A�l�{�9?&���<jf�,��R�|*BB��8�l�/UE��-��55��%{ ��1D�\[�p�X�]������'9�B�� �0��[��ņ�������ݰ�V]�8��o��U$E���w��Q\>O��(o�Y��1���#-HA�$�z���b�zG�������.v��Xw��5�R��G�[�ǵ��,��\�6h}X4���s{`h6�T���D &VIO�*E���ѻs
+e_�l :y��'����y_,�_��Ot��,\b�`Z��/�9Qn��^�$)����R�W� cO@Г �Ȫ���{x��c6�I>cH{ ���zH���+,��=U�5�� �2����A*<�/R�No�l_���Fk1�͂iPԒE ��9���>��B�9���pw�� 1G�eR���m�|�/<w��Y׺�f�Ư`�.�]NL��D�a;��\��*���̠:�>jШyk&'r~��vq�A��H��E�ٗ����v��u�_2c!-X�xΖ9%�<��0�S�$H?$z�Pv��G'�7AWO�(r���B���� �`�9 �9���9,���T0�gmJ;�N
+�g'�M���W]6,�&2
+�=o�ܜ<7�8��e�Ơ������M���I�xDܻ�=���dc�>R��a[]� �@%bm2?i�c���K��������3��<|⭾�Q��a���U!~I{���-_wx��Ë6�F>�r_\2w�,6:sQuf��RAѫ5������ʈ�d`\��c���}�b�fYs�1K���n
+�����3Jb{�ޏ?S�O�7��M����~�}:�P5O����L��U�*�������G ��9� ��&&���u[o0)� ź]�W�͕�O?��*y� . V�sH�Y�?�z2�DA^po2���AHCkH�g�̜�P�Q�C7��������%4����16�cʧ
+I��xa��,�+��0
+S��<���<T��T��O_���P.e)� �N���}��O�$��|8T~�ߣ$|{)���>����)��h�Nu����4�%i�9��9/#dƴ���я�v�<W@�O?�k��`2���Eg1��3=m�SW�'>ѠA��0�u3y���#SA���8�ͅ���oq�:ձa���8Q&�Ȃnds��"���_(�0�q�l~~ڍ� �K�I��W�=��뙆��8�����$>M��'X�og�T��7���ǹ
+����$�_׹�X^���ӧǓ0ƞA*Q����;��E/�O�1a�DE��������
+��X;�ʮ���k<dIt-Q�=b�k0��ί�����P�1pTCa�tz?~�k�W����Nu0��:U�Gs�^�>\�]u� ���t,1�yk��zt�e�\�΋�ѱ� *bp�b#f?LƷP��*�%R�B~�-7S�8%��z�ɸ㖸�<��z�l��Q�����<m�a�dZ{�V ��)����I����o�R�f��jt��s�C�MA�# ,�n��k,L�F�X?5Aʶ��� �;E+��G/�ٻ���]"��`CE(
+� �>+�t�i��Qp&�Lj~��VQ�H �x�̧}C̝�:T�(� �C}M��d�2vS�%St3;��$]OB��78N��]��h��7#X�Q���?x�X�nԎRW��ɼ]K�޵�J��U֜b�0�m�)6��s��['�?~EA?�
+�,���#�i��UA��<B�3�>in�Kok��o���S�4��{��j�QH�)���%=�;�f7���_��OȕP�.̺��w���{�`~�v����w�1��]�H�7��k�u7��o!�O.��L�h�6HF�n��@c�C�2 �|}������
+endstream
+endobj
+273 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] /XObject << /Im7 588 0 R /Im8 589 0 R /Im9 590 0 R >> >>
+endobj
+274 0 obj
+<< /A << /D (figure.caption.15) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 161.693 463.601 173.137 474.789 ] /Subtype /Link /Type /Annot >>
+endobj
+275 0 obj
+<< /A << /D (subsection.6.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 191.011 427.736 209.172 439.108 ] /Subtype /Link /Type /Annot >>
+endobj
+276 0 obj
+<< /A << /D (cite.li2023towardsgte) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 128.603 418.017 139.861 426.271 ] /Subtype /Link /Type /Annot >>
+endobj
+277 0 obj
+<< /A << /D (figure.caption.13) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 287.895 391.87 294.427 403.058 ] /Subtype /Link /Type /Annot >>
+endobj
+278 0 obj
+<< /A << /D (section.3) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 236.477 316.134 247.983 327.609 ] /Subtype /Link /Type /Annot >>
+endobj
+279 0 obj
+<< /A << /D (figure.caption.15) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 254.783 168.707 266.041 180.162 ] /Subtype /Link /Type /Annot >>
+endobj
+280 0 obj
+<< /A << /D (subsection.4.2) /S /GoTo >> /Border [ 0 0 0 ] /C [ 1 0 0 ] /H /I /Rect [ 196.347 120.887 214.832 132.075 ] /Subtype /Link /Type /Annot >>
+endobj
+281 0 obj
+<< /A << /D (cite.ivf) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 407.958 182.899 419.216 191.153 ] /Subtype /Link /Type /Annot >>
+endobj
+282 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 523.634 182.899 534.892 191.153 ] /Subtype /Link /Type /Annot >>
+endobj
+283 0 obj
+<< /A << /D (cite.hnsw) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 500.509 158.989 511.767 167.243 ] /Subtype /Link /Type /Annot >>
+endobj
+284 0 obj
+<< /A << /D (cite.nsg) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 543.021 159.078 554.279 167.243 ] /Subtype /Link /Type /Annot >>
+endobj
+285 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 355.869 147.034 367.127 155.288 ] /Subtype /Link /Type /Annot >>
+endobj
+286 0 obj
+<< /A << /D (cite.sptag) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 422.973 147.034 429.599 155.288 ] /Subtype /Link /Type /Annot >>
+endobj
+287 0 obj
+<< /A << /D (cite.nssg) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 432.316 147.034 443.573 155.288 ] /Subtype /Link /Type /Annot >>
+endobj
+288 0 obj
+<< /A << /D (cite.hcnng) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 446.29 147.123 457.548 155.288 ] /Subtype /Link /Type /Annot >>
+endobj
+289 0 obj
+<< /A << /D (cite.wang2021comprehensive_survey) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 495.712 111.168 506.97 119.422 ] /Subtype /Link /Type /Annot >>
+endobj
+290 0 obj
+<< /A << /D (cite.baranchuk2019towards) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 357.883 87.258 364.508 95.512 ] /Subtype /Link /Type /Annot >>
+endobj
+291 0 obj
+<< /A << /D (cite.zhang2020learning) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 366.805 87.258 378.063 95.512 ] /Subtype /Link /Type /Annot >>
+endobj
+292 0 obj
+<< /Filter /FlateDecode /Length 4162 >>
+stream
+xڥZK�����W��*le c�\��bK�˱��}�t���i�j���=��`A�6)Պ�<{z��u7��f�-^=�&���bat�ebau��&_�v��x��B+��h������w"[|��3����䥗���y��KQ�"-�Ջ���Ҧ�� +�Td��f��=y���JȤ�q���_����y��)��h�s�Z����������I��;��҃����?rR)��;s�%��3g-L��C5�����6,a��8s)�<U�^,�J-�Vx�lNǫ"����dI�¯.�߯�N�߶���;�z3���W"O�}s&켼�"5NP"��T��:ly��"��W?]-��z��5.� *rɅ)qi x W�n݊���[�O��ڶ>�K��^fx�<Y��nC���k�[|œ��Ǫ=����륣,K�" ,/SSX"l�=upt�����=�(���S�4Z6��V��y�,��
+g��4�S}�����Ͱ�g8���< /��K�����_A�f�-8�,U�bML��K�ϭ��06O��K��{�x��h/�4��AN��nhYdX&a�iU��֞��ѭ�!%Ƙ��L�]3l��'�dUy��Xm��`æj�a�[�4��q�q������Q�(�6#=�| с@�2-.��_���&kd���^�@m�L������7�}:��筥*Se�x�7M��i�Ox8���Đ� Q�i�$u)L�d���aAu��@�r����θ����5� ^.�"���р]�����i K4C��i��,w�nR���v
+�p,��eR��Z���Ɛ��,>,��>[��� ]8��h�L�\ӪwD<v�?�LGjGc��вip�x���E��,Kf�O��gi�*y�?�C;Z-#�a� Cn��Z�� E&H�&S�� ^cV�]]�J[�Ɣ��#���u��&�A��r���>�ՊmI!��c�i:81I���X��2&m��c�l;.�Ռ�X
+�B�:��9e!���.ձ��p۽s�nĩ]G�}�<�zo��m*�B�xԐ�/�,i��vp…s�AS����2���������O0N,�Ԃ�&GV[B��C��K�S)�xIe�c�$U��5�w״�ݶq.�U�A��(���w�R�oW
+��&�S0,g� �M�|��U��SF�˧�O���5�ӎ�9����C�W�I�D�p�D�`(`�W ��>0��m�E�A��;�&^3�=�7]���b�S�.�/'���$4M�JT�RiU�JrK�?��Jn<Q�9l�� #t�f�īV����(S4�Zm�Ʃ'B*�Py�{��-$�$;�"꼌g��R?��6i1�H�9zn#g' z �1@bJ�6��Ͼ�}�a��2�|*`�s�|ۦe3���n�����84�U��a~U��u��j�4<:PW8�2���� �����۪�ۦsQ�ʛm�3��n�$���'�p�L�g��Jf�/���#�*� {����cS��\`��=7ҡ� V�al����eR��5��e���HZ��܃�x��m����4ݮE0�l�����%H�Փu]N�W]�����Or��9|5�g״�ݶ��}��?e4_0��j�ܑ ٳ_�z��"��(ˇ�\�3�!��p�z<<.}3�!��C\����M������[_���(q�B;�j���A�7i�F�������m�j�����O� ��� �C��h�{nOM�v������% ��:#�ؾ��?�L؀8���y��E�x}7Iw�;��&☛P ���jI, q~GR�e�Gc�!'�4K�$mR ��>|��h��J����<�֫s�p���,��������+j��E�����f.�?/}2�ojw��f\^�*�� ,y����wZ�E6�qɻF[�{vr
+���
+�q��{]p��^V=�k���M!���XQI�k�6 c�����C������/�ω�*��:�"-�J��������qC�74��Zӓŀ�������"���w^�F
+#)U�\���M֡�r�s��b���UhӲds��%:t�
+Ђ+�8}�C�;�1�� �Q�9� �`J� �$��mϪ��|,�Q���P�A�R`8j~j)P� n�����ʱ~��E R����h}b����[:��]��m�ۖG��꜋�M4 6�q��W�X"�����-�
+߼��/ϟviv�9� �U��k��vU��iZ�Ճ�{4�\�-�� 2�1F�S�N�vO��%x�u
+7�砩���i| Xg���j����h�E�<�(-Ma�n�ӘA
+!��E*�Om�D$EN+*#�-�Q6u�@i·�g��(ϕ��� ��n��~.�%����������ƽ��8�l �z�Ŧ���rP#{��k�!��!0�M;@�C[��v��(�:����R�ټ�]S�Kn�/ �ձGX������h���A.
+�;��l������97�|`+�Le�<�� G9?�Lr�:�8��z`�n�,����5�h5Ft=�Ǻ ��]�<βTI�1֜� 5�u�Yt~uy� ��H�@1XG� ��;�Һ��f�W�|P�E�*� j:�Xd�r���">��8R �}�f�'7%pG�Q������[�܋:G�_cįܦZ��"=.���쒝̩������f�<����D���b�LW���#@^��p7���
+��x��+/Vp���`���;���3t�Ғ�ư�j�t�ii�+��7�7��F�R+,5��c(x$ �W�.{r�#�xVk|�|w@�E)N���5e6A��A jAj�Q�l�ԗ���9GUȧ4��
+�Y�'���*_aTɧ%���iPƕϖ`�c�ż�&�jc��?%p�k����.3��`l�yC�e`�'5�1�М�.��Z�WwA��zX��50��:��O7�v�M[����g��:��O�8e1�U��Y�5�?^�8�����h\`>Gr �P����(-�&���U�*�M��\��V� o�N���>�G�x�Q�cz��@%�Tg�Ǐ�q�C����c���_�T�-D��0��y��-��]0������"��i�0����X��d�d�R��AIVv�[m�}]S�p�SG�M�sR���W����Ef}~�� /���T�$�)r���f��6��?T]7r����u%��o�"��7�I��W���a?]9�4���jJ�.S��LŸ��9�6b����p!�q$�츤���3�ڰ�A��m���!n�>!��U^�z۔\��33ۺ�x�i��y� ��3�
+����p��0��?�E���;i���WV9�!�\�8��*2\�B�y*��p�]櫺Cv �ɯtnb�B��Z�+ �fV��Êe��+��zx%5k�U&�Sm� RI�0&���%�H`�l�n6��|���x�ɯ/����_�6S��wxxQ�RF��ѾԭLF���1�=�:��Ӏ'Rh ��bRDaq�B�TZ�6&1�pʛ����\H�=�X���v���s[�g}&C�}�ҧR��� ?j�_�8�Z�(*׳��U �c%-� �m���A������r�␿���7jy�md`d3�3s#�pu��}|�Hy*Z;�,)�g0*��Xb
+<�C7 ��>~ECY����-O�S�v��)R��[�(���w��gA���`�?�%�$y�~q�- @2~��A���!��{j��<����L�5���'\����>��uQ����V\D��KF<J]�2/�"]����{���4E�Ma�ӕ��P�3�C��Tu�jeB�3 a��Y�r�� d6n�zLNIE�+��P�#},��W�����%��ŝQ:����;D|x�i�tdT��&���+� 58�ƪA͈#�4����q=OՖIV�dY��������'y�w\d���0 =�nw�C��⯧$�?LdH$gʔF��g9�ς1� ���؅��k�����t��.̉���d�tY��*\�!�G,DBD��h��]M0\bZ�w�s�zy4ܙdh�}�,]��b� }c�_�*��YxD�^�V."�D3����^\��_����?��r�Y�9]�!bo+@ڰ�<q�J�؂��ǜ�]e�xT��D^�<�/��M�
+endstream
+endobj
+293 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F206 92 0 R /F209 93 0 R /F212 94 0 R /F70 583 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] /XObject << /Im10 591 0 R /Im11 592 0 R /Im12 593 0 R /Im13 594 0 R >> >>
+endobj
+294 0 obj
+<< /A << /D (cite.diskann) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 280.166 685.016 291.423 693.27 ] /Subtype /Link /Type /Annot >>
+endobj
+295 0 obj
+<< /A << /D (cite.wang2024starling_sigmod) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 75.624 649.151 86.881 657.405 ] /Subtype /Link /Type /Annot >>
+endobj
+296 0 obj
+<< /A << /D (cite.fast25) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 133.353 637.196 144.611 645.45 ] /Subtype /Link /Type /Annot >>
+endobj
+297 0 obj
+<< /A << /D (cite.tatsuno2024aisaq_gps_ref46) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 279.742 625.24 291 633.494 ] /Subtype /Link /Type /Annot >>
+endobj
+298 0 obj
+<< /A << /D (cite.LM-DiskANN) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 115.668 613.285 126.926 621.539 ] /Subtype /Link /Type /Annot >>
+endobj
+299 0 obj
+<< /A << /D (cite.seemakhupt2024edgerag) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 280.29 601.33 291.548 609.584 ] /Subtype /Link /Type /Annot >>
+endobj
+300 0 obj
+<< /A << /D (cite.pq) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 243.921 517.644 255.179 525.898 ] /Subtype /Link /Type /Annot >>
+endobj
+301 0 obj
+<< /A << /D (cite.gao2024rabitq_gps_ref15) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 170.627 505.689 181.885 513.943 ] /Subtype /Link /Type /Annot >>
+endobj
+302 0 obj
+<< /A << /D (cite.work-in-progress) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 236.776 374.182 248.034 382.436 ] /Subtype /Link /Type /Annot >>
+endobj
+303 0 obj
+<< /A << /D (cite.ryan2024enronqa) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 251.005 374.182 262.263 382.436 ] /Subtype /Link /Type /Annot >>
+endobj
+304 0 obj
+<< /A << /D (cite.wang2024mememo) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 265.235 374.182 276.493 382.436 ] /Subtype /Link /Type /Annot >>
+endobj
+305 0 obj
+<< /A << /D (cite.zerhoudi2024personarag) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 279.464 374.182 290.722 382.436 ] /Subtype /Link /Type /Annot >>
+endobj
+306 0 obj
+<< /A << /D (cite.yin2024devicers) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 215.298 362.227 226.556 370.481 ] /Subtype /Link /Type /Annot >>
+endobj
+307 0 obj
+<< /A << /D (cite.snap_cvpr2023_tutorial) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 69.987 314.406 81.244 322.66 ] /Subtype /Link /Type /Annot >>
+endobj
+308 0 obj
+<< /A << /D (cite.nvidia2024blackwell) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 541.775 411.465 553.033 419.63 ] /Subtype /Link /Type /Annot >>
+endobj
+309 0 obj
+<< /A << /D (cite.nvidiaA10) /S /GoTo >> /Border [ 0 0 0 ] /C [ 0 1 0 ] /H /I /Rect [ 495.356 399.421 506.613 407.675 ] /Subtype /Link /Type /Annot >>
+endobj
+310 0 obj
+<< /Filter /FlateDecode /Length 5314 >>
+stream
+xڥ[K�㶱�ϯ�]�s$� >�c�#}��3;�$�`Kl��)Jɞt~}�P��ܴ�"�d�P��
+��fw�||����7�}�yv��<�����)��E7�&Q0�nR�H�7w���-����?/�Ŧ\�pl��\TM�\���r�"��e�f H��\�řƿ��}l/��w��݇8��_�U&�D�?��?����o�u���>h�M�g"�bz��x�p�2�}�L�*��� ]�R�d����~�3�}I����f�Bw�8�؝�U�����>��lf)�!c^Uwd�sl�]�>��v`�Z��q,6�������遢|����~�M$��oB����q�Oo���Ϥ�I<&�����F��0o4�ޭ9R��S-d����-�b�-��0rO݁y0�����Rcw.N<��tVK�vl���Y��0��s�����ܞ$��%/�j���6z�9N��aG`�<�4���]K7���h��jWtձ4�+γba"z�P o����4��}u�2#�̌���w+Z�ѱ�����~�F��H�MU6��+�rM���%��ڝkWv�{� W"Qhg2���(���`�� .�} �q�J�WrC*-��=�cv�H ����{�r�5rA������t��v��2_0�^�����j��k�M� Pҗ6dQp:HR�9A�i��ےhc����e�/V����rm��_���!I:��>�{�G�<�
+�����v �g��j��Te��$�U>�و����W�n�Z!asފ����-����A�r$f�N�\h�������x�=}��?�k@����:T�$3�/�}y�g�ѷŮ���B۷��`��F��Z:���b����݉M�s&ID�Y�Р���j�������b��# �Ogɘjc.��{n`�GxW��3 Sɘ�EM�u��xbp �SI��pݕ X�����1N#�挲I3a��F��Vɽ�hh�/�_>�>�W��A�������q�yi�Ŋ�V=�vU]�P���Lc�?x"#P�$¤�9ע骢čd:ޘ��ea%I����u������uE�P�.���K�f�Ωl��J����t�[y���u#�n0|x�n$ܩ:~x ne׬�9 ��'K��ѡh6��@ӌ����mK�L['[�ۀMQ�^� ��N��q!�ݞZ=������4݅�����O�����^�H����`y܍E��Ѐ�� ����E �N�zvJc��:�'3��������ڝ�H�h<�_��=D�[?����g��9؎�q~i��j�[BBt0z��ɲ�90:u��T��4��a�y R�Mݞ6����z*���x�����ZǕJФ��cu�<���e���L�8�+�~h-�93���h9�I�;����t�E�5㴪��Xm`�Rv��Z�zh��L=�}�m����F٭�[�r�����ݮ.gl��b�X��h/Ce���+ ���� X��BX�e��A�቎L(ha���:)S̗]ٵ�foz���@��v,i?�' c�"th�Ȼ�6k��6&y���gL�6��� � -��c�2lx��C����!Y���x>��+�adꬽ�:����:r,���%9�g��wvJ��q2��Ҍ����/kth��\\ Bh7* L%�C���q`�x�,� �E4�q�y�- �mc�= ���':VBJE��e��C|K��&Fr���N5��Zˠ���{K��M�'SB�m�&c*~j�~�vN�m]��sk�s����!.Hӹz�Z_n��ͭk]� �E�|���KSy.���+�x /��ֵ����tO������b�p ��ł�.X2V0��h��G�R.��6��:;
+���B�.�]O�z2ie͓�y�+c���X� #[;s�г̰"5�j6"F�[C'����$���� �m���[�E4�Z߫R���_��UP�x���4� �F�0��7�R����cp}�w$��o�< ���M��:�|3�7��r�Ɠo� '�y`%�r��Y�B�����!Y4�^�ͫ�11��qn�$�`�SC�m���{����6�*��|v��t�=+#�rIa��)O�C�V �֕����u�8���+e�>Vޱ��XutV%4+*�T�dM7
+!��!f��(�nS�e��� |��j�)Q��{}?�K��Th���`���GFk�%��:�r�V������o+����5��Jzh�u�H�H�<-�����ej�.s����eD�?��i s��s=�2'�r���
+�?f`N��a��$]w��$�W�,\48|)�ޠ;���F��p�H�D����c9��T��\�s
+����&vz�i��9��?��e<���������ܬAb3�1w[ )C�"<�����Io���w>g�_�|����*�=��H�������� �$]�� N(����Y�B���?��^/��P��$���z�ki �c��(�_�ȱ�j&c�ކo��b�CŒ����C��� ���H�E���q>A5��S���x���x�iy���#D��/$ �Gb41�D,�0> ~�� �*�H�De�E$�":s�)�m���귾�fE*��6D[u����4T#�I2���5C�Qã�� *֔��bB>K�0 ��MO��(a"Ys�W&`��@lZ��(�#�����V�?Ӊ-�HR��N]j��}��AM��$h�tɋ3 sN6�����0:%A-��3 �^��냘s������Pz~H9ΤHPY�,Ք��2x��m8'�[n����_9PbXP�Æ\Ϭ���o<O�X]���.q��
+�a���2"�$��;�|�6� �CѼ��=6���%0|& �8�g֞J�,`7�R�6�m�4.��끩V���ΑEB��Ő�:�ǝ �"O 5<r��^��a�+��iHa'�6�Cʕ�ڎ�sJ�eB%.��:Qm��Y�J ���v9q{�w>ؼ4�<�!~ =��i�{�ͭ���.g��Z��e�� �5u� F�(�s���?�)��qVBۗ_;�ʐ��͆ J����"�!'�ͽEvv:H<���l���
+���
+�M��l�#oT����p��( ��e�m_Sna# =A����!?��� Tw�qo����
+K7����/8v�#'�7������d P ��%�-��� ȚI�Γ֍����yb���C������6<ֺF&�Ң�e�n�
+KD<��[��A�,P�YK-rt:�������`�"�����f��I���u!ZĚcEOy*1 �J�}��J/��%� P|)}��W5��������E��!�:^���<BH##w8��gc�) ���QtQk_+h����������v�#��!���y�4Tw���|Lg�vu�!��9gJ���t��F�b1.�k��`b�=Ui.d���G�V��o>bK:4�킚w�2@�E�>�}�NAV#��`Ɣa����u�$ep-6Ou9b�z�EP�U)�KX��&R�g�e���J���%p�R�|L��k�gw
+&3^汆Zc��4����Bo�䑻|�"4�9�aDS�r�� �,�a�_V��]�2�q�.b�D$&�*�J�(�e>��i��y��l� �^�[_�X:7*�-��Jh9*��k\�9�w�g9%����nx�م��l�d6��1^�RB���ߑ�9
+���D�ЉI4z���[O�� #� ���
+�U��!������2
+��s�:7�D���=L��s̓�B2�3��C��,���6eXd+慠��8[�`�cͻr�Na~��*E_�f�Q�R� �4���;`f.2.�6��T�&��q�M'�&Y�(>+|���-3�7�m1
+�ú=@a���p�P�����yO�Fx৅�̹gX�M��2�|�j�tf_��J ��Z�l��7]�d*�AW����-⾋D�>CC�3W��c,Z\��Y4�v>˄�� �XӺJ|>�����h��d��?���+�_�B��4�cz�e��_���+NF�9�u����3Y����-��D5h��n�ҝ�2�;�n��n��Օ�:O�6����j����Hd:�o����!'�K���E���CAHlR���fw��$q�eF4f�\-�(,r��Q�T>�ӣ��)[n-��$R-g�PIb.$�/�9����� 6�C�D �r��~#/F�0(q���@Oy�mU�MYe�f0��P\��Rpe㫻��Ψ��5���c���:�J�~I�Ş�-�s'0�褨�F/�g�����%�Ϯ�,x6H.�l��T:j¾ Uqe�O��棡�e#��Ŗ�*¡H:�x��FÐ�Ls�Yř�&��iM~� a7-��E�B ��x���L�B�G)}��6�/�V�g.+�mً �iޞ�?��������D/� ��%BY�� �o�.�x��\���b?�x�o�Y�h� ���2�>N0�8�8�E��L�K{��� ����UᏳ��t��DK�
+3w���:k1x������w3� 䙇p�� ���6����-h�]2֎mm0��(���6>��蜴�I>�|��Wý����K9NXcֲB� q({臞`yù���T�����_yvW�aR%CX`-J]=��8���p��G6�Hs��������6�sM���YPs!����g�n�u�p��;����%����G.��n�NN�@Yp���z�.dV�P֎�u�k����XJ��R|M���@�8���I�iz�R�3��e��������`L}��^Pߞ��O,.&��*5��v��u�G�I�Ms��v�*���faKCi7�-\�m�2֮�8�py{�Rr�=�k�,�t��]�᥶�D%��_�b�EWd��J�OD3���_�dV�pfP�6��23B�l�S�P�A#J���#ޑ�Ƴ����C|�A4�?�(�#���W�s� ؾ���Yp���h�T�Ц6R����Y�哲 ��[��K<U%�������� T�aq�\��oC���*����gXf��p褰�Q/>z���,�b��r�D��� y��ia��`�����nC��Gg>���Y�K�o�K����T�?���� �������_jT��U�2��O=b������JFn���wb��E����'ruF��[F_��q�=��1���K�����R:@�t1B4��u
+x0>
+�H!�������0�Io �Ю�X� �߽��n�g
+endstream
+endobj
+311 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+312 0 obj
+<< /A << /S /URI /Type /Action /URI (https://aws.amazon.com/ec2/instance-types/mac/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 195.914 491.999 295.041 501.464 ] /Subtype /Link /Type /Annot >>
+endobj
+313 0 obj
+<< /A << /S /URI /Type /Action /URI (https://aws.amazon.com/ec2/instance-types/mac/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 481.997 137.108 491.501 ] /Subtype /Link /Type /Annot >>
+endobj
+314 0 obj
+<< /A << /S /URI /Type /Action /URI (https://aws.amazon.com/ec2/instance-types/g5) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 195.914 472.074 295.041 481.538 ] /Subtype /Link /Type /Annot >>
+endobj
+315 0 obj
+<< /A << /S /URI /Type /Action /URI (https://aws.amazon.com/ec2/instance-types/g5) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 462.071 128.532 471.576 ] /Subtype /Link /Type /Annot >>
+endobj
+316 0 obj
+<< /A << /S /URI /Type /Action /URI (https://techcommunity.microsoft.com/blog/azure-ai-services-blog/announcing-cost-effective-rag-at-scale-with-azure-ai-search/4104961) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 108.617 392.333 295.041 401.69 ] /Subtype /Link /Type /Annot >>
+endobj
+317 0 obj
+<< /A << /S /URI /Type /Action /URI (https://techcommunity.microsoft.com/blog/azure-ai-services-blog/announcing-cost-effective-rag-at-scale-with-azure-ai-search/4104961) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 382.37 295.041 391.715 ] /Subtype /Link /Type /Annot >>
+endobj
+318 0 obj
+<< /A << /S /URI /Type /Action /URI (https://techcommunity.microsoft.com/blog/azure-ai-services-blog/announcing-cost-effective-rag-at-scale-with-azure-ai-search/4104961) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 373.101 130.868 381.752 ] /Subtype /Link /Type /Annot >>
+endobj
+319 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/togethercomputer/RedPajama-Data) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 189.956 282.744 295.041 292.101 ] /Subtype /Link /Type /Annot >>
+endobj
+320 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/togethercomputer/RedPajama-Data) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 272.821 148.601 282.138 ] /Subtype /Link /Type /Annot >>
+endobj
+321 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/kvcache-ai/ktransformers) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 242.893 220.181 252.25 ] /Subtype /Link /Type /Annot >>
+endobj
+322 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.cpu-monkey.com/en/igpu-apple_m1_ultra_64_core) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 236.137 232.938 295.041 242.435 ] /Subtype /Link /Type /Annot >>
+endobj
+323 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.cpu-monkey.com/en/igpu-apple_m1_ultra_64_core) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 222.968 221.897 232.325 ] /Subtype /Link /Type /Annot >>
+endobj
+324 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/facebookresearch/faiss/wiki/Indexing-1T-vectors) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 212.136 83.491 295.041 92.995 ] /Subtype /Link /Type /Annot >>
+endobj
+325 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/facebookresearch/faiss/wiki/Indexing-1T-vectors) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 73.528 214.088 82.873 ] /Subtype /Link /Type /Annot >>
+endobj
+326 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/2401.08281) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 353.9 677.264 391.001 686.769 ] /Subtype /Link /Type /Annot >>
+endobj
+327 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/2401.08281) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 418.466 677.264 523.863 686.769 ] /Subtype /Link /Type /Annot >>
+endobj
+328 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/1907.06146) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 477.234 567.683 514.265 577.18 ] /Subtype /Link /Type /Annot >>
+endobj
+329 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/1907.06146) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 539.045 567.683 558.996 577.18 ] /Subtype /Link /Type /Annot >>
+endobj
+330 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/1907.06146) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 557.713 420.299 567.058 ] /Subtype /Link /Type /Annot >>
+endobj
+331 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.14778/3303753.3303754) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 536.81 527.833 558.996 537.329 ] /Subtype /Link /Type /Annot >>
+endobj
+332 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.14778/3303753.3303754) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 517.862 450.227 527.207 ] /Subtype /Link /Type /Annot >>
+endobj
+333 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1145/3589282) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 389.431 478.011 493.353 487.516 ] /Subtype /Link /Type /Annot >>
+endobj
+334 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1145/3600006.3613134) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 445.313 378.385 558.996 387.742 ] /Subtype /Link /Type /Annot >>
+endobj
+335 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1145/3600006.3613134) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 370.256 354.371 377.19 ] /Subtype /Link /Type /Annot >>
+endobj
+336 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1145/276698.276876) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 419.12 318.609 543.326 327.966 ] /Subtype /Link /Type /Annot >>
+endobj
+337 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1109/TPAMI.2010.57) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 514.876 218.975 558.996 228.487 ] /Subtype /Link /Type /Annot >>
+endobj
+338 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1109/TPAMI.2010.57) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 209.02 418.06 218.138 ] /Subtype /Link /Type /Annot >>
+endobj
+339 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1162/tacl_a_00276) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 432.442 99.423 552.503 108.935 ] /Subtype /Link /Type /Annot >>
+endobj
+340 0 obj
+<< /Filter /FlateDecode /Length 8369 >>
+stream
+x��|�R�ȶ���
+^nl 堔T�jj�� �{����jd��dh����LY�m��{"���rּVf�w����W�~__������^fF���/{Q��P퉽X�%"
+#��]-�~ ��^ڛ|��)=-�ݟ�TU�Z��*X�A�.�|? �9S�c�� ��έkVR���6��_}���}2�dad�pF7K{7�`�=FB�'n�4�R�ծm��O�`�?�:�9���^ܭZ�u�FlE�K�L�H5�7��^?�/uw]TEu��vۊ�}�( c��l`v�d�9%����=���˛�{����S
+��gY��Ŷ��%ih9l� wH�.�Bc԰ݵmi�� p�6�v�p�;a�� {;���N�>~䤝΋ng7P���U���G���O�C��;�-�i�y������^���Pߕ��_Veɩ|q �E Q�YW��ېSoVKh�쎫�_��P
+��E͐ ���e<0�Ji��j���VS�k_�����t8μ��s�Y~�!C�CҖ� m� �y9��"��~�k,a��kڥm��8D�ۀ8
+��_3"usr �,�tN:2���f���v�y�t���vH�MW� �JC�7v�����Ip�odP��x��}�8���e@�W@_�yye�yi���-���]ǭ�#��Q�Qb�7T��$�Ά@��i�y������/�]Ʋ�)*[��̶�+4œ��[$cNu��X���s�}Z�=M�$ʆ��-���ڧVB�*3��?Q*���E�m�E��;��Dq����c�N��� ^*�Fz��d��[�t�m�H��f.�DH_#��� �@��%!��~�E�3�s�%�vՔY`Ǜy�0K�*�c�7���W���IsH����T�n����� 4�8��_h?�*V������V��s�4�iK��O�q�qeG���X�����(]��G���V���yǬ�� cz���Y4�b�T8�)#�B�'
+.�������?\� !�����n�m���8%��� �]�0G kL��D�WHD��]��! Fd`#M@K���jM�ק�_
+80�
+�{���A|����}�m��HnA��j�u�$�b����_��Q��Gn�������f���'Y�#�p��L� �2A�WJ��P
+(�(�v (�D�h_�`��M%�,��tY�r�װs"
+���+W�G�]���o�F��9o,�Rd�N~ ����$S{1���1 �װ��]�6�*�ҏ�\!S �n���%}O {w�S�Z��e��̶��t�Fn.UL��N �A$$�� �A��>��Lf��/��$}뉛$n�[� 7�-�#�9��D$�� !b��0�F0��A ׫3X��n�^�� �/��q�H��>�"Tpz,Y|�oQ5���9��1�Q@8ٻ�~$W'Qo��I�̄��Y�[�e�;��mB��N��A8��gq�O�WێW�б�ܴ'@Ld�>���.���Y&a�0�kܜ�z�_��}�ʢ���c[ Bt*��-�r������@=@|�����@�@��������_==�Yl�=���ٳ�M���(�����;��Ej��#g��E�zu
+$'��KX�|u����C�ђt|�{m=9��q�!g�r3H�D8��߃#�\�)E 2J���k �DO�GI8��U�Q��$ʏ\8c玿��H�P���8BA�a��$ N�.�S�s?�E�P��t\+hf�^�W`�^!�6�ǡҩ ��"C��q�i�=<o��y6
+������W����$b�����%Q���H�yũ��3�N�r�(�]�
+�#��n�_��0����kċH��B
+�-�W<��bC���Ѕv"0�"�X��t�*�b��)K�w�M��|b�TaFj(�NXm�D�f�\���P��%G'�) I�:�)��~M6��xI���f"��$X��u��6 ��QUիjJ ��iݴd͋a)J���.Wd*� �W��d���v<�,�G1u��b�l��������0�,iޙ������g�b#FÐ� @T�_��C�T���)}ثC�z0��y/M{����+�_QN��q_i���E�?�3?�T�D�)�T:��\��yM�Wz�+��~�4O�iʐ^�Ɓ-�p�����0v�A�B �[�:ɂ����G���U���w��,���T��>�]�U׌;�v�Q���4ج�Ж9.�k���n�����v�f��iW���zFh�:��S��e������� [�X�����P�HgF</Uϲ]W"Ca�|��H�H��M�{X��c���|M4������ƌ�l1��,�s�</�uT�qV�^�m� 9uwV�6��~N��Sp~F��(��|nk��yt\ς�W�e�f1����j�%OA�g\^��A�{��ށBU>v�������� L�:��*KФ&�<�P��kk~\�xT��H��*=�H�; �e�Jf�9��M����N�� pF^!��:���/�ν�)������Θ#Pj�&�H�^�]@.��y��M� ��8q����Zz�f��3)�ZM[�9��媲+W�aU��zQ/ۅ��!����ߔ�������7�EhA$��y�����v��m���!L�����N{�|�j�����q��`K@ u��$�%; j4G�1��i#���3�s���*궜��&L����p��}��,��h r�aW0
+�!J�"z��I��!���?Q���)ȶ&$�<��(���م��.�+.>���;����^�+V0�� ���*m�Cd����tp��r}��3{~�0x�/�`�6Uk�֒�����}��G����T���Wנ/[����mTG4��񴿇�s���q�ϲ�Ą�R#��h_��ֈ_y|�&������J�D�x@[l�c^ �y&�C��H����#���4$1W��$���^���q��?�$�Ν\� y͗h��VG\� ��n�Ε�fi�d���${ ����`�'y�zz;�#$N�v�'`_�
+`��E�Ʉw��0�{vvΉ�C�2�|�}�xb;�7
+�]�$�N �E��H�3�������'��$t
+!���&Q<�M���H�[��Q6Z!��T8$8������y]��?:st�B����(a͜4zr�1�~�z�'=�ժnΨ� ����cA3�Y��PN�V��o ������b�H�갸����_�� ��
+����Lau�;ϴ�|>�Eb8 ��CV�!������]
+:l0��Ѿ_�z����,��liv㐇L����6�v������ӧ b����(���ت�p��.ؔѸ�P٤ �Ty&^}( $�����,�Rq���ᬅEŴ~ş�� l ��?�63��l���,�G/��G� � g�ɪ�]���������10o����Y�(4����!�������e��XGvh�~v�)� �9\���s����drR�t,+�NVr�upO,�P)�p飀�;g���µ-�b�؈��"r��*Qw�p�n�El ���<
+Sm�س?����ji]�G��;���b��PlhhB�eIFN����IƠU/� \�����Q|"��܈b���<pE?�� q�����!2��ٯ!�� �c���}8��No���e�ky�5T�r��6cF���Sm�#�,ڧ�/���I�� �e�F� OS�OЀ?'C@&@t!�@&1Ԁ=�~~���M\���Ox����b�*8y��Nr������y��93��4���k�so�p��NWTh(y,����;G� �Cm6E%C%pt������n~"A58�:A�3�0z�^S��3�( � ��yi`)T�35l���zR0N4E�8��3!��=��?\;*2Y��a`���~I���i��� w�-c̠%�A��:���Y*$���<�ӿ��YhP2�c���pB���ɰ�m� 9��ڹ��xI ���칁N�1��M�1[��N>~|@@b��� -�N�����/�E&T�S���� �:�u+�`���N��"LA4B��ͳp�G���n^Nj`
+r�(�픽�q��e��Aj���<���?�F
+���ZQp8�]�8��'�>{d^–�Y �|w[�_ë.���m8�S��N�c Z�Y�D��򔎹����G�l ��� e��� ���:!��^=�e]�������m;2W����Թ&�l]�� �#�@Q�ܢ���m����aP �z�ht�\���_l�4��mq�[���
+�J���y�B��X�ǿ������u���=�N�\8X�I������j��/1�w��[W���֩)��1��<���C=�6l;�L"�I��s��$x���T>� .����6�.R�/�|I�49],l�BA���]��%x��,,�tV/�8�5,m)G��Z���jP��
+e�$����#�W�4"�}��M�
+���D*5�?b�N����r'���� ��¼t֏��*�@z���F�L�_���/՚����߄j���d�Xv�7�Aq�����^7�;f� &�&b/Sw֨t 9��[M��&A�Ȧȁd�� 2/�uiI$ݨqU;G�;�����on}�L�D���Ί�v'��R�83wo�`�l��� Gg���E|2�D.G�C�.b�d��wv�&ly`��a��7V�c�Ë!�J+81lu��"��ګ�:xzz�Eξ�x�֮��Ի3������d�����j;:��&3�N��S7U1��� TQ���)�1���7쩱 ����e�lH��q���y��q�㝬��'h;4�c5�Q��:m��]͗���K�څe7m��-W�n �N6�ڻ�W���Ya�_��|a�q稜��y9@�"o��v����7����:_-�d���:���t��-j�^t]����`fZ8��,�����
+������zO'�s�q8h%��nL@� 4A9��B��������� 7���+9���oY[�]�iܙp�0Ff��V�&�u�3n���(��M����O�H��!z�9o�%#?��^�8C��t.|������p������6�30b>�!�:�x� �58�)&�U,yհ%�GH����� ��PNrN\��/f�&c�m�,Z�ĸtwEɡ���78��(����-�K��uQ�0����1^��s�[?T�B��C�����A����~��\
+&��…�f"#��.`L/\����7��i�#-Kfqc�j��]���6�d��w $&L���'�W@50C��T����Zg΢�Y�)(��u�Ӈu/�b��ulðNW?($9�N�� ��Z�F��О�� ����h���>� �ӱ{_�ض3�4L��Ԥ�G �0q���*hI��K����`�{��!!w����kN�V3�����߷�"L���<��b�A���Vn���h#Pd��J��E�h��0�S��e�i:��S�(���Y��':��2� B�:G���J�����?G�� ��A�ݱðI{�?� �K�gm�5(�s0uVs<����u���N�d�*l��y����L�C��#\�s��!���{d����Wg{+8#O
+�f�_@�w�~��N���Ԑ �J
+��K�]�3آ#�;��� vJ���I���V�W�C\�C��P�`�_���=Z�Ŕ�*�\¥U�oktQ����T�ږt7����oC�8�X��#���� ��u8��Po�#T/3�No��8�z��0��&N`�I��� [�߿�|�"��S�Œ���<��f�Ҍ�
+�.����8s� ��v�NE�h�4��~J��S^�+ձ�����(�3昏-X���J����S����b0г�.�BR>�:���P
+K+�%���;[A�O���zC�(؅�^�{�鄿��2�� �t8�vHC�׺�����3тl6b����z�g\��b��l�3K8Os�I��N���
+��+G �u�\Z�o�������h��bi���ޖ�R��� �[w�|
+r�C't'��)��{L<�'���HyO�>:��pR3p�Bi��=�2(U���oc4>�b�����)�lY�Z����`(S5���䔐�.�:�t^��Ѕ7��m��#���/��ׅ���E��$4��F<���S�G��[�%����cTJR���c�|��q2�D�-�H6ލvÿ��3:M�]^!���8[���<� T��A�{
+�־\�P\M���Mϙ����L��_n�8����/2~�K`���ɵJ�Ų�gq^��������^e'�@ꪸ�;�9>���9��S�����Dc,E�]����2 �㱊� d�r�JI��V��u��~�l0#��t!�x9�?Ǥ��T&�?LAfCl���*нC�����8�H��%ce`<�$㋢&~��3��$`���Bs��{��R��*B� 2t�io�ԁ5�����W�7�������7�۰h �>u�A���D0]-g��!l���A����й�z����pF_9'� �m+쯚\� `�9!N� ع���G���壏�*V �"�
+�k��A\��9v�e��:��(у��<pb��6�F���T�q�]P��m��pI��=9bC,��:�tI2 ��?s����]BI�3 2�JG��^t�5 d�AB��e���9��nox��>����o��@��\������ <w��{� O��&�2�&f$Է�0�a�)v)21������ڰ"�U'F��+��
+Ăؿd�[A�JО';e�>� 4�%����1��S?�G�=��(�_ۦ��HX���gfy��U��Ch�5� ��������� )
+� V�!��^�E�
+���Y�"a�}�p�񩐳�t����Y�gc!J�6�vw��(F����U�؍b^�拃����;�U�� �_;.���ߟ'��t�����;u<4�m�]�!deB��|��?_���;HF>3�� �Dg��qP�fF�0��A�tU5�f �����h!}�?�Y�\ ����9�K޶%s�G��]��Lw��瀭IH'����Ya���8(��E�b�8'��K��%�P�QT��.C��ӹ��^�ˌ�Nm?`8����;�~m�u�I=��9��`�%��+�_��w0�WQ*FoD$�G�cd���p�J���k̝s��
+oy���
+TdXʐ��ȼ1C�׼���,�RX���G�E�]��T4���Yl��{���>D656u`������ (�plVа�})蒗��Z��3�e������nA@JS�Z����)�ѵ�ޝKE7ʲ��p�d�V�Ib0�R�#-�CP��B � �L�����C�Wf�PoCv����g��������}�$_��
+_�{��i@7a���*�(~2�B�w��9qQ|*�]��ױ����逓��{���2λK�
+A��q��/��,w��r��j�H��
+��������3��}��t���IM6a���
+~�υ�+�]Ȑ���j��g�\�ݓ}.�1I4:ߚ�]�1��TRD�{Ϥi�}O��#�.�d����I�o5r��+@��>�Q�t$/�#2#�`0���g�o�1���W3Qv^rOɦ=��$�n8�$�$հ;�BÇӾ“* ����2S�a+������>,��Wh���R45���]�y/�+пEJ9�� `�y��,��i�]�@�*R����v��� ;w�t������])�"������is�T��}I��z�˺q���V���(�T�7'>�i}�6N��9�����n^��3��9��g�ƒ���'cW- �J��N��PW3�&V�=�j0M��J�r}�gSNs�6�s����8������g�G�� $;t�4~� R�߆��[�?�+�~U�'Sȗ��g�����ZHIA��� ���ny� *�.��f!�#�Ѷ�
+�aw�o�Ow;�?�XW߄J��BQ\��!���=�f��"@�C��a�����c�d���Ɨ�v(��S:9�_D������{+X!0N�>�w��dh�c�~����$��1���� h�=��y��i���#�U|�n‚�j��3��~�@�V�E D�y��u,�Ͷz̹�B�.�v,���W7s�L��X��n��o�U�;���E��#.��E:��r�Ј2)� ��>*���j2���(#^�=�z�.�u�F�W��� �k�=7��*�_,QfI�Q���;s���տ�`�2�
+endstream
+endobj
+341 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F198 89 0 R /F201 90 0 R /F204 91 0 R /F212 94 0 R /F470 595 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+342 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1109/EMSOFT60242.2024.00006) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 275.333 697.182 295.041 706.622 ] /Subtype /Link /Type /Annot >>
+endobj
+343 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1109/EMSOFT60242.2024.00006) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 687.227 213.928 696.572 ] /Subtype /Link /Type /Annot >>
+endobj
+344 0 obj
+<< /A << /S /URI /Type /Action /URI (https://learn.microsoft.com/en-us/azure/search/vector-search-index-size?utm_source=chatgpt.com&tabs=portal-vector-quota) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 275.43 408.265 295.041 417.777 ] /Subtype /Link /Type /Annot >>
+endobj
+345 0 obj
+<< /A << /S /URI /Type /Action /URI (https://learn.microsoft.com/en-us/azure/search/vector-search-index-size?utm_source=chatgpt.com&tabs=portal-vector-quota) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 399.004 295.041 407.655 ] /Subtype /Link /Type /Annot >>
+endobj
+346 0 obj
+<< /A << /S /URI /Type /Action /URI (https://learn.microsoft.com/en-us/azure/search/vector-search-index-size?utm_source=chatgpt.com&tabs=portal-vector-quota) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 388.348 259.19 397.693 ] /Subtype /Link /Type /Annot >>
+endobj
+347 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.nvidia.com/en-us/data-center/products/a10-gpu/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 224.187 308.686 295.041 318.151 ] /Subtype /Link /Type /Annot >>
+endobj
+348 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.nvidia.com/en-us/data-center/products/a10-gpu/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 298.684 207.612 308.041 ] /Subtype /Link /Type /Annot >>
+endobj
+349 0 obj
+<< /A << /S /URI /Type /Action /URI (https://images.nvidia.com/aem-dam/Solutions/geforce/blackwell/nvidia-rtx-blackwell-gpu-architecture.pdf) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 278.759 295.041 288.104 ] /Subtype /Link /Type /Annot >>
+endobj
+350 0 obj
+<< /A << /S /URI /Type /Action /URI (https://images.nvidia.com/aem-dam/Solutions/geforce/blackwell/nvidia-rtx-blackwell-gpu-architecture.pdf) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 268.796 201.877 278.153 ] /Subtype /Link /Type /Annot >>
+endobj
+351 0 obj
+<< /A << /S /URI /Type /Action /URI (https://objectbox.io/on-device-vector-databases-and-edge-ai/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 254.426 258.841 295.041 268.338 ] /Subtype /Link /Type /Annot >>
+endobj
+352 0 obj
+<< /A << /S /URI /Type /Action /URI (https://objectbox.io/on-device-vector-databases-and-edge-ai/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 248.871 242.027 258.228 ] /Subtype /Link /Type /Annot >>
+endobj
+353 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1109/BigData59044.2023.10386517) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 199.058 241.561 208.402 ] /Subtype /Link /Type /Annot >>
+endobj
+354 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.pinecone.io/learn/series/faiss/hnsw/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 179.172 252.969 188.489 ] /Subtype /Link /Type /Annot >>
+endobj
+355 0 obj
+<< /A << /S /URI /Type /Action /URI (https://snap-research.github.io/efficient-nn-tutorial/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 539.045 687.235 558.996 696.584 ] /Subtype /Link /Type /Annot >>
+endobj
+356 0 obj
+<< /A << /S /URI /Type /Action /URI (https://snap-research.github.io/efficient-nn-tutorial/) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 677.264 488.942 686.8 ] /Subtype /Link /Type /Annot >>
+endobj
+357 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index/28074dc0ddc733f84b06fa4d99b3f6e2ef65613d#if-below-1m-vectors-ivfx) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 537.954 617.528 558.996 626.993 ] /Subtype /Link /Type /Annot >>
+endobj
+358 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index/28074dc0ddc733f84b06fa4d99b3f6e2ef65613d#if-below-1m-vectors-ivfx) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 607.526 558.996 616.871 ] /Subtype /Link /Type /Annot >>
+endobj
+359 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index/28074dc0ddc733f84b06fa4d99b3f6e2ef65613d#if-below-1m-vectors-ivfx) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 598.257 558.996 606.908 ] /Subtype /Link /Type /Annot >>
+endobj
+360 0 obj
+<< /A << /S /URI /Type /Action /URI (https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index/28074dc0ddc733f84b06fa4d99b3f6e2ef65613d#if-below-1m-vectors-ivfx) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 588.294 374.204 596.957 ] /Subtype /Link /Type /Annot >>
+endobj
+361 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/2412.11854) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 353.9 358.46 391.001 367.964 ] /Subtype /Link /Type /Annot >>
+endobj
+362 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/2412.11854) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 419.016 358.46 524.413 367.964 ] /Subtype /Link /Type /Annot >>
+endobj
+363 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/2404.06004) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 521.377 278.751 559.18 288.263 ] /Subtype /Link /Type /Annot >>
+endobj
+364 0 obj
+<< /A << /S /URI /Type /Action /URI (https://arxiv.org/abs/2404.06004) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 268.796 439.428 278.141 ] /Subtype /Link /Type /Annot >>
+endobj
+365 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.usenix.org/conference/fast25/presentation/tian-bing) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 466.001 209.02 558.996 218.377 ] /Subtype /Link /Type /Annot >>
+endobj
+366 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.usenix.org/conference/fast25/presentation/tian-bing) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 199.058 458.815 208.402 ] /Subtype /Link /Type /Annot >>
+endobj
+367 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.optimum.com/articles/mobile/choosing-phone-storage-amount-needs-guide) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 179.132 558.996 188.477 ] /Subtype /Link /Type /Annot >>
+endobj
+368 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.optimum.com/articles/mobile/choosing-phone-storage-amount-needs-guide) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 169.17 432.234 178.515 ] /Subtype /Link /Type /Annot >>
+endobj
+369 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.optimum.com/articles/mobile/choosing-phone-storage-amount-needs-guide) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 149.244 558.996 158.589 ] /Subtype /Link /Type /Annot >>
+endobj
+370 0 obj
+<< /A << /S /URI /Type /Action /URI (https://www.optimum.com/articles/mobile/choosing-phone-storage-amount-needs-guide) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 139.282 432.234 148.639 ] /Subtype /Link /Type /Annot >>
+endobj
+371 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.1145/3639269.3652200) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 429.97 79.506 558.996 88.938 ] /Subtype /Link /Type /Annot >>
+endobj
+372 0 obj
+<< /Filter /FlateDecode /Length 8136 >>
+stream
+x��<�n�H����.0ME�x508v�8�3V:}�,�2-U�"�"���=��HJ�3�݇VT�n<�:u�޳�3���w�������U���7K������w�$�?��T���ͳ8?��Q����$qn�D�s���e�eϹ�6\�>��U� �;s�[��Q�E����ʋ�劋��_�P~�*�R7�S��� � �n�<7K#������D�>���E��R7A���iU�曣���y�UU��/W�G�s�� �ά�m�5 �z���r��P���B�a�n菀sy&�����S|�è_�s��ݳ���Ya�zF�*Ȇ�X6ͺ>����:y��ɳ8�\@�n��Me�j���X�eS~�:pq�]~1鍐h��?�'L27���?���`�3ح`�sq
+�3�裙7�S��6_�MS�=E)�Z (�PTi�|X�\g�O�A�f�s��j��LL ۙ8�]�܏e=��0u� ����vNO�ǘrQ��-/4�U2z5Xt?Mx��� Sz,%��˗/�n���H�IM�u �̵Mml�.o��n�����W���#A����+.D�#@�ӏ��'A�S-������{��A��#�ry1(����/�����yε?�N���8�s�<��!�L��M� ��^�����Ƃ���!!NF��J�������4������ߖ0�9�?]B�N����>���}�M[~��?Ơ�Z&Xv�V� 0P�@�J$�*V0mޫ?]�eaJn�� $��M�� �%B���ߖ�s.�`�Y���U�u�r��f#��*3�3<h7�@Z���亮6׆�4p��) ���~����a���.�bH��P�y�Hga%�N�M���OOE�d��X�%��r&`V=β笇�UYb�Uo~1�xܚ�zcʆ+��8}x\'{��^�Qǟ���b�Qc�Ó�1u�F�0zM�����GiT��//��H
+Ϳ�[m�gm)}a�ɍ��}ǎ�K��w�����gv �C�\( S����/m�2%��x�\���\FƓ5�核�٬t�s�2g�[7��,�̬-���e���,��S S�����Z�`�΍n4P���!i��>M�G �_Cׇ:�[��' ��j�|"q���)v��n!"�yr�JQ��߇��s�H�z�d�f^����b�!�soɥ��”��'��>,��B`C@T�J��O���)�?L"$�; �O�<I���t��P�!ُ�<7��(D�-_"M���� ������B �t"�,u5n��3X����Su�� ���a�\c.�� F'%�+��.sS���陮��g��Qz�@zSs�E^��r�!�m�&�ʵ1ȵ"�@ýi�\b)iy��7ʼn�ͺ�V��We��uc>Y��s
+8��A���;�h���U �{*H�C�K��U�(n�%n%#�I�@�p!�o�j�L,��X�+f1����]�hs���Χ
+'����E�3��� o��d(���D09ɢ\$��rvo�n!p�$��'�
+�+�Ν����&"�r[y�w/@���a��9���#��6�����b�B��^XY�nZ֬`�}�2�ټ���v��wf���^�ߥ.H4�2�����4��[m�'�a��-�ma �)�I�KOB�f���W�-���d����sX�Bo���~�������I���0i3s�m8��d�����C�B�Ci$�h��E�
+�=B�)D�Z���k{S�
+��xN�D��{8W�;]&��ٚ�� �Zix�2߇�!��4�Ғ�Y�R�MP_Y, ��C�F�v��sR�(U;�I]�F�]�$���͔H��zq� ��B�U [S9���Z�~��Y��7�&S�÷3� ������^��p-������v�e[Xڿ��!��R��.��%�<�|s�J�k������Hq���83�������>�lfۥ%�J��L�8�v�H<�a�L� ,4�u�13� <a9�eVIpr�+C 0�9W�5pNX%ᤈؓk]wv�s8,X���1C�5ە[ӡ�
+�)��� b�W�*<���s�T�h����)*��N��rN/-e +���T������'�D<5�,[��">�jW�v5������u���ש�7H �"�3�n��ꃯ�WT ���U���� ���`d��t�F;G�s�������4h�~$�祙�uu������’�e@��IB
+*k�0�ǣ���sLfm]|W�%K�̾B)�UE�m�� , 0���-�SUX
+����˞�2 ��}�e�2��3��)JQr-��U�uCג�$o9+��}m��Cr�S�ʀ� �ӽ��^��ܜ09�d>
+�D�(_��v���i���@�����˭ b��QX������"t�s��Y��9g*�����|��v�ग़��Ir����n�ƝW��4�����4��g��B*",�*珶-��L� A0<���Q�FLB��o@���j�9��,���˶����� sU[G�U�OuA/Q?��߀/���gF�ꎲ]��E���D��P��X#D)��h|l-�����&p�_�e<l� u�*?�dв��6���c`�k�a�C�M�e�W�02=�2=���S:����Tb�ܞ�;�g�~�n�D�G�����,��(�*i��bx��X)��I^��{�2�B������A�ֆU�{-��G��ȵvW/A���Գy��c��VE�ҥeu��w|�������3�1�b*@-q)�����X �������7b�}�n�3�����2���$�u�h�v���"7HGfZ�{b[����6�> �}ȑ�L'_c��2�(�[�ǭ�� �H�梴:/�.NȲ;�{�e'�7rۉ�c(�SW��9��/z��)9s~¥�6N܇:Q�o6�������<q�'sc�;ߋI���X��j5�K&�m=E�*�y���)S��v��S�{�q�n����9�*r�0�Iq�N@�A����ZH�q���ċ���(��XJ�� � �^���,J�����!�3�y��ho�#|���/\��?�CM;'�jp�;�S���(}Cz�m'Y�v� {�|�p�8 �[~��n:��W�W7z5�UEKZ�t��V,L��]�E��}X���Ď��|��3#H7�� ��Y���]��>�/A�^6—�q��?*�;"I�G�>z��I|9?^�.о�D6�S���" ����/�J�'�r��rҁ��O����'$�2�n�7�AG���� ���N��u��/�S�������x=$<`�CbM� �F(�FdH�p|����D(��\7� �J� �(��H�"���wD��m�tp��1H:�uפ )�xɻI�� ��VB'8�T��=]w0=A��p����J�6>�iH�O�)�(�D8���>>�D����� �ʷU�22uzϲП7F����C��}k1���U���Y��e���{#Hc������w'��s��J��0�I�~�e��]u6\t]�"SH�X��t%��&��֍��HV}(A|�s/
+u������ �� Q� {k��\; �wr3/�vK �A��&��BD�YpA�zPB���ȝ�?r���� ���<U�� �H�,���Ȍ���,TC>3�D�� C����TG~�'TƧ�?>�w�6|/ޕyU
+�Jn!�aҁԉ*9hs=��]5 �xי�y�ۡ�g�����&���R������C���zH$��t���pAU��2$�#����kN�9MV�Ի��U7}�V�����7�A��>���ި���cF�<��O��gٛ����_O��Jg��(�"�t��m�!�t�>���c�=�� P�_P��L��0�E�4\��p��}�5�
+��5ߜ2��"��3�+���lo@N#'6���ACx~@@�ۗce�K6��ǩ�����s�{ L�⛶0df�������4\�y!-�|�̙�Ց�dF�۫���؈l�l) k�Vq:1 d��5�]���:���V7�� � %s��(g���(򉄸L�����_�DJ�S���J��۫��* s���u��q� ��̦nl �(��sl�T?,�ۆ���e�Þ[w�Sy��⑌���լ��m ����Z�a.��|� o�j�(7��bm�]fsv��2� �(�z��x0�k-N�����T�b���|�KD ~ '`Ya\��_勿�cr����N���v�$v�j�50V�$�>!9�:�=j��.���$�ͯ�Km�K�����E��9�G� �~��O�{P�d8��%%(���(p-Gj7 �
+��D7���+4��=� �"9���3��p��h��Z�rk�F��"0;S�14݇�H��x�A�<���;(w�p��~r6��8��=��S���<�d��a)l�#���Ĝ�d_h�@bv��8"M�:�Tvr�l��s lUyd#d�A|`���L��~���v�^�������Ҹ0'" S�'��]�R$x�7vpWs�+��ߜXiw�H�@���6 ��bϮx%��]�3>��.��������{�LE�� �@ǘ+/�� �W*t�q��tZ�z�v���h.q�J�5&�T����5g�JY�F�� Y(1< 2�(6��D��4�x����o����Ʀ�n�YnC�{����� �5[��I����ɑJQ.�-�1`S@:%3��A�<��:{������=gD�*1�/1&���I[1���U��FYW�x[x#0�y�~⽣Qw���?H╣#�BʳN�P�֪;�<r@��ֺ��8��y�j�@f����'�A*��$ �s�����[�U�%,��̾���9?�T����S�aQM�>������}�=��we���`"W�i7"�") u-)e8��r����r�>�̯�2y�6�I��=
+�ݜ�� P�B$�4���W�I��0FE�a������J�s9e ,.�����b��-���i朷��\à31�r����*u���.��O��J+�/�6��q�tr(��ZS��NTG�������L��@�z,ܒ׊u��MNF�-E��6TYO���3�%�-���c4d���|�s�9�S��s����pv��8�R����3�L��5��G� �C��Pͼk�5<�sE��ʷݜ��sݛ?��ѽ><g�]��ӎ�;�)���pk����`������jX�$�gJ���Wt����d�XTH�Q�A�!;j>�~~�����.�(r�����#$#�����l����^=h+)��r��w"�����H<�;6�r��V��q���j�6��sO;{9 /Kb`�ߏPL=fI������݇�}Y��sE�ѹ$�Z f#C6��DŽ�GZߊ�z �,ꉗ@���n=�c.1ȟ8�a�PS�X��^��8�E���`�BA[�Tk�����b|�ދ���?%$����Ziʫ�
+ݮ����<�i�A��G �����/w�+
+o��sT�!G q��BgIo�����S4d��{�&x��N,s6���No���]�.t�QNCS�#�P�����2��4u�E��Zc��c�F�9��� ��l*�����K���ya�w�A�~�I�\�$7q�ql&_��ε䣞��_��j����'�QL(7x�MQ�Ix�&j�{�����\:M�) r ��)�n���q�Ù"� ��&�}����J�X�_�e�n�K%F-��ޚVj���^�9��K�����]������Ϗ����1o5�XA��T�vK�����!X3���Of�̭�x�d���8�� 
+|T�bC)��|�������n��Y[���^v��$�w�Ý����k���G ��.mZ19��,m>ř��
+6�lӱ������T�I�� [@ҟ2~���滳����!�L|ԓ(L��U] Gpf��:-Y�PG�#�v�mY�\��@Ĝ=�/�s�,p�'~�C�SO����U�G�Gxg�$����C�]� ����/x}5&���ݶ����Z��ؙaz�$9& :��hI����]$ܜ�鍑"駔/��8�ؐY�g�-̊�����5�kƘ���N�qs?�RR�����7���W(�=��/��,T�|�6P�0 �?��إ�;�PL�'� /F��=��R4�}��N�sϤ��v�����=�
+x�����n�|Kҋ{�l�)��Q�?m��']�sy�)��������g��}h�U{܂�a"Q�����X(X�1eu@�˝�.�ގr���iys��! N���e�ԫ��ởPd+��`�Q��~����r�9�3�������g-fuE�HoX���>�΁�k�˂�>ЋaqB� �l�#ui#���CH�� ��%�&��c�f���"��jp
+T̹F������2�C��F�t}אE�F�U�*� ��Q
+��4
+���©����{r��o����b�o6�Eo>O@/ƾ��zz��q.��>,e��'wK�kl�d������$ӵ�P��Q|jh���1V�����un�;�>c{�0�9��bw/�� ������Za3��8=]�! h��eB��8t�;gM<E��t���^D
+Zz��l�z=��kD�΅�m�rhi��j ���i\�� �\b_�5&︚@�R�V�,�q���Yh�����,�8���W��~�:1j�2�7�{?�
+m'c�65Ixsit�4�x'2�,47_��{i���$x��/��ǥ����|2���-IF
+�궫n��\%J��o�p�Y�h��P��N)�3#���cn:)��)'3`�(D�#尷��v��O�҅�j �线��l�!��~O gW'���NsϹv (B��"� }�<�:�*�\�}0\�n�C�[e������b� �r�$
+d�t8�P��i�o����;����n �1�����O�����\�O��AP� �NIC�[,�ֆ���e6I`����X�=���+h�a� �1��d�X��l�e+�������8�^�$��a��[���?�e�v�ƔR�K�ڨ��:�4uk�e�m}+C��As�y
+;��I�Vo7�(v&��o�Dr�XN�����r�6�(D[=)�v���{!\��)%�#�h��m�P;��c�gC������s*�J�.mIbӊB[����ye
+�dE�ᐯ�<��Ca �! ��^ ���|w��: ����|��_q���8P�c�/��~���˲*��!ީ��I��"{2��5��?�����X�'���Ec����t@��"���%�B���'R����͟�3yH�&������䫭��|&*6�����(��MQ� ��ؘ@:���6@�$�H��-�<����ƸՏ2�h�9ǡP@:���˕?П:�7���~;���N .��k�`��v.��:��_�8�-�\�(���B�?��d���c�k��^�0F="�pw����{)S�9~G�7�����+���2���F��?Ϯ��Acz� ��=����y��ި~�i7��w�����{�H)'G��+z�����쬓��ax^3HRݪj�h�����FI������(�c����B��C��'��g��,�c���,��@��^�-�}�{%�qt� �ڛ��/���0�_s��I�yX��!����� ���Tc�ei��C%B��W����?3V ��9���#Y��p4|@���K��J2| D8IEU��v��t\҇���V��~,�����+��mmIօ/����K���|?����|�z]"���l
+�P�;)��b��Ć5��2��të��U�[(��{��`�~$���^u���'����3���_5E��n�Z�&2�izyk"�c�56�F�K����|��<}�Sۃ9���x0�W|j��2��)9rN1���Q��������22�|ʟ��]�_�x��k�Q�)�Ҋ��=k�O��*��d����;�KU��$��'�K �����B7@����͵ ���Uę��(<��c�[:�7n�g6�� ���^~��+� r
+endstream
+endobj
+373 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F201 90 0 R /F212 94 0 R /F470 595 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+374 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.14778/3476249.3476258) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 177.094 677.264 295.041 686.769 ] /Subtype /Link /Type /Annot >>
+endobj
+375 0 obj
+<< /A << /S /URI /Type /Action /URI (https://doi.org/10.14778/3476249.3476258) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 70.076 669.135 86.893 676.069 ] /Subtype /Link /Type /Annot >>
+endobj
+376 0 obj
+<< /A << /S /URI /Type /Action /URI (https://openreview.net/forum?id=HJlXC3EtwB) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 334.031 617.528 488.38 626.833 ] /Subtype /Link /Type /Annot >>
+endobj
+377 0 obj
+<< /A << /S /URI /Type /Action /URI (https://eprint.iacr.org/2024/1255) >> /Border [ 0 0 0 ] /C [ 0 1 1 ] /H /I /Rect [ 444.791 547.75 551.272 557.107 ] /Subtype /Link /Type /Annot >>
+endobj
+378 0 obj
+<< /Filter /FlateDecode /Length 3068 >>
+stream
+xڝY[s۶~ϯ��h&�  HϜ�8v�K�Ա�ܚ>�-��H��$ί� R$E%����c|����?X�g�����ݳ�W�O�K��=~ ���L�-�$���_w�����A�?�yP��v�f�$�r2 xH�ODLT�|�ՓU���v|�*Pͬ+�=o�ɘ$��:��O���-p�[�L<O&�'��� d�AF)P���7�����ɔ9�כb��,�WS2���b2��`�$�8��o
+/�o`!�z�d�J�˩B�y���a�Xa�{�(�Y�6�� U�ޒ� BA�7V����תJ��M�
+hJʪ����~2�I^����̈��W�J�a��CwD D� ��r���swxwu�ž���hp�f�g��F�o�н�c�����h0�r�ƂJ�W�Ͼ�͋��6]q�?�������(,+�^@����\��BPXÏi_�UUmʣ��E���XR�'etȸ {��7\����Ӆ0QO{���J�T���؋C֨^8�z�`��p��v��ɥ��VӰ�)� �5�"'�y����T�a?�67�.(�N��u~���gӅQ��z���M��0!@�С�*��g�#`�� R/��T�hI�y0�5�7��j�n*(5t�$(�J�艈k����j��
+Β,)�.p��)���$���[mD�cS¢3 ߀T� \V+�Ȫ�Ȭ���i�{r������-=ɳ��ڝl�ֱ��ۤlxg�� QX�"�S{�f�4ߘ��f���"�+^77 �I�eFT���0��H'2F� X�#t
+����9h�,w�<��G68#�j [�C�Lb�+�wsS��������&<E{W4
+�� V�����C�?ʩ��|r�� .��0�5 �p�W�t�^�b��3�`:8�����V0v*$#�`�$��E Br ӣ�3[��ڬ�l��~f׹�8�}T�ܛ] ަ��1����<�L;
+�z~D�X��5`qV��=D� ��D�Ĉ�ģ���N-(%�|��� 1o�k�)�c�67D��|���2�U���F��� ��u
+P\���{l��!���䰓�)�_u�� �3��/��#�[-�h���1�>�` U�Y%6���Ze�kp�1�P<ϫ������6hy�v���Xsa���,T���
+�`ӊ$�(-Ԟc�5��T�Lݧ �����U���?5Pg_@�g:�0�K�a�xc�6�5A�� u�k�4�cp��Q����>Hi4Rʸ'�����0�2�4��F�Xi0`�,.�N��r/�v��+4{���vm�(��v<*]k����qd�3����)��B�|�ui�| ~ba���g�e���#t���8N����� f �-�kO�� �U��, p|����9�c����h������<���א�����Do0(�c0/���!���5���F��:����7}��˅����Ўі�A �#,�3X�qv����>S�@F�/?���5���;�e� ͙��0��,C���ZF6�`";�� �Lu�X3aF߀������#�#* xb֗2�SQ�p��(@�{�3글%H�#�!�\;D� ݵ ~s������j݄x��'�V�vQ�e���4����n��Л�*�c�eO%�|��*o��W�7n�Z���_��cm<|$I�q���$ɏ��̆��Hd�cl�/l�{�������^{��.��q�Wy�-�%��gsM�@-J\[�gm!��Ab�3�£B .�*�gv q'�Y�;*��46�XpHdm� ��۸�C�>�^J�p�d��|�G�F�3u�'H?�I���Fl�I�k=_�$��Y�~��۶6�l�6c389;����|n�d�`(V7��^�t�$��a��*Ѝm�u��L��o�h��G ���z�P!�%��ޓ��u�������>f1�KI|�Ei 
+�3g��S�V�n0~����Ra���V*k�ZM]���m����>�d�ld��p*b�� ��t3�ʇ��Ò1��c0~�x�&�'%D�5��v�Ɇ��m�ıHa�q?k����I�ف�y��|���\�����9
+ݹ�n\�I��>4�.#��)S�MHe�)��@�����@cIye� y�C�}���
+.Y�Q��?e�v�B7)�|�d�<_��:|�t /��oz������ {Y}{у������#��W)�zt#dM�����m�Yprc�9cՔu�PBmȚ�I;���
+�{�UZR� T� ��w�i���x<wT�7ce��iʛ�Km�`��M��N��E%4o�L�D復�W����e
+Mԋ�����I�9��%z1�ͱ�ea�
+G.: 5h�]��>=Ų$�`��.n���Ap�ņ��R�l�Y�rnC�~���؍������?&���Zg����%D���Z3������Dx��ů���֡�ٰ$ĘSa�FUIꚯ���X�;�\�
+�*��v��)`��2��"'l�=��%�&� =iC����TMb�g p���mE[�����M�\/]ɺ���.���e(��zhV��|�8���H>�ٺ�c�ԅV�p}6�bٓ!kp�C
+x�oQP��-1h�)� O+� �T�߉v�'��H/bl�� `������w�(�dJu�����V�Tmv�6�}�g��Y�`�f'��9�\���f�ST���G��b]J�^������^Ǥ��Y��1ˁ�7шg-q���rt�n���-��I;a���2e.�6����qF{�y;�~ܷ?�aԠjoT�C�Z�u4J���������%M�쿆��f�����g ���-UK�,��Xo�Ԧ��&Ė٭�����M]�*�#��˷ܷ�������L 9�3�i�����@+F���|(d7��d� �:��8�I�٠��6B6B��9��`�k�a�:Y�[�b�b��N�J��x�c���F�U���p?��q����F���E=�FP>�l�1��}OJ���K���7��Xʝ��g$�^���7�u��Xݤ,��_���2
+o���j,�6��:�A�q�6D�۷�w������
+endstream
+endobj
+379 0 obj
+<< /ColorSpace 87 0 R /ExtGState 88 0 R /Font << /F201 90 0 R /F212 94 0 R /F470 595 0 R /F551 596 0 R >> /Pattern 97 0 R /ProcSet [ /PDF /Text ] >>
+endobj
+380 0 obj
+<< /D [ 47 0 R /XYZ 65.955 704.471 null ] >>
+endobj
+381 0 obj
+<< /D [ 47 0 R /XYZ 65.955 584.919 null ] >>
+endobj
+382 0 obj
+<< /D [ 47 0 R /XYZ 65.955 572.964 null ] >>
+endobj
+383 0 obj
+<< /D [ 47 0 R /XYZ 65.955 559.679 null ] >>
+endobj
+384 0 obj
+<< /D [ 47 0 R /XYZ 65.955 547.724 null ] >>
+endobj
+385 0 obj
+<< /D [ 47 0 R /XYZ 65.955 533.417 null ] >>
+endobj
+386 0 obj
+<< /D [ 49 0 R /XYZ 65.955 510.942 null ] >>
+endobj
+387 0 obj
+<< /D [ 49 0 R /XYZ 65.955 498.986 null ] >>
+endobj
+388 0 obj
+<< /D [ 49 0 R /XYZ 65.955 487.031 null ] >>
+endobj
+389 0 obj
+<< /D [ 49 0 R /XYZ 65.955 475.076 null ] >>
+endobj
+390 0 obj
+<< /D [ 49 0 R /XYZ 65.955 463.121 null ] >>
+endobj
+391 0 obj
+<< /D [ 47 0 R /XYZ 65.955 680.56 null ] >>
+endobj
+392 0 obj
+<< /D [ 49 0 R /XYZ 65.955 448.839 null ] >>
+endobj
+393 0 obj
+<< /D [ 47 0 R /XYZ 65.955 668.605 null ] >>
+endobj
+394 0 obj
+<< /D [ 47 0 R /XYZ 65.955 656.65 null ] >>
+endobj
+395 0 obj
+<< /D [ 47 0 R /XYZ 65.955 644.695 null ] >>
+endobj
+396 0 obj
+<< /D [ 47 0 R /XYZ 65.955 632.74 null ] >>
+endobj
+397 0 obj
+<< /D [ 47 0 R /XYZ 65.955 620.785 null ] >>
+endobj
+398 0 obj
+<< /D [ 47 0 R /XYZ 65.955 608.829 null ] >>
+endobj
+399 0 obj
+<< /D [ 47 0 R /XYZ 65.955 596.874 null ] >>
+endobj
+400 0 obj
+<< /D [ 9 0 R /XYZ 54 638.463 null ] >>
+endobj
+401 0 obj
+<< /D [ 9 0 R /XYZ 54.498 96.339 null ] >>
+endobj
+402 0 obj
+<< /D [ 50 0 R /XYZ 321.326 126.771 null ] >>
+endobj
+403 0 obj
+<< /D [ 50 0 R /XYZ 321.326 117.078 null ] >>
+endobj
+404 0 obj
+<< /D [ 51 0 R /XYZ 54 372.096 null ] >>
+endobj
+405 0 obj
+<< /D [ 51 0 R /XYZ 54 334.048 null ] >>
+endobj
+406 0 obj
+<< /D [ 51 0 R /XYZ 54 286.512 null ] >>
+endobj
+407 0 obj
+<< /D [ 47 0 R /XYZ 54 725.978 null ] >>
+endobj
+408 0 obj
+<< /D [ 49 0 R /XYZ 54 725.978 null ] >>
+endobj
+409 0 obj
+<< /D [ 50 0 R /XYZ 54 725.978 null ] >>
+endobj
+410 0 obj
+<< /D [ 58 0 R /XYZ 54 241.793 null ] >>
+endobj
+411 0 obj
+<< /D [ 58 0 R /XYZ 54 271.681 null ] >>
+endobj
+412 0 obj
+<< /D [ 58 0 R /XYZ 317.955 201.943 null ] >>
+endobj
+413 0 obj
+<< /D [ 59 0 R /XYZ 54 630.336 null ] >>
+endobj
+414 0 obj
+<< /D [ 57 0 R /XYZ 54 245.778 null ] >>
+endobj
+415 0 obj
+<< /D [ 57 0 R /XYZ 57.706 574.545 null ] >>
+endobj
+416 0 obj
+<< /D [ 57 0 R /XYZ 57.706 534.695 null ] >>
+endobj
+417 0 obj
+<< /D [ 58 0 R /XYZ 54 421.121 null ] >>
+endobj
+418 0 obj
+<< /D [ 57 0 R /XYZ 57.706 464.956 null ] >>
+endobj
+419 0 obj
+<< /D [ 57 0 R /XYZ 57.706 435.068 null ] >>
+endobj
+420 0 obj
+<< /D [ 57 0 R /XYZ 57.706 415.143 null ] >>
+endobj
+421 0 obj
+<< /D [ 57 0 R /XYZ 57.706 335.442 null ] >>
+endobj
+422 0 obj
+<< /D [ 57 0 R /XYZ 54 176.04 null ] >>
+endobj
+423 0 obj
+<< /D [ 57 0 R /XYZ 54 146.152 null ] >>
+endobj
+424 0 obj
+<< /D [ 58 0 R /XYZ 317.955 361.345 null ] >>
+endobj
+425 0 obj
+<< /D [ 57 0 R /XYZ 317.955 680.149 null ] >>
+endobj
+426 0 obj
+<< /D [ 57 0 R /XYZ 54 96.339 null ] >>
+endobj
+427 0 obj
+<< /D [ 57 0 R /XYZ 317.955 640.299 null ] >>
+endobj
+428 0 obj
+<< /D [ 57 0 R /XYZ 317.955 720 null ] >>
+endobj
+429 0 obj
+<< /D [ 58 0 R /XYZ 317.955 630.336 null ] >>
+endobj
+430 0 obj
+<< /D [ 58 0 R /XYZ 317.955 271.681 null ] >>
+endobj
+431 0 obj
+<< /D [ 57 0 R /XYZ 57.706 484.882 null ] >>
+endobj
+432 0 obj
+<< /D [ 57 0 R /XYZ 317.955 480.897 null ] >>
+endobj
+433 0 obj
+<< /D [ 57 0 R /XYZ 317.955 520.747 null ] >>
+endobj
+434 0 obj
+<< /D [ 58 0 R /XYZ 54 391.233 null ] >>
+endobj
+435 0 obj
+<< /D [ 57 0 R /XYZ 317.955 441.046 null ] >>
+endobj
+436 0 obj
+<< /D [ 58 0 R /XYZ 317.955 680.149 null ] >>
+endobj
+437 0 obj
+<< /D [ 58 0 R /XYZ 54 520.747 null ] >>
+endobj
+438 0 obj
+<< /D [ 58 0 R /XYZ 54 690.112 null ] >>
+endobj
+439 0 obj
+<< /D [ 57 0 R /XYZ 317.955 411.158 null ] >>
+endobj
+440 0 obj
+<< /D [ 57 0 R /XYZ 317.955 321.494 null ] >>
+endobj
+441 0 obj
+<< /D [ 57 0 R /XYZ 317.955 281.644 null ] >>
+endobj
+442 0 obj
+<< /D [ 57 0 R /XYZ 317.955 211.905 null ] >>
+endobj
+443 0 obj
+<< /D [ 57 0 R /XYZ 54 275.666 null ] >>
+endobj
+444 0 obj
+<< /D [ 57 0 R /XYZ 317.955 172.055 null ] >>
+endobj
+445 0 obj
+<< /D [ 58 0 R /XYZ 54 620.374 null ] >>
+endobj
+446 0 obj
+<< /D [ 58 0 R /XYZ 54 570.56 null ] >>
+endobj
+447 0 obj
+<< /D [ 58 0 R /XYZ 54 660.224 null ] >>
+endobj
+448 0 obj
+<< /D [ 58 0 R /XYZ 54 540.672 null ] >>
+endobj
+449 0 obj
+<< /D [ 57 0 R /XYZ 57.706 504.807 null ] >>
+endobj
+450 0 obj
+<< /D [ 57 0 R /XYZ 54 225.853 null ] >>
+endobj
+451 0 obj
+<< /D [ 58 0 R /XYZ 54 351.382 null ] >>
+endobj
+452 0 obj
+<< /D [ 57 0 R /XYZ 317.955 560.598 null ] >>
+endobj
+453 0 obj
+<< /D [ 57 0 R /XYZ 317.955 600.448 null ] >>
+endobj
+454 0 obj
+<< /D [ 58 0 R /XYZ 54 301.569 null ] >>
+endobj
+455 0 obj
+<< /D [ 58 0 R /XYZ 54 321.494 null ] >>
+endobj
+456 0 obj
+<< /D [ 58 0 R /XYZ 317.955 172.055 null ] >>
+endobj
+457 0 obj
+<< /D [ 58 0 R /XYZ 54 201.943 null ] >>
+endobj
+458 0 obj
+<< /D [ 57 0 R /XYZ 317.955 251.756 null ] >>
+endobj
+459 0 obj
+<< /D [ 57 0 R /XYZ 317.955 371.308 null ] >>
+endobj
+460 0 obj
+<< /D [ 58 0 R /XYZ 54 172.055 null ] >>
+endobj
+461 0 obj
+<< /D [ 58 0 R /XYZ 54 132.204 null ] >>
+endobj
+462 0 obj
+<< /D [ 58 0 R /XYZ 317.955 590.486 null ] >>
+endobj
+463 0 obj
+<< /D [ 58 0 R /XYZ 317.955 560.598 null ] >>
+endobj
+464 0 obj
+<< /D [ 58 0 R /XYZ 317.955 510.785 null ] >>
+endobj
+465 0 obj
+<< /D [ 58 0 R /XYZ 317.955 480.897 null ] >>
+endobj
+466 0 obj
+<< /D [ 58 0 R /XYZ 317.955 441.046 null ] >>
+endobj
+467 0 obj
+<< /D [ 58 0 R /XYZ 317.955 401.196 null ] >>
+endobj
+468 0 obj
+<< /D [ 58 0 R /XYZ 54 480.897 null ] >>
+endobj
+469 0 obj
+<< /D [ 58 0 R /XYZ 317.955 720 null ] >>
+endobj
+470 0 obj
+<< /D [ 57 0 R /XYZ 57.706 375.293 null ] >>
+endobj
+471 0 obj
+<< /D [ 58 0 R /XYZ 317.955 321.494 null ] >>
+endobj
+472 0 obj
+<< /D [ 57 0 R /XYZ 54 305.554 null ] >>
+endobj
+473 0 obj
+<< /D [ 59 0 R /XYZ 54 720 null ] >>
+endobj
+474 0 obj
+<< /D [ 59 0 R /XYZ 54 670.187 null ] >>
+endobj
+475 0 obj
+<< /D [ 58 0 R /XYZ 317.955 142.167 null ] >>
+endobj
+476 0 obj
+<< /D [ 57 0 R /XYZ 317.955 102.316 null ] >>
+endobj
+477 0 obj
+<< /D [ 59 0 R /XYZ 54 600.448 null ] >>
+endobj
+478 0 obj
+<< /D [ 59 0 R /XYZ 54 560.598 null ] >>
+endobj
+479 0 obj
+<< /D [ 59 0 R /XYZ 54 530.71 null ] >>
+endobj
+480 0 obj
+<< /D [ 59 0 R /XYZ 317.955 720 null ] >>
+endobj
+481 0 obj
+<< /D [ 59 0 R /XYZ 317.955 690.112 null ] >>
+endobj
+482 0 obj
+<< /D [ 59 0 R /XYZ 317.955 620.374 null ] >>
+endobj
+483 0 obj
+<< /D [ 59 0 R /XYZ 317.955 660.224 null ] >>
+endobj
+484 0 obj
+<< /D [ 59 0 R /XYZ 317.955 580.523 null ] >>
+endobj
+485 0 obj
+<< /D [ 59 0 R /XYZ 317.955 550.635 null ] >>
+endobj
+486 0 obj
+<< /D [ 59 0 R /XYZ 317.955 510.785 null ] >>
+endobj
+487 0 obj
+<< /D [ 50 0 R /XYZ 367.621 477.429 null ] >>
+endobj
+488 0 obj
+<< /D [ 54 0 R /XYZ 54 725.978 null ] >>
+endobj
+489 0 obj
+<< /D [ 54 0 R /XYZ 54 532.376 null ] >>
+endobj
+490 0 obj
+<< /D [ 54 0 R /XYZ 317.955 725.978 null ] >>
+endobj
+491 0 obj
+<< /D [ 55 0 R /XYZ 54 725.978 null ] >>
+endobj
+492 0 obj
+<< /D [ 55 0 R /XYZ 317.955 725.978 null ] >>
+endobj
+493 0 obj
+<< /D [ 55 0 R /XYZ 317.955 424.975 null ] >>
+endobj
+494 0 obj
+<< /D [ 47 0 R /XYZ 317.955 725.978 null ] >>
+endobj
+495 0 obj
+<< /D [ 48 0 R /XYZ 54 725.978 null ] >>
+endobj
+496 0 obj
+<< /D [ 50 0 R /XYZ 317.955 725.978 null ] >>
+endobj
+497 0 obj
+<< /D [ 52 0 R /XYZ 54 725.978 null ] >>
+endobj
+498 0 obj
+<< /D [ 52 0 R /XYZ 54 400.904 null ] >>
+endobj
+499 0 obj
+<< /D [ 9 0 R /XYZ 53 747.899 null ] >>
+endobj
+500 0 obj
+<< /D [ 54 0 R /XYZ 53 747.899 null ] >>
+endobj
+501 0 obj
+<< /D [ 55 0 R /XYZ 53 747.899 null ] >>
+endobj
+502 0 obj
+<< /D [ 56 0 R /XYZ 53 747.899 null ] >>
+endobj
+503 0 obj
+<< /D [ 57 0 R /XYZ 53 747.899 null ] >>
+endobj
+504 0 obj
+<< /D [ 58 0 R /XYZ 53 747.899 null ] >>
+endobj
+505 0 obj
+<< /D [ 59 0 R /XYZ 53 747.899 null ] >>
+endobj
+506 0 obj
+<< /D [ 46 0 R /XYZ 53 747.899 null ] >>
+endobj
+507 0 obj
+<< /D [ 47 0 R /XYZ 53 747.899 null ] >>
+endobj
+508 0 obj
+<< /D [ 48 0 R /XYZ 53 747.899 null ] >>
+endobj
+509 0 obj
+<< /D [ 49 0 R /XYZ 53 747.899 null ] >>
+endobj
+510 0 obj
+<< /D [ 50 0 R /XYZ 53 747.899 null ] >>
+endobj
+511 0 obj
+<< /D [ 51 0 R /XYZ 53 747.899 null ] >>
+endobj
+512 0 obj
+<< /D [ 52 0 R /XYZ 53 747.899 null ] >>
+endobj
+513 0 obj
+<< /D [ 53 0 R /XYZ 53 747.899 null ] >>
+endobj
+514 0 obj
+<< /D [ 9 0 R /XYZ 54 638.463 null ] >>
+endobj
+515 0 obj
+<< /D [ 57 0 R /XYZ 54 591.482 null ] >>
+endobj
+516 0 obj
+<< /D [ 57 0 R /XYZ 54 574.378 null ] >>
+endobj
+517 0 obj
+<< /D [ 9 0 R /XYZ 54 642.448 null ] >>
+endobj
+518 0 obj
+<< /D [ 50 0 R /XYZ 54 703.345 null ] >>
+endobj
+519 0 obj
+<< /D [ 9 0 R /XYZ 54 351.948 null ] >>
+endobj
+520 0 obj
+<< /D [ 46 0 R /XYZ 54 351.752 null ] >>
+endobj
+521 0 obj
+<< /D [ 47 0 R /XYZ 317.955 154.76 null ] >>
+endobj
+522 0 obj
+<< /D [ 48 0 R /XYZ 317.955 427.975 null ] >>
+endobj
+523 0 obj
+<< /D [ 50 0 R /XYZ 54 401.888 null ] >>
+endobj
+524 0 obj
+<< /D [ 51 0 R /XYZ 54 410.706 null ] >>
+endobj
+525 0 obj
+<< /D [ 55 0 R /XYZ 317.955 222.506 null ] >>
+endobj
+526 0 obj
+<< /D [ 56 0 R /XYZ 54 275.308 null ] >>
+endobj
+527 0 obj
+<< /D [ 56 0 R /XYZ 317.955 162.73 null ] >>
+endobj
+528 0 obj
+<< /D [ 46 0 R /XYZ 54 277.761 null ] >>
+endobj
+529 0 obj
+<< /D [ 46 0 R /XYZ 317.955 268.334 null ] >>
+endobj
+530 0 obj
+<< /D [ 47 0 R /XYZ 54 320.139 null ] >>
+endobj
+531 0 obj
+<< /D [ 48 0 R /XYZ 317.955 352.02 null ] >>
+endobj
+532 0 obj
+<< /D [ 49 0 R /XYZ 317.955 591.123 null ] >>
+endobj
+533 0 obj
+<< /D [ 51 0 R /XYZ 54 252.261 null ] >>
+endobj
+534 0 obj
+<< /D [ 53 0 R /XYZ 54 720 null ] >>
+endobj
+535 0 obj
+<< /D [ 53 0 R /XYZ 317.955 515.407 null ] >>
+endobj
+536 0 obj
+<< /D [ 53 0 R /XYZ 317.955 179.029 null ] >>
+endobj
+537 0 obj
+<< /D [ 56 0 R /XYZ 54 208.558 null ] >>
+endobj
+538 0 obj
+<< /D [ 56 0 R /XYZ 317.955 651.563 null ] >>
+endobj
+539 0 obj
+<< /D [ 56 0 R /XYZ 317.955 475.137 null ] >>
+endobj
+540 0 obj
+<< /D [ 51 0 R /XYZ 54 228.045 null ] >>
+endobj
+541 0 obj
+<< /Differences [ 27 /f_i /f_f_i /f_f /f_l 40 /parenleft /parenright 45 /hyphen /period 48 /zero /one /two /three /four /five /six /seven /eight /nine /colon 65 /A /B /C /D /E /F /G /H /I 76 /L /M /N /O /P /Q /R /S /T /U /V /W 91 /bracketleft 93 /bracketright 97 /a /b /c /d /e /f /g /h /i 107 /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z ] /Type /Encoding >>
+endobj
+542 0 obj
+<< /Ascent 714 /CapHeight 628 /CharSet (/A/B/C/D/E/F/G/H/I/L/M/N/O/P/Q/R/S/T/U/V/W/a/b/bracketleft/bracketright/c/colon/d/e/eight/f/f_f/f_f_i/f_i/f_l/five/four/g/h/hyphen/i/k/l/m/n/nine/o/one/p/parenleft/parenright/period/q/r/s/seven/six/t/three/two/u/v/w/x/y/z/zero) /Descent -231 /Flags 4 /FontBBox [ -1082 -328 6171 1014 ] /FontFile 597 0 R /FontName /SVARXO+LinLibertineTB /ItalicAngle 0 /StemV 130 /Type /FontDescriptor /XHeight 433 >>
+endobj
+543 0 obj
+<< /Filter /FlateDecode /Length 874 >>
+stream
+xڕUMo�:��W���A5iE_�a��, @��Eo�D�z�%W����쮓��ڃ��jvwv(�7o�<Ķw>N�i�՟�������=E77��^�~�?y������^}�����궺��~~��C{�t�����O��JAu�����C��������a�&�w۳��y�g������5�<��!d�]�
+l��lEm���܏�{e�i�C`3t�x�#�h!S��u�}?t���v42K���,+�o��Z$?<�g��c�Z�����<O�4��h�y���O��5�����t�Чt�^���C����ѫ�������|�jIkÓ�c�ϧm���䣕�k�j�u��?�L�)���� \݄��N�u�2H6K
+�
+���I, 0ZE�iÁ"20r��30J0���Q�K�5�V55��`lhM�  �6�Ҡh����R��0ƿ�Y�����$q(� aw����ʀ�5L�wıh�S���c �sn\p��%�6���pZ;�K����f�Q�$���a �0{���5�5\3�v�z]����bXo^״����9�An�Cs.;
+���6��g�d�>E�=�;�`��мE����1q
+�
+������>�1�Ѣb O��1էYM�}/��Y��}K֟�_�~zOJ֟BO��3�e�f/YN|֟�u��\���X�΄rYgB������>[�b�g�h��X|&���^V|ƻg�g���3���3q�g�n�g��3tZ��[��Y����o�g�t�3�:�|'>���g�q�3�Ϙ݉����_��OX���������N����]X��߄�:�?85�J�C#�9u#��28~q����e��m@w��8����rM����G���n��s���6
+endstream
+endobj
+544 0 obj
+[ 641 947 716 680 631 0 266 376 514 514 637 729 253 315 315 433 537 244 358 244 316 514 514 514 514 514 514 514 514 514 514 256 256 512 551 512 430 988 740 654 706 734 609 545 732 817 367 373 736 577 899 740 730 614 730 716 504 652 732 700 1028 718 624 624 397 307 397 518 486 253 506 542 456 561 489 391 521 619 322 312 613 325 905 616 551 581 573 428 427 358 598 529 777 561 558 452 ]
+endobj
+545 0 obj
+<< /Differences [ 16 /quotedblleft /quotedblright 21 /endash /emdash 27 /f_i /f_f_i /f_f /f_l /f_f_l 34 /quotedbl /numbersign 37 /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less 62 /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft 93 /bracketright 95 /underscore 97 /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z 159 /section 225 /aacute 231 /ccedilla 233 /eacute 252 /udieresis ] /Type /Encoding >>
+endobj
+546 0 obj
+<< /Ascent 0 /CapHeight 0 /CharSet (/A/B/C/D/E/F/G/H/I/J/K/L/M/N/O/P/Q/R/S/T/U/V/W/X/Y/Z/a/aacute/ampersand/asterisk/at/b/bracketleft/bracketright/c/ccedilla/colon/comma/d/dagger/e/eacute/eight/emdash/endash/f/f_f/f_f_i/f_f_l/f_i/f_l/five/four/g/greater/h/hyphen/i/j/k/l/less/m/n/nine/numbersign/o/one/p/parenleft/parenright/percent/period/plus/q/question/quotedbl/quotedblleft/quotedblright/quoteright/r/s/section/semicolon/seven/six/slash/t/three/two/u/udieresis/underscore/v/w/x/y/z/zero) /Descent 0 /Flags 4 /FontBBox [ -1082 -257 6171 1125 ] /FontFile 598 0 R /FontName /DHRMAA+LinLibertineT /ItalicAngle 0 /StemV 79 /Type /FontDescriptor /XHeight 429 >>
+endobj
+547 0 obj
+<< /Filter /FlateDecode /Length 877 >>
+stream
+xڕUM��0��W��J�!�N�/TUr�FZ Į7�&��M�4=��of� �Z=O�̼yq�7�Bۍ;������ej]X}ܞ���zl/G7���u��>=�W���}p����껡��z���.����N*�S?�R�G�>�o�~����4��{ ��>�M�gv��=K�N�$�(�����_yʓտ�5��s?�y������U�v������!���M2��a��D���YV����H~x>��x7��`�R�/��y��i�����Թ�����I�)���� O�`�V���N����ѩ�y����|r*���9ڱs�Ӷu�vxr�J�Z5�:pC��3s�n�n<W7�/�q�V�&���HH9�@d���c�=N�>���Qe��Q�Q� �
+]j��q����9�cCCh
+l�hP��E�4���p �1�u�"�����Nb����.��\GU
+�a�^Ǣ�N8^��-pƹp�q���[��i]r_�T/�k�5M̹��Pf/c�`�f���k����۬^�/���֛�5�����"�-#z��C�T3� ���������a �1��1c�ϗ�7�䯡��1��c��<?4���%/���%ch�+��(�S}��$�y�: ֟�o��� �O��`� ��?�\֟b���g�g�)�Yg����^ �S.�)�u���g�Y�����������ˊ�؋V|F_+>�O+>G|��V|�~+>C��1������� �V|��R|F�R|���/�g�)�g��1{)>_|&~Χa90K)�c�R��>,���߉�����TG���^ |h#�0�n��S�1.����L���F�����^.��xB�趻^�X}j�����
+endstream
+endobj
+548 0 obj
+[ 375 375 375 543 543 548 742 0 271 271 272 560 829 582 540 815 250 288 336 465 465 637 705 268 298 298 369 550 220 338 220 323 465 465 465 465 465 465 465 465 465 465 236 236 550 550 550 435 895 695 588 646 701 557 485 685 730 297 322 637 528 839 699 702 541 702 587 485 597 661 652 951 660 575 604 356 287 356 518 486 268 457 493 428 506 447 310 500 538 271 272 512 264 790 542 504 519 503 372 390 316 531 497 747 490 515 424 277 205 277 449 338 695 695 646 646 701 557 557 685 528 528 528 699 699 725 702 587 587 485 485 485 597 597 661 661 575 604 604 604 598 297 506 473 457 457 428 428 528 447 447 500 264 290 264 542 542 528 504 372 372 390 390 390 374 316 531 531 515 424 424 424 542 288 435 465 695 695 695 695 695 695 865 646 557 557 557 557 297 297 297 297 701 699 702 702 702 702 702 869 702 661 661 661 667 575 527 0 457 457 457 457 457 457 687 428 447 447 447 447 271 271 271 271 486 542 504 504 504 504 504 778 504 531 531 531 531 ]
+endobj
+549 0 obj
+<< /Ascent 707 /CapHeight 707 /CharSet (/S/arrowleft/asteriskmath/bar/braceleft/braceright/bracketleft/bracketright/bullet/dagger/element/emptyset/existential/greaterequal/intersection/lessequal/multiply/parenleft/parenright/periodcentered/prime/propersubset/radical/slash/union/universal) /Descent -152 /Flags 4 /FontBBox [ -47 -944 2835 838 ] /FontFile 599 0 R /FontName /KLFPWG+txsys /ItalicAngle 0 /StemV 52 /Type /FontDescriptor /XHeight 400 >>
+endobj
+550 0 obj
+<< /Filter /FlateDecode /Length 980 >>
+stream
+x�mVMo�H��+�C������nY�0R;3�D��:��"�`�6�~�U��Y���W�Ut�����q���7����i���ߔ���]54�����޷������?ǡy�s|_>T}7 �}�vi���s�¿v�j�<����{3�;�O��K�6w�F����߂�g���ſq1���ǩ�o��*�ġo���h�舷We/]ߎ����"��k��~�Sh�ߧٟ��!������r��wR�%��[?v�k|������r>�y��E��ǭ C�ߏ'o?+������cEϒU5C������N�}���}����e�痫mlE~���}��*`��� �DJ�I@�s5�`�d�.�DM��("+�k��0aAP<&+Xh���AG"N�[���]
+��-b4�Hv�0�� ��: $��� �ar��B��� d�xi�V %�!K�
+���]4�f�QP'�u�ru�!,׫Kay��p/�Za%���RC�}=��\O���8.��D`!)D��E�"��%���0V��°/� �>��tԢ��q*�����K4�!���� �Ȍ�.�s�AyJ�,��J2F��W���(�Q!��1�;�d_�/����gFB����A��0�S^EC��Wt.��8-hDS��z�5ٓN�Ws�:5�+ȗ�֡�wI`5��$��KԒp4lR�W��wY���W0�~�gg��X��i8�E|��AL�y�`8oE�@�)�s��b��K}s�� �d�:�6��\Y�1�،�@���fI�1dS1&���l͘����@CFu9 �ܬ|no��\��s�>�7g��7��U${� ��k֌�z"T����NU�㽣����cN�a�:˾��=�=-� ���B�`��`��;X�7��`��|���3*��)�1f���}�s/�Ϫ�������r�����u��.%\��]s�p�-K7��y8Ë�������u�x�u
+endstream
+endobj
+551 0 obj
+[ 250 636 471 636 512 636 636 636 636 636 636 636 862 497 497 636 636 636 636 636 636 636 636 636 636 636 636 918 918 636 636 1024 1024 499 499 1024 1024 1024 636 1024 1024 550 550 1034 1014 1024 636 347 853 536 536 634 634 0 0 587 587 640 500 908 703 712 712 639 870 718 648 860 622 669 704 876 650 775 796 749 1080 822 703 709 703 680 679 678 897 892 1202 738 797 865 654 654 654 654 654 466 466 371 371 371 371 411 411 363 363 200 400 499 550 460 264 703 727 664 409 654 654 636 636 500 500 500 453 578 531 605 542 387 642 908 443 677 957 443 443 513 1173 456 456 376 633 889 418 663 928 418 418 472 1134 424 440 727 670 587 500 697 460 333 333 333 333 333 333 333 370 333 333 548 454 454 454 454 454 454 280 175 334 389 421 275 350 425 334 564 333 333 333 333 ]
+endobj
+552 0 obj
+<< /Ascent 437 /CapHeight 437 /CharSet (/comma/period/u1D434/u1D436/u1D437/u1D438/u1D43A/u1D440/u1D441/u1D444/u1D445/u1D449/u1D44A/u1D44B/u1D44E/u1D450/u1D451/u1D452/u1D453/u1D456/u1D458/u1D459/u1D45A/u1D45B/u1D45C/u1D45D/u1D45E/u1D45F/u1D460/u1D461/u1D462/u1D463/u1D465) /Descent -11 /Flags 4 /FontBBox [ -342 -238 1011 786 ] /FontFile 600 0 R /FontName /PEYUND+LibertineMathMI /ItalicAngle -12 /StemV 82 /Type /FontDescriptor /XHeight 400 >>
+endobj
+553 0 obj
+<< /Filter /FlateDecode /Length 592 >>
+stream
+x�}T�n�@��+fH�@���B�/ iI��V{5�@,�m�q��k�mr������.Ӟ�z���yu�3뙳�V}��Y�Mkc2����Ȳ{�2��xھ����v�c�pmʢ{"���}.G��E�<���������� ��(�6�>��١/��8��Ew&��BF��S���#����&�9�D�eVL��[�l>�},ʼ���h�&ˋ��E�]�*$�m'/��X�%��a�5W���1kr��M��4�����0n�V,�G��<zM/���.�_k�L��Ӭ�e[��l��$�%�+�L��!��˙����q�Z��.���b"N�a�( B E� � �X�}zD��D�e� G�d�@� M� ��@⺅9���m�ʮ�I��B���kTw��%�$Cxj>��Y�u'ȯ����>���)灲Sq�:7�`pm 8�V�|#� �����}
+g���z�5�@�0�u�Zv��q�}�����z�ֳ�C\��>h��7�!������uo���Z����3�������b��;��MC룖T-ր���uU#K��`�!zK��aL
+endstream
+endobj
+554 0 obj
+[ 667 557 616 667 526 457 664 673 280 315 637 519 804 666 668 499 668 555 454 544 634 597 858 628 552 578 486 478 389 489 401 314 499 519 276 259 486 266 783 518 447 489 491 357 353 307 521 391 688 475 503 436 636 668 621 648 691 594 530 670 687 693 478 522 472 458 450 369 402 490 447 258 506 494 451 440 391 525 482 410 521 410 455 546 469 584 630 424 421 507 507 537 454 642 494 539 519 494 494 276 259 381 631 470 511 540 338 462 448 481 425 473 438 469 469 516 465 465 465 465 465 465 465 465 465 465 220 220 ]
+endobj
+555 0 obj
+<< /Differences [ 37 /percent 48 /zero /one /two /three /four /five /six /seven /eight /nine /colon 97 /a 103 /g 105 /i 109 /m /n 114 /r 120 /x ] /Type /Encoding >>
+endobj
+556 0 obj
+<< /Filter /FlateDecode /Length 732 >>
+stream
+xڕU�n�@��+��H��a�!$�ABJ�(���
+�!�62FJ��sT]$ �sϜ��r��e�O�zc}s/ū=֧&�~�}}�nn�:?�m�>Y[آ?=>���Η���"[Te{�ċ*ߝ
+۫�/�ڷ��H�Gܮ�O���ˍmڲ�+��m��U��Y��۴կھ��[_"ʪlw��k�©�'Ղ���ͱ�����UEZ�1��7����mYMךؠQOiQ�y�Y���n�p^~[�_T�������惺���Ma��z�����,O��΢>!��Xv�R�?��V �6�����`�&[q'y]��a��f]�Yo$�X���g�⟳�=6�^9���0�`�4|�!v�2a@@m�LĎ0s�&�F!ܣ {��Q�@R��� �}E��u��.M�Lq��!�f �a<2��ʖ!c��0&� ��SQ.eP������5��8�r���r�4�Kg��x:��"�'�1���j�ix43���ԩR�������F�94Z�D3��q� �8�e8���̸�t���&�&�q��̹� %�7ʘ�>b}�8�Fs�%�0t?���b�9��\lċ��>��ËMy���;�㋍�%N�v�;��.�������Yz���g��]s�g~�Q��g(g�[Kx&�����}����{꾩dx�5jMxZ��!��{=�z�ݗF_vv�y�䧦q��"-����;�P�E?Z�������r
+endstream
+endobj
+557 0 obj
+[ 637 705 268 298 298 369 550 220 338 220 323 465 465 465 465 465 465 465 465 465 465 236 236 288 550 435 435 895 695 588 646 701 557 485 685 730 297 322 637 528 839 699 702 541 702 587 485 597 661 652 951 660 575 604 356 375 356 349 291 268 457 493 428 506 447 310 500 538 271 272 512 264 790 542 504 519 503 372 390 316 531 497 747 490 ]
+endobj
+558 0 obj
+<< /Differences [ 38 /ampersand /quoteright /parenleft /parenright 45 /hyphen /period 48 /zero /one /two /three /four /five /six /seven /eight /nine /colon 63 /question 65 /A /B /C /D /E /F /G /H /I 75 /K /L /M /N /O /P 82 /R /S /T /U /V /W /X /Y 97 /a /b /c /d /e /f /g /h /i 107 /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z ] /Type /Encoding >>
+endobj
+559 0 obj
+<< /Ascent 0 /CapHeight 0 /CharSet (/A/B/C/D/E/F/G/H/I/K/L/M/N/O/P/R/S/T/U/V/W/X/Y/a/ampersand/b/c/colon/d/e/eight/f/five/four/g/h/hyphen/i/k/l/m/n/nine/o/one/p/parenleft/parenright/period/q/question/quoteright/r/registered/s/seven/six/t/three/two/u/v/w/x/y/z/zero) /Descent 0 /Flags 4 /FontBBox [ -634 -312 6171 893 ] /FontFile 601 0 R /FontName /TCFTCN+LinLibertineTI /ItalicAngle -12 /StemV 76 /Type /FontDescriptor /XHeight 429 >>
+endobj
+560 0 obj
+<< /Filter /FlateDecode /Length 876 >>
+stream
+xڕUM��H��W�&����+CKr�!������R{V�-Yf�����3�%��`�T~U�ޓܺ���cl�q���V_�e�N����w�������'�;��~�|P_��}������v��w�����7֏I��7
+���'�G��>�{?������|<ij�������~�̟�����S�����Q��I��5��t���2�֡��z<!�K�Wjq�y�nkj��Y��og�����E���e���p��J-��/��B��E��S�~xV�?�9�<^�磇>���Zu�V��?�N^-~-��槗�WK�6�;9�Z?�g��^��s����~3 ��7�&p� _K���he�l�T05
+)
+�PX`�8��SDž"20r��30J0���QcK�3�V  �4`lȄ�� ���[�:��� hq
+<#`ؿ�,��w��n���8 ֆp� �zYg� �!��X��)����ι7.�N��{��:���%N��
+��1�$܋�a a�2A�g&�kxf���������|W����n��oj˜5�?ӌ�;���,
+�Ԅ6��i�d�]E�3��`�Ԑ�"c��EΘ8{��B��^�o�EQ1�sZԌ�K�0���פ���c �%�O��d�)�%�g�d�)���?�^֟�{��s�����3��u渗%�L��u&��: ��8g /Vr�G+9���3q$g첒3�?+9c��������#9û����J��i%gx��3r��3͗���J��YI��[I��W�3��� =��L��3�W�3�%g�|�3^*�^*��a%��L�oX������H��4�+EN0�9����N�xż��u����Ct��$����<��Ez���ϸ����
+endstream
+endobj
+561 0 obj
+[ 705 268 306 313 433 527 219 333 219 291 444 444 444 444 444 444 444 444 444 444 219 219 487 527 487 405 829 667 557 616 667 526 457 664 673 280 414 637 519 804 666 668 499 668 555 454 544 634 597 909 628 552 578 334 321 334 518 486 268 486 478 389 489 401 314 477 519 276 259 486 266 783 518 447 489 491 357 353 307 521 472 688 475 503 436 ]
+endobj
+562 0 obj
+<< /Differences [ 132 /dagger ] /Type /Encoding >>
+endobj
+563 0 obj
+<< /Filter /FlateDecode /Length 689 >>
+stream
+xڕT�n�0���C��@cLB��"�R�n[5�jo+N)1�C�~�fH�]��=�<�ߛy3`_}{^�i�n��J�b���U�_~/���U�V���ã1��/���x��jmq�\e+� 7�����T� ��$m^�NAq�1?���>4[� �5����|[���o�˖m{�|�,�f�;�ׄ±�'ق��0]ߴ�^�RJ�m�l�H�MƮ���箱u7�&�h� ���jW��n����`+�k��\L^�f?tg��ƛ<u���*�?��i֧�qo�OHo��ٹRnƏ�������&ޜ�F(Z�I�֦?���J�j��� 1/��gl��^Ċ�n��SG�g� o�*��;���aHH9���FvP@C�!�!BH���K�q)8�] T���Y�̊�LB&U��3���9���@1΁c� �� a��
+�T������9�]�?�ѐR�%Ǘ��Z!�*���u��g���œ�̔���1��s���-�x��8��jLZ��8�W�Z1�(���3���LR�L��̀��<'s0�d�FZ��[�)�s2��9$�s�#��R�*�Y����G��<g�9�1?��?���Ai��5ϓ0Ϝ�gq2�)�c�Q4��-��cxE�!��~_��{a��{c\�{�L_.�����\��Νt�_�℺S�v�#T����r�b�TxVI�r
+endstream
+endobj
+564 0 obj
+[ 588 ]
+endobj
+565 0 obj
+<< /D (section.2) /S /GoTo >>
+endobj
+566 0 obj
+<< /A 602 0 R /Next 603 0 R /Parent 99 0 R /Title 604 0 R >>
+endobj
+567 0 obj
+<< /A 605 0 R /Parent 99 0 R /Prev 603 0 R /Title 606 0 R >>
+endobj
+568 0 obj
+<< /A 607 0 R /Next 608 0 R /Parent 6 0 R /Prev 99 0 R /Title 609 0 R >>
+endobj
+569 0 obj
+<feff00320020004200610063006b00670072006f0075006e006400200061006e00640020004d006f007400690076006100740069006f006e>
+endobj
+570 0 obj
+<< /D (section.8) /S /GoTo >>
+endobj
+571 0 obj
+<< /A 610 0 R /Next 611 0 R /Parent 102 0 R /Title 612 0 R >>
+endobj
+572 0 obj
+<< /A 613 0 R /Parent 102 0 R /Prev 611 0 R /Title 614 0 R >>
+endobj
+573 0 obj
+<< /A 615 0 R /Next 102 0 R /Parent 6 0 R /Prev 616 0 R /Title 617 0 R >>
+endobj
+574 0 obj
+<feff0038002000440069007300630075007300730069006f006e00200061006e0064002000460075007400750072006500200057006f0072006b>
+endobj
+575 0 obj
+<< /BaseFont /UZJQXT+txmiaX /FirstChar 56 /FontDescriptor 618 0 R /LastChar 61 /Subtype /Type1 /ToUnicode 619 0 R /Type /Font /Widths 620 0 R >>
+endobj
+576 0 obj
+<< /BaseFont /FBLZCM+LibertineMathMI7 /FirstChar 25 /FontDescriptor 621 0 R /LastChar 71 /Subtype /Type1 /ToUnicode 622 0 R /Type /Font /Widths 623 0 R >>
+endobj
+577 0 obj
+<< /BaseFont /JESRHI+txsyb /FirstChar 82 /FontDescriptor 624 0 R /LastChar 82 /Subtype /Type1 /ToUnicode 625 0 R /Type /Font /Widths 626 0 R >>
+endobj
+578 0 obj
+<< /BaseFont /THUYEG+txexs /FirstChar 205 /FontDescriptor 627 0 R /LastChar 213 /Subtype /Type1 /ToUnicode 628 0 R /Type /Font /Widths 629 0 R >>
+endobj
+579 0 obj
+<< /BaseFont /IIOJER+NewTXMI /FirstChar 157 /FontDescriptor 630 0 R /LastChar 161 /Subtype /Type1 /ToUnicode 631 0 R /Type /Font /Widths 632 0 R >>
+endobj
+580 0 obj
+<< /BBox [ 0 0 515 294 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/bg/anns.pdf) /PTEX.InfoDict 633 0 R /PTEX.PageNumber 1 /Resources << /ColorSpace << /Cs1 634 0 R >> /Font << /TT2 635 0 R /TT4 636 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject << /Im1 637 0 R >> >> /Subtype /Form /Type /XObject /Length 3205 >>
+stream
+xݚ]oI���W4 ,΂���=�.i%B,�����+�lB����s�?�corC������y���y�^�wJ+���gU0~��(��5s�n�������{��)�<e7�n���^�۝��# ����b���k�����f\�!,Faº��SѮ>���!K~M>���g�ϛ�HXDT6�5��E �� ��AtQM-]2l�X�]Z��W���K�Ҹ�>�!nJ�
+��%\�r�h���������k�5!�ȕ�Gy�<+�[V�_��[��N9ym����h̠;h9����6:�����1��n\$�Ֆh�\��:��� ��8�?������Gx������0�ᢷ��IT�ߵ��fy7���,P :�.����h�f��z��~L��:j���V�RR��������̺ɿ2~��[ԉ㼌K�卺������'u����ꏗ2���e���iV�L
+k��z�l19�[6���^7è �L��50~ꒃb#���2p�eKLM]2����(|W/���p�wq�[L��+��>�iJ���u/ǟ�Ñ�!�/@�@]���?T,��- ;�/�#f�� �-���p�g�가�0�9�+��a�mu��� �-n8���_=]�K ����P�qf��;�U,;�����|T.�5�[m,Qw� ���k��!)�xfX/I�,C�F ���a��[�S�9ݦe,`�+�#�E�ρ�i�9e�T7�,3A���Sq���u-�p��໏�������2��l���b��u��h�h$�<��<�d�B\X3 Ab��2�����$0�Vͫ�B�k:.CrP���9N� ���d�;s(��V�0�"��ԃ�f�,�$D�>�!�!ٙ���s⵻���cxma��w�U�m �w���V�}"����FH�}����Y�܌�?f}Z�7��s� L�����W'��Hf�f\ �7\v�Z{�ȄL`�^+j��bk���=��!p+� ��� A7�cM��*!BPȩ� a� s�t ��9uќuSD`���h���Z���Ζ`��+��47�ɀAhUB#�B��#5�RV���jS��L �rQb�nh��+� ����S(���V�=��Rm~n}n}$�J�dH�R �S�����O�JD�!��a�L-C�3���W�G�f)5M�4%�ϵQ�P���i��ۛ���;f5F��LMs-��Ӱ��V�MC}�+ �b5M�C�OE.Ż�f���`��; �����.n��@��?�>��b�Y)��ܯO.���_/�o������B�}J*@Nj��qqL��R'�Q$g�'W� UӐ�� !Y�<^jWC&��0V�E�scJ}Ԝv�4%����zb�`Zi�L}��>��"U��~L��T{z�ʮJh����!�FS��@����3��o&VaJk6�I�
+ZV�٭v��UK�.I&�Z�j����DM˅��ѥ)] = .CB�z ��(���骦�vK<QRZ�h�tu�����(�%<4&�es�C�X�4�E�:M7�t�~�����'r��M�,�zba�8 ��[m'_�YI�D�sҤ$����&b�k����� �@E����\j!/��Tk�  �Lef��~Zý5$��݃�K�]/�w��l�Q��t��K>'�\�� �A�p�M�k�q�,B�`����LC(���M�{�*��6A<XRվT��x�����ܶ�tJ�vf��j�X�ά����ii���s�Hi��,3~��������r�/����O�'C+>����q ����RH�ºˋ�$6
++�m>y���ͥ�LO,��{ls�l���J#��
+n�x�ZrL����������phS(Y�r0m�OE��yW1p͚v��4�_��d�i�˦�'P�F�gwU��n�sZҚv��X�G� 7��D��~�#�ǒ?2a ^���Q��̦%�&[� �@8iU�n�%�����K�y* ꗷ���/i:wc2]6'�5M�4V��h���{42��u6>�x4�x����j �!�B�`���^<%iL"q��!s�k��ݟ�ɱ�ݨ},i$F���[�XgA��O_�����ܱ���(�vrF+�*W3H �D�c�w��M ��OŨ�r@*gX��Y{-(�ض�<��F(m���C�#/��5Mg���m�+���{J��y��Jy��§G�GB�?�S6m��#M,�mH�S������ ��T��G8MF��[���$,��.��ȅ�� dJ�C�� o����PԻ��u�@�5�ftEP[9 ���u ��T�ۼ��.��;�`Б����w�������.����nmB��ne�,��ZЮ~�j4�@=.Ŝ�)�{a��h�̎[�K��gv[��n95zV���(|E�������w��-R�Ԯ���֕-��/$�H������FNl�ᖣ�k�M����ad�L��0dn�n/���j�K�-5�6 �s�Yҫ��Lj���� �& �ѡ�[Ӭ��t�^���[����l�Q�[���ܹ�������=��FWO��١Y� �g#�qC]O��C5�!��W<�C�����ޜ,�K� f"2���M�����ҥ۝��x#_��i�� /�"�y��B(�c����0(��;5nL<�8ښ�̝����N� #n���l�� ��g��2k���^û�6/t����D�/��u|�G[ �@
+��w���Y�Wʺ�
+� ?uY񬎜� G��ęU�}!�Y8��(�k��7ճ9N��XF<���Yb�f� �Q� ����x��71�S
+�^{<��,��+�vJ5"�X��Щpz���ic�B-���m��c��T�S/?���%���ҟ��,�*�=�J5L�b f%�n�o�8$��J�_' m�3٣���j�Q)��h`ޖWT�:o�O/�|u{��ׇ�x�n�P��Z�� �ƍ�5.G������2݋oo������/����Û�\�|{�����Շ�7Ѭ��/<��7l(���-!sw�U�HI{yP��ݰiS���-,_����`����3�l�r� عWg(�M]��~�8���$��)��$6d �e.>/O���4���LZ�LJ���t9O���=�� >:��n��V�Ӂ�tt��\�MZ `���s䠁��W�VGal'�[�zBdU?���R H��r�S��t��
+endstream
+endobj
+581 0 obj
+<< /BBox [ 0 0 654 173 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/arch/Canvas3.pdf) /PTEX.InfoDict 638 0 R /PTEX.PageNumber 1 /Resources << /ColorSpace << /Cs1 639 0 R /Cs2 640 0 R /Cs3 641 0 R >> /Font << /TT1 642 0 R /TT2 643 0 R /TT3 644 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /XObject << /Im1 645 0 R /Im2 646 0 R /Im3 647 0 R /Im4 648 0 R /Im5 649 0 R >> >> /Subtype /Form /Type /XObject /Length 7213 >>
+stream
+x��˒�q�����,t�4R�R8dɤË�4�gHE�3␺���˯��O �:�4I[�B��@"��;�����_ڎ�.����ؾh��}�~���}���o~u�������_�h��}�]�y��� �/���]�.]ۏs�����ڿ��wi�o�7��k��������Ű��4M�����u��֩}�N�\~},����<����>������7�i�wV�Ջ���C;������2K��m����ċ��g����o޽|l��߷�}���߿j_���͋���l�6u�9����.þn�n<�2��������v��T�p�MS��-�w8����S����c�N�~7~8�����?���u�����[������������y��W��/~�Xvg�:�jѡ��㾰�!m���z���,����?=���O_Ne�4w�yX�AG}��g�i��~^u0�z�F�Ǻ_��[wDn��.������0]�q��j�x���4`�/���[��
+��$ �e_�m� ���en�<�Eq��0��خ{S A@�s*Yϱo�e�74/(pHs��Whd����Z ���L�~��1�������F�nYg >o�L ����A|VP(�^��Ќ:�~X�I�f�PH,��2�p� _��8i��z����^���U��$d��eZ� ��mBБ�y�l۴���\֡���]�i��R��(��G�cV��}�W1d^/ݰ.c�m��6��<]�q(����;#�Y�e�nk���!���g9�,���e^�����j_�;�9B��Ў�z�m�X̻�hg7��@� e����1͜!<�����Ҍ*�i� ,�X. L�<yy����\Bތӌ��Z� (���\0f��8ʢ��,�" ���C���G߶�i�P�y�c�E|��>1k���˞����x��n�[65 4CY�nF��<��0c����W��id�c��t�X�H�Y����Q\@�%�I.�xP5b��^ži�U*4�'�%�B>7����l„v�P�;:N2hNYl;�N��Ӕ�P��0żD��9rLؾ���dHE��Rt�#��N�3��;�\L�l?b1��e��ٖKߍ�Bxm
+�G�� �9,V�c̓'WLp��7n�+��6o�u]��\v�4^��"b�)~ �.��>�<� *�#��;���w��<��pL��N�c���l�t�0��<�2�p�1 S� �� -���r�1�*^ ^����4K�1"�ˀ,9����F��BMrIJ��ʋ##9�,�{���rGF|�{���ï �ȕi���Àޮ���Q�Y�a�D��l�0,�PdP�v�qC: 8>
++Dl˰RK�����S����): �G�@�q$ ��`�e�=DX�aI�`Ax��[���(۳o���)z�ɜR�{���D��)ܴυ0�� k�� ,�X
+�oD��\�ؤ��In��"_��aRc�5�O�>�*� S�/�jw&K�s&f؁Ԙ{����H3�_D�!5օ���Ԙ{&���ҦN�p��$wE�Z'�g�y�_�}g��R�Ay1�R��TG�O%��~VI��������O>�׾#�'��>�����o�#6��,�?U<�W�a5�o��'S~���ACPl��~��Hm&�ؔ�jB��Ӵ�>㆕�`�6r�����ŜTY��׷�R�L��N�U&2�Х�
+�##S�U�*cj+V��1��f�֪6�DF���[�#"� n{��_��� 2;�6�=��F�
+�P ���Nr��<�wUe&�-rE��J/N�@ܣe_�'}Im�&B����m�p.�|�?o�=��3�1���A<�>��ׅ����߿��`5Y��“U0�
+Ӽ~Le��K�F�|���}ٜT�"�)�>������c0��3Ss��i_ؓgN�WO`� hG� ��A�?����$B�:�p�Ak�5�ji��
+v(D�q�����Emg�Z7SRv�{��~���+U>
+C�;BG������^?!
+� �2���u�QD!D�Xiي��
+7R���%�������S�,� �/���#�L�@Y�w�>��W�y�9�!�� ��>����GX��6�VT[1g$)Sֻ�U�K� V��_ψ���Տo����7?�+j}C>tG�ܔ�ћ���95�
+��J"C�)SX����k]f
+��ǎ����.�N,m�Tb��lY~0@�!�F��i*�>� D*��-dՔ����\!�\?9q��i*�~�$��� �*z/V�\�ų��zl�h�b�v�2�٩� ! �T��H�� x��<�z� IW���-�`U����l�6��i52������,���ђ �ׯI08|�ED\�� H���!“��ӤO�{ƿ�"���*P��C�<�mǧI�ح�l��b�~�����*`i`O�[鬪�D�G���M�T�> ���OnܗoF*�ʞ��I �N5�P@^W�Ӫ�7w���V�t��7?ږ�T��igB5������,���TrU�H$�Rؒ� J���k��g��gO\7��W�`e:HL�6�W���8�$�� ����ڈ�.]�˷ĐT�6��w��4���u5Bq`�M��L����U�D�7�
+}.S�;^�?>������y� ��D��/��;�DB F�=�N�E bS���y��gK�{��c��F<��R�D�MsQ��2v��Wz�`����T� ���8�{�H$��7R4x$��)l(�V�M(��<��89�9��w���S0� S�Rõ;�-ߩ� ���R�;)�%<�����tD>NG.-O���~Jt?/��� j�X
+zJ��~L?�m���*�J��������_�����N��k�w"
+��,ת�]�����+�x�~w/�� Yu7�yt�9����:"�{l6����ˎ��
+}��/����)�k�B[y�f�ƢE0ݓ%~YD`:���(i9..���"9яͳ�0�U(%jU�U��A�S��o�g �Qi=j�1/A��A�^E*�F���� ;�s����@�_����L�<T^1���.�hO{����9�(Ǟ�WA��)�)g!\ 턀vê%>Tn:�+ ��@�ԉ��2��8��\v�3H�gBS�{�L��9��<�i^K!.�X�g\�'�Ũ8U�i��wJ����4�)*If�hϒѐ5�L�mp�����{�R��<��'��Ƥ;T�,:������a��'ӝ���t�DQg(�.\���.�#؊6���1�d�y�����g�2rw� �� /�[�zi�2��Н�VL��,m�C��� v��D�DZ1�`�Z�*�����iϜ,c�ܫ �dž����|��`Ў<$� \H����B֒�T4H&Mw�%J�[ӝ1v�t��P�;�Y���B}�9C��s�@2�E{�Ǩ|��qʼn�(
+E�3ACu�AiHH� ��R��l2��)�ܫ gy���R�8R:� �^Uf��гG��;`b��Q��ú�u�4��-�@�a��2Yk W~X�^,�C��2Li�۲ʾ�~�qݰ�ٯ�+��V�8零ֺ���6]��`�?�*H�q@4�5(�#�R���W$|��)ca6���~�"J0J�K
+r�+f�l�{��~L�OS����V��s�R �T�*���+Ai���M���3�g~���9ܫ gy��rq'�\8��� F�j��ɂi;�N�.�tp�Ҥ�-H(86V
+S�5�&w&��+gr�츹:�&��8��W9��6���d�)�2T���Ld���3���e�)��9S�s����q����,Fd��t.����v:d��T4H��"�Rv�]�"[m�U�ɂ�6첚{@2�| �™8 gR`~b$;�!iarh�%�'�ĵC�MHQ칒5JF{-��{&�i7��ڊ�K΄e�yW$-nJ���ٙ�$.��iL�U O��ə`u�� �+g��W�$�|9��u��7 �3qX:�e�U�I�r��1W���Fq&y7U����D��s&�}p��$��|�I
+���3!�J|�QjO�JRted�I��p҄� gg��[S��H��3���v&>xrXN�q�Su*g29��L�C��JR�I�s�H�s����]�uv0JR�8Za��ϳRL<;:��uv&T/���H)��L�d��T�@�� �d԰#21�I@܀i=冎���9�p��,4�*�ə�nܙ�Zy�L�3��{ij���+?��ARw� f�)��3. �����M�;A���*g�}v&$�I gR`ٙT��B�Ӏ4DVꔆ��nܙ�)�r&��p
+��
+r����1*;�\���/��R�sW�R�(Wl�&�]>ͫ] ��:��.@��Z4s�������j���Ҥ��Kb􄕢r�IIk0h�< u�5u8LC��i$�cYܔ�; J�"0W��)��*@.p��QZ<gр2�̬� �D� ����I�emqP��
+ Wy�� �ra P"�l�\FlA �|H�M�Ԃ�H̊��ⱃ�6F�\1�&�� //^�B�[1`�V%J��E�y��*���iD�cs�E��^L�'R���Wv�a��x0D�MU���F!�\͓�BȒ��D��H�
+H�~��@J8����e�4q�`t���踘}�)��u^�籰F�e�٣�b��9U�l��;�Xe��}7z����͖g�3r�iT����J>^E��a���� ċWyT�"Y)A�͹�]h|�(EFSL�w�\�R�=��1�k�q��x�s.��Y���+?ՠ!���rJ�����s)�=�4�����&��?��౏���S��QԮ2�J(9��QQ�q�y|Y�Z�s�Qt?����E��ڂ��q����E �*3�yLv�r��k��.�ۉE� F��y ��ZUX�R�d��+UM���U��AU��AQ���c.R��)�:��ED�Ƿ��&�@���� h�Y>��䗫�Tq1*���O��Ë���.��&��m+\ܢ*U��8��q}VI*LU�
+�J#�!*Y�����$"�Jm��ʝKRr�E`8.�`r�E��."C�ۊ��Q�EȽ�BV����I�\�E0*9�bT}7nxKI��g�LfݹG���F)I9�*�Ĩ�$���R�"$?��(���/�����(����s��E �=��)\�È%�Y@���©W��"��*���S�de )���[�%)��E8gj�,d4g!�5�]���PS��=���)_�.<#�ޔ�����_��Sn"���o޾�@Wki ���{!�E�y���y�xn����WJ���� �x�4a���#N�>4?�]�����h��j�%����#|oξ�����h��v,LZ�ה2�1@ի]=�/sՖ��E������y�N�����<��y�S������k�i�W�w�œO��WC �x�H��J������:EV=J�u��*��X�F�Nk�?B���jA&Ҙ�.i���鐦���6�N,���I�z��X>�
+�XB�P��x�M�/_A�{{�%|��mc�U���K
+�� �O6Ek�T��#���7��}*"k_�.4ϼ��co�3��T1C5�4��ڲ� ա� ����c^X4��j8��e,_ Ad�G,�6&) ]��[x�P+o�YDɝB�i�&uz�h!�_��v^�6B���֠-�8��^��bA��Z����*������8 �4\�,:�hU�b��@�� J�
+�<��ȹ���_w�֯�=�u���z��ih�"*#�7v> QA��{��|֓�yE�y�Mj'pg�{�b�c�&�n�C= �'FL��@��M��Dj1GΪ=]�yu����v � �h$�x(B�����rL+�L�lO��s��k21��b�%����r�T�Q4Z����@C\�j��{S�cC:^^>;��=�]�+t� {��x� ��T��������� M>d ��Xd��C�%�6��1Q�����A�b_͞|�E]��7ɥmbF� ;��a�P̰'d�>qK/�0��H��E����z�]�zN2(�e���?� T��x��J��������DuD<���ڴ"�;YES:G�<�䵖z�z��|��L5�|p�WDId�T,�>F@��y�# ������[m��T�����@��L��������jcЛ�j(�u��x���ԂL7 �x��G�9��4�����`PhF�+>p^@���lj��jC��=��@b}5�<�R�9�j�F���4b��ޞ|�e��"�BXA��I��x�R�<ԝpr�- � �U��gn|�e;"74C�����g�&4��T�Ei�:!}"CT �O���3Uy�ޣ�Q �@�1�L�""Vo���K,�#=YO�=���';FbE_}zQr5�g��+�R�� �jz �fND5���+l�0���z����������;�bi�Ԟ;��l���ք��� �e�;0=jP��W3�nLf��B7�k��B��dB�I���Ѡ�Ρ��7 y6�j����s+{�DM���x�����[AU�s�:����;os�v�f��_��@��sN~��'ֱ>�������'���&�o¬;�ȧ�h����8O>F�o�d�v�a2%��z|��\����p>;1�ڊg��6H�ȃ
+<M~����O7��><MW�E���7��P: �
+ ݳq�bn�����`ݾOD�p�������#Y|������&�̽&5ǎ����h�O))�Tz9�I���Ͻ>��I��+]\�U�V�jR�i0���`�L�G��E+'GJb �|V'E述$�'��Uދ��6�� ��SNt�v��ٯ�����7�Z����F���8U�&�ҿ�8����A �dO�;�c�3������u��{w�?��V��۔��d��� _q�a_q|���v*S41���=yIO��w��w�،d�D�S~*}��63�܌c��7��?��D��P�ڑZ� �o;�ݽ �͖��)U�m�0l�\�L��Q �`���0S�[�?�@+�T��6�KiXK�m��%�PQZ���{�U� ���Ƒ�!���f&�ߢ�Bҿñ?�~g��^���ۇ��X7P�E�>�H���P)Գ�(+u���n�[�
+endstream
+endobj
+582 0 obj
+<< /BaseFont /XKEAZI+LibertineMathMI5 /FirstChar 56 /FontDescriptor 650 0 R /LastChar 56 /Subtype /Type1 /ToUnicode 651 0 R /Type /Font /Widths 652 0 R >>
+endobj
+583 0 obj
+<< /BaseFont /ZGUGQH+Inconsolatazi4-Regular /Encoding 653 0 R /FirstChar 46 /FontDescriptor 654 0 R /LastChar 121 /Subtype /Type1 /ToUnicode 655 0 R /Type /Font /Widths 656 0 R >>
+endobj
+584 0 obj
+<< /BBox [ 0 0 424.8 172.8 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/hnsw_visit_count_per_degree_corrected.pdf) /PTEX.InfoDict 657 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> >> /Font << /F1 658 0 R /F2 659 0 R /F3 660 0 R /F4 661 0 R /F5 662 0 R >> /Pattern << >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 1358 >>
+stream
+x��XMo�6-zԯ�q}=3$��c�4r(��hMM��M���}ԮW�"�2P,�uv��y|�|<������o.z��}�r8���4�{�ϕ#��/��3|�r#��!J�V���r����o û��.��φ���v�<璬�8��6��aM�{3_tLQ�r������f� ��+g-ā�c�>
+Ef�"������� 6�OGG��L�`�C�^,0�n�9��:7-Z| %J�DhP,�����?����˷��4q��L��n� �O�cu�s�=��鋔B�+k0SI��N�c�H��s�>��(^R��PM��B"��V�ĩ��M��O%!Ϛi�G%y
+ 9�K�a�D����k��O$A�|!B�N��e�p�H l�ߨ���n���$�"!��KH(P�>��
+�v_�M�=��ʨV�4B{�DI��f� �q�dc4��y��������ϯfb\�l: ;F�����%��i"{4�H}50S��F6�;F��S���"2�EdhN�������-�L�Q:�T"�z̢��t��2�V\vh��A��<�;F�𣈽���o���'�R}XEUL�9tKh���n������b8��|Q9Y����0qGl)v";4�\���!Dw�v���������aZ€1�d�t� ���T�9�B�+�i,=5�!������7�3Tδ�jk�i�tFsFb!N�����a ��`���W���K�譁��gt;;��E�"�IW؅FY��L�*%��ρ��/蠬�i8y�=���.�h%��~�[x;;�i�뭏q�?���c�{�zۢ��QrƘ#�z�����H*M�o� ���[2n~X˼Hc\��@�����p o�3(��9 �5�4ƥ~��ے~F��cxd ��m[k:4��x4����b�x;=L4�ƒ��k��Ҙ��A0�R��u*ߢ^���0�\@Tj�_��o/�܈���n���\^���RJ*����>^�����F��~-Y<;�ZWE1�S��;� -b_���lZ��|G��#������Ѧ:d�I�e�X�5��NInig�a���E�\M���,��i�۠#��`l�)�������W�{�} s���%L�����E��-Lh�;��Mx�� n7+��TD�U@O52����D�RF!E�$�l��ػ[�G�������畊���׿���������W�Cq�?�ͫ�~� dEt)n���v�u�4l���Lε�0��XL�`�!cpۋ��ca���)Ap�:�l��������C��9R����om$=D�~�&��&�)��&֫��,�|�t���{��f��[���Wo:oo:q��7����Wb���l�
+endstream
+endobj
+585 0 obj
+<< /BBox [ 0 0 1996.0275 438.448 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/main_exp_fig_1.pdf) /PTEX.InfoDict 663 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA .7 /Type /ExtGState /ca 1 >> /A3 << /CA 1 /Type /ExtGState /ca 1 >> /A4 << /CA .85 /Type /ExtGState /ca .85 >> /A5 << /CA .7 /Type /ExtGState /ca .7 >> /A6 << /CA .8 /Type /ExtGState /ca .8 >> >> /Font << /F1 664 0 R /F2 665 0 R /F3 666 0 R >> /Pattern << >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 9284 >>
+stream
+x��]M�$�q��E_�<���%�̰i�ܰ��Պ�<+�$%��������.�,�ݳ��C�d���B"Q���/_��ۗ��x���_��}��z�������o�f�g��co��������;[kZ�ˡ:�}���,!P����v�?�>�]��;��vWLu%�SZJ0�tC]j.6zA��d��n���N� �?��UC�k9���!�})��jq� Kv�ӧh�߿��n���G;�kwP������nq�x�i���G�����<44�Ж��h�U2
+��z������`Tߔ����������G����~���R��>9_��şv5,.U� ��}]� !TcCؿ���5�_����MK����Rx���ZW�þ,)������O����}�/���)Q�R�8���^4�.cz�ۙ��� �2� _� �@'�J2�>;l��^;��R,� �x��N��b]���9טr.�؛�X���B��Q�/�X�]�)� /�XwK� ���\T��K+6���a��� ��=�P<���w��c�aMq����62bXX�I� ����[𧏎���G4��)3{�j��߾���_^�����
+���&����?���|����Vlד(hd�`ZQ����t���h�1'��R\�f1�a-.���/nɻ���Y<���AC�~ �g�OS�VoVE.bb��U$�WP�I&2�<�� �:1�C �0� А�{Lڂx�1�۶}rn���������ڈ9����?�������]��> �Oq���o�E)�DW t����?�.��,tЧY25��)/�9��)�k����Nm�}6�$L̰X!���.�z�����'����mB6�C:����R�(,���x���}��(٧b*�����C��E��=a9ѻ|TɩI��J,�P��/��ȅ�,�z��1������<���L�́�������\Sx�5�� M#���ʖ?�Ww��� @^ �TTc�J]�D�se�\}�p�/!�� zkO^���n[,nb8�����zlW��ȫ��p&9��/�G�kDw�� !������E��u8v��b1{�ˎr�#o� �-�c�k�� �!����|��'��$..0':ѭ����1�-�/�f��%�@��vS<;Q��Ҝ�W(Yp�L�Y�ҙM]��m=��*�4�3��l��"�e,�%jwN\�3w�ڝ˂u�8�ݹ�(�Y�;w�t�ޱp�΅v�γt�.�tP1�r�8ăuk V����-�f�CU��)��h�n�N�+��s����,��g6�qM�~�� �[��4��ǎ5�^�j�C�.�VG��Z2��&���즒DiWA�^�;^޹�^�y�^��'�V�B;yY��lE;y\r,>h��xL��DZ�AmT�v�ҹ�.ܖ�D���;��W���w�̦.����NLЎ���=��=Z��ը�#[��������;3io'��l�&����}��������2L%���`<,^G�6F�jO�����D{;i���'����{�������a�q1�U�:�4�]�(m�=?�^�P�����Di�>N�LJۛI�+���!��oH�_�4�-,%n ��� v�!`�n*� �T�=���ס� ]�ҕ�)]��'�� ��A����P�=�Wq���,����Hȴ"��=te$�τ�����ҵ�&�� ���+�QB,2䀥ގ!6!��������U����Ҷ�3�T��gB�!s�sJW��ɸq§��&�r� ��=DHa_�[Q"g^�]�i%���$�r"��Gk���� ���o�$%��;�d%v�$���V�Z0�ݗ�8 �b[s���|'�������s� f'M�&չ�h�J ��F� 6~�J����t���1 ���%#��1U�1C�T��E�N�U�D�oy��%9d�/i�#���a���~)��&G��K9W�&LMȃh,U�T�OaA{��l �v�{�o��g3r�l!������E��9�G��(\!��0̉��G8���c���]�K��u���x�& 1�/|�,���R0���_Og�f�=s�QҶI������=,���>@�&��ݗ�@��S 0��I�b�^�t�}��O �nPB���6����˒ah����+���V�]�3�7�D�f�Nė;A��/�d�~#��D�� �J5ԗRA?$g�tF���7�^��һ8w���.��J����q�����*Y�t��� |��G����7l�ڳK��"9J�$� T������[ن���1o�-b8f_�|�-W�x������J�iS�?��rυ��G&@�-I���ɇ�.+<�Nȱ?����#�xG�?��v&���-yM|@`�$P�Lt�'�f���B��a����j���@>�����V�{��0Ħt�D�CB�ۻ
+�����Ws!���f��N,(��B��3� �G}��J�.����� �6�X<�|'�l*�G��#�'>��I�ˉRϣ����;wP1J�5����c�b̒��y���K� |�P���{Wv� biF�`3��M�>y�㏯�?yޱBCV~�c��.��R&�l1���D��NUA�wq^�A5��sNԷ����o�c�܊ 9-z���X3_�@pSr�R��� �
+6G��� !ȗ6D"��GD�b�V���5������(5+ȗ�l�v 9&��&\T���%��V�J��R��\��W�E�Z�\���KdY� �ŋ�L]�I���U���5�m!E��nX�;��E���1"�u�.v��@��LI=㛭�[�����s)U��3��jC� �� C���$�_�v�� �%�{�9�=!٭�U�#�쉀��Ku���&N�����^S��5pOr���.��,�ل._J#�z�k�cח
+����E��r��Jx��U��� �mdZ.�Q'�O\SBЕND?�����m�j5.kV�̥H�׎#Xn�%�>6�X5
+/9> �,�����+�O
+O�;rPv�� %�(X��E)]G:J]H\$c��>&ݘ��\��ؒ�݀AN�`�h��e�)����l)N�+t,�P< �u�̦.6q�7���a�_Ƣ�g?ʗ#��C�tf(�"u����g�|>���0�r�#ip�U��K��}|�Ɲ[��'ɴ�"������эK�޻s7FVh���L6��s�.ѣv�������|��lh���(�m��B��1Q���RB�n]�kG��-~��������$QUЅ���sw.�sw��s�� ���]g���5vJ 6�ڹaM�$;:���([�]OvS:;х�R��W�x�B��ʲ��.���ŵ}��y�'��>
+ɕ�?�x4������+p�lo'�%bK�#� �U�Tno&�7��7��f�SȈ����x�kk����?�^[O�����zn��M�ۇۛI��Z�V��`�g3�\��Fq�=����Z�����W6���a�><��L�_ۦ׎��'`��ٲ4*{��C0]�
+V������p]�VU?��v'6gdՋ��j&\�n���7a�b�?����Z�a��+] �����Хe?���+�S�� l�k'|�~�i�Lj��y%Xm�i`]�/cA��k�D�F�o(�K��~&te��甮}c2���)���M�a��c�JĔD9�z�J4s�[ԛC����Z�jW��o��éZ#�ٹ U 5�d%w�$���p[�/c�K�n�n�'��F�f�������]6��^�j3O܈�P+W (��L����%���b}{Ơ� ,
+�&jtw�>Ɨm��-ζ��ƴZ�}��yK������2��������D?����.iyJ�-"�I�Zu�,�X>bVL�n4����1V�R�TC����\�0z]����4.��~!��^��bʚ1��Jet56ɚ�\���X�k
+
+�UL�\.�[R
+�Oj
+����~�w_n�"_�p��e���J�n^����?^�:�\�ס/,�ή���3rƯGbGpK�� ��+�
+%� ع�M�ׅ(
+��y�=���5oR��{�K�$w��xBI[z�x}��{I�:�6�;��8î���Á>�/�5X����ù��!��.�ٷ����?�8��V���̅<���Խ�]R��u��m�@V�{5آ���i�{�OĘ���^�S���(wź�aX�@D�u/,����
+�ty��BHwǺ��e)�^۠ ׎+X���:#�u'�-@���QG�{�Y%���u�L%��Ubݷ��.��2o�%�c��>�9�U<Ƃ��ո�.�*�ʎ�1e��b��Ƈa����o����0�c��o��'��I��(���'Z"�a�M�(��ܘvY��M`絠_\��,������,���߀v=3D�1��k�ՎXB���z@��.+�lbś֮�_^�ؗ�*�c.�z`�[�.$E*^��/I��v:D�ſ
+o��a%t�/���7`A�jiH�H�FP��I���M0^%u
+/�� p�%�����\�y�c-<
+R��~o}�q<���d"Q��� J��co1�p�� ��>~�/�3�׎6!�S�E�Z�K�m����+��1�A�w� ���uU����@`��� `P��ϻvN���~aPL��ꊹ���.��F]R1|EW���=yr��^q-�(�|84X]K5�yB�G�c�[�'�K�:'Z\��J���Ԃ}��]��+%uRR1�b��|֧�ti�N�T�;����S�`b4�#�;�n[P7S��ԣ�[*���m$8�6r�m�l�4o56��M��g���(,�yzF������`�Z��ӣ�����O�jO_����. �~�\{���3O?�>x�I����1GO����ᙧ��y(����� WG2�k]}KR7ӌ�T��{t�#/�~�}����f[3���GY!M�&��1�<ٗ�P���x6JŽ�,��I�G��g3�4��+u�� � 8u�g����p�}�'I����g�c����l�ݛ)g3 [�3���ql �f�q�z�]�����O�+��r�m�\��!�!ڋ8�Ok��]!bA�hw�K��^!ne{;ioU�0i�'����ͤ�&�f�����rf?�0d�f���m�ﰳ;+���;��afw\ה��>1���뙁���`��uG������vv�`��av��;�쎫�0O�������k�c�;�
+K�b�1ջr����]�. �Zٝ_�]���nƮ�j ,|���!y(ќ-���}Ѷ�GFW>^8��� �е�DG� ��Vf���9���*;��g�������Y f����7=�ш� �P&�wA�Xv5�0Xqew~a0�lp7cWvum_9CH����O/� �]"��E�-�m�(p헄�a*��u�k)�&�}���5<���AvoW���o��G��WA+1�� ����N4��Z��xZ�s���$���F�M��@.G��f�y�֭#������Yނ(c��
+|6ǘ�#�o{RSظ���h��8g� �[�����} ���`�0 �Rmt0̙b�U�����!�n#��T�-�aM�u-� ��q����>�s 2����t���(��)1�S��:9�2q
+�'�xݺ�[��3�%�\g�q6q�f2Sް`
+ ��< ؄���CF����OGL�* �g��0m�� �*��vT:-�,�zN������2@�Ui���"���/YT�R&U�>�ƅ�Vr�&{�� K�kA *4����T ��C��~�2�ϧ� W7��[��/ ��F�cc�Cn���`�T$�kq]0�=�4s,����Mz�,�k�3z]`=���4R�X��W>Y�EX�Y�Bɺ *?�u腘�k��-2��+p�����h�>k�:�����\@_�.mi[,Y 0��,���&@�&�\.T ��4"�j�*K���V�����Z�Ѥ`m��d�#��N"a a@Av��A����mI99���J%��7E
+ȝ�����kI��1�q[HْG��W ������sZ��~q���^��R�X �� ���{�H+�
+���9l+L�*�Z%� h�u��b�P�%��n��,��S.��i���t��
+,A��v+� Cv�<r%�����նWm?���[P$Z�@�fg��&U o+dJ�*d�U p%�E%@��r�<IKU��y܆������{;���$�36;�rK��p��TS�X
+ /(���i�})�\��k�Sj}�g����PӃ����uU�=y�-�c���^���Q1�R���ꊹ��) y����|~u}��D��r\ps�7K�wD]$�0��|�8}�x�x�a;�QQ% R^�I�y�XJ^"S�.�RR'%c*f��!C��|8ݜL��y
+Drŏp�×ܒ9�{�4��7�(��J�h# ޥQ��f[/���[���V�勣��=�� %'���J) 9��X�1�\��>�ttAՎ�/H�����wN?�+?�r*?Cj�B�i��@::���xqpt��ƴ����#�Mz��mA�L1yS��o�蝗��;��ѻ�f[3����Xc�� >O�?�#���H���������X��zh7��?��d�� Ї�@P���� '�h����%U3@���)<o�T���*m���pYJ��0�t6$���b�Z�מ��l �߹V��h�uru߿z���LG,�nKX��4f��"=��]x���w��
+�&��w��� �0�;�QƷ��'8fbY\M�3�ԭ;څ���&;�a��2�#��fv�uM��T�yeΦ3�1��>^��B��qG���Z��;�C�Kr��p�;��afw\���Ƅ��P�X�IW����^�]>�t���W$�Wu5�0������U� ^&쪮6��7��h�ɏ�������ӏ�F��AT�y��\��T]�.h�uv��MW�)eWW5�c$��&�g��.&yƒqa�#�S E����(;�]������)��̈́W�ѵ�{튀�,�5ر���t"+�x)[��P�'�FS��d,+] Y�&�}����v��U);��p�k��&�}tmƈ���i�8�������!^2đ^�`7к�!�+���}Pq��-Stc, ��4�P����~`�x�>�Ơ���8�>��� �@����ǚ1���P&���ܦμ<:�HH��A�%��Uekmcʇ8t͗�%��b��.p�'N>� �j������`���i2Z����s茨5�;XZ�ܛ��6PU����U�ŝIi���ƺ��wE��Y?�`� ��<��Č��cF����OGX�*�g�������+�b�\0�2҂���"g��:R ^Re1���bu���Ř�/X��B&] ���م�Wr�&{��zAH��BTjlK�)�]�����ܖy�F�����b��|��_��q(�@l� �-؏��zKX �lT<�߰ ?��� �/2�8D�\J�u((�.PC{l.
+J8T;�
+0 �XuA�~(��* � ?D�����B�QM��Ͳ �D�7U��P@�ҟ�{�^PJ[*�E'2w��(`[��(�ĄT"d�o������j��V�`bx��;�`j�e�H1��)���v�?q*g�zl��W�G[� g;����l�l:NP {���Ԙ�
+�K ���J�#�n׎�g��홐ډq$���N:�Kp��]`1��Φ�u�3�8���l���c{��5�tz\�� �&��/�s;��q\DR�rmL$��X"��1Um��=��w�@�֙X�y�3s�í�Ļ�qF�St���I+�B�| ;��~K�_~����gZ��H a��S="�j���G���NO0�tن�Pd�CĎa��H�Z|������Y�*ֲ��Gc
+���K�j`޾��Y]�Kha�3k 7b��o�VW�[�W� ݏ��u��W�V%t"�_�4�R���C��I�c�Ɗ����@����g�o��։J ��U&z�<(C��لt����Ry�ye*` �����o8�o>��wӉ��k!V��ݒ�e8�y~�i�p�<o:v�e�=���j�=�N�� �U{�����^��V���J� و۲ɿ�篧&A���V�lB�<�, ^+_]@��]h�m{h���X��=�Z�����B�� v�TW|H�9����]� oek��%Â��� ����|n��[�����1��:x�9^@�\=�:�6.�� ޱj��@f~C�\���M�/^����_���^�`vc�����߼�� �/�y�����sY�@ٝ��}c8ag�q���Uv~��<P��y���x�b���b��$Au1���#����&;��0Y������1��ۺU��A�>��)����!�q&g��l#O1�C_��A]��3?˜�.gH[�� ��6�%ne����-5Ӟ��<����B���Gv�+/������o͜H�\�thM T�x��a�**L^��3pk�0^�����D�9t���D �zl��Q�O�r%
+ �4}X�%����!������� ��߼��.�m�M>��.��#w��r_+�[uo`�p��ȷ�!,>L�RC D�t���w4�i*�&�]�u�3��Q�u8v�����b�}EǶ� ��{o�cԙI�-Vil��C/X!�Mp����:I�?O��P����Iqx�A�<�H��]׆x�j[��=w5K>�M$�݂B@e�-�x��2Fw� ��'!��R�����˯���ՏK ��������_����&��|����nd����D���,�W&sa�����G"��iUqiG^%D4m>�T<M���u@ajE���F���r�頂�ՙ�x��2�,�3�P4����@��n0 v��,$"GJn�3�6�KU�Mʼn����$�ia��x��[~�3��S������fH5b�����iK����-7�u9䩖�Y�s�}��%��Ǻ�M����-��*���\�AY����uP��,�.tgS�w�T�HGVܯn�D�E�&�+��_t{Oh8�=�=c?eJ�#�&?�Er�q�-����o�Q�.�.��F�K�vA�l��[�-h�,m_�ܭ��L.��<e�O��S���m?e�O��S���m?e�O��S�����z� =�yB�<�G��#O�'��z� =�����w��B�
+endstream
+endobj
+586 0 obj
+<< /BBox [ 0 0 1996.0275 320.256 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/main_exp_fig_2.pdf) /PTEX.InfoDict 667 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA .7 /Type /ExtGState /ca 1 >> /A3 << /CA 1 /Type /ExtGState /ca 1 >> /A4 << /CA .85 /Type /ExtGState /ca .85 >> /A5 << /CA .7 /Type /ExtGState /ca .7 >> >> /Font << /F1 668 0 R /F2 669 0 R /F3 670 0 R >> /Pattern << >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 5487 >>
+stream
+x��]߯�q����R��� 9�ݴ*���c}p�`(J"C�YM�����瞳3<�ײ�{k��o���-��o^��ͫ׿{���/_Oϗ_�~�����<��;��c� ��y���n
+��#S�����Nѻ� �^��/������(�G<�b�Zu�[�4��*y
+gj�q 9)�[-��B��K!F�+��|��2�p)� 1ϔ�˥��J x<F�=~������������ϣ47L�����]�Ʈ��P��g��ϕ0 յ����VO_O_�C����B����q���^:}�rz�ox<�|J%����XZJ)�95W=5����6����9lj�<Z�<���B�(a��p�����?�?�� ���5�F ��z�����+���G�23D\�!3(��f���#���CvX��A;��jZV�v� l,�Efn��r���z,�r�e��xo`�ˑs)������,A͖(�l�U⽁��:,\2���+H�lN��&�v:_�{�C��#���tƵ� F��R<��� E��)��Xg�#{j%CK���������������\C�BL�x���ݏ�� ����Vl�Q!%��7����|ۥo�0&ʋ����^)@)����-uogz︤���@��G@��\�5r �n�v*�8��ۀ�"?�����s$��ԉ��h��
+? P��@1B>�`6��0���w}ك2el�����=�6|��l�a�|�����v��<�}�����^���c�������Ӟ.��z�B'<�+���8��:yx0�I�,��� K�X"���-h�%^��B<f�r����W��D#h3���XT��������-�M=7A�����+�w�a!Q��v4;i�[#G�@�@�*G���$�z4���2������o��2��4�7�h����Jn�W��<�
+�qRA\Sd� �d?�+k��ruz� +��0Աf��D8��c)m �r��.�`H�"�V���cfc pb*Ib<�PX�o��.�o'H?��xS����Sm![bS���M�*&��������Qf$L��Qq�"*�6[�F��Ћtٖk�R6��4K 7����U���R�4�c�$�� N�a0e�؂[*��� �(��h[��U�l�M�K+7�S�WJmT�l΃�)!ւ6���S(�˶C���E�v�*hM|ˮ�$�e��F�r�����c�G�U�]�Z?ٱXz�yB��R.�
+s��1���%t\��*ř�ø�Z�}M������Yf<�¦\��aM�g����sou��T@���Q��� ��0�)�. �cC�+-�HF|��m���+�P�X=�V�[����q (7�L��ڳVҥFm���4zr1wc�p=�gStB�L �lH�B;��0oc�rX�g`������7
+��H�\)A�ր�/6 U+���z���*J�֊���X�٢�9����!pԜ��o.v�߾��s���l�l� ������z��fO��d��_��` �?ϧ������T�m��ߝ�⓬�Ζ�������5�#(� K�b��#sE���W��� i8�����rU�"�+�WZ%�W��EʫҤ˾�u��EuU��*ίN}�?� ����x��Iz� �-b���m���_JN>��a0�T�S(�o(������x�e��U9f ��.�?�$���}��h>m���W�n�ӌ�e� �����PL�}/'ɆdA�=�W(̡�8>�g"t�����0CR��4S�R �L��(F��WI��Лd�)���C=��x�{�9��+ɮ �w>�E�� ��qNM�����y�u����H(��&�H���W@�6g�゘a&i��Y� �0K�z�K�A��,�y��s^��.� _r�s/,6��ē�2�%��,IB�+$�J��UP����lr����Ljh�Qߟ�]�$����eI͕�o<f~��DY����X'Y(2U0�g�n���?|x������9����Y?b�cf둃�2H���H�]����L��2&�/LaL���4��a�@R&J3�,��s���a�e�ҭ�u���"��C(�ކ(����ăE�yrd�
+���4�J�7� �Y����#�<9����YX/½A�Z �#yٸ�|[��Qm���}aK�T�� ��I���q�Qt�'G6�[: �(3�"�[D���
+�S��x�&�#A!*���3v��|K,e(;K�52vT� ,*T�+���P��9v���޽>�ǀi�I|?hx %cՉe���+���B����c�O���aK�.��c�Ԁfa�2$��\'�u9���0�kt���xZU��#`O1�00��h��9T�G�,�Kˍ(XL�b�+\I���LT9Gcr�(�O٢�bw�Ke��`~���K�r�wdyo�`���r����l�u�������+�j�i�*e5�z�#���ϭ �C0a�<XNɍ���JH1�m�6�*fKl����M�*ƯW�7ڨJ9�r����l�]�s2qn����L��a�+��\C����^��rSn��Z�q������y�gmTV��R:���E���-��o���Br������ײOp���:&�_F�zk�V\��=y�J7342y[ e�i�D�h`y[�$n�9#� �-��st f��U���2�U�Ǿ�a�Ƣ�*٢9BDo�����ˎ�j����Ē�ㆵ�5Aŝ�����=��̲�#��SF g�ӥFc��F�R�ƂW�і�H94�6�J&&(�Z�&����=0M��%�p�� �l�p���3��ĺƮb�A������^j�f�MOy���9�ε�E]t
+����!Q�Y�¯b4���62\�׫��w[�2�����6�Y�� ���$������P�v�/�� ���5Գp��k�"3(�!3��Z��S4�6CfX41\�7�G1w��I�k¤�=�5�AI/J/U-�� ��\0�Zޓ��C�r�}��0|3߽|��l C�b��;yQ��ш�y���o�����wT�iF(���چ�0����*�5� �Ax�Es�$��G����ľ�P�DŽE$+����b��ڂf<Ta��-� $Z���x��S(�}��x�#�cZ�f<�& `�,���j�6 � O~{a< �@�+�xX��)�l�f��h�0�G���-�1O�h@v`=(�q���u惺#��$$��B�a�Y���sB��O���W���p�E#_{J���n� )�"/�d�G1 n�M�N�8��|wt�-�<TK�<x0ϯ�A��BiF'Jc��代�����@:���7��'CaDW]%�]D�$b�:�8J�-� Mց�廣K���&�a<&+^I���9�X7`AjYb�
+�Fj��� 9BGt=�<d���� �l��w(M��FN{�yh����d_E�P[�=���'>�
+X�J�iO=�0.��p쁾`�=�E���wf��UtFš'-�b7�r��"�����v7ag�s'�=�"[9��F\� �*�p`a�4���<�go��p���S���]�<�\eNM9�rS�j��]R\�8n�S�����!��#~�2!�ݯ\�L�\L�� ��b��5�RҦ�V�4v����F�q����c��(�+������ޚ�W�2�ra���K�9����6�ꥱ��7j�[MUn܃����O�=�N� =�,7��D����OA^Q��r�L��2��?���,Wث'����,����S��Xu�*�Y�$��WQ�p:C��T���A�Q�����r"����#!t�:��9��W��1�
+�A�C�)8�z0���4<�F��&���M��r
+�]��0�l�` I�dg�1��S�Gp���h�c������e�a�����|lB�Z��=}�1c���i���
+c�~e�̃�s�>-1�r��PlaQ����R��Q���O�g�A�zl��K�=alb��Z��~|$c3O��v�ݛ�޻�ް��1��q��3��'�@�_��"gh9g���F��ANﺒc5��҅�`����冡a/\8�Nů�M4$ ���it�}bZļ.N��傦k�Ba�T#���.���hf!�����Ò����x���6ƾ;��d �{�+fa�6F�s���7M����M��|�h�l��� GHxN��Eɐy��*;3 )AB �^N�XX��""���MːW��pI�2z(xd,/� T)O��fxB��G�cyP�bj�#E3&�T��]�/�?�M��@�)�]aY�9#R���3n��$%ߡ1� %�� U�9�r�V' =bV#ga�v⣙x.�ݳR9I�FO.���P3��E��I�`Sc %��E� J���0j�ӣ+���*.Ǣ�代�E����|��H�xzt�����5�AW��G�b&�ҏ�d�Q3n]h��tJ��g�J�P����z�tc�l����И�~��n�B G9��Q�����r0ԯ�f<�U�e�*4��f���P3t<7R3�C���Z�f��/�f�dS��:�� �p*�"l�K�C�;[Ԍ�4y��q`�#�
+�g��
+�ĺ.�HL���8TQ� ����w� ����9QN��}�B��:�����c(
+֠y��ȹ0�p‰�`�QE��{���SA3!\�á�I�"앜mg�l^�)X]Ҧ�T��}A�T6j.[MU�'ot���� �:]��ab-�3�� �&o��Ƿy��k)iSn�^�}A��5�VSUAǚ�1���������W���V�Ѹ����\9{�>pAC�Kڔ��Uc�/h#�����6Ut�q�&h .w�y����M��U�m��В��O�3-�En��U��8|����)���,����S����Y�({�&��Y�����!�-�BEr��:�!����(��F�R��6s�G��X�۫������+�\��d, �����f#�Aw�~4�|���+�R��%� �lT�r��֏r���R�5G?
+��p�B@ W�ƒ;��W�陴<|��S��y�r:����8�a�Ȇ+ju8�%�qM�����5)f`h�z���H 9� �[�7l�Q�6�T��ӄt#���*��V�n+�&{8�y�w�y�a��cr��V�!h<P�O4�,�A4���? E�4��\�!�g��&h�&h(�%h� SBթy�����t� .q�B�Ӎ.b^'S��!hh����T!���>�Kѱo��I�`�jh )�f�A�����> $��I��(�O�B1$���%�φ�Qŗ�H��F-,_d�/vY��'9s�+�IU>� H��+����^ 4"CҨ��FQ�@��\/G�7 �F��!e>}�s�iTa�9;b�i�,ܐ�����qנxrfG��OW�Ӑ�9Rf���i����< �8%�,�2�h��W����W
+endstream
+endobj
+587 0 obj
+<< /BBox [ 0 0 539.2639 206.37436 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/accuracy_comparison.pdf) /PTEX.InfoDict 671 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> >> /Font << /F1 672 0 R >> /Pattern << /H1 673 0 R /H2 674 0 R /H3 675 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 3039 >>
+stream
+x��ZKs��ﯘK�ȃ@t��Qrl�\�D�Y�C����e���C�v���5f9fw���� �۝~�����^�������W?n��ˏ��ߛ����ρ�s�{���t�� ����'����d�����f����9�|�S盍sƏO� ���zC�Mp19����`�m�O2:�������rd�'q)E���� g� � �������p���H22�����ࣅ������O��n�c���oi�x���M����,�!�b]%�C�������ɇ��$�E�ɋͫ��|q)��PcMd��G��"��0뇹�<�)�D�R�f�&z�{7+�!8�+�2Z�Q�h�(��]�o�77�ɰK6��7��A��V�#\HV�*�E{ ��c�&���l��z��'�i��JQ�*�E�T@�M�Id��1�ȧٶ5x�aKm�R����b���s��1gG4s��k��]��t����N�bOZ�M��(ЊlPU#�@�E��� �V]�#�鋋��7���K($���_6e�,��� aU��.~��s8��?�/?��8�̔��³��_���t��p����M1pC$�y�)ص�
+�0�D@Hl�@涝|C��Ż�|�:�o)yU��g�\q�/Ф��;� )&��'΃�&3*c����e��7d�sl�N�:��A U+�8*��dK���Z� �NqHq�xe$B���%G�K��:�]�����
+�"�;�&��b�";�!s�4jHF���0����l��iׅ ��������S�%'��;�������N���i q��W�Ş�dM�i����t�z�N�5���y#�N���6�*����'��
++�K��� �S@��v���' �W7�@;g�6!l,�]�����*�����2̤#"�Wb��V+��4漐 �:�f<s ]B@ �󐒑�%qt�V�*�d#؉ ��#����M��b0t���X�������Hb�����`��Bș�c��ET
+B�DY��"�7��;6D�W�"n[�n���a��A��2X̄�8a����ɵ����>���DP�tx�k]�e��}k�� y-6���p�E��FN����?oC�%%޹G!�F9��4/���zZ�ßɪ6e-��cr��Z�����[�[9Z F5I*(�����e��׿�\}�x�s���R�|�����&�D���������uh�<h}�&A�y9+���cMJj�����<� �Y*�A��Y�-� �U�F��X����@�� NB�!�����QeI�+
+%�����b�~Qʣg��m+��'�H=lJ^� �h�lF�WƤ���`uK���$����Ϛ��г0m�!��a&�:+���� �Ԉi������ � ��r�������x��;T���6V\�Rj'A-��“�(����*#J�}�_ )uܤ��b� ���}��A1�m��W�-D� ��^VI~���РOj$t��k�bp, 7*?xdG�!ٜ��� ]s��An$ ���7�7�a ���UAU�s��,�3rM��*RlI�6����E�A���S���+�K��,B���rYT��n�>��+�Ry����$�<*�e�����#֨���+Փ�H��NC��e��(�le�� �V??���1����$��?�����l�|�~�Ƣ<b��~</
+��w� ,��%ֆ�� ��^�zH�t' w�Xq�@��~LX�A� �� D��rքc�srXo̽ �ؐ��;����G�#�j��^��FUFs�a� my�d�E��$�G%L!�MqW���d��i�ڐй��ڒ��De䣇,b,�v�gH$�&K�ZsإÞ!{� �لh[�/��e.N��M��(�p�ܜj7՞#�b �p�����_=�M�9&�ē�����-|Q>܆gw1�H9<��XnNԾ��w��s>G���{6�ma�hc9Cm���D<˝�HGbb�����3u��U���O"Z������� �J_Pu�!�a�R�λ
+�����N|����x/.�� Z�;H�#��E9������ND ?���W�>�vN-�z��;Z���*���BT�h�/w�j����E��ZN�:J$;�'!-|���q9�� �
+�xT
+>;���c ��%��y��+l+A��[��6 �L+y����%���)� v�Vp�mU�� ��TWx�j/��[ռ��Lv_u�W��iU�E�����n�K��A�i��e펍��+�V;�±�����������nQ��,8�W�F�d�3�,f�an��� ˻^dy:������Jݡc�4�9�ɠ�:�`�љ�8��'{��;
+��J��(�Z���~�f�18��Hy_ey��;z�
+�u ��)�*��B\$���Ћ���%�J���ͩ�M��
+ݝ"��%���Qy���KN����0�f�X��5їl�����©�qx0�~�z���� �8����ȉ� ��}�r�_�m�� �ޡ ţIL O��z �%,��`�ޗ�V�]�kŝ��T�`����A�S9���Io>�`[+(��Z������N0�L2^l�Q/?���Ρ��>FNţ*�ßV|
+�Kn�9�x+ziN�D�m���"��p��O >E�y����s�(����s��z7R��+�����߰���sr�!��W ^o(��%���<���t�v>�5�
+�J dds�������-i߲z�PF{�>��ZC�х�l$�}i0���,*/�A �-L���+���!� i�;
+�_�l2��b���+��W+ _����3:@H�@3�_��;.Hw����㼋�/�%��|�]/q %�k�T����/kXA�=�9 8�d�A��>����^U8�T�׽���j��!Ŝ8z?2U�G�3z�\���:�g����Ύt܎�� �#�I��eä�,�]"F?<&SL�5:J�^"Cq�((;tT�r���:z�3E�A���j����y���S{��o?|��çJ�_m�Ѡ;
+endstream
+endobj
+588 0 obj
+<< /BBox [ 0 0 327.86253 142.22867 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/latency_speedup.pdf) /PTEX.InfoDict 676 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> >> /Font << /F1 677 0 R >> /Pattern << /H1 678 0 R /H2 679 0 R /H3 680 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 1454 >>
+stream
+x��XMo9 ��W�cQE�(J:6����E�5��EA�-܏m���ߧ�=#�v��E�C��̣H�O��[|~s��������OOW��[�]Zo���%{��K����N.+G�Ӳy"aǜ5 `�?�6�9~ �+|uj����+N�Է*��B� J^]�5<2t��� ]b�p�e8�1���1S�L7�w�1mN�/�dn�� [\QV���W&�S
+��E�k�bP���_��?�fv���>7� Iv��p��om��8�)G"�m�c��3K��
+^I�S�G�f��+9'��(٣7�ߜ�=��v�tZ)�-���ܭ��o��R\*�1�'ڎ��j��g�8��7�ì �1��^�s`*YC�i�������7W�39%:����:�+1�fD~e�\l��`�A"~�Z�`޻�Dz ��,O�-���L�ﱬ��-�xG��Soy�υ]ٲ<�w�����2O>o(<(2�ɯ( [��E�E�&>8�>y%�b��%���?./����e�t%������;�v��y�S
+��B�=m�nh����]A%�F9CFi[N������o�!xZ� �������|,��?;��^|z����'d�.��!!d�7�O(�
+��e��0}ߢ�kƜ�oY=r4��!r���Ą�R���B�(ų��c�r gŢ��8V��V�o���NFw��[�;8f�k�����mo�ʛ\I�s� ��eN\:o4+�H����}�}�M�R��I1Bv��kWԱ�$�[�����P�diF�^���u.��i[�ֹ �:� 7�-E ?T���m�v�����Σ MU�c��/[��a �$�� m�G[�,�փ�n���ݔCh; �s̎���t�M��������H���p�(���<�*
+����hB�Yh����#E ��������Z-p���� l�!���-���uJVG�NZ��η ��Ib�Tቢ�,����J��'�g�4��jP�� �|�B�P������ L�|�oN��Ǥ%��F�����q�f�5 #��EO��Z(H�B��a�0�F� �� h����"�
+[N#A���
+��Q ;�(el�����>ā��g�|3&ݔ�f,�1�#�CY:?�Ȁ���^P�Ȍ�0�ZM8�Qv�yܖq0�k<pVA�%H1���RqD�9"�C�{�������]ei���`cd�:���P��4-�
+$\�7?�8���isV�� ruWg$J�����-�k�RZ|��!�z}6���P��[��>ٯ�l+.�VA�cU�{ ]6h�:1�谚^?N��!:��t4;]���_-6�c�v󞧃"�.���A�A��[w�o�y�����0�˹U$!����lByڣ_v`;��|x�\�L�h@��٣�3���h���fu���n��6]8N�b�ԇ� ������(�<�ݒV<��0��������i#�������
+endstream
+endobj
+589 0 obj
+<< /BBox [ 0 0 348.90483 183.81324 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/H_hnsw_recall_comparison.pdf) /PTEX.InfoDict 681 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> /A3 << /CA .501961 /Type /ExtGState /ca 1 >> >> /Font << /F1 682 0 R /F2 683 0 R /F3 684 0 R /F4 685 0 R /F5 686 0 R >> /Pattern << >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << /M0 687 0 R /M1 688 0 R /M2 689 0 R /M3 690 0 R >> >> /Subtype /Form /Type /XObject /Length 2108 >>
+stream
+x��Y�n\����M�����~f'E�r"��v9�$ Ř��|~N�<n�̝p�H^�Э��W��������/�ڿ�1����'��][o?��w� �]��ñ��c��ϕ� �] L�@���;c~1�O����0���D�d9�j��wpe�lG]ij�ѵ�S̠O,r����
+5Bݲ+-�-r1Q�-Sf<���r��{��?ڏ�� A[�%x�'[n:���WֻȍB��K�}���X|���}�bϻ&2dGhc�w�&� �W�P�1��5���&"Rt1��x�
+R�l+9"*1�l�'�]|�rw����6 �6'�4�A�l��"��ZEJ]����>��n?S*px���"��t���<�y�; ���$h���W��:�0�2����m�FE\�I8S�G�C(��`��!��ȗJRq�y߳H��T��h�C��=��ѣ�MO��n��a����[G�5+�D�X���C��\R)�{�t��'ʅ�;�QB2{<'�����I|���u�8�t���JqR��C@���js>E�a�O�u4�;E#�&��x�7�SI��LA^Gb]tq�;һ*�DE�F� ED)ܴ ��7O/��s�w��}k�^�bW*�d��=���4��qqe����^|0�0]�}%XOWr+5�\�Ӟ`��J���*M�U`<U)03��hUTt�Vԓ�p�cc���w�70R��%�B�~K�qjh<T8A�=�H~��Ov�zy�v�:����p À����34��Ջ�w���g�y�+O� �
+F�+����>u4�=��)�*��-J\��a/�;��µHBOԇ ��2�L(�].���7W�C V�I��! �U����Hh#��mE~�lR
+b]����pI��NJU���@������
+J�7}�?A��W�O3`�|;C4oo������7��y���9��X@&ǖ0��4i��S���y<��1J}�v�Y��lrht�� 8�
+hD��
+D�'*���y� ��]��y� ��R���lLi�����9�U��;���NK�Nz�6�1�Tfx&��'���tQ>i�j����v=Rl4��`#�k�!h�y+RF�h��+#]{���nZ����H��M�\�\ D�q*� �RP�\JU����%3&-�;�y�8����B�P�q�Cg�#����jׂ��)byS1$�OLڂ�b_(�Jܙ���X��`�&�f�$j�)������Q��2�|t�2c�&*(��-�u��@�@)��5��";���!Y|�XO�����[<Z$�ړ�� V��*�S���:��;�� 5�avŽ�v����Ƿ�I�y� T-���͏d)�O�$�aX��5��o�3��-��˿�L�N��Є�y�Խ�'6����7�S�.g�[����g�\�l��C�k�m�/�Hs�V���f���Qi�[�.Yvt���!��Ԇ��EP�k�\!˿�rt�,�����R XN��� ^n8̢��<���z�Ǹ z�g�u�}�y>��%Je����� ��9��/�<�Y�\~~w{5����5�ms�}�; Vt���_!^3��u��Ǿ� �E���;�T�D�8K~���8��H�{�������Z�����1�<��DE�:
+]�4P��o��2���O�Q;�NI���t5h��E�<jX����_A�%�͍ڻU�_�^S�c����Y�{~rX�2������܌��ah�n#�������ї������e��>��h�_5�}g�"W��=�I@끽&؞�a��R/d¢ ۤ���E�!���Zs�Gd�{+���$\" �ֿ���𝤭@Mg{X���-��w'u�D�ӝπ�#��2�� �[� ��
+����@�V�8�wuS����d
+���ᮤ�麑0j9I^ b��s+�0�*�d�R���Iu���� #\U�&��|����'&�|B=x���X�����Y3 W+��"�-Wf�r���}��a{k��( ���2�J4�7��#��8M_ tĹ�8�> +>���8L,�0�ȋ����cz�H�s;�^��!9�
+endstream
+endobj
+590 0 obj
+<< /BBox [ 0 0 449.05213 244.08 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/degree_distribution.pdf) /PTEX.InfoDict 691 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA .85 /Type /ExtGState /ca .85 >> /A3 << /CA 1 /Type /ExtGState /ca 1 >> /A4 << /CA .6 /Type /ExtGState /ca .6 >> >> /Font << /F1 692 0 R /F2 693 0 R /F3 694 0 R >> /Pattern << >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 7294 >>
+stream
+x��]ˎ%7r�߯���Bl��I� #{F ���B�4�$X�f~�'2���#JՒ<N�@��L�C&I2�����훿���'��������/?���[������������ �}���p�(�q?���{�30���������GH�#.��v�V탵w���%�pW�
+�����8nmP��==�ަ������Z�����M1���,��=iel��hW�����?߿����"�7��+ք�#ت�M����G�I�����@Z}r�� Ws>t�e���A{�7(�mI���3�^�j�����q��?�cMrd��&ϴ��jԑRr4\��H ���- ��I�f��(�� iP���h!1�^Ő���B�u�%�I�
+o���Z$�JLq~���H��LNUx#-���Uq�&)��(~cN�@�G �/�@���yV�Z��*���b�FJ�!ER�X��v�Y����0)T፴?ܐtaҢYL)*o:���[����Ek7�P-D�ˀ��(O�7�B` -��6�07�͂��p`���chQT‹��LZT�)Ie�$b�FZ�n٪����Y��v.��^�
+�ZD��Men7��UV�G���chQ������lS�B��(�7�B`�p+V9�+s��,�xl��1x-$��"(�qs��,�8}�yX/�7�B` -�/��s��,�1�(.1x#-�7��U���͍'3�9�A$ș��`�|��Of2��+�L �I�4鑕6h�6���7��PʬS�w�C =�Qe��v�� :��idb�FjH�I �lƕsK�L&ӧ�T���S��;�!�&=��XʦEc�L&'�ej�Nj������hі6��4F�Ub�FzH�I�(;iі6��A�?è�w�C MzD���fі6���D;��句@��(�d��-m&��^$�^G���i��B�̢-m&��s� Ŏ:1|#=$ҤGT6��i3������������H�E��qњ6��D 8̨�w�C =���QwX���D��s��Y��o��D��@n�szў6���Kub�Nz�I��2�W��%f2���)�N�I�4�h���U&f"�xR1 �*��i����b���Lʊ����_�N �I�4�:L�Xmb&�F�wub�Nz��G4�:+N�D����Q�N��o��D���H��,��f2)�Pt9�vu:1|'=ҤGR�[�Xyb&�m�秱^��龜@z C)�X}b&t&* �Ө�7�C"Mz8ULq��f1ɫ�VB�Q%��ƚ2���)�y3mW�ɳJ�I �3��h ��w�1)�]L��N&�o��D��p�9��ei&����9�:U|'=ҤGT>9��]��d�U٣7q�N �I�4�Q�[��?�,�3{�ìR�wRcMbВ|��.�h&�h�₷�J �H �3�T�٧E[�L�������T��H�#�X�-m&�m0}-n֩�;�!�~�Y�����ܖ2�1�*&[7���}�I�A����B�Q�1;T��Nj�)��C�綔���q��f�R�wRC� 9 Zì���Rf2��l��a����!�&=�J�c��Rf"���f�*��i�#)d c��D�}�1�Y��龜@zX���y��ƺc�9�T��(�͡zі6ю��4�T��8�I�dKXU�j:�c�˃L�I�4���4�zі6�1�,!�4������Hw>f=����*Q��nЉ�U���ӵ��ws���~f�����æ9:�}|���������|1�� X��|usE���Mǔ���C��9���7_�^��o���˛nc,f���ǀ\�bQ�꡶=�}T���=��/R.�C�1.��cy���$���R3B�x��Y>6����K�@$T� �y���w���t�Q��d�3���׿�w�1i�N:�t��L:���)�W��e�1�#aX�5ge��9�ym�����v`� ��.�qΫ��e��������+���C�(1��UyM�:i����T��+K髲�eH��1}M��9�'h� �����OP�)�t�q���Pk�l*S��h^ѓ$7$�� ���)K �D�t:�� �D���C� hR��v&����Sԁ��x�:]�F/UJ��P�G/f��TxJ�P��-�B���q�d�P��<d����Oh{k���j��t��C��{g"F!�V^����&�7�"���q��O�����ڄ�8�M^�x��W ��|���������=��z�G?�gwކn� ~�D�EH����^�>��G��|z?=9����6]0�8|�`����q6�B���(�hC8���p���8.z�^�iQ_�����t?�sNj���1�sG'Le��wtΥK;�Qi_���Ea��-P����c*�ꇷo��ۇ�ZA까��2u�v� �n�M�-C�)��u�Qk����F��(e�S��f�W�|��w_�[��_?��ϭ&>z���jY�%�g���P!Q%�K����0���>��,Ƕ �q�W ��
++:���?,��q+�F��_B�QDh�[P-�U��j��L��
+�� כq���vDy���y�3�?�S:��t�0���~�Q�=���̛�
+�D�1�$ �&u�QG�rY��a����A��K���.�#��;��W�^M��§x8y�p���~�N+���ՂQ3�8����" �&q��43�4oe&4�*a��A8~Q�?��yG(z�f�L4�(���FI~Q�?P����.��1���M�������פ.�#��Y����6 {��Q�_�����GL �+ۂz5Ѿ�����sE|Q�;"N�ò]}�n&�?�fT\�_����Ql�fA�2o&�f�fga���פ.�#�V��_�z3�k ���n. �/J]�G�3��kԫ�>b�oΩ ����.�{�a�JA��Rg&�Њ7:^*�$�$u�QǼ�ч��j�=��X \:I~Q�?���wƘlU��t��p��<J���R�uڐ��W�^M�}<���I�_���� �튫�:�D�6�8}|��$a�5�K��: DsY�f&�`�>W�:I~Q�?���7Z*�*�j��6:|��p���~�n1�.�/B0-l҇�0I��kR��uL�]HeQ��dbT������.�#�zӡ�U�W��ԉ�c�P�H�/J\`ⴭ�.�q38��7���k��q:�e��3��T��ܨ� ���R�����;�*�j2��|S�&�$ �(u�Q/��.��1��*�i)��0���~�N�����W9f"��-#,$��5�K��:&��_� o3����������.�#�x��^|�c&��֬��I*~Q�?PG6�y��.�L&d<� ǯI]�G�1�9-��1�)�dFI~Q�?�N{���U�WQ��ymgI*~Q�?����GW�*�j"��ъ�,I�/J]��4(�h���L��9��FI~M�?�����<dQ��D�A �$�(u�Q��;i��.�LD�ؐC�%��E� �@=�dvQ��D� --�$ �&u�Q�c >/·1QL.fI*~Q�?���wIf�{���"r�B��_�����^ǥ\Y�z3E4���Y��_��ď�;
+y�:��^MDQ]�c�$�(u�QG�Y�X�z5c:;��<��.�#�� �ED f��g�=FI~Q�?P/VY�L,J��(�)��,IůI]�G��y�iQ��tR���Q�x偬ď�gZ,4 �t�me����.�{�y���_�(g��L�(�~I�"?�N�� ΂z5��gE�����HG8tX�y5 �u�O�Q�'���~DS�h�_�y5�/�`����.�ucU�>.��2��{gw�$��5�K��:�¸lQ��D�/U�ΒT���~D�y�V�^M4\5:�#�B' �/J]�G�L1�v&,� 2Q��ѭ� IůI]�G�1�N./�81�q������ I�/J]�G�i�#2�*�j�/pm���$ �(u���.����L���b0��FI*~M�?���:-��1���>�0)�����H�8V�י�XR�ޝ]���.�#�Nq��w9f:��t\�_����<�nm
+��r�tl������%��K</I��;����|>"V�Pr��:_r�+�;t� =>�L*,�&�&���%���ꌏ�� ��Y�����sޗ�a,ft���/{,����/�9/ۼ/uE��/Y���X��{A�I7H�]wFĒ�ވ��1�@]�z�@< �
+ē n�x��'uI�g�.I��K�|uIz�@���;P'r��K��uIzA]�!�Kһ�0A]��IO½�$�� ^a�� ^aGA]��)�Kѹ
+�0_A]��YPW������$�_P��s�%`���ˠ.I�ԥ��������|�,��<�~S���{�`�t{�y�s{�K4����{��QDy��aǹc~���a���Ӿ��Þ���zl�f@�����������uԿ/�����7��y���������_��<�ȧ�p��1� ������%�sp�V�Q s>���_��Ɓ��m���&EKƏc��ѷ> ūo��\��=���Q���ޞ�,���3�^;ɱ�5(b���t�g]-�>�. �H�G��� Mh��$�I�f!/E�6���� �� ����]�d��B������}��B���SLq~盥`NZ�������!�}�E��p 3�P zF�sO�G��A 0�N����d�����tĩ�>2l����=7�͂�mH�����i�>2dn%%�p��dh���|��;m��md��B
+I_?>�2TK�Al
+�葉��}��BLEl�an%���$�F�<�G�.�(*�u?���BT �=� ���Tt!��LҼ��l�Y�`����BL�n#�DBD��Men*��S����S�}��B��L6�ύe�d�Pb�1Z`�0t!�7̘�)�̍e��@N�����m���B�@K��͍e��o��݉���j�K�kЋ#�ؠB��wx X�
+ ���>� 2?q�{d�_��!&���eH��3[�_��! ���U<rU_P}؊��G�
+lt��x�r�̓�$�l6I�"���-^�R�N��@�~Ƥ�����Du �J2�yO)-����+:�J}�ᔜ_����c�������H'�� /�S�|��+:^�T@s��� //4�ty�LE�˓��q�LC��-�.C1��+:\�1ηh��
+����|�vu����r��H�
+�bj�xy�@�t������娤6�!LC����9
+p�LE�x(Uކ17 �8�pHA:��%�>���!����h�^�����>�5����Z���<�登?����-���c5߱��y4���A�����.���{ج�q?��"b��>�8���Z�N��Pм���Q�D2�-+4�;+��_�[E���{���jZ[�u��,�2��Ћ��a'�/v����"�ل�i� � ��M�� �a����p���Ie��f��0j���9�tíT���*^y�1�Z�RM�=� bqx'5ʤ�j��3��f�^$句@��c`Z��k̬F3ђ0�{� "1x#5$ʤ�X>>�Ԩ&:Y@'L"Ux'5ʤFD�^4��T��9�=:��;�!P���!\�hE� ��d�9Q�"1x#5$ʤF��E+�L��qZ��H �I �2�q*��D���S�v�A K:ж�lˢ�l&Z�zy��e
+Ё�I��d�~6��V?��i"1x#5$ʤ}�&/��fʞ� �1��"1x'5ʤF���E�h?����r�1 "1x'5�g<]����f�Fѭ��L$o��D� �bQ�^=fJ�KO�c[��wRC�|F}9|$���)�/�N��\$句@��btZ�57K"Os1h7H��}����<�ZhQM�X���c��izg����?��eԈ�;�!P���t�MinA�)��d�X��"1x#5$�ݹ�Y�jJFѧ��=/��;�!P&5j{����Y��hэ�A"�Ś0��д mgD��VX��;�8��c�)�bXa����g>�0���eR#�h�^�a�c��A$句@��(h�_a�U@Hf��;�!P��Ǯ��6�f��΄��=���i!>�h����3EO�k��L"�����bb΋3$�i���B�I ���#J�g3E�(h� �7RC�|ƂA��^�����|� �wRC�|��� ��RA�� L[U{�8��k�g��dm(�ֳ�BR9�X1�D �H �1���0���ֳ�Ƚ� ��A#句@��H��B;�f5���ȸpN��F �I �0��0
+Ɋ_���D>���$b�FjH�I �eg+��>��qv�݊�;i�&LR$��n�~6��ʻ��TL"�����9���3yr�7�F �H �2���csZ�!1��
+�
+%"1x'5ʝ �Y�j�t$�L[�;�8��eR����XC���z6a
+5t'%�t�(/F'�ZAj&�U�!����8���3��!�V���z��F �I ��
+��j��LQ�5N��f�I ��&XL/�g3���������Ԑ(�cb�ݭ 5��<��Rz����3~L*ř�`���hg
+.�qx'5�gH��1�bi���J��G5����"eR#(��]|��&:�e���J�I�4�A��|\ ���
+���t��Nz�)@�Q.8�|փ�� �9:q|#=$Ҥ�W�дk�G3aޞw�N�I�4�TtZ�Ek�L��FGJ�8��i:M�U��/\�qS� ��G?������H�N��G7eO�J �N�I���ES��E{�Lq��ht��{�F�N�7��R�����a;��#�Ro7}T��ϰ��3�7�>������;���>s����^��� �>��a ��`pÏ�3o,�~g�9E�Y꽢��-
+K0�E� �c�����p�(,���'`�Qx��;
+O�ܣ����9H� z)����^p����9I� z/)��8s�� ~Rx�(�'�=���U
+K0�J� �������0w)<A�/�'`Sx��cJ�>0�)� ��L�0�)]��k��<���ʿă�_��[�7Cl��D�� �p�%,��Y���7 ��o�dqp�%NGT��+�B��|��������1�6W&���1O O_Vk�Px�mI�v2<����˷/�ޞ����nS8L
+endstream
+endobj
+591 0 obj
+<< /BBox [ 0 0 270.72 163.62 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/plot1_em_f1.pdf) /PTEX.InfoDict 695 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> >> /Font << /F1 696 0 R >> /Pattern << /H1 697 0 R /H2 698 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 1520 >>
+stream
+x��X�nG��W�%yа{�{G9�p�r�sY�Aʈ���ߧf����2�b;���X���t�h����w��O����Y�mq߰y�ύ!��O��>7 �۪q�lt�u�������;u��m�7�����ы��b�Ϛ G+�\���>�@.f��evbEq�٨���f�G�D�3�j6L���kȹ| 6'�j��/�����m�*r&+�1H$�~af?_=<\�ݢ<f�#���m�ۜ99���Jp!r/��b=^���
+D:O�K�ejP�uB��|JΫ�R���ģ�N��a�n�`ifN�C/��,��%���Ė�(�.+ 5��R<�gE/.��=*��vpN�KֶC�����Ƭ��I�Y�l������`R$�S(]����.�����A�X6�&��@�@���{!T��y���<�7�gl��!�(�h�o�諔�
+X6b)d� r3����L��u�x��3#���U�3yq��x;5������i�CVlc`�~m*���J��+;�E6y�S3߹]�Xuq�"4 
+�����~��&�A���%B�B����#�\����~K��1&��) #w�-�Z�|�q�kǨ����2�2��BjݺCn�1n�$�W�}��r b
+8* '���w��)�3\�m�ĚT�)S�%�6�eղ�z���?�&�RY�;3�Z�=2�'߽�v#����|>>w�\ڼ���AN�����㝝�OmV�%�ղ�4*�ٕ�/��Jt��i�H�S\GNV��]qL�q��k�ZA)%e�L� GL���Hr�@1��ĸ`��b1fTv>S���mcd?�����Pr�\�i]T ɯ �����F�բ�6���ݏ՛�d�B)p��[�n_���h+$�=�����͒� &<� gT�O��T:��ޑ���?ɀ,6h!�~�0N찹�
+��S�+���
+�ZY��=�1
+���+ ��Ē�⦆kS[7�@���}Ȕ'DB1j���ց�ؒkm��O�q��nG�۽�O�K�D��b���8��zR�'�Aa�'=�.W��R��R���}g�$�z\�U�U Hư#�;����w]��(YL(���yT]Uޱ�@��s�{?�;Vm*b+:������qms��5�G\�Q�*J�d�<\��O�4�e��A� E����Ō�LiS��j+�����x���[찋B\k�t�FY��"9��G�#� �_�6"���Q�8B�JK�ػ*^�5�e �c����4�#�VqD�`�̧x��g����L �� �0Ո����������[+�E�UA��q8����.ٺj A�|�.{h�-��^�B��ݺ:��R��֐���
+"�����e.�z�F*��h;�\-�˲�\�Ĉ�Ci�Mn���WW�������eW�����s��'�����!���Uj#�Q� Y�!���)�Y|�}���qen��W�l&�`���Zp
+�����
+��[|�6#���v]�f]����I�W
+endstream
+endobj
+592 0 obj
+<< /BBox [ 0 0 224.92906 163.62 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/plot2_latency.pdf) /PTEX.InfoDict 699 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> >> /Font << /F1 700 0 R >> /Pattern << /H1 701 0 R /H2 702 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 1224 >>
+stream
+x��WMo7��W�(Lq�rx���"h�:�CӃ�ʪ �Am#A�}w%�R��( jX�����|��ٷ��w7�����wf6�n� �{|���{|>Y���,��jm��+\|,W�%�����?��5�sl��ƈ�T2Q��6)0J]�9�^�a����4�4p��/��/S��=����<y�oL����c�`�W�`g��r�ؽ�0�b�8Х��r���x|@����O7Ƥ�|�K���Jⵉh@q�"!,�Q�sa��� �RP� \b]p�(d�v?@�,���j� ^rIm���8��>i�]��)q>4�Ӿ�&ԟ�Ӧv��m��O�bnfߓ%rE���$�[���%"�l��r����a&?^?/n������n�^n����gy�q;�G_=JT'�9e�ĕ���L�����)� F��]�bh<艞�b���{�c�5�[ ���=ѳ�^ h�j�z�c� 5��E�#��|��}`D^z�a���0�=�m��2�#�#u)�U���A��ov�3��-������������n�o�C�o:�m�p�a=��0}���'v�D���#K���w�-� ���ImA�s�ޗݵsIV3����3���w���W�}�.g�)�ʫ�թ >���ҋ
+3*Lh]�"�HF;u�q ����3�����F���7i(�K�-_��]JQ�L9�M�FV^�[���4u��bt^D%�qIM�fڋk�%C �LT���� �W��Kd� â��^�48���F9������ t��$P�� 9�'H|��D1w���Zw��Cq��~�Z,p�yy]�F΅���L��>�yDm�(kL�uo���QX�u>��:ϰ� �2����/>҄˒cl���O�a*�Bhu� m���T��ӭ�2]�qe�Z):��3��^ ��
+�R���@�u�E�-�:f�zHe�@V�('�f���V��51� .RPK��r� c>EA�)�����2�,��h'wﮯ·qc�=�xU��D��86ڢ{��z��n�������߹]u������R�rP�W���:�V;(c8�@�}#��2��l�dE����k�n�ӱ��s��v��8{Z_�V�~Op�\~����U0�D@=��j�Q�f�C^�W�q�J9�����ϻv+��E�-��kS�����G �,��{N4Y<����ǛSs ���>�������qJ
+endstream
+endobj
+593 0 obj
+<< /BBox [ 0 0 504 432 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/disk_cache_latency.pdf) /PTEX.InfoDict 703 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> /A3 << /CA 1 /Type /ExtGState /ca 0 >> /A4 << /CA .8 /Type /ExtGState /ca .8 >> >> /Font << /F1 704 0 R >> /Pattern << >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << /M0 705 0 R /M1 706 0 R /M2 707 0 R /M3 708 0 R >> >> /Subtype /Form /Type /XObject /Length 4006 >>
+stream
+x��\M���ϯ��`.��<�v"�H��^ �c-�Vvl 6���gX�tO7g� `���YUd�^={o>{�ۛ�W_>�d����M���� o���������@�s�{}�����k����Og ���?�n���_�����e��K)�Fec��`cI�#%)��r�
+ڄ� /�T�Y��Խ��0W% �,9D��6�Q�_��JG��O���On7��He�)$����>*?��0ܐJ>'�ȑn�;<q�<:ܾ=���� )٬�˃�I%lt��i���菾~zdt�@���l��������F�)Rp�/��T�t#%���R
+~����+N+(��uE���B�)gmЎ�X��5!or�3b��7 �D�Ǭ�7*_����^�[oc���$�} �X��C�+ ��\1�U��6�T�;\�N]�)ђ'��Y��1����
+���-2K+���d��Hr&E7�!�69������D�*�nk�Eܫ>���vF����J%��k�Bܩ�d̀`@��yNx��CR��d�Eܫ> �"���¨>��1���Ⱋ��
+�!缱�j��7�F�Xc|7B�|9<�۷�_�x�����&F�������o�r�}3�~�:��ń�#����+@v�j߭B"^��� 1�Ez�q�V����\s���Kt�C�i��#��/����p�E;'=p> �=�NV����=){�F~y5�k�q� .T��!�Z��"SN���El-^L� �� ���Ç2��v���*k����P!�s�|BnMT�y��0�����5�~L� :�(EZ��V*M�y��2N%,���@֤[�Q���scv�[r�Lv��{9N%,�3 ߙhۤ`�3Rc��[@����N���>ni6��9e��ԦSv��8�P�9I'����i2p;DF� �"��Xk�������!d7� �'$���&�5xI�l�����6�)��K$�0��`c�<���A�&el�� F��A�D �<�=M�̄$��3�:��G�� ̛&e y���8����l�#Ml ���Q�J�+j��%G<J�.bY�N{�����4���U�����p!���G�#H���aÄ�R�.1$1��Hy�3^# �t-��"��Ő@J�Ǿ���!9��%��&ƥ�×�cd�3(C�fH6e��kϕ�^�䐭�Kl}����8.�mB.BŴ�\wq$&������M��r�A�f���{?x��5����KZ׏w3���_����Ks�7��i.���dz #ޫ�y���Q;��u����~�2��x�^�{�s�J!�L�i�ú~�s��y��$���r!�(�9[�_�K�!� oLf���*R2������3]��Ù,��˓|�wΙ@Ho�b�Q�p������/`���#d����oo�}�S�FO��l���=�a.GA�!m�%��
+I��� !����\��q*�����v�C��ۡ�H1���"g�Ez�<$Ʃ�f�w
+:Cj�; ��7v9*ĕO !�r�J�hva�ѡe�!�z̵t\�Q}��l�G��ng/�wmF��-%�r��H�ぁGʷ�*g�������(4�1ʯ�p!צ ��t{���&н�=R~ s!�7����T���4� ���B� �o �a�����L ĜlJ@�#�s�����0 ���&�����׉o�]|�}9�O>?++��g}�J�Ӈ�ڋ�&p���P k�AM(���AI��Å�u�Bjɉ��S�Fw��v�����������S�G���t����o<-�q��T��"�q��:�yqM�iɍ�='�F�z�����*ؽ '@$�J�Eک;3%�@��t@F�i<g����r!�Ԏj�G�R�M���l�p����n�\����=+hԾ�_��b���:=��L@�9�����<�'s�i����O�^w,^�4r2JSG�E���B�y.,d�����?��Ң��ui�H��������T}�J�8��Ler��T&1��t1��&O%$�Ko����r*��������;<���l.��j_�>NU�1LG�j���J���!��wƂ�� ?n�U��p�ˌ(����$��w��y
+�w$L�q���C�+�M�E�A��h�;?e�,�Ÿ8b��!΍*L(�Fre����b�N�Q�8U`���U�۹�r4��}�Ctp�B��F�׹�v4m���Cto*G��Ǒ��s�hZ:�x���TQ]�=~4���xG���G<Dצ�;�h{9�1�����x�dq��C=���s��z�惰Jyo+ E�uHبCB���aƢu�` �8��ME�{��`�ׄ٘ 0'v62�YN�uc)��C��/Tt����&���!]�|��@>����z/ Ast��:Jt��ZrF��+a�분��6?�d�L�L.����"VތIՒ��et�$TF��Cet#��� �S1�?�ɥ�Pm��s�
+�"FQM�P ם)~$�E��2��*���8���T7!�x�a��7���0�M�s�ͥ�G�m�#*�Qk;��h<����T���&��h�8�P�s����P���Q�rƣ@�S���V&[���R�qf��K�cJ�u7���d���l�V�xZ��kF�u~;w���^�`yf� ���QDf��"���q�0��, �C��s̍E�m@O�s��5�|f_����ج����!α�@C��� x��١Y!�6��B%��� n�a�*�?���ˇ�%&<9`NjNm%��*�|��E�"�Z�%T`A���0[b�O��.���&�u�|�5�(����JV��r@��Tn���]Xk_���Ԓ�$#��J4�P�yO�D�`�頧�/��ӣ�����-'!�/g�8"~>p;��'�l�n��$ܽn����~:=m��<#z:g�%�\F�1�O�m9NB��?�� ��[�[O9 ����q�gv�z3�B��5� ~��������H�{���i�oc�4@b�4�{Z��G���# ���ƀ�# ��# ���րKسٛCrQ���h <�{Ffp�n�}����Zs��y�ذ�ho��Or���� �����2�Ӂ[�� ��i���1�:C�� �mj
+XE�(��]7�l�Jcv����q
+��‰�u(x`t���+�Uȯ27^4��Wg�ćN�y�Gy���`"��{yF���|*v���<������>��7��@d7��J��a���\�b��z�O� B��DN<-Qp��^�Ѧ��<-�Qw`;���"�U��qv/��Y�|N���W;ji�;��ت���K�{��+m�/����x y���dD����D.�.�!䩹l�/[@�6�uDݣ#���F�����Q{$��a&nYmu��ư��J���M�1}q���\+�2Q,x�xj���`H`�5��*�sʹf\�J9JW3�j
+Ɣm�<4�h��<.< �H�����������r��|u� ����/��WWݐ9�P���[P#�K��;��Q� 5B����j��P#Xj���i��i��i@Դ\��^�����h��z�b!�Q��̷Z���X���6e��d�NUñ������|��Q��cQ���ă@�l���>Ll�-_n ���j��m]����o����蠚_Q��t!=�^�������� A�Ș�ͧ��եg�:�/�����`W�|���� �n��������Qǩ6�K9�h����F��y�!Q��UłE�X�r��X������sE� �g�R�bPO�
+R,�#���� �� �%w҇Y��X� �\WO��:�񩓆J:���Y��^ʅ�B����y��z��-�i9N ��3+EV�����]� ���HPt��q�|T|�w(n� pƲ�l���{��(������t�~J"���:b1|��,x�N��3���r�EI��1��o�5g ���0H�@�sgΡ�F�d��ғ�K8/��=�����
+endstream
+endobj
+594 0 obj
+<< /BBox [ 0 0 502.1103 119.88684 ] /Filter /FlateDecode /FormType 1 /PTEX.FileName (./figures/main_eval/bottleneck_breakdown.pdf) /PTEX.InfoDict 709 0 R /PTEX.PageNumber 1 /Resources << /ExtGState << /A1 << /CA 0 /Type /ExtGState /ca 1 >> /A2 << /CA 1 /Type /ExtGState /ca 1 >> /A3 << /CA .8 /Type /ExtGState /ca .8 >> >> /Font << /F1 710 0 R >> /Pattern << /H1 711 0 R /H2 712 0 R /H3 713 0 R >> /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading << >> /XObject << >> >> /Subtype /Form /Type /XObject /Length 1176 >>
+stream
+x��WMo7��W�R@B[j���-vR�F�ڎ��R{�ؑ�4r������Z-Wf `����<>��z���|{�\����b6<]��;|n$�;|�H�'����R8Ҋ� 9<.�G�b��Z�4~|'�[1{�0k,;"�䓋Z���{k) kev�E 3�����*�Q�`됡"��8#u�-hI�>�8�I|Gs1��e~E{K����"(-�W6F�M�/9�����x5-��QE�Df�6���y� q4�q�b���:���j;�.���Y#��h��ױBnwɣGl����Y�#i��#�;��:e��ޏ� xrm��gbr�W���!� 8b��@��"�$�
+��7بd�O���=�DJ�>%��L�#��6�r2�]6S��A�D�-Rd9��,חө�S�O3����'��4���[jԟ�u�ϗ���Xq�]��q�������6�Y���Y���c#�+��ivD��e[Q�9x�%X�����C�q�c���X��Vb�.࠘�c�CY[S��eJJ;�q�u�.�Ϲ|��M�:��ep��p.:���&hgiyq"Ǻt��&a)ЯZ��caZj���
+ʲ�A��]�i%=�c:9����E�-8J��[���
+��0�d��J����@sZX,fiȧ��]�P�F��"��g�X_�����8�8�?��B
+�q�B$���%A����`5����h���g���6lUY�"��T���!���-���‡9���.�J�'�#�*Z�z� Lʴ;�V�eΊ _!i�+B4��LE]��-��R]�
+C#�[WM�'l87�Ms��� �q TƺryAJ�킞�b��j�F'xD l��۾@Y�.�(a�G��e��{z�#ț�)vGllD��Ɠr(Nl\n���8Oԟ���X��������� e��sWgcɐ1IN�y��G+��D;;����߿��3[t3{/ )'A���\���6_
+c+'�UH��7�Ea[N�&�<dˆ��V>�3J}���d:�X���rı��'�g���=S~�X ��C�O����S�s�M%\�^ޮެ��J��/?|zh,�� 2���lˡ��=�����%��`.҈���`��:�Q%8���C�~^58���
+�K����^ ��5�׷����.��m����4K�*��q�����H^w��_�X
+endstream
+endobj
+595 0 obj
+<< /BaseFont /PNRYLF+LinBiolinumT /Encoding 714 0 R /FirstChar 27 /FontDescriptor 715 0 R /LastChar 122 /Subtype /Type1 /ToUnicode 716 0 R /Type /Font /Widths 717 0 R >>
+endobj
+596 0 obj
+<< /BaseFont /TCFTCN+LinLibertineTI /Encoding 718 0 R /FirstChar 174 /FontDescriptor 559 0 R /LastChar 174 /Subtype /Type1 /ToUnicode 719 0 R /Type /Font /Widths 720 0 R >>
+endobj
+597 0 obj
+<< /Filter /FlateDecode /Length1 1756 /Length2 103156 /Length3 0 /Length 103199 >>
+stream
+xڤ�p�ݶ-�N:�m۶:~c۶��:NǶ��m�vn���>����[��[5�y�s����yɈU�L��v��tL�܄���FGg [��0!==+ ����5�?wa���Nv���‰8 ����:������۹2�23r�pp���y`b�'�Α�P�ΈP`k �u�!���p�03w��(w��Fh�A�hnamaoO(IO�hgmM�ox{�-�_� t�58��t�q"�3%4��s��5#wU�L�� ���N'���P�%��� � ]��-����"t�p6���G+��1����ښ*��� ���\��}{��?�‰�9�)͝����:���z'Sz[�3տ%��9����,�Eֿ#�ߑ����w��;r���]�?+L����?��W-��J��0233��%1���L��D����O�`� M,�� �f�0 Q�z��M��x�3tv�p'�a�gdd"d������1�����/��� ��AE]HYS��?|�/����;�#'3! 3'!;!#+�ϿS*Z�%1�W����!�?*7q��g����5!�߾�"�w&y;�?]%�����������+�/C�2�1��=�g���ϖ��on�+��/��Ƈ%�7}�+����� ��x��(��ݴ�?���x���i��0���h�bm��T�o�S���6�O���XX{�7� ���u ��?I9��K����_�c�$n�0Q�p6�������ju��� �vN�H���[���V�''B���H��'��ۙ��P�?}0t4���_��.���:�����Z��pì,��[�w<�}s�;� &����*�6F�����5���;F$%
+.���ږ&�i���Ta0�u�A���{����c��@2��wle���v'��2z$� ���q���y1Z�%�o�d�A$H����S��v�f��/<Džɹͧ��a���L`�������RHes��+�z ���ؔ�_,V�n )Ǘ�bW���̯��y2��ϡs]���E��v��"�F��f�\�M���Xޙq�M�l�k���x(�����et�k�q�bu%Ҵ]�(����>#����T�����Ff���d��\#U�ڧ�ۘ����j�5�;ci��/Մc/ŵ!��P���?\~�Q0�d�/׎T�o��%YyOJ^!��ñ|�I��R�bD��s�N�0���^��oj�8��k�:$�m'ב�řJ�Q�==;�(���� ��<��
+�k���zD&�ǃBd��Z�Ir`�u�YŞW�d�A2��۶��҅��y�sL�_HU������hj�[ӽq� �7�
+��|R�����b�xgbٵ���cw�������h�T۝o��&ͩ���/��Y�qx��lUR�=t�z"Y�� ٰ�|A�AAWi$�������Iu���"���/9^m�R� l2����Ù��Z��^2A�D� .��� @���ǜޒ�l�;�,��Z�32<��_���k�'"5��)wJ�A':ǯ�|
+� �A�UݑJ���Q;9^�*h��@4�� �=��q�C$��O`��W�C��苌�F�h��?��;c�1L '��kƄM��<y[Z@[ ѥ�i ,����}��u�A�����H21h��� ��ѷѶ�����<)N��$@g���&�v�"k&��r���y�t9GE�m?��gg7�5ڇ:�!ž�$Qͅ� N�����Yd�` D�@��p���Y���{Ia� A����v ^-�I1b~��5�j�j�w��PA���g���3�3�R��K�dcGkL��v7���l��lz��+�{�p��nϮ]�.�DU�/�h�~��gפO���'5
+��Ѽ���>�hD�G��W�`��
+!!�r�iF� '���$ɏ+��8�fԘ��zR�t}�l�G��}k ��$�3������Ζ���l��2�$���(N'1�#5��‹Oy�� r?"��ȗ�6�ۏhD�V���Z?Fq�4�~��6��w�@i�q���1��ǘ�J��h��E��2�ո/dz}q��m-�\\�&�?(Q�|ؠ�>6tp�d���@1��)v��ŖϚE�����3�^���2�Z/���D�A�+�xw-�1˫�����?E���-!\�;����1M����I\����4,K?"�̃馣r��9Y=��ܼ� ��dO �'��^�^`"D�Ӎ���� �0��/���!�i'vo�XN�`|���?���S��m3����IJ��G䟵K椖�Y�yd��rn��#����qV-ٛ�֞�)�<
+����$���+���l&����.��V�WN,��j�͐Hw��0����*�㩾Oe)�^�5a�Ҁ?��@��-dqH��Ո���'�a����k�m�S����7����aO�0�y$�۲�Q�MP�k��tVl�m<uH4�=``Ҵp2���
+�$K�� � �ԦM(�n;�x��O=*�eMz��[ھ���Z��ۓjS�`$����vA�QW��j �[�״�*�ܖ��ٚ�Ode�wPB�1 �ѭ��P����Ѥ��0�r�Z����>G9pv������T+� �9�a�=����x��eDS�p�x^��4/�S�Iv$��G�$�c%���{�Tt�$��@]�$� Q�C��7�:,>,=5h���0i� ����P�W��N��#ܟaJ;Cp�5 e��*W?*{��%,y�,^�A�"0?5+�F��:Q/�9�E/��Ų�(4�� �X��q���M ;~�bz��ǃY��D��(MEbO�L�tU�~O�z�G[�R�Ϙ��6 t�=N�虧�Z������q�7X~�6�p�)y��� �l�aYݢܐKP��W����%5�!��i%��1/ME;DUW �jp�ۥ[ �~9�d���&�p�FuJ��rg�_��R���1$�D(��a�on�n�/��:C��`�g��H�Ov�@�MD��kFV��e�n;;f�["�h�M�T�>l�VlQʰR�`��.9)/n.��'jD"�=�'_���ʷ���J��v�Ԩ��-)^��NX�k�f���!w�&/�nXؒ�f3}n!{�lO P�F�j[
+ܟ$��΀f<�Y���gpZ�R��,�.0b�zS���&�Jp?l]��LٷE Ǭf����C��H&?��d?�B��7{U� L�x���̛6xyiy[U�h��|�<Fe��?�F6zf�K�V��Fڣ�
+}aQ{��e`3;��e��chg�>��j424�:%ՠb5��~�>�_h5���0�
+�����RV{�#S� g�a^[?����u�|̟�����b.U�še7�� ����0`�b�� �=����i#�fH�\c�#�퇂�~*��8�g�Bۅ|[>���!uZ@g0�]�D{ 9�V���Kޕ�p��h��#5��6�= �����E�O�Ә�D7��h�L��7!:�}-֑I��p�����C�� �ףuU� �q3�L+`��
+}���:�Y��_ݦ�J������vQ�I�%^��Z5�R���o R PDٽ���"r#��]�U�8AdE\R�8ˈ[f���/��S��P��Ut�BX��)�'��N(��(.��;��I��0�O�/M�]F���]fbO��>|`¯�;�4BO�{.5�oe�zɘ��΄�}9\<}wN@:�;g��X|eT۔lDq�fe�m��x���u�pc��SN�R� �!n&7D����Jbh�4�˖�ADXnB�߲�M�(X2�晙2�p�ӷLau����&��+��9$�!w б� W(*B�g���D�Q�\��6��4 8�.b~q{�e����T> ��f����ljs��n����� �Y?f ��W�\�p\��YI�N��֪B�2��iqd�1ȝ�#���� $j�W�`��a��If�o�<#/od�JO�`L|DĴ��r���~2$b8���4 �\��ԩ>F�6vof̧{3��� +�A
+���}�<O F���z�x�z��#�܃��o�5��\tG6�pFW3�U�_~�p�v\��4���9N�(�>�z �z��,�4%"�ފ9�*)�u9�|�T!��ēL���;�D^�'��d [�r���^�� ֒R�=�L��l���Gp��=)�n��Hii�GE ��D��w ėwM3��r�I�t>��k�k�� 8�ц-}2����w�r���:�pܛ�f��'<��G#��w;��溾�!���TJ�ȃ���j�q)#"5O"�]7�y��[9�N�Sc�C���c|k}%:ڷ4t50�ɮ��{�O�#�h ��RR
+�R?��qfn|9�$�M��ǻnK��}Ңk�R�n���Tja?O��%���엇�Rh\�t?�s�#��K_u��|}( ��#j��/t�g�䍱2(a��M���w�ySӳ�]���w�|�%�Ŕ4M���Fr�s�냑�����_s�� 6����".�fJ�ig�R�x�C�⭾�A���ks�$��X�"wt��������v��70������5.���u�@��P�Qi Q;��"*p��?�����x�f1�]�3"0����R�Fj�J�?R�m��F��hѠ_�9�������f�b�� E?�c�YE����4���7-�ﻏ����M�j����MG��<q˿�H���? @��f�ia�����h�Q8^D�s*[�F�y2yWZ�&�8�ً:o���J��/�d�X�Dǒ��(C�$�qW�
+(�^͠_(/ ���CV���=�lw�e��'bj�uڹ�����eR���v S�� i�w����jtV2�I>�Q���6�#���j�g�|�қeg�C���?�����W��/�@Zn`���V�1��lk���GG� s�;�i(;�|�����jfռ���Y �̖�@�X^��F썳!S?:ʹH��~O$�uy� ����yX�)b��nR���j���RH�*���������ti^7�<m� A$P�(/��4��j1�5s�fy I�)����]bx"C������ Dd�*_;���6�՜1Eb�~�{�AT� �e�!�4SjGDt�E�^1�LI��r6����觺h*~�•�g�F�vlA�W����|��j
+�l�=����/�@�Z��B���T0�Սf̔
+��M�t��'U3��p\w2��oUP�M'��6�%�|q���k���]V3c�e0yKLJ �G3Q�k5��QN����n?SW��F�2a��Wq�͹�w.i�R7(��4��9�{�4�L��Z������Q�%�#��O-���e� ��36��#���7�Fۦ�Cux�U�@��R�Z�6�$�=�_��"ޝKxTi�)��:�2�sd����ĕ��i��vk��.�7� f-�v�n��)�� (��5�f;Tb5��a���*_}a{��> �z�F���*���Ec��;)��!VEr9��jCm� S,sҜ`t�"�L�Ɔs��)_�b��� 7p�R�B bI(W38Z^�3j���#~&՟��0w0���0}t�F��,H�P\���) >��X^P���ϥg$đ&����㚒��N�oE�vVFvzM�[ d6'P�g�,g�<G�E���|��VC:=�(Ur-���y�5*~�z�9����g�Y��񲰼�&������D�\�Ћ��B���]������5��@���s���M���:7z����b^���,�?�,C���_��z"��k/۰� Q.�v��t�3љ&�b���5�ps�C�{r1����q�H��9u)j!�l:sKM9.j V[h�DL{
+�fd����E�8�q����U '�VmpaB����������&ň�B�mזb�bKi_�� bF�d�S�8җ�ڒCX����nb?�g��0 �:����+�Q�J��aT�?al ��o��/��U��/Յ1��*�`]�F^���%�Q�%-5#��f#�k{�^��Ř��;��{ϒ�ڲ�����Z$,b��ʜ <Dw�cg���f�a�G�o���@?*�u;֘}J#�#�E�"�?A�O�kG?\���-���7[DDq������L�B$��nι
+H����^ԓv_�
+1ڵ�ҳ�!��H���U�4�b �� z�׉Y���u�.X��tO��'W��0�(|vZ P�gW�I��~=iψ y��D���7 75S����_h,Q�1�d��z�� N+�M-�;�w��1
+���os(����]�T���xDFX�nn`!\�|Daʄ�8�u�/��T���c���-`�IE���{w�Sl,R�������z�ce~�Q9���'b�p/�,�%���q�=�C�`�嵷!�g�Yӗ:��� [�:�n z�'�<�����A��"���I�eD�PuĞnJ��\C
+X�������46��w���^��2�!�����%�������r,�7 >=޴/���k!*��%�I��n��6������=7#�T�}Q�.~�@��)iJ�p�;��ڲI��Otl�rA�LE��oZl���
+��Ľ�^���T�G���غ�)�N�C�n�ͪ���}�3��hKq�V<�J$�"R����7�)���9����h]�Ք+�T��IZP��#m��e�Mm���a4�RI��V�c�1�4�G־ōYu��q����1*��e��Je��4�u��C2�C��������}U3x��g��~��(�&/L���/l�� �2`�Ā�[H5�KR�דuRV��'��l��|��H�8�oR��\��߀T�ѿ�;1#ڪC��p:1 lײU��a@�j��:s�4W%�~�J�bC���$L�ز�������P� ��-\�2/�ɺÞ�*����D�`��T�����=mA�/,�Qΰ�����H�g���jݛ+�w�J~)m��H1e&�'S�h�G:��Y|�4n����
+� P��DV�� �S��;��/�?T�swg��?�D�/鶨L�[�i}������v�N�>�hT��gp$6Kȣ"�=.d��[�� X60��U�µ帔iu��`ubUw[��N���Cl�:�>M�Z�¸T��S��x2Q�Jt��v�n"~4�Ƣ5�4�~�*i7�ɡ���Ol�Y�f����������j5p�� �tc��@����׃�hV�E��/wFNY�4��=)k��r2 I����e����Gs@������-�s�r��K0�mj��$�EL����[���C]7EM"�8�K1 '���F%t�z�${�IŒi�{Z�IOd�:��]�k0��}��ئ��>��\?��s����q3�.�+�bW�i���MVZꃺ=[z�F��t���_���~���1} +��_(:�҂���^�ol�A��.���� �J��e��Q)jG5r�\�b��7\�y������Y���5D:ŵ��bX3�Ur����R�p�.x�doW��!��$������g���s+{�w �1f^p��3e�0�t(2Sgva��]�������y��ܗ�������O�o��Z�P���������.{�՜�#��E֩91��nG������͡���J*6'ft'���g���]�HO�^�<�-*&�O$���SԬ�F�Ո�>�s�]���/��YOH���*��d�1�XE�i��D8�y�Yٞ}w`�<�):U{��ˡ���Y"M�㚣�B
+= r4Ӆ��ׄyf�W��b�7�]|���+ ������k/�����n8~�D-��#+[�k���z7��ii��0I���.����=�K����W9�{R����J,��� 8���S�)�>#���x&j�=��w� ��z|ih �F_ �p.�2���?B8��Pl����a�� ��j����2��`]U�(��y� ~rO�*���X��j���4���u��.5P�����0�:
+�AV�S}/mh����|^��{�)���8��j�$�V�P� �������}^&��M�h�)��r�����=v5y?����E�[b'�W������g GR�G�g� �(��%�LLJ��Eޝqxl�Y�3.���dK݂m3�h7��Pvm2(¦��.=�R����)k���;���O~�'8�$+oh��i��.� U��+wE0Z���6��ZB�#)���ZesU��&`��)�����@d��G�����(J[V�ؽ{ vp�� ���&�~��Q����>�`La0���a5i/�DO/�V�Y�T��Q������z u >��oq�-[l&` �"%��Pm�\JB��2�Z�Ւ1����D��G����H:�V���#28m�|T%ŋ��2E⾂��x����W@eȆn[���3B��m���f��g�5cj|ǭ n+�h !í��Z�t��=�izto�R�� ������f$$c�!�$�+"�7J ܬ�֏#�,��eL�-qOL��5[O��ȽW=F�$a�Bk,��`���[������|�۸ԑ���oh�Z�G��{K��||�˽m�-�C�[�}*�G�P^�x�g��5��*c :� $��i[l��C��� �%a���Ӂ�{�'%Lk֔�?� }�j^M�(o�,|+�E��m�����4Z�eњ)� ����͜]'���E���jL���M�WB5�)��=���kcjP�w=�C �S~ݱ��qFnՇ��hI�}�q���Is+ۇºF���)���B'����.��<�
+�^ݲi<�ܥ ���g�ڛ��s�Ì�(���8���u��k �"��� �*().猪�; ,��@-�8ڪv睊��e؂Bː��vt L�oA���5 ���7�|;����˟��k@�H\��=�o� <v�{>I�K�K�8�\�r�]�;�zZ�=���31L�A���][��v
+�i��ˆ�y�Y��e���o>m$��4s����BR�z�����+��s˔v��B )";��$M;[����w
+�|���@?r� &���}%��b
++A��L�<�T�w�X]��-M����[��9%G/ �d�®G���Qb�)��e!ձ���N]� '��?Q������:�Cњ�è"�[*ȳ�A>��#T�Z��5���zuTKQ�,�}J-&PNN��tC!��k���u¨&�6�0is�l�>^[Dg�����Z��������W@��d�OZnɺ��Ԥ��5Mװ��a���b�����6�:`��/,QQ曑�g\��;�$$�h�"�i.6��2�#c���; �G���퀼=@@\�&�i�-���|��
+����Ř�DY�riO�]d
+�Lŷ1�v���^�XX�'c�-�&�by妿�еE?��*�R"�x �0���C����7�M"߇Ta4�H,��"Y��qŘ���e�����zd��t'n�H��g�N��8s�_�ʝ�9 �B��
+�5,(
+Q5o���f��j�V�,L�I��׿� �64��=b��3��@���'����{'Nt�_��cI&��Q3ݰꮘ�EfE吆��ɫ@��Q{�Y����y0`}�h����P�ǕW�>�OP��e��D5�T��ގ����(Ɔ(=P(�H���_��0}�,��I!5}�N�D�[ D cF�JA��� d��-�}�J}�1��B�f��@��8T
+m���:g?Q[�olE������;Q�?�eY+B�EN�~
+nAT�;G���,�tf�!) �z6~���2��*"�O��=�T��}�po �_����D�*]΢-����V_]�ǚ�w�u�賟���񞰎�A��'��w%>�@_�T�{Z��(���l�픶�]g{�֙����ȁ3
+"�k��0ֽ֠j0�� �CI%d���˯9^�]
+�5@#���Ԡ0�����-+��)��>���+���XU�9=‹��$������8�}�+�^���ӋSd�`[�}��K���Ιa�T1��@�h8��|М���,���>�jg�N�6rۀ"��x���{����'��e�[�D��軥��@�׬t2��TI�� Z�a���#�%�_ �"%��3�MM�Ƶ�ð�TF���^Bc�[�g��I\AT��X`o�1�#������FB�/��� e����� xn�������V��S�z�0m�:��?t�8.S��f�t�(���g�R�}ٓ�Hp�`�m�H��|���WR`�U� Ȉ�j������!�-� ��r����<2,T��b-;�:�˾��eĢv\y�]qKW�����k�J���b}v]؃�i�7:�%�I#w/��d����`Fs�(�?�x��� 2;��4��k�&��x� 3��|̓σ\�PZ%�f!����S��v�'y6��,B�=�>5��� �T�vp�ѷX��pǓ*�͟���g 8/��4��������)��i ��+]Cy%��mDJ�Y;O1tgA�3��j��c�m�~���n� ,�Q���G�B1['V�~�p�ei0���U�����E��h��힃ە@�9��������sBo�j���3�dz�����
+���N�A��)���B9��\?��8�%���>N��?ȴi�,?��FO��d䀐�E�oɻ|����zVj�Q�,�e����!�'����@��|x�r�4=ڷ�}AJ�K�pO���\�������H�&j݊�"BsZ��%��q���c��7P�'�����\>���Q��L�)=ŒZ��i�eљD�ǫ�Gկ.( �J�'�t�ռ=2�0��3ˇ$��7�uij�ҭ4 ��Ү���qw���5�yP��l�
+�I�hM�Zs�8�:f�h k��SuC[X�ls�c�U�%���4��� ��r0}��^�J�z���\�R�K�����„�ь⟶��3=�q�����Awzڑ:�KHgj�{O� ��3�4(옓��Ƭ��e�fʆdK�E�c�[}U&#�YV��oc�dw���N1�#���X3��L�R���}F:k�j���)A)�Q�C���K�<b����[��� U�v��?zK2�e0d�����$�1#\�e 6�[��Gh��5��򏷄��.k�`JP&!�昼��I��`�ޏE�%,�QHm63����t*�<�|1��x1��P���
+�_����|�K��-�f"�q��R��2�y,F�A�Ia���YtcXhNJ`�֭��(]=��W5ɑ]��4r�%��+���JK�\�'�|ĝ�9����+�vqPl�.�������Dc�@�y�ncH���h��v(.݄��`�Q_%������ܣ�ǘ��e����V *O�/�h�����s�‚�����K���V�j6$8A,sr�O :��ޅ�d�!�5��s�6V��Pi�u��6 ��z8�}6.E��������e(�Gֱ�H._ ��z�Z���g�yki��u%�W���'��N��W��ֱ��G�O�M���g�
+NL X�v3o���E�z���p��3��*M��[�ԏ�f'��I��ǁwX�Ҕ.v���,X�Z�Q�6�]���>p��yS�.PW�_�� �e5���g�q�T��3Ezk��E�=��� �?3 �W3�L�O�0�#�D��^C�+2���z-IQV���Ӷ�������+�LS0[��Ζ��^zKژ=���3m�" z�I���[�� �Űǯ����]�z/
+��D�N�C�y�]ӛ�϶j~g�P���"���A~�=`^� �R�<��mA���Vđ-�Qd�y�y}��~�Q���*"3ԔVڠ���L('��V{��DN0!��_E����&�5p��P̈Kb ��T��X�ES��DEd���;�XI�e��e�vp�S �Zv1�]h��yC���BMoȿ]e�� �6���n��1S�����B���+�����rU�X�����"��r��yu��A!���B�?���i�Jx,�z���W��^�MM�7X�#�S��U[;����&�p
+m�����^S�PF��b��i���� �.ꄁ�v
+GB#�i/��)8s��l�e�]i��p�Q�V8�j���/v�*�F��R1��M��U�_�V���5y�_K��Q��}t�Ԭ_�c����0*U��k�)tFϧ&�&��� ɉ��+���G��K��>�Y0*1a"����?���)H0�׀X꟔
+���̒8柀T?�fg���A�0������:�k�Ń�T%�8���瑣#`Ӭi3`�*�|�8+��/�<���jb{�D@�}* �����Z�����D�O�.UE�'�s8���b8>���/<�6���<U&���*A�Y���^�W+R���.�=l Lʦ����z���0G�Ў+
+=>:���׌Z�M�-��+mȏ�J�[�[�0�O�f�2G�j9�eF��u����G���ߧ��Pk:H�
+��j�^F��읮���J鵌҉{��S=��h��C7 }��'u�=���D�G�i��DK����Ԃ�������8��'� J>��s��8��
+�@YV���!��Q����0�0�OuKs nD�Ibi_�晭�̈́Uee��V��6:��I��i�ZpI@k��2�,��z6���-��7o��+��o��i+Iտ�J��܈oG�-�Ɩ��t�F���m@v��<�uѱ"'%���'4��د߳z�q�s{B�� n/,�|�Q��DB���b�q�^��Ϸ�8�ҿ�g}T���ؘ�tt���+������.�֎|���]��FFu&�>��KR�}ҝWk�U�D�L���&tA%߇n�c�I��4ۗ鬙 z#c�P��7���]D@2�/��z=�������D����Bul[�y�X���l@�Q?l<y?�ؼ�+�~���nq�U��o�� �6h��Nc�_��/d��P����㉲�t��:�VGp�>c(��hS�
+h&:~��E�dI��D=ję���ʶA�[�s�d�B@ �Ȁ��s��� �>&g�u7;��e�֘�
+��T��1��iॖ���
+ET�Q�t�>�'�np�eE����p�]���
+)���A*���G�΄Ǫ�cT*T�n��Y|�Y=@o?�E@\9�����B*����mb��V�s�T��y6�#�\�+��3+�E�b3�E*�$�,�p8����M��#*e��Dvf��� �Q�1��z�)#d�p���*��S��Ζ� 7?-�)o����%�u_wZ�Lf��W�#qg�Cs��1{;���w�4׊�5)��`��CN���=<$5]��@坋��M�v$�h�]��Z�uB�}��c�pY� ����������� ��+��d�)Ƞ_;�� ��Z�< yzE/�=yY*j\��~F���PmH��М�`�䉜�ٞ�;��o� �!7��K��eq]��<��ʃ*�L�'r��Y?�<��J "o�J<���p,Gj�t�z�;8vϬ/0���&3�`��97�d?��g��x�WoaLY�
+�{k ����I����P(�u)n�vtȹ* ޻�yj�"�[t���w����E1�� .]�ϻ�p���_
+ͤ,��� ->�ZJ�8D�qw���y�e ��&�>s�p��S�_�����%����yT� ��>�x��B�jOV{�ېr5��vU�M��H�� L�f��`q6f���Ș��A�uV��Z�J�p��̽�6��[��G5�C�,���`�����A)�*��O t�]�W�`���y's'�̂�@W��>�]��KD�^�ćl����4�B�f��w���QWe��Mz\� ^�0L�槒˂1�ɷ�aJ|O���\��tK2��t�����Y�~(3�+�}�����}������j������-5��Qj��������X[T/c�?=�/v6aw�?�=���m:*�uS0P�v��n��v�Ѭ\z���a�mƝfL�s=�o.I+��@1+]$y�p��҉z����C�w�k�87��r�۱�w&ä� �=�`9�fV�y׶M�TX�3�JZ�Ѭ2���Zًq~K�W�v�{��F�Lq���2� ��<��T�u�b%%‰��F���[�>]#=�ծO�rko�o�SY�"���x�Đ3�4D3P�:�t8��A#tZ���/��O�;9#|@��XS��z�[�y���!�T^��9���a oW#c�Hhlѻ��L�e3����s�T�~�X����5��.]WYȡ J<;&�/-}���0� 8��{Zǰ���=�ۏQ�#������
+?�1h��y�����< �#�aZ>N(�5s�.0Á�[~ų��w���]&%��������V���>^��J�l˝�g���"�!�JzQX�J��5��p�1rZ��T�IY0���M���̼b�CB1� �FIi���5��G8+?#�Dϙ�pE Ή0i��C�7Q����~���Ƒ�(� *�$�?D΁㺨SJ��:���~c��|�Nw;��ț�k|�g�o�?��é}�����31��fۭ��
+RHQ��1�5-4���e.��)tа�L�t�Q����>���N��3��v��e��?�c�x�[3��t
+'?�K�1�+k�td��Z��/��x%F�v���O4�0�� ^�S@\lW^�o�L���0hTYgcn��0W�Om�����!�'s�����w��x �*.�f�8��h��tκ��z<c:A+�D�*eBX�a4�D�7٧9$�O���%~��I�@��.IМ���#�v$���'1����H��1���#~����� ˑ��C���偡71��vڔ�����*A1� ����%����|L��r1��8���[��J�W�v���Ⱦ�)P���zk���R�15�]Sh�J` Y���]0qH���o����C����N�Y[� �+����SS KG\���q�5��>����� 0��շ&?�
+���Q��(��.Mjs��bc?Ɠ�~���ǬX��f�ጽ���J�e[N*渗���X�?w0b����j��  yu@��s�ø7��g?�� �/���K�h�GL���x*G�+O� ��M'����r���������6B��i�ؾ(6�G�1y8��s���f���D��'�hf����6��!VҨ�tsJ�2��aD�*!������!�+��
+� ^SUf��q��@�Ҋ�� O+���gw!�X��f�9ZHK��Z����XZyA��|E9�ּ�,����7+�C�:��jF��^t긤t�QU�Vt��@�*�2�����d�rD|��\�/Uz�����Ko�X��ZM.� ‰i�p�u4ۭ ��]�.��=I�%�����ϣr^tj�����l�ϊ�����:jOn߆i��;
+r��ӄ�N^��}�{\4F@���<>��9��w�r�Y��Kܰ��b�1��t�H�w�a�:7kt�r}��B�r�����qe�b�:�ŻR����h�Y�*dHkI�Ux&�M�]FaN|�5�o�'�W�#3RN��ބ��4m�vc�1�F�l����6 �x��8��j%�~��M��k��RD�@�(s��HJ���bz{�y�\Yi��['��!qgD1$X���7���V�C��ܦ��.U��� ��L�2E�]xy�ٺ��/a��N釥Ǥ�Ȣ�rS�@yy��[^g����I���0�I霁ɠn�D�ɵ���k��U mR�cI�?��0b�yx��<D ��UUR ���~z}�)|8�VB��H�yъd���I���]
+�IsD1��FA��>�R�9Z~�gNBUe3�$Q>�t�Ak�Z� fRve��!H9�(qj�S����z ��?k��5]q63=+���<@v45iI�J��+]����p==\���I,�3������FAdp��R{c?@�ƙ�x���Z4Z��q�E��}��}��[�*v�W�� �]��m�%Z(�Է�O��D��|��o �ޘqB�HK�0<���6 <��g�zOP|���3~�CH�z�)��h#KrD��Vo�'��On K.�  �ɤ=�ch f����(���&,��(�t�pq�~��c�]� hZ�� Ŭ��F��6�[���v�ħ��j}#�o�JG�ʔQ�(u��q�'�շ��ܲ<~Gt�v!�| _�aQ F=���Dg��Z��]��$st���6�߰)����b\�p�J+xG��2�i�ŕW�et� :r�̴"��jq���M�2��^�u;�fJ�E�9M�G��y�\�TR�iXm�߰?�D�.�MH*�#e�w�4CM� j�o<������ƞ��d�[�ΑV3sg���
+�U_�J���]=�¤FC$Q��{I��C8Ř�V��O '�3�j�{�e��
+�|��0�ܷ1��Վ��Q�Azh�o`�.<����U$z�K\�4��J'�q�Q�m��oy]E�� �'b�g����zKͬ��#M���� q��(LD����<��TR��$��G�%�i��~�m�dY}z���N� ��f�W̒�샲�#$[DE�m J�̮ g��AT�3�>x�ð��VNS��A)Z+ю\n�|�{��� ܄\v~�� ���b�O�M�b��5�O��unO�@������B�`u��9U�$+r[��"n ��qٌ_S�J����� �ضm۶�۶m۶m۶m��zx��&� :�Ӻ��d �H�3�t5�z3?ƣ\����M��Hq��/� �A,U�����z� UӶp��Z��P:Wɇ��f!�TR�Z
+B�pu�鈰{��^��, ��1�}�4�|��f�j�`P� ���sڎ���b��r�"�u��=�9���,�_���4�A���Z�����j7�Wy&�!�Zw=~���H�*g]���c�6�9�(+��B�M�¬j��H:������YH���u�/6��7�a�n��!�!^� p��y�u5��ε�k�9H[����x;`Tr �p���ZteS�&��G�Je����B¸TG�������d<*gH��rv}Ske������ļ�=���Q�(� ��߉] Cj����uR�zh�[7�b������������z�%�]YǮ7���:W��@F+k,�,�$ˁ�vWD�7�`W�syǣ{�©�6$9+�蔆���0ļ�����^3x9�W#H)�<θ%�!�� ��������O��s#�?ENV��q�a���-�ߔ��@*��3�ֵ�d{�z�X� ��vu-�2�LVXq�J.{���9���^1hý s�q;���� �O
+)�G�\��{���-��5�!]e�_hj��S��:XTu�2�∻@I��+�%�����i�[ y+��MJ$�8�*��� 0� ���K�� Q��~���ܧ/���u�b�.e��G��V��W�莒��XP���Z���N��g,gL�98K��ON$�� �$�?Z"Y4��%w8t$�?84=;�d�;��V�|*W]�&W2��~�#b������m`�����G6n�DZ����cC�`������2i�|��< �L�M�N,Ub�c8p�ϟ��M=��!ȷz��>sˏ`�9�eK�-\����7�۰ѳ,�z����|��=6y71͑H��Y���A��̐;��;^�W�lE~.���O�i����� 1�u�N�Sً �#����_p���_W�zN�f$���A� g(�&�Ĉ�oJ���7�n@ sB�擃��B���SE��z6]���8�P� �p�CQ����NqLO��qs+n�o��X�&Q��f�j� �K��;������Ў�(�w��%a��MI��y�7J{LU�@�,hu�~! Q^7'��� ��}�cx�2�+��w��U;64��P-G�W�R�%�BW�����=)9��}XO�s|Iճ�,g�%�$�� FH:j;I�r�������-���`�u�ߎ����Viή�~�D4EG���q#�S�����Z��_h��|�ZW�����2ˠ��B������;��dy�H]�:���Y�|V��#��R6� �v3��x��q?G\̹�?g�s6|E�J��������l��m�-��P�.;M_�g���qD�X����h��oy<��`4a�8�Φ�^w�L��r��=� O�M��-�oヲZ�-�N�^��{-S)ŧZW���|�s�P��ԉO��,�x�*���G�5���I�{U�:�B���N?��l��P' ���C{�p�)2yigJ9���}tr���?� ��Q
+�l8��*�����?V����qW�������%Bp:�-D�Q؍ j�w�[H��t��\���1�U��ԣcɍE�Q�:J�����:���O�������&7�e��^�"QU��h� h�ԅF�����zČ���ӧ ?������Y����u�˃��iGZ�c�%u�����"�nP��x<�� Ʒ"�)��=m�_s�H�>sB����] �7{J��f�;����@&"㜄YŵsxGB��[��EC*SFY�&C4b
+��X �X����īg&O@m(�O��?��< �U����gRO��E��( ��\ڏ���|�~�s�|'4/g}նoٰ��'��,1bݮ����5��ƕ&=2_�Ll�c��W���D����M)�/������RfUQ�9O��)?��S�Nj;}���a<�ʄ,ٕ��0�c�%��5T�d�� �$p�A�o��ad�y-
+�� �&�Ǻ�Q�k���,=f^�b����_+ �j�E���ޮ[�� ����!y"����0���pAјv J�B�H1�뗧|At���v@�W@|�x�c��̹��� ��,�M8�v��O�Ilj ����'$2F׉��$�`K�[Z������O�'
+���,���*����W�Qj�zP+�*��x���)Vk�qs����/�95�]�i� 5�=s4�A�<���<�x�C/�tP����)MJ�d�f�8����Vv(Gw�T� ��S�F^o���K��]I� ��r���b�I�te����[��/����9��ԧDt{I�q���|7�W7�a��0�b oq�,9��삂�+گ�M��������)1~K�0F�E����S~���� ӵdc��EQ�]�T˟���h��– �xR�is]h0�N�뒌 �7���>�X��v������{�q���Mc�����
+P�Vpg �a��)���o� Yy�t���3_�.ʣ|M9�.h�a�K�دYq�o7��NXQH�QK�g�}%�Ѻ��%-�@�?͚��~'n�(�]m �P����D�juvk�'��s�y��նנS�6��42v��m����a)���.U� "�S�AjT)'U0xr�j�Z�s{P��pf�^c�ڙw�Mz�&�
+(�g[�}�4�r�.��,s"2'���^���@4=jMfæ ����M�����x(>�� ��k���TtHpQ��x]��)�̺����k?���Y;�GF�ZS�Z����Pѡx��1>2)H�V��Q�[H��J�5�zw:W�����?#z�s}175k_x��|�Xw0���ə9l$�^%-��˼�u%�)[�h�jN]Sa�6��U���W��؟(�Y��4��1a��Y?.ưs����G{R���Tob���.x�z�R3�<׶� ��XK �&m٦�z�hb)4cڜ�)9��^��5 XG�w������2v.A-�!a�=���\��CX�xv}��?~h�2�mo���t� �<�d����L1Tw=�E�؋�_�l��5����)?c>����h��wޓ"Q��8���zK{�� H��d�)�L�tФ���{�{�3�ɑ<���"�azi�.O�ĥ�Ψv7�r�{��>���pd0W��� S A�~�3{+�gh^�匡z|�� �ꥩ_znG+�����т�~=��٬�R�����U0�_�˹�cZ���ȟ��2oA5օ��ȼ�W�K�b�K����uΊ�x�E�dO��漘T_�8<�^�YF�X�կb7SW=�͗H&�h�WOMU��r4+��T����6��i��~�K:j.�(a0T�k��J%�K�I@�%-mG2�#���P�QYNɽ]��¯%�RC1|�&F�����{�]�:?H�r>q/�"%�f�
+�5�E
+�>�,&P�'hӤ�VR1� � ���ٕ��F��]�^���=�ԗ� ��Q���6�k��9���O}~ �E��T�ze���0rf,���z,�ZB���Q��th��qN7�a�LH�H ���拏��z�7�m��ߛ�5����ɣ~���gͫ>��1���w�u��V��*A8:4 e�4i�#H�(��������Bl��q���O��� �o)��n�] �&eL�L�n����rTg|��Jܕ;B�P�V[��$�~�QU�c��,���qBZ��˘
+r�F�D�Q3��J� mD �ک���0�W���t����&�^0}�l[ٖSG���kI��%�����D��z��X< v�����^��������G'�_�;�mX�}�&�:"����^#CE�Q�bom/���F.Λ�ڹ�æu�?� �ۆ�=�����E���u7=j��aq�_8
+vZ80J �IK���y��^��hY"�V��e����-jB� %`.d|w�R�:��*����(�4{����߬�&=�@�Т\ၑ~۩]�O2B��&L�m<3�V|�4�k�X��f>������H��/h�����*�5,��s�Zuy����;��X���n��HK[Sgu2�y��x����5���sM:j76�?x+�3I`:'��㫤B�����'�L�>�h&��5#I>�j6+����TY�I��I�|�l�;�nt�#��
+�3�|� 7�ڈaV���zd���l�@Y( 9��AhJ���Q�5��rr@J�ȷ�2L/�W�l�ƒ��(7�~���;��7J��3BE(.YU�LL�4�w�ڇ�3z7pz���#W�c�!< 8�O%�p�ll���5�ti��`�
+�F@� .�������}��37�&�lsĊ���d�z�u[��<��Ll��|��Ckp�E�,���<c"�f��L�R^mNݏ��K��χ����똽�{�\�ͽ T_�.
+@:��) �۳.�q5�ﭮq[�oK�ǘ��'1-0�\�C�<�s��3��%/�jN�w�MHT%��|�X�E�}���܁��Ć�)��Y�$�D�%�߻$�r�(gF����
+�k�� ��#���`���4{�����C=�l�h��at�'h�X�/kY��w=�P��86�$|��7a���1T��YH�/����:bp��8:�=���랿� :�K��7�Ǯ�Uɢ���Z �.�#4��Y�N)�Kd£u|o4� �שК�����0�z E�zsfQ���"��@��L���;ސ:��-.<(�d�3�<M�����. .�K�;�,K�s�.-�:'2>��N!�5�s��i�}�H�f�F<b+
+0=}U�Z�vM��G��h��e�,�K��RgX�|��C�g�ڃ����֒ ��Ʃ
+�,o�ݣ�����i|W]��4<�4RY�N���8~���U�@�a�gdƼ�s�FBG�Lzڃ������B�����8-?�ʏ�V�X��H���$�������)={���7�����N<�N���c� ��> 9l�?��j�S<^�]�% �����<[?:G�Uo���})�[_��1� �\�~�����-��:�Y��Y �W ]�ؤ}Fa��,�80��:�o �˔z/��ВG�q;-��"��;P:e5趖eة��6��/�ލU���ep3,�8�~ߴZjq�^jam�,ONMˏJ��JN~�T���ܔh��c�MLʖ��]Rs�y����A{i��op��!]Iߜ@�c�섬 �ۄm})d§+r���?�;Km���k��� 1�8w�LU�ï񔗖��]�ͬv����`0 g���p�$�Ȇ�F�&����,������p����V��p �{��,_�R�k2��cl�Ul�2����r��g���N���$/�E|r�C�۰��z�1��Ԓ�h? �g���o�<<(/hP��?ֻjei�)��֫��S1M����)�ݹ���)��!�_��>UM �����t=���$' q�� ��]� �� ����v3��5��+MfDnX���{69t،{g��@�5�{Ƚ�@vV}h����Z-T���.Y���( )A��i��{Nx��4���AHlv��_��&�����56f��8
+l���KwWP��4�Iq^4'Z�Q�����l��"��eHG���A��}�_n$!�y�����_87\`q��6 9�=@�C3�B���vKq
+���ɭ_��Q�Ie3�<I��]��c_Qڽ��ʶh��Q��X󖽽"�Y���9rg���ن�kL�2�ylw�M�?0Q_!(}��}�FL�&q)
+�
+|�׊���1r 7�.��$��y��#��#������k���It�ƚ�o�v*K�@ {$���iHn0�$r�&�G��94�o5{�W�l���=4�R�X�V"I�@:Qq�Q2���3W�ňPQc�#�ݬ���>
+İ- ��%��eN�ose���mo��fM��{=��\�jO/�W=
+RJ��dRxq@�X�!��,�yI�+�:����>mf��r�wH�V:4ey~a�E��)ɝh�n���!A�,��cg0OTad>�mʋ]��� &=�6VhD����][����Щ0���n��?U�ܼ 55�;���滧Pj)w8�vU�A����5��Z�M:��[�h�[�ی
+0��i�P ��������w?vKYt`?CĒ��!��8e�ϓU�o�E]���n�&�xE� iwژ1��?5�./6�H
+Ru��]���e�Z͚����6;,T�2���\�s=xY��i���]3�CG��d��_�&lp�K ���@��zOfC�"{I2�;\�b� (�U��p�giV �ȑZ>��=��:K4G�·�%�$� W��rW$�8�bI�����#g̀ϻ2��3`|�A�������9�����]L�k�V!�f9;�@n',�w�W���VTP��;4y_� I��V �de�Z��G]_�V
+�E���YV���)U���1��:D�ߘs�υ���g�l��U�`Ԗ�%�o�6(w�֟���`�A�=R�y��L����M5��Sz&#6����L{�6��ͮ�sY��7]y_����[�mMX�w;A�q�����y�.sAm���n܊���*o�����.��ݤ�FimP|:S��m���o�&K�6��u'!1��9�;k�D��g�0ލ�hKD�O„!>�� ��3�����r���f;�#^O���)4HE��Q�D�k���/n�ޚ�����C��/��# ]1O�2��L�1���O�oR4*�B��!��<<�e�<���}��ZP ���Wˢ�@��U�>�Kg�go ���I�`#ϽV��]��GuR:#���y�K?MfAB\R� �!��IUzƢ>�ˇ�ݍR�?<&jĀ�@���s����2��D� �� 炓���ˍ�i����žy�f�*�OlOÐ[�=��� -����+����l�; ���37r�<��8u�"r�ijX�r0'���L����-a��&BxցsoN�~l�YC����W�5������O(ix���.�� L�����$�L)�Xn��k�a^<˄����j�VcJG�`�yS@s����T.�_��B,2�����%>�P����V�NUv\+4�p��^��v=�xr�?=�{�;�| ) ����0�Iz�a���jX"(2��Ƀ��P���� xl�QS��yr�"�^|˦��%��LZ�mY��ۅ ��.p^SvB����R����u)XS�H�xݨ�1���\�j{�C��(��E�R�j-�QUbz_x���C���)��H����D #F�����&{lMz�d�<4��qf0���M���;H������q[����� �A��� j�E �-C��`ANey�����ң�b��
+P䒋� נ�A SI�BԒ�F�p%4�Uͩ�9���׋cfCK32�S`������{�0R�����IQ2�?W�:�j�D�o�'��N7CrFr't�^�Λ��-Pw�W)Q��U��3� r���&��^q%H�t*�B4�e�o��`�|�Cn�T?��k|�I�:��ꆨ*�V������ ����B�� <Z��`bxc
+G�bQ۾z��>�Ws�^F��42z��6 ���햽����vi��� ��`��E��G���E�>��_�ˍQ*n�(�~�`�w:��Q� e}�PqpN�d�~��B���_�Dz8�r^B�,kE2|O�G� '������a&x���8�,Q,�|n<���ʘys����re����8�~����F�50�xP)g�f�/GQ��,�y����l��Vw���A,��N
+A��<)d�L���~6�Y��(�/��6ͨ""����� '�4^����\7_O�rYv3�=H?�f?�C\ͣ�I���]eA�,�]0` $�7�F�;��~A�W �� ���>�� �4���f@ݐ2�Tx}}����IP'8�T��Q�9�K]dH*�\�KRn=U#e�脙Ҋ�E:�P��[�Ș�z���䶘]��W#���w�`o}��eZg w�w�bT�,E$O�ĸF\�şq��暸qb�� �� ͖���nσ��c}G�Š~s�t7�q�X�OH)]P�w061�ć����XFU� �Y H�)�P]FDqg.�����Ш_�d������ۡ�Ɔk�Q���^��=���� �VC�NyG�L�pkM‚ձ���F� �j�f��9&�s�_�}���iI~3}0.3r7_n�j�v��A�r|x�vY@�#���L�.� _�&:9��,D ��4���X��s9^�7���r2y� �c�� S�$�~��Ӥ�G��`�Ӟ�Z��e�d�Y�OE��M��c�Ç�e� �ٍ/��M�#H�IE�<ζ?ݤ`��l��&� �ࢄ���n[�G�J�$ �L�k�Gq�e��a���c<]�x1�~�d�ύ�V֤��9Q���^b/[�+�p�oMb�*��!� �9�{�_�HĈ#f�Pÿ��Z��R{U��%��G:����Xց�O���NTx�"M d{F���0����W�&��Z���Gܰv��P�����v0�^��-�!��
+}3K?x��{H���eGi �N�`Z(%�y��ks}������4q �����)��6��0AM(<��h��(7:[G=���Ĺ��=�[r��F*���w��}Z����c�݉��A�$�s鳐��eP���񪊡��$�[�K�_����yµ����}��L�+��OXB>S��^�y�h{��֕X{��}n�l�P�èm��1��mdzO��5������/#M*=�A�<���x�Q��M���h'O)����l��ĪX帠)���,l1x:�H�jR��� ��hzk!j�|��~����h��M��A�X�՚�|�#^���={b/M�iO7h��5���c`Q�� jo;7p�Q����Z�b�K����X�l@A]�U" ��pz�ꯥ@~,Smߗ|�D8��;�aM=�����9��Uº�Q�}�������z�����6�F&X���K�7� g�0^���b��,�`�/Qk�v�\���B%�ܧy&K�).��;|c���E�����n�Ŭ��wK:��"c4�X��nJY܁۽
+:U�Q����:� w��¯Q�,���J0.�i �.[bno �ò&D*�0J�A��'y�+�
+�^���TtZ�T/���P�P�Z4�����*��ǣ�mL@�JG3\644�F���kNg�״����7����MT���s@����~¤q����l��3Z04�p��s�L2Wnߏ0j.#��v MKԐ}��r=��1s T�$���� ��*]+.�%i�_Fn�N�D�6.���߉=7i F�f�w�z�N��H��
+Q�u��.�9�A�j��3�A�Ѐ�Ex�>���q=�b�����M�Q~���>��5��6!H�T�>�LU(|�L/W�KM+�õ@��h��c���.Wh[�G�e��p\�=�`���榻�� ��T��d�"Q5c��gxt�s�%�^Z
+�l�M�e���YW/�Ӯ��c�UH��T���P�l�~�s�0���4��Q(�ͮ��k�!�؍����7`�˵��Q�ζ������p��)���Dzy��wȅAM 7���� ��_4݋`��� ��4�����b�)���aL �'��;�k�k��.�p0Yg���u�eH��Uы��T̎֒7z�� \%�R=�v� ����c�Э@�쯱�+d
+Co�$t�{rJA�-s�Y�B��P�6T{����h�����[�%,���f�&ЅeJc�L�d{�MƐ���,k�<�6���]>{�vAd�����D�q���St��C��s�������M��.X������v4��f���:��Gg>7[3�Dl��>A#B�s}�7����,�q��$t��f |�lYF\J�h�~6�[ ���ŽC�,�ȹ4���]��H����,����pp�����XBX_�� gU�:�,Kq��h
+=�_ �7F#���[/wI�D�˖5򦃭01i�%��\�ٴ� ��c��i���{Y��ɉvY�e|��az �'��{m���0n��|H�X�^���<��J7��� ��|�����U�6�j�Gޘ7����u��F����*n3�rN�s�Xax�ʼ�A'̠��INԕ���IE!"�V�����W~�˞�'�0���FfbW#�0����c� �Z��PP�ȳ�='��f�7
+�l��Y��jY"��$�uYy��^\6�z���4_ �ML��3f�X���JQ �M� `�~pF-���—����z �U|���u�f%!�V��x�\��h%@ġ�)T`ͣ��}}��}׏_����)�Z�����2��겔�N��X�2������)�Z��u�~��ݫfE|���Dw��#��Cv/?[�.� �bq�����[픜Nht��R�ͼ'��HA���ZϘ��Lc�7���{�V��Ľ����<��V>�&��"<ӯ�6��{���~�3��p���7>;YM�"*M������m��/��)�����$�q{�ᚾQ�����#�W0ٗ��c$�Ę��4;Lw�J2V���'™@��K���x�=��ڂ�N�xX ���4>D�E�u�?�1�[��Ȁj�l�M[7��|�G厡"P�6�6(�[��7_շ�-��c���ZV]#Q �d
+�ӡ�i����~R6��'eѽA�Ϊ�lS���Y��J��JMjkm���]L����$I�]�L^(h�y��`� ��fO�߰��N��w�k�>�Pn�*ty �^�4:�g�I�:*x*�zj>�Xs�$�j�l,
+2�N���x&�U�F���Q�X^�ZP:f�x�S!V0�~j�]V�a�TR���`e-�w�����@� 'M~����)(x���T�9 ;&�j&�� H��i�!T�,:~�F�0*��|�q���~� O2)'p�~��y�RP�zaq7R`G�c�kl��*����@���9f��(�8h��*�Y~+�ֱ�<����X������1{|������[����xY�=:�8M�5"D+�Q̄�N�\lxUĜ�G�C�e8.�1�� K
+30��Ƨ>LۜG�����w) 0����s
+9��#� �b�.c]0�Mn~�����%� � ���F<[���a�.�3+�E��2�u>����i�PU�"�޵{t冉9��m�"d����2�p3~��{$�K��c���Ϋɼ"��"c�{y�\n��0p�DXn��t��S�[��н��; <U��0�&�����sYN堲��ފJ����0h4`��G�E3A�2��;h�ۚ�`@g!﹮j�7��H��6[��#�UI�y�9�%q�|� �x��h�s�fy3��-/��E��F����y�S�C�i��Ia�7r[�OF�m�>�c��7�,|��qx�E�Xn��>�W��WJ���վ3%Zo����dǬ�.�P��K��o�.�fp4-��
+��l{���`�'�u����Y����ѼlE���EH������c�/
+�K����i���,��uׂ �8SZ<���6��~6��sN�-�5Y!��Σ��_z����\��B�y�rs�bd� g�Q���rW���r���Οf��Ftŕ ��ϡ���#�����Efؒ-b @8����M/fVD���k�+6_k� @J���6"�Q� 1J�;���2�'�����@ƛ�"�4��v�s�o��V�����x�O6�rF�� �A{��+.��@�a!4n����U�Iw�8��y��r4Łqx��y��rG��(�\k�R��:�g� ���6,ѡ���%V*�sWE���in� ����̊ J�h�1t�簢tH�8w��=��gL�jB�#�'�3��ݨɆ����S�;Ɖ�(����f!/���eA����?-[I�Æp��d�!臡��)ҳ����ϟ��`#Y����c�8�2�O��~�U�TN-��� ��#a�"Y6����/�����k󔵢'i�DE$�)�(@��vN2�^R�x���xMݷ�������C/rI b.����= ~e�s|�Q�X9�p�rWLVz�zB��e9C/��ra��Mo��\����֗l�G+bheMiQ۟�,�3��ӭ��1IReg�������zhY��,�L��h!�FMk���ߡx����<�>�ԊD�R���Lr1Eʁ�u�O���N��%�7�U���P����??��=^�V�5Ė�V����G�~� ��mS�q�ʣIo�}iM��G�G�T�x�@ܵ��~�޷���Rs������r�ED_
+ % *��Ȇ4�i�췳Ť���,�W�ɭ&�c�u��W��l�YP/��}���6��A�
+}��zж�T�"��IvK����]�/7;�<�$'�2�W<.{�C�w���b�U��.��3:*j��V��U:~��N1A��
+# <��͛��;,��P&z�W#���~CtrR�D641#H��Ӷ�JЃ!Uo���ѯ�PejT�G?:�''�x���,���aȑ���VX��|�
+��H��4��n}�*gh$�:oH6X��&���%E 8|l�ʇ�8�����%����8��̫��}�(����A} a�{e�������_��}�����aHO5�@N�Hc)q�SěM'��q��iuط{�ש7�O7FC��Ė�ZC�����zr.����M3��aH �D�>��{ο�l�=�H�*C�^���2ز. ����~3 f�Eӽ ����F���Z��/�V�G;� �3���/R;�D��u&�~�� � eY����i�0��*Vϋ�[F�B2�+��0����K~��^�/ߚX�F:��|��Tm�yZ��8Z�}�bC��r�� ����yb\�&�<�� p �d#e
+�JD.�0�AG�2���vR�m�7��m�20 �F�W����$LR&���z�`��Pel��‡�� �n;�Q�']&{���xP"m��T����40������,�%���!tD����n���D��/��T��:��{߶��s�� �V\t08�8ɓo�:s�k'ȋ:>"�C�
+��l]�T���u>P�Yj}���QD��N��$O/�a�Oћ���x����K�d��K7L���T�~��]`iIɹ� �{f������r'� 3��SAh1
+7�
+ꐟ��\����yJϱ��g�VX�Ћ` =G~��Y!���.����%���߄�{���Gh�Y���52�D+����U5T�3*R��vwp�iP`9n�-�V{��B!��I�� 8�5�a�D-S�:�+�/kP��,|6ɾ
+ZxRB��&�ÑoX�9W�p˂w�@r���W�牪m����<����q����^F�^ r�Rv+0�51�'�'U�7n�ק�41>-��6��0;�PxE{��(I�jD*W�m⨁��Y�q4��wf��r����5$��*{�eU�p��%糏� �ɽxK«�/�yT?�|�6X 1�Qws�j:��wM�?"���7E��J)>���xq�,��H @�n\wB’Z������<��G7�U����(_��I ��5Y�)$7���$G����R@�� �Y���S��hU���{�[�E�v�������|�OU�>��A1�%{�o`���CY�k�%�r�S� oև�(&���4� ���*�d)uy�����C��noW�sp2 �c�J�o�\~�#�� ��7JEq�����L��y"Gx��Xf� �7 �����2�ruX�2�: ���|� Hs�'\�
+� ��A]�e.��[��"нk5�W~k�̪����7Q�L����1=�6�^�Q� �����bcJ4��O�iG7A��� ��<4'9��K���r�­=� ��븾��Y*b�95�k) e����I*�z�y�7R��ó���~ؐ;�}�y�s�ѷŏe ���٬�{�I����P(_�et�����i�O0�2���[<ؕn1��i�J�퐆�^��5e}$α�kVK�65�{3��7�2ZG8�;}���� mL��y|T�1�0q�P�*p�u�L쪌V�!�v�<~1��������`�eKZ���3��8;��;2��` A@�_��*�m^ǣ*�i�W-��� �0�6��(�6&Xa�i� T�d��R�Eқ�o-�����}��@���MY]9�u�U-��$0�`�77�Tȫۥ����<�� �M������vx�_�=I��\8X�G�V�5��uE�f��#��ňؤ���e�6����HW�
+ž��7�S4�>�t�?���r�6���ߩvs'XX�%iO���5�m~ϝ��m ���I�K��c��o����^�d��[?nA��@_H�-�� �����V~j�^�n �Wc��ш�+l�PSj�W;}
+ȀA�68� �{G��O��eZ���K֋Q����r�0>
+bR�։f�kp�}Ÿ&R�kx� L� ���`^�@��~`�m��e�5!$vB�Fw; 컅np�I��G�%�z�^��6���k���%�_�)ĸ�ۗ�����Z;��&�S�� �}
+$QI�S��|
+m�!#q�n?U�O:����|Au��;���iؼY@xm��6�U+�G5h����OeC�s^��ȟ��'���/�W�M�k��������9� ��0M�}����>~���Yr�u��N��h ��i�Z\�&�R8΅��ý��(����V�' �&����uaH"�B��L��TH�iN� �-��t.�j����ZM.���لS/,�4=�Q�0Y��Hfs0C��O8��S��#g�C9���O��ó��rC�o��ڋ43�J�}�6z��S��'��A��S�~� �\�����ή��ە��)�d�3=��MҚMk<F+��J~�w�ڄU��aQUm�n�B0ô�|�-���b���@��P�9*)}l�̠�MqY&����pzƑZ��O���]�Z%'�F>���y���:;I���9N� �����o?�{�V[;M�`6�Ct"E.��e��P�PD�K:���v@�~H��ޛR�iʧ��+� K���!r�Co�D��&�����=\4 *�������خ+����غ����lZ��??�7��2�0��>̪����Y��=P�re�v��T��f�e ��!�����o$�*V���Y�����@z����̷��Q|�k; 3~������[%���;.��cP���A���D�1�����s%�N�E��tm��V��*!lX�kjĝ���N!e�i��:(�)��8�I�J���ȋ"٠��Bϩ8����68T{�����:�-CA�q��)������J�$� dh��EI���CNA9?�>�iB��!KN�!F�3�W��%cñ����`����2���,��5Bj���M��ᰨ�#ڲ��`���P��^�����L\�~Mi���I�e�pP�K�ԍ����e+�����bY�ވ�DݮGY2�UϮ"�֖��%��KG�+� L�^H7@a�p}�fQ`9��T�%~���s�{�oisN|��5�G��R��I?a�� ���|]�5���.����C�maw�� WE:���+m>�{�o��'6�I�����w=N�ޜ/����H5���l�Y�.Р˭�V�2�ޟC[&�ڹu���Vqa0���NC�NZ����X.���Ʋu�,������|`�$d�>Y������V���]Q��RK�+����Y��EkR|��KZdю�� M��y{�#S�U/`��8[.����ч��ڻ�)�P�ͣ��e�i0Œoޮ�!F��r�޳P�_����v�u� �V1+%���TXs�`��#'a�u�V���M�s#O� ��,,8-B�d��Pd|�X�O�j��l�
+�Y7�hWf�G�[��sr���< ƣH�G�ֵ�
+��%iWp��:Vp�_"�;�`� ��ɍ|>E��|�Y�d�WL�a^
+��K��!� �>]49�
+I;2*����(�Sݞ�vA*���A�8�H�5������Fo/�y+vT�#�n e��
+-�'v����o|���P�@�5x�s��-�������V �U������m��_�tߢ{)��ݹ(��A�lF��C��ײ�t'f=M��$��#���!�yN��ŏ/N��(����?�ΩW� �۶m۶m�x�m۶m۶m۶曫I�������Uy�ג����K�����EQ �?ǜ�@�V�E�ˏ�`�� C�w5�(����M��._�rq�}��!C��B��!�ש|�s�����@���mb���^�X��yB�<T�mQ�f���c\��b�r<5�6�<Ζ���D��aV�_Az��G s_3�
+xZ5�G/�+H&�5��1K�8�؋r�T{UJٹ.�l�ߋ�/�צIs�}������@9�5#����~wA�����i�x�V�P~ ���a� bP��Cۘ�%{��[�|�E,��4V�E�c����o����A����mi�� 3�2/>vC�����2[�~̑��� <�X��k.`�Ʌ�p����-u�y��H �6Yz�����K�E�@�N.��\W-�2LT�̹�$�f;;^�԰4����<ym�{�"c�6��4@x�-��r�
+�� $FD�Iߕ��0� �]ã�K!���;Z+�$\��@�- ��A��o�#���ZJp)���^#!��,Z1�;fN���d�a3�O���85��7�2��h�]�^�����ٺ8oݞ���� �si�x�p�4GJ��KEr����/��:��a3�*t �n�� �器��y �$A��,N��)�IG7 z=j�<^������NS��OA�f5?XyZ��T��O|���w��7Iؕoy���U�t԰F4��3�fbp��:�BE�M;E5�L�i���7E�n�H�
+�%2�����J<��u�D&��;�Y
+Z�)�$��.�1͝Ns���B��*\�ƯZF�3�ߧ�_�h� $"�'���~ZY[�
+ *�k�p��Z�͡�A�R�.&��1Kcɮ훲��d2�߱%�>�7�_;-�馪xᤍ-ma�ç���յ��N ����D�{B_¯mʡ�gn����bn�j,�KV,�%P�'�� T% �¤76� K���9԰e�a����a;��9�};&spL�q��W��f����5���`��hhV��!��=�I�W�9�ŦY��Qګ)e���Աa�,c-1y뫽8��a�>���L�V�'��y��ߎ }f�R�am_�5֚��%CĿ�oR�Y[�?s���Ǔ�x����]���C걹�B�<�;y�L�R���T�A��]0���m#�컞 ����lWPy|����V����; �3��B˳���1�W܌�J ���p�U��F���ΛM� Gj7�`�%�w����i,�”�ܟA��]�"��PK����>���n08�@7��(X�U��~���*���,~ 7���n����B?z��,hͰ�FF]���EH��� �[�,�N���H�
+6=�L�z! S�X�@��۹��B������./A��&(����`�����:h f��ߕ�aB�)���h��N��trB
+�ѶN8ii���G��0�J���7Hb2fE-@ exr�dUd�Np �@�hH�[�&��,�8zz��~�$9y9!dF��G�t�/yr�32B�<N$(t1~��d�yx�g:�5`����':0 ��Z��
+X<�Ie �ڻc�m��AyFl�F�j����<W,}�v���Ŕ�̽tVS�]^�$xIɑ�ªdN�m�r㦾)"+��������s�i�~�-4�@��"����l \�6_�9D�K�s��LmCT:Z�i�#Y��3>0T4xvQ���g��NK����K�&�}�knجv��V�F�O��<��N 2� 1P���/���\sW�Ii�빑�D;#4�īm��VV�/-�µ� ��{b%q��("ɟ����c���L��ɛ�o�S�' �j��^2�I� в;T��S'g���M]����\p:z��Y�T.�u�� �.u09��ْ��T#Eht� <�7�&d?ں��9l�V9�L��$d�:~b�թX7��G�s
+�8�����4t7�UK0`C�̵�d0+������UtVYK}܈p冹����r�^���8�������pf\S��������,
+.��$5�(_�k�ʍ���9��Dg�2��Q!�)~=�T�e������7_�yu�C�.%h���ٌdK���p�Q}s]d aD��#�$����X7�g�2�r�
+f���ą���IIw5�7Ʈ<R�a3[�[a2Xe����S�`,*�Uy�e���=xi���z������b+�p쁛oL$\?Y��8�!曳�5��8��C'�u&��)���0�@Mo�i�{��q�y"��+�����n�d8V �xd�+|>�xỿ�4X��I'��* �������8�;@�+�7Нm�ҹkH��Ņ�����`@\�(m�..�_@Ϲ�e�O9Ik ��R�Ѫ�3qW�&����b��
+�%4�Y��2�ظ��}׵�!�:[4�S��`W=Qw��?�^�] ���xH��UK��ž�.���q⃟�8"N[�͸I� ��'ܪtS���w�U۪�9Tz�����#g��R�&i��O��T�;�X��`h���\�䝧bWx�Lj�bq(���}J���}P<�Ŝ��r�9���;ʘNs2S��|-����P��GA_�Q�K؂�%�����6�RxٴxI� �V�_4�,�}I2�����`�'o�{�˖.�� n!?Jb���3�~��?K���sÜl{�� O�?��͍|���}Ҳ(*鵑q:Y�8u���n��!$c?�Y���C�z]I��l�Dü?&�z��M%�w��v����a�V�/p҆VW/��v�\�4���=��Ё�7���v�-�H� r��F��)�9�yxx���E�N"77|��R�h ~|�x��y<lEf��6IXҮN���B<G��dv���
+������<�ym�W傘:b,���g�H:γ:���� `��/����ro#Z�'CvK��)��$m�Ȑ���u{\�������;������E�h��q�C��[���23���n�;�"�3�bA �h�`m<{������>�6�D`��HN'9b- w���T��F}_���>�������7R�x�+�,�$�Xt��?Hx��I�5��k9�����HO�ʉAfVݏr����GX5�. a�\�M�G����U�����\���{c�ui�E���*Hf��c_Dh(�
+�_Ȝ8ܸ���x�Ѱ�� ��'=�uG�Gfd�1(��|G��ys7 .�4�V�<U+��C��s'k�|
+iu� ���\�������i^�"&�����@�tʤi�4tK��z��^I;���d��x��/g���Ț&����r�~=���?�����'Z��)ʕ� ���AwL�Z� A��geu��UDJ8r�E�8؎��H�-~���6�mݱt�2�nuy)A�>/.�{�2�A%B�,>6K�����TB!T�#��b�|�������5V�q��Ӄ9����-|�ܘt�����e4Q�"���7���ogcj����-k
+H�"DA�-wF
+xןzgD���d�<���s��M�5�v8��П�lԇ�V�����Qh��.d~���Ę��l6d񫌫lA�}�ͻ�*���p�c���]P�)3�4QA��ن-�7�PK"� /�
+�}��f�����A; ������C���=�.�����j��4;k�HpT�Αd<�z��wB��M5��m�n�z��rDA��x0���C�c�[JH#`�������˗dd� =�S��omh2w$�4�Rj��Ĕ��c� �7:��a�+R�.� *�%�[&DD]��7�P���R�E���$j8
+{b{�� �G!��Z���k��� �R�e�Z�5�b���J�;0MVտ�C�� �!�}�]9]I+�2c���lU"�<s�G�� ���`��Ƃ�@�@ �ޞ�;�XQr�H����s�3�W��>A�f���u~�=c��b��E��2��׭>'�~�6��S��?Mm�d��l�@[�-R�@���r���\��,��@��)-|��`�>?8� ��lE�Ѡ�����Q��C�6? ��i2".�$If�!��@�ulF2w,R'�mD�����!;H�pm��|hݾ��(�06e
+"r!�PN�%1)����%�U$��(�n�w1��Q�[�������´t�2�����r��B��V�v��M �:iȑ�c10,��!ō��b�֮��P-��o{`x�#������A�M@��]�4�� b�M� �qU�s]�%s�|��#�,�ã�ٺ�a� Z��W��=To{��K6#S��Zn|�W� ��)~�&MLUZ���F�)(C3"$�9ΰ�� x�����QE��[�����A�K�@�|�$�N��NO�(��7Ϡ��k6@�2�������Q�;zt<�= �/��I�0��0����Whr� � A��
+B��ԃ�9�dTb���4y_��<!Y?� ���u�/\�ǎ�=dH8^������귅cus�ov�ٰ�'�ף���੣[S8=�c6�̢d��3�e���"1K)Z�Ѳ��B�v�����FA�N�! �0��⧧��&k�=���}zrN4o�����+��݇�Y ��9��vE�� Р���[9��2�Q�d�h�C� �\g2 �Nz�oK��I}��y����~��/��1w�����;����&��ğ�M*���Y�4�‡�1��<�r؀G̓V�̹�y���?��� 9Ѕ�����`���� ��g�n�cs|�͟V2���g���\C��W#;]N
+ļ!=�M��_���8�׼ކd���l3�i�Dr����voyu/3bj�Ĺ��e��p�[�K�����꾁/����g�d���o�[">��� I��'H����0 }i��w�2��O��2Nu���/:ܥ3K/���Cϔ����nbz�-Ր#��`[q��3��.�~�W���>
+���Q�/d+�5���Y_P����Z��#Hق�� ��B���@��p9p�`8����h���c�3��ܓ`�Hy�K�C������_#�����SA�� p���1�[���D�?���]rԏVS��%q�"�ג����
+UB�V�BݶZ?���_��p��Dw��)A%{��^��>� ſG(����^��RN�4="�A��-~[�]�,�u�K�����Z�Li�E�f�e$���3C�|���6�v��~ �c��t١�gl������P��a�q�8�c�;}�"X��\ �;�u�J��|x�r�K�z�HNDp�Y����t9�}��7���ߟ7�(���e�Z,�t���-�ek�y���/�K���xT�̓"�ߌ�~��p�V���s&�j�7�y�P� ��1oEo��5y���Y�>BW��&�|��O���s�,u��S' �I
+��m�7#�T�Lԋm��3ե��Nk�(�bˑ�z�c�,~֟K�� �+)7����4����/s�&A-�\��]�ㇸ^�=Ӱ
+�����̃Z�#�ZL*'��P��������ńε|��_�r 6a��ɦV�>Aj�~�j������pi�������6�M �M{���m�:��s���F%g,EI�����29�f���J,��I����ZȘ]���o�t�f,�/���+b�=E
+qZ�@��ͰI���a�+B4��xG��
+@�f�*�
+�{��v��[��l̹�� |�ӢF:F i���Qu� #�{G�C.@�,a�d%�9o�L��a��$�M-s|��`؊��zli���G���W����?:؜�����Q��$��5��� �)w�S��E�Q5)'�׾�mp��@�l�7)��ɬٯ#�r�kv�ARA��e����s��w��]������0���L��#�,�!*�"[�;R�j��O9^N���h���BMu$�&��M��ò��]��p��}7�<��P �a�C8|��_$��IB5��@ߟ�[��M�>z�`�J��(���ۡ���w���LZ�<��&�∝*���v$���+a�f �)No?kv�tf�8 ŵ���'��X�;� KcW�ׁ��X:���P쭧�@�ZI��Gm=�x���r��9�0�����7e�'�*�ئ���8ؖ$��!P����o�}s!ؼ%2c5�Gx�`��)��f�1�m��*;��sg^n� 1�>��Ѝ� 6,k�/C$�-���Z��U_�3v�>�\R�#^G>2���L�>��s�[.9<�A:��a�J�ブ� (k��ҍ�A��ݔ q��wu>%ΌjV��&`��ԛ���V�+:��a��ٗN ��1���&�n1����O���\v��T��7?o�**&W�e�3��4|����^��ƗҿGG��)�Z[l8��S��iY��;]�rN��A�C��ש�4T>�MU�� ��-[/M�E%sJ6LǖP]���7�u��-ߜW��x�Su�_��C7H="��?v�3��>� k=ލzG���l�u�"�r��M�lI�F��]a����3��4Ñ��/�Z��QK,1f%��M/��8��Ծ�<Hz�*r�Pi�A ���;plG��a������V;�x�N���V�ԖZ�MN��*������f��ӥT����ݓ!%u@w�!��:�TC&���c��X���fw.0� Y�gK�=�/Z���M�� ͇%����:���͕9'd�c2�����CVaMe��K��4�>mx��2��{Ťp�M[(�S�w�p��y1�
+cݷ�
+Jmv�X���QiAc\��n�z��Z���|' �y"w�����)���x'�뼪�sA�8`�+s#R�,��k��|9�f/8�'���[e���@�X=�w�l��ۺҨ�E�>6a�S-{�A��6���JE���O��ln+n��v@�Xrc����gVMK�DR�;p&���T䵳^)����:c8;Е�
+?��R������p��c,�NKM?�0|�_(�e����2o������#�Gp
+~��Qkp<]�E R�Q���,r�q4C��g����If��R0����x_�\��� 6��$~I����|�0
+^���F�F���Ǿe����wl�9�|�����T��r� �Fm������ƀ� ��PF"]SѢ>qd���fsEȰP賯·�M���(4�%���F���h�J�j�]�[�Ur��/�@���:~�W��fV#�ǥ��b��M��Tk6�+C�F��]��hsڦ����_e�2���+��V�B[��EM�i�B��K ���p��5=�ݧ� �+�>���^��5���Ph�ƨ��r�G���ن���54�-����s��i����]��f�hl�6�?N.���+2��s�,��<�\�kL�LEt�'�qX9�l'�Ym,���� Hp���ﷆ�%��ˬy�9�YN�%���@ ˁ���-i=;��ˑ/.Y|3��!
+y��+�r@@d���h��4�O�!�u��3`B7W�@F��]�9��~`�)k���t�(]���������`�`T]#��!$y �S"*���<>נ�1��5<l0�8��f+�b��}�Z��oK�zChM-��Al����\�4���s�9������q����S��W ��7�l������D������#�OQ�Szja��쬽��ɟ[V�h$�{�6|��s` `�����G"|;RUb7=�B�\2�GЩ^C;��cΉ߷-vJ= u���D�%O�F�D�\�� u"����n�3Ãlrfc�e���ċ/ʃ���5&H�K�c�#�(�UE2f�G����B~����,#�2��^��b5;�~����>Ǖ��鍑��oe`�@�U%G������8� y���Qӵhv��K+��觖!KR��Ş�����L*|�����>brF�����E|ְ�yQP}�<��du��`Oa��|=\åV��6L���������h�Qɔ�]�K�����b�}����*Hq�q�d/2*����$9�#��dW�� y�YW�dg�T�.f�K���\����<.���c��R��4��Ye��`��8�������U+q�#~r<���L�x��B�9L����G���Qie9���d �����. ��Ļ>�#qˍ��v��v�*�B$}��S]0x���oN�\�o�M�W,<"=�{ �{�]�U�^>^�r�[{,j�*���'prd{�PwV`�Mo��^�c�c �QA��?Wm�E:ľO���-�-��,&���2�F���M��75���g-S^��,a�D�j�^�|~��T����qUXC6*�D}�I�<��U5o_$g�O �#�9��,&wXQg�vƙo�{b �K��U�7��\��^��xs<Wk!jG�$D�(����+*�U�e���0����Aii����� �J� �:X�x�ɒ:ᑘH9Y��a����NM�!X�;Cjas�'��t�B=P���**�ɻ���� ��Z�j�LF�-���|_�k eO�H��X��r@2^����a���1� �,�-AWO?%*vi��*�|�ˋ4��[I6zk7�gT�Ǒ��v��G�T`q���� �0:��s� �ä���g�4��h�j��A5{m�!4�+�‘��F�R"bv�*̩�48����яO�ч�^���p��{��h���B��[�e#D��(������1��_���k�e'����*1V���=� �o�Й��n$fV��/��J�>u8=k�ơ����N�a�r�G,uN�1��b�9�z���%V���"Rx��_c3�}Ǡ����d���&��������b͆c�/܋dw�Á���{�s� �4U~Y�HY�T�q�B �uh����H�"��s���pc®Ze�1���=c�;PA�6�0��6�@��g;�b���J�g�2�/�D�d�A ������,@����$s�[۷pI�Yu�R_��xagO��V�P4����o?�=0%���r�q%#n���*jŚ����O&����z{�~��$���`�eWR�Y�[
+���o�j�:�K�`��[)�k���=���]��"Ba�]c�8{}m��Ҥ�O���@%��r2˥u�x��?ƯA��3V�dH\y�[���q��8�f�߯7V��p(���d�%���}��P�L�[M�Jw�bB(��-�`�.3��)b�~�Z��� � K�����W]W��ى�6���k�^�:~�V����TIR�<�\�+�CQ"7B�����"X� mw�~w˸���Hz�F�OS����`T�T�FG�[�Lq/���kX�� ���9y���p� �N*�ȅ���i�KR/��Pl�]c����
+�����aI)?h�#�%~�x58���VG+��0P��E� ���Iȭ��
+�{)�yV�B��[Nߑ ����\ѝs��5��+�'ak^��Av��3po��zEO�Cs�[]�=F�1�3^D�*i�t"��dҥ�v��j��NT8��.[9��[p�I|�*[�����54���Bh���3�&��$ۡ��M�]���k�R��c�`�h*6�)�򭐾8�tm&�5��uE7JW�_�F�bP vT ٽ���-<(~�����\����?�P�Зc�{�����ʁGT��-22��kit� �N>q��Z.�O���5��7� �)b^��K����063�E�ّOm���%O��4m\�6p�G䷯��CA� %g�`�,��@W�M���2-s.t2��<��A'�"����gz}�TX�_X�Mn�]�4į[k��N�i����*��x���f������m���"'�zMmP��48��] L��,�ݔ��b2�n`�����G4�R<��,E��V�D���c/����ğK�Y(�A�� >� �� �U�V#V��C�(�����ZYg��,��p)ˀ}�b��?�M\ �~q�*Hl,�s�-Gۋ�r��<��&��4�쬇`m��\� v�� ��x�H&����G ���Q��H��*����L�͒^�.X���=�mKIa�q)yy,9���=&��NJ����<�>�&�:�E�ƞty�k�nhI�Q��0�f� W�VR�F��$�����t�W�T'Z�������6��0L��'�Q��:����� �V�HN�{/�)�,��[�D/7�ߚLd��f��Cͯ��_��e��8�z�8zVU�2@�@��1�S�h�i��>�%[�ۀ��j��p�fF�j f�Z�p vlC;hs�l�3���Ʉ�.G�<�V ���S�7n�`�O�g�4.1f,R.��������Re�U5ѵ����~���3�.jE1�0���� ķ@��ĝZ5wg�47&������T�4ٳ�6��X�HҩN���|w<��s ������(
+�'Q��/������9J
+I���y�Y�O�#TKs*��3�u���jGWK�>_~Hx���/)%� n~�RZ}<� �(�~��^6���%����Bt��̯���x�u�&w<�Ni#�OR;���TJg'������lk6?fE% ��V q�t ��*l��M����p+):k;A_�]�Gi�7?\Y�hgTkw@v!�}���m%/VSYD��b̃%���uxa55'/���T���;�K�q��G��E-��V�aۨ桋�Y��r�er>��lB�&�b�&e%����*0��`��k����(j�3�Zge�� 62�7�f\���&��Τ?�����1H�n���@�޲�MK�<<Yi�dh���n����QiꪣDn�2V�Ձ&�W̛�BߖD<P�� !�O-��/�Y����a���[ON�!.(�h�T��qA� �y��,�ȸ�R"�pY�<"V��� ��V�d���6`�P,S�z|c���! ����� ��<����E�5׭ lݔd�=e��:O���8�l#m2^=:�wӿ�G� �x�#)0?��Q�<�+��`I��g��9z����8G�|{m~�@�>x��D���̦V�����R���Ad�`��V��o]�|��T1UN8=:: �\Z����j�љ�m��|~���쑃�zf�Y5����QB)A�ݴ:n/��_�V8_��b2;.���f���>u�uU�)��IH�m[��S �IY"^gz��H��fh�=��h-��c�R�w#+����N��XB�,n�gQn˻�9?�>}!��aB�u?Z}�`��z8P��A��0�[��)OL�C�4(6��a��B�A�����|�o=&{������HŚ�u� ً�3Қ��H�hA\7�t�$�O.���p�P ?M�s�� }�� 696�0��\�����b���R���۠�vз��fV�D'���a޵l>��J鶝�w�����bO�;/ �%��z�N`� ��C��/hP�L�YT��$ ��ml �*22�}O5�a*�p2��TO���o�ƕE��\�o)�|�8�\ou�%ZU������+��꟫I����Ci�[M�5�0F�(~�k��{�9�ߡ�#�wxk<�]��h1�WN�@�M&�k2I�D|鎉Jd�"�pǸ 59A��g޳4����<|pP�i~[�m��n�:��2�8�.�Q2)� 2_����R�J�(��\1��>��,W��B�K��/�*S"9�Њ��R�L���Պ�T�������w��
+7�T�͝��HD�{1.M�B:�0���uM7���Ϥ�^]XW��=�M�A�������y��O�#A��SBș�)l!�#k`"\]ώ4J'��叇�wo^�:6��_d�(>3͵$��Q�����Sڀ��S� x��"_�>sI$oM�S�%�8�����J�����T�f��au��ӆ�8��ˆ���AͰ<���#Q3?�-!� KF>v��a9�lT�Q�(��c�G�$�`][���cr�v��x�M��SC��s4g,`�� z(�Gjm�LlSs��to����)��.��Bg��",��Ogf�}v �������WL
+��~�J����r����>@�'�f���a�:^4aq>��κ6.K�T�I�c��S��4��˟Ĵe���%b��i���/e��[8���R�H���N 1����r�Qd���ƴ�'� �A����b�eaj�����'�,$d|2� )_�o�cp�md��_�mU�]�/��,w� ��'��w�S�P<��C������U��L�U�c� c��}V���:������O��.���[�N,�;�9b!�6���r5��ͼ�*��C�w�����L^�:$})���������-��T��b��^'g�YO�&� v�����(5�>����9x���AЭ��Y��TMpdTU��*��LJ�)�8m�Uy�Fgd��R?:q?Ƨ"���U�p*����vv���7����D��l������)rr ��qWA������^����2
+W�|"��6>j<ާ�GJ�2ϕٗ��z�"{1$�g�&Og�f&M��x���
+oGx��6-�=4���y±2Ga"�@��RR���8��:ͱ��/���k���
+_H���vwtV��9���Ze>n.#v��rސ�J��'Ҡ� ���� �O�1U�#�Px>��o���D�ɊI��Ԟ ��/��ut�#�9�I���7���y����3��3��#�/�tɜ$uك�u9V�PAX� ���G�`>��>q�6�m9���"S��8W ����#e�%R�����#o���<�F�7�s���
+{�cY�����x�m�6? S
+�e�
+�������!S��a(����b��|�3B��F������� ���P�]&e�|K��aK��Pٵ��$�@�U6�j���X��{W��p�3l��|��@���k����[^�qr��4 D�ވ2����k�% h��)Y_��*C_�\�Y�! *|p�u�&�,���#�uF�%��6~o@�/�R�z�t�\�k��"{��cv��&��H���P�� ��]��U{��e�.D)Ww2]��T
+@���e��\]������Y^�;��z2i�ա���&� ?�I݆H�< 8v��
+����LL��l ~"�U1N���fT.�|����0����j*���� �,��F�0�A^�L5U*7`3�?F�;2�5,��2uo�hw]n%��򉲠��d�yc ���to�`�����B�߁7kdY�
+���9�^�
+��a2����ʑy���Y �=�1�#�u ���O�0�8NZ�|����>�ٶUH�ii�4�op%,�0,A+mU��S_y(�h�V�.qc�=$a���t4ݾI�U��=K�������6OeS�M� r�n���`k��^� C�7S=z���m��c^����e�1򙜈B<�'���U`\�܋�S�o��:l� ���B�6�d?�;�%̻Šz� ������W�;�~K�`���`U��U�:62�닾�� 9S��h��'L�DK [X�ƣy�HV�.[%���o�H�;b鉳��c�K9�/����<&N'8�b���[�����g�9���?ijAg� >;+��"3 ?�+�R`�sd�QwQ��:H�G&�t���tq8����8\����5�AmH,���v���vd\�b ���A2Ѿ � 얣��b� �����)P�}I$�҃��U��1q�Fɉh��&��V���d�� ��^��� �_�����d|n0:dke�=��x8��ɠ�K
+b�����kn�bz���O��'��^�Q��q���7��������Y߰�p8of�Uqm�aQ��w��DӔx7�?ras#§m,xmN���c����z��)��u�̣� t�If�> �i��K3iز��S{+�fv|��ph�bt ��K&�lo�t|����I�*�4[�Ʋi�"��]��pF-]� `AIRv���N7,�-���P�3��T�[�5�T��B`� z��!��E��v�ηJ}�Yi����=��x�C�N���?8�ݱ��������G�� ˜����ʌ�B۠��N>Ū������Upn6"#34�"G�’ӿ�G�������>eZ{0K�Q�DB�xV�x�} �$��j#^J|#�����l�@�Vv澜H� � "ZfA'���tE����Wf��L|4�aN���=b�4g��_�e�̨éXR� V
+��HL5���G����,�T�*G����U�M��>2T҈p��U!��xw"ޣ��D\�r �^�Nd\��Mk�Q��$wT�
+���%6;��l�[�|}��V���m�W�<׉��`H*��w]���u�� �;Ǒ~ ��T���:/GP''��t@i�QF�2(�L��"R`���Fh��9��W�p"|����~+FDQI�����_� �D�0��ո�� ˊ�� ���فr˼��o���L�}U��]F������|q�ڒw" �e�1 o bw��i��V��ʨ�\Y��K#Jc�KK�C ���uJ�[r�>W�*z��:��ى�׸��V����P/��?g�q��.����X�ퟎ��;��A�hYI��i�m�����pˁ�7�S�)�‹%Yڡ����y�^il�ȉ�k�0�#_4 M��X�'�p>lCR2B=5z�TV�
+�n�ڗ��R9Tj��e�����3�i�Bɯ��x;�� � K쥗��7^gi�cR�g��`}}2-e��b������]���JR�&�˧mǷ�V0�����k���4 �j �����f�����\ϓNd�����.�[��n������O9̂�u�c�+ףI��k�EדZ�!Tw�߰��=m����1���Пt�nB�W�t�������L����Y��q��/�Ä 7yI?�fKPp�S[b��'K�
+�Uz�\�d�' 1�\�������1$K��nmD-�=� D�m��=��|��EG&\�����}'iRm|��N*$��-�8s,>�b o*�ba�dλ�L�}�'����׵M&� [�*��3��7z��l�5���C���E������s���d&�h�/�m��1d4ckk8(#�~V3�N~v��y�D��+.͛o��v�Sx� #+[�W{}
+/B�v�&�"��#��];7,"�pg��lD�5[ׁ�ښ���L�L�M�Q�߽]�p�8h���B�Q%�;"`iL�+ɶ�x,�$b�yDK袴��"|���R��,��)������v�ۙ�'���=����B�Nɰ�+4��$���i�1xK�ڗ�q� O�y�Gp�"`�&q>�ꉰ&T
+g/ד���DY8�8YGYP���l/�Y/(G�����ӣ[��by�o�l:ågvl��I��o��]�$���q��O c��,��B�}N�4��B��=� �S�)�;�j�H��ru�i�'!(=�, S]��K ?c�*��U��E�u�4�5�u@��AB*���֌��|-2jI��i�~��H�D�}�
+�HH���;��Ҕ��X� OS���A:��Fm;��T<5�_Jxy���0�,oﻟ��*�[!j]-?{��zt�m!߄���-��_1���|���?�b��8�>�_@���Jj�=�*x� �� ��TE�?�'��-Rlr�#�e�����r����P�`sq���� -�"�?R���%�,���A�K��L���F��'V����@`�e�����������FS��9a���~�NW��tM�%W1R�u�um� O�O�f��r�Ћ������y@�z����f�?-L��E:��5B�~��(
+<Ϣ�,�ufH���F`�ƅ�����D��C� a.�sU����S�c^_��s�L� ;H��`�”�z(O��g9�[�.w�/bm���r����Ͱ�vz�Mm"aӊ�#.�\{9�T:��e���8��m&�����K4�\�H!FQt�P�T��I��� a��.��Ե�L�au�뤱 `7��UТ�LMw�?��%���3LQ�$�j/ؿ���\����E�ya�R�C�h� 0��.Ė/x3�:$�8ގ�4Q��1��F���R���]�9�y�J8���p=CB��Y|^�daL76�*3�.'@����9��o�0�\��8��/۔�4%�N�Y�D7a�!��8�}ʎ9™���+a��bh���!m�lD�ސ[T��5��J�-{D�ت��Q�t���W,�}T���h2�{&�;����[�4�ij���������BPry�D���Y�f�.���W7�D]y���aZ �7�v^Q���&�x��PcH'R�h�w*�Υ���&��p�X�/�m��X�� |ҧ������S��;��;�bà$�I8��_�����x� ����*٢��t�
+Ƽ)����_o;Kx'�4����/R�I�z���uoO�ZfI��!뜶DQ�m[�m۶m۶��Y�m۶m۶ͻO[� �-#[���� �/zl'���
+ ����~�@9��k��ƔNm&c���Z�dt�pM�Rz���Ɗ��D�%{8<���Y��]?�|��P�J�bK�߄�[�N��k�?��5������Q��o�6@���ȳ�K��~;x�m'ڑ׶��31)9�����������T�@&zhǸ��<H���L6z���Ǘ��͂v4&��Tc�;#L�J5bޚ�4�A'�m���W.�^5��v1��������YX�������fy-��^���Q%�i!�E$�7@�A�4�]��B�JI���ܵq��ߨ�^ ���� !j�w����,D<a���vXI8��v��k���,��=��G���Nރ�S�Js� J�Gez�w�}f'� ��sSf�gX� ko/J�WN�2���5A��J�}�T:��J�41}\��-�hSM�,�ȼ�9�?a+ؼ��A"���� :�"��şV; �"�#�Q �ӈ�t��: �!� XO�3CBe�S��+�Z�9�xdbG��Lm�G�л�m�g�|��'y�x&�^j#�t��6�V�Bp�Ŋ���j*q�������k��
+�{��<�T�����o�@\��F֋p����=Q�� �3���}�z:��J�L�z���_�n̉��ύT����e��D�kL"�S���y�g���^�k,k�kG~�G�v�/�K�2's6�6?���S>�S��d WF�i(L��Ҍ’��(��8&�1[��-����u�x7���t?!]�{=L�����=򹣊��- Ϥ
+��Q}�U�?��Sy ��f�L��X�ޫ���dA,K�:n�&���-G��� �XNNđ͘0|F�T�{r�׵H!c,s�A/IUw��׺����nd[a��j��f �wER$3p;JK~��V�큿|���� L���� +<�� Nefڢ+�/s�$m��Iݯd�|5nm�̇���3��B���7��In�؀+9�����j���w���|.N,i�� D�`?�õ�D<�|@q̔����ӗ�k·뾟� >�鱏�S�$��
+�!�[���̴�Hf�f��7�<j�@8S��̂@�A�9[�����A�^��S��������΅�)�С�Q!�$:�_�aP��k0S�h�~T^A�G�'U��� ��Z�xCT���p���f;�TH�k�^������c���)�-��۴�uj{5FD�.#�9�ܬ}'�vN�q������Cieh��X�Z[P(�u��9��X[.�2���>l�Ejd�8e�B����?F����#�,���,5�0p������?1�'��-�;I�o�����'Y��\0�M�
+���9�����NuN���Q�a�r� Tf�U�)����"��J�a�Оo�ɹk�_<�C����Ҳ|QH�2- ]٘G�\} ��"��R �UR5�A�Ӛ�0��hu�����,]�/)�G���[���w����]��I��m<=QZ��#��W5�C�/���ŏ0�Q�/j������w���Ť!ࡾ��:AYs��s_���[�c�?�(ɺ=h��l�����Р��E�j���8'Ywl���K�u%^�V��^���W��%hA���R�|&���Йծ�lgZ�s��"�E`��3����E��&������9vU�_q',O~�`�WA珈��U�ˈ�Ȧ����d�*�s�3�Zxα�?�S;��P���iW��7u�<bUX��X����7E|F�)�f���3�UR����j�,�k�X�z�Ep��`$gBW�ya�VA?~zq�Vn=�2���f����j������eDv�o_θQax
+=�/t-(YX�o:R��zkf8��&� �҇���
+K�!,�� )=������q
+5U�ي���$���O�����4� ��*�r�q8u��p1�"e���oZ�J.�_
+��6\��3 ��N��C��u���ذpx@|�� 0��)
+=bT�r�0u.X>\��BA��o����l��*���t��1���B�A�������Ƃ�)r�$���!���1�p�=Z4,�GD'Q�@&��Ej`W��h �v�p��!iox�a"�Ce�0t���>�Q\�
+Qe$tdS��JN�:0��C� �� �� �l�/�=��";J�E�f�Y�3������V����b;M����&y�ȉ�&�׃v]p&'%�� �p��� ��M��8�Sp��2�1j���Vd�h��{d�.��]kK�a�o��Mړq���Ah�!���������[3�f,��Ή=O��ִPd�ni@�Hr�$|���Lh��L��h�������m{U����3�^S��o|�! ;��
+j�9���0���:�j��W��Kƾ�,Hd�`�w,p+TL;�oыu����2��3����i] D��wK5 ������w��p�R,��b���m���� =�����D�E�8��dR O�f��@Y*�� F)������s�+��{(V9���x��j��|A���U��`dꣻ���ī �J����Ƣiq� ��)|+k�, �è� �V�j���d[�������I��2i�W��G��F�D{�;�H�� �-�^�8!|���� �S�n�ق�t�_wmU��E�wA�o1�}هxw6�-���EsFU%멩��yT�ߪ
+[ۀh�V��N��&�WE{ .}�Z�:;�&J� ��R�m���4v���jkM� �99E=����Z���f�F~���d��Y��qoH��-���&J�?|�}��6�1 �hH�x���d�Y��7��n�q��u��j: W_Ӗ������F����Yqq��ep��-E�:��h���ƈU�{�������EjfI��e�f�M����)�[h�9 =�����o�U�� i�w#eS ��艀F�������������t$�Քo���S�޽�RL��8oX\_��@�\��� 1��ۉTb�r�&p����c<���|NPn0¹����3f�A��GQ*�'�c��<�!ER��b^�S�ޑ~0��6���˾���Z�th�qL9���aƁ�˹�L)Bϫĭ���˵�/sŞK�IGs�JJ��
+�cJ'p�D8�TJڎ�Q���� =v.&����3��3n��Y[��t���T�9�2D{
+�^+R�4�������n=e�hĭ M���F�h�'��H��9ofrC�F$.v�Vj��\R��gY��͸#�u�&���~cv�Ê�� �0��y6�[bZ ��C�=e9[�ޢ��Mg�G� S��,�|���p�ץ.���'c����cP.-� @���:#(��!�@/S�o�4��a(��i����1��P�=�jN�}«�EX.b�W��~���]�i��d��Q?9
+,Y7N7@��<K(iځ����������c(W&�/� |�l)�����?)�^���i ��$��΄>�C�5$���
+aE^�-���~�D�(GQ|?��P7��zC>�+���?� ��S�SUJ����32�u8�Q�N������נq:_��0��J B��[���2�Ãn�P˩`aJ8�{N��B��F�� ��̍j6|�/�;g���9�e9$���+) k��1�Laz�總W�Tz�?�JF��a"n���f꜡x>ddH�QC߂ުTC�}�h]�I���MΔ/n)��ˁjy��N�E�=U�L�\,nh�i_| p�iM�Vkv~2�E���og���-©��{����c�!W�S8`�T��� �&�ʢ�tC����Y�^ޭ-y�[��7�����Ú�t�S8��l�����a��\k;�'��|�]&[r�/* 9�Ai��l�b9�g>0���[�Ӗ=�^�ڵ��!�_pEA��4r�p�|IB^���_�w���ڍ"[Vwh\�o���36M. �`�_e�C똭M>gL`���6�o}OM����d�0�������Bz�3�TO�����)o�8�ݬ\��PJruZ6��H��i+u㏮��c��y�f;������a� ���⌋���#/.�~��:�+oҤ��J(�� �ݎ�'P�`[�J�?��f*��/5d�C��y��Κ0�����2�NC9�8���!�״t0��ұ-��X�����{x ����Nj`W<[�(ķGĦ���tׂrcZ�>�5E�M������Y�#
+��k�|^�2>�,B
+�{���[f�>�S��mDD�:�偌��_Φ�K�d���[o�v"�!��zW*,�g;PuRʂ,ȓ�!�Ǐ5�)r�&U����Lc`l|�+'��~�<E�2���h�e@y��8Bh�ai9�W.��T�)X���L7���Z�h�GL(�T��3������E�!m� 6������z#��:����.����')~ ΣQ}Fz)pe��^JR����!�~s62��Р�L�`t: apW��# ��_��ί}F�˴2�& J蠽�t�U��!K�h�q|R�]�_m|��%��w���y6�_� �]3��0�(k�b��k�e �x����>�߳�H8�������z�z�]-d�p�� >�N.pŋ`P�ie"�IN����l`��� �7�b��VYl���c�l�%�gnD��t��R�W<���>�GbE.��H'��ʦ*[9C^�$�ˏ�K?�T�U}�GG2$�Z��¸�>��ٻ9�5��o[=y�$F
+���!ѱ�T�;�aN ^S"vXA �V�o>+�zW�$����w�|L���;��&y��o�ʎ�=��^8�o���d����o��ju��}p�ݲk��+�/�+3~+����� �F�����9�H���8����;Ԝa��RO�!�Z��- `h > ��l�Cݴ,ޫD�<��_|�?���%��}�6"�H,d��pB=��d�.>;���q.� L-��� ��3Ʌ$�}���j�?�n�)�8�8;�y2do�jE�4ˤq{
+�z�L�����1�*y؛��<�~d�*=G^͓�nKVe���R�#��<w�fX�sI>4��[Q��Qsn�Q�P��� E�n ��ߔ(�vD�����*�kc8�ɏ��f#�]�H
+�(�ђ�� ���d���w��I�c��b�MP��`#?�"��x�G������@9�{�4�P\6,�I^ka��,S���m<����1�7٥rV�O�l^�]�5�ռ�/-n�wE��R=��J�֣��9kx;�*�S� �^Y�j�S��K���{&MȐ|�� � ��8�yf�/�|Pm,�V�E�;�����!
+N.��uN�=#d�ɜϤ��z"����!Q��
+��k��� �?��H�1U�� )��1Z� �P�'J�pP���E �#������"+�0�
+R�e A�}EK����������{�6��sfZZf�cCB�� � 2a���h�Fvu��g�.U���z��_�H� � >ھ��L➰�p���i�Zi#�L��"�]����QE����(t6�ݐV�)�]�2����"�9+���Z����ս�i�V~���.;9ՊF����D�+�S�=�<5)Jy���6�KG�7�ZO>�+SP�]!0�ŀ��E��(ׄhd��_;��ʴ��OG��ǜC���v�]��+W������k���@���[��f��C����f�D���4"��� �X|��F]����VŸꏇ�^Ic�MB�{p����*I���1]�R�����p~"37W�=��ҝn�����b�=F+C�D]�gI�偾ť'Z�Iݺ�2�?��=���>jDwM�z��1�8"LK:���M�go��zBL��=��R��B�=�7�D�`.��[HRbIp�j�#�;r����j��g�VSRy`t��� .�C������n Ͻ��D���I��#xLWΤo}9_Q��{Eu�ۏC�����Ģn��xos��� 1��� xr�V]э~�-� t�RM�OB^�f���%Q��a����ഓ;�D�_8�+l�Ot����_W����@�.�u�Z�-��& )�d��,Q�(�{8㴑��C�V2�9�2ٮ{�g�B�h�x� R[*`��,I��#z�to���,��sw��
+�`LS����v��yX�a&K�pK��3
+hHH�3L��Ԣy��r�8�0�SH$0�'���ɕuuPkZPQD�2���Z���\� 'N�m3O]��Rz��v>@�.���Ew�9GPD鏸�n7��*
+����p�� aV�c#��WV3��|(<��mW7@�dSN�7$��!Re*L"��� ��
+�U�IC�V�����&�_�*%�T���+>S��<�� �EH�#l�:��OU?a��D6Z�aT��>��&�1ard��
+�����X�1�-a�*� �!�AѼ��"z�@B@������<S�Y0�(�?Z6�l�`�!}L`J�_���K)�4I���as*d��� �D�O;�O��x�u���;��I ��Xv��m����LE ZnC,(F�x��m�h.Y����-�O�^o )ō��ŜO�w�B�|&LP$TY8�
+h�"�'d�t�}*6��-@�h8���T$c��jvt��7wf�*���M�Snd��rVjz C�Hݤ�L>��\%s�zvcb �l���%/_�_��~L@�w����R�3����o� ����>y.O���4�u�!hǃ�� C�ܩ���˦\��BU�;n[�]�?E(��Jf�Ճe����_fb�T�_�}��I���'��LT[���r��/#u��]�:;�:�u����&?p�a��Ц@ϒ��E
+����ܽ� " �k|VI�=>�a̼����y���xv��� ���c����r��Й�9�x�s�z�;���u 1�_�(TE8̸.`�R�mN)�y�!�1�`6N'�n~���K+H� �L������������0I.K��΂+V����ׄ;�<�%N���#���U8�j��O�1�Vb.8Q��n4��T�d��Feе/���p4�t!Xb���v��!�Օ_P�Pm� P��{��xmى8$���]#p�@�
+��ذt�a����K���������Wx��O�o.5�}�k�1�K�Bs�S)c4���͈{T���y7�o}����]���+I���)����3���i)�Œ��+>���iG-~Î�z�5���RH�"c#mj�0po�8�����(�L͞���.j�N���]K�I�(K؞���L�TW�f�J���� ���
+�O��J?Ml8ʌ�f*,��N��Ѷ�T�H���$ �Pt�s���T&�A`;N��kE}�p��u ��7R�Ó"�T�����Mؑ�k�/߅��]�A�,�)�]( $'D�Sb��u2^���O t%�n�0z�1����3ۥ>֡���5����mz�S���Ft�GK�u��l��$=�w���?�ō4.g� ��t�FY+#���� y@�~���#�6Ļ��!��"�`V�B&�E?��ޚh<m��U�[�H�b�,Ę����4Ogw9<�/,T�cA���K�������{'A�i� N����1�ʤ���2l�d�g��d�=�4}P� ��p��j�����\��g��8��d�a�����oU��0cZ�Pbu.�| ����&��Tn&��p�\;2�s8�DNמk�f"1'q,�D�,-���]��}'0>S�m���?�d�q�������]��#�B�g9� �N*b� �sw��mR�㓃^{KsA�"L]��ix������oچ:���q�֚4c��mp�
+rRn?�-���߄��l6��a ��,oeM���iA�@? |����Q��Rdq`�HR���K܎c�M�\y��O�٪�����<c30����� %O�l�ʢ�C�t=Dý�KDl)� >%y/yw�"�Y��j��g��##�I�8�ʃ�u�a. zi*�H]2�����<�ml�hjX�Z�����l���1!� �դrx(����l�n[�Lt�Sʶ�!z,�!&���A����$<3qk4@j����?��O�л��q+F�� !tC\��:��8�;E+w/��Řߙ?d^���äȦ�f�0��&)]�|Jk�g�9\�Ǵl�q��:�p&��b�O��Q.mR켃&��C����&���ˇ���ƞi�� !�i@ �N
+��Ç諙�f���-�YM6,"j�G�����^/��R�dX�D�`eȢ�%���}d���y1�B��6 ��;�aR=>�!6�(��Zw�-�cO�#pM�@�>̍��c���CH�e$@�r]$��嗛#(��-'��*��]?�����w)�0�l>����d���k 1dcm�<O� ��ٽ�ع�2�t�
+�,G��9�ajjj �xVQ��t�D?����c+[�OJ�辒.�⸁{)ٍb�[x�Y���3]*V������T�;Z�������DP�By�{�^^�q���6�%�/d� �3�|j��[Ɋyu߯U/)�,ڄ[�����O���,�Yă�nάL��U:��c���`|��-{p�9�#�t���W��WG�3�٭� Y\��5 �-{ ��q����/*>; s�~�8&��+�(��Q�!�y�܉��2�v���8�:��㬶�+zO'ie����Td�y��W�=�qbTy[֮٠�� ����ρ\t�æ"���z- ����+�3�o �~��.#�2�~Ӆd��{��1/�4O�N��(���7
+��<��$|<��m$����Q�W�ݠ'1��\�:���4O��o��E2�EZ��.��o(yhH���a=�f�BS�$��N&'��C��8�p~m��W��&:z5�H|��0�_3�|�����W�ֿP"�5u~}}�.����+���g��f��6������F,#�` � \�Ϧ�{��p�ޣ�=b��_�z=��ԍɲB��� ��RVk�|� ��7*�1�; 5ϓā*�֑�_M�9���*��$��_G���.�]`�<�|�&��B��^CW�ݬ$���x��Rd��D5A(O� s��������Ǹ�;�Z���WhE���ص�xK�1�o��W%��V�:�Y�J:h|�|=?�*�-��n�2朓�9�u}�,�Y�?�a4 �0DڻR6�.�X,�
+#��T�6��Ա3�0MR�4 ����
+_S �[(w�@�._W>����ms�i���0��Q�䂼���uq��C��l1�.��zq5Kk�������~~�D'GC�IKߎq�i�eW� |Kl��|S���;px��Ftw:��U�q �MbK��AЪ��0�gP�,֛{�ܪ'*����� ���������L�j������ݑ��@�w-#;'i��8���S.ѭ����{�j/�]���̷%�
+ڟ�I� LSؑ���P%Ѩ�p�|w�7���|Z|��Xf����ź�a��i�ۙ��5��-�C�
+�\ϫ�{�!��D2�z���w"N�7{K���#���3���(<���~���:����Dʡ�:7��"A<�=e��O1���pCʞ��+��)��f[� d�N&��x�a7����[#��+�66�.J�m1�?��|��Aۗ�e��߬(O����y��t"U��v������������h�#pS�;�&��E��I���{��k�w���%g�qUu���x�[�%��.��Ԇ�9��}Zx���q`�t�n�'�26*J�;[Z�0�^��&b�X�#�j�{���-����Q��VJ���� �`�x��Z�$�H�I
+����$){#��7�߉=��"e^UH˿b�&�@3&�N�Xʼ��|��{ �hZ�CY㡧�أ�i�2��f��z�܄�v�0�΂�"�N��x�H�8�P���tRݢ�����?Vt���4���q#| *� �Ö��}����ؓ�Oh@NHcw���
+&��/��Vi1��%ED�>I��CB���v�Q��cјK`>��Y�ʈ����_�FR� ��28��E���:��[�~m�M�U�T�z���^7���W 0�B�<0Dw^��A��"��C=S�׫��9Ƹh��p;R��gčdw��ԇi9|`(��}��j�1�W��NJp�m=�Q6�.3�i��ܓ�o@E��ś��9�M�B���i)D'h� sa�`6���᜸�f��E�m��Y:����駢׭D�Qj�S��h�|?�lQ�.�P$v���'_8�ߦ������^̡���\����
+�A�?�|<��h��0��k�[�of��רuZk'��x���i��J�pɹs�a���<g��ǧ?xȫ#t{F����_n�R��љ��#)E��L�@)i!�kN�*"���� �����{��^)o�\o-R���[��~���Av< (��s�2�'@��f��pR���ͥ���^OJ:����Z��i5B ot���A�.���,�s�E����m��O���H�Mf̈́����ׄ��&�UbZ'��"�i�IVv���ַBV���"���%�Nb��;��)4 �g�7;�L1n}c����M��
+D�8�� ��Ѓ��:M�d�Tձ�#������]īD}J��~��yr��A��S�AV�g���z���q
+��δ�tlְ�sPxB|����W]�}�౟.��_�Y6�}wPj`��v��L���8�Q��K����û�1�j�Tfv���К����g�J(K���a���"ۘ����<��ă/��$BJU י�N��n�ktM\�"�;�-~��r��lnr3�3�`��z����!�hE����m5��g� ��a�=� %&��2�A�� �. �?��T�#Tg���T5ȃ�Z�X��2��U��{�e.d1�Y.n2w��(�9���A(�s{5Y=��8��jšb��ӀR�d�� KM��a�۶CҎ!>��,�^
+�݄��4�N-�S��ih�n����4�T��l7��;�R�>I�&e����UF2��P�tfz�AsmLܢO��Y��}P"�sV\��A� +ә��/–`nj;v�@�r��k���Ķ�������q'���)�y���K�NO���r`�4l�.]�]��}�.�L>ӱ���K�fSW��_&��d:t7QE��]J�IVf�Q̙F2CK�!��>�����I��]7�� ��δ��O'�X���n����g���Knhsf��٧�M7\L�3!����c%,y_ 6)K
+�K���{��O�(=��NGm��h�e̺�w��c�R��$n�jH�Ԩ� ǟ���P�`���g_�#� :E o�ȍ�����D�������8��+�9��Ѹh� ��c5I�BSIE?X��W{7����
+�:�޶��m(�6������3X G���A��@� F��љE���<S���0��Qt����{�GKk����M(E-Ųwmc���d����bk�,����`�r�"�k�'��S�W���#1�i��MV&Y�[���N�eD癝��prkb63��hj�Pk�U�m_�����`�R���4�j46zT�PR�����A����[�&�x�I� ��+}��O�l�X� < ������\���h�a����&��U1 $Uj����"_�����`K���͗�[��ev��3��[���yZ�v��~)R�@- �-Ƿ�kA'��;�ڻu�F�|U�!�A�>���JZV�g.��y�_�%<��/�Y�(�C��P�a�$���%�����3��6f��X� ���"��m��C�SOx�jr��f�e0����3�� |&�|���|��+2j�) ����)��~��4j���uj�G���!hq57.�ŝ(�����[W%�I�o1&fyW{���H�F������N��n�F��r�u�Z���,Eg��G9����̫����&�<��� �{E�z�����lĞ(�<G9�c"H:��
+�志��)^�Y�>tϒu�" q5j�|ٿ� �� ���U^�b��tRZ���<��<��fpg�zvN�� ����H�?"V�|��_@���˹S �t�'�r��]!�� O1�r\��`O#7���\IU�j:�[ KSx�/�D�Qt
+;�@T�4�KzI���kJLȑ'�\·� ��T�N�c$h��w�]p��ȒG�*+�����|yݞ�h����n�X�ŊRӞ�(kՔl���<Zxp�*�rf���E=���Ϟ��۵ى�!CM��;��x9ܤi�Ѵ����&\�#�#�u���I�%�� ���iT7��\?�5di:��+�&Y���������~���;݆�?HOAf�g-aX �W�����2��xy[�x��[o%��m>1$n��&U���;�9� T2㔇�ߔFL�?T,@�
+r�"��*<��$+)��oV��*g��V0z��ȲI�c��ϓwh���
+r�u��-z�0��> 5�zϼ�>~� �1���
+`k��m�u�#�?��s%� �Y�R� ��w��ø^<Ô�L8ga,�m���L�y�%C[��ռ^|&�u �u)�|��C$�UD ���mY�+"���N f�����w����A~��Q����,x���*�aE�s �o�2QHs����#� L��1�( �� Y ���>d>_P�!��p�Ҁ��:� ��Ȑ�\G�xV��Q#?7��Q?�iɖ��� �a/�����!?_�q�;�ң� ��K�UN��\^��v8�)e@�e�����@�4�x�w0�W���z]�K�U榬D�53�2J,(�p�=���z9�dI`�Usx;#��FIKqE��D�hǟ7E�$���=v[�B^Jf\�f$��q̼X'��r����l��#��l���[�ɨ��(��'�U>��x��,�ܼ��������&"�k�8nXjDw �?Ff��ǠA#~o��*��m�^ Mda������T�֐�I� _$��=o_�Z8� �p�0��1m���!5)��a>=P�� {��g��
+7/A�
+F��5$�жW�����Q�D�9���H~^�y�Y(>8�@��7�F��m�+ؕ�@��<�r[�^��Cr�� -��x6�����E��0����L
+�!���~Wd�[�i�=q�d�#N��8���f7�0[{��V�0i4x�O!�8tF:`Rk���w3�k�$o�"�]�}Oo��̊��g�>�eC��3���~�,%����H��(c�AA2�����!�4���5��7�j��@��fj-R�j��Q��hr"Ѝt��p�V027™.f�Pċ��[;���X�L!���Ǥ�E���Q��Jrɟ3E�{�}��^mnVxt�26�Q����؃�Y;R�9�������L���P�U�L����-Z�F-�V��a%e���^�@��Xfq0��7��@):UW�A�_B�� ����>�����3ŎaC��[?x�#t&�{��M�K���Ѻn�A����n��-�8�����6���֪x.��7B(q�t#�>|�fv���Ѩ�����_��惬�A�U6��$�m�S!Hb������1�i�XE酖��Avu� �N�/v4�i�zy)����y�gj��-#�R��xI3���T^eo>��^�,�{pg]��ݺ�4]흑�z�ːS�F����h���_F��X��f�#xs�ww{d��ǚ��@[�a����W�k $��o�ː��� ����%\O��L1�]j
+x^p��I@F|�cVWJx������e���ϲa�>�Q'��q�c��KT:}�!�q���H�2� C�� �G�w*X��P��x`[�wo�� 5�d�gR�=S$@��=@�8�3-���������Br�PA� ��M_���ڀ�D9��f�ـ�S��F�j�������cY$sm݀C��
+�M}����
+.`��x]�^�"��#�\=�\��(),Ta���Y�9�?~څa���ax{#)?4��2�úS�w�AY��&��8��Wv�2���Mr��<�]Z�D��[�iH֦w�(��g�q����y-�y��s�L ]Z�+����(�"�B"ɳ׾���$��7sn�h�7RO�:8�%�0���|�����m�6��$X `���KA���6dS��O��3R�M,Q��L!�-ܾ��u/��y��z���9��Y&�����[R�;���z�q�\�#����ף����l�qp7�k"��O��VW�T�_��әVm���N!RQ�\��S*�{5�I�6$����C��{tе�B�ѓ��!j�Eh|?R��@@��%�kل�̻F��Y+4?�fq=�fjy�������5�2]�XD� �̸���fmy>��w�e����V^ǃQi��_E��z*��g@u�P�#'܇X���Vzߊ�Om=KT'�Mc�3 �E>�w� M(�2�>�^�v�U񊡮ޠ�VY�@l���˲�\���0Z�`�u�5*2��PX:�w����Vfi`R=���񋊩Ώ_Ε� "Z��xSm2�^p�Z@��''U+!�ra���x%���(k��j��hӱ>����D�A�^��fּ�,����&k�0p�R��ő5FI���8���A>��J���^�r4�9ܓ�]�$��V��8�s�,�Z��'�`���������t��Z��}�?��\���*3�nM�x�be�lT����-]i�t+=
+����vǠ��j�,��*�x�5��Qj���3�����N~���� {�<PK��/��Iދe�e��ȑ&��JB�Gp�������y$0�++����^D�6���n�p�քU��iYUm�n�BT�B�xp�M’�n�w`�G��l�u��(� Vb�̢�C�g�F� S�C��- vOD�t)��@�4�ܿ���d�r�H
+��MK�;�sc<��؈���~p��V?�����X1��%hE_ Pe�Fk�$a��+QȘQ��d\/)FZ듋�
+�Y��:1v8��93(� 溓�^z�U��5�-�'w��}���F��RF{n�T�U@ki'b�����fB��D� ;)�Ly `�R��kp�`7�#�ˎ3��j,�_��sT�FQ�. �Y��[�&�\�*�YT���b��z�fޚ=�5�wjb��S�y���D3�
+nt��С[�����1�1�1��Ó^���Yj�d���?��d�ٷ.��y�����0)W��s�/d�g���E�w�����U���P��2�/����6nݴp����&i�ij`̻_�Uͫ{U�m��c6~��%z ���!�� �l_���so.���
+.%��1zW��x?=��^|���l��_cӠ�+���b—VA1)��Sf��ĥ� �Q ��(�G�"���"�D���=^�؇tƻ{\0��X�2��ю�MV ����V�$�z��]�ȶ��m�z��t��ud] ��(�0���8Qh ۉ�%����6���a���}� [,��F8����hK(&��M�Q{5yw �?�O`��J\Wgeݐ���X�Q�����l�]�l�o�`:Z��l��YD@-�͎k�x�eQE9���蹚�<��Q�����p�|�lܾx�mC`6�$��� ���R��q8wNB���?��0���S��B4桓��ι/|�2�~އ-T�Q��ʋm�T{ �r�m^���׆�&�^i�=c�Y����/��9�aW�z(�{�� ������m�J��"GJ]^��RT�>��.wRe{[?�}HG�~5r#�u�,���,�Ң� ~�����ۀ��2h�|�����x�*dѳc��?�<S�K���L�ٖ�"��� �>, q~$���&� P��f� ����lby�4�$
+L��`����5����u�U�snƪ3_������0��(�ȼBV%�Ԅ1‰�&��������<�f8"�Y�i����N�H� ��r�GD"NW�!��p����RAVUߙgCW�q��X��\��ണ�e�5��z����!�r���-�� 8 2X��]��o�ڋ� ��V��z������M��[���$ ����c#�9#[ݶ��lO� � f�U&29��u��2,Se聯���d�ryj ����[�j�}!�P��m�����Xi�Hp��huy��F�xD��5�r��w~<�� 9#܈a=�Z��8��#"��$�y���em�K����vdᡳ���Iyar�VF!����`��j�&d�O.m����Wdn%�tf��#v��\��Ls�'�=M�IdX�֨�&Č f�N�H3S�����^��'�� ��quNM�(@w۶m۶m۶m۞3�m۶m��CR�� �ҽ�w�L-&�F��
+�4L�Ӥʖ��}���$,f~�hZ �����Z��5�a�O��7] ��p����*� xs#M�M��5�:|��9@�ttf���M��Ḩ�#�&}����e}���Qp��\��v�D;s۱�U���NE�M� e��|��V��\�-��>Bh�wv�?�"�/��#��#�2�h�h�K�6� �ߵds�a�c�S,��G��;7�ʊR�����e:�P�v���U7�{�rX�4P��9�c�ώ�cbn�.C��A��5�E��L`� ?!
+�?,T����/E�V���=^Ƅ�)U��&?��þ��F#���4��ܹ���W�w2\��[ʸ�Z�b��$DS_�&^Y�M_q�d)wG�l7���d�6�x ;�h<��
+X�Ս � �m�'}Ȳ��LN��-������Ϧ�%^[�|��/�mz��JJ���A�–%K�ɹ`sr����c��1�gs�1|�ȵ"d��z �׬'7��lW�!G�֤ ͙��ܾY��c�28G�O[��/p������^V���'i4"B�ndp���Z��(z4,���;I��5�SV���C�9G��0X(�(_�2Y��1.�v3R�J&[:�U53|�lS\ M�Ӏl���SCl"1 ����v6t��{��e`�|�.C�~�͝U���؋c�PZ)W+u\�V>"$(:�
+�L��L{Wְ���zof5wg������U�Ú�⩾L(ۉ��
+^!M�_C�ÕqN�ZƌNj� L�.���X��up��y���`ma�s���s2=:1z��kG0>��� �^�N5M|�F6�^��� ��v�dczsw�Ɇ��Ժ� �Y�t���֟�[���Z�,�-\���k�>-�]��Ӆ���U�*&��'��K e�v �M��k�����L �1T��j:lDɨԢ�^23��~MB��^��ug.]�?��%�w����?�R�6�>��%��z� ���XC�+uu�ee���6g���p�m%Bo���swru�ycY"��
+��)`l��'7G��;�@K��mUc����E� �$�D<��L[0G��U�Vm.~nf�5
+;�,@1Ep ���Mtj�[~��:$�-i1O�˔��2��KqP�03�JQ��,�:`��9U�����g�h�Pڽf ���ly�}c�����o��g�`R��vg�<Q�BB�5s��9c��ķ�X��`�t'B��.�n����S`A��  �o�߄H���`�R�0�&>ǔ��� �5�;���W񉞪9:"�����n�%y��g�-̻��R]c�Wc ,H��h\�3���o��O_,�<6#DRD�+j�t�u|��S?|\��Y�b�x�X=�@5��� �;�ϱ4F"}��&|6�F���+����{������m�S7�CdsL�J�7�����Q��I$M�g��)�k�n�2���� ������!���F8k9�-�2���F����L�a�X~j��'r�K���� ��`B���h \�,�p`����V�L��&���L��3E��
+�f�tZ7$�ս�ƒr���"���U�jZx��9��Grxh���m��>�w�#�r�8X됕p�{������\~�k���|���u �&�<��[����j��c�t������`��?z����P_%�!�u�����~FL;E�u���xWC�Ӻ8��;)s4|��,���y�ٮ��8�W*��뮌�jj����׬n|��YSH_A^8���Y���׏�ܳ!:����E�D�x$]�O�
+?���k�4"q?�2{X���J� �u~ΠR7Ix�ª`j�Cy�>���K%>e�@�lʏ�H>�7mZr$3��6���K�`��+�A��5���qun�2���vJ�b��_u��dAU��F��}S����h sZ _puFY4��ϑ�$���T]U�8�C��~�%���������|6OҴ����'k�…Kc=IM$�7�����;Q@��&��V���"�"z��:C�&VY)y�>,�n �{OjgR�e��_ ������!��#���}�#� {S��-�X@o9�����:y��G6��[D�4�rx|x`� H��o ���=��<2jwFI�y����:A������<ݮ���x�I!v��/�\����s�9#A08U<��'p�X�3b?$�Y|j8F�*� z2�ibYX:�K޺L�t�_��-�p�}��=�k�������^���;��ⱐ��k�J�#�/��u�jC�T�odgذ� �q���0B��<����\��ke��|�R�Af�+=���H ��\�u���/6���N�U��a�Z��jaT�8��F���Y�ٽ�Q=�6��;K�� �'Ց�J;�Ϡ,��y#�*��� � ��"q��gr�uM�h!hfcHS� Z�As��Gc�r�hU�?!K[Q�d�ߍ������'츰+����M�t�ǭ&�������L�c��XH����T��̫il��"���6{)ZCt�H�*��E}܉�s{��`���y;b�K}�>u����B(�z`@�k�L�I�*Z�4��!]z�ߛ:]�9�-#��W�pF��Ʉ�P��-��̑4;�_���?<}?�#�C�!2 s��������c�3F�\O���aB.�%:G<�z*��V~^,'��y-�W�D�qC���>�7���ԥ%�䳤 f���o4tx�a�'ĭ�; _��Nl��{ 9�œV�G�,��[��,8bB+�@�L�Q�o$,�T��t���XF aɘ !�����[�m�YXS݂��6.��eζ�#-�R�\�3ܞ%H?�F66��rQ�O�Br��]�Z�B��`Gӧ�������{�:(�
+��y���y�k��k��
+|�&��\��dž2pL/œ1T��vb쬎���:QgkW}\����k�>�n�c�H�o~��f*��� ]䠍�љ����#���,� 4�����7�$OQ�9D� xKZRC�P�k�o��.F��Ъp�`S3��ꯟ���b����xf�k��yN�P#��P`1N]�'9ft=��B`�D9#�M����q-��_Uy��䇓;*G����1 x�O�����پ��Z�͹q�'�~S����THT�Jk��8J�K�dZy ���b�wy�)�,�+9vm_R���*���Y�rH����kۙ�ؤ�Zz,V�0���\̍��\l}r��et�r9��:��5�9�{������cf�k�N�E5N�k�@���v�����65E ��K<~� �j�;cP���ub�.zd��$7N�{ �89.��€:���U��crg��,����cԞ����'4&� ��x\G�I�n�Zex-�"���T���MEN��R:��iӡ� 8a�Ճ���0����18�SA����ws�Wp��<� ��=�N���n#9�2�� ����u��w�T�^�?�C���aՑ!������ � �vLѽ�a�_ ����������b��ßȳm��|�+ '�Q��U��*�9�E��T��|b
+��&&r��U b��T�� "J~o�8�����>es9w /^�+�< ŕ�.]%��'�[ўW��X���� �n��E`Qc���\�B��ީ���4~�U]�т�6*G�M���!�'P�M�ah��x�`�/���O��@�XaQ�;�W9�x*�P\�\"�� ���b��̕�{��a�;>/�lg��fL�@l[�
+��ʪM�<04��LG!���H@<�εB�!�ӻ�?ˠa�8����=*ӎ�~�|��U/3*�ʁ8=`h��j���Ϟ��1���}��Jz�0\5�AUvg>��O�|iw]zk4��__G�*�l�P�N˹��c����.L銥�*�D��a�����8 ;dV�8���h�8���i��T� O�jD�;~��m��{[�x�6�m`9�*ǖ��f܌b  �7ʿ� 2yg7�����EY�,���C��7�Оi����V��>z�_�-����ۈ`�?[�M�ŤT�|
+ D� K�1��P/�.��gn��_�rE ���D1=���P H�mO�������w��L-���F�A�_��6 �T���@3au����>@�EG C�m�1X��רYV�� {��|��9]�)��_Op†�;1� ��� ���fX�
+��}�M�&���V�e#j�*(�/�zm%�Ϋ��U��t� ��v@>���$�p�J�务q{2}����\�(�-����_�|�ø/��^�����m*�g�Q^� ���G:�5�9��sl���@�0�0t'd�H���U^���(��*����� �k���YV>x:����L��IQ�1�PL�f���D�A�î��U�\�Mu����G�w��Y��7E�#.�Ѧ�[�y;�V�|�
+m�)[��>��V� �/�r��Y����ߖ1 �­Sfo6Z͎Q=,��r#O���(}�{�@.�3��D�,�v�}r7r3t�ٸ{�ȼSm���!�A�P�6O���֙���g���$�q�P�.�M�g�wJr���/ �1q�'A�ń���y�"�a�\�.�'��w�w3&��)���n��(�ܦoȪ��=��".,ա#�}��y��z�OF�;}��Cb���c~D�:�4��_�|�L@����@pS��hSu�ؐ�MRŃ/����ɻqqz��b$�J~s�zy _� t� ����e� S�� �����lx��;}ԗxD��u}Z��!a�l@�.�S*Ӷ����]s�^��Rv2G���Ӊ+��˼��Ly�2tߩ�bꂨ)�gϠX��i1>��MQ�,�TX� [òT��1v�#��t�d��Ѕ,H���
+���?Ì����N'��>p~�ޠrY����q]��5f(�T���6�-�����o]2���R 7.���gy������=p痕s��0F�6��@<( z~�O���ϒ�{���FGI�nS�Aӟ�hsݢ�,$��Jz�FמQ��ϟc.5���S {�u������OKS>�u�c�:��D� �)r�K�����;�_��9���y�hІ ��w�1�x7�
+8}����#B�'�i�X�F�r�O4|�6�27�e�N;`&�-��d0�����(.Y��Ә��h�^�2������kXf%�A�jƄ;���}�+G �����(Nn��j2�N�f�����o�9d5�i��s�(�m����݌��a��D�}bn��zyD�d���?���G����e���$�b��u� ��B�OG�#%����)c�ן�uc�����Bș_n������I�1�a��YY���P+�*�>��j�@p���8A�5/}ƯR#��b�W�H+�:�o��?J]�V�ӓ/Pa�Le!�����n��'rш���"��6� �^��nc��v�'��_��e X ���e ��ߧ_���G�/մ��޹e!d�-K+ z�%��nS��rZ1[����-Hf���Z�g��E��F�yJv����|&j���A���Ja=xղ��w��T���i�ڵЃd�(->�k�4�YJ���V���na+�ԪP$0�C,����։�i�[-�8�.I�~���`M^��(f�,& �Kn���t[��%�q�L����M"�h'�e���cJ��i)y���p,�����hp�}���1��?���&T>i�NW����w{OUv4M���bX-]RW��ժA�V�pC ]P�{TZ�&��$��Oi��!����M� ��γ��bNR�tu�Eאn�(7�d*Ro�!�!�9>T�Ѧ2����#���1C�| .��~���� s��
+���8i^M�Q�ǽ�)J���~��[jH��%�7����̤ ϒƚ;����
+��%�s��t�J��զn����
+>\��������eTdr��g&^�ҋӾ!��]7?a��!�#�E���>j �AP�XHI�q�*'�{�^����[[T�&��M�ճN�A20��!��^1�M&���%�"γ�*�r��}xW����]�k9QϾa�ދ�u#D7� �$\ߩaΠvػ ��J�C�U��8>+� #����]���N
+����w��m~��W �j6��zNv�Er�5��R�U��[�W�U��v9:��o+8γ�)ya�佭3���=gjvy��<f�2Xn�Ť�žp v�uf��Sp���~�%�vW�D.�eu!�H��p�z����m#s빿�5�a���� qm8��.JelJ�p�v3��~j���RG/������Rf�h��0�>��:��^Y� �,>���ͻ��v�?H�%K��fL�ψ,�g�9"�F?�^ծ5��@`Q��V���1���g炿������;|�b��~.~����*S�5�[O�Z.�CS��PG�.� aoLA\M�侸���"���'�t����Ĥ[<�_ ��f�e��a��&��Z��-@���/v` v�y�w�p���y�Ԫ.��~�-ҟa�F~ ��������=�O߿�k!��@,���=b��4��N痰̥qbrĭ�l���)J����c/
+�v�6#� ��V����>Th�FS��jI��nܮ���`wD�x b�LS��y�JN��2P��ϻ�G�Lә�r0��yu�wEΛ($�vSof��wG�c� h�W�“V�Ŕ���g�� �`>� ���i>hiZK��(��>�A�0���nB&��HD��!C��]�`߰�(QBNy,5���ܖd��G��R脄Yb�$�`���G�L��R!��+C�p��2�����(�I;a9͉��R&}��@ٽ��}����zZ;D�\�(u�����.�!x���}~���T4E'��U͕-c;���Iu���F�T��۪KRr����Ϫ�{C=�O�9�-։Uc6W۶0�I��a]F�*j�z��U|q�9��(|9�n���=}rmDR���z�3.(���1L@K�O��"}'R�p��,E�C��O�d7@'�V�=�~5�2(S�xB0!d]�D����`ZjUs?"����^��G�7�ބ ��S��`� �������r�"��IJ��! ��O),?��I�����w�/�NrmDs�A>����.�Cj����I��ʭ���qnU�â�^� c*>
+iecF&�¡+ǿZ�,׎�325��챺�=���k��m{��#�.Y_�\�������ϑ�]lA/�] :M�P�74�<��&�P�)D�ʪ5�a`��m)v$�Cc��5kSh��f �� �bk��/�kX���O��_|�ӵ�8/��fhj=L��9e*�r�G�bY+{p������;vtUQ�JH���(ᢲ������0�"����Y/bReLK�5@u�0&L��
+�0;k��D_כ��$`N�_��e�Ѝ�s��8c{V�|_����`��{:ޠc���1� lͽ�kT-[���m���D�;��z���Is�J �j&��� ����H���؎)�#.)������I�ك
+@|�K΋&��-�V1�%_]����p6��f<�қ�MV�%�UM��1�~�>���MGo��f�p�d�3����f�>�/$���;�}N�]�a�1��1���C�w"x�YA)�J饙guM�� �˜\�>�[�"��1%{ ��]5/Kv)d+��h���G�,Z<��<�;��AN7�Ű��`�1�yh)�r��f�xn�nbZ �2߳�� �4x:gu ȭ����aA2]��(z��$�FjZ�/��c�.����{�.�n�� ?j^+V<�| &'Uxp��k<���,�[fW�ol����5�'my�pL�l*T�/�f�����Ĺ�'��O�E�N��M�h{��5}�K�m����/�`.�\c�(�H��%��H_��,r1[Qu��J�8��Ȗ��<�3Nc�Xy���]EbZH��2?�C��nR�k b�gT,�l�����l�D�����f�����C�>[qX�1G��~� ���w2��T����4� �|�gF�>h]����ƕ�Q��gM C���f-�򇗀�J�I0q3i1n'Vj-�{/�0n�k�S>� ��~��)���!�� k���9��5�}[��Q�ÚYں��ړtH�[�ܨ�����i]VZ�z��
+e\�S��E�`|'���<e=�A�e�ϴ?������M�viR��r���9�/$?���Q���{8�h���p`�}�E��dh��0�����H�;5�G�؈xH�蓙zl7 �8� $��]4E��s�5��Łո،��U���lJ�$Ƌ���K$����5���ŕ��@����vx]�HO��M��V鱟^qћv,�\�R����8ak�t���_�:_(�l���4�h"/��bv <h�d����WSf�Q3��d�Y@�9���1��N���;-�;�{�@.��Ӂ` �6��Xo&��b�ak�l�FUA�n�7v�A�@6x��������]�T@��(�-p�^������ ~�:X ��ā�V�� ���E/��z�1�@Kړ�쮦{ɗxa5L$���dn�lK��V6@�C3֘y�: � �6��� ;۷½
+&�aO�TY�����С_G����z����::.%�ޫ��h�����;���.x bĄ�a��<�V.��(,K� I�{a���kV����b��iy��6��g�G6]���fH#"n�\&�
+�bo,y�r��4s��)֯�ݧ0���?�U2f�A��E�1��P��R��n x��Ȃ{9�ŭ�c�{7 LH��yy��L�����j�%7C�d�%J�J�;{:S8%g��d�O��3^��1���P8��9 �֏y֟���g�v��G2�2�������i�$���
+�=��d�U�uD�l�LK +̼3ÿe WP0��Y���`��^CmU86�w��)�Q�x͸/T�7�`�\�q/�t ��n�S�C#�1�sJ��tv�K.����G'���fZ7ri1xY���b��)wy��(�cd�,-t48���]*h0��,�u�8�j�~!��w�(wx/Oj�0��7Y� 'O@Z@2w(�x�* �xH�� Q�z�R��x��ǜ���N���h�Y�z�^��`���C��Ƒ��N�/SE��[���jMp����țXxP��l%$��h�iI%��'�B@\%<�=����e~���0���`�R�1u�Ȭ��`�h�г'(�ƹd}{����d��i���[R� �F$�50Q��nt� sO�0�^1aL����n9/}dY�8lr5Wg7醴J�m�A �����ݧI�uMd�[��D/r)�p���`�<��*ti~N6�.� ��SY? ���8ǫ�a�:􂗽����VK�s8�*`s���9�z�>ʢn��$�FG��u��Y�eR�DD��譫��c4���Nݠ���&&.o�&T׸�� +��t�#�ɍxT��Y$���L�' ���(��� Ko��bu>�-��O4�#�R �
+��� ��
+���>� ���)fu�R�,� ��d5�Y��T��=¬����R����}��w#���w�`o$�\��������~�ڋ-�4�� ��-)��tPC�w\(Z��� �76*(�i�
+��C7�N�|��� �� y�ᇧ��@���2:;-?ki�b�����gߎ����5�߽V�w��෡�`���l_B�(⹠�� `ff�[ہ�40S���vG�tC�Q�v�n��[
+}�����u��;��KhP���n{-I����� -3�����+>�{;���lG��+Z��e\\}�4��&��5f#]�5sa�e�<���S �r鏆Y�}��6�>ݦ0��d_2�I�
+F�"��z�U&DNv�D^~��pRK2�%OQw�+��kE�S �����"YI�!��)u�C���Q�
+y�~��zE��o�'��g����b�������K���-���I�s6Nf�4 �RK��,�X����b��{�|m1��3Xk�'�<�����Đ�Šh�d���g�s� �:���0 ����(��k %��XQSt**��b�G��,���z� �m_�f�*cF\�^,֎�1/�}6��o��cc 8hv3[s�&��H� �+fp��/�͸��|ɏ�$X�J��u�8�{u���%��*��!�F�x5ou
+v�rS�S�1��#���ŀj�(���:2���b�Tؐ�~� F��ՍxEg<��PR�ޔ n�X!ۖZ�<�9�OUՀ8I�O.l���KUF��hn }�+��oZ�Cŗ*�U�}�jJ�8s`7��^�ǯe��c�a�|���qq���`�B��� 蔰R��l])�gVъZ^����Q��M�D��έTu����U ��(�������(Q��
+- z�c�������(gS�P�[�����"bqo�Ф%K�����g\ I���{���!���A��k�!�!7od�=|��&��\�
+y+��d6d,Lu,�+�DӁS�(&��F��W��8��N����А�D ��F��e_�0z leg��~n ��F��&��+�i�n�V��h<���aր��rN�z��z�]Z%���;_ك��c}/VӕC#�o��wTZ C��J�M�Yg^AN��\�j�ʾ��qFp�@�{��E�G����w�F�މg�kb4K�:u�v�kk!�Ϸ��� �J���:>q�98l�@��_��h��$�. ��*���Q�p��X�o��#��p�4�ڦP�1�u�F�W��[����E+ϙ�%������U�7�Hb�P 6^ʾ8��U[ Q$�� J]2�������ŧ�]��S.쪲@���-�]mq�Y��m�V�֩�_'��Dd�»x$����C� >(fx���O��b(s]�oH��t�
+����� �p8�H:��Dzښ*�J.��q�c��ec���#���|�#�D�O��_|f�N5�uqQ���ZN�p^(yPU��`���p9G?}��1���״��c���̿G�r����t�3W8�}1�� ������A;M?�kA�1���Ne�D���mU멟-˿b{o����O}��f��u�\û8!��W�������A�4HpjsL��FP�-�R'h��fܝ�1��{��+,g.���l\;;��*��*�|s�a<i�j;��r}vl��M+�����X$�R��-D${½��N�\%�@�0��d�$*a=�q`4�t` _�)�|��d��32�7ͻ�)��z���}��e����@ɝ8M*c��eO��o&”�5����G ����f����{E���[}�6yH�n������q����A�[dn���A=F@�������C��rMu���I������ 5Ν���j 㽔�R���䲧Eqm� �� ��9��E�I�Ǝ���4��?*��w”>����Gf��zPʯ�V-��~ѐ݌����ԋ/�=��$P�����o�yNa8"Y�Z'篼����z�%��lJO���El�v�8ҥ,�].`���2�)�����i����}��E@�f�����s� ���Üt����O|D*��Y� }xd�`*Țc-���gg���4�H���!��������`Ig������Hq�bn�"��#C�ǃ�H(C��
+��epJ���ُ�\U���ʊ7iz��_��CK��ӤVM��_�N��UH�~h9��?5p���(��ᰎ��L���EJ9�3�=j��rߡ��=�oȹ��Ok�T"����8TXe�� ���/����㬜 �YDOcm�)#��(N�̟X��a�ǖ������e��z~�Y�1}���N��>��+!��y�Uy�;�-�_7��1BG��%�S��#�/(�j� ��]��9���a��"bw�94�s�m��Λޡ�gJ ��G(I �w��􈹠��M�i!{m��k#Z8қ$,��ʽ ko�Se�m,�p%�A��n˸h�N�E�o����T��$�B�o
+0C׉>���AB �CA ���z�!��OVXdž������D����� �[���D9Jbc��5nS�z�����1�"�nMF8�^�r�fG�8?��0\���:
+�r��7�� azkӌ̧�K�� �����[��Mä�h���� �������I� g�-M��l��)fA@G����nai=��8�a1��N�lj_�p�]q{C����-[�}���-���s�$M���9s� *ڪBp�XJ�u� O�vF`�J�����"��wwn�%�:�z�LZcL�VN������`{� q{K+m`j���t�8pm���6��L�2A�Q#f��qK�RΌ���\�bs�'�j>#1K��T���۪M讁yp�������1j+�|Pt�������Px`�q��5j:�w`�2ނ���9�߭�J[:��>���lߟl�ш� �[~A��S#.E����{�zps��-��{k�~�0�b߯旽X0m$�c� M��R9%<�4ӴU�ir�&hF��� K���;��7����p��4QG���8�B������͌� ��)�̵xz�Y�<�gZ���5� Z����s��ݢ���s�N�"'8z��6��ˍRq�J|S���Wh�C�O�S&bP�Щ�%l#��/�H \V�����=p8����)�g� �<�e�*Sj;83���n�����+��W���.�Q��~��h�n�IB ��VT[�3 rs�B�D'y��?�[r8���H��&��'��ds���P&�FZ(�rE�I�N8hu&�Gu6���V�͆{اҺ]�E^-��y�T�a�������C��U�$RZ@c�zn�1��Ql�W���f��J9�a
+�N��$�����EO���.�,�Q@[�ޡ�Y V7j��~
+�=�#͍��� ������#����h�X�򄻸$�H/�՜�V�Lg�}��1�[cY����j��6������a}���BW�pl$]�I-���C`��CͲB��R'��ۏ�8��ܲ��m�~�#x��d�9�����M�ܕ�f����Ҏ�<t!�H��NJf�poCl�
+֬dy̝A�i>��%쿎��\@��r���<��ژ5l�z ����٠�F�� v����*`���
+*��(�|W��W
+�d�執m�ž��z�& 0�p��1�6��#���Y
+���"L䣻uFR��w���"�I�Bޗ�p�S�'����xp�-M�s=���`r���P�*Z� &ip���)�vJy]�U��cZ=��J����r%*���7�W��,ӑ�V/� c�?d=��o�b~|�S��HB���y�V��8�d���ds����/�=|Lws����ȶ�r�^����W���j;����!h�6���Wu��wg��o��]YM1�R�4�6i��W�9 �y����8"�5h� ����U�j�V��z(r��C�Pb�᎜@/p�]L?iT�A�Eh|E9 I�y��0�Z.��0q���"f��I��P02�Fn�i���?�*`��� �)��-� �D���=� �����iݡ�nW�-W������i�c:u��^pX��'��5�ٞ�$��}�kA�~؜8\x��u��泳L�2��ơ
+�]�#������SAB6%i��z���Y��c�;uz#��L�YI���~����V�9�7Z�I8<ˬ�^y�����8V_D�� ���6�<^��#!�F�`��'���4�id�Aڽ�E6�M P�`'��]gsS�._sf�YԲZ�m���4��Y����q��~y;p� �wk0}v�Q��m怌z�C��.�(7m��exMi+o��s,����w�L��sgFY�Y5D���M�A�Z�,d��yi��{8��*���4�ِ��xvز3�D��u�kO�P�����|XG ���D|�f���D8%]�����^쎪�P�AaϤ���T���7��B���KD2�(\���������8ϲ� ��8���I���U����陽�b�yK������67"{��;�������2�>بIR���R���e��ɚ5���2�� �uO�O� iQ�����ˆX^�C{*�b��y�b��l�\s���|�ߪ��Y#�[|*@���j ����$u��nj�`���4���Q�h8|�陳�j8”��5�W���0+_��M�'0�\�x��zM�4����en���a���W,�f��1���?��Mo䯷�i���ZF�ߐ��vR��+2D:ݽ�-� �0M-#��%�&.�y@����y� �[(���$C��C!�Ož0��ծ��-�0��׾��B�r�^�Q1 s�xI�5�,�Ǝo�hmS�">;��J����R�z���I��_
+tr��
+�m��(n�U9u�]MV�h3����9�R��j]�lJ�A�(�ҙĩ���L�x��
+Ao
+n'Z U�7��1Mj@�8=D9w��;�ި�~��ǡ� �X��IT�4xVhA闉j�qߗ�:�ߘLt(��!vMd���7b�iT�{�� >������V�a�.t!�(�9��+t��[l�3�B��3n���8,,H��'1�$ލ���wdc�=x�;��v܋�Yy���S?�Y��X��;+��(~7�s� W������?�'3d���H��(〶7��1G��~1�>���)Op�����'j�MX���a�^��o�·�N�j��� 5F�
+g�X~Hԁ�\{,C����r�I�ꄆ:��C��BB!��G�ŋ�;T�R��˞Ï�YAlJ@��^�mr'���<j����]і��Z��+�� ���^@��ga3�D�(PT-��Ч�Dž}��K枑)�Opx��N���g��fEt{>�ͨ{Qj���o�w=�QՉ衵- -E8Jŝ�f��t�����$ Y��:�g��/տ8�f�i��9S6ir����'*F�N�$o�c[l7�L��m�L��+-�@m�w� �u��Ϗ�G�Y��͆�R��#���%�|I���8YK�8�
+� �Y�Zc��ׄ��9�i��L�ƭ�S��z��2WN�^�o{xب(R'�CW��b��8�٘~L�PS���0/\��$����@���ol��7+��Cs�Ńl�K�dE~��;�<�P� .>����Mx�{^�%P��6G�b���F�Y����:����c�N��C �h��� ���^L�,�3�g̮O�5Gw�h��q� &ۆt��4�Gnp4' ��\E!�1�1vu����pH�{�6�t �h`�/�*�]��hf�$�1%�Y�H���L����V���`E5q��g��%O^���6�$����ɘo�+<as�|7ѻ.��H�Q +�A��6fP�W�G�ˤ��U�oYWi~�-�%G�垵@� ˵�"���ȁۂ/G�ݪX-Sz��y"ة�O'{ħ$��0&%�_�8��7����Eջ3]#ԃ:����^r���p[W=� q�v ���_���@����i�=ǯ�"�@G�/ [�
+�W�v�>f�r��<�D��qP�@,WU����9֖{G2�;"|GJrq���Lc�`Z�D��{��\�|QqW�T�}� ��vLkW��=�N�
+�"�b��2�[.� ���zD\���Ƅ�Q��5�LG=5�3�hU��W�N����-��8B�.�Ϊ}��ó�0�($C�XTIv-�_�(P����Ȱ�C�ˊp�]����j�� ��8 L�d���B���%�,Gd��y��5�&e��I�^��ڵ��� :�G�{�����Vd���{� =܃?�.����Bp��fNKV�:�v0�b��j9��� -m!���4` 4ַ��D������Wy�+��X����!O��fp3��NG�p�"]۬]c? ����@WFubPA� Z�v4�����K m�^Ni�4�|Gn�4��gqU]�-'�be� 0KOB貓%ab)F3�'��o_�U�EJ�!4 ������QS��rߢ��4]M]=���E������]Y���^�~c�ҙ&D�|��K�l�^���*H$c _CUܧ���:Z*�Q�����Z�p[{�J�_7�C!�n��ȅ�wf}n?��+�?l#���2��&]L5�S6�x�g��6TY��җ�^&�QG�ɱj�)4 ���R�z�Ϡ=غ�x��l�hO�w��_�iB�l�U�3���F���j�-��XC�D'�9��/QK*騜1rQ���"*�&�l��|Z��Go]��.��B�4�����YN��� A21��J�����9-��(I�m۶m۶m۶m۶m��nۚ1o�+jUf��_7��� @�nk�-�� ��d+f>��* k�& {o���]�
+E���[�K����ʶ�8�@YJ���V]ّ� �~^͵�j�u���H���!Æ�I~��%�iB ����@�w���GI�BU�;��}�*G^g"��/�f�[�6YG����{�M��hx��S���I�K����f��=k*�fp\p�2L�rJ���=���0ad���g5�z��B�R�3dNJ- �Z���:S�Õ�t6�\7�F��,R��:F�� ���]Ă��aO��$�DJdF}�biYod #v�y,V.y��ִ"�lk��(�xH�8�Yb�Y�I�blA���&N��T+�]%K��>E�<���vz�3
+����\θ���-��7�U.�s��s�@u���zЈ LCC�7��� �3hs&�� ׬����9�!�Dܔ�G�Bj��M�U����"L[��n������4�(g�.K�'�`�T�n����oh�%���$�QUK��S�\�s��ҩ�$�� �5����}�c@n�
+̾�2i5�p�(-$#*x�}�6X\�0e�߭Y�c�'��L�U��#0r ���eW�<���H�g�L�F�uM�5�m�{^/0z� 5M���� {����(�4q��{��U�!�|�[e�x�MK���K�q��B�lJId�;.0���P��W�.{:��|�3Ğ9R|��%����̅<GS�fcy��n(�L[ph�a<�mo�9A�gi��9KP���{O��� �G,ּ3���?kwAN3���W�Ԑ6��%|~-����(�ڷ�T��M�"5��%���v��s�����l�d|��[������ᢚ�Avæ�X�J��@�"1�4�X�����9f�����S��i� #>��u�)�&���=�4��Ķ)�f�"��}t�r�՚��V7NV*� 4�?]t�y�zD ��#/6��21-�J��Upi{%�2l����?���|ݽ�[k�Y��6¬�.��}��������T=c�'�#�؞6�v��+k�}���Eˍ�r1�{�ҷ&ո���Kb~��h_�YDE=��fuca���_�l�����Sύ�E� �n� ���&�H��B�s��*������b �F ���٤�@e%!q�^�oH!3��bN��y�P�[(Ŋ_XlzT�U�Q�����l� ��!����|�c�7� b�ڕ�Ӆ��B���^�y�~ �J��S��D&yY&zx�X����y��jrR��ގ���+S�A{p����!���R*R����� ̜�WĬճ�yP�M?d��ʯ�����FI^o���\�ȾĹ����W�\b;53���X��_І���s9n]FK旤_��.�U(ou�����5 �6��6�t# Ǘ���cF�����"4yc�BOL`�Zl��>�H�5���^-�����|)j�O��?8�q�XTg=o��qy���ѫ:��
+ϓ�{n�EU�x�XI~ު�>jWL|����Z`א�����q�c����}��i2��l���adZ���(��l� 3�1��ӵ� ��,6[���},�����J$s��[!0elkI���T�4|6HXc$�7�Cm��Lf:j��Z��[A���ƋN�����P{d3�U%aJ�x��ɴ�PT�Vܰ��� X?^a)y��]�K�ǝ��4!�be*Y������e�ȸx��|{�� �HM� �_L�Oٛ���±fҀ�Ycβ��&�q��Z&a�nK��}���e
+$���r�]��ӻϻ��6t[+u�7Xh7a~ӌ8@ϑ���0�;�Ԫ�)=� X)����~ߞY��l�R��Ns���/ux��ū�u��$"�ݎ@���E���-I]q�yU�D��
+�����-�����L��돐�\N�D6�*`��1c�|k<��}����,��a��ֲ�T� O� ObA�1r���WUYB�#��A�.)�3wt moA\�`l�ps�Ą5D4'���T�q!���M}�ߐ>��8��i��G��a\1C�cKh���{V�F_ �QO�8���C��xN1���lp���oO vn06<=c)��I�)���n݉y��x�A��w�hy�@���v1�S("n��A��Mͥ
+� �p�g����}��)�m�rQ� 6��#>�r�l-W�[ea#�>-��g$-�+�iN��9���R0��W�2lg�ѫ���.=sr_�B>$�@��ZkqA��X�5#N@dT��;}~A��hV0����2L�(�o���[E��4ވ�r2�4��-Ь�z�96]&�#=����~/] �����k�h�ꉪ�#YUlK0�Q�Eݗ:Yl^�l0Nu+2;�4o�h�r�2������ݣ�K�-X������lI�q�$�%����(n�� 8Դ+�-󳞑�#!����yr������(.�,��Iu�A�����x�ק�o�}0:Z�צ{��H����EU�q��zK�\���u������MD +7Rw�PN���_�4ZCi=����^4$�]�����#��;���ƚ�q>d� �9�Q��X��sB������gG�\�+� �������Yϙ���sn����Q׷Iعv�j\c՚�+�
+2��_�!����X����םj�wQ� u�z:��Z{Ml�O7��f��{�^�s,�͍����� ��R��9�J�=og�/�X ����L9�a�v�7�=�������N�~Z-.�����P��+��?���D�k=��@�A�M�Z��8[p����k�°���凶Y���|;�/����}r��� ���j������g�TW���z8wi��[��N0�ˠ�"ϳ��#z_�Շ}k�$^�de��� /db��u�ho�OO#d�%O����[�Ƃ3��ށ�����L�IwS������&��e��z*�$�-j$k;�����P�����Wݶ���[\�X�2d���Rfd�h \$��6���
+�)D �:�C;1L��-���o����Ґ��[�NW >:���h ���q�5S�ۺZ}���DZ� <]5*�� C�=�@�n$Q�8X��_���'��ד�q�����6~�-e��@��Z&�z�l�����xN�\=�c����.�4�m����O{��(G�oI:-d�2��)*�ӈGl�L����՟FC*N����Gh�!b�ȝ����?�
+�;��d�@}�oD�l��!�#ab��v�S4i{E��,��<���թ�a�8���`�����f�/`�}�:i��͒[=0��Ag��O�.��8���+YN����>&,��;��Y���.��D�֥ ���-���f��L�io��֏�I������P-�6Y��x�&vh�p�3�e�g?N����C?E�׆�t$�d��(�H��N�p�LL��q��y�0M��A�fX�sEM�}i+�x��a5;��
+�s�R7c�5�2�P�;�O�祲e��;Է̀�� ���(�ɖl�QI v�6{'��ō�F���`���F� ����:��3�WX�IMQ��
+v���G�?/Y�A�95c��k�p����ebND�ɺ��F�Nxa�8��@�s6 H�9O�魗X|{�O���hKٛ�%e`��<OЕ�N�*��^�dt�8�)��ي��� nʈRn"l�G����ws�v��9zsD����f����񠺈6&�&�t�^,!ᙊ"�y;���aӀR#��6�䇔�Ow��4�����l��/�X����y�hk͂0a��
+�o@|sɛag�-8xMs��� ��o�
+|3X���+��bID9�l�I�.�-�N{,,V�z9��?� ��O��!-%�vc���*�pm�'FBD�m4!vZ�F�M��C^:xs���ƺ���Ϭ�2_3�]b<��҆Z��}���Ny���<�,���Ll &�������w��| ?��zJ틞֣����}�FB.�9F[���}cV�1yo�^ +��/��T䒐�&�YE���[�ȂƢ��̎�~��|�t��^�N�
+JQ7�F���Uۡ ^�
+a���]LH)iHP�L���O2,/��k)�eis~�Q0(!��>��������p�a� �R+СUT�=P-�ᅚ�J�M�]�՗� �R]��d�=�y:�O�a����'�Q*|�s�p�X��פ4>\��w�~i���'Lk��sxP�'��E`4[���I�,��n�)��CP[A��е�����3輅L@\]r8�FJk8D�QkV*���j�����-�dLm�¿=���/��3.�����5l6�5sym��n.��\�� �@� ���"b�N�
+�^ھD�veË- �~%C�b�%\��M�6�87�jf-�c���,F��j"�k��J�RqH�щf�C1�l�9C<'�y7.�2bUyZ�����漤�� ��i`k�R��]f��c�;�Mq�ɦ��[.�[���^ Hm+f|n��� e������? �������N<��B�˖��J3�MEr�� �9��X����l#���X����-cU��:cq�X�����F�}s�i���б��&#%�������͌��@���u��� 1����e_�"��J
+�V�JP�bq3Wl��_�I"�T6
+0���b>�#ט�����p�2�s#� b���i �)��{P{��u��=h0#��x��դ����3��WF��3ԓ���6���r&�
+��ts3c{��w�\8V�rI�� �H#F�ٗ�f�{*<2��� � �&R�a݇e���5������4����Bq);�"���]�q�d�%
+�h������(�&#`�WP��~��y�A��+ ��I6�B�UҴ]��0���2.��7QvȄ��I%��"�]� �@):rhA���KKt~��$���d��9E^�'€�}@�t��f�p�9��+y��� B��ܵ8�:��=�o���v�J\r�i/�8ѽ�Y�I �/�ǿY��l�n�vA�ޅN��Dh/�5�)���6�ÎM ���X,Y䠊�"KY�/����]� 6q�m�"7�b�-��ܫ��u�P��B�tC��=��d6
+�Be���ZUS�����7P��5{� �o���� 6��A@�>�;؅�Ti�v�4i~�m�:��'=��jG��et-A���p�/���_�[�-�Y<�w;�y���N���@�D�QT�x��o�����v�R@]�:r����[�Tp)b��Q���EX+͜�`�Iq�!y�,k� ll�ۢl]�0����'{Am������[; c;\�c�;�.�ZXŬ- �e!���mT�'��
+�nR4�7-l���� ���c]��gn�9�Ope�?����\�lz���o��<�V}�,r�J��@��fˌzg�a%���dT�L�u�\=��=2M,��0U3t�A���~t��&�P�ҥ����=�i%1��[ju:�6�˒�>7�����}��E 3�����Uk.x/B�;�pA�-6�٢�����m�v� !�~���$^���t%Is�p9����� Ɉ���k֦t���?l,�c%�X��&�O��ꣶ�����{g�'|5���TD�x��P;H/b��ɾ3���6��P��1��&�d�@T�xVz����묳_&I��0$B��_�ߓ���ow�B� _,�~�ea�y+1M
+S�F��w�w����
+��{����qMr���0&.�MZ
+��EZ��>G��RAk� ύE���Vu�o�����p]ݼ�1��zun�-��R=���A7ό@�����ȍ K�t�s��g�ZQiJ�#��D�fN~=����-�Z|`��^��d�L�꺿����x����,�D�彁DQ��e;Y�g&
+ǦQ����-bf�9�UK�tYЩ1j��[-��:҈
+h���S�Qߒ���O×<(I� ��h���;M�0%Ƌ�EBz�g��*�H٪l��$��j���1��@�Xn�a(Ϲ��
+�����j��˿�����{�e�ԗS��<��e���5���Ӝ#K_��5��Wgˮ�%B�L�G8Գ/�f��vt��Q�e5b1�oZG�p��0���k���薯S�|lt˵s�?�'����P��O(���lT���,���?�1s�.c^"�nn�c����_ �������:vTKfa^�hY��J4�[�M��|  �?�S��XI�� >9���>��:jO�]P&�T�]����s�bv��S���zY��л����aU���.�r���c[k�ke�[�.� ��zv����uA�V�n�t"oS��^�^V�Jc�Zj8�c�ϱ����"
+�?2`=%!�pb��?\sq�A�-{^�ߒ�6��:�3$�1��<�8|��Aa�/�ˠ�[�Ť�x�D����<���Y�i�H�9��dTj"�4,�(�_ [�S����� �d�6�>�3�}A���RЪ%��@09�����̚抩wl��f��oZ4
+ێ
+�; ��.L��mɈևvÎ[<ǐ�,vY|]7_ B� T&�n��B��E�o��BR!�];"b�V5Q`l���&^4I�w�3��k�|@��2�_]��kFI���������m��tT@��1��&E�A�˅��D����[Kb�龠�|� 5љ
+k�/?��)��n��7��Qr~�5�g>�\յ��K;�\�v&�3 ::-z��Y$�����w�Z�D��6W��M�U�Z;MӪV^�3.ҫe���[m�h�ĭ�W�]�M5�
+01U�r䂁�:���B�i���]ݿN��g�2��y-��j;�şCx��ї��q� %P��o/�?T)6��K���q��U7:�(D��q�g���K~t��C���ൃ� @�W?PHwY�.���>�,2ߛ��t�SN'����h�H��"R����9e$�e=H����B�h���bz��Z� Ͻ�d&g{� �x$��э��ثԏa/�n ���y�-��X��X?*fl��tc?̿ �Y^I!D,Pp�O܂I�R��D�G=D����� ��7�Y�F�"*�p?)�L�� ��U�`�gd�y��g.��wM$���ZTx�Eh&Ao��
+�����#�v좔C��M�'��"�L4#F Q2�9��7C@�.�U���ҁ/�����yz8Z���=��*��+x�2瘗vL���
+ �A���D�0�F�K�8�$�V�?Cf��˦h��ޓ��M�x���k�!���%�oD~l�3��*����9-[���N\\{2@���Sڴv"D�����'�����f?2����UUkG�Q���Ⱥu;���h�s��KK�����Փb^�����w �v�%����f�kk�ɱ^����-[x+����E\�D�O蠼��.�)("�|�_��g|���<��=���&������o�L+�I� /�9�����oj-��Pېx�>zZ�y��@3X��K���9�����l~;�_����!������ ��������-��!�cT+�ԘY���O4����wKdQج�DUؕ���r�w,�� 0������������8�,cʒ�;D;C��\� /�^g���EvRP2.=����O�d���q��kMo��v0t�s��q�Ky/H��O1��,հ�zd������Y��oI&��m�v,jAsy>�˗zD�=[�N��G���L�!T�C��i6ς:�.Re�I�~R��ߢ2����mư���9�k\v����ֺ�Ǥ���#;�k�ٓ׽>�ɓ%�UǶ��:�$4sFfnٝ%X� �Е�9=(q~ª�sOe�腲GYeQ�`�=U܄zy��L�ԅ��V�JňY1 �C���V|i���$���]h�*�'�@i�-QUĞ:��C &�ӷj$D�ph/\�����8E�b�������o��]�4�}�SQz�!��d��Q5��'�y\��ÿ F��e<�Hf"�]�.�C�]�w�i2��7�'���aS�y�A��Y�潳ٙ��}߆����Ն��Ƕ5�~�����!ys�\��0�ήx���AZ4� u8�uO$n�B����g��X"��'`:�RG�4�P����ND�@},�������H��[���מnkP�+�6wA�����+��,�\�iԘ�J�,���D��� A�\�^XR��n��3F��,H@�$���S��*����]���4�-���se �����A��a��7�"˳w�Dμ��8k#��>������+���*�b �o�8A"��j����@�@IH�q�L9&V�D�dDƯ!����G��~l�N�0x7iv� Z�+^�� E���r�kp��ݍ��6���)A+�
+D#;���b�i�1��\zf��B�%��2[���"�Yn���!��!Z!T*�x���Z�&ʝ,
+&fxB����)�fI����L}��%'�껳f���VNy��������y&,�b��."%�Ōmme�G�t���'��G��K��t�Oۊ7�O���%KMQ쥔p����*-�<P!���)r�Ko� D��.���Ş#�Dz�j�/ p���E��c��o��+oC��F��&����]x�2aEְ�z` �j�k�*4"a<�N��c%|��H�`���U���h�&:��n� B`�h��9��i� ��s�1��b�Ie\t���r�"{��J�@�`-�_��Ii�Q�� �Ӭk���l����,��Em�e�r5G� (N⥷t#���m�D��1�P��h�VgU�K��Ĥ�[:���V� %fٍ��{��CZ�̽��-�<[�uss�E9xA�Z�cnk@�� �N��KŸ�v�:�u���U��n�Q|͔o���k]M��pX��9�0ӗ�ps���n������#|��xY(?���������}*R�`N�#����,R�XP���s�bu�̸�������ĭm���C5������ɐ��%{��n�i���W��6�P��V8��y홠g;ѹ _K�'�y�.��8=O�sW�ӷ�#�X�"���>�5��t{��3�T�?�ꠥ��J\�+�3�(�>~(
+Н �pa��Z�ӄ ��nj�8 t�fWy����s�z5����C ���6%��u����uɦ(� SuV��):t<��K�̒n'/��x���6/�Uc���7o*Q�Ȋ���pD`X��7��JP����
+�v�Fč�����&6�)\�Ftuኊ�Q� �֚O�tjd�<6�&��1ݓqT�х%~�XЋ���_��/�.��o-��A�r�c�)M �)6^�9�Ez�xҥz���|BFP�VX��fύic�l'C� ^��.Y"w6��>���(����pU�R��P�cnV������^Z 7QD��b�R|{���#�p������kv�孏,��V���@�̐;^�dž���*��?s��i����8"p�'�>�<�bV������x��nA��J�"F����pxT�'�_Z���7���-�bhu���h�Leg �~��h�W4��k��˦]�/��xp ��������0��Y�W,��S��M{`X�*�;���[�d'Y=�������ZsW����I2�C�{�J����o�`v0�ϱP�� ��7�3�ϤVon�s'�B����Ж�Yȡ2�> Y4�)�В��iC���n#s3?�R/�ᣒ�*A{A�B�%
+����I�s�zp�!�̽�ԑ�1e% ��]7��%ЉO?�R�Y���"D��\���V���%���7���������|r��J�e���q�v`�TgK��q$�ۡ�����Q��=�++W0���7eힷ�B6����T�_��R_#�=�)#������B��D7h?(��e�a��Y��S�#�=�|�`��Ͽ��m���&-L�~�� >ĒK�ǟ�`&���|��P<�}s�M��k`� �fc���C����B���W̐��S�!!9�<�
+7��\���,�m:W�M �JN?
+���M�oֲ���}遊9̞����蒜h�n�5�3}�+Bb���H&_�ѕRc���?��Y돚3d���<���/$[t|��*�v�u���v��6E�ڋq~4����ъ0l�8�<\�B^�hp��A��I^|��RJ&m��LC�E�D�1�q\j�Iڼ�g�(|_�#�j�M��[���Ħ��嗳֬��OV�g�߳z�@�B���D�f����C��b���OH�#0WhCi\��9ؘ۞;�o@K�l��Y��L�����A��;�qW?W4'$��rbe��+��H�� ��1�(�0������2fa��u'_u/=Y��q����;q��U���������������7v��j��?��~� �ڽ��#4�N�Z̠;s ��(,Z<���a��U��$�l�9@����]%�d��_鷩Fʅ��v��-b[4�ڑ��,ؙ�i>W+��1�"��{��b�eo��"�)�����'�3�fu�k����
+��8�?�o�����ןҏX����N��#
+qa�?�wI��t,F��!��\��n���Rw�ؤ]I�?%Su��_p�^�$P���iK(�ȏy�\����E�J��# ��y�����lW�d����P�|��)����=Is �_�'���7W�0n1�"*�q;C���"P�X[���Bèv�j�z8`u� �m�I � �v�h�Ra���������f�c˴����ڛ_��
+p�5E�c��a�3O��b�;`���[*�nl�Q
+����{/��Y>��Hx��s���M��o7j�qq
+�+�[|�ytyR�����&p;������~�M����us�'C5t2���o?��0d}�* W�4+����ou�/t!��G�s_��3`��Jc�-#j��BT����G�l�H�z����(
+��G�&��SS"����@'a'H^��b�y����'7vs�w�Pא�����Gke�njJ�_�ep%o<��,6����9�3�!>���*z�� ��M��1+������?��'��z:�`H���U�P�b��r�X�6γ6��6�^ �>k��Pۢ\ܟO1�;g9�yD��XA2Ը��������G����|3v��d����(�h;7�?nC�7<C���JF���Y�v�+Sk@#4��l��1J��"�ZY� �L�wi�`�/}CCe��;p��������<: 7���e�o��z}X>��E(�<
+U7<�^(�lB�t�
+i��XB��S� s'T�$]#Qpv�F�X&e�� h���P+�;n�$��Z2� R!����q�?���zo��ONS  .P��K��@5���jخDר>�{�`0�R1[Т�£o�ZW(!�6�����Q=�Y���T3R��F�i�F��T��9{�&s>v�S�͚���T�! T�������*���{bt�fa۰�AOƍo���A�U�M��|�?�
+>���7 Ј\�-BZE��ŕ�0c�o!a�L�x�)�#���J��F�]!����|%a�BvO]B�;*/t$�c!��-^C]3��I�J�} �#u���=����غ�"�PX1kY��뚻>j>�%!y�Ҷ�L�-���(�x��u�r�/�E��v l]�i�#��@%r|���4����/7��isx:{v�KJo��.��>'%��üU� ;�ȦZ�����
+���=t$��C&8�ˠ~�I���0O���H���]x�����X%���%����J6�ŽV0�25év!bP�lIF��)�rj8����_a ˛��K�������/�V�g��a�)b$Hu<�����q�v=���Ɂ� "BG/Sf�M1���G-��� �C%)��Q}b�Q���Q��t��y��G�7u�t�ʍ�Ӹ�w�x�Z�p}.Yf/l����R�)�k�KO^��#���һ��5�`�I@�d��x`1r��י�I0�8Q������&O��{$
+�K�:�o@��6ŭ��@�i��3m�X�B�4x��ڊ)���}�~�/::����|�&�ĖB�� ������W[<�𺵛bJE�b7}�򟩋+��g�m��o�����#I�e�+��
+�t
+k$�f_ )�L��ERU��7*\��i��( ��^V��F7���X2;�c2�ƪg�v<���.�lP�E�˰YV'��w�.X� B@����
+�-�!+|��� ��
+�ko �m#y�U����#UmL
+5;�V�Ԏ�*��Zb��_���J��/�˞n�N.8���Yb5ʬ��t4C��쬕 �V^��g��?��h�o6���� ��ܦ+�j_�;�>ʴO�J�,MD���Rx2\�D����Z��]W����w�������SS�\m�A��Ujw����L#l�8�� ��.���s�tw��9',6������iX�C��{��%)ǕL]�й��k���s[w/t^)Z" ���ၠ�X� ��Q?Q6E�M���� 1���q�'r>���J�՜�S @ wH�z�t��Ӄ�y��wР
+��CJE��z��,���Mv ������d�C���p+O�������4�+�7� �T�%V|�mSg7���»ާE��fqV6���^��Ћ�� i[��Ӈ~��XG�����g�WoշZj@�[3�6v��ty�VbG��j��BBRI� �� <��x%n�o[�R���V߬Ÿ���cҕg'!�x`�{�G� �7�9�m/��Ƚ�������/Xj���Ť���Dve���`�j���{S�@�H�b߱y�mA��P7�p��yT a3���^ެ>��B��*Vr�GY ������ʎ
+��C)�C%XtcDr�p�V�4e�7+�'Pΐr��@(��$��zO�~g"c�B�����-�+'������(!n�L��Z*��w)�.��ܨuͥ�1���d������$�����*�B�9���{?�>���&��dk/�ʀ >.h�� �Ok{o�VLLt���ö��r)�.���wm��d�Lk'��� �c�� PeAqo"h��Pc�!�N��'����' ���j���E��7�kj�}py�@y�>�<ɬ+�)_nC}�v��1ְ���v���]<�`��ŗ�`�G����t��u�ѭ F��)��a�����'�գ����˼��f��8Tmg�0skW�����)��^\��0l�<v8:Z�T��l��5=�mc-~�.~�N����(�9��f Tfq�� �LK��6_�d�Σâ1��{-��?����&L��=p�R�J�)9�Օ�ѹ�)�Ǫ^0���H�B�A�?�x9in#�����3�Z ;A;g�O?h��MV˥7��ǺR�ZT�UA��ЇzD""� m"�A'�ŋ |ͥn�K�B�\<ѡN.of�E��`ӎ���R`k7�n���ԍ��,ڕmS�"
+LjD�����cC�� ���us�э�{ *�3[��8j�_e��h�6z4$u���n����7��4���Бc.��2U�з)����o툳�@��*Q��VCRl���Z��Ø�{[�Н��R�Tz�4�b,B��g�\�L�}J���C|��#�K�$�Y���eI����$ɗ׬��$�r O���d��_�X�D��d[����7 \����A#��m4��������[�l�k��m<�I|�1����޸�b�,���9�����-M��|����X��\��w�Z}�H �1�Uy�,~�'��]�r�_��G��\47�fۃ�o�5 ��E�nP~�44a�M��>�z+���,��5)�5jIw}����ܷ2S,I����c�9%0���,�&}��Gds�%�v�e�1WϽԻrr��4���d�/���&'[��Z�{��@+(F���.� �oW<t�p0����<�" B�P����.NA�ݝ;������}�l�� ����EQ=o5����ӹ �Tz�;Ÿ5���(&s~�u��8�����6�:G�� 6�q�#�f��������-���ȑ#`x:��ݰB%��D�X'@ )��%ac�.[lT����������� 0!�ڙ3xWS��@�v�bM̝����B���Xj0·��%9U���㠃��bw�5���'�6�`�j��2����S�xFƞJk���I���D�꽺��%�|8�#�t�l�8���3�23k����I���e��p� �a��$���Տ�f���8�����i*,���5SIjx�fP��5��M�+k�3=}�kb���5��Tw�!I��jm��,r ���1��q���J� ��� ���s!���x�z��ipc��D���{&�EY0{��B&f�w�A�GH�a/��I�"�W�+�q��]9�[��o(+�"�����?#�2J؟��[I;�Oj���z#��E���S�R���� �-�ă��djJ�a�\Ǥ�.��U�!|������=5���n�v������zhC���*�o����4Ь�P��[3L��n�����M����9�ejPI�!�ԖQt���� ,K��1� 246pLgl���ܚ��'H�ן���O*�41m�$7~
+�.3�(:�Wwx�; r�+\�0<�G��[βm���I�׍m_��>j٠����ϕ� {(�r���/�[Yl�܎4�}<�b�v��u����v�?y/v��D!���Q]dH����5t��� ��P�;sJ��9T�'.-2^����ѓc��)�3�~I��\�.sk O^��C��*�S��ѩ(�ts_-�8g{�굓R���>��� �T�u���>5NP�������51`�C�7����$�J��!8�g ��V�Ul*<����߾����D�gE !x0�Lo�l�� @8� m����j��mj� q����G�����-�:���>�lQ��m�p+�l�< %��^��ء�1'f�0n !4e�=��d9�lׇ�R�?l ?A7!YT��2���)>�{�%��~�/��䚸p:�6��)���iQ�N�K�(���{�3�7 �z]��iV]dҢ�v�n�W&<"" ��9>�O�(�5o+���ye\�8�Rf,�����"/t�S)��(��kD�N��w~��m5 �ɝ�lg#�;ek�?����t�8 �\�n؃�;��L�
+�ED�B��°��V�D� QVx�ی;j>W��
+<�zqj����J�g$9�Έ���(�e��:���:�C�k�$O"�x�bm$�aP��lgD�J�k�V/���m`��p���*
+E�;/���+��,5 ��j*
+>^����X��ɾ/7��g��K��h���S(4�����<��2'� �G@I���yhӠ� U�����m��V�}ZA��b���1��^�^��0�{�e�6��MC1D� ��b��$]"Gw�f+aY�U��֊��p䙳:������$�<���K:��hL\M�*��n���8���B}�r��,��BXC b���L���d�ƫ���U����֔|������q��R��&v�($���w��\�?ݻ6pA�"��k��ȖD9�5
+���wx��-']����=��g��jf��W"��O8#��E�Zy�>�~��(�)��!���� �b�0X �4^��!��B���m�J��$wU[��*����b�ˑT�=�w
+�ƃ,I׀Y�$�_(��c��� ���;�$�G cV�����{��%T1��öwg�.qy�]�<��0ξ���ݦ �/����hs�U��uN�_!�k� ���;�0�A��!��k�Ǩ~燶�G�K�.rC����+�ꇌ�U��;� R�P�w�nL����॔�8�����2+2At����<]��d#D�-�R{>8rn�����`�%�fuVx ���#*Y��ȳ#}@&�?�I_��8�L�s�4�ڣjY��G[�~P�: ���*]eo �F|um��/{ M�"˚(l�r_p��gf'��n��s��YѪ���ΤB��hQ �İ�]?��l'@�.{�� ������b�)2�?�P���nj��M.eW���Qq]gXu�`��2��/���o�=�ͱ��2H���h�J�� �&M{6��)�М�x_�f&����|U�[X����7�W�C%k|
+�.F��lS{vq*S�+%��M3���֖�S��Ӽ�_�!�)9$ ����1�c�-���`��n��]� f�C��G��D�_�0�J��c���!ۏ��C�Ӑ+���-�|�,��LV�`j�$iTD�D��^��n=Q�'�+e��˥͊�'��t�u�
+̾nh�d��{/t�-G�E��E�o�6F%V��}��Iz�%�� 4n)\6Uk��RI�
+�Hk�ݔ����:ֳ`�����d�� A]�(Nt����Y-q���` M}N�;����4�mY� ,i˘YY%?x$����\�I�!/�3�_�W�Ǐ�Ҥ1�!cC��C�*e�?�k�z��{�X�ę�1M�eC|X@���f �~�λ
+��u�}��/M-�2�G��Ӂ� �p7�iV������7n}n2:��3�裭��޽.�qܽ#L'�(s2nN�e۶W ��@��3�ǎ���y1�ʛ��R�/�b��YP^�jHQ
+��Ӕ�}8������o����N���'��
+���O�j4#!���mxx���{���WE������E]�d�w7�x�H]�@ ��î��Z�KuT�����B]:��P�T�%eHy�w�EC=�<�L�N��b��#e�6FaJ�nv��:ߩ";D)�4>��I��mav8�+k���wE�8��D�-��;��xF��'3�b�R�i&2��ɨ.�SH�ʿ�<<ܩ}";���m�Q��yC2��}9��Rk�!�R���w�o���Cnw0:�h0'��k,�v�%m����|��Z:h��<��Պ�d�=6 �O-{S1�<}��F����n�7�w���mZ�7"DcF�d��3k���DjPd9�OxAG~�^�Z��n� _�w�v��=$�q,�$�$
+��[r��j�>hE�� �S+U݌<
+��t�'d��pCϤ�ƣ���k���s��a�
+t�W R����d .��ʽ.r�_������Q�����E�'G������^�>v���2� ��4$2^����� ]D>�X%2���^�?�3Ź>��X��y��!��W�Ϩ� s�chG� ����E4y���B�͑-�ErI�F{\�ܲ]����ʧ{�5�\�VA
+�.4;�*�?YjY��:ʅ`t�������ݯ i`�����K�t)]'-B�'�Ӆj� ��3l~濸��<J���N/柵�I�v"!꾷��b��'���ւTR������_�Q���슍�d_/�ƀqV��uo �}mUrRkR�8yd)����ݥ�P�����}Ƨ���a;zw �e�¯mN�i�P�'����F��V75ZC�Jb0�P
+(�o�� Q.Nb�*rs0p�e~�Μ��R�j��g��ր�e=�-$�BL�����o�����.8�[���R ���^X�I)�7q��0O��C���K�,��g^�b��ĩ����iY��5e�����A�<�8�JBD��|/��,���"���&x�Y��m|,y6XX ��0,�B�K��7 �D�g����(��%�$朼~u�A=8��LO\i �{�b�& �4S�!����<{�y^�Z6�j�RN�j��Ӛ�X��Rn�s�j���Il͂� �/�+(0 ����ڷqI>�{�CS���wI% 4�dC�aC?%�{%������T�C�e˪F5��ى� �Ɖ9L<�>R��#��t,�t\�?-����4YA��E�(�s��a\ש[��
+��^���,H�K)<̐ʪC=�$��X �*�k��������i}cn� a��V>��E�,3��-�spCX����e������~*��1hGc���u���Ir�d���5!�����t��&>�V���IĬ=%jd�W��k'�}P�m�S{�M40� hD|�<���0l�w��aE<(�f�p5qPwz �(p���0\7�fٰ��B7�����nox�$;J�.���m��,� 6�����.��}�]�^9�6���3��}��m+X�����]ΐ����'xF�-&~>�3W�L�������a}����M��ēg�\7j~�Ee*���� l'�|t�� LY����on���a;�޷E�FX��r�B�{x�Sk}�69#,�D,)�.N��Sk�o\���\e���b�s$�2ޓ�Uk�"�|6[ȍ�0���3nG]v��Ϋ �7.�!��~W�΂�m>�f_x3[�t ��~}&���e��b�(�j����,��ɐYF�1���Mȸ����+x�L늞˂86�ۤ�-��k�r+�{� ����H�^�e.A6��߉�[��X�~ftC�dy�/���jw
+F�]@�+�In��isD@PU:!Z~q���\J|\ͲX<a�Y{����&�G�q��Sru�.*'n��'�{D���Ь� ���t!�t�XW�TH�S�ͼ��D�@&�����z˄��Ϩ��&���y-KM��6���;I��P{����{ �,�oT(ۛ��#�<�����_���ߵ�4�L#7Z]��ލ_��"������k�sw�P����IW���1ܹf~��n�2!�]} ��f+�0�h�j�};��&^���*+�|De��\Α�� !b� �G쮋�8Ӯe�>G�|�XW�k�(70�er8+���3��\����S�D����>j���|���Ѣ e;�� p��4� ��AH�C�ri!v����)�]��WA�8dT��T��a�������Af�ȃ���@�:P�l����]V��G �VK�Ba�8�aSW���sbE^��O��/|`��zS��`��S�7��9�vb}�XY�vs�N3�0@�Q���72L��`��z�2Q��s����jx+}&��6�In6��R �(��K'5Qp@-б�x����k��fb�>��9N"�i���QM��ꜜW�j p�Ĭ�ؤ�Y3k���潵��Y�K��c�Jq�M�q��p,��fvi�F�uL��5@M,5}MA�tŎ86N J���n<
+pnߎ��ŬMϳh����(��i����2 ��R��^(�َ �q'7�:i��6�>B��ҔsS��<}����zj��Ɯ����e��ֈk`�
+�:7 �xVu4��BY�5���qA� #V��b2����_����j_�٪�2>�GDť����)��OSupO�< @i�n/�����k�a������z%� ���f�k0I/���jCm�͐ �u����*JWr����0��c �� @�r{�.=�d⑄�1|��D��&6�ǂ���J�gWZ�V~F^�'~W�0?UE'@z���l�{�ջ�E�Ug嘬h�
+��pS�a�[�&θ�@�� 7�}�)��s�TQˀ����+��4oC u�����C�z�g��Jd�}` �YB�΢���q��q��R�q5,䊯�f�i?Q��M{��Y:�ͪ�t�a���F��|~nCP�n�a8���U�`�}m��,�!K���$���"�����W�f�o<��d'X-�5�}�뻳39ͬĠ�b�����x�u,�L�C���5kXsuIц̺����t>�m���M���qA�GYCI��#�VZ�r����L�H6.֗��"$]N$��Ș����Ђ �V'��pu�e�V�>>A5�rWV~�7wT��*uEۛu��=��U����1M@�I����F� �5���=)[B��X@,g*���v4�t�C5{9W�H~b�����t��;30�6W��ƕ]ǷKI2�>z)��ȳ�� ߾v�b�I�!��l��`#�<F]���u�}���_�EjR�Y�I��A����)�m^��l���`�& ��O*)�O��~��� ���ݛf���Xc����J
+�W��)���ᜦ
+��fE���@�^�񟏗ta�8n$Ν)/�v,����� �#��-���.�n�&�q=V��2�l��?����\P�k.�.���T���y�k<��R�VF� ��B[č���:�� ���!�Lb<P�������\?7��>�f]�dN�ǥn(C�� �Z�՞�����Fuo5�Ǩ4�1�3�7�U�aV�`��������A,��ǝ� 1=�{�F�:�"Dt�OS�ܖ0�0i�vT���Nj'b���LU�`�No؏ф_�W��j�xKƸ$'�%�Q����&�A�o
+endstream
+endobj
+598 0 obj
+<< /Filter /FlateDecode /Length1 1748 /Length2 102745 /Length3 0 /Length 102950 >>
+stream
+xڤ�Pݶ5��Kpظ������Xp�w����� ���!�����;�Թ���nݿ�jV�Zc�s̮nJRuFQ��H��ޕ�����`m�`mrv��i8�ؙX()5�]mA�e�R ��b�`��/��3���ϊ������=@����`c�c��ce�s���O��3@�� ���ٻ"P�;8z9[[Z������d3/�������#@� ��`k��xeG�=�S�� �?1��\�?Pk{K��3Pw�p�0u� m�w���Gi�4��lj Pq3��6�'��a�j�'��@�� ǿ
+0����#Ϳ���/��>=�����-A+WWG>f�RX����b�dr��g�?����������r�m����[��-�_���?�������>�qԿj�C�+� �����ߖ���&JI{����ݟֹ �����3���=�_�4�AVd�gESWgkO�>  +���_w�:��z��dj0KȨ)�����*��s�|ade�a0�qr�X�Y��l�����bj��V��owY{ �?
+�9��x��@�i�I���OS4���!�/̿��ң '���$������o��C�y1�����_N�M��r�������0J�?����_�3����ߑ�G�n����!=���Q)S;k[��!X��{@#������ɺ��aJ����_�c�"e� �X���!����uͿ�b�'������2����- +k��� �?������%����R��O L���Z�k�������������g �?��@� s��Es�`�����ZQƃ �â``��NS��[M�#D]L�g����U1�8�<O��KN���x�n��9 Ap�6��E��C K2'�o�Г��
+�u� �%ˆ>��|�����`�d���_G�tW�Dz�
+���X��xA-(���u���ÜMZ��P^�CAΦL:��ls�#s�q��X-� �߼<�l��[&wa=�>R[��l�F���6_O�;������j[%;�T����3L<����f�2��uOz���'�Q�#����y[dI2Jz�p��쁪YYv���K�L^Hm��:%�cX��(�����T'KL�CA�ެ��@ʽ�� +5��>a�3�����㹥tQ^��阋@ܤk?&*�4�~Ҧ��>Im�=�'�F��A�r�����e7�Ix<L�k�g - �VVhU�N�Eu�2��@ɱݬU���8�H�d�ڷTޫ� &�����=%"��/9G ��<l�}��.��,�]I�6�Q���F��mO*�a���L&R��&�������W&��S�y�Ygw�41UH�T ��D���O�|��J����7�;C��� 勽L�lF_M�����jh�t�I7�����܆� r�CR�H��B+Ey���(i�t' �i �5��s7�D/m���%vO��E�<�J����Q�Y\��,��?�q�h������Hk�|�7sC��:�>Y,�f��A�o��̱�dX7O쿛�Y�{�m%��
+�]9�!*�[0��!쨉�dU��(�z�g�g
+
+,]�⌖�Եd>����P��ːǗ����Z*//�#�_-X6/E1�'��ߋ���6�Q��\6�Ç�� R�Fh!��I7��.�ZYB���mτе̇� �Ծ��*k��?�V�d`� �$�r�o�e�������N9B�6;5B*A�n�條�Vv���.!�Tf����0B�ͧ�1Rp��y/By7�x���t�!��3Σ$b�����DJ�zJ{<�*�nGe�����%�a"pJ=�`�4��`:Nv�7�VYQ,�}$pX�q�m�3e�W�aB����w�p%7�������z9/I�
+~�����o❆�q��x��g�_��u�">��6��NK���˿��<����/40���̠���a�ʼ�]XVN���Wv�:�4B|2���z$�H]���S/��lj��z�5-�FG�������ޏ�Eư
+������qS���L��ݓyo;W�Y�[��y��
+�S4LE�ԇgBg���_���������{F��]���'-�������g���BT�e���K`p��ZWu� a��J��1Z���#h�lPQ%�O&�%[����g�V�_��E�����({ɤ�'w Qkj5]�< Y?���i�.���(x�
+U��0z<�N莝
+-h�٪�K/p� L�H��mۓ��V9gTr�v��GT�A�_���Vk�~P�]�Nda�T�Qb��(��PL���ZKU���c����ڳ��iu;�^������_ 6�ݹ[EnP`�a�P����� zA�׹�W��=T�Q�
+�DM���쑒�n��T��11N��0@U�s��k?n���x�,hFgd�U9�"ٟ����n� mh��38��3Z+1�W\��t�(0�^�r���7F�I_���� ,aQ�jU'ϝ�@�0���iP�ҕn�x��O\�w�6�� .[���:o�Jl'�a�Ꜻ]��+�*�u.��S�"~F� �Ԙs�yd�%�����iE첳� ��A󄒶s�)�B���&Ef§[�S8&n�w�M�M+�^�|�
+
+��fͬ��k9?< nG}�xs0%�1� f��Lٸ�pg�ۖE���jw �� �,t��:Xok.�|GD��,�^��������:��w~�����
+�y��Y�b�{��6T�����,�P���+�B[�@g}φ�4�Q�A�y�_h�֜��qu6�(vF����P�fIL�b��R�g��6�m��Z���&7�p�t{c'>P�+3īܹ̋�$�P�?�� �O��~{V\t"7��tZ��J�c�f���Œ�Dړǝ���$�8R���Z�F6 =�������&U����d� �$j\v*��4�m��������H��Y5��aX� �pc�&N^�|.:�߶(���ْy9&��g���$��U2�������yV�)u*~�*������� �bqm�dQjv�0���z�.\�-���m�1��X�)O��;*�C�!"��F?��k-�a���hxĐ�k�BQ>���?%ɍk�OP�<7�E��-R��
+֞�>���wt��əl��a�$[�>G���0 > �[�v��p�>���P��/<�w��q*���&��I��P�W�p�$R�=ߕ��k�6����p,��# ��أO�|p+�>��R�������0���edb�9Ja�Yͪ��9��W��Յ0�x���2�Σ6B_֊�[$2�r7�ӑ��\?n%Tw�d�X~Uh��Yw%���4��EPc� e�[L�@ �^�w#��)Hg����l��Y�r�;���>���Dt��Γp���&�r�s\N��}U��\Q�O����A9���R}�@Q9�!���S���K������WAT��5%_�i��eR/oaB��3��a0�4" �`[�M�^�ğ�;CK�k�WyPcy�����z�l��q[{��{���=��ķ����<�r9 ��>7l�9W�]�Ap �Rf�lvB�I�����œ��lСϏ����.�y��1o�\ψ��!� �<��JSx���<�1+��R+7u8����*Λ:�K"�^fr�#��2j�%~�;���TZ��`����2��O:����yo�c02�}L?(��ڤeڂ�{������ZN�)>��^�OcĿ�s�� ��k
+�&� K�y�wYj�jN-�xCl[����v�_�\BtW�@�(o��Ŝ���|(�����|���Əm���g��� �T|Ӑ6^ 6P6H!�_1�
+�%�R�i���+t��j(�'ѷЁA_�f��"!�_�aʲ�hN���s����,3cM�H ��=p6�f��v��Ah��f�9S�h_�/�/�9T1��*���r �4��0Հ^Q��=�� �����z��l�}X��u��m�%��#Ӄ ��T��jw;�͕Ԋ��$�d�T��QS���������3ɵ�32��1�� ���ջ� �s&'�#2u�^��]������&�Z�X��?Aȴjԁ�=0x�UG���;��u
+��̫���y��ؓƘ�<;>Q�-����y?���H]X�����o&�4��⸾a�Oȫ@��8V��C�6�b ��Y�a�+oP(��ތ�]O�#0��˛l�H�;��á�J����%�!Q�����4�l��ٿ>��OB�EK��V+7*5f�t�ij{i���C9��6Rd�!��nWJ�ك�"T�\��B�_��9�:�U���pM!Y��0�9c]��S��������^i�H�(+���e�1uLS>}�/�q�y��[r����Y|�Ə��~b�}�m�o�ϰ����6E#������~#%!qަ�x"B����}��%�� �d��w^� B�W������)h$��ql.���;q�x��_�^z@2���~�u��/7�jK�}�|h�y���f�We���zH'��4�l�~A;S �/���x�#v��E�^��ui�`�b 4|�׷��ڣت��i���a��$����8.��V�ع;;s|U�JB�[þT�� Y����C���r� (ަ0V}7ۡ��ºZ��3[
+���_0��v�y k7�G&��L������~�ktm쨺�B�1Z���ۮ}�n���Flj��΁�X�4 yZ1����hH��ݼ�ތ�j<|w$���LG �� ���d�
+f|�J6�@�׉�4Rշ�8d�؊(� �{Ca�=�y�������O�����Ȕ�bUE)
+�J}��d���Tv2��)q�@�^��\��=Y��"��.� �!.m��Z����7 �%�Ӣ#o� �_�0$�n�`rZ�i�����-AW�̜���N"�9n/g�51�J[Q �ӎ&>%��*U7g�ҝS�=� �S�������x�Ǵ^IۼۧA���/�6�(�$5l�x2�,�(m�Zg#�ڱ��+ \ N)UE-%��np"lHU��zV͓�|8
+2�ė7��i���-��b��B����U�Յ��n(2�OPs!�p��|�F������u�e��C 3xv�s�b[�*��_��\'ł3�)7����qwI8c���K��7���%�A�W�e���̏���A�<����^�0"K�4<�Ta��+2cQ������Ei�0/6�,�]��wsƷb�zt���ɀ|.@�@"�#��{��\Y��Aֻ��nV;z���"���"�Wkakx�IV�Y�>eD E!����/fȏ��4�V���;Y}� !q)�h��ք���ƽ"�C['N_��Ex��ԧ�2�4��#dG���\N7n>�T�� -��NG)Ei ��mc�)�/��~'����צ�\Y���.�)�ms�|�l�,�/?B�I�賱�p�te钙�mL⽍�"�]�&
+~���,RO�'��7Dn�5ٸ����5�r�;E�{ք%A��3���ʘl򈟻34̚��C�~}�q�+1�ɱJ�<�� ��Z�&\�"�d�e\�vt ������(��d��.io��z����9>4�ۺ�$�U�WZ�#0��e�8 dc:\}O@́?�p��-[���D�;-z�h�@9�ܾ�����pE1�a�`e��s3Jc#��ı~CI�tT���ĉ��a��DK�_��¶�1EQx�a �t�#���q�/���{>�m[�� k#�Ӓ8$ƻ���� ��<�*����Ҿ;{�
+��y���5�M5}�7��2��~�P�"��v�E��y�p��]�6���~��M���6���CQU���S�ݒ�ҐX�w�x��5�����N)2�2�W#nw�d1��\�ؑN2� � ��D� &`��pn���T��fz�>\�>V��'N ��r�=���7���%��v�,�k R5q.I'3��jHה�J���O���L��_�ͻi� �4�ν-c���|���Z�3�6�X�G�]��P��#f�|�� (��ac�c�⪌*
+V?c ���D�ks �3c�]_���,��8#������KT9���7e��R�k�k���m4ŽO���-ҕ}�W���~��]���"FL+^��&]��|_:�ɝ���Q���\s��ST��!R�ǿ^Œ��r�;���9{�a� �x{�w��h�5:����� V�>q�[�ot����C�^��c��cf�(�����*� Tq��(D�裢��5á�1�gI��gTE�G��f��|��5���$r�۷x+0�8��2�7X�c���Z5���F�nY�:�W ��-�Y(��
+X;�7�5�w����M�����$!hτ����#qM"T}_�ɛ���5߭�Ҟ4�v�����V^|?8��)Oy�-�[�J_��Z�\ ;ZV e�x |ٜ � ߓ&��k���Җ(�J�_���U�c[��}[�6_��ۋ��^��0�s%����Aޣ��~Y�ْ4�}E����6��$� �2*f�G���ı���Ka�}5 5qh�G1���6)�ܛ��ԛv]�q5�0C��ġIz���cÓ��N������Z~�zp{N�?�� zIVu|ٶ|�� E����>�(W�^�'�ug��������{
+��]*c� �u��$B_����8ށ�IEw�z�x?�����@���l��kB2�]����e�Bj���Ӥ��_���o�CaͿ^`WA_�-�$���^�������{"y���{\zD��n�8y8��E����*������_�pV�/����A ��AK=@�:"\��Џ��I���*�|��u�t����H!F����qc �5���β� �'X�Kǖ}� 1�/�`D��l� �b�_�V�0�#��4*��rz���ת�ލ�����3��k��6�FBH�S��]���y@}1aɓ��㗍����B�@�1���O�ҡ�!Bqz�m?�ҫ�7��c0��\�*�C�TF�`V}_#Ľ�
+&[�B-c��"��kQ��=W�@�$�|G.>*d�)���n�u��b�O]��s��nl�2��8$��u�V3�[&t���>F�G�8�o
+9-���ѼK1�6cv�8l,����o�܈�D�> �7@[�#,*b���&���ue������"i'�I)<�vd=��nc����q�c�����~D��6��`y��Y&���)jJl6�Ԇ������؅���9�QH�r��
+STVͳ:���TLξ^D]'.���~JL���W���g��ҋ��4����^�ŗ.�/���Tǻ��o��HH�Tk0"�+Au�k޿q-��� b6���Wh��q�;T��Yb�^��3�F��7� .��"3u�~^}^�,Q�=\���~8��qeLh";�(��7�W���ka�SΊf v������99}�\C�K������O���C�;�t��3��.�c_fW��w,�$�,�H =A_�g;���
+Y�$.�M��7����ڭ�@��4�H�6s��[�f�ڇ|1�.�7�/�l�5�.hP ��!g"��<��9�h/5�[<U���W1�T9�Ɓ�v]p��A;b��=��vE����&1`�NS7x��qY��R"�[e� ���ӛИ�r_3f��.$/;�m6�`�����tāĝ#�/^�ӗ��S�mA4��h ��SFݦ�dG��)�P<b ���.jgE�fEhJ3\��iP���i:�}�!_�Ўh)���Ǧ�MHV�Ӟm��4��~2 W
+[$s�2C8�y���[˰<$�8��Ys`�8ie�LU��H��=sYEB)RKQF��0��DV��+¶ �W��1u��">7����̵�{ɐ7����i�_K�f��N
+O��ǿ�O������v��6�~
+P@u&y��
+-���[dx/��(�u�~'V���C)�v�:�s{Zc��zw�1>yA�1$�з�;��vq��s�8����kD�U��7��b��P_U��Rw#%���{������(��^�Ŏķ!��*v���3C�f��<��t�v�G�%6�����﨡 ^s J��u|{49����Ngd��u����� /,��غ4��I:-l�5r]L0|�s:ۭ����sx��a�1٤�_��{E�}��>Rue�On���T���O������ى�(�o(���;6��ȸ�� \���
+�?�-L
+�Ъj[���� #��03���/-+�����>"L��w5gs+Q�ۇx�-2 `:m�-Hw��+K:�⢓�`���>Gj��!�O u;���/��Ӑ��m�CFRE���k�y��qU� :hK�'8+���G��r�+w^VW>�S�ۉ$�l���Ԕŕ��6QIh���i�E��r�Gߓ'��t�1���^S�h�"Ւ�Ӷ�*~eg��IY���D4}��!�ƒڹ�����N�%�ڃ�pl]�T�(oC��up�Ɗ����r63�ư��!����8�U*vhs/v�[�B֓�C��1�A��3#��j�Rৌ�1�A���c�� ���sΞ�2�>�-��v�6ن� ���"�2�����iY��O��%��Ԏ�l���"���[�X��V� ,�ҋ��ˤa��{�\F�c�Q �N�/��"�����=|B��<�;H���,�!π����� �օ:sx��ɨo/<���yBr4�w��g�~�E=O�e���KW�F<mqB�7��G�5̈́R��m�L�Y�H���&���,���`��$^�7V �2�j���Rޔ[�}�� �hZU��>8S�+�0�����"�� �����A��3,�ʨet*HӦ$R]|�pQ�ߔ���c� 5�NZi�l��:�5,��i����j�Pm��>�͊�U���J��Hu�Z"L]�z�'�5�D3�Hb��ae�T�p k^�����m�b�A4���QV���>�ڬR�$f��*夒2���S��s ���T�+�~S�WV� *��᳦�K��'���_����&�� ��_�H�K̆��[�5�Ѝ�t=}Q�3ף�vD��qp0)�O�����x�M�D:p�3�a���4����Y�ˠ�*Z����TN��݌J�q�pH��
+ެa�����8Y����3�5Ksʖx��g�P�L<=��N,A&=�e#J�@`�Ι�H���?<P�y�Gf_����S���I7�V�y���� +��$DŽ��nΤ��ƶ��s{�Z�\��&�r_�����܆�i���A��C�0�XWqSB�3�^D�g�Q�� ��������������*~��ڶ-<�Oj �C�ԀXS���|���k�8�˱̳ 8�պ �H��ڌ6D¤��y*�>g{C���OXj��x3���r~����eɞa��7�1�u�MA{�Ik�<zd��s;�����w�`�YmJ ����7]����f]X~�ج���'�9y�����Yݬ �W{P�+Iq�J��W:�%�ř$�`��X��&��}�1< I,#t$ؽ<[���j�i�|�(�]N��Py��(���� N��2�s���u�"N�_!W��s�)�0��T�p|-��{!:33/��Ƕ�o[o��{��E�Sa�2J�����N?W
+"ĺ����73�E�)~x��R��O��F�>��\ �o�y?��*e��q�L��EU?�D�� ��o���c/}r���]X �l�J�_���K�*��C��$�}눼�Vq3n���X4�}Jv�옪�D�5���mG6*�k�M�������'s�!Dm�/� ��tz� -�h/�ҪM�uW""�uQ&� �\�W�B���cZ�^�- �BJS��&�� ��`5�z$�ɩN4 }�ϑ0���3,x�F�A}G��7���C�QVE������a�Ua|��r��_z���(���g�<��b։��^����Um7��k0%���U�?�sY@Ч��6ӜJDJ��i�d����ff׹I^����.�����.㑫‰ E���m�?l���i �����0<��Ґ�4��s��=�le)���8+1Db1"�e��-Pc�N�����'C�[ '�D�А�u��~���>�a]9�|\o��_��2f3<��ll��>'��S �VIZ@J7Bo�r3�K�.*���p��D���~[-��g�#ޡ���8|����ͣ��鸚h 7jk5�]!00`���t�U�=N��D;�ep��@z�W���S��gSB8��X��Q�NJ0Q�0:��(\��#�j���K� #Yq��o�s���(�ݵ��汲G0� ۬�y�.D����4RL/Bh�S�i���{<3b��D�b�YO����[�B(���Pg���ڙ�z�i�c��.�U0���Z��;�\�K����G�,�~l�~���x��1����Eˋ�oy�VˬN����jtH�wq4�,t���T�TE �C�9�B�r���� �?&[ �U�y"���u�K�����"��M�~?}���+�r� - n�Q\�.������"�>
+›�ܻ���� e�e�ۗ4�� p1�$���HOY�:�H���=Z&�,Q�.�A���S6C�� ������ ���V\x�F�g���u�(��� m=��X���a�ߴ
+�u��+%_H�7
+c�G��WMN=��LϚ���)�}������s��φ�F-��,�"��ׅ��ˆ�?u>�J0�Zl��7^F�zG5���>�s9�?V�����Qup�8|X��:�!0O哻�
+74��X0��Vn:��:�۱�5�kn\���)�"��D�3�]N9x��>Q~@&p|�=�����,APF�����]�Fu�MKrm�ˌ�׈��,���}�Cǃb���t���٫[H7K �@�!h���
+� Mx�E���Dm=S�JO�~k��̚��'��"�׹����m�]R����m��rQ2Y��$���+9y�r5'g��;Lz}����i;�^`TaX'4���.f}މzV�{U�XP���`��[F�?v�Z[ {�
+w:��<�N�9�s����G3���@9L! �Ed���1��G�-�����#�P��p���`f��l;�pc�Q$��Ϙ�h�j�Ӕ夠e� �u;hn�/��ȣ�%6-��*[,���r6�t�]A�8 j�|>�R�ʟ��i��f��N m�萆8��J�Y�!�e�}��'E��(!��X-W�RQ����R�k�.(BhA+�@˥5 U&F��cHsk�A� ^��Q�@���ޛgU�˳����'#��L��A�{�c _5�*��v/�ʁX]���K��5:�ڒ?Q �s��@�l����l �'��������gW�(Z�[dm�=�����5Oģ�kUMI64��w]E:b��� ��%���b�Uh���]��3!�����;i$N�U�5^��Ԅ�G�ha�o_�H�`�s,S�[ �=D����0���rV�nj|��C�B-�ߦ=5�
+G5��'V�"�m��]ѭ*!�PC���+�C�+ I���5��h���y������_�c�����&������Sz�52O�i�RW���{�I� ���b�q�+�6�e��B'�.�T{]�Q��c�⊗T�F�>�c뤯�^w�v�D?�ϡ�Z�l-W�� VCC����w>�{n=P+�]�8rRw'�E�p[�*å ������Γ7�����o�{�D/��80J8Ð'�/�������Ul_��m�z���3.q��b��>oJ��h���*���t�)*1[���h{�_[���n �6�"�+6�ՙ�ܒ�*��j��_��-���l- ����E�g�=�)�G��V���G/���t%�Х�B����ʓ4'bYt2=7>�^�غ�&��bj����1��]���4�����>�G!ĥW�h�k�[�!7m,ݣr���<(q7$z����7�̀�wO���Y����k#�Q��7=Z ��`2�����VŰ1�3� Q��o�R�}L�;�Ɨ���#�ԟs��"�k4� ��0��wΩ�z]� �Sx���Y��?w�� ������g dR��ۖ�@·��_yw�
+^��x�"�s��L�5Z�V|��;/�[�>�\m^��<8,��+����bQsY��
+جX�e��x�a ��%�G?T�Yθ�LǺb:I���.Z%ww�>�ׂ]]bHo�%��o��.!��G��V(TC��|~�<���]��Sc�ہvh���4�m1�6��%�UXrg}\���+-Ȓ��h�$~M����-Rwe��Z"~�J��4�[���Ѝ\Ɓ%�Ńw��Af����Sa'�����8i\�Y?��_��3�5�]��G�kt�GT�=d����*1�&lѻ1�Uճ����`�,�Р��.y��MO��z����ZFFy�>5�LƳq���ߓ�:�f���'��Ҭ�Q��M�d��ww ˶9���7m3(S�������f�J �2
+�P'�z�M��'k�;WQ�r��*?�nG���#�or�j"3Frzb��%7L���y,e�Q/`��ͮ/a��-�|���Y�0,e�n:�X������f�Z�]Y�h�O���^%Ծ���;W؉��r�V�h�=ӕ�U�Y�Β�\�QqIv�ͬ�A������fl 2$�9����hF}8�:"�X��E"|~������ ��E;�IΦ5ש��~���tgd��]|��ØëeoK[���ɚ�PY:a8��K����ؓ���2�=b���d*�̓���]���%��T�#�U)�e���<��2,��p����M:6
+�NW9�͉�n�rZ
+����xB^� Irc��mBE��o���6W�Ү�p��b�Ђ%�m�����$����n �m�&��� `��gQ�2��&��է�SP˧͸�A��N����9Z|:�c@ydE���Z�T,$Cm��t�� a&gY������'��Ǜ{}��..o�2�� �$Ƿ�5Ci�1q����-Ȟ�#�ِ�;q��4�a���L\S#�� ōF����^��V��*2���I��苳���BU��<qH���5�r]�ù���>�y̘�����h��d$Vy�c��Ȁr&�6�7< ��D����}tLV�9;��ȑo$��t�.�^�Ӷ������5R��T���B[�܆_z�/��sW��%kב�d�Q�Ka�T\w����]�=;y�HPYկ�Y"_ƅ�G��2��_z��;-�=�|*/q�?~��� �3AD ���z���-�<����5k�� 򰾡[I �
+̪Q�~US���e���#�DRz~<����dJ��_�5�ϭNzƓ�#�j��sY�r�w���)��=��$����;��m�'�VU���B8�tFuz<�ک�������bĶ�A}��TW�wFe5onoX|A�y/c.�5g�>ċ^e��:��gX-�������r��M't���_��8M�����'F��^d�4�!�M���j�����k轎�k����3l�n5�z6���.���T�����/��k�����_��wG��<J�m#Hǘ�X�%}H�6�}�`������q���r�Q_>��4�֖v�E+qqVL#EW�f�Q��@�對COߡ�^~iش��*����Ҭ�B S0�@����y�ϛ֩�i}k���!��@�Ӳ����]�{!� �m7*j��&X�KlU�&�C&w��+r��� HS�h�@�d��<�g�Hm>��5��x��f������
+��5���P���7ܶ�ج���'�u���u�-ů�.T�!X����޾B�]��SN�Q�x}�ؗ�x�,0���������L����E��@�<���V�Ȟ}FLz����@t�/Y.���I���/�/�n��bgfks$��7*�ğ?��(}����tq��E9]��1�<��O;�k-�<{�oG�����`4� {$��j�Jd�:y�@���D��������f�B ك���q�T��i)���M����!�Fj~1���J��x���`,�d2�_{a���FvT�nb�A}w <T� u {�(<�&��I@W>��&~o��V��2�Z):�vn�M8�lFi�u�i��*�� |�.�SM*��۪���k� �DXJh �!��t��{B )<A�FĂ�΢Ц�� ؏���h�ǽ���P5pᮏ~���F� Kx"dj_����� �<����V��L�C:1.ECܶ�����qQh��W��[f'��¸����&6���w�P�XRZ���� �b?*� ��["2gC4��Y2��4����u>���糋I هZ4Dn�3��@ty�5ƅ�{[�@ySlQ� ��:�kD�-n��Q=��#P,�>��yb߭���Hl.�YL�W��g;b0xy�����y�d�Rږ݌����C2�
+�=���/��:\����c��O*�Ȳ���tڍ)/���'%�����vx#�9�C�k�� /���ԕ��b�1��z5t_��@�x+2/��2�)r���l6��ӵ� %9��Nl��� �W�����h� �<�2��a��|]��={2x���gQ;;�)�ne��K�P ��f��� �;KŦ @W����Bl� �6��Dnx�vWwo��7)uN��Ή�E�e�����}eM�?� NLB�>%���3x�؇B?�gx�vvs���#�C 2�h������y��}ɣY&��<!��Mݍ�7�d�a�l�Kp�]��:V��5�T_�� ��a�to�\5X P�����P ����L{�4�#Ymm��{N�UAb���Q4-��r0�I&� ��� Bxf�q�P�bN�c���# ��Ei |���r�����9Tr&y T�6Dy⮪��JW�"�h{qO�A`��1*;����G���.�Fi~�J0�B��k���&s-�+�E�/N��*�Y���f�vÛ��X*���˴kxN7
+�pC'a6��wZ�X�� �-��]S�}y��cЌ��4H7�ѓ�X�´ iy߂W&P<�R���m����l&5��k=�BU�W(Ka=9F�D/YKi��m�Eܯ �Г��p��d�����Ѥ"�<]��!:F��L��M7����); �|�s�;�Ţ�`��
+jĽ�.�� %�P���� ��?��U~��/l��"Wq�<�P�T��B**�l^�/V�&EqF#Ŕ�f���8��jz;թ^��y�C���H<M|�۾Ko@�v��Am�dҹC���7�`�ShzGM�R!�]_���+g�؆;)�Euk�^�H�Z"�T[���h�� ���X�\=���T�yk^�ќ�O6a���E� E�@���N�5aIV�ϧ�o����Mޗ=1ܾ�q��"R�]��D���1$l�r���74�0���V�4����)t������x�O:��5��D�bpf��{M�:e�-~�$)����
+����]%G�G�jbMnӸbZ
+K�2��nُ�x�'��YgH
+�M�r~�J-���
+�:�֥kI(A����9�����"Q�_����H4-6�´�)��y6Nj��\��I�����G[��8n��x��S5N�`_>�?b�<�NǦ˻Ϳ|�b�6X!�ʹT#ܦ:�n�u�5^�6��%�NXu�C0ѩ��&����"Ix����� ;���Y�ЅVC����H0�#�S��l%� uUp8��!����̔$�c'{�5~�YP��E��!:W�`8���=m��.��y�@/Xč���~�UV�ŭHH}W�uL�=�:�WY=���)� W5�f�%SŊ+�b�=���|�& ��I,�)��!\n��&���{��+cSTʐ���#�[`S����D:~�u�\T�FC�jG#i�ـ!�� �|"�/sڠ^"Ɖ<����"NZ0��r�a����;��-09���E'�2����*��ž-be�29�Y8{r���$A�=�#����C��X����3s�ܸ�6�����O�b��� - M�r��G�կ\��Q�P������J\��B�+��Go�T#5�79q�(3�C�+J�h�tmL�Pl���W����Ȇ˯%���Ҫ��- ��o�+s�n8��\�ekr<1%� �0!� ����`7}w�~���r�8ۜ>���݉-��Ƴ��4�s/[����D\�o�ܒ"x�T��T!Zx*�&��Z��J�Fc9��vn��L�wyBߘ��]�aH��*��C����4\s�#�=�L{ �t���w�J���Tz�E#�pr��y��`�Me��_�� �- �Z�ء}��c��4,��m�5U��}�wv]W���.��&/��L�i�A~5�uz����� �E�0�,N��$s:�iv��"~����[��Ɉ�D�0oy��r�z��Y�{N���`ou�J�U4���-�8�������p�O �|v�����7�$���0����T�ߟ�8�=Vg�-�(�|ھc���>���a�$�W7qi0�@. x��ȐF��R�j=�Q6��b�0�a�3{B��a�H6fx�Đɢ��"A1S߲2�����iA�PK��?Ӻ컻�E�D�DZ��r����4����k�4ʑJipQ�`��� V����3]��Dc��%�<��i y!
+B�.�5Y��r��-c X�� ��<tEa�3�� <gG�Dnb��V=�.α9ز�m۶m�Ɠ�ض��ضm۶���ܩ��;����еw���e �q�h͔�7z�N���8m;��B�T� K�6�u����p�&���\�A:��p�<�
+P`A~%��p�M�D��毖 jAZv>������x�u�q[r��ha"�'p����
+�%A�q��^��v����x��8QkAI`P��D����-�q�,4����V,�p.�~*�#F$�`}MR� �l�??����[y�t=cBaa�E|!P���h�+@���'3��G�+>`�Υ��%�c�b�^���vm�ws��]��)-����?۠q9�8���jm$>�{��Gۣ��5�p,�%:Y?��9�z�g�^/�J0>� ��NԀ����Pְ/K�pX��K���ǗJ�;�d�D��4}���8�_�G�d�<����V ��� ��*�D'Z�ɲ0Y��LS�"�I�o�"x�7����bd���f
+�o`z�b��W��W/�A��A�ɪ/m8d��k����� &�e�����1,FR��K�F\!|M�+(�iEX0��b��e�2�R��A��,�VbD���+�J�9�y��4buX����=���U�EԵS�_�Rh����Z�Y��N�b�8��,�<mݿ8�[�������\����E��r��n:��A??��x���`d�.�gi���,t���c�| o.��4^ND}t�2j��__�5�,T�zݓ��������*����+��h�,�|���;�^d�Igର�a�nO���a�R臡��`�Vk��Eݴ�,^����e��Avx�'����^O���I� ֎Jm���F��qҵ�!9�JW���A����QzsC4.��%-��r��� fy7E8&���~ ���Ƅ�6N�œ�� �݁=���G9�fK+i�>�ծފ���ӆ�(w��D�no���l =�"�V���M��/I�J%2�:+�b�<7��3�D�R�t1� j) �#A=(�{u�u�����@)ĦgN'��}GD���W�A[E$��F��aKe,� �]_�CAU���<���;X7+jh�$���z�![��2"O{�l�y=��o������
+�w�����_���YKw��1j�����(���]��6TqqZ��6�X�r�y>"i7H���s�xAJ,�'Qr���q���]���3��KXffK�7R�_7ß���hA�sn�Xq�͏�.ps(2e��'��b�@w]�<J�� Axnٍk�|�9X/�mp�������oR�ߍ�K���oeb�.�-��H�(���)3�/�=�*ŶTH�<�<��Z�܌��*KB� � *��e�[�p�_@(Pq|��h�R��I��0h���B%$���ɔ����W&���.A�'?3�ߠ�u*�%�N8|xjeൢ����������MJ�Ŋ��[ν�~��&�L�`}�9��&��
+Ȓ��>� <i4|\Kw���qsV�"r&6*�@�"^s@�3V���k���������.ѓ�QݞS�����u2:�B��J�'o������w�_��ڳ鑦�K��L%�GY'��ކ@���WĬv#~� ��D/W���C�B����p��~��9LW =@u���+y��"D��ᕆ@��
+@��y�s\�ӆ;��f���&�a�/j(���4��җ`�ٹ%�f���sW�-������RB�(t<6�W1�.��H�j7떚 B{3I���6|C�6Uӈ�h���X��Y-�_��xz�G�HF�h̙Sz1.��D0�w�ĮR"���Rp�vom
+t0���:���p�Ɋ�������-��9oY�`B� T����@� 8o2��ap�f�0b��V�����n���/����u�%��E�h��(����7=wF:���dX� ^���\�t��CXL�V�j���h-�ok�Y��ɐ�o�!Q�A+-� -������r�Fd�@��x:��(N�R8�lϵ����eR?����G�ݰ#�-W���Z��T�f�> ���}
+��,t_�:���� � �:�͇�P�
+[��܏=�Ϲ�ĥ����&, s�x���Վڿ�6�#YH�8 ����{MV� `��1�����>�lM�oK����ƿ��X���mD��б��
+�E�CV]�VQ* �#߁z>�і tC���Q^�Z���x�U-�jw���OM�hf�5��{� ��M�+�`\j�l� +cpM�
+a����ǜ��h�Q�):�����e�;�ꎅ�z ~�%X�H�� ��V6�!�ɱ�u��g��WX�f���D�8�Q��م��s'T l�l�;3�;�A@h��yR�p��#���8�*��E���Zo�<̯G\N�|�4g��h����ޭZO�����K��!��h�2Rz[E�:��K�q�U�0�w��6y���_MGye�@�̕�j� �;��:��ߐ� %d5@�E ��CΚ�C ��
+ u�y�4��+��E%�m~�ԥ����]�D4[X&%>�‰e�X[�o�0Δ�e��!�/��G׵@`� �1C֒v�Y���1=�u������c>�f���h5 � g黍��tN�F��ij�p�:Ƿ�Y]i�>��|C���]�+��{�_j�� � T�
+i\�=��)�A�
+lF��x{�7�V���%]�hݨ��~�������k}E�I��]ʷ\�^` 8���rI_@��;�R�$F�gO��1��nz�� �?��(<N�j�<�4ln�*�w�`<�.�^{�ӡ�L�,�l[H��B�jb�0��� F�Ԓ�[xL�",���ƶ͝,���H�F2N!�����{h�ۜb
+�������66q^��i��ջqZN��3����T �K YT.O]b��{��xj���y��$���� �}/V���M6#���±ݹ���i*����'�e�$�n�~{��Ϡ>B�9 Ƒ)�T�7oө�>R�A��� ���7\�Y���!�f��?���pMc2�?s�K}��}^��.$3
+��q>#p�g�{�U��Z�"���H�Y_Uw����E�s&i/�,���/+����5w�V�K|�[؉�`֙�J�Q �*鮛�N�r9��%����86�$Þ�Ǘo�0<�{��i~�)l�؆�|���.5���e6ɹ����Oi����K�4&�iP�N������x�<��J�)�6
+���mU���V��vϼ$rq���H��j��(֭2ŽL:� �AH��0A\}8>A-tx -e=FO'���fn�>�f�"� N� ��=�\G��w鲭y���|�m|ԛ8���h#��]�͒@?~�f�k�%(yk�H���Թ�ޚtLbYĸ�c�3�K��%�� }Xݮ��.N�ִ��V05\� <Sh��E�ݿHof�Y��� �������ĵ^�:
+ �R$�͡0�c�:G� �7L����*y([�)?��:L���ȭ��qm�}<.��Ƨ��J�%,Tn��q{�UʌK_�q�~ؗ�SR���},{� ��d?1���%�'[15�I�fQ=����GgJVs����՗�2�M���P��8ՉbK{M<j�r�g, �@ c��P7��s��Hr������n=�N�^���po��Hb�` i� ���0d�Pn7�E;�/Rq�kJ1�\��)o7��j�pJ<�ʂk軈R�0�lOD���!B~���xl0�[��L>��O�>�|�9����h�<7ARij�U�gh(羨s��\��� KRƓ5���BRּW����u�����]���Y�>�1�9����D����3�:AaM�����j
+!�$�H�=B�v�3����5�"���P��X�]G (���F�B��}UP}=F��1!����=�4�T^�h�|º�,�h�3�z&�ֿ�4 3�eD�x~{��L#��ӵȲ=��xo�1�8�4y�$Y�^p�Hc�l8lI��_�N��P�U������]��f���"��C���3P���74� ��p���q�F5�yR_�����V�rœ^�0��t#ƾ��խ���x�yU`���ͨ�+ ��Rp�i�YGe?�W��̯���
+a��z*����1/�d
+ ��Ļ��[Y�W��z �E~O����[5S�.�H����H�56bQ�����Ɋ6NK c��[���%�. ��: K����@���2(��2�Yپ��l���g��Tș��6/k�S#"��$5`�����HjXi�a�y<;@E��d&�� <8]��nDΏ�Gh{Y��s+���{�)�)[����T�y7�l�{~<���C�x!buK �4��{�h4ЖCkoyE���U��w���[}����/�d���^9�#.r�Hz˱�Lj�xncM��38v$s>?9��*��I��?�sa�C��/k��?�P���&��+� ,_Ij߽��u�a\?�)�E�Ѽͤ;Oʏ�'I�]s��6io�u�Inun�h�0U�����j@�)�[n��EZ�<#�{Q���y'F_�K�Z���I2t���w>�� �6e����&s�qܡ&�Ĭ��X�F��L�� �����&��aɱ�*�|�T6��ݪ���������٬4Sx ��T%��̺�9w� �٤��zC�z .2E�^ɸ �s�|4��'t�F�}WGIH���`��BC7h�WJ.<��/�ۋm�rW�6�h��POpKh�<�k��`� �yd��h���aN� �$D���3,�W�xd�;'��6Iqe3#p�8JE��ת+ӟ�D(�BχT{{���MDBr�}kt�ϟƼ�8,+��I����V��nu�*������w>�N������k-�ʄ�������#.s6zv�N��/Wb�DZ�5:�0��T�6�)��A:�h4#D��+ۥ�B���V�k#�$K
+�4���K��~KS�k>�ѕ��A2�6l. JE<g���M���>���a7*r�Ak��<�
+>��\��a/�5�x��_#f�$�`�M _���!�����a�1\I�k�:����_R�9�16�!����ű-'+�6Q^ܘX=<&)�#T���z 5����?j�����SM�~�#ݻL z�~� R��9 �@{���&
+NJB�c~�/���5��g�:2�R�|-�{ �gmBfV�T�+���b��$�ey��������Q��Oxx0�,�'�W���N�MF���t�N*%)���Jp�tK`��� �����(�e��„Մ��)?��:۽����PR�vme����I0��Y������p!fͳ�QI��O����{[�,�?|=�!� �v��P���E�.Ԣ�������&@�8�K���k�s��� j�\��AU"��PU�`�z�&��o
+�aZ�7�����z�[���J��X�CZ4���n�p�36�?�\��j]I��Bd�qH5��c1”I*y���E��4��߳�ER���\V��*�����wr�gz�Qq�V��( �c��8�s{�p��VX�ɿ��|Da�ʐL�p�%���;دؿh�/��%�% 3�g�11;F���T�/^�O�Ob)[�'���G�yd��3���+�@�P��:�]c��F������G�5@��#�����*�~�l(7V�u]¸iZ�E�9�k�sb��#���� Z��>����Fb^��nK83%ǿ3�`-�~�Ć��X/�d�����+#�����ZZ�ZA�Cr����W����d�C�2 O��]"��R$�d��0��4����[ ���� }���h��]_�7�� J^_���(qL;4T��Y=L���uF��� ��Ҏ�\���T�Ok.��A��v�q$���r��-ke6�$J� [V(�2�Q�qՀʴ�g%���ZZ>j$S�K�]�%����p9YJ&Si V�NCP���%��G6C�B���v�0,�y��#�q;jn�D"y��3@t�Pi�x�fL�G#�]ƒ �![��+�F��J ��^���(���T�Xܨs��6u����U�������g������6�e��ǻZ]�H�`���L�-���&8�{���|�H=^�`@vf(���dh7Ѧ�4����,G�J ˿�`��8��W[��'O��.�����՚�1ᝪ�Y7f0����K�G�-R��PNSj�b t��A9��� خ ž��oD�)������U^��]O��������hC�؊۫D�q-!#���#���������2�Zp^�aޑ�X�d�2���>n���`��]9 <]4*m>�n��-�?{P�<4�H�3����6�#��Ϡ~X�U
+�A�H�Wmy���Q1H:8� �^�΢�
+��? ]DŽ �E ��|EDe:�����+~(�Gk��CPhlUCTu�LE��o�$�G<���k;�/?�g~�:؛"|L]�As�C�Rf� V��F�麰�E�v�zl�jF3(9���W�'p��*�}��5^g` x/c�ѳ�ΟOZ�;k�����SJ����C?�H ������<��K$a�����G �ϱ�-�t7���i�%���U�^�3s���# ��N)|=W�ݾ�Z�H�eh_w��y�I{�B+W�n�,sZ� "���Jpq�j$E��6U��Z������P�}@��ܯQ-ŧ�/i�ze"]Ć�+K@�j*0?{$~9mc��3���LN5�T�[�;��&�f�[\�uC\�6��7uf�� �t&�BB��C��}�Qc������8��y��V/!����t�_��)���]�t��b?^� �-�h��_9�{�1(���]�Aw�U���/Sz���mM��I�F�ס�� � Y!�^�uu��{�����Ra�����r�N�����[,�!N��u��bۜ=������bf(T�"Bua��=�6.5Nɒ�>h��=q�+��O�D���`�����$d>�� ���;!q�s ��ר� �n��$o��ri�þ'enn\�Vc&;�Cv)&�+�n��Y��&� L��%���@���l��tXxfh��<Gb�f��E�l R��dU|y�WT�� @-W ;���r�2r�<�Ġ�,j����I�E'g����#�y宸��uBvJ�����y �ąV��^���"��N1ݷ���c���y& ޠZ���q��u� ��'�V�� (�8����=j շ��\(�M�vەȮ�q��sUv���=f��T �3���2��2�2t3h�/��� H�?Lr�x�Ph1$�Zj�⌀;�9����z�azZ��|(A��,�s�A8>�,���n����%+������+��8kT�����r�*�=E��N '��5�*U �C��Xk2��>O�H�{���֠��U����Fo��'�"
+c�+�'���U��jw��:��0S/��k3�,J�/0�Q�M�x?����A0r���������!��q92�.���&b�JG�����'�I�̷, �-��e�&<¹�7Ŧmq!����Vw��p'>r��<�咝i�Ա��sM _�f���[��]�"�*��i�z9�8��e���
+���i<�����==>��cBj>�BL�х�G���9vF��e���`͟�(��v�K}���qIQC�C�h����Y>i��8>��d4I���$ȅS����Nϩ�ܵOɸ/ �^҈��@�I���+���%��H����� �.�����ܠ1�QV0f��"�EǼo�q��ܭ]N(���M�fxyJ|[�7��{Ù?�q �I �菸4 �F��J/�G��U~9բKsؐx���Ix���Yw (%���z�Ža�@�M���si�sd�]Dt�D��TCK9���&�`$r�h3j��v�K�?k �.'��T^��n_7#�Wљ�B?dm�Mྐྵ`}.��sB8u�_�˪�V�eė���q]b�y]�@��J�߇2��_����{78�zo+]�%8Ӂ;�c�L}���!u�!�3�m�(��o'DB ��:A&���k��V��F����-!m͒���8���o��t����Y+��xQ����L>`�V^����hWw͇����}3� �ٮ#gAf���/�IB%gG{�X���ۊ2�՗jt'�}�1@�$)^���%̿ =�x�]�����E3�`�����@��x�9������c# �%W��9�(�7�����Pu%��4��v7k�g���8�C_Z5]�
+\���A�8� ����k��ss]c�s��W���o��2�yJK��.w���f�����jo����<�����{��T�����~ߔG�޽ȯ�m�nzǖ��������H*Fs��Ie9�y��2�J5�bǯA���z��:A���BGh��m!�.#P&b�#��Ry,�bGM[�,�|#�;H���w;:T��HKJ[ȶ7c�-�_
+_D�!U��.�g�!E��s66�p��Z��"�d�Yw|n8�+�;�[�\�f�
+5"��Ժl�� ��Ay��Í��'S
+�ſ*wE��f��hu>$U�;�qM��tT�`F&�����=���L2I��z�D(+���0��j�~� S#k�@� v%c�$�[������M�k�ޭ6�9�����|�$��t����{]vSf�t��i[�tB%h���[K@Í�?��Z4""���#.�ku.�OqWڍ Z������J1 �<�ȵII�c9�m{�)�q����y���5�&��N�\P7p^t(��A�^9N7��5W1%��߮oI��W�����ېݭ,(��%�Q�S4���3B�[L��x�.t|{�ຊ�/"l�
+��P��+���00p����'Z.��`/B��C1�����y�񍍁�vRc�&AH�r��@*�!�>�ޘ`n��V����n��'��AYR���Z|o�i��M�B�$�̦ ��)�/��Zi]zX�b�� 4��!;bR�r~�?RR 嵻�̳kh��7�z7������ �M������ �v����P����] R7-���� zai�����g����y�}GZ}���=����%��iāS��a��N( �)BD����q{!S*
+h�� Ĝ{�:o���j>���)��6ڱ�,���?�M^T�m�:�X�;��-z�[S��h6�n%���J ����F���'hZH��6�]��:���n �)f t������!R"���/f�41
+�L�j~%�!k�^
+�/�y'n�0�NoV��&�qQ�的�p�*�h��#01��AA` m@0m�;��'���-O�+��y���69��������7
+��x��E���(jw
+�މ.|��2���B���& �U�8�_�g�e�<�o�(��� �KD��ԖR��M�v�m�9)�uj�����C�?Ѭ�ճ�����,U�X�.���-�V�U����r�R�T��QMq��a�P0��:2�sV4:���~D�@���h��Q��R�����â��ґ���S�~k��������, U�l�H��_��3�7&���2�nH��a�O+v�<���a�� yO�R��h�܋�e���~?��2 �7Hh�5��m����z�b�
+��ިC��.��v��-�����ê�:��a�)Jp@�w�:������D?_`��eD�{����<kVA�E�B}�/Ti#�����)Ϋ(_���?��>q�q��"���}G�Jcܧ<e�#�w�|,�}�8-�C��mD�"��AxZ� 2��Za]rޖ�q�����>hJFž�+߆�3�O>G������Κ�f;��|)=�S8�����e�"�rh������s[���l��*%���*���C.����Є�� {ZTu^u���{6,�
+��ĭ�:�'l��@p���r�y��=D�2��kvվTy ����f�.dvu8U��l�g�b>ΐô8��x�f��!�!�+'�U����2�X���F;��Wǔ\_��J\������$8�����:w�=E��Y�uo�4cg�CX<2�&�{���7>L�%��1�i�ә3�D3�s��=�y��q�I�.Q�-�t|c#|]%j�`0�ۆA <����Ř�d&�� �����;�S�v�\ǜ�_�Ռ{�w�뫰`��su�� j�1����� ��8Ui�d���B��m�x�q�NZ��h��b�D^<\g*g?�V��,�dES1�^� �q5 z�F�C)��0�9[S�r�J)Z�R���\*#���k �h��P����6��=��8�Ta�9t��'�@�����?���I��V��[�2�ܫ��r�k���A���V���>(�CP��B{D&<�fj�G��H�%P�)y� l��$�Kp�$}��ب���j�Ai`����w|��NS��ݭ��&�U�g�eT��?�B^䊟K}����M �C��a�o
+���y��NFt�)�e��V�(6`�)эHp0���U�ɨ8DW8NR�SPF���Lt�@--7�XĤa���f�a7�Ja�]J~���C� �;԰���3�Bh���sD~k��; �&�$�CY.F���0���հg��h�
+�/+�������/�Dj�:oH\������֖5x��p�<E��@�H�lQ�5;׵�K�,Z`ь�G5Wv�7���Qf��)��S]�3[�qt�q%�>1Q]b�`�� nPc��6PPD�>M�M8`Y�a�fvb ԎO�M�OX�¾� �CUڵ���u�d샏�%s�Rg܋fS��~�te~=#�`[��k �ְ���%P�s
+,6���ɝ��/�"q��R{��8.�����k��J񏴛J����ԯm1=u�9� �>,}�a,�M��'1�b�;�o ���A��<�:.��`ˋ�_7�"��ƹ���� &��k��
+<�]��^�4�2��:�`$���1��}�0��/��[´��u��<&Vd�o��|��f)��هp�ʣ���/2a��~���y��>�,���X�I�'�@MilS5��G�! V�������G�T~I@�=Q����<�=Q4�*/}����'Qd���'-X�C�PV��r��m � >rL]�l�߉�*i}�E��c���Z�&`�˃#�޴.�I�/����<䪢mj����8G�-����=+O��E
+v���Ad��]�g2\E@�?h����Vw^Bm4P�ϱY�S� "c���Vy9��Da�K�|)����^���^�\ �>/i��ّ���Z<&��s$�����[���A|Q��CBȚ�1�N%k�é�=w΄X�� ��h8)$T���������՚~� ����Nx�"�8��>%�� E��V��'ڂ��1\�镭��� ��ᤊ�0� pn�����ĕ��Z�2:��l��p�]� r�4�qy�������h�
+�OX�9a�l"�4�p��?+bIP;mTt���Sb�ن��)}����_|� �x��iof@���Q�XV�16�y.�4c�g��0���B�I�XɈ5�K �*�D���}�}���M<�U�F�^aI6��qa���1$!���V;�O���1R�F�}�ˏ�zrP7T�.�/d�
+>�?���zyq�k��F�W�R�L�s��DQ_\�����R[\®�T�56���N'KOퟡ�Itƾu�-㝸�)�^'mdb�M�>��>��I�f������ ���P��3�N�9j��k
+J�r��fr�u��Y%:mU/�w���8<U[EǵR�k%n�*0������Ս!d�\�☵yԪ������I,Tk[@d���B�e�=�������x7Lj �j"�%�����i� ��R�"���BfV���s�`z:t1��Ԃ�_�S෸�3��ħ���暖���'�W�$й��C��$���m���(�3S�s�E`1c���;m}�n�� QCƇ(Dd@a�4%!�:�)ɗYk���F>Q�8\?Jf�yK����G f� 2��->��Ȓ�UN�:�(w5�ѡQB������15xq�]Q�p�ڰ6���?F���Zz��0�\ڼ�A����l����o�$Y���~�~顽z�
+�J.�ބoЉ3z��?�F;���2��r�;�ƙG��<��3�I}��R ����
+
+����0��Y��m�� ��!�y.���M�F4 v0��3 ���yJS����G�M3�X6�C����ᤆ�F�����GU��v�����J����X(߂��� ���;�_ʽpY.��#���믍$S3��2_~􋒑>B�u�;���[��ç*Ν3P�Q���������U~���r�b� �d���Na����.�}�ْD=a�5F��"(Hc�p���x�n���D�h돚��̙e�6԰��JB�uf� ��w(�$�Cpt��:K�cS�TA��6�=�����9�@E�"�t��[dvˋrA����[]� Ͻ�Q�˨6���gIG��$r{���?ĵ�2�ș���4(��� h C��-SE�Pm�Mp��d�O,d��c.}F�+d��C5H�݂��X�LY^_k$�f@��?�+\G��^M���9(x;����,��|acB V���[��3�c�Vr9�>�m�f�۱z;jFǶI�
+�i���J�Ϩ�������y��»F��Y',?�fq������*��7,���z�/�1����d"�(a�h��g���{�ld�i��=;� Q�-��y��((���u�s�Gbuk��鳒 k���h���h+-�O��e�~�[��m��Ŋ:���P
+��16�
+C[���H�W_&� �ҼBK���d����?�z�z�O��W��Ɛ͓0DžX�>� ����?�D|Х=f"���-?�W��m�g��M�A$�;��LC)%��_�ͼ��`CH
+T��ɀB�uߩ �euQ6c+9��Y���u,�L��'(�$7��(�q ��O=����<�����Y)�3h���1�m_�}Y�0U��F�t<�JFy�f�;<�2�y�'2cX�M��;����g���$�zn^mm�%�@�Y;�|��y�.89�(���ٟ�š�Z*a�?6P�r8�?�1`�4��Zm�Y�u��/���[���f�:f�ZƼ�6UB����C��ߕ��0������0Z��B���]@^��y��Wq1��X��H��}�ZP$���ap�~aV���<�?�ɲm!��C�Z�"}���$�p���� )�a��g����{��ϥ�-�g���`�����_L���Ds��g��@�a�`��f�X�xt=��B��qS�δ·+� \�2>�򴃃ai,�Nq�x^����$��k8r?�G��}M����U"z����2J�, ��y����)9_��p�%��7������~a&��"zA�˥~�e�b(<W�����skph� ?ѥ��%|����]���Q�㳩8;�4��S�IEҽ��l�- xtp�^Q7�+G�s���ʃ��ej�3L.�W5�)�� -������jh�W�z��G��B�yǪ_�lzUf�K�_w����D����7����̛w��+���������n�b�rX��4z���}�Ѯ�W�E�Ǯ��*�Z�AV� r+�.}��ߝ0�c��f�7��p�������y�dž�� ���"A���9&�%�}`��*�e��^0r����IS�&�,�`�|5Fx �W!�ȚƏ������6_sfU}�f�����b���0��仅7��+�uu g�PH�����Z=]���5 �}Cr>���O@�?�~���Y^ܫY��m�ܧY��pb����N�2�(�)�����Y��z�
+v��L)&�����/h�E�GR�D����Ȳ�\<l}��� ��e���Z!��bIy\:@ =�K��{�W �9phF����k�=�?� V�����U[�}�a�R���p��oȴ{k�ճP접��(����-�y3�8�K_��5�X����ލ(�u�Q ��:5�A���%m��\��6jGG�����ԵާL?J���{�fE��2�5j16�ݞ��[f�济�W��Wl���d�+�*��0�a��b��"� ����mqE�/(��+q�ƅ�4�-�@���ۣL��i��e��Do��֧��y��&�`81���̒����Y� �kO��"/tWp MՕ���CM��6*�W�7�*�ɴ^Z���'���}�P�bb�0r�9�����h5� ߺ{� ��Z��&���& ;�e�M�&��dH��d���+���6EB�2�MP������{-2�*� �9�ԒORxu����Y�K@�"~�ԩ��#J���Y-�cI��H�o������8{v���"���J^[��n�95B�KJ[��ץ=���д�mR��g���Su�Iԩ�>#7����†sJTF5�.Ď���9kM��Faj�I3��[6�� \ũS��?�yy?�Zw4l��'!�}���R�L9��CKƏx"x tڟG���pHj)0�L�/B�æ%��)� 2��~`2�xD�t2RM^��T��!�mƗ^T�Pa�:��-K�$��ƕȄi���l��e+�� �LP�v��0�{L%�wͷ�U�>(s�渫��i�
+0��b���-Z����A��#E}NM��<Ȫܒc=�7�E� ��u��N"%Ϗ��'پw���TMc���|.�݊��c��Y�����%v��,�� �}mmg͟N��ݑ�h�_�'���H���l�X p:?�"�L�!^e��i���G�y�lČ+*N�F/Q�^H"P�E��U�!֊JF�d�B2���v/����j��IY�j���-���l��n�ʕ Ǹn�0""�mS�{
+n}�!jo���D,8�'x�&�� �n-��v5nL�?-ބ�5�s���Jт~�3����Y�����?���H�s򡬘'��s:A{�9�(���t�����h1�`���rJ�IJ;tB�n�ZF�������4U3Ea�}�ǽ�e`�ĐG�O5�j����<$������6
+���q'�T)���9OahKKc�һ���p��L(�{SG��pm�'_}�!�X�Vi����k�X������ �Y6�0-���V�Լ�s�˳�5wG|Fk�'<�+n��&��GR}3��� C�m%�aJk�Pi�n�z��gw���v~XS0�'���YV����Z��CW�|�y�4IʺN) wO�fC�_�xYT;ܧq^��x���|>7S���b+�E:a2<�Ll�n�m����x�4Nm���Oh@"�s����x����X/��D���N ���7�? w�׾� K��ƫ��d)5MW�.�.� S�2�q�t�}Cv�}����6i}�FM�h5�.}�rX��)�1ce]�9�g}�s/�Bf�4U���V��l�>9h߽�nė����&�reڰ�|^��?���9����>wKUy��?�BE�L��%��*��\�����z*ML��+���gh�rk��x�:�UQac���s��GT��i�r�_�q�XlJ1�u�?�/3����t`v L�kc���f���z��T�>�p��^�onFXMųd���Γ� Cu�A�0u� U���-��J �<���,2q�1������D��Y9�"j�����A>,=�cH���0;��у�%3�Nξ 8e��w;ߵ+D���,�L����a�@$�� S��p4C���s�#;d�,#�?��d�ٕ0��<t$����k�t/�����6�K)��2' tt۟M�����аi��z�[�2/qjBKx����ez��!�f������&��gDGc�un���W�N��p�t��XxN�\`���l�w��� ��r4�p3�u�ce�;q��"S� �� ���3���}����ٲ�;Š����R��[P�T��T�����+���۾~ۂ�Y��"Bb ���'
+�Xc�{JV\q3�z�����; )�.��:奠D �U���h L���z�{>�~BM>�r�yh��3 Y$)_�#|tY�Q7�'�V��W� ��i�N#�%iɰ|#UP=LY�l� ���+�[QA�!�2Xɇ�A>���0V��Ɓ`�4 ���^ ��i�?��
+�νna��w� �����b4�������P l@CՁuν ��P^˳���.GZ?�����*X(���N{;��%���9 �9�\+-{��m&p9��3������=;ו�t��z!AG�<_�,Dڝ&��W�ïM�N��4R����/�bD�Նbl(�������/��]52���o�Î���z|�Έ��d#d%�0�����~(�n,t��\���L�Ԟ���֙�o�xKl����7$`h��ܲ��c�MT;w���@�z�FUQ^B��:�-Q ˦m۶m۶m۶�̛�m۶m��ի����D���W�ח�F�� G|���`x_0P��ŭ�0Q+��?x��(C �
+vTv�~�%@,������9�����/�\����`���^VÎ\ұ)�i�gLQy�/}��>����}�m�d���wt�"� ��5!8M=�4��t蓢%���K���U��Q]x ��b� �:�
+�l�Br:���81�g��+U2��Ox�qgm����T�c�Fwl <!�XQ0��5`*�l�N��̋U����^Q�=�v�K�&%�ژ��a:C���H�VYQv�N���yj�y ��*)�g���m"�|�D�B�i �t���Fl3�sw���_˳zێtp/��'��)�x�GW��A�~�
+j������&���"�c���7�6;���A� y��X�j�o�H��9���ǀG�-��m��Eo-NU��7O+�E��C���ޮ�[[k: ��~R��m����e�MmCL�+�J�����q�h��dMpz~�x�Z�TR��9��~��'f�[M�3&-OA����ذh�pA<�&��^˩�TĆ�q�&����$�Q{��[l��6VG$�D�8 ��&�}�+=T@(����d��Y��%C��<��N�h��Ԏ-��p�5�]5��#D�!��w�,��o��ޣ�
+@G 7��m��M���N�-���l��n��N!�k8$�1�Hp=s�Q��Y7�Ϩ��@�+J� v�C���"�t���.�_�%RPδA^B=�B�Z�M.W'�k��p�����!�;�{r�� ��ΦF�Z@t��b����h^@��C�9��) �l����9�)f�)�Re�����H�lX�A<�b�k:��8�FƼ
+?�\���t�cR�����Vˀym� 9_N��•�^Qx7zyh����#�=���d�� �$�'C)����YbbzQ�M�5(v�4\>� )sHW�[�`hi�'�A�F,A�x�?��to4�
+�=����4���oi�J�F����';`,�����?�\��j�n�۫�bO�9��s�'�"��eA�?mkL�4���e���jm?tP���nV˩����u\���b�_�ֈ9�'���"Y��|�3y�ΝT��#s���B*0�NFPfN�3���t���f�I=1�0M� �}�3�X���QA��z
+m�q� �6�N�F
+�"�AR�G���d��Vlw�UqW.E�km�c`F�!@1R�
+������Cƒ���oo.��5\G��6�Z���ѸZt�U�7��\}m��4;Cz>���e{��C��w��W�uN����p/�tggbSW�h�)���ҫ���&›�L�ze�� �1$e�ҔIՀ���3�@�]�@���9p?<t@������Iu�$�VtO}P��vr�EX�Ң�}�\j�����Z��Jka�i_#�qP{���DWNë������:q��UO�l�a|�]Q:"����&��L��}=��Tvg��d��n�gO��� I&���&�p��ߤ�������Thzܪ�9k��l8e'�Xz�#�;-)���-?��f��_TAα��t��H�ڲ̴4��Q�ܱ�q��E� &97��L��zA}�]*x��Q�bW�� �K���[p�ϮHI�Mj�GdJ�{@M1v�� ��8"
+�?f�r~׺�~����_G�%4�!F�k˜��+n�d��f�g��G���|��R� Ai/�B4�
+ �w\0H: "c�h>��� ��GJZbY�$��O�xeQl��� 0���Gw��ﰜ��3��O=)��Rd)�
+�x�� 9%b�'+h���pHo,�T���Ro���q�}�y.�����ɸ�n���Kc3�ч �"����V�01A�S����J��\
+"���j��ڋ/��=��p��2��d��|�7HY[OK��{�k�w�,Q��~�����ؕe�c���ĝ�*�؁ε��� X+�XW�ʿ��_���hr��E6���^�R�����{���–)�:�ࡪ�O��;��G�g�1q;�f��К�^Cu$�}m�`��~O�fx�-1ދ����t����� z�G�;,w8���J>�ج+��F�fց'�ܤ�4e�Țx�u�~ -���1v�r ��;EQ���ѵ���NK����v��)�d�w3hɁ��n{ᱸĢ�������{ 8��b_CM�c�˱�_p�����Lډ.��?ss��|�H'��Ʊ�̟(�������J���O_(7�lN��G� Wࣜ��O~�!1��s���F��ϭ?m�˝ t3[��yn���Ǡ�g/`��Ԟq��oX��kd.��4"F���-֔#��N��҉ +���=�J%5h����K� $y ���bZ9��cY��˲R��!Ek�ۑ�S�f��:*�>�i���9���B$̆� ��ZT�m/Nu�+�������B6:�"k����� T�,:�Q9�Yw+Gl��q���_���>O9u%e腲�Y�Q�`�ݕ�$״�ڸ�<���V��g���'5����`�[y⭱<���8R�
+��H� i������SV��a��̛\��n����P�@��?G(�q�ӯ;��6�D�D�u5�|��%���I�r��'�?�
+��o�n�/�_{sK�h�~�x^UE���E��C�
+V�H����Q�E��V+9|�{�z&}�U�Se�o&�'Io�>����"���7�!�R_���K���'y���
+�sok2&Q�=�;.Ρ�`�.�E���/�&�f�<��[����xcI�0�ڬ"�30�8z��m�9gY;�?Zc�Uq�2�<.�#��,�-�Sʏ���긪��K-L��.�Ę�G�� R�ʹ��U�B^�`4���<)G��n����{��j:V0ڎņ@P�K�e������\\c����OZh&K�[�EGCVb<n^M�U��F���(�io���o��~��ӌ����e�kW�ו+f��z2NIl�a��|&��'�Q���d������ ��I�H�-�zA�2��'�CN>��� 0y�&�G��jbm��Cvv�j���Ba��IN����A��U��,U���r���$1dQ��]�q�����or@��Bs,��ړX2�;�z��z1��DC�qoP�N�¼E9[��!Lm��0g1\,�=�S`W�}�#:�����h��X��x��U��꽤�K�Ȃ�4
+Y�:����1, Z�O����=��'�*��93�Fj��k��D�Ás��n��dD?�t3��fX�,����ؒ�8'm��M#cw �vh ��?U��.��(�/�s��-�v������V��1�6���^О�G6�4'���?�ܫ�k`��rf�c$���i'a�pD @�C��\�^�hp~?�&�R����-��C� �S@k-���*���y��6��"%��9�������� �g�V/�{ఄ�-�z� ���zȋ\9��t#4b�S(v$j��dM�,M�f��7�6R;����*z)]w����+����^$�t���.L�DT��Z�6;��ď� ��� �^T��<���~#�ڰ��UF�҂�A�A �_A#�9�fc�;%@Qv�B����'%ҥ �%��w���P4�&�-\q����Df� ��Z��-��A�l~P�.��D ;�7/I��@�j j����z��<� �*~=V���Ɉ~w��~�r�g쿚�>��:Y�h�������h��A��0���V:?9����Bm�<s�@� �������jCn��6dj7�9 hg�n��q#�F���#%+!�$�ذ��4b�Ww/�_�d+�#FIսKG1��R�r��PJ�P ���,�Y�`gK�O �[^v$uE���d�\\�Dd�'�/�7ڣ#�HS�3�j=�$�v��w��
+,m�x����6�����!]�ޭ��\=�+��^m�mХ���`���P�Y�欀IqK�G�?��'�մ�S��m� �\�i�B"��1��НSr�"D���*�u��Ls�����g�;��C&zh�����0f���� �]K�g����qjk�q䑆��2���(}��=M'2nz(��b�i�Q�3�Z��o8�5��'N����2�$��^���Rss<5F�?�B�я���C�Zp� _�"�9��_*?��[��M�.a�ƊV��h�1�<�ţ�Q�(�Y����Y�G��Y�tѐ�B�$f>T�@��k8+v��pÚl�G�Q9�9���奆Wڱ"� � �a���Oۿa����Ue����o��t)JH�y:�HP�`���W��2]1\�B�)���W����j�@�R^���cZzD�7&R�)�W��� �wBnh,�v/8f����=r�����#�&�hر�]�#����.����kA8j�t�&�_���d5DT�y���!d�g� �6�c��
+_�s�D�|�]����e��֜�Nr�K!�3c�3Ν�α0_*@�.�H"��,a���=.r��;�����u}�4��t�д��[���C�x -m�!6��=<O��؋�a���Z����g�%b�Q5�7(B���g�
+V�����4����S����K������\����C���:�GN�����"��=��*����`Li��X;Q.[?�)��;���R��J�h�-�$֥������qׅ�z���ېc�yn9z�������%T��~7?�3@����3j�3]Ʀ�݄�w��J���qy�������H:AP�@)/g��\~ *O;k=�����4�F�Im��4�‘*1 ���.,�I�L��dL�ȡR�W/��W"n��R��y6O,9�!�W����~6No)5��I%n�1|r�SC��õ�v�P���W��/e������j匴�Ȋ�F�?��3�ȤQ�w�`���;�X#/�t-䊒4~ H�[��P��b���|���Xwk�f�%���-�)���V�*-��g���V*F�a���c%�6o(䧹0`\������d�
+@OF ���P�t���d�1�v`*s;�aO#���7s���i�JO�T�}h�l�Z�.�F"�1,�ӳ� l+����F�����4�đ�#ja5���Dغ���=p Ba�)��q�b:�Ris7���q��`TQ�LJ�1B��G��Y��_8�]� c��YI��^}�(�ݕ�b�� ��1�������F~=���r�cEyJiՖ�������+���QD���bO�(婶�&�z
+��4E�e&�LG��i�Ġ�djӚ�}��0)d��Gʸ�ߧ_Z%��K�`S�#�����_�D`��_���}��NRT�m��˅����i�y��)Gv��,�Ӷ���?�1I+�oDB����{"#�b
+Q��=��o٪j�x���������fl�&OR�x@����ڛ����y� pJ<FX�7 V ��d���zd���H �
+[\aK7��t�+�w[�Bj��!#ٯ�\
+�`���� GG-a�S� ��H��T�$R�E���C�����˶���W�w�f+�=�3�<o�u�0�sդ�4�N� Ѫ^�>��
+5 ����xrm\��#:LW�|]]�5�m�e�묃5��J:DP���amo����[��Ἱ |S�s ҄q�8�c�Q�����|�V^�aϴ� ��yo DI�ݍ.\4/߹�>�Emɬ1�����5�@K�z*
+VU��z�J���0�3zKx��b��er�m�J4?�5�I����!��#��R�+���7��*��?�|.�h ��^���o��J(�:
+�F��ϙ[2zF�#���R���e�j���6�;��A3�Z�%(n��i� o��U҃i�e�S�X������ӑKg^����i]��Ƿw@W��@�J\5�cc�Ҩ�C�-�[།}\��RN�}�P���͊��d�t��㑻�X��xv�L����Gi��5:+��;`��AQ�h��F�x1���YvA�l���91��� ~k�N�@ f��TH��a�������S۝5,]��1��;�Pb�#��@��#�ڣi�W:�f��[��o��e��e>��o����&�k)������{��:��n����f�w3ܠF{f[��2Lƪ�X�~m�7��+n��@�}���5ӊ�[sy��?�EF����YV`Vό��T��7m�^a쟘1������9ڠG���s��zf��F{|L��*�����^ss���)gN����Sc����i`�ձ�{�C��Ϝ�wLc�歑X�(E�9���{�Y� ��ޖ&ÖNW������~M΢0�!���Lįal����M@�������� c�?N-G��]���5��N1ĿE��"հ��$:��p3ǚC��c|dR�j��l$V�+ס��x�I����҅����� ��a���QR%V���.;\5W�{͔�A��� ������NB&}��*_c����OI^���S�����O�����:��?\��'�_bހ�b&$ٚ�zݶ���~��6W�融_��U �|J6L ����rV�dտ/�� �l�r��������,�"��_�[�R
+� %�_����jA�bP7��B0q�(��(E��#���e� ���G9bu�V��]���5��wcAy��D� �_�pq�BA��S��@���e |����
+��s."o^���fS��k�-b� �_5]0^�a����~Z<,��B3���7W�>P1��sT������a�����eq��t�����P�PJ-�(�K��C _�r��x �A�d�{��YQZ#bJ�S �6qrb���vBϟ��L8؎�O�[x�Iف8�h�5|�G��y�6 .�4�V��T+hI������ �2ua>
+*��c��o�Yk�Z:1 ܉����-,�z��|�'�(E\�>l.P�����-ƾO6~�p��G�xa �����~&���dޓ��,^����� ���S��|l�8{�N�&�M|:�A�;���g��(H�-$k�(�Mz�ʧHi�,e ����GC��|����!���M�BO�/��d�S�����ܺ�?�����}��p��z*���kΞ@�c�gfž�s�FAGE�(?�����#(q3L��v�b��R �a'#Z��^ 4��s����A6���E�2l��I�y�zkj��kq�|D��d���"� �9R���6w�g+���1߅��Q�%.+yP���r�i�V����V{�@{i��Q�C!�aH����]�p��ꚏl�Z���h�����-#�����*أo�.]>7��;����FN��m���������]�Ǫ���4[8‚��_f?��;ڤ���H��}r5�b~2{K��v6����#��4�ϋ�e�0�Hz��{{�E� ~�{E6�O%7�~�S<��,t��!u���FsZ���0��6��{��t���3�z���1����D�Ŏ�8J��fe�S;#@�L<��we5�{{Ɨe���/�'1����r��%��|�҉�ޭv콃�p��-��Y@ �e��;��%v��^ɟ�/�$� W�1������`?�uSm���_W�ix�%������b.�Z�5��� j�p�$ڸ֓ !��;G�#����XT�=#���, �/��{��
+�A:��߭+�t��)��1�\�,����ºU`��:�>Rϝ^p�y���:�Th�)�����<�rў�n��3��+|C�81w@ ����ى�6)7 K��c? �ܔ�䪲Â��[xBl��j(\��r�,��Ҧk�]�Ly�r�7\�+�u��10B(d*���In��2@���s��b/ Mk�T�еXZqzC��p��i�I@ !��S�*B��3���,������X{5����q����9Lm7�򯥈���{,�֠J�P]a�`Z�O�8.u}ˌ��2YM�'t}� ��;��UM���oc_�R ���_t̞�cN�踕G�,����0E�}� ZKv9����58Q�u�[�� ��� ��FL�p<�2�M��׫jj�+RG|�Y�>��#W� ���w�#�k�z��o���72y�Yt��_�F�[^/��z�����9l��+kA���wfJ��3I��v4�XB8�l�(�B��,�h�Ɠ�!�}xf_K�,QL��$ �����Y�d7�kA�j��fߣce#�3H�ft�s�G���)v�*���&79D�<qq���,V�c`;��9��:&sqL���O��0k
+��ݷ�q��s`���ĺw в�� �JA�ҵ�vwSk$�T�5�)�y�|�� W$|�K@�H_7 �3�,y��,O5���U��MfhƁtD)�TЀ��r��v��M�v� n?���� ���{���>N0wy��OE�z^*M?v�,� ��E������F>�=5Oe��lUx�eihGy1��wpJ�aY�!�p�.Y��i$##:3�����z�_���,���fR�������ᗃ��'�S_ �ӈ}�3�’ҳ��N�G'���������K\��C免��Fۢ0����-]��㏅���ﬞ��j����Z��ʝP��f����'��a*� H� �z/z��z~��JL��%��!}/�5��?h�:BQ6�֏�*D�QϩP�.��� 4}��aWCvrO��G��sꆄ\��n! c�I�3�9�������]Ld
+�3��? ��_��t/@
+F}�6Ū�K� ����V�W�ݺ�B����'��H��B,�I�4�௽c���>FA�ݖ�@�@��o�æ'��v'<)I����͠�m�|�C�!Ӌ�sr�(=��Ι�N2[�oA�����������������gs-3W��;5(�U���fr�J���x� �9E]��bp@�O"�?�*�#O��k��?piU_��m����
+*K�^9(�cR*2�<G�Q�Gܷ��u����̃�/��{ŧY;���o� _���Ɂ�~�ً0*��Ny��Z��]Qa�*ח�y��kV�\�%��r�͖QR:���I*���c����S�������n�Q7�tμp��\U� �_�~&�6ʳ���V�*���� >���HK^:&��P��I#
+ ƍT�ll�]��L�Y���"�9$X�X6k�������j�����J����y�}�p"��x UFO�/����
+s8�y�ͣ)��e�����m��B��� ɫ����Yx]g�&%�7�)�PjM���|k�`K�KF�9��?�ۦL�#��a�[2��>:)�[������ƀkӑS5 3D���
+�1ݚ�Rr/(9!��d ��K����@v�����so���Q��`G��F��4�M[�!m�$��'Q��P��AXBx�m� ʗ�i�yO�qJ��y�0S~7�\]������ی�p� *���v|2$f�M\8FH">+ q��Ԣ/j�$�^�Z5Š���9��-���Ʃ�XM�F��9���G��#Eo{G�x�.q?
+���~��? �ٞ �>)B� a��qA�t Y�>���;fb�z��X�H��1�à�CZ��xKY �.�W�#H���P��������A����^`�����N"�ͲOi��M��z��t`�|��cW� ��5T����ݷ��W�� D�BI��,c��KZ8PX��q��Y��k��@S#��jPQ>r��\��08ܞl{i����+n|�7�������������=���=�ͤe����h�gij �g��t�R�i �U��U�D���:3 ���s����q�Vƴ���
+�� �V�8�qZ�����Xb�3��evZ�y�����LYJ�� �Y���z�[N��>d�%9���4K��^��=w�e�@�C3�;Y��$��OL�K�f���|��"eo���T������VC\�~Wt"|���\�6���4��<��P�<G���0R��
+ ܸ�džly��'[��'z-��������'��<=�=��L���q�,�R���ڢo�=�蟒�7`����h�Ŭ�%�4��M����i���(�Sm )k��[�r�Ri��}�D}0ϛL��ѵ�֮IQk!-���Ѿ�%o�i鯲��:7���[x@N��e�E�f�_{�#���,5q��]�B����|��(Z�:9�m�* ƽijiD<�<�(eU=��eSՏ��%2Rr�ő� �r�nߐz)���xpW�3?T.�y���QRd��jN��a�t���#t�@J��8O/C���H� �-3s ֱ���ej7���\ ��)Uz��i�����]�*�X��Y7��d -�q-?��n$�@nG/H������m\d�s�~�̱O�<�T������XA~�i��)����U^Œ�nG�@G�z�s��c����GMhl������]�h�,��`DUҙ��:�]q�⃢'Ƭ}�>g�1�®D�-��ބ'0- ׄsi�7k�b�N^�э��|�5z� mX?_��6�-��U�<%�̳]v��C�m0��5�� |�Lo�ɸ��6�<���2jXi<��%iٔ��ֺ�4�.L1xn��Wo�7�h:�t\7ć�-������z45�͒���cy��̴�0r/5���&YH#
+n2��P��>8�"�]���I���*,���$Y.n��`�؆;K�Μ��A�ÚYں��ړtH�[&�E֛��s��cFM�� D n�ݧpd� ʒ��L�,��jm<w�kJC�� �}���|��)��M1���<=���~��~����y ַ̜��(��'v�]N577�VoN���N��98V�=�D�[���Z�t���]Ze�72����(����v~TM`�'Z����Թ�i�@UÎ=���Y��M��g�3�(�)�kL@'!~���sz�(����T�b��� �l&�^�� s�|Ͳ��u���=#[�C��G)o���:����5:@-S�����w�x�$��O�z[`��g @��p �xrLH����W+��5�rVy��jQ�&���)�(��b�5�5�,��/��r����{�@<�<�l�>lU.�����=�{�f�����\!� �)\�֯���$#�1+��W�|8!%���t����<=8h��fk������h@N���9U60&3W�
+:ek�ޙ9�kf@0����>�f~aF��޹d ��Xg0�ـ��G+�;�X��Wɘu,�� �~B�7�%ϋ�����0o��������cԞ����'4&� �׫5���r 5On��N����������aF��3;Ny6W^�t�y��6��"�|6��P�8PRf��+K�M���Lfm)�ćt궫�RP��c�3|�2�? Pëzn��&;�U�O�~�tRV�?!f�WSb������?�.�H�`#e�+e���
+dO�����a�d"��+Q�Ũji��E5m҉uՎ������[Y��-�*|k%��w"+�s�K���#Ä�-�זl�A��X�m��ӧ���*J��O���s[��:��S�[�-@�"����.���e �\:��8���[>��%)D����L�����[L�4cd�f��M��I��$�Y��l��>�dy۴�A¶�Z����p��,���I��0˳�8,�Ы �qq�mt`�l֦z��V�僿�= h����+7�B-�4�uJ� � �fw�9M�v�>��-�Ī�3�/hLjm�l�DtQ��������9z,5<���'�턒�f���$:��q��K��A'�Ļפ(��䍙?�EYc�GD�ź%��"PD%��Q�#]!�S/b����B���K������7<�"�� SR�1�UHä�>1���\��Je�u4�*pѪ����!�M�(x!!V��o=��j+c8F�BM�xn|¿=���Zk�y>�" �ۡ�,6
+}<v<���@(��ה�!���hY{@��T;�I��;<-+*���t�} ���:��=�m. �A��>C�>U��G|��Q��FB��_޺�8Qf�ucw1�RJ0 ̷�}-�99({�4ӹ���:Kb��C�9Dp�д��8��;�@�p������+�7�Q�Ѻ�l���o��%�Z���\�R��MG�]{�ğ��ߕ>(�1��α����ZAѥ(zg�g�̒ES�)Sof���&�g��3�: �Hׄ檰�0-�Uip�A�_�F-�b��cZ
+�H0��0e ����7���#~��I�d��#"N�Yy1�,m��v���_�S�&H)��t/����Ƽ����ΰ�x��"f}��8^� i�����G��5���Zi�Mu��v�~cw6`���-���Vu�6r�=����~�,�/SO}s��K�`q�� ��� �j��'�d�ҙ���;9� ?��!6��������<5���%����$Eq��s����ĵsTuG�R��<��[��~�׽&�1�6 ����� nݲ�Y޴�d!����n��SP�9"Ub��:-�a�m �8���i�"yz�`�A�g���Y�+�ߍc���x���\OjM�$�4�DD'e��ؙ�yc�tΡ�y<˩�ܦ��þ�����<�Q����Hw$oqR_ ��$L{:1�BN�Ɋ���vl�*�4|Ig<\|�X���=FŁhB�'Nɹ�ݕs�6�F��Z�#���戺���������q=��<ώ;Y�ݰ16����)70�δ���
+���ZqZA������ I�/7�^�OA]u0X#��u���X�jrȿ��H}�yqV�� ���1un#�3���+�6��Dp�'�����\6^�A�y�W_��� ���T�[� XR����# + 9����gaj����ǔ��W$J�E�z�S��-W�Y�I-x'᫟�ɗ��4J8s���5�ġo�S��t�+-��o쑧���b`=i� �- �ĸ%�_Z�����!�����]:zj�c��>s�ҋA�p�a��:�Bۉ���1�K�e�#m ��Ly&"�"a�:���Ǟ��5�!�]Zc��0���uX�^��Am �\[.Y3�t����wڲ�+u���CS��� �Y���<�D�~��O�gNr��{>��1qx�^Pof�g�~�T)�I��C�*��t �¶:���Q�N2Aw�lSgS�L��c'֫�!I���- ���� M���2�ߢq����@f&��� � ��Z������L���Q�^�zD$����~ڌ�@�7)�%hT.�����T��Oi&�v�_�N��>���}�C5������#9!��m_'��i�C�=�lM육 �܇p�c����ah������e��}I���~�)WIbܚ\�a�6�iN�ߐb� �
+f�xZ �M����e���,�\���J'ךˍ��U@����(���*��.��q)�^�>V����ճ��T̙_ɉ�rۍ\_Z΢~�G?��ft��K�I�|U}N�鯝@ nԘ�^��8�:��4�(���g�������,�ټ�Eh�Z�2�V���\�"��������ǧ�:�q  ����P��cE�y���!�X��(�һ3��b��h�6��"�!�Oݻ{�;�u'���K���q7]5|��S��jf�s��͈@����!\?a�~�}��$[���i��܁i ����0{���P$��\�VM��cJ��lcg讂G�{���ҏx�g$�8���Y��G�!��>�*��0�}�nՖ� Ɏd(�<Ti�u��wJE�/��յ-�q<I�G3�|]FCT-�R��C��W�$�|�XH�ApƉ�E�c�!��<L8��}(��ߢ?�d�ϐ�R~(|�ׄV�tf�B���Pc��=ugI%`�2
+���~�6��o�A�
+H4[.�=p����D4�F��*����u�"ykpgئd�"ԹK_�t&i��BFX��=�Ⱥ�6CFߩ�'�G�6�2�l���&H�E����aJ����wu�`s$Ī�9Zΰ6
+�TE��^w�^���,@>��.l&�9c�� ���k�{ҿY�
+`x�u�d�0��43ܻ*^�#G�5s��"}F� �'���m�e�}�u�#QI�m���Z1�V�bv���:�Q [�֯��0s)�x���jn��q�rǀ. �̝�jZ�ڼ��4��|$}����V�F1Wmߏ0j.#��v��96j2��P�P @KR�H+���'�;���?br � !5���5�HO\� 鐝3{�R T2��f]�92�G>ZkѣI�'�%{��{:��O~�ؘ��d8ǯz���(���1rC�Wz%������f75X�\��L�3;N2�j�8r}2Q�c�f���u���c�l?�5��k[��H��K�K�l:7ɻ@����+��A?��D���O���K4_O���Ƅ�����< In���#e��Ь�x���s
+�x��v� Sf5������H�(!�׊"�OD l�F����ƛ���p+B�f���3h�����f�j�}�j��E�f�SQ�D��e�\���蝨w�]�V��Ug�5��(r � ����������u�8}7�z�7+ӥڟ>w~���8z/��"�jhU��i�nYMy���F��H�'��ؗ�K�'z(lY��@tz﹞���5��XЃo�S ���:F�-���P�.<ߨT���E�,N�a
+��W7^������ݐ� cW�k] �;��1u��,JT
+��a�![��`vU���"6�V29�֝[Y��z�(�8��"��b��to��̒B�:�0?��{OВ�����C �� 6�ʺK��|C��9�`��Ǽ��Y�c֢N]DŽ�A��,T�R�l�������4;���D��j֑��ݳ�LM�D�UǍF��3q���y-�0����A1��a��I����Å\��~�Ha�@��P���9d7�Y%��[h�S�B�`�� �X�Y�B�(Pgi�'��
+z��:C�&VY)y�>,�K�!~�XEk��~'����+�x����$<���T3�p;���DŽ��I�a���oi��w�o�F�.�%S�:��ۜ�s���-t��� �� ���ԀU�>L�����uL߾�S�(@��ŊX��%Z(�#��@i-RP}r� |�܍o�^]�q%�MdSK��I=���I �M񤼍�:���.��̝�]���8�bL&G� �&1o���R��9h�������j��_�K�tS��D�*n���Լ�=� ��X�R���3{�*&(�0P&֖6�U.E>q�a��i��곔��JH����vE�u�ʱl�����âњ[`ᬌ�a�\r�͍��^W� n4�KO ��*��,��6BY�BC�g^k
+�}���I�z���`A��L����:<n�s��k1ٵ�����Tm���b����H��jI��1Qv�R>�b��ARcL���kN�\�P�A<Y>��Բ ��ɛ�^k�r�Z'�`l�+Etj��i����z�a l���+/ƟMն�"U�\Ke�#ѫ�+��k�M:�M}v�SL[n�BR��'qꡲ�����*:� �X� �U}���R, ه־������ڙ��w΀Kr�{#�õ�;v,��p�'qr��GC:a��h�W����b��M��U�z���t[�� ?mbE� Li�Xi��e���E~�G�ĒDpa�:���]�G�7����6l��
+f<z��p>�Ҫ;����&�_�z�i�1���X�7�� �]ݸ$58�Z�y:�=s� x�W��]�|D�bZr���*Ku��$82͆�C9��!6.��"]�J��^hS|����#�uD��/1�w���B#d��c�������B�A�FW�� �#��L2�(M鸝Em�w����1���8m;]Te���zO��R`����>Mlˠ?VY����*w8�R�r�G�����5�/���Z����:�X���eHX- H�D~P�h4dg��͹�`�����>AL��"`6!<U:���`�t� ��MD�19� �Z -�*��t�?Шcj�|1Ԛ���p��C!�O_s��K�اC���������D�#�f@3��+֕J�M؟dQ�2+k��>��F���:I-;����A�G`��r�<����,���:D!�*��%�� I�l����H��\a��$iG܎f]� ��ٺ�&���?�YCw-<9ώf{�����'�"�z������`y(�:�ۢ��L����&|2�VtЖ/S�~3�C��A�sr �3>�2r�IK��������]6k�v3+������)�o�z ts��AU�;'4W�РNkF��+*�(al���<3��)�'��n�9'o ��'�e��^�"����wE�4˶m۶m�m۶m۶m۶]�tw�̼��*�8ߡ�g�Nͱ�)����A��
+#W�^�g�TP�f�L-.��n��Rt�y�X�[W@�o[��� �`����3`��(�56[�e>4�e�s� 閟4j ��3w �Ũ�s��G&�X�<�!%).�6��ѥ��cC�����Fh��?��b�.��b��D�;��Q��k�6+x8�W b����Ơ0Ԡ��m�� 5D!�H� ���%z�xx�Z�O#�Y���5�}s6����݅����}��Cd=lX��&�Ŧ�8=T�Hg���H&��N�m���WS�6K�����> 3��A�S���j�x� ����bAi݌Q�~�zX�!�������EG4pnK�L[n��r�q3s8Vˬ&0.�X�������?B�D>�k�ϳuBnt=��m��[�*d{6�:*������%Rj;KJm4�9�Ѧ�g�0��p"p n�\
+@^��cT���M.�^�|�4�6����6���o_%!02�=5^2?�aL:ы�TVx�����4�t:��8���;g�B%R�@�:<�_�l���Sr>��3Q��,P� Q�թy܇� ����>�'���s��3��fSp�=����l�朄 �Şp8&� �iyv��>t����3�y�c�'] ���F2�, z?W4�>r�x��߂���K�TY\¿�U*3�;�� �XT8k?\�2���������i��Y��=i��m�|��-�i��U�,WH�T���)|��s�^؝�A*���+�X"��Eރ�:�3c‡�q�2�Gy��Pp���>Ɣ���]t2F)��������ҒA'��-(��5#�������;��
+9��L��7 Q48n�i�X�O��6����Nj8{ `�L�;G��p�)ڜ� ���@rՔ�����.S�PҠ�[��w�^���̛�*�E���7��C�1=�rt,�g��U�� P��7Af���c��t��W�O;l���eH���V[��ꍅfKȉ?r��B2�R��%���x�M������:�Dܮ���R�\��p�Ty#�^XBkl�hՉ�[�k���LAGb���g�"+c{�^�M�=3���r͎0��kJТ�m/�l�L J��:L5t��]v؞&�plp�C��_�p9�e�__�
+��A���S��y4sMSl� ՋPW_�7M�-g�Z��\Խ _��T�v ˋ
+����s�ުۀ^n��bPvM����*����l���E�7Do�|4�-�D�j�-ls�a·�'�b�/�U�\c��7�G1�P�����=Ht!��i?�~���8��[ "��)P��Х߿�.�"΋�D+8ʑW�rv��g§"�D�����;���79TN�%)m,Q��G# �O�Y(��?��ʄ纣@�| �1<��۶\^d����d����H�mN��P���K����"�1�i�f�m�Ś\=��C��:� rA�py4b����~q�T�.�T3a�8���<a�w����5A��8;P�S� �Tnk��r#����t5�md���X��N��#f��cv�h��t#���{���"囎[g/����_,�AƒOW.g[`�� ���� ������2��AC�`n�ݦ��?����s0 �S�6� ������@Ș��M�Σ�(X�I5��ծ�_����Œ�Ҫ�^U~� ͢5�*��qvC�Hw���7R):q�Hk]��Ju��Y�&��?��s #��ia��V�9��j�a���q��2�&��<b�� 6�,�,�B9�60$������Òr4��C-�����xL�A�t��@!�ܹ��ڳ�q?����m��I�%�����|�ؐ"��m�9qК�F������P�\TnPOC�r~���"JkR��aZ�{�s�`u+���o�17c?�ri@���W6�[��J �Hq>0�3�d�Z�/�^=1F�"x�6����jwqe��NBw��u��o¸��o�"��W�k���/ y�@ފ]�˿���Z��;m�e���2��5\��[��[-c �Ǻywr P(%�6�'iwK���m��U�nX��q��l0`�B�J�Kz�UgW��=�xA>s�� �����S����C���Wj�+�p�Bj[G�r�=S��Llx����o]e�SV��C-`�x<#��p2^���^aHhC��L�%�b� ���#8���� |g�,\2Y�
+u��(�_�i�%r�^���g��`lOzv���G sj�]t|.\� Xw�/ ">��K��$���L�{�Y���)����r���:n򗘨]o
+H�9�����^t��T�TI1�&�+2'�b]f��W�
+L��ra'����%��N'��ҡ1�(­�UiN�w�w8H��X:��'������G+���1K`���c�,�s�#�o��U"��
+�~�|5h���B��պn~�B�Jv�nњ�9rM�� �� �k$k�f
+m-=��m�j�(��C��Rb�Y��Lʦ���r~�ěnM�Lg�`��jƚk OƁ�3$G�I���
+ŗO4^�០K����=�b��� �0pSS�PW��eP�K��`Lə����@��ʂg��p���}���<,Y�=���D�3!C:@ �\�~-�����U�k�x�s�i0����7��},�̤4cD5���pq<i�6/%P�0P%�.�,b�t�����3Y�ll��J��A��h�N��D�L=�-;"�L}�s�yr3?�[~)j��x�Ka��goq�[�Bl�G����:)D�� �Jt�M��x��S��yܟˀ��wup(������"h`u�X�2ѺU�fl�ޜ�M?'NV.�e!ǑŒ�O�z��r�����|/�$�-�U��;κ�>E݊�xd!�$H9�s�\����m�������W�ܷ:��B��Š�%م��)'��T�G�J�9�*��N�ں�_1W���)sC�� ��
+{�Mל�ػ��W��~���(����+����Z��f�R1��?]�{�!��1.=)�PD}��`* QO��7G�!�BN��ГD?=YI�x@-�j"0� �^�&SwJ�4*9cy(JBe��t�I��|u�ȭ[�j�:Ф��y�_~��n���H܈t}�ݡ�4"\�&�)��C��ZrY��[� ���V�����3�Y��]�R���f���-$�;r�j`���mi��f �W�q�9@=���OV+q��;�nK&���������n�y�4yٜk[?L�&U�⚌Iz� ,�J��ٗ^~��K�9��[Hz�;�cV��Ԋ�Y���,JO�1'���
+�=���&.KL��i��*�JL� /��@y����`��CTC��J���q�X��`�N7�C�|�����~5����v��z8�n�;��FF:Y��
+bbE��C�J�pJ����W&|<Ip��jܕ �
+ϐ�߮�q�� �z�^��6��Ύ}��M��|=z�~6~t��U�O�����3^}I��z�0'+��@4������;=�k��w��̲f �,%��7�}�[@�첑IQ �y
+�*�a�R��j�S��$�![�|Έ���;0�D���h�k� f4̩K�`2-jQ�?'�pRm�:��ր(��>u�uU�)��qH��t;n�-���'Ix3r�n,�Cw�ta�Or�$_6�%�2>�}rJ��J~�#����6��^���� ��7�Tc��l G1x�����Gy=�ښ�m$��4��`���e�(뛑�/�G�6�2�����|�������u�UV/|A�閔!�o�A����t!��Pi�/�/�>cO�$n�E$�uW3��A�3����gN?�Ŏ��Όk�pV��x�ZٵB��/n���O�l�9��#-/~a�-ҝo@�8��-˶�5���Ԉ�D�jX�_�k2<���zf�8"�}����D-�@i�_J�m�@�.���1>���������� {K~�^W\����5ZR�܁�'7JE��,۟zJbx4,BT������C�N��Ц�[��2��5j�V� :��|�`A��GUn�K����Z����vF;}�+���N �[A�2�����K�!�ޙ�����[�O��$�����}����'s��|�N sGbG%�!is� ��M@]����������5-g�U�iO�)�� �M��p�fW�)��������sU��IM��Tl�-,�W\���̒)j�F����(@һ6r}����H�=G�h�@1��)SV�Y/�2����1��������)�<ߧ�ڈ����F���$]���� -IU�!�k�( L�C�ʅ#2��d� �f{�{�Nf��N��%5Γ<y �����-x�����H�.Dz�E�@ �����������Jy滥ﷰ����O�#���_�� �b�;4��Y0zm4RWe�I�t�@��:�SL�����P7����) j�X@�^0@������(M?����x���1� �B9������}���"�j��(,-V!\N��WU�W�b��<c�ˋ�}�y6���C���PY������80���a~ y��6b?�UA
+�?�|��R]'�K}���>6�m^���LgN>Q���˗����e�%��Zh�x�rvK�5Yöh����4��rL���P��k*�+}�;�I�4.���~�>���5�?��Ȑz5����, ��p%��߸��in� F/��Dˮ�C���P�����e�ɕ�L�"f�ȹM�^t�zL�y_��U��#���խ-�`�ͲȈX_�y��g_5f�������M ,��&R�����[����� �����(�B�'e�e�NT}W���I&��k�5�;E�fיy�U����H�C+�������P!�_0��=z42�f���b��V,0�J�6*��0�c��3�it���t.i�z���X$쳦8�� ���!� �f�s�)⁊��.�Nܠx��-���Ѿ���D_�^5Yu��c^�"W���U�w�2�3k\�S�D�!+΅Ѩ��5�cr����������.�IB�tT�֩zB�3*�L�9{��_ !I��]��W��aјJВk>��{^�;W���~��ć�)#��������u*-+�BH��y��� �hHm����٧��u��J� ��
+/�95q��A��-:�6`>>�2� ��<����� ��u�=���Kw'��] o�.�|�q�5ll+!�\خe�Ke-�ݱ�rARFE�1����_c
+��҂�����>_�[��v.�]���� �MIb۠7a-c�r[Ζ!;���Y�D���Ф_��>��(6-?��P_v���E‘Y����D.�h����T`���5f�|�ར+�=�ֆ>���81��y&�ŗxX���ݱ���A�~x��gT�>3Nd��@���w%�)�4�1�#v����n���?��B�Q��46�aPp�} 5ۈ��+K��D�|+q&�J���H�ٓ�,�-�>^rW���2��L�<*���*�e��Gn��\�-�8>Fb��H��뫢��u�}T�'XFN�������$��"(L��[hQN�(5�˹�d'�MrQ���ӛ�r&e��ϯX�b�y�/0��"�3���PTO��-���)ʙjL�6~;0��>Mi��T�8- g&g~�/�vQ9�Ĥ-�^�bA�rI�*����o���m���,�w�ܬ�?��*�"�v��m��?h��:�(�Ԑ����N���o��գp����c��Ccut�p����ӣ�t��A��5�y�d��`��X�b�*�k눩��^�}_F,;˄p��~�O"�+� f�vژ����LZq3�z�o�qG0��'ɐ����j�lL��z� �c�f�>H�f�a=4�:
+��WƱ�b��nq�� ������`���]������:(�}�y߶ǂ�J�L��N�L�7p�qhɈ��f���޻��W��)[0�?Yt��#ˀ����� ��o��&0㞕�`��j�Z�����d?�"�!$�י�u
+�o���/�v����C�{�锔�! ��;�蒪�Ҝ�D�Vճ�R�:z�B'[�s-�t������Й�-��|T���� �n�9�K`6�Qv�tX�Ҟ��w���?̵ńw��* p����>2�\X<U�3�o��c��J�,e�C1��"g {�$�]��0�� W�CA!N�D��M\��� ���k�ٙ�$������x��"��n���r�y��������
+���Q%{"�.3�)���Bw߭A�ֈ+4��;=����}j?��&��P�Cb��l��P۬-���jQfSS0����b&����q�P0�L��
+�J���p��%-�e��t��)��C%��Qy�\��|�+�9b�0��fо�{`�;�`߱whx�h�գ>.w����6��A�
+}��zжD�MN7c���ݕ�K�:��m��ʍ�ذ�C��� ��B���Rj\vݧ�$XJ��օ�U�e��r �}҄�ſ�ޢQ2�-Ҡ��Q^�P��OM���|��Su��螒�-�p���c5�>���bil�� S��U��8��-~�ɭ�U�w�ԱQ:)��,�O_x0|�Z�F�J�u��Y-�?)"��7[8`���∪��2� B��9e��"~��L���kI�3�A�)��ğ�R�g��+2xM㨢�nPV��C��� �n����v�o _@nNc ���>�3 ���ϧ�y �b�i��c�\�ZG�F!��~���̦'�F�#�� ҽ��ж�n�
+��G?��8��Y�P<��"�z��ݢa���9E@�.E��5jm��纀���݆$�V!J�V���q�u�6��'��<w�zK����%6�@���9*�.�vq[H8ގ�ǖ��v#I��7�i������ٙ�x䠫Sf���K�����I�2d�Lơ�m7����=(�u�y���Z�ӻ�(y�e�6����C<R ΋R�g��^���� {e旞`����=�ܩL���_�uBǸ@�Pl�•�q�(/�n
+�L���&�R�u�wٵl�=?���B
+�/��e�>��b[oI���e�P���D��w�]�$efZ��ܶ�Q�hq���b�j���ߑ��Uc���w�U!
+f�����?�]�ya��)n߁u�y� _o��G�����cr ��G:�;x��j3��,�͇��i��������b��I�OK�a ~���(ٌ��Q����E&z�!r�yW��|5�|�D̺���.a#�6n�F�����W���-��#�s�;{�x� �;I��G9qfѦ ����!��p�N��Oh/��� ���* ~��qܯD�%#+�[
+<��EƑ�d Z!t��l�j��p2�P��]�۳ =TC��]ҽe�N��U;d�l�Q�[�a2����
+x�ʀI��|N0 L�%�"��z���ʟF�^�B��a��e��i���,-��im �� +>20M��� ���������mL��f2��!}�eR�.��t�|q��샥 =�F��sR߲`O2p���e�ӝ������Tm:� o�h)�R��/��O�6��ذ�*�U�H$i���vT�@��~�V�?.B:JKRZUc:~��x鰐�� ����F�QOi��u��T��0{i¸,�yR�V��o�ar��i�Ǣ��P���v����٣/&Gj։Ҏ� �Ĩ�me;���1g��H@&7$I(���$�]��m�9S _300+_�I�m����LMyz�q�Z=�n��ޱjw�u}C�O����cj�,��|Jl�����xs޻t?����F��L�z�� ���7&
+p�^E����z�-��� l��4�hp uw��M�w8S
+�Η��@9�C*a�C�w�{�'u��n��P͓�G^���4����o��C.c�@Q���D�_C>�2�6'D"�⮝G����$Y�����M�30>%=�@��t*�H�$�0N� �eJFIS����H���� Pn���x��eqX�?q��G�j�xgExr �\��'�� gk{�C�M������I��O���Ǡ��R��3̄.�5ٜE�a��j���ӻm�M�� ��?~-�%�bv�[:E�� ���Xw�F��-���~���A� ���
+
+�û��H>�]j}�#�n}��$��?æ��=�-H+~���I�Z]���Xdg��䟇C}�\Hb�������[�^��DL/�>�$5�BF1_�b,�͡������0L��|�R��x�D�hO�.���(�?���Wݰ�"�K�Q��<�h���^V�r���,~�(+>+��Es�S�|)�%��Z�g�Y�ye����}ƙ��OD���[_��9` ��a��8�M��%ΠҊ��ލ�⛟syAݐo1�E�E��f�������7S;�qMJ�ȿ�{{Wt�m�������^��e�}���z4m���F���`8_I��[���"��Id��C@�A�~��\��g�f��� �� ��&�J�PM���[�5w����ʔtq_#��%h�T%���UV7"�K��z��t��h�RU��#I��cO�%�ޛ���0qn~u[�YAu�MޘsDW�C����z��b�8�^p�a���*� zbL�d�,�9_�hi�}�L!7֩� ��s�I tZo_Z�1�[�ݮC�3d�(� c���KBS�2�2K��+f�$С` 꽣���{����ք�x�g���|y��?P#�w��k��XU��y;�v?J��>���E�*@�P�C��c��/�� ��*S��W������:���6��򴱊����^�*����3mKf�Q� Ho���1��P��[F`T3��1�r�h0�6�C��-� ���|m��$�ڽ�ġ h(w�b݃hA�9^W)��w^td�\�&�ߨ
+�_k��;mK� 1T+a5��IC�X�)l��*��(��WI�KVr��Z��`#��jz�"�� �fe�ҮU���DN����D��Rx�D��a?zP!bY#W����S(����6�R�����묳��HD���7�`�6�˱߄Q�(����K�̇^�Z�� �r��� Hi�z�7+l0�T۵$Md�\�S̢�� ��
+��a1������(���d4�1��M���7Y19y��eV�i� ��9��!��2�Q�h٩�,��z˨f�f&�[�E����l��Ɖ�x�o$z�8koÃQ:n�����L�.�}Y���3�b�
+ (�&��b��h���qV�0?; u�C��Pر��iy�r�K�aC/u��0y��\��Z��I? �Y$� �ɶ���^= ��K�Eg$���{P�_��
+Y�����S�,%.)X��Mz�|��:�!�����u4<���R8ٹ��}L��{�W� ������5^I@�6V�S�KH��'�rxR�n JZs�Z�(�_8<�aͅS�� u�N��������6�t����cؑ�?�l�аb�3�+�S<�F��O�Db��qmx��o��D�'+��KXNmTa) yC8n�*�m����Q���*�[�5@�P��( T����sY�D�U�{w��n�����w�.�'����@�|o�vԦ^Q,r�o�z���;�߫�눹�)�U�l�q�Z���Z����������AGF2���C4M$��zbE�Elb����I `y�c49���z��d�M�d�]kPۄ�0`��(& �x�m�VO
+!��0�Dh��I���x@�Y "U���rS��2�Ϫ���B�1Z]�.9o��|L�Sы�[ Ɗ�����4� �5^Q�:#>����ըk�Z���2�wCTS8�� ��ψ���4��GP!��b`[nԆQ*S����ƈmF�:ʍ÷�Z0X�+2� x���U"�ht�L
+3��(]��eEo7`4� �����Q4�ы�`��A��\s]Vр����k�IP������.���Nv�
+�, ��}1�����0��6�|:����"J�7���zصQ��|��&B�$̟�.�ō25MV�MHߪ��L"�������ޅ^��h����o������i|���N�K8�H�:��:�Ή�m�5m�
+�U։ k����f�l0PO�:�����Pm;)� %��f [N%�{`jF�lU-E�iA��Ev�#�f%r���wnm�2�V�� c�Ÿ,���-���
+��ƿ^9bz=i���N~���j>�3v�m�d��g�ZS �|��3��z��rؕ�R�qʘ��WP-��K��@�u�e��`�� 6Iw3LX��g���.l�p�_��!�X�Lc�W�U��J`�h&����3.����]%���p ��>Fm_�rppǺLS@�N ���0{wK�B_V���yE�� K��u`�E��<X�:��]�2L&�/1��V��~0GFA�O�|�V�D�r�b��2].<��A����Y iUH�o��ƹ��}"R2P�� F�a�!�M������є鄾:������.�W�d�iԌFz�p���S?�^h��b �G&v�Jr`�.�a��#8> �Q)hs.[�H���I��*L�Gpe(�&{јʗ�����js�Og���P�{ܷ�;A�E��{ϊ���Q��e��Z����ڀ���������cϿp�"���{�L�� �K.F�����zq�>`���������4��y+D75�b�櫩^d�-�\h�'���8��L`J�΀�z����6���uпJ���{��y����(Sz9��@��3aokޣ?��ﲧ�CSdn��4c���\�b��OfJ��L��� H+OR %���Z�hP��w�[i�*�l��
+vY�v~�
+ Y|QkK����a�M�u �-��p#�1ݷ�F
+(ow\����4TD��k�@ 1�bL�Ȟ���ƒ/}��ID�e�Q^O�$��Ϯ+vڜ�c�L�C���h�Y�j44�4�<a��줁 U��6����=�7=��j� H�������/&;�”D*�+: � XC���@�jP� c�"�2���B\������w�6U�gؠ����a���d@�@�Z'i�<�P��y���OX����'~;����]�U�`2��I(�v�`�_�.�f��$l�.�7g���
+�5eSD��D�9V�v�ƹ�?�䝃�.{�0Β��G���V�s��Y�A�Ż�-K��*�U0�W�E 4>�ٳ)0�|���h� �@4�6g�>]n&�%ʞMF���] ��gyC���%���_� �����p�_ۢu��8qD���|�B��ƈE��Qq.ͯl�ߟ����w�+h�#.kB� e�/�Mޜ#S�W��ۍt׼^��/���[��y,戓 �$u�9ŧ��!�o����/2Sj����{t��`wZpP��3�T߸��M՟-�\���)���6�"�/��U�� ��spOUBJ��X�̣���5��fx�1�O�(�R��(Mq뢱If�N_0��=�|���mo��z��ɴ������>�01�P�iA�������^+��|l�s ��:4 ���7����v���2)?��Bm����H�^��O��_�W���sM�` Y��Zn
+7�2�K�/�} A�����M��� ��p�M*� �_|g2���%�����ue����z���_�o�� �n��wrM��"����
+�I���̌|ˡ}E��k��$���6SOk�5Y�/��s�S�dհW���q�s�K0�J"�@� zWT�� ��4TRI�����CO�_�9�Ug-�(%N�?�J2U��$z�])�ϥce����3����j���`�<CM��\�47�ty�i� y=�R�����ő0�%���jQ$����׉8�T�h���%a��x�����>�� ��A�����Ϻ����V̊„ h�s�x�rMy�X�K�hk 5��Oj�V%[z2l/�����*��WZ03}���-�&����^T�+L �ҙfL�4\zz}��&}L��8w�&��� 7�Y�+�a�+����J��t�LŸԽ#L2U�~G��ˬs�r�̂�!z�2����c� ������7��+�����ȏ��y�S9j�O��4��T��� �V p�X��ܜo�u��d�=Y4E�0?�j���IП���:�8t�z ��3ZGqZiP � j����b��K���jْj'$ܙ5��o[>y:'F
+���!�zב�F���7C�*�=d�{�L�\����= ��,��T��Llja:8�3����~������ ������𦛷��R�wX(֌�
+��,��^v����&::�LZD�>�}��L�<���2ھ�:�f�$X[8�1R�*�h�_Q�"iH���/���8��ٮ7'���lhtt뚪��/g�
+�4�,�z���o�� 'M���:}|:n��A�S[h��p�7���^� ��
+G:l��呑qЃK�) wy����U���su�|�oϙ�?��:mj���#."�"W��0��A��v0K��p���j9�����%��zcj?�{�ϮHff}˼l�0�/_\7}D(��I��K��_͢:N}�C咛�� ��K�7�˽�IO��WL����: ���%D���u�����t�j:ou��=���V,�y��>���QR<V�����]�L�K���K+�P��J�2�(�\��d3��<�/da�x�s��$�u���(��%�Ђ U��� �"���mDr9
+Q�3C\�OgD��n�������r��.
+޸�DK��)�(a�[Ȁt�h�Y�t���GqR�6��K�y�]�6x�WA�6)����zظe�lb�f^|��깣��o�޳F\��1�e=!Cr��y����1�S�h��փ�������mdD�-�>Yw:��h� @��sk����ؐ7���퇣50&d&�7з�G�šu'Z[����1
+:�|�� �ӄ�b�3��ymo�˟��d��zR
+��s�ᭈ�N�6�v5�|�y3�2�i�2:-R�E�WI6E��:���ʁ�̨�<�&7���*8`#?nX�O��Ol,T�� [3�Ͻ?��o!"d8�Z���˴���.�1tH(�p v ��n���`�����F�?1��Y�w�C�Ϻ����1������d�%K]$����U@ʓ>�2x^4����Hҟ�Ç`�*���r�?Bl[m�7�q7���2i��+�2����զ�C��f��\`�1���������xK*e��];eM��#����gɑ�nq R �+��i/�WQ^� }9�v���|?�~^T�\'�D�n�R��wo�7x�d�"�����NW� �zs�|YJT�̓t��)����P�5H 6���$��������4�"��Ƥ�ݎ$!�
+��-���o��G�Ll��;�X���7n�!�#����y�� �r�un}p�����.��R�����~2���*���0zH�^����U�ty���$���e,y>PY-_}�r�-�7�4�$q��){��j2���N�l�!�хT�x }�I/o�j��`�.�E�ɞCȸe��;��>f�|>�@�y�n"NKu4ו`��?�" 3�̱D��!9�;5����>�e�S��r�{s��T��7ۘo[�Hͣ����
+y�S�GE;׀�����5=���}� 0��K|P� ���),jWs�'F�0��������D~��+*�꧈[pZc��
+ B�ߕ�g��Iu�3(�u<�� � �"��E�0�r ���_�7���U�#�YV�y3n�w��� K4�g&ۊ��>�J���<rS��.�P۟�|�������f]�lC�+��־��GF�:�,+�2���{2E�t�MCFΊ�$��_��� � Wy� B��d��� �~�U��U���o�duW�|�:;���zCb���$��9Oi��w|�� nr�
+U��6�
+����PA��ZR�©�K������iA� �p��1}d>��5(��V��<�I"��4T�os��,S�����QB��F�f ;��T����зKj�����y���:�l"0~�3��f�${MU����0�\��+(�gu���?=���{@�ˈ�d�w���%( �R��~?)��ΐL?��CX��C�D:��鵟�8XgN� $�5uh�`2��β���!��PA��ş�M� �
+��B���{, �P��sg���i�� �t���r)�x�i-�� ���Bl� NJf��Ι1��������ƚ9�>rl��������#�:��l[���<|��d ���lg$�e�2-�ݜ�K^�ꉳ��p�M���c١���R����[s�(���~�~0=+�y�t�u�X׮�ֈ��C��"^�!ث�(�co����Kulڭ�����q�)� �ձk�|�t�k�>�����N�d5s�N�H�4��+���W-k�f�K�����נ�.L�Ԓ�u�Q�!���-(���-��L�I��?�����lqN�43�թ���Ҥc�ϗ����ܫ��w���C;���� I�ޯ��8�@�����?H�0��?_*ǐ<V�y���R 2lc��c�K�J��Hc�aH˯qZޱeS(�a�'k�����viv���P���ν��m���8�jȹ��ۊ�8]�� y�A?OڃoM��+�f�;���$�͂��聢b
+ ���R/ �5�9�޼SM|��E
+J�hq���X���$����q�373Y�`mk�8J���U�
+9xP��kRc�q��0rv�i��s�}�4�=aCIcq_���4�Ú�nE�s�G��(5���v���>�# m/ ����hk��A�޺�y� г���0�E�´-ŞSW"��C���k+UBP����� &�^�2���p�107��uU�n`�W�$X����r��H��lj�����Ʒ��-Y_�Mbs(46����eQ��2P{c�o�C�u�>}�5��w�vM�jB�|��uN��mo3�y��Bt�G5z5�V�h�e�g_X��N:�=?nf��[�š'(�o8C��z����T��! eK�pd�ӠY��}�Y������c8}�DV��9]BR�fUQ�R�����x�BS-�ez~�b�Sj�o� cR2��5�xm�B�y+y�* �bk_�B�m�s�ax!UW{�V���r6��ISB�l���z�� �����R�
+xc� !A���!U�j�����r���vt<'�#/$��ghjg�P ����\�֦����Zi�b`�`JĽ�+����&�JT����2f$���X_
+e�0U�  ���䓡=�����k�l��i!w��-묛T�5�^� �z����s �`N 6+�%ϵ�P{q�T�M߫ء����tN���U|������ٝ&`����!ݰR*XZ�",�Q�R���; 0ޛ���еr�y���Hj<!Y��{m6�@��Gg0�8x�C�N����ѼD3�įG�E���>Q+���^ K�c�e�8�3���T���-�Qo?���?��|ۍ@NK�8 dT���e�{v7���7�B�`ڄ��A�9V���� wۊ��Ktn��E�<̇|#���ހ[m�~��a<p��2�}v���ʓ��[ �1�3e}��K�j�W���G�1��R�-��o��ҧu��|�L&�z�g�< �~�������LZ,<��eM�~�gRiZ,p�*s�wӓW��#�6+�XA�8ԉ��x���NO_� f�ؠ6�T)�R�W�$��4�|��W {X��=�h�Ia��D'Z�n�~�G$Pg�kzҭ�t��b�  ���%�cW��>���-�����^'����t��9_Oϓ���0\��TD&?9�;Dp�/�T����6 ��%��H#����7fK�1v�����k�pKv�i��gi�*�����>��8ʒ(}����7���*�H��4��NX�Z�+����m�r�w��! ut��sF]�ꌊ�y5|� i����F��>0S���<B�zְ���s}�0��.�U���M� �[�o UW�{�8p��Z�� `�1�#A��-�Q�ݥv���-h�5�X1QՁ�"zQ*�g�Lo�jT��&r�oI������!�@EN�^�Y1���vD��X�~��r; �T�)lDe��q����Q$;����'�|]&�<;��P���̿��/ɻ0{ʝT(�����߰?�Љc=��'~�|g�p�(/rkm�!�D#R%]|+������0���)�@ꍧ��Ɓ�3�~V]j�������:�%QDɖm۶m��l۶m۶m۶m�j�'�m�r���e<�������c��"i���W��GkhCE��(���#6cN��<2=�a8 � ��zg�p����ٶ֖^�Ν,fX���) ��]�7R$0.x��!]7˻�i�#^�}u�����z�t-V|�2�j���@��ȭ7z����k�*D��_���Gp����-x$^�<�=r��ϰ� G[b�Y�`v8�جu�1LOe�I�����zX��9��O@ �}0i��m>�����7��4@��1�<f�ZI�'VE�ƛ��4����k�!V�ۛ8EEX�x�� �X�?]X�/�@ȟp4l ��vp�[S��An�ƯM�Nbx�#m7����!�+�Q:9��XB��vT�EFd3�g�M���\�Q�D�TB/�~5��K��_ʸ$�̼E���Rg/q�_
+E:e �����4VtмX,4�29�,�� �K��[����x��zE��Y=_���s��A�D �&� ���i�eMr2� ؘ��Ś:��#Ei��y��e�7��:*S�%�ƞO�a�5�i�2�3�l��z�62�����AQ C�B_^�fuK���=��h쟕�ݥ����K��hC�Q��T����R����X��Xp�Ζ��
+V4�D�Ay���{�4S?�P�.��8�gr����y�',�҂�ӱO�}����k�`��z<���T3�>]�JӲ��Y�X=�'%6�J��;i��4A����$�����V�G�u�#�� ��S���v��@� Jձ$og����0�V\m"7�[����԰g�ʼ�$(ˣ��<e�z���X���>C�d3�J�>:��K�XȚ1Q���U����T�� ��*v{�q��;^d���'�׌��@Y3���tOT��m��W��Qo�1��R���-\������s�CI�u ߘ)N�O�Q, /0�\T�e�)t�WޚW�V� ������0�B��a�\4�����.�%���ڷVK`NX�5�kQ�4�34.*������8ErF���Lq[X�Gc �eJ��)-�����t��3�<�� �QN��2�Q�%KE*��&KB���W�<N�����1 a���a���[�|u�����:Qs0�qT �?o���xxCLl�ťОD�.�a
+�:���fF��H쪸�d�I�_ das��f��Ktw�>E�f�%����a�������o� o�6 Vɮ�%��C+�z���+n�OƘ�\����h]3}&��RK���"yȻ�۵:�`���+p<p'��Vl�<� �"����VZO�� K�SG��4����� �+L�Y3����1}����T�Ƕ pa���Sc[|DV�}.Qˢ�D�<��]ߦ�I3*^��S>�N3m�T�L�G���"t0�W:�g�����g�SbW�tw��k�c�����6�rk&���˅���1u�vh,�n�(� 2G�����O����0T��"�����
+Wo>��6�/���m .-���5��v����n ��9��8��b�L���p`���y�%T��t��nk���e�kd��&�����'O�nL�&�A�gVjɱ�u����s�8%����r���_RXHaQ&�:����%�u��A+�tWq4;� ٱ���~n�=�����'�n *��ܫ\�X�0�p��1���Ou����?�&Ĥ�9Q-I�|��EcM^��SL�Y� %�t4^��Sw����UL�FDeD�m��v��^��(� ��;�c��L�Y;e�S����9Fxm���dƀ���������:�t��kE��}���}1ߴq���י���ƺC��/�%3wH ��,��H~c��5���CCGh~(�Z?�H�̮n�.��"5��4���ҝ`�k��x��>M �薈� k��&��*@ ��R�2� #(K�RLQ���e��D4�G��`��¢Ȟ �U�@q �,� �7��D^32gF�0IH�8�p��R|�#�AF�J��|�ӳ0J���uzis�8FOp��Hv����\�0 ���>Z�#W���ga��y8�B�.\][�-YΛW�b���7 ���6������MH_bn<�*��_N�Wx�(I���Z��iwn������:f�T�� P/D��BTC�� 1#i��`����H���ex&�Z�>�R�o[��;�/����k����^��/ҟY��A�p49���!G��Ѐ|ZOgbE~ 5��w�l��[M�36q�V�6�25��`���7�P)���9r��̶8 �ɤ�H�u��FXo�
+7��yd��4@7(����"!��y7�>��SX" �:�� ���=��ؑhsr�/�ܖo��2��z���h~ �<q4&�����j��C9��L�}�qAwjҎ* �!$mH�����a�R��� �� ]���H�}m�K����|$��"#��ǂ$䋰C�� �ǧ�� ;��i����Eiv0W��Y,� T?�}�4��sy�&���[��o�/){�\C%#��YnʚP\!XU�Ƚ(��Vc��L�{T>D��c��~��u������<�)�BӃ�r���9�����?� e<�]dE�X2���/ ������t0�1�k�]�E!���d؅+���|s�E�J��G�Xu7�1�b�<�W���x/�e����d��ZJr���p���NW�̸-f��䦫i�o'��'�Ca<�!��e�}DZ�}�$��Q��P$��C`D�N]�¤����ڼ}3ɮ��1?v�Ə�#$���ʓ�4(��jt��c W�SL n|l૚��q����l9jK�q���'~��@��!�o)J��-k@n[��zŶ����n��]���F�m����*�wqmX��y~iȿ�-��(Y=k;?��X,]3�Ȗ��wƄ`�%t�V�[�e`�͜B P88�N���`� 9�Hu�� �P���XV������;�0�)@��M�6=w\�; �9&���)��)���ȭ��޵�8;=�l��䛱L�p롏?-� 5�V{� �]�z���1������6�������Ei��\� =��gHW�9R����C\>6HI�ѨNA�ڥ�� i�bt��ۃ�y��_[_:aw�0���� ?o�[$�8�2�>u� ������&��Qq����������/�N!-�[�=\g���Ԧ�V���Lx ���{
+(n�l�)!�ߩ���7��Fd�.�ӌ߅�?����Y�Z�7ff�~����'/@u�W���}�.<&^�6�#�m�]�l�usIH"v �~���R?i_���H��ǀ��J�$�d��ʏY�pk�]������w��p5�m9sҌ�<.[�^"#މ�~��_T�1`?�k0J�+2*=�j�ڡ[�i�<�G�g B� iٽl�r*>Y�S�D H���K��w��Q�;^�b`���?�ٿ�?�F�}�w�:rk H�.�� �� N�ߐ�Yފ����nP/�)�M�;͖N����rf4�3������� ��F��Zf��a�gzۙPճH�ݤ�D�L�L��j(�&���3L̤n��O��xBX��� ��J�Ʉ����C~�EM�ݧ�fN�E�=-���^k���I?����a�\[�u,7:�v)��<��H�#Rg���nn:���P)� *��-�J�"�́x�?Ɛ�ց����@_��0Yт�
+>��'��:T�<J��79��Ӭ�T������Vo��%�x��%���4�F�p���˝��k��]�L�
+�O��bUtM/*���m��1��6�����-������T�p�bڷ[��`$Lҫ�"5MX�{�?�� B掞��g\����@5�Y8��;W�1��E/:����L r< ;M��y��B��|-�kє�B� W��<��%�f�"���N.>�|.;��)1,W�����ͫ�
+~�$�qC� Œ��
+���^A�ƨ�mή[hW��[u7�������xJ�Ҋ���<� �7u!�$�4m��tv�c��Y7w��J��n,$C$O�J�c�M��ã��Ύ��#÷8X�&Σ́-�&��-����S�X�x��� ़aQ���G�䎠Ǯ�?�S��e?c�UZ�4����-`v9<F K#h$េ�UK%;Վ�J����!.^1�#r��J�(#?oo �r�?�����T�Z7�׉cMZ�}�Qp��r��J�& ���e����fC��Y2��Y�$��,�eqˀh;�JJ�!����)�-t���籔��C1�F�->���E4��}z]���۵���e%�d�,� t���V\�Rl�˴��@c�}^Ś�c*0�v�fC}8 Tc�L��"9�g��|C�0L/�BsHe-��������w���>�rk��eR).?G�l��q����>���%l�C�5h����&A@a8�����#�Y3�E�d�Bd��k���ir�r ;�5��ž����ҥ6vf[o6 P ��l5��Z����~ab��N�/���9��f>�Q耇���%_F�U[nl���ǭ�)���P��/(U�CU�A �W�RZi[�������������^��Ko�#�n
+�����Y)KG
+�=󷭙�K�M�΋�"�ЮUH���QU��N��Ǯ-�&���e+~e��j~�0 � ��$0�\��5#�2y���e<�]�#)�Qx�V��;�x5�Rm���v~���s�D��i�l|m{S��a��!�B�,��ꤊ�
+\]l1S�:x�� qx�Jb��uO5@C a'ӻ��ք�l �~��7a��B�g!�RX��G��z'�}������u�� �X��J%> ?3YK�� � ��ҽ=�؎H��Z
+ �.�&��>���b�1Za7��?fLls���D�gOl����Q����O�N/�L�����N����g�ˍ
+�Tʲ��d����<ĭ=���n����47uX�CѶ��!����5>z���H�t�C?@���6� �\o^�s�A��W��j=�����bq���!Z[����W�Oo0@�� ʌ�}��X�zU�b�/D��#��J��(KN<���Fv���w�Y-h���G�A��{vAG��0z�e)�ʛ+5ٰC)yEr�#ݩ�&t7{mB�70�Inw;[l��/����c�.�e��m�WvS4���GmKW�唀Oj��5�z=�0�U{�!r���&}�L�|���ԡ�K��i�/$�q��h��0�" �K�{�d/Y�U����s�/�\B&v����م�3eƷ���h�b� $���W����������_�PTg �I�d���0�ZQ���Ԥ���]a @g�+|j�j�DV���Am}�� L��[b;��0��=�q��-�&%�\�D�&��޼���_Cy�Z� �Y�͓s��-5�8�tm��/N6��/G��P>L�y��7�5@���gJؖ�˴��c ������O�W���#d�����H�X�vc�v���2\Z�`��P,�R��(#)�ԩ��e��*�y�0�G`�q��^�j�fD���.��uԓ��57'9�%��aA�Hlv���4�A�j��{yP/�5���s4q��1 �P�7p1C;�H�UT~�""U֋l�|�(h�:P�@���h��7�"kw�g�=��kvs�EfjߴV�F�j��u�w���0E��0�7�\�>�OOY����E���A�MB׍0�'��w����9L1w'Sfǡ�t��� p-��H�����S�H-�cwp�A�����rZ���G��1�T�T�G� ԑ��y'0M�zH�չ9��S�!�is��oP�ݐ�`�%�ّ {�^�h8֯PB�p��v�rF"^˒�Jt5eOFj���3��<p:8�:��Ee[VTbq9,/��\9ʙY������Ԋ��W0����:����Q#Q�}i+�&z��n����/��`pV�{͸�� �+\����g�,�e�e�Q���bb�������Uvb���Ȁ|yT��Ѭ[���\4�%ln׉B`����%н}�zۯ��'�؂>Ф���E��+w�PWD����SZ�:�3�\}~$>86�K���o�w�l�۽�$��,�ϰ�z%�f0�0�<بK�V�p�)���� ���5��Qw0%m�����9ݵ���G�_>ig�����U��imb��n��:05�� nM���JT��I� �����i�P[��V��)=�AVu�8��˖9�F���*�Ez5v=��4����7T�P{�����zo A'_���E������P�s��{�x�fd��qL��T�;h�ey�K>��,v�5]��c��(�:`�G��<����㍉� P� ��
+�����*ɲ���H�=��Ȝ�X<�.���]�u��=@��:}22��m�=��͛�"���J
+}(f?$��ՂE�a��/��N���0Ȭ�����A��K;�%Vs@D��UL�����0,��+~)5/ ��L����&$���o-�l@��y��G� �["�LYex۬�8���txF!3[�� �$�?O����z����yW��~T,a�HN��Qz��QBcב��ZV�:��I�2��[�I ��~�#�2���r�ML���`\<V!-�z����Z��9�2X���c8C罕%���s �b����up/�� ��U{2[�9����q�v����ѹ`���OE;O"�*���e�����$F��%S�El��H;(p#]I���k:5~�h��'�C�2���&k,�U��6�<�G��bB���B��8����T�3z�"�wP�2�����6�O�,�]�{X��ۣ>Sۊ�k~�y�������{zP��O��(Q��'�y ׾_Z������U�� �0��M 3?�_@ɸ%HK����$�\��n*hb�V�� ��3D�4�P��P���"��LQ���v~�-9K�0�z{"��D���MԸ�:����y ^!�'Jğ
+Y$���'G�$�0�hgY,�]Ml��M��C���Q��Y/(B2���B�ڀ>�X�~�� 4��my-�G�hgd�Yg�Y�P�,�ӊ��e�R;�Ƙ��s&��cn��O�j�e�3<�`x��pj���OrJ��XV�k�]���3b�F��N��a$*A�7&�����������}U�4�s�������g����D�� D�Mܳ��#gT
+��ZE��FY�~�U,�i�m7�� 7�"�NGQ���]� � ~m���4� qAl����C�hchIJ2>�*B�g!ɬ�rg��� E��-��@Ti�3>��]�"1x���H����ޫ�>�-���e͠P��I7�2j��?��
+|f��i~[U�l����#�_�k�3{0� ���5���O�oYx XU0�Dc�9�����L�+��(Y���jݵ,#a�ڛZTb\��f�:���j6�@�@�[0V��K+�5�=�O�x�T�
+��>Q�e^J��oY}ֲ{~���U��X�Ҡ�����B=T���1h������*���՞Щ�q�߽�i��X:�j,iK �b���`� N��~�ib�z<Ö���#�� �A�/�9�v�����F������="U�F ��µ}H�
+�1��0�W��2L��O�j I�"xyu3iJO�j�ȅ*jԒ 5���~T_ �O���ygm�"�+�g����TR�q1�Ymq������]��,�pR��X��<$�^?�H҉����z�����!��}ƹ)<]���G���u���͋�i{��]��+/׫o��/��+�̷�d!���?>���S������@�=>᳡v4!j����Ί�TY!�[��y���?��QP��uñ*'K�~��k�����q�'�c��o|�<����^�O}�Cr����b+��je����@��`n�(p�f4�?4�8�Gf�`�B�RAߨ�v��v�3�̞�����ܸ�3�]<1\2(����#�ό>��iY/4ϑ���Z/�����P�%�=� ����0���;x��:��7�Bx�S���M�jE�N������S�p��� !���MK�֤�y"���T B��x��X� hN�/ڗ6ijy�]�X"����&��ɛ(J&3&GU�MN+����.1���Ç>��"�s�@K�COҀ��g7�� �a�ߡU��M��s��yA3�9` ꦧ��n�}�7��܊OH�3Q��Z���x���<�9r�<�E5�+�d���S�.~2#�*��F.�H����ĖS�Oc����v���I��%�6�Ӎ ���U_�)\�ܯ���ذ��^�lD�w=5�p��FԞn�?5m��T5//��eaC,({gKcAG� Q�c�24�:>�N��h���N���vx�UB���a��&7��[-v_r)��BY����'��9�.�����ND�1�JOM�y6���l�`�:Ķ×���w��w� N\7��T?��Uڞ .�% u�A�VȻ� ��� �����`a,q�;��Y����9�p�+`D�e%��&o���פ��Y��� ��e���������?q<gdX�8�$\7 ��Nj�&��<�*�( v\��A8��~?o�ܴ��F̟(q�1�8B��]a�.ܐtg�h�N�?8��*F\�� ���P��r�m���c�Lf�,�KY� ��8�'�<j�*��1pX/���� ���}R6��Vρn��5U�c�(�?�x:������M$��� q���=��ST����]xgJ����4��~��I��Ӂ��?�,\:��E�������o��IYT�^���ľs�k'���
++r��N�9$&��aE���I�O"�G��+'i�I�@o8ɸ�ehBC/4ؘ#�����]�ev�_/�B���fBP��ڌ�<���f�- ��=Yط*?���!'3CM���;O���Q�C�.jr�����R�bѢ��6�(���-�{��R�߯ A-C|m�t��z�#�GV6���>9�+>�ߢ�!*v�Լ�/�����qM���#�C��v>�+U�jJ$Zc��X�� ��m�����sV���8�`�8c��w��ot�U���$.�aL�x� �O�|f�T��P��*` {�z�D��&F #����;���8KXӋ�U��v����)�Ou��bœ^���B���`/+��7�]�<.v���I7�n�khP ��f_�/�����W����<{���Gv���k{s�x��
+%�����z( �f�r��hamcj�>g���}�NCŗ�=ڈ��.骵���#F+�0�0�-�[�٘k))�j������rm��Կ���Y��j��%m�c_R=��}��a���U �u�'�x����\�.x~u�q�IM�_37�o #&�h`X�$T4i��dZ�4*�K�NJ]�皏�~d`fz��� B�_ �>�L��"E������U�h�a�����!
+i��YR�LM��j�����VA�Y5Z�;׿��G8l%#�"��iG}��'��@x����J�������4�0�"9���6s Ѕ�m�m����{�$yB\���d�gT>������?�w�{ϵ�;�:믿�p��e6�t}t�����Q ��0Up����ԋ����\QLh�X~R�?�Jτ1["^_���!%=�yµv9쮍��`ۘ��꽱$ǖ���3�9/
+����[@����F�d%?�x���u#Vݸ�!��q=ۿY������߄�<��zF{�A��!�qC�(���3�&�:~D�P&�_i�?��p�p���@'Zq^�p�Y� e�tU ��IF�#KS���?u?��~�%�� ,�"�ĽNOA(�wj�ܻT��&�U� ��.� ��*ˆ��a����l{�&. ����r�U��O���2ss(a����h"d5>NLt��� �+v-���H`\�)#6Ə���E(�#���{��}�m ��V���+�z�ᡃRJ5�$f�OYa�J=�ϛ`;Gc4:+P�-L�DH��S���F�L9�f{ȻՁ�?�A��7o4|�٤ ��J$�kt0j$�D���@9���,��;�3�p�TZ����]'K���n~G��z �%A̓ �2g\�V�|�$��v@�7��4�;C���='������N�7XU�St`f�����!���^�&g��$�d[�2��* &�()P�����ذ����,�%�塀����OFVE�����UIH=�v��l�)�ٲm�bMps���vϏRG�� &<^�̬x?2�iץF`�>L�@%�M��b(7U3C U��~��0�4_ �����ŗ��P� {��C�9
+���J����\��g��dmx{���zb�խ�_����'F3i=�d�����p�}��2�C�L����dA��E�K��_��c :豹2����ԉ��4�3xE4��Q��o�Ǒ���"�Q�^*n\������?�ޒ��� ��2��[�� &�N�HZatdMA����OfG|����'5Ρ[|a���0�7�"G�$��/91¯�����O5~��"p=;Sb�
+�"*�;��e��&r�b](�o9�?��O�r A��aU���P3���4�3��K��C�)�l�ñ�G8¡�%Ak���m� �z���}w_���;p9ՙ���� �
+�d�b����A����Y2�N����)p�0c~�,��/2Tˈ}�4��V0�����̳����:%p��U�A�b��ʙ[[Ñ��g,L��#| �%����S(#�N�h��5<`�� R����3uq�B�ݓ=x8�T F4�E(��a%���IJ/�k��~����E��S�"?�G씲���E[s�H��vF-E_� t��wv� 6�@&�� �sG;� ��� а �2`��{{��\RX5�]�����l�c��e�z�iTTl��~�� ��-���N��}f���Џ�<$�W�!�� -�Rx��� -�ģ~�"9�^>-�!��SU8��Ȫ��B��Y^�����J��Žjk^��E�pr��i3*3É�Ww+��^y'��������V����|�j���5���lKe}0��!�b%��- x2�AdڌC����>k�[J׷N84�A�v�W���p$y��"�>�ž���^.l� ��7/3�S`kU�=�$�&/�낚6��2>��0<��B���S���P��@��K�Cwp���*���d�+��h��$I����ǣ��ZZ���U�S+�=g��TKt�l�(I� ��a�W�n��|)�T�9߁����43�i�����N���6�N�����aP.��V?o���ƫ�����M�r7��\=��ثf�jZ�&!=(���� �Č��b�%�ܐYpR�����`߉R�s�n�l�sq�ӀX#R���4Ev�+����,��ܽ��΋Ed��܆�������Ϫ��f))tȠm�n������.��
+v�PH[�ȯ{�3Y\2���`��w�{�DɄm��%��}\�+�g� ���<ϵ6MQo�����#>�n�@0E��M%
+
+6�W�8�xT{h�&�m�<ËC�(��E["c]�Sf7�t����6��=�����q`xܔG��L�\�h��h���� �]�B��U����Q����q��>f2w�L��A,�c+}f�8{)� )>蚋���w㷻_
+���� �&�1J��
+���ڡD�t Zk ��X=ҙr�Z�(7jAߊ7U�HD�7��#R�HG�
+5i�J���β�H �Ҫs{�fU�KoŽS�?����N�����J~B�k�?Yʩ
+M(bͻ��$��ȵ�Z�>2�W��ҭT�t*�)�|NiP��B��S
+�jQ���y�<@�zCV��BN����-���v����g���mJ����O���7�S�p��Z�F]���$�~����ۨ��I+ܐy��޵ܮ�q�My�;�mK�;N6E�� ���ۊ��@!�L3#���Y4`�U��d�����C,Er��k����Q2�^ bl�CoM};k�g8)Q`ƛ�$M���TG��OIx7���N��)����[ *�������rL � D�a��O�^D����q+ءq%�7��)�J����i%e�z�@]/`���au����+h�@� �f;�̐Ѝ�����3�����3���,���O}١Q �aƎF� �aI� ��Fߤ��O�ԡ��p���<{k.�a\������� ;\�*�z�*L[�0�\��#�����#*̈� c��$�))ͳ�nǓJ��,�"%\�b�$#�jF���"_^�Б��L�yݐe�‚��6�ܩ���v�r���(�!p��>ҭ���j+�v!� ߓ�a���7��I�*.d�ۤ��W"L>=���8}������f��Q$k?s�:���\N�Fp���y��ޤ�5j��R)đ-���[th�dk��0����d����1�^>v�4R��O{��J���LJƄZ�WƪMw��c�>}0�ۖE����J�7�
+�s4�E��b��Z�ы�}m����B����U�qx�\���{����%��` S�������*k��ו-/��Ab�j���_����uP�o�bLV��x@-��C9[RY��#+U��m#^� r�7��:�"Eo���x�;�Yhi׫���4����Q_����J� xd���i�4���j��=�h3�z `�H~b3���C��7�D�b�o*2䃽�*,�u���ԗQ-Ԅ�L�d�dU�fT:{���Y�� ]��E!]D@X7Ũ7�R�T���/�s���㉮��ԫ�q{%������“�D���M����(ji��)���A�r����U��*����E�O�$#Y� 6�l�Q%?=����V��|]ō��6�^y�F�eӯSƒT����j����L�m<<�;C�_����I��3{7ԍK\�f�{�;E&���vsSS)ra�AT�P? �zX�bϦ扬��dW��n���jM�pW~������P����xpҐ]�N��ff�z�*�{���1Ƒ�'�h��S/1���-Zmh&��.1��27bBz�u�B��f)Y<c�&j�CW�X�d�N�֑.|� ��P�❒R�$�Y{p� o<{�b���T��&8©�MlAL���w;�`K����xj�U_u���D���+@$F+���i���N���f�g+�����S�*%&�)��ESL�^�IQ�Qu�U�w�����5������?^�<�KA2��}7I�۹?� t���=����./������n:��ze�?}��ą��4Bڿ�k!P&��({��^X<������xl^�R8(Y �D�_1J�2����NJR�#�y�L;�1m�x��� �?��^�'��A���(�#6|�<���*����&C*�0 �:�񣁑�^�w#���i �����<)�]ݪ�i����[B�2'}�Kr�Z�a̋j~%�'��a愈�^�?a �c��Űv��vqtUE��A���t�]��%�da�5+��792E�n�W��|2'U=d\�x���"O��.!;'h�o�Bi6{S��Z�+�ae PI[b����q�[`:��_S�''�d�Ϳ��mk������.#Lر��ǷX�-�i��ЈF�=� �X8�� '�ǯ� ��+���N�����3|��T�:tp��k��-˂tS]@�ʄM�*�N�a��ܜa�e�}�7s�k\R/+�*�m�P�9n76�a�� >P�5��hGM� ��\?�Io� ��6�C>��`7�f�* �� ��<P��->&�F��LJ@�溞���À;��ux�+���K6�9y�M�l���|V\C\��9��Л� ��K�/���L���T����G��f����a�:�����L�1�^��)�kܨ�N=D�8%i-w��TU$a��̸� zb�G.Ԅ���T0�R��=������tCe^��;b�q{3s܌�݆�X ��zC4�U��̾�-.LC+�:��i���f��d�� @s6�'�Mt�U��J� 'a5���Pb�,�w�Lr�D�SSH����6._ր��Rmc�]kf 'j��yJ]�Q��@��(�>����\Y��/�~�rc f���Q�b Ts,%=���[��~!�Et�Q��w_�.��k�?07�����-8ԫ��m��%О��T��|.�]� �}Jz�:ͤYT�D��ި�963J�M�H̍�΁�� ��n�GM�4R��Bd����Y��aV�:��B�:;�WG33��o���o �Utf��Gb@�@�oޙ�?S�z�lU�� �o�e���YK� -A���zG�.78vwY�/�"��23�I� �"r7�6{ ���f�t,�*���sd@���z��N��?�`���Ah��i�T�sn0��%W�Q�����(kS,�i��R�f��2���:���n��7 �� GƇg� �::]6�L�]w�*�H�����W�s�F���zɠ'i�rB�1��Ǒ�q����X\ԉos���^� ��P%W{�
+���HH�=�)Pά�T�W��b�JI�suϑT�LTɀ<�����Vonq�a풚�ְ�x:��"9eb�A���Q��6�wģ�$�:�֎�:��mbA���@����k��&�d�|�f��tj^�
+�D8��p��Q���ힲ��B��J�;I���\.3�p��R��q�u�l�SO��@��M=�a^��A�V-<&,�`�̀�*M���?0F)���}��6eFI>��O4f���M)�d�6j|0����.AC�HuX��[����� ��JyY�j��t,���q~��8.��~
+��$�aǂ �•QB�]h/f.��:�W���*�o<�2�(�!�T���N�B��x���\0�w�,4��?}V�J�7�Ь�[4�<�˾���Ϩ"XQ�u��ܞ�N��X��X�ZQ=|���=W�{13�mрR��R֞�Z�g�{�I�=��FO���3��6�o^>aҟj�k���'�Z��2�`�*�# \��_�t:=���V"C�N�U�c��@�I�kc�bڬ`E�\��m� �� �5�/L�X�퍝�1��PC���-�`�9 meg����s��}���٘7���]v��H�ع�7W}��D�A��g�2ثķ��^�۞3w[��?/z �� ϯ_-Q�<�8��ۢ�P��9ew��J��鮶ף�ic8Z6�@!J�W8�m�g�s�R��dˮ�V[~%�1US��1�g��i�qckb^|��B?t B6��V��� .ۣ0�ú�e�3��C�X��<������g��y>h��=x"�� ��$�z����C�u��i�y�9Եh;%ZQr�N�e[�`���a�k��)������5�(���q� <F��^�@�B*�U͍��l�<3J�(��=<"�
+�rg���p��I=��OMC�B�Ճ�O�@�Ǜ����2QA� � �?iĔ���E��mN| b.��.�y'����+��ؓ4="���G�LL�,��S����õH+==�����ݹ�Y!�ciA��R _h'�m�!sn�Ď6���o�53�h7�V�¶��l�ἂ�I�4@���f<V��^(��}�*T{��{� ������mxhq�v *�b�� �Ef�`�KP���:ɬQ�-�+(TcP�;Y�יbe��k���o�}߄�1����E�A�~{�g ��Q��Ư/6[��]���q�_ֆ�F^GƗ����-�f��.^O5�Ԙ���ϣn=&�'�RpiX��!^S��}9����
+oK3jhY/+�����u�8���t��B9|�=q�ǰb��ۍ����"gOI�]MEѰ.� K $��^ޟ$rqi�PU�F�=���p��g���P���7=���u Myz���AzHTr����g~�?3T`�À���o�SF��V|$uku��9t���w�u MCC��kS�9 �9%@�i�� ���y�8�����Q���6� ?'���).�U���ԑ��ƨ�u�_��Ł�>4����6�y(!؀��M�5"��H-J����q���S��՟�v~`*��ڨ��o�a{]�̗��~.�� X+��0�^��:|�i{ bQ���Ө�Ś�l�$O����������k�;8)��t ��?��XI|%I2�p��p(a�l4�'_q�[^<�ֳ=�|4H{���d��(����m۶m۶m۶m۶m��^�rnR�����LO����t�/U��_�O�H�x�^-��b��[�v��9� �DT�j{�D�k�N��.k�1a�q�x.����E�h��Zו���Ă��8P��N0a�$m�S�����K��I%-i8��~�k��9q�Z����\5��ˆD���5f��Y�s��`���Q?qe��� �
+*�ha/���.��j��hݍ�Qcv̀Zf�?�����rM Qʇ�P�1���Z��Q<�gvA�91���(�%�U�K�5'v_4�Y��[�
+y�Ħ�G
+�� q�a��
+-�l�I��Kؠi�����C�7ˬ��r2S�/���B �H�����LBU�`��3٬��ޅ�ݐ_ L�$E�q^'hW1)u�P�?r�@훵��'��ο�@wECPk������9�z�S�Tc��/�ǧڅ�V�7���G�K;�Hb�^ �K$���Nn���c�:�5>1���`�������_���
+����{��O��������Pe�H�*�}]��ە ��[�����(/8�$��gq+H�B!OE�
+Z�2Y� ��M�!�52r���+�ȳ� �ԅ6 ��Y/������14�O�[� �����j`Mu��CҎU�� ��ſ=�K�&L���S��/B������T1do��t����q�d6�{�0U$�|z�D���(�'��"n7���l�A41��j58ٯ���/��&T�x���$˒L�z�t8?��+��1d��Hh�xj���l��{Ѣ�X��O��ę/-�\��R����W�mb��g�����=J��pA�M�iO��۬4"�"K9aZ���;s�B�͂,�N��O]�{=�Ow����Պ��$�M����ˤ�:�'/���ۊ=�R���u6�� S������meY�n�=��9O���:��ګ� u���.dt}��-�w��*�"� խ����v)� �����0�_���R�[ZXI���,l�Su^B%ƀr��Ω�-!�d�c��B�#F����*
+Bf�!1�La�; �DX��)�a^�h/��`=BV���!>�`B,F��,�Z��mW$����ė��ǁ@���:��9> ��w�՗5���b�O��
+3*Bj?�F4�L�U6m���|�G�{�͏��+���%�r�u���q�;J�. �5�'ggl Y�9��D1�E�5��,N�p�~��ԗ�u�ϙv�3��EX��?�c.�=x�j��L�� �,aҝ� 0��.��zw��e��i�h�KS�&g�V�o����,KMM�i:,��v����]��D�V"�_�v8�~9E��eˑ�X"ov��7���ZAT�֩գ(�C��1�s�$�J�FE "(�@,��s�*Gm84C7Q�r��t%�c�x!����%�
+��d�wy���8��d<�<uL�}��YV�ɗ�2'�x(.^�O�h]�I��Qi����,n��� ��;�n-q�L�&�E�$�O����C3�w{�+R�on���y���18'�9����to \y ��n�Xz�]�^��M����'
+��0�!c+������� �Zw�߽I�kD1ω@ �_�M�]Lr���ɏ1?���n���\A��嶡���)���#&f��2 Մ��� �UT�Ci&�AL!uU�>�ik7A����(��;|)�����l!�/��S�1�Ϟ"�h�U��?_��Re � ��|
+��Y4�Q-�6�&VT���Y��ZJ�h �U�k�*�Ʈ`;Dj�c�\�^�fFq�;�M�Ǭ��0�O����le�Q�}�TuND��������Fc���X���]^͞��%�'#�����-��?\� �����]N�J���^�$����~���V�� �UZ��T� ��.�Y�>T�F�fvF((��Pqp�Д7�ۿ��s�����2���!����,q�2�H.�/�p�R��a��F���~���+�Ydn��T�q�݅ԫS�ږ�eaИ[��i�8��y��n३ �ʌ❡�����Fŋ.}%1�dS��W��{n��8����eA_k��2��XD/>��t�z��'�4~��c�v���~,+K�9��A�"\-��aי��.��&{%E���ׇ�P�@|���%i�V<K�͐�-�e{I�X7�7�k� z4%k�>�l�� ���rV�<���%em r�Ҹ�[�����x��?� n�=(m,�?O(Q�PjdW��g�/�mn4�೙�/��x\u��#�8�ły�?�-��@9��Mg+�x��׳��6��8Ļs�'��Cdx� �Q�fN™� ��C��{��,��;�G������咡ن�k�ⱅ��7�b�vL"�j8Q��� m1�f���Js�������9z��Qd�v��������np��3~_4
+�h��-y,�wOM�B[.�ߊq�T��k��Z��3?+zް���hR3GA�RIf��XX�":�s�'}���� ��Q�t��ʈ�i��(�UԦ��6�nqVc��h���Q�r�I�� �8�����г�9&4��K=�$�~�L1�q"X��)\ �ů �XvC�Rtbn�?זT�}%c�חy��)n_�����ʅD�K�X! �у(���!7����C��"�f!���b��5�ृ���v 7U��ƧU��B9�G#m6��Eu�����op�n4�B^�q���]�@?L��[�R��p��δ�(ޛ ����� ����65p%�|jԪ�ˢ���]��) �:��CJki�������U�J.S
+sl��]�J��u��8�o�(b�!mnM*�ƒ�'�"W����k�!_]�Nh�V�V)�b޴��2I�)}'w$%nTBei����Iڢ�W����'�e���X�E�ճ!���������˽aρ�4f��E73Δn�)] �"P�����i�|upD��3�{8�����ƫ;�=� �u`y�j�6(�`d����`����Z��% ��lV�1��
+�ɶ��)$͵=��r��Ʃ��?L���U�ψ��$���Y=8X�Y�; c�.ު����b۷� ����VK�kE����X����d��K2F��v6@��6]�J�v% }ߑ���d˅)� �U|��Y6�)S0:�g�2� K��2.Nn��7��!�n��mN<M�&����js��I��.�0� #q;��ֽZe�:�7��6N�@�
+q��_pKP� �4/i���X]h}�d/˥���RŨ�a��PGn S��#&t�1�#�Y\(�o ���\�4��̧$ݚaH�)�̽��3����iag����%�^��8�I�Hq7�Az��/ӊ�ȫsy�2o|��G$�qo0?k���/*I��n��5�����4��+����$;��bW�p�iPZէ���n �Do6]�G���U�� L���/&C����YĄ7t�y�Z(]:�?�����isDMGά5{���e����5�xpE���]j��<TWs��`�%(�v݌����sX G���t�z�Ǻ 315.�>�*N����KRZ��,�;ɍ��Q�G�.��4�O.bG�kD)w���\�p+��j�$�3��'��T�}��6���H����!z�P�RR)���w�>�v"Qb�%���D�otNJm˨���*ۦ���L�� ������9Z���.���~g0���Ip��ï)v/ `��x1�lmB��������~�8KFp "|��b��xz�sJ��^M�6�3F���~~+i!�$��C</���d᧏��V�`�^�M�8R��c3աx9���Krt�U~���S4ڙiHх G���$��mRۆgTc��2�^V)�'���+�
+WW��uz�.��@ �5�\���^m���
+\��Ġ@��J٘®�,-�v�� ���et�/^�����3dɯ�tKO{�<����䤪�zM�v���+&o�3���#���P�����9%�V�a�&��E.^�����H� ���� -@�IG�
+Uz�N���kJ�3k�*/R���Ⱥ��ѭJ��e���>�jn"Eн���(ƚvM�9��������RUr�e��9��v2:^�J�Sb�W8A�/��1.��/5 �ۣ��$8���"{����\���pE_�?�D9[�-�L$��D������xC�,5R/M�`mR�O�5���kv� ���������ޙ�� ���^A"�6�-���'ٌ9AA��|��x���u)4���M�)R)Q��<|Ur_ k��Y �����_��0��y�N�r��O@����a�Ur�ſ߇�TC}k�ެ�L�r��0R��-�=��F�������ᥩ]��� ��e�x!
+PZ�=��Eη�Qp,��n������7,���Φ�j��p��g�H�w��e�Q�Yi�4�ݐ(�|B�`�2�z��f����/Cl&�RqTdo��� &��#�J"�����^�9�O�el�8�nLeȿ �:�yG�d�Q0�Tq޴�T2�����tN��'erE�W� �(�\�^�s}�(��kG�N���T�f���%��aV�d��,�GE�.(J�i+�f���N[�� ���C“��h=�2�^���+}{� X�E��n��W�"�ʄg06�T~�Ӕ����E3����p_2壼�dɝ�+�f��:�fw���3��y��9P�����(�������n�����;O��;
+��}�m>{IW��.�ɂG���4=�#������!� ��� ā��D�2�(v@��-�s�aaD�� E|� ��,�N��㓁�N�*1�D ��0�ϻ2B%�O��F��9���OT�2Ǽ;�_���Q����_�U~�f?�]˯�k��3�Zc�V�}1N�Yˡ���O?Q�²�� �'~\�� ��Q�Щ#׀;b�:�A��`�e0��N������������b2���ˌ��c^z݂ � L&6$�]�Vr�b^*����‹
+��Y��~K\��ꎙѕ�ʎӺ}�s_~Y��12ƑJ�K8t���8��
+A�� oW�z���e�(��S�|�X�O�5s��+G�>�2�t6>�CS�b��ݬGG�������7U6ϟ?�r�'���?M?݀���05|�� �w+v�?p-�ײ�p�����6��x/^�癒�q���[�K#"�d5n�|�����zgɪXb1^��E`����&���8<�k�}�o#��ן=�϶}��3P%�HX��i��2���
+�PN�����SN�Lv� !Upܬ=sp��78p�# ��~+:.�8&!-X&�E|.�o��z��N��V��T��B4(�V�~�m2V�\�Z�?��M�G�zp�XL�C��M:�R�8u���&|�\�%�P��؋Q..���&��������lR�R��b yt ��h�S��$K#L;<�������Ԝ�N!�i4ײ�L��-�b4��K $p�x6�: �ƒ����Eg��U�r�J��2 -���+���~�T�!�� �)b�o���E�����4�}��e���XF�
+��� ��ԒRrf$�&�eKR?�*���&Ŋ?��<Fx_*J�T%I�mg��M�X�̑�jlN?�ռ���v�����(�d⬣���ƪQUhQ�V�=�pbwe"��9��t���T�8Cp���1���;/������7'q]e�����,4���h���R�>0F�)�K���S�~r,�.FgVk^��$2''����� 2
+��Ky\�G0�l8�/J��wb�3�@(;�o@�J�6i�ɻOI� .��cɒ���D@��lF�3�� ��_�w�=0/{�v�*��ʄ�ݴ@�h˲�2L��j|�)�oXL�hq���� S~/��D�N
+g�&�$����#Uv�i�#�r��9�[t�@�M�^�x~M5UI�hX����/�\�Jwz��[JHښ��d���Lś�߽����+ �Z��\<��*i �d`�~�K]ܕ\�L���2ܑg+(�Q����3 ��E+.�Hܚ����oA(�&_՞�N�bf=���;Q��i|?�'�ǣu�����
+bn���s���u�nj�4�Avh9d*]i[R������}�u�("���_�#�[q�����UXE~w�QWH;0�"ݒ��a*b k60��?���Α�݃X[��iV\�5IO���|���V�:3̬.v�ƺ�}$���:@f������^��4
+]&�Ŗx���3s1GѦ �\ |(��B�tM���U�ҏ���BV!�0�ʞ�%;�i��Z*�t`�٥z���̀L�y��@�pJ���p�o��fϠb��SGGb�UV[—loL�w>&���%l�*s���ʐ7ͳp2��Q<��ԍ?8��Zf����R+��AD^�2x(k>�� �T*�7�r��xvhu�6�xCߤ` `wGљ�'�⣟€ J�Ʊ�Ȋ�� �0��hH�u�
+;wq��Z��3�?�Y9�����N� ��s�t>�R[s �� �q�͙�3.j
+GX!-�>�S�1��Yl����cڑ���5mK���VKq��?��`����'Hs�9_C �P'��t&�� )��0N<��C+�H���e}���.�1�h���P���\Μ{�6���/��6�O�#z�Eh� J��P@��%�k����m��� Ur�;���M���}�vs���% :ծ w���%��������"���s�f��ڃ��C&Sh&T1��A���ͽ���v(c%9J�� ��B��ah'�I��$؋F�X;�Z��I���� y����F��\��!�E���V �S���
+��J��V��0���ˏ7�L�!����e.�q3ԇ����V� ��p;ݪ����ʎ�x"����e&�2-O�+�
+P� ��v�t�tģ��/?.�R���.�#^'㎄G�#g>9t �ۍ�5���!j�%���ɮ\�1�z����]�Ws��U�)ÿ:�*0�n"�#2~
+�n��D�Wj�y6�����(`�;��ۣ(z��^&q�~�U[�yW/Q����)�X"%��u�8-���;jgJ!#G����Ph����*�F` hK��Mŋ�?$���#Ԗ�+׋�g��\_� ��t�J �Z��B&� ϟ�Lk�H�(����b'�D����6��?�n>u2d�˺��Tz�O g�km�� φ��v��/v�2M�F�[���A�U��S�ִ"�1�h��#5<�V�RTo�)@@h�����^�������Rݩ��.�xZK&��#��?m|�
+廬|�a�l����S� ��\ b��� ����X���`m͸��E<�bG��L�Fbؒ�~]ģ���1+a����D���>�]���ǫ ����9�J����(����i3�eC`��be�J������qvt�!�5a��g{D��7�|N�����I"1���n�0����c"� ��"���i�h�pb� ��(W���S�8zR��8;,‹��z�����˅871
+\k�a�˗�<B 6���#)��[�,e�d����m��$���-�_��b�Y��9%�g��o��T ���;l�VG���a�9"�7t
+ɟ��I��2^�1|���}�-�1�Lݕԋ S����;[�P��vP� ̪P�����Yp0�U�Z�W����G����n����؁;�$I�0YF�9p}����O�� ��E�%B9����X�e�zd�G�]��4�/2,��'����),���{�nV�,t%U�M�����
+���6z��Ÿ 쀃�y��"�5����U�~�1���4h����������&�H�E��i'�;������8 ��k�s9y����?*�`��'�{c�C�0�\i� }�D kk[,G��״%(?�0�D�K�)�)r�O����cX��Yg#��[D���}���z�2�29�wS���O�al'�E.�E�2Rs�c��weq��Q�DF���#�[A.��u�}�d��i�[�����k����ڮ;���V_�|-s�"~�Y� N([�+�~���Dd&o��-վ?ڍ0������ڥ���aG��Ė�]3�&d�!N4����E��G ͌o������-5�a�d#�1�B�H%��t�/���N��e��1�:�E�`a_����칩�%�S�� ��G�(i)�n��¬�Ϲ]9b�� ��8�kX�L�)���Щm9Z��iߔ��n�jS:�%��?�7�W{��L����_�o����a^r�:�k
+�ď����P�(�,�������f�]���N�a)���� Mل��¬�nAb�S7Q�u.���
+���d% n�3 ��&���˙c���Zr���Q�@�*���z������=��⩰5�?z�QaV�[����e W<�PV�^8�7���ɢe��}����[��^�Rt��\ �`��Θ�p3�O<t)���9M�Fںqx�1,(vJ�h�@Y����g`Nʊ�Q�l����ry����� ��g�����n3�[�C�{�Z;{o���0�"��;TԽ5z8l1?\{b��y�c�k��iv1`֯�y ��u�Jܓ?�$sz�;p8X�w/��o�x��w�kQe���k�~�Yf���e��c V��0���ə�P�I�&�oo��[��X�Z.p?NDQ�:j�+���yX%w��<:�^�h���m�oB@����ыxL��y
+�EVQJ,5���\Oq����A���w�T�ڸ���i厙���K'H����DCE�-����؟1X�g�͍R\����q��#�v[X��WX+�ߜ�� k�}�~G c�$���G���d9����
+`1]cbɸ�E�m12�(^?�v�@�A��;
+�!lP �)?@���z.p�_&��(�����b}�'�|�_�N�^��׉���н ���˦�Vc%�$��h�rKO�謬�>Awͧ���(<,�.�!]��� /)�U}G��~���G�L�R�9���c�)�$v�M.V5t��L�Hc���BR�j�����ȢW �<�Ր�R9#l҇Es��B�6n���m�t��:+Z���.p�u���xq���8��&��a�/Ԑ��cNx���m=��@Kmw\��P�����I� ٮ���=����t>���T���Y;Ԭ�"�IhK�W�7�,�b��9��.<dL���b�U��6�h��i{Y1�%�qSiFoP��o󉙥�R��H�o����h����9����I���F�Zu�;_&L���,��� E�y�u~�� 1ǷP��p[JO���<��pR���E<��(]dy���1����[��� n�?�Z *�A�}���R��0CZ<sp��8��v#"hg�D���Ɍn���{���z�i'E\�0�/�g�~��
+a[�eu�,�Y8V�=�9�B��Sc�ve�L�y��S^��k%�6�Ԙ���6F����aC�R����C�O�͙��$�]U>�9h��x�2� ��d 6�K��W0i|��-
+ݳ��r��1���#�����͹��qu��W��~�����m�a[U��>W�0� <~��1֩|)�t�n�᥽έٌ� *s����7M��S�ET��: q%��tҾ.ꕜ��@���J�T���{h� N���{�'�(�Šlo�[4������R�|�A'�Q�R�:��mw�OR��E M1c�â*��i Em`��U��!�1�&�i'|1o1��}���*պ���0�*��`6#��q'� �%*�^x�b����"?c0g�44����&}_����w4ꙍ����F�g�b�J�s�՘��CƄN�ʸ����|�YQ�����m�!l������ BO��WXF|��]v��Myh�D�@y���!�~��-<<p48ís]6I��1��!�]!޴/ #��U4��۸9�u�[�e�g�������7VK�ٮ) u�S�"�����A�b�#�Ԫ�?2��8(D�[4=ך�:�3ԁLhK0���pc׭QAb�k(RXΊ�h;�$:}��T��7@Y�Ӏ��D婳%��m�>�$�qKu:u֗�����C�+��~ԋT�u���dnL���]��}�*��s<E�`M�T�����*�Dz���V��3n23Ũ��x^�3�_ q����U,�c���"�L����ĭ2)��G[?�F�Q����Y�4��vΣ�g. �#�U���s&tQ��R{"w!�<~7�d���>�d�����6�: �"� O��H�h�7����h���r��D���g �"?_���­$t�5� 3ײ�v�� �w���o�����!��#.��h��d$ �1]�nX�)�� 5!q�1��1�K8�8> �=D0��'�9�xl״�j�Ze9\�V32�˶q�Qv�r ��\!�xd�+�����t)u��(���o���$�j��nf/N�2��8?e�Xs���6�Y�����;��ƀ���#������e�lnC?�0��`�����}���<�\��2��z�S'� r�/��^�ȸ}� ���.�yS������L��k�+�V_Lg��T�����~)b�Ao*��WH6Y�6b�ݫ�H�3\����].s����Y�~����Ѻ��郠���qQ޸�V$�| �?o�:����T��(�%n�͘�¶bp߸kPd�qk'㥈�8���
+.mS(����w��!6EP�_q-�tO��\݀Z� �����gp_|�&�F�B��%�{ծS���������N�����H�˻`�9f�ۛ�>�&������}��3:G��k?�v�����,�k���A�o�"৩8���!SRTFqFfNI�",���I���l[eN\`��)l�E��5����)�ޝ<� �N7����xَ�7DV��>��^�e�n�M�x�^��9����4�f ���'�F�W��l4=�3�%1��l���`0)���1N Y�"<�Ѝ�+i�)�i�} o�v���i�N0g���6O�:���G�a�d�ΡU�$���t�V�?qb��(���_oi77L� c�7N���˙�K�E��\�?�n������3�zF�wZk�J����� C`�R{��H�^�ckIP᪚�I՟���i�n��3��f�I1�!��Q\]�5��U�w�.��r�UV ��,Hxa�d|
+/�����0,a�g���t��- V6�(�Ƀ#�]]4a�P�)q_��Y�b��ܻ��r�@~���C�uv�!H�E��6��X����Ac�] �(0PʻV�6������s�ٮ�ڣ��rX�xRpb�=IW4xc 'ŧ�e�W~����{���Bp.��d��>��$mn\�&��nH�� �)�� A�����-�\9KhПdbQS�ɫG`�/�t�z�`�������WK���,�9y�{ �*�2�^[�F��[ ���i�Ia�0��T6����Gu���>�<��[
+�Z �إ���[��8҇S��NUǬdo��L,��<�0����j +1��7�N�=P#�0��f�05Y��V�A ��{��k ���vw��%n�~�Ԁ^R�i�Y0*6�mVO h;Ԍ�Be@L��o��/q1W���*��p��l:f3;$ 6AM.GtD�k��M��q۰�# ����s�$��@<;�{�Q �[����b pf̦��3���Q�d�@l1O׹=��RXM�R�D�<��A�90�߶���p�H���FG�Vcw*��Z�
+;�P Ҙ!ַc �m�^�U�^Z[o/f~�IN��/��dv}\�o�)q��{g�E�1�[�C����6@��-KK�TZ�1��aՏb:��H��׿�Ժ��"jD拉��;�{�Ȋ��R>�� !T)0#UR���� b�)�
+K�U}������J��4��9�{‘=��,�^�rA n]uE��|�
+���K,e���X+��0"WV·
+<n!Ha�\4�+9�Q!���BP
+�:�v����}1a�r�[����$��Ƃ;F �e��1��"s��ȃI�(��I�@�Vb�����j��V}�e�^���VL�В�Ҋ�Z�{�� J��$k"PC��a��͍tq�
+���q'V�ipH ��s�E��{-i-h(����C&ف{�c��{��\(�ߺ�ٰ�+���Q�kI�o��3�z۾h�{8�t!i��TS���8c�I��y� im�P$ɑ��/^��b����]\�J�ר'�0z�Ե��5�ɒb~����ϭ��/�q�3Բ���Vϥ�|U��o��Q�5y��9s&n�l ʥI(���a���܎E��5��P���DJkOD.�Ғ�0� i
+����w����k[���i�X�񄚼U$�2��>�@K�?���LK�g���eXZ��d�s��u�� :]x�v%s�>�@�fd���A9Yܫ��19�]�S`'�* �
+�U�Y�68��x~��W�"�����H �Oއ]=,��)D�9��bI�!o����L��m�O�O:p�X��U" R$VY�`s,�A���+�!�eزb���[�O�{��Z4� |a`ђ���䈰��8����X ����$���l[�w�N�� S�l)/�="- �8�T?�誙����
+d�Q�vܐ���^̼�I��j�T��L��)̡��y�s�{���gE ^��]ﺮ�.o�!��v-h��:�� �8J�I��j}|V���U����b��âo�� ��s
+��m�a���Xr�a���� �uͳo�x���썱����A� �*���*��>0�4o��2u��q��|m�1�|Y������F�(�6?]��U5�VO�ʭ��5�.� ,���P��������ʯ�%`���n��v6�“ ���l�ߝ�[\L$�BG�$� ��9�xH� ��
+��*���篖���~zL���@�@��LpF�7x��+��ǹ���Ih{jzg�`�͝E{}=IS�:���'���0��J��� @n�6�1���#�ӽ��4���4G��lm����~��N��=)�K���x,3�V鮈�ߜ����ٲ��r���{oM���?��m��i++�JZ����M�6���4摀z4|)�Z\���~��U�5��<�a��»;L��Y(���3!<��F8P�!��bA��3�}Y���L{�şe6aO�n� �t���א� l��g�P~d%$�Ey�yA[���,���?�/uJ����g��.�9�:N�rC�鰴� >�Fj]���Q�9Bnu�'��`�ъ��+�zF�Kx/��H�}����S���O�F8A�:q�)�7���f
+���ۼ�G�*�8=|�7����~8C�}K"i�y�}�P�$�/���_�r˄�H�ޅdJ�|N����@�$�%IT2q~�طP�=������ܺ(�����?-^Oh*ϳ;�+�$a�����`c3���6p��#}b���Vl�3��"I��b� �&3B��$J�l�-P{�Z�a��`�Z�R��`���Ѕ�i.S�K������w�
+� ���$�di��������Q�s��Ys�jk�VB��)0[��„n�K��d�C�k�UL�{w��ݣ�!�� ����P����|4_��"$� *����9D�?���pIe��S���)�'��N ���T�q�C�-����s.�����<��hӶ�RF<#�
+ݟ�0}%�x5]O�IJ���P�g�^nu �&f���lax\2��J�� {� ���(�����Pv���-�B��D�2����6>4��7D����sbb�T�&z7�ʇ��C�Խ��
+|3�[g��Vq�Rdž!&;&"wb���)�n��23�d�POEd��%}�
+Z�����l�D؎�1�Ȗ�k𨌡0\Oy���g�F��W�[�HЙ9ŖE2���3�!ڦ�V�H.�#�c���Y�𝈬��;���Ё�9\��'&�yx��,͠4�;��6�x����'���s���
+X���{� �~����3HΔ�7�h\�Z�8�F[l�<�;?/|�BY��9�Ԟ��#�K�<��� ���u)n�p~�C���‹!�U>�O�h^���
+�U� ��gs��6��r�H$2��(��>3OϽr6l�����O�
+u'̗t#.�a�n��������䕍���k�9jD�l{r2MoCtH�Ȗ�����Ǘ��.���:Β�0ߋ<]�>����e8X�Ŋ��r���U��?��C�2�°�d���'�u�w�"��c�����v`����dX:�dj���,)��-k�����A����iaT�#��[��p����G �nb�ʊK���TPRL�ÂB�1+�~�O�S��gV�J}HLXHJף��j�h�.���R�4�������Ш�K�=���Rs��'@o �s'�����E�?�[~@I%jЛ����Amn�F�w�J��.��-����Y���� ��
+���"����ƛOd����#��wo�aH�ɲ�!������k�� �s�� ��t�|J�i�5� ����+�O�d��sRL��?W�)�Q:��^���&��漯'M1[�(�� ]_�9�l�I�|Z�.�-ؘͧ����!���u��3*_��]�A���5��Jw�vA}7���>�:���>����k��}�ԍ�g�9'��
+�uʾ���v�@%�C��]��/"�����'�򭃅X����
+�s�M��Jp`O�eh�0��$:��Y�y����[���F�(.u���^s�ڀǺ�E�.X�!�2�n�r�v˫��οyb��>�}��%�C3��=ݕh�c7�_�KU;[i�ʍ�1���&V�z�b2�.b�s�*Rďڴ7�ji�R���<ۻ��r�K���V:���m� ?謕j���MC������!�L 8@|�/�Hծd����3�$; �Jߍ� ����H*�5:���!�%�@�G���rQR���[x)�vcai\�MA�O��\s-��̞��s1�/$���P�QBMv"H��CS)y��6�j[0�"L#�5�E��+����5�KT�Hg�/�7M�#+�� in��6���#�0$�CC]iW.�W"�'L����]"��|5 ��AW2����V�G#Ё��FN�"c6��0���]Ԍ��iNI��&6j#0|�b'5d�(U&���DW�r�<��N!��:�>� eRg0҆�!NmҪPo|��~�9��|��:��7��p���}�:6"ӈ|�Ru���y������~k�GG4̒k�� ��9��nD�?6*L�E;G 3�KM0�u��*�<,v��<�B��[�!qw��k�b���y��?��C���� $�4�&�X���7�nCox��,�%��d�Q�3�:(8_�Px�z�x��D�E}�o !Z���e��s��.��YBNT�IJi��|y��i �<�)h+�����A`2��c6�A��;�H]l���#A EMv�1�0x�f��OgHF��[i��6�lͳ>���5C�!{<)��MZ�z��_� �ά��D�)�O�d�%K�\5O 6ɬ����M7��?<��B�����'G�:��)X�,�᦯je])�j� �WCQK&Cv��CH�C���Յ$�`E�k,� ��Fz(|m��^����_�!�a�x0|���7[
+�?_��ϲ��3E��5��i�u{S�w]|��ڪU� �(
+WjK�gs��ZaOEc6�"��_ÙJ�����0��^�E4M"��Y��ة΍�8� Ʀ�⛚�u����N����w��jw��t<�ыD
+�3�<�Esz`�7-+���y���N���t&�Ia>5eS����Ы6<A&; Ɨy� �[�j�o� ���h�=�k��[(3��r�� �b3��c��x�iў�'��X���Y�y#�JjFę��NG�����̣�rx�ue�p0����K�{���]����և\��C� o�����j �=P�"� Qp�z��e7��Xߐ��#���6L"������'EFp�Ƒ� 3�߭jNɯ��i&yb�[�5d`�s�P�^S���8%�d�fnp�j�J��yK�Y Z6���'[��\۫\�.�0� �q�řL��/Q��0[�nh>o
+���=�48�������p�ٷ1�$u~��̎��c!��`�� ��*z3?��x;�CoC�3=Y�K�^��"���\�%"?�ʽ#����~p��e|1j��3�[4a��ZR����—�( G�T:���Y9��úe�-�#_�O?U�p�� ��i�S�d��Q�JDu�����+Q����r;@pTЎ
+����.��!�+Œ,]!@��a(sat�DҌv=�n��W4����>��tL��i2�D��ڿ��W�n:���xS�Ƶ�+B��<�r�~��x�8^o���NӎD�yh��8�����b��j�&�V�]�bd�����)�c��3y�c ^�`d��L����6.����7GU|����P1Dq긜 [ќ��c�름$�K�褊 ��=A��O��c�)�p5���c[_������b j�i��&`��d
+@V���_���*!NV�������7��
+�s|[ir���[V+�G�W�Wo�qc��ee7:֧G��e)Q[5Is�! �ZO_lEG|�UǐP�J�:�݀�ξnd~b��u�D���w��QW,9B8�E�e�;���ˁYw�گ�&�������%��[Gs�ǎ��1u���Z,� ��܄ ��ֈ%r�ǃ�J<���Ӑ�i3��&���z�:������ȝ���׶�kʵ�U���� p$л�ر�޷��A�i���Y�S�u�W���S_?�n�Ro�����_�?����&i���:ok3Ui����NW9�(��N�\[.��w7\0� u@}���2�T��[k%J��K��Ջ����bH�����k�x�P���AJ����0�,_�,o���^ @�[� ��Y��;��طJ�� ����D��u�ȟѸ{Q0�Q7 U�܃yx�/��&�A#���H�2Za��"Y��w��NϾ!q���2T����w�[����b/���}o��O�ȡ:_�+����C�Iߗ.��g0�y�5,����@�s!{nX���N�V��c�
+*I!Ws�E�z�{)�$��0�6���v?D���ļ��D�D!��ـ��;{I�؜2��]�s������ͷ`�3�O�$��=�aZ��@� �P}��z�t���5�|MTb����uˠ������v@�z��=���@��)W�)���"wntނ��j�"𯄡���S�ꉊ����ш�Ug�G�+���&[�\�P6��Y���,}�U[6�x����).�vޯ�HO��~1�舣o�J
+����djx�\��
+�}���G�{�m�4�ܫD��[�˔�%�r�cw� ��UжR�M ���vC�6��a]�* � ���?������M`�r�Ac��>u�9o�Z>X@~;�ƀ^�����<��F(ʢ�/��N��@N}Cm�FE�� �cb?�5#N�/V���f�~�ٓ$�ӛN�2���y'�r����N_3otz� ;�q��iP��$�~+��L�P\��0�����&w 5f4FD�B?=�o�@��h^|2�Vi�MW��zi���zg�e��6r?`�3����R}�/�!$d˜�����d':W�ʏ�[E�W�������Qq��Mrz<�QLt���ڂ��n�/i(!�(�b�*�d�<�]��(Ž� �AS_��<s�U"�ޅ��L�u��դ�Q�N�A�v �,]��w��#0�j�^�|^U���g=��q�)|�9M�im�鐍;�݅I�t�i���gZ���QX��/B*yV��)�D!M����\'��D��T�/�3̏����ӊ?�-�%u��*�zwW�E��H��7��mn��J���Sn�y!nP��I��{�v�R�0Oy���c���Js�,ɹI�*�f]���_���y��߽;��� `����WظdY����4�{�[�32��Ax;�P`ͱ �+ �����#�l��0fW�,X��΂[H�����~�\Q���'C��=�]�On#��޸4�+��,oXt-�����N�� tY�E����+�2�����;�ג66���jřJ����/�b���J�>3�ލ��!eZEAF(��kg4����܄R:s�pǎ����������)1I&�G��ߢ��A��|����d�Q/�|8���ȍ _��L��2k�i�SFo��~|
+/��ۅ���1O��,��6 ͣ��v������=S�����D�MSǂ%urq�ߓL{=ڙ,��d��n�O�g������2(��s�b��W��/�G_ �Y���H�&�w:p� �!���n[X�5xͣS�i��F$�lŗ7��I��F6 �`��E�V�ớv�]����v������&�^8��� δ�����FM�� �_sq��Gw��hQCb$ݞf��vo:�ςo�Fhg����i�Vڤ2�����h&�˶e_�
+����^1 �|��� � ��}^f�0p��^��\�Rl ��4��8'.��0�ʄ1���''/�l�%��)�<�����&|�� i)K�Aj�����R�$�z���sPK���3�X���3%o v?�qg��d?�'E���D!�ʯ�A�I���T��݀�ȯul�ҥ�AH�)�H�F̙ƚ��{���ן�&2rR�7��gLx���9 �W@!��;`�L{�v�:��OR�A�Z��9�=*U���Z�e�c}���͕���΂���,rL�Ro��j%�N�GM��@�m�'r{�o���dž�ra�l�I8WS��ײ���ӈl��z2�B��gv����k@��=���<+� u�@l��|;�]��}?�wM�^�������Za�ȝ�T�4}f�h�B�S5�1$��%zz�<�c�:�d�0��G���N��� �C>m&���/$xT��*F� `2�HQ:O�������a�?�Fy`�+���3}�����5aG��ϫ@g��H��s���J���v�h��� V������랃�H�S���n�b��!�X�?��y�D:�Rh�X� ���*i�9��k(��S�d���s�4�RMߏu>�w̷C�$������J�~sIZ�C������0��{�r«y0^{�[efz�:�����r$���F��q�_��� ���L>�>��3U��9!{��Dj B�,�o��D�bmd���mج�mr$�r�FEs��.~�a�%�鸥�|U'T�/��ai�h���H.`ߞ8 P�W�����'�����|���kjJ
+�8�cL��̄6?��Ȫ��KҲ��G�fB\U�*MVsV�?Y�e5�.L&&������wbzB�â��Y��a��z�e:Wj��݆�����6�M.���O1���.?���討�@� ��cnj��_{�����%Jh��T~� �&W(�����Y��_����~¿]][�t!�����7+��Υ���LQ�� ���t�{ܖ�A�uv�S�--��Ҥ"o j���ȐC|N� ���0�D�LE)�F�V�D�PX�{&{r�th�{��1A���4�Y���~9Ӛ�����,[J/Ɣ�%4��O����8 ���2���w^�����(p����m���1=�}�� �Ǥ��1-����n3s�v�r W���c�*��/<��J�9�t뽋�^�3<{=�zrTQh\E }�Q���>Sؠ¥鞿���A�p��w����5�X��0�6Z]�}!`
+�W�\�{<Fl����-FdYzA�6�9�ے�2�������c:�9/�k�ײ�(I��;�t������:'���5c>7���X�W���6_86Ql���5#m[(X��4Y4t����?�$YM��k7����&v���=��t+���y���A���s~��i)���>����˲�v1Y���c��\�v�~�gGS��0�|6�2T��k�Fq���Rh��y�fUK�J.��fz.����VL���Ĺ��5�Z��8�+����,���y�,?8R�p��V4�=�����t��m����F�ʴ��@�Ia �@�+�qٯ�P(4�әs9=}Q��~mj��SO���0 �y��HF鹏!�v۷����Z�&�)���ǔϑ4gho ����T��;|f�ȕ�fY�AN�"�&���_R6���kZ3a���ބ�
+endstream
+endobj
+599 0 obj
+<< /Filter /FlateDecode /Length1 1388 /Length2 6325 /Length3 0 /Length 7213 >>
+stream
+x�}TuX��ז�nF7���F:�m�`� "�Hww�4H+
+"�h)AB���������>�9�>��/����2���������QA >�)���s�C��Pw�?��p�=�V�G�|L�}&O��@XLFDZ����t���� g{ `�l���s�zx��N��ܿ���Fz�M�;����ix�� �����ng�SFH�er�e�vt� �xP9����nnw�7�0����_��i�' C��#�P� P�b�����J>��𷻁� ���ad���{�����x���$�bb)Qq��� ��4F��?d���vw��)����d�?�Íj��D(��o��������7��c�w��� ȯI��!`��������m�=
+Rvw��A�5���r8�ü!��f�`u�yxC�@@����
+ru�x{�7A������Cݝ"�{8�>�����8 HE1� ���B��T��@-��FK��L~A��DEB(?��7��8������. �9������� ȿ⅁���-�߸���+��)�� � GP���흜  AuK�����I�07OD��?��Q
+ �PTu��=�/��ӯ��!^>�0H�*D-0j� �ߦ�W*% 5�����|`�'j\W�*��q�O���)���A~�E}������ ��6��t�(�(o��)��< ��Q��q¿����{�=RiT6�օڪ_ȯK�#�_��#~;\�r��v��.���f=@��.M�]g ��~_�DĈ�>=ƵXW��ݼ�*w~$Z�T�ވ;_%���mu���ڮg��Pͽ��rtX�'����������~(�v��o3�;V������u&gKS�����y��eW�},!�FJJ�=�[9��N�Qyj��6�����^2���y�Ј���7�U�h�ϙ���D���9�
+��%�t��8���i.�sGwE�s;x��%ON-��e1���5���t6��Z3<bg_�b�2��}_А�;��=�_�t��F��SP&��ְz]�$mnj�, #m�ĿD��$S-�:�z���b��)�|�cq��{�j��f����e��&�>SM���R<��M�FL�p�g��%ȆifMx��;��E��1 �����H��w�:��=P#��YV[l'J��� �����O�b
+��_] q�q�t����;�N�@l�^rQlV��x�N�}�'����q��h�l@�GO%�mnץT��?p_�'���� 8�k�'[h�/C�V0�[���m5-��P��EO2q��&S�|�IR���4zw܋'sD�.Zm�/A�c����÷�Q��?�ś�S�0]� ��s��Vl�Hw^+0cl��҅K徙��F�c⿴���5�z�N����(�r4j*�i��Nu��h�Zo�/�P����uN��?�'� �ύd�^<;ck��+�UQ:�k��Nz�t �̊ �#8ݲ��I*�io�8������_�q��dN��� �����<�c�X���W��WR'�]l�O�Ȗ�׎*�Y�em8�U֭w�w��HROS[:lC�c�(��u����y��w�Ї�'���l31/0�R�v�����ՂV�I} �߽�zq�� �o�*Ȓq�>\�5g��{���ͻ����o"�ﭝ���W���VK�h�C�y���G��{�c8�mNe(����<���'�\|+�*؄�����-;�ӱ:�猪�Jۣ���,�?�Tj��N�Uy�/:�0�ٍ���q<��d�]z�]4 K��Ė�a����:S��.�WD�V�0��������9�VPbf!�ը��\lWݰ�ꆆy�k�f������M���Z���M�#����O4��w����z~��y }#.�/;�T|�E��n�ո�|�]^OS2���lMj^pr�˲䙾�ݪ9�$�o���Y��P~I��J�������SR_�SC��1F[�ŷd�G^R>��C�M�TG� �:�t1���.,�_�������+��)?�Z ��D�, =ۉ�6Y��N/�*��͗~{2�Q�F/�����~�b�KUEf�&"��u� 1��XR��72l�h��9$Ҥf���g>>0�I^86
+?Ѵ2z'y8q�����ܘB�Kaz>IVph�;Mq��q��ԒH�]`��-�ą�f���g¶�xo��!���gdz^Ta��ో�X�|YA�
+̃�+e>oT�1��-f�B.����tZ���yJ��Z_m��y�I*�#^�Pl��j:��ȘC��g��>�$��ȑ��*��.�m��r�v��� ���Z��'���1P���*��Y����}��Nd ��z���8A1׊�!���"�'!P�'���d��5��S��o�y_�5��@��{�S��Z�b}���֧��3��)AM�a��"�&�����Xy���E��r �ٰF&��g��z7��fi����0���>s��C��u��#��e�K<rI�?}C!��߱��P�(�m� �_�WY�������hAc������L[�fq�������}1��i�TJE: (��5�4P��?ʦ�M��`�`Ԙf�-�:��_ �-rxD9i�hat�n�+j/Ւ5�7�����o�F3-HI�� I��������&`<�&��U�����nl�K!oYˢcS�37 \����
+��R� \8�X6+��݊|E���$� 54����s��+Z���"3��U q���뛎uv.�{����;H"rc��<e~x1�@sws6zl͛.�e�_�G�)#�z���T�
+�aQk��D������T��-���ܫ�������56��S5��dp���[� �Ecl<C�S���[y%�H"e� f��C��T���^F�'Mm�2HU'g�9���#N-��HP�9�Zm�ǯ�#R2�{����؃RȒ�S� ^��oVN��;G��aƅˎN*Ӌ�A��5neJ!�<�nJ�&������oD���Wԯi�Oδ齉=���V]�m}��@������:j����_n���������� ay����P_�2�+a���-�MG�kD#��9~Y���;%������u\�-mM�!��g��Y�<"�O�8�N�fN�_��bO�-ʌ�&8X2�l���_ʿ�����b������g�o =���"(pzA?,*���k�fm�����0�"m��?�yx���1��eW�������C�a�Vc�c��5g�է�묘��+3��T�j�lHёC���O��)s7�9�{/�L����Hlk�
+���� ���Y�<��i%Me�j��'�;�2�ı@����v~L�!~��/����
+9��Ma�q��X�OW���}'P%����lư�����7WU ��ߧ�r���&2P�#y���. ʤ�� HJ\��u,q~p|�pIe�?K-1���� �5:�^�1K`)9��/+��
+���Ȉ�uD��d�������(9���8?Ͱ}��ٲ�Q=Ae� cW���ͳ�^[e��ۻ�7�E;��S<)�,
+m�S����MO)C � ���A%���1i
+��F%"�Y]ɡ�v�/u&s"u����� '��G�\���z�*�'��2�������j4 d���XOR���M�G��'h�)�a�)����1��wx"]�������PڢQ��?]�~�Z���7�rȱnȲ�,���'��q��1����>\9�<ď���z��O;�E�I��?`D ae$�A�� 3&;��d��;���J�N$�P��m�x�ш���[��@� 2�r��OK5#(�2�'K�p�8Bnh&���e��N� � ݬcUd�O M��%&�O&��� �Fd1T�R ���3��R�[Y1�,bjiK��]�MYt`��ȻB���;r`��i���m֊,/��:�F$�k2GY���k���#_��/0��I�� !��Vv�0� ä��2o"ck)�,N�D����1�w���B�-��o�^ը�Dݩ)��L�mc����˴j��ͼ�G�����B���s�2[�Y��<J�����5Y��F�n5�g0<���+�Uj���=1�����"���O��f&���u�c5n���K�$Q{�7a9؞��h�W l+j/�~%�Y� �Oֶ!ׇs��g��3��]+���,� aԲI���`{�.�<$��h����.�^���v����Or�+��:�a�/�渰�,;�`Mߠ"զ~JQ��9���տ�-��e��+&{J�΂�E�tsD��д"_�x��s
+v?�Bi���v�1U�^�g,�� T��|��LTRH��v�' y%�
+c&`�g�)Z�@H�V��bK��cV�"����<�,���aD�¶�p}����N]b{��`��kf6M!y謴�7�f�/�t�-왮B��o4~ ^r�K��E%h����뱐�J,��Dw�' �����{�I��4�a��
+=4{�/bA3���ԃ=���X;�����̟�ṏ��pˋX¥�B��jT��?ƚ��p6�s��y�mX%������T�\_�7��zU��N�����A�q=':B�$=��E�*��AL�����ּvYK�}U~�(������0$����Oc�?<Ju�;���|�%;��Ԟp�kG��1z���)��3��
+�"�tr��ԟ��&<��T�P��ݫF��Sb�6�$�S{�NJ�fc~�Qi��y�v8��u��Žf�jfb��[�ζ��b��i�V��h���!�˨�h3��j��ni��������@4&.�;�B �'�S�P��⤍y�)�}N�Q�����d�'a�\*XQhSTe�L�>Ȗ���7?�;Ӯ1T�m���i�8H�9�9�������Oq��aR��U��m�D9�g�Ҝj�`l*��"������d�;������z� ��M���_M��t�������*'�0E��H?�q�U��V�x4k���,�w�Sj�h���5uN픲�H����p�)��7�#��4<�y��^�#����"�����!�ah�[yT����X<� c�j��Z����ϳ\&@�+���E80<�D{ަp���;�`��88�J�ߗʿ���&n� ���D*)J��'{�p��߯��:xJ�r�U��I�=�g��~WŰV�|���Z��Ew��],^�q��i��j$��M }��O�[<���Z�(O^��S~̓?�1RyK|���!{�[�l�����e��۹q.�h��Z�����m��-�R��[��m�>U�-���Ԧ ��➩9;�A�����o�[��u[��O��j0y���6�uEV���#�����Z��
+�B8i�E�IL=ru��sբ�o$:�=?ܖ ^��jo���\��j�{J�`�Oz�YQ߈cT¸�72���''��I�L���A�C_��^��;��٩C�?G2��o$ل$�&�|6�&�s��-F;����)��v߿����+�n��= ,��Ҷh��ب*���|Q��� �m~oAE,$ ���\7�I���݌��F)
+./�B���"�>��������\lWИ<<6�� ��Ҳ����R4��!���49Z�W̦d � �lغ�+�nۦC�e�G方l�3{���n����VN$h/uTx��~H�酾 �+|�qd��᳞���C��Ƙ�ˇ��I���Ce���caʧ�Z@����o���c�`���b�)#x����Rk�x�]:���#�#�c†���~��b���/^�I����⪴�N-{ۀy;���@9]š�0����N��S�����c'���Pg�7O�-X֯��&��L��4ms�[�h�- %��� 3��/NSR�%ŘR���
+�}��`�/b�ǣ
+ %� �������8 �v����Tl^�5pRn��'��^}X:,�1�X8h&m:e��Y��N$g+�IN:'|�y �V�:�v�CDJ�h����wV�
+H���U�t�NъtQ��?�4F�� ��y�Ѓ�ї�~v`�?���5��g�P�y�˫���F�I�9�����<P"�N��T����FG������@L��h�B4�{q����ܯ:T�A�N�:�x�i�m�fb3b�/�Ŝ����؋�6�yU�;xOr:ܚ�Z��2#�@���@Ϩ%�`g��E��]c�^k����g I�Y e�����ă��8u�1⏖����6��O��1hv^Wo�9�V�MyR1�� ���9���ˍc�K�?E�4؃�%�xC�i��E\�z�F�r�����󌘖�f��M�T���y� _���ʹ�f�=z��<t�/2��o��B�Z<�s���-�:w�_-R�c�"MK�rBv���|SP�J�i^�1�Rx&�^d0r���S1��%���`�WO��]��:�l�.u!�>/ ��u#�lA���C�I'��t�Q�l���Q 3��
+erN�L���^��뭛���-��>���fE��>��9�I����%}d�x��}���# Y�L��R�=��s�Y����Hb9�Z���tf�:��}��' [d�]��� �� /�3�&'��h��<��t���u#��ZR�B��M��n�T���k���n��6����ۭ��E�Jiƭh�D�)�u�'%�6�pV1��A �ҙ���`-�$JJ%��Řag� yu1�3��#��B�?�k�t~k�d +q@� �-�ݻA�ٶ�]��*����3���4θ gӎđ��������8:���de����<�5"���(�pu�zK�$����y�.�ɽ��B;����pD8I��W�vz�yl
+���OK'8��%�Qy�dH�K%��Q�d |qM�,(����:)@���Z#�
+�7W��������K�������l����Ⱥ͇qx�\$я�j����WRSE|;�^l���c�BOK?��:E��V� ћy�KT������� �.w|��R�n1�u+���HL�E�Q��.d�}���e\>g � ���N��?��FT1���&��S�84�Aɱ��I|����td��/�s!F���,�^Y���/g��2��,��d�.ZS~m0��>[�G�O���I�*u�rU��Ѐ�8�d���?0�
+endstream
+endobj
+600 0 obj
+<< /Filter /FlateDecode /Length1 1873 /Length2 10572 /Length3 0 /Length 11556 >>
+stream
+xڥ�P\�֮q'Hpm<o����4���݂{p�A���[p�g�d&�̹���u��v�~�%���DA�N���$fk�D�D���1798�ۀd ��d%�������B���
+�_j Gs[�3v8�2�Wu�1@d`b01r9�X@F&ο m���Ff +������B����������L^U�>�3�(��[��l����I�������_*����g��C���󌉉�U,�__���;��蒘��)����Ɏ���E&�� ���8���/C���###����ф�����L!jc,lkm �qrD`b�9 A��6 �Rq��� �?�_�`�����u&�����6���r�m.g` 0(�j�ʉ��s�[ �~x�1�t@f�׉����� ��� �)b��,icb �K����_�]�\��_+B ��`r�N�F�]�_G����h�za����02�os����N�B(����c�Ĝ���5����A$� �̍��1ks+�8�a�OCuПٕ@��V�G���g.AS+�� �'4w3�2V0w22�X9���6� �״
+���T������33s#K��#���#���?$������de{홃���NYYL��H�����ml�^]v�N^��p@�c��X8 F�ψ���0؁�m��f@ ���I����7b���~#�_��7b��8~#�_H�o��+��{�o�+ �o�ˑ�f�_��o��� q�F������B��_�E�F�]�b���u��D�u��j����藈��ѯN���믌������ ������[=�_"~�g�K��o�����W'X�����b��/�l��fc��~���K=���~�g�]6�/�lN�?�������������f�uob���@AF?fm��-j�n��]���y���>�/�n�X��0�/}����C�.i�&�A>�,��G���#��1v*��ϖ.�4����ύ+���G�H͗MK��o7%�� 9a�?��B)�M����j��k��d�. �ȧ��gR��B]���< jr���,2�b,w�ē?Lη@%���@�f��`�A��RSܨS���2gC_ugv���[mD3S�k[�Jm��^����h_p�)?���������@�\m��f�r�d#w<*���3��\�kWQ���79 �A�L#ID�J� M� T-���0[�$S���d�igS��Ƕ���Yk-�<�XS�Ÿ�V�k
+�D���/Ͼ��������U��!��ыr�ZG���r�>?���5�b����5=�� �KX������ZM2U�ՓSjƱ�5a�j$��!� ��o{t�on
+Ӎ�t0�I܍ʒ�g�f�T�urs�� w�� D/�?^%��D�T��!/e0��̷�������̣��֣7��c�h��a' ���1��l�p��CB�z�G��U4; ���u/�����3�(ř�Ǖ���ũh�����i)� �jJfR�g�Ov0�?H��ӎCo����bt�c�0'�4m\ଔ����y�b�s7O1�iqw���簈��
+�� �M�_�)E}�����I�X[T��:p���N-Z~�j�3�agq��}�
+�4K1��I��
+��|d9���Z�l�ӪG_��ȩߤ��?��9w��Xi@L��O��M �G欷���z�������|��1>I!A}� B��>K��JVBu��Gʚ7����i��frzw�l�j�W�
+]rW�r;�5��+��#ÜWVv5�Z�К�տG+��X�����Qk���\1}���}?t�6��EF�(��D���*��k�9a�^B=���d����:q�qX����D~W A��W�[F��{p|㈰wy����˿!٘�p7�d;&Ɇ(�펗��O�$GiN/&�5��2Ȝr���e<���� �ܝG��m��74��5%�A��ݫ�9�3�}!���\�ďE��mjG���NOg��#(���o09����XMi�oJ5�gm%^>�##��@���]ޖ,_���Cx�9�IE;|r� ����tW�|)N��u��Ѝ�m%/������[;����:@�t���� �h���m��V"��g�"3t���0�ֱsO}�GB!����=�sK?�"]Q>Y�Cj��V��F r��w�Q�Z_�%o�n�xZ]��Z�$B��4��3w &�C޷����]5����PR�Ad~P4�Y0�����njl�C�QI�[S��aJi�]�� B�[8C��v#�:"�1�D&ԫ�"M��jT�*�6�1+֊�>�a���5FJ�E���E)�S3n'�[�J��~Z���Kg���(��V��[P�B��~v�d��A�p��ZE"M�(. ���R�i?���U !:�+���Y��~��\�e3��m��Diy$%/�4e�~�_�ᒖ8�J��G,�姺��[��� Ra�A]'lQ��K�8��ζ�T #~S�խ?�c��ְ�n�`�Q�N��f���`���|tU3c��]���Ec��۸u3���;�>(�Ò_��V> = ��Jd,R���Rn7�#�4��6����e>�E����(���;��9#�v�'���B7��֒ݚ���6���L��|^�3��Sh:�y55V)����e�'m��!����_�L�{� g��#�ze� Dz�Z��|#�֞�&I�GT�`�<u��]Aj��D���I�Պ@���u����6cɼw�o>E�2v���|^����9�����t$����!7!R����{��En��'�b��ږ;y��\&!�g�4ࠋ:�c(e�"�ڮ����P�Zk���
+����d��ƕ*j�I����N߇z�P�X��B���1�� �d�2���1 ��T����t����t!�6Щ(�-�q�5�4�QO��$�r�w��$��^�N�E��M9�R�٢i������\��&��<�j�P����~*�2���c���>��&3�� ���Q�W#Y9'Ł�/�q���%��k#�"���T-  |L\���b���[r��V�g��
+����-N���O��zi����?�a�Z��9(�`{������4cN����k�-��b���D /$�Z��OuLf�q(�J;M��F�M�A��7� ���qJq���ED���"*��{��LR�)~�4Ǵ�o���3�b����B� W+�dόO�~6}&��6H�q����I�������
+�yd�ܩwE����w,�%hv\ �^����Ք_<G � � g�d^G�5��$S��
+s��� ��ƶEHG�Kő}t��N”b�%M����"M�|f]+}MH2�|�.�AD���#�~'" �w0[�Ʒ���!9l١�M&�{.\��q 2�e�B�ov����n���`���T/�a,Rt���'��[���=�X������F [�fQ�Y�\�#M�#�lW�RmD�Kv_�Y����(�"P+G�� c�sJ�Է����{f�q_�kb�л��E � ��@���C�������!�*���X�����Ƕi]4[ĶL ?LM�0�vVbLn�i��g��}j&�S5�rS���f�x�)}�$!_|�L U�>iF�e�D�o�CB�4~�&���i4hʰ����F4W�lLΧ�Xz���G����� !�H�<���E��N��J�V�xGq�cNk%t�����06,?.�e&kHa*q��A�u`�ߢ�z�n�I|;u�4�.�P�������򳺃N�3w:]`Y�5�d��^�̻��b� D�s���s�⌷`S k��}o�K64�˲[�k/��.��j�=��N���Ւ�Fᵜ[e"��1�]c�FVp6ā����t��z��5�� "*��WlS Dܑ���'�^虗qm�EL
+wx�X�A��~���{o�Y���)KjU�IS�����x�V}x�1��,��'�vՆ���9�n��xЬ��PB�˿w��寠�w��ԩnh_�1T3��!��c�6J&�G�%�^�QW]��p ����*�1�a�~�%\w��1��`.Yn��B�7�?M��x�s!�?�X�P�K=���'������6#r�A�%c��Q��%cb��:.L,��D[8y�apv�آ����:�\O��a*?���)�D�L-�U8bY{���m���1���W[��aO��Ibä�,s�(
+X�{����A�������DSX���^�O�+��drT���vaD�DŽ�����1J)��Y�{��s b/�\ū����; #�O6K ��{��� ��݅J =�i��-2BuNR��nP�T�eE�6�����:�x7i���3�ľ�xe�N3':�"0ƙO%�;Ej���f�>��IeCӌ1�<�
+<[�*��]i�,�x{��X�ȟ���c�Yf�a`�<��#i���M!�;�:I B��X+��v0 r�Zi8`Ԡ���u�<��k�Ә���p���تt��+�~2@�����0��_�z�ʷ��!�jS�$�K��}� C�g�c�ԥ�%���KC�b�I5Tc��biትU��o�>���ےJ��K�)%l�f�:�Z��]�m�}t"��7��5�=fOVR��:�;��"G��
+��JS�7qh�P�_�Z�*6���$���Y�V���w=�&7P��F��]J'�`N�|�8�0od��J��v�����y
+��� �d�����3"�e�:�cHv?X�D�k��)ȼ��T���k�u�G�q��}��z�E�4A_�������A]*�f5�u�)���C� �X��(�vO����(���>c�o��1��+r��tU�q�ݮ��)0�&J�����gҊ�V��mܦ�8(*�A�#؉���FJq��W��*t}�Ļ qޜԢ�Қ�Ϲby��Ue���I~��%�:;
+R������^�C�,p��e��ˮ�� ���]|�Fd
+�cܔ2������4kx��}�F�0�X}�t�<krO$�-�{�AW<u����Q݅�(!ຎSRl��9�KI�!h?��|gŦF|���eu�yj)�$��J�m]�5�=�q*������ֲULҗ�D�!������C�t׭BN�q���N�,�j�Ƀ����l�\��~��Rf��C�I��=���vA�Ú]�7��cB�$ D�%�)�>WZ�%A2�O��RRvd#���ǭ/H���}D|� %�
+j�C���WLGu�2=x�=>Ob-�Z���W]�Qډp�� ,��-�s|�Wz�c�z�U�O�K/㩡��K� �>����FzX�F��9�n���uyYt��d�g*Pyt���ʦ\�4ɮq�!�E�A��JL�F{�յb˓U<M�2��͖Ar.I�.�8��Q�*60*#���-��%Ci�O��V/ �����+&C �/� �m%Y$\��t�ϱ�6P�ڹ�i���ft�b�#�����8-�{�G�զ����gA�{��)�!��C�|��&4�0#M(P�v�~�NƢQ�3o�/ t�W�Fw`����>�*��%�\�GI�;�s�����0� �K�f���}��PJbD<�^�lU�4�,y��b)(�P~����\�v�/��z��>\�5f������+Rҍ9������[� ��p�Ӯ�f�37i(�l�7� ���L�6Ub�h�t&�������F[����.��� b
+�2 ��+�J�Hҕ�>��K0��[�'�+�o�YF/�K@
+`څ�rf7v��`�U��ɳ��/n����&�!6���H�_PJ0r���H��)��m� ��5�,�xwA�����(�:���ɏ����E�Y�Ec"��wKyN�t��%���#�Xvލ
+Ӽ�+%� �%=��"S�%�k h��˜/Y�U��{�u�l�
+˳��� _�м�7�2O��YT�M��k,;*q�s;mW����̦�{#}m����� vh�/���NϽw�27��Yt����R�b�( �L�ԟumT�`�ٜ�a�FHU��4JJGg&��`f6�10/^�;S �b���sf��bs����k�#p�(C���-��Z��9��L,����&�\��3VD���g]On�s��KW�h���/_��G���3�n; ��uV�P�}>�bY1�Ph�yg�Gs�z�� �13�Ai�ZeH�9in���5��������>��
+ ��–�a���!��Z���P�H&oX
+S���ط��9��y���?`ز�5�to!��Rҕ����VK���|��x��P�o�{�6sTO���\�y@:#���?��f9�wr��WRCwȷ�ؖ���c3���.p|���!�� +���>Uq� �J�X��<���9���d���ׯ����^�~G��F�Y�R[��o2��oj���e���-�����k�I�A@�rRۀ�79r�w��t�Y�S}�!�;}m��{�4(Ř�!d��D�D4�\>1b3]�������}]�i���;4�4R�L���C38E<��q��x4`��1|�ْ�����t`]q����p�~��$ؿq�2�����_0��6�ڧ8y~<����Ȱ��6Bf[�<����,Ӻ��yͦ �&�P4��w|�օ��G ��N��ù>�7� W#Q{��l��'g��L>9�ު��c� ���݄�m��\ҧg��5:����r{���c�s�����&�P�A*�+W�`��#�9@}q�]��������ႜ̉�S��˒��Us8R�;�\��N ���Vؒ=N�3m.+�Ճ�\�s�������h���c��EH*�����t���t�cm��Qae�[ �1.�pf�&�Q'~�����B��yҹ�=��8�FK�֏�W���3H �XF����R�}�7pކ�4�L<�|oX0����NާW�$��{�9f�c��!zN�����j�KH�-.����5��H�%9iP;�+���S|9��nat? ��"�xf`u]����zWm�ښ:��˅��O��dR��Ā[����2s�^�|�d�F��
+�2�N!2�� �)�|_���Sh'j��B�c�q�s�d�����%�!�o �\9� u�rbA ֆ<�6�'��M!Ǹ?�ݖ����@!�h�by���A�����!²��,9;��&o�t4!��${}�$��t�3g�Š[adr��Q+�]�F��K�!���4�������y����J5w�OHON�g��Z<��L�8�]�|�P;wn�e:�K�Ʉ���J��&��L1湣���*d�I��~j-j���D�w݅]@@����ԩ-
+D��]�|�3�w���EW�"n ;/��Ҁq�#-v[���É�e�M�0��?~3����^_����h��QsQv]ܔ�u}G���:�Z�͌��9��b&�T�j:s�h��Sc(�т��� ��2��T�ˆesFz���*�<g3�4%��S���H(ծ��hw��[Mt��>*�ֶh�zt1����[[�ݵ��.�J��s$߮�Q���'�`�����I6_���+5����q\�B9� ��
+vbU�ju\�D��g����y�Q������[x�:i���b��_����#�X��⩱��:�?�=��S��!{.z ����R�B�T4���q���<'�0-;�k�%���m'������^ ��1x� �v��x�$%Z@Q�"�A����
+2$|��w�-@'�^��W��Q.֦“�vv¡oJ�9߂��q�\�]k��fv�?D� � eCF,R�6/��aad��y$|�ݎ�w��s@yc(~:M���V@��X��r&
+�� 9x��ʠ�,Sp6�x@�ƾˇw�� ��L�L�o'�QAa���0mtUX*�*'�_7�#�5�kYqY �u\ ��c�~���0�H�Z��{#g!c���G.�%(n3��%��:��Ok���t�mt�J���p3�����w�}r���y�׌��U���\��G��s^ �%�6^A�CP �D0j���� �op�h���B\1??�T���τG�$#�sCa閃�oGPY�CO���U��œ~�l*`0ԉ-�Q���4Z�Xf�Eۀ�?Z]b���E��C-%r�_���:f�!we�O��8���#q ��!�iu���e����ޢ�
+�+���R � �]jy����h<�����@���0�<��u'U���6e_ �`g�h`��N
+�8�`�x�D���T�S��{�*��O��ݓi�|�6f���q�<λ �:tc>�]�( �=���o�cjm�a�lIۥ����C�V|p��c\�f�ع�?l+����T�%"��%U12t������i�(��h9�N� �G��DՊ
+�+u��HF!|xZ�X,�)�D��i2�P,Թ���R ��V�*i�҅�����e"0{
+�WA�٪�}
+����hM$*�-u�`���y���'6��"s�U�j{`��]xZ�ɹ8K�wQI��r�۔*���v�@0F:
+��b)�"dwӁ���m��E)��-�#\���'@�5}O~�lA@��8� k`I�(�P�Nl�qw=�)��%=���[cnJ�J2���m�}e���O�^����i���ڻ�G�" zj�]���Ng(����f�" ��pR6 hק����lz�z�U�醀S ��]����W���}$R��&��
+R6��7G�nk��?�8S�aX�ڃuoB���7�)<u��w�Y�.�:o#o��48<ݘ}�Je�f��4g�����_|�u]飚��?t�/�1���[5�q� +9R�b����W�F<��Օ�qLZ'�����(�KĸU���曭 b��Ƶk���c����>��6��0f�+l4�M�+g����_�Ð{k��(A�����f�<���j�e�ְ?9�pc��WT$�{�idO�hJa'y1�g��I�� �O-�Q��|�V�g�˕��d�����g���� ���5�E��������� :�X^��d ^��y��6��5��*{�8�W�Q2-�gSK�S�4���!�Vf�mH�.L%��R�q��}�ȘzuQo�5ᖖ_����c���k�,��XZyI���T�w~?�����n��si��#=7'gby�� � �Sz�����?�c�aL 샷f��K�r�K��UZ��i�'��1�Uˎ%�۸`�w#�;�)�D�280P��tPS:�5�§B9��:� >��%�}b��+�G�fv鞕5��$����C�̯;y�����'dW����}ư?e>0[�#��9�Ң[ft��D�7�q�����3?��Zh;A�# �}���|�Ӈ���PxQ�
+P���+Ye���䩺�&��7l�.'��\U��<2.��5qi��P <ؤO[ú����Ȋ���Je�lk ݏ���ƅ�質�������EIZ�HeӮ����@��.h�M��� )gꑀ` y!CZ_��:č�φ�S;�.9f|��A'l ��2cyh�EH�q��.������A���+8�UX�ۘZ�;������} ⊉�X|�4<��t���`�֜���}���d����[2 C%���`��~��*�(�}�0���(�����M{]�Ld�De(�ztY��ǜ)�iL؛����y�� ~�b`��x`��I���v���;�B�v�3�C��K�p��sl2>�D�:�U' n�C�m6�,�n�a`m�t� �y��J
+�V�00���"i
+�?��<m� T�D)[%��e׬��=�3`��&" K�$%K��UrfR�V�~B5K;�(*&55���R�0@��3���q��ir�"uLƒ ��˝?�U//OدF2�+�B�R�|k��t#m˛�( <�Î�b��"�p��ۈr�̰-���;�_"r)*� SoF�*拁��B�w���h����[1��gݿ�L�ޕ��2EG��A��O�/+ ��}"���t���b�����Ŷ���/���������U�Z�cQ"EqC�]
+�rJ�[��VZw}���z$�d���J�j�1��=�;�.To���ƍ��TW@,��Z���h���S�&k��g���<���OР�V��!t9[{�,]��p� ��̜݅~.�L��k�d8�ԍ[�G����1����
+�����1��sO=��N�I�+��%�O�=�E>mA��|�n��K��]����R��P��O� ��6
+�Λ�����i�K���/��� .�1��K"�ċb}*�7$\q�TEd����M06�ޙ<w#np��H�6����E�Al�v�y�bi(�x7 C���O�{����.�y8[=�ޱ5B1 �@[�YP8.��'z��%j�"�s�'����U�XW��ș�v�/�]'#�>ߖG�c���]9t�ert���Tm���B?1^%�����P�0F!�w�7���% 6~�)�1S-u=�F� F������8��w��v��R��hw������ ����;^�s�*LRj0���8\�V\@� ��闽��t%�0B�M�r��J�v���k�Y� ��z#���w���5nh`^lW���vHaof���']C������<�]&�/�"©u7��W�k����H$
+L�C�A��2*M)g�G�*�˕J�s��I�&�}�W�*x3����6��� lA�*�?߶s�<�o�f� ���3�ͮ��!��e�X�A�0rO�\7�=�lP�&}�.VV�W�!�[X�e�y* qs��T��cj�Kg\�B'��og˅dT��ľ2�w ���E��iP�\u嚈:-vJ�lB�l ��X}�C�ɏ���``�}���75܋��%�RW} *`�]QZ��2�����;��:�^��JM(�ޣ-q��ET#���eaX������;��e �r��wc]�&Q���jE��`�kV-}���Ҭ���m�cȼ��U�B���ۘ�cM� �k2OM�|I��`���¼t��7 G��'y�sĔ��vkd@�,�X��P��w�Bj0���0\�:]ПK��,�4�|+T��ybdߓ���a>�~"gՉh��*��AV�Cz6Ô�2�V#T��*(�&�/��e�N��*���D���<���~��r��.me!477 t���B��R2#$��� �j#��v(��h�2�����m�W ���;���k�3���)q��=����/��0�s�mu�)�^(�*D^:�kdH���3 �o�X��E� ��%& _'��m��z��Y�0�kf&r�f�?j�9~�8��I���p�F�)�|Zz�c�\QR�Ttǿ"Q����{cU�q�)h��l~DP��8�u��ɣ��`�r$��@/ɶ�6��)hXz~Bąk?`ޝ��?�o��[A�ݻ�=8����
+��p���/*����.��B����?����'����1}D��-9�I�hT_��S h<9�KSw"��ʎ��� ݂�ߦ�슰ށ ���G2<��e�(��1���}-�e<ʓ
+endstream
+endobj
+601 0 obj
+<< /Filter /FlateDecode /Length1 909 /Length2 63390 /Length3 0 /Length 63746 >>
+stream
+x�t�t&]�5�c'?�m۶�'�ٱ�1:�m۶������=����5���Zs��kU��QUdD�*tB���@q{;:&zFn������1�����*`�g�g���Z�����v� �
+�7�TE�UE�i��c
+4�� );3{���5uu�o������@�oq*����������.�&@�?�����{-,m,��E{ZX��_��v�@'�*���`o0��m�nigw*�f.�FN��L�v�@gnX EY�.���ddPt5��4�o�.��������0:���x��L
+�������à��g.@�����)n�d�'���Ł���_jf�2�;���]t�`U�Q032��� Y��l�F�#ǿ�����/db�72����Y9qW������*@��� �_ #[K���k-�-\�������t���*Z���S6#g���+���� @���_F������Ζ��,��T-,M����V�������3�7�W�U\�錑�����V4��sQ�t����1����8Yzt��� �g��=��H���do ԰4����Eaa{�7; +����3q08�X|�7���� h���K៩�������@صe{�`��?�.�X9Ó���D�b,�C��V�g�ԚA����Ұ�t�ᄳ���ݼ�d|6��E�e~��R���r�y�*�P�;a_-�J� [�-�o���Ρ� ��c��i1��:1g�%zy- �a{no�nw��J��Se5�~�u^n�]�0jf��*� e�Tts��A#��ex�iL�M�1�'V�۴�,���>&��!��gB���n��p��'�c=��Uw�EP��4�-k!O�w�F���Uu5,����� �����+:�6�Eq �C[*̹e��贅]���Z���r�<, +��dˆ�|<��J`Q�Ps���As=��0R��g�=k�3f�y�Y��9��gc�IXhl�<�M��
+k9m�=���� ��h/����X��4b��֬���1; ۲ie���ʳ#ʍKb"��d s�‰�}�0R��� ϓ�m�9Y�e5{v��l�����!��;��{/J �ުSSo+�~�P
+�����8��� �Q�n0�P���d �a�r}D���+N� ,H@Q��AͶ�<��e�(̈́��q�[�Q0^6o1�� ����K�����7���|�"�o��� ���][D`<�ų갵
+�d��'��פؾ#���܈�zq0���?��� 4-�����v�ŕ��G-�J�uA���|=�.��Q���s�����]{ G����u�>W~�qGi��k��G/'�{Z �ou}�*�+x ���sH�� 2>�O���Fs� �*S��5��q7�������:���=��_��`-�!��BI3cEy�v����y*x�������H�ӿ�E 0D��0_dy�����ۛ��JϘ�qA�^>��P4;��,܇�����F��U՞�r���Y��}qE�*�[�B:3s���S�o,A�Z��@���2s��5�H2���^T��x��~�ii�x9�N�8�fr9�2�r��7�T�.�6%�$����ǟ��e�)�V�D�Z��"����JS ��8I[m�ç7*�=i�a
+>[�������7��,����=׽�kt]1��>��>�﷔������06:�_�N"�t�(
+�w� �\"�h��]��!��ͭ�R�JK��X���2.z�/ 2l�Mi���J
+��805�%����J���}u�&h��EN�qNu�DŽ��"�3�e#�OL�2�p�qK�j�Xv-j9�.'�F���L���ڏ;��^�������/�FsDD�+�&�'>���6M�Z�`�hЊ�'�)vuh����lQ����/XR?� �Vҟ�Lu���/���3���3���Nw�� ��c:X�c-$r� �'r��D�]��g��!��~M���&��W����0�m� �!��S.0 A ���+~*�̓5^2���e�ؽ<ՙ�W�͏.���w0�<Q�='��P!4����oԝ�%ʣ!�7(��1ҝ�EE�<Q�<џ+��5�%�F���㰥�4<��X8� -u��+����P�{e y��v�W- ;sh��-DD1� ���W��` �e� � �Ҭ���a��~��~����n\7'�B1�ܟ��f�غ�-�%�����"mu���'� *�+ٛIyc�%��$�W��i��Ûf��w{�a�b��s�
+�~K&�3��9*+���-v��X����.2�M��Ȝ\i>��7���-q��-Qi�ÜA:�> VCԹ�&�^A�hD�GD�sr�I�Jڿ�wj�!���.\~���}�=��-���"�������X�C��V���Ԋ���m-��c�ݑ�].԰1��gD���lĒ���"G����Q����;�]7.s ��������%��� �"��ӑI�-ar��r�:_��N�q��]nOõ��R�{�<�Dl���ԔH�w����!�q�̄�A�#9��� �+.$UC��l�=E�w��N��1L�}�� o�P^b L��'��,t��b�)}hu�O¾�b��v��ԥ�-�X4E,�R�a����؊�#���ղ�'�~��#�� ����R/J�*�6�'?�~� pW��NT�����q�fG�(��?`��FŴ��\���bQ�s� f��٧\F�2�8no��Y�P��4�U8z�-�h���i@�z!F`Fw�[��g��'մ@��F�p!=�_+��G�� LM;�/�U��+�7~�w6��/u!p�}��Q�F�p�����S�8�ގ���~@.��a0����(�����9����8_�N�"�km��?� �~�� �o.[g��JAD��܁� �a������[w�ճ���$�Z'.����ՔA��ø��{��U����n9��[_��E� #�B�8�t�ƙ���
+�ŕ � ��)�%���~(S�y�G�N��=;{�g��\ܨue��P�k�`F%����*����<�����nX�v������~�1Q�z������9mUh�n��_P�R�^,{ ���E��A��qEߺ�fU"��f�^�W}L$,�L!��1V�=5U���^��gd��$��']�0�p�������&#�f(����3x8ۏn0��Y��w!7�_P�SEh�1��2����ѿ7�(�Ei2��q0_̬S{��y`�*w����p0�� /ԇ�2&aF�;�]\�U#*�C
+Y:�V1Hj%���l�>�����+&�G�̤�s�Y��H$�� ���Ck���'�Miq�qa� �=&�.H�vgnI��8��,��������2\D���+����G?�4/B F���}�ߨx���I����'��IJ�B���@�
+�L��L8q���o�/e�2�NF�E�f.T� ��)�8L�<�q(e�a������s�����u"��O��/�l��?-��pg�2u�t�NG���0�WN���揵��U��Rf6ߩ�D(�>I�V���N� A��"R�07HA�Q������%��U� �� #�� )� �[ȞY��1��|�]���$5v-^�R0&��i��F���J�R%�Fݙd�
+@��6��&�&"7[/����%M��˗J}�׈�,�G����QeLJ��sT�pu�V rX}���4���xH� D�v���>A�OqNܵ�z0��%oh��V��WZ��1�M�����Ŧi�Сc���s3��6�͏�s%}�?�5F�����aM!/asX�z؇��ܷ���O��<&=]�W��;7�����v1~t/���:�0<rb��:稶�N"���ᴠ�߼���,$,�[��\2� 񈻃��Y����S�Mp�� ��hci�J���qA�-���5��K���#llל�Y�B�c��X�լ�~�E)%eڒ��'ڰח���B�z����D��]�S��5DB� X��5'�w�eV�~z��P�7��d���|�*v�;7���cÄ��h�
+
+�ƃZ1��G,0
+�5as�*:�)~��n&0C��w�-$E?er�^��uYP�JJIE�:� ��_�X����U��&�z����ڋ��2l�������x�p�2�Ց�!O��Z+�d@�d�U����/��]�ܠ��i����.s�Vo1�l8���0��`�/��2�z���䪕0l�E���a��#����K��.o��=?���D�N��e�9�v�Z�몘Y�0a5Slhj:E~�=��'J*� �i��
+���2-<;s���c��6Gg��Wn1L�_5X��IJ:�f(,a�V��Ҩ]�q�C��}���>�����/~]m�5�o�Gע��ThtI���MR@��N&H�^������3>��A�.�/n�WQ��X2��HK���u����FŜ5�=o��>K�~fX�!�u���oI�fT�T��D^W~��9TSC8R�J�J�5�dyS���;��\�P����מ��^ez�O(��j��������dR1��&�l���d��Y�O��H�H���i��n�{�- �� ���W���a浐�]d�8�М-��2��i-���ۨڿ�n���J5�K�f ��/g����P��{���]�F�aV��頩w���<4w��Zv��}�8��ހ�f�:�[?.T�� %)�6bI��F�s�K?Z��q;=�����$�i�"8���o�~~�|Ym7��YW����띹2�p[�˂�h��'%�uв�6CCCh�K!m���fc*�b�Ⱎ��@��|�O�[�W�DX�
+F�t��ޯgy8o �b1���+Z�I��������*���$��?�~��PKޒ��Ao��B�N'�c<���@��l�Z� �!�7+�o�"/��":����Uʖ��' �oS��!��-m����:��.����
+32�?#!0��2��!���*܄8P����n�/3т�o'9t!!K4~}ݵ�:�[�I��U"E`@N/X��JDE�iAR-룈�|0�hK:�{ �v ����d�l�� ���#_zȰx� �څ꘻e�b������3c���Q�+y��8�V@1�+{={���579��=�~����/ �^q܏�8�� �A\ �� ����A���S��ĵÑo��&M;�����׌7�J�y�~�z@��죬�mR业D3V��*�����ā)��q���r�1�*�Y�}/�3��D[�lB�lWib,��z@��o,c��":��pE�7��K�zo��R ����#t_�B�ɕ�'��a��*Q^P����BX�Eiپ���;����?�ώ��΢���}Z���x�h�gk�>7s4Q�{�O*����׹‡qm��{(׌���FM|�X��������A��ՙ
+ƾ='���p�:�Xra��ؗ΍hw��ڟV6�l,�;x�"<�[>�^�.
+'�cż ���۱l)�c��?c
+�$�Yt(�3Mh8�P7M`jI���v���YM
+G�0��/�6���5Q2O�S
+�u�5?k���W;�D C��S��k�~|��<��D��M��ӽ��;g���dV��Cv>n��~,8��@u��rE0Vp��Sx�\X/9��z ~,0���|�,��<{�iW���ځ.�@WkǨ��s��F�o=X��7���63ȇ���%tW:t��}�z{x+��A�����npg��Gk�}%�a[�&s�3�))�Gr<���2�4H�=���+h3Q=H����q��k���g��O
+����1���:/Z''�<96H�:��t fd�~,v���Y�o�]cL�Oz�=@���%�̩��g\0v|�g/,����4�W�k� NQs�Z�b�_��! `����#}b+����`��gʚ_��Sw &� �UX6�n�Z���3V?��"���Z�O��t��<�����Px��}�g3��.��Ę�q uv�96�2ρ+�|7/Mf,P����T�\ӑ�WQ篃/ft��T�6�!�L�����|P}�2-gC�;lnUF$��k�r�ԭ�Ӟ�Y'��}����&�,�=� �׎'�r���ڧ��{k�:t��Ϣ�����L t�IKIf��v?KU�m��ʷ?��u�v��+l(
+fv^xT�Բ��H@X߰� 4�����ʬ�{���pJ�����i^���!���+P���i+;^K��?؈���/�(�0� OWkQq�|�S��KS��F(�lG�7Z!�1�כ10�~���7�8P/»t���[1lL�_2��&� �ny\�����k��p͚wN�ɅLʴ�D�Y���mW-���Uݑ��i��KO�L�` n���Ι�GP�Zph!B���K �D���ٳ!�z��ܼ�i���.���ΘE��\D�Ep��#�7b*�> ���&��{�� aE�}�G��?��J�[���P���<�UU��1� ��+��>�F����@ ����y" 8���Q�����Pb�Ns�t�ڿ'�kQ��[��dr.���%yo��4>k����k����+B�u|�~B�8yG4_��O�� λX��q2}���u.J�ԸD�j�f�!x� 3i��qCYK(j�p]�At3J_8��p�:�k��'(z �=��Hc9��]��Pc:/u�b�,�LfQ1`K��9�d%�yOY�hufE�Y�&��x_�1D�� ��!fJ���@�jSW�h�=�c`�5-�o�s�N0e�b#�_������]��r���O�57�|�h�+�Q�ނ��G�����ި<�#
+G�22�A�E�˃�mʭPU�s"��X���R?#����0�Ai��v��0=ZJ@���NJ��
+4��n1J���� �4��j �'C�~ZI������e�`R�����H���
+Ib��b�� i�L�nI���R�-�r��}�1�m*TM���b2J��K��m��vȐ��RO�}�e�I��U,,X�[�L�ށA�!�.�(ά(vw|�x�.�#خJ�Q�yn�yy4��Ѯd��Gk�����[]H:�&V*�� ?����߉T(�p!|���V7���_6SM�G����'t��MԆ�&�ʓ���z�j�"��G�G'8V~($|ed�I��6�D <6��Ԇ�yƳ��D;�!���ԥ�p�ե��ҙcn��>0� %+�}h瘌%��H�e���Z��+T�Ǿg�!��S��x��n(����|�O�ERA,BHn��%����t�e���� s��|R��u��3,��
+�Ic8�i:.t_͐I�I�r;�����7��cx��\2��H�ZC���T�?&�- �'D�_�5է��Z��Ǯ�yP��ZT�/bu�0P ����J.����\q����D�ŀ 5���-��g����`J��k��f��;�(ax��������n�6���C��$~�.5�h��罀�ނ���?�,�:��u<G-L�/UT��~?�s�8}�x�����$칱�أ#��S�1����`��zP��a�(�����H T�8N�dOeBĐ���0��gp�qW�0�5]0<��g��Ҧ�n�9�ui��{�(j$�[��/�� ]f�H�o$�խ*�4Z�h��%$:��DcyJ�(
+ ��nKg����S�z���H�12�B�={�2��qw����U�E�w��#Qᬹ�fYW��du�b~�EM�9S.����tU�S㢨6�W�{)c�Zl���ޅ�,�6 EN$��>9��À�T�+���r �Aڗ�<ri�u#����+̔��l��Y7��xԳ`�Հ����i�������("!���àe1ވ(BfL���N9@�+�D� b���<�"�n�Q�hp�KҤ(v�7���^���䩞F�A��(��-��1&�<��
+^TE�s ��L5��C��q�(��C��W�Q0_ܽ�����fU[֐�%<��w���-.]�I�W��jJ��:*f��&D:A�P��P���Hpէ�D��u6
+Y�t:MՋ��e���?\|I�R|w܁���[��}�u����82\"�-�k.��&S5M�`�=i)��f�x�C��\�&�����3���0��1}���AH�Ʈ��[�w�"|(��Two<�l.�I�"��8dY���)���cr`�t�R� C��d͚���
+�G���iU;x�c< v��3{�����#���SUw��#ۅu�&�k��p���ko2��h�� � =:Zeb�޲2�Ÿ)�ɆE(�N{j����A� �f~��v��bQo��!�c�j���W7N�RhX��Wo���Bcs�S^�W�t��� ��f z��T��S�-L^ӂ��t�e|��S�0�V�L[��g���ʯ��ju�Nj� �'o�Em-���,�}9��E!/�#����F�L�ş{��[�"����:���_�Z��f /�Jv-���5�lv�����;���O�&]JCL��Yl��:��A0�)�;��ؿAu�l�%�d��F�f����*�]�LcS 9>�x��8�DCz�@[xV�%vL�V���Nq3�֠����"�������"�Y��V-�?̊�l�C�KU��/�.�����C�f��T�@�C�K犥�KL��sR4`;c��/��ZS�\�#�|6�4�R�!�����:���~`�Fu�ϯ�c��K��v��d7����� i����/*%������'�VۀX`\�@17���W�VB�ۤȣj$6Od�]R�~��h��c�E�8� ~/��zK���B7�E%��.�[��G$�pS�p�����9��)<1��8��/�_q�h�Z��G+L�E������3*�h��.o!�m*N�� ���ruc���>��z�!�$npݴv�W���m5u/���.�k* U�l�\ˉ�ga�[\3�ݬ<_4�ο#X-������z���?H4k��'�n�ꮛ��LP� �5�������-���Aθ��Ō~�[ ��[:aO��c�M�� ��UAg��M�;����5u��l�R/�$�A��-�{~H�qf���`>dq�.�%�1�xގ@?�}���{�~m�,qC����r�����#N��`�]]xa�ctJ8΢�$,�B@�k��L. AZ XѓyN����6�ԋ&������������(ɕ�4\{X�r��q<�MՎ;b�� >&YuG�yU��.�Z�"�3#�20\*��x ���,��D�]����Gx^���{�r�Zxd�R� L|�甕��������疨Z���mh���0
+V\]�%����B�h8�����sM1 ���޴w�z�x�p�ы�I�+��5�{tW�F�����wE���n��d�z�h����\�C4�h���OYE�E��9��)�(��>�0P�3�r���݄��6;�bl��T�@�9ø��|�V��ŭ�k���Nmu4��v03�H� ��-��e �=��J?�ч�]��up��U�� %�瞵��r�X�vX��1(�a��*�A�{���̗Q?��yĂE�Hى���F�U'7�Xc}`�T�-�s<��8��~�V}�He��n��]r��)���PXhk'^1K�9I�����%�Xז��{u��[3<�G���F������ԹMG���=K��#���]���j�L�y[W�q��$�X��J��~��]�W��zDy�Tw�bI�A�d������ln���\)gJ�F�~"#"��n��D���n1� �8�Q�R�X S��K�A����1΀S\�}���n�=� ��a #��W+Cp'�;�s _����8ȧdž��AHeH����XB�G��I6T�f�7����/�\΃�K����A�x���%���-�r�����uk\6���h+���<���Y�:롌��H^ �•�s4z(-�0�9> _|�-�q�S��Y��/C�a��_P�O��#A���n�e�=�=�R��Y+_���9���Ax�ش�h��z�;���5%G/"�|�|��}ذO�.G|�$8s㉨ۮ�)�<=�b�tW*�������3u�ߓ�h�.���_� �‰2�ӷ�OTS�줢��I{_�� P
+$���ADž�x�D����9�qs��h�+�e=��T��AVT349�0m+����_�Ձ�/���=$��} ���P�� )�9�DH�B���S�K=� �%�N�y�bʭ,�b��3�i����Ԕp���h�Aw��lm�z}� UXJrj]�#���~y#�hN�0`��b+�7�] F�� y<��J �P]�K�~s�L�����e����յ����2�Z��)e>��wSq���?v�������W�ޱS�ƛ�Y����a_�J��D���>� �)�j���l�+���H�'�Qv��h���k� ��Q��I�aUd?�p�W����!�d���y���A �vð�;<�Gr�-%2%#���6b��d��: N�&H\S�ʅ�{h8#���+Z��)>>��%�
+�c���M�P������-� ���E�+5�d��?�¨��Ҭ���ZiS�0:F�1�9� ����{a�����ܰ},�f�ZA8�C.�V�tL�5W��ؒD��(s��
+��HI��g�y�V*q{I�ns��mF�d��d����JiBK7ۗh��p�*���ô�;�g��Vq����l�`����&���1����;=I��'�쾹.]�P�
+UG��($N��pƇ'_�-qd �����第���.��e7z˹�̲6n�fe;��6�S��ѾHi��y������-��xPm�W�p!��vg���O����]��0����2A��Ӓ Ǜ;��R�z`N3k�� !�a) ⸏�;,RP}�/�6T�����Śz'�M�?f������q���Vg����7�P( �LP�)Lʗ�g�!�T��Ňѫ@�����9D�;�s�����#��(�j�Y/��Af�.Y�O?>q�T""4�Y�0�oO�ݖ���E�l*
+�8���A�%�®����s<�ߌ)��m�PS0���fu�9��b@�#S~��>H�*�U{N���l��D
+�38�r��i�� iG�~��N�VψDw����`ئނ�pkʿ�YB.�����r�2���#���˗%],��.�t��BV M6c�`�\1�f������7���C�� C�P۫NՐ�I^;�1rq�z�s�|6��n�-i��Z� ��1����`�pL^��'[1�%��������^��)�p_o��b���'�`�N����`{�1L��n��g���Iia��m����=S���'1[r[ 8���Ҳ��n�m5��g0��b����O�3N��9��4&�~4yN�q����͘Ul������(��U�"c�s��Z�y���J6K�p-��C�<Fo4*K���oЫ������44$!��X�N㏡�|��� ���Y�� ����/>Ao�R�M��lx��t� 0y�Jwn�g����Ak���s���I�r� ��Ɣ
+Ĥ��\�L�X��'m~]51�d���W��M���V +h���q�
+C��[�d+b<���Ea%��}�_�������# �AӮ��]���`Uw5���DCl�j5K�Q�TY⏣��(��\=�h��깆e�F��(��O��(��Hf��(�kdJl�J,,3,�ެ,]w�j}|sZBU�;MMg�� �$]��Y��HF����[�&-?n ����6�Wi��~gt~W~���1� �������0� /��_[���y&��E�"bg[&���ڊM��؟�ǚ�,�R!b� ��q���"���º?li.١�k�Q��-/�L|�X���M�
+��!�d|�L̋Z�O�j�%h����BϞ�0E����dV�z�;�G���B\�-Ӵ������p�i�0 *�ʯ�6���)��'x�J���T��C��& H
+̬����?~x ?�޾�:‹���4�Wi�U�!�:�Ҹ*�}߼ ����&̔�+�x14aؤ%�g��ֺ���f �3I3�Un�YXܴ_0�D6�QW���#CNF�q^���K�TgA�ۏ�U��`��3�a�q��9ꋢ�pfL0�7�i�S5G����Lk9W��
+�v��(s������+F��VWi ����ݺ5}��q��X AS�Z�(�}c��E�D�Zuhٯ�6S�c�;�V$�t�y*�oGI�[su��W��U��p�V�^�(
+�����EqӮ�}widV5I�Hp��3ڣ2�Y�m���`����6$Nt�W��9ǧoa^��a��t�{�~��'Z�y@�N�;�^CYxRМ���Ӱ��"���ܭ:QB�� �}��n3�3b�Ё[`l�P Yfx �J���b*@��2S��;�3;b���7�#�q'G��bW�a��α0�����ùn<�d��H� ��`�i���Q�{�N�Kg�A}��xP��-�߷��I!��Ϟg�p�8K$1�ݯ���u�* ]����Z�sHHX��(e�����7�D�����||�ؾ ����4�#�K/n�6-*���&�߿�]7W��c��̈%w�^'5ݶ:�.J��x�;��D4��qʦ�$<�χ����ʸ�xg r�$�%�N ��_2��JA�m�¥/�W��b�5O�3 �����t�<���C�s��\-1ιgG� �b�Z�T�4�Tmz�̘sT�����V�~{]��:6Y�2�ɋ[�Pt�d��>8�=$`Fkv�� 9��� �Eq�x� ��/c��m�H��(���<��������d}���v�[���2��W *�VB���Q���7MO���c|.��]KTB6s��"�o���i^��~E���[�i��,�'�[��;��i�Nݾ�C�K����!�:I($� ��
+�:cx%��<M�½QQGxŪ��v"�Z3"1r%��)���[�r�1s�<�_��)ئKB� ��#��}��G��٘=sQ�ר��y5��)��ˈ8hX��<-F�A;�x���)|�l� �g�t"d'N�8x���{ev������SlE2ӇO)���R�f
+�-��g�[O�$�Z��\��jyH��!�]w:O�.N�� 6�P�%?2�C%?�����q��2O���0\�.���r��M:4ڬ��p_�:���j��d��0��]#Rxh��j�� �?�~q�hm�3W�j)!��8�ܘ���u��6B�j] �i4��`<1s��K���a�4����@�A��
+%H<m����'\��\�u�����EW��w��x^�L���(5��/�$�w�D';��VN��s���"�w�����MV�e�Ҽ
+`�K��s�F���G���3J+üY��5'gh�h�`��v�#nR �[�����W/V@Y�aM�f��nb�C5�?�]���(\�&�oJ�����B�?gϢD³`&�RTG��a$��]R��@2b��ԯ���GC`��|]8�ن�<Z�F�����Z���l:f���'����炚� 3K��߯��%A�,��"� ���_�w�ţ�`I1^|�Q���'�]����F��������Vƅ�'�[�9Jy8�� �z��)�0�hR#�ßr���D���4��^��rzr1~NQ_&ݢ+PQ�q�_�1e��bz7�1)�g��3&�VU�~ǑM9( �������̏ �CU2UJ)�\k(�#CJ�L�{<��_}{�A�i�oT�6\Y2�`�!nU~������fI@q��4x �!o:N�/҂�ȿl�/�{�<�\,�Sx02��>󲠇�^��"f. ���X�i��$�t�~�"��6�����w�
+���C%���,��x��O�h����H��(n�"�=5$�f�@*�'A+{��W�OMߌĺ5��9l�o9
+��&A���+�l��7�
+���Am^N3s����67��Ϭj����ނ��(�[1�q<c��i�fk�_ec�U���ۍ,�uyl�Z9��}L< (�2��EY�L�9�T�ɼb| J�GJ"[B�(���1�:���fO��9��Z<��<�������"�e4T�������Z�I�[�k.���A�kB�|��V�h{rI,�I�\D�,;K3�n+�b�� U�5ވ�m�;�t��i�I�_uwh=oJ/�/_g�� ��$�PX��py$:{���/Y�؊,�# �<��k��� ��p���In��r�!�\���vtџۅX���M���Y�;]����ŋ���� �gc}D�����`��׭X�8��T�a� a//���"��[�/�l�x�`���m~j��`�����<4�UP?f��4 oܺ΅�r��\�[g�����Cx�MMB�@�^[����5gL�S�_���e�P6����fc�JS[9X�vI�8�b��:VP�T���m Gc�?��� �H�l�%�y��:�l���F�����. ?�2��2I�ZK032�ا�b�O,Gz*����\$�%S�ۖ��qs�
+���_ APȄd%H���� ��F�B��Ո͙Xo�.���1��$��/�0���#��ѱ��dPw�-P s��Z
+s�ZL����EZ���Ud��[��c��j�� g�L+cԨ��tg��gIW� �ք���#m��z�W�O� f�48��2���՟��"�ض��Y�ʇ��Q*s�,�Pr�4�ju�/?��?���mC�#�8
+�IDŽ��ߕ>L3�&B�Q*��6u�נ��#�´i�u�U��Ȥ\�o('��� ��z���v�V�݇ ������a�oՄ�sȈ���e�섫j�:8�Y>42��2���@��V�Ѹ�d�����9/��1W�^ �ӛ]#�|��Rb��A3���J�1q��(����F�O������� ���fg})f�L'�m�tM=�)�.
+��}H`zB���d��a��2��u�j�\-�1�Mx�3�� �?��,me�@*�=������Ou�Y���mx�f,�����"p��_�����l
+THC������3�.QV5����ṱ�# �7g�"�ͤλ��ۇ]�8�������ؐ�d��ǀ�h�y�彧�5ϵ��m��Ï{� ���r�0wS��=��El���^v����M�:x�ޓ(Ƙh�y�ߓ:C����'
+��:C��C[��!��Ӟ ���&��L��%�3/��2��N�H+�6`�3�������t��pfc����jŲ�}'��W��v%+pl�5>`�L4�����W���6v�1��� �Id�%\���:�-{�{+#%z�&W�1Ɏ3ǁ3N��|��2���>�nBb���juI,��ԉ)�(�~���\��\\r��RTA�NOf�j��y&ǧq��y=2C�Z�l�=��=0�W���a<01J:���[�Q �6���}tn{=��+%#M 5[�^ 8~�Ӕ�~u�����-a!�[^� X,�%�*�'����=��N|q� S >��_��P�����>��FX񂏭JT$�P�?�z(��p�������藦�l"z8T0�� 8ѥ��c�W=��y��J��,��������ia���ɥ�o_����{�itxJ�L<����ODO�.�F���½�[j��2��A/��b�̑1g?og ��ܾf�ь�+W]��J��~�G%8������V�!C�fAvWE�3��-��uǭ����#Dmr7m.���iѹ6p
+�J$�����P�dS�.A5S�;�6�R��k���M��4;��:���R�9�����,P��[Y�*A[#o���3�$ٳ���( ��$̚(H��]��>�,r���"�
+��ƿ�OZ����$�+�yq �H�i������P1�E$�SOj�g�AQ'd A�Wh� KYqQ�*�v��f�e���$��N$W�����e0tB��\�M�UM��̪�d��������Z�f�.w�;cC#��pA�W�#�Wȸ���9��]��#�2e�~SʽdB$�|�g��
+FJ ���� ��Z��p���\������8{�jwn3�஦�HF���VR`z�v�8v�.=��� �����O�F� `Tv��]��3uw“���`/��t����>���u��-:���_��kA�^;��SHŹ�p�4`��:�����3��GS��?�8=cQ+^�?;] Vs1*�TN��e��O�_;��h̏rsZ1�,� � � 5���/Z�"�b�cL�Ou��7�-|�V��,� {�Ӡ�Sb M1��� �lA)ƃ� ��C�SF#��-�V;�r� �m
+�,�γ�~�U�$����=��@��@^-��0�Fs2B�` �NX�NsF"����ܘ���s �QVs��̤��Z˥�6��Q�BY␁A����۠F�Ʀ�>�ڙ�@L�/�
+K����������]a����T��ow�J�v�s��tú7�VB�����д���|}��e�Q�t�=Ȱ�?��<��$V'E¨�@���o�K�2Ω;Xұ�۶m۶��v�ض�c۶m�ɜs7��?�Z�zUU?�[ԥU�� >jn\!�|J��O���c���S���r<��o��V��uiMFDL��?9t1��ɟ� �Q:�\��bLZsۗ������}ܜ�c��ٶ�I!
+��� ����#!h�ݖ�H��<����J��]3�R�s{�˻bF�[-:*�ĸ+�S��统Oȶ�`�܍��m�]�4�u�O�|��&��QJ%���.�U����ORRA%Β�w;J ��F:ʀLC��FM�������H IjD_���Kgr��%�q3q��7����=ח�)cx�2��v��"� �DÏ�mL9b(V�z��!���^����ͯ}ٜ�
+'F�:��t����i ���?�9dx� "�;���'c����J��>kN�*v*����d�K�O��X ͫ���$�Y��� �6�U�$ �,3b�9cŧ� W'dŰ�_��jh t�Ս�ᅥ��X�Zpj͋Z��R�*sv���&�V z-)����%��i\.m-�yܾ���>�*tw-��hZ$��Ydz�<�M> \"��.D^�l=��TjK��I��ڐ9��$C�%�Y!\�Zn�:h�ވ1P������8S�֖)I����E�����ۦ˚u��X%�bnTʢ��xR%uP�jj�<�,bӻ��#�UYz�1���� d ~�� ���� u#˄�9���-��u[d�if�f�9)���U�פR �Q�I�ƍ=���%�o�e����ڎ��2���~c���ܷ��M��c3��=�lda�$z�h믲T�H��4�{�[5�Q��=5��,N��^؜(g��52R��v2l�-N<�~m&k�PI]�ɧ���v���v��~�qB��.��i�i\m�V�6�e�F$z�oY#dQ�I̓�֦ڪ�����#P�- ��� M�������&��
+(3�ņ�U�pM^Se��%��3�R�p>B�z|$.g�Y�D�cl�lm�>0�6���7U�G7 �c�0�Ƭ�����pH����>��Kn7�5��s� n��b�JN�ʻ��ѵ{�V�3�𾝠�~��z�?��� ѓ�6�F�b0RV����.� �YT�W0��S��I�}č}} =u�c3��C� ��������%!��S-�@b��S0�x��.�;���@AF �Z8#�x���3�yp͈8�����Φ��&���A��]�؄F�[ZRȲ$�^�H��{_9��!8�E�[��#r.v���c��1F�DW�}��b]�k��=�Z���2֜=�Gs9{�(yk���Q�af�� 5�Iz�f�÷VO#q1�]BlǶ�v��ˮ�%���7bhI#7��K��� ��L3o�~� ��i%���z��~l0��;�ER�����gm:��v_��n��5��줁i���F�� �+J���2��SNVn݄PH� =�����7�u� ��v��Lϥ��X�/�F7���t$C��� Q��y�aK���b��TKuT-�4o�Tc�'��Td)+�+�BW4~!�@�����\�EЯN~�`��c�Ԓwm2�o�8� �4�;�v� � .z�b���>��˥��=�p�+�c�S����3 [tl����
+HF�}��&>'N8�vyX䌛::�-x��i���� J� ߹���3���]ݲH9�/�p�!�+*�}��b�rgi�5x���q޲"� 
+Rb�w��^�x��o(������E��M�5y��3�l�Y�
+M ��gY� S��]a���& ����w qF�ߗ�yx�4���WQ2WWn��Z6ɮ��E5� JH�
+�ԑ�˜�u@^�)�T����;BP���K<X�5Ne&"J9B=b�S$g!����L� �2��BK�g�v�f3N{�3��x�7�蔓�u�p,"��Z1- �Ж \��ma�[o�,���y��V�\��}��}�Ɵw�Ea�~�M�b��\@��#�I�ùn�=�[�G�.�_oR�^]�ۃ��_e߿ Q���yRpV��P]�h�{ {��'Re1EM!�6$�)(G���;��� ו����tPg専�t��&��_Lg����K�K���e���ݔ��W�t���Wa,)jPs�8RQ�F��?��������kg뻨���*:�%(�%�L�%ҹR����|2 .y��ު(�i{���,լ��?�c�T[��
+��j�������=�/�ڝ��El�L�G��������`n�ʅ�g~������R��6���6�Sú���{ '1�4A"Q훯��=�(��J����Sd��hm��U9�ɐGz������D��ƗɅ�ƍ��q��#6XjN����AJ =^{�pE���u��=k-�Z�-�s$� �4����1c��j�������qy�BQ M�.��vR��O�nU[��Gw-�B�VJ�t)F���U�"nM��T%r�C���������/�,0B�qa[������M��Y �L��k�M�ɑ�"�|�w���"��as5�]^��;����/���^�lI����e��k; U.<�̀�#ʯ y�VU�� �6�v�wuˀ ���z��pdh-�f%+�NS�$���D��r�3r9b.���(�y�����ءfl� �gb���ª~�X5= �k�"�P�aǚ��v-%�Z����ac<�^0N�Ty.��#X~��W\�iH�=݉xqT)�y�V��Kl��f -sM�Fg֛��kR�e-j��=�P �-��a�:��.���>H^8�\��ަe;TA]�fM<����ycAt}h�W}�MԊ���!���[�dSz��3з�Ku<Y��EϢ�E��E� �QV�{�/.5��V8v{� ���2�]}�<��] +M��.�����ܒu�Y�^�VX�簚��8�=n/n��S��o
+q�#8bQͱ����n���蕒;�.���#�����8�E�JA~�Q���
+��i���a��)R�
+I��B!�d�!���x٪�"nF'��?~�c�o����� ��Fq4�L<��u���ſ+~
+W}y|�&��PSH��E�黠��5�)W�H�?�v�y�̬����,�����N�SO޾�T뼘�մG�c(�a`#��*�A��R</*0�’G�Z�q�p;�����S�%3��!Yx��Ku�#�����3�n3�5����9
+��z���߆��J��}s�Gf%�F�MRwO��\ Y��`7.n~�4�+O���p��9�������~2� �$�ȄsGR+��8�w�)�Jy��1����P(��;�QK�l��g�� �v>L�? ��aZsg):1�����r|��y�q%����ri��^xH��Z��ҷN���s�j)��3a׃�i,��_�t���"��B
+�o� �oM��'���g�eE��fG\�}O���XjE�Z[L,����b'<�o�O+���Uk�oo��_��;Z�v�F@�6�̡�����O�\�渌͕R��I�:��i��fZ���)�j_Ԣ��4�-���X~���puj���зpw�dC�oY ��ڲ��ñK��l�-������"y2�ͥ�z4�-�FI���6s����̘]� t�Q�j���N�tF�8-ۀ06]ŨYc��:(����Ʒ;�u��Z��~���,�p���X �I�,�7���qz��8}>�����68�aamvg?�f_p�V3�l�SH��(���&Y��2�w�>cTx#ܘs����vGwk�;���VU��,�.aJ�u��������G
+L�m�h�O1i�E�1N/�b7y+��̉%��P�r�@*]K=�Q��j�̫���6�&4�Kݴ�9���G��4�k����4�я����60Mg��s�6((#I�{��+��T9Q�b.���+T���������>c`�O{7�@��xɲ\�&�y8�$ii#Ν�U�!��*�?q�G�}�Z�W����Y$P �"���l�n�`��!�ز<Gr5B�,��c�h'������_�T�����RC�!r��5JvKf�v�l#G6��ޒ�SL�#�FJ9@��u0�V������ PL!/W[ �{ZU�ۮ}���U�UY�R��+��}�~�E�����G
+ ��b3��3�`�m&�j�=���Ee��q{ %��
+oV�P�??��¿Jr��!�{�L���Ϲ�I��]�,�烤y��O�Y���F�A�f�@@�7��Hl��UKA����R��`-��5�IbџDQqP�r%�6���7���\�P KE�?Ÿ����W*��N�J�MQ<D<hr�m&LP�����,�^�̍1"j"�{� ��VɈYf�������;�:���O��R�%r��\~)Amf�*����&{�]���Q���~�\a�ܑH��ڌ���Q1��@B��s�ӕ1� }�iȌ �)CG��X;׼9F�3�B��H�Y�l�=�j�)mJ6�1b�v�-�������+x3�%��ޖ&G`'���A6��,���٬� �E�Ak��N�XC�0H}�oY!�t��)��X�i�P1+O|�V�(��u0O?,��� Ld�9��n���Y9��;�VY3pԏ6K3ѐ�g���f=׋a�A�!�+�@�Q�: ����a��;z��z�Y�@�U6d�yD�乮��[Vo�K)Z~�iG��}JzU�� Y"�ռ��mj)t�ΡK�<��к��2�)����6�
+� ��8u8���(�N��\o��?薣��h�����,]i�&痷���ӯ=�\#���h��O���+}�u�㔜���4fh��]s!�w��G<0㢺��)o1���#BG�E�,M��(����x�If|<��� j�)h��:��V�/^/�uB���$�H���� ��y�(!����{�"�ܖ��(����|�xI��"gt��t'i��]\� �,�X���a��� _ �M���?����H�J%�8�J�?u�>KRg9"2 � JC]j������$�*9�� 3���^͊���eQ�໲�������:f��m��k�l�����y6*��g�Zw��b�@
+��� P9�HL�_��#�K/�P��̥P�2�jeb�M��!�.pJ��.#��r��ȡ�"����E��g�� 6dd�%�,+�� �{DO2�W���k��z�H� |�6A�vy �
+Q!l��?�.p�柤Z �D9��D~�𹛟� z��Dl��8�'7 �0�yxfT�v�����*M���x0P��w�bqn�b_�s�`�N�j�z����,�e _��CY~ fՖ��t#M��e�
+;XUd�?��9�����#�����- _�1�QiD�d���/�@�|�̓�Ƞ d�M��e?�J}�P�؁��z��5�'i��{@Ht�GTHq،��#����j��sD����ɽ; }�����^�8����y+rWo� X�0htZ�(� .� ��JL�!�� ��t�u�r��9��FU���L��N0� ݓLݘ��ߞo�B�����>��F�7]oz��}ڛ)Nu�{�<�`�O���8HL{b}�c�*<nO�?Ťc8�`��@e�Yl����'>� ��پ5'�gw*���<�IZ�p@{�m�b� ��]mS���KNZ���h����6uwm��gC4�8�y��zϞ_M���8�aɱG���i ��g��T����� ���#��*�Cڬ�d�f��W$+�Է�����$�"�e�:�Ou��Nd��S�����X��˧��u� ��z(Pɘ�H�yJ�X6s�??3��8�r���e]�2z������ �7u���zp4���S�L��>2��$^�2.�4��sT��bԳ��2��4ӥS�j2ӷ6�UAp��{�T�h��W�9���|� x��L ���qq���\�@��!t FB��XL�X�A 'wm�g�y�@�oS�������N�F��T��o8WK�Z�r�Ք��2R��qTY�a�J��~iю���<!K<�P�lp�|2;�����Q|�[�a�J�Tg������#N
+�_� �(�C~�v[�'S|5�_ԖnU/~z��%%
+:���w��5O�\�X7 Ue(S}7��"�� �(�I�w<����+�9� �cc���x1Ft7�8`N ���u��8�}�49D�(Z��Q@�T
+�-_��W����sw=�����˧��VX�i��C�_\�-\zӅZ�z�����S��%�� (ϲH��#��w���,d�ȫs/����,t-k <�����z�'z�Fd%[��wtf ��1�?�EplOW�Ee����&<R#5F���lΌ"$�:OYdƿ x��h���_��Pr��=��H�T[ϛ{�R����C��E�)+Uud�3�e�����ډ�'U� J�҈��9���r��υ��y���/���Fs.����S�/l��0�M��4� ,�'���B�$;D�6�X��T�~{�h%�hi_�r��K�-�ij)�wr0̮���N��V��P\� ՃB��h66�Y!W�g���J��BU�6����l�_�����3r�2�!Ѭ�V��d���ݚ��� �I޳�=� ��Z-��b��{���P�(?O���f��� ��=:��!�� ����g��sRP({����F���1�A��XˣE����GkUWtR��4�n)%Lv��q�HW�;�t�����S�T �*���� �:}U��ž�����و�(-U����x����GuF�+�R�c�t�[�S5�9ɽ@A햬-�i�6$���� ]b���v3,��}���f�TG؂�̥:s��lm��!������P˂���r &�������u#���_�^�_��𲡦�Yx�f]62�� ��:WO�y՗���e�d�*��c17���)�J��{XMp��d�Gx.Zk�);�Y)�
+$����,Y�� �>tz�<!��K��G�rʹθ��˻�Q2y��8�?� E$E�1>��FK�{��;d۾���Ik�|Ƽ_q��*���~�_��]����p~�sN9 �<ʺ�(1:��� XB��UH�9�9��o�R���B���Fl7_�m��k{�������[2���l�\{>����]-_�N�X}~�r�� �Z��m낥y���=38{ZpߴS��6.;���c��V�f�05�
+�*&��w$�����tޚ��t�[��>�|-l��w Pl��@�:ĭ?>�?!�.U�,������g�v�5&�fN�\/� K_ͬQ*�V_�F,�P�?�lY|����D���m;��c���*�+���P7�^ ���
+�y�AjF��I�gB�1I9�ut~����`�B��4�xkO��[�4��+co�6a��]�y�$��MQ�Bl�½��넙�cnS��#�RA7Үܽ��9]��Ș� ۸����q1�GRW �^�1�+۟c�D��XVYm)��)�R y�����@?�}�a{;���� 2Q�yi#�SA!��lN i��� �C��!�Q-,+d��|����#oc�W�t{���;�|CY|&�β"�L�%uRH�:�u�j���J{?gn��waN�,����� �4����j8�М�BhԆ��ç�n��H+Or��K�U*��¿q�G�Kʚ����� i���q<�,%pj��(x�5K����e3�Ʉ"��"l�����#�͸��������@�����?t� �����x [�'��P��1�+nc��)Z�?U:�0�ߙ�����"Ƅ��6G4��+���O$:��G�M�]���L �{h�Rl)�ˋ8�5*T�3M�c�F� �w�`��fS<�Sr�mW��;C��Q�Pl5<'�u���k+��v�O��FBT:�Z8�(� 4�I7w[$�:$5َ*0��y Ђ�,�IJ���s�_.-�!�+疸\V�ݨ,I��$����)ZzoZ�;x*y������Lם1�-6�c������(�i����K�T��GZ2.ݵ�t�ק�{u\��5CJ�.�[5r����cکuv '�P���Q��b�Y�{i�M���aa�&��Zʺ�ݔ-�������&����2��ɓA�Id�:�Y>K<��R�����Et?�]�T)���&��cNŕ�e����.���{,/�:;P\�6g9��;��P��Ȥ��!T�F�ƕ�Rj��D�ɧ���M@������_��t�����Y��ߊA+�c���Kz���F�� �m�譝�V2mG���g��������(z�o?uB��>@�k�p�Da,�{e�I�����t��9�<�<b_�-�1�3�꿦�p^����7J]M~'�� �����׉���)��0-��͙�Y ܞ�j�t"� �\��P�F"q<��QONپ3 �
+���+�Ay�A=�4F;��x����4���-r���S�%��M�[_�����Ae3v*t@��d���X��*��\fG�̂��I4������# 42���3�^�5D�ڕ�Kn��a����Y��p�=c�7���:T'�e�ǁ�OK N�-��A��&�W��g��灕v{C %U���ٙT����+�"��_��K�y$%�˞#�PmE�Pm٤��E�P#�_�1<�ɩ]�@k�F+��ړ�)k� nF�T��*��C��R�'�oj Q�5�ϒּ}�v �Ҩ�W^�&��߱M�g} � ����|_���J� 9jE�pE�C@džD��m�A�W���,<�e����l��F�JB��r��Z� ��g�w�1F�Kְ�"�Ʌi���1��������o~ʵ�<8��}"��s#����(�0�s���Bvf�. �t��P:A�f�ҳ��o/�m�gMyV�Q1�`S:m�����j��iq��gj
+�n} ����+z�cb���׃p�²-��9yA�~S�,�1� z�W �y
+�h�p�H �-�/��Y�`5�3aU���6�i��������na��"�J�J�Կȅæ���<�x�:���g�VÇ�U��S�O���w�rHSD��T�X
+:/��'�����bͳg�gP��pG:k���4J�"��z/���t�Z���8KC��~m� ��iI�.c�o�l�!��Q�I����#���Δ�"�`�uŽr �3��C����8���l()�<�+Ay�㙊�cp�Փ�\,v�ڳ_�l�d1H�ŤKɐ����X�6u5\:Y�L���9��gS8�0��VL@ �o��+���E[�7��ȷN��`V��i"��{-��w�r\�]�B'b9̇�Y=� $OuB����!�0:�q����n��-)~ �-��2�3��~f��:u-Z���ք<Ua��� ��d�p��T�4� Gr����a��JAW��׭�6���E����v��k�W�l���7jkvD������3��8� 6� �юQ����|�PJ p �Nw���O)��hZȤ�L�0T�9��q$e{/$����* !He�Cn���1��� �g�!F?\;,�����B�"$�؇Ƣ̧����<�bq�D$#.���;�2�Q���ܫ�u�Z��k�L�y ���Mj���-u�S��׀7���E��f�����{��� ��:�(<YH�� ���=����EL���~�[���-C
+4xyV��M.�����~7�B�8�g����'�5���)
+�T��~����)� ��M �=��a^e�� H���8Uǎ�h�[�� �IPXİ�o_��ݸ�Qw�[�XF9�`�ҙ�a�E�,�<Y^�QZ#��u��d�� ��$�0S�Gϵ@ig�9xi���=���W&����ֿ��S�&�/K1��u;��� |Ej����΋�H�H)#繿w���u8?$�*�{c� #f�W��E�,F��G�.SIu�3 !�!�Ц�}�3�å�>�?��7>𚡹��P�H�g�8��Yr�$b��m5@���A�:y�'b)"˭�s�RYn��d}MYo��'e�{������/�fC�I���
+�n�.�1d:�*w.�X�så�<�/Q�{�1�a N�y����a�K��x uVN�t�/h��<3� A}7,VE��v�};������a�r�A6��h�w$�,a���弑����Gf�{���ĩ������x��CnX���D���V��I�]ニ���te��4?W�]�b��s��~�Q9Y��H�(�A0���[�͖���&|ӈJt%Bw¬�j�R��8#.�2b
+��/�_`E�����eބ��F���x6�o�W7�X����Ej��&4��DI�X���o(��<��/_�ʼ�.%.g�,���k����H��Z��6��h/��T��u��.���E{|[���;x�Ů�5�Ǎ��6�m������p�)�\�氤 Q�t�/n�u��X-��pFgi2��2��}��!�z s+6� t�a~�xQw6�l���zG� �5Н=^J*�mI�j�S5��%��K�,����w��1�����3��ֶWt�*�-��?'�n���2���[�nIv�>��H[ά���ݺK�y�ȶ�j�hv�Jm%\�N�d�^-���;�{1 +��q~��+�>�ܫXr���&�Ƒ����Lf�*y�8�I?�ş}�{Fq��ZoI`3;��nK^����5�'�a��$�=���q�:��o�7@2�2��^p���"MD�k�F}B� ��Y�˴^{t=J��sK�`�c�Ѭ ��9�����k��-�)[Vt��*�U�������� �Wa��8�JvMu���Mr`���_Ψl*a4�̔��N�1�I��ٚ�kE�
+G� ��o�
+ꞁ� ��`�� �^��P�TK*�C�� 3��iN��u�u?��~�Cs�]�}����v�|�)#`��;��b�i��ad���'�:[`'���q�oBTͼ��QIZ��*ju+ �{F�@w�^(a�ZP�l�Sl��a�#qŤ�yMٜ*��C\��jj�ˣ��O��Ԣ4��� J�G�v�����y�ø�f��C$z��T�иZw�z8��֕�c��`�p�#��ie+�[��+lGĈ��J�w8?�KP�i�� {t��}��X6�/�ĵG�z qu�M��t�$�� �[��\��@X{4�Jo ��-�`X14�N��D��(Z���ۀ�p�B�Gl��Y���掚�1B ���Y=��F����CE8�s������+����w�`<4�W�Y=w�??�h� �ѧn_4
+�N��7{������4m_��4�6=��T�C��A�i+��
+��L
+�1V�4�Rg����P�~.�s��YS�l�{[�=��
+\�9 w�TY������$�>�8�jn�މ���P*�践��N�.�= �n�1�'�@`�nf�gd���~@)�W��� K
+�g�))��r���CXc(=O�,=� ��J����t�r� "ϭt��ޖ�Z�.��^:Wl�J�w�[� �-
+dž�o�ej����_#�'0zuMF@�[�qW wg Qi��ʶ��x�Bت�qX$hh���� �����7p�3
+�w+%�Jx���g �n�W���o�7?��[R�q�r(� ��3yQ���.r������q&��o�,���Zf����L�g�%�c�0��X��D_ ;�t�!�j͑�G�i�;��,���N2����� �6�4eGnx1�7��ś�Q7�K Q*�$X8dj#�[/�SD��R�ǀr�[���a3���
+9�mU�pV͏�d����.��ſGX9����U��_��ж���r�m�e`zK��s���K|n>�������q�8�g�BRJb�e}Gn��/̱�6�Y��C�s|��9F�C��7RT�\�B�`��F�!_k�A$� � Q]�j�'t$�������)�)���1���X����xײ 6�xDӋ�1^:KpW��Y�su>����I�����W�Ĭ3��T���ۿ>��o+��l|$�V7�ݮ�0j�u�,1�?w���f���E���p�Ca5�q@���[�ڸd�޺5}��~Y��`��+�n��.�VrO�L|֍�%Hnf��L��!
+�{��U$|6�^���jS���KŽ�3��<�D�>�����t�*AԐT��4!�:cPh��(�����"&{����fz�W��j�Ij���ζ����fdNI�u;�K�P����D�;�,�W�T�<���6�<2����h�@��c:�/RP�i�U��Z'��Q�4V��]��IDX�i�lňJ����#���g�{ ��� �v���#~�����ۂoK�������c�،
+�LR�*M�+��M�^I���K3��렟��7��'z��;�Y����I5͐��6V��+�z�j���y�Dp�$�|���zoH�[�Wԡ�w��y�%�ؗ,.ڹU���U(�:�M��&��j[�m<������ r!��g˨�~>��W�A�F�{ a�Ԗ�u`�2D�
+���@�V�)D�#,��mk��˪&����^��v#�n"���/�;I�|/�6u��d������#�N6�Ą��WC�}���Ɣ�Ƶ.�p��'��LL
+zVU�-`=�_��?R��O��jrC��r���(���_P^K����%�J���(����ʘ!�V��J%J��fTs�u�����#��1w/�Rg�-����[z����*>"�^k}������4������� b�j�E�-O]s���=='�ڀ��R�(u,�`�~��˄~)V��p,� ����fV�U�5炙UY�\����9ѩW�C �It���m�
+�0�rV�@�.{
+�*;��������9�A�OF�K�G��؉2��xTE^�$��:��{��;�l�lQS�l�%��1u�Be��Ҍ���W��MQ��v��H(��!��e{�4 �]��%HplO�d{˪������^�G�e��:<�o��flT��L�����S*�LT��(���V�W,�?�pFAj ��9�M�P�f��
+#:&��F�`����iA�{��y����Ġ�w��~!b"Ns���ݷd9J��X6<��7�-�^l/MC&��m����~�l�HWșg"�WԴ�,���c��{j����}�rgMe�e��q�Z�d:�n��ě9��#���J�
+��`��n�i1��m�DLb���� 9�d ���A���)E���d};�XK�G��#���L�Q����F$�M� :�/6N�6S�P)�)�v+�2 ��3~���
+�{��?�ŵ���"N�E� d��+;��rH������~��9~��Y�4Yv춼=�l�]"+�]g���s�h���ҕ�q;���ڇ��>O�+Z��=*�!i�{�> Q:"�P�*/`*d�yLQsB�{Z/�I!����9q�y��L-L�:�� �\Z�[�%w����O��O��$����K(��PKYF��^�&��w���C��`�0��~)�r�Y���fQ��V�Χo�h0(j�d�g��m�����g�ѿ�5�h$MQI��.Y�;�(�
+}��s�)�wR^:4��e�����"v�ɭ�b���.���kgp � �V�gE����u���,KS�O��o$cAG&xe�BX�����{�O���x�#����n�Q�mpy�)��E`i��9#�@;�,`�ej4Aͨ�r�8\^+%� CNc�w������g�y����aX�Gv����llQdsd"\p� ��� �v�(�-��4�\Z�Ŗ��/7�ٖ�\� +���ֈl���:��ܝ�������&����UO�'$�Cpl���添{_C%��$����^�S�[u����Ⱦ�w��Y�r8Ro�R��܂�V�E�h�?�"��f�[�vS�Yv�%������LC�7����P6�ƶ4E`�<f��
+
+�s�g��kO�=����a�`��#�;�-�1Q�ULU]�m�� �Bӧ��=���5~�JM$���ja�ʲ��R\9E�sTV���٠�+�so�V5nA�<�(�TK|��A"K *Ʒ�!�y o<?�'rP΀����l̿�挛h��793��6;� ���\���uv ���[�{G��������_O��g������þ�D"�4]l�l��o�CQ`��|��3�2B� ��C�粒a�-��ߗ&2e�Z��'B�yn.�H�2ա|6d��r���Z<5�Le�6��"e�� �Э Ֆ�,�]W�t�K��� �����.S��ZSO�iWfy<(-/:aL��UU����`���I��ᩇ�-C} ݹ?�XL�*�r�?���c�d��Wyd�U�1ת?�2�x��`��D�o,����P~Zi��}6a��r~�����ߓ+$�o��8D�f�<��??���:����f� ��!������R��^�J!#o-��F7n�m#�&�h�Lk,WW��Xa-���n�ټ,�\4<p��*it�z��h�F�#�R%��X5 �"U�BFnz��;Բ��i����(��ޖ� 0 1Z�)ђ� ���5���ӑ�usw�A[�ң~^.տ��N��F�J�0�B#�d�˵�b'|�H���2���9�<=���٤�a�)���}Ҝ�i[�3�ѣ)P2�=�q<��Yմ�U�3�XLv�Գw|������I�ݻ?>7�_�������3Uȃ��7V���9˄�'�I�D���S=�r��T����
+��I7&�����2�Z�m�LR���*[U�&�?iO��ߴ��A7Y2��tu�Zi��Y��$���(���G͵�)�?����Ը��S^����f/t���An�%O�(�� I��_�-B��_9g�ʧB�3C�y�?`������ag�m��LRX~o�1���������E���o�:�zKi)�:4��fg��� ���C��?Vͩs#��B7�$D�e�<��`�Y(��%6U�av��!Jw��!K�g5j� � �UI�d�qV��Z?[��)qư~΀% $��z��'5��G� >lN��w]�\ΥN4���tA~Wo���@���a:$jS����� ��?U���FZ��澎�m��A��U�2*��T)ܸ2Z��Y;֮�5s��U~^���;����-���9�c��Rs�ɹ�Ռ=�5R�Ke�r��� �Z����ߚ�~��W��~�)�p'����<[��V�l�Y<c���q��xz�r�:_38;,P[���4qkr˻�#S����z٪K)��1}#�[�/��sR�<�T�����1s�+�a)a"<��|Ʃx}�~�����|Y~C3W3�q�xEi5�wQ�>v(�C���bkt`�%�#����ٷ�����r[����K�N���=��o�8tZ�����_�:Fٯ�G
+]�넂�I��#��v�9�ŭ��[.�/dX�
+ϢnC%���\��\���-�=�s�ځ��V�+�����,+�Y���qT�ی�H嗖��&X�~j'�غq���ֆg���=���(4=��X�Zˇ3^
+B_x�]��=�ʟ�L{�@s'K��]�AѶ6@����x�� };�.��5B3��|�z3�/n)ψ��rѐl/2�3���'�Ԛ�jRח�|�q�8���z�3��b8�f�14\e�/b�`Y����L��(�-\�����d���T�u�T�LT���e��%�u�����Y�m�M�1u��p|��x��0*����U
+�n[ ��W� f6��P�9�����P��UO�V� \7#OdP-e՚�֮�Ԭ�#��P�>�bOLp�Ev��9��'�3�Yj�����p��$K�֕�E�4�`�g�9�� �{.-.��������$Vm���=�B��
+;R�H�5g�厚b�Ԫ�f�Hq� ������c �C@�$S�t�W�x�v"f�pW�H�%S��R�!01�K�Oqӵg���xJ��t��R1!�ј�_W�׍����l�҉g4�k�8?ﺑ����K�l��j��΂����*& �<���PK��wx=�ܝ��3ABr����e�.c��Y�;̔�e*������a,8<�T��O�F_�N�N��jT4ݶ��#�>�������l�Z����;\��Q�xj���\����`1�񺙺��15�yW���OFƺ?��9�d?���P���;1V�>��2 !����DRI:K!Q�ʉx p0�${�z�g�o @ ���'m��]t��~�;ȓ���sw����M�t���7�p����F����l�[]���&��|@��]љS�'�IıY
+��b}�%-Խ}�72 ��툌?�%�m�&1�0 �a����Õ"Q���F�N� aҹ����=fÓ �;��i�L4��L��|�"c/����:�<����+�Y��#㷲-�Ck��%&J<���9q��S�#S�UFm:�1�<X�����?\�S{&��fc۶m[۶mwl۶m�v:��|�g�������ZK�>�|�9�2�zG�Rr�5�8�Fqy ��)�Ƶ/�6H=8����.�����1����6up��},[΃\��Cw[�CIx�RXO�%�v-�$8�7�s �/�PJe��u'CW�=H"}l�;m�:�a��<���Xx�
+�-L63���"B�w��|�x������T<�U���^����F�������nyW��:ќ�!�[2�fz�c|� &��Q�����pS����+���Y�V��潜W��Do�RZRN����;S��F� ���b�7�,�w���v��;%9���c�汄]q����<F��ή%@�$�6g��u��ee5]}:���1�;ل����f�<��q|��8����(�m<��R�"v�=��,[p�#�Ӭ{��>�F��
+�7�`-ZӐ�,_�>�K��]s-�N�ٱ9Ok A�ō ���;�Wy���K|�Q<��C�� �e� v�q_�:�r]�|D���3C���)���}*�_��'SmFV��|��f���� fj�/�5�{Y����E{�_T����$\�SbsMr��G�f�,�\��� C�!��G��ӝصQ?Z1kax�c���v�/ܲ/���� ?je�X����Z��a�� �&��[���Y�͘�p���l�����M�";K87���HD�v�$mdkst����nq�.<��}���>D����:Q���������`��x���9y!�� U�ÓY�y�Y�ӿS;!�#Kk���p#F�ڮ��
+�o��Þ���y+��A���0�k M�;�2����N�޶�"id�����"�]��g1��DL���xB��y��)-�*O��*r�:�Sm9��Ȉ��(�o�u�Kؖ'Oz!C�ݟ�u&}�5�q�B�WNQ�p���H�(ÌL)5��U�'b)�=YK��'��C۔ h��{��u2�N8��En�X�eT����i�4t��R��*K���Ŧʦ$M��_�VL�Q/L�k^��E�` ������>= ~}��BU܈L���n;�$�?��� ��z�-1&<�Y
+6-LG��z�®�ܾ�ŗJB<ZVy�(��L��O�� pĺa!�0)h ��t�4��EǾC��X�o���_��m��.�r�,�0���aIA 2� S=�ڪ���i����o��l)��> ]�����`t�
+����"��� ������p�o>��8�Ǧmʎ+c/wӇ���$�k���3�#-ta*�7�mLg�aC{W}^��l��ZM̠ MȠ��ɬ�� ��J�4�$���~ʚ�,�SH��㍑�z���}�(C*���jܮ0��M�U=\�\{Y�x�g������Su@ �ϨZ�;�@��\�� �]�}��6����� p<�1��W����N�x����3�����M��& S��%L�f��'x�p�.�/�F��g����žH��mOP����C�G����vr����v��
+�*�_&�>�\����E�ӑ!��2!�+�{��c��z��h/�g0 �M�Ƅ��g)�}�w^��
+������V8Q�;���h��+xA=�nZ�����Qq�ij�nq���Ӎ�y��~�㜙�%�� >i���|ý]m�!���G��{S|���r�At��L�hα��U��(UX�e���%�K�4�K���1���A.�^R��R"�%�m?���_x�~���_����9�w�4p=װ�v�0����VU��ހ`�kU%U�4k��X#�>�.���*g+��z�t8�e��[*�F��۬6(m(�&��M to蒙�������8���@٧ތ��r.%�G�eX�PPH� �i��� g�����[� ���E'��kFgJj�R])��YV��Z��1˙���b�)��N4�H�(���y{&}x_J��,�|5��D���|��%�@�R#m�� � O��a2��=��qP�9+�����x�Ԛ��|%���o�D����e��Iv4�Fj� `Ej �� С�w�6IE�\qs�� � �dК
+�v
+O�mJy�e5��$���4+ޙ_�#��ى�1�H�A���k�l,T��c�8Vy�
+�u�B�_��i��:��Ef"����|M9G�>�3c��͖a�c'��?��8��\� k93�R�U�_��o� Kh�d�B�[��T��x��O�/��4K?��_"�b��Wtg���W�)�XR�fO�g�ڏ��t��~8t�8�a����_h�o=b�_V���t�n/MN"4��E�cP�Gb�ᥤe�+��v�_Ű�Z!�~�{Z �tA�{�7)����ڞ~ !�V-E<�x1�d�����H�|j3���Q��]h�z��]��ҷ^��JT�����a�@E�+�K���!(��9�Ⱦ��;�(����F]^T]j!�{�.E�>U�&E�rs�+X��~�{l2�����s��QS^�+��b����dښt�z4v��G������R��� 2� 9`���|�*�� K1B漞A�?z��)� ��?�r�GG\�ȼaɉ�����r���W��F䟥Y���dL^c4�劥1���E_��cӱ�GL�z�]�-�{Xφ���eMT
+��hǙ��%_�͡<�t�c�M���my�V��z=�W���g����R�|� q��i���"hF �'Ft��8{}���6� ��0T�ẟ�������A*�Ku�|#7�|��K0 �g��b��aA�����7�/��e��$���h�.�[J�?��I?���1���Tuӕ4U��o�F�o�K��˹z�����'�m)5�M\{���q$.�J�� ;�85%}�N�ú�q�ڻ���1�b-Pi���Lq3`�}=G��b��̣z�n��=��(V}�X�y�>^��5l���J�M � �����-ayG> 3�d�:�֕w�Q
+s|uѪ2վ�`v3�z�k�ޣ�T9��7.dzB�H7��O-%�Ͻ8������7C�f$�eU�Ô�i���Q���F
+����%�x⬿�ښ�V'L;�����t�*�;w ^���v���,�I8��#4�o��S�Q���mfY�
+��A�����U+�gn��}ґڀ�������1t+�z������)7�lݳ�^�͑Fm"�9-���pە4�i*��-cՄ����1ߢ��%�6�OQE����� �6����<eb�`��@��P'@�R^� ��A�.�P"He��;����M�/9l"���To�����6*����-�� ��bl��:@=����;b�b�2x�|���rV��=�h��[���t���Fv�
+�E �� ]3T�����D7�O8�:��G�N.-;�Dh�"��^�-9�0a.����I�H�'װ�$��6�gT�k l�6�Xv����ޘ��Ԇp�_@��
+�0�]����tBС�J+�_&�4 ^���߄�c!�ܢd�\"i�ë��O��c��xz<o��6�>��rգU��5Q�o�ډO!�JE�TK0�!F]����� ��E����a K�h�J-|bӒc�6���i�A
+M5&���
+�
+��/��'ABA�ь=p� �5��Pi���1 �0'�x /���w�Xq&/l*��L/��,�!�%vg/��
+ϑ<�=���$k �K��/��Qc��D� ��\�R��i�������ga3XſG��DTuWc�GR -�On�c�t~�����ɚ�/��p㡓��qմ��������zAೊ,x�zH��&!,��� )�~x{i!-ѝ6����N�iyZ�0C�>s�3�k�g�Y��V��.q�?d6,͔�d
+ �"���,�Јȹ������
+�o��I�_�iq��U|�땻W#t�bpG�{��l`][��i������2���u�-��g�Q� 0[�������[�n�oH�^�3�=� �n���X"$�����k�^ z�%��$pZ<�c3�����-'�zX� s }��5[���=�����>�0��+�&��A+Cw���RR���~��L(SMѐ,�� ՞�EG�z�;p��nn]x���K�p���O͚I)z�A�������)b�"�l��e-p �3d����]S����/8@�gu)��":O9}�#��aX�����H9��ŧ�oJJP���<�]��D��.3
+7g=]BS���'�6S) 3���Tgr}n��9�G�~�e�t����Sa/���Ծ_F��x�ģw�&ЖU�o�:�W�}6��/��ׯP
+�<�Ҽ�> ���oݖH�O�X�(+Jh2-�Ț�|,�Nr~���Y�,�@�!| }�<z@��?}iZW��`R���v>[KL�9:��&/�!�vI3/�A��m���i��W(�0�����ɭ7bc� �$M|E���$�����gU��x���R��5_�*�Tӏ��q1`�[�~lP��MxR\��$�g��+n�[�{�`���?у�fvJҎ���GK�/'~��nl@�yiA���y|�J- �:�Ԝ�f�b���G���+�����p"v)�Π��p��kv�a<���B� b*-Z�Xw��:�2�l�C�"�P�p��>=�b>RD&� U��/߇K�1� $,��,�FN��ޤe��sIK�z��T ��,'4f,3?��[��`��D5NQT��4�I�ҊT�?�"���x�9�ޥ͛dH�����+:���,�1~gmk�W W��!��F_U��[�U���ZBI��M%�x�}C�%؟`�GF�t2Fnaa]���U���?��F�����V�2^��:|NBV�/ط��N�M�Pi��d���4JV��$�8 q� h�V����
+�0E�R�� �a���q������6V��l�����Fz^j�CGH�9�0i�$k��������"����rDž�|���5Y*P���h�����E{%{�4}s�p{&���&`؍U ���r���'��� i\d�x���G�g�POԊ����K-K�1c��0�d�5l �C�6��ݍ�T�s?n-�o�-��a�� �%�}$?��:�ϗb^�q���#�cf~�> bVP]S�"�E���褎xWRz�g�`ǒ�'�a�S�������D,�G�bB5���'�̇r1 n?)->$9xH���aGCݤi��n�v�V��=�J���LP�B���Ƥ^��c�;/�F皱���)t1G�n���J�"��\:���6��r�wkH�k)*(q��:e
+ �"�xnj( ���������4�\�b�J��uL�� ��B}ԅ��^=bq�"+�HH�q��t�vn�0�?=J���)�NoA����c��[,ya����|'���;p ��7=I��'�)�`'?�@�LB׊>�ay�T͌3��m�Z�e$�Ζ�ͨMl�������3�����̵�"®���}�߻�4Dn��w��}���Z���:�1j����~��<������{�͌�c�' $ףB�`*�R���Z�aP ���0קT�[���[������,Y3���6�Žɓxo��u�T�X(q��. ��Oڑ�0����Um#ʷ K�Q��W�WƵ�ƭכ��rm�>�'�U�f���#T� Z������4v��I��k�-����
+^G�'�����D�������n���v��&O�G �� �fa A����Cu�h���._Ǘcmz�����A����8u�x�<���MV�:J�9��@��zM�L�γ������i�b�PW~;9w+d����o�C�T:��ur�}B+�w�m&X��3�x�ؕǭx�^�S��!���i��}�:�J]�VE ���>�bv����%�(NF�*P*ʄ�?XE�L�F��3���n�a�@d� 0 9q����
+�S+�A/����{]�$���t�r���N�� ȣ�Wc&�ip�R.)�9��'R�7�Kvb��F� �&�s ���Á�46Fc�����M�m�'�Li��w���3 `t�_@�oIsNqzO!|�{v*F��������{~�B��I=o�`�g���x�gU��� 肼�S��ϡԦ�_C��p���oa���<u�)/�+#��ta"���b��nݥ�8#=W"�S�\X���k���U:p�pE=��+�FG�&ȼ[p�b�����D�{D��e(��7ì*�� `f >x�[��(j�q��������R��%����5��e��d��IJ���_�$�� Y����FpO_�X��Ut/�?U6 ��3� �u�kӧ���4N���<#f&�_I�X��B��Tq:��Y���4g�Lk�x�X�iӏ��c��B;A��Y�ړ^{<|{�! � �� ��ٖ�M!fU��o�/�x�� ^�?��x�J�8;�L���bФ(�]EX���f"��l�j> ���g�xEB���y�t�"j7�^�j~�^‡��k)�: ڌ�?�n��)����4�[���K�|p��Q�D������6yc�"]� p�Z� T�A.v�����lG�{=��w�t����U_��9���:X��Ü���W�8����4=e�nG�kA̵��+�� NkP������ٶ$3�M�;�C�p�� C����f�6kGeC�~��W��7l4=��x�s�x�~Qے#�T��L�O�>OT/=�|)�b+K���F�L{~_�p��}�)����E*�c��&.Q<)��ȣ�<��{�7t��skA~B�]7�e&�U�W���E�����R�`��|�>�;��.p�Җ�)e����_g���^x��\���b?���N*9��WX�� jX?��(�R�3��:������%e��^*���D�L�ZL�\����k��V}Ӷ� &S��eޜ�u*3�5 �~H�e����4���?q �3��'!eN�PT!�1(�X���/����kc !�-�:2��w�7����~WKĪ�}"����B�6��̉#���]x����M�s�ڵD��)�c��@��{�����Z�o|4��*rI񚢣N(T�^ �\�6@u��,�V�x=�}�T��NkV�K So
+/淉�=�{�`�/B�KqSG�ף�$�h)�}��O�oCA���2s���t��6V������ݤe�����x��1f!Q�\7�a�k�#d��V��@��S��|��F���Pb��� ņb�+g`����F�׾��F����Z��-�d4����PP��޳f&A�Ź����۬�nKm�6p��D��f5��`pЉ���S3�<)k�V��$�7�M�/B����~��\nX6����ᔵu�!~��yQ�J?%�7 ��A�:���C������'Ƀa�D�H���xp�LEW�K���NF�{�O���|Rxn�94x�� �����wp��&[$=���߬�|���`ʹ �s���l�N��(�vG8k����vxט��Щ�T�-8�$k�����<ߓr�B�d��w0V����F?�Ƅ�W2��x������;H�
+���RZX�� #~u�&lhZq�����={{���{�F��ʾ<0��~L�ђ�A@E����h���d4��pܙ&�t֖Rl� ���1S%�@˧�s��df4��N%ty��`~�����A��#F��f���$�}�av�Hv$����rW�k6C)JY}%��O���S��qЩ�X#����g_�Pa�޻T-��� ��.t�����1���o�I(��Mο��`3�b}F��'�N�;H�g�%A��>2D� �iRu�㠎E� |̣O�+�1�m{��pQ��2E���7��<�!�ڕƲB�ƎѴ��yd�1$Xl&=M��6:UZ|��hU��IV1w�F���6M��t��Q]�&�^_>��gգ�{�
+���X\Vϴ���tb�T�ߝ�j
+�:��l� y���eIz�V�dIO
+X��c�q{���Շ r�A�QO�<�r�>�h�%zʖ�-NA�h{C�=D9 "�d��qJ���J��(S G|�?K&b���?���^G����#�=�6Y�ynl7��w~NڱQj�׭�N��I�e0W(ȯ���;Y�j���"����fӡR4 �r�E"�Fo�DP���#��+����(&߬�\��_Z"c�R�l�7�D�)�$���k������>2��"a�M2D����,�7/id?�Z�A�hxƓ�{\��v��]�U����B��tj�I�U`%����u�YW�}� <S
+�3"�kA�m)|����9�&���0��D�D���Crw>�+z�XO�^qQOW���1a�%3��|{B!�ק��v8�$��� 3���L��L���I1���#�GN\������)��I'ą�J��,XKm�\��!%�rA6H���_� e�R4CTL+�����U㙮n;Fjf�z���qZ�g�"��� (]!5`�DlD(v���9:�G�Υt<���nT��j�z�q��G/zQ��G��m�:��^�$;G�&���ynE��@)������r(F��Y���|N6�����:��ld�|�&:~�NUh�%חW�Oڔx%mg��w�\Z�7�h�O`u� "�Ǒ�]���p�]B�E� �
+K��1عV�q*}���=( O駏Xeh���&��<�oG9��E֞FY�����,�5VF�FMB���$��\�a$���zF=�$Y����nG8La%��� |�k.�� �8@W6Fh�_�+���уk�aR���#�TN0� ����t�y��'�5+������0Vč�� h�R�T�e��?}k��ϻ��۝K�}�/��X��)v�3P2�CmWn���ɥ�̏1����G��*���Y\�$o��.9����a�1�tx���.]����%�T`�S-�������S_о���1Q#C�������/a]��/K _�g-xZ�I�%k�u�8/� �eо����+��غ�>ݏ�CQ�73n{����i]ŽB�ב��MP�%�h m4־�䤶��V��xB�i]fu��׉ ⸞��GΌ]�;!�f���y ��2'���a�����m59@� ��7j�2�5�W"}��5Mߵ�W��G�0�S4�U�\�T��Q�n>6f�;�n}N�O��$Տf֨횕lv�<�yHv@>k-K���[Ǚ�2$\������ơ F���O��쎵�h���Ȇ�0@�X� ��o������6+'T��c��W��5��19h�0�����v�x�+�^�;��LJ�5UXJ�=�Y�����f�tY�)�1�'#�%��J_j�p S:&��Z�����kf:{q����\����8�e��bF�c�I�,�AC#E�&'a[Wv�h���r!��-�x}]�1M ����W9����[�� n�G�4J�5m���m���X��;���� � |+��3�gѪ竽�4�!!yU���L�p����a�r�hI%/���ϼ��[��)���ʎ�|!��M�������~ ��N�‘��A��Ny���8sv�kqd
+z@"Z�؟A4ֵ���o�*uNP4q)��������5 x�>��-=A�������n��i�M�flN��'$���z��dzw�o{��e�R�XV�����Ό�q��J�Ž���?
+;��� �d���d� �:ݬ��^���~��ε�,a�d=�=5��)��Пaڗ �I�xc�rPsz2�=�T�n��|���B������� �+ͨ(��q���3cJ���%Z{�j�p��آ%�[�R�P$#�P�)��  ȹnx +Ѳ�B�@G�L��/~��ؐ*ޓA����$��:a|e"�l��=�"��N ��P-�q�@��A�� �E�f ?�@^A; ��˦ �k����.�=�1��5�EWtê��hu�^77Zˎ�1-����h��q�t��8f|�T� ,>�+[6�����ew\<�丽`��.|_�F�>� "6�b��%N��ϕN�=�`�;�q�K^�ms����"{f�")�/@�Bfh��# k��`�Pش�`2ע �
+i3z�-1G�uC6�*/�~'��� hN�C+‘��M�k�o1de�d��MrG��8~��K��}0����m��s�l�z��r�9��$ ��r��ZC��T�M�����vs�yP�)-� Z0]� P��nh��[r��)$��xR�vVzE�x��Ybjb n���9u��{s���̓Im�c��;��tBwP�)�*�%��LQ�,��E_�-���څP_"�,*��hx>������?���"1�O����"���QT�O������nh��6� �5 rD��#�v��658T� Lc��G@���N�~g��a�6^'νo5���F�6����3�Ձ�O��dj�9 M@�^n<��ԉ��^�ᱶK���/�T�FS]�.�&59c�y  zW�,��+���-�Kv�A�;t�d̯�y3D�3��ƞv����ԸIݪ��`���%n��5���HJ&��|i�bE4c��{� ����caзN�GIGǺQ���Cw5!Ogn ����Z-��.qLIU*�<A\}^ q�\g �x>XS�c��q�8�U>�-s�g���D_K�)>�v����Ȫ�:�c�7�1Q" ���Z���= x�T�(c�!{"a��d8o�x*2-�|��Y�_��D��8�تy���JKz41�-��0 ��do�t`i=��ܿ�b�"mC�������b�4j����F��z���1HF�U���`�.]��p���A�<�41�������~Ъ,���w�Rl�:�@� x�;�Yr/ �2ª�ˎ�h�9
+S[���������q���J�=�L*� #k�4�1ox{�g#r��5�s�ӷ�փITl���m���R[��>}���w�5^R}���ܦ��@� q��.��A��y>���:�LTb��֐�������'�3����V ���)�f�*��=?�� ��� ��0�(#�����*�_��V�ԟn>�O����<9G7�V�q��[V�8�W0oD���*�b�����k��*IТ���x>&� ���C� O\� U��D�m’��%D�s�ո�d��Q$ ��"Nl�[�l���6jz$��K���_��=$�e�c��B�'�6f�N5�U`2�|�֤'ʂ8��/j՝�zО��
+ UQٱv�<C엫�6X��X���ԛ �� �Dk�o���'s��Q>�t�.@��57���������D@`؏�r@9F��{�!8� p7�H'��G���IK
+/�3�9X�����z���4��ȳ<��Ex>�����5��W�Ga�Y���kޡf�z5�d]q*S��Dl��,��_�)�8��#k�;~��p�J=���oI�ZZK}j��6����6��3S�6�>�t�e~\P����u&��ʓ�t�ΰ�`PG���Y��9v�\���*�����]fu�Ȭ�EO�x
+.�S�)���i�^��穻)��!z�m7�l�(�Ϊ��M��*'�I\*�����[0��.��ٱ���yڜֶ�i��F'#Q�c�J$�fN��G��Y5J�%}E���;]з��Ѕ[�+|\����h΀��I��KM�<g�#���2�ϐ֒+<S&g*!;]N%�N��PXL��ʬ�9���W�^f :C<:�>����| Į�|8�"WR�vk�����?j�s6�#=���9��P��+x.��Si�+j��_A-Bs�����U�4���|��!�c7G��JV�ߎ�:s�ǗN9��8���~�%��T�OȀ?-|�(O�[)TW�i f��]+'�,e��H��dߥ�b�g�*��8�y6�[IL�\�X� ��~������368������A�8^�O2���̋�3�2�I.پ�B�����?�3�jix��U���z�L��8%�Amet~�:K�«j�@�]_JSS\1�&��7��R9�9��r��H(��m��_����;�C]�)����E�^B{!%�΍���e�~����[=�Z�X.�vę�r?m' ��`byX�2Eץ0�6� �
+=�"/�ukY
+ʺ�xSSY�6"YvB�\��F�WF�:M������j������CYt���[�� �� E���.?H��ۤ��)�JF�D��U�ո�˛&:�s;W��� ��<G�V��Ѝ��%����|���&��n�� 4{����vq��%NJ(��+�Z|��f
+<��j��я'm@𞷍�n���|����Y��� B�RI�ܟ��ힵv�#�7�R�fݐ ]����P�����!`׬�������){N �Gx��������"�L�S_�m����g8Qn��� �|[��Ѝ3��o�_o�B������D�OZl��a�-[�����t�<�à���G&�!x,��8�k� �B�\��7�8�' mn���gh���<�4���X��l�������#��Z��H�F[V�TALtҏ��\2 �]���S�y��?��*����W��SC(���7.SF�� ��U�>����w��̆D�t[�_�S�N�4xY4Q9�+���5�@�2�s����U��UƸYU_��/*w9��&��i3����;N�_{0h�U�3�����<=�-P����=Ǽ]��h%k0ç���rSx$�bc����I�LG{ mC�4P .uW|�������f&�O ����!�h5��q�<�b^��ɇ}�Y|���6�k���W?�adDS����A���񡍿[y ���d�i�"�U��Ќe�9S�fH���F@7�����=������=�(Z��
+�X �z�ۧFLt�uȣ�`��NO�^���A��� [�������@1�wo�kz�� )&/�
+���$5���c<����!ԭR^Y�v!��2c_d@�.��r�4Q��/�@V�C�+�ч�!��o���u�wf3XMWp�Jf~��W��F����x��{�h��W6�S�޶ �*�$�V�nm@��\��='��4C��[ ���7�[���-��%C�k�b���ѳ�b ���W�G<n�&8C<=e�Z�2� e����\ҟj��b~�ל���#h��*�^'.-����dzɵ�51]S= �}Ĭ����Q0@�.H3�ʪ��NY�Y� *�?4�絧,ONL�
+��;�r`�����#�o:��[ V*�$8ٗ��L�O��8P�t�*Fkc zIܼ'D��u��ţB�B}.� �s��������*�Z4jNآU1�'OM���1>C̵*�����\�#t�f�6__�tf1Sao�pS�N�Cw � �$�|m�k�]�-�ڪ?��qt��#{nXg���� �����rj��~\�{4!��������w�|n�L�?;��###�EAOߛ���p�U��n�j���H��*��BHۤ1I1G�T���<v���:�ӋuE��� ��^2�uaip���7@f��� F��vC �/ٖ��]_qָ�8�o4~^��I�� p<F_��pj���q�N�Μ�RG�W!��R���E�� �D�.��{�yE�4���x��Ld�Bۿdf��;�03�w�����x��iŪ<D��c_��F��@�&�v[c)*��e���<a�1�ַϼ��&~���M�M#��Q��>2}�"�hNi�܅;Dy��!oa���'T-����ԣ;����(���'���ܳ��y� )���$"��Њ��g:*�� ��Lц��M�z я׮�����5u��O�x������aUW���ĈWr0�df�[�1L_| {�(`E��y����l۸�� +�v�����dˇm��b�������|YꄦE�`}{U�vmA�n��_O�>���x_�~��Ĭ����,؁�=b�� ���
+�)��pK'ƴ��A�&�LE�dAFd�&���<|��FWROLT
+MX#Fg�92��Pl^�k�x�D���+mpN�5�7�(3�8NZ6yϘ`!Ef��-���D=�-Qdír!T�yٝ��({���9�(fЫ{Ӈ�ꏸ *Ba�
+��B4�7c}�+�����m��F����i�:\���c����B��hs� C�T�hj�]�w����\�oؑ|O�g�?� ^�i��CP�@�#ځ��$�2��W �eC��_�v\~x��͖�w�V�q�\!�3����\� d�hKl�nj�y��H��.g!kV-�!7sq�j�}� h8F^��w����1��C������o�n��0^5�y�j��n���ږ�ʓ��G3z8D��PP���{���7R�촐c6ik�e'veV�E�d�� )-��祖s7Vg��% O�R�H.�(�V=���~�x�41�dF�N��%�=�H+�\�+�*�~�����q����ׅ�/'>7=1~6�f��'����Q5��g��� �?�o���}���o�C��(��9e��e;��ׇe�c�� pH��F��AA���%@��\q�<�E���ZO;FK.J�p h�w@H��@���/Fے���!�Ġ#��j�=&aܑC����d� �x�7S��r�"��28����8�{�����3�w=��In�20�P&� ��㨉Y��j�n:��d�RSW8���C��� N����Y�0��ELf�P�a]h;i�ν�=k� "&�����~���P�}ֆ+�� �܀#U�G�b4��D����+�}M $tK)����'���D0���nS��a���t��a��5f�d��8_�\�W う��ԩcLJ�j��N ހ�D��&d��A�#0������� Z!SL�- Ƹ坶{����j���3�����]�(���R�;�Y�Euq��a0��8;�]ܚ㌄<��#UUMWL� I���&�qE�
+C9f�!� �d���a�"�8�l D:���&�[�iHI��f:�z3����O$qD��v�;�"����� � ���7���-v M�Ak��@����u60�#Z��=�hF �|����]{�
+�� ����x�|��J���U蔊:X�I����၇E�
+�t"�}_c�}�������U:6 ��ʬ��8#Tf��K!J�h��j`���3���Ut�>������*j��iM5T��Џ���Kƶ�zZց7:eeUm��4̩x&/�*Y�DH���sl�a��\l���R�@zr.\9�=4�d�˗U�V� ����G ����[� �g%��lj}����v��N)Z���ο�&�I�7�y�U�O�� c��m�c]�uZ�2zɻ�6:r���!(1��sfQ��pϘx�2�駥���Yo�8�س ��lR �2�ҏ�A�^�d����o��ej��N���ꎶ���}=(���eK� xc���b����<'c;�s�O������-
+_�R �.;f�P0P�q��`�L��_ر��rgG��9��JS6o�Z���'eɎ�"S��i�b/B��� �cx�mDFɣ�� �(7����1���� �k|8N��)ee�#����hU) Mo�9m&��fɟe?�/##m�E0�;@<�
+-P`űk(��*���r�D���ZД�v����x8_�r�x���Wi�y�s��}�ߊ�A����yZG�P>% ��R�j%wE�r�.4�F�K�p� ��o�u��n�N�Yrk�3]����)s��C��N�X�-MSL|����ZQ������� �~�YLHz4��
+�"� w6�6�
+�y<s2!\l2Df�����`o��G���>[��P�]��=��FpR�*"����9����aZ�4����:h����6 6���`@�-F���i���5г��⣥g'n{�)���}'�1�0d�ϵ���L��1��M�����;�חsV�M�A>��/ޙ� �U�qM@A��i���:GP}����[��.�-vA���ԓQ�k�:gN'sy��T�@ v���ӶA�;b�n�e
+UpJ���u҄�_�|+�> Y�@k�Q2��ZX�h�;��a�a��
+���"o��_ôw6Oו,��J�)���ƢpJN �T~�zh�d]�jU��]wv����Bu�$K/ů,�&/�. �����<�滱l����Y�3 ���Z���4�IR�����M���_`@�
+�hh�E�0��w��|z�7��{Ȕ\jß��T�8(��3�԰�܈,B�-�+���l'Nh�>������Ԗ�����׳���f-�+G^�D�(�� ޹%�U����-�\lNʛ����eC�Є
+��8�s�)Q�SKZ�H
+��-�9m���wS�������G�XI/���x5]���R��<y4)<��īv\lD۫��1����vDQ%۶ݽ۶m۶m۶m۶m۶͹w2���C�TR����Ծ`/]0$�Gc.\[4���o0 cwڳ���Ԡ�<S�r\|=B6KA|�y��#�������㔕i��� �I�4�P(p&�H� B��@6T�' � |P��M��5:�^W���8�^K$�MNN�� ���&U͋k�CL�
+w6 4+���V�S�U��J�'�"��af�`w���nXB#�2C��άMb���W���pR���c-�ѝ��g��:,ջŪH8m�⽍W2��65�/�r�Bk�ٞ�����3M��%�H�q�Y�"�`�����>vsL�"��=|��u��zg���vV�V���sD�iI-��������4�� iV�'�E"�?�pX��7.�^i�W9������P@�}�*5���w����QU��Q٪�}\�o�B
+ g��QpY��m-]��7B�"5鵁�ExbxP:�Ln�'�ȃ��X /���`r��6���_�Z�3�,U�B��NU$� 䧉a�#��ڞ�~m��������9^A�t���!�G<(��J��)�j��O�t����<��}��Oݽ;��p�s�����-?�w~�"H���v�����|��}eO'�2�@ �� tp~cR8�y�9������o���1�L��xrv6�]]jz(Q,�y;�^
+��Ƅ��jߑ}�?����ʺ��Մm�- Din��W����N�J�ɷM�� �&�͋�ߤ�-[�&�x�e����������"����tN��Ϡe������e� �]Nu�˦,s��`�� ���5�W.G���Y���B�D8����6Q�#�Ο���eL+59K(��-r�HXIZ/nQ�?�T��<�/!)�oRd}�<m�S*�o1y�F ��}�W݂Z�WSTɕ�6s9���jь�m�/���� 6�/��>��RFj �#, ����p� L;щ_����N<3l�ajF��q���X2>�1!�mӽ���5,}�5;Ϯ]:��"�~aΒ��TC�����ʅj�n����
+��l�޳�C��l��=��W�V ����|�<�������\�[���ב-d�P��i����V���I���`�y�.;���J1Q!��l�-Hӱ�-Bv@�"���W];A􇩀�6;\y_ZУݗ�l��-�Dzym�r`�fuj�� i~��}]��Ԙ2d����,V;Χ?�)!Sp$�j�-�n V�:�b�ۂ�W������1}ܩ��t8
+��
+s2���}+��?�K"������9�����w����m ?��Ro34BVQ+ddɭ}<vJF�x�7��f��_�/�q�z�栬%(���Ui�c�P�j�?�O��h_� n1���>Q�M�e���t� ��gy�`zL�u�z���q��V�5���F�*�������o�a,��Yz��Z�+�kǪ�F�lٞ`�_�H��H~�#oq��"�Jdi!�/����r����}��������<�,ͩa A{T���R}��EC,~�����wH�G�w�)�+bВ�#p~eJ������ÂT<�`�~ς������jB�֊����p�<+в�S;�l��Hұ�:�Dq��P� ��ݐEK�]�����"����w9�h��}�����1�{F����#�����b6�Y(=�I�FnҢ&���S����Q0K�'��|x��"�hoc�%��/օ�⋩�i���(�����4�7~C_�T�@5.�E�h㓁���8��H)����a�8�B�5�D��Ʈć��5���v~Y� ���a76F 6���D���G����ōK��o�����V�ʴ���Wo����t�5~e��?�����z̩#��#/�D�]� �^}�<�<ǯ��,�$���[���*kDiMŽ8��…�6�IZ��+{�}9 o �)V`W�lM���J���Ӊ=*- ������+���D�����ʾ����yNJ��`�"N?�s�%��L�Lӽ�~Ar����J�E��`Q��gNJ(1ǯVD�3�>7���X�XK��-Y�a�9g����R�A�5>��ˌw0��ی�a��6)GFr �ķJȄ$��Z~h��=8g)����\dPr�c2���,��<(��q������k0ay�݇<���0��p&0�P1�ҤX�P%�#�[���_R2�y�u>+e���d`��`
+"������~��'�j��{b��n2��g�2i�� Pmi3m��G�������=��d.4>��">�a[���{8�1�B"�X�=��l4?���
+\4����/>�Z2�C[5�:"��6؂P�����z&WA����soH�c���EU�� 9]<��wE��֜?͗ ��<�� ���(s�Z�b������y�^tᒟj��d/�zb�����0E����e�c�,8��Lt�WGn�P��Rg�t��*�N�@ ���Z���ľtQK��[6����J����,�c&s�~H?4���yD/,��K��
+G����'�NB#�%�WJ/��]��� Ò=K��#HAK �Y�� �;i��<;�M󜅶D.,�t�ǥt�Nl�GR[rµ��p�E�TaP�)��D �`�ʱ����� "�����֞��L���o_#!L"����1�&H۞�N����@#��>�k<��� �C$}��DH�> �{��|�_����,0�Ǖ�����Y�2rh� s�(ex�j=܊�f��4�E�hV�����{h+wP�t�WBWe��uST+*H3ۃS���G� e���!����aG�6%����i%ӫN��� �}j|�.9�j$�F7]h������DT9�Hb]� ��f�O㎏��@T���)�Dq1�j�������dJ ����{�z��kK�z �G1\?g5�+]|N�4w�M�ۊ\�N?FD�z�
+65*u$Jr�FB��r�%���R? [M7��"���6{jm�XHO�\(���og�h����ZBk�̸�3aX������I_����̃Y�G����v��/C�J��d< a�ϳf���w ��i �Q��ОS�3.��r�u�^�I�Kc���[<�P����3$��:R��S����NN��|�Ijpl�d�]${�ξ��H>��s�,vaA
+�y��#���bk�!'�T�G?9�liQ!I�,��1v�H��nS�c4��y�b���p]{Y�����f� y��T�����UƗ��q\h]�yxJ��� $
+[��.���zY�t�^� .,5�%2��j(�O��欮d;�m�n����=(y
++h��#&v���r�H��3����7��d�o���;G6�~��<:�����wg�����5k`��6��i�g�3�8vcf O������ ЛSa�$lL�m��)%U9�L9y�'�F� mw� (Rf�-�e��ĸ�d��Z��'%����������{O�VK��B�]!��'����*�=�!����%Β�*&h��RT�Z�̨���BΗ�S�ގ2Vg����� ����Ƥb�$#��(?�Kf�veL6#t2�&�ɭ��0x��Y�t��\�L֪4箱�}������nuH1�y|�ju�d��ml�[��%uo�H���!L���j�xM&�Pv��,_i���oG��Ud% d͵�Z)e��3���U�pZ$e�5����}腽���Ȧ7=z�Cل �
+J�L�K~�<��k��؇�(�Rz`<u*D�;E�qɝ��;��}� zI��p`•��U1����驗�f���
+(���x_�����Q�T y��� F���H͈���6� �"��tr< B��P*�l�/�V1�Յ�"t-h��N��t���:�̆9�ɽ=�!˸,�Q��Fv�� �TPn�a�Wܴئ�q*m= >{H�B�&��q� ��B!�*�|�<�x�� �,�V�L�z�r���3�����F �
+�� ؗƙͧ�y�-�F��?����mG1�/�8W)}m���DE��~O�Q�Q�M&^��x2��3)\G)�z {Q��k��S���wb9U̎���$����4���k��ě ��K
++�~�(6MF�V��%?���[�ʼ�-��Iy|Cl&�]�#DX~t�~�lw��?*VtEƧ"���c�v�
+�:�5A�p5(��Pi�U<�1���%������ �f�t���x ��\�-�`.�$�b{<���?�}PT*�� ��|��E�ߞ�r^ e毢�c���#�����p���"1�gU3M*��Q���Л �>��n8���؝̭n��:|��1u�W��HvŮ��M��m�;�l����@�;ާ���� ��P�>ۅ�-2 :���q�"�B�
+pېR�V�C�JSp<@M�A�oU0[mo��[�v���C� ��~φ��Ʃ��Qn��:(�hg�-���ݯ�mz����GžU�=�ɰ�i9~Iv��I�A@+��=7W{ ���;o(h7�?4K"*�+�������)�Lce�%�K\T?/�G�"��ɓ�U�m���rF-D���6��<'G�L^�
+��Nঋ����5TA5�0�\y��N;P6[��C9#����I�>�v@���e���y4 � g)���w6 ����W{pS�"�H�٠9����/&�eE�/V� ��N뺂_�\�lx�` y"��Q&��[� ��;/ 4;�� �w�� M��W���C�Y�_�ArEO�жnkC.�Y��E`h(@�����3��IZ�J\����D�
+�v~� ��vdS�in��{V�������k�"g�K=6劣�E�#���
+cL�Y>��Uk@8ꣅ!��#}NN�!����Z*n�A�&$���\�_ʰ�;'��T0�X�EYڢ�Kg���2l1h?��x\fڕ!-Z���u^��R�wb���_��D��|�;�J��j��ur�K6_�M��=�;k���y̦��U�P�2i�_Y;�g.:�+v,�s�>n���[K,�Z��ł�c�㥆{?K x�;7�0��}\�=$�e�m��V�F�'�#�7�`�mK��͹3���X��r�TR6k���l���^B�C�T.��K���A��2���\����>���:3S���zo^1�� _73W�~����s�=���TLQ��l�
+6�ϯ��� ;�/���[!�B��$�b%ջG��'QQ/يR���Z�.�)�HI�F��$9&�_��� ~��u v�#�ȥ�$� k2�ڎ���3���ֶ�j |���!c�vs+�;}�|b䣲4 �&m�v�V��ǧ�%���^wG:�D�*��_SM(N���F8�˭�C���!p.���I�F�T���2� iSW�K*�菢U�V��.�;�͒���ic�P �+�v|�ݾ��ۚ��z���o��բ�k&x����>�}ڕ 1D��g�ל��b���'�P#;*�WF6�t�/�[[��%̼��,;��U� ���(��Y���(�픆��� �(�fʳF^��?�V���rW:�����:6������ix�+�-}A)��x�$"�ux�z�_S����H�5e�6���;�17�xqz�F�d+#��(jU�vs�RJ�P�u8@�PH�@�ܫ�A��>��#�9��Glߏ�٢������Մ�_X�i���m���c҃^������R��KF&V���X�e�&�b��p�Ԯۘ�,�3�8���#!v��S�A+R�_�M��Ͳ)����8'R1w�Az��N�W�;����`t��к�}_��X�\Q$o�'�|�Q�{�����a����`��!�R`�7��"7�N~p&�Exv�2�N�S�d2�}v>����u������b;D�
+0����WJ�n)���U�O�5�B>�[n�� �u���q�������`q�# g
+K��� � �'Ǡ|���{D�lsvR+�J:�m��E���:���(e���@ 7���,,?��)`�F
+ЮkfO�۠>��8���]D��܀?�@uP�S21�qa��p�1�ǩ��2Y�` ��l3
+��T� �7�.�2y&:<���j']���� Q��uV�ۺ �w�2����y%�3��G l�ϻ���u��b�:&P�?����/�� ���ѪT��h��~x[L�,c�KbȊ���� ~/ �����b�@��MQmF9r�6��q�c��}��~��ڍL�p� ����Ծ� �.��=�"�CH��72:(�{%g:� �)<�7�6͸a��{\��<'z�D��#)�:������BI����}kU�$k�F��PE��� 7��/P▁�A_��JHt���5��o����
+8g>���(�.����;��FƄ q�T�-�@E� q�^� j�^�'K�pJ��e_�6$t���
+G�
+�t�s ��T�D8k޺�`Ȝ�L _���P� �����C ����!���A��l�0���G��k_F�:!��u�PI�Sdi��f52�����{�v�+��E���z�h_҂� ��o ����)�/���rqW�T]��̾� � *e���b/����f�"n���j׀������;�Q �,ɒ]�������ϼ���S0��0��4<!�d��J�U8|�A3�w��Г�G��?7��Ȱ�h7oĩ�C[c���Ue����k�&֠� ����ބ�DR�p� ���h�(�:O� �٩(�V���/��wv~��Q�j~�@L��k�(E�X���z�u�g�b{we��_4���� �5��ѩ��ZN���C�uX�j�1IW`���d,叏��{�Rk����!��V�!C�K�n +�<kT�:�x�����(��mh�lqT�q���8-E�B2��W�]T�����z�� �nCqcDF�&7���D����%��?��F���,�oM6�#V����~k���2
+�Q���^�%e�,�\�;%��F�! *Q�����yy(ѾL�Y��(�u-e�5 UƷ�_C8�t�"�֑Y��R�ɷe�loX� q��r?q]������5��46���9�r�]Q��D�� 8�FZ�>_��Ѓ�����%z����C��3�LmcO�U�IG���݈?�u��P��|��Lgbu&�O9�Q �-E~15�����$b�Jm�\����A�Pi��>V:݇��ez�s�.��'yWs�2�[�:�%�B��?X;>�5&����TÒ��D��s����t}�� 5j��Z�� �,W1F
+�+���r���/vX ��hg ��j��|��ɇF!�q`8{^�`!��}o��d�/a��$s�5�����dK�D�A�`�u[{M�;)�2�|2�=�H��85�w5OI�2䏧S^����C&���1�cI�X���E��Hh���P���rޑl끠�.l@�<h��=� ;b
+��K���[�T�������g���B�6-P7���&M��t�ٵL@��m�j�̙@fwķ!R�'��z��d��:Թ��� ��&���5�Nd5�ȟαˆ]w8Hb�`Є�?yC��y����%u����\�b�����e�sBk߉��a�^ �6G�]�p?0+�� �3�����N�H�f��[��G>j��R$k98q�4�Zdԟ3�����zh��Ty^�"M������aBDM���n�H����La���Z_�X�'R�D�rH�#�wK�C�ǐ��ܱq)�Ȅ �8�~���'�U��k7�y|���������Ҿ@\#ë�`m��z�3Q�y�g/�M���J�S Ϣ 1�&�e|�Y���9%:d@��_��7��im?Z�Bᶣ`ؒj�k���1d(M��ѻ�v8,�p�Cm��#��D��^]҅#����&f��Dd�p�~膃韱G�[{O��[/��S;�|%Ni
+�N���|�e� 3o@�Ld D��v�b�$)PߙKfs�ɷڲ�,4k���kt�j�� {�#��S�Q�p$B�\�7�\�H��y��G�׈!�d�V��U��.�FPR4%^1Q�y���ze����t(�A�_�����cE(nI����?�t�ݴ�Cv�m�{�"�a����G����J��یGi��@�XZSpx~������s�l��"����I瞮aGy��"��lً��7�P�Yt�^҅:�<��6� ���IW>� XL%&x]� 員$���("� ~t9�A������ ��B �u k�D���_��k�;�`%+��D� '� ��x`V���`�Ŋh���ξ���l���=� �>
+kV�7��O���G� �����5��v��[d�k�9��m� ����_�@� l���>�u���C��i_G3X���k�(�r�2�%)3*��_���y��k��O��&� H����g",,����!y���� j@6s$�og%W9'�Ib9�Z��4���]�J�4�&f�{��+C��"�zA�d���U��@���! l��x�������==Y���Bj�%}�6{Q�a�3���x+W��}����[� j�u��+�p�сB{�(6�ߡ����B�rZ��f��%Ƞ�ʩ��1Z�� �����1�J�?�W��Q�_���W�Y�A$��t��ZׄF�G�bl}~.���I���i�Me�js����R���\�Ja4Qg�ĝ�G��1��[�ksӄ�j���M�y�+f4C�Hd)����Hd&,��.���jm���(5�y��W���!�z���/�t��Kp�zB�~O�3�9Tj��ƽ8�XWJ����N��_'��6�A� I5�dr�V
+��9�Tx~�ik�S�vo�4c8�?K;�A�a_@D�>�D��̺�x��1|�g"g��&X$t�n-߷��y��W@Fd��A-�f��@g�q$ 'Z������l����;�<������7z��t�E/#N�m��բB*uc
+v�m�XV��&;4�������Ԧ�ң��#,%��/�uym7�E d-XmU��.�S</J��dq��#��v�j�hi��ddFD��ȟW~��^�4����Lj��2% OgS;oȪ�"�S�'��ϙsj �<��Ω��l���8Fi� ���� �ߥ��2��N�K�j�؇��۴�(��!�o�<G���E�$������!��}8Gl���ۇ�����Z��$C8���_��]�^t�jaE���UYJ�_!�ȳ٦W-���
+���.kkN$���h8O�M�@J2�Կ�{���������w��|�gYE����ʴ�
++� j�"���m ����Ώ>�d�� v�� ?�ݿ$����Ft@F�%gL�:�p_�b@�0��Y�m‰h����0�yi,�G a����ڍ`-�z"�2= <#�lXA�8Ԁ�]e9�) <Dhm��'8�[����)���!�������?NCƅ~�̋�� �
+�p�r�O�@΄��u�<�d�
+^뒝.�:n�Y� ��5��hq���.P�O<C�����$l�>���#�(S:�;e >ޤ�� �0���ZѲ'�1{�ং4& yu���XG�s���`��6��\ �+p�c�D t�<�l��Ɣ�N���Q͠�C�*���S@��>�?�z�OA{��i.�2�T��pv��#9�1ΣUK���{X�<��5<�m3��o�?>z�����y8n_�o�KbA��ݩ}�Ÿ5"��sTM_"z�PLM���nT=�\�S�o� ��{"���_�����'g�.�wd�D*�1PΣ���Ҳ���i�Ny��8@X�Z�E��X�� ��M��1���%[m�d+G�4L���sc�;��*G������z���1���˒���`��{Ҥ�mP��Z����ѷ\����A̿FWm�y��b�a���fpS�˽�=״��b~f�葖WB�� 1ʁʆt��G���E���LL��{���9o� �+fL�P��*a��H��|.!��r+L:0�]f��<�gY)ٳ(8|2��g��BUsplI7��w5�D�ϓ�ԑב�*#V�3a��% �ϖ�NE��*��;���ֲ�����|:�a����
+ �s��v�W�*�;&[�G�����d���s���d�_�%+���~�o�%�q �� 6 U2':[�K}e��DA��R'vfǭuJ�ޝG�$�_���<�������v�6��#ˈ��~o�X.c�ֵ,х��@�������)� ��y�>�F�
+�Fz�{��=;�+/����8�e�@���a��`<�\5�u+�3t� �UYs_�\Ӌ�q{�*����Ӗ�[���MOh%�H�����e({D��,T9.�BV]��&}�n�d�׋I����^��r�8P|<��R,����>�q�Hф���� �ϔG��M��|�~8dR~�0�kg9$��x����C��P��L�1���l���(�~���YU_�s��H�:+���6�[�\�eԷ���z�u�In�� mSќ����7UV��&¤�C7vA����5�0�;����Z��Q���j �I���;��i���959PC�~��I�i�_��T�&x\Ͼ�����F�:�Ym�P%�N1�Z�N��%�U�A�n:��_a��*jqi�H�<�K��w�`t� 5��as���3zrHr��H�X/�7�z�+64���Tݑ\Jma8�t�9oQ h ������M,y '��{ϓj�]�[}`Ɲw�
+��I�ԫ�o�\3Y�a��f�d�]@uc�n��<�f:�� �Y��M Vo�z[���q�'D�v�����
+u&
+7$_��"�o����f�&{�xD����oQ�ۀJ7h�ma!,���4q� M���Q�J0X[a�NP��+_`�{��^h8��� 4�ˢ@ƴ0q҄!d7QrÈ`ds��,Y,K�^';XP�nh�z5E�5�*R�M#���"��=�~Q%�ty�� �] \._�9��v�t*����`pt0�J���?��=&cb�1��ە��e����Ц��.:�V�L���䀊�Hv��G �o�;i�tJGׂ[6Z:���P��E�� ���&�m�M=3�����D�f[|'�_���+���`��Ӂ�CI��(���;'kj��=� xm�~ �#�x'�ԖT[
+� �@���l&��5n<�/2�OK.q�H z4������-$N~ ��A�̓��'; �^�Kso��֟ ��z��q���*���[7�Ħ�3h��D� �㈆�)D�:OWf�Ht�����f�oeu�������G�~��&�h �P������s5t8a��,�����!���B��T����΍[�%I��W��� �6��������&�|7�Z�|W$`� (���;p��2,��
+�t�3W�n�L^���-F/�>��盕q�0���T�y{���z ��n��br���g":?�tS�J���Z�Ү~>���}B!<(�Ul0���ʀ�=�4.T-u�l��75B�+�:C[G\��L'P�K �yy���R-<�ͫ(Ct�K1P���������:�S� ��x��ѾXo��9��b^>% |����9�2SՉ�t�2Rc����T2��K��9�*����y�� ���<��"�L8��+���9����B��%�b,���LQtI�_��M"�g!?�д�Cid�;���?_����s<ȱ�����y�k9� ����� WI0�=nR���Y�1Ձ�Q+�WH��@�$�0-0&��Gލj����(�p��A��3�j��Fw�"��u���y���4���^��:�:�S�4���� 0 �`�w�6��s������%i���,�nc%�[
+�ӯVX�gJ �ƻi�����e���,#�&�ےrp�Z���䋷Ҳj>-�8����,4��šۄN�ƴ��o(�p��{l`��� H:���ś�NZFR����^Ũ<vr�&-UC�5�^o��o7���B:t:d�줙Wv.��ƿ_cdoӸ_���p:�ǿv|)l�%h
+�#�������Q�r~+v]�a> O=[�$�5�)�)�ҹ�O�b9�{37�9w��HV��H&�9�7]�r=�%-煇>6+��=��cO+;�\��g�nվ%���Ѳ� k]|���5��:�>I)t�~:��<S�d��Qx�j���F�e����Z�T���rC+mf���H����7�`C���},��f��"���,�6����m˱D�ΊER�&S����1,'�����b�D0��vJ���U� m�;k�
+x%|�/`�D�C
+G}���<KsPl>t븝zd5�:!����w�)�JO��UQ(@j�~�SN���h5�" �P�1�䪄�o�,������>������/[}d�W�~����L���������(^:7b)*�%�Qq�[L?F�U����AK �[\���`h��%����Q�� ��%��'�>^�&MG�?��e��Z"�ܧ����40�[R�G=I�ڀ���I
+i�t벳�*�+,��f�s��f�|~�B�kj�����T�J��G�C�����P��u��O������ ��fѱ���UR�[>b�A��h����p9�(go�]��z�D��/��7�xi̝�^�z
+d���@d���`��� #7�C�Sb��`Z�|EJ�qRd�^ne���,E�N@G�V0�"�����`&�h��!+�!}�Ms�����V��:��s򗳌w�  �8n��⹯�8m��AeimG����Ţ�FK2���ϭ�Ҟ/o�\��L�戯�e�+˥@P��"nn�W\�o#�B< y�'V"T��ӣ�7��Hscs�^$�ݹ�;C�T_��
+�U�2�M�*��K��܊��杈��]�ou+�!�bY$�ux_~ѻDi~vr���0iP���-ꕒW>ݶJfM{r�+oվ�+z����c- �4bЩ���2���X�p�"J]��� �M���.1#e�D{E��K:�H�Yz�q�E�&���ܨ�o�w����ӂ� �ʔ�v��X�q�}k0S0dA-��w Ğ�&2����[S� .j�p=�&�V��b�|�-<�T^³�X���Yun\s'!%�8?x��"Ǖ�k���č��� b�WC١�d�txX���{�����t���J���J��� �-9��;[�Y~C�P$l��#u��L^(�廐(:���\>W��体0. 1-�R�5aZ%x�sq��7��N�+�{�,ڕM�%l��T�sGe%6�L���~�u�”.� �\��D�" *X����No��ۢ��~cO���u�Yd;L�6s�����C:f
+4�oqP���������ܲ�&O~'���!�d�n����{щ���萅���OzX2���cF���^�eڛ\�V$�|�N�IX^�ˇ���G+B�SX3���.l7�x��]���
+�nVC-��x���^}�-p�Ƈ&o�L H�Y�a�Z��l��H:���p1�Щ��Zw��+���2/y��C��8*2qe5�\TnQ7ֹ�=������/3.����\��W���w� �������~ �|z4+[6;��.2I�� N�hR%Ղ_r��J�>J��{�h�6����N�)A3h�rnʿ}ͻߧ4w̪�4�j!ވy
+R����+���H]�P?�vT4�G��؞kܕ�RR,��:�����ɔK/�bu�7�Cc��
+'�=���$��5��W�xqt����)s�('e5��Ahn����9;}s)%�e|��OO���j���ȥz��u_Cվ���qF�v��*D��i`d|�-s�hC���`f��<�&w�'p����*-��w4G����+�)��̡���W�{#�]g�#�B([eԾi�g�w��&/d��7��c�!`�U��|,G!�7>)�s )R���.�i&���OT[J�F�t������Z���Ô�����(�;T��Yl}릘�/��e~��|s�z+2������p$�$8� B}�I�j�έ�̄����+۷����B́��l���~�����e�"�DŮx�$�z� 4l�k�`�e3�B�^��'���B�H�
+Γ R�G� \}��p�;N�2�; 5Ð�м��&~�e���4�"��� �����}�~]٢ ���JPh��pV�m կ��Ir�"�O?���m� ad ��r��}k������p
+endstream
+endobj
+602 0 obj
+<< /D (subsection.2.1) /S /GoTo >>
+endobj
+603 0 obj
+<< /A 721 0 R /Next 567 0 R /Parent 99 0 R /Prev 566 0 R /Title 722 0 R >>
+endobj
+604 0 obj
+<feff0032002e003100200041004e004e0020005300650061007200630068>
+endobj
+605 0 obj
+<< /D (subsection.2.3) /S /GoTo >>
+endobj
+606 0 obj
+<feff0032002e00330020004400650070006c006f00790069006e006700200076006500630074006f007200200069006e0064006500780020006f006e00200043006f006e00730075006d0065007200200044006500760069006300650073>
+endobj
+607 0 obj
+<< /D (section.3) /S /GoTo >>
+endobj
+608 0 obj
+<< /A 723 0 R /Count -2 /First 724 0 R /Last 725 0 R /Next 726 0 R /Parent 6 0 R /Prev 568 0 R /Title 727 0 R >>
+endobj
+609 0 obj
+<feff00330020004f0076006500720076006900650077>
+endobj
+610 0 obj
+<< /D (subsection.8.1) /S /GoTo >>
+endobj
+611 0 obj
+<< /A 728 0 R /Next 572 0 R /Parent 102 0 R /Prev 571 0 R /Title 729 0 R >>
+endobj
+612 0 obj
+<feff0038002e0031002000470065006e006500720061006c0069007400790020006f0066002000470072006100700068002d006200610073006500640020007200650063006f006d0070007500740065>
+endobj
+613 0 obj
+<< /D (subsection.8.3) /S /GoTo >>
+endobj
+614 0 obj
+<feff0038002e0033002000460075007400750072006500200057006f0072006b>
+endobj
+615 0 obj
+<< /D (section.7) /S /GoTo >>
+endobj
+616 0 obj
+<< /A 730 0 R /Count -4 /First 731 0 R /Last 732 0 R /Next 573 0 R /Parent 6 0 R /Prev 726 0 R /Title 733 0 R >>
+endobj
+617 0 obj
+<feff0037002000520065006c006100740065006400200057006f0072006b>
+endobj
+618 0 obj
+<< /Ascent 686 /CapHeight 704 /CharSet (/equal/uni2209/uni2260) /Descent -177 /Flags 4 /FontBBox [ -400 -243 1032 871 ] /FontFile 734 0 R /FontName /UZJQXT+txmiaX /ItalicAngle 0 /StemV 65 /Type /FontDescriptor /XHeight 450 >>
+endobj
+619 0 obj
+<< /Filter /FlateDecode /Length 844 >>
+stream
+x�mU�n�:��+�E�t�=���%�@m�&��֑�\�d�2p���s�,�E6���1���O?7�vx��E���<\��o�o�Stsc��r�����ַ���W�c�G?��������9$���ۥ�׬��J���k
+��'�k3�w��6ϗ�m���D�S7����Eş����x���P_��������9��T��J���q�#��.RZ�]3�O���(~|?O�x߿ �ݝ�� ��i|'���������_�������tz�!d�ۉֿ��a��G/��q�yz?y��Y1�fh��th�x�_}t'�N�9��|����3.y~�=W*�����!� �'
+�{r%⚀R@���2��%��e��B�yl�@W(#� �ICl@F�<�~�$ �<����&�V�V�c�&jm�X@�)���
+��04�P#3Gf�N7�&��|��3r��1)�Y�H� W@�X�����2^�D�L�+���Q�+X�!F�!uE*KLu��H�N� W'������NY�'�� �؍�9�02aW��L9&9���(��%����@�{Z誹�#�{Vص�8���k8F�H��j��'�n!h�!�C��g����W)�l�IE.3z]�lc�g��wEژ���<M�q���)8����n�SF��)K�žcCфSE=ソ��1�d���")9�L��b�rN���3I����S���.g�'�9�O^�\��n�.t*fN�+fNг����җt�h �%��ט]�5�s�f+���e�؏�Nj`���sH;7���Xw:Ǻ����r?.N\�˝�\�1\��-�[�o���sqN��}g�6<=��#��
+endstream
+endobj
+620 0 obj
+[ 536 536 847 847 636 592 ]
+endobj
+621 0 obj
+<< /Ascent 435 /CapHeight 435 /CharSet (/u1D437/u1D44B/u1D44E/u1D450/u1D452/u1D453/u1D456/u1D458/u1D45A/u1D45B/u1D45C/u1D45D/u1D45E/u1D45F/u1D461/u1D462/u1D465) /Descent -11 /Flags 4 /FontBBox [ -342 -238 1088 786 ] /FontFile 735 0 R /FontName /FBLZCM+LibertineMathMI7 /ItalicAngle -12 /StemV 82 /Type /FontDescriptor /XHeight 400 >>
+endobj
+622 0 obj
+<< /Filter /FlateDecode /Length 590 >>
+stream
+xڅT�j�@��+f�xFoc�^`�<�ͲW[;[z���5�<!l�����z��������\�A��#gﲫ�6�f��o��,���"��E�B�i����:�ʞ��M�����ț*?��X�'E�TV��>l�����A�}Y��}�����P�)79�ve&�LF��c�.�#ۮ��'&9��U� ���P���˪hoj�� a����[�����B����򲩎��\��;v}{U���k[ȶ�Nl��H"m��9Kb�X�X!�t7����H����;{wm$�T.F�y]Ȯ���W'i,9_�e�� Y_΄3���&.�񰩎��z<)�O"J�@X`�b'�G�n��.D�b� L��j0�r��`�y�fJ��ξ�A�������5����.�* ����f# @Uh��k2��&��}{��HY���ѝ[*�\����q<�1�D����o�8�b�SĖ�t
+w��;z�=�H�0ωu�^N�� y�}�3����|�ѳ���p�S|�$�m�S�9� B��Bu?�0s�q|s^9�o[w_�|h[���j��ӊܷ��T��Z��_�kf�5�_�
+endstream
+endobj
+623 0 obj
+[ 720 566 492 715 719 304 270 678 553 848 714 732 540 732 601 506 578 684 637 923 681 594 618 535 524 431 538 443 336 501 563 307 288 519 292 863 574 494 527 543 388 400 351 570 438 741 515 ]
+endobj
+624 0 obj
+<< /Ascent 441 /CapHeight 660 /CharSet (/R) /Descent 0 /Flags 4 /FontBBox [ -45 -187 2238 794 ] /FontFile 736 0 R /FontName /JESRHI+txsyb /ItalicAngle 0 /StemV 74 /Type /FontDescriptor /XHeight 441 >>
+endobj
+625 0 obj
+<< /Filter /FlateDecode /Length 713 >>
+stream
+x�mTMo�0 ��Wh��!�$;�S� 䰵h�a��V:������v�=$ ��G��ݷ��,�ڽ���R�ھ�t����wg��.k���6�k+[M���x��rkq�n�MS��i�㥲�kRb������7�k6�����R���Ip����8_ ��O�������y�QJ逼����zo>��I١n�n#���)-��F��˓k���~��Msh��J�_�a?tWR��͟��vu�.�?)s'���|�P!��^��\BW���Ɋ�W~Pޮg+4��U�me��ݮy��JʵX�ڳM�ߙC��[�T�O�0Z;@� 0@`��@�#��ɑ�đq��-�o��Pȡ(G�, �Z2�H89���@����F1(դ4N�oH��Ç�k����S�Zp�qR:�[�(.��t�����J rΑ�� S��`��{׹N���d���s\��'?'?.&����Ww=������p��3��L��O���5i��uԵ��숰��1���lg�y`�6k� g=9�R�*%<a��)۔��U�?�b�|n�Ĩ�GB[�3�8��)~��l������0�~�_ȧ7�^d��6��8�k�Q���p��ń��.�ceP�A�,2����4 }e ���"C¹~I���]������7V���(/]�v
+�+��uc?Vڹ=#�~� �� ���o�[
+endstream
+endobj
+626 0 obj
+[ 667 ]
+endobj
+627 0 obj
+<< /Ascent 56 /CapHeight 0 /CharSet (/summationdisplay.1/summationtext.1) /Descent -612 /Flags 4 /FontBBox [ -5 -2960 2900 1444 ] /FontFile 737 0 R /FontName /THUYEG+txexs /ItalicAngle 0 /StemV 1000 /Type /FontDescriptor /XHeight 400 >>
+endobj
+628 0 obj
+<< /Filter /FlateDecode /Length 558 >>
+stream
+x�m�Ko�0����]P'!�BHyJ,��
+��  �(����h+X�=�7>�&�޷���4s�9���ꛜf��}mM&I����+QA�8۾���ʷԱi�I6��T�F�羠1�qRD�R�S��������vv��sW�G���*��4S��1]򇚶�� ��9�JHeW��Z����Ύ�,�� ;��e V�y7Dz�/j3P���]6�XY���ɶk���5k
+jJyb�o��̶��3���z�
+:���_�b�G �Rvך�бm\�UAm�ϩ��Y+��l�ek�d�c.0�� 5�����Jp!xj!, �F�!���B3őA�H �_�%�䋐*��MPFGK�;Z���k��f�e��9[���S�c�%�5���a]�0��7:�s�6xi8��pdX���pN ��̬���9�������;��{f�l;K9<�������|q���w�1�B��=���}�/ k=6 _�pd� {�9Ӝ��_}���p��Pn�:�F�x���M�.%�\]ը�?�R��Do��[�B.
+endstream
+endobj
+629 0 obj
+[ 808 945 853 853 853 853 853 853 1323 ]
+endobj
+630 0 obj
+<< /Ascent 438 /CapHeight 438 /CharSet (/greater/less/uni22B2) /Descent -9 /Flags 4 /FontBBox [ -342 -214 906 786 ] /FontFile 738 0 R /FontName /IIOJER+NewTXMI /ItalicAngle -15 /StemV 82 /Type /FontDescriptor /XHeight 400 >>
+endobj
+631 0 obj
+<< /Filter /FlateDecode /Length 673 >>
+stream
+x�mTMk�0��Wh���F��K�v 9l[�����Jא��qX��WoG��3��Fz�&�ݯ��L��^��G����� ���w�wwWt����Y�Z������]��#���źm�C^���R��3)�M�(8��o���Y�۾�^����86팃�mƣa�L`e�PFe�pn����GιVm�w'tr��W5l>�;4m=\%�=zB����kF��d,A���<�Ӻ=t�b��of�<������ ������f�6��?j�`�[.Y�fK�������6o��g���\XeUW�s����k?���|�e��t[[�-�&�o�<��7uH+ DV�K�� P"B�!"����0��PL�3�C�Q�,b�HN`I�"�����X��N�3��M��4 �H�?ӛT��R�Hj-�`�T��9
+��<�2�P�O�GE arۏ&�����:(�3�Vq��%.)�Bę�B���xA1�*8�1c4���
+��X�yځa�����A�r��.�YA���� K /]N�O\~��b��}��/�8A�r�D�I���4�����䫄idc�fiG�XY�%�V���+�,��E�>_�?ۘFl�!�Tjo�W�G��N���K�G�v���0��O/ �h��շǧ�zTя^��D�Rz�x�
+endstream
+endobj
+632 0 obj
+[ 418 418 636 441 636 ]
+endobj
+633 0 obj
+<< /CreationDate (D:20250605072812Z00'00') /ModDate (D:20250605072812Z00'00') /Producer (macOS Version 15.4 \(Build 24E248\) Quartz PDFContext) >>
+endobj
+634 0 obj
+[ /ICCBased 739 0 R ]
+endobj
+635 0 obj
+<< /BaseFont /AAAAAC+Calibri-Light /FirstChar 33 /FontDescriptor 740 0 R /LastChar 42 /Subtype /TrueType /ToUnicode 741 0 R /Type /Font /Widths [ 507 507 507 507 507 507 507 507 507 507 ] >>
+endobj
+636 0 obj
+<< /BaseFont /AAAAAE+Calibri-Bold /FirstChar 33 /FontDescriptor 742 0 R /LastChar 44 /Subtype /TrueType /ToUnicode 743 0 R /Type /Font /Widths [ 686 537 503 355 474 488 537 347 226 532 538 246 ] >>
+endobj
+637 0 obj
+<< /BitsPerComponent 8 /ColorSpace 634 0 R /Filter /FlateDecode /Height 214 /Interpolate true /SMask 744 0 R /Subtype /Image /Type /XObject /Width 214 /Length 2977 >>
+stream
+x��q�6E7� B)8�[�𗿜����*���� (l�>Ѝ�q�TCr�ۇ}��h����
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�
+�@u
+�}|V7&4�o�?��!p�x�7Q��o���oh�h���x�hW7Io���ǀP`�`�1�"^�' ƈk �� ���0�1b^�,�����@v�uE����������?�y�#�=���/X�����4X�I�
+ b�}ǽ����!Ĉ�N�#,�`��g��,Ĉ����-#�>��LpӂE�g���?6-X���zf�g�q=1�x$ i�c�ZA,Ĉ �����w���҂E�ǎ�'^Z� #�)�5��c�5D��1�`����IQ� 1�"�����w @�I��`�ˎ���P�� 1�>(;�����Wg�_�`�;��+p����q�:��cĝaPj:�-X��R����l��@��uJ���cĥ��M�7-X��nda"f
+ܴ`A Fl�n:�o�q70�O$��4h? zlW�,,Ĉ���~�,#��]=f�`�;�)(�т��A�:�"�c� a9��,Ҡ�\�E�[� #n�
+�1kX0Fl���R�`������*�d��@�X5�M7�g�q�`� ^ՂE������� 1�ذ��c�6ql� i�Q���,Ĉ�B�h�6�7�����,X�A�y�~+
+�Y� #n��qZZ0F����7�`����gW�؂�q��6נ�c��A�7�",Ҡ��h�~�X� #�����`�X/� �\ЂElH��C}F�g/�?]���?<�����O½����������%�#�M�$�1��㟦Փ���T��7�V�q�Næ�S_ܣK�M����t��`��"�esHM^�+h�ߔ ?&�B���1Z�:
+�7A�>92G�r ����|ׇao����UJ�m���3����L� twG)e��@��u:*x&dBww� E���+��K@WiX!D�Ӳ��x�UU �4�L��<���ɄE���iU�^���@��R�5��ȄTiJ�s��y�QM�%��6/�L��& ���� n+'� ��s���*�.g�@�俿�æ�����iB~���\��8~��aYH��'J�mz�{�!d%��5-�j���q�ξ�A���?��؟F��B�4z\ly@�<�Ti���^����&dU�ҍ�ߔ )��
+��.j�Ǔ��;ò�*M:ke�������oRa|2@H�& f{����7�r�����tOC�_V ƯrJ /@H��2f{��c��*�Bwγ�MB�q�*���Ϻ� �mv�Tpd6�1Q�^��=Z�-@x�7�f�K�u�Z��*�,}8�;���Ì��1@�9M]���1:`��z�bƏ�Kֻ�!O�_=Afۛ��ƀp/Ru��E�TXR� 4���am��!da����O<v�0��>�� �'��v �J~�pX]�Jö׊��� �A��Xؾc�^jζ��{ �¾�4n�;���4%��L8���G �^�铃�P���Ŵ���
+������.�Ѵ�@{�^�� �ۂ��N�u�+$��{ �@�W)���1b���`o�,S(�6�{1�B���ǂ=��S4�_ O�}tF���S���[� ���9#N��5+Fx���0b+�^��c���:L���_�a��0� 51GL0Kt2Tf�@�U�$�п4Z&�p2b�%���^�Z�琥�f燵`O`��`�fȉ�F�`!5���ဏB�E Fl �f_ނ�z�&0�D�TU`�G!k1bU��{�G{�&�q�K��aby8��Y����0�p$���%�01�<Q@,�d=�����b)��E�Z%�؛���e9 5�(��dq v�2��ť4�ӽ��d6x�|����8��l�VKg�B3{�g�l�9n'�YpCG�Է�].*�������JJ=
+Y�>1�Gr.�<��ED����f7����o=ǂ�#^�#������/��=�?�O��A;�4T�r$;vQ�>�f �9���`��|��#�����[��.�3~W��=�_c>���f��B@��w�鸝O° L�����C��E����� B�X���=�O�O �.S9T�2�_��wT�V㪏B�R�Z��ޭ��e�r���ɛ=uh�>1}��u0b�/�7Pz2e WlyUj�9~�q�d� ��zU3.�B�x�\�|�!F�����\<����x`�_��e\N7��2��I�ׂS�]��Ό_1���o3�c�ڌ��'p��,:y9���
+�.����O��ܱ`���,����wd����q���O�Ԝq��������8��;�8cP�Xp�o�U��N2��ՙ��S��̝G!m�>���k�XHz��g'�Y3��7/5_��ާ�$�`�{�s����6��f�������:���9��.5��u��51�:��ُ�'6����<X�젎�{�!�Q{�騬ԜW�S� ��5ɫpܚ��4�"��P|8�ײ���p ���s‚���Rs^݂>�1w��R��^�8`�[+ L� 1�n�$,x��'�;R��J��>��9|��)�ks�Z�X���t�?�N�����N����Pp��^蚀0��I֏B���W�9)��{b�g�􊹛��@�{Ə��+)7!Ĉ_ɶ�4t�-6�U:����^vNF����l���s�m�����{C8+�]|@�i��� ?_��8���[bsG���b�E�GGBҎf�2�H.R_6���5뙴�� ��5�zu��Y
+� �|B�������o�H(�(�(�(�(�(�(�(�(�(�(�(�(�(�(�(�(�(�(�i�Ou4�
+endstream
+endobj
+638 0 obj
+<< /Author (Yongji Wu\nYichuan Wang) /CreationDate (D:20250609221353Z00'00') /Creator (OmniGraffle 7.24.5) /ModDate (D:20250609221353Z00'00') /Producer (macOS Version 15.0.1 \(Build 24A348\) Quartz PDFContext) /Title (workflow.graffle) >>
+endobj
+639 0 obj
+[ /ICCBased 745 0 R ]
+endobj
+640 0 obj
+[ /ICCBased 746 0 R ]
+endobj
+641 0 obj
+[ /ICCBased 747 0 R ]
+endobj
+642 0 obj
+<< /BaseFont /AAAAAB+HelveticaNeue-Medium /Encoding /MacRomanEncoding /FirstChar 32 /FontDescriptor 748 0 R /LastChar 223 /Subtype /TrueType /Type /Font /Widths [ 278 0 0 0 0 0 0 0 278 278 0 0 0 0 278 0 0 556 556 0 556 556 0 0 0 0 0 0 0 0 0 0 0 667 704 0 722 0 0 759 722 278 0 0 574 0 722 760 667 760 0 648 593 722 0 0 0 0 0 0 0 0 0 0 0 556 0 556 611 556 315 593 574 241 0 0 241 0 574 593 611 0 352 519 333 574 519 778 537 519 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 556 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 556 ] >>
+endobj
+643 0 obj
+<< /BaseFont /AAAAAC+HelveticaNeue /Encoding /MacRomanEncoding /FirstChar 32 /FontDescriptor 749 0 R /LastChar 121 /Subtype /TrueType /Type /Font /Widths [ 278 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 556 556 0 0 0 0 0 0 0 0 0 0 0 0 0 0 648 685 722 704 611 0 759 0 0 0 0 0 0 0 0 648 760 685 648 0 0 0 0 0 0 0 0 0 0 0 0 0 537 593 537 593 537 0 574 556 222 0 0 0 853 556 574 593 0 333 500 315 556 500 0 518 500 ] >>
+endobj
+644 0 obj
+<< /BaseFont /AAAAAD+HelveticaNeue-Bold /Encoding /MacRomanEncoding /FirstChar 32 /FontDescriptor 750 0 R /LastChar 116 /Subtype /TrueType /Type /Font /Widths [ 278 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 556 556 556 556 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 649 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 574 0 0 0 0 0 0 0 0 0 0 611 0 0 0 352 ] >>
+endobj
+645 0 obj
+<< /BitsPerComponent 8 /ColorSpace 640 0 R /Filter /FlateDecode /Height 587 /Intent /Perceptual /Interpolate true /SMask 751 0 R /Subtype /Image /Type /XObject /Width 512 /Length 3955 >>
+stream
+x��  �Om7�@a�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�����
+endstream
+endobj
+646 0 obj
+<< /BitsPerComponent 8 /ColorSpace 640 0 R /Filter /FlateDecode /Height 512 /Intent /Perceptual /Interpolate true /SMask 752 0 R /Subtype /Image /Type /XObject /Width 512 /Length 13152 >>
+stream
+x���eey�{�>�o�otӇ����\���i��}�"!����t äTp�T&��b�3�L�� &fLi*�jf*sI+Q'3Έ�F�P�L��y+gfמ�����^�Z��P��ֻ��y�����w�^{�}�,�?@� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @�<�,[�e������������S�����N�N�{�ݲ�F'sS t�Z:������ �� � ����W��Z:���-.L`����O|hB�� `����^�j���@�i�W���Ώ�m�,H�;�v?���767��{��ĿX�O�Lp���A�$�4��{�o��� �~�q�&��� �,[���F��U����>To��G�G=��4��to���ѱ�Z�s�z� X%��ࣵ��a�o�m��̾ ������a�ck������!DBV 8+�� ���� �%`���Z-�!�J��"4L�j'�/@���a�ck�|;�x@�*�Z�`�0��̾ _��������!�j-�A��v2��| 6:�VK��C����� ���� �%`���Z-�!�J��"4L�j'�/@���a�ck�|;�x@�*�Z�`�0��̾ _��������!�j-�A��v2��| 6:�VK��C����� ���� �%`���Z-�!�J��"4L�j'�/@���a�ck�|;�x@�*�Z�`�0��̾ _��������!�j-�A��v2��| 6:�VK��C��žCg7m�vي5������@���k�B{�=�� }���
+����L�j�~��� ��n򪱩Vl���5U�T�Um+TY�E^�ѣ�����욹���I��\k�H^���dlj���K�-w?3��� ��%X�z��[@0&��@_,]���i+��l���]JMB@��^Db�I��$ 0y Xp�#� W����5gǷc��q�����h������ $`���~ 0F��ƮT��k�m��-�G�)5 �];��'��0s &�Ğ踷/X����3V��[����v$���v9�_��P���[@1V,�]��ɵa�i!���-`� ����W1�Eҟ��f�o��M��:��
+�1����y�W��_�?&8�ƫ���&�����ˬ��`��| ��Z����"���Ǩ<�@7M��*�?���jA���!��/�&���8濠_�������Ǩ<�@}��$�?���P$�xna¬��5ۮ b��S��������vp}���t������3yi�,�[@��0�����S#�d�����QO/#xA�oaBcV t��+�`� :� ؾ��Ǩ<�@�r�s��v6� ��y��K�;�?Z �/za��z 诏Qy�Q���1�ߊ������0aV t��e`�^.Dp�����cTF`h�]8��[t3� `��!��/�.��| ���0�u�n��1*#����[�1
+&`��!��/�.�?��<L�������h��1��8eD0p �f��@����Gz�;E�ﷀ����h��1�Ny�$!��[@��0�����?�ې���{ 诏Qy�V���kQRB=��y��K���c� }�T�%��[@}����̿�~Ea� ���!��/�����'wv�@�n��1*#P������욹�"/ܳ����;�tʃ@-׺�� ���N2N8�D&Of��@��za��a�0�ZWa�Gbn7_]J�/�)�Y�%P���:����Q�1��w��D����Y�%P��6m���?�>�Ox�w�� ز��2: )SzM�L_-[�Ɨ?����(xAa�
+X�vs������(�W���(�A'!��n+V�/�S/�l�@�
+�侀Q�H���v���Ԁ�������E!���� �v����A�k}�~4굮)"w P~/�=;=|�owM�6܏]t��D��[���O��[?\lʴ�NՀ��t�����&�\�����_(#R���*/�Z:@]8DB���~���g�^u����(�k/�}��2����H��>��ʆ��| <�?����O��􅽇�W�E��N��A���NuV��!�dҠ�V�)�6(]��2�e�_�r Π�H�[�k���W,�C�/e� �uJ� i��)��ʘ��| 4�����S"m(�Tn ���X���1e$Y���S"m�m��:+cZf;�%�\}zB]�D� ��FL���W,�C���E��uJ� � #N�Y�2ہ�/QS9�t�i�@�.ϩ�� �0F`\>�Ft�i�@���Y�2ہ�/�2��]E�)�6ԶA�A���X���1�է'�uJ� zo�Dꬌi��@��@��"��:%��Ȇ��|�B<�5�#L�)�6���:+cZf;�%0.�b#�N��A�Lk�|�B<�(#��Ut�i�@m$�Y�2ہ�/�����:%��7b"uV�b!��-r��S"m�lq��ʘ��| �����Hrt�xN���X���1��)6��Hʴ��ʘ��| ��d�*�N��A�� ��|�B<�H�>=��S"m�{#&RgeL�l^���''��T��b��:%���n��ꬼ�B0l�տ��·�;{��y�,_��m�:r�Gt�%��uJ� I�f�$:+rf� y�٩��q�LM-ݹ�ŕ0`�FlH�<R� u� ny�S�ձ�NPVڗ&W«��ퟦl:7�f  ���ߛ^�b�:��N�t��M�J;>�^�G m�4eӹ��! �~�qEۮ<ޤ���J1�X"������ ��-@@$p��W(�X���&e�W�!����ӔM'&
+�0 0�j�"���˚��v\)�K��OS6��Q��t]4)+��^�6�ퟦl:+Q8�A�]M�J;��C� i��)��ʀ��D�.���v\��H��OS6��(� `����&e���!����ӔMge@�l"]M�J;��C� i��)��Ja0@@�E��Ҏ��i�@��iʦ�2 j�����&e���!����ӔMg%
+�0 ��IYi��z��A m�4e�Y5[��H@�E��Ҏ��i�@��iʦ��C �uѤ���z=D� ����� ��-@@$��IYi��z��A m�4e�Y��! �hRV�q�"mH�?M�tVD� �uѤ���z=D� �����D�t]4)+��^�6�ퟦl:+�f  �hRV�q�"mH�?M�tV�p���.���v\��H��OS6��Q��t]4)+��^�6�ퟦl:+Q8�A�]M�J;��C� i��)��ʀ��D�.���v\��H��OS6��(�Ȱ3�����_����?��˖�[753������]��{��ϿY�p�K�n�f���d��
+d��;8ѭ/}��p�b����|���rp��E�z��1Ӥ���z=D� �����|����o���7�.�KJ93;{� ��6�%q���7���䖛�������'���<�����+7�j�ճ|��q��#3�V5)+���Ҍ�&����� }�)�;�:��ߙ�|�^I��� ��/ �9�}��܁�?r��7D�a�l'�+��oIY����� ��pG��Ҏ׬͐ii��)���W�J��_��۶�5���Y����?P��q�#jB.S������'_�*~D�W 7�
+s�s𙧕Kv������v\)�K��OS6���B'ǻ�w>rZ_�p侧>8���W�3�¥�/w��_K�8�=�_h|$�[Ϧ����I�޲e|��#+Wm8q��6)+���/i��)�N�I���� w_�/]>ҽ�/7e�Ν�_��=���
+�B�,q_��j�0X�������]5�v~d���'?�$���Me0n�@��M�ӛ F����w�nߦ��J�{�㵩ap�*�܃����w��ELp��u����W�����_.���� ��^w��S�Q+�L��50b�@�F����*�6�=Ww���m+�=ʮ����
+�]׽��_��kD�$�v�������[�^��U�{��ݻ�[���{����_��(�i��4L wG���F��Mw�;��gH#�9�0CG.�vW����������z�H�v}�D� P��uV�*'�t� �
+�}zr�^�^���©��T�>�oD��J=�է'��K� zo�D�b��溏z�k��l͚�_�����[y��~�v���2���d=_�i$a1B��۴;ƭ�lq�N/FG�D?�_����ԗ�0x��9�u�#��;F�5��zDM���K� 9�h<���K��`���B-F���c������'/�.A�x�NN>��W����'/1>q\>�F&�W�(�Z:�q9�#�}:��uv&tg���}�(��wbl�M1���a�"�A+���d�*�~��A�� �ꬂ���M_ey�MGn�����η������Oֿ��`P�C����aqp�_���|:`��)u��ǂ��X�vݨW����է'��c� ���,� ��o��Wq��vl��6!a�_Rw���w�(u��sb4�ױ��W���V�Z�\}�D� �0�t�U�T���{}���7��N�����RyF��[݁r�����d���rԖ�࠾ʂ���R���a�~��A G���Y����1} �m���!R7����r����חi��G_
+��꾖, ��;��z��SlD�/�6�i-���B��ݟ�җ��c�!u���߭{�7��.�dɞ�φ�z�Kx� n��2��]E�/�6ԶA�A�U�T/=q\\½��D�f��uH%a�[���z�Dغb~��wV+�$W��P�/�6����U�|���Ϳ�ɰ%:5K���o��O��/� �%�waa�}g�RO��"���%��Ȇ��|:���墨2�G=Ö��,�gR�w
+�]��0\b~��wV+������Hrt�xN���B��ff�%}��aKtj��ٴ�:qݥ˖��󻰰���Z�g\>�F��i�@���Y�*t>>w�����R�����G�#q]�?�җ�d�*��%� ��6H>��
+N��aU���~�[��4�Ox���OOظ=^0J@H^��r��*߬V�����'��1B��;a��d�@dÈ�uta:ʝ?��|�Z��Ç�u��g̥5�#L����!����s�„�;XU�f���]�5}Q~�+�ҏ˧؈~���A�Lk�„�;XU�f��M�����?���/��]���y�����i�@�.ϩ���a��g��9Z�3����^z�WG3��%��T�J=��)6��Hʴ��JQ�xL���+�;Rl��7����v�`8��%VX���T�ٶ�oݴ��mW�����hst}�D� 0z���DaV�r�,��i�����r�t��������!�`>�y&/�5qr ��z�����}����6���G��H>U�g����{ Ljΰ" �4w�a�Ͽ|ݓ��x���U+�E�#ݔ������\�a°ߥ�ů�����z�a�|g������o/�Y>{���!�ڜ�~��A�� ��|:�;��*'?�ٙ�Y}��H���>�S��6Րi������Я��~��u��|-f�̝���K.�ڄ�+�U{j� ���M��hd��n-g���t�� bn $o�e�NA���^����w���#�?�,��&�dmB�b,�m��:�0-����$���Ιի>����]1��_�J�v���
+�S�����%6lz{rI�&T�!���6H>� �s�������ޯ^Ld�5g���,���Y��s׳|�����]�䒬M��Hj� ���*L˹�oعS_B�to�ޯ^LL䦽{���Ͱ����k���8w=��ArI�&��K� �m�|Pg����gfW�K��R����G�ݶ������,����L�����'�dmB�"m�m��:�0!�Ο�������.�����C��a���9>7�H�z���%Y�P��Hj� ���*LŹ���KxE�ޯW1���O����9��q󝕻=rI�&��!���6H>���Uh�p���o�+2�~���
+~����}데��f�4eH;��=rI�&��!���6H>��
+�o��9>�9_s���d�H�9���z�n\��vz�������K�6�^�6ԶA�A�U��s�wU�_ג?����w�=H��9�����5���NH�������K�6�^�6ԶA�A�U�xs矯���/m�k)����԰`�`�R����>��$��+LH���r �-�`�a@rI�&.��"!P��u��u�8��Ʈ��� �ݕ����^:πȩ���d�/�|����s �>�M�`�Z��a����'�dmB�"m�m��:�n�Է����ܷ��ss��Z�z���%Y�P��Hj� ����W�����V������?z|!g�B{pZEϟ\�� �z��A�� ��*Os�����#?����҃s�*z�䒬M��C� �m�|Pg5�P������q����ȏ�9�������?�$k��i�@m$�Y�:m��Vա���A�\���>I.�ڄz=D� P��uV�N[F��Uuh��?��������%��1"�tV�N��Of�8������E��_�4vq��Wx�����_�"� <2L����xL���+N�]�G~����u�,��Hc��P'�jӫ�WV�%}��MIR�?����,]�,lQ1� ����cӕ�ִ:�V D6�8]����
+�%���o�-��z�o�Z,f�� z��H1� ��s���(�Ȱ���J �a��:�Q�ӏ�]�C\�O=�� ���ωŸ�� [B������\Ǧ++
+-2�iuƭ�lq�N/�/=q\\bˑ�aK�.>tP,fۭ'����b~�/��:6]YQh�aM�3n�@dÈ�uz�.��~�q}����u=�o���z%{~� ��������cӕ�ִ:�V D6�8]�懷~���k.}�ï�}�B�g=��+�oc���'_����U}�~�?ױ�ʊB� kZ�q�"F���kr���g^??5�T_e���WO����#?ze�7�5LMO?��k����������MWVZdX��[%�0�t�^��Y�T髸H���]����*�c��۶z��uW���B��G��X{qE�E��.͠a� #N��X�<��V_e���!�q�����~zw�t� ������>Sق~:�g�q����X{AE�E��.͠a� #N��X�t�vv�E�B�F�n��}��ie ��^|����X{qE�E��.͠a� #N��8y�c��/�n��g��_ы��;\���+
+-2l|]Fl�lq��P���H����.��j+rݎ��������>�?�q���B� _��"F��3�=�6�~E_������_�jm���^y��q�:V.�(�Ȱʢ��'�0�t��M�לyX_�|䵏�k�\����;\�ѫ,
+-2ltE��Ȇ��$ul�tO6�ݣ�X2rn�u1o�����_��:�^eQh�a�+r�D6�8]'9�����|#�����~?f_ù<{���� �p�ZZd�p9 �Ȇ��0+|������f������=��o�2qfv�R� �L�ݩ��\��Qh�az=D� �0�t�UB�:}��M��՗���<|� ���J�.,�m�2|��8#
+-2L��H"F�>55��
+�{XM��!�:���@Y=S���}O�g��{����j]���[���E�����C� � #N_9�Q�従'�G��k�N��"J�b�{"����@ܿ&fV��\� H����JJڻ����諢�"�FW�x1�lq�%;�?���ә���y����xs�k�����o��G���N�w�`�F�m��z7�B� ��!��Ȇ�<���� �.}�[�զ�!���/����h�B��tv���eu�!"���
+p�'���a��3�Qo-Qh�az=D� �0���W-�'�~�׋9����۾���[�/0���+6\��z�n��覻$.�K�}��w��t�/�v�����w��COf��6�E���먷�.��H�"m����'���ˏ4A�u��c��|FAft�@��ǽ�<�.#� �J��}G_�q��Y�`j��w_��AmRrн%Ln���z��A��C������ǟ��/������%F~t���!It�`�"mX�%�tV��2t�'���z=D� 0z� ���@��t)�M�"m(�W��tV��2t�UP�A�"mH�Bz�2ct���!��b"�z��A �["�vV��2t�Ԛ8]��H���VFb����=$��s��i��x�*) e�RF�z=D� P��jW)#1V�@g �R���z=D� ����U%�A� �CtY�D��i�@L�D�-#1V�@g ��5q�^�6���#����0�!�{H����!���(6RFb����=��*�z��A�L_ծ�YUR��=�VA��z��A y � �H�U �Y��貊���!���n���YUR��=$Rk�t�"m#GX��
+:K@��ϩ�C� �=Pl����0�!�{HU��i�@���]���X�%�{H�����i�@��vV��2t�e��C� 1�9���X�%�{H����z=D� 6F��Ϊ�� P���!98�S��H�{���-w?s����������U �A��P�[B��H���p���ήݰuɒ���7l�n���j�� ����!Ce=��!����4���������]���<�˷rˍ���&9���J)������&���*��^qt2��O<�)mR r����W+j�t:�"Nj�@�F��=p�_��O����}��/s+����)� W��fa�L��H��[��W(��@��&�@ 7E�1Ae:��!��L�TI�rv��k����G~t��"�����2���i�@�F�����Vp-]��;ڤ�&��b>�"�L�z=D� ���*iuV�G~t������2���i�@�F���YuG�T��t]T��T��H25R%��*������uQT�S�"m��H��:��h�J �������2���i�@�F���Y�V�!��.*��t��C� ���Vg�mR r�uQT�S�"m��H��:�܊#?�C@�EEP�N�z��A S#U�ꬺ�M*�@n�.*��t��C� ���Vg�[q�@w躨*ө^�6dj�JZ�Uw�I%�M@�EEP�N�z��A S#U��r+���]Ae:��!��L�TI���6�� 躨*ө^�6dj�JZ�Unő�!��"�L�z=D� ���*iuV��&�@ 7]Ae:��!��L�TI��ʭ8�C�;t]T��T��H25R%�Ϊ;ڤ�&��"�L�z=D� ���*iuV�G~t������2���i�@�F���YuG�T��t]T��T��H25R%��*������uQT�S�"m��H��:��h�J �������2���i�@�F���Y�y�|nё] �Z]�EEP�N�z��A S#U��6���^�<���y��M���uQT�S�"m��H��^���2w����;�T���K� ���*i�)/V��̓�.85$'�۵���|*��t�U�dj�J�e+������yH�:��w�Y�bmEP�N}EJ|� dj�J�M[� Ń����x�3���KvW��4@�L�5�L�TI��й0J�+ ����Ea?�ϫf��sAe: )��K S#��}a��a����Z,��@��o���15��i$L���/�L�4���=�ή� �- � ��1��$�3��L#a�dV dj�ڴ����ٵ��X�^@+�Ţ����;��Z���>V+�L�a�dV dj����"���="�/�w����Qy�&��7�-�GF��zg�����zV>����[@��0��h����<�� .��%n��1� �S����,�׳��������)'�_���{��a�O��ܯr 踛Q��^�?�f��������-��a�,���?��k'+~A.�-���Fa"���Yh�g�we n���A6��ﵓ���s�nt6JZ������,�׳�x��
+��݆�N�d����<�xљ��q 蔿Q������^�*f��B�&x/u��=���{��a��\2�[@G\�2j �4�?�B{=���{��-��yl��U���{��a�{yr�`n�{T6�?�B{=����.�-��?��H������v��} �|<�������u����0aV ��I�Y��� 8rhD�'��߉��>F�a
+;y�r�ʛ+�X$���Yh�gr���0�������v����x̊���b^qQ�?�f����ƭ���� ��������v��[���E����Ź�"4�?�B�;k0���ⶦ���{����V�䣞���>^*LH`����mЋAn ;�TI�����@ I_�]��V�T$���t�b�����/�.����皬�/��F/(�m0`��[��ʺ���O��[@+�âC6��^P�k�o9zϳ�}�G�r 0߱�ݠ���;�c ����z�-���d��])�[@�&!�H������E�i����}����<��ic���3{Z�1���{ڇb�}�tߚ���@X${��G�Dǧ�ziO�t� �g����9a =�󀲹Lh^�$`���������#����욹�_���T�����ɕ��rP�N`�����놹+t>DB`2�+3�>5=.�����^�܋`䅽���m��}��`0����V��q�3w�n�H���
+a-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C�|��A@ �@#b�V�4s!�Z�%-C`���5�/�q��[����Nf���/�2F�*�X:�|��3��A< `�@���� ���2���/����R-��Y�� _��Z�$�/K`��[ 73[����Vk��{;ث=� hُX�,�F��ffk������j�8~��^B0 `���w}�}?�����[&��MA^���e����'���Y�&!0I�} �}?����l��d3�)@����[�/�=��>��e+���9�>!0F��=�MϬlߏ��8��W�0��l�"���cō�;A`j������!3n<����t'̈"� �|�ڛ�|�L?�@@$p�;�v�o�uX�C\�?���3�A8��+�wȆ(�=�A�����v�]�L&���u��y�Ӟ�vte�1���ݰ��Y�� �v�d�*zD��ىz��G����OG��� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @� @���R-�
+endstream
+endobj
+647 0 obj
+<< /BitsPerComponent 8 /ColorSpace 640 0 R /Filter /FlateDecode /Height 512 /Intent /Perceptual /Interpolate true /SMask 753 0 R /Subtype /Image /Type /XObject /Width 512 /Length 3453 >>
+stream
+x��1 �Om�@a�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� ��
+endstream
+endobj
+648 0 obj
+<< /BitsPerComponent 8 /ColorSpace 640 0 R /Filter /FlateDecode /Height 512 /Intent /Perceptual /Interpolate true /SMask 754 0 R /Subtype /Image /Type /XObject /Width 512 /Length 3453 >>
+stream
+x��1 �Om�@a�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� 0`�� ��
+endstream
+endobj
+649 0 obj
+<< /BitsPerComponent 8 /ColorSpace 640 0 R /Filter /FlateDecode /Height 512 /Intent /Perceptual /Interpolate true /SMask 755 0 R /Subtype /Image /Type /XObject /Width 512 /Length 39513 >>
+stream
+x�x��>�'��=!NHB $D �� B�www�;��R� u�R�F���(rk�o����{���pJɑ����}������wfޙ��G$I��@@ ��@@ ��@@ ��@@ ��@@ ��@@ ��@@ ��@@ ��@@ ��@@ ��@@ ��c"�q�����8)*S��$��)����HmGI����R���_�R���~E��W;L���$��#���:KQYRp��,i������@@ p.4ɧ��JJ,��5���j�r�T{����*���R�.���p��1XJ,�"Z�뀚�C �C�+P�̐R���)R�:��*$�1w�&�O�T}�"�%��0% �@��W����a
+gI;��Y&���R�t�� 2(w�h,���@@&��zy{��z�<�-,dk�y ��^���4G�� ��] 8n:)���9Tϓ}���MMI�ѰI�݊�4���T}X��@@ @B5ͻH�ӥ��8�:��J�ޯ�5j�'D�^#2 ��_���K*]��K}S��8���T�@J�W[�@@ p> ��j��A�&?v >@�����_��@@ �r��&TX�:�fn�ջ)5��!샻 �3�1�΀lf����n��]5���ʬ�-��+��:C� 8=Zw��#,8��u��<�9 Cc�?����o��5L,�U���o�R� }!���'E�ȫ�s�cõ�>"5���7 q"�$E�x�I����^)g��i���\��N*[+����v�@@�KvB������N8��6�p�V�L�-{�� [�b)6W�+ /�������)a����Ч�����s�����/j����W�� b��`X'��@@ ��� l��0?��aG�;AjY)Ŵ�c��� m|��8�P$���S.an'��9�W��*u~Q�@�e�� ��������\�Yz*���+p^�Xc����R�y���v:��pZ���tٮ*^\ P D3���VֻuΓ�
+�����Ą�4�3E4H�
+S��@��;Rz�`A���x�^nI �G8������,���w|McGC��@���A��Wu�-�|����������$W�䅠�(�$�+�MR��.��7��
+ c��י�U G0�0�Ym��I]�8�U:�xO���N��`�)�#��$�j:�=X����\j����D; x�E���8�4�"��'D�~nǹRl n��Q�<|b�&j���*z�xq"pu�E ��ڎ�� �� :<6�hl��MQ}���0v�@@ ��@�R���]���R�L),��a��>�`":�
+�E�V�4��������-(�@��R�}j���A�pM��V��6q�:�� v|ø+(n�շ��`o7s��wq(���NV��^X�3�8A��U!�`&�JZҪ��\�8[�VÇ�܉V�js�� l�հ?�Wo�$�z�nRh̪p�� ~P�!8% g,��R�}�>F����`�����2�C���J�L�dè�������_���� �?���W��՚�g �U'�F
+~s�96��G���핳�v9 %����ƻ���< ��j��W�%aKH���! �
+�?�#`�eSw Zw�����>3�������?���?�_���o��]�޷�}���&�m]�=8������ؤp��=�߻��'q΁�ʫ�(LySm|������c�c=�����\�?ũ���-_������9��6��Ag��P�r �ve?�:͵�:+)pZ�T8p;��Ҋ��@��eUs��|�5����o&��� R|ǔ�Vk��Ï${�:��A�b�(�ܿ#��+C��X�V9bR[��2޳��^��ֵ�K?� IQ���>��҃�Z>+����O�JS���"�Pj(��NT�� ӹ{�v,�zۚS��ة���5��w���Ӭ��*�7����9��,�o=�B�@@ �@@ ��n�aa�ʦ���-�����l��oT�u����\���%��Eƨەھ�"Ŧ�{Z��� J!O�*�w�X����)��W��肣и�z��62�e��^t3�}�e ΂����<����$J�*(�_��(t`K�p��ȧS�-�C�Vn�n���+x��߂r�;Lr�=
+�sQ�@�z�Q�⪀���eГ�|���w\�V��a��UA�^��Z�QL��<���,����@XK�}���T���=z�0�R�?����'���1��e`l�V, znU�C�x���m�1"Y ��m$�O��VW���Z�&|�Ҟ�x;K��
+����/D�@9pСTXgȔ�@"�@@-�2�T�3?q��'��/}��9��ʇ| �n>A�-���}�!��&f�Z�RB{q�E ��*�<���߈G��A`D�'d��7��1�5��@͢����,��恜�r�S�=TU����'py`�����1ί#��E�n���`��ϝ0o�
+�l>aM�t�gm����#'�i�s@
+g�X��mn��%��v��s��F@�S���7(�}��5G>��R��y2�"7~m�I��nGt�P�jv{��O
+KcΙg��H��4Q4_(�r6��M ���ꪧ�_o�GMyf��e�/�*����V�����CO
+�7
+����9���kn�Q#��U`
+(�!A�T��u��;"-�ci��;m;���� ��aQK���ݜ�Z�"���Q������:�8�"U �,���c�J�_W�n��C����OT ,�x���g*�5��T����9O2*��Ei�@C��n*����<���ςi�L#��_��-�>J�a­_�N��
+���!���F���z>���f��'�f@`��k��]�����
+�8/�g#\{H�)�85@�u�ɿpˉ��n����s��)`���Ŏ���]n�þR����҂lS���@\���ii���;Ry�c;�;Q��,�pS~�O�P@5�Keke������B�����(��w!�%���{�����i ������1���@`�y=��7��&������ءt���d�+�AӋC ���O�ƌM��� �l�!+e�4�)���w�'� :QI��z}�wN����~���˜d~�%����H[��O�a)��I C��_��_���Ht v_�>�?A��q�U��p���r� �{ �Y�#�&�J[���a~XJ0⥡��š�l=����)v\�6�ۛ_��?v>,�}��&��� eh�9$An)��@���92�����/�Q0p�)J鎅�����ԛ��������,� ����G�J]��6���"0��_��`���M�|��\����Et���X{�� ؈��c�� N� ���XL�$ �"�@���{F9:p��! �������p,8��Y o�N����p3.G�L��6���'#���NsoS�axv�a���D�M!�����u�@7�B1t��)�����p��0g���!�����"�#��?ֺm��xt�;��(���龜���̱��4v�����x|�#/���7?[s����]�C�j;n!;�\�� �ǯ����rԪ�����龁#r4����G�����Ņ~t�8Gq��}��I�=�e����:wz����yxF�l�ճw�Is��0)��v^���7 S@�c�zr�j$�y��,��ߢ�N��� �a�����V| M>���l���YоoP_eԸ��ׯU���� ����)���\Ԓ� 70 T?�WH'ȰF�m/�pX�l��\q�@��i�;��H�e|!h�R�x�Ǘ�� s�ٵ���* I�+D+���-��'��y�3~�0��j7g/���!�����.���!�˪=�#���/;��GY�Z��; ��ֿ1("�t܌ů~����g!�{s ��� _����T �|_2:��{�x�@�z@S�oL���E��������o��]^��|���ea1v���`�%����'���Ǐ���s6����U( )'��6�E�[�����|� t�|U���^�m��W��+�U����:�Ph�1)�����y�r��F|J�
+^�Yuq�@��@TǞ��V���I�.���!��O⫀}�m�YO�a�+y�ZA
+4ƘS@���p: �yI=6q~ ��8�8������v;����O 7n���M�ҝ� 5Mn� Lm2��W��a
+(\����$8y��" n%�!` � "xhLJ��h����e�Ӿ+�2���?�aP�囜�p`��릤@�ڌ���0��x�SF���/'��6�A@#u^�3��������NV&��v� �?���Hl������ᲇ ]�;(h�����U�x�n�:/�����
+y�(�8 z�*��u��zs`W�Sx^>���,�8*���@�u�]���JXz#^�-گ7 ����Yx����³���A\��`�r'��5������6*�B�{��*�Qu�ނ�ұ���B�lX"ENh��n:p��wX$�X�׭LH'�)$��k"��P {g�M9��?\�Y��77�
+8�-ɹ�N+m�F�B�M����%��Y�2��eLWC�3@��>ǐiY�uv���"�_8��֘��vu ��m8}QmX�4��Y w��}�H��������<N�#ph���A���sH~ �Ǣ]���ݿ��8�F����v�ѻOϚZ9���=�:'$��ܹV��Mh�8��T�E8
+�z��'f��a< �t��ҵ��4xj(���\TKp�B?F����%��2z���Cx^ާ�s'?<���S�w��}��w�.\�hU4��& �?iGI��(FX�'�>�G`B
+���!����v�C~��A ���Y)q})w2FAR*0��������Q�����o�=�B��R��d���g�UX+� ��tAo(U=q�g# 0�kasD
+M���^��� �}�b�x�/Q)i�������$�9;�X��y��t�R
+f���6a�����>,�`A
+�v�j|���t��<�����b��?�"*H�pJg�F�ACT�z3Ş<w1;7���rr:��ی9؍O����/�Cg2>��*+.�&�z��� @ l�8�]W녫ģ��E
+�?�Z�ʇ�*���f�Z�Kg�������rgv�)`��O�~o��O��T���z��85��x�FDk*(P�T�^ ����h��B=��X�7��� �������t�)@��� p�-���U{�,ӹ�M�s*�O��L�LGD�c�X����a�����"�=�-���>��_�%v+�_�qNǝX�u���������6<�_���Bm�e�� �2�����)+�1�6r�!���D��`ByꝓZ-�� �׬��S�'@�W��zzս)� �E�a k$q�عsDM�OE"8:vǷ�T�����^���C��M�:v{�e�t�)��-�A�v�J28z=���z�'WL� �>A^����DŽ�O�A�(���b'����+�A`����_@ }���q
+�~���vF��=89��[2�_8�����!<1,2:�s�ky,��[
+DuT������1����N�ڱM�¸��#N3�z2|�8�
+>m� �H�ʉ�B ��L���X���k�ɳ�����u����>8��g���Iw���pS�y��u�@�J��{>� �����8wh���}#yн=�M���;��v��Q�=h�{�u����������>�����js(Y����ͺ�0L���qs'���r�0PuA:����)�k"3����>ɟ@Yx}���-_��$'\�ޠ4G���*��̚����鯾q���%Ao��=�<�8 �K����j�VA����ģv� �Z�?��g/'��=n���]�+`Ǖ�w��0�����!��٤y�����ִ������6��P��:����/��8�7(�q����۹v��:�w���� �����^��9K���@�Ѥ����j�˷?2o��&-؂ߨi+�O^:p��>æV�ح���UC�:���ΏKL ����$=Ed�H�A��tG(`�\�Ɵ������je=z����
+XɂGP�.��O��Ύ�>g��(@41�f>|��x��3��J�=����t�o���$&� �7 ���j����ʔ�m��D�|2�Wdt �����`�a�{���ߠL����_~���NE ��E��]�>�a�@��;����G���!��wbɖ��ϒ���w=���}��X�gȄ��k��+(mּ���/ ���M"������6�Հ�U�ӕ�_���YO��R�(U�|�]����'���Lw
+Z��D��X�\�<�pX���1����ѦmA`��eOj1gϜ=�����H���4S�ϧ)2qq�w�)�N6>rm&uT��G�9@P��C������Q���]�s�n�41�Cq`0�~����m�h�R�Z��N�����5;Lѵ����
+��*B�`� �r�}����*��^��!�V��{��x޺�5C��i[��K�Gz}�َ�p��a2��a���Gq�7U����O,�� ���撺��$����>����T%s��?}��ݏ���|wy���\v� �Q�ym�ب�X�Q���KLq��� ���S�f�����~�9�! ���O���L����O��q��ס���S��VS�B�6n:r��]DF���l8}Q �7U���:�w�)`���c-�5���or����FFu�j�#�����\�=����k�<���͍��"��!E���>������"j�����'�枿V���O��=M��9dW��٠���e�u�+�`����>��+r� �b䣹�S��M+���;���Y��!<3�6��*��d��6!m5���;�����X+E2e�Y�4��F�0��ɉ�b[e�bi���7���v_�>�� �_��n��ؕ�B���8jQn� �i�y�5�ضe�z����$�L7��"�~�G�;B�Qz8^�����񼩒��������C��/�0�ܽ������y�|I��b�m�ZէC�t��5I-i�"$EfY���uoL��/\��n��/�XZ�t��������%�|vZC/�i��!���a�Z�J�;|~���1s��VF��òu��ev�ɛ)Y��w�)`#e ���)R����� $�S���8�8���y��Op|�W\���h� r��4��ZՐ*�^�w3�K����3M�����ǿ� Ʉ> ǞT_�i���?u+[���|R6taHT<�!DV�h�O^�P����4�s����JW�[�g��~Ǫ
+�ϜD�K�Z@�;�E�}�N_�KYv��Ҏ��e���V<qq����-ڲc%r*�@�Q4�﹅�􂁣T�w��
+�g���Q�z?� �KItw�C������؊�p�+Yy���7z����nx��5�~'���G�j7�ȳ�Z� ����9��p0u"���4BO�J?UG.������$���� |��/u�o8�����eC�=�t�A9"�}�:vL��������ߚ��#����� ���W*@���-3�s�]鱉6R(A������?c+^�;���`
+�����8�j��]�4�L�ͥu���$B����7�dk�)�����|��o�� ���D/��ů~d�&n�,�p`�O�(km�T�&m,�����j����-P��`�=t(%�5eJ��5�֥�)J9��{���柂���/�+�?4l�_Y���?�1"|��7*�Н9|d�&����?]+^Ç��Ԁ��9u�[-ڕ�IdeG�l-��[�e/�M��z�������9�_����?�l�6<n1[8�:�O�7��?�û���JD`��R�]���������s���b)*��vuլZr'l�5o�k�{��>��?4Mm���_��j'k)V`��w?J���h����� cퟮը��g�����;�c�r/�a53�.����aG�|�b� |�r\�쵷�{dN�<n�7s�̽����}W�m��^�m���n:wv����4��|A9=��k�en�j�7����ǚ�)��*�@ ��֙��6Q����G�To����������cj,�Y\��sI��w�&�fR0b����� ����&�b;І �+��X����w�lr ��D���! �������0Q'�4S>f=}|w_�M���Q����;_}k�͌$Cu��.��y3�ʙ�����S '疉��>2'/6���$�`ڐ��Ba�c���v�VW�z{_��aR�����x�8��\&#u�7��RjչL�(V�^���s���Ν �X�l��yI��$������Hk2BU�v�yڀ/�J���|t��[ ���2�ճ6��7����sY���vp��Zw��/Ş�ʡލ��������_b����? @�OLr�������J� �*@��h a�%Xu�����j�\�F�v�L��7� �Ưג6q�Ǖ�D�FR7��/i��l����X��k��"��Iϸ��2��fn�3L��FQ�d�E�8�"hH*%4Ijm�tY��"�p����s�;(����)#V<��K����$Κ�j�ۅ &�Dz�?�=�-��������]/�y�Ko�c��e^�E��G&��}�w���H�
+(���� /�E�,�(�@�:��=s�u���Fy�L��m���RZ�)�Rc~�%h2��')2�ebe�?���;y��k��O��G���埱��zE]�7m���K���އ2'N�Ź�?�������'���pԪf�Z���x�f� ��h�!��4��?��q �t�Cjp�����/�����zg����&�k�6qƌ�i��o�+�|M1������|�� ��'�]Ά��|��?��ݪ��!W=cxDD�����g�OY-߬������.�j)�w\&�z?���j������'�N#۰�k�3j�J����U�n��������{< ������$'��I}�b�k�Şyް����鋖��wZ�������������I:ۍװN$������8�;�S "}�ء����8��s����##�3f���u�`�74�xv��|L��)��l��V��Is�G�yJ�O��W�)�m�|��;�U������Bӏ��� Ғ�D�����C؛�]A�=ӵ�u����F�7d��A7\�L�ӻ�?B�U�1SX�KkN���0������W߂����7H�?b7���#<�n�,;�b���0�[�'@b� h)� c�p&{�.����_V*$�o0A� �Î��� N�u�bB� o�}���?�嗠6�ta
+��j����{
+�<�i�'�­�F
+l����2B ��O��|x��)�ƶ��qY�6�z�"�p��Bf�],cL[Z�0������[�T����aYr�n���(6>��A���
+���)�� �_��(��8��9HR}�ճv��
+V ���>���Q�G"��EI㽚�:}��r��ډ�fU���7�{{�i�G�������c������h��Q{/�O���T!��'����=M�݇���X��g/ǃo+H�v[��J��6���f�݅r��I�I]���1e���i�tU���ǟfǤ����ǽx�V�c�=�T�x�y2���o4�z�����f�����ݒ�R;z���j.� s���� �1Wao,��I�a�������2ϛz����cO�cҵ�J&���m��Or
+�^=+���7�T�)�Nudy�p��OG\L�\�W)���rv�"��O㥾�� `�W- �^�b"�<�h���S�}ϼ�@P�5�D6N��������z��,$��3��6m ��O������;� �ǔ��2����9>rscݧco#���u ��R������訴~���?����8�&��Tv�S��{P������z��jwm�L�k�N��u���=u��Ϩ���x:Hh�GhYW�Z���{K������7�I%;%�c
+@t��������S��LjJRfjx��?mA�Mjӏ2��H��ٛ��r�|���v�d%�O�DP:x.;�.�����b����yx��������1��������en;��T��_z�l��) {��Ejѓ0��k�3���.v��2+v�k<��ꘜ�����;ND~!)���̎IPD�z�Z�s�a���kv��)��p�A�N|MmP��K��?y�w��s)�#mQL�3r�dҬ}�~����\�]3�� ���g��0-Y�It�V���
+�\�� �����G���rm�a#:�v�� l����g6Kh���i��*�>��m��s q�ET�R�“Ӳ����
+{���q�`qvXx�W��;N�hZ��H�ܡ�J���X�����@��������'���$L��[3��MYn����~�˄W M� �n�� �i�(�i��އlG��`����)
+i�c�#�[��N���������=آ�[��Σ^���\��g>4QSc�1�A����Gp�;�p�*��_}S/3_��~�{��H뺔��}�Z��Y�"�_q�7����ޱ' 0H�hq��T
+
+9�<��o��g��AD��� ��&[{����?�J�S7#�Z�;�Ο3�%��ŎI���Y��:y�����b���������F�+��B��0����?����q M����Q�]&�jt�����h��>ߴ͆o�Nz��hv5jgK@4:��'k8;�GNTcD�)�_U�G�_�����=ٻG��=�ײ��E���x�r����A�Ͻ�J���U���~�z��_���܀�-��Ҷ�v�]���l�gPLW�����*�_m�G���TZ�7�j��Y�X
+�L�����g�[x��V\�AB�>�ɓ?��Skr��/�������Y`��gt���F�Ù���u�6��߾ۤ�
+d�E ����P=E�K�NR��h�x�Ml��I�����}�Ϻ�Y>�z������c���k'�|��uO[ս�)�7���Ym�5]*5�Kk�_����6I�o��S^x�4�o������1����b�?���h�y�����^�>'T�_�z�G��9�'ySW�?~!4�yb'����Tӕ�}���R�� ��|e
+����A�f�D �&�k9_˚�k��룸��W�5����tӑ���D����}�W�g~����U>��)bgL�O0�0���t-*��u���}لYfƦ�/ ��&������ٻ
+r��)�%���ϑ�������Py�m���'�O����)��O���e��| ��~}���E����ǻ������.P�5�Ϛ8g>i ťgs7���_�!���?*��.�;�����degΌ+d��B\��ѳF��uݶ#�߸�б�����[������F��["[(�+�Ĺ�p�"{�%� � �=L
+��{�0.�m�����x�^�|O
+� .��Y�Ri]������?B��]��+�?�چ�046��qMݸ�����α�sɷ m����pw[�:�s�޹�տ�z��>u����ox����Z9�h]7w;>9����O�o}�5y{oQ�����@���/�k.�G�Q������Xx��y�:��]��Ŷ�|�H����C��Dų��r9�#i]7�0�۔��>ϛz��������������_��K|`,mQ����EZ���?����q�S�L������+&1���bN��:��3 �9����������_�u�K�,�~�ќ���6sg�����\���ew?�^s�*D�����Ȧ���ؚW����ve�ej�Y����:���9u���K�Zv��s��1}�7J��D�)ӣc����ͭ]~��=wsO/�{oQ���������$|�HMsh��d9;,qIi�dxS�:z���siO�\����)�� �pN�T{��V�`��' ���U�E�}�o|���C�����>���ƷXL�SP�ޢ8��©���Y����R�b���?%�R���8�:�0����U��m��v�'��:ތ� �ŝ)+B��[�S\B�o���S�ϩ�
+�7C��=`^W\�j�����!xQV��7�*��3&P�R{F�E�"���ux��S �ﭟ6=gwf����������e~�~'���ڑ����*Q��_�Q�F≳���-6iq�rS%�J�-���ȩ� �o9���,e ���,�ei�̬��������6��e��M]��V��i�'� �!�y��Bۙ�X���*�9�X���X�|��ɷO�*�h�m�>W�/�?~M;�`�D�-g<m��f/�z�D� �P>4����FG[���y�lߕU����.�AN��d>�����U�/��(E#zchX8c{��>�h!�m����?����TFL��:Υ���R�‡LX�*�C�r��/\]u���9M-��-}�?���#�*93��zo,A��ϒ *�9�X��FYz����ciW���J�-������_���C����D��"��1e�65���G��y6v�^���#}�#��W�1�uŌ��flYI����H�OH��FY��>ao�VYF 1�hC��v�_�g� œ���Ss�6����1_��a���������^���IG]��M×?�̎��i����ޛMpg?&�����4b���R���h!�m���dl�V<����7��L>������v�[�����?�������bWYꘜz2}���24f�]2#�z�����JԨ�_�Q�vV��{�_��h �s2��4��5�-ꑗ����G��r�͟v�t�5yL�K:ۥ� ����;2z��:0�z�M��u�?*Q:�X��.���������c67�4˧ ��[n�i�����S?���;��S$o4}�c�{O��$�2j" �FHLd�̓�X�ʇ$�V)�����]2,14+&�pIT�N��%2&�"�C]��7��|��|�D���Փ6G�閄�xDFf����a| �V#�T��I�
+�w�_���/��/�B50�%�Ogg�RFNQC��W,���ӾW~����5v�x��2����5����Xv�,��yX6u�X��e(�I��1m��:~&��U�,��u��~�r�W�|^*[G;)���N�����Pځ�&��n{�3 ����� \{PXSv�Xr�5iV2�I����'s0�S S;��D�b������?�&a��$����QY�嗏X����f�̥qw>�4�%Ɯ-;V�y��fJdƢ=[�.�>�7����C��]�F�j52; ������M��h��)�V��O���n��Y�O�g�e~�:,��޷%j�����|���� O:�Q���߱��Ѵ( �����#��&���;�;�$�:~F J'�������DDEφ�Z�N���Yؾq����24��� ��� SIq��Ss@Ҹ�*�q����8%ɛz)���
+k�����_��m`~�O�0�ҳ�aBO�=,!p �1|�W������̈́S�j�+��jL�S����������E�mL@5X���`4��V����)�;�LbLJ%gxJ~��o֑�X����fZO�'�Q8�5(�T�C�?"p��oo��:p�Y��� �����+�Gߠq�S���6!`��9:=��m��_m��$o�V<�C@A8V�����ɬ]Z��L}����?S���?�� ��������k���]h���o����t2�_+#� &����Ճ��)$9��i�&��R�����v7E�N�>c�[//�I�v��Ҁ� 
+��qh[�����i��1�
+}�����\W<�C�JZkc�I����� ��U'��Y2�>��[gSSIAq�!�OXKS�5N/���<oꥠ��j��w@F�E��|e�����$��IKRc��e�(c�����N*�q����W�!j<m��q ������2�?�����MM*� ڦ��0g�)�t�txu3
+3c�F�֬]���M1�X��C> I���~+����Ht�xf������2�p�_�\��<�7��L��V��o�7�ݎ���r'҆L�ZK%�v}���N��^
+־�~Ϩ��
+K�-��y��_1#��-`8�f>#�lk�����o0�,�v,j����t&��)O�'o�Nv��9˷����(�����5E�N�����mK�Cd���a�N��o[�'Jƣ��vZ�U={����NN��{�^�C���?4�o>�4���rB��X�r��B;$y�e�IB�č��e�ͯ�o֞E��SUx�X�䥉�~~��U��W=̝�Gg�.���;�#���5�iRWZ���dQ�.�,Z�N׊�������Yf�#������X�5�2��KbL�e$��z�RU��O\�X��]���ިe��_P�K�_+������˳�?_����n�z������z���od<�o�����]���;9�PqVg/P�s����d��C/�F/�
+���v����{�RN*g��_ݱ�h��5��Ǧd{x�}�Ɖiy=�u`�Y�}��^���;Ϛb�a�u�Ɵ��v�zp��{-� �o�v�h�R�]�^Mqf�qs�p�";c+�S���f�~!��/�A8/�G
+Q��d���؅�O[�R��b���䰥��2��0H�B��Յ5 � SU��?����m�o��+ּת|�_X���0�L�yA��%��\s̠�?%����VeY��4��N�����;|��8�gP��q��Z��a�/���e��3$2���/8���-/�w75�=G�d����Q�ܴ���~����<}����}�M�;��Tz���V����U�t��f:��D�W-��RT���3��9�;+�C�̷��?e�<knP4�֦m�`L��֙�ko���Kϡ99��3;b�C�������zǧ�F%�{��6~QjJ^��uO_BT��^�Ǥ������E�6���������k��NYbg,M���*y?��O�fnP4��u5m�T�h\�����'����ȕ� _� \@�� �^<`d,mK�ʯHL������7�LQV���Q�T�� ]}�4P\Z��}�mddle� �wV��$#�;������0(�_�mBs���D#���X�p��o+U�� =*g<����(H�G��6�;ci�������s����!��{#c�
+��Ǵ�=�as{��*E�*�#��B��@��Qʼ���O2�����;%�O��� ��)(��{Z��*�!�Yz�]_M�V���*V���Ci�C�(I6  ����������A-�ˆ�>�H�Qd.�_��>o]1K)�V����{`GbT X h�-{3�����o���ڞ�(�������y{��?s�›�����^d���ȰU�Ns��r���U�m���o��$��;9�GS�!�����y�;�o�m�5���Ң=����# _��\���� ��R|N-G��~�L�p�9<�m�� ��%�����<o�X���~��g%)���K��ᘹ����uT*�I~��L] ��$��sHB�1��WXx[�<����' ��zT��bS����;�]�M�c4��>c/�MV[���J<v�N746����\�����������Y�i�#(�;����M�ݦ�t�s6!s��
+�g�b)=�]�E9S�73�.��>���T���9���ײ���qM����>��r�7sTd�S��/�t�V��w�i�����LW� ��'��f�R�}�A��_��v���78�eǖe�F�\c��s�����~[{���{l&y8D5�@U�G�u_&`%i��F��T�w���X��-;L�c*=>)���YKW�*�h�J�/_��WV���f�+� '��ᇧ�%w�3lK�ů5`T��S�?k�/Z@��a����ȗ����=c ��?دv�p�w���/5ʖfGN��R����{�_6S��K�-e)\���K�h �U��i�%�}�8��jY��V�.��Á��փl}a~@dRLf��n���GL�bx���ڿ8"\ "*��yx���#��̦6���|�,Y��NSli&�� W��C,B;y�B3��������음*������A~��ǯ�1��-�4Y#f_0�����'F[ y����;|$�`H�j���2My ������9���%�{k��<��^W*��i�8���x�������Q,���۳���߮��a���?�������;�������b��ѷ�����axb���������M�+��{�^� ��6_n�f�4r)k(m @��?�H9�K��o��4�GJ���K������R9<�xo��'��_�v�cM��լ]U�E�0�� ��B�9B�oݗP��1�5'�2r��lV���/�Ӵ1:w���~��?LQ%K:X�YB�ƅk��a�'�����b*��>JlѲq�p��w؈3���ͤ+��K/���lX�'�a��݂��O�}7���1��u�k>!1������}�9�Q��è�ES��^�РC��^=�>��arG��x ���a�pن���#A��
+ )����� A�kv�-�� \ �J��v`�7>=c�'�/��7콧�Gy\b6�[gf��6��?e/�LN|>`o���WBrJhXxZz�� ��=�[�_R��w�����}�kȷ-t��9l~˷I�[ ���k�d�A���kҼ]xJ~d��X�C>�T4�e��� �9b �ݱ"���/_y�z�Lh練��A;4���������h�O�F깙<$��+��57�v�/i�;����<%��Ue��lo��ĪA�:������Ei4�ĎC�<���{,r� ���Na!��bE�[��$w~L���վz7�3�(���S����A��7���?!��$t&��B��Kf?��|N};|�ܢ �gY}��
+��M�剋�#�^��B�O�5͹� A�<��w��/����Dx� /ȋA��_b�#6����nh=Ä� %(&��`��ٯI�Ma�ψ�N$@�Ad�(�n���C�l���C9����w�>ng�K����� �»ȿd���x#ol.����V05�I ���!��0 0S��轈� \��g��ߐ�� �Gl;���|y�;(�o�����_��DǠ ��?n�+7�G��S$s�̽�$��#H����� Dn P��<t[O��P/.��G�(�� �kX���cA���(�+ �y�|��)�tt{H��"�=|X�I¨�����Y��M7��^i��3��S��6q����]�����W@�3�� �~����J=6��|� n�(G������ur���[�M`�N�)�#��D����AG��M�[���ɜ#�����;���`�׵���������*҃ ���+v���՛>����v_�f͖32�Z8�^$�}���h˙�(VW�,Ow�<�dα @w����?������2j�}��ի�@볥�=�/βc�$�y��u���o��-��0{�� ���[ɽ�z?��Oz�2y�n��fW�<o���jQ:Nf,HH�,6̜����b�"�It�R���A�wo�e���g���T����{��
+�K�����F��5MS��5����g)a�5���>1&z��d�,���3]��+ ��u�ӗ}���){jgu��w��6|�$���n&Ŷ�d�zBi��q�V�?�k��O������_ױ�"'�y����C����c}���'.�HXq%�ϯk��X�C��w${���/�w��y�j���NC���Nn�(N�W:�Y��B�Ԣt�ֽ�!0v���I�2%uF� �x�J�ȥJ��D�;9�p������U��4x�"��2�cU)�}�y��_��=��ʛ`꫄��g�h���M��Y4z�~{�Kn:U���K߀�j�4z�4�}�n���Nd�_ ���IE���j�GFs�J��S��`�}\<�U �����k�
+��_W�t���2����ŷvU�=nU�����v]�>N��g���w�;�5hڭ1G{򇁼O�[�0����)�r�������Ά/��h_�Sz�t�,
+@��j�^�hM� �@�=^G��O�3ۑ�0x�8nw�vE�֯�kHtS�<����iJ����4+� �����#ȗ~�?���� mH��<�+ ���rz+�D�B�-t~��5|(��/���VA<�㓶���|�7��m�\��~8�5Z�o�ꉇ�~!8$�5�@�8��J�y��?o�����ߑ�cc���5���A���pP�]�^eG�d���k"��d�W9o!}E Li�o�|��o�R�?�ɷ�{+#�l��EO�s򓫿���Ue +;����@�[�1��v,Y��2{�p��"��I������-��h[y�" ���o���<�T�HD�(`���I@��b��!�)2�r-,>��"����^E�|�~�Ė<��0�g�_�S�^4��I%)��H�j�q�Td��`��ȷZ� ��gXr��5)� I�u<>J�SC���}�E��� �(��(E9|�C��w�m����߭��^�<��ܼ��8���V�O��!<㻷*��R�Ryz�8��i�u�8�i�9d�� � �����U�S���s���M�O_.��o��3V�T�J����e���N�{HBd*C*E���A J��#
+MQ��c,�d�Ӱ>f���#�΋xF Bi��jԯa��.�����Q���O�X����n�׸B��z��<�S�@�#g�fF��l�ҏ�]��\4�|�v�7 .��*� � ���,���e �u�2r��O���JNUQ�l�6�O�}^�“�.*K�{���;ͣ��D"8S&����=���k6PWLF7�2T}�h�7��'�A��XS�.*�w�&�S���N`O���$�"Ь���2��� ���և�Glw�^h2����:��eW�He*ּ�4�gc�Z��!���� NG!X�n�O��4���#���=$��4����M��yD4�m������2����
+�����H�������[��B�����g!p��}rtz��|�eˬ]V���
+5���SL9�����σ��t�#��E �N�`�%��򼯸G <�Bk^�\&�����e<F%�7H��I��� /Xw����ХQ4����%:�(C�V�r��=ؿI��c_��
+@��}ɖ�|w�G���Ǐ�$ܞ6lR�b 灱�R?Z ��2 ��5&�̥�Y헅�)!�?{�xj{��4`����hJ$kP��tͩsr��+׺��I{Y�[�Q��_�T>���'���Yq��걉���M��=�e _R�]�|x�N�^���X"?'~�����ф�#.$�ٺ��9��qw?�����6
+Qy]��$��sro�h$x�����"��6� �9���[��t�/,���D^k!��u��
+F�^4_�uo�<e�'��O�O|ӪK��bʼn�@擿b$��ɟӽ�ᕠx�G���iw���W��~������F_�*���R ��#�׽ZӴ�M��E��&��T\Fۺ�ʼn"x��f�����%���Xې��Q�+ ��Y�R/_f�R�'g�^�yw�f�2��8�rW����������PȌG_ž���w}č05W.�8�}e���h4���Ep���W����C_9���zTߠ�^>����mg���9�,�榕JW�_s�2�*462������o��b���>M�#o��j�F�Jh��; ;|�lͬ���h�^�n��n�Z~t=�$�����]=@;���GК��"��֢t��4�1�ᏺOz���;-"] nͺ����l�O0�!0"jٛ�)8����w��ҋ��I�r%?g�h3ZƲ �SE ��?{��.g&=�C_�\'2�G��)�%���M]���O|�}�i��'L��� �N���!+����Sܬ%nT��W��>/ۙ�͹c����җ��ov"��;��C��%[{I��_h��S��M��B���%QQ���v��>�#=��:���͎!�W l�qOP�E���^c�=���B8�v�ڤ��]��$�����i��ۗ|޺/W�9��(g�VSt'� �uC�轰�Si�o�'��h݀�����!w!q�Tム�a���K}f]~L��Wm��.q�L�_�>�[�V����>�e��f�9A|�un�o�٪� y3��{.�d��?���M���ݧ�O�8ז�g�]d���C�M"��C�0L"2���{�2 M�Έ�ޫ�]�����ܵ^O�-��%�Y>��'�-�F���;^�Ͱ��^�r�ˌ�Zv�L�|�& R�gw�7��ֲ;�8q�e���X��\�A5S���ȁ.� 2�)�)�����#:o�@}7�"|�r/?�J �k�{��W�(�3C���Y����xF4�j��uk7�}�F��}�I�Ch񩅽�r��{ ��N���H��I����.��Vx�U�)������s���DƈV�Jh�u��J~�&�6��Z�����_�k�o?dcLfw���I��F�i��u�6��76��2T��<P$YB�]�B��?��4�P9�C�
+L�j��u����\�8�CD�K]���&-$��r�:�������R��N���%Tm��`���cC�35��� ���)���>҄��n���$�;�3�R���.�p�;:���E�������V/d>=��&;rwx�⺞�qҢ����ݱG ^��2�����\+4!�fAX<|���N��|�Χ᧭��ײ�.��&�� �(�����`�BdR�E/�%�H�;�^�C�5e g���]�}�����{�<�%����3Q+X7��+{vr��f�ohtwo��Zu�$�:�ox2��&�i��"έ�w���%\��|��꿦�N�B/�o��U�
+H�]��y���VY�ۈ��r�������6�দj�i9֮��X}{�i=�G���,���uo�M��=�}« I��,��;��"�_VG�u��s�P(�ʰ �{ᖅ] �Ǣzצ�וU�A��������5���}�R��� >��V�Y2�I�bl����݂q� z;����S���i��m�8����3?r���4nJ�UG@#�+k�b\C1�;X~M��6b�ll�jC�3��r�|n���y�ȜN��Q_BJw��aY��r��ۄ�2Y�V��[����OJ�<�;|����U7k���χ��wiB�]���N �_�n\�_��ʇb@�9��*���b (q4k�����ɥ��,Xu-WZ�i��-�,����*�;a���\Glv� ٛ�h�&�;�T2�,I�8$�E�OH�C���Ķ����>�Æ�nZ�s+��w5i\m+nRl���m��ǘ�LW�~:w���Kv}�o�bf�k �_y��xEE�P�x�]�.�Z�Y3�?� "3�$���7�+�?��z,{�h�C�#���^��ydlvyh󶾡MU��C��B��rݐn�9 ���3�MB!�"�u�
+�z��d� �M*U���&?r����\S�W���}W�����D�|�|� 8~�ŀ�
+(��C�"` L�X��"�`��0mj�Im��B�o�c�w�r?����_��o���C�rS�vD���f���>Z<� �
+'܋�0.�S�{��±m+#�:C���
+ �z�r�R�R�p-}m�<��o�3?f��%����:A>{n��x�D�>P�����B�V����f��_��팕�| = �˷��<���8ٶfFz6k<!:��Û������O7�~Y�oX�O?�����1���O[�bLE�9b�� Ԃ#]M;h������D{/�r�/�?���f�+����~<,!J�8����yGm����)����Iob���L��~���\�<Gοۥ�$ Ϣ\Ʀ@�!c6��h���5��%��U����Y��ɐTNѺ��h�6��-�iP�m�x?������.����;��+�ް-JN�t�H��! 6�wQ-�,p�Ǘdr�}޾�^�SA�m9?��~�KMZ���4ވP��?X9��?�=,�� (c�~"� w/�j��Jei�0e@MH�
+`���e7 d�"_��F��5����o���֜<k�4N�՞��W�pm��� �?������e����yBE_>�C�/�>�m �6Mp3���t�{ܧ[v�ó���[��|�;d���Y|Õ�E`[>�/�޵|�3Ǩ|k'��Ϲ�>,� ~Di�J�_t3�Q�$����ƥnր���a5ܽu]�e�n�S<�^_���n�QMdk���x�*���z�x�}I-+% �#/����{�}�7;!v�Հ��mXxAa_�u�x�i}� �� ���d����V�K�P�䩼kޣu�4͂�}���J���g~��2G�O~�l:ۿ���J�u��e>+�9|��A������VW�σP��ϫ��{�{��/��e�C��%*M��F�rf�{�!���TJ���x���h�r���w����s��o��G5ъ*8�NWcw��eF=&���76�U�0@��>��}[���VT_���.��8�������>�z�~;u���Lኧ�\��@�n)$��ƉM_H� m�\�l��3>���������Y~L��(n�����2^� &u��i����ܲ���'d+�o��w�M�}5ܢ�s�z��)\��7kn��J��J\2���0=6KP0�Lܴ��+.��,�RѾd���ݮ�� ���?�e�#,H�
+�q$Y��h�Ҟ���Z�޷*���v~���µ�_���� ��a���Ћ�GM�o���r����{�l���C��88���D�rK��v]�|D-�����F$+hW�K���4�-9�F��x�4���(�`l&*j&fU�+;}�C/r;��+�헯m�|1�\�>�;u �@�}_�&oَ�.�:o�/��Uxrk�O�k_��e��M��!)�h=4M�ܒ�!Qі-��?@��R���;�n�0�ؒΖ!�����'��� �\�x �X\zv�S��x�gW� v_�m��W�m�t}�z�k��/��7˚��^�sG��x}i���#��/�;��&UQ�W�e�5zl��ԟ,���K��7�B{�0��>����%󡍯��_e�ҝ{j���[���]��.����J�C!Z�6Z&�$��k;ku׻����9eɜ��a���ꉓ�k�� ��[����J��o1e>����U]�]�Q�v��%��X|B�������DM\�V�n�w�������úq/�9�7� f��-_��HU���+��� Z_/A��7�'3���)��fy*j0�A������w�E����ȫ�$���-���/��|X����ӆM�T' .Q1'�l/h$�5g�ܠ]�[1��� �%w1� >�ƿ���n��6�5������i"��-��[Rg(Cj���]����~���ݢf͟9������&I�r��mo9n���tw���<K�m��jT.�!_7�Y8=s0�7�1�L�zܔ>�º�x~��.X��&�T��cl4C�$��#ʇ�g`H`BrxV�vr�0�Y����1a~�9k��t;$6���y����_��������+>1ZO���W5w��/k��@�umW�$��.ח�[��ְZ�� ¤�����6\��"FgO�,�iT�Pe� qp��������z��?��8�,����Y����L���{�_s5�9� Tٝ��-�n�N�3J/�W)D�F�R2�o��#�_��f�����1N��G�����po`~��y4e�����>�2�:���a&���k�֦Z���z& ��E8��1����n/�@�Q�ꟈM�\f��a�m���EH�CTY�:T�`0.����e���q�y�yA����j�be�����b����/�? ���~��Z�A�p:Bx�88h��׳��M�8�e�O��78�nt� 2��h�&��T���� ��������l�[�֩�$����GJ� �G�!j���]�t�g�u:Ζ��,��z@�Љ)���6�Cݠ��rF�g�sh4�}*V�2J�b�o�FP�)9�l��u���� !>L5-�ȶ��t�S�|�L� ��Y@z�m]�TG ���r,b%�PS�E��ȤNS�7��b���V*��y�V���l?F
+KUKW�Jh*�� )���ΚL5n��\�*q@���� %�� ���� �q�����Y��N��� �?Tl�"|'���:j�W�' ��e�.07S |aS�`�5Ts�9�b�囩�D���P���XB;D�� >r�� U�۷ز0�M)]��3�_������c(��q�]�Tl�`�֤���ھ]�ڇ���<7v4.��`�E9A�6��ě��N@�NB����m�Q�v���nZ]B~��ުO���s@m�[T�wD�9�!���� ��t�*�}�B�������Z�tpz樬k��=�tn��4a���̶>��׾����,�}� ��m�z\��������yX�h:}��������0�J*���=�Yj|0�*h���w� &n~/MX�=~e@�Ӽ` ����u`:� ���B
+<��m��n���F *�5��������|�w��E�"Z�J����ÝZ|�[Vx���٭��6�C&>���[�G��<A��Y��8�Fh-{���-JƖ�<�xIOJ�����Ri����o1��W�)6�1�a��3�J�} ��QYz‡�jI;���͏
+�)�5�g�C�t[uP�?|xfS�uma�;���T�lǭ�x�ӄ�`�Jj��X5�?�9t{�6|L�yS��[��z�ʲ���V�S*^*�N�/z��+p�p �:���Y����=��7 g��>��}5K��%����'r�o� �Ӗ-�6�n�#�_���a�1݈�����+����-��>f�5gU�B��V]
+���r��s� �W�}�X H�&Rh2$��E]�HE ����U�^�0M� ���z y�r�9�#p ?�{���mh8��c4(��� �~��V�L��O�p}���LMB!\��e�s�Hm��M��,!�ʨ'!_ҍy�O'�����M1ホw��/��������U1A��]��M�:h�3`]��^J.�$�n��ش�� �9��-��e�� nItc�;��OKp〖u���oD��Gc ��[�� Fn�GR���]Q8�`�-_��p9W�;^?�.��M�Aqޱ�b-�0���]�Ɛ�&dg�[Y��#9��x���^������H�E���K��C��ꪀh?,)'�f�|�F�7d��Bc�Y$6.��D� �͈����W����UG�M���)����U'H��Tf��������o�*�����^�3U��*٣J���Te����;|����A9��ͷ�}]u$���U�,�]�Ϟ����x鷯)jÊ$<!q��'w��[� �����Y����گb��.}]�� � 5]�[T����Q�����O��_�y*��U��6����*��,� �� �̡zS)�7����zM�V5z���r}�qp�|���MGof���M��$�&nP�Ep�6IE�;��Y�J��'�����K������A�!k-:��
+�t���C��`�� ؗ�� ���P�����\8� (��'�ת|fT�/e���H5��w`�s!ہ�~���j���� �7֞v�#���E���a����XLb��Foo[������
+��}��9D
+O�f�D�6���7�;�˨�|������ �� ��N�
+�܂�wYYcSA�GQ����;b1i�h�U{�>9���5)=��Y�G
+Ҭ]U�[ʝ(!
+��=���/��r-A��s�;��n]1�iV�D�Q�<� �o�ճu�l��+ּ�, ۰4����`���6��P�3?L���y:�qQϭz�tI�RP3�(p���;��xj�-՛>/��\�Q;[Ǔ˩�R��O��{��>O���
+O�K�Ц׼�����T���0�6�?����OdVC���D}�TW�<,������" Z�+���꽱ٗ�M�����כ���ޡmxh41ݺ.xQ�`7s;쏊�>�~�F�4���E�(���Mg�� �@����Oh�����:���d�S�6�eT3 ˿T��T�ұ�)�C,0�e��9����:$���?J�es�}z��Ml1 �V�<�O�D�3l����1_>t5�+||�D�ۉ��F��/ɧ�����X�iC�� Z�M��P٪splk�x"�M��C�ńz����*��n�zp��cs�+���gS_j؏��$��ٻ�Usj����S������;�s`F���"3�n�1)@m��" fS�n|c�C�ģ��k���Vh�*�/y؂�b�V��8��j�`9Z���.3-wv�3k���!�����>1��������V�S’��/Q���w���~AM�’;D��
+�4-�x�^����ujA�x��n�_���~̬��-@a=w/���>H�Hmy��H5�������T�Yl+����~W��) ����V��Y@��\�b>4Y
+l���(���2nZw�����U�Xv���`�$���}� m(�R��cm�¢�Yu���S���(��,�d��M���D����Z�;d"�rJ��\iAds�U�ص`hL��a�%�lVB�/B]�I�m��i%�1� Y�u{Hc_dvcR{3�n��*�}��d����Jm�Ie�x� :�"�Gz��O�F����@�þՎ��$(�z��O��!�5L]�vT��/�FF^����U��Il攙�Q��[��H `���p�S]��[��pt�>1e��8��#�̍@,`�>���vS)�k�#ƒE6u� � ��ۢU�N�K#D��*��?��-gL�h������&vŽ@�轌Ŋl�"��
+u�
+�%����vX9ö�\�.�`9��\m(���C71u[��e؟�g�bE&���:���VğR��^>��`,�~�f�5��{���g����4�8�`���[9r�ڰ +f�� ���i�� ��<��=�:�w�d�wq�g�� �-û� �7���혐m��� ���i�S���%g��n�Op��ޅ�=��~�S`�4q�J�4��gL i�2a+E�g|A�v��Q_��3p�4c��}ga��"�E�8�DfJѻ�r:N<�.a��� ~��b�*t�R�q����s]z����k#�p�ـ�����ġX�E�.�=f�{M����Ap�J%�L�2@�*T�x�fF\�Fn+Xti�=�����<_v���D&a�Ѣdl��gIe�S���X�9���cBA�^q�"&O�4 "\x\gh����v8�B�3�JD��8�C���M}Ȇ8 T(<{3VUdS��Lk��A���k�@�*be뢡o�'Q�7{˲ �d¶z-�J�#����<��Js��' �s&AD H�A� �H��"E���`ŕDY�$�dK�l�A�V �(Y'�K������z�w�w�ἶ�t�p�0�i��t�tx��#;TWW�U����{��?�RH�f�~�hJ ��^5H���}/"�+����/2.��ռ�{���;@�k���S�D7�ǃ�xe�hP�x<����K����L2�C�1�4?�$�7����U���.��TE
+$(��=�B�����FbA��쥼�-셤�2"P1�����nZƊ-k��>�^ ��T��^2! ����C9�������4b�-��KH)eD ��4,��?$����')�o%n/`���W��J KEWD �Z����AD��A���jU�$3��d��xP��?�K�O2k�bX�� ��B�#�� ��ʨ���+"�L*����,.P��"������r:&0GL[��\���?y�����7čJ���ox���0|9� U���!CP)�3����b���B\xy�?��?e��}��F�_zb��m���L�\5c����*�I�;�2U_��b3�w� ��x�S4�Z��m��[�"�X�����Nr#`6��V�1�Y�|����)mmnl��7=^G�� �._͔^�߫@2g|:,��*�[@8��NX
+(|ܯ�٧]F�ᦑ�A� ���H2|ԎߑU�.$:%pl@UHa�Y���
+t͐���`��L)A�b>��;����7(�0�Mm�**�1 �MIV~ʈ�����6���=��l0,>����IQ����{�I��Ek�����j8/]�������QCՍV��(/C�a�7�۶�%^����"����ʗ��(�m?_�6�4P߄��SJ�8�_�@ ���,y�k��4� J=\���p����.�dEiԏH���?�A��7C#�N^���z-���2B�^5(X0��_PJ������~�F%dA����\ϣH�u�ڿ�h��}&� џ
+�m!p��;�>�p�4�#�7���lk �q*���� ��Q2�@t98������[>dݔ���$?�z:��tkz���oA��3�#�E��
+%���g� ��5��:! �@��si�]���WA^B�"�9�-��{O�?���̥��BX�`��$�U�y�J ���t�p#�P����c � �m�󦏮J��!`6-?���%����<`Cy�S����L!��nIt`D��X����,�(�2��c2����|���h��2E�A� ��?���^�2L�ĜQ+Q����#�
+WN���c�өq8{ ����Qa*!Ϟ��9W�m����{[�_��QJ+�@\�i}0��.���e����~ �����5ҡ���=2��� �u�6߉0"ƕ{R�pj=p1��̂5n�oR���y��_�[��7J�[x��������٧�vuթ��r��o|_͢2c}�B�����r���+<A�n� � �vQ�̩��������������!̦�A��@�C�D�!�-��)����㺌_���D�./��'�]5�z�~�}K��$�U���?o����g��.�-Y/�[��q��`
+��'L���?�0Gg,,�+��g� ҽJ('(�!"w>D�>&�5'ީ�9��E1r~sV=��e���ES(��
+ @�{��&�-���A�w��rR"�ǟ�>j�!p�cK��&�r�[�#��uɺ�;�}U��P��8���5b2+� �v����Y���C���A���@d����`���t%�����:Ǝ�֞����2�mV 4&%�aڃ�[>2��VeA�Z��lNӆ�����(���T`^��p6g7�[ C��5g�0 `�?90s���G��[�m�N�ex�������O)XP[BX����<_7qOn�ƈ�<9�$C�f��k���|3w��-Cn���.
+ڟu�): ���SDJ�X �Nj�?��9�ʏ��N��<���� ,1
+�=#�*���{s�7���(uS��ݕ��pG�r��Es��э@�q��yZ�Y_���Fs�Z�ngP�WY����I�j�#<�R+:���n����3�V� g(D�j�|�d�U)e��547\� ��;���z5[�e@.�a�{;��G���n�H~׫�# )1͹-j(�� S�u�����2�C�g��G�F���Y�6�|w�:�z?���s��&p�џ��MY�2��Y���*{% �8�X~��s��������u��C�q��ʡc-{��C�2���`dB`eP�U >�iRi8u����i��C������W�z���2��T>l3���5�ae�*��+�]����pK7��j�ΰ�v�l���o����iף/5x��bS�������?o��L��iPs����H���>�:��X��LL�<t�+�Pf��[�!�`j�'��)2u�+�DN,MSbF�k%6��eյ��9 (}�`$�N�>h._��l./�y$�5��"���v�LYߡ��͐�ÇBLn�����o��z������$y�(C?@8��[��Z��㽔T̖�D��~=�������KP�E�IvHt2�H�B L�D�Q3v
+�0˧ϭ8�<��zN� � ?���٧���x��9��f�dy�����0���P���\k�rz���mk(>?�N ��}�5�
+���4�\'w�i�@g��ji�C�����e_������w\Ɯ\�ϛ5�.����B����A��Q��%4����3] la1��0�h�*`�Ɠ��u����W�ݿ�SjY��mոx�螻u$�
+�e����F�%b����\ڏ�Z�����W�?ѣ�<r�c"y���D��jj9"�C��[�;����
+V��xq�>n��_�4�@�x�(�"`�J�j�򛟓�G]�d߻D�x�r��E���K)���w�1 ����>���%sR�d+�9��s"h���@Ѷ ���q�\�$�ER��G�۾�9���6�ϗ�k�����?LU�Քe��L'�g1��k�Q�Y�z���ЃR"`�� �#�jm�D���9���ۤ,3�8ޜ���vӽL�̟�J�����B����|�4�3K���L�&09?%8 <m�H���3W�AZ]��@��>��n�8����Ҽ:,�+����u��93�g�����]�E�>��(���\���OF��R�q�U�Q�S��#�o�ͭ_�+�G����3\i���:�@^��"��e������'⛞m:pr�D+N7���ڿ�s���e�ƒ绲�"��<O�3����,�\�}\�X��-�,����8t����p%=frT[�
+��
+�-+;e�D�b�����J4
+�a/aym�X(�=���%7�%c�X��^��b3��5���M�mb��'��n��I��g�lk9�|���Z���$�5���
+�g��S��}\>��@pj�)���acA���8��[�6��"��&]?s�M:�S�*Rf� �a�xA`��{k�P`o�+^��#�xY*i�L-VsR �dD��8���s2���aN_j�֐�������Sn�7T�,QBθ|S�&�!yM)CY0s֙��<~�C�ZzN¶�iMD�Dq����)�\�r�&����JД�?��?v�Q�q ��)��������u�O�U0M 5���o4�|���mI�8�K)=f�c<�K�*+Dsd2ɐy���Qi�� �.��!H���C15>K�O���l$��y�&�Ƀ���;�u� ]S�d�Ȣ�����"��@���Y`��9��������G�V���)���b��9�g959m�w����P��v.΁C��n5YI ��΋f�&��x���ӓ����d�y-�珀�� �Q�l�N�`[���q�t\�5NAH:���rsx���B�̉E����MSNκ����[g��N[|�%�U?lB$�+X�]����Y^��vV,*��J�z^y,��Z��|��#'���}��6~��4$y|z���������u?x �3�5�͙u�!uڢ��J�)��#ҩ�I,����o���l�
+&��������G�1
+ ����ޠ�_��X��Eb" ��F��e����B�d;c���|�%=�A�r��ty��?����O���A�5�հ��M�xD_<��u��]?�T�R�����SP�~.��:���+�u��+O͞W��L�9`@��r�X�����>�΀N��-6�[��(��%�����*xY�#ܕ� p� �57���_'A�޲�"����qc�RaI���NU���Yj%���÷��w�����/�����,O�rCqgF�7a@�Ԃ�\��Z#w�1��O�?�m��ܹ�U�,��(����,�W��P�^f�>������K�ծ���n��EzK�������������w�|/#�`@�.�0�Qr[��c,����<Py ?�v����Pk+���$�]��ƙ/ ɢ��,��T���H9ؤ�3�@������Z�(7<,���V�� .�Z}�� ?�U��Bd7ħkѪ݃w~�!�qJ�����U� ���|_E��,�澠x��� �K������/�d(����!�w�e ֫�Ua�f�[�u���]�������Y(�]W .��dE*���>.jI S�;�KG@X��VMK�]��l2��@#�~��� }h~׏`" ��J�����@/���%�]=y�#�:V^�/0 `z�3+#��#������s���e�J���Ab���jh�ay�Ψp�";�} �S�׀�@��4�{��w�2��v��+�A�6��R��`������ ���5����@tHA; ʺmP)��H�����S�XSr�?��$6����E%����� �A��,/��-e�re���g�x.~��8j��Htz��L�>��(��k���5���
+a������{.�\�g�9���Q��U�g�d��F���3#A��"�����
+�h�+���M�g�E���U,�|�`��MF�~��sV�yΊ��B�� �G���(O ̑)����5�g� ��I �����` v���/{�ÝRJ��h��A���_�o�O9!��CM��ċ�7~Ӻ�}�:����j��f�˩i�|X��7��j���N��1)|�;�ݾt�<����k�����F� ��1�f;iӖMX�nr~ �y�?yȸN�h2�ڍ=s�08�Nc2հ��lVX����{����m��.�Cت�55ܳ��\A$������������`�E��eN�p~#��s�g"~��{�����������NeNr�bf�������mO�5?'�=�2���H�P���B�����$H(�]í�ԅ�5B��%)�r�� ����`�q�3�-��|[[��`E�F�H!�������9���U�P��5OhlZy����|�!�95��GLƿ٦j���Kd{q�l=�2fB@r���kM�������J����'���S*�q��0� �6���g���85KrPX ��7�/����•-�\�v�ኺ0g!\/b{�3p��9pkZ����'�������A�?��W��ǣHؘF�aw��AP�I�� 8��z�'d�vAx��-�r%n &W���/}�sA��5\9H�q^�q�\���\�;�U���2���b�5�xt�� "��/K����<���2]��"�����=���-\��/P�e4B��@3ض�Yw?����=-��ӕ��sK����t�P�hWL���5�`��㠒���ӟ
+�?HE���f7� �z_3���b�W[��Y���'H]�^;��{lb0bՇ��#*q^��D�@�g֮� ��]�r���-�k��y��kNV�OR�*�K��G=V�0�j~��W�rPf3h��;��Ax�D�rw��-��_��!cU{����F-P��������U��H)k�m!Fm�����5c�֜xgn�X��^T RP���(��B2�T�0W��w  U��C�V<r�M-`Q9��otF>�� 5x�/ݭ��������iD평� v �H
+�T���+1���y걢����ep.V����*|�%�חt���;>��pj;֥������\���Oo�Ӛg���leP���+F��l��vy����0� �X�И�v`��~Pvr�v �c]���Չj��e��'(I���Sm�����G0"B�?X����D����<�Ȅ�%�W�t�%ҖG3��T�>)�Cƪ��[d�)����忇`���Ӂ��*Ŷ����'�����hAYOu&��<�g�Y�/,&,�uvC�HO��Cz �� 6���]�3���?&s�5$�Ѝ���pċͪ�\6־��{Vy .H��TO����hI폹���}z�A���?{�iף�ս�1���Ȱ���ʮ�`��Vb�a�m���o-�؝V��Z�;��@��!�ҫz`�_��vh��N�ږ�cH�ֳ�K:ѯл"s��5���I��Ԓ���!�� &���^������`��%G�),.�r���3���+F����o|�#�n,!j`z�=ޮ�/V�gBu#L��sG���= kL�/A96��*?������&5���Ӎ�ל����'�l�U�?�! N���9څ�b ���7TU%�����W`�X���� ����`����� �0�a�* �Ȼf���
+^���L��Ȫ[�ߺ�.��i�� �����u���;���0=Tx|f�����$���1v��\�P���+�j��S���1xW�;��>����T���X��x���SD-����������`����#|u���.��G֜|ϕ�^U�- �҈��E{WRI�@&^o�xx�l՟���9*� ����+�Bx�ck�B��u����%(,_kFOP�����{E�z�f���P�9���{�<cΪM��"a�tU��o��T-�T��o�2^�c=/4l�"Fp�U�
+.��z�E5 �[�ػ� �W�� ˜�:��&�b!�~i���(�:!�R���5���7lw�nįWSb�#� )���X��X��nƜU�,�f��x�BѪ�+�+P!�T$7���kIk�PY�A��j�&�[.zK'�p����y�6��]���^KHl���T��E��5�B�e�ʇ)>�:�����Pb]!p�;�_dJ�u?{iQ�5Վә�x��U�AO�/�Ks!�(�P������ ��0Ň/{�(�>�32c��2{���ǘ�ڒUŇ���%��^K�����,D�}(�o�oar\�*8�tE�����+B)U����R��?c/ F ��#Y����&M��]��ő"9`�<�E~���eM��(����戈Ϩ郻��co2���)�@���� ñ�U�g�?8X5:�}5����EQ�w��e%|�#��Z+����Цj@ҕ}@�S��b���Ī#��d�^lJ)!���rj�D�i��S�܂�<��pPGT�_F���\XN�_�,�ӊ�(g~�]�PS �h�C�cX��t'�!�lbQSq�L���J!\f�+����.���|���E�4��}�ڻb2+'�=g�ԕ^K+�bE��wiU�?w:8]�"zPI�� �����7\z�T�_%�%m�h��2��7�_)!�Y(r�7���Gb��j�&�#.�V[X4Z6���H)p�������]�V����JQ����%��›��q����x1�نb��PNӘv�U ���ު������]���%��o���|,EU[&hW�/,�/F������^�< �t� ������{�A�
+]1���%F�Ҍ� ��pV��G+c9U�l[q�B��+0mI S�T_Ԍ�=0W���@T�� ��_c�u7ƒP˰�Yau�0�8�{��zi��t���:am-�0j�}Wʆ5<B2r�� U-;��ܠ �T աg�`����@����X��OR�Ց;e(�}>���B���L��R�R!�)`��;�0�.�RLt>���:���ٛ��#V5|\���>ޮ+�����V�n�F)�CS@��c��_�ߵ�}��`�)_��s���$u�LX��\mG��*�=�Q�?��!0uv����#��PCH�c�����!�%e�-�mBaY������8Ҵ���b ��b�a,�ڒE�a'�3�?�:{H���N�Z�]�������#̺˺��(�#�/U "�K���R�7.�"f�S ���G<9��L��N��T�1&�-��w�D��8����PDؓ4O?S��xy��� DD�����Z�Q|M�R^_�~�ǰ���{�-Cg�޳:{���:Trp��X{�8OƱ w!Hi ��Nr�W]�
+c1( �;�:"�6���nx�%��@�S��*���x���Eݫ�1|9�'� t]��+���7��>�KB��^*��d�JI]Ģ��M��S
+WN�ぢ��^=rb�_)PG�*�C����D��qg��jY_ʟ/�I����� 6<��pSXXV���^����L�J�bsHJ,\B����g� �Ӈ2P`~��{�`u�+��������ھ �:�_`��J+�iG@@����`�H,lb� �0ȓni ��}�B�X�U���hI����U�/O�P�T��j֡�"X�H���/�x> �v�L*^N��%�J�O �iԼ�c�ϋ6�������hy��b��9 �F��0���eCa�:���F��K�P���f��S�� ��~����W�{5ɿ��.���D'#rk Q�#�
+�!�=��ѓ���ux��q��b�O;��{�63V�ʘhN�Q��B��e�1M�{��4�B��٧��7�E��@ #�˰_҃k��B������6'
+4�F�����>��}����y-��uS�rX���^����z*M�a��P�c�#�g��Be�!p��>��0�7j0�%��Їm��f���
+���w��ˑ�8�Ec"�����o�XCB��*7p�/7|It?(�hLշ��?�K��0%�O�whQ��v�?7O=��������,@�C�J��G{�7+R�j��F��8!�Jx�X�eCAtm�]c-D�U�u�ާ����vXy��֭�
+-w������r�-��8]y]Mg�?�_���k��u
+p�iWf����+�?�R���n<g~{P�j���xo5�k��@�Vܵ���w��^ҁģ*�*|��?/Z�;")OL���3�6��o���:G�C�Pp%�m��g��$IVK��@�&�n�Gĩ�o)[����?M����*�v(�%��p �`zUO��)e��H( ������Vt��p=�[�Sì�ۦC�?�?���Vc�Fȅ>
+2kj�Nw+Xʀ\D��U=r3 ���-W�k6�W{su��A�:3��}�l[Q����MZ�jЂ�����#p��t;�tCcR��i�-���X�
+�_o,&�e{��'`�L.[���ɇלx'@�F�/Da�v<P�5�T�j���t�+�í��ߨ�d��U;���Cn)e� �-�57��P�ѕE@��Ɲ�+���P��R��s�z]�c^ �rRE��"��!��p����3OB�-*������7��|����Z����h'� �8F�U��ݔ >�8!D�J�^�-K|#�m�{��n�� 2����p�X��.��aX�����$��we�U���3/��$�0�]�����5��ٍ��� E�\��#�M `T�8���]��n�"� ���#`�-4*�8�9�6]��f��{��K�]�*8��#s���ɐӴެMӣ��{�6i?�0 ^��tv L�=u�����<�D��=0�DI
+W��iK�^��,<!K����D�'�����������Sŝ��T�Y��BX\�,�3���LN,l�J0X�/����s�⺅�W���Z��Q�E� a�ȣ*� ��rP����2�*~���>Y{�#�!��
+�kw���<�֟���!�����#le�}�wJIC�W����G�2�5&U� V�E��� �����ؔ� �9 �D�U����>�4�!0DBԫ�oK �_W:#B���g:�t)�1Z�u%� B`�
+u)�w����Ʀ �!@�A�7�J�'���"�'��9�L��!@,@�o����T�.�!@�C�_v/����ߦ*a�:��tB�!��ڥ7�"��� �!@�����?-)a���sB� ����R=�.����6� �!@xC���"=����Xo��k�!@�|�S?a���a!�O�&�sB� �"ps]�n��'����k#�EB� � �� F��S�iad�饉�!@^ȏ��C�?ۑ嵂t� B��e�L�����W �uB� �#�D{��?>.�^7�J�!����h���ͅd�黁�!@>��$�kw
+� ��b�Q9�L�! �����ڕ�7�& Ս��!@�F�6!T����)�d��i�!@�!��@����[���'B�B�)9Ls��_wW�տP��=B� ��i���Z�3�+%"B`1��XQke
+�����~�:�}B� &�/� �h~4S�(!@�6���X��?��&��6�� B���ǝ�vai~�hQJJ�39Q_�T��+�KB��B B� �C��*7�4]�� ƿ�PjB� ?��!EU��$�.����� B@ g��T2���~� !@b�&,B����x!�}Ķ"=G��Xz�"�h��e�I��+���9B� C�"������(�{`MGO�!(p �Q��"���di�u ���yB� $Br���q��U�D�)Q�Q6�!@H�@KJ؛2� �F�w��Kc��"B�����ЇZ�������D� ���2$B�� �������_g���X�5Y�V�4�2�eK��F�7Ĝ�Ky�+��Ѣ�8^���)��m+��xɅ��g;��_�4��nS�L�B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B� B@��2�8
+endstream
+endobj
+650 0 obj
+<< /Ascent 435 /CapHeight 435 /CharSet (/u1D456) /Descent -11 /Flags 4 /FontBBox [ -342 -238 1247 786 ] /FontFile 756 0 R /FontName /XKEAZI+LibertineMathMI5 /ItalicAngle -12 /StemV 82 /Type /FontDescriptor /XHeight 400 >>
+endobj
+651 0 obj
+<< /Filter /FlateDecode /Length 590 >>
+stream
+xڅT�j�@��+f�xFoc�^`�<�ͲW[;[z���5�<!l�����z��������\�A��#gﲫ�6�f��o��,���"��E�B�i����:�ʞ��M�����ț*?��X�'E�TV��>l�����A�}Y��}��q��P�)79�ve&�LF��c�.�#ۮ��'&9��U� ���P���˪hoj�� a����[�����B����򲩎��\��;v}{U���k[ȶ�Nl��H"m��9Kb�X�X!�t7����H����;{wm$�T.F�y]Ȯ���W'i,9_�e�� Y_΄3���&.�񰩎��z<)�O"J�@X`�b'�G�n��.D�b� L��j0�r��`�y�fJ��ξ�A�������5����.�* ����f# @Uh��k2��&��}{��HY���ѝ[*�\����q<�1�D����o�8�b�SĖ�t
+w��;z�=�H�0ωu�^N�� y�}�3����|�ѳ���p�S|�$�m�S�9� B��Bu?�0s�q|s^9�o[w_�|h[���j��ӊܷ��T��Z��_�kf��_�
+endstream
+endobj
+652 0 obj
+[ 354 ]
+endobj
+653 0 obj
+<< /Differences [ 46 /period 48 /zero 50 /two /three 53 /five 61 /equal 65 /A 68 /D 70 /F 72 /H /I 76 /L 78 /N 80 /P 83 /S /T 86 /V /W 95 /underscore 97 /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p 114 /r /s /t /u 119 /w /x /y ] /Type /Encoding >>
+endobj
+654 0 obj
+<< /Ascent 658 /CapHeight 630 /CharSet (/A/D/F/H/I/L/N/P/S/T/V/W/a/b/c/d/e/equal/f/five/g/h/i/j/k/l/m/n/o/p/period/r/s/t/three/two/u/underscore/w/x/y/zero) /Descent -174 /Flags 4 /FontBBox [ 0 -177 509 835 ] /FontFile 757 0 R /FontName /ZGUGQH+Inconsolatazi4-Regular /ItalicAngle 0 /StemV 72 /Type /FontDescriptor /XHeight 457 >>
+endobj
+655 0 obj
+<< /Filter /FlateDecode /Length 843 >>
+stream
+x�mUMo�0��Wx���N�W����H��
+Z�&��T���~3ڮ�z��y�87?�����n�k��N�ehܤ��=77U�\�;?:׺v�==��o��n�U����;O^u���u#���½��O
+��ۍ�=٘�a�?���kLy�6F��/7��}��̽���][�H<Si��c�ݾk�^�90�j��YV����H^����v}0����<���rL��� ��ͯ�_�/��Ck���B�n��y���W������THk����u��qö{s�\녚��"p]�Ϟќ��K�յ� u�/��A� )`JbD>`���2���$`�TY'`�(Zq����BJŌ
+)K�̌%553<�,��(�h�l��wB�6��0��a�G�+L�gı�c�W� c �rn
+�q��9�����Mܗ8%� ���CMq.�5�S�hr����A���I���皎��\S���ȩ��� �]8 �`Y�7ь1O�ye���zl��,d mYĸ�S�SJf�-�1i�:C&e c4�R�������$D&� �
+�&+ü�bL���a�j� ��b��y�����+��b��YB��������g� �YJ�Y�Yr֟b����x(r����GT��̛��`F+�٭L ,C9���?d+�����͊���1��1���ӊ��Ċ��׊�T_��~+�Cg!��o!��_����?��?�����/�?㫄���Y
+���?^�B����\�j�UP���{���xᇻL��^U}9pQ��q����0�O}c���}����3t�Ȣ}�Ə!VOu���˷
+endstream
+endobj
+656 0 obj
+[ 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 ]
+endobj
+657 0 obj
+<< /CreationDate (D:20250604140153Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+658 0 obj
+<< /BaseFont 758 0 R /Encoding 759 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 761 0 R >>
+endobj
+659 0 obj
+<< /BaseFont 762 0 R /Encoding 763 0 R /FirstChar 0 /FontDescriptor 764 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 765 0 R >>
+endobj
+660 0 obj
+<< /BaseFont 766 0 R /Encoding 767 0 R /FirstChar 0 /FontDescriptor 768 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 769 0 R >>
+endobj
+661 0 obj
+<< /BaseFont 770 0 R /Encoding 771 0 R /FirstChar 0 /FontDescriptor 772 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 773 0 R >>
+endobj
+662 0 obj
+<< /BaseFont 774 0 R /Encoding 775 0 R /FirstChar 0 /FontDescriptor 776 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 777 0 R >>
+endobj
+663 0 obj
+<< /CreationDate (D:20250516111417Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+664 0 obj
+<< /BaseFont 778 0 R /Encoding 779 0 R /FirstChar 0 /FontDescriptor 780 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 781 0 R >>
+endobj
+665 0 obj
+<< /BaseFont 762 0 R /Encoding 782 0 R /FirstChar 0 /FontDescriptor 764 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 783 0 R >>
+endobj
+666 0 obj
+<< /BaseFont 758 0 R /Encoding 784 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 785 0 R >>
+endobj
+667 0 obj
+<< /CreationDate (D:20250516003513Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+668 0 obj
+<< /BaseFont 778 0 R /Encoding 786 0 R /FirstChar 0 /FontDescriptor 780 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 787 0 R >>
+endobj
+669 0 obj
+<< /BaseFont 762 0 R /Encoding 788 0 R /FirstChar 0 /FontDescriptor 764 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 789 0 R >>
+endobj
+670 0 obj
+<< /BaseFont 758 0 R /Encoding 790 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 791 0 R >>
+endobj
+671 0 obj
+<< /CreationDate (D:20250515122242Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+672 0 obj
+<< /BaseFont 758 0 R /Encoding 792 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 793 0 R >>
+endobj
+673 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 206.37436 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 345 >>
+stream
+x�uR9r�0 ��
+}@��٦�>H���6�~Pm��E�����^Gi+��/�����
+�q�}�o�_�|���1/3��\r �Σ"�p �Ǚ��@.��' �y!N��Ay) ��LK�Ux�������E�%�v�vy�zg ]��!7g�ze�U�m�e�u���4�X�H��ĕ�!9@6$�+(�
+A~W�u��G�(�N�Q%Ɓ?#��x�K�u�6���xoc�Q��U�m�'G��T5߆���BO� *�=��)�F�#Ӵ47T�{Ț�&�����Z���!?�Wu���X��\�7�E��c��������L5|#����0�ƹ���uo��!��
+endstream
+endobj
+674 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 206.37436 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 564 >>
+stream
+x�U�=S1 �{�����vKC��楡��H�2�IƓ�r�������ju��3k���a��:��5~�J�ׯ�1�kV{�����;��$���(y�W���f����}�Hyj�� =?K#M4R�>�Јi%[�"�ph��lKi�!�����������n�-�n؎�iw�k�A�:�jkѴt+��tLͲ��EY�qA�V,��Uh95ل�tM97 �s����x��"��r�3�'p�o�x�%�q� �-1%�!��L,ި� ���rQ)j~���Ж����`���1 �G�aZ���%��1_LZ�6��k�F� X?�_��qS�"W�-wr.��A0:�Kɉ"L�܀���Fp��T�����pr��/8�T�0q���Q�3L�0�f�a*��/Bl���SL�`��:�T�X�sL倌�9�TH�d�l�eq A۾,�S ��Yr��/�� W�Y�sv�g�8�~+rifF�T�����z��2��VV'��
+�.� {��Z�c�F����g�%�v)���Ҷb����2�
+d�0�t�{v�����0)�?�_�q�'
+endstream
+endobj
+675 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 206.37436 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 313 >>
+stream
+x�-�;r!DsN�L���N���)Q��� �[4�Yu �sj{�6��E��vo��:��#�h��7f=�����?���B�h3�} 6��$�S7j��*%��sڪ NT�[�޴P�ĉU��H��8��8N�N��#��8Q�y�J2��*S�1HF�X��a,�'V�qfQ 69*�J0_2��X n�E��v"�3p�!kelu����$
+qG3_� ���zb����6S ���Ir���MrO�#=�0�1�pqȽ]ځ��/{�q�{ӴB��7��;h���o\oG�r%{߸�.l��iG:6|��瓿
+endstream
+endobj
+676 0 obj
+<< /CreationDate (D:20250516081347Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+677 0 obj
+<< /BaseFont 758 0 R /Encoding 794 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 795 0 R >>
+endobj
+678 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 142.22867 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 345 >>
+stream
+x�uR9r�0 ��
+}@��٦�>H���6�~Pm��E�����^Gi+��/�����
+�q�}�o�_�|���1/3��\r �Σ"�p �Ǚ��@.��' �y!N��Ay) ��LK�Ux�������E�%�v�vy�zg ]��!7g�ze�U�m�e�u���4�X�H��ĕ�!9@6$�+(�
+A~W�u��G�(�N�Q%Ɓ?#��x�K�u�6���xoc�Q��U�m�'G��T5߆���BO� *�=��)�F�#Ӵ47T�{Ț�&�����Z���!?�Wu���X��\�7�E��c��������L5|#����0�ƹ���uo��!��
+endstream
+endobj
+679 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 142.22867 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 564 >>
+stream
+x�U�=S1 �{�����vKC��楡��H�2�IƓ�r�������ju��3k���a��:��5~�J�ׯ�1�kV{�����;��$���(y�W���f����}�Hyj�� =?K#M4R�>�Јi%[�"�ph��lKi�!�����������n�-�n؎�iw�k�A�:�jkѴt+��tLͲ��EY�qA�V,��Uh95ل�tM97 �s����x��"��r�3�'p�o�x�%�q� �-1%�!��L,ި� ���rQ)j~���Ж����`���1 �G�aZ���%��1_LZ�6��k�F� X?�_��qS�"W�-wr.��A0:�Kɉ"L�܀���Fp��T�����pr��/8�T�0q���Q�3L�0�f�a*��/Bl���SL�`��:�T�X�sL倌�9�TH�d�l�eq A۾,�S ��Yr��/�� W�Y�sv�g�8�~+rifF�T�����z��2��VV'��
+�.� {��Z�c�F����g�%�v)���Ҷb����2�
+d�0�t�{v�����0)�?�_�q�'
+endstream
+endobj
+680 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 142.22867 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 313 >>
+stream
+x�-�;r!DsN�L���N���)Q��� �[4�Yu �sj{�6��E��vo��:��#�h��7f=�����?���B�h3�} 6��$�S7j��*%��sڪ NT�[�޴P�ĉU��H��8��8N�N��#��8Q�y�J2��*S�1HF�X��a,�'V�qfQ 69*�J0_2��X n�E��v"�3p�!kelu����$
+qG3_� ���zb����6S ���Ir���MrO�#=�0�1�pqȽ]ځ��/{�q�{ӴB��7��;h���o\oG�r%{߸�.l��iG:6|��瓿
+endstream
+endobj
+681 0 obj
+<< /CreationDate (D:20250515122158Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+682 0 obj
+<< /BaseFont 758 0 R /Encoding 796 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 797 0 R >>
+endobj
+683 0 obj
+<< /BaseFont 766 0 R /Encoding 798 0 R /FirstChar 0 /FontDescriptor 768 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 799 0 R >>
+endobj
+684 0 obj
+<< /BaseFont 800 0 R /Encoding 801 0 R /FirstChar 0 /FontDescriptor 802 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 803 0 R >>
+endobj
+685 0 obj
+<< /BaseFont 804 0 R /Encoding 805 0 R /FirstChar 0 /FontDescriptor 806 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 807 0 R >>
+endobj
+686 0 obj
+<< /BaseFont 808 0 R /Encoding 809 0 R /FirstChar 0 /FontDescriptor 810 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 811 0 R >>
+endobj
+687 0 obj
+<< /BBox [ -9 -9 9 9 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 132 >>
+stream
+x�m�1�0{^���6>�6e��&������N�(n������$�F��E9�G,�;+I�ռ0jj�Zm�dŴt��v�.��2��,C��@����t���Cg�� ��to��E\�1�&'Ó���A�� EGb
+endstream
+endobj
+688 0 obj
+<< /BBox [ -9 -9 9 9 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 33 >>
+stream
+x�3P��2P�b�\.] ��R\\N\l
+endstream
+endobj
+689 0 obj
+<< /BBox [ -10.303301 -10.303301 10.303301 10.303301 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 49 >>
+stream
+x�3P��2P���5P�5�360660T��3 r��pn�.�T��� �
+endstream
+endobj
+690 0 obj
+<< /BBox [ -10.706339 -9.854102 10.706339 11 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 100 >>
+stream
+x�m�;�@D{N�����ZKOb�޿;M�!a�1�$�r4���xt�&��)��R�ks�?b}6 .���ƫ�T�n�V9q�� �%��[�><�6zh�&�
+endstream
+endobj
+691 0 obj
+<< /CreationDate (D:20250513045445Z) /Creator (Matplotlib v3.10.1, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.1) >>
+endobj
+692 0 obj
+<< /BaseFont 812 0 R /Encoding 813 0 R /FirstChar 0 /FontDescriptor 814 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 815 0 R >>
+endobj
+693 0 obj
+<< /BaseFont 816 0 R /Encoding 817 0 R /FirstChar 0 /FontDescriptor 818 0 R /LastChar 127 /Subtype /Type1 /Type /Font /Widths 819 0 R >>
+endobj
+694 0 obj
+<< /BaseFont 758 0 R /Encoding 820 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 821 0 R >>
+endobj
+695 0 obj
+<< /CreationDate (D:20250515122205Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+696 0 obj
+<< /BaseFont 758 0 R /Encoding 822 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 823 0 R >>
+endobj
+697 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 163.62 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 343 >>
+stream
+x�uR;r� ��\`�m���Iܼ&׏���سcVXڏ�Us���VH�>_���OHxF���
+�V¯Y�{��BN3ld� 9d�U�o8�W
+��tM 7@��Is9'����<���Vr�%���*<��DX���E�%�V@������T[CnN͕eW����]4��4=���bE��Wfv��!�^A9� �J��F?=�E�ur�*1��1�6��/ ��md�N)6�nc�^��U�6��\U��������:C�
+� @�k
+���4-� U���I�n�ijmD��~ȏ�U��j�W�-W��|�;��}#/��(7Su���� x�qn�=;i�m�a����
+endstream
+endobj
+698 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 163.62 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 312 >>
+stream
+x�-�;r!DsN�L���N���)Q��� �[4�Yu �sj{�6��E��vo��:��#�h��7f=�����?�ƿ>ڌz_A�͟"-��ԍ�8�JI5���*�U�֪7-T1qb�)�>�e N�"��|�����$#NT)G����8���j �'V�r�dĉUj�YT��E�ʳ�ė g'��|.B��@���H� ��+h�Z[�0Ŀ1�5�B����!�|�ޅ������T�b�{���s@{���HO! �g�%�FroE�v`"���o��4�P�����ڧd���Q�\��7�� �qwڑ� ����]
+endstream
+endobj
+699 0 obj
+<< /CreationDate (D:20250515122206Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+700 0 obj
+<< /BaseFont 758 0 R /Encoding 824 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 825 0 R >>
+endobj
+701 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 163.62 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 343 >>
+stream
+x�uR;r� ��\`�m���Iܼ&׏���سcVXڏ�Us���VH�>_���OHxF���
+�V¯Y�{��BN3ld� 9d�U�o8�W
+��tM 7@��Is9'����<���Vr�%���*<��DX���E�%�V@������T[CnN͕eW����]4��4=���bE��Wfv��!�^A9� �J��F?=�E�ur�*1��1�6��/ ��md�N)6�nc�^��U�6��\U��������:C�
+� @�k
+���4-� U���I�n�ijmD��~ȏ�U��j�W�-W��|�;��}#/��(7Su���� x�qn�=;i�m�a����
+endstream
+endobj
+702 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 163.62 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 312 >>
+stream
+x�-�;r!DsN�L���N���)Q��� �[4�Yu �sj{�6��E��vo��:��#�h��7f=�����?�ƿ>ڌz_A�͟"-��ԍ�8�JI5���*�U�֪7-T1qb�)�>�e N�"��|�����$#NT)G����8���j �'V�r�dĉUj�YT��E�ʳ�ė g'��|.B��@���H� ��+h�Z[�0Ŀ1�5�B����!�|�ޅ������T�b�{���s@{���HO! �g�%�FroE�v`"���o��4�P�����ڧd���Q�\��7�� �qwڑ� ����]
+endstream
+endobj
+703 0 obj
+<< /CreationDate (D:20250516081045Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+704 0 obj
+<< /BaseFont 758 0 R /Encoding 826 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 827 0 R >>
+endobj
+705 0 obj
+<< /BBox [ -8 -8 8 8 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 132 >>
+stream
+x�m�A� E�=E/�IKE�
+n=���$�;��M����/ oT
+�O���4K�7 )��Ĉa^-�r �b�\��� 7F�KaJm��7��n�=���b����J�g1d•cp���=���E �!��c|D
+endstream
+endobj
+706 0 obj
+<< /BBox [ -8 -8 8 8 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 132 >>
+stream
+x�m�A� E�=E/�IKE�
+n=���$�;��M����/ oT
+�O���4K�7 )��Ĉa^-�r �b�\��� 7F�KaJm��7��n�=���b����J�g1d•cp���=���E �!��c|D
+endstream
+endobj
+707 0 obj
+<< /BBox [ -8 -8 8 8 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 132 >>
+stream
+x�m�A� E�=E/�IKE�
+n=���$�;��M����/ oT
+�O���4K�7 )��Ĉa^-�r �b�\��� 7F�KaJm��7��n�=���b����J�g1d•cp���=���E �!��c|D
+endstream
+endobj
+708 0 obj
+<< /BBox [ -8 -8 8 8 ] /Filter /FlateDecode /Subtype /Form /Type /XObject /Length 132 >>
+stream
+x�m�A� E�=E/�IKE�
+n=���$�;��M����/ oT
+�O���4K�7 )��Ĉa^-�r �b�\��� 7F�KaJm��7��n�=���b����J�g1d•cp���=���E �!��c|D
+endstream
+endobj
+709 0 obj
+<< /CreationDate (D:20250516055607Z) /Creator (Matplotlib v3.10.3, https://matplotlib.org) /Producer (Matplotlib pdf backend v3.10.3) >>
+endobj
+710 0 obj
+<< /BaseFont 758 0 R /Encoding 828 0 R /FirstChar 0 /FontDescriptor 760 0 R /LastChar 255 /Subtype /Type1 /Type /Font /Widths 829 0 R >>
+endobj
+711 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 119.88684 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 343 >>
+stream
+x�uR9r�0 ��
+}@ɺ�4��I��&�����YZ�������u��B����e9�y���g�|�_���Y,=�} %�6�rc:�
+��L���XM�S���RC,'�d:T�PgQ�`�3,����c C�U�6/
+.ٶ�+�k��˵5`s�i�l�ʴ ���B��)L�ɲ�82�[� �
+ɱܐ���N�3#G�Y�֨2��o#��x��F��R��6�� �[]l����N��6�5f�d��4����L���@�%�%k��4��O<ע�݀�<���U��ѯZ�\=7�E<��`Tύ�O�<L�s��œB`���NFw�}��ӕ�
+endstream
+endobj
+712 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 119.88684 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 563 >>
+stream
+x�U�;�0 D{�B��_lӤ��4r�&�� ���ñ4�g����>��*�ju�J[�j_m�]���k���~����V���������\��$;j��1�ߦ�a����i�w�p|�(�Z�ۃE����V��="��E<���0�^�[�(�O��.�Nۺ=��l�vW�V��s��J�:��ӹ,�
+M�%�4R.���"XJ�+Zi�,ق� K�6 ����D��"��s�3�'q�O�x�%�q�I�-3%�!���,ި�I���rQ)j~���і�d���9��1 �G��aZ���%ǐ1_L��v�k�F� x?�߶7pS�"W�-r.r�A0�K9�"L�܀��Np��T��}�c8���/�T^�a SyFa�0��a4 S!�C �~)ƈ�b*/Ƙj`L������ cw2�,�$��@YCж���u`����C��o���y5�\�5μ�ߊ��?�}`����zXf�֊���Ю�9�ǀT�11�t׃q�K��P[��m!����0�
+d�e8�>d�e8�rd�/ä0�l�a8}I/��
+endstream
+endobj
+713 0 obj
+<< /BBox [ 0 0 72 72 ] /Filter /FlateDecode /Matrix [ 1 0 0 1 0 119.88684 ] /PaintType 1 /PatternType 1 /Resources << /Procsets [ /PDF /Text /ImageB /ImageC /ImageI ] >> /TilingType 1 /Type /Pattern /XStep 72 /YStep 72 /Length 311 >>
+stream
+x�-�;r!DsN�L���N���)Q��� �[4�Yu �sj{�6��E��vo��:��#�h��7f=�����?�!|�����?EZ۩5qb��j�9mU'�ԭUoZ�b��*S}$�@�XE'�T'E��IF��R�<G%qb���$#N���0Ɉ��8�����g%�/�N,��\�"ہ~;��8�WА�2�:a�ck�����C��f� 1��[me��v�v�$����&
+�'Ƒ�BrϘK8�8�ފ.��D̗�=�8ȽiZ�d����O��7���h���o\o6��#>�?�J�\
+endstream
+endobj
+714 0 obj
+<< /Differences [ 27 /f_f 35 /numbersign 38 /ampersand 45 /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon 61 /equal 63 /question 65 /A /B /C /D /E /F /G /H /I /J 77 /M 79 /O /P 82 /R /S /T 88 /X 95 /underscore 97 /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z ] /Type /Encoding >>
+endobj
+715 0 obj
+<< /Ascent 685 /CapHeight 657 /CharSet (/A/B/C/D/E/F/G/H/I/J/M/O/P/R/S/T/X/a/ampersand/b/c/colon/d/e/eight/equal/f/f_f/five/four/g/h/hyphen/i/j/k/l/m/n/nine/numbersign/o/one/p/period/q/question/r/s/seven/six/slash/t/three/two/u/underscore/v/w/x/y/z/zero) /Descent -237 /Flags 4 /FontBBox [ -1082 -268 6171 893 ] /FontFile 830 0 R /FontName /PNRYLF+LinBiolinumT /ItalicAngle 0 /StemV 80 /Type /FontDescriptor /XHeight 432 >>
+endobj
+716 0 obj
+<< /Filter /FlateDecode /Length 881 >>
+stream
+xڕUMo�H��+z�2��`�"�RF���M���F6��H6x���笴���`��Q�uU�ݧ�ϡ�ƃ �/Z�p�x�ZV_������� ˓s��nW��}�g����~��'?��ڹ��I�{�)�Gݿ����P����p9�ń�a?��tX�_Q���ߡƌ�~9�ޏ�)�U��U�şn��qxP���vCW�gd1+�V7��~�&1���Hu}�Ȋ�۳��o��Ώ�q 6���/���F�>�oS�~xU����w<_/���:���Vu��7��>��N�>�{���ũ�ֆ]�c��˾u�~xu�F��4�6pC��k&�����y�n�_��bl �MDS����r!������Ǿ�{�4\�}!#��:��(P0v�y���������T؁�`h�- �6hi*.���Q����g�|��'�ȋ�`m�k`�Q�DŽk���ı�F'\��S�8�� 8�:� �m�-ב�.y_�T\/�k�3M̽��P�,c�`xf�} �LS��������������� ��$�s���uD�<cMНj�Н�]G9ej|���#�CO3��|�xL�򜧌1?�'g�А�ڗ��5��K�МW��K^3����$��y�: ֟`߂�'�������'�S���zY
+��ψ��S�� � ֙�^�3�^�S/�4�q�^�� �Vrƽ��3q$g�e%g<VrƾVrF�Vr&�� �Vr�~+9C�����J���J�4_r�~+9Cg)9c�Rr����/%g�)%gꕜὔ��/9?����9�RJ��RJ�xKɟf��ai&�%͑���y�94�Qo�S7r��I�#���C��N���7��s�����?S��.�����U��[�`k�
+endstream
+endobj
+717 0 obj
+[ 592 636 602 1247 411 250 228 336 470 465 680 710 268 300 300 433 527 220 333 220 323 465 465 465 465 465 465 465 465 465 465 220 220 487 527 487 405 895 629 616 677 710 538 504 717 726 294 320 629 515 886 718 741 559 741 600 506 540 692 631 951 581 582 622 361 292 361 518 486 268 481 504 429 530 453 314 499 549 260 272 503 252 807 539 500 523 522 355 396 340 537 462 722 455 506 416 ]
+endobj
+718 0 obj
+<< /Differences [ 174 /registered ] /Type /Encoding >>
+endobj
+719 0 obj
+<< /Filter /FlateDecode /Length 678 >>
+stream
+xڕTMo�@��+��HɁxYl �e�#YJ�(���*�)� ����}��`��zH�۷�f� �{��e��E�7�/ū��͍�|�5��MZ���T��1�).�݃xi�|czq���uU�w6x]�ǡ0���i�VV�!XG�n�w���˽i��2۵�n�y���u�=����0��gW"Ͷ�V�I������fڮ����K)-����>�)�3 �K���*ڱ:�G���DQ��8�w~�݅xs�zsZW��Y,���Nv}{����s[������GM[�fh���A!��R�`ײ}~ڝ��|�cW����h�q-y]�����Uo�YH��,[:�*����bCé g����Kg+��}Ii�%"1�%4�k� ��D�D��h�Ӝ�bK$ VL$���`�.���z�Z��L�T��ы�9S�go�]x�c|`�x{�zc�TS�ڏ�l�~,F�Jy��`^W!��(�Z1j��g?e-��+�ѵ)����+��Zfc����S��!i��Z��
+�. mH��ƈ��g4em
+0��F���>�D�x>��?j��'1z����ȩ#�ȣy�hԢ5��0���Ť�O�8#��Al�͡�Y���~��=3N��H�50�ƹq�Ү�9�Mq=��ж�\�uB��ў���� T��Uu�i1zΜ���
+endstream
+endobj
+720 0 obj
+[ 633 ]
+endobj
+721 0 obj
+<< /D (subsection.2.2) /S /GoTo >>
+endobj
+722 0 obj
+<feff0032002e0032002000200042006500730074002d00660069007200730074002000530065006100720063006800200028004200460053002900200069006e002000470072006100700068002d0062006100730065006400200069006e006400650078>
+endobj
+723 0 obj
+<< /D (section.4) /S /GoTo >>
+endobj
+724 0 obj
+<< /A 831 0 R /Next 725 0 R /Parent 608 0 R /Title 832 0 R >>
+endobj
+725 0 obj
+<< /A 833 0 R /Parent 608 0 R /Prev 724 0 R /Title 834 0 R >>
+endobj
+726 0 obj
+<< /A 835 0 R /Next 616 0 R /Parent 6 0 R /Prev 608 0 R /Title 836 0 R >>
+endobj
+727 0 obj
+<feff003400200045006600660069006300690065006e0074002000470072006100700068002d006200610073006500640020005200650063006f006d007000750074006100740069006f006e>
+endobj
+728 0 obj
+<< /D (subsection.8.2) /S /GoTo >>
+endobj
+729 0 obj
+<feff0038002e00320020004c0069006d00690074006100740069006f006e>
+endobj
+730 0 obj
+<< /D (section.6) /S /GoTo >>
+endobj
+731 0 obj
+<< /A 837 0 R /Next 838 0 R /Parent 616 0 R /Title 839 0 R >>
+endobj
+732 0 obj
+<< /A 840 0 R /Parent 616 0 R /Prev 841 0 R /Title 842 0 R >>
+endobj
+733 0 obj
+<feff00360020004500760061006c0075006100740069006f006e>
+endobj
+734 0 obj
+<< /Filter /FlateDecode /Length1 885 /Length2 9111 /Length3 0 /Length 9745 >>
+stream
+x�}seX�[�5 n��
+ww �Zh�)�p(R�,��{�5������v������y������w -%P�U� b���;�r�q���@�n6NZZ-+'[�0Z0��
+b/�7+���ܥAN��,�j�N.N'���� ����߁�@����hZ��`Z)��;����I��_�,9�2
+-@l���6���r( �Z�������0X:99�������������N�ޔ�7���ف�Q89fV���-��Q����rw8f`��U@NP+7�'����'�?�� �����
+�ص��u���.ٿIII���������� �����s���d����NV�7��e����_�]��ß1���*��� `���g�����?�3�����AvV�����࿺`P�Y9���|���7
+N [+S { �CV��Vn`3����%�d��'�mo��Zك�G��F
+�����������=����O
+lo�d�M!fV�.^>
+��p��2//��`�G� v��6;�=��O
+�����gxP�*5'���d��� ���ןa����7�����,�:C�f�����_ws�?E����(�3S�몀�J W�������Y=�-������Bo$�:1�6e��(�=j�c՛����5Ʒ�P���{G�%�{ȐIY��w��?{����6�iS����,���s��-�V�S�84����O ��d�5B;��_�m�I�4!�+������$v��+�b43��Qw���W����r��c; �>!�5��8���^�"��gQ�nSG[�+];=�В]�k��*g\9��<��Ǧ���
+�җ����͚��]��N��e-^�����e�!��*
+9S�;n� �d����0|�9�`5NF�&��G�;��ya��8�.W-���y�bQ������c��+��#�}��<�^vuJ�˲Q��;_��&/ug�dX��)��44Ԅ���&�ᐂ��v��v�L"k<���ֺ �8�E���D��a�;nk�6K�7؟!lȧ�^"�M0-BQ�[sJ{ �\gw�@~G���R�]%q�<� �N���E/�m��#���Y�d�'?��O]Oi܆H��i{�9�4�憆Y'2�T��8:��oK�
+S��I��V��a�(EbN�z�s@/d�d3j�I��3~ �]�|���3\$��:�$�(ME���*񱹖� ��6y�K��iX��?�yd���{W��D���-l����4�s �M��Sm?R`4�?�����Fi�P$Ω:v�RCp}b�K���w4x��>��W� �>:����S(mqb�V�2ʡzd�[�M9����c��,��M�C��1Ig}������9ۂ/P5�^U�n��3V�%�{l�!u�8�(�*�㐾�����z�-\ԮhKn� 8�\c���^��>�Ǡ��A�����7�,��S��mA0�Bg�ض�� �YN���ũ�X�W���W£�ð���S���e�M��C�q�h}�:t�r7}>�s�g�۴Q�o�b��S���,p1�r�ц���SU �J� ����Z������|Fu<Y7�J�_@��WnZ�j*>�i6�&�����•�͠�4$��~�˵ݞ ?\P�� ��x���ZH���2��L|9\�0
+��ĸ[_'D����v�(�Ǝ;������k�� Q��Æ�C�rj��K�yB�Z�5,��UK���5陵I�N*'q%i7O��R_��r}978�����h�!Af�m�'ݓ>�v� �`��L�Sdo���^�[ �b���/���{��Ez~ �E����� �W�Ri�ד���P�˗0ϑ�3���[G�+������G�<8�g�3GZ�Љ��
+I�W�&��"�ʴ5n����
+i�����6���XC}��!�7����F!DC �\1�-5���-��g������ES��LH��%����a�)z�2d~�_.u�#��d6�'���͟�A�?=`@�oQt�]��bN���v�{��ݧ�49�i �D� Os�`i�R��!O�p����+o�����}z&8�g78(f���_&�vXoD/�c�2��1Jâ���P/Ik���Z �~¼�UX�$a�r����fwd0B>���j���ytzC���B��O�e�lFÁ�d@�]�A��2mV\�� l�u����| R���s�_O�3^<b(8}�=���c�W�
+j�-2 �ձ� I�y"+s-��_���f,RX���M�|��X! �+�So $3b�2��d��5K@�ߨ��mQ��[@l��&p� ��Lb �s0�kQ�)����J<=�2<�u����fRr�9��O*$� �3̴�����=���>�}զ��7�ѧd*�Y|�,2�8*����a���w�}Ud1>��ZE��F���P� ��c-ob�悇g9�➅�>��U�)bZ
+��eN�&�l��C`M�h���������WFne�oj�}f�����P��D�C~K��ird���u��������-ޥ>'c�x�sV�]��шn�O�k-��&��O��+g��^*�Mm���2�Y���}�k��xl܅�㓆 Ӏ��Ů�/��%"��L����P>dzm��V�߰��]��(L�LU����s�
+ A8�����1�����!�!��E��M�>@Q���1Ƭ���2~��–%j��wط\y�T��8�%JC��6gtͺua5Y�B5 �F����R�Q��l���D�j>*qq9Bq�Dp�g[<x�/S�*M��'�!�J4�E���rb�9� !��=��Ao��1G����Q��v�2���Z�;S z���2U���1�>L3᫹%����9�����r<���@�E�� ���\�J*�%<=SϮ�t�P��<�� �T������d tl�u,����Wm'/,��&zb��s�EkG�&�+�M��%Q�i����Qy) �k=T���^'���`�� � $D�%����X�k����p�AB�n���5�n\��o�nS�6�Q�X��q���Qw-d�yvZU��?�;t$��j���4V��K��du���Aq� #, �ן��y �+]9��ʀ�n�T����|�֙Z=�� �W��ϫ�G_�1`.k�V� *��'��3�-��2���D�Zn&`1�H*��C텲w�.'m���zn�lnSΌ�T���z�*A1$��-Rl2}�P�@�W,����*:3�Ҙy*�U�?�d�<䋙�O��^�Uκ���Ii��tJ:0<�;.B�G�buI?�9N��q���c_�
+��,��+�N �BJ/��2:��v/Y(���r��kӇQ�3�ވF�� ��VnW�������4�6���@x�ے;�^t{\
+�����G�Iԛ�������"�����j�#x��Q�4,jkwj��l񏷂 k�
+��5H�u���b��}�(ɋ|�tSI��l�A��z���ԑx�q$�R�ś2(n��`����3��&V�b���sEz��a�-�l�vQ�q!��l���[_�����U��H��BuJ&_s�FLՄ��@2N� �ؼ�(�Wmw,�$46d��RJ� �_�)�۷��_�%V?��qL:%��>W_cP8s��7¿�v��8��
+w��y��� �D�z���֠^z�k&ߓ���nl*gi�X�R� ����T2:t�4Za�ϔ�͐�Ki^�UǴ�W.� rB8�{2}��9^1�b�ȶ�+��d�>�o���b��<qbs�O⬜�:$m����P�M���\C��Б�T#%?�yg�}�9 �@�g�e�Ԓ�-�ٙ#U���]��Q��/����I�Z˨f�KA6O=)�M��`�^�2 !�ً~���`1z�O���_��{�q�# �S���S�E�
+?�G� ܋·���&�x]6dT߁uW�Q���Y��Ty�o�w�R��T^Cj: sԢȜ�[��1^�4~��Ie��(B�jp��W�o�B%DU&k%7���ߔ���m��o�>"b��r� �;ic�ڧ��f�=�?�cH�fR���b��;�`1�����)U��j�I����� �2���B��ǒ��r:Q���y��V����k�i�F`�*���\�e�r�[����Y�;O1/�|ŗQF��忠�.5��SB����B��Z�UÇV�I��Eo���(G���ռc�D��P�$h�^�PI��9� �-R��0�;��K۔��^fNu��9���HX��]D��,N��s�B���2N�����h�x?�����,�Pi��ȸ��5h��|�v�gv��'�8�F��\%'��C�d���[�L�d�p���|��C=)��:_q=,�[���ǪT�pn����G�=�w��hŭ��!0��Ǝf���]��'Ij[���cQ޼�����G�.��:�h�it\�:J�!W �� �O�h�$��Vu��#[]quz�C?��Y�����@��w;_o���J��W�hg5� ��g���c�ر"1�+���<��C�hWs�$
+�h�Z�Q�'%\�2��_.A��L�w">�i"�SpR�_W([���p���!�<Y3[`/�l�.� 5�+� "�I�z1��\��fU�/��l�����Y
+�*�0�S�UaFN����� {M�EjU�ͱˎY�n� $�曶���<kI�KQ1�`�XH�v��k��͢�{%|��E�J:G���A�hC
+6re��"_]O�>9��}���rJC��A\YkKK+�@�� i�w/L2���j�4�A`“�Đ��F*`E��w����tf�u��f3�l�-�M���~TR���-�l�I��®[�(��S��3��9�7���C���L?���D��ϐJ�s�QĬ���U~2�9t4B_�a�Ga��l>v
+^�v�~��{��>�wjس���T�~*I�H��TmD���eT���rgnx���d�/�D�-C�4Õux�<w��[�|5���(��7�������A�h� �U��QŞl����v��+|�t�p{�S%n�6��U6s�x.*�uR`&��2����g߮���tɦ=��G
+����C����]�U[�b�"�>$�d-� �Fm|"P�P[� �����4� h�^ϔ�.��Y��'F����w���, ?^TQ�� Y4��~L}͇|�x���c"�&Ë�)����0�-��T�$�w��~�kf(%c�φS=A���~��9�m�dd�a���սCpIW�S,g�ʍ�{�/�G�=��ϴ8�_��]MQ��vA}2C�o��l�C�rJB��� �L'
+
+��rd�E�s�n���;���k�D�}wn%�oNg>q�O���U�Y(�lF���"L[��13�^w?.�D~U��\���B�/���%��.1B�}��(��g.!u�#���]l��1߉_���6K�l�u�8}�����x rR�,�ɪ��x��m�H߯� nZ@�gк�R��9)�~��U{�.�q[E��������/�&Uxb��������y�5q}"�C%�����[��_���{���'/î�\Iw&yh���E4+�R���O��뵩I�:�J�g�&%�e6�I����[�-���4} �ң���'KQ:m��#98!ؼ��|�IT�?qи��H��� �N�9-�
+��-��&c�݅��s� n b�������w�T� zJ��vVr?W���J���4I�7; H~%Kz��|��'T��@�̞��-�{�� w ���x��H�I��=2���otR�
+�(�(�QǗV^���o�=��+�!9�D�~�Y��6l. � �������6O�����ԕf��mu1t����H��R�y߇��U�Wn���y'������s�Ñ;�C����>| ;�jZˇ��,%+�y��9f�Kn����|NM�,��)���> ��C�󁗟']r2+���N����� X����D�b&]�֖v�aIӸ��JQW�Y��QL%v`m����֌ڞ���`LW�|h�Q�Z��u\�=K�o�YpD� O�=���H���
+��x��U�kO������2�������>T��F[F!B7�]�]:G:dzns�ڑ��^���`tQ�e`�B*��oQ��� ��J���`�U7!�Md�K6�hi�b͸��Bvt��A��{2����� g��rN�l�]r�:E����+�]���qX�5}� �܎@ˈ���Q�•����3�ϡ�5��Fmů)B�I���E��)_�`(�w.cQM���$ �ߊ�hPc�QȎ.{��jW���,��Pn�1}h��n6��y7��iU0٢�������)��_�Իh���\�P"L���;�R -��j�\ ��$��\��(�;����+;�
+�V--�����J �z���t������_5�@$g�6
+ɒ��� A��vSdöY��P��o�پ鬍������'��x$r��=3��V�Ѹ����+��=����B�^;N��G���T�E߰��yL����;"�I�@-} D����7`�k�
+;����r�$���r͙ٗPt���<�aà����Gh�D������ j_F�t��3@_����������@�]+��H�bu�+;�Q�ܐ$�X��,Q.c�����4Dn�Ń2xB� I�=.Qt���w�0esn�+ΐ��w �/Xc��4��DeR��O �s���� v���ޚ!���a �8d�P��p/��0���Y���֎�1{� A����|O{f�)��f�qCb>aU�@���<�G�ח�(IJB�l����0k��)��� _�� +t�� T+��i"x�����br�!�8��+ ��u<1�[�� ����a \������w�溦e�{w#o�1�Z�QHa�7��df$���$�����H�l��ӷ@�gx���kC!�eUV�H��Q+)s�Xָ��f�y���l-~�������?�u��1� �T���,�j[0d�r��W�^-�f=����@���ѯ旛� kx�g�l7��������J6/��E�8 -�"�מ�s�����~ ��V�Z0��GW�T�:�}�n�P��8d�|�G���v뱢ek���{�ڦ�i�YW2�'�3��@r�ҡ ��<16�2n����w<�U3��ϡN{���]o�`@L��f*J&fD�KM�e�U�x<�B��1��<Y�3_e)n�h�D�C[Vu�b�*��OO� N`Z4�����r�9���x[mUx�~<C�5�F-i�ӶV�6����s�o�]��(7�������|�ۃe�.�>��K9�2�A �D��>f���`��5L��n�cMt/K�a����?2�Ĩ~��y}WF���-�H��bX�5���U4F�^�\yY�:Y߻�����{�Y_\�y*M�vW�A9��4���hJ�Q�70?�ā!� �&H}\��X�k�'|�mp-Ÿ����&YMK��9��q+'�G���"���`O�˹��V�T�u}��q(n����[������A� ��y�=y��+���V���:�-�^�5D�e�6/A�t��I8��� �:� �'��U>�$Ғ�J�+Z��YjnY�)��?��)W��?H�T@�s�?<G���Gz��� v�KDJ����2�˱ ?�?�����}\(Sd�閉&}nP<�A��ԯ�*�F�lS�����-����^l��P��B��ʩ�)�NU���&xW۪���e4�<��>��D���?�����bӅv���J�'Ȼ,�e�_�?�>5�����J�w���<��̢>K33��+4�����H��wijb��ռw�=���Q�|�5��2|����_t�׻�4轩��{�'��x�I�ԏ`�CP졁�T�}wT�^�9B �^�h��T�5������PO-!%��hr���w/�|>�-�����N��F� 5���B���.7����֓dѪ���X���n+Q'�����1��7v߄ՓB� ӓ/(/��s
+�w�#�ڿLO�C�il<���w:{*��) ��5����i<�G�@w����V����*��I�fV�d:ԡ�,��<ļ�p�'����.K���'�5̙c�v�aKx
+�[.�d^�6İ��>����A��)�jM�7N��/%���nTV*�W% pSf�L%>�A9����Cb �Ӌh��l�;��l�dkp�'�w8��Z��-���1;�h@�`�[�2G�%M`\�ף�>������r��i�=�l ��X �tz]�c�7���4TJR��un���ZݧD^b���t��~[c(��d�q,�v�$�l��T�w5���վ�������o��F������zM�s{-᫠� ]#y�͵K��/u�$�\�T�!��q�{n��`'�T@\�E���g��wn��]Yx��s����:83i3�����y����r�E�X/ �e׫��k ���g���Б�jKk �zS�`�S�ӿY����<��4�y�v��4���`�����J>L�xg��c��T,9��^
+Z�X]a�ˣ�5�h��y�+�F=��V�N�� ��؂��,{��G:�@t�i��<���;P;�yB�:qE��wo��H��`��5��`J�1��Z��U�����f�r���ea�`78z�?T��!��~��U�\�sT2I�������0�^rK�*���ue�#�^}��v���HY���HI%��i�g[`T�c`� �S�� �ߙ;i�7��3��a��zi� D"|��,���X�遴Qe
+�oM��, ./ �{j�aQ29�(/�ZT�xi)&2%N\'cK��TОF�T��
+K�bn%*����E�Wa%���N~Z|G��U�b�c�ϟ�}%�b�wC��$��u���T�!�\�BFV�G��O�su�����wX�Ϥv�� ���q��pua�ԏ�v�z��X&I��ﶹW�[w�k�6��f�ʒ�r�^�~ͭX�$�E�H���J�f�Isn���+揰I$��:�^�F1�|����eM-��hij��XŔ���o�N���� �F�Ɯ�v�i�������ȺT)�����ۺh8Ԋ��Y(z.%R��'饹A`�2V� ���u3F��F�>q����;�n�J9u{��i��d �R"�E�/�X��ew�� ��2��Z�C�/����_S(LGK�txV�ǔ��6���@�=}��j�# �62(��\��:ճ�J�I����D�h]�x\�Ҙ;> "�Y��g=��c4'���u޸�{X��j��(\�I��oS�H$O(�`��8��ɏz�kFRtR��S��y�Xm6=�)l��Զm.�����8w�lڔ�=~S�4�G�_iqD�fZ:�yg�|ݩU�%�#"�dh�O"���󜈇�޺O4ՈQn�R{̞��:s����p�|0��ąM�\�C*��S�ԫ�'b�*����T�펇�1YE�о%l�mbq]�-����,�����%Z-�J��A?&zU!�x���~op� �}*%�?K�'���Q��C��-Rמּ��Z����73� ݯ�Qt���8�D�NQ�2eCY�'��l�Zz�16���% �s ﴛU3׮&.|�Hfd��+�V���dm�A����������O�7�='�Iܒ�k�� ��5�&ϧ;夑&�i8y�H�%#s$kK,��14d3^�� �|
+endstream
+endobj
+735 0 obj
+<< /Filter /FlateDecode /Length1 1572 /Length2 7543 /Length3 0 /Length 8410 >>
+stream
+xڥ�P\Y׮��{ �h���xpw�� �@k�'���I��������݂��Of2������u������%�^k�����j����� {(����C�19� P�� �,���x����Z��-��u@N�{��?l%�@f�&e{p�t��@N'� /� ���S�/;{'A�2�l�h�͜@�����Nk0� V2�-�j`���fog�N���+��"�fN��=��c�)����s�����Y\!00�g�d읬AF0 � ���S��O��paz�AANx�����g&~�����cp���ZJڿ| �œ�99� �d ���� ���z��%����8A��E�p������A��=�������K�]FB�@R��������������I�\��N~~?���!�� �$q�v��Z���n����W���׈0�3��= b�P����F��v܈�������N�k��%���a��?f�]����~�c�?;����A,|�.���K����\~z��P�g~ ���������g���&��X9���g��R ����Arm�%���!���3��\88����X�BA���?�@P�I��Z<j ��>T�����a��xy���C$7��!7;���pp�y?�� ��Dq��]8�x��~�?�/�#���B��A���߈�����!��� �_��!�_��#�_�.�_%��2J�F<��o��_{�����Di�F�to��?����������m}h�_�V��y��@�S��B6 e�䮬k�|"=j�����V�l�9�fݔ�R�E 3�&ʛ7H���z��^�e
+OE
+rD�d��۳FXxuu|�؝�8����TyՊ-ԍ`E���\��ԊtQSgԇ�ċKO��Zߗt>wV�\5>�b�.�^��h�nG\����2m���p�'��zx�� !��p�~�N3b��*���S]����u�� ([�%��� )-�̂e��3�>G�ɜ\�r�H�K�1�X_���W�J�9����Pϕ,�v��\֭my�Jז�z����I�-�1hK^�%A��{z��J�2�2B�H�?X��jC�H^�p0"��k�*{�ߕ�2�X�(�H<b('Y����uV���R�_j�c��A�2žR��>D8�8��ρMZ��e��X��F���� �:��m����4яb�L�S#�H�y˨Gr�[�����_cW��z3����}���}'F0��)��'pʺ?�> �i�?�ªm�%����߆c&���h{(h1��\�!���c5���$;5y�~��~��d�8���~L�wn�$�%�kU���["��f�N:I�[�utv?��{��W�����bn���f������eF$�]����i`w�������2v�v�-L�*��=� DÂ��W�v��T�� �-�����H����0�# OqG���߾<���c�� � Y$�f�Ӛ}�D�(J�?cS�5�!� =�~���N�Ž�F�j�&��s�p�^�V���Ăs:X1=q���D_���e0<S�=��^ �L�c��S�h,��1��s`�d&u4��W�6�����G��"���Bx��7���m8e�^� h����+Ø������s�6XX����cx�)�_�J<%����^=���f���(z�-s��U6��fm��Ƚ��v�@)^�������M�����4��﷓6�9:�W����C�QE�/����s©t��>���x��Nj��#S��|=U���Q����6+�̩|��Y�����ݩ�}�F��k�_��>-+%�����|*^�ez��A5�Z�� ��\��������$Ŏfȓ�Ji�I�u�`�Ȕq�sk���wS*�c(n��N$/�'FE�y
+�����%�hN���F��O*v|� Sx���lg4p�!�a��HFp~’NҤݱ!�v9F� "\+�)�� Μ�*��~r4�yV��\��#wS�7Rl<��<�K��Onc*�/� ^m����Kc�y4,Z�#����H�y�L^��Dp72�8 u����
+�M�>`d0s�Xh�`�j4v}���h�  m�*�8���C�ohj
+g^�[&�,�pL��~�ϖ /�Va@{��Oh(u��S����Z6��l�P޾]\�߻S�����$��0q@"��+� L�� �"���f ��_�x�^��QG�����r��d��O�$|9�����Ȓ�N�)R�^��5�~c�3��>�̟���ق�{ZX򨖵����+�t�����.�\���2�wt���"��Y�a�����`���
+���X�m>�`x������لB&��w0�n���|G[��M�@���6��dM-eM�aw��<����k�ɐ�w?��RG`Sы�MWP�2{��̓h�C�m�h�*�)8������`q�п���EXT�ؾ�u�i�不�|x�N�M������ +S��fXU����Lڜ�m�68�AF�X��3j�������8���|�7�Ys�����U%�܈x`Iz����wG=���%;���o��������N|F�Yo;���nƧ*� �M#h���� 1�g(��%gw��:p� ��y�v��zP|Z#��#s�`��2w�v�]Z�Cb�E�:��YEgdxϭ�J�qD�G�j,�J
+V��褼�L��L�Z�U
+v�Ό{���L_H�e:�̗�l�I!��]��8&=�eϰ�;a�^���D0i`aO�+���F���(�eAHkˮ`����%b
+����
+��q��= �p������Z��g��t�2����U�Z�����D�K��z��0}o�Zr�c>�Eb�P�γhh���v �C�-�8K��K���Sjx�-�4�})�'�U���� /5�{q�μqj����Q%NV��y?i/�IWil� ���̪�A����e��5h�X5�R��`�!9t�أ��n~Q(БRH<J�#|�~�t�ō� `���U;;͖��\$@A����*Y��E~� �֐4��G�N����{ܒ���ή��� aFOF �,%�X��I>W�H���X����7�����tw �?z�:��܂&vEi&��Y����ȡ�w�����nT�� $43Ո�<��<�����9V�q�"o8aa���J�����^�`�q=�5SI-�f��YU���nג�WTekg�m�3{��<k[#*)��yw?[���̀#a�.��5? x R��Y"E�r�"�P��'�$�ʷ��WJ��$���zׄ���ł%� )�S�@�va#]�����������U5lO[>#{��x����!-����z�ŷr0m��I��۷�ӬH����� IH-Y��dof�K�sK3B� ����% MU����#^L����D�:{k��[����p����H���8lk�1��_��C�%|У,�f1���w�5�M��$抨:�P��b�B�w��~Qo���=+J�c�zsU�Y7L Q�}z���jlP<� ¬!���@�'n߮9z�������cQ��K��d�C,��'������vn�L�_{�d��Q�o�)� ��!5���Uh#����}��� ���í\#PD���7�k
+I\�[��I0�Z7^A��� W��u�B��ݼ�g���ѽ
+xf>'����a�ڋ�
+��w�m���?�7د;DzB���6�FqG�_��}���N'���"�tr�3�ОP"�T�]{n���ya�A�|�y�i�%�c�b���Z�$XE�t��N�x�8}����z�5���E�4�R���- f�/��`b+��*�j� H $�Dԅ*�� Wq �"���&���ň��/yx�4'����ɹ��拋�I)�T+(��]�������G���F�}���夅^��T�wH����4�M<I�̎pv̡m���K)�&��Rmg8�����Ȥ@C�Ξ�x��z���� ��=A�J,9�� j$2��Dj������:����W���s����q�:B�x���u��p�C�U�#�V5Rk� �g{Ɓ/�=���oK���e_�X"[U��!|��2/�<�ie/��{���{�q�6�Mis��Ro���\��@ze�e�$j��x����VOD9TJ�m=e��k�ޔ�4y����nj�~��s�1�Z��w��q%����y��g��Q6ۮ<�u�/��Rs���tn��S�e�+�]������~d�o�?����R�8ʓjL!�)ʛ��F
+Km�«�|)n�9y͵���=$�>_�Nu�����>��繕�Q�`*YT� ��n�Q��
+R����Η�^��s4}�a�Id �]n�4�\O ���Ԝc��Dt�W��XΆ��?�0 �9��Vv�>�L�jGR�C�s)_aSnP}�PQ��BOqJ>��B�CzB�;�¡�3�����?�ƴ����mԝ׊��Xe�O���Ik�3Ç���>��t�{L�鴪 ��϶9ORh�-Z�`J��ݳF�쌉�,#H�ܶ�0��(}��"V� ���>;�����:�@�-�HJ��3��lέr�Ye�B��2D��4�k$,s��]��^V� �֏OXɌ�LW������1iE�|}Ƣ����o����3y4�gز�\o �A��d��}�w�qO�a,���J�W�u ��tO��䛆Ubh�\���;�/�&�o���9.qͫ �WY�:�����k��0�O�GE<�o�6&�脵�������� ���c��6?�]��SS���t3:y�pձ�0*'�j� &r�t�:hK�f��~#����/<�ij��B������K�L�*v�b'y�G��-��(Қ�� �0Q�_��9�rkT���__�>iS 6"��3b>T:D)�dI����nĩBy=ȉv�ᵴ��4yNa�m�k�a���b0Rd�]�#��.���L �h��\�p�1`�aJ���13��"���^���.�ߛ��: n�V��K�N.U�~ a�\�J
+��V�� k�y�o~CN����h/��X�/�ÙWBBk�h�S�NA�
+"��B���Ktd�h������s7c~Ӻ��ܲ���"'��յK��#
+�G!�U�~�gV��ΰ�4�(��#'A��M�#!��<g����=kr
+�77����W����9�T�j�3P&�$��*dY�+�ef�-�ёm$�i��s�6�V��GCsHΘEZ�Ц�An~������ ���ڡ����H��M��T�� �f�BfG'I��SҼ��3���%����a�����t�|��g\��.���;�q�Hŕ� Q��c|�K4ҫF����k]�f�]�`9ū#׭û��'7�|Z���h�tD�:ϖ0�R?�PT�,@�͵�ɧv�I%Q�3�@�(�B{0�i7SS��RկqW���v����˓����O�Lċ7���[��S"�e?4�6(�&���l�T�Ff'�<�V��z�(gْ}��9h>U�Z��Q�E'��[][l�g�z d~��#hB��<RF0��M�� .�^��(m:@����+�Q�j?��)W�p�p�j̳���-��\]b����Ӌ+ߐ����z��90�fXLQ��i�q\�Z�渒�㥘���C�[�,������S��� 3� t��ukS<ᱛH˜�VZ����*L"��צZ�;� �o-:�:?��X��i�ru�܆�CXs��B �o��Sf#�7��bݬ� 𪶾\���r4z�ȹ;�C��Y�頔�X(�ȼ�ָ��m��Z��"��Z�I3�<��re�� _}D��s"�X��{Ӝ��3��[&{�OJ��~Z�<�9[�86n����/�����B�]l� e̽�NKuu�G�+|`!L�!�� ��f�*���k_� �􃬮V&��KA$C�Q#D
+�W���cc��'?���Cbg�Uk��^g�ٶ�v ��M�_C2/")B�͋`#����9�C��ffU�"7�8�j92%/� Drh��ILa�w��҈�{R/-.ȷ`��7#�A@����F��増�E���s�p�2�]�8��G`��1�8��-�4T��T����to��܃� *TxS�hI�}�|�{*���u���U�IkU�p��cG��.��qBz���&V�b%_IX^b�at"��fu=�C���xO ��h���!W��ۏAr�B΃�P8��T��lы^��Zf�]�W�V���5��/�� p���O0S��{@�h�bĞ��Nyp����%��-��=�]�<��8 ͅ�Lk��(>䃜��O��h��w��<Ykb�L����'u)b{�� ̻},����CY���2������+�sq��bJ�W�ٛ��� �|�:C��%a�Z�d�x��y�|�~�C ��ਰ��&6�� �D� ٕ���*���݂\DX�!αl�sX8���2�Z������l��� ��&�kD�S+F��<f�N�vj_�M8k���E�2�]l� �t��i@��]�u�@{��v�c};��^Z<?\z��g��+���s ��EW�˧��W~��IK�`�i+ ������ZxI�T�-7`�Ϯ��)�T�F8B]�b�(�G�)SW���x��muY�2k+��ܠ j���+���NX��$�Ѹ�C5u{c����]_��u��~���J;��Hp�wmpy��a�sϴ���ƻ앓�(��4��gJL�SVbJ�fp]��w��͒�Xh(��{��H���#К��]#PU��MZ�ڵ6��;fA��<�e���d�$ ��M�0�5�]K7sz�H�cm_�e��/���'����{����M��F1���E��V�x�ȏ�^_5|��^��DK������� % 'J :�uo���� ��|������Hw��C'��g`����Xؿ���ᓥ���x?�D܎�N��‡/�M�I�K�H�ɗ��fvn�\T^4
+�.=�8sM�G�������(�J!/��<D[=-�i�2`(�����(o�J���So�c�} �]��I]<
+��6a�0t��_�׿���K�w��n���n���*����zL��xc���m{ ���+�*�� ��ZB)1=�$�H�~R�#����- �TԪ�m�E��ăH��o��wU� �쏉���K� Z����u�_�C�v�6kH��Ĕ`Mdr�Q_�zۚ��y
+���;�w�}�����N�H�/[�F/[�)v�3'RT��ǔx����iM��,��Er�|Y��^\(���'���f+g����\0��7���/$����'��Z���B�V��+��iZO�*Ш�%JB���B���%R�{[9����
+�p�'�;���\6o���}��%zF�.gPs�� ����`d��ܩ��z�U�,��厣���tA���u>_���+P�0�+�M�d�(������l��*S���ʬ��Oǣ�=��E�\�jók��oK-o�w�\��^Df�]���U qC������ ��DYVBT��X$� 2�<���dQJ 2�Eۆ��T�����@�q�6
+QfH��v� �{�԰����M0&U�ܫ��s�@����I�Q4ٟ�U��἞T\b���)��Nҍ����x�����yc�5}�QV������}o%�,NQ!��Σ෾&U)3�D$���{�Y8/�(��9��� �� �D?���3�L�/����7�?���}��J����="��d�w��3F��xeD��z��j�'A�����������!�;���aSXA��*�r����ר��;�����g�.Q_��� ��~Wr��
+l��R�T��;s��������i�|uh9�@�B)��ý��8~��o�2�̌Q� F+)��k{�����2]�˩�b��,�`���/l�Pf���0mԽ��;�,�@S�����d��b���+G�\�ȺmI|�h�w�G�PN`��{��s�q%���<j�`��^f�Ќ-�*�� ��DɃQ�b ʰ�c6���:����Yʉf
+}�"� V�k�f/���UV���K���qq�C ��KAm�Ue5�&�_��NF�S4�Ꙗ*��e��j��{n�25*�wm�I�?V%�v�x��xR
+<�3� �W;\�,�؟'��� ���� C{ Z�+熛��·�Z�����֪�/wD����ɺ��O � ��[�"�m�l����#N�������2*�X��Q�G���?[�Z�� x�u�+"��^�KX�]]�t�L+�7�t��q����4}�^�'��11��#Y��L<�*�,�&asTC��
+�Ԏ/��dE����l�#,����]�PX�)�8{y�9pݣA�{0ⳬ�~�����
+endstream
+endobj
+736 0 obj
+<< /Filter /FlateDecode /Length1 743 /Length2 942 /Length3 0 /Length 1468 >>
+stream
+x�}R{4Tyo+dt,��R� �0cf� )��&�Y�3�4����ڙ;��C�g�):E[�BmJ�z %R�T,:�;��9�"{�:g����y�~�����:lw�-��0'�(TK�˥���)�J���!��8��;�8l htÄN�R'�%q`;6/g���?���najJ'ѩB8��#(�d�}*��l��dA Z0,�E�Qt3 JB*,$���b~ ���J�"���1xÈ��0���TY8_�lQ1 ��"u@�0�Fp��b)<�{�,#(�Ƥ�l&�L�R��<D��
+K���Ir�pD@4��iFbDc����e'p ��{|�Fq`��!x��"`�2"޹L�ػ��f�oqN�G�����4|��J��� ��w9��Ĵ&É+ H�G!&!�.ɂL�f)��%�|�=B��Mn��9L���;{#.��ř�K9�J�RiO| '߯g����ad������| #�3�@&����UD2 X�K�a9, u�a����US��Z!�އ�/_W'�rj����
+�DNJy��d���}��n?���e84�$��ʏ���]�/����!�j�s��?��4��ͳ{ԇ�~X��w)w�1ﶏ��o��_�;3]-���2A�N��d{�z`����k�>����B�͑y�<��ǚ�N�4�f4���,����-S�)1d��Zż������5G6���"e�`����_ X�G�"{3�軃C���}O����D��!w��Eb�\+I���r�+}^C[RV��� ��4�Z��:�!Ժ�����l|5�glr�.T�H�v��R�p���T�`������cU�swFm�9�U�t��os�$���ަa�MJu���Ԍ����.d{|�襙�RuGT���lk���:�p�x�������~U;/� �M\�����9�''S\�wĄ�
+���Z�����
+OS�]�w!Zd1)80��@5$�Mx�^���xhi;�|}�Fw�+�X��&e�lK��4�b��>�Ѣ��[V窐}r��^��3��s���M�וd�=yp�wo�O�1�߭X:S0�!^��Y�� =��%�e�r�v��a��^�9OYe�{ݭ/��X��*�5�G2.��O�q�(���[��Ro��Traq�4��J�\k�����*��F���*�(n������g�W��e�u�{rG>�МZ�^��l��6��ʠm�?v�{Q�v����6U./����h~۳���ᰱu$����ccL�L7ç*�~fҟ�G�$�J���A{� �C �u�5�|��:
+|�Jc촯��V��4:s�[�5r#Ki�t������n��> C��=�M3k��q�C����A�DMrUq-�zVܚ��:e㭃i��q(��4�rI7��ʣ)��S�QWSO#6���7��ZQ�Ň^���z�V^��M��δ6f��ώ�� 8÷
+endstream
+endobj
+737 0 obj
+<< /Filter /FlateDecode /Length1 883 /Length2 1288 /Length3 0 /Length 1908 >>
+stream
+x�}R{<��NN.��#~�dTf޹�M��q��i��C��;�e�}�y'3�rlI-��J� �d[ݶl�ms�Ӯ6$%�!��ۊDv�ڭ�|�����~��������Z}���u`���T2��V�� ���\ ϷV�a� �P�<�&�y��v��*C��TP�L�i�4�F}OĤ*��`1���0�� �VJ����s�k�'w#�
+x�(,Ui @�������(ѩ @�x4�B� �D� �(�SlTg�Q�&��(.#�, >��%P����0�,|Wsx�Q�`� AT�}�BT�*V�A��I`@��
+b{�y����`����9�C���a0 �c.���1�
+1�ޯ@����xH�|l��B>��a@�4�Oyr���q�[��yD��?�@x�� ��/�~��7�#|W4B����<,�"8_�<� ~�@�T��0�!s�l�� �/B�Q(,��w�
+>1�F��A#���R���
+^UفT���V�Φ�Q W��h9T�C� �F��L.���i"��d���� �a>~�/�JU;���T��BD� +`>�A �_�'���ɋ�f��= �*����r !E��E^x��$�Ќqz���)w�m����9�j��f���('VY��h��B������}���Z�_F�*Ӵd���~7e���g�^Y}����_"f��8�eo_�������"m߾��S /|�Ļ615���ݡȄ}�:�+�ᄇ^��N���QQ�aؽ�j�����DO~y8�,�ЁY�smJT���\�rm��l��1R�����`����1����Oz< �Dڳ��{����h������]� �fX;���%�Zt�V��vH���R���(���q7�ݯ<�Qt�R2p�J*�j�!T���Š�ہ�ɵEg��}�W�y]a$�vyۤ�,X�w���[z�Dk�mū~�펠t�utT�.jNǖ�<�������S3+��iI�$h�����D^�y��؁�3�~��w͢Jh�8�fU���'1Cգ[�_�NOj3m�l�쒯>��-oxZ6:��`�)��i;; "Yѣ����U��X�*1m�A֧/]K��y���ci���E�K��5O��3� ��f�Lg�#�7ǜ�q�]��N���v({�G�^����(m��G~S�� s~��t �wpa�߈u!�_?ְ��H��� T�ѫxq~�+|����@T˘�-a�v��B�#a�G�.`�k�^|dڼ��nYc"L=TsqP�64�v{�WTҽ��77�f��(Q����D�m�;U��/�Y�&�Q��L�;v��?\�jc�v��8� �v�����_����W�%���T�^�s�#C��Qs�>sm�V�� ��3S+*K���K�>�S�&�����v��[gƀV� ���Q�Y��=����)]��ƨ���]��Y���:iK܃�[��븆��s�S��c̲�Z#:��%*i���#>��)�¢��9�"����"�����4c�d�Wvj��:��X�mp*0_ �5i_�n�CM�41۹��Lz�ad�s�Ӄ��Cn�k�&e��*\�.�NMʽ۪U���]�v���T<�Xd�:n�4�3.�����~�9A���*�mvN�&f՛{J���S#K ]^f̰����F����5�D�����}%F���ͩ�%���MSv_�����ءn�U��l˶/�Qn�[��75�Z�1۪S_w8/�}�ݜGH\å��3g.�3�'���?��E��dt<��Θ�tV|�{���-'3"n��ד��1���̖,[1V�k�,P;۔�Q��Mw��x��e-��W��F�`��3�|��UurB~�NƖ%�J��Pw�\@YZ�����BS�Q�:'�FI�`��q�,l��~)�s~��/
+endstream
+endobj
+738 0 obj
+<< /Filter /FlateDecode /Length1 1284 /Length2 1147 /Length3 0 /Length 1893 >>
+stream
+xڥT Tg����"�k�%d��@x�f+1(C2I�LBH����
+h � Ԟ� � *EK��Bt9<ʢ����BA� �����s��������yP�%�b`6��(4;� �P�?@q� ��U("��o$�0O@0��N�7�dḊ'#*�8�2@g� љ�=�C4��B g�/��"��R�d�I�8"˘��9,B��\ $�%*~��8<G�Vu�v�"�?&@�� �a�& �| '������h4
+�a�&A! ���j�E0 �e2)�JU1�"v�͆���(��!b��ԫ&A��?�v(,�`+_T������[�h �t1�AITU�P�4 ���g� G`+DhO��z�I�`�D��<�*��7��u ��zya
+�L�w�
+��\ G���v.n�C~'��rP! � ����ȿ� X�,�!|B�?�sD��/{# �'n��n�{D������Ee'J$s^��L��b���$�}�ؼ8D�|�XU�~�fx~j0,J���?�y׮�9,T$��Ƙ" lD �_ �<I<߄
+`\��p���ޔ�@�{�P1�ߎ� �1�� �S�E��\���8Z�<% "��`�d@�N
++��T;� M��$L�I�m�9�U4�!��|����ط'@MD:݋>\D����ć5��Å�!��a�'u����i���'�X&I��N��1O���ߞ7K{գ��u��7��<NL���e٦��@�]�[W&��(���Q2D��WO����Y���|�k��
+�A��}���߷ G�C���E�sY/��S �
+u{<���o��e��C���7�gFY���&u۷�콴���ԝ\l�po�������B�x)�%���l�Ny}D働��vg_�_��X��(�����- +�dc���[�m����'ၭ���V�����̽�@�`i�UN��Q]��H�5'�&�rYClߵnԏ�|���J�Q>�>��n��`[�[�l��o�hוX��՟W�Nt�Ò�&�[O����[�A��O����쟭ϫK�����):q��t|C��8�V\q��n����Q\F
+�Ԝ��st~����q�h�G�ő%_�n�,��2,`T�w�|_tF���Am���:<��`*u��/�~����T�c.�O�f�ۯ{��u4�=/����#w-Z��Z�r��q�������������(�k�:5�M��‚ц�� �:��1�����6�Y���i����ud�n�'���_*FO�:{h�uw�ƚYz�<o�̄���Σ�}7�C%���/WD�ϔd���ͪ��-d31'��]����z�mJ2#�2s��0�Q�2I0���Y(�fߺ��u�o������̊��~��[�ںkߔ��V���SB{����=V�w�6���0�N���c\����Jy�x��i��`���d��K�&�ĵ���7�����ɻ�SM�k����ʠ��C7Cȟ+��I�[Mo�{��2�v�Jo�ԥ�]m��x�D�}L���l�f�5���0��*3�F{�VyN��%�`������f��]���|����L+�岼$��l:��-���9�3������iӖ0?��U�є�%�'⟮�%׫��~��Sx�69�����j�� ���1-6����Z�C�:ݵ����o�Y;��9r����Ը/�iF�E�8k@�[7$��.]���-.�-M�ݓf�K��8����8�>�dW,g��]jx�0y�8����F�� M���������ڳ�E�.3�9��^i�����>e��n��I�f��o��_�>(Y���T�V�`͸���w֫0T�qoj��YtYhgҺ������
+endstream
+endobj
+739 0 obj
+<< /Alternate /DeviceRGB /Filter /FlateDecode /N 3 /Length 2612 >>
+stream
+x��wTS��Ͻ7��" %�z �;HQ�I�P��&vDF)VdT�G�"cE ��b� �P��QDE�݌k �5�ޚ��Y�����g�}׺P���tX�4�X���\���X��ffG�D���=���HƳ��.�d��,�P&s���"7C$
+E�6<~&��S��2����)2�12� ��"�įl���+�ɘ�&�Y��4���Pޚ%ᣌ�\�%�g�|e�TI���(����L0�_��&�l�2E����9�r��9h�x�g��Ib�טi���f��S�b1+��M�xL��� �0��o�E%Ym�h�����Y��h����~S�=�z�U�&�ϞA��Y�l�/��$Z����U�m@��O� ��ޜ��l^��� ' ���ls�k.+�7���oʿ�9�����V;�?�#I3eE妧�KD�� ��d�����9i���,�����UQ� ��h��<�X�.d
+���6'~�khu_}�9P�I�o=C#$n?z}�[1
+Ⱦ�h���s�2z��� \�n�LA"S�� �dr%�,�߄l��t�
+4�.0,` �3p� ��H�.Hi@�A>�
+A1�v�jpԁz�N�6p\W� p �G@
+��K0ށi���A����B�ZyCAP8�C���@��&�*���CP=�#t�]���� 4�}���a ���ٰ;G���Dx����J�>����,�_“@��FX�DB�X$!k�"��E�����H�q���a���Y��bVa�bJ0՘c�VL�6f3����bձ�X'�?v 6��-�V`�`[����a�;���p~�\2n5��׌���� �&�x�*���s�b|!�
+ߏƿ'� Zk�!� $l$T����4Q��Ot"�y�\b)���A�I&N�I�$R$)���TIj"]&=&�!��:dGrY@^O�$� _%�?P�(&OJEB�N9J�@y@yC�R �n�X����ZO�D}J}/G�3���ɭ���k��{%O�חw�_.�'_!J����Q�@�S���V�F��=�IE���b�b�b�b��5�Q%�����O�@��%�!BӥyҸ�M�:�e�0G7��ӓ����� e%e[�(����R�0`�3R��������4�����6�i^��)��*n*|�"�f����LUo�՝�m�O�0j&jaj�j��.��ϧ�w�ϝ_4����갺�z��j���=���U�4�5�n�ɚ��4ǴhZ �Z�Z�^0����Tf%��9�����-�>�ݫ=�c��Xg�N��]�.[7A�\�SwBOK/X/_�Q�>Q�����G�[��� �`�A�������a�a��c#����*�Z�;�8c�q��>�[&���I�I��MS���T`�ϴ� k�h&4�5�Ǣ��YY�F֠9�<�|�y��+ =�X���_,�,S-�,Y)YXm�����Ěk]c}džj�c�Φ�浭�-�v��};�]���N����"�&�1=�x����tv(��}�������'{'��I�ߝY�)� Σ ��-r�q�r�.d.�_xp��Uە�Z���M׍�v�m���=����+K�G�ǔ���� ^���W�W����b�j�>:>�>�>�v��}/�a��v���������O8� �
+�FV> 2 u�����/�_$\�B�Cv�< 5 ]�s.,4�&�y�Ux~xw-bEDCĻH����G��KwF�G�E�GME{E�EK�X,Y��F�Z� �={$vr����K����
+��.3\����r���Ϯ�_�Yq*���©�L��_�w�ד������+��]�e�������D��]�cI�II�OA��u�_�䩔���)3�ѩ�i�����B%a��+]3='�/�4�0C��i��U�@ёL(sYf����L�H�$�%�Y �j��gGe��Q�����n�����~5f5wug�v����5�k��֮\۹Nw]������m mH���Fˍe�n���Q�Q��`h����B�BQ�-�[l�ll��f��jۗ"^��b���O%ܒ��Y}W�����������w�vw����X�bY^�Ю�]�����W�Va[q`i�d��2���J�jGէ������{�����׿�m���>���Pk�Am�a�����꺿g_D�H��G�G��u�;��7�7�6�Ʊ�q�o���C{��P3���8!9����� <�y�}��'�����Z�Z���։��6i{L{��ӝ�-?��|������gKϑ���9�w~�Bƅ��:Wt>���ҝ����ˁ��^�r�۽��U��g�9];}�}��������_�~i��m��p���㭎�}��]�/���}������.�{�^�=�}����^?�z8�h�c��'
+O*��?�����f�����`ϳ�g���C/����O�ϩ�+F�F�G�Gό���z����ˌ��ㅿ)����ѫ�~w��gb���k��?Jި�9���m�d���wi獵�ޫ�?�����c�Ǒ��O�O���?w| ��x&mf������
+endstream
+endobj
+740 0 obj
+<< /Ascent 952 /AvgWidth 520 /CapHeight 632 /Descent -269 /Flags 4 /FontBBox [ -511 -269 1309 952 ] /FontFile2 843 0 R /FontName /AAAAAC+Calibri-Light /ItalicAngle 0 /MaxWidth 1350 /StemV 0 /Type /FontDescriptor /XHeight 462 >>
+endobj
+741 0 obj
+<< /Filter /FlateDecode /Length 278 >>
+stream
+x]��j�0н�b��"�q�` !%�E��8�8jY����;J�Bwq43g���v6R��p��:x�A3��b�Zd��w�3ݷ^ehn�1r_�n��TD�Z�&��p�'9{ ��u�}�t�\���]�\U��ֿ�=S�Z�A��i�����g�D�X�F҃�ѷ�C�.��<��өR�̿���p��7�EUJ�|��TY �K����{�D��p"`!܂���}b.lA�m��w"YV�X����-����í��/򃗇�����
+endstream
+endobj
+742 0 obj
+<< /Ascent 952 /AvgWidth 536 /CapHeight 632 /Descent -269 /Flags 4 /FontBBox [ -519 -349 1262 1039 ] /FontFile2 844 0 R /FontName /AAAAAE+Calibri-Bold /ItalicAngle 0 /MaxWidth 1328 /StemV 0 /Type /FontDescriptor /XHeight 469 >>
+endobj
+743 0 obj
+<< /Filter /FlateDecode /Length 301 >>
+stream
+x]��n�0E��
+/�E�@C�H�J�E*��=D����Y���v�T��,�g.��٩yj� 2{�j9��X�y��X�|1V��F���35vNd��xl�0ɪRf����r󨧞��٫�썽���M'����l�$Q�R��=w�Yf)�m4�&�[��:>V�!����&ͳ���^XTDuu>ׂ��W�M���pm-��y-����C�
+��IwP�j�%@�Q�P@�K�(@�c�
+м�z����vP�1��P���
+
+��n�;~�`|�����=v�^+�3��X�=��\�@�y�q
+endstream
+endobj
+744 0 obj
+<< /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /FlateDecode /Height 214 /Interpolate true /Subtype /Image /Type /XObject /Width 214 /Length 1345 >>
+stream
+x�a��0�]Kcg.�I�}�4&�BL�3�5��|ROOߙe��t`:0�L�Ӂ��t`:0p���QnU�8��m�ms��T�C0��� @��*o!x� �@oS����� �����
+�@O�zB���W� x��W� ��@/�:A0��)�>Lt��7�����:@0�}s�G0�y�ZG0�u�G�@��h�;M#x�e����=��,h��v,h�2�V,h�2�F�h��6�h�:��h�:��hA
+���hA���h A���h A*���h
+A:���h A:��l���p��j�b��O�|n�_����Xn����U,�L`��e�%�(jY,�\@��}�Yk�(3ݪ���&��q̈́�� �.*�}>5����G��7<R�oVV�DO TV�DOe 9
+1��y ���EF��"j� �h�c��,�� ���u�Ŗ "�WԲ 1�1��c�?
+D�OxQ�8���P��=��Ĝ��dq�S�땒,��`_�LxiQ�������B��������eIN�Ԯn�d'z*��(�4�����E��'��(� �:�Cvf���=�����/6PL��(��306��Jb����������\F^��T������k��ݧ� ���|��_��b>�����쪆@��!~����������g,��]�{5��% J��G�Щ*u%T�P��BH�2�2*?^��*�� )u/V�^��Xb�4?��t�JA9/T|�U���$�j�Ц
+���x��
+� ��[��kC��(��W - �.jo���]*��ë)�mc�����+ݘ�Y�8N��"u�K�l��!�h�'I�]�D���[�� �R�ED;:,���QGyY��ׄ5o ɵ�ﯕ^Uu�S��ˮī������5Y���4Q�r��T5�R�E���c������ta���
+���D\P)Z|���|��><��l��up+��*�Q��<z���Hn�<�ӿv�}ܨ��|���J[v��^aK�ܵyY��T�\NG���nf�3喋\��wn�Fy%c����8&�d_�0~_j���N��g���F���QG�8���XޏD��I��#�wE�pQ%Ш��k�� xI�"��A/Y6�,g���Wp�xu��s��%Ɵ,�L�mߺ��1�oY��b�\p��O��ҩQ�W{BA���!��s���G2ħ�W}u��Ҫ�}"�S�PƼd:0�L�Ӂ��t`:0����\<
+endstream
+endobj
+745 0 obj
+<< /Alternate /DeviceGray /Filter /FlateDecode /N 1 /Length 3385 >>
+stream
+x�W\SW�?7�f�ž2�F�eˈ����"&��b ��R�`���QѢ�E��:Q�V�ƭ/�RA��Z\X}���������~_��p��9�Y���B�[xRi.!�')��'pҦ�����"M�4y�)'..� I�DH���^�D)��B�5v��Q�>�:�DP��C��Ä/�"�2 ���
+�$.���� x�Q^ bd.�eb>+\�+a����x,wWwV�,?S��V���?��\9i7����^��oW��B� !�/�C|^h"`o��E��AQl��SG�s�9��7f�’�+�G�xB�Q�()� ���(r��Lɜ�X�� ��_��p�H�%sf��,?����CB������4�+ �I9�I�(�v�.�z6/2�`;an8���FK ��=�O-��Ɛ���(��>�Q(J��;�BY��Uf�ø����"H9�K��*x1���d�� ��Ћe�2�#}�P�L�8B�R0�|4��u#*@bT�@Y����gh�0KM3
+Pȳ�|'��
+r� ��X>ʄ���rD�B�A���%�#w�U����
+�ͿFr�~����b�0�� ��X��Z܁I�(Na��r���7�%V���H?����T
+c�m
+� C�ML��GD�[�M3J��B>Y!���sҷ��Z炭����(��x�ι�d8>`�;�;gx��h*4�2�;H�5+⹳��^�\6[̿�r���b�\~�b��j9���� ��h�q]���d�S6Gl���ѼQ0I�7ހ.�5��C� Ă�/�Nj/�{�����hϧ���\� %����I����U��A4�L y
+�u<�oDO�#s� ��� !w=N2B�= �U�>1���� !��l�{|�/'d��Ȕ�2�Jg՗ �����.�y�ʝ����]���쇊((�Ǿ������#O���8ނ����V�4ޢ@��c�|�q������A�?|H� �98����
+d>�}�l��Gb�=|�Gs���h����Y4:�c+�2��Sʴf�1�LG���Ę��3�Y3���LC�`�3C��>�c$c� !D2��u/ �a��/ST9ް���#k��d�>g��d�&e �9WE��T�d�$F��ĕ��=�1s��MV-`<6]���(͗fO ���Ze�b�Bh�0Ģ��r�Z$`raN�\�z��Ep"h��p2<dT�ȅ��"��&k�ho�el�j�Ϟ�>�p�(�}��|i�L�%*dq�f$dq%|Wg�;� ���=���Ћx�� 3���eEJA��H�`z��#k�����^����po�EI( ��D�KĶ -A���B��f��B �BG�1t��.�+�݃/Pz��K4�a��t1c��Ŝ0w� �B�h,K�2�,L�ɱ2�3�[�m�v` طX v��]��`�X����S�)z3�eś¡DQ�(3)Y���RJee#�����D9M�H�tQ�Rq����%�{��x,��g�2|!^���ux#T�v�:ޅ��o�K��M�L����Bb9���C4g��D71@��jPM�NT_*�:��E�G���P�G��j�P_�h4���%��M�O[N�J;@;E�J{D����t'�?=�Σ�+����'���=�� 5�Ý�HgH��^� �5�cƐ������J��@�De��.�V��*=*C�ڪ����I�٪KT7�6��S���BMM�J�G-^M��Xm��A��j�jo�u�Ճ�g���W��V?�~G������F�F�F��
+��35^3u��L.S�\Ĭe61�1�i�h�jr4gi�j�hּ�ٯ��e����Z�U�բuKkP[W�M;V;O{��^� ڽ:t;�P�N��N�3:�tq]k�`]��g��t���������z�z�z��]���џ���_�_�\��7�3���48dp�ୡ�!�Ph�̰���+�qFAFB�*�F�Fo�Yơ�9ƫ��?0!LM�M�l39g�?No��8���q���5��:�&��7�i�a:hfnn&5�dvƬ���<�<�|�� �> ]� ��:��OX�,+���u�5`ija)��ay�r���*٪���kUko�L�u�m�66Sm�l��ܵU����n�m�}ego�j���]���=׾�~��} �@��u7���{���u�G����ȱ�����I���3���Y�\�|�E݅�R�ϥ���5ڵ���� 6�'���>�=ۃ� ߷{n:n�n�n�n�;���k�oLԘ6q����'9MN�6鶇��T��myzy�<=��l�2��x�����^�}އ�3�g��1�7������|�s������;�~�p�ɏ���y�;��X_tZ����=��ds�s�MaO�M92�U�o���S!xHxHUȥP����͡ì²��� �{��?A���Xq�k��s��^� "�F�G%Fm��9�1Z�:�25r�ک�clc$1GcQ,7vm�8���q������k�MpK(KhO�M���7�eҔ��I�����m)�)3RR^����I�6aڂi�L��i������������O��1�r�͙�3�g^�e2+w��ٚ�y�gP3R3�f�����x�s�s����7�
+��}B���L��5��Y�Yk��D��Q�8X�Y�<;"{{���؜�9rSs�1�2�Z$:���|�����R'i��k����sdQ���`fAs��S�!w�.�.
+(�-z=/e��b�bIqG�cɲ�ǥa�_�'��緕Y�-)�^�Y�c!�p�¶E֋*�,_�g�꒜%?���ה��Y�g�f�+}���Jf����R��ۿ �qi��e����T�Xͮ��~�����/ݾ����+.��\�mm�d��Ձ����^S���کk�ֱ�U��s���j&�lߠ�A��kc���M6�Vmz�Y���vJ�-�[�my�U��ڶ�m��ͶWo�����;�w4������,��뮔]�_{�PoR_]��n��= {�6x54�5ݻre�|_����|�Ms�K�����O����桨Cm��7~g�ݖ#�G����������]�i�W["[�Z�Z�|����c��j��_yB�Dʼn'KO����?�u�Q��{g���q6��sQ����ÙvN�����]�����G/z^l���8��OG.y^j��u���ϕ֫����x�����?��޸��y�f��۷f��-��{'���Ew��-��}��5M��k��tyv����9��{�����R�˻��_5~�yl�׽�X_Xߕ'ӟ�<�>��M��-��}�{���z�˞�c� �����g�`��×y/�^U�6~�������o�{G������z�Cއ� �b
+endstream
+endobj
+746 0 obj
+<< /Alternate /DeviceRGB /Filter /FlateDecode /N 3 /Length 2612 >>
+stream
+x��wTS��Ͻ7��" %�z �;HQ�I�P��&vDF)VdT�G�"cE ��b� �P��QDE�݌k �5�ޚ��Y�����g�}׺P���tX�4�X���\���X��ffG�D���=���HƳ��.�d��,�P&s���"7C$
+E�6<~&��S��2����)2�12� ��"�įl���+�ɘ�&�Y��4���Pޚ%ᣌ�\�%�g�|e�TI���(����L0�_��&�l�2E����9�r��9h�x�g��Ib�טi���f��S�b1+��M�xL��� �0��o�E%Ym�h�����Y��h����~S�=�z�U�&�ϞA��Y�l�/��$Z����U�m@��O� ��ޜ��l^��� ' ���ls�k.+�7���oʿ�9�����V;�?�#I3eE妧�KD�� ��d�����9i���,�����UQ� ��h��<�X�.d
+���6'~�khu_}�9P�I�o=C#$n?z}�[1
+Ⱦ�h���s�2z��� \�n�LA"S�� �dr%�,�߄l��t�
+4�.0,` �3p� ��H�.Hi@�A>�
+A1�v�jpԁz�N�6p\W� p �G@
+��K0ށi���A����B�ZyCAP8�C���@��&�*���CP=�#t�]���� 4�}���a ���ٰ;G���Dx����J�>����,�_“@��FX�DB�X$!k�"��E�����H�q���a���Y��bVa�bJ0՘c�VL�6f3����bձ�X'�?v 6��-�V`�`[����a�;���p~�\2n5��׌���� �&�x�*���s�b|!�
+ߏƿ'� Zk�!� $l$T����4Q��Ot"�y�\b)���A�I&N�I�$R$)���TIj"]&=&�!��:dGrY@^O�$� _%�?P�(&OJEB�N9J�@y@yC�R �n�X����ZO�D}J}/G�3���ɭ���k��{%O�חw�_.�'_!J����Q�@�S���V�F��=�IE���b�b�b�b��5�Q%�����O�@��%�!BӥyҸ�M�:�e�0G7��ӓ����� e%e[�(����R�0`�3R��������4�����6�i^��)��*n*|�"�f����LUo�՝�m�O�0j&jaj�j��.��ϧ�w�ϝ_4����갺�z��j���=���U�4�5�n�ɚ��4ǴhZ �Z�Z�^0����Tf%��9�����-�>�ݫ=�c��Xg�N��]�.[7A�\�SwBOK/X/_�Q�>Q�����G�[��� �`�A�������a�a��c#����*�Z�;�8c�q��>�[&���I�I��MS���T`�ϴ� k�h&4�5�Ǣ��YY�F֠9�<�|�y��+ =�X���_,�,S-�,Y)YXm�����Ěk]c}džj�c�Φ�浭�-�v��};�]���N����"�&�1=�x����tv(��}�������'{'��I�ߝY�)� Σ ��-r�q�r�.d.�_xp��Uە�Z���M׍�v�m���=����+K�G�ǔ���� ^���W�W����b�j�>:>�>�>�v��}/�a��v���������O8� �
+�FV> 2 u�����/�_$\�B�Cv�< 5 ]�s.,4�&�y�Ux~xw-bEDCĻH����G��KwF�G�E�GME{E�EK�X,Y��F�Z� �={$vr����K����
+��.3\����r���Ϯ�_�Yq*���©�L��_�w�ד������+��]�e�������D��]�cI�II�OA��u�_�䩔���)3�ѩ�i�����B%a��+]3='�/�4�0C��i��U�@ёL(sYf����L�H�$�%�Y �j��gGe��Q�����n�����~5f5wug�v����5�k��֮\۹Nw]������m mH���Fˍe�n���Q�Q��`h����B�BQ�-�[l�ll��f��jۗ"^��b���O%ܒ��Y}W�����������w�vw����X�bY^�Ю�]�����W�Va[q`i�d��2���J�jGէ������{�����׿�m���>���Pk�Am�a�����꺿g_D�H��G�G��u�;��7�7�6�Ʊ�q�o���C{��P3���8!9����� <�y�}��'�����Z�Z���։��6i{L{��ӝ�-?��|������gKϑ���9�w~�Bƅ��:Wt>���ҝ����ˁ��^�r�۽��U��g�9];}�}��������_�~i��m��p���㭎�}��]�/���}������.�{�^�=�}����^?�z8�h�c��'
+O*��?�����f�����`ϳ�g���C/����O�ϩ�+F�F�G�Gό���z����ˌ��ㅿ)����ѫ�~w��gb���k��?Jި�9���m�d���wi獵�ޫ�?�����c�Ǒ��O�O���?w| ��x&mf������
+endstream
+endobj
+747 0 obj
+<< /Alternate /DeviceRGB /Filter /FlateDecode /N 3 /Length 357 >>
+stream
+xu��KBQǿj!� ��CÛ��U�A. j E��
+����W���{O�h���2h����� j���ɩ���v�{�.�˹�����sﻀ;�2VP�-#��K��-�� -�T�d1EY��T�{���>M�Y�N�8z��+_ެ�g��ї͙�~�C3,�%+{|@0�R�5���g��5�i�%��f�[�r�/_��r�"�&�ԟ�7�(�'���`(AED��l}��� ����'F1!G�f �"�w�^�����ɽ�����_�r�M�b�5z��(06�7�j��8��|�:F���#�l��Hخ��q`����I�{tj���rީ�7�V�)j�
+endstream
+endobj
+748 0 obj
+<< /Ascent 975 /CapHeight 722 /Descent -217 /Flags 32 /FontBBox [ -576 -287 1987 1160 ] /FontFile2 845 0 R /FontName /AAAAAB+HelveticaNeue-Medium /ItalicAngle 0 /Leading 29 /MaxWidth 2225 /StemV 0 /Type /FontDescriptor /XHeight 524 >>
+endobj
+749 0 obj
+<< /Ascent 952 /CapHeight 712 /Descent -213 /Flags 32 /FontBBox [ -951 -481 1987 1077 ] /FontFile2 846 0 R /FontName /AAAAAC+HelveticaNeue /ItalicAngle 0 /Leading 28 /MaxWidth 2225 /StemV 0 /Type /FontDescriptor /XHeight 523 >>
+endobj
+750 0 obj
+<< /Ascent 975 /CapHeight 866 /Descent -217 /Flags 32 /FontBBox [ -1018 -481 1437 1141 ] /FontFile2 847 0 R /FontName /AAAAAD+HelveticaNeue-Bold /ItalicAngle 0 /Leading 29 /MaxWidth 1500 /StemV 0 /Type /FontDescriptor /XHeight 650 >>
+endobj
+751 0 obj
+<< /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /FlateDecode /Height 587 /Interpolate true /Subtype /Image /Type /XObject /Width 512 /Length 13388 >>
+stream
+x�]g�SE׾[�K[:��� ��D��� %��Qy1�X�(
+E��(��#�#4 ��,��R�βl���&�7�=s�$gl��s�y涙33���-۫o�{j�i�e�m���t�ܛ�^����_Y����*�����v9�Ƿ�ٖɦ�F���U��635Q1J�v5hw��CF�,��_�׾W���`�fOy٠����
+��nL��9���h����R�ٻM�m˾������:@_P����Rk ��s��'9r����I�QAO��'��푗g���9x�����O& ��\r�NA�OL�⏽W�s�D���Km�=~Kf�ф���j����W���u�CN}��$�Ĵv�����ӱ����k��0�MJ������Z��}Iy��ZP�q�u�4$%��^���3-�|�m��tG�D�O|�Ҳ���8}���Z&�iի`L1�]һ>m��2�d��]m�>��
+��f��d ����\V]r��`^|� ��J��qB�Z⟝�W���⮚{K.��[[�����-���<�0$w��n��h���4v���f���y�-�Q��6���[%*��t��#�ɺ����@�ǦK� 唛'm�w=!ԇ�^Y�|[�/n6 3��c��@@^����&�L�|l��r���Z`L3�i*�nQ��J�x��q�155�z����G�#mJ˱���P�����'�R���\�>��.�W6q��P�� �q$�θ5�K �\F���Y �{������q��mI��!+�$eǭ8�
+47�$�AYp2� ���K�� e���&�z@=îk �n}5%�@;� *i8n�V��:� /�4L(�T�}w{@�Q��j(�eB`�`�V��1�� ���7֔�&�Ĝ�r%J2����6��8 WjIF��O�)��`c �/ghE�6K��ϡ��I��I����N��}i�@�g��}LՃS�<I'2O��ܱM:KA�4��sHc!H��r�u(z@����/)O� ��Z����M��\�;b���Kn"(��r{ +�S ��/%9���W��@�,���������m�%F+ş$�4�!�H�&����$�f���'��*���`ˎ�%&����k<4LJ���y���֝�fk^���NH�+*N�  �������q�;@�9a ��(�x L�PJl�l�j,N��C�**��gU[%>s��i0����Z��&b)��O
+�+*f�~LO��C3+&�t��K� P>$��'�+' G�6�� ���.)� ?D�@0m-n�=�"���0AZe ?F��`]7~Ilѹ���5��"�g� 0C��$�Z�� �9I�5�
+U���q`���7�:�k 8"����p4 l�� ���j,u��=n��20J|�
+´�,H�d2A��2�J�Yr��"�|���]r p?<��[����i`� ��E%�[���?���aX�%9��\�R��e`���#�Ё+��j�%�Wʡt����/p� ��/Fʡt����q� ��)'�P:�D�T
+����Ur �=A�%�Ё'�H=��i`���� l��z@��[��Z���ɭ*jY�?1CrE�K���'����:0Jb.6 �o��x���/Ë��`���䟸�\B= K�� �O6,M�$D`6�~���J5��Iw�ʎ� vÑ%�l*�N��}�a���"�T��C��3�(��t�t�@2^���?Qo#^F�5R!�!��O� 6K������d�I�&��[�A`Op؟�|U0k�4*A*>�m�{(��z| K�@`S��t��ߥP
+2qA��zt���ҿ��T�=�W#QMLy�Z�����>���E<�+�"py8뤼���*i8 �?��7��z q0l@�����٢���� ��F��kL�~3t�[�(m2�G���'��ɵ����e%�3�yfι��R�6D� ����4�#��(�@��Q���Gf�٭����TP��΅GA�B2�Zj
+���p�B��ژ���4�
+N����G������Cu�9��1!p���� 7�����1�eF��ޜ���w�U�� Cd�0u�o��� y��W���EPW>\}yRzW�s��Y���^+�kh���;���T�$����P���Z��A`#yY?kGH1�,��~ �!�� ���?���H2O֮Bɼ��$�� �����鸓b�呬����V�2���b{'*K���Q>��Z���׼w�6� A
+�͢2��a �#�n���NDf �:R]*��f����hE����#sD�vpT�����.�B�;�d��M��!����1��ty8jf[�ICg�,�<DS�-)U〛 ��f�:ut;y�v_>�I�Fl���w���\i�kb^�OG�/��F��f�˜����9!M�Aj���>��zB� ����+�S�Jv--<��H�[���o�b�.p�<��]4W��ϑ��wŠ��T�m|��Q�.ĉg�8�і�-1� *s"��ܖ�:���C��ԓ8�^K�����(B`��+ �,Y-�o��^������%X[��`B�c���0[V��D�o�*���Ґ[��H�@��$��c/Ew@��@��u���Wj��Q�N���[�܂��v����iWO��U8{fZ�ŝ����2�U#�9\I���hf��;��� 8^L$��&���+����E�z�+я����O�R-R�(���=�&u����� ��)��H چ`J] <
+���ym:��0A���]����so ���r�w�OT�3����C/df�cG}�u�A�/6����ap��g{���Y�h.z�J��
+-�u�&�R�j-.�U ��zlz׽����"d#�zM H<�̸c�o�BZEL�o������I�l9o�틄b|�֜{Y�KA]V=�[~�lK��0�9��1��MI����[}�H�t��n�=u��v:4s���6�ky:�X��UzKnZxq�v�e5��ڞ�����c����"��{*� �M��+ŋ�|�pj*�.xcP+j�Q�Զ ����c�,ί��U:��#�} - \�򝾋^��7n 2^��f;�H_���V��h?�����J��2�n�I�CLͱ)wv���e["dU��,w�.6-�:m&�:�a�P��o��CS4zL�P�#V�݀�g��#�� �n��:n@;��vx���H�Ve.���6���\�"z���y�����c�bU��� K�kw�����[����p���y����A�G|4�X�I�Cς˹zY�d0���Ҕ�]����u�~=��aw��N�%�4\[k��YX��2 85[� �ƴ���zH�A�3���X��Go�6�[K��v�4�;p^kW�2���@%*��ݭ�F�cz{�m�B�Z����B^�h� ��z���:εM}�4Z�������ӓ��A��X���Py��������nf�l�_g5�s �i�$�3HlO�y�F�>��7�� ��L1��]H���k�.jc�W�2��;�!�?��,���� �d�!���j���$�j�/k}�A�Լ�>��y����%�E,��#�Yij�3�|$/,{�v��Ǥ�Frٵ�M�C��,��U^�۪����SO����χŶ���8�Li��b�K o9�\V��=l�]v�h̹'�� �u��f �9F�'���Nɶo��'�Ha��/|�=A��)摑�kA���V�Gn�֔�W=m�(\1}T�$�d�5c�$Դ��Yb��f�$�a}�o� ��k�t�|�������5wv+ү�g�L'�} ��]��O��Zc@C�,��r��Dzx���f�<�;��l�3(N`���<k��8��ŲT�^j{��^�j��D�Z5Z���m��|s�$T�UE^��b��d��d�Ti�&�Ý���bi���գ[�ا��G6��3x�%�d��>��4��-�`G~�4^>������W�y���$xF�hֱG�Ǟy��tn>�tQ `�p�w�z��l�7'��j����[ffr<3�23���V�� � 5������~r���= �c�o,Ɯ)����R`T.X�. � � � � � � �C�º�s����Iq�@���- ۚ��#��T4l�%�V�pCD�j�H����x���� ��f�3ҩ�7,<�7c��p���bU� �G���`(es������Sy�� �W�=�7-�v�3��ۙ�{(<��1�C�S&�M�"��� ��5�
+�b������-9ʯ�����S3�� �.�< � ��P���=��_9(%'+��x��3��b�=4?�V�}p9�rPJ>�͔㓆r�&2(�Wȁ���]5�_9(%e:2��p?��|{Dq�;Osg�y�br!�F��YU�v��@KY��3�� �!��(7���X ˍ�q/kRf[�8)A����j�Ⱦ�P�� �����R�&�av��O� Єʞ�V��� �+��M#�C�}*�U���|E>b�!����&���![N��#� �_��4;��5\e��*�&��R�i�o�mW��O&�0��B���*�5Mȳ����u���K҈ M��&K"��(]�ô/��Ofrs�,t�Ɂ����}��d����F~�S{|��!��~4��p�ɬ�׼.�t�Y�@ѳ��,:���eZ'ԟ9j��~=���nQ����5��7m{����W�a�I���VP:q�,3�H�D�B�ʁ@���uG����%8��6����6A�h��P�oa�7�i��d�!.sjPx�o-x�C���J2�Ua����QUx��p�B����W�S���B9Qd�8.�1u���|^�d0,FD9YL^�Ԭ�a�"4a�`����H�x��H��O#��@�s4g�=�z�I��_�� ��R~���P=�qT����%#Rv�{Gdž��N�+"M�G��R���)a 2N��.�D��*�jAԖ�V�D���P$Ɓ��S�k��[E�ۈ p bH�cN��J6oCݠQ���mZffGA\���a�6g}�L���oX�Τ-}��E�xNA<V�=Ţ�@��)h[��9�E� ��B �<��1S>@�2�孉f��"��a�x ƛ�k�Қ�7g�ة�M�"�����㧤T�M��#@N��TN�G#l�����t'ϳD�oЉ&iK������&J� p��ja�U�YJJ�5�:�6�6dPt�BR ��T��:-�[�ޭ.hifNlc�;J٦3�]�wU&B�U�6�gf�!'�t� Q J-�HfM�u�ƂN���b�>�Y�̾�jCA��X��{8�@� X"eD`+�dN�� ��, �B��)�h�h�9R��0Ԭ�&oaKrye��*���!�𢗻P�>�Y JNy��� d�a�hYXC���������� �[}͹t�� 'VJ�ag3�{ۉ�+O#��mJ ^�
+G��/ύ\s�Ĭ��M��);2����ߗ��"yc�����4A�T6�~�" V��iY�8�߄���١f�؟��()����B��(˥n6B�-*ؘ�
+�hϨ|ƄVV� ��x�=����Ee�|�҆��zT5Bc�)Je�`��y�5�lѦ�f�~i@[�>1���0b8V&x���~�κ�i���z�Rs0 @��"I.��� �7��s�>YY���Q���Ƚ\�<��������[Ӗ�
+Sj�Q��O@k$�!�s\=&v��[/�S�v�(�@�,ܛY�(��X���Г̘�b���k��)��\��E�u����o�˩�POq��6o� �"P0]�S��%t��ذ��Dq�N��P[ �Ȇ2(�������n O�W��o,>-i;�$��X��:�b�m��_�1}��������E�,sk���/���^�I��@��#��D ��UJW��V+m���we��u��v���$�Pt�K]����'�'�<e��'��5�6xMut�˹z!����D��g4�LU��hOtC E8y�����ShH��1\��荢)��#m �$�)"T�6��ɒ9Ѱ6��"W/�<��Z �x�LW�C϶Y#7�����i�Ms����Z��؟�9Zh�/-�Ѝ�fml���@��Ҳ�ᓗ�6��G3ݔ�R�EõO#'�9�C����6��P�ؚ��]�C�8W�m�6P�7�O� ��mݦ��v䷮v�)W��d=\���{b�؎�h%ټi�H���T����Dg���Ӭ��GƷ��K� �`��e�p��6���OT��ߌ��͵��fIw���R��7]��Jo�T�A���b.7?׬mH���4� �s�zs���ip��$�Ӡ`�;Z�#��p�j�Kz$��G�9 Ekveb�����*aS�]y�g3�!.�夣�5�̩Cz�7�ڍç����%@L�ί�=�G�8�Yj�id_�q�"�Y��|rVf����e�/~�Ϻ�&m6��<2bD;�EpqjS�@i�g��?�P�_*�NH��՟=��8O�5tN�`:�iN���ͭ��1X��xu//t;,z����h������h�+��&h�+�����3�7;Q^�,�����?�#�R�c��ݠb x̨_f#Zͼq�q���ؾ"n[d}�Auz��^kt����e� ��b�,��`�庱ؖ�(ߝk3�5*�Z�{F�1���C����<�Q�
+p�R�c������;���%������Y汏��YF֫�hi����c��͙D%R�t�3h�������j[�w��G��^4��֋#��j&�g/`Z]�]����ǒëRJͼ���߽��Ǚ,���ߜ����޼�B�m+J
+ {w��˝�9�[-��G�ޡ��*S�,ʆ�L=�)��#m:1 �P�-�^���k�R~�qçDM�e7e�×��V|e�!����;�9�U#��!~�$O�4�ٍ�#��Nt��"�&��-�<n�WYf�����a�G;� ��u�<)�_�צC���WB%��X���O߽J=6}넢H��4�Z\����0ƴ�M2ȱ��󈤿�%���/�D�� ih ��k�/�Nm��}%�Q��*�PJ��[]��h@ˋ��.��z{���YYZs.�m�d%G.e�����m�t!bR��&/�b
+[.���wۍ9��2��h�o�� �(��CɎ�^t}¿�����;Y� ɘ$_���0�Tx̶��Cdi�6��ãSm��<�ք2l�}������~σg�"��� �5r��ivy �:�͙��Y8�C�}b�����ܝ��K!�uT�=����I2���mfi'7-�h�V��w��j����ޙID�S�q���: ���Z�9:����&�
+�$�Q��q9�����rz��[9CٚY*���[�����v�+L���[���Շ�سs���Y�{ :v�G_��b�a��F�� ��w�Z���c�+F���nM�Z���"3������";[�[�a0�b��KǒU��ǔ^d�~ ���0���{%<��@@@@@@@@ ��sL�|����9���T�3dq "�X��SKg.�{1[� u�T�C1Kq��������8�/VSW�G�O �U&ԏ�o��� Ǎ�`h�,�����P�7 ���7���1!PJ��iFLB�r� �O{���M�И�J���<�^�Y�Ɏ@1/�;���W劫ʜ�ϸ�-U���DF�o��Z����9~���¯���E�}1;-�P\ނ�|�Q�*{�LG��JU"Pl�0�4�s�iJ�`����g�!p�� �U��}EVG�G{�lԌ�x�br!�\�#�U�U� V�W �i
+B �Ӱ���2Oݨ*O�V e�$��bT��[��$�n����#��2�v!�Ox�b� ���~�Xî{>u���'؋�sg�-���G�uZ�'p�E�V}<�IVe5)A��&���ˬ��^ -�9�U6���R���8�G�z��`kv�^����ngS�3�RC��,%����7�Ĥ���=�5I��P'~�b�4k3���c��'�ڑd� ��� �hXַ�?��ۜ��t�9�w8�F9s�����F�2�3dJ�-��>�_�%*{\P~�͢�C%>젞~�:���� )��u�D�n
+��w���(JUW:~-�H_�cv4E��ť��_���h�M�+��^$������vV�����������j� D�Z?�Q�
+�����IT�w8�/�W��_�/#�!�����%|�^�:O��ld��{��VBw‘��(ŜB�;�C�,�# ��QZL���af�$G���r ����SQ�����F�vp���cB_����J�?��t}l��^�{><��t�y6:��-*2 p��Cq���S���X-W&�ɣ�<�������,�A2����g����\O�7>�dk�5ÆD�2V+iX��(�@���-]A��Xc���%��Tx�b\�\R��3�Ɉi��T�|�{�t�����0+�U8�>�
+@��Q��0�
+�*�HcNdғ��� P� ����h�؊�+OFC���({� WzD@\�%�6ҢG薖DX�6]�Tor +��5Z�+��qM��>M)#Po黤�y*��������>�������_��C_9�`�[^�k`c�]1��z��b_�ŋtr��%��,�(2q~�����(8N�X��ykx7� ��~�/&�֢�f��>���?� �Dk�*�e<����K ѐK���6��x3Q��7e��D2����Fd��vS�5IC����CϢد�����
+$Ƀ@��׭��NQ�xV�A .����Ȍ�/j�Q�p�Eh,)�#P4��\�=�*J�1�Nɹ�
+��S�@�U�5�#��#�V����ٔ�F�Kr�(s�o!� R�U�,ds ��k�=�����V�|׎BK��P;6DmR�X����ޢ!�� �+v��ƴd��H��d�2��M̰a :|��fy���bx��~Mm�kT̅�b4DH����e0�5���9mI��#�$�T�Mz!�|M��\p'=� �j;�*v�$� I�ɽ����dy� �����&p�R��--ɬp������%�"�����M#/|�|���Y��R�=��Z�����{3���c�[��0̖�n��� �_$M�`��`�]ܛV�� �X�N�;�\~��pp��]3qo��g �;�� �������,�o@eɏ3���S�^��a�+C�6�lr����!E~j��OP,�ٵ��rU��i0uSh0�5�vX4��U��ꃻ��a�J� ����R[kWtw#n���\}���S�t��|��fT�c���3� 2��_����M�`3[�h?�V^���m��c��A>�,sʮ8��&ѯe�LBf�*+Ci��l��:(Ɗ���rD�����f�N��j���3�WMM��}/ږdL��4
+ݧ^�)�����aS�"�Xz��m�9V���צ��d��V��Պl w��Q���9�L���6d E�5�_��ܮ��)�7=����x#�/:Mj����������[/f̉jRz�7V��f�#᳊V��3v�Su�O�>h��Y� �j��d“(���f �e[� +2VM�G����&dFj��ېwOV�� 3�a���`��˒yd��n%�Q�}t� V�;�%״G�/��B����*�=�X?H榩�VWR=Z�sP<W��hr����o5E���3~�>Q��qpWg1�l��"Y� ӹ2�3�=��B��;��7.*��*����N�P.R�����nj�}3�,M�EG�Ly�c̃)$��Z:�ܝ��]آ�(����\o�=
+]6��)C�cKV۔q��ej��̵��:���b���}�?x�V��̭�S߀d�_���h� ���<���1X�8�N��u�L:5�&�j��PzD��]��yFmo���<7ձ1��lq�[\�7:�>w����Ra����X:��kg�c֜H�$�����{s]�pd�a��c����ߑ��5TȨ�^���*j�mQ5���L�Fo�:\^zB��i�u9�R_�$`ڿ����"�]�Q�����x��9�7����p9��s>�0���I��Cnj8�2��Qs�*f]J�e1�2��z���&�g�n�[�xX��`�>�� C5�a;a�V�%�ۋ�����W��A~��j������ �'Z>��s,r:�n��`aa!C�(�e�zܛ��E�y�O-����KvCy�\ K��q< ��vZp5���U�&`$lV#�-n>�*������h��wk�O�u�׏(3�j3��x�g��m����K�}F��MN� ;Bo^�.!pfŕi��L'Ȯ���--V�&��Q���EvW�ύݩ=�X�oO��~�X ������H�t�O𓗋ּ���l�ʯ �Mq����M~�Y�h1?p�.��c��7�ÛMq����Ϟ`����҆���Pp:E�ސq��FY�-�]��ת|�Ŕ��Yy���yAznyk�_:����P!����=��p�qޠ$]A�����'q%<dW=�c�����]����v��7a�U�Z�{_��x��Q�;�H�@-iG ��{�n�VA��T_=���I�>�d����[�����ބX�BLj2i%�W�1?ٿK��ؑ�v�.�G�5g�a��� E��o�K��n���R�8��xܾ������*�GZб�^��s��� ����F5�T9:�ٷ��ab�3.ٱzѷ3����t�.��Bzf��}7�g�Y�zǑ �4�`A�����\4��ѻ&�h�^��hz�o���5 8�Vmk��5�̹I�S����1&ӻ�l�~u�w*�9�! @@@@@@@-��N�X��z"��Ɖ���>n��'&�����U��1e�2��k H��'�-7U8� -�)P\8�#�gn ���5<�n���2ø�S��������|�R�B�"�!D:)�5Nf F�%�᠂�B nT���5?�E$ԍ.��yrhd��,��<2���}<e�R6�@�^��߲��0�䐖��Ň���R�"P�ؐ�F��|d>玠��[(��{f3�rPJN~�!t)��å��PYr`6W�@��e��A)�(K&�x�"��I��U���M9�� �\�(Ah�3`7u�'P�O�?|�gA(&���� ���~2�A�c��} +���a�V��iUekRf �)A��E&A�ط
+vE~�db��%( ÁAh' ��'�eK�Pj�?�^<�;� `�( ��&���9,��'X� ��~� ��⫶��a�&���Ӫ��(ngpJ�J\}�S5@�@W�� ���b�ώ߅y�=W��NB�AT�\&�ʈQ*}��~/��B*2�7�3r�/����f��`kd��� (��s��\���j ^����U��0�PO�jb��G3�-�%���Z�㧳�<>%���QKT�SA��kDՇJ|Xq��0�����AVȿ�hXfuXS6��@�P<����d+�� g҅�E������1�R[��c�( ������l �`�P�` uk q���W��@���>'�\n�~>�=�
+�;�4V�����Z�CS�bE���.7L�\v��pIh����F��N/agET��*Q.������@���4�W�=�0���A�=Z��q]�GF}zR�#F/W�'h삉`.Ԅ珡�ٗt�S҉o�}��~l�1Βb
+�OgV�WbDA6�� v�Ց>��_@����W�d��?OQ��W���i�j11Ѿ��h��u�BlM@�O�'�U_$����C��"��( �B�S��lJ��x��҂��� �����ߚ�QжT=�t���|��ﭠ��#�G'���RU죹(7�^� #���a�@����*t�b�v�GC��i7��'���" �P��zW�S��uLv����2�J\�BقD�������؝T�M��߇'S� ��G
+\�+�~ ��;�'�W��w�l��NtB�Iʻ��h��L �0{��n�ov!�sh��3s��P�>��� �,��Z�S#��� .?`�6+EJ�N�� g�L�}��S��qi�!��k��
+��{H�^���;�|��bZ6G��%�d�(~��:����#�{=7��J�۪|k�al��H��ѥR�p��0�.�oz�G�)*��D��3���N�L㑕���Ii�����H������}��d����LQiͭ�� � �8]B�+�Lc3�⥤f@�Ɵ��uY �T�xD�6�n&���{�b<�pu�� ؘH����C"�CO�o��d�B���/�7�Y>Qݢ��Cd�^�y�J�1V�k���H������b�U@���?]����+��w ��@.�����6A\.����cI�Rj"*�$=E���~�S��>H�H,_;F���0ˬ��F�ֵI�6nv�۱��L��|7�ўc�e��֚��K����~q��=ܴ�K��X�%E ����k#O�#C�K85��y�E�(��GlZ��{p��o�� SD"���vК�˷�n�q�rX9@G����?��ݸ�772����>�/������sT&'�PI�+u[��O�?�h,n��zU1�Mא�xMk���@�>�0�]��u����������T����X��q�z����1�aT��g����Lkq��!��zl����3u�:����b����`���gi͹I���˪W�w�N��yĬuI�@ta�'�;�=�'c'��x��0�������X���*z6�L�H����k�N��"��4F�+�$/�8�:�M9���^�5}������"O��֤�n�b:k��ds��A��a1h"ZC��ip����sY�kW��K��g����m’�}��-����vL '��j}顛�$3C�z�Zk0�r�� y]�I�QՕ�����@F���|u�wK�������-K��^���m�+�@�l���Q&Ϛ���]�H� /��Z�x���~X�Ά+]I�y��<�[�]��cLo[fھt8~w�t��z�ޓ����;ƕ@�/c�۽�����m��mӘẻzu�n�x���?�[M
+endstream
+endobj
+752 0 obj
+<< /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /FlateDecode /Height 512 /Interpolate true /Subtype /Image /Type /XObject /Width 512 /Length 5305 >>
+stream
+x�ߏ���τ/$ިL���Iſ�����1��A���zÏ�J!`�Q��M�Ђc/�%3�*`�J�E���3EA<��;����˕}^.�㜵��]�3��sZ-����'�͝_��kg��M>7�1�k��թ��� ���>��������
+���W:�6N� [h�go-̎.t
+lR�ز�[nn��ၐk޼�0�4d�վ��2?� �0�T���ޱ9?�)��Ѯ���, ����v�򒐍��BZ��̺.��BN>ӽ�&`cW�Ž��N-�c��n9�{�肅m�Z'�7� :�菑�n9��}�� ��^h]�ޘ X0�Т?F&��̷{�^�0�{��`a>`��S@��1`-�����߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱�j�o��#�߱��j+�����o��=���|�����!ԝ�<�ҩ�C��D��W8�ۣƚ�כ��{�n�y�޾w�����׋@�`�g��4_ �|����B��o~�aO�k_�m� !�'��ŒQ��-�ͤx��4^�����v��������/y�ݻ��hQ��?Ylh��4^��O` �DsQ~��FJ��B�!Z�"p1� Ij�b^��CK�I�Zw��T#�D���v�[��k8��aC������O�Q,ຫ�!�V^��B>��7.i�t�=J�|@RLjY�U�4��� s��-�{����q�Hك5�4��n�9Nƻ�{��8�q�H�k�i���8�(#p�㎑2�5�4��5�9N�e�8�)hs�30�q2�(%�q�HA�k�A�a����F(�;F
+�\�  s� �5�@ p�1R��g`��d0�QJ�㎑�6�<��'�q�2Pw�����8�k���c���5� �0��`\� ��#m�y�9N�e�8�)hs�30�q2�(%�q�HA�k�A�a����F(�;F
+�\�  s� �5�@ p�1R��g`��d0�QJ�㎑�6�<��'�q�2Pw�����8�k���c���5� �0��`\� ��#m�y�9N�e�8�)hs�30�q2�(%�q�HA�k�A�a����F(�;F
+�\�  s� �5�@ p�1R��g`��d0�QJ�㎑�6�<��'�q�2Pw�����8�k���c���5� �0��`\� ��#m�y�9N�e�8�)hs�30�q2�(%�q�HA�k�A�a����F(�;F
+�\�  s� �5�@ p�1R��g`���X���D�/�5�@ �ڙ߶��s�;ˎ�m4����՞k^}d��1��YY�������h�7��EU��_{��)jC`K��W'c����*�կ}����!�E��W���k�7���LW����K�.���ծ�^��׎o�LW������� t��v]��~<_� �]���a�ǨJ��P���6�F��y�N=;P����Uڡ��^r�P;� �43�*�����8~�܌㎑R2e��1�q2�2*��#�d�~oc��d�eTr3�;FJɔ���0���˨�fw���)���a���Q��8�)%S�{�'�/���q�1RJ���6�9N�_F%7�c��L��m s� ��Jn�q�H)�����8~�܌㎑R2e��1�q2�2*��#�d�~oc��d�eTr3�;FJɔ���0���˨�fw���)���a���Q��8�)%S�{�'�/���q�1RJ���6�9N�_F%7�c��L��m s� ��Jn�q�H)�����8~�܌�6e���0R2e���ٸ�Vr��g��f(�3����4�&���&����^�}������V_��S���8`��'+D׼���[T/��X�슗�F�k�9��������w�����1���M�\�슗��}���8V!���b���h�슗O�>E�pS��?�V��_q®7>�������o��F�@o=P���5[ǂ?`,�q
+�`=c[�v�z�r�B@,{�9`q�S�{c%P�QH�e/=,�q
+�to��9
+ ����5N!�@9G! ������)ҽ�(�($�����8�@�7V���X��s���H��J�����^zX\���X �s`�K��k�B �+�r�B@,{�9`q�S�{c%P�QH�e/=,�q
+�to��9
+ ����5N!�@9G! ������)ҽ�(�($�����8�@�7V���X��s���H��J�����^zX\���X �s`�K��k�B �+�r�B@,{�9`q�S�{c%P�QH�e�2gx��U��Ɲ�:�s�Rr���Y���V�ّz���Q��.u�/�a}��5�����vE>Ck� 쨑]�~��c��զ*D׼t%���K`�Fv����߯��f�+D׼4�-�%�����*M`{�7{����h�n/�_!����?nE��<]�����q�іO�0��֒'�W�>]­��؎��_�B�p#-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@��7 �(&`���apu-4*1}�p�"`��W��@���7׽0>��p�"`�v&Ʒ�E����h�1�#K���GfߢjfV_��G<A+� L/
+�x��%*E`K��ɨh�5�����t}��E�"����h�5��������"�i���h�5��������VS��D�����'h�3������aϧ�N���5��4� mx%p��H��ë6�Cy=��^�v�V�򱅲9{�s�s�+��{�4�e����u����^ ��+�Q,�l�^����J��^9�b�es�z�(�WBe��i�.����0G9��*�WN�Xvٜ�^�9�9�PٽrŲ����:�Q�i�����(�]6g��a�rN{%Tv��F��9{�s�s�+��{�4�e����u����^ ��+�Q,�l�^����J��^9�b�es�z�(�WBe��i�.����0G9��*�WN�Xvٜ�^�9�9�PٽrŲ����:�Q�i�����(�]6g��a�rN{%Tv��F��9{�s�s�+��{�4z3{���0R6g���ٸ�R=��l�� �ٌ����7�gh�3�7������S�-��>�π���_c���<���KT.��X���QВk����?�6W�Z�����'h�3�s����|���8����'h�3��p��'=�n1���l����0v�������7'����U� ������c�0���@��������y�1�� `�rN�յ@ ��(�M8F0�Q�i��rŲ �(&�9�9 W��@N�X6�E�0G9���Z �i�&���(�4\] 9�bلc�圆�k�@ �Q,�p�"`����pu-�4�e�QLs�s����F�l�1�� `�rN�յ@ ��(�M8F0�Q���pw-��i��O�1J� `�rN�t9�bٿJ?F 0�Q�避�嵐L �Q0����k�e_��9��� d
+����K��h#+ʽ���t"��:���{�����^��k:�@n�p~�=Z��~r/`�5�H �N8?��c`?����N$�['��x��1��� X}M'ȭ�O�G��O���� �� �'ޣu��'�V_Ӊr����:F��{���D�u����h#�ɽ���t"��:���{�����^��k:�@n�p~�=Z��~r/`�5�H �N8?��c`?9�wM_��k:�@N�hv{6���PG����pX_�BF�`�����m��������H&�Q(�� M�J�8~%��VR d
+F�����2b�()��ň�ZI$p>�P0���S�A�ߠ������H�XF�`�O�z��AIǷD��J"�M����O�z�e����F��J���f��t��#�u�s~�~x�”���s����H�E�8�C��� k�?�&l�x,�N<|,�����ʻ�D��pᾼ6#�G��&J��A�W��Gh>�����������ƞ�=�����;�W�����t���Hzw���;@�Qhk�n�����3�2b�����o��/#���\���o���w���k4��\�c��^y�����4F�Ƒ�ys]�g���.�T8�n��w����ꃛw����~k'�.|t��͞��>�K��� h�{?��`a��Bk��|��A���1b�Z�)ɿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�����Gȿc9�^]���~���,�К�޸�`�)�E�,�<�U��~������ ����N-�cdm��Cn>ݽ�x����� �Z��ȑ.;φܼ�k᭐��?.����SH���Y:s�硁��~���Yh�����N���t
+*�C+o����;v�о�>�[h�\��5v)L�e�)�z�-��ι�O_}"��'�>�����E�Kv��r������� 5�\^�" " " " " " " " " " " " " " " " " " " " }I����7�
+endstream
+endobj
+753 0 obj
+<< /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /FlateDecode /Height 512 /Interpolate true /Subtype /Image /Type /XObject /Width 512 /Length 8514 >>
+stream
+x�]y`��� a ,�&�E��pܐOEK�h]��Vc�OS�6�kj��K�.���(AEDA��UD�";a_H� ������s��Μ�ϛ�3s���;g���5�+�
+��+�
+��+�
+��+�
+��+�
+��+�
+�$����ХK��}�ti��Ӏ$F��@��.�Yރ_��?��b�V}5�բn;�g#L���f��ۢw�u�c��y����ӚhF��a
+4�5�`jy����XV4� _�C��<8eeuB�9�j����E�/
+�L�5�xষ��#�Jr{����)������:#q����� [JN�.���0�7����퓃�g+P����q��y��x �(p�[�o�qӿ.�:0el�[x|�LZ�����u�qh�f2�qމ8Q���B���V�A�r�;� �Ey�xJ������\�*Ыp��S����[\�|]�f����8������9r�N
+�� �����I?v���
+��*S�]7k�Fq1����j��ƍ/4��(� ����ֹ0�V|A��� Y�'J��o���$m��.
+7�b(г�� ����9�0z�}��0�!mv.6��>,*��=���F�����X��Χq���������a��M��0���]1���ן� \N�g��sB�w+5��Q��KZC$��WFii��[�ϰ@���Lw۠���_rB���=6�L�*���;�e?j���T/[5<Y ||~�)T�(������=�����+O��M'��_O>�*C�QF���e����� �����"��t���,'�O]L�]��������S%ApjY��o/;����W�m�s��M�Ye+��w������{����qm`d��:(���#<T(,�~�Q?;�z������u����C�}�1��h^QWq���~�~�����C��z�@�ߝ���~ l:��N���E�WuZW���??���?2����.�,yS5G�Lyoco���:�7����g\zWGcs��S?�X=��R��}���^� ��#������>T*G�+&��������)���h'�G|4U�ͺ ��[��]6�������7K'���Y�]7�C���^׫_ݲ���v�Hi���څB��H�R�e����Wj���8���ݮ����[��Y���d����xV���~ a�^�癊�����dAg���]���=!-������UF6{�O� eM>�?�M��>�ԁf){b���ڒ���|���q�p�W��xY���=��`��z��Z_<*=�6�&� -R��x�GP���̹���'~�0�������Ń`�1�]=kf�6�*Q����@���/�����&Y]�?<�E�ӟ�\ATs�L��[�� �/�>Mr�NMypH<�,��Y=Ei�i���,˶yp��vߞMR/X��$g�=7QX��������b�W��x=֜�)e��U%����+z�Jk4�uІ7��JrMI'���.�X���{�#�W��z���ᒪ47yh��&�Hq��q�j�����ܭR�}��
+��L�!о{T}�'Ҷy��� Odה㿓��i�� c���+1@�'��ώ\ ���I�����2%� ��[K�����t
+�7л�it]~�$����]��U��p�*�����u�v��ꇌ�z�:dM�{��L����/��N3��ב�?��d�+?w�w�|SN��u�rS�i��dm�0T(ά�(�=��L��2h��QK�]��ܻ���
+3fJ:k*�'])M�ѨB3cv�/1yW;;P6�"�&͕���X�?�AMi�Y�S9N f+)���v��"Tq�c��r5bo�ݔ�F4���Bp5�HNDr���8n�S�~���y'&֛�=k>�z��y�^����sx4��+��-�)��OM�i�M��F��3�^��3� $�+������h�=ޤ^�˽>�� ��35ak V࿑f]G�M�` �t|�#�`��|�ХE��5�� R�R���;$�����r"�
+G7s������sL}�wQ�r167 ϕ���8����k���q��.s�i�p:��2�����q&��i�Rqϡ����iid�987D��ۣ��2��[��ƣ���GeKs�Y �5?�IN՟04��(h]�e�P�u3��{]SPz�6�x#�KMl��(�!�g�Ʊa���{� w�����'�S��ޞ4b�H���A�$!��0n�k$ӟ��wF��GH<�!^��LA���x��D� �K�[�� g-<V�nD���gdo�x~;�G�e��(n,�G�x���0�.�L$(R�9��)��d��5\��D������lmm��g�z�W|����ϷQt١ � \T�E"#�G��^��R����5z��p,Y��>��,���vp��z�]�����}탱�҅�kO�e6�k�~v.i���]����A������gB��U�l�_��oLW`���N )����Z/w�N)��2m���!��/:H�+ ��'@�D�Kɋ@RF p ������߅�J�� t��������������%5��� ���������c$��0�,r��M���^��6��?��������� ��e�$�o���L��|8����G�����*�#���V�������%06�r���Λ�l))`U���M� W8�����吾D�}<$�䔲��&Jm��~���5D�7��o�A��
+6�k�P�J����Ap�{K�τuk��t|4 �:L̠C�9���N�cZe }"���PcY����*PA�x���r�� �."#l�7?~�չ�<���"���s��P�e��x v��ߺ�!W?$��;�����2�� �ۃ^�o�I OВׯ ��%� �N1@ ��j�P����/V���^�m�.nk�E��M!˄V7K֜��GC���H�d:"���
+TDz����C�{@ʸvf(�j7k�<2Y���I��?��li�>@��&� `]�He�fr!��&� R�S�צ�z�u�����|�mA��}� 5���I4��O �_7������B^�(�cW-���oR 6�^��Tg2��)/�1dB8�3���my��3d(��y���m��S�@�;���a�=��"����?�Յ>����jq g'g
+��4@���p��q���w�&|�8v�Q�����'@�9�`�J3v*��p�f��5c�b����5�|�Th�N�|��o5�xY<v��/���E,
+���8t�߮�4�1 X6K�ri��_��b�)��7�BM���M�����Z�v���'j�h'�~��+��{7�V/��'$�^��ők�\��$�ucq-�]�GNd�R�Βq�6q�N����*CHC�'��+�R�>Q+pZ�'��� �L �߭8-㏉�?_+��Ł_�8-�w����L�>D+pZ�C��N���N�Z���ջn�b��_w���2~������R��Ax��'��t`
+���9)��#��� sU�����l�o��]Y�,a���`�VV5¸�i�M͸�j�tR�v���N��l�r�N.��+s���.¶�w���|�����o�Pi��/,d�Nb��a[�u�&g���At����9������5��*�%����H\��l�����F��L�'.d+�l����6=ӆ����s�FD�vT����?��n����h����������lTo��>R����%��Z��҅a[3I�C58C���S�W-1i{�o$�����5�����J�z��w ǭ�vK��Md/KXF���˭������8�e�j�����z�v���8S+|��ŧhN��y���[���8�3i�@+���eԻ�b�8�Z�e<O\�?ke�'q��
+���'�e�K+��ā?�8-� ��ke2^���kN��q/���rq�z�iU-��q��d�2� q�{U�m����VO��~@�V+rJ�O����H�x�u�V䔌_+���y������D\��Y*���\i�-����������š�-Q���"�^0u����P ��x/*K�CPduV-4Q{��oK�����pv��. oh�WsLF�Y��]�� �/��y(=��������Օ��_CM|�u�!9W��J���g:G�,g�$"'���ЬI�E����]�c
+����)@V��9����s�����r}G�=< �,�g�~�RćY��� G�W��
+� �w�W�vs���_~���GaM�07���1������ �B7�|���b?f�v�eq�m�SC�
+y|�@�0���$Z�?0��H��ڭ�< P��Z��k�u�v�� p�u�^�ǭ_
+�PB��>�!❫w�eH����AXN��l)��4�!�jH ���A�� ������_z�R���>oh��� ĕ~^�K �ֹNW�F��!a�:*7?�>Q�� ��g/��O�)�A�Ե�/Ҁ���D �t�L}�z!H�G�(t��D2<T)�Fg�t6�+����F�6���T�������t���G@��4B����&�uPm��{�g�P�AL�������-0�z*u��/�O���zB���b�#EF �K`���j#3E�䤬̆Iv)2� ku��C��
+0��ܿ��;3dh���8 ��?#oX�Usjdv�߻�~�Fןz7e���r��A��Joӹ�k��ö`u�V�iayys$�n���It5��tr�$J�/P����e��Hi��]#����ՙ^����!�H�ZM7�"i��3,P�F��mî�3��4��|d�%�07��m��͵�����th����ބ
+��';�'�z�jrX�d�v��ӠU?��|P9��믉Ujc��G#Ȅ�~5&O c���hl��>
+V�<\@h�5�
+���̐4Q�3� }JZ�S���r,v<���/���uw��h�ʰ�ݵ1�z+!ZDZ[�U4��2;;�e���/���1�(/�5�� �O7�g.� D��2�qi(�kGpyD���4�#�۱�J�Aiy�+����u���PJƆ���e"� ��fqQ�W.%1埳*�@�T뷜Y�:�>�I�қ\��wR `?�c<�� ����-����m�6����ԫ����k�7)Tw�4����]$� ���k-�M�A�^Kc���eP˽A�����1�h�;1��noj�ǃpA�w�@�5ƧAZ/�ǵ=�'�t ��_��I!�(�֌�?(
+!�l��3�Qm_|"D�ڻQA�ˬ J`mh'�Ҝ������R�c���B-'�ҝ�:=���6~��M��6�"�x���-�Bv���XM��^+��V!����S��f����U6�SMJ[������bT���K� ��xqȃ����^��> ���Ն5���5
+�>����%@,�[/E�_���T�;���m�h�U�[�;� ��"����%:�-��]�^�,끄ƨ�pRE�!; ͬ� ��9\��.�zs8���&
+�3B�+���.�'8 `�@i�r9N��1ޣE�%����`�8x�K�TN�C{���=�6�`t F@MϺ���L7���nL<'k�`�g�h��� h����� ��2R����&�z��Hఽ*��C��u����\m�2����<lgÐ�VHm���ҀN�OFE-p�;����G_>��Z�m�z��?�SCnu��G{�� ���.�-�,��AWS�tx�� �ga��
+g<Ϝ������5L�9';�ҝ<�z����9��#u ibY����sH�G��<�v<>L�96�O��6?謜F"� q ���DF�8�g8@�.�u��V��ƅ菹���-��oB���p��bJF�����e[��Қq‹���)��R�=��V��)����M�2S�+@�L{ ( ��)<�2���):�u��x�8ݽ�3r��^G0���J\�]1�iΐD����)�W�H���#�O�����ڦ�O��4V��=R�~b��1{��{�)�Q���H�h�� Y�sfs���kQ;y���G��3C:��&��9w�uD��#%����O�J��H����І��e:��=DH�F�k��/�p􇲾e�U�H<���ȆB��ý
+�~�;���H{ב ځ�Y�e�m�;�i-�g덗����g��Gf�A��7[}���%@��a�$nV��C�:O�{�B�`�e�8qTl��<7�������<��y�0mN�h}l���=z�Q���I��d�)�%�Y��]9bݛwI~���'LE���J7'y�������|?����0h}�-�|�ݏ��7J�+�VƑz������^0�s�0��'��Ÿ���G������!o����#�U.�#[�������l��E����J�p$��G��Z?��՜���(�8D��%�/�?D��:o�������U����~�V�K!;��s�
+��,�0w�?�7��
+VsB���{s'��p�������;E ��&��H)0Ak�����&H0�<��w����5��}�GJ��|�IA<)��( ���4{܉9E�U^ ��sT��![^ ��Er�J*^ ��8?�o���<K�}���䖧�O��H˯��UFw��L��3:��Ū|��Ηu�r� ��B�VT��.����& P\,�[O��^�ح�/xoxȡ��W#f{����zFq��$r7#�K�*�b'����x�^W�3+��fJmW.��vy��o4 �<?�Wp� ����g�����}L9"���^,C���.9ɆU(� $���_���c��Nu�u<� �@�@ʘՆF����㶀����o2�Rn���!�%��(�I����jas~V4 �}a"���3EWm��s��Z��v�i������ڼ�֢�p�ydz��M򜆖�<��H>�=���7��Fh:fۈ�sMz|
+�G9le�IL>�n�pU��j�6�vH�VD����B�d޶K>��kl _�� �'��͋ Z�x��C�);���C���+�B'e�+��&P]6�Q`� Y��oX^�1Y�N�s8)㘞:�o5>��+�M���h�� Vh �e���~_�(A\��*X�8���[R�q$%W���o{GU+��Wo�,*:v� V�)i���d=P��?�- ��8DT ]��ҧ��Z_n�'��t�N�� �J9���+�dr�@yI��Nq�90�l}�#��I\����1�b@tʃ�I�d��SP�L4
+�O-�?��<��s:��I�������+��;���r�'/�8�dE� 'Q�I�����^y�����ǧ����R^��/=q߭׌��F���;�t������B��rt5&Wc\%(�]�ɕ�W�� GWcr�0�Ur�r��՘\9�q��rt5&Wc\%(�]�ɕ�W�� GWcr�0�Ur�r��՘\9�q���os�y��i�Y4J���r��@�#��p(��9jQ��@����qP�b<��f���G��P,85s�<��b�������x8 N�5�(���Xpj�8�yD1łS3�@�#��p(��9jQ��@����qP�b<��f���G��P,85s�<��b�������x8 N�5�(���Xpj�8�yD1łS3'#�S#�x��Ks���j
+���~��gNO�F��8+ ����!�~ p� r$���%����欁�����|��q��[�������ZN��c��� �� �.��E��"�?XQ��}T��0�pK����g��p'�i����7�cπ1�YN�{�6�=CF,�
+��pB+ZI�Ac�ve)�T��`&{F����@� %�G@M���8�#`�h����`� =~Lb�VZ\c4{�
+h��h��E��g�P �����x P��|��@�x����_C<��I���r^Q@�8��+왇�;�D��C
+$]���{��l P���[
+$�x���3��jb�����[]N�f�x�=3
+tY�.���ތ�}�"�n�&yf�T'����PV`䪸P]����Z �y�^���3>x?F��6�G��Q�'� k�����XQ�c��?
+4:����UuA�c� 7�HO��>�4�U�~=:6 ��+�
+��+�
+��+�
+��+�
+��+�
+��+�
+�M���\~-
+endstream
+endobj
+754 0 obj
+<< /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /FlateDecode /Height 512 /Interpolate true /Subtype /Image /Type /XObject /Width 512 /Length 6368 >>
+stream
+x�}�U���8�Nj���� ��j�+�a�&�"Ԍ#/�($J� �釤4��,%�@�Q!0DP�Ǘ�z��H%H8���9s����sf�Y{��53�y~��sf��f���}�����3���W�s�����}����[+GU�����w���H��'���tDr�u�/�5 ��$��ϑ'. | Д{'>(�á���&��>���F$@.�[�]��G>2 �v�*����Ϩ��R�~h�� j�N�3@��j[���f�]H)�`pm!W��M��a���T� 0��'��a���((׮�rA�v$�vU�m���0�ǡ[��D�U���1z�_u"]��W�?��Y�_?��2���}~��e��I�/>�}v3� �B����v 0K⿭5s��f������/5�}V�Uҗ�5����i �/��>�F���tdǿ�_���A7�⟤�_����9���0��S#��+1�X J�Ñ?����
+K�ߏ�E"��~��-��9��c��9�l��sM�o��4�?ϟM����{6��5��Q��e��r/�zMyJB.$��& p��w��͟�q��K�Ɨ9� �k������v �
+���P��/�'�W�r5�{?:n�9*�� ��A�.�;T��#�U, a.X��#A�f��i���J3�����$��t�:�..Q�F�df��J��<"3����w�p�m�>��}�e_?�&���o��|��#w�iV��?���h6�q�@�>�����a��B������<�"��O�����?)8�3��_��� �I�]~����w�[��$�ϴ��d[��N�n��i�ո�����w�l`��"��C�1����3��;��v�,�gP��3lL��ٳ�W���@����E������Q.%@ՇG�8�+��?��W��c�/=�g\s�#`����̃���u���ߑ�x]���N����?t��Np���ǂd�)O���{U�ź1���wO�$�V��?7�|�gWL�N��w����v�Y㇝��[�?�3@�t G���9��?Q��̪i<tga��;��h�&����y��-柺�\�?���r�)���ޞ�,���j����K-���D���U��'E�&�RJ��?G�R���\�\��| 衜�k7,�e•ٗt�/�o -�"X.���ܮ�/�m~t�r�}�o �wіQe�OIt=
+ɔv� ����h����L٨xe*�n
+���]�;�隷����� ��OC�,��y�1��~4��f�u����'�|u��^~t/��5-���ζMo�������J2^o��k��j�oK�E{�Y�3�VIE�ѭ��Dr�n��]��d�S��bK8Z�{��":���V7,Q�h�/�P|�5���I�����-K�&�D �u�
+�aOr5�E�2��%� �-Z�`H��xD'�+L�V��J����Z�N.~*J�����䪾.��X���qC�S�kJ�����(�as��ەo�����Ջ�{�K1<=\���b�� ��\̯���� �V�v�B����/��%E/4���v����E��Y:=ݷzJTn��ܲV3��
+��?*-���{��M�z���f�{K����">�C�;(���t�
+ ���f��-����h�g�7�`l��� ���퍼�-�wY�R~�����������Y�����s#�џ���ol�o����á���\F�~�ì���e�;����t�[ �ndӰ-v2����y� ?&��9�����n�>���������H+����~�r�s�G~�
+�N7�0�7m�S���S�� ��-u�C�w
+��`�߸�Nu�N�2,��ԩ��)\ƃ�:�!�;��x��o�R�:t�������I�2;��:�����!�,�������Q7�%������
+��<zv�Lu("�����q����"�K����H7AI�d"r������q��V]�P� ɨp��"���d���U��1�
+�������Ǩ*�?�s4�������X�ip����:Gc=��1�
+�������Ǩ*�?�s4�������X�ip����:Gc=��1�
+�������Ǩ*�?�s4�������X�ip����:Gc=��1�
+�������Ǩ*�?�s4�������X�ip����:Gc=��1�
+�������Ǩ*�?�s4����˿jԒ�뉼����C� `�����w�s���#%W�㎻\��~f�`���c�}��GDH���vwX����O��O�G����s�kh�5��Sl�s��
+{G��� Y�e���R��p��`+��/ {G�fb���2O�mk(��5Ԟ��<؊'o����O�`5����@��a{M��fL�{�W��_�a��<����+�ֹ�I�K#��Ll�g�w;{(��� ���,s�_�OTۂ?U�z��_�'����*Y=]���V�O���.���j+�JVO���D��S%�� ��|��
+������z>Qm�T���=����d�t���OT[�?U�z��_�'����*Y=]���V�O���.���j+�JVO���D��S%�� ��|��
+������z>Qm�T���=����d�t���OT[�?U�z��_�'����*Y=]���V�O���.���j+��۟z�׀�Q�/���j����B����H)���_9�\��{�`ʿ���}��(L�O��b�ǿ0��s�wH�D�U�'��?Tr�H����������'�����T����-� _�q�>�|K��J�)~&OU�?O�޳D� 2v���oɔ���s4
+W䡖�)o"��5�o�O������4}^ž��1ꛛr���~�/�y��k늉Q��I�����%��L�7}���d��Z�~�6�Slm��d���"��dETi:��M��6�`5e���QD��?Q����_�(����(XMY�i�f�O��,��4�h3�'
+VS�kE���) �5�"� ���Ք��Fm�D�j�M��6�`5e���QD��?Q����_�(����(XMY�i�f�O��,��4�h3�'
+VS�kE���) �5�"� ���Ք��Fm�D�j�M��6�`5e���QD�1�ڔ�y�9����ɖ�iĞ��?"eW���o"�~���( ���}��!��_)�G������ɿ7���g�\��s`,���p���`+����wj���-���a ?�clœ��wj���-����(ܲ��3��[����P��ByU��2S�]�B��aO?M��fL�{�_�s��f�\�{��:pha���^f���.;��k������ ��`Z��e�?��}��7f��� �$�%C���pI.�K�0+�?3��\� aVf�%��/¬�̀Kr�_2�Y���䂿d�"�3.��fE�g\� ��!̊�� �$�%C���pI.�K�0+�?3��\� aVf�%��/¬�̀Kr�_2�Y���䂿d�"�3.��fE�g\� ��!̊�� �$�%C���pI.�K�0+�?3��\� aVf�%��/¬�̀Kr�_2�Y���䂿d�"�3.��fE�g\� ��!̊�� �$�%C����P�Q3���
+���M�(�,�LV4A������@���"H�W�b�*^���Ϫd���ku���6`�J��\�V3����.S��-�*c�'?���R�+m�U7���C� x��B- �վX������d�ȁ�Akl����2���?��Æ:��;�p��o�PǺǀ� �Xw��0�ႿaC��f8\�7l�c݁�c� � �� u�;�w ��p�߰��u��3.�6Ա���1`�Í��G<�����W�y��0L�xwq�o}�� ��P��}�T3�V��_�����J[lU���������NV��+�����3w�w>�Q��+����?1�>��@�,�W�b�*^�� �����_a���x�?*����
+S�U�����B�+L�W���u�g�w����ߞ�.� �.P�#���օ���J�b{޺�3��@�^��o�[z(ً��y�B���%{1��=o]��]�d/F�� =�� ������u�g�w����ߞ�.� �.P�#���օ���J�b{޺�3��@�^��o�[z(ً��y�B���%{1��=o]��]�d/F�� =�� ������u�g�w����ߞ�.� �.P�#���օ���J�b{޺�3��@�^��o�[z(ً��y�B���%{1���G�]���s�~�#D/������oc��ݘi�~���2�j��E��A�1��=�@������5��Z�����L��բ���Uk���Ę��v���{�#��c�5ÿ������FKV��'����v�Q�h��q4
+9P��䱎�&F+ �_&F��h��:�J2r�e��_#�]s�帉v�c�d�\�B ��U+Ž����Iv_�Q��?۲NC��5r�O~�r��o���oҦ�_!G��_�Lў�B&Zߏ2ſի���_�z�p���i^9�͐�5�m�7�ߓ��Z^�|������}�C�}�;����毊���mw_��+�*���)����*������P�Եā/[����'='�%±nցMN�����t��C����y�L���W�e1�7���Rwh�+�f�{��ϼ���7�߻3������I�^5� $@�����2�����A��ϼ�w���X�o���msz-�����coڀy����WZl��1>��>V�{m���`����u6�&����)�h���+�o��M#3�K�3��|����3(��5�<=������Je�K�q���W��w@��{W���ϟ6��A,�-[��
+g64F�0�'8�NJ�c�;u��!�5 �����m�E�K�}� �3ա�Ɗ^.M<t����b�3���� $%.E����݉��pw�^�O\��b̿O<f��~�yS�R4�Kw�������]�� �ű�y[��W���b���ڝ����8�ʁ���5��9$F�|���w��+_�<Xeqcz]k�������u�V��%#�� �/��)���{�qR�bO��7&�J�����4~��\��.�Ћ�Ut�{���E2'� k������]��7�ִ�KG�2ٰJ; W�xJD��­c{G��wB���ʀTq�|c7����~�x��{�B�}���-ߚR��u��}�f ��1z���U$�d��q����T4�{ i��Q�f?vD���x/�.�lz�=���J��uGV�Y��3�l�����fc���_�tu�>v���V uV��fC:��4�{}û����m�z��Z s�)ʤ��R��7�ު�v~�O�� �FT?2��Dj��{ӭ�l緅�_g5��~�&����~`ՑD;Y4%S�"��7���%UQ��;͚��ގ�v�>f3��6�~���4�6��>@}�������^�؊-�1�3݌�oϖ${���k���\hc V���;e�5_��X�;��,ų�_��Û.��W�U�.
+3�
+����џ���(Scn���q�K�
+���o7�k����-%Z�RT�e�`:OS=�@�ȥ�f�9��w����T�� �/��Y|�`��9���k:[:zG��U�^a����?�>���I�q������tT=w��߮w����I'�<p�//C޻���s��v�����R���Ř�J��2�Vv:,z9"�q
+a}V��$��Bȏ�;��uk�W�8�H���z���ܸFZ�]��8�!!���������+��H��y�m_�����\.��Ow#�E�Z�i�PO[�h^]�?JWG����c�K
+R�t{߯���H�V�-�,�;s�������{OH��i����C��c�#����������}�1���@�A��5(<���G���p0�Dv��7x�կ{������鋚�9�{�D~��v<��e�Ck��.r��"��AEY?�����qY�и��Bk�t Ex� �kؚ�N�?��M�:����D�hY��$ �;u��S{�OѴ龕,�X��v��uX�OD76?���߼V���("����}���',zC����zFy�Ym����dK�֏�c�@*FmV����~�V_��t�y��m��� �f!ǷN�.�-����y�~iW f�f�ʥ��]ۖ;4M����.�
+endstream
+endobj
+755 0 obj
+<< /BitsPerComponent 8 /ColorSpace /DeviceGray /Filter /FlateDecode /Height 512 /Interpolate true /Subtype /Image /Type /XObject /Width 512 /Length 7801 >>
+stream
+x�w`U��'�$�^���Ҥ�O"�O EE#"��ntQAY��*�(.JQV�EQ@~X�4QW E,� ��BB���W�̛�S���;s�����μ�y3�j����h��ο�0uv��� [s
+�ssN�۳a����<rP�v J��Z���.J���m'�c���ü _w^�������jq��E;cc���ت�Ou�����=�u��d�E���~�'n�x#=h@R�����Z�Mo�u�-��6���㴵� ��<��U�Ǜ�l�٩h�y��kl����W���uw�4�}b��uu� �Q��}S;�p�@�5`i"d�P�&�q�AT��Bcb�[W��� ;�ڛ�?���D���]�dC0�$�g��#GŶaU��[�>����"I�?�ZK�x<-�,������Mq���_��s'������E�y@�w�&�����ݓ�l@��u��Y���7��G��d����w�eK����8�Z�`m:G���q�{n�֧�Z�u��G�lwO[Ѭz�7~ܝ��CZOɱ��%DZ�E_�y��-�Imh�J��?�>nPHte��Sɀ96Dn� �&�x�W�]�Y�cݶ��CU�?�pjX��x'�W�^���@��\��;�Õ �+�С�4�����yG�[\Z��7Ȏ6�K-�8@X����[�u�\�;R_W:��U����~uWz����7���ܭ�皋������@���4
+�e��`wH~Ւ�����F��i�����2��w�hA�wo�+�jw�-�d��jo�o~aCq�L)gjt:f��̐�DL �����?|�.�`������ ��nÙӍY��h��ԲN~4q��[U�&y>@čUY毶��������Z]ͮǬW~��a~k�#g����=�v掆����6Ү���张Î���0�W�A&����|�'z��(7� ��n��-]˷e����6��5ЁÊ<G� ;3�{�6o��bҙ����:������A��g������z�8��+6��E�c��д�`i��mr@����BG���?�ȑ�;B8�zz�?RV8j���~W��'ଂ�˂|���nȾ�Jp@��n ఆ��},$�u�882 � �g���<���9��5�o�~�o�Uw����z^ � ���zچlб�s����2 vU ����­!���̀���]��k��=.��R�jj�*{\a��DL� �579�-E�3.�����RA�>���W�{
+
+�@=�g�Z�5�}˗��� �o�;�-EWa\"_���� �
+�U|�������I �x���_32q������������s*�{���J��c����L&;�뉁���kL��� `p��e���)ۅoL�����1���T����������쬬��g͚>q�đ#G>��7\���^�ʗ��(ػ>���c�l�ȋ�ĭ�+L�-;p`M��<Թ��n��r��!��&fv9� ?ΏY��`ׁ��f ���Y����v��wp��M�z*�l�
+����%c�8�U%�-9�3��6)��{1��|Z"��sޒ'ڸ�������H��l��@k�eO\6�����E�pk�h������� �=dI���@�g�|��/z=в�����З��-���}s�C�� �b$�v���xȎP�C�@��^�ϙ,%�D��t`��'�:�ӏMNt���h�6ѕ!��;0�-�Xf_���t���8F@ 9�SB�^v5���A��;g�Q���!,|ь��# Y�����>�O��א�P�]Ow
+ '��E����€�b�-4���Ά'�[$����#^���L���p]�Ɂ�ǡ��?<�4���"�.Q�p�F�K�6.�ǁ�-P?F㨒(lB�YX�{f���h�3@�a,U�́�k�@36ђρcm�@<Q�ρ͑�x>͒ с�5q�׈�$�_�L'�~02CM5
+�p�$ ��@Q�БQ���u`���2�3.�h��'����%�K�/A$�xX�`7�`Ɇ�@7�'@*�����j�d�0�t��;\�,G�1;�����r%���A�)d9�ہ� ��s˕|���� Y���v�(h�U�r%�WBN۰�H<n@_r��J>l^�e��H<v��aW+ �X ��[��cw`+��U�j%!���o�#��(��ƮVb;���������Î =!�?t5���G��J>t �3��H@n �e�nZ�� ��ˑ��@�˚�̰�A�?H�GB�:��W^�������HH^ �e�'^V� �o�$1Y��XQ�$��D��t¿ �P�E��mE����B%����$�$(���F�����e$�$(� �2
+�T$��O �$A��(TR�8�/?�0�
+�/�q�"��ߐD�etĿT�RIE�����B��dt��F����Y��� gLy��E.��� gL��R%�0��I�� ���E* ��(4IL>��e
+(>T$����p*|A���I�L�k� 4IH>���*���@���sʿ���� ����@��ds��TID��WQ��0�r�ٴJ"|���E��$"�p�CٴJ"|��/�%�����&V�;�MC%�@�/ˀ���O��?�(�,���m6�VI������$"��+�%@&Z�i0�ks�uIDP��,�,(�S(�����.�:�C�� p`k D����IHV��t��ȡUr�;��"��|e�Á� �K�6(�+9�\��J�BG��=�zIg� �v���%A�6aK�x �A�<�A���v��P�����I<zꁘ�u�J�V2 ;�<� �ͅ�' 2�p����_���fؚN��-�8�F��@���_� ��䖍${#�8�E��0ޑ����K� �̍$|�Q���w����#�ǯ��,��� �6 E���T(��_�k� ������6 E���P����k� xN�|�V�'N"�;� �;��z͒ρ�Q� 5㉓H����.�CCL�i4@`K�FDy���;@�8�Ē%<��G���,
+��8T�
+ ����Ģ%<��@���G�'��@��!r$�����“��Z�@(�H��ɪ �����O� O�D"t���v�� FH /4�)<���2����DKd4��kM����@d���$-�� ��BS)����_~�j���%�"�
+�ʼn*)�~*��Z�� $���b���<<8�����Zې�J��k�ɼp$������z#)�0���FS薘80�OxG�D!p���V� ���Ze�
+A�Z���%$�<���9Z%�L����p|x��k��0\�!��k��`tz��|����J0�vF�Z����%�N�Z�\�\��+��,������j/T��Gu����X�����Փ�B��0�����G&@`,~�rCjw��oD�@�Ap������ �w#� ��;����JOd��?� g�'��o_��Dv����k�p�p��L bzO~���" ;�&Gj�+���Sdjpl��x��'��Jgl�����/�`��o$O��p��f�/����Y�O�����p��-^�`�_� X��v���L� !���Jl��߂�\�a8�����j%�L���a �x(0��"V��;����"t�Ł�ȵ�)ޟ#�|��"���wD�R_��(�����(��/)����$��pb�Ί�]�=8J%
+�� �(�SpÊ�) ��gP���th��_Z�K��8P�yh�k C��~��菘�?4_&�������PV�k�R$��4)�DZٛ'�@:�80��X�W u�Zj^��-��oo�Av�q -�Y�wOꤵ�\�L%�A�7~�Fv�v���5ʇ��*���U�0��5'�˒� յcC ����ZJ�����\�$���V4��5���\�_�gFF\�v}GL��b���r���gm��Xx2��2,
+������wg �9j��'� ��̸�c�Ւ��|�-�u��jX����mq���2�����uT���-��jH c��d!���6�بw�'��;Q�(��m����!��5-�=$<��w�X�k�)�U���X���ަɲvvD�K���#�슸�m���*["3�|��^~e�n65����J���qayvTJH���D�(΄�^�M�4��$9�G�]�.�Y�p)���X�l��E��KKq=#��m����OAm{
+����
+ҕ^A��w� ���eE���l�M����,&$�R<]>�47�!�����]�"�t��|D ��e��A���<mw!i�#�N<a>�� �ǚ6ϛ�)����Kx%:i���� G�����G������������B�V�b���:�C�u���@ů %T�o+S�l�T��t�J7L��YIk_�?L��W:���B�{�{��r�W�/��_�ˎ$�&�ۊ���'����ƃƿ�:����跦����G���6N�>���W�@�_f�:���V�߮u��!�b-k�� f%���t�����7�@?������¿1��J 5.�V ���G��O|�r��a�m�5���m�Ŏ�ﰘ2��S���ο�!ud��-��}�,��OYi1c�ݿ��/ǿ�w0����I85������OWF�4n�y&Y�+���;��
+iBr���_�ƿ��ꨀ��*�`�ծ0�㬦���d�r����`e��_M����\�5]��_=~���� j�&�A�Y� ����\&�ߔ �M؄��}�]>��S��z���_g�: ��he�2�rg��K}i9�������.����`�Eʕ^pƄ\�U����z����pP+�D�gӬ��UI�Q���O�\ ڸ�쏿�CH�+��:�?� n�s���%;���Y�%R��Jjr8��?������_}�2�q<h�(�_ �:���@�Ƣ�:�p�����u�Ôq����p֋"���,�'��/.�G�]����Z�-J̺x�zQ���,��*� 4���.���,���2B��H���%%k��b-���E=nX��?��S ����U���!g�8�_��
+��y������� %'+�3�P�C�H�+AY� ڲnQJ~!�����Q��j0Ͽ�fe���Z�v�$e�?�nQBR��'���6��?P/B;�2�!�9�����'��/.�‰�������7N�T�C�
+%,s�ܻ��H�B9Q��JZ���W�Ej\C�y�0�J\���!.���(V �?���-f���Y��q
+�Q1�������=�GE�"i�J`&��Sv�j<q. �_I,6��ʎX��F��i�Jb1���E���*�QQ��YL�� ��|��!E�]��c؝Alѽ1��m&�u��!���� &��/�[�8?��Z#=}���e$.k�azԍ��K�f�� =�J\TA�������y܇���Fّ��B]�'�������-2c�p)�KSo}�RWS۳R?9�����Ɠ���*yA}���oI$����!���}�E��xw�~v�-�� �^��&�fd��w��7��U�;�b���KN�^� yI^K�Sw�������~T���]C��/=�nGM� 6������Ҕ:�xB��������k�Gf�*}z�r�m�
+��Hm��/Z6gp�ӹ8���d�j$_����� �|� <2�{��y/�������V�R��$ei>�ei�����s��]N{�M�/���A�u���:W_��Qz��G_�J̦,�S��<v5������<����_���/�ػ�V{�wd��j-�� ��1"�\�Qmn]�����Y9[_$t�;��T[N��{�'��YY[�*
+��7u>�����VV�:�JE[��/JV{ә�ÿ��DuZ�ֳ~�"J��*��M��ۙR2�i�[��pFR_���v<� Z7r����V�����JH���:�? �j��$��4W�� ����s���+$.�B@�L~��X��-IǒZ��%/�I�Ls�َ�M{዆�M7���Ro�M�̆^��1p�>�����^�(W��5��6��{~{��O����۱ e^�V�E��s���q� bw��k�l��V�/=v����zn���h���~������ި�6���D�+��u~t0ư���ȑ����u1t������3����c�>5PވTCs���F١��P��f����1 |���2�{�bU��QOt��pt�U��Vc+~��|W�ŧo���-�3b_v�����`��:x'�\���׻���t.9�BӺ�u���Kܱy\�hC��Z�c%]�_�v�pAI!�������4y�۷�⍮�6�;g�����u��kL{M~��L����:�M�����d/��ahAƯS�g�;]�J�J\��⃫Nk����2���Q| [������j�$��{��EC_ ѡ
+�ܢ2gwO�2븪
+����m|�W��J���T�]�V9c� .w�y
+>�[�~C�I�� ���'(C��m��{��Dz���˺ơ�(_�w`§Xś�^��۴�B]�3����*Q�t+4������{�-�g]��H��ᗂ�af��;l���Mãz�č@��o��Qj�[آt⍇
+uC���ө��y��}�Ű$�Gx�b��;������ǥ�͝L:�S���� ��4���R��敿���U�l��JQ�2��جT��ش���lϋ���:� � t<7�����2�r�v˜�d�S�}Ѥ�7]�>�P]�_�\�yȴo�X��O�����o���{�r���<y��/R���/}~��#g-�����=gⰌ.i,sd���6��uO�ժk߁O�{���+�y��0gÊ�M;�>]�j�~Tn ���#xa��]HUR�������w�pczz��S�z��w��᪓���q���=��P͔`�pL��S��Bu`&�����[Q+�`fx���;�4cN��I������%^L��y�K������|���q���P90��{���q���_-�9��P@%�[�3 ��F�Ȧ<�q�@Q`��PJ�# S�F8p6����.(P$;@8�l�̲� N��� ��c��R}Xn�X��ÁǨ��/7���E���%� ��[ل�]���Ů���� `����g{�����gsτo��4�$�����`�� iEHW� ���}-ғ߁�5�`������ԧW��-2 �(})肸��7��Li��b�].��O�������
+�tP,�W�Isp�h��j�>��䫿W� �`���*~MK�~(zF�{�ɕ�3A���r���7.ms�
+oB8�Mm_
+��eʲ�� Jeښ��`�|�|wO��6���_�=�E ЁĿŜ�0�R��r�=wW�r��� ��2fjw�@5g 3y_�����Q��!�}������TU���`�/|��k��~w�V��~R|�篜p��S >*��o���s��lY�d�����e�Ld�?2��
+endstream
+endobj
+756 0 obj
+<< /Filter /FlateDecode /Length1 1269 /Length2 1151 /Length3 0 /Length 1867 >>
+stream
+xڥS T�VTVÊ�<D���\����#IJ�7�) ܐL��0���*� ��� ��A[E��Ů,H�Pa��[d��N`U�n���s�������w��c}_�#�@�p���x���@1ċC�� Ad�(��(!B>Π")�c����C�1AB��G�� 1�L+�C���D\�^(W�AD�_ȑ���3.�IP��X���N���r̀��b���D��p�G�s*��#A�H~�R��G��g0L%ł9���X�e��p��B�3i4�"�2bA.f$���"B� _��B�J�B�H��+�sƣ���R`�P."�Qh�R21`�C��{� v@d�a)�w_a�n��d�ӽ9Q�{�:ngo���wiNNx��ZZ��ni `�� ��� ��堿H�ރ�o���o����0�eF���żq�m�U�C!�%x��L�oF���݋������-Z$��c���N6��\�X� 7N*�-�(���y~?D-�H>��вy6GL B��Q���|Q�+|�H��Ƿa<D""i}q)��3 ��EgB�� C�R��?B0�" ��l&t�5�5 GF�ȱ�3 (Y) q$7�� ��Di����(D��]��7�|P�-�������o�|����!\JG;ε�:�����z�Ծf�-��|�z]wz�������8q8�e��ώ�s::�W{< �P�:2�PV[q� ��!ȍy�rf��D'�4!�[�� ���8�^��e��ꞯ�������ܹ����bH�nw�F��>�R7>7:n��X>�vxv�1ĶR�E-�hu�uM��t�?�6,K�sV�j������|Vv��z� ��K��O�}�YTL _�ٻvEQ�y���Up^��,B/���6k���%/C|r����w՚]_�T������`_��Ѡ�D����c�K�Dv����{��V3,�Y�� klW�4W��ឺ���?^�4�mx�|�m���>i�p�D��ګ�|��_:�iU飆�ʒ�j�.Cye�7�6�x��AY���L�%�-\��Ge�GØ��θ��YͤN�����&�x��%G��
++���=�8��V��C����kGzW��%�u:Ӊ}w���i�6
+n�aw��X/�C�թL����uv�}��m�*��p6�k��t.��Dl1I����������S��� k_T���dDu�4��]��<놁���wJ ~n�亊o6?�Вvn�~C�ɟ<3*>��~�L�?�o�²ckw��*2�G'�M�M, �وq����Ń}�@��L�֘)�ne�`1+E~hRͦ|P���v���g�ʳ���W�}��۷=��o��/\�5qݟ�l�c=}*�6�3���� GF^�a�z� �F[��e܈*�����F$�.ԁ�ҳ�����*��&R+�#�Y�̌��Z~w�D�e�O՗�?y�_H���67���H.��)�d#9���OM�Ce���c�뛻gGSM-�A9;7�9����{~�R�y�#,�9���P���f+ʸ��Gu�k�S+mE۸c�,c��L�1&:�����}�>F�wT�o���2�:���j���aыf[��WO���7N7�M�#-y��PM�S.}Fs�<E�o9E��N���z�3�4C������'��A�./3oo�Jk�;�rUi�;}�^������}�@+`:ю[x� ��}���%����������v&T詭,أ���t�e-�?�լxD�nZ�������R��] >�?�@��'�������u��@�gE�"��t�a-����[YUI�5gT�O�^�`�hf�wc��A|AB�-V�bX����g|�w
+endstream
+endobj
+757 0 obj
+<< /Filter /FlateDecode /Length1 2227 /Length2 13588 /Length3 0 /Length 14726 >>
+stream
+xڝvT�]�%��N�����Bp(�p����B����<HHpw����=��̚UkU�}�}η����LE�I����\���������ڃ��m�]����Lj斮��N��36.** ����g�@�e�� ���m/�dn��#a����jP4��q�x�ٹ���l|�2�w�(M���m�V�N�T���N@K+~��K�)ݛ#+7ӛ7;#@���
+�`�4������dlg�lk�υ���1Ж��ގ�� ���π������?~��,�O�L�r����E�g)Z;�,D\M�͘��\���Lhjr67���̝�
+��������1@�d���J3��'ே&�F����<�<�Z+~���,�:bv�`���н�Xd&noggrqF`c�M]&�@�_�4<�8���-���]��}VfVV6�_��W��Zaf���m���\������ ��������=ެ&6+��� ���AU���E����,���/�f��*�����Cxt��d���C��f���j���������z���S����%��������?d�/��e���˅��-��M7��GG���f��{~��f�����t�H����C����?'� �?u!el����|�\��R������@�
+U�����(����-�����L�bj�0�u6���_��A�*����.ʷ��b��3 +�� ����_G� �� ��� ��sq����=X߆��� ���E��{��faٻ��\]|�:���qsXD���'��H��xX,R�;�E�7����F����-��߈�-��o���qX4~��(Z��E�o������ &����o�������`1�]�_���M�� �
+��r�����q��c�|�l�|k ��V�����������߈���o� ��F���F��o������ h�G�o�T�?�3�?�����2߂�X9����Ma,.�&|�����o��1�Φ�Nt����ߐ�-���-��o�o�{�;�3ǿ�����������M�����A27�07EXY�7�� n��%tgڛ�]��P\����)�a�M�I<gS\\c�/�U+�}�ɭ�������x9}l�P�ٍ5������q:�,0�'�����ۈ��=�It4Z9{���@�}T9u^"/��wV��-�Y��_�{N�� ��Y (ּ�w���N���;Q�W�� ��b�b�q�D4vDI�=�E�oC����V���xߜ[� Vkr(2����w$&��.ق�[��T̝����}(}��.P֯D���e�Q��
+A����UW����)ML�m��;����SF ��KZ� #��z�<u����G"��3ɷm3���{��f��d��q %�I��IɅʦX���W����j� �)^�P�y�v*\��R��L ����W^�����_ñ����[O� �Rt;�N��B���Es=���/���34��AtT�g��"��Fr>�r�6px,����{I���#�V⸁]+&�d�� ��RSU�2�R�2����h&�)�<�p8U����3� Z6�����Ƹ��Ai�ߐ� u@��B�JPFsъl�� u*�����_�=����|p� �D��]��-lu��?��j�r��#��� �n����/l�8�N  ����0�yLD�3����3]��~��0��05��rf�8%���)CS��E:�ߖ���Rk�D#���8߹�o�S��$� ��k�G [�)X�۔�1^��o`F��4I�9��1�8�Kw�/�v��LՓEl �⦨2g��L����Xy:t�l��.�Pȟ-���Q�� a��'G WB�]HUYf���pوCJp���&�'[)F2Q�K���DH�P�@��b(�F��"�>ᡝLk���*t3�4���h.i�. هi瘗��,��� oK����!n`pڭ���׍I �l����I^��F3�Z{׉�nK}hg��l߈"�z���y��w�U�̀s�o};�z�GPj��d5p�*6��?7��_��k[��Iu����߃ZC�~��縿r�t�~��@f�0�����`�:�4��I��2N��`
+�F�!���^�Nך�*�z.L�Ju� =���*~,�VE��e&V\�gZSC^�#E\Η�Ut��횢��L�V�p����L J�`>COHe��N������i�,_�E���s���T�Lx�P�q�����shR�1$O��p5�%7�����l����O����]5��ΐ ��|��bk��np��� �l|�p���j�<Þd;�$1 �tyF��b���)s.���l�<�>���:z*� f��4B+��}aOo�(��b֟��@",,����nII�R$��c�5���'���`V�8��**�i&2�%�>� F�?�0�u�ɨI� R�8G ��9U�`M��������*r��:�ޢT�[��}�.9Ӓ�M;��-$�r�B�[��KY�EZk�ŷ��j�4�Kl��� �u��=�p�?�5��0̒ �/-�j�Wk7N�� �RT��겇%��y�7�D?�h�'+R��%[����>���Ԕ����8&o��E��~Udŋa�ڟ�_��:���xmt6��I�E���WE��&ɷY!f,��'.�Z1�� �cن���ܥnϮ6�m�T]ƗE��-�,;"L�{X'��k�S���|
+��Z G�*+�9
+?�-�Y5�m�{��댉g�8�;2��|�� �Q��%O]�H+�I�wTd;L���5�=���`����۾��z���+5RV�����;P��ݚN�������lJQ��]���&r�b��i��S�^� � �3<d�ѳ�f��c���H2���� �������͗�wK���t�̮����'��;,0"���ʻW`��%�|d�GW�4�Ҭd��[�Z͛�J9��$�� )���(?�KX�M�|4I�:����� =u���Q� 2_�&[c�-�R{�_�dE��4�7e�� ����U1m Ы_�/s2u;:<�`H �!iWG�m��+�K_ض5�} �ۘZ~�r�t�ϑ�8�����ͻk�=���Fi�.4�}G�ۍ���G�����f���EI�i�>~x��i����b�����Ů��$^���Hb�nXF��A �ó:�T����616s���~d�����a:Q��u�N�8U�Il�_�6���>Q�[��S�Tü��Oa����3��(��Q��A@�\�ۏ����J���V�B�.Φ��;�����W� ��a�=�7/"����hN�"3a2��F/��zmn�v�$Nhn<̄��D���`����:\-7����.�)�Q�I9�W���qO���ҤS��|Q&u�4�w�g�����
+��9$Tޤ � ��g�{^�I�~�/��[@�%���C������s��LZ��N!x�;�`��������$؜MFQz��x��g�ψ�gF�G�:�U���u!F�y�`-�^v����it�.��8�z�
+dd��g��nRӲ���s�t�tv?5��t���:%�+��U��&���z����(���ZF)�����dZώ����׆��)浖��Y¯[���1��>��" ���8Q�U���^ݺʀ��i���ت�7�)rRz��P �d�'ۊݑʪ�p���nav�-��i%�N�<��.Ao����W-�T ��$�.�J���� �:�\a:l����!�����X����{^#"����#㲟� ��ׄ���A��&�T�|� ��G�ȰE^�D�GD��+j��0��m�,�d�J�ȕ��'����#�V��K{��h��j���f�U�\�:?���Ү8�P�yF�#�Ng�2�3��4X����'fP��R(E�.���~1y���yG�e���Vh�uS[_�DF���-1���=+If��6Z �Ҫ���c��r�V������8���
+�_<�}>_|�!ߊ!�ǔg��YV��5�-�t�J¦B �ӑ��:�y���/�v�=$!����hL��$-!���|�&��
+@�����%]�<2�!�ɉ͊���+ۨC��u���mQ5������,mJ|dé�b����%� '�Nz�g\4����!��Ը��la��+�IλS����{L�܏�1��`¦��b�yq�=����Į:�w^T�P7�(�%4ͪՅP�u�G�x'h��`��h���_�o����E{i ����r�����9 �K?��O�*�=c�|v ?/�S��l/� K���9s��_��!qɢ�~L0���Mț�wM�+5v��$�\"xx�ɰDg���Gt�G�\� �€AZ�[���G�������2]�B9�6�� U�dˎ.G�
+� �>ƾSv�3A�#N1=��U�c��v����y>.�)����vIz��!��P9�n���8x�%�f{Q������H7Bap��yJ[��| ʜ���5���`Qw����~�vF�k]<r_�٦�{��c_����o�?c�!hGI�N;���r̼��&%])Al�#Y
+�t�|ףnѳG"��W�_�0�М�p����W�%OK}���B[�p�e`���5�w���&�^��r��r< ��s�g��3�{fD����w�X�i! ��|���";�J���u�j�X�ۭ;!�+��VlX˻�n�7y:mF��D�EW�G(b���#W ��`ȴdrSdQ���_s,��~ŷ�,�s<ty"
+�I�� ֡�ٴq����2!]� n���g*r�UD�� �^�6�K��5����K,_b�!v<��T0�}]�*O���s�r� y,��Yh�}����{�m� �*�S�*#�#敪����Q�4���F�4� ��Gx�S:���t'�VӦ_F�g�[�/T����@�$Z~�~�35e�8�R�O��o�l��ҍĤ���5�؁|�p[�z\�g�m5kD�_�2��D'=?��*�\� J��5�,C�5 �a8{�֎O6�>��P���H�F�.T<m ř����څ��y�6���(C�ݢ��2��H�l0X�'Y�1b`O��G��Ϳ ]�r�i����8:Q����E�e1�U�\)�����Z� �z�)'AdK#�P��zV P��+�{��=�-��;h�Oi1�4�h텹�)-�6��;M�e�����Q���&G�7���[�b_[ ��5Q�1�K�}�0=i�X���"u�7�FJܰ����7O�`ܫ����#�6A0cl���9j!T�'��`g��8�GO1��fx���e�]�Z�̒���4�i��It��9����ϳ qQXȒw/� �9(U�䅛5���K��.���k��� �_؄�!�z�Q�[���
+�a?��EI�j�b}��a�X&aK�(����̣��{~@T+����� RA��t�o:�H7u���1bt��d�:S��8�c���ri@��
+돰Tb�iF|�OF��G3x�;aʪ%�<���a7Z�1�R����9?� &�5GZ���]������~;zV0� [& �.�r��]TeO�B�3/3u'BN�-�ʼD.�o�����eu��/�9��1 �A:�N"?�탶f�Y���ײr��owXP$��B���'$���)��6q��G` ]��� ~�m��/�H�T�JC�
+�6(�~r7z�s7kEwX�{�[Ր, L@61�#�l{V���i"��'I 7 $���1�b+;濋���#��Vj�.J��a��m��S�h�?"�dש^����N�2!>�,o�d�����K�� a��}@�k�E�'��Qes��k�n'�)��$�
+�?��m��4�X��ur9}�Y ������B�`4����2�6y�m9���Q6������S�Ȉ�_��M� wB�բ�~�X����u���2�ev��ւ�:;H�*�:���6W��"�G�~�@�8���s\A7��M��i�m����
+B��3�Ǒ����9X]4�ɾ�<��x.U *� �SdQ�����2.�����0�4[���%�s*owif�� �9��c�4$ñ&j'`h�Ȱ��!�("E�gwi�,���dW.����Mz���"������]T3�ς
+H2}�e oͷO��kk��_#����������J]���P���5�;��wA�� ���R6ڡ\�o�7�h�G���`�܅�N(�k0�g�����t��5tt�/R�=�u� 2EZ"z6mzA�w^���.��?ˑs�c��%��uSk/&/�k�������S��eX����e($a cݎ0��� ��'p��Rٲ.# ;��;��A�� �^Ͳ\ {�����K���
+�١i���"7�+E�80ա�g�n�N͊�3�+�R��w��?$�G�&t0�n ��9�_t�^����\�I�3��_p�Z�W�#4@��q�"bE�6)�,UkU׹��2�_X�<T�œ(V.��MB�㶾C�v�)����4��km�#~a-�u��-T.�=��r��h�]f�W/�I���i�<��������W��R����F��M�� ��_ly��<��Zr�9���Rۅ.ӄ���ܫ��w��Eb���N$��]�pў��޼�$��"�{��^I4�����g�����o���b�Z`릉��o�W���f#J�L�Y���̧W�gu��Z�z�80��[\�%��ϡ�&ا���?j��V ��̞O��N�g�7c�B��0<D��u� �,�]��[pzH}"��'� �q��/0N3+2-���@N������Av�tq4�|�~pRJ���نFK�m'��J�ټ�Hn��Ʉu̵�Igj�l'f�b�\sR(9�� ���5���DBҴ�,�˸f�֍n�8�Ң��V�3 a�F7v�t'z�-1?�Ƀ͓|%�+�S����z��ܯ�z9�X��^*��.B9�w{?��V95�LE�P�����CS�L"��RJ$Va����"�Ġ����C��|X�+:�@��&�0�~q]�"f����E*h��f���UdJG�ԝ���a�~��I\���,_���a��wr)E &gzƚ� ���^ �� �f��t���C(���l*� *��Yw=�sX�sYh{��[�om�)�B�!R'����D?h�����եT������������P�����:�I�y�@�c��/^]�(��u�i�t8��n<�
+8k@,�߃��Q���N�t6,9���uZ4��N�����hB��
+��h(@� s�%�Q)�����I&�u..�5�g�PB�ɺZ�,̞%
+��xo�#{ڞ'��#|���Z�( �`T��b���rJ�Lˬ��{a�iٹHi?���W%<\��.�w�m�F�#��c�z��kG��.a�x�+\N�:����� �)%H��a}�j=�ʈ�⣕�A�o@0�;#�Ε��nnљ��D�Lb�Y�� Hp�}q�=��Q[�l��2��S:;ׄaK�5��(�����N�����*�b�*XSW�iU���9t�Q�\�U�ݰf)�^;�vя�Ј�: �O�r�O���;�Q�#!��A��� ԚB'�S���Gj�fɗ#d�Pپ�_�9ޓ)��z���(��Š�𷉡����F�PY?�ͺ���פ�M`_�*c���NR��q�M���{5��u��E���U�#��@pz<��]W��i_�>��������T9���ˆ���G.��ڥ����u3{�c�����ӡr_L�$��z�HK�J�U�׻��뀘߰>��浳��,wK�+�F 2��YՁ�������Uq����⼟) of�Q�x�-ё�Y�-X� ޟ����u�VX~��U��²^��|��"�E"�#�qቋf�'�xo�.�� Q#8�֟\�eK4��\ć�T��|��F�(S���#�cV�>����Pø9�#/�ƍ��b��+��d��%�a�X��Z�����=CP?1��%ƀt�< �N���A��$�ڄ��������>��7O�L �_֐�vU���S�&e�]6�;�]�P���n��_N�s���[�̺<�i~�㦊'ѡ���jE� [_���W�v,�-�]%%��#&o�3;����^O�T>I��aW�Z�8�!9c̄1���X�K \��U�B�����Cc%�;N!$0i�{��Q*���^�0g�7,��~tdig6��@L���2_��#D[��+�SÔ�٥v��1}8$�TXU}]����a˯�� �U�yT���y����L���� gl�W׺��g9�v7�Rю��M�6z=�<�$�DR�W���_@C�1��7
+-���O��(�("X[ ��]vo�xx�)��ң�/���y��7W��%��\�V{���~�>{뮧U
+�6xd���P�)������V���!E����ٜ(�."�?�_�t��N59<~�</�'��\�Xʪ�E�QJ
+�� �L�n�'1��P`2gD�����L�rnXsM����~�KL���4<j� �D)Y��Ar �J�� �\AZkޯל�4�'3� ㎦Ĥp�!;�ViX�5#v�𤣇LM�U����� 8��n����n܃�WѠ���hc�K�.�F��d:e=;c",1��0���e��ȍ� ޕ��;P ���B†�����r: ��&�=��������j��%��p��n ��e#�[����V�/���>MR˼��D����X�j���=K���V��:VZ>#zP�X�D'��a�{S����@�6C�����{��û����u���Op�6�K�R �_>sc��^�o| �]׮*��@`���oӜ��폩r&-���n+���cA:�Ө�zMMM,�f�[B:�CA�g�eaM���%�,l��{q�-o����k�>+'8�&��3����Կ�Tb6��-� ണ�X��
+��\NxHS�:Q&��@�y1q�f�;7ì^p���`�H��%A� ��d��p_�|i�܄lm�Q�Q8�ŏ�N��}"�<>�%�52�^fs ��;vz�՟2(��RT�қP�F���;�*`�'v6 LF�4oX��k�~�, a�;'���s��!tec�ŕx�C�9���5�[F��U*�ּ��K ܏<c�޾��@��9ā�9� �чF�C3��_uM�������7�G���0P����|PǬ�/�������߯]�*
+��"G+םX�sXd��`��s� �}|�E�E8����izn$�zp/�-�W�|$q�0�@�gE�_lz��W���RX� Dl�-"C�ƙ 뭖��v�N:D��Nq�����J�H~~E�����h�#\�dui�ߡ���Kp�\�u�BK������C���3���`[م�7ŝ�����|�|
+^<�^|�&x8��ϓ m@�b�a�PP���xpT�F��͏��R 7>l��7U��]��^�=s�-��7w’[�X����� K$�sYD��þ��>��Gt�T0eУ��t b��nA�/t.E �X:Q��s@�$�R�����"���fh7,#��w�4�bT��{�\�� �x5c��P
+������ �Y�|�2�a���mY�4�P�-a�`d6�|��/��C15q:���K/F'��ۨ�3�A0}����W-��(�i}5L���Y-�{C��C%�{4l��&�aN�L9�P1QMI/�G���"�.�<+�mz���W]��80��(��&ߝ��ɤ��_uU'>H7���F\���N�Bf*���B}�xovַ1�x��CC͸�S}�H����U�XϺ�H[�Ǎ��X�,�9��ƭyg��uto�b$��r�]�N�IGJ���%ɗSf7-s�P��"��$t�ԩ"��z}?�7{j�xV&f�\#4l��j�`8������5���?�{
+]����B2]H��C�f������+�a� 9h�s�Z� 5����v=}u@!�V =j�� �����I�����#�b7jyK�
+ D ېZ?�VV�/��8#I�&��=-�+�T�fKt8��&���C��/��q���ҳKW*�h.ZU����.(q?F���ç�t�掍��{�vw��/ �G����[�Q|��SN�~���d� O�)���P
+�LU�$/����E���m��o�_��/TK9�zU��2yG�J�Zsj
+�)���B'Q�K���j�49%I���T�2a�u�\�h����,8\�{t�`�VU��6h��pe��Sw#�sb��oeq���Dj��� Lv��=�
+̆�>m��7��8���3��4���U�Q������1�� �5�Iَ�J����3�'�A�}�.s睫V��G��+Mc� )sR�?�]:K
+�0k̂S|����3� �y�l(NZ3��I���t�J���
+�9~��ѝ���e�����
+� olT�}�CH�`��wn�}�����u��$^U�A�����1&&6�Id���拉��lE�,g��B CX#F�%Pd?��c�O��YE������-��5�x�( l��k�~�j��{)�_d���R� �s5;��GT�'ܴE�r���U����5�_Cz�vQ���6����-��W�-���*������ƈ��'lw�oM ~�,n�|��K�Z� Ԉ� �JUS{Gx��w��Z����i;����=J_t5�9c?OB���P'�sN��g�t����~=��\m�:���%AhreD�z�O�|�-�"��j�Y9M�#)�hm ���gv� �����6vE�
+A,J��hA�苭���G�rѐy�MK��x�0��W�j�f+h{��������=�9�XJy���[gһԴ��@����� -�ӭLw_nj�Rp�ɩ@,�Gp�V�#Mp��t��9��Փ�����[e��鶹j��Di�Vx�TBhy*Q���"Y��)�?(���%���Ʋ���@��:f���_ȥ�mۨ��,�N�$�-��yz�a�8�0�[ ɚ;��"��cY)�ܠ�6-���9XF�2",$ ��3���%��^h��!
+���<�%\ܭ�.e6�w��6��?HU �T������E����y�{yU�6�#����!>�)؁͹�N�Fa�ۂẖ�D<z�Ȇe��IT�X�����$��2_� g0}���1Bf��Hst7�i��Y(<���rA�>�U)� >ʼ<��"�~�~7�hJ�2�;%GF�R7�G`�جR]|t6����pA&�>s��"�EU�CK;��8��V��<���C;�v:����]�_���DJJ���Q>N�Ĭ�ޝ��}���r�械Z�����#�x��(�%)��-���.�J$�}��2�j���_��{<��.4�J�ɻ1 谈b9.�h(|�8N$WS�.��Dt�؅zn1��:Ir�]�!K���T���|E�.r9�ryl*�t�㓖'�cT���8��n]��T�?D�iC����\�yl��!2���te�d-s����+�����m:���N���_���ןIh����Q�� ����>�J{�;~%�#�eѦ���.&@�r�����I��V�rN�e�W��:&�E Ԏ���
+ZB�����D�{|X߿�n��af��>Z�Ӫ!A�U��Pc���}�M�g�*��ͺ�]���:��� �+��$b�hS�ـ�Ю��X����EF��&Y:��\�\��Ib�����>/wg��N� ];��]�3R�$*�0�:����Ń��OF�Ss��G�N��+PWW�G��T�Ѱ���e>}&�����x�i‰�x ��BQf4g[���0�_T���:�凴���`�2F���ϝ��Ri{���P�N�*���}ާ��A��q�?�$0�"��l���F��o� 2�`g�
+qF�;��u:ߧ
+��N��~��+��P���-�H���n�q;��\�u\a�J�R���W�,���y��-f&��$)����s]7����́�h%��pn�=ז��/rE�=�4DY�ւuL[� ��%���"���S &��Q)�ʚ7�*���[��7�lku~`��_sE���e��A�\f�����7����+�z<�;w��Ʒi{�S?v�o�d��^?v�#Ѫ� ��U~/ �������mUTƇ'�S���N��E��T�x�w�7�5K�� �`ؓ��%bs$�.�@��;���t�oХ24p�7��H�$^�d�.4so��hc5qG�HG�P����.(���Y
+� ��j��E6}ϯw�E�3G���gKuU ��ԩ����M�a՝�(^w�� e��s&-�<;ń���3cX�G��q�x�N+�N�Tұ:0hܧ���#�c���-s�韇�ز���5�3��I����ૺ�Zc���&ދpc�k��M���ew}t��>�[/�^�=�
+�*j�)�*Q,� �
+��e����r�U���[���Z�����7�t��F�e{�Gw0+)e/$�ڥ}(a?���!����\�o'F؄� Ur�Gt�R6 �;C7`��{GL�9��� _vb��-���Sh���sW���f���t���ҍ�����h�eM�6ĩ�͊��W�ؖ�D����UJ��޻fܜ�/�H����2r}_�*D�kt�]��3��Hv��-
+�+�R�{M��^�ݜJ7с��JDNrk�Wf�r���ü�]mk�}��`���
+ ��? �(w> ��y.��,'
+l��� ��jYd
+:��oa�Z-3�!���0�
+I�v�NҀѥ�0#�'��J���~���D��,j��%j�� ,�:�)�p\�];<�D^�UWԲA������jH]-V�;o�,r�<�����]x!�_.)�>i��K�/>�󅬷�'���̬��f]'�����kĢsh���4���b��y3�(��CGXm8k�UA�cN�P3lB�9�%��6�0�9/��������K�����W��AF�����Ʋ�IrV��-��*�'�NN�*�賈���!j��,y� ����"��c ��4�&S�>i� �(vNLgP \�p(�:Y��>P<f|��8r^1�:���@zpkSCۋ��`h���ZH�4k����mP`(�n�8yd॰Q�pj�g���K��C�X�) �6nt��͚'2(Je&�|��5��Mm�`�����M���2Hq�a�Y�~� �:�~�-+���u���<"�P:8��1�~xͲq�R�Pɵc@��6C+�+䫤�����vHb���o�li���n� Ɠ��e�hgh� �٢.}HD{-e*��O|Tő��WΘ� ��a����y����J�L34��^~
+ҡ�����$��9>��H�a.�tw rLƍ��|` �CW�IC���&�"�AVE�b3I�9,R��y����2����"��4���6� ��T�W�aJM�J���Ҥ�:��"���{%?(`bp�����'Xd�".�Ԍ��Bēk����L��"0F ��펦�xn�5�����4]��d�\e�)��0�/Jr�'5~sL������<s��2�3���� H�v�f�~���\��-��>�Kd?f����%p%@��� ���Ώ� '۫��u ����h"���pc]�s�a^^
+��dž0�x����KE�� /_~F�
+���wg�þ6qD�FoD��M�mg'ڸKq��j���Mz�p�U�:��I��&q�1%�ܨ��N�`������ε\�0�j�x2�:����d�;*�]�8_)�j�xN.f��_b����/㖅�צ�W � Ҡ `v�>�ڽ��+�b��y��X����D�ϖ�ދ�����P�`�/|� ��0��إ�5�u��>.+gj�+C�,� ���}�`{���Uf����'ݻ�(�p���`��Ov���x�ALn�T�۸�����(�}1,X�'x�����B}Xk7�x���{���Sߙȍ]�wg����7�Ļ�3mM�M���B��%l�te�S4+2:���hï�F!3vO�� XS{��c�?D j��a�����6z����/�hx�]�����rv��Hty�$z�F����`{�jO���]���[S>e "�E[�JJ,ٯ��'��X��)����Ny����"�2�M,]�#�
+�H/����-4X!&8��GH��<�W�H1�0��8�)`|�ǶDJ�Rv�~���٫Fz'�J�m�e^�����'4����>��Q��i��y�B�ѺW� �����n���\�b�s�(�S[�95ialu�A,t@S- �
+Um)�^��X5L���@M@<$3_��X��X(��QE&�
+ƨ� <4*IWh��ч^�'V��!�Ow�>0��ׅϲ_� ����lǪ��8��dvC��Q���@�G.xr< ( �3<�,����P��2�Ӝd�RM�?w!r/����@��=�ܨ��*(࿉�2�9)��.�iA��C�C���Y�@�>�i��S���+�GЌ5��J}}~��F��4�0��()��yش��|�8�Vv�;-^ "��=M��Mf�SSÔ�$L� ?6��[ ���K$Ԡ5��6p�<�k�U\Gy�=Ze�|frh%r���u�1M�����ױZ���e���VuӮ��)Cm��By� {K^
+endstream
+endobj
+758 0 obj
+/UGSFAT+NimbusSanL-Regu
+endobj
+759 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+760 0 obj
+<< /Ascent 953 /CapHeight 953 /CharSet () /Descent -285 /Flags 4 /FontBBox [ -174 -285 1001 953 ] /FontFile 848 0 R /FontName /UGSFAT+NimbusSanL-Regu /ItalicAngle 0 /StemV 85 /Type /FontDescriptor >>
+endobj
+761 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+762 0 obj
+/PXVYKT+CMSY10
+endobj
+763 0 obj
+<< /Differences [ 0 /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /arrowright /arrowup /arrowdown /arrowboth /arrownortheast /arrowsoutheast /similarequal /arrowdblleft /arrowdblright /arrowdblup /arrowdbldown /arrowdblboth /arrownorthwest /arrowsouthwest /proportional /prime /infinity /element /owner /triangle /triangleinv /negationslash /mapsto /universal /existential /logicalnot /emptyset /Rfractur /Ifractur /latticetop /perpendicular /aleph /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /union /intersection /unionmulti /logicaland /logicalor /turnstileleft /turnstileright /floorleft /floorright /ceilingleft /ceilingright /braceleft /braceright /angbracketleft /angbracketright /bar /bardbl /arrowbothv /arrowdblbothv /backslash /wreathproduct /radical /coproduct /nabla /integral /unionsq /intersectionsq /subsetsqequal /supersetsqequal /section /dagger /daggerdbl /paragraph /club /diamond /heart /spade /arrowleft 160 /space /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus 173 /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /spade ] /Type /Encoding >>
+endobj
+764 0 obj
+<< /Ascent 775 /CapHeight 775 /CharSet () /Descent -960 /Flags 4 /FontBBox [ -29 -960 1116 775 ] /FontFile 849 0 R /FontName /PXVYKT+CMSY10 /ItalicAngle -14 /StemV 40 /Type /FontDescriptor >>
+endobj
+765 0 obj
+[ 777 277 777 500 777 500 777 777 777 777 777 777 777 1000 500 500 777 777 777 777 777 777 777 777 777 777 777 777 1000 1000 777 777 1000 1000 500 500 1000 1000 1000 777 1000 1000 611 611 1000 1000 1000 777 274 1000 666 666 888 888 0 0 555 555 666 500 722 722 777 777 611 798 656 526 771 527 718 594 844 544 677 761 689 1200 820 796 695 816 847 605 544 625 612 987 713 668 724 666 666 666 666 666 611 611 444 444 444 444 500 500 388 388 277 500 500 611 500 277 833 750 833 416 666 666 777 777 444 444 444 611 777 777 777 777 ]
+endobj
+766 0 obj
+/YHUNPG+CMR10
+endobj
+767 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+768 0 obj
+<< /Ascent 750 /CapHeight 750 /CharSet () /Descent -250 /Flags 4 /FontBBox [ -40 -250 1009 750 ] /FontFile 850 0 R /FontName /YHUNPG+CMR10 /ItalicAngle 0 /StemV 69 /Type /FontDescriptor >>
+endobj
+769 0 obj
+[ 625 833 777 694 666 750 722 777 722 777 722 583 555 555 833 833 277 305 500 500 500 500 500 750 444 500 722 777 500 902 1013 777 277 277 500 833 500 833 777 277 388 388 500 777 277 333 277 500 500 500 500 500 500 500 500 500 500 500 277 277 277 777 472 472 777 750 708 722 763 680 652 784 750 361 513 777 625 916 750 777 680 777 736 555 722 750 750 1027 750 750 611 277 500 277 500 277 277 500 555 444 555 444 305 500 555 277 305 527 277 833 555 500 555 527 391 394 388 555 527 722 527 527 444 500 1000 500 500 500 ]
+endobj
+770 0 obj
+/NZOHYK+CMSY7
+endobj
+771 0 obj
+<< /Differences [ 0 /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /arrowright /arrowup /arrowdown /arrowboth /arrownortheast /arrowsoutheast /similarequal /arrowdblleft /arrowdblright /arrowdblup /arrowdbldown /arrowdblboth /arrownorthwest /arrowsouthwest /proportional /prime /infinity /element /owner /triangle /triangleinv /negationslash /mapsto /universal /existential /logicalnot /emptyset /Rfractur /Ifractur /latticetop /perpendicular /aleph /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /union /intersection /unionmulti /logicaland /logicalor /turnstileleft /turnstileright /floorleft /floorright /ceilingleft /ceilingright /braceleft /braceright /angbracketleft /angbracketright /bar /bardbl /arrowbothv /arrowdblbothv /backslash /wreathproduct /radical /coproduct /nabla /integral /unionsq /intersectionsq /subsetsqequal /supersetsqequal /section /dagger /daggerdbl /paragraph /club /diamond /heart /spade /arrowleft 160 /space /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus 173 /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /spade ] /Type /Encoding >>
+endobj
+772 0 obj
+<< /Ascent 782 /CapHeight 782 /CharSet () /Descent -951 /Flags 4 /FontBBox [ -15 -951 1251 782 ] /FontFile 851 0 R /FontName /NZOHYK+CMSY7 /ItalicAngle -14 /StemV 49 /Type /FontDescriptor >>
+endobj
+773 0 obj
+[ 892 339 892 585 892 585 892 892 892 892 892 892 892 1138 585 585 892 892 892 892 892 892 892 892 892 892 892 892 1138 1138 892 892 1138 1138 585 585 1138 1138 1138 892 1138 1138 708 708 1138 1138 1138 892 329 1138 769 769 1015 1015 0 0 646 646 769 585 831 831 892 892 708 917 753 620 889 616 818 688 978 646 782 871 791 1342 935 905 809 935 981 702 647 717 719 1135 818 764 823 769 769 769 769 769 708 708 523 523 523 523 585 585 462 462 339 585 585 708 585 339 938 859 954 493 769 769 892 892 523 523 523 708 892 892 892 892 ]
+endobj
+774 0 obj
+/ASBNUF+CMR7
+endobj
+775 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+776 0 obj
+<< /Ascent 750 /CapHeight 750 /CharSet () /Descent -250 /Flags 4 /FontBBox [ -27 -250 1122 750 ] /FontFile 852 0 R /FontName /ASBNUF+CMR7 /ItalicAngle 0 /StemV 79 /Type /FontDescriptor >>
+endobj
+777 0 obj
+[ 706 938 876 781 753 843 815 876 815 876 815 677 646 646 970 970 323 354 569 569 569 569 569 843 507 569 815 876 569 1013 1136 876 323 323 569 938 569 938 876 323 446 446 569 876 323 384 323 569 569 569 569 569 569 569 569 569 569 569 323 323 323 876 538 538 876 843 798 815 860 767 737 883 843 412 583 874 706 1027 843 876 767 876 829 630 815 843 843 1150 843 843 692 323 569 323 569 323 323 569 630 507 630 507 354 569 630 323 354 600 323 938 630 569 630 600 446 452 446 630 600 815 600 600 507 569 1138 569 569 569 ]
+endobj
+778 0 obj
+/SACKHC+CMBX12
+endobj
+779 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+780 0 obj
+<< /Ascent 750 /CapHeight 750 /CharSet () /Descent -251 /Flags 4 /FontBBox [ -53 -251 1139 750 ] /FontFile 853 0 R /FontName /SACKHC+CMBX12 /ItalicAngle 0 /StemV 109 /Type /FontDescriptor >>
+endobj
+781 0 obj
+[ 675 937 875 787 750 879 812 875 812 875 812 656 625 625 937 937 312 343 562 562 562 562 562 849 500 574 812 875 562 1018 1143 875 312 342 581 937 562 937 875 312 437 437 562 875 312 375 312 562 562 562 562 562 562 562 562 562 562 562 312 312 342 875 531 531 875 849 799 812 862 738 707 884 879 418 581 880 675 1067 879 844 768 844 839 625 782 864 849 1162 849 849 687 312 581 312 562 312 312 546 625 500 625 513 343 562 625 312 343 593 312 937 625 562 625 593 459 443 437 625 593 812 593 593 500 562 1125 562 562 562 ]
+endobj
+782 0 obj
+<< /Differences [ 0 /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /arrowright /arrowup /arrowdown /arrowboth /arrownortheast /arrowsoutheast /similarequal /arrowdblleft /arrowdblright /arrowdblup /arrowdbldown /arrowdblboth /arrownorthwest /arrowsouthwest /proportional /prime /infinity /element /owner /triangle /triangleinv /negationslash /mapsto /universal /existential /logicalnot /emptyset /Rfractur /Ifractur /latticetop /perpendicular /aleph /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /union /intersection /unionmulti /logicaland /logicalor /turnstileleft /turnstileright /floorleft /floorright /ceilingleft /ceilingright /braceleft /braceright /angbracketleft /angbracketright /bar /bardbl /arrowbothv /arrowdblbothv /backslash /wreathproduct /radical /coproduct /nabla /integral /unionsq /intersectionsq /subsetsqequal /supersetsqequal /section /dagger /daggerdbl /paragraph /club /diamond /heart /spade /arrowleft 160 /space /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus 173 /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /spade ] /Type /Encoding >>
+endobj
+783 0 obj
+[ 777 277 777 500 777 500 777 777 777 777 777 777 777 1000 500 500 777 777 777 777 777 777 777 777 777 777 777 777 1000 1000 777 777 1000 1000 500 500 1000 1000 1000 777 1000 1000 611 611 1000 1000 1000 777 274 1000 666 666 888 888 0 0 555 555 666 500 722 722 777 777 611 798 656 526 771 527 718 594 844 544 677 761 689 1200 820 796 695 816 847 605 544 625 612 987 713 668 724 666 666 666 666 666 611 611 444 444 444 444 500 500 388 388 277 500 500 611 500 277 833 750 833 416 666 666 777 777 444 444 444 611 777 777 777 777 ]
+endobj
+784 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+785 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+786 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+787 0 obj
+[ 675 937 875 787 750 879 812 875 812 875 812 656 625 625 937 937 312 343 562 562 562 562 562 849 500 574 812 875 562 1018 1143 875 312 342 581 937 562 937 875 312 437 437 562 875 312 375 312 562 562 562 562 562 562 562 562 562 562 562 312 312 342 875 531 531 875 849 799 812 862 738 707 884 879 418 581 880 675 1067 879 844 768 844 839 625 782 864 849 1162 849 849 687 312 581 312 562 312 312 546 625 500 625 513 343 562 625 312 343 593 312 937 625 562 625 593 459 443 437 625 593 812 593 593 500 562 1125 562 562 562 ]
+endobj
+788 0 obj
+<< /Differences [ 0 /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /arrowright /arrowup /arrowdown /arrowboth /arrownortheast /arrowsoutheast /similarequal /arrowdblleft /arrowdblright /arrowdblup /arrowdbldown /arrowdblboth /arrownorthwest /arrowsouthwest /proportional /prime /infinity /element /owner /triangle /triangleinv /negationslash /mapsto /universal /existential /logicalnot /emptyset /Rfractur /Ifractur /latticetop /perpendicular /aleph /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /union /intersection /unionmulti /logicaland /logicalor /turnstileleft /turnstileright /floorleft /floorright /ceilingleft /ceilingright /braceleft /braceright /angbracketleft /angbracketright /bar /bardbl /arrowbothv /arrowdblbothv /backslash /wreathproduct /radical /coproduct /nabla /integral /unionsq /intersectionsq /subsetsqequal /supersetsqequal /section /dagger /daggerdbl /paragraph /club /diamond /heart /spade /arrowleft 160 /space /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus 173 /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /spade ] /Type /Encoding >>
+endobj
+789 0 obj
+[ 777 277 777 500 777 500 777 777 777 777 777 777 777 1000 500 500 777 777 777 777 777 777 777 777 777 777 777 777 1000 1000 777 777 1000 1000 500 500 1000 1000 1000 777 1000 1000 611 611 1000 1000 1000 777 274 1000 666 666 888 888 0 0 555 555 666 500 722 722 777 777 611 798 656 526 771 527 718 594 844 544 677 761 689 1200 820 796 695 816 847 605 544 625 612 987 713 668 724 666 666 666 666 666 611 611 444 444 444 444 500 500 388 388 277 500 500 611 500 277 833 750 833 416 666 666 777 777 444 444 444 611 777 777 777 777 ]
+endobj
+790 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+791 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+792 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+793 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+794 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+795 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+796 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+797 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+798 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+799 0 obj
+[ 625 833 777 694 666 750 722 777 722 777 722 583 555 555 833 833 277 305 500 500 500 500 500 750 444 500 722 777 500 902 1013 777 277 277 500 833 500 833 777 277 388 388 500 777 277 333 277 500 500 500 500 500 500 500 500 500 500 500 277 277 277 777 472 472 777 750 708 722 763 680 652 784 750 361 513 777 625 916 750 777 680 777 736 555 722 750 750 1027 750 750 611 277 500 277 500 277 277 500 555 444 555 444 305 500 555 277 305 527 277 833 555 500 555 527 391 394 388 555 527 722 527 527 444 500 1000 500 500 500 ]
+endobj
+800 0 obj
+/LYTCQL+CMSY9
+endobj
+801 0 obj
+<< /Differences [ 0 /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /arrowright /arrowup /arrowdown /arrowboth /arrownortheast /arrowsoutheast /similarequal /arrowdblleft /arrowdblright /arrowdblup /arrowdbldown /arrowdblboth /arrownorthwest /arrowsouthwest /proportional /prime /infinity /element /owner /triangle /triangleinv /negationslash /mapsto /universal /existential /logicalnot /emptyset /Rfractur /Ifractur /latticetop /perpendicular /aleph /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /union /intersection /unionmulti /logicaland /logicalor /turnstileleft /turnstileright /floorleft /floorright /ceilingleft /ceilingright /braceleft /braceright /angbracketleft /angbracketright /bar /bardbl /arrowbothv /arrowdblbothv /backslash /wreathproduct /radical /coproduct /nabla /integral /unionsq /intersectionsq /subsetsqequal /supersetsqequal /section /dagger /daggerdbl /paragraph /club /diamond /heart /spade /arrowleft 160 /space /minus /periodcentered /multiply /asteriskmath /divide /diamondmath /plusminus /minusplus /circleplus /circleminus 173 /circlemultiply /circledivide /circledot /circlecopyrt /openbullet /bullet /equivasymptotic /equivalence /reflexsubset /reflexsuperset /lessequal /greaterequal /precedesequal /followsequal /similar /approxequal /propersubset /propersuperset /lessmuch /greatermuch /precedes /follows /arrowleft /spade ] /Type /Encoding >>
+endobj
+802 0 obj
+<< /Ascent 777 /CapHeight 777 /CharSet () /Descent -958 /Flags 4 /FontBBox [ -29 -958 1146 777 ] /FontFile 854 0 R /FontName /LYTCQL+CMSY9 /ItalicAngle -14 /StemV 43 /Type /FontDescriptor >>
+endobj
+803 0 obj
+[ 799 285 799 513 799 513 799 799 799 799 799 799 799 1027 513 513 799 799 799 799 799 799 799 799 799 799 799 799 1027 1027 799 799 1027 1027 513 513 1027 1027 1027 799 1027 1027 628 628 1027 1027 1027 799 279 1027 685 685 913 913 0 0 570 570 685 513 742 742 799 799 628 821 673 542 793 542 736 610 871 562 696 782 707 1229 842 816 716 839 873 622 563 642 632 1017 732 684 742 685 685 685 685 685 628 628 456 456 456 456 513 513 399 399 285 513 513 628 513 285 856 770 856 428 685 685 799 799 456 456 456 628 799 799 799 799 ]
+endobj
+804 0 obj
+/WQSQWU+CMBX9
+endobj
+805 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+806 0 obj
+<< /Ascent 750 /CapHeight 750 /CharSet () /Descent -250 /Flags 4 /FontBBox [ -58 -250 1195 750 ] /FontFile 855 0 R /FontName /WQSQWU+CMBX9 /ItalicAngle 0 /StemV 117 /Type /FontDescriptor >>
+endobj
+807 0 obj
+[ 710 986 920 827 788 924 854 920 854 920 854 690 657 657 986 986 328 361 591 591 591 591 591 892 525 616 854 920 591 1070 1202 920 328 360 617 986 591 986 920 328 460 460 591 920 328 394 328 591 591 591 591 591 591 591 591 591 591 591 328 328 360 920 558 558 920 892 840 854 906 776 743 929 924 446 610 925 710 1121 924 888 808 888 886 657 823 908 892 1221 892 892 723 328 617 328 591 328 328 575 657 525 657 542 361 591 657 328 361 624 328 986 657 591 657 624 488 466 460 657 624 854 624 624 525 591 1183 591 591 591 ]
+endobj
+808 0 obj
+/SUXZQL+CMBX6
+endobj
+809 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+810 0 obj
+<< /Ascent 753 /CapHeight 753 /CharSet () /Descent -250 /Flags 4 /FontBBox [ -49 -250 1367 753 ] /FontFile 856 0 R /FontName /SUXZQL+CMBX6 /ItalicAngle 0 /StemV 130 /Type /FontDescriptor >>
+endobj
+811 0 obj
+[ 824 1143 1068 953 918 1064 993 1068 993 1068 993 824 787 787 1180 1180 393 431 693 693 693 693 693 1028 618 707 993 1068 693 1236 1386 1068 393 429 710 1143 693 1143 1068 393 543 543 693 1068 393 468 393 693 693 693 693 693 693 693 693 693 693 693 393 393 429 1068 656 656 1068 1028 973 993 1048 899 862 1077 1064 506 711 1066 824 1289 1064 1032 936 1032 1019 768 957 1046 1028 1403 1028 1028 843 395 710 395 693 393 393 674 768 618 768 634 431 693 768 393 431 731 393 1143 768 693 768 731 571 551 543 768 731 993 731 731 618 693 1387 693 693 693 ]
+endobj
+812 0 obj
+/EEICHW+CMR12
+endobj
+813 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+814 0 obj
+<< /Ascent 750 /CapHeight 750 /CharSet () /Descent -251 /Flags 4 /FontBBox [ -34 -251 988 750 ] /FontFile 857 0 R /FontName /EEICHW+CMR12 /ItalicAngle 0 /StemV 65 /Type /FontDescriptor >>
+endobj
+815 0 obj
+[ 611 815 761 679 652 734 707 761 707 761 707 571 543 543 815 815 271 299 489 489 489 489 489 734 435 489 707 761 489 883 992 761 271 271 489 815 489 815 761 271 380 380 489 761 271 326 271 489 489 489 489 489 489 489 489 489 489 489 271 271 271 761 462 462 761 734 693 707 747 666 638 768 734 353 503 761 611 897 734 761 666 761 720 543 707 734 734 1006 734 734 598 271 489 271 489 271 271 489 543 435 543 435 299 489 543 271 299 516 271 815 543 489 543 516 380 386 380 543 516 707 516 516 435 489 979 489 489 489 ]
+endobj
+816 0 obj
+/HNIPYH+CMR8
+endobj
+817 0 obj
+<< /Differences [ 0 /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /exclam /quotedblright /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /exclamdown /equal /questiondown /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /quotedblleft /bracketright /circumflex /dotaccent /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /endash /emdash /hungarumlaut /tilde /dieresis /suppress 160 /space /Gamma /Delta /Theta /Lambda /Xi /Pi /Sigma /Upsilon /Phi /Psi /sfthyphen /nbspace /Omega /ff /fi /fl /ffi /ffl /dotlessi /dotlessj /grave /acute /caron /breve /macron /ring /cedilla /germandbls /ae /oe /oslash /AE /OE /Oslash /suppress /dieresis ] /Type /Encoding >>
+endobj
+818 0 obj
+<< /Ascent 750 /CapHeight 750 /CharSet () /Descent -250 /Flags 4 /FontBBox [ -36 -250 1070 750 ] /FontFile 858 0 R /FontName /HNIPYH+CMR8 /ItalicAngle 0 /StemV 76 /Type /FontDescriptor >>
+endobj
+819 0 obj
+[ 663 885 826 736 708 795 767 826 767 826 767 619 590 590 885 885 295 324 531 531 531 531 531 795 472 531 767 826 531 958 1076 826 295 295 531 885 531 885 826 295 413 413 531 826 295 354 295 531 531 531 531 531 531 531 531 531 531 531 295 295 295 826 501 501 826 795 752 767 811 722 693 833 795 382 545 825 663 972 795 826 722 826 781 590 767 795 795 1090 795 795 649 295 531 295 531 295 295 531 590 472 590 472 324 531 590 295 324 560 295 885 590 531 590 560 414 419 413 590 560 767 560 560 472 531 1062 531 531 531 ]
+endobj
+820 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+821 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+822 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+823 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+824 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+825 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+826 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+827 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+828 0 obj
+<< /Differences [ 0 /.notdef /dotaccent /fi /fl /fraction /hungarumlaut /Lslash /lslash /ogonek /ring /.notdef /breve /minus /.notdef /Zcaron /zcaron /caron /dotlessi /dotlessj /ff /ffi /ffl /notequal /infinity /lessequal /greaterequal /partialdiff /summation /product /pi /grave /quotesingle /space /exclam /quotedbl /numbersign /dollar /percent /ampersand /quoteright /parenleft /parenright /asterisk /plus /comma /hyphen /period /slash /zero /one /two /three /four /five /six /seven /eight /nine /colon /semicolon /less /equal /greater /question /at /A /B /C /D /E /F /G /H /I /J /K /L /M /N /O /P /Q /R /S /T /U /V /W /X /Y /Z /bracketleft /backslash /bracketright /asciicircum /underscore /quoteleft /a /b /c /d /e /f /g /h /i /j /k /l /m /n /o /p /q /r /s /t /u /v /w /x /y /z /braceleft /bar /braceright /asciitilde /.notdef /Euro /integral /quotesinglbase /florin /quotedblbase /ellipsis /dagger /daggerdbl /circumflex /perthousand /Scaron /guilsinglleft /OE /Omega /radical /approxequal /.notdef /.notdef /.notdef /quotedblleft /quotedblright /bullet /endash /emdash /tilde /trademark /scaron /guilsinglright /oe /Delta /lozenge /Ydieresis /.notdef /exclamdown /cent /sterling /currency /yen /brokenbar /section /dieresis /copyright /ordfeminine /guillemotleft /logicalnot /hyphen /registered /macron /degree /plusminus /twosuperior /threesuperior /acute /mu /paragraph /periodcentered /cedilla /onesuperior /ordmasculine /guillemotright /onequarter /onehalf /threequarters /questiondown /Agrave /Aacute /Acircumflex /Atilde /Adieresis /Aring /AE /Ccedilla /Egrave /Eacute /Ecircumflex /Edieresis /Igrave /Iacute /Icircumflex /Idieresis /Eth /Ntilde /Ograve /Oacute /Ocircumflex /Otilde /Odieresis /multiply /Oslash /Ugrave /Uacute /Ucircumflex /Udieresis /Yacute /Thorn /germandbls /agrave /aacute /acircumflex /atilde /adieresis /aring /ae /ccedilla /egrave /eacute /ecircumflex /edieresis /igrave /iacute /icircumflex /idieresis /eth /ntilde /ograve /oacute /ocircumflex /otilde /odieresis /divide /oslash /ugrave /uacute /ucircumflex /udieresis /yacute /thorn /ydieresis ] /Type /Encoding >>
+endobj
+829 0 obj
+[ 0 332 500 500 166 332 555 221 332 332 0 332 583 0 610 500 332 277 0 0 0 0 0 0 0 0 0 0 0 0 332 190 277 277 354 555 555 888 666 221 332 332 388 583 277 332 277 277 555 555 555 555 555 555 555 555 555 555 277 277 583 583 583 555 1014 666 666 721 721 666 610 777 721 277 500 666 555 832 721 777 666 777 721 666 610 721 666 943 666 666 610 277 277 277 468 555 221 555 555 500 555 555 277 555 555 221 221 500 221 832 555 555 555 555 332 500 277 555 500 721 500 500 500 333 259 333 583 0 0 0 221 555 332 1000 555 555 332 1000 666 332 1000 0 0 0 0 0 0 332 332 350 555 1000 332 1000 500 332 943 0 0 666 0 332 555 555 555 555 259 555 332 737 369 555 583 332 737 332 399 583 332 332 332 555 536 277 332 332 364 555 833 833 833 610 666 666 666 666 666 666 1000 721 666 666 666 666 277 277 277 277 721 721 777 777 777 777 777 583 777 721 721 721 721 666 666 610 555 555 555 555 555 555 888 500 555 555 555 555 277 277 277 277 555 555 555 555 555 555 555 583 610 555 555 555 555 500 555 500 ]
+endobj
+830 0 obj
+<< /Filter /FlateDecode /Length1 895 /Length2 53767 /Length3 0 /Length 54253 >>
+stream
+xڌ�st&_�5�N:xb۶m;Ol�c۶mul'�tl������w�wϹ��Qc�Q s���U��XI�^���(�`�J��������r���w�S0303p�q̬L]&@ +{8��*��J
+*�r���a4�O������0�����tv�r�P��45�hl�`o�������)@�OI7��btv��L�J�V�V��)����-��#��N7{3�3@ �l�p0��v𰲷H8�UsWcg�?�L��.@8I%9��$��ll Pr3��2���5�����*�(�4:��k���fE���o��f0����W����
+J88[�ɶtuu�ad�W5��\�쁮z�p��T�01��� �����F�#翑����/df�72��,�[9 7[�O��h�_��2���l����j�,,]T"6�;f�"a� 4S�r5�G-c[��Ү���)loa 0�ǥ�������b�o9鹹�WH�������`� ����������ٿ����8������ﰒ�����������m3�_[������������O�?�����v���6@M+�F���("�� �gf�bгpp8�9�\ܬ?�'����h��������mn��.@�'�nm���7�:#;ӵ;tZL��R��c�{�:��̊F+��`��D�%}�H�n)������fg�؁�lB(1u��)g�;��5OP�����"�����K�z��Z�Ɉ�)���Y��7�d?���\��]��N{9@(!]6Y���jx����I+o�ԯ�6�mHP�˥Z �r
+�3�]xI�dtH���L���r<�ʞ�F�������}k){U��Ƥ^��ψ�� �% -_�O��T��� '�z"_I
+����m*�q�l{?L��j��� $A��"�U'��-b��y�,�?hpOw�_z#6qwD�{3>��S�tp����"^���1����O������4飜:a�r���2�:ʙN6�AA�A�� �<p�xY�6�Ot[����`s,Zd��8V�O��|^��m�M���3Q�����q��Izj����s�`�g�8EC��]�:>��7
+��1�����u[��EL3�h��N����4�_tb��~~���
+���;��~�O�껪Q-?cP h� ��~��*n��>��uu�g��p�_D[��o���п9�A4fԂl����Fi� j>��������.w1isc�h���!�h�;1��v��� ��LE�_?� ����t�1��Z�e����H 4l8��QKdo���!��P6ޟ�;iQC��X��wFdL� O�K���[9��&����o�؋��[E�dx��۵�L<dƼ�ß���죺�ߜ�6��:�a�(����)��|�uSNj�$��|Ld�L�`��P��U�Mк@s]Q O���Y�p�L$���c�9�F�Ƣfjc3M�Ϭ�}��U�1�Q�h��{� Y�a*⬈aN<|Ғ4+~��U��-�����#6e3q�o;���kjK���Q4sS�I��N?���Zv�������ıqT��I-H�ץ�X��s����� �c� $�L�"|ٯ�l"VG���z�\�av�/��J��o�Uj�� �;sH��"�������e�N�•��`�>��]�(_Y ���Yξ��=ސ��I�ɓ�L�p����C ���ڂ��r� �+�s(���A[���iK��yė>�-�Zy�3����������S� �Ӏ��n3p���x���r���+|5Gם�h��
+��Dl�Y_���5�=�.x�*!�i Pe[��EEߘ2�s�>�W��й�rh���$O�X�u�x�r ��_'� ��>J �=�� ���Yf� �*e�b�q��͘�4N��}�:�s�����ual�GP�&N��'�h��_e��_���;�����\���L�9!�ZJ��w��R�7�f�x�iq�����
+�(}��Ɛz�B��g!`����]�#��������K��аxv������ըYOBᓂ�L(gc�M�
+�0;1֧bX��i�QM=�zo��������'��p�QR_A����? S��8��̒_��|:��y4uV�kJcTn�3��6*��^��1Yvq#���m@A�@���3��M=p������#��(H�#��2 ����E�>o�"�~����}q.�k>ѣ���p����%J� =i�?� ۹w�_{l,M�q�1��ݰ�T[?3����1�qܻѝ\}!1���D��&�;����� �cg&.[4�7��$*�+�����$gw4��u�'? w��T�wa�(��:�ƝNj+�*Z��(MD�4��i�����-�@�7m�[�ʉz��O��Ƃ{���k�D��M)Ʒ�"�)��ʒ�[|���+Ȉ0z/����� �Vd2>���f��kh>��TH����( �ḃ�!�0;K1aV�����~h�ʗvyf�W��b�����w�J
+�F"]dF���(��T�����D�k]�X�g|R���r��Z%ܓ������!߃e�e ��:�j44��0Q��H-���Q�?��p������~�+-~�ͭ�Bt�kv��M�pK��Q7ɺЃԡ�-��D�;����TZ��'��u��a�¢O���D'�m1��7��jƎ0J����0�#f�۶Ëن��W��w��ޅ�Y�ц%�πer}�Z&���Ȇ,�/�ȷ�����R��ˮ4],� c��� -�/�D.!�8�k�<n��J����U�^ՠ��8^��e/����IED�ϲMnB*�.� *����ܿfH.(a5�%D��˔�c�`�-��2��8�P�S�Q��2*!GvͺT���� ���qd�s�oֶ���ň�$d��LT�4���u���|V��%؜/�b���U���7 �M,��[r�<��A��cőd��e���6K4Y�7~�k�DԵ[ǿ����.L٣���iV�.������Bi��u�u��L8��[�3�,d���Ģ�Us�zzm��ٴ;��\�`�ԍv�;B31�q��bG��h\հ��. m�Ρ:��ڈ�kti<�ُ�I���0evK�"npQ��B�CW�BЏ��}��U��.�~�� �9�����r�3��H>M?�E�`�/j�R0Ѝ�7�|ϵ0 c��R7�S����݇�>�*{߾˺B�U!j�<ȵ/�����kF��WQ���Pw��{h'DHaE�/�`���ә��A�\�
+�e¬?n6S����$lV^q }���QY�e���J (��J��n�0���`,��XE��!lU7�2a �*̩ƛF�GD1�U)g��S9A�<V������-���&XH�����)�c1��zn��>������=�2b����[~S�}$(��.�����B0�ϴF^Z3B��J����`(�O̔{�g^8PB�Ϡ�����B�)��G^�$��3����ڟ%��턓�nڶ��5u:S�!�u�����Ve�1ш{i.:�h��`��� �+�]��B�+���V`�Miz�ĝ <A�M!�T����X]$�P0�J!ە�\�ܧY�0ʲ�e4�\�N"�Ӭ�;�������O4����:fZ2���'�A ��$�o��@���E�Ř��f�څ�S����g�g�(w?�f��T���s[�Ca��dz*B�[�.�Q����H~�<��$&���&K�zӈ���Hf�֟7-TZ��s�FP� n������rW�o�5���ʥת7.�����X½��yo�^a�E)o�S!�=x��&�x��3�*A$��>���_���/��Y�5��NKd��ǽ� ޅ������`����|�U�]m`#�ݦ�lPR賸��Lkne^$R?-�yH��_��$Q�K��z���q�x�d��܃\��V&����%?5��@�A������E��d���*��Q"�� +���/��8��T?�8�dz�*k?Fk�������O袧�^��??��[�j9�D*� !w�C��eu}�T<�֢-��gG]�~�v~a��x����,GDI=�ӆ���r*����ؚ�`u�o�^*b�+�bL�c�bX"LV/�E�0�¥>U�� �֣�]�*�����з=�� { v�讔ge�����[䑶s2?vQ�*��7�8�Ē��-ď�+ =nϝ�*x���� v�VC�]��o1���%Ԝ�>>f�R�@�-�����K��n�t,��m&�ណK���"yV�>q���$�DT���55�/�0��}�? ���� b�r���x6�?l(��1�l�ȤBD�J�&]Ml�2��S�X� j��f���h9��_U����XK��iB!���H�L��ñ�W$���`����- !L |x#��m��"� ������ֺ��
+>lhC-��`�$���z~��,�#i<�]�4�]�7ˣ\��a��{!B�W�|�쟐ӜN��8�/=�G�T P�Fe� �e���r�x N��>oi��� �[}������n_Z#Ǒ�dI�/��&�G����g��웉ӗs�m�����36�.0����P�ϑ�u��6[�Q�?C�|W��ʫq�щ�R�X����nK�.a�Aۣ Oi��Pj����OMOP@��� z�-V�s��ty� 7e���P<Wm�`B�S.���#*'I���%h8U�E9� CU?$s.(�T��{ttRp�����K-��%���1��4���iȉ%.���i&��/>K���]s�����Ԩ��!.1�fE]��r�M�DA��6Ѿ�O�.���¢�n�)Lf�<�T���D�X1!u13�E�{'�Rj�ba���41�0PL��� ���L�hͽ����+ص��UǏҎ�Ldd$�<�hO��1�t8�) ���} ��PO�%n�'ʺ��L�ӽ�x�4�Z-D���1J�؎��� �ת��V}��R�/��_��)GpEu�_Eɣ)O~�J�o���-�d�1?Ky4���}X }"O0�*؏�R
+9�O������ ��6�-��~v8>�X}�9P+�_�zmw�H9�C/;,7L ��A=C�A:Ap}a���ڳ�7�qr����Z� ؚ��]B>6�C�j9�,͈Jd��e�>yȰ\��=E�Q�!����~�E�H��]��f�7!�5�;!��ꔎF��� ;�ۮ�x'Ij������4)*�M���n�!tdIU�U�Ln݊�0Q���QU�o�e�&�k�Sv\����7O>@�n�G1��$V�"������^&hy,l�����9L�M�xk~�p��|�4�lE�(�H�_~5�;_�=#��[���)~��2���9��/6�aق֑�&̈*�(�=���MG���Pⳓ�`����(����}���5�+X6�Q��,��2�I]v�H�ɵ����m7�$ i]�i�;�g_*��*�9�"�M��c%yh�]�^U��ʨW*Ye��������'���!Rע |��ϙR��xO��$���$�9f������k7���߆ A�6c!�e!F�]����'jt]�}�v]Hf���a+K�&�)(;V1�u��6����Z�aK��1KT<?`|걛jkԌ\�L͟t��.�f�qo���t�n���p֤YF�&I�����'�X���X� �ZG� ���l�����%(�Vq����� |�V�/���6�3����#�~蹿��a��"N�iA��u�y���s�s`��sŦ�5������P�}��eg��tX���V\�0�K���g��*�xj���
+xw�bd�.����$�{$��uC��
+g�uO+��/ŧ�)����_���ZD�S���$0c ]�ԍ6������ ��9S�ɇ�ABt)7�� ��B��8����J�c�Y6W/���3��C?)ͷ��Ln5�DI� �ƐVM1 x�]�!C*�w�ߠy�˖�9���4��&f��E��� q�L������M��+�[��7����M\m~y�9�Mk��:� �rl8�U)�>���=R�n1� �F�N0/�.8(��"�CT��+D2�$��[�ƛ_K�"��Z��G�)�� �� C�Iw۱�i�ٮ�F�v#M��=c�
+s{?y\ՠu����D���V J��:�^Qsjs�����K�ӄ��ݚ�ױU�z�f]��_�N�q�cz �����Ȕ_��~�����pdz�F8��(>�C~%e<����l�|#}9[T����R��u��H�G-����(܀�Lf}��U}�rd�\A��gp>��\+Eͬ���p��C�{��;��ق|�Uh�S-5(���~��ѐ%������Z>��H� ��K�7�eI��G� ��Cw��Jɲ:ٰ�5�Y��$x�Y]_�����Y�^@�o=(D�t��]��;1~����?�:��^Cf�#s��)��e���i��-1��2n<r�� ���%1��9�+�����e_��XJ�j��p���*�� q�I�0"��&(�C��#"uĘ�y� t����5��C�^le��( s��Cv�M��0*���S��B��)� ����Vd6� ��و(#��wZ���2y�)�J�A-BI՜�����,!K �n;�����,��pv`�S(���d�p/��*A�L�z�6N��{,�����D@v��Ȟ7��r���Y�-���'M�s���_�\�B�M��8g�� ]���j.����E�ۢ�>Z����օ����Xm�.u��V?���3w�"��ŧ���kl�.V�������.�K0�s ��[V���$�MB �&��mwu��;��&� �^IC@c�ű�'��S��Z�O���V���z�w�=�ָg� WԤ~]k�ҿ'�)u�br
+�L�I��=| �2}"2��yWEY���
+�b�o*8LgU���V�v��xu�0j��IP��v��c�C���X�?�B� �H ��nj��<���*������jz���G{���q�l��S���1��j�GL�5�PA9%���k��l���$����|&�I�zpHHͨ�I҆���~߬�z-�Mti�{�R��1�}��Q�%�p�fd���IRP�2�o���:��^�-��
+�<i�#��0Y�U�O����=uI^ۺ�*������
+L/B>Ð�8���Fv�?��W>i��l��F@N��ߩ�^t���!06K�O.K�Ԝ���/MT�S]�JϮض�vt���w���ak�L���v�¤f�y�A���{�Q�
+���c�3<��Ik^֑m��4��fL�Hqyl�?W6�{;[~��^�:*H=�}�#'�:����.#)V�#�o �I.�/��6 k��꡵��&�?˿P斅��W&�1�m � ʩW?ti:HC��Y���y�u�I�6
+7�O;J隬t�HE@�#b՟G:��
+�xg��\�
+�G��7���=ƭ*6S�N�[��d��%V�vTB�u���]bO��q^�9�d,x���I��1�MN�+��Uy�2��_�F� ,Z�� fvg�',��${!g~�������3I�pٝ� �@�{QV��J0_�vV�\�h'�Q�U_)Uj�7�]�n����)�`�Cb�;��"@���*�vECݒD��1�٣�J�6g��A��w�{��ða��p�� M�~��J4�� ;�T�^��/6�ڙ ��No�8X�Aþ����P���\3�����t�NY���v�(��n���g�����.!���ȑV�ѡ��G��[V�\�/��׌����8���@ŧ"�qA�����>� �ܹ�k�5Y ��ɗ�ZNZ���t�-У�s�����V�@MB��\i�Ʌu���ІxQ۸�hUh�-0��B�;��
+�U�h�&s������ Q�HկQ��k���ۥ̻!k5r��_�彔P:G�hڋ�ӫU��ƻ��8�3љ0}�+�M:� ����"��"tӣP;ԅ:��1+��x��trMyT.Fj)[y�܋�_Dywe!z�"��������Q���Kˑ�ľ٣�ʡ/'�<��[ Ʉ�&b;�_�Ҫ�ul�[9��n��$�S���b��BNi����'s�5��w�� BJ�3>��*�=J8v����Ѕϡ��^w�T�>�^�o�|�/� /�O&72�F�~������H���_Z�W�����i�� ���z��|�q�8p4�v.�%x�o��ɷ�䃣3ļ�f6�+R��Y.�� ��/�4/=|.%��j�ə����/B���X���e��'�X��pې?���Q� ���#w ��� N<z2(n� �)�6C�(��MS
+H�� �Pz�(G��%�+%f\M[9��q��6O<��$����p˛��o='������¤��#>1_O(��BN�vHO�u���A/���KC��U��?É � �A�/ו-� p�t�;c8L��^X�i/ ᪧB����A�:�a~�KSFFTr��>'1i夰 ^���I����c�����!^�s�l��X�I�_k��a��'����q-� y�f�0�L�2�ԋ�S�ޙ��g����*� !��H q�e���W��e�!{Y�&���E0�إ�G �nM���l/��-� �s��$ʼ8�GW����+��n����AS��Vꮥt1�Z(�E�B��czV/��M�D;�-���U���������%�뉖�c/E�d`)� ,L�.i��秲���>���O��$���P֘��Ÿn9��R�e�C� ����P�,*1����6m��v֞*��N��S{ �
+b��s<BʒXG|��f�4a��� �{ji��F󫘳��W.h,�O�c�nϟ�~���?���� g�N �f�=S;�u}��;��oLZA�kn@-���&=�X�`9�����R�F�,>S����;ZiFyT *,��QG��
+
+�3��%���V��#�$�Y���7�2�ȭ�y�_ � X�:�]6�0�r�r�x���}�9��'kq�!Ʌv��������=
+G5�1� ���������yF�:�;�̾�6/���Qnޜ:��ѭK���)�w+q�����Kj̹�^nU,�1eGeP- ��98CJ�� ��*�� ~��U��g�eɣ[d����57�cc����ş��@���X�gJ�/h�ÿF��m�|kK E�Q��m��Ԭ>k��W�#�L��2�Z��7p�y��������Q�+\f�Kb4j�E{�
+cH��ר����(���z�2���Q�?:��L�d�^T���fS���W���N'�m�֢�l*��nNT}S�i䣰�iZ a���jD�Ibt#S'�H�.Ŝ�Pl�l_V�%L�#F��6��ӽ�����I53��I�A��Vl����-*C�lҰ`����"d���M�v/����n=I:F���݂}�=Nk�����E=K{���k��}�q�p*������|��H��_�=n����4GWV���������yU8����V��<�P���~XKW%�K�{�Ot��_y���g�)� ��d�3◐�Fb�`�b_�-T=!���ڪ�CŇz�I�VuIe?�_����� ɫjf2��D紎�ubID:ȵۻ�HJo��- �T�Ҋ�W"@f�նv[�ȼaB�ۙ�������,+)^�������".���F�#A�<h�5b��@
+�����7�����k<?��+\Fx�^�v.�g'�-�Ph��]�]��YzW*8�7=N����M9X5X��ה�ƶ��l����}���NF|�������lݞ̜,6̧��^w��o�,��������m%�ېL�h�tƳjؐ=�n���x?�C�xv;�*h^�(����-5��ӑxe퀃F�s茻������Z��$3��&���xf@���o<HIP~9h�;�:O�����JB��!����ZE'�q��ɠ��X�L�,�n�La_�nG�mz5b̈́x����>7�`���=�!���*�͎��ێ(�^�E����U�Z_M���c>����� <�|���7����r�dJ1��.Yg��c�+G�y-z�RE��_��
+I��v�|��Ve�����H�ʮu��tm�/�ZW~E�,B��G������;��CBE�������f^� s ��ji�]�)����xᜓ<3,�Gs��F�? �p�Arvn����XL�����+���H-ʋ��=S�d�@2ڞ�s��kP���f]��������%>J��hfd {B����pB���>��+����O�R��S]�S�-��'� �3r!7��V���j��A��O�p���/(T:�铫@����F�f�\},
+�ќ�>3C�$@w����`�Et$E�y� �87-K�mZ�&�������m��,Ks�.G�I�ED>Ұ A_�S������0�4���8M/�T�k���N=Qop45-���{{����"� N�d����|X�� X?e*�ː}.��e��P>��n�ŮF�q�����F��a��?6���!W.�Qǟ��~�'�e0�]?ݿ/Z�;X{�r�H�с�Մ�����qٝ6�8�K.���e�8SN�䨵��fܡ�]��JL�>3�D�}E�|3�kt�
+f����!���MCl�ǡg��5X�1�gJ�� �+��OR�K�2���_���=�3�+>V�KA��)t����Su�G��ߟ|��D�f���_c)�����.��*X��,R��z��,oh��"+����I �iZ�x��B"�F���|��X�j8�2��3 8�{��z�� ��ZxBU��Ֆײ��� �G)DžҿcZy���㦨W���N�z^f{`�߳w��iJ詚**XX�LCc]� �R��\��ŒnϿ���%�}��m+5��4gY�p�R3`�yJEW㊤��jBvx˜�5�Y�l�-�h����_��㸖g\@�|�!pv
+r9��X����e�]�.h6��J�u�zt_EԸ��'�j�`��eKŽ/i����RS��ѳ�� ~FI��6l�7_��YT(��׾�m��/������zn
+M��V�(�Tǟ �*�˿�z~I;�h��_�ո)?q�L1@[��W�l�?�wo���U2��*lb�@�����ɓ� ��@�3���tHݜ�—��k�Q��qp�}T�$P)�;M��3h�O�����Ϥ�N��Fu���ou�]4ñC[�� �C�
+V%o�d�"��S0��j�� ؞F.ۈ:����l�d���}�gJ ���Bpm�� �~�vj���jc����q��F�.���OQ�-�L*��gq���{z��l#���{���ԃ�j�d����)��&��3�'�ˑ�[��p�Z���Rq�����leI���/�y��H)�J b�#߅�Z=�ݤFQIrl�L��!� �W�5BR9oܞ���βF��A���?��V�Րb�N�H���Ẻ�5�#�Lmr�|�����)즸��e���]IZ���| 8�:%�^��(ߖ���d��/�X���i-���E��L���I|t�r�,?�a�^���:�9rGEˆ�ݖ���6k�\$.�E\l� ������w�&��xAGS�ԟ�R֖�Ut`K�}q r�<��!W8/_�'�Β�а�w��5Sl��(#���%�"�8r��^Q�g��I������p��Ip�� �>x��6�C!�SV�;��*�d����5��-O�Y�=�O�R�Y;D�(>y��+�}��.7?&VK�ԡa�iX-����+� :������M�S�ϝ8�'z�lg`Ѯ7�2�zcO�����\���YF���`7����H����z���R�j�6J�"y���;���s�H�'J�Qf~�lʼn͋~�*7�~d�WL��V�����e?�L�_�����]�eEdfH|t�Ml��mX<��.��E����i��-�����苵�L\�I��;KZ(�Jq��Mݙ[�`��4�Y�@.�8��6��#gFS���\�|�X�>�������1\�07�_���Övy�$ �˗��&��ݮU��=+����f\�*$�b��)�0nY���`��ƶ�'�d���)��9�o�<�ހ��m"j��PЮY3V���'�a����T}!������R��C�ŭ�r��ߺ�%Gv����+\�)Pn�i�p���\��.�ibD��6�n� �q����s�/��BՉ1���LR�����H}
+F����P���'��v1�s\ǖ�1̦4e�R���NUƱ�R�`�|�~��?R �oݝ&x�#�W=^�_� �X^8$(
+P�[�'"{�e����x��Z,�,��Qk?K�0��ש!2+�2�8@���!�)���e> �XZ���g�ɐ�|���� �a��:��W��Wn]��\����VX�x� ��΁�ۑ�ൟ��~I`�*�9��Ȭ�t@��Unp= 3�q�m����I�������>.�����,�� 28W�(���Wベ5�5���]�OZ�����]����K��s��Vd�57�����((e�Z�\� �0B��r� ?��}�7\.JNc�Ng�¸ �����R���x���NO�:az2��4�-����rJY(8��o ٻ3P��� >R�ҕkz~3�升�1{�e��B��hW��DBk���S�;����)(Ֆ�L���%����!�@�u����d�o���cR���O����/D�e����S+Ij��u
+ a?�|z{� �,a��*�Io��Z]7l�6�p����wD �S�kl��W<u�T2�xdH�8�c���s^��/��۾UCrNG hI�.��n�Fk�EJ����ک;L{��ѷ�����s����!�m�c��Z@�ޒj��n���:̓?��J���:9IԿ�7��Z"�A�
+U�&�H���>9���f?����
+j�\'i�@�z'}
+����p'6��JC"�L�]�q/z���g�W{4 ϠC�����tr�g���$�L����]�;ˆ�������8��b��R�45� ����A��x86�9�7����K;�J*���a�lѥ"�0��(n�����i\T �\��iנEdzw}�z����9���j����
+N�{���UE/�p\pR���\�D]��ݬ��$�;b�j{=�C�R��MpZ�ߒ���b��R"3Χ�3 <���+g<����i �o���
+K5p�y�S$H�B.��&�ϰ2�)��k���°�&���N�x\��t�x�Ž T��L]��@PW��N��&�0��Y,�u[�J�a��߮$���4���մ���5��}c�{T����|��T":�l7H)�a��8�1�X37ր�U�x�_�Q��U�>������M���e���Q¶<Mh��J�dl���.'؟�;ș�&>0������(�Y�h ��ڢ����G��%�H�\=Kt�d�
+�L�CPw5����ҹ�޼pL���R-�Q��o� k�m�*��eǟ�,j�����P�X�����^���)��8f�p%�#��5��#�o?)Qt�慜� O�+��>�Cv����Fr�֊�"�o��4ݴ88nq���s�A�ԷUU/�l��1�`t|]4�����zZ84N�`�݄T��*![��kK�������ƍN5�Ѳ��n�Nl��e�ٽi|�gt�����\&��F���������MP|Z�7��U�0�k]&������bñ����J�7>�߆R���{�,�����w1�۫K�'h x�\��! �G?�>?�a0<��8�n^h�8�{W��嶤-�r��k8��穠��
+Y��^W��e��$e�ߏ�2]�,��ɿ9�w�d�!��VYuᨤ w(4վ��R�y���u�0�.MQs�*:��+�N�22MR:w�=L������Bi�����A�v"�i��y�b�6�ea�ABU��\�~��Ǫ���
+|����Y��g�Y9-��k9�!�LXj���]w�j�EUc�L{3{ώ2�> �Us #��Ε�E�>���l)�>�+1jn;�ܻw��a�>�5���[E�yyh0� �~�F�úA��bਜ�m¨{o�
+�����'_i�j�w��œ�.?��'��ʣ���W</�钙h�b�$��N�Ւ{��}��g�[��.-���n=$明*ԬN�L���f͈Q=�3q��V��G�y'@��?����ц��3�0}8J�Hmd��||^XSE(���:����/�½��+Ӊb��q}O͉��D-�T�?��3H�!!�0i<Xfz~WL�����&��U����E���[ <j�2B�2-�w�q^
+�9�By�ц�#Leݶ��ږ��dOq� ���h4Cv�B<[�t �:'Ě�?�5X~=����RM#�,���Cy���>��f���;�{�[.;�Ȁ] q�aC=0�x�Gi�0�ݓ�B�p{��)�MS}�� ��_Wٛ���A��s�y���eA�������M�%������)%+��7� � �}񿙬�;g�ԥ�%��� ZX�lp��V�6�2� L�j�Բ>�҇�Ԡ) :��W�4����z @�ݦ�Η���������)�� L�!���H`P(wڎ���� {U��谊����ᩫ������)t6�kU E$��;� �q̡2ȍ���\���2���� iݺdwJqX��q޵�M^��9� ǘC�x�t�����N�L ���O}u��� sۃ$F� /���I�.���D��wC�f�1��O�}�/i�[Y�``۸�������`}�K9zT��_�۞@��J(S4�bS �5�2˸di�B��[%pt ����Z iT�����?ls�UZ�ي1�lr�4��!�:�8�cf�[͛>��,�vV�I��\������ ��H�`����4PNF}�ԕ�W<|����X&�:�u�B�RЎx��%ŵx�m?�!���ɚA��U��Ͽ漰�L;���r�������~�cY�_E� �0�)ik73����-������:!+V��HZ��vg��8A�f�6zsk��- ORV�I�I��_ � ��N|m��gO;��\|�n��Z����6T�.���$��TKUZ�:�Y����%�<�1�*��R��̟
+.������h׵:p/��%1�9�*�4!]���?D�,��c�V���~��)B,.���L�=:=HO>��:��VX�����$q?�jn��C����V�;���>�k��$V��^�4W�3�<�A� vc�6����Q�h�M/���X��榭����j�O��u�
+ \����j2H�d���u�?� %lu�R�+�{�sw�g�&Ρ��+4����R��%]�B]?h?�Q*f����IJ-�v 9�Y��E��-�+S�q�v�J0�h`��϶1�7lE��5�P����B�v�����:�T��������Ն&��z�:Z1�B �p������
+ud=�;�d������*�cW�YTp�POڪ����!�<�ɱw7D����Г�e W9�~jp � B�o��,~�$�ɑ�I �{��~{u$Y�����ȧ*����OMu��P$��v�b%q�0ë^37�YB�"da�t��*�o3�
+L�������ҭ)���԰��t'G�����B�h9��~W?��ůnfS�jl�H�I��L�w�w/�4�N���_�"���^-x��ta%�v**�����*(`�?\ƫ0��)j� ���Zxfmo�U��s�*�!M���<O��70���AB'Ͻi;.o;�>������&�B�Y���c��ӻ�¢��#F>a�3��:�yd̓��\@�6����߱���s� �s�zW�fX>�e�t�˪D�䡽�v���*U�Z�N,7�YB r�"���b�sۡ-�O��A8��E8�ɳ����e�9B����Ol�Tf}D $�� �o�b�������4���$)]Z ��ξ죿½��4�9\,aǶ��#�%�s��3Jӫ,��E�+��E%�]�}�?�?�
+��*`��:�hCR�n٤=�SL�J۠�ք�v���d��<�����|˹��ڃGd15�Y�i
+C��7���IӤ�T8�e�0�ޝ Cy�v� N��w������~���1�Cc�������M�>y�b*{[q��(G�dն���v���<�Z���E|T"����n c��jG=���(�xH���a���P@O9>lJa^���\~+v�\Q�En�/�Ҷq{���RdR��-��:/��WKN�6�
+n�j�I>-]8o��i����Z��B3Cw� %�%��AI���
+�A��NA��r�$�~xFKWē+§�f�S�}^�Lf�6՗g�4� ��OzPT�qI������H��J���ɮ��Ns��"A�>���B�h�4%�}éqJ��;������Y�rr���ϫ��F��q��owk�����0�h�V�v�;}Z�\���y��N:����wj҄Q�۶m�6��m۶=mL��m۶m۶�݈��������ʬ�(�%�s{��TJs�4������w���l>Vq�
+��`��wŰ��BZ�7�e��WH3�g݂����۪��L�`b�T�ol�q�$¶^#���__�=4LfR�X�T�S���Ӳ�UF�em���vs�.:5�sCH�7DA�B4�k�\#d�h�㜡�C�㜩i�Of��y�|g>�v���"��r���qN{N�$���N=+u0g����\b8�y$ +h��j��
+�ev��w&-���84��+b��sfg��7�����4�szMVm�f��p��dZ��q|�w4��Ӷ��R��4�љ n,�o���@:�"B.�)�n��F������~�ෙLG������bO�,G[�h�3c�lJ�����,L�����_�=)�Ϥ����`<��u��p��WI�^�}��*�]]��\"v�E���h�gҝ�����?#�$����� �{�X˟s�Fҵ-�S�x���$��/�� �`�Z�o\t� ,�9u���J�H�����k�� G�%WH�/���
+�������q�.�(YNt�!�z�+�� �t7�H��� g�R�ΉQ�kr/���Kj˿BP�{���
+'��̩J���p�{L��V��T����D�U�H0����O�\���B����r�-���A4{�w��I��.҄�9�Z�E@v
+��39 W{�N�A�ea�G*�YU�6�R�uͨ�r{��4ǀ�/=dN�=W)�au�Bg��.¦��?���ē)ĵ�d������;�8Vx�O!v���JD=�G��Ӳ� ����-cz�G�����s���-r������E�t���F�$��~��2v�9�"���y%�'�J�Pަ:3�l��F�f�/�6���YBӡy^/N��jx���җ햽�'�H"��n��FҢ�ɛ,�=4�^�&���-3��g��>
+��*�Ӑ���MP�fH�Ct���� G�b���>�K �,�c�b��d����;��z�Z������6a1k�����):�1vW��oa !�`PH��r����EP��-I@$��Sh˶ ���`{"Ԧ!{��tq ��/w���`SP��(�ڴ����f�cR�
+�wa'�M05��8-�ҭ�o���#[�4g_��k�e�v�1H�(��9$�:��'��<Te1e#'N@E��LI�o�kD�~�k��)��|��U�Q%�qyʍ��F�y� H.�� �J�����ȧ�{>㭁J� .��o��K~�t'��s���Xq�`��ۆ��DM��t��V��?osN�]�w�$�������e7LgM���y�<!� ��Xqy#���;y㹍IbxW��!�X��=~Y����ElҒ�p����#|� ��g�o%�K�����V[l�� �sj��v�O��u&�0��nR��7���o��4*��B��7MMjfr�gw�C�ǵ���E��у�L���
+��3T�Fg��UU!��f]+��}cb�� CB�=��ğ�u���ZLlgETp��%y��ʙ�����;*)��gB�Py*G�
+�zc^,�)6ND�Y�g�u���^���>#�c<P�]@��il��IJ ��`��X�_���3�YX�j��y��k?|�
+�Z!�8�m���9买Ww�q�.=��z�(��ND*�:`]/��x�e\13-�":_���CJM+�|%eU~ˊ����@�{ĕ�`~[9�C ��D�� ��BE�����M�,���� ���lĖ�'H�b��>~"�k�(� *�c��u�Y�=��B����σnu�b��{`�1'��j:�Q�YT��D+�Y}�"iߍ����P�x�Q0��RT��&|���c���
+R|jx��z���}��č�:�JI���*�^e�1�Y:��Cˉk-��t.��>{�f�o�<����C���${@QE�y�)%�H��Y���K�B�?'�VL79�M��5b�`q�N; �s)�H8�5B��LcPD���[34�b��?�ph��O����H��5mZJ~Q ��i��O�LO˒���sj���eP���Ût���T�����1���u3��nj S�8��؈)ͬ�ڑXSM�!E�������7ŏUb�<M3ni�)�{�Z��~�:F��-Q6/��5�S4Y�>�����{��j���i4�,~���K����iH��(�O��=U>r+ӒUhѺ��ZbF�e4Mm�ஊ�~ZT�{����ϖ���BKP��ֲ��^}�/>�l@ y��"8\{�f (z�n�w]`�K]�]���H^�eLB�X"��O7��K,�D{�F�p�&8\z;����C����$����X��k�%�N]=Т:�J��hɚ�vg5�����,�I� �N����G�Q�~^s���(��k� �1O5����0���SW�"���a��[x�i�?��H�7�S�F���:�ȬYv :�E$P��K �1�x��*�N�2��Eg�ݗ,*ڹU���S(
+�D�u���U�g���N���8�D@�����#�x�d�"Dv�Xs�zw��$�A#[A���?�rN3�/�yU�F}��h�Eka2�\�:[J�(S�4N�67��LR0��#8X,��~
+����������D��!���.�" a��:�|��-N����A�Me�1�-c��Bδ��yW�FG���o��h� n�6dl]�@���}?�!��j��Q�_DQRk�P65إ��V���1cj'�=�ߠk��iL�S�"5Q�@?b�(�C�񅆩M�a��1s��Y�S;@ob�~����&��_uFõ<q���B +`K9��$#��^>�镄������t<&m�����Jq�q�, �|9��I�d �'��V�a��3��ʬ�� Պ���;�EC �wyz*�0��|"�)�@��h��$�{ӂ�RB����%N�U�_��!�?��'�z���!C}s�dRL��ށ*�����\3���_��gRΨsZZf�
+~z���/N��Oic���=pa�@_[��U�ׁ��Ǎ%;��Tpg`�Rw����`TxsX񲠈����� �&���C�� Ϳ!�� Jvw�1/kVL�-�'aY�r��`� �D���l&0�{�߯8��ʞ��Y�\2\�>�H�R��4�J�+lq���(D�W>Rݪ�9i��¶���s������
+-�W�͇%�P�����$$�!�CR��%�L\�KvCcn��B��﯁
+1���|�Yw�o��
+]ϑ����}���D����`���kA�Go
+7%���������K\铜�uY���Ύ�WM����&nw��D������X�|x��� ᄎ�_D�.F�����6xc#]{8��r �\%N��k7d�Vn{���7���ܛ��5�!N�an�w2����|�g5�T,jt�AE���\�\l*6@����gtT�n�߼�'�F�+��$�ot+=hK�u��d���j\��#����l��%/�߹T)b�W+t�v�-\b�X��{V� ��b
+4��\�fq�&���>�W]3<N�����K=L����g��ƒm(���=�:��UE��wi���1u�8�Wl[
+ԿA`���O5�>a����:>���|���h1�Jǧ�[�5K��D�f�i-�J��2l\��c�쬎W���ͦ"�`���ж*js�?B �(�U�� 0��d ��3 [������V�T��r�L�~`-[����,��R��o�e�=k�#'�9��E� 4:Q�^�1�~ѴzB�z΃[g/�c�C ���8j����H��/��*����Zϱ[����2���]*}�}�B3P�$��n��Mu7d'(��.ޖX��r�,��W�<���ǰ��؞>��*>�����rl�'o���7��U������8��=����,ISVdSv[���17�-�z�yY���2�� �5P����ڣ@�ք5�$ υ�����g��K}e�����gX��v�p��?nXW�(.C'�� �� U@��8�R��,��6��f�(�]�����a!b�ݼN��F=��3;| ��3C�p-����}װ�줵Ęp���J�Us�~¸6������8;��Ek* ��ɭ�kP�.�UU�o�}�5��%h �Tdm�mgk
+ac�|����0ܑ�D�2���Y-_�֧����rD��g���zo� �X_��Y_Jn�́����BY闝��ޥږ=����C��Ø� �����vȡ���Ȋ���aC<?٭mX|{�A�ނB�����rO���Ӯ�L�/�Q�)��9]s8�_�6��<+<�|���!�zO2䠤jC`�ꆴ$��nl��M镔�
+/O�d�t�ڑBQ�V�x���x4)[�0�{��v4d��]%�4��-(�_@gl�������i�R��I�Eh�b>�e�!k�t� �l3�B,J}�����\�e��j�^�#O&x��K�膺�>��*c^���%V�l �J�xm{�#��k?� �ux~u{� o�868�5��|�B��/ �?����d���m����ҙL�����C�
+o����.���� 5v����ƶv`7T���-�\���-�����Iv��Ҧ�G��'�d|����϶t�e������L~\:��������.�ۈ%�PBo�y�M�> ��;D� �mHw
+��M~�*�9bFň�5�AYK>�%_����b�p��%X*fH��,�Q�/r��_����!���)�����>ϋ�]�mSf&������N%���d�~�� ͵ �-)�������i��D�SBy�]O ��!��G�`C��x�<�%�P�� lp8����/Q_����9i���7�2Lw٦�S��@YT�d���N�*� �@�ٗ��1�I�<[(��� �y����t�����;ɑ�Hi�z>�JXx�m�:�Si����hLI��g���2δ)nMꗛ�
+"�� ��Ψ�D�"G�w� Ȅ�D��I���"q�^͈�P������[1g���0�b �m�è��)�z�wD(���9������!� ��9�Xe�)�O�3�UK������ ~3-2�r�&]��D,G1$�;�U�DD�ۦr9b�-6@X�# �m%x:?��ml�:�6�Թʏ-�鮡��r�8�I�"q)�d� F �U~ݚ-P�?��d�a1H�8U�z�����N�� �|��}^��n���v��`d�<�\RQ���Z��^J��x�(�'���|����"g��S�HMv:jࢀo>�q� "�JȘ/���Nf��Y8��AbkO�ak�Q��\G:�]3��F;k��`��V%gU���p���m��;.q7���Ռ�����f��nB\�������}|��&��?@�t�2wO���[��-wb��;�|�xC7'��m���ۖ�U7yG#[-���j]ۢ���He��<t��k ��/LgY�\pi|a�$n�^���\�J]�&Ľ$����h�j�q��_N�s��AbH�ـ>Q�1�t�W5��?!�C<�N��u��X9��e�ܿ%}�*C��G�� B[X�F���_�c8�ܥb5Y������a'��.n��QM)�A�����<��Q!�jNXD��U'!taMxH J�8�~Nr��Dc���7�L�YF�<��mg���0���eó�./�5�@�1�,�A���V:mS,����7Bk�6.���zX ��Ov�w���y�YI��Bx ��H��]2���z �F�9~7ٵ�%� ����,��T���&K����Z$���5�H`aaw�{VC3H.�g���� �2�r��B��(<���v����/� Z�L( U(ؐy�C��豒�U�a/��9L��"K����H���(1�0mo�}J��8�����M4޽m��*�U���'��?��S��b��,D �o���4LT��¥�.�����5�d��tr2����}��>,y�����sha��5����l��Q�*��0�!��?�s�zl����H�<��w.Ԝ4ɏ������)Κ�fu�S M�rM�� ʼn�5g|�t��Y�`W��jY���u7~�A������Wy��)Gp����+�Y �Ų��K�(u�oU������o=�F�q���YN�K�����}\�����yx'.�,{�f�
+��Vq��&�]� 1������R��h��%���
+U�~́�3Ł'�"%���C"oa꧗�Ys�2D颼�G@ͱc��j�D�����Z��S����-�1W|wX�4\!�Ģi(��v��/.$YC����_�f����F;�խ����O����+�>� ��X~g���8I{}�ڀ J��/�G�����D�c��됪<�;��Z����G��/�@[z��c���=NW�s#}�V�M�F��Ѿc�d����x�R� ��oO��}G\ү�L��z̕G8 �z�q�B��C�t��W.D��Y�Yb����� E�I�#ΐҌ��?K�Y�NgHc�=�ќ�;��` �v'zؖڛ���C񁃫�D�v���Ȇk�u�����z�����9��O|�u��ag����e"i�_Mg�O=�3�rX���х~ /������eY�5���>ivf(�:
+/��rR���W�s+��C��lHrt��M6j�v#(�����y�t�C�t�Q�]9՜�ҙ��a|��|d��%��@7�H�Y� 8t4Q�o�c�@��a�>]�p�ͥ��(R �;C�zL����1 ��`K��Ǚ\��cJP[�T!��ʽ M����g�t�\��{��R�i�0'��')��X7:jQ���'���r'"]��D#�!�~6���l�"��}��q7U��W����̀y���BR�~���'�C|��:, �0V�z�ڤK����"rѥ��D���-� ��ak�Kl�qUC�Ľ1Q���E ̺*�Ώ���)̀�PZ��ј����Cuզmi��[߉���gG�;��[gق-c������_�_�PEC��8'hW)���.�%m���L$]��r�&����D$+p}�d��:/��R.��p�r�ދ��#�v���6�cBbL. 1a�j�@Y[���4�X�����ư�vb�
+"�qn���F��aW�AI8�ǜ�ϝe�|%D�r�J�g&��!��A��n�?�A��8�A�
+��$�d���n΄Z �pAmu�2 ���x�m����
+O/b1�,Rt�Ľ@���ˣ��Oœ�k��R=pTZ8+���N�ꈍ�� �u���>�;�)Xq��I�d��_Z��߻r� Lv�L�\�Eroԛ?��:���T@�MR���{�:\Z�� ��><��DG���w-L7�y��0�H�:�ŷi��hG���c ��|$����d��L[�3/=�dh?]����W��y;��.I�L�޲��-A�+�����e�d��C~��n^5�_d��U��t������W-�hR{�P��g]���[���HD���v��=Vo?0��J��Ҧ��2LVJà9~%N��|1$��v}* t��i?Ğ?�?�l��8,2�����&�����]�H0D��J��n�n��V��[D�>�:i��߻�)�}l��0�p����F1�)�0Z��G�p6�?�v�ݸ­t�v`��ɬdMǶ���t�(*|���v����"�dE$ʑ����Ĭ#�x?`$|*���ҐFk��c���}��v��¦�����n: "�� �/��w�A5X���7��۪���r��*V�Z�3|�=�^2��WQ�K{��#Wz��|�q�Ku��)n�6�� խ$������l�?�t��x
+�'�K�y5 ��5����(u�Y��fD�ï�hÀ�s�
+��P��Ǝ��Te��6�ц� ^8�,�("?u�����Qt��tvV�\2jta)�t���� �6�ɕ[}Ya5c{�Qh�`�f0�Eɷ-.3��#S�1\���NQ�WUg���1��CI�=T�&��M)��} "� �1��7z��W�-[�8[A���-�.8�i�U��d�q �c����-P�O�6�.s�J�A��E�Ɲ�}C\�g�gM(�IP �
+���V�=��d�Ha�H��'��0��Pl�o�Y}���_���3:�xJU���4��CW(x��IH��� ��-]�㧑�� �k�{�a��JP�z<%���V�RMr�4s�)�5�C�v���EGt����V�W�K��xW����a��u�$\�C{;�#0��`�Z*" ��w�� �����o��P4������(���\*_�:u�{%r�z�_��8$Ժ��v� �*8o��M��-��b��s�8����|
+�{z����n<�\&���,t�=���! N���l3r�<�憦�$�<�WJ U���!�u�U�p��uv��l?��c�ĬH� �f�b���FĭY4.2SpE�J#]����BOe���*��#�-�yi�X�,��ԁ<;^}0������R�ޟ�p Y�z#s�¬Ԧ��=�vb��c��њ���U%���^
+���Yq֥;��=�p���yPN�}�9ˤ��`?�l�C-�7��3����O�ܦ^���t0?Ep:��
+X>4B���jQ/B�†�@i�_X`M����Z6��� �� "��,���20�/���K[��_/)�r-{�����ޮC7"��t�Tz���>J^����X��)���b���3��؇nu� B3y۳�M�2<M٣_,�#� ���Hcs��W���ܴ�8 �
+!e�uz��\�(O�|i+����豸��nL�*x�c=����ܩ��}ϑUƅ��n��)��.M��ij���5M�HU�K8�p*�����A�ԅ��L$��.����,�襏ی7Kt�em��q�<��Z��VG���'Q�Z�T��y'��z�{H1�H��ݚ�`���X<m�q�� �%�� ��`�VJ���_G�Z���e���Ck�J)��Rn���6»�A{2�ʼn��[�U|�������,�������9�m5!�w������*+��i��]�d\����W��:��~(�%��Zk����T��I�1k���d6%��Dl�a3����\��2U<�r�t��-�h�H���6�ɺ�>���{%�͊�䫊��9��t"�p�H��ح��S%;:{���b4�z"Gw�1��6�?�ckW>� �n5^�+X(�+���.�l�s�o3{)����턡Q�βs��@���d}ad������J�kÊ�������������n�V�P�����t��M7!
+Y4(���l��.�tC<%���H�a�����3�S��
+��b�����\�Y�������x����V���b^x{�G�{v��+M�>R���'�Wu�Ju��@�Z�V�B��t �Q��F�� �i"�Y�P6���9JO�Uel$�Xe ���?���-)O"]��݈ة�����)fm��ǨNH��:����km]]Ǭ@�?�vԾ��3�9X�ˈyb;2�TG��F�KJ���U�Mgz߄eY� 㜏����o�D�D�F7\������g"�]9.8u��}&�+/O��/��i%=��� p } U)�C�w��B�Q�3���g�>wQ~ �&fN���_��9�<�T�c�ܶP0 �J.�SE��FN"�eف�����C�O��X��/C�z`<t�O�؆�g?��@����C��u*%W�\����#<���G���m=���^hV��K<���_�1�BM깈BfM.��><��G�!�����)������^xc���|Y��?��".<��Îjw{�ݲ��p�lL��&C,:YJ��ٔ����d6� N-d�+#W��^�b{gû�?�m�r-�\HC�d�� wEK��窊�Ъ�V�����U Ě�����QB_����j�\*��֟:�M�/͔��£���TN(�O"X����0M#�fӸ��*����N�0����1H���-a#0y;�J��x���ݏz��>쒁��\���u�g���fo�(= �"~�N�R�+U�/5�Y.�����lu��3��L�O�r�\��u'Q�L�%/9���EOwN@���z� r� `"a ҿ"��+���E=a��,� �_�>.ƍ?$�\����"=�KݟN;^��#�cWl��f J4r�`M �H��mp
+��"�.���~��Q�]&iK#�q��B��A������w���X#����T�#�`H�PeN� T�;O�߬�H�Pfw���w����9)�5��ְ�{O�!z��fÐI�g"�1I9��ut��~�&���I�_�K�j�囟D��"4�6��� ���Q
+ ��q�C$�b�55�C�|�$�K
+�N���oم���Hۊ �GW��ueldo8f�8!�� ˿[cu(X �oq���v�M�.���I5�,7a��Y��zn�oy�K%�z�����l.��]s���m��9�ؼ���d͡#�������c��� m��4�)�����d-j�u kȯ��27zx[cJ�&���pK����k ��E�����M*&O�:9�y��;ق �3����3�}_�xaJQk
+LYH��z�Av6�ř�Y���p΋�<h��ܠj�~�(26Ƒ�)�M!�p{fd�/g���c�k�v^�16�<ÿV4�z��b֥bL���r�)Q8-�:̙�d��� �W\a�&z��?Eb OL-\Y�+��1�+�^N�������˚��P h��K�*+ ��#�驋���Zܡ�SA��0-ߑN� ��hS��)^J�wi��x��̏T�ɼ�q:d�@�6U��m��s:W���7Q��ɀ������%��/�Rσ�S���Q�� B{�����B߼��c�ƍ��3��>�Nr�R�}m�I�h&W�D�ҵ�&����:���;R0 ށ��h��J���$!`<jf�We���[9���f��g�Ҷ���"u��] ��; ڍ��pB�����L�]Je���m3�s����B�� gjD<�%��<I&5��V�-�5«���(��Jd��v��*��~X�޴�]K ��V���ĭ3&��Qy��9�ZR{�|�xx!�@�W��p�����n��%�B�-� s�-��_)A��s��kV<,2!���?R^(3(�� ���l�v;/� �G�B��[m
+[&�'3U�"�aW7�86��� ��I?T�p3|r���}�o�_�C�
+�7?�X����iʌ�����w��0.�J|���+�MC]v���ա�i4��<ż�mqN�5�%W�g��"�v!O�%������?L��\H� �T���Aw�pRP9EH=��񾀼4���?*.�,��[+ɛ�����`��3�ݩj[�����kց2����.�����0�ނ�4"���ĝʄa{�|c�E.IC��P��� �A �+e0�^ A�������1O�C]�|vKՐ M����p`�K��+�pj��$ⸯT�� �r&>{�$jT�j���7�1^:݈ϸ^Le̯�@&t���1Á��3^�N��%��aP��ά�{��ķP� 1 �'!�g�����}m�_��i��̒����޵�g !/���R[4��ȫ�ݎꇣ}��!!��pSa9�Y��QS��n�e�\�#�]x "\T��`ˠ�V��]�^�`C��:��%`�!
+��ʕ�:�F�Gbx��9�˻������ECn��ЊfԸ���Q����k�%s��s��[���Oﳆ'sZ��QK�W, `8|uf�I"��›/*�>��� ��Lm��7�����%Z�� ��[0�����/H��֌6��� ���,�Q/<�5���HSإ^�ߍ� ����gʬ�T-t����#�.��i9��a�aBi�#m^���ϛ�C\����U�*^��1�v� �}��D~=IT��u�!����g'>�+N��1�c'��V���0��`qv0'Ƨ �]�@��y�):���M1|?e1��ŝO��,L $_��8�P�,D�P�0�U������^Y�C-^ư޿%֝�Y"S���j����� {6�Ai��U�����9n줾��,9�*_�e�9��%iRZ�ٽ�� ��2v�iI��u_� ��ע���6c�p�$�@���t��T����F�f "4���2o�]�S\�q�d,XCb`c��I���E
+A�ޒ��d�u�1B?w���f)��T�b{��y,���2Odg���� �TJ��ݞ�"ЩZ����-8}�Du���ُ;X�qC� וm�̽V!Q�Ϸ kvAz�����e~�9��yc!6#�p�*����f�&�D�j�&� T��+m~���̯�Ii�X��w�if���`1���{��>4�_s�蚺�,yv �-����x5U�7����u>i��ny�� � 4�v�k�F�\�"�<g���{T����J�1`�`Sci����4xW�FtC��:�w� Fz�|�= ��
+8��3i��F��!�P�65b��*�RKL.I���|�������Ŕ�a�~���� ��K�@\h⹈0�zE iv�}C��(P����#�d�Ҩ$�brq7��^�S�n�F�K��R���ӦL�����B?�f�p�1Ɣ�|����?G@�`߇"��q1�N�k,��w¶��M�f�Acn������+G�sU�Iȳ���@YEB�� �]��n�fコi������ٙ��* ��j��m����b� E4���R�0�O#�"4'?J� Ь~�~��WǷw� �tpH�R��h��
+�����$�F��������`B@�#��9�wb���?�Ow�Oz&��+��,s� ʿ+i /dc���)�o�t�F�ɷ��I��@�� ��b8�'!:m�d�#���5�4D)`�������eOD��,�Y6X)���x��|Pt��A�-+�r���H+H�w�66SLސ��O�l���r����w�x&��dk�#�̢���s��y�f�b-�X
+�I&�s6x���LNa�? A��%�TI�G* jX�&�Y�DG�Qգ,��j5��i.�\��K���8�x��K~�_� ������ �e�\�Q�j(h����n1�<|YKv�>�<lB� OnDu��"��;��
+�`j�B��� c�a��|!qڱl2{�$FRP�w(�R�0�� Ï�j�jV��"��R�q�\����kw��:o�Š̿"QA�����a�|��M􃪟
+�L�י�gQ��mtT筷vDs��z����U�}Ѽ����Aݚ�[@�6�E���j�\��T7�����K��|�eI�̨<V/o��x����b�'���hK�a�3 J�R�����%������מo[5��#sD�����d楝)o��B��H��j_*� �윜r���R�����'�l�zA��R�������c�Be}m��1���r���}?S����:��-E��p�$Z�g��2�yEc��u���?�9 ������/�Z�M2���ic:?�\�7R����$>`L)K*����9NR��<6Y�ֿ�}v�f��UO4쑫ݝ�Y�Qۿ�[Z\M�c-�r%K��
+��\%c�i�!��K�Z�99<3�� �[ $q�?��8�_��57��+\Դk]z� �P��f>*�O��oG��?���630z�j''_�T�g"�I�Xª��ŠR�2/�V�4"K�mB%�R$boF�.ϋ�$p���z?5͛30P�7�w�=�,Q�]wC�e�*�5lT�`�z2��C,b+h.���dnQ�� ���~�{T�p �2��g`�m��<�;��u��3e��5�-��:K侅י��aRv�?ڻ�7���m2�I��vF�~���I���^%VG� ��`�[�7غJ��+�QҐL��� a��Yf�犾�M�I7e\L����I���=Qq*ߐP��K�$����W΀V��`��F���@�xK� ���1��}�"��c �-"ɷ&мi�,�9�ַ�o>~�u���w����1S^��$��#���v+:m��i;�n��]LPNC 5y[�؆ 0��9>R����{����)7�[mV�_pg�1Ł2E�u� �*�Y;�
+�8ױ�v����8�D��b�mrn���1�FW27�\ߩ�ߣ��eS9(j���"�q�����JD@��uFA��� D�VG���a/A��(�o��& } �>���o �Q�q 4���+&�=-�N�3�Vg��X?[࿡ry�yaZE�Y���U_!p�V���H�m.�sO(3mBb{xmm�q <��K�v[���( ~���vI���>w�|��SGV��f�Q����;`Jj>�.ݶ3���a$ڹT寉g����pd1��HsM�&bG�5���߂ĺLjX��n����J���V�o�žV�@��7�{��a�Ɉ-��:�82�G%\�J����Q)o�"�+�Q��<�@O�/�x�IHV��a�)bf�]ּoQc������Sɑ*�_��U��׉���V�#�
+���ۿ����. nэ���4(�ִ.^&��n� q�+2}�Lj��؟d�5�_P���1.�W}���H[$����Ė�2��V�@��� ³+�u���ɚ 5�S`/`����*����d����ߴ����ϬX���R5����&��ѿ6��(��i�)���y_!�����ϋ��dc:�Se�\�l�&�l�]������Ӄ�M��:y�` �Î>���� �S�5^LX����3#���/73�e��6P�ߐ.��h�����(�O?��U���AJ�E�� ��k�� ����P�&���S������^�$��[���eg�j� H�E���j���("��F��bЗ1�.�����S�ߔ��6�Y&���� 8�h82���c4��OW`�I3��N D*����􈃩����y�q��^��A�-���MA{r[��s_���!�FN~��L���J�:�"7�3:�����pTt��\.�� �q� lO��E6[��ܮ��<�]P�}cf?�7 4�������Zb���!2�M#�1@-�]]�x5�tS$�F�uNJw�Ґ��YP ���ibC�2&�y������$��ycF��k�}F���pF�kb�>p�;6�nm���w�Y] �e����61P|�S�¤:�
+f���W,\�����B<��w�6���B�S� �ˇJ\I�x�����tDc�����������R�m�Ax#HNOc�-J��kV+��ԽB�4{��\[Q�^�����o`��f$uN�߹)HX�uR(��u��!��x\l
+`�Q�CBx!�;{ � ��깾�~���Q�ƻ��8_����iD�zQ�s�����\�u����
+���dY"y������D�cRh%Ȁ?�me�{�ۥ)�e�$�7��
+��{�V���r*�T0��f����)��]����ot�JEx�zx>�b�5��%qS�� )#�~))x���gs��X�t,?tWb~$_�s3�מ���"��x쇟�@�a����k�'�}�7(e@1~�WHP�'Nๆ��p�x�'7@�Ŷ�c����"��-"l�'���G��'K`�e�Q����(ZC4>�$�E�lZ�+m�De�
+_`,�*Z�x�Ѷe��Ԝ���ڲS�q� ���Xa�Y,�N�,�.Y��L� ��i��L��@R�ZJ���8 .?VW�s���x�E/�����,e[���^e��g/��T���ٕ7�R�� �K�N�^z � �y���ݢ ;�����
+������ P iB�d���Jy罀:j��쀥��[� s��ʚo��aij*Nq j�%��"�[$6��sJ���E(�����F_��gI����z���M�;V��
+�N\y��M/�ׯ<��+�>��{�=u�� �(9�z�)�l����iWi�<i=D򸣺~h�7���� ��+�w{���(�R�bvS���, ��*9%�mp�t ����)[�A8{��s�am!���A�yw<�����u��R`�����1���ڼQ��N���g�%7��?�z�t�5BhB��a^�=�s��6퓱,k��~8c�[6Hʥ#�>/N�D�Me��k,o����� ��9t.V����A��k��n9k����d����;_>�U|�Su�ұ%��l1ԒJ���B���W�:��H����^�z���ſ���r0���7��|(����9����$]sh�v�;��W�$
+�d[�m۶mW��m۶m۶m۶msnO̼x�?"��z1H������\:)���}���� ^�.�� �0����D�$��M�b&6�l �h��ا��}ǁ�&MG�B�↯�V�� 5j�G3�A?L2F9�X�]WyiE�����Y� [����]Y����$K���<��$��׎���Y��}��; ѯ�v�r�j��=�y:z����MPf����%@���%,����-���7�&��T�����v�Rs'��@����x�"B� d5xGϸ��C�#�̔%��}]0� O*�ef���\�g��L<�x楨����l]}��0_��S}�`Ѽ�DAwb;�g��J7!P�c4ˣ���B�D�%���sP
+/q���#>/��wq�W�]Ph<&Sd>J68����J�P&��5}e'L�P���H/h�Ԣf��<V�X�Q4?��x*�MF�������qO��Z�p� M�����eN��ف�Ơ�
+3�t'>5e\�H�&
+3�{�u��]��(v@���/Vݯ��߂��:ŭ}E�v�u3c�²�cA�l(���ή�|�l�%S:Ђ�����*G��h���1��0(
+@$�����8a��7:d�_uaJ�~W���y]v{F�7�\ ���v��˽��,ۋ�ZxDڢ�+��X��M�Ɉ��}��F�N��� h�]��:�Ie:(|�4ɟ:�S!*�Ni>cX.�,���̄M2<��1�(����&��(��}��c��vj;qWҙ�Bz3�b�.�����\�H�H]�we�ub��a��R�pp���g6��~�k� k�F�&�`g��b�L>W��5]T���{�� �0&sPixK�p��sK�/��q!��.�0��Ix��3�'���{��4Tf���m<G�>�L4�˙Y�0�;~u o{puJ!#[ d�������bj�OB���B�� �p.�#� ����Ev!�(R?C�� e)RɌv9�9l���kJ`��Ҷ>�˕��O]�&�� �)E�c lz6| Q�$>p�XeC?[߶�s�/����W��z����7����~\�a>2���r�j�w…
+[���l��6������F����̚��D=��*�0�� 7W�@��|�)N(���=~?��\y���� Jݕ�D~����Y�)�Y.����K��y⭤�4Xpp����ZWo��|^��fٓ 9�r�����4�I%������ y����=��Ѝ�� HP���*Up�����MBU�b1��Oڅ�R��MuQ�Tq*��p�ee�{uo����ʂ��`'R�*[b�K��� �it[�d���u�Wxp�����|� ���+�9�����N�E�!�0۫�N �8w�3����Q> :�+� M�:�DkF��MQF*��ZE�kr^���F�T:�U��a�K��� � �#K4Q2~Z�����R0��T��-�?.Z��d��`/�u�sLE��N�5b�r� 2��=38ըE�2��!ܥ=��s���:sN7_o�*@1���|��}@Ģ1ޕǹ N`Z�Mv'�4z�$�Y��ͽ4�?[���J���Sv�o���b�R��,Ii�RFj��A�Z�y��n��ߞrţ��͐ �=���:<�P�hL &� ~�_Q˓�:�e�c3 |I��R�������Ļ'o�5����i�Ej���ֺ˾� �-��� GB�(z���<x�c��} �A�W��vs����?w� ����7��� �&��!w��� �$�������e��&��ƹy�뫙[V����n�dq娵�Z��aX�+H�l̖�;��
+�g��0�� -����.Z���έC�O�>�JG�j��d0/p[�,c�T5��@zɷ9cԙ�k���X�"H`w )�����{DP�mJ�8NA(��U
+�b�(��Cw'(������\%U]���oG6 b����/l��R��4�� �������C��
+^�y@XS忮�!���d��D��H3���X/z��\R���0�q<��U߇v6����ܻ��SY6_�µɓ�]����G��(��d1u�6�WHLc��V2��~�du�q���흦lP�'J4.�_�Q��b.�)e�0���0�.�\� i ����|�y��T��-�k�UVڣ����@I�����l�U�[��¬cE�+��z73C�VN�3K��g�-Y�~�@F��y=�(��I����Ċ�.�Q��|Fe? �z�c��"�+�f#u����Jq�6���T7�]�D�Z%�2�U��{�
+{3���j��2֕�lј& |κ�Y m�G'?ɋы�dQ1�Օ.( ��K,)�9@�˲v�� |���>�D�Tt��Cڣ����i^�=�gy�$D�NP�g1����8HyI�����V�$iZk���l���g$�Vs�<)��Jݓ���3>R߲K������ r�H� ������ͽ� ����h� ��� �1~_�K��$�'� ʰ9V[17�d�cm)yw%xwW�
+x�ʓ-��i�|��B�M/�ߧh��?����ܑ�� *��A�⩎��ȷʂ e��?�)J�{i��Oi�O�2��N"9������ �'�c�K��q �I�W-EԂ�lƁ��8�nm���H$ps���^@�n`X��9U_�*
+��W&�ٟ�m�I0=Srb�j0�&Kh�~��jQ��
+w~>gG�4�Ga����>ޅ6ӑ�L(iw�7�.e��Dm'�5AǷ���� �9��ڡAT��������v�L��*�aKP?�b��W�׏r�̈́#��J4�vsW����͞�"�� 0���1���Er��c�R�ɤ6�M'qhk(��,p�]v��~�J�Ҭ�֩��)���
+\�i��l�NJ9���TR�7��`]hA��`��!#�L�y�{�VS%��B�0��z�J
+�Q~��^���F�C_폂u-�=�Z���*�oO3�"�y�R�OQ��7yڪ���]����?{N�4jdX����|ӥ��N&��Hc����r����Z�@ ���
+�Y9&)��}F��;ZU�Î�� ��W=�\��E;�����˚&*EFҎb��L��,`k,2�/���"2��eK �X��!H��]Gf���"�v��I�|����9���:��g��욵�Ks
+����U�� � ~Œ��'��>�>�p�9���Cz�U���A{�,��o��>7���/*�s�Q��AWg�D6�]hu�m. �^��u�Crx��k�k� ��tਅb�q�H��P)!f��4�)j"R�;8e�A+ ݢ��]�#��� e"��) ��0���h,F����Շ����O�~21'�]�6���t�$hovi��O�V3���/*�
+����j�բ��)�GK\����3�PZ}�+\,�c���2�'�;H���1�&ɚ�#wZ�e{��wo�����C,�|� ��x˗T���&
+Z~uEC�=��G��� � ɨAF}�I�#�ސ���d�~`<�"�%�1�|��v��T4���P�U�B���g092� �=���?A�kr"�DQ,,��- �!\��� &n�� FʬQ�U�Z�k:�HHC�`L�6��
+<�_~��C5$&H<����)�!=��8p���ҩ~C��;�����ؿO$`��}������=�Or �9�2p%p�x�yy����'O��\���w�T?ڑ�M���9���
+���#[�ѧ-τ �� Z�)��I].H;���&�`���q� ݠ�\�'y$���ѹ�f������(Ss*:~)�V������W"r�@ߥE�^_����C�V���R�!�i����������;#_�� %�8��/���+i�,i }؇ �*��i�Fs5IK;�O��-���؆�OP3�@#�@��5n-r�i�O���~�|G 싖fJ��H>Mk������X� uѯ�� $w�PZ�ʸ�7� $[�6-��\ڃ;�����@N=#� �u|�ڢ.B��?��.w!i��c:PI#C�&�
+j�M����>!^��5XA �*��V�d���3����[���ʮ�_�p�&���%� ƌ���٪:���S�Sg�y��vp�ta�p�I��Or�`M��{�|� �1�:Ֆ��yX�z����Օ���W���#�߃��F�!-u^���APL�7c��
+�;��ZR�����Fx 7;���?���L�-u~�f��y����b�l
+��1� ������I k�G��q�p\�ƀ�>�0d��~�X��M�?� ���Ulzm�:��!Fe�(L`N�Z���o���/��k<�m�C
+O��N�?�K�[i=e���~�x��p�����[hen�>(���!A�����z�퀿o�P�8��Yo-vu�� ���� g�&��.��5#| �!��9\a��$:#�w��7C��O71D�lcM�Fg+)��N�-��_˥������]5��v0�� ��B���:3�E���VW��Jn��!@-�×�=C�[A�G(#o�ǥ�U\�#�{�XƟiڔ�ק1��dJf��v�M�f�Ģw��-Y?>��<a�F�<#C��Z$^YSZ_G[�*~����� E�G�wKY�}�+�F0`k��/ݘ�����1�*��g)i1 o(��&d�EX�����bNa|)�_#[��FZ'��u��cogu��������̏�Z�.�J��ѳ����K�W�F���aN����|����])y?�̠���D !,�=0����]��t�\����"�� Tk8��]Bqg,jj �6��}M����q��<(��m���]�f�x���oy2�*k�fj��R,�Z�1��Aw�at�i��]V��� bҢ���4n�D���۽���O� �A[�<|B;��T$G�����Onݨ����P ;�r�ljH����@�z��!s�P&�A,�1{�7�6���
+��<�'UO�i|Y TEy���!JQg7���cC��@?G?�9��.tX ��.��}*�S^��H9�p6�v�X���UA�X�g�$㿝� �YP:7a�U)��䄩���l�@; {dpu6���ؚ
+Rl� M�����d�{�[g\�4�>:��e
+�|(ױ����t�]Ӭ1����+(Q����(�8㸐7�[�6����E�U��D~zd H�4q�����?>��}i����'�{�^���5PҠ,�?H��M<?�)�L��=H�������������3!H������s>2 z����r�x�3ķ�������h�u*d�H��ѻ;��t 7yv/�5��� y������-�nT�~�EBV� yǔ�^�|����}�ͥ����|h�ĺ�-P�M�����>�e o�,jS�+����D
+�T !xH�qTy�V�Y���q}� �Q��[i��TNHm��&�S6��A�.�3���/�:i�M��8A|�ں�ͫ������&����$���e덛��aF�aZ�u�J�����Ũ��i�8�$ ���w��lQz�M��b� O�盲��罢?�'��E�}\kGy�^t
+��f.Y�Z�
+�_<� P�[T�2a�� �Q�:=�%բ���J2 r���{�@fd{�jB�I���.�g�8�U���ʑ�9�QV������E�=��wO��K9��m�1�fkڸJ)�M��vU�`?M�4�~�d���ۙh-~� �,#�{�l0�2�7���Pwj*������,`����A�}FG��)��ݫ�l��f�n쳲-u�ij)�͎-�����/�W!f)8lt�8��O��߯3��״������ 6 7��5�o�b�g���+r.K����?��SC�O���S��d4V��İ��ظl�$_ f�����'��s�����t5b;�2h� � vR��� s?On�9"b
+���ti�2�3_s:�gDjNC���r0��~Y[4����Wʮ�ՠ�0�,�$_�a����/Gd�+\/H��V��"��������+��>�4مu�]D���*Ƈ���`�C�ѣZj[0��r�ԣ��=�Y
+ϟ�N �s����y�����ju�+��~�͋��2I�]Z!�{������N=@4�H޳����Y��TV0.ˏՆj�ֈ�s�!c$�/f�2�'`EKi��4�Su���w5;����VW��R8���D��_�@�����-B���
+��0X���M��?�1 �ދ����X9@���;��^�:hm��"&�'��a�C ,�ܡ1�)�2�Le��F�Z�U#�m�o�+;�κ.�L@!Gu��N(պ�1�{ �^�!9ATI�㊡���s�'|��E��+��r�O�;{�y��� )��%��i�)�R�^���C����Тx;#��Dl�v�S�Nu���
+�ƨ�K��T��:`d�S�5�qߊ'��ض�B��AM�e�^]|*�Y�9���r�A�%�U�R�@ ��� �r,�s�Ӑ ��+��8o�tĈNj�C�;��3�G��L�9�,�
+N��P��B���½",��Nn�#��2�My����1��[���?�4A��%YO� �� aj��a��������MѢ�D�D��j�����܎w�ey'VXS���Dž����^��Q��� F]>���� ����Z�[�Q�D6/��ux�B^.���/Lr�O�^���
+��wv9�c6r�����I�>J[ i�$q���"��_��
+B�$�7i�%�v�3K9M�NA��x���Ӥ��Fdc�ߞ^�ϐX��{O�k�������^����Y�X�nE��yS����t"���6��l]���,�����5.��J�X �U⴫���3��ñ�qE(�B�lV���n%�S���i9�__�5S�,����O�D:1����`���UYq��V<�g�����qk��#�s �k%m��e��K���(۶�9�jN�x�6ʓ]�)���� ش�l�x���5UƘ>�ԛx��!*|~��fC���+��� E&u'/2*"4*���-�q>��[��$�v����a�vc�2F�!��`������q���̲Y����.oa�U*�4�+eL�<VM�.�\��z&�%�_��"��(y�@̧�t�i�Q
+4K���~�F��{l�^�0M���u"��^SG���N7u|Z� ����ܺ��c��k@*�������b�_�o`�����\�������D�g����<���y ��k/J��C�\ 3��) �p$�!]������͢{�ꔕ;o�i��R��N��m�QD��� 3���6�K�m�%��7�( G����l�X�� R��F�'%ک�M�;%��nEޟ̅3�����Q-�`'>�����<R%^����+�혺��پ�"eS�=�͇����8�@^���(�~����W\�T�E� ,!�Mo
+p�'q���2�!�A}���=��~I�J��>�?�1�\9��ZS�U�M��6�O�ǖ�cm���3��8s:y-�I���3r`ĵ;�:���.$R�y��A�1���<в\�B�H_�+��O'��Y�&�#T�C�|*����Y�_`�Zq���~*2׼�z�J�-j��_�袱f�i|AK�Ȕ�W� .�!���s@CCFF(��n�:����z�-�k$�<8�:��Hm�1e:mֿC*����o�e)�>�EY�b��?����l�'�"���pk�ҍ���j�p���S�*�t��{}1V>�1tEB24Jc� �d#d��i Ži_ bD �u�?��e�gVT��>�EIu/���W�C��z�B���ј��nd��K�kq �{Ԏ��6�8��b���S>ԑ��Qi�2S��Vii�{p��D�Ꚙ �U�!�I�.B���Dlc� ;+�]�8ʹ��V�Kaq��78��č�3��
+F��S��(�����/����%fSvE��>
+
+����M7ȼ̄�p�qۢ]^H~��u�L�W��h<vQ�'�%>�� �OFE�uh�p�[�X.('�2j�?�%twU�3l\�Lv���� ?NK���$ޢ���SZ�"�|H�kyLj�>���v�V������]?{�������`����_�Q�d��}`� o��W�����<���?��v�Kh�KFv�JMn1��8�6.��7����ϼ>��=<iw%��T�E����׃�J�7HeUo~�Ip��S*�6�RY8I�E]�z����߉1������B�5�<�ӌ���ο� ��n�2]��� � N3�����b��&F�76�c��
+�����t��8ʕ�C�xH��@K�0�C��6fh���$��?h �ڝ%��2��ЯԺ;�8�q�1�o�F��~ ���'\�Jb�P4@�G� �
+iˡ:?b��6-Γ�.�頷(�ͩc)^ӂ��L��p%�����7���$1�N��1W�h�CcMH�J�uIt<ލڛB�� �s�2��<@�\��ۚQ1�a�m�ڝL�z��z໎�C��?-�_�A�&A�?>+%��I����>[��\[c��!M���_Ey�w���WK�Um�E?��# �Q���)�\b*@��Mh��nh���r@Js19�?����ܲ��� ��CF��z�yݠ�մ�l�L={��-�k��o6�d4��L0�����u.�� ��e�
+��i�u�����2cF�z�'�f����BN WeT�1�;kh���j㧔��֘��X����_KI}�m���}�ւ�c��+� c��T��O �4�
+.q���E��/V�P�� �t|��A��l`q���2ȥ�j�w�0\@ 3#u���Ǎ�+���eS(Px#�?��E&����cM�ގ�n��� �ϰuz���/�� ������+�D�;�� �*�3�u��0$�p뫴���Ϯ�TK �NG�(!�ۄ-���������?�q�$I� ���{�a%�g�Jئb~39^��Fe.)��Q+ U��^�Y��a�Y.h�T�Ħ�`Ҳ�@y��cə�E�B!8U�����"]��#=�fq(<�,h�q�Gy�y�ʾf=
+�c.��)Cމ�<|=�S�B��tpوDt���~f�j�,�i��dڠ�������A��Sﮥ ��F��&d̖�p �`��E���w�������m�S���sJ��R�"1�RF_`(� �>��f%��(DTb�}H���z����[�GAy��.����Wp�M6Z�j�I�Y��Q�.��=��u�H�Z��TG������6�+|3�!�<��8J*���yM��n (~L�. %q��q椄
+sʾ��`�\m:zxj�D�5hC���Q8�4�C�@]�B��KΒ#������b���ؗ���U�:(�6u=�+6 ���Q}F 67�������k�hS#���>B�v�ƃL^_��],y}8�q���ov������z�Ԃn淤X0���|U���em�C�z3sh��Ar~T��M�`��H�p �:Z=Vňu�� LV�:ӫ[�Q��eB=��h,2u2j��u��P��E��I������'����B@�l%w�/Ŷ�Rf�.�eN *���L/9*��(����V���o����4����r #��ձ�n ɗ�jw&7Ɛr)���ꨒ3H�r����}N�2�;aX �]V�VwTЯ� !z�����ș�� ���$]48ӭ�XʄR:���{Or)$q�v��!A����
+�?Ñx�~�ꎝ�wG;�П�w�\R�k�6�Ԟ��j��N���F$�DƦK��&E8�-��ǒ���(^����p���ؼA�v@dBێé�@7��ڟ�SN0�^&�"P�^��j�����qLz�u����«�D+����ho6.��`�g[|�eb\d|W��zEG���ime��dXt����ҟ�-<z7�r���]VEA���U��[:�y���{��E�����ٲF���/��+NG�^�1U<Z�6�H��'�S��k���x�u|1�P�V} �낇>�.
+ �d�����Q��A�{$ �(w���E��ӑ�i�������JO!x7~o��c�]��e"���">�ڞ�&�����aή"bW����d�&�HLA�gއ���k6So��G��}0����W��Ixnbgٸu%G�%B�8�%2{���ۑ*�87>�{B>B�,����m�:|�
+��E���m��_�V��m� ����gi�Bj�G���~� �T���+ ��\C����@f� ��3CX!���E�3� ��V΅�{ei�R�4F�Z��4Cp����~P1 .��'D��H�FlبvF$�����|}
+]�9}]��q#ěe����[�ع��#�̞2 ���@k��f6o���zo���Y$��pqb�$C-������ �@g$‰$����{\�!L_���u:J>��5Vp�lj�0�k�T���n𠎠6 �P��Z�+�<D�����~V��-�g�T4����ku���+��L0���W�i[�KK�3��u�y ��e�MO�7�f>�K�<����/�zƴ#����F���)�$֋^�X�j0������;U����t�<�I��I.�x�Yq�j��&
+�'��-�b���WTv���*dA�(�嬓W�d\p]�P��&�o%���z;o�� g+5S}-���p2I5�gTR��Sv��ny*�B�b��,= �X��e���S�����<D񼮳_ԓ(U�OV��C�YٲzA��[��>��yw�?�����Q��5����u-�uΨ��������D��) �Id��]ڶ@�����%?Z�R����Qі�>ط���^�˘�GJ�*4���'#���AY��tNA�';���d��|I;G� ��{]ϵc�Ԟ0�m�Q�v[���;�d���w?���y��u�S9��Pe�����f ���B�U �.�� ֞E�v�Ja�59[h�]횋nZ�:���J�,���Z���xw�
+�[�7E4h�2����r(�Fj2�]�h�4���;2��mQ>R�΍y��etdK��ģ$�h��hB�wzEק��Ժ�� ���]>�k�mX���� 5��H�=�1!/׽�WaD�FK�!*�=��h�+ f[����=F/��̮�|*�(賌��t䣠d��ّ��?(8��J�Q�t��%������i� �mqi{ά/�� F��B�g w㚍u����?؊R��n��y�����M]n�u�)��z����5Cш�-o�z|�[�
+ʼn '&��U�� �������y+��F� q�m��S�Y>|�x�E�9T�Hlq�g 8�y�W�N�FK~$�u.�*8�0��L���4ĸ�Z"�hMc�I�O�_��k}��xּ�"e�i���[��2���`�S��l���h����ne�ృ�]�K�B���7!������ / V�B�O�{V�j������E��@��������3�0c� a�6��:�a��Vs�v� �ַ��ZepmL�i�L4�i=�0��\�jK��nȹV1���+Q|�D��y�׺�k�� �J'��l�G1\9����<��y˫5�>{�u@�:���>�i@��e������K�F3!�4V3NmC��k��^�4�tH_�U��޻A�w������JT:�p���g�V-��p��\]��3�P�����h<M��: �l=��!�ڭ}ܫ�lQhqL0����W���xtM�L
+����h�e�
+ �����n4ۄ�gV�ݥ'�`� �}�P��U5�K��t�Q��Q��A��U<�V��{X ub�
+ݕ����&J�R���@b��e�Q`h���Q�t�\�]�0w�I��+|8.pT9<D%]rL�����t7x���B��F(`� �I�_�: �:�{�Q+����N&��n�+�j�9ܘo�U+
+�K˦dmu�~"KݡZ=1���D���\V��W�^� �<�����"��W�O�a�a��.����ܳ �Y��z��0X��v�Y���6 <�1c��/�N�<��6�^h2_��U,AE9��YU_�����ˁo��߼���_�>X�&Nt�OX�c��С X"��i�`��t��r����N��P��ƪ�H�iV�h�[F���܂�1�2Q����&r��������Ω wt�t��xV;�ei�����\NU�yE���$ٕ����n"摓rP1�T��u]��m�1oD���k���
+dI�ڔ����E7�UE��R����"ژ \�` Ipx�������H��)Q����"�<�ñ��B�tB�10�ʯZ��ϻ��9��%i��^��Q�.���R�=����W�X�y J�ֆ����Nb�4��.�BV�8����!��p�Φ;����9�QJm�G��+9\��+betƎ��r{�"\��M!g�R������x7����0�p�V]�(ŠS� �)eAT�%�� sC�d�����:��d���e :�C�4�bEU����]o��tɊ�9ɰU�`V�a6W�voSTKQ��2_Ɔ��b@2F;�.aѻ[��wp���z,C� ��Ə,���>��m(��T���%P��r��x�?�ғ`f�!�^s���+1_�Y�ɚ���5�{צA�a��# �65��̈@�yKT.<T:\���Ƅ�e�W����up�D/�P��C�U%��v0���Up���#%Of ?����
+RQ��f&֬0��BMgK��U���>N`"2ȗ��=���B�!:XRْ~��gw � ��`�H�W�����u������F�PK���0�p��z��%ek����ގ\�3��@���n�,%,����ׇ�����/�K)�Q��%�� ��c�R|ڱ�j�/��$�:L_�xK��<}�Շ�c�dlH��H���w1l���+�����a@�� ՙx4����^�l"�2�B)�/][M�����!�d&�>����]�`�E]��rv��2[@���'�m��q|���5E����?����%�=��4 B���Ha�?��4� ���&+�6++�#AT���<�� ���-�w�3)��8�Ps#,F��{����=�=������)w�X�
+�~K����������Ulj�+g&,�x7�Xd��w*�5��) O͇5=y�zo&�!)P�D���a�E�?���^�ߡ6u� �f���^�T�R'IV��������^n�-5��Od0o�ʤ���}�82�� ��3�t�`���2��U\R��Āv=�~^vX� �Rx�b���4��.7O ��ƴlk��C��:�Q��\m��������<� �4��A��qŌf��,%����8b�hG��7�,$�̴���KS^)�n^$t/(�x��t��B��((�]̢�M�0��vI�#Q��uW�{ �b�D���\���\_3XB>+��+1�$��,<�7�����'�7���eDÔ5�'h�)��gL���O?�sE+��2�Fg3�.���׺�����}^���E�QW�$q�x夤O�&f�oB�KA���}1��?���Ȃ9��(���F
+ ]lX%�x��6{��:��ĉ/���u���n�y���S�(R����,g�)���;t?��H�n�@��%���
+t�m����Ϭn��$𐈞��|����vIד��b$����&����Ŏ�k�l%��ƾdO���)\r���Uxқ#�pE�0���.�!���ۑ�B�Q�*aT$a9/������HF|Sx1��@(���0�JC���9l�dIo�&�?���ޤ܂u��-�ir�m�0�مލyta��;n��7t�b�.���uڒ�n]�5����]_g�aw�P��k�ċ�cH�Ա�.<�wFJ����%h�A��ͩ��øHkHH_]���֡]ѻ�%(�^���n��Ý�1�5�JN��P��%���+�JQ��۹z�䟾 ��̬.yTe&���������o� o 4>co`dz�ȧn 8��w�_��/�5\$ �wkB��E<����#�Mn*�@j����v�H�`��B�{�
+�ï�́����C���W��y�K�ڜi�1���*e1 ��5��ϟ��������LN��8��l r�K�*�o � <G�j���G���~ ��MH��@v���1�U��� >��8� h��J!V����:W���ΆG-6 sY}GAc�|–���"����dzX/�&VU#��:FA�6ra9��weߟ�O-��l��!Lj�_ҿY��}Z|�"��CcpŒ3��[�=p�� c�a�d�y�DX
+�=�e ��"������݄��IFXA{V�"��s�`ww��$�r\b i�)��w���[��������Ź6�Tg����M\�Y����;P����ƳD��v�EUF��z�*���m(KF�^��C�gi�9�Wַv&����������1='Q~#[��h#�R��m���v.���2P�� ��
+��
+ŭ��H�$�6����
+���'^TĢG��Bgf:�λ���ʛ�� ��������f����<��M��^�|�(C��Y�}˽�I�A~��=�|�T"/ LLu�5�=c�ǍAW���@�h��P"� K� FE,�WO�$xm:�ut��%�7��X�<�d�P��2�婺�R�)��w�*)��VŽ:��-Ȑ��v�/L}p��IRMAی���n���'8�K��djD~v�h'�\X��)��HQ�=�F��o�;�jb�N��֪���(� �ձ������6�,>Q�<��U��7H`�$tv#)�9��ph��4����A�����n���,��:�ƀ�wl_{���?��"Vޯe7�ڞ��H)L����/q��*���+p�g����~M�}- }�61/6��p�ش�� 4���C�w3��%Isŗ������L)&g�q�U]��(n0�H��N�`�f�� ��_����}�����z���
+�p9�Y�U+��s*��f��c#�L�'X��!*�����K�˂��N�@��B9��q��#'e(' +��Պ ��T��ٷ؝�����y�! �d�:O�xg��#jRtnE���=�]�o`3���-��I����,hܹD�z��J^5�RtЕ�l�:Mƒ�U�$�!�����|����e���'3�'pU�N~���W�S7��(R$f��x�.]`L����0�'�����sX�a.�f~P�m��̄�#H\�C�6;J�&���ߎ��3�P�G&C��C��+؆�q� 8�_Úߕ� ���$ ��[Y���B��}� �:K,��]3�7XLt�GJ3�&=�;���jf�� G ���@yf�� �7_� �>;�m�:�/�^�;t��� `�ߣk� �������lH�0oV��6{����s��ɚQ�������^�AB\��Q���<9�: ���\�X�Y�V���cծu�_��0�zx�]���]N���ҹr�=XBU����y�(˩z/�iI��!TN�T�6��R6��M��?�
+=���?�fP�˸Sq� 9��D�t�p�����Bˠ��L�!������8z��t�BW����Y���PQ1N�djå������� ��r��޿v�38&����:aӅ���U���xZ�jP����/�]uvx#�L�{�pM}��
+�܃����A�7��s��`��WUgu�J�#��0p��7I�����FV��6�=���� D.LxŠɜ9��K@w���,�K��6fZ=Wkp�e� Ó_��J�XQzQE��؆�C;�+�` o�j-ˢ����<�a��[�2�YK���A�0�|Wj�����P��m�o�� �77����sA��yUm����&��Bv���=E���s��j�Ch�0�2@Cp�Q�O[��� %��@ �i$*�
+#3Pםy���E.�36��[apVE2e�4�|ˇfp/�Y��S�K�;Jż���"�>,�g�v �|A���
+ ��H'I��l�vƕ>��|\ ����l�_`k����z ��2�ʊ�S ��g����E·��,��>��s=`�u��a�9��X����� �5:I_�P��V���䖕�#O�'��F��N*��v�0�[>�6�-g�� -�SZ�A*j���;b����Qdđ�f�{u9��q��錄�\T�pW`򮇹.ZJ����׭����d��&�;gXd6��t ��[����sq4���,�aY������l��Ł��+).��w���z<<��e Or>'V���{� �UP}�R�:6L^����G�S��ɰ�ą`�Jqr!0
+�d���}2�o�Au;4&ndJ�]�t}���g��欄"��i�r����!�Q�I癡(��ͽ���;��ɬ�Yz�qĺ����^-�IeN�(���ev��N��uU���ڑ���ӌ'fL"��ȓ19^�qE�!']ˎV�{jn��y���N��t#$���꽨8t6hF#�g9\RP
+��\�riX4���@�G�jZ����A���P+!�^�޳�.�����T d4mF�i�1� � �A{"���:`G =2�0 }�ꘜ>��>3��&��_�����S�]�A0�=b!�}���Wwm��K��B�Y�����O����y�<�poJ3T�ѾȨ�@�>������ɡc��YQ��k���um��~Bݐ�O��(��<|Y��X�U
+�7�c��[R� ?eנ����OoFX�Ƭ6@]RP�/�& Q�B��M��c��n;+$ָWٝ����MX~sd���g�'��͔:z@�:�����cI�����5A6�'?q-^���U������=��!Oɸ-4���qn�x��o>K�і�$0#�\|w�&� g�BԢc�?ks$@�K����ѰS�[Ja���!v�F�d�9<���[�"�_�&��:M���<�&a��*�-� �hBy�8��F���~��KlM���d�z~䳶#5E�;aEd�܍*�,��r�o;Z�����V|���+22I�v�NH'�� �T-��v���hAo��D��ab2_��#���l�{�u C�j^M��B$��]��J���܌6����Pn�r8Z� ��r�t�ySK�ܾ�x�2��J!�$B�?���,7Ê�d�p}/z�k�^��f|h���İ"��3�D`��]�B�| w��;��rMʾ�{dFG��豠Q�"�F�Z6������i��Y>�A6������Б^�I "�����DޚP[W
+��(s�+N����v�>� �r{S����^}c��;φT%5��i�<C�"8L�E�eV)傿�O�~p:����*��n�������c�xR����&�[0w�.鄈/B"��%�tat�#&m���n�y���x~#Ϙқ���qt���K�B)�ơ�ҏ��\R�џޚ��������B�m�5\�OSn�����p��Y�$L���;σ��w��CxK�L����G�P9u,�dD7��T�0��W@d"������O�$��@�`���hW��aXC�b"-��)�HqS�k��y�#x 7跟1E��I�KR"�Ec�����bW��8���d-�m
+�Ŵ��}:�[��)���w��G{��h�?ٹƘ M�G��:�L�r.�ʆ�x�.��,7�X�N*�ƶz�!o����eڽ�����T���b>���IU)m�mxl�y�3��ɱv1���޲� fCdǽ��v+�T#�����q��K6X�p~�)�e�&��e�ʕ����Nq]b@1k1z��U(̠(y�B�ϟ.]s��G+9� �&���ʏ��m����_�m�I&�)F/"Lk+O~J@���|��g&���Ebr+����c�`�#��^��|}�BL��\��@2��m�Dž3M������P{��k[RN�`�X�7\%+d��G����C'�Z�Y��m2������<|����[���p�E���M�<����`*�[��db״C�.�g�R�'>����B-������7P��s���Eu�_=&r�����F"��M�k�i��\g<U{3�*����rJ(L8�NHĄ����U�F�ik�3pbs�t�[�������^4s�2N�D�8�KG�i>���+CB���N���LJڱ�k�U�A"�f��"?�[�y��� �U���윶og���x��%�W��rC�X��-ϼQ{�Lw}8y_��&�-Y��1.��&4.���A"w�a~sjb��U�CI�_Zi� �~ ��+lo P>m e}���g�����~~�u���Q��e�b��G�ȿ�$G
+�%]��*<S�Gd<:��~��)�N �>�]�{蹽x᫓�h�[&�U�%��6��k�ޫ; ��tQE��n��C+
+�;�,��Gs�1���N�e��)�eR܃S�v����ʪ��Ƕ�K1oF��(�9�ǐ]����kn�i������>Eir)�S��K�m��&�'B�U���S�
+Ġ�2�<&\��eUC�(��� ���jS[���� �r ���Te- \ڮ��2��e�9-�^���^J�@��!��k���L__U�›�‹��D3��R�L=���̉2���?��t�NI!yk����)^ח[ɇ�o�n�N�v��a�I(=�����ms�ڝ�#ǹ�l�|�ޕK�U�fo..���� K ���`p��v��!�l���s]S#�;��yud�?i��$ �r���W���9��PQQ0囷�/�E�x�[ �_�W��"^����p�ڢ�j �J�Ǣ�G#��@_��ȭ
+�Q�n>�l�}?���Ot��a���y���ae���� JK=��'<�f� �e�i��} o�(L�u��WT�$<�k���S[���ɗ�������:��5�?�'�����"*��V�ab��_�a��}jn7�7�dz�DLV���{�~|���L�K_ �.|~.����޴y�vq����O D]\O�ߟYPc�ӻ*&�/'���W%�]��ol%��% 1�&�v$o�+)kcd����F���Bj�ľ��i�$�j���o� �Ȫ���L�#:�o�+�Q�k)$���GUp U[�rb�\�Œ�:me�.���ts��O`/��:د5BM�O�Ԫ"hD���tΛ�{�;ՋOF�Uw��,Ә��K�`f�"�L��-2'��ȟO7<�kJ%�Z��j���0���pqA5t�d D� Ӝ�� � ��lЭ�g�V� I�(��LX��pR �B6H6�ٻ�%@�I��R�b�z���)5�G�s���,y��7[Q8J�x�/���0I��w�Y�/��dE),�g�"�Ӽ�-����i�~ޢ�kWz}�`!f'h'�.�����B�r'T2�����A��]�g<�M|o@e6�ins�*.,z��J>�I �~~�����}��{�f����FVؙYS�.n�1�c��%��*�S��p�­<Zv� � �Iƌ�˾�tLM�nN�rOO��R�~�H����=�k$�~ߚ߄Qh6�T���Ԡ.�ed��� ��c�-g���!m�����s"�x��%��(Q-2{R����Kz�D���`~w-�Z�ҨX��w�C���r����_�l�_���o��QA����w���_'�n���P�B]�� �����˥߷�y���LX k��<�8���?|=R65�C�y�1��-�L���x:uM�.���T�|����)��A蝒�"ϮԈ'"I��Ei�� ����zw�YUFK� �<�/U�=g��^:�F+�ޚ�\)��-�H=L�<b1XO ����L���0@��U���4Rj�x0e���4܏��]�l�+�"U�n
+A �)��H�ғv���ݍ�]��w9�x'g)7K
+�9�ۧ�� x�S���Ո��S%��h�S9�wӏ����ӿu�������sJ��oJOGG�C�Љ�������Ϳ2Lf ���(� Sߔ`Z�H*�Rq��د����ug0 1=��Z�ӫh(�gA(5s�'[;�wB�� 3�W.����&����]�����ɔJ��T8j�K��U�n���I�6�Ͻ�-�h��=y���^Hb��N�A���`�v$�hp�@���V��2��5VG
+W ��n��
+����bٟ���@�`xR�cݍ��h��C��r0�D�Ů��Of�/|�-)��)Y��[2�5�)w����%@�dYT�K�*�E� �.��/v�i�L�۰�ml+�4d�n��v�� aᠤ���pC.��<�܈�:C�@U��0��ջL�E�4�еe-��Q�/�NbK~'�\�Z�f!�#�,ڝ3��uKP�K�)�dڅ�\GA�K�u�g�^���Nc>b3k��j���M��g��!��b{��dNQRcԮ���ku� z�V��w}�<���6!�� 9���|��b�k�u/[�j���t� ?jɏl�H{�e+�gFi�:|!:�t*ʸ���@ثM���P�k��;&����P����h����9=���Re`���Liy~z �ʞP&���V*0�! q��㐉v J�
+��[L�U0�-R�l*���\���i;n�^�w�~������w`�Qo��j��v��t��;��k�� p�?v�'��;�n9��#�
+��|�K%�
+H���/r��߬o�p��I�N8=��[m��"_������-g��q���y����4>� OD'G�u�Ԡ|�x�D+�d�e��N��N��hIr�FQ�a\�k��C���)If2��r)so�m���s;ȉ/�-�����w,��W"vd ��Qmx�j�W��w$��ﴝ �9�bLK�^Uo�o�Z�L,�B���b:������
+�N���@vk��(� �D�Y���Kq,of�����[�y�~ ;�q�
+\R��y��x��Ĩ�J������~��[x�F=}:#��
+E�z��ٗ_���_�1a*��)MFo]P7�G���O��fYeS��$���"K2n�~�KT�\�rM��J�hv� �z�֍#Ж>��Һ �Jx�ܕh
+endstream
+endobj
+831 0 obj
+<< /D (subsection.4.1) /S /GoTo >>
+endobj
+832 0 obj
+<feff0034002e0031002000540077006f002d004c006500760065006c0020005300650061007200630068002000770069007400680020004800790062007200690064002000440069007300740061006e00630065>
+endobj
+833 0 obj
+<< /D (subsection.4.2) /S /GoTo >>
+endobj
+834 0 obj
+<feff0034002e0032002000440079006e0061006d006900630020004200610074006300680069006e006700200074006f002000460075006c006c00790020005500740069006c0069007a00650020004700500055>
+endobj
+835 0 obj
+<< /D (section.5) /S /GoTo >>
+endobj
+836 0 obj
+<feff0035002000530074006f0072006100670065002d006f007000740069006d0069007a006500640020004700720061007000680020005300740072007500630074007500720065>
+endobj
+837 0 obj
+<< /D (subsection.6.1) /S /GoTo >>
+endobj
+838 0 obj
+<< /A 859 0 R /Next 841 0 R /Parent 616 0 R /Prev 731 0 R /Title 860 0 R >>
+endobj
+839 0 obj
+<feff0036002e0031002000530065007400750070>
+endobj
+840 0 obj
+<< /D (subsection.6.4) /S /GoTo >>
+endobj
+841 0 obj
+<< /A 861 0 R /Next 732 0 R /Parent 616 0 R /Prev 838 0 R /Title 862 0 R >>
+endobj
+842 0 obj
+<feff0036002e0034002000410062006c006100740069006f006e002000530074007500640079>
+endobj
+843 0 obj
+<< /Filter /FlateDecode /Length1 6916 /Length 4896 >>
+stream
+x�9kTי��hFBo ��4�G$ ��a�����xY�(�`�&qL����i��q�v���c9Ng{
+l�qq�:=����&ݴ����?=���G�=� ��H�����;����q����}��w���� R�D���hxIE�G����l �"����p�]����F��p]5B�K��0�I��B ť�#��Gb���ґ��q��<#>��p��pt �4���q!�Rb���u"j��H�4&�a|,=� ��g�{u՟�t�4�;��(��ss�w~u�C��%`$����/��!��;���P��,���6-�Fn���.T�\���u��yw[-�7�
+@<����Xp@@7@�B��G38��&�1�C;a$�� �A%\�������:����k�� ���@�R*V)z� ����:��WI�c��`:x3PB=�˸�*�C����ul����̿/�3���!��>(d>|���{�޷3?{��y�Vs�V��y�u槷f�-ena[r��΍�̏o���Wv0?Z 1?\��\_b~�e���0hE�®�Qv�h���H!��+���柗��7�ۘ�/G�Zg���`��2-�xq����'��<�|W ��E�Y_v����d�q��yc���������,�`^_�f^�|����i��g�.f2�.V2߸�U��y�9���ç�'I�E2����0?��>�?>�wÎc�c��p����c���)����L}y�)r
+O�uO��O��x��$j�$Ϝ���N�'�1�e�w����#CQ^��у��Q2
+���c���������C������A3�A���>>2��
+ ���|��zyO/~8��w�wy��� �+����|{��o�o�[i?�3���AZ�� �<� |�|�@ؘ@�����ɶ(�bf���BD�Ө�\���EK��gk����v ��������_꼚� ol��O>�ʬ
+�����/f�u����H�u��@�sϸ����4�=�qxğo���BPE(�m�m��Ğ��P%bL1$㝱 ���0�a�L�O*"<l�#�
+*J.�}UL�V�G �=h�������{� 5�T��Q"B럭��� u���G���e�붞���H�h:����լ-�u������F�xV2zj�]���8%�c=�־����U�������
+mCͨ�ƣ��z�&h��i��hM�ȋ�h��Plp}�p � ���>4����)�4zͣwP���Q4����Dt�{�E���
+�Qtξ���<p�'θ��sh?��4����w��BI����^�[�ֽ�VR�
+k>+���|��(:@����-뿣�뿖_�.^�=R���C�`��hokmٹc{s���!���{�yܵ5�[�*+�]e��{^�5��0f�A�Ө�
+9M�H#�����BN� ��
+D� !|�W`��PF`�~a`= �ɡ����$=��X�V��;��X�f=�.������:YaUjo�ڲ ���=X�9R�
+��� ��Ȝ�����TJ/�T�тRM��<nt��b�A����Ј�
+��ZZC�����N����X���X�:�3�����E=�뵩����!� C�9�77wJ0؄|�^ȟ�O3pP�s�>�Ɓb��� �@Y�;�)��_���Q�q
+m��D���M3 8��F�h���u9��A}�3��΢�����u
+D�ȹ��I�E��g�{/��q���o2bf��;xV�Y���@����GD���a�`K�<�������-9@>� ���ܨ`��b� b� ���.1�O0y���%8|�B�7':FTP�k -!��' �l�NT�:E=�d/8%�7�����!6��%x:�|�\h�S���?�頀�^������e r�� �d��- �~xqu��� t =ZW͆p:��Y�b�q!��� �zҳ ���7TJ�-��:�@ �s�b����ŤE��Y�`�}
+>0( �����w= �qc�
+
+ѝ �
+��Y`+�)�D/�Y��!n��� �<-!�9��%�ۥ���x�t���b��M^�%��#$�m�SE�Jx@�7ц�`7n��9l��.\|@�����9��3�Rة~Ȓ�?̱z�?^\��[�x�F}��*�s\����GJ��X��8�q������n�ó� <��Z�#��v��ps��\�^h�E�#Q �*EVDđ�QH��K�f$�L"Hx�"F-&4���M�!GM�y$Z'�^�����}�Xgd��S�Y(�?,`� W�� Z-(��:A�Չt�Hw��H�suNƐ�}n�V�/�
+WˤD�b#��ɴ����-P߄:�T�T�?U��FV�bS��d �YH �w*��H�W|/ʀ&�g� ��!n� �]و�3��\T-u$
+"o� ��^�h;j�dȉ����+)���}]!���$WF����F� #�G��M7T���;>���U��p�W���VQ16d�j�r���,�DYn���,�%�Js8���h���Z�Y�� A2F�%$���0�~�O����J��$�VI�ҒL��� ��\w+'�I)�y��,ߐ�� �M1�:�֙��-��>�=��S!;q�q2�z������2Jv#%)�Г��!�@&���D�<Ѩɩ����q��hj���T&$�4������#�9q���,s�2'~�_�cW޹<"A���1E>I�)�ܷ���H�Xu���ʹ��_�F�U���ұ���'6��%E�={z6 ��DVVZ+��Iq�ƓǬ&/-�j�V�%�7�"/�7OvV�LE;'_�6�mZZF`J�PY�w� >�����=�~%d�I�����3�am8h�g�o�x�hsnべo��rq��2AkT��:�ʨ�k�ڎ/-��T}�੐;Ҕ�K�LgߚpVv��B=`��)�r@?�̝�_��'O֟�����w��W��j<[���vm%^.��� ��lD���8)ÚA�2pjr~2�L�.hvk�
+NU�+��8��!����ۦ��[t�<ʊ�,쐺��NW�NM Up#��w��!j����f�����E���~� R#� ��Z������C�[HRr�g ��r%��%�L����փ/�}>���:Ѹ��k)�����]���~����|!�ӳ��q���?V������?�ܳO?��ێ�.�o�h� �����S���t��r�w��A��8T,ˈ�5y�YO�;�l x�������Ԕ�-�����Ȇ&=�p��<b�t.ѐ�%� �̜�$��3���i3�=#>e��+4x�zJM,*p�����&�u1��ו��%]�u��%�rܤ��_�O�D�L�Z�b�2��W�O�4XP�_�C3:��*��g�4n����)��_��B?�ꟿ�̧�����{j2{�{��>8�}�92= �� ax�J������-��V�!'%�����Kt(]��6v����a���͢b��ò�\%z8�@�tN��tkl�%��t�V��{��JIS j9f�~�7�e fr�J�^e0k�?�5 T�6QMQ�D�ڤ��r^Q���&��ۄ��2ZI��/ט@��� x�ux�s�1U�TL(N�^H%���#�8�:$�U�He��d���eg2]خ�\�/By�P)F4v�ތ�dpH��VX\9��0�%�xڥ7CZ�%&�3T�6�/A�� Z !�?Q��TwV��%jZ)' �<��c���T�=��D��D�V�N�)hM�Nc���9r��#EE���r6�֘4j�Fm�p����zk}F��\+��D���z��qr�����n<� �wᩖS-Dy3�6cY���8_�O�/������������;r<�6�:�vn5l5$�����,K5�'/��T̸�� �mb�7Z8��*�w=]�$vt��6��M��iV��� 1<^>�����UZ8�4��������&kQ׉�Z���J���P�-�rwU���b�dWZa�h�l�|b�C�����8�qv�"y �V�R�[�-y��ފ�?l��$j�@MAK�%ۖ-S'T�Ƙm1u�{k�W( ��-
+��A������q�f�ጣDC����Y��\� �Ŀ�*P��dGnz�̖��+�ڔ<r����J�jI���o��t�h=N{�?�� �I 8)�`%cg�?I4^�[<��{�%hUp5I��.�MJ�6k.Lkok��8���� �*2q�`+����%Y#W�I�\-�;�F2w���)��Ԣ1O�Wj�WCR5���W��WM�a�4|$ �.��h�L�W�W�̈́�q+�ͮe{��Yz-���b�����gO��6n�8<�'��A;#>��� ��ݕV�2���"O�?v%R=�Q��d)��5E���.�����n>;�̤���J4��`��k���}/>R����I�MZy��5O����Mj6�����Ҥ�kCQ�7���7n2 vm5��*؊D<Ͱ�5s\�8 ����� ^��N��)�1-1%UIR��ac"��$���f�suRR��� j����z�l�MрN4lm�7~+�y��C�|t�z�CQO��
+<X0Q@�x�>a�N*���5�PqX1gy�B$XR-�r6�|���3��_Z�����YbY�k�v�<vůU�?ܸU�2��a�O�x��q�A�t�#�6nU���E�O.i;zy�}gm�1AL���������d�}��i-��x�T�'�8�|$�2�H3���]W.�T�t}Z�Ψ����3�C��f���-�M6�7G�^j=�#���G\�Ͷ0������<Ȅ�6�xm���p��pA���a��^�w�
+endstream
+endobj
+844 0 obj
+<< /Filter /FlateDecode /Length1 13628 /Length 7205 >>
+stream
+x�y|�U�������i��{R�t�K�QZZh�FK)��є��,E�v
+e_���T�AG�eܪ�k@ ���:*���2���#Pqۼs'-�,o��y�r~�{�=���=���Kb]��9��"d�,jn����lY��JzD�j���y�H�;� ��p�\ғ��[�4�&~F浢�t��Lh]�d9�I s���등�YԼ��u�͋���dr{�=�����reXg�I��}0��p�?�b���U99��j<0�X�Djd�V�w��n��a�]��hA��ˠ���!�nDž�ߤ���^�V�jl�X�5��X��,f½((D�FY�rE!���!,b����pO�%����F}�hK��+b�c[�"� �%�B �#�y��\d҆��GZ���G��_��T�Z!��,h@�R�_;�T@��e('PDu��e �(w�E9�����s� �Z�ۊ��ؿ�n�VP ?y�b-^�GO\*�O\�{�w�sT�-i��&�%�!��<�����/�S���/ &|A8��� �D���� 4��F">��:�>!|L��\>$폄��#�K8J���� o�"�I�8B8Lx��:��5���U�+�� �/^$�@8H8@}>Ox��� �����g{Ovv<�^OL6FP"������I���㞘,ty��(�{��0᷄����v���#�����p5�J�5�n�]�;���-�� �n%l&�B]o�� 7� �"l�� 7n$��p�zOt.��:Baa-a a5aa%aa9aa)�������A���������������p a>��0�0�0�0��B�Eh&4ff����=�#qdn�Մ�.B��0�PG�%L"L$�&� � U�J�8B��PF(%����b��hB��0�P��(���F�#��B6!��)Cd�� ��A� B:!��JNH!$���'�;K �<�|��Bē�J����B4!�I� ���t��C0�f��`$ ����#h�O AMFAIPD�@`��|�B?�g��y�O� ?ȷe��3bߑ��[�7�� g g%�N�"��p�p��%��Ϟ0��˾ �����a"|� �G�8�'���<ae�O �>�����#OX�C� P��ޣ�ޥΎ�@x�:�=�{���M��a���u��5��h�^���� +���/э^�Q�@�$ <Ox������,u����R��P�{OvӍv<�^��D�Ix��~�����8�1O(���QO�X�#��=�5���:�'t�AO�d��P'�~r�A.��e��Gu�!�{I��<�~M �&�� ��>��w�n�!�F����f�-��:l��<7n&t{B�X�+OH#b�'db�'d:�&O�xč����_R� �y=�\�܉�g��3���c-/���r��*��EBى�ʓ(O���<��ʣ(��<��[��PDy�~�(�Q��Z-��lE�5��(w�܉r���QnC�U�jٌr �&��(c����y�
+,�d+X�:O0�l�'�o�%��3_��_� m�k � ����l���OI�#� �r� ��e2 A3�D0 &��z���%hj���Z圊�+J�i��P��r
+��ʧ(��|��ʇ(Ĵ|��>��(ϡ�Gه�,�}��ߠxYEz���7�
+
+�r�2�RB'��PBqKp� c�iʡ�B0�^Q�����_�8�"�@cYE���O���j � 5� �j�xB��0�PA('���i�V��G�%�� Q�HBM3���ۏ�3���(?�����Q�C9��-f���Q�D�3�('P���9�q����(o������P^Ey�e�C(/�xQ����Aye7�.�{y��~���j�|�?
+�V�<
+�\��lB a���D�I�A�N�F�J�Bh$� W�"� !�B�NH#��RɄ$B"�N�I �J�� � �0I>�����P�E9���wP~��6�[(ob����(�-�3,7� ���]��z�\�*׸���q����^#��D#V��Y����ʕ�U=+]��!+݊�e��=�\�e,`ie����D�N1���sv��;:��A�P���C���w�ԙ_X��yk���t2#7�w�+�Tv��t��B�v�� �����C@�] ��{DGXT��#���!����������ֶ�m{ہ6庶�m�N, �6�����E��1�/���rP�yD]�>a�8# 8}l� ���y�֞y���]szf�Z2f��3�\33��f�LwM˘��3�՘�v]��We4�\= ���:��:פ����h�ɨvM�v�ϨtU�T�j+ٸ�
+W��g�'��=�+�l�B��+���=+�ǜ��E3cԺ��Q�/]"-��#�G�T���$����B��i~�|̬��`�l�n�i'g�}F�N#�x �@qR����@��u�� �Ȫ0,�8�A,r� � �fs2�+������I3�����RqF�� NV�����O�@dVƀ��s���Z*�����c�BCj�W�\-ij�Jl�d��Wg�I�Aה��^�ni�eBi�R]7��7m�ؒj)���w�-i���x���>^tiL���s��%��S�2c1Z�t�[�+�;��K�.����=��e�ŝ3;�tF3� \�.����]3��ً�������2_մ�������∙3䟻���\���up�z�ix^����-��o�7����� �o�,�Ű�K��7�7(�A<*���x�w
+���K,[P W$^���|}W�� x�T��$�5 o`ogY��P�-M�<� �yY��Y�����/�@;t@',��V�X ��� ����b�o��� n��p+�����n�5l�{�^��}� ��븾 ��%���ax �@>�o�x��1�O�Sh# �O�e܏ևя{=O�N�'A/x`�Ɯ�>�y� �g� {1��`?<�cbf_�m�2��cO� ���
+�
+���pe���� o����^xo���\kG�]xއ?�G�)|��s\u������}>�{G�/�z�aO��|�}��rG��cp�i�;&��a�g�.9C[�<��݃y{H�3��N�y�(�<7Ob̟������=�l<�����H�(�ml����}x,x<)�oc�)g���"��'����rq1 <�<~��`t>�$�_������~ ���K�ǣ|#ȳ���<��c[�o�c�c:؆�}��)<Nc�9��3�|9T��_��3�|= _�y�-�C�{��E� ^/�^i�~��'8���/�.-�~�� &0.�.Zy S0%SᙦaZ�c���?�����՘���b��uZ�� �B� g,�E��★ųa�b]�P�kl,�����䖑Cm-�1*�� �Ma�l^SYs`9��l$+@K:�٨�ºL�%P �`!�W��B�T����7��
+;|?�J��/�a �0F1|��k�v(g�e��{6���r����4����C��g�q�X���9c���Sݮ���u��&�L�_U9�����d��x���Q�#�F82�Ӓ� �a����h���J�i嶊&���$)m���\�5���C�dES��>���kƪ�<��9�
+O'y:�<��ZE�i�r�U:Rf�zٔ:7�7���R�\��ˊDY1��-���eV�5Y˥�����Me�i�W�+���ѥ�A�N�E=��d[{/K�䂐\>�W���V��ͳ��:wyYt||�l�R�/IU*�徬�%3�l�M;ؽ�k�YM��m����%�u�����%s��b+�RV���Α�le�R� V=y�LR�M6k�w������Q_bi�[Tv�w�+���$���2��p�8��x>���N����U�&�
+��=�t�6JB�98X��5]�5C͛l�r[y����5B�eMO���o���c�U�f��r6�鶕� 1�����eXp6��Yޛ�@��&��|�:�䰵K!��6�{��z�܄��RH�M-�V����)����}���{!�w�7��+r���C
++Ť$�w�gϕ,Mѳq}ε���%g#�����ȳd3I)��v��ʭpnWx:�%�]cu �b#��x��a�IR��3ZRdu�htû�=x�~P�����MK+��qq˯2�h�C� �I��P^������R��s�.�e��"������c�A��Y�琞&`ي�I�y�&����V�m��цk�Y���᱖�[]o�_S�l�WI�e��S��� �A�亥�T9�<��>Nև��+�����[u}7����!XqarT�U�7���f����V�l�����^_׬�^������un�n[��n[��s)��5�+�����U7�����S�kc�z�lC��^�,m���������7��{�N�*p+7r+WxO�Q����{�]r�B6�z���l#'�1h�
+d3 � hS��)��;,�S��p�u6O�����F�� S�o&1����aA �lsJ$���ۋ����*nW�J$�08^<���lxN�sC4k��a�_�[�>_�;�Ht_c<n�i(Sܒ6�J�x�ǥ �㤮�f>p�V�;�����`��R%i��������刍Z07�@�}*RW�Ԙ�o��Gd��$���´S��D~#Gcw�-�/lt�t��ZԻ��*� \>#u��ņU-MV̀Z�q��Y��yC�<�sd�E�+�OK�� :I��⛗��!�Ս>yY[�w�{�$=�(�P�`t������q����M�&ۖ���-�J�Ւ�^Ռ�?�ףŖ?���ع��q��j>���ho�����'��+=��|aB�^\���}�A�������j������o@������"�� ~ �%�I�jj�~��jX���J�X+��߉�a��:����C.^�O����0d<����J��@ :��T�~#ey�#T�a�5�Y�,�1�R�ת�o���h[@ L���``��W�Q��ee�t��
+`eo`���� V���b��F��\U��(4@q������#A�#��I�{}��W����}�Y�o�%$PP�U*۰ aDRb^NN�aDn�mX� �r�F�s��=�2F�:?�y�Xޟ ��/��R�T{�%X�-q{��X]c�K�R*4*Q�Q'��\��{S���C�� �_T��Fx�jEم������
+�^Pj5�%Dž&dŌ�6 �������^�ܿ5��Ӆۣb�/{?�;�M����4x��j�r�F%y�۝Fm�5؊Ɉ�0ل�gY
+$�N�1���DU��wr��^����"����ǩj��⨾��T�cj_*s8�
+
+S_vfV����3��<���G�s�r�1����|E'�3j��Ƨ�� 7iuJ�.P;���k��l��`���< �>)Mњ���L��@���1�ẁ-��$���w^!b�b ��#���'l3�
+/8�`�˱�{Y�.�*�6*v;C�\ ���>\��v�'l3�1�� n�R!�]�\�BC\vRbN\@V2�ʨ_��!m�/��&�}i�+/F�qѣ��Zt&�J��F�C>f�Ye�����a�]8�Z_�r��IP7Ӽw�⃒�‹��F����g��eӜ��z�b���^6��4\EK��yq0�Y��pq����7� (��O���\�i|1�㔌��ehHn�1�r�: P�`�u#3n����]յ�N�s�g['��9S�4�M
+� tXk�������N�j�\���N(m.��<p���.�1����z�� S��c �9�s^6�r�S<���r����S��}H�\&�#��J=��
+����ŋi�iBt�K
+����qs�¤&�*������t���p:���8�8>�{4
+f1P�j����S�ܟ�z���a��*����S�fL�hg��v`�����[��Ue�����":BS��'�jqOJB�����cKfWe�QPh ��,)Y�kyᘥ�]Ӿ}n�9q���q�H���H+�>vXpx�:(>2�f �7�|vͲ7V�t�a�fE��zfe��<ۤ����C)e�� pC�
+M�б�UO;#MU� |�����(���(����c�?̃��i%��S);�� �ʹ�3c<��U8��P4LG�N\�3�U*�Q�2'�ʯ�PX���Z�y�\=ٰ�� އ��0�q&���.=�A���g���j�zg��� U�h��A���2|���_�����ϐo&���ǿ�B�p��Q񝀘�{VL@pBAb����E�X���u��O]S3lh������;���z�4���h^w3��wJ��X���6���?��U��FQN�q�M>r����8�򎐟F3�/6�W-�<���ʧ�%'�BQ�һj��$��gV-���f��7�E�e5�)hȋb�:�o_�ֻ����Ǯ�^W�69#eR�8dz��6ʷ�����h�
+M��2�,:�N4�:~`�u^V��9S�'C�U��B�3�gw=s�L��S�K&ȏɿ�Z���J؇;P� ��
+�� �/�������Ag��+�X���Sk�愢���� �Rۖ=6�(������8�p�i�E/���h�Ϙ͆���{q��_�P��U����8 ^��Y��e�<N5e=�ta����C�f:��B�� >���>h�+����M� >gp)���1���0�x�p�>��S}m��!� Cw�>�vŋ<!�/e�X#�j�^�\����8i�d��cdlr��U�I�T�MXO���^U�֪ա ��T9,����|�:�'��$�3�����$�2�*A� x&�v��a�?��e"o�B����7ŀ���Cv�3��y��!�xX�b�O���>yښ�xy�x���@h���ML�� �wy��
+C�M�|$u��g6p��g�-4�=L� ��h�P�;!J�;���(KU�.�JW����/�G �tD��'��?�pE����8�x��92811�%�����S�nX���IΌ�� �ʁ#�����~G<�
+N�Z�8�6E�Y�*2P̵�C5b@dx��e�h�쑘5A(���� ��Wyji����:槗�-�����?��
+endstream
+endobj
+845 0 obj
+<< /Filter /FlateDecode /Length1 22008 /Length 11130 >>
+stream
+x�| p\ՙ湷�j��v�[�֣[��Z���zڒߎ�_X`c[ca�;�E��@�&����&�&�*��M"pNe� 5xf���B��s��~�9��(dCՌ฿>��s�����sn�4�*Rg�G����)��|���>{��7E�w�Q|�Ξ��z���J�?�f�Y�=�R�Ե3�y��B����������n5�s����1w�۞��������y|��8|���~������or�c<�W��g��-�k盶�Z��j7����T9�T��Ƭ�պ���;��VUy���㗧���[�/]X���{9w�k>�5����rR��}�҅�V��ܾ�f|�.������QIU���G'J�
+�4�I=��~�Q��6��4�Iի�U]��Y���.�����"�(������J���GT
+��S�ʉL.��XT�yd(�t�(@'(�WU�L��jP[�ZPU����9�G ����ꨪQkp'�������N~/Sq<O��c~��pMD��5x�.[���p���h��{9�"�f�W����`�Y�AB%Hapc:I���s�A�,oY1@�;�����AP��z���A�iP���V�Ӑm��<�G���gԬ���GiV�P �ى+X��������(^�D}Z���7݌��y5�x��*��(O�F�1[�.�����nY��Z��?��&j��z]��Z"��c�i|�[P��D6���7���LE�F�n>z6�!r���r�� 3g��#���������scS� ���D?9����S��:�|��K��۲5rΓع�����L�ύML����� ;���0�NM�� ���
+kh����f��^v�t1u�,�ܽ߉��p�l�,����h�wV��xp܂�\���Ľ�p�aV8Q'
+��&0T~����'AX���yf�ƵE��Ps��߉�% �K�"�e(}�����^���X��Z��3�`��wgy`ˡ��~�e�I�tZ��?�s�nQ=(I�JǾo������'�߫>7�m����h�A%����y��ڗ�<\3�{#��#��XkU>��7��/, �u1�����}*bm�����|O�*��T�}�P8Y��E*�:�ψ����j����M���k�*�>�����'G���H��D�Y*�Z?�d�N��ʟ��@e%j�
+�M��9�%/ڀO<��s�� .�?�/������}ń�P�W��ʬi�S�������N�� ���`_���[\V����lC�⚜5/���w�;B�V|�RU�U����_Gj�P[W�@]o���o9ߙ`,х���=��A�pU���(ye�]Q�Fs�oP[����q;���?��C :G��
+/+�*52�0(���but��Q��b����?,�.�إ��?{��[�syܪ���^�rjR�^rR硖k�XD�@P�ԸЫ���Cw� �"Ջ�%���j�b�h�DCz�H^���^]�X�T��TGgE�����/]b�C߭�I��N}�c��;6���us/�q���q����d�hzo8r
+9(�D����I�Se��N2^��"(s�qE�ڌ����y��%,K�K��4P� ������;��[ם�p)���F�z�8I�=��$����ܣb��aXNJF��[��r����K��O|�c�=��*�۰��CE3���w}��>v�cgd�5-�D`;nKN܍b�1֛Z�z���ՠ�3�5b������M�%s.�7{SQMK�҄�+=B�� j�^_T����N
+�N(�$�e�^������1�mp#�P�oՎ�4.e�Q�P,���\p=x�/>3Р�к�@��U�[Z��?��Z��>ğ��C���p�܀9<������v��'Ɖ�� X3& nQ?L9�t�(�����s]<��a��7<��C����B��=
+̋�I�a?.�1��eZ׈�UQ)�V[�dQU�O%�"����h>�0BnD�GلB3� �(P�&k����u��NC��s�G�tW�,/��Em�R��kcÖ�F+��-��.�桩k�����[���� ����;;��{G��xU�},>xdSS��ֆ扁��D���Q +� xT�u�<|�^A�Ɍ�TF��E5���b��Zf��wQ_Q`.��y�{�ء{iY��m�*k\���5��Az9��%�W��zP��?J@Z
+8#���
+���My�i�66�-�Qh4�6��Qi��i����n0+������o�iY3��6�C�q���H��(�]�U�p�NO��J�ӧ��������+`��K�>x��� ���_k5��-��@%��~��g�� �e ��4|�tr��Xs�� �v�Qmu�Y;m}�1��'YK�����>�9���p�����z/�;�j9��)SC"(�!��֣n�#�p��(��ì�G7>����4�z��(��㢄S�wP�b�H�� �~�0U�c���a�$��E��"Ƃ��P�PP6��ӑ�F�� ��k�QG#�N�����5��5F��9g"���DN� ���@�+JN�J�i��F@WKy ��-h+���yp1yXv積( ګ�̢���Wy�5�Fw�J��Æנ�0;e_a�F_a�F_a�+������QJ(����G�|����` ��*F,������t���=�",�ݺn�1�b�ӽ��6���X��uI{�;��/.��b�%���g�֮;�����6��{w� W6�Gj{+�qe/�,�/�[1�{��<��ę���A�Mh\s5_�4�K��C@5|Ej��7����R��x�6��Jj�'�KT��H��a��/L}P@��E�k��bD��~)�J^<h�W�W���&C��n�7���v�����A�4��3}�-R3(5���� ��3Ҕ+M=>C7��o�oR���izV�n��o �&��Tiw S��p45�ֺrr�xP[��´���`���f[`|q)[h���(����Z>Y�i���p�0�S%Zw/ӎ��VjN
+@8e��+ $��Q$�j����D�(�_��%�J��-8""�c��fBr�ܙ���� ,MSY����fNj&�;�(�e��+i#�5o ���A+m9ɨ� �=�U�+���K/���ϟ=�����X5V� &t�@��c sm�u =c!��<&�*�W���e< ?9��}ė_��9!sB]�����Ÿ��0g����܁E�~�{$&� ���r5�r
+EOm�Ŭc� v.�@�B��A&}����F6/�r̀�L��Y'E�ꆳz�}B,�0,~V��#�i4( ���m9U��#�]�X���d�+�U\���ۉ�I��O����\������s�D���ɥŅ� ���ĺ?���2��w{�.9��ysO����:R��!ȉ � �*�(��⮚��������\(��I���O� ���|F>Ө�2��U���U�"a�[frE��>{B�iׂ��N�*�A ܦ@ jby�3���mV�[����nݵ��n�|�'�9��v����wn�r��������ރ�X�#�����y��[�,�Vp������z�1�7Q���Ѭ訴B�b �)���5x]�:x ,]s\�$%P�E,[���*�q}ݠ��TB��:�0��� 0�������GX�GE@�p�ѭ`MD׈3/�F���hW�z=�C/w]�U]h~1C�0W�&����B�B�B���61�61�ҫb&L:-^��fϢ*E_�!Ͳ�Ar�Q@��J�F�~�M(^7L2 �:��qO��ޫp�<\���t����;]G�w���޾����c�z}�F�FvwWUu��ؒ���:� ����k���f�� !ϰ�m������۬pzK�!<�f��]��B��O�E���;��U�{�62�ӸP �~􊺦C������,�|P?��/��VY��v�&����;P�&T�f��rRȦ��~c6%�w6/X� K��'�^�j.�Z떸W�dzzlE��])Ɇ�wg����k�������������� �AZ��m ��Jt��9��r8K9�;��+��cf�\9Dq���z�<m$`t� S:ڞ^1��kJ��/� �{]Ff/Rx�)#3�)<�\!��V��j�W8������Hҫ u�y�4ߏ�}E7�9� ����\�������Z�t�*�{�t=s݉���4��Ů���ڗL�)';�6v �v'N����lxF����e���!�C�g�>͖yx_�B9���[�p��:��:���@�9 {E�' ��2��H�n~N����Q�X�穧P�u��e7�� �i&&��� ��[�[>�t�s ��v 2�ŗ�C%0�栀JZ�
+��9�#� �N#�݁�;�U�!����T����$PzQ6���i@�&m���¢jB�U��yvb�,��GO�7p@���:���_�KJqo)��Rx�R3��2]]�u�i�� �z��<�+&�:V��1�b����J�F@s���Q��
+^_��+ k��]͌S
+0�`�)�9�2.� 0��8�2 ��ᤄ�ta��������o�/��C�wm�~��Z�% 3�Y�*/�zQ��S�a���� �}ބYEj.�9(�V�Rdu���A�:V�@��U>��l,6l�6�\U��Czn��9�Sb��� �$=��6�tOo{ta�[��xEyCK���-���n_�Z��ukQ���i s׎�����*�d�qQu!;�F��S��UV�/���DLZǮ1!�G]#a�56CG�N��H���跜٧#+�F �]�յ�\#��AF䀛��g�L?�"PÅe5� 52�Պ�e�s$��I=dR�`k�]���>�@Ig��d�'���
+8�Rf�n�8��w�,Il������
+���DH:�bb<[aP�m%[��Vb��l�������V���6��[i�������V�Бq�'dқ2r�"�Y�Nh�]W����s?��#��ŗ�C*ʤ��𫫷�~|���}�+ ��2����jx��7<WV��]���[7�W���tm/0���|�"H�^?:j��K�P<����!k� n9�w
+�I�/�^
+��^��܉��Zt�� `��T��4�c��~&�(���(3-�Y3 ����h�j-�5ѻO��� ~E+�M�SN
+x
+�&�� s�IS�̧n昮�.���#ڰ0�v�;c(;Q�<}�~�7�pJ@���+��h��)�q �!��C���=��q������^11 �b�Ĩ��h3�h)-�AX&5����g/��g���g=���{���E$�$@?���o>/�fi���ܨ����(�o�:ā�q��V���pс�9�2ǘ�}��k4!���4��&��50fVBu��I<�$�}���=M%�mV�{����ӆ� �)TQ���:;�<�j��M���x(1��m8Vں媎�#[[�{�Cm���DN��x����;w�� ���~�4���Mɼ���dGoM���������X8�*�J��s
+��5C{{��F���pZ��`��-��q͞<�-�#�w����<�Q�Ɔى' |97,��<{�K ��~b��m�`� ��'1^��tv������qy�<>d�/�0@WR�Y3��^h �~ ���*P�(4�U>h���)1$�/zM"RC�Ǥ ㊉_t�����o�y�ܺusۛ����mY�H���Xꛜ�lh�?`E�T1;�~7Y��h`!�L|��]ͨK����� �D�\i���Z�� '�^ZX��ر�L<��t������P���#�+��Ɍ�nɤ�:h��6���*���������r��E\�e"��z`�\}�@ s=`�G���K��0I�E�_2��z�ş$�<�Q�ܣ����p����&a�I��h�G)y( �M�v�8�`U3C�`�i�EE5� ��e��00 � �n�t����n Ut`���+^Jw����%�H$VL�ا�lόx�����]7`����������}N���H�3�Y� l������� �Hμ�y|W*�eml�z[bMCui�>^hIV�\cﰽ9v�� �C �9�ޢ��PM����k]cYYl��~��S��Ks *�ܱ��Z�t�=&��4-tс.2�=�Э��3��a��],��gP���t3�r ��^/��%�]�-~�:��t�F� �ծS믎�c2Bs�1��8#`L8�2�x�HV��>�+ �(D�<��U��7m��Z�<4=���.Q��J��N\�W�$Q�P6���^ Ug*Ӏ8u�[2z[
+���o�#��\S�w��͗�vt��X42vh�����kGgi�浑�������M��ݚ�h��i�Z~|g�j����8#$�ҙ=�B8����b�N2�����@9��K�������AA�;�+��M[�!����-ݽ3"� n˛�L.����bEPƊ��fU22���X��~!�� ����I�
+2Q��GH@� �b�I@� H1)b� e#'t���4�r���ṙrB��΂u0��8��>b�o�w'8s�Μ]��s�ʡ���e͕]m�b{~i����}����>�tCk2�efp������������u�E���MG{ֻ2��M�tӏ�CD�������X%w]+����ڴ<�����J���� 4V*��5�L��C��S�� ��1�}L2�J�� �N����^��r i�Wb���� ��3\�M�B�G�Yi ��C�qVh�� 8< uށDu���97;r�N^(�2���lB� ��œ�Ɖy�
+�Q��l��g�/�����`�e��2��2X=g1s=8I#�[8yD�9 �t��g��|Ϧ�}��v �^[��-Cw�k�t.�ed{��U�Qg�����Z���W�]�[����R��u�����!>L�~��2��>�Ɵ���>�6-�j��s�P�r:�С�������Ԫ�1�v���OY�W�*Ȋ�Ic� !�C��P ��G�C8�N1�S �С�*��%�*K�M�\�{ͭ�pr��e����tM_Ua��"z���^ۛ����<�P�g��N�YBg9mWþj��[Tk]���6��{�D�wG�?nr�'�Nq�N����d]��]/��I<[ע5��p�x)q��#�����oa�'a�e"��bP���� �p&uhp�����D3��J�5N{���En8�G���s�Sb�"��"����
+�{�p1Ċ������h-�{T&�"���n��Qh8��j��O%0�Z �q�>��i_1#��p�ˡ��4#L�� =�wB(|w�Z� -�D�� ��N='�p��/=H���f�'4����Zqa]����!T��I{2gsL�Į�����-9���hchr̮��1r�@ud���]!{�R�'ZZ�'�#%e�t���#��u~��؎TGj����Wmlnjٸ��>=��t�D���p\0ħlv��V��d�Dk��eEq!�}�I�T+/����j���."�L'8 ����z�UL6C�*��N�Y��ݽBpƣ`+�g�R�g)�YJ ��r�Rȳ�,�<��~z��J�.�L�c�]���BAx 7B�;C�vpwz���vG��-�f˹�;���/�gkr�>�f�)�\��[�>�|����3���|MF_L�]0g�n,2U�a���i���s���NP� �t�2��n:<c���â{�қ���>��_���B�*ZW� �赚8 xu�
+�M���.~�?����s�2��5Jk�)�W�픷�ʍ��MG����Yﺏ���{�H�X�r3Q�_��Կ�>��������M����T�j��a�ֆ���J1�W2�I^p����`���Q/d��$�F:���
+rZ�ST�s!:�g&�
+�P��bb�J�ׄP6�H�KD��\�@�&SS��U��1� 0��MӸ���+��A�m�~9�>_�,��/��/�_�_�� f��c6�8�����Y_P_P_P��;:�+�*�Ւ�p�V���������|&�c~�?�~�4!�Z{tS>���
+���u�H$�.�0��~ay��\���\��B� �T��;;]7�ҟ]a�I�OA�z�\TQ�h\����Ͳw�:������Œ٭]�ٹr�K�ކ��Ӯ��~��޶�X�k�Z�D~��2˴b8���W�sbN��Q�ej7�ޏ��$�T��mBz�"���5�I�s��9�h�2c%�2:gW����,ܷg�ʬάO���:�6=N��)��\�m=:�}��V�ϖ���:���Gw'�����.�8�R����w�F92Q~]��?���4+6���l��嗭�΋�BA}(����� ��P�I�� �K�Z�:n{k����K󊪊jӉм�=l���� �SѺ.�;= �i����#v*D��*�Ck4b�_�6 ���g���29���W����`Zj.�5��#�]je+��Ѡl-����k�k�`C� �AO�r���8�)ٽ)����2>�G��tH����i��w�&�Sr�N���g�0..h�5�+n��Մ4C�I�A5���MU�5��>�nS�%��$��,y؃��Q�t����z���`��VÁ�,ci�nq%|��/E`�q�G�需����N�9���Y�S��_�NI��r��S�umeM�
+��}�>����it�Ӹym�{K��DQ����}(R?�^ۼ~Wc��a�z���[n���|� =���ğN5����jSߝhk\j]ߦ���ߴ���2_3�#\O��W=����yU��.��]g�2Y�w)s����~�+�V�E�=��n e���E�\�
+[2�毹�S
+Ub�־�Bk���ᄑK���^�oy��9�hW�ꤞ�!���#)��w6͙`�;B�'E�".8)�Y9닩`&ͨ� '�N/Ȭ$2,]K�>1k���ei6�h�dG���=��A�M�i�>��@j�����XG]���d�̬�i�{��xw��0���,ovxۙ4j�j��K�����!K+ģV� fI�0ɚ��P��r���
+�T�*��}��&њ7xF��$ h�7�E���Ҁ�Rs�*��'��>d������=����Ն�4��/�W�����Z�i��
+�@3�W��F� �H�3��C�yF����Bg�E���_��y� �\ԩ��c��1��(l��}E��� �N�W��g$�`ղ(���L}���j�[B�^��(�]T�3.���'ڡ��8��!�/������Op�DF�l �����Uo �.@��9�ed6��{fP�?/���ߚ/�D�ڦ_�5c�V��DB��j�������*`Jd�=R}{��� ]�KM��I����Na|[����p׋������_���"5�0p�ƌa,D׸���\&2�V�&ȕ!���5�4�����y�S|ی}�ƃ����x�}�V�֝,�޴�,��!���B�K�w��>ʼ�Ź�m��WEO�%�7�(yԂr��k ���=d؋R�~��gB�k��r�R#5�-1s�ۄ<ҏ��<O�{�R�O�)��G_L�Y�|�e=����"���{Ej�/��UQ�7M��p��,|�[�����a���J3��\)5����H�w H����Ɠ<��&��+�O�h��'���M^�}��Eٵ���>���� �I^� $���x����BV9���u^�m= ��������E�rd�����B&���k�5O�����/L��"�{�H�x���fL� xY@���R�DT|q_�9g2��k^o�m}��nʍ�~H��"�o Ȉ��&�dwi�eկ��-�?�����tE_�p�>����� >�����G������K�>��b�><� �OW��p�*=���������o�B@?'�k~"��4�N@}Sj�����q��;�9#f����v�2����K@
+~(5?���� �4��#� ĹST�4�PX���3r�(b^�t\@��;l!�� ���Hӧu�٪��*#s���4�{�53"�r ��hx g�xn����=玗�q�ٵǫK&��9~DQ~d^�ȼ�%��G��63����BF��h�_g��Ƶ��$��#��iV\��q��d�Gw���n��Y]5�dr�-`��Fx{��|aN���� H����1��Q˳�1�C�<^N�6&K�Kʱ������ <y�;m{ �~���1{����uj���� ��F;Yd��i1&�Q
+�C�V!r�u @QcO���`oH���C�4_��1�%}1)��z��ǣ0]XTw���;L-�?���V�U� r���ԣ�ËU��8�����>�ߣ�A�ęށm���KE@���kx\yQ��dԇ9� �8�eE����$e + =�R�.h�9��
+��
+���O�.̩]V��:�l���6�Z���8]e�#PW�<�U���E��]���8�".v�]�Gn��n�g5�|\jNI�j�L����$g�����R�����V�(A�(�و���g���\�8Qp2�}��lLb� ��b��C��}m8��5����z��
+IȺ��L�c�khd���_� �k�}�m�h��r�҉κ��Ht��~{fN��Xjso�ҳ�f �Y�P�l�545Tƣ��Xk��5Q�X��<�
+���u���[�)'�/K����7+�"������ -�K�����������ˆ ��c��r�#�)� %女w�Ӱ�#�ư⛷�ʤ��P�J$>��Jՙ� ��͞dp=m�b���U�yU�!���D�s)$�V\��p�ܳ�cς��'y�(�(�(�P���jb"A҇j���+G��.'���/ݽ�����SG H������ZQɭ�"��h�����$L��Ri;�.���@�@���F��ַ���]�5��n�����)��+13~T}=[To=l.rhj��R�f��?sӱ#��7s�L�����n揸�?�۱D
+endstream
+endobj
+846 0 obj
+<< /Filter /FlateDecode /Length1 9380 /Length 5521 >>
+stream
+x�Z{l[�y?�R$EJ�H���K���(�D�-ɒ+�mڢmY�-�2�j/��4��5��%M�6�Ӯ��.m�zS;4�U�54��3
+,A3�萮� �<֤����%Y͊�����|��{�������9����!���2:xb�mL�h��y������5�Z��ێ��]_f�����3��k흌y�p���E��m�(:�kރ6t���;�k�/����k��\���Gm~v ����?qHy>��Y�m'O��];�.���C�����*��}s�� k�� ��i�y���]���־7�IEr��7�B ���:M����k�n��RWA~G�|=�<�����ڧi�>�ef���!0[�" �<��vfƃ�8��l��k�5��_f�?��c��e���b�B���n��뽬IP�f�9f����2���}��*���'�G���U-���P �����B�8U�?��
+�o�+������������r���WR�%�}��w���*�5�P�ҋqh����W0­���]�U<�NL��T���ٹ���ъ;��-]��[�<�T*xJ�&)$��+2k!�&����(�1���?Oc�J��.�?�>���=b`��ZVJϨ�c�|hf�n �7u�19*�[���>7I$���T�Fש�iMP<� �d��|H*5|��~ ��$�A�&�l$����J�ߡ�5 ����*>�>6ߠa��ְuMni��VY��IÎ�a�ҰkM�4��.ҰgM�C�%�Zh��Ȳ�ÿ�ʽ�T��`nC�K�] �p��w��lZ�1� ��� �>���"��XXp��0�6�ڐ��/���O٘�̆����s���Q?x��a:���]�)���}�~D����>B-�o�^�l`j���gЭ��=kB�k�_�Ok`���L� �̈���36fg�ĕ����y�B�_�?�&�G�[<�_��¯Tw�^i��:�~J�vQ�B���k�t?���_ѿ��͡�m�o�L�|�e���id� ��y�X�����0�BL5���R��� �/!?������Sn��Tjj�P��h� 09^P�C.z�+����0� ��L�zDxd�3…բ�,,� &Z���L\�%�e##�&��"k�:�Ʈt�$T�5c���H~4�,|����4Zm����Ɗ���Yg��c��p���!t^V��`�W@���s6A�M,
+*�&A�1��9��c�K�+��y��mЗ �r���[�VL��$`�$� �92�>�j1Z�J�T�U�')�A��(��`6���읣��ќ���T��Fʏ]^�o6Y�+y�s�����`�.t�<����T ��,�dq"�}S�ٴV���D�VA�04�A� TàW���f��LmŮ��g�*���~��W_�?Ó�Ǫ��%�����˫�_ĘP,���g��Q�$8�����@��N��o-����[+ߍ���U@�@g@�@@��.���Z�W`�1�Y4%�Ř���Q������U@�@g@�@@��.���Ȇm�V� R�����b��5X2?���&,��&���kڳ�g���Y�����B�'"e85I��Z�{����c�l�e^���=�#�|Z4v�d�_���wm�}Y�HD�E�Y͉�-��^�`�^�m���j�z��M��7
+I8�_]�;�_`�+� |F@[�K(ʁ�A;A�A���= z�8�P�<���`� $�C N�*Z�+��V��y�t���˓o�X6!�&�.4�L/�}���n�s��/T��djho��)��:������W:|nz������&nʷw͞�/��� K2 c�cH��e施�U������Zū��(�j�k�m�ټ�͛j�� ����/~idw��es]��7+w���������CC#�!�Z���\�Ÿ����h=\^����2+�<J|�a W17E1�T����;��7R1!l�����Փ�T�~����jn�홗g�9����k%�F��0Q��xFF@0^��bV���X1+F`���#�bV���X1+�:V���XQfpcT7��&��%���1q���S�$q���=c
+X36�`:>�~#��Eg_�ٟ ���Bߞ��4?ܱ��.��Gz˟(Ǔsw� �Y��;f���P��#��r�9R�Vz݃��?=~�b)]��ؠ��J=S�̃kh�L�L�e��(� ՈjD.5��QF�(�F�Q#ʨeԈ2jD5��Z�2�Ԧ���zL��aJM�Z|a�m�4V�F⦌)c�!l�Wf��f������'���\�ihh��9�-.���D�?-����N���\�h
+�Ĭ�"B��=�ux�y�XA�N��o�pC��`w쮃�u��v���:�]��`w]��:��T�݃�̊��З��/3�e���З�2C_f�� }A�� ��@�@W@-�Гzj@WP���b��!Fk׬�
+T���%��J&U�Q�?�}sWfx_��ӷo�ڎة�}�\|��r���8�'���dv����P;r&�dߖܧ�M�{t`�轓h�c���(��!�_*���/ &b��Uū�г �^Yϒ� Z��Z�� Z�� Z�� Z�� Z�� Z�� Z��PEd�f�g� �0i�2� |P�D!v��\ 駖�D��4���_�1Ws�Z��[[[A�d�ڇK�ǟyuS���� O[Ŕ˕KE��R=9��K�h��û�O�z4'��z�T�w�Ev?�vY0���%!�ВT��,Љ�� tb��,��U@�@g@�@@��.���(w�Oi�ek��i�<��� yJC+��#�I��xRS�X�?w ������Ʉ4���mX�� �;n*��S�З>8����;{}[��K�˙�9��:�m�dX��6[bÝ� �>{f��O�-&W4 �<�c�'����)��b#|/���a���9�!d�&ڲc]�T� ��w ����/-�K ����/-�F�ڟ�yd���%�
+r;��j�2Kc�4���k�}�J�0k\������ZG#u4R�
+b���2��ۃb"�s�.�!t#�TM��@GAw�!g�Ê�H�&�yI� �'q^�d�A�@G@�k��� �aWM��^���*BE$k��p�Vnk��JN�&�-ӝ� j%j��&$q>'&ݾ�`@��XQKnBUB}[�X!��4��7�{�^�;d��Eڄ�p,6�R� �i����l�D�]#�6}{����ϣ~��I����Vo[�]��Bo&:[��)��6B�-h�b � h����n�֨��1�w*�� �r�=� � �r�1��,'<� �r³�0�s³��,'<�){�,^����!ԓ�C�aR��J��f|Ц�Kp.(���n&ׂ>aSY0D�)s�R��J���n��K�P)���L��x�_2S����5�&���R�7U�#�` �9��9r"N>�߁���
+��Լ����S<���)x��⁧x�)�3��A>� �y��<X�\�z����%v4�B;V�A�!^�0(݈�r����5�!��SGJ[�{�}��{JOv5n�� ���dn�/$7%��C����#Go��gGC�d!�S0Aq�L����(�Ɗ��(T��;ZX(<0%�3�fX9��A㠝 :3�t�aУ��Aπj+gX9`�ad=F�cT�]������Yeϧ'T�P�
+�%�Z�3/��^ $_A=��M�I�q됱�e ��׃�?(c&iY���,�$<W}��nn�ˈْ���i!r�Uzhc�
+����,�[�:�@~�UQU܌�����Z�u�`}z��c⩜ � ����L+*a&�ժr��j�E���YɾcG�X.6�����
+����le8$���;�{|��]��}�ۓ����;&�J�s�zR���t�>��
+➲1M�bᴦ&U���s4ൂl%�^�k�$��N�@HI!I $ �$�%�>��q�3�B�@�m�;)�F�pR�e`7F&Q�K��&��8�">J��I��Ix�{�L�(kMZ��[�:���қ��ޝ���`��ƬI���BG�T��ӯ�
+A�)��(�F �ɖx<s��dvas��+��xu�=�2��9�8.�G{��ّ`h��:��|��W�o.6�Tp$2�P�/a] ����N|(>B �f�݌�G/�����P�)�b+q
+F(���HQJʦ�hƞ� ���
+�����U��#6���[n�A)��~���0GMF +S~ ^C>��P��)RgE/m.)��G�ί��u�u���V�=����T��ڰ�-�0��`>Ug�ufIf�ݒ�������B��י%�4P�x�(#�f��5J3˽��O�U tj9q;R�+m\�Ҍ׈�_�}qM�8_#6�����5Z��V��[ٰ7lӕ'�%[c��9(e�.�t׉^AP���GZ;c>S{�Y��G�&��cp�Q �����9�\�����z�݈Z�bRp��V��6R֭���Y�u�8�U$��}������H��S2��� ,�?�!���{�Rm�Qm��Ն��ÖzTzTzTzTzTzTzTzTzTzTz9�:e S�k�C$�n��{e�|lz�3Q
+J g�����?0?������s!5��ruO�R�i�+=�*��F'�'c�Ƀ0 �_%�_&���c����j��������WV���_jl��7`�S.ԅ�я����Q"�+G�r��Z�f$�u5�Ց%My����@���-�����vӿ�ޚ����s?g���^�-z��i����k�����r�H+'�i ��r���@`L�i 0 ���4��@`L�i ���JCk5�s�(��j@�i��pK��z5�l`P�ȹK)���V��7e5���i�GLǥ�%o�����j��%�5� eU��%ˋ�SsSݎp��JK�/wm���FR��[ ��fq�jt��35n5����n��v�Fo��6/r��%�(T@3����h)sر��=,�=�~��2���S;(
+��bo�?��1K<+o�`���sso*0,Y��A���OU�%�)����O)8��_ErPΥ�H�͘n���.�
+s�q��$�Z��T:ӣ!���d?�d�S�3V����[���ה|��U��|���BT%��� �G?Y(��~A���@�!�1�XE%�y�����C �1�,���wk6X��M��P6ޥš�m��8Z���
+}�2y{F����ç�<���|���y���������o���iYo6v�'���9�ϱ�^۰[�ú���s��v�:Z&���v��Pp3dm�λ;�f켛��n�λ���n�6o`�m��ЕV��?~��q���\�1�7�zŸ��gh��]�N��-��=� �6���Z�}� T+������/�n�����
+ZQ��Q H��c�1{X>:��P�n������� �e��vVF}� ����G1h� D �b����8t��C���?}�;��U&�
+endstream
+endobj
+847 0 obj
+<< /Filter /FlateDecode /Length1 3988 /Length 2293 >>
+stream
+x�Wmh[�~��W��+Y_�dIW���H�%YW��8��ر[�8Ҋ���{���s�d�4��$f ������`�5 �M1! ���X�؏�yc��Ja0�
+�6��s���]څ�׼���=��{��=���/^��z�L:�4{��Ǽ��W�^Z��>?���󧗪��O����޷T�,�g��>}�6���g*�օ��z��.��3�NU�-o��^��X�O"�|vvi-i���s�Zֺ$����q�:���T{�͠�� qͦ����]��q�o���:!�?a͆�����5)�?�����y#h�i��y5U?�7�7��oZ���M7��Om��q�JF��;��(H^j�D-�{��aqP�9t����$�<۟I�R|��F��h���W�Ayy��P��8� �Yt�.�v�jF.u����Zɏ`v�����$�!����^�|�@>��J&|cG$ڊ�䜴D���M��F�V2q+}�턡ez��O����a��j�&���/��
+�L���R�m�Z)��6�7�8�Q!����B��D�'`����h�=TTJ�2>�"�� �secDk10�RJ�e�..�}�*�|��|��?F��`�J �Y��V3%b�)1!� ѩ��b�r�W*�|��<R�?U,�/�B�f��3EƂ=g r6�0�K�2 pQZY>���P��ʊo+�,J�¨j�J�Cd�†��bhH ��A )!�Q*�wMbb�8�LB"�����
+�@Z��(��#�: ҆� R�@*=���Lw@jG�6i��!U��m����e�ˏAرa�W#���I���KC��5!��$7?���Lw �C�^�p�6�C�2m-�����/���r�#�����q�'���Cl�y� ��)ʱ�d����'�z�ĝ#ӑ�E3ɋ�`4�h���=��N�U��T[7�q��g�����׆3�;�8� �/\����B�����+��g6����g��_
+�u������{*�lf#�I(�U�إ-�T:dW��6W�ή�`�v�D��N{.�����I1r!��(��B��\���D�V!�:���&�=�},�Ι�>45�mjh7�2)A!� � �CnAnCއ4��<:� ���io�����=$��m���̚F���:�3]n���-V�+� ��j'W�V�Z�;��q��q0�p��0��'�6|,�gvHf?k�M�{3rW{������wZs�T�d6s�'괎�}���,�Vq=JZx+Ri���l��o���[�7k��a腌CJ�E�%�5��[�ې�! 3����ּ�ֵ
+��"��V�+�q`.���{q�[qӈ��i�M#nqӈ�F�4�7��i�M#nZý޺ׁt nn�t ��NM�@� ��/��WW���f%���s\ �m��-,�h�J�_����p*���+,R������ӱ}�c���_aݹ���Ceo���L�;�i8�7�;ڝ?���Og�c]��P)�۟��:��#6�i ���&V�+G��:�� �5\xh��ֶ�a�uZI��11b�$�׬��̥t;\�l&���b=�� Wff^�X�l�x� �' ��x6��_��z{ 0�cPs.8����&��Q���Ŝ
+�T0��9̩`Ns*�S��
+�T0��9̩su�:tB��p�:�Z�>{QF��^�O��G�s�?g �u��F
+pO��{\Nt������ȹ��s���~����:�騇�HN��I��LF��m��HK,�
+�Ž>9�N��t�n��� 8w�6���c=������H��������S�)�.��o�܁s*L{-Iв�5��bMR��> ���]�DA����2h@�YB9�P��t�+S�Q���X��#�f��.[�<;�?;��(~7�e0�b}R4���Q���Ll|�/?7�65�g���/ WH�W��ɃCS��A
+�5���e�"�;V����#�w dI�]�x����%�.�w �K�]�x���]�ɻѣՕ��`�%Q�. Ep�d�=��t�����^�a�q-E���[u xgv�}��{Z�g�(Y�N���I%� �v�w׹�`��HoKK_q 5��3-��������`0���~�p��h[��I�{~�3�ż�);����y�����x"v���kX����"b�ً;[�b�&֣��J��&��\GVq)�ڪ�g5³X��׏�v�\��Zw}k�7��Ɖ��R�n8�yS+�HG{6ߤ.]�»}NKn'�h���6���,lH<����)���ϼ4��xj��� �����ѿ��H
+endstream
+endobj
+848 0 obj
+<< /Filter /FlateDecode /Length1 1144 /Length2 42889 /Length3 0 /Length 43673 >>
+stream
+x�t�ctfQ�-�v�ض�Tl�yc۬�b�fŬ�mۨع�����N����c�5��5��$J� "f&�@WFf^��������1P�A��� ��0���P�v�3�_�_B������(n���W�r|3v�2X�y��y9X�����������lm�� P2w5w�����L��́��n��v��f*�.nΦ�.������1G/gkK+W���& �����1qskK �������������2�;�M���J�f֮�(@m�������hal�ct�`��2��MTh&�`�.p�虸����ߢ����o�@����-��f�,��͑Ih��f.#���Bp��,�]̬�<̬s'�����?B�y9���d�l 4��qtpX۹��Y[��}�����\����|��������̬M]&���o�as����:[{t���Y��x�{��w�f@;��+ۛ�ԥT%E�������u�뒁�������W)=�p���G%c�����-<�J�o��+ywsg��*P�S�4���I�����@�o��1s0������S<���J�?cH�����~��[� @���팝�����������j��K��?~d\���ME��v��&kIkOs3%kWS� �_�:��7�\����w����������-������I���#�����h Pu��?cg���A��9;�m�?����-��&hn�in
+���`�j���\/���p8�6ȩ���F���t�l@Ƕ�����G��Ҹ�`�.�7p��|��\�<�݌�h�ah`�Qx�M�
+�70�3��cq��NżF��I��)�&�T�0�u�O������j`O�hx�^������y�F{ęm�#��e{[g_�du�[/��k�ь��D9¥�\oL�+�x{&{Y_���{@��K���&�?wFi�p� 7�pp��8���VMa�3 ��g�G�WD�F�&u��[���d8n��R;{�������+w�����0�ڇ^25��7��Ǐ��z�v�'@�@� ꒃ�Z�|eT ��28�������_7�[��&�$���O�^�PB�+U=�,����p�8�wmQ|IK-+���季��D���yuؙL亱��\wsS5>� �u ���)�.��+�uG_T�C)��H' �`D�����T�3툨4͢����KK�.��<�E�nE���-nZ�c#�
+�@��q؏?k8��4S(�#��C�.i�b~ 5db�=��ճ��{��� (L(�kP5$}l��5=� F8�o" ���h-a�� �*9�(q�� ���6�S�20;��-�����~3�"!�A{���E����G5��|���#������D�E ��N����j�Zr�-����$=��^�`i�o�F��I�`���̑���Ѱ������s�d�|m��&pØђvz�Q���4o#�̋x�A��yIg9�Q�S�� 0�*���O#�v1��{,G�=��~��%�ow����G�������#�H���tM���h��j7�4O`�ƭMk�y�׬*
+�����\�{ �P��G���F9��m�����U��$H��TNy����o��X���-�)�3N���H��hZ��k�5E��;�3�l�[7ݟ�s�edKA� l]Ϥ�Oڼ��5�.� -�WX�e���c��9 ��SxG����|{�6��9/?��*Y�7�kH�����N�2�@�F��Ϝ|ǡrgn��+�)�S��:k�YY.KK�6�Z+ W����(їu�K�,(zr퐖Ȼ+9��Ͱo�Eo���\�V�j�0�z9uq�$ *\��y˝���&�!��%0v�ɰ�l*�];
+����D� B�������6R<�5���3"k�eD\~1('���ap�����G苔�\b�̠4؛>�_��f��6o����Ii�xA&�h��ېx'��Ie�(0w[Z�g�_ M�n��?;�[� ����}L��F�>�SˆΆ����<_>�P��qk�t���꒤
+����X 2�� so�Y�2���c!w����e>�����ܼ�.��^���WzS7 n0D�e 0�͇�_���ڢ����(���yTt�Bn����� �6�����ҏ��“L9�ߝ[(fߪK�i<\��9�F��JH���,�,�~�������&��X��"3́�-2�N�� r_aA�f���iִ���"�,�Z(&׽M|;���G���)Le2&7����CE�L�᪦m�|���K����w3�}o��~G`͵$�1&�d,�{�Z(�j�J��T�%����|���j�>������l���J�J�^�D!R�N^x-vUm��\��I1����Gľ���קx 1��p�썩Piu~���^ޡ���+�� �85�Ss�d�2V��C�I�-ޛ*e�M� ^9���?�X� +��V/�[��H)�����@��'����~O=��F*��f^�1qNB�U� l�T�"���E� bpX�]�I
+<"s ԛW=�`C�����8]�[���~�ta�NJNx٨}����H��ZW�4�bL�ߤϼf�ZP����,�7e��r�1��a� ����m2�p.N2������d2e���� ��L�SH)#�.�$%���u�]U2�09��P�]>y��dDN�R~����H��e��y7��hg��~�m�� .[o����a����)��=KO��]���Z���'W ��{%T@D����\0�4B�g�+a3�9R�g���@[�������T���� 4zY>fP�h\.(y�
+�(�
+1G"V�b��qP���� �w�X�kl}딫F[u��E��G*f���v#1�p_�U��räM�S�;�ځs �m1&�i�ǯ����Nxr+e����ϱyV�<ՙ9��OD�( �;��I�l*�T�^~��b���*N��T;�1Z�?��L�^�Xʾ��!�m,p^�䋕J��PIf�`ҟ���� B�6��}��v�O N�u�)� �A��j֦���\߆8�ѯ���+���]��RT�C��{ߥ�KF� ��ړ�y�S�H�#sK�����s^��2݆�y���`�*Dv�t,!�N�~'&ϐ2�(k � ��S�>����8��M�CV?�(�b�%�E$���#��2F��ۡM�™ͷk�e�j<@�(�:��9�v���� v� �f0m�ۆu���=�f�W6/�������Z����a:�B���pm��|��m�M:�6%�
+�?ь7d)�E��fd���$fP�]��k�Y��5��پ���
+����0 ���A/����$Yhp�V���CS�G��H�gB8Qr��K( �F
+�A�4@��O!?|o�m��*[�2\�(��Q�������yIVB���f&� �lYTwĝL�7���>4z�L�6?�NlJ�jl���[�T��C���R��R����JI�+�Y;l��`y�1h��' �f3�{C��F��l��d�4tM:2I9��t6����'<���n{���������EF�N3��|KB���D�.�}\7V`�L7��}x����G��B��4
+ <D7Y׳��vB�w��,C]8IX�5�9�8\ؚ��8��v�E4�%睟w� ��{�)�M!I�c�@B�e.�^x���@���S,�4)c�G`�Bu裏�X���p���N�: s@�tex`& ���>��v�����QR��D�����Kg�xK�l2� �3���z����"La���I������km�A8�胺$�����*��X:�4����K�$���(Ǹ��ж}O�����<�{BD�8�##}����C��Q�e��J.�O s�M���"|���߈��B4 a;�L�r"F�� �b���y�G<2[��iK���1ŧƫ���VK��| ��2���0(�~����tU�IrYv���mU�n�gmz7vt<����%Oe��m�� �{�Y�*�c ���p���
+�!�M*8��W�×j�Pp��/�OM�+֊d���o24�]�� ����t�N�=L_��J7�סr)��� ��TEhT����y<�o%��9�?z�H��6�x����pc�e��6.i="�������\n�4��k-�fsL򰐭��K�V��~�@�~,�t���̳�/�����:�͸��/�l�<Qi'�.CA��iSwi��Kl���/[3�gze�H�mz�^O�I�`rR�u��2��j��7!2�%��S%N�ߘ s-�2�c�-�w�z&wH0%�'�(���/�ԥ�̘�}��t�� �V�=��m��?Q!�f�R�vIm ��>8.~Vx�� 1��-M:9�`dbv#�m�h{u���'���<O���P)@�^���s�r,l�Dp�&�p�O�������.!��R���vn��c.�Hˣy�������`t��+�Cԁ|���nR,=k%�Yӆ�u�����b~Q-}�`D�U���O`D���D� ��7*�9��c��HE�����$ � �yZ���b;K���l|o�Md�*���ś�>�� �4H��շ)+��\��)N��XG�U1ed�8��p[-�I(l��+N�|�`n�3�Մ.`y@�*6���/c"&<��[��S7��WXN�}�Z��
+p���Ӻ��V�1������a�66��+�r������"���b��?�#��`�y}�/w2�;��
+o�e=n
+y� ,�<��7u��Ǖ����wd�II<����q~����7��i��9<�D�8&����Cx���F��<�>&�~4,�};@S���V�ǡ��F�l[L��
+<�ΌQQs��P 5�H^�F��9���_4��IY�B��
+��N^��W�g��xg��8 ]�!��6�㰻�|�s5��� W��0O̓`S�{��Ξ��@��*%�(|}��_c����8}�:��������H�&,�z�(,����B������󡆥�kR�ϴ��
+թ,�u!E �|9���}���m�������i-�Uqr��H��^���I2�頞��1�&iC|dg(Yh&�}<���:�����n��n{{��8(i�9\�j�Ʒ����R�����3hޣa�z�Sj�y
+��Ӳ ���[^�����x����3ډ
+�C�._��G��� ���D�h���lț ����l�4j���.�e��Ω�� �N�sxy! ꖤ���oApB*��t�7�Ts�h���b$���!8��>��D^�+(=.#xA"�M�䛧�+�x��c�ˠ� �
+��^֫���N�q
+�S��P�y7�`�^6�o��u
+*m�����D�E�:��%A͏ݓ���&Tt5��=�c0�zg��x>�raD�0EB� ��H���8�j�V�b�ü�<=pS�Ju{�SVizH��ß �T0JCj1N��p�P��� 2wL�X�W���&9���MX��� ^[$�F'�����JSr�c]�_(�U�A{^�F^���݋~���Dbw�n��JD�_Z3W�H~F�pG�g\ o�576~��|9Z�d|���M�� w� F�~V��\�p�m8S��xK��>t��%A��N��p+��Z�X~#�C1�h'p��� & (�}r0� �^�S����V.V�CuA�܄�~؊C�Ի����3��Ha�;��K����[�8˪�v�p��x�2Qsa���HA~�g6���o� �攇|�y� ��]
+N;:�:)�I��V��S"����� (1�tJ�J�{��R)�x0d����*F��)��az��#7���R�jjf�~}o�P~Ҙ $;x1�jS`� q��o�����n�
+��k4��x���wF�VRkL���VQP���G�
+�4n��$1o:�>�jh+؟�8sqJX̧VC&������4���/�'��$�>��ibdQ�!?/H�8�ܖ��J��Y��QX1ݼ���FOsh4)Џ�[���{^�`�l<��8�������o��j�D�;/�`MS;������i a��H�x�K���Tq!/uQ�b�����@��;�N, ����l���zָKݒ�=g8ӎB�� ��Er��$�9O)��J�<��g���Fk�:ESem5Gs^s򃯗��v�v=�/���t���<��U�<qi4�6���� �4��)L��n=��|z�8�^xB4�����=�×P��PY��A���<K��AAN��c����A�O2�a6������1������ ɞ��Md<�+O�T��?�N�"=�Rk����aU~=eýW�͘O�k�̔w��BSs��<��*�&�fq҄�:����ѓ��׿��5����"���Z�G�t��� �yZ��2�Ww����k��nNJ���:εO�MHG��z�x��ѵ�FA��������
+��#��$F~�[M�#� 1T�V��D>����*�*��Na�[��� ;*F�k�d�3m�P����QO��g�<��u-� �O�KѠ�,����m:����R�����\H��K�`5�*�~Rֆ�ȧ�4"� ��܆'�kgj)��ރ�M ��sq(�J �T�6�`Z�ӷx�V�3a�
+�[{%1_δ��~_";{��l�u͢�%M��T�|Ⱦs�u�2�ۻە.;�<~R��P*c�V�V�ج��A}������pY3���ƿ\K��U ̓FQ�+F"O#�T �3W��0�1���J�Tlv�Q�ۃ�Q�*8����<C�I�*��5�-��OcH%�nTYy��זTc�s�J�C��cܻ���e� � �� Qg%��t�E�.%Z�����J/��Y|��c���8:��k�*B<ީ%J�Z>�&�������Sx�:��Q`����ߟg��U�?�"ih�d[j���2�����@%H�jb�7ˢ_�΂�*g�$h� z�
+�W�/�M���;N$��[S3Rn<p��Z|������E䜃�t��ws
+��f��]�x��K[�S%~FjkU�8��p�]�b���[�5�U���.l���/�P�i���)-Cq�P�ϔ�F�����Q(*=Tُ�z;��"��c��+�&�� ��5c�^�-��(D|���X��SKr��=��5��a��Wk�niO�K �G��Y=�I|�gY������9]�H�PEU��ߦ��]; М�@l
+o�m��A��03��!7�<�Cya?���1n:�v@:���j6�E\�1b �L�98_�/��;r�Irۆ?c\�~n~�&�y�{��b�� ��� �맑+U]�TC�X4��#fT�/�ht���!z{p�e֋���� ��9~f����ؿ��k�O���"�?c"�|�]�42���O��7���#�6�Z��+D��C�~]9=�w�b�2��nXTZ�𓯏�L���8�;�*�Pt'}� ��|[);@��/E��:��R��9���1բK>wM�+'�e�֋vL���$,�F�p"[�s���1�El�EێKt���!_��~6���N+�P M�x�{VaL�UǦv+^|o�����+�X���1��{��R�X �/��0~�9]3�%�}�B�
+R���̝`��?�.�T0ߵ'��Y)<��3/�W�u9�r�Z(3N3侷� �U��,n��<ts<:�QG�:�9C�QsT�^�\�bx��&����.�6�6�gh��f�Q�p��X�F�&�AU6N�"�J'c��ъ=��~�A97���v܀�g�F��.�a�(bA�=MX��x���x�2�I�n�C��j ��w%���i�ّ#��U�� i�h��Z�ӛA�4/�
+Վ�$�*PDu�H���c���<�F3�&�62?���" p���}���^i��sl6�ę�(F5�>�Mcr{�q�����B~<Rx"���.� ~�9b�u��t�l!����m�������Ɇ�d܏zݐ&�s �Eø�u��mOW��Oף/�OP�r@#�B6I �)9ɩve�dzᓠ)��B������ E֏Xb.g?K�;��I3���d�Zzc�H�E������(R�y���`�MTհ�B �0u
+R��Wi�Ÿ�O�M�����%��sm<�l�����[�LV��t�� ʎV�g�9bF�����'���p3�ߟ:U4w���.7�ܜ�!Ud�2Ƈh�
+�;LH�ï�E�;u�´���ٞ�=��H�uП�ejh�A$2�UUʤCK��N���%�<n�a�W��`���%�ӏ����F��;eg���x�c�b3<D,���#5���Y�wrB+�w2e��-+���<�RJc�cF$ʨ��-��Hay�f:�'�^ B�v����(?�ٻ��a�����k�jv<��\���Пq�q�0g G0�b�c��rX��2�����W�{����6�k�FF�GH�W�2�6;�A���=0�xԎ=�c:���! �Wl�Α��rB]�j�Ե
+�#U~؞) (*5��j{�N4�z��z#�Oa�D���[%]���%�c�تk[I�¤��ݟ<���TcX�����K�i��E�ӣ����
+� 3��6L��V�J��*��C�
+;��� ��t
+���`Z�Wv��j�"[�w�V=$�+�Y� !f�O�80H�B{��|�]�g8\ա̣/�y�POEU{�r�q����ʠY�~h����0��Md�B���<�s7��%
+-�4�b���dG�2.��,��󢼶V#�u�fD��
+��R�;��1`�^��u�Y Ġ@�����r�@�44G���%G-�~�E).�>Q�e�7[��W�^��T^�d��k���u"-�*��Y݌� �=R�LK)��l <|Cl�O�>���ռ�Yr�����; �B�C�̰���:>sCi�Sg�O,��_^)6�Z��}%�t4�x\w\����$�_�P5W݄�+B��U�%�� `�f��(��/RH`BRgt���p�s�-��f<�;¿��DFԖ �)eP��k����z����F�dK�H��(XG��!,Vz�V�|�!�lxk�8�<aq�m��t��F2���B+YT�- ��瞤��;W_��r��_qD"���LF�?%=���_%��o=/�U�}U�,ӹ��-0���l���C���'k��-H/��P�s�SJ��� �ld��WZ�!��We|7�_�*M����Q��ޑ`�D�)J]��Zb�+_��MD���_��U���!50Xb0�˺����V��Y�76���Kz��3M=Ma�,�$���Ia9��6N���2�/�z�y�j+����D-j�(M�(� ��z��W�!�~�>�p�l���%���g��8�k�P%3{o��{6�!�I�� ��a���3Z��sV��rZ�H�_�xuF�5�E| �HϞ]���� ��$�X����b�H��e4�+a`Ct�ã4W�}0mir�����Xr5Y�{%:��u��4[� ��|�d�N]�2��α&_���}(����Svv ����z�r�^v�߿x����x�~4>ZL�5�5����Zn� Df�X���w��Y8Px��ûiK��z�6 P����h�Z�]��Eȋ�����L:˥����ad��q>G�_K$4���L;$0�(�J���a� �E��^��GC���n4��U�n�X�� M�?i]q�����.�Q�Z@ K
+�ހZ�����Oy"�!oBZ� �}��2� ���S�1�ʷW�`0�����~�Se.���i+�QѰ1Ox�j�x=[��;M�?�\�4�N\u�qv�qQDp�h?r�Rz��cSE�`�dkox��kH��Ҍ�5�Z�!��Z��֝�|g� #)?“$i��h�)+n( �ȵ��`�Dz�N��ѣ���.H���֕�o_(n�):��2�|�+���lp�[���`q�gJB�|�*��_� |�d(�R�=~�T8b��'7�9��KT�1\a�Y8�fM�I����K~�����Hts�z&��F>��&u�kf6�]���HZ4���d ��!0�����'�����9�_��48 ���W�_��҆��d����=}����`��[�&�x��ͦ=��u��&K����� p�����&�Et�%F�����#0���z��� ���u��}���q���׍6 |��X= ��n��� @#sN�@g����V|�k�']��U�J�MPZ���7*�(���xlssp�}���r�#)�-7�!�&���]���L�+�K��n
+#�b����P��j�B�Q�!i����V8�\��a��]ͫ� XM%�5q$�.�َ'����<<�����v>��f���y�������c����co�8ޔ)�:ʱjrg�7�g|��F��q�#�x�xB�?�B%\m^�J~�^�]��A!k#�V����bW>"�'�lnȪ�L��FU��),W�ԭ����k�&#Z��^�8C6h�\d�ݨ��Z��`z��A��br��A�l�1�d�'e���}Cd�bT�E*d?�N�^��kn��⧭I$0�$Y6�]ɱ�_u���"wznT؝em`��7aVr��r��Q��=K $H�w�� ������2�]=��elO>��R!�L�=z�j|�*�����,M8�L��f��1Bb�-��/M�D����I:��p�����'S���oG �:�R�������9<ל��F1Ib�r� �]ٍ�,�ʝ��&�HΖU�"3�+�*2�C\�@�AŒ�U��a��Ե.c[t+/������] RX7�m���ݷW�F9�X�Q� �;%T�9���l����+��i���<�� Zu�^�livQE���ˊ����;d��(��o�ͻ�2�tA�=�'&A��!*��+}.����X�4��j!���n��UW<w�TE�*�c�Λ�p�C�?�p |���!�c�8p��WT������Z�� PPƥ�z�k�-S���b�AF�ąL�)1Hn�[�؄�� L�� ���<�����>_M���>Nd�]�յ����"x��$�ӦQ}�cS���t��ݰ��cJ)�9�f���� fY���5�\J���+f�K��Л!B)7���$�d��,n�o�6�,��pO�'�:�Ђp���o�\�����p���.�()ɩ� ��)�{H݉F;�z�6� W6���c۱�)�)�8���~����BK����b�JNd8o��(��P
+l㡱U�����:��+�!�u�AzH�N�u>$h�ɖ��;!a��O%
+{@V�o�?H�Z��{Ҩ�?k��?��k�U���Q�tᬙ�Ii�u3[<W�ϙ|2X���a�9C�m�Z[����of �b.��p�A%� 㲈7B�9��l��t{[�����%.�v� �=+l���EE מ�Y�r��`-Ob�N9�_�U��f dyhnX��}�4�bA��C�����!�Q7Y�ޭlk���X�I,4U\;|Nj��d� �ر $�ƌ\�/�8'"LB%����D�9j�A�"��B߱ p�*��{��f ��~8�P����S0(S?�bT@`�1P���n�S�OC�&�e��y��t���^�i+�2�;�����/!7��Ƃe�V��� s\JnT�<XH��[�}-��[c*:�J%�0�$��UI�ݞ\4�v}SqQ:�"�#��|�^M,�|�Qz=|��b�v̨����3����v<�&���j�
+R���$���k9�pYy��LzG��
+�6�n����h�n��[��y/r(��_1n"j��ž~S�[T�C�bۙ+(n�2���o�7,a��'��vծ,_Ɩ�F,�)�[��"��+��<Z���,�оk�>���8;����=P�{�G�PcCմ� +�C#�A�4�V�e����ӗ����G��!�xt���d�2К��0 ����%�K/�N�b��v|��^)�]�9�@�����/imm+R�[�/��W�ǀ�p ��@M��ɵUն�b�\K-m@��q�Mg�4��8 ���QäQ+�����̹ ��.
+�S�=<����3�Ӌ-y�=�� ��d8�_K��*1~3G�ѹ8t���j9��Rd�����C�2%�iaBP�H�42<�VGC��� C�%�lߋ6�b�~�A>���g(��,����(6% ɻ�
+JOw�A��D�F�q_�$O FTaH�B�1ѹ�.�uv:�D�G����͎"��8�ۊ���4��F#�x�a�w9��r*��p]&b������Έa�u �� w:���d�Fq�b�?U� ?��4X����*�1%7��td ,9�neMb�2���+�������/��/�s��T�X�bH�U�ͯ� i��q꣒�,1�g;g���I� ��^�s�e��2mAY3��g��ۆ��y����^��lܚ'n�ǟ�Z��Ʌ�'�Ѽr��Q,ƶ������ -Ey�J��(�E��Tb���� �Ueu��b'�v2��y\�Ж]��ݼ�T�Q[��g����m�������6�&��.�YM.�rFE�\�!��w/�-t�նYp7�E��Ӽ�^W�>,��5�cr����g�~��Y�&�Z�s�+��@�g�k� E†����K���D��0��
+O<��|��y�.ыz?���#��k^�t�o�U�=�O%Hu^�;!��5�vX���_J�2�r0�I�-<��k�tca������z�t�����eֶ�m��t�˃�'��$�6�F %����Z�Յ��\��0%�C��U�i�������Y榟w�}Zzp��f�t��~�g�������hٖPw�G>%2 ���z�:�B���h����^�z�Y��-�6����@�~�3:]~G֜��o8�������2=�P���K�K��6�Q@*�A�{_/�C�2`�q���l�>8�N� %@��@,$��+l�`$��t�l���qW[z�e��5��`�`��۪_�%J8/�I��FA7������΁8�(\�I~O�j���ں�* [��[�v JL ���]-9����-F���R��/ k
+�8R��S�����@�8�X�m�2�7��:+�O��d�΅�-���w5�f����W���� k��'�� y��2K�J�Y��,����GG�<«<5HL��j�4|�{IEz���H�Pf�H�eOo�Fᯎd�Q�S&r��w
+���̓t�-�1�W�?;�֜h�[��y�����{���ی��A8g��dD_� ��[����P>Y��Z�/J����G �*��s+��i�J�%�$�s���v�� CT�N+�섕�ONb�c�pG�U����w�Ĥ��å�+G"��Re�Ϧ��#��]��[���mbI�(���>�v-�̈�,&�O��ʥK,�A|�iW^K��Q+����.�j��H��V ���=�j�!ƚ��� �e:���Cy撫�'�ؽ���u���j��!�w۠��>���u�o #Pf�e{B^o�~,������p�����O��vLqH�/e<C�!=X��n������uG� ��{D��0LqH" KQ޲%�3�3�6��U�ߞy����9&!R�Q����>c�r�r�N���*zJ�Xv^Iqۙ�l ��0q���۩�����J�|m�?�� ��q��P��(i ��Is�#�E��oR��Z7�HPP }h� ��hE�7J�y�O"��������ra�(��js�����c�Q�X,uR��x�������a4����%]2��t��-N&���TQ�8���!4�(Ρ]TqoL�Tb���_��g����;�{p��o�9����T����bS@<C��&5;)Fh������oS�Υ��*��q��0��`�`-�j:#X� �|X�Qo��[������狝����5H7�W�͋Z��i�$8{H/c᎚BI�r����#_2r�4s�:_��<b܏`ꄫ�9��-�빤uu;�߭� pK� �M��b��z��Q6�`I���a�� �ylh%��� ��·��X���x~�OR�Ҁ �����ݯ��=mȉ��g��db5��-6����bǝ��GZ�?j����8��r�Ԍ�]� z*22Q TM�-/t�w�^f4��Q�s-x��IE�:ri�|�,�߭b�ޓ����Gb����O ���5�����֍?�b��]��[_f;�'|�ƅ�+Q{w��;u��&aHmT=N{�ɼRכ�>�����K|��IqN�.�����յ=�|�#�Iv�8�Jt��� �X���X�Ldp�I�p�(K�&����Q�i x�)6D�ֽkl�U�& ��L9�����J�F�'�W(t����7�5H�T���|����(Mwɲ �Y�u>
+s�"o18�>�I���^�_n�%z�f�?�Դ%�S��N�oZ���Hc���L���������#Q�*�dщ�r�7�-0��rZ�*9Z�ދ���[&�M��<Qr �R>~BI6���=w�N�� ��Ӂo���vv�C���=���eA�_�ʞ�:M��m��=�=���?p+P���7JC�.�;V�� |ۤ�38���������h��`Y����*t�H�HI��R��&���DH�݌�3S8��CE�cd\v.��=V+��䆋K7�L�~�j���\�\nۀZvԋ��,�d��U���r�7�k��P��=�毣��|���.�MT��Y�������;$���!��$��6g{.]�ݒ� % ��P�6ɒ2�=:��Q�s>��������,�@�}�uۢ{|���H ��Q���F�;l��6�=u9�r<Nϻ���GA� �� ���_���eQщ���>����<.��O|��՜�� ����Ҩگ��t���!����������Ms��Xxv�D��}6Em�T�>��s�t��>�e_�����i;Z� �t�#�o�E��e�e�`��}%҅�V�C��̹Q�5B;R���x������������ ���Zc�E�;�[�LN.o^��h!:����!Qz�iW���$/���
+|"u����<��Vu�N��$<0�~R�uk�"��T�Z<�K�����E�(�o�f<\���j[��V�AV��-1 O\�%/�����1K�r���B��Р���8|%�y��� ��a���AF[V"���Q��w����F-���w�k�f hч䜰�s�Z�\��^��H���q��~ g ��]*��w�����[iy�TҪҢam>|���1Uּ�5`O�)`��M�j�-%~�G0��k������ecb;Ʋ3���I�{%���<�/q��X��p����/�����w���y1]K Bb���%���J�*()���c��-i���(�����β�P�BW�ժ�#�ٗ��'�l�  4�r��g�r���������D9��o� �0����������<��~h���CD����̍��z��M�߯\<��y@hI+���j�fb�e�v��a$��׆��R�XQA�4y,c�V:[�醨d�f�u߈�����F��*0(̒@?^ # �[��(�~Y�wQ % }�~��� w˼W�{�否����c��|��`����o�А�9�����g7P� ^טQ��04k�v��dϙ�5w�x|�-��0O{�ZUjZ7� gAY��ģ�hZ�K\r3ni&Z���|���5a�G��nT�SmTHo8~��Op��.���=���=]�zN�����,ŭ�͋;&����l퍐<��ϸ��q�����U6�� )�ߜ����`&x6��b�&3˵��T��Ϡޖ���0��9;�aݚ�%�Dj��4J�b���7(���}cUz�m���q�]�b��,�ҏI�������a"��„��x�����W��A[Y�]�=�����D�$��V�WMN��� � FY�{�q�s0�hPi}��#���6#�6�`-#�SxgБ�h♑�Fw�8񥴇�Z�nk�n��^�o���V�^��\ m ϯ��0W�?��?ܹ�<1�",��I�:��ݺ�m7�)���_�&�E��A����ϴ�*�&�n���Df�:�h$�8���:P2�I��B�Z�����(�40O�4�y�t���+p׼ĉ���w�t*��/�s�u2�5T�� jՋ�l:�yԐ�0X)Q��˜��%{U�ܿ�GKj[Q;q;��"�>��4;�į�َ�PD�"�s�+!b��\}�$�|�˻٫�L��q�k�nb�^ ��l�R>R6�Q��%yp�/��p���T5�(F�]rHx�����C����^e� �S$ �`[ex��W�*�s*�Hy�3�����W\� @��C�
+c�!�Wkb.lv`YX��]�z��rka� ���_4�3��U��u��K��C�خ�o|��TCbt�f ���2A-r��* �`?b��HE��ySI���'i@3 �;6*�
+��}=��Ǿ��Y]�I����y�\����*�K�J�V^yOl�R�-�F�<F�\�Ey����c+�O��Y��'�q^���ZTsS��>�?s��NDrcB�ɳ��3�%���Z�ق��9��t����aj���Yu�4�p�PQ�MF��v���yY�����1��q�8�30��^i�����
+�.��)�
+\Cd�N��&I�K��� �eg~�Q�u��C�O&8Z1�3A���h��q���N6�š�N�ܧ�FƉ+���_�RS����p���n��� 1�R_���Bc�@��0;��f�_��͓o2˭�x� 6Vu�d~ ��w[� ���N�֞`k�C���Ղ�DžО���?3 ��B0�_�lX��V~�k�p<�ϙ�������aE�%g*R5���4�vyǞ�������{�� 5�ol�Be�讈���vN����h���={�τ;�K�,hq�'���m�=�&|�9�fIL|�PA�;��G��Ov�m;e�q{ls_�rSV�xL=�l%�L]⬂�lvn� H�g3gN(3�V@n��� �w�J��Y^} ޞ�lG�{`�_�������țx�b^� ��� L�n�\�~n�F�����{Æ��U�m�w%IN[@Q��k�=�g�?����9���h���eEv2���uF(���r.�(j�B��7oû7�ݚ�1�&8K��L�}l����g\���+4R���(�H�0%��}~87�<�gu�UQ�� ��������&*�0��w���Uvl7~�� �=c�{-
+m3��:�}�0�v�W$B�'�8�7+�0����*��0�x�6��[W� ȟ{�W� �e{q���T�'R�r&�q��[�Y�;���Q7}�����yM;8��b�\D���u�,#.���r7�1g����n_f 1�μmE��ϫ~�<��i����5x:����@�#Ř�|�U�88\s���o�_�((p��9��� �����x 9^��,����j�Y���D��|E�XV��Q#��ֶ�p_���r78^� �"�(h�QZM���yQ�t�O���j���(��%ˢ���q(�ա�Y�_y�06~o�� 1�02��*L�˾=��dK\���wO���1L���lM�l늆]����#��I{�T��۴*xm�!�ﺽ����$�"l��M�e�~������۰ *��oG�H����� �����<�l8%`���u��eOй��� �'�`ggv j�k7"��C\���-���l��';��<�G̭����*�����R _=FT�����CT�/�+�1�W�������$>9������腊�b�CɊ����3�s�_39uu�����1^5���'m�������_�O`�n�|u��i~5�?��-6��8������17��,���(2�*]�@��17�϶��-���Uiq>�^C�t[WS���ZK+S_�XRSuSS6lq�_@ 1w����J��lvgM�o&Nq1D�;z�rAɢT��Z�CTIG�Ra� �
+1�I����מd0�]�1��}r��>����T������g��5Rp3�t���䌛�������w ��!VM��?i� D?/���{Su� �$[�kl$O��#�D�+��Q�--�hv ����L��#� !�[� �}i��]�����
+�%�N̆E��T?�]0�h*%���tF�C�Xw�C�g�R�t���w%�L�4OH)���C�Xec�?vٹ�f���� s�Ǔ(�����>�d�?^��q�G��:ODg*�7�Cs���n�{�o�'����f�"�u�ߠ �~67�]�^! 8�Zs&b'���V���yܣ�d�χR�éOD��X�k�M�>�� y�Ei֞y� �͹�C�+�i�Cv� ����[8�W�ѽzo�c��3�g5!�jc��[<;�c0H�6��xA��Q������0t�� ��4�Rw�]�ſ���9���y�l����Щ e��ȋ�~)څ8�_��2��L�z�n�VHi��'���?B�k��n5���@�ŗp(�x�� ]����pa����=��?@Vk7Ia2v��,�.Y��<9�Ւ�8a����&�
+�8
+�v�s����O���;�Z!$�L!���Tɕ�s�e����-�L9���:��HG� ��B�X���b��5@��8�+����}�e�W�]�Y �+%�xW_�}�đV�8 ��&�EP��Y��a�'67G���@���Y�󔰏��Ī�J)VKs7��yz�ց���`����������HB�ƙ����}z�1�zEo2�bC��Z�4%$��ч�}�׾1���Δ�xq]�ŚS��Z�~?q� a�����.O|
+-�'}�q�>+��r� ��V����+��$3�%ї����r̳n�a���k�IԜY�e�c����!`�m&ބ�ҾGUBd"����@�ݴ����jZo��,mrԥ 戋ʨU���f@?\���L#�I��0����H�2�G�I�q�kϵ���8��ϯA=�ܢk|�-�1�Rܸ<�m�h��e�AY�d_<V��
+|���e��22���yj��=�C��M�P��IJ��2:�C�X}�p�x&�Y����q@Ɨk��w��9� d��S���}��!N���N ��w*B�A��<'�͔���P��3���c�t��7�Lu���ϵ�Lw�їR2FB��1F�S�ˡ u>��(�Yu<߉��k[�})��o�U��C��7�k6���F+[�n��{�̤�e�){����w�"^ʠe-�y:��O�S���]���$=m��E,S��c�gw?҅KH������V��C�+�1X x�G�5`��@l�O�J)����қ�j�d�I$j�J"�#��OC�Y{�"8��ŝ�|���܋�(�Ύ߾5�Qr���e�zB��Q�Q:�TH[�)j�]�C�8ĩm���}���@�i�4J�.�3 ��"���V�Va] ~�����Ζ�Z�Q{Y�cI
+x
+�� �]���h2q�<˥@%Ꮠ�;J�ǁi�r�bY��Y�
+���k�H /E�� �"����y����T9|�C�Pȯl�݉����%��S�3K"�L{�U�Y�䊱��ĵ�Q��� ���++e���R4CD�$�xh��TsVJ3�4
+�Sfy��f��c�/�?�S~w˫��Pӟ63��B/�d�b�=#�V� ���%A�9G���l Ձ�� J���,���xn[�蛅��rh��l�����0�g&���X����D�b,���u%O����b��&$v[�i\���3�Y3)�N�~���b��\$gV��4�7�������YVF�t�5-�Y�]o �P"D��qU��!�ڝC���;�����R���w��e�wR���U �� �*�c�K���y�����9[�5��[�Z��@��-v��V�rΟ^���5�$�����2Ni �R�?@ՙ�fO]�a���Ds��~���V Dlito���!>|H����\g�.�ֹ+��q�ZtW�B�Q���l��,nu� D��哰�S�tq���$��L-�W�S��0H�Ж�M�w��4�-���!��~O�~�54��X������z)�:l�.�v��G�P�?��<�#N�"�R�e3�p��9�͒s��m��{�Y�ȩ�Eu��2�G>���(�ټ�` �b�T��X
+d~�N2?�eE_?:F�#Q�SM%dᢗuڧCӟy�8D6��`�,�6 t�D�s��}Ҽ��%
+�
+��|�{��N'ey��r���*X��;p��~�~A���7��Sa�qֲ�!�[B��YFKĨ`��`Ì���_M旱j�c� FH� ��K".$�M�;��nH�ǧ�#�I��y�yw���-�b��2�!C���ٖ�����ٍ�s�t!,2w%����%:4}��Ό6x'�,G��s7H�r�!=���'�>�UqHk�׿���m�I�E2�ְ���-�����\VQ Pf�AD���^)��"�1��l8ira�6y(�b]��#�+9 ��)�l\�y�2(��g��"{ v�ITi�T��H�ws*�|e����=Pn���� ��7`�HY���ʔw�;0L� �z��tH��5�?��t�n� Ju��hN H����ْ�BQN��U�nf#&U%��Ga������-8?�e� ϟX��
+��b��z�"W6���Pi~g�xڣT�e��16;����͈�K�=*���:STf�F�t/_����[�@�q���ۊ ��B�I�V�f�l0��0V! ����HH H�[�z����a��%;9������[����+�`.��e���Zx��Pn�)HCVM�^kQ��e��7O*��.���л�Ü �h�Nf=+�:3��y�ƙ;�ߑ����hW���+����&�a���Y���c�a�q�z<i׬�\�&a����y����� �#���^ ���o�*b���`��[u�g���nj��/����K��1��]W0�� ��'�eH��?�-�b�9�攒�m�TXǂ����@�O��E���W[���9�L��`�/G��*�W�l��8�5�\����+!)��4�a��Z7�}#���z�����[����-�ڴ���s��`�m��'�d���k�'��K�6ʞ���yL<�����[Z)���sZ�c�jA#M�ִ���j���Eh�q�b4�؝Q/dB�[� dKy �m��"͔{r1E 1>��'I������P6֋��� WK?��`��v,l��:*���Bj�t���I���L\vV�� �6���M�O�D�_ _|�gQ�0�"���0�������t���ܦ��э��7��7Tf��v���f������������g@�`��Z��k��bX8ðJK��V'A]��Mےwؘ��qz䡙�ȎM�l���,(>�f�>�  p����n�u�
+9�� ��;\�_9�B�wR�`���tjyH��/~�$������D�`�of�O�4�ܴN �l�A;1x�)���
+�H9�E�T� ����A���e�³+g��������Zͥ(�`s5�DMp���o6�Sh����BU
+ o�~����41�~WF0,f�$�%��_o��;�xb -�R]���*f�'�{͍�t?�'-�s�63�8l �VpT隇�0������TZC��s7JC�q��~����Y�jJq����U�"��X�2���w�Z"D5�Os��O���H��%�Y�����p�լ��?��T�,{�hw���K���qΨ=��w�n O����9Z�#8 ֆ9{����)3 ���ܦ�)��4W�#����1�O�[x�"�V���;Y�����hk\P�����K%�޿�K������P�k�n�z;k�?|4�~=�2��1!����.`}�������ǧ�տ_�e��z�5�$��S5�~�lo^��%�I���$�L�A��*����qAZ s���^���Jf�)}w�������Ҏ{-*i�0���XKj+�g��\0�f��1�U�+��J��46͍��~gJ:���w=YT���Q�::uJT� FM}� �<���a��>8��w��b�N.3b�x�i6#Rp �����(��- 3i\ץ�+c��M�.�f�� �d���ٕ�$��K�)��b�����Z���`x9�&���t���ľ ӂ��0u9��q��=�� #�#�_kb{c��A�h�Bv��ļ ;s����1�I%������4�kZxY���ձ��Ut��)v>,=�Ii�(F�E��.b���m{b� �!`���aJX��#
+ ��;��z��_Ne�3��9�e�D8>��3��LI���c^-D�C4�\�А^�d� �c� `���ʨ&&��n\h{��֡���a- A1����c���g��$7E��'au�U�ꩵ��}D07n��Z����,��R۩�Q"#5��P ��=�ي9^KY��i �|�ڀI��� ��Q_N��S�i0�Dc(��m�m�(�+�RY#�����l�Z��K�;Y I����Z�i�~�ߨ D�?@�M�4��<`3 1�O���TN]�-�G�[ov&_j��TA���P�r�m"6���Bܳ�j��@K��W5v���a I�_�Zm�K��V'�N���>�d]��z��?W%r������9P�K- h>ފF�~�J�!������lf�?a�A�!�&��1 �wH����R�nR��10�|�Zq�����2����z)P8����F��*2,��H��+�K����yg��qq@y���X� ��]m�E�1. ��+S��;qح.[
+�Xx��q�6Y� ����9)� 6'�C���tivӫa���O�b㱍����zw�tM���M�>r���ܽ�@O����P��`�lq'Ӥ����s�:j\E3 Kd_O�rړ�����6=Q��'���>��&�,Ϙ8(r� �f�~��<���g|YM�Z` �L#\�h�v����W�s��;ݤTK?��wJ��q�[Wh��X,����Aԏ]�����'q�M�(]�u��VF�ZHH#8���4r����=��ƍ�׬˶�wrv/�KJ
+�E��b�����^9�G�3U��W�n��z�Ȝ�k�Fp�m
+�Rt
+p뎚&����F+(��6�x �7Ĝ8q� M�,��s��eaB���FR������:���H�]�Y���)6�^� �'P����R�
+m]b�������j����U��O��zu1�&R‚w1�.u;�t{��Q�#�z(ђ�a�9h���h��_�
+G�#�r���b�aT\! ��+{�윾�"Q�y��2k��$��d��a�\3LV�%�&] /KM=kvR��B�s�A:q@Yr���>��Y�|:�4Cq�j��X�=��-�;�GV���� �N�G ��W%w<m7LK��5t>hg"�籆#�����.�!Cw'֣i"�7���:����C��;�f8����I�Q�w=�Bi����]*{U��Jc��ht��~�S\|��N�yN1�PD��`��g�s�U���tzpn/s�ўfP/gP����q���ׄ���w]^�=�%gΤe�ƌ<����B;����H��]5R�J O�G"��X��1TO���(�(1r�|�-H�R!�
+��}�)��%���!�&·X�3x +� ��P�Hqo%s�;�*^�F9!g;y���S���T=��_�E9_�6�01��c����J-�,R�߾vl�{f�G›xP� ��%$-H�J1gW6�S���>k��a���;�����T�?�P'�Ko��5�]���;�gT�ˤV�h正����0|�0@@�w�J�TAR�ynH�f�x 8��zٵgP����V���wR:|��t~�{�-3$]�|���o��z��硃����@zT�1����0Ͻ6VL1����j��- ��z*�贮G0�H�Z���{�\��+iAD���g��#��%n�eM�c��2QWv-���9mtP\?g�$_���G�x�
+[_9��U��b��+�D!�1<����a�� ��:-9����v�|��
+�!�ߺw@�3O��F���PK�3 5!�y[$��A2��/��%�u�"˪|��ắӂg ��\��w��m�e2�'K��A"{-4�quS�y��8�!c��C#:4Ƿ�*�z���=T� �u�nL�²�� n'b �A�����/a�Hȓ>)����;C�@.� �'"�>]$RM0]�Zw��>+�Q�J�nȆ����x]�����OXi�������J��)��7����{ε�hk��z�o8Ð�HF]�{9���0�!���v4���,QW�"iqT��5�?ydL��3 ��Hn|��`��؇����ex�?����b�������p���I�E����E���W��c�s��5?�|kE]���?�Z��1�"�]ǠF)�ȧ�I�J�����\L��S⽤�꾄T.�dMd�vv�c������yW� C��8E��SeU>e �B�D���,V��z��UJ�zzm�c�CPW�I�����&�;�/N9��#z�������g� �֨L�X$s'\��>9$5���� ��-PA,JTV#��u�H�0ܺ�+�2��}PM.D��Q�ws�.�Ÿ����V��vvg9��|�H��k�Р.-4ga��)^15�� A�Yj�ư��[�}$�/��]^%��T0B�z���'�~='��R|l����A�]W�Ľa(E���2��W��L$¥M�M�O��}˵���ת�q��b�tnh7J)�ʬ�x ڳ����O�dF���S�!H���|�5ZAsb�B�l j������N�pX�^3��Ѹ��F�|�9]�V���|(��x:����C���SZ�Akj�KCD��}�1�W���A�F�X9<M�hh�uJ�\+r��\�~X����vm��+׍y���(4�U���`\O�4�e��?��.�@U�}1uܔ�:��1vh0��^!VNj|����
+,O����~��_k����|曹 ��៦E*ԴC��<҆Bνq�������ސS�DK�̿�>�����Չ��EشT��&�Y�<�x�s��
+�"�I��+�& ��@�N�͢*?�Hv�]� �M���"�|l�}.�K|P�0��M-�){��*���0��|�C� ���f{U�9�:�Y�������@�T*!����9�$ً�E��I/�<�ty��M]jK���� Pe[�_H;8q��x~7�Y���WS��- � I��b��/��@%�9id��������.���c�}�c�������,ɢ�]`k�e�62L�� �m��O���i4h��}�ĉCJ�ΐ�e4��u�g�yN]����̘>���#[l���"#�}� ���r��I��V�q�4=r,Vhܠɭ�p}�aG ��'3Ƨ������_h7ҽ�/hO�V ����z\z�n_�Ah���N�p˥�2g�K�V���$�b,�E��"I3 �8���@�/H4�j"�s.
+���T��1"�QV#�:O(12����/Hu�db�4�Gj`� ��;�F*S- o俄��xه�R]����1��q����xPD�n6q���,�e\��N\�D ߎ`d�o�xҐ嫋-��V98zYSdO����P�_�i��j˿����� �ԧ�{Z*^�e��Isno�԰�p�$�'�BS�A�2������ghWW��4z�IJ��Ȫ��f ��̓T��]H�Z+y�+bVSL�'�9�Ѭ�s �ˁ�Cѹe�q�1�}���}�l*O�V� ���΢��+ �h����>y��5C>���v�ML)D��h�1���� o���`Vp��^4��[�ۀvwS䝏44ڪަWujX��W�&(N|�\E����4TX-\��9�8��RЀ]4�P�?��vy�V��&e���yu�,�"(�r�R����r�ۗ��E����{ٽ���z}���DA�!�����v >~����ˑN�����s%b��4TD�#���\��-jظ0+�so�R�dkL�h�a�K���L<�6?�7�%���R�P��ZC��\ր[i���&,_�+|��i�qp""' ������o�; !� -��EI8J�[�A45D����խI��`���ٱ��&ޕ|�l��K�"���`�a��WN뇇�]��nwWN�xL�.�r�x\l��E��߉��������>��51GAl'���&�䶔A9�ڄp�EZ�޼�<O��sU7��S!��%�M9�� U/�bd�թs74�vps1�;�L�z�-ƹP�d�@P4�s��4���;��q��N�"Lzh��{!�*�(c >��z���F�v�px���Z��Nzvm]�3�b�I/�\&ߍ.�z���L��=L2�'�N��$���P���.����u7(!(��R�Φ���6���Ĕ!� ��&�4 "Onː"B�r�ؕ��r�,���q~�,�PUj�}�l�Ц9�I�4�R�~��X�L; 嚴� ���Q�@Pz�ț�+)F��M��h�ڰ7��хJ���Y��w�P\���>���C�X6�KAxB�Z��_I@b��m�c��^���Y+򎵿L?��c�����˜=Ak��5" ���4h�c� 56KP6 ���׏S(�W�R��Aw��\�@y����+w���M^���8L��N�o:������*;#�/���� ?y��-!����� w_�Wzpc%z�h5���A0y��o�41�4�K�O�K�{�'��kzU�_�r��R��{I�T��>W`Jt�l�v\���Nʓ着�'��Ya�ʀ ���3�}+(/7�V1�U�=���{i���n�5������n��۳ t�[�+�|�H��;*��k]���A� �Gê����Һ�N�$߼��AUn��QC�+��l�\�� 0ݨ��U�=&�{+�,�gDأYYV���J�#���o2z���Ad!/Y�v𹯊I>8{�l�>�{1�Lҙ� 'w5f���&�SR^�B`�ӿkP��v�P#`��ªW!MI�tB������3��<�A��#�ƀ@�s_d����S����A�Y2�WR¨�}���x� @r�63����:@F����yd���` LƈI�%�� 6X��;`PTE;��LO�w��`Բ�4O�Q��%�9���~���1Q ��W7���G� -N�Oю3�YG�zËA���^���>��|�3Gdz��B�'ij"��XO� ���d��t�ī���a�>s��юh*KQu�>�n�M��1��ڒ�ݱ��u��V=� �s�
+HY`�EN�پ�t�聳}��4�P��g�;���n���y�.����R�9U%�y:<��I!^���U�����oiN9H�]4Gg�,Ҙ�Ga�]�^��X�#-@�;�/�z�ي=�Ǹ����Ұ��Dž����(p���a��6�_A��}l������������7i����ouy��do�4��+,%���2�TB�ʶK�#n�xh��-��}N���&�'
+�aX�߻�/̙�!��_�}�KIF���ͮk�X{\�`��}ט�g>(������׾�'��(|�j�i%�]a�5�r*���z!�'s�B�l��8�ؔQ���}��m-JD|�yG���AU%�\'��&����o��"�\=�nx?�KQ���w�N;�:��H9�� �q<�X_��� ��a
+Ֆ�QlK}���}}?p ۬��
+cQ@4��1cg�xW�&�"�ˀq�,�Pȥ���ݯ�V��x�AB��=�y���N�!0�?�����m����5��/���]��7XX�F��~WTut?�|>��G�XsŌA�5L�Y�� ���]+3�(Z��-��ZX�Q�"��R�7�y��$p�����=�� ���e�he'�
+T����ϫ�?ԁ9�&^��=���'7Qv���%����4�X%� \o��V=�6�7W���h�C2z෬����o9�Qg�U�d���1Wo)��Ǩ��<��)D�c/Q� �m&�"pݼ��d�-��,6�co,rp��1g��y �{������1�^(�pd��~iօ����<�UV0x�7�+��8"�9A-���ˆ7F�69Y�~d�e8�8u���Y���fBjЎ1
+�� 2�iI�Ιz-4rp*u�tm�+G�<�eX�1]�=r�@燶�[�q�R�B���daemG�vs#��M3s�p!Ɏ ��gmrB�Ѝ>�vdo�����ǿ�"ҏ)��H�t8���S�`0�G�q����`�iM�z��T���FD[��Gc�)�X�-�o�����v%�jcJ�]�.��F�#�h�~����z�ڜq�«^��c'���K抑����@�e*�_d���n�N<s>У�7㖍��k`h�F��+<0˛�.�1 ؞��G���ǺR�s���]n��GJ�sY��U � $�*��4V��"�����]"W�y@�-��aJI�,i�?IB�&�]��Lj�+��9�]���q.����A�*mseP�U|�������||�H�4�2��D\}�����Œ1����W����A蓔FXxin����,���<"�t� �.��:�Jn:p�p_�]���0�s=� �L�6ai�o�� �����6�J+�����]?D��΁�:{(��K�� #�*��{���?�Z��p��9����d�Wj���1 Gjqn��z
+h|��*��fO<�c#��JH����+MY��:��Z���qA���j��E��Al��n����j��B�a��zs� �;oj�Da�l�x1��Q�=㗙^�������R��5 T���-8輠�i��6�U�������?�[���/��Q����tG�XgF���V���}�_<�]�ng�u�LO��i:��Y��9s��QX�ί�zp����R��e%��_ -�ys�­E�M��#fF��=%M2���@�E ��]�F�Id�e�@��x�}���Z �#K{OE�i���lϞM��0$���o��M-#��'*� k�yy�r�
+H���"�J�G��%U�}a���������I�%��/���»�B��]��eM���>X󌁛�K��Fj�ml,+xo6a�4f9����� �}5(a G��<P����3�*Ȼ|z�h��'4�C��w���7� 
+\��ЛԴ�r�Yz?����72��j���pфT7����<(Q���zVY( ۀ;�����u�E�D��u�%4�3F�����ao٧/��-V ��//�g�!-��VX/33�����Dm��M��%�%�2tES04�#��oǴ@懘u�%�Zx��Ǧ5��.C��D�o����~����ț��p��[����Ȥg&�P�|̋M�WI�P�p�4g���!� l&����V�#�[� �la2|y73�h�� ..�6���xD� aͽo� G[�
+b����-<�v��bN�g�r�0dv��U�����_�Xidű�$��BΎ����Ԓh<�Sӏ`4�������g��3S�9�#���2\>ށ�_/�`���q��1� ����n�wLa�~�:�>��_
+C�g8��j�Ȯ�&]�3�b Г�̸��"D02jJ7[�A�K�/H]�~����p*@J&?��5T��³�Db�F�88RwrȺC�?bׄu��.�ٌH�('I�q�F��a@��,
+���o㡏�j�+�M��@K���X�<���ԶmOܳ� {wa������ ��?��U-�L���/e�}��?�{Ŗ��8�c�A�S�e�h{��F�s]�7�CآJ޹�e�Hp��=tb�V�{]�8l�C��fd��d�An��"��_����Li��m��i�r�F�7mV�Ց\�N4*�����}|�X����6� q�8�Ǥ.I��[0U��g�N�v�1�'��I�׏���"���Ɔ��/��Q %��#�@~��N����2 y�?^�٣hO=�1�x|\5�y�YR��C�N6 �Deq�Z�vMT�Kp��5���2^�֓�.;�^R��Tᠷn�l:C 2\�xr����:��G�(�3����
+f UD��3�Kge���e#�e���X���ѧ�.󴭐2Ǫ�R
+̈́2��T�^��᚛ց� ��Y����8�tE����-=&^�w�Gl�0�k��TL.�IAAbAݠ�;�����Z��~*MBC�>\���wX���֐|�z�eh�H�����}��.�3������,˜� !1ï4��p��!p�0Y�;I�p�����e51 ��j����_p� ;z �����O�Q�r��HOINJrKȄ]ġvx���� N��F+c���I`Pz�M���,��V�:� �O�ɜ ��}e��8�_g��ƦMmR��ع�k�4oe0ӏ�T,�;R���}���q)��3��K��ʈ>s�&ڱ��!GΖ�r��C��Begb�u��"��k�/2iX��n&���H��oNε��uH6Ýb ��h#����VŶ`Y�z���q�kW������� /���X��|���F�;�oh:x�f�0�Þ��2hB�i�_65g���,���}⠫TK� ���V��8x��F@Z.�cj��%�����,vJ+ڳ���� �71" � �!h���.�� NSz~x��D ���f�i ����;�m;���1���O.4яq��e���ۻB3�?�gէ���������졀�%ȵ��s�6,&H����E���t#%3Y K�t���P\�[ 왺� ��0���Y2k�Ƣ������)@�d ���TUʠ�b���P6X��Ӳ����fš�CY�%���cc�E��R������=�����q�X����0����%n��(��D��գ�z�Y�d����G��] ��ٚ�Ɠ�����9z�I H�G5�0�5E�^���e-���"x���Wʖ:��%<j���-8a ~{k��KY";��w�o�P��̆�/_)�o�}�7v�T �_�n��]M�ǥ���t�w�翆z����]��߾0�ca<���a�ٲ#����4�����X�Q���WC�Vf1BQ X� 8I���(� ��r~��*Y����ΐ̈yU����\��J���b��4���+˼�kb>��b-!���p�~um�U�2����2VHv{\�p�L��)B��U�%R�D7������Q��j�# ��8���,}x*���Ť��tn�O�؁6�n��d]���9�|��j��� T��\�h��*�ݦ
+a��* ;�p�>k}[+�К���m��9Ƽ��06ba��LV0�x�O� F�)���u�x^�ڬ�g��e�� �u� ��6��K2&]� ��9��1�}��҆g���R��5e�%#&#'}J��vU�Q������0�4��o-(��!.�pmW��zj�t��+W�����^f�n����f�z�aj>LJ(L.��.(B����;�Q��Ϡ%��@E��������{R2�l6�AfٗR�[/t����25@�S*p��p >˪���pa��ݵI��Fg`����x����Ɨu�0r =K� `u@�EPo��� �fNwy^h���,o-NOg+RC�}O���W�A�8Ўp��6��@$Έ?�w"ۡ��cJ���N`�N���ѻ2axY���*x��߃��#)4�+N�(ɢ���K��� ;���Ɖ�e�����d�(��bu�Չ�:�|s���f�S�T�EG{�#�c]7A��D��,�6�����|M��*����]l�KOv��x��~�һ�
+."�k�l���[\-���d�|(�m;
+Eemmp�0��L�T=l�u�+��#����}�u�y��m�ݏ�M������?� �5��D�ߋ!��$K{�B'5�I��e����?��W���h�o�_=��x~SQ���j%2 5����_t�,�p���
+m�01�tt�8��QlV��S����\����S1� ��1 =hŔQs9�'K��e���(޺>c�9?����5D�����j\�-�,�M�2��Ȑ�`Vm����g2(0Ȃ��B�mp�K�Xf�t�,cxָf�\z_@.�&�X:Ctg�&���T��I�B�qϐ)su���Q��]d\P�DG�_��$��7t�Ѐ,'0��r�ZWR�d�M*������j��i%��(I��E�aO2���#r9��Мxp~OY�,����S���{���{�l\���Cs �km��D�Q��E�#�\���NM�5����Q7��k,X�^���2w����u�@�R5���#���hn�y��Œ��Jiz��}�8�V��b)'Ὶ��9���P��f��<���7��߄M�x!�j6?N��Y?g���+�X,,l$�t/d՚{V4����#�<?GSe���b���� kt!�-fJE���L
+��ߡ�*j��:c������O�ʇV]�F��D��|G*5 +�.��)M���R[��fB����+����VU�cѼ�g�S[�!�aP�s� wO*N�6î %���l�4�t�[&������X�
+5"2�I�^�ou�}��������i�$�3���D(�^(���)Ý� ��R-?Kb�9�����2�+D�� ����[��l���0��2�c���0����$�L-�>n���a��X��E/�\d-��}F��ox��F��>��&�р�3/��bo�X�1=�����QH�L����A�ZԠ��B1 ����_K �<��`�Nf����_��Rc
+4w��������>ãBy���l4^�g��$�ճc+*�{^f��
+F ���'�����˹��أ�x�9��ֱ��gK�*���ϐp��n0o������`c�A����� @�>��>Jv�� �M;�R�K"�`�ܢg[D�� �{�ӄ3�iD8 倅��h&IM���}��$y����t������z� �`2hqI{R�����hĕ����� �~V]�\A���u,��[�S��pTD/�l~u% s%�q[˳�. ��"�bDm<;�D��`��!�;!���#��:���XN;���Zn��^�Ra`�g]P�R���k�Ԝ�=�}�����Q[�ϊ�o�`I2��MPip��S��i�Կ�����†Cs����Ƃ]H�0�+{K�S�A �۔�����8�_m���I �GoO��i���~�=�Ůo����¨�}f���H��s .I �.�뫮A+� C� ��k��{�)�1�Q7�@�1��\�f�]X��I�u�n��� �.�s�5GOc�J�
+���)��d=�H.c+T('5?җ�cIi7T�G�OX����,���9l�賎���b7��IG��̃O���c���6�Ҵ�i�"
+DX�[VD����!B��;��~�� HK��c� �º��JGѤ�!�7�u�<jObq$�i^�Ã�;����!%^��oH���y��7L'�����O.9:So���������GҼ�O����:�Ikz2q�K�“.�������!���m0���X\6z]��9ս�`����d���t4zt̓iH�c��"l�Z����\'�r�����*�66�1I���NA�&�ĖN�d����]�ťX&,�~����Vh��`H5�cj�y̌�3�-�5~"����K����̿��|0eg]ϑI�񭯸\ �w�G����mb�7����.}l�x��@F�r�x�Y�jp\��L��#��������v����=@�V-��X��h�B�O���ɱ~ÿ�;i3�YQ}�^��PWN�Ԫ�v����|��+n�����md��9��+�T����.�ʈ�2SKR"w�s��>�i��`��*��>�7��i<�*�go��X��K9�'Bl�� 皋<�j��i BZ5���0�q'�b�.�2�� ��0��K$J�zև��C�Z5R���7e'����CrY�i0M��k�.� �^��ZE�8V���V���f�� r��R�yʒ5�w��4�e2Y��Z��B��*Ąw�t�ָ�
+?ʱ���@d��N�1���TÞ<�Vű&}��t8���f��\, �.Բ�����f���Ӽr�'(I�f���I2='X����r��5�6V/%�*U�����&+g5�f�~��/7�•klE�t�K�3$kק�U��d\�ӟňǿ~�[�,�.U�|y�����]A7|�K�g�.e�6�#�w^]=�8/ƾ�蠆kS^Š�h �e7�����+��f�P����kAS��Ba�~�ɓ!���4��v�#�w�o����c�pI�~�0�N��Ց^H�xY�xl��:, ���+Ǣ1��#6�r�xd����c ���r.~�l�����ղ�M���81�*��RuعzQL��� �N55�j�& *}X)��,�i�N�qU��}>�<������� �e�mD�X�:�Gh]%;U�yfnCb�=���Y����]����d�%Uu ����m:k��W#?J���x�� ���̀)u^�ȥ}��F`uSQX���Q�䯀�F}�d��7����!ōT&�Z ����O��BzT���=��H��0A��衊����ޮU�k��{�̗-��D�݃�a~�c"O��ЌZ&��ުUU��g�cN�$�����G.�^D\�Y��j�R�t3�E�������3��by:Cz��B�E,�=t }hx�� >�4�)Jb*�pi�H�Kd̝چ��2���W-&�.�x]=/< �qފUJ񨓅I�kb��������p{���|� �aP����C�ʦw��W�����F^4+K����d��}�H�5G�ҕ�����/1�D��΅w��e`]34QP�/��6#�R���_'�0#6w" b�~8�����V�9�1ƣ�F��m]g�멜)g �)+|GP�@e<���u���^<�^���� a�!�Ϩ��>�ޞ�S_�V�cQ�
+Q^T5SRW�Q`��ǍqxN�0.9e�Jb���&���@'��T�V1�-;>v�xz_�m!MД�0�6�:"�Y�]�%�@%��R�g��_"�U� $�{�,,��<��&�"\>���� z��?W?�L�:R�+�O���������a���Ǵ>Dq��셢f���C�|���Rz�� 2F��� ;AT�L9��"���Y>�hɴ��,;��l���@>��WR*�-?��x�#�k�XP�i p�є�MtR�Z)å�Gt�I�<�eWP �h� /=��Gl��N�{�w�g�3��"X�\��ʞ#�f���2lB19���<��� BD���A�@������7(1m�,� ����j�����I�X�*W�������!R������ގ�%�qi��>>l憈���t�i�6
+�/B�ё����juy1�MH�=�8�����t�֏�:�.����q+ ��pw��e��t��F� �3�u��m�$��ao88@��⑛�:G��{��i��AϞq�C7!"��_k�6��Eha��x���u�탟��5s�p��r�� �] �qp����E���'P9�en��� #܀l&<�f���'�Ӡɶ�vj#>c�
+�AQuە���<Y1q�T��Bz�����I1��M�x{U�n��n�?�H�P]��N4> �(�\/�g��g>���b�I�j�t��Co>�����4]fބ��drM�-�O]�L>���Z�'6�(P��Iu�cȠ��hf:�ÏTu`iֻ܍��n:�� �9�\�8/K�d�\:�X�whN�)�h,�zh 9�J�{i����ɑ�,{bѵ�җK�k��xF/���YU�Q5Q�Fx�Wkab��N�r�vw�����qN��˲G��=���
+�a���������(@� a�(�Ë��s@��D����X��ZZ�;=\�tr/�`�� ���Wp��W��>;�أ���D��]n��c��~<�^0���ό}�� ��O,?�R�= Ic�톈M�7�һ����X*�{G�I�!Q4v��t�����2�����l
+� �l۾8�1j:�'���{�V�}]4M�����9�;�5��sx P�.�R�l�E�ZX�%?�vv~���L��OF���Zl�R�-=��W�e��b�nul��-.��c��=�P�������Fpq3��[[TZ��* ��C�ʤ��i�WU,Zխ�،�㚺��[���f*�'>�n0����� *�Z�
+�I�zy��W��#8S���^�}<�p�5�jr�x���'L8ʪ��+��nC��Q�e"���z���x� Ƽ]X�z�A���s0mq���_mU�Q\ �E7��E?R��ƥ���/*���C���z��} Wk��)7PQ��>���mMl�p�8�4ĸ��p��^��fJG�����������N���\� ��C�ۉeF(솚�E=�瑇��<�o~'�_� -r8hn$ٱ����ۼ��Rн�F#ȸ,�y�[�-O�-��vN�� r���"5�^���"���^��o쯖E� G��'V �֒�i�D�e�?�)�'+����o�Mh'�w������f�h��'�Y�I�6���9E
+u����&ծ��e5H��y?/�B�bL�2h�W���;3���v��J� � 4����
+4�+�-C��vS1n���V����i��Cɵ���� �<�Ѳ�g���,�-��*�Ⱥ����/xP���,1�C`���,LlQ 1�{�[�p\~w2dPLO�B*��W�7�K�_ZN��v��h��u�t�r��IB�0Q�M��_������L�L=h�Q�u����Eq�xT�vJ��P��џ���A/�.����U����6��q�YJۧKJ�NE��o)�%���N�V����_�$�~�X� ��}s6�5�=�alo���<���<@7�D�EڛR �N�S1�,�8��[xʖdz����v�fъ�pl�kz�6@����K���� �z�%�x7�1!H�'��%Ř�@5%CϞ�m�Iݎ��U�{,OlE�
+g�y�dE-n�J�O�S�=~Yj��\z����'Ph� �Z�7B�Omߖ\/8.�JA\N.�˧[D�<P�"��hS�moYIT`�E��5��yn�
+�Zt����>�S�H�޵2�nu��!so�%w�I7��i v�q(#����{��y�c��+8E����e����
+�`k����U��=�Ƽ��� �P�l��ؙ��� ��ՙ�@_,��/�Ac�&ɞ�D�rw;���v���Ǔ�QhCa�r�5QY�s�?�X��h%�N�4�s���ڧ&h[��O�Dr7��\M��3���O+W�䅟� ��w���0{�_��{mV�t�U����D�e�:��7�+1�"ב���w�Pʯ9�<"�+!���C 3���rÓ7{�=�w�R��7�2"?N2��*��t �o����ps�����]���><�$Ϭ�ԽzY���L[�'�B2!����7Y�ջ��j����⢙;HN�*]�w�L5��&�n9cZ�;���S�x�)� ��ĥ U�%Em�.�uQ�OrRC�f�,�Q���`A�s�k�:�G��ٗ��NN&�� ����p��}��� �e�NIH�7S��2r��@�����M���[0㜹��ps���*���֑�:�uT��Xɍ�2�5�N��*��OCx{��&͙)�'���O<�D�70��^Ԇ�T ���Y�EO�//g��� �ur����Xҡ#:!�8;„�y3*��<��.�4-Ō�y�O��K�d����],�(��O<yFψP�z� C�;��Iu�[�2���*/S��4}�r��!=r�^]��a�
+������A���u���+��yicW(�,�lN ����_2w؛mFD D���<�/����C6�Y� 秜@�JB]�].mCB�f
+u����i�I�-Z +Q�3�t� ~WI[��a���m]�� � ����ˋ��k�n��q����%�*��S�O�,H�nr�v��d�`K��f7�:U� �*�*0to�>��K�T�<$o�0x��H�G���0��$^�ri����ֿ�P������/���M6�{4�q�o���a��9��S����%�M�㰺 �3@'�~�F��!�g Jǭn{�4��?C�k#�Ȑ%�1ٻ��BU+����د���Kpn�����-ٞ.�i��?��CEb�һ�˼���� y��@g�rb���a�}[h�"�-fT�N��Y��`�ma�XSPL� g�,=i��ʯ����Z�����UB��c?N��qe!����8 �^�C�����뫑BR�ͧ����|��b)��s^/i콅��b��}��x�+�Y����*Ԯ1/[B�ٚX��ke���TO ���/�3�������7����(5�4^���?���IJ����ҘZ-7��6OaC-4nZ��7�K��J�`W �� ����c�}ߺʢ��@u�t����;�-4L���»GK%2��NmT2�J fR�� ²���Q��S��p?wC��TosZ�-���]Eq�Q��a���F��.|#3A:�`��.�WH΍��2��m�-Fz � �S{���.��3p�p�}�|4�-�<�d�QŇ/�:h���pd��:uW�hڗ��3|i��Y��%RG���0��X�~�eHx����-�*X�U,Cl`��D�%���D ���=$G�>�y�w�}�sx��0UB1VCC��7W� �m��M�O<B�7�T����E]�Oa��$�;g\0�I����hɚV�k��(9aZ�� �n0����ա�: ��t6� �f�҈$�"7�"�g�gv]�Dn������$��WR ş�j-(��5���T���;�]^�/��∛3�����-�q�q�{��&k��P��Q'+��*�f���A��^4����IP��S��A/�S_�ƕ"\X&��v/3M��sf��!� �!0!7�p��<�f��������!�'me���(����׆�SHdʇ�HYq�4��?[�3ذ2�
+�0����dJ�]��+����~~�2�=gr��LL0���n�ν&��\.��X�3;��c%-.�+� 芹]�A��]�lg�i7Ts�E��͋��!I4iu���~��_�ɏ�o]�X���\�����z!�����D�x�K�Q�7Fi���u�*�s��I��:�V�V���#��p;��o]f��-�$��<#Teamjc��f���� � sj�y�(��?��~:z
+��g�# ��p_7݇� #�*S;���q�4����4�, <�,�P5W=�/��`�|�aR�R�T�a%4�o��G��M�kt��μ�
+�(�N�_�q�|�Tu'������_�
+�4/����H2���n��<�U���h�ȘI��U�a��/�
+-� 4 je?��t��i�L������j��$[V��9��%�����Y�f�΂�M�}�e�
+U7x�y(�,V )�ʣ���C�GH��}g��υ;�li�28x@�,e���8���p[�l�.�"R*��/j��'/��:g��ו����S3�o�-��g�+R����BT��2Eu�%�9D�]��uc�O-�/[��N�@�����uf������}�PcL���D&B�\�D�IG�{y�쩁#������rX�Y��S�I�$�� �l�'�1v��[�ъ]P������}���+���$�㖂��:F���)���;���~���H~X���X�b�\~˞3���� vi��Ud[�t�ݠ��<�� �� �OZ���!�����ؗ�MiPf��'���|�[�Z@�4��O�)�� 肠�7|��@Zt���J�TZs�(2�=�f��ED5�ɟ�x����\��EJ�'�E�}i�Am���r��f0���z�
+��A�/�)�Ě�&­IycQ�9��q��ľ\���00�!�n�#���^fI����/h�º�l��� ���/yO������mn�8�����єv�~�P�` w���m�;)"��l���?%ս��)���X��&����V���9�1��& �ڄ4Fz��̤,����>�_r'�&��6�Ps\��jx�5u����' �XBa"�Y>ˌ>�������$_XyH/�љpO��WhWY�|�e��
+=Ё�z�?e�WU ��h����`B�t �ۇ圽U� 3������:�3|��^y$���G��B��鬀R=���
+[�^�.mAd�p�ߛ��|Pm�l����ׯt)�.���P���o��*�2{P�U5�+� d�%�ҍ�-�ɚ��V�|@Ast�*AO�;#2�a�����m�Ǡ9�Qs�~ܱ)�Aǘ`?܍��}C<ƭ��u���#�F�C�O�3�3�n���C{�W��C�!��ʕ�'8���ރ9HY�Q\썋�:�R���:�VL�.w�P��r�-3X��`���T A5�U)Ŏ�����Y9����T����3���a��"�y���ԭBT�����1�������&E��wܠ�Ak����X��t*��d<)<��������?mo
+��f��F��W^��r�f�mOa�a�w����2pK:����yP�ۃN�9�E��TcV�`,��_g?`����2�:O NOZVv���̻B+XQ���s t��jЌ:^�XR��O�A��=������f+���n���;�N� Gaf��1s�ө=�%Y�� �|g����1����=�:���Mj�$������$���nύ�ܙcb!`�f"Y|���<b0w�`}���H�_7�^�5լ�VIR�_p���V��Qj+;!�TװI��u�%Q;��"��?d�;� �_N4_��-y�f��fҠ6�u�9^>Џw�ڑ�R��4�mc�Mj�����؀�Ï�J�]����=�9���KF��1���0�&|\x6��g�&���9��z!��X���
+�+�% ��,7B ���mΩ4 ��@�{�!��c�cF��l-�:�\�EBKɕmN7%��͇��d�g���ƣS˂D�
+ *.5/����Z��O�܅�@�Cg����x�]��9Rm���ș�7v�C�NK._k�V�0�2�������6[���-�ք��N�jP��Z)������Y�W�t��{�Xq��@b�7��\E�KS�f�mf 2�´���9_�:�����V&H��-_
+���>�]�p�/���q���.�6հ��G$ɔ�ešZc�B�z������U�ƶ΋�I�袆����^ͫ���@��/���Qx0h�3�@��1n+8� O]�"��U�? �>��
+�1�_���S�\�=Z:S��� ��2yI�@;�)��n��1�N�*�+T]M��2 �榼�_;��C}��fm�l06��-��Ö: ��,��f1��.����x���C�.0��������B
+Wc�v����w�k�Z�
+��X�j1o�*���p���<��`�O���$�ś�@�zM��s������l���X�YQ��"_�n�ut;q�5\����3#�ݚ�/]��8LB˦t��zC��ͭM����|k�04��z�� ����9_泾���P�Ϩ��g�a\a�aĆ5��j�P�g�Fv��^�v�}cБb�em3}d���<��)��fT#�a:8��`6�&���Ds�1=U��.[=d�[BMui�d�y�vB6��)
+7o�C���3����Ez�S�
+�N�mk��3\Vqծ�itj[���<�=�"L�/��i��-A����s\���!a����|����P�qa��8(�ZջE�P�
+@y�K��ӵ#��OHT-��Ĕa��O�/��P�ܫ>�b�W��pi���%2����ѧ�a�;��&8�K��?d �r��MO��+�p��ݶ��k��$���K�8�O� ���3Qd����ّu�ʬQO9��+?�A\Ġ�n}����bM��{:�6�d����\�$^�i����p�؎^�8����3�v�s��}�&�*�C��K��Cx�����Q���<E��}���U࿈R�g�p�Q��֑f$%���G׶}���.��<]�$�5�F
+�:�`G�a1*��↴� ߔ��!�$EE)��ܾ�G�A��X��T+�D)H��3��"��@_�7��[�{�)1���B^��
+�Nm%�˺;�Z��Z�M���UM�85`^W{�ԉ�o�iʏ�6S�1 B��Zr/c�y� چp�S}��o��'m�Ӗ��g%�p9�(�j�?�6G�K#�]rR��!0�f��
+ީ��j�@H%{(&ҳ�U�8�:�w�rµ��ed,u9Q�>�?Lx�5e8T�/A�o��K�q�%�����
+!JRv���%W굶�/��KiF��6B�IA�5��G��#���wQx&omI��ap@�.[�9F6���� ��A�IV6�:�dĐ��\�]�G��!�Byn��[�%���j��n�U�D��8�����ۮ?_����[�����o7�7��@�����x�(�_ypxMs)�0��Ѷ��<E�ɥ�b��f"�������wŝ4vW�����h�D�0�f����)uG(j�(�ދ�Ҫ~�]��b*�l�X٫=�%Y��� ���;��������.n��Uq�9GC�n�K:�X����٬.���o��ӣ��Gh�U1�0��c��r.D�@y�@LmPK���P*Ȍ���;2�,���Mt՝C�ľ.D`�5hjy� � c�r�b�+g�l�nhF ��#���l�(�u��������2q��b�����P�"��VI��;e,�M[n�C�i7�6��*�Z�౗ĵ� 0�9��iE@R{(�ݎ����_ Ӳޑ�a���.8�*�*ߜ����5lFC)雧#C!X�vU�E��tH9'c�e��uKXE���/�[_ז,u9�J� ��ȶ`Q�:ͦ�Qvrl�E�J�q xo�b�P�f�jYn������ɯ���rw���Ϥ�J��m�{7�?�)E֖2-%�]�� o�|��P�d5�
+endstream
+endobj
+849 0 obj
+<< /Filter /FlateDecode /Length1 1381 /Length2 27007 /Length3 0 /Length 27975 >>
+stream
+xڌ�P\ۺ-�[p�4wwwwwkwwww��\�C�/{�}����{�U�����ٜc��Z�$J���f ��ޅ���� *����`bbe`bbA 'W�r��ێ@�tr���������M���Pd�q�0��9x�9y��,LL����xb�nVfy� ��@.
+r�t���t�S�߷*Sj377'���a;�����=@���h�����-@djt���T|�..<����� �v� ' j:����%@� tr���`l�g4r������ swc' �����h��'��� ��S�*-Pt�� ,�/���030�W���Jde�w���)��������`ne (J�1�x�������:����[����ݺ1@BX`�g��s6u�rpqfp���kFƿ���fq{3Q�������Ĭ����ݓ�õ���{�{eneof��f����V��@i�0L�m��ؙ�98ؙ@G��Ԓ�j����������r���ke����l��8�}����?W��3+S� ���ῳ�1����s�NV]�?�c0����;�? 3��z�7��#fT��ЖU��g��r���<��,�zn&333������y�������Jۛ���j��>��e�8@��@���K�@�]�����υ����������,�W���$\mm��S� ����Y�z����\W�?*��т���j�%]y�������J��Q����F�3�10���n�,a�4S�r1��k�eW�Ko�V�@%���_O�?QLL���Gd�6�"���� �GC�YW��d���X�9�NNƞ��ϊ���G�f@��� `d��� ���`rB��`��Î��M]����o�)���ߪ=��+� S��Ɛ��zaw��)�������v��oK9�,��"Ff_q'ҕ�+��}h.��=��s7Ӥ�]�ć�D�� �~��[��@�3��{hW��D(F�P��ɚ��C9X�jK�z��t��v��GT�4�X἞3�hm��qm=�8t'� W5i��7�h��'���_�{�q���sF��Yo�d�8��a�azɐ�M$��a%�ȴ9�Q��?�V�&��څQlBqn���|Keum�P ���7���b_��ؼ%4��V�ň�۞iIW�N&B^g�8�qU�j�?�M �i�Y����W<i�A��������>�f%2����r�n�p(�;L�k���K`��c(IC*�X�N|�cx(�����l���k| �DvI��#0A�;�l�4�M���'��8�K���א:>/~�_%?J�[�$����,i�+J�ڒ��X��6O�p�<*2��e%Q�j �dP;*W����5���y<j��'�_� &N׌,p��=:�F�
+�2.l V�g ��E�^s.n拼��bT���Ǿ�=ݷ\�k 7E��F�����3,�$���#��=�L=�jyy���0��% )��n�g����T�1��o�s�4o���Ȭ��˶�`pܢp��Z�("@G�\�f��*@�� ���/�����d<�IJh�fiފ�o+(��]t�K����"�p�8H����@�(3�e�Y$���ĺ�ͨ����S��p�wv���H $��ͶU~֎V��0Y��$~-�Ʋg����kG%H*������)eo�+��7��㋦�g"�,�۲�̎�y��W��� ���z�rh*�̵�y&7e_g|i�m�D��e�kTp!�n� �`Z������M�O����4���_ �Uj�����QZ���V)���#���8��z�����n�2�ɛ�;y�1�*D��ʅf�c��zA����Ã��1�D�-dj��T l��$)Mኁ���M$����H�������5�μ�$����ϼ)9 ��t!#{��=z�տZS�p�T.��TDS�K�r��,�� ��F�'rP�mбcM�m����� ��2�W�0�̤Ǥ�l�L�X�=^����U�Օ��̽e�+���C/���
+/����gt ;^����� ��2��Ò��6�(�d�'����FȚI-�����w�hC8ݐ�p�ה��}�$Q��J�� �YS#����;����e����!�H5L��?ȑC�C$K^�T��1���O��g ��,������33wER'N}_�FV�Y�)E�<7w� Gk�k��M�����9)���e#~��(��\�W -��*�m�6�@�ћ8�6?3i�9�!uWI`Ο^ڦ����@߂ ���(b�n�ѸlS��ۜ;(BB�vw ��H����� vj.Wf�v��UI y�S���F"��fr���ٯe���}͌o��" �{���g��������ʟO��&̲B�45�v�[�k��^�BR� ��$w�Uur��X�Q(��?��Xݟ �5��ҿ?\�C���5q)�MΰD�H�P�p0,�Q9�l�NP@*]�(;<��'<u8q<u��6����-s� z��a�H%y:�⋍-����.�sfy�UB�k6�M�$EIɃ|���$� iS��*J�d�m<�?�Ǻ�Ŀ,��Q� ��w�"~gc$��������,�� �M�����*�C��_�5��k�a�@�De�I���]��kͣ�x�ụ]Z3��L��V�� ��a(?�fD/�˄��F@y�3�0�X�Z1V�b&�Ѡ��A�:�d��٢�w!��w,�۔vbӴ6��rA��0c��L��!����.�X�4ʉ��]0h��y%��A'�אB�\ ���U���W�~ %��C)�-�q?W ��GΖ�>a��,�B��f��(�6��)\�Jr�"��#]����0
+�$�Ť���S�wh,�lEIV��rɚhbzm:�^�J�zSV�M�i�ʨzqS®�כZW�~� ��tD����ѣ��a�ph���Q}i�� ���h�����.������b��0-�V� ���<-_D�I�\VƗ�����۬��?K1Ss�U�[���^�1-�6WjZ���Gz�q� ���
+�}X{�e��h؍���9�OZ���%�%^-�uf�s{A;P���gr��L��.�\�snj8�,HG����/d1<� ;��`��iM��o��m�䮔u Y�Z���A�]�ݔ|���[0@�sf�g�|��q�/�f�7%��4o}�*�wH x/ ���bP'�<�u�Oz�����ҩ��[��aYwe��X�f � �Ũ��遳D9�H������0m�����1�Hˌ�U�*�Y���;�=����:'A�{2h�C�����9$,R+�+{4c��/��������.�#�g�©��%����f\��|B�2�+�ر�U�_4��"��4�S�5�%rX7�K Q���AIu4� �nWN��f�����J�~@�s���k�<� �ve��Lm��CL�b r'Q'Y��yc}c
+���]N����9 Ԓ�X�h��Zѹ�&Z����|��Դ�֕�6���&7��,svu{b fU�[v��̗���2@r����� ����Fș��zԩ�R����>�1Y�� �+�( �;gqߔ���$� �Z8������XW�����qf?, &]�յ�/��3�0JT�uL0�����tFA0��-��z��
+���v��2�f���ݴ���S�����X'�"��~d���E�� ��������\ow�:Cv֧R�K���&�\�����s�j��n�ƙ� ��[}�sl-�Q��% ��̵J�?�k��U��9���� �J�u7�݌��Z^cq�{�=�$�>� BJOg| ;�?M��U���HLe���7d%��~�7'��L3�]��x�3���I%����d��-4�@!m���Q,�E��.x3.4m����A�CCT��9�� �B"4��s��+�q
+�iiE�0C����Bs�P�-K#j����~85��3��j��vڊ} ~P, Lf�E�A�h"�oS!0�]��mc>|[��%�O=�s����+U�)��_Z�
+�<)�Ν�2�O�H { ʕ�V�)��%��v�3�!�+��������X�d
+�W�.��C��M쑈b�qL��HW�h��{Ʀl*<Y�A�Q�`뀀�H���x1�ݎg���n��3�o�$����h����L42,��#K|��G/22}��:,�kS��—:�o�P�iB�w������m��
+��3#�Lv*���[�
+Ւ{$渠 ��ђz��0��~���ySx��-�������ZqN�`7���P�`�9j���ߺ�,���2� V���Q�M̘�w�]���={~�ګ3"_��"@-'�R&�ad�p���7?���Yp��ߺ�u�[�P�%�U.&{!k����Z�<5b5�F�g��OC>] \#����"��<)��5+�ɀsr�ƫgƴ~˗@�G�0 u&rI���|��K�t���J��c�9 ���a���%��哼|'BKS��Ek������X���s�����w"�sW�L��R^4-}���B�����g%�o��aa��]?�{���L�T��pVfYrͼ6����T��� 1�F���F XG�³pR<͵;�RD&��-�ߤF��݃GU ����
+�$*~�I���j� :��zΥw`*m�K�  �y\y,��]V�l�Sh�m��7<���V����a�7���;܈�ϯ�8� e������
+< J쪿^Eڮ��y���U��5�����m���_vM�;G~~�Up)>�R�V��&/&���P� h�]^���I��Z� J;Ҽ��$j%�Om��琏�����I�sZQ�ޒ؛����]<���h�MD!{� ��]� ��
+m)[���R߁��?-��B�*%Sp���@<�Jz��Z������R��4񾬫�� �uO\�~�k� �Ƙ$Aʡ�P�$pqO�.�<„G:>_=�x�|�y����Y�"�t�͡�����r6�ώv]��;Q�D[�V�V��7gT��sPV�b�����P2�Z~�(�oI'�]u�!T�I����
+�����(8�� ɪ�e���S��:y��-*k���-��L���E�����2Ĥ&n��r"~�2CLq��kx��� ����C�wʠ��.���}���Q�C���sM�x��� ���a{:�lIJ�P���%�G(B19j5)�J�GR�Y#eY����{��ba9ɑȾwoC\� o��ߎL��DLi��{i���"(l��:�f�-��%�x\R�`T��MG��YD�tK��9m4_lJ�*�!&��(�/�ʰsP�����ָ�@f�k�KȬ����_�o��\(�RͰ�i�9��a�2�b����oc�:r��>�ܠ�}[��*5�wËֆ��N{|��r��?�$�R���� Y+�p��~%��H�ʍ�^Q����1P�W�Lf��K#�)���$Yۖ���G��" ���'�� ��-� _zn,eơ��&`@��r�����pb�s�}H��2��^���o�Ն�,|s�Si#�P��.�U��39 x2�B%���A�'H.e-�n0�a z��&{s���X�L�Ӵ6�,���i��m����{V�����B몰�A�����˄E���1]�y�(�|�8mt�&�e;� ��{�rX�$=0��i�{�:g��R�<> Y����e� ��O:���`vt�s����:��Ȑ�2��m�O�����
+�MƶU<�dϊ�[J�!���LQ$������s�,߹���G�xH����M��m$�/D'����ݜ��Õ;$ex�oUHs���ɾ�B2����a�V����$�U~%���/�Kl���p���)#
+�h�̆�@�# �O�
+�i�5�BFt{%��Z��{a����"�LWǷ�ݪ� �vq�X�q5SN�v��4�lT3#M�*6�=�W �_���ئ�p����jE��%V���7Ϧ�r�7/�Ȝ�=��;�a��uBl�"��V?���������� ���@�}�e�ie���c6�n���L���f�f�=�LE�܈j8T�;��SS��:b_�%���S�p��C}���W
+�R����i�|�"&���$���B��?�R���
+�ֺ]�O��� I3��(]/�}�H�X_��cq�� jSp�2���;�_XPU*�Q<���}�P��w��M��zS}���M�Te�mr����ѐ!���'��?q��Ta#��&#4��+`MͰ�tQ}:"'
+��>ftP}�\�"�eiqE�&�?���;���R��a6t�?dl�D(7��_׫ڢ�[?��`���P7v��0d��0 �B�~�=a�����5X~����0�1�eLG5�Kx~૯�̵ �1G,}O&E�U��,V|{�Kd�Q�z�d0m��6M�֦�����<�~�Ɖ�����������N��~\zK"*�1G��dT����3C�� ���)�5�]����Ǘv�񕪅߬�9�Q9q,��}���������]��R��g�Ѷ��������>F����,����l<�6�cto"3��F�a%t1<�Z�c����� �kl\�^��j]Jъ���R㇍k�4[���L�����4�5l�[�[Ӌx~
+g�0���E�e�G������}j_���;�?��9#!�&�vm,���K�s֮�9�/�2/���X1�Ĩ;]�t�*ENV`C��Y���
+-�f�@�i@��_�2&CG��G���� G_��9:��b�U~��u2N��iu��.7C\~]������#J����V�A��ܲ��x����_ v�PD��k�e�;F�'+j!��0wwd�jj^�ou ���q d�!- �p�^d��w7K͇�Z�j�luoԅ6(c�����3��qTm���ў��TY�h������Pr������q�N�Ye_��j/$��b�bwKJj�8ҿ���]Q��m�+e�(�.��f��Zn� ���L�d�NPG�#d�<�����X�������M��u�l]�RH�{*�1�)C���cٿ�|�������,Tޒ� �RW���� �W��� ���t��t��x.����ӑ�F�8�*T1���<� �>�� 76�G:��Gm� ��m]�*�ޱ���!� ����� F���ā����>��tL1��yH]�Z�ƙF"���ph�h,�� }򭜟����Jt ;�}�nk�|;H)�o2���9"; v����.;)�M����7��E�xF"4�nW2 6��h�\&�l��y$H�4�*�On�!'F7�24���n����b����^���6�i#�3��jC>*�Q�+���zs�V��w����*�Pkļ�څ3��u�k�ϥP>��6Sm5x�Ok�5)4����^¡�����
+2�By��5;[���辆D�Z��M�V��� wD`dKdV��#����z�Pa�o�U�� K�V�F����vHz����³�����h]�.%���|�\���lp�
+��g�����.b�ޢd���G�-��N�����
+2���?��B���ԂIevp�e�(a�;��T�Έ�n �9wH �/�zީV)kq�4/�� �1 ʘ�m� �e�Jh3b���+������� ��:�%�Q]����e �p��i]�7|ZW���u�涄��u�a;v7#�����h-���a���N���h��V���]�N��Ӡ���')� )��~M� ZW����!�⣺��I��Sa�/�?����
+�گLʚ嶈�R� �gE��>!��RD���g����eY^�Ґ,z=���j�~~�k���y'�P��)ꏯ���KЗ�s�@�%����ŷ�ZY��(c�G�R��M�oې _Xda��fjW��S�:��\�J��+d�ڬ8��8��k�9���Od4r�$�����Et!B\`*]�e��A+��xJf��x����0C}K�� •��>ռ鴘5�v�טDշ�,���t��Ig܏��X �1�ֹՏxS���U߂S;YM���w�mo���g�ŀ\��˧��Z�e�W����S� �P�{�'ԝ��X2�6
+��'f���O�(���E�pg9_;��Y��J�.r$)��?n��_{`D7�_�%dz!���� ��<�ݎ��$�>�"�7�$g�k�IQ���]��o�i57+Ek�rhv#���IJ�$6Z��@�A���K%���U�q�رU=[(&R���[ʴ���1 ŇM�;F��X�yΌ����=��1����>�\9I!��O�er�����ݘ�"\=)��`�v�N~��Bk#� Q~/_��������l�Z��OLK�u���0Ÿ:Y���E��!�zo��-�d*��a� }����R@E�g�v%�-���B%P���������hbŅ�pl-A>�0)���$x��� �g��,�`��Λ6�%=U��<��3�޽�t:�G���G�<Қ��l�0l�]�`w�Ǡ����S�(��*�I�� �0̀��غ��.v��� �)�2��r����̮eu��ϻE��33-�fb����Ņ��m��L3���X�T#��/�X@�W�&�JX.5 hny���! ��c[} O�6y9�Dzӓ���b$�Bot��#[��l�m�S>Z��� ��wa��,�#�̄gŖL�5&��s��N
+Ӗ�N�a�<(�
+��ݔm ����$ڪ�y[��`���k_I�ն^�nUɝ��֪��D���� ���S5”�eg�0�Sy<2�)�qR��Z���L%��h�9}"�ba>��z�s gmT�'I��d`�����B>�>�����ݏf�鬯���(�Y\�l1���p�5�QH�M�Svܰsq�,�5Q�t���8V�`�[����ۮ�a�/��Yt���56C!k'�S$3��瞖q�o�[
+' �T�33Q�/ڵ���ol���h���+�H�ް��ǜ���bYkP��p0XI�\$[��,x�g_�)�i'�C�� �B#����9� L���%Ǯ.�d�1�|����bWQ�3�J!l��$c3� ��YYo����w�.h �&)�=4�8b�o�b��j�l�� ]f�'uG���������a��)�Ҥ�„�"BN����� ��dЄ��҃ZDS)kQ��$�!�� �����3z�Q�t���J�G�剱���B�D6�����nĚh&��<�,���z�F��W�g���S�Vy��㎎�z�Y����y�����{��-%>I� ��E/Tm�%�l�\��&���6\2bS�p� ��-�T�>܃RQ#Z4n��5�fSyب�u�6��j v�f��
+N�����nG<L�s�3�&.�
+)�u��@��~'�v�ξ{�c���O��P�`)1iw .m�V{�ߎP�2����*7���s7�v�f %� h�͉��BC�Ru���?5���H�/�IE�cb*b�B�� MÎ+{Y��y��
+jY�����Z���Y��Tr��3���` ��ݺ�˺�c��Փ��h(�y�EH��T��ȣ����0ʢ&v�J� Wd�zu`?�����tg;�� �xe���cP��'ab"��1 �N]���' � �"���}gKE�� Tݸ쎷 r�@(m��翵<�
+0%�j�}��3����'��伸� _�< �gC8�A<!�I��'���J���K��Y\�A���ab��;�7��Y�����볗a��z5(�]Wґp��ʡ��O{l��_�W�e����!{
+~ď�����TR�\M�ËO��\GN�P�(�0j�@�7��U(�5���Kxl�(�I��P� �1'F[FlR���7n2(��b��%�q�
+��=�O�W��)ȁ�cѧm�������`�p�cԊE<��f �۴|8m�p������2I,Ǵ��9��{�gfA�-,I:eVA쳙�}#���58`(_�w�R�����B�=���Š���B�x�R>x��-���/%h��W���v���5��/ۥ�]Zb5"M�ע,�'�]��(ZI�k�[_�|����� �H=Eyv�d���×��0�n���܍�>�f���é�[PG�'��cX�砇v�ː�K(��2���2.Z�֯ �F>�{y0�Z��F��>'12��&-t��kqZ+V�>�7�P�%���ƪ:��B��m^���ͯ�&���f�U�������/R�G��u±>��g!�H��me��G�v��j ̙r��Q������w����ds�(�uQ5DŽ.��^(_�D �Ȟ�ZAzn�{w�|�aB�������U����Aލ�Ԁ6��_�ƥ�,x�zy��䋔�5��6�����<��֦��`�R�lM���`{"�ß@�¸4�<_�8�Y��w��"�z-yNU�,�&R�r���'�9+�C�Q� �|��N:6���
+v�s�S�q�0`�� ��ѿ����@�Vq!FBI�\(���l���
+WȜ��sbn��|#1���\cD��\�aw,� �T@Y^�>x�&�C��ꮚ��]<e�)���'��6z��ۡ�-R��J�~ ���I���)�G���4M��:���_�"weW��TwN H��*��F�0��T���˜ g��Z)�D���t'[�Z" dE{N3h_m��ND�k�|j��z��q�"h,8,�J\�Ǡ�V�pN��N}#5�;�6~>��X|��9�˩ �^7��hTRp���Z�!23TyI����,�gP��=��/2Xȭ%>� D�]�,;��v'�8�+���]k��<�'�_���y B��*�/�vC#!�n�p7g���N��_M9c�/�-�{�Svkt8��,!�=n0d�X6��o�����|���� ���mmh1�#��;(�:U\.!��:s�i�F�"�B�3Hea�п��/�FݐdnU��
+� z0���ca<�.���8�]��ֈr�CZ�c��x� {b�ַk*z�������zhൟRN�rp�fa��0�P\�c�F(�=S�^��{ͩ�D����kĊ�O6� \�u2��'���P���}��������b��>��p���ƽ�.�"� cs`���`v�흏lAH
+_!�ѭ�}��1h�5��B$"d}$z%4� ]*��;����#{�n#�Z�� �B�T�0�����6 s3qe��߭�Ѐ ��J��Qkp�W� ����֩�N#��o�$d�hT�$cҕS�F�짍�3| �U-�{��Z;�[��qk`�i�A��n%{}d�;DY7�{���!;)��xBa*�y*��ڥQ���y�6��>ȯd�u�zy@�A�19?8�*ޘt�T��W�h��Y8�䊯�d�V`u�8=�`>��#Ww�L8Yn֓�e2W�g�\zS��ݸN-%I\�d��=(�����n�q4��򯋎��3{�.S���۴��\�>��.���6 ����M��l�0�e|Rg��� o�zq��&�Ś3Ƕ�f��W�j���{�H�bf�\ ����|<���_j�w%�,L� eGzN=�w���5_5��,���P �~ ܏���9�hY�sM%G"��–�T�Ē�By>�Sp�=E��2l��x �b��Y�����F���D����C�7�ce�o �B0��P;�6��6B�x���8��;ɸ�c��{�� ��|��u�yh�\%���P��Q��~"C�Q/.���5C�1����GX���6GS�Jå�k܏|U��U���?$���:���Ξ�Q��9�iqVP��Д �-�� �1��٦�
+I-�t��E��p��xD�>P��B��Fw��.u�$��"�d�|(�H�}�Ĩ�ū+Ya�����G Q����k5�A�;��h�)����1u�J !�����[�=o��}��{ġm��lZ�W�!��>���7��E��i�~h���}��ZV�� וL�'}H�=�B�@3�����c5�N��t߃�F]8b2>i��)K���ݺ�e0hp�=��י��Ug�@ᾅC�+�hT7\[*��Zkp�L��j\���>�.�<����)x3,>`[����F���la�d� ��`�s_����HT���t�pw�\��K���q&1�a�
+��:���G�d�l*��&��@�W��!-R����ڽ�[
+: �T��Ē����i�%��ڞ:1����z�>{V׳�$O��#� iY,j�g���<�Fg9�T/� �uT�p��6,�DK��_u�93����Nm�[�0L����F"�V����w}���w#����7F��Gf�aއ%��AL����+4�g������4a���h�y=V��` iUjɻ��$i��<z�B{G� �~�x�>h9r{r�%�)��
+0�HӺ�!���.֍� ��<@j}�ӹ��B~����s�#���:i�Z<�]h���`$[���
+S�v
+���u,�1� 1�/�j��P~��(b���{�bR
+�f���-��jГ�o��D�#��� �9HP6��K��<o����U��T ���y�>g�J�^ ��@b%�Ǽ+Nf��!FykqsFWD=� ۵��M��ă��NXbu�G���<�;� 1B�p��>Y�E?�>���_:@~ŷ����R���OSO��[h�d�Z0������`�퍣}��#(��˂B��x��iT�QTON�}e8����.2�B����;3���L����g�n EY��o�^�:>���,Ց�+I=�t��CaQl�v��s�H� ���<�<M��׳�%ϺA�� f�����a�"+�Nb�|�^Wؓ:Qk`B�����_��K���e��⌶���J�7A/��Hk�"i�jwl�,*���XŘ:��Zx��5K�e,����¨<w��D��t���:=mX�’2��}���)���\�D�Sk�e�_*�1# r�MW=�C�u# U���Yg*����O2��H>]��9!�v]a�*�ZL�h�ڼ(3��-�hh*����#�{�_�*�qW�M#r�����(�>�`N���
+G4��9�Y��d���aL`�gf��'U�5�;�KFݻ��,�3��L�&j�������w� c�?���|F�57��� ����vrSn�/�9ї����]�[7��Q0�!G{ )w&>ʸEEҼz��)?չ��H��s�g̔��z�����dk�g2V��oV1Q`g�&��Zv�����?r���u� �q�.��A���V�g>��U��B��4��[+\5�a3բ��_`�I�n�:p9�e�j����qN*�7����|���5C�e��v��E-ᫍ����0*R�rI��#���M@�1=����W2i9h�HTq ���9�>ο���W� K2�N�+{���Hm��Z���Z�G�Ui�� fp?kנ�[�����hAl�� �NQ1vc& 5[��
+����"o�w ����GI��E�!�g��H��K���A����%5�SX�*�p#j���$[��3(��.��j;���(��J?h���ѐtbDA)�P��Y\���j���lO�`�:Z��+�-�02JfqQF���f�F���9*U���#���:�ws.F^�R��W���=B�u�i�H_MWȎ��f��V�⌬�5�
+|���"H�5I���)a'����ew�I�'O�`Θ��>���w���{|Ή[e/J8�֙�g�E�^�@�p0�M'�~5(�=�EK��Kx8�p`I������I�KqCϿ�b��/O��>�eɠ2��7fH�L/�E)ʎ߂��� {E��l��r���8!���Doug%��~Vg�� H��8�9�kāy�+b���"�m<6�
+���ψ��k.�1��V��e�������RTb?�������l�v�ڥ�jXa���B%��,yJ�m�'O��>�Zga2�]&�s�ԧ�o!�<Ht���E�m􋽥� ,�Jv��M��4�����Jv�)O�G��!3��6��.������̺�^���IO��������B�ޠdrP�� W`Gr�3��u��r#Z�LS�V�Y�~t9){$� ���A��U�Er��u��cJ
+�~�?舃{&�C���mC�}(�G��LD�Az�r��y�/��xFH:��[�_������ϙYk��l,7�Ж����Sl����5���
+�(�zb���~���}F�19�z��ދ ��$��k���@��;ϵ}�=`ݳN� �p��{s��˖��]f�$H�1f*���(���k���������7�H6%�ID��^ߎ��� �w.�"{��ҽ29�s�xm��p�C��R┕�t�qV��M�$�'hf*g\�F� ��v����J�#n�>�
+RϘg��]pǷ2�F���$D>�_����l�B�뽛s��?�u��m��Y�
+�����ԛ�����҂���+�]rWʵ�&�ES1&��n= WK5.�!�<�c�w�����R�3������J�
+��mf�p�c��9�(J']ZP�X�JN�C �Dɑܬ�m;h,� �>3Z7 a�n�0唡�Q� ۜ?���u��#� �/�XK%l��2��!��1E��<<P7�I�8G�!Ij�<��TJ�E1-q_��x?>�%X�oeF��PE5&��M�<���c�Ӂ��'����mQp��K�M#|̐���9�=U�Lou0�OW�De�����������4�vt�s*��Qp ^��c�".��i���[�~���CB%1��7� �6�����PG�۹/�˻����TV�����?�Y�KÕم}��G�c�n���}&��U�X���H���N׆=��ԤUS�8;Zyn��ݍZOI�D�����ۧ�|�c���!�JD�tɴ)-�R�m`E�=!Mt�`�%.K�ښN��j�Y��Z �¼y�ɿO�����&.��n5EhV?��j���0e��� [,b,� <�}9H^�����\�k"�X�W���E¦�%'Yr�x�v�f ����i�x�*�Xe�u���T�:[� l���]ʳ\�H��H���q����1�ж��O�[�0E+Un��k)k��æ� �ͧ {����⟶�J��<����2�?餛��ܟ�?����/ �4�����;�z�NJtV�`�=����4��d������'�4>;i��=�{JH��o��W��^y,�@R �!�s��s�d���0�u���|�|��F����h�-دiBKк��0y�&���(�.��j '�}�Q���=c��yn*g'�lF���8� S�C%8�D�[�4FAq�x|fQ�w�r�s�����U}�C��w'�&J�x�y&��,�fI��Mr-��Mi��O��|� �"�����ܭ��H?ً�o�5g�qL]�Y�7Y
+�50 <�}�}^����Ϊ���t6�~쑖> �*m����%��t����o ��y ��UM�C��v��o�z��9 �e&����� �X�.��nݘ" rdt�*�9 #M������a�BX� ��N[���h�t�^3��?³�sng]��k�������̗Y����ť���h�΄
+�gB�s�to��"�]�/���Ɲ{¬_����>�o������F��(lS�����@�4w�HQg�ޜ��|Gfs�'�����_��G���mTd��S<G� �U�Q�@�4%�:�G��"N�p�ރ��&Rx��C\J9��O����3y0T`)�����#�gv����. k�MWq��E��Ay؎*Q�=��I��8���p"!Üb��ё�%ڱc�S����ni�W9�h�/J]]���K�!L�[���j4w��y )���ZBT5��Ƥ^�m,n�؛�j �S�j�Z>/[�
+��"��;����M�2~繜e'��F�5��{�K�k?H��?�`M���"�,gӗ��.�Iy;����vEZi̯Y�OUv��b^wb�f=�Boc�+� K�&$�������?���p��a����V��Cɷ;��ǚh3� �X�uf ��;[AN��6Œh�t�7���X���w���*�"����W4� �1P�Pʰb��F)c�5 S7�W��b���PW�F\r��oQ�����v����FO��/{>:���Y)i�~����j�i�~2(׭��Ūy���ߪb�,d��� �W���3;���G�g���濝5 GcZz�%V4� �,G?U�p�t�Q�-(�@d�.rp�Q*؟�3+ƀ,��^����S���RL�\BbCyU�I�)�Q=��b��m�H˯�� HΏ�I��y f&'
++�BQ� >�9�M~Iy��iȯ���j'���-���yl���h�b�PO����m��^&cE����/J ˆJ����eೂ����B,��}[)�7�ٵ�X�܈�tCj��~.^Q.�2�.g�)O ς���]��ZZ��8m�!�
+���0��w���@\����S�W�֦�,�Uc_<R �]lZ��9��s����J�Ճ#фN��\U����`d��
+sÑ���#��%�!�!_"��L� ���Š$š2}|hS`,�B@1���<o�Q���P�B%�Kz��(����j�KJ$U\%b.2���hMIf����
+O������ ,���"6�x���W@y�Jã�+�[L�h@yT��p'���v;={��N#ȑ��$�':,��G�a�s�A˨���J2��eyg ��.��F߹K�~d�������0��y �~�
+"O@8��Ru�yGu��Ia[P��S��D��(!�� 2]�'�o���k�4?���_!6ʳC�F"�B�4��e�@��.7 ͺ,S�cB�ƶE��6*�?�_�+렝��kIvu!";�6ڋ���(���?�z ���)�~��<A�q 1�}�n���r��G4[�N 9jr1>۝nP~���Pd��}lz�O�lx\_�&%�������jF\�'�{�_���a�mK���gL���e����3�7G��%̞����Aw��e�;��O�p�fK�J!\�$o���4�F����7��t#��x;��/���q�����O�C�~H��Kw�B%�-S��dM�D ��5�PF�A��-�H���}4�:Hk���}&� "��n��u�u���ñ�|�&���6����
+�{���c�˅�n(��t���戈y���7�v�Z ��eZ����T��:���-N�3�V�O�ڢ���|���C�lt�fvna �&c���]/'��L]2�j����F-� [�Jᖬ+ne��7"q �m��.�_(�{
+Wi=�U��3���z-eL���e���?�N� Һ-����vU��BFZ�q]Pe��ΐ���Wi�����^#}5��ż��⥘���y��9c��nR�p��Pj+>��m7^A
+C���G����C^N8%�]�٪��3n��E
+�'��(؃#}q����f��]Nsg��ߔ��ȼ̴s� k3Z�� �O�����#�t蒕䃢.����"�$����N�׹��7� �r����� '��,E/[X� �K\ u������i�Qjߪ9�@�`+.�x�r��=�b8o�X�<�Y����q���Y��k�H��cÝ�� �Su֏�{c/j�:l����Pi��,�/v�i�X8�a .���`�U8��=Xw)���Iq���q�e�y� ם����緬��#e�ky*�����<dž�b�m�AH� �����=�<鿅�{�I�$Q{�E���-!(�5>�����`mv��Q��h��G�#���<L���8CK݉-�eȃ<�"fÒ$�������&�>�k� ��ur�zw'���ƞ2ņ_L���zII�_/N�JlSp�h.���J�k�犴C�BF����� h��Q���U ��aDP*[n��P$5~��^���E�W ��!svy�����5C�Y"��w��(�bu��O�+l1ȿ�M]�p�'�`��:T&g0|UҼ�Ӭ� '�|7��� ˀ"��s����n,oL'�v�(Ae�`��H8��2����;c.P�xt��6�r�KOFe2;=i҆f�[� '0Fd"�I�o�b����"0��9�c�ڀ����q֫��T�-jup@H��ZQ�I.�8��N��:�q��W��Sx���b^����_ b� ����l=Kr:1$���7������5c�z/@�^j�DS���E���EJ�H�����#��
+=;m)�o���� �\���&2��w�����$y98�&CP�oo�W$e��)��0j����ދ;T�P塕y&�`H��$�יVѪ
+M���H *�-�"�]��Y��k��J�cM)�0�n��$�<����w�;�*m)�����c��D�®��=_#��u�-�1Ўg!xoMB��<�g���Z�?�����{9�VZԊRHd�A���dF�(�٦<�Q_���<�D�ה�;��v���uS�E��a[3�����Պ��j�ToّLS~U�0���4S%���M�V�3G��a�̗`k[KX��^}�.#}DS��$��p���n�~'��O��N�b?�`�m �ii� �*g�p*PD�o�C��b�>n�׀Ev��-`4h�d�Q�
+��L������LP��]X6���#.��l��x�*��%�׽���J���H&��^h�8��m&��Ȱ�b$�4�̃�pȗ�$F����`u)\��uX|� ��� �8��ƹ���*�<W�F��>�����4"`���‰ ��P�Л��Ȓ���1 ��K��~8�y�vGr/k�L�j;�4�P��WKN+5K��ꂱ����8(]4�G���vڙU��N�5�N��z�%�m�䌩�΁:ALc���d�'�)M6@�:�
+/H/�p&�+ѣ+��9ׯ �$nEn��%r�N�n��t&�0=xR�Đ�C9�/q�jD��3���\���/��HWe:ُ����˧7��R���,P��N$Awf`~$Y?��A�X厱'6�&�nKQI^��|�NĮ�z��hJ�Z,�9e�����^�(/_?��>�"D�Zew�=雷���"��(|{[¥sE*��Q/�y�ߌ,�;��Y]����7�t�y@��]F�e�ԗ|�
+, r,}Zz��mK?�| ����>�o/$����=J8�����&�,�«���>dɯ5xG7��. ,�Yz"rdj���� �7F����6��\e��['��E @�o��N.�-B�-�k4Ն��D�a#M�BC�R���3]� ��k�Um3 ��Wn�Nh��}��Y�E�>��>�*1�҇h�a`��sw ���g����B�l�Z۳o��O0��Y��MǕ�|��n�N���L9����!F?�<47ɣ�{���0�@p�3���w�x��E�;��X}vr~�~K�,R<�o��xƣ�W����-�\*�W�,0.��QD>����JC��/�
+l�G�l��RtU��f�
+L ������y-xw�X�bp6��%���I�R;��s@ �䐁X�4�Iž�hL�g�8��+q�͗v�8�����^�E� �:{��LY�L�q,�F����<%� �+�!��hx�'\�� �1M��S8����������@�Mf�X��l����Y�T�_k�[ /�T$� ��N�3�-+�DPv%:�ΚlWY�(��]z���ZX�?�<<�`zJ�Z}�ƺ�z ���������C�}���5Y�Y�Ac��g���6C����8�̍dQo���q�n7I�u؏c�.ihU����ʢ��z��ݕq��K��S%���j�XW���S@�Y�����L�3�գ^!�v�q�({c�)8�[b��Aq��=l�ڨS���� �hN/O�H���#�����;B�g����?�Ni��|�W��{N��_�󋙖��[ӝ ȗ�]X+�#��4q#B��D+���O'%/!��h&V>&(�\f��H���H$���7�a��V�q��A�1���"^ڍ�@E[�;x�3؝x)#I���ij����{(��)� {!}m���� ;T I���%}��N�B�Q���0T��ԅ����;�m��p��`�p���IP��9���U!�#�w.hslhEn�ŨT�²�`�u�LAK،B@���z�5�čKA��›P���P̈�4�q\��ұw,g�/��l�B��&�T�?'-���Z \Un�oH���B�r�����M�ǎ�s1�j7�K�y�\3�"e���i�y2IQ4�U#��r3���z�ac(׹C Z�]ㆶN�SB}E�Z1�F�#_�|fل���~��A�#+l�R��PX3~��x�tqH��<���"�]
+S��Hd�@_�͟��) �����7ƒ^ ����� �螢��뫣2xB�OrW�aX���k��a�>W���g��eFQ iڋE 5@Boi�� Rm�a�u�W2
+��W:���$��+����w��F���l�?��P��
+��4P�M;>IF�p��ƽ���$�5;7���BK�r[����Z�$P;Z�[��2ݿ�d^w�e�J�㚽�C���v�ۃ�f�Y|,T�t�sr3�ї4P7�B��0�]����9<vlw���٘c+Z�(49{�O"{���*�*�ۊB��K�ե mC-�+�8sY��� �lK�z�9l�!���Go���]�j"(y�ܙ���6\�Ϟ�'b���,�d����������3�|zm4����� j��b � 4����"�'�!���hBD��Bؒ�H-��!����oy���r}�G��[<@�O%`� /_6����P��ߨ D�j_��"�B��V��9�竎��m�|cG��G 2�@�>�^ۻ��y���>�̤���AeSb6 (
+Q�u2N���C����k���R�~L�B߅m��_����M� ���y��#��}w�a2�t����
+�16�V�@�5�j(<�@���>s �:�G}�N��5�ܰ �����#�JU�}�z��Zj��X�LП���G*�C��8� ����dO��.��/-/��jI�٬B��8ܡ��0HJ�I��W kdӖ�Z_oO�خѪh[�Ju�Z+��4hE'��B�t�]#J �U �<�m��t�#7|��i� ��3KXV^�,����f�@��/�v����w8��"N����V'ٍ�m��ԫa �DeH'�u��`�om����t�-i��2�;���?�� �{�u�e���{��>`?��p��I8<�%�'�('�u�6�W9���2X��E�0_OГ���g�;:26�x%�_�3B%�h��i��K,e&�C2���)lO�E8V��P�|� W[���X΅8��B�y z�kCR�hl2��w�"�-�;��⛳]���>��@�����W�a��] �.�C��� �/��vi6AP"z��Ň�s��vI����ҎsC�C��� ��S�]�<�F��n���Ӯӻꞣ[�;�q��а�}/4���� J���̤>��a���q�e� X��Y�uBY��se�S��v���(��%ԫA�Y�39�Iq����plG����O������4���&��g~��M�3ѩ�~@��i�r/�K�w�C)�(�m��Ǒ�&9�[}����Q����������H�H�5�'�9 ��e}����dt��v���9&�j��k����FVL�m����%;N�3��qd��:��DYZ$�߈��JڋYlw�Ĝ-����Z�+Fcg�^����� �{v��+���L�q�� �z� �[ ��{�,OYrt4�VV�A�y��@�8��'"}"�d
+����R�3����a��m �{Z ��=q�KT�#�Ys���a����V�eZ?;ڤ���x��`���k5�dT�c�� ���{ݭ/�ȿ�Z'������@[�8�:���R��|���l�K�OS�lֻ?:b�I���.��-�U��M]7���p}���&���;��^�K�,�T󜲍��UR��$��Ux0�]U4+��[�у��g�Pz�NpF�!)c�<�P����R�� �jM�~��+�x6��*B�˃��.+����l��^�%�t5���5�9�N(�D�]�t�>��&Ĕ �M}sSd=�;�^;�$p1���Y�5#x+�zf ���PV���%v�S����������Q�um��sʬ7�_�E�?�j_z�r��+����g�`J��5J(@ �0�{�w�GkF8E��,�w���`������]�l<��#>�scS�bP|m�ٲL��o�����@�9�J�����[/���.�|�b� Ԉ����C`�ݹ�Yb}�ц�+��MF�4��z����~�{*��^��^!u�m��_�n����+�������kD�0�AZ1�mLu=�C�0�!�#�P&�"������ �mYi�W�`~�-G7pn�1?M0V�bAb ~{K��{��o���<y�vv;c�f��Ŏ�����¸{��#v���Duzx$�;�I42��)��f �Ʉ�wW�.���T�=.�^{�XnD���P�Ӕ/�s��3�M��z�H~{�� S<���u�������b�tkU�=��I��>���p�o1���T��EV�2���u`-���7ý)�dM�]/#���J!KG����\r)J ��q� �L�����H-�_dሇ͘yPll��\��N���Ve`feR)�c_�:�z{�����F�����T� ��`m>�P��1Cr�a߱K<7�{����;#xj�R`/�VTp��(ȟ�H����vX���������+��1Y��� ��)q^���E��y|b"�b1)����O�^���l4� -�>���;��3�.������3{X&�C �������8ʗ$ָB5�;��*LC�%WgE�4*P}jvT���܊֛J�1k�/��A�-�*���.�)=ed6�q��"�&��Ee����2��4 ������ݟ|��*#t�b쀔ˤ��f���Ї���ƀ�����/Gc��`����I� �~���ЭTc�r�䝽�h�.v{o@���3���8� ��=  (u=�g�2�Q�຺���ؤ��r��2�TU'�¦ ��b���C}������6|_��\l9��5fL�Q0�f���T��̄_���8����\[�^�ءhN��mai
+�K��I���%w�p��S�O���K7z�؍^?�EA� s)uԈ�E��e��c��N��v)�־K�o�}����N����Ӄ��R�P9�׍:&����i��g+�c����=11��<'��k�h\pWb�l�v2=�}LO�pzzK������(�h���x�ċ���AU~V:J���T�C�ޯv��F~ДqGV,�:��P.�ZaSJ���$����Y0T[c�������?��G|�E���s/��<��p����%��S?�m�3�C��f�"'
+
+���A�3Ⱥ�6�O&{v��W�g�z -�K�TW!f N�p���X�j�uw�AO���g�*��]�A9��p��e���y�R`N��� Dȼ�|4���#����=�Z���t0��7�Kqp�ΜZ��w� "�4.H�e�c�5t��E�`G��F���������K;ˇ��-y�[2�آf�;���:�+o1�����K�(:ȭ�p赝@���h�!�o�%�Dåv��3��L�N5d>z��C4h֕����c�h�;�,�m�i�A��0�m��Fiv��.��S��S�x���G͈<��H��mR��D��G��⧺�H�K/jm�� ��`��ˀxU����T*����~ ՠD�v{`��j)�z$hqQ8�2S��ó��[�PA���_��*���:�P+6�YXu�&(�J��Z�X,�q�S� b����)$���r�>nj\T�a�(�|^�
+!x��U���2f��椼�.��E��&���w���� �K����1^%��DT)�D�M'�_P�ߌ��{����������fX�@�=`���Ax�&���6�B�O���- e��u�����Rm�Y-� +���=�Y c��ү�}e��U��0��Sm=���{<���%m��q�_<D͘���T�`Ok )3�tX�I��vmO��p;�ql�CVAb��T�Q��R�X�<�#!z6oĘ;��@�=Z�A#���$s� �t�>�_�iv��q��<
+A ���"��%Ͱ^���<�ꅫ%WgE�:}����CZ��< ���'{���޹�||��ˢ��M旌X�կ��`%R� s����5nYc�h,s� �#6�Q=0X#�4DH�%��3 �cR�KO�V� Nm�� k�+�\�I=�ޏQzw�1�+2�bB��{�
+¢П�nd�����F�J���8����:w�t�I�(B5�})�ШAu�Zun$5I�w���v�Z��Ps�(0 B����7�~�d��=�@��Kk9�*�E���nY�2�b`������ ����b��@��Ѐ[�%c.��W٤ �"I�+�ݜ9�z�[pb���F�Q���"��L��y� �o�6�j��&�$��q� 9ܦK﫿�S0y�Yib&Ⱥk�9��/շF �p�@�)� �� e��9aVA�k�&���J'��]7\bJR��ոi&3�&���
+�o��%�������8���I�Mb��K�;����+[�W�!$,Q>�iRC��@��.W1���m�\-�0*@��ݡ��ڳR�M�1E�.��,�(�� �U�1�Le �S��z �m��'Ɓ�9�C���ټ�=�7���ŕ��'�,���F�S����{Oq�m^�q��4����\���W�}�%�,���#S�lPc��@��`�)����<�����&�4��Z�̇O�|ƙ:� 3Û?���y�J�P�!��H��Df}��I�ZԳ�p��us���m�2C�e5bU�"�n����˕E��+N�|r�; �xQ�i��5�E��|��X��FR��A��\���&�)��W@q��+?�6l�� 4Dj��u/(O����J�|���o[�{(�1����T]���)�����9iL�m�Cg <�� ��:K���v�E��q,�q�t@J�����b��`�h� c8ѕ���Z���-5�7�/��?�z#2�$O�k�H���� S�ؖJG�p��C2�~,���\��sH�Ql���]G��o����O��H4)��S�����D�U�<)[5'�W՟�*[����4A)��dP��y�O����v9���0XRʒJ�bV�"�k��B����X5 ('R��a�BJ U�m��N�#9 Z6�dPR2���+
+XU�Er���t���H��5���4;���9��(~/�|󑷀v�� �9���6e�{����[���&�Z��a$t�Y�
+�"O�a��v��n��Ff��ǩ���M�~�]���Qn��]��썐�g��&�>�>��=V|-2V��L���x xZY���gN[M{�'�#l�d��1-��h~�˺��3LtM�3wۧW�6��M�\;(|�Nr��a�0� ���Y����������5�6�2gaK�m�K���Z�>�� �mD1ץ&�*���r�T�� ݥg?'�Fm<J$�n��Ne����(K��-0�)��"4L��}�'�Z��
+:j��{����#^���i�㰤�gIǾUK�F�y��W���~ͺҁG�$E�(���� Z'OnhvX���p����ib�p��l�U����)8(�0�03��)Le՜Ta���l�� R#A���G�8xh c&~-\��Z�1���<mh'��� ���8~�W��֙k��b����1C�9G����A���j>������m��� ?d2*z����Gŗ�ruM›l��]��1kP_f��& ���Q�`'w��������!�Ï-X����W��*��M5#�՛��Y�W����l?>ݲ��2�P�e��5,���|��$���� ��D��K�L���Y'o�j�t�a�n[nv���S�j>�v7x+tI|�sع��n?��%'��x�|�98^N�#ʽ}U�M���zHQ����ϛ�r񆦻9�������o�ߧt�|6�1ׯF\�{LO���G�K���g���[�4�|���w|��[H$���@o�2d�ܫ�K��vo�K��!���w�PR}�q� �R��>}{�]9��0�q;�� � W\wM�:��/�����~w�Fplc������u��3^T�.�Cu��TҤu)������v�䫋��<��ڭ+0�����k��)�wa�� J8��i�#��Wr���������l�-������F�f�2{d3@���͐��Sׅ�(��_�A~�uP�<��V���a����\{�x����T#���?:���k^��w���3�z�>�9_�-Q���i�P�� �,�Ʀ���t�U�':�� 0�B��[h�|!V� �mk��� .��f[;�Br&��rw;{<Г�S��ך淢��N� m�N�E����{�T�.ѓ��W���K�f����e<^7W�Gہ�Q;[�u�!b���s2��A�Ib�!�"�k��#��oZ,�F�"c�$�9��(�n0#ߠ�lN��A�v�ɇ�Q��O+H�o�)�2e��|Q�+I�ţB��"��;��z �&�l�lh������=<��.����: �:�DŽxI����8�o�0�QGo������uBԄJ������4$v*��zt
+�n��-���F�� {5�@�0_��X��?�!����Fm����
+��d4�F�F�����ہiC%ߠAp��"� d��"ɂp��x抡]� e���s<-�Yǃp��~J퐖!�[�6C/�LTsP�b��l�c\W���m�aѻs܊�d?�!�U� ��I���9�r�U�>I�Ĺ�"ɋ�껪ty��6�
+��۱ ,X�I˔�~'���ˣv�3�i��U�ٺK��P�p�V��_��zʫzMW��(
+�+�䉮h�揌�D�JN
+;��2Pۍ����{��ö׋�G��*L��
+q � b,����@z� ��CtR�`W�����*��U����0?����!w۫5 ��5M��;j�h��n��rci��k`� �����^��[L�f��6v��7[��D9z�SMa�`���mU�1���fpv���J�;�Xs���g�!6ζ����8�[���@��`@Ծ�ǯ����\<��R[֒��0�z/'�[0Z"����>�&Lq�����SC�j�¾�s����`����9�'{���2�<�j�O�W���ձ� L� �uy&���헤v���FLu�9���0ܯ7���� =�1��vv�q��?���jӦ����'h���?�^�Y�gH1��u�D'�C��¾�X��c�#�s�<��1��a�S[6ӛDj���@]=���d��`(o�˷��r@&�v������kl�T��M�����W���˩`�3��=s����T��.5�UIɎP�7vߢ�����G:�K�*ɨ1�����)O��|6��N�=��E��T&����.%*$>lJTr��]��&��q��m �ҠJG^��3m�t�R�ib�\��{6de�H�q��8@�V�^9�n�G� ��(O mv�#�����`ㅮ�2�qo( ��[2򟿽�)��Lj88k$'�Y ֐G�ת��MX��-���<���d��F� n��+
+o6��z�������SA���(CQ
+���)��Yj�4�6κ�w��M�w�(%~D"}���H�pN5pf�A�9��v̙%e'@�e���cf�С��9�Y����x�j�r�~���b5����/#U.�;���
+XOký]�L�˱� �H� ��QfJ]F],�nϛ�P6U Q�gx:�׽���r���h�I�ĞYo�d�!�1-@`
+endstream
+endobj
+850 0 obj
+<< /Filter /FlateDecode /Length1 1368 /Length2 30875 /Length3 0 /Length 31834 >>
+stream
+xڌ�t�]�5 Ƕ�۶m�ٱmt�q�۶ӱ:�͎����y�s�{�����cﵪfժZ5�um
+e5sGS���� #3/@LA���������
+GA�n�f���B��j�����\�&nm�&nq
+�Yw; �������������_@G^�����9@� ��t��st�v���r�{�-�f4.��D�.�f&7+����L�j�f�@7��������͉����ӓ��ޕ���R���i�fP�]<��(����#@�����v5G 7O ���� ���7�����{8@MF��t�7X��z����������O"k����9�;�8x[;X,��%IyF7/7z����?@;Wǿ�&&�v&���� )�0����s5s�vrset����E����e s1G{{���+�?��[���^�7ӿ'k�������������?M��;1i8X;�e���k���%� �������:�^fVL��W�v�����o��N�N��M��-��|]M<�7w�������;8�����hi��?����������@��/�X��|�{e�^�v����|�t�5�������DE�� ��Vf�?$������i�M��S��+�`���w���*����#��Υ����@���\��������g��+�������F��� Iw;�������q��[�y���n���W�7T �o�*ͭ���o����_!�8X���5Z�JZ{͕��̬�͖�5�Q���P������
+���h�/�_i���}t����\�����GJ8�9��#1VN�����7��!��q|Y�j���/��������pt��g������r������׿�������K�@�� nu�ь/Ԧ!��Nߓ�pJ`��P�' ��K��+t
+Mmַm�G���~��} ��5�߳�&舎$��7�w�����p+3X��Eg"�C�� ��G~�~�������d)�ݹ�� П=���*�'—U�j9���+�b5b�K(�M�qH��ahѮ����r���e����Dz���ƽ,�lV���������?�M�R�����b/��o �x���"ҧm0�0��f�Z�F;��{L����B�������[1�\H�0k;������l��'=��]��}6ik<s�_�D����>߷&�ͱ�a�������>�R�!!KOZ +���u�L�4�
+�I�^-� 
+��G
+�;�I���W<��"ff]n�� �K�<��8���kŞ��e;O4���N�/�_i��E�Vl�Y����}���T��� !L�;�X������{+7#���2R��5cQ�߼m^x
+/5�5:8
+UHΣ&O��GEC�y�O�++E 1O5_��=#E��vչB������*�K�D��<�/���]��z�ط�#k� ��O���{�WȈSP�* ɝ�G������ c}h bm�Vz�A�Bٌ��:Z'3�kռ���WS. ��X���'�=�O�kW�_�>���I��AI���q�-@�iն��)ҴFP��0 �>��%��fc��:��Sem��a|-%����d �Ƿ Ը�7la<��U
+��ꀒo� Ej���9z�Lɝ��Wq��ψ�=���XJ�!Y���g�����@��/�!����cv� �ϿH�1��z����&�O��[�J���9#�$�\��:� &;"�VB9����YG�930�{��$���t�T>�$�l�I*ɑ�y�I�W���?u<�?k�ŸM��\�����yj������5fu���]}��\W�)4�k,tǕz�o4����s�����βHx'�6�, ����Ǚ����"��r����!i���$�V�0;���C��`FD���|���qĮ��A��i�$�QPw�X��9|d�ǼMXy� �����\5��˹�����<s�u� e�xO�V�ӑcܐ��3F�G�-5.�k)�+*�� GD�N�%G>���<��V�)�LNn�v�Z�Ɛ���׋s���~�����X�d��L6���x���M�ww P�b���rOLϋX���-A�G�����5U�-4X(��eF��{�iW��2׭�R�|?nz���J�̳;騋<�\Q_�-�hjM�qiZ�X�Ջ��ۙD�|�f��,��E�)fTT@������9�O'�����e�i$�b��������.��c��6���CH��7��I����$6o3 �J�9L��7�ӷ޵-�$bY(���ڭ'e9��|]m���s��Q��ꉏ.�w+�צ%�%4�Opy�E{LH��^�QR��?��­Z���8E���̫?!i_�3Π󓶓�,���)�%X�y�4Eh�D噎�+�.9�+�rD
+�����j|��S�u�hC:HB%��D�� ��U]qLD�TǦ>0Һ3� ��sT�7B_�O�B��$�э�}�p��T�Wo��d�C #��r�ϔ "yC����MD��o����<#5����n_���3#�fW�RI�/+X�X���%�?֤I��P]�ƥϿ
+�*�RE�j�*���V�f<閇� �z�(�1қ�֌D���WɫETW�z��{���':}�ᅸZ%��%�c�$�������<U����-�9�𤷕M<f}p5&1��r'1�u+Y�h+Fb�j��FL����|7+&`��UذN45�V�&#��j��rv�黸�+��B���,s�v�I%w^�$���M�~��� ��������^3����$i;�XL]�����b®‚]7���s�,n+�($��^���e: ��胁�.<.�]"����5�C��p��*.��P�V���!�����LY���u��������Tj�嗃=<S�,R���O
+ܚ�+�<n~�9\n�Z��Z�9 ��-`�|�bf0Y�Z�ιÚ�����q� ��H/沁�y3���y��m����WWd#8�L3�����z&ә�ʋ.�x8V� ��C��$D�|t\N�E�^�h:{Rp��5�'I�h�F��R�O�קA�D"v�賗,���w�t�����w�|��>cM�p����y^��?]��.��i�HzM_.��m,?��6{iz?4���f���क:y��!f��H\*ct��N��Ц#V-��:�Va.L�T� 2c��-W�7�W��g!�.X�
+~%F�.��og�������4��}��+��$?e=�ܵ����Y*QL�8L��j�{l�S%iJ��Q�{po5$��"��t����I�g��\7֕'��x����eM�W1��|�u�a$��X�"!ːPk3���������|�U�
+��s3l�\�����T�$}|Rk�V�`���ػ"F�6r,Y_%�_��b�Z�&��P�hnT�`R�F�ި�!�_ C���t��R��>��0�~�� ��_!@(�~ZщP~����Ր(8������ �]D���jh�U�B�Y�q�(<�J���+����yϳ�r�F��=աZX7�oQ���v \�Ngr0rH���ǂ��N�k8��=�WݬH�+'ټ�~mh�i����'��X���fݤH#�}��=�c�J~{�㨀=��'y ����ץk
+F��ݭ��68mz�@�Ӹ�õc&�����%x11�h_l3F�@ݖ�+�#fl�S�0KW��� ����S ����N� �ڐ����2��O^�S[�,�F|��<B�w�D}j�#r��Y�<�`����u=,G h���p�.�å�G�Xz��@��<sJ��{�܄傥W��9�.�V%��f{�0���FI&C��~�,��6ы�f���$����Z뽉o]�h E��M��c����yWZ�t�R�%u*�ŒC��I��K�S��ٕ �2�Œ��� S��MP�f�{2I�u�-��X��ǀ�2��޻�ƺ7�c�Ԧ�Q�,Z~PUԐPU���יW�Q޲N6o�Bi-����:�U4z\g5r3~`��MQ���j>���q��8�A�h����v;9��v�1�LQul��"�����f�K*�����Fp? b������"$�<�Cjt�����Qغ%Fbs@�p<_�1Q��E��h��5'p��o���G�`��/��x���4��-�/�ŷL�|�j�T���n��6�0�*C$������:0�U����G�mթگsP�r���V܃����X���xip�?��犃��g|X���z
+�Y��c`j���l���
+k�)v�7���0D�1�C&{'E9.P�`����ʖI�tj��n�|-�{��������2( �,��T���? /$ �20 :�e�r'f��m�Do���2�AjP,O���T+� =�py�
+��oj.��&e���>"�X��Yl��0a�����Yj<�����!�c��6(���.�߼6R���f�jk�m�j���(Sk����2�n� 4��>�ƭ#�B�2f �jҔ��_�]��@n��l�o����lCw&�"$��]��7�t9f$�^א��L�>���2Y��m�f��.�'�*OE�>��Pp��^ �����lnm�l�5�ZX���!�V�����#6zi��;�h�� ��'�摏�l�AG�
+]��N%f%̑����A�y��F8�'6ä�)�#]$�,*���Q �I��6����l�xy�A��fݘ��̃�Ƹ�J�.�#p����=�a^���7�J������ɉ!|��ՙ�-�qv�e���+B5�����m��]�;�����G�w�Ǧ�b�+�s�9�}5h�[͑5��m^�R��:u�P)��PR���y
+K���dg�A�7r�f�'$',SZW�"^��c��q�g�g�h�7E���^[ �N��َP�=�l�3�<[�������FB��tȇm�*�Y�ÇUЈ=#դ�~�x�Ī��;1WV��ÒXc���i�aK��;��T&�s�*K��S���N���5���z�j�H�7qA'(�#�
+K+r�ײ!P�+��ùv)�G>�J�"ϑ�N��+�26 �o�:���UA���ݳW�sh:.(������k�DЪ����$7T�3��z ��������i��R�/�c�D�P�Au�rm�O˱���=0�h|瑐Bo�ԯ.��
+�^�f?+�^�>�{��� ��:�t�U��SWǃ�ECY,�n��W���#�����`x~U�ĘK�'MÆk���L9޳o�&��h%��Qz�SQ(�s=9���x}��&D��>Gַ�&��h�6�u�c�o�Q��C�^�GWZ-����q?�h�|�j�t�}�S�Ѣێ�/���g)G �����Me�Ʃ����\+�:<~w��M�\�P�-S4��[���
+�q$��]-Հ�򙽳�c9ir���$�7��?�����VQ5�J�6j���.��jП�^&�1Y��|�a�7�,tl���qq��T��8�%xN3\t�.퐐�QV-�Ez�+�������04r��zX�f�#�}�hQX�5 ��5��F��Z�-q^��2��g��wf��Vv]� �wM������f��rnU�D���(�W{' ���C�b�!9�G����w�u���/����c�L�i��󧁗@IlsM)�%z�c,W�*�ϢC��r���GP��!䪗]�*�P�r7a�' ZFf�Š�� ����BW���r��W�.p�BS\v�/��C��T�%j{X}Td����gab��?d�|���<����V$ɧW�c��'Å$pB<px�t�^�?�q��o��� �_*C3?��U�FM��������&x+lLQ/�)��d@3 ��+}]f�hn��zԵCu ��]��5�e��s8�����H��+R�Q�[�G��+����J/L���
+��^�H^a+~�C�i�m2��W�tZ�h-Aw�[�K��Zů3�4����A�2�9x���G�*�I`Έ���>���ǪB�}��ٺ���ZV�.>?uv9��%�2��bC�5r�����G"B���5�P8e����C�7�y�4����Kxhe�����I}W0a��4�|�o��$�,�'V������i$"����kg�z��\[�G��t^��1�!+n������v�/��ruDdhN�����'��S��;�x=������}�/�_lRC�*� ��X��*�a��_�V�g�����h޺��.���шETMp�ev�������ۭdžev8S���3
+��w��wB֣�^����)l:Es+!! ��{�Jh����F�6/ķ�u!3�G��z� �� Q5��琾F�؊ҁ���F��Ӯ�C�r�!�u�Zr@�'T�� fTL�~�!�"�K���O1q8%�K�����1Sd�?� ��G���-��GT�;�d���V�ڡr�d�H�U� ���+v��܄��ʌ�2Wv-х΁�C���$�v��SX���\>��U�W��_�:��1…m�K�n��L����WӞ4 �)���jo���qw�G<)�h�j7�B1�L��L]���{�P[���AS�{�o(�e�<�P�y�;^4��e�ㄳ'{z��C���w��"��E�� I�p�m��e�\:�����E�����up|��[_` �(�����������am��{>S��Q�=�rq�$z��.fJ���U��~��#�}���F}�-_t�R�w;�k~\|�'��*������t^���?�jӦ�����Q4��ꭡ���֟�1Q��΃j1�E\7}+-�{{�Z'^˲��LG�1��h�fT�6�jA�RċJ J�����0�I1K��[+g\%I`�3&��1�Jԉx �����.\����\�Lb�қ����0LP螗��e���}���N`r ��z�`��H��VԜ��߸��4`��s�@��8N=aѰ�>���#�MB�|�l1����
+�j�p�������D4</b4�꧊������L��#�>�{�3��N��B�!E~xP��sG�0����g>]�o��fi9V1>�Ѯ�G|��� eW�2��XD�A��$� �� �Uh���6x����C�
+�n���u|ou�]����6m��T��6O%]��G q�g�K�V~9����F#z�B�>4�I�2V�'qӬ��yD�s~&g]���>��O�o7�S8��K���=��������-�E�!�sd|t�u�� ��U�O�j�v�� jd9�<��q�>������������)�>(�6���F��l�4Y��zHokSnn���*�_�%��$PH�8�r���8'ϙ�����D���Z�^��y�i�`��̄�\�Fo.;<E�P���{��[[���/R�
+I�8��z1�E<ٕ�X>���8%m�2�#]��¤g���[R� Â� <��/1.���w�# �ST�QDq�1\��-��Q�t��R%4sCG xn,���d*��+,ir��f��"r��N�U��rH�xz�V����ₜ�M���r�������Z~#�L`x�W�Ј⍃ �{��Kg+^�N#�������S/o!��xf���b؛�G����0G�5'�1�`�r�\C~
+I2��k)�2 kA���nVB*Z�u�m��t�Ɍ�…�s�A�w�p�$�1�vL�o\��_|)ވՔ\�S�A���Rd�`�x�L�/ ����?y�{ �E�|�O�Ie4�7v�vHRMK�|^�;�:�я������
+Y���l�́\�����z4 }W,@(�r 8��@GX[���ۯTׅ�E�]sM�K����I��I��.��HOGAZ@G-������Q�~�\��h��_���?����^�a�I D`���韇4c U,��™��z���Os�����΃�H4��ddPh2¹���͎��kR $��z�H8��{̔o G�<��A1=�T�Bv�,P�[@��c�"ho����]?�c�v�����L��D�,�e|<���I�~6&��5�zefh�h�Uw
+����}zM�K7�5�,ح���)t�1_ ��7�xY�����~[�-ASK8A�H���x2���m�o�{;�l%����V
+�� ezV������u����} ���9�D A��:k�z���;ykhb+ζP�
+����(q$w�_ yװ��ZS*��"�8Q�*�9ZlST����� �Pp�eFlhW��=p���Rш�"p+X��ڊ�
+״#� �]�S��6,��m�ܸ���K�6�7ɢ��=!,�'�f�r�ʼn��B_��x�mui��u,�&����FK+ɋ�Irٵ/e�2���# f ���cu]/}��w ��t2���U�k @Fs�m'�2�1�X_�q���z� 3�?��~臢n� �Ωӂ�_� M!F���Z���`b�Ɩ��~�/2����Q�ڵ��B�W� ;�F]����/��CO�"J�B�/�*��|LMP?�h�[|�C���#Jkƥ4��Y�`(U��=1�T�Ts���R���M6�k�y��faKzj��~��7ڔ�:z�D�7 ���&m���#v����P0}Y']��Z��Tգ��s��s��^�v37��Ct\~���-M�䝓{��%�3b�6���|�d�U5���#sU� �j����I}���M�T�_^�Y{W�]���߁椗<K-)ap��ʬܒ`s�<�uI��pS���5��P,�}�� Qy��%d&懸}Vޛ�Jk�Wi���>���VC����0�n��ݛP\F{��€&}zƙHx6��a���`��j��?n�6o_) ���vմ˥��8Svi�K��!��r���O��CR=��pM���m�2 [U;���}��5p�a'c�N��q`-_N�W���ǥf�M�!_��遞l~�a��}�ğ�@���s?�6?\�.�%���0��jQn��{����|�J�\� �R� N� GIͫ,�~Z^6�R{�ނ7uK"�ȸ���}�%\�|���~�S�kd����j;�n���!C>�«5Ӈ�X,���t�-�F�����ס􇼟�����Q�B�+�{i�
+ ��.� ���`��t���y�3�3����5���4��s�;6>������ކ�/=���O�qf��ucd8t�UQ��@�m5�<aQc�����l��!q���{��Ȝ}�O�����,�oseME�,����{���B����48�,)��=�n- ��٪ �����V�d���� ��F��e����AXP>�1�斥���L����0f���~7*ì
+D /vr괞��+��LZbfC�]�ש���W$��.�UB�G�s�; �V�Ǚ�m�99u�ɦw��M�KJ� �Y�$q��b�B|�8+�z��y�Y�#���tx �}��w���{�K6��LS����Sٍ̺���Gة�C;��$& �42� V�����m�d��L�f�j[Z�O�n~zi
+��TSz\�|� ����ְ�rV������́�"'L����7,~�h�<�q���hZ8
+�Xm�WA�6�8Ħ٤�q*��RuV�Pf�-�z���mgU��Q+
+o��J�����G�����8���nEl�ԟ�V\CJ�A �tN��B�*��N���fb+;�T^ N��w��}1A����?��Ic�B5�<7f%��#%Z�6ڀ(tc�d�(:0 �ol=AqN������^��|�� �=��R��^o�}�lUjQ�ne=�� ��,r�Ƞx��� ��;����;�ۼ.W|'PnC�s��/?��b�' ��� �L�k��᡻ɢ#����l��I��.��P�HG��4�b�����*/�^ƈ�8��� �ak1�����U
+g?�6E�襲j�s/�)sO"�݂�0��E������&� �B/e�XiA�ռ���8��0-�|^k�'
+���h��y�I���|�EIS��J��O;�����(�\��B�ҺA���^[�����N� �)=]��e�e;?|�����Ҽ��@L�d������U�/C��_�2�.��|��"ǎ:e��`I�COf��C���@�{�N�w�+����[+���E�Og�GB�� �
+�2� ��v_����:�Yt�>'�%��?/�;j��Y�{�bPd�
+o�5��;ʓ-�Xo'�-J����p�nƻĮ)D7GĈW�o,VBsGS Ղ� d���^ǀ��rĮ���JEӞ���E^��$y�^6O"��b_p,�&���?��,��m�oۤ�:Lv���V�&O6��Ӡ|��ŽƏ�3�ja�"i8��赦�ƳD�}YJ�S�l
+�9�y8�i���( �0�a#�R`;�ȡ̭�v�ҽa���t�Q�����]�{R�|�͉t>�Y6]���AX�Z?
+�����M1��R �X 1�1J�RJ=�]�"����֬i�L_�L��V��p����߱�XG`a�i�c
+.y�q�c��k��� ��V��'��� )����)W8,���V�è�9ȇx���@ n��z~x�[f��PI��y�k�1CR����� w����n��ʴ)�<�PE�ϗ��G��<m�������9�m����.ё(��B|��WztQ{�E���_7Y qJQ[���W~NƕM�. <��o�7��������o�+�-�H��bk��䩼ZVLVMư��c�􄲯��D�&�v�n�����v{�g��v9�*��#�"��_o�R9'"2�=���olaś����1�@P��)��3�7H*��9����V�gT�aD��ZT���k$t��ꮘ�hp~1
+-�� �?�����I�{!�ٝ^h#Q���q(� �q�ڑ��?�*q��oY��5�>v�qQ_^`��<Z���c|[8)�S9ԂV�#�~#��z���cSQ��Ȋإ�������9&�^�%q4V������Pd�����%; �
+)���L�'b����Q�:0s�T��vX���H,40�Ԗ�������rY���:��4�\�O���.�mXM�Jn�zCV5S�q���`���`�1wk�W�7�4�� N*1���e3�~��84��xgGg�%C�d.R���rCg����<�Zv��[Q�V Sa�=4���;�7a
+:��_���71��n�[
++z�-L0�ݑ)�7�T7%=�fy���k�0�>�� ��{���u]u��6�"WA4�-43��' ����8�Vy|��tJ>�F<"��&"Q���iם���~}�}��T9����5�!P��?��,H؎I\���H�%��G�~b�K��m�^s���~0�/#Zֽ���峞�u�����v:�!Q ����z�^����*-p�4md#�]S�<�R�!���?QX (s��G�6I�ǩ�7��?��l�t l<;����0i�� V7f�V G,��t����|�>�r�"H�.@��HB���o��/N�Q�Y1wԥ�.�R�\�q1۠7K�X!���x(Ŏ�y�*�rQ�L�9�G�6�w�Ɔ�tƚC��2���B�*X/�L��<m��7����}9�OalNLԺY�Q"�?8��ߪa�F�� �D ���D�-s�/�mm|��1��Ps9��0"�Oo Q���/��m��X�K�m��}i���q��u��<\3�b �˸�W��Ω�l?��:"Y����WI,�X+��)��U'$���0�#&>��^��L��L�x^x��]0��-��:��Q�3�]f�0��R2[G��.;��>X�r6��K��Z� ���!F%��:�)��\�B�l�ѕ�P8�r9��2 =�룄�#�`�:h�J_S�i�[>�G@�Z7[�*�M.4O�c�۟j�W§�ϙS�㵘���3N�ހq�UI�E�C��=<Fwo��z9� �3w������4�� ���P�իKT8 �(Χ�8=�����'T�A��L�yG�`�-U�\#�u�� 5��s�G�vQ3�r�{�u��Q�͐��fUHT��~"����X_[>6.|�"��䋟�Mǜ�����^Ɖ��V�� �^��Jt퍏���u���A�r
+n5}�!�/��\)6��|�o�{�L;1��C�8[�˖־���A�m���C zn�o�??J�V��Bح���<�E{)�eCPK�kL���G��\+^�U���+��yN8U=bI��W��HM�˨�L3_�����<<��kfL�`I|��g[�(�ţ&H���x��|��;�ɜiVB(Wb����w���D���/Gޔ�s߃Ȱh�Xјr�%��W.ܤd9���F$3$���x���64n� �I�p/w�doĭVY�E��5l��R���FƢ!>��z�Jg��+d�E�򍬢����0�F�NӼ�3i�`����X����|X�G��?�x�δE���nMM<(>; ھP�ص�Ou�V�G�M����c�#�`�↢�`��#���.S"�
+t��v�Cy�Yv��w�e�[�x�5���6� fL���92���;>�R�6�� �.#�nQ@_)b7�[a0�����@��pa�)�wU��oeG[\ng�>;O���|�,���yw9�Top���%��l�싅+��� �EhW� ̰��nQRܴ_΋�߱ޏ��y�s��w�V?*��z�"ق>T����ڧ;�IM<?�'�TU��HG��&S3�S�?!��Rntآ��)Lb���\H��ú|5�v����x�= ��? 'L��vgN�ƛ��<�d+� �)�X��d};ic5C�%��B��T��I�p��A%�n;?)����C��S�v���9�� ��d��S�Jko�y�$"$z�Gy�B��x�d;b�\�끁�����d��r�V%� 2V��%�}Lw��������B��%�V4f%yѣ�լu���џL�'M~C�U�B+h@�FUfa�7�l�|������|A�@=�.���/�ӲI�t��ĂP�J�?kE8�� �P����g�MӤJ,?�]�Y�/?��'��&�է u/�.��ͺB|�><�t�����z�"}i�[B_�,�c�����Kg���ϦQ�{X���y�\$D8�,G�Ҧ�{G��k
+��J�L�t���q���f}�n���1�k�5 O�;� \�~t��"�8r1V�x�t��A��z���=������j�<�?m�����@ ����=�>�4���Ɋ�S�=>W�] uA5!���M�n W�l�&�d��w�)� n���L�&��1�4��7�����Aq�$ab�s��Sͩ�hW�e�� ;�˅l��m�.ӊ(�h[!��:»��R��>��3S; �` �`���*��M$Z⾽�� Y�v���c퐽�� ���2��� ZH�����*� u�GA�1Q���VE�‚3W������L�B R�ֲ��6ӄi V��j�-���1�)�t<̹:��2`�P*�R�p ƱFN~=�u��� 6F�����lj�64՗�nrȓD���X�0ހ.�η����K�Rt�ڊ�N�*P�L��C��ށ�4,�k ����d��0Q�l��Ua�Y+ʝ8����+��/o�m�O(���ַ����� ��A���� ;TD��i� өI �Q �b��س�+]ɜ˓���f�����DC\Wëp�]��Z<5��X%�����i���x/��<{J���0쓊�>i��Ρ#D����.�3�d?% A2\}v�%�L�,q̋��s֏oq���j�Z�l`i'8���4[νz� 7������Ʊw��A c�` �V� �,nY��8Wj�b�1�����P(��&�^���s��>��l� I3��+\�U��Sܼ�a��x���:�b��8�$���|rk�R���H�~��q-o/M{޸`��[��p� ���-Y�߳�U���UHy{�����Z`SI���2�d�Jv&�Q�}*Žq�i���? {����i#d&�l]ʊx���ߙ�˶�3��G�� �fU����N���E�.Q͎��T�p������Ά�8�}������͎�������v�*
+y���-�"���<�g�*�uyh�>�ɖ��a�4аa�D� ��d�1�I��~������Fv��Ꮽ_�y� %�Q��J���L��Lq�Al�ZO � �Z��O�,/�����!q)�#�Z�g"�BW��B~+ �C�jEx� ��UxR�I��;[����V���Bi��D<Y��m~6��P�o�pp[HQƶrΑ ��[�T�ŋik(����z?g�_��ar+A4AH�g.��u9f���N�e����z�8@de6�G�UDHv�M�?���-��E��Z{� ~8�/�7 �Ě"7�<G�i#��b���.j��S ���f��3����{@���H+@����ȗ�9NG{��p_�N4�Qֻ��ub%M]%�L�_�o���o�o8�����uR��ݍV����K�w���35�6�@n%����XǗ�.?�A �����A]?콰 V&Ë�v� ���~d���P����JHP+�aA��xrM�(ٚ0��`�t;�w!
+K��:�������[8� ����/���9�3'y�'=im~�y4!a��EG��\�#���R���v���{j�%�F|���p����� UU?�T�[CևKݠV����r
+�-(�ax.4��k�r1�ȟ�*��q= "��b���%�{Q��3�'f�n@�!RBOWXI��� @� $u���\���-8w.��*y��ˎ�0��p�Xa����Â�ƬܲA5�i��1S������:������YF�r��k��=;^S~���~��5�N�,B2ª� ���u$�D(ƭ\wM�� �#�E������f��rT�x5�m�$5�� as������˔���'�4�����L��j���m����q�:���snʃ�� 1�w�
+�����7�arw 8e��r����ug��3��R�m��/WYL7�Gii���2�"�N��JQk)y�q��Z�G��$4�g����{GY�w�r{%+M�����]�m��0�d)���ْ�N����m��@` T��63��˪gbņ=� >2s�YS3 g����[N���N����^�� �߉̀���-a���4���M�G|�8��6��) Xj�)^^�"[�B5��9��Ja/|`��yB-��f�sp�{�������鐜K��6���_��&:�@��3nxJ�jb7��i*��Z�B���у.��dܽ�6��O�r�V�p�<fU��V�4T�;�+���jv� ���u������=� �����+p��:{/z��X�P�0�|�>����Yx����Q����x�TF��Mm��A��_���צ�kE(�ېf6���
+k��j�+���������!o���I��K,*�p�t}�<�-����O���*�M�A���d"j��]K]r��Ͱu4oҕA�|���r�JSP�po_���d��Iw�h����i�����M��]��&�|�uhb�qt����!*�#P��U..��©7��[��o�;ʪ�PdF�8�7]���u�Ӌ,�!dts�;֐�ѭ7�Fδ�4��@�u� �N��C���oC`~�+��;�I��6�< ��5��c�h�)X��e|�~X����� e�3 �}P&���k@��/�{�"�~��OK�o[].�H^K�b��vo��A�K��>M�+��#��OY��'���W�M>Dneӵ�cI"f���Y�Ɇg��<,�%�[�T�;�w��*3���G�+�)��Ј�D���;���^�qM����]t��4��UY�4��Fe�o�U�� �1v�8� �aRH����� <��x?�B\����>#�X=����y�O�a�
+W�kW���ab�Pej,��IC���t3c�y/�)�{���K�,�Óx���=$��a��4�j�~8?������{�)�%m;�v.ӺϨ >"}��jOA�<�ꉶ 2Ƴ3
+f��5hڸU�����-d��*WL�4�R�|m'mx�j�v�pb�4!X2�Ճ�6��5��3�IG{���1]n8/��i�WҜ�+���\�%�JE�+=� �&�x� ��P��/j,&̔�]q����i:}#Z �C>�O5�{���|��/��\��P�+�Y(�Q[����Er�$�#�y �q�r&��������c��<,R�' �$�Ü��^4��ix�h��g��M���s��?�<K�E6K5#����/&�GB��:$Q��>�� FU(b����d?|'�χ�˩������P��+��1H�ЇC��,�������f��s/��0���?Ww@˰鳃]�C�7�6�QKw�[���5T'�����E,@|������\��-����0�3��$��U��U��L��ч�N�?��{u.�7�KIR�z�������׬�+�b�χ��2��ѩ�O��`�GC� lb��Ac�є#�N�'CdLCO;:�h ��ç=ŒS�z>�rG� �#�.���Z�_-
+�JD��;5&�k�
+5��pp�k.���΀DS6���|<��u�4� J�)�A�dx��OO;��x S�g��FV��K���Q���{,� 7�D��ހ�"� ��ow��+[�cr�����^�fn���FFi����7z;;���E���y!�f��� p�²�z�(���Œ&h_ �xL%�|<_$t%�UMw����<��m���2�EZ�|�˸6���!=��k���nQ?����P���7a2��(o(� F��fz�Ɯ�((� ��MݴD[�c�%�}�Ј�}��,_�s� i��yH^��g'�gw;=�JB��E΅VW,�`p�l �]�x5UXb����J�� �|��l���N�p/Q�Ct��,�٫F�S�R�톁x���3�M�����|��/ˠ*0�Ǖ�T5'b�l�� =j����"I���S����^�� �RD������� �P8 ���O
+�%�,�uqc��(��
+^���$N��ky����'�e$�o����/�^�0�h"���m�A�!Z�S��9Q�w���͟����;��ɳ��(�F����Rᕟ#ih%�k��D‡�.�|r����A`��X޻e������ ��a�w����h�ڋ��vE>����|����%��&�jYR�C�d�k��I���fح�� ��m��w���N�2�{�
+��Q��C�1�@����<#܅�% A��K �E/ *3.����Oq���W��*2
+�2?��ie3�j�Y�0��u�@ۚ��#b��k��Q���"��.���:>��������ؙ����{Ȇv?��#�q9A���;�`��\�Ћ�R�8���=�꽃1@@c �6��|&��玹Z�A=MV}��|��[�I�/����X���V�<XȈ_?}V#CC!�ˉ�Hf^�qu�KA�Y; ���ş��K7d���=.�EJ�z�Ufˤ�ǻ�����҆�]D�b%�7AԨӠ�H+a�<)8T���W�7�9����gʈ��
+;�����j� {-I��B��>T��e�J����BOm�h������FA��<)���X���̴�Jy���v=�-�����D���\@��@{�j��s��b�N�K�dSYܦT�[ps� M�"�d-sfp49�����-���NJ�I �E)�^�dN��3s34�& 0O���Ʊ
+j-s�O��l˯K��KS�Y����J��oWqt�Aր��*N|�JP~l��0�5�z���n<���6 n{z�ax�-Hϣ�1��c�C莦*,�ʍ�Q @�ZV[ڒ
+o�TLߔ$����f J��G8%�i��F#C�{$m��&���>Il�1cgRP���f�m���WhdN9-��jKe/q�e�s�t^�;-�qk� `�%�r��v/y�.��{�@#�w�֙��̪מK> :<�c����j�k%L���$Đ�e(�k-�M�p����� ���7n �[u���-]�%!o���X�C6p�J�d���U�����\P�hC1Z@07c���߱�(X�[�0S�gr��Kd��v�'BR১�֎~��o��z։�KL)�H���&��'�C�8.}'"�bk�E����ݫ@k�BM��CZ� �@���,1d,+�Qze��9�bO������v&~B�M�y,f���q����.��� �G�b�Gnv^? � �y2|h��O��S�|�܄uǂQ("e]�l'`�]�Q)Ӥ�;�tCzi�� {Mo�;}1�jC-_�A���8���h���9,����g�U�L?���&��U�]��~E+nB
+8�\)1l��'DW���5E�n< kA7�e�z�a7�eRa�&�$�nz���;���C3��>�~@dds)�^����i�=Œ(�s�#�T���y���t(��tT���@w ���xM |�n�K)�����>AR(�;nn��RTE�m�]�$��j�w�̆$���jɸ GN+�PI��t:��+�.���؆�upF$!:o���u�]?5����Q r��C��Y�ֵA�)Ȧ�s���ySS���E�@�%>O������KBr�c�@衦!-iC�V��Z/�����vf���$y'x��JbTe1Ekvo� ��Xkk
+�j���������e,hѴ�����+'g^%.�� wK��4�n���XEqQD�<��$�\��� ��n�q�L��"��8Y������n��
+���'���}���|X�C/0�FQv�*Ma�ڊ��beH�U� �Nv���>�O�F�� `��pr���������8د˫�Vl2��\�hl~�X�
+�P����ϓ���)U>f>:�`�3hb�,T�;I����գ��ET��ʫ�8�iH:ֹw����]���������c{Rū��C�;#��Ҥ<:�&A��<u�\�$X9���P�",�)�#ӌ�-��{�Kn����1ID"���Z?�d�������0�Z�pW��i��] ���0�{q90�W�2B�;
+��
+�NhF�
+�L0�e,lӝ�X|�y���}a����(-5�q=v6�L�����W�ۋ� T�~&��Uإ�zpTژ��c�1�|�td�`_&Y�;��5?���>��u��3�����v�
+�춿R������6�#���xw� �H�h��.Ҫu,�/�?,Uf-8�IhF��ҧ��_�&\ ��B�4�G���Zf�l��i�ngp���|�l�r3ܨ(p_h����woR�����9�k`�T�?��țV����I���s]��,�Hd��a���K��ј�M�Z g��i+({�xB[)��{�,�'Z!��/[�̑��� W=��G���"S��Z�� �/ �Yі��:Yu��ȍ/!6�3�`?�d^ܮ�v�0�E�& Q����!Ч�ĉ`�fB����R!�Z}f�����,Ō��4�`7d����qϸ�\��g~,��|1&+�݆� ����p��`=de�f���?tV����1��%��s%� X�7'�"��QeSz�b���7J��[���Ԡ�V�8 (b������G�*��^-��9�0_��٬ZuuO���_I��l{��#}Q�$�M��`�v��n(�̷~��Rp�#LR�B���ɋA6�$�;F�P��ͤ�j:*1=S[���k��?j�R�i�q�S� ^����٪�e�z�Β e����I� ���\�.�H��_�a���(�v��m��}��C x�1�0��s���s>���IJ1���M�~w!�O[�P<:�ϩS�a׶����kh
+�e�k+���} �tp���VG A�@de�q��b��SO��5�O��L�0G��;�A`>ɝY ���Z���<w��X�)��A䘖/���$"�a����`��B��9jF�}�.9�Q��a9�=& �C�� d��B��b����?VR�4���(��!&^+��Y-���fqi*Y� �i����M���"�{����*؉�o4Q����x�\)��YҀC���,�G"�B�+9B tg�Wh�F�%�d`�+,��;��xiQyǐB?�;W�Z��*ĥc�K��_�%O�^6�7+���G;�>;(���F��CF.L:4U+Bv$��}���xѯ-�{��p�n���"�~�WJ��1*��_�a�ԉ7AN�����h�c,�r9�����N>BK}B;�5�)yo�8�& �-���.r^��=>+LG�1��
+��MH���I�X6v ]�òn&#o�z\���ҡ�§c�+�6�s|m�ڃ
+�KI_M�
+��L��j�K��{�AElG���&�iV��8�^�|dt����7�ʜI,/�:��|武�r�$2���m�e_���x�΄,j�M���;
+ʴ�9���^7�v���.�����^�i��Yg������m���@5�@��ٻpFri��9� �v�-K�\�c��t��3�!�䉂�֠��L_���/�ba�_`b���>����1|�� B���}m��a��g��Y�3�^�ᬱ�dX�/�<]�R�f��JSt?��+Rzu��\�)HbD$�y��GDPG�>�.�B�v�Y���D�9E��e�����y`hJH ���D٨��ۨ| ����)u��p�?Oh�Ʉ���G�[+�z�����E���E�f����>A�3�4~�tQ��B�WK���2����"���t�f��g�X3�T��I��EK��a�72�m�T �&���d񷓅��W,�Z{� ��X�{�Ӹ�D^�g,�ʆ�  kx�]���=�N�% sj�0�ͮQ����w#����f��������#2�\w��4ZA�V�����w��f=���X^b�^�i�T{�]^��\�}Qe�D*���$=��Tl.��X�P��i}����* ���Sq����;����/���:c�$9X��r�6���t���6Չy�����iWܪX��gj�� �Ĭ�?W��[!#K���[�0?��U��1GӘE�o��Q�3)}�)�������+ �E�\'�_��f[�څ�zc(sɶ^ ��'a��s�ay�q2E����@5͡�8f+h�ԁB�,a{�L�}�5Sd+�r���iɇ��n�Qz�F��LZ.P=��:%�,�r 8��ђ��EE�6�AO���A���x�䕻�;�0�K���%�
+1 ˴S��J��<����8���/��(h��u6���-��Q���K���f�����s�Uv�8d�i~�����Dh�,q5³98��b {��M.�� c��/������F?.�hC�\��84�>>�8 )C�Ow܊���ϵT��b���� ̣#��z a����|��h�[�� ��>eϤ&?�1�ً����[�$��ʚ%��A�L?0���X��B�y�@�����l�~I���c?�/k�\`���� ӨY��U/����18S�ʑr�������R1���/��a"�`>8*�'���x��]ҨllЯ/�����S.�W����z�%�Jg���`�U�����>��d�_�6���0�$������@�D�-AIӹ�-\[@?����MY{4U3����$���G�ߦ:\�N�w�@��3w ����o
+��Q�n�4�(N��?LFO΢u��+,�\���L��� ar}<���)��Z���#2�`�e�%�+��M`<ͣ�)������aT��W&
+!7����o-sq��ڏR�uq#*�D*���gI s� ��:�t��-��(t�)�x���L �!X�L�+�B�� ��T.(�� yI�R���3/�~ S�.W���CH*�y#j���oG��-O�>4gn�RȕkLE"��sɓG���^�p�7�p�jР�Q>
+0���meciY������V�М�����$9X@|p��D�����a�Dَ��� ��A�B>-9�n��+��S�j sϴ ���6�ПE������J <�=�FI�o�-�+���v��<gz${r�m�/���1}���GZC�[O��s�3�nc�K���?uJ��=�≅����_�i'�9�e]I�0��� HI�0I��1��S�m�k��(N�p=ѼzA`]����)�=Iaa��)Xy(`�6�]�5���$�{����}�nj,l�a|B�#b��^�pm��
+��c���q92�s�t�q�p� l����ӽ`�� ~�O�4�< �8�S @AU��cbr�P�%�״��a��]���C5�6<�UDb�D�e�z���N���,I%v?�㷘���K� �a�VO/���\�l�^p6h���>5�_z��|�QH��#R���������V[�K��u��AP���tc*��aa�${�H:�]�� V���)X���s�:�۽�5!� ,A����~F����Tu�_hq��9Ss*ۢn�!��i ��b�]W�MG�! -�� ^� kJ�W��b�Z��$2�������k��a��ש��wş�v�Z� l/�q�m��!�B�t���S7o�cK{ps:�q��bU#����m�@���f�u�1���㽉��+��e��Cmq\T���oKK���R"��������_z ��)�@ؼ���3��s��Y����0y�������q�ҡ���H�;��˳���9�4K��?zᣅ��;�ҷw�=﫛0m&���Y�XI)� 7Њ��3�p�J ;�����b~�� !�Cɭ *���6m�X�*�s�%���N*�E��L� ���"qs�vH{5�!��4�t�ĉ2�8�2��tB����( ���0)he��b[���},n�(�D%�sP$zu}��\���b���o�M��rЂ��(�*���|"��iJ��Xƴ$���M��C&%7P�����P0?�Մ� G���/��DKu.������&T�(+<�Tt~��I#��N�N�u8aOR4�{���K�Q���_�z��8�^�� ���P� ��Y�%�K��i�8C�_?���V!*A��g<׵��&"{
+��)V}��yV��g��I�BD�(g ���-
+i���gO��?x���ΰ�/�Q튵{U���
+�;n�t
+��w<R��F�YOB:9jq���[��>vF���ۿs���Meh=�b����k���!A�Q�6�z&�B��\�ŝ�ЮH��>��:$�(3�G��:7�������q"'@0>��3ݻ�n��=v�<�vxOq�*�V�*��2=�{�%��{�,�ZyF�ц� I��k>��ҵ�"m�=e
+����n�H~w��t�U3}=�O]l�1������ט��
+��ET�+��1X�����J�E S���\�;@��3@ ���p2'`*����P{�avO�»��)��וu�j�6�m�V��{`8�>���6�Ϫ= �d��/Y�2���b.+��D��]K��@EQp!�]�(g�O�Q_����n�(BC���%r�,��%q����B �0AZtԕ�ئ#+6#gE�E��d ���]?�j3�Y��zw����
+W 膑�2H6I_+a
+Uu���,�_�7�^V/M �3�C�o�`k%���ܞ�HZEW��3�~#�M��s�B�]u4D�'�������N�G�m�����&�@Y�u��l��bk/��M��M7pv`���ad9%�����I5g�gRh����Xŕ�h�^�N2rh�.'�]� "Ks!J���B +�vw��Lz���s(�F��l�_Vi;?�ER�90_N�}���k:���2�� P�"���L�lWv�!i��0��������������a-�+N� (�&��[�h �(N�GC��7(�P9��q�CS�yXK�� ٜ����/"0������:�"����c0�ۈX;�p�e��O� ��<c^4���NaUڤn�J�}����5,�/�f�*�?qG2�������=����-��כ!�I��ķv���h�₥�iR؈eR�_4�Q@�Kg;�� ]%��`�d P�f�����O�Ƚ #��iT�γ��il�a312١��l�_��
+�E����BW���q����Ki�/1c.{}��/�_�T�z��N�7x��1���bD������ �Q�+��L� \��Nf;�a��4���R�A`Aodi��B�p������J����g��>F�܍�ѝ�i�����T�Z�T�1r�t����D�5菂�Ot!���8A�V�I��2�ABOM:b�g��x�%:�b{���� ���F�7�DJ,��Q �}����I��`�
+-�kkc��L�1v�ګ! �f!�RU�"$���0��f�G*.� ]}
+��$�V*���l�6q�����\�v ��Ȝ�A����CQ=�lq����r��=���ڤ��n���/:�k1.� ��V��y�d��b�zx1B��f���&�A%O�:/4+��3A���K�'~_�k��ss�A���D���T-���� ݷ�N�zS�����0��F��t[�J�LcHF�2�F-��$$��|�5!&��c_�M3�~�E��Ƙ �ˤϪFdqk(��K+��]#��?.h����Q�L ��,T����l3��(��e��-H�j�o���v7 d�<Q9�,'��T�XXE7"t$j$ 4����;�|��Ɛ���/=��];X�gl+��� y�m5���e{wg,abj��oZ�è�����Wr��iK$'��o�n����C���D��֨ �$txo�a���8����]p�Y-�u��D^�u��+!�p������ =־NM�sw����j�%_�T\/���O���,g��pu�u��N����At�`r5��tj��T�V+��A���*�t�ɇ£��\ﻘ蜈}�Bq$�٣�5. * � 2U��h���6���>h/�1p�*8�on���8T@j��]�nu�:��ڦ�?*�6 ��]�!����e߷u˲�I ����'_t�j�c.s���*Z���VxP����[�:q��}VLw����q�n#�
+�@B�AH[̍��TV�N��#�;.^�>��ω� ������I��i���:1l�ڪ���>2d���aT���}��!�c*���G��L(�?k�����k�. :��I�ȳ���9G��:�K��[d��8u�dRË�=�'؟Y��5��<��R�� �����K��W�0.1�)����m
+6v�K(˛+�� q��p ���t]ުl�q��3N�?#�|N���v�k,4�{��%�e|��*9��y�-n�H\�ɵ�hs�sO��ƧA�xM,��݅�+UC�Lvd��
+��s�.�MT志x�5b��x1��xV��u�<�2���&�)[��2�KhS�3o�4Y�>���/w��c�
+����6��'v&��R����`2&���o�#ƥ&���*��JJׇ�5����Y�V�sŞ�1[[���{/���T�CD9Ӎ�SW��P�(�� R���.\>26��X��K�urg�a�C���H d"TX��+D�0�veRj4JA�u?������;˒Z7������-vj��*Z|�!��-��U�\zS u�y�I���9~ w�h�Z3;���"�K�dX�Kx.��o8< u��l�kڊ����pΏ�!���z���w�J�l��u�)�+�^u��+W�&�D����S�—VŠ�k{��j6�G�g��$�tB4q�%A� `a|w��4<�hr�D6u�WS�h�H�:g����M�h���^�zc��ljJ� '� khG�`�W�mx�n����w��k���!a��M�Ê�]�Վ�r��1�n��"��x�B�!�7��İ�=����fzT=o�(�?[v�$6��s��A��F@�aJ���l<��q͘oQm ���7,���[X��7.C�܏Y�ȪI�~��+�Y�5��|o�ǐ��#�c{��+a�)�]�/�|��K�/�T�v���h9�>\*v+����FM9�`Ć N��Kut�Tv�P qn� 1�R�&��S��l�R���/�Fw� �bmuKHh(G\�-ۻ���v���+�0���r�9)��Q�M;�.��}��F�p�ߐ�*�(@�� ��Sg
+zx4v�\�P�׾{QS<}(Z �����հ���Pۭ�H�a��`���5�-CǪ\���$��L�y����!1%E��G�Ԇ��5P�u�����o������B�]���?,mP[߱7~��^/�ٿux��蓮��-�=�u�~�{̦�C0'��hx�1�?�� ��wtY��4��5��{���!jStb� '� a�h#�k�Q�Qυ�PlP�ȵ�Ǩ����"�D���������y+����݆;jR���I�;� ����/�O��=�Aa����<�D%�Ўhrp��
+�N c�JC)���[��xc����JW`�˰����pFe�uDY58��<�@np6��U��'ፒ�آ~�^�l5,����}��/��v�r���Wg��Hρ �S��ų�+�����Z����ľӛto��f� r���$�^� ŀd�+`��IZ��Ɉ�Ҿ
+���?�~uc�}fa�
+l+6�aƆN&�:�<��|��jMY��x����j��թ%W ��ڸ�&�����V+��Ze:K�֫8>��ZmS�Ӻ��k��"�c�����@�L;�L��5��j�M 2S'�"��b��i��)�HV�oTJw0`�oKI66V-|ӎi� &�h�pa��E}��3��X�E��|*=�<@��/ǭjY�_5��D#���ۓ�K:/� ��{�K�����r��GAŃ!F ^ú�\7�M�`�~J�F���b�ty2�õ��k���d��\ ~6; ⚰$L~���R^�xó60v�� ��ƨ����L�Dڀ]�؈�q�{��,�Ǎ���+i�zu���L�O����P��y#��,K\h��"��b׷ͪ'�Z��n���������sQRZ�^ҎC�|ѫ�ޔ���~�8V��Ӌ@�:J@�Xڹ8��z����� L�Ot�TF��b��b2f��;\��1e�J��4�o>�r�.v��^;�u����y���#�s�8�������4��#���b���
+��<��k�):]��[��qh?Ѣ��>D�V����K�O~�\M���B��l(��ȜqN6���aL�����Ai�FR��3힒�0��2�#���v����mTid��q޽j� 꾯����vP�P��x�iۦ�ڟ�+�!��7�JiD`u-a�wn��⧚�����w���Ԩ��3��qp�N�aM.˼���XA�� ?�<��b^�i�0��[Ô�W�m�GG�`Ai�c�`@zJ��fv8����F��2���C�a��$�Nbڕ�sjS)2�]{b�)J��Ͽ; 7Ȧ_S)�v_ʊ�8�p5=>ۮ�����lg��X�<̀�}Z����E��Ck1��V�9/]%��y~��!�~j�a2#4z���o���.`B�.��F��́51p���v���e$H��V+{��u�Q�I8���E�Uzby�X�u��6��*To��,
+o*� �W����f ��T$�y����s���5)T�!��;���i�P�i���Ⲯ�F_��H̡ 44[����:�2���k[ � ��n�Z�SD<~���k�o��w�.LP��M��7�7�-6�F�ݍ^�ڠ���`���ޭ�оG����q �=Zz� ��Φ�|s��T)�0�z���Qr�p]�ܚ��d�f������h�����::fャX�)����Qν;ػ4)?
+�P�[-4�k���;nۖ��}9��9VH#�W�` e��Z��ĥ_��!�w���L� /�@i���Y�D]WGr~��e�U����2�<ID��NG_(����4(�Q�b����"~ڀ���2�t��X���}xS����"q&�RI)�t���O�F+p{��i�����OX6\L�]�χ��p,�E|V��n�R������"��rY��ϑ�
+�C���*�(}|�g�P�:��]5hJ ��>>��k����o;�fP�*������I �k��)��x�5�gc �\�h�?�_� _��'��H���)��-��EVoP����cd�����s�}�� �a^J�٧�%R��M�w�m�%���|jM.���]t�]f�PrN:��$�!����)-;9a~�ۛx�W���4f:fC����E�7/\�I�-pX{O����髈ҳvP�&�2�F?}�XVq����1� �|��5f��8꽓1H�Z�f$��b����%���k���>"��92i������}d��۬s��ZO�-T�$>0S��آ +�jF�v���na��:H�:�&+�ǐ1:����� B��P��|��G��N���"d��4�O���� ��Rjͣf�C�z�k����%�k��W�`,�`���q͊Q��"/����� Ld�U�9s=cI�uq(l�����A�-n��ĮH���� �~�7��.��A�ᦋ��AÔ�Gp,�tL[���4��%l�.��z)��ݗ�kNX*4�~]�|sfj?܅�7w{�k�f;|�q>�����~���H�!����q���������I�ek)��b"C1����t���"Cvc7Rr�|�X��nG�#�WŬ�t~:�.t[Zُ�E���������H ���m5;S�}[��V�5w�ƫ𙽗#�O��yt}<}!',��0�Lx���ѷ�]��gyIqe���F���K'�ѐy�_��ۘ�bq��z�������7�z�N��w�>�, 9�/������4d�矐 �ު��p1��GK�W�k�U��{k'���" ��:U��{��4ь�hg��� �8���:�V���j�I�R�@�*��9�� /���r�� �*нH�z�'� ƪ�����5(�*&���u���VB�d/w�B(K� VG1=2j�Wǘ�\Vũ׼�pa��\��`��0�c�3�W/N�l��
+R��%B�5q�;����4���j�_�J��B�k�[c %F�� 
+��5Ns ����(�u=z"u�����&����o���,�0���,�5��:�v�V�l � �$P' �_��w{9�Sq���Ur%Z'���MA�†&� v ̓�]����&�!�%+���
+���];F�������o�M���d-���CnpY�*O�U��D%t)�����V%����4FDvQ���"�cN��T���.7���S�SsZB*�����(�%���C�4�,hԖ˶ZP�E��Ճ�[��S��5��|�,�uDQ�A��B�e0�1��U�?��j�5q.��I~4T�.^_ �]�
+��SF�y!5, ���"b��k�^Gn��F6+g[\��ߞ�,}Q2��ͫ�Z�y�ѫ zE#�K<A�gSU ��}�rӆx����}��Wc�W��w����ʬw|����ꗧVA�<�B�+ 5��@e��oj�������"J ��v��X#U���c��\�q�-mJ �=�&b�=�|-��T(���N^~|�r�Bi4:u�֨�:�6����.�y�Ĕ$�k}!iV�bH�E����s�8;�����y�OP���t�^�����j�A��ZM{3��^�*��e�bղ��;Y�=��_n��iN>#�f�̓b�Ǧ�m�4>��D��!DWȩ̉P�*6�O�Ю�+_��n�H!A��n���Y��������U��jK#;�UhG��p��/�;d�sa
+��s�V����NCN$ħ��l��A*�cH��B���~�g%����ԛS2Ϝ��2'Q��F��E�! ���z�����d���+� �aU�{������ڜ�e�LuK~;�!١�`�C���ִ��6K�����Ç��f�q<�Q�o�M�x��%$�H�a�\�Vƒ�ƶ�����f���_rw,b��w �ݖͼRA�� 5�"�]`A����A4����"�[.��N��2R�i���6B��s�Mt �Zw _w�)� w! "X��E�BX+oV��!C��<�/Qd������~H�Ԛ��a��#�������r2��Y����Ѕ���=�v�~_'�}�.|9��7�c��������N$lA��{�5�`�OѶ�S��H���W��*�-o���@L�T}]�")�Rl x '����>Wܧ�Ox��a`u���o0�����9������p�����K��F�~e�^Â2�o++�ΰ6(fR�|"�}
+�x А�<�^`]~J�c�p]f��ƅ#��2�؟(,J d��$@��<���cuM�5viE&7�h��Q�،���T�y;� ��Y�?���J�s�1y��$a�^��r��e��G�)J��f^i�� ��S��� �tP���$���$���^�-8��:�iOg�{�r'�&Y2���ݿqý%�e.����G�r�3�~ �HR��P�U���vγe���' ���8)r��,�:P�WEP7��$�P���'A�r��ّ2K��^�*��1�}ڑxQ;b�9BD��29hJ�� �a2?���뵏���W� ��q�d���a�V] �w�+�^� �� ������d�%<�msc��e:z�>Qau�U�)K�eA�f�B�y V��=5���^5e�A����ㄮ��� �Y-0��z/Ar2*�1��C�R}ӹK��$��q��d�ƫR�f���!@3�-f�+�4��5�J�$�Ҕ� t2��~̤�}� ���x�u��#�I�����"�7��+G�5M��U~� � �9}�
+����ڠl\o��4�? �~�P�~V�m`aqjM�Qݖ������3�^D� ��ԑ�|z%&���d)���Gwۼ�<����m���殰�W���27p. �����j�A�#��n�Z����@a�̟�� �gC��+�vV�гng��b�������:f�D��k���JvŤx�)�[��ԉ8?+��c3��E_��R�!���4~�if��&f�.C��g޷T����_ŻU<�Xk�4��/WZ���}�yX�������O���W>�5�c��{�i�H�+?\$vk�7j� �5���Ԗ�%mY�q� A���{I��/�e��küp����fl*��7����I"_�ܙ�h��b_�LJ��z�Qw���Z!)����XV�ӻ��'"���sB�E��En����J���H��
+�
+�E��]NT�"�bT|N��s�$2Aa�Zan���4�7�a�O�c������O,D�ܳ�
+�@yP ���|'���_����p�U��W�R4?Yux��������TM����J�n��p �J
+
+[¾�zr����E�q�g%f���i�5 ��"�;p^\����%'�՚�m:�7�~�$�50���p��{�.�@���1�(�!]u����ż��̰�!���N [��Q����
+I���}wG��/��"čt݅�:�Vtk.�BGg���Q�O�;>y�^�!9���F��}#���ۉk�[&��I*m��[���}/���4��yc6v��C���k�X���I��N;�(Z�=w ���(7H���R���,A���Oa���`�����"��}����EOk��{Ɛ7�ˍ��n��8�*� �Ć��;�8l tq���U������81��,�N����(ym ��
+endstream
+endobj
+851 0 obj
+<< /Filter /FlateDecode /Length1 1373 /Length2 27162 /Length3 0 /Length 28127 >>
+stream
+xڌ��dݶ5�vf��Ȭ�m۶m۶*�J۶m�6*mv}����~�{��c�8{������D��+������:�0��s�d�4���L���0$$���&�1Ð��8:Y��r��B�&�m��q2v�Ik���������HO��_@;GN�����1@� igk�C"dg��haf�����ȍ( l��
+ؘ8Z�d ��Ml�V42�(�Y�8{���������ttnnn�6N�v�f��7 gs��������1����6&�����ln��o�������� ��������o�����#�oq���4@�����`����-��I���Y��+������������ `jam���uvw���4�v��o�j`am`��� �
+���g<'#G {g'Z' �F��'��]�5���1�uv���?a G����A���s�����������!�]��Tl-\L$���k��o���3�������`�0q72��'����ɿ� ���N��eog0�;�������//'W����������?W0 c #g�����-�g�k61�����;Z����r�@����������������u�t��r�RT�������^4 ,�� ;#����7��O��+akj��w���:v���#
+���%k���&��&�6= ��� ��o��+�����d��"��nH����_n���n k��������d�����C�L�-Zc ���p6�+[��d�a`��g����I����X�����ߔ��]��Y[ؚ��9Y��l�EO��|�ed��������r������+bkdg���YX��0������b�+Hc�1@Gkk��7�wF���#�?�J�?�0�#�����_��� ���_�61q71�Y[�3�
+���|��q�9����뎈�
+gq&]��2���-6� �o\�9�*�Z:��Cy�2��ݗ��"�� $2t xC�7�z�gf�ol�m6Öq�t���C_ L�,Qm�#���������D��`(~B$L�q����� $�s��F�Ev�JsQ�P�����}��z�8ЊM���Je�˗�a�
+E�B��$̞H�B�ϔlq"dy*K�#�*� %���_d��%�Ģ���ZNX�'8����i�蜛d$�&����%�B�tTN�31e��"7:�(��>k<�YIv���0� ΊT�����O.����p#� +��{җg��c1�C�P�"<����!]���e]�d~�-�� S���V�x���� p���;) �B-�� H�DkOF�M\�.|b����e�p�>{GӰYd��/ �zB�n����lz<.Z�Vi�~S�K�n�~�N;_:�׎2��Ǩ�7������a�b4H���Q��p=�� m#���] �[�N��7���l:��t�ՎK�.O��9|jt �����t����/h`�4�wY�_������%|HB�EQ�[~@˥ ����_d�.iw�|%��(� ; �t���!YNC��3�JB�v��h �S����ñ����8�E�?(��^ �q��zA��V� b�-[A���#ґ�[��=y�}���A��?��:ykǝ�+n�'�]y�;�&�)ӌ�Z�nG�� ���ͩw�B�g<�I~濶�����3��8߲:���㔴��J�
+4zԜ��k^ f�w-���Q�"�:5`�f15I�^�٨�`�s7;1
+�-�^��փf4��
+`��$�y��\ Z���S��k��J���m��� �m�� ��1z.LX��m��n���n֍d_�O��j��ކ����~���o�L��X���m�D����X��̜�����=TS�TF^��d�o�GqrÖ��|��&����_��8,��q��k��]����$bO�u(X�����=��m�s{0|V�$� ҂skS�'���]:�\�&�jjJr��T�[������V;���`t�_nNa��I�<<"� �A��yp���
+�U���jo! (��K�{����+eT\{�.�L�?r��n׶D��� E7X�{��DO���� ���M<�ޯA�����Y��p!l�(���|<t��-��7[p�s� F��-R-��0x�+� �����o��\]� >ӹ3�$�*��× ��Bt�x,��}�f�&�q���P��o'rk&�H�CH�uS6��]���){�)�`� U�z��H���^�m-���O���aJ�m6_�B���^@]n�XLt����x&�Ӫ����?9O'���8߇#�P!g�=������"d�g����6P�W��݈SJn�̄LӍ�*���q+v���&gBBSU��%S���bU�4���2$�������)�S�k�C
+���cjSF�޿�7� �GkE��������Q~�0�e�gt�� ��T��$���;s7�����˶���^\@>4xv}W��� �"�E����$J�{����#�����o�Iu�*�IB�x��3RA#�Z\'�k���pE8y�R���9�pX�q�k�0/���ߘ�g�i� � �e󧹁i�7@ ���[�(UN9`�v�Y��?�� P-WF�㾒1@I`LzR�-2~m1W)�U��+���M�<�Q��t"$�c���;fȨb
+��+x�v�p�=�R�ƺm2��7a�{s�q!���&�2YV f�s�ȱ�S� a��=�V���z�4��'���oݘ�4��R�p���ǧ4�A��Nr��aa���.�ś�S��Ӱ ] �<�W�?z&�ɈT�L��g�^��3��*�)S��G�Y�҂z�+h����رV���������"60�1�bu�p����^hmѷoP]YNd�dq�BN�o?F��kU��NY(^��c� �߲l!`��$#����x��vԷ)��O%�R�i`�04�|�HD��9ߧ��A�gHI/s�jRB��L�s���Ό�>d3hΨ��D_mA��2��4����.\� �(c� ����ݪx4x?�� ֆ&��)g�N8�ϡ�RZ�+<��Nr��K��S#��:� )�R ]�_�2�!�X������B(4�yYg /��u�U�m� � +=�y~ĝVV����bW�?,c څ�tث�l�թ���E�ET.� o��t�cd�&M�)LgQ�|�0 �g���=�^h.�P6�xĹ<w&��<-
+�
+�!tY{��zBgK/_�GY��4 ,������ �ٿ���Ơ�yx�.������Y=Y)�Li�\]� �b@���a� ��&׷�\[O�b<��ٷc��������D>���}X�Y�;���~3���i�thE��+ L�fA�h{�X������U�?���tT$�ȫ�:ցG������`4A"$�=E�h� �ն�������x��Zp$>���Q����7�|�-��j+P����Ń�1zL�����3?�ΓӪ�� ����T qȨĒ�څ�� o��(LpǺ����Q���y��|��QO"�s0%"��B����9=#��FJlNy����^�F��R�v&%tҐ��ND� H�,��~���ew�i2he�����8�������SM��`a�s�)�ݐ��}�b8�@s3�%�^�e7��m��
+� ؋��e9|=N/�h�1�������tP�*;eo~�jQ(m �R��� �T� wWvJ�S�\���3 z� ��;�g���һ�k?SΓ��Q7�|hx�7*�(~�i���5�=R�׌O��������|՝d�9~�ۿ_p�8�bO��ϲu�D�]k�-�y� �9��B�k�%��������b8��\�Vѩ)f�:VS�����;D��\!p�?Rlil�v��xbE`�8�! ���cM�ʟE8�~���;� 5�J�J��{i� �רa�\�����f����r�%0|��\u�O�z���"9��E,�y��$ë��:的�h��\�O��l$���(f,yH�y�Yt���!/
+<h���}�6�GШ<� �$�9�1������S�0+*q9�k�ڝO�����;�IN1F�k�h�j�Jr��lf�y<r�np���H�;���?ۓZt�u�B~�[p�w��H��e��v�b��V�0q�+��NX�M�Z�q�^�:�3��[��SzGBw=D7.�n��od�Vp�̋�-/�����e��[�u����uG��lL@�s{�@N� BV��U�f5WG��yi�yp s%�P$�i(��[]z"n��P�o ,���$4}~{�녤��Us�}9Vf~�5p��M��AqJ�_ CK�<�w'�|�  gz����V,����E�л(bk�5�G<�Q�Pupz��*�� Hq���q���e(�u��V�΋����?[�t��U�*g /4󉓙_[DW����|y5v@���:�Н�_ G<��[������ SN�����(���]�џj�.�����p{[=HL��&���!�U�dV>��('"�� ���zrp �쪙Z��Hڃ��P�.mw!Q��),��@�%�M�
+��h!�'շ�k``��b����,-Åʀ u�^��I���L*sm ���bT���A�����S/#󽏷�����#A���D� {K���^�1���BF�����(�7����Z��T7��mW����`��#��M$��u�3L��0ɯ5PE>6y��#���&E�(h�W��®5�EO�̠�E]0r���&Y,I ��돚�y�&��ǝCS�,����j�K$���G�T�ݖdY"�k_�Q#ZBӝx@(��k�A��/ݷ�0O?]1�%�/*����D�Ĥn��ɍ�>:��-��|V���3�I��"����8P���-�U/!%(�+��}6j�Z�la���f��Շ��8�֞�U ���ڶQ�]&��o+!V����Ɛ��jO,����(�G����~+S,�6CiR��@p���� ]�Ά�Z�رUйt�KU9qΨ�hKɼ�H�6�9���P�� Ta���x��~��r���AĖ��`�A��۰��!�$�D����T�s�͓6*�� ,��@�8�<�����6�>�D�L���l��2��ڔAH��p� �����h������� �)�ӟ`%�ӡ{p>ʶi�����#�~������A�6:�4��&aJ��v%m��.Z��`��ݛ�U �Y��Z��@���nw��7v�=�H���=��)�xN��v^�r�t�D|���+��n��Ñ�#���z���SK ��G�� �����N�hT
+;H`.",{�
+�T=R5QQ�����Q\��z#}>�_��Q��ڱ΋�R�-�N7 �j�#��`�̛1B6��۪%��iV.���T�?*IA����aq����u�ؖr4�,�����u�b�Y]�=�_%ɑ�~R�a�#V������ �����~i� N�]�+��UF�䏪W;We>v�j9���U h�cn^R���*H$$�%aB�B���فY��
+��N�>Hz�X� ���]
+j�ak�_ �N���8#��t��9���5�4I�a �K������ЗiH������S��]saU ̰�C4)�@��Y��P�ܙ|X#�.\��jefǮe:�[��v�|v� G���d� n��Ǝ��dd��/�)�ߕ�� %��yC���q�ס>vl��Ѓ��9�C+]�=��8�D�@���M����VXP�*R;��I+�.^�E��h�4�˗9��@)�.��+&�f�Y�1�me���,�㛕 x&��[��V��9�c'k"��[�g6�����<�^��� �w�B�l��B��pL�U�M �E� �Y HЦ(�%e}�. �L� Hh�V�T�[�x`���(D�IR]r�Q|�ȁ#�6���
+�c�V�2����}�4�P��9��0n��P?�*��gV�_���F��X����t_d�ɗ�ؘ��go��L�T�X����U��}3�BC�➖��+�����휞��y���3���� DҼkllܴ%�p<�;5�6Y�+�4\ �(Af̮,R�b���WĎ:��6R�πi:��*C-�څ�*8� �{4 �#��T@���M�E8���
+�M�=�)��}H�v��1� ��$�3�x�N�P��Јs�3^�a�R������Y�2q���-7>�8� �x£E�ה6�f1�Lqd?����� ڧ�
+1N���R������d�E�+�rŒ]J U�0`����X-胒Yǽ�r�����b��涋5��xj��6�v��Z�k-��V�+/�u$������t�mϵ�9'�`^T�s)�+���u���ٛy��AՌ��UM�$:�����Y 5/<� ��oVu�U�q������v�z�u;,�z�`�h MᐐU"z�.R���rt�&��G!���Y��� � ���#%)�RKw1�k;��.��+u�D
+���5M�+ d�4�6ɳB�>� ������Q6R�⁻��~o��nI��m��{F����n[Q�(�Q� �9!����5pԋ4��V�j��q�d����G��[2�Сc`W��$�I3���� 1{lymd��k�j�X5�`����2Y �(&G;]�$����*.M巘y�d��kI��EY�ǐ�7}��"b�i��: ��M���d����C p����@O�E��((��:����*Q�Y嚺�/t�H�B��d�BbGt���-��z�ʖS��jɭM7��&J�����!��\���gj���T�GC����k�����K�MJ�����*�'Bj(��q�u�ү������/~�u~�4��ڃ,��Q>���<�OM���X�'�<j๨C�4�{��BG2W��\a��y��+��G�>u�r!RH���_."�B��PuQXfȩf�L�p��U&4�I���6��+�mC�K��6Ӵ;4}���U��7z�G��*��+ D�� �`[�icu��"�8`�>�T�y����xpp�U��_��|�▪�^6�~ك�@�j �5�����$�xOz�^�t���\����[T���*
+�苸~���-Sj��8x�����V��W����t?�<���������<t[���%"]�܍�[-T���S�C�@�p��C:I�+�O��h�]p�����i� �"�Myߔ�qu�������*�!��Ѳj�\�75��;#d6M7 �;����C���,�bR>�L"���0N!�F�!�!�:�L��̪�.8��t%�3(���~iC���O#$#~�Hj�9�b��ؠ��]w�#��":*�C�q=sx�E�f�1��=MJ�3��롈�9�˼�Q��������1Q�o�{�S����[���.c�)Np)S��ſ��1�YM(���ąT�2���Qc.ly��u�;��H�?b�V>���~����Z���CTT\4�|v�����3� ��tWS�I(�M��k��b�~�$lx�_���Ù��ђ3���+�]s��EL�S��^L�I?+oPhe�c�����
+��(����������^�("�n�h��jP:�뢧��W��JdO ��z��k�_ϛx�+�Ę|�_E��(#�;�(�ssN�&����҆E`=#:=�'5�Vh�|�̑6
+MG��5xʹF��eh����{���3���|%����M��۵�%Y$��i�y.���<�m!1��E�ZmC[����B:��%����9���d��
+�N�"<3��
+z��\�:�(#K���Ei0�93X��m���i���U��ٽ1���م�U 5(c=���3��w|�&<c�c]3��?���� �ٸ�p�U�Mq�4�� ���@o��O��gK�K��-��_���Y��
+Rx9ʕ�2�}q~��ǤU�n�@����B�H�_g��C,;N���K9t�=��X� �IJ��q�h�x�������l�eLbC^�- בb�δ�z�e��7T�`mL�A��U ���/�I����=ӻ"�E|Oq���W�������KkT?��˾�W�jd��V�9�Z6����쁝 ��F��8�:�BH�J�IM͐x���i;�=8sS1n�3�l�3�Id�!� :�J������>- �yv�y��F���5��5�9��+�R�9��'�/B`��y-Z�!g��|����ߞR��ϥ��� Ǣe?�|�=��\/CwL9��Ȣ��N�:��n���e�uFI+�u��(|�C,2|0�K"�k>8��4��ASi���~��"�Vf�?'������ĝ���~gR�*��Z
+X&,fB��*�rϫb��P 7���^�K��O�_�4��l�7�^���2v)6����h��ϥ�uw-�3L����1#��>�Z�3w�6V�շ&.���d�*���`BC��2O=-b�ߜ-9@���#O�����K�t (_꨹�TM3�N�p�����61j-��� CY����3
+�>�E.h�
+�QT�jF�O��q��E=`K���� �0dMdC�w9Q����9E�R�]���I���#E]�����l\��X�9!vEe�K����5dm��a� l�@!��Na��\�F�'.۲��7ە��5�yr�}��i]�_��$��V
+�.:۷�%cԒ�{�= �f�K=��� ��J�_�1�Tg��~?��Q
+��z~��\һ�I�|��o��h]�D2�b7��wB�<�������.��*����� G�y1 � ���%9�����ݨ������a����NW��i�[�9�'��|4���Y|.�M�Gi�;&�
+��n�lM �_�-�L����vK����R _Ů�v�� ��`>�u��f��!|���ݧo�nb3{�a%x#�;���ْ���ɉ���.-y��J�JTV�a��A�+J �'�"� �tY�>��b�����@���� ^� �?5 �w[���ϝ��V�&�@o������t�W��]��s+�Av��I/1���z\.�;��y�<M��[���x^C7������� �ba��͞��Z렰�E���w���}t>��k������Ϯ�_�h���D�4�;L�ع�Ӻs�O��8o��X�m�[$�ެ @ �`)��>ߗ�g������H���D��1��K����8>�3�7Z�D��*� tjb����À����6�m��]]ll^�%�]�� { \���6�iE��=���Ξ��ȧV��|���[�Nm�x��G)}�H A����������c���c�w�����Ä7��OǸ�A�BS͡0�N`�����A��(3(�9�� ��yn��|z�� 3y�R��0��").�ȵ�����%+G�����)�v���Kw���:���a�V.ً  ��h�C�T��(x�_�"��w"i��N���N�`l2�vP&�f{]�IX]e���F�\�j�V��v۹%������~�{CdE3���Q<h i�mE�_i���A�%/�>�6n�K��LJ�g4��(���u�LZ�b�߆� a�����kII�>{P�d:LXm����� O��b�R^��7� ܃��eW�Z:��m��`�*C(t�u'��>?~wlf� ��p,�Ɠ�/��*�֬R�M� lo<�2�&@�`j���2�4Y�|L"G#;G���"du�f�"����v����#��0��햋H%�yL��
+�J}�o�O�W�4�Ϯ�%�gG`8)��鎀�
+OS�H�΢�EL"�q�t���vѥM�0`����z ����
+�n�0�Z��dE�er�w�i�9���&� �Br䆁)�CH%]�QX�#��%Oh|�U��d�9�=ݿ:�|"�3��*�C.�.��rv�� HE "�,'I݋^ҡT&�Ҷl�'q6�מ�q�F�b$D=�D�[�M�2��O��0����
+���ז6(��� u�2T]�⹝��O�'K���]aWn�
+�h�D�M ���t:�n _ s���깑����� 7��..�Q����*����B�?^<�o��#P�ޯ��bd�Td_�u�y�dl>C�2����q%�^��V�B���,�{U�%6ƒ��&��!�S�Y1�M8Q�&��W��C㈠vn�.����_e�]��,R~ �MVlղY��Q��!#��k�RLnl綖�E<��&�:����bj�w����+c�'b'��bk�B_�jS����^/Z���h������ٞ�ʡ����I��z�Ȋ ��+�9f6;��.���m�q�#k>�\qX�05b�D&��q�jcD�$3� e��(�4 "��p낃��BV�;�̓�ܶ����p#�Ԏ#:��˾:����y��5e;���p�K��*��e�����@�����ص߫4r�Q�w���4 ]{��Zʣp��P�� � l[� _���&��
+��
+I]�|�� ����o��ͫ��ty d� }�0����s��N���5PW�L�>:�&��h���r����P8M� �w��X��9�ȩ�*w%8G �+NEk���F��c ώ�ٙ0O�P#u���Ֆdn��ɀ L���/=��ɢ���!�
+U ���jx: â��i.J���O���n��E�X�����_��R��� [��f�O��]7�p\a+XoKRr<{|�j��PV#8�[kT�١8� ���׺�D���Y �ͽ���kU�&^ȤqR��J�d�}�9'E�2� m�Z+��چ����3�l�]�:�5Ձ��Z���'=����]���.����z��k*r@ź���LL�
+@<�&���DFx�&3Y���类t ��yz���`ӚT7��J��:�} �F},�¼`�ѩL�N!�K�^�smy���U��b�ݯ��C�u���A��Ǥ���8{߮!g��`.��oK��5,��A��]��Qf����ƩV�۹?��e�-�w��A FP�~g�G� O߈~)�%X׭�y�R8���&�e�֗nY���*���8]�Y��rVH,H����u�G�Jz���K�%&I��p�̻�W�8�҆����x��Sv�!�4ć����<��^u�nd�ߌ�Ǔjc���וD���>ˆh����1���]��q�,��!�5���OϜ!� 3/�v�� 1Br X��̝ɖ��_�#�tu2��B�������'=��y�EP��һ��x����� 3�T����a6LҖ�#�H%J�j��,��Z�aX�͢��P��X&��&Ef{#0�X! ~n`�l�=@/ٍ�� �"��&+�KU]���hׂ_�K%�l&)����5��hU�D\���L�,��*�aK�+4)�3'��Q:vڭp�6��g����%8i#�g�J'؟�����%��m�� �{ �1�x��'K��b�;È��Qgz��q]��Ї/bOl�t��
+�;%��"�����F.��v�/�;?~���h1�<Z< ���1<[� �liϨ)���-�����
+WD�yUB�sąa�"NTYƾ푯O��AWj\ص�Q��?�7�l�%���'�7�A�\l���AD��_����.�-�x�����,L�*�t�'`:i��Ls}��&ȟO�F��7[�^*�,�JN����x�pxj��<�\:�_��?���Cg��sW� 54�U(T��ߪ,Drle�D����9j˚i>3�&8�!Fn/&6���ЦѼk���|�z}g�у!(�~ �I�ql��J>gr�̳šc��,��>w2㦱���o�yY��m[�0�>c�Z�-)���*��N�4�����L_����8�Q�����1c,��@����2@ͦó��/�%��c8q�5{-���Q��;��v6�{��()��; ���d߱j���b����D6�|��q�:�ӱ.M�������϶tA^��8��H1���i�K��<Z�r!�=�K�s����oK�c��*G��u{d�c�ϳ���ܡ���V��x�Q/^3�����O��a� 5�� �+�Vr�N�ꒃZ��U�=�R�i����✧���p\�,�%�j=�!2�L�<�w�����_���TH��9,��GC������ռ�o�AClKjET�ƚ�]b���������Z��v+~�瑚��SWt�4R� V�#c��y�<Y�aB��<�}� �������i�cA�&Ñ���əN_�$�V��y���h!��σ���ԭi�iQ��������j� �벰���Vg�.�����Z�lOzQS@N��;��'P�f����W��
+
+�*ކ�~hl�w�#Z,��(��x��}[�Ӛ:d�нI!�n�NS��?��ri�1z%+Ś2��U�0�j���s�y_�#��|G|���3�L,�?�`޻\髟t[�㣊� -�|��P���A5��f�$;�)���P��@Ub� �\Ak@�(�� ��c�&�R}����&�:l��#���rNZ7�`mW���p��U[f�X%W�j9М�[�MS��]0YWy�7�|dl�� �!CDmt� ��<��ZE����I����lU�Fr&Z$ sx�*�rU
+J��84(��o�/������/�9��.�qX��PH2�����Wo$4Pr�tVH.ĝl�z�(/ߌn`~[蜙����֕����=����_F���� -<�r������Wϓ�AAu��7Ɇ �-�h-�%Y81��)��_:I�D?:���C~���m���Jo���.6{Q���r�A�'m�r8�����WЭ��9�ϙ��k�0��2#k�� ���]����0���b��� ��^2Yѷ�M��:\yj�%��<+�ҺԸ� 7��.3}Wø��KÚQ!��.y0kI��ᣜ���Q�hW��e�M^�jv�
+�F��,�%�ZH���)�ϴl����ݔ��hf�_"GG���I���<y�r�<�~�:$���.i���?���Fg�;�l��y���^[s�G\`�:�@�»w���2k,t�}� �cI`@�M���7��'�/��s�P�,�' b�O1V<��0��1z��p]��T\��vF0@��@�+�ڰ!j������ABm�I��c*�W��9���K�y�ߒ�e��J��AHo][po��Nt�[ ��r@Wu���gj��ޒ�iF�\�����$W��'M����č����5��� y6<DB�W��˫�D���_V ��C���蝐a=:�P�"��[yv����������M�/�������|�¹���1���^�^Hņ�R�֟�Rd�P��W�ݽ��t��f1����GC�̓�p�Eqt�����'����2E9��i+��9n�� C��#���sM�+ �ː�1�]t�u8�N
+�x�o *��܆`D[�~�7�������+��l��Q�4p�D�xm^�&fA�U ���k���⚳���
+���e�.U��d[kTQ�F�
+�ݗ�������vʶ�%������Vb��L�tT�/
+�BP��%M0#���Q�Tfsȴ���Wef
+��0�ۑ��-5���2/g*w�~bZ?�$à�筷�'c6�@�EC:|%Z���Dc�=tچ��v�ܮB��%P�U�s�3���ľ�J�+���54@Az�"�\ӿ�r�,��螎v�!q�뱢yX���+�����v��Ʀ'F}��{����w\Ls�R�?�M�h���Ƚ�S����Ȋ�!q���W�����ܦ5��n���}�h�>S����?(�M{�n�X�ሮ�;�aav��~d\Bx� �-yS�߿&g�kiX�yt�e���E;���"
+��2���y��q�-I��U+��+ˁ�^R��������!]�q�7fa�F����g��ˆV����n�}��K4"�����X�N#O.�Mx� Y�� BJ�G��u`�Gd��x*�c�ܺG
+�_�ڌV�_z���IsG$��Wl�4�3$bs/ �V�c�h���砘�����>! [��������k��Xd����FX���Ք�>��G��V��A�����xl�&/�;��h�?�9C��u���\�b��A�V�W��^ ��vfu�u����λ�>�����״),\�]�旼z��4!6���U��/nx������n��Gt����e���૊�g]-6�h�leF���lɯ*�e�3NǪ.u�I�Ub�56�;D�b9 %�ڤ���?��X�e�:��seg$��Ab
+�����6n\_ S�m�*����v?�IF�JS�2�2t@{�g��u_U�i�!+��}�v���㫔�D��5[ �7Z̚c+�9ov3W u0=g�d2�(�a �E��W��Ŵ��yw�;J}��韇��h�}H���n�o��W���d� {�i��2�L�0{�j�N���h�T�.��b�̀�1�o�˒���]k�N�o�ȫ���|�]��R��V�#.��4#ig�2��)��m���X��g���L��r�����.Dxb�'*(T���R�5�����k��`�
+x�<ݴZ�l��|��<D#����31]��r��g�0���>�����٫O_A���6
+Y�s&��|��Ϭ8:�~wUH�6�U��"��7AN!�q�c���td�۬��
+Ҷ�v�kŵ�9Qq]�}�hk%��ɂe�<����|RQת���Q_�}2���Rl�
+Xt7藺9|��x�{J��h�0��Dϕ1�Y����0�O�B�o� �f8���e�z�:�{pB�hH �Ҋ�k�K�h5���<`o"��� ����*�5�+����Ie��� ���v��1��P�I�-y�z�4bp�Ӏ��9h�r�=���M3e�? ���`���H|��T{�%Xk(�P�_U�醔�n�ּ�N&H��#�[K?�wVk�G�}����il����գ�1m��ԛ�C�T,�]h��5�?g��څ���uA3��e� ����"wBt
+z����S
+m2��{�#�Ao�٩��}�(�CX�I�#�v��3=����-�:�ފW*�r��5ި�$PE;™Ԗ F����lW/�a����=G5����}ZĆ}w���a�$WQ��1����b=��u�%�Ν���')�K�������)��$_�2���Τ` M��E� y�64�҅"�=��nP�S���j������dڠ&����+Y�U�*���?�'q�i���0�!��JO_�'[�O� ܒ��m`)J:�=��H�9tW>&̼�r����G"'��~��x0�
+t��y}"]:�ù3���d�P~-8�dS�j6�}ax�0(X�0đ;3s���2Ψ |K; �������U� p��_��� �#��Y �M�"����88J���?|���+���W���{����}�`�L����Q ����f:�1כ{bɍ�SqT&�?e�i�qw��}C�&�y��&y���l�S��5o��$y�d�Ws�:қ��������.�\U���S �<�|���gν�(�Q���{�Š��vUD]zAig�{��+�E�y�w/�Z/�1\􍸢Y ��r�k�k��t�J��@o~+�eS1]�K\�O�͍[�7r:ؾی�.�_���a��z ��Ρ$�������Q�Λ�ɡ�ٯ��ϲ��2�8����J�N9ږ�7�[�� �_3u�� �`���a���NSH�l�/��L�̌��sȨ ��ǚ`B\_8,�$��T^DT˜�oA2�~}m'F[��"��w2��E�����7���YQ�5���7�8dO��a* �}x�����8�N��~�� � KRu��K��V�9���})�.k��K�~G��QAc����4�$./�pAaM����E�+xad%Vn�(V��?@�o���ż���`j���7�=�RS��\UH/���h�b�z�>�Ql]���L,�p!z39���y���<�vkX�����'E�m<�M<��E�]7Pd �;ؓ�M��k�#
+[U<���Ɉc�n$�'ކm�J�V��*���U��n��� I��-�CՉKڭ��*�܂_�R�L��+���`ꄀ?�8?�2��ͭ��A�$�����]N��i,���r8��=����ɝY�[ѳl?��?���n2P�F<��b��i[K!U��*�A0pV��yO�(r�K���Քqg,��1�)�]��x��V����9[D�s�͡T�R���� NzӉ\6����&f�^H��S��X�*&1�jJ�cP�Ì���{1�*�u#y�|v1dO�K��w����p�<fVY� \� �{Eį��� Uvln@j��a"�@��4� 3a��Yl����5�\~��1�C�� �Q!,�GK`�lZ�3���(����A4/�����\M��?"g19�����,'�VC���ǼK�F��F��
+@T��N�%�b`@R���u����V�w��ev;�P&�q���.�'HۛW{��u��?|��@M@��Ϋ��� 7i��Ӌ0����u ��l�@�OZ]m��>,PdJ��� W^᛺pdx�5����L{ll��׌��<p�:g�G՛ޘ�������2����'���7~Q�����a*H�e�� Ľ�S����n$�` ����F���5�����X�+�
+O�}z`��^����[KM36�\i�1�n�z���H��y��@�#��A��1�� �����vp�\cc��}cD��D�Y�j.�ɼ�`>� ~��1א�#T�=�³��fwh�I��G�
+w���^��L�+�u
+��n���K��]�?6���"��8�XP<Gלت�
+� !�T�ܘO��+*��LA�h�eP�e���S�n��awr?י;���d�}ٳ�i#�|Ǒ� �φy��M���_���s1�#H�GU��>� �#��#���$��M�{Cy[�'7��ƨ#��M2��N�����2�$������� y�T%2ٲ��~u��b���̶�Π�V���򱓎T��h���Ƥʿ��D�J�w�� A�i�-�vqO&����xl�����B�ѹh3K y�~�F>��&_��;<�� �l���x�P�]9�����We��,]/���A�޹�� ���ڱ�Ɯ�jx�����W$�p��C�^02�ܶ�)Da`��9S�6w�7Fi��c?R���
+ԩ�
+xFcT��d����.�M��*�Y-E2����}�p��J�����%��11{%UOz@���|#���u���X\W<�ۮcWqO��;~3�{�Hz����Hp��XT� �#��̿3&4��fYZFڏݲ�m۪���"��󛷓:.I��������|!��i�"��r�����Q�է Y��$F4�Q4Ғ�*J���E��r�W��l�����-C4j%:��
+|L�i�"yG�<2� n�I]HPL� ��; i�5nr����X�:�a��?�H<�y�ڞ���6 �Hu輙ׁlryz�t�S�G�D���.ɧ�YLZň� 99(���l$�� Q�vE��S|�锱����斑W�XY�kҿN3�*ߕ��*^?3�^/��i���KR�xT����c������$�+�,��E��㤌p��^�������?C�j̗%�0O 69䳸�t�=���h�b���M��f�9�4ZH�+��M�gH/0��D�Ɉ���B�U�����A`ܒLv�7��� �Y)����_��0���n��>�r)�i��8q����l�}t'F���˘$� �n�h��c����m�P��Umv��ě��U�6K�K�`���OY�jna���"�~�|��ܵ�"7́G+i�����*}�e)�nS�*�I���X�4��ԗv�/#bs�l�C���������L����<p�� �qpJ���/w��A�H_��S3_��bSO=�u"q�i#'\��hs.�!�I�]���[�Z7}ߘjm�qQ��<u�!EcQ�AI�ޔ�x�3��rC���xe��we����XY+˒{���ƒ$5���6��l�Lx��#U�* ��ڑg*��vx�@.�.縃���zW������O�-
+� �hk�~2��W��Ֆ��E`)�/����m�X��̐��F��ń����F�N�ݚ��m8c��G&ax~tт0~Gt�,A��;�i�uH ~#�>ڙ��3��V��Y��S��j�͕g��Yq��5mZ<��@Zޟ�
+�c
+��>;E�MV�{����������~�n���R��m���s���:+H��}��I�6yɤ��'�%h��V6!���_7�I����|�]p�X�Q4� a�av7� C�����no>]�;hq�ߡ-&�,f���e��qfYo}Wt�,U3���1�H���"�9qKY��Iց�LpV�"��VKB��d�k��|4�<�ͧ�Nw�?���)(�F�N5+��S�A���[D�o���DÌ���a������o�_�c��*��^�2Ө��y2 ��{�b>�����7`��۴����a��)��� �n���|�Ǡ� � p=�gt�UG^���7Z�{��}@��t�
+º�-��(5��EҺE�wR\Ϩ��x<�!Q��9N���5Ja�IӶduӔ��J�UR"��Bڧ)`��c/j} *pQ�V��开:�'헉`�8Su��,�P ���+�4h�DuM4�B��n�3�{�gr�����2�tP��֥�9�l<�Q� �y/�V���r� @(��\ ��lq����}�� ,U�\�?�>������:M��š�C�?R���m��
+�V~[)Դ f�M4����o�4�P9�dPYHw8�-�<�J�6���)Z �0}���I� b�^=)W��8���:;�f?�Z$�:@����x!9�`lip� � ��3��t#�r���V��p�]0T �GOn!d�9U����cN� ���nQ�q|c3^>J:�d����+ �-\Т�%�]�Kي��W�t��&�>�޲��?��\F$��x:�D[3��Qb��eB<�� Fݒ�C_���n%�h�V+6if�1��<��X�eB�+�ZN` 2jwaQ��cX�@�� ���nH�zѱ���S����7v�7@u�3��-�)�1�˼?��t��H R�$��葛���޽iħc������&�./�p]����f�.e5A�P(E�3$�%�^�"M�B�fc��VRh���]� ���� �� �I�gSm~5����F;�^��ȓ�W=7̙ ���X�9_=�
+L�:�UE0@��?u�ύ�pReI@^B�Q�9�pa�bd��F�q���}� ����񇷷�C}"�`���]O6 AWCV�ې�Wǘ�\t6P������:�� ������{U�}�E����`��}5�����m���w��t��`��n�i�l)�w�\�M�+���}��܅��@�_�_Э+Z3�#��0���5��Gz�:9��&��/���G���f �tE�-� X�P~�YKSQ��Mw)�L�ӎ��9�O�f�98qF�X0�T��3z�N�]�wBV���5g���3w��h`�f�,�сs�1A3g2�=y#�
+��Ϩ�1>����
+_x�Z�N�ڡ����4��wI9ρ*V=�\���~� ���Np�.�-T�{��΂��:������{�� z�­�Jvf%�R�V�xh���FJ�����j�Q�"�d�H��6�
+X�J݃�^�+b:�GŀYK��:��d��;�����P� \�Sn#8�^Tޓ ����q�V��ma����8����W�~{ ��za=٠:N��H�|tr"�-}�˙�����F���H�S~��ަ�׳WmJE���0С�
+��zB��t50��?hZ� �ID�(��8]��]Ƅw�22��`��(\^�}��M�@���-��y��Yֳ z�����
+��U�i
+0��;W^8�d��)2��ҙ�Ђ!Ӷ�������l��~��!Ԗtfb����á^����$PV1*��I��*��� �����ɬ���}]�d�H}�*���/�wU'z^��S�����9�F2g0J��Īj@o��bH0�V��l� 2q�����Z�?����h{�c��]�Y��p�F=K�r�CV�C�Jpz���o.�"���)�![T��U(ԯWz�}Ib�\]2dZs�+a�/f}r��<���F�m�N�f��s4��0X�8���<.� խ���笪+�Fb�6/D� �6��M������{6x9fB��� `��l��B
+%ہ��s�U%`�g��G���U���$l�#�+��v"�-�f�=T(N�������"$�H�bѽN�X��V��:�Z4|ah$|R lj�B�b_�կOO��~ 6��̏�M/�Ƽx�GD�z�G��ݫ̸L�NJ�cY�Գ%���9��,�V|tPK�FFx���ȅQ4�-��^t,v�5O�\��@�#�����Y�rE��M�Қ��YV�(V5�f�b���,>b��|*,����Ѳq�b���<�W�Z@L��lϝ$k���5�ƍRP`1p��@-��qz5q��% b'Z&���g�keFL8�H��f��u�̘6�V��h����鱣שׁI�ˆ�L m�f���|�:g��q�=�~��1� ]������!�ua)�3���!������s��SJ�0�ݻ�����Fx8�����Qe�vyWzp�-w�������V�X�8rQ�1,�2*h$����ԑ�#��� �Ah��")�Gj�n_bT�&��7�.�I�!Uߐ���#����D��Dv���?��������^�iRY}D�Ī4j�o������Pg<��^�ut6eүI<�#�����g�D��:'�<^�a2.z�Jy�
+���ਫ਼t�f���(����^<�����H|J�tF�h��م��mB���-kތ����Ƽ}�8Eƍ�����:Q� $}5�L+�s ��͏�����֗���-a䀌�!~�����!�0�h��`@}���$�=� NI_��0�����2eUU�rJ�,ݩP�c�^�4.��
+'�N:/ڢ���dF᫧`�=��Z�M)&^�oQ�� �=/�OF6�6@�:��R����{:tb��ny��u���o�r.G�ء�jj����8d�������5�6wxע(by4����a�!/⫊��P��%�c嘽VhR�V4��qon��T/�b�f��ΥU �QR�����,�Z�q� ,A�h-��&�����7�'j޵����^�� �'-��@�2� M�K*Ҋ*�����}�v5� ]<S�S^2ۢ~�0T#�@<&��\C୯�۰J:�k mD���/yPe��R�����{�;(�{G?, �I5g�Y~T}.��.W"�1D�1���Hq��sF ���b��� 31cWwU i�ό�1��~�ŋ�O�dS.�?�48�����a�1.���Y����j/��*���"��$B���fc�����!�����rj�FF���@�g�C�VO��$��Ö��a�~�L���'�#y��7*F��S$f���z� .Z���M��Ss�[4�D�eMj���@R��5,6w�PPN�3�V|�>]�Հ�%< �[��R����|v��;֝�elY ��ۙS^�7�i׵��Ģ����&h~)*2M���U_�u��P��8e���?ei��1��~�IA;׋4�*���R���y#��³�8pC�G]Ŵ���n��JZ��'��!����Q$.��� ��h� �d��l��4$����ʼ|dw�u��e�q����C���.�@��2P̞��b� ����&��.- UDxd�F\����´�a�K̓����HM����Z�V�{���� �em��؇WyO����Zg{R9�!T����UwX�l� �؊+,f��Lk`&����/|F����lg�h{�"�Q���
+ �k��UUF0��C�����;�ґ�����AI�Zvc��3���>W���[�q.�U ��8@��W>9~�T��fDq�:�����h�n�]*�ph9OaT�͛Ը�`(�Ԫ^�>�i�h)���{�荕��"c��g=O������c���[�j-U�D�+�T.O5�A�@��U Wv�*2tBq�H�܃-g�U��"K6`�~W_�� �s&�ٮ��V���L,�c���;�]���a��N��ȉ���X��Yj޳,��H��p�|��LJ� �œ�(��}���Ā,5oЧxl�Q���[�Aރ*��j��_���`.G�Z@�P�F1�!e�����G͉q�'��� ���O��ۈ���)����sie�=F=I�fD��lS��n.�f�4|�B��v͏���;{��g��ТG��F�wc��������s#`�w��B3NU���O�� DZa�\R�/�}b��j�S��Ų��i=�Χ0d��=a���Egy�~�A�o�a/����o����ƴ�n�N[�8''S�<5�PrB�aR���3�t?!���� �k��b��0�*,�&��;N��#�O�jweY �n�L�� ��K���B���r��V#BTn�I�k ����$8t.�.h�ю��A��I�-���(7E��B%ʆ�h�K�����{�y�'�v��M��~G�rw̲ς�)U��B&��Z��}�#����p,�Et��!`����+�A�ULh�c0Lc���G���$�.X?��q�i��! ,
+m�|���%�����l��ҥ |���wԧ�'��Ͱ}(�Cg����oa-�(��b ���=��ƄM����j���i�{ ���m���G�S��p,��;弱��2&�rJ>+&�{��V�]��4��4�N_�m�d���4"7��������
+���C^���6+s����C�(Jy�*3�_���u��,�7I�"���
+Хh�躿�_1� �. �
+o��bA������-�űF�L����F! ���M����L�NE�tb-�2��_4���Jƶ,n��*�ة�,��K�H�����k�)�`<V����w*]{Ph}������,1��37�_-�C��>�?^�W�eA�n��|h�Mׂ��;~��:��E����&���EzB�l{3)1�c���y���{�7��C�OaGb�l�\=#�h���FmQ��� � ]�r� n�Π ;��3��G���bKI����=��� �&Dz�a��K[�E��%'9oe��u �8WhE�ËRV���߱G���<L/@Qj얚�n O���)H�9K~.X -��
+�;�Zv��T5�m�����z�)�7dH�K���������a`�d�(!�5�l����g���n�޿Y�~�ʀ5�$�� f "ԏ���#�?.,�mE3�Я{*�����J��gۣ2����>�G�� U#���1�ً���m` YO���50���>��L�ݎ�}��1��c�xe�Ⲧ�a�Z��pu*%}tH-�SF�7�C�p�����P�i�MH��� ���Z���7�Y �=�)]�aۯ%#C���$����k����SG .d�t1�^�I�ȫJ{���$�-�0K�a��)�wd!�(�d�����׹�"vU��D@���㊅�����+��~4�=�3���~ᯚ0�/[���Y�΄��Þ |�9�M�>Xϖ�����dӑ�[&�Z0��Rf<q�A�s��į�t�S��XP�հ�]�$�G����LO����9{�/�+-Cr���߃ S�����K�$�G�q�G����y����e�{��=���u��$�i�u�C{��ϒ���&����k>��J)��p2U~Jj1���`o�7ݤ�{5k��K��m8��&�`����˜t�wз�֜S'���D?�����ꓻ�d�����[S��5�L�1D�i�������/�;?�Ï���*��ǫ-��R%e>:X13��F0�>��uȦ ����h�|�#��]�t���`�.�����f��O`�02w�`���8D���OJI�n���0��Ahdoc�Ţ{�lf�0�����HL���� p�;�x ��c;�Ve��I�Hv�
+)s��sM�6ckI��b�� �h��*s����썯e��c�p)%ΘQ��7��'0pk>�F�rndh̬Ψ���=��D�Hm����w�Ĕ�܍k��yɝ�M1�a�T�U�jMk*��8h�-vY�(sqL)�Irڞ�b�萀���/��.|g~� �tP��}�c6tҾ�b��5��S(-�j�j)�:��
+uС/�� ��*I )d��{���f�f
+ �J�ܕvzA���@�ABb���>����:�SC �$rڽ8����a��i{Z���w�� W��P�g���Zo���5cO�&�r[�mR,����p)%ߵ 폦f�="3r��x�Ku?6���\�3^,�k\)Q�`��ɺ��� �7���yS��c�AAn���/R�8A�3��LF�� veu��Iy�I�B3h��ȁ�Q 9E��
+�4�=1��$���Ev4�!d~���:�.���ϞF��6��HXm������ur���me� M�Frf�Zc�ׅ����)�TW8(��
+��cю-ۛ�ӌ�O?n��Vc�|R�3"Mpv+ ���?�_��vH_ 8�)n�V!�|m17��#��W��c��R���D�ص��\#}�'�B��q]��\�3�-��md�<y�N�C�p+ 6-�c��J1�Qǒ��tV��`~1
+��{w����(,�@�GK�=lGH ���
+�.�����Ͽ�_ˡ�nAr��t� ��0�M��*KO�&}�����5��0�G�v�Y��֪��Ń���0��Z������j,A�Y���"��+�*��&m�n,U�L>��32&��+S`>�AwS�4�^�'%��F�%x2�@ ���(����_��:y�&�l�9֛W#�`���彿��9|�il{� ���&���i����Ͳ���/��z�"�yTH�����- �����^ȑu p'>)x���)
+X(��;��N���8Ǟ�'��=�~�9�"�qH��Q��c��t{�� �v �"K���F=oy0:�vx�9f)��I�@&R't.%���m ![��=+��v�3A�[�V!3;yu�. �0.����9P��G��k�k볻Չ??�"EgC�1\k�י��̺`�l6�B��0#�WT(�Ry�T�`�y����~ �H>���%s]@�Ro�tG�� {]��7*)�:��>�,��F�KSA����Iǽ�����e�x���՛�0�o)i,G���Dy��?ʃ:u�O���x���W�ˎ?��p������^'�T��� ��$�U���p33��L�'/t�T<�[�. ��Ѽ��,o�(�eW�5i�ݓEW��>�'�T�~�<̳~�̕1P%��Y�G�7`�ܮ��`�<�d�_�����\:��4!��}�'�c��N���n|�_I�<�eP^y���� )�@�����T y���fNV���� �L,'|tv�&V���O뻛_�s�Jco���|�%�|ɟ~ 7�YWC-J��u q�r�f*U�a��
+p��ib�|۟ _�f4�˪�\[�M� e�;�.�+��g�Hc8��,�f�J�B^n��o�mVz�g��FJ t�R���=�G ��0'���.C�\鈻��㛼�?[�t]� ���$r֓���ʧA0�=�=#~� ��7Wiii!���)���$�� �E�������-l�0#�m�ov\S�=�#�i�ǯ*9Ź�!�I��O �h28�duyx�<7��աL%Y�>��D�ʰT}��׋3-4Q�jf�g�=��ƨ���=!u�d� l��C�UނU�\Ŧ� ��F8D9ӡc쥳 3}�e_K��� ���L�N-��)h����9}p/D&$H8� ��v� e4�@�HXR��N�O��[�g]4-$��&Tb��5���J�6�O�I��<-�ڑ�W=ō��3�N�D�L�E����%�?���}Jˠ�����1��o�M.��1~gW�4*�|©�׏O_������Sf-�yzJ��O�8��܆��$����_m��E:������9�����k�]~��<!�g����������>%h.yD�[�Lk�b\�BM���6����Z��H+B�<�^q�
+2k�j/��C
+9�-�Qe{z���"W�d{J�����g�q�HD*���`>����jӞ�;������=Iϰ]��flC�6-��7.��q{�Ȟ�Dwd,��0?����?���=��M�SI2�"��-79��,!}��G<pZ�V4"I͏
+͊����5R�&·dH����'�2��l*С��2�$��K��@W�-�@:�,��H�z� h��οZ�t3+���c��e���$�W�c6_�#5�$r���۱��Մn�y(6 .%T��t�����d�C�BU�5��ݩ�X�] ���cJ�9��Oy��u)lE�p��9W��͚LX�o=���@��4�e"ٙq9��}���e���$��ջ���s�+��y�=c�X��7�G>yz���_�e�f7���}�G���C1�wCQ9��P��+g3r��F�i�V�Dh�s��I}5�Q���=
+Ye��9D^$�� ���2e)�i���X��Du�ÃvC��K�����?���3����,��#��Z��u�A��i�p0�ɯ�'�
+�O���ml}� - @���3�7#_]��O�&�79)/`�!�y.�`�7���K�P���w��j��A>B�� �h��s.�<S��`�e�����"Cl�����H�~
+�O��g�y8$?i��{Oӭ�^�A� s�;Ϩ���`�c4#��v����P_HF�f~K��N���ә!��)�y�j?����o�l\�I�(Z$�90���^�q{8��S���UG���(�G�C�Tf�=x��>��IP=�8���Ko��0�J�h�5��= Z'j�{�Y0��&�AU<�� W|�b�9�iS���FBI�h��$Z�Q3���~��WT^'��m�)>�X�H�V��� ]�zwY�b���!������؍�9��-���D@�ל�M�V$��e8W l�����(�ZBJI!s�rq�����L�&?pr�S���'w�䧨��7K���'2�ehj����&��O��a��x�ŀZÕq��M2z[�i2��>�5H�ą*_��))��o�+·�!,H|^/��i4��!�߷���\�K_ �"1N�~���OLd5���z��I���8�]��S{���l���y�u���ٽL������K[ �]
+��`h�M�G}sxHU_l������JDƁ��-�܍���ϗ<!���rQ�S���ߠˆ��0�q�$�6�PB�H����n#.k����Ա�z��*U����%��2�4c��|ʥ�m���d�Tf���2R����*c�͖d+ ����iÅM��śyπ����,������������DV�(������\�L�n�P9��.6*����~I��� ���@�E�Y�Q_�������-�= {}s)~����w(�*2���٭��ǟ���pȀ �h���\��؀�vwm�=�K��a��@�^�|�Z�v��e�]|�=� �7^��k[����#�g<�cb�&Y�G,�݂�kx�����+)��5���݌(��4�BΧ� ���jG�zv�h��Ha ��F�� x\�ԁ���8�_�]�� }Ԑ�2L����}� 0/ vS�\o��7��Z=m)W@��V��$��P�K׵��� �G0�8����~�6��[���f-q����{�N� ��S��N
+endstream
+endobj
+852 0 obj
+<< /Filter /FlateDecode /Length1 1360 /Length2 27894 /Length3 0 /Length 28856 >>
+stream
+xڌ�T�߲=����������i����݃C����B���&�{�{o�f���ku�S��Nթ���)IU�E-̀R� 7FV&>���7������� ��R����o+���������]��nm�n�A9w{+;�������������_��.| S �"@�tE�wt�v���v�{�-4�V^^n��D�.6� ����5�����uGs����JA#`����������d�����b%D��q��]�.@ �?��L��j� ��am��o������� ��`oc�� pY]���*����;+�ہ��2��w��D�����`SssG'S�� �
+`ic(K)0�y�1LA�8�ڻ:��7�0��75����MR��ӿ���;Ws'7W&W�:d�'��K�Y�;:8An���'a�4�{���������ﵥ ���,ܝ�5A6��@Y��x�5!���
+��daa��e�@/sk��kx;���c�[�������o @K��_WS ����������`ac�0Zـ�'�_3������w����%+���� �r��d��?��.���������oHL�� ���� `d�d������.��wS��T��?�� KGᅨ�{K�U���O�a��w.%ǿ�h���,�,��X���_!�o��'�����z���������?PS{������������?]�����"������De�L�j@de�ߗh�*e��P�q3��7U�m��G`�6 �����?#+ ����U���߇��_>� ���>Rd�h��8��..��G�w� �e�+C �׿ `f9�� �m�`����<Y����6wwq�������������@/�9�꒣9�mcX�S�(�'�����v-��K��
+l:m]nȖ˃h�� ��=I�{�5�w�ӎf���TծW�7�d���.��9���NE�F��5D�ޝ���� ;���( ��yPT�1�<����F�֧"�T��ߪ~2�k����,2�[�#�qc$��ø�B�u���Q0�I"�L���^꫷͖���]�͵�_��cj��W�8Cwٷ�t�䗁{Y4��~0C逥]xno�d��1H�C��dz>��I�tT�ZƷ�w���Z'�ã7����@� �%�*��F���o��O��ػ\�Ar�����i$W.�k$Bk$�w�����$��R(��#��_�lbi��Hm*
+�81��FJ��-R䌪[� ��f C��|�pq ~��ߴ�G�YW.@�*{��v>�����bH=4ʞ��2�B�
+~(�YԎJ��O�X�%��'�!�,����8�I79�׫iKb�KT�@F̠�No� 4���O;��r�M�H~_$��m4���>�֫�ڼ��wr�J%?cz�O<| RAҺ8��YI�w��Kn7��\��7��i��֤u���Ӣ}�h+�d;����2���Y��Ԙ���y�]�+b�=A�!S _O��۝�8��kp��sgk^�Y� �u���n�Ύ]:7�lN�%�۱�B �
+���F�'me6�,�̧�v��,y�"F�챖�� ʠ�ș�f���\L�-9.�˚�5Akѵ���)>�>�$G�%��M,`��;�j�9�`�1K��1���J����A�%���S�k̟ �ԾC���"3�:.����zI��L�I�OSi(�*z�ٴ��qi�{ ���ݧٺ:w��ķ�ć�� RK`c�3ٌn�Pp�c�W�LPH�
+A��_Q$vh �.m(ͽz[��7:i_�m�Fp�����"�� :;�i�����n.�;��(�&>X�w�9�vwI�Y�`t���2\��Fy7���X��^�*�fV��;�N�hr:d ���W�51V�yI�_(�g��$ӱ;v��f����g�Wbzyo ����, n��{%B�4��'su���������J���֞Bp���S�`C����� �����v|A��\�[E��� %
+M�U��;���Q��;��E��(�KLQ��z��A-#y{H��D���od��<��hOE�#��mýbQ�=(G�1C�Y&IF��__�K �)LGt�U�m�֤aE�����f�U��3s�Y�(�˧D2�V˖o�C�U�ޗ��n�S����'�ٚ�s��E"q��(��^%c���_[�m��M�`_ ��&�k�#��Ɔ���t�b�t�u�"㙫�2.�~F�K��膙�'��jT*8�a�R?��
+��1Z��`^��,1z�_bI�G�����9�ۤ���X|��� ω~�]���uf�6���۠y���-��,i�'����c<�� #�C�eꍐԷ�G%�$���'W{��
+G�hOS}[\�� B�C����퍤���HV`D^O�i�2�\����^��SW���^#��1����RCV��p����D ;|s��I��Y�|s$�Θ�Լ�8�;��i��<1s:��Y�Ѫ �
+�w $�b�\>�!�����ϧ�ν7� ��Q���}�?L�3������%���2.��eѳ�$z.�'� ��-G^����.�Vo�rk�����ޓ1���/���2�`#<��)g��_Ӣ_��t��ՁX�<�J�,Դ*�kq.S�j�>\�����Љn��$G�D�+�������IY�d b&D6�<9p�3��ك"_pp��:-����"��������)��/�߀��=��@���^Z<��Q��L an� �4R/�?S�MD}���a��a�^��JkSF�Pen�������!�����Wӂ��u�L_K'�2��̭�Nj���e�ջC7����r��gn�{,�ɇ�>\Zq[5��`���Ĭ=�����Ө�'��$�(c�M�<��-0�ԓ��-���Lu~a4��'���<�6B-gˊ��B۹%�R��"y�+���$ha�P2��қ,?�і�~twt� {�7u:-�;��*�p�U���`�S����z����{�5Գ�~������{h�%G!R�w��'7��OAo����;:�|�,�M�"
+K��)���T&�T�1��hF���C,�������Я6�t�C���@��В8B�|@����x��o�r!�C����h�z]���α
+Η�c�6_ٞ�!�)o裐F�9�捳PQ6�~�gዒ�2�(�z�+�q����Gg&I?�qj6S���FX'�l�#t���������k��Ma�5��*U�Bo���-B�6�锣<!��ˈr��t�� gRb��RO��<�;,A��
+��YB@e�u���9z�G��)�p�O��5�A�����ۜc���|Lz�B �yU�}1��&�o����X<,u!�Ƽ�r��$���]}5Vȃ���t�;���Г5�U7ӯ�� )�IOv̍��}Z5Tr����b�RW�k�h�Fr�]TOH�|s�� �0�[8�q��1���:����5�@L�ա���I�t�*�/�Wx[I�v�45R��=��7"]0�g2&+��vu���ә7Ӯ�<���3{��6Y��'��8o]ϵ��u�������*, ,N����XI�����W�b� c�.�G8�P��h�Y< G��\A��B$���PN�6��e �ڕ��W���fn6򈚾ȫ�^�Xm�8]��%���+s��|Ž5�HMh����$�1e��*[`n����{-���;j uܱ��f`!#��z�X��BC9ϙ��W#K�XO%��]��j�MgBlÛ0�pʋ���dΛ4���#"����!9��I�G��+��JM���^X��aCк����� �
+V[��+��2������F�J�1���Y��e�U+���f���-��e*4=��X>��U���,LW�w��5�zJ���^��is+|�Ӵ�쳓9�q �=g���1� �>��#�D� �`��2��4��nuπo}�ղp��0����(��c(艟��A�F�IL£-'w��ol�� �9����|~��kncE�~��n�ݚ�:O?�CD�~85�BnR�h�.���"-�o>�-�6Hc�ތĊ*��~"D�+K(��NY��E��s�q����SFWBm�:L�":.r}��RA��σ�z[���!{�]J/��m��
+���Qܦ�Ӝ��c�f���O� 8���Ѧ�.*�έmĘ����+���|U.�Xw��h���2��]r�?��K��<�A�"s'�•�Ca_w���t/2q���4Y"G�MzWuV�!|ʾ�#�+FT|�~�AW�*v2[�\��4���z�cc`�*Ѡ�S�w��g��'��Τ�M���{ ;�]`t����Q����7<��5�����+@ߨ�,R�tL��M�o ?�ηJ �0���s~�&m��G�h6]�m��$i�S����_���-B����D�R�L���ϋ?���PQ�N6������͉Tъ_��ʒ�4���|l]��>�d����K�}�^*��~�%�k�,��>�щ���v�NW�x93��E�u�ڔ)Q�9e�tj�4�g!O���:�zn�� ���X76�P>YT2�32�QF��5�����^� �;,#�� ��zI�L����#DEa7R͊��:���E��� ��t��༟dκ��n:S� r��]o]��C�Ѹ��Y#�q�Q��7�3c��Upd`��i.�udPm�1�8ʛ��~s�R`��ãܢ�$i�o@
+&n5��J����da�}ѣ�)�?�7�/�,��������4����N��� �����/���q��qs�����%����R0,?lS+y��4��p+��(3�'Ј�� ��>ڸ�l6eU�|@�l�B#��6,�drҙ^�Xs�D�����`Zi�^� ������x��s�� ���4�!��N���ڙ�䑻f��V�#�Ȥ�+";C�L�����/B��!7��wN�y0�D<�z�SIl��T�1��Kaq�+�lx/jV��ni����Q������D�a�>���cr#��D��2�Hϓ�i:�j�.}�j�b�q:�<������1�Y-d.�b W�E‡���i���YPce��Ϛ�Y�L�)⭷�j�.!=F���8�>�y�֙�8R��/";��;6T|ǽy���RKl�k�85I�t�EG�����^q]���07�G��lt;��m V�n�e�����2��Mg��Zk�(�ɺo[�g���i��9o _*>9\��&����_dM{�43S���W%/����Vf��Lg�\��ٍ�x��u�?���@O�Ks�1ᔔ| Y�g�x}F�lBG��#�#"�/*f�B�4��ś�u���m���T%�� W���a��%Q�͒ש'���Msf �
+�Zӑ�E�1Jl ���6%���\@����1��y�v�mU����P�>X́����p�l�g qV����75���r��/<Rx � �A�XF�?�0�_�ͺ�yY�4�V��c�/Ua� �f��?�$���ۮ<�WK�Um��ϊD�9p��s�Wk;27�.ss��f�x�c�F�_.�����T4����RȔSB����c��*��=���㒹�3�h�Bq�����aׂ�)���%
+x�d�mj���6
+���“=��$�@'Ot�/'�#�dʰ�<�/�#b/t����61�=���� ��[��N��y�uE��"��+=��B�R��D���A�տ��4:{�'b�C �6(n|&4�I�s�c.v�Nm�TZ*P�Ҩ���^�)TP�֓ĺ +�|x��k<����h��uN�����p���Ȏ,�p������-.���Yl�dm8�m��T���z�Q����SM������ �9�ۈ�mՍ{A�6�. �������W�X?�G1��"�� ��R�y2���[�QS ���%��E��E�ͩkj�ʄ�y���[��Ս3:��o���$�"�
+-]���2�0��|iDz���J��}�]W�+���Jdt���F�}/ z �8�m�xa-8�vH%D����\�9p�B}2$�����ܨ�ӬIߕ_�
+$܉GV�y�M�ݧjP&��< $OWk�A�,��� � ��O��pd�Е�Q��*[�gF5��
+��Sa�`h��Rf������>�L$���EW��u`�<�HՌ�3��k���� bZ)P�2�뺸��Nr��[�N�r�����ŮH�P-tꪺ
+�b*��!2�PbêV����^�B�3}��u�Df(o�=�d�B�v�|� �����I'��^�lrw�9�=34h:�*���p�d�.˻Bɠ(K��m+�"&b ���P ���.���+�.���q�C�X�h��^_!�?M���Q���|g�47+4K]��t$s� �C��e�v�“U���(������]L8�W��}�_�_���� ,�#�����D��^���'��^^��e#��N͑��.:c�k���u��Mt���]�x�mLsH��57w�&�Kڊ
+���$� ?Z�ۆ�޼�a�%w��TJ
+E`j�W���4Ӊ8?~���a�_!}ѹ�^��'jz0��V%C�L_!~�� d(��9�H��v#^b~�����u4_��|�e2|}�PL����C�Քbc�v� ��;_� ��h�"oʁ_��)�
+]{�:�wsŴ���`� ���?�e�H^��M��|/z�J����H
+�<��%�%*_L�*yLΣgE�|��b���J&IQ��,�i���+��%k���V2)�C����\�ʽ�f2�S�w���Yb�s���"��7��r赔n�l��6ZN��jnZ�Lr�� r_�
+!������P뷠���u�y�4�&R���.S'%��]���6�N�z�k� 7��
+�&���z:3=Z|��[�tp����Q)$A���o�^l)֠���>�
+U9������PA�Z���aF-�n+2��Ϛt�r;�ՆL���1� %��f-�/��Q���Э7�U��˖��=�1�і�#��|�(*��|�7*ʟ���P��z����5Kg�H�&��o;*ԇ���KR��Jp;r��d�
+H��U�Ԕ�4��nĪ�3�EA�,����\]I؛!l=�#;������t �cg�3 ������߻���l��L��R�����xVn�X�Yiͳ�+���oT�U�F}_%�VY�W�$�R۰��{��n��+�w�M����b%4�.�O���j~���spm�����ʽ�&V�ƭ��� �[HB�*t��p��,�e��}��\S�����=� ]���4;��)�`􃍹�a��7Jz�zڞs�6_�k� ��M�V�R�E�H�r�,�V��ק��ḟL��<~��wޔ�gS"�3�Uݾ&�b���{�Bg+~/R׬ey4��*�f��iJ���P���D�*�>er�h���8v3{nZ��?E�"�Y 7l`wQ0���3�n�� ˍ��#���,S��Rܖ�U}{��=ɥJuW��R�MF�M, �N�(��2�_o߉ݫ/�`�G�z��r�xp�$Г~t4���a�h3���7x�l�!bo�~�� i3�qC�]�8��5��"6 ��a@s��-�4}��r�/��*�(�n��^G�l/i�<hM�n3�����#��Y/I��%�z�­�.�;�h7a``98�g��;Wa�|WI�k��)-�l�2��k����@5��0�!��3�|f��~Gw� �@�1���C:"��D��ÇtBV|X2�^��p�F�7 `��Y�`� ph_䥙�������cX�ȑ�y�Ep,-�ϫU����n�x���l�k�� ���.ʁd����O�Bj�i�<���/����}i��';Jю�v�MzӴx�6�\�RFV�sH��/c�_�?�,��Z��#mQr ��ft�H�*mS��C�%�����|/�Vbc[jw�DU�:֬�D������x�[��’�g���`��M �r�@3�d)���̍�V�k�żAm��,�����������e����n;6�h��FQd ^��_Gʗ���k>�(� t\� ��
+�3 >���
+�\�B�Y��+e�l]���<��V;�ذ‡:g�4zY�J�T�q�ҫ��`HQ�g�HI���C7�~�� �X^# �WV��|`5�BgzT�t֭��΢u�94�P�����NC㩡�[i��!��џ$�[�&/�?�<^W�;@��K�R ����{�T�u�!8���ޫ���"��Q��\�_�7$� ���[��p�t��o���m/FZ,����μOh{��xn�qܸ�OPR�G�O���=�ulux!�#f{0<=�JM���$��4��ޘ�K�af�f���޺t����w�hYF�o�Qp$�{��4b�@#L���Z}�Sz:�i!W������vd�P���KMM0�#EY�3$8�]�u�[�n���Mc�iM�χ�Bӥ�,����&�E��t�h�:�62aj��Z���F���b�]�9�n�Cw�aA w� ��h��y����P�T��?��Z��K�/ g ��O����L-�cdu6����S#<��:vY�yC�]�\˪�|q�[�g�O���@����P���(���3{�5 Ԑ%h����?7�U��:E �mA}n��nym��L��1�1�_��C�
+�,���w�����{�MM^�2��Қ��j��8�S , � �2@
+���'rF좂�&J+>R������lk]���S�`�>�qo�Ph�E�l�Q��wR��v)�sϔ��eSw�Đ�h'�X�l�6��R��t䃘���[�zd|�^�P��� [���+��C���|J��u� �q_��F������p�,]�[h'���c<Y��& ��Ea1[��Sddz4}��?��e���D�E��9?7.��{��e�9B(��d�9�
+��� ۲W�ҽ[�[���ۉ���n��ŒV���*g����B;�~����#�)��=QX/Շ��l7!�I0��� r����ӷ#{���I�B�S���1�*��,lC�ݹ=��|�Ġ�K�d�vg�l�xXL���w�;�Ϊ%�+]&�J����W�!��#�;hy�O˖�ۃ�יf��jN�Ė �YM���l�X�t�_4K� u�;�Cm��\�=�h��v8��!��-�xc��ѷ`����E�Y��N�N@C;��}�m)��tw��>��AQ,32�=i�7���/p*w_�7f�m�qI~�C̸�D��R�������{���n��`�����{��G�I���Y�G^����nS�q�jY�
+�L�,��o���� X�</����eg,��`�V1��D�k�>@��h��^s���j�IԉI�3�0P[x�ї�:N$ 4X �� !�T�k+�:<��}��Ƕ���9[2:,7���P͍b �hYi��|�?����_��]$���?� 8�hG^�W��@��A��:m�E�e�\s���j�8<%����s i�a=��wӎ�~AQ'n>Vg Wdׯ,�u��c�)Z��V�ƑA)�j�(8�S���u��a(SOR}�xT�zV*�h?����5��� b*T�`5�nY�{��)��iM�^��@�*�8�e4�N�E9ȴxW�3͸b,�Fe6��M� ��{F�h�*�� ���(���}����%��|�%��j�}f)F!��sm�x&B���h�4���(�cv���E\�`��]Imh��݋���o��p�ᘳ��!��S�S2�@�k׬a.hʊ*c�8��X�D9�ئDn�N���g�]܎H��� �k ������=j���y�ڗ�-�Q+g�^�9��]�ݺ� l�#s���t�J��-21�ð�1��N�+��[*�s�q72jp� .��@�u�0�qU��]k��n�f��;N�t9��^���܉g���ۮ��;���@�[N�bfO�q9����s�w��jL��v��^���[�)[�j�xk���[r�;p)Kw���%j��5PR��\��+0Ѣl�#.��]&a�"&5�GQ����W�%��"ȹ�C��Û�4,��W�i?R�f��ܸ$k�u
+37��,��n�>n��xȅ�Sw/Йj.Ke��y�O_$)婕�����g &𣞅]����-8��+���DTz)��}���S�?&$Ȏm~~,R���M_�1��/���Z���ԫ��͊���А}��]�-GYY+�u��R�CŸ��ˑ�����.aAZ-�����W�p�l{.����QJ�r�`��ph���J� >��CV+�>�GX�.7�~��I�9T��)o���g� � ��Mk!�'��P-;�7"MSC�I���O8���0���cl+m�Rx�2�K2K�w���.i�藓��@ ۊ%K ^�b���F��}��s@(.�^�S iB�:՚"BW��Y�4x�bquIB^������K���d���}���d�gs��){�/��4�{nO�V�o�A�s�ƨ0̄����]��
+�e��� ����&����.�V'�M�Ye�۠y���Z�jN�2�J�ϥOCn�� }v�|z ����z��� B���p�͏�<�c{^eܛ~�E���L�3;kTȁ���<�D�,�{5�۱H�o�QXaJ6s��J�Lߖ~�d嫟L4e�� tJ���QO�a�A.���e�%�F��ߝ��@2 �����-+�.���ј��6����_W��r��e��?{O\�ݽ�!�{�M���C����d�s�ڋ�~�+ş�� d�h�9)�ozUh���={�pN3��`A:JL9a��˯;\'�Ӳr���58��snI ��mv^�V7�%0�� �8&�Os��c�P����(fH��_��K'� �{�q��ȦkOԜ!)�y��� �����Z6�u�^����]�ל��#����$�����͹hwX+;�a�-�U�P��!�_ԡ� �Y��4>�sʩ��gu��JP%��>�����mZR��P�T&0ւ�Qp���GD�A��"��4����Di��H�~[~�v���U/+]���}x'WJ��h���B���e������//U
+ESy��mf�B%li�Ox��Y2 ��d��ƒ^*V�1�V"����j‹b)�CsC�<���!��.�3�;?E^KęWv���h��<����w6� `V�����<��I3uw;�5�y[���zv��
+����y��D���;��P�]8�_Ru
+���R{�).*L�v��ym�^^�R��ؽ��LDr��'�S��U�D���!��|��`N�S�8J�j� �M2������u�P������@u����@2��W�陼*w�#�O�y� �/��}p�H}� ��7��t���.&��)���<���}�V3��/F�� �s��]��~b�{�!1lA �|S�G}���v�6��|t��)���#C*^SR��'�0�Fb���A�K*T =|�[2ei�U5�b���M�������|*�Ɍ9�M�0˸q��i¨on���l��D����� 5��D�Q���T�˒�i9���;ىh)ċ�Р�{�q��@���`�Y��A9x�����e&�s��=�z���BV~�Ɖ� 5� ^�? :�R�f����o�fM�&�fcضd;�dU��=X��߲��w�ԉ�����p$>���P���)$�#i�+�v�ˏAn�@н�k�Q-Cg��<��~)۬��� Lp�j���!�H��x��A��Z��5ZbJժ<+!q����"��F����e����Ҷ�Q�Su!0ή�$5��̈� �I��.!h#4w� �8�O*�Bq�d|�"Z�`���X�B6Op�-Z�I������W��t��V.N�Jo��\0w�t�?l/�b�T���Q�� ���'<�dj�����Z/��5���C8E��[W)跂'im��m�VV�������z�c��15�t��sr�����A ![�L����A�l�2�]|�*UW��ADKa�N�����#S�*����ge�ע��o�­���� �����I%ͭv��ڞ���L�)7(�q_V+[��'[�ƕ: �Y%�����>���}8ӽGY�T�Z_x�
+vX���� ����0�^�^ǡ�}2
+'�nl��A {O�1����O
+�Oc>����{���-<��3���I3?L:�wV�v�!�D�e�X�uz�e�5@˲��v20Q�Q��h����T�a�Ï��>�����d��<oNr8��nЁ�hy7so�F�2��!����eW�3B�
+�_���㭀�/nH.&��:KT z�ͪ��#����ю^P�t�m5��ߔիPp�/�畷���ņ2]���r��Fo8��k��"o˩eK�B[�wSO�e��xy�RoN�ƪ��Q�±�O�˚9�T�vLF��π�(���d_C����3�LZƖ�$s d�_w�9S�f]~�i�A��3����H��6��f"s�ȳ�������`Ú�WV��~~ф�.a�(�K��Fx�0G����3���.�=�uu�H HUr���vX�|D�Yz����B��Y���[L��L^�T�D�zY�D��;(�� &Wz�Y�e&��.�;X��6�e�ј�BԐ1
+�Ă>�t�|ֵ3�����H\�M�(�l����r�<�r�@�B5�q^�����w�Sz:����eoo�*�Y{��B��������7��xof�W_��/3������η�`��s�z �ի`�}p��Z��t�.��,�C8)|8�\�A}����oq�HF$޹P�őacI���!<<��7b.j�m�)U�Ԡ_�8����ڑz�7 y�� kM�����Y�G�&Qz�;��kY�Ǔ�]�3�pz�0�z E�\�[�M��n,8�����
+k6��%^�6�=P:Ĥ�K��j�"�z�Y8z�i|գFsvU����� � �6�-�FsG��֣�y�/�?
+ Z?�r�;�ƴ���L�,�#;vn��s1��s M�MH�E>0�rzL�)�;w��B�O~%oi\�����1y��3���F,���3,���_4�GNQ�U�`�Ib��GW�3�\u�H��!�@s��U���� I�����Q�6� }���z;�)�o��BXK)��0¸2�Q�I�� ^�y�����l��V���Q�Rj��f�%+�!�ms��91)4��>U�d3�<h"Ooڳ�Ke��H��~�̤��:���Ȉ�FW �<�����H����B'wg��4�X��� ��@\b 5�i � ��06/��Fr�a����Y�15����������7.���hEP��]=���v���q�����o����@3�GXm��$�Kh<��h�h��<q�/�"�WR����n�_���l��f9�Fo�ٴ�2��p��~���C0^L�L�j������
+����������;z�E0m�ve�������m,F�U�z�������j�f�����q_{���wU���V��1��t��Տ0�[7&?�0�+�<�T���� ��h8��1�4��y7�O��h�҉BK��e�7d����[ �/]�jҝ�b}�:cGg4�z�xo��/�iƧ_&=<��0�4�,�J*��� ��n�1�2G�Uӧ~Ø����M�Z-�p5-V����;���a��@a��q��M��cd�үVԋ����&�5�����I��5����������t��*�>���x�L�W9&7=s�@1��C����?�gaV��)�#<?�gg%��Ô���E%};�Ã]�k$��;+�WTU�e�[�n��
+���zVez<RC� ��П9br,�o��<��V�� DJ�-*D���O템�@VV&S ��RK� "�"�'���~���wز����J�Bܷ*Q�\��7�*�h�gV���l�l�{� kޞ�8��.������2����>��)��7X����E�Bũx�C��n����������,��/��خ��Ȋ�_��1�E��U2Ԕ�@cW�g@�͔�ߟIyHvr ��:� �ڷ�y�����k�w�Z�8~�D�|����ޯj�����L��6i�n�b,���*��C'����ayA<�cݑc��-�@K��2t�)]<��v�Y�q�<�y5� QP�O��'�'.��O�1��b�O&�|"������v��n�o�` X�bG��M�0�J5P�����e�h<-��z�����l�ެ� �,�B3����XB�V���{��'UC0}?�*����η����?��W�!I�շ 1�������O>�ՒZ���O��!�u�;��c�F#�ן?��V� X��ج�� �9;���~G�@��y�����K��9)������WO��؜*�q�8~rf"<K����Pr��ȣ .0bi��I��z��d�SL��Ϗ�P�ߠ�DR�� ��\�1��L�Ư+�=��V�x�X�Ǘ ������i
+H���7u�6����CQ��I(�g���K�[3�������_��!)L����fDL�-"�m���fBӁ�TFp�9��f�������a(��r����Ax�;�M%GY}=2����y���\c�wkx!�qD&��7��K��N����������`�!�v�����{escN��g�:�F ��`��i�������Q�!��)��nǛ������/�X(���)\����=&b �ub�����k�g$������?%�����,��#�Y�H n�i��~�XWU��u:�% �y\�ݶwdo;^*���<5s�?q���Q�� ��;���E�Y���V�H�Iy{�;ؚk<~�[o5nٹO�l�zlp�W=j0��)�
+)��S,Oѯ�-��*'�����T�j$\�������(x�w8�����%��4���A���Xk�(C6���d�{^)�+"u���#��Ŋ:�v�5uЀ�����e��03� �qGq��߿�ʏ�1��7�g����
+ w���_O�0���!|-��V=�� ��DC���� �����@0\]՚�s��f�˭�y�o��_,���N�l ��4!����{��;Q��%����=��袎kYg�!���C�l����^� �r/,q��-�\�i!��l��(�Lu&��_���]�w���̿}�J�Ҵ�rH��"��ײbx��T輁6�?��Ի%���z�j���tb�V�W���^�T�uӛ����?o@�["9�� =��f�����j���?)M5�Q�r�"��[���.�Z!uv&�5�_kv^�Γ�o��������̮`�_Gˋ�-0�'F���mxn2�ϩ�w�bH�T�c�O�ˍ����wa�/4�ޔ B�.`��%���lJ7�F��>Q3"��;omjR5���)]�Ԙh<��Xx����;'�=Č. �[6$E����1��`��s�i�_���6����/b��T���s�C-��:+�x'@N��+Z��V����Lr��H�(���5��[,�n$��N �Gˑ�W�&�6g�E�E.)��{MU���>������Ԙ�(�|�7teR�+�p��$�2\d���<�3� 4?�G���V��7zyQ Ԕ�N/ħ��u��W|l�K��ґH���8�H_�o�"���/£���N�C@8�~{Z�8�[�A�Yۭ��o�B��?��?BTfp�9S��d�X��:��M�S��3��в�s�z���~/^����,��[#���l�BR��&�e�w}�H�6��S��N��"�Y�u�����:F2}���:����C�Kg<7Kn��bz�}��~��>C�����#�(�S��x���p���R��'Nq��f�����YKbP�(��`[�c�W�{���:�3:���+�A\�OYk!<Z�����_��̥V-��|��� �X������s�JS�K2
+�˟�y&�(��3��S����}�y��'1r�g9�4M��ƻ���1P�|�� �����&*B�����"4�X��I�H6��m�ܲ�$1p�&Qi7�܌�M6[�ꃕ3�6�� ��Z�P߿
+�A�$�� �G��L�&vx�gnRXX�M��R���lg�dx�)�̭F#�;F"�St��uI���f
+<;�0�|o�.�}���n���
+��'7�H�u%�W�� k�X��ի�6� ��~'�xN/K͐��+���![wz��w����{�73��.�����Sa�9 �e}�}^Hc=:��=��{}kq��6"@��^"#� �cz����h��EpJ6��P�5�.<�aD��Z`���:�����.=M 9%"jy��c�3���w��t���F���8G��F�_2=��������2����&��0x�oă��Cd|u5��?W�N~6��I��J=z�X��d�s#gx.�lP��)�T���~-�?�.��yo�?�|1�\�c������b�\���l�����`�!��F��1j����?��Dp�B)7I��v��屌�'��[翐F�5O��ZHG�͞Z����ΑqE������/NЁB��Fhe#}-(�w�<~˶g[$�n�R&���#����;v����W��YN6�ж �(3��F��j�)�F^ � 5şp�N�k�g^ �I�c��+�sց��eX� ��!f@���'⴬�M50G�����z&Ԛ֟ai�vO@�e��ydqWWh�`�O|#ˎ�P�@J�~����5}�N�C��wö���+!���4�eU�������z��}ȕ}_U��s�|c����r+H�[�}&�z��4ǂ�s�2���p��=�5X?%����W�EZ�ǧ�{����e�����?�Q��
+��i��.lCso
+�"���pm��%��}�R�1�/�N������ά��t�m��_M��/V����ȎM�h�)�[���+��� ��j��U�b29?�����n�pl���kɪr������9Q�mpԭ�:ք�q����R�p1'�Ag�E8�4b���nL�� ��S��+=������t�z�묱�^�I�m}O� 8$H���\�U����:$�C�n�y���ߥ��� ��L.�1��n���n�wahnm}�~�
+~Ev��a>��=0:,H�3�i!˒Ÿ�=7=���,�!HE|_�m �u��a��@Hl�D`nGM�~�bj����P߃�����>�w/M��ԍy�e�or��2�5��P�B嚅���t��K�yPN���w�EFwBJ�:���>0���e%r�� ��!�)�SH8�K ?��c\�>��q�7�9C�Z�hy�a��h���q��D)��
+vl��r.A^I�x���Gf� �.E���=r�gޢA������˶�cG C�r��� ��M�,�DP�+��_��"��ʍ^xrF�r#1m��ByX)^� {����u=��P�?3���G��nC��4JMl�i�\�1O��B�7Ec0�?�
+�E�-� ��ɓx�?�q��2&`�'΁�����-g�ĈSH�4��E`[a����P� 't����f���L��S�Ȧ�ߒ����Zt�30K���~�g'6wޜZ�=jXTL[�E^��:��jک;Ϸ3~��k�c��Y5��A���I%a�%K��8�X�EUP�n�� \԰�U������4�a
+�Ǵ�6U Hl3y\�����FǾեS.����*^�X����i���Y�������Q!n?^w+փa�n��*�&��JM! E���¿��G�����+#0,����J���\-�]V�W���SxW2t���O/eD��D>�
+�m��z `z�(�|��͂�x���>�)���)�W�*�]�Uq���6h��K�C�ɠ�)k:�M��%��J\�詫�X�JN�O��D�� Ao^v ��EӀJ���>o�N�
+[�KN�h�*��Ds�4��YI���d�D�XtL��b�i����`gc�(Ue� -P�$�)@��ɥ�>�Ϊ�|{���9��}�d)��b�1�}hGU�C� �-qG����$��j���'�j���+�|7~�ï}.b�U�}��d/�?��(��9����[��l�&'����b�\*�Ǔ�����*/Cz�����V����U]3���!#��_��T>��em0��7���2?�0{SR PNնh믊�5+o����}-u�>��Mw���T' ��/������|i�%C�XP�_�V��ھ����@�=�-T=� X��d>�$�<4y^{�����3�/m����&��>��d��Ԗ�<&r1��4˨�P �:���V��T��k����hw>� ��J�@½��L�Ԫ�ڢN�މ��-�W#k�� #�L�����i��HX *Mc/�fkw
+�m�Ub����Ҧ�^��ۨ��$nc��ap�t�:8�E�J:�U6��~���R���rbu6���S�/���H6$�Ĝ�: �,[m:!��o�c]���PG*�&�J�����%SH�=2Ÿ �nc"=�X-�2³# z�Ѥc���� "��w0���8h�c�$��iu�)c[:4�\ //(Ga7-���Ӹt�Ư=-��Z���� k>l�øY�?�0�d�23�5�j�����`l���"7Ba:�p�gñk��}ߨዬ��@�4�Q>��i'�Gw�3�K�?�F��X��(C~� �j�j  o7���1�;�k�Y^�ǧoK�ux��~=�]�[�X���m�&A�e�XZ��s5_17[ \�+��`x�}���q��8�_p��9�v���3�m�=����\��D���n�_;��Y�G���u0�LVl�������a1���l�'^"��x�2f�!^���!�>!C����و�����Q�*^�G��\�ꆊs����q�i���:Ξ�'�Zw� dÈ�l+8o�+]: {vJe\GǨ�w����2o�9T��t�7=�'T����r�^�4Ϭ��_g���]s��V��26�8 18댂E(�Lu9�n&�p�@L;����&O��I����UIA�u~F��h�G1w����5w �Jd
+訡�؋�4�k`F�1�!���$;�J��M�����C �X�j\£�U����W��Q��V�S�]r�Ž�gGO���Q�~��>����㞈 %?/�g.@¾�d��� �葬���Z����Ol��R�Ǭ�@�:���N ���.�Z��(`�� =���6���PD�?���m�� 5G��Q�[%Q��
+��ǧQ�#G#ι<�+w;>�d�!��=��t��=�A��> T;)r�#C�*��0��4mm��^Q�J�{�zy�Ѻo%P�\�֡AӒ??�Hpg\�iW&
+�Q(X.��"�����z��`=���ǭq������  �Y�`�r|F�k��mI�����Ԑ�($����y/�TF(Y'�E�~����j����ڎ���B%����9� �����oܼ|9I��Ue�����ͻM��ѥ�<5a�(w.��aoBG]�r�� Er��#_'��E+ײ��zKm���r?�����w)���v�P����%!��p?�ZPQ4w��c��wٍf�f���xe�/꯶��I�́Pm�|c� Tn��5�����ݫ��jL����g���n)�0�#ϕ���t�ނȉB�Y���t3{�O�"gT��$J/���Ӏt+X�]XU䌰��J6hv����KL�h�)�ۡ�j/~���Jay��p�����,`cYο�D��'�!���e �T�(��X߉ t��'�T}0R�oι0��2ãو������Ɏ��ԼLM=��2]��%/��W��gW���f����G�z)rD6,��v;(�f���_���h�V����o?��'�����i������~J��. ��S�NF���V���.�q{�� �0Ib�d�b��K0�B�0���b�[n�,�w��k�Xe�4ܫ&ڨ~hr�)�Œ���W�1��l汙Ĥ���·)����p�k��&���۫�(*u�F�k��B�ɐl� �U'�p����������zSk�D
+�n͛��H�Mp�5��9"_�ԥ��A0�ļ��5 ���jJ�.��Ў��d��-bH�w���LRV���G9ݡ��vӒ�83�K5QJ��U'���^���
+�T�l-Hp�p>� �N&�P��X��pz($4ѭ"R����=� 2�`ustL���� �h6��Y�pP�����9)zXW�A���.;D ��h��A"��%!Rq�D��6�S�� 7�0�%-�H#��w',?��6e˗�)1q�
+�Pn���qؤ{�CTs�n��)*W%�H��o_��XH���� ׍�Ll�L�j�K��ߟ�>M�C^d�o�F�>�����9�;�J��|�Xې���|���u�C�K��Q��;�2^�t�Z�pE��05m�j,VB\ ��z�X@Nv���*N| ��r�x�{�-�� �{7)��S>$� ������b� ���aY�N �;E��uvMg�x�ik�E��"u��e^����SvR�;��(H����ˊW�R�M����� P�c�d�u�����b� ��)q�����m 毪sIA�HR�N]G�!�"�R n�� ���TL(.�*�R�"L�Rb[��E��xv���yt�K��v�e���Q_�e鴴� g���L�5
+&����I4b8�N��Ƭ�~�O�%&�9$z�!�ؘrK��jwJv".�9p���"]�b�fC�|0����s�M�P�UH?�11N:������c�V���@y��8�����rb�|��5�!�a%����%����f�jX��W4�������n�X(�Z�@&h2V³�q��K�]ni>�M���Ҵ�X�|' �d��#�G�s�w> �ᨸt�7�HU�(�A=r����6HTC0�<h )I�A`��<�ڢGO@����+�l�K��h�v�F�D�D+�#��P.���_�B��-N"'{��DR<ԙW�;Lު��ऺ�J��i8�����W�����5�v��HF@�=5b�����y���(��Q��+�4��,S��]3�$���'ᔱt^�O���lj�/�3bt:�j����la������n+�-�G�RĻ�^d����^,�� N�ݣ5Z�O2{�
+c������7����
+��xgZ�N �|�<�r��gYnSE_}��A3Ѷ^ꉻ�Z������oeynx��Zj;�^rz׃z{��O.%����n���|Ҝ? �X�����y� v��,K,�Ӯ����W���;� �Z� �NrT!Pk`n��H;�Q�c��+��� !��)�3�2��$f,2>.�� ��lSY_-)'�7S��?���a�B������hgX�0�܊�]�!nB=��H��g�1Ki<: ���vgʌ*1�d�kc��ykT���ߟ��MƘ�
+p��<�"�-�b�򃃜4�E3@�z~%u�Ko�yg+z| N�������k����.��2|��R�&Px���b��f�5X��3�zl����v����r�j_ў�s�ͅ70��M�_�]d��`lė]bk���]��UfFr���
+eG(a�m��b�H/4v#��z��@:�(m�:�cA  �zr-�3�V��� ����q{�=/s�U ;��^c�"�s���-~YN��DOt�i�$v$��9�X�A���Yz�"������2&~�2���P��Jn�)�7�}<?>!� .�zv,@IF%Nk ��)�G<#�?�)7k�o��I�� �ep ���O�pv�U[��ZT����dUk�<IJ�H���R��}�d�Q�C{]��UY���w ���)��?�zy�WҞ��a��<ߎ��2��^�3s�`�XM����SZC/��p/�Y�ϝ�%�� $u6���*9� Q�0Z rW�od�,~^6!�G�.�S��S*+ah��4��J��PY��CJ)P,[x{��h������=HΒ,�wd�rrj�p8�;��'�^K�mڥo�_�푲�W�>/ '��ʲ�{
+����qf�.q��~�j�R�j���i_��pV�!�Npr F�+5�|��^���������ȸvv��/�|0�hb\`��z�=(�����H�>�k��^�_��� L g�.F�}���J�MƁ�i4`_i��m��r�՟ߴK4w�P�ߡLnG� K����m���*V]��֛�t��(��Q^a�t�'�Xüd�6Ȍ��';�La���y��2�ܽ����1kc��%��l3�~�ZC�Z��9,�d�T�)����rR[w�i��Aޙ6J��i*e��v�֑�l�w�J��P����;��Fx�a����BN�Պ ���ۋ�iU��m�RR���L�Q"+Yn�
+������e���W��O[���[�#~LqiH���D�Ж?���,iG�6�"ڂ ćw��,<X̕� :�f@8A�62Q�����(��h ���b���7e�'Du������2u@����.B�؋��&���oB��SR0ɺ#���������Ak��ԘDRj9��֏/�%n�5�H�$B����(x5��.(���#��ZibeO` wouEK}<n�j r��
+��q+��� ���F�C%Neu:h����'����3 
+�Sl�燌�FSi��Ќ0 :;�����6)z�L�����9A(���w����D�2���ڠ�V����gE 2kY�*�4[�b���5��4����U]�� �WѪ##Pe\6�s�~�����v�q���E7y��ȯu]L���Ô�;bT9G�n�����z�t[�G�K�1BU�2 Y�3Jh��hu7K6�Ji�Q���^%a4&��Al���~�� w@�j��m�jŔ�`�������8�Yv ���,�;��u��rJZ_���l�<�[������PPo.m� ��dU�l?�Ŷ��w�x�ҟP���}�QQ#�}ww�
+C@��|E��w���w������+|�:��Ev8���*�����P$�0� ��#'�=�� �ۀ��̛7�;0I{�L|�}�w{4{��m`���Z�����<�L�̋����=EC�&���r:z[��~M��c���� �n��n`�#��s/)�4��>�RR���-�hN+!g.2 ���0ҡ����3֥?��� d,o��{��8� �[���7�D}�`�F���,�Pɸ�W�.Y��茵��W�� V}�h��r�
+�U �$uD��j�'۳�O�\�f�tv`u�%�P� ^�f8�M_+.�����] �Ee�*�X��Ye��~0w�OaL��-�~fm�\���Kxp�C�+MW87^@��H��`�4��[&����e2�s|a:O����Q,.��L y�u,�;`y��$�O�fdOp}%jm")�kQ���erKx�2�$*�5&}���nX�P W�_a Tv�QYꚿ���a��t[(����q��R��$+#+ �D%oؚ`]H��1 r��cm�ܫt@dgF�A���iG@KcX�s�-/i��`�5hb�lg[�,����o���%��\۲�0V|�\�!Cz{w��]��Vv{ߩ����Ň�m8WۣhV1�#�[H�ɶ�G�Y�P�<�MB�㢁�t�d���p#���1n�'�:�ijY�z�����l끞��p�ܣ` p� ��Q{ ��^v# Giz��ܹ�7���璇�F&��?��u&�t�sR��"���2x���%Ao�3#O ���~Ͳ�G ��o�r/JE����?OT��W�J�)�[ky�֎��H�91~��̤��g5��+����͏R/=
+}�b�U�@X'2��LPP��Y|у�����.�ΰ+��!�v�Z Rs�� .p�y��:#enē@jf��Id�փ�� uDK m͐�N� |���ظM��u�ૢ��0�{�>ix���wtP�jӪ��.�ſI����(™MN�W������a(��;S����c`��!D��Ǧ.��?��_P[ ��b�1� P�Wˬ�WN��)a�D���}k
+�����Ǣ{�G�z�d����霢��\�7���cp�V ���i�����gT}���Y���O��n,#��v#�3��.�U���ו��^�����O��UR/�{V;ǰ\���]��S����-����ԕ�i�t����M4ĒSDU�7
+�z0*G��G�M���h@7)�o�y�=e�k|(@-+2�$��;�0�i���c�l<�pı\1q2<���w�\�����g媱 �i�u[n�K��2�|�1�6m��M>�Cv�9���a8�#<6"�ψ��,2�v\�*�o$ž% ���{���4����� }&�AƵ#�˛;y3s���zUt�_�K5#7/+�?������E�p`�*�mB�zB�69�-�N������ �9�8%r�ڔ��`���v�>��J^����d�IĵM���«0���J�����6I�#��x'`������!�aZ�����g���n�p6
+���O �~���Hm��/����D�R?����tI݌���UV;�y��I��٪�}���v~��{5t|+b��o�����~ka�N�� ǡH�ݭJ�v�39����&�p`������Y�Ȗ�/�"څ^��l"�8 q=��� ���V��D��isD,�#7�Gᬼ{� 2N�wՎ�v~��;�����Ϛ�ac`JF����:}F����v-؆���oQD����@�4���l�V��-'��x�W�_{��hjI�sX��fS_]�e/����B,l+#�c| �$�Ji�]��hD�� ��t�jf$H�C�12�I��'�բ�)Ub#Q�o�rb�Nkk�^���sLs����|��3�W��|�~I�B�SEO-=ռe�)o[ .H�N�.�q,1����i�ҷ��o�{�������le��5�Kn)
+����5#��m�F+`2����C�D�&K�n6˹�� Sd�A,FEG�j�k�v��ob�5�ޝv�t�6a�/�o��H�P��'��r<!�g [�nFs'=���+�5\���pa=[�YlФ
+�RUxT$����\�̓E,��ɸ���_LS�� ������3��d��j���ӹ�*���8�h�����d�bV��,����&ī�x����],��s�f
+Q�cRԱ�%��&�Cl�LI��.����t���b%y���OF; " �� ��r�RiX@�/;PM?��4��!z�$���uw�d"{�^G]8P���_G�=�q/*�c[�m\�f E��d���0XD��7(��DD���֝V�7[�����h��@b�s.r���e��M�; kB�ݽު� �Ѹ�G�Z��ct�?&���!h�"Y�$.�
+y�W��(1=+��<�.����엷���AT=S�@s�_�m�g�L6H��QJ`�b�y#٢�0��1>�4V����9�}���lZ�*<c��*q͹5�\�Y�c�.��c�9��,(k�퐧mYc�V��S�V��AB^��w[��h�=.�:�`4��}�.�w�o�Ė?��q�qQ���ܴ�៞Z�eft<���I��ǥ��ŨtV{�7����d.�j��%�bS�^�`\
+�T��`@96�rT�,9�I��o��:�D��)�G�qJ�S��D=m��n ���w� ƙqN��<hQ��7���?��Ƹj�zRU��.����5%=#]k�r3����gl{=L��c#�}������c��K���V5�Y�����>�t�|�ʎ���tG�b�v��eP�wZ�9��p���t�=���Z7@���u�jY�� �~�4Q��bWu=Y�Q�3+�LY%��ҍ�FS>�&>n� �� EǺ�ҵ�]+��2� �Wפ�DJ�+2�p��$�^%o�[�z���X>�<:9ֽ۫����m�6��bJJ������Ö��H#������<�}��ơ���eX5�Ff��2�?�o̬4}�[3�G���(1*����ҵm��-e{��4���6��x<cγ>X�i����|'o�? �I�
+K~Q�1~���&�@�~>L�`f�-���/8�:rnP&#�󊵖 b3�/�H&Ȕ�!]ͧ|\!���C�R��A*��W2�`YV6�y��XQ��H~���H2V)��Z�6�rl���ɴ��
+v��q]t�tJ�� Ȟ ȟ�9�C< �g�����3� B�O9u�8���!"�r�]��V/@��l�#�������(83 �(\k,�b݉�� ɪ:kS�[ӋE V�����j�qL @ a�}���Cv���a�F���6$°�^�go(Bx����w��G�'��DX��~��H������9�|W����3� _;H�ӂ���w�ÌAD�M[Ra� ���y)P�:���\t^, �A��v����+�JЖ�md��M!����l$F��!��t�Ky��:�̓T���P���g���76T�Kx� �m��kt��������/�+d��3&2�Go���|#x��� h]�������>ɼ��ѭ
+ˊ_>2�t-�%� ���?�X5��T�SM�:�*\J-�k�S���6i���2����fX �?>H7s�����z�Z(G�x�}A��Z�}�~�,n��c.�C�>�A�(ۻ=�B���O����q��]��qd��<<^�>]അ���+��ۛ1,O��̎�vv��Q��`Z�$��$��힀�~� +=���4q��#�ꡒI���.*�Ts7��c����`*P�\����[�ލ
+����N�-�0C���rZ���X�#fA��H��i�)S�]5{�'��d3'H����6=>W�6&N]*ʕ���w���6^�Z���~f��fϷ�>@`�^R�a����޼����s���tEm�&�ױ��_i�X�|c�h�ڌ��M��i4g����Cx&�8��'Єө��j0`rV0_���>u
+E_��/R7�(br�P$͘<-��!`�g��PH&箘 F�����q�X�`ca�J�Gr�ޭ4�-t�~� �kFL{�ْ�¶}Jh��g��J܂ ���.!J�M�A�#�j�����K�[+q�78���A�}��o\߮ ��>�ȁ v0�S�,Y�B:��ޘ�jQ�?�9��È��%n0 ͢y%93����R � ��9.�3�AtEl ��� "uO'T�ol[Zʜxp}�
+�R�+�1 �2(�L��-��w��DT���p��ND/�Wg���oa��އT����Rw�����f��"�.��Q���ڈs #�;������B6�tE��K�_pE�����O�RN���0#���Kk�7�9� Ϯ�q���{�~�V������� j0�m2Hw��k�]�� |��PT��}�VZ瞶�+r����7q_����O-gE�!�; �C��."�< K�$h�p��̪H���P� �g�� m�J�}�O1�����Я������F���jGq_F�n ;�i$,ɑ�.z�_�?�c=���V�ݜ�f)�Ic���4G@�T���ؐ�4�R��;[lؘ
+\�(�٨1���Jf�xw�xk>���\�r
+-JA���V�_?rֺ�r|2���Y�����
+K?NQX:�����zښ�򁟶������L���6}�C��|Opr[ʧn�hC�?��ѳkP��]�:^� S���Ą�'�WQw�G�(~S��k%ѧ��7s'�G�m��n ��(ͧ���p� H��F�)�� ��pNH.��h ���@?bm��s���LF5�]�oV�n$���N:[�! ��ѭ��6�DI.?)1�
+~y���zj�ýÌu���
+>zn���?����_�wÒ���v�]����ɔX�03��).�A%�����hT7Ӎi73���u ��$~�̫�/>Fo{IM������kd�" ��c�-ux�[�i����v�C��,k�ç�k>�,�P�y�%M}[eΌ�~��}\ �^w�/iY�����]HI���K9�n���v*��mB�0���P��P[6`�x�P`�$X����B%�k�_����y�Qz�'�`L��<ۃ���Jrź��0�:��^���� �[.��P�֪9[�Fݞ�va��1�G����D���
+#�?$�X9(qO?�H-�B[�a�� �C���_\b�Ŏ���Z��Z��hMG��{0�M3,�jB�:6����[ue��;�dіxY�3�̤��}��} ��8 ���ض��V�ҍn`Gn]�Կ����{0@C���i\o`.�ד"P�@��<9��K��*��U���c�e�m�x
+�w�SW�"(��Nv]�78��
+���k�����ˠ� y���! f�K�ŲA*��]{hi�%�nMf�G�򙛝�ө���}OCX���"#�g+.�P��"�U}�>Ń���å∨��7\�l<\q���� m�Ps�Ar4�X�w�ڬaO"�Mg>,�Mw��*a��@F��{<��hV�1��Obo/:�Sn�>�Ȯ�Ah�9��|zԓ,�&�tf��E>�p�̎�p��&ʼn͆|�.��K�_\�8�NaG��A�/\�sơ�m�8T��#�I��%xJN��]U5�S�����NyC��� W��ӈ
+endstream
+endobj
+853 0 obj
+<< /Filter /FlateDecode /Length1 1374 /Length2 27197 /Length3 0 /Length 28158 >>
+stream
+xڌ�peߺ=�tG�c;ٱm۶m۶��c۶:�ӱѱ��wι������Uk��}�Ӝc�Z��@^�F����D��֙����($#�����g���g��([8[���@�j��dag��C9�8�� 8����%]�� L@VN6Nzz #==��9����@Z������D���������o����Q88ب��1q�02��8�����hd` T�3�0q��_)ȹ͝��9�����h l�h��x)��n��@E'GWc�?#e lL�3-��ln��o�������� ��������o�����#�ou���4P�����`����� -���O�?�,l�l`ddgco`�aak4��6ʉJ�:�;S l��X;���7p5��60� �W�@Q��� �3�����������?3�����6�� ��ؘ�:;��O������{���p�l��l��kejakl���.�t*�.&����5��ff� d���gc��8M܍���)��ao�/'�?�3�x���M��a�caj����d�jtvt1����;��
+��4�0r��Y��'�_���������E��~ @�~�}��a�v������) I� Q�g��v
+
+ڹ�hX��4�, @&  =���7��O��+akj��w���Zv���#
+���%k���&@��!�6= ��� ��o��+�����d��$��ّ���������?�6��A�e���_���Ղ�� U3��t����O����_-ؚY��6Z8�Z���[8���.����#4k [y;'�-@z����W]FVN9�/��_���"�Fv������h��h���K%F��_9�����@:Z[;�!����M���(����Wn#Gǿ
+����-�_���������lg�l���\'��Fs8ͳ@r��NA�����
+�BQ�3p��Q elac_�����뼽 2�#I����]/Aq��:��k��\�q��2������j���v�^I�<v8��g�!1���ߓ�ˇ
+G��R���41*����$���K��4�P�H����� H�3_�� T�?1L�^�;��/K��UʌN}�Ę����&�H�OR%�W��J�$C�JLqu�[y�� �� z׸+&fv'0N��*���B��H�N��r{0���J�?�
+N
+=�h�QՋ?��~Y9_�3�e &Z�?��A��������b���'kJ���OXe4�w���2p������|�33#f ��u��q��< �3Fd0�`N�����6���ˊ�<f�d��d�'�נlιQߺ.�� ?̷��C��U�
+-���LKN�~[� ��H"F��:����lAC$��*�@����2��Ԉ2��0���'y\�馹��p�S�ZA�D�9����q]�p���"a�+��J&��¾��ٻ^IZ4֕�E\�teL��?�ͼ���U��#�9�0{ADY�������c�T�*�n�_7���&�����=�]5YZ�br�y�+٣#���6&D8�E�[k=��r�P�֧
+�XS%����^�ĩA}\��_��{��u�.���<.��K����k���Q��>�m��}}����iOʩ�xLUǾ����n�A��
+�ߖ� ;��w�h��P��;*�
+]1�*��3��5�#YW3Y�~/f6�.Py�#�u�ӃR��9jT%Er�Ԣ��� –�I�.|�/�}�g)��6�����µ�6B� �� �ж � ���H>;��y�ä���0���r[]K�
+���Zߜ��ͪ���L>N�~���oZ�NWl��$�>�Y�4����\�,�c�lhm�7���9�`�w㎣1Z�æy�S�s#^����$CR+c��M3M��~�s
+�Z���&MmjMƢںT�}s-�eA[K����S����y#jB�K��A)sQ�1x���|�0$5O�D��(���0S����0��=� �N�c[��m������Gپ��^���R� �\c�Y #�� ��7��I��;�B��Ƣ�ם�)ߝO�<��e;��z��g�>P�E�ռ�G��)-鐇P�I]��&�T��$1.�_0�1a�y��}kt+GAUxk}��|)�8�S�riP�f� ����m2-�^��@�S����jV^Nn���N���k�ڜ�C٘���e���v`'$�p����驓���}N�$��*=F7fY�.�Rg��dA&���Qʂ���|���iE�^]�Q�G��H�k��z_��l[�����i��űc{Li��xkY���m�~xy��D�4�`(�� x�P���7|b�����!9�T��=)
+1���b5�-{�l \��@=�v�*o`�%�R���!~�>Y�9�.�� �ĕG�`�3]���W� w���j�)js�� m��w�߼1� '������0Y��6k����|JQD}&�]x��%���2d�H��r
+G�3��@O��9��<���������X�!���6{Y��G�� �O7i��oj��n4�T̍�[ż��E�<D5&�R�jߺD"j����h$��G� q� �
+�4�����R���x�e/� ���㜾�d��I�������.���/��ec���Kr]KRi���q$1�X1��0�c�m8!da�����Z���sV7/x#n��W��Ixy��m�y�Ho'���?�R����cJ��l_���}�b��)Cups��-� P_$�,~�;L��H����y��J/�p>�b��n����6 �����
+غ�K���g����)��\�度y ��|/��6%|J�q���C+�x:�6]��H�ʬ�W���H�,@�|:�=�d��Fy���y��S� �
+���0��H�`�����R3�5d��o: f �w�,(~E$(ö�O�CV2�I" x�֖iBT�_�V��Z�v4�+�}�fa K!�_sE�
+јi�@=F�:P*��i�mϨ��R�f'-d3��eL������L����1���;�Q
+uW�ܦ �E��3�&�e��i�er���e���eLc�/�(�e�]�HdN��+'�/�>��iW��j4���pAA�.�*e*��Y��$�]lR���i2��v�ˍ�u�Q�l��V��F�� �i�X��� �I�x�}s���P�X7?07��y�I;�%�=+KBhq�W�Nc��E�E�>GɠRv��ɂ[\]J�ޙ�.ҕ�A�L&�!LO�L�m�� �9�<xjw�g�Wm%+�e82����ɼ���-�d�����^�������5i��O�ُ�Ʈ���8������OK'��|���"VDm<1��+�b�e��������~���[&ˣ�j����}�q��S��v�L�P��hz����Э���z�X���P#�=�v ��C"�n}��g�z��7�( ���T*m�P<{�n>�V�8-�P�2�F&YO�rՉ;�5w[m� /���Dk���j9&Jb�[&�`���4d��W�ߒ���j n�5bJM�A��[8T�����V@��_�3aGs�H�y�c��#)؂�o{��*@:`އ�(�Q��� �O^@�~M���9qoދ���'�e�w Y� ����$^��j��z��ިkk ����9�����ɖ1�g�=��J�載Mn�'-�Ѵ�����o��P( ;=��A�gį�D�&P�<HKV�и7�[����qѹ�5H�M0�n�"��3IJ����e_ᄖ����N�?d�V�Dj��d/I����4Š�"U�H��C�DŽԷ�Ζz�J���e@p��O4���=�2�R�eX�F��-�۸A��.��7��_"~t�願⋧+�z��βCTA8;_c���c)��l�W�f4sb� ��#2���W9�[�����j2t���vm�k]�d�|�Pr�/�8mq;�� �0���60q�@�4�훥���%�yA�<�j�yxk��Q�7�����w�/�������+ߺ�u�����d�G�c^5Ҵ�^�+��xR�[��2����A���� B�G����i�f��ʅ��- �6�#D�,=x�~���=i�G�r� ]Ph�׃/SNo ��9 �s/��P�8OU'��e^��Ő:�0L�N���0�����d�)���d�U"�����*��sK��D�u�+e�(`��>�}�|�ɉ
+i��/���^�SV�/���\j�2 ����I��v��[Q&�w3����(����e�L��V���1ڹ�.Ƽ�7\O��z=��;Q�� #�٬Ũg|[��W��%
+�̔���D��/s^�WP��{5-ڢ�*�p�{��/$��ZfM�!����HBЋ�����V�B W�$8���$�-jK�?��@Pd2<���P�}�4�/���-$
+B�Kr�&��(݃*�u�*�S)��-rAA��5�RUAul#T@��ޒ�k�(�@,>��$4�$U~�i��)��-��b���E@���S?��]��0Ϝ���<��ܟlܵ��qt}Ȓ��%��M̃2�w����{�,��lʅ�� �H
+���a��S��2=W��4�]y�]�wl<%������;��m*_h�z��+�@�KF�wɪG�[��|uj�j�.b.�l��Q�g��B2�z�)4r�� rw��G�V��g�����6��91E���������n�P�H"n3h�/<�y�Y�Y)�������q���h�伾{���[��{�_�PA�=�a�,��<��e� dV�Ib���]!6�\����Y���� >�e�?�- ��q˺Q�z 7���c@��Eo=n�nH������4#% �T����W�6��ۖ2�"�06�e�b��*`�Mp���ϲ!�e�_�R���:CE���|����W�d+��V}^��i|��t��$F�M���]`�A����((����.z��g� -0�����&E����.�/�T_���̈́МР���J��Օ�5*nr�"+o~��׷�<�q�ܿ����C��Q@�?�34��c��i�1`.�'F�Z44�O�����v���H�-V���y�ނ>D��f�<RKgM.-~��my?��5�/ ����̛�E���Ds��# �S Yͨ�1n�4$=��o@���T�����GY��E��_��_۬t���W�p3�s���A��%W+�m1��x.�Ԕ�L*�}�!���㆞":(ò1�������3ao ���X�8�?�jGƱ��D�UYu��wC�I��G�.���^�>Q��
+j�ǟG�d2j� �s�BM�:}� ���Kj8V�u�[̓-Ƒr����#�{�F�ȿ�����#H�����I�$E@K�|JQU�`z���xǖk=g�)�v����{ ��9��z� ���s��{b��u+�Y���x����W"D$���~�&ӵ:�֐z@+ӽ"0`wA#��5}�G�����i�S�X�M(�W�J�(�G�H�@@u�Y'Rx������2��e��6�o�{�����:��JG�����Ⱥ���9L3(��Q,uR�p��U���םE�i�z�u��xP8O�ڋw��l��t�LJ�i��������#� ��1�c�\0�}�X�2��!�]]����EHȑ�R��I���B92���]Yp@�(wc<�bƻ����=Y�-]�i�͠�A�,R��h�+ |�)�M&�`Y}��wq
+ �wi=��T���ʽw��o���^`z]k����(����;v�ן;��G��k�VUЂ�|��p���SL��L��Q+�7B�~�km�y���B�^i|�v�R�υi����Ť_�.����c� ���-i!�#Ù6�z����k�� D�B�#���vJ
+���=H�]A�
+��4��������H5B �jr>�a���&$���Lֈ*�oqF)E�%�ʛ+A�M���d�Z4��Wb�_5���>%_KLvU%���Pf*r�o��^q�~?���x�"�~ ]kV�� "�-��(��Ce0�m�O���I���~_�r�0o�=��+��'����ޘpO�s�0�%�Q0Bg��}!N��+ ���t �P��1>�8W����2m���mv���$��#�9���ʢleMxx�ӕ��x3n��)e%h ��ڲ�I��ܷ��GÓ�U��v7Vc�i�`�4�D�Tg�+n �d�;fZ�qDC@H`&���H��[C†H��G����Z�ذ �,��*t3t��:G "xP��I����&����|��"��`��Y���e}Z�y2��!hR�ؑVn+A|e��1�B��X��m �1�qu���e����������8�;���n��5{Δ�@N%��]v��rOq������Œ
+O!mh�)��e���?�2hp���Q8�Cw�[r���z��P0���<�E���(�vXWU��������J����FG6de��%V���lP�F:������x���i���i�:|�L��%���) +H���I�u>Y⨭\���̊�q�~!s'g��P#�m�\�? BK5��|��j����[�U�Sh�q[4v��I��wR���뜶� ���̳$?
+�L�zCf��DN���D�������{��z���������Ń�`5o�ά=R�8�����I��kpH�ϟ.��#3�$�`<�ɮ�t۶o'��b^�$1N�8�� =0���;���:'/r�L�x�9:��ˁY��3�R�S�̪Jy]���S�F̷y�PF����k{��0�0 zu}+���C�pAY:�#��b�qO��B~"���k�[5I7��~��eMD�.��6���=(��� ���
+�C�(�+��h3�g�hc�d ��G->��N��L����3`<�Ϸ��y�IS��t�t��M9�H`Ӭ� ���\��3��� �� � �IRUl��0p�df}8�6�(G$���`Gˋ+=0�e�DІ5�"�ps8��=@��ҙ}��:�J����췝 0��X�r�=��PǗ�$�w� �>oP
+�Cm�|מ�[�XF x �|TX ��,�5Q)�� ůtMc�`��g�itdf�����O$׊����c�Ғ�G������ϖ����gJ�w\������az���7�?���>8qHAn�9T }�������F��76�W��t�[ʵ�g�{�&�|�Z-4o��ڥ�휽f ���s���a���0�T��/U9��8/p�[���)��C�W�����
+1%>f��:�@Z�HZ���t�o���5�TA;��_旚/Ί���D���~�r�A�c] �� Be9co=g��f�?q��R���͌D+M{)z�rZ����9�Y5ݏ.v� �ia�N ��y�<��8����(>Vp����>�됷<�hu��NqxC,8�i�IQ��E�`�9�K%��3�,hF�dis�h�3� �5�r*�����FO9�0�o�I2gjU�Fiy)Ho�����j }�M������g` ��N���E3(����8�G���k���d��'��3rU����q���{ku�7]쉦��RrFH�*bģ��n�E%#՞�*~װrM�aK��]p�Z�!Įp���4�k�,}+Ҧ�*�v5l��Ti��ILPL�[�z���
+�� �6@�U#������ڗ����1������XV�V�B:@��^L��v��-;I�k<gm��4���r�D�!v)tXgR&Mg�4
+���[CP�Ϩ���Mt{���#��ɪ��R�0x�`*����&Gs�11~NJ�0�m�!�V� �Σ�
+������g�q �$��s�BKd�U���V�8*��N�'�py�g�%��%� �L(�8笮j���a��R�F�5x�)n$=q�!�e����Ɖ���� �s8n�r�%����Gu �FGU�n�t$�,�u�W�2]�"��5��K1����ɞWH9t<�S�̶yVt���� �R��+2�x�=��c�����/O(:9pU��i1��h�z����Yde���P��h�<�ё�NZy�ʊ9b{m6Ҧ��gÚ�}�����0�#��8�[�������]�-��=\��±) l��v�%�T�A����]�b�Z�y]-ǁ1���*rI� <gy����E�}�,S|�xGvbHQF��z��ߙ�e�m-ާ�R6�g�x-��<�8�,�~p���*���T ��Ȭ�sڇC��e���9��;��d�8�#s����K~R$�l�^0�����C��.��;P��M��7 ���6�$u2jqQ��B{��1�
+�U.��L��%�h5����&#�=/ �O �- 1i�vq�ʭNH��~���3�&�� ݬ� �˅0�扫+�V����$� �Wi���#tnt�6�����_^�� A�/���R,�|�1����!_��/�
+߶�L�̯׶����PR�vo�i������#Y����ԅm�jjΩ��j ���g&I����-W�f�)vJdx�L�`L��f��{�,71�43K! ��T��f���Wo�8dYD�ǣR��4�i�զA����ik����W�|�raEj�>U��ϯY�w�$ʯ���A�7�$�nФ>w Ou�󲷚������[�]?�AMD���%��r��ݚ̌(��h#�qR�d?2<�;��Sz�
+�&Tڿb�Ȍ��;q�� �DBIs�+�%njH��ܿ����e �n��,���~�]7�@����R{%��T͔0�N��$���w��BC�.!:4��6�����j�����^"���CWj9V�z��0d��/�ot~� !SR���Dp=�m��X���1��%�
+���T��<�.Ŧԟ�i��&�P������*����cs���f;g>2
+vgfQ�k�_ubi�(H���`��<:�@nS����k�6s*� 3��L����A�+�ϸb9�1�kP �! 2ZK(E��}��칶��q����.�M��e[`��D�F����kA�X���G7ڶ���@:�2O �.Ă�L9���\X56�f�h�X3'_����.��H�,�:%
+�@�u��E��k�O�*e��>�|�b=�(���"�)_K��:�;r��"��kʐW0�"��2?�b��9��I�{�ސ�E[�Eڻ���M��:�6��_�׎!�gQ���3��~� j*�C��c�"�[� ��K�2Ӥn��V���%!�K���n�S���A[|�pY��f��;j�rjz}�:D�-����&'
+��:y�h������ �f��~F���T��t�Fa���3l�# ��ض��U��AV_ʢ�i3/[e���g�V���r�i���!����X`�*���|&��('lF�X�#��4\��V7!�NQ�s�ϟ#h����
+�x{�%�,�����x��Ywʶ8�Ѧ�5��Y��4�(��T~���d���h�(����K ��'N�(���MmxcJ��F�r�;���,b�,2��^Ud'�?v��!�F�9�k6�?�عW?Q��x^B\��r��cNKk�wAD�[hr�\�Ӛb&?(z���Iq�+4B�Bl,��d[�=B�^3-~}���a�^�0;!����E�}��P�(�B�p¤Y�4A���Z��7�T/:t(R�$w}u�l��-�[�ޝ��E�� ���"��BE��0ܛ^�L�s�z��/΂kTqC�2L���ŝaO��/ ��V°M�YIk�$b����#���e}!am]�NY�n��n�C�r�F!����H���� C����oY"#��������BuW���+��9.e���皍~_u�\JqX7���>�D�~�RR�#�CN�����bf�"��4���6f�4�)�(�����C���G�����+�9�I*�M 8u�a=siQ�ٝ�<��p6�犱m��n�>:F��Bw8�O+=����b�W�"1_��P�>��t�`\?m����–�uV���b��PhC��[�� �^<U� x�~�Dbkbk��p�(��a
+j��R�2g�.C���ըЯ=����T����(/J��,������?(Z�.�jj�7�<\�vEKՁ�v�~��w�AA���"^ϫ"86�j��D(՝�#���+�ۼ?O��>��'�L �;);���(�^z\�u�e㕒u�m�a��Dʹ�T���YH��"�Zd�z̹��fܪ�,=��m��IQ� �����Tꦿ&n ��Ӎ�75�:ؘ"�DJT@oR���2.�|8�� �#hs�w�+.��w�?�,���6V'R�y1��Ul����g"#
+(�'�����X��_h��[���@HuM�A���*�E�ˑΌr�+X�F���q��O���C��'�y`C�2��J=���mD�����YG��=zIQ��#�v%�P�e��P`,�M��� p]8&[g���GG�� ��ޫN���y�
+����|�w*X��b�tv�8�ٔ!�h�Br]u!r�a��eY=G-��Ͻ��������U &]ӓ��RBC!HH%E]��xr�X�"q�����Y;K9]"z�������?F����>A9?���7��+�v�~MOr�2D^䎣҅m{���줙��&�6�����7o!�>�¦D:���M//���J�NNNO-�m�̓GK~�/�?؉[�'��-�1�2��to�A!j�+F���a�q�69�~�"�Jr]�V/�!���d-�-s�W��o, �5���I2� y���! KZ���*���h�5��=m���^k��;Wo*�o�j��OW�Q��C>r.��[�� �L�ʰ��Z�E��oB,|���7�����yo�JXd�v(������Y�JEO��©�&�r��uL?no��񋖽���k�a�㘇*��ϞKP+ζj |�Uoּ8�䛲��^��ϴ!?�o��/�� ׺ Ys�R��:�Y2��q?�����:5K}�č;����J��E��z Q��#��5l��9���_k����+>l+��Фw'5Q�ξ�ؓ��-χ8Vh�e�U^`�iϰ�$̡��۪��5��q*Q ��:w����>��5O��@!8|d�h`��!�/s�}��/��Xt�v�������wP��>�^R>{�jz]��5(tI�a`_��tw� ��FCAb��%��[��� R���3�J2���㈥����Ԭ1t�à�n��;j��^xِ\���)�tg�p�󣦭��2��K-�+��s7�a��W�M��gΜ+U��,_�뤯������R��ր����80ރ.�Gqx���j��-��� �*q*Q}� �=ιDD��N�<M���d� �q�5�ʵ��PA��Ӑ���? [����Ϫ}��O��Z���,��� zx�"���.�nUO�ʴ�jV\^3S�(��B˃d��zݪ�#4ci�E�"�/�A��Mw� 1]��t �96�����H�N�m�ܽ�F�.��WU�rB<b�s��x<%��i�R��ލ?��i�P��ԥ��MF[T�)�]RtE>O*�jzl���'�LUzs�B��̤8�"cQO|6[[Fo�߼�DG=_Tb���J��y Լ�S(�(�&�M�b��|'���m�m}��4�1��4T�K��vQ��1�$ZE���FjnS
+b��'÷�Ä���V�7².5��p 2��s�R5xL�����@�Jlmx��L�WF���=0`P��XQ�H�T�n�xd�πe�O,����*�7��_�����R� F�1��+����l�G.�78�jS�ډZݘhY3��0��޳q*DG�RF��<�# �֝FڎĽ��H�/�P��O�Њ�U�G�x���b>�ˑ#~I��.��E�_����z����wj��� G���I z���:C��g��+���Biggë�]T��:(&+�2!�˃~"^�ķ�-B�eԈϨY2,y��KODO!�}RnחBdE�!@����zS��씽�Qd��Z�G��Ո� k)Q+�6ɮZ(*j+�,���KkNt�������̯�t�޺�{c�S��&����KP�6���NZ������+��&vjjJ��Q�3�/�/�>�Ag�\*��(���� �\�H��Lbx_��!�%4���=���#E�}�~΢�ay��Zws� ap
+>7��
+!��'5r���_w�6BT��o?�_g� ��C��r?�x+��a�&mD���dK��� �ƃNu�VڵY�/�H��%�b﷊�d�Xl�H�h���|Ci�!��s��
+�K��;�K*hј/:pm��l�����Fm>3 d��mE,���f����۞8�kg1
+Oc롱=��pX*��Ф�=�q�|U%#�Кwxo��k^���M�?�5���)nFz$g5�� ���� �"N:�
+�XR<]ǻ_�u�Q�N�6#�'��:��"̋y%<��D� ���܉G�X�>z.P*�;���1j�� ^�=O�����<��R�L�+���JsCʯ�\ҧ�� T!�IV��21�ϖ��������o�Ik�S��x̿c�l��uA Y�%��+��7a�It[w}�V�D�Ld �M�r�y>`�%��H0�1#�Q^ �\wA�Xa�ȉ�C$�`7�u��]��'��ޖC2X�]�l��R6I1i�<�-݄=" 9g;��V�S�� Q1Ud q�">_��t���ɮ��{�P��\�[������0�Ǔ�X��o��&�����+��9_����UnzH�Kwta�meCW�F.ئ�V��M OV%W�2yDDm�Gx�d����M6�x�o{�] m�����4��*�<���0�4
+n�@ �5��r��4����;Tۣ�jv�qU/�u�%o��q�j_�i���vP���.����4�W�X�?|�_^ٮ�`\��#cS?�����O���B�[ �u�u�8l��#ւ��3^DM�M��]g��9{�WQ��fe�÷�1�4���b�y&i�~�\��g4�Z����:/+��Wg�so qf��fR�#a��?9O�2��:�i ���&#������>�C@l���ՠ"�>iA�d�3�Ojݞ|��0�#��}B�2�k~j�����E�VC���Mg7O ~+�X�� ���?6��wLٰp�̦�b,�9���-�0�����Ն1O�E 8�Zj�jV�.��ړ�K7�+fqr�-r$�-���"�P ���itN��!A���W4����V E*�^!gC�LU�5�yIF�>v '?߽
+>�ON��2��Qm�߄#���擄�誦�-��÷R�@]H7�Ռ�v��1x��6�Ǭ:tV�6��0;��Щ9F�ձ�ӣ�&î^�P�~���4���/����뾲W}\Q~1�i�QJ�aR�����Oՙ�2��g��Q��BF4|�E���yYL{⸹܌;C.+���~`�:�]�=#[bm[^�3!�'�����4���3 z�_w֦���c|��)���;m�{:ă� R�h��v7M�,=�4E4��x�^+��&<������:�%҃]�}���߱i�o��e��n�zI��(��aRp�N�!����h����1�eM �v��)���QH�THH`���A�?`�@@V*���.��Jj��1�5����`�C�)҆a~��
+�����Q����n�b�@_��=;
+I,�h#ަ�X����w�kl^Tt��桋�k��ݪ�#��4晞T������9z�U��}{�9�k���̿wL�Y�e�Υ�+�g�H���!����qi�DO-�rM�z�H��t����_�
+�5[x��Q�!���M�xA��}N�Tz�&³~7����ޟ뙰䖨�IV7k���c�y2�
+G�j��Ӹ�dԋGĊ$\}w�P�7D��_�!�3�g�����y�T?NS�G�0S�ʣIY��5�0����A�\������ �V����j�Lˇ�1�u��i�F�9��t��2��*(p����e�jL���%� S���jc��(��?�7'�?'oq�D��8���ݪ��-�Iq�Lm�;-�YMc�EgJ�M� ��$�Ǹg��f�f���� D���]j?���1Y&�v����so4����}���Px&��3�D����b �m�tL�/0C�p�3�GQ#���ß��p���0�m<S���$��J�dv謈� b ���!Jz�I��g�x��]���Gk.�� +� ����-��o��aʻ���{.��#s�����Q�B�g��F�����b����g @\+|^Ϫ(�)ͩ�W�<6u�ex�]�a�ӻ '�ޭ��d���eY��?#���gm���RLz�����T�>�_zڻ��C��/�(���(kbi���qG^��R��Tď;<T�<p�) bݼﮣ�SN���
+u���O���] �t+�G�t|iE���xûzЅ�@�`L; �|-=6���.B)k_.���V�� { lU&�� @�o�-HP=~���n�ߥ�ғ��u����$�+��n3helE��#k��~[M��2������|��:r�G���?��84�~ٖ�}��H�j,Ŝ���-��0Z�F�i�H�a�P���������h��1���
+�$��z#V��떦�XX��3��/��~�; �q�>5��H���n;J��~�I�aC�G::2��Dn�
+�@�?�����8�ߋ�.(���ف6iTQy�`��kk!|<**���4M����8 ��m(��lt��X ;
+�̰ ��M��|��fy��npl�g�bQ�Z���^��缙]u�k㱦�w~���@¶K��
+@�(]�i�A?��y�tmGnԆ�$�'*�BL/���5r��'ݾ\�T��`ʩ7����R�/�-i��q@�e�z����9n��3Ob�Un�U)��� �P4�k�B��ER������� [[�:���B���} T`�H]��G�@X�}��p#W�6I�ڌR8c�M�y+��;}�H��(Ò~y�1��U�6��|G���_Ϡ���c�����O[�<����s35�Y���R2��<z��[I;����*�[��$287>����4�P�u�B-�ֶ��|�f{��m���5��oa��0?��Ӆ��W��u_5�;ztҍi+Ҋ�C���us#}=���X8��m��aH-$1h-�U���c?��_o��'�}H�������#����z �[k����@f�m�/�w��d�߹I�>j�7
+��y�%��ܔ�$J��8Hi�������Wo j��O��fͼ<լ�d00��3�I~v�X�$"_\k�2 ��V��ϼ}Y����!���~%������B��[w�w��e$�w���,/g�*�O< ���?x]e���)�u�q9��!*���AU )�z쳠��]�R���L��=u��B��m�4CA�!$�L��C��P�&���yma��4�*���3�ň@E��s�
+�����6��6��e�:�Ň��m��Pg�;������ұ
+{�I"z]����{g�"b<"\0Ʊ�����8��j�K��@I`?��Nc�c���������N��7���.�u��ZO#Tf�x��1�7�3F�qy��'��vU�����S5�{���+C�c�����ũ�\1䏨���o�f��P -��]�y�Q~o,c�s��/
+([HY�x���ϩ}<���Y/�:E�HkX3,n�IVK��I��^h��YD�x3Q���A��%�-������ kVп/!�`E�ʎ�������+�����S7|i�F� �Cs?��!���\ W�N�Ρ7_n!��n�&Lu���H�\�JI禧����+����[��Ў=�/Y�{����ku��_�0�� ��s�4\�2`i����2+�������e��0>��c�aE*S 0y�6��ss��e֏6!���Z�2��'���]���(XU����+#�"�5��ϝ�W~��Z$�B�b�/F)Z���ͬ� J�e� 4,d��Ƨ�=C�|*�k��`�����A���������HG?�n�zi�md��8G)S�h̏?�;@zu��5������(
+�����^g���0_ss�Χk�EW���ʱ�W��. N��_���SrKAWy%ZF|s^��Cd�!S>��㱫�Й q�]pw")
+�s�`�S��VT~�vPTd*����x��AM�q�<q}ID�&7�g6>��1�@4�aw�!ٹ��x���1�8Hp�J7Yd]��wb��ɭ�$>��=����y�f�PuV�PN���\H��l>܁Գ@�9v�C����$b� h�������2? ��'�₌<�b3`�������-�iH�xN� �s��*�X���� U���o <u��m��V��o��'nΒ�.�ܱ��o�6��J]Kf)�uBo�0�����
+x,��H��&Y���7�H��,5񬔁��WZ����4������gY�+�8L�r��3���ϓ�/iwԘ�מlH`���:�dK��R
+�zl��ReB֎�&�_�,��f����S4!j�7�k�a�����H� 9�kϚ��� ����0��A.UI��h.G!��O���Cay���Nj�p3��<���a������٩kh\%�$���u��'o�����P�)��eڬ��QLj!�&�|EV��{�4I���IT-RJ��ڪR{�����͋�-(����[��yt��C��B�0k�!0�F==b�������f�{��
+Xaa��
+��a[Qm��l�)9@lM�`��� ��1A���<$��@'��P��$�a�a[ؠ�ElF��6��Ƹ���%g�<wX�,{�@6ID��?�5�<���P�Bqu��}�|�X�ဋ��K+�\}g+s�ʛ��z¿���h�s��'>(•`���3M��,P���g)�G�����B�h���X]��s�����YIR0���#n�krg%�����S[��I�`��L�6���'�EL �%VR{5<>�.}�\YN?��ƃ&
+>^FnA-F�Ј�( (����q�(EuQ�f$�����X�Y!�b�Z����z�M��,��>ڋ'��)y�7Q��l`\��vZЂ���;9��eD珂����z��e|'��^E��kI-'.'���6���S�eT���U������a�^�b��mꏁ�Y6� 8� 7��ೢVr�e�I*ѥvл[*9!���(�G���:�@܏% z��R����_f,w�*Sp�6����l�V��8�x�F�DTxZ�W�:X�U �WG���.=BGz�$i:����b�)iņO�0٬t����d�9���q߹/X�A#����3�]{ٶ�#�S�1'i�x�-�`�����ENj!���F�u�ZH��#������;�/�s��N���Fwp�Xm��T���>)p�e�_�Ѿ��_
+�2�fQs�f�e���
+��cN���KM�{,�\����fx�!�[h�'�2� � �_u3��p���]���pS��t��v��=�^�e�G/e��HK҂mwƮ�yr��U��V}�,�񍱾Sg~r����5�:koqp� 7�#V�8�^B! �� ��G#+T)�he� �P\ؕ����-[,TS�}E2��=��F�~�,���<����*�dQãeE����喱��=�J�T���̣�zp��Űp��� �{��W/�l�gS=�LAQ{���][)�Q�"A����"�e&շ|��z<:�wN��"CAJ��p�y��9聫k6vЙ����@��a!~��}��J�8?֩�S{��60z�'8��s�:A��`]�D�W/c�3��1�X���Y�=����L�2�@���|�j\��D���D�\�";&<�S���x�5攃��{����7�L��)�B�}=wXHE��P)fnidI�A4O�Y��|CZY�p�/8�phņ/U:��Fh�s�_o.v�ݓn�ܟ�+���`�;��Y@����SK�W��'�w��lp[BUŚ�5-�]n������V�>� �vpg&f���[ܙ�kJ�ݨ*e�ij��?����������Jj| ���N:A�l0F��O�M
+�=��J��CJ`�n�pP���@}e�����X��c�����@�]�B���@�sY�2C������6C J1s�c�"ΐ;�um�G���\��g'��_i�Q}�`��v�s�X&鶏��������&�8aM�w��gQ� st(M�{5����A���@!ⷰ�n��Ѡ��}����E��U����T������Pm<�����g�Ҳ���2�b!l n"Bw�҃_8��(�٤�b�?:&�p�z�$'+����� �kl�?N'#z�M#�Kd
+�nX�>�����,ᙋj�� P�'���>Z�Ig�FW�NRʭ����t6�P�ESS&&-�.����0�Q�c+�L���|�f����_x(ߪ\��Xt0M�N���R�
+73.�P�:Ri� E̓C�/t�A1������3����O��9���j!���yڃj�ɱ�#g����eE�Z�X⡎X���Ģ����y!��A*��O��M� �a���7������1��P����ʋC�;7na��ә���� sc��B͝�6�o�5���u-���S_ ��`���4�f�|���������[�+���M�V����;�
+bb�Z �-!���ۣ�Mۥ�|� 06Te#�,u�yb �ԕ���L�F��t;��ˠ�Y�! �V� ��P�
+?��^'T�g-#m\Z 9�)�R8! YP�54��h%�� J�%�~���ن��4�d�|i�K��P�a�(�\<����z8��o<�yR7�DƳy��g��V�X��K�5��5ik�M���`=��x綪3�h����ܗ��ͬ'�޵������4J΍j���~�cH����A'm���*j3��z����j�a��f
+%�c ��? ��`Y�P��O#Ob4�j�˵�v��.�*ƒ03�k��ק2
+�*��~�3sw��榯�d|�sL��1��&�uٴƮ$B;h�i�V�-�F�t<��m�����oI� �#.\�t<kt�[��1d&I߾eAsC�a&�5v���9���y��!�� �TI�&�b��]@�� Qu񥊔�m��j��p^�����U�٘isҴ��O�2�[ji��K��Z}a���㛿u%��A.:��T:��,Λ��8��gc π���gI��;mEI��� �d�w���Φ�f���X�m��2$d9��Qn���?m��1-Nd��ަ:9&9$�-^r� \J��׳ȓB��,��!���)�=�6̗�J}#'$�}e��j�Q]��9�1�:!��x�y��T�(>��^P�9��X�� 4o�G�$`<�[fC�� ����(Z� <����hV��Ҭꯜ�au�f��KH��/L衆-�-�-�Ԩ��X���������+� v
+�*D�U�#n7�KjX��(J 2��Z��Y�?�?�H�X*�(�;�qq�l�I����灨-8,��<��)�Q������$��y4$��N 4��Zۑ¢.�M�N���C��(�x�ɣ�V.���:g���x[���bEF��'�b큢_������W�AD+�b�Jj��f�q�# q gxV�aY��MneA.�L� 9�?��"�Lh�.���U�=��d�m �p��)��G|��,�p�C�M&8�㼶�?�]�.?8Q�n���w\=�B��gd����c{���u`y��ڌ3%F�W�f?��W�d8mG�`j�@���x���&leq�#e�U�*��a����&��ӷ-�w��U��� �_�0�K繢�B�T�}�rE-�+�C��Ö�Ƭ��ԇ�I7�7����3��ύ�����F u ,���I�!�4G��R�G��쎃M���*3�Š�EÖA���b�g��ާٕ�})0î�� Wy���/I�Us'X�B���v��e:Fia�"�}��F��{=�}���c���9����3��v� �̂f~s6�
+�&�T�����+�l�3��u�>�Fs�rUk(� ��pK��l�H�����?���� yT�1��&���3n�d�w"H9'Y�%Š�V����$V�׌�Ym�B��]�Mj���I��O��POĔ��NvN���J�pu&8?��cp�P���������F��Ta������sߎ�|}���ms��u����a�
+kG��c�s2� aV����[���?e@2�8@��2^��/�5�M��1�`��gd��&��%%�㙪>�թ�d�,5�|0�������K���4� g��q9�Qȸ=�כ��1}SE��^�����n�Eh�eFD*�u�B�`�+��]@x�u��h|��v����v��ݺm/$��p��?����ճJTux�o�<b�Ug���wuvuՆ}r-8dz�
+����\��V0��[��;v8��%���k��1�),�����j���)R�}�v��^�[��Jҝ\�~��Ah �;��BtOo)w���{���d��|S;��C����?���V���� �P��ձ9�|^���)������t��b)�DΑ<;���7�#���i�C����b�`�{�V,���{d2�:����#�y�kv���� �i"�˜#�$Utg�V�.�^�ǫv�VIY�X34{��H�Ⴔ��QjZ�>HI�K�������b����H+�R5eʞ���zٝXO�ǚ%�I�,0�1�p��Y����s7�F�DP�O��b���*|U@���V�u1W��YeW x��^��p�ͮE���0��d��X��6�wA�5��u�棃0�4��9��\#�Y �za���Ď�u��;m��;��R������#gz��R��oU�,�/sB�}\�|D�&?-���aO�9"�ސp�z-�}�������/M ��ӻ�$y��ky�"}0�,T�I�nCL��V� �F+��S��P0h�d��^#}cA�v�tܥ�.:J�{����4��Ђ* ����$RB��J[��/=��=N�=�x9wm�o���r�=����.o�F(�U>sw���_!��&Bwwë�J�;�eh)� x���U7�ow�!���/��C�R)QgF�ݞc���73%mB�- ��VKH"���(��s:��8��� �:Th���]�,u��֐��mW��m��g]��h�x7$��� �:���\.Z��'`�?+�*v�Rf�(ab[�C�-�ʎe?Q�+�+}J��g�I+��ѮϷfd���pK�]`�Z r�.�Ii�RX��R�/���s7(,�����yy��bo��J@�I�f3��$�BP,0�ț��> �J��sV�������h�����q
+K�ۜ��ƅϫ�T7��-i�а���f���,�rœ z�\���_s��>DI��\�;��&ū�V�6Ѩ
+;�E]�[�ۢU���\Iq�CC�:@�ΦYn�޲T���#�c#���JL�q,�rě������Q����23���s����z�g� �#�9y�ˌw����e����R����v���"e�y����+���fSS0�a�fC�ﯫ�a�知�չD���K�4���\��GĦ�N�0�&��,{����ݤs�ó1�j*Y���D�Ԉ���_�G}/>>nOt���p���Xg�֘C�D�Ȝ�z�T5(���>B��qWT�X�_2t��tb_�[i�ڇ����:� �?��IS�M�@�\%p�d~ʿa����Ïj�"�&��w��C�1��
+�*�AGi�
+9P�u� ���h��ȳ�JS8=q�_!�� �'�G���po�]b$x�����j�m��
+�]��xԗ!V�7�<q��#\p��� ��y��W��k��2� A����0��L%��j��ͯaks���� ������w�׹�O^`/ؽ��"�b���a��t˺�3�#y��Q5�U��Ϭ���7/��
+�{͗H�,Q�ɟƟ7S����.���eP�ؿ��@���6��p��I>�����5�9%�SB�Nl4�R���m*�OA L��-˂��Җh�q�BN�l��F��^G<Q� �i?Ǎ7j]1��>��Q�ed��d�i���|v�~�\�h���^J ���B���+�F�&���� ̍��%/s�V����L��N�R
+���_��k��V� -���oR� Ձ��)jEqw��/O��l�%ؐ������v� �J�%N$)[Y���M�ֆ�pY0��+����o�"�oa� ��CF�-]=Ȥ�_)���r|v�4IW{-��l!~���F���Ņ�d:1c�Uy�W��}��[jP�V�9����~ �*L�۵Q1�������/&j��C_�Z�G��_���6k�>~=?[]��z��z���.v/���;��.S6䮥E��y�nl)n $r�[`D��S��q��j�u���ࡼ���iR;����<`Ңp[A�[�ģ)�F����,ZJ�2�?�������)^dZ��8�9}�[Ga<6���F�Bj��/���}gD�nh����n���C��q���H5"�R�q���{�m��8e��� 87*�a�X,��Dً@��F��M64��aĝ�N�Vb��z]�)����1�B�Y����EB��z2Ǒ�����j�3�)"��:��0��YRA�� �b��u4:a ��;m�&��A ��e�= 4�j<l�kIҫ�
+t���.� � �_�#3����-��9�qn:�z�`�q�H�Q����@�8 ����l�?��vNs�[����b�����Lu��
+�1�0Ȃؘ�}�!�V����[����c4Z;�e~*��u�ݽ�y���=L�,�PL[g���\N�mNZ��-��M�>ڀ���U����ߵ�~�ħ��O�s���S��H'{�1�~� oܗu��SHU�F�&Q1� �f�ʟs��1�ch�=�8W�{�?�Wk���`�>��: �a�O�ѣmѸ� g��,Ɲ12��2 r9.��{eߔ�a����д�>�C ���{�b���T�����b�F+�Vܛ٭�0�zm����f�v5zm���T�Vd`�}�J}l���Q��֎XuJ<Lu6S��"#3Ir����4�;T�0-�W�WÂ�< ����"փ��At��� {9'%���A�E
+;��I��$���ަ�s��n�0����V(��odx�,񙕼<���$�cFp��䏌,en�uV�6����N�u#T��M��ʂ�З�I�.K��+��=����R3`#IҔ6p��U�E:]z�ܥ�I��o�VC�e7H�<�⹵����>���e��SS� ��D��f
+f�`���q�����-���CyX
+��]��+�R4u�z}v�G�(���%�1�PPC����!K����6�)!�@����6h3�����E�4�Rt~ô�J�L���r(h�4Hp���Od�HG���^����Y]Xqǡ�(#��T�1۾�Z/O��E1Z#�}���k�2�q�W`�R�dS����{93����ȔmHK�T ����'j��Sn�~��ԫz<�вjNq#0��/��i�:�����q�vH'�6ÿ[n�YNa"�ѡH}�_�߿����y �m�º�n$.�9y��큄l���9�� _�����Y|���'B�H�>Q����8��� y����m�:.����5Y�JL���S����U
+�'��B��
+~\�;U�l��tn��I��bM,'G?�zo��IQ F$K�^��Ga|$:�?�:���&����'7=�H=����p\e��2�e@�3���������<�ԟBC�tw�����n"(~��eGpۖ� A�������t�����A���i�*����J#+�-FX��o����ˀ�����&��=9�_����V�7�_L�1��q�Y�t%)�2��2�K��,�5�/6���7c��O�;����+)s��S6&z�r`L�B1�1�HI���%�ݍf����3 �<����'|�K����W:J���Y��q��o����<��^,SD@n�H4 �8�Q ��K�y����5UH�2r@Ӗ�)���n 4�PRu}7v �]aBlxs��Q7�ל��@ ��9<o���Z#���lç���iL֣$��,���7�,+���D1�-H��_�S�i��#a2*v�a���Y�a�Ƣ�/]�-�?�z��n�m'A��Mm7�Z�r��XE€e2-��-U&��^"����Q��+���A��T�.*�K�d�R��52�b�s��֮�W=�/Y�{�eVȼ�ܿ��n�r� 3=eJ����[E]��������h�"3��':�C]��庚a�Hx���ޡ5����ZшP�s�1L;�!��S[w=J,%�7}��e�|�e�2leU�m�x�&~�r�'�3q\᠀�\)yqc X�65?G�S<\,/��Ԍy�]�K��b����{o�z� q��\I�� e:t~f<a�/XϚ���m] ��lVN����N<C<���`�Pf�>���WϮ�>$�nDeM�����A�DS��i$S��\��1����V��u������):����7�����9F���&�ﳪ��?�,��y{����'n:��zH�-��ɀ* .�����u����� ���1(�r��!o��-�����q�]1{�I����[s������-q�Cs}Q^�W�f����kxLV:ƮW�U�i�$b8E��.�hK��⁨:��(Z�d��[�/����1J>�ʳ tF���MI_w�D��&nC2.�;F���\�3X�r%2�'�h��/tD�`��?;o����I�Ee&����c
+͙���9���q?�/��V'������>u|��鄺=�V)e�ͷv�()�h��c�N��y�S6D9��t�[}ruIJ�a�R�y�ˆ�7���,0��(͉�F^�N��G���#��p�v� ��4�"�c�EF���&�����j��^�H�W��U�Ew�Sf��`�!�}��_l��Ǐj,f �5���?� ��9���m'ӥ��.&��גb���;�c��h�����qRS`y@a���a�WGq��\�04����TŐ1�`�:^�zޯ�It�`N��F��G��C��%ZJ�1P���a��3ŷ��:��M�M�/�|S���B �'�_����'hP<�A�$w_q�ە8�H~�3y��+D������ S��)gs�%�cbG�i0��"qt�iO��ϰ����a��J�J�|-)��@q��}�Z�o�T=���QJ.R����ڃ�
+��?�%�<�Y��O��$!҅�H ��~6WK���v�VTA9���Y��z�VVӈg�><`�l�İ>Q�/�?4�ɕxp�����s5Ľ�;�G͵�&K�Ϭ�ڔ�Zc����S��yn9M�eXd+)�`�G��3O�7�|X�l�z��d����a�t���_W�(f�Yz����˅���&�/��S���hR��a0�&$�<{J�3|������g�Zڐ�?�Y���� [���{x����m��Ѩ��qu�
+�XfUC�YIy����QL���{m ���w��&�[�����Z��� u���5��H���½=Z-�'р��|����TNc+�$ N']���`�FHM@r�P���:w�Cc1�A�M/&�ٚ���╮�VsCG?���1�w8;�|��?♗��g�;�[�?����ob���v��N"3�]��:��߫6� �1�� ��!� ]�^֣��ӛ��W�����DVL)�|}'��X�L#���K��i���&��-��BM�G2�R������)��)�O��}E8�{ ��l��G�(�li��n����$d���21������Mm`x�L �R>?�"SJ����/]!�η$�~rL�T߈-E�v�L����Yd��sI��ɰdQ䓹O� ��V���� �털�!f���_�Z}�ۜ��.?�F�%��R�(7 90�.�LU�k�(�/Sf �Oف�z��v�Ѭ zQ x6�O��,r�
+�^��8ŧ�
+.<���c6L0gH���NC�VI��r%�D�|Z냝�%�)��O�g[����j(Y��R���˂�x�.C�<��NL�[�u#��xb����xU1��#��ג�d��TL��1��&ɕ��<���.|� �^���q�s����睩3�U� #���q�u��H�{F�N!mQ�i�4����R�[wOG�A�U&e���5��4��-���ü�x<��,4 �j�_�F��04tM�a���g����l�o�ݔ�+~Ň�¤x�5�<"��$)X����BYx��x�G}�]+��b�ϗzt{��6�ϸ�|a��ͱ�w����P�OUJ"a��v�w
+���u���x��<#[{�o
+�$�������� ��x�}�N�
+��b 7�4����~j&�]uO�Qvl�t}GIuC�ʦ@_O ��p�p�>��=8�v�{\)�[�!/?�1��ҊV�v����S���k���i���]�s�ە�/7R~y�m��$�f�����k=��z.���m&�����l^�V�u��'v���D�ʅ���X>h%I�M����b���K�I=>�k}S/k��Ζ�E}4�Y�s��v��AsEXb�-as�r�5��Q^�%�ܓ� 4dgA�`�.���4��~Ny�.I��!=\_�YsJ?�=�c�ĉJ�װ�O��7fIԇ��QZ��,�N�H7�I��|��y~�v�}�,�V��1�+¾om��Ɲ#��ь�� �����u�?����3�Ĺ�&&��8)BM� |��5m�^���r+�xo���"�*xƲ���� *��
+)D�&p���k*]�*� 0���������V� %>2m����T�,X`|���i<da�ve�%�N����LX�a���-������}2��LA�7j�_ ���R��l�� VV�(���t�O)X��g�|��g�MӇ�� ٭#����` ɏ{�ϒ~���%k��Wt��3�4��]��-� 9�G"�H��Y���w�Q�P�����_6l������/M��(�)��$-M`o���΃���!��OVV�h�����0��
+�*��a
+#���2��é����A!��vG8��qGn�[�wy˾E��)�̉yB&�} �ȉC�:�U�h�^
+)��ֱbu�m �M���̩ qF� ��16�X�C2��KG�E�*� ��W��2�t��i����l���E萴�]j�v/�# �ଝK[�����m��uJ�(U��z�i?o��a4'j����,�6�L��R�qj���Æ�-�ټ���rOR�'�� JB�Dy����y�T��M���v���V�Y��:?y���˴n(DU.�|�lM��&f����O@�.�Ӡ-j�%,R�(��{����9���K)���DDN�Ξ��?�5ؾ�F���rN��V��/"K�~v��9�+�0��>��R�����+�1��F�<&0o6 %b3���Yp
+E��dO���}R7�R:zT���JB�7��c�<�j��C�Y�,m~Z� ݋�ؒ���P0䈂B�@-ۤ�焊%LB$�49�T�G0ؔ��wIz?"}>���^�&&�4r����p��4��Iַ�¿��n���x�/SBv
+Ӳ)Ũ� T{$yJ;Y����/��؋�4e�H�U wz_W�i>�V{qp԰�Q�Lj�_��[���b���h#�Ӂ L��P���V��K(#^7�� F���}����78<}?Ҥ*2BC��ﻰ�9�o�̟��Go�� �a���"���+��_V���#�e��h-;�;�ʧ$|��[���מ�A)?�"��@��&)��g�'pZ�}z �{P���3��e�}a��q���2�����ℯ
+endstream
+endobj
+854 0 obj
+<< /Filter /FlateDecode /Length1 1373 /Length2 26888 /Length3 0 /Length 27856 >>
+stream
+xڌ�p�]�5��X;NǶm�v�c�6;۶m�;�;�;�8��߹����U{?k�1�s�1��MN��B'd
+46ڻ�1�3rD�T����,��p��V.�f��p��fN�V@{��� �df��5r�Ó��]mL,&vn&nFF3##��N�Q#7+S�=@ho� G.t�t���t���=�L����8h�Nٙ9Y���\,����hbd P�X��x�G *^Knwwwz#;gz���WZ����%@����������y#;�&��#�ZZ9����]܍��[+3{�?���fN�?�T�d
+f���e�!��==���7��BV�'�����=��-�V�fqYzZ����_D#[g��|#7#+[#�?��;7� )�� ��x�&NV.���V����W�?�,fo*��3�wq���?Q+'3�?������������]�[ٛ��5�����������返?��`f.6F.vv6F��#���Ē��f����L���t������������������������
+�� `je�06�������`3��.������G{Lƿ>����G^�@{[����}� �Z�"J�4�L��1aa����� @��� `bbeppp|�����տm0�O���9��O���:v�WT���+�?k���� @�?"�edc4�����[����)��*�_"�� �������;���Y�z�K�#ZW�?�������j��cZ93S+W���r1�c!{�?b�cb�gd��r��03U�r1��G2��jY����L�l�׻�O#�����͟���]�2�c���W��h��Ϙ��FNNF�p������f�cHS3��� `����I���`t���Z�����&�NN<���l�_� mf�af��h�b���\'��Nw8 �����5��B���m) �Mb�Q�д{2]q�<l�����n����4�\��}�k���~ 3BS ��,Gz�>�U����e����P��㚣���cm�3����8 �%V(�� ,Z��l�eBK%�I'�UUJm�,�*�I�+��s_'.sbss���p:�m��`-{u:�/i�ɤQ���ҭ� �l�"� $8�va[��[o�#���,���"��
+~S-���QY���@�<l*�V���FJ���4�С[�V��q���q�� �n�w�$� �I�L��د���
++~��;� ��{�� F����]�/�0�� I�y%U��Cܒ�Q�%��Ii���+�w�ot�_6"���΄Z�n~e�zys�V���@�C��1!b���mO�,�x.ꣂ�F �bl�����UL>6t)L ��^���e���lv�s�3Yg{����O�����VIl��~pNM��b/��\d��jD�"��RQ�=�{1���4�m�}�z֞:�l_�/���c+-G(�[�杬�u�RHQ��#���Έ�� ':}�Ѕs�&�"6���P�s����'� ����J>�����$�4�Q�8k.�̰ �"3�N�}�b��fw[����5p�?'�l�/z�,m���K&�� v4Շ��D�Gu7Z�!��� y�/��똍/q��6�=�>�u� �:+�O}��h���7u���_*6�k�� T�L���8L?���g#��@t%u}�%�}�� aР��l����ˆ��W�\�|��}��ui���u�
+E��QL��Sɹ}�����F�&��x�DN������օ:��$�']�h��'z�1S�e����\7�#%S�Ѣ8^�r�����:$'͟�(�C��ϔ��R,���Ke�)ċ��b�J'+��Wu\ٺͲ/U�Hc �� �G��|�1�d��� �$/>+���ȥc����ْ9�B�Ig�,�ۈڰ�XL����K�ujP��F�Ξ�7`}����;x�}��k�E�ç,PJ0��5P��\�U���%KO�`���W�|�|�b%JX�p���1���t]I��UX ��60:[�ժ����� ��6�O�k�}> n���,`pſ�CΧ�%*~�p�P���ևP�("\91�"�M ��P��|DzU�V�����ty����3g4���s���=�'�M���/(^o[���X5Jg��Q�U�� �d���M;DxԳ��w���|l���׀��<��,95�p�M=����TZ-f�fl#��#�� �կi"�����Cǣ�̼����v�"n��Rk7f���mG�F4gD�zu�…�]���A�V���S�o� ���Y������ml���&{��#O���s��AZ}*� ᇅ��ݴ޶�����%�ӎ\-�S'�X)�=���7���@��yݲ����`:��u��*[��{z�� �Y��sϞ��I��m�����W�f5ٹ:-��69�H��b�|� ;w$�-������ ��1�� M�`5xaa����E �g��2��P6I�{).��Q�,β�/��t�ٲ�;�6c�蟱��j��)[�����\f>�8k����V�b���F�L�����j]1�5�\d8a���#J��1�M��Z�����1-Oi���҈lȠB鳯|�*��/%B*I��&�|Z�V���Ͻ��;�|A�7\�)� ԃF`�f�hz`�,�KR�\��(��x����}�6�2η p$g�~���߾݇o�Z�R6�zf��)���J��p~5�\&`aȂ�`��I�C!p���3p�D�n:���gä󅫪��fv1d�i6�q�n �}�D��a_�t
+.��~H��t� B��$>�{|���\���)*)�|����l��:�r�%>���lF�k5ٶ%ߟw�=c�ޞ��SM�GT�I�`�G��If�����[���YK�l�/��s���l�+��A��N_W&�8*��<��,k뫾SG\W�#�.��
+�S��L_W�=� gC�����]a�X�2��Z���K��8w��>u��� '<9+ʷ1k�~�"U����[��oQwE���Ta.��:�]Ӟt���Q0������I�~�F�̔��?�?T����祫����*ϲ��x�NUb���;����%�,�m��Rw��E�B��q�X�w�B�E�I��a��<lfZ߃�f�N��VO��/5�r�ݝu�S/�u�9���ž3'3�J�w}���j��\Q����<�3�(K�wg/5��T���f#��gk�2�����̭}Vi'H� ��� ә�L)a8�ں�*4�� �K�w��d���q�[�(z��)��2�9M5�~�^�o��w=���>�_尐X��?TE�*Bne|a�m�w 2�tl>�xq���e��O��Q0��8^��̳KL%I�4��}ٲ���P(�LӮ^#�׿���6���hYNYT��p ��:/vc+���U���s���.H�a��W_ 4s��p�H�q��Xy� pfE��%‚�#�=��&B��,0/.�-�'�l{����$���E�+/��|�R��c�I�X;ys��%9�b���G�p0�Nf���`�}}�xi�QD�WH�%��Y�n�����88�k�:ߔ Y2wb �M�����)g��}})�u��9� 8�W��ħ?0’��Uś�z�S �l�{0�j&Q��<}�0{\!Q�ItPda݃Q�p�*f1N�/�� ,9��u���5gL ��h���kc�bhcg�7+�Ai�6�����w� �W#g��u�[Ɛh?H�y ̧�9�b|����P/%�Y��
+�
+7X�0?��� ��%�Rq����lj�]�I���+�j]��X|mթu��K-p���!-�����ZPY\�"'r�\��<�F�/A<���{��m<�Db8.{��DU�Bf��8.��q�\�\d(��MJ���d�0W��H��^5�6�9����BH���RhN��q6+. @090n���r,�|��c�< ��Ǫ��X�ɽ� &�m���}��u���ك~�}�٘��+�7g�OwW�L�Rox�s`Jm5��'FT^ ��}�O�Y>����H�N��M���! ����$�Z�:*��:�,��N�'�y�]��Lq��u����IT����ǯe���$,���z� _���ʹ�9ۓƙ��"^Wl6��2�N�C<P�/K��R?�6��l4���^E��<|}��� u��^ �p�" � !�zֺ̓��88���Gu��s�5[2(%�N\�n �
+�6�dn@`ɕ-��:&�D�!��h!oUh��~�xї3��m��:hi�=ᑓ�<�l�ׂڈ���iڲ"F��r���2Z�컈H+,��|����O�B;.��*X7`��I���Z�ԋ��\�OJ��� ���d���F�d򉉆�"0�9v���5�.i�~����a��I��t.]�6v�{8��BP�K^�Ӭ�H�S���H��=��w�"4Tn�}d�5[ ��g�o�Y�s\�ަox�'̻cE�o�ST�M��!�4k�f���wœ���85��y�]J����y4��U��]�&X-�&�ӯ��̀�Z� ��� >��^���.�d�l�O7#&D��=�C��[�G(�����Q�@׌L3Bɹ��/{�-�B������|�RT>��{s[s'h�6Yp�,��/5fn�Bc��_�pkTL�R\f8~��_ �[:!σ�1Q&���D���q������I�`"���$.W�y(��^Os�� �%��$��Nj밷����AҊ����HY�x��S�ܗ7-���R���.Et�~T"cQ�ěM�K�M� ����V���s�ė�_��Y�)�
+u�� ���,4��N���z�6����W�d*��:�k�?�m��X���
+�b֊*_�������6�S�M��;����b����o$4Z�;��+�\�O)�����>:����6=��%���D����Q�G� =�\ݻ������,����^<}~i�Bi�nO*��xI1R�I�~� k�<����~�����R�!4Ogs:HĿ�x[�(�DWz�}����Z$��ȶ�)�i�<��*�+P� M^_}�K�]��u�������e�%�(�=W��T♰K8:�������fn���a0++��:|/�*'*,G�����ͬ�h���0 lԸI��f��[`5u�<b>ҁL���^��٬��fsT�$��bH(��IG�&�#�L��Ͱ���2�b���r2]^�p��y ���K<La4;���n����7�:�j�d��Q"�ː���bęHNyW�=���d�0�b+S#xFz.7D���Č��弞��Wf ��_NW�[���~p�٭LT�? :�d��!O�ܒ��ļڒ����Hn�ܾ<��k4��F� i�Ÿ�X��%q�������ɏ+��zf"o��꿧OQ�E|���~=�$V1�5�x!ĠZ{�nl���Tf���N{ �f�T�Ǚ��!�o�[����_�C���ߩ���bE��7U�h�L��:�d}\��_j�j�H%��e���3����1KX��a Ki�- ��0�����^�=�!+O٧���o⮄��V�O�
+�
+ �s�"�퇬�v[b����J$�g�G�ف|�Q�|��#2�H~1��`�p�?��� g�Q(��">[�@�[���@�Ċ�S�p�)�<"#*X_'���Z
+V����Rݭ����b��]�縳w�l�q �c �N��ֆ���/~���G�����Zc�Wl�]OI�o/����u?S���{�у���+�e 3���K�uNC�SE�( x8�ġem=�A�Ȏ�Q*!��Z܏�TH1�����@��*F�_��D �<Y��Ot��+0ؤ���~�0��-Qt�#��A~�%滿Q�* ���]0� �����0��Չ�>�Bx�� �\�J��2��(���ܩ5=+��䉤�*�X�q�r���=Ѷ��e�Rb(�c�=�Y�(}\C�i<0��WS
+ʾ�_��h+���۝6:�� =�]��5*b(w F/�ܢb�Uu��{l4�B@v{��ԪU����o¢�.xP}e�RO � ���m�,��ņ��Jמz3��}�ӟ`,�^��Β�}���K�KR����sy�~"�:Nw������&O�1}��V�(��}�Ć�AI�J2%X��8��w����憱"�!��GA��4m��P��t�ETL��,g�Z���Fy�_VH�N
+~��V ����s�bR#l7rg����v��>���wԸ�3����=C<���f\\E���U�f{����i��jd������U��t�r�Eoc���
+£��Ol�1���u@Ƨ=~�$wo:��=^u�>��l1�m9�O6�� ��"�;��>���
+����};q
+��kr�˧"U|����: 7�*Zw���z-�E�n�3Es��x�W�鋕��7?j�
+�)]3Zr�!�Q�Ѕ�c�ez�ӗmd������;�a�)e�['w��F� J p1�|�Љ1筞]X4="eA�u�e�|�J/�>(1�.����S��[~9�ȯ�4y�dvK��� ���;l��M .�
+f�t�n�S��uw�)e��q�L����0�J �
+39�� )��F���O�/z�wr�_�0�"b�i��yus���퇭�Q�A=]k�����S�韾���* ~`��<�}�SD�]<��7���`����-� ��K���
+�=�l7M2�=N/��ݠ�$>������t�sG<`���_0��c<��2�m�dO�D�}}3b�iص �f:?�Ġ���h���y���:�tہTp�6F����H� �Z�|�� �NƎ�*��(����7G��}����� ZLf��8�Nյ����\���5����B�'���qb�-��͍�5ڣa��[���Q�z�;����VX�hr$���?JebBԶv���� ������A�yi
+�� �Ļ;y[ ^V�f����+,�h�"�@�ީ].q�!�t`U-3�[ �B���yw�>����M(n�y���$6S���y�6
+,��Ɯ�8Z�5�(���o��߾J����+�?&�a�Hآ52�OU�הs�KSVH]��82�<o�I?��b)$έ��A(�.:���Y�Y
+p���u�f5���� � �U�5�J�$�!���t)��P��&Bd'}�5��������E�E]#��>� ��fT�� YWU�*M�r�,.{�I��gT<��Iyg�*�_GQ4�Yꋈ16I^��#|�;��^^��ERA4�!�~�,Y/�"�e���bx��YR� �����8G��r�*g��K�����7n"ᡫ�[����;=�p�g��
+#/��Vc�l�Vj��nuT ���و�L��2�p�Լ�6��$��k?�"N~ObM�KõЀ�(돔4ȽC��r9�{�Z� �#�O1>jd/k��@�����>6/ ��l㽳�u0�{�2�)�P@��rbk��k<�G�_g;?5�����q�"Z}�kZX�A����ٛ;�� Ο��%����rQ@���ɚ@<�z����{Ȧ Ar'����uO2"�E���q�X�Szӄ}-�{Ձ��=���]�������(
+�h�
+���,GԵS�e�־���^q)��$u!°N �:� �;��i�i���0`V�)5 ��A�,\�Y,�4��j����VB?�C���p��5m o#D+��0����6^~�$'eP�t��p�����Gۃ"��+��!�k�����Ѫ��;ȅ�>��՛�
+�6�J��4;OL.��DӀ�uO�ęYO]��B5�eɋ��qv/�'�i�_�w��bb��!/���e����ƀ�O�忓a��6W{����KH�䰪���iX6&�+�8�|� �ý�i�Z�C��芒eg��zo7�Q�/<#J��ڴ�pwF�r���ЯN����.�/��i��O00+gi�k�ો��6��0��&8� �{d1��-^�TA�/F �Lg� \\a�2�
+�R����Dh#�ӭ���Ua0�e���߁p��N+�f�f��/C.�F��{�����̦�c�7z�������5,"s�fA�B]ȭ�G�0 L$��E�X�c� Ƃ���n�޸dUP��d9 c�}e|��8����Y�����d-(�RLnl�Ώ#�JX�_��J(�C�t9�$R���B�����=Υ�HN7�4hj���O�ݲ�!.�ø�)P��/�㙊��%iH��ŽpA1�q��m�f��������fE@��>��a����0���q�<
+����N�>*�L2k-$S�|xٳL�Ni�
+������U�����L�����ƲԻ}:=Jy�&� �E"V��NH��Nu��׸��A��e�F_|n�@���%~$��=F�����%�p���t
+c� Q�J�_�O�2 <�ō�p��G�`� �^6�����7՝���?�,������g����$ez���Cĸ�f,�d�N-�$�F��FNVT7� T�`��̲�Ą ʴ�ר�ッ��e�^����'���m�RNs�:_䀐��t�4�L��w(y�R��5�A��&[P�i�����mm �U�^�6"]0�3y뒬��֨a6�!D @�����B�k��<dMSZ�צ����� ϷV��o���iy ��'j{7!^�r�T�]x��Yz�����/=�r�0���$��,$T[� {y��+��N#/��r�$��I��.���.�O��#��-e��9�cg?�Nw��qi��~����I��x����|�41?O�E��+E1������O7��e��C ��c�e���\="�.���y�R��Zd�|�/ ���τY`l�,�v��)Lf�;�C���Gi�����MV+O�c�T�W�/����~??�Z� �9%"�T$�:i$�{�?��N��(�x���WO�(wİ۬�f��S�#��'�Ȋ���^섥h�{���[�� �w��M��d�fѓs��o\�s�� ��^��L$�������VZ��Tb�@�&ƀדV�-�5�d:;MUA�$d��)8��p@!L��d��B����6�����������J��s��(�QʌQ��� ���T)4�%��zqn����D)` �ҹ���{V~-�`���F��]��,.��
+�nKf��~ 
+u�¡j���`���B�k��(2n��'�����w�ߙʺbaS����C2�Xr�gҶ���5��M 9�.��Dy�!=9��͹�-ɨ�{+�/����xo�ն[�9��L��b�: \����M�PY0�m պ�V_�����!c۸{�pzP��;D�;N|��L������!},y���?�����Ѹ��ƥi���M���g1 �D�(��7 ]�$������ܟ��ɹ5��m��r��TS�뎁
+���M����Q8��ؗ�Ul�b`�{[_'�cZ�b��Xt�F��#�2o=Z���S|P#�e N�`�LF4+��@�y㜛۔��0�DU*�(�O7��`|zE��mCM����{̐�>�t� �s���76�i[��a���b �{xa��jjdȹέ�#��͞�v�"Lb� qp�S��[GG�3UՁ�Q`��V�&8�������D��;��bW��~� =kIP|�����WЄ��`2� I�2�啩��A��F��Z�gw�`�t46� v���Š�a h��{B\[�
+bO��klsI��C�1]�l�)�mw���A���=Q�k�H��0�iXL���g�b��k^N PW��(|�1"�}y���A�c��
+��:_H��BW�C���C$�3."���
+t�1Y�:��؀�$N�m?}����U�r�8&ȞN1�v���G�i�s�h0��7!|�}ި��m��6 ��� w1œG����-�h��<��!2 ��9Uc�5s�ˇ��oe��6ܐ�Yd,�����E�?��k$��]aFӵ�S�b{g-�ݹ�4퐳^-?"�|T��2D��[ �Ϡ'}B,T���yٰ�oᐳ�����N�'��� ߣ ��2�v>Qz�jx D��0�%�iF���ni��zN��5�p�������� !C��)/�2qq�Z9U�1��-��_]`g{j�� �l�G�:�S�� .�f� �G%�1b��E&H��wu#_��sV5��e@Շ��G�4E+ �V�3ƻ�ˇ\��# �2n�����D����}�u�'�Œ֖�� e0�5�^�Z��`��A�u�+�$�4y��J���'�����q���8'7Sr�҅%V1���������l�C0�7�%\�8�n��u�wWd��S�{��݃�8>!4P��Ŧ*v��ƋWZ!��ւ�aԆț�Sw�23��.څ�� S���ŽB� *�r���m_p|�t�;��3S���
+�S� ��8DJ��M�[A��Z���Dtmb��)��}{��w\��k�..�r(����LQ|Fr ��9K�v��s���IY+���ȷ�����4d�18PޏLNчg�u<t���5n���������ލ�۽���K�����z�/8��C����t���ˇ>`�][�
+�?�p� �85�aW<�_/�1(�����™��l�1����AP:Du�� # �:U�eN�S�,������<�P�>��I�����ܜ����9�YE�[>k�6�o��ÚD��ls�hZ�M廡�5�P�Fc#�͉�Ĩ{�3��3�H#��t�/�z�uŭ�4�ڷ<�\e �~��%�iTm4I����}�y�ʖs�MZ�̟�� �7�K� �����*��z�~�l �^�v�%��h�=����r���7i5QΥr��X��q�|��0�U����HI&�4��}�����T�<^�."���j��$0�w�F��'��!� ��gA>d���'�4��f
+�)-]\֣�3�F��o�Ӗ��nӻ9 d�}��E ���t�ιS�>ưB�p�+D�ajv�ܬ��`�ݔk5���"F�����T�y�4��©M-�p�΢t��d��l暢zi9�"�ְb�%�AW�����x��pIc/|���~E�{�n�!r��y�K5��^��h�����m��(�a��ٛ��P]� �V�ѵ��`s��<VH��$Ǘ+Q_?�|Z,�[ �Y'�1{��%�^�)�z�X�d٤��z�Z���i:�s jc���N�i[���aצ�Ս-!�����t‘�%1��/�_q��Q���� R9�Me�w1���FJ"�۵�����v������|�3�7�Li�x���8R�I}�m���vzt6_J),�/[o��~�M|��39<Y�}��=86���
+���� �/�F8μ0�I/��Ѳ�L$h�Qӫ=�%[� �c߻���?�u4�_R++�)$0=ה��DtXh.մB�ԛ�U�.$�]W���q�0�fD%�S��ۀ�3�/��
+`�t��]h��� �Y��lz��b�k"��i�'�Q���4��iU}O�� R�&�I�ˎ�K��l�Ub�)�/�0�gϑґ|� G��z9w~�!��@>z � #���z�b1*��5O���$6s��b�d��[ɦQ��1&Ѯ�ќa��(X���ɦ�(�B�cXRɩ�v&��S̭�p�H��)�!�b%Ա��Uk�`�� ��%�m��ԋq�!��ڬ���� KA H�G&X�WՍw*�re2_z�-�q�����u1�6�L�k��P�e|ȯգ����ڟ�ʐ���l�HI� ����d�rw|���'��)+�׻1R2�J�*=F����jEN�� cA�b�84�{.{ ���*���<��{D��\~��5����0�o���xx�
+9ls8��ݵڑ��o��e ��[�T����� �K�g��� ����rU�Qը�տ�ۋ�����o�Y8��M��+����Y���̄������G�����7{�F��mL2|M��D|j!���u�Fsel�g���xr|�荡� 5��O�����BI ���X�Fܟ9�2�=�ϩ�3��.-��9�h��xP��$xo�������G�+��0k̅ލZl���b�}��+g���r��Iat�QmZ��"ZZr�? #>�z �N�K���,V!g7J��
+eZm�_76ۖ��\�4X_Q�؎���2h ���к�L�@�*E�B�e�3�'�F�&��Bѣ(�^)����S��T�o�R<Ұ�,OM�]+^P*˥v�LR��{�*���0��z���
+�\��z��@�2e�`��#
+[�������ܑ���L@=!!`����,���6۾��ξ��'B�/�l ۅ���]�<�$0��#�q=n�I��k��&#q!��;J=�pwS}��K<���Px\�v`q��fwe����.���Vç
+����ƛF���(�J�d���2'�'��`�d/ž���c���Ѩb�qj��OJn�8�RĶ�W�Z:l2�a>,�����X4�_H��'���th�(�� ��T��V ��n2Xz7E'����\p"v�F��t��i(�N$w Ӂ���1Z|���r�Gp�Y ��/��bsX%�-&t&�G��(���v��E.%�T��=&I�>J'c� t�h��W�j�3f<G@4C�1��ް���fD�)
+kr�,��R�W�ԥV;PL��b��՘�&d��� =�;N�Y�q���� _Sr�p�=�Y�Q��8�-i�O�v��8��,;~� �������=�:c�QK�k���Әu���=��E����I��=�r,��{;S���{���-a���0p �A��;7���\���b˅�w�X�~��GY�)�� ����.��E�t|�,���5q����݆o���:E�iɜ�O}p�9���|V�#
+���֥�a "Ԗ��Vd��b(Z�
+����=c��3&w��?n� ���1r�lB��]�,H�Y�M����$�X��4d�>"ڽ � ��>A-4�p�|L��B���s�S��.'>l�+��@�s�4�A(_� Z�b,�ؐ�h�K�6�� �GiX:�G �K���3:� ��p\�>��DV�P��&����Q� �Ld�:꬚ dh8�/=9&'�Q���� ��Uڛ�QbͿ=��$����-D ��%�� ���a�75�&��Βtu�V�
+2O�2>F�p�Y���j U�h�ћ�{q� � x��A���~C��|a���3�ܐ��k=��愆���`o�o,\V ?Aٙ�B��p���韐�\l~�-6�ݕ*u;1��1��/�h?kɈ���q�l�$�g�mm�}���ԍw��-e�� 7�}W��1����?�K5m��W� �8:�J-����X7��������x!�잴�����T�*�@)�؜I��^& �O��kzb����հ�#�A\�w�����ȯ���s�Q���W:�����$��kJ9�2�,!��7�|2�������#n��F��v 2 O�����_Z��!z����A��g,��Lp��^ET�l�Ɂ������|Bb|�㮽�Pl�>�2DŽ��Kd�"(�SI�T�錚�D7Fâ ��RC�'\B�v�|�L��d6��f�0��5�13��r���ܭ6��0 �+˴� w�:� �򓍽U~�Ք~ ʏ4,e�0�3�����h�|�M+��P�T�d�<�Œb�=��b���'��"�m�����w�c"١��u��S�Ma�Va�'I%��1������b��kw�S��SS?���R�N��*����C`C?g.P���.��B��]��O`�_� SB�g��C&r���� ��u%��ږX���=&qsi�a��נ� rG�g�z�4��R���j>\�|�܃����D��EzV�ME�/���d����v���6@���R*�~Pp��l�+�͂RZ/g�-�N+Ǧ!�b��d�Ħ��5��g�}� u�"C���iJ�(����ܐW��v��,���
+�?c����DFb>֐\������Ź"�[��"��\��dY��Xia����vv�J��މ���3��M{VU��:͠��K
+}�.���z���j�,Y����_�J�Q� �_�ߨ;wjv~� ���*Y?�yvo�HUI(-��Cf��V�}(���1��O�r�f��Dr�f3�.$�&�ۛ
+��_�L�D��f� Z$�1�Kt�%'>�y��f��I��<9Az�����v�הY��KLa���҆�"��=�kA��V�+�]$?� *K��Od��cC� �� }6�����J����R���Q�7����A�*�wk��1^����e�lw��QK�-��(<Lz����#w��Ό�(
+����Ρ��� ��o�0#���"w���!��p�E\�s �S*�(����䛰��J�F� [I_�����V�[�����0~0����,]g�'�W)��$��g(9�X�~��w^5�EPx�m��[I���V��`���C�އ��Wx&)gVN)���{�sNk��|�l-���ը;�JtqRS�K�����>B7R��,͝�Ċ��׫�Y1� ���$[#�ѝ�Җ����:�#y��>�0a�J����t�ҷ� ,i�B�hU~Pq�@0����|��Ԛ�b�wO��P }��2:xx��V�n���D�����y���$���į���+N�wU0�Cq\��Ü�pa�wn�����bC5���bd���T��o� <H�' ���4���%//�h����-�9זl}v��}���� 9����`ݴc�z�!��=y�6
+׬v�&�@�<7Im��b䀸W��x"� Sp �R~���x?��oi;/-n�NEͻP�%B�Ӏ���7 ;}���E �o5�C}�"�"��
+�9�P+�C��鄆�R��b�2"�@�c�t�K��eg ޅ��8Վ�V�N������%�A<��du:e���mF�B$Q|t%�^s�;Zո����ٞ����y��iR����%���ԭN�4a�.� �rє�S���<��U�ֱ-)�r���)���Ot
+���[�G�e��4B:dy����w�l,�������?.�7�_�z������!�u�Wd�(Ռpq���8��s �Ι� "�H<��e���!�W�� {�Sn�x(�sj��-�*u0�o]�^f��i�q��s�m� #�C^T]��b8��Y����-
++��?�'�%5������mY�>�14@Ĭ�ߗ�����HaĦ�v6lE��U�y�0X9�ζ�9#?���7��6{Q�'� ��$> �w;�Ɔ{� :sED���c���7���;&~���ZWq�^_B1��
+�*��9ť���� �7'��6��]{t�0�kW� ����&h��WS>�e�$UTc)��u(�����m��Z?�"���ՖJ ]�B,�B�Ļ-���/�g`Yn��.�&�`$aE]7%9��'���vym�ڀ<l���8����Զ����cTCE �K^ҔȘԜ笄��a(�4{���e�@�gn����QJ[1{y�%��� ,��Lj��:F� R�y(D�:���m��o�$I�'��U�^��sG����h��R�6�����!�ˎ����6SS�F~�5R��
+�}�<�-����~��~��؁�8<T<�6�L�76�UJ������4��b ��o#�f��w�ma���
+����ǝ���Vb� P2��\v:�u����G� ^D��v����%�S�Ss�`����jЃGbR:roJP|�.ϖ���V�2j �͜Ò¬a �n�P��ʬ}�#��,����@��8Z2̐��ĕ% ?SQ�'���40X� ?�߆5)��fÝcn�����_eM�^�cf��t ��휂 .����LSTn�qfu�B�f� ӿ��a�&O�a.h/jo7PW�t��;X!�?��DLO犖�#�& ��.�0�[��,b�� ����� �[9t�U%JX�/-VM�(�d8D.�icW���Ptr;q k��=p\#5�L����㋑�5�:"��g�]�rw�F:���rnj�L�(4���D��l��t�Xyb�����g>��X=7�5bJ�JNgh��XQ� c쭆��t~���j��r�%��/�IY3Wbܶn�a�b�At��3��A���5J�aUl=�=O2��u�I #�?/pu/z��3��|I�X��[Hՠ�$2�q�q�28/n�ã3ӌ�քL�!$^�L��RIe��{\1Saai� OXAby����%�zFN�4k,q=�T�i{�h��c���� Ć2;8�D�#\z��v���on���n�4.�V������a �E��/�łz��n��������9��6������E���x��g&U�+�C:���8� +̹��L=�F���4v�?��f.ja)x�P�=����1��N� @f�����n�*��6�fC �
+Ǯ�d��S AB[�V��}�~Fl&qt[�+��D���uhF�-Ј�caE���+3�"޾C�Z<bzl�v�ʪc;k�o9G���Hp���p�^k .���HL�L��y�䪤�ʬ6_|iY�W"���Ypt�T#�4y�W/��狵�?e�2� s�9:# N�/\�T;�n�_�q�l7J���M)�xӃ}��>��W�8�if�|Q�ZېO�am�����G�߲䚼3� �ᇊ� X�aw�&��"��/t�r~�=�:��������<o7HIwƷ6�W��~y2[[�
+{=�m�n������Hh;�DԳX�9� �n< �ZӞ�$S�5# �B,�QR����+
+�lЉ9r*�3u����=�S���CT�#߄�l�e��j�hj{G�De��HT��2�b�&?������Ž��58Pc d�Q�߀�!�;�Z��r��AXq��˓�Nk��/�.��8�`�'�Zs�͚�9h��Bƍ�)2%�A��>W(�I
+�qL!��@x���T]@�Ӂ0N�M�V��=<�Y�]u�M���Fְ>��T% ̛Z?+djG��dڬ���O��М�>E�CtQ���:4A,��;�G[t� �.��~��B��3�c����G;�5^���.��x�}�ɱ������+�F:?{�{D�w������_x���ʱ�:aK�$c�x����tڛ4�ڞ�,ј�᧩��z!�����!qM0M����ͬ�TB��]�Bn=Ȗd�u<=����g���<��u��"C�E�V�kqW��KN�2�b�>���*mcm���i&n���� ���e����х7��p9�U��1B����7'��d�( �Jo(��
+}�g���-慄 ��Z�]� f� ���3dM��?-���*��5H]�[ ִ��P"z�O �O�� �,7��j���2د/B�{�|���gil>);/,3&�ù$��#h5^�0P�6����#"�IB>�C��q�ޞ����;����ԞT<C�+ed�{���qX��j@��^���~��J�s�h7 A5���F���L��x:�� �5ع�݄�&R�l¬A��h�{��SQs��Ϗ�i.b����t����b�%^���3�ّA`� �`/f����[�����B��T�j���T�J��B�ϛ�%�`���*hr������õp��D��U�S��"e|��:Cu�����5��F�Ƈ�f 2l]�Ĵ1J�v+j�Ԡz;����d_�h[��2� �`Z���~DG�ȅ��ٙN�M=�Og���&)�S���H66)�]�i{�7��>�}׀�#Ml�DYo�(\ҳH�&J9d���YV��
+`�_*�,�o���}�~�fz/ ��p)����!RZO��~s�|f�9D.v]�s���!�ѥ�� ����y��T?}5��\4��t-�W�����,^�t��oJwO.ʨĺ)כ[���7���� �Y�����k�r\��,!#�$�=q����� |���d�w�G�*��Qi�[��+�ݹH~i��D6�� �𹧝�&�(fd��=�����u4�f�� Arr+�v��]V�tS0�`qڠԠa�[��U�fB�ng�p��C� �l�l��ZյW1�Mlk%�����?:��b�F8��R�!�A�V�la��}�L
+<�*� :UbG
+��0�?�4 ����?;��& ٣-�
+n )�9YBh�L�xdOi�����jaY�{����+��Z˔���� Q�M����L��G�B����c�\ɥ�\M-����7��7M��S��s^i�^�;�^��,��.�!7Zg�� �(��\(�ܻ�Z�C)���L�$�O��jU�iяOV�&<���V]r"k��ܯ=�Hu�yv
+���yn�k��?N�����,�<(!zS�����.e�:���^d^UJ�eG'���������Х_^�5����ԓ���H�N���@;Y���N���$y��*6 ����I������Y������3��O�m���bCz2)l�� ��0+Þ��� ��֜b��M���v彔W<r�r��D�y���!�N�:U��HI�8kb^:P§��q�U�y����ٝ�!fui�C���� P#C�<(���p�[b�*ݤ�zJӈ�_����<|�b`?��Y3�m� B){�T���?O�&"
+Uav��Q��\#�t�%u6��y�I�� H�"���E�?�b�q���'�A��s��&�7��@V���:�q[�Pϯ��Ov��S�����p!�b*���q�Ok��n.8^�L���o"�Q����;�`ۺ��N�#uc�?�������k�DPc�:+��]Ŝ8+m�Gt"�yހh�p4;^꯾LV�������:�e�'��(�Z"��O��v��(WZ,P¯tS(�p#L��U2Ჷ�x�`��8:� �F�C�XF�9��3-��+�����{�k5
+fW�7+Oi� �vl��H�D��`��w�*>�Ή�| �����2
+B������[_�h�h�=�ꡢ�]�X�U[�� o���c��H�:V-z���J&p�߇I�ㆠ�̊LA ��h�3�È��O����go@����fR�#�X��^��q.�̼��44�F�8J�&;2�,��RK9bԃ| ߚ�JEgT{y�ѷ^-jQ(���n��ԁo�2��
+hE������n{�$��m�+���}w�>Φ<.}�5�%�5?�Zyu*�Z���L<M�)�D���c�m���o��#�o��̄8V�Q�$�t�t �F��m��uJ��%��� w�c� �g����R��
+0~�X�� n$�Sz �S��M3 J�� Wp!q_�rj�KH|H�c^�=��-�0Y���!�m���[S� �vQ��7x�R�c�
+K X=�u��Α/������ە�>���wѧ8��x��Y��r��u�^�E}c�S�,��G�sD��\�I�Wf�qf���ؐ��b"���V�Z���u�F�TkOw�JLF☟i�0�e���I�q"7e� ����
+H˳� ����5��k�O3(��P���]9u�~e�=
+}D"D�4��T��G�mJY3��J*�n����$+�)$BV*Cf�s�Xa/� R�s C�1�—�DCt��ы=�/x�W� �:��Q`�ʝ�K�0�i�4�$M�k�WKmϻ� Է�: �����=H5v�F�e��� �bh�Q���p�L���V��m����4Dn)��ub����#<�04�os&�S�״6��\���WZ�p#����t����tc  PQ j��6�4������x[�H%�[��ݪl-� �k��0a��f��!�!'�s�?���l��2��0}�ڵ��D^�c/�\O��A�1�8�O
+��� ʶNN� �^�D��C�+[�%t�?��k\l9�uS11���x��#�$J5u�W7)�`�Q��ѣ�W��a~*m�ͿH�а�Ĵ�� �#Č�j| a�vW���Yq෾�I������u�;m���ԛ�.�c,�Ь�!��3��*�� ���:S7"��bK�=�����)�6Q"/?�e���9�K���s.�����5�E�#X� HHf���Ȱ�C{X����Y(�߷h�$� �LD��l �K <���s=����9s1�+��O�Dl�j,ȱhV��7x���4&���3�D�&����Ԝ �zN���/^�2��D@�f*�}iU.���F�u���#�����j��́�z�����~Na�^${���lmB��O��d����b���a ��J?�?KԀ��xG.ꩣ����aڋ������֟M��P�8�b�"�3~�1������FȬ]`�
+fplN?��gcN3�KSoԮ)���1�"@���� ex��W#Jh��$���8�}��zP[@�;?F�c�� a�����G/���_0a��?]>C ;%p
+e���{�y�/O�!3͞a�ZFć�0�_>�7�5�KT��`��u^� L�r����S��6�5� �@�?[}�O[�m��s�����8�;�"��d�=��E�;�.4��@2aB:��yH5אU��o��Q����G�k� �q54��P?��8AuX�P؀�Ok�2�5�[?��g.&�ܕo-��BǷAM � ��J������Ā�yX�Sj�6o=���l�探�0XЊG���0���8k������X���ur�#��3o4�/����/H�y��Vj��� 0L[w�$TP��*(�����F�=�39��[w�dXip1'�<+=��z �:�rP�X9���G��-�1�6� _Q�4K�����d~I�$uba")�fĽ�-f|:���o� gV���O�o����W�����y+��S���R�**n�3��Ǐ�{�����T�H�1ۃ!y������(���9�j���A��nO�-M�y�K��̛��n���^����Y#K��2��PC|�W��ؽ�Y[���҇2���F�����\�~��+ ���<� ����]HL�M��vy����-���zHʘ�֔�g�
+e�6\�/ݶ��i�i��S���������7AV]3V&@�����v� #����$4���t��MB��bЦW�%���'G��.}g��8�F� �� ��8l!�bu?�ס�{�c���+MVP��2q�p�"c���U�_��
+��IX1������s0ݽ^���2��<App=I�X���۩L}3�en���eI4���ZV~dQŤgw"�3���[A�H�B���E��,����X��.�iӄ�F1��h_w*��{�-��� �O0逖��ZP�#�,n��oY�M��V��q���E�2�Z�� aG�A
+��C]���K�~,OUs��� 1Bh�JV{�B��B_���o�
+��"D +�z�X�c�Y�:�Nq�J9���x�+��?J�Ɋp=�� 58�6�
+Yq���[�t���WQ�Hk�0�9ޣ� ���*����B����Z޳�v�fO7)�O!~�� x��5�i{?�<����l�R�E��6--7q�iu�Yuo*~n��٠QY
+v�����O�)I͆Ѐ~aHZ�̝s�s� ֽp��4�eŘ�夅��.Q�ݽ��Ŗ҂=�L� �Y���O���6e�ɘ���@�JP[}rv��E�p� ��Ҭ�™ޝCܶ4��7<G���U}�@�X6������*�}D
+1����_�6� �3���W]*ۼ������p�HG�PqP��R��<QF���4J�!(����6`wmz��jd��hx�_,�xZ��.�\^�\2�Z���"5 �O��6�� �?�M�l��,��t3�F����|X�#��|�"���4�E�ˊrlm����~]vv7b�ТT�f4��8S����#����B� ��&��xC<-�t8�I Xԝܡe~��ᔏwa�̀2���+�}@>��HBC���Iȉ�8��?ōt��ʾ+C�V,_��8&�����[�J��u�!{rC����h�*�V�.�A1�f4ٱ��*��O�ӊ3��`�Q����;L�"=Md����W�Fʲѣ5?L�l����g\iO��)тCx`��s}�� 5қ��S��ⅾ?��T�#���Ԟ��.R�m�&cBp���ݪ�M��f�r{��u�{ K==��k[n������U=�*���� �t�"�KV0E��w�?�D"��=�e��� �2 ����^� �}7��0�ov"Gĸ0�y��ZQ$c���^MC-�� �«��/Y$��<)�"ܖ�ʞz��o<�e�����DqCR�� a���H ���K��s�o ���w��d́FK�C���A �Yh9Knb�AdP��h�
+޴�"c ���L�0�ԍX��y��&)Q�u;�$�qEO�͛OS�gg��^f�;�!��ë�(�߉}v%] 1���fшR�O��ڠf!͚�j���p�Hm�m��PR0�6>����Z��>:�����7`���,�,ep�Xcoy��i�� hi߀�ͤg����&X�Z%��lv�;Z|����!������b�%Hes���T K俬=l�sᄏ(� j_.1�YD$Re��,��c+Ï ��o Y��\�����' ��!��8Uʸm��R�^d[�i\�W��A��u$�`��S���&��[ h����nw���!8 F��G^]GM-w�ҁX1D���I8��.� Y�A��5x<��W�huSW@��s�P`� ������q +��wqp�/Ҳ�Q�_��A[�Nims��M�&���k�/P#L�'�k%� aNr������-�r!K���K���J��G�fP�I��vS�U���� �<9���ZN�ez3y!��П��c��R�\�;ʴ�:��೜�x��j?�*>�'�*y�X����^C�H��q���"�(���^[����PF�K��Y� �05�F]�eOl���ɬ�6��dG��8.�K�q�>��0ڿ�%Ʌa�@o�VF�򯡷_�Wx\^j�\Nq���� ,:T�qw�������� ֎�j]0Y�w�o ׆���k-�@8��/z�@ "RI�K����V��5_��H}�ǺxI ��!K�E�k:���lUq 5�øe�
+,�.;n����W ��q�c�2,r.1x��
+昤 ���+��/i9��e�=c� �$�E�h�%Gh1�����O���*7�oB�\�/�Y[��fD����d?���;cg"N�!�2��㓌���%���4�'
+�"Y�߭�$o���h$�W3���Z�0Ɣ�(zx�mO��F&,���+�ͷ���
+��
+�5a�^3�/} �v�u�Z�
+��J'��0SWp����o4�-[K�Ɔ��d�e",R ��@cDH������֙21g�W�V*=-?������8-k��+���8��✫3K���Ny-�L�C8_���1�,�eV��!Na����q$UQK�Ҍ�S�P��_0E_r!�D���:���D��S �Ki�z�]I�?l��|�7����I�c���L�����k��i�<�r�'�iƑ~S�h�����~�����T���ιf����K"�6h3qQm��ZM�7ߏN�����E�8�
+�����p��2���DM$���=H$8�S&5"r�41��f��~h2p��u�M +n�"R�%�b��FMF���3�ߑ/&<��3�\z�X��Te]!���jB�S��3�Yib�j�����*���f��9��Z�n�0�R M�#��l�u����HL�z�fg�� �um�_�?ر�W��Ι��ھt��'����� �Gh�8�3.�DÒ6���*����W�fj�-!�0|�6��D1{%�"��(M��@_cd$(���>[�\�����Mt�� C{�w7��6A^,� �i�*��G��(mź� `r�h4D�`�$��J��Ϲ:C&�c�I�bЈ-�l�D7��p���U������s&�9�P�Q��`&i�]�2e��ȸ���������m@�_���d�UT#z��R�xv�`�% /����n|�t.��S��V�8=\�T{6�6����<f�R�\K � *�͸����� ��#���;�X��UW�k�f� �H�̜-Ά�c���-��鏚| ��َ�/ %c�դ9�"��/p"��1o�X�,��:H�V/S�T`�шu:��EU�1��;y]n�}��Q�ɫ�'���B��<=�+�@W���֋���D����!�+�50��b�5�P�jB�?�����
+˭'�(�u���R�bc�Bp�60��P �/�Y�ͯ�����~����hA�+?���\.���*m�B�(��'����N�[+�������6g�/�U��y�����g���+a����2D
+N����4�����,��V�u�.6�k�����c�O�α�o��wrR��$_PH�'�{���ap� x�d+1��rT�ܾ�M
+�w���od���FoSy:����؇x�����(L�}�Q)�𛻢4�+��� = ���F�9F�F�#����vEm\3�}�� ��f���8|� j�4C���h${6�`���Y�%(�!��e�8Xs��]&�ѮZ�5�оK�/^��X�UD�#���H���Lx`Ӆ�����f��D����� ̶"�0��{o��Hބ����j
+����O
+�ώ��.�� q�f�|�aU|5�nd��Q7�h=�QJo����ŇP�m�1�$�G�5�7�� ʌ� �]�0��S��b����r�y�c�J� �BC�Ϊk�e�eBL����
+vb��1�H?8�Њ7��zP�7�Q�c$���tBm rĶ6 ��o�X �q���0.�9*��J1� �.�����5hf�E�զ�HK����9̜��-�(���s�4��^�_ ?HۅE��-ۯ4"��(��biY�jl�q�Q*����'�B%�J���k�b`|��=-��ĩx�1x��>\�0�x��m:�J�$_���w�J�x��8�KDp�s�,3�%��9���mBwQ-�xbKj�G ˎ��u�۵'�:�@��6�� 񪞝�
+�Id �����2X��_� !����0�ۈa���D�DL*[1�_+L�7�"�K�<m�$��Key4����R#uZI귋ɔֿ������=��G�r��o�K
+Ke�Owkٞ�w|��sH�ј\��"����ȫ�E>�"���/@ߧ������@:�x�e*���^=�o��#-�R��/���j!8���_�`[b\�3��d���;T���jZD�*%g�p�A�$nl|{j�|hh��D>(����/y`�� ��␞[Sa���cE�����#�I�1�v#{�Vx >SQ�#��vwQo�o{��G�
+�]��^��"��L�҂����σ��]����f�غE ��d�썼��q`
+yd.~���_*g �V���ȸZ� RY3҅�l������Ej�< x�P����zS���)L)�n0o����.�0�_�G��� ��PK�Y9.�챒�j4+��/�ևc�w����N��:�d;
+�Q�%��Š��k�U��cNZ�mp���g��nh������"E=x�^��@��.���Ĭ$rk*�6N�ڽ�=x�{LI~����ߖ'��z���}�A��wa� �W켞�r��;b,�V����FX����.�/�zaE=�{d4����O�'�6�޳�N�sd"6����ˣ�sl#]oK$pq��_�s�����@���/Ǒ��|�0#0f����V��TgQ�K"z� �ρHq\����H��S�+��D�.�@����<s ���Hιxt����� = W��h�����ܾ��tG\lK;���1Y}h��a�gtH,ٺE��oVk���ą�r��*0��[��R�Y�V��4��qgF3�p��^^� ������DB���y�������6x%�i�Ʋ�1��%��˅s5p��w Q�l �1�ME&���%��.��o��!�KH_V9�YR���� �߮]-�)8�`��tb���]r���3o+W; fJ%��$ <�3wl7xa��L�R84��gq�9���f����NBS��
+(��Hzf�wzn��n�h��ު9c��� �89�3u�k�|����J��"� ��ѳPM���ޓ� �s�s���_�~�9��%�A�_�@XvxC� �K�ӘqbZkB�x��b�Y����v���$c��G�*��/���[���[VR���N���� ��f���e���#���!����,�p�7��/�f��Uf�]�p�D�3A��<��=���x���� �V;xl���W}{tw{�BQ\�x��Z��Y:���E����#{}Vy���# q��l�
+�e����$ͣ�.�:���V[0i��p��1��U�m���z���? �:�a��K�N%OJ�m���.�PᲦH��x�á���4su�O�����w� �E\�= ��@߸�I���|��E�g` -��I��,Ǯ�bB)> µ���#�{ĩ����rj5�M%V�0}���Sw��eE����UԘ*���mn�ۢ6g�+�}�ݔ���_ˢP�������]�a�х�FVU;ܸ�Z�.F��r_����z�T;�N����Z��@�%ᰔ��.�33�D��,��Q�Yzwo���E�H��$c��,�aͩ$����V\}3R����� �O�k���4"@�5C�.U��\!A4��<{帻���������@�Q=�Ζ��%��0�/���i�r�eD�R�&
+��bd��X^ER'=�Ǩ�0���j���n"+1(�d^���,�^ng����� �l�K���W\�Ul��_��;��{�}~zeGWd�q��(��g��l�O�W�z^ q�����pt� 0w�
+dq������r�D�Ҹ ƺ�f�p�~�W�3�L�U�!�k� ��-�}. ������H&ճR����~�c�R�'9�0�fS�,�k]��S��!��Mג;c��6�0eV���H�v��b �}���h��^�kq�o>@��n�ľ�ZY��Ҙb��QS�0xF���a����\�IkK���""�`:�g��U��+7��6#��ApAA��}5qD�-R����
+�
+b�ʤ�#��P{k
+]Ⱥp#+���mS�8����"�O�� a�x� `�3�@��dE�/$�Jե~��3k��S�qa���ч07Kv<
+Ћ%��K]���Y���9~ЏL�����2�k,V�4f�%.n�[z�6����
+&�"hm�Y���![)Ϗ�,�]PU���� ɯu`$^Q�zq ~�haC��~��"���0h��� �=$sޙ��ځut��1���CkH^X�:_Lz4�q��/��p�3�i�����x�ֻ�$N_m��`�9���n��w��`��������%A��E* ����Tn��k׀0ʫ�_�9�;�Vl�&e��!e��{���8��VIv�\t��v�@A
+(���:�H��$T������h��%�(%��-���g���ز��npV�9���-n�b�Q����A��,ZGҜ�0��ފ�1�1����r�t�@zq_H��t�b�ȉ�߯2@�Y�yG��U@���~-oY��~ |��v����D3._�#T��.�Ւ�$D|�
+endstream
+endobj
+855 0 obj
+<< /Filter /FlateDecode /Length1 1366 /Length2 27424 /Length3 0 /Length 28388 >>
+stream
+xڌ�T�߲=�C �{����ݵ����]� �]�����[\'�{�{o�f���ku�jW��S{��5 ��&��%�$ ��p�� ��%���\����44Z�n����it@.����� ����I���!`����� ��+��'���dg�/ �E ���(� `�+2����������6����`p�1�+ �r����@7���-�M��-������qssdc���d:��B\�E���n6 �+��d ��a�
+����X�iZ6����kB��<�. �_�����7�l r���)�Pu�� V�7��p�r�w��D�����`���� ��[�l@UY%V7/7fl���
+���:���U9 +��m�?��Z��:�����:��"�?i��� �R
+����"�S��� ���{��{��`�'��? +[���?MX�;�i�m��A�����5!�����agg����� / ��ky;��������_'���o [+��d_W��������;��
+��`ik�0Yۂ��'�_3�����w���������?���%���?�͗MW]S]W�����OR��e���p�88x|��w5���`��Xy� ��j��U����G ���K� ���܈�������o��+�����d��"��Y����ÿ�����?�@G[���������!e�?����V�`���݀e �v��C�u���Y�ٺY���+��k��1[0H �j�ϥ`�`g�?|�ea���p�K��@u󿷔[@,�'/���F�;�+�/�_%Z���Ea+��7�9����y��/;���m����W\���ߍ�k�/%�@^ �e��P�]}h�C��'�Ѵ�͑n��K��b
+CM���;���~���[�u�Wߟm���I��~/� sGȫ�x�3E?%�H?��h���:���öA�(��9��`?x�y5 UlL�/���*��T̳�j��.��g/P"���"1b��B_��[�ʝy'WH`B�?��*�5������U����KHMh@@
+{�59G�+y�Mŷ�$N!<�Ċ�d�E� ��]Gѳ&\11�7A��4X��`.<�B}�Fr쇃fn7V^_��+�i!��z��+�Ot�%����b1�� u��k�8~� ��l?�/��{'���j��;�<�/�Dsf��ڼL�F<s���Cd%E��0Ӌ�9��{M�)�Bt�)r� �yK�е�iח�u���f���j��lF ơ<��o�����Z�壶ѡq����y��%��!h��{�������%R-�Q ��
+�\�]I%tڒ�ER,�d�
+%�}�A�M8a�`)���R�>!��_�!�J.�xg.wđ($�����*'���KrU�/G�@/�{����m�M8Μ!�a��8�t�2H�*�B}s�z���_���X)̜��F{yye@E`b}y�]FR��K���,��P"��Z���|/�J�U��#����Q�>�����-RLO4+(�MyךCqiZ�H��l(�ÅW���]�6#����y�E&�e\���� ѯs�\���Ԡ�)�a��ο���r��� ����~;>5�"C��ʶ;�gB�A7 E�(�`�v��'����xy����<��y�8�1���^t��6n�����
+3��,i�`���z�`���>��e�n�
+~<5'���Zd��������� ~x�>��2Y����V?�b�Ϥ �ה����J�)�1���%��V ,f2����v0ϖ��o_��I�9)HN�k�����d=�\��]���i:��Cn ��5U���ds�0����L��Ip��6�>� �,�O�I#�<z������f�qa��=��ٛ�C�`� �Y8� �ݧ���4� �c�'(k?�UƏ ��X~D"!��9����.f]E��%��[J�s"��"��:D�zM��f�#ڰ��=����=xV{~2e�n0�\iD�G�\�5n8�@�/�_-d�3�`���4��%��U�ZP����!.Od���VjD;6���=6fS2��N�EB������6 ���� ����F XtsED�ؼ8��ܛ� ���.��B��ҙ��[�,�9Nk+�:=�޴o����U���pm�7��"O��������8�����Ḗ�%���Uc&��`E�B�f9Sa���h���qg#)����5i�,C��p�v�_7
+�F��Z��e�F�fF��6�~J�f������-ԏ��V���;eU�G5�G���i���.���q�|������Ұm?[��•� �X)1p��zY��qq1 ;���c�Ӵ��e�$�K\>䷉몫��b��v뽿S��Z��Dj�8xB+N�2�p�7�/K��`��0�[t�K^�$�����f|�N���&:�L����I!�E(ɶ]���E�}������B�o�,��9��Ī~���r�(6:�e�r�����
+�;_x㉆w���|��P����k����b1cd�d�r%�di�7b�K3���6ݚPU�8� ,�1i��撣dpd�d7)��8�tuB*M+�MS?|ɰm\1V.�o,.nz���������&)K��,��i�ŧ�&�����j����lѵ�?�n�w���#u�o١'�]� �SE�b�� �3DX�F煴�+:������n�0�z��"67�P��+sm�<$��hY{dc�ԌMZ��d!�7�\ۂ!�0߱϶\�>iF���R$j��� ���dN��C�kzȱ ��Y����;\
+X��g�|�c�J�"|�r���dՈ�)xG� �!�yTA~� �V�x���p��2&h�M���Bbz��Ĥ������|��aӗ}�ъ�F k��;}�� |��p|*v]OW�- ���;��6G�,��鳅lUn��L�rԸ�(L�!n����-����i�CY ?�T��ׇ����D �\A���T�+}!�Cf�$@}mI��<X��8[�z�}��]��76J���_�B7GY���C���h(^��.�cC�6��$1��Qx-;�6q��g&����S{��|ʹ8ˉ_헕f/N�o�{�r�cѬy�:�i1�BRca�= FL�N�7��Fs֞k� y��]����msv�X,> ���U�QI!�)S���9������F���fՅ��$��:�P�@�G�"�L�¤�tlr�MHx�–�,]ٹ�w@' �M�E����I5�����^_��rLc�,�B1Z�xq�ڥ��xPή]��$�_�D�@��&�H\�b��f���<8�2-˯#L/rc���8��s�fy�"^IuK�V��#&� k貚��<$��+�H�Fxh��6BA�O&���oMċ���#�F��;D&je����x��qo�rE��9����_����E|qh���e�w1C���]4
+p k��D��‚�O}2p�,)"O��C� c�=����ŝW˔�$��<�9�Y*"�+����%����.�j�j�g�B��:;�,dk�~i:��0dB�@� n���l��G���0�['K���V~h����d�/�Q�붲�i/�V����@��#�S�x�Է��Ã��ƒ�_a��*M�d�BJ��1��[&}���b�jo����0O>,oԽg��l��Ӟ$�Rf��q�뀰?��n0o#��=,��RzH.�c��~H�w�����} Ņ�D/�)_b��yy���I |$bs6����u����@A��
+u� �V��H��?�јӠ���B��$z�Ɂ4[^&��د�}��i�+ƪ&kI������g~ _>��g��7N���ɐs+���9�y��D�� -�\�ֽ �@1c�t\cg��ix_(������N7?\��=f줨]��J�� ��rضp���������T�J$�~�HR
+�Tgi��;�e� �hg3�m�P��'{�����ۢ&��lf�����zY�ʣ������ E�5|/�]��Bt'����a��eW. b���
+|��`�l�*�aM���Q�v��*�4�3��g��Ri�#�/$��lZL��W>���������<ڷx8qg�I�]�\(ߵ|� �E\��@.�Y �Xm���&�!�=�:!��h��������~�l�!o.�腮�t����.*�vL6y'��l�sg/��"�j�g|��K?�-���z<w���#�&�� ��Ý~7&���8�������7�}3�?�ݘ�b�H� T���3fv�����ge����;�s�ͧ^�GqS,^�称AJ��G�\.���_���h?6�������I�Z3��I�iΎC���"哿]�?��A��n jG?M�@" ra�u[Ys#�S]��mPdR�E��?���f�>�]ﹼ�cd�ƻ.��!�=�UT@Y�#q�P� 0n�%>����#�x u� <��'2� ��wd�xd�,&֨d�a5�N�?W܌�� �Js�ǵw���:�;�����=���v��p;��E�2���>U�{H�G7K�o�]SB�d�6( ķ6r�\�;o�&w
+g_�Cn���Zq���YH�_�) �h��V�6��2�l�DUD^R��Fc:32��x}`XU�˯$�.e�k� ��Hm
+��몳�>j3ޔ��7�8 ��p�G���]�I*6��^�Q#��v]��ͫW뮚T��U���G��
+\�$�ܥ�8��XT�ӂ:�sa�/q��$M����ޞK��&�S��)�=A��Flɵ �L�&��(J`��{^����G$�J�>�Jw-�j[�tr���7���P� ��.ΐ�ջ�����)���ؔ�^�y }!vk B�y��qԥq~
+�?�f$���'{��u��>C��������n ��:˯����+�;ܣ����ˁ�j��FX��aݛycIDn28ɦ����5��>��%_f��!�ـ�K@F�k[���R�H��%�9��#[Y��R�=�h."V@���5Cߕ���hjA~�ٻڏ�<�?��C/��슰bج��:i��� ��4�b�ٮ[cN��?\f�i��9e��W��u�ʸ�t�j9�x;P�0$!�<⿮Y��a|Ip2�8S�j ���jm� ���R�*~��%��$�:�ڒs17;��|@��y*=�뗉���_ȸ�u�bE#�
+3͇�σd�������� :�T��e��.�3�'�]��T��k8�����մ��4tJ]�h��MP��Y5����T��ȓx����Z����8x�4�l��Zy������&"�7�;����Ny�J���w/DC޶�R�ɖ%f|��>V`��2�t�H�O��/֠Hru��]��3��.6�,W{�p�=��N�]W�hJ������!�#3<�;�1Z�eJ�:� +D7*��u�I�Ƕ�m��z��H����Ղ/������t"
+Y}ot��'��+9~+�X ��n�k������,S��T0z6& {5��o�Cg��� X��w���@!���+��.)�O?��W�t����{��4��?� �bRwR=�$;z�>��Q(�K�1�D��/�q��C�pGS�R���)�U�g&!ڰ8(�������mR���_���� $��A���KA�#Vw�`�n�S�,6,��� d�Dž��]T5����t$��=h>���e��,�ؽ�-%����W�c 2~������+�-(}��>�� cLc���o5��X��f�"�
+TF���/�RB���WiQ���,# T�!<���9�_�D�'G�O�xXF��f7@�T�9l_��<��Bϳ8 ��3!7p�e����N�֨Y>���'��� *B6>2aY �8�U.��l^}g�`���kCa�1@�*T����c#,(��̕y������� |d��@�3�vGಈ.d'�:tm�Kt7��������� ��p3��9L7�UI��oD�U���I g߈�Ⱦ�|s��蔣���^���s�a�IA�z{�ݽ}6�G¡Y.\��LE��=�;��U���#:#Xb^��$��=Grs��T^3�>l�S7�����$W���y��!ok�8�&�9ܐ��ԤbQQ�pa�f��&�J �k���X�V�S��G������nf��櫓ڂ���@n4��X�;D�_V�62���vn���e������~��4g�ǫ̽�B�-~_>��9�j���ps��������m��V��Z<f��^}�x���]��db�5��zȫ'fy"v�m�\-��j�a) 1�+��� �*� 4�v{�R�Jq�9���du&A[݉�T�k���࠸${
+����=N�@��ܢ�Xb_�������&w�b<l8[�6���3����jߗ݁��)E��^휁��ƀ�k��r��6��ˆ�k�?��dX`�TDŽន����?0F���_�|#Sٹ
+tC��sk��
+�8�k@�kmC�7����J:��2��m��rԴ+�ϛ(/�o�1���x3[!�@�ŵ^KW��������˥�������>��h�V�J0M�:
+�C�`J>����߬JM���L��x!���q$�X6_9�H'*�B��/d ?o��_$���`���2Zy��7#|��J��޴̿HS������=Ā�� U�A�m�t���*�|@Is�u�4m?�p��H~�.�r��xr�8�3�_�� )%�z���4�X�]�/Exs�Vx~�~~}%;�B�h��d6��CU�9m���u*s�h�s'! ������d5"�?�+t:�1�S̤�v2f)�&|���r2�VW��b����2�<m\h�]c%�
+���+�H�O LS����/��[�ć$0� ���-Q9w';e&�=�x�Ua� ��tt�4 ~��10.P^w��f�SL
+�I��:m�j��+��^���]vӳ�–t�kUޔ����Pg���ۿWAq��K����\ ����7��!���15F�do���&,�r�Hsz�зNokE&ə����h��=촀6;�U�2�(�H�.�Z\��!��1�p�/�;�_���HB��J�����ʳ��G�>:�S��ο�x�do[��j�"���\&�A�ye��H��\�`n����Ţ %�p��#]V�T_;Q&L��T�;C�e}�ő��a@�F=v)�:Sͨ��Cl#�q������x.F�,����B8�$�Ei�@m��/���)�F���,w��x�� ��[��Cl��T���:�l�/>��^��)ð�u��D���-��1M�%���F���2�BH��|G\Q%��&+mkݲJN�Q�K�������@�pN���C���8�^Uݩ�y�W�L�AoV_d�/3;=�Ix@�3�b��\���f�V�I��J^��,�w��:����P::�(�� �~� +�eǹKH $ d4}�q�!w���ȷ�]8�l"�f2�
+������[+}��L��0�q�1� %����Th��9���n��S-����镧�d0�GxɆ\��v2���kŬ Nߏ�׉�����c|��S��u�!���Da�TT! 3��� ���]x���-��q���I� 9z�X�����nX�� ~��Р$��B��M1�'�[��Ea�T!H��G�K��\�lEV:�<�����Wv4�Z6
+6V(L�4���p�_�u1g���XCF���y=FN� 1�l�>K� ��A��bǼΰ�"?u �¶��@N�l��/D����jG���-�t.���\��ꕩ�E���Sl�MٯP���y��@U�Gv��/D3^O�-h�b���Cr 6�c�08EL�PU��΍�ZMx�I\��q����Os *!�]���g��I"k�QH��*~���l�?��_���n���y�)��7��iǞV���ي�\*B"��J��z�@���|u��'3$Aʖ�N�E�~�h6W2"{BLh��NҜ�gp������ʌo�����0�2���KS�
+��>���6��1i������� ����r��ۊ��%= OהsN�C7Ʃ/ ��v=;CcW:�C�b�տ�g�Ec���� ���V�C�o�^ڤ�c �XG��O��ًD�ם/v�]2[��H{�������u��}N���2v�ΰa�Z8d0ߎ��+�3�� P�eQ��[g�nN�<5�0@ņ7�z�v"I�^�N蠟F��Dz���� �P�m3�������7��aop�V���HP�C��ZU�P�<���c���������X� ֜��qd:L��t����8�1�D;8���NJ��Q7v8X�49����X��ۇ�����g����R��z�pL!⾰[p����R��@ �Y�`������C4<q�� Iy����'-�o�Z2�ʝ_}Ê����<�k9��Mh�FՖ{B�;�Z��"���������Y/n�� ����^�s�E�i�:>LK�
+ �rˏSOI}?.;�I�H�(PA���Ulǭi5��·��LvI��Gi��;��W؇��1#����g$ai���1d��Ϗj���gY��oT�6�����׌����p�2�� zC��
+h�0�-��4ai5\��?���D��2c :��R3ma��4j�}Z�BJ�m�}��,����g�7�tv�.�}~z�2�:��D����v�׌�lA�����ʹڎA�~VC·p����\����YDreW��j�w����c_���ɲY݀�����o@�[��2��t A ͢���m� ��wPԘ���� 6�3 �%ZqJu�D�T�r�i���'�E��k5�q�ƃPx�������%ł�W)OVaߚ��)�$�4�U���놯O�7~���H'f�T��8 Y@G��Ȱ��ދ6��y�(.�ቂ>ڳ� ���Ϫ,܆Q����Q�7 �ѳ��,�S��^����Z(h�z�����<���*� ���q=HaHJܦ����g}�#.��V� M(�S�J��I�]�r���b�6��Q$#��� +%iG6�� o*Gt�� �����#[7��[޲��<D�0H�����:�K�`VNF�gISZ���@Cd(
+��N���C��Ne[J�_��G�;S�_%(���>%��;���mk:]Ɔ/n偔�&+�|z2���9��Ӑ�n �Qݩ �tnqZ!We�eN��]k�G�!�\��~��Y�2���ꆖ�Vh�?o�^Ҵ;��4m�L�`\��:���?����̢��S��~�wB�����OJ����4����*��6�؛��E8�f+�+1%�ex�k�=���~4N�v��1��0(I�BR+-��XiŔ�7*m��R���^���U�F��A���uiZ�/�| J�&�w4���2�R��7�޼_���h��S�*E7��7P�*�'����?B�y��r%�#��KY*�w�� >-Iqw8}�W������,��^��L)�ͳ�ﱁ��(e/��>r�!xy����[c.��~�+ 3�%�W=���R<�R�^�����fE���1�����cZ���#��OS
+Ɛ��i�S͂�Iy�+֚�)���Y�2�zZ���? T���Ƹ�b��þ] �F�쁾��� 2�>"[T���&oYG�TD�++W�:X#u���v_0���E2��M��w�
+G� :�B�����O�u�w�}X5���׭��Y�[�%�OO���El�?�
+/�����'~�=�0�@��x!B�v#'n��^S/t��BW��֚M��O�.�o.���T*�ʵ���
+qD!X����\|'�x�F��E����߶�a��Ĝ�J��N��_�s�S��_��Yj���t��.��nw9� ������_e����.{m�� ����T����L��|��X��8����1��S ����đ�o��9�t<:��. �ȿv�C�>�W ����(+�����Q�ʤ�9�C�n�L9�"��Ɔ��s0�ޅ��u�R�Ӯ�1�7؀�������QyxW�u��Çm��v�/�2���5�n��=�#��g�y8��:`�+��d������K�z`�/�bAߤ�|N"�d��l��T�67o$^�.И"���fA9_���(N����������X9��3���&"����Ӥ�7k�r�wYX���S�38���~�> �O�r��\V�\��is��f���M1 ϰ���U��F�Uq<��+�p�4�c�r�`)T*�V�Z&�A�b�Z]���D-�q�&%��Nw.@#|h�U������kZ��;o'�k$ki�����oJ�7�+$_6h��}���n{SS6���TƨK���}�����ņu�M��'�������:eᏄ ���g;'G�wJ6봧�ø��"�a�hu{8�8�7���dG_9���-t��Ԇ)u�^���q���m8�|��M�/�C��,6������e\� `�(5�@�!��(b�N���\��J�ԐL� �9�i��L/��o��pn�W��B_�f�����Ĕ���Q9KY�fmm�݈�*�N�d�:�X;^߱�ҷ�">�������H���Q]Y�D�y �: ��-M�0��q0���C�ȉ���B5U�l��f+���dv�:�aw�ů4�r��:^o��N��5^��+���j=��}0�O�Q�Z��PU�-.���&Qи�t���ةN�G�%�H�����v\S˾�\��<�:U&eD� ��oٿ Om1�^3���D�0]��/��Ef����O�5
+8���dj"���ΧΔ4:� LW��ǟ�d��.�3B�j:ѹj�P�Ѯ7����f�7ś�c����f�&"�<�@��ZTpB��� ����t�����~�����dZw:+��B��j-"pC����a�XЕ�ނL5RQ
+� �7Y%�&��0����ݖ�Y�I�N�i�Pd�Q����O��%���d���O� ^ɓ���2�y-SyKu��*AJ�!��;���>yY��
+��b���YN��p/P�8�]�O���Z��&���� w���
+,W����Z�=�8�N�?}��ޫs����[�R1[v���F�
+'��` �`�V'�.2�祒Ɋ�g��~����w�NR Q���߭���� �<ft�g<$etc��R���-7^� ��b��K_�ӨnA>ggnaA�k����f�2Y���bF��U�1 �ԉ��7G��u�g�������כ�����WrWK'����wl�\�9�.��&� $G�*,ΧM�a~N�g�f�3w��'�ZN�F����V�+%(��1�^�a���@-g�d���]I��p6�R��r��ߊ8C�o��պ�I��3��d�@�B��{\�33M�f�c�{n_z�Qb��}Z�8�#z7fk����FH�h-�H��>��k��Z�e}����y~�)�}��0+뎎�>>��F�$4�1�+�e-���&���JS�7xEr ��J��$���%�}�i�gc�+��������@"~�!)�??�K�A
+u�%߮3fx(W�Z�q�o��}5xW�o� r|�I�|�ӾY��/ap��
+27�-X)���Y��nכ~��/����xVH�M��,cZ��Z�P[��쨰`m��*��w��m���ۯ2��cd�Ψ�T���oF�^�Gnf~b߭0����vJ�g/o"���KlZ���'s@cZ�P��|f4vHa�0C�����b�9����� 3` ��?c�v$�q2g�3��<�/h'1 F���v��t��;��c!l��� I���v��j�q���m]G�wzc�m:��� �'�\�����i���x3b8 С{���0/2�<�k�T�i0���\C�D�Jis��_�.aI�~���v�,'vѾE��`�0q��>A�5 ����G��&�w�h��+�V���\X�,��ff�L H|�����
+�Fۀ��b��􉣯 #7���V�*Jq����y��)�س�Qt��^�i# "��?�3,���.���I�{ Y!%�$��e����pC�YOv�]+~:�ährG���"0��<�>��A�<��W^o�ڷ�`��\䉋=[m~�;��M� �yn�L)��4-�=+=�Q���;#��<�O|4l��㭖,�Zh�ο3��Lœl2��zUkn�E���� �k?����8���l������?m �z�9�DE8fz��>Uͦ�OO �H����j�!�,"n"�!�W7W ��.{&�J�v�T�3"��p�`zC�:`�Y�8��B��V/2�]����������A��s�N�vs'p�e1Nt���R'�L����C����<Ǖ�T�I���A����]�Wˮx9aZ"$*��^?��}|�8��i�LV�';k��7ɲ��%�r�8�~��z�� ���-�tu��y��/�_]+��m:�Σ"p߰T�J�2�L>F�NO)�RJ ��ʇ�}󀰜pT
+�@�j"My�o���y�x�}{~��g9�ў����?���9�꺤����]G���e�� �K�餠�n��^U�Q��&�w6�Y��B�~S0-K�����#��e����(�G�W�/�M��jZl����}��6xJɕ*�c���Hmu�Sn�%�� �?�@q���)�u+U�^�w#o��Ot�kt'�b�:��̏�Z���D(|'�������(d������Ո/�}$n�c��c��%��pXˀL�I联G��\��u
+ŧ���@�����m.���-�B�y@A>賭L�gu�;��*�R�r0�F�! Nr���>l��K����b���]��[��D�hP Q���^�!8_��G����$JOt,���J]|*�tӰ�>:���1����m<7��zC�U���������մ��33���v��A���<e�Ϝ�ۆ���J�2�뱾2�>%]㠯R�`���V�������**�(#�H�W�SUP8�A��_�7�nTQ'������oDß#�g��H���s+bN��ķ�e0V(��[
+T�D[�/VdJ���$V��؈����Ē����79�G�P��_Ηz�p5��e��] �� �Fr�,���[�0<�Kh6�����"��ԟu���֟`J8Q�eg{�v� �DtYw U�����8�lu�����l� JnpwW���4d��:�Y��8��$å��l�"�N��7e�mV���� �:\x���KØ�������«�A��g�d{LUP"�h>�E�KɄ�T�g�3��'{7�OI}@���"��/¸�M����W�<��ܫ��'vw(��(���d������ԪrC*���JLjD��{�ѓ[o ���B�B���?Zד���� ��n����|��Q�6�2��%�y(~��rʛ���(�l��a@6��%���. fʊ�.T���6�rT�g�^HS�L���ҽ Ȳ�� �%� $(��^��.� �q�#�(�/޴��]�������_�-UK �L���W�{�%u�8��g������؟}ӟ m�;e'��n��I�N~��@a��� ���w����\���u���k�gzֲ[;yeC��B� �]��c�~c�UQ`��}�X��Cf�Ѝ��>~����p�p��oP$� ����2�j�f�Lk4"�om�_�й�i�,�N%�b��"���x���k���vVڨ��5VF� D����j��<�M;�]�Vwx��?~��|q�I�����M���ჶ<�4���I��nR�[Ͻp�בx($��BiH)H�DA�� /�^�f�.k�����jkr���
+�=���z?���sb����|�~������GJ� I�zh
+`"V�S�3bZ�Z ��� :]j�K�U�Z�U�fD�� ���V2h��,���+0źK������*�g��=ξy'��X��]�k���I�L�jl�b���)�U�D8�a1b�:�&|���|�mf/I�'N�%���ɼ'��I����K����ƀ+ӵ8�����;�������g��3��_z�����v���8 �q��%�ˡ�i��(rn��z[+X��^�р�q^�KIg�:ڦ2��� ��U�t����<a4Ȯ:��ݖ:�pq��^罐B2���Cg����>�P�u�;��ܛw�Eb�(f�褄mᜉ���iy�a� ���/���j�n��U�+-K�X{�W�(�Da���0�<{70�?e�5V��ۇ�-��/q�ۃ>�<��ڋ̮N�긕>�"牰�q8�Gy&O�.7S��ꌷߌ���y�M�*h��}cv_hΪ8We���黵 xb�u�{@ (�˅=Jt�n�F���@� ��r���ǹ���Ec$�E�|�ҡ��<bN��7}0�
+#�0��h�j�b�Ҿyr��۰�!�p�׼s6���EKu��!&�� �I����R2�g��Gd$�,"�N˓JVq�7pE�و�����x�C�ǬЏ�h%g�G�ʼ{�XtO�8��k��y�u��*9���jBmɅt����%&ʮo�]�+i�V/�.�����g4F4�g�,�ȏo.D��V�z���4�����H'����tG�wv�2��HZ����G��j��(���X6l! �IM:��D�C[b�����B�Ӥ��31̆A�~�j���Ğ1V��}� ʇ^2-C��"���'q�8�'Y��`Sx =�gnꍶ��N�+�D��Qr�u�/տ�&���*N2��[2��R��_����8�K�I�%���o�؍��j�IX ?WùZ�W۷�9,< �/T;���c�/Pex;��(�or�<0wQ��ԁ"�,��(π��: &Kĝ~�������f #.O3�B^W�/��7�
+���wo3)��uP�����!�N[z��E�a6Ϟ E��͖Z���g� ������m������N|/9��
+Qa;m��(#׭�3�~3�ɜ {�A?*Į;�w��靬N��Q=;���� ��5�۪&�$��=�4�u���_#��'�Y)d)~�m�T�%A��>���Xy�c�z��Ŋ���HM[�s%ů�GU���&x"�,H�һU��q(�R� ��F�I��l�ŗiL��hD��L&@_��#��A�L4�LflW�Q��<�xrn�Ey�,h^#������_�`5 虝���e�d�Y�0��càI)�Is�����+ ��*jSKv~?Lm�َ<4r�h��
+�9P�1��1# J�6�Ӕ�k�9|9ݚslƽ��2}�b�5hL���ɑ�hR�0ݔ���>�F��0�d�[LPC�P1��N4����'�+4�B�|F^̫����>ae ��"���siW@�.���R�����$�uً}����k�1\e���q�7ޟ��1����o&
+Gt:�6ͪz>�p�i�����l�*m��Ẻ3��o�H�Z���0�'A 4����o�%Q�n$�a�K[�Wc�� �c(�\�o>�+hjUL)��:�!)S��V�/Б�p�U*�#ի�1J���h�7�� "��.�WL�>d�֏?F�j~��F�[h�&��&zv�nQ?�� VKv�z�K�T��3�ZQO?���̬�k7~��e=���
+��3G�4�*m׽wn7��i�8-�%j]���_��JJ��� �C:�M �V�~R����˔��ms��j�#�Yw�On�`3�UP�U�uSߨ���-���B�x����1�Q<^;0�89�]LP;j����H�Xf,��q��D����/������d�#~�c�z�7KI ���_1���քN��ݶ����G8;���:�n�5|\�����0i ��s����[n�9����B�l������g9U� )�[�.c7�����^
+�BwA�핖�A���
+[l�[Ye2R2�ޔ�5>I�R���{��NJ����P�&�z�i�&��:X�X�`�
+h���sxG�[?V�~b�� h�"�Z�6!�W�P��Օ����ƒ��;q���FF0�y4~�%�%Τ�bx��9��w���\7��� �`��ց��~���wSՅ��Y��*�*�0�l�˛� ���ƹ��K�Ql����D�zָ� x�r�����cG�B�� ����"kvG��2)�P]�K&��F�k���e �iJ�"��u/�tv�+� �Ϋ��3� N�0O�<94IafӑŴ�LZ��bD��62����+�w��M�Dk*��i��sV�6Y��R���`�鏉3�'����Sj��$�
+T��'w�Bv��UQ�5<����D|�:��LRӤ��@E5~fK�CH��ò�Ow��g��fMd`{��^�g�^];�����A�-��/�#,�D�4�h���h\b�����-���ᶼ3>1\�̦ ��u����A��7M��o����!P�w-�u㯌sԚ)r=�ƥ z?s���A��#�4 H5�i��ޣ���Ӏ� zw�-��>��N��C4�Z#9���);xc�v[�8 �7`��
+C�.͈N�)%�����L�@{m�iE� �<�+���k��"�Kk�q�'��RNP,��Ғ,�W�-)�F����Z�S:�QtB}�֊�"���Q_l�2��C�^΋�s%�i�����$�Q>� ek'9��XÞP�L"��^��P����f_�ޗ��j�9+���@OTЋ�t</F��Ԗdͳ�1K��ж
+�}�����M0\��>r�dW+h�>t��O� 52qWЙ���¶Ʋ�� ��y$�Uؚ|��l�~մ������*P�������{����I���`�a�3�QG� ޷���$ᬻv�m.xD��01 دc�a?� )�3�Z�5�`�(�ڸ��J<N���m,����ݷX~ $EAޘ��O_���،�l64ݚ��HŽ0�͵��Ӽ�y�S?��i+!ck�nA��&[��3�RS�?+p�@�\ѻj ;��c-��'��h��ц�#�կ���ϒ�>�L�&�`(xQ���S���%o�6t���]Pqyy���^ɠL�r����7)?R�������1�����G��= �|��z1��lxd<E��y�xZ)�
+�}��1�{��"�d+0��Gb�A���8(�@�<;�� ���K2l�1C�C�~!*7�*1���>(��� ���Ϟ��zdM����
+�8"�ܪ�����+3�ᵂ�r$��a�ڿ9�#sؕ�^X�hZ8K�πs"���ڭ����t���8��z�߿��6Y��)��%yw2�STq< s� ��v�P\�лói���J-�
+��� �V�ydᆮ�7�����{u�/����Ps�bTq=悜��@<r�ә�fyˑ�;5ri6���
+ �"U�Z�9=�>�CP�T�v�N�i�}^P����r��Źp����|2o�EO��E|�
+b9r��ICj�l��:������>���t'/Ps,\�1ܝ|�K�� ޟ<@��Ҩ�Ӹ'����?��Fuϼ��,���7���a:�n�P4�2h���Q ���}��zmyw_%�c�W��A2KB?�� ����� D|{$���1���v���&�V�{��34`�_� ���a��v�0?��hP:rN���:^w�Sx8c����p`tb����s�5:��B #�+7�� 2M���<�'㱱4 Ցw�@��j��OC�6j�@6"P���哃�b��ǃ�N|�X"�G�|��hK���cP�9{s��-U��&W\�ç9�L��a�6k��⩽��3�O�,CriM�p�WC_�d��Ό�_����E/����2 E�T�H���m^=�]F8�i�'3�Z��5?/��a�߉}�����m���%�B��ns;���B)��6 }��0f��V�үg��W="��^��o��6��&M�#��T�34h���P����1O�N�{���� ��~%���\�x�~��0�����N����"k/��`��-��N�pA���rֶ���`U� ���1��h�H�7�ь`���̞9H�q�R�����v!����;pn��b�į�C�}iY���&�X��ˁ"\һ�$E�B�$��E�t��X���D�_̹|� �A��f��Oj)G]}��X �,�ι����-��G.���c���W�� "p��Ҙ�}_��F�-4�>�^�7��)HT=
+����P�\J��m�2�M��_��-�P��ܢk��|;�J�
+�ry �B/>����*�;q��Wj�|[�~C2�g�/xx�4�X"8?��;�j*��y�N���
+�Jq�ڇ��g�u�1�k��#�xŌ�Akm�n�Ա?֮�j��:�c'���,�P�����y�Y z7DX������ [�j�􄙱��b>'#�@�R�*�c������(I���P��utH�{ID��i�����345)+vF�y����`�;�Z ��ڕ�|�wԂ` �������Q ;[�t��5���F�s$��V�5�ʼ\'�ʎ�M���!e.e���sH�a@�s��yr
+�U�2a�"�p��Ķ�����3�y�� �q�9KY1�+(�N޹����� �đѦEzX������l0T��e�}���� uQ>���� � $�� "`©�����frOtNZn��ţ��J��k&����q��j_�[� h����:f��4����>,6~t�Џ�)�w�%��[7l���,$���r�*q,���>��O"����}�b�}�3u�����@_j~oع�^���
+K%��|`�:c�i�^��1�2�2���S"4�;�&<*�Xw�� �y�?��m�+��M��}��O�|���I�5Ȋk�4�o�
+���tc��C�3H��Om�0\��0��@__2�4'�'WT�Vv�+ܹb���Z j����T�ўԟEݺ��1X�:Wn(Y𠦺3 B�o��ҋd�F1m�Bz?_ ��-��L+��������tJ'�q���4�$��B������� b�B ��K�%��/��j�t�u��\!%�NG5�^`�H�D=����(l�3�u>�N���F�����0���-�x�Tk��r�Ne�h���fv&�g�0��_��<˴վ�D�ꫩ��H�&�|���b�bI:*ٛR������(�i{A� ������ĩ�(� )���+�H�;pS����~qu�a�5g���0�����F�u�E��ǨMЋb�A #�+8�?_��#\�d{��7��N&Q��Z��i\��~�t|-ۅͱ�ÔZ��/�I�97�O�z6��x��X=j�5�n�\_`$m���s��֕W]k�51��px���^�(-���;Y�t�uX��7M��9'zm��J[�+ΐ����=*�x�d�%������F�� {e���݄���fl��!�����F)ꭰ��}-6�}��C�x� �y=N��MΪ�����x�nx��Y�K��d���"��bW�o
+ �(bw����Z�sx�T\� ��dk G�|�p��K}��@��Z~�����d>��I�
+){}�W*ju�f �=��r���NP���ƥam��J�>�U1&C���{�<hh"1':k��s� 0 H��0�ge�z�xS� n��Gl ��\�6�_����t�x�ᵰ<��v7�/��1^����
+.���h�a����.�'t K�O)+^�r��� ����྿i^�C�H��js����$�����2GN�������f�Af�����]$#`a��/��-��]фdϤN�/��gs��m���6���4u�~&A�� 6G� ��Y��c@V��A�'�����[� �P�0U�l����C�X/M*�՗�Ԡ$��l䁼�@�ʆ7���f6��ĸ��Cy��l �$�S��'�����W��ti!E�B��V��}�����ۈE�෻a\�?��sUL��-C�?Ie9/?�I��b��g@��Y��0ډ�Ea,o6!�F#��9Oٜ�l�v{�*���B�1�fM�/U�1A4����չ�
+6ʽ ��a���|M�{��]*c��J�\�,�Z��M�]��$��ۉ�j�,ǩ�LRR�b�gɹ�y�5�
+�m��v4�]51g==̼U�'I�3����������q\\�� s-� �v��
+�V���Jrq�p�0�?;�������>��}����2��/q�A����=�$�Y"-��9��>(�-8��rM"�S��{E�C� ��.n�zw��I�.H)P���e, h�Rm�G����J��3����t#��(T2�~xxC��L�'������rO�ԋ��,^��#�0Xv��'�?��%��I��(�:�x�(a-s� T�/D��5��r��ܢa=�%q�n��;(�/�dT`8m�.X�)=��)?.�Ə����汸�rвZ�{�s��dI�!�W�E6��,�5����Z��GNC룱|4"��A��{%7���1�x��3l�s@��j�jY���Nj!<��"��4�Ko�a��K��4Šw.M� u��`�v��-�͚D(R�;��� �r��:�H�?�M���m[޹�'�؃�� ���㘑�.�M~�F�Y&�c�1��ם��Q����[�:�o��@�%���Hq�$�3?��]Nl����w�PW�uŷ)�%�/�ˤ�u�v2�a�Q�7b��+�]�]E��D(y�N��_��1�if����F�;��͙���B#� G�r-�D���0����O���
+�N�u��5�;&*T`��1On��7�O�!bu/�3�-s4op����kb L��^��v��ݢ�[�5���=�jc�C�L�����$�?:�#�7P�S��fR�6K��A��WS&����R)��J@� R�I������Ya��g<K>&>��t$ͥ�gr��l dԭ�b�������]V��x��-����ƙ�U}~�H��9��? p�2 ��fN$o>;�B�w<@�u��܎]_��a&9��dd��������*}�Mo"�m�Q:�]_�yn�u����Q��Nm�a!���� ?nuL�R#p��x��M��ԅ��*ܨ3;1�(@ ���Xa�‰dD�]��ysNN�%�-C�K�|��y�̭b_V��)O��v�>uX��`�-��?�+'�B���CzK�'P��{";�<��`�t_C��0v�3dz�4�r��.��0�K���� �(������y�șij����Q�贓��V�O� ���"����#S�~��wo��������$��\�2���Ҩ�/i)���T��xP���Ф ��� �E� S�V}����D��P�B��s+w�Uj)r&V"�������QC�h�Y=�� 6�&�p����ṋz�W�o���8��>7q�O�-����� �Zޜ�/u�$�Z�����������'h�G�v�Zys<8�I��pJr���)i/���fV.�S�D�zeiSc��M�mx�!X��s�b�'�cV#�Q���+t�K�KnX�>&�Q"���� d$�, �� m�ou��o�eC�8���{��8� =�90l�Fd�b��
+'T=�'E�������'-rX���ݬ�#����PA%��А���_�D��2��m
+ m8�g�G_�,��7b Y�}��!s�� ��g��%��%u�՚�]i�&R��jCޱ�lH",_ݨ�Y�pegY�ZN}������� �x3�O9) ��4�ڼF��H_���.A]���*�a�iN.�d3�<7J4�Ux�$�ip�w�C����Fh1|���T����&߮���~q3�k�%k�S��hPoX�a27�T��t�}��yE��.@U[�2R�3�8��,2�܍�#nqh&ND�����k�I[97�*ǔ�v�[�V�zk�0�ƇC�w\����p� �C��0��)�g�<dP�< sd0x�MP��pj1e'���I��,��=�g�f]���?�X�#����W���%����2��ׁCs���Nb�r�5� �!(����E���ZJ�^'�
+��Qo��DIRKO��{�mS�|$(n�=������T�n�A��8u�o�s31P���w,�S� Z�-�����݇��&�Ih��AUV^�T��L�~|�X�� (�8ƤF˗����H�Äw ������������r�С�sG��> ���`(����8;K;/��ɿ�1�7�<�c�؋J���� M��E+t�2��(^=O5�I�����>$����`*3ҹh4�;ǫ��������$�`~�ˤr�l��dS/�=qY�Q�ڃ�T��R�S`��U���%.H�du�Ͷ<5���.<&o"��S�&�S��8��^���.gA������{&r'i��+Ӓ�T��o�?E��i�:�I�t�x1�6Jے,qЍ9W������m�r�a�Cu�R/��~ +���%�8�,�Ibk����زM��u�Sc��K�Y�kRCG.�����v�~K�._�8��Ż��M��� ���Sb����Ų?I�+�C�K �b�Ӊ�,�u�G�*��Ps�n��K¶郕1)���^�ة�y��w�0 ��<mx���a�ฐY7�.�m��Z�%x^���w,���3a�G�[�$�B�XBu�pn�_�j𥍌�Q�<@�(��o���ʮW+����w�$t ?fn;��Y��X�-�!Rln�7dO��]��xE�e�(��P)�
+3�ᲢtL��S�������*Q�%;6
+FsjXQ��&��>%'��RV����Z����%�3�F�Qp�
+ ΗS��t�M���"�).����VkǍy�xL}����(x��od�R�L�\Qk�φl�4w5��%��W�3s=&;�2��ֶ]��ѳ"?��oS\ �0��Q�&��$8۸�!De:���+� @a��
+\u�� t�H�-А��=�`�8����D B5��\ �F#x�A��ѕ+�����&Cg�����������_�3���Zq:z�/���W�{��R������3@;#�_�@p��q�3�(�=bXJՐ�$K�}�o+��yk0ڽ�u�� ��)��1�1x�h�Ƈ���W�N`��# H��Dy�W��z,�z�j �A ��o͢E��#xR)���Z��B��0��et�^S:`Xo"�A�;Jޕ��:ټs���j�e)��!��N�����\�|Y~�i�m�T��t����Z'��Zv�@v
+j!���N����quc�����4.?N!;LQS~���`���WE_�;a��_� ��b�Ԑ��1�Y.zd^�-|/���P���M�PE�\�찹jAW����b}�al��W���rr���X~��[��H-�܁v��n�����
+�KNj����H\�j��#*1��3��[Z����8x7�������8���A|���uSs��� �5[���O+ŷ��b[JY����[O���(�>�r5db�U���P�<�;��Z� q�!(H�jcMJȂMt�i���4�4���E��0h��K�� �o �@~KbDK�������1A],����&���|�r]�wZ�c���7Qv������~Q ' #�l�з�n(�'�~�]��|$74���,3z�`!�b�TD� ;���!qUyf��O pb4����*��xO��PG� �4��q~�(y֋�W�v%2okg"W$k%�J���ʑ�?� ��͊���s��U��I�]�#�p� IPa�1W&f��9Q{����U����zW�YD
+���h��$2���3�R#�����l���s�w��;ٖ�2�� �R�;^�ဝ���8�d4����JEXEGʋiq�F�a�d�n�@�]��Tmr� ���^��+Ԛ��\��d�5 Z����98,$��^S������;�e��{EK�p��<|�m��7kG=��p\��,�L�v��ɧ��%N�x�P���+~2��[<���뿫��v�9 ��Kd�$N:�o�VU���T����?�����\Q<Ua߃+X�DK[����N���D�F������42�1>��}|�Nj����w�N��GQ��L�2Q����d|���i y�g�k�n��Q��ٹ��4�e/��8�ݕP �O��(��R10�t�x^D��Y�Ib����
+���_-5`;���F<�<�]
+����VN�����-_41\F��[K�L
+���15�a���~�4,��䱤�ttoh��MNo ��i��D��R�6��+�H�ᰕ/ ��k,�0�O�%2�F�g�����?�����E2l:-�l�#����i�8�,�y���cƂ[��|?�ô
+����V�-��Q�a��(}�J$@��U��L�U�K�N��j�_���j�i40�{��� 2���o����.[5
+������S�����m��� �S,y+��ƇMq>8B�0�\�0� Ʉ��9:ܲF
+( �a�<ԏ��q�Z]�;쒢��F�|So�
+ 7_Zi� l� y8�������K���[�W��B`]�9?>1��v���+�q�ߋ�He��
+�]����h�FӉ�!�֊"��<KzI�F��)�� �Z�u�`t���7��H.�-�kGy�+����Q9��0�O� g�~�ob�f���i
+�|�K`�����u]�ל 8�S:Rx�.���H�\�q%��p�zɴ�0�g{U����]U�?���# �9��WM��"����cs�1�Ič�_Y;dx-W�&���8���2�I3�H �O����h��Q`w����j��}Dy� �����]��n��������������*.��o�H�#�=�5��� �s�F_}��n��\8'�� ����C!��Ӹ��������w�x�~�t.yW@���;
+���eZ�C��:��w4�(��i�_�t�M�a?vm|��(c ��@��c
+�a��Ǵ���zT�nzy�̦݃*��'v����U{>@��F��>d,���A'�w��bѼr �TZ3����<+���":�����@*id5k�R�� �XT]�4yTbJ�2`-���� ���I��c�����3����O��iPYoމ�D�z����@N �iA����~Yt`+�b�+U;����������o��1��+`�������:̞�٥?D��Wσt�A��m���ߐv�s��rĴ���J�:�R�9 �-c6��F��)�pnE�M���+�58
+\e�z"�g �bܟe�#��Ϥ7[�}’���*R=O�h��r��ڊ
+�����Wr4��}�E-ޜ��w�n�(!k��y�7�0�����'%�7o`i�(ƛC��&B�4�IT�}ڍ$d�K�z�3��{<p- )�, ֭H���J�p<1�
+K&=^�~�N��m�������Hp��:R��-y��;�њF�6_�WU X}3<Y`0�V��P�ibS�e_�����!b��^��̷3~ &dx�E�:^�\ѕ��>A7�*� K�5��7Ģ�N��nnU��{�i��"� �mQOA���5݈S�uZ�P�C2���S�-D�S���9���"�����
+�X+�e���<�=���
+ �����ݵ����G[Ek�K�m�zzAw����$�'7������+�2����k���&�6e�q
+����t鱅Pu�Mt��7t1@�6�a"��5��3Ҋ����$��/+����UN����-7���G��Q�^���*�&>�#���M&����s�&Bp՟��-����L�<�C0��8%����r:����J����zY4e��r.������a�Rp��b�{[��"��-5��Fƃ�!¡n�cS�v��1Ī��8�iVDJmR2�~%�3��_{&X��T�9��D����ue�)�U�Ю����c��[�R��5� `4��?�q�����l��W�S��?:��z0�O��z;�x��WV�!�`4����fg�[�+�F��F�h��aȼ��-����Ì�0c����9��$E��J��6� /0�d�FI����\v�t�����dn� �=T)��H"�k��xt�p��k�NG��JF3��/���'������L�u 3��)�j��Oa��*3˭#�Z�r� jOo!Jr�|���Q(�a�����.D����VdO��N�w�<�}PϹ��HZ�+T�y- ��JJ6}�R*� �)=ڼ�D�N0Yۗ�ϣ)�ʹ���b \Q�S��E�ɿ��>���?���MW���
+�c����%�-��Z ��*Y������ �5S� a����Vn�V��):b]��by�M�y+9Št"�,��// L�nlIG��M���ă�}6
+>�`MWN+��_����Pd�ȵa�|��y�.�6��dIe�{r��u�90�/�6�� -7e��)�o��*�z y��˜a���ULN.�K�Ù쉚��u�3�ة�����:�L��*|K�#��+����8���|��S�uH��)�?3�ٜC[��]I�g1M?��m*R@��!4�p.�sw���9�����n�׋V%��ヲ+�h^�t�_���G�d�X0q/S����0�� ��
+��f�\O7�=6-�N:�p��) j*���c�=ٕ;�vU$�|�&�4�V���(n{���i�6� )�o�B�MR_��X�ӱZ�ݏP7T�Ȁ}�d������G���I�[1�[���s�rΡ�OWE� �)4lz����P��
+�Ky�|�;��� ��l ^7~���[e� ��]%�ܕ�;��X��}���5m�Ї�{� Щ'y�j{3�����B�ͱB��J^������ �J�Je9d�:s�qp�}WTs��j g���0�bw%��2a �7�Ƌ���������;;I��7���ڱ���ok�h8z����6O�-0�ĮM!�ST,c�!P��̍ a ��������c��I����UҞ�$� P�,��A����=�-�Q������PZu8��G�#�xR�)��%_d�vwq �n2����9�B,ܯ��amu���է \��#F�ג,�g��>YwuQD�v��hTw��/��vE׉Q;1'j9F�TDa9�(i;���Q��V��A�c��Nn�6�1�Z�p� ��|�3�F�?PC��F��ȁ:�i�et�D���%id��AY��Ax^�
+L�o<���W�a�ԇ�����n�����#�A0�96�^�R�{�D�! S�8�'�7�Z��xpS�0��c���u������8T2�?�?����j��������DMO��cq�p�'�>���G�5�B��H��:%�9l�_iЭ�'?��V����Vpxg�{����;>
+�g�s��m�y6�$��M5"o/#eT|�$�����H��<���� ��4o���=T��� w��I$�K��!� ������o�hڭ(�](���� J��b�t�
+�I��������!}���{��Δ?Bû���?d.�� |W�ԬYM׮u.���uh�_����L`n�k� IW��F�1���b�T��n/g�[@�Z`�oʶ0��^ӗ�����>> � �|V���B�؍Hk�2�S�ք|�$a[��I�R���D�SCen���ѫf*CZ��:W
+�e�"���XT���MY�9p�v9������X��*C � �ౄ}o|������@澜����(2e�=���(J)#Ӊ������v�0We���?r Tv��s�a$y�.kW���\%�އ5��{�բ�y�rX<���͢�-���^Q6���4z�����1�gNU��6+6����Ԋ�;f�`�`���E����4k���#O��QvL���&7�X���
+� xt����,l�m2#� :��]�[T=��ܱ��S��$U���JD�� ��CP�����d� �>?)���hc"һ����ޑ,<^������世t��<E�q$_X|I��BdhŶ)��ѱ��m���3��SRq�9,��V.JDAZyΠ��%�,��V� �C]��w�d����8��6dX]�(N��
+w�h7]��C�l0Ҹ�+�����G.�i ɉ�K��(���%��qf��:� ��A������XR���=|u��5�
+l!iߛ=T{�V�����(�(�w?I�8�z_��T��s��{� 63r�ĶĘ�U>\�vb�0DZ�� p���4۫a��Đ�t��@>�J,�'�ɷP(�C'as�'�?�K
+z)�+�D��$9��m����?�9
+endstream
+endobj
+856 0 obj
+<< /Filter /FlateDecode /Length1 1366 /Length2 27501 /Length3 0 /Length 28461 >>
+stream
+xڌ�PeͲ5���8h����������޸��;�C���4�2��{�{�����8���\��Y�֎(R"eZA;#����3-#@XVH� ���L���KJ�b�l ���T ��dag��; ���D ���d�lR.�Ff##;�����v�\CW �,@���K*lg��haf��w��zPS99�i��:Z�d �́6w46�(�[�=�W
+
+sgg{.zz777:C':;G3>J����9@ �tt��i gh�wgt��s �ە�L�� ���k c����[�#���eI��=���`�h�9#���O�?�,l�lhllgcoh�aak0����d�ݝi��&� ������ZX���rC���"��o��i������ى�������I���EmM��ll���N���'b�4�{�������������&��4a�bO�jk����� �lf@g+; ������^���/'�?��x���L�6��0����r2t�]�>^�w��^�22L,��F@3 [����� 4�����-�� ��`����o��ebgk��?�͗^YUCKQ�����OH���E�� �ebe��W6v;+3���Q0��O �+ikj��w���*v�(�#J���%g���@���\��������7�����������,H����_n���nC k��������d���������-Z!;k���'�l�W��f��}�Nb�@ gc�s��v�4fma T�s����ed`�?|�el��������r���o)jklg���X������G�w�
+�b��D���( ����s��ۜ�����y2�/;���m����W\���ߍ�k�/%��@c��%;c�`ˆ��:A\7��߼��i��^���.��P)��Y�ێ��)c���k�^��MPaI��o��� J����+3���E炍C�0x�*G��jV`���R�y.�
+h�n����*�'C��j٤��+�hcT�uJH���!�i�P�ݑ�Qs����a}.b����v�b_=7�T����`ka�=�NΒy ��J}_�*+�h�_X,����yp{82Soҁ�֙raC'�3���;�\6t�f�C\\iU���50e�@�,�k��r������ْ��n ��P��2f��#���M�:�+�����n�!cT�>�2�
+��ZF�F�E�� ��9i��s􇫼t†�,ӎ=���ճ�J����� �\i�:܋��H��/D5�܍�P�5����?+|�M,������(�a@�{ё�h���G})Ә���-h��zrYX���ԇ�?��ak��2��M�/�[�%���G�t:�I�ҟ�F�5!�T�[�U�˨s,�jg'YJl�s �������� �p�����Q��I�z��&(m���A�j�4qX��{DG6G��[��HDU���o��G�{����}�J�p��z�ᚁv� <���mI�ld爪-���1Npm,���N�TK�Uё���x*E��67.2)ŌZ2�Bu�H�:t򰡝fS� ��AV��xG�z���r��ꇿ~� ��ݸ�t����>��|s�5�-�8p��b58���f>����CNf5Gst�6��ɸ��y%mPɣ��#C����Rn8�
+6E��X=o� �v /+諜,�R����ez��꒞9����8m�/2εq��G�����r�˯����t�o���\�����N{R�|�ؙ7�I���YE޲u؃L�["�d��3����L �H.���VO�ň� q�^��f�iHE��S��p�38�5�j�� � ��0��-�c����) =��~����q������hFϨ�k��9����x ��� /_�x7[St~�3�c>$�j\Wܬ�=;�$��*��|�������%����w����O�5l��B�2y>�A���=� 4i���8�cF��z>P�-�6��_�zd������fT��0� Ưd1� 漋/�2n�"4Z�
+2�u�5��������"a7�}�9�g�8�+�[p�@��uw~|�a$=1�9��᫽�`F�4$A'�)�N}cڏ"NG���.:�|,������ΐZB)�� 4-8��c򻲷���]_VI���_c:)�I����� "؉�;�pWt��U���m?���O)��`�3_��<��.��P2�AS|�O�P� 2H�����}?�pr9$G�&���ߝU�֔��_�̧j��mO ���N=�%��>�hHeV����&��;[���D��,|�T&�0ai#�[��&�|@M.�L�Mc��6��Oz\z��0'�@k]�î"��$c���D�[I�tPۨ�񞼦��H'݂d��b�
+_G�� l RM�R6���)Lo��/�18����;���.I�����y?*�A��)"*�;^�wl�-x�� �z�U��M�s��hЂ���C�-era���_C��2�
+����#�-��)���gr#΃�V�͛�fx��!}��^�<��ݚ�>�3�b�bO��FM��*��a=�O���e���B�Eh^<�晳�d��b���M_���!L� ��|6�?uc:\�Ϛ�� V���v� �q ��o�]��5ݼ(���ǀc�`�(E�v�����߿杴؟mX�&��UHv/�P�u`Z����:Ә����>��x�Ɣ3�C'�&���M��L|b)O!#ϑ�����`����7�wmw �� ��6G��2��$\gŐ��Y�+-�y��\��9�5�����F ���*'�L%�go^SϚ�T�����G?!eQ��o.�i��j223�x�~�a�QN�Y[ �M����o�+���l~�w5rp�̸͞��S'�$����=ۃ���/��xn�k� ����[x�!����!�ϸ���Q��PV�!���d������wư��KF �f8� ��+S�:�$ݴ/Wߚ u1�yR+t�8]�/"��n��݃)@�g8H�
+-�x�Ī;���xj�z�4���F�z̾�ݍ8pj���� �����v���o���H���i���hD�R*͎.�G���w�A0X?`6�� �2�YȰ`�ä�ށp��E�H�*��U��ξ1 �I��#���ȡ�y�N�1���#<�� �*ǖ��Qx��A̔�oa�_l��_� ��Yl:sčx�ȼ�%?�0-�h�$
+�eq�~�i3��qrΐ� S0�P��}�Z�ˈ�0;�KQ��&$g%r ���bʟ֩��#��6믡�e8.Q '_�����h��D/�������u1�9OR��Ԥ\Q�m�{���A�9>�t�1�l�ۧ��\�5O, ���uʣ���E'�v��X5��a㵂�?^۩�g.'?j��碎� ��Ǥ�#f�4՟E�:����n��6_@(���Ϭ ��n_���q�ҺG �X�kyw��ߩ�K�]�kj i6s�=|�O&��3b����̯����j4�r��fɭ;��Q�d����|/$��H�m;nُ@J�Q >��R#�W�;���
+�P���B�����97�j�J��S��F�Ť�W�]������>��A���}k+N)��ZF<�hx���0���a���tw��"�Ǎ��$e�f��엣)�.�7j�ㄒC���P�}COښ[�~��˿!����kR+��>�����ς�c����gH��������������4]��u�|P-�^P�U��5W��E�֢[F���n{�>�b5 ��D3g��1��G��}�E�O�¹��9n�n(�g�boꗌ�Gzˑ��;"t�=[�0ۤ����M�z,�^;�*/f���� �3'0�%=�|ԔS_�&���CℿG]bBI���)��x����>��x�WI�u*�c՟����m̗4��`\Y��+���"�|t�&]�� ;!B�Vq@���PlR�8�Oo[l�u˄���UJ&�����k0)h�E�7�L�
+j��������͢{/F����/~zyi��xۭϰ9/ˋk�u��N8��0k5S+� u
+,���uL�"�ݤ�3�^�wݩ�]!e�KRoCIp���At,FVP��n�m%��z};� K��D�2��~ @q]�8�(r�R���:�����:���b4�� Td86�� ��(��*���9�wpk;��.b'��ϥ���ժn�� �Q�J��S�F!$�Hr��?d�ܦn���������V��$1��l���B��@W c��p��o��ȷ��`~a;�מ��o�![G��ȼ��,�C�\a����/$�M}в�"��L�c�p�0S^��ѷ�s"������^<�p���q+��е g4�����AP��v��V���_=0H� u+��٭JWc�Q
+� %���*8��EF`���O�d�Sʫ����>=�kЕ� ��E�G��Э=B��ҳE��#�(] ,8e�!fD�ҵ�xc�&چ��|q��^�_C�/?�<���Yb�5�|�8R�����I|�6I��1<b�K��-�Y;#�ڞ�,�5���i"Q�'�2���G�Ė
+=� ‚���l�5���:mFܛ,��ӒR�jA�)b}�� �iќ�T��{��O�r�ު��ˎzV�HĘA@�Ow�i�L��&�/�wN� U����{~���z=�~x�.�ݝ @%o&<�O�����f�ID( 5�+H}�ԣ>p;�Bj��ٲN_�̢�v�4�u��0�B���N'̰~П�B�I������D����ѷ� ���m{��&���O�6��2��{-AW`���:�EcY� Q��\&��4嗋��&����r�Z����Q�Z���ѧÆr�&�ɩ�;B��bf��O�o�I�9MY�t��D�5��e,�S;��ne�G^b
+�4�T��A����W� �n�Ϸ��$��7���b���*�w/�t���H
+�����B���Ž�����"%�L`��1~ C��D��� �����j���~J��'G�س 6lL V��k�B�Jڰ�ߡ���3 �.`��j�N7 'W��D��p�5�0t:� �����ۋ�'�"�ѩ��5\�K���;K}dO70왤;����
+��'7`���Y�x�:ŃX0CC��]i�1+����F��$/�0<�r�}��C꛹��:� ��ZF�y�3ĸ^�m�.�PeA`ߞ���r����'\�Jaf��?O��X�)��1��j�a���y��5ʬ*�jt�b4��m)`�������,c����L��S��M�:��0�Ȕ�5���SP��o
+��P�9�P�:��7%Zۙ~GTԇ ��� ��Ĉ�?-��g��7d��&��(��b]�U;�ݑ�q��W��^9H�Il�%�Q%P�U&yY���yK���@4L�]^3]��͕M!i~_�T��.�2���0�+a0;ꮈ�� u�+�|y6�!������Q,
+��S9�뭓�w�'���ywG��ҼȾހ.Ї��wۥ�:�~��v�=ݖ+R%�B�z�N@9��bMb{ ������Ө/�׬9񇍚�QC�+4dBf�����9�q�Aɱ��kt�����L���������=��ҍ�O�G0����l"�]4�©UN�F;wۯ��pw�I՟��ɋ�b�k�aI��I1��:<Ϧ$ڇ��e0
+P��^����a(�u�)��ޗ\~j���7B~�*/�_ςbVT(�bJ�9�u�
+;o�\�c<J��� ~�d���5~�z�Z�#�ĦF%&߬�� �3���ҩ�f�<
+)g��Vܛqr�{�=�s��$R �$K�� '���Ug �q����=�����֠��NMǚ!Bwr<���o+�\Y�,.��[rw������*%��c(d���-��{Ž� �"l�8��s��D�n��P��I%j K1��e��`�-����R38!�9%�bEF=IO<� �V@����h@���A6����U �4�9M���{Fa�,�Zאj��=| �>MYz��V�q-T33s�6�I>Q���%�=�˃����u����CPeA��6�?�y����d, �B����w��u�o�������4��ߙ4�6�T������G�N�<��3ƭ Y��~IQ%2�}DV�u �GȩV��Gjh���äy��'G��� C�%����!#D�؜'{T՘+D�0�Ev���������e����n�^�1/zi�8�O�G�����)�'�j_���3��vܦCS@��s!d>��"�7�K%Y��.�B�;�6���72=b�߅u~���Ʉ���D2���;&�]�9��W�+�Zs�Q���?V�~Ž����fF[��1
+�xsF�o4&��b^A<�G� ���S}mS�e����:u��_F+1�Z�� �����kf�-Ǎ69O��j��
+� �(iƑ��V9�5ϕ�5;
+����o�[�d0�s0��1�|y ҄�-���:�I ��zޓ��i�E��d�M@��$��Q���.P|&�1ʘ����(�9a�@���KC��c-܉�^�L�P[v�ʑ^�I����~d�9(�o�D� �f���X���"��n p�>�d��ݵ2R��1�} �{U��V���0����~l�\��"&m ɤ�!l~Cr[���E� ���3/o�!�s�#h=Q�</�{�~�<�����p������YL�X�Z�8��n�P���ؘ�F�;\w��r`�����M����IP����_6��h6���k�`�/�7蕍竅%�Ԑ�w�Z�Bd+�Q˽l^ ������6E&��늉�����ws�Xk&N��{N����m^*I yP�-s�k��hص� e��� R2��b���*sQ�P��3\�t���l�n�`�|R�&��s�9mc�Q�䭶��1u�FhX���J�Yy6x#d,KT� �{�f�����/*`�y4,)bƍF�S��V�%�hn��6��P������|�=�q�`K';1���W6>��uuŴ�2�Xa5 B:LWG�������zd(��Ώ�b�A��vh���[��䃮zv�*a�'HڑT�m^�� 8/ܲ�Z���H*:1*2��1�b9�Ы��^T��vY�I�n����O��7�e_1����!zC!���ll{�)r`�Γ�I�N��)\���h� E-�[���X�Q��C7�f�-.
+5��g|�>Y� �j�j]Y�c[m���5'�E�Z�K����od�ԛ}�&gP����=�ی��@�y��9CV��g�7���ڭ��0x�];$ �m��1$�D�\S�ɷo�JQ�GlOS�k=�z����K�R3}iθ��GuLb-�Ώ�qq���F����H� ����x� �e�?8�X������Ŷ�{�g��Z�|���̒n�i*�N�R�4�TB韯b?9���8q�㰑�>�Z�^j,/ߚ�H�ܶ�Y�=��ˋ�������"�s��А����i9�j:�&�*_�D�V�JH�z��F�9�& �L�]Q�RKũ��u.��!�fZc/���u���U�ݝ݋�QT����01�]{�.�`4� !y�؋�GT�,˱��z��x.�/�#���\�!��[bؙV�h�g/�7�:wwi��D=D�%n�W��hCl�}&b�^)w\;�,�x-��S[�]$1��)MH��x�h 3���w��@{���#�m_ז-�S�ɼ��xB���������b�e�d���^�'������0!aG)Y��*ʩ��@:���7mcɷP�*���� ϓ�U�w�e�藳"�LZ/X���>���C��ɚ~˝F��(�v�1L�r11W�.�S4x��r4�U�_�%F X����^4\z���޷��C��E�t�����<)�RiW�Z�9�Z���504�n+4Qˌ���Lw�9�r��p�G���q}}��O$��O�
+Ee��#4����ˢ��%�������0�P>�v��<$���pZ.&��I��z��0G����n ���bĝP��Ok�(�g2�?|���T�m���Y�?vV����̶5\��e�ݠ� ��gr��+ǧ��B�D�����y�`ԁ�Οm[��T��E� P�n
+������l�9h���y�Q�E�ľn��t��3�=�#�7bFuD3r��̴ ��9�y�&�X틸�/p��!(�RR������Y*�s%�;���W�ޖ�ٽ�`d^wr ռ�lK�[1~?�'��� ����R�K�?��2lB��yi���o�th�f �0� ʭ�� ��y6�)mM:Ε{ͮM�"…Lӻ�c���N���A�ۀ�n�%9H�D����Nvʥ~H�H� g��jA����n��٤-{` ��q����!3MT���6PU@��VY4�>�z��H��y�F�s׻�S��b3—�_%����Ɏ�ė@���
+ڮ&��ԉO�E�Iۭ6�o�s�\�x❑�|�W*%��_ى�JG�n�e�/+�w$�+]�2���^���T{j�y�� �"���1>|��V��2E2��l��F>��z#����nؐ7_a�]#����M^Y��!P��M�ؾ~�1"p��rd�8�'h���,�d��3oC�{�9�׎��JήH`1�t{W������q4� ���/z�&B���\�|�
+�I6�97�G����\2j��s�R���vdD�]��.����B",%k�(8�#W�A,鼇ͽeS(ȤD������b��-��g�p�t#ͣ|2��HU����>�� ����چF�$#T��Ӂ����WlG��'�*msE��LyO����2yN"��J*�X�6�[�цjJH����Qw껦�����rAO5�-N>�H:C�YU�ż�!R�v�ۃ�����~�\���R+-��҂�ϒ�Yx�2����H��N��J��ci�o����ҵ)A*m��R
+���us�ʨ�>�؟�6 �ޯ��-�`�x��9<W ��/�����V›bh[ak �D��A�������h���"�E |�+04�U[�:�H�_+��P���>N�MA��œ|E��f�ה�W��G�� ��dFY�읯=�E�D_�i�jw�]�3W�{PB�dk̎���探� �Kn}�A~�{!�?t�(<7��k�QL��R,/�����T�� e�֊�>2~�&��P�E���ͼA��YG2iAh�"�J�ڧI��a�Ŀⱔ�2�&'� �e^�N�
+"<��,�[����7l*�#)�J>4Ɔ� �nТZv���{�/C��(�л��3�uD��;���\��.�&��dI@�5IF󛄖(�-%7�:���(��������T�:L��d�QQ �=��F�~�`6N1%� �N�������Fc��sŞ��kn:#�����"ٲ�5�g�L+�(�@�?Nx�*^�Pyx�p�P�arJ�}���5k`���� ���@3�Y�Q���'p$�� a�Q�Qc�˷�,�C'iq-�`طm�����p��1�f�˛�F�bT��>T�:������d�O�^?A�"�f�؛�Mc�M��]��a��i&��ͤAx5| p��H�� Swb���o��ي��> ܏{�葨���DgE4�=�l�0����4$v]�Ac?=�j �D���o�Og8h������w7�ԉs0��p�kgy�a|R��.m};�˅�dצ�P��"�Z`�rTr5Ε1�����3j��w� �1�#q�">� 4w3�,w ���t, �.���<>�ӗ=�!��̹�� ����m{q����i��c��s�am��%ż� N2��X) hm����.�
+��K"�?�C��`6��� ��ś�����������_:vЊ��H9* �D���6���,[9M�8���v���90��Hq��F�� �N���忺hє���)�ɬ��K��:���3�_�+��V�I�}�K�e�*�_��W/`�,1� ��1���S_�$�5�:;/��u󤐃��gFM�z6eܿh���(H�D��Bd��3��A=��1���4��s��ˆUbV0�5��?��۞�����]wq/�3A�c�!�'e>N����@i�*��nkYvY�.�?�}ϗ����v ����٣�5:ir�xR�M$�}�3�lѶU@Tݐ��F�JF��u�N�e[�
+2�]&_�)K�8d-ƅ_Vo'�t ��B�^������8�� mOM��@I�� Cfo,�X�" %.�u���nC��E�y�I@��v�@)v� BAԥr9�-o��-p�V"}Q
+uw�}�`�A���m|9�ή�i�a�K^�m��j %��L^5�����4�gi2����p�������;�^n�=�Xf�.��*����$�6���0���J��#"�D9���-)By���g�Y20v��> �@��Ρeˣt��|��9~ mJ\���S#H]�b�=;+�, �b�� -�$�ǒic绊;P�#I�)�+È���o�–��&���z4�Nf�E}��d8�� nΓ��X��O��7��f�����"���)�,�3���)X�n̮�J��� g��j�3JgI���q��jm�G�-�(O��N�)�+:�Q(b}7�)�yKĸn�j?+�#^5��לkm�4����FNb��"�\�J�� �q�SX�H���C(O:1[fG�ey�.kz��x�v�+�;_kh�(y�`$�%;+��B�d+B�oj��� ���һ @��"��m�����*-P�������lV��x+:S��k�aF�(Q6�8�Z��{ɨ�I�9��jD��Rll��4�F� K�яw �k�M1+>��<�˵ J�@��*��|�Ξ����[�e��s%7�t�_��U��ڎ|�H��@{ϱQ�p�� ��Z�KWT�B�%���]�� M]�F��5�>����jg���Ⱥ����E,��)��&����Al?�W���R��L�۟V���I�Tm[*OI@p*�Oط���K�i��%�W"�ݘL���,r
+=$����5�vʈ���ş��)��ğU��C2Oiq]��]�e.L����\��6r
+寑����W�"P�rs�j�����5�^E x%;`v���&xcpR`� �8�1���t��I�ۑS�C�у�X�J�<�w��=dJZ��lr"�*�OF���k�lĺjأ;�
+
+d����v�ҏ�c�ߖ �`=Kl�#��7#�!tv�:�H��C�?��g:yA�&�+0�TNj�`����O��yy����V-�ޒ���4z��z{j&���<�NG��mC`6a�{�:64x����k&=<���I=������/��� $�<*gL�ܾ�#��G�/<K��bWȏp��� _���Dw�e� eI�������?_��Y�p����=V�vE�a��8t����3��SO7�+��w>��2�R�[P^'b[�>:8f�ߕ��,W9Z������ؕ�} �F��ҫө�T���Qg�^�5(.���cG���K �����a�����B�N�ʇ�L�>�i�aI\
+�G�6��iC�҅B��ͯc�6���r"����Yi�걇܆�_ȑL^�{;��Ʃ�Ò�9��_��j2�4��֡�ysX����r�𬯛1f ��rg&:������گ�z��Ҭ�qS�:�֬�P���Ô~k��8����������ŏ��=gd�Z�X,�0CZ���H�Ź-n���n4b�����n�5\��߁F���޿r��~�vD�v�h�� M���_�280(�䎴�^���tٙ|���wHC����i��!���:jft�2���'��) ��8���l7A��E1���}�����C'��]��-K�0�e�]rI!�(�)��!�ƻ|�N{P��^<��խ�;���7D�r_F���8��UJ��Ų�T)z �xU��zGE��=�Z�gs��Y���*�t� ��"���f���RԤ���}����p~��K���U}�5 ���$�KJ5¹��_�d�w�
+�*�[��ɶS�7�5��;�g*e��f\��e?~�� ������%��o�S����v���h�lG.:�F���z��>$S���!'�eM�gU�k�
+ff�S|���m�[A�tT��_�D�����v4A�*�n2��L���0|�x�'qW�j���y�ԕ4~���E�y�I_�a�7�I��i�VWx��ˢ�A����'���9+�����jR�J)���z o����߱�" �����4ތ��핬 Q@��u��������7��-��������{���3j����ݡy����)��ϟ�ii�~���g!}��,Ҕ�@�[��
+��B�~ O�� �Y� �rv�������jA�=�L�^���Y�� ���+,��>>���j��ә�y�*s���%\��.�ސ߾ˊ��'�glt�~�[�q���M$�{��U�$��Ȝt>��V~��� :S<� �z2Y9)u'��d[h|���xm?��j��4Q�Y��)`���(���6�:��<�#Dn}�r��sT��;� ��v/Pް>���mhi�9aS}�m5�� ��'H&f<?-�Y<��2E>:?���g�љ���Oڣ����>�y x�ZZe���� 1�|���i����YS�i��XT���3��b5lK����1��U�Yt!V{�ڣ���ά�$y5��Z9.����Q�������X��F�?(�[��d��Hp�y�ݩ������(�"� e��-� ݨP3�׈,��3��}��a�,�Fs�u�w������� m^}c�\�� z`��t��i�M�.�^r4��������΀!��%Yz�|ۜw_ u�-��p�6��lʡ,�]��ڝ.G ���;Aw���A�b��NI9 �T#1�:0T*m�)�eE�Ufu1��J���|� <��?�7ف�yꊿ���5��eBx��mM������/1l�G������Wݷ�phziA�6d1@�\�q��9��釀�f�P�@\r�!�C�W�y����
+e�}+�n�;d�LT�|LM�Ič!��/��Fj/A���ꥑ �r���8���3pp�ܽX=�[9V�?����H�z�ɹ�����glMF�7(G��ʢ��4Kc�{$�c3�������4�fE����%䚓�H�tY'���K�q]�aX�vUpZ����~m�w#�L�����r��{�J糆{����)@C܏�.��bd����%[{h��C<#lgF�h�5����o�CΑݶ��u����j�R*�����5�Q����6栛��X:���>�Pܷ֯���a'7��0�|Z`O� <�(��}�u�na���c�9�}�ɛ#�=j��A)W�y��.�gd�H
+��~0��>�z�{�^<��ë������8�bѵ�)�h{R�%X8�U Np�~���3��d�*���71 rἦ� ��[jsa���G>�e�b��P� �5+���������/FM݈_��>a<;7����$��y�+���U����O�otx��=�
+<Pv���v>t��iYd�u۲.S���Jŋ3�To� '��V-m�F�ń��-j��B�( �v������֙�t@7��*R²,y��� ��Jn{�)��`.h��n �|~���n�(�y�X��ZH&��!��?W� ,]���v�񚌺:[VS�'�.�����E7��nQ�G/�?R����0:Jk�5��C����J����������y+^X{8V/�ﻍp�H\a6�bK�j�
+�U���� ���jsF�2�� ���1��䋚KU{�YK�s�(�����&<D� ��XT�`gH�\�
+��؅���ȑY�e����ھR��r�&9�� )J��v��]��*�ٽ�@:HK6�4�t����{��ppPx���թjt�.���Y��e9D��������-v�Brr�����9|ٲ�̈́M*�@\% y 3�Z���.W�ϛB��t۹%�X�[�Q�咇;�8nH`��)��\l\)1���X����R[�I}Ưng�{Y;)��␊+G[i��~��{�H?��e8ч����g0u�k�!���R4�8��c�#��u�
+B�)�������Z�L�Mv|�@q������|6�i���m����{��a���� ���7���m8��@ΛZ��!����?�+`���F�'�Jʖ����A��<۝��&�}��n�$��z�I9P���t���xmZ+���bH�99����(�'��\Cp2���s��g=OU�jR��zA�O����;�kʛ楿�Ǣ��{��t�K� MkgpSRV����aO���u�7Ԁ�h��eҺ��V[��+e+�$(S�!ϫ�v�U�S���~͏cX�h�W����q�_9�G2A��7��
+�M��'�j��`q��l�5���6}v�T�婠T{�y#&�ܑį�#�|��O8������g�֔4QJ$��Z%Lf�{@�}A�5�`��F��y)���c~Mz�����Di���Tp�c�����1�Q{�'~�=^��'q�io|M��3䗠��Cil�����Qcy?($A��t���b�$@�ǡ�<��l�]{`�rk_+|�v�#�W�0����l���n���N|\g0����� ���Y��YM`g'���sk�P�0�dA^w��@a�5��R
+͒ܗ�F_���Nj��_����?��r��#AY��q%j�~�~�'�!.��djq��i��夈��gJհC�[*�������Լ�(@����ɳ�(�Ҳ�596���?�mS~�x�X n������t���}ͥ�O�z�e�$%ȣ�OcهQ�FT�iRӍx ���N���-�B_de��� yz��_1w���xq}/o�Ky����eJ�z�O��Z��ez��p
+79�� s��0ڗ���Q��XZ7YF��eF��z�<����=�^� ��I�Qh��Ji4���q�`�6ƌǥ�ЌZ��
+�`0J�$r�0̞�Ѧ�������C�:��fy"���LМ8�:0�hf;�2�*BrP�s&V�A�DH/y���h�rٿk�ԩ�2z+��R"��Q�eٔ�_��Ao�*�ϻ�NT�}�?b����!;fJ�^3�ݩj��a�kօ��4$���:,A3��6�r��d�|�2�t��n�[�M�q�������p�+4`\Do3���PX:x���D�N�}&�0�N�脼uHQ��A��V����7��H�0��f+�ʹ=���1�S� ��7��(h��(mL�� ���]�K`0����m9����bJ��� ܚ� %��%�
+��M6׽3���won� �?4[0��_�UBI��j1�6 OaTx�ܿ����9�A(�$�������g�X�w�%S~���993��<Vs��Hl�!hY�mLL$yO�b;G$����EJ�j����rr��dw��H���%��?"�_�м͐w{mc&��'>K�:738�
+�B��۾�t|�� ,+�M�d):�� ���|xì�F&*_���1�*���@=�BO������(~���\�O���u�ߨ��Y�AY��G6�#�L#�9,Uo8��=F���yիRh |�/��d���' *����a��˂$�!P&���ͧEW�|�*A�N���:�$��B��"EL�@��g�C<t�D��O/Q��� $l��x��(D���I�X:M�h��E������WKrO&���`L;���S �}�^]��^�p/��JQ?���hѰ�(�z�T5��ܩ)��m�?]5ȣbh f�#o�!m�]��B�x�:�t�2���ߒ��X�wFFc�O% ]T�Fd�"���_��p
+-�� `��5���>J��i��X�m��E�W�n��ҟg� �tn̂�ҁ�t�`N" ,���9ۛ���TN�l �z�{�w>%���!\�w"O�Lտ3DVԇ�b�&�_��Z]J�hUv�8<�&�0)�V� ���A԰���kY9kɆ�:|Vv �O6Б�m;��2C�U m��g7�L]�?ʲ���-���_���
+��z %������V��7]�[2�f�$�y��~H=M�&�E��̂|�f_ ��1€N&�Ue�! ǁf�,vu�J�A��7��ړZ]���f�h�^��ldZ:�%��5�%A ܦ_~����:���uA�B^�+A�I�v �P\�ޔ���C�l�f������J�/��d��2e
+k���
+Y .Y�F��"އ�E�'1X�;�P�!,���=�Ș��Ic!�O�9w�r�'D�
+ly�!���~?�̩R�/ܲ�E��%����[�*0���m�9�H����cȭ�и��S9�"�'� �����2�ug벐 ���s����ȡ�)}�7T���1|/ɖ-+��BÈw�`*��)�m_�_о�ehj�M:��j��adw���}��%8��}���ék&Ѧ���B�6.R�י[��KG��O���g0�����<���!�� �J�~F��m��8�_.���R�㛄 q�U��`��:>�ы?:q5�7�����t+W���}����F�߭\�r�6����إE��F�$B��d��^,�' ��^�r<�N]fYWRK��x�5�@�t��F"�gL8�������%P��>�-Zd�T���Qe��lP�w��T��x���kX92 2*v����
+�r \�G&�즯 `��T*��%�6��ژl"���?�ڶ��>�����U-�[h&��.���MU= �n��28D[ܲYJ��br��<=1� �5�.0$�O�v4����)
+�b�c�����z�ꜥ�H$׾Nsss����ɨ_�4�A�uy� �
+l��\���Xv��5�G�$,ֹ�1�/ѣ�V�"��p�,����/�h�^ f{���'� V�Fl�+p
+]T�׾AAN����g�wETN��{�A?�w�5� T�i�+���g�Ǵ� ���7N�\���eq����?R@ȹ�}�zY0��u�\ZG7�N�8� ,�����f��A�F����?3�i�0�-��I O���6C�u����@&8��#�Ҽ_M�hq��Tm�E-U�2�.�� ��2qnQA+{c0�e'xY�~��=��J�mfZ�1;�%��3�w�poY[s�L=aedzc�B  ��,��QA�R�H���B�`���7Ը���� P����n߽�-g�;M�nwg?�Ay,�`^�a�Y� ���9����T��#jg8�.B^�z��7���Y}�[�>���ڌ�]�Ax٠y~_��a��3�����ݟ9=2>���]�nrs<I)[�|��*����Jm�fcaWl��f��G]D���x�c�]����/V�� L��"��rջ��,� ��S��Ax��f����H�F]� =��Su�ˑU֎��¼)������絓u��m( �)���1(���Ͱ�f�T��cf�>4�:UٵF�����˓^� �{�y:\�d�ខt���ܕ�*g����7-"s�9AD�T��I��K��2��N�{F��1�;z�77YQ���2W0o����,M�쀗 �)���� �3��{����L���V8�i��n����'ݸ�d2��ń�B����5y�'F�ͥǕ������1�M���ܤ�4���=U�M��MȂ����s�U�F��t�x�ؕ�G
+��c\�4ǿ`#����AV�=nҶmP+����i����� @*�&ܬ! ����;V�>��+��l
+�f�-;�"X}Em�#iv=%�t�bD�8J�����P��l�9չ0$XR1��~��]2;�eBr�V��Se���� ��93#FPfo~����N����l*B`ΏS��}��g�W�̅}��?󨩻�ܺ;��jF\�IO�ɱ��cM ���R¼�gG�������c��oƿ�*R~���1�+ıͬ���o���l��r�h [�� SO];i�d����ŷ~�!=��ML��Ye��}�:dwës�y�TS�dc��(��R���M�L�W���B�[�Z̬�9�t�䰻=��������"q���`�P��DVr�D M K:�22(HZ�rUa�U\�.B���P.�L���,�z �S�[Ԣ �N�Y����y�Iu}���@�f%�_�3Rܐ�b���2�"g�r&,#?}%��'�"�K���N�F_oPtw@���U�f��'��A���jw��̜���r��ەW�h��͡��3���Y����~]�uJ��$�Q���N��m_�59�/c�’ar{BP��ݴ��&�y��=�Ơ����F����P�����P|��ؕB�o������x?38!]���E�P�q1K�i@����۱�4�-��,�G�cmŁ�,��u�����7�4�"N��?,��F{��3�
+�� #I �A�+X�g+M7��e�q�V��>��Ͼz��Y�x捰�[1���ޑ�������R6�ˣ�1 �mZ��Jҏ��"��t#K� �Ř'^vB�\�ZӃ�NR*��Š�1j�7���?���j��V O:ı�q��0��G=���~f�np��n<JM�;A��ӏmP
+j����,T������^���M�Q�?fۦF�J��X`�$ �+��Q�HQ��R��<����4�™�!^�&����3H��%tT չ�}��¤N������U{X��^��6�y�
+���YQ�%�-�(! ���۶�R ��{�e]��2��Vq��H�a-[�(�[������(�h65��;Z����¥f��œ�8Xჽ� }C�׊2\==V�|�8���N ���Z�;�O��y��D}g�y���0�g�!Ի�6�!h��Ch��`��f5�Iߐ�4�O�*A{>�\�s1����� �.h���0x� �XG�J��h���@&�������fúO�F�$O%���Q'�����[�4M��]��V�Ú�V!
+���Q.�Ca��pQ��ZD=~m��aq��P��U�a��I�����SE��;=�N9g�A�"�������fF�f��3��P�UR�ͽ��Oݹ�`�~�B+�W��LV�}XL7��Vl�7.�`��v�l�}fVޑ�{� ��՛_ͯ/�W�0�͹����&�X_��<�H4��ґ��x�[>�����m��.��B5��7���v�̽@�h�����W���S������'r�
+L٪’L�a.>k����J*SL%�ҮE�X���F5�!�=$@2Wڣ��<O�����6窾�A�/��s|T�ܓ�[+ W(f颅5�/�r� ^@ב�1Nx��|�ԚNJ�8����,-9�V�Ć�ie7Nҫ�=���/�p7oh�z���ɪơ�3S��S�'����,Y���V��I��ꨃ��L3�VG���4�YXt2���c�Dh�.����i g������輏:�U���߉���k���[ Z��=.H�� �8�E �B��4����xvcZՑ�s%8�6-�T��-*�7ꆣ\[
+
+��`1���V���r=�򲊤�V�����=��A�O50@��$��%)�;As�ݡ1��"+T�R�0�/�� bB!�${݇ t��6b��C����1-��:�n�oC^�q�"c#|О���������8@���n�v�����z{��+���/(a�-���~ؐ��/�][�P����޻�4-��{%y����\�OK���NZ 5�|�j3��1X�G7�g�3':��Ɂ����}���;(KR��P�0����q^� *ǽ�i#mJ4�^ȳ걋z�ŏ����c�dֿMh|0�X��y%W��dh��ؑ�� � J�8ٟ���c�Ptsʻۖ�t�
+7� �.>�\f�o����m^��r��w��NOb;0I�^m��>w}i� ꣞�R���R��JM���_�����zh�cV�{�Wi�.Pñ�~#_)��'*��- o&0{��O���4g�k�;발��s�[��c!����Z�vP�1� l����2Ө���ĉ�Q��X��j+5ΈWf��Ab��7�����Jx\� �[d�f��� #cxA% PO��s�܉�S��E�;�n!i���m�\��&ΤE�� N��,o�j욷4�n� �����80&T�
+��Ϣ`DTrJS��L����>I�����Q1���.�U3gX[:�g��*N���] *6Pл��5���?H9Έ���7��pf��_5F�``�8�G�&&Y��/���-��)�&Bq�vԛ�/���a�� �� ӕ8�L]�90�a�"�3�?����]g����o;�c7bȶ����BO���MWP�'Th�K �Ur�͏� lo�:#�d�9 ՟��o育�4Hb�v����f��e%F����]��dbL�  �R`+�7B<�Ӫ�s�m�s!�}N�%����=�:0��k���z���&�г��|g(��3 ��M�
+z�����hy8��v�ȒrI}��(�� @�I��|Rb],�)��C�Qz����g]~ ��,=XMlI��<�M�ڮ�0.F�&��ٛ�XD���_NV�s�(��D�1�`~����^�}�Y �Q���@`G��Y�v��GI�O� ���M�X����ca����q^�kX��ir��L�u�ѽi� 䈩�$ ��HK�7v�޲�淾�F@�%��A����J~��49�R�l�%;S��M�_N��-�egV��^v �$q��Yä��4��5�0�m6ը��TN�f9$U��)������B!ڷ5Hb–*̀T4)�I�[#x8JĔE;2V�P�鳞0mƟ�ĔG a%$K���ѳu�ð��9L�>Mpw�-L�>��O�݀G�����a�b]�W8q����xV.��`� D�HZsy�Ŋ�`W�$ �����X��v&�P|p���JV̰����p���0��!�%J���(�FN� ���N�U_4�W|�t�2l���r�r_T���kǘb.�
+���1R�l�]D���; |�����'m̛*���=�G�0<A*!eu�׺l�(_ K�2�p����Oij9#p���5��3�fA����9�{���Kn k�-����
+�T:C�e}}��<)C�>�A3���\W-u�ӳ��XST�6K��2��me㮲W�Xh&jE�П��XX��%b|�?�+Z���-Λf/�g� ŎJAI ��;���6[�Z0_9'؀�V�7��+�rH��tDÅ�̃h����F��a5s�…��٥%G�9��P�YE������*��^�j������Ċ?ӽ�譆�U�t�a�F���)���@�|�kPX�F��-�=��h���&*R#4Y�L�0�a��%\{/l��;��e/b��tO�ol��؞nS�J�h���ҦS ��! } ����n7)�e�e�<w�v�n}��M �m�?�!:�晦�(�B�P0�/> ��֋1�,�y$~ �/6q���P��������W �v���m\M�o�=7���A ��T2�MM;�3��$K�� šǍ��iXAK�t/Z�FP���I����b6�m{ڏ��OZ�__�- �]���P�OF�H5����5��@y~=��4#6������|zI_eOV�ſ벮�y%����v��������mgW�7�  ��� ��6���,�f��}�[�����zKM�X�+��:~�7H�>*,����N:��~��7(t5��J�~vI�g��fC@�^����0>�/�ߍ)�� �٠�p(�w�n�,i�S�#��� ���/I��RRz9E ��!H�{O�N�D����&N�6œS�?´��� �Ź��g7� ��M����W��!�,�����c.��+V��Ĝ��`Dž(} z�Y�qE�FD�B����|`�����N��[����Ӷ� �j�:��x��Ƙ��p,�M��7������w�_��˦3w�l"단���*S f��ʭO�F�5���p+�f“ ���Ho9����s�1P���'���g�+7�ijdR�'ǂ5�e)(��&��?�T��]?Y��l�Ʃ�L/��ݪ>}Y����"�أV��#�[���F��%�E(�쫙x,6mX|g�Q�>Х��ϒ��}e\�J[�}D�`�E�����]�D�A�^"D��Oxj�����d�C��H�E��k*8Nu�9M,�2{�A���&��ac�ߪl]$#"t�0�k�ExLQ,4<�BB�IX�|���A��`�qӆQ�H��,�U��v�hJ��/�ͽ��>�5��2�)b k���{����� ɠ�%9LU�����T�t�u�7/K�]H�vF�9Ib��طE6G�L2�C��Ǣ�w������n�ӻ_9ז�)Q��VM
+t������#�០�Q��,d\Ma`_�3���VbnՍ|��{�+��*[x����L=Pq� }��E�I,��B�?�G��X�HƵ�5��[p�����,����7�?�7���S4���V�M�����;�j����*��>3������r?ݚl#:[�u�e�Y�P<�;WBs��~�6Y�[������7r��~��3��~�>�6���p�ˣ�l��1ygtm[�7�"����$�Q(�;;��w•�����f����z[K $e#���ar���,��u���K��+�>��0�N��'I;@)�F�̘g}�4G�n�–���.��tK ��^,�֋�}�<�نC���N�q;*��-u��n��o���\NPB�ݶ��㐖W�7��̀�#��J��� ���5ö�����>"ߑ�*�ե�X�����B.#�����b|rk���h�r9̣��2��s'�H{�5>꺙G�\�!V�5���7<�3]?��G8Y��"�7�T)E�g�h€j��S��42{�u�� �)}i��~o�VZ��Q##��[�m(K����/qz���ڍ��S]�4�c�6��ӑ_�� �s�����_f:<w�܌P���o;&j�d�iA1iF�w۰�F3c*�j���FB�ސW��|p�O1�5�ί:�^9&:��;�f�H AU���+ ��*��ė��ro'���d��FhR����ܡ�����O�H ]",�V�f�;��y�M�^c�J�D+y���<U�.�A#�
+�,����v�X<�M�*��X�A�
++'��>E�dQ�NlK,P�S��,®a鳤�=� ޛ*hQHOp�V���E�Q�ԗ71A ��.ng茳Y�G��ip�H?vo���w�)a�K��r-�~�c�U��O���т ����Ԝ!��|o�����ͮf[�V���A�����T�L�^W� S`&�&�1�Y�����rխ'�3������'�Χaz��_��� V�?�G��d������Ñf�f�%�**������A��X�<LVb#\Yi;��x*g�2�1���w\a�����T�N���%�v/%&y?=FFӳ� �A ��#݁D�kr��dO�I ����yo���:�w��� �S60����a�;�W��F��e�����Fb-Y��x�Y,c�L �C��b�-�=li�{f���ch¾����� ��ΙH�qX�<B�����ɗ=J��hM��E�HJ�kG�[���3���݉���;�U���Lr%�>�iWw�xtI?D�%mc��C�;���׷�N��MF$la��'R���&v�`B��Z��X���c'�yU�C~ų8��m��2�7��ZQlAW,�ܰ��$fƜi*I�����;*� �0 )=��H{��D3G���a�1��I���DB��Ȃ*����
+���0�G�J,r={RP :���vI#�D�-T�FuL\㠊Kݷ3�^������aD˚wC�WtQx�Sy����R�`>��;�>3�Bd����������? 48���G��#q�@�l^7i��Aa�BL�y��E]�UK�5�$еƹ�}>��A@�/��R������D�r������b�TS��yaZ� L̥8���&o5�L�Ů����V�P��WВ�]τ/O��)���.R�l�0�2s���%#}�:[���a����Ϸ3Хt�;���Zd*aӔt��fp��Q�Y(=���j��Z=�e��<�j���+�|�~q��a�~�q��7�q\����k�Vh�`�G�yNo|�#�:��m�A��B]65�3�A��y,�{�dž�u3z[͉T��=.�,<�c�v �
+���H>v���k�<����������lZ�5�z�zhHS
+�^rM?�h+��"��)�"�3'g���A��;+��3
+-%$x��ټ+��0�b�;�7Z{�8��xSJOO[;��\67��Ŵ����ю�!������E���j��4��n�k
+;�k#ZI�ᡍ���T�L���k����\^����m�̺~�C�3>�*�{���d+�� l Gi@AK�����YW�-[?U2 �D�=�=� ��}�U���e҆��Ȇ�2)l.��'\�NLʍ���·b1��E�?
+�r��� ֳCd��A����Hkq��m1N�un�����]��CA�S9#:2���q~8�7���~;��jo-�w��;�dv���FQ�u�:�DٌH�;�8�|�l�C����?k��i-����t�Tt�nq�n�7���B���>� ���R��%���J2%�ّ�V�>j���?�}(��o$
+4��Y�3g� ��p���sF��^D&�V�8�K��U��Fq���b8s��#ܡf9�F/�wr1HU�;�!Zǹ�lr�o3�X����c��I�e[!A���e&���>,e`R��j�R|{�{�]����p 0%��uh�2�a����F�Uܷ�
+��aY�
+PO1�.4��?* �����ԗ�)��f)
+aO]�U'�gT���6�>Y��,z��M�����%�/ ����=�hpKf��-�Ǝ�J"[���������������3$Ʒ{M�Ȏ&��șh4�!��C�@r�_���͖@���@IY�� &)q�LFF_)�{�U)��M �\T��}Bk��0��^�)m� �!CZ��1���p� �jE?�|�c���
+ex�?��Z����5&.����P���Q�S��f7��"�U��Ypc�n�B������*I^˅vk�_�)xx�<aZ1k�(���x�7!Ÿ�����0q�Pr��a�����@[*�2��� Ė�5>m6b�B���&��z�u�h_�[�YF5�ō>��' ��w���2�1�����X^�\䫔��!h��LN���/��9 �%
+�s�) i)��(5�n�GS���k#HP���_91�K]sjϖ��9у�2L�P��Ķ F-&�)<l6� V��ylfq<� 0�8�Ȱ���V��Z�]���I���- ��0,s*��`_�JO�V�<�}��� E���wLTM��t�TO��;`-Eõ\��%�[�2?���d�#�!NY[��Eh� �}g�f�"!��pհm�=�?� V� ��ˀI����YxL�հ��d~n�n����]t]�1�H$b �W��D�c� B�_�M�z� F���X\�j���
+ߘ�k� ��<&�;�������Ǒ�d�m���~�BT��H����bC{�ݪ����kp�w�\:x�V~���s��6�q��Xa�aw�\s2Z�UA��p\H����q�j�&%>�xX� ��Z[�ZJ�(�Q�&��[pxz��7��"Gt�ƨ���G3 ��Ji��[�-3;N�+kta�S�צ�
+Id�wD�ĭ#݉�����3�?Q�V�-.>�&<Ɏ�/0*�6��뼼n�]n����/��%��Jb�پ,6�~묋t΅E�ސ��.���Q�S?9 �|.���2����I?��_U����g܄�E/���a���TB?q
+$0k,��c
+�5,;�g�礟��Kֿ<�:q0Gւ��-���¤QĎ`;��Ϧ�� �����ñ�.�#�{�?Jrg�^-{|v8�-X�~�T����$[��E����,���KtuT��J�i���! �l��啸�bլ� �N�%�*��%'� ǫh�-����ū .��w݀ ���� H�X �B��-���X�䬗ֹ߻��n?�1�ƀ�/�^d�������[:?4�Ch�9���*�̽���k��f,�԰�/�@U�q�j�S%��&\�*�u���w�V��o�1��T�ͨB%�4Z�����~��&%6��#�lʽ���FD�$���S9>�h���myT�
+*“���h � j(tʛH"�۪�eL�)����#�RJF��YRP���`^`^ P�� Y=��dN�����Ff�{�
+���P�N2˷M�:�Ek�b|-�/�_p#��wRY��k�M&�k�4(���_���̑p�$��'��J�ӥ��V�@�\m�o{�\`[Ȩ��&B��y�e���$�v�|�Vd��Lџ��t���_;r����D�?�~�8�d�r~�YE�����-M��(��մ�J8�|��$�Jߨ{��5U7�#�BY�ǣ ����7aؚW�K��o"�f4��k$����.��G��-�L���k�Ѽ��bb����O{���:�qt0�W���Ad\�m�J�2D^� �;zR��TMM�ET:��$�H�~�d�)_ ��I\L���4���`�E`R��;��*b_�� ��r�Y��i��4�R�2��a��c<��7�Y]��G ~����
+j�F<ݩ_�lU2�igT��RR����<��j�[��s N;��^��#���-�[u��R����EJ�D�PmްΰZ�Κj֗��*� �SãN��_�D=�lc��uw0�Sp Oh��" b=�\ɕ�!��(�-���g�q0�Xr���g�,{�[���)�l|�=a�(ŝ<-�A��X���v1��>�v|mT< �\$�̔��3Z�&���%�Z+�1��3g�� C����a��Fz��,(��O��$�6�2��&�<��Ċ��m �{�ã��$�άR� � ��t��nΰ�1E#�z�U��R�}:\FFE�����8ݣ�qO˘�Ҁ^��0&��Ŷ�f� �L� r{��j͕�2Gu�P��������f�a,���"�f������X�ʵ\�6�Ӆ�]�p��Tt��j�+�·�� ��4��?� ���P]��Q����T� *q�k�Bەk#_o$p�/�Kq�B ���ZM�`��
+�wr�r�ķ䔐����
+����9���-\c�M�k�ܴ�qo�jK�h� =����zAպe� ž|���<�)�a�$�J%v@�
+'8g�\L��.f���&�>�_��c�3����#���K[���Q]/���������K�����Ey�-*7���W�hQ���[w03x����ֱ����7�Ž���]�("Z�i�l�?(;�"���O @���mŘ�f<򸷝؋�)ϫ�u"(\�������e��-�6E崍9x5V(s���x�t���I �+Z�̶��Z>0��hNu#9��T��{� J���
+�+p�!<�2x���;X��:�Q�D�;C)��0���,�&0]!�wTI:�,qP��G�w��:��8�f��nR�#}��&��e�57غ��/Hq���U�=�$l���Zߕ��ꢞ������-/QH���:����/թ\��u����<�%�q�B�H@��M�ۆm���Kp��v�#����L�5b�m���AK�Ѐ�����㛾o�������6�6�J�%K�饫�%CS҅^���U+�����QYQ6����m�5dpun��@䯃�8�UU8�5a,�O�a�ɌP �
+�ݯF'���>w���.O�~Yw��P��2���P04��˫��giw9�a�Q�L�F!4I�;��v>�}�/��̅0c�F��p���:��%_ոP����������hO^��!�t��Ho��?�"� �\]�X�{�@6_�v��5$J�toQ�S�ӊ�^>C E���2� ��t+�����&����䗼����K�5Q[b7C�'p�0��S�.�_,#.z���@bf��꩞����7���R�������x���6>�R4Փ,��t��f�.B�/����jB@� )�Q��M� �w��U��S���,��Q�@�zjÊP1�����~Xd�gy���0��矛M��WvB)_/�- �N&
+endstream
+endobj
+857 0 obj
+<< /Filter /FlateDecode /Length1 1367 /Length2 27845 /Length3 0 /Length 28805 >>
+stream
+xڌ�t�߳6Ll;�ضmNlwl۞ضmgbNlMls� �����Ͻkݻz��wW=U�j���~ɉ�T�M퍁�v.�� L<Qyef+ ,9���� �_3,�:����ގ���:�\��Č\�����2�6fV33'��������N<1#7KS�<@��� K.j���din��g��zP�P���9����,M���F.@�?;��T�M,�.��������Ł����ݝ��֙���\���n�bP:�܀���(�����ja���]������ �c��4�9��p�3:�lP��(:������{6f��N�o�_�,��621��u0��3�Y��r ..t#;ӿ�F6���܌,m������ !�`����s6q�tpqfp����Eƿ��9eq;SQ{[[���3�_��Y:M��'�?����w���wafigj�W���jv���@i�!L��c3�ؙ��8��@G��Ă����������t���`�0����� ������ pqr�z�ߎ�\�23L-M\�@sK;����� 4�g�g�N��?�c0����'�?�2��������e��Ҡ��������{��Y��,��n..';��?�(Y�[���Jۙ���)��)�W�n�Ο�_mP�3����T��q]&v&�?_�����w����������]������n���������翀?�uu��y�?*���P �?���Z���o����ۙ���1Z:KXzM�,]L,�!�?v��DfciT�w���V�331�/�e�X��9��0�o��p�sKq;{ӿ���0rr2�e�C$vv�7�)�=��0������O�O{�3{'ؿ&��v���m����G]O������[�@��vm�ބ7Ī1���^ϝ�p���P#���{ͩ��*��.;h��p����8գ�:ѻ�yG3Txg�׮�>o �s�]����#3���M�0���BG>�>�����2����\�J�h��C�MÕ�aˇ_��8d��*��cԢu�� �s��I ]� �iPo<�-���|�$���^İ�xk�ľ,y��Veq��!���&D����9I��Z�./�v�L[��ڵMf�9��:TP~v:�ӧ ����fG����)�h[F�ɖs�)��!}��a�L��h��h��Į �}�����uE�ѨI�l���Dd7�N��D�Qth>����;j�s�'zK;7��8AGO��yv�{��OU��M�1��[����}���,��ޣ)gS[}�� ���Δ<18Z�o�M9���;� pcHS�3�;X[��F ��ᨳ�N���a�#����+�*?��j�Q�a���b_���w�\1%gwyĶP�we"b?��
+�5j�_��3�1T��� �+�$�i�*��]/IJ��s7���v�@�\I��|zF��*���qr;v�a �X1�y��6~���<��? ��ā����Wzti��_�)�ٰ��pL���^�7�SڷUito�d1�����g ���~9����j�>��:v ����-d�7sy�H�Ǫ2��j�[&3��%G�H����/t�ϝ�9�9�^_A̭�5:9�Ar�YŮ�C���8�k!�7C�ʷ$�"� ���+�w��R>fiRE�C��]CcO�������;V�.�aϟI�7��l���=(_��(X8� ̖-�"��fސ�b,�����W��v)@U�#�6�g��cy�gi�L�,K'd��3�N�87��S`f�� i-R�}��F�~�D���]��,4�:���#!�d*��h�|�=�1��'r��>� 8�h^f��z-\�8��Vi�ȍ���pj�B�]£����hs�Z�W�x�|��ۯn����F�Ë�R�2�I� ����O�ү9�B����^!�.x;�,?���z�p��/���}���&�<�����p�!Ȯj�L��A�w��l�G ��v�<���;4�Q���r�� �T����F.��9�Oa��"�]�Ms"epl��*^�~u�K��� Ab�����9s4œ �P�!�$��V��$j��Q���TuctN�=�܊G�jX��d�{��I����5����A���O�������r�E��$�y�L���ټxB"�7���=�n%rj��vDۛΕ�TT~�n#��j���A������� �X�5\o�����܉4��8N+�'\�@����t�4��&#�ȷ2r��t!N68�O�36�D�n~�+��a��C��>�G�۔�oX��I�eV1�� �ָ����x��[�U�=���]v 8a~��R��Э��d�!����>��z+�#�P��6�s F���*��'�]>�)��{[ �� �Ϛ� ��7��sT�1���-My]
+���{�B��Z �
+����fpt8Zu�ѡC$"v��
+��1E Z<��0���ғ-9��jόu�.���kh����]T�봆!� .�W.�wIVs���n8���M� {�)��w�$���G�>��t��o��Z����ѣ�V� y����v�rq� 7I<�-���OB�� y �� �l���U2��!"��&�Ȫ����0`��͙0��&���m�B��v���Z�\;r�q� ���s�ƪ!��"�|pK�8��en�����]� %�(A�NM�K�G��|�i�Ix0����L�9�e�4��Q�o�����D�`W^������!fu���mM�ChT��;7+�E�6��V�20l���D,�e |� ���K��=<���KG��-�7sԠ_Ky�p����Iw�e�ene���Dh�7-���R�v��I�'�A���ˑ��K�A~��b�7S����8�V�mMKa�V&md�m��"��"�w<�'����L=�n��U=��A
+�c8� EJ8��b�W�p��}w��"�>V�K�2r1�G��6��0�wwq������6K���66<F�Z�� J܌_���=(�w� �U�32£�M��e��ny �4xP�Ҷ.� �<�
+��iAE�r xGF���ġo��=�p��Y��-4������G�X*��b�h֫����d��귣a��.�l����-)��!��:�6(ʝ����&��,ؐ�0�3�uR#� E�\h�C�.�6b��6��0=��zu^+�B+ �/�엑 3�qIbr��NkR��5��Aeu��N�eA�'�SuJ�I�<զg��}����&����3�oZ�?�Bhxr��cL #
+ ��_��C�����O�\�$ꑶ�D�ؘS�/��j�NR��M��h�a���T-^q~ڸ�rw�P��,�L�9�fe�� �NR����,u�+�V����P01�b"jع��ǔ;�P��^�%L5Ly��,� G �[����?a'(��k�R�[�rFI�Àm�໯�VAm�鲀�ɖ�7�T&q���wt4�j�_�@�"QS�B�J)�%����HH�ǎ]�Q��o01�O��| ���ƅ~��Z��V��sA�5�N��`���n��T����KK&�F�3�{a�ԩѻ��>q�.i^�N�v�5�'Jtɫ�����)��Zm��m4>�R��)Q�.�HM���l!��H}� *��A#h�M����m;��dZ3T%A�S[N�Ĩ(���H��_p��e�r����*Z:W� o
+d��#j� Nx:_0mAc��/�s�G�U���f��.��C�A���_JGZ�P��
+��
+‘�l�j�zƼ� ��1�r<��O��뵓hF���H<���/��wc� ��})���`y���&�؈����i�����kd_�j�ݶ���0}�B)�����k94���I�Lg�u��QB��BL�b��퉞� B/��Y��~vU€E4��"�#��{��K����<�萙���i/#���Z ��%Y�(2�s���u:�@y��.g�5�d��߀/��s�#�lLC�8�u�m$h�2#� �l�iN�2��v���%��+��c*W��sc���_j�{LMRAx6}�������pa!�*�=,KNJM�$'�G�Ve���c��mA�����J���%�������*[���8�a2����%��@tE�dSh`x��-��Bn|"T"� ��0�eh��"2'���y&p5�1�w.C�w�ו=��u �� ��K���
+�+�Ŷ�C�]�����Y�$g'BK�᫏�"eoV��t)�
+��>hE��DF,��rS@e� #n�9q"��|���k�ȱG~E=�dԉ����I
+
+PTv�a� J���x���Y)�����8L�T^�u�lvD��z���� ��d�#޼��vJ 9Ǎ��9E6t�"nd'�m2�R�����8���Q�Ԏ�l*5� =�8���@d��
+�F��ޭ�=*����+��Y��+_� ��dگ����p7ۭ�&,�Ǘ����yt�j~%Qߐ�M���E��Gt4��0�S^`�$�J"D�t�st�W�~�΄_0Q��p���r��*{>,�I��1��v�<��V��O�~�)��k����6�D�;���}_��L�D\۩��dž)K�24H׋�Ub�|�OD=F�{K,�d��ң��ӟ��~��l�X.;p�A����yD�M��p~����v�>V�n����ѓ#��@R�ku[/��f�PEY�U� bü��ֻhC���'Z�ߖ��)�g� i�Q�Μ�$�I� �{5�+LRL�������X�%�����けYqp@y�0����Xe�<D�m���4�5Żr�5�f�9�����Z<����cv�ɔ"��]��}'^vA\��$���
++�ږP���O� �ia��a HcL�RST?�]5zJ�|�T'��ե����h��B80�&M�k���Ҳ�٧���ki�V�"^�S��� K�-�
+�dD�B�qr� �K��,��H��,�BA��̇��a���/Ǯ���L� =S�^da�Ea�fC��ɧe�(�4^;,FzE{PfeGx�G^c�f&�����sYI�V�\�ܶ��"���3�� D��ܛ���˿�Yf���&f���BN'�m(ƙ���Qh����̭\����(ZH����P�>J��xYH�%�C[KkJ�W��&��b�>�6LS�cje��O �u�PA� ��4&�/�G��^MwYm���{�
+"RH��M7�X����Ě��Lͮ{F_�gϩ��K� _n�������!�'W�ȣ��z��"I��b,�;�|�@��>[�Hr�/����P��_�{�g'�8D����PKdD:��<f)���~r�����)�Q�Iֽ�*a�#5���)���u�cۘu [C��
+�/����
+E̴5�BT�k�S�SC��L��gF/��-�"�g9�4Ȩ��r�rm��'z:�gB{8�� A<��R{(�����T��;5�i?B�q{o۩[AW���}Y��lrM9���}�m��6���Še��2�t@�z�~�,׉fe�M#�a�,_͛�>��|.H$���븞�Qkd�8��i�Q��;�z� �0�I�{�x�3/���Fo��S_��q$��3�7h�w�p��i�����^��\ 4�ͰG�pOjk�_� ��wx0]oҴA��t%B/̕�� 4f�� F�WV��-�74=�:�O���TPSt�1
+ �=��v���3��f�T������ʜ�Z��T}��\�2�v4�T��������@��[g�d} �@c�Nb�������%rV���u�Oݤ>�����|E�B��kX<��m��Zh!Кi��gS�TO�gE�T�>6.��"�a�"8'��~�r�R���τ
+��( �G�Ba�02�蠘E��Xn]%xI*�-��ʗ�ǖ�� ��~��yd��/��yi�$Ix�������{RQ���8-1̒�yORQ{ZHݧ��S�U����*ѐU��M���<�A���@H=�o/���NAO�N�e�#�UR�7C�U@ ̈uB�5�p��!~�~��e�9~3���T�gs+�I���"J�|u�%��t �H�nK���p2� 4|� �*�`c`��ܾ�:ʬ���,�
+���${n 0⏉:� H� �
+
+Abx��D��E>D�7�����ةdw_1h�‚iٺ<���1� rbgE��t��ڻ�a� � �P�S"�n��K��}*���8`L�P�b���k��y�51�T� � ��\��` �o��#rO~5��1Z���6��9;�v/��[��`ka��4
+�ψ� &Q9��E����R�\�,��3(����ww+�KY�� �*���cXBH=Q �Csz}9��ą
+[%kF�WL�fq�6q?��`��b���ND�xn�� P/�"�/:I8Aߛ��h����&L�U[m�m��򁷟�S��]��b5������h�H�C8�z�ep�*� ez[`vC~�� }0���ʡ�S����L8���#��������Ȁ�{'����o���H:Op�R�_�d���y_�|4q�.�4RՓ�6�oS�j2<־€B�%"�W���7N�Z �_]UM��e�2T��Q�ЙY���[� �SY��#� ��##�69pr��K�C�a5Ӌ ;��3��F+���w��u��X?���u�+�8<��!|�OPɭѤ���2 #�H膏��Ύ��1�Fa`�/��] ꭎ��Ѓ�ޯ<�$hs�Zڱ�e�6= �.�m~o([�I>�'�{J�:iՌ�H���R�]/c������rPH��N�)���ʤI��OZ� 2Hr�ϥo��ڝ��}b�Q����[���g����2㫉i��EM�`��o=��D �t݉o.Q+oL2��N��9��/6Fu:&4l� ]n���f_��\��yN�\�L�L��DC�\�(r\tE������x?�d,;�����Sg#����E����?q\��8��:9KOhF��.��%�����SD;Zm�caxVX˿�N�u�U�lV�~�V��"2�gu��G�);5��_r|
+K/�i%PSc��*�wI�)��Ä9蓩,bG�[?��{�d6:�H�R~W`�� 9u�+������'�:X ���X�xS�C���<[�Y��Uð��O�Ҵ��Dڑ#��� D�=�x�3��v����,�J�N
+�ҝzQ���(t\׋&���}�m ��� Rj\h[w�PJy� xG���Kx�7.M�b��{�v��J6�e��� 3�_���'�� �R�t��1u�P]�����Z�3>�%9?��}�I!���P�ɰN1j�<��C\Q�mIq�.���zO���'CChhs�봶b��$�VS���45M���u(j��9�Xa4�/)@ ��|�x)v��OAk�P:�XmG��:�r�P*�I�4�Hcd��8D�U��ʒ|�Q�4�Hr����ɮ�����O���PvAlv�Hk2z��%���1�j��ʣzM�,��r����N ���D%ۘT ��ݶ%\��E�����~�V���&�=�s�2p���%�3����M�/*BP��I�����|�+�=����v����&5��~5�̬ �LV�zM��Ԉ�90)�.��w�iO0u�_D� �lv��c�덾�C�aB�Q~J��l����ym�}�� �:��e�u}!VpF��
+�� י���!9u1��[�u�H��\��Q�u/4�D��fLva
+�ZqYϴ�\�HS�0b5wg��@��Q����*8AM�/�E��\�4���,(R[� ����ýx2���˛ yB�݁��?D�l���� �Pw�u���p�v]v�ݺ�~Z���HВ��Z�P�u��׷��vRW����ӹ�&_ʤ�C�;P��r���֐�ȩ²'m ��)�Ē��Ŕ���������귨%��#�|�1�ԛ/iXZ���ȕ'J�#�^o�J
+\�G���[<#��>>z"��(QƬn��C�4wY$�7����\�T���N�#S��D�K���e���d����?�CB��=}���ى]�j��z�~�Rjt+_w�����U���s 4,����� _����*N����3��O�� &��o|����ׅܔ#�cp��H� ��d���������2�a4�Yo!G3�[H�-���er��?�[lzi��3 �T��Y�� �����uc�����BSͪ�`�J` ���?��T+��x�5rl�Z�/�-D2jV�gW�m>�Y�2�^�G�Ԥ2���{l���<�s z� �i�mb*?Y� w64�t _`ӰC�II�㜍>�i�Fc�w���j�gtޫ���?Džߘ?a> ����
+/�B����hݝU� K��n{N&�9GN䳖�s�b�j�x(�d�a�AU�"�R��������<�m��3�=�������^�e���b��K "�k��-�B�����/���.���˨��(�b�
+����jQ�f3�4���rA<�������^�~g�R�=3��U/{>~�tC;�+��CٺIPz��菺�"��C�"����e��ȏj���x8����b��hLͦnJ�$3�o6㜿Y��QlN�Uf"}�Dq:��j(��@6���� u!�g�G���{����׳��5j���va=A���p�bD<K��(N#��ҝ�)�y�=��=�_R��v�JI-�B��ULt����B�y,�����G��i�7}1�ba�_#�:��N~���3X��nɀ�\c�qr&[玈Z��yH�Y��&͖9������t5���I�B��z=��ߐ �P˪j�Ȁ�������rF6�V�3�3�ܬ��+����hL�R݁>K�S�:�����Oud�K�Sٶ�0��Џr��d��W�7�\��EJ�w�J�P�G���_�3q��,�TU�+<�UA�3�Wg|@��|n�b����Se��6� xn�\�u��Z�Ⱦ��ed��1�Wѽ���
+���� ���\�K�h����9���]1��W��C�'`j��F�)�G��\N�Q�|�����4�|�:�_�SZ�5���*�i�%�~ݒ.U-z��w�ʘE��|n��oY�ʰ��h*i�q���Si � ���t�j�����ۥh���͙�R��pÖ��Toge���)|Wש�ɯ�D/�3��㪒�G��bP�0�����/����#�孇 �ԪV\��F,����"G^�~^(2��\��(�ҫ6j=t�5o�ʪ���,�Z�iۉ��ĝ�B�K7^*�0F.CUF1��F�����]����ϤsE~�R6����lM�H*M���g*PGD�ۻ�=���gq� 1T��+��x� �'�xA^A�y}Rl���˛�$��<Ew��DaV&�.m�� �,| �9�7��Ś��v��9>�3���y<�[�)�I�f.0��K��ٳ/�[��u�F�����(�P\�u���";�
+<���(��>��HUQ%b�9\���N�RO�R��0�y̐�el�>�u��5��V��;��fc����F�%v��;5��wɖ��P�d����&@QDИ�x[ӮҎ�8�io+�M <��sQS'���G )��uI�?�F�.��<v�����{�����٬�>�K��T g��Ҡ����)QՁ)�Ԇ�찜&��a���W�Ħ\�f?
+�S���~XL�k�;��2��y��zޓ��F@)�`t�ZRH��밧��"!���lǢp�xZ)��8|L(
++1H���V���� n<(Rtg��vI_a�Ny:,�z��r7fM q�}�o0P�2RY2��29�.���b��k���ЃX% ,�i���bK��Gowf_�'A��Nbm�C��sW<9I_����N��PE�q���F���� ��zT+qE3Lo����/�s I��7?��5����.�,R$6c�$��z�ȪD���m����#��B"0T?;�-���"�$��oM�I%ߩ�"2�b.Q���=L =�ބ<��� e}K����\}t���a �z���D���j���ͩ<����M��A�+f��/l��Ӕ"5Y|�{���i�?N� �����,�VJ����U��WC���|��IZ����L�_��*:(j3,�?[��]_v8q�Y�4�^�ot�>�P��Sn4�T�[���O~�އ/mڿ#�3��=��M�B��� �L(՟ ��=Kq�#-��o�Z�V�2W�hbK5�8��xϳ��*d��sW����0���*CK�/�s�����Q\��q>����d�P��s��Q5 )]P�z-`*Z�?ƥB��B�����t�NQn����kڱ��T�eZ$�pI�3�M�OB��q(� �3s9����dV)�+Y�
+"�C ?ɼ~�!W���a� I?JF,�Dy\W��%��]I�T��ѭ�B�l�sѶ��Q.��ث]{Ȟ�Ϟ��{Ax�]���7^ԁ���ib��>=�;��C��w|�&k�A�y������!��{��I]��-��ۢ�/-%��p�x¥2�(e
+C�T�!(�48n�E-��F�͝-���8=�mU����QJbv��n�D��ƗJz�B_6�u?O[[�UO�'�B�VBn��8hZ~��_DVq � j����0�E���A� �I6�0������ʊ}��c �#-S��9ʴ�[�9ьt�����D�)'}��]��P���B�8Q�[x����{~@_<̖��_�}�㢀@lٌV���4����)�L�J��+n�J��o�|;��t��F�$`�U�WFYA �pTk�Vh�Y�?��?�m��`z#�z�2��O{0����FҦ�W���le����Ğ���5B�zuu����i<3F�vr�����>� 5X�ە����U�����[Qp�,@r�j�ck�|w��B�gy�#�⇔�Po�䧛v��Q���y�Q�0t |ٖ��vσ�;`Z3��l~���EVR�<���S}���I^�N���By[�"xX��汩�7`���¶��hZM%Hp�~f~ ��^ �b��*�KQ���A�����x��1��$�F�P�+��";7-�<�ARC$R��53)([=�J�c!3'�h�)
+[�����P�&� �|�b�6�G��S�οv�\A�2O��1溯V�q��` � ?� uy;�V͇tfK������$ya���� Gv�j����Z��R%�� uk���+�#�6�*���K�R~���@��X�=�h�D�z�_�=���A��ͱ�N Y���{���W˵�SON{�����FG@DC3�v>�d�7�'�( A6����R�M앧D����-��ĉ��]-rBƄT�&|.�r.M����|����x�� eꗑ�C�%��][@�|Ss��G��l���F��GT\Z�g֎LM��$��`��(�%�>����B%�����Uf5fS_|}?�[݀,f����~��_�Ho�)@.�O/�cf&���4���#�="l �æ��|Ɠ���/-.����d' 6?[�����������!�ĺ73�Bٕ���*9[?V������I��Oh�n l�_ #���'�0�S�h�.n�K�u(�0 �Y�V)�>�}� ~Z��#��z�*�lm�,q��M
+��
+��>Qҭ�k�e�RZHut�q���6�7`��BE�;�pV$�R�8F�֜�����&k�DŽK��k��K���O0a�Ǵ��G6�ϢN�B�ח���!����z���\����O��L$��]�Pt����z�k^>d��2�Rl"Ue�E2J|�,D���~�Z�Н%����}��eG������S����������U.]�8�d4�\opfI">+LG`L�, 9���V�$��\�$����|�A�kj3�(�<��.���OHΑ���J��c�h�KP/�z�uͅ�A�X+���Ŭ��w�I|,n��ǹa3l�4Q� 
+�����G6ꁓ�����k� n,�+F�'��JH�Q깨$�h���Nj� �a{�u��!��'��^p�îW_�mu��pk��|OM�H����- 4��ڗ�������-�~pv�̥:0+��^�!n6Z�vu��� �\�@߲l�s�Ԧw����r�.���y��s��. ��2Ĝ'�,PPA�zf[)a��|�#�����Ooh�y�Z�� `�-�Y1�0+�µ)ͤ��|�l�Ѥ'���@SX���IQ�faij_�� ߼!&^{�}n A�}��k�Ob�)V�I�͕M=��-��'�Z�i��$>@0N[��T���D���#�mvÌ_�"�T�ΌJC��D��v�$HR�U�v#��;��Y�������yB�����/��Q򐪔�k@s��2�m� �4�n�mp��z;l�o ���B�\U� �_�kq�!��]D�J��=h��].Ys$� N�ٵ�Q���Vo��/��'����>+!a��H�ެ0�Re�CЮ�i�¢�t��JBU�9����j��M��c���X��a�!ሯ� �጖4ލB��4���[M9UplUjmx��Z9����tl"�Đͪ$Ԅ�Y��m��Uw����> /o>��� �gq�g-�″s��H���Ar9W���l��}<�,Mݵ�Rɧ�~��!�ЄýX��\�)d��� uڮضr��|��6�h��g~b�S9-�q݅�JO���~�+I�=8W8�^� t>OD\�(�s�_L8Yᕥ��� "T��Qq$�koҪ>v��'��3�or�^��Iz��bN�#<'|�����5�wpf�Bm2髢#�2�z7�2���.��[p�?�Y� ���wiT"�gV�y��7!�ꡚ>"�k �-+E9cm�jo�%�z���oY�}- ��yu��nN���<f7���&ej'��'� d�b�%ϵ?�IT*�G=U9a{����ۃ�y��3:��5G�sU#(��=!���ݟߠ�<�(�$y�[�͔]��w�6�;� a�������&��l��70��ҵ�������=u�z�}�9�bF����V�Ե;�ä��DXx� �4C�_�J��}cϙ��t�
+��*(�?MՄ��<� H���� ��b����%���8��1K�1y�|/�d��� 5�:�<�Y��>KG�@
+�^G����#�Uy��p�Lj�l��]?�C���!A1t�y��<,� ��ۿJ�ͯ�D���p?~��sC}>l l�@@9����]Eo9b��])`y����#(�~2��NO �GlL��!'��yV.�3��}�@K&���q����H��һ0�[;���C��ƓKP��H��0��1K���2]�������ɤ9�.dG*��Ÿ%�O���"-��@\u�ۦ���L��}=�U3������Y#:��|b/�D����7?$��Y�6������惩~p��g�('�U$��Rv\]�E|���3ud��׌���0�!��I/�j~�
+�vz�*���~� �7z������(L�N[�b�*3'-x�N�};��IqKv��bd�}�*D��>!㔥 MAo\��,lXMv]��f6����ÂLeQ��Xeц�Q�-�Bk��v�#�HO
+�ڛ+m�'��^����B_��y���t[�TK%�+�@U�̦f����k��%�֤���l8��0�` V���hT׾^"����� �1���J�qhTz�ZR)�(��&�5]?,%��Kz.�2ڛ˛k�
+�g��U��uD����@@U�4�P�g��b���N�� =�C��Ջ��X�D]K� Y�/���A�
+L����-�ũ&��tݗ�;b�O|oF�[�����~0��XcY���iRg�$�ΈP�Noo���$�Q"W8[�K *����K`�h[Q;��^.2��5�u����/S�� ��C����-������)�
+7�B���gh�!���oJ�xn���y���#�e�5�B�1H�}��>*�$���x�9x����;@�k���á�.yN@#.6��ȃ�8d�ur��"i�-3f��=(�1N{k'�
+�b3N��}K�;� KoTUs�H�c�`��wS�B��h�ubO�t]��f䘠�0�НK ��5m�=��t�g��x�~�9���W<CH��wgo�*+�<|��8���Lʹv)
+�������w�0�~�Ok�(��:)��
+����Clu@�te ��k�-?�6� ,j�}#{&yD�`�%��I���6^��C��Ӡ�Ɯ������|I�X3&�)�k4�E�(ٯD4�ܙ���<,�<��lg��[8�.t��e8=�u0��Zs��<BM���՘˿�<:xi�Im��Jc�߳~����:���|���"ne�s�N8h
+*@��m}i7��w��2?}���wњ�g ��#3�O�w@GW/As��O��h���$ ٟM�<*ߟ��� �[��q�w��u��f���Q��eoL�+� ��.�Ԭ��1 �7A��y�2�pֲ$�I�`
+���:T���q6<��>'�;}���v�]R�okh�'%��#U�<߲龹.x� ��� ����L�ɬ� '1��h�uX̶�7��In�P�q��ijD��x�J+"Wl�q���ZDj|���%���GaK����m�� XW>#1T ���5�E��T>b5R˥�P~�~M��:���^ J�i��.���������Is�>�S�!
+��o�wf7�1܋��&�-�;�ϡq��v(��il�r88E���s��Y4U�a��'O�!�EW�)���.�� Ry&=�����爧z3Ad\�?�;r=g~:4��F��O֧�0�Sy;.)0av��]_��1�JjW<>յ���=��AU ��!U"S ZŌQ� %�������co� Б�d���+L8]�~��P{L�(�R:.�$Aq��|v|T��a��J �BiNI�8�v�@��z��Zx&�a2u�qE���Ag��5D�5>Za7lnU�0r,��,3�>l��/��'��K�=!;k�V��KF��]���ws3_y<�P>�߾��"_�v=(l<o��� k%|�c�u#��q=�q��i���};��"����k���Kh��MO(�3Ov���w���������۪� ?������w��s?Q�Ӻ�8����5����o�
+�Et����'�AO�,�ޖ�X��U���c��9j,��δ��Ze�ަ��I�V�X�+�$7���d�dl1�����*�!} z�=�CO�'�3ɚ� z~���N�5��J�a�$q����A����8�V��P���츺_�|E��K�~�ŷ���{r[�\�rz��WH��}g5e[�?��B�Ts݁����f@���Q�Y.�!t�����W�
+��O��n= V���b0��2z�"A�"���q�u>�@{!k���73X�$<h2�jh&��h߬\���$X�Q j����$v�*Euft��\����+\��C2�#�[�Z<�i���5� �x�k�9w��ƁT҇�M '}���B���o�$�]�L�0��J����{�9��k�wPM�r��c�}���$ �f�� �� ~/"�.ۇ��`I���\�O����)��&��rǎ�j�4���%�xLm.�8�tIoI8���lHؠ����ś���O>�8�
+[_���bj��K� j����4$J���M�ې���<������3p�� M��VF �/�K��">7�#~�o���s�d��'γ�#�J�Y �jp,/W{��b6�YB�~��h\df(uP���PS�����~�x��/1'���M��yMq�_ܭ���q�Y <2�)B�R��%!�lH�N��T�r�pz��Z�Q{<�����V���WN� ���^A��z�Px@�Q�F?��*��_���D� юڞ�С8�1��#x��]3��kѦ�:v�1ϛ|>�!-���h��YY-|�|�c�5�k�k�.4q8�g��Y>�9a] ||���-�����UǶ�15�>��R���M$�� ^w�ʩf����L������>��/N��-,h��H�;��3�QΖ���A/�Jc��~�(��Y��,�|��D&�Q&~-�7p>��qqZ�#D�Pw���ك�?4_����,���F�nE�<A$�l����}��Q�MQ�br�;:�!rC���9�h��1�jZS���EZ"o����%d�$�b ��!�<BBS��Al�E���@(/P�h��%��ť�[���0��1XG�5_!��8]�h@;�����~�B�4U|��,��9�~A���Z���&))��v�3�.�h����k�w��!�M�p���Q��� �x1�M?�vӲ?�D��Y���fq&2��q4���H�bü/��Am� ���K�������Z?X�����p�}�i ����|_��ΰQ��W�p&�y-�����m7�@ʀ���ڷ���n�6ٍ��'�Ŧ�E�{[�WT�⵩���P� ?����_)�V0P'Z�'�/Хp���X�Z{�����%�檽F!&u"woP��?�8�d+'P�K��m�ѯ,���k��J���F�X*��D�)�+O>�H���W��.�������R�QRf58@Y;��U�q�+,���^� T��:v�d�_���]�cݔϨ>%�w�����j�|?@LeZu����� �u�2�C��f�����~�GnTGm_֔��͸|��m��� :�3nvN�4��� ܸ_��*���W�u�� ���J�����j�k�]�~�`��W���h��h�择���4NT�d,�筁��X<��
+�^Ec�T[eO��:���F-*�z�R���S@��N�]?�ڧl�,(I�B��p��ef���7����%�)���Q�Vf�p6~�͹C® xQ�l�`{���}���� �\� ��j���a�`����H��3a�����mdw%����T�:�4�C�u@�Ƽ����:o���E; 5�f��\Au&MVQIc�UP�2��k|����C�7Ë2��c�m�򽖐/�{����R���I�M�ҷ��-��TRA:c5B�y�$���>�
+�Dn]����S�t�Eyy���{��Y���#�m�ewc![��e�aD��G���� Y)��[_r�`��)ҫu�|)0wH�:�F'�u9�����f.��uR�`"'��أ�ʖ��a�~E� ��X3��t�}8 �����AC'����vK�E�G:�F�6��o�ԉ�.�ǣ�$)X�J���|�I `��b��'��-{�)UEm8b�$D�Đץ9�K�I�Q�o�E//
++S5"�*8�W� J��Y���y��u���kƔ_x�9�(ΐgqǬ�^�>PM7�ṑXui�%{�G{���w�8Mo���Rް���d�c(uw, '�)D��8
+��V�L�2`}���O����w�\��!R�� �g�G��W�r=�/��4^"ۅ�oM8bn7|�5�,4�tV��Gd�4T3�t�a��{��Y�9�j��'�?�8OzV8z�H
+��DS�X��
+�)��[09�����8�W�p��n�;� �_��9)����ie��nb��w k�Y�e�E� �X�P��K�Q��x�ҜݸE4<�,�� �t�c�0h�!T���
+r�y��������̏9�Cy1?�^p#����3nڍ2�˾ؾ�m(z��$_z&���9kʚ9�2&��s��q�<��a�jK�^����-��3t��ٶf8,�;��;�������Œ&���Nخ��j��ݲ��ښ�� H2��3��)��V��_�MR[�t�O���a�=t�E�k�5�b����0<+�s��(�����TzIN糬�W�S)\Q��UM�≥�m�Mr�),�9H����pL�yg���d[�?�<�F���H��㧑�|S�
+�U��=%qc!s�1����?� 8�/��(2t��.�˕�H9�=�.�9�q�bK} iJv�{�[{{����!m�����)K �L�6X���ED���k�y����*u
+��{E�`D���@���I�/�.�.{��[�J��H������윧�-�>�䝖M�Q:r���סvg��c��1��3i@˲�h��L���ܓӮ=�M"�1����Њ��%��Y:��`>fY������8 �x��%�vq��|����M6g�� >$����ջmDe�j��Y�ԋ +aaQ�҆tG�/V�Tz���Јy`w6���HO]IԄo5��:J�����NI��b"�c� ��1X�=�W�H|�'�l(M�#�P�b�柆���\������R�����n����B�ܾPVYy���Kgح?y��pF��p���S�<���aǪ���!��5y;�3b#���*�x`{D��U���,��\��̸�(�ߓv��xW����-ُ�8���4��%�7,���2��Q������\KK�/y��{�#m��f���o���6�\��o'�oF].z�g�t��<o\~��q
+���Y� �#�674����)���M��8�+�1u�����y����y47(<�y�Ah�T�{>�`���j��"VswBq�p(�b}��O��ALC=&�)-+̗t�w��ʥPs�*S�P�HX+G��
+����\V�`݆�*'R6� �%�O��S.�Y��B�NJ���\?�6y@�j1[�����D�7 �E��Kc놵��b��������4cRd0ۉpa�bzGBr�`2�� ��������~����
+Q�!҇�t�����c�i 12ݲÙ��1t�8�'�E>]ņ���1�B� u�X�2��UYB��I0�J]���E��IP'8aԤ
+��L���r�N�S�o`ʅjZ��I��`���>�� %��y(���3�A�q�J��Y��W� g�l��(�>��;����}S����ًiDp%;J�<գS 慯 �^��2��x������8W����ߌ(�=+�v�r�c"')mn�DE9�Q���۫L�mh�M4K{�P_�P�:t?��Ab��a�N�W�A~��R-�[h/�2g$l�-Ĕ�a���4��vț(� �L�4{�Q�/B���w�Vn�K�,o<�;��5 ���i���T8�A��`�j�����D��WY��M�Ș��vh7j.�M<�}�� �)���S�P�5P�R�A�|uu�;2⎠RCO�=�#���T��d�M��+�^�,E{���wt,��F@�����b�M������3:�z�]H���Y�Ҕ�.>m*��J�%2�O>R* �
+rh[�pT���M�@r>鄡�Y^FR���iBۛ�0)�����]/������+|O3����&�t������B����/���]�ƃ�ۯ6ax=S��QcZ��k�,��:ˀ��4'��� �AA[�Գye`���([�+UM�Bׯ�4���g�88�U(I h�Im�����,qb�w>���I��+Ϛ��P�W�S�e�Y�I�'/Da�t��83�yA ��?���g��sgL��,-~bx��zU�m���!�k�\b�m;�A�c�:�H����Kn
+i������6��슛붺gܥՕ�d�b�=Z�)/%e݇�x1�q% �j�F�R�` ��:���%��<�ٸ[t2ZO�3)-[��xL�݃w�s<��GȤ�N��Xs~�d�uJ c#�vc��I >W^�!MѼguc����$ꚜy9��5�ܻ��Ã�2�/��@�ȥe����`�J��0��A.G߳�m�d�z��J�{�|ߤNRm�nŏ?З�{G�k.
+�X��k�)� ��<~�) �4�9�_�h���0�s1Ɯ"vޗd' *��n�����GJ�BO:8��{dv��l���;~� ә�+Eb�;|�l,�半�dBHpy�:X��� ��A�m�)W�"���T=���{sӨ��PXx�a��
+�����N���� �Y@Q��bOb���� �&��7�WXec �v ���,�w��{�H�pX�B��� I�*t��X���� }-���瓹U�kq��\�*]�w(����(Y"H����B������9��ݥ�#������l�� '���v�x��iB��6"�D
+Cm��8\����<��D��1���� n�#�r��vM�*��S��-�ot�#������w���� �B}��rcIO��Q� r8ډ`0���˺� *Q3&��a�����re�w=�#������i�rS|!�d�X�v�y�A�Q��<�z��̠*p��Y���x�D���t���nr�̓������J��u- ��(1�"0%�Ś)���,YQ\���~�.+���[PH��aڐ:M��>n���Z�"�� w��贪��,��UPx�i�"��'��x���(��m߾��j+�HU�'9����ok8���L"֒�� ĝ����R��K8�����pZ��j=&�u9�6V|�q��G䱠G>�²xG@����_�:�Y�A^��꘸a��H~�G�3�r��'���Z��2+����U�ŝ�xM�s n�������h��)��8����g�IAl�*yC�9�)%.��k�]C^��`� *���B4��0��������"wŭ�� Z�15.���6qx���zn&��ŏ�� (+MW8�%e]7R2A/��E����z=��@����w���&��G$��S<��Ҹ�z7���<}"�Gb����*n(�n��Xl9��������s� ڊQ����h`Г�C��x�.l?ݻ?�-��- {C��S�y�sW�p�d�C�ʭ��o���~�? �u����������P{u"O
+�&�0����+��6�A��Ծ� rA�BV��9:L�p4��W�Ł�Z�9�SQ2k�h�۪���Ѱ�K���Axg4�F�̲����cY���z �a��m���mOcnR5>��]���Ki����:Cm󘛴H�7�q*�4�f�O��]Ť���� �ϼ<$Na�“i���: V�?´�_7�My�;���2%��A�ȻCki_��굸�=�z�� �F�+�h�<��wˊA)T��;�����Bnk���������q&�k{���T�=;U���Q��Q�����8�V�f���(قV,-k�Q�w��x���u�p=��f� �+F~X��Tq�݌��0f.-��ݫќ �;O�oL����r�7S?�9�,�̧�.���)���k���rY.�j+���/�vs+j� a|���֎�H
+�"**����l�‘UQ�� �k�q۲�U��/�x�Y*}g�/W�h�V �U
+vN=����[���qq��������^�J�T�J��4F ���q���cȭ�֡�V��4V� `���E��g��ͪ�+��6��� �h��6ȝ�R��d�H-�zwz��H5a�"?;����&Gvh�g�4��@ɦ{���ְاk�?Fwo�R�M�A��q@i�SY!�9�.$����XA������� ��9�vol�"�K��{�ۢh6��S������Y`*��<>>z��|��؞s��M�>I�4
+4Tzy�0�������r�3��U�#��A��n��V�֣S7c��;\t�I �6b��څ���0~F��ݞi�D��2h��e"�q�S�����f`��vS�v9� �̽Bd���ݥ3C�gM7 ?@����]�F��E˜@�Fa(��!���_|���K,��t��v(��I&���y
+��-�d�R}�{ � "�ö���JqK:�<l#�W���N�g�~�q�{lb�V�s�R�/�?���Uz�)�;sR-<��?����|���K��k~(�'ԆF��.�d7�u��`�W�Z���A��nj�En ��I��{@0���-5��Ӵl8���m&P�Gȏ>���fOʄO�BKH�:[) �e� �/%T�Gt:V��B���:�a���|�^pp�]�x�N��:La����Em�� H ���`�'�R���� w�7�OgLN�Mx2�e���w�J�S��1&�Y~��>W֌U�gQ<k��`��x�����VF��M�J@ç�������ۆ68ԭ,m ��Ē����ƭ� <,�����@�۷��ȑ�S!C�Ӫ���U13���P� pX�D��'i�A=c �\f���M�e��1�rg�(�S)�7z���SM �]W2�}#�G�4����P
+t��~]0^1�X��]�[�&�"�o6�,�Ԅ[�%�W��aw̏�^�gFIPj:�^j#O��Ax�J��=��ܡ&���{Q?��K����K�TR��ʥ���xD�r�I����x
+�'�D�]��ʏ7�s�{U����b9�7��2V�Yg�=au�����cՎ��B�yF�N@_ŢT=��OY��P��xg��B�E��0Ұ���\
+&{�8��3��t���bp7��D��?�<��s ��m����`�)�܉k�hHE��j�367<.s��ǃ� �H��}�<��n�
+���/��n��˜���-�&��*c� =^���\�"&�-�j�L
+宽� ��<E���k��v<2DZӈ���۽g�a �p.�������>���k;?�D�u��-�\u����ޫg��0��g:K؍ͧ��B|/=W�t���Y��!�r�ť��:���r|����4�.���C��ٕ�a��g!C��+jlmG[q�Ep2}$-�t>�0����4�Ҿ֛8�П��V�'�,k�� =��}x,���0��8��y��V� 6���n�%E�Ϊ0�&���� $TOؒ�@�Wu�脎�G�� �[X9���1��g�Bw�~�x�W�{���r��M��bE�ŝ��7)�{*��\{
+Ou�>����#�|r�`
+FN�:�Wv����nXY����N2b(7Kٚ��.r}̱)}$%��Fv���h�=
+��$5��8�0v ~VR��Lʢ� ���٨��p�+���| m3L~գ�O}�U��Ż�j��@b���=�m F�'ΎМ���"�^p���^�6�`�)�����>�ޔl�Aq�@�;�h��Ǒ�MX�3|ǃ���o����3�������N�Q42kG��˩,©�o[�X�S���0�s/ EX@)������!��WB� ��L\��nf� ��u$�Yg�=+��Mg�~�$ج��nn-��W!Z_�vRQ���5OI�~B����5i*@e��c��3C9u9'��]w9�A�At�@Y�����dH=�4Q�#1�  ����9�,��>e"����%EcH=]=�����r[�a19p�\��� yA���#԰�vZ����@@*�d�%����B�e�X�RMZ�?%�)���`J\1�N��f�j��"����J$1�lQy� T�xG%G�0fX�e)��a��W� S��v��ٲ��Mf�9�X] )��� mzR��O��r�?�rg�t�bCT�S� v�U��%}�>A��B�h������,)�H�8 ���f�P�4/�n�3��}���奢f�i��Of��X+��m����]c����w �/�ࢇP���Qa$��u !�wˀc��@z>%�aQY�&�,��=� ��W�3`dX�E�O��L�N��?��_Y~�v�W�� �p����꫘Bt[p �,! /�V�^�gTr�±{� A�B�!���~��w���$���%>���*��я���e.@�ə���y�0�k�U%v ~�y,}���FfU�O^:��5s�7(�ͅ����u�V��j���#fᓷ��K����'&twz2��1��%}^�oi}�u���l��-z�Q�P}&�3�c��{g��汑ۺ;7v�m�}��>��E�bÞ�7�3JuS>9�o���S�%1���t����S��yI+���:/=��n!uyn� �N��׋`[xt�h6ɧ���]{]�t���g?�������,������Q��6)�`��m�K�2�u7?i?W� �y{c�+& up� ���2EF�0��:"������{H!-�f!�a���t�����<.rT�N��ڔ#�EQ�<��#D�t����e�
+��=�#ˍV��F�k���ǣ�E�����/��H'ܿ�,���
+"�M����=����.��Y X.KԦK��G���Mr9/�q���>MKo���n�����nj�w�n�d#U�c��\p}!C�
+J����AZuq�T�`6�<�!O����s �����
+O39��ӡ���� pE�&�j8�*��5�Uؕ��D�L 64g`����������� ڷ�B߆��� �m
+ �
+��<�Mh�'^nfz����tD�uM6.a�);M���RpE���Ƚ{o��W�ѐM��t�Y��OI(B#k,^�ͮ5������O���Z�A&��vV\����bÝ���f�yZp�a��z�����ݖ h�D*����+�;��o2.��9������ro�4��c�,�&����'��SV���b��=� j2.#`m�I.����6��:�s&�� ��q� U��n}n!+�����\�R�)/���i+_���߰�z�n�V�z����S$�.>�;��T\�� ���y�&"�t�җ�$[oA(��W`�ʢ0��=��&�\�^=��*)�1W8�ڐZ�
+-�Qz5�E:r����+�Q��\��(H�r']�P�/�g��SL��W��Z�a�T����b(Da���5��~&R���e���.D����o\��p;@��s)��==Ā��嘄�O�����L�{��s𑮁��qoa��˸�jRj�����R�� f#��,U���,l�$�IV�lp�?��֜�D�VI���g�y@VPw&���P-� �d�:��t���9!nn��~9HYI��5P�����,8%�/kљ���֪�eU&�����_��id4x+I]�FW=})��Y��\���љ���S�ŵ{J$ff$�� 5��"-\.�D���Ex�2���&�VS@��:�f]�����$�i|�
+F`*3,�Ӿ���hc�e�4�o�Nj��+1�%\�!��|����Q���m�:S�����K-n�?�E�L��o/�`�IH��8y����.�y��bM�W��EYg0l9��Նx
+��=���q�#�O���_�M��J�Đ?�>l( ����B������ԟ���}�_���[�?��#x7�i�γ��
+Gi�j����z�K���ؤ�q��¦�Y�u�H�\T�Z6/4{~*'$�CJn|SS�P�s�/���`-��m%H��Ps_2}�K��QnM@#��:�B)JE�u^��DaS�\n�e_�N��h̚�� �o�[�02�G��w��@�1�GV��l=�����9�YQ$����"��R�<d����Z}v��D��]2£T��M�k�U*!�S�K����a:ȏ�ƫ�ff�e8yɽ�d1�@� ��ssI���`�0�igD���#A��5�C�Zw�i�_
+V
+=�l� @I����sr�|�ON����?T�rq��T�s�u��n�xnW�������(!��,a#��\��蔙��[Y�Y!F�R�H���ZɊ�3�F�TI��H�)Χ)�:|Z�*K�[�����J�uӯd����նyv��_@��f 2�7��Wn���L��O�@I�Jfx񘈧����]�^�ͥ�� ��n�tڍx$�YU�Q�oI���Ȗ�Ҕȥzy���r]��v�����9�=�+�N��zcX�#C��l!a� �(��[�ԩ8�ɉ������� ���a�a���H$��V���;�Q�L Ru�ф�<'��m5熾ft�H7ٜQ�k+\�����[�����9�rI�<��I�`�+�,Pگ�k��o�_*�[Q �ժ�`�x�UsH���(y�ךN�8�ml1� +�1�Xr�$r܏j=f`�Z# 2���V�w�װ?`��NT#VLPs�8#��.�W����/�ά��m�����"����i���㠔��kTL?�C2������M���D���a�j�V��6� �����F��8"=}yg��N����w�K<\��U{=��։j�6f�����w^V�(D����U��l��U����Ե�NcKo�gl�G�\�#&��V�(����m�z��9�١M/SVwF�o)f<�*�Q���h(J� ��x��.U�!GxВr���3��ѵS�7�F�8X�B8 j?jp`����3�h���q%`�5�x�Ǐ�o�4kd@R���Vt� l��S��/;[�Y��ý����؟/ß����@�����j.m������m�ڼ�Ўc�ꮣEHGo�3����gM���#��4˯�id�A�:/�h�H�A����fm*y�+���D�,�&���j ,V")��Ȯ�'F3Q^Ip:fa�,���;dy���O��w�Uc��c�!\��ԝ�_�0gM�w�{>��8ؕ u� k�[�mOݞsO��o���ؘ� uˊ�Qhq��V���e.���$LX�V������J<��8i\ɨL<z���8���I��c���wJ�S�J
+^�{/@˃G��{O�<W�2>w����,) ��}�>�hl�uv�gt�Ld�M��8<�n�#&ę�������^�F�f;�����޽79.�dʂ(�㤼ɫz7�uz��E���/���V�/@r���9R�J�-)�6����r�0�?Ue/���K`�Z(�`���'��v�]���Uw�}1��N#�'_ieF"�f
+�u�$:����a.ϕ#AD/"���X��1��;O�X�bb%yl��qu�خ۪}
+6���I��.��.�<����;}���!�s Vm 5HiW���g<�O�?�)�0$ګF��y�(x��n����&1Щ M�P�gk�)&�)`��R I����_U�j*��5j
+νN gR�O�K� "�M��Z����H����^�w�N�3��W�P�G��ە
+��r�o+�/����v�<��곯�����_G��SOE6Za��/��C�s�*aZ{)��32*� Q25�(�c����~PrY�3⹒��|�0��%z�M�Yv�}C�H�DGy>a�����h����
+������=<�2��(sNW��㘮�m:#��nJ&D�\,=�Y��/�` `���I*"}⟷�7!rv@�I�[�2i�U��+ ��M����.A&�^3B��J��*����h k�[�؆�Vg�2I�r����2(�Iy����"�VJ�Fj�ɯG�����_����ْ�@F%��> ��Z�|�$��7�������>�!/��b���x�l������b���X�~Y����r�_��\`b�h��xǃ��Y�Mַr����_���6�d���T�������E��*[�E[F���Y�g^T�mu1fnՒ�ή{5 �k�r�{tW@��F�ڋ��gkE�B������f�N��?c�9`��Ge[ "Ȍ�Ҩ5�d;���M�,�B�$]�"��GV�/~F��1C�u��hjF��e��z�w�ĦF�Mx&�y^�� ȌB�k�CWחm�"m����N��T<Ę\��襂��;"�jG'�YfkE�Kj(��������Ȳ��m8��}.iG�R �|#� - �C%�o��l�j�(���gI4rw�Q�t�_�:;;p�ǻ�~���gx[�93�@��0w�n��ʍz8��`�
+n��epr���k�m��|�crK��ۜ�����iy:��U9)��R�eݠ;�!]���2��:�-��k�D{��|"@qZ�p����?wj�7�%�‚�=����\�c��&��>����g�@�jW�{܇N�}�T��a��Q ��� W��J}/6}��Ʈ�<�ߧ��Ѳ�����7���� �by�)7��09$��A{� ��nħ\"0"�C�HF�j��;�Luؕ�?`;����(D�h6݉^
+3���S�9q7�'(���WAN� p��O���aBYzy�_�p����z�,O��w��a�J-��{Y�� �^!�v�JǴ1,�Ω� |��]F[g�6L�k�ΌF�7f��Fl�-�e^��j*�S���[���[j�#�4�K�Ǧ~��p�@]����t;���w�1^����]];��������i�F����R.�Ū���5_O�h����+�\�L�m���+����3��A�Z�{>�6.��h "����x�Ғ�#8�2�<s��#�}��c%ؚ�Z5�V૞k6��'����(��я�N��= p�&�֥ ��C�EY��i6�Nf�at`Ä�� �����ɱ�������@� ��֧���V��.opT�%���K�?��P���>���Ė�U���:O �u��WS�]���7ρ��Gm,�
+�ܡ���JP�k��jjB�ē��J�[� 2��w���5��D��bn�h�4�_f�����9ӛ���HW���‡;�a������l��-�#S�+��-J@�����]�a|R�w����/HX�'���ktҵBc�/� ��孽8 jN~2Z|�„�0��cxJ\�xնh�-�d��/�\������< �%
+endstream
+endobj
+858 0 obj
+<< /Filter /FlateDecode /Length1 1360 /Length2 27857 /Length3 0 /Length 28815 >>
+stream
+xڌwP$ʲ%��:4�����N��:�0�����; ���s�}��}7b7:��*O��ʓ���J���f&@ {Wzf&���
+���������\������\��b�`����@c�?61c�?n��7[3+�������� �����_��<1cw+3�<@���G.����lea����Z�L���ܜt����V���ycWK�ݟM�m��V@W�����tuu�ad���`0�sapp���xX�ZT�.@gw��r
+�v�� c�#�YZ��cVu0w�0v�l�L��.��̀΀?gT����@����q���j� ��M��迈���665u�s4������[��r ���tc{���m]���[���q�;qc���2��O}��������Յ�����
+���s���f�vv@{W����r���u/ƿ�jc��a����������������܀�b���c�����
+`gbb��f�@OSKƿ�ռ����������0�S���������puv���������fV�����=ܿ��������t������Gx���>�����-3{[����\F)i%m)ڿ �oHD���C���gag03q28�,���E���_Y0�;V�����O�n�v�W���5Ԁ��Rp��X ����cbg2�����-�C�o�����!���������(�_����Y�z� ��W7�?ڗw�3���U�ϸ�ͬ���'*�j�g��-l���\$�<�fJV����H���_fkeTrp���A�331���T���y4\���o�gh��Hq{S������`��l����v��?ch��[�F{�?!�?�������'�����������d���?����1=��p����߭�w=� �{�N�/�j�Q���:w�� A'S�f}�v~N@����Z#z�9oo��HT�|�}3�W�;��9�52St.�8LK@�&t����h��+C���ƅ�T���1$��8\�>�|�|T�! �V1O��X�H�o���C�JOC�v퉼x����;�I$O �w�Z죳���Y���҇K���C~�69G�#r�"���SV��<����=�k��l{B�}����|�ۀ�|��
+�C:2j�C*���8�-�zCf�S�7g�� �b�է�-g��Э�\cZ� �Q�Rj@vjS[��+�g]���L�6H�ŏJ}��p���_+Z��1�����my�`y&�<���_�>����NE�>IS��l�w�|�OŇ�U�wL�R0U�l���*������$�V��/�1EE�K��R��J��s���ڎ�ݷ��<���& �$W����4�]���B��L�K45�A4�� �n���3F>$��m�IP���}��e=Ђ��D$�w/#�T��YƦ�/�f�j4�H�y.����ʵg��ח��fz�m�y�P2��ee
+/~��O ��q<�X>(t K቉A��݈�e �s��¸��`[.`tɃ�+�b����œ�^��{<w��D�� &9ʷ�'��@��0�T����Z�О��gg�����{ �mC!\���|���}�Q!�|0`v��e���)� ��~�f��:���_씂̧��;� ����3�J�O,Xfl�-�'�$�O3�~m8"�j������i)��E�$`��QԮ�ZbGӊ@��! �x�bfO�� ���D'��|-y���^=X��N�u���;%��3nXOa�^�� ��*���c��6�Ԍ���c��D�#�G��@��<�f8l�ĩ���*h� Tp��C��KH}��RDa�J�G�>V�
+���Q�fU�k@Uk] R���!*�bT��5���^�W0�����9KD[�� ��C8i��:��`�]GL���u��M�O�J�jp����zJ�R�4J.�E�^���6E}�zA��>��@���`gO|�!\-�u�7�����h*�C��[eL��=�o �^��� ��Y�x*ڠ�[�չ~ɬ�ғ�ˬs�� �[�W�{�7-� �G;�f�'�_���: ���{i������cj�O��]���u�-&���-����ؘcޥ,!��jQ1@:i�E�ը�#|��L���T��<�h��m��V�h�{5qik�Il�rq��; �-��3���� ���W�D)���G��Wg=����7�+Æ D�p�����������4r�����F���ep�idW����!��PQ�7��+�£�D���4*��_��� ��x@pϽ?�m�� ��I�l���"���^@��d��\����T�|Lr�C%Q��\GOd��W��/�A��sskLj�ܳ �B �_2�#G�@Gr���u 6��B"Њ{���X2V����:�k�{����zGzFq����%cAk=HhD$=��+zʄ��YKؕ|������'X� ��j %�\;M��w�D� 6-�9�-�
+��n���jT}�>N�
+ �ѣX� ��q7�h����7¢q�����5X��jtu��#t�u�%�!�Lp:`���ÒEP���M�_O�FV��tٝ�B��`Ԯ���E�+M��x,rv/�C`�4�1�����*��T���y�=ҳM��M�d��K<xj� EwWv7G;��iGs8��~�G��B��]�&a���p�o�V-L���zB��$1���<d�����NQ�fp%�@_`#u3�+c!�a��̇zi�F�����$�M����l���.�������[=1=\��8�V��#ۃu:�n˃�As}���{�X�Aj��4QT�:�'YZ�%���݁gB<n�g-�.�*���3�<~�7�mg�I�1�pJ+=X�dkb�����r�����M����Rp����t��r_
+�P�E�� ������,�fN�9pBeG
+*Oe�����?])Eh1�:�S�ș�XP�S���,�i�u����|�Kن�sv���_��ql��8Q�y���a͝D�%���ԆВ]Y0�6���("قB&�슨5`q�ngt�ZU�����$�����VML�U�m�oUs�$�T'�ZJp��3�'{[�6�w�!����� �e6�u5�Xdl�O-?6K�2�m�!�P���Pyc��i�,:H�p�!�‚O��e��}�A�\m�*?�;|O��3���+!V�ӷ�tpJ�����qW PC�@E z�+܀U�� �x���B^�����[�y(�Q�G8�1:a� ��m����%�� ��! f �Hpo���J̄��1���aU6Z�\����0��� ��Nm����-�bA]��dWb:���C����'ٸ��x5��Vԕ3K]������$��g����k���S+G��X��C�N8Z��V��N��mD=p����54�� ���jֈu�� sntr�?�S�l�<���2��0[������CJЭ ��%c��ۺ|�vm~���T�ډ�"6Jy�p��I>/?�'_`0>�� � ���y�'�Vu��r'a�_�[.���d�ܞ���H�\�1ַ�ڡ�c�jC�е*����f7�x���O7q��wZ�0 ��`{�[�e,�������S5��~����~C8��^��.e�VH{���vI�Di��(}hq��:��x�a����À.6�P� �}�"m"h��Ƽ���A�v�8��1�K�Sʺ�-�jv�z�O�-��˸҈�� n�
+��l5s�Bo'�nGF�ۋXc�?�?wn� ��v��bk$'q��U�5�틗��qp $/��qJ�� �.�t��}�gk�5&
+����l�s��-rx�?���� H��E�ļf�.���7��LK��}O���� �_��0Z�<1Md�Xޮ��"^ � 4!ԅ58k<��1I��e&��AUXJ�3�F����$�3�)0�|;�i�<h&!�
+eT٪�5�����|+�߃�:2UNs��(�X [��+�#_{�!��ы�]�겇bU��4�8i^�^n�g`�B7mv7�o��zqr\�y�9u~���f5��蛦��/[�����@1�*JksZ��d�G���{��}~��X*��,h=�呍_< O��}��*a�`Q� #9�qD��2�X��|�>�u0���׈�uU�6��-j yyTQU�3��,ѯl�� �3��̭���Lh�+�l�j8��� *�@�b�񝼭�
+�\�;|r�� |ferc �u+�
+��e*6��{�hP��6�r�N[�ݻA�œE�� �:��o�݂�L��!�&�afV0?s��7������ #X8ICKI���dY#M|t-���U����mc�8k�M�����b�K�{�n��� ��ȵ98�C�ۋ���ktN�Ԗ8���m\%��{N;h�[���А�0�RJ���!=r4�K�2�hK(�b���U����3Þ/TD�V}8�m��
+�mn{�?��]����vp4��>�����u ���/�/R^�t]�m@��ld:��kT+f�e�H�����}��!񣓚? �i�!�d�d�V|!�z
+�{<Dї�cl�`ֆ=ݒU�[ ��1�o&���2G\��8ל4$� ���UhO�d7>��W%��F��(���AQ���!�H8�O}�9z9H��0�Hr�6' �aCs
+9��BF�(�Q���‰���������H�ԖdӬL�M���Q{���О�+B���2po *�����
+�t�� *T�Ίy�шTf��mi��8 �W�Pk0�TM��G�A]i+">'�݅Bm������ L� Z��� #��y{Z��v؋�L�Y�7�Z�WP���1f���˯u䇔��� >#* �4��bոtӍ=�gh�J#���%�PI<���q�x��6�|��4'�V:�9�)f"��N�]?�I$���~�b$Ђ{U�Y�����B}�0��~`���� ܮ�^ː�������m ���eGZ������̌ ύ���hY�4��^gi.rї�WdH���e7Q-�K]ǜ_O�f`�٭�]\n 1���8�)"oI�����D|T�����-����X�y�^��p�(�X�U��4�B�#������5{T7���ܨ��+k�.��$�f�qC����� �V�=��qg����D>U�f=�q]� +���>%�Vռy�������"�;��8��!�����U����7��}��%mv�F��]瀱/�z���-�u�]w]��A�����Uaa�C&EҊc�賛�?m��6Lœx��P8}����$'B�gm(�-��T�E���<�D�z��/> �Joͯ�|�J��� ���^�˥�P� �Mл"��g1@U��m�}/��wEȲA��!�� Nz�u��O���~ׇ���|�o������ -ڒͪ���9�+'���/�4������#5��$����-�Ζ���zګM�z���L; }g]A�=2����r2��t�+S�����?���#�!���EjM����o�=�1&1��òE���,w��שZJ�$lۃ����gn��{Ud
+��I �Lvgf?���NA����mB%Eq6rÅ)�@e�pt@ -s7h�����{ީi=�4[Yq����P�E�$��[���b���U�1��!�G�^��a�LX��F �D��gT�� {of�ĥIL���)���C���N{f1�ي}P���ԕ��-f�O%����0rK �7���R�z_m)�?��'L`�����>�s{��P/� ��_Iֈ�ط���O�g�)�Fe��6!s��5-Tؽ� n��� ��|Q6]���y��}�q̙��>�q�T7�cف����K!4դ������>]�v�p�߫M[!;��!18��=���b����M�c;��:@�o�P����:D�V����N[�u��q�&��.]��t�5��"(=�������P���!�DE��TՉ�3|������|<LW�[��'�T2��MnZ��[%›w��]�K�~u����ڠ��7�tf�!���4��/�h��Y��}x_x�mf pp3��p���>�. T������E>n6n~L0�5�yI eD��_�ʅܕ�s���M�n�{d�e0�j)܆hL˝��I j�e��p�8�X�u'��b�:�?����~���}��4���,�]N )�(\J�{7����y:�rf���6*�{���E@����M ����t(�}�j��+F�L�����ypQ�?�Hi'G�}#�v������ھ�d����j�Fwye�D��̮�F�]w�3�3P�z˵4�V��$�]N/���n���}#a���N�d�:�/�(��ɻ���-�#YE��OK$��� V!��i�8���x��,0�#�T_��LF��q��H����5J#����-���P-���,�dOm�;Z��AH��L�Prngرj�Q/h��r��ȩ��)� �)�m�}���+7��k�g�}�ִ���q�@�o��LU��� .a��=M�c0�{m>bEۥ��q4/N��C\g��/���>�)�7����_ wյ)0zW6:�E��V����^9�7uǢkT��( Fe�^�����x��?�f>j��F�w}��)�Abyp�8Ո㲬��s\�!߳OJ�2:s>2�^�m��\� &�V��%& ���m=�(�!y�67�wH��5�omN���������W4�nߓ�ç���q�IU\(��CQ�Hd����^�[��%��#m��c��o�]�O�5��V�)9Q��/e9��ב�!�Z��6mA4}�0�&��<6ۂ(�5���Gz�r�y#���[}�BH�jl����n�@�9|��U���B+�i�M��Ӯ��B�)֧O�1>�3�R�v��� ���� p�+�}�
+��a�R{������7!}G���z��v���~t]7r�]O�0����M�m8�K��Z�A�����
+LT�V�Og���V��M�7M���A�U9u���/4%�SCp <�;���j��J`��/��k�7���ތ&���x���M\����H���qh8!Ŧ~5H c�cRZK�Q$�FB��y�Rכ�[����)�М�#W�&C�oX�=�*��� ��&�� <����K�7�A���S�N����e�����1��HYz�)S꠺��A���?��YY�)pH�y;mt�_�qL��e�����y�V��?_���|�IA)7=�; EQ��/���驍�$��m��� )�ͅ��ܧBu��ܗ���W�_v�i�s�3��6+��UQخ�|�hi��ꮳ��z��~*�%�*�<PR�W*�/�Ey �M@3���ea~�f���FrG[�Z'��>����1�<!���)�j�OLeNe�E���F�DK��2�F�ӵ�qa
+���,�(��qA "v3����1c�_��F8�q҄�)6����Ƿ�}���О���<[b�A�@�T��8��#uI���z�$�ǽ�7 �o3�.1��DZ]Z���J~)��2��G2�F�KT``,(�ȁ�orquj���y��Ɯ?O��� Xм)sg�� ����eq�4�����†xT��ui���[�/MOg�7S�{�`�U�
+�d�Y���=(+�GXH�8�S >�5|���XW z�=���@,���ʪ��I9٣`��4;�q<�,nc����?��a��Zs�G'��Y�>�,���j���問�06V�M��$hU9���Kl�+M�Z~g�lŊ�I��^�/d��e�6���~[_٥V"��r5a�sX�[��6fi�ꨟ�z��hj�Mzej�X'�n ���L2��ET�wI�~}����gB�o0��Θ�?j(���� 7�\��^�l͚y���� ~�(k�Y���z�E��&ĭu�R �gt�U%�n�\B��ax�ա`�<��k3�9w��&�qǣ(Goy�|�snv�ߓ�f�o�&�����1P>��7��9V��cT� +#��2�� �al��.���Tm�p}�6 ���A�k5��xX#�a��{`L��ԣ��*6Z6���@yK�8��᠝�[h�j�����M�g��8zIY�w��uL�W���qq6Wt-CL��س�|� �S�JT�������=��5H&n%������b��[�ם������\Lv���V���/�N_�Ϸ�X�Q?� t��h�s�#K�#"��z얉˄�9%K�;X�*�ʭ� Q;!'�jM ��Z���Y�~����t�m)򬥷�L������:h5�P����?<Q����+Z� ~�$����𽶘s��SU�v=PF �w����n��~����J�X� v�߈�kb�t$�ӍO�kA}�<-���I�ԥ���4
+m����V�'����dQ�mD�.!-���� �T��)������7<4����p-5���YF����6뽈�醭�3���!���G�obH�[Ϲ��� =R�ƭV�Ֆ�!/ �"��4�IU�T��s>m�b��CJCd���hC���9�5�N7� ?\��C�[}s�sm��^[��%R��Tי��԰���"Z��k+��| �mY�y���R��(ֵ��/lk!gU�7G��a��
+��w��'�U��g��7� \������"YIk�mA��gÚgJ��X}p9�W� g��'���"�{tѳ��r� iy�y�ny�0²��V��6�>�I �S{f"(����\�vCgӇ���eV0� �>� �e�b�� Bk�� m��X4��/�4{���*�'�U�P֓˝w��ea���uc���c9�Ek:��B&�&��Ơ�.w$�o$�'MD�
+�9�U]<A�������B/�Tу��(緥�����Ck ��fm�<9����[�gK=��]�������yٟGi��n��H,&Q���K��c�F��<��K����Y;�V��b�K#�H�z�kz'��Jj�r�Z�C-�TƏ5�8F�������!(ָ�~�� )��c��U��5��~Y��� Q����X=�� о�U�6\兿� �?0����'��ep�b5*�@�v�0�:�J)�h�@��F�8��h'�k_*%Y?�,q����n�����O�f�Э� &gPT��5�}Z2q)� EY� N��K�7;*&�e�+ø�����i?>����֬ ��n�"�9c�cI��t�<^�U��;=���r��Q�VBCf0X$�2M��D~��QF�r�v��@�]g�� �{/�y6]�rQk) ���[k�͟���E��:�<��z/Mw�@Ʀ Í1���m ��+�H25�����l��7��e
+�ֺ�@pXD^'[jB��(P)T�'��W�fZ��aNR@�m���!��t��dI~8pG\�w&4T`�,�D��;�Ω�[���v�yG˦��鏑�D�+bA*y�E`�0�ÿP��>g�`8QV�
+M�?oTY3gn8�2�m_7��������D.Ք�,m]%���|Ó0���m��rBMz1�8��Q�U��m�%�${W���P�o�6�J�W��"��� ��1�d,'�5T)�ozH7y.KR��Ei�{)��\���1?�N���� p7��u,��~Ǖ�]I3���4;�~�r8�I�� Y�kNr��}�Y���<8��A�� ��;
+mq��}���'ߞJ��<D�8X��i��� �գf{��.�v��,�G� hH�L ���(�Z�1�}q���pA��%���h�4�nE������0e�v��x�=��8�S�%��U*���=�
+���X:�Q�*6Y��I�}~��|���;%�;�/X$�dCx����j�I7�O�ߍ� +�kA���-4����O�67��N�c��1{:z�9�w�zƎ�&G��7�b�W��口-��gX��y!х�DUKu�ߪp�H?�t]�G�1���z�� �P��1�y+�{9q(��ͤ�������w�B�&����@������~=���;7$.RE�.j��QP�CD�n~-�J�z��6�w�ݎ9� nD���6ʖ��|����E �UHP��{c����\^W5mҔV�K,z�Jt,�Hɳ�U7��R
+I�Ĝ<�=9M����k���B0� 1��|����+PFҤ��0S�g�:�~贯1�lr>����m�]�|⍾��4�X�KƂ?,,p��1o[1v�ehK! $m�Q)��ǫI�8� r1b+ ����'�Y;D4綠�ew(��6wNS����^� T~�47u���d�E᨞�Er&T��7��6Y�>8%�/0i��o�e�&k�)�2��VMs��H��Iʠ^wGm��*;10"���xD�~�|@��9����I����m�-a3�2Ā�Γ��13,�Z =p ��*�V���^��*8)ݷ�E&�[$v�O\k����К@.U�d*�x�*�/��� ��u��͹4bm��04�3
+��� �Ò�/�$i�=�����v����A�^�����L)���y]����X�j�Ԭ))��x�j5� O]2L�6����a0l��K]��w8� �n`�iUŊ1�]��a�eغ���xOe�D�x:̈́�-<�m� �.� �|N�� �N= ���1��ps���C���A-B��`��)�=B���K2�E��!(Z1���脵��:x��ĦP���46i��Q����i�\�j��3�)��(�
+��d�- ��� ü�=��h �I|�N$l��A0&�<�|8'.�J�5�t�>[t Bj�˄���h~ު�3gi�I'� �1��/4����d����{`S$.Y��X�o7^��Rnjд� >
+�Jn�V���g�)��O���̢ ���m�h��[���5�ak���5a-ֿ�$N��B���[��1]�f��y6O�@y#�or����GX��h`���&���;�lZ�P������<���o #�?U�جk���� �@0wL��X�L{�_�/hϧ˛�=�b
+�><���"�����~��Q�2SQ �_�b�/&ҵ?S+�*D�;��+ 4���Y�M��,�����G��d$��ކ��gd"��K��jҮM� C��m��D�"�_�w�艆���4�z(�D��C����V���uF�������yJsW�^(\TB{�(> XL܋�Ã6�Ԃ]U���{�i��ҵ��!��b�����
+Zz�b��P����f�E~6�)�R�u�|S\T����I,R��_�i 4䪿�����~�9rؙ� T�(���SB����$���&��iD��~��lY��̋�v��V|��Bo�� C�9ā��i�^�Z�e,����%?���Ч���c���c2��**�MFD�kx@ �ʐY���'�r�E8��ߢ��C�i�,q�����>�u��A�(ֆ�Lo�����t ��?���ƺ���3�S����ˆ�H���6/XEj��8� mE�!��?��ώ�xs )E�I>RG�\� ��1�w&!����l0]��i�K[��Aom�@�K�p�G��Gl ��U��NVYg(�#��r��22�h>�U�l%�����G��}{kT���}M�E=e���(*���F���ae`9�\�ڰ�6Du�97��e��אs�J2"W�>t6#Ŕ$�<���E�r�ͪ~�G`�H�'����CS-/��C�>�o��_���E��P�mا�n[)Bw��̣^e�%6e��V��v��������4~��� ��1�}t��+��KZ�"
+�>�H�F=��L���oV��.�\�T�;9߹cҗ0EB�f�S*as�)�+��i?�}���I}�����q��� �p${kI�Otl� 9��m��OC��4(�E�g��K���>�(��~a���: ��͂<��/y�I/ D�.n͆������ ۞��(�|��Ӿ�2���*C���Ơ�ZL���DN��5�&���P`Dr�w�{�J<<�8�D�1.��*6��x:�?axw��$����̈́G��R[��_)�T�2��|M���1�B� ��*`os�u�M�N��t�����<X�8޷IR�J��ji��sבz:�>1|^�L[��S�:�ѱ��3��_/VSh�i�N:����>k[�Y���Z�P:���{����<~%8�!
+{Ǣ��"�����es-n9'���/�Iϥ��n��d�C�G�ԣ*��h��1�t3uœX�qE��SWi�����N~�1��;��H�sd��κ3y�g$�\�L��lL��d�$BF��x$]�)�m0c�ĩ�`�W帢x�x��&2�r��Y�|ZKcd$h�K�,3Ֆ:�1��^��C��Ի˲��o�����t�Z�QH �,f�wo2gX��3o���&~j2J�\�� ������r� �-�edmM�C���b�k�hK� S���oC��oZz����Kx�;;\&����<��T�74�є# A�"K�v�En����G/ :A1�l�%?Ө?��_�w�X^&�� �� ,������<V���O�����jS����O�‹�ٟ���?���`�MR���_��!+
+7� Ҁ`ȫ��?��qhP��M �ax�3Q��(�͸�I��8�1��F�R�ӂ�q��`�ZŊ��Lp�5G� �Y��H4c��ҹ ƯI���Q�h1�t�RC�/+F��H��TC��@���_��-�fDL��E
+^=2^X3:پ�…K�n8\�j�Z��+�����r���-/J����^4�K3��:�+���l�c��Bu��8�&����XV�<��K�G��e���Ԣ���
+�}-&7Dw0�8Aw�Ւ�U�� ��YI���JQ��(���m� �ʗ�p�/�w켺�</��u4�����|h�4NAm�(|+1;eD����1�� ��@r�=���U�1J|��#%ލ>�;B��w��\�U��*��9�4,��ډp���B. /��^p2w�8\mz����0��I4��o�d���(SPD�ә�y[ʳ��������;UF��=�1h��N ��>T<w���3���W2�ތX �.��N�_��1<�VJ=�A:�U�,4<�w�6��ݞ<�gC�jx?2�z*Д�X��8�LS�=GS��Kyw�����t�魳d�S2CR�'���;�X2�T%�N뾔�ʯ*>
+#��n��>ۮӍ��W��%���G����+nS�ez�$W=��a�f9�aڠ�Mb�T e�Z���2�Ц�J�)�
+$8�v���W ��,������ŷy�v���ń�rO7k���4{��Z�wX�b � ׮�W���wS�'3z�[� \.�-�dU}9�� ;C�6p���8���|ùUφfdZ�P�4;����5�2*!�`�(E�W!v��ف��꓊���l ��'c*|�m`�>(�:OÎ'A��[�ȳv����z�V�A#ٻ�~S\shK)� �) �Ϯ'm+^�4�K9��
+�$d�*�9�l�r۫a�������*��Ě>�!��^
+�M��7f��|'� ��}=:��7l}�I<�Uh���$�3�RP���\ �(A[������c��t*�B��h[��vU�KQ��Ҟ�Z �:���U�+��-3z�QC+�� �ZO��X�\���$�U��{�*EA��Ek����d�T�w�Y��cX�1�0'�<w�fu%���O�DbA�|:�g)�|�N��{�ޓ���x(v���8�@ޱ8$�Z���}�ƶ�
+�)�"�
+��#��7�?� �Y��l��8���/�pM�� -v��*H_�%�����r K^��w�]����a�ya�Q�2h�d択b3 7��;d��n���d��:>�R���7yW�kbyk�5!ݔI���9��<�� )�����W�����Ds�,�$h������g������XV�\pW�;��"� @S�̆�(s����,
+��G@R9�b8����FMsD��0F۹�}�ۆ��S�?G0Ҫ���dw�q:���#%���w�YcUw�-�,1�h!��^y��h7�� ��׸�mxGK�l�삗���V�éƇW�@�����lz�+V�Ð�Q�2H����|}`i�q���DF�b�Z��K����+��qr���}3[o�*;�YN�gxS�U��ܯ`@��Sco^]$�%1@i2��C����Y�������NߗA�܄�C����ܞ�l%璒���V�dT����l,�sg-s&v� �R���MP�aU�|�Fd% ]*4��F��d���2-�ݡ(��~�듁v�-6k�-,W��ݎx��KLt$�����qm�Z�>�����H�rz"��hW񏠤�7]�4~��l�c� �<�_ Ie-���|�;QZ2g{��j���-Z<���!���= �J�M��M2�`k�����ᒬq����������d�W%3��H�� }RS��>�K����Mc�c�����(֢��c��Awa� C�~-�B�����L�e��e.�����M�2�����U�0'���e(ɓS ���vN�=��S �1;m�P^�'ջ͢�o�
+^������r'��v҆¥t�l�T�X.�w~��j�H������)]����CPJ������􆦆[b-ކw���!�U��fYЭB�Y��?�L����E�D���xU�R�gtl[���>Ɲ��S�0 ��gX\}L�񵎊^a���4��Z�N�^��~��wA^z6>S/U�B���]���_e��!���E�A $��C<�� �� 3�*
+�@��h�A�5�t���*�0��d�7qr�+�@�@�6�<� ���-f)��!� � �1d�U2wsgU�C�b�ğ;B�{��93�.k��C'�]�z���6L�:�IY�$�����_XqL���.V��|[Ěv5��L�-�`�t�cx�z ���,�k��B9։��f��gX՘��L�P���Z�8�-,/ݚn��2�c�|�N;��I�P�"`t��:/�\{� ^���f6�ku��?\#6�1*-m4��6���d�̼L��yT�P��M��#�a'���� �M}\z��{&�Y��'5[Pq���&L@�C��Q?��;�v�]��v�]�H���!f�ߝ�1$�!v#��ˣ��+�����"y�R� �W��iB�`��̹�r�m+�� �+� �c�E�ȴxB���ܸ�P,�l�йI��"�G�|U�:F�K�-�����x��e�$ݨւ��r|�+�Xz�]F�c&�Lz��u�M���Y�F }��֋<����H�5��K!E��૊c܍aʮ�xk=;���Z����0y�<F�oYD�0)B�3ҏe���L�e 0*@�爗��� �HW��ih�0d�:s���v�l=$>����C���m��0џ���pu"�A�Dl%Z�+5}i�:��'"Y=��X[��xfA�ta�UH|� $���[���?�
+\�7( p�ѿ\Nf~G�4A+ۊ?�n)��J��{��"51���}"�X���&�)�)d�-2Bݘw�7��G�PpVb���0 �<i�sy���ޝ?\�&�R���H�S1����#�{���LM�e(���9`��_�(�}���Yl2�éE�/���,���3{��P���LYn�P|�����4�j�A� 8[�� �o)*ғ)Di���mwh��B'��M��њ���3-z��G�����Z�s�C�4k������
+�%��@/��4�)-��
+�':V�_�� ��ll ����e��l�ˇE��*�*Jŭ` l���ſ.y&��Q'8�~8�� �T_!}Qo64�D1�Ҽ�=�%��xW��ֳ7Ƃ�˵qը��s;x5ã��5�����p�b�X6r-�_d�R9R
+Qh�9�t�c&\*��g����uy���Y�^�=ojY|�+���eo�{���IOm�,�s|�p��@�ϩ>n�+�hc�۸キh<L�.��}য��:P|d��d\}� }$6cL�ܑ�;O�k��VD�MN/�\]Ge�E~�|p����|D�7�)z�� ��E�ߵ5]^���o��7x!-1Ĝ����cbq�z����jv�7=B>�Z.���)��[qt�ڃ�u��Y#�< �|m�5���e*�八�x. {��r�j��8H�᝼x��(.� ͏A3�AM �zK�qbݹA>�l ��Q���ۿ�%���{ݞdXa&D���wۄ�W�
+��h�,]�^\R3�^��9#�������U �8����!Ծd�U���ݡ�DXM&[����>�)�!�9�1i����o���k$���̰Б|�T�3.���r�� GC~-���Q��e�Z*!����ި�p����l~�&�3��_�%���_#])��
+�=jx��L�|��i��<$��)f��ZR�y�!h�}�Jf[�Q�M�{��--�U�#����O�ؼ���LxЧ��|���DҳR�x�y�&�f�V�e$��W�/z�B���$�& :���(K�{�$�'��2ᶓ��]�]7]10�oR���:� �`0�o�q�~^ո0�\o��BY<=������~��w�ע�=����o�ޝ������+��ecn\�uzg��I"�P_Q<���XxOIr⏒��/`��nf�zAW���V��eQ�!�)��A+�ls���eɄ�%���s)�E a���m_� p�|�L����&����^gCL�+Ͻ ﷼�p�����%1��I�q���� �
+|�Y_�-�~�҈����Ŕ݆�C�&�9'py ��)��[�Zx��Ȅ_�(�"��|�RM��-,�i?,9R/�'�� �R�Ā�J{E��<<�6t��7(�-�3��c��2��=0�_q8��P'L�� ��ݎ�uk�{ �S=��/c��oĬ����v�</����Ix�K �״B�p��E��z�F�I�`�`��h�ݖ� j�ȳ�D�� .[p T���~%P5��P��n`X}G��Tuќ �Ĭ����4O��w�4�x�)eDT3)Z�[5�����U�w2뵤���Q'Ā�����0io��� %�*ݩ��i#J�"�̒/i^�`MԖ�t`R4�W0����� R1y�B�ѝq5U�LDp*�lzI�=Pjs^���l���8�,���Lޤ��T<!�K�DzPȎ������Rt��7�8�n_���6KY�;���X��N�2�2��
+�h�J-������5��_�7�D�� r�d aA��Y�S�g��r�W�-\�`��1��f7�8q,���nd���/���;*p��Y�
+���O��|�~S8�Mp4=\U{6������p�y�_�\B�v;)�j���X�<I��6�5���::�h�5d'Ů�:��;w{�Q���Ň����]�w�J�2����&@J��=��L�YE���/�v���|ԛKHU�|"��ℯo��M�!������^<��⫙�C�j���hޱ��z]S��[<�H�/���KC���JF+�պ�\o���??��ɠ������Q-P_������H��^�ȊRl�(����qց�f�30�mL�u^�����q �h�ՙ�#�4�.�ȳH�^k=��֧��y��w-�mk�3���0oϞ�J�+�1kق�$��ack��qP*�>�e��aJ��
+���j.ղe�khH0���%�/p�5��v0ki7y��Jwc��偻����l�7;J�fFۯ�^�K�@�Dd�R�'�z��7�`r��ytS����.�������V�ʳ�Ŷ$pA.�"��l��\�4x_���n���%G�O�D�3L�����D*�3^\WW���|A�Af�P��C���6O�5֝�+���K�R�$�N"�2����Y���WD@ފ�4(����0��{�)�+%�F��+����l̿�2�|���a���d����_�x�eI¦i�y��6�����B��]ojMk ������UEJ�u�"сF�(��CZ��/���9ţ��g������&�ϹiN�$���:!�n�%Z�;W�^&�����v���UF^�]���gf̍p;d�` �Dr�Z�k��^�c�i�u���}�uSC�p�Z��s��n#.��VFK)��nY�G��R����h��(��s;� 4�p3dvP2�3'�B�b���5�fgt�y�P��\�$���`�IǤɨJ�a�(�� ��6�D�c�*�a %J0]����Ȁ���� H�U=��t�q��|X����� <�'Ib�X����g��?ZW�=�4� �裟N�#l4��n{��0�yt�+� �B~$����8-=� ���`�۝G,)��K�V��ʘV�)��6��W��R�f���H:��b��<�BRt��6�5&L���PsZ
+=�"�}�[Ņ��`R�ԨWa��\k֚���� �T� ��ֻ��&Tc}� ����E�6������1H@:i�"��qd/�BV�"e������w?L`��'#"��Z/�_��!�̵2G�6!�JH�ث�P}/�#D�RZX��4Q�F�Txtޞcu"�<1�SPKN���'f{9MA��Ш.� |�D�
+�|LX��gsNvud"=]�5��Y��o!��1JTZ�U� Kh� ��
+I���­��Ua�^0UJ$�xaӉͬ�-��`ˀ��9!P0���1BE �R����d��7��c��7 ��X ^.��:�< �&S��#�R�U �LP��-_�sn�d��g��|�ϖ@ ���Et.[�6��I�+'�r�]=���U�zNP�×� LߎF�J�����JM� 2��h�T�a^U��cW �c~��!����N��P��d��cw�Q%|g F��0cA��w��Q ��?�����Do=d\�������l<���~4 ��������n��=`�LAg����' �2��wf� Ɋ�󖹉aE�����@��<���`f3J�ù}WX�����(�e���.+bOKC�[/�гUq�C]dlB����%Бd�_�ɥ��U���-���.�v#��YR�/�:�4��f���ϕ�.eE��_  ��D�����74H��=���U宵�������C�6`BP&���G�������ԉ�%P��,s3�z0�~_㙭B�a��D�+��4�GJ/� K���Rc�G��*4ʜ�۩Ϭ9r]���$�޼6�>�Q�\�\�������ݰq�y?��G���u(}-�I��kY���(�����2��6�-_�9�޺H�@6�K�#0����5�@� �|���%����Q�k���F1�+��'xŘ����2����c�H� Z �;��Q嘲�"Š�,O<��Ϗ#@ G�@ '����/A��� ��\cn�In3���i�c�z_��T��[)��tA�=�h�R�8��U�^=�z���QU�y�Rq<MB���8��r��+�M��5�&|�<B)�5�u�K%��h��'�Vu� �I�cpX����������D��emO�y� $�K�5�ȃ�9L�}�2_������m��G9����Hf����� <��5H;�7�P�#q��e� Mi*[�7# ,�M���H��1��~]4�{�ъ8DPWxF�GS��O��џ��;m�3�J3�R+*������n�uOE���1�)Y� ���>b\l��&��ޏ�hI܋��;���8u��~-��D) ���@�dSA��-W�����b!=O'�P��@-KC I�s�ٓt!Q�v�Q�BN9F�P�u��It� �,����:ۍ}P���*��!��7wwB�S�}`���;�'�#�,�#4���7���9d�u�}b��#z�5��������&X�b=����](1�b�i1��K�o��~���`�9,\K����P:e�$���Iϼ"�,d�S��olZ����qϖ([�� ���`KĶ����aF���M�������Z9�Ӧ~�:����v����R����q�ۆ-|�\�ko\`h,�����=@1 ��P1���.��*�rXch�Q�6Ȁ��uȠ#�!����-Oq��6������tu\)J�6q+����6�R&�A�(���J)J�!�h�K��0ڂ\��b�͉-�kѢ/p]���Lž| �uS������[���ӎ�*��<�Je�ɣ���D�<�H��*�sž��]�%���u�����>�'�l��DP�Ae�|�. �j ���`R�H'k  w2�5M�M�RDj��0 �o��JN�H����jc�D
+ N��]k�UF���$��8�!}���g��������4�v~�VA:|Kw�gՙ�������\�0�)�� �SP�:�u�u�q;9P�!4{����-YYV�n���;��T�����y�F�K��<>���b`�g���'���ʳ�H~ku%6�E����m�C�� ��"�~�$�Oxf�%+4���v����7G�6eT�I]�7��]T�;A�G��� �3��߀$*wA���C��٧T|����T��u%�����׷mRe�d�򍗰\y�MUT�͕�S6�~B�����T��_b2ۦ D+j�i8˘߀��,���#�d��[]:d�#�}+�< {�`��X��z�-9+<_ ���h���������� &��)d�>�m��u/�H�m~�lTtd����Swm��ә�X��%:��{L2[)�>�[���mp��uB����•����^�7/$Yp~9E;S5
+t����G�v�N�)��k"1c���%��b=�ښ��s�W(��6����àz^����,,L�td!2H� �֍A5\�s����C�i �:� 2�����[C�h��g\`�]�+X°K��K���$�[�!?��U�!�����7`}�*y���NA��J��
+�٭(��7r߶9�(2����:67������ ����J������X/ZA
+��o����“K}_� }����"#��T�ϭvk7S�QU���mU�Q~n�>Ơ���� (�����ߎz�`�V��g�e�;l�M.��t�R���T�qޒ�|��E��i�˵��L�T�g���BqAKA����Ĉߜ��E�)���4d��M��0�N*!.���+a��n�m�k�����o_�d�u�0Bz�~�I�?���h��wk�;\_�+��+j��^�YᰂݕN�]4���8��@�oΙ;���4�:�]RfM�w�刧sLʓ*���.TD�=t'�͢p#6}9Cd���g��� (x�E�Ź}������������d�Y���\�4V��_'%��g� ��+�"��ʒ�≦�m�k���@B3)��`���%q�܉��H�C�h�� ���}*挦���������U�� ��8g�� �Ð�0-������!F�g�AZ�&��n6� v7y؋�� nY|��Ha�N��f8F>���%ϿKL�zj���D���ꢈ M���vF�2�:ⴌ��f���RT�-���ka���T�'xk�� �^=��Ru���m� ��ٺ� ��~Z3�� ���p�#~D8t3�</5� �Tk�O)O�3�}W�x�B�Ј�"K��t���m��@��68�G:sl<�Ԓn,�i���[�W�9>�\�7+)�������Ǻl���gO-J�? Di\-[���p�I�������̱��3��?z�"���SVGQsY�1C�X�5����*�Z�`�9/�.w��¹R�<'Nc�҉L�׶�>(�g��7ǘ����'MH���Ɓ(64*� ���W�{4dF#k�\@�Y'\���˺��r��$4��:�F��'ϣ� �l�96�o�����$��l�?�e�R���$⬵�\"��"����d?_�w�tZ,X
+��7
+�*]5}���L\6 �a+�׷t���U���`�33|��G�K����`�� ��@ K�_�����C��Ӗw�>�,��HmF���tʒ�pHC>�[��R�z^�n�|n���87�@=Ė��-Z��� BX.;!�I ��J� �tHQ�`��u)?�a����"Hԉ�4]�'�����ٱv��0Oob2O�g$�XF��A� 1�i��h����}n�Њ$s���� ��Ϙ��;S|�&��!�dl��x�ŭ9ֹ}���-3L�9�(V�}G�a�XݾRf�Jr��q+U��~�����YvU�n��5O�o@����\���N�b:�fr��+�BVQ���� ,k�V���߉��t�<A�;�_� ���\��c�� K�|ۛ�t�dɼKQ�� ��&J�A���j��*&�x�Af%�!�ﳶ˪��q��3�r�^���]�ɥ�3]Y3����έ��2G�Q�� \���6�c"�����Xy�[�0/�j�pV�^���m(��nP1�>>���:����c��zHd1�ȼw@�Z� �SyP��"-0S%�|+�ހ��k�uq\} �
+��w3oJ��"+!�9��-0�<I����)��懨����WaNZ_���-d�{��2�e�/�K^��P@{~��kt?� ����U��y"yq��\ұ�����;�̨����� _�4L�v��jȪ�oA��������޽�au�,V�����0�Ю!�W����Z���� P�8T�C�]ͧ{�̨� ����������k�N#.,��3B�-&ڸ�:�_��#Y�[�(/TH[$ L�~V��� R���r8�����!���J��X��q.��sY��>�]%�7�3���MT�Ԛ5�������Z�k�/Ź�{�1M�!t1 X��vpu
+A>Ի(��m�,��F�����'����+ފY�ׄ "7]9��RuӢ !��z��|���c{E��.Z� �Ɋ�[�.C; -2��^�E�cu�az��B5x���v��,Z� x~�僇|h��_�V�|�]l Z�q%��X�k���k����\�q�&�eƴ�X�q�T#O���ٮX�k�3Et�3�E�ᡉ}{��dd|��#���i�7�$�?h:X��G�<b���Z)5hS,�1/���� ����)Cz��{�C(�L���0� ��}H<�m�P���'i������`%k��p����~u�3yr�@�zʯr��7f��[�!�Q���A�t5 �o�A�v�����0-���dq�ԝ�¶tpB�c�J�t`��v�%D/��N�GQ���,D��mNse+��&z�����) �^%��8���ҒS`��G��zG���H*}���K��Y ���>�]XA 燘84�c]�2�P�[�oj`�|nI��Y�@�K �'�(Q���(��2JBȾ:���a�G˓k�Ad��[6� s"vi@vMd���O�)&0yп�v\��ݒa`TY����ݚ���7��+��Ǡ�ue��/O��D����X�[�e��!?y��T��h�W|�����v�=|'�o��re�y5�S��뒔���������$� n���(��sp��`�I�i��T�P���J��(TY�7��)�`��O|i�����7B\SF�Ԟ"����0�V>���>��+>���`U�_oe��p� _�,&Dj�l�s�*1�Ϋ������E Mkײ�6C<�� H�\���m�z�S*�#"3�Zw��0�y���-�$�/�5���cu��'Y͉-T��̪� �P�>ڌI���L|�p�W��26q�
+]Y���L���:�0���������J#
+>b�� {�� �SG:"
+t�YK��k� ���������fz`O��$�7�%g'�( ��.>���!Za1�4t]o��>�~I�(YD����Y�rNo|*�
+�L.C�ic�A�G��ć�=tѢ�G�i��R�15 ��/��.r��x��n�-,E�tRd�/�^Q
+ �i5'�_��s����F��l�c&�KBd�j��ǽvF��`����cц;4��U�L�|< ���6������NS���:fNw�1�nRf��H����`��F�ګs$����fO� ��ڀj��yun��y�G��s�r��Ѐ|�p���$<G�ô9�R��`�5�d�b=
+����T~��uMtw�W8Y�F�Gɠ�I�]J�G���H �2��:�l;g鉍 ��w�4u��䈚*�ňӣ�4��7E��lu>=T��5D�
+20�H� �>l�nڃfK�oI�.�X��S�G߲����]�E|Gy�#�F괯Lo�Z�����I 7`|ʏ�!6d�9���Y��i}שO�\k$v}u��� �
+iP�ɣ�n����E({��N�έiu�y��;�'�zX �цLf� 7�{�ř~ ;fE� <`�V���� ��q�`��e؉ fN��߲Lp��Pȩ �Z#2u ���Q��l"K�z.hX��+�K}����� 5��y���<r+N
+x��BIQm Լi�ӷ���F7 l\�+#��]< Š����
+� ��sF��/[Z`v�5k�v)�@��;�\J:�2�kN�K�,��n%>�:hV�ct�1�'�ڦ�ƃ/�xWczV���8� =��Yt���
+��Ol�40���+c�Q�I+�F��X�O�ve�����
+T�,vJ(�I���*I����6�M"�������O����zu�+4��$t+��O�z�)W�E�CB���9�]�徦y�T���\-���x�A7�7
+��1ӡ�J ��� j�;�a�k�M��CB�Z�DM�!��{��)l s, !~�6�� �:��S����~m�_�$M^���l��&����O��j�䘂Y�Se�SWP��C�W._�������+�H� ��k麙�� ��A8 n�/ #�,��ߠ�7I�\J[I�Y��8�����������gI�l�).�� U )�����I �fR]�%Ri��D���{
+f�v��x�+/��>(���ɢU��l����-���`G�*�aҞz.ak.|��;��6�SY�y�&���'f__�Hm��s�E���i�dR�5���X�;|�ӶP. ki�}T5�U����ߢM�����M�Ȃ��S��"�]��%�n3�b���2�Q��:�MQ��Q&�]�t��|��b|�o�"u�ߪ=�"mjvj����i�uA4(�"5��j�)VX���G���G���ѡ�a��L��҅;�=�;wjʴd6HfM�-�+Ū�!���Q�뭠Ӕ.g+],�{�j��T�������0Q�o{_�Pi�ψ'�w�J�J�����U��5�o�
+,�|��DyWyGj{@�e2�6��LҠ��U]J�Ԁ%�ϖ��S��Ԃ��Lʫnt����t��?/a�r������v8i
+QJu%SoPf6jI�d+4�EܡZH ]������}���U$fl/;�W(I��AN����u�R��I=�>�O.�a1��+��<�Cm�⤚�V�_Qs�4rC�Ǝ��t��h��Q>�"��:�$z57�b��b�ųA��*�e����Z}~ ������L0)-J��B�>�Cv[�e?��Ȳ�<�AS�K �e߼���6�?�Yj�[�^������(m�w���%t�U\oDxv��njP�I��=��Y���Ď�Ӆ鮝��j�-���nq0�rZZm���A�-ąPR�T���Fn�ͭ8��P8���/��xC1�π����"���.i�~�L��j�q�w������+��q��������=8�o�V����$���N���� �f�w��]��e���D�l Q�2ӛw���-z��+O��+�d�Qp���TST����^�M�À�\�P��O*QdcC��
+c< H���������3�-x
+e�ZV�^��W[�N�5,�����y:C���PVξ7c�qC�Z�ֳ�i⽝(6��*�{��`�����5�������� &�cH���+\2grZ�mnZoј�L�4k� ?>O��g>�O
+Y�+�S~�gA�KN�?���l����e�=l�b&X��y�� ��>�’:W��jęI8.:�D^f����թ���2,�[��v�wZ�~$����% ��Q �6��쯇� �c�u��8 �X!Vc�6g_M��^l@�A��XXQh�p�� d4�@���:~�6�;%�����%��0Y�t��sU��~��X9�a��~o���f���@�ɔ�#����m��.�a� �`�x���Idp-^�^,,�x��64�/M�|�s���#4 us+Y��^�E ���`[���g���_^_� UA��z�����_5�,� �Y���֓g���#�ʀFh|��IΧ��l�P/��rR2�����j�$w�)��8̰���3T�~ ����/ͻ�S<�0���XJ���W�^��S%�UI�3��Z�!��7�<z*��9"��� ���xo�N��r����c����=N��������o�}�I�����P�:��Un��&)� h⻽&s
+��0���uI>�v�5k�>���M���{�8���s�����!1Ý ԋM�Q��Rb�3��SQ��؆v�_��p&^H�9�y���,�¤~�}�W��u�P�� DRŶ�J��F�����i߫�� ��� �1�d�#ڦ�^��V�4.YܩٸI>$�0hhW�J��퐐��3i�ƚ��i?\�4���<�k�ٚdBd?%�A�2\9)F�(�w>/04�t��zEjU�?钠�Vk��!�JE6/���o��NX�.0P�1�0X�rW���K��5�m�n��k~���Q���q�qZ��
+g��"�0'J�P5qx��� �3��]��G��VV��ӂ�Z�T��с��Y���`��$u0A���ܪ�*��jTJ�<B��N���l����g����kȺ��(.�@ǔ�g>� ��1�4�,7%����O�x�6e1 x��j�~-c�;�7��)zb$��� �R��5�b���u� ���ui����dlm�o���`�{C'j�6er�I�g���g��w��xݣх��87�C��"9C��I�p2��G$�C�:a,1 ���k�
+���<@��-�1Pη�K�5���EcI����/����>dy<�Q�d�0g���������D;��}����i]��i����k�j�[E�(-�G�T��<��VU���ug����:�f”^�"��Scv-6��2��Oϝ�<�O)��:@sO�2�B\ٺ��3Qu�ȟ�[}��T6HWC_q�U+�֪ M ɧ�$�L�x�߇�� #m�)�����w�gp;�~0�Qo=�-��?�Ԙt� +� J9H�aݍ� �ڳkL:�\�3TK���n���F�5@Ӎ��B�V������縑��E�ƲS�� ˭������ëb�C`�'J�;��.oO���r��,�9麘���#� �� ��y�yD#��$ �,�lZpM�(��BL�t�=�g9��n'����AA1�������N�UU, ʋ1��oQ��Q��:�k�6����K�U��9��!�<�oJbL~���J�"�w=C�Ă��W#�����rV��6n���� ���59f����F�v��H~��[�ɀ"zV���o��� _�{�d�0=s�o�5�CN��]�TȤ������ Bv�*��"�k�IVtG�lɟ�6�T�#�U������.�b�����b+F2���
+ j\�|,�=�ݞ��!����zGQ�BC��^��9�u�A��|�߱�E�,�M�9r(�DC��b������&{��������jZ�F��Z_�6?���q�A@�c�q|��ʨ@���Dg�;ʏ5�w��� l�`�l��,���Rx̻k�:�T_���R7�<���;�5ʆ�@�u��Dܢ�A������ 3�P��+�`�۔�Lñ�$7/+�7ʒ��<�.��Vl%���R�kT��!�T��5G�E�:J�� T������Y���Yg�٥Fr��MBP�z�Bՠ�1��������_�����f�@<�s*l~�s �z���jJ���)���H�ڰ~��������zɯ�,��d`7)˫��t' ���l�[�4/�wP4�t�+�򖢖����D�� c�u�5�BX�T�Pw)ꁩK��thS�e?w�x/U����t.y��e�ye�pP�G(G#mcr�F�@��[�.f������k%^�׊R����XB8�S�
+.F[6A�媳0��f��Z�[��q'� ��l;ʩ$|r�,����\i��}q^\�-s6��\Mp�I�4>m^3�Z�ݘp�b�4M��4����ȳ'p�O�~��P��T��$�H<�D~��@�' R��x�%(���.�õ�>��Dz-a��ؽ!\�[X+bc�/�'�������B��6u+?� P����C�B��9��y��v�A`\ϯ2ڿ9��aj��iLr��r+��~�߆u��f4l��!l���#���<�P�ԩ�>!�B����_�_XC�G&ۭ8a/�/���M��侷�ꂓ�G�L��Z+�Z�,q�� �j��H���۲�kK�����_�i,�Ϡ;�9
+endstream
+endobj
+859 0 obj
+<< /D (subsection.6.2) /S /GoTo >>
+endobj
+860 0 obj
+<feff0036002e00320020004d00610069006e00200052006500730075006c007400730020002d002000530074006f007200610067006500200061006e00640020004c006100740065006e00630079>
+endobj
+861 0 obj
+<< /D (subsection.6.3) /S /GoTo >>
+endobj
+862 0 obj
+<feff0036002e00330020004d00610069006e00200052006500730075006c00740020002d00200041006300630075007200610063007900200066006f007200200044006f0077006e00730074007200650061006d00200052004100470020005400610073006b>
+endobj
+xref
+0 863
+0000000000 65535 f
+0000000015 00000 n
+0000000208 00000 n
+0000000876 00000 n
+0000014395 00000 n
+0000014429 00000 n
+0000014477 00000 n
+0000014551 00000 n
+0000014626 00000 n
+0000014735 00000 n
+0000014986 00000 n
+0000015059 00000 n
+0000015132 00000 n
+0000015241 00000 n
+0000015351 00000 n
+0000015440 00000 n
+0000015559 00000 n
+0000015695 00000 n
+0000015807 00000 n
+0000015925 00000 n
+0000016020 00000 n
+0000016182 00000 n
+0000016361 00000 n
+0000016534 00000 n
+0000016709 00000 n
+0000016889 00000 n
+0000017067 00000 n
+0000017240 00000 n
+0000017413 00000 n
+0000017587 00000 n
+0000017759 00000 n
+0000017932 00000 n
+0000018103 00000 n
+0000018289 00000 n
+0000018449 00000 n
+0000018610 00000 n
+0000018783 00000 n
+0000018938 00000 n
+0000019150 00000 n
+0000024775 00000 n
+0000024997 00000 n
+0000025044 00000 n
+0000025131 00000 n
+0000025186 00000 n
+0000025234 00000 n
+0000025323 00000 n
+0000025386 00000 n
+0000025670 00000 n
+0000026002 00000 n
+0000026254 00000 n
+0000026434 00000 n
+0000026638 00000 n
+0000027002 00000 n
+0000027230 00000 n
+0000027474 00000 n
+0000027718 00000 n
+0000027986 00000 n
+0000028238 00000 n
+0000028586 00000 n
+0000028950 00000 n
+0000029106 00000 n
+0000029309 00000 n
+0000029512 00000 n
+0000029711 00000 n
+0000029911 00000 n
+0000030096 00000 n
+0000030368 00000 n
+0000030641 00000 n
+0000030917 00000 n
+0000031163 00000 n
+0000031395 00000 n
+0000031713 00000 n
+0000031986 00000 n
+0000032223 00000 n
+0000032483 00000 n
+0000032838 00000 n
+0000033140 00000 n
+0000033441 00000 n
+0000033699 00000 n
+0000033952 00000 n
+0000034177 00000 n
+0000034350 00000 n
+0000034515 00000 n
+0000034702 00000 n
+0000034893 00000 n
+0000035097 00000 n
+0000035326 00000 n
+0000035532 00000 n
+0000035587 00000 n
+0000035609 00000 n
+0000035797 00000 n
+0000035984 00000 n
+0000036144 00000 n
+0000036315 00000 n
+0000036502 00000 n
+0000036690 00000 n
+0000036878 00000 n
+0000036978 00000 n
+0000037000 00000 n
+0000037046 00000 n
+0000037174 00000 n
+0000037254 00000 n
+0000037301 00000 n
+0000037430 00000 n
+0000037502 00000 n
+0000037665 00000 n
+0000037850 00000 n
+0000038024 00000 n
+0000038199 00000 n
+0000038369 00000 n
+0000038536 00000 n
+0000038698 00000 n
+0000038858 00000 n
+0000039018 00000 n
+0000039232 00000 n
+0000039394 00000 n
+0000039562 00000 n
+0000039725 00000 n
+0000039887 00000 n
+0000040061 00000 n
+0000040227 00000 n
+0000040395 00000 n
+0000040560 00000 n
+0000040723 00000 n
+0000040886 00000 n
+0000047474 00000 n
+0000047720 00000 n
+0000047890 00000 n
+0000048062 00000 n
+0000048237 00000 n
+0000048399 00000 n
+0000048569 00000 n
+0000048743 00000 n
+0000048923 00000 n
+0000049096 00000 n
+0000049268 00000 n
+0000049444 00000 n
+0000049623 00000 n
+0000049799 00000 n
+0000049978 00000 n
+0000050152 00000 n
+0000050333 00000 n
+0000050507 00000 n
+0000050682 00000 n
+0000050859 00000 n
+0000051034 00000 n
+0000051207 00000 n
+0000051378 00000 n
+0000051544 00000 n
+0000051726 00000 n
+0000051887 00000 n
+0000052050 00000 n
+0000052215 00000 n
+0000058351 00000 n
+0000058611 00000 n
+0000058775 00000 n
+0000058939 00000 n
+0000059102 00000 n
+0000059265 00000 n
+0000059435 00000 n
+0000059603 00000 n
+0000059765 00000 n
+0000059931 00000 n
+0000060101 00000 n
+0000060268 00000 n
+0000060436 00000 n
+0000060604 00000 n
+0000060770 00000 n
+0000060935 00000 n
+0000061099 00000 n
+0000061261 00000 n
+0000065919 00000 n
+0000066111 00000 n
+0000066281 00000 n
+0000066445 00000 n
+0000066618 00000 n
+0000066792 00000 n
+0000066957 00000 n
+0000067125 00000 n
+0000067291 00000 n
+0000073407 00000 n
+0000073626 00000 n
+0000073790 00000 n
+0000073953 00000 n
+0000074128 00000 n
+0000074292 00000 n
+0000074455 00000 n
+0000074620 00000 n
+0000074791 00000 n
+0000074959 00000 n
+0000075129 00000 n
+0000075293 00000 n
+0000081278 00000 n
+0000081566 00000 n
+0000081731 00000 n
+0000081895 00000 n
+0000082073 00000 n
+0000082237 00000 n
+0000082401 00000 n
+0000082566 00000 n
+0000082729 00000 n
+0000082896 00000 n
+0000083062 00000 n
+0000083230 00000 n
+0000083409 00000 n
+0000083591 00000 n
+0000083771 00000 n
+0000083940 00000 n
+0000084114 00000 n
+0000084294 00000 n
+0000084467 00000 n
+0000084654 00000 n
+0000084830 00000 n
+0000085001 00000 n
+0000085175 00000 n
+0000085345 00000 n
+0000085507 00000 n
+0000085670 00000 n
+0000085831 00000 n
+0000086008 00000 n
+0000086170 00000 n
+0000086341 00000 n
+0000086515 00000 n
+0000086679 00000 n
+0000092341 00000 n
+0000092558 00000 n
+0000092726 00000 n
+0000092895 00000 n
+0000093058 00000 n
+0000093232 00000 n
+0000093403 00000 n
+0000093577 00000 n
+0000093755 00000 n
+0000093920 00000 n
+0000094086 00000 n
+0000094266 00000 n
+0000094427 00000 n
+0000094597 00000 n
+0000094776 00000 n
+0000098571 00000 n
+0000098842 00000 n
+0000099010 00000 n
+0000099178 00000 n
+0000099346 00000 n
+0000099514 00000 n
+0000099682 00000 n
+0000099868 00000 n
+0000100036 00000 n
+0000100212 00000 n
+0000100384 00000 n
+0000100555 00000 n
+0000100723 00000 n
+0000100892 00000 n
+0000101060 00000 n
+0000101229 00000 n
+0000101391 00000 n
+0000107408 00000 n
+0000107585 00000 n
+0000107748 00000 n
+0000107915 00000 n
+0000108081 00000 n
+0000108250 00000 n
+0000108417 00000 n
+0000108586 00000 n
+0000108754 00000 n
+0000108922 00000 n
+0000109092 00000 n
+0000109255 00000 n
+0000109418 00000 n
+0000109589 00000 n
+0000109770 00000 n
+0000109946 00000 n
+0000110108 00000 n
+0000114337 00000 n
+0000114581 00000 n
+0000114752 00000 n
+0000114920 00000 n
+0000115095 00000 n
+0000115265 00000 n
+0000115428 00000 n
+0000115599 00000 n
+0000115767 00000 n
+0000115929 00000 n
+0000116092 00000 n
+0000116255 00000 n
+0000116417 00000 n
+0000116583 00000 n
+0000116747 00000 n
+0000116910 00000 n
+0000117073 00000 n
+0000117259 00000 n
+0000117436 00000 n
+0000117610 00000 n
+0000121847 00000 n
+0000122121 00000 n
+0000122286 00000 n
+0000122466 00000 n
+0000122630 00000 n
+0000122810 00000 n
+0000122979 00000 n
+0000123157 00000 n
+0000123318 00000 n
+0000123500 00000 n
+0000123675 00000 n
+0000123849 00000 n
+0000124022 00000 n
+0000124203 00000 n
+0000124377 00000 n
+0000124555 00000 n
+0000124732 00000 n
+0000124900 00000 n
+0000130289 00000 n
+0000130427 00000 n
+0000130642 00000 n
+0000130856 00000 n
+0000131069 00000 n
+0000131281 00000 n
+0000131580 00000 n
+0000131878 00000 n
+0000132177 00000 n
+0000132396 00000 n
+0000132614 00000 n
+0000132824 00000 n
+0000133050 00000 n
+0000133275 00000 n
+0000133508 00000 n
+0000133740 00000 n
+0000133939 00000 n
+0000134140 00000 n
+0000134340 00000 n
+0000134540 00000 n
+0000134741 00000 n
+0000134949 00000 n
+0000135158 00000 n
+0000135358 00000 n
+0000135566 00000 n
+0000135773 00000 n
+0000135978 00000 n
+0000136184 00000 n
+0000136388 00000 n
+0000136592 00000 n
+0000145036 00000 n
+0000145214 00000 n
+0000145429 00000 n
+0000145643 00000 n
+0000145930 00000 n
+0000146217 00000 n
+0000146503 00000 n
+0000146730 00000 n
+0000146956 00000 n
+0000147227 00000 n
+0000147498 00000 n
+0000147727 00000 n
+0000147955 00000 n
+0000148173 00000 n
+0000148389 00000 n
+0000148612 00000 n
+0000148833 00000 n
+0000149144 00000 n
+0000149455 00000 n
+0000149766 00000 n
+0000150077 00000 n
+0000150275 00000 n
+0000150475 00000 n
+0000150675 00000 n
+0000150876 00000 n
+0000151107 00000 n
+0000151339 00000 n
+0000151589 00000 n
+0000151838 00000 n
+0000152088 00000 n
+0000152338 00000 n
+0000152543 00000 n
+0000160754 00000 n
+0000160906 00000 n
+0000161115 00000 n
+0000161322 00000 n
+0000161532 00000 n
+0000161733 00000 n
+0000164876 00000 n
+0000165042 00000 n
+0000165104 00000 n
+0000165166 00000 n
+0000165228 00000 n
+0000165290 00000 n
+0000165352 00000 n
+0000165414 00000 n
+0000165476 00000 n
+0000165538 00000 n
+0000165600 00000 n
+0000165662 00000 n
+0000165724 00000 n
+0000165785 00000 n
+0000165847 00000 n
+0000165909 00000 n
+0000165970 00000 n
+0000166032 00000 n
+0000166093 00000 n
+0000166155 00000 n
+0000166217 00000 n
+0000166279 00000 n
+0000166336 00000 n
+0000166396 00000 n
+0000166459 00000 n
+0000166522 00000 n
+0000166580 00000 n
+0000166638 00000 n
+0000166696 00000 n
+0000166754 00000 n
+0000166812 00000 n
+0000166870 00000 n
+0000166928 00000 n
+0000166986 00000 n
+0000167049 00000 n
+0000167107 00000 n
+0000167165 00000 n
+0000167227 00000 n
+0000167289 00000 n
+0000167347 00000 n
+0000167409 00000 n
+0000167471 00000 n
+0000167533 00000 n
+0000167595 00000 n
+0000167652 00000 n
+0000167710 00000 n
+0000167773 00000 n
+0000167836 00000 n
+0000167893 00000 n
+0000167956 00000 n
+0000168015 00000 n
+0000168078 00000 n
+0000168141 00000 n
+0000168203 00000 n
+0000168266 00000 n
+0000168329 00000 n
+0000168387 00000 n
+0000168450 00000 n
+0000168513 00000 n
+0000168571 00000 n
+0000168629 00000 n
+0000168692 00000 n
+0000168755 00000 n
+0000168818 00000 n
+0000168881 00000 n
+0000168939 00000 n
+0000169002 00000 n
+0000169060 00000 n
+0000169117 00000 n
+0000169175 00000 n
+0000169233 00000 n
+0000169295 00000 n
+0000169353 00000 n
+0000169411 00000 n
+0000169474 00000 n
+0000169537 00000 n
+0000169595 00000 n
+0000169653 00000 n
+0000169716 00000 n
+0000169774 00000 n
+0000169837 00000 n
+0000169900 00000 n
+0000169958 00000 n
+0000170016 00000 n
+0000170079 00000 n
+0000170142 00000 n
+0000170205 00000 n
+0000170268 00000 n
+0000170331 00000 n
+0000170394 00000 n
+0000170452 00000 n
+0000170511 00000 n
+0000170573 00000 n
+0000170636 00000 n
+0000170694 00000 n
+0000170748 00000 n
+0000170806 00000 n
+0000170869 00000 n
+0000170932 00000 n
+0000170990 00000 n
+0000171048 00000 n
+0000171105 00000 n
+0000171164 00000 n
+0000171227 00000 n
+0000171290 00000 n
+0000171353 00000 n
+0000171416 00000 n
+0000171479 00000 n
+0000171542 00000 n
+0000171605 00000 n
+0000171663 00000 n
+0000171721 00000 n
+0000171784 00000 n
+0000171842 00000 n
+0000171905 00000 n
+0000171968 00000 n
+0000172031 00000 n
+0000172089 00000 n
+0000172152 00000 n
+0000172210 00000 n
+0000172268 00000 n
+0000172325 00000 n
+0000172383 00000 n
+0000172441 00000 n
+0000172499 00000 n
+0000172557 00000 n
+0000172615 00000 n
+0000172673 00000 n
+0000172731 00000 n
+0000172789 00000 n
+0000172847 00000 n
+0000172905 00000 n
+0000172963 00000 n
+0000173021 00000 n
+0000173079 00000 n
+0000173137 00000 n
+0000173194 00000 n
+0000173252 00000 n
+0000173310 00000 n
+0000173367 00000 n
+0000173425 00000 n
+0000173482 00000 n
+0000173540 00000 n
+0000173602 00000 n
+0000173665 00000 n
+0000173723 00000 n
+0000173781 00000 n
+0000173844 00000 n
+0000173902 00000 n
+0000173964 00000 n
+0000174022 00000 n
+0000174085 00000 n
+0000174143 00000 n
+0000174205 00000 n
+0000174268 00000 n
+0000174326 00000 n
+0000174380 00000 n
+0000174443 00000 n
+0000174506 00000 n
+0000174564 00000 n
+0000174627 00000 n
+0000174690 00000 n
+0000174748 00000 n
+0000175128 00000 n
+0000175586 00000 n
+0000176534 00000 n
+0000176938 00000 n
+0000177586 00000 n
+0000178263 00000 n
+0000179214 00000 n
+0000180179 00000 n
+0000180646 00000 n
+0000181700 00000 n
+0000182483 00000 n
+0000182944 00000 n
+0000183610 00000 n
+0000184143 00000 n
+0000184325 00000 n
+0000185131 00000 n
+0000185488 00000 n
+0000185855 00000 n
+0000186307 00000 n
+0000187257 00000 n
+0000187618 00000 n
+0000187686 00000 n
+0000188449 00000 n
+0000188474 00000 n
+0000188521 00000 n
+0000188599 00000 n
+0000188677 00000 n
+0000188767 00000 n
+0000188899 00000 n
+0000188946 00000 n
+0000189025 00000 n
+0000189104 00000 n
+0000189195 00000 n
+0000189331 00000 n
+0000189493 00000 n
+0000189665 00000 n
+0000189826 00000 n
+0000189989 00000 n
+0000190154 00000 n
+0000193741 00000 n
+0000201432 00000 n
+0000201604 00000 n
+0000201801 00000 n
+0000203700 00000 n
+0000213649 00000 n
+0000219760 00000 n
+0000223317 00000 n
+0000225286 00000 n
+0000228023 00000 n
+0000235905 00000 n
+0000237918 00000 n
+0000239640 00000 n
+0000244244 00000 n
+0000245980 00000 n
+0000246167 00000 n
+0000246357 00000 n
+0000349674 00000 n
+0000452742 00000 n
+0000460069 00000 n
+0000471741 00000 n
+0000535602 00000 n
+0000535654 00000 n
+0000535746 00000 n
+0000535826 00000 n
+0000535878 00000 n
+0000536086 00000 n
+0000536133 00000 n
+0000536263 00000 n
+0000536327 00000 n
+0000536379 00000 n
+0000536472 00000 n
+0000536652 00000 n
+0000536704 00000 n
+0000536788 00000 n
+0000536835 00000 n
+0000536965 00000 n
+0000537045 00000 n
+0000537288 00000 n
+0000538206 00000 n
+0000538251 00000 n
+0000538602 00000 n
+0000539266 00000 n
+0000539475 00000 n
+0000539693 00000 n
+0000540480 00000 n
+0000540505 00000 n
+0000540759 00000 n
+0000541391 00000 n
+0000541449 00000 n
+0000541691 00000 n
+0000542438 00000 n
+0000542479 00000 n
+0000542643 00000 n
+0000542682 00000 n
+0000542890 00000 n
+0000543105 00000 n
+0000546284 00000 n
+0000546540 00000 n
+0000546579 00000 n
+0000546618 00000 n
+0000546657 00000 n
+0000547314 00000 n
+0000547736 00000 n
+0000548107 00000 n
+0000552284 00000 n
+0000565659 00000 n
+0000569334 00000 n
+0000573009 00000 n
+0000612745 00000 n
+0000612984 00000 n
+0000613648 00000 n
+0000613673 00000 n
+0000613941 00000 n
+0000614288 00000 n
+0000615205 00000 n
+0000615530 00000 n
+0000615684 00000 n
+0000615838 00000 n
+0000615992 00000 n
+0000616146 00000 n
+0000616300 00000 n
+0000616454 00000 n
+0000616608 00000 n
+0000616762 00000 n
+0000616916 00000 n
+0000617070 00000 n
+0000617224 00000 n
+0000617378 00000 n
+0000617532 00000 n
+0000617686 00000 n
+0000617840 00000 n
+0000617994 00000 n
+0000618608 00000 n
+0000619441 00000 n
+0000620023 00000 n
+0000620177 00000 n
+0000620331 00000 n
+0000620945 00000 n
+0000621778 00000 n
+0000622360 00000 n
+0000622514 00000 n
+0000622668 00000 n
+0000622822 00000 n
+0000622976 00000 n
+0000623130 00000 n
+0000623284 00000 n
+0000623540 00000 n
+0000623696 00000 n
+0000623900 00000 n
+0000624148 00000 n
+0000624302 00000 n
+0000624456 00000 n
+0000624610 00000 n
+0000624764 00000 n
+0000624918 00000 n
+0000625072 00000 n
+0000625681 00000 n
+0000626259 00000 n
+0000626413 00000 n
+0000626567 00000 n
+0000627176 00000 n
+0000627754 00000 n
+0000627908 00000 n
+0000628062 00000 n
+0000628318 00000 n
+0000628574 00000 n
+0000628830 00000 n
+0000629086 00000 n
+0000629240 00000 n
+0000629394 00000 n
+0000630006 00000 n
+0000630838 00000 n
+0000631418 00000 n
+0000631789 00000 n
+0000632230 00000 n
+0000633185 00000 n
+0000633591 00000 n
+0000633663 00000 n
+0000634415 00000 n
+0000634440 00000 n
+0000634492 00000 n
+0000634712 00000 n
+0000634759 00000 n
+0000634838 00000 n
+0000634917 00000 n
+0000635008 00000 n
+0000635180 00000 n
+0000635232 00000 n
+0000635312 00000 n
+0000635359 00000 n
+0000635438 00000 n
+0000635517 00000 n
+0000635589 00000 n
+0000645447 00000 n
+0000653971 00000 n
+0000655551 00000 n
+0000657572 00000 n
+0000659579 00000 n
+0000662293 00000 n
+0000662538 00000 n
+0000662890 00000 n
+0000663135 00000 n
+0000663510 00000 n
+0000665046 00000 n
+0000668534 00000 n
+0000671248 00000 n
+0000671706 00000 n
+0000671958 00000 n
+0000672203 00000 n
+0000672454 00000 n
+0000686034 00000 n
+0000691530 00000 n
+0000700235 00000 n
+0000706794 00000 n
+0000714786 00000 n
+0000716767 00000 n
+0000731609 00000 n
+0000731650 00000 n
+0000733772 00000 n
+0000733989 00000 n
+0000734987 00000 n
+0000735019 00000 n
+0000736810 00000 n
+0000737019 00000 n
+0000737563 00000 n
+0000737594 00000 n
+0000738684 00000 n
+0000738890 00000 n
+0000739426 00000 n
+0000739457 00000 n
+0000741248 00000 n
+0000741456 00000 n
+0000742003 00000 n
+0000742033 00000 n
+0000743123 00000 n
+0000743328 00000 n
+0000743866 00000 n
+0000743898 00000 n
+0000744988 00000 n
+0000745196 00000 n
+0000745734 00000 n
+0000747525 00000 n
+0000748069 00000 n
+0000750191 00000 n
+0000751189 00000 n
+0000752279 00000 n
+0000752817 00000 n
+0000754608 00000 n
+0000755152 00000 n
+0000757274 00000 n
+0000758272 00000 n
+0000760394 00000 n
+0000761392 00000 n
+0000763514 00000 n
+0000764512 00000 n
+0000766634 00000 n
+0000767632 00000 n
+0000768722 00000 n
+0000769258 00000 n
+0000769289 00000 n
+0000771080 00000 n
+0000771288 00000 n
+0000771833 00000 n
+0000771864 00000 n
+0000772954 00000 n
+0000773161 00000 n
+0000773699 00000 n
+0000773730 00000 n
+0000774820 00000 n
+0000775027 00000 n
+0000775595 00000 n
+0000775626 00000 n
+0000776716 00000 n
+0000776921 00000 n
+0000777455 00000 n
+0000777485 00000 n
+0000778575 00000 n
+0000778780 00000 n
+0000779316 00000 n
+0000781438 00000 n
+0000782436 00000 n
+0000784558 00000 n
+0000785556 00000 n
+0000787678 00000 n
+0000788676 00000 n
+0000790798 00000 n
+0000791796 00000 n
+0000793918 00000 n
+0000794916 00000 n
+0000849284 00000 n
+0000849336 00000 n
+0000849524 00000 n
+0000849576 00000 n
+0000849764 00000 n
+0000849811 00000 n
+0000849975 00000 n
+0000850027 00000 n
+0000850120 00000 n
+0000850180 00000 n
+0000850232 00000 n
+0000850325 00000 n
+0000850421 00000 n
+0000855406 00000 n
+0000862701 00000 n
+0000873922 00000 n
+0000879532 00000 n
+0000881914 00000 n
+0000925703 00000 n
+0000953794 00000 n
+0000985744 00000 n
+0001013987 00000 n
+0001042959 00000 n
+0001071233 00000 n
+0001099205 00000 n
+0001127709 00000 n
+0001156286 00000 n
+0001185207 00000 n
+0001214138 00000 n
+0001214190 00000 n
+0001214366 00000 n
+0001214418 00000 n
+trailer << /Info 2 0 R /Root 1 0 R /Size 863 /ID [<af631ce1565b05d1244923546ad8b5ca><96eff7b33f17172214393742ca5ac9ea>] >>
+startxref
+1214642
+%%EOF
diff --git a/examples/document_search.py b/examples/document_search.py
new file mode 100644
index 0000000..72d5bdc
--- /dev/null
+++ b/examples/document_search.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+"""
+Document search demo with recompute mode
+"""
+
+import os
+from pathlib import Path
+import shutil
+import time
+
+# Import backend packages to trigger plugin registration
+try:
+ import leann_backend_diskann
+ import leann_backend_hnsw
+ print("INFO: Backend packages imported successfully.")
+except ImportError as e:
+ print(f"WARNING: Could not import backend packages. Error: {e}")
+
+# Import upper-level API from leann-core
+from leann.api import LeannBuilder, LeannSearcher, LeannChat
+
+
+def load_sample_documents():
+ """Create sample documents for demonstration"""
+ docs = [
+ {"title": "Intro to Python", "content": "Python is a high-level, interpreted language known for simplicity."},
+ {"title": "ML Basics", "content": "Machine learning builds systems that learn from data."},
+ {"title": "Data Structures", "content": "Data structures like arrays, lists, and graphs organize data."},
+ ]
+ return docs
+
+def main():
+ print("==========================================================")
+ print("=== Leann Document Search Demo (DiskANN + Recompute) ===")
+ print("==========================================================")
+
+ INDEX_DIR = Path("./test_indices")
+ INDEX_PATH = str(INDEX_DIR / "documents.diskann")
+ BACKEND_TO_TEST = "diskann"
+
+ if INDEX_DIR.exists():
+ print(f"--- Cleaning up old index directory: {INDEX_DIR} ---")
+ shutil.rmtree(INDEX_DIR)
+
+ # --- 1. Build index ---
+ print(f"\n[PHASE 1] Building index using '{BACKEND_TO_TEST}' backend...")
+
+ builder = LeannBuilder(
+ backend_name=BACKEND_TO_TEST,
+ graph_degree=32,
+ complexity=64
+ )
+
+ documents = load_sample_documents()
+ print(f"Loaded {len(documents)} sample documents.")
+ for doc in documents:
+ builder.add_text(doc["content"], metadata={"title": doc["title"]})
+
+ builder.build_index(INDEX_PATH)
+ print(f"\nIndex built!")
+
+ # --- 2. Basic search demo ---
+ print(f"\n[PHASE 2] Basic search using '{BACKEND_TO_TEST}' backend...")
+ searcher = LeannSearcher(index_path=INDEX_PATH)
+
+ query = "What is machine learning?"
+ print(f"\nQuery: '{query}'")
+
+ print("\n--- Basic search mode (PQ computation) ---")
+ start_time = time.time()
+ results = searcher.search(query, top_k=2)
+ basic_time = time.time() - start_time
+
+ print(f"⏱️ Basic search time: {basic_time:.3f} seconds")
+ print(">>> Basic search results <<<")
+ for i, res in enumerate(results, 1):
+ print(f" {i}. ID: {res['id']}, Score: {res['score']:.4f}, Text: '{res['text']}', Metadata: {res['metadata']}")
+
+ # --- 3. Recompute search demo ---
+ print(f"\n[PHASE 3] Recompute search using embedding server...")
+
+ print("\n--- Recompute search mode (get real embeddings via network) ---")
+
+ # Configure recompute parameters
+ recompute_params = {
+ "recompute_beighbor_embeddings": True, # Enable network recomputation
+ "USE_DEFERRED_FETCH": False, # Don't use deferred fetch
+ "skip_search_reorder": True, # Skip search reordering
+ "dedup_node_dis": True, # Enable node distance deduplication
+ "prune_ratio": 0.1, # Pruning ratio 10%
+ "batch_recompute": False, # Don't use batch recomputation
+ "global_pruning": False, # Don't use global pruning
+ "zmq_port": 5555, # ZMQ port
+ "embedding_model": "sentence-transformers/all-mpnet-base-v2"
+ }
+
+ print("Recompute parameter configuration:")
+ for key, value in recompute_params.items():
+ print(f" {key}: {value}")
+
+ print(f"\n🔄 Executing Recompute search...")
+ try:
+ start_time = time.time()
+ recompute_results = searcher.search(query, top_k=2, **recompute_params)
+ recompute_time = time.time() - start_time
+
+ print(f"⏱️ Recompute search time: {recompute_time:.3f} seconds")
+ print(">>> Recompute search results <<<")
+ for i, res in enumerate(recompute_results, 1):
+ print(f" {i}. ID: {res['id']}, Score: {res['score']:.4f}, Text: '{res['text']}', Metadata: {res['metadata']}")
+
+ # Compare results
+ print(f"\n--- Result comparison ---")
+ print(f"Basic search time: {basic_time:.3f} seconds")
+ print(f"Recompute time: {recompute_time:.3f} seconds")
+
+ print("\nBasic search vs Recompute results:")
+ for i in range(min(len(results), len(recompute_results))):
+ basic_score = results[i]['score']
+ recompute_score = recompute_results[i]['score']
+ score_diff = abs(basic_score - recompute_score)
+ print(f" Position {i+1}: PQ={basic_score:.4f}, Recompute={recompute_score:.4f}, Difference={score_diff:.4f}")
+
+ if recompute_time > basic_time:
+ print(f"✅ Recompute mode working correctly (more accurate but slower)")
+ else:
+ print(f"ℹ️ Recompute time is unusually fast, network recomputation may not be enabled")
+
+ except Exception as e:
+ print(f"❌ Recompute search failed: {e}")
+ print("This usually indicates an embedding server connection issue")
+
+ # --- 4. Chat demo ---
+ print(f"\n[PHASE 4] Starting chat session...")
+ chat = LeannChat(index_path=INDEX_PATH)
+ chat_response = chat.ask(query)
+ print(f"You: {query}")
+ print(f"Leann: {chat_response}")
+
+ print("\n==========================================================")
+ print("✅ Demo finished successfully!")
+ print("==========================================================")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/examples/main_cli_example.py b/examples/main_cli_example.py
new file mode 100644
index 0000000..35c6a9c
--- /dev/null
+++ b/examples/main_cli_example.py
@@ -0,0 +1,76 @@
+from llama_index.core import SimpleDirectoryReader, Settings
+from llama_index.core.readers.base import BaseReader
+from llama_index.node_parser.docling import DoclingNodeParser
+from llama_index.readers.docling import DoclingReader
+from docling_core.transforms.chunker.hybrid_chunker import HybridChunker
+import asyncio
+import os
+import dotenv
+from leann.api import LeannBuilder, LeannSearcher, LeannChat
+import leann_backend_diskann # Import to ensure backend registration
+import shutil
+from pathlib import Path
+
+dotenv.load_dotenv()
+
+reader = DoclingReader(export_type=DoclingReader.ExportType.JSON)
+file_extractor: dict[str, BaseReader] = {
+ ".docx": reader,
+ ".pptx": reader,
+ ".pdf": reader,
+ ".xlsx": reader,
+}
+node_parser = DoclingNodeParser(
+ chunker=HybridChunker(tokenizer="Qwen/Qwen3-Embedding-4B", max_tokens=10240)
+)
+
+documents = SimpleDirectoryReader(
+ "examples/data",
+ recursive=True,
+ file_extractor=file_extractor,
+ encoding="utf-8",
+ required_exts=[".pdf", ".docx", ".pptx", ".xlsx"]
+).load_data(show_progress=True)
+
+# Extract text from documents and prepare for Leann
+all_texts = []
+for doc in documents:
+ # DoclingNodeParser returns Node objects, which have a text attribute
+ nodes = node_parser.get_nodes_from_documents([doc])
+ for node in nodes:
+ all_texts.append(node.text)
+
+INDEX_DIR = Path("./test_pdf_index")
+INDEX_PATH = str(INDEX_DIR / "pdf_documents.leann")
+
+if INDEX_DIR.exists():
+ print(f"--- Cleaning up old index directory: {INDEX_DIR} ---")
+ shutil.rmtree(INDEX_DIR)
+
+print(f"\n[PHASE 1] Building Leann index...")
+
+builder = LeannBuilder(
+ backend_name="diskann",
+ embedding_model="sentence-transformers/all-mpnet-base-v2", # Using a common sentence transformer model
+ graph_degree=32,
+ complexity=64
+)
+
+print(f"Loaded {len(all_texts)} text chunks from documents.")
+for chunk_text in all_texts:
+ builder.add_text(chunk_text)
+
+builder.build_index(INDEX_PATH)
+print(f"\nLeann index built at {INDEX_PATH}!")
+
+async def main():
+ print(f"\n[PHASE 2] Starting Leann chat session...")
+ chat = LeannChat(index_path=INDEX_PATH)
+
+ query = "Based on the paper, what are the two main techniques LEANN uses to achieve low storage overhead and high retrieval accuracy?"
+ print(f"You: {query}")
+ chat_response = chat.ask(query, recompute_beighbor_embeddings=True)
+ print(f"Leann: {chat_response}")
+
+if __name__ == "__main__":
+ asyncio.run(main())
\ No newline at end of file
diff --git a/examples/simple_demo.py b/examples/simple_demo.py
new file mode 100644
index 0000000..058841f
--- /dev/null
+++ b/examples/simple_demo.py
@@ -0,0 +1,81 @@
+"""
+Simple demo showing basic leann usage
+Run: uv run python examples/simple_demo.py
+"""
+
+from leann import LeannBuilder, LeannSearcher, LeannChat
+
+
+def main():
+ print("=== Leann Simple Demo ===")
+ print()
+
+ # Sample knowledge base
+ chunks = [
+ "Machine learning is a subset of artificial intelligence that enables computers to learn without being explicitly programmed.",
+ "Deep learning uses neural networks with multiple layers to process data and make decisions.",
+ "Natural language processing helps computers understand and generate human language.",
+ "Computer vision enables machines to interpret and understand visual information from images and videos.",
+ "Reinforcement learning teaches agents to make decisions by receiving rewards or penalties for their actions.",
+ "Data science combines statistics, programming, and domain expertise to extract insights from data.",
+ "Big data refers to extremely large datasets that require special tools and techniques to process.",
+ "Cloud computing provides on-demand access to computing resources over the internet.",
+ ]
+
+ print("1. Building index (no embeddings stored)...")
+ builder = LeannBuilder(
+ embedding_model="sentence-transformers/all-mpnet-base-v2",
+ prune_ratio=0.7, # Keep 30% of connections
+ )
+ builder.add_chunks(chunks)
+ builder.build_index("demo_knowledge.leann")
+ print()
+
+ print("2. Searching with real-time embeddings...")
+ searcher = LeannSearcher("demo_knowledge.leann")
+
+ queries = [
+ "What is machine learning?",
+ "How does neural network work?",
+ "Tell me about data processing",
+ ]
+
+ for query in queries:
+ print(f"Query: {query}")
+ results = searcher.search(query, top_k=2)
+
+ for i, result in enumerate(results, 1):
+ print(f" {i}. Score: {result.score:.3f}")
+ print(f" Text: {result.text[:100]}...")
+ print()
+
+ print("3. Memory stats:")
+ stats = searcher.get_memory_stats()
+ print(f" Cache size: {stats.embedding_cache_size}")
+ print(f" Cache memory: {stats.embedding_cache_memory_mb:.1f} MB")
+ print(f" Total chunks: {stats.total_chunks}")
+ print()
+
+ print("4. Interactive chat demo:")
+ print(" (Note: Requires OpenAI API key for real responses)")
+
+ chat = LeannChat("demo_knowledge.leann")
+
+ # Demo questions
+ demo_questions: list[str] = [
+ "What is the difference between machine learning and deep learning?",
+ "How is data science related to big data?",
+ ]
+
+ for question in demo_questions:
+ print(f" Q: {question}")
+ response = chat.ask(question)
+ print(f" A: {response}")
+ print()
+
+ print("Demo completed! Try running:")
+ print(" uv run python examples/document_search.py")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/knowledge.leann.meta.json b/knowledge.leann.meta.json
new file mode 100644
index 0000000..6a0d839
--- /dev/null
+++ b/knowledge.leann.meta.json
@@ -0,0 +1,32 @@
+{
+ "version": "0.1.0",
+ "backend_name": "diskann",
+ "embedding_model": "sentence-transformers/all-mpnet-base-v2",
+ "num_chunks": 6,
+ "chunks": [
+ {
+ "text": "Python is a powerful programming language",
+ "metadata": {}
+ },
+ {
+ "text": "Machine learning transforms industries",
+ "metadata": {}
+ },
+ {
+ "text": "Neural networks process complex data",
+ "metadata": {}
+ },
+ {
+ "text": "Java is a powerful programming language",
+ "metadata": {}
+ },
+ {
+ "text": "C++ is a powerful programming language",
+ "metadata": {}
+ },
+ {
+ "text": "C# is a powerful programming language",
+ "metadata": {}
+ }
+ ]
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/CMakeLists.txt b/packages/leann-backend-diskann/CMakeLists.txt
new file mode 100644
index 0000000..ee9d932
--- /dev/null
+++ b/packages/leann-backend-diskann/CMakeLists.txt
@@ -0,0 +1,8 @@
+# packages/leann-backend-diskann/CMakeLists.txt (最终简化版)
+
+cmake_minimum_required(VERSION 3.20)
+project(leann_backend_diskann_wrapper)
+
+# 告诉 CMake 直接进入 DiskANN 子模块并执行它自己的 CMakeLists.txt
+# DiskANN 会自己处理所有事情,包括编译 Python 绑定
+add_subdirectory(src/third_party/DiskANN)
diff --git a/packages/leann-backend-diskann/leann_backend_diskann/__init__.py b/packages/leann-backend-diskann/leann_backend_diskann/__init__.py
new file mode 100644
index 0000000..8074aa4
--- /dev/null
+++ b/packages/leann-backend-diskann/leann_backend_diskann/__init__.py
@@ -0,0 +1,7 @@
+print("Initializing leann-backend-diskann...")
+
+try:
+ from .diskann_backend import DiskannBackend
+ print("INFO: DiskANN backend loaded successfully")
+except ImportError as e:
+ print(f"WARNING: Could not import DiskANN backend: {e}")
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/leann_backend_diskann/diskann_backend.py b/packages/leann-backend-diskann/leann_backend_diskann/diskann_backend.py
new file mode 100644
index 0000000..71cf2fb
--- /dev/null
+++ b/packages/leann-backend-diskann/leann_backend_diskann/diskann_backend.py
@@ -0,0 +1,299 @@
+import numpy as np
+import os
+import json
+import struct
+from pathlib import Path
+from typing import Dict
+import contextlib
+import threading
+import time
+import atexit
+import socket
+import subprocess
+import sys
+
+from leann.registry import register_backend
+from leann.interface import (
+ LeannBackendFactoryInterface,
+ LeannBackendBuilderInterface,
+ LeannBackendSearcherInterface
+)
+from . import _diskannpy as diskannpy
+
+METRIC_MAP = {
+ "mips": diskannpy.Metric.INNER_PRODUCT,
+ "l2": diskannpy.Metric.L2,
+ "cosine": diskannpy.Metric.COSINE,
+}
+
+def chdir(path):
+ original_dir = os.getcwd()
+ os.chdir(path)
+ try:
+ yield
+ finally:
+ os.chdir(original_dir)
+
+def _write_vectors_to_bin(data: np.ndarray, file_path: str):
+ num_vectors, dim = data.shape
+ with open(file_path, 'wb') as f:
+ f.write(struct.pack('I', num_vectors))
+ f.write(struct.pack('I', dim))
+ f.write(data.tobytes())
+
+def _check_port(port: int) -> bool:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ return s.connect_ex(('localhost', port)) == 0
+
+class EmbeddingServerManager:
+ def __init__(self):
+ self.server_process = None
+ self.server_port = None
+ atexit.register(self.stop_server)
+
+ def start_server(self, port=5555, model_name="sentence-transformers/all-mpnet-base-v2"):
+ if self.server_process and self.server_process.poll() is None:
+ print(f"INFO: Reusing existing server process for this session (PID {self.server_process.pid})")
+ return True
+
+ # 检查端口是否已被其他无关进程占用
+ if _check_port(port):
+ print(f"WARNING: Port {port} is already in use. Assuming an external server is running and connecting to it.")
+ return True
+
+ print(f"INFO: Starting session-level embedding server as a background process...")
+
+ try:
+ command = [
+ sys.executable,
+ "-m", "packages.leann-backend-diskann.leann_backend_diskann.embedding_server",
+ "--zmq-port", str(port),
+ "--model-name", model_name
+ ]
+ project_root = Path(__file__).parent.parent.parent.parent
+ print(f"INFO: Running command from project root: {project_root}")
+ self.server_process = subprocess.Popen(
+ command,
+ cwd=project_root,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding='utf-8'
+ )
+ self.server_port = port
+ print(f"INFO: Server process started with PID: {self.server_process.pid}")
+
+ max_wait, wait_interval = 30, 0.5
+ for _ in range(int(max_wait / wait_interval)):
+ if _check_port(port):
+ print(f"✅ Embedding server is up and ready for this session.")
+ log_thread = threading.Thread(target=self._log_monitor, daemon=True)
+ log_thread.start()
+ return True
+ if self.server_process.poll() is not None:
+ print("❌ ERROR: Server process terminated unexpectedly during startup.")
+ self._log_monitor()
+ return False
+ time.sleep(wait_interval)
+
+ print(f"❌ ERROR: Server process failed to start listening within {max_wait} seconds.")
+ self.stop_server()
+ return False
+
+ except Exception as e:
+ print(f"❌ ERROR: Failed to start embedding server process: {e}")
+ return False
+
+ def _log_monitor(self):
+ if not self.server_process:
+ return
+ try:
+ if self.server_process.stdout:
+ for line in iter(self.server_process.stdout.readline, ''):
+ print(f"[EmbeddingServer LOG]: {line.strip()}")
+ self.server_process.stdout.close()
+ if self.server_process.stderr:
+ for line in iter(self.server_process.stderr.readline, ''):
+ print(f"[EmbeddingServer ERROR]: {line.strip()}")
+ self.server_process.stderr.close()
+ except Exception as e:
+ print(f"Log monitor error: {e}")
+
+ def stop_server(self):
+ if self.server_process and self.server_process.poll() is None:
+ print(f"INFO: Terminating session server process (PID: {self.server_process.pid})...")
+ self.server_process.terminate()
+ try:
+ self.server_process.wait(timeout=5)
+ print("INFO: Server process terminated.")
+ except subprocess.TimeoutExpired:
+ print("WARNING: Server process did not terminate gracefully, killing it.")
+ self.server_process.kill()
+ self.server_process = None
+
+@register_backend("diskann")
+class DiskannBackend(LeannBackendFactoryInterface):
+ @staticmethod
+ def builder(**kwargs) -> LeannBackendBuilderInterface:
+ return DiskannBuilder(**kwargs)
+
+ @staticmethod
+ def searcher(index_path: str, **kwargs) -> LeannBackendSearcherInterface:
+ path = Path(index_path)
+ meta_path = path.parent / f"{path.name}.meta.json"
+ if not meta_path.exists():
+ raise FileNotFoundError(f"Leann metadata file not found at {meta_path}. Cannot infer vector dimension for searcher.")
+ with open(meta_path, 'r') as f:
+ meta = json.load(f)
+
+ try:
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(meta.get("embedding_model"))
+ dimensions = model.get_sentence_embedding_dimension()
+ kwargs['dimensions'] = dimensions
+ except ImportError:
+ raise ImportError("sentence-transformers is required to infer embedding dimensions. Please install it.")
+ except Exception as e:
+ raise RuntimeError(f"Could not load SentenceTransformer model to get dimension: {e}")
+
+ return DiskannSearcher(index_path, **kwargs)
+
+class DiskannBuilder(LeannBackendBuilderInterface):
+ def __init__(self, **kwargs):
+ self.build_params = kwargs
+
+ def build(self, data: np.ndarray, index_path: str, **kwargs):
+ path = Path(index_path)
+ index_dir = path.parent
+ index_prefix = path.stem
+
+ index_dir.mkdir(parents=True, exist_ok=True)
+
+ if data.dtype != np.float32:
+ data = data.astype(np.float32)
+ if not data.flags['C_CONTIGUOUS']:
+ data = np.ascontiguousarray(data)
+
+ data_filename = f"{index_prefix}_data.bin"
+ _write_vectors_to_bin(data, index_dir / data_filename)
+
+ build_kwargs = {**self.build_params, **kwargs}
+ metric_str = build_kwargs.get("distance_metric", "mips").lower()
+ metric_enum = METRIC_MAP.get(metric_str)
+ if metric_enum is None:
+ raise ValueError(f"Unsupported distance_metric '{metric_str}'.")
+
+ complexity = build_kwargs.get("complexity", 64)
+ graph_degree = build_kwargs.get("graph_degree", 32)
+ final_index_ram_limit = build_kwargs.get("search_memory_maximum", 4.0)
+ indexing_ram_budget = build_kwargs.get("build_memory_maximum", 8.0)
+ num_threads = build_kwargs.get("num_threads", 8)
+ pq_disk_bytes = build_kwargs.get("pq_disk_bytes", 0)
+ codebook_prefix = ""
+
+ print(f"INFO: Building DiskANN index for {data.shape[0]} vectors with metric {metric_enum}...")
+
+ try:
+ with chdir(index_dir):
+ diskannpy.build_disk_float_index(
+ metric_enum,
+ data_filename,
+ index_prefix,
+ complexity,
+ graph_degree,
+ final_index_ram_limit,
+ indexing_ram_budget,
+ num_threads,
+ pq_disk_bytes,
+ codebook_prefix
+ )
+ print(f"✅ DiskANN index built successfully at '{index_dir / index_prefix}'")
+ except Exception as e:
+ print(f"💥 ERROR: DiskANN index build failed. Exception: {e}")
+ raise
+ finally:
+ temp_data_file = index_dir / data_filename
+ if temp_data_file.exists():
+ os.remove(temp_data_file)
+
+class DiskannSearcher(LeannBackendSearcherInterface):
+ def __init__(self, index_path: str, **kwargs):
+ path = Path(index_path)
+ index_dir = path.parent
+ index_prefix = path.stem
+ metric_str = kwargs.get("distance_metric", "mips").lower()
+ metric_enum = METRIC_MAP.get(metric_str)
+ if metric_enum is None:
+ raise ValueError(f"Unsupported distance_metric '{metric_str}'.")
+
+ num_threads = kwargs.get("num_threads", 8)
+ num_nodes_to_cache = kwargs.get("num_nodes_to_cache", 0)
+ dimensions = kwargs.get("dimensions")
+ if not dimensions:
+ raise ValueError("Vector dimension not provided to DiskannSearcher.")
+
+ try:
+ full_index_prefix = str(index_dir / index_prefix)
+ self._index = diskannpy.StaticDiskFloatIndex(
+ metric_enum, full_index_prefix, num_threads, num_nodes_to_cache, 1, "", ""
+ )
+ self.num_threads = num_threads
+ self.embedding_server_manager = EmbeddingServerManager()
+ print("✅ DiskANN index loaded successfully.")
+ except Exception as e:
+ print(f"💥 ERROR: Failed to load DiskANN index. Exception: {e}")
+ raise
+
+ def search(self, query: np.ndarray, top_k: int, **kwargs) -> Dict[str, any]:
+ complexity = kwargs.get("complexity", 100)
+ beam_width = kwargs.get("beam_width", 4)
+
+ USE_DEFERRED_FETCH = kwargs.get("USE_DEFERRED_FETCH", False)
+ skip_search_reorder = kwargs.get("skip_search_reorder", False)
+ recompute_beighbor_embeddings = kwargs.get("recompute_beighbor_embeddings", False)
+ dedup_node_dis = kwargs.get("dedup_node_dis", False)
+ prune_ratio = kwargs.get("prune_ratio", 0.0)
+ batch_recompute = kwargs.get("batch_recompute", False)
+ global_pruning = kwargs.get("global_pruning", False)
+
+ if recompute_beighbor_embeddings:
+ print(f"INFO: DiskANN ZMQ mode enabled - ensuring embedding server is running")
+ zmq_port = kwargs.get("zmq_port", 5555)
+ embedding_model = kwargs.get("embedding_model", "sentence-transformers/all-mpnet-base-v2")
+
+ if not self.embedding_server_manager.start_server(zmq_port, embedding_model):
+ print(f"WARNING: Failed to start embedding server, falling back to PQ computation")
+ kwargs['recompute_beighbor_embeddings'] = False
+
+ if query.dtype != np.float32:
+ query = query.astype(np.float32)
+ if query.ndim == 1:
+ query = np.expand_dims(query, axis=0)
+
+ try:
+ labels, distances = self._index.batch_search(
+ query,
+ query.shape[0],
+ top_k,
+ complexity,
+ beam_width,
+ self.num_threads,
+ USE_DEFERRED_FETCH,
+ skip_search_reorder,
+ recompute_beighbor_embeddings,
+ dedup_node_dis,
+ prune_ratio,
+ batch_recompute,
+ global_pruning
+ )
+ return {"labels": labels, "distances": distances}
+ except Exception as e:
+ print(f"💥 ERROR: DiskANN search failed. Exception: {e}")
+ batch_size = query.shape[0]
+ return {"labels": np.full((batch_size, top_k), -1, dtype=np.int64),
+ "distances": np.full((batch_size, top_k), float('inf'), dtype=np.float32)}
+
+ def __del__(self):
+ if hasattr(self, 'embedding_server_manager'):
+ self.embedding_server_manager.stop_server()
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/leann_backend_diskann/embedding_pb2.py b/packages/leann-backend-diskann/leann_backend_diskann/embedding_pb2.py
new file mode 100644
index 0000000..8285be2
--- /dev/null
+++ b/packages/leann-backend-diskann/leann_backend_diskann/embedding_pb2.py
@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: embedding.proto
+"""Generated protocol buffer code."""
+from google.protobuf.internal import builder as _builder
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import symbol_database as _symbol_database
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0f\x65mbedding.proto\x12\x0eprotoembedding\"(\n\x14NodeEmbeddingRequest\x12\x10\n\x08node_ids\x18\x01 \x03(\r\"Y\n\x15NodeEmbeddingResponse\x12\x17\n\x0f\x65mbeddings_data\x18\x01 \x01(\x0c\x12\x12\n\ndimensions\x18\x02 \x03(\x05\x12\x13\n\x0bmissing_ids\x18\x03 \x03(\rb\x06proto3')
+
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'embedding_pb2', globals())
+if _descriptor._USE_C_DESCRIPTORS == False:
+
+ DESCRIPTOR._options = None
+ _NODEEMBEDDINGREQUEST._serialized_start=35
+ _NODEEMBEDDINGREQUEST._serialized_end=75
+ _NODEEMBEDDINGRESPONSE._serialized_start=77
+ _NODEEMBEDDINGRESPONSE._serialized_end=166
+# @@protoc_insertion_point(module_scope)
diff --git a/packages/leann-backend-diskann/leann_backend_diskann/embedding_server.py b/packages/leann-backend-diskann/leann_backend_diskann/embedding_server.py
new file mode 100644
index 0000000..f2e715d
--- /dev/null
+++ b/packages/leann-backend-diskann/leann_backend_diskann/embedding_server.py
@@ -0,0 +1,397 @@
+#!/usr/bin/env python3
+"""
+Embedding server for leann-backend-diskann - Fixed ZMQ REQ-REP pattern
+"""
+
+import pickle
+import argparse
+import threading
+import time
+
+from transformers import AutoTokenizer, AutoModel
+import os
+from contextlib import contextmanager
+import zmq
+import numpy as np
+
+RED = "\033[91m"
+RESET = "\033[0m"
+
+# 简化的文档存储 - 替代 LazyPassages
+class SimpleDocumentStore:
+ """简化的文档存储,支持任意ID"""
+ def __init__(self, documents: dict = None):
+ self.documents = documents or {}
+ # 默认演示文档
+ self.default_docs = {
+ 0: "Python is a high-level, interpreted language known for simplicity.",
+ 1: "Machine learning builds systems that learn from data.",
+ 2: "Data structures like arrays, lists, and graphs organize data.",
+ }
+
+ def __getitem__(self, doc_id):
+ doc_id = int(doc_id)
+
+ # 优先使用指定的文档
+ if doc_id in self.documents:
+ return {"text": self.documents[doc_id]}
+
+ # 其次使用默认演示文档
+ if doc_id in self.default_docs:
+ return {"text": self.default_docs[doc_id]}
+
+ # 对于任意其他ID,返回通用文档
+ fallback_docs = [
+ "This is a general document about technology and programming concepts.",
+ "This document discusses machine learning and artificial intelligence topics.",
+ "This content covers data structures, algorithms, and computer science fundamentals.",
+ "This is a document about software engineering and development practices.",
+ "This content focuses on databases, data management, and information systems."
+ ]
+
+ # 根据ID选择一个fallback文档
+ fallback_text = fallback_docs[doc_id % len(fallback_docs)]
+ return {"text": f"[ID:{doc_id}] {fallback_text}"}
+
+ def __len__(self):
+ return len(self.documents) + len(self.default_docs)
+
+def create_embedding_server_thread(
+ zmq_port=5555,
+ model_name="sentence-transformers/all-mpnet-base-v2",
+ max_batch_size=128,
+):
+ """
+ 在当前线程中创建并运行 embedding server
+ 这个函数设计为在单独的线程中调用
+ """
+ print(f"INFO: Initializing embedding server thread on port {zmq_port}")
+
+ try:
+ # 检查端口是否已被占用
+ import socket
+ def check_port(port):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ return s.connect_ex(('localhost', port)) == 0
+
+ if check_port(zmq_port):
+ print(f"{RED}Port {zmq_port} is already in use{RESET}")
+ return
+
+ # 初始化模型
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
+ import torch
+
+ # 选择设备
+ mps_available = hasattr(torch.backends, 'mps') and torch.backends.mps.is_available()
+ cuda_available = torch.cuda.is_available()
+
+ if cuda_available:
+ device = torch.device("cuda")
+ print("INFO: Using CUDA device")
+ elif mps_available:
+ device = torch.device("mps")
+ print("INFO: Using MPS device (Apple Silicon)")
+ else:
+ device = torch.device("cpu")
+ print("INFO: Using CPU device")
+
+ # 加载模型
+ print(f"INFO: Loading model {model_name}")
+ model = AutoModel.from_pretrained(model_name).to(device).eval()
+
+ # 优化模型
+ if cuda_available or mps_available:
+ try:
+ model = model.half()
+ model = torch.compile(model)
+ print(f"INFO: Using FP16 precision with model: {model_name}")
+ except Exception as e:
+ print(f"WARNING: Model optimization failed: {e}")
+
+ # 默认演示文档
+ demo_documents = {
+ 0: "Python is a high-level, interpreted language known for simplicity.",
+ 1: "Machine learning builds systems that learn from data.",
+ 2: "Data structures like arrays, lists, and graphs organize data.",
+ }
+
+ passages = SimpleDocumentStore(demo_documents)
+ print(f"INFO: Loaded {len(passages)} demo documents")
+
+ class DeviceTimer:
+ """设备计时器"""
+ def __init__(self, name="", device=device):
+ self.name = name
+ self.device = device
+ self.start_time = 0
+ self.end_time = 0
+
+ if cuda_available:
+ self.start_event = torch.cuda.Event(enable_timing=True)
+ self.end_event = torch.cuda.Event(enable_timing=True)
+ else:
+ self.start_event = None
+ self.end_event = None
+
+ @contextmanager
+ def timing(self):
+ self.start()
+ yield
+ self.end()
+
+ def start(self):
+ if cuda_available:
+ torch.cuda.synchronize()
+ self.start_event.record()
+ else:
+ if self.device.type == "mps":
+ torch.mps.synchronize()
+ self.start_time = time.time()
+
+ def end(self):
+ if cuda_available:
+ self.end_event.record()
+ torch.cuda.synchronize()
+ else:
+ if self.device.type == "mps":
+ torch.mps.synchronize()
+ self.end_time = time.time()
+
+ def elapsed_time(self):
+ if cuda_available:
+ return self.start_event.elapsed_time(self.end_event) / 1000.0
+ else:
+ return self.end_time - self.start_time
+
+ def print_elapsed(self):
+ print(f"Time taken for {self.name}: {self.elapsed_time():.6f} seconds")
+
+ def process_batch(texts_batch, ids_batch, missing_ids):
+ """处理文本批次"""
+ batch_size = len(texts_batch)
+ print(f"INFO: Processing batch of size {batch_size}")
+
+ tokenize_timer = DeviceTimer("tokenization (batch)", device)
+ to_device_timer = DeviceTimer("transfer to device (batch)", device)
+ embed_timer = DeviceTimer("embedding (batch)", device)
+ pool_timer = DeviceTimer("mean pooling (batch)", device)
+
+ with tokenize_timer.timing():
+ encoded_batch = tokenizer.batch_encode_plus(
+ texts_batch,
+ padding="max_length",
+ truncation=True,
+ max_length=256,
+ return_tensors="pt",
+ return_token_type_ids=False,
+ )
+ tokenize_timer.print_elapsed()
+
+ seq_length = encoded_batch["input_ids"].size(1)
+ print(f"Batch size: {batch_size}, Sequence length: {seq_length}")
+
+ with to_device_timer.timing():
+ enc = {k: v.to(device) for k, v in encoded_batch.items()}
+ to_device_timer.print_elapsed()
+
+ with torch.no_grad():
+ with embed_timer.timing():
+ out = model(enc["input_ids"], enc["attention_mask"])
+ embed_timer.print_elapsed()
+
+ with pool_timer.timing():
+ hidden_states = out.last_hidden_state if hasattr(out, "last_hidden_state") else out
+ mask_expanded = enc["attention_mask"].unsqueeze(-1).expand(hidden_states.size()).float()
+ sum_embeddings = torch.sum(hidden_states * mask_expanded, 1)
+ sum_mask = torch.clamp(mask_expanded.sum(1), min=1e-9)
+ batch_embeddings = sum_embeddings / sum_mask
+ pool_timer.print_elapsed()
+
+ return batch_embeddings.cpu().numpy()
+
+ # ZMQ server 主循环 - 修改为REP套接字
+ context = zmq.Context()
+ socket = context.socket(zmq.ROUTER) # 改为REP套接字
+ socket.bind(f"tcp://127.0.0.1:{zmq_port}")
+ print(f"INFO: ZMQ ROUTER server listening on port {zmq_port}")
+
+ # 设置超时
+ socket.setsockopt(zmq.RCVTIMEO, 5000) # 5秒接收超时
+ socket.setsockopt(zmq.SNDTIMEO, 300000) # 300秒发送超时
+
+ from . import embedding_pb2
+
+ print(f"INFO: Embedding server ready to serve requests")
+
+ while True:
+ try:
+ parts = socket.recv_multipart()
+
+ # --- 恢复稳健的消息格式判断 ---
+ # 必须检查 parts 的长度,避免 IndexError
+ if len(parts) >= 3:
+ identity = parts[0]
+ # empty = parts[1] # 中间的空帧我们通常不关心
+ message = parts[2]
+ elif len(parts) == 2:
+ # 也能处理没有空帧的情况
+ identity = parts[0]
+ message = parts[1]
+ else:
+ # 如果收到格式错误的消息,打印警告并忽略它,而不是崩溃
+ print(f"WARNING: Received unexpected message format with {len(parts)} parts. Ignoring.")
+ continue
+ print(f"INFO: Received ZMQ request from client {identity.hex()[:8]}, size {len(message)} bytes")
+
+ e2e_start = time.time()
+ lookup_timer = DeviceTimer("text lookup", device)
+
+ # 解析请求
+ req_proto = embedding_pb2.NodeEmbeddingRequest()
+ req_proto.ParseFromString(message)
+ node_ids = req_proto.node_ids
+ print(f"INFO: Request for {len(node_ids)} node embeddings: {list(node_ids)}")
+
+ # 添加调试信息
+ if len(node_ids) > 0:
+ print(f"DEBUG: Node ID range: {min(node_ids)} to {max(node_ids)}")
+
+ # 查找文本
+ texts = []
+ missing_ids = []
+ with lookup_timer.timing():
+ for nid in node_ids:
+ txtinfo = passages[nid]
+ txt = txtinfo["text"]
+ texts.append(txt)
+ lookup_timer.print_elapsed()
+
+ if missing_ids:
+ print(f"WARNING: Missing passages for IDs: {missing_ids}")
+
+ # 处理批次
+ total_size = len(texts)
+ print(f"INFO: Total batch size: {total_size}, max_batch_size: {max_batch_size}")
+
+ all_embeddings = []
+
+ if total_size > max_batch_size:
+ print(f"INFO: Splitting batch of size {total_size} into chunks of {max_batch_size}")
+ for i in range(0, total_size, max_batch_size):
+ end_idx = min(i + max_batch_size, total_size)
+ print(f"INFO: Processing chunk {i//max_batch_size + 1}/{(total_size + max_batch_size - 1)//max_batch_size}: items {i} to {end_idx-1}")
+
+ chunk_texts = texts[i:end_idx]
+ chunk_ids = node_ids[i:end_idx]
+
+ embeddings_chunk = process_batch(chunk_texts, chunk_ids, missing_ids)
+ all_embeddings.append(embeddings_chunk)
+
+ if cuda_available:
+ torch.cuda.empty_cache()
+ elif device.type == "mps":
+ torch.mps.empty_cache()
+
+ hidden = np.vstack(all_embeddings)
+ print(f"INFO: Combined embeddings shape: {hidden.shape}")
+ else:
+ hidden = process_batch(texts, node_ids, missing_ids)
+
+ # 序列化响应
+ ser_start = time.time()
+
+ resp_proto = embedding_pb2.NodeEmbeddingResponse()
+ hidden_contiguous = np.ascontiguousarray(hidden, dtype=np.float32)
+ resp_proto.embeddings_data = hidden_contiguous.tobytes()
+ resp_proto.dimensions.append(hidden_contiguous.shape[0])
+ resp_proto.dimensions.append(hidden_contiguous.shape[1])
+ resp_proto.missing_ids.extend(missing_ids)
+
+ response_data = resp_proto.SerializeToString()
+
+ # REP 套接字发送单个响应
+ socket.send_multipart([identity, b'', response_data])
+
+ ser_end = time.time()
+
+ print(f"INFO: Serialize time: {ser_end - ser_start:.6f} seconds")
+
+ if device.type == "cuda":
+ torch.cuda.synchronize()
+ elif device.type == "mps":
+ torch.mps.synchronize()
+ e2e_end = time.time()
+ print(f"INFO: ZMQ E2E time: {e2e_end - e2e_start:.6f} seconds")
+
+ except zmq.Again:
+ print("INFO: ZMQ socket timeout, continuing to listen")
+ # REP套接字不需要重新创建,只需要继续监听
+ continue
+ except Exception as e:
+ print(f"ERROR: Error in ZMQ server: {e}")
+ try:
+ # 发送空响应以维持REQ-REP状态
+ empty_resp = embedding_pb2.NodeEmbeddingResponse()
+ socket.send(empty_resp.SerializeToString())
+ except:
+ # 如果发送失败,重新创建socket
+ socket.close()
+ socket = context.socket(zmq.REP)
+ socket.bind(f"tcp://127.0.0.1:{zmq_port}")
+ socket.setsockopt(zmq.RCVTIMEO, 5000)
+ socket.setsockopt(zmq.SNDTIMEO, 300000)
+ print("INFO: ZMQ socket recreated after error")
+
+ except Exception as e:
+ print(f"ERROR: Failed to start embedding server: {e}")
+ raise
+
+
+# 保持原有的 create_embedding_server 函数不变,只添加线程化版本
+def create_embedding_server(
+ domain="demo",
+ load_passages=True,
+ load_embeddings=False,
+ use_fp16=True,
+ use_int8=False,
+ use_cuda_graphs=False,
+ zmq_port=5555,
+ max_batch_size=128,
+ lazy_load_passages=False,
+ model_name="sentence-transformers/all-mpnet-base-v2",
+):
+ """
+ 原有的 create_embedding_server 函数保持不变
+ 这个是阻塞版本,用于直接运行
+ """
+ create_embedding_server_thread(zmq_port, model_name, max_batch_size)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Embedding service")
+ parser.add_argument("--zmq-port", type=int, default=5555, help="ZMQ port to run on")
+ parser.add_argument("--domain", type=str, default="demo", help="Domain name")
+ parser.add_argument("--load-passages", action="store_true", default=True)
+ parser.add_argument("--load-embeddings", action="store_true", default=False)
+ parser.add_argument("--use-fp16", action="store_true", default=False)
+ parser.add_argument("--use-int8", action="store_true", default=False)
+ parser.add_argument("--use-cuda-graphs", action="store_true", default=False)
+ parser.add_argument("--max-batch-size", type=int, default=128, help="Maximum batch size before splitting")
+ parser.add_argument("--lazy-load-passages", action="store_true", default=True)
+ parser.add_argument("--model-name", type=str, default="sentence-transformers/all-mpnet-base-v2",
+ help="Embedding model name")
+ args = parser.parse_args()
+
+ create_embedding_server(
+ domain=args.domain,
+ load_passages=args.load_passages,
+ load_embeddings=args.load_embeddings,
+ use_fp16=args.use_fp16,
+ use_int8=args.use_int8,
+ use_cuda_graphs=args.use_cuda_graphs,
+ zmq_port=args.zmq_port,
+ max_batch_size=args.max_batch_size,
+ lazy_load_passages=args.lazy_load_passages,
+ model_name=args.model_name,
+ )
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/pyproject.toml b/packages/leann-backend-diskann/pyproject.toml
new file mode 100644
index 0000000..70383e8
--- /dev/null
+++ b/packages/leann-backend-diskann/pyproject.toml
@@ -0,0 +1,16 @@
+[build-system]
+requires = ["scikit-build-core>=0.10", "pybind11>=2.12.0", "numpy"]
+build-backend = "scikit_build_core.build"
+
+[project]
+name = "leann-backend-diskann"
+version = "0.1.0"
+dependencies = ["leann-core==0.1.0", "numpy"]
+
+[tool.scikit-build]
+# 关键:简化的 CMake 路径
+cmake.source-dir = "third_party/DiskANN"
+# 关键:Python 包在根目录,路径完全匹配
+wheel.packages = ["leann_backend_diskann"]
+# 使用默认的 redirect 模式
+editable.mode = "redirect"
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.clang-format b/packages/leann-backend-diskann/third_party/DiskANN/.clang-format
new file mode 100644
index 0000000..ad3192f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.clang-format
@@ -0,0 +1,6 @@
+---
+BasedOnStyle: Microsoft
+---
+Language: Cpp
+SortIncludes: false
+...
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.gitattributes b/packages/leann-backend-diskann/third_party/DiskANN/.gitattributes
new file mode 100644
index 0000000..fbf9358
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.gitattributes
@@ -0,0 +1,14 @@
+# Set the default behavior, in case people don't have core.autocrlf set.
+* text=auto
+
+# Explicitly declare text files you want to always be normalized and converted
+# to native line endings on checkout.
+*.c text
+*.h text
+
+# Declare files that will always have CRLF line endings on checkout.
+*.sln text eol=crlf
+
+# Denote all files that are truly binary and should not be modified.
+*.png binary
+*.jpg binary
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/bug_report.md b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000..829d38d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,40 @@
+---
+name: Bug report
+about: Bug reports help us improve! Thanks for submitting yours!
+title: "[BUG] "
+labels: bug
+assignees: ''
+
+---
+
+## Expected Behavior
+Tell us what should happen
+
+## Actual Behavior
+Tell us what happens instead
+
+## Example Code
+Please see [How to create a Minimal, Reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) for some guidance on creating the best possible example of the problem
+```bash
+
+```
+
+## Dataset Description
+Please tell us about the shape and datatype of your data, (e.g. 128 dimensions, 12.3 billion points, floats)
+- Dimensions:
+- Number of Points:
+- Data type:
+
+## Error
+```
+Paste the full error, with any sensitive information minimally redacted and marked $$REDACTED$$
+
+```
+
+## Your Environment
+* Operating system (e.g. Windows 11 Pro, Ubuntu 22.04.1 LTS)
+* DiskANN version (or commit built from)
+
+## Additional Details
+Any other contextual information you might feel is important.
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/config.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..99d680b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,2 @@
+blank_issues_enabled: false
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/feature_request.md b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000..9c3c58c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,25 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+title: ''
+labels: enhancement
+assignees: ''
+
+---
+
+## Is your feature request related to a problem? Please describe.
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+
+## Describe the solution you'd like
+A clear and concise description of what you want to happen.
+
+## Describe alternatives you've considered
+A clear and concise description of any alternative solutions or features you've considered.
+
+## Provide references (if applicable)
+If your feature request is related to a published algorithm/idea, please provide links to
+any relevant articles or webpages.
+
+## Additional context
+Add any other context or screenshots about the feature request here.
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/usage-question.md b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/usage-question.md
new file mode 100644
index 0000000..7532f76
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/ISSUE_TEMPLATE/usage-question.md
@@ -0,0 +1,11 @@
+---
+name: Usage Question
+about: Ask us a question about DiskANN!
+title: "[Question]"
+labels: question
+assignees: ''
+
+---
+
+This is our forum for asking whatever DiskANN question you'd like! No need to feel shy - we're happy to talk about use cases and optimal tuning strategies!
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/PULL_REQUEST_TEMPLATE.md b/packages/leann-backend-diskann/third_party/DiskANN/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..0b97019
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,22 @@
+<!--
+Thanks for contributing a pull request! Please ensure you have taken a look at
+the contribution guidelines: https://github.com/microsoft/DiskANN/blob/main/CONTRIBUTING.md
+-->
+- [ ] Does this PR have a descriptive title that could go in our release notes?
+- [ ] Does this PR add any new dependencies?
+- [ ] Does this PR modify any existing APIs?
+ - [ ] Is the change to the API backwards compatible?
+- [ ] Should this result in any changes to our documentation, either updating existing docs or adding new ones?
+
+#### Reference Issues/PRs
+<!--
+Example: Fixes #1234. See also #3456.
+Please use keywords (e.g., Fixes) to create link to the issues or pull requests
+you resolved, so that they will automatically be closed when your pull request
+is merged. See https://github.com/blog/1506-closing-issues-via-pull-requests
+-->
+
+#### What does this implement/fix? Briefly explain your changes.
+
+#### Any other comments?
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/build/action.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/build/action.yml
new file mode 100644
index 0000000..219d9d6
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/build/action.yml
@@ -0,0 +1,39 @@
+name: 'DiskANN Build Bootstrap'
+description: 'Prepares DiskANN build environment and executes build'
+runs:
+ using: "composite"
+ steps:
+ # ------------ Linux Build ---------------
+ - name: Prepare and Execute Build
+ if: ${{ runner.os == 'Linux' }}
+ run: |
+ sudo scripts/dev/install-dev-deps-ubuntu.bash
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DUNIT_TEST=True
+ cmake --build build -- -j
+ cmake --install build --prefix="dist"
+ shell: bash
+ # ------------ End Linux Build ---------------
+ # ------------ Windows Build ---------------
+ - name: Add VisualStudio command line tools into path
+ if: runner.os == 'Windows'
+ uses: ilammy/msvc-dev-cmd@v1
+ - name: Run configure and build for Windows
+ if: runner.os == 'Windows'
+ run: |
+ mkdir build && cd build && cmake .. -DUNIT_TEST=True && msbuild diskann.sln /m /nologo /t:Build /p:Configuration="Release" /property:Platform="x64" -consoleloggerparameters:"ErrorsOnly;Summary"
+ cd ..
+ mkdir dist
+ mklink /j .\dist\bin .\x64\Release\
+ shell: cmd
+ # ------------ End Windows Build ---------------
+ # ------------ Windows Build With EXEC_ENV_OLS and USE_BING_INFRA ---------------
+ - name: Add VisualStudio command line tools into path
+ if: runner.os == 'Windows'
+ uses: ilammy/msvc-dev-cmd@v1
+ - name: Run configure and build for Windows with Bing feature flags
+ if: runner.os == 'Windows'
+ run: |
+ mkdir build_bing && cd build_bing && cmake .. -DEXEC_ENV_OLS=1 -DUSE_BING_INFRA=1 -DUNIT_TEST=True && msbuild diskann.sln /m /nologo /t:Build /p:Configuration="Release" /property:Platform="x64" -consoleloggerparameters:"ErrorsOnly;Summary"
+ cd ..
+ shell: cmd
+ # ------------ End Windows Build ---------------
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/format-check/action.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/format-check/action.yml
new file mode 100644
index 0000000..6ed08c0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/format-check/action.yml
@@ -0,0 +1,13 @@
+name: 'Checking code formatting...'
+description: 'Ensures code complies with code formatting rules'
+runs:
+ using: "composite"
+ steps:
+ - name: Checking code formatting...
+ run: |
+ sudo apt install clang-format
+ find include -name '*.h' -type f -print0 | xargs -0 -P 16 /usr/bin/clang-format --Werror --dry-run
+ find src -name '*.cpp' -type f -print0 | xargs -0 -P 16 /usr/bin/clang-format --Werror --dry-run
+ find apps -name '*.cpp' -type f -print0 | xargs -0 -P 16 /usr/bin/clang-format --Werror --dry-run
+ find python -name '*.cpp' -type f -print0 | xargs -0 -P 16 /usr/bin/clang-format --Werror --dry-run
+ shell: bash
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/generate-high-dim-random/action.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/generate-high-dim-random/action.yml
new file mode 100644
index 0000000..65e9b7e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/generate-high-dim-random/action.yml
@@ -0,0 +1,28 @@
+name: 'Generating Random Data (Basic)'
+description: 'Generates the random data files used in acceptance tests'
+runs:
+ using: "composite"
+ steps:
+ - name: Generate Random Data (Basic)
+ run: |
+ mkdir data
+
+ echo "Generating random 1020,1024,1536D float and 4096 int8 vectors for index"
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_1020D_5K_norm1.0.bin -D 1020 -N 5000 --norm 1.0
+ #dist/bin/rand_data_gen --data_type float --output_file data/rand_float_1024D_5K_norm1.0.bin -D 1024 -N 5000 --norm 1.0
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_1536D_5K_norm1.0.bin -D 1536 -N 5000 --norm 1.0
+ dist/bin/rand_data_gen --data_type int8 --output_file data/rand_int8_4096D_5K_norm1.0.bin -D 4096 -N 5000 --norm 1.0
+
+ echo "Generating random 1020,1024,1536D float and 4096D int8 avectors for query"
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_1020D_1K_norm1.0.bin -D 1020 -N 1000 --norm 1.0
+ #dist/bin/rand_data_gen --data_type float --output_file data/rand_float_1024D_1K_norm1.0.bin -D 1024 -N 1000 --norm 1.0
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_1536D_1K_norm1.0.bin -D 1536 -N 1000 --norm 1.0
+ dist/bin/rand_data_gen --data_type int8 --output_file data/rand_int8_4096D_1K_norm1.0.bin -D 4096 -N 1000 --norm 1.0
+
+ echo "Computing ground truth for 1020,1024,1536D float and 4096D int8 avectors for query"
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/rand_float_1020D_5K_norm1.0.bin --query_file data/rand_float_1020D_1K_norm1.0.bin --gt_file data/l2_rand_float_1020D_5K_norm1.0_1020D_1K_norm1.0_gt100 --K 100
+ #dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/rand_float_1024D_5K_norm1.0.bin --query_file data/rand_float_1024D_1K_norm1.0.bin --gt_file data/l2_rand_float_1024D_5K_norm1.0_1024D_1K_norm1.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/rand_float_1536D_5K_norm1.0.bin --query_file data/rand_float_1536D_1K_norm1.0.bin --gt_file data/l2_rand_float_1536D_5K_norm1.0_1536D_1K_norm1.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type int8 --dist_fn l2 --base_file data/rand_int8_4096D_5K_norm1.0.bin --query_file data/rand_int8_4096D_1K_norm1.0.bin --gt_file data/l2_rand_int8_4096D_5K_norm1.0_4096D_1K_norm1.0_gt100 --K 100
+
+ shell: bash
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/generate-random/action.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/generate-random/action.yml
new file mode 100644
index 0000000..2755067
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/generate-random/action.yml
@@ -0,0 +1,38 @@
+name: 'Generating Random Data (Basic)'
+description: 'Generates the random data files used in acceptance tests'
+runs:
+ using: "composite"
+ steps:
+ - name: Generate Random Data (Basic)
+ run: |
+ mkdir data
+
+ echo "Generating random vectors for index"
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_10D_10K_norm1.0.bin -D 10 -N 10000 --norm 1.0
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_10D_10K_unnorm.bin -D 10 -N 10000 --rand_scaling 2.0
+ dist/bin/rand_data_gen --data_type int8 --output_file data/rand_int8_10D_10K_norm50.0.bin -D 10 -N 10000 --norm 50.0
+ dist/bin/rand_data_gen --data_type uint8 --output_file data/rand_uint8_10D_10K_norm50.0.bin -D 10 -N 10000 --norm 50.0
+
+ echo "Generating random vectors for query"
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_10D_1K_norm1.0.bin -D 10 -N 1000 --norm 1.0
+ dist/bin/rand_data_gen --data_type float --output_file data/rand_float_10D_1K_unnorm.bin -D 10 -N 1000 --rand_scaling 2.0
+ dist/bin/rand_data_gen --data_type int8 --output_file data/rand_int8_10D_1K_norm50.0.bin -D 10 -N 1000 --norm 50.0
+ dist/bin/rand_data_gen --data_type uint8 --output_file data/rand_uint8_10D_1K_norm50.0.bin -D 10 -N 1000 --norm 50.0
+
+ echo "Computing ground truth for floats across l2, mips, and cosine distance functions"
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/rand_float_10D_10K_norm1.0.bin --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type float --dist_fn mips --base_file data/rand_float_10D_10K_norm1.0.bin --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/mips_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type float --dist_fn cosine --base_file data/rand_float_10D_10K_norm1.0.bin --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/cosine_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type float --dist_fn cosine --base_file data/rand_float_10D_10K_unnorm.bin --query_file data/rand_float_10D_1K_unnorm.bin --gt_file data/cosine_rand_float_10D_10K_unnorm_10D_1K_unnorm_gt100 --K 100
+
+ echo "Computing ground truth for int8s across l2, mips, and cosine distance functions"
+ dist/bin/compute_groundtruth --data_type int8 --dist_fn l2 --base_file data/rand_int8_10D_10K_norm50.0.bin --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type int8 --dist_fn mips --base_file data/rand_int8_10D_10K_norm50.0.bin --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/mips_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type int8 --dist_fn cosine --base_file data/rand_int8_10D_10K_norm50.0.bin --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/cosine_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+
+ echo "Computing ground truth for uint8s across l2, mips, and cosine distance functions"
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn l2 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn mips --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/mips_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn cosine --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/cosine_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+
+ shell: bash
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/python-wheel/action.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/python-wheel/action.yml
new file mode 100644
index 0000000..6a2880c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/actions/python-wheel/action.yml
@@ -0,0 +1,22 @@
+name: Build Python Wheel
+description: Builds a python wheel with cibuildwheel
+inputs:
+ cibw-identifier:
+ description: "CI build wheel identifier to build"
+ required: true
+runs:
+ using: "composite"
+ steps:
+ - uses: actions/setup-python@v3
+ - name: Install cibuildwheel
+ run: python -m pip install cibuildwheel==2.11.3
+ shell: bash
+ - name: Building Python ${{inputs.cibw-identifier}} Wheel
+ run: python -m cibuildwheel --output-dir dist
+ env:
+ CIBW_BUILD: ${{inputs.cibw-identifier}}
+ shell: bash
+ - uses: actions/upload-artifact@v3
+ with:
+ name: wheels
+ path: ./dist/*.whl
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/build-python-pdoc.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/build-python-pdoc.yml
new file mode 100644
index 0000000..444a7ee
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/build-python-pdoc.yml
@@ -0,0 +1,81 @@
+name: DiskANN Build PDoc Documentation
+on: [workflow_call]
+jobs:
+ build-reference-documentation:
+ permissions:
+ contents: write
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Set up Python 3.9
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.9
+ - name: Install python build
+ run: python -m pip install build
+ shell: bash
+ # Install required dependencies
+ - name: Prepare Linux environment
+ run: |
+ sudo scripts/dev/install-dev-deps-ubuntu.bash
+ shell: bash
+ # We need to build the wheel in order to run pdoc. pdoc does not seem to work if you just point it at
+ # our source directory.
+ - name: Building Python Wheel for documentation generation
+ run: python -m build --wheel --outdir documentation_dist
+ shell: bash
+ - name: "Run Reference Documentation Generation"
+ run: |
+ pip install pdoc pipdeptree
+ pip install documentation_dist/*.whl
+ echo "documentation" > dependencies_documentation.txt
+ pipdeptree >> dependencies_documentation.txt
+ pdoc -o docs/python/html diskannpy
+ - name: Create version environment variable
+ run: |
+ echo "DISKANN_VERSION=$(python <<EOF
+ from importlib.metadata import version
+ v = version('diskannpy')
+ print(v)
+ EOF
+ )" >> $GITHUB_ENV
+ - name: Archive documentation version artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: dependencies
+ path: |
+ ${{ github.run_id }}-dependencies_documentation.txt
+ overwrite: true
+ - name: Archive documentation artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: documentation-site
+ path: |
+ docs/python/html
+ # Publish to /dev if we are on the "main" branch
+ - name: Publish reference docs for latest development version (main branch)
+ uses: peaceiris/actions-gh-pages@v3
+ if: github.ref == 'refs/heads/main'
+ with:
+ github_token: ${{ secrets.GITHUB_TOKEN }}
+ publish_dir: docs/python/html
+ destination_dir: docs/python/dev
+ # Publish to /<version> if we are releasing
+ - name: Publish reference docs by version (main branch)
+ uses: peaceiris/actions-gh-pages@v3
+ if: github.event_name == 'release'
+ with:
+ github_token: ${{ secrets.GITHUB_TOKEN }}
+ publish_dir: docs/python/html
+ destination_dir: docs/python/${{ env.DISKANN_VERSION }}
+ # Publish to /latest if we are releasing
+ - name: Publish latest reference docs (main branch)
+ uses: peaceiris/actions-gh-pages@v3
+ if: github.event_name == 'release'
+ with:
+ github_token: ${{ secrets.GITHUB_TOKEN }}
+ publish_dir: docs/python/html
+ destination_dir: docs/python/latest
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/build-python.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/build-python.yml
new file mode 100644
index 0000000..b825398
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/build-python.yml
@@ -0,0 +1,42 @@
+name: DiskANN Build Python Wheel
+on: [workflow_call]
+jobs:
+ linux-build:
+ name: Python - Ubuntu - ${{matrix.cibw-identifier}}
+ strategy:
+ fail-fast: false
+ matrix:
+ cibw-identifier: ["cp39-manylinux_x86_64", "cp310-manylinux_x86_64", "cp311-manylinux_x86_64"]
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Building python wheel ${{matrix.cibw-identifier}}
+ uses: ./.github/actions/python-wheel
+ with:
+ cibw-identifier: ${{matrix.cibw-identifier}}
+ windows-build:
+ name: Python - Windows - ${{matrix.cibw-identifier}}
+ strategy:
+ fail-fast: false
+ matrix:
+ cibw-identifier: ["cp39-win_amd64", "cp310-win_amd64", "cp311-win_amd64"]
+ runs-on: windows-latest
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ submodules: true
+ fetch-depth: 1
+ - name: Building python wheel ${{matrix.cibw-identifier}}
+ uses: ./.github/actions/python-wheel
+ with:
+ cibw-identifier: ${{matrix.cibw-identifier}}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/common.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/common.yml
new file mode 100644
index 0000000..09c020a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/common.yml
@@ -0,0 +1,28 @@
+name: DiskANN Common Checks
+# common means common to both pr-test and push-test
+on: [workflow_call]
+jobs:
+ formatting-check:
+ strategy:
+ fail-fast: true
+ name: Code Formatting Test
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checking code formatting...
+ uses: ./.github/actions/format-check
+ docker-container-build:
+ name: Docker Container Build
+ needs: [formatting-check]
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Docker build
+ run: |
+ docker build .
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/disk-pq.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/disk-pq.yml
new file mode 100644
index 0000000..930d213
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/disk-pq.yml
@@ -0,0 +1,117 @@
+name: Disk With PQ
+on: [workflow_call]
+jobs:
+ acceptance-tests-disk-pq:
+ name: Disk, PQ
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-random
+
+ - name: build and search disk index (one shot graph build, L2, no diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskfull_oneshot -R 16 -L 32 -B 0.00003 -M 1
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (one shot graph build, cosine, no diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn cosine --data_path data/rand_float_10D_10K_unnorm.bin --index_path_prefix data/disk_index_cosine_rand_float_10D_10K_unnorm_diskfull_oneshot -R 16 -L 32 -B 0.00003 -M 1
+ dist/bin/search_disk_index --data_type float --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/disk_index_cosine_rand_float_10D_10K_unnorm_diskfull_oneshot --result_path /tmp/res --query_file data/rand_float_10D_1K_unnorm.bin --gt_file data/cosine_rand_float_10D_10K_unnorm_10D_1K_unnorm_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (one shot graph build, L2, no diskPQ) (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskfull_oneshot -R 16 -L 32 -B 0.00003 -M 1
+ dist/bin/search_disk_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (one shot graph build, L2, no diskPQ) (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskfull_oneshot -R 16 -L 32 -B 0.00003 -M 1
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+
+ - name: build and search disk index (one shot graph build, L2, no diskPQ, build with PQ distance comparisons) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskfull_oneshot_buildpq5 -R 16 -L 32 -B 0.00003 -M 1 --build_PQ_bytes 5
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskfull_oneshot_buildpq5 --result_path /tmp/res --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (one shot graph build, L2, no diskPQ, build with PQ distance comparisons) (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskfull_oneshot_buildpq5 -R 16 -L 32 -B 0.00003 -M 1 --build_PQ_bytes 5
+ dist/bin/search_disk_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskfull_oneshot_buildpq5 --result_path /tmp/res --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16\
+ - name: build and search disk index (one shot graph build, L2, no diskPQ, build with PQ distance comparisons) (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskfull_oneshot_buildpq5 -R 16 -L 32 -B 0.00003 -M 1 --build_PQ_bytes 5
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskfull_oneshot_buildpq5 --result_path /tmp/res --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+
+ - name: build and search disk index (sharded graph build, L2, no diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskfull_sharded -R 16 -L 32 -B 0.00003 -M 0.00006
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskfull_sharded --result_path /tmp/res --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (sharded graph build, cosine, no diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn cosine --data_path data/rand_float_10D_10K_unnorm.bin --index_path_prefix data/disk_index_cosine_rand_float_10D_10K_unnorm_diskfull_sharded -R 16 -L 32 -B 0.00003 -M 0.00006
+ dist/bin/search_disk_index --data_type float --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/disk_index_cosine_rand_float_10D_10K_unnorm_diskfull_sharded --result_path /tmp/res --query_file data/rand_float_10D_1K_unnorm.bin --gt_file data/cosine_rand_float_10D_10K_unnorm_10D_1K_unnorm_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (sharded graph build, L2, no diskPQ) (int8)
+ run: |
+ dist/bin/build_disk_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskfull_sharded -R 16 -L 32 -B 0.00003 -M 0.00006
+ dist/bin/search_disk_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskfull_sharded --result_path /tmp/res --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (sharded graph build, L2, no diskPQ) (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskfull_sharded -R 16 -L 32 -B 0.00003 -M 0.00006
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskfull_sharded --result_path /tmp/res --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+
+ - name: build and search disk index (one shot graph build, L2, diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskpq_oneshot -R 16 -L 32 -B 0.00003 -M 1 --PQ_disk_bytes 5
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_10D_10K_norm1.0_diskpq_oneshot --result_path /tmp/res --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (one shot graph build, L2, diskPQ) (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskpq_oneshot -R 16 -L 32 -B 0.00003 -M 1 --PQ_disk_bytes 5
+ dist/bin/search_disk_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_int8_10D_10K_norm50.0_diskpq_oneshot --result_path /tmp/res --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search disk index (one shot graph build, L2, diskPQ) (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskpq_oneshot -R 16 -L 32 -B 0.00003 -M 1 --PQ_disk_bytes 5
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50.0_diskpq_oneshot --result_path /tmp/res --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+
+ - name: build and search disk index (sharded graph build, MIPS, diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn mips --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/disk_index_mips_rand_float_10D_10K_norm1.0_diskpq_sharded -R 16 -L 32 -B 0.00003 -M 0.00006 --PQ_disk_bytes 5
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_mips_rand_float_10D_10K_norm1.0_diskpq_sharded --result_path /tmp/res --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/mips_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+
+ - name: upload data and bin
+ uses: actions/upload-artifact@v4
+ with:
+ name: disk-pq-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/dynamic-labels.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/dynamic-labels.yml
new file mode 100644
index 0000000..d5dc712
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/dynamic-labels.yml
@@ -0,0 +1,102 @@
+name: Dynamic-Labels
+on: [workflow_call]
+jobs:
+ acceptance-tests-dynamic:
+ name: Dynamic-Labels
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-random
+
+ - name: Generate Labels
+ run: |
+ echo "Generating synthetic labels and computing ground truth for filtered search with universal label"
+ dist/bin/generate_synthetic_labels --num_labels 50 --num_points 10000 --output_file data/rand_labels_50_10K.txt --distribution_type random
+
+ echo "Generating synthetic labels with a zipf distribution and computing ground truth for filtered search with universal label"
+ dist/bin/generate_synthetic_labels --num_labels 50 --num_points 10000 --output_file data/zipf_labels_50_10K.txt --distribution_type zipf
+
+ - name: Test a streaming index (float) with labels (Zipf distributed)
+ run: |
+ dist/bin/test_streaming_scenario --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --universal_label 0 --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/index_zipf_stream -R 64 --FilteredLbuild 200 -L 50 --alpha 1.2 --insert_threads 8 --consolidate_threads 8 --max_points_to_insert 10000 --active_window 4000 --consolidate_interval 2000 --start_point_norm 3.2 --unique_labels_supported 51
+
+ echo "Computing groundtruth with filter"
+ dist/bin/compute_groundtruth_for_filters --data_type float --universal_label 0 --filter_label 1 --dist_fn l2 --base_file data/index_zipf_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_zipf_base-act4000-cons2000-max10000_1 --label_file data/index_zipf_stream.after-streaming-act4000-cons2000-max10000_raw_labels.txt --tags_file data/index_zipf_stream.after-streaming-act4000-cons2000-max10000.tags
+ echo "Searching with filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --filter_label 1 --fail_if_recall_below 40 --index_path_prefix data/index_zipf_stream.after-streaming-act4000-cons2000-max10000 --result_path data/res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_zipf_base-act4000-cons2000-max10000_1 -K 10 -L 20 40 60 80 100 150 -T 64 --dynamic true --tags 1
+
+ echo "Computing groundtruth w/o filter"
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/index_zipf_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_zipf_base-act4000-cons2000-max10000
+ echo "Searching without filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_zipf_stream.after-streaming-act4000-cons2000-max10000 --result_path res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_zipf_base-act4000-cons2000-max10000 -K 10 -L 20 40 60 80 100 -T 64
+
+ - name: Test a streaming index (float) with labels (random distributed)
+ run: |
+ dist/bin/test_streaming_scenario --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --universal_label 0 --label_file data/rand_labels_50_10K.txt --index_path_prefix data/index_rand_stream -R 64 --FilteredLbuild 200 -L 50 --alpha 1.2 --insert_threads 8 --consolidate_threads 8 --max_points_to_insert 10000 --active_window 4000 --consolidate_interval 2000 --start_point_norm 3.2 --unique_labels_supported 51
+
+ echo "Computing groundtruth with filter"
+ dist/bin/compute_groundtruth_for_filters --data_type float --universal_label 0 --filter_label 1 --dist_fn l2 --base_file data/index_rand_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_rand_base-act4000-cons2000-max10000_1 --label_file data/index_rand_stream.after-streaming-act4000-cons2000-max10000_raw_labels.txt --tags_file data/index_rand_stream.after-streaming-act4000-cons2000-max10000.tags
+ echo "Searching with filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --filter_label 1 --fail_if_recall_below 40 --index_path_prefix data/index_rand_stream.after-streaming-act4000-cons2000-max10000 --result_path data/res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_rand_base-act4000-cons2000-max10000_1 -K 10 -L 20 40 60 80 100 150 -T 64 --dynamic true --tags 1
+
+ echo "Computing groundtruth w/o filter"
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/index_rand_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_rand_base-act4000-cons2000-max10000
+ echo "Searching without filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_rand_stream.after-streaming-act4000-cons2000-max10000 --result_path res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_rand_base-act4000-cons2000-max10000 -K 10 -L 20 40 60 80 100 -T 64
+
+ - name: Test Insert Delete Consolidate (float) with labels (zipf distributed)
+ run: |
+ dist/bin/test_insert_deletes_consolidate --data_type float --dist_fn l2 --universal_label 0 --label_file data/zipf_labels_50_10K.txt --FilteredLbuild 70 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_zipf_ins_del -R 64 -L 10 --alpha 1.2 --points_to_skip 0 --max_points_to_insert 7500 --beginning_index_size 0 --points_per_checkpoint 1000 --checkpoints_per_snapshot 0 --points_to_delete_from_beginning 2500 --start_deletes_after 5000 --do_concurrent true --start_point_norm 3.2 --unique_labels_supported 51
+
+ echo "Computing groundtruth with filter"
+ dist/bin/compute_groundtruth_for_filters --data_type float --filter_label 5 --universal_label 0 --dist_fn l2 --base_file data/index_zipf_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_zipf_random10D_1K_wlabel_5 --label_file data/index_zipf_ins_del.after-concurrent-delete-del2500-7500_raw_labels.txt --tags_file data/index_zipf_ins_del.after-concurrent-delete-del2500-7500.tags
+ echo "Searching with filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --filter_label 5 --fail_if_recall_below 10 --index_path_prefix data/index_zipf_ins_del.after-concurrent-delete-del2500-7500 --result_path data/res_zipf_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_zipf_random10D_1K_wlabel_5 -K 10 -L 20 40 60 80 100 150 -T 64 --dynamic true --tags 1
+
+ echo "Computing groundtruth w/o filter"
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/index_zipf_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_zipf_random10D_1K
+ echo "Searching without filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_zipf_ins_del.after-concurrent-delete-del2500-7500 --result_path res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_zipf_random10D_1K -K 10 -L 20 40 60 80 100 -T 64
+
+ - name: Test Insert Delete Consolidate (float) with labels (random distributed)
+ run: |
+ dist/bin/test_insert_deletes_consolidate --data_type float --dist_fn l2 --universal_label 0 --label_file data/rand_labels_50_10K.txt --FilteredLbuild 70 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_rand_ins_del -R 64 -L 10 --alpha 1.2 --points_to_skip 0 --max_points_to_insert 7500 --beginning_index_size 0 --points_per_checkpoint 1000 --checkpoints_per_snapshot 0 --points_to_delete_from_beginning 2500 --start_deletes_after 5000 --do_concurrent true --start_point_norm 3.2 --unique_labels_supported 51
+
+ echo "Computing groundtruth with filter"
+ dist/bin/compute_groundtruth_for_filters --data_type float --filter_label 5 --universal_label 0 --dist_fn l2 --base_file data/index_rand_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_rand_random10D_1K_wlabel_5 --label_file data/index_rand_ins_del.after-concurrent-delete-del2500-7500_raw_labels.txt --tags_file data/index_rand_ins_del.after-concurrent-delete-del2500-7500.tags
+ echo "Searching with filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --filter_label 5 --fail_if_recall_below 40 --index_path_prefix data/index_rand_ins_del.after-concurrent-delete-del2500-7500 --result_path data/res_rand_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_rand_random10D_1K_wlabel_5 -K 10 -L 20 40 60 80 100 150 -T 64 --dynamic true --tags 1
+
+ echo "Computing groundtruth w/o filter"
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/index_rand_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_rand_random10D_1K
+ echo "Searching without filter"
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_rand_ins_del.after-concurrent-delete-del2500-7500 --result_path res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_rand_random10D_1K -K 10 -L 20 40 60 80 100 -T 64
+
+ - name: upload data and bin
+ uses: actions/upload-artifact@v4
+ with:
+ name: dynamic-labels-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/dynamic.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/dynamic.yml
new file mode 100644
index 0000000..edd691e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/dynamic.yml
@@ -0,0 +1,75 @@
+name: Dynamic
+on: [workflow_call]
+jobs:
+ acceptance-tests-dynamic:
+ name: Dynamic
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-random
+
+ - name: test a streaming index (float)
+ run: |
+ dist/bin/test_streaming_scenario --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_stream -R 64 -L 600 --alpha 1.2 --insert_threads 4 --consolidate_threads 4 --max_points_to_insert 10000 --active_window 4000 --consolidate_interval 2000 --start_point_norm 3.2
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/index_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_base-act4000-cons2000-max10000 --tags_file data/index_stream.after-streaming-act4000-cons2000-max10000.tags
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_stream.after-streaming-act4000-cons2000-max10000 --result_path data/res_stream --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_base-act4000-cons2000-max10000 -K 10 -L 20 40 60 80 100 -T 64 --dynamic true --tags 1
+ - name: test a streaming index (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/test_streaming_scenario --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/index_stream -R 64 -L 600 --alpha 1.2 --insert_threads 4 --consolidate_threads 4 --max_points_to_insert 10000 --active_window 4000 --consolidate_interval 2000 --start_point_norm 200
+ dist/bin/compute_groundtruth --data_type int8 --dist_fn l2 --base_file data/index_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_int8_10D_1K_norm50.0.bin --K 100 --gt_file data/gt100_base-act4000-cons2000-max10000 --tags_file data/index_stream.after-streaming-act4000-cons2000-max10000.tags
+ dist/bin/search_memory_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_stream.after-streaming-act4000-cons2000-max10000 --result_path res_stream --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/gt100_base-act4000-cons2000-max10000 -K 10 -L 20 40 60 80 100 -T 64 --dynamic true --tags 1
+ - name: test a streaming index
+ if: success() || failure()
+ run: |
+ dist/bin/test_streaming_scenario --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/index_stream -R 64 -L 600 --alpha 1.2 --insert_threads 4 --consolidate_threads 4 --max_points_to_insert 10000 --active_window 4000 --consolidate_interval 2000 --start_point_norm 200
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn l2 --base_file data/index_stream.after-streaming-act4000-cons2000-max10000.data --query_file data/rand_uint8_10D_1K_norm50.0.bin --K 100 --gt_file data/gt100_base-act4000-cons2000-max10000 --tags_file data/index_stream.after-streaming-act4000-cons2000-max10000.tags
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_stream.after-streaming-act4000-cons2000-max10000 --result_path data/res_stream --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/gt100_base-act4000-cons2000-max10000 -K 10 -L 20 40 60 80 100 -T 64 --dynamic true --tags 1
+
+ - name: build and search an incremental index (float)
+ if: success() || failure()
+ run: |
+ dist/bin/test_insert_deletes_consolidate --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_ins_del -R 64 -L 300 --alpha 1.2 -T 8 --points_to_skip 0 --max_points_to_insert 7500 --beginning_index_size 0 --points_per_checkpoint 1000 --checkpoints_per_snapshot 0 --points_to_delete_from_beginning 2500 --start_deletes_after 5000 --do_concurrent true --start_point_norm 3.2;
+ dist/bin/compute_groundtruth --data_type float --dist_fn l2 --base_file data/index_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_float_10D_1K_norm1.0.bin --K 100 --gt_file data/gt100_random10D_1K-conc-2500-7500 --tags_file data/index_ins_del.after-concurrent-delete-del2500-7500.tags
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_ins_del.after-concurrent-delete-del2500-7500 --result_path data/res_ins_del --query_file data/rand_float_10D_1K_norm1.0.bin --gt_file data/gt100_random10D_1K-conc-2500-7500 -K 10 -L 20 40 60 80 100 -T 8 --dynamic true --tags 1
+ - name: build and search an incremental index (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/test_insert_deletes_consolidate --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/index_ins_del -R 64 -L 300 --alpha 1.2 -T 8 --points_to_skip 0 --max_points_to_insert 7500 --beginning_index_size 0 --points_per_checkpoint 1000 --checkpoints_per_snapshot 0 --points_to_delete_from_beginning 2500 --start_deletes_after 5000 --do_concurrent true --start_point_norm 200
+ dist/bin/compute_groundtruth --data_type int8 --dist_fn l2 --base_file data/index_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_int8_10D_1K_norm50.0.bin --K 100 --gt_file data/gt100_random10D_1K-conc-2500-7500 --tags_file data/index_ins_del.after-concurrent-delete-del2500-7500.tags
+ dist/bin/search_memory_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_ins_del.after-concurrent-delete-del2500-7500 --result_path data/res_ins_del --query_file data/rand_int8_10D_1K_norm50.0.bin --gt_file data/gt100_random10D_1K-conc-2500-7500 -K 10 -L 20 40 60 80 100 -T 8 --dynamic true --tags 1
+ - name: build and search an incremental index (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/test_insert_deletes_consolidate --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/index_ins_del -R 64 -L 300 --alpha 1.2 -T 8 --points_to_skip 0 --max_points_to_insert 7500 --beginning_index_size 0 --points_per_checkpoint 1000 --checkpoints_per_snapshot 0 --points_to_delete_from_beginning 2500 --start_deletes_after 5000 --do_concurrent true --start_point_norm 200
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn l2 --base_file data/index_ins_del.after-concurrent-delete-del2500-7500.data --query_file data/rand_uint8_10D_1K_norm50.0.bin --K 100 --gt_file data/gt100_random10D_10K-conc-2500-7500 --tags_file data/index_ins_del.after-concurrent-delete-del2500-7500.tags
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_ins_del.after-concurrent-delete-del2500-7500 --result_path data/res_ins_del --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/gt100_random10D_10K-conc-2500-7500 -K 10 -L 20 40 60 80 100 -T 8 --dynamic true --tags 1
+
+ - name: upload data and bin
+ uses: actions/upload-artifact@v4
+ with:
+ name: dynamic-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/in-mem-no-pq.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/in-mem-no-pq.yml
new file mode 100644
index 0000000..07fc4a2
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/in-mem-no-pq.yml
@@ -0,0 +1,81 @@
+name: In-Memory Without PQ
+on: [workflow_call]
+jobs:
+ acceptance-tests-mem-no-pq:
+ name: In-Mem, Without PQ
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-random
+
+ - name: build and search in-memory index with L2 metrics (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0 --query_file data/rand_float_10D_1K_norm1.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 -L 16 32
+ - name: build and search in-memory index with L2 metrics (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/index_l2_rand_int8_10D_10K_norm50.0
+ dist/bin/search_memory_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_int8_10D_10K_norm50.0 --query_file data/rand_int8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 16 32
+ - name: build and search in-memory index with L2 metrics (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50.0
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50.0 --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 16 32
+
+ - name: Searching with fast_l2 distance function (float)
+ if: runner.os != 'Windows' && (success() || failure())
+ run: |
+ dist/bin/search_memory_index --data_type float --dist_fn fast_l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0 --query_file data/rand_float_10D_1K_norm1.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 -L 16 32
+
+ - name: build and search in-memory index with MIPS metric (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type float --dist_fn mips --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_mips_rand_float_10D_10K_norm1.0
+ dist/bin/search_memory_index --data_type float --dist_fn mips --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0 --query_file data/rand_float_10D_1K_norm1.0.bin --recall_at 10 --result_path temp --gt_file data/mips_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 -L 16 32
+
+ - name: build and search in-memory index with cosine metric (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type float --dist_fn cosine --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_cosine_rand_float_10D_10K_norm1.0
+ dist/bin/search_memory_index --data_type float --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0 --query_file data/rand_float_10D_1K_norm1.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 -L 16 32
+ - name: build and search in-memory index with cosine metric (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type int8 --dist_fn cosine --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/index_cosine_rand_int8_10D_10K_norm50.0
+ dist/bin/search_memory_index --data_type int8 --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_int8_10D_10K_norm50.0 --query_file data/rand_int8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 16 32
+ - name: build and search in-memory index with cosine metric
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn cosine --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/index_cosine_rand_uint8_10D_10K_norm50.0
+ dist/bin/search_memory_index --data_type uint8 --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50.0 --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 16 32
+
+ - name: upload data and bin
+ uses: actions/upload-artifact@v4
+ with:
+ name: in-memory-no-pq-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/in-mem-pq.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/in-mem-pq.yml
new file mode 100644
index 0000000..be20f10
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/in-mem-pq.yml
@@ -0,0 +1,56 @@
+name: In-Memory With PQ
+on: [workflow_call]
+jobs:
+ acceptance-tests-mem-pq:
+ name: In-Mem, PQ
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-random
+
+ - name: build and search in-memory index with L2 metric with PQ based distance comparisons (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type float --dist_fn l2 --data_path data/rand_float_10D_10K_norm1.0.bin --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0_buildpq5 --build_PQ_bytes 5
+ dist/bin/search_memory_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_float_10D_10K_norm1.0_buildpq5 --query_file data/rand_float_10D_1K_norm1.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_float_10D_10K_norm1.0_10D_1K_norm1.0_gt100 -L 16 32
+
+ - name: build and search in-memory index with L2 metrics with PQ base distance comparisons (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_10D_10K_norm50.0.bin --index_path_prefix data/index_l2_rand_int8_10D_10K_norm50.0_buildpq5 --build_PQ_bytes 5
+ dist/bin/search_memory_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_int8_10D_10K_norm50.0_buildpq5 --query_file data/rand_int8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_int8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 16 32
+
+ - name: build and search in-memory index with L2 metrics with PQ base distance comparisons (uint8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --data_path data/rand_uint8_10D_10K_norm50.0.bin --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50.0_buildpq5 --build_PQ_bytes 5
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50.0_buildpq5 --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 16 32
+
+ - name: upload data and bin
+ uses: actions/upload-artifact@v4
+ with:
+ name: in-memory-pq-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/labels.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/labels.yml
new file mode 100644
index 0000000..93995f7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/labels.yml
@@ -0,0 +1,120 @@
+name: Labels
+on: [workflow_call]
+jobs:
+ acceptance-tests-labels:
+ name: Labels
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-random
+
+ - name: Generate Labels
+ run: |
+ echo "Generating synthetic labels and computing ground truth for filtered search with universal label"
+ dist/bin/generate_synthetic_labels --num_labels 50 --num_points 10000 --output_file data/rand_labels_50_10K.txt --distribution_type random
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn l2 --universal_label 0 --filter_label 10 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn mips --universal_label 0 --filter_label 10 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --gt_file data/mips_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn cosine --universal_label 0 --filter_label 10 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --gt_file data/cosine_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+
+ echo "Generating synthetic labels with a zipf distribution and computing ground truth for filtered search with universal label"
+ dist/bin/generate_synthetic_labels --num_labels 50 --num_points 10000 --output_file data/zipf_labels_50_10K.txt --distribution_type zipf
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn l2 --universal_label 0 --filter_label 5 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn mips --universal_label 0 --filter_label 5 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --gt_file data/mips_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn cosine --universal_label 0 --filter_label 5 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --gt_file data/cosine_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+
+ echo "Generating synthetic labels and computing ground truth for filtered search without a universal label"
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn l2 --filter_label 5 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel_nouniversal --K 100
+ dist/bin/generate_synthetic_labels --num_labels 10 --num_points 1000 --output_file data/query_labels_1K.txt --distribution_type one_per_point
+ dist/bin/compute_groundtruth_for_filters --data_type uint8 --dist_fn l2 --universal_label 0 --filter_label_file data/query_labels_1K.txt --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --gt_file data/combined_l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --K 100
+
+ - name: build and search in-memory index with labels using L2 and Cosine metrics (random distributed labels)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --FilteredLbuild 90 --universal_label 0 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50_wlabel
+ dist/bin/build_memory_index --data_type uint8 --dist_fn cosine --FilteredLbuild 90 --universal_label 0 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --index_path_prefix data/index_cosine_rand_uint8_10D_10K_norm50_wlabel
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --filter_label 10 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -L 16 32
+ dist/bin/search_memory_index --data_type uint8 --dist_fn cosine --filter_label 10 --fail_if_recall_below 70 --index_path_prefix data/index_cosine_rand_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -L 16 32
+
+ echo "Searching without filters"
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 32 64
+ dist/bin/search_memory_index --data_type uint8 --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/index_cosine_rand_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 32 64
+
+ - name: build and search disk index with labels using L2 and Cosine metrics (random distributed labels)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --universal_label 0 --FilteredLbuild 90 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50_wlabel -R 32 -L 5 -B 0.00003 -M 1
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --filter_label 10 --fail_if_recall_below 50 --index_path_prefix data/disk_index_l2_rand_uint8_10D_10K_norm50_wlabel --result_path temp --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: build and search in-memory index with labels using L2 and Cosine metrics (zipf distributed labels)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --FilteredLbuild 90 --universal_label 0 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel
+ dist/bin/build_memory_index --data_type uint8 --dist_fn cosine --FilteredLbuild 90 --universal_label 0 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/index_cosine_zipf_uint8_10D_10K_norm50_wlabel
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --filter_label 5 --fail_if_recall_below 70 --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -L 16 32
+ dist/bin/search_memory_index --data_type uint8 --dist_fn cosine --filter_label 5 --fail_if_recall_below 70 --index_path_prefix data/index_cosine_zipf_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -L 16 32
+
+ echo "Searching without filters"
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn l2 --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+ dist/bin/compute_groundtruth --data_type uint8 --dist_fn cosine --base_file data/rand_uint8_10D_10K_norm50.0.bin --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/cosine_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 --K 100
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 32 64
+ dist/bin/search_memory_index --data_type uint8 --dist_fn cosine --fail_if_recall_below 70 --index_path_prefix data/index_cosine_zipf_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/cosine_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100 -L 32 64
+
+ - name: build and search disk index with labels using L2 and Cosine metrics (zipf distributed labels)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --universal_label 0 --FilteredLbuild 90 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/disk_index_l2_zipf_uint8_10D_10K_norm50_wlabel -R 32 -L 5 -B 0.00003 -M 1
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --filter_label 5 --fail_if_recall_below 50 --index_path_prefix data/disk_index_l2_zipf_uint8_10D_10K_norm50_wlabel --result_path temp --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+
+ - name : build and search in-memory and disk index (without universal label, zipf distributed)
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --FilteredLbuild 90 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel_nouniversal
+ dist/bin/build_disk_index --data_type uint8 --dist_fn l2 --FilteredLbuild 90 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/disk_index_l2_zipf_uint8_10D_10K_norm50_wlabel_nouniversal -R 32 -L 5 -B 0.00003 -M 1
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --filter_label 5 --fail_if_recall_below 70 --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel_nouniversal --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel_nouniversal -L 16 32
+ dist/bin/search_disk_index --data_type uint8 --dist_fn l2 --filter_label 5 --index_path_prefix data/disk_index_l2_zipf_uint8_10D_10K_norm50_wlabel_nouniversal --result_path temp --query_file data/rand_uint8_10D_1K_norm50.0.bin --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel_nouniversal --recall_at 5 -L 5 12 -W 2 --num_nodes_to_cache 10 -T 16
+ - name: Generate combined GT for each query with a separate label and search
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --FilteredLbuild 90 --universal_label 0 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --query_filters_file data/query_labels_1K.txt --fail_if_recall_below 70 --index_path_prefix data/index_l2_zipf_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/combined_l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -L 16 32
+ - name: build and search in-memory index with pq_dist of 5 with 10 dimensions
+ if: success() || failure()
+ run: |
+ dist/bin/build_memory_index --data_type uint8 --dist_fn l2 --FilteredLbuild 90 --universal_label 0 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/rand_labels_50_10K.txt --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50_wlabel --build_PQ_bytes 5
+ dist/bin/search_memory_index --data_type uint8 --dist_fn l2 --filter_label 10 --fail_if_recall_below 70 --index_path_prefix data/index_l2_rand_uint8_10D_10K_norm50_wlabel --query_file data/rand_uint8_10D_1K_norm50.0.bin --recall_at 10 --result_path temp --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -L 16 32
+ - name: Build and search stitched vamana with random and zipf distributed labels
+ if: success() || failure()
+ run: |
+ dist/bin/build_stitched_index --num_threads 48 --data_type uint8 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/rand_labels_50_10K.txt -R 32 -L 100 --alpha 1.2 --stitched_R 64 --index_path_prefix data/stit_rand_32_100_64_new --universal_label 0
+ dist/bin/build_stitched_index --num_threads 48 --data_type uint8 --data_path data/rand_uint8_10D_10K_norm50.0.bin --label_file data/zipf_labels_50_10K.txt -R 32 -L 100 --alpha 1.2 --stitched_R 64 --index_path_prefix data/stit_zipf_32_100_64_new --universal_label 0
+ dist/bin/search_memory_index --num_threads 48 --data_type uint8 --dist_fn l2 --filter_label 10 --index_path_prefix data/stit_rand_32_100_64_new --query_file data/rand_uint8_10D_1K_norm50.0.bin --result_path data/rand_stit_96_10_90_new --gt_file data/l2_rand_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -K 10 -L 16 32 150
+ dist/bin/search_memory_index --num_threads 48 --data_type uint8 --dist_fn l2 --filter_label 5 --index_path_prefix data/stit_zipf_32_100_64_new --query_file data/rand_uint8_10D_1K_norm50.0.bin --result_path data/zipf_stit_96_10_90_new --gt_file data/l2_zipf_uint8_10D_10K_norm50.0_10D_1K_norm50.0_gt100_wlabel -K 10 -L 16 32 150
+
+ - name: upload data and bin
+ if: success() || failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: labels-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/multi-sector-disk-pq.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/multi-sector-disk-pq.yml
new file mode 100644
index 0000000..969467a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/multi-sector-disk-pq.yml
@@ -0,0 +1,60 @@
+name: Disk With PQ
+on: [workflow_call]
+jobs:
+ acceptance-tests-disk-pq:
+ name: Disk, PQ
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Generate Data
+ uses: ./.github/actions/generate-high-dim-random
+
+ - name: build and search disk index (1020D, one shot graph build, L2, no diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_1020D_5K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_1020D_5K_norm1.0_diskfull_oneshot -R 32 -L 500 -B 0.003 -M 1
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_1020D_5K_norm1.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_float_1020D_1K_norm1.0.bin --gt_file data/l2_rand_float_1020D_5K_norm1.0_1020D_1K_norm1.0_gt100 --recall_at 5 -L 250 -W 2 --num_nodes_to_cache 100 -T 16
+ #- name: build and search disk index (1024D, one shot graph build, L2, no diskPQ) (float)
+ # if: success() || failure()
+ # run: |
+ # dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_1024D_5K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_1024D_5K_norm1.0_diskfull_oneshot -R 32 -L 500 -B 0.003 -M 1
+ # dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_1024D_5K_norm1.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_float_1024D_1K_norm1.0.bin --gt_file data/l2_rand_float_1024D_5K_norm1.0_1024D_1K_norm1.0_gt100 --recall_at 5 -L 250 -W 2 --num_nodes_to_cache 100 -T 16
+ - name: build and search disk index (1536D, one shot graph build, L2, no diskPQ) (float)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type float --dist_fn l2 --data_path data/rand_float_1536D_5K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_float_1536D_5K_norm1.0_diskfull_oneshot -R 32 -L 500 -B 0.003 -M 1
+ dist/bin/search_disk_index --data_type float --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_float_1536D_5K_norm1.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_float_1536D_1K_norm1.0.bin --gt_file data/l2_rand_float_1536D_5K_norm1.0_1536D_1K_norm1.0_gt100 --recall_at 5 -L 250 -W 2 --num_nodes_to_cache 100 -T 16
+
+ - name: build and search disk index (4096D, one shot graph build, L2, no diskPQ) (int8)
+ if: success() || failure()
+ run: |
+ dist/bin/build_disk_index --data_type int8 --dist_fn l2 --data_path data/rand_int8_4096D_5K_norm1.0.bin --index_path_prefix data/disk_index_l2_rand_int8_4096D_5K_norm1.0_diskfull_oneshot -R 32 -L 500 -B 0.003 -M 1
+ dist/bin/search_disk_index --data_type int8 --dist_fn l2 --fail_if_recall_below 70 --index_path_prefix data/disk_index_l2_rand_int8_4096D_5K_norm1.0_diskfull_oneshot --result_path /tmp/res --query_file data/rand_int8_4096D_1K_norm1.0.bin --gt_file data/l2_rand_int8_4096D_5K_norm1.0_4096D_1K_norm1.0_gt100 --recall_at 5 -L 250 -W 2 --num_nodes_to_cache 100 -T 16
+
+ - name: upload data and bin
+ uses: actions/upload-artifact@v4
+ with:
+ name: multi-sector-disk-pq-${{matrix.os}}
+ path: |
+ ./dist/**
+ ./data/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/perf.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/perf.yml
new file mode 100644
index 0000000..d4eb9e2
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/perf.yml
@@ -0,0 +1,26 @@
+name: DiskANN Nightly Performance Metrics
+on:
+ schedule:
+ - cron: "41 14 * * *" # 14:41 UTC, 7:41 PDT, 8:41 PST, 08:11 IST
+jobs:
+ perf-test:
+ name: Run Perf Test from main
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Build Perf Container
+ run: |
+ docker build --build-arg GIT_COMMIT_ISH="$GITHUB_SHA" -t perf -f scripts/perf/Dockerfile scripts
+ - name: Performance Tests
+ run: |
+ mkdir metrics
+ docker run -v ./metrics:/app/logs perf &> ./metrics/combined_stdouterr.log
+ - name: Upload Metrics Logs
+ uses: actions/upload-artifact@v4
+ with:
+ name: metrics-${{matrix.os}}
+ path: |
+ ./metrics/**
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/pr-test.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/pr-test.yml
new file mode 100644
index 0000000..f84953b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/pr-test.yml
@@ -0,0 +1,35 @@
+name: DiskANN Pull Request Build and Test
+on: [pull_request]
+jobs:
+ common:
+ strategy:
+ fail-fast: true
+ name: DiskANN Common Build Checks
+ uses: ./.github/workflows/common.yml
+ unit-tests:
+ name: Unit tests
+ uses: ./.github/workflows/unit-tests.yml
+ in-mem-pq:
+ name: In-Memory with PQ
+ uses: ./.github/workflows/in-mem-pq.yml
+ in-mem-no-pq:
+ name: In-Memory without PQ
+ uses: ./.github/workflows/in-mem-no-pq.yml
+ disk-pq:
+ name: Disk with PQ
+ uses: ./.github/workflows/disk-pq.yml
+ multi-sector-disk-pq:
+ name: Multi-sector Disk with PQ
+ uses: ./.github/workflows/multi-sector-disk-pq.yml
+ labels:
+ name: Labels
+ uses: ./.github/workflows/labels.yml
+ dynamic:
+ name: Dynamic
+ uses: ./.github/workflows/dynamic.yml
+ dynamic-labels:
+ name: Dynamic Labels
+ uses: ./.github/workflows/dynamic-labels.yml
+ python:
+ name: Python
+ uses: ./.github/workflows/build-python.yml
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/push-test.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/push-test.yml
new file mode 100644
index 0000000..d1261d5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/push-test.yml
@@ -0,0 +1,50 @@
+name: DiskANN Push Build
+on: [push]
+jobs:
+ common:
+ strategy:
+ fail-fast: true
+ name: DiskANN Common Build Checks
+ uses: ./.github/workflows/common.yml
+ build-documentation:
+ permissions:
+ contents: write
+ strategy:
+ fail-fast: true
+ name: DiskANN Build Documentation
+ uses: ./.github/workflows/build-python-pdoc.yml
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ ubuntu-latest, windows-2019, windows-latest ]
+ name: Build for ${{matrix.os}}
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: Build diskannpy dependency tree
+ run: |
+ pip install diskannpy pipdeptree
+ echo "dependencies" > dependencies_${{ matrix.os }}.txt
+ pipdeptree >> dependencies_${{ matrix.os }}.txt
+ - name: Archive diskannpy dependencies artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: dependencies_${{ matrix.os }}
+ path: |
+ dependencies_${{ matrix.os }}.txt
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/python-release.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/python-release.yml
new file mode 100644
index 0000000..a15d4d1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/python-release.yml
@@ -0,0 +1,43 @@
+name: Build and Release Python Wheels
+on:
+ release:
+ types: [published]
+jobs:
+ python-release-wheels:
+ name: Python
+ uses: ./.github/workflows/build-python.yml
+ build-documentation:
+ strategy:
+ fail-fast: true
+ name: DiskANN Build Documentation
+ uses: ./.github/workflows/build-python-pdoc.yml
+ release:
+ permissions:
+ contents: write
+ runs-on: ubuntu-latest
+ needs: python-release-wheels
+ steps:
+ - uses: actions/download-artifact@v3
+ with:
+ name: wheels
+ path: dist/
+ - name: Generate SHA256 files for each wheel
+ run: |
+ sha256sum dist/*.whl > checksums.txt
+ cat checksums.txt
+ - uses: actions/setup-python@v3
+ - name: Install twine
+ run: python -m pip install twine
+ - name: Publish with twine
+ env:
+ TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
+ TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
+ run: |
+ twine upload dist/*.whl
+ - name: Update release with SHA256 and Artifacts
+ uses: softprops/action-gh-release@v1
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ files: |
+ dist/*.whl
+ checksums.txt
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/unit-tests.yml b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/unit-tests.yml
new file mode 100644
index 0000000..6ae6877
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.github/workflows/unit-tests.yml
@@ -0,0 +1,32 @@
+name: Unit Tests
+on: [workflow_call]
+jobs:
+ acceptance-tests-labels:
+ name: Unit Tests
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-2019, windows-latest]
+ runs-on: ${{matrix.os}}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout repository
+ if: ${{ runner.os == 'Linux' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ - name: Checkout repository
+ if: ${{ runner.os == 'Windows' }}
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+ submodules: true
+ - name: DiskANN Build CLI Applications
+ uses: ./.github/actions/build
+
+ - name: Run Unit Tests
+ run: |
+ cd build
+ ctest -C Release
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.gitignore b/packages/leann-backend-diskann/third_party/DiskANN/.gitignore
new file mode 100644
index 0000000..c6a88e7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.gitignore
@@ -0,0 +1,384 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+/vcproj/nsg/x64/Debug/nsg.Build.CppClean.log
+/vcproj/test_recall/x64/Debug/test_recall.Build.CppClean.log
+/vcproj/test_recall/test_recall.vcxproj.user
+/.vs
+/out/build/x64-Debug
+cscope*
+
+build/
+build_linux/
+!.github/actions/build
+
+# jetbrains specific stuff
+.idea/
+cmake-build-debug/
+
+#python extension module ignores
+python/diskannpy.egg-info/
+python/dist/
+
+**/*.egg-info
+wheelhouse/*
+dist/*
+venv*/**
+*.swp
+
+gperftools
+
+# Rust
+rust/target
+
+python/src/*.so
+
+compile_commands.json
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/.gitmodules b/packages/leann-backend-diskann/third_party/DiskANN/.gitmodules
new file mode 100644
index 0000000..125572b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "gperftools"]
+ path = gperftools
+ url = https://github.com/gperftools/gperftools.git
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/CMakeLists.txt
new file mode 100644
index 0000000..4025861
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/CMakeLists.txt
@@ -0,0 +1,563 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+# Parameters:
+#
+# BOOST_ROOT:
+# Specify root of the Boost library if Boost cannot be auto-detected. On Windows, a fallback to a
+# downloaded nuget version will be used if Boost cannot be found.
+#
+# DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS:
+# This is a work-in-progress feature, not completed yet. The core DiskANN library will be split into
+# build-related and search-related functionality. In build-related functionality, when using tcmalloc,
+# it's possible to release memory that's free but reserved by tcmalloc. Setting this to true enables
+# such behavior.
+# Contact for this feature: gopalrs.
+
+
+# Some variables like MSVC are defined only after project(), so put that first.
+cmake_minimum_required(VERSION 3.20)
+project(diskann)
+
+#Set option to use tcmalloc
+option(USE_TCMALLOC "Use tcmalloc from gperftools" ON)
+
+# set tcmalloc to false when on macos
+if(APPLE)
+ set(USE_TCMALLOC OFF)
+endif()
+
+option(PYBIND "Build with Python bindings" ON)
+
+if(PYBIND)
+ # Find Python
+ find_package(Python 3.6 COMPONENTS Interpreter Development REQUIRED)
+ execute_process(
+ COMMAND "${Python_EXECUTABLE}" -c "import pybind11; print(pybind11.get_cmake_dir())"
+ OUTPUT_VARIABLE pybind11_DIR
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+ find_package(pybind11 CONFIG REQUIRED)
+
+ message(STATUS "Python include dirs: ${Python_INCLUDE_DIRS}")
+ message(STATUS "Pybind11 include dirs: ${pybind11_INCLUDE_DIRS}")
+
+ # Add pybind11 include directories
+ include_directories(SYSTEM ${pybind11_INCLUDE_DIRS} ${Python_INCLUDE_DIRS})
+
+ # Add compilation definitions
+ add_definitions(-DPYBIND11_EMBEDDED)
+
+ # Set visibility flags
+ if(NOT MSVC)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden")
+ endif()
+endif()
+
+set(CMAKE_STANDARD 17)
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+# if(NOT MSVC)
+# set(CMAKE_CXX_COMPILER g++)
+# endif()
+
+set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}")
+
+# Install nuget packages for dependencies.
+if (MSVC)
+ find_program(NUGET_EXE NAMES nuget)
+
+ if (NOT NUGET_EXE)
+ message(FATAL_ERROR "Cannot find nuget command line tool.\nPlease install it from e.g. https://www.nuget.org/downloads")
+ endif()
+
+ set(DISKANN_MSVC_PACKAGES_CONFIG ${CMAKE_BINARY_DIR}/packages.config)
+ set(DISKANN_MSVC_PACKAGES ${CMAKE_BINARY_DIR}/packages)
+
+ message(STATUS "Invoking nuget to download Boost, OpenMP and MKL dependencies...")
+ configure_file(${PROJECT_SOURCE_DIR}/windows/packages.config.in ${DISKANN_MSVC_PACKAGES_CONFIG})
+ exec_program(${NUGET_EXE} ARGS install \"${DISKANN_MSVC_PACKAGES_CONFIG}\" -ExcludeVersion -OutputDirectory \"${DISKANN_MSVC_PACKAGES}\")
+ if (RESTAPI)
+ set(DISKANN_MSVC_RESTAPI_PACKAGES_CONFIG ${CMAKE_BINARY_DIR}/restapi/packages.config)
+ configure_file(${PROJECT_SOURCE_DIR}/windows/packages_restapi.config.in ${DISKANN_MSVC_RESTAPI_PACKAGES_CONFIG})
+ exec_program(${NUGET_EXE} ARGS install \"${DISKANN_MSVC_RESTAPI_PACKAGES_CONFIG}\" -ExcludeVersion -OutputDirectory \"${DISKANN_MSVC_PACKAGES}\")
+ endif()
+ message(STATUS "Finished setting up nuget dependencies")
+endif()
+
+include_directories(${PROJECT_SOURCE_DIR}/include)
+
+include(FetchContent)
+
+if(USE_TCMALLOC)
+ FetchContent_Declare(
+ tcmalloc
+ GIT_REPOSITORY https://github.com/google/tcmalloc.git
+ GIT_TAG origin/master # or specify a particular version or commit
+ )
+
+ FetchContent_MakeAvailable(tcmalloc)
+endif()
+
+if(NOT PYBIND)
+ set(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS ON)
+endif()
+# It's necessary to include tcmalloc headers only if calling into MallocExtension interface.
+# For using tcmalloc in DiskANN tools, it's enough to just link with tcmalloc.
+if (DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS)
+ include_directories(${tcmalloc_SOURCE_DIR}/src)
+ if (MSVC)
+ include_directories(${tcmalloc_SOURCE_DIR}/src/windows)
+ endif()
+endif()
+
+#OpenMP
+if (MSVC)
+ # Do not use find_package here since it would use VisualStudio's built-in OpenMP, but MKL libraries
+ # refer to Intel's OpenMP.
+ #
+ # No extra settings are needed for compilation: it only needs /openmp flag which is set further below,
+ # in the common MSVC compiler options block.
+ include_directories(BEFORE "${DISKANN_MSVC_PACKAGES}/intelopenmp.devel.win/lib/native/include")
+ link_libraries("${DISKANN_MSVC_PACKAGES}/intelopenmp.devel.win/lib/native/win-x64/libiomp5md.lib")
+
+ set(OPENMP_WINDOWS_RUNTIME_FILES
+ "${DISKANN_MSVC_PACKAGES}/intelopenmp.redist.win/runtimes/win-x64/native/libiomp5md.dll"
+ "${DISKANN_MSVC_PACKAGES}/intelopenmp.redist.win/runtimes/win-x64/native/libiomp5md.pdb")
+elseif(APPLE)
+ # Check if we're building Python bindings
+ if(PYBIND)
+ # First look for PyTorch's OpenMP to avoid conflicts
+ execute_process(
+ COMMAND ${Python_EXECUTABLE} -c "import os; import torch; print(os.path.join(os.path.dirname(torch.__file__), 'lib', 'libomp.dylib'))"
+ RESULT_VARIABLE TORCH_PATH_RESULT
+ OUTPUT_VARIABLE TORCH_LIBOMP_PATH
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ ERROR_QUIET
+ )
+
+ execute_process(
+ COMMAND brew --prefix libomp
+ OUTPUT_VARIABLE LIBOMP_ROOT
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+
+ if(EXISTS "${TORCH_LIBOMP_PATH}")
+ message(STATUS "Found PyTorch's libomp: ${TORCH_LIBOMP_PATH}")
+ set(OpenMP_CXX_FLAGS "-Xclang -fopenmp")
+ set(OpenMP_C_FLAGS "-Xclang -fopenmp")
+ set(OpenMP_CXX_LIBRARIES "${TORCH_LIBOMP_PATH}")
+ set(OpenMP_C_LIBRARIES "${TORCH_LIBOMP_PATH}")
+ set(OpenMP_FOUND TRUE)
+
+ include_directories(${LIBOMP_ROOT}/include)
+
+ # Set compiler flags and link libraries
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+ link_libraries("${TORCH_LIBOMP_PATH}")
+ else()
+ message(STATUS "No PyTorch's libomp found, falling back to normal OpenMP detection")
+ # Fallback to normal OpenMP detection
+ execute_process(
+ COMMAND brew --prefix libomp
+ OUTPUT_VARIABLE LIBOMP_ROOT
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+
+ set(OpenMP_ROOT "${LIBOMP_ROOT}")
+ find_package(OpenMP)
+
+ if (OPENMP_FOUND)
+ set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
+ set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+ link_libraries(OpenMP::OpenMP_CXX)
+ else()
+ message(FATAL_ERROR "No OpenMP support")
+ endif()
+ endif()
+ else()
+ # Regular OpenMP setup for non-Python builds
+ execute_process(
+ COMMAND brew --prefix libomp
+ OUTPUT_VARIABLE LIBOMP_ROOT
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+ set(OpenMP_ROOT "${LIBOMP_ROOT}")
+ find_package(OpenMP)
+
+ if (OPENMP_FOUND)
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+ link_libraries(OpenMP::OpenMP_CXX)
+ else()
+ message(FATAL_ERROR "No OpenMP support")
+ endif()
+ endif()
+else()
+ find_package(OpenMP)
+
+ if (OPENMP_FOUND)
+ set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
+ set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
+ else()
+ message(FATAL_ERROR "No OpenMP support")
+ endif()
+endif()
+
+# DiskANN core uses header-only libraries. Only DiskANN tools need program_options which has a linker library,
+# but its size is small. Reduce number of dependent DLLs by linking statically.
+if (MSVC)
+ set(Boost_USE_STATIC_LIBS ON)
+endif()
+
+if(NOT MSVC)
+ find_package(Boost COMPONENTS program_options)
+endif()
+
+# For Windows, fall back to nuget version if find_package didn't find it.
+if (MSVC AND NOT Boost_FOUND)
+ set(DISKANN_BOOST_INCLUDE "${DISKANN_MSVC_PACKAGES}/boost/lib/native/include")
+ # Multi-threaded static library.
+ set(PROGRAM_OPTIONS_LIB_PATTERN "${DISKANN_MSVC_PACKAGES}/boost_program_options-vc${MSVC_TOOLSET_VERSION}/lib/native/libboost_program_options-vc${MSVC_TOOLSET_VERSION}-mt-x64-*.lib")
+ file(GLOB DISKANN_BOOST_PROGRAM_OPTIONS_LIB ${PROGRAM_OPTIONS_LIB_PATTERN})
+
+ set(PROGRAM_OPTIONS_DLIB_PATTERN "${DISKANN_MSVC_PACKAGES}/boost_program_options-vc${MSVC_TOOLSET_VERSION}/lib/native/libboost_program_options-vc${MSVC_TOOLSET_VERSION}-mt-gd-x64-*.lib")
+ file(GLOB DISKANN_BOOST_PROGRAM_OPTIONS_DLIB ${PROGRAM_OPTIONS_DLIB_PATTERN})
+
+ if (EXISTS ${DISKANN_BOOST_INCLUDE} AND EXISTS ${DISKANN_BOOST_PROGRAM_OPTIONS_LIB} AND EXISTS ${DISKANN_BOOST_PROGRAM_OPTIONS_DLIB})
+ set(Boost_FOUND ON)
+ set(Boost_INCLUDE_DIR ${DISKANN_BOOST_INCLUDE})
+ add_library(Boost::program_options STATIC IMPORTED)
+ set_target_properties(Boost::program_options PROPERTIES IMPORTED_LOCATION_RELEASE "${DISKANN_BOOST_PROGRAM_OPTIONS_LIB}")
+ set_target_properties(Boost::program_options PROPERTIES IMPORTED_LOCATION_DEBUG "${DISKANN_BOOST_PROGRAM_OPTIONS_DLIB}")
+ message(STATUS "Falling back to using Boost from the nuget package")
+ else()
+ message(WARNING "Couldn't find Boost. Was looking for ${DISKANN_BOOST_INCLUDE} and ${PROGRAM_OPTIONS_LIB_PATTERN}")
+ endif()
+endif()
+
+if (NOT Boost_FOUND)
+ message(FATAL_ERROR "Couldn't find Boost dependency")
+endif()
+
+include_directories(${Boost_INCLUDE_DIR})
+
+#MKL Config
+if (MSVC)
+ # Only the DiskANN DLL and one of the tools need MKL libraries. Additionally, only a small part of MKL is used.
+ # Given that and given that MKL DLLs are huge, use static linking to end up with no MKL DLL dependencies and with
+ # significantly smaller disk footprint.
+ #
+ # The compile options are not modified as there's already an unconditional -DMKL_ILP64 define below
+ # for all architectures, which is all that's needed.
+ set(DISKANN_MKL_INCLUDE_DIRECTORIES "${DISKANN_MSVC_PACKAGES}/intelmkl.static.win-x64/lib/native/include")
+ set(DISKANN_MKL_LIB_PATH "${DISKANN_MSVC_PACKAGES}/intelmkl.static.win-x64/lib/native/win-x64")
+
+ set(DISKANN_MKL_LINK_LIBRARIES
+ "${DISKANN_MKL_LIB_PATH}/mkl_intel_ilp64.lib"
+ "${DISKANN_MKL_LIB_PATH}/mkl_core.lib"
+ "${DISKANN_MKL_LIB_PATH}/mkl_intel_thread.lib")
+elseif(APPLE)
+ # no mkl on non-intel devices
+ find_library(ACCELERATE_LIBRARY Accelerate)
+ message(STATUS "Found Accelerate (${ACCELERATE_LIBRARY})")
+ set(DISKANN_ACCEL_LINK_OPTIONS ${ACCELERATE_LIBRARY})
+ add_compile_definitions(ACCELERATE_NEW_LAPACK)
+else()
+ # expected path for manual intel mkl installs
+ set(POSSIBLE_OMP_PATHS "/opt/intel/oneapi/compiler/2025.0/lib/libiomp5.so;/opt/intel/oneapi/compiler/latest/linux/compiler/lib/intel64_lin/libiomp5.so;/usr/lib/x86_64-linux-gnu/libiomp5.so;/opt/intel/lib/intel64_lin/libiomp5.so")
+ foreach(POSSIBLE_OMP_PATH ${POSSIBLE_OMP_PATHS})
+ if (EXISTS ${POSSIBLE_OMP_PATH})
+ get_filename_component(OMP_PATH ${POSSIBLE_OMP_PATH} DIRECTORY)
+ endif()
+ endforeach()
+
+ if(NOT OMP_PATH)
+ message(FATAL_ERROR "Could not find Intel OMP in standard locations; use -DOMP_PATH to specify the install location for your environment")
+ endif()
+ link_directories(${OMP_PATH})
+
+ set(POSSIBLE_MKL_LIB_PATHS "/opt/intel/oneapi/mkl/latest/lib/intel64/libmkl_core.so;/usr/lib/x86_64-linux-gnu/libmkl_core.so;/opt/intel/mkl/lib/intel64/libmkl_core.so")
+ foreach(POSSIBLE_MKL_LIB_PATH ${POSSIBLE_MKL_LIB_PATHS})
+ if (EXISTS ${POSSIBLE_MKL_LIB_PATH})
+ get_filename_component(MKL_PATH ${POSSIBLE_MKL_LIB_PATH} DIRECTORY)
+ endif()
+ endforeach()
+
+ set(POSSIBLE_MKL_INCLUDE_PATHS "/opt/intel/oneapi/mkl/latest/include;/usr/include/mkl;/opt/intel/mkl/include/;")
+ foreach(POSSIBLE_MKL_INCLUDE_PATH ${POSSIBLE_MKL_INCLUDE_PATHS})
+ if (EXISTS ${POSSIBLE_MKL_INCLUDE_PATH})
+ set(MKL_INCLUDE_PATH ${POSSIBLE_MKL_INCLUDE_PATH})
+ endif()
+ endforeach()
+ if(NOT MKL_PATH)
+ message(FATAL_ERROR "Could not find Intel MKL in standard locations; use -DMKL_PATH to specify the install location for your environment")
+ elseif(NOT MKL_INCLUDE_PATH)
+ message(FATAL_ERROR "Could not find Intel MKL in standard locations; use -DMKL_INCLUDE_PATH to specify the install location for headers for your environment")
+ endif()
+ if (EXISTS ${MKL_PATH}/libmkl_def.so.2)
+ set(MKL_DEF_SO ${MKL_PATH}/libmkl_def.so.2)
+ elseif(EXISTS ${MKL_PATH}/libmkl_def.so)
+ set(MKL_DEF_SO ${MKL_PATH}/libmkl_def.so)
+ else()
+ message(FATAL_ERROR "Despite finding MKL, libmkl_def.so was not found in expected locations.")
+ endif()
+ link_directories(${MKL_PATH})
+ include_directories(${MKL_INCLUDE_PATH})
+
+ # compile flags and link libraries
+ # if gcc/g++
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ add_compile_options(-m64 -Wl,--no-as-needed)
+ endif()
+ if (NOT PYBIND)
+ link_libraries(mkl_intel_ilp64 mkl_intel_thread mkl_core iomp5 pthread m dl)
+ else()
+ # static linking for python so as to minimize customer dependency issues
+ if (CMAKE_BUILD_TYPE STREQUAL "Debug")
+ # In debug mode, use dynamic linking to ensure all symbols are available
+ link_libraries(mkl_intel_ilp64 mkl_intel_thread mkl_core ${MKL_DEF_SO} iomp5 pthread m dl)
+ else()
+ # In release mode, use static linking to minimize dependencies
+ link_libraries(
+ ${MKL_PATH}/libmkl_intel_ilp64.a
+ ${MKL_PATH}/libmkl_intel_thread.a
+ ${MKL_PATH}/libmkl_core.a
+ ${MKL_DEF_SO}
+ iomp5
+ pthread
+ m
+ dl
+ )
+ endif()
+ endif()
+
+ add_definitions(-DMKL_ILP64)
+endif()
+
+
+# Section for tcmalloc. The DiskANN tools are always linked to tcmalloc. For Windows, they also need to
+# force-include the _tcmalloc symbol for enabling tcmalloc.
+#
+# The DLL itself needs to be linked to tcmalloc only if DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS
+# is enabled.
+if(USE_TCMALLOC)
+ if (MSVC)
+ if (NOT EXISTS "${PROJECT_SOURCE_DIR}/gperftools/gperftools.sln")
+ message(FATAL_ERROR "The gperftools submodule was not found. "
+ "Please check-out git submodules by doing 'git submodule init' followed by 'git submodule update'")
+ endif()
+
+ set(TCMALLOC_LINK_LIBRARY "${PROJECT_SOURCE_DIR}/gperftools/x64/Release-Patch/libtcmalloc_minimal.lib")
+ set(TCMALLOC_WINDOWS_RUNTIME_FILES
+ "${PROJECT_SOURCE_DIR}/gperftools/x64/Release-Patch/libtcmalloc_minimal.dll"
+ "${PROJECT_SOURCE_DIR}/gperftools/x64/Release-Patch/libtcmalloc_minimal.pdb")
+
+ # Tell CMake how to build the tcmalloc linker library from the submodule.
+ add_custom_target(build_libtcmalloc_minimal DEPENDS ${TCMALLOC_LINK_LIBRARY})
+ add_custom_command(OUTPUT ${TCMALLOC_LINK_LIBRARY}
+ COMMAND ${CMAKE_VS_MSBUILD_COMMAND} gperftools.sln /m /nologo
+ /t:libtcmalloc_minimal /p:Configuration="Release-Patch"
+ /property:Platform="x64"
+ /p:PlatformToolset=v${MSVC_TOOLSET_VERSION}
+ /p:WindowsTargetPlatformVersion=${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}
+ WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/gperftools)
+
+ add_library(libtcmalloc_minimal_for_exe STATIC IMPORTED)
+ add_library(libtcmalloc_minimal_for_dll STATIC IMPORTED)
+
+ set_target_properties(libtcmalloc_minimal_for_dll PROPERTIES
+ IMPORTED_LOCATION "${TCMALLOC_LINK_LIBRARY}")
+
+ set_target_properties(libtcmalloc_minimal_for_exe PROPERTIES
+ IMPORTED_LOCATION "${TCMALLOC_LINK_LIBRARY}"
+ INTERFACE_LINK_OPTIONS /INCLUDE:_tcmalloc)
+
+ # Ensure libtcmalloc_minimal is built before it's being used.
+ add_dependencies(libtcmalloc_minimal_for_dll build_libtcmalloc_minimal)
+ add_dependencies(libtcmalloc_minimal_for_exe build_libtcmalloc_minimal)
+
+ set(DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS libtcmalloc_minimal_for_exe)
+ elseif(APPLE) # ! Inherited from #474, not been adjusted for TCMalloc Removal
+ execute_process(
+ COMMAND brew --prefix gperftools
+ OUTPUT_VARIABLE GPERFTOOLS_PREFIX
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+ set(DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS "-L${GPERFTOOLS_PREFIX}/lib -ltcmalloc")
+ elseif(NOT PYBIND)
+ set(DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS "-ltcmalloc")
+ endif()
+
+ if (DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS)
+ add_definitions(-DRELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS)
+
+ if (MSVC)
+ set(DISKANN_DLL_TCMALLOC_LINK_OPTIONS libtcmalloc_minimal_for_dll)
+ endif()
+ endif()
+endif()
+
+if (NOT MSVC AND NOT APPLE)
+ set(DISKANN_ASYNC_LIB aio)
+endif()
+
+#Main compiler/linker settings
+if(MSVC)
+ #language options
+ add_compile_options(/permissive- /openmp:experimental /Zc:twoPhase- /Zc:inline /WX- /std:c++17 /Gd /W3 /MP /Zi /FC /nologo)
+ #code generation options
+ add_compile_options(/arch:AVX2 /fp:fast /fp:except- /EHsc /GS- /Gy)
+ #optimization options
+ add_compile_options(/Ot /Oy /Oi)
+ #path options
+ add_definitions(-DUSE_AVX2 -DUSE_ACCELERATED_PQ -D_WINDOWS -DNOMINMAX -DUNICODE)
+ # Linker options. Exclude VCOMP/VCOMPD.LIB which contain VisualStudio's version of OpenMP.
+ # MKL was linked against Intel's OpenMP and depends on the corresponding DLL.
+ add_link_options(/NODEFAULTLIB:VCOMP.LIB /NODEFAULTLIB:VCOMPD.LIB /DEBUG:FULL /OPT:REF /OPT:ICF)
+
+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/x64/Debug)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/x64/Debug)
+ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/x64/Debug)
+
+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/x64/Release)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/x64/Release)
+ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/x64/Release)
+elseif(APPLE)
+ set(ENV{TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD} 500000000000)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftree-vectorize -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free -Xclang -fopenmp -fopenmp-simd -funroll-loops -Wfatal-errors -Wno-inconsistent-missing-override -Wno-return-type")
+ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -DDEBUG")
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Ofast -DNDEBUG -ftree-vectorize")
+ if (NOT PYBIND)
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DNDEBUG -Ofast")
+ if (NOT PORTABLE)
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -mtune=native")
+ endif()
+ else()
+ # -Ofast is not supported in a python extension module
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DNDEBUG -fPIC")
+ endif()
+else()
+ set(ENV{TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD} 500000000000)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx2 -mfma -msse2 -ftree-vectorize -fopenmp -fopenmp-simd -funroll-loops -Wfatal-errors -DUSE_AVX2 -fPIC")
+ if(USE_TCMALLOC)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free")
+ endif()
+ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -DDEBUG")
+ if (NOT PYBIND)
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DNDEBUG -Ofast")
+ if (NOT PORTABLE)
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -march=native -mtune=native")
+ endif()
+ else()
+ # -Ofast is not supported in a python extension module
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DNDEBUG")
+ endif()
+endif()
+
+add_subdirectory(src)
+if (NOT PYBIND)
+ add_subdirectory(apps)
+ add_subdirectory(apps/utils)
+endif()
+
+if (UNIT_TEST)
+ enable_testing()
+ add_subdirectory(tests)
+endif()
+
+if (MSVC)
+ message(STATUS "The ${PROJECT_NAME}.sln has been created, opened it from VisualStudio to build Release or Debug configurations.\n"
+ "Alternatively, use MSBuild to build:\n\n"
+ "msbuild.exe ${PROJECT_NAME}.sln /m /nologo /t:Build /p:Configuration=\"Release\" /property:Platform=\"x64\"\n")
+endif()
+
+if (RESTAPI)
+ if (MSVC)
+ set(DISKANN_CPPRESTSDK "${DISKANN_MSVC_PACKAGES}/cpprestsdk.v142/build/native")
+ # expected path for apt packaged intel mkl installs
+ link_libraries("${DISKANN_CPPRESTSDK}/x64/lib/cpprest142_2_10.lib")
+ include_directories("${DISKANN_CPPRESTSDK}/include")
+ endif()
+ add_subdirectory(apps/restapi)
+endif()
+
+include(clang-format.cmake)
+
+if(PYBIND)
+ add_subdirectory(python)
+
+ install(TARGETS _diskannpy
+ DESTINATION leann_backend_diskann
+ COMPONENT python_modules
+ )
+
+endif()
+###############################################################################
+# PROTOBUF SECTION - Corrected to use CONFIG mode explicitly
+###############################################################################
+set(Protobuf_USE_STATIC_LIBS OFF)
+
+find_package(ZLIB REQUIRED)
+
+find_package(Protobuf REQUIRED)
+
+message(STATUS "Protobuf found: ${Protobuf_VERSION}")
+message(STATUS "Protobuf include dirs: ${Protobuf_INCLUDE_DIRS}")
+message(STATUS "Protobuf libraries: ${Protobuf_LIBRARIES}")
+message(STATUS "Protobuf protoc executable: ${Protobuf_PROTOC_EXECUTABLE}")
+
+include_directories(${Protobuf_INCLUDE_DIRS})
+
+set(PROTO_FILE "${CMAKE_CURRENT_SOURCE_DIR}/../embedding.proto")
+protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS ${PROTO_FILE})
+set(generated_proto_sources ${PROTO_SRCS})
+
+
+add_library(proto_embeddings STATIC ${generated_proto_sources})
+target_link_libraries(proto_embeddings PUBLIC protobuf::libprotobuf)
+target_include_directories(proto_embeddings PUBLIC
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${Protobuf_INCLUDE_DIRS}
+)
+
+target_link_libraries(diskann PRIVATE proto_embeddings protobuf::libprotobuf)
+target_include_directories(diskann PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${Protobuf_INCLUDE_DIRS}
+)
+
+target_link_libraries(diskann_s PRIVATE proto_embeddings protobuf::libprotobuf)
+target_include_directories(diskann_s PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${Protobuf_INCLUDE_DIRS}
+)
+
+
+###############################################################################
+# ZEROMQ SECTION - REQUIRED
+###############################################################################
+
+find_package(ZeroMQ QUIET)
+if(NOT ZeroMQ_FOUND)
+ find_path(ZeroMQ_INCLUDE_DIR zmq.h)
+ find_library(ZeroMQ_LIBRARY zmq)
+ if(ZeroMQ_INCLUDE_DIR AND ZeroMQ_LIBRARY)
+ set(ZeroMQ_FOUND TRUE)
+ endif()
+endif()
+
+if(ZeroMQ_FOUND)
+ message(STATUS "Found ZeroMQ: ${ZeroMQ_LIBRARY}")
+ include_directories(${ZeroMQ_INCLUDE_DIR})
+ target_link_libraries(diskann PRIVATE ${ZeroMQ_LIBRARY})
+ target_link_libraries(diskann_s PRIVATE ${ZeroMQ_LIBRARY})
+ add_definitions(-DUSE_ZEROMQ)
+else()
+ message(FATAL_ERROR "ZeroMQ is required but not found. Please install ZeroMQ and try again.")
+endif()
+
+target_link_libraries(diskann ${PYBIND11_LIBRARIES})
+target_link_libraries(diskann_s ${PYBIND11_LIBRARIES})
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/CMakeSettings.json b/packages/leann-backend-diskann/third_party/DiskANN/CMakeSettings.json
new file mode 100644
index 0000000..af5d7b5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/CMakeSettings.json
@@ -0,0 +1,28 @@
+{
+ "configurations": [
+ {
+ "name": "x64-Release",
+ "generator": "Ninja",
+ "configurationType": "Release",
+ "inheritEnvironments": [ "msvc_x64" ],
+ "buildRoot": "${projectDir}\\out\\build\\${name}",
+ "installRoot": "${projectDir}\\out\\install\\${name}",
+ "cmakeCommandArgs": "",
+ "buildCommandArgs": "",
+ "ctestCommandArgs": ""
+ },
+ {
+ "name": "WSL-GCC-Release",
+ "generator": "Ninja",
+ "configurationType": "RelWithDebInfo",
+ "buildRoot": "${projectDir}\\out\\build\\${name}",
+ "installRoot": "${projectDir}\\out\\install\\${name}",
+ "cmakeExecutable": "cmake",
+ "cmakeCommandArgs": "",
+ "buildCommandArgs": "",
+ "ctestCommandArgs": "",
+ "inheritEnvironments": [ "linux_x64" ],
+ "wslPath": "${defaultWSLPath}"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/CODE_OF_CONDUCT.md b/packages/leann-backend-diskann/third_party/DiskANN/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..f9ba8cf
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/CODE_OF_CONDUCT.md
@@ -0,0 +1,9 @@
+# Microsoft Open Source Code of Conduct
+
+This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
+
+Resources:
+
+- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
+- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
+- Contact [[email protected]](mailto:[email protected]) with questions or concerns
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/CONTRIBUTING.md b/packages/leann-backend-diskann/third_party/DiskANN/CONTRIBUTING.md
new file mode 100644
index 0000000..dcbf795
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/CONTRIBUTING.md
@@ -0,0 +1,9 @@
+# Contributing
+
+This project welcomes contributions and suggestions. Most contributions require you to agree to a
+Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
+the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
+
+When you submit a pull request, a CLA bot will automatically determine whether you need to provide
+a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
+provided by the bot. You will only need to do this once across all repos using our CLA.
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/Dockerfile b/packages/leann-backend-diskann/third_party/DiskANN/Dockerfile
new file mode 100644
index 0000000..ea1979f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/Dockerfile
@@ -0,0 +1,17 @@
+#Copyright(c) Microsoft Corporation.All rights reserved.
+#Licensed under the MIT license.
+
+FROM ubuntu:jammy
+
+RUN apt update
+RUN apt install -y software-properties-common
+RUN add-apt-repository -y ppa:git-core/ppa
+RUN apt update
+RUN DEBIAN_FRONTEND=noninteractive apt install -y git make cmake g++ libaio-dev libgoogle-perftools-dev libunwind-dev clang-format libboost-dev libboost-program-options-dev libmkl-full-dev libcpprest-dev python3.10
+
+WORKDIR /app
+RUN git clone https://github.com/microsoft/DiskANN.git
+WORKDIR /app/DiskANN
+RUN mkdir build
+RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
+RUN cmake --build build -- -j
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/DockerfileDev b/packages/leann-backend-diskann/third_party/DiskANN/DockerfileDev
new file mode 100644
index 0000000..0e95e40
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/DockerfileDev
@@ -0,0 +1,17 @@
+#Copyright(c) Microsoft Corporation.All rights reserved.
+#Licensed under the MIT license.
+
+FROM ubuntu:jammy
+
+RUN apt update
+RUN apt install -y software-properties-common
+RUN add-apt-repository -y ppa:git-core/ppa
+RUN apt update
+RUN DEBIAN_FRONTEND=noninteractive apt install -y git make cmake g++ libaio-dev libgoogle-perftools-dev libunwind-dev clang-format libboost-dev libboost-program-options-dev libboost-test-dev libmkl-full-dev libcpprest-dev python3.10
+
+WORKDIR /app
+RUN git clone https://github.com/microsoft/DiskANN.git
+WORKDIR /app/DiskANN
+RUN mkdir build
+RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DUNIT_TEST=True
+RUN cmake --build build -- -j
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/LICENSE b/packages/leann-backend-diskann/third_party/DiskANN/LICENSE
new file mode 100644
index 0000000..b7a909e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/LICENSE
@@ -0,0 +1,23 @@
+ DiskANN
+
+ MIT License
+
+ Copyright (c) Microsoft Corporation.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/MANIFEST.in b/packages/leann-backend-diskann/third_party/DiskANN/MANIFEST.in
new file mode 100644
index 0000000..0735c27
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/MANIFEST.in
@@ -0,0 +1,12 @@
+include MANIFEST.in
+include *.txt
+include *.md
+include setup.py
+include pyproject.toml
+include *.cmake
+recursive-include gperftools *
+recursive-include include *
+recursive-include python *
+recursive-include windows *
+prune python/tests
+recursive-include src *
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/README.md b/packages/leann-backend-diskann/third_party/DiskANN/README.md
new file mode 100644
index 0000000..44f4c27
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/README.md
@@ -0,0 +1,135 @@
+# DiskANN
+
+[![DiskANN Main](https://github.com/microsoft/DiskANN/actions/workflows/push-test.yml/badge.svg?branch=main)](https://github.com/microsoft/DiskANN/actions/workflows/push-test.yml)
+[![PyPI version](https://img.shields.io/pypi/v/diskannpy.svg)](https://pypi.org/project/diskannpy/)
+[![Downloads shield](https://pepy.tech/badge/diskannpy)](https://pepy.tech/project/diskannpy)
+[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
+
+[![DiskANN Paper](https://img.shields.io/badge/Paper-NeurIPS%3A_DiskANN-blue)](https://papers.nips.cc/paper/9527-rand-nsg-fast-accurate-billion-point-nearest-neighbor-search-on-a-single-node.pdf)
+[![DiskANN Paper](https://img.shields.io/badge/Paper-Arxiv%3A_Fresh--DiskANN-blue)](https://arxiv.org/abs/2105.09613)
+[![DiskANN Paper](https://img.shields.io/badge/Paper-Filtered--DiskANN-blue)](https://harsha-simhadri.org/pubs/Filtered-DiskANN23.pdf)
+
+
+DiskANN is a suite of scalable, accurate and cost-effective approximate nearest neighbor search algorithms for large-scale vector search that support real-time changes and simple filters.
+This code is based on ideas from the [DiskANN](https://papers.nips.cc/paper/9527-rand-nsg-fast-accurate-billion-point-nearest-neighbor-search-on-a-single-node.pdf), [Fresh-DiskANN](https://arxiv.org/abs/2105.09613) and the [Filtered-DiskANN](https://harsha-simhadri.org/pubs/Filtered-DiskANN23.pdf) papers with further improvements.
+This code forked off from [code for NSG](https://github.com/ZJULearning/nsg) algorithm.
+
+This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
+For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
+contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
+
+See [guidelines](CONTRIBUTING.md) for contributing to this project.
+
+## Linux build:
+
+Install the following packages through apt-get
+
+```bash
+sudo apt install make cmake g++ libaio-dev libgoogle-perftools-dev clang-format libboost-all-dev
+```
+
+### Install Intel MKL
+#### Ubuntu 20.04 or newer
+```bash
+sudo apt install libmkl-full-dev
+```
+
+#### Earlier versions of Ubuntu
+Install Intel MKL either by downloading the [oneAPI MKL installer](https://www.intel.com/content/www/us/en/developer/tools/oneapi/onemkl.html) or using [apt](https://software.intel.com/en-us/articles/installing-intel-free-libs-and-python-apt-repo) (we tested with build 2019.4-070 and 2022.1.2.146).
+
+```
+# OneAPI MKL Installer
+wget https://registrationcenter-download.intel.com/akdlm/irc_nas/18487/l_BaseKit_p_2022.1.2.146.sh
+sudo sh l_BaseKit_p_2022.1.2.146.sh -a --components intel.oneapi.lin.mkl.devel --action install --eula accept -s
+```
+
+### Build
+```bash
+mkdir build && cd build && cmake -DCMAKE_BUILD_TYPE=Release .. && make -j
+```
+
+## Windows build:
+
+The Windows version has been tested with Enterprise editions of Visual Studio 2022, 2019 and 2017. It should work with the Community and Professional editions as well without any changes.
+
+**Prerequisites:**
+
+* CMake 3.15+ (available in VisualStudio 2019+ or from https://cmake.org)
+* NuGet.exe (install from https://www.nuget.org/downloads)
+ * The build script will use NuGet to get MKL, OpenMP and Boost packages.
+* DiskANN git repository checked out together with submodules. To check out submodules after git clone:
+```
+git submodule init
+git submodule update
+```
+
+* Environment variables:
+ * [optional] If you would like to override the Boost library listed in windows/packages.config.in, set BOOST_ROOT to your Boost folder.
+
+**Build steps:**
+* Open the "x64 Native Tools Command Prompt for VS 2019" (or corresponding version) and change to DiskANN folder
+* Create a "build" directory inside it
+* Change to the "build" directory and run
+```
+cmake ..
+```
+OR for Visual Studio 2017 and earlier:
+```
+<full-path-to-installed-cmake>\cmake ..
+```
+**This will create a diskann.sln solution**. Now you can:
+
+- Open it from VisualStudio and build either Release or Debug configuration.
+- `<full-path-to-installed-cmake>\cmake --build build`
+- Use MSBuild:
+```
+msbuild.exe diskann.sln /m /nologo /t:Build /p:Configuration="Release" /property:Platform="x64"
+```
+
+* This will also build gperftools submodule for libtcmalloc_minimal dependency.
+* Generated binaries are stored in the x64/Release or x64/Debug directories.
+
+## macOS Build
+
+### Prerequisites
+* Apple Silicon. The code should still work on Intel-based Macs, but there are no guarantees.
+* macOS >= 12.0
+* XCode Command Line Tools (install with `xcode-select --install`)
+* [homebrew](https://brew.sh/)
+
+### Install Required Packages
+```zsh
+brew install cmake
+brew install boost
+brew install gperftools
+brew install libomp
+```
+
+### Build DiskANN
+```zsh
+# same as ubuntu instructions
+mkdir build && cd build && cmake -DCMAKE_BUILD_TYPE=Release .. && make -j
+```
+
+## Usage:
+
+Please see the following pages on using the compiled code:
+
+- [Commandline interface for building and search SSD based indices](workflows/SSD_index.md)
+- [Commandline interface for building and search in memory indices](workflows/in_memory_index.md)
+- [Commandline examples for using in-memory streaming indices](workflows/dynamic_index.md)
+- [Commandline interface for building and search in memory indices with label data and filters](workflows/filtered_in_memory.md)
+- [Commandline interface for building and search SSD based indices with label data and filters](workflows/filtered_ssd_index.md)
+- [diskannpy - DiskANN as a python extension module](python/README.md)
+
+Please cite this software in your work as:
+
+```
+@misc{diskann-github,
+ author = {Simhadri, Harsha Vardhan and Krishnaswamy, Ravishankar and Srinivasa, Gopal and Subramanya, Suhas Jayaram and Antonijevic, Andrija and Pryce, Dax and Kaczynski, David and Williams, Shane and Gollapudi, Siddarth and Sivashankar, Varun and Karia, Neel and Singh, Aditi and Jaiswal, Shikhar and Mahapatro, Neelam and Adams, Philip and Tower, Bryan and Patel, Yash}},
+ title = {{DiskANN: Graph-structured Indices for Scalable, Fast, Fresh and Filtered Approximate Nearest Neighbor Search}},
+ url = {https://github.com/Microsoft/DiskANN},
+ version = {0.6.1},
+ year = {2023}
+}
+```
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/SECURITY.md b/packages/leann-backend-diskann/third_party/DiskANN/SECURITY.md
new file mode 100644
index 0000000..f7b8998
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/SECURITY.md
@@ -0,0 +1,41 @@
+<!-- BEGIN MICROSOFT SECURITY.MD V0.0.5 BLOCK -->
+
+## Security
+
+Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
+
+If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
+
+## Reporting Security Issues
+
+**Please do not report security vulnerabilities through public GitHub issues.**
+
+Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
+
+If you prefer to submit without logging in, send email to [[email protected]](mailto:[email protected]). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
+
+You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
+
+Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
+
+ * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
+ * Full paths of source file(s) related to the manifestation of the issue
+ * The location of the affected source code (tag/branch/commit or direct URL)
+ * Any special configuration required to reproduce the issue
+ * Step-by-step instructions to reproduce the issue
+ * Proof-of-concept or exploit code (if possible)
+ * Impact of the issue, including how an attacker might exploit the issue
+
+This information will help us triage your report more quickly.
+
+If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
+
+## Preferred Languages
+
+We prefer all communications to be in English.
+
+## Policy
+
+Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
+
+<!-- END MICROSOFT SECURITY.MD BLOCK -->
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/apps/CMakeLists.txt
new file mode 100644
index 0000000..e42c0b6
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/CMakeLists.txt
@@ -0,0 +1,42 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_COMPILE_WARNING_AS_ERROR ON)
+
+add_executable(build_memory_index build_memory_index.cpp)
+target_link_libraries(build_memory_index ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+add_executable(build_stitched_index build_stitched_index.cpp)
+target_link_libraries(build_stitched_index ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+add_executable(search_memory_index search_memory_index.cpp)
+target_link_libraries(search_memory_index ${PROJECT_NAME} ${DISKANN_ASYNC_LIB} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+add_executable(build_disk_index build_disk_index.cpp)
+target_link_libraries(build_disk_index ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} ${DISKANN_ASYNC_LIB} Boost::program_options)
+
+add_executable(search_disk_index search_disk_index.cpp)
+target_link_libraries(search_disk_index ${PROJECT_NAME} ${DISKANN_ASYNC_LIB} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+add_executable(range_search_disk_index range_search_disk_index.cpp)
+target_link_libraries(range_search_disk_index ${PROJECT_NAME} ${DISKANN_ASYNC_LIB} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+add_executable(test_streaming_scenario test_streaming_scenario.cpp)
+target_link_libraries(test_streaming_scenario ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+add_executable(test_insert_deletes_consolidate test_insert_deletes_consolidate.cpp)
+target_link_libraries(test_insert_deletes_consolidate ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::program_options)
+
+if (NOT MSVC)
+ install(TARGETS build_memory_index
+ build_stitched_index
+ search_memory_index
+ build_disk_index
+ search_disk_index
+ range_search_disk_index
+ test_streaming_scenario
+ test_insert_deletes_consolidate
+ RUNTIME
+ )
+endif()
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/build_disk_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/build_disk_index.cpp
new file mode 100644
index 0000000..f48b617
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/build_disk_index.cpp
@@ -0,0 +1,191 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <omp.h>
+#include <boost/program_options.hpp>
+
+#include "utils.h"
+#include "disk_utils.h"
+#include "math_utils.h"
+#include "index.h"
+#include "partition.h"
+#include "program_options_utils.hpp"
+
+namespace po = boost::program_options;
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, data_path, index_path_prefix, codebook_prefix, label_file, universal_label,
+ label_type;
+ uint32_t num_threads, R, L, disk_PQ, build_PQ, QD, Lf, filter_threshold;
+ float B, M;
+ bool append_reorder_data = false;
+ bool use_opq = false;
+
+ po::options_description desc{
+ program_options_utils::make_program_description("build_disk_index", "Build a disk-based index.")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("data_path", po::value<std::string>(&data_path)->required(),
+ program_options_utils::INPUT_DATA_PATH);
+ required_configs.add_options()("search_DRAM_budget,B", po::value<float>(&B)->required(),
+ "DRAM budget in GB for searching the index to set the "
+ "compressed level for data while search happens");
+ required_configs.add_options()("build_DRAM_budget,M", po::value<float>(&M)->required(),
+ "DRAM budget in GB for building the index");
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()("max_degree,R", po::value<uint32_t>(&R)->default_value(64),
+ program_options_utils::MAX_BUILD_DEGREE);
+ optional_configs.add_options()("Lbuild,L", po::value<uint32_t>(&L)->default_value(100),
+ program_options_utils::GRAPH_BUILD_COMPLEXITY);
+ optional_configs.add_options()("QD", po::value<uint32_t>(&QD)->default_value(0),
+ " Quantized Dimension for compression");
+ optional_configs.add_options()("codebook_prefix", po::value<std::string>(&codebook_prefix)->default_value(""),
+ "Path prefix for pre-trained codebook");
+ optional_configs.add_options()("PQ_disk_bytes", po::value<uint32_t>(&disk_PQ)->default_value(0),
+ "Number of bytes to which vectors should be compressed "
+ "on SSD; 0 for no compression");
+ optional_configs.add_options()("append_reorder_data", po::bool_switch()->default_value(false),
+ "Include full precision data in the index. Use only in "
+ "conjuction with compressed data on SSD.");
+ optional_configs.add_options()("build_PQ_bytes", po::value<uint32_t>(&build_PQ)->default_value(0),
+ program_options_utils::BUIlD_GRAPH_PQ_BYTES);
+ optional_configs.add_options()("use_opq", po::bool_switch()->default_value(false),
+ program_options_utils::USE_OPQ);
+ optional_configs.add_options()("label_file", po::value<std::string>(&label_file)->default_value(""),
+ program_options_utils::LABEL_FILE);
+ optional_configs.add_options()("universal_label", po::value<std::string>(&universal_label)->default_value(""),
+ program_options_utils::UNIVERSAL_LABEL);
+ optional_configs.add_options()("FilteredLbuild", po::value<uint32_t>(&Lf)->default_value(0),
+ program_options_utils::FILTERED_LBUILD);
+ optional_configs.add_options()("filter_threshold,F", po::value<uint32_t>(&filter_threshold)->default_value(0),
+ "Threshold to break up the existing nodes to generate new graph "
+ "internally where each node has a maximum F labels.");
+ optional_configs.add_options()("label_type", po::value<std::string>(&label_type)->default_value("uint"),
+ program_options_utils::LABEL_TYPE_DESCRIPTION);
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ if (vm["append_reorder_data"].as<bool>())
+ append_reorder_data = true;
+ if (vm["use_opq"].as<bool>())
+ use_opq = true;
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ bool use_filters = (label_file != "") ? true : false;
+ diskann::Metric metric;
+ if (dist_fn == std::string("l2"))
+ metric = diskann::Metric::L2;
+ else if (dist_fn == std::string("mips"))
+ metric = diskann::Metric::INNER_PRODUCT;
+ else if (dist_fn == std::string("cosine"))
+ metric = diskann::Metric::COSINE;
+ else
+ {
+ std::cout << "Error. Only l2 and mips distance functions are supported" << std::endl;
+ return -1;
+ }
+
+ if (append_reorder_data)
+ {
+ if (disk_PQ == 0)
+ {
+ std::cout << "Error: It is not necessary to append data for reordering "
+ "when vectors are not compressed on disk."
+ << std::endl;
+ return -1;
+ }
+ if (data_type != std::string("float"))
+ {
+ std::cout << "Error: Appending data for reordering currently only "
+ "supported for float data type."
+ << std::endl;
+ return -1;
+ }
+ }
+
+ std::string params = std::string(std::to_string(R)) + " " + std::string(std::to_string(L)) + " " +
+ std::string(std::to_string(B)) + " " + std::string(std::to_string(M)) + " " +
+ std::string(std::to_string(num_threads)) + " " + std::string(std::to_string(disk_PQ)) + " " +
+ std::string(std::to_string(append_reorder_data)) + " " +
+ std::string(std::to_string(build_PQ)) + " " + std::string(std::to_string(QD));
+
+ try
+ {
+ if (label_file != "" && label_type == "ushort")
+ {
+ if (data_type == std::string("int8"))
+ return diskann::build_disk_index<int8_t>(data_path.c_str(), index_path_prefix.c_str(), params.c_str(),
+ metric, use_opq, codebook_prefix, use_filters, label_file,
+ universal_label, filter_threshold, Lf);
+ else if (data_type == std::string("uint8"))
+ return diskann::build_disk_index<uint8_t, uint16_t>(
+ data_path.c_str(), index_path_prefix.c_str(), params.c_str(), metric, use_opq, codebook_prefix,
+ use_filters, label_file, universal_label, filter_threshold, Lf);
+ else if (data_type == std::string("float"))
+ return diskann::build_disk_index<float, uint16_t>(
+ data_path.c_str(), index_path_prefix.c_str(), params.c_str(), metric, use_opq, codebook_prefix,
+ use_filters, label_file, universal_label, filter_threshold, Lf);
+ else
+ {
+ diskann::cerr << "Error. Unsupported data type" << std::endl;
+ return -1;
+ }
+ }
+ else
+ {
+ if (data_type == std::string("int8"))
+ return diskann::build_disk_index<int8_t>(data_path.c_str(), index_path_prefix.c_str(), params.c_str(),
+ metric, use_opq, codebook_prefix, use_filters, label_file,
+ universal_label, filter_threshold, Lf);
+ else if (data_type == std::string("uint8"))
+ return diskann::build_disk_index<uint8_t>(data_path.c_str(), index_path_prefix.c_str(), params.c_str(),
+ metric, use_opq, codebook_prefix, use_filters, label_file,
+ universal_label, filter_threshold, Lf);
+ else if (data_type == std::string("float"))
+ return diskann::build_disk_index<float>(data_path.c_str(), index_path_prefix.c_str(), params.c_str(),
+ metric, use_opq, codebook_prefix, use_filters, label_file,
+ universal_label, filter_threshold, Lf);
+ else
+ {
+ diskann::cerr << "Error. Unsupported data type" << std::endl;
+ return -1;
+ }
+ }
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index build failed." << std::endl;
+ return -1;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/build_memory_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/build_memory_index.cpp
new file mode 100644
index 0000000..544e42d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/build_memory_index.cpp
@@ -0,0 +1,164 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <omp.h>
+#include <cstring>
+#include <boost/program_options.hpp>
+
+#include "index.h"
+#include "utils.h"
+#include "program_options_utils.hpp"
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <unistd.h>
+#else
+#include <Windows.h>
+#endif
+
+#include "memory_mapper.h"
+#include "ann_exception.h"
+#include "index_factory.h"
+
+namespace po = boost::program_options;
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, data_path, index_path_prefix, label_file, universal_label, label_type;
+ uint32_t num_threads, R, L, Lf, build_PQ_bytes;
+ float alpha;
+ bool use_pq_build, use_opq;
+
+ po::options_description desc{
+ program_options_utils::make_program_description("build_memory_index", "Build a memory-based DiskANN index.")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("data_path", po::value<std::string>(&data_path)->required(),
+ program_options_utils::INPUT_DATA_PATH);
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()("max_degree,R", po::value<uint32_t>(&R)->default_value(64),
+ program_options_utils::MAX_BUILD_DEGREE);
+ optional_configs.add_options()("Lbuild,L", po::value<uint32_t>(&L)->default_value(100),
+ program_options_utils::GRAPH_BUILD_COMPLEXITY);
+ optional_configs.add_options()("alpha", po::value<float>(&alpha)->default_value(1.2f),
+ program_options_utils::GRAPH_BUILD_ALPHA);
+ optional_configs.add_options()("build_PQ_bytes", po::value<uint32_t>(&build_PQ_bytes)->default_value(0),
+ program_options_utils::BUIlD_GRAPH_PQ_BYTES);
+ optional_configs.add_options()("use_opq", po::bool_switch()->default_value(false),
+ program_options_utils::USE_OPQ);
+ optional_configs.add_options()("label_file", po::value<std::string>(&label_file)->default_value(""),
+ program_options_utils::LABEL_FILE);
+ optional_configs.add_options()("universal_label", po::value<std::string>(&universal_label)->default_value(""),
+ program_options_utils::UNIVERSAL_LABEL);
+
+ optional_configs.add_options()("FilteredLbuild", po::value<uint32_t>(&Lf)->default_value(0),
+ program_options_utils::FILTERED_LBUILD);
+ optional_configs.add_options()("label_type", po::value<std::string>(&label_type)->default_value("uint"),
+ program_options_utils::LABEL_TYPE_DESCRIPTION);
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ use_pq_build = (build_PQ_bytes > 0);
+ use_opq = vm["use_opq"].as<bool>();
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("mips"))
+ {
+ metric = diskann::Metric::INNER_PRODUCT;
+ }
+ else if (dist_fn == std::string("l2"))
+ {
+ metric = diskann::Metric::L2;
+ }
+ else if (dist_fn == std::string("cosine"))
+ {
+ metric = diskann::Metric::COSINE;
+ }
+ else
+ {
+ std::cout << "Unsupported distance function. Currently only L2/ Inner "
+ "Product/Cosine are supported."
+ << std::endl;
+ return -1;
+ }
+
+ try
+ {
+ diskann::cout << "Starting index build with R: " << R << " Lbuild: " << L << " alpha: " << alpha
+ << " #threads: " << num_threads << std::endl;
+
+ size_t data_num, data_dim;
+ diskann::get_bin_metadata(data_path, data_num, data_dim);
+
+ auto index_build_params = diskann::IndexWriteParametersBuilder(L, R)
+ .with_filter_list_size(Lf)
+ .with_alpha(alpha)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+
+ auto filter_params = diskann::IndexFilterParamsBuilder()
+ .with_universal_label(universal_label)
+ .with_label_file(label_file)
+ .with_save_path_prefix(index_path_prefix)
+ .build();
+ auto config = diskann::IndexConfigBuilder()
+ .with_metric(metric)
+ .with_dimension(data_dim)
+ .with_max_points(data_num)
+ .with_data_load_store_strategy(diskann::DataStoreStrategy::MEMORY)
+ .with_graph_load_store_strategy(diskann::GraphStoreStrategy::MEMORY)
+ .with_data_type(data_type)
+ .with_label_type(label_type)
+ .is_dynamic_index(false)
+ .with_index_write_params(index_build_params)
+ .is_enable_tags(false)
+ .is_use_opq(use_opq)
+ .is_pq_dist_build(use_pq_build)
+ .with_num_pq_chunks(build_PQ_bytes)
+ .build();
+
+ auto index_factory = diskann::IndexFactory(config);
+ auto index = index_factory.create_instance();
+ index->build(data_path, data_num, filter_params);
+ index->save(index_path_prefix.c_str());
+ index.reset();
+ return 0;
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index build failed." << std::endl;
+ return -1;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/build_stitched_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/build_stitched_index.cpp
new file mode 100644
index 0000000..60e38c1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/build_stitched_index.cpp
@@ -0,0 +1,441 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <boost/program_options.hpp>
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <random>
+#include <string>
+#include <tuple>
+#include "filter_utils.h"
+#include <omp.h>
+#ifndef _WINDOWS
+#include <sys/uio.h>
+#endif
+
+#include "index.h"
+#include "memory_mapper.h"
+#include "parameters.h"
+#include "utils.h"
+#include "program_options_utils.hpp"
+
+namespace po = boost::program_options;
+typedef std::tuple<std::vector<std::vector<uint32_t>>, uint64_t> stitch_indices_return_values;
+
+/*
+ * Inline function to display progress bar.
+ */
+inline void print_progress(double percentage)
+{
+ int val = (int)(percentage * 100);
+ int lpad = (int)(percentage * PBWIDTH);
+ int rpad = PBWIDTH - lpad;
+ printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");
+ fflush(stdout);
+}
+
+/*
+ * Inline function to generate a random integer in a range.
+ */
+inline size_t random(size_t range_from, size_t range_to)
+{
+ std::random_device rand_dev;
+ std::mt19937 generator(rand_dev());
+ std::uniform_int_distribution<size_t> distr(range_from, range_to);
+ return distr(generator);
+}
+
+/*
+ * function to handle command line parsing.
+ *
+ * Arguments are merely the inputs from the command line.
+ */
+void handle_args(int argc, char **argv, std::string &data_type, path &input_data_path, path &final_index_path_prefix,
+ path &label_data_path, std::string &universal_label, uint32_t &num_threads, uint32_t &R, uint32_t &L,
+ uint32_t &stitched_R, float &alpha)
+{
+ po::options_description desc{
+ program_options_utils::make_program_description("build_stitched_index", "Build a stitched DiskANN index.")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix",
+ po::value<std::string>(&final_index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("data_path", po::value<std::string>(&input_data_path)->required(),
+ program_options_utils::INPUT_DATA_PATH);
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()("max_degree,R", po::value<uint32_t>(&R)->default_value(64),
+ program_options_utils::MAX_BUILD_DEGREE);
+ optional_configs.add_options()("Lbuild,L", po::value<uint32_t>(&L)->default_value(100),
+ program_options_utils::GRAPH_BUILD_COMPLEXITY);
+ optional_configs.add_options()("alpha", po::value<float>(&alpha)->default_value(1.2f),
+ program_options_utils::GRAPH_BUILD_ALPHA);
+ optional_configs.add_options()("label_file", po::value<std::string>(&label_data_path)->default_value(""),
+ program_options_utils::LABEL_FILE);
+ optional_configs.add_options()("universal_label", po::value<std::string>(&universal_label)->default_value(""),
+ program_options_utils::UNIVERSAL_LABEL);
+ optional_configs.add_options()("stitched_R", po::value<uint32_t>(&stitched_R)->default_value(100),
+ "Degree to prune final graph down to");
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ exit(0);
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ throw;
+ }
+}
+
+/*
+ * Custom index save to write the in-memory index to disk.
+ * Also writes required files for diskANN API -
+ * 1. labels_to_medoids
+ * 2. universal_label
+ * 3. data (redundant for static indices)
+ * 4. labels (redundant for static indices)
+ */
+void save_full_index(path final_index_path_prefix, path input_data_path, uint64_t final_index_size,
+ std::vector<std::vector<uint32_t>> stitched_graph,
+ tsl::robin_map<std::string, uint32_t> entry_points, std::string universal_label,
+ path label_data_path)
+{
+ // aux. file 1
+ auto saving_index_timer = std::chrono::high_resolution_clock::now();
+ std::ifstream original_label_data_stream;
+ original_label_data_stream.exceptions(std::ios::badbit | std::ios::failbit);
+ original_label_data_stream.open(label_data_path, std::ios::binary);
+ std::ofstream new_label_data_stream;
+ new_label_data_stream.exceptions(std::ios::badbit | std::ios::failbit);
+ new_label_data_stream.open(final_index_path_prefix + "_labels.txt", std::ios::binary);
+ new_label_data_stream << original_label_data_stream.rdbuf();
+ original_label_data_stream.close();
+ new_label_data_stream.close();
+
+ // aux. file 2
+ std::ifstream original_input_data_stream;
+ original_input_data_stream.exceptions(std::ios::badbit | std::ios::failbit);
+ original_input_data_stream.open(input_data_path, std::ios::binary);
+ std::ofstream new_input_data_stream;
+ new_input_data_stream.exceptions(std::ios::badbit | std::ios::failbit);
+ new_input_data_stream.open(final_index_path_prefix + ".data", std::ios::binary);
+ new_input_data_stream << original_input_data_stream.rdbuf();
+ original_input_data_stream.close();
+ new_input_data_stream.close();
+
+ // aux. file 3
+ std::ofstream labels_to_medoids_writer;
+ labels_to_medoids_writer.exceptions(std::ios::badbit | std::ios::failbit);
+ labels_to_medoids_writer.open(final_index_path_prefix + "_labels_to_medoids.txt");
+ for (auto iter : entry_points)
+ labels_to_medoids_writer << iter.first << ", " << iter.second << std::endl;
+ labels_to_medoids_writer.close();
+
+ // aux. file 4 (only if we're using a universal label)
+ if (universal_label != "")
+ {
+ std::ofstream universal_label_writer;
+ universal_label_writer.exceptions(std::ios::badbit | std::ios::failbit);
+ universal_label_writer.open(final_index_path_prefix + "_universal_label.txt");
+ universal_label_writer << universal_label << std::endl;
+ universal_label_writer.close();
+ }
+
+ // main index
+ uint64_t index_num_frozen_points = 0, index_num_edges = 0;
+ uint32_t index_max_observed_degree = 0, index_entry_point = 0;
+ const size_t METADATA = 2 * sizeof(uint64_t) + 2 * sizeof(uint32_t);
+ for (auto &point_neighbors : stitched_graph)
+ {
+ index_max_observed_degree = std::max(index_max_observed_degree, (uint32_t)point_neighbors.size());
+ }
+
+ std::ofstream stitched_graph_writer;
+ stitched_graph_writer.exceptions(std::ios::badbit | std::ios::failbit);
+ stitched_graph_writer.open(final_index_path_prefix, std::ios_base::binary);
+
+ stitched_graph_writer.write((char *)&final_index_size, sizeof(uint64_t));
+ stitched_graph_writer.write((char *)&index_max_observed_degree, sizeof(uint32_t));
+ stitched_graph_writer.write((char *)&index_entry_point, sizeof(uint32_t));
+ stitched_graph_writer.write((char *)&index_num_frozen_points, sizeof(uint64_t));
+
+ size_t bytes_written = METADATA;
+ for (uint32_t node_point = 0; node_point < stitched_graph.size(); node_point++)
+ {
+ uint32_t current_node_num_neighbors = (uint32_t)stitched_graph[node_point].size();
+ std::vector<uint32_t> current_node_neighbors = stitched_graph[node_point];
+ stitched_graph_writer.write((char *)&current_node_num_neighbors, sizeof(uint32_t));
+ bytes_written += sizeof(uint32_t);
+ for (const auto &current_node_neighbor : current_node_neighbors)
+ {
+ stitched_graph_writer.write((char *)&current_node_neighbor, sizeof(uint32_t));
+ bytes_written += sizeof(uint32_t);
+ }
+ index_num_edges += current_node_num_neighbors;
+ }
+
+ if (bytes_written != final_index_size)
+ {
+ std::cerr << "Error: written bytes does not match allocated space" << std::endl;
+ throw;
+ }
+
+ stitched_graph_writer.close();
+
+ std::chrono::duration<double> saving_index_time = std::chrono::high_resolution_clock::now() - saving_index_timer;
+ std::cout << "Stitched graph written in " << saving_index_time.count() << " seconds" << std::endl;
+ std::cout << "Stitched graph average degree: " << ((float)index_num_edges) / ((float)(stitched_graph.size()))
+ << std::endl;
+ std::cout << "Stitched graph max degree: " << index_max_observed_degree << std::endl << std::endl;
+}
+
+/*
+ * Unions the per-label graph indices together via the following policy:
+ * - any two nodes can only have at most one edge between them -
+ *
+ * Returns the "stitched" graph and its expected file size.
+ */
+template <typename T>
+stitch_indices_return_values stitch_label_indices(
+ path final_index_path_prefix, uint32_t total_number_of_points, label_set all_labels,
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ tsl::robin_map<std::string, uint32_t> &label_entry_points,
+ tsl::robin_map<std::string, std::vector<uint32_t>> label_id_to_orig_id_map)
+{
+ size_t final_index_size = 0;
+ std::vector<std::vector<uint32_t>> stitched_graph(total_number_of_points);
+
+ auto stitching_index_timer = std::chrono::high_resolution_clock::now();
+ for (const auto &lbl : all_labels)
+ {
+ path curr_label_index_path(final_index_path_prefix + "_" + lbl);
+ std::vector<std::vector<uint32_t>> curr_label_index;
+ uint64_t curr_label_index_size;
+ uint32_t curr_label_entry_point;
+
+ std::tie(curr_label_index, curr_label_index_size) =
+ diskann::load_label_index(curr_label_index_path, labels_to_number_of_points[lbl]);
+ curr_label_entry_point = (uint32_t)random(0, curr_label_index.size());
+ label_entry_points[lbl] = label_id_to_orig_id_map[lbl][curr_label_entry_point];
+
+ for (uint32_t node_point = 0; node_point < curr_label_index.size(); node_point++)
+ {
+ uint32_t original_point_id = label_id_to_orig_id_map[lbl][node_point];
+ for (auto &node_neighbor : curr_label_index[node_point])
+ {
+ uint32_t original_neighbor_id = label_id_to_orig_id_map[lbl][node_neighbor];
+ std::vector<uint32_t> curr_point_neighbors = stitched_graph[original_point_id];
+ if (std::find(curr_point_neighbors.begin(), curr_point_neighbors.end(), original_neighbor_id) ==
+ curr_point_neighbors.end())
+ {
+ stitched_graph[original_point_id].push_back(original_neighbor_id);
+ final_index_size += sizeof(uint32_t);
+ }
+ }
+ }
+ }
+
+ const size_t METADATA = 2 * sizeof(uint64_t) + 2 * sizeof(uint32_t);
+ final_index_size += (total_number_of_points * sizeof(uint32_t) + METADATA);
+
+ std::chrono::duration<double> stitching_index_time =
+ std::chrono::high_resolution_clock::now() - stitching_index_timer;
+ std::cout << "stitched graph generated in memory in " << stitching_index_time.count() << " seconds" << std::endl;
+
+ return std::make_tuple(stitched_graph, final_index_size);
+}
+
+/*
+ * Applies the prune_neighbors function from src/index.cpp to
+ * every node in the stitched graph.
+ *
+ * This is an optional step, hence the saving of both the full
+ * and pruned graph.
+ */
+template <typename T>
+void prune_and_save(path final_index_path_prefix, path full_index_path_prefix, path input_data_path,
+ std::vector<std::vector<uint32_t>> stitched_graph, uint32_t stitched_R,
+ tsl::robin_map<std::string, uint32_t> label_entry_points, std::string universal_label,
+ path label_data_path, uint32_t num_threads)
+{
+ size_t dimension, number_of_label_points;
+ auto diskann_cout_buffer = diskann::cout.rdbuf(nullptr);
+ auto std_cout_buffer = std::cout.rdbuf(nullptr);
+ auto pruning_index_timer = std::chrono::high_resolution_clock::now();
+
+ diskann::get_bin_metadata(input_data_path, number_of_label_points, dimension);
+
+ diskann::Index<T> index(diskann::Metric::L2, dimension, number_of_label_points, nullptr, nullptr, 0, false, false,
+ false, false, 0, false);
+
+ // not searching this index, set search_l to 0
+ index.load(full_index_path_prefix.c_str(), num_threads, 1);
+
+ std::cout << "parsing labels" << std::endl;
+
+ index.prune_all_neighbors(stitched_R, 750, 1.2);
+ index.save((final_index_path_prefix).c_str());
+
+ diskann::cout.rdbuf(diskann_cout_buffer);
+ std::cout.rdbuf(std_cout_buffer);
+ std::chrono::duration<double> pruning_index_time = std::chrono::high_resolution_clock::now() - pruning_index_timer;
+ std::cout << "pruning performed in " << pruning_index_time.count() << " seconds\n" << std::endl;
+}
+
+/*
+ * Delete all temporary artifacts.
+ * In the process of creating the stitched index, some temporary artifacts are
+ * created:
+ * 1. the separate bin files for each labels' points
+ * 2. the separate diskANN indices built for each label
+ * 3. the '.data' file created while generating the indices
+ */
+void clean_up_artifacts(path input_data_path, path final_index_path_prefix, label_set all_labels)
+{
+ for (const auto &lbl : all_labels)
+ {
+ path curr_label_input_data_path(input_data_path + "_" + lbl);
+ path curr_label_index_path(final_index_path_prefix + "_" + lbl);
+ path curr_label_index_path_data(curr_label_index_path + ".data");
+
+ if (std::remove(curr_label_index_path.c_str()) != 0)
+ throw;
+ if (std::remove(curr_label_input_data_path.c_str()) != 0)
+ throw;
+ if (std::remove(curr_label_index_path_data.c_str()) != 0)
+ throw;
+ }
+}
+
+int main(int argc, char **argv)
+{
+ // 1. handle cmdline inputs
+ std::string data_type;
+ path input_data_path, final_index_path_prefix, label_data_path;
+ std::string universal_label;
+ uint32_t num_threads, R, L, stitched_R;
+ float alpha;
+
+ auto index_timer = std::chrono::high_resolution_clock::now();
+ handle_args(argc, argv, data_type, input_data_path, final_index_path_prefix, label_data_path, universal_label,
+ num_threads, R, L, stitched_R, alpha);
+
+ path labels_file_to_use = final_index_path_prefix + "_label_formatted.txt";
+ path labels_map_file = final_index_path_prefix + "_labels_map.txt";
+
+ convert_labels_string_to_int(label_data_path, labels_file_to_use, labels_map_file, universal_label);
+
+ // 2. parse label file and create necessary data structures
+ std::vector<label_set> point_ids_to_labels;
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points;
+ label_set all_labels;
+
+ std::tie(point_ids_to_labels, labels_to_number_of_points, all_labels) =
+ diskann::parse_label_file(labels_file_to_use, universal_label);
+
+ // 3. for each label, make a separate data file
+ tsl::robin_map<std::string, std::vector<uint32_t>> label_id_to_orig_id_map;
+ uint32_t total_number_of_points = (uint32_t)point_ids_to_labels.size();
+
+#ifndef _WINDOWS
+ if (data_type == "uint8")
+ label_id_to_orig_id_map = diskann::generate_label_specific_vector_files<uint8_t>(
+ input_data_path, labels_to_number_of_points, point_ids_to_labels, all_labels);
+ else if (data_type == "int8")
+ label_id_to_orig_id_map = diskann::generate_label_specific_vector_files<int8_t>(
+ input_data_path, labels_to_number_of_points, point_ids_to_labels, all_labels);
+ else if (data_type == "float")
+ label_id_to_orig_id_map = diskann::generate_label_specific_vector_files<float>(
+ input_data_path, labels_to_number_of_points, point_ids_to_labels, all_labels);
+ else
+ throw;
+#else
+ if (data_type == "uint8")
+ label_id_to_orig_id_map = diskann::generate_label_specific_vector_files_compat<uint8_t>(
+ input_data_path, labels_to_number_of_points, point_ids_to_labels, all_labels);
+ else if (data_type == "int8")
+ label_id_to_orig_id_map = diskann::generate_label_specific_vector_files_compat<int8_t>(
+ input_data_path, labels_to_number_of_points, point_ids_to_labels, all_labels);
+ else if (data_type == "float")
+ label_id_to_orig_id_map = diskann::generate_label_specific_vector_files_compat<float>(
+ input_data_path, labels_to_number_of_points, point_ids_to_labels, all_labels);
+ else
+ throw;
+#endif
+
+ // 4. for each created data file, create a vanilla diskANN index
+ if (data_type == "uint8")
+ diskann::generate_label_indices<uint8_t>(input_data_path, final_index_path_prefix, all_labels, R, L, alpha,
+ num_threads);
+ else if (data_type == "int8")
+ diskann::generate_label_indices<int8_t>(input_data_path, final_index_path_prefix, all_labels, R, L, alpha,
+ num_threads);
+ else if (data_type == "float")
+ diskann::generate_label_indices<float>(input_data_path, final_index_path_prefix, all_labels, R, L, alpha,
+ num_threads);
+ else
+ throw;
+
+ // 5. "stitch" the indices together
+ std::vector<std::vector<uint32_t>> stitched_graph;
+ tsl::robin_map<std::string, uint32_t> label_entry_points;
+ uint64_t stitched_graph_size;
+
+ if (data_type == "uint8")
+ std::tie(stitched_graph, stitched_graph_size) =
+ stitch_label_indices<uint8_t>(final_index_path_prefix, total_number_of_points, all_labels,
+ labels_to_number_of_points, label_entry_points, label_id_to_orig_id_map);
+ else if (data_type == "int8")
+ std::tie(stitched_graph, stitched_graph_size) =
+ stitch_label_indices<int8_t>(final_index_path_prefix, total_number_of_points, all_labels,
+ labels_to_number_of_points, label_entry_points, label_id_to_orig_id_map);
+ else if (data_type == "float")
+ std::tie(stitched_graph, stitched_graph_size) =
+ stitch_label_indices<float>(final_index_path_prefix, total_number_of_points, all_labels,
+ labels_to_number_of_points, label_entry_points, label_id_to_orig_id_map);
+ else
+ throw;
+ path full_index_path_prefix = final_index_path_prefix + "_full";
+ // 5a. save the stitched graph to disk
+ save_full_index(full_index_path_prefix, input_data_path, stitched_graph_size, stitched_graph, label_entry_points,
+ universal_label, labels_file_to_use);
+
+ // 6. run a prune on the stitched index, and save to disk
+ if (data_type == "uint8")
+ prune_and_save<uint8_t>(final_index_path_prefix, full_index_path_prefix, input_data_path, stitched_graph,
+ stitched_R, label_entry_points, universal_label, labels_file_to_use, num_threads);
+ else if (data_type == "int8")
+ prune_and_save<int8_t>(final_index_path_prefix, full_index_path_prefix, input_data_path, stitched_graph,
+ stitched_R, label_entry_points, universal_label, labels_file_to_use, num_threads);
+ else if (data_type == "float")
+ prune_and_save<float>(final_index_path_prefix, full_index_path_prefix, input_data_path, stitched_graph,
+ stitched_R, label_entry_points, universal_label, labels_file_to_use, num_threads);
+ else
+ throw;
+
+ std::chrono::duration<double> index_time = std::chrono::high_resolution_clock::now() - index_timer;
+ std::cout << "pruned/stitched graph generated in " << index_time.count() << " seconds" << std::endl;
+
+ clean_up_artifacts(input_data_path, final_index_path_prefix, all_labels);
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/python/README.md b/packages/leann-backend-diskann/third_party/DiskANN/apps/python/README.md
new file mode 100644
index 0000000..2b0bc35
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/python/README.md
@@ -0,0 +1,46 @@
+<!-- Copyright (c) Microsoft Corporation. All rights reserved.
+ Licensed under the MIT license. -->
+
+# Integration Tests
+The following tests use Python to prepare, run, verify, and tear down the rest api services.
+
+We do make use of the built-in `unittest` library, but that's only to take advantage of test reporting purposes.
+
+These are decidedly **not** _unit_ tests. These are end to end integration tests.
+
+## Caveats
+This has only been tested or built for Linux, though we have written platform agnostic Python for the smoke test
+(i.e. using `os.path.join`, etc)
+
+It has been tested on Python 3.9 and 3.10, but should work on Python 3.6+.
+
+## How to Run
+
+First, build the DiskANN RestAPI code; see $REPOSITORY_ROOT/workflows/rest_api.md for detailed instructions.
+
+```bash
+cd tests/python
+python3 -m venv venv
+source venv/bin/activate
+pip install -r requirements.txt
+
+export DISKANN_BUILD_DIR=/path/to/your/diskann/build
+python -m unittest
+```
+
+## Smoke Test Failed, Now What?
+The smoke test written takes advantage of temporary directories that are only valid during the
+lifetime of the test. The contents of these directories include:
+- Randomized vectors (first in tsv, then bin form) used to build the PQFlashIndex
+- The PQFlashIndex files
+
+It is useful to keep these around. By setting some environment variables, you can control whether an ephemeral,
+temporary directory is used (and deleted on test completion), or left as an exercise for the developer to
+clean up.
+
+The valid environment variables are:
+- `DISKANN_REST_TEST_WORKING_DIR` (example: `$USER/DiskANNRestTest`)
+ - If this is specified, it **must exist** and **must be writeable**. Any existing files will be clobbered.
+- `DISKANN_REST_SERVER` (example: `http://127.0.0.1:10067`)
+ - Note that if this is set, no data will be generated, nor will a server be started; it is presumed you have done
+ all the work in creating and starting the rest server prior to running the test and just submits requests against it.
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/python/restapi/__init__.py b/packages/leann-backend-diskann/third_party/DiskANN/apps/python/restapi/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/python/restapi/disk_ann_util.py b/packages/leann-backend-diskann/third_party/DiskANN/apps/python/restapi/disk_ann_util.py
new file mode 100644
index 0000000..ec89310
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/python/restapi/disk_ann_util.py
@@ -0,0 +1,67 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import numpy as np
+import os
+import subprocess
+
+
+def output_vectors(
+ diskann_build_path: str,
+ temporary_file_path: str,
+ vectors: np.ndarray,
+ timeout: int = 60
+) -> str:
+ vectors_as_tsv_path = os.path.join(temporary_file_path, "vectors.tsv")
+ with open(vectors_as_tsv_path, "w") as vectors_tsv_out:
+ for vector in vectors:
+ as_str = "\t".join((str(component) for component in vector))
+ print(as_str, file=vectors_tsv_out)
+ # there is probably a clever way to have numpy write out C++ friendly floats, so feel free to remove this in
+ # favor of something more sane later
+ vectors_as_bin_path = os.path.join(temporary_file_path, "vectors.bin")
+ tsv_to_bin_path = os.path.join(diskann_build_path, "apps", "utils", "tsv_to_bin")
+
+ number_of_points, dimensions = vectors.shape
+ args = [
+ tsv_to_bin_path,
+ "float",
+ vectors_as_tsv_path,
+ vectors_as_bin_path,
+ str(dimensions),
+ str(number_of_points)
+ ]
+ completed = subprocess.run(args, timeout=timeout)
+ if completed.returncode != 0:
+ raise Exception(f"Unable to convert tsv to binary using tsv_to_bin, completed_process: {completed}")
+ return vectors_as_bin_path
+
+
+def build_ssd_index(
+ diskann_build_path: str,
+ temporary_file_path: str,
+ vectors: np.ndarray,
+ per_process_timeout: int = 60 # this may not be long enough if you're doing something larger
+):
+ vectors_as_bin_path = output_vectors(diskann_build_path, temporary_file_path, vectors, timeout=per_process_timeout)
+
+ ssd_builder_path = os.path.join(diskann_build_path, "apps", "build_disk_index")
+ args = [
+ ssd_builder_path,
+ "--data_type", "float",
+ "--dist_fn", "l2",
+ "--data_path", vectors_as_bin_path,
+ "--index_path_prefix", os.path.join(temporary_file_path, "smoke_test"),
+ "-R", "64",
+ "-L", "100",
+ "--search_DRAM_budget", "1",
+ "--build_DRAM_budget", "1",
+ "--num_threads", "1",
+ "--PQ_disk_bytes", "0"
+ ]
+ completed = subprocess.run(args, timeout=per_process_timeout)
+
+ if completed.returncode != 0:
+ command_run = " ".join(args)
+ raise Exception(f"Unable to build a disk index with the command: '{command_run}'\ncompleted_process: {completed}\nstdout: {completed.stdout}\nstderr: {completed.stderr}")
+ # index is now built inside of temporary_file_path
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/range_search_disk_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/range_search_disk_index.cpp
new file mode 100644
index 0000000..3167572
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/range_search_disk_index.cpp
@@ -0,0 +1,379 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <atomic>
+#include <cstring>
+#include <iomanip>
+#include <omp.h>
+#include <set>
+#include <boost/program_options.hpp>
+
+#include "index.h"
+#include "disk_utils.h"
+#include "math_utils.h"
+#include "memory_mapper.h"
+#include "pq_flash_index.h"
+#include "partition.h"
+#include "timer.h"
+#include "program_options_utils.hpp"
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include "linux_aligned_file_reader.h"
+#else
+#ifdef USE_BING_INFRA
+#include "bing_aligned_file_reader.h"
+#else
+#include "windows_aligned_file_reader.h"
+#endif
+#endif
+
+namespace po = boost::program_options;
+
+#define WARMUP false
+
+void print_stats(std::string category, std::vector<float> percentiles, std::vector<float> results)
+{
+ diskann::cout << std::setw(20) << category << ": " << std::flush;
+ for (uint32_t s = 0; s < percentiles.size(); s++)
+ {
+ diskann::cout << std::setw(8) << percentiles[s] << "%";
+ }
+ diskann::cout << std::endl;
+ diskann::cout << std::setw(22) << " " << std::flush;
+ for (uint32_t s = 0; s < percentiles.size(); s++)
+ {
+ diskann::cout << std::setw(9) << results[s];
+ }
+ diskann::cout << std::endl;
+}
+
+template <typename T, typename LabelT = uint32_t>
+int search_disk_index(diskann::Metric &metric, const std::string &index_path_prefix, const std::string &query_file,
+ std::string &gt_file, const uint32_t num_threads, const float search_range,
+ const uint32_t beamwidth, const uint32_t num_nodes_to_cache, const std::vector<uint32_t> &Lvec)
+{
+ std::string pq_prefix = index_path_prefix + "_pq";
+ std::string disk_index_file = index_path_prefix + "_disk.index";
+ std::string warmup_query_file = index_path_prefix + "_sample_data.bin";
+
+ diskann::cout << "Search parameters: #threads: " << num_threads << ", ";
+ if (beamwidth <= 0)
+ diskann::cout << "beamwidth to be optimized for each L value" << std::endl;
+ else
+ diskann::cout << " beamwidth: " << beamwidth << std::endl;
+
+ // load query bin
+ T *query = nullptr;
+ std::vector<std::vector<uint32_t>> groundtruth_ids;
+ size_t query_num, query_dim, query_aligned_dim, gt_num;
+ diskann::load_aligned_bin<T>(query_file, query, query_num, query_dim, query_aligned_dim);
+
+ bool calc_recall_flag = false;
+ if (gt_file != std::string("null") && file_exists(gt_file))
+ {
+ diskann::load_range_truthset(gt_file, groundtruth_ids,
+ gt_num); // use for range search type of truthset
+ // diskann::prune_truthset_for_range(gt_file, search_range,
+ // groundtruth_ids, gt_num); // use for traditional truthset
+ if (gt_num != query_num)
+ {
+ diskann::cout << "Error. Mismatch in number of queries and ground truth data" << std::endl;
+ return -1;
+ }
+ calc_recall_flag = true;
+ }
+
+ std::shared_ptr<AlignedFileReader> reader = nullptr;
+#ifdef _WINDOWS
+#ifndef USE_BING_INFRA
+ reader.reset(new WindowsAlignedFileReader());
+#else
+ reader.reset(new diskann::BingAlignedFileReader());
+#endif
+#else
+ reader.reset(new LinuxAlignedFileReader());
+#endif
+
+ std::unique_ptr<diskann::PQFlashIndex<T, LabelT>> _pFlashIndex(
+ new diskann::PQFlashIndex<T, LabelT>(reader, metric));
+
+ int res = _pFlashIndex->load(num_threads, index_path_prefix.c_str());
+
+ if (res != 0)
+ {
+ return res;
+ }
+ // cache bfs levels
+ std::vector<uint32_t> node_list;
+ diskann::cout << "Caching " << num_nodes_to_cache << " BFS nodes around medoid(s)" << std::endl;
+ _pFlashIndex->cache_bfs_levels(num_nodes_to_cache, node_list);
+ // _pFlashIndex->generate_cache_list_from_sample_queries(
+ // warmup_query_file, 15, 6, num_nodes_to_cache, num_threads,
+ // node_list);
+ _pFlashIndex->load_cache_list(node_list);
+ node_list.clear();
+ node_list.shrink_to_fit();
+
+ omp_set_num_threads(num_threads);
+
+ uint64_t warmup_L = 20;
+ uint64_t warmup_num = 0, warmup_dim = 0, warmup_aligned_dim = 0;
+ T *warmup = nullptr;
+
+ if (WARMUP)
+ {
+ if (file_exists(warmup_query_file))
+ {
+ diskann::load_aligned_bin<T>(warmup_query_file, warmup, warmup_num, warmup_dim, warmup_aligned_dim);
+ }
+ else
+ {
+ warmup_num = (std::min)((uint32_t)150000, (uint32_t)15000 * num_threads);
+ warmup_dim = query_dim;
+ warmup_aligned_dim = query_aligned_dim;
+ diskann::alloc_aligned(((void **)&warmup), warmup_num * warmup_aligned_dim * sizeof(T), 8 * sizeof(T));
+ std::memset(warmup, 0, warmup_num * warmup_aligned_dim * sizeof(T));
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<> dis(-128, 127);
+ for (uint32_t i = 0; i < warmup_num; i++)
+ {
+ for (uint32_t d = 0; d < warmup_dim; d++)
+ {
+ warmup[i * warmup_aligned_dim + d] = (T)dis(gen);
+ }
+ }
+ }
+ diskann::cout << "Warming up index... " << std::flush;
+ std::vector<uint64_t> warmup_result_ids_64(warmup_num, 0);
+ std::vector<float> warmup_result_dists(warmup_num, 0);
+
+#pragma omp parallel for schedule(dynamic, 1)
+ for (int64_t i = 0; i < (int64_t)warmup_num; i++)
+ {
+ _pFlashIndex->cached_beam_search(warmup + (i * warmup_aligned_dim), 1, warmup_L,
+ warmup_result_ids_64.data() + (i * 1),
+ warmup_result_dists.data() + (i * 1), 4);
+ }
+ diskann::cout << "..done" << std::endl;
+ }
+
+ diskann::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
+ diskann::cout.precision(2);
+
+ std::string recall_string = "Recall@rng=" + std::to_string(search_range);
+ diskann::cout << std::setw(6) << "L" << std::setw(12) << "Beamwidth" << std::setw(16) << "QPS" << std::setw(16)
+ << "Mean Latency" << std::setw(16) << "99.9 Latency" << std::setw(16) << "Mean IOs" << std::setw(16)
+ << "CPU (s)";
+ if (calc_recall_flag)
+ {
+ diskann::cout << std::setw(16) << recall_string << std::endl;
+ }
+ else
+ diskann::cout << std::endl;
+ diskann::cout << "==============================================================="
+ "==========================================="
+ << std::endl;
+
+ std::vector<std::vector<std::vector<uint32_t>>> query_result_ids(Lvec.size());
+
+ uint32_t optimized_beamwidth = 2;
+ uint32_t max_list_size = 10000;
+
+ for (uint32_t test_id = 0; test_id < Lvec.size(); test_id++)
+ {
+ uint32_t L = Lvec[test_id];
+
+ if (beamwidth <= 0)
+ {
+ optimized_beamwidth =
+ optimize_beamwidth(_pFlashIndex, warmup, warmup_num, warmup_aligned_dim, L, optimized_beamwidth);
+ }
+ else
+ optimized_beamwidth = beamwidth;
+
+ query_result_ids[test_id].clear();
+ query_result_ids[test_id].resize(query_num);
+
+ diskann::QueryStats *stats = new diskann::QueryStats[query_num];
+
+ auto s = std::chrono::high_resolution_clock::now();
+#pragma omp parallel for schedule(dynamic, 1)
+ for (int64_t i = 0; i < (int64_t)query_num; i++)
+ {
+ std::vector<uint64_t> indices;
+ std::vector<float> distances;
+ uint32_t res_count =
+ _pFlashIndex->range_search(query + (i * query_aligned_dim), search_range, L, max_list_size, indices,
+ distances, optimized_beamwidth, stats + i);
+ query_result_ids[test_id][i].reserve(res_count);
+ query_result_ids[test_id][i].resize(res_count);
+ for (uint32_t idx = 0; idx < res_count; idx++)
+ query_result_ids[test_id][i][idx] = (uint32_t)indices[idx];
+ }
+ auto e = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diff = e - s;
+ auto qps = (1.0 * query_num) / (1.0 * diff.count());
+
+ auto mean_latency = diskann::get_mean_stats<float>(
+ stats, query_num, [](const diskann::QueryStats &stats) { return stats.total_us; });
+
+ auto latency_999 = diskann::get_percentile_stats<float>(
+ stats, query_num, 0.999, [](const diskann::QueryStats &stats) { return stats.total_us; });
+
+ auto mean_ios = diskann::get_mean_stats<uint32_t>(stats, query_num,
+ [](const diskann::QueryStats &stats) { return stats.n_ios; });
+
+ double mean_cpuus = diskann::get_mean_stats<float>(
+ stats, query_num, [](const diskann::QueryStats &stats) { return stats.cpu_us; });
+
+ double recall = 0;
+ double ratio_of_sums = 0;
+ if (calc_recall_flag)
+ {
+ recall =
+ diskann::calculate_range_search_recall((uint32_t)query_num, groundtruth_ids, query_result_ids[test_id]);
+
+ uint32_t total_true_positive = 0;
+ uint32_t total_positive = 0;
+ for (uint32_t i = 0; i < query_num; i++)
+ {
+ total_true_positive += (uint32_t)query_result_ids[test_id][i].size();
+ total_positive += (uint32_t)groundtruth_ids[i].size();
+ }
+
+ ratio_of_sums = (1.0 * total_true_positive) / (1.0 * total_positive);
+ }
+
+ diskann::cout << std::setw(6) << L << std::setw(12) << optimized_beamwidth << std::setw(16) << qps
+ << std::setw(16) << mean_latency << std::setw(16) << latency_999 << std::setw(16) << mean_ios
+ << std::setw(16) << mean_cpuus;
+ if (calc_recall_flag)
+ {
+ diskann::cout << std::setw(16) << recall << "," << ratio_of_sums << std::endl;
+ }
+ else
+ diskann::cout << std::endl;
+ }
+
+ diskann::cout << "Done searching. " << std::endl;
+
+ diskann::aligned_free(query);
+ if (warmup != nullptr)
+ diskann::aligned_free(warmup);
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, index_path_prefix, result_path_prefix, query_file, gt_file;
+ uint32_t num_threads, W, num_nodes_to_cache;
+ std::vector<uint32_t> Lvec;
+ float range;
+
+ po::options_description desc{program_options_utils::make_program_description(
+ "range_search_disk_index", "Searches disk DiskANN indexes using ranges")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("query_file", po::value<std::string>(&query_file)->required(),
+ program_options_utils::QUERY_FILE_DESCRIPTION);
+ required_configs.add_options()("search_list,L",
+ po::value<std::vector<uint32_t>>(&Lvec)->multitoken()->required(),
+ program_options_utils::SEARCH_LIST_DESCRIPTION);
+ required_configs.add_options()("range_threshold,K", po::value<float>(&range)->required(),
+ "Number of neighbors to be returned");
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()("gt_file", po::value<std::string>(&gt_file)->default_value(std::string("null")),
+ program_options_utils::GROUND_TRUTH_FILE_DESCRIPTION);
+ optional_configs.add_options()("num_nodes_to_cache", po::value<uint32_t>(&num_nodes_to_cache)->default_value(0),
+ program_options_utils::NUMBER_OF_NODES_TO_CACHE);
+ optional_configs.add_options()("beamwidth,W", po::value<uint32_t>(&W)->default_value(2),
+ program_options_utils::BEAMWIDTH);
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("mips"))
+ {
+ metric = diskann::Metric::INNER_PRODUCT;
+ }
+ else if (dist_fn == std::string("l2"))
+ {
+ metric = diskann::Metric::L2;
+ }
+ else if (dist_fn == std::string("cosine"))
+ {
+ metric = diskann::Metric::COSINE;
+ }
+ else
+ {
+ std::cout << "Unsupported distance function. Currently only L2/ Inner "
+ "Product/Cosine are supported."
+ << std::endl;
+ return -1;
+ }
+
+ if ((data_type != std::string("float")) && (metric == diskann::Metric::INNER_PRODUCT))
+ {
+ std::cout << "Currently support only floating point data for Inner Product." << std::endl;
+ return -1;
+ }
+
+ try
+ {
+ if (data_type == std::string("float"))
+ return search_disk_index<float>(metric, index_path_prefix, query_file, gt_file, num_threads, range, W,
+ num_nodes_to_cache, Lvec);
+ else if (data_type == std::string("int8"))
+ return search_disk_index<int8_t>(metric, index_path_prefix, query_file, gt_file, num_threads, range, W,
+ num_nodes_to_cache, Lvec);
+ else if (data_type == std::string("uint8"))
+ return search_disk_index<uint8_t>(metric, index_path_prefix, query_file, gt_file, num_threads, range, W,
+ num_nodes_to_cache, Lvec);
+ else
+ {
+ std::cerr << "Unsupported data type. Use float or int8 or uint8" << std::endl;
+ return -1;
+ }
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index search failed." << std::endl;
+ return -1;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/CMakeLists.txt
new file mode 100644
index 0000000..c73b427
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/CMakeLists.txt
@@ -0,0 +1,40 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+set(CMAKE_CXX_STANDARD 17)
+
+add_executable(inmem_server inmem_server.cpp)
+if(MSVC)
+ target_link_options(inmem_server PRIVATE /MACHINE:x64)
+ target_link_libraries(inmem_server debug ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG}/diskann_dll.lib Boost::program_options)
+ target_link_libraries(inmem_server optimized ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE}/diskann_dll.lib Boost::program_options)
+else()
+ target_link_libraries(inmem_server ${PROJECT_NAME} aio -ltcmalloc -lboost_system -lcrypto -lssl -lcpprest Boost::program_options)
+endif()
+
+add_executable(ssd_server ssd_server.cpp)
+if(MSVC)
+ target_link_options(ssd_server PRIVATE /MACHINE:x64)
+ target_link_libraries(ssd_server debug ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG}/diskann_dll.lib Boost::program_options)
+ target_link_libraries(ssd_server optimized ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE}/diskann_dll.lib Boost::program_options)
+else()
+ target_link_libraries(ssd_server ${PROJECT_NAME} aio -ltcmalloc -lboost_system -lcrypto -lssl -lcpprest Boost::program_options)
+endif()
+
+add_executable(multiple_ssdindex_server multiple_ssdindex_server.cpp)
+if(MSVC)
+ target_link_options(multiple_ssdindex_server PRIVATE /MACHINE:x64)
+ target_link_libraries(multiple_ssdindex_server debug ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG}/diskann_dll.lib Boost::program_options)
+ target_link_libraries(multiple_ssdindex_server optimized ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE}/diskann_dll.lib Boost::program_options)
+else()
+ target_link_libraries(multiple_ssdindex_server ${PROJECT_NAME} aio -ltcmalloc -lboost_system -lcrypto -lssl -lcpprest Boost::program_options)
+endif()
+
+add_executable(client client.cpp)
+if(MSVC)
+ target_link_options(client PRIVATE /MACHINE:x64)
+ target_link_libraries(client debug ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG}/diskann_dll.lib Boost::program_options)
+ target_link_libraries(client optimized ${CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE}/diskann_dll.lib Boost::program_options)
+else()
+ target_link_libraries(client ${PROJECT_NAME} -lboost_system -lcrypto -lssl -lcpprest Boost::program_options)
+endif()
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/client.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/client.cpp
new file mode 100644
index 0000000..fdf4414
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/client.cpp
@@ -0,0 +1,124 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <ctime>
+#include <functional>
+#include <iomanip>
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <string>
+#include <cstdlib>
+#include <codecvt>
+#include <boost/program_options.hpp>
+
+#include <cpprest/http_client.h>
+#include <restapi/common.h>
+
+using namespace web;
+using namespace web::http;
+using namespace web::http::client;
+
+using namespace diskann;
+namespace po = boost::program_options;
+
+template <typename T>
+void query_loop(const std::string &ip_addr_port, const std::string &query_file, const unsigned nq, const unsigned Ls,
+ const unsigned k_value)
+{
+ web::http::client::http_client client(U(ip_addr_port));
+
+ T *data;
+ size_t npts = 1, ndims = 128, rounded_dim = 128;
+ diskann::load_aligned_bin<T>(query_file, data, npts, ndims, rounded_dim);
+
+ for (unsigned i = 0; i < nq; ++i)
+ {
+ T *vec = data + i * rounded_dim;
+ web::http::http_request http_query(methods::POST);
+ web::json::value queryJson = web::json::value::object();
+ queryJson[QUERY_ID_KEY] = i;
+ queryJson[K_KEY] = k_value;
+ queryJson[L_KEY] = Ls;
+ for (size_t i = 0; i < ndims; ++i)
+ {
+ queryJson[VECTOR_KEY][i] = web::json::value::number(vec[i]);
+ }
+ http_query.set_body(queryJson);
+
+ client.request(http_query)
+ .then([](web::http::http_response response) -> pplx::task<utility::string_t> {
+ if (response.status_code() == status_codes::OK)
+ {
+ return response.extract_string();
+ }
+ std::cerr << "Query failed" << std::endl;
+ return pplx::task_from_result(utility::string_t());
+ })
+ .then([](pplx::task<utility::string_t> previousTask) {
+ try
+ {
+ std::cout << previousTask.get() << std::endl;
+ }
+ catch (http_exception const &e)
+ {
+ std::wcout << e.what() << std::endl;
+ }
+ })
+ .wait();
+ }
+}
+
+int main(int argc, char *argv[])
+{
+ std::string data_type, query_file, address;
+ uint32_t num_queries;
+ uint32_t l_search, k_value;
+
+ po::options_description desc{"Arguments"};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("address", po::value<std::string>(&address)->required(), "Web server address");
+ desc.add_options()("query_file", po::value<std::string>(&query_file)->required(),
+ "File containing the queries to search");
+ desc.add_options()("num_queries,Q", po::value<uint32_t>(&num_queries)->required(),
+ "Number of queries to search");
+ desc.add_options()("l_search", po::value<uint32_t>(&l_search)->required(), "Value of L");
+ desc.add_options()("k_value,K", po::value<uint32_t>(&k_value)->default_value(10), "Value of K (default 10)");
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << std::endl;
+ return -1;
+ }
+
+ if (data_type == std::string("float"))
+ {
+ query_loop<float>(address, query_file, num_queries, l_search, k_value);
+ }
+ else if (data_type == std::string("int8"))
+ {
+ query_loop<int8_t>(address, query_file, num_queries, l_search, k_value);
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ query_loop<uint8_t>(address, query_file, num_queries, l_search, k_value);
+ }
+ else
+ {
+ std::cerr << "Unsupported type " << argv[2] << std::endl;
+ return -1;
+ }
+
+ return 0;
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/inmem_server.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/inmem_server.cpp
new file mode 100644
index 0000000..11da541
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/inmem_server.cpp
@@ -0,0 +1,138 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <ctime>
+#include <functional>
+#include <iomanip>
+#include <string>
+#include <cstdlib>
+#include <codecvt>
+#include <boost/program_options.hpp>
+
+#include <restapi/server.h>
+
+using namespace diskann;
+namespace po = boost::program_options;
+
+std::unique_ptr<Server> g_httpServer(nullptr);
+std::vector<std::unique_ptr<diskann::BaseSearch>> g_inMemorySearch;
+
+void setup(const utility::string_t &address, const std::string &typestring)
+{
+ web::http::uri_builder uriBldr(address);
+ auto uri = uriBldr.to_uri();
+
+ std::cout << "Attempting to start server on " << uri.to_string() << std::endl;
+
+ g_httpServer = std::unique_ptr<Server>(new Server(uri, g_inMemorySearch, typestring));
+ std::cout << "Created a server object" << std::endl;
+
+ g_httpServer->open().wait();
+ ucout << U"Listening for requests on: " << address << std::endl;
+}
+
+void teardown(const utility::string_t &address)
+{
+ g_httpServer->close().wait();
+}
+
+int main(int argc, char *argv[])
+{
+ std::string data_type, index_file, data_file, address, dist_fn, tags_file;
+ uint32_t num_threads;
+ uint32_t l_search;
+
+ po::options_description desc{"Arguments"};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("address", po::value<std::string>(&address)->required(), "Web server address");
+ desc.add_options()("data_file", po::value<std::string>(&data_file)->required(),
+ "File containing the data found in the index");
+ desc.add_options()("index_path_prefix", po::value<std::string>(&index_file)->required(),
+ "Path prefix for saving index file components");
+ desc.add_options()("num_threads,T", po::value<uint32_t>(&num_threads)->required(),
+ "Number of threads used for building index");
+ desc.add_options()("l_search", po::value<uint32_t>(&l_search)->required(), "Value of L");
+ desc.add_options()("dist_fn", po::value<std::string>(&dist_fn)->default_value("l2"),
+ "distance function <l2/mips>");
+ desc.add_options()("tags_file", po::value<std::string>(&tags_file)->default_value(std::string()),
+ "Tags file location");
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << std::endl;
+ return -1;
+ }
+ diskann::Metric metric;
+ if (dist_fn == std::string("l2"))
+ metric = diskann::Metric::L2;
+ else if (dist_fn == std::string("mips"))
+ metric = diskann::Metric::INNER_PRODUCT;
+ else
+ {
+ std::cout << "Error. Only l2 and mips distance functions are supported" << std::endl;
+ return -1;
+ }
+
+ if (data_type == std::string("float"))
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(
+ new diskann::InMemorySearch<float>(data_file, index_file, tags_file, metric, num_threads, l_search));
+ g_inMemorySearch.push_back(std::move(searcher));
+ }
+ else if (data_type == std::string("int8"))
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(
+ new diskann::InMemorySearch<int8_t>(data_file, index_file, tags_file, metric, num_threads, l_search));
+ g_inMemorySearch.push_back(std::move(searcher));
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(
+ new diskann::InMemorySearch<uint8_t>(data_file, index_file, tags_file, metric, num_threads, l_search));
+ g_inMemorySearch.push_back(std::move(searcher));
+ }
+ else
+ {
+ std::cerr << "Unsupported data type " << argv[2] << std::endl;
+ }
+
+ while (1)
+ {
+ try
+ {
+ setup(address, data_type);
+ std::cout << "Type 'exit' (case-sensitive) to exit" << std::endl;
+ std::string line;
+ std::getline(std::cin, line);
+ if (line == "exit")
+ {
+ teardown(address);
+ g_httpServer->close().wait();
+ exit(0);
+ }
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Exception occurred: " << ex.what() << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ catch (...)
+ {
+ std::cerr << "Unknown exception occurreed" << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/main.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/main.cpp
new file mode 100644
index 0000000..cb48d67
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/main.cpp
@@ -0,0 +1,83 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <restapi/server.h>
+#include <restapi/in_memory_search.h>
+#include <codecvt>
+#include <iostream>
+
+std::unique_ptr<Server> g_httpServer(nullptr);
+std::unique_ptr<diskann::InMemorySearch> g_inMemorySearch(nullptr);
+
+void setup(const utility::string_t &address)
+{
+ web::http::uri_builder uriBldr(address);
+ auto uri = uriBldr.to_uri();
+
+ std::wcout << L"Attempting to start server on " << uri.to_string() << std::endl;
+
+ g_httpServer = std::unique_ptr<Server>(new Server(uri, g_inMemorySearch));
+ g_httpServer->open().wait();
+
+ ucout << U"Listening for requests on: " << address << std::endl;
+}
+
+void teardown(const utility::string_t &address)
+{
+ g_httpServer->close().wait();
+}
+
+void loadIndex(const char *indexFile, const char *baseFile, const char *idsFile)
+{
+ auto nsgSearch = new diskann::InMemorySearch(baseFile, indexFile, idsFile, diskann::L2);
+ g_inMemorySearch = std::unique_ptr<diskann::InMemorySearch>(nsgSearch);
+}
+
+std::wstring getHostingAddress(const char *hostNameAndPort)
+{
+ wchar_t buffer[4096];
+ mbstowcs_s(nullptr, buffer, sizeof(buffer) / sizeof(buffer[0]), hostNameAndPort,
+ sizeof(buffer) / sizeof(buffer[0]));
+ return std::wstring(buffer);
+}
+
+int main(int argc, char *argv[])
+{
+ if (argc != 5)
+ {
+ std::cout << "Usage: nsg_server <ip_addr_and_port> <index_file> "
+ "<base_file> <ids_file> "
+ << std::endl;
+ exit(1);
+ }
+
+ auto address = getHostingAddress(argv[1]);
+ loadIndex(argv[2], argv[3], argv[4]);
+ while (1)
+ {
+ try
+ {
+ setup(address);
+ std::cout << "Type 'exit' (case-sensitive) to exit" << std::endl;
+ std::string line;
+ std::getline(std::cin, line);
+ if (line == "exit")
+ {
+ teardown(address);
+ exit(0);
+ }
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Exception occurred: " << ex.what() << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ catch (...)
+ {
+ std::cerr << "Unknown exception occurreed" << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/multiple_ssdindex_server.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/multiple_ssdindex_server.cpp
new file mode 100644
index 0000000..89cb06f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/multiple_ssdindex_server.cpp
@@ -0,0 +1,182 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <ctime>
+#include <functional>
+#include <iomanip>
+#include <string>
+#include <cstdlib>
+#include <codecvt>
+#include <boost/program_options.hpp>
+#include <omp.h>
+
+#include <restapi/server.h>
+
+using namespace diskann;
+namespace po = boost::program_options;
+
+std::unique_ptr<Server> g_httpServer(nullptr);
+std::vector<std::unique_ptr<diskann::BaseSearch>> g_ssdSearch;
+
+void setup(const utility::string_t &address, const std::string &typestring)
+{
+ web::http::uri_builder uriBldr(address);
+ auto uri = uriBldr.to_uri();
+
+ std::cout << "Attempting to start server on " << uri.to_string() << std::endl;
+
+ g_httpServer = std::unique_ptr<Server>(new Server(uri, g_ssdSearch, typestring));
+ std::cout << "Created a server object" << std::endl;
+
+ g_httpServer->open().wait();
+ ucout << U"Listening for requests on: " << address << std::endl;
+}
+
+void teardown(const utility::string_t &address)
+{
+ g_httpServer->close().wait();
+}
+
+int main(int argc, char *argv[])
+{
+ std::string data_type, index_prefix_paths, address, dist_fn, tags_file;
+ uint32_t num_nodes_to_cache;
+ uint32_t num_threads;
+
+ po::options_description desc{"Arguments"};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("address", po::value<std::string>(&address)->required(), "Web server address");
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("index_prefix_paths", po::value<std::string>(&index_prefix_paths)->required(),
+ "Path prefix for loading index file components");
+ desc.add_options()("num_nodes_to_cache", po::value<uint32_t>(&num_nodes_to_cache)->default_value(0),
+ "Number of nodes to cache during search");
+ desc.add_options()("num_threads,T", po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ "Number of threads used for building index (defaults to "
+ "omp_get_num_procs())");
+ desc.add_options()("dist_fn", po::value<std::string>(&dist_fn)->default_value("l2"),
+ "distance function <l2/mips>");
+ desc.add_options()("tags_file", po::value<std::string>(&tags_file)->default_value(std::string()),
+ "Tags file location");
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << std::endl;
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("l2"))
+ metric = diskann::Metric::L2;
+ else if (dist_fn == std::string("mips"))
+ metric = diskann::Metric::INNER_PRODUCT;
+ else
+ {
+ std::cout << "Error. Only l2 and mips distance functions are supported" << std::endl;
+ return -1;
+ }
+
+ std::vector<std::pair<std::string, std::string>> index_tag_paths;
+ std::ifstream index_in(index_prefix_paths);
+ if (!index_in.is_open())
+ {
+ std::cerr << "Could not open " << index_prefix_paths << std::endl;
+ exit(-1);
+ }
+ std::ifstream tags_in(tags_file);
+ if (!tags_in.is_open())
+ {
+ std::cerr << "Could not open " << tags_file << std::endl;
+ exit(-1);
+ }
+ std::string prefix, tagfile;
+ while (std::getline(index_in, prefix))
+ {
+ if (std::getline(tags_in, tagfile))
+ {
+ index_tag_paths.push_back(std::make_pair(prefix, tagfile));
+ }
+ else
+ {
+ std::cerr << "The number of tags specified does not match the number of "
+ "indices specified"
+ << std::endl;
+ exit(-1);
+ }
+ }
+ index_in.close();
+ tags_in.close();
+
+ if (data_type == std::string("float"))
+ {
+ for (auto &index_tag : index_tag_paths)
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(new diskann::PQFlashSearch<float>(
+ index_tag.first.c_str(), num_nodes_to_cache, num_threads, index_tag.second.c_str(), metric));
+ g_ssdSearch.push_back(std::move(searcher));
+ }
+ }
+ else if (data_type == std::string("int8"))
+ {
+ for (auto &index_tag : index_tag_paths)
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(new diskann::PQFlashSearch<int8_t>(
+ index_tag.first.c_str(), num_nodes_to_cache, num_threads, index_tag.second.c_str(), metric));
+ g_ssdSearch.push_back(std::move(searcher));
+ }
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ for (auto &index_tag : index_tag_paths)
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(new diskann::PQFlashSearch<uint8_t>(
+ index_tag.first.c_str(), num_nodes_to_cache, num_threads, index_tag.second.c_str(), metric));
+ g_ssdSearch.push_back(std::move(searcher));
+ }
+ }
+ else
+ {
+ std::cerr << "Unsupported data type " << data_type << std::endl;
+ exit(-1);
+ }
+
+ while (1)
+ {
+ try
+ {
+ setup(address, data_type);
+ std::cout << "Type 'exit' (case-sensitive) to exit" << std::endl;
+ std::string line;
+ std::getline(std::cin, line);
+ if (line == "exit")
+ {
+ teardown(address);
+ g_httpServer->close().wait();
+ exit(0);
+ }
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Exception occurred: " << ex.what() << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ catch (...)
+ {
+ std::cerr << "Unknown exception occurreed" << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/ssd_server.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/ssd_server.cpp
new file mode 100644
index 0000000..d179973
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/restapi/ssd_server.cpp
@@ -0,0 +1,141 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <ctime>
+#include <functional>
+#include <iomanip>
+#include <string>
+#include <cstdlib>
+#include <codecvt>
+#include <boost/program_options.hpp>
+#include <omp.h>
+
+#include <restapi/server.h>
+
+using namespace diskann;
+namespace po = boost::program_options;
+
+std::unique_ptr<Server> g_httpServer(nullptr);
+std::vector<std::unique_ptr<diskann::BaseSearch>> g_ssdSearch;
+
+void setup(const utility::string_t &address, const std::string &typestring)
+{
+ web::http::uri_builder uriBldr(address);
+ auto uri = uriBldr.to_uri();
+
+ std::cout << "Attempting to start server on " << uri.to_string() << std::endl;
+
+ g_httpServer = std::unique_ptr<Server>(new Server(uri, g_ssdSearch, typestring));
+ std::cout << "Created a server object" << std::endl;
+
+ g_httpServer->open().wait();
+ ucout << U"Listening for requests on: " << address << std::endl;
+}
+
+void teardown(const utility::string_t &address)
+{
+ g_httpServer->close().wait();
+}
+
+int main(int argc, char *argv[])
+{
+ std::string data_type, index_path_prefix, address, dist_fn, tags_file;
+ uint32_t num_nodes_to_cache;
+ uint32_t num_threads;
+
+ po::options_description desc{"Arguments"};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("address", po::value<std::string>(&address)->required(), "Web server address");
+ desc.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ "Path prefix for loading index file components");
+ desc.add_options()("num_nodes_to_cache", po::value<uint32_t>(&num_nodes_to_cache)->default_value(0),
+ "Number of nodes to cache during search");
+ desc.add_options()("num_threads,T", po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ "Number of threads used for building index (defaults to "
+ "omp_get_num_procs())");
+ desc.add_options()("dist_fn", po::value<std::string>(&dist_fn)->default_value("l2"),
+ "distance function <l2/mips>");
+ desc.add_options()("tags_file", po::value<std::string>(&tags_file)->default_value(std::string()),
+ "Tags file location");
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << std::endl;
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("l2"))
+ metric = diskann::Metric::L2;
+ else if (dist_fn == std::string("mips"))
+ metric = diskann::Metric::INNER_PRODUCT;
+ else
+ {
+ std::cout << "Error. Only l2 and mips distance functions are supported" << std::endl;
+ return -1;
+ }
+
+ if (data_type == std::string("float"))
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(
+ new diskann::PQFlashSearch<float>(index_path_prefix, num_nodes_to_cache, num_threads, tags_file, metric));
+ g_ssdSearch.push_back(std::move(searcher));
+ }
+ else if (data_type == std::string("int8"))
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(
+ new diskann::PQFlashSearch<int8_t>(index_path_prefix, num_nodes_to_cache, num_threads, tags_file, metric));
+ g_ssdSearch.push_back(std::move(searcher));
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ auto searcher = std::unique_ptr<diskann::BaseSearch>(
+ new diskann::PQFlashSearch<uint8_t>(index_path_prefix, num_nodes_to_cache, num_threads, tags_file, metric));
+ g_ssdSearch.push_back(std::move(searcher));
+ }
+ else
+ {
+ std::cerr << "Unsupported data type " << argv[2] << std::endl;
+ exit(-1);
+ }
+
+ while (1)
+ {
+ try
+ {
+ setup(address, data_type);
+ std::cout << "Type 'exit' (case-sensitive) to exit" << std::endl;
+ std::string line;
+ std::getline(std::cin, line);
+ if (line == "exit")
+ {
+ teardown(address);
+ g_httpServer->close().wait();
+ exit(0);
+ }
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Exception occurred: " << ex.what() << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ catch (...)
+ {
+ std::cerr << "Unknown exception occurreed" << std::endl;
+ std::cerr << "Restarting HTTP server";
+ teardown(address);
+ }
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/search_disk_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/search_disk_index.cpp
new file mode 100644
index 0000000..6b0793d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/search_disk_index.cpp
@@ -0,0 +1,499 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "common_includes.h"
+#include <boost/program_options.hpp>
+
+#include "index.h"
+#include "disk_utils.h"
+#include "math_utils.h"
+#include "memory_mapper.h"
+#include "partition.h"
+#include "pq_flash_index.h"
+#include "timer.h"
+#include "percentile_stats.h"
+#include "program_options_utils.hpp"
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include "linux_aligned_file_reader.h"
+#else
+#ifdef USE_BING_INFRA
+#include "bing_aligned_file_reader.h"
+#else
+#include "windows_aligned_file_reader.h"
+#endif
+#endif
+
+#define WARMUP false
+
+namespace po = boost::program_options;
+
+void print_stats(std::string category, std::vector<float> percentiles, std::vector<float> results)
+{
+ diskann::cout << std::setw(20) << category << ": " << std::flush;
+ for (uint32_t s = 0; s < percentiles.size(); s++)
+ {
+ diskann::cout << std::setw(8) << percentiles[s] << "%";
+ }
+ diskann::cout << std::endl;
+ diskann::cout << std::setw(22) << " " << std::flush;
+ for (uint32_t s = 0; s < percentiles.size(); s++)
+ {
+ diskann::cout << std::setw(9) << results[s];
+ }
+ diskann::cout << std::endl;
+}
+
+template <typename T, typename LabelT = uint32_t>
+int search_disk_index(diskann::Metric &metric, const std::string &index_path_prefix,
+ const std::string &result_output_prefix, const std::string &query_file, std::string &gt_file,
+ const uint32_t num_threads, const uint32_t recall_at, const uint32_t beamwidth,
+ const uint32_t num_nodes_to_cache, const uint32_t search_io_limit,
+ const std::vector<uint32_t> &Lvec, const float fail_if_recall_below,
+ const std::vector<std::string> &query_filters, const bool use_reorder_data = false)
+{
+ diskann::cout << "Search parameters: #threads: " << num_threads << ", ";
+ if (beamwidth <= 0)
+ diskann::cout << "beamwidth to be optimized for each L value" << std::flush;
+ else
+ diskann::cout << " beamwidth: " << beamwidth << std::flush;
+ if (search_io_limit == std::numeric_limits<uint32_t>::max())
+ diskann::cout << "." << std::endl;
+ else
+ diskann::cout << ", io_limit: " << search_io_limit << "." << std::endl;
+
+ std::string warmup_query_file = index_path_prefix + "_sample_data.bin";
+
+ // load query bin
+ T *query = nullptr;
+ uint32_t *gt_ids = nullptr;
+ float *gt_dists = nullptr;
+ size_t query_num, query_dim, query_aligned_dim, gt_num, gt_dim;
+ diskann::load_aligned_bin<T>(query_file, query, query_num, query_dim, query_aligned_dim);
+
+ bool filtered_search = false;
+ if (!query_filters.empty())
+ {
+ filtered_search = true;
+ if (query_filters.size() != 1 && query_filters.size() != query_num)
+ {
+ std::cout << "Error. Mismatch in number of queries and size of query "
+ "filters file"
+ << std::endl;
+ return -1; // To return -1 or some other error handling?
+ }
+ }
+
+ bool calc_recall_flag = false;
+ if (gt_file != std::string("null") && gt_file != std::string("NULL") && file_exists(gt_file))
+ {
+ diskann::load_truthset(gt_file, gt_ids, gt_dists, gt_num, gt_dim);
+ if (gt_num != query_num)
+ {
+ diskann::cout << "Error. Mismatch in number of queries and ground truth data" << std::endl;
+ }
+ calc_recall_flag = true;
+ }
+
+ std::shared_ptr<AlignedFileReader> reader = nullptr;
+#ifdef _WINDOWS
+#ifndef USE_BING_INFRA
+ reader.reset(new WindowsAlignedFileReader());
+#else
+ reader.reset(new diskann::BingAlignedFileReader());
+#endif
+#else
+ reader.reset(new LinuxAlignedFileReader());
+#endif
+
+ std::unique_ptr<diskann::PQFlashIndex<T, LabelT>> _pFlashIndex(
+ new diskann::PQFlashIndex<T, LabelT>(reader, metric));
+
+ int res = _pFlashIndex->load(num_threads, index_path_prefix.c_str());
+
+ if (res != 0)
+ {
+ return res;
+ }
+
+ std::vector<uint32_t> node_list;
+ diskann::cout << "Caching " << num_nodes_to_cache << " nodes around medoid(s)" << std::endl;
+ _pFlashIndex->cache_bfs_levels(num_nodes_to_cache, node_list);
+ // if (num_nodes_to_cache > 0)
+ // _pFlashIndex->generate_cache_list_from_sample_queries(warmup_query_file, 15, 6, num_nodes_to_cache,
+ // num_threads, node_list);
+ _pFlashIndex->load_cache_list(node_list);
+ node_list.clear();
+ node_list.shrink_to_fit();
+
+ omp_set_num_threads(num_threads);
+
+ uint64_t warmup_L = 20;
+ uint64_t warmup_num = 0, warmup_dim = 0, warmup_aligned_dim = 0;
+ T *warmup = nullptr;
+
+ if (WARMUP)
+ {
+ if (file_exists(warmup_query_file))
+ {
+ diskann::load_aligned_bin<T>(warmup_query_file, warmup, warmup_num, warmup_dim, warmup_aligned_dim);
+ }
+ else
+ {
+ warmup_num = (std::min)((uint32_t)150000, (uint32_t)15000 * num_threads);
+ warmup_dim = query_dim;
+ warmup_aligned_dim = query_aligned_dim;
+ diskann::alloc_aligned(((void **)&warmup), warmup_num * warmup_aligned_dim * sizeof(T), 8 * sizeof(T));
+ std::memset(warmup, 0, warmup_num * warmup_aligned_dim * sizeof(T));
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<> dis(-128, 127);
+ for (uint32_t i = 0; i < warmup_num; i++)
+ {
+ for (uint32_t d = 0; d < warmup_dim; d++)
+ {
+ warmup[i * warmup_aligned_dim + d] = (T)dis(gen);
+ }
+ }
+ }
+ diskann::cout << "Warming up index... " << std::flush;
+ std::vector<uint64_t> warmup_result_ids_64(warmup_num, 0);
+ std::vector<float> warmup_result_dists(warmup_num, 0);
+
+#pragma omp parallel for schedule(dynamic, 1)
+ for (int64_t i = 0; i < (int64_t)warmup_num; i++)
+ {
+ _pFlashIndex->cached_beam_search(warmup + (i * warmup_aligned_dim), 1, warmup_L,
+ warmup_result_ids_64.data() + (i * 1),
+ warmup_result_dists.data() + (i * 1), 4);
+ }
+ diskann::cout << "..done" << std::endl;
+ }
+
+ diskann::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
+ diskann::cout.precision(2);
+
+ std::string recall_string = "Recall@" + std::to_string(recall_at);
+ diskann::cout << std::setw(6) << "L" << std::setw(12) << "Beamwidth" << std::setw(16) << "QPS" << std::setw(16)
+ << "Mean Latency" << std::setw(16) << "99.9 Latency" << std::setw(16) << "Mean IOs" << std::setw(16)
+ << "Mean IO (us)" << std::setw(16) << "CPU (s)";
+ if (calc_recall_flag)
+ {
+ diskann::cout << std::setw(16) << recall_string << std::endl;
+ }
+ else
+ diskann::cout << std::endl;
+ diskann::cout << "=================================================================="
+ "================================================================="
+ << std::endl;
+
+ std::vector<std::vector<uint32_t>> query_result_ids(Lvec.size());
+ std::vector<std::vector<float>> query_result_dists(Lvec.size());
+
+ uint32_t optimized_beamwidth = 2;
+
+ double best_recall = 0.0;
+
+ for (uint32_t test_id = 0; test_id < Lvec.size(); test_id++)
+ {
+ uint32_t L = Lvec[test_id];
+
+ if (L < recall_at)
+ {
+ diskann::cout << "Ignoring search with L:" << L << " since it's smaller than K:" << recall_at << std::endl;
+ continue;
+ }
+
+ if (beamwidth <= 0)
+ {
+ diskann::cout << "Tuning beamwidth.." << std::endl;
+ optimized_beamwidth =
+ optimize_beamwidth(_pFlashIndex, warmup, warmup_num, warmup_aligned_dim, L, optimized_beamwidth);
+ }
+ else
+ optimized_beamwidth = beamwidth;
+
+ query_result_ids[test_id].resize(recall_at * query_num);
+ query_result_dists[test_id].resize(recall_at * query_num);
+
+ auto stats = new diskann::QueryStats[query_num];
+
+ std::vector<uint64_t> query_result_ids_64(recall_at * query_num);
+ auto s = std::chrono::high_resolution_clock::now();
+
+#pragma omp parallel for schedule(dynamic, 1)
+ for (int64_t i = 0; i < (int64_t)query_num; i++)
+ {
+ if (!filtered_search)
+ {
+ _pFlashIndex->cached_beam_search(query + (i * query_aligned_dim), recall_at, L,
+ query_result_ids_64.data() + (i * recall_at),
+ query_result_dists[test_id].data() + (i * recall_at),
+ optimized_beamwidth, use_reorder_data, stats + i);
+ }
+ else
+ {
+ LabelT label_for_search;
+ if (query_filters.size() == 1)
+ { // one label for all queries
+ label_for_search = _pFlashIndex->get_converted_label(query_filters[0]);
+ }
+ else
+ { // one label for each query
+ label_for_search = _pFlashIndex->get_converted_label(query_filters[i]);
+ }
+ _pFlashIndex->cached_beam_search(
+ query + (i * query_aligned_dim), recall_at, L, query_result_ids_64.data() + (i * recall_at),
+ query_result_dists[test_id].data() + (i * recall_at), optimized_beamwidth, true, label_for_search,
+ use_reorder_data, stats + i);
+ }
+ }
+ auto e = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diff = e - s;
+ double qps = (1.0 * query_num) / (1.0 * diff.count());
+
+ diskann::convert_types<uint64_t, uint32_t>(query_result_ids_64.data(), query_result_ids[test_id].data(),
+ query_num, recall_at);
+
+ auto mean_latency = diskann::get_mean_stats<float>(
+ stats, query_num, [](const diskann::QueryStats &stats) { return stats.total_us; });
+
+ auto latency_999 = diskann::get_percentile_stats<float>(
+ stats, query_num, 0.999, [](const diskann::QueryStats &stats) { return stats.total_us; });
+
+ auto mean_ios = diskann::get_mean_stats<uint32_t>(stats, query_num,
+ [](const diskann::QueryStats &stats) { return stats.n_ios; });
+
+ auto mean_cpuus = diskann::get_mean_stats<float>(stats, query_num,
+ [](const diskann::QueryStats &stats) { return stats.cpu_us; });
+
+ auto mean_io_us = diskann::get_mean_stats<float>(stats, query_num,
+ [](const diskann::QueryStats &stats) { return stats.io_us; });
+
+ double recall = 0;
+ if (calc_recall_flag)
+ {
+ recall = diskann::calculate_recall((uint32_t)query_num, gt_ids, gt_dists, (uint32_t)gt_dim,
+ query_result_ids[test_id].data(), recall_at, recall_at);
+ best_recall = std::max(recall, best_recall);
+ }
+
+ diskann::cout << std::setw(6) << L << std::setw(12) << optimized_beamwidth << std::setw(16) << qps
+ << std::setw(16) << mean_latency << std::setw(16) << latency_999 << std::setw(16) << mean_ios
+ << std::setw(16) << mean_io_us << std::setw(16) << mean_cpuus;
+ if (calc_recall_flag)
+ {
+ diskann::cout << std::setw(16) << recall << std::endl;
+ }
+ else
+ diskann::cout << std::endl;
+ delete[] stats;
+ }
+
+ diskann::cout << "Done searching. Now saving results " << std::endl;
+ uint64_t test_id = 0;
+ for (auto L : Lvec)
+ {
+ if (L < recall_at)
+ continue;
+
+ std::string cur_result_path = result_output_prefix + "_" + std::to_string(L) + "_idx_uint32.bin";
+ diskann::save_bin<uint32_t>(cur_result_path, query_result_ids[test_id].data(), query_num, recall_at);
+
+ cur_result_path = result_output_prefix + "_" + std::to_string(L) + "_dists_float.bin";
+ diskann::save_bin<float>(cur_result_path, query_result_dists[test_id++].data(), query_num, recall_at);
+ }
+
+ diskann::aligned_free(query);
+ if (warmup != nullptr)
+ diskann::aligned_free(warmup);
+ return best_recall >= fail_if_recall_below ? 0 : -1;
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, index_path_prefix, result_path_prefix, query_file, gt_file, filter_label,
+ label_type, query_filters_file;
+ uint32_t num_threads, K, W, num_nodes_to_cache, search_io_limit;
+ std::vector<uint32_t> Lvec;
+ bool use_reorder_data = false;
+ float fail_if_recall_below = 0.0f;
+
+ po::options_description desc{
+ program_options_utils::make_program_description("search_disk_index", "Searches on-disk DiskANN indexes")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("result_path", po::value<std::string>(&result_path_prefix)->required(),
+ program_options_utils::RESULT_PATH_DESCRIPTION);
+ required_configs.add_options()("query_file", po::value<std::string>(&query_file)->required(),
+ program_options_utils::QUERY_FILE_DESCRIPTION);
+ required_configs.add_options()("recall_at,K", po::value<uint32_t>(&K)->required(),
+ program_options_utils::NUMBER_OF_RESULTS_DESCRIPTION);
+ required_configs.add_options()("search_list,L",
+ po::value<std::vector<uint32_t>>(&Lvec)->multitoken()->required(),
+ program_options_utils::SEARCH_LIST_DESCRIPTION);
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("gt_file", po::value<std::string>(&gt_file)->default_value(std::string("null")),
+ program_options_utils::GROUND_TRUTH_FILE_DESCRIPTION);
+ optional_configs.add_options()("beamwidth,W", po::value<uint32_t>(&W)->default_value(2),
+ program_options_utils::BEAMWIDTH);
+ optional_configs.add_options()("num_nodes_to_cache", po::value<uint32_t>(&num_nodes_to_cache)->default_value(0),
+ program_options_utils::NUMBER_OF_NODES_TO_CACHE);
+ optional_configs.add_options()(
+ "search_io_limit",
+ po::value<uint32_t>(&search_io_limit)->default_value(std::numeric_limits<uint32_t>::max()),
+ "Max #IOs for search. Default value: uint32::max()");
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()("use_reorder_data", po::bool_switch()->default_value(false),
+ "Include full precision data in the index. Use only in "
+ "conjuction with compressed data on SSD. Default value: false");
+ optional_configs.add_options()("filter_label",
+ po::value<std::string>(&filter_label)->default_value(std::string("")),
+ program_options_utils::FILTER_LABEL_DESCRIPTION);
+ optional_configs.add_options()("query_filters_file",
+ po::value<std::string>(&query_filters_file)->default_value(std::string("")),
+ program_options_utils::FILTERS_FILE_DESCRIPTION);
+ optional_configs.add_options()("label_type", po::value<std::string>(&label_type)->default_value("uint"),
+ program_options_utils::LABEL_TYPE_DESCRIPTION);
+ optional_configs.add_options()("fail_if_recall_below",
+ po::value<float>(&fail_if_recall_below)->default_value(0.0f),
+ program_options_utils::FAIL_IF_RECALL_BELOW);
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ if (vm["use_reorder_data"].as<bool>())
+ use_reorder_data = true;
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("mips"))
+ {
+ metric = diskann::Metric::INNER_PRODUCT;
+ }
+ else if (dist_fn == std::string("l2"))
+ {
+ metric = diskann::Metric::L2;
+ }
+ else if (dist_fn == std::string("cosine"))
+ {
+ metric = diskann::Metric::COSINE;
+ }
+ else
+ {
+ std::cout << "Unsupported distance function. Currently only L2/ Inner "
+ "Product/Cosine are supported."
+ << std::endl;
+ return -1;
+ }
+
+ if ((data_type != std::string("float")) && (metric == diskann::Metric::INNER_PRODUCT))
+ {
+ std::cout << "Currently support only floating point data for Inner Product." << std::endl;
+ return -1;
+ }
+
+ if (use_reorder_data && data_type != std::string("float"))
+ {
+ std::cout << "Error: Reorder data for reordering currently only "
+ "supported for float data type."
+ << std::endl;
+ return -1;
+ }
+
+ if (filter_label != "" && query_filters_file != "")
+ {
+ std::cerr << "Only one of filter_label and query_filters_file should be provided" << std::endl;
+ return -1;
+ }
+
+ std::vector<std::string> query_filters;
+ if (filter_label != "")
+ {
+ query_filters.push_back(filter_label);
+ }
+ else if (query_filters_file != "")
+ {
+ query_filters = read_file_to_vector_of_strings(query_filters_file);
+ }
+
+ try
+ {
+ if (!query_filters.empty() && label_type == "ushort")
+ {
+ if (data_type == std::string("float"))
+ return search_disk_index<float, uint16_t>(
+ metric, index_path_prefix, result_path_prefix, query_file, gt_file, num_threads, K, W,
+ num_nodes_to_cache, search_io_limit, Lvec, fail_if_recall_below, query_filters, use_reorder_data);
+ else if (data_type == std::string("int8"))
+ return search_disk_index<int8_t, uint16_t>(
+ metric, index_path_prefix, result_path_prefix, query_file, gt_file, num_threads, K, W,
+ num_nodes_to_cache, search_io_limit, Lvec, fail_if_recall_below, query_filters, use_reorder_data);
+ else if (data_type == std::string("uint8"))
+ return search_disk_index<uint8_t, uint16_t>(
+ metric, index_path_prefix, result_path_prefix, query_file, gt_file, num_threads, K, W,
+ num_nodes_to_cache, search_io_limit, Lvec, fail_if_recall_below, query_filters, use_reorder_data);
+ else
+ {
+ std::cerr << "Unsupported data type. Use float or int8 or uint8" << std::endl;
+ return -1;
+ }
+ }
+ else
+ {
+ if (data_type == std::string("float"))
+ return search_disk_index<float>(metric, index_path_prefix, result_path_prefix, query_file, gt_file,
+ num_threads, K, W, num_nodes_to_cache, search_io_limit, Lvec,
+ fail_if_recall_below, query_filters, use_reorder_data);
+ else if (data_type == std::string("int8"))
+ return search_disk_index<int8_t>(metric, index_path_prefix, result_path_prefix, query_file, gt_file,
+ num_threads, K, W, num_nodes_to_cache, search_io_limit, Lvec,
+ fail_if_recall_below, query_filters, use_reorder_data);
+ else if (data_type == std::string("uint8"))
+ return search_disk_index<uint8_t>(metric, index_path_prefix, result_path_prefix, query_file, gt_file,
+ num_threads, K, W, num_nodes_to_cache, search_io_limit, Lvec,
+ fail_if_recall_below, query_filters, use_reorder_data);
+ else
+ {
+ std::cerr << "Unsupported data type. Use float or int8 or uint8" << std::endl;
+ return -1;
+ }
+ }
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index search failed." << std::endl;
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/search_memory_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/search_memory_index.cpp
new file mode 100644
index 0000000..1a9acc2
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/search_memory_index.cpp
@@ -0,0 +1,477 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <cstring>
+#include <iomanip>
+#include <algorithm>
+#include <numeric>
+#include <omp.h>
+#include <set>
+#include <string.h>
+#include <boost/program_options.hpp>
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+#endif
+
+#include "index.h"
+#include "memory_mapper.h"
+#include "utils.h"
+#include "program_options_utils.hpp"
+#include "index_factory.h"
+
+namespace po = boost::program_options;
+
+template <typename T, typename LabelT = uint32_t>
+int search_memory_index(diskann::Metric &metric, const std::string &index_path, const std::string &result_path_prefix,
+ const std::string &query_file, const std::string &truthset_file, const uint32_t num_threads,
+ const uint32_t recall_at, const bool print_all_recalls, const std::vector<uint32_t> &Lvec,
+ const bool dynamic, const bool tags, const bool show_qps_per_thread,
+ const std::vector<std::string> &query_filters, const float fail_if_recall_below)
+{
+ using TagT = uint32_t;
+ // Load the query file
+ T *query = nullptr;
+ uint32_t *gt_ids = nullptr;
+ float *gt_dists = nullptr;
+ size_t query_num, query_dim, query_aligned_dim, gt_num, gt_dim;
+ diskann::load_aligned_bin<T>(query_file, query, query_num, query_dim, query_aligned_dim);
+
+ bool calc_recall_flag = false;
+ if (truthset_file != std::string("null") && file_exists(truthset_file))
+ {
+ diskann::load_truthset(truthset_file, gt_ids, gt_dists, gt_num, gt_dim);
+ if (gt_num != query_num)
+ {
+ std::cout << "Error. Mismatch in number of queries and ground truth data" << std::endl;
+ }
+ calc_recall_flag = true;
+ }
+ else
+ {
+ diskann::cout << " Truthset file " << truthset_file << " not found. Not computing recall." << std::endl;
+ }
+
+ bool filtered_search = false;
+ if (!query_filters.empty())
+ {
+ filtered_search = true;
+ if (query_filters.size() != 1 && query_filters.size() != query_num)
+ {
+ std::cout << "Error. Mismatch in number of queries and size of query "
+ "filters file"
+ << std::endl;
+ return -1; // To return -1 or some other error handling?
+ }
+ }
+
+ const size_t num_frozen_pts = diskann::get_graph_num_frozen_points(index_path);
+
+ auto config = diskann::IndexConfigBuilder()
+ .with_metric(metric)
+ .with_dimension(query_dim)
+ .with_max_points(0)
+ .with_data_load_store_strategy(diskann::DataStoreStrategy::MEMORY)
+ .with_graph_load_store_strategy(diskann::GraphStoreStrategy::MEMORY)
+ .with_data_type(diskann_type_to_name<T>())
+ .with_label_type(diskann_type_to_name<LabelT>())
+ .with_tag_type(diskann_type_to_name<TagT>())
+ .is_dynamic_index(dynamic)
+ .is_enable_tags(tags)
+ .is_concurrent_consolidate(false)
+ .is_pq_dist_build(false)
+ .is_use_opq(false)
+ .with_num_pq_chunks(0)
+ .with_num_frozen_pts(num_frozen_pts)
+ .build();
+
+ auto index_factory = diskann::IndexFactory(config);
+ auto index = index_factory.create_instance();
+ index->load(index_path.c_str(), num_threads, *(std::max_element(Lvec.begin(), Lvec.end())));
+ std::cout << "Index loaded" << std::endl;
+
+ if (metric == diskann::FAST_L2)
+ index->optimize_index_layout();
+
+ std::cout << "Using " << num_threads << " threads to search" << std::endl;
+ std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
+ std::cout.precision(2);
+ const std::string qps_title = show_qps_per_thread ? "QPS/thread" : "QPS";
+ uint32_t table_width = 0;
+ if (tags)
+ {
+ std::cout << std::setw(4) << "Ls" << std::setw(12) << qps_title << std::setw(20) << "Mean Latency (mus)"
+ << std::setw(15) << "99.9 Latency";
+ table_width += 4 + 12 + 20 + 15;
+ }
+ else
+ {
+ std::cout << std::setw(4) << "Ls" << std::setw(12) << qps_title << std::setw(18) << "Avg dist cmps"
+ << std::setw(20) << "Mean Latency (mus)" << std::setw(15) << "99.9 Latency";
+ table_width += 4 + 12 + 18 + 20 + 15;
+ }
+ uint32_t recalls_to_print = 0;
+ const uint32_t first_recall = print_all_recalls ? 1 : recall_at;
+ if (calc_recall_flag)
+ {
+ for (uint32_t curr_recall = first_recall; curr_recall <= recall_at; curr_recall++)
+ {
+ std::cout << std::setw(12) << ("Recall@" + std::to_string(curr_recall));
+ }
+ recalls_to_print = recall_at + 1 - first_recall;
+ table_width += recalls_to_print * 12;
+ }
+ std::cout << std::endl;
+ std::cout << std::string(table_width, '=') << std::endl;
+
+ std::vector<std::vector<uint32_t>> query_result_ids(Lvec.size());
+ std::vector<std::vector<float>> query_result_dists(Lvec.size());
+ std::vector<float> latency_stats(query_num, 0);
+ std::vector<uint32_t> cmp_stats;
+ if (not tags || filtered_search)
+ {
+ cmp_stats = std::vector<uint32_t>(query_num, 0);
+ }
+
+ std::vector<TagT> query_result_tags;
+ if (tags)
+ {
+ query_result_tags.resize(recall_at * query_num);
+ }
+
+ double best_recall = 0.0;
+
+ for (uint32_t test_id = 0; test_id < Lvec.size(); test_id++)
+ {
+ uint32_t L = Lvec[test_id];
+ if (L < recall_at)
+ {
+ diskann::cout << "Ignoring search with L:" << L << " since it's smaller than K:" << recall_at << std::endl;
+ continue;
+ }
+
+ query_result_ids[test_id].resize(recall_at * query_num);
+ query_result_dists[test_id].resize(recall_at * query_num);
+ std::vector<T *> res = std::vector<T *>();
+
+ auto s = std::chrono::high_resolution_clock::now();
+ omp_set_num_threads(num_threads);
+#pragma omp parallel for schedule(dynamic, 1)
+ for (int64_t i = 0; i < (int64_t)query_num; i++)
+ {
+ auto qs = std::chrono::high_resolution_clock::now();
+ if (filtered_search && !tags)
+ {
+ std::string raw_filter = query_filters.size() == 1 ? query_filters[0] : query_filters[i];
+
+ auto retval = index->search_with_filters(query + i * query_aligned_dim, raw_filter, recall_at, L,
+ query_result_ids[test_id].data() + i * recall_at,
+ query_result_dists[test_id].data() + i * recall_at);
+ cmp_stats[i] = retval.second;
+ }
+ else if (metric == diskann::FAST_L2)
+ {
+ index->search_with_optimized_layout(query + i * query_aligned_dim, recall_at, L,
+ query_result_ids[test_id].data() + i * recall_at);
+ }
+ else if (tags)
+ {
+ if (!filtered_search)
+ {
+ index->search_with_tags(query + i * query_aligned_dim, recall_at, L,
+ query_result_tags.data() + i * recall_at, nullptr, res);
+ }
+ else
+ {
+ std::string raw_filter = query_filters.size() == 1 ? query_filters[0] : query_filters[i];
+
+ index->search_with_tags(query + i * query_aligned_dim, recall_at, L,
+ query_result_tags.data() + i * recall_at, nullptr, res, true, raw_filter);
+ }
+
+ for (int64_t r = 0; r < (int64_t)recall_at; r++)
+ {
+ query_result_ids[test_id][recall_at * i + r] = query_result_tags[recall_at * i + r];
+ }
+ }
+ else
+ {
+ cmp_stats[i] = index
+ ->search(query + i * query_aligned_dim, recall_at, L,
+ query_result_ids[test_id].data() + i * recall_at)
+ .second;
+ }
+ auto qe = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diff = qe - qs;
+ latency_stats[i] = (float)(diff.count() * 1000000);
+ }
+ std::chrono::duration<double> diff = std::chrono::high_resolution_clock::now() - s;
+
+ double displayed_qps = query_num / diff.count();
+
+ if (show_qps_per_thread)
+ displayed_qps /= num_threads;
+
+ std::vector<double> recalls;
+ if (calc_recall_flag)
+ {
+ recalls.reserve(recalls_to_print);
+ for (uint32_t curr_recall = first_recall; curr_recall <= recall_at; curr_recall++)
+ {
+ recalls.push_back(diskann::calculate_recall((uint32_t)query_num, gt_ids, gt_dists, (uint32_t)gt_dim,
+ query_result_ids[test_id].data(), recall_at, curr_recall));
+ }
+ }
+
+ std::sort(latency_stats.begin(), latency_stats.end());
+ double mean_latency =
+ std::accumulate(latency_stats.begin(), latency_stats.end(), 0.0) / static_cast<float>(query_num);
+
+ float avg_cmps = (float)std::accumulate(cmp_stats.begin(), cmp_stats.end(), 0) / (float)query_num;
+
+ if (tags && !filtered_search)
+ {
+ std::cout << std::setw(4) << L << std::setw(12) << displayed_qps << std::setw(20) << (float)mean_latency
+ << std::setw(15) << (float)latency_stats[(uint64_t)(0.999 * query_num)];
+ }
+ else
+ {
+ std::cout << std::setw(4) << L << std::setw(12) << displayed_qps << std::setw(18) << avg_cmps
+ << std::setw(20) << (float)mean_latency << std::setw(15)
+ << (float)latency_stats[(uint64_t)(0.999 * query_num)];
+ }
+ for (double recall : recalls)
+ {
+ std::cout << std::setw(12) << recall;
+ best_recall = std::max(recall, best_recall);
+ }
+ std::cout << std::endl;
+ }
+
+ std::cout << "Done searching. Now saving results " << std::endl;
+ uint64_t test_id = 0;
+ for (auto L : Lvec)
+ {
+ if (L < recall_at)
+ {
+ diskann::cout << "Ignoring search with L:" << L << " since it's smaller than K:" << recall_at << std::endl;
+ continue;
+ }
+ std::string cur_result_path_prefix = result_path_prefix + "_" + std::to_string(L);
+
+ std::string cur_result_path = cur_result_path_prefix + "_idx_uint32.bin";
+ diskann::save_bin<uint32_t>(cur_result_path, query_result_ids[test_id].data(), query_num, recall_at);
+
+ cur_result_path = cur_result_path_prefix + "_dists_float.bin";
+ diskann::save_bin<float>(cur_result_path, query_result_dists[test_id].data(), query_num, recall_at);
+
+ test_id++;
+ }
+
+ diskann::aligned_free(query);
+ return best_recall >= fail_if_recall_below ? 0 : -1;
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, index_path_prefix, result_path, query_file, gt_file, filter_label, label_type,
+ query_filters_file;
+ uint32_t num_threads, K;
+ std::vector<uint32_t> Lvec;
+ bool print_all_recalls, dynamic, tags, show_qps_per_thread;
+ float fail_if_recall_below = 0.0f;
+
+ po::options_description desc{
+ program_options_utils::make_program_description("search_memory_index", "Searches in-memory DiskANN indexes")};
+ try
+ {
+ desc.add_options()("help,h", "Print this information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("result_path", po::value<std::string>(&result_path)->required(),
+ program_options_utils::RESULT_PATH_DESCRIPTION);
+ required_configs.add_options()("query_file", po::value<std::string>(&query_file)->required(),
+ program_options_utils::QUERY_FILE_DESCRIPTION);
+ required_configs.add_options()("recall_at,K", po::value<uint32_t>(&K)->required(),
+ program_options_utils::NUMBER_OF_RESULTS_DESCRIPTION);
+ required_configs.add_options()("search_list,L",
+ po::value<std::vector<uint32_t>>(&Lvec)->multitoken()->required(),
+ program_options_utils::SEARCH_LIST_DESCRIPTION);
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("filter_label",
+ po::value<std::string>(&filter_label)->default_value(std::string("")),
+ program_options_utils::FILTER_LABEL_DESCRIPTION);
+ optional_configs.add_options()("query_filters_file",
+ po::value<std::string>(&query_filters_file)->default_value(std::string("")),
+ program_options_utils::FILTERS_FILE_DESCRIPTION);
+ optional_configs.add_options()("label_type", po::value<std::string>(&label_type)->default_value("uint"),
+ program_options_utils::LABEL_TYPE_DESCRIPTION);
+ optional_configs.add_options()("gt_file", po::value<std::string>(&gt_file)->default_value(std::string("null")),
+ program_options_utils::GROUND_TRUTH_FILE_DESCRIPTION);
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()(
+ "dynamic", po::value<bool>(&dynamic)->default_value(false),
+ "Whether the index is dynamic. Dynamic indices must have associated tags. Default false.");
+ optional_configs.add_options()("tags", po::value<bool>(&tags)->default_value(false),
+ "Whether to search with external identifiers (tags). Default false.");
+ optional_configs.add_options()("fail_if_recall_below",
+ po::value<float>(&fail_if_recall_below)->default_value(0.0f),
+ program_options_utils::FAIL_IF_RECALL_BELOW);
+
+ // Output controls
+ po::options_description output_controls("Output controls");
+ output_controls.add_options()("print_all_recalls", po::bool_switch(&print_all_recalls),
+ "Print recalls at all positions, from 1 up to specified "
+ "recall_at value");
+ output_controls.add_options()("print_qps_per_thread", po::bool_switch(&show_qps_per_thread),
+ "Print overall QPS divided by the number of threads in "
+ "the output table");
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs).add(output_controls);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if ((dist_fn == std::string("mips")) && (data_type == std::string("float")))
+ {
+ metric = diskann::Metric::INNER_PRODUCT;
+ }
+ else if (dist_fn == std::string("l2"))
+ {
+ metric = diskann::Metric::L2;
+ }
+ else if (dist_fn == std::string("cosine"))
+ {
+ metric = diskann::Metric::COSINE;
+ }
+ else if ((dist_fn == std::string("fast_l2")) && (data_type == std::string("float")))
+ {
+ metric = diskann::Metric::FAST_L2;
+ }
+ else
+ {
+ std::cout << "Unsupported distance function. Currently only l2/ cosine are "
+ "supported in general, and mips/fast_l2 only for floating "
+ "point data."
+ << std::endl;
+ return -1;
+ }
+
+ if (dynamic && not tags)
+ {
+ std::cerr << "Tags must be enabled while searching dynamically built indices" << std::endl;
+ return -1;
+ }
+
+ if (fail_if_recall_below < 0.0 || fail_if_recall_below >= 100.0)
+ {
+ std::cerr << "fail_if_recall_below parameter must be between 0 and 100%" << std::endl;
+ return -1;
+ }
+
+ if (filter_label != "" && query_filters_file != "")
+ {
+ std::cerr << "Only one of filter_label and query_filters_file should be provided" << std::endl;
+ return -1;
+ }
+
+ std::vector<std::string> query_filters;
+ if (filter_label != "")
+ {
+ query_filters.push_back(filter_label);
+ }
+ else if (query_filters_file != "")
+ {
+ query_filters = read_file_to_vector_of_strings(query_filters_file);
+ }
+
+ try
+ {
+ if (!query_filters.empty() && label_type == "ushort")
+ {
+ if (data_type == std::string("int8"))
+ {
+ return search_memory_index<int8_t, uint16_t>(
+ metric, index_path_prefix, result_path, query_file, gt_file, num_threads, K, print_all_recalls,
+ Lvec, dynamic, tags, show_qps_per_thread, query_filters, fail_if_recall_below);
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ return search_memory_index<uint8_t, uint16_t>(
+ metric, index_path_prefix, result_path, query_file, gt_file, num_threads, K, print_all_recalls,
+ Lvec, dynamic, tags, show_qps_per_thread, query_filters, fail_if_recall_below);
+ }
+ else if (data_type == std::string("float"))
+ {
+ return search_memory_index<float, uint16_t>(metric, index_path_prefix, result_path, query_file, gt_file,
+ num_threads, K, print_all_recalls, Lvec, dynamic, tags,
+ show_qps_per_thread, query_filters, fail_if_recall_below);
+ }
+ else
+ {
+ std::cout << "Unsupported type. Use float/int8/uint8" << std::endl;
+ return -1;
+ }
+ }
+ else
+ {
+ if (data_type == std::string("int8"))
+ {
+ return search_memory_index<int8_t>(metric, index_path_prefix, result_path, query_file, gt_file,
+ num_threads, K, print_all_recalls, Lvec, dynamic, tags,
+ show_qps_per_thread, query_filters, fail_if_recall_below);
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ return search_memory_index<uint8_t>(metric, index_path_prefix, result_path, query_file, gt_file,
+ num_threads, K, print_all_recalls, Lvec, dynamic, tags,
+ show_qps_per_thread, query_filters, fail_if_recall_below);
+ }
+ else if (data_type == std::string("float"))
+ {
+ return search_memory_index<float>(metric, index_path_prefix, result_path, query_file, gt_file,
+ num_threads, K, print_all_recalls, Lvec, dynamic, tags,
+ show_qps_per_thread, query_filters, fail_if_recall_below);
+ }
+ else
+ {
+ std::cout << "Unsupported type. Use float/int8/uint8" << std::endl;
+ return -1;
+ }
+ }
+ }
+ catch (std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index search failed." << std::endl;
+ return -1;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/test_insert_deletes_consolidate.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/test_insert_deletes_consolidate.cpp
new file mode 100644
index 0000000..97aed18
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/test_insert_deletes_consolidate.cpp
@@ -0,0 +1,536 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <index.h>
+#include <numeric>
+#include <omp.h>
+#include <string.h>
+#include <time.h>
+#include <timer.h>
+#include <boost/program_options.hpp>
+#include <future>
+
+#include "utils.h"
+#include "filter_utils.h"
+#include "program_options_utils.hpp"
+#include "index_factory.h"
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+
+#include "memory_mapper.h"
+
+namespace po = boost::program_options;
+
+// load_aligned_bin modified to read pieces of the file, but using ifstream
+// instead of cached_ifstream.
+template <typename T>
+inline void load_aligned_bin_part(const std::string &bin_file, T *data, size_t offset_points, size_t points_to_read)
+{
+ diskann::Timer timer;
+ std::ifstream reader;
+ reader.exceptions(std::ios::failbit | std::ios::badbit);
+ reader.open(bin_file, std::ios::binary | std::ios::ate);
+ size_t actual_file_size = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ size_t npts = (uint32_t)npts_i32;
+ size_t dim = (uint32_t)dim_i32;
+
+ size_t expected_actual_file_size = npts * dim * sizeof(T) + 2 * sizeof(uint32_t);
+ if (actual_file_size != expected_actual_file_size)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. Actual size is " << actual_file_size << " while expected size is "
+ << expected_actual_file_size << " npts = " << npts << " dim = " << dim << " size of <T>= " << sizeof(T)
+ << std::endl;
+ std::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (offset_points + points_to_read > npts)
+ {
+ std::stringstream stream;
+ stream << "Error. Not enough points in file. Requested " << offset_points << " offset and " << points_to_read
+ << " points, but have only " << npts << " points" << std::endl;
+ std::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ reader.seekg(2 * sizeof(uint32_t) + offset_points * dim * sizeof(T));
+
+ const size_t rounded_dim = ROUND_UP(dim, 8);
+
+ for (size_t i = 0; i < points_to_read; i++)
+ {
+ reader.read((char *)(data + i * rounded_dim), dim * sizeof(T));
+ memset(data + i * rounded_dim + dim, 0, (rounded_dim - dim) * sizeof(T));
+ }
+ reader.close();
+
+ const double elapsedSeconds = timer.elapsed() / 1000000.0;
+ std::cout << "Read " << points_to_read << " points using non-cached reads in " << elapsedSeconds << std::endl;
+}
+
+std::string get_save_filename(const std::string &save_path, size_t points_to_skip, size_t points_deleted,
+ size_t last_point_threshold)
+{
+ std::string final_path = save_path;
+ if (points_to_skip > 0)
+ {
+ final_path += "skip" + std::to_string(points_to_skip) + "-";
+ }
+
+ final_path += "del" + std::to_string(points_deleted) + "-";
+ final_path += std::to_string(last_point_threshold);
+ return final_path;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void insert_till_next_checkpoint(diskann::AbstractIndex &index, size_t start, size_t end, int32_t thread_count, T *data,
+ size_t aligned_dim, std::vector<std::vector<LabelT>> &location_to_labels)
+{
+ diskann::Timer insert_timer;
+#pragma omp parallel for num_threads(thread_count) schedule(dynamic)
+ for (int64_t j = start; j < (int64_t)end; j++)
+ {
+ if (!location_to_labels.empty())
+ {
+ index.insert_point(&data[(j - start) * aligned_dim], 1 + static_cast<TagT>(j),
+ location_to_labels[j - start]);
+ }
+ else
+ {
+ index.insert_point(&data[(j - start) * aligned_dim], 1 + static_cast<TagT>(j));
+ }
+ }
+ const double elapsedSeconds = insert_timer.elapsed() / 1000000.0;
+ std::cout << "Insertion time " << elapsedSeconds << " seconds (" << (end - start) / elapsedSeconds
+ << " points/second overall, " << (end - start) / elapsedSeconds / thread_count << " per thread)\n ";
+}
+
+template <typename T, typename TagT>
+void delete_from_beginning(diskann::AbstractIndex &index, diskann::IndexWriteParameters &delete_params,
+ size_t points_to_skip, size_t points_to_delete_from_beginning)
+{
+ try
+ {
+ std::cout << std::endl
+ << "Lazy deleting points " << points_to_skip << " to "
+ << points_to_skip + points_to_delete_from_beginning << "... ";
+ for (size_t i = points_to_skip; i < points_to_skip + points_to_delete_from_beginning; ++i)
+ index.lazy_delete(static_cast<TagT>(i + 1)); // Since tags are data location + 1
+ std::cout << "done." << std::endl;
+
+ auto report = index.consolidate_deletes(delete_params);
+ std::cout << "#active points: " << report._active_points << std::endl
+ << "max points: " << report._max_points << std::endl
+ << "empty slots: " << report._empty_slots << std::endl
+ << "deletes processed: " << report._slots_released << std::endl
+ << "latest delete size: " << report._delete_set_size << std::endl
+ << "rate: (" << points_to_delete_from_beginning / report._time << " points/second overall, "
+ << points_to_delete_from_beginning / report._time / delete_params.num_threads << " per thread)"
+ << std::endl;
+ }
+ catch (std::system_error &e)
+ {
+ std::cout << "Exception caught in deletion thread: " << e.what() << std::endl;
+ }
+}
+
+template <typename T>
+void build_incremental_index(const std::string &data_path, diskann::IndexWriteParameters &params, size_t points_to_skip,
+ size_t max_points_to_insert, size_t beginning_index_size, float start_point_norm,
+ uint32_t num_start_pts, size_t points_per_checkpoint, size_t checkpoints_per_snapshot,
+ const std::string &save_path, size_t points_to_delete_from_beginning,
+ size_t start_deletes_after, bool concurrent, const std::string &label_file,
+ const std::string &universal_label)
+{
+ size_t dim, aligned_dim;
+ size_t num_points;
+ diskann::get_bin_metadata(data_path, num_points, dim);
+ aligned_dim = ROUND_UP(dim, 8);
+ bool has_labels = label_file != "";
+ using TagT = uint32_t;
+ using LabelT = uint32_t;
+
+ size_t current_point_offset = points_to_skip;
+ const size_t last_point_threshold = points_to_skip + max_points_to_insert;
+
+ bool enable_tags = true;
+ using TagT = uint32_t;
+ auto index_search_params = diskann::IndexSearchParams(params.search_list_size, params.num_threads);
+ diskann::IndexConfig index_config = diskann::IndexConfigBuilder()
+ .with_metric(diskann::L2)
+ .with_dimension(dim)
+ .with_max_points(max_points_to_insert)
+ .is_dynamic_index(true)
+ .with_index_write_params(params)
+ .with_index_search_params(index_search_params)
+ .with_data_type(diskann_type_to_name<T>())
+ .with_tag_type(diskann_type_to_name<TagT>())
+ .with_label_type(diskann_type_to_name<LabelT>())
+ .with_data_load_store_strategy(diskann::DataStoreStrategy::MEMORY)
+ .with_graph_load_store_strategy(diskann::GraphStoreStrategy::MEMORY)
+ .is_enable_tags(enable_tags)
+ .is_filtered(has_labels)
+ .with_num_frozen_pts(num_start_pts)
+ .is_concurrent_consolidate(concurrent)
+ .build();
+
+ diskann::IndexFactory index_factory = diskann::IndexFactory(index_config);
+ auto index = index_factory.create_instance();
+
+ if (universal_label != "")
+ {
+ LabelT u_label = 0;
+ index->set_universal_label(u_label);
+ }
+
+ if (points_to_skip > num_points)
+ {
+ throw diskann::ANNException("Asked to skip more points than in data file", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (max_points_to_insert == 0)
+ {
+ max_points_to_insert = num_points;
+ }
+
+ if (points_to_skip + max_points_to_insert > num_points)
+ {
+ max_points_to_insert = num_points - points_to_skip;
+ std::cerr << "WARNING: Reducing max_points_to_insert to " << max_points_to_insert
+ << " points since the data file has only that many" << std::endl;
+ }
+
+ if (beginning_index_size > max_points_to_insert)
+ {
+ beginning_index_size = max_points_to_insert;
+ std::cerr << "WARNING: Reducing beginning index size to " << beginning_index_size
+ << " points since the data file has only that many" << std::endl;
+ }
+ if (checkpoints_per_snapshot > 0 && beginning_index_size > points_per_checkpoint)
+ {
+ beginning_index_size = points_per_checkpoint;
+ std::cerr << "WARNING: Reducing beginning index size to " << beginning_index_size << std::endl;
+ }
+
+ T *data = nullptr;
+ diskann::alloc_aligned(
+ (void **)&data, std::max(points_per_checkpoint, beginning_index_size) * aligned_dim * sizeof(T), 8 * sizeof(T));
+
+ std::vector<TagT> tags(beginning_index_size);
+ std::iota(tags.begin(), tags.end(), 1 + static_cast<TagT>(current_point_offset));
+
+ load_aligned_bin_part(data_path, data, current_point_offset, beginning_index_size);
+ std::cout << "load aligned bin succeeded" << std::endl;
+ diskann::Timer timer;
+
+ if (beginning_index_size > 0)
+ {
+ index->build(data, beginning_index_size, tags);
+ }
+ else
+ {
+ index->set_start_points_at_random(static_cast<T>(start_point_norm));
+ }
+
+ const double elapsedSeconds = timer.elapsed() / 1000000.0;
+ std::cout << "Initial non-incremental index build time for " << beginning_index_size << " points took "
+ << elapsedSeconds << " seconds (" << beginning_index_size / elapsedSeconds << " points/second)\n ";
+
+ current_point_offset += beginning_index_size;
+
+ if (points_to_delete_from_beginning > max_points_to_insert)
+ {
+ points_to_delete_from_beginning = static_cast<uint32_t>(max_points_to_insert);
+ std::cerr << "WARNING: Reducing points to delete from beginning to " << points_to_delete_from_beginning
+ << " points since the data file has only that many" << std::endl;
+ }
+
+ std::vector<std::vector<LabelT>> location_to_labels;
+ if (concurrent)
+ {
+ // handle labels
+ const auto save_path_inc = get_save_filename(save_path + ".after-concurrent-delete-", points_to_skip,
+ points_to_delete_from_beginning, last_point_threshold);
+ std::string labels_file_to_use = save_path_inc + "_label_formatted.txt";
+ std::string mem_labels_int_map_file = save_path_inc + "_labels_map.txt";
+ if (has_labels)
+ {
+ convert_labels_string_to_int(label_file, labels_file_to_use, mem_labels_int_map_file, universal_label);
+ auto parse_result = diskann::parse_formatted_label_file<LabelT>(labels_file_to_use);
+ location_to_labels = std::get<0>(parse_result);
+ }
+
+ int32_t sub_threads = (params.num_threads + 1) / 2;
+ bool delete_launched = false;
+ std::future<void> delete_task;
+
+ diskann::Timer timer;
+
+ for (size_t start = current_point_offset; start < last_point_threshold;
+ start += points_per_checkpoint, current_point_offset += points_per_checkpoint)
+ {
+ const size_t end = std::min(start + points_per_checkpoint, last_point_threshold);
+ std::cout << std::endl << "Inserting from " << start << " to " << end << std::endl;
+
+ auto insert_task = std::async(std::launch::async, [&]() {
+ load_aligned_bin_part(data_path, data, start, end - start);
+ insert_till_next_checkpoint<T, TagT, LabelT>(*index, start, end, sub_threads, data, aligned_dim,
+ location_to_labels);
+ });
+ insert_task.wait();
+
+ if (!delete_launched && end >= start_deletes_after &&
+ end >= points_to_skip + points_to_delete_from_beginning)
+ {
+ delete_launched = true;
+ diskann::IndexWriteParameters delete_params =
+ diskann::IndexWriteParametersBuilder(params).with_num_threads(sub_threads).build();
+
+ delete_task = std::async(std::launch::async, [&]() {
+ delete_from_beginning<T, TagT>(*index, delete_params, points_to_skip,
+ points_to_delete_from_beginning);
+ });
+ }
+ }
+ delete_task.wait();
+
+ std::cout << "Time Elapsed " << timer.elapsed() / 1000 << "ms\n";
+ index->save(save_path_inc.c_str(), true);
+ }
+ else
+ {
+ const auto save_path_inc = get_save_filename(save_path + ".after-delete-", points_to_skip,
+ points_to_delete_from_beginning, last_point_threshold);
+ std::string labels_file_to_use = save_path_inc + "_label_formatted.txt";
+ std::string mem_labels_int_map_file = save_path_inc + "_labels_map.txt";
+ if (has_labels)
+ {
+ convert_labels_string_to_int(label_file, labels_file_to_use, mem_labels_int_map_file, universal_label);
+ auto parse_result = diskann::parse_formatted_label_file<LabelT>(labels_file_to_use);
+ location_to_labels = std::get<0>(parse_result);
+ }
+
+ size_t last_snapshot_points_threshold = 0;
+ size_t num_checkpoints_till_snapshot = checkpoints_per_snapshot;
+
+ for (size_t start = current_point_offset; start < last_point_threshold;
+ start += points_per_checkpoint, current_point_offset += points_per_checkpoint)
+ {
+ const size_t end = std::min(start + points_per_checkpoint, last_point_threshold);
+ std::cout << std::endl << "Inserting from " << start << " to " << end << std::endl;
+
+ load_aligned_bin_part(data_path, data, start, end - start);
+ insert_till_next_checkpoint<T, TagT, LabelT>(*index, start, end, (int32_t)params.num_threads, data,
+ aligned_dim, location_to_labels);
+
+ if (checkpoints_per_snapshot > 0 && --num_checkpoints_till_snapshot == 0)
+ {
+ diskann::Timer save_timer;
+
+ const auto save_path_inc =
+ get_save_filename(save_path + ".inc-", points_to_skip, points_to_delete_from_beginning, end);
+ index->save(save_path_inc.c_str(), false);
+ const double elapsedSeconds = save_timer.elapsed() / 1000000.0;
+ const size_t points_saved = end - points_to_skip;
+
+ std::cout << "Saved " << points_saved << " points in " << elapsedSeconds << " seconds ("
+ << points_saved / elapsedSeconds << " points/second)\n";
+
+ num_checkpoints_till_snapshot = checkpoints_per_snapshot;
+ last_snapshot_points_threshold = end;
+ }
+
+ std::cout << "Number of points in the index post insertion " << end << std::endl;
+ }
+
+ if (checkpoints_per_snapshot > 0 && last_snapshot_points_threshold != last_point_threshold)
+ {
+ const auto save_path_inc = get_save_filename(save_path + ".inc-", points_to_skip,
+ points_to_delete_from_beginning, last_point_threshold);
+ // index.save(save_path_inc.c_str(), false);
+ }
+
+ if (points_to_delete_from_beginning > 0)
+ {
+ delete_from_beginning<T, TagT>(*index, params, points_to_skip, points_to_delete_from_beginning);
+ }
+
+ index->save(save_path_inc.c_str(), true);
+ }
+
+ diskann::aligned_free(data);
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, data_path, index_path_prefix;
+ uint32_t num_threads, R, L, num_start_pts;
+ float alpha, start_point_norm;
+ size_t points_to_skip, max_points_to_insert, beginning_index_size, points_per_checkpoint, checkpoints_per_snapshot,
+ points_to_delete_from_beginning, start_deletes_after;
+ bool concurrent;
+
+ // label options
+ std::string label_file, label_type, universal_label;
+ std::uint32_t Lf, unique_labels_supported;
+
+ po::options_description desc{program_options_utils::make_program_description("test_insert_deletes_consolidate",
+ "Test insert deletes & consolidate")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("data_path", po::value<std::string>(&data_path)->required(),
+ program_options_utils::INPUT_DATA_PATH);
+ required_configs.add_options()("points_to_skip", po::value<uint64_t>(&points_to_skip)->required(),
+ "Skip these first set of points from file");
+ required_configs.add_options()("beginning_index_size", po::value<uint64_t>(&beginning_index_size)->required(),
+ "Batch build will be called on these set of points");
+ required_configs.add_options()("points_per_checkpoint", po::value<uint64_t>(&points_per_checkpoint)->required(),
+ "Insertions are done in batches of points_per_checkpoint");
+ required_configs.add_options()("checkpoints_per_snapshot",
+ po::value<uint64_t>(&checkpoints_per_snapshot)->required(),
+ "Save the index to disk every few checkpoints");
+ required_configs.add_options()("points_to_delete_from_beginning",
+ po::value<uint64_t>(&points_to_delete_from_beginning)->required(), "");
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("num_threads,T",
+ po::value<uint32_t>(&num_threads)->default_value(omp_get_num_procs()),
+ program_options_utils::NUMBER_THREADS_DESCRIPTION);
+ optional_configs.add_options()("max_degree,R", po::value<uint32_t>(&R)->default_value(64),
+ program_options_utils::MAX_BUILD_DEGREE);
+ optional_configs.add_options()("Lbuild,L", po::value<uint32_t>(&L)->default_value(100),
+ program_options_utils::GRAPH_BUILD_COMPLEXITY);
+ optional_configs.add_options()("alpha", po::value<float>(&alpha)->default_value(1.2f),
+ program_options_utils::GRAPH_BUILD_ALPHA);
+ optional_configs.add_options()("max_points_to_insert",
+ po::value<uint64_t>(&max_points_to_insert)->default_value(0),
+ "These number of points from the file are inserted after "
+ "points_to_skip");
+ optional_configs.add_options()("do_concurrent", po::value<bool>(&concurrent)->default_value(false), "");
+ optional_configs.add_options()("start_deletes_after",
+ po::value<uint64_t>(&start_deletes_after)->default_value(0), "");
+ optional_configs.add_options()("start_point_norm", po::value<float>(&start_point_norm)->default_value(0),
+ "Set the start point to a random point on a sphere of this radius");
+
+ // optional params for filters
+ optional_configs.add_options()("label_file", po::value<std::string>(&label_file)->default_value(""),
+ "Input label file in txt format for Filtered Index search. "
+ "The file should contain comma separated filters for each node "
+ "with each line corresponding to a graph node");
+ optional_configs.add_options()("universal_label", po::value<std::string>(&universal_label)->default_value(""),
+ "Universal label, if using it, only in conjunction with labels_file");
+ optional_configs.add_options()("FilteredLbuild,Lf", po::value<uint32_t>(&Lf)->default_value(0),
+ "Build complexity for filtered points, higher value "
+ "results in better graphs");
+ optional_configs.add_options()("label_type", po::value<std::string>(&label_type)->default_value("uint"),
+ "Storage type of Labels <uint/ushort>, default value is uint which "
+ "will consume memory 4 bytes per filter");
+ optional_configs.add_options()("unique_labels_supported",
+ po::value<uint32_t>(&unique_labels_supported)->default_value(0),
+ "Number of unique labels supported by the dynamic index.");
+
+ optional_configs.add_options()(
+ "num_start_points",
+ po::value<uint32_t>(&num_start_pts)->default_value(diskann::defaults::NUM_FROZEN_POINTS_DYNAMIC),
+ "Set the number of random start (frozen) points to use when "
+ "inserting and searching");
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ if (beginning_index_size == 0)
+ if (start_point_norm == 0)
+ {
+ std::cout << "When beginning_index_size is 0, use a start "
+ "point with "
+ "appropriate norm"
+ << std::endl;
+ return -1;
+ }
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ bool has_labels = false;
+ if (!label_file.empty() || label_file != "")
+ {
+ has_labels = true;
+ }
+
+ if (num_start_pts < unique_labels_supported)
+ {
+ num_start_pts = unique_labels_supported;
+ }
+
+ try
+ {
+ diskann::IndexWriteParameters params = diskann::IndexWriteParametersBuilder(L, R)
+ .with_max_occlusion_size(500)
+ .with_alpha(alpha)
+ .with_num_threads(num_threads)
+ .with_filter_list_size(Lf)
+ .build();
+
+ if (data_type == std::string("int8"))
+ build_incremental_index<int8_t>(
+ data_path, params, points_to_skip, max_points_to_insert, beginning_index_size, start_point_norm,
+ num_start_pts, points_per_checkpoint, checkpoints_per_snapshot, index_path_prefix,
+ points_to_delete_from_beginning, start_deletes_after, concurrent, label_file, universal_label);
+ else if (data_type == std::string("uint8"))
+ build_incremental_index<uint8_t>(
+ data_path, params, points_to_skip, max_points_to_insert, beginning_index_size, start_point_norm,
+ num_start_pts, points_per_checkpoint, checkpoints_per_snapshot, index_path_prefix,
+ points_to_delete_from_beginning, start_deletes_after, concurrent, label_file, universal_label);
+ else if (data_type == std::string("float"))
+ build_incremental_index<float>(data_path, params, points_to_skip, max_points_to_insert,
+ beginning_index_size, start_point_norm, num_start_pts, points_per_checkpoint,
+ checkpoints_per_snapshot, index_path_prefix, points_to_delete_from_beginning,
+ start_deletes_after, concurrent, label_file, universal_label);
+ else
+ std::cout << "Unsupported type. Use float/int8/uint8" << std::endl;
+ }
+ catch (const std::exception &e)
+ {
+ std::cerr << "Caught exception: " << e.what() << std::endl;
+ exit(-1);
+ }
+ catch (...)
+ {
+ std::cerr << "Caught unknown exception" << std::endl;
+ exit(-1);
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/test_streaming_scenario.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/test_streaming_scenario.cpp
new file mode 100644
index 0000000..5a43a69
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/test_streaming_scenario.cpp
@@ -0,0 +1,523 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <index.h>
+#include <numeric>
+#include <omp.h>
+#include <string.h>
+#include <time.h>
+#include <timer.h>
+#include <boost/program_options.hpp>
+#include <future>
+#include <abstract_index.h>
+#include <index_factory.h>
+
+#include "utils.h"
+#include "filter_utils.h"
+#include "program_options_utils.hpp"
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+
+#include "memory_mapper.h"
+
+namespace po = boost::program_options;
+
+// load_aligned_bin modified to read pieces of the file, but using ifstream
+// instead of cached_ifstream.
+template <typename T>
+inline void load_aligned_bin_part(const std::string &bin_file, T *data, size_t offset_points, size_t points_to_read)
+{
+ std::ifstream reader;
+ reader.exceptions(std::ios::failbit | std::ios::badbit);
+ reader.open(bin_file, std::ios::binary | std::ios::ate);
+ size_t actual_file_size = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ size_t npts = (uint32_t)npts_i32;
+ size_t dim = (uint32_t)dim_i32;
+
+ size_t expected_actual_file_size = npts * dim * sizeof(T) + 2 * sizeof(uint32_t);
+ if (actual_file_size != expected_actual_file_size)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. Actual size is " << actual_file_size << " while expected size is "
+ << expected_actual_file_size << " npts = " << npts << " dim = " << dim << " size of <T>= " << sizeof(T)
+ << std::endl;
+ std::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (offset_points + points_to_read > npts)
+ {
+ std::stringstream stream;
+ stream << "Error. Not enough points in file. Requested " << offset_points << " offset and " << points_to_read
+ << " points, but have only " << npts << " points" << std::endl;
+ std::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ reader.seekg(2 * sizeof(uint32_t) + offset_points * dim * sizeof(T));
+
+ const size_t rounded_dim = ROUND_UP(dim, 8);
+
+ for (size_t i = 0; i < points_to_read; i++)
+ {
+ reader.read((char *)(data + i * rounded_dim), dim * sizeof(T));
+ memset(data + i * rounded_dim + dim, 0, (rounded_dim - dim) * sizeof(T));
+ }
+ reader.close();
+}
+
+std::string get_save_filename(const std::string &save_path, size_t active_window, size_t consolidate_interval,
+ size_t max_points_to_insert)
+{
+ std::string final_path = save_path;
+ final_path += "act" + std::to_string(active_window) + "-";
+ final_path += "cons" + std::to_string(consolidate_interval) + "-";
+ final_path += "max" + std::to_string(max_points_to_insert);
+ return final_path;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void insert_next_batch(diskann::AbstractIndex &index, size_t start, size_t end, size_t insert_threads, T *data,
+ size_t aligned_dim, std::vector<std::vector<LabelT>> &pts_to_labels)
+{
+ try
+ {
+ diskann::Timer insert_timer;
+ std::cout << std::endl << "Inserting from " << start << " to " << end << std::endl;
+
+ size_t num_failed = 0;
+#pragma omp parallel for num_threads((int32_t)insert_threads) schedule(dynamic) reduction(+ : num_failed)
+ for (int64_t j = start; j < (int64_t)end; j++)
+ {
+ int insert_result = -1;
+ if (pts_to_labels.size() > 0)
+ {
+ insert_result = index.insert_point(&data[(j - start) * aligned_dim], 1 + static_cast<TagT>(j),
+ pts_to_labels[j - start]);
+ }
+ else
+ {
+ insert_result = index.insert_point(&data[(j - start) * aligned_dim], 1 + static_cast<TagT>(j));
+ }
+
+ if (insert_result != 0)
+ {
+ std::cerr << "Insert failed " << j << std::endl;
+ num_failed++;
+ }
+ }
+ const double elapsedSeconds = insert_timer.elapsed() / 1000000.0;
+ std::cout << "Insertion time " << elapsedSeconds << " seconds (" << (end - start) / elapsedSeconds
+ << " points/second overall, " << (end - start) / elapsedSeconds / insert_threads << " per thread)"
+ << std::endl;
+ if (num_failed > 0)
+ std::cout << num_failed << " of " << end - start << "inserts failed" << std::endl;
+ }
+ catch (std::system_error &e)
+ {
+ std::cout << "Exiting after catching exception in insertion task: " << e.what() << std::endl;
+ exit(-1);
+ }
+}
+
+template <typename T, typename TagT = uint32_t, typename LabelT = uint32_t>
+void delete_and_consolidate(diskann::AbstractIndex &index, diskann::IndexWriteParameters &delete_params, size_t start,
+ size_t end)
+{
+ try
+ {
+ std::cout << std::endl << "Lazy deleting points " << start << " to " << end << "... ";
+ for (size_t i = start; i < end; ++i)
+ index.lazy_delete(static_cast<TagT>(1 + i));
+ std::cout << "lazy delete done." << std::endl;
+
+ auto report = index.consolidate_deletes(delete_params);
+ while (report._status != diskann::consolidation_report::status_code::SUCCESS)
+ {
+ int wait_time = 5;
+ if (report._status == diskann::consolidation_report::status_code::LOCK_FAIL)
+ {
+ diskann::cerr << "Unable to acquire consolidate delete lock after "
+ << "deleting points " << start << " to " << end << ". Will retry in " << wait_time
+ << "seconds." << std::endl;
+ }
+ else if (report._status == diskann::consolidation_report::status_code::INCONSISTENT_COUNT_ERROR)
+ {
+ diskann::cerr << "Inconsistent counts in data structure. "
+ << "Will retry in " << wait_time << "seconds." << std::endl;
+ }
+ else
+ {
+ std::cerr << "Exiting after unknown error in consolidate delete" << std::endl;
+ exit(-1);
+ }
+ std::this_thread::sleep_for(std::chrono::seconds(wait_time));
+ report = index.consolidate_deletes(delete_params);
+ }
+ auto points_processed = report._active_points + report._slots_released;
+ auto deletion_rate = points_processed / report._time;
+ std::cout << "#active points: " << report._active_points << std::endl
+ << "max points: " << report._max_points << std::endl
+ << "empty slots: " << report._empty_slots << std::endl
+ << "deletes processed: " << report._slots_released << std::endl
+ << "latest delete size: " << report._delete_set_size << std::endl
+ << "Deletion rate: " << deletion_rate << "/sec "
+ << "Deletion rate: " << deletion_rate / delete_params.num_threads << "/thread/sec " << std::endl;
+ }
+ catch (std::system_error &e)
+ {
+ std::cerr << "Exiting after catching exception in deletion task: " << e.what() << std::endl;
+ exit(-1);
+ }
+}
+
+template <typename T, typename TagT = uint32_t, typename LabelT = uint32_t>
+void build_incremental_index(const std::string &data_path, const uint32_t L, const uint32_t R, const float alpha,
+ const uint32_t insert_threads, const uint32_t consolidate_threads,
+ size_t max_points_to_insert, size_t active_window, size_t consolidate_interval,
+ const float start_point_norm, uint32_t num_start_pts, const std::string &save_path,
+ const std::string &label_file, const std::string &universal_label, const uint32_t Lf)
+{
+ const uint32_t C = 500;
+ const bool saturate_graph = false;
+ bool has_labels = label_file != "";
+
+ diskann::IndexWriteParameters params = diskann::IndexWriteParametersBuilder(L, R)
+ .with_max_occlusion_size(C)
+ .with_alpha(alpha)
+ .with_saturate_graph(saturate_graph)
+ .with_num_threads(insert_threads)
+ .with_filter_list_size(Lf)
+ .build();
+
+ auto index_search_params = diskann::IndexSearchParams(L, insert_threads);
+ diskann::IndexWriteParameters delete_params = diskann::IndexWriteParametersBuilder(L, R)
+ .with_max_occlusion_size(C)
+ .with_alpha(alpha)
+ .with_saturate_graph(saturate_graph)
+ .with_num_threads(consolidate_threads)
+ .with_filter_list_size(Lf)
+ .build();
+
+ size_t dim, aligned_dim;
+ size_t num_points;
+
+ std::vector<std::vector<LabelT>> pts_to_labels;
+
+ const auto save_path_inc =
+ get_save_filename(save_path + ".after-streaming-", active_window, consolidate_interval, max_points_to_insert);
+ std::string labels_file_to_use = save_path_inc + "_label_formatted.txt";
+ std::string mem_labels_int_map_file = save_path_inc + "_labels_map.txt";
+ if (has_labels)
+ {
+ convert_labels_string_to_int(label_file, labels_file_to_use, mem_labels_int_map_file, universal_label);
+ auto parse_result = diskann::parse_formatted_label_file<LabelT>(labels_file_to_use);
+ pts_to_labels = std::get<0>(parse_result);
+ }
+
+ diskann::get_bin_metadata(data_path, num_points, dim);
+ diskann::cout << "metadata: file " << data_path << " has " << num_points << " points in " << dim << " dims"
+ << std::endl;
+ aligned_dim = ROUND_UP(dim, 8);
+ auto index_config = diskann::IndexConfigBuilder()
+ .with_metric(diskann::L2)
+ .with_dimension(dim)
+ .with_max_points(active_window + 4 * consolidate_interval)
+ .is_dynamic_index(true)
+ .is_enable_tags(true)
+ .is_use_opq(false)
+ .is_filtered(has_labels)
+ .with_num_pq_chunks(0)
+ .is_pq_dist_build(false)
+ .with_num_frozen_pts(num_start_pts)
+ .with_tag_type(diskann_type_to_name<TagT>())
+ .with_label_type(diskann_type_to_name<LabelT>())
+ .with_data_type(diskann_type_to_name<T>())
+ .with_index_write_params(params)
+ .with_index_search_params(index_search_params)
+ .with_data_load_store_strategy(diskann::DataStoreStrategy::MEMORY)
+ .with_graph_load_store_strategy(diskann::GraphStoreStrategy::MEMORY)
+ .build();
+
+ diskann::IndexFactory index_factory = diskann::IndexFactory(index_config);
+ auto index = index_factory.create_instance();
+
+ if (universal_label != "")
+ {
+ LabelT u_label = 0;
+ index->set_universal_label(u_label);
+ }
+
+ if (max_points_to_insert == 0)
+ {
+ max_points_to_insert = num_points;
+ }
+
+ if (num_points < max_points_to_insert)
+ throw diskann::ANNException(std::string("num_points(") + std::to_string(num_points) +
+ ") < max_points_to_insert(" + std::to_string(max_points_to_insert) + ")",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ if (max_points_to_insert < active_window + consolidate_interval)
+ throw diskann::ANNException("ERROR: max_points_to_insert < "
+ "active_window + consolidate_interval",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ if (consolidate_interval < max_points_to_insert / 1000)
+ throw diskann::ANNException("ERROR: consolidate_interval is too small", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ index->set_start_points_at_random(static_cast<T>(start_point_norm));
+
+ T *data = nullptr;
+ diskann::alloc_aligned((void **)&data, std::max(consolidate_interval, active_window) * aligned_dim * sizeof(T),
+ 8 * sizeof(T));
+
+ std::vector<TagT> tags(max_points_to_insert);
+ std::iota(tags.begin(), tags.end(), static_cast<TagT>(0));
+
+ diskann::Timer timer;
+
+ std::vector<std::future<void>> delete_tasks;
+
+ auto insert_task = std::async(std::launch::async, [&]() {
+ load_aligned_bin_part(data_path, data, 0, active_window);
+ insert_next_batch<T, TagT, LabelT>(*index, (size_t)0, active_window, params.num_threads, data, aligned_dim,
+ pts_to_labels);
+ });
+ insert_task.wait();
+
+ for (size_t start = active_window; start + consolidate_interval <= max_points_to_insert;
+ start += consolidate_interval)
+ {
+ auto end = std::min(start + consolidate_interval, max_points_to_insert);
+ auto insert_task = std::async(std::launch::async, [&]() {
+ load_aligned_bin_part(data_path, data, start, end - start);
+ insert_next_batch<T, TagT, LabelT>(*index, start, end, params.num_threads, data, aligned_dim,
+ pts_to_labels);
+ });
+ insert_task.wait();
+
+ if (delete_tasks.size() > 0)
+ delete_tasks[delete_tasks.size() - 1].wait();
+ if (start >= active_window + consolidate_interval)
+ {
+ auto start_del = start - active_window - consolidate_interval;
+ auto end_del = start - active_window;
+
+ delete_tasks.emplace_back(std::async(std::launch::async, [&]() {
+ delete_and_consolidate<T, TagT, LabelT>(*index, delete_params, (size_t)start_del, (size_t)end_del);
+ }));
+ }
+ }
+ if (delete_tasks.size() > 0)
+ delete_tasks[delete_tasks.size() - 1].wait();
+
+ std::cout << "Time Elapsed " << timer.elapsed() / 1000 << "ms\n";
+
+ index->save(save_path_inc.c_str(), true);
+
+ diskann::aligned_free(data);
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, data_path, index_path_prefix, label_file, universal_label, label_type;
+ uint32_t insert_threads, consolidate_threads, R, L, num_start_pts, Lf, unique_labels_supported;
+ float alpha, start_point_norm;
+ size_t max_points_to_insert, active_window, consolidate_interval;
+
+ po::options_description desc{program_options_utils::make_program_description("test_streaming_scenario",
+ "Test insert deletes & consolidate")};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+
+ // Required parameters
+ po::options_description required_configs("Required");
+ required_configs.add_options()("data_type", po::value<std::string>(&data_type)->required(),
+ program_options_utils::DATA_TYPE_DESCRIPTION);
+ required_configs.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ program_options_utils::DISTANCE_FUNCTION_DESCRIPTION);
+ required_configs.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ program_options_utils::INDEX_PATH_PREFIX_DESCRIPTION);
+ required_configs.add_options()("data_path", po::value<std::string>(&data_path)->required(),
+ program_options_utils::INPUT_DATA_PATH);
+ required_configs.add_options()("active_window", po::value<uint64_t>(&active_window)->required(),
+ "Program maintains an index over an active window of "
+ "this size that slides through the data");
+ required_configs.add_options()("consolidate_interval", po::value<uint64_t>(&consolidate_interval)->required(),
+ "The program simultaneously adds this number of points to the "
+ "right of "
+ "the window while deleting the same number from the left");
+ required_configs.add_options()("start_point_norm", po::value<float>(&start_point_norm)->required(),
+ "Set the start point to a random point on a sphere of this radius");
+
+ // Optional parameters
+ po::options_description optional_configs("Optional");
+ optional_configs.add_options()("max_degree,R", po::value<uint32_t>(&R)->default_value(64),
+ program_options_utils::MAX_BUILD_DEGREE);
+ optional_configs.add_options()("Lbuild,L", po::value<uint32_t>(&L)->default_value(100),
+ program_options_utils::GRAPH_BUILD_COMPLEXITY);
+ optional_configs.add_options()("alpha", po::value<float>(&alpha)->default_value(1.2f),
+ program_options_utils::GRAPH_BUILD_ALPHA);
+ optional_configs.add_options()("insert_threads",
+ po::value<uint32_t>(&insert_threads)->default_value(omp_get_num_procs() / 2),
+ "Number of threads used for inserting into the index (defaults to "
+ "omp_get_num_procs()/2)");
+ optional_configs.add_options()(
+ "consolidate_threads", po::value<uint32_t>(&consolidate_threads)->default_value(omp_get_num_procs() / 2),
+ "Number of threads used for consolidating deletes to "
+ "the index (defaults to omp_get_num_procs()/2)");
+ optional_configs.add_options()("max_points_to_insert",
+ po::value<uint64_t>(&max_points_to_insert)->default_value(0),
+ "The number of points from the file that the program streams "
+ "over ");
+ optional_configs.add_options()(
+ "num_start_points",
+ po::value<uint32_t>(&num_start_pts)->default_value(diskann::defaults::NUM_FROZEN_POINTS_DYNAMIC),
+ "Set the number of random start (frozen) points to use when "
+ "inserting and searching");
+
+ optional_configs.add_options()("label_file", po::value<std::string>(&label_file)->default_value(""),
+ "Input label file in txt format for Filtered Index search. "
+ "The file should contain comma separated filters for each node "
+ "with each line corresponding to a graph node");
+ optional_configs.add_options()("universal_label", po::value<std::string>(&universal_label)->default_value(""),
+ "Universal label, if using it, only in conjunction with labels_file");
+ optional_configs.add_options()("FilteredLbuild,Lf", po::value<uint32_t>(&Lf)->default_value(0),
+ "Build complexity for filtered points, higher value "
+ "results in better graphs");
+ optional_configs.add_options()("label_type", po::value<std::string>(&label_type)->default_value("uint"),
+ "Storage type of Labels <uint/ushort>, default value is uint which "
+ "will consume memory 4 bytes per filter");
+ optional_configs.add_options()("unique_labels_supported",
+ po::value<uint32_t>(&unique_labels_supported)->default_value(0),
+ "Number of unique labels supported by the dynamic index.");
+
+ // Merge required and optional parameters
+ desc.add(required_configs).add(optional_configs);
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ // Validate arguments
+ if (start_point_norm == 0)
+ {
+ std::cout << "When beginning_index_size is 0, use a start point with "
+ "appropriate norm"
+ << std::endl;
+ return -1;
+ }
+
+ if (label_type != std::string("ushort") && label_type != std::string("uint"))
+ {
+ std::cerr << "Invalid label type. Supported types are uint and ushort" << std::endl;
+ return -1;
+ }
+
+ if (data_type != std::string("int8") && data_type != std::string("uint8") && data_type != std::string("float"))
+ {
+ std::cerr << "Invalid data type. Supported types are int8, uint8 and float" << std::endl;
+ return -1;
+ }
+
+ // TODO: Are additional distance functions supported?
+ if (dist_fn != std::string("l2") && dist_fn != std::string("mips"))
+ {
+ std::cerr << "Invalid distance function. Supported functions are l2 and mips" << std::endl;
+ return -1;
+ }
+
+ if (num_start_pts < unique_labels_supported)
+ {
+ num_start_pts = unique_labels_supported;
+ }
+
+ try
+ {
+ if (data_type == std::string("uint8"))
+ {
+ if (label_type == std::string("ushort"))
+ {
+ build_incremental_index<uint8_t, uint32_t, uint16_t>(
+ data_path, L, R, alpha, insert_threads, consolidate_threads, max_points_to_insert, active_window,
+ consolidate_interval, start_point_norm, num_start_pts, index_path_prefix, label_file,
+ universal_label, Lf);
+ }
+ else if (label_type == std::string("uint"))
+ {
+ build_incremental_index<uint8_t, uint32_t, uint32_t>(
+ data_path, L, R, alpha, insert_threads, consolidate_threads, max_points_to_insert, active_window,
+ consolidate_interval, start_point_norm, num_start_pts, index_path_prefix, label_file,
+ universal_label, Lf);
+ }
+ }
+ else if (data_type == std::string("int8"))
+ {
+ if (label_type == std::string("ushort"))
+ {
+ build_incremental_index<int8_t, uint32_t, uint16_t>(
+ data_path, L, R, alpha, insert_threads, consolidate_threads, max_points_to_insert, active_window,
+ consolidate_interval, start_point_norm, num_start_pts, index_path_prefix, label_file,
+ universal_label, Lf);
+ }
+ else if (label_type == std::string("uint"))
+ {
+ build_incremental_index<int8_t, uint32_t, uint32_t>(
+ data_path, L, R, alpha, insert_threads, consolidate_threads, max_points_to_insert, active_window,
+ consolidate_interval, start_point_norm, num_start_pts, index_path_prefix, label_file,
+ universal_label, Lf);
+ }
+ }
+ else if (data_type == std::string("float"))
+ {
+ if (label_type == std::string("ushort"))
+ {
+ build_incremental_index<float, uint32_t, uint16_t>(
+ data_path, L, R, alpha, insert_threads, consolidate_threads, max_points_to_insert, active_window,
+ consolidate_interval, start_point_norm, num_start_pts, index_path_prefix, label_file,
+ universal_label, Lf);
+ }
+ else if (label_type == std::string("uint"))
+ {
+ build_incremental_index<float, uint32_t, uint32_t>(
+ data_path, L, R, alpha, insert_threads, consolidate_threads, max_points_to_insert, active_window,
+ consolidate_interval, start_point_norm, num_start_pts, index_path_prefix, label_file,
+ universal_label, Lf);
+ }
+ }
+ }
+ catch (const std::exception &e)
+ {
+ std::cerr << "Caught exception: " << e.what() << std::endl;
+ exit(-1);
+ }
+ catch (...)
+ {
+ std::cerr << "Caught unknown exception" << std::endl;
+ exit(-1);
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/CMakeLists.txt
new file mode 100644
index 0000000..3b8cf22
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/CMakeLists.txt
@@ -0,0 +1,110 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_COMPILE_WARNING_AS_ERROR ON)
+
+
+add_executable(fvecs_to_bin fvecs_to_bin.cpp)
+
+add_executable(fvecs_to_bvecs fvecs_to_bvecs.cpp)
+
+add_executable(rand_data_gen rand_data_gen.cpp)
+target_link_libraries(rand_data_gen ${PROJECT_NAME} Boost::program_options)
+
+add_executable(float_bin_to_int8 float_bin_to_int8.cpp)
+
+add_executable(ivecs_to_bin ivecs_to_bin.cpp)
+
+add_executable(count_bfs_levels count_bfs_levels.cpp)
+target_link_libraries(count_bfs_levels ${PROJECT_NAME} Boost::program_options)
+
+add_executable(tsv_to_bin tsv_to_bin.cpp)
+
+add_executable(bin_to_tsv bin_to_tsv.cpp)
+
+add_executable(int8_to_float int8_to_float.cpp)
+target_link_libraries(int8_to_float ${PROJECT_NAME})
+
+add_executable(int8_to_float_scale int8_to_float_scale.cpp)
+target_link_libraries(int8_to_float_scale ${PROJECT_NAME})
+
+add_executable(uint8_to_float uint8_to_float.cpp)
+target_link_libraries(uint8_to_float ${PROJECT_NAME})
+
+add_executable(uint32_to_uint8 uint32_to_uint8.cpp)
+target_link_libraries(uint32_to_uint8 ${PROJECT_NAME})
+
+add_executable(vector_analysis vector_analysis.cpp)
+target_link_libraries(vector_analysis ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+add_executable(gen_random_slice gen_random_slice.cpp)
+target_link_libraries(gen_random_slice ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+add_executable(simulate_aggregate_recall simulate_aggregate_recall.cpp)
+
+add_executable(calculate_recall calculate_recall.cpp)
+target_link_libraries(calculate_recall ${PROJECT_NAME} ${DISKANN_ASYNC_LIB} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+# Compute ground truth thing outside of DiskANN main source that depends on MKL.
+add_executable(compute_groundtruth compute_groundtruth.cpp)
+target_include_directories(compute_groundtruth PRIVATE ${DISKANN_MKL_INCLUDE_DIRECTORIES})
+target_link_libraries(compute_groundtruth ${PROJECT_NAME} ${DISKANN_MKL_LINK_LIBRARIES} ${DISKANN_ASYNC_LIB} Boost::program_options)
+
+add_executable(compute_groundtruth_for_filters compute_groundtruth_for_filters.cpp)
+target_include_directories(compute_groundtruth_for_filters PRIVATE ${DISKANN_MKL_INCLUDE_DIRECTORIES})
+target_link_libraries(compute_groundtruth_for_filters ${PROJECT_NAME} ${DISKANN_MKL_LINK_LIBRARIES} ${DISKANN_ASYNC_LIB} Boost::program_options)
+
+
+add_executable(generate_pq generate_pq.cpp)
+target_link_libraries(generate_pq ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+
+add_executable(partition_data partition_data.cpp)
+target_link_libraries(partition_data ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+add_executable(partition_with_ram_budget partition_with_ram_budget.cpp)
+target_link_libraries(partition_with_ram_budget ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+add_executable(merge_shards merge_shards.cpp)
+target_link_libraries(merge_shards ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} ${DISKANN_ASYNC_LIB})
+
+add_executable(create_disk_layout create_disk_layout.cpp)
+target_link_libraries(create_disk_layout ${PROJECT_NAME} ${DISKANN_ASYNC_LIB} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS})
+
+add_executable(generate_synthetic_labels generate_synthetic_labels.cpp)
+target_link_libraries(generate_synthetic_labels ${PROJECT_NAME} Boost::program_options)
+
+add_executable(stats_label_data stats_label_data.cpp)
+target_link_libraries(stats_label_data ${PROJECT_NAME} Boost::program_options)
+
+if (NOT MSVC)
+ include(GNUInstallDirs)
+ install(TARGETS fvecs_to_bin
+ fvecs_to_bvecs
+ rand_data_gen
+ float_bin_to_int8
+ ivecs_to_bin
+ count_bfs_levels
+ tsv_to_bin
+ bin_to_tsv
+ int8_to_float
+ int8_to_float_scale
+ uint8_to_float
+ uint32_to_uint8
+ vector_analysis
+ gen_random_slice
+ simulate_aggregate_recall
+ calculate_recall
+ compute_groundtruth
+ compute_groundtruth_for_filters
+ generate_pq
+ partition_data
+ partition_with_ram_budget
+ merge_shards
+ create_disk_layout
+ generate_synthetic_labels
+ stats_label_data
+ RUNTIME
+ )
+endif()
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/bin_to_fvecs.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/bin_to_fvecs.cpp
new file mode 100644
index 0000000..e9a6a8e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/bin_to_fvecs.cpp
@@ -0,0 +1,63 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "util.h"
+
+void block_convert(std::ifstream &writr, std::ofstream &readr, float *read_buf, float *write_buf, uint64_t npts,
+ uint64_t ndims)
+{
+ writr.write((char *)read_buf, npts * (ndims * sizeof(float) + sizeof(unsigned)));
+#pragma omp parallel for
+ for (uint64_t i = 0; i < npts; i++)
+ {
+ memcpy(write_buf + i * ndims, (read_buf + i * (ndims + 1)) + 1, ndims * sizeof(float));
+ }
+ readr.read((char *)write_buf, npts * ndims * sizeof(float));
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 3)
+ {
+ std::cout << argv[0] << " input_bin output_fvecs" << std::endl;
+ exit(-1);
+ }
+ std::ifstream readr(argv[1], std::ios::binary);
+ int npts_s32;
+ int ndims_s32;
+ readr.read((char *)&npts_s32, sizeof(int32_t));
+ readr.read((char *)&ndims_s32, sizeof(int32_t));
+ size_t npts = npts_s32;
+ size_t ndims = ndims_s32;
+ uint32_t ndims_u32 = (uint32_t)ndims_s32;
+ // uint64_t fsize = writr.tellg();
+ readr.seekg(0, std::ios::beg);
+
+ unsigned ndims_u32;
+ writr.write((char *)&ndims_u32, sizeof(unsigned));
+ writr.seekg(0, std::ios::beg);
+ uint64_t ndims = (uint64_t)ndims_u32;
+ uint64_t npts = fsize / ((ndims + 1) * sizeof(float));
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ uint64_t blk_size = 131072;
+ uint64_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ std::cout << "# blks: " << nblks << std::endl;
+
+ std::ofstream writr(argv[2], std::ios::binary);
+ float *read_buf = new float[npts * (ndims + 1)];
+ float *write_buf = new float[npts * ndims];
+ for (uint64_t i = 0; i < nblks; i++)
+ {
+ uint64_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ block_convert(writr, readr, read_buf, write_buf, cblk_size, ndims);
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+ delete[] write_buf;
+
+ writr.close();
+ readr.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/bin_to_tsv.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/bin_to_tsv.cpp
new file mode 100644
index 0000000..7851bef
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/bin_to_tsv.cpp
@@ -0,0 +1,69 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+template <class T>
+void block_convert(std::ofstream &writer, std::ifstream &reader, T *read_buf, size_t npts, size_t ndims)
+{
+ reader.read((char *)read_buf, npts * ndims * sizeof(float));
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ for (size_t d = 0; d < ndims; d++)
+ {
+ writer << read_buf[d + i * ndims];
+ if (d < ndims - 1)
+ writer << "\t";
+ else
+ writer << "\n";
+ }
+ }
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 4)
+ {
+ std::cout << argv[0] << " <float/int8/uint8> input_bin output_tsv" << std::endl;
+ exit(-1);
+ }
+ std::string type_string(argv[1]);
+ if ((type_string != std::string("float")) && (type_string != std::string("int8")) &&
+ (type_string != std::string("uin8")))
+ {
+ std::cerr << "Error: type not supported. Use float/int8/uint8" << std::endl;
+ }
+
+ std::ifstream reader(argv[2], std::ios::binary);
+ uint32_t npts_u32;
+ uint32_t ndims_u32;
+ reader.read((char *)&npts_u32, sizeof(uint32_t));
+ reader.read((char *)&ndims_u32, sizeof(uint32_t));
+ size_t npts = npts_u32;
+ size_t ndims = ndims_u32;
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+
+ std::ofstream writer(argv[3]);
+ char *read_buf = new char[blk_size * ndims * 4];
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ if (type_string == std::string("float"))
+ block_convert<float>(writer, reader, (float *)read_buf, cblk_size, ndims);
+ else if (type_string == std::string("int8"))
+ block_convert<int8_t>(writer, reader, (int8_t *)read_buf, cblk_size, ndims);
+ else if (type_string == std::string("uint8"))
+ block_convert<uint8_t>(writer, reader, (uint8_t *)read_buf, cblk_size, ndims);
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+
+ writer.close();
+ reader.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/calculate_recall.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/calculate_recall.cpp
new file mode 100644
index 0000000..dc76252
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/calculate_recall.cpp
@@ -0,0 +1,55 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <cstddef>
+#include <cstdlib>
+#include <fstream>
+#include <iostream>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "utils.h"
+#include "disk_utils.h"
+
+int main(int argc, char **argv)
+{
+ if (argc != 4)
+ {
+ std::cout << argv[0] << " <ground_truth_bin> <our_results_bin> <r> " << std::endl;
+ return -1;
+ }
+ uint32_t *gold_std = NULL;
+ float *gs_dist = nullptr;
+ uint32_t *our_results = NULL;
+ float *or_dist = nullptr;
+ size_t points_num, points_num_gs, points_num_or;
+ size_t dim_gs;
+ size_t dim_or;
+ diskann::load_truthset(argv[1], gold_std, gs_dist, points_num_gs, dim_gs);
+ diskann::load_truthset(argv[2], our_results, or_dist, points_num_or, dim_or);
+
+ if (points_num_gs != points_num_or)
+ {
+ std::cout << "Error. Number of queries mismatch in ground truth and "
+ "our results"
+ << std::endl;
+ return -1;
+ }
+ points_num = points_num_gs;
+
+ uint32_t recall_at = std::atoi(argv[3]);
+
+ if ((dim_or < recall_at) || (recall_at > dim_gs))
+ {
+ std::cout << "ground truth has size " << dim_gs << "; our set has " << dim_or << " points. Asking for recall "
+ << recall_at << std::endl;
+ return -1;
+ }
+ std::cout << "Calculating recall@" << recall_at << std::endl;
+ double recall_val = diskann::calculate_recall((uint32_t)points_num, gold_std, gs_dist, (uint32_t)dim_gs,
+ our_results, (uint32_t)dim_or, (uint32_t)recall_at);
+
+ // double avg_recall = (recall*1.0)/(points_num*1.0);
+ std::cout << "Avg. recall@" << recall_at << " is " << recall_val << "\n";
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/compute_groundtruth.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/compute_groundtruth.cpp
new file mode 100644
index 0000000..da32fd7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/compute_groundtruth.cpp
@@ -0,0 +1,574 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <string>
+#include <iostream>
+#include <fstream>
+#include <cassert>
+
+#include <vector>
+#include <algorithm>
+#include <cassert>
+#include <cstddef>
+#include <random>
+#include <limits>
+#include <cstring>
+#include <queue>
+#include <omp.h>
+#include <mkl.h>
+#include <boost/program_options.hpp>
+#include <unordered_map>
+#include <tsl/robin_map.h>
+#include <tsl/robin_set.h>
+
+#ifdef _WINDOWS
+#include <malloc.h>
+#else
+#include <stdlib.h>
+#endif
+#include "filter_utils.h"
+#include "utils.h"
+
+// WORKS FOR UPTO 2 BILLION POINTS (as we use INT INSTEAD OF UNSIGNED)
+
+#define PARTSIZE 10000000
+#define ALIGNMENT 512
+
+// custom types (for readability)
+typedef tsl::robin_set<std::string> label_set;
+typedef std::string path;
+
+namespace po = boost::program_options;
+
+template <class T> T div_round_up(const T numerator, const T denominator)
+{
+ return (numerator % denominator == 0) ? (numerator / denominator) : 1 + (numerator / denominator);
+}
+
+using pairIF = std::pair<size_t, float>;
+struct cmpmaxstruct
+{
+ bool operator()(const pairIF &l, const pairIF &r)
+ {
+ return l.second < r.second;
+ };
+};
+
+using maxPQIFCS = std::priority_queue<pairIF, std::vector<pairIF>, cmpmaxstruct>;
+
+template <class T> T *aligned_malloc(const size_t n, const size_t alignment)
+{
+#ifdef _WINDOWS
+ return (T *)_aligned_malloc(sizeof(T) * n, alignment);
+#else
+ return static_cast<T *>(aligned_alloc(alignment, sizeof(T) * n));
+#endif
+}
+
+inline bool custom_dist(const std::pair<uint32_t, float> &a, const std::pair<uint32_t, float> &b)
+{
+ return a.second < b.second;
+}
+
+void compute_l2sq(float *const points_l2sq, const float *const matrix, const int64_t num_points, const uint64_t dim)
+{
+ assert(points_l2sq != NULL);
+#pragma omp parallel for schedule(static, 65536)
+ for (int64_t d = 0; d < num_points; ++d)
+ points_l2sq[d] = cblas_sdot((int64_t)dim, matrix + (ptrdiff_t)d * (ptrdiff_t)dim, 1,
+ matrix + (ptrdiff_t)d * (ptrdiff_t)dim, 1);
+}
+
+void distsq_to_points(const size_t dim,
+ float *dist_matrix, // Col Major, cols are queries, rows are points
+ size_t npoints, const float *const points,
+ const float *const points_l2sq, // points in Col major
+ size_t nqueries, const float *const queries,
+ const float *const queries_l2sq, // queries in Col major
+ float *ones_vec = NULL) // Scratchspace of num_data size and init to 1.0
+{
+ bool ones_vec_alloc = false;
+ if (ones_vec == NULL)
+ {
+ ones_vec = new float[nqueries > npoints ? nqueries : npoints];
+ std::fill_n(ones_vec, nqueries > npoints ? nqueries : npoints, (float)1.0);
+ ones_vec_alloc = true;
+ }
+ cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, npoints, nqueries, dim, (float)-2.0, points, dim, queries, dim,
+ (float)0.0, dist_matrix, npoints);
+ cblas_sgemm(CblasColMajor, CblasNoTrans, CblasTrans, npoints, nqueries, 1, (float)1.0, points_l2sq, npoints,
+ ones_vec, nqueries, (float)1.0, dist_matrix, npoints);
+ cblas_sgemm(CblasColMajor, CblasNoTrans, CblasTrans, npoints, nqueries, 1, (float)1.0, ones_vec, npoints,
+ queries_l2sq, nqueries, (float)1.0, dist_matrix, npoints);
+ if (ones_vec_alloc)
+ delete[] ones_vec;
+}
+
+void inner_prod_to_points(const size_t dim,
+ float *dist_matrix, // Col Major, cols are queries, rows are points
+ size_t npoints, const float *const points, size_t nqueries, const float *const queries,
+ float *ones_vec = NULL) // Scratchspace of num_data size and init to 1.0
+{
+ bool ones_vec_alloc = false;
+ if (ones_vec == NULL)
+ {
+ ones_vec = new float[nqueries > npoints ? nqueries : npoints];
+ std::fill_n(ones_vec, nqueries > npoints ? nqueries : npoints, (float)1.0);
+ ones_vec_alloc = true;
+ }
+ cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, npoints, nqueries, dim, (float)-1.0, points, dim, queries, dim,
+ (float)0.0, dist_matrix, npoints);
+
+ if (ones_vec_alloc)
+ delete[] ones_vec;
+}
+
+void exact_knn(const size_t dim, const size_t k,
+ size_t *const closest_points, // k * num_queries preallocated, col
+ // major, queries columns
+ float *const dist_closest_points, // k * num_queries
+ // preallocated, Dist to
+ // corresponding closes_points
+ size_t npoints,
+ float *points_in, // points in Col major
+ size_t nqueries, float *queries_in,
+ diskann::Metric metric = diskann::Metric::L2) // queries in Col major
+{
+ float *points_l2sq = new float[npoints];
+ float *queries_l2sq = new float[nqueries];
+ compute_l2sq(points_l2sq, points_in, npoints, dim);
+ compute_l2sq(queries_l2sq, queries_in, nqueries, dim);
+
+ float *points = points_in;
+ float *queries = queries_in;
+
+ if (metric == diskann::Metric::COSINE)
+ { // we convert cosine distance as
+ // normalized L2 distnace
+ points = new float[npoints * dim];
+ queries = new float[nqueries * dim];
+#pragma omp parallel for schedule(static, 4096)
+ for (int64_t i = 0; i < (int64_t)npoints; i++)
+ {
+ float norm = std::sqrt(points_l2sq[i]);
+ if (norm == 0)
+ {
+ norm = std::numeric_limits<float>::epsilon();
+ }
+ for (uint32_t j = 0; j < dim; j++)
+ {
+ points[i * dim + j] = points_in[i * dim + j] / norm;
+ }
+ }
+
+#pragma omp parallel for schedule(static, 4096)
+ for (int64_t i = 0; i < (int64_t)nqueries; i++)
+ {
+ float norm = std::sqrt(queries_l2sq[i]);
+ if (norm == 0)
+ {
+ norm = std::numeric_limits<float>::epsilon();
+ }
+ for (uint32_t j = 0; j < dim; j++)
+ {
+ queries[i * dim + j] = queries_in[i * dim + j] / norm;
+ }
+ }
+ // recalculate norms after normalizing, they should all be one.
+ compute_l2sq(points_l2sq, points, npoints, dim);
+ compute_l2sq(queries_l2sq, queries, nqueries, dim);
+ }
+
+ std::cout << "Going to compute " << k << " NNs for " << nqueries << " queries over " << npoints << " points in "
+ << dim << " dimensions using";
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ std::cout << " MIPS ";
+ else if (metric == diskann::Metric::COSINE)
+ std::cout << " Cosine ";
+ else
+ std::cout << " L2 ";
+ std::cout << "distance fn. " << std::endl;
+
+ size_t q_batch_size = (1 << 9);
+ float *dist_matrix = new float[(size_t)q_batch_size * (size_t)npoints];
+
+ for (size_t b = 0; b < div_round_up(nqueries, q_batch_size); ++b)
+ {
+ int64_t q_b = b * q_batch_size;
+ int64_t q_e = ((b + 1) * q_batch_size > nqueries) ? nqueries : (b + 1) * q_batch_size;
+
+ if (metric == diskann::Metric::L2 || metric == diskann::Metric::COSINE)
+ {
+ distsq_to_points(dim, dist_matrix, npoints, points, points_l2sq, q_e - q_b,
+ queries + (ptrdiff_t)q_b * (ptrdiff_t)dim, queries_l2sq + q_b);
+ }
+ else
+ {
+ inner_prod_to_points(dim, dist_matrix, npoints, points, q_e - q_b,
+ queries + (ptrdiff_t)q_b * (ptrdiff_t)dim);
+ }
+ std::cout << "Computed distances for queries: [" << q_b << "," << q_e << ")" << std::endl;
+
+#pragma omp parallel for schedule(dynamic, 16)
+ for (long long q = q_b; q < q_e; q++)
+ {
+ maxPQIFCS point_dist;
+ for (size_t p = 0; p < k; p++)
+ point_dist.emplace(p, dist_matrix[(ptrdiff_t)p + (ptrdiff_t)(q - q_b) * (ptrdiff_t)npoints]);
+ for (size_t p = k; p < npoints; p++)
+ {
+ if (point_dist.top().second > dist_matrix[(ptrdiff_t)p + (ptrdiff_t)(q - q_b) * (ptrdiff_t)npoints])
+ point_dist.emplace(p, dist_matrix[(ptrdiff_t)p + (ptrdiff_t)(q - q_b) * (ptrdiff_t)npoints]);
+ if (point_dist.size() > k)
+ point_dist.pop();
+ }
+ for (ptrdiff_t l = 0; l < (ptrdiff_t)k; ++l)
+ {
+ closest_points[(ptrdiff_t)(k - 1 - l) + (ptrdiff_t)q * (ptrdiff_t)k] = point_dist.top().first;
+ dist_closest_points[(ptrdiff_t)(k - 1 - l) + (ptrdiff_t)q * (ptrdiff_t)k] = point_dist.top().second;
+ point_dist.pop();
+ }
+ assert(std::is_sorted(dist_closest_points + (ptrdiff_t)q * (ptrdiff_t)k,
+ dist_closest_points + (ptrdiff_t)(q + 1) * (ptrdiff_t)k));
+ }
+ std::cout << "Computed exact k-NN for queries: [" << q_b << "," << q_e << ")" << std::endl;
+ }
+
+ delete[] dist_matrix;
+
+ delete[] points_l2sq;
+ delete[] queries_l2sq;
+
+ if (metric == diskann::Metric::COSINE)
+ {
+ delete[] points;
+ delete[] queries;
+ }
+}
+
+template <typename T> inline int get_num_parts(const char *filename)
+{
+ std::ifstream reader;
+ reader.exceptions(std::ios::failbit | std::ios::badbit);
+ reader.open(filename, std::ios::binary);
+ std::cout << "Reading bin file " << filename << " ...\n";
+ int npts_i32, ndims_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&ndims_i32, sizeof(int));
+ std::cout << "#pts = " << npts_i32 << ", #dims = " << ndims_i32 << std::endl;
+ reader.close();
+ uint32_t num_parts =
+ (npts_i32 % PARTSIZE) == 0 ? npts_i32 / PARTSIZE : (uint32_t)std::floor(npts_i32 / PARTSIZE) + 1;
+ std::cout << "Number of parts: " << num_parts << std::endl;
+ return num_parts;
+}
+
+template <typename T>
+inline void load_bin_as_float(const char *filename, float *&data, size_t &npts, size_t &ndims, int part_num)
+{
+ std::ifstream reader;
+ reader.exceptions(std::ios::failbit | std::ios::badbit);
+ reader.open(filename, std::ios::binary);
+ std::cout << "Reading bin file " << filename << " ...\n";
+ int npts_i32, ndims_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&ndims_i32, sizeof(int));
+ uint64_t start_id = part_num * PARTSIZE;
+ uint64_t end_id = (std::min)(start_id + PARTSIZE, (uint64_t)npts_i32);
+ npts = end_id - start_id;
+ ndims = (uint64_t)ndims_i32;
+ std::cout << "#pts in part = " << npts << ", #dims = " << ndims << ", size = " << npts * ndims * sizeof(T) << "B"
+ << std::endl;
+
+ reader.seekg(start_id * ndims * sizeof(T) + 2 * sizeof(uint32_t), std::ios::beg);
+ T *data_T = new T[npts * ndims];
+ reader.read((char *)data_T, sizeof(T) * npts * ndims);
+ std::cout << "Finished reading part of the bin file." << std::endl;
+ reader.close();
+ data = aligned_malloc<float>(npts * ndims, ALIGNMENT);
+#pragma omp parallel for schedule(dynamic, 32768)
+ for (int64_t i = 0; i < (int64_t)npts; i++)
+ {
+ for (int64_t j = 0; j < (int64_t)ndims; j++)
+ {
+ float cur_val_float = (float)data_T[i * ndims + j];
+ std::memcpy((char *)(data + i * ndims + j), (char *)&cur_val_float, sizeof(float));
+ }
+ }
+ delete[] data_T;
+ std::cout << "Finished converting part data to float." << std::endl;
+}
+
+template <typename T> inline void save_bin(const std::string filename, T *data, size_t npts, size_t ndims)
+{
+ std::ofstream writer;
+ writer.exceptions(std::ios::failbit | std::ios::badbit);
+ writer.open(filename, std::ios::binary | std::ios::out);
+ std::cout << "Writing bin: " << filename << "\n";
+ int npts_i32 = (int)npts, ndims_i32 = (int)ndims;
+ writer.write((char *)&npts_i32, sizeof(int));
+ writer.write((char *)&ndims_i32, sizeof(int));
+ std::cout << "bin: #pts = " << npts << ", #dims = " << ndims
+ << ", size = " << npts * ndims * sizeof(T) + 2 * sizeof(int) << "B" << std::endl;
+
+ writer.write((char *)data, npts * ndims * sizeof(T));
+ writer.close();
+ std::cout << "Finished writing bin" << std::endl;
+}
+
+inline void save_groundtruth_as_one_file(const std::string filename, int32_t *data, float *distances, size_t npts,
+ size_t ndims)
+{
+ std::ofstream writer(filename, std::ios::binary | std::ios::out);
+ int npts_i32 = (int)npts, ndims_i32 = (int)ndims;
+ writer.write((char *)&npts_i32, sizeof(int));
+ writer.write((char *)&ndims_i32, sizeof(int));
+ std::cout << "Saving truthset in one file (npts, dim, npts*dim id-matrix, "
+ "npts*dim dist-matrix) with npts = "
+ << npts << ", dim = " << ndims << ", size = " << 2 * npts * ndims * sizeof(uint32_t) + 2 * sizeof(int)
+ << "B" << std::endl;
+
+ writer.write((char *)data, npts * ndims * sizeof(uint32_t));
+ writer.write((char *)distances, npts * ndims * sizeof(float));
+ writer.close();
+ std::cout << "Finished writing truthset" << std::endl;
+}
+
+template <typename T>
+std::vector<std::vector<std::pair<uint32_t, float>>> processUnfilteredParts(const std::string &base_file,
+ size_t &nqueries, size_t &npoints,
+ size_t &dim, size_t &k, float *query_data,
+ const diskann::Metric &metric,
+ std::vector<uint32_t> &location_to_tag)
+{
+ float *base_data = nullptr;
+ int num_parts = get_num_parts<T>(base_file.c_str());
+ std::vector<std::vector<std::pair<uint32_t, float>>> res(nqueries);
+ for (int p = 0; p < num_parts; p++)
+ {
+ size_t start_id = p * PARTSIZE;
+ load_bin_as_float<T>(base_file.c_str(), base_data, npoints, dim, p);
+
+ size_t *closest_points_part = new size_t[nqueries * k];
+ float *dist_closest_points_part = new float[nqueries * k];
+
+ auto part_k = k < npoints ? k : npoints;
+ exact_knn(dim, part_k, closest_points_part, dist_closest_points_part, npoints, base_data, nqueries, query_data,
+ metric);
+
+ for (size_t i = 0; i < nqueries; i++)
+ {
+ for (size_t j = 0; j < part_k; j++)
+ {
+ if (!location_to_tag.empty())
+ if (location_to_tag[closest_points_part[i * k + j] + start_id] == 0)
+ continue;
+
+ res[i].push_back(std::make_pair((uint32_t)(closest_points_part[i * part_k + j] + start_id),
+ dist_closest_points_part[i * part_k + j]));
+ }
+ }
+
+ delete[] closest_points_part;
+ delete[] dist_closest_points_part;
+
+ diskann::aligned_free(base_data);
+ }
+ return res;
+};
+
+template <typename T>
+int aux_main(const std::string &base_file, const std::string &query_file, const std::string &gt_file, size_t k,
+ const diskann::Metric &metric, const std::string &tags_file = std::string(""))
+{
+ size_t npoints, nqueries, dim;
+
+ float *query_data;
+
+ load_bin_as_float<T>(query_file.c_str(), query_data, nqueries, dim, 0);
+ if (nqueries > PARTSIZE)
+ std::cerr << "WARNING: #Queries provided (" << nqueries << ") is greater than " << PARTSIZE
+ << ". Computing GT only for the first " << PARTSIZE << " queries." << std::endl;
+
+ // load tags
+ const bool tags_enabled = tags_file.empty() ? false : true;
+ std::vector<uint32_t> location_to_tag = diskann::loadTags(tags_file, base_file);
+
+ int *closest_points = new int[nqueries * k];
+ float *dist_closest_points = new float[nqueries * k];
+
+ std::vector<std::vector<std::pair<uint32_t, float>>> results =
+ processUnfilteredParts<T>(base_file, nqueries, npoints, dim, k, query_data, metric, location_to_tag);
+
+ for (size_t i = 0; i < nqueries; i++)
+ {
+ std::vector<std::pair<uint32_t, float>> &cur_res = results[i];
+ std::sort(cur_res.begin(), cur_res.end(), custom_dist);
+ size_t j = 0;
+ for (auto iter : cur_res)
+ {
+ if (j == k)
+ break;
+ if (tags_enabled)
+ {
+ std::uint32_t index_with_tag = location_to_tag[iter.first];
+ closest_points[i * k + j] = (int32_t)index_with_tag;
+ }
+ else
+ {
+ closest_points[i * k + j] = (int32_t)iter.first;
+ }
+
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ dist_closest_points[i * k + j] = -iter.second;
+ else
+ dist_closest_points[i * k + j] = iter.second;
+
+ ++j;
+ }
+ if (j < k)
+ std::cout << "WARNING: found less than k GT entries for query " << i << std::endl;
+ }
+
+ save_groundtruth_as_one_file(gt_file, closest_points, dist_closest_points, nqueries, k);
+ delete[] closest_points;
+ delete[] dist_closest_points;
+ diskann::aligned_free(query_data);
+
+ return 0;
+}
+
+void load_truthset(const std::string &bin_file, uint32_t *&ids, float *&dists, size_t &npts, size_t &dim)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream reader(bin_file, read_blk_size);
+ diskann::cout << "Reading truthset file " << bin_file.c_str() << " ..." << std::endl;
+ size_t actual_file_size = reader.get_file_size();
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (uint32_t)npts_i32;
+ dim = (uint32_t)dim_i32;
+
+ diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "... " << std::endl;
+
+ int truthset_type = -1; // 1 means truthset has ids and distances, 2 means
+ // only ids, -1 is error
+ size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_with_dists)
+ truthset_type = 1;
+
+ size_t expected_file_size_just_ids = npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_just_ids)
+ truthset_type = 2;
+
+ if (truthset_type == -1)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. File should have bin format, with "
+ "npts followed by ngt followed by npts*ngt ids and optionally "
+ "followed by npts*ngt distance values; actual size: "
+ << actual_file_size << ", expected: " << expected_file_size_with_dists << " or "
+ << expected_file_size_just_ids;
+ diskann::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ ids = new uint32_t[npts * dim];
+ reader.read((char *)ids, npts * dim * sizeof(uint32_t));
+
+ if (truthset_type == 1)
+ {
+ dists = new float[npts * dim];
+ reader.read((char *)dists, npts * dim * sizeof(float));
+ }
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, base_file, query_file, gt_file, tags_file;
+ uint64_t K;
+
+ try
+ {
+ po::options_description desc{"Arguments"};
+
+ desc.add_options()("help,h", "Print information on arguments");
+
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(),
+ "distance function <l2/mips/cosine>");
+ desc.add_options()("base_file", po::value<std::string>(&base_file)->required(),
+ "File containing the base vectors in binary format");
+ desc.add_options()("query_file", po::value<std::string>(&query_file)->required(),
+ "File containing the query vectors in binary format");
+ desc.add_options()("gt_file", po::value<std::string>(&gt_file)->required(),
+ "File name for the writing ground truth in binary "
+ "format, please don' append .bin at end if "
+ "no filter_label or filter_label_file is provided it "
+ "will save the file with '.bin' at end."
+ "else it will save the file as filename_label.bin");
+ desc.add_options()("K", po::value<uint64_t>(&K)->required(),
+ "Number of ground truth nearest neighbors to compute");
+ desc.add_options()("tags_file", po::value<std::string>(&tags_file)->default_value(std::string()),
+ "File containing the tags in binary format");
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ if (data_type != std::string("float") && data_type != std::string("int8") && data_type != std::string("uint8"))
+ {
+ std::cout << "Unsupported type. float, int8 and uint8 types are supported." << std::endl;
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("l2"))
+ {
+ metric = diskann::Metric::L2;
+ }
+ else if (dist_fn == std::string("mips"))
+ {
+ metric = diskann::Metric::INNER_PRODUCT;
+ }
+ else if (dist_fn == std::string("cosine"))
+ {
+ metric = diskann::Metric::COSINE;
+ }
+ else
+ {
+ std::cerr << "Unsupported distance function. Use l2/mips/cosine." << std::endl;
+ return -1;
+ }
+
+ try
+ {
+ if (data_type == std::string("float"))
+ aux_main<float>(base_file, query_file, gt_file, K, metric, tags_file);
+ if (data_type == std::string("int8"))
+ aux_main<int8_t>(base_file, query_file, gt_file, K, metric, tags_file);
+ if (data_type == std::string("uint8"))
+ aux_main<uint8_t>(base_file, query_file, gt_file, K, metric, tags_file);
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Compute GT failed." << std::endl;
+ return -1;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/compute_groundtruth_for_filters.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/compute_groundtruth_for_filters.cpp
new file mode 100644
index 0000000..52e5864
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/compute_groundtruth_for_filters.cpp
@@ -0,0 +1,919 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <string>
+#include <iostream>
+#include <fstream>
+#include <cassert>
+
+#include <vector>
+#include <algorithm>
+#include <cassert>
+#include <cstddef>
+#include <random>
+#include <limits>
+#include <cstring>
+#include <queue>
+#include <omp.h>
+#include <mkl.h>
+#include <boost/program_options.hpp>
+#include <unordered_map>
+#include <tsl/robin_map.h>
+#include <tsl/robin_set.h>
+
+#ifdef _WINDOWS
+#include <malloc.h>
+#else
+#include <stdlib.h>
+#endif
+
+#include "filter_utils.h"
+#include "utils.h"
+
+// WORKS FOR UPTO 2 BILLION POINTS (as we use INT INSTEAD OF UNSIGNED)
+
+#define PARTSIZE 10000000
+#define ALIGNMENT 512
+
+// custom types (for readability)
+typedef tsl::robin_set<std::string> label_set;
+typedef std::string path;
+
+namespace po = boost::program_options;
+
+template <class T> T div_round_up(const T numerator, const T denominator)
+{
+ return (numerator % denominator == 0) ? (numerator / denominator) : 1 + (numerator / denominator);
+}
+
+using pairIF = std::pair<size_t, float>;
+struct cmpmaxstruct
+{
+ bool operator()(const pairIF &l, const pairIF &r)
+ {
+ return l.second < r.second;
+ };
+};
+
+using maxPQIFCS = std::priority_queue<pairIF, std::vector<pairIF>, cmpmaxstruct>;
+
+template <class T> T *aligned_malloc(const size_t n, const size_t alignment)
+{
+#ifdef _WINDOWS
+ return (T *)_aligned_malloc(sizeof(T) * n, alignment);
+#else
+ return static_cast<T *>(aligned_alloc(alignment, sizeof(T) * n));
+#endif
+}
+
+inline bool custom_dist(const std::pair<uint32_t, float> &a, const std::pair<uint32_t, float> &b)
+{
+ return a.second < b.second;
+}
+
+void compute_l2sq(float *const points_l2sq, const float *const matrix, const int64_t num_points, const uint64_t dim)
+{
+ assert(points_l2sq != NULL);
+#pragma omp parallel for schedule(static, 65536)
+ for (int64_t d = 0; d < num_points; ++d)
+ points_l2sq[d] = cblas_sdot((int64_t)dim, matrix + (ptrdiff_t)d * (ptrdiff_t)dim, 1,
+ matrix + (ptrdiff_t)d * (ptrdiff_t)dim, 1);
+}
+
+void distsq_to_points(const size_t dim,
+ float *dist_matrix, // Col Major, cols are queries, rows are points
+ size_t npoints, const float *const points,
+ const float *const points_l2sq, // points in Col major
+ size_t nqueries, const float *const queries,
+ const float *const queries_l2sq, // queries in Col major
+ float *ones_vec = NULL) // Scratchspace of num_data size and init to 1.0
+{
+ bool ones_vec_alloc = false;
+ if (ones_vec == NULL)
+ {
+ ones_vec = new float[nqueries > npoints ? nqueries : npoints];
+ std::fill_n(ones_vec, nqueries > npoints ? nqueries : npoints, (float)1.0);
+ ones_vec_alloc = true;
+ }
+ cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, npoints, nqueries, dim, (float)-2.0, points, dim, queries, dim,
+ (float)0.0, dist_matrix, npoints);
+ cblas_sgemm(CblasColMajor, CblasNoTrans, CblasTrans, npoints, nqueries, 1, (float)1.0, points_l2sq, npoints,
+ ones_vec, nqueries, (float)1.0, dist_matrix, npoints);
+ cblas_sgemm(CblasColMajor, CblasNoTrans, CblasTrans, npoints, nqueries, 1, (float)1.0, ones_vec, npoints,
+ queries_l2sq, nqueries, (float)1.0, dist_matrix, npoints);
+ if (ones_vec_alloc)
+ delete[] ones_vec;
+}
+
+void inner_prod_to_points(const size_t dim,
+ float *dist_matrix, // Col Major, cols are queries, rows are points
+ size_t npoints, const float *const points, size_t nqueries, const float *const queries,
+ float *ones_vec = NULL) // Scratchspace of num_data size and init to 1.0
+{
+ bool ones_vec_alloc = false;
+ if (ones_vec == NULL)
+ {
+ ones_vec = new float[nqueries > npoints ? nqueries : npoints];
+ std::fill_n(ones_vec, nqueries > npoints ? nqueries : npoints, (float)1.0);
+ ones_vec_alloc = true;
+ }
+ cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, npoints, nqueries, dim, (float)-1.0, points, dim, queries, dim,
+ (float)0.0, dist_matrix, npoints);
+
+ if (ones_vec_alloc)
+ delete[] ones_vec;
+}
+
+void exact_knn(const size_t dim, const size_t k,
+ size_t *const closest_points, // k * num_queries preallocated, col
+ // major, queries columns
+ float *const dist_closest_points, // k * num_queries
+ // preallocated, Dist to
+ // corresponding closes_points
+ size_t npoints,
+ float *points_in, // points in Col major
+ size_t nqueries, float *queries_in,
+ diskann::Metric metric = diskann::Metric::L2) // queries in Col major
+{
+ float *points_l2sq = new float[npoints];
+ float *queries_l2sq = new float[nqueries];
+ compute_l2sq(points_l2sq, points_in, npoints, dim);
+ compute_l2sq(queries_l2sq, queries_in, nqueries, dim);
+
+ float *points = points_in;
+ float *queries = queries_in;
+
+ if (metric == diskann::Metric::COSINE)
+ { // we convert cosine distance as
+ // normalized L2 distnace
+ points = new float[npoints * dim];
+ queries = new float[nqueries * dim];
+#pragma omp parallel for schedule(static, 4096)
+ for (int64_t i = 0; i < (int64_t)npoints; i++)
+ {
+ float norm = std::sqrt(points_l2sq[i]);
+ if (norm == 0)
+ {
+ norm = std::numeric_limits<float>::epsilon();
+ }
+ for (uint32_t j = 0; j < dim; j++)
+ {
+ points[i * dim + j] = points_in[i * dim + j] / norm;
+ }
+ }
+
+#pragma omp parallel for schedule(static, 4096)
+ for (int64_t i = 0; i < (int64_t)nqueries; i++)
+ {
+ float norm = std::sqrt(queries_l2sq[i]);
+ if (norm == 0)
+ {
+ norm = std::numeric_limits<float>::epsilon();
+ }
+ for (uint32_t j = 0; j < dim; j++)
+ {
+ queries[i * dim + j] = queries_in[i * dim + j] / norm;
+ }
+ }
+ // recalculate norms after normalizing, they should all be one.
+ compute_l2sq(points_l2sq, points, npoints, dim);
+ compute_l2sq(queries_l2sq, queries, nqueries, dim);
+ }
+
+ std::cout << "Going to compute " << k << " NNs for " << nqueries << " queries over " << npoints << " points in "
+ << dim << " dimensions using";
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ std::cout << " MIPS ";
+ else if (metric == diskann::Metric::COSINE)
+ std::cout << " Cosine ";
+ else
+ std::cout << " L2 ";
+ std::cout << "distance fn. " << std::endl;
+
+ size_t q_batch_size = (1 << 9);
+ float *dist_matrix = new float[(size_t)q_batch_size * (size_t)npoints];
+
+ for (uint64_t b = 0; b < div_round_up(nqueries, q_batch_size); ++b)
+ {
+ int64_t q_b = b * q_batch_size;
+ int64_t q_e = ((b + 1) * q_batch_size > nqueries) ? nqueries : (b + 1) * q_batch_size;
+
+ if (metric == diskann::Metric::L2 || metric == diskann::Metric::COSINE)
+ {
+ distsq_to_points(dim, dist_matrix, npoints, points, points_l2sq, q_e - q_b,
+ queries + (ptrdiff_t)q_b * (ptrdiff_t)dim, queries_l2sq + q_b);
+ }
+ else
+ {
+ inner_prod_to_points(dim, dist_matrix, npoints, points, q_e - q_b,
+ queries + (ptrdiff_t)q_b * (ptrdiff_t)dim);
+ }
+ std::cout << "Computed distances for queries: [" << q_b << "," << q_e << ")" << std::endl;
+
+#pragma omp parallel for schedule(dynamic, 16)
+ for (long long q = q_b; q < q_e; q++)
+ {
+ maxPQIFCS point_dist;
+ for (size_t p = 0; p < k; p++)
+ point_dist.emplace(p, dist_matrix[(ptrdiff_t)p + (ptrdiff_t)(q - q_b) * (ptrdiff_t)npoints]);
+ for (size_t p = k; p < npoints; p++)
+ {
+ if (point_dist.top().second > dist_matrix[(ptrdiff_t)p + (ptrdiff_t)(q - q_b) * (ptrdiff_t)npoints])
+ point_dist.emplace(p, dist_matrix[(ptrdiff_t)p + (ptrdiff_t)(q - q_b) * (ptrdiff_t)npoints]);
+ if (point_dist.size() > k)
+ point_dist.pop();
+ }
+ for (ptrdiff_t l = 0; l < (ptrdiff_t)k; ++l)
+ {
+ closest_points[(ptrdiff_t)(k - 1 - l) + (ptrdiff_t)q * (ptrdiff_t)k] = point_dist.top().first;
+ dist_closest_points[(ptrdiff_t)(k - 1 - l) + (ptrdiff_t)q * (ptrdiff_t)k] = point_dist.top().second;
+ point_dist.pop();
+ }
+ assert(std::is_sorted(dist_closest_points + (ptrdiff_t)q * (ptrdiff_t)k,
+ dist_closest_points + (ptrdiff_t)(q + 1) * (ptrdiff_t)k));
+ }
+ std::cout << "Computed exact k-NN for queries: [" << q_b << "," << q_e << ")" << std::endl;
+ }
+
+ delete[] dist_matrix;
+
+ delete[] points_l2sq;
+ delete[] queries_l2sq;
+
+ if (metric == diskann::Metric::COSINE)
+ {
+ delete[] points;
+ delete[] queries;
+ }
+}
+
+template <typename T> inline int get_num_parts(const char *filename)
+{
+ std::ifstream reader;
+ reader.exceptions(std::ios::failbit | std::ios::badbit);
+ reader.open(filename, std::ios::binary);
+ std::cout << "Reading bin file " << filename << " ...\n";
+ int npts_i32, ndims_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&ndims_i32, sizeof(int));
+ std::cout << "#pts = " << npts_i32 << ", #dims = " << ndims_i32 << std::endl;
+ reader.close();
+ int num_parts = (npts_i32 % PARTSIZE) == 0 ? npts_i32 / PARTSIZE : (uint32_t)std::floor(npts_i32 / PARTSIZE) + 1;
+ std::cout << "Number of parts: " << num_parts << std::endl;
+ return num_parts;
+}
+
+template <typename T>
+inline void load_bin_as_float(const char *filename, float *&data, size_t &npts_u64, size_t &ndims_u64, int part_num)
+{
+ std::ifstream reader;
+ reader.exceptions(std::ios::failbit | std::ios::badbit);
+ reader.open(filename, std::ios::binary);
+ std::cout << "Reading bin file " << filename << " ...\n";
+ int npts_i32, ndims_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&ndims_i32, sizeof(int));
+ uint64_t start_id = part_num * PARTSIZE;
+ uint64_t end_id = (std::min)(start_id + PARTSIZE, (uint64_t)npts_i32);
+ npts_u64 = end_id - start_id;
+ ndims_u64 = (uint64_t)ndims_i32;
+ std::cout << "#pts in part = " << npts_u64 << ", #dims = " << ndims_u64
+ << ", size = " << npts_u64 * ndims_u64 * sizeof(T) << "B" << std::endl;
+
+ reader.seekg(start_id * ndims_u64 * sizeof(T) + 2 * sizeof(uint32_t), std::ios::beg);
+ T *data_T = new T[npts_u64 * ndims_u64];
+ reader.read((char *)data_T, sizeof(T) * npts_u64 * ndims_u64);
+ std::cout << "Finished reading part of the bin file." << std::endl;
+ reader.close();
+ data = aligned_malloc<float>(npts_u64 * ndims_u64, ALIGNMENT);
+#pragma omp parallel for schedule(dynamic, 32768)
+ for (int64_t i = 0; i < (int64_t)npts_u64; i++)
+ {
+ for (int64_t j = 0; j < (int64_t)ndims_u64; j++)
+ {
+ float cur_val_float = (float)data_T[i * ndims_u64 + j];
+ std::memcpy((char *)(data + i * ndims_u64 + j), (char *)&cur_val_float, sizeof(float));
+ }
+ }
+ delete[] data_T;
+ std::cout << "Finished converting part data to float." << std::endl;
+}
+
+template <typename T>
+inline std::vector<size_t> load_filtered_bin_as_float(const char *filename, float *&data, size_t &npts, size_t &ndims,
+ int part_num, const char *label_file,
+ const std::string &filter_label,
+ const std::string &universal_label, size_t &npoints_filt,
+ std::vector<std::vector<std::string>> &pts_to_labels)
+{
+ std::ifstream reader(filename, std::ios::binary);
+ if (reader.fail())
+ {
+ throw diskann::ANNException(std::string("Failed to open file ") + filename, -1);
+ }
+
+ std::cout << "Reading bin file " << filename << " ...\n";
+ int npts_i32, ndims_i32;
+ std::vector<size_t> rev_map;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&ndims_i32, sizeof(int));
+ uint64_t start_id = part_num * PARTSIZE;
+ uint64_t end_id = (std::min)(start_id + PARTSIZE, (uint64_t)npts_i32);
+ npts = end_id - start_id;
+ ndims = (uint32_t)ndims_i32;
+ uint64_t nptsuint64_t = (uint64_t)npts;
+ uint64_t ndimsuint64_t = (uint64_t)ndims;
+ npoints_filt = 0;
+ std::cout << "#pts in part = " << npts << ", #dims = " << ndims
+ << ", size = " << nptsuint64_t * ndimsuint64_t * sizeof(T) << "B" << std::endl;
+ std::cout << "start and end ids: " << start_id << ", " << end_id << std::endl;
+ reader.seekg(start_id * ndims * sizeof(T) + 2 * sizeof(uint32_t), std::ios::beg);
+
+ T *data_T = new T[nptsuint64_t * ndimsuint64_t];
+ reader.read((char *)data_T, sizeof(T) * nptsuint64_t * ndimsuint64_t);
+ std::cout << "Finished reading part of the bin file." << std::endl;
+ reader.close();
+
+ data = aligned_malloc<float>(nptsuint64_t * ndimsuint64_t, ALIGNMENT);
+
+ for (int64_t i = 0; i < (int64_t)nptsuint64_t; i++)
+ {
+ if (std::find(pts_to_labels[start_id + i].begin(), pts_to_labels[start_id + i].end(), filter_label) !=
+ pts_to_labels[start_id + i].end() ||
+ std::find(pts_to_labels[start_id + i].begin(), pts_to_labels[start_id + i].end(), universal_label) !=
+ pts_to_labels[start_id + i].end())
+ {
+ rev_map.push_back(start_id + i);
+ for (int64_t j = 0; j < (int64_t)ndimsuint64_t; j++)
+ {
+ float cur_val_float = (float)data_T[i * ndimsuint64_t + j];
+ std::memcpy((char *)(data + npoints_filt * ndimsuint64_t + j), (char *)&cur_val_float, sizeof(float));
+ }
+ npoints_filt++;
+ }
+ }
+ delete[] data_T;
+ std::cout << "Finished converting part data to float.. identified " << npoints_filt
+ << " points matching the filter." << std::endl;
+ return rev_map;
+}
+
+template <typename T> inline void save_bin(const std::string filename, T *data, size_t npts, size_t ndims)
+{
+ std::ofstream writer;
+ writer.exceptions(std::ios::failbit | std::ios::badbit);
+ writer.open(filename, std::ios::binary | std::ios::out);
+ std::cout << "Writing bin: " << filename << "\n";
+ int npts_i32 = (int)npts, ndims_i32 = (int)ndims;
+ writer.write((char *)&npts_i32, sizeof(int));
+ writer.write((char *)&ndims_i32, sizeof(int));
+ std::cout << "bin: #pts = " << npts << ", #dims = " << ndims
+ << ", size = " << npts * ndims * sizeof(T) + 2 * sizeof(int) << "B" << std::endl;
+
+ writer.write((char *)data, npts * ndims * sizeof(T));
+ writer.close();
+ std::cout << "Finished writing bin" << std::endl;
+}
+
+inline void save_groundtruth_as_one_file(const std::string filename, int32_t *data, float *distances, size_t npts,
+ size_t ndims)
+{
+ std::ofstream writer(filename, std::ios::binary | std::ios::out);
+ int npts_i32 = (int)npts, ndims_i32 = (int)ndims;
+ writer.write((char *)&npts_i32, sizeof(int));
+ writer.write((char *)&ndims_i32, sizeof(int));
+ std::cout << "Saving truthset in one file (npts, dim, npts*dim id-matrix, "
+ "npts*dim dist-matrix) with npts = "
+ << npts << ", dim = " << ndims << ", size = " << 2 * npts * ndims * sizeof(uint32_t) + 2 * sizeof(int)
+ << "B" << std::endl;
+
+ writer.write((char *)data, npts * ndims * sizeof(uint32_t));
+ writer.write((char *)distances, npts * ndims * sizeof(float));
+ writer.close();
+ std::cout << "Finished writing truthset" << std::endl;
+}
+
+inline void parse_label_file_into_vec(size_t &line_cnt, const std::string &map_file,
+ std::vector<std::vector<std::string>> &pts_to_labels)
+{
+ std::ifstream infile(map_file);
+ std::string line, token;
+ std::set<std::string> labels;
+ infile.clear();
+ infile.seekg(0, std::ios::beg);
+ while (std::getline(infile, line))
+ {
+ std::istringstream iss(line);
+ std::vector<std::string> lbls(0);
+
+ getline(iss, token, '\t');
+ std::istringstream new_iss(token);
+ while (getline(new_iss, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ lbls.push_back(token);
+ labels.insert(token);
+ }
+ std::sort(lbls.begin(), lbls.end());
+ pts_to_labels.push_back(lbls);
+ }
+ std::cout << "Identified " << labels.size() << " distinct label(s), and populated labels for "
+ << pts_to_labels.size() << " points" << std::endl;
+}
+
+template <typename T>
+std::vector<std::vector<std::pair<uint32_t, float>>> processUnfilteredParts(const std::string &base_file,
+ size_t &nqueries, size_t &npoints,
+ size_t &dim, size_t &k, float *query_data,
+ const diskann::Metric &metric,
+ std::vector<uint32_t> &location_to_tag)
+{
+ float *base_data = nullptr;
+ int num_parts = get_num_parts<T>(base_file.c_str());
+ std::vector<std::vector<std::pair<uint32_t, float>>> res(nqueries);
+ for (int p = 0; p < num_parts; p++)
+ {
+ size_t start_id = p * PARTSIZE;
+ load_bin_as_float<T>(base_file.c_str(), base_data, npoints, dim, p);
+
+ size_t *closest_points_part = new size_t[nqueries * k];
+ float *dist_closest_points_part = new float[nqueries * k];
+
+ auto part_k = k < npoints ? k : npoints;
+ exact_knn(dim, part_k, closest_points_part, dist_closest_points_part, npoints, base_data, nqueries, query_data,
+ metric);
+
+ for (size_t i = 0; i < nqueries; i++)
+ {
+ for (uint64_t j = 0; j < part_k; j++)
+ {
+ if (!location_to_tag.empty())
+ if (location_to_tag[closest_points_part[i * k + j] + start_id] == 0)
+ continue;
+
+ res[i].push_back(std::make_pair((uint32_t)(closest_points_part[i * part_k + j] + start_id),
+ dist_closest_points_part[i * part_k + j]));
+ }
+ }
+
+ delete[] closest_points_part;
+ delete[] dist_closest_points_part;
+
+ diskann::aligned_free(base_data);
+ }
+ return res;
+};
+
+template <typename T>
+std::vector<std::vector<std::pair<uint32_t, float>>> processFilteredParts(
+ const std::string &base_file, const std::string &label_file, const std::string &filter_label,
+ const std::string &universal_label, size_t &nqueries, size_t &npoints, size_t &dim, size_t &k, float *query_data,
+ const diskann::Metric &metric, std::vector<uint32_t> &location_to_tag)
+{
+ size_t npoints_filt = 0;
+ float *base_data = nullptr;
+ std::vector<std::vector<std::pair<uint32_t, float>>> res(nqueries);
+ int num_parts = get_num_parts<T>(base_file.c_str());
+
+ std::vector<std::vector<std::string>> pts_to_labels;
+ if (filter_label != "")
+ parse_label_file_into_vec(npoints, label_file, pts_to_labels);
+
+ for (int p = 0; p < num_parts; p++)
+ {
+ size_t start_id = p * PARTSIZE;
+ std::vector<size_t> rev_map;
+ if (filter_label != "")
+ rev_map = load_filtered_bin_as_float<T>(base_file.c_str(), base_data, npoints, dim, p, label_file.c_str(),
+ filter_label, universal_label, npoints_filt, pts_to_labels);
+ size_t *closest_points_part = new size_t[nqueries * k];
+ float *dist_closest_points_part = new float[nqueries * k];
+
+ auto part_k = k < npoints_filt ? k : npoints_filt;
+ if (npoints_filt > 0)
+ {
+ exact_knn(dim, part_k, closest_points_part, dist_closest_points_part, npoints_filt, base_data, nqueries,
+ query_data, metric);
+ }
+
+ for (size_t i = 0; i < nqueries; i++)
+ {
+ for (uint64_t j = 0; j < part_k; j++)
+ {
+ if (!location_to_tag.empty())
+ if (location_to_tag[closest_points_part[i * k + j] + start_id] == 0)
+ continue;
+
+ res[i].push_back(std::make_pair((uint32_t)(rev_map[closest_points_part[i * part_k + j]]),
+ dist_closest_points_part[i * part_k + j]));
+ }
+ }
+
+ delete[] closest_points_part;
+ delete[] dist_closest_points_part;
+
+ diskann::aligned_free(base_data);
+ }
+ return res;
+};
+
+template <typename T>
+int aux_main(const std::string &base_file, const std::string &label_file, const std::string &query_file,
+ const std::string &gt_file, size_t k, const std::string &universal_label, const diskann::Metric &metric,
+ const std::string &filter_label, const std::string &tags_file = std::string(""))
+{
+ size_t npoints, nqueries, dim;
+
+ float *query_data = nullptr;
+
+ load_bin_as_float<T>(query_file.c_str(), query_data, nqueries, dim, 0);
+ if (nqueries > PARTSIZE)
+ std::cerr << "WARNING: #Queries provided (" << nqueries << ") is greater than " << PARTSIZE
+ << ". Computing GT only for the first " << PARTSIZE << " queries." << std::endl;
+
+ // load tags
+ const bool tags_enabled = tags_file.empty() ? false : true;
+ std::vector<uint32_t> location_to_tag = diskann::loadTags(tags_file, base_file);
+
+ int *closest_points = new int[nqueries * k];
+ float *dist_closest_points = new float[nqueries * k];
+
+ std::vector<std::vector<std::pair<uint32_t, float>>> results;
+ if (filter_label == "")
+ {
+ results = processUnfilteredParts<T>(base_file, nqueries, npoints, dim, k, query_data, metric, location_to_tag);
+ }
+ else
+ {
+ results = processFilteredParts<T>(base_file, label_file, filter_label, universal_label, nqueries, npoints, dim,
+ k, query_data, metric, location_to_tag);
+ }
+
+ for (size_t i = 0; i < nqueries; i++)
+ {
+ std::vector<std::pair<uint32_t, float>> &cur_res = results[i];
+ std::sort(cur_res.begin(), cur_res.end(), custom_dist);
+ size_t j = 0;
+ for (auto iter : cur_res)
+ {
+ if (j == k)
+ break;
+ if (tags_enabled)
+ {
+ std::uint32_t index_with_tag = location_to_tag[iter.first];
+ closest_points[i * k + j] = (int32_t)index_with_tag;
+ }
+ else
+ {
+ closest_points[i * k + j] = (int32_t)iter.first;
+ }
+
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ dist_closest_points[i * k + j] = -iter.second;
+ else
+ dist_closest_points[i * k + j] = iter.second;
+
+ ++j;
+ }
+ if (j < k)
+ std::cout << "WARNING: found less than k GT entries for query " << i << std::endl;
+ }
+
+ save_groundtruth_as_one_file(gt_file, closest_points, dist_closest_points, nqueries, k);
+ delete[] closest_points;
+ delete[] dist_closest_points;
+ diskann::aligned_free(query_data);
+
+ return 0;
+}
+
+void load_truthset(const std::string &bin_file, uint32_t *&ids, float *&dists, size_t &npts, size_t &dim)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream reader(bin_file, read_blk_size);
+ diskann::cout << "Reading truthset file " << bin_file.c_str() << " ..." << std::endl;
+ size_t actual_file_size = reader.get_file_size();
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (uint32_t)npts_i32;
+ dim = (uint32_t)dim_i32;
+
+ diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "... " << std::endl;
+
+ int truthset_type = -1; // 1 means truthset has ids and distances, 2 means
+ // only ids, -1 is error
+ size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_with_dists)
+ truthset_type = 1;
+
+ size_t expected_file_size_just_ids = npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_just_ids)
+ truthset_type = 2;
+
+ if (truthset_type == -1)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. File should have bin format, with "
+ "npts followed by ngt followed by npts*ngt ids and optionally "
+ "followed by npts*ngt distance values; actual size: "
+ << actual_file_size << ", expected: " << expected_file_size_with_dists << " or "
+ << expected_file_size_just_ids;
+ diskann::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ ids = new uint32_t[npts * dim];
+ reader.read((char *)ids, npts * dim * sizeof(uint32_t));
+
+ if (truthset_type == 1)
+ {
+ dists = new float[npts * dim];
+ reader.read((char *)dists, npts * dim * sizeof(float));
+ }
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, dist_fn, base_file, query_file, gt_file, tags_file, label_file, filter_label,
+ universal_label, filter_label_file;
+ uint64_t K;
+
+ try
+ {
+ po::options_description desc{"Arguments"};
+
+ desc.add_options()("help,h", "Print information on arguments");
+
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("dist_fn", po::value<std::string>(&dist_fn)->required(), "distance function <l2/mips>");
+ desc.add_options()("base_file", po::value<std::string>(&base_file)->required(),
+ "File containing the base vectors in binary format");
+ desc.add_options()("query_file", po::value<std::string>(&query_file)->required(),
+ "File containing the query vectors in binary format");
+ desc.add_options()("label_file", po::value<std::string>(&label_file)->default_value(""),
+ "Input labels file in txt format if present");
+ desc.add_options()("filter_label", po::value<std::string>(&filter_label)->default_value(""),
+ "Input filter label if doing filtered groundtruth");
+ desc.add_options()("universal_label", po::value<std::string>(&universal_label)->default_value(""),
+ "Universal label, if using it, only in conjunction with label_file");
+ desc.add_options()("gt_file", po::value<std::string>(&gt_file)->required(),
+ "File name for the writing ground truth in binary "
+ "format, please don' append .bin at end if "
+ "no filter_label or filter_label_file is provided it "
+ "will save the file with '.bin' at end."
+ "else it will save the file as filename_label.bin");
+ desc.add_options()("K", po::value<uint64_t>(&K)->required(),
+ "Number of ground truth nearest neighbors to compute");
+ desc.add_options()("tags_file", po::value<std::string>(&tags_file)->default_value(std::string()),
+ "File containing the tags in binary format");
+ desc.add_options()("filter_label_file",
+ po::value<std::string>(&filter_label_file)->default_value(std::string("")),
+ "Filter file for Queries for Filtered Search ");
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ if (data_type != std::string("float") && data_type != std::string("int8") && data_type != std::string("uint8"))
+ {
+ std::cout << "Unsupported type. float, int8 and uint8 types are supported." << std::endl;
+ return -1;
+ }
+
+ if (filter_label != "" && filter_label_file != "")
+ {
+ std::cerr << "Only one of filter_label and query_filters_file should be provided" << std::endl;
+ return -1;
+ }
+
+ diskann::Metric metric;
+ if (dist_fn == std::string("l2"))
+ {
+ metric = diskann::Metric::L2;
+ }
+ else if (dist_fn == std::string("mips"))
+ {
+ metric = diskann::Metric::INNER_PRODUCT;
+ }
+ else if (dist_fn == std::string("cosine"))
+ {
+ metric = diskann::Metric::COSINE;
+ }
+ else
+ {
+ std::cerr << "Unsupported distance function. Use l2/mips/cosine." << std::endl;
+ return -1;
+ }
+
+ std::vector<std::string> filter_labels;
+ if (filter_label != "")
+ {
+ filter_labels.push_back(filter_label);
+ }
+ else if (filter_label_file != "")
+ {
+ filter_labels = read_file_to_vector_of_strings(filter_label_file, false);
+ }
+
+ // only when there is no filter label or 1 filter label for all queries
+ if (filter_labels.size() == 1)
+ {
+ try
+ {
+ if (data_type == std::string("float"))
+ aux_main<float>(base_file, label_file, query_file, gt_file, K, universal_label, metric,
+ filter_labels[0], tags_file);
+ if (data_type == std::string("int8"))
+ aux_main<int8_t>(base_file, label_file, query_file, gt_file, K, universal_label, metric,
+ filter_labels[0], tags_file);
+ if (data_type == std::string("uint8"))
+ aux_main<uint8_t>(base_file, label_file, query_file, gt_file, K, universal_label, metric,
+ filter_labels[0], tags_file);
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Compute GT failed." << std::endl;
+ return -1;
+ }
+ }
+ else
+ { // Each query has its own filter label
+ // Split up data and query bins into label specific ones
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points;
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_queries;
+
+ label_set all_labels;
+ for (size_t i = 0; i < filter_labels.size(); i++)
+ {
+ std::string label = filter_labels[i];
+ all_labels.insert(label);
+
+ if (labels_to_number_of_queries.find(label) == labels_to_number_of_queries.end())
+ {
+ labels_to_number_of_queries[label] = 0;
+ }
+ labels_to_number_of_queries[label] += 1;
+ }
+
+ size_t npoints;
+ std::vector<std::vector<std::string>> point_to_labels;
+ parse_label_file_into_vec(npoints, label_file, point_to_labels);
+ std::vector<label_set> point_ids_to_labels(point_to_labels.size());
+ std::vector<label_set> query_ids_to_labels(filter_labels.size());
+
+ for (size_t i = 0; i < point_to_labels.size(); i++)
+ {
+ for (size_t j = 0; j < point_to_labels[i].size(); j++)
+ {
+ std::string label = point_to_labels[i][j];
+ if (all_labels.find(label) != all_labels.end())
+ {
+ point_ids_to_labels[i].insert(point_to_labels[i][j]);
+ if (labels_to_number_of_points.find(label) == labels_to_number_of_points.end())
+ {
+ labels_to_number_of_points[label] = 0;
+ }
+ labels_to_number_of_points[label] += 1;
+ }
+ }
+ }
+
+ for (size_t i = 0; i < filter_labels.size(); i++)
+ {
+ query_ids_to_labels[i].insert(filter_labels[i]);
+ }
+
+ tsl::robin_map<std::string, std::vector<uint32_t>> label_id_to_orig_id;
+ tsl::robin_map<std::string, std::vector<uint32_t>> label_query_id_to_orig_id;
+
+ if (data_type == std::string("float"))
+ {
+ label_id_to_orig_id = diskann::generate_label_specific_vector_files_compat<float>(
+ base_file, labels_to_number_of_points, point_ids_to_labels, all_labels);
+
+ label_query_id_to_orig_id = diskann::generate_label_specific_vector_files_compat<float>(
+ query_file, labels_to_number_of_queries, query_ids_to_labels,
+ all_labels); // query_filters acts like query_ids_to_labels
+ }
+ else if (data_type == std::string("int8"))
+ {
+ label_id_to_orig_id = diskann::generate_label_specific_vector_files_compat<int8_t>(
+ base_file, labels_to_number_of_points, point_ids_to_labels, all_labels);
+
+ label_query_id_to_orig_id = diskann::generate_label_specific_vector_files_compat<int8_t>(
+ query_file, labels_to_number_of_queries, query_ids_to_labels,
+ all_labels); // query_filters acts like query_ids_to_labels
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ label_id_to_orig_id = diskann::generate_label_specific_vector_files_compat<uint8_t>(
+ base_file, labels_to_number_of_points, point_ids_to_labels, all_labels);
+
+ label_query_id_to_orig_id = diskann::generate_label_specific_vector_files_compat<uint8_t>(
+ query_file, labels_to_number_of_queries, query_ids_to_labels,
+ all_labels); // query_filters acts like query_ids_to_labels
+ }
+ else
+ {
+ diskann::cerr << "Invalid data type" << std::endl;
+ return -1;
+ }
+
+ // Generate label specific ground truths
+
+ try
+ {
+ for (const auto &label : all_labels)
+ {
+ std::string filtered_base_file = base_file + "_" + label;
+ std::string filtered_query_file = query_file + "_" + label;
+ std::string filtered_gt_file = gt_file + "_" + label;
+ if (data_type == std::string("float"))
+ aux_main<float>(filtered_base_file, "", filtered_query_file, filtered_gt_file, K, "", metric, "");
+ if (data_type == std::string("int8"))
+ aux_main<int8_t>(filtered_base_file, "", filtered_query_file, filtered_gt_file, K, "", metric, "");
+ if (data_type == std::string("uint8"))
+ aux_main<uint8_t>(filtered_base_file, "", filtered_query_file, filtered_gt_file, K, "", metric, "");
+ }
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Compute GT failed." << std::endl;
+ return -1;
+ }
+
+ // Combine the label specific ground truths to produce a single GT file
+
+ uint32_t *gt_ids = nullptr;
+ float *gt_dists = nullptr;
+ size_t gt_num, gt_dim;
+
+ std::vector<std::vector<int32_t>> final_gt_ids;
+ std::vector<std::vector<float>> final_gt_dists;
+
+ uint32_t query_num = 0;
+ for (const auto &lbl : all_labels)
+ {
+ query_num += labels_to_number_of_queries[lbl];
+ }
+
+ for (uint32_t i = 0; i < query_num; i++)
+ {
+ final_gt_ids.push_back(std::vector<int32_t>(K));
+ final_gt_dists.push_back(std::vector<float>(K));
+ }
+
+ for (const auto &lbl : all_labels)
+ {
+ std::string filtered_gt_file = gt_file + "_" + lbl;
+ load_truthset(filtered_gt_file, gt_ids, gt_dists, gt_num, gt_dim);
+
+ for (uint32_t i = 0; i < labels_to_number_of_queries[lbl]; i++)
+ {
+ uint32_t orig_query_id = label_query_id_to_orig_id[lbl][i];
+ for (uint64_t j = 0; j < K; j++)
+ {
+ final_gt_ids[orig_query_id][j] = label_id_to_orig_id[lbl][gt_ids[i * K + j]];
+ final_gt_dists[orig_query_id][j] = gt_dists[i * K + j];
+ }
+ }
+ }
+
+ int32_t *closest_points = new int32_t[query_num * K];
+ float *dist_closest_points = new float[query_num * K];
+
+ for (uint32_t i = 0; i < query_num; i++)
+ {
+ for (uint32_t j = 0; j < K; j++)
+ {
+ closest_points[i * K + j] = final_gt_ids[i][j];
+ dist_closest_points[i * K + j] = final_gt_dists[i][j];
+ }
+ }
+
+ save_groundtruth_as_one_file(gt_file, closest_points, dist_closest_points, query_num, K);
+
+ // cleanup artifacts
+ std::cout << "Cleaning up artifacts..." << std::endl;
+ tsl::robin_set<std::string> paths_to_clean{gt_file, base_file, query_file};
+ clean_up_artifacts(paths_to_clean, all_labels);
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/count_bfs_levels.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/count_bfs_levels.cpp
new file mode 100644
index 0000000..6dd2d62
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/count_bfs_levels.cpp
@@ -0,0 +1,82 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <cstring>
+#include <iomanip>
+#include <algorithm>
+#include <numeric>
+#include <omp.h>
+#include <set>
+#include <string.h>
+#include <boost/program_options.hpp>
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+#endif
+
+#include "utils.h"
+#include "index.h"
+#include "memory_mapper.h"
+
+namespace po = boost::program_options;
+
+template <typename T> void bfs_count(const std::string &index_path, uint32_t data_dims)
+{
+ using TagT = uint32_t;
+ using LabelT = uint32_t;
+ diskann::Index<T, TagT, LabelT> index(diskann::Metric::L2, data_dims, 0, nullptr, nullptr, 0, false, false, false,
+ false, 0, false);
+ std::cout << "Index class instantiated" << std::endl;
+ index.load(index_path.c_str(), 1, 100);
+ std::cout << "Index loaded" << std::endl;
+ index.count_nodes_at_bfs_levels();
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, index_path_prefix;
+ uint32_t data_dims;
+
+ po::options_description desc{"Arguments"};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("index_path_prefix", po::value<std::string>(&index_path_prefix)->required(),
+ "Path prefix to the index");
+ desc.add_options()("data_dims", po::value<uint32_t>(&data_dims)->required(), "Dimensionality of the data");
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ try
+ {
+ if (data_type == std::string("int8"))
+ bfs_count<int8_t>(index_path_prefix, data_dims);
+ else if (data_type == std::string("uint8"))
+ bfs_count<uint8_t>(index_path_prefix, data_dims);
+ if (data_type == std::string("float"))
+ bfs_count<float>(index_path_prefix, data_dims);
+ }
+ catch (std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index BFS failed." << std::endl;
+ return -1;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/create_disk_layout.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/create_disk_layout.cpp
new file mode 100644
index 0000000..f494c12
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/create_disk_layout.cpp
@@ -0,0 +1,48 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <cmath>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <limits>
+#include <vector>
+
+#include "utils.h"
+#include "disk_utils.h"
+#include "cached_io.h"
+
+template <typename T> int create_disk_layout(char **argv)
+{
+ std::string base_file(argv[2]);
+ std::string vamana_file(argv[3]);
+ std::string output_file(argv[4]);
+ diskann::create_disk_layout<T>(base_file, vamana_file, output_file);
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 5)
+ {
+ std::cout << argv[0]
+ << " data_type <float/int8/uint8> data_bin "
+ "vamana_index_file output_diskann_index_file"
+ << std::endl;
+ exit(-1);
+ }
+
+ int ret_val = -1;
+ if (std::string(argv[1]) == std::string("float"))
+ ret_val = create_disk_layout<float>(argv);
+ else if (std::string(argv[1]) == std::string("int8"))
+ ret_val = create_disk_layout<int8_t>(argv);
+ else if (std::string(argv[1]) == std::string("uint8"))
+ ret_val = create_disk_layout<uint8_t>(argv);
+ else
+ {
+ std::cout << "unsupported type. use int8/uint8/float " << std::endl;
+ ret_val = -2;
+ }
+ return ret_val;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/float_bin_to_int8.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/float_bin_to_int8.cpp
new file mode 100644
index 0000000..1982005
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/float_bin_to_int8.cpp
@@ -0,0 +1,63 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+void block_convert(std::ofstream &writer, int8_t *write_buf, std::ifstream &reader, float *read_buf, size_t npts,
+ size_t ndims, float bias, float scale)
+{
+ reader.read((char *)read_buf, npts * ndims * sizeof(float));
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ for (size_t d = 0; d < ndims; d++)
+ {
+ write_buf[d + i * ndims] = (int8_t)((read_buf[d + i * ndims] - bias) * (254.0 / scale));
+ }
+ }
+ writer.write((char *)write_buf, npts * ndims);
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 5)
+ {
+ std::cout << "Usage: " << argv[0] << " input_bin output_tsv bias scale" << std::endl;
+ exit(-1);
+ }
+
+ std::ifstream reader(argv[1], std::ios::binary);
+ uint32_t npts_u32;
+ uint32_t ndims_u32;
+ reader.read((char *)&npts_u32, sizeof(uint32_t));
+ reader.read((char *)&ndims_u32, sizeof(uint32_t));
+ size_t npts = npts_u32;
+ size_t ndims = ndims_u32;
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+
+ std::ofstream writer(argv[2], std::ios::binary);
+ auto read_buf = new float[blk_size * ndims];
+ auto write_buf = new int8_t[blk_size * ndims];
+ float bias = (float)atof(argv[3]);
+ float scale = (float)atof(argv[4]);
+
+ writer.write((char *)(&npts_u32), sizeof(uint32_t));
+ writer.write((char *)(&ndims_u32), sizeof(uint32_t));
+
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ block_convert(writer, write_buf, reader, read_buf, cblk_size, ndims, bias, scale);
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+ delete[] write_buf;
+
+ writer.close();
+ reader.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/fvecs_to_bin.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/fvecs_to_bin.cpp
new file mode 100644
index 0000000..873ad3b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/fvecs_to_bin.cpp
@@ -0,0 +1,95 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+// Convert float types
+void block_convert_float(std::ifstream &reader, std::ofstream &writer, float *read_buf, float *write_buf, size_t npts,
+ size_t ndims)
+{
+ reader.read((char *)read_buf, npts * (ndims * sizeof(float) + sizeof(uint32_t)));
+ for (size_t i = 0; i < npts; i++)
+ {
+ memcpy(write_buf + i * ndims, (read_buf + i * (ndims + 1)) + 1, ndims * sizeof(float));
+ }
+ writer.write((char *)write_buf, npts * ndims * sizeof(float));
+}
+
+// Convert byte types
+void block_convert_byte(std::ifstream &reader, std::ofstream &writer, uint8_t *read_buf, uint8_t *write_buf,
+ size_t npts, size_t ndims)
+{
+ reader.read((char *)read_buf, npts * (ndims * sizeof(uint8_t) + sizeof(uint32_t)));
+ for (size_t i = 0; i < npts; i++)
+ {
+ memcpy(write_buf + i * ndims, (read_buf + i * (ndims + sizeof(uint32_t))) + sizeof(uint32_t),
+ ndims * sizeof(uint8_t));
+ }
+ writer.write((char *)write_buf, npts * ndims * sizeof(uint8_t));
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 4)
+ {
+ std::cout << argv[0] << " <float/int8/uint8> input_vecs output_bin" << std::endl;
+ exit(-1);
+ }
+
+ int datasize = sizeof(float);
+
+ if (strcmp(argv[1], "uint8") == 0 || strcmp(argv[1], "int8") == 0)
+ {
+ datasize = sizeof(uint8_t);
+ }
+ else if (strcmp(argv[1], "float") != 0)
+ {
+ std::cout << "Error: type not supported. Use float/int8/uint8" << std::endl;
+ exit(-1);
+ }
+
+ std::ifstream reader(argv[2], std::ios::binary | std::ios::ate);
+ size_t fsize = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+
+ uint32_t ndims_u32;
+ reader.read((char *)&ndims_u32, sizeof(uint32_t));
+ reader.seekg(0, std::ios::beg);
+ size_t ndims = (size_t)ndims_u32;
+ size_t npts = fsize / ((ndims * datasize) + sizeof(uint32_t));
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ std::cout << "# blks: " << nblks << std::endl;
+ std::ofstream writer(argv[3], std::ios::binary);
+ int32_t npts_s32 = (int32_t)npts;
+ int32_t ndims_s32 = (int32_t)ndims;
+ writer.write((char *)&npts_s32, sizeof(int32_t));
+ writer.write((char *)&ndims_s32, sizeof(int32_t));
+
+ size_t chunknpts = std::min(npts, blk_size);
+ uint8_t *read_buf = new uint8_t[chunknpts * ((ndims * datasize) + sizeof(uint32_t))];
+ uint8_t *write_buf = new uint8_t[chunknpts * ndims * datasize];
+
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ if (datasize == sizeof(float))
+ {
+ block_convert_float(reader, writer, (float *)read_buf, (float *)write_buf, cblk_size, ndims);
+ }
+ else
+ {
+ block_convert_byte(reader, writer, read_buf, write_buf, cblk_size, ndims);
+ }
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+ delete[] write_buf;
+
+ reader.close();
+ writer.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/fvecs_to_bvecs.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/fvecs_to_bvecs.cpp
new file mode 100644
index 0000000..f9c2aa7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/fvecs_to_bvecs.cpp
@@ -0,0 +1,56 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+void block_convert(std::ifstream &reader, std::ofstream &writer, float *read_buf, uint8_t *write_buf, size_t npts,
+ size_t ndims)
+{
+ reader.read((char *)read_buf, npts * (ndims * sizeof(float) + sizeof(uint32_t)));
+ for (size_t i = 0; i < npts; i++)
+ {
+ memcpy(write_buf + i * (ndims + 4), read_buf + i * (ndims + 1), sizeof(uint32_t));
+ for (size_t d = 0; d < ndims; d++)
+ write_buf[i * (ndims + 4) + 4 + d] = (uint8_t)read_buf[i * (ndims + 1) + 1 + d];
+ }
+ writer.write((char *)write_buf, npts * (ndims * 1 + 4));
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 3)
+ {
+ std::cout << argv[0] << " input_fvecs output_bvecs(uint8)" << std::endl;
+ exit(-1);
+ }
+ std::ifstream reader(argv[1], std::ios::binary | std::ios::ate);
+ size_t fsize = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+
+ uint32_t ndims_u32;
+ reader.read((char *)&ndims_u32, sizeof(uint32_t));
+ reader.seekg(0, std::ios::beg);
+ size_t ndims = (size_t)ndims_u32;
+ size_t npts = fsize / ((ndims + 1) * sizeof(float));
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ std::cout << "# blks: " << nblks << std::endl;
+ std::ofstream writer(argv[2], std::ios::binary);
+ auto read_buf = new float[npts * (ndims + 1)];
+ auto write_buf = new uint8_t[npts * (ndims + 4)];
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ block_convert(reader, writer, read_buf, write_buf, cblk_size, ndims);
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+ delete[] write_buf;
+
+ reader.close();
+ writer.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/gen_random_slice.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/gen_random_slice.cpp
new file mode 100644
index 0000000..a4cd96e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/gen_random_slice.cpp
@@ -0,0 +1,58 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <omp.h>
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <ctime>
+#include <iostream>
+#include <iterator>
+#include <map>
+#include <sstream>
+#include <string>
+#include "partition.h"
+#include "utils.h"
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <typeinfo>
+
+template <typename T> int aux_main(char **argv)
+{
+ std::string base_file(argv[2]);
+ std::string output_prefix(argv[3]);
+ float sampling_rate = (float)(std::atof(argv[4]));
+ gen_random_slice<T>(base_file, output_prefix, sampling_rate);
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 5)
+ {
+ std::cout << argv[0]
+ << " data_type [float/int8/uint8] base_bin_file "
+ "sample_output_prefix sampling_probability"
+ << std::endl;
+ exit(-1);
+ }
+
+ if (std::string(argv[1]) == std::string("float"))
+ {
+ aux_main<float>(argv);
+ }
+ else if (std::string(argv[1]) == std::string("int8"))
+ {
+ aux_main<int8_t>(argv);
+ }
+ else if (std::string(argv[1]) == std::string("uint8"))
+ {
+ aux_main<uint8_t>(argv);
+ }
+ else
+ std::cout << "Unsupported type. Use float/int8/uint8." << std::endl;
+ return 0;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/generate_pq.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/generate_pq.cpp
new file mode 100644
index 0000000..a881b11
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/generate_pq.cpp
@@ -0,0 +1,70 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "math_utils.h"
+#include "pq.h"
+#include "partition.h"
+
+#define KMEANS_ITERS_FOR_PQ 15
+
+template <typename T>
+bool generate_pq(const std::string &data_path, const std::string &index_prefix_path, const size_t num_pq_centers,
+ const size_t num_pq_chunks, const float sampling_rate, const bool opq)
+{
+ std::string pq_pivots_path = index_prefix_path + "_pq_pivots.bin";
+ std::string pq_compressed_vectors_path = index_prefix_path + "_pq_compressed.bin";
+
+ // generates random sample and sets it to train_data and updates train_size
+ size_t train_size, train_dim;
+ float *train_data;
+ gen_random_slice<T>(data_path, sampling_rate, train_data, train_size, train_dim);
+ std::cout << "For computing pivots, loaded sample data of size " << train_size << std::endl;
+
+ if (opq)
+ {
+ diskann::generate_opq_pivots(train_data, train_size, (uint32_t)train_dim, (uint32_t)num_pq_centers,
+ (uint32_t)num_pq_chunks, pq_pivots_path, true);
+ }
+ else
+ {
+ diskann::generate_pq_pivots(train_data, train_size, (uint32_t)train_dim, (uint32_t)num_pq_centers,
+ (uint32_t)num_pq_chunks, KMEANS_ITERS_FOR_PQ, pq_pivots_path);
+ }
+ diskann::generate_pq_data_from_pivots<T>(data_path, (uint32_t)num_pq_centers, (uint32_t)num_pq_chunks,
+ pq_pivots_path, pq_compressed_vectors_path, true);
+
+ delete[] train_data;
+
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 7)
+ {
+ std::cout << "Usage: \n"
+ << argv[0]
+ << " <data_type[float/uint8/int8]> <data_file[.bin]>"
+ " <PQ_prefix_path> <target-bytes/data-point> "
+ "<sampling_rate> <PQ(0)/OPQ(1)>"
+ << std::endl;
+ }
+ else
+ {
+ const std::string data_path(argv[2]);
+ const std::string index_prefix_path(argv[3]);
+ const size_t num_pq_centers = 256;
+ const size_t num_pq_chunks = (size_t)atoi(argv[4]);
+ const float sampling_rate = (float)atof(argv[5]);
+ const bool opq = atoi(argv[6]) == 0 ? false : true;
+
+ if (std::string(argv[1]) == std::string("float"))
+ generate_pq<float>(data_path, index_prefix_path, num_pq_centers, num_pq_chunks, sampling_rate, opq);
+ else if (std::string(argv[1]) == std::string("int8"))
+ generate_pq<int8_t>(data_path, index_prefix_path, num_pq_centers, num_pq_chunks, sampling_rate, opq);
+ else if (std::string(argv[1]) == std::string("uint8"))
+ generate_pq<uint8_t>(data_path, index_prefix_path, num_pq_centers, num_pq_chunks, sampling_rate, opq);
+ else
+ std::cout << "Error. wrong file type" << std::endl;
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/generate_synthetic_labels.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/generate_synthetic_labels.cpp
new file mode 100644
index 0000000..6741760
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/generate_synthetic_labels.cpp
@@ -0,0 +1,204 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include <random>
+#include <boost/program_options.hpp>
+#include <math.h>
+#include <cmath>
+#include "utils.h"
+
+namespace po = boost::program_options;
+class ZipfDistribution
+{
+ public:
+ ZipfDistribution(uint64_t num_points, uint32_t num_labels)
+ : num_labels(num_labels), num_points(num_points),
+ uniform_zero_to_one(std::uniform_real_distribution<>(0.0, 1.0))
+ {
+ }
+
+ std::unordered_map<uint32_t, uint32_t> createDistributionMap()
+ {
+ std::unordered_map<uint32_t, uint32_t> map;
+ uint32_t primary_label_freq = (uint32_t)ceil(num_points * distribution_factor);
+ for (uint32_t i{1}; i < num_labels + 1; i++)
+ {
+ map[i] = (uint32_t)ceil(primary_label_freq / i);
+ }
+ return map;
+ }
+
+ int writeDistribution(std::ofstream &outfile)
+ {
+ auto distribution_map = createDistributionMap();
+ for (uint32_t i{0}; i < num_points; i++)
+ {
+ bool label_written = false;
+ for (auto it = distribution_map.cbegin(); it != distribution_map.cend(); it++)
+ {
+ auto label_selection_probability = std::bernoulli_distribution(distribution_factor / (double)it->first);
+ if (label_selection_probability(rand_engine) && distribution_map[it->first] > 0)
+ {
+ if (label_written)
+ {
+ outfile << ',';
+ }
+ outfile << it->first;
+ label_written = true;
+ // remove label from map if we have used all labels
+ distribution_map[it->first] -= 1;
+ }
+ }
+ if (!label_written)
+ {
+ outfile << 0;
+ }
+ if (i < num_points - 1)
+ {
+ outfile << '\n';
+ }
+ }
+ return 0;
+ }
+
+ int writeDistribution(std::string filename)
+ {
+ std::ofstream outfile(filename);
+ if (!outfile.is_open())
+ {
+ std::cerr << "Error: could not open output file " << filename << '\n';
+ return -1;
+ }
+ writeDistribution(outfile);
+ outfile.close();
+ }
+
+ private:
+ const uint32_t num_labels;
+ const uint64_t num_points;
+ const double distribution_factor = 0.7;
+ std::knuth_b rand_engine;
+ const std::uniform_real_distribution<double> uniform_zero_to_one;
+};
+
+int main(int argc, char **argv)
+{
+ std::string output_file, distribution_type;
+ uint32_t num_labels;
+ uint64_t num_points;
+
+ try
+ {
+ po::options_description desc{"Arguments"};
+
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("output_file,O", po::value<std::string>(&output_file)->required(),
+ "Filename for saving the label file");
+ desc.add_options()("num_points,N", po::value<uint64_t>(&num_points)->required(), "Number of points in dataset");
+ desc.add_options()("num_labels,L", po::value<uint32_t>(&num_labels)->required(),
+ "Number of unique labels, up to 5000");
+ desc.add_options()("distribution_type,DT", po::value<std::string>(&distribution_type)->default_value("random"),
+ "Distribution function for labels <random/zipf/one_per_point> defaults "
+ "to random");
+
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ if (num_labels > 5000)
+ {
+ std::cerr << "Error: num_labels must be 5000 or less" << '\n';
+ return -1;
+ }
+
+ if (num_points <= 0)
+ {
+ std::cerr << "Error: num_points must be greater than 0" << '\n';
+ return -1;
+ }
+
+ std::cout << "Generating synthetic labels for " << num_points << " points with " << num_labels << " unique labels"
+ << '\n';
+
+ try
+ {
+ std::ofstream outfile(output_file);
+ if (!outfile.is_open())
+ {
+ std::cerr << "Error: could not open output file " << output_file << '\n';
+ return -1;
+ }
+
+ if (distribution_type == "zipf")
+ {
+ ZipfDistribution zipf(num_points, num_labels);
+ zipf.writeDistribution(outfile);
+ }
+ else if (distribution_type == "random")
+ {
+ for (size_t i = 0; i < num_points; i++)
+ {
+ bool label_written = false;
+ for (size_t j = 1; j <= num_labels; j++)
+ {
+ // 50% chance to assign each label
+ if (rand() > (RAND_MAX / 2))
+ {
+ if (label_written)
+ {
+ outfile << ',';
+ }
+ outfile << j;
+ label_written = true;
+ }
+ }
+ if (!label_written)
+ {
+ outfile << 0;
+ }
+ if (i < num_points - 1)
+ {
+ outfile << '\n';
+ }
+ }
+ }
+ else if (distribution_type == "one_per_point")
+ {
+ std::random_device rd; // obtain a random number from hardware
+ std::mt19937 gen(rd()); // seed the generator
+ std::uniform_int_distribution<> distr(0, num_labels); // define the range
+
+ for (size_t i = 0; i < num_points; i++)
+ {
+ outfile << distr(gen);
+ if (i != num_points - 1)
+ outfile << '\n';
+ }
+ }
+ if (outfile.is_open())
+ {
+ outfile.close();
+ }
+
+ std::cout << "Labels written to " << output_file << '\n';
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Label generation failed: " << ex.what() << '\n';
+ return -1;
+ }
+
+ return 0;
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/int8_to_float.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/int8_to_float.cpp
new file mode 100644
index 0000000..dcdfddc
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/int8_to_float.cpp
@@ -0,0 +1,23 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+int main(int argc, char **argv)
+{
+ if (argc != 3)
+ {
+ std::cout << argv[0] << " input_int8_bin output_float_bin" << std::endl;
+ exit(-1);
+ }
+
+ int8_t *input;
+ size_t npts, nd;
+ diskann::load_bin<int8_t>(argv[1], input, npts, nd);
+ float *output = new float[npts * nd];
+ diskann::convert_types<int8_t, float>(input, output, npts, nd);
+ diskann::save_bin<float>(argv[2], output, npts, nd);
+ delete[] output;
+ delete[] input;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/int8_to_float_scale.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/int8_to_float_scale.cpp
new file mode 100644
index 0000000..19fbc6c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/int8_to_float_scale.cpp
@@ -0,0 +1,63 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+void block_convert(std::ofstream &writer, float *write_buf, std::ifstream &reader, int8_t *read_buf, size_t npts,
+ size_t ndims, float bias, float scale)
+{
+ reader.read((char *)read_buf, npts * ndims * sizeof(int8_t));
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ for (size_t d = 0; d < ndims; d++)
+ {
+ write_buf[d + i * ndims] = (((float)read_buf[d + i * ndims] - bias) * scale);
+ }
+ }
+ writer.write((char *)write_buf, npts * ndims * sizeof(float));
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 5)
+ {
+ std::cout << "Usage: " << argv[0] << " input-int8.bin output-float.bin bias scale" << std::endl;
+ exit(-1);
+ }
+
+ std::ifstream reader(argv[1], std::ios::binary);
+ uint32_t npts_u32;
+ uint32_t ndims_u32;
+ reader.read((char *)&npts_u32, sizeof(uint32_t));
+ reader.read((char *)&ndims_u32, sizeof(uint32_t));
+ size_t npts = npts_u32;
+ size_t ndims = ndims_u32;
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+
+ std::ofstream writer(argv[2], std::ios::binary);
+ auto read_buf = new int8_t[blk_size * ndims];
+ auto write_buf = new float[blk_size * ndims];
+ float bias = (float)atof(argv[3]);
+ float scale = (float)atof(argv[4]);
+
+ writer.write((char *)(&npts_u32), sizeof(uint32_t));
+ writer.write((char *)(&ndims_u32), sizeof(uint32_t));
+
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ block_convert(writer, write_buf, reader, read_buf, cblk_size, ndims, bias, scale);
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+ delete[] write_buf;
+
+ writer.close();
+ reader.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/ivecs_to_bin.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/ivecs_to_bin.cpp
new file mode 100644
index 0000000..ea8a4a3
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/ivecs_to_bin.cpp
@@ -0,0 +1,58 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+void block_convert(std::ifstream &reader, std::ofstream &writer, uint32_t *read_buf, uint32_t *write_buf, size_t npts,
+ size_t ndims)
+{
+ reader.read((char *)read_buf, npts * (ndims * sizeof(uint32_t) + sizeof(uint32_t)));
+ for (size_t i = 0; i < npts; i++)
+ {
+ memcpy(write_buf + i * ndims, (read_buf + i * (ndims + 1)) + 1, ndims * sizeof(uint32_t));
+ }
+ writer.write((char *)write_buf, npts * ndims * sizeof(uint32_t));
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 3)
+ {
+ std::cout << argv[0] << " input_ivecs output_bin" << std::endl;
+ exit(-1);
+ }
+ std::ifstream reader(argv[1], std::ios::binary | std::ios::ate);
+ size_t fsize = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+
+ uint32_t ndims_u32;
+ reader.read((char *)&ndims_u32, sizeof(uint32_t));
+ reader.seekg(0, std::ios::beg);
+ size_t ndims = (size_t)ndims_u32;
+ size_t npts = fsize / ((ndims + 1) * sizeof(uint32_t));
+ std::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ std::cout << "# blks: " << nblks << std::endl;
+ std::ofstream writer(argv[2], std::ios::binary);
+ int npts_s32 = (int)npts;
+ int ndims_s32 = (int)ndims;
+ writer.write((char *)&npts_s32, sizeof(int));
+ writer.write((char *)&ndims_s32, sizeof(int));
+ uint32_t *read_buf = new uint32_t[npts * (ndims + 1)];
+ uint32_t *write_buf = new uint32_t[npts * ndims];
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ block_convert(reader, writer, read_buf, write_buf, cblk_size, ndims);
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ delete[] read_buf;
+ delete[] write_buf;
+
+ reader.close();
+ writer.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/merge_shards.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/merge_shards.cpp
new file mode 100644
index 0000000..106c15e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/merge_shards.cpp
@@ -0,0 +1,42 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <algorithm>
+#include <atomic>
+#include <cassert>
+#include <fstream>
+#include <iostream>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "disk_utils.h"
+#include "cached_io.h"
+#include "utils.h"
+
+int main(int argc, char **argv)
+{
+ if (argc != 9)
+ {
+ std::cout << argv[0]
+ << " vamana_index_prefix[1] vamana_index_suffix[2] "
+ "idmaps_prefix[3] "
+ "idmaps_suffix[4] n_shards[5] max_degree[6] "
+ "output_vamana_path[7] "
+ "output_medoids_path[8]"
+ << std::endl;
+ exit(-1);
+ }
+
+ std::string vamana_prefix(argv[1]);
+ std::string vamana_suffix(argv[2]);
+ std::string idmaps_prefix(argv[3]);
+ std::string idmaps_suffix(argv[4]);
+ uint64_t nshards = (uint64_t)std::atoi(argv[5]);
+ uint32_t max_degree = (uint64_t)std::atoi(argv[6]);
+ std::string output_index(argv[7]);
+ std::string output_medoids(argv[8]);
+
+ return diskann::merge_shards(vamana_prefix, vamana_suffix, idmaps_prefix, idmaps_suffix, nshards, max_degree,
+ output_index, output_medoids);
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/partition_data.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/partition_data.cpp
new file mode 100644
index 0000000..2520f3f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/partition_data.cpp
@@ -0,0 +1,39 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <index.h>
+#include <math_utils.h>
+#include "cached_io.h"
+#include "partition.h"
+
+// DEPRECATED: NEED TO REPROGRAM
+
+int main(int argc, char **argv)
+{
+ if (argc != 7)
+ {
+ std::cout << "Usage:\n"
+ << argv[0]
+ << " datatype<int8/uint8/float> <data_path>"
+ " <prefix_path> <sampling_rate> "
+ " <num_partitions> <k_index>"
+ << std::endl;
+ exit(-1);
+ }
+
+ const std::string data_path(argv[2]);
+ const std::string prefix_path(argv[3]);
+ const float sampling_rate = (float)atof(argv[4]);
+ const size_t num_partitions = (size_t)std::atoi(argv[5]);
+ const size_t max_reps = 15;
+ const size_t k_index = (size_t)std::atoi(argv[6]);
+
+ if (std::string(argv[1]) == std::string("float"))
+ partition<float>(data_path, sampling_rate, num_partitions, max_reps, prefix_path, k_index);
+ else if (std::string(argv[1]) == std::string("int8"))
+ partition<int8_t>(data_path, sampling_rate, num_partitions, max_reps, prefix_path, k_index);
+ else if (std::string(argv[1]) == std::string("uint8"))
+ partition<uint8_t>(data_path, sampling_rate, num_partitions, max_reps, prefix_path, k_index);
+ else
+ std::cout << "unsupported data format. use float/int8/uint8" << std::endl;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/partition_with_ram_budget.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/partition_with_ram_budget.cpp
new file mode 100644
index 0000000..937b68d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/partition_with_ram_budget.cpp
@@ -0,0 +1,39 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <index.h>
+#include <math_utils.h>
+#include "cached_io.h"
+#include "partition.h"
+
+// DEPRECATED: NEED TO REPROGRAM
+
+int main(int argc, char **argv)
+{
+ if (argc != 8)
+ {
+ std::cout << "Usage:\n"
+ << argv[0]
+ << " datatype<int8/uint8/float> <data_path>"
+ " <prefix_path> <sampling_rate> "
+ " <ram_budget(GB)> <graph_degree> <k_index>"
+ << std::endl;
+ exit(-1);
+ }
+
+ const std::string data_path(argv[2]);
+ const std::string prefix_path(argv[3]);
+ const float sampling_rate = (float)atof(argv[4]);
+ const double ram_budget = (double)std::atof(argv[5]);
+ const size_t graph_degree = (size_t)std::atoi(argv[6]);
+ const size_t k_index = (size_t)std::atoi(argv[7]);
+
+ if (std::string(argv[1]) == std::string("float"))
+ partition_with_ram_budget<float>(data_path, sampling_rate, ram_budget, graph_degree, prefix_path, k_index);
+ else if (std::string(argv[1]) == std::string("int8"))
+ partition_with_ram_budget<int8_t>(data_path, sampling_rate, ram_budget, graph_degree, prefix_path, k_index);
+ else if (std::string(argv[1]) == std::string("uint8"))
+ partition_with_ram_budget<uint8_t>(data_path, sampling_rate, ram_budget, graph_degree, prefix_path, k_index);
+ else
+ std::cout << "unsupported data format. use float/int8/uint8" << std::endl;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/rand_data_gen.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/rand_data_gen.cpp
new file mode 100644
index 0000000..e89ede8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/rand_data_gen.cpp
@@ -0,0 +1,237 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include <cstdlib>
+#include <random>
+#include <cmath>
+#include <boost/program_options.hpp>
+
+#include "utils.h"
+
+namespace po = boost::program_options;
+
+int block_write_float(std::ofstream &writer, size_t ndims, size_t npts, bool normalization, float norm,
+ float rand_scale)
+{
+ auto vec = new float[ndims];
+
+ std::random_device rd{};
+ std::mt19937 gen{rd()};
+ std::normal_distribution<> normal_rand{0, 1};
+ std::uniform_real_distribution<> unif_dis(1.0, rand_scale);
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ float sum = 0;
+ float scale = 1.0f;
+ if (rand_scale > 1.0f)
+ scale = (float)unif_dis(gen);
+ for (size_t d = 0; d < ndims; ++d)
+ vec[d] = scale * (float)normal_rand(gen);
+ if (normalization)
+ {
+ for (size_t d = 0; d < ndims; ++d)
+ sum += vec[d] * vec[d];
+ for (size_t d = 0; d < ndims; ++d)
+ vec[d] = vec[d] * norm / std::sqrt(sum);
+ }
+
+ writer.write((char *)vec, ndims * sizeof(float));
+ }
+
+ delete[] vec;
+ return 0;
+}
+
+int block_write_int8(std::ofstream &writer, size_t ndims, size_t npts, float norm)
+{
+ auto vec = new float[ndims];
+ auto vec_T = new int8_t[ndims];
+
+ std::random_device rd{};
+ std::mt19937 gen{rd()};
+ std::normal_distribution<> normal_rand{0, 1};
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ float sum = 0;
+ for (size_t d = 0; d < ndims; ++d)
+ vec[d] = (float)normal_rand(gen);
+ for (size_t d = 0; d < ndims; ++d)
+ sum += vec[d] * vec[d];
+ for (size_t d = 0; d < ndims; ++d)
+ vec[d] = vec[d] * norm / std::sqrt(sum);
+
+ for (size_t d = 0; d < ndims; ++d)
+ {
+ vec_T[d] = (int8_t)std::round(vec[d]);
+ }
+
+ writer.write((char *)vec_T, ndims * sizeof(int8_t));
+ }
+
+ delete[] vec;
+ delete[] vec_T;
+ return 0;
+}
+
+int block_write_uint8(std::ofstream &writer, size_t ndims, size_t npts, float norm)
+{
+ auto vec = new float[ndims];
+ auto vec_T = new int8_t[ndims];
+
+ std::random_device rd{};
+ std::mt19937 gen{rd()};
+ std::normal_distribution<> normal_rand{0, 1};
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ float sum = 0;
+ for (size_t d = 0; d < ndims; ++d)
+ vec[d] = (float)normal_rand(gen);
+ for (size_t d = 0; d < ndims; ++d)
+ sum += vec[d] * vec[d];
+ for (size_t d = 0; d < ndims; ++d)
+ vec[d] = vec[d] * norm / std::sqrt(sum);
+
+ for (size_t d = 0; d < ndims; ++d)
+ {
+ vec_T[d] = 128 + (int8_t)std::round(vec[d]);
+ }
+
+ writer.write((char *)vec_T, ndims * sizeof(uint8_t));
+ }
+
+ delete[] vec;
+ delete[] vec_T;
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ std::string data_type, output_file;
+ size_t ndims, npts;
+ float norm, rand_scaling;
+ bool normalization = false;
+ try
+ {
+ po::options_description desc{"Arguments"};
+
+ desc.add_options()("help,h", "Print information on arguments");
+
+ desc.add_options()("data_type", po::value<std::string>(&data_type)->required(), "data type <int8/uint8/float>");
+ desc.add_options()("output_file", po::value<std::string>(&output_file)->required(),
+ "File name for saving the random vectors");
+ desc.add_options()("ndims,D", po::value<uint64_t>(&ndims)->required(), "Dimensoinality of the vector");
+ desc.add_options()("npts,N", po::value<uint64_t>(&npts)->required(), "Number of vectors");
+ desc.add_options()("norm", po::value<float>(&norm)->default_value(-1.0f),
+ "Norm of the vectors (if not specified, vectors are not normalized)");
+ desc.add_options()("rand_scaling", po::value<float>(&rand_scaling)->default_value(1.0f),
+ "Each vector will be scaled (if not explicitly normalized) by a factor randomly chosen from "
+ "[1, rand_scale]. Only applicable for floating point data");
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << ex.what() << '\n';
+ return -1;
+ }
+
+ if (data_type != std::string("float") && data_type != std::string("int8") && data_type != std::string("uint8"))
+ {
+ std::cout << "Unsupported type. float, int8 and uint8 types are supported." << std::endl;
+ return -1;
+ }
+
+ if (norm > 0.0)
+ {
+ normalization = true;
+ }
+
+ if (rand_scaling < 1.0)
+ {
+ std::cout << "We will only scale the vector norms randomly in [1, value], so value must be >= 1." << std::endl;
+ return -1;
+ }
+
+ if ((rand_scaling > 1.0) && (normalization == true))
+ {
+ std::cout << "Data cannot be normalized and randomly scaled at same time. Use one or the other." << std::endl;
+ return -1;
+ }
+
+ if (data_type == std::string("int8") || data_type == std::string("uint8"))
+ {
+ if (norm > 127)
+ {
+ std::cerr << "Error: for int8/uint8 datatypes, L2 norm can not be "
+ "greater "
+ "than 127"
+ << std::endl;
+ return -1;
+ }
+ if (rand_scaling > 1.0)
+ {
+ std::cout << "Data scaling only supported for floating point data." << std::endl;
+ return -1;
+ }
+ }
+
+ try
+ {
+ std::ofstream writer;
+ writer.exceptions(std::ofstream::failbit | std::ofstream::badbit);
+ writer.open(output_file, std::ios::binary);
+ auto npts_u32 = (uint32_t)npts;
+ auto ndims_u32 = (uint32_t)ndims;
+ writer.write((char *)&npts_u32, sizeof(uint32_t));
+ writer.write((char *)&ndims_u32, sizeof(uint32_t));
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ std::cout << "# blks: " << nblks << std::endl;
+
+ int ret = 0;
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ if (data_type == std::string("float"))
+ {
+ ret = block_write_float(writer, ndims, cblk_size, normalization, norm, rand_scaling);
+ }
+ else if (data_type == std::string("int8"))
+ {
+ ret = block_write_int8(writer, ndims, cblk_size, norm);
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ ret = block_write_uint8(writer, ndims, cblk_size, norm);
+ }
+ if (ret == 0)
+ std::cout << "Block #" << i << " written" << std::endl;
+ else
+ {
+ writer.close();
+ std::cout << "failed to write" << std::endl;
+ return -1;
+ }
+ }
+ writer.close();
+ }
+ catch (const std::exception &e)
+ {
+ std::cout << std::string(e.what()) << std::endl;
+ diskann::cerr << "Index build failed." << std::endl;
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/simulate_aggregate_recall.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/simulate_aggregate_recall.cpp
new file mode 100644
index 0000000..73c4ea0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/simulate_aggregate_recall.cpp
@@ -0,0 +1,85 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include <cstdlib>
+#include <random>
+#include <cmath>
+
+inline float aggregate_recall(const uint32_t k_aggr, const uint32_t k, const uint32_t npart, uint32_t *count,
+ const std::vector<float> &recalls)
+{
+ float found = 0;
+ for (uint32_t i = 0; i < npart; ++i)
+ {
+ size_t max_found = std::min(count[i], k);
+ found += recalls[max_found - 1] * max_found;
+ }
+ return found / (float)k_aggr;
+}
+
+void simulate(const uint32_t k_aggr, const uint32_t k, const uint32_t npart, const uint32_t nsim,
+ const std::vector<float> &recalls)
+{
+ std::random_device r;
+ std::default_random_engine randeng(r());
+ std::uniform_int_distribution<int> uniform_dist(0, npart - 1);
+
+ uint32_t *count = new uint32_t[npart];
+ double aggr_recall = 0;
+
+ for (uint32_t i = 0; i < nsim; ++i)
+ {
+ for (uint32_t p = 0; p < npart; ++p)
+ {
+ count[p] = 0;
+ }
+ for (uint32_t t = 0; t < k_aggr; ++t)
+ {
+ count[uniform_dist(randeng)]++;
+ }
+ aggr_recall += aggregate_recall(k_aggr, k, npart, count, recalls);
+ }
+
+ std::cout << "Aggregate recall is " << aggr_recall / (double)nsim << std::endl;
+ delete[] count;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 6)
+ {
+ std::cout << argv[0] << " k_aggregate k_out npart nsim recall@1 recall@2 ... recall@k" << std::endl;
+ exit(-1);
+ }
+
+ const uint32_t k_aggr = atoi(argv[1]);
+ const uint32_t k = atoi(argv[2]);
+ const uint32_t npart = atoi(argv[3]);
+ const uint32_t nsim = atoi(argv[4]);
+
+ std::vector<float> recalls;
+ for (int ctr = 5; ctr < argc; ctr++)
+ {
+ recalls.push_back((float)atof(argv[ctr]));
+ }
+
+ if (recalls.size() != k)
+ {
+ std::cerr << "Please input k numbers for recall@1, recall@2 .. recall@k" << std::endl;
+ }
+ if (k_aggr > npart * k)
+ {
+ std::cerr << "k_aggr must be <= k * npart" << std::endl;
+ exit(-1);
+ }
+ if (nsim <= npart * k_aggr)
+ {
+ std::cerr << "Choose nsim > npart*k_aggr" << std::endl;
+ exit(-1);
+ }
+
+ simulate(k_aggr, k, npart, nsim, recalls);
+
+ return 0;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/stats_label_data.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/stats_label_data.cpp
new file mode 100644
index 0000000..3342672
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/stats_label_data.cpp
@@ -0,0 +1,147 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include <fstream>
+#include <string>
+#include <sstream>
+#include <cstdint>
+#include <vector>
+#include <unordered_map>
+#include <omp.h>
+#include <string.h>
+#include <atomic>
+#include <cstring>
+#include <iomanip>
+#include <set>
+#include <boost/program_options.hpp>
+
+#include "utils.h"
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <time.h>
+#else
+#include <Windows.h>
+#endif
+namespace po = boost::program_options;
+
+void stats_analysis(const std::string labels_file, std::string univeral_label, uint32_t density = 10)
+{
+ std::string token, line;
+ std::ifstream labels_stream(labels_file);
+ std::unordered_map<std::string, uint32_t> label_counts;
+ std::string label_with_max_points;
+ uint32_t max_points = 0;
+ long long sum = 0;
+ long long point_cnt = 0;
+ float avg_labels_per_pt, mean_label_size;
+
+ std::vector<uint32_t> labels_per_point;
+ uint32_t dense_pts = 0;
+ if (labels_stream.is_open())
+ {
+ while (getline(labels_stream, line))
+ {
+ point_cnt++;
+ std::stringstream iss(line);
+ uint32_t lbl_cnt = 0;
+ while (getline(iss, token, ','))
+ {
+ lbl_cnt++;
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ if (label_counts.find(token) == label_counts.end())
+ label_counts[token] = 0;
+ label_counts[token]++;
+ }
+ if (lbl_cnt >= density)
+ {
+ dense_pts++;
+ }
+ labels_per_point.emplace_back(lbl_cnt);
+ }
+ }
+
+ std::cout << "fraction of dense points with >= " << density
+ << " labels = " << (float)dense_pts / (float)labels_per_point.size() << std::endl;
+ std::sort(labels_per_point.begin(), labels_per_point.end());
+
+ std::vector<std::pair<std::string, uint32_t>> label_count_vec;
+
+ for (auto it = label_counts.begin(); it != label_counts.end(); it++)
+ {
+ auto &lbl = *it;
+ label_count_vec.emplace_back(std::make_pair(lbl.first, lbl.second));
+ if (lbl.second > max_points)
+ {
+ max_points = lbl.second;
+ label_with_max_points = lbl.first;
+ }
+ sum += lbl.second;
+ }
+
+ sort(label_count_vec.begin(), label_count_vec.end(),
+ [](const std::pair<std::string, uint32_t> &lhs, const std::pair<std::string, uint32_t> &rhs) {
+ return lhs.second < rhs.second;
+ });
+
+ for (float p = 0; p < 1; p += 0.05)
+ {
+ std::cout << "Percentile " << (100 * p) << "\t" << label_count_vec[(size_t)(p * label_count_vec.size())].first
+ << " with count=" << label_count_vec[(size_t)(p * label_count_vec.size())].second << std::endl;
+ }
+
+ std::cout << "Most common label "
+ << "\t" << label_count_vec[label_count_vec.size() - 1].first
+ << " with count=" << label_count_vec[label_count_vec.size() - 1].second << std::endl;
+ if (label_count_vec.size() > 1)
+ std::cout << "Second common label "
+ << "\t" << label_count_vec[label_count_vec.size() - 2].first
+ << " with count=" << label_count_vec[label_count_vec.size() - 2].second << std::endl;
+ if (label_count_vec.size() > 2)
+ std::cout << "Third common label "
+ << "\t" << label_count_vec[label_count_vec.size() - 3].first
+ << " with count=" << label_count_vec[label_count_vec.size() - 3].second << std::endl;
+ avg_labels_per_pt = sum / (float)point_cnt;
+ mean_label_size = sum / (float)label_counts.size();
+ std::cout << "Total number of points = " << point_cnt << ", number of labels = " << label_counts.size()
+ << std::endl;
+ std::cout << "Average number of labels per point = " << avg_labels_per_pt << std::endl;
+ std::cout << "Mean label size excluding 0 = " << mean_label_size << std::endl;
+ std::cout << "Most popular label is " << label_with_max_points << " with " << max_points << " pts" << std::endl;
+}
+
+int main(int argc, char **argv)
+{
+ std::string labels_file, universal_label;
+ uint32_t density;
+
+ po::options_description desc{"Arguments"};
+ try
+ {
+ desc.add_options()("help,h", "Print information on arguments");
+ desc.add_options()("labels_file", po::value<std::string>(&labels_file)->required(),
+ "path to labels data file.");
+ desc.add_options()("universal_label", po::value<std::string>(&universal_label)->required(),
+ "Universal label used in labels file.");
+ desc.add_options()("density", po::value<uint32_t>(&density)->default_value(1),
+ "Number of labels each point in labels file, defaults to 1");
+ po::variables_map vm;
+ po::store(po::parse_command_line(argc, argv, desc), vm);
+ if (vm.count("help"))
+ {
+ std::cout << desc;
+ return 0;
+ }
+ po::notify(vm);
+ }
+ catch (const std::exception &e)
+ {
+ std::cerr << e.what() << '\n';
+ return -1;
+ }
+ stats_analysis(labels_file, universal_label, density);
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/tsv_to_bin.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/tsv_to_bin.cpp
new file mode 100644
index 0000000..c590a8f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/tsv_to_bin.cpp
@@ -0,0 +1,121 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+void block_convert_float(std::ifstream &reader, std::ofstream &writer, size_t npts, size_t ndims)
+{
+ auto read_buf = new float[npts * (ndims + 1)];
+
+ auto cursor = read_buf;
+ float val;
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ for (size_t d = 0; d < ndims; ++d)
+ {
+ reader >> val;
+ *cursor = val;
+ cursor++;
+ }
+ }
+ writer.write((char *)read_buf, npts * ndims * sizeof(float));
+ delete[] read_buf;
+}
+
+void block_convert_int8(std::ifstream &reader, std::ofstream &writer, size_t npts, size_t ndims)
+{
+ auto read_buf = new int8_t[npts * (ndims + 1)];
+
+ auto cursor = read_buf;
+ int val;
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ for (size_t d = 0; d < ndims; ++d)
+ {
+ reader >> val;
+ *cursor = (int8_t)val;
+ cursor++;
+ }
+ }
+ writer.write((char *)read_buf, npts * ndims * sizeof(uint8_t));
+ delete[] read_buf;
+}
+
+void block_convert_uint8(std::ifstream &reader, std::ofstream &writer, size_t npts, size_t ndims)
+{
+ auto read_buf = new uint8_t[npts * (ndims + 1)];
+
+ auto cursor = read_buf;
+ int val;
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ for (size_t d = 0; d < ndims; ++d)
+ {
+ reader >> val;
+ *cursor = (uint8_t)val;
+ cursor++;
+ }
+ }
+ writer.write((char *)read_buf, npts * ndims * sizeof(uint8_t));
+ delete[] read_buf;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 6)
+ {
+ std::cout << argv[0]
+ << "<float/int8/uint8> input_filename.tsv output_filename.bin "
+ "dim num_pts>"
+ << std::endl;
+ exit(-1);
+ }
+
+ if (std::string(argv[1]) != std::string("float") && std::string(argv[1]) != std::string("int8") &&
+ std::string(argv[1]) != std::string("uint8"))
+ {
+ std::cout << "Unsupported type. float, int8 and uint8 types are supported." << std::endl;
+ }
+
+ size_t ndims = atoi(argv[4]);
+ size_t npts = atoi(argv[5]);
+
+ std::ifstream reader(argv[2], std::ios::binary | std::ios::ate);
+ // size_t fsize = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+ reader.seekg(0, std::ios::beg);
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ std::cout << "# blks: " << nblks << std::endl;
+ std::ofstream writer(argv[3], std::ios::binary);
+ auto npts_u32 = (uint32_t)npts;
+ auto ndims_u32 = (uint32_t)ndims;
+ writer.write((char *)&npts_u32, sizeof(uint32_t));
+ writer.write((char *)&ndims_u32, sizeof(uint32_t));
+
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ if (std::string(argv[1]) == std::string("float"))
+ {
+ block_convert_float(reader, writer, cblk_size, ndims);
+ }
+ else if (std::string(argv[1]) == std::string("int8"))
+ {
+ block_convert_int8(reader, writer, cblk_size, ndims);
+ }
+ else if (std::string(argv[1]) == std::string("uint8"))
+ {
+ block_convert_uint8(reader, writer, cblk_size, ndims);
+ }
+ std::cout << "Block #" << i << " written" << std::endl;
+ }
+
+ reader.close();
+ writer.close();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/uint32_to_uint8.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/uint32_to_uint8.cpp
new file mode 100644
index 0000000..87b6fb8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/uint32_to_uint8.cpp
@@ -0,0 +1,23 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+int main(int argc, char **argv)
+{
+ if (argc != 3)
+ {
+ std::cout << argv[0] << " input_uint32_bin output_int8_bin" << std::endl;
+ exit(-1);
+ }
+
+ uint32_t *input;
+ size_t npts, nd;
+ diskann::load_bin<uint32_t>(argv[1], input, npts, nd);
+ uint8_t *output = new uint8_t[npts * nd];
+ diskann::convert_types<uint32_t, uint8_t>(input, output, npts, nd);
+ diskann::save_bin<uint8_t>(argv[2], output, npts, nd);
+ delete[] output;
+ delete[] input;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/uint8_to_float.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/uint8_to_float.cpp
new file mode 100644
index 0000000..6415b7c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/uint8_to_float.cpp
@@ -0,0 +1,23 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <iostream>
+#include "utils.h"
+
+int main(int argc, char **argv)
+{
+ if (argc != 3)
+ {
+ std::cout << argv[0] << " input_uint8_bin output_float_bin" << std::endl;
+ exit(-1);
+ }
+
+ uint8_t *input;
+ size_t npts, nd;
+ diskann::load_bin<uint8_t>(argv[1], input, npts, nd);
+ float *output = new float[npts * nd];
+ diskann::convert_types<uint8_t, float>(input, output, npts, nd);
+ diskann::save_bin<float>(argv[2], output, npts, nd);
+ delete[] output;
+ delete[] input;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/vector_analysis.cpp b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/vector_analysis.cpp
new file mode 100644
index 0000000..009df6d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/apps/utils/vector_analysis.cpp
@@ -0,0 +1,163 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <omp.h>
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <ctime>
+#include <iostream>
+#include <iterator>
+#include <map>
+#include <sstream>
+#include <string>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <typeinfo>
+
+#include "partition.h"
+#include "utils.h"
+
+template <typename T> int analyze_norm(std::string base_file)
+{
+ std::cout << "Analyzing data norms" << std::endl;
+ T *data;
+ size_t npts, ndims;
+ diskann::load_bin<T>(base_file, data, npts, ndims);
+ std::vector<float> norms(npts, 0);
+#pragma omp parallel for schedule(dynamic)
+ for (int64_t i = 0; i < (int64_t)npts; i++)
+ {
+ for (size_t d = 0; d < ndims; d++)
+ norms[i] += data[i * ndims + d] * data[i * ndims + d];
+ norms[i] = std::sqrt(norms[i]);
+ }
+ std::sort(norms.begin(), norms.end());
+ for (int p = 0; p < 100; p += 5)
+ std::cout << "percentile " << p << ": " << norms[(uint64_t)(std::floor((p / 100.0) * npts))] << std::endl;
+ std::cout << "percentile 100"
+ << ": " << norms[npts - 1] << std::endl;
+ delete[] data;
+ return 0;
+}
+
+template <typename T> int normalize_base(std::string base_file, std::string out_file)
+{
+ std::cout << "Normalizing base" << std::endl;
+ T *data;
+ size_t npts, ndims;
+ diskann::load_bin<T>(base_file, data, npts, ndims);
+ // std::vector<float> norms(npts, 0);
+#pragma omp parallel for schedule(dynamic)
+ for (int64_t i = 0; i < (int64_t)npts; i++)
+ {
+ float pt_norm = 0;
+ for (size_t d = 0; d < ndims; d++)
+ pt_norm += data[i * ndims + d] * data[i * ndims + d];
+ pt_norm = std::sqrt(pt_norm);
+ for (size_t d = 0; d < ndims; d++)
+ data[i * ndims + d] = static_cast<T>(data[i * ndims + d] / pt_norm);
+ }
+ diskann::save_bin<T>(out_file, data, npts, ndims);
+ delete[] data;
+ return 0;
+}
+
+template <typename T> int augment_base(std::string base_file, std::string out_file, bool prep_base = true)
+{
+ std::cout << "Analyzing data norms" << std::endl;
+ T *data;
+ size_t npts, ndims;
+ diskann::load_bin<T>(base_file, data, npts, ndims);
+ std::vector<float> norms(npts, 0);
+ float max_norm = 0;
+#pragma omp parallel for schedule(dynamic)
+ for (int64_t i = 0; i < (int64_t)npts; i++)
+ {
+ for (size_t d = 0; d < ndims; d++)
+ norms[i] += data[i * ndims + d] * data[i * ndims + d];
+ max_norm = norms[i] > max_norm ? norms[i] : max_norm;
+ }
+ // std::sort(norms.begin(), norms.end());
+ max_norm = std::sqrt(max_norm);
+ std::cout << "Max norm: " << max_norm << std::endl;
+ T *new_data;
+ size_t newdims = ndims + 1;
+ new_data = new T[npts * newdims];
+ for (size_t i = 0; i < npts; i++)
+ {
+ if (prep_base)
+ {
+ for (size_t j = 0; j < ndims; j++)
+ {
+ new_data[i * newdims + j] = static_cast<T>(data[i * ndims + j] / max_norm);
+ }
+ float diff = 1 - (norms[i] / (max_norm * max_norm));
+ diff = diff <= 0 ? 0 : std::sqrt(diff);
+ new_data[i * newdims + ndims] = static_cast<T>(diff);
+ if (diff <= 0)
+ {
+ std::cout << i << " has large max norm, investigate if needed. diff = " << diff << std::endl;
+ }
+ }
+ else
+ {
+ for (size_t j = 0; j < ndims; j++)
+ {
+ new_data[i * newdims + j] = static_cast<T>(data[i * ndims + j] / std::sqrt(norms[i]));
+ }
+ new_data[i * newdims + ndims] = 0;
+ }
+ }
+ diskann::save_bin<T>(out_file, new_data, npts, newdims);
+ delete[] new_data;
+ delete[] data;
+ return 0;
+}
+
+template <typename T> int aux_main(char **argv)
+{
+ std::string base_file(argv[2]);
+ uint32_t option = atoi(argv[3]);
+ if (option == 1)
+ analyze_norm<T>(base_file);
+ else if (option == 2)
+ augment_base<T>(base_file, std::string(argv[4]), true);
+ else if (option == 3)
+ augment_base<T>(base_file, std::string(argv[4]), false);
+ else if (option == 4)
+ normalize_base<T>(base_file, std::string(argv[4]));
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 4)
+ {
+ std::cout << argv[0]
+ << " data_type [float/int8/uint8] base_bin_file "
+ "[option: 1-norm analysis, 2-prep_base_for_mip, "
+ "3-prep_query_for_mip, 4-normalize-vecs] [out_file for "
+ "options 2/3/4]"
+ << std::endl;
+ exit(-1);
+ }
+
+ if (std::string(argv[1]) == std::string("float"))
+ {
+ aux_main<float>(argv);
+ }
+ else if (std::string(argv[1]) == std::string("int8"))
+ {
+ aux_main<int8_t>(argv);
+ }
+ else if (std::string(argv[1]) == std::string("uint8"))
+ {
+ aux_main<uint8_t>(argv);
+ }
+ else
+ std::cout << "Unsupported type. Use float/int8/uint8." << std::endl;
+ return 0;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/clang-format.cmake b/packages/leann-backend-diskann/third_party/DiskANN/clang-format.cmake
new file mode 100644
index 0000000..19bb3a8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/clang-format.cmake
@@ -0,0 +1,22 @@
+if (NOT MSVC)
+ message(STATUS "Setting up `make format` and `make checkformat`")
+ # additional target to perform clang-format run, requires clang-format
+ # get all project files
+ file(GLOB_RECURSE ALL_SOURCE_FILES include/*.h include/*.hpp python/src/*.cpp src/*.cpp src/*.hpp apps/*.cpp apps/*.hpp)
+
+ message(status ${ALL_SOURCE_FILES})
+
+ add_custom_target(
+ format
+ COMMAND /usr/bin/clang-format
+ -i
+ ${ALL_SOURCE_FILES}
+ )
+ add_custom_target(
+ checkformat
+ COMMAND /usr/bin/clang-format
+ --Werror
+ --dry-run
+ ${ALL_SOURCE_FILES}
+ )
+endif()
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_data_store.h b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_data_store.h
new file mode 100644
index 0000000..89856f1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_data_store.h
@@ -0,0 +1,127 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <vector>
+#include <string>
+
+#include "types.h"
+#include "windows_customizations.h"
+#include "distance.h"
+
+namespace diskann
+{
+
+template <typename data_t> class AbstractScratch;
+
+template <typename data_t> class AbstractDataStore
+{
+ public:
+ AbstractDataStore(const location_t capacity, const size_t dim);
+
+ virtual ~AbstractDataStore() = default;
+
+ // Return number of points returned
+ virtual location_t load(const std::string &filename) = 0;
+
+ // Why does store take num_pts? Since store only has capacity, but we allow
+ // resizing we can end up in a situation where the store has spare capacity.
+ // To optimize disk utilization, we pass the number of points that are "true"
+ // points, so that the store can discard the empty locations before saving.
+ virtual size_t save(const std::string &filename, const location_t num_pts) = 0;
+
+ DISKANN_DLLEXPORT virtual location_t capacity() const;
+
+ DISKANN_DLLEXPORT virtual size_t get_dims() const;
+
+ // Implementers can choose to return _dim if they are not
+ // concerned about memory alignment.
+ // Some distance metrics (like l2) need data vectors to be aligned, so we
+ // align the dimension by padding zeros.
+ virtual size_t get_aligned_dim() const = 0;
+
+ // populate the store with vectors (either from a pointer or bin file),
+ // potentially after pre-processing the vectors if the metric deems so
+ // e.g., normalizing vectors for cosine distance over floating-point vectors
+ // useful for bulk or static index building.
+ virtual void populate_data(const data_t *vectors, const location_t num_pts) = 0;
+ virtual void populate_data(const std::string &filename, const size_t offset) = 0;
+
+ // save the first num_pts many vectors back to bin file
+ // note: cannot undo the pre-processing done in populate data
+ virtual void extract_data_to_bin(const std::string &filename, const location_t num_pts) = 0;
+
+ // Returns the updated capacity of the datastore. Clients should check
+ // if resize actually changed the capacity to new_num_points before
+ // proceeding with operations. See the code below:
+ // auto new_capcity = data_store->resize(new_num_points);
+ // if ( new_capacity >= new_num_points) {
+ // //PROCEED
+ // else
+ // //ERROR.
+ virtual location_t resize(const location_t new_num_points);
+
+ // operations on vectors
+ // like populate_data function, but over one vector at a time useful for
+ // streaming setting
+ virtual void get_vector(const location_t i, data_t *dest) const = 0;
+ virtual void set_vector(const location_t i, const data_t *const vector) = 0;
+ virtual void prefetch_vector(const location_t loc) = 0;
+
+ // internal shuffle operations to move around vectors
+ // will bulk-move all the vectors in [old_start_loc, old_start_loc +
+ // num_points) to [new_start_loc, new_start_loc + num_points) and set the old
+ // positions to zero vectors.
+ virtual void move_vectors(const location_t old_start_loc, const location_t new_start_loc,
+ const location_t num_points) = 0;
+
+ // same as above, without resetting the vectors in [from_loc, from_loc +
+ // num_points) to zero
+ virtual void copy_vectors(const location_t from_loc, const location_t to_loc, const location_t num_points) = 0;
+
+ // With the PQ Data Store PR, we have also changed iterate_to_fixed_point to NOT take the query
+ // from the scratch object. Therefore every data store has to implement preprocess_query which
+ // at the least will be to copy the query into the scratch object. So making this pure virtual.
+ virtual void preprocess_query(const data_t *aligned_query,
+ AbstractScratch<data_t> *query_scratch = nullptr) const = 0;
+ // distance functions.
+ virtual float get_distance(const data_t *query, const location_t loc) const = 0;
+ virtual void get_distance(const data_t *query, const location_t *locations, const uint32_t location_count,
+ float *distances, AbstractScratch<data_t> *scratch_space = nullptr) const = 0;
+ // Specific overload for index.cpp.
+ virtual void get_distance(const data_t *preprocessed_query, const std::vector<location_t> &ids,
+ std::vector<float> &distances, AbstractScratch<data_t> *scratch_space) const = 0;
+ virtual float get_distance(const location_t loc1, const location_t loc2) const = 0;
+
+ // stats of the data stored in store
+ // Returns the point in the dataset that is closest to the mean of all points
+ // in the dataset
+ virtual location_t calculate_medoid() const = 0;
+
+ // REFACTOR PQ TODO: Each data store knows about its distance function, so this is
+ // redundant. However, we don't have an OptmizedDataStore yet, and to preserve code
+ // compability, we are exposing this function.
+ virtual Distance<data_t> *get_dist_fn() const = 0;
+
+ // search helpers
+ // if the base data is aligned per the request of the metric, this will tell
+ // how to align the query vector in a consistent manner
+ virtual size_t get_alignment_factor() const = 0;
+
+ protected:
+ // Expand the datastore to new_num_points. Returns the new capacity created,
+ // which should be == new_num_points in the normal case. Implementers can also
+ // return _capacity to indicate that there are not implementing this method.
+ virtual location_t expand(const location_t new_num_points) = 0;
+
+ // Shrink the datastore to new_num_points. It is NOT an error if shrink
+ // doesn't reduce the capacity so callers need to check this correctly. See
+ // also for "default" implementation
+ virtual location_t shrink(const location_t new_num_points) = 0;
+
+ location_t _capacity;
+ size_t _dim;
+};
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_graph_store.h b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_graph_store.h
new file mode 100644
index 0000000..4d6906c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_graph_store.h
@@ -0,0 +1,68 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include "types.h"
+
+namespace diskann
+{
+
+class AbstractGraphStore
+{
+ public:
+ AbstractGraphStore(const size_t total_pts, const size_t reserve_graph_degree)
+ : _capacity(total_pts), _reserve_graph_degree(reserve_graph_degree)
+ {
+ }
+
+ virtual ~AbstractGraphStore() = default;
+
+ // returns tuple of <nodes_read, start, num_frozen_points>
+ virtual std::tuple<uint32_t, uint32_t, size_t> load(const std::string &index_path_prefix,
+ const size_t num_points) = 0;
+ virtual int store(const std::string &index_path_prefix, const size_t num_points, const size_t num_fz_points,
+ const uint32_t start) = 0;
+
+ // not synchronised, user should use lock when necvessary.
+ virtual const std::vector<location_t> &get_neighbours(const location_t i) const = 0;
+ virtual void add_neighbour(const location_t i, location_t neighbour_id) = 0;
+ virtual void clear_neighbours(const location_t i) = 0;
+ virtual void swap_neighbours(const location_t a, location_t b) = 0;
+
+ virtual void set_neighbours(const location_t i, std::vector<location_t> &neighbours) = 0;
+
+ virtual size_t resize_graph(const size_t new_size) = 0;
+ virtual void clear_graph() = 0;
+
+ virtual uint32_t get_max_observed_degree() = 0;
+
+ // set during load
+ virtual size_t get_max_range_of_graph() = 0;
+
+ // Total internal points _max_points + _num_frozen_points
+ size_t get_total_points()
+ {
+ return _capacity;
+ }
+
+ protected:
+ // Internal function, changes total points when resize_graph is called.
+ void set_total_points(size_t new_capacity)
+ {
+ _capacity = new_capacity;
+ }
+
+ size_t get_reserve_graph_degree()
+ {
+ return _reserve_graph_degree;
+ }
+
+ private:
+ size_t _capacity;
+ size_t _reserve_graph_degree;
+};
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_index.h b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_index.h
new file mode 100644
index 0000000..059866f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_index.h
@@ -0,0 +1,129 @@
+#pragma once
+#include "distance.h"
+#include "parameters.h"
+#include "utils.h"
+#include "types.h"
+#include "index_config.h"
+#include "index_build_params.h"
+#include <any>
+
+namespace diskann
+{
+struct consolidation_report
+{
+ enum status_code
+ {
+ SUCCESS = 0,
+ FAIL = 1,
+ LOCK_FAIL = 2,
+ INCONSISTENT_COUNT_ERROR = 3
+ };
+ status_code _status;
+ size_t _active_points, _max_points, _empty_slots, _slots_released, _delete_set_size, _num_calls_to_process_delete;
+ double _time;
+
+ consolidation_report(status_code status, size_t active_points, size_t max_points, size_t empty_slots,
+ size_t slots_released, size_t delete_set_size, size_t num_calls_to_process_delete,
+ double time_secs)
+ : _status(status), _active_points(active_points), _max_points(max_points), _empty_slots(empty_slots),
+ _slots_released(slots_released), _delete_set_size(delete_set_size),
+ _num_calls_to_process_delete(num_calls_to_process_delete), _time(time_secs)
+ {
+ }
+};
+
+/* A templated independent class for intercation with Index. Uses Type Erasure to add virtual implemetation of methods
+that can take any type(using std::any) and Provides a clean API that can be inherited by different type of Index.
+*/
+class AbstractIndex
+{
+ public:
+ AbstractIndex() = default;
+ virtual ~AbstractIndex() = default;
+
+ virtual void build(const std::string &data_file, const size_t num_points_to_load,
+ IndexFilterParams &build_params) = 0;
+
+ template <typename data_type, typename tag_type>
+ void build(const data_type *data, const size_t num_points_to_load, const std::vector<tag_type> &tags);
+
+ virtual void save(const char *filename, bool compact_before_save = false) = 0;
+
+#ifdef EXEC_ENV_OLS
+ virtual void load(AlignedFileReader &reader, uint32_t num_threads, uint32_t search_l) = 0;
+#else
+ virtual void load(const char *index_file, uint32_t num_threads, uint32_t search_l) = 0;
+#endif
+
+ // For FastL2 search on optimized layout
+ template <typename data_type>
+ void search_with_optimized_layout(const data_type *query, size_t K, size_t L, uint32_t *indices);
+
+ // Initialize space for res_vectors before calling.
+ template <typename data_type, typename tag_type>
+ size_t search_with_tags(const data_type *query, const uint64_t K, const uint32_t L, tag_type *tags,
+ float *distances, std::vector<data_type *> &res_vectors, bool use_filters = false,
+ const std::string filter_label = "");
+
+ // Added search overload that takes L as parameter, so that we
+ // can customize L on a per-query basis without tampering with "Parameters"
+ // IDtype is either uint32_t or uint64_t
+ template <typename data_type, typename IDType>
+ std::pair<uint32_t, uint32_t> search(const data_type *query, const size_t K, const uint32_t L, IDType *indices,
+ float *distances = nullptr);
+
+ // Filter support search
+ // IndexType is either uint32_t or uint64_t
+ template <typename IndexType>
+ std::pair<uint32_t, uint32_t> search_with_filters(const DataType &query, const std::string &raw_label,
+ const size_t K, const uint32_t L, IndexType *indices,
+ float *distances);
+
+ // insert points with labels, labels should be present for filtered index
+ template <typename data_type, typename tag_type, typename label_type>
+ int insert_point(const data_type *point, const tag_type tag, const std::vector<label_type> &labels);
+
+ // insert point for unfiltered index build. do not use with filtered index
+ template <typename data_type, typename tag_type> int insert_point(const data_type *point, const tag_type tag);
+
+ // delete point with tag, or return -1 if point can not be deleted
+ template <typename tag_type> int lazy_delete(const tag_type &tag);
+
+ // batch delete tags and populates failed tags if unabke to delete given tags.
+ template <typename tag_type>
+ void lazy_delete(const std::vector<tag_type> &tags, std::vector<tag_type> &failed_tags);
+
+ template <typename tag_type> void get_active_tags(tsl::robin_set<tag_type> &active_tags);
+
+ template <typename data_type> void set_start_points_at_random(data_type radius, uint32_t random_seed = 0);
+
+ virtual consolidation_report consolidate_deletes(const IndexWriteParameters &parameters) = 0;
+
+ virtual void optimize_index_layout() = 0;
+
+ // memory should be allocated for vec before calling this function
+ template <typename tag_type, typename data_type> int get_vector_by_tag(tag_type &tag, data_type *vec);
+
+ template <typename label_type> void set_universal_label(const label_type universal_label);
+
+ private:
+ virtual void _build(const DataType &data, const size_t num_points_to_load, TagVector &tags) = 0;
+ virtual std::pair<uint32_t, uint32_t> _search(const DataType &query, const size_t K, const uint32_t L,
+ std::any &indices, float *distances = nullptr) = 0;
+ virtual std::pair<uint32_t, uint32_t> _search_with_filters(const DataType &query, const std::string &filter_label,
+ const size_t K, const uint32_t L, std::any &indices,
+ float *distances) = 0;
+ virtual int _insert_point(const DataType &data_point, const TagType tag, Labelvector &labels) = 0;
+ virtual int _insert_point(const DataType &data_point, const TagType tag) = 0;
+ virtual int _lazy_delete(const TagType &tag) = 0;
+ virtual void _lazy_delete(TagVector &tags, TagVector &failed_tags) = 0;
+ virtual void _get_active_tags(TagRobinSet &active_tags) = 0;
+ virtual void _set_start_points_at_random(DataType radius, uint32_t random_seed = 0) = 0;
+ virtual int _get_vector_by_tag(TagType &tag, DataType &vec) = 0;
+ virtual size_t _search_with_tags(const DataType &query, const uint64_t K, const uint32_t L, const TagType &tags,
+ float *distances, DataVector &res_vectors, bool use_filters = false,
+ const std::string filter_label = "") = 0;
+ virtual void _search_with_optimized_layout(const DataType &query, size_t K, size_t L, uint32_t *indices) = 0;
+ virtual void _set_universal_label(const LabelType universal_label) = 0;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_scratch.h b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_scratch.h
new file mode 100644
index 0000000..b42a836
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/abstract_scratch.h
@@ -0,0 +1,35 @@
+#pragma once
+namespace diskann
+{
+
+template <typename data_t> class PQScratch;
+
+// By somewhat more than a coincidence, it seems that both InMemQueryScratch
+// and SSDQueryScratch have the aligned query and PQScratch objects. So we
+// can put them in a neat hierarchy and keep PQScratch as a standalone class.
+template <typename data_t> class AbstractScratch
+{
+ public:
+ AbstractScratch() = default;
+ // This class does not take any responsibilty for memory management of
+ // its members. It is the responsibility of the derived classes to do so.
+ virtual ~AbstractScratch() = default;
+
+ // Scratch objects should not be copied
+ AbstractScratch(const AbstractScratch &) = delete;
+ AbstractScratch &operator=(const AbstractScratch &) = delete;
+
+ data_t *aligned_query_T()
+ {
+ return _aligned_query_T;
+ }
+ PQScratch<data_t> *pq_scratch()
+ {
+ return _pq_scratch;
+ }
+
+ protected:
+ data_t *_aligned_query_T = nullptr;
+ PQScratch<data_t> *_pq_scratch = nullptr;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/aligned_file_reader.h b/packages/leann-backend-diskann/third_party/DiskANN/include/aligned_file_reader.h
new file mode 100644
index 0000000..2e2716a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/aligned_file_reader.h
@@ -0,0 +1,138 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#define MAX_IO_DEPTH 128
+
+#include <vector>
+#include <atomic>
+
+#ifdef __linux__
+#include <fcntl.h>
+#include <libaio.h>
+#include <unistd.h>
+#include <malloc.h>
+typedef io_context_t IOContext;
+#elif __APPLE__
+#include <dispatch/dispatch.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+struct IOContext
+{
+ int fd;
+ dispatch_io_t channel;
+ dispatch_queue_t queue;
+ dispatch_group_t grp;
+};
+#elif _WINDOWS
+#include <Windows.h>
+#include <minwinbase.h>
+#include <malloc.h>
+
+#ifndef USE_BING_INFRA
+struct IOContext
+{
+ HANDLE fhandle = NULL;
+ HANDLE iocp = NULL;
+ std::vector<OVERLAPPED> reqs;
+};
+#else
+#include "IDiskPriorityIO.h"
+#include <atomic>
+// TODO: Caller code is very callous about copying IOContext objects
+// all over the place. MUST verify that it won't cause leaks/logical
+// errors.
+// Because of such callous copying, we have to use ptr->atomic instead
+// of atomic, as atomic is not copyable.
+struct IOContext
+{
+ enum Status
+ {
+ READ_WAIT = 0,
+ READ_SUCCESS,
+ READ_FAILED,
+ PROCESS_COMPLETE
+ };
+
+ std::shared_ptr<ANNIndex::IDiskPriorityIO> m_pDiskIO = nullptr;
+ std::shared_ptr<std::vector<ANNIndex::AsyncReadRequest>> m_pRequests;
+ std::shared_ptr<std::vector<Status>> m_pRequestsStatus;
+
+ // waitonaddress on this memory to wait for IO completion signal
+ // reader should signal this memory after IO completion
+ // TODO: WindowsAlignedFileReader can be modified to take advantage of this
+ // and can largely share code with the file reader for Bing.
+ mutable volatile long m_completeCount = 0;
+
+ IOContext()
+ : m_pRequestsStatus(new std::vector<Status>()), m_pRequests(new std::vector<ANNIndex::AsyncReadRequest>())
+ {
+ (*m_pRequestsStatus).reserve(MAX_IO_DEPTH);
+ (*m_pRequests).reserve(MAX_IO_DEPTH);
+ }
+};
+#endif
+
+#endif
+
+#include <cstdio>
+#include <mutex>
+#include <thread>
+#include "tsl/robin_map.h"
+#include "utils.h"
+
+// NOTE :: all 3 fields must be 512-aligned
+struct AlignedRead
+{
+ uint64_t offset; // where to read from
+ uint64_t len; // how much to read
+ void *buf; // where to read into
+
+ AlignedRead() : offset(0), len(0), buf(nullptr)
+ {
+ }
+
+ AlignedRead(uint64_t offset, uint64_t len, void *buf) : offset(offset), len(len), buf(buf)
+ {
+ assert(IS_512_ALIGNED(offset));
+ assert(IS_512_ALIGNED(len));
+ assert(IS_512_ALIGNED(buf));
+ // assert(malloc_usable_size(buf) >= len);
+ }
+};
+
+class AlignedFileReader
+{
+ protected:
+ tsl::robin_map<std::thread::id, IOContext> ctx_map;
+ std::mutex ctx_mut;
+
+ public:
+ // returns the thread-specific context
+ // returns (io_context_t)(-1) if thread is not registered
+ virtual IOContext &get_ctx() = 0;
+
+ virtual ~AlignedFileReader(){};
+
+ // register thread-id for a context
+ virtual void register_thread() = 0;
+ // de-register thread-id for a context
+ virtual void deregister_thread() = 0;
+ virtual void deregister_all_threads() = 0;
+
+ // Open & close ops
+ // Blocking calls
+ virtual void open(const std::string &fname) = 0;
+ virtual void close() = 0;
+
+ // process batch of aligned requests in parallel
+ // NOTE :: blocking call
+ virtual void read(std::vector<AlignedRead> &read_reqs, IOContext &ctx, bool async = false) = 0;
+
+#ifdef USE_BING_INFRA
+ // wait for completion of one request in a batch of requests
+ virtual void wait(IOContext &ctx, int &completedIndex) = 0;
+#endif
+};
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/ann_exception.h b/packages/leann-backend-diskann/third_party/DiskANN/include/ann_exception.h
new file mode 100644
index 0000000..55f069b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/ann_exception.h
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <string>
+#include <stdexcept>
+#include <system_error>
+#include "windows_customizations.h"
+#include <cstdint>
+
+#ifndef _WINDOWS
+#define __FUNCSIG__ __PRETTY_FUNCTION__
+#endif
+
+namespace diskann
+{
+
+class ANNException : public std::runtime_error
+{
+ public:
+ DISKANN_DLLEXPORT ANNException(const std::string &message, int errorCode);
+ DISKANN_DLLEXPORT ANNException(const std::string &message, int errorCode, const std::string &funcSig,
+ const std::string &fileName, uint32_t lineNum);
+
+ private:
+ int _errorCode;
+};
+
+class FileException : public ANNException
+{
+ public:
+ DISKANN_DLLEXPORT FileException(const std::string &filename, std::system_error &e, const std::string &funcSig,
+ const std::string &fileName, uint32_t lineNum);
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/any_wrappers.h b/packages/leann-backend-diskann/third_party/DiskANN/include/any_wrappers.h
new file mode 100644
index 0000000..da9005c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/any_wrappers.h
@@ -0,0 +1,53 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstdint>
+#include <cstddef>
+#include <vector>
+#include <any>
+#include "tsl/robin_set.h"
+
+namespace AnyWrapper
+{
+
+/*
+ * Base Struct to hold refrence to the data.
+ * Note: No memory mamagement, caller need to keep object alive.
+ */
+struct AnyReference
+{
+ template <typename Ty> AnyReference(Ty &reference) : _data(&reference)
+ {
+ }
+
+ template <typename Ty> Ty &get()
+ {
+ auto ptr = std::any_cast<Ty *>(_data);
+ return *ptr;
+ }
+
+ private:
+ std::any _data;
+};
+struct AnyRobinSet : public AnyReference
+{
+ template <typename T> AnyRobinSet(const tsl::robin_set<T> &robin_set) : AnyReference(robin_set)
+ {
+ }
+ template <typename T> AnyRobinSet(tsl::robin_set<T> &robin_set) : AnyReference(robin_set)
+ {
+ }
+};
+
+struct AnyVector : public AnyReference
+{
+ template <typename T> AnyVector(const std::vector<T> &vector) : AnyReference(vector)
+ {
+ }
+ template <typename T> AnyVector(std::vector<T> &vector) : AnyReference(vector)
+ {
+ }
+};
+} // namespace AnyWrapper
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/apple_aligned_file_reader.h b/packages/leann-backend-diskann/third_party/DiskANN/include/apple_aligned_file_reader.h
new file mode 100644
index 0000000..160e1ea
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/apple_aligned_file_reader.h
@@ -0,0 +1,26 @@
+#pragma once
+#ifdef __APPLE__
+#include "aligned_file_reader.h"
+
+class AppleAlignedFileReader : public AlignedFileReader
+{
+ private:
+ uint64_t file_sz;
+ FileHandle file_desc;
+
+ public:
+ AppleAlignedFileReader();
+ ~AppleAlignedFileReader();
+
+ IOContext &get_ctx();
+
+ void register_thread();
+ void deregister_thread();
+ void deregister_all_threads();
+
+ void open(const std::string &fname);
+ void close();
+
+ void read(std::vector<AlignedRead> &read_reqs, IOContext &ctx, bool async = false);
+};
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/boost_dynamic_bitset_fwd.h b/packages/leann-backend-diskann/third_party/DiskANN/include/boost_dynamic_bitset_fwd.h
new file mode 100644
index 0000000..5aebb2b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/boost_dynamic_bitset_fwd.h
@@ -0,0 +1,11 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+namespace boost
+{
+#ifndef BOOST_DYNAMIC_BITSET_FWD_HPP
+template <typename Block = unsigned long, typename Allocator = std::allocator<Block>> class dynamic_bitset;
+#endif
+} // namespace boost
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/cached_io.h b/packages/leann-backend-diskann/third_party/DiskANN/include/cached_io.h
new file mode 100644
index 0000000..daef2f2
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/cached_io.h
@@ -0,0 +1,217 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <sstream>
+
+#include "logger.h"
+#include "ann_exception.h"
+
+// sequential cached reads
+class cached_ifstream
+{
+ public:
+ cached_ifstream()
+ {
+ }
+ cached_ifstream(const std::string &filename, uint64_t cacheSize) : cache_size(cacheSize), cur_off(0)
+ {
+ reader.exceptions(std::ifstream::failbit | std::ifstream::badbit);
+ this->open(filename, cache_size);
+ }
+ ~cached_ifstream()
+ {
+ delete[] cache_buf;
+ reader.close();
+ }
+
+ void open(const std::string &filename, uint64_t cacheSize)
+ {
+ this->cur_off = 0;
+
+ try
+ {
+ reader.open(filename, std::ios::binary | std::ios::ate);
+ fsize = reader.tellg();
+ reader.seekg(0, std::ios::beg);
+ assert(reader.is_open());
+ assert(cacheSize > 0);
+ cacheSize = (std::min)(cacheSize, fsize);
+ this->cache_size = cacheSize;
+ cache_buf = new char[cacheSize];
+ reader.read(cache_buf, cacheSize);
+ diskann::cout << "Opened: " << filename.c_str() << ", size: " << fsize << ", cache_size: " << cacheSize
+ << std::endl;
+ }
+ catch (std::system_error &e)
+ {
+ throw diskann::FileException(filename, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+
+ size_t get_file_size()
+ {
+ return fsize;
+ }
+
+ void read(char *read_buf, uint64_t n_bytes)
+ {
+ assert(cache_buf != nullptr);
+ assert(read_buf != nullptr);
+
+ if (n_bytes <= (cache_size - cur_off))
+ {
+ // case 1: cache contains all data
+ memcpy(read_buf, cache_buf + cur_off, n_bytes);
+ cur_off += n_bytes;
+ }
+ else
+ {
+ // case 2: cache contains some data
+ uint64_t cached_bytes = cache_size - cur_off;
+ if (n_bytes - cached_bytes > fsize - reader.tellg())
+ {
+ std::stringstream stream;
+ stream << "Reading beyond end of file" << std::endl;
+ stream << "n_bytes: " << n_bytes << " cached_bytes: " << cached_bytes << " fsize: " << fsize
+ << " current pos:" << reader.tellg() << std::endl;
+ diskann::cout << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ memcpy(read_buf, cache_buf + cur_off, cached_bytes);
+
+ // go to disk and fetch more data
+ reader.read(read_buf + cached_bytes, n_bytes - cached_bytes);
+ // reset cur off
+ cur_off = cache_size;
+
+ uint64_t size_left = fsize - reader.tellg();
+
+ if (size_left >= cache_size)
+ {
+ reader.read(cache_buf, cache_size);
+ cur_off = 0;
+ }
+ // note that if size_left < cache_size, then cur_off = cache_size,
+ // so subsequent reads will all be directly from file
+ }
+ }
+
+ private:
+ // underlying ifstream
+ std::ifstream reader;
+ // # bytes to cache in one shot read
+ uint64_t cache_size = 0;
+ // underlying buf for cache
+ char *cache_buf = nullptr;
+ // offset into cache_buf for cur_pos
+ uint64_t cur_off = 0;
+ // file size
+ uint64_t fsize = 0;
+};
+
+// sequential cached writes
+class cached_ofstream
+{
+ public:
+ cached_ofstream(const std::string &filename, uint64_t cache_size) : cache_size(cache_size), cur_off(0)
+ {
+ writer.exceptions(std::ifstream::failbit | std::ifstream::badbit);
+ try
+ {
+ writer.open(filename, std::ios::binary);
+ assert(writer.is_open());
+ assert(cache_size > 0);
+ cache_buf = new char[cache_size];
+ diskann::cout << "Opened: " << filename.c_str() << ", cache_size: " << cache_size << std::endl;
+ }
+ catch (std::system_error &e)
+ {
+ throw diskann::FileException(filename, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+
+ ~cached_ofstream()
+ {
+ this->close();
+ }
+
+ void close()
+ {
+ // dump any remaining data in memory
+ if (cur_off > 0)
+ {
+ this->flush_cache();
+ }
+
+ if (cache_buf != nullptr)
+ {
+ delete[] cache_buf;
+ cache_buf = nullptr;
+ }
+
+ if (writer.is_open())
+ writer.close();
+ diskann::cout << "Finished writing " << fsize << "B" << std::endl;
+ }
+
+ size_t get_file_size()
+ {
+ return fsize;
+ }
+ // writes n_bytes from write_buf to the underlying ofstream/cache
+ void write(char *write_buf, uint64_t n_bytes)
+ {
+ assert(cache_buf != nullptr);
+ if (n_bytes <= (cache_size - cur_off))
+ {
+ // case 1: cache can take all data
+ memcpy(cache_buf + cur_off, write_buf, n_bytes);
+ cur_off += n_bytes;
+ }
+ else
+ {
+ // case 2: cache cant take all data
+ // go to disk and write existing cache data
+ writer.write(cache_buf, cur_off);
+ fsize += cur_off;
+ // write the new data to disk
+ writer.write(write_buf, n_bytes);
+ fsize += n_bytes;
+ // memset all cache data and reset cur_off
+ memset(cache_buf, 0, cache_size);
+ cur_off = 0;
+ }
+ }
+
+ void flush_cache()
+ {
+ assert(cache_buf != nullptr);
+ writer.write(cache_buf, cur_off);
+ fsize += cur_off;
+ memset(cache_buf, 0, cache_size);
+ cur_off = 0;
+ }
+
+ void reset()
+ {
+ flush_cache();
+ writer.seekp(0);
+ }
+
+ private:
+ // underlying ofstream
+ std::ofstream writer;
+ // # bytes to cache for one shot write
+ uint64_t cache_size = 0;
+ // underlying buf for cache
+ char *cache_buf = nullptr;
+ // offset into cache_buf for cur_pos
+ uint64_t cur_off = 0;
+
+ // file size
+ uint64_t fsize = 0;
+};
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/common_includes.h b/packages/leann-backend-diskann/third_party/DiskANN/include/common_includes.h
new file mode 100644
index 0000000..e1a51bd
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/common_includes.h
@@ -0,0 +1,27 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <algorithm>
+#include <atomic>
+#include <cassert>
+#include <chrono>
+#include <climits>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <ctime>
+#include <fcntl.h>
+#include <fstream>
+#include <iostream>
+#include <iomanip>
+#include <omp.h>
+#include <queue>
+#include <random>
+#include <set>
+#include <shared_mutex>
+#include <sys/stat.h>
+#include <sstream>
+#include <unordered_map>
+#include <vector>
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/concurrent_queue.h b/packages/leann-backend-diskann/third_party/DiskANN/include/concurrent_queue.h
new file mode 100644
index 0000000..1e57bbf
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/concurrent_queue.h
@@ -0,0 +1,132 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+#include <queue>
+#include <thread>
+#include <type_traits>
+#include <unordered_set>
+
+namespace diskann
+{
+
+template <typename T> class ConcurrentQueue
+{
+ typedef std::chrono::microseconds chrono_us_t;
+ typedef std::unique_lock<std::mutex> mutex_locker;
+
+ std::queue<T> q;
+ std::mutex mut;
+ std::mutex push_mut;
+ std::mutex pop_mut;
+ std::condition_variable push_cv;
+ std::condition_variable pop_cv;
+ T null_T;
+
+ public:
+ ConcurrentQueue()
+ {
+ }
+
+ ConcurrentQueue(T nullT)
+ {
+ this->null_T = nullT;
+ }
+
+ ~ConcurrentQueue()
+ {
+ this->push_cv.notify_all();
+ this->pop_cv.notify_all();
+ }
+
+ // queue stats
+ uint64_t size()
+ {
+ mutex_locker lk(this->mut);
+ uint64_t ret = q.size();
+ lk.unlock();
+ return ret;
+ }
+
+ bool empty()
+ {
+ return (this->size() == 0);
+ }
+
+ // PUSH BACK
+ void push(T &new_val)
+ {
+ mutex_locker lk(this->mut);
+ this->q.push(new_val);
+ lk.unlock();
+ }
+
+ template <class Iterator> void insert(Iterator iter_begin, Iterator iter_end)
+ {
+ mutex_locker lk(this->mut);
+ for (Iterator it = iter_begin; it != iter_end; it++)
+ {
+ this->q.push(*it);
+ }
+ lk.unlock();
+ }
+
+ // POP FRONT
+ T pop()
+ {
+ mutex_locker lk(this->mut);
+ if (this->q.empty())
+ {
+ lk.unlock();
+ return this->null_T;
+ }
+ else
+ {
+ T ret = this->q.front();
+ this->q.pop();
+ // diskann::cout << "thread_id: " << std::this_thread::get_id() <<
+ // ", ctx: "
+ // << ret.ctx << "\n";
+ lk.unlock();
+ return ret;
+ }
+ }
+
+ // register for notifications
+ void wait_for_push_notify(chrono_us_t wait_time = chrono_us_t{10})
+ {
+ mutex_locker lk(this->push_mut);
+ this->push_cv.wait_for(lk, wait_time);
+ lk.unlock();
+ }
+
+ void wait_for_pop_notify(chrono_us_t wait_time = chrono_us_t{10})
+ {
+ mutex_locker lk(this->pop_mut);
+ this->pop_cv.wait_for(lk, wait_time);
+ lk.unlock();
+ }
+
+ // just notify functions
+ void push_notify_one()
+ {
+ this->push_cv.notify_one();
+ }
+ void push_notify_all()
+ {
+ this->push_cv.notify_all();
+ }
+ void pop_notify_one()
+ {
+ this->pop_cv.notify_one();
+ }
+ void pop_notify_all()
+ {
+ this->pop_cv.notify_all();
+ }
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/cosine_similarity.h b/packages/leann-backend-diskann/third_party/DiskANN/include/cosine_similarity.h
new file mode 100644
index 0000000..539a8b0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/cosine_similarity.h
@@ -0,0 +1,285 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cmath>
+#include <cstdint>
+#include <cstdlib>
+#include <vector>
+#include <limits>
+#include <algorithm>
+#include <stdexcept>
+
+#ifndef __APPLE__
+#include <immintrin.h>
+#include <smmintrin.h>
+#include <tmmintrin.h>
+#include "simd_utils.h"
+#endif
+
+extern bool Avx2SupportedCPU;
+
+#ifdef _WINDOWS
+// SIMD implementation of Cosine similarity. Taken from hnsw library.
+
+/**
+ * Non-metric Space Library
+ *
+ * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov
+ * (http://boytsov.info). With contributions from Lawrence Cayton
+ * (http://lcayton.com/) and others.
+ *
+ * For the complete list of contributors and further details see:
+ * https://github.com/searchivarius/NonMetricSpaceLib
+ *
+ * Copyright (c) 2014
+ *
+ * This code is released under the
+ * Apache License Version 2.0 http://www.apache.org/licenses/.
+ *
+ */
+
+namespace diskann
+{
+
+using namespace std;
+
+#define PORTABLE_ALIGN16 __declspec(align(16))
+
+static float NormScalarProductSIMD2(const int8_t *pVect1, const int8_t *pVect2, uint32_t qty)
+{
+ if (Avx2SupportedCPU)
+ {
+ __m256 cos, p1Len, p2Len;
+ cos = p1Len = p2Len = _mm256_setzero_ps();
+ while (qty >= 32)
+ {
+ __m256i rx = _mm256_load_si256((__m256i *)pVect1), ry = _mm256_load_si256((__m256i *)pVect2);
+ cos = _mm256_add_ps(cos, _mm256_mul_epi8(rx, ry));
+ p1Len = _mm256_add_ps(p1Len, _mm256_mul_epi8(rx, rx));
+ p2Len = _mm256_add_ps(p2Len, _mm256_mul_epi8(ry, ry));
+ pVect1 += 32;
+ pVect2 += 32;
+ qty -= 32;
+ }
+ while (qty > 0)
+ {
+ __m128i rx = _mm_load_si128((__m128i *)pVect1), ry = _mm_load_si128((__m128i *)pVect2);
+ cos = _mm256_add_ps(cos, _mm256_mul32_pi8(rx, ry));
+ p1Len = _mm256_add_ps(p1Len, _mm256_mul32_pi8(rx, rx));
+ p2Len = _mm256_add_ps(p2Len, _mm256_mul32_pi8(ry, ry));
+ pVect1 += 4;
+ pVect2 += 4;
+ qty -= 4;
+ }
+ cos = _mm256_hadd_ps(_mm256_hadd_ps(cos, cos), cos);
+ p1Len = _mm256_hadd_ps(_mm256_hadd_ps(p1Len, p1Len), p1Len);
+ p2Len = _mm256_hadd_ps(_mm256_hadd_ps(p2Len, p2Len), p2Len);
+ float denominator = max(numeric_limits<float>::min() * 2, sqrt(p1Len.m256_f32[0] + p1Len.m256_f32[4]) *
+ sqrt(p2Len.m256_f32[0] + p2Len.m256_f32[4]));
+ float cosine = (cos.m256_f32[0] + cos.m256_f32[4]) / denominator;
+
+ return max(float(-1), min(float(1), cosine));
+ }
+
+ __m128 cos, p1Len, p2Len;
+ cos = p1Len = p2Len = _mm_setzero_ps();
+ __m128i rx, ry;
+ while (qty >= 16)
+ {
+ rx = _mm_load_si128((__m128i *)pVect1);
+ ry = _mm_load_si128((__m128i *)pVect2);
+ cos = _mm_add_ps(cos, _mm_mul_epi8(rx, ry));
+ p1Len = _mm_add_ps(p1Len, _mm_mul_epi8(rx, rx));
+ p2Len = _mm_add_ps(p2Len, _mm_mul_epi8(ry, ry));
+ pVect1 += 16;
+ pVect2 += 16;
+ qty -= 16;
+ }
+ while (qty > 0)
+ {
+ rx = _mm_load_si128((__m128i *)pVect1);
+ ry = _mm_load_si128((__m128i *)pVect2);
+ cos = _mm_add_ps(cos, _mm_mul32_pi8(rx, ry));
+ p1Len = _mm_add_ps(p1Len, _mm_mul32_pi8(rx, rx));
+ p2Len = _mm_add_ps(p2Len, _mm_mul32_pi8(ry, ry));
+ pVect1 += 4;
+ pVect2 += 4;
+ qty -= 4;
+ }
+ cos = _mm_hadd_ps(_mm_hadd_ps(cos, cos), cos);
+ p1Len = _mm_hadd_ps(_mm_hadd_ps(p1Len, p1Len), p1Len);
+ p2Len = _mm_hadd_ps(_mm_hadd_ps(p2Len, p2Len), p2Len);
+ float norm1 = p1Len.m128_f32[0];
+ float norm2 = p2Len.m128_f32[0];
+
+ static const float eps = numeric_limits<float>::min() * 2;
+
+ if (norm1 < eps)
+ { /*
+ * This shouldn't normally happen for this space, but
+ * if it does, we don't want to get NANs
+ */
+ if (norm2 < eps)
+ {
+ return 1;
+ }
+ return 0;
+ }
+ /*
+ * Sometimes due to rounding errors, we get values > 1 or < -1.
+ * This throws off other functions that use scalar product, e.g., acos
+ */
+ return max(float(-1), min(float(1), cos.m128_f32[0] / sqrt(norm1) / sqrt(norm2)));
+}
+
+static float NormScalarProductSIMD(const float *pVect1, const float *pVect2, uint32_t qty)
+{
+ // Didn't get significant performance gain compared with 128bit version.
+ static const float eps = numeric_limits<float>::min() * 2;
+
+ if (Avx2SupportedCPU)
+ {
+ uint32_t qty8 = qty / 8;
+
+ const float *pEnd1 = pVect1 + 8 * qty8;
+ const float *pEnd2 = pVect1 + qty;
+
+ __m256 v1, v2;
+ __m256 sum_prod = _mm256_set_ps(0, 0, 0, 0, 0, 0, 0, 0);
+ __m256 sum_square1 = sum_prod;
+ __m256 sum_square2 = sum_prod;
+
+ while (pVect1 < pEnd1)
+ {
+ v1 = _mm256_loadu_ps(pVect1);
+ pVect1 += 8;
+ v2 = _mm256_loadu_ps(pVect2);
+ pVect2 += 8;
+ sum_prod = _mm256_add_ps(sum_prod, _mm256_mul_ps(v1, v2));
+ sum_square1 = _mm256_add_ps(sum_square1, _mm256_mul_ps(v1, v1));
+ sum_square2 = _mm256_add_ps(sum_square2, _mm256_mul_ps(v2, v2));
+ }
+
+ float PORTABLE_ALIGN16 TmpResProd[8];
+ float PORTABLE_ALIGN16 TmpResSquare1[8];
+ float PORTABLE_ALIGN16 TmpResSquare2[8];
+
+ _mm256_store_ps(TmpResProd, sum_prod);
+ _mm256_store_ps(TmpResSquare1, sum_square1);
+ _mm256_store_ps(TmpResSquare2, sum_square2);
+
+ float sum = 0.0f;
+ float norm1 = 0.0f;
+ float norm2 = 0.0f;
+ for (uint32_t i = 0; i < 8; ++i)
+ {
+ sum += TmpResProd[i];
+ norm1 += TmpResSquare1[i];
+ norm2 += TmpResSquare2[i];
+ }
+
+ while (pVect1 < pEnd2)
+ {
+ sum += (*pVect1) * (*pVect2);
+ norm1 += (*pVect1) * (*pVect1);
+ norm2 += (*pVect2) * (*pVect2);
+
+ ++pVect1;
+ ++pVect2;
+ }
+
+ if (norm1 < eps)
+ {
+ return norm2 < eps ? 1.0f : 0.0f;
+ }
+
+ return max(float(-1), min(float(1), sum / sqrt(norm1) / sqrt(norm2)));
+ }
+
+ __m128 v1, v2;
+ __m128 sum_prod = _mm_set1_ps(0);
+ __m128 sum_square1 = sum_prod;
+ __m128 sum_square2 = sum_prod;
+
+ while (qty >= 4)
+ {
+ v1 = _mm_loadu_ps(pVect1);
+ pVect1 += 4;
+ v2 = _mm_loadu_ps(pVect2);
+ pVect2 += 4;
+ sum_prod = _mm_add_ps(sum_prod, _mm_mul_ps(v1, v2));
+ sum_square1 = _mm_add_ps(sum_square1, _mm_mul_ps(v1, v1));
+ sum_square2 = _mm_add_ps(sum_square2, _mm_mul_ps(v2, v2));
+
+ qty -= 4;
+ }
+
+ float sum = sum_prod.m128_f32[0] + sum_prod.m128_f32[1] + sum_prod.m128_f32[2] + sum_prod.m128_f32[3];
+ float norm1 = sum_square1.m128_f32[0] + sum_square1.m128_f32[1] + sum_square1.m128_f32[2] + sum_square1.m128_f32[3];
+ float norm2 = sum_square2.m128_f32[0] + sum_square2.m128_f32[1] + sum_square2.m128_f32[2] + sum_square2.m128_f32[3];
+
+ if (norm1 < eps)
+ {
+ return norm2 < eps ? 1.0f : 0.0f;
+ }
+
+ return max(float(-1), min(float(1), sum / sqrt(norm1) / sqrt(norm2)));
+}
+
+static float NormScalarProductSIMD2(const float *pVect1, const float *pVect2, uint32_t qty)
+{
+ return NormScalarProductSIMD(pVect1, pVect2, qty);
+}
+
+template <class T> static float CosineSimilarity2(const T *p1, const T *p2, uint32_t qty)
+{
+ return std::max(0.0f, 1.0f - NormScalarProductSIMD2(p1, p2, qty));
+}
+
+// static template float CosineSimilarity2<__int8>(const __int8* pVect1,
+// const __int8* pVect2, size_t qty);
+
+// static template float CosineSimilarity2<float>(const float* pVect1,
+// const float* pVect2, size_t qty);
+
+template <class T> static void CosineSimilarityNormalize(T *pVector, uint32_t qty)
+{
+ T sum = 0;
+ for (uint32_t i = 0; i < qty; ++i)
+ {
+ sum += pVector[i] * pVector[i];
+ }
+ sum = 1 / sqrt(sum);
+ if (sum == 0)
+ {
+ sum = numeric_limits<T>::min();
+ }
+ for (uint32_t i = 0; i < qty; ++i)
+ {
+ pVector[i] *= sum;
+ }
+}
+
+// template static void CosineSimilarityNormalize<float>(float* pVector,
+// size_t qty);
+// template static void CosineSimilarityNormalize<double>(double* pVector,
+// size_t qty);
+
+template <> void CosineSimilarityNormalize(__int8 * /*pVector*/, uint32_t /*qty*/)
+{
+ throw std::runtime_error("For int8 type vector, you can not use cosine distance!");
+}
+
+template <> void CosineSimilarityNormalize(__int16 * /*pVector*/, uint32_t /*qty*/)
+{
+ throw std::runtime_error("For int16 type vector, you can not use cosine distance!");
+}
+
+template <> void CosineSimilarityNormalize(int * /*pVector*/, uint32_t /*qty*/)
+{
+ throw std::runtime_error("For int type vector, you can not use cosine distance!");
+}
+} // namespace diskann
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/defaults.h b/packages/leann-backend-diskann/third_party/DiskANN/include/defaults.h
new file mode 100644
index 0000000..ef1750f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/defaults.h
@@ -0,0 +1,34 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <stdint.h>
+
+namespace diskann
+{
+namespace defaults
+{
+const float ALPHA = 1.2f;
+const uint32_t NUM_THREADS = 0;
+const uint32_t MAX_OCCLUSION_SIZE = 750;
+const bool HAS_LABELS = false;
+const uint32_t FILTER_LIST_SIZE = 0;
+const uint32_t NUM_FROZEN_POINTS_STATIC = 0;
+const uint32_t NUM_FROZEN_POINTS_DYNAMIC = 1;
+
+// In-mem index related limits
+const float GRAPH_SLACK_FACTOR = 1.3f;
+
+// SSD Index related limits
+const uint64_t MAX_GRAPH_DEGREE = 512;
+const uint64_t SECTOR_LEN = 4096;
+const uint64_t MAX_N_SECTOR_READS = 128;
+
+// following constants should always be specified, but are useful as a
+// sensible default at cli / python boundaries
+const uint32_t MAX_DEGREE = 64;
+const uint32_t BUILD_LIST_SIZE = 100;
+const uint32_t SATURATE_GRAPH = false;
+const uint32_t SEARCH_LIST_SIZE = 100;
+} // namespace defaults
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/disk_utils.h b/packages/leann-backend-diskann/third_party/DiskANN/include/disk_utils.h
new file mode 100644
index 0000000..08f046d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/disk_utils.h
@@ -0,0 +1,108 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <algorithm>
+#include <fcntl.h>
+#include <cassert>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <random>
+#include <set>
+#ifdef __APPLE__
+#else
+#include <malloc.h>
+#endif
+
+#ifdef _WINDOWS
+#include <Windows.h>
+typedef HANDLE FileHandle;
+#else
+#include <unistd.h>
+typedef int FileHandle;
+#endif
+
+#include "cached_io.h"
+#include "common_includes.h"
+
+#include "utils.h"
+#include "windows_customizations.h"
+
+namespace diskann
+{
+const size_t MAX_SAMPLE_POINTS_FOR_WARMUP = 100000;
+const double PQ_TRAINING_SET_FRACTION = 0.1;
+const double SPACE_FOR_CACHED_NODES_IN_GB = 0.25;
+const double THRESHOLD_FOR_CACHING_IN_GB = 1.0;
+const uint32_t NUM_NODES_TO_CACHE = 250000;
+const uint32_t WARMUP_L = 20;
+const uint32_t NUM_KMEANS_REPS = 12;
+
+template <typename T, typename LabelT> class PQFlashIndex;
+
+DISKANN_DLLEXPORT double get_memory_budget(const std::string &mem_budget_str);
+DISKANN_DLLEXPORT double get_memory_budget(double search_ram_budget_in_gb);
+DISKANN_DLLEXPORT void add_new_file_to_single_index(std::string index_file, std::string new_file);
+
+DISKANN_DLLEXPORT size_t calculate_num_pq_chunks(double final_index_ram_limit, size_t points_num, uint32_t dim);
+
+DISKANN_DLLEXPORT void read_idmap(const std::string &fname, std::vector<uint32_t> &ivecs);
+
+#ifdef EXEC_ENV_OLS
+template <typename T>
+DISKANN_DLLEXPORT T *load_warmup(MemoryMappedFiles &files, const std::string &cache_warmup_file, uint64_t &warmup_num,
+ uint64_t warmup_dim, uint64_t warmup_aligned_dim);
+#else
+template <typename T>
+DISKANN_DLLEXPORT T *load_warmup(const std::string &cache_warmup_file, uint64_t &warmup_num, uint64_t warmup_dim,
+ uint64_t warmup_aligned_dim);
+#endif
+
+DISKANN_DLLEXPORT int merge_shards(const std::string &vamana_prefix, const std::string &vamana_suffix,
+ const std::string &idmaps_prefix, const std::string &idmaps_suffix,
+ const uint64_t nshards, uint32_t max_degree, const std::string &output_vamana,
+ const std::string &medoids_file, bool use_filters = false,
+ const std::string &labels_to_medoids_file = std::string(""));
+
+DISKANN_DLLEXPORT void extract_shard_labels(const std::string &in_label_file, const std::string &shard_ids_bin,
+ const std::string &shard_label_file);
+
+template <typename T>
+DISKANN_DLLEXPORT std::string preprocess_base_file(const std::string &infile, const std::string &indexPrefix,
+ diskann::Metric &distMetric);
+
+template <typename T, typename LabelT = uint32_t>
+DISKANN_DLLEXPORT int build_merged_vamana_index(std::string base_file, diskann::Metric _compareMetric, uint32_t L,
+ uint32_t R, double sampling_rate, double ram_budget,
+ std::string mem_index_path, std::string medoids_file,
+ std::string centroids_file, size_t build_pq_bytes, bool use_opq,
+ uint32_t num_threads, bool use_filters = false,
+ const std::string &label_file = std::string(""),
+ const std::string &labels_to_medoids_file = std::string(""),
+ const std::string &universal_label = "", const uint32_t Lf = 0);
+
+template <typename T, typename LabelT>
+DISKANN_DLLEXPORT uint32_t optimize_beamwidth(std::unique_ptr<diskann::PQFlashIndex<T, LabelT>> &_pFlashIndex,
+ T *tuning_sample, uint64_t tuning_sample_num,
+ uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads,
+ uint32_t start_bw = 2);
+
+template <typename T, typename LabelT = uint32_t>
+DISKANN_DLLEXPORT int build_disk_index(
+ const char *dataFilePath, const char *indexFilePath, const char *indexBuildParameters,
+ diskann::Metric _compareMetric, bool use_opq = false,
+ const std::string &codebook_prefix = "", // default is empty for no codebook pass in
+ bool use_filters = false,
+ const std::string &label_file = std::string(""), // default is empty string for no label_file
+ const std::string &universal_label = "", const uint32_t filter_threshold = 0,
+ const uint32_t Lf = 0); // default is empty string for no universal label
+
+template <typename T>
+DISKANN_DLLEXPORT void create_disk_layout(const std::string base_file, const std::string mem_index_file,
+ const std::string output_file,
+ const std::string reorder_data_file = std::string(""));
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/distance.h b/packages/leann-backend-diskann/third_party/DiskANN/include/distance.h
new file mode 100644
index 0000000..7198308
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/distance.h
@@ -0,0 +1,236 @@
+#pragma once
+#include "windows_customizations.h"
+#include <cstring>
+#include <cstdint>
+
+namespace diskann
+{
+enum Metric
+{
+ L2 = 0,
+ INNER_PRODUCT = 1,
+ COSINE = 2,
+ FAST_L2 = 3
+};
+
+template <typename T> class Distance
+{
+ public:
+ DISKANN_DLLEXPORT Distance(diskann::Metric dist_metric) : _distance_metric(dist_metric)
+ {
+ }
+
+ // distance comparison function
+ DISKANN_DLLEXPORT virtual float compare(const T *a, const T *b, uint32_t length) const = 0;
+
+ // Needed only for COSINE-BYTE and INNER_PRODUCT-BYTE
+ DISKANN_DLLEXPORT virtual float compare(const T *a, const T *b, const float normA, const float normB,
+ uint32_t length) const;
+
+ // For MIPS, normalization adds an extra dimension to the vectors.
+ // This function lets callers know if the normalization process
+ // changes the dimension.
+ DISKANN_DLLEXPORT virtual uint32_t post_normalization_dimension(uint32_t orig_dimension) const;
+
+ DISKANN_DLLEXPORT virtual diskann::Metric get_metric() const;
+
+ // This is for efficiency. If no normalization is required, the callers
+ // can simply ignore the normalize_data_for_build() function.
+ DISKANN_DLLEXPORT virtual bool preprocessing_required() const;
+
+ // Check the preprocessing_required() function before calling this.
+ // Clients can call the function like this:
+ //
+ // if (metric->preprocessing_required()){
+ // T* normalized_data_batch;
+ // Split data into batches of batch_size and for each, call:
+ // metric->preprocess_base_points(data_batch, batch_size);
+ //
+ // TODO: This does not take into account the case for SSD inner product
+ // where the dimensions change after normalization.
+ DISKANN_DLLEXPORT virtual void preprocess_base_points(T *original_data, const size_t orig_dim,
+ const size_t num_points);
+
+ // Invokes normalization for a single vector during search. The scratch space
+ // has to be created by the caller keeping track of the fact that
+ // normalization might change the dimension of the query vector.
+ DISKANN_DLLEXPORT virtual void preprocess_query(const T *query_vec, const size_t query_dim, T *scratch_query);
+
+ // If an algorithm has a requirement that some data be aligned to a certain
+ // boundary it can use this function to indicate that requirement. Currently,
+ // we are setting it to 8 because that works well for AVX2. If we have AVX512
+ // implementations of distance algos, they might have to set this to 16
+ // (depending on how they are implemented)
+ DISKANN_DLLEXPORT virtual size_t get_required_alignment() const;
+
+ // Providing a default implementation for the virtual destructor because we
+ // don't expect most metric implementations to need it.
+ DISKANN_DLLEXPORT virtual ~Distance() = default;
+
+ protected:
+ diskann::Metric _distance_metric;
+ size_t _alignment_factor = 8;
+};
+
+class DistanceCosineInt8 : public Distance<int8_t>
+{
+ public:
+ DistanceCosineInt8() : Distance<int8_t>(diskann::Metric::COSINE)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const int8_t *a, const int8_t *b, uint32_t length) const;
+};
+
+class DistanceL2Int8 : public Distance<int8_t>
+{
+ public:
+ DistanceL2Int8() : Distance<int8_t>(diskann::Metric::L2)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const int8_t *a, const int8_t *b, uint32_t size) const;
+};
+
+// AVX implementations. Borrowed from HNSW code.
+class AVXDistanceL2Int8 : public Distance<int8_t>
+{
+ public:
+ AVXDistanceL2Int8() : Distance<int8_t>(diskann::Metric::L2)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const int8_t *a, const int8_t *b, uint32_t length) const;
+};
+
+class DistanceCosineFloat : public Distance<float>
+{
+ public:
+ DistanceCosineFloat() : Distance<float>(diskann::Metric::COSINE)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const float *a, const float *b, uint32_t length) const;
+};
+
+class DistanceL2Float : public Distance<float>
+{
+ public:
+ DistanceL2Float() : Distance<float>(diskann::Metric::L2)
+ {
+ }
+
+#ifdef _WINDOWS
+ DISKANN_DLLEXPORT virtual float compare(const float *a, const float *b, uint32_t size) const;
+#else
+ DISKANN_DLLEXPORT virtual float compare(const float *a, const float *b, uint32_t size) const __attribute__((hot));
+#endif
+};
+
+class AVXDistanceL2Float : public Distance<float>
+{
+ public:
+ AVXDistanceL2Float() : Distance<float>(diskann::Metric::L2)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const float *a, const float *b, uint32_t length) const;
+};
+
+template <typename T> class SlowDistanceL2 : public Distance<T>
+{
+ public:
+ SlowDistanceL2() : Distance<T>(diskann::Metric::L2)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const T *a, const T *b, uint32_t length) const;
+};
+
+class SlowDistanceCosineUInt8 : public Distance<uint8_t>
+{
+ public:
+ SlowDistanceCosineUInt8() : Distance<uint8_t>(diskann::Metric::COSINE)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const uint8_t *a, const uint8_t *b, uint32_t length) const;
+};
+
+class DistanceL2UInt8 : public Distance<uint8_t>
+{
+ public:
+ DistanceL2UInt8() : Distance<uint8_t>(diskann::Metric::L2)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const uint8_t *a, const uint8_t *b, uint32_t size) const;
+};
+
+template <typename T> class DistanceInnerProduct : public Distance<T>
+{
+ public:
+ DistanceInnerProduct() : Distance<T>(diskann::Metric::INNER_PRODUCT)
+ {
+ }
+
+ DistanceInnerProduct(diskann::Metric metric) : Distance<T>(metric)
+ {
+ }
+ inline float inner_product(const T *a, const T *b, unsigned size) const;
+
+ inline float compare(const T *a, const T *b, unsigned size) const
+ {
+ float result = inner_product(a, b, size);
+ // if (result < 0)
+ // return std::numeric_limits<float>::max();
+ // else
+ return -result;
+ }
+};
+
+template <typename T> class DistanceFastL2 : public DistanceInnerProduct<T>
+{
+ // currently defined only for float.
+ // templated for future use.
+ public:
+ DistanceFastL2() : DistanceInnerProduct<T>(diskann::Metric::FAST_L2)
+ {
+ }
+ float norm(const T *a, unsigned size) const;
+ float compare(const T *a, const T *b, float norm, unsigned size) const;
+};
+
+class AVXDistanceInnerProductFloat : public Distance<float>
+{
+ public:
+ AVXDistanceInnerProductFloat() : Distance<float>(diskann::Metric::INNER_PRODUCT)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const float *a, const float *b, uint32_t length) const;
+};
+
+class AVXNormalizedCosineDistanceFloat : public Distance<float>
+{
+ private:
+ AVXDistanceInnerProductFloat _innerProduct;
+
+ protected:
+ void normalize_and_copy(const float *a, uint32_t length, float *a_norm) const;
+
+ public:
+ AVXNormalizedCosineDistanceFloat() : Distance<float>(diskann::Metric::COSINE)
+ {
+ }
+ DISKANN_DLLEXPORT virtual float compare(const float *a, const float *b, uint32_t length) const override
+ {
+ // Inner product returns negative values to indicate distance.
+ // This will ensure that cosine is between -1 and 1.
+ return 1.0f + _innerProduct.compare(a, b, length);
+ }
+ DISKANN_DLLEXPORT virtual uint32_t post_normalization_dimension(uint32_t orig_dimension) const override;
+
+ DISKANN_DLLEXPORT virtual bool preprocessing_required() const override;
+
+ DISKANN_DLLEXPORT virtual void preprocess_base_points(float *original_data, const size_t orig_dim,
+ const size_t num_points) override;
+
+ DISKANN_DLLEXPORT virtual void preprocess_query(const float *query_vec, const size_t query_dim,
+ float *scratch_query_vector) override;
+};
+
+template <typename T> Distance<T> *get_distance_function(Metric m);
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/embedding.pb.h b/packages/leann-backend-diskann/third_party/DiskANN/include/embedding.pb.h
new file mode 100644
index 0000000..9f5c2b7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/embedding.pb.h
@@ -0,0 +1,675 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: embedding.proto
+
+#ifndef GOOGLE_PROTOBUF_INCLUDED_embedding_2eproto
+#define GOOGLE_PROTOBUF_INCLUDED_embedding_2eproto
+
+#include <limits>
+#include <string>
+
+#include <google/protobuf/port_def.inc>
+#if PROTOBUF_VERSION < 3012000
+#error This file was generated by a newer version of protoc which is
+#error incompatible with your Protocol Buffer headers. Please update
+#error your headers.
+#endif
+#if 3012004 < PROTOBUF_MIN_PROTOC_VERSION
+#error This file was generated by an older version of protoc which is
+#error incompatible with your Protocol Buffer headers. Please
+#error regenerate this file with a newer version of protoc.
+#endif
+
+#include <google/protobuf/port_undef.inc>
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/arena.h>
+#include <google/protobuf/arenastring.h>
+#include <google/protobuf/generated_message_table_driven.h>
+#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/inlined_string_field.h>
+#include <google/protobuf/metadata_lite.h>
+#include <google/protobuf/generated_message_reflection.h>
+#include <google/protobuf/message.h>
+#include <google/protobuf/repeated_field.h> // IWYU pragma: export
+#include <google/protobuf/extension_set.h> // IWYU pragma: export
+#include <google/protobuf/unknown_field_set.h>
+// @@protoc_insertion_point(includes)
+#include <google/protobuf/port_def.inc>
+#define PROTOBUF_INTERNAL_EXPORT_embedding_2eproto
+PROTOBUF_NAMESPACE_OPEN
+namespace internal {
+class AnyMetadata;
+} // namespace internal
+PROTOBUF_NAMESPACE_CLOSE
+
+// Internal implementation detail -- do not use these members.
+struct TableStruct_embedding_2eproto {
+ static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[2]
+ PROTOBUF_SECTION_VARIABLE(protodesc_cold);
+ static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
+ static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
+ static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
+};
+extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_embedding_2eproto;
+namespace protoembedding {
+class NodeEmbeddingRequest;
+class NodeEmbeddingRequestDefaultTypeInternal;
+extern NodeEmbeddingRequestDefaultTypeInternal _NodeEmbeddingRequest_default_instance_;
+class NodeEmbeddingResponse;
+class NodeEmbeddingResponseDefaultTypeInternal;
+extern NodeEmbeddingResponseDefaultTypeInternal _NodeEmbeddingResponse_default_instance_;
+} // namespace protoembedding
+PROTOBUF_NAMESPACE_OPEN
+template<> ::protoembedding::NodeEmbeddingRequest* Arena::CreateMaybeMessage<::protoembedding::NodeEmbeddingRequest>(Arena*);
+template<> ::protoembedding::NodeEmbeddingResponse* Arena::CreateMaybeMessage<::protoembedding::NodeEmbeddingResponse>(Arena*);
+PROTOBUF_NAMESPACE_CLOSE
+namespace protoembedding {
+
+// ===================================================================
+
+class NodeEmbeddingRequest PROTOBUF_FINAL :
+ public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protoembedding.NodeEmbeddingRequest) */ {
+ public:
+ inline NodeEmbeddingRequest() : NodeEmbeddingRequest(nullptr) {};
+ virtual ~NodeEmbeddingRequest();
+
+ NodeEmbeddingRequest(const NodeEmbeddingRequest& from);
+ NodeEmbeddingRequest(NodeEmbeddingRequest&& from) noexcept
+ : NodeEmbeddingRequest() {
+ *this = ::std::move(from);
+ }
+
+ inline NodeEmbeddingRequest& operator=(const NodeEmbeddingRequest& from) {
+ CopyFrom(from);
+ return *this;
+ }
+ inline NodeEmbeddingRequest& operator=(NodeEmbeddingRequest&& from) noexcept {
+ if (GetArena() == from.GetArena()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
+ return GetDescriptor();
+ }
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
+ return GetMetadataStatic().descriptor;
+ }
+ static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
+ return GetMetadataStatic().reflection;
+ }
+ static const NodeEmbeddingRequest& default_instance();
+
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
+ static inline const NodeEmbeddingRequest* internal_default_instance() {
+ return reinterpret_cast<const NodeEmbeddingRequest*>(
+ &_NodeEmbeddingRequest_default_instance_);
+ }
+ static constexpr int kIndexInFileMessages =
+ 0;
+
+ friend void swap(NodeEmbeddingRequest& a, NodeEmbeddingRequest& b) {
+ a.Swap(&b);
+ }
+ inline void Swap(NodeEmbeddingRequest* other) {
+ if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(NodeEmbeddingRequest* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
+ InternalSwap(other);
+ }
+
+ // implements Message ----------------------------------------------
+
+ inline NodeEmbeddingRequest* New() const final {
+ return CreateMaybeMessage<NodeEmbeddingRequest>(nullptr);
+ }
+
+ NodeEmbeddingRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
+ return CreateMaybeMessage<NodeEmbeddingRequest>(arena);
+ }
+ void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
+ void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
+ void CopyFrom(const NodeEmbeddingRequest& from);
+ void MergeFrom(const NodeEmbeddingRequest& from);
+ PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
+ bool IsInitialized() const final;
+
+ size_t ByteSizeLong() const final;
+ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
+ ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
+ ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
+ private:
+ inline void SharedCtor();
+ inline void SharedDtor();
+ void SetCachedSize(int size) const final;
+ void InternalSwap(NodeEmbeddingRequest* other);
+ friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
+ static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
+ return "protoembedding.NodeEmbeddingRequest";
+ }
+ protected:
+ explicit NodeEmbeddingRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
+ public:
+
+ ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
+ private:
+ static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
+ ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_embedding_2eproto);
+ return ::descriptor_table_embedding_2eproto.file_level_metadata[kIndexInFileMessages];
+ }
+
+ public:
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ enum : int {
+ kNodeIdsFieldNumber = 1,
+ };
+ // repeated uint32 node_ids = 1;
+ int node_ids_size() const;
+ private:
+ int _internal_node_ids_size() const;
+ public:
+ void clear_node_ids();
+ private:
+ ::PROTOBUF_NAMESPACE_ID::uint32 _internal_node_ids(int index) const;
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+ _internal_node_ids() const;
+ void _internal_add_node_ids(::PROTOBUF_NAMESPACE_ID::uint32 value);
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+ _internal_mutable_node_ids();
+ public:
+ ::PROTOBUF_NAMESPACE_ID::uint32 node_ids(int index) const;
+ void set_node_ids(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
+ void add_node_ids(::PROTOBUF_NAMESPACE_ID::uint32 value);
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+ node_ids() const;
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+ mutable_node_ids();
+
+ // @@protoc_insertion_point(class_scope:protoembedding.NodeEmbeddingRequest)
+ private:
+ class _Internal;
+
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > node_ids_;
+ mutable std::atomic<int> _node_ids_cached_byte_size_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
+ friend struct ::TableStruct_embedding_2eproto;
+};
+// -------------------------------------------------------------------
+
+class NodeEmbeddingResponse PROTOBUF_FINAL :
+ public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:protoembedding.NodeEmbeddingResponse) */ {
+ public:
+ inline NodeEmbeddingResponse() : NodeEmbeddingResponse(nullptr) {};
+ virtual ~NodeEmbeddingResponse();
+
+ NodeEmbeddingResponse(const NodeEmbeddingResponse& from);
+ NodeEmbeddingResponse(NodeEmbeddingResponse&& from) noexcept
+ : NodeEmbeddingResponse() {
+ *this = ::std::move(from);
+ }
+
+ inline NodeEmbeddingResponse& operator=(const NodeEmbeddingResponse& from) {
+ CopyFrom(from);
+ return *this;
+ }
+ inline NodeEmbeddingResponse& operator=(NodeEmbeddingResponse&& from) noexcept {
+ if (GetArena() == from.GetArena()) {
+ if (this != &from) InternalSwap(&from);
+ } else {
+ CopyFrom(from);
+ }
+ return *this;
+ }
+
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
+ return GetDescriptor();
+ }
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
+ return GetMetadataStatic().descriptor;
+ }
+ static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
+ return GetMetadataStatic().reflection;
+ }
+ static const NodeEmbeddingResponse& default_instance();
+
+ static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
+ static inline const NodeEmbeddingResponse* internal_default_instance() {
+ return reinterpret_cast<const NodeEmbeddingResponse*>(
+ &_NodeEmbeddingResponse_default_instance_);
+ }
+ static constexpr int kIndexInFileMessages =
+ 1;
+
+ friend void swap(NodeEmbeddingResponse& a, NodeEmbeddingResponse& b) {
+ a.Swap(&b);
+ }
+ inline void Swap(NodeEmbeddingResponse* other) {
+ if (other == this) return;
+ if (GetArena() == other->GetArena()) {
+ InternalSwap(other);
+ } else {
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
+ }
+ }
+ void UnsafeArenaSwap(NodeEmbeddingResponse* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArena() == other->GetArena());
+ InternalSwap(other);
+ }
+
+ // implements Message ----------------------------------------------
+
+ inline NodeEmbeddingResponse* New() const final {
+ return CreateMaybeMessage<NodeEmbeddingResponse>(nullptr);
+ }
+
+ NodeEmbeddingResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
+ return CreateMaybeMessage<NodeEmbeddingResponse>(arena);
+ }
+ void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
+ void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
+ void CopyFrom(const NodeEmbeddingResponse& from);
+ void MergeFrom(const NodeEmbeddingResponse& from);
+ PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
+ bool IsInitialized() const final;
+
+ size_t ByteSizeLong() const final;
+ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
+ ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
+ ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
+ int GetCachedSize() const final { return _cached_size_.Get(); }
+
+ private:
+ inline void SharedCtor();
+ inline void SharedDtor();
+ void SetCachedSize(int size) const final;
+ void InternalSwap(NodeEmbeddingResponse* other);
+ friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
+ static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
+ return "protoembedding.NodeEmbeddingResponse";
+ }
+ protected:
+ explicit NodeEmbeddingResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
+ public:
+
+ ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
+ private:
+ static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
+ ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_embedding_2eproto);
+ return ::descriptor_table_embedding_2eproto.file_level_metadata[kIndexInFileMessages];
+ }
+
+ public:
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ enum : int {
+ kDimensionsFieldNumber = 2,
+ kMissingIdsFieldNumber = 3,
+ kEmbeddingsDataFieldNumber = 1,
+ };
+ // repeated int32 dimensions = 2;
+ int dimensions_size() const;
+ private:
+ int _internal_dimensions_size() const;
+ public:
+ void clear_dimensions();
+ private:
+ ::PROTOBUF_NAMESPACE_ID::int32 _internal_dimensions(int index) const;
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
+ _internal_dimensions() const;
+ void _internal_add_dimensions(::PROTOBUF_NAMESPACE_ID::int32 value);
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
+ _internal_mutable_dimensions();
+ public:
+ ::PROTOBUF_NAMESPACE_ID::int32 dimensions(int index) const;
+ void set_dimensions(int index, ::PROTOBUF_NAMESPACE_ID::int32 value);
+ void add_dimensions(::PROTOBUF_NAMESPACE_ID::int32 value);
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
+ dimensions() const;
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
+ mutable_dimensions();
+
+ // repeated uint32 missing_ids = 3;
+ int missing_ids_size() const;
+ private:
+ int _internal_missing_ids_size() const;
+ public:
+ void clear_missing_ids();
+ private:
+ ::PROTOBUF_NAMESPACE_ID::uint32 _internal_missing_ids(int index) const;
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+ _internal_missing_ids() const;
+ void _internal_add_missing_ids(::PROTOBUF_NAMESPACE_ID::uint32 value);
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+ _internal_mutable_missing_ids();
+ public:
+ ::PROTOBUF_NAMESPACE_ID::uint32 missing_ids(int index) const;
+ void set_missing_ids(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value);
+ void add_missing_ids(::PROTOBUF_NAMESPACE_ID::uint32 value);
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+ missing_ids() const;
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+ mutable_missing_ids();
+
+ // bytes embeddings_data = 1;
+ void clear_embeddings_data();
+ const std::string& embeddings_data() const;
+ void set_embeddings_data(const std::string& value);
+ void set_embeddings_data(std::string&& value);
+ void set_embeddings_data(const char* value);
+ void set_embeddings_data(const void* value, size_t size);
+ std::string* mutable_embeddings_data();
+ std::string* release_embeddings_data();
+ void set_allocated_embeddings_data(std::string* embeddings_data);
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ std::string* unsafe_arena_release_embeddings_data();
+ GOOGLE_PROTOBUF_RUNTIME_DEPRECATED("The unsafe_arena_ accessors for"
+ " string fields are deprecated and will be removed in a"
+ " future release.")
+ void unsafe_arena_set_allocated_embeddings_data(
+ std::string* embeddings_data);
+ private:
+ const std::string& _internal_embeddings_data() const;
+ void _internal_set_embeddings_data(const std::string& value);
+ std::string* _internal_mutable_embeddings_data();
+ public:
+
+ // @@protoc_insertion_point(class_scope:protoembedding.NodeEmbeddingResponse)
+ private:
+ class _Internal;
+
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 > dimensions_;
+ mutable std::atomic<int> _dimensions_cached_byte_size_;
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 > missing_ids_;
+ mutable std::atomic<int> _missing_ids_cached_byte_size_;
+ ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr embeddings_data_;
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
+ friend struct ::TableStruct_embedding_2eproto;
+};
+// ===================================================================
+
+
+// ===================================================================
+
+#ifdef __GNUC__
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
+#endif // __GNUC__
+// NodeEmbeddingRequest
+
+// repeated uint32 node_ids = 1;
+inline int NodeEmbeddingRequest::_internal_node_ids_size() const {
+ return node_ids_.size();
+}
+inline int NodeEmbeddingRequest::node_ids_size() const {
+ return _internal_node_ids_size();
+}
+inline void NodeEmbeddingRequest::clear_node_ids() {
+ node_ids_.Clear();
+}
+inline ::PROTOBUF_NAMESPACE_ID::uint32 NodeEmbeddingRequest::_internal_node_ids(int index) const {
+ return node_ids_.Get(index);
+}
+inline ::PROTOBUF_NAMESPACE_ID::uint32 NodeEmbeddingRequest::node_ids(int index) const {
+ // @@protoc_insertion_point(field_get:protoembedding.NodeEmbeddingRequest.node_ids)
+ return _internal_node_ids(index);
+}
+inline void NodeEmbeddingRequest::set_node_ids(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
+ node_ids_.Set(index, value);
+ // @@protoc_insertion_point(field_set:protoembedding.NodeEmbeddingRequest.node_ids)
+}
+inline void NodeEmbeddingRequest::_internal_add_node_ids(::PROTOBUF_NAMESPACE_ID::uint32 value) {
+ node_ids_.Add(value);
+}
+inline void NodeEmbeddingRequest::add_node_ids(::PROTOBUF_NAMESPACE_ID::uint32 value) {
+ _internal_add_node_ids(value);
+ // @@protoc_insertion_point(field_add:protoembedding.NodeEmbeddingRequest.node_ids)
+}
+inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+NodeEmbeddingRequest::_internal_node_ids() const {
+ return node_ids_;
+}
+inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+NodeEmbeddingRequest::node_ids() const {
+ // @@protoc_insertion_point(field_list:protoembedding.NodeEmbeddingRequest.node_ids)
+ return _internal_node_ids();
+}
+inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+NodeEmbeddingRequest::_internal_mutable_node_ids() {
+ return &node_ids_;
+}
+inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+NodeEmbeddingRequest::mutable_node_ids() {
+ // @@protoc_insertion_point(field_mutable_list:protoembedding.NodeEmbeddingRequest.node_ids)
+ return _internal_mutable_node_ids();
+}
+
+// -------------------------------------------------------------------
+
+// NodeEmbeddingResponse
+
+// bytes embeddings_data = 1;
+inline void NodeEmbeddingResponse::clear_embeddings_data() {
+ embeddings_data_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+}
+inline const std::string& NodeEmbeddingResponse::embeddings_data() const {
+ // @@protoc_insertion_point(field_get:protoembedding.NodeEmbeddingResponse.embeddings_data)
+ return _internal_embeddings_data();
+}
+inline void NodeEmbeddingResponse::set_embeddings_data(const std::string& value) {
+ _internal_set_embeddings_data(value);
+ // @@protoc_insertion_point(field_set:protoembedding.NodeEmbeddingResponse.embeddings_data)
+}
+inline std::string* NodeEmbeddingResponse::mutable_embeddings_data() {
+ // @@protoc_insertion_point(field_mutable:protoembedding.NodeEmbeddingResponse.embeddings_data)
+ return _internal_mutable_embeddings_data();
+}
+inline const std::string& NodeEmbeddingResponse::_internal_embeddings_data() const {
+ return embeddings_data_.Get();
+}
+inline void NodeEmbeddingResponse::_internal_set_embeddings_data(const std::string& value) {
+
+ embeddings_data_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, GetArena());
+}
+inline void NodeEmbeddingResponse::set_embeddings_data(std::string&& value) {
+
+ embeddings_data_.Set(
+ &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::move(value), GetArena());
+ // @@protoc_insertion_point(field_set_rvalue:protoembedding.NodeEmbeddingResponse.embeddings_data)
+}
+inline void NodeEmbeddingResponse::set_embeddings_data(const char* value) {
+ GOOGLE_DCHECK(value != nullptr);
+
+ embeddings_data_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArena());
+ // @@protoc_insertion_point(field_set_char:protoembedding.NodeEmbeddingResponse.embeddings_data)
+}
+inline void NodeEmbeddingResponse::set_embeddings_data(const void* value,
+ size_t size) {
+
+ embeddings_data_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArena());
+ // @@protoc_insertion_point(field_set_pointer:protoembedding.NodeEmbeddingResponse.embeddings_data)
+}
+inline std::string* NodeEmbeddingResponse::_internal_mutable_embeddings_data() {
+
+ return embeddings_data_.Mutable(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+}
+inline std::string* NodeEmbeddingResponse::release_embeddings_data() {
+ // @@protoc_insertion_point(field_release:protoembedding.NodeEmbeddingResponse.embeddings_data)
+ return embeddings_data_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+}
+inline void NodeEmbeddingResponse::set_allocated_embeddings_data(std::string* embeddings_data) {
+ if (embeddings_data != nullptr) {
+
+ } else {
+
+ }
+ embeddings_data_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), embeddings_data,
+ GetArena());
+ // @@protoc_insertion_point(field_set_allocated:protoembedding.NodeEmbeddingResponse.embeddings_data)
+}
+inline std::string* NodeEmbeddingResponse::unsafe_arena_release_embeddings_data() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:protoembedding.NodeEmbeddingResponse.embeddings_data)
+ GOOGLE_DCHECK(GetArena() != nullptr);
+
+ return embeddings_data_.UnsafeArenaRelease(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ GetArena());
+}
+inline void NodeEmbeddingResponse::unsafe_arena_set_allocated_embeddings_data(
+ std::string* embeddings_data) {
+ GOOGLE_DCHECK(GetArena() != nullptr);
+ if (embeddings_data != nullptr) {
+
+ } else {
+
+ }
+ embeddings_data_.UnsafeArenaSetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
+ embeddings_data, GetArena());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:protoembedding.NodeEmbeddingResponse.embeddings_data)
+}
+
+// repeated int32 dimensions = 2;
+inline int NodeEmbeddingResponse::_internal_dimensions_size() const {
+ return dimensions_.size();
+}
+inline int NodeEmbeddingResponse::dimensions_size() const {
+ return _internal_dimensions_size();
+}
+inline void NodeEmbeddingResponse::clear_dimensions() {
+ dimensions_.Clear();
+}
+inline ::PROTOBUF_NAMESPACE_ID::int32 NodeEmbeddingResponse::_internal_dimensions(int index) const {
+ return dimensions_.Get(index);
+}
+inline ::PROTOBUF_NAMESPACE_ID::int32 NodeEmbeddingResponse::dimensions(int index) const {
+ // @@protoc_insertion_point(field_get:protoembedding.NodeEmbeddingResponse.dimensions)
+ return _internal_dimensions(index);
+}
+inline void NodeEmbeddingResponse::set_dimensions(int index, ::PROTOBUF_NAMESPACE_ID::int32 value) {
+ dimensions_.Set(index, value);
+ // @@protoc_insertion_point(field_set:protoembedding.NodeEmbeddingResponse.dimensions)
+}
+inline void NodeEmbeddingResponse::_internal_add_dimensions(::PROTOBUF_NAMESPACE_ID::int32 value) {
+ dimensions_.Add(value);
+}
+inline void NodeEmbeddingResponse::add_dimensions(::PROTOBUF_NAMESPACE_ID::int32 value) {
+ _internal_add_dimensions(value);
+ // @@protoc_insertion_point(field_add:protoembedding.NodeEmbeddingResponse.dimensions)
+}
+inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
+NodeEmbeddingResponse::_internal_dimensions() const {
+ return dimensions_;
+}
+inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >&
+NodeEmbeddingResponse::dimensions() const {
+ // @@protoc_insertion_point(field_list:protoembedding.NodeEmbeddingResponse.dimensions)
+ return _internal_dimensions();
+}
+inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
+NodeEmbeddingResponse::_internal_mutable_dimensions() {
+ return &dimensions_;
+}
+inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::int32 >*
+NodeEmbeddingResponse::mutable_dimensions() {
+ // @@protoc_insertion_point(field_mutable_list:protoembedding.NodeEmbeddingResponse.dimensions)
+ return _internal_mutable_dimensions();
+}
+
+// repeated uint32 missing_ids = 3;
+inline int NodeEmbeddingResponse::_internal_missing_ids_size() const {
+ return missing_ids_.size();
+}
+inline int NodeEmbeddingResponse::missing_ids_size() const {
+ return _internal_missing_ids_size();
+}
+inline void NodeEmbeddingResponse::clear_missing_ids() {
+ missing_ids_.Clear();
+}
+inline ::PROTOBUF_NAMESPACE_ID::uint32 NodeEmbeddingResponse::_internal_missing_ids(int index) const {
+ return missing_ids_.Get(index);
+}
+inline ::PROTOBUF_NAMESPACE_ID::uint32 NodeEmbeddingResponse::missing_ids(int index) const {
+ // @@protoc_insertion_point(field_get:protoembedding.NodeEmbeddingResponse.missing_ids)
+ return _internal_missing_ids(index);
+}
+inline void NodeEmbeddingResponse::set_missing_ids(int index, ::PROTOBUF_NAMESPACE_ID::uint32 value) {
+ missing_ids_.Set(index, value);
+ // @@protoc_insertion_point(field_set:protoembedding.NodeEmbeddingResponse.missing_ids)
+}
+inline void NodeEmbeddingResponse::_internal_add_missing_ids(::PROTOBUF_NAMESPACE_ID::uint32 value) {
+ missing_ids_.Add(value);
+}
+inline void NodeEmbeddingResponse::add_missing_ids(::PROTOBUF_NAMESPACE_ID::uint32 value) {
+ _internal_add_missing_ids(value);
+ // @@protoc_insertion_point(field_add:protoembedding.NodeEmbeddingResponse.missing_ids)
+}
+inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+NodeEmbeddingResponse::_internal_missing_ids() const {
+ return missing_ids_;
+}
+inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >&
+NodeEmbeddingResponse::missing_ids() const {
+ // @@protoc_insertion_point(field_list:protoembedding.NodeEmbeddingResponse.missing_ids)
+ return _internal_missing_ids();
+}
+inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+NodeEmbeddingResponse::_internal_mutable_missing_ids() {
+ return &missing_ids_;
+}
+inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< ::PROTOBUF_NAMESPACE_ID::uint32 >*
+NodeEmbeddingResponse::mutable_missing_ids() {
+ // @@protoc_insertion_point(field_mutable_list:protoembedding.NodeEmbeddingResponse.missing_ids)
+ return _internal_mutable_missing_ids();
+}
+
+#ifdef __GNUC__
+ #pragma GCC diagnostic pop
+#endif // __GNUC__
+// -------------------------------------------------------------------
+
+
+// @@protoc_insertion_point(namespace_scope)
+
+} // namespace protoembedding
+
+// @@protoc_insertion_point(global_scope)
+
+#include <google/protobuf/port_undef.inc>
+#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_embedding_2eproto
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/embedding_compute.h b/packages/leann-backend-diskann/third_party/DiskANN/include/embedding_compute.h
new file mode 100644
index 0000000..354c9c5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/embedding_compute.h
@@ -0,0 +1,118 @@
+#pragma once
+
+#include <vector>
+#include <memory>
+
+#ifdef PYBIND11_EMBEDDED
+#include <pybind11/embed.h>
+#else
+#include <pybind11/pybind11.h>
+#endif
+#include <pybind11/numpy.h>
+#include <pybind11/stl.h>
+
+namespace py = pybind11;
+
+namespace diskann
+{
+
+class PYBIND11_EXPORT EmbeddingComputer
+{
+ public:
+ static EmbeddingComputer &getInstance()
+ {
+ static EmbeddingComputer instance;
+ return instance;
+ }
+
+ void initialize(const std::string &model_path)
+ {
+ try
+ {
+ py::module_ sys = py::module_::import("sys");
+ py::module_ os = py::module_::import("os");
+
+ // Add the directory containing embedd_micro.py to Python path
+ std::string micro_dir = "micro";
+ sys.attr("path").attr("append")(micro_dir);
+
+ // Import our module
+ py::module_ embedd = py::module_::import("embedd_micro");
+
+ // Create benchmark config
+ py::object config = embedd.attr("BenchmarkConfig")(model_path, // model_path
+ py::list(), // empty batch_sizes
+ 256, // seq_length
+ 1, // num_runs
+ true, // use_fp16
+ false, // use_cuda_graphs
+ false // use_flash_attention
+ );
+
+ // Create benchmark instance
+ benchmark = embedd.attr("Benchmark")(config);
+ }
+ catch (const std::exception &e)
+ {
+ throw std::runtime_error("Failed to initialize Python embedding computer: " + std::string(e.what()));
+ }
+ }
+
+ template <typename T>
+ std::vector<float> computeEmbeddings(const std::vector<T *> &points, size_t dim, size_t batch_size = 32)
+ {
+ try
+ {
+ // Convert points to numpy array
+ std::vector<T> flattened_points;
+ flattened_points.reserve(points.size() * dim);
+
+ for (const auto &point : points)
+ {
+ flattened_points.insert(flattened_points.end(), point, point + dim);
+ }
+
+ py::array_t<T> points_array({static_cast<long>(points.size()), static_cast<long>(dim)},
+ flattened_points.data());
+
+ // Call compute_embeddings
+ py::object result = benchmark.attr("compute_embeddings")(points_array, batch_size);
+
+ // Convert result back to C++
+ py::array_t<float> np_result = result.cast<py::array_t<float>>();
+ py::buffer_info buf = np_result.request();
+ float *ptr = static_cast<float *>(buf.ptr);
+
+ return std::vector<float>(ptr, ptr + buf.size);
+ }
+ catch (const std::exception &e)
+ {
+ throw std::runtime_error("Failed to compute embeddings: " + std::string(e.what()));
+ }
+ }
+
+ private:
+ EmbeddingComputer()
+ {
+#ifdef PYBIND11_EMBEDDED
+ if (!Py_IsInitialized())
+ {
+ py::initialize_interpreter();
+ }
+#endif
+ }
+
+ ~EmbeddingComputer()
+ {
+#ifdef PYBIND11_EMBEDDED
+ if (Py_IsInitialized())
+ {
+ py::finalize_interpreter();
+ }
+#endif
+ }
+
+ py::object benchmark;
+};
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/exceptions.h b/packages/leann-backend-diskann/third_party/DiskANN/include/exceptions.h
new file mode 100644
index 0000000..99e4e73
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/exceptions.h
@@ -0,0 +1,17 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <stdexcept>
+
+namespace diskann
+{
+
+class NotImplementedException : public std::logic_error
+{
+ public:
+ NotImplementedException() : std::logic_error("Function not yet implemented.")
+ {
+ }
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/filter_utils.h b/packages/leann-backend-diskann/third_party/DiskANN/include/filter_utils.h
new file mode 100644
index 0000000..55f7aed
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/filter_utils.h
@@ -0,0 +1,221 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <algorithm>
+#include <fcntl.h>
+#include <cassert>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <random>
+#include <set>
+#include <tuple>
+#include <string>
+#include <tsl/robin_map.h>
+#include <tsl/robin_set.h>
+#ifdef __APPLE__
+#else
+#include <malloc.h>
+#endif
+
+#ifdef _WINDOWS
+#include <Windows.h>
+typedef HANDLE FileHandle;
+#else
+#include <unistd.h>
+typedef int FileHandle;
+#endif
+
+#ifndef _WINDOWS
+#include <sys/uio.h>
+#endif
+
+#include "cached_io.h"
+#include "common_includes.h"
+#include "memory_mapper.h"
+#include "utils.h"
+#include "windows_customizations.h"
+
+// custom types (for readability)
+typedef tsl::robin_set<std::string> label_set;
+typedef std::string path;
+
+// structs for returning multiple items from a function
+typedef std::tuple<std::vector<label_set>, tsl::robin_map<std::string, uint32_t>, tsl::robin_set<std::string>>
+ parse_label_file_return_values;
+typedef std::tuple<std::vector<std::vector<uint32_t>>, uint64_t> load_label_index_return_values;
+
+namespace diskann
+{
+template <typename T>
+DISKANN_DLLEXPORT void generate_label_indices(path input_data_path, path final_index_path_prefix, label_set all_labels,
+ unsigned R, unsigned L, float alpha, unsigned num_threads);
+
+DISKANN_DLLEXPORT load_label_index_return_values load_label_index(path label_index_path,
+ uint32_t label_number_of_points);
+
+template <typename LabelT>
+DISKANN_DLLEXPORT std::tuple<std::vector<std::vector<LabelT>>, tsl::robin_set<LabelT>> parse_formatted_label_file(
+ path label_file);
+
+DISKANN_DLLEXPORT parse_label_file_return_values parse_label_file(path label_data_path, std::string universal_label);
+
+template <typename T>
+DISKANN_DLLEXPORT tsl::robin_map<std::string, std::vector<uint32_t>> generate_label_specific_vector_files_compat(
+ path input_data_path, tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ std::vector<label_set> point_ids_to_labels, label_set all_labels);
+
+/*
+ * For each label, generates a file containing all vectors that have said label.
+ * Also copies data from original bin file to new dimension-aligned file.
+ *
+ * Utilizes POSIX functions mmap and writev in order to minimize memory
+ * overhead, so we include an STL version as well.
+ *
+ * Each data file is saved under the following format:
+ * input_data_path + "_" + label
+ */
+#ifndef _WINDOWS
+template <typename T>
+inline tsl::robin_map<std::string, std::vector<uint32_t>> generate_label_specific_vector_files(
+ path input_data_path, tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ std::vector<label_set> point_ids_to_labels, label_set all_labels)
+{
+#ifndef _WINDOWS
+ auto file_writing_timer = std::chrono::high_resolution_clock::now();
+ diskann::MemoryMapper input_data(input_data_path);
+ char *input_start = input_data.getBuf();
+
+ uint32_t number_of_points, dimension;
+ std::memcpy(&number_of_points, input_start, sizeof(uint32_t));
+ std::memcpy(&dimension, input_start + sizeof(uint32_t), sizeof(uint32_t));
+ const uint32_t VECTOR_SIZE = dimension * sizeof(T);
+ const size_t METADATA = 2 * sizeof(uint32_t);
+ if (number_of_points != point_ids_to_labels.size())
+ {
+ std::cerr << "Error: number of points in labels file and data file differ." << std::endl;
+ throw;
+ }
+
+ tsl::robin_map<std::string, iovec *> label_to_iovec_map;
+ tsl::robin_map<std::string, uint32_t> label_to_curr_iovec;
+ tsl::robin_map<std::string, std::vector<uint32_t>> label_id_to_orig_id;
+
+ // setup iovec list for each label
+ for (const auto &lbl : all_labels)
+ {
+ iovec *label_iovecs = (iovec *)malloc(labels_to_number_of_points[lbl] * sizeof(iovec));
+ if (label_iovecs == nullptr)
+ {
+ throw;
+ }
+ label_to_iovec_map[lbl] = label_iovecs;
+ label_to_curr_iovec[lbl] = 0;
+ label_id_to_orig_id[lbl].reserve(labels_to_number_of_points[lbl]);
+ }
+
+ // each point added to corresponding per-label iovec list
+ for (uint32_t point_id = 0; point_id < number_of_points; point_id++)
+ {
+ char *curr_point = input_start + METADATA + (VECTOR_SIZE * point_id);
+ iovec curr_iovec;
+
+ curr_iovec.iov_base = curr_point;
+ curr_iovec.iov_len = VECTOR_SIZE;
+ for (const auto &lbl : point_ids_to_labels[point_id])
+ {
+ *(label_to_iovec_map[lbl] + label_to_curr_iovec[lbl]) = curr_iovec;
+ label_to_curr_iovec[lbl]++;
+ label_id_to_orig_id[lbl].push_back(point_id);
+ }
+ }
+
+ // write each label iovec to resp. file
+ for (const auto &lbl : all_labels)
+ {
+ int label_input_data_fd;
+ path curr_label_input_data_path(input_data_path + "_" + lbl);
+ uint32_t curr_num_pts = labels_to_number_of_points[lbl];
+
+ label_input_data_fd =
+ open(curr_label_input_data_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_APPEND, (mode_t)0644);
+ if (label_input_data_fd == -1)
+ throw;
+
+ // write metadata
+ uint32_t metadata[2] = {curr_num_pts, dimension};
+ int return_value = write(label_input_data_fd, metadata, sizeof(uint32_t) * 2);
+ if (return_value == -1)
+ {
+ throw;
+ }
+
+ // limits on number of iovec structs per writev means we need to perform
+ // multiple writevs
+ size_t i = 0;
+ while (curr_num_pts > IOV_MAX)
+ {
+ return_value = writev(label_input_data_fd, (label_to_iovec_map[lbl] + (IOV_MAX * i)), IOV_MAX);
+ if (return_value == -1)
+ {
+ close(label_input_data_fd);
+ throw;
+ }
+ curr_num_pts -= IOV_MAX;
+ i += 1;
+ }
+ return_value = writev(label_input_data_fd, (label_to_iovec_map[lbl] + (IOV_MAX * i)), curr_num_pts);
+ if (return_value == -1)
+ {
+ close(label_input_data_fd);
+ throw;
+ }
+
+ free(label_to_iovec_map[lbl]);
+ close(label_input_data_fd);
+ }
+
+ std::chrono::duration<double> file_writing_time = std::chrono::high_resolution_clock::now() - file_writing_timer;
+ std::cout << "generated " << all_labels.size() << " label-specific vector files for index building in time "
+ << file_writing_time.count() << "\n"
+ << std::endl;
+
+ return label_id_to_orig_id;
+#endif
+}
+#endif
+
+inline std::vector<uint32_t> loadTags(const std::string &tags_file, const std::string &base_file)
+{
+ const bool tags_enabled = tags_file.empty() ? false : true;
+ std::vector<uint32_t> location_to_tag;
+ if (tags_enabled)
+ {
+ size_t tag_file_ndims, tag_file_npts;
+ std::uint32_t *tag_data;
+ diskann::load_bin<std::uint32_t>(tags_file, tag_data, tag_file_npts, tag_file_ndims);
+ if (tag_file_ndims != 1)
+ {
+ diskann::cerr << "tags file error" << std::endl;
+ throw diskann::ANNException("tag file error", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ // check if the point count match
+ size_t base_file_npts, base_file_ndims;
+ diskann::get_bin_metadata(base_file, base_file_npts, base_file_ndims);
+ if (base_file_npts != tag_file_npts)
+ {
+ diskann::cerr << "point num in tags file mismatch" << std::endl;
+ throw diskann::ANNException("point num in tags file mismatch", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ location_to_tag.assign(tag_data, tag_data + tag_file_npts);
+ delete[] tag_data;
+ }
+ return location_to_tag;
+}
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/in_mem_data_store.h b/packages/leann-backend-diskann/third_party/DiskANN/include/in_mem_data_store.h
new file mode 100644
index 0000000..0a0a617
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/in_mem_data_store.h
@@ -0,0 +1,89 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+#pragma once
+
+#include <shared_mutex>
+#include <memory>
+
+#include "tsl/robin_map.h"
+#include "tsl/robin_set.h"
+#include "tsl/sparse_map.h"
+// #include "boost/dynamic_bitset.hpp"
+
+#include "abstract_data_store.h"
+
+#include "distance.h"
+#include "natural_number_map.h"
+#include "natural_number_set.h"
+#include "aligned_file_reader.h"
+
+namespace diskann
+{
+template <typename data_t> class InMemDataStore : public AbstractDataStore<data_t>
+{
+ public:
+ InMemDataStore(const location_t capacity, const size_t dim, std::unique_ptr<Distance<data_t>> distance_fn);
+ virtual ~InMemDataStore();
+
+ virtual location_t load(const std::string &filename) override;
+ virtual size_t save(const std::string &filename, const location_t num_points) override;
+
+ virtual size_t get_aligned_dim() const override;
+
+ // Populate internal data from unaligned data while doing alignment and any
+ // normalization that is required.
+ virtual void populate_data(const data_t *vectors, const location_t num_pts) override;
+ virtual void populate_data(const std::string &filename, const size_t offset) override;
+
+ virtual void extract_data_to_bin(const std::string &filename, const location_t num_pts) override;
+
+ virtual void get_vector(const location_t i, data_t *target) const override;
+ virtual void set_vector(const location_t i, const data_t *const vector) override;
+ virtual void prefetch_vector(const location_t loc) override;
+
+ virtual void move_vectors(const location_t old_location_start, const location_t new_location_start,
+ const location_t num_points) override;
+ virtual void copy_vectors(const location_t from_loc, const location_t to_loc, const location_t num_points) override;
+
+ virtual void preprocess_query(const data_t *query, AbstractScratch<data_t> *query_scratch) const override;
+
+ virtual float get_distance(const data_t *preprocessed_query, const location_t loc) const override;
+ virtual float get_distance(const location_t loc1, const location_t loc2) const override;
+
+ virtual void get_distance(const data_t *preprocessed_query, const location_t *locations,
+ const uint32_t location_count, float *distances,
+ AbstractScratch<data_t> *scratch) const override;
+ virtual void get_distance(const data_t *preprocessed_query, const std::vector<location_t> &ids,
+ std::vector<float> &distances, AbstractScratch<data_t> *scratch_space) const override;
+
+ virtual location_t calculate_medoid() const override;
+
+ virtual Distance<data_t> *get_dist_fn() const override;
+
+ virtual size_t get_alignment_factor() const override;
+
+ protected:
+ virtual location_t expand(const location_t new_size) override;
+ virtual location_t shrink(const location_t new_size) override;
+
+ virtual location_t load_impl(const std::string &filename);
+#ifdef EXEC_ENV_OLS
+ virtual location_t load_impl(AlignedFileReader &reader);
+#endif
+
+ private:
+ data_t *_data = nullptr;
+
+ size_t _aligned_dim;
+
+ // It may seem weird to put distance metric along with the data store class,
+ // but this gives us perf benefits as the datastore can do distance
+ // computations during search and compute norms of vectors internally without
+ // have to copy data back and forth.
+ std::unique_ptr<Distance<data_t>> _distance_fn;
+
+ // in case we need to save vector norms for optimization
+ std::shared_ptr<float[]> _pre_computed_norms;
+};
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/in_mem_graph_store.h b/packages/leann-backend-diskann/third_party/DiskANN/include/in_mem_graph_store.h
new file mode 100644
index 0000000..d0206a7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/in_mem_graph_store.h
@@ -0,0 +1,51 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include "abstract_graph_store.h"
+
+namespace diskann
+{
+
+class InMemGraphStore : public AbstractGraphStore
+{
+ public:
+ InMemGraphStore(const size_t total_pts, const size_t reserve_graph_degree);
+
+ // returns tuple of <nodes_read, start, num_frozen_points>
+ virtual std::tuple<uint32_t, uint32_t, size_t> load(const std::string &index_path_prefix,
+ const size_t num_points) override;
+ virtual int store(const std::string &index_path_prefix, const size_t num_points, const size_t num_frozen_points,
+ const uint32_t start) override;
+
+ virtual const std::vector<location_t> &get_neighbours(const location_t i) const override;
+ virtual void add_neighbour(const location_t i, location_t neighbour_id) override;
+ virtual void clear_neighbours(const location_t i) override;
+ virtual void swap_neighbours(const location_t a, location_t b) override;
+
+ virtual void set_neighbours(const location_t i, std::vector<location_t> &neighbors) override;
+
+ virtual size_t resize_graph(const size_t new_size) override;
+ virtual void clear_graph() override;
+
+ virtual size_t get_max_range_of_graph() override;
+ virtual uint32_t get_max_observed_degree() override;
+
+ protected:
+ virtual std::tuple<uint32_t, uint32_t, size_t> load_impl(const std::string &filename, size_t expected_num_points);
+#ifdef EXEC_ENV_OLS
+ virtual std::tuple<uint32_t, uint32_t, size_t> load_impl(AlignedFileReader &reader, size_t expected_num_points);
+#endif
+
+ int save_graph(const std::string &index_path_prefix, const size_t active_points, const size_t num_frozen_points,
+ const uint32_t start);
+
+ private:
+ size_t _max_range_of_graph = 0;
+ uint32_t _max_observed_degree = 0;
+
+ std::vector<std::vector<uint32_t>> _graph;
+};
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/index.h b/packages/leann-backend-diskann/third_party/DiskANN/include/index.h
new file mode 100644
index 0000000..c4303a1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/index.h
@@ -0,0 +1,452 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include "common_includes.h"
+
+#ifdef EXEC_ENV_OLS
+#include "aligned_file_reader.h"
+#endif
+
+#include "distance.h"
+#include "locking.h"
+#include "natural_number_map.h"
+#include "natural_number_set.h"
+#include "neighbor.h"
+#include "parameters.h"
+#include "utils.h"
+#include "windows_customizations.h"
+#include "scratch.h"
+#include "in_mem_data_store.h"
+#include "in_mem_graph_store.h"
+#include "abstract_index.h"
+
+#include "quantized_distance.h"
+#include "pq_data_store.h"
+
+#define OVERHEAD_FACTOR 1.1
+#define EXPAND_IF_FULL 0
+#define DEFAULT_MAXC 750
+
+namespace diskann
+{
+
+inline double estimate_ram_usage(size_t size, uint32_t dim, uint32_t datasize, uint32_t degree)
+{
+ double size_of_data = ((double)size) * ROUND_UP(dim, 8) * datasize;
+ double size_of_graph = ((double)size) * degree * sizeof(uint32_t) * defaults::GRAPH_SLACK_FACTOR;
+ double size_of_locks = ((double)size) * sizeof(non_recursive_mutex);
+ double size_of_outer_vector = ((double)size) * sizeof(ptrdiff_t);
+
+ return OVERHEAD_FACTOR * (size_of_data + size_of_graph + size_of_locks + size_of_outer_vector);
+}
+
+template <typename T, typename TagT = uint32_t, typename LabelT = uint32_t> class Index : public AbstractIndex
+{
+ /**************************************************************************
+ *
+ * Public functions acquire one or more of _update_lock, _consolidate_lock,
+ * _tag_lock, _delete_lock before calling protected functions which DO NOT
+ * acquire these locks. They might acquire locks on _locks[i]
+ *
+ **************************************************************************/
+
+ public:
+ // Constructor for Bulk operations and for creating the index object solely
+ // for loading a prexisting index.
+ DISKANN_DLLEXPORT Index(const IndexConfig &index_config, std::shared_ptr<AbstractDataStore<T>> data_store,
+ std::unique_ptr<AbstractGraphStore> graph_store,
+ std::shared_ptr<AbstractDataStore<T>> pq_data_store = nullptr);
+
+ // Constructor for incremental index
+ DISKANN_DLLEXPORT Index(Metric m, const size_t dim, const size_t max_points,
+ const std::shared_ptr<IndexWriteParameters> index_parameters,
+ const std::shared_ptr<IndexSearchParams> index_search_params,
+ const size_t num_frozen_pts = 0, const bool dynamic_index = false,
+ const bool enable_tags = false, const bool concurrent_consolidate = false,
+ const bool pq_dist_build = false, const size_t num_pq_chunks = 0,
+ const bool use_opq = false, const bool filtered_index = false);
+
+ DISKANN_DLLEXPORT ~Index();
+
+ // Saves graph, data, metadata and associated tags.
+ DISKANN_DLLEXPORT void save(const char *filename, bool compact_before_save = false) override;
+
+ // Load functions
+#ifdef EXEC_ENV_OLS
+ DISKANN_DLLEXPORT void load(AlignedFileReader &reader, uint32_t num_threads, uint32_t search_l);
+#else
+ // Reads the number of frozen points from graph's metadata file section.
+ DISKANN_DLLEXPORT static size_t get_graph_num_frozen_points(const std::string &graph_file);
+
+ DISKANN_DLLEXPORT void load(const char *index_file, uint32_t num_threads, uint32_t search_l) override;
+#endif
+
+ // get some private variables
+ DISKANN_DLLEXPORT size_t get_num_points();
+ DISKANN_DLLEXPORT size_t get_max_points();
+
+ DISKANN_DLLEXPORT bool detect_common_filters(uint32_t point_id, bool search_invocation,
+ const std::vector<LabelT> &incoming_labels);
+
+ // Batch build from a file. Optionally pass tags vector.
+ DISKANN_DLLEXPORT void build(const char *filename, const size_t num_points_to_load,
+ const std::vector<TagT> &tags = std::vector<TagT>());
+
+ // Batch build from a file. Optionally pass tags file.
+ DISKANN_DLLEXPORT void build(const char *filename, const size_t num_points_to_load, const char *tag_filename);
+
+ // Batch build from a data array, which must pad vectors to aligned_dim
+ DISKANN_DLLEXPORT void build(const T *data, const size_t num_points_to_load, const std::vector<TagT> &tags);
+
+ // Based on filter params builds a filtered or unfiltered index
+ DISKANN_DLLEXPORT void build(const std::string &data_file, const size_t num_points_to_load,
+ IndexFilterParams &filter_params) override;
+
+ // Filtered Support
+ DISKANN_DLLEXPORT void build_filtered_index(const char *filename, const std::string &label_file,
+ const size_t num_points_to_load,
+ const std::vector<TagT> &tags = std::vector<TagT>());
+
+ DISKANN_DLLEXPORT void set_universal_label(const LabelT &label);
+
+ // Get converted integer label from string to int map (_label_map)
+ DISKANN_DLLEXPORT LabelT get_converted_label(const std::string &raw_label);
+
+ // Set starting point of an index before inserting any points incrementally.
+ // The data count should be equal to _num_frozen_pts * _aligned_dim.
+ DISKANN_DLLEXPORT void set_start_points(const T *data, size_t data_count);
+ // Set starting points to random points on a sphere of certain radius.
+ // A fixed random seed can be specified for scenarios where it's important
+ // to have higher consistency between index builds.
+ DISKANN_DLLEXPORT void set_start_points_at_random(T radius, uint32_t random_seed = 0);
+
+ // For FastL2 search on a static index, we interleave the data with graph
+ DISKANN_DLLEXPORT void optimize_index_layout() override;
+
+ // For FastL2 search on optimized layout
+ DISKANN_DLLEXPORT void search_with_optimized_layout(const T *query, size_t K, size_t L, uint32_t *indices);
+
+ // Added search overload that takes L as parameter, so that we
+ // can customize L on a per-query basis without tampering with "Parameters"
+ template <typename IDType>
+ DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> search(const T *query, const size_t K, const uint32_t L,
+ IDType *indices, float *distances = nullptr);
+
+ // Initialize space for res_vectors before calling.
+ DISKANN_DLLEXPORT size_t search_with_tags(const T *query, const uint64_t K, const uint32_t L, TagT *tags,
+ float *distances, std::vector<T *> &res_vectors, bool use_filters = false,
+ const std::string filter_label = "");
+
+ // Filter support search
+ template <typename IndexType>
+ DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> search_with_filters(const T *query, const LabelT &filter_label,
+ const size_t K, const uint32_t L,
+ IndexType *indices, float *distances);
+
+ // Will fail if tag already in the index or if tag=0.
+ DISKANN_DLLEXPORT int insert_point(const T *point, const TagT tag);
+
+ // Will fail if tag already in the index or if tag=0.
+ DISKANN_DLLEXPORT int insert_point(const T *point, const TagT tag, const std::vector<LabelT> &label);
+
+ // call this before issuing deletions to sets relevant flags
+ DISKANN_DLLEXPORT int enable_delete();
+
+ // Record deleted point now and restructure graph later. Return -1 if tag
+ // not found, 0 if OK.
+ DISKANN_DLLEXPORT int lazy_delete(const TagT &tag);
+
+ // Record deleted points now and restructure graph later. Add to failed_tags
+ // if tag not found.
+ DISKANN_DLLEXPORT void lazy_delete(const std::vector<TagT> &tags, std::vector<TagT> &failed_tags);
+
+ // Call after a series of lazy deletions
+ // Returns number of live points left after consolidation
+ // If _conc_consolidates is set in the ctor, then this call can be invoked
+ // alongside inserts and lazy deletes, else it acquires _update_lock
+ DISKANN_DLLEXPORT consolidation_report consolidate_deletes(const IndexWriteParameters &parameters) override;
+
+ DISKANN_DLLEXPORT void prune_all_neighbors(const uint32_t max_degree, const uint32_t max_occlusion,
+ const float alpha);
+
+ DISKANN_DLLEXPORT bool is_index_saved();
+
+ // repositions frozen points to the end of _data - if they have been moved
+ // during deletion
+ DISKANN_DLLEXPORT void reposition_frozen_point_to_end();
+ DISKANN_DLLEXPORT void reposition_points(uint32_t old_location_start, uint32_t new_location_start,
+ uint32_t num_locations);
+
+ // DISKANN_DLLEXPORT void save_index_as_one_file(bool flag);
+
+ DISKANN_DLLEXPORT void get_active_tags(tsl::robin_set<TagT> &active_tags);
+
+ // memory should be allocated for vec before calling this function
+ DISKANN_DLLEXPORT int get_vector_by_tag(TagT &tag, T *vec);
+
+ DISKANN_DLLEXPORT void print_status();
+
+ DISKANN_DLLEXPORT void count_nodes_at_bfs_levels();
+
+ // This variable MUST be updated if the number of entries in the metadata
+ // change.
+ DISKANN_DLLEXPORT static const int METADATA_ROWS = 5;
+
+ DISKANN_DLLEXPORT void get_degree_stats(size_t &max_deg, size_t &min_deg, size_t &avg_deg, size_t &cnt_deg);
+
+ DISKANN_DLLEXPORT void dump_degree_stats(std::string filename);
+
+ // ********************************
+ //
+ // Internals of the library
+ //
+ // ********************************
+
+ protected:
+ // overload of abstract index virtual methods
+ virtual void _build(const DataType &data, const size_t num_points_to_load, TagVector &tags) override;
+
+ virtual std::pair<uint32_t, uint32_t> _search(const DataType &query, const size_t K, const uint32_t L,
+ std::any &indices, float *distances = nullptr) override;
+ virtual std::pair<uint32_t, uint32_t> _search_with_filters(const DataType &query,
+ const std::string &filter_label_raw, const size_t K,
+ const uint32_t L, std::any &indices,
+ float *distances) override;
+
+ virtual int _insert_point(const DataType &data_point, const TagType tag) override;
+ virtual int _insert_point(const DataType &data_point, const TagType tag, Labelvector &labels) override;
+
+ virtual int _lazy_delete(const TagType &tag) override;
+
+ virtual void _lazy_delete(TagVector &tags, TagVector &failed_tags) override;
+
+ virtual void _get_active_tags(TagRobinSet &active_tags) override;
+
+ virtual void _set_start_points_at_random(DataType radius, uint32_t random_seed = 0) override;
+
+ virtual int _get_vector_by_tag(TagType &tag, DataType &vec) override;
+
+ virtual void _search_with_optimized_layout(const DataType &query, size_t K, size_t L, uint32_t *indices) override;
+
+ virtual size_t _search_with_tags(const DataType &query, const uint64_t K, const uint32_t L, const TagType &tags,
+ float *distances, DataVector &res_vectors, bool use_filters = false,
+ const std::string filter_label = "") override;
+
+ virtual void _set_universal_label(const LabelType universal_label) override;
+
+ // No copy/assign.
+ Index(const Index<T, TagT, LabelT> &) = delete;
+ Index<T, TagT, LabelT> &operator=(const Index<T, TagT, LabelT> &) = delete;
+
+ // Use after _data and _nd have been populated
+ // Acquire exclusive _update_lock before calling
+ void build_with_data_populated(const std::vector<TagT> &tags);
+
+ // generates 1 frozen point that will never be deleted from the graph
+ // This is not visible to the user
+ void generate_frozen_point();
+
+ // determines navigating node of the graph by calculating medoid of datafopt
+ uint32_t calculate_entry_point();
+
+ void parse_label_file(const std::string &label_file, size_t &num_pts_labels);
+
+ std::unordered_map<std::string, LabelT> load_label_map(const std::string &map_file);
+
+ // Returns the locations of start point and frozen points suitable for use
+ // with iterate_to_fixed_point.
+ std::vector<uint32_t> get_init_ids();
+
+ // The query to use is placed in scratch->aligned_query
+ std::pair<uint32_t, uint32_t> iterate_to_fixed_point(InMemQueryScratch<T> *scratch, const uint32_t Lindex,
+ const std::vector<uint32_t> &init_ids, bool use_filter,
+ const std::vector<LabelT> &filters, bool search_invocation);
+
+ void search_for_point_and_prune(int location, uint32_t Lindex, std::vector<uint32_t> &pruned_list,
+ InMemQueryScratch<T> *scratch, bool use_filter = false,
+ uint32_t filteredLindex = 0);
+
+ void prune_neighbors(const uint32_t location, std::vector<Neighbor> &pool, std::vector<uint32_t> &pruned_list,
+ InMemQueryScratch<T> *scratch);
+
+ void prune_neighbors(const uint32_t location, std::vector<Neighbor> &pool, const uint32_t range,
+ const uint32_t max_candidate_size, const float alpha, std::vector<uint32_t> &pruned_list,
+ InMemQueryScratch<T> *scratch);
+
+ // Prunes candidates in @pool to a shorter list @result
+ // @pool must be sorted before calling
+ void occlude_list(const uint32_t location, std::vector<Neighbor> &pool, const float alpha, const uint32_t degree,
+ const uint32_t maxc, std::vector<uint32_t> &result, InMemQueryScratch<T> *scratch,
+ const tsl::robin_set<uint32_t> *const delete_set_ptr = nullptr);
+
+ // add reverse links from all the visited nodes to node n.
+ void inter_insert(uint32_t n, std::vector<uint32_t> &pruned_list, const uint32_t range,
+ InMemQueryScratch<T> *scratch);
+
+ void inter_insert(uint32_t n, std::vector<uint32_t> &pruned_list, InMemQueryScratch<T> *scratch);
+
+ // Acquire exclusive _update_lock before calling
+ void link();
+
+ // Acquire exclusive _tag_lock and _delete_lock before calling
+ int reserve_location();
+
+ // Acquire exclusive _tag_lock before calling
+ size_t release_location(int location);
+ size_t release_locations(const tsl::robin_set<uint32_t> &locations);
+
+ // Resize the index when no slots are left for insertion.
+ // Acquire exclusive _update_lock and _tag_lock before calling.
+ void resize(size_t new_max_points);
+
+ // Acquire unique lock on _update_lock, _consolidate_lock, _tag_lock
+ // and _delete_lock before calling these functions.
+ // Renumber nodes, update tag and location maps and compact the
+ // graph, mode = _consolidated_order in case of lazy deletion and
+ // _compacted_order in case of eager deletion
+ DISKANN_DLLEXPORT void compact_data();
+ DISKANN_DLLEXPORT void compact_frozen_point();
+
+ // Remove deleted nodes from adjacency list of node loc
+ // Replace removed neighbors with second order neighbors.
+ // Also acquires _locks[i] for i = loc and out-neighbors of loc.
+ void process_delete(const tsl::robin_set<uint32_t> &old_delete_set, size_t loc, const uint32_t range,
+ const uint32_t maxc, const float alpha, InMemQueryScratch<T> *scratch);
+
+ void initialize_query_scratch(uint32_t num_threads, uint32_t search_l, uint32_t indexing_l, uint32_t r,
+ uint32_t maxc, size_t dim);
+
+ // Do not call without acquiring appropriate locks
+ // call public member functions save and load to invoke these.
+ DISKANN_DLLEXPORT size_t save_graph(std::string filename);
+ DISKANN_DLLEXPORT size_t save_data(std::string filename);
+ DISKANN_DLLEXPORT size_t save_tags(std::string filename);
+ DISKANN_DLLEXPORT size_t save_delete_list(const std::string &filename);
+#ifdef EXEC_ENV_OLS
+ DISKANN_DLLEXPORT size_t load_graph(AlignedFileReader &reader, size_t expected_num_points);
+ DISKANN_DLLEXPORT size_t load_data(AlignedFileReader &reader);
+ DISKANN_DLLEXPORT size_t load_tags(AlignedFileReader &reader);
+ DISKANN_DLLEXPORT size_t load_delete_set(AlignedFileReader &reader);
+#else
+ DISKANN_DLLEXPORT size_t load_graph(const std::string filename, size_t expected_num_points);
+ DISKANN_DLLEXPORT size_t load_data(std::string filename0);
+ DISKANN_DLLEXPORT size_t load_tags(const std::string tag_file_name);
+ DISKANN_DLLEXPORT size_t load_delete_set(const std::string &filename);
+#endif
+
+ private:
+ // Distance functions
+ Metric _dist_metric = diskann::L2;
+
+ // Data
+ std::shared_ptr<AbstractDataStore<T>> _data_store;
+
+ // Graph related data structures
+ std::unique_ptr<AbstractGraphStore> _graph_store;
+
+ char *_opt_graph = nullptr;
+
+ // Dimensions
+ size_t _dim = 0;
+ size_t _nd = 0; // number of active points i.e. existing in the graph
+ size_t _max_points = 0; // total number of points in given data set
+
+ // _num_frozen_pts is the number of points which are used as initial
+ // candidates when iterating to closest point(s). These are not visible
+ // externally and won't be returned by search. At least 1 frozen point is
+ // needed for a dynamic index. The frozen points have consecutive locations.
+ // See also _start below.
+ size_t _num_frozen_pts = 0;
+ size_t _frozen_pts_used = 0;
+ size_t _node_size;
+ size_t _data_len;
+ size_t _neighbor_len;
+
+ // Start point of the search. When _num_frozen_pts is greater than zero,
+ // this is the location of the first frozen point. Otherwise, this is a
+ // location of one of the points in index.
+ uint32_t _start = 0;
+
+ bool _has_built = false;
+ bool _saturate_graph = false;
+ bool _save_as_one_file = false; // plan to support in next version
+ bool _dynamic_index = false;
+ bool _enable_tags = false;
+ bool _normalize_vecs = false; // Using normalied L2 for cosine.
+ bool _deletes_enabled = false;
+
+ // Filter Support
+
+ bool _filtered_index = false;
+ // Location to label is only updated during insert_point(), all other reads are protected by
+ // default as a location can only be released at end of consolidate deletes
+ std::vector<std::vector<LabelT>> _location_to_labels;
+ tsl::robin_set<LabelT> _labels;
+ std::string _labels_file;
+ std::unordered_map<LabelT, uint32_t> _label_to_start_id;
+ std::unordered_map<uint32_t, uint32_t> _medoid_counts;
+
+ bool _use_universal_label = false;
+ LabelT _universal_label = 0;
+ uint32_t _filterIndexingQueueSize;
+ std::unordered_map<std::string, LabelT> _label_map;
+
+ // Indexing parameters
+ uint32_t _indexingQueueSize;
+ uint32_t _indexingRange;
+ uint32_t _indexingMaxC;
+ float _indexingAlpha;
+ uint32_t _indexingThreads;
+
+ // Query scratch data structures
+ ConcurrentQueue<InMemQueryScratch<T> *> _query_scratch;
+
+ // Flags for PQ based distance calculation
+ bool _pq_dist = false;
+ bool _use_opq = false;
+ size_t _num_pq_chunks = 0;
+ // REFACTOR
+ // uint8_t *_pq_data = nullptr;
+ std::shared_ptr<QuantizedDistance<T>> _pq_distance_fn = nullptr;
+ std::shared_ptr<AbstractDataStore<T>> _pq_data_store = nullptr;
+ bool _pq_generated = false;
+ FixedChunkPQTable _pq_table;
+
+ //
+ // Data structures, locks and flags for dynamic indexing and tags
+ //
+
+ // lazy_delete removes entry from _location_to_tag and _tag_to_location. If
+ // _location_to_tag does not resolve a location, infer that it was deleted.
+ tsl::sparse_map<TagT, uint32_t> _tag_to_location;
+ natural_number_map<uint32_t, TagT> _location_to_tag;
+
+ // _empty_slots has unallocated slots and those freed by consolidate_delete.
+ // _delete_set has locations marked deleted by lazy_delete. Will not be
+ // immediately available for insert. consolidate_delete will release these
+ // slots to _empty_slots.
+ natural_number_set<uint32_t> _empty_slots;
+ std::unique_ptr<tsl::robin_set<uint32_t>> _delete_set;
+
+ bool _data_compacted = true; // true if data has been compacted
+ bool _is_saved = false; // Checking if the index is already saved.
+ bool _conc_consolidate = false; // use _lock while searching
+
+ // Acquire locks in the order below when acquiring multiple locks
+ std::shared_timed_mutex // RW mutex between save/load (exclusive lock) and
+ _update_lock; // search/inserts/deletes/consolidate (shared lock)
+ std::shared_timed_mutex // Ensure only one consolidate or compact_data is
+ _consolidate_lock; // ever active
+ std::shared_timed_mutex // RW lock for _tag_to_location,
+ _tag_lock; // _location_to_tag, _empty_slots, _nd, _max_points, _label_to_start_id
+ std::shared_timed_mutex // RW Lock on _delete_set and _data_compacted
+ _delete_lock; // variable
+
+ // Per node lock, cardinality=_max_points + _num_frozen_points
+ std::vector<non_recursive_mutex> _locks;
+
+ static const float INDEX_GROWTH_FACTOR;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/index_build_params.h b/packages/leann-backend-diskann/third_party/DiskANN/include/index_build_params.h
new file mode 100644
index 0000000..d4f4548
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/index_build_params.h
@@ -0,0 +1,73 @@
+#pragma once
+
+#include "common_includes.h"
+#include "parameters.h"
+
+namespace diskann
+{
+struct IndexFilterParams
+{
+ public:
+ std::string save_path_prefix;
+ std::string label_file;
+ std::string tags_file;
+ std::string universal_label;
+ uint32_t filter_threshold = 0;
+
+ private:
+ IndexFilterParams(const std::string &save_path_prefix, const std::string &label_file,
+ const std::string &universal_label, uint32_t filter_threshold)
+ : save_path_prefix(save_path_prefix), label_file(label_file), universal_label(universal_label),
+ filter_threshold(filter_threshold)
+ {
+ }
+
+ friend class IndexFilterParamsBuilder;
+};
+class IndexFilterParamsBuilder
+{
+ public:
+ IndexFilterParamsBuilder() = default;
+
+ IndexFilterParamsBuilder &with_save_path_prefix(const std::string &save_path_prefix)
+ {
+ if (save_path_prefix.empty() || save_path_prefix == "")
+ throw ANNException("Error: save_path_prefix can't be empty", -1);
+ this->_save_path_prefix = save_path_prefix;
+ return *this;
+ }
+
+ IndexFilterParamsBuilder &with_label_file(const std::string &label_file)
+ {
+ this->_label_file = label_file;
+ return *this;
+ }
+
+ IndexFilterParamsBuilder &with_universal_label(const std::string &univeral_label)
+ {
+ this->_universal_label = univeral_label;
+ return *this;
+ }
+
+ IndexFilterParamsBuilder &with_filter_threshold(const std::uint32_t &filter_threshold)
+ {
+ this->_filter_threshold = filter_threshold;
+ return *this;
+ }
+
+ IndexFilterParams build()
+ {
+ return IndexFilterParams(_save_path_prefix, _label_file, _universal_label, _filter_threshold);
+ }
+
+ IndexFilterParamsBuilder(const IndexFilterParamsBuilder &) = delete;
+ IndexFilterParamsBuilder &operator=(const IndexFilterParamsBuilder &) = delete;
+
+ private:
+ std::string _save_path_prefix;
+ std::string _label_file;
+ std::string _tags_file;
+ std::string _universal_label;
+ uint32_t _filter_threshold = 0;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/index_config.h b/packages/leann-backend-diskann/third_party/DiskANN/include/index_config.h
new file mode 100644
index 0000000..a8e64d0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/index_config.h
@@ -0,0 +1,256 @@
+#pragma once
+
+#include "common_includes.h"
+#include "parameters.h"
+
+namespace diskann
+{
+enum class DataStoreStrategy
+{
+ MEMORY
+};
+
+enum class GraphStoreStrategy
+{
+ MEMORY
+};
+
+struct IndexConfig
+{
+ DataStoreStrategy data_strategy;
+ GraphStoreStrategy graph_strategy;
+
+ Metric metric;
+ size_t dimension;
+ size_t max_points;
+
+ bool dynamic_index;
+ bool enable_tags;
+ bool pq_dist_build;
+ bool concurrent_consolidate;
+ bool use_opq;
+ bool filtered_index;
+
+ size_t num_pq_chunks;
+ size_t num_frozen_pts;
+
+ std::string label_type;
+ std::string tag_type;
+ std::string data_type;
+
+ // Params for building index
+ std::shared_ptr<IndexWriteParameters> index_write_params;
+ // Params for searching index
+ std::shared_ptr<IndexSearchParams> index_search_params;
+
+ private:
+ IndexConfig(DataStoreStrategy data_strategy, GraphStoreStrategy graph_strategy, Metric metric, size_t dimension,
+ size_t max_points, size_t num_pq_chunks, size_t num_frozen_points, bool dynamic_index, bool enable_tags,
+ bool pq_dist_build, bool concurrent_consolidate, bool use_opq, bool filtered_index,
+ std::string &data_type, const std::string &tag_type, const std::string &label_type,
+ std::shared_ptr<IndexWriteParameters> index_write_params,
+ std::shared_ptr<IndexSearchParams> index_search_params)
+ : data_strategy(data_strategy), graph_strategy(graph_strategy), metric(metric), dimension(dimension),
+ max_points(max_points), dynamic_index(dynamic_index), enable_tags(enable_tags), pq_dist_build(pq_dist_build),
+ concurrent_consolidate(concurrent_consolidate), use_opq(use_opq), filtered_index(filtered_index),
+ num_pq_chunks(num_pq_chunks), num_frozen_pts(num_frozen_points), label_type(label_type), tag_type(tag_type),
+ data_type(data_type), index_write_params(index_write_params), index_search_params(index_search_params)
+ {
+ }
+
+ friend class IndexConfigBuilder;
+};
+
+class IndexConfigBuilder
+{
+ public:
+ IndexConfigBuilder() = default;
+
+ IndexConfigBuilder &with_metric(Metric m)
+ {
+ this->_metric = m;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_graph_load_store_strategy(GraphStoreStrategy graph_strategy)
+ {
+ this->_graph_strategy = graph_strategy;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_data_load_store_strategy(DataStoreStrategy data_strategy)
+ {
+ this->_data_strategy = data_strategy;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_dimension(size_t dimension)
+ {
+ this->_dimension = dimension;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_max_points(size_t max_points)
+ {
+ this->_max_points = max_points;
+ return *this;
+ }
+
+ IndexConfigBuilder &is_dynamic_index(bool dynamic_index)
+ {
+ this->_dynamic_index = dynamic_index;
+ return *this;
+ }
+
+ IndexConfigBuilder &is_enable_tags(bool enable_tags)
+ {
+ this->_enable_tags = enable_tags;
+ return *this;
+ }
+
+ IndexConfigBuilder &is_pq_dist_build(bool pq_dist_build)
+ {
+ this->_pq_dist_build = pq_dist_build;
+ return *this;
+ }
+
+ IndexConfigBuilder &is_concurrent_consolidate(bool concurrent_consolidate)
+ {
+ this->_concurrent_consolidate = concurrent_consolidate;
+ return *this;
+ }
+
+ IndexConfigBuilder &is_use_opq(bool use_opq)
+ {
+ this->_use_opq = use_opq;
+ return *this;
+ }
+
+ IndexConfigBuilder &is_filtered(bool is_filtered)
+ {
+ this->_filtered_index = is_filtered;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_num_pq_chunks(size_t num_pq_chunks)
+ {
+ this->_num_pq_chunks = num_pq_chunks;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_num_frozen_pts(size_t num_frozen_pts)
+ {
+ this->_num_frozen_pts = num_frozen_pts;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_label_type(const std::string &label_type)
+ {
+ this->_label_type = label_type;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_tag_type(const std::string &tag_type)
+ {
+ this->_tag_type = tag_type;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_data_type(const std::string &data_type)
+ {
+ this->_data_type = data_type;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_index_write_params(IndexWriteParameters &index_write_params)
+ {
+ this->_index_write_params = std::make_shared<IndexWriteParameters>(index_write_params);
+ return *this;
+ }
+
+ IndexConfigBuilder &with_index_write_params(std::shared_ptr<IndexWriteParameters> index_write_params_ptr)
+ {
+ if (index_write_params_ptr == nullptr)
+ {
+ diskann::cout << "Passed, empty build_params while creating index config" << std::endl;
+ return *this;
+ }
+ this->_index_write_params = index_write_params_ptr;
+ return *this;
+ }
+
+ IndexConfigBuilder &with_index_search_params(IndexSearchParams &search_params)
+ {
+ this->_index_search_params = std::make_shared<IndexSearchParams>(search_params);
+ return *this;
+ }
+
+ IndexConfigBuilder &with_index_search_params(std::shared_ptr<IndexSearchParams> search_params_ptr)
+ {
+ if (search_params_ptr == nullptr)
+ {
+ diskann::cout << "Passed, empty search_params while creating index config" << std::endl;
+ return *this;
+ }
+ this->_index_search_params = search_params_ptr;
+ return *this;
+ }
+
+ IndexConfig build()
+ {
+ if (_data_type == "" || _data_type.empty())
+ throw ANNException("Error: data_type can not be empty", -1);
+
+ if (_dynamic_index && _num_frozen_pts == 0)
+ {
+ _num_frozen_pts = 1;
+ }
+
+ if (_dynamic_index)
+ {
+ if (_index_search_params != nullptr && _index_search_params->initial_search_list_size == 0)
+ throw ANNException("Error: please pass initial_search_list_size for building dynamic index.", -1);
+ }
+
+ // sanity check
+ if (_dynamic_index && _num_frozen_pts == 0)
+ {
+ diskann::cout << "_num_frozen_pts passed as 0 for dynamic_index. Setting it to 1 for safety." << std::endl;
+ _num_frozen_pts = 1;
+ }
+
+ return IndexConfig(_data_strategy, _graph_strategy, _metric, _dimension, _max_points, _num_pq_chunks,
+ _num_frozen_pts, _dynamic_index, _enable_tags, _pq_dist_build, _concurrent_consolidate,
+ _use_opq, _filtered_index, _data_type, _tag_type, _label_type, _index_write_params,
+ _index_search_params);
+ }
+
+ IndexConfigBuilder(const IndexConfigBuilder &) = delete;
+ IndexConfigBuilder &operator=(const IndexConfigBuilder &) = delete;
+
+ private:
+ DataStoreStrategy _data_strategy;
+ GraphStoreStrategy _graph_strategy;
+
+ Metric _metric;
+ size_t _dimension;
+ size_t _max_points;
+
+ bool _dynamic_index = false;
+ bool _enable_tags = false;
+ bool _pq_dist_build = false;
+ bool _concurrent_consolidate = false;
+ bool _use_opq = false;
+ bool _filtered_index{defaults::HAS_LABELS};
+
+ size_t _num_pq_chunks = 0;
+ size_t _num_frozen_pts{defaults::NUM_FROZEN_POINTS_STATIC};
+
+ std::string _label_type{"uint32"};
+ std::string _tag_type{"uint32"};
+ std::string _data_type;
+
+ std::shared_ptr<IndexWriteParameters> _index_write_params;
+ std::shared_ptr<IndexSearchParams> _index_search_params;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/index_factory.h b/packages/leann-backend-diskann/third_party/DiskANN/include/index_factory.h
new file mode 100644
index 0000000..76fb0b9
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/index_factory.h
@@ -0,0 +1,51 @@
+#pragma once
+
+#include "index.h"
+#include "abstract_graph_store.h"
+#include "in_mem_graph_store.h"
+#include "pq_data_store.h"
+
+namespace diskann
+{
+class IndexFactory
+{
+ public:
+ DISKANN_DLLEXPORT explicit IndexFactory(const IndexConfig &config);
+ DISKANN_DLLEXPORT std::unique_ptr<AbstractIndex> create_instance();
+
+ DISKANN_DLLEXPORT static std::unique_ptr<AbstractGraphStore> construct_graphstore(
+ const GraphStoreStrategy stratagy, const size_t size, const size_t reserve_graph_degree);
+
+ template <typename T>
+ DISKANN_DLLEXPORT static std::shared_ptr<AbstractDataStore<T>> construct_datastore(DataStoreStrategy stratagy,
+ size_t num_points,
+ size_t dimension, Metric m);
+ // For now PQDataStore incorporates within itself all variants of quantization that we support. In the
+ // future it may be necessary to introduce an AbstractPQDataStore class to spearate various quantization
+ // flavours.
+ template <typename T>
+ DISKANN_DLLEXPORT static std::shared_ptr<PQDataStore<T>> construct_pq_datastore(DataStoreStrategy strategy,
+ size_t num_points, size_t dimension,
+ Metric m, size_t num_pq_chunks,
+ bool use_opq);
+ template <typename T> static Distance<T> *construct_inmem_distance_fn(Metric m);
+
+ private:
+ void check_config();
+
+ template <typename data_type, typename tag_type, typename label_type>
+ std::unique_ptr<AbstractIndex> create_instance();
+
+ std::unique_ptr<AbstractIndex> create_instance(const std::string &data_type, const std::string &tag_type,
+ const std::string &label_type);
+
+ template <typename data_type>
+ std::unique_ptr<AbstractIndex> create_instance(const std::string &tag_type, const std::string &label_type);
+
+ template <typename data_type, typename tag_type>
+ std::unique_ptr<AbstractIndex> create_instance(const std::string &label_type);
+
+ std::unique_ptr<IndexConfig> _config;
+};
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/linux_aligned_file_reader.h b/packages/leann-backend-diskann/third_party/DiskANN/include/linux_aligned_file_reader.h
new file mode 100644
index 0000000..d1d1e74
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/linux_aligned_file_reader.h
@@ -0,0 +1,41 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#ifndef _WINDOWS
+#ifndef __APPLE__
+
+#include "aligned_file_reader.h"
+
+class LinuxAlignedFileReader : public AlignedFileReader
+{
+ private:
+ uint64_t file_sz;
+ FileHandle file_desc;
+ io_context_t bad_ctx = (io_context_t)-1;
+
+ public:
+ LinuxAlignedFileReader();
+ ~LinuxAlignedFileReader();
+
+ IOContext &get_ctx();
+
+ // register thread-id for a context
+ void register_thread();
+
+ // de-register thread-id for a context
+ void deregister_thread();
+ void deregister_all_threads();
+
+ // Open & close ops
+ // Blocking calls
+ void open(const std::string &fname);
+ void close();
+
+ // process batch of aligned requests in parallel
+ // NOTE :: blocking call
+ void read(std::vector<AlignedRead> &read_reqs, IOContext &ctx, bool async = false);
+};
+
+#endif
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/locking.h b/packages/leann-backend-diskann/third_party/DiskANN/include/locking.h
new file mode 100644
index 0000000..890c24a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/locking.h
@@ -0,0 +1,20 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+#pragma once
+
+#include <mutex>
+
+#ifdef _WINDOWS
+#include "windows_slim_lock.h"
+#endif
+
+namespace diskann
+{
+#ifdef _WINDOWS
+using non_recursive_mutex = windows_exclusive_slim_lock;
+using LockGuard = windows_exclusive_slim_lock_guard;
+#else
+using non_recursive_mutex = std::mutex;
+using LockGuard = std::lock_guard<non_recursive_mutex>;
+#endif
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/logger.h b/packages/leann-backend-diskann/third_party/DiskANN/include/logger.h
new file mode 100644
index 0000000..0b17807
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/logger.h
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+#pragma once
+
+#include <functional>
+#include <iostream>
+#include "windows_customizations.h"
+
+#ifdef EXEC_ENV_OLS
+#ifndef ENABLE_CUSTOM_LOGGER
+#define ENABLE_CUSTOM_LOGGER
+#endif // !ENABLE_CUSTOM_LOGGER
+#endif // EXEC_ENV_OLS
+
+namespace diskann
+{
+#ifdef ENABLE_CUSTOM_LOGGER
+DISKANN_DLLEXPORT extern std::basic_ostream<char> cout;
+DISKANN_DLLEXPORT extern std::basic_ostream<char> cerr;
+#else
+using std::cerr;
+using std::cout;
+#endif
+
+enum class DISKANN_DLLEXPORT LogLevel
+{
+ LL_Info = 0,
+ LL_Error,
+ LL_Count
+};
+
+#ifdef ENABLE_CUSTOM_LOGGER
+DISKANN_DLLEXPORT void SetCustomLogger(std::function<void(LogLevel, const char *)> logger);
+#endif
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/logger_impl.h b/packages/leann-backend-diskann/third_party/DiskANN/include/logger_impl.h
new file mode 100644
index 0000000..03c65e0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/logger_impl.h
@@ -0,0 +1,61 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <sstream>
+#include <mutex>
+
+#include "ann_exception.h"
+#include "logger.h"
+
+namespace diskann
+{
+#ifdef ENABLE_CUSTOM_LOGGER
+class ANNStreamBuf : public std::basic_streambuf<char>
+{
+ public:
+ DISKANN_DLLEXPORT explicit ANNStreamBuf(FILE *fp);
+ DISKANN_DLLEXPORT ~ANNStreamBuf();
+
+ DISKANN_DLLEXPORT bool is_open() const
+ {
+ return true; // because stdout and stderr are always open.
+ }
+ DISKANN_DLLEXPORT void close();
+ DISKANN_DLLEXPORT virtual int underflow();
+ DISKANN_DLLEXPORT virtual int overflow(int c);
+ DISKANN_DLLEXPORT virtual int sync();
+
+ private:
+ FILE *_fp;
+ char *_buf;
+ int _bufIndex;
+ std::mutex _mutex;
+ LogLevel _logLevel;
+
+ int flush();
+ void logImpl(char *str, int numchars);
+
+ // Why the two buffer-sizes? If we are running normally, we are basically
+ // interacting with a character output system, so we short-circuit the
+ // output process by keeping an empty buffer and writing each character
+ // to stdout/stderr. But if we are running in OLS, we have to take all
+ // the text that is written to diskann::cout/diskann:cerr, consolidate it
+ // and push it out in one-shot, because the OLS infra does not give us
+ // character based output. Therefore, we use a larger buffer that is large
+ // enough to store the longest message, and continuously add characters
+ // to it. When the calling code outputs a std::endl or std::flush, sync()
+ // will be called and will output a log level, component name, and the text
+ // that has been collected. (sync() is also called if the buffer is full, so
+ // overflows/missing text are not a concern).
+ // This implies calling code _must_ either print std::endl or std::flush
+ // to ensure that the message is written immediately.
+
+ static const int BUFFER_SIZE = 1024;
+
+ ANNStreamBuf(const ANNStreamBuf &);
+ ANNStreamBuf &operator=(const ANNStreamBuf &);
+};
+#endif
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/math_utils.h b/packages/leann-backend-diskann/third_party/DiskANN/include/math_utils.h
new file mode 100644
index 0000000..83d189f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/math_utils.h
@@ -0,0 +1,87 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include "common_includes.h"
+#include "utils.h"
+
+namespace math_utils
+{
+
+float calc_distance(float *vec_1, float *vec_2, size_t dim);
+
+// compute l2-squared norms of data stored in row major num_points * dim,
+// needs
+// to be pre-allocated
+void compute_vecs_l2sq(float *vecs_l2sq, float *data, const size_t num_points, const size_t dim);
+
+void rotate_data_randomly(float *data, size_t num_points, size_t dim, float *rot_mat, float *&new_mat,
+ bool transpose_rot = false);
+
+// calculate closest center to data of num_points * dim (row major)
+// centers is num_centers * dim (row major)
+// data_l2sq has pre-computed squared norms of data
+// centers_l2sq has pre-computed squared norms of centers
+// pre-allocated center_index will contain id of k nearest centers
+// pre-allocated dist_matrix shound be num_points * num_centers and contain
+// squared distances
+
+// Ideally used only by compute_closest_centers
+void compute_closest_centers_in_block(const float *const data, const size_t num_points, const size_t dim,
+ const float *const centers, const size_t num_centers,
+ const float *const docs_l2sq, const float *const centers_l2sq,
+ uint32_t *center_index, float *const dist_matrix, size_t k = 1);
+
+// Given data in num_points * new_dim row major
+// Pivots stored in full_pivot_data as k * new_dim row major
+// Calculate the closest pivot for each point and store it in vector
+// closest_centers_ivf (which needs to be allocated outside)
+// Additionally, if inverted index is not null (and pre-allocated), it will
+// return inverted index for each center Additionally, if pts_norms_squared is
+// not null, then it will assume that point norms are pre-computed and use
+// those
+// values
+
+void compute_closest_centers(float *data, size_t num_points, size_t dim, float *pivot_data, size_t num_centers,
+ size_t k, uint32_t *closest_centers_ivf, std::vector<size_t> *inverted_index = NULL,
+ float *pts_norms_squared = NULL);
+
+// if to_subtract is 1, will subtract nearest center from each row. Else will
+// add. Output will be in data_load iself.
+// Nearest centers need to be provided in closst_centers.
+
+void process_residuals(float *data_load, size_t num_points, size_t dim, float *cur_pivot_data, size_t num_centers,
+ uint32_t *closest_centers, bool to_subtract);
+
+} // namespace math_utils
+
+namespace kmeans
+{
+
+// run Lloyds one iteration
+// Given data in row major num_points * dim, and centers in row major
+// num_centers * dim
+// And squared lengths of data points, output the closest center to each data
+// point, update centers, and also return inverted index.
+// If closest_centers == NULL, will allocate memory and return.
+// Similarly, if closest_docs == NULL, will allocate memory and return.
+
+float lloyds_iter(float *data, size_t num_points, size_t dim, float *centers, size_t num_centers, float *docs_l2sq,
+ std::vector<size_t> *closest_docs, uint32_t *&closest_center);
+
+// Run Lloyds until max_reps or stopping criterion
+// If you pass NULL for closest_docs and closest_center, it will NOT return
+// the results, else it will assume appriate allocation as closest_docs = new
+// vector<size_t> [num_centers], and closest_center = new size_t[num_points]
+// Final centers are output in centers as row major num_centers * dim
+//
+float run_lloyds(float *data, size_t num_points, size_t dim, float *centers, const size_t num_centers,
+ const size_t max_reps, std::vector<size_t> *closest_docs, uint32_t *closest_center);
+
+// assumes already memory allocated for pivot_data as new
+// float[num_centers*dim] and select randomly num_centers points as pivots
+void selecting_pivots(float *data, size_t num_points, size_t dim, float *pivot_data, size_t num_centers);
+
+void kmeanspp_selecting_pivots(float *data, size_t num_points, size_t dim, float *pivot_data, size_t num_centers);
+} // namespace kmeans
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/memory_mapper.h b/packages/leann-backend-diskann/third_party/DiskANN/include/memory_mapper.h
new file mode 100644
index 0000000..75faca1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/memory_mapper.h
@@ -0,0 +1,43 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#ifndef _WINDOWS
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#else
+#include <Windows.h>
+#endif
+#include <string>
+
+namespace diskann
+{
+class MemoryMapper
+{
+ private:
+#ifndef _WINDOWS
+ int _fd;
+#else
+ HANDLE _bareFile;
+ HANDLE _fd;
+
+#endif
+ char *_buf;
+ size_t _fileSize;
+ const char *_fileName;
+
+ public:
+ MemoryMapper(const char *filename);
+ MemoryMapper(const std::string &filename);
+
+ char *getBuf();
+ size_t getFileSize();
+
+ ~MemoryMapper();
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/natural_number_map.h b/packages/leann-backend-diskann/third_party/DiskANN/include/natural_number_map.h
new file mode 100644
index 0000000..e846882
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/natural_number_map.h
@@ -0,0 +1,86 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <memory>
+#include <type_traits>
+#include <vector>
+
+#include <boost/dynamic_bitset.hpp>
+
+namespace diskann
+{
+// A map whose key is a natural number (from 0 onwards) and maps to a value.
+// Made as both memory and performance efficient map for scenario such as
+// DiskANN location-to-tag map. There, the pool of numbers is consecutive from
+// zero to some max value, and it's expected that most if not all keys from 0
+// up to some current maximum will be present in the map. The memory usage of
+// the map is determined by the largest inserted key since it uses vector as a
+// backing store and bitset for presence indication.
+//
+// Thread-safety: this class is not thread-safe in general.
+// Exception: multiple read-only operations are safe on the object only if
+// there are no writers to it in parallel.
+template <typename Key, typename Value> class natural_number_map
+{
+ public:
+ static_assert(std::is_trivial<Key>::value, "Key must be a trivial type");
+
+ // Represents a reference to a element in the map. Used while iterating
+ // over map entries.
+ struct position
+ {
+ size_t _key;
+ // The number of keys that were enumerated when iterating through the
+ // map so far. Used to early-terminate enumeration when ithere are no
+ // more entries in the map.
+ size_t _keys_already_enumerated;
+
+ // Returns whether it's valid to access the element at this position in
+ // the map.
+ bool is_valid() const;
+ };
+
+ natural_number_map();
+
+ void reserve(size_t count);
+ size_t size() const;
+
+ void set(Key key, Value value);
+ void erase(Key key);
+
+ bool contains(Key key) const;
+ bool try_get(Key key, Value &value) const;
+
+ // Returns the value at the specified position. Prerequisite: position is
+ // valid.
+ Value get(const position &pos) const;
+
+ // Finds the first element in the map, if any. Invalidated by changes in the
+ // map.
+ position find_first() const;
+
+ // Finds the next element in the map after the specified position.
+ // Invalidated by changes in the map.
+ position find_next(const position &after_position) const;
+
+ void clear();
+
+ private:
+ // Number of entries in the map. Not the same as size() of the
+ // _values_vector below.
+ size_t _size;
+
+ // Array of values. The key is the index of the value.
+ std::vector<Value> _values_vector;
+
+ // Values that are in the set have the corresponding bit index set
+ // to 1.
+ //
+ // Use a pointer here to allow for forward declaration of dynamic_bitset
+ // in public headers to avoid making boost a dependency for clients
+ // of DiskANN.
+ std::unique_ptr<boost::dynamic_bitset<>> _values_bitset;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/natural_number_set.h b/packages/leann-backend-diskann/third_party/DiskANN/include/natural_number_set.h
new file mode 100644
index 0000000..ec5b827
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/natural_number_set.h
@@ -0,0 +1,50 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <memory>
+#include <type_traits>
+
+#include "boost_dynamic_bitset_fwd.h"
+
+namespace diskann
+{
+// A set of natural numbers (from 0 onwards). Made for scenario where the
+// pool of numbers is consecutive from zero to some max value and very
+// efficient methods for "add to set", "get any value from set", "is in set"
+// are needed. The memory usage of the set is determined by the largest
+// number of inserted entries (uses a vector as a backing store) as well as
+// the largest value to be placed in it (uses bitset as well).
+//
+// Thread-safety: this class is not thread-safe in general.
+// Exception: multiple read-only operations (e.g. is_in_set, empty, size) are
+// safe on the object only if there are no writers to it in parallel.
+template <typename T> class natural_number_set
+{
+ public:
+ static_assert(std::is_trivial<T>::value, "Identifier must be a trivial type");
+
+ natural_number_set();
+
+ bool is_empty() const;
+ void reserve(size_t count);
+ void insert(T id);
+ T pop_any();
+ void clear();
+ size_t size() const;
+ bool is_in_set(T id) const;
+
+ private:
+ // Values that are currently in set.
+ std::vector<T> _values_vector;
+
+ // Values that are in the set have the corresponding bit index set
+ // to 1.
+ //
+ // Use a pointer here to allow for forward declaration of dynamic_bitset
+ // in public headers to avoid making boost a dependency for clients
+ // of DiskANN.
+ std::unique_ptr<boost::dynamic_bitset<>> _values_bitset;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/neighbor.h b/packages/leann-backend-diskann/third_party/DiskANN/include/neighbor.h
new file mode 100644
index 0000000..d7c0c25
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/neighbor.h
@@ -0,0 +1,152 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstddef>
+#include <mutex>
+#include <vector>
+#include "utils.h"
+
+namespace diskann
+{
+
+struct Neighbor
+{
+ unsigned id;
+ float distance;
+ bool expanded;
+
+ Neighbor() = default;
+
+ Neighbor(unsigned id, float distance) : id{id}, distance{distance}, expanded(false)
+ {
+ }
+
+ inline bool operator<(const Neighbor &other) const
+ {
+ return distance < other.distance || (distance == other.distance && id < other.id);
+ }
+
+ inline bool operator==(const Neighbor &other) const
+ {
+ return (id == other.id);
+ }
+};
+
+// Invariant: after every `insert` and `closest_unexpanded()`, `_cur` points to
+// the first Neighbor which is unexpanded.
+class NeighborPriorityQueue
+{
+ public:
+ NeighborPriorityQueue() : _size(0), _capacity(0), _cur(0)
+ {
+ }
+
+ explicit NeighborPriorityQueue(size_t capacity) : _size(0), _capacity(capacity), _cur(0), _data(capacity + 1)
+ {
+ }
+
+ // Inserts the item ordered into the set up to the sets capacity.
+ // The item will be dropped if it is the same id as an exiting
+ // set item or it has a greated distance than the final
+ // item in the set. The set cursor that is used to pop() the
+ // next item will be set to the lowest index of an uncheck item
+ void insert(const Neighbor &nbr)
+ {
+ if (_size == _capacity && _data[_size - 1] < nbr)
+ {
+ return;
+ }
+
+ size_t lo = 0, hi = _size;
+ while (lo < hi)
+ {
+ size_t mid = (lo + hi) >> 1;
+ if (nbr < _data[mid])
+ {
+ hi = mid;
+ // Make sure the same id isn't inserted into the set
+ }
+ else if (_data[mid].id == nbr.id)
+ {
+ return;
+ }
+ else
+ {
+ lo = mid + 1;
+ }
+ }
+
+ if (lo < _capacity)
+ {
+ std::memmove(&_data[lo + 1], &_data[lo], (_size - lo) * sizeof(Neighbor));
+ }
+ _data[lo] = {nbr.id, nbr.distance};
+ if (_size < _capacity)
+ {
+ _size++;
+ }
+ if (lo < _cur)
+ {
+ _cur = lo;
+ }
+ }
+
+ Neighbor closest_unexpanded()
+ {
+ _data[_cur].expanded = true;
+ size_t pre = _cur;
+ while (_cur < _size && _data[_cur].expanded)
+ {
+ _cur++;
+ }
+ return _data[pre];
+ }
+
+ bool has_unexpanded_node() const
+ {
+ return _cur < _size;
+ }
+
+ size_t size() const
+ {
+ return _size;
+ }
+
+ size_t capacity() const
+ {
+ return _capacity;
+ }
+
+ void reserve(size_t capacity)
+ {
+ if (capacity + 1 > _data.size())
+ {
+ _data.resize(capacity + 1);
+ }
+ _capacity = capacity;
+ }
+
+ Neighbor &operator[](size_t i)
+ {
+ return _data[i];
+ }
+
+ Neighbor operator[](size_t i) const
+ {
+ return _data[i];
+ }
+
+ void clear()
+ {
+ _size = 0;
+ _cur = 0;
+ }
+
+ private:
+ size_t _size, _capacity, _cur;
+ std::vector<Neighbor> _data;
+};
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/parameters.h b/packages/leann-backend-diskann/third_party/DiskANN/include/parameters.h
new file mode 100644
index 0000000..0206814
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/parameters.h
@@ -0,0 +1,119 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <sstream>
+#include <typeinfo>
+#include <unordered_map>
+
+#include "omp.h"
+#include "defaults.h"
+
+namespace diskann
+{
+
+class IndexWriteParameters
+
+{
+ public:
+ const uint32_t search_list_size; // L
+ const uint32_t max_degree; // R
+ const bool saturate_graph;
+ const uint32_t max_occlusion_size; // C
+ const float alpha;
+ const uint32_t num_threads;
+ const uint32_t filter_list_size; // Lf
+
+ IndexWriteParameters(const uint32_t search_list_size, const uint32_t max_degree, const bool saturate_graph,
+ const uint32_t max_occlusion_size, const float alpha, const uint32_t num_threads,
+ const uint32_t filter_list_size)
+ : search_list_size(search_list_size), max_degree(max_degree), saturate_graph(saturate_graph),
+ max_occlusion_size(max_occlusion_size), alpha(alpha), num_threads(num_threads),
+ filter_list_size(filter_list_size)
+ {
+ }
+
+ friend class IndexWriteParametersBuilder;
+};
+
+class IndexSearchParams
+{
+ public:
+ IndexSearchParams(const uint32_t initial_search_list_size, const uint32_t num_search_threads)
+ : initial_search_list_size(initial_search_list_size), num_search_threads(num_search_threads)
+ {
+ }
+ const uint32_t initial_search_list_size; // search L
+ const uint32_t num_search_threads; // search threads
+};
+
+class IndexWriteParametersBuilder
+{
+ /**
+ * Fluent builder pattern to keep track of the 7 non-default properties
+ * and their order. The basic ctor was getting unwieldy.
+ */
+ public:
+ IndexWriteParametersBuilder(const uint32_t search_list_size, // L
+ const uint32_t max_degree // R
+ )
+ : _search_list_size(search_list_size), _max_degree(max_degree)
+ {
+ }
+
+ IndexWriteParametersBuilder &with_max_occlusion_size(const uint32_t max_occlusion_size)
+ {
+ _max_occlusion_size = max_occlusion_size;
+ return *this;
+ }
+
+ IndexWriteParametersBuilder &with_saturate_graph(const bool saturate_graph)
+ {
+ _saturate_graph = saturate_graph;
+ return *this;
+ }
+
+ IndexWriteParametersBuilder &with_alpha(const float alpha)
+ {
+ _alpha = alpha;
+ return *this;
+ }
+
+ IndexWriteParametersBuilder &with_num_threads(const uint32_t num_threads)
+ {
+ _num_threads = num_threads == 0 ? omp_get_num_procs() : num_threads;
+ return *this;
+ }
+
+ IndexWriteParametersBuilder &with_filter_list_size(const uint32_t filter_list_size)
+ {
+ _filter_list_size = filter_list_size == 0 ? _search_list_size : filter_list_size;
+ return *this;
+ }
+
+ IndexWriteParameters build() const
+ {
+ return IndexWriteParameters(_search_list_size, _max_degree, _saturate_graph, _max_occlusion_size, _alpha,
+ _num_threads, _filter_list_size);
+ }
+
+ IndexWriteParametersBuilder(const IndexWriteParameters &wp)
+ : _search_list_size(wp.search_list_size), _max_degree(wp.max_degree),
+ _max_occlusion_size(wp.max_occlusion_size), _saturate_graph(wp.saturate_graph), _alpha(wp.alpha),
+ _filter_list_size(wp.filter_list_size)
+ {
+ }
+ IndexWriteParametersBuilder(const IndexWriteParametersBuilder &) = delete;
+ IndexWriteParametersBuilder &operator=(const IndexWriteParametersBuilder &) = delete;
+
+ private:
+ uint32_t _search_list_size{};
+ uint32_t _max_degree{};
+ uint32_t _max_occlusion_size{defaults::MAX_OCCLUSION_SIZE};
+ bool _saturate_graph{defaults::SATURATE_GRAPH};
+ float _alpha{defaults::ALPHA};
+ uint32_t _num_threads{defaults::NUM_THREADS};
+ uint32_t _filter_list_size{defaults::FILTER_LIST_SIZE};
+};
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/partition.h b/packages/leann-backend-diskann/third_party/DiskANN/include/partition.h
new file mode 100644
index 0000000..c2c4c76
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/partition.h
@@ -0,0 +1,49 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include <cassert>
+#include <sstream>
+#include <stack>
+#include <string>
+#include <unordered_map>
+
+#include "neighbor.h"
+#include "parameters.h"
+#include "tsl/robin_set.h"
+#include "utils.h"
+
+#include "windows_customizations.h"
+
+template <typename T>
+void gen_random_slice(const std::string base_file, const std::string output_prefix, double sampling_rate);
+
+template <typename T>
+void gen_random_slice(const std::string data_file, double p_val, float *&sampled_data, size_t &slice_size,
+ size_t &ndims);
+
+template <typename T>
+void gen_random_slice(const T *inputdata, size_t npts, size_t ndims, double p_val, float *&sampled_data,
+ size_t &slice_size);
+
+int estimate_cluster_sizes(float *test_data_float, size_t num_test, float *pivots, const size_t num_centers,
+ const size_t dim, const size_t k_base, std::vector<size_t> &cluster_sizes);
+
+template <typename T>
+int shard_data_into_clusters(const std::string data_file, float *pivots, const size_t num_centers, const size_t dim,
+ const size_t k_base, std::string prefix_path);
+
+template <typename T>
+int shard_data_into_clusters_only_ids(const std::string data_file, float *pivots, const size_t num_centers,
+ const size_t dim, const size_t k_base, std::string prefix_path);
+
+template <typename T>
+int retrieve_shard_data_from_ids(const std::string data_file, std::string idmap_filename, std::string data_filename);
+
+template <typename T>
+int partition(const std::string data_file, const float sampling_rate, size_t num_centers, size_t max_k_means_reps,
+ const std::string prefix_path, size_t k_base);
+
+template <typename T>
+int partition_with_ram_budget(const std::string data_file, const double sampling_rate, double ram_budget,
+ size_t graph_degree, const std::string prefix_path, size_t k_base);
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/percentile_stats.h b/packages/leann-backend-diskann/third_party/DiskANN/include/percentile_stats.h
new file mode 100644
index 0000000..7932575
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/percentile_stats.h
@@ -0,0 +1,65 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <fstream>
+#include <functional>
+#ifdef _WINDOWS
+#include <numeric>
+#endif
+#include <string>
+#include <vector>
+
+#include "distance.h"
+#include "parameters.h"
+
+namespace diskann
+{
+struct QueryStats
+{
+ float total_us = 0; // total time to process query in micros
+ float io_us = 0; // total time spent in IO
+ float cpu_us = 0; // total time spent in CPU
+
+ unsigned n_4k = 0; // # of 4kB reads
+ unsigned n_8k = 0; // # of 8kB reads
+ unsigned n_12k = 0; // # of 12kB reads
+ unsigned n_ios = 0; // total # of IOs issued
+ unsigned read_size = 0; // total # of bytes read
+ unsigned n_cmps_saved = 0; // # cmps saved
+ unsigned n_cmps = 0; // # cmps
+ unsigned n_cache_hits = 0; // # cache_hits
+ unsigned n_hops = 0; // # search hops
+};
+
+template <typename T>
+inline T get_percentile_stats(QueryStats *stats, uint64_t len, float percentile,
+ const std::function<T(const QueryStats &)> &member_fn)
+{
+ std::vector<T> vals(len);
+ for (uint64_t i = 0; i < len; i++)
+ {
+ vals[i] = member_fn(stats[i]);
+ }
+
+ std::sort(vals.begin(), vals.end(), [](const T &left, const T &right) { return left < right; });
+
+ auto retval = vals[(uint64_t)(percentile * len)];
+ vals.clear();
+ return retval;
+}
+
+template <typename T>
+inline double get_mean_stats(QueryStats *stats, uint64_t len, const std::function<T(const QueryStats &)> &member_fn)
+{
+ double avg = 0;
+ for (uint64_t i = 0; i < len; i++)
+ {
+ avg += (double)member_fn(stats[i]);
+ }
+ return avg / len;
+}
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/pq.h b/packages/leann-backend-diskann/third_party/DiskANN/include/pq.h
new file mode 100644
index 0000000..3e6119f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/pq.h
@@ -0,0 +1,93 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include "utils.h"
+#include "pq_common.h"
+
+namespace diskann
+{
+class FixedChunkPQTable
+{
+ float *tables = nullptr; // pq_tables = float array of size [256 * ndims]
+ uint64_t ndims = 0; // ndims = true dimension of vectors
+ uint64_t n_chunks = 0;
+ bool use_rotation = false;
+ uint32_t *chunk_offsets = nullptr;
+ float *centroid = nullptr;
+ float *tables_tr = nullptr; // same as pq_tables, but col-major
+ float *rotmat_tr = nullptr;
+
+ public:
+ FixedChunkPQTable();
+
+ virtual ~FixedChunkPQTable();
+
+#ifdef EXEC_ENV_OLS
+ void load_pq_centroid_bin(MemoryMappedFiles &files, const char *pq_table_file, size_t num_chunks);
+#else
+ void load_pq_centroid_bin(const char *pq_table_file, size_t num_chunks);
+#endif
+
+ uint32_t get_num_chunks();
+
+ void preprocess_query(float *query_vec);
+
+ // assumes pre-processed query
+ void populate_chunk_distances(const float *query_vec, float *dist_vec);
+
+ float l2_distance(const float *query_vec, uint8_t *base_vec);
+
+ float inner_product(const float *query_vec, uint8_t *base_vec);
+
+ // assumes no rotation is involved
+ void inflate_vector(uint8_t *base_vec, float *out_vec);
+
+ void populate_chunk_inner_products(const float *query_vec, float *dist_vec);
+};
+
+void aggregate_coords(const std::vector<unsigned> &ids, const uint8_t *all_coords, const uint64_t ndims, uint8_t *out);
+
+void pq_dist_lookup(const uint8_t *pq_ids, const size_t n_pts, const size_t pq_nchunks, const float *pq_dists,
+ std::vector<float> &dists_out);
+
+// Need to replace calls to these with calls to vector& based functions above
+void aggregate_coords(const unsigned *ids, const uint64_t n_ids, const uint8_t *all_coords, const uint64_t ndims,
+ uint8_t *out);
+
+void pq_dist_lookup(const uint8_t *pq_ids, const size_t n_pts, const size_t pq_nchunks, const float *pq_dists,
+ float *dists_out);
+
+DISKANN_DLLEXPORT int generate_pq_pivots(const float *const train_data, size_t num_train, unsigned dim,
+ unsigned num_centers, unsigned num_pq_chunks, unsigned max_k_means_reps,
+ std::string pq_pivots_path, bool make_zero_mean = false);
+
+DISKANN_DLLEXPORT int generate_opq_pivots(const float *train_data, size_t num_train, unsigned dim, unsigned num_centers,
+ unsigned num_pq_chunks, std::string opq_pivots_path,
+ bool make_zero_mean = false);
+
+DISKANN_DLLEXPORT int generate_pq_pivots_simplified(const float *train_data, size_t num_train, size_t dim,
+ size_t num_pq_chunks, std::vector<float> &pivot_data_vector);
+
+template <typename T>
+int generate_pq_data_from_pivots(const std::string &data_file, unsigned num_centers, unsigned num_pq_chunks,
+ const std::string &pq_pivots_path, const std::string &pq_compressed_vectors_path,
+ bool use_opq = false);
+
+DISKANN_DLLEXPORT int generate_pq_data_from_pivots_simplified(const float *data, const size_t num,
+ const float *pivot_data, const size_t pivots_num,
+ const size_t dim, const size_t num_pq_chunks,
+ std::vector<uint8_t> &pq);
+
+template <typename T>
+void generate_disk_quantized_data(const std::string &data_file_to_use, const std::string &disk_pq_pivots_path,
+ const std::string &disk_pq_compressed_vectors_path,
+ const diskann::Metric compareMetric, const double p_val, size_t &disk_pq_dims);
+
+template <typename T>
+void generate_quantized_data(const std::string &data_file_to_use, const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path, const diskann::Metric compareMetric,
+ const double p_val, const uint64_t num_pq_chunks, const bool use_opq,
+ const std::string &codebook_prefix = "");
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/pq_common.h b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_common.h
new file mode 100644
index 0000000..c6a3a57
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_common.h
@@ -0,0 +1,30 @@
+#pragma once
+
+#include <string>
+#include <sstream>
+
+#define NUM_PQ_BITS 8
+#define NUM_PQ_CENTROIDS (1 << NUM_PQ_BITS)
+#define MAX_OPQ_ITERS 20
+#define NUM_KMEANS_REPS_PQ 12
+#define MAX_PQ_TRAINING_SET_SIZE 256000
+#define MAX_PQ_CHUNKS 512
+
+namespace diskann
+{
+inline std::string get_quantized_vectors_filename(const std::string &prefix, bool use_opq, uint32_t num_chunks)
+{
+ return prefix + (use_opq ? "_opq" : "pq") + std::to_string(num_chunks) + "_compressed.bin";
+}
+
+inline std::string get_pivot_data_filename(const std::string &prefix, bool use_opq, uint32_t num_chunks)
+{
+ return prefix + (use_opq ? "_opq" : "pq") + std::to_string(num_chunks) + "_pivots.bin";
+}
+
+inline std::string get_rotation_matrix_suffix(const std::string &pivot_data_filename)
+{
+ return pivot_data_filename + "_rotation_matrix.bin";
+}
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/pq_data_store.h b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_data_store.h
new file mode 100644
index 0000000..7c0cb5f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_data_store.h
@@ -0,0 +1,97 @@
+#pragma once
+#include <memory>
+#include "distance.h"
+#include "quantized_distance.h"
+#include "pq.h"
+#include "abstract_data_store.h"
+
+namespace diskann
+{
+// REFACTOR TODO: By default, the PQDataStore is an in-memory datastore because both Vamana and
+// DiskANN treat it the same way. But with DiskPQ, that may need to change.
+template <typename data_t> class PQDataStore : public AbstractDataStore<data_t>
+{
+
+ public:
+ PQDataStore(size_t dim, location_t num_points, size_t num_pq_chunks, std::unique_ptr<Distance<data_t>> distance_fn,
+ std::unique_ptr<QuantizedDistance<data_t>> pq_distance_fn);
+ PQDataStore(const PQDataStore &) = delete;
+ PQDataStore &operator=(const PQDataStore &) = delete;
+ ~PQDataStore();
+
+ // Load quantized vectors from a set of files. Here filename is treated
+ // as a prefix and the files are assumed to be named with DiskANN
+ // conventions.
+ virtual location_t load(const std::string &file_prefix) override;
+
+ // Save quantized vectors to a set of files whose names start with
+ // file_prefix.
+ // Currently, the plan is to save the quantized vectors to the quantized
+ // vectors file.
+ virtual size_t save(const std::string &file_prefix, const location_t num_points) override;
+
+ // Since base class function is pure virtual, we need to declare it here, even though alignent concept is not needed
+ // for Quantized data stores.
+ virtual size_t get_aligned_dim() const override;
+
+ // Populate quantized data from unaligned data using PQ functionality
+ virtual void populate_data(const data_t *vectors, const location_t num_pts) override;
+ virtual void populate_data(const std::string &filename, const size_t offset) override;
+
+ virtual void extract_data_to_bin(const std::string &filename, const location_t num_pts) override;
+
+ virtual void get_vector(const location_t i, data_t *target) const override;
+ virtual void set_vector(const location_t i, const data_t *const vector) override;
+ virtual void prefetch_vector(const location_t loc) override;
+
+ virtual void move_vectors(const location_t old_location_start, const location_t new_location_start,
+ const location_t num_points) override;
+ virtual void copy_vectors(const location_t from_loc, const location_t to_loc, const location_t num_points) override;
+
+ virtual void preprocess_query(const data_t *query, AbstractScratch<data_t> *scratch) const override;
+
+ virtual float get_distance(const data_t *query, const location_t loc) const override;
+ virtual float get_distance(const location_t loc1, const location_t loc2) const override;
+
+ // NOTE: Caller must invoke "PQDistance->preprocess_query" ONCE before calling
+ // this function.
+ virtual void get_distance(const data_t *preprocessed_query, const location_t *locations,
+ const uint32_t location_count, float *distances,
+ AbstractScratch<data_t> *scratch_space) const override;
+
+ // NOTE: Caller must invoke "PQDistance->preprocess_query" ONCE before calling
+ // this function.
+ virtual void get_distance(const data_t *preprocessed_query, const std::vector<location_t> &ids,
+ std::vector<float> &distances, AbstractScratch<data_t> *scratch_space) const override;
+
+ // We are returning the distance function that is used for full precision
+ // vectors here, not the PQ distance function. This is because the callers
+ // all are expecting a Distance<T> not QuantizedDistance<T>.
+ virtual Distance<data_t> *get_dist_fn() const override;
+
+ virtual location_t calculate_medoid() const override;
+
+ virtual size_t get_alignment_factor() const override;
+
+ protected:
+ virtual location_t expand(const location_t new_size) override;
+ virtual location_t shrink(const location_t new_size) override;
+
+ virtual location_t load_impl(const std::string &filename);
+#ifdef EXEC_ENV_OLS
+ virtual location_t load_impl(AlignedFileReader &reader);
+#endif
+
+ private:
+ uint8_t *_quantized_data = nullptr;
+ size_t _num_chunks = 0;
+
+ // REFACTOR TODO: Doing this temporarily before refactoring OPQ into
+ // its own class. Remove later.
+ bool _use_opq = false;
+
+ Metric _distance_metric;
+ std::unique_ptr<Distance<data_t>> _distance_fn = nullptr;
+ std::unique_ptr<QuantizedDistance<data_t>> _pq_distance_fn = nullptr;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/pq_flash_index.h b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_flash_index.h
new file mode 100644
index 0000000..174df5c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_flash_index.h
@@ -0,0 +1,286 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#include "common_includes.h"
+
+#include "aligned_file_reader.h"
+#include "concurrent_queue.h"
+#include "neighbor.h"
+#include "parameters.h"
+#include "percentile_stats.h"
+#include "pq.h"
+#include "utils.h"
+#include "windows_customizations.h"
+#include "scratch.h"
+#include "tsl/robin_map.h"
+#include "tsl/robin_set.h"
+
+#define FULL_PRECISION_REORDER_MULTIPLIER 3
+
+namespace diskann
+{
+
+template <typename T, typename LabelT = uint32_t> class PQFlashIndex
+{
+ public:
+ DISKANN_DLLEXPORT PQFlashIndex(std::shared_ptr<AlignedFileReader> &fileReader,
+ std::shared_ptr<AlignedFileReader> &graphReader,
+ diskann::Metric metric = diskann::Metric::L2);
+ DISKANN_DLLEXPORT ~PQFlashIndex();
+
+#ifdef EXEC_ENV_OLS
+ DISKANN_DLLEXPORT int load(diskann::MemoryMappedFiles &files, uint32_t num_threads, const char *index_prefix,
+ const char *pq_prefix = nullptr);
+#else
+ // load compressed data, and obtains the handle to the disk-resident index
+ DISKANN_DLLEXPORT int load(uint32_t num_threads, const char *index_prefix, const char *pq_prefix = nullptr,
+ const char *partition_prefix = nullptr);
+#endif
+
+#ifdef EXEC_ENV_OLS
+ DISKANN_DLLEXPORT int load_from_separate_paths(diskann::MemoryMappedFiles &files, uint32_t num_threads,
+ const char *index_filepath, const char *pivots_filepath,
+ const char *compressed_filepath, const char *graph_file);
+#else
+ DISKANN_DLLEXPORT int load_from_separate_paths(uint32_t num_threads, const char *index_filepath,
+ const char *pivots_filepath, const char *compressed_filepath,
+ const char *graph_file, const char *partition_file);
+#endif
+
+ DISKANN_DLLEXPORT void load_cache_list(std::vector<uint32_t> &node_list);
+
+#ifdef EXEC_ENV_OLS
+ DISKANN_DLLEXPORT void generate_cache_list_from_sample_queries(MemoryMappedFiles &files, std::string sample_bin,
+ uint64_t l_search, uint64_t beamwidth,
+ uint64_t num_nodes_to_cache, uint32_t nthreads,
+ std::vector<uint32_t> &node_list);
+#else
+ DISKANN_DLLEXPORT void generate_cache_list_from_sample_queries(std::string sample_bin, uint64_t l_search,
+ uint64_t beamwidth, uint64_t num_nodes_to_cache,
+ uint32_t num_threads,
+ std::vector<uint32_t> &node_list);
+#endif
+
+ DISKANN_DLLEXPORT void cache_bfs_levels(uint64_t num_nodes_to_cache, std::vector<uint32_t> &node_list,
+ const bool shuffle = false);
+
+ DISKANN_DLLEXPORT void cached_beam_search(const T *query, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *res_ids, float *res_dists, const uint64_t beam_width,
+ const bool use_reorder_data = false, QueryStats *stats = nullptr,
+ const bool USE_DEFERRED_FETCH = false,
+ const bool skip_search_reorder = false,
+ const bool recompute_beighbor_embeddings = false,
+ const bool dedup_node_dis = false, float prune_ratio = 0,
+ const bool batch_recompute = false, bool global_pruning = false);
+
+ DISKANN_DLLEXPORT void cached_beam_search(const T *query, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *res_ids, float *res_dists, const uint64_t beam_width,
+ const bool use_filter, const LabelT &filter_label,
+ const bool use_reorder_data = false, QueryStats *stats = nullptr,
+ const bool USE_DEFERRED_FETCH = false,
+ const bool skip_search_reorder = false,
+ const bool recompute_beighbor_embeddings = false,
+ const bool dedup_node_dis = false, float prune_ratio = 0,
+ const bool batch_recompute = false, bool global_pruning = false);
+
+ DISKANN_DLLEXPORT void cached_beam_search(const T *query, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *res_ids, float *res_dists, const uint64_t beam_width,
+ const uint32_t io_limit, const bool use_reorder_data = false,
+ QueryStats *stats = nullptr, const bool USE_DEFERRED_FETCH = false,
+ const bool skip_search_reorder = false,
+ const bool recompute_beighbor_embeddings = false,
+ const bool dedup_node_dis = false, float prune_ratio = 0,
+ const bool batch_recompute = false, bool global_pruning = false);
+
+ DISKANN_DLLEXPORT void cached_beam_search(const T *query, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *res_ids, float *res_dists, const uint64_t beam_width,
+ const bool use_filter, const LabelT &filter_label,
+ const uint32_t io_limit, const bool use_reorder_data = false,
+ QueryStats *stats = nullptr, const bool USE_DEFERRED_FETCH = false,
+ const bool skip_search_reorder = false,
+ const bool recompute_beighbor_embeddings = false,
+ const bool dedup_node_dis = false, float prune_ratio = 0,
+ const bool batch_recompute = false, bool global_pruning = false);
+
+ DISKANN_DLLEXPORT LabelT get_converted_label(const std::string &filter_label);
+
+ DISKANN_DLLEXPORT uint32_t range_search(const T *query1, const double range, const uint64_t min_l_search,
+ const uint64_t max_l_search, std::vector<uint64_t> &indices,
+ std::vector<float> &distances, const uint64_t min_beam_width,
+ QueryStats *stats = nullptr);
+
+ DISKANN_DLLEXPORT uint64_t get_data_dim();
+
+ std::shared_ptr<AlignedFileReader> &reader;
+
+ DISKANN_DLLEXPORT diskann::Metric get_metric();
+
+ //
+ // node_ids: input list of node_ids to be read
+ // coord_buffers: pointers to pre-allocated buffers that coords need to copied to. If null, dont copy.
+ // nbr_buffers: pre-allocated buffers to copy neighbors into
+ //
+ // returns a vector of bool one for each node_id: true if read is success, else false
+ //
+ DISKANN_DLLEXPORT std::vector<bool> read_nodes(const std::vector<uint32_t> &node_ids,
+ std::vector<T *> &coord_buffers,
+ std::vector<std::pair<uint32_t, uint32_t *>> &nbr_buffers);
+
+ DISKANN_DLLEXPORT std::vector<std::uint8_t> get_pq_vector(std::uint64_t vid);
+ DISKANN_DLLEXPORT uint64_t get_num_points();
+
+ protected:
+ DISKANN_DLLEXPORT void use_medoids_data_as_centroids();
+ DISKANN_DLLEXPORT void setup_thread_data(uint64_t nthreads, uint64_t visited_reserve = 4096);
+
+ DISKANN_DLLEXPORT void set_universal_label(const LabelT &label);
+
+ private:
+ DISKANN_DLLEXPORT inline bool point_has_label(uint32_t point_id, LabelT label_id);
+ std::unordered_map<std::string, LabelT> load_label_map(std::basic_istream<char> &infile);
+ DISKANN_DLLEXPORT void parse_label_file(std::basic_istream<char> &infile, size_t &num_pts_labels);
+ DISKANN_DLLEXPORT void get_label_file_metadata(const std::string &fileContent, uint32_t &num_pts,
+ uint32_t &num_total_labels);
+ DISKANN_DLLEXPORT void generate_random_labels(std::vector<LabelT> &labels, const uint32_t num_labels,
+ const uint32_t nthreads);
+ void reset_stream_for_reading(std::basic_istream<char> &infile);
+
+ // sector # on disk where node_id is present with in the graph part
+ DISKANN_DLLEXPORT uint64_t get_node_sector(uint64_t node_id);
+
+ // ptr to start of the node
+ DISKANN_DLLEXPORT char *offset_to_node(char *sector_buf, uint64_t node_id);
+
+ // returns region of `node_buf` containing [NNBRS][NBR_ID(uint32_t)]
+ DISKANN_DLLEXPORT uint32_t *offset_to_node_nhood(char *node_buf);
+
+ // returns region of `node_buf` containing [COORD(T)]
+ DISKANN_DLLEXPORT T *offset_to_node_coords(char *node_buf);
+
+ DISKANN_DLLEXPORT int load_graph_index(const std::string &graph_index_file);
+
+ DISKANN_DLLEXPORT int read_partition_info(const std::string &partition_bin);
+
+ DISKANN_DLLEXPORT int read_neighbors(const std::string &graph_index_file, uint64_t target_node_id);
+
+ // index info for multi-node sectors
+ // nhood of node `i` is in sector: [i / nnodes_per_sector]
+ // offset in sector: [(i % nnodes_per_sector) * max_node_len]
+ //
+ // index info for multi-sector nodes
+ // nhood of node `i` is in sector: [i * DIV_ROUND_UP(_max_node_len, SECTOR_LEN)]
+ // offset in sector: [0]
+ //
+ // Common info
+ // coords start at ofsset
+ // #nbrs of node `i`: *(unsigned*) (offset + disk_bytes_per_point)
+ // nbrs of node `i` : (unsigned*) (offset + disk_bytes_per_point + 1)
+
+ uint64_t _max_node_len = 0;
+ uint64_t _nnodes_per_sector = 0; // 0 for multi-sector nodes, >0 for multi-node sectors
+ uint64_t _max_degree = 0;
+ uint64_t _C = 0;
+ // Data used for searching with re-order vectors
+ uint64_t _ndims_reorder_vecs = 0;
+ uint64_t _reorder_data_start_sector = 0;
+ uint64_t _nvecs_per_sector = 0;
+
+ diskann::Metric metric = diskann::Metric::L2;
+
+ // used only for inner product search to re-scale the result value
+ // (due to the pre-processing of base during index build)
+ float _max_base_norm = 0.0f;
+
+ // data info
+ uint64_t _num_points = 0;
+ uint64_t _num_frozen_points = 0;
+ uint64_t _frozen_location = 0;
+ uint64_t _data_dim = 0;
+ uint64_t _aligned_dim = 0;
+ uint64_t _disk_bytes_per_point = 0; // Number of bytes
+
+ std::string _disk_index_file;
+ std::vector<std::pair<uint32_t, uint32_t>> _node_visit_counter;
+
+ // PQ data
+ // _n_chunks = # of chunks ndims is split into
+ // data: char * _n_chunks
+ // chunk_size = chunk size of each dimension chunk
+ // pq_tables = float* [[2^8 * [chunk_size]] * _n_chunks]
+ uint8_t *data = nullptr;
+ uint64_t _n_chunks;
+ FixedChunkPQTable _pq_table;
+
+ // distance comparator
+ std::shared_ptr<Distance<T>> _dist_cmp;
+ std::shared_ptr<Distance<float>> _dist_cmp_float;
+
+ // for very large datasets: we use PQ even for the disk resident index
+ bool _use_disk_index_pq = false;
+ uint64_t _disk_pq_n_chunks = 0;
+ FixedChunkPQTable _disk_pq_table;
+
+ // medoid/start info
+
+ // graph has one entry point by default,
+ // we can optionally have multiple starting points
+ uint32_t *_medoids = nullptr;
+ // defaults to 1
+ size_t _num_medoids;
+ // by default, it is empty. If there are multiple
+ // centroids, we pick the medoid corresponding to the
+ // closest centroid as the starting point of search
+ float *_centroid_data = nullptr;
+
+ // nhood_cache; the uint32_t in nhood_Cache are offsets into nhood_cache_buf
+ unsigned *_nhood_cache_buf = nullptr;
+ tsl::robin_map<uint32_t, std::pair<uint32_t, uint32_t *>> _nhood_cache;
+
+ // coord_cache; The T* in coord_cache are offsets into coord_cache_buf
+ T *_coord_cache_buf = nullptr;
+ tsl::robin_map<uint32_t, T *> _coord_cache;
+
+ // thread-specific scratch
+ ConcurrentQueue<SSDThreadData<T> *> _thread_data;
+ uint64_t _max_nthreads;
+ bool _load_flag = false;
+ bool _count_visited_nodes = false;
+ bool _reorder_data_exists = false;
+ uint64_t _reoreder_data_offset = 0;
+
+ // filter support
+ uint32_t *_pts_to_label_offsets = nullptr;
+ uint32_t *_pts_to_label_counts = nullptr;
+ LabelT *_pts_to_labels = nullptr;
+ std::unordered_map<LabelT, std::vector<uint32_t>> _filter_to_medoid_ids;
+ bool _use_universal_label = false;
+ LabelT _universal_filter_label;
+ tsl::robin_set<uint32_t> _dummy_pts;
+ tsl::robin_set<uint32_t> _has_dummy_pts;
+ tsl::robin_map<uint32_t, uint32_t> _dummy_to_real_map;
+ tsl::robin_map<uint32_t, std::vector<uint32_t>> _real_to_dummy_map;
+ std::unordered_map<std::string, LabelT> _label_map;
+
+ private:
+ bool _use_partition = false;
+
+ std::shared_ptr<AlignedFileReader> graph_reader; // Graph file reader
+ std::string _graph_index_file; // Graph file path
+ uint64_t _graph_node_len; // Graph node length
+ uint64_t _emb_node_len; // Embedding node length
+
+ // Partition related data structures
+ uint64_t _num_partitions; // Number of partitions
+ std::vector<std::vector<uint32_t>> _graph_partitions; // Partition information
+ std::vector<uint32_t> _id2partition; // ID to partition mapping
+
+#ifdef EXEC_ENV_OLS
+ // Set to a larger value than the actual header to accommodate
+ // any additions we make to the header. This is an outer limit
+ // on how big the header can be.
+ static const int HEADER_SIZE = defaults::SECTOR_LEN;
+ char *getHeaderBytes();
+#endif
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/pq_l2_distance.h b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_l2_distance.h
new file mode 100644
index 0000000..e6fc6e4
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_l2_distance.h
@@ -0,0 +1,87 @@
+#pragma once
+#include "quantized_distance.h"
+
+namespace diskann
+{
+template <typename data_t> class PQL2Distance : public QuantizedDistance<data_t>
+{
+ public:
+ // REFACTOR TODO: We could take a file prefix here and load the
+ // PQ pivots file, so that the distance object is initialized
+ // immediately after construction. But this would not work well
+ // with our data store concept where the store is created first
+ // and data populated after.
+ // REFACTOR TODO: Ideally, we should only read the num_chunks from
+ // the pivots file. However, we read the pivots file only later, but
+ // clients can call functions like get_<xxx>_filename without calling
+ // load_pivot_data. Hence this. The TODO is whether we should check
+ // that the num_chunks from the file is the same as this one.
+
+ PQL2Distance(uint32_t num_chunks, bool use_opq = false);
+
+ virtual ~PQL2Distance() override;
+
+ virtual bool is_opq() const override;
+
+ virtual std::string get_quantized_vectors_filename(const std::string &prefix) const override;
+ virtual std::string get_pivot_data_filename(const std::string &prefix) const override;
+ virtual std::string get_rotation_matrix_suffix(const std::string &pq_pivots_filename) const override;
+
+#ifdef EXEC_ENV_OLS
+ virtual void load_pivot_data(MemoryMappedFiles &files, const std::string &pq_table_file,
+ size_t num_chunks) override;
+#else
+ virtual void load_pivot_data(const std::string &pq_table_file, size_t num_chunks) override;
+#endif
+
+ // Number of chunks in the PQ table. Depends on the compression level used.
+ // Has to be < ndim
+ virtual uint32_t get_num_chunks() const override;
+
+ // Preprocess the query by computing chunk distances from the query vector to
+ // various centroids. Since we don't want this class to do scratch management,
+ // we will take a PQScratch object which can come either from Index class or
+ // PQFlashIndex class.
+ virtual void preprocess_query(const data_t *aligned_query, uint32_t original_dim,
+ PQScratch<data_t> &pq_scratch) override;
+
+ // Distance function used for graph traversal. This function must be called
+ // after
+ // preprocess_query. The reason we do not call preprocess ourselves is because
+ // that function has to be called once per query, while this function is
+ // called at each iteration of the graph walk. NOTE: This function expects
+ // 1. the query to be preprocessed using preprocess_query()
+ // 2. the scratch object to contain the quantized vectors corresponding to ids
+ // in aligned_pq_coord_scratch. Done by calling aggregate_coords()
+ //
+ virtual void preprocessed_distance(PQScratch<data_t> &pq_scratch, const uint32_t id_count,
+ float *dists_out) override;
+
+ // Same as above, but returns the distances in a vector instead of an array.
+ // Convenience function for index.cpp.
+ virtual void preprocessed_distance(PQScratch<data_t> &pq_scratch, const uint32_t n_ids,
+ std::vector<float> &dists_out) override;
+
+ // Currently this function is required for DiskPQ. However, it too can be
+ // subsumed under preprocessed_distance if we add the appropriate scratch
+ // variables to PQScratch and initialize them in
+ // pq_flash_index.cpp::disk_iterate_to_fixed_point()
+ virtual float brute_force_distance(const float *query_vec, uint8_t *base_vec) override;
+
+ protected:
+ // assumes pre-processed query
+ virtual void prepopulate_chunkwise_distances(const float *query_vec, float *dist_vec);
+
+ // assumes no rotation is involved
+ // virtual void inflate_vector(uint8_t *base_vec, float *out_vec);
+
+ float *_tables = nullptr; // pq_tables = float array of size [256 * ndims]
+ uint64_t _ndims = 0; // ndims = true dimension of vectors
+ uint64_t _num_chunks = 0;
+ bool _is_opq = false;
+ uint32_t *_chunk_offsets = nullptr;
+ float *_centroid = nullptr;
+ float *_tables_tr = nullptr; // same as pq_tables, but col-major
+ float *_rotmat_tr = nullptr;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/pq_scratch.h b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_scratch.h
new file mode 100644
index 0000000..95f1b13
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/pq_scratch.h
@@ -0,0 +1,23 @@
+#pragma once
+#include <cstdint>
+#include "pq_common.h"
+#include "utils.h"
+
+namespace diskann
+{
+
+template <typename T> class PQScratch
+{
+ public:
+ float *aligned_pqtable_dist_scratch = nullptr; // MUST BE AT LEAST [256 * NCHUNKS]
+ float *aligned_dist_scratch = nullptr; // MUST BE AT LEAST diskann MAX_DEGREE
+ uint8_t *aligned_pq_coord_scratch = nullptr; // AT LEAST [N_CHUNKS * MAX_DEGREE]
+ float *rotated_query = nullptr;
+ float *aligned_query_float = nullptr;
+
+ PQScratch(size_t graph_degree, size_t aligned_dim);
+ void initialize(size_t dim, const T *query, const float norm = 1.0f);
+ virtual ~PQScratch();
+};
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/program_options_utils.hpp b/packages/leann-backend-diskann/third_party/DiskANN/include/program_options_utils.hpp
new file mode 100644
index 0000000..2be6059
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/program_options_utils.hpp
@@ -0,0 +1,81 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <string.h>
+
+namespace program_options_utils
+{
+const std::string make_program_description(const char *executable_name, const char *description)
+{
+ return std::string("\n")
+ .append(description)
+ .append("\n\n")
+ .append("Usage: ")
+ .append(executable_name)
+ .append(" [OPTIONS]");
+}
+
+// Required parameters
+const char *DATA_TYPE_DESCRIPTION = "data type, one of {int8, uint8, float} - float is single precision (32 bit)";
+const char *DISTANCE_FUNCTION_DESCRIPTION =
+ "distance function {l2, mips, fast_l2, cosine}. 'fast l2' and 'mips' only support data_type float";
+const char *INDEX_PATH_PREFIX_DESCRIPTION = "Path prefix to the index, e.g. '/mnt/data/my_ann_index'";
+const char *RESULT_PATH_DESCRIPTION =
+ "Path prefix for saving results of the queries, e.g. '/mnt/data/query_file_X.bin'";
+const char *QUERY_FILE_DESCRIPTION = "Query file in binary format, e.g. '/mnt/data/query_file_X.bin'";
+const char *NUMBER_OF_RESULTS_DESCRIPTION = "Number of neighbors to be returned (K in the DiskANN white paper)";
+const char *SEARCH_LIST_DESCRIPTION =
+ "Size of search list to use. This value is the number of neighbor/distance pairs to keep in memory at the same "
+ "time while performing a query. This can also be described as the size of the working set at query time. This "
+ "must be greater than or equal to the number of results/neighbors to return (K in the white paper). Corresponds "
+ "to L in the DiskANN white paper.";
+const char *INPUT_DATA_PATH = "Input data file in bin format. This is the file you want to build the index over. "
+ "File format: Shape of the vector followed by the vector of embeddings as binary data.";
+
+// Optional parameters
+const char *FILTER_LABEL_DESCRIPTION =
+ "Filter to use when running a query. 'filter_label' and 'query_filters_file' are mutually exclusive.";
+const char *FILTERS_FILE_DESCRIPTION =
+ "Filter file for Queries for Filtered Search. File format is text with one filter per line. File must "
+ "have exactly one filter OR the same number of filters as there are queries in the 'query_file'.";
+const char *LABEL_TYPE_DESCRIPTION =
+ "Storage type of Labels {uint/uint32, ushort/uint16}, default value is uint which will consume memory 4 bytes per "
+ "filter. 'uint' is an alias for 'uint32' and 'ushort' is an alias for 'uint16'.";
+const char *GROUND_TRUTH_FILE_DESCRIPTION =
+ "ground truth file for the queryset"; // what's the format, what's the requirements? does it need to include an
+ // entry for every item or just a small subset? I have so many questions about
+ // this file
+const char *NUMBER_THREADS_DESCRIPTION = "Number of threads used for building index. Defaults to number of logical "
+ "processor cores on your this machine returned by omp_get_num_procs()";
+const char *FAIL_IF_RECALL_BELOW =
+ "Value between 0 (inclusive) and 100 (exclusive) indicating the recall tolerance percentage threshold before "
+ "program fails with a non-zero exit code. The default value of 0 means that the program will complete "
+ "successfully with any recall value. A non-zero value indicates the floor for acceptable recall values. If the "
+ "calculated recall value is below this threshold then the program will write out the results but return a non-zero "
+ "exit code as a signal that the recall was not acceptable."; // does it continue running or die immediately? Will I
+ // still get my results even if the return code is -1?
+
+const char *NUMBER_OF_NODES_TO_CACHE = "Number of BFS nodes around medoid(s) to cache. Default value: 0";
+const char *BEAMWIDTH = "Beamwidth for search. Set 0 to optimize internally. Default value: 2";
+const char *MAX_BUILD_DEGREE = "Maximum graph degree";
+const char *GRAPH_BUILD_COMPLEXITY =
+ "Size of the search working set during build time. This is the numer of neighbor/distance pairs to keep in memory "
+ "while building the index. Higher value results in a higher quality graph but it will take more time to build the "
+ "graph.";
+const char *GRAPH_BUILD_ALPHA = "Alpha controls density and diameter of graph, set 1 for sparse graph, 1.2 or 1.4 for "
+ "denser graphs with lower diameter";
+const char *BUIlD_GRAPH_PQ_BYTES = "Number of PQ bytes to build the index; 0 for full precision build";
+const char *USE_OPQ = "Use Optimized Product Quantization (OPQ).";
+const char *LABEL_FILE = "Input label file in txt format for Filtered Index build. The file should contain comma "
+ "separated filters for each node with each line corresponding to a graph node";
+const char *UNIVERSAL_LABEL =
+ "Universal label, Use only in conjunction with label file for filtered index build. If a "
+ "graph node has all the labels against it, we can assign a special universal filter to the "
+ "point instead of comma separated filters for that point. The universal label should be assigned to nodes "
+ "in the labels file instead of listing all labels for a node. DiskANN will not automatically assign a "
+ "universal label to a node.";
+const char *FILTERED_LBUILD = "Build complexity for filtered points, higher value results in better graphs";
+
+} // namespace program_options_utils
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/proto_embedding.h b/packages/leann-backend-diskann/third_party/DiskANN/include/proto_embedding.h
new file mode 100644
index 0000000..f17e225
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/proto_embedding.h
@@ -0,0 +1,9 @@
+#pragma once
+
+#include "embedding.pb.h"
+
+// This header ensures that the protobuf files are included correctly
+// and provides a namespace alias for convenience
+namespace diskann {
+ namespace proto = protoembedding;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/quantized_distance.h b/packages/leann-backend-diskann/third_party/DiskANN/include/quantized_distance.h
new file mode 100644
index 0000000..cc4aea9
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/quantized_distance.h
@@ -0,0 +1,56 @@
+#pragma once
+#include <memory>
+#include <string>
+#include <vector>
+#include "abstract_scratch.h"
+
+namespace diskann
+{
+template <typename data_t> class PQScratch;
+
+template <typename data_t> class QuantizedDistance
+{
+ public:
+ QuantizedDistance() = default;
+ QuantizedDistance(const QuantizedDistance &) = delete;
+ QuantizedDistance &operator=(const QuantizedDistance &) = delete;
+ virtual ~QuantizedDistance() = default;
+
+ virtual bool is_opq() const = 0;
+ virtual std::string get_quantized_vectors_filename(const std::string &prefix) const = 0;
+ virtual std::string get_pivot_data_filename(const std::string &prefix) const = 0;
+ virtual std::string get_rotation_matrix_suffix(const std::string &pq_pivots_filename) const = 0;
+
+ // Loading the PQ centroid table need not be part of the abstract class.
+ // However, we want to indicate that this function will change once we have a
+ // file reader hierarchy, so leave it here as-is.
+#ifdef EXEC_ENV_OLS
+ virtual void load_pivot_data(MemoryMappedFiles &files, const std::String &pq_table_file, size_t num_chunks) = 0;
+#else
+ virtual void load_pivot_data(const std::string &pq_table_file, size_t num_chunks) = 0;
+#endif
+
+ // Number of chunks in the PQ table. Depends on the compression level used.
+ // Has to be < ndim
+ virtual uint32_t get_num_chunks() const = 0;
+
+ // Preprocess the query by computing chunk distances from the query vector to
+ // various centroids. Since we don't want this class to do scratch management,
+ // we will take a PQScratch object which can come either from Index class or
+ // PQFlashIndex class.
+ virtual void preprocess_query(const data_t *query_vec, uint32_t query_dim, PQScratch<data_t> &pq_scratch) = 0;
+
+ // Workhorse
+ // This function must be called after preprocess_query
+ virtual void preprocessed_distance(PQScratch<data_t> &pq_scratch, const uint32_t id_count, float *dists_out) = 0;
+
+ // Same as above, but convenience function for index.cpp.
+ virtual void preprocessed_distance(PQScratch<data_t> &pq_scratch, const uint32_t n_ids,
+ std::vector<float> &dists_out) = 0;
+
+ // Currently this function is required for DiskPQ. However, it too can be subsumed
+ // under preprocessed_distance if we add the appropriate scratch variables to
+ // PQScratch and initialize them in pq_flash_index.cpp::disk_iterate_to_fixed_point()
+ virtual float brute_force_distance(const float *query_vec, uint8_t *base_vec) = 0;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/common.h b/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/common.h
new file mode 100644
index 0000000..b833963
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/common.h
@@ -0,0 +1,18 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cpprest/base_uri.h>
+#include <restapi/search_wrapper.h>
+
+namespace diskann
+{
+// Constants
+static const std::string VECTOR_KEY = "query", K_KEY = "k", INDICES_KEY = "indices", DISTANCES_KEY = "distances",
+ TAGS_KEY = "tags", QUERY_ID_KEY = "query_id", ERROR_MESSAGE_KEY = "error", L_KEY = "Ls",
+ TIME_TAKEN_KEY = "time_taken_in_us", PARTITION_KEY = "partition",
+ UNKNOWN_ERROR = "unknown_error";
+const unsigned int DEFAULT_L = 100;
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/search_wrapper.h b/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/search_wrapper.h
new file mode 100644
index 0000000..ebd067d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/search_wrapper.h
@@ -0,0 +1,140 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include <stdexcept>
+
+#include <index.h>
+#include <pq_flash_index.h>
+
+namespace diskann
+{
+class SearchResult
+{
+ public:
+ SearchResult(unsigned int K, unsigned int elapsed_time_in_ms, const unsigned *const indices,
+ const float *const distances, const std::string *const tags = nullptr,
+ const unsigned *const partitions = nullptr);
+
+ const std::vector<unsigned int> &get_indices() const
+ {
+ return _indices;
+ }
+ const std::vector<float> &get_distances() const
+ {
+ return _distances;
+ }
+ bool tags_enabled() const
+ {
+ return _tags_enabled;
+ }
+ const std::vector<std::string> &get_tags() const
+ {
+ return _tags;
+ }
+ bool partitions_enabled() const
+ {
+ return _partitions_enabled;
+ }
+ const std::vector<unsigned> &get_partitions() const
+ {
+ return _partitions;
+ }
+ unsigned get_time() const
+ {
+ return _search_time_in_ms;
+ }
+
+ private:
+ unsigned int _K;
+ unsigned int _search_time_in_ms;
+ std::vector<unsigned int> _indices;
+ std::vector<float> _distances;
+
+ bool _tags_enabled;
+ std::vector<std::string> _tags;
+
+ bool _partitions_enabled;
+ std::vector<unsigned> _partitions;
+};
+
+class SearchNotImplementedException : public std::logic_error
+{
+ private:
+ std::string _errormsg;
+
+ public:
+ SearchNotImplementedException(const char *type) : std::logic_error("Not Implemented")
+ {
+ _errormsg = "Search with data type ";
+ _errormsg += std::string(type);
+ _errormsg += " not implemented : ";
+ _errormsg += __FUNCTION__;
+ }
+
+ virtual const char *what() const throw()
+ {
+ return _errormsg.c_str();
+ }
+};
+
+class BaseSearch
+{
+ public:
+ BaseSearch(const std::string &tagsFile = nullptr);
+ virtual SearchResult search(const float *query, const unsigned int dimensions, const unsigned int K,
+ const unsigned int Ls)
+ {
+ throw SearchNotImplementedException("float");
+ }
+ virtual SearchResult search(const int8_t *query, const unsigned int dimensions, const unsigned int K,
+ const unsigned int Ls)
+ {
+ throw SearchNotImplementedException("int8_t");
+ }
+
+ virtual SearchResult search(const uint8_t *query, const unsigned int dimensions, const unsigned int K,
+ const unsigned int Ls)
+ {
+ throw SearchNotImplementedException("uint8_t");
+ }
+
+ void lookup_tags(const unsigned K, const unsigned *indices, std::string *ret_tags);
+
+ protected:
+ bool _tags_enabled;
+ std::vector<std::string> _tags_str;
+};
+
+template <typename T> class InMemorySearch : public BaseSearch
+{
+ public:
+ InMemorySearch(const std::string &baseFile, const std::string &indexFile, const std::string &tagsFile, Metric m,
+ uint32_t num_threads, uint32_t search_l);
+ virtual ~InMemorySearch();
+
+ SearchResult search(const T *query, const unsigned int dimensions, const unsigned int K, const unsigned int Ls);
+
+ private:
+ unsigned int _dimensions, _numPoints;
+ std::unique_ptr<diskann::Index<T>> _index;
+};
+
+template <typename T> class PQFlashSearch : public BaseSearch
+{
+ public:
+ PQFlashSearch(const std::string &indexPrefix, const unsigned num_nodes_to_cache, const unsigned num_threads,
+ const std::string &tagsFile, Metric m);
+ virtual ~PQFlashSearch();
+
+ SearchResult search(const T *query, const unsigned int dimensions, const unsigned int K, const unsigned int Ls);
+
+ private:
+ unsigned int _dimensions, _numPoints;
+ std::unique_ptr<diskann::PQFlashIndex<T>> _index;
+ std::shared_ptr<AlignedFileReader> reader;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/server.h b/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/server.h
new file mode 100644
index 0000000..1d75847
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/restapi/server.h
@@ -0,0 +1,45 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <restapi/common.h>
+#include <cpprest/http_listener.h>
+
+namespace diskann
+{
+class Server
+{
+ public:
+ Server(web::uri &url, std::vector<std::unique_ptr<diskann::BaseSearch>> &multi_searcher,
+ const std::string &typestring);
+ virtual ~Server();
+
+ pplx::task<void> open();
+ pplx::task<void> close();
+
+ protected:
+ template <class T> void handle_post(web::http::http_request message);
+
+ template <typename T>
+ web::json::value toJsonArray(const std::vector<T> &v, std::function<web::json::value(const T &)> valConverter);
+ web::json::value prepareResponse(const int64_t &queryId, const int k);
+
+ template <class T>
+ void parseJson(const utility::string_t &body, unsigned int &k, int64_t &queryId, T *&queryVector,
+ unsigned int &dimensions, unsigned &Ls);
+
+ web::json::value idsToJsonArray(const diskann::SearchResult &result);
+ web::json::value distancesToJsonArray(const diskann::SearchResult &result);
+ web::json::value tagsToJsonArray(const diskann::SearchResult &result);
+ web::json::value partitionsToJsonArray(const diskann::SearchResult &result);
+
+ SearchResult aggregate_results(const unsigned K, const std::vector<diskann::SearchResult> &results);
+
+ private:
+ bool _isDebug;
+ std::unique_ptr<web::http::experimental::listener::http_listener> _listener;
+ const bool _multi_search;
+ std::vector<std::unique_ptr<diskann::BaseSearch>> _multi_searcher;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/scratch.h b/packages/leann-backend-diskann/third_party/DiskANN/include/scratch.h
new file mode 100644
index 0000000..2f43e33
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/scratch.h
@@ -0,0 +1,216 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <vector>
+
+#include "boost_dynamic_bitset_fwd.h"
+// #include "boost/dynamic_bitset.hpp"
+#include "tsl/robin_set.h"
+#include "tsl/robin_map.h"
+#include "tsl/sparse_map.h"
+
+#include "aligned_file_reader.h"
+#include "abstract_scratch.h"
+#include "neighbor.h"
+#include "defaults.h"
+#include "concurrent_queue.h"
+
+namespace diskann
+{
+template <typename T> class PQScratch;
+
+//
+// AbstractScratch space for in-memory index based search
+//
+template <typename T> class InMemQueryScratch : public AbstractScratch<T>
+{
+ public:
+ ~InMemQueryScratch();
+ InMemQueryScratch(uint32_t search_l, uint32_t indexing_l, uint32_t r, uint32_t maxc, size_t dim, size_t aligned_dim,
+ size_t alignment_factor, bool init_pq_scratch = false);
+ void resize_for_new_L(uint32_t new_search_l);
+ void clear();
+
+ inline uint32_t get_L()
+ {
+ return _L;
+ }
+ inline uint32_t get_R()
+ {
+ return _R;
+ }
+ inline uint32_t get_maxc()
+ {
+ return _maxc;
+ }
+ inline T *aligned_query()
+ {
+ return this->_aligned_query_T;
+ }
+ inline PQScratch<T> *pq_scratch()
+ {
+ return this->_pq_scratch;
+ }
+ inline std::vector<Neighbor> &pool()
+ {
+ return _pool;
+ }
+ inline NeighborPriorityQueue &best_l_nodes()
+ {
+ return _best_l_nodes;
+ }
+ inline std::vector<float> &occlude_factor()
+ {
+ return _occlude_factor;
+ }
+ inline tsl::robin_set<uint32_t> &inserted_into_pool_rs()
+ {
+ return _inserted_into_pool_rs;
+ }
+ inline boost::dynamic_bitset<> &inserted_into_pool_bs()
+ {
+ return *_inserted_into_pool_bs;
+ }
+ inline std::vector<uint32_t> &id_scratch()
+ {
+ return _id_scratch;
+ }
+ inline std::vector<float> &dist_scratch()
+ {
+ return _dist_scratch;
+ }
+ inline tsl::robin_set<uint32_t> &expanded_nodes_set()
+ {
+ return _expanded_nodes_set;
+ }
+ inline std::vector<Neighbor> &expanded_nodes_vec()
+ {
+ return _expanded_nghrs_vec;
+ }
+ inline std::vector<uint32_t> &occlude_list_output()
+ {
+ return _occlude_list_output;
+ }
+
+ private:
+ uint32_t _L;
+ uint32_t _R;
+ uint32_t _maxc;
+
+ // _pool stores all neighbors explored from best_L_nodes.
+ // Usually around L+R, but could be higher.
+ // Initialized to 3L+R for some slack, expands as needed.
+ std::vector<Neighbor> _pool;
+
+ // _best_l_nodes is reserved for storing best L entries
+ // Underlying storage is L+1 to support inserts
+ NeighborPriorityQueue _best_l_nodes;
+
+ // _occlude_factor.size() >= pool.size() in occlude_list function
+ // _pool is clipped to maxc in occlude_list before affecting _occlude_factor
+ // _occlude_factor is initialized to maxc size
+ std::vector<float> _occlude_factor;
+
+ // Capacity initialized to 20L
+ tsl::robin_set<uint32_t> _inserted_into_pool_rs;
+
+ // Use a pointer here to allow for forward declaration of dynamic_bitset
+ // in public headers to avoid making boost a dependency for clients
+ // of DiskANN.
+ boost::dynamic_bitset<> *_inserted_into_pool_bs;
+
+ // _id_scratch.size() must be > R*GRAPH_SLACK_FACTOR for iterate_to_fp
+ std::vector<uint32_t> _id_scratch;
+
+ // _dist_scratch must be > R*GRAPH_SLACK_FACTOR for iterate_to_fp
+ // _dist_scratch should be at least the size of id_scratch
+ std::vector<float> _dist_scratch;
+
+ // Buffers used in process delete, capacity increases as needed
+ tsl::robin_set<uint32_t> _expanded_nodes_set;
+ std::vector<Neighbor> _expanded_nghrs_vec;
+ std::vector<uint32_t> _occlude_list_output;
+};
+
+//
+// AbstractScratch space for SSD index based search
+//
+
+template <typename T> class SSDQueryScratch : public AbstractScratch<T>
+{
+ public:
+ T *coord_scratch = nullptr; // MUST BE AT LEAST [sizeof(T) * data_dim]
+
+ char *sector_scratch = nullptr; // MUST BE AT LEAST [MAX_N_SECTOR_READS * SECTOR_LEN]
+ size_t sector_idx = 0; // index of next [SECTOR_LEN] scratch to use
+
+ tsl::robin_set<size_t> visited;
+ NeighborPriorityQueue retset;
+ std::vector<Neighbor> full_retset;
+
+ SSDQueryScratch(size_t aligned_dim, size_t visited_reserve);
+ ~SSDQueryScratch();
+
+ void reset();
+};
+
+template <typename T> class SSDThreadData
+{
+ public:
+ SSDQueryScratch<T> scratch;
+ IOContext ctx;
+
+ SSDThreadData(size_t aligned_dim, size_t visited_reserve);
+ void clear();
+};
+
+//
+// Class to avoid the hassle of pushing and popping the query scratch.
+//
+template <typename T> class ScratchStoreManager
+{
+ public:
+ ScratchStoreManager(ConcurrentQueue<T *> &query_scratch) : _scratch_pool(query_scratch)
+ {
+ _scratch = query_scratch.pop();
+ while (_scratch == nullptr)
+ {
+ query_scratch.wait_for_push_notify();
+ _scratch = query_scratch.pop();
+ }
+ }
+ T *scratch_space()
+ {
+ return _scratch;
+ }
+
+ ~ScratchStoreManager()
+ {
+ _scratch->clear();
+ _scratch_pool.push(_scratch);
+ _scratch_pool.push_notify_all();
+ }
+
+ void destroy()
+ {
+ while (!_scratch_pool.empty())
+ {
+ auto scratch = _scratch_pool.pop();
+ while (scratch == nullptr)
+ {
+ _scratch_pool.wait_for_push_notify();
+ scratch = _scratch_pool.pop();
+ }
+ delete scratch;
+ }
+ }
+
+ private:
+ T *_scratch;
+ ConcurrentQueue<T *> &_scratch_pool;
+ ScratchStoreManager(const ScratchStoreManager<T> &);
+ ScratchStoreManager &operator=(const ScratchStoreManager<T> &);
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/simd_utils.h b/packages/leann-backend-diskann/third_party/DiskANN/include/simd_utils.h
new file mode 100644
index 0000000..4b07369
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/simd_utils.h
@@ -0,0 +1,106 @@
+#pragma once
+
+#ifdef _WINDOWS
+#include <immintrin.h>
+#include <smmintrin.h>
+#include <tmmintrin.h>
+#include <intrin.h>
+#else
+#include <immintrin.h>
+#endif
+
+namespace diskann
+{
+static inline __m256 _mm256_mul_epi8(__m256i X)
+{
+ __m256i zero = _mm256_setzero_si256();
+
+ __m256i sign_x = _mm256_cmpgt_epi8(zero, X);
+
+ __m256i xlo = _mm256_unpacklo_epi8(X, sign_x);
+ __m256i xhi = _mm256_unpackhi_epi8(X, sign_x);
+
+ return _mm256_cvtepi32_ps(_mm256_add_epi32(_mm256_madd_epi16(xlo, xlo), _mm256_madd_epi16(xhi, xhi)));
+}
+
+static inline __m128 _mm_mulhi_epi8(__m128i X)
+{
+ __m128i zero = _mm_setzero_si128();
+ __m128i sign_x = _mm_cmplt_epi8(X, zero);
+ __m128i xhi = _mm_unpackhi_epi8(X, sign_x);
+
+ return _mm_cvtepi32_ps(_mm_add_epi32(_mm_setzero_si128(), _mm_madd_epi16(xhi, xhi)));
+}
+
+static inline __m128 _mm_mulhi_epi8_shift32(__m128i X)
+{
+ __m128i zero = _mm_setzero_si128();
+ X = _mm_srli_epi64(X, 32);
+ __m128i sign_x = _mm_cmplt_epi8(X, zero);
+ __m128i xhi = _mm_unpackhi_epi8(X, sign_x);
+
+ return _mm_cvtepi32_ps(_mm_add_epi32(_mm_setzero_si128(), _mm_madd_epi16(xhi, xhi)));
+}
+static inline __m128 _mm_mul_epi8(__m128i X, __m128i Y)
+{
+ __m128i zero = _mm_setzero_si128();
+
+ __m128i sign_x = _mm_cmplt_epi8(X, zero);
+ __m128i sign_y = _mm_cmplt_epi8(Y, zero);
+
+ __m128i xlo = _mm_unpacklo_epi8(X, sign_x);
+ __m128i xhi = _mm_unpackhi_epi8(X, sign_x);
+ __m128i ylo = _mm_unpacklo_epi8(Y, sign_y);
+ __m128i yhi = _mm_unpackhi_epi8(Y, sign_y);
+
+ return _mm_cvtepi32_ps(_mm_add_epi32(_mm_madd_epi16(xlo, ylo), _mm_madd_epi16(xhi, yhi)));
+}
+static inline __m128 _mm_mul_epi8(__m128i X)
+{
+ __m128i zero = _mm_setzero_si128();
+ __m128i sign_x = _mm_cmplt_epi8(X, zero);
+ __m128i xlo = _mm_unpacklo_epi8(X, sign_x);
+ __m128i xhi = _mm_unpackhi_epi8(X, sign_x);
+
+ return _mm_cvtepi32_ps(_mm_add_epi32(_mm_madd_epi16(xlo, xlo), _mm_madd_epi16(xhi, xhi)));
+}
+
+static inline __m128 _mm_mul32_pi8(__m128i X, __m128i Y)
+{
+ __m128i xlo = _mm_cvtepi8_epi16(X), ylo = _mm_cvtepi8_epi16(Y);
+ return _mm_cvtepi32_ps(_mm_unpacklo_epi32(_mm_madd_epi16(xlo, ylo), _mm_setzero_si128()));
+}
+
+static inline __m256 _mm256_mul_epi8(__m256i X, __m256i Y)
+{
+ __m256i zero = _mm256_setzero_si256();
+
+ __m256i sign_x = _mm256_cmpgt_epi8(zero, X);
+ __m256i sign_y = _mm256_cmpgt_epi8(zero, Y);
+
+ __m256i xlo = _mm256_unpacklo_epi8(X, sign_x);
+ __m256i xhi = _mm256_unpackhi_epi8(X, sign_x);
+ __m256i ylo = _mm256_unpacklo_epi8(Y, sign_y);
+ __m256i yhi = _mm256_unpackhi_epi8(Y, sign_y);
+
+ return _mm256_cvtepi32_ps(_mm256_add_epi32(_mm256_madd_epi16(xlo, ylo), _mm256_madd_epi16(xhi, yhi)));
+}
+
+static inline __m256 _mm256_mul32_pi8(__m128i X, __m128i Y)
+{
+ __m256i xlo = _mm256_cvtepi8_epi16(X), ylo = _mm256_cvtepi8_epi16(Y);
+ return _mm256_blend_ps(_mm256_cvtepi32_ps(_mm256_madd_epi16(xlo, ylo)), _mm256_setzero_ps(), 252);
+}
+
+static inline float _mm256_reduce_add_ps(__m256 x)
+{
+ /* ( x3+x7, x2+x6, x1+x5, x0+x4 ) */
+ const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x));
+ /* ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 ) */
+ const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128));
+ /* ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 ) */
+ const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55));
+ /* Conversion to float is a no-op on x86-64 */
+ return _mm_cvtss_f32(x32);
+}
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tag_uint128.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tag_uint128.h
new file mode 100644
index 0000000..642de31
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tag_uint128.h
@@ -0,0 +1,68 @@
+#pragma once
+#include <cstdint>
+#include <type_traits>
+
+namespace diskann
+{
+#pragma pack(push, 1)
+
+struct tag_uint128
+{
+ std::uint64_t _data1 = 0;
+ std::uint64_t _data2 = 0;
+
+ bool operator==(const tag_uint128 &other) const
+ {
+ return _data1 == other._data1 && _data2 == other._data2;
+ }
+
+ bool operator==(std::uint64_t other) const
+ {
+ return _data1 == other && _data2 == 0;
+ }
+
+ tag_uint128 &operator=(const tag_uint128 &other)
+ {
+ _data1 = other._data1;
+ _data2 = other._data2;
+
+ return *this;
+ }
+
+ tag_uint128 &operator=(std::uint64_t other)
+ {
+ _data1 = other;
+ _data2 = 0;
+
+ return *this;
+ }
+};
+
+#pragma pack(pop)
+} // namespace diskann
+
+namespace std
+{
+// Hash 128 input bits down to 64 bits of output.
+// This is intended to be a reasonably good hash function.
+inline std::uint64_t Hash128to64(const std::uint64_t &low, const std::uint64_t &high)
+{
+ // Murmur-inspired hashing.
+ const std::uint64_t kMul = 0x9ddfea08eb382d69ULL;
+ std::uint64_t a = (low ^ high) * kMul;
+ a ^= (a >> 47);
+ std::uint64_t b = (high ^ a) * kMul;
+ b ^= (b >> 47);
+ b *= kMul;
+ return b;
+}
+
+template <> struct hash<diskann::tag_uint128>
+{
+ size_t operator()(const diskann::tag_uint128 &key) const noexcept
+ {
+ return Hash128to64(key._data1, key._data2); // map -0 to 0
+ }
+};
+
+} // namespace std
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/timer.h b/packages/leann-backend-diskann/third_party/DiskANN/include/timer.h
new file mode 100644
index 0000000..325edf3
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/timer.h
@@ -0,0 +1,40 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+#pragma once
+
+#include <chrono>
+
+namespace diskann
+{
+class Timer
+{
+ typedef std::chrono::high_resolution_clock _clock;
+ std::chrono::time_point<_clock> check_point;
+
+ public:
+ Timer() : check_point(_clock::now())
+ {
+ }
+
+ void reset()
+ {
+ check_point = _clock::now();
+ }
+
+ long long elapsed() const
+ {
+ return std::chrono::duration_cast<std::chrono::microseconds>(_clock::now() - check_point).count();
+ }
+
+ float elapsed_seconds() const
+ {
+ return (float)elapsed() / 1000000.0f;
+ }
+
+ std::string elapsed_seconds_for_step(const std::string &step) const
+ {
+ return std::string("Time for ") + step + std::string(": ") + std::to_string(elapsed_seconds()) +
+ std::string(" seconds");
+ }
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/.clang-format b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/.clang-format
new file mode 100644
index 0000000..9d15924
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/.clang-format
@@ -0,0 +1,2 @@
+DisableFormat: true
+SortIncludes: false
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_growth_policy.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_growth_policy.h
new file mode 100644
index 0000000..6bfa9e5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_growth_policy.h
@@ -0,0 +1,330 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Tessil
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_ROBIN_GROWTH_POLICY_H
+#define TSL_ROBIN_GROWTH_POLICY_H
+
+
+#include <algorithm>
+#include <array>
+#include <climits>
+#include <cmath>
+#include <cstddef>
+#include <iterator>
+#include <limits>
+#include <ratio>
+#include <stdexcept>
+
+
+#ifndef tsl_assert
+# ifdef TSL_DEBUG
+# define tsl_assert(expr) assert(expr)
+# else
+# define tsl_assert(expr) (static_cast<void>(0))
+# endif
+#endif
+
+
+/**
+ * If exceptions are enabled, throw the exception passed in parameter, otherwise call std::terminate.
+ */
+#ifndef TSL_THROW_OR_TERMINATE
+# if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (defined (_MSC_VER) && defined (_CPPUNWIND))) && !defined(TSL_NO_EXCEPTIONS)
+# define TSL_THROW_OR_TERMINATE(ex, msg) throw ex(msg)
+# else
+# ifdef NDEBUG
+# define TSL_THROW_OR_TERMINATE(ex, msg) std::terminate()
+# else
+# include <cstdio>
+# define TSL_THROW_OR_TERMINATE(ex, msg) do { std::fprintf(stderr, msg); std::terminate(); } while(0)
+# endif
+# endif
+#endif
+
+
+#ifndef TSL_LIKELY
+# if defined(__GNUC__) || defined(__clang__)
+# define TSL_LIKELY(exp) (__builtin_expect(!!(exp), true))
+# else
+# define TSL_LIKELY(exp) (exp)
+# endif
+#endif
+
+
+namespace tsl {
+namespace rh {
+
+/**
+ * Grow the hash table by a factor of GrowthFactor keeping the bucket count to a power of two. It allows
+ * the table to use a mask operation instead of a modulo operation to map a hash to a bucket.
+ *
+ * GrowthFactor must be a power of two >= 2.
+ */
+template<std::size_t GrowthFactor>
+class power_of_two_growth_policy {
+public:
+ /**
+ * Called on the hash table creation and on rehash. The number of buckets for the table is passed in parameter.
+ * This number is a minimum, the policy may update this value with a higher value if needed (but not lower).
+ *
+ * If 0 is given, min_bucket_count_in_out must still be 0 after the policy creation and
+ * bucket_for_hash must always return 0 in this case.
+ */
+ explicit power_of_two_growth_policy(std::size_t& min_bucket_count_in_out) {
+ if(min_bucket_count_in_out > max_bucket_count()) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ if(min_bucket_count_in_out > 0) {
+ min_bucket_count_in_out = round_up_to_power_of_two(min_bucket_count_in_out);
+ m_mask = min_bucket_count_in_out - 1;
+ }
+ else {
+ m_mask = 0;
+ }
+ }
+
+ /**
+ * Return the bucket [0, bucket_count()) to which the hash belongs.
+ * If bucket_count() is 0, it must always return 0.
+ */
+ std::size_t bucket_for_hash(std::size_t hash) const noexcept {
+ return hash & m_mask;
+ }
+
+ /**
+ * Return the number of buckets that should be used on next growth.
+ */
+ std::size_t next_bucket_count() const {
+ if((m_mask + 1) > max_bucket_count() / GrowthFactor) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ return (m_mask + 1) * GrowthFactor;
+ }
+
+ /**
+ * Return the maximum number of buckets supported by the policy.
+ */
+ std::size_t max_bucket_count() const {
+ // Largest power of two.
+ return ((std::numeric_limits<std::size_t>::max)() / 2) + 1;
+ }
+
+ /**
+ * Reset the growth policy as if it was created with a bucket count of 0.
+ * After a clear, the policy must always return 0 when bucket_for_hash is called.
+ */
+ void clear() noexcept {
+ m_mask = 0;
+ }
+
+private:
+ static std::size_t round_up_to_power_of_two(std::size_t value) {
+ if(is_power_of_two(value)) {
+ return value;
+ }
+
+ if(value == 0) {
+ return 1;
+ }
+
+ --value;
+ for(std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) {
+ value |= value >> i;
+ }
+
+ return value + 1;
+ }
+
+ static constexpr bool is_power_of_two(std::size_t value) {
+ return value != 0 && (value & (value - 1)) == 0;
+ }
+
+protected:
+ static_assert(is_power_of_two(GrowthFactor) && GrowthFactor >= 2, "GrowthFactor must be a power of two >= 2.");
+
+ std::size_t m_mask;
+};
+
+
+/**
+ * Grow the hash table by GrowthFactor::num / GrowthFactor::den and use a modulo to map a hash
+ * to a bucket. Slower but it can be useful if you want a slower growth.
+ */
+template<class GrowthFactor = std::ratio<3, 2>>
+class mod_growth_policy {
+public:
+ explicit mod_growth_policy(std::size_t& min_bucket_count_in_out) {
+ if(min_bucket_count_in_out > max_bucket_count()) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ if(min_bucket_count_in_out > 0) {
+ m_mod = min_bucket_count_in_out;
+ }
+ else {
+ m_mod = 1;
+ }
+ }
+
+ std::size_t bucket_for_hash(std::size_t hash) const noexcept {
+ return hash % m_mod;
+ }
+
+ std::size_t next_bucket_count() const {
+ if(m_mod == max_bucket_count()) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ const double next_bucket_count = std::ceil(double(m_mod) * REHASH_SIZE_MULTIPLICATION_FACTOR);
+ if(!std::isnormal(next_bucket_count)) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ if(next_bucket_count > double(max_bucket_count())) {
+ return max_bucket_count();
+ }
+ else {
+ return std::size_t(next_bucket_count);
+ }
+ }
+
+ std::size_t max_bucket_count() const {
+ return MAX_BUCKET_COUNT;
+ }
+
+ void clear() noexcept {
+ m_mod = 1;
+ }
+
+private:
+ static constexpr double REHASH_SIZE_MULTIPLICATION_FACTOR = 1.0 * GrowthFactor::num / GrowthFactor::den;
+ static const std::size_t MAX_BUCKET_COUNT =
+ std::size_t(double(
+ (std::numeric_limits<std::size_t>::max)() / REHASH_SIZE_MULTIPLICATION_FACTOR
+ ));
+
+ static_assert(REHASH_SIZE_MULTIPLICATION_FACTOR >= 1.1, "Growth factor should be >= 1.1.");
+
+ std::size_t m_mod;
+};
+
+
+
+namespace detail {
+
+static constexpr const std::array<std::size_t, 40> PRIMES = {{
+ 1ul, 5ul, 17ul, 29ul, 37ul, 53ul, 67ul, 79ul, 97ul, 131ul, 193ul, 257ul, 389ul, 521ul, 769ul, 1031ul,
+ 1543ul, 2053ul, 3079ul, 6151ul, 12289ul, 24593ul, 49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
+ 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul, 201326611ul,
+ 402653189ul, 805306457ul, 1610612741ul, 3221225473ul, 4294967291ul
+}};
+
+template<unsigned int IPrime>
+static constexpr std::size_t mod(std::size_t hash) { return hash % PRIMES[IPrime]; }
+
+// MOD_PRIME[iprime](hash) returns hash % PRIMES[iprime]. This table allows for faster modulo as the
+// compiler can optimize the modulo code better with a constant known at the compilation.
+static constexpr const std::array<std::size_t(*)(std::size_t), 40> MOD_PRIME = {{
+ &mod<0>, &mod<1>, &mod<2>, &mod<3>, &mod<4>, &mod<5>, &mod<6>, &mod<7>, &mod<8>, &mod<9>, &mod<10>,
+ &mod<11>, &mod<12>, &mod<13>, &mod<14>, &mod<15>, &mod<16>, &mod<17>, &mod<18>, &mod<19>, &mod<20>,
+ &mod<21>, &mod<22>, &mod<23>, &mod<24>, &mod<25>, &mod<26>, &mod<27>, &mod<28>, &mod<29>, &mod<30>,
+ &mod<31>, &mod<32>, &mod<33>, &mod<34>, &mod<35>, &mod<36>, &mod<37> , &mod<38>, &mod<39>
+}};
+
+}
+
+/**
+ * Grow the hash table by using prime numbers as bucket count. Slower than tsl::rh::power_of_two_growth_policy in
+ * general but will probably distribute the values around better in the buckets with a poor hash function.
+ *
+ * To allow the compiler to optimize the modulo operation, a lookup table is used with constant primes numbers.
+ *
+ * With a switch the code would look like:
+ * \code
+ * switch(iprime) { // iprime is the current prime of the hash table
+ * case 0: hash % 5ul;
+ * break;
+ * case 1: hash % 17ul;
+ * break;
+ * case 2: hash % 29ul;
+ * break;
+ * ...
+ * }
+ * \endcode
+ *
+ * Due to the constant variable in the modulo the compiler is able to optimize the operation
+ * by a series of multiplications, substractions and shifts.
+ *
+ * The 'hash % 5' could become something like 'hash - (hash * 0xCCCCCCCD) >> 34) * 5' in a 64 bits environement.
+ */
+class prime_growth_policy {
+public:
+ explicit prime_growth_policy(std::size_t& min_bucket_count_in_out) {
+ auto it_prime = std::lower_bound(detail::PRIMES.begin(),
+ detail::PRIMES.end(), min_bucket_count_in_out);
+ if(it_prime == detail::PRIMES.end()) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ m_iprime = static_cast<unsigned int>(std::distance(detail::PRIMES.begin(), it_prime));
+ if(min_bucket_count_in_out > 0) {
+ min_bucket_count_in_out = *it_prime;
+ }
+ else {
+ min_bucket_count_in_out = 0;
+ }
+ }
+
+ std::size_t bucket_for_hash(std::size_t hash) const noexcept {
+ return detail::MOD_PRIME[m_iprime](hash);
+ }
+
+ std::size_t next_bucket_count() const {
+ if(m_iprime + 1 >= detail::PRIMES.size()) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maxmimum size.");
+ }
+
+ return detail::PRIMES[m_iprime + 1];
+ }
+
+ std::size_t max_bucket_count() const {
+ return detail::PRIMES.back();
+ }
+
+ void clear() noexcept {
+ m_iprime = 0;
+ }
+
+private:
+ unsigned int m_iprime;
+
+ static_assert((std::numeric_limits<decltype(m_iprime)>::max)() >= detail::PRIMES.size(),
+ "The type of m_iprime is not big enough.");
+};
+
+}
+}
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_hash.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_hash.h
new file mode 100644
index 0000000..5ecc962
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_hash.h
@@ -0,0 +1,1285 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Tessil
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_ROBIN_HASH_H
+#define TSL_ROBIN_HASH_H
+
+
+#include <algorithm>
+#include <cassert>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <exception>
+#include <iterator>
+#include <limits>
+#include <memory>
+#include <stdexcept>
+#include <tuple>
+#include <type_traits>
+#include <utility>
+#include <vector>
+#include "robin_growth_policy.h"
+
+
+namespace tsl {
+
+namespace detail_robin_hash {
+
+template<typename T>
+struct make_void {
+ using type = void;
+};
+
+template<typename T, typename = void>
+struct has_is_transparent: std::false_type {
+};
+
+template<typename T>
+struct has_is_transparent<T, typename make_void<typename T::is_transparent>::type>: std::true_type {
+};
+
+template<typename U>
+struct is_power_of_two_policy: std::false_type {
+};
+
+template<std::size_t GrowthFactor>
+struct is_power_of_two_policy<tsl::rh::power_of_two_growth_policy<GrowthFactor>>: std::true_type {
+};
+
+
+
+using truncated_hash_type = std::uint_least32_t;
+
+/**
+ * Helper class that store a truncated hash if StoreHash is true and nothing otherwise.
+ */
+template<bool StoreHash>
+class bucket_entry_hash {
+public:
+ bool bucket_hash_equal(std::size_t /*hash*/) const noexcept {
+ return true;
+ }
+
+ truncated_hash_type truncated_hash() const noexcept {
+ return 0;
+ }
+
+protected:
+ void set_hash(truncated_hash_type /*hash*/) noexcept {
+ }
+};
+
+template<>
+class bucket_entry_hash<true> {
+public:
+ bool bucket_hash_equal(std::size_t hash) const noexcept {
+ return m_hash == truncated_hash_type(hash);
+ }
+
+ truncated_hash_type truncated_hash() const noexcept {
+ return m_hash;
+ }
+
+protected:
+ void set_hash(truncated_hash_type hash) noexcept {
+ m_hash = truncated_hash_type(hash);
+ }
+
+private:
+ truncated_hash_type m_hash;
+};
+
+
+/**
+ * Each bucket entry has:
+ * - A value of type `ValueType`.
+ * - An integer to store how far the value of the bucket, if any, is from its ideal bucket
+ * (ex: if the current bucket 5 has the value 'foo' and `hash('foo') % nb_buckets` == 3,
+ * `dist_from_ideal_bucket()` will return 2 as the current value of the bucket is two
+ * buckets away from its ideal bucket)
+ * If there is no value in the bucket (i.e. `empty()` is true) `dist_from_ideal_bucket()` will be < 0.
+ * - A marker which tells us if the bucket is the last bucket of the bucket array (useful for the
+ * iterator of the hash table).
+ * - If `StoreHash` is true, 32 bits of the hash of the value, if any, are also stored in the bucket.
+ * If the size of the hash is more than 32 bits, it is truncated. We don't store the full hash
+ * as storing the hash is a potential opportunity to use the unused space due to the alignement
+ * of the bucket_entry structure. We can thus potentially store the hash without any extra space
+ * (which would not be possible with 64 bits of the hash).
+ */
+template<typename ValueType, bool StoreHash>
+class bucket_entry: public bucket_entry_hash<StoreHash> {
+ using bucket_hash = bucket_entry_hash<StoreHash>;
+
+public:
+ using value_type = ValueType;
+ using distance_type = std::int_least16_t;
+
+
+ bucket_entry() noexcept: bucket_hash(), m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET),
+ m_last_bucket(false)
+ {
+ tsl_assert(empty());
+ }
+
+ bucket_entry(bool last_bucket) noexcept: bucket_hash(), m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET),
+ m_last_bucket(last_bucket)
+ {
+ tsl_assert(empty());
+ }
+
+ bucket_entry(const bucket_entry& other) noexcept(std::is_nothrow_copy_constructible<value_type>::value):
+ bucket_hash(other),
+ m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET),
+ m_last_bucket(other.m_last_bucket)
+ {
+ if(!other.empty()) {
+ ::new (static_cast<void*>(std::addressof(m_value))) value_type(other.value());
+ m_dist_from_ideal_bucket = other.m_dist_from_ideal_bucket;
+ }
+ }
+
+ /**
+ * Never really used, but still necessary as we must call resize on an empty `std::vector<bucket_entry>`.
+ * and we need to support move-only types. See robin_hash constructor for details.
+ */
+ bucket_entry(bucket_entry&& other) noexcept(std::is_nothrow_move_constructible<value_type>::value):
+ bucket_hash(std::move(other)),
+ m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET),
+ m_last_bucket(other.m_last_bucket)
+ {
+ if(!other.empty()) {
+ ::new (static_cast<void*>(std::addressof(m_value))) value_type(std::move(other.value()));
+ m_dist_from_ideal_bucket = other.m_dist_from_ideal_bucket;
+ }
+ }
+
+ bucket_entry& operator=(const bucket_entry& other)
+ noexcept(std::is_nothrow_copy_constructible<value_type>::value)
+ {
+ if(this != &other) {
+ clear();
+
+ bucket_hash::operator=(other);
+ if(!other.empty()) {
+ ::new (static_cast<void*>(std::addressof(m_value))) value_type(other.value());
+ }
+
+ m_dist_from_ideal_bucket = other.m_dist_from_ideal_bucket;
+ m_last_bucket = other.m_last_bucket;
+ }
+
+ return *this;
+ }
+
+ bucket_entry& operator=(bucket_entry&& ) = delete;
+
+ ~bucket_entry() noexcept {
+ clear();
+ }
+
+ void clear() noexcept {
+ if(!empty()) {
+ destroy_value();
+ m_dist_from_ideal_bucket = EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET;
+ }
+ }
+
+ bool empty() const noexcept {
+ return m_dist_from_ideal_bucket == EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET;
+ }
+
+ value_type& value() noexcept {
+ tsl_assert(!empty());
+ return *reinterpret_cast<value_type*>(std::addressof(m_value));
+ }
+
+ const value_type& value() const noexcept {
+ tsl_assert(!empty());
+ return *reinterpret_cast<const value_type*>(std::addressof(m_value));
+ }
+
+ distance_type dist_from_ideal_bucket() const noexcept {
+ return m_dist_from_ideal_bucket;
+ }
+
+ bool last_bucket() const noexcept {
+ return m_last_bucket;
+ }
+
+ void set_as_last_bucket() noexcept {
+ m_last_bucket = true;
+ }
+
+ template<typename... Args>
+ void set_value_of_empty_bucket(distance_type dist_from_ideal_bucket,
+ truncated_hash_type hash, Args&&... value_type_args)
+ {
+ tsl_assert(dist_from_ideal_bucket >= 0);
+ tsl_assert(empty());
+
+ ::new (static_cast<void*>(std::addressof(m_value))) value_type(std::forward<Args>(value_type_args)...);
+ this->set_hash(hash);
+ m_dist_from_ideal_bucket = dist_from_ideal_bucket;
+
+ tsl_assert(!empty());
+ }
+
+ void swap_with_value_in_bucket(distance_type& dist_from_ideal_bucket,
+ truncated_hash_type& hash, value_type& value)
+ {
+ tsl_assert(!empty());
+
+ using std::swap;
+ swap(value, this->value());
+ swap(dist_from_ideal_bucket, m_dist_from_ideal_bucket);
+
+ // Avoid warning of unused variable if StoreHash is false
+ (void) hash;
+ if(StoreHash) {
+ const truncated_hash_type tmp_hash = this->truncated_hash();
+ this->set_hash(hash);
+ hash = tmp_hash;
+ }
+ }
+
+ static truncated_hash_type truncate_hash(std::size_t hash) noexcept {
+ return truncated_hash_type(hash);
+ }
+
+private:
+ void destroy_value() noexcept {
+ tsl_assert(!empty());
+ value().~value_type();
+ }
+
+private:
+ using storage = typename std::aligned_storage<sizeof(value_type), alignof(value_type)>::type;
+
+ static const distance_type EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET = -1;
+
+ distance_type m_dist_from_ideal_bucket;
+ bool m_last_bucket;
+ storage m_value;
+};
+
+
+
+/**
+ * Internal common class used by `robin_map` and `robin_set`.
+ *
+ * ValueType is what will be stored by `robin_hash` (usually `std::pair<Key, T>` for map and `Key` for set).
+ *
+ * `KeySelect` should be a `FunctionObject` which takes a `ValueType` in parameter and returns a
+ * reference to the key.
+ *
+ * `ValueSelect` should be a `FunctionObject` which takes a `ValueType` in parameter and returns a
+ * reference to the value. `ValueSelect` should be void if there is no value (in a set for example).
+ *
+ * The strong exception guarantee only holds if the expression
+ * `std::is_nothrow_swappable<ValueType>::value && std::is_nothrow_move_constructible<ValueType>::value` is true.
+ *
+ * Behaviour is undefined if the destructor of `ValueType` throws.
+ */
+template<class ValueType,
+ class KeySelect,
+ class ValueSelect,
+ class Hash,
+ class KeyEqual,
+ class Allocator,
+ bool StoreHash,
+ class GrowthPolicy>
+class robin_hash: private Hash, private KeyEqual, private GrowthPolicy {
+private:
+ template<typename U>
+ using has_mapped_type = typename std::integral_constant<bool, !std::is_same<U, void>::value>;
+
+ static_assert(noexcept(std::declval<GrowthPolicy>().bucket_for_hash(std::size_t(0))), "GrowthPolicy::bucket_for_hash must be noexcept.");
+ static_assert(noexcept(std::declval<GrowthPolicy>().clear()), "GrowthPolicy::clear must be noexcept.");
+
+public:
+ template<bool IsConst>
+ class robin_iterator;
+
+ using key_type = typename KeySelect::key_type;
+ using value_type = ValueType;
+ using size_type = std::size_t;
+ using difference_type = std::ptrdiff_t;
+ using hasher = Hash;
+ using key_equal = KeyEqual;
+ using allocator_type = Allocator;
+ using reference = value_type&;
+ using const_reference = const value_type&;
+ using pointer = value_type*;
+ using const_pointer = const value_type*;
+ using iterator = robin_iterator<false>;
+ using const_iterator = robin_iterator<true>;
+
+
+private:
+ /**
+ * Either store the hash because we are asked by the `StoreHash` template parameter
+ * or store the hash because it doesn't cost us anything in size and can be used to speed up rehash.
+ */
+ static constexpr bool STORE_HASH = StoreHash ||
+ (
+ (sizeof(tsl::detail_robin_hash::bucket_entry<value_type, true>) ==
+ sizeof(tsl::detail_robin_hash::bucket_entry<value_type, false>))
+ &&
+ (sizeof(std::size_t) == sizeof(truncated_hash_type) ||
+ is_power_of_two_policy<GrowthPolicy>::value)
+ &&
+ // Don't store the hash for primitive types with default hash.
+ (!std::is_arithmetic<key_type>::value ||
+ !std::is_same<Hash, std::hash<key_type>>::value)
+ );
+
+ /**
+ * Only use the stored hash on lookup if we are explictly asked. We are not sure how slow
+ * the KeyEqual operation is. An extra comparison may slow things down with a fast KeyEqual.
+ */
+ static constexpr bool USE_STORED_HASH_ON_LOOKUP = StoreHash;
+
+ /**
+ * We can only use the hash on rehash if the size of the hash type is the same as the stored one or
+ * if we use a power of two modulo. In the case of the power of two modulo, we just mask
+ * the least significant bytes, we just have to check that the truncated_hash_type didn't truncated
+ * more bytes.
+ */
+ static bool USE_STORED_HASH_ON_REHASH(size_type bucket_count) {
+ (void) bucket_count;
+ if(STORE_HASH && sizeof(std::size_t) == sizeof(truncated_hash_type)) {
+ return true;
+ }
+ else if(STORE_HASH && is_power_of_two_policy<GrowthPolicy>::value) {
+ tsl_assert(bucket_count > 0);
+ return (bucket_count - 1) <= (std::numeric_limits<truncated_hash_type>::max)();
+ }
+ else {
+ return false;
+ }
+ }
+
+ using bucket_entry = tsl::detail_robin_hash::bucket_entry<value_type, STORE_HASH>;
+ using distance_type = typename bucket_entry::distance_type;
+
+ using buckets_allocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<bucket_entry>;
+ using buckets_container_type = std::vector<bucket_entry, buckets_allocator>;
+
+
+public:
+ /**
+ * The 'operator*()' and 'operator->()' methods return a const reference and const pointer respectively to the
+ * stored value type.
+ *
+ * In case of a map, to get a mutable reference to the value associated to a key (the '.second' in the
+ * stored pair), you have to call 'value()'.
+ *
+ * The main reason for this is that if we returned a `std::pair<Key, T>&` instead
+ * of a `const std::pair<Key, T>&`, the user may modify the key which will put the map in a undefined state.
+ */
+ template<bool IsConst>
+ class robin_iterator {
+ friend class robin_hash;
+
+ private:
+ using iterator_bucket = typename std::conditional<IsConst,
+ typename buckets_container_type::const_iterator,
+ typename buckets_container_type::iterator>::type;
+
+
+ robin_iterator(iterator_bucket it) noexcept: m_iterator(it) {
+ }
+
+ public:
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = const typename robin_hash::value_type;
+ using difference_type = std::ptrdiff_t;
+ using reference = value_type&;
+ using pointer = value_type*;
+
+
+ robin_iterator() noexcept {
+ }
+
+ robin_iterator(const robin_iterator<false>& other) noexcept: m_iterator(other.m_iterator) {
+ }
+
+ const typename robin_hash::key_type& key() const {
+ return KeySelect()(m_iterator->value());
+ }
+
+ template<class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value && IsConst>::type* = nullptr>
+ const typename U::value_type& value() const {
+ return U()(m_iterator->value());
+ }
+
+ template<class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value && !IsConst>::type* = nullptr>
+ typename U::value_type& value() {
+ return U()(m_iterator->value());
+ }
+
+ reference operator*() const {
+ return m_iterator->value();
+ }
+
+ pointer operator->() const {
+ return std::addressof(m_iterator->value());
+ }
+
+ robin_iterator& operator++() {
+ while(true) {
+ if(m_iterator->last_bucket()) {
+ ++m_iterator;
+ return *this;
+ }
+
+ ++m_iterator;
+ if(!m_iterator->empty()) {
+ return *this;
+ }
+ }
+ }
+
+ robin_iterator operator++(int) {
+ robin_iterator tmp(*this);
+ ++*this;
+
+ return tmp;
+ }
+
+ friend bool operator==(const robin_iterator& lhs, const robin_iterator& rhs) {
+ return lhs.m_iterator == rhs.m_iterator;
+ }
+
+ friend bool operator!=(const robin_iterator& lhs, const robin_iterator& rhs) {
+ return !(lhs == rhs);
+ }
+
+ private:
+ iterator_bucket m_iterator;
+ };
+
+
+public:
+ robin_hash(size_type bucket_count,
+ const Hash& hash,
+ const KeyEqual& equal,
+ const Allocator& alloc,
+ float max_load_factor): Hash(hash),
+ KeyEqual(equal),
+ GrowthPolicy(bucket_count),
+ m_buckets(alloc),
+ m_first_or_empty_bucket(static_empty_bucket_ptr()),
+ m_bucket_count(bucket_count),
+ m_nb_elements(0),
+ m_grow_on_next_insert(false)
+ {
+ if(bucket_count > max_bucket_count()) {
+ TSL_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maxmimum size.");
+ }
+
+ if(m_bucket_count > 0) {
+ /*
+ * We can't use the `vector(size_type count, const Allocator& alloc)` constructor
+ * as it's only available in C++14 and we need to support C++11. We thus must resize after using
+ * the `vector(const Allocator& alloc)` constructor.
+ *
+ * We can't use `vector(size_type count, const T& value, const Allocator& alloc)` as it requires the
+ * value T to be copyable.
+ */
+ m_buckets.resize(m_bucket_count);
+ m_first_or_empty_bucket = m_buckets.data();
+
+ tsl_assert(!m_buckets.empty());
+ m_buckets.back().set_as_last_bucket();
+ }
+
+
+ this->max_load_factor(max_load_factor);
+ }
+
+ robin_hash(const robin_hash& other): Hash(other),
+ KeyEqual(other),
+ GrowthPolicy(other),
+ m_buckets(other.m_buckets),
+ m_first_or_empty_bucket(m_buckets.empty()?static_empty_bucket_ptr():m_buckets.data()),
+ m_bucket_count(other.m_bucket_count),
+ m_nb_elements(other.m_nb_elements),
+ m_load_threshold(other.m_load_threshold),
+ m_max_load_factor(other.m_max_load_factor),
+ m_grow_on_next_insert(other.m_grow_on_next_insert)
+ {
+ }
+
+ robin_hash(robin_hash&& other) noexcept(std::is_nothrow_move_constructible<Hash>::value &&
+ std::is_nothrow_move_constructible<KeyEqual>::value &&
+ std::is_nothrow_move_constructible<GrowthPolicy>::value &&
+ std::is_nothrow_move_constructible<buckets_container_type>::value)
+ : Hash(std::move(static_cast<Hash&>(other))),
+ KeyEqual(std::move(static_cast<KeyEqual&>(other))),
+ GrowthPolicy(std::move(static_cast<GrowthPolicy&>(other))),
+ m_buckets(std::move(other.m_buckets)),
+ m_first_or_empty_bucket(m_buckets.empty()?static_empty_bucket_ptr():m_buckets.data()),
+ m_bucket_count(other.m_bucket_count),
+ m_nb_elements(other.m_nb_elements),
+ m_load_threshold(other.m_load_threshold),
+ m_max_load_factor(other.m_max_load_factor),
+ m_grow_on_next_insert(other.m_grow_on_next_insert)
+ {
+ other.GrowthPolicy::clear();
+ other.m_buckets.clear();
+ other.m_first_or_empty_bucket = static_empty_bucket_ptr();
+ other.m_bucket_count = 0;
+ other.m_nb_elements = 0;
+ other.m_load_threshold = 0;
+ other.m_grow_on_next_insert = false;
+ }
+
+ robin_hash& operator=(const robin_hash& other) {
+ if(&other != this) {
+ Hash::operator=(other);
+ KeyEqual::operator=(other);
+ GrowthPolicy::operator=(other);
+
+ m_buckets = other.m_buckets;
+ m_first_or_empty_bucket = m_buckets.empty()?static_empty_bucket_ptr():
+ m_buckets.data();
+ m_bucket_count = other.m_bucket_count;
+ m_nb_elements = other.m_nb_elements;
+ m_load_threshold = other.m_load_threshold;
+ m_max_load_factor = other.m_max_load_factor;
+ m_grow_on_next_insert = other.m_grow_on_next_insert;
+ }
+
+ return *this;
+ }
+
+ robin_hash& operator=(robin_hash&& other) {
+ other.swap(*this);
+ other.clear();
+
+ return *this;
+ }
+
+ allocator_type get_allocator() const {
+ return m_buckets.get_allocator();
+ }
+
+
+ /*
+ * Iterators
+ */
+ iterator begin() noexcept {
+ auto begin = m_buckets.begin();
+ while(begin != m_buckets.end() && begin->empty()) {
+ ++begin;
+ }
+
+ return iterator(begin);
+ }
+
+ const_iterator begin() const noexcept {
+ return cbegin();
+ }
+
+ const_iterator cbegin() const noexcept {
+ auto begin = m_buckets.cbegin();
+ while(begin != m_buckets.cend() && begin->empty()) {
+ ++begin;
+ }
+
+ return const_iterator(begin);
+ }
+
+ iterator end() noexcept {
+ return iterator(m_buckets.end());
+ }
+
+ const_iterator end() const noexcept {
+ return cend();
+ }
+
+ const_iterator cend() const noexcept {
+ return const_iterator(m_buckets.cend());
+ }
+
+
+ /*
+ * Capacity
+ */
+ bool empty() const noexcept {
+ return m_nb_elements == 0;
+ }
+
+ size_type size() const noexcept {
+ return m_nb_elements;
+ }
+
+ size_type max_size() const noexcept {
+ return m_buckets.max_size();
+ }
+
+ /*
+ * Modifiers
+ */
+ void clear() noexcept {
+ for(auto& bucket: m_buckets) {
+ bucket.clear();
+ }
+
+ m_nb_elements = 0;
+ m_grow_on_next_insert = false;
+ }
+
+
+
+ template<typename P>
+ std::pair<iterator, bool> insert(P&& value) {
+ return insert_impl(KeySelect()(value), std::forward<P>(value));
+ }
+
+ template<typename P>
+ iterator insert(const_iterator hint, P&& value) {
+ if(hint != cend() && compare_keys(KeySelect()(*hint), KeySelect()(value))) {
+ return mutable_iterator(hint);
+ }
+
+ return insert(std::forward<P>(value)).first;
+ }
+
+ template<class InputIt>
+ void insert(InputIt first, InputIt last) {
+ if(std::is_base_of<std::forward_iterator_tag,
+ typename std::iterator_traits<InputIt>::iterator_category>::value)
+ {
+ const auto nb_elements_insert = std::distance(first, last);
+ const size_type nb_free_buckets = m_load_threshold - size();
+ tsl_assert(m_load_threshold >= size());
+
+ if(nb_elements_insert > 0 && nb_free_buckets < size_type(nb_elements_insert)) {
+ reserve(size() + size_type(nb_elements_insert));
+ }
+ }
+
+ for(; first != last; ++first) {
+ insert(*first);
+ }
+ }
+
+
+
+ template<class K, class M>
+ std::pair<iterator, bool> insert_or_assign(K&& key, M&& obj) {
+ auto it = try_emplace(std::forward<K>(key), std::forward<M>(obj));
+ if(!it.second) {
+ it.first.value() = std::forward<M>(obj);
+ }
+
+ return it;
+ }
+
+ template<class K, class M>
+ iterator insert_or_assign(const_iterator hint, K&& key, M&& obj) {
+ if(hint != cend() && compare_keys(KeySelect()(*hint), key)) {
+ auto it = mutable_iterator(hint);
+ it.value() = std::forward<M>(obj);
+
+ return it;
+ }
+
+ return insert_or_assign(std::forward<K>(key), std::forward<M>(obj)).first;
+ }
+
+
+ template<class... Args>
+ std::pair<iterator, bool> emplace(Args&&... args) {
+ return insert(value_type(std::forward<Args>(args)...));
+ }
+
+ template<class... Args>
+ iterator emplace_hint(const_iterator hint, Args&&... args) {
+ return insert(hint, value_type(std::forward<Args>(args)...));
+ }
+
+
+
+ template<class K, class... Args>
+ std::pair<iterator, bool> try_emplace(K&& key, Args&&... args) {
+ return insert_impl(key, std::piecewise_construct,
+ std::forward_as_tuple(std::forward<K>(key)),
+ std::forward_as_tuple(std::forward<Args>(args)...));
+ }
+
+ template<class K, class... Args>
+ iterator try_emplace(const_iterator hint, K&& key, Args&&... args) {
+ if(hint != cend() && compare_keys(KeySelect()(*hint), key)) {
+ return mutable_iterator(hint);
+ }
+
+ return try_emplace(std::forward<K>(key), std::forward<Args>(args)...).first;
+ }
+
+ /**
+ * Here to avoid `template<class K> size_type erase(const K& key)` being used when
+ * we use an `iterator` instead of a `const_iterator`.
+ */
+ iterator erase(iterator pos) {
+ erase_from_bucket(pos);
+
+ /**
+ * Erase bucket used a backward shift after clearing the bucket.
+ * Check if there is a new value in the bucket, if not get the next non-empty.
+ */
+ if(pos.m_iterator->empty()) {
+ ++pos;
+ }
+
+ return pos;
+ }
+
+ iterator erase(const_iterator pos) {
+ return erase(mutable_iterator(pos));
+ }
+
+ iterator erase(const_iterator first, const_iterator last) {
+ if(first == last) {
+ return mutable_iterator(first);
+ }
+
+ auto first_mutable = mutable_iterator(first);
+ auto last_mutable = mutable_iterator(last);
+ for(auto it = first_mutable.m_iterator; it != last_mutable.m_iterator; ++it) {
+ if(!it->empty()) {
+ it->clear();
+ m_nb_elements--;
+ }
+ }
+
+ if(last_mutable == end()) {
+ return end();
+ }
+
+
+ /*
+ * Backward shift on the values which come after the deleted values.
+ * We try to move the values closer to their ideal bucket.
+ */
+ std::size_t icloser_bucket = std::size_t(std::distance(m_buckets.begin(), first_mutable.m_iterator));
+ std::size_t ito_move_closer_value = std::size_t(std::distance(m_buckets.begin(), last_mutable.m_iterator));
+ tsl_assert(ito_move_closer_value > icloser_bucket);
+
+ const std::size_t ireturn_bucket = ito_move_closer_value -
+ (std::min)(ito_move_closer_value - icloser_bucket,
+ std::size_t(m_buckets[ito_move_closer_value].dist_from_ideal_bucket()));
+
+ while(ito_move_closer_value < m_buckets.size() && m_buckets[ito_move_closer_value].dist_from_ideal_bucket() > 0) {
+ icloser_bucket = ito_move_closer_value -
+ (std::min)(ito_move_closer_value - icloser_bucket,
+ std::size_t(m_buckets[ito_move_closer_value].dist_from_ideal_bucket()));
+
+
+ tsl_assert(m_buckets[icloser_bucket].empty());
+ const distance_type new_distance = distance_type(m_buckets[ito_move_closer_value].dist_from_ideal_bucket() -
+ (ito_move_closer_value - icloser_bucket));
+ m_buckets[icloser_bucket].set_value_of_empty_bucket(new_distance,
+ m_buckets[ito_move_closer_value].truncated_hash(),
+ std::move(m_buckets[ito_move_closer_value].value()));
+ m_buckets[ito_move_closer_value].clear();
+
+
+ ++icloser_bucket;
+ ++ito_move_closer_value;
+ }
+
+
+ return iterator(m_buckets.begin() + ireturn_bucket);
+ }
+
+
+ template<class K>
+ size_type erase(const K& key) {
+ return erase(key, hash_key(key));
+ }
+
+ template<class K>
+ size_type erase(const K& key, std::size_t hash) {
+ auto it = find(key, hash);
+ if(it != end()) {
+ erase_from_bucket(it);
+
+ return 1;
+ }
+ else {
+ return 0;
+ }
+ }
+
+
+
+
+
+ void swap(robin_hash& other) {
+ using std::swap;
+
+ swap(static_cast<Hash&>(*this), static_cast<Hash&>(other));
+ swap(static_cast<KeyEqual&>(*this), static_cast<KeyEqual&>(other));
+ swap(static_cast<GrowthPolicy&>(*this), static_cast<GrowthPolicy&>(other));
+ swap(m_buckets, other.m_buckets);
+ swap(m_first_or_empty_bucket, other.m_first_or_empty_bucket);
+ swap(m_bucket_count, other.m_bucket_count);
+ swap(m_nb_elements, other.m_nb_elements);
+ swap(m_load_threshold, other.m_load_threshold);
+ swap(m_max_load_factor, other.m_max_load_factor);
+ swap(m_grow_on_next_insert, other.m_grow_on_next_insert);
+ }
+
+
+ /*
+ * Lookup
+ */
+ template<class K, class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value>::type* = nullptr>
+ typename U::value_type& at(const K& key) {
+ return at(key, hash_key(key));
+ }
+
+ template<class K, class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value>::type* = nullptr>
+ typename U::value_type& at(const K& key, std::size_t hash) {
+ return const_cast<typename U::value_type&>(static_cast<const robin_hash*>(this)->at(key, hash));
+ }
+
+
+ template<class K, class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value>::type* = nullptr>
+ const typename U::value_type& at(const K& key) const {
+ return at(key, hash_key(key));
+ }
+
+ template<class K, class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value>::type* = nullptr>
+ const typename U::value_type& at(const K& key, std::size_t hash) const {
+ auto it = find(key, hash);
+ if(it != cend()) {
+ return it.value();
+ }
+ else {
+ TSL_THROW_OR_TERMINATE(std::out_of_range, "Couldn't find key.");
+ }
+ }
+
+ template<class K, class U = ValueSelect, typename std::enable_if<has_mapped_type<U>::value>::type* = nullptr>
+ typename U::value_type& operator[](K&& key) {
+ return try_emplace(std::forward<K>(key)).first.value();
+ }
+
+
+ template<class K>
+ size_type count(const K& key) const {
+ return count(key, hash_key(key));
+ }
+
+ template<class K>
+ size_type count(const K& key, std::size_t hash) const {
+ if(find(key, hash) != cend()) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+ }
+
+
+ template<class K>
+ iterator find(const K& key) {
+ return find_impl(key, hash_key(key));
+ }
+
+ template<class K>
+ iterator find(const K& key, std::size_t hash) {
+ return find_impl(key, hash);
+ }
+
+
+ template<class K>
+ const_iterator find(const K& key) const {
+ return find_impl(key, hash_key(key));
+ }
+
+ template<class K>
+ const_iterator find(const K& key, std::size_t hash) const {
+ return find_impl(key, hash);
+ }
+
+
+ template<class K>
+ std::pair<iterator, iterator> equal_range(const K& key) {
+ return equal_range(key, hash_key(key));
+ }
+
+ template<class K>
+ std::pair<iterator, iterator> equal_range(const K& key, std::size_t hash) {
+ iterator it = find(key, hash);
+ return std::make_pair(it, (it == end())?it:std::next(it));
+ }
+
+
+ template<class K>
+ std::pair<const_iterator, const_iterator> equal_range(const K& key) const {
+ return equal_range(key, hash_key(key));
+ }
+
+ template<class K>
+ std::pair<const_iterator, const_iterator> equal_range(const K& key, std::size_t hash) const {
+ const_iterator it = find(key, hash);
+ return std::make_pair(it, (it == cend())?it:std::next(it));
+ }
+
+ /*
+ * Bucket interface
+ */
+ size_type bucket_count() const {
+ return m_bucket_count;
+ }
+
+ size_type max_bucket_count() const {
+ return (std::min)(GrowthPolicy::max_bucket_count(), m_buckets.max_size());
+ }
+
+ /*
+ * Hash policy
+ */
+ float load_factor() const {
+ if(bucket_count() == 0) {
+ return 0;
+ }
+
+ return float(m_nb_elements)/float(bucket_count());
+ }
+
+ float max_load_factor() const {
+ return m_max_load_factor;
+ }
+
+ void max_load_factor(float ml) {
+ m_max_load_factor = (std::max)(0.1f, (std::min)(ml, 0.95f));
+ m_load_threshold = size_type(float(bucket_count())*m_max_load_factor);
+ }
+
+ void rehash(size_type count) {
+ count = (std::max)(count, size_type(std::ceil(float(size())/max_load_factor())));
+ rehash_impl(count);
+ }
+
+ void reserve(size_type count) {
+ rehash(size_type(std::ceil(float(count)/max_load_factor())));
+ }
+
+ /*
+ * Observers
+ */
+ hasher hash_function() const {
+ return static_cast<const Hash&>(*this);
+ }
+
+ key_equal key_eq() const {
+ return static_cast<const KeyEqual&>(*this);
+ }
+
+
+ /*
+ * Other
+ */
+ iterator mutable_iterator(const_iterator pos) {
+ return iterator(m_buckets.begin() + std::distance(m_buckets.cbegin(), pos.m_iterator));
+ }
+
+private:
+ template<class K>
+ std::size_t hash_key(const K& key) const {
+ return Hash::operator()(key);
+ }
+
+ template<class K1, class K2>
+ bool compare_keys(const K1& key1, const K2& key2) const {
+ return KeyEqual::operator()(key1, key2);
+ }
+
+ std::size_t bucket_for_hash(std::size_t hash) const {
+ const std::size_t bucket = GrowthPolicy::bucket_for_hash(hash);
+ tsl_assert(bucket < m_buckets.size() || (bucket == 0 && m_buckets.empty()));
+
+ return bucket;
+ }
+
+ template<class U = GrowthPolicy, typename std::enable_if<is_power_of_two_policy<U>::value>::type* = nullptr>
+ std::size_t next_bucket(std::size_t index) const noexcept {
+ tsl_assert(index < bucket_count());
+
+ return (index + 1) & this->m_mask;
+ }
+
+ template<class U = GrowthPolicy, typename std::enable_if<!is_power_of_two_policy<U>::value>::type* = nullptr>
+ std::size_t next_bucket(std::size_t index) const noexcept {
+ tsl_assert(index < bucket_count());
+
+ index++;
+ return (index != bucket_count())?index:0;
+ }
+
+
+
+ template<class K>
+ iterator find_impl(const K& key, std::size_t hash) {
+ return mutable_iterator(static_cast<const robin_hash*>(this)->find(key, hash));
+ }
+
+ template<class K>
+ const_iterator find_impl(const K& key, std::size_t hash) const {
+ std::size_t ibucket = bucket_for_hash(hash);
+ distance_type dist_from_ideal_bucket = 0;
+
+ while(dist_from_ideal_bucket <= (m_first_or_empty_bucket + ibucket)->dist_from_ideal_bucket()) {
+ if(TSL_LIKELY((!USE_STORED_HASH_ON_LOOKUP || (m_first_or_empty_bucket + ibucket)->bucket_hash_equal(hash)) &&
+ compare_keys(KeySelect()((m_first_or_empty_bucket + ibucket)->value()), key)))
+ {
+ return const_iterator(m_buckets.begin() + ibucket);
+ }
+
+ ibucket = next_bucket(ibucket);
+ dist_from_ideal_bucket++;
+ }
+
+ return cend();
+ }
+
+ void erase_from_bucket(iterator pos) {
+ pos.m_iterator->clear();
+ m_nb_elements--;
+
+ /**
+ * Backward shift, swap the empty bucket, previous_ibucket, with the values on its right, ibucket,
+ * until we cross another empty bucket or if the other bucket has a distance_from_ideal_bucket == 0.
+ *
+ * We try to move the values closer to their ideal bucket.
+ */
+ std::size_t previous_ibucket = std::size_t(std::distance(m_buckets.begin(), pos.m_iterator));
+ std::size_t ibucket = next_bucket(previous_ibucket);
+
+ while(m_buckets[ibucket].dist_from_ideal_bucket() > 0) {
+ tsl_assert(m_buckets[previous_ibucket].empty());
+
+ const distance_type new_distance = distance_type(m_buckets[ibucket].dist_from_ideal_bucket() - 1);
+ m_buckets[previous_ibucket].set_value_of_empty_bucket(new_distance, m_buckets[ibucket].truncated_hash(),
+ std::move(m_buckets[ibucket].value()));
+ m_buckets[ibucket].clear();
+
+ previous_ibucket = ibucket;
+ ibucket = next_bucket(ibucket);
+ }
+ }
+
+ template<class K, class... Args>
+ std::pair<iterator, bool> insert_impl(const K& key, Args&&... value_type_args) {
+ const std::size_t hash = hash_key(key);
+
+ std::size_t ibucket = bucket_for_hash(hash);
+ distance_type dist_from_ideal_bucket = 0;
+
+ while(dist_from_ideal_bucket <= (m_first_or_empty_bucket + ibucket)->dist_from_ideal_bucket()) {
+ if((!USE_STORED_HASH_ON_LOOKUP || (m_first_or_empty_bucket + ibucket)->bucket_hash_equal(hash)) &&
+ compare_keys(KeySelect()((m_first_or_empty_bucket + ibucket)->value()), key))
+ {
+ return std::make_pair(iterator(m_buckets.begin() + ibucket), false);
+ }
+
+ ibucket = next_bucket(ibucket);
+ dist_from_ideal_bucket++;
+ }
+
+ if(grow_on_high_load()) {
+ ibucket = bucket_for_hash(hash);
+ dist_from_ideal_bucket = 0;
+
+ while(dist_from_ideal_bucket <= (m_first_or_empty_bucket + ibucket)->dist_from_ideal_bucket()) {
+ ibucket = next_bucket(ibucket);
+ dist_from_ideal_bucket++;
+ }
+ }
+
+
+ if((m_first_or_empty_bucket + ibucket)->empty()) {
+ (m_first_or_empty_bucket + ibucket)->set_value_of_empty_bucket(dist_from_ideal_bucket, bucket_entry::truncate_hash(hash),
+ std::forward<Args>(value_type_args)...);
+ }
+ else {
+ insert_value(ibucket, dist_from_ideal_bucket, bucket_entry::truncate_hash(hash),
+ std::forward<Args>(value_type_args)...);
+ }
+
+
+ m_nb_elements++;
+ /*
+ * The value will be inserted in ibucket in any case, either because it was
+ * empty or by stealing the bucket (robin hood).
+ */
+ return std::make_pair(iterator(m_buckets.begin() + ibucket), true);
+ }
+
+
+ template<class... Args>
+ void insert_value(std::size_t ibucket, distance_type dist_from_ideal_bucket,
+ truncated_hash_type hash, Args&&... value_type_args)
+ {
+ insert_value(ibucket, dist_from_ideal_bucket, hash, value_type(std::forward<Args>(value_type_args)...));
+ }
+
+ void insert_value(std::size_t ibucket, distance_type dist_from_ideal_bucket,
+ truncated_hash_type hash, value_type&& value)
+ {
+ m_buckets[ibucket].swap_with_value_in_bucket(dist_from_ideal_bucket, hash, value);
+ ibucket = next_bucket(ibucket);
+ dist_from_ideal_bucket++;
+
+ while(!m_buckets[ibucket].empty()) {
+ if(dist_from_ideal_bucket > m_buckets[ibucket].dist_from_ideal_bucket()) {
+ if(dist_from_ideal_bucket >= REHASH_ON_HIGH_NB_PROBES__NPROBES &&
+ load_factor() >= REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR)
+ {
+ /**
+ * The number of probes is really high, rehash the map on the next insert.
+ * Difficult to do now as rehash may throw an exception.
+ */
+ m_grow_on_next_insert = true;
+ }
+
+ m_buckets[ibucket].swap_with_value_in_bucket(dist_from_ideal_bucket, hash, value);
+ }
+
+ ibucket = next_bucket(ibucket);
+ dist_from_ideal_bucket++;
+ }
+
+ m_buckets[ibucket].set_value_of_empty_bucket(dist_from_ideal_bucket, hash, std::move(value));
+ }
+
+
+ void rehash_impl(size_type count) {
+ robin_hash new_table(count, static_cast<Hash&>(*this), static_cast<KeyEqual&>(*this),
+ get_allocator(), m_max_load_factor);
+
+ const bool use_stored_hash = USE_STORED_HASH_ON_REHASH(new_table.bucket_count());
+ for(auto& bucket: m_buckets) {
+ if(bucket.empty()) {
+ continue;
+ }
+
+ const std::size_t hash = use_stored_hash?bucket.truncated_hash():
+ new_table.hash_key(KeySelect()(bucket.value()));
+
+ new_table.insert_value_on_rehash(new_table.bucket_for_hash(hash), 0,
+ bucket_entry::truncate_hash(hash), std::move(bucket.value()));
+ }
+
+ new_table.m_nb_elements = m_nb_elements;
+ new_table.swap(*this);
+ }
+
+ void insert_value_on_rehash(std::size_t ibucket, distance_type dist_from_ideal_bucket,
+ truncated_hash_type hash, value_type&& value)
+ {
+ while(true) {
+ if(dist_from_ideal_bucket > m_buckets[ibucket].dist_from_ideal_bucket()) {
+ if(m_buckets[ibucket].empty()) {
+ m_buckets[ibucket].set_value_of_empty_bucket(dist_from_ideal_bucket, hash, std::move(value));
+ return;
+ }
+ else {
+ m_buckets[ibucket].swap_with_value_in_bucket(dist_from_ideal_bucket, hash, value);
+ }
+ }
+
+ dist_from_ideal_bucket++;
+ ibucket = next_bucket(ibucket);
+ }
+ }
+
+
+
+ /**
+ * Return true if the map has been rehashed.
+ */
+ bool grow_on_high_load() {
+ if(m_grow_on_next_insert || size() >= m_load_threshold) {
+ rehash_impl(GrowthPolicy::next_bucket_count());
+ m_grow_on_next_insert = false;
+
+ return true;
+ }
+
+ return false;
+ }
+
+
+public:
+ static const size_type DEFAULT_INIT_BUCKETS_SIZE = 16;
+ static constexpr float DEFAULT_MAX_LOAD_FACTOR = 0.5f;
+
+private:
+ static const distance_type REHASH_ON_HIGH_NB_PROBES__NPROBES = 128;
+ static constexpr float REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR = 0.15f;
+
+
+ /**
+ * Return an always valid pointer to an static empty bucket_entry with last_bucket() == true.
+ */
+ bucket_entry* static_empty_bucket_ptr() {
+ static bucket_entry empty_bucket(true);
+ return &empty_bucket;
+ }
+
+private:
+ buckets_container_type m_buckets;
+
+ /**
+ * Points to m_buckets.data() if !m_buckets.empty() otherwise points to static_empty_bucket_ptr.
+ * This variable is useful to avoid the cost of checking if m_buckets is empty when trying
+ * to find an element.
+ */
+ bucket_entry* m_first_or_empty_bucket;
+
+ /**
+ * Used a lot in find, avoid the call to m_buckets.size() which is a bit slower.
+ */
+ size_type m_bucket_count;
+
+ size_type m_nb_elements;
+
+ size_type m_load_threshold;
+ float m_max_load_factor;
+
+ bool m_grow_on_next_insert;
+};
+
+}
+
+}
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_map.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_map.h
new file mode 100644
index 0000000..5958e70
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_map.h
@@ -0,0 +1,668 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Tessil
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_ROBIN_MAP_H
+#define TSL_ROBIN_MAP_H
+
+
+#include <cstddef>
+#include <functional>
+#include <initializer_list>
+#include <memory>
+#include <type_traits>
+#include <utility>
+#include "robin_hash.h"
+
+
+namespace tsl {
+
+
+/**
+ * Implementation of a hash map using open-adressing and the robin hood hashing algorithm with backward shift deletion.
+ *
+ * For operations modifying the hash map (insert, erase, rehash, ...), the strong exception guarantee
+ * is only guaranteed when the expression `std::is_nothrow_swappable<std::pair<Key, T>>::value &&
+ * std::is_nothrow_move_constructible<std::pair<Key, T>>::value` is true, otherwise if an exception
+ * is thrown during the swap or the move, the hash map may end up in a undefined state. Per the standard
+ * a `Key` or `T` with a noexcept copy constructor and no move constructor also satisfies the
+ * `std::is_nothrow_move_constructible<std::pair<Key, T>>::value` criterion (and will thus guarantee the
+ * strong exception for the map).
+ *
+ * When `StoreHash` is true, 32 bits of the hash are stored alongside the values. It can improve
+ * the performance during lookups if the `KeyEqual` function takes time (if it engenders a cache-miss for example)
+ * as we then compare the stored hashes before comparing the keys. When `tsl::rh::power_of_two_growth_policy` is used
+ * as `GrowthPolicy`, it may also speed-up the rehash process as we can avoid to recalculate the hash.
+ * When it is detected that storing the hash will not incur any memory penality due to alignement (i.e.
+ * `sizeof(tsl::detail_robin_hash::bucket_entry<ValueType, true>) ==
+ * sizeof(tsl::detail_robin_hash::bucket_entry<ValueType, false>)`) and `tsl::rh::power_of_two_growth_policy` is
+ * used, the hash will be stored even if `StoreHash` is false so that we can speed-up the rehash (but it will
+ * not be used on lookups unless `StoreHash` is true).
+ *
+ * `GrowthPolicy` defines how the map grows and consequently how a hash value is mapped to a bucket.
+ * By default the map uses `tsl::rh::power_of_two_growth_policy`. This policy keeps the number of buckets
+ * to a power of two and uses a mask to map the hash to a bucket instead of the slow modulo.
+ * Other growth policies are available and you may define your own growth policy,
+ * check `tsl::rh::power_of_two_growth_policy` for the interface.
+ *
+ * If the destructor of `Key` or `T` throws an exception, the behaviour of the class is undefined.
+ *
+ * Iterators invalidation:
+ * - clear, operator=, reserve, rehash: always invalidate the iterators.
+ * - insert, emplace, emplace_hint, operator[]: if there is an effective insert, invalidate the iterators.
+ * - erase: always invalidate the iterators.
+ */
+template<class Key,
+ class T,
+ class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<std::pair<Key, T>>,
+ bool StoreHash = false,
+ class GrowthPolicy = tsl::rh::power_of_two_growth_policy<2>>
+class robin_map {
+private:
+ template<typename U>
+ using has_is_transparent = tsl::detail_robin_hash::has_is_transparent<U>;
+
+ class KeySelect {
+ public:
+ using key_type = Key;
+
+ const key_type& operator()(const std::pair<Key, T>& key_value) const noexcept {
+ return key_value.first;
+ }
+
+ key_type& operator()(std::pair<Key, T>& key_value) noexcept {
+ return key_value.first;
+ }
+ };
+
+ class ValueSelect {
+ public:
+ using value_type = T;
+
+ const value_type& operator()(const std::pair<Key, T>& key_value) const noexcept {
+ return key_value.second;
+ }
+
+ value_type& operator()(std::pair<Key, T>& key_value) noexcept {
+ return key_value.second;
+ }
+ };
+
+ using ht = detail_robin_hash::robin_hash<std::pair<Key, T>, KeySelect, ValueSelect,
+ Hash, KeyEqual, Allocator, StoreHash, GrowthPolicy>;
+
+public:
+ using key_type = typename ht::key_type;
+ using mapped_type = T;
+ using value_type = typename ht::value_type;
+ using size_type = typename ht::size_type;
+ using difference_type = typename ht::difference_type;
+ using hasher = typename ht::hasher;
+ using key_equal = typename ht::key_equal;
+ using allocator_type = typename ht::allocator_type;
+ using reference = typename ht::reference;
+ using const_reference = typename ht::const_reference;
+ using pointer = typename ht::pointer;
+ using const_pointer = typename ht::const_pointer;
+ using iterator = typename ht::iterator;
+ using const_iterator = typename ht::const_iterator;
+
+
+public:
+ /*
+ * Constructors
+ */
+ robin_map(): robin_map(ht::DEFAULT_INIT_BUCKETS_SIZE) {
+ }
+
+ explicit robin_map(size_type bucket_count,
+ const Hash& hash = Hash(),
+ const KeyEqual& equal = KeyEqual(),
+ const Allocator& alloc = Allocator()):
+ m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR)
+ {
+ }
+
+ robin_map(size_type bucket_count,
+ const Allocator& alloc): robin_map(bucket_count, Hash(), KeyEqual(), alloc)
+ {
+ }
+
+ robin_map(size_type bucket_count,
+ const Hash& hash,
+ const Allocator& alloc): robin_map(bucket_count, hash, KeyEqual(), alloc)
+ {
+ }
+
+ explicit robin_map(const Allocator& alloc): robin_map(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) {
+ }
+
+ template<class InputIt>
+ robin_map(InputIt first, InputIt last,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE,
+ const Hash& hash = Hash(),
+ const KeyEqual& equal = KeyEqual(),
+ const Allocator& alloc = Allocator()): robin_map(bucket_count, hash, equal, alloc)
+ {
+ insert(first, last);
+ }
+
+ template<class InputIt>
+ robin_map(InputIt first, InputIt last,
+ size_type bucket_count,
+ const Allocator& alloc): robin_map(first, last, bucket_count, Hash(), KeyEqual(), alloc)
+ {
+ }
+
+ template<class InputIt>
+ robin_map(InputIt first, InputIt last,
+ size_type bucket_count,
+ const Hash& hash,
+ const Allocator& alloc): robin_map(first, last, bucket_count, hash, KeyEqual(), alloc)
+ {
+ }
+
+ robin_map(std::initializer_list<value_type> init,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE,
+ const Hash& hash = Hash(),
+ const KeyEqual& equal = KeyEqual(),
+ const Allocator& alloc = Allocator()):
+ robin_map(init.begin(), init.end(), bucket_count, hash, equal, alloc)
+ {
+ }
+
+ robin_map(std::initializer_list<value_type> init,
+ size_type bucket_count,
+ const Allocator& alloc):
+ robin_map(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc)
+ {
+ }
+
+ robin_map(std::initializer_list<value_type> init,
+ size_type bucket_count,
+ const Hash& hash,
+ const Allocator& alloc):
+ robin_map(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc)
+ {
+ }
+
+ robin_map& operator=(std::initializer_list<value_type> ilist) {
+ m_ht.clear();
+
+ m_ht.reserve(ilist.size());
+ m_ht.insert(ilist.begin(), ilist.end());
+
+ return *this;
+ }
+
+ allocator_type get_allocator() const { return m_ht.get_allocator(); }
+
+
+ /*
+ * Iterators
+ */
+ iterator begin() noexcept { return m_ht.begin(); }
+ const_iterator begin() const noexcept { return m_ht.begin(); }
+ const_iterator cbegin() const noexcept { return m_ht.cbegin(); }
+
+ iterator end() noexcept { return m_ht.end(); }
+ const_iterator end() const noexcept { return m_ht.end(); }
+ const_iterator cend() const noexcept { return m_ht.cend(); }
+
+
+ /*
+ * Capacity
+ */
+ bool empty() const noexcept { return m_ht.empty(); }
+ size_type size() const noexcept { return m_ht.size(); }
+ size_type max_size() const noexcept { return m_ht.max_size(); }
+
+ /*
+ * Modifiers
+ */
+ void clear() noexcept { m_ht.clear(); }
+
+
+
+ std::pair<iterator, bool> insert(const value_type& value) {
+ return m_ht.insert(value);
+ }
+
+ template<class P, typename std::enable_if<std::is_constructible<value_type, P&&>::value>::type* = nullptr>
+ std::pair<iterator, bool> insert(P&& value) {
+ return m_ht.emplace(std::forward<P>(value));
+ }
+
+ std::pair<iterator, bool> insert(value_type&& value) {
+ return m_ht.insert(std::move(value));
+ }
+
+
+ iterator insert(const_iterator hint, const value_type& value) {
+ return m_ht.insert(hint, value);
+ }
+
+ template<class P, typename std::enable_if<std::is_constructible<value_type, P&&>::value>::type* = nullptr>
+ iterator insert(const_iterator hint, P&& value) {
+ return m_ht.emplace_hint(hint, std::forward<P>(value));
+ }
+
+ iterator insert(const_iterator hint, value_type&& value) {
+ return m_ht.insert(hint, std::move(value));
+ }
+
+
+ template<class InputIt>
+ void insert(InputIt first, InputIt last) {
+ m_ht.insert(first, last);
+ }
+
+ void insert(std::initializer_list<value_type> ilist) {
+ m_ht.insert(ilist.begin(), ilist.end());
+ }
+
+
+
+
+ template<class M>
+ std::pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj) {
+ return m_ht.insert_or_assign(k, std::forward<M>(obj));
+ }
+
+ template<class M>
+ std::pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj) {
+ return m_ht.insert_or_assign(std::move(k), std::forward<M>(obj));
+ }
+
+ template<class M>
+ iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj) {
+ return m_ht.insert_or_assign(hint, k, std::forward<M>(obj));
+ }
+
+ template<class M>
+ iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj) {
+ return m_ht.insert_or_assign(hint, std::move(k), std::forward<M>(obj));
+ }
+
+
+
+ /**
+ * Due to the way elements are stored, emplace will need to move or copy the key-value once.
+ * The method is equivalent to insert(value_type(std::forward<Args>(args)...));
+ *
+ * Mainly here for compatibility with the std::unordered_map interface.
+ */
+ template<class... Args>
+ std::pair<iterator, bool> emplace(Args&&... args) {
+ return m_ht.emplace(std::forward<Args>(args)...);
+ }
+
+
+
+ /**
+ * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once.
+ * The method is equivalent to insert(hint, value_type(std::forward<Args>(args)...));
+ *
+ * Mainly here for compatibility with the std::unordered_map interface.
+ */
+ template<class... Args>
+ iterator emplace_hint(const_iterator hint, Args&&... args) {
+ return m_ht.emplace_hint(hint, std::forward<Args>(args)...);
+ }
+
+
+
+
+ template<class... Args>
+ std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args) {
+ return m_ht.try_emplace(k, std::forward<Args>(args)...);
+ }
+
+ template<class... Args>
+ std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args) {
+ return m_ht.try_emplace(std::move(k), std::forward<Args>(args)...);
+ }
+
+ template<class... Args>
+ iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) {
+ return m_ht.try_emplace(hint, k, std::forward<Args>(args)...);
+ }
+
+ template<class... Args>
+ iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) {
+ return m_ht.try_emplace(hint, std::move(k), std::forward<Args>(args)...);
+ }
+
+
+
+
+ iterator erase(iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); }
+ size_type erase(const key_type& key) { return m_ht.erase(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup to the value if you already have the hash.
+ */
+ size_type erase(const key_type& key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type erase(const K& key) { return m_ht.erase(key); }
+
+ /**
+ * @copydoc erase(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup to the value if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type erase(const K& key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+
+
+ void swap(robin_map& other) { other.m_ht.swap(m_ht); }
+
+
+
+ /*
+ * Lookup
+ */
+ T& at(const Key& key) { return m_ht.at(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ T& at(const Key& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); }
+
+
+ const T& at(const Key& key) const { return m_ht.at(key); }
+
+ /**
+ * @copydoc at(const Key& key, std::size_t precalculated_hash)
+ */
+ const T& at(const Key& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); }
+
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ T& at(const K& key) { return m_ht.at(key); }
+
+ /**
+ * @copydoc at(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ T& at(const K& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); }
+
+
+ /**
+ * @copydoc at(const K& key)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ const T& at(const K& key) const { return m_ht.at(key); }
+
+ /**
+ * @copydoc at(const K& key, std::size_t precalculated_hash)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ const T& at(const K& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); }
+
+
+
+
+ T& operator[](const Key& key) { return m_ht[key]; }
+ T& operator[](Key&& key) { return m_ht[std::move(key)]; }
+
+
+
+
+ size_type count(const Key& key) const { return m_ht.count(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ size_type count(const Key& key, std::size_t precalculated_hash) const {
+ return m_ht.count(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type count(const K& key) const { return m_ht.count(key); }
+
+ /**
+ * @copydoc count(const K& key) const
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type count(const K& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); }
+
+
+
+
+ iterator find(const Key& key) { return m_ht.find(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); }
+
+ const_iterator find(const Key& key) const { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const Key& key, std::size_t precalculated_hash)
+ */
+ const_iterator find(const Key& key, std::size_t precalculated_hash) const {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ iterator find(const K& key) { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); }
+
+ /**
+ * @copydoc find(const K& key)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ const_iterator find(const K& key) const { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ const_iterator find(const K& key, std::size_t precalculated_hash) const {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+
+
+
+ std::pair<iterator, iterator> equal_range(const Key& key) { return m_ht.equal_range(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ std::pair<iterator, iterator> equal_range(const Key& key, std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ std::pair<const_iterator, const_iterator> equal_range(const Key& key) const { return m_ht.equal_range(key); }
+
+ /**
+ * @copydoc equal_range(const Key& key, std::size_t precalculated_hash)
+ */
+ std::pair<const_iterator, const_iterator> equal_range(const Key& key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<iterator, iterator> equal_range(const K& key) { return m_ht.equal_range(key); }
+
+
+ /**
+ * @copydoc equal_range(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<iterator, iterator> equal_range(const K& key, std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(const K& key) const { return m_ht.equal_range(key); }
+
+ /**
+ * @copydoc equal_range(const K& key, std::size_t precalculated_hash)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(const K& key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+
+
+
+ /*
+ * Bucket interface
+ */
+ size_type bucket_count() const { return m_ht.bucket_count(); }
+ size_type max_bucket_count() const { return m_ht.max_bucket_count(); }
+
+
+ /*
+ * Hash policy
+ */
+ float load_factor() const { return m_ht.load_factor(); }
+ float max_load_factor() const { return m_ht.max_load_factor(); }
+ void max_load_factor(float ml) { m_ht.max_load_factor(ml); }
+
+ void rehash(size_type count) { m_ht.rehash(count); }
+ void reserve(size_type count) { m_ht.reserve(count); }
+
+
+ /*
+ * Observers
+ */
+ hasher hash_function() const { return m_ht.hash_function(); }
+ key_equal key_eq() const { return m_ht.key_eq(); }
+
+ /*
+ * Other
+ */
+
+ /**
+ * Convert a const_iterator to an iterator.
+ */
+ iterator mutable_iterator(const_iterator pos) {
+ return m_ht.mutable_iterator(pos);
+ }
+
+ friend bool operator==(const robin_map& lhs, const robin_map& rhs) {
+ if(lhs.size() != rhs.size()) {
+ return false;
+ }
+
+ for(const auto& element_lhs: lhs) {
+ const auto it_element_rhs = rhs.find(element_lhs.first);
+ if(it_element_rhs == rhs.cend() || element_lhs.second != it_element_rhs->second) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ friend bool operator!=(const robin_map& lhs, const robin_map& rhs) {
+ return !operator==(lhs, rhs);
+ }
+
+ friend void swap(robin_map& lhs, robin_map& rhs) {
+ lhs.swap(rhs);
+ }
+
+private:
+ ht m_ht;
+};
+
+
+/**
+ * Same as `tsl::robin_map<Key, T, Hash, KeyEqual, Allocator, StoreHash, tsl::rh::prime_growth_policy>`.
+ */
+template<class Key,
+ class T,
+ class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<std::pair<Key, T>>,
+ bool StoreHash = false>
+using robin_pg_map = robin_map<Key, T, Hash, KeyEqual, Allocator, StoreHash, tsl::rh::prime_growth_policy>;
+
+} // end namespace tsl
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_set.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_set.h
new file mode 100644
index 0000000..4e4667e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/robin_set.h
@@ -0,0 +1,535 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Tessil
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_ROBIN_SET_H
+#define TSL_ROBIN_SET_H
+
+
+#include <cstddef>
+#include <functional>
+#include <initializer_list>
+#include <memory>
+#include <type_traits>
+#include <utility>
+#include "robin_hash.h"
+
+
+namespace tsl {
+
+
+/**
+ * Implementation of a hash set using open-adressing and the robin hood hashing algorithm with backward shift deletion.
+ *
+ * For operations modifying the hash set (insert, erase, rehash, ...), the strong exception guarantee
+ * is only guaranteed when the expression `std::is_nothrow_swappable<Key>::value &&
+ * std::is_nothrow_move_constructible<Key>::value` is true, otherwise if an exception
+ * is thrown during the swap or the move, the hash set may end up in a undefined state. Per the standard
+ * a `Key` with a noexcept copy constructor and no move constructor also satisfies the
+ * `std::is_nothrow_move_constructible<Key>::value` criterion (and will thus guarantee the
+ * strong exception for the set).
+ *
+ * When `StoreHash` is true, 32 bits of the hash are stored alongside the values. It can improve
+ * the performance during lookups if the `KeyEqual` function takes time (or engenders a cache-miss for example)
+ * as we then compare the stored hashes before comparing the keys. When `tsl::rh::power_of_two_growth_policy` is used
+ * as `GrowthPolicy`, it may also speed-up the rehash process as we can avoid to recalculate the hash.
+ * When it is detected that storing the hash will not incur any memory penality due to alignement (i.e.
+ * `sizeof(tsl::detail_robin_hash::bucket_entry<ValueType, true>) ==
+ * sizeof(tsl::detail_robin_hash::bucket_entry<ValueType, false>)`) and `tsl::rh::power_of_two_growth_policy` is
+ * used, the hash will be stored even if `StoreHash` is false so that we can speed-up the rehash (but it will
+ * not be used on lookups unless `StoreHash` is true).
+ *
+ * `GrowthPolicy` defines how the set grows and consequently how a hash value is mapped to a bucket.
+ * By default the set uses `tsl::rh::power_of_two_growth_policy`. This policy keeps the number of buckets
+ * to a power of two and uses a mask to set the hash to a bucket instead of the slow modulo.
+ * Other growth policies are available and you may define your own growth policy,
+ * check `tsl::rh::power_of_two_growth_policy` for the interface.
+ *
+ * If the destructor of `Key` throws an exception, the behaviour of the class is undefined.
+ *
+ * Iterators invalidation:
+ * - clear, operator=, reserve, rehash: always invalidate the iterators.
+ * - insert, emplace, emplace_hint, operator[]: if there is an effective insert, invalidate the iterators.
+ * - erase: always invalidate the iterators.
+ */
+template<class Key,
+ class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<Key>,
+ bool StoreHash = false,
+ class GrowthPolicy = tsl::rh::power_of_two_growth_policy<2>>
+class robin_set {
+private:
+ template<typename U>
+ using has_is_transparent = tsl::detail_robin_hash::has_is_transparent<U>;
+
+ class KeySelect {
+ public:
+ using key_type = Key;
+
+ const key_type& operator()(const Key& key) const noexcept {
+ return key;
+ }
+
+ key_type& operator()(Key& key) noexcept {
+ return key;
+ }
+ };
+
+ using ht = detail_robin_hash::robin_hash<Key, KeySelect, void,
+ Hash, KeyEqual, Allocator, StoreHash, GrowthPolicy>;
+
+public:
+ using key_type = typename ht::key_type;
+ using value_type = typename ht::value_type;
+ using size_type = typename ht::size_type;
+ using difference_type = typename ht::difference_type;
+ using hasher = typename ht::hasher;
+ using key_equal = typename ht::key_equal;
+ using allocator_type = typename ht::allocator_type;
+ using reference = typename ht::reference;
+ using const_reference = typename ht::const_reference;
+ using pointer = typename ht::pointer;
+ using const_pointer = typename ht::const_pointer;
+ using iterator = typename ht::iterator;
+ using const_iterator = typename ht::const_iterator;
+
+
+ /*
+ * Constructors
+ */
+ robin_set(): robin_set(ht::DEFAULT_INIT_BUCKETS_SIZE) {
+ }
+
+ explicit robin_set(size_type bucket_count,
+ const Hash& hash = Hash(),
+ const KeyEqual& equal = KeyEqual(),
+ const Allocator& alloc = Allocator()):
+ m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR)
+ {
+ }
+
+ robin_set(size_type bucket_count,
+ const Allocator& alloc): robin_set(bucket_count, Hash(), KeyEqual(), alloc)
+ {
+ }
+
+ robin_set(size_type bucket_count,
+ const Hash& hash,
+ const Allocator& alloc): robin_set(bucket_count, hash, KeyEqual(), alloc)
+ {
+ }
+
+ explicit robin_set(const Allocator& alloc): robin_set(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) {
+ }
+
+ template<class InputIt>
+ robin_set(InputIt first, InputIt last,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE,
+ const Hash& hash = Hash(),
+ const KeyEqual& equal = KeyEqual(),
+ const Allocator& alloc = Allocator()): robin_set(bucket_count, hash, equal, alloc)
+ {
+ insert(first, last);
+ }
+
+ template<class InputIt>
+ robin_set(InputIt first, InputIt last,
+ size_type bucket_count,
+ const Allocator& alloc): robin_set(first, last, bucket_count, Hash(), KeyEqual(), alloc)
+ {
+ }
+
+ template<class InputIt>
+ robin_set(InputIt first, InputIt last,
+ size_type bucket_count,
+ const Hash& hash,
+ const Allocator& alloc): robin_set(first, last, bucket_count, hash, KeyEqual(), alloc)
+ {
+ }
+
+ robin_set(std::initializer_list<value_type> init,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE,
+ const Hash& hash = Hash(),
+ const KeyEqual& equal = KeyEqual(),
+ const Allocator& alloc = Allocator()):
+ robin_set(init.begin(), init.end(), bucket_count, hash, equal, alloc)
+ {
+ }
+
+ robin_set(std::initializer_list<value_type> init,
+ size_type bucket_count,
+ const Allocator& alloc):
+ robin_set(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc)
+ {
+ }
+
+ robin_set(std::initializer_list<value_type> init,
+ size_type bucket_count,
+ const Hash& hash,
+ const Allocator& alloc):
+ robin_set(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc)
+ {
+ }
+
+
+ robin_set& operator=(std::initializer_list<value_type> ilist) {
+ m_ht.clear();
+
+ m_ht.reserve(ilist.size());
+ m_ht.insert(ilist.begin(), ilist.end());
+
+ return *this;
+ }
+
+ allocator_type get_allocator() const { return m_ht.get_allocator(); }
+
+
+ /*
+ * Iterators
+ */
+ iterator begin() noexcept { return m_ht.begin(); }
+ const_iterator begin() const noexcept { return m_ht.begin(); }
+ const_iterator cbegin() const noexcept { return m_ht.cbegin(); }
+
+ iterator end() noexcept { return m_ht.end(); }
+ const_iterator end() const noexcept { return m_ht.end(); }
+ const_iterator cend() const noexcept { return m_ht.cend(); }
+
+
+ /*
+ * Capacity
+ */
+ bool empty() const noexcept { return m_ht.empty(); }
+ size_type size() const noexcept { return m_ht.size(); }
+ size_type max_size() const noexcept { return m_ht.max_size(); }
+
+ /*
+ * Modifiers
+ */
+ void clear() noexcept { m_ht.clear(); }
+
+
+
+
+ std::pair<iterator, bool> insert(const value_type& value) {
+ return m_ht.insert(value);
+ }
+
+ std::pair<iterator, bool> insert(value_type&& value) {
+ return m_ht.insert(std::move(value));
+ }
+
+ iterator insert(const_iterator hint, const value_type& value) {
+ return m_ht.insert(hint, value);
+ }
+
+ iterator insert(const_iterator hint, value_type&& value) {
+ return m_ht.insert(hint, std::move(value));
+ }
+
+ template<class InputIt>
+ void insert(InputIt first, InputIt last) {
+ m_ht.insert(first, last);
+ }
+
+ void insert(std::initializer_list<value_type> ilist) {
+ m_ht.insert(ilist.begin(), ilist.end());
+ }
+
+
+
+
+ /**
+ * Due to the way elements are stored, emplace will need to move or copy the key-value once.
+ * The method is equivalent to insert(value_type(std::forward<Args>(args)...));
+ *
+ * Mainly here for compatibility with the std::unordered_map interface.
+ */
+ template<class... Args>
+ std::pair<iterator, bool> emplace(Args&&... args) {
+ return m_ht.emplace(std::forward<Args>(args)...);
+ }
+
+
+
+ /**
+ * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once.
+ * The method is equivalent to insert(hint, value_type(std::forward<Args>(args)...));
+ *
+ * Mainly here for compatibility with the std::unordered_map interface.
+ */
+ template<class... Args>
+ iterator emplace_hint(const_iterator hint, Args&&... args) {
+ return m_ht.emplace_hint(hint, std::forward<Args>(args)...);
+ }
+
+
+
+ iterator erase(iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); }
+ size_type erase(const key_type& key) { return m_ht.erase(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup to the value if you already have the hash.
+ */
+ size_type erase(const key_type& key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type erase(const K& key) { return m_ht.erase(key); }
+
+ /**
+ * @copydoc erase(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup to the value if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type erase(const K& key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+
+
+ void swap(robin_set& other) { other.m_ht.swap(m_ht); }
+
+
+
+ /*
+ * Lookup
+ */
+ size_type count(const Key& key) const { return m_ht.count(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ size_type count(const Key& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type count(const K& key) const { return m_ht.count(key); }
+
+ /**
+ * @copydoc count(const K& key) const
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ size_type count(const K& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); }
+
+
+
+
+ iterator find(const Key& key) { return m_ht.find(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); }
+
+ const_iterator find(const Key& key) const { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const Key& key, std::size_t precalculated_hash)
+ */
+ const_iterator find(const Key& key, std::size_t precalculated_hash) const { return m_ht.find(key, precalculated_hash); }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ iterator find(const K& key) { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); }
+
+ /**
+ * @copydoc find(const K& key)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ const_iterator find(const K& key) const { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ const_iterator find(const K& key, std::size_t precalculated_hash) const { return m_ht.find(key, precalculated_hash); }
+
+
+
+
+ std::pair<iterator, iterator> equal_range(const Key& key) { return m_ht.equal_range(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ std::pair<iterator, iterator> equal_range(const Key& key, std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ std::pair<const_iterator, const_iterator> equal_range(const Key& key) const { return m_ht.equal_range(key); }
+
+ /**
+ * @copydoc equal_range(const Key& key, std::size_t precalculated_hash)
+ */
+ std::pair<const_iterator, const_iterator> equal_range(const Key& key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists.
+ * If so, K must be hashable and comparable to Key.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<iterator, iterator> equal_range(const K& key) { return m_ht.equal_range(key); }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same
+ * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash.
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<iterator, iterator> equal_range(const K& key, std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(const K& key) const { return m_ht.equal_range(key); }
+
+ /**
+ * @copydoc equal_range(const K& key, std::size_t precalculated_hash)
+ */
+ template<class K, class KE = KeyEqual, typename std::enable_if<has_is_transparent<KE>::value>::type* = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(const K& key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+
+
+
+ /*
+ * Bucket interface
+ */
+ size_type bucket_count() const { return m_ht.bucket_count(); }
+ size_type max_bucket_count() const { return m_ht.max_bucket_count(); }
+
+
+ /*
+ * Hash policy
+ */
+ float load_factor() const { return m_ht.load_factor(); }
+ float max_load_factor() const { return m_ht.max_load_factor(); }
+ void max_load_factor(float ml) { m_ht.max_load_factor(ml); }
+
+ void rehash(size_type count) { m_ht.rehash(count); }
+ void reserve(size_type count) { m_ht.reserve(count); }
+
+
+ /*
+ * Observers
+ */
+ hasher hash_function() const { return m_ht.hash_function(); }
+ key_equal key_eq() const { return m_ht.key_eq(); }
+
+
+ /*
+ * Other
+ */
+
+ /**
+ * Convert a const_iterator to an iterator.
+ */
+ iterator mutable_iterator(const_iterator pos) {
+ return m_ht.mutable_iterator(pos);
+ }
+
+ friend bool operator==(const robin_set& lhs, const robin_set& rhs) {
+ if(lhs.size() != rhs.size()) {
+ return false;
+ }
+
+ for(const auto& element_lhs: lhs) {
+ const auto it_element_rhs = rhs.find(element_lhs);
+ if(it_element_rhs == rhs.cend()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ friend bool operator!=(const robin_set& lhs, const robin_set& rhs) {
+ return !operator==(lhs, rhs);
+ }
+
+ friend void swap(robin_set& lhs, robin_set& rhs) {
+ lhs.swap(rhs);
+ }
+
+private:
+ ht m_ht;
+};
+
+
+/**
+ * Same as `tsl::robin_set<Key, Hash, KeyEqual, Allocator, StoreHash, tsl::rh::prime_growth_policy>`.
+ */
+template<class Key,
+ class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<Key>,
+ bool StoreHash = false>
+using robin_pg_set = robin_set<Key, Hash, KeyEqual, Allocator, StoreHash, tsl::rh::prime_growth_policy>;
+
+} // end namespace tsl
+
+#endif
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_growth_policy.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_growth_policy.h
new file mode 100644
index 0000000..d73aaaf
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_growth_policy.h
@@ -0,0 +1,301 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Thibaut Goetghebuer-Planchon <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_SPARSE_GROWTH_POLICY_H
+#define TSL_SPARSE_GROWTH_POLICY_H
+
+#include <algorithm>
+#include <array>
+#include <climits>
+#include <cmath>
+#include <cstddef>
+#include <iterator>
+#include <limits>
+#include <ratio>
+#include <stdexcept>
+
+namespace tsl {
+namespace sh {
+
+/**
+ * Grow the hash table by a factor of GrowthFactor keeping the bucket count to a
+ * power of two. It allows the table to use a mask operation instead of a modulo
+ * operation to map a hash to a bucket.
+ *
+ * GrowthFactor must be a power of two >= 2.
+ */
+template <std::size_t GrowthFactor>
+class power_of_two_growth_policy {
+ public:
+ /**
+ * Called on the hash table creation and on rehash. The number of buckets for
+ * the table is passed in parameter. This number is a minimum, the policy may
+ * update this value with a higher value if needed (but not lower).
+ *
+ * If 0 is given, min_bucket_count_in_out must still be 0 after the policy
+ * creation and bucket_for_hash must always return 0 in this case.
+ */
+ explicit power_of_two_growth_policy(std::size_t &min_bucket_count_in_out) {
+ if (min_bucket_count_in_out > max_bucket_count()) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ if (min_bucket_count_in_out > 0) {
+ min_bucket_count_in_out =
+ round_up_to_power_of_two(min_bucket_count_in_out);
+ m_mask = min_bucket_count_in_out - 1;
+ } else {
+ m_mask = 0;
+ }
+ }
+
+ /**
+ * Return the bucket [0, bucket_count()) to which the hash belongs.
+ * If bucket_count() is 0, it must always return 0.
+ */
+ std::size_t bucket_for_hash(std::size_t hash) const noexcept {
+ return hash & m_mask;
+ }
+
+ /**
+ * Return the number of buckets that should be used on next growth.
+ */
+ std::size_t next_bucket_count() const {
+ if ((m_mask + 1) > max_bucket_count() / GrowthFactor) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ return (m_mask + 1) * GrowthFactor;
+ }
+
+ /**
+ * Return the maximum number of buckets supported by the policy.
+ */
+ std::size_t max_bucket_count() const {
+ // Largest power of two.
+ return (std::numeric_limits<std::size_t>::max() / 2) + 1;
+ }
+
+ /**
+ * Reset the growth policy as if it was created with a bucket count of 0.
+ * After a clear, the policy must always return 0 when bucket_for_hash is
+ * called.
+ */
+ void clear() noexcept { m_mask = 0; }
+
+ private:
+ static std::size_t round_up_to_power_of_two(std::size_t value) {
+ if (is_power_of_two(value)) {
+ return value;
+ }
+
+ if (value == 0) {
+ return 1;
+ }
+
+ --value;
+ for (std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) {
+ value |= value >> i;
+ }
+
+ return value + 1;
+ }
+
+ static constexpr bool is_power_of_two(std::size_t value) {
+ return value != 0 && (value & (value - 1)) == 0;
+ }
+
+ protected:
+ static_assert(is_power_of_two(GrowthFactor) && GrowthFactor >= 2,
+ "GrowthFactor must be a power of two >= 2.");
+
+ std::size_t m_mask;
+};
+
+/**
+ * Grow the hash table by GrowthFactor::num / GrowthFactor::den and use a modulo
+ * to map a hash to a bucket. Slower but it can be useful if you want a slower
+ * growth.
+ */
+template <class GrowthFactor = std::ratio<3, 2>>
+class mod_growth_policy {
+ public:
+ explicit mod_growth_policy(std::size_t &min_bucket_count_in_out) {
+ if (min_bucket_count_in_out > max_bucket_count()) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ if (min_bucket_count_in_out > 0) {
+ m_mod = min_bucket_count_in_out;
+ } else {
+ m_mod = 1;
+ }
+ }
+
+ std::size_t bucket_for_hash(std::size_t hash) const noexcept {
+ return hash % m_mod;
+ }
+
+ std::size_t next_bucket_count() const {
+ if (m_mod == max_bucket_count()) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ const double next_bucket_count =
+ std::ceil(double(m_mod) * REHASH_SIZE_MULTIPLICATION_FACTOR);
+ if (!std::isnormal(next_bucket_count)) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ if (next_bucket_count > double(max_bucket_count())) {
+ return max_bucket_count();
+ } else {
+ return std::size_t(next_bucket_count);
+ }
+ }
+
+ std::size_t max_bucket_count() const { return MAX_BUCKET_COUNT; }
+
+ void clear() noexcept { m_mod = 1; }
+
+ private:
+ static constexpr double REHASH_SIZE_MULTIPLICATION_FACTOR =
+ 1.0 * GrowthFactor::num / GrowthFactor::den;
+ static const std::size_t MAX_BUCKET_COUNT =
+ std::size_t(double(std::numeric_limits<std::size_t>::max() /
+ REHASH_SIZE_MULTIPLICATION_FACTOR));
+
+ static_assert(REHASH_SIZE_MULTIPLICATION_FACTOR >= 1.1,
+ "Growth factor should be >= 1.1.");
+
+ std::size_t m_mod;
+};
+
+/**
+ * Grow the hash table by using prime numbers as bucket count. Slower than
+ * tsl::sh::power_of_two_growth_policy in general but will probably distribute
+ * the values around better in the buckets with a poor hash function.
+ *
+ * To allow the compiler to optimize the modulo operation, a lookup table is
+ * used with constant primes numbers.
+ *
+ * With a switch the code would look like:
+ * \code
+ * switch(iprime) { // iprime is the current prime of the hash table
+ * case 0: hash % 5ul;
+ * break;
+ * case 1: hash % 17ul;
+ * break;
+ * case 2: hash % 29ul;
+ * break;
+ * ...
+ * }
+ * \endcode
+ *
+ * Due to the constant variable in the modulo the compiler is able to optimize
+ * the operation by a series of multiplications, substractions and shifts.
+ *
+ * The 'hash % 5' could become something like 'hash - (hash * 0xCCCCCCCD) >> 34)
+ * * 5' in a 64 bits environment.
+ */
+class prime_growth_policy {
+ public:
+ explicit prime_growth_policy(std::size_t &min_bucket_count_in_out) {
+ auto it_prime = std::lower_bound(primes().begin(), primes().end(),
+ min_bucket_count_in_out);
+ if (it_prime == primes().end()) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ m_iprime =
+ static_cast<unsigned int>(std::distance(primes().begin(), it_prime));
+ if (min_bucket_count_in_out > 0) {
+ min_bucket_count_in_out = *it_prime;
+ } else {
+ min_bucket_count_in_out = 0;
+ }
+ }
+
+ std::size_t bucket_for_hash(std::size_t hash) const noexcept {
+ return mod_prime()[m_iprime](hash);
+ }
+
+ std::size_t next_bucket_count() const {
+ if (m_iprime + 1 >= primes().size()) {
+ throw std::length_error("The hash table exceeds its maximum size.");
+ }
+
+ return primes()[m_iprime + 1];
+ }
+
+ std::size_t max_bucket_count() const { return primes().back(); }
+
+ void clear() noexcept { m_iprime = 0; }
+
+ private:
+ static const std::array<std::size_t, 40> &primes() {
+ static const std::array<std::size_t, 40> PRIMES = {
+ {1ul, 5ul, 17ul, 29ul, 37ul,
+ 53ul, 67ul, 79ul, 97ul, 131ul,
+ 193ul, 257ul, 389ul, 521ul, 769ul,
+ 1031ul, 1543ul, 2053ul, 3079ul, 6151ul,
+ 12289ul, 24593ul, 49157ul, 98317ul, 196613ul,
+ 393241ul, 786433ul, 1572869ul, 3145739ul, 6291469ul,
+ 12582917ul, 25165843ul, 50331653ul, 100663319ul, 201326611ul,
+ 402653189ul, 805306457ul, 1610612741ul, 3221225473ul, 4294967291ul}};
+
+ static_assert(
+ std::numeric_limits<decltype(m_iprime)>::max() >= PRIMES.size(),
+ "The type of m_iprime is not big enough.");
+
+ return PRIMES;
+ }
+
+ static const std::array<std::size_t (*)(std::size_t), 40> &mod_prime() {
+ // MOD_PRIME[iprime](hash) returns hash % PRIMES[iprime]. This table allows
+ // for faster modulo as the compiler can optimize the modulo code better
+ // with a constant known at the compilation.
+ static const std::array<std::size_t (*)(std::size_t), 40> MOD_PRIME = {
+ {&mod<0>, &mod<1>, &mod<2>, &mod<3>, &mod<4>, &mod<5>, &mod<6>,
+ &mod<7>, &mod<8>, &mod<9>, &mod<10>, &mod<11>, &mod<12>, &mod<13>,
+ &mod<14>, &mod<15>, &mod<16>, &mod<17>, &mod<18>, &mod<19>, &mod<20>,
+ &mod<21>, &mod<22>, &mod<23>, &mod<24>, &mod<25>, &mod<26>, &mod<27>,
+ &mod<28>, &mod<29>, &mod<30>, &mod<31>, &mod<32>, &mod<33>, &mod<34>,
+ &mod<35>, &mod<36>, &mod<37>, &mod<38>, &mod<39>}};
+
+ return MOD_PRIME;
+ }
+
+ template <unsigned int IPrime>
+ static std::size_t mod(std::size_t hash) {
+ return hash % primes()[IPrime];
+ }
+
+ private:
+ unsigned int m_iprime;
+};
+
+} // namespace sh
+} // namespace tsl
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_hash.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_hash.h
new file mode 100644
index 0000000..e2115b4
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_hash.h
@@ -0,0 +1,2215 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Thibaut Goetghebuer-Planchon <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_SPARSE_HASH_H
+#define TSL_SPARSE_HASH_H
+
+#include <algorithm>
+#include <cassert>
+#include <climits>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <iterator>
+#include <limits>
+#include <memory>
+#include <stdexcept>
+#include <tuple>
+#include <type_traits>
+#include <utility>
+#include <vector>
+
+#include "sparse_growth_policy.h"
+
+#ifdef __INTEL_COMPILER
+#include <immintrin.h> // For _popcnt32 and _popcnt64
+#endif
+
+#ifdef _MSC_VER
+#include <intrin.h> // For __cpuid, __popcnt and __popcnt64
+#endif
+
+#ifdef TSL_DEBUG
+#define tsl_sh_assert(expr) assert(expr)
+#else
+#define tsl_sh_assert(expr) (static_cast<void>(0))
+#endif
+
+namespace tsl {
+
+namespace sh {
+enum class probing { linear, quadratic };
+
+enum class exception_safety { basic, strong };
+
+enum class sparsity { high, medium, low };
+} // namespace sh
+
+namespace detail_popcount {
+/**
+ * Define the popcount(ll) methods and pick-up the best depending on the
+ * compiler.
+ */
+
+// From Wikipedia: https://en.wikipedia.org/wiki/Hamming_weight
+inline int fallback_popcountll(unsigned long long int x) {
+ static_assert(
+ sizeof(unsigned long long int) == sizeof(std::uint64_t),
+ "sizeof(unsigned long long int) must be equal to sizeof(std::uint64_t). "
+ "Open a feature request if you need support for a platform where it "
+ "isn't the case.");
+
+ const std::uint64_t m1 = 0x5555555555555555ull;
+ const std::uint64_t m2 = 0x3333333333333333ull;
+ const std::uint64_t m4 = 0x0f0f0f0f0f0f0f0full;
+ const std::uint64_t h01 = 0x0101010101010101ull;
+
+ x -= (x >> 1ull) & m1;
+ x = (x & m2) + ((x >> 2ull) & m2);
+ x = (x + (x >> 4ull)) & m4;
+ return static_cast<int>((x * h01) >> (64ull - 8ull));
+}
+
+inline int fallback_popcount(unsigned int x) {
+ static_assert(sizeof(unsigned int) == sizeof(std::uint32_t) ||
+ sizeof(unsigned int) == sizeof(std::uint64_t),
+ "sizeof(unsigned int) must be equal to sizeof(std::uint32_t) "
+ "or sizeof(std::uint64_t). "
+ "Open a feature request if you need support for a platform "
+ "where it isn't the case.");
+
+ if (sizeof(unsigned int) == sizeof(std::uint32_t)) {
+ const std::uint32_t m1 = 0x55555555;
+ const std::uint32_t m2 = 0x33333333;
+ const std::uint32_t m4 = 0x0f0f0f0f;
+ const std::uint32_t h01 = 0x01010101;
+
+ x -= (x >> 1) & m1;
+ x = (x & m2) + ((x >> 2) & m2);
+ x = (x + (x >> 4)) & m4;
+ return static_cast<int>((x * h01) >> (32 - 8));
+ } else {
+ return fallback_popcountll(x);
+ }
+}
+
+#if defined(__clang__) || defined(__GNUC__)
+inline int popcountll(unsigned long long int value) {
+ return __builtin_popcountll(value);
+}
+
+inline int popcount(unsigned int value) { return __builtin_popcount(value); }
+
+#elif defined(_MSC_VER)
+/**
+ * We need to check for popcount support at runtime on Windows with __cpuid
+ * See https://msdn.microsoft.com/en-us/library/bb385231.aspx
+ */
+inline bool has_popcount_support() {
+ int cpu_infos[4];
+ __cpuid(cpu_infos, 1);
+ return (cpu_infos[2] & (1 << 23)) != 0;
+}
+
+inline int popcountll(unsigned long long int value) {
+#ifdef _WIN64
+ static_assert(
+ sizeof(unsigned long long int) == sizeof(std::int64_t),
+ "sizeof(unsigned long long int) must be equal to sizeof(std::int64_t). ");
+
+ static const bool has_popcount = has_popcount_support();
+ return has_popcount
+ ? static_cast<int>(__popcnt64(static_cast<std::int64_t>(value)))
+ : fallback_popcountll(value);
+#else
+ return fallback_popcountll(value);
+#endif
+}
+
+inline int popcount(unsigned int value) {
+ static_assert(sizeof(unsigned int) == sizeof(std::int32_t),
+ "sizeof(unsigned int) must be equal to sizeof(std::int32_t). ");
+
+ static const bool has_popcount = has_popcount_support();
+ return has_popcount
+ ? static_cast<int>(__popcnt(static_cast<std::int32_t>(value)))
+ : fallback_popcount(value);
+}
+
+#elif defined(__INTEL_COMPILER)
+inline int popcountll(unsigned long long int value) {
+ static_assert(sizeof(unsigned long long int) == sizeof(__int64), "");
+ return _popcnt64(static_cast<__int64>(value));
+}
+
+inline int popcount(unsigned int value) {
+ return _popcnt32(static_cast<int>(value));
+}
+
+#else
+inline int popcountll(unsigned long long int x) {
+ return fallback_popcountll(x);
+}
+
+inline int popcount(unsigned int x) { return fallback_popcount(x); }
+
+#endif
+} // namespace detail_popcount
+
+namespace detail_sparse_hash {
+
+template <typename T>
+struct make_void {
+ using type = void;
+};
+
+template <typename T, typename = void>
+struct has_is_transparent : std::false_type {};
+
+template <typename T>
+struct has_is_transparent<T,
+ typename make_void<typename T::is_transparent>::type>
+ : std::true_type {};
+
+template <typename U>
+struct is_power_of_two_policy : std::false_type {};
+
+template <std::size_t GrowthFactor>
+struct is_power_of_two_policy<tsl::sh::power_of_two_growth_policy<GrowthFactor>>
+ : std::true_type {};
+
+inline constexpr bool is_power_of_two(std::size_t value) {
+ return value != 0 && (value & (value - 1)) == 0;
+}
+
+inline std::size_t round_up_to_power_of_two(std::size_t value) {
+ if (is_power_of_two(value)) {
+ return value;
+ }
+
+ if (value == 0) {
+ return 1;
+ }
+
+ --value;
+ for (std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) {
+ value |= value >> i;
+ }
+
+ return value + 1;
+}
+
+template <typename T, typename U>
+static T numeric_cast(U value,
+ const char *error_message = "numeric_cast() failed.") {
+ T ret = static_cast<T>(value);
+ if (static_cast<U>(ret) != value) {
+ throw std::runtime_error(error_message);
+ }
+
+ const bool is_same_signedness =
+ (std::is_unsigned<T>::value && std::is_unsigned<U>::value) ||
+ (std::is_signed<T>::value && std::is_signed<U>::value);
+ if (!is_same_signedness && (ret < T{}) != (value < U{})) {
+ throw std::runtime_error(error_message);
+ }
+
+ return ret;
+}
+
+/**
+ * Fixed size type used to represent size_type values on serialization. Need to
+ * be big enough to represent a std::size_t on 32 and 64 bits platforms, and
+ * must be the same size on both platforms.
+ */
+using slz_size_type = std::uint64_t;
+static_assert(std::numeric_limits<slz_size_type>::max() >=
+ std::numeric_limits<std::size_t>::max(),
+ "slz_size_type must be >= std::size_t");
+
+template <class T, class Deserializer>
+static T deserialize_value(Deserializer &deserializer) {
+ // MSVC < 2017 is not conformant, circumvent the problem by removing the
+ // template keyword
+#if defined(_MSC_VER) && _MSC_VER < 1910
+ return deserializer.Deserializer::operator()<T>();
+#else
+ return deserializer.Deserializer::template operator()<T>();
+#endif
+}
+
+/**
+ * WARNING: the sparse_array class doesn't free the ressources allocated through
+ * the allocator passed in parameter in each method. You have to manually call
+ * `clear(Allocator&)` when you don't need a sparse_array object anymore.
+ *
+ * The reason is that the sparse_array doesn't store the allocator to avoid
+ * wasting space in each sparse_array when the allocator has a size > 0. It only
+ * allocates/deallocates objects with the allocator that is passed in parameter.
+ *
+ *
+ *
+ * Index denotes a value between [0, BITMAP_NB_BITS), it is an index similar to
+ * std::vector. Offset denotes the real position in `m_values` corresponding to
+ * an index.
+ *
+ * We are using raw pointers instead of std::vector to avoid loosing
+ * 2*sizeof(size_t) bytes to store the capacity and size of the vector in each
+ * sparse_array. We know we can only store up to BITMAP_NB_BITS elements in the
+ * array, we don't need such big types.
+ *
+ *
+ * T must be nothrow move constructible and/or copy constructible.
+ * Behaviour is undefined if the destructor of T throws an exception.
+ *
+ * See https://smerity.com/articles/2015/google_sparsehash.html for details on
+ * the idea behinds the implementation.
+ *
+ * TODO Check to use std::realloc and std::memmove when possible
+ */
+template <typename T, typename Allocator, tsl::sh::sparsity Sparsity>
+class sparse_array {
+ public:
+ using value_type = T;
+ using size_type = std::uint_least8_t;
+ using allocator_type = Allocator;
+ using iterator = value_type *;
+ using const_iterator = const value_type *;
+
+ private:
+ static const size_type CAPACITY_GROWTH_STEP =
+ (Sparsity == tsl::sh::sparsity::high) ? 2
+ : (Sparsity == tsl::sh::sparsity::medium)
+ ? 4
+ : 8; // (Sparsity == tsl::sh::sparsity::low)
+
+ /**
+ * Bitmap size configuration.
+ * Use 32 bits for the bitmap on 32-bits or less environnement as popcount on
+ * 64 bits numbers is slow on these environnement. Use 64 bits bitmap
+ * otherwise.
+ */
+#if SIZE_MAX <= UINT32_MAX
+ using bitmap_type = std::uint_least32_t;
+ static const std::size_t BITMAP_NB_BITS = 32;
+ static const std::size_t BUCKET_SHIFT = 5;
+#else
+ using bitmap_type = std::uint_least64_t;
+ static const std::size_t BITMAP_NB_BITS = 64;
+ static const std::size_t BUCKET_SHIFT = 6;
+#endif
+
+ static const std::size_t BUCKET_MASK = BITMAP_NB_BITS - 1;
+
+ static_assert(is_power_of_two(BITMAP_NB_BITS),
+ "BITMAP_NB_BITS must be a power of two.");
+ static_assert(std::numeric_limits<bitmap_type>::digits >= BITMAP_NB_BITS,
+ "bitmap_type must be able to hold at least BITMAP_NB_BITS.");
+ static_assert((std::size_t(1) << BUCKET_SHIFT) == BITMAP_NB_BITS,
+ "(1 << BUCKET_SHIFT) must be equal to BITMAP_NB_BITS.");
+ static_assert(std::numeric_limits<size_type>::max() >= BITMAP_NB_BITS,
+ "size_type must be big enough to hold BITMAP_NB_BITS.");
+ static_assert(std::is_unsigned<bitmap_type>::value,
+ "bitmap_type must be unsigned.");
+ static_assert((std::numeric_limits<bitmap_type>::max() & BUCKET_MASK) ==
+ BITMAP_NB_BITS - 1,
+ "");
+
+ public:
+ /**
+ * Map an ibucket [0, bucket_count) in the hash table to a sparse_ibucket
+ * (a sparse_array holds multiple buckets, so there is less sparse_array than
+ * bucket_count).
+ *
+ * The bucket ibucket is in
+ * m_sparse_buckets[sparse_ibucket(ibucket)][index_in_sparse_bucket(ibucket)]
+ * instead of something like m_buckets[ibucket] in a classical hash table.
+ */
+ static std::size_t sparse_ibucket(std::size_t ibucket) {
+ return ibucket >> BUCKET_SHIFT;
+ }
+
+ /**
+ * Map an ibucket [0, bucket_count) in the hash table to an index in the
+ * sparse_array which corresponds to the bucket.
+ *
+ * The bucket ibucket is in
+ * m_sparse_buckets[sparse_ibucket(ibucket)][index_in_sparse_bucket(ibucket)]
+ * instead of something like m_buckets[ibucket] in a classical hash table.
+ */
+ static typename sparse_array::size_type index_in_sparse_bucket(
+ std::size_t ibucket) {
+ return static_cast<typename sparse_array::size_type>(
+ ibucket & sparse_array::BUCKET_MASK);
+ }
+
+ static std::size_t nb_sparse_buckets(std::size_t bucket_count) noexcept {
+ if (bucket_count == 0) {
+ return 0;
+ }
+
+ return std::max<std::size_t>(
+ 1, sparse_ibucket(tsl::detail_sparse_hash::round_up_to_power_of_two(
+ bucket_count)));
+ }
+
+ public:
+ sparse_array() noexcept
+ : m_values(nullptr),
+ m_bitmap_vals(0),
+ m_bitmap_deleted_vals(0),
+ m_nb_elements(0),
+ m_capacity(0),
+ m_last_array(false) {}
+
+ explicit sparse_array(bool last_bucket) noexcept
+ : m_values(nullptr),
+ m_bitmap_vals(0),
+ m_bitmap_deleted_vals(0),
+ m_nb_elements(0),
+ m_capacity(0),
+ m_last_array(last_bucket) {}
+
+ sparse_array(size_type capacity, Allocator &alloc)
+ : m_values(nullptr),
+ m_bitmap_vals(0),
+ m_bitmap_deleted_vals(0),
+ m_nb_elements(0),
+ m_capacity(capacity),
+ m_last_array(false) {
+ if (m_capacity > 0) {
+ m_values = alloc.allocate(m_capacity);
+ tsl_sh_assert(m_values !=
+ nullptr); // allocate should throw if there is a failure
+ }
+ }
+
+ sparse_array(const sparse_array &other, Allocator &alloc)
+ : m_values(nullptr),
+ m_bitmap_vals(other.m_bitmap_vals),
+ m_bitmap_deleted_vals(other.m_bitmap_deleted_vals),
+ m_nb_elements(0),
+ m_capacity(other.m_capacity),
+ m_last_array(other.m_last_array) {
+ tsl_sh_assert(other.m_capacity >= other.m_nb_elements);
+ if (m_capacity == 0) {
+ return;
+ }
+
+ m_values = alloc.allocate(m_capacity);
+ tsl_sh_assert(m_values !=
+ nullptr); // allocate should throw if there is a failure
+ try {
+ for (size_type i = 0; i < other.m_nb_elements; i++) {
+ construct_value(alloc, m_values + i, other.m_values[i]);
+ m_nb_elements++;
+ }
+ } catch (...) {
+ clear(alloc);
+ throw;
+ }
+ }
+
+ sparse_array(sparse_array &&other) noexcept
+ : m_values(other.m_values),
+ m_bitmap_vals(other.m_bitmap_vals),
+ m_bitmap_deleted_vals(other.m_bitmap_deleted_vals),
+ m_nb_elements(other.m_nb_elements),
+ m_capacity(other.m_capacity),
+ m_last_array(other.m_last_array) {
+ other.m_values = nullptr;
+ other.m_bitmap_vals = 0;
+ other.m_bitmap_deleted_vals = 0;
+ other.m_nb_elements = 0;
+ other.m_capacity = 0;
+ }
+
+ sparse_array(sparse_array &&other, Allocator &alloc)
+ : m_values(nullptr),
+ m_bitmap_vals(other.m_bitmap_vals),
+ m_bitmap_deleted_vals(other.m_bitmap_deleted_vals),
+ m_nb_elements(0),
+ m_capacity(other.m_capacity),
+ m_last_array(other.m_last_array) {
+ tsl_sh_assert(other.m_capacity >= other.m_nb_elements);
+ if (m_capacity == 0) {
+ return;
+ }
+
+ m_values = alloc.allocate(m_capacity);
+ tsl_sh_assert(m_values !=
+ nullptr); // allocate should throw if there is a failure
+ try {
+ for (size_type i = 0; i < other.m_nb_elements; i++) {
+ construct_value(alloc, m_values + i, std::move(other.m_values[i]));
+ m_nb_elements++;
+ }
+ } catch (...) {
+ clear(alloc);
+ throw;
+ }
+ }
+
+ sparse_array &operator=(const sparse_array &) = delete;
+ sparse_array &operator=(sparse_array &&) = delete;
+
+ ~sparse_array() noexcept {
+ // The code that manages the sparse_array must have called clear before
+ // destruction. See documentation of sparse_array for more details.
+ tsl_sh_assert(m_capacity == 0 && m_nb_elements == 0 && m_values == nullptr);
+ }
+
+ iterator begin() noexcept { return m_values; }
+ iterator end() noexcept { return m_values + m_nb_elements; }
+ const_iterator begin() const noexcept { return cbegin(); }
+ const_iterator end() const noexcept { return cend(); }
+ const_iterator cbegin() const noexcept { return m_values; }
+ const_iterator cend() const noexcept { return m_values + m_nb_elements; }
+
+ bool empty() const noexcept { return m_nb_elements == 0; }
+
+ size_type size() const noexcept { return m_nb_elements; }
+
+ void clear(allocator_type &alloc) noexcept {
+ destroy_and_deallocate_values(alloc, m_values, m_nb_elements, m_capacity);
+
+ m_values = nullptr;
+ m_bitmap_vals = 0;
+ m_bitmap_deleted_vals = 0;
+ m_nb_elements = 0;
+ m_capacity = 0;
+ }
+
+ bool last() const noexcept { return m_last_array; }
+
+ void set_as_last() noexcept { m_last_array = true; }
+
+ bool has_value(size_type index) const noexcept {
+ tsl_sh_assert(index < BITMAP_NB_BITS);
+ return (m_bitmap_vals & (bitmap_type(1) << index)) != 0;
+ }
+
+ bool has_deleted_value(size_type index) const noexcept {
+ tsl_sh_assert(index < BITMAP_NB_BITS);
+ return (m_bitmap_deleted_vals & (bitmap_type(1) << index)) != 0;
+ }
+
+ iterator value(size_type index) noexcept {
+ tsl_sh_assert(has_value(index));
+ return m_values + index_to_offset(index);
+ }
+
+ const_iterator value(size_type index) const noexcept {
+ tsl_sh_assert(has_value(index));
+ return m_values + index_to_offset(index);
+ }
+
+ /**
+ * Return iterator to set value.
+ */
+ template <typename... Args>
+ iterator set(allocator_type &alloc, size_type index, Args &&...value_args) {
+ tsl_sh_assert(!has_value(index));
+
+ const size_type offset = index_to_offset(index);
+ insert_at_offset(alloc, offset, std::forward<Args>(value_args)...);
+
+ m_bitmap_vals = (m_bitmap_vals | (bitmap_type(1) << index));
+ m_bitmap_deleted_vals =
+ (m_bitmap_deleted_vals & ~(bitmap_type(1) << index));
+
+ m_nb_elements++;
+
+ tsl_sh_assert(has_value(index));
+ tsl_sh_assert(!has_deleted_value(index));
+
+ return m_values + offset;
+ }
+
+ iterator erase(allocator_type &alloc, iterator position) {
+ const size_type offset =
+ static_cast<size_type>(std::distance(begin(), position));
+ return erase(alloc, position, offset_to_index(offset));
+ }
+
+ // Return the next value or end if no next value
+ iterator erase(allocator_type &alloc, iterator position, size_type index) {
+ tsl_sh_assert(has_value(index));
+ tsl_sh_assert(!has_deleted_value(index));
+
+ const size_type offset =
+ static_cast<size_type>(std::distance(begin(), position));
+ erase_at_offset(alloc, offset);
+
+ m_bitmap_vals = (m_bitmap_vals & ~(bitmap_type(1) << index));
+ m_bitmap_deleted_vals = (m_bitmap_deleted_vals | (bitmap_type(1) << index));
+
+ m_nb_elements--;
+
+ tsl_sh_assert(!has_value(index));
+ tsl_sh_assert(has_deleted_value(index));
+
+ return m_values + offset;
+ }
+
+ void swap(sparse_array &other) {
+ using std::swap;
+
+ swap(m_values, other.m_values);
+ swap(m_bitmap_vals, other.m_bitmap_vals);
+ swap(m_bitmap_deleted_vals, other.m_bitmap_deleted_vals);
+ swap(m_nb_elements, other.m_nb_elements);
+ swap(m_capacity, other.m_capacity);
+ swap(m_last_array, other.m_last_array);
+ }
+
+ static iterator mutable_iterator(const_iterator pos) {
+ return const_cast<iterator>(pos);
+ }
+
+ template <class Serializer>
+ void serialize(Serializer &serializer) const {
+ const slz_size_type sparse_bucket_size = m_nb_elements;
+ serializer(sparse_bucket_size);
+
+ const slz_size_type bitmap_vals = m_bitmap_vals;
+ serializer(bitmap_vals);
+
+ const slz_size_type bitmap_deleted_vals = m_bitmap_deleted_vals;
+ serializer(bitmap_deleted_vals);
+
+ for (const value_type &value : *this) {
+ serializer(value);
+ }
+ }
+
+ template <class Deserializer>
+ static sparse_array deserialize_hash_compatible(Deserializer &deserializer,
+ Allocator &alloc) {
+ const slz_size_type sparse_bucket_size =
+ deserialize_value<slz_size_type>(deserializer);
+ const slz_size_type bitmap_vals =
+ deserialize_value<slz_size_type>(deserializer);
+ const slz_size_type bitmap_deleted_vals =
+ deserialize_value<slz_size_type>(deserializer);
+
+ if (sparse_bucket_size > BITMAP_NB_BITS) {
+ throw std::runtime_error(
+ "Deserialized sparse_bucket_size is too big for the platform. "
+ "Maximum should be BITMAP_NB_BITS.");
+ }
+
+ sparse_array sarray;
+ if (sparse_bucket_size == 0) {
+ return sarray;
+ }
+
+ sarray.m_bitmap_vals = numeric_cast<bitmap_type>(
+ bitmap_vals, "Deserialized bitmap_vals is too big.");
+ sarray.m_bitmap_deleted_vals = numeric_cast<bitmap_type>(
+ bitmap_deleted_vals, "Deserialized bitmap_deleted_vals is too big.");
+
+ sarray.m_capacity = numeric_cast<size_type>(
+ sparse_bucket_size, "Deserialized sparse_bucket_size is too big.");
+ sarray.m_values = alloc.allocate(sarray.m_capacity);
+
+ try {
+ for (size_type ivalue = 0; ivalue < sarray.m_capacity; ivalue++) {
+ construct_value(alloc, sarray.m_values + ivalue,
+ deserialize_value<value_type>(deserializer));
+ sarray.m_nb_elements++;
+ }
+ } catch (...) {
+ sarray.clear(alloc);
+ throw;
+ }
+
+ return sarray;
+ }
+
+ /**
+ * Deserialize the values of the bucket and insert them all in sparse_hash
+ * through sparse_hash.insert(...).
+ */
+ template <class Deserializer, class SparseHash>
+ static void deserialize_values_into_sparse_hash(Deserializer &deserializer,
+ SparseHash &sparse_hash) {
+ const slz_size_type sparse_bucket_size =
+ deserialize_value<slz_size_type>(deserializer);
+
+ const slz_size_type bitmap_vals =
+ deserialize_value<slz_size_type>(deserializer);
+ static_cast<void>(bitmap_vals); // Ignore, not needed
+
+ const slz_size_type bitmap_deleted_vals =
+ deserialize_value<slz_size_type>(deserializer);
+ static_cast<void>(bitmap_deleted_vals); // Ignore, not needed
+
+ for (slz_size_type ivalue = 0; ivalue < sparse_bucket_size; ivalue++) {
+ sparse_hash.insert(deserialize_value<value_type>(deserializer));
+ }
+ }
+
+ private:
+ template <typename... Args>
+ static void construct_value(allocator_type &alloc, value_type *value,
+ Args &&...value_args) {
+ std::allocator_traits<allocator_type>::construct(
+ alloc, value, std::forward<Args>(value_args)...);
+ }
+
+ static void destroy_value(allocator_type &alloc, value_type *value) noexcept {
+ std::allocator_traits<allocator_type>::destroy(alloc, value);
+ }
+
+ static void destroy_and_deallocate_values(
+ allocator_type &alloc, value_type *values, size_type nb_values,
+ size_type capacity_values) noexcept {
+ for (size_type i = 0; i < nb_values; i++) {
+ destroy_value(alloc, values + i);
+ }
+
+ alloc.deallocate(values, capacity_values);
+ }
+
+ static size_type popcount(bitmap_type val) noexcept {
+ if (sizeof(bitmap_type) <= sizeof(unsigned int)) {
+ return static_cast<size_type>(
+ tsl::detail_popcount::popcount(static_cast<unsigned int>(val)));
+ } else {
+ return static_cast<size_type>(tsl::detail_popcount::popcountll(val));
+ }
+ }
+
+ size_type index_to_offset(size_type index) const noexcept {
+ tsl_sh_assert(index < BITMAP_NB_BITS);
+ return popcount(m_bitmap_vals &
+ ((bitmap_type(1) << index) - bitmap_type(1)));
+ }
+
+ // TODO optimize
+ size_type offset_to_index(size_type offset) const noexcept {
+ tsl_sh_assert(offset < m_nb_elements);
+
+ bitmap_type bitmap_vals = m_bitmap_vals;
+ size_type index = 0;
+ size_type nb_ones = 0;
+
+ while (bitmap_vals != 0) {
+ if ((bitmap_vals & 0x1) == 1) {
+ if (nb_ones == offset) {
+ break;
+ }
+
+ nb_ones++;
+ }
+
+ index++;
+ bitmap_vals = bitmap_vals >> 1;
+ }
+
+ return index;
+ }
+
+ size_type next_capacity() const noexcept {
+ return static_cast<size_type>(m_capacity + CAPACITY_GROWTH_STEP);
+ }
+
+ /**
+ * Insertion
+ *
+ * Two situations:
+ * - Either we are in a situation where
+ * std::is_nothrow_move_constructible<value_type>::value is true. In this
+ * case, on insertion we just reallocate m_values when we reach its capacity
+ * (i.e. m_nb_elements == m_capacity), otherwise we just put the new value at
+ * its appropriate place. We can easily keep the strong exception guarantee as
+ * moving the values around is safe.
+ * - Otherwise we are in a situation where
+ * std::is_nothrow_move_constructible<value_type>::value is false. In this
+ * case on EACH insertion we allocate a new area of m_nb_elements + 1 where we
+ * copy the values of m_values into it and put the new value there. On
+ * success, we set m_values to this new area. Even if slower, it's the only
+ * way to preserve to strong exception guarantee.
+ */
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<
+ std::is_nothrow_move_constructible<U>::value>::type * = nullptr>
+ void insert_at_offset(allocator_type &alloc, size_type offset,
+ Args &&...value_args) {
+ if (m_nb_elements < m_capacity) {
+ insert_at_offset_no_realloc(alloc, offset,
+ std::forward<Args>(value_args)...);
+ } else {
+ insert_at_offset_realloc(alloc, offset, next_capacity(),
+ std::forward<Args>(value_args)...);
+ }
+ }
+
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<!std::is_nothrow_move_constructible<
+ U>::value>::type * = nullptr>
+ void insert_at_offset(allocator_type &alloc, size_type offset,
+ Args &&...value_args) {
+ insert_at_offset_realloc(alloc, offset, m_nb_elements + 1,
+ std::forward<Args>(value_args)...);
+ }
+
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<
+ std::is_nothrow_move_constructible<U>::value>::type * = nullptr>
+ void insert_at_offset_no_realloc(allocator_type &alloc, size_type offset,
+ Args &&...value_args) {
+ tsl_sh_assert(offset <= m_nb_elements);
+ tsl_sh_assert(m_nb_elements < m_capacity);
+
+ for (size_type i = m_nb_elements; i > offset; i--) {
+ construct_value(alloc, m_values + i, std::move(m_values[i - 1]));
+ destroy_value(alloc, m_values + i - 1);
+ }
+
+ try {
+ construct_value(alloc, m_values + offset,
+ std::forward<Args>(value_args)...);
+ } catch (...) {
+ for (size_type i = offset; i < m_nb_elements; i++) {
+ construct_value(alloc, m_values + i, std::move(m_values[i + 1]));
+ destroy_value(alloc, m_values + i + 1);
+ }
+ throw;
+ }
+ }
+
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<
+ std::is_nothrow_move_constructible<U>::value>::type * = nullptr>
+ void insert_at_offset_realloc(allocator_type &alloc, size_type offset,
+ size_type new_capacity, Args &&...value_args) {
+ tsl_sh_assert(new_capacity > m_nb_elements);
+
+ value_type *new_values = alloc.allocate(new_capacity);
+ // Allocate should throw if there is a failure
+ tsl_sh_assert(new_values != nullptr);
+
+ try {
+ construct_value(alloc, new_values + offset,
+ std::forward<Args>(value_args)...);
+ } catch (...) {
+ alloc.deallocate(new_values, new_capacity);
+ throw;
+ }
+
+ // Should not throw from here
+ for (size_type i = 0; i < offset; i++) {
+ construct_value(alloc, new_values + i, std::move(m_values[i]));
+ }
+
+ for (size_type i = offset; i < m_nb_elements; i++) {
+ construct_value(alloc, new_values + i + 1, std::move(m_values[i]));
+ }
+
+ destroy_and_deallocate_values(alloc, m_values, m_nb_elements, m_capacity);
+
+ m_values = new_values;
+ m_capacity = new_capacity;
+ }
+
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<!std::is_nothrow_move_constructible<
+ U>::value>::type * = nullptr>
+ void insert_at_offset_realloc(allocator_type &alloc, size_type offset,
+ size_type new_capacity, Args &&...value_args) {
+ tsl_sh_assert(new_capacity > m_nb_elements);
+
+ value_type *new_values = alloc.allocate(new_capacity);
+ // Allocate should throw if there is a failure
+ tsl_sh_assert(new_values != nullptr);
+
+ size_type nb_new_values = 0;
+ try {
+ for (size_type i = 0; i < offset; i++) {
+ construct_value(alloc, new_values + i, m_values[i]);
+ nb_new_values++;
+ }
+
+ construct_value(alloc, new_values + offset,
+ std::forward<Args>(value_args)...);
+ nb_new_values++;
+
+ for (size_type i = offset; i < m_nb_elements; i++) {
+ construct_value(alloc, new_values + i + 1, m_values[i]);
+ nb_new_values++;
+ }
+ } catch (...) {
+ destroy_and_deallocate_values(alloc, new_values, nb_new_values,
+ new_capacity);
+ throw;
+ }
+
+ tsl_sh_assert(nb_new_values == m_nb_elements + 1);
+
+ destroy_and_deallocate_values(alloc, m_values, m_nb_elements, m_capacity);
+
+ m_values = new_values;
+ m_capacity = new_capacity;
+ }
+
+ /**
+ * Erasure
+ *
+ * Two situations:
+ * - Either we are in a situation where
+ * std::is_nothrow_move_constructible<value_type>::value is true. Simply
+ * destroy the value and left-shift move the value on the right of offset.
+ * - Otherwise we are in a situation where
+ * std::is_nothrow_move_constructible<value_type>::value is false. Copy all
+ * the values except the one at offset into a new heap area. On success, we
+ * set m_values to this new area. Even if slower, it's the only way to
+ * preserve to strong exception guarantee.
+ */
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<
+ std::is_nothrow_move_constructible<U>::value>::type * = nullptr>
+ void erase_at_offset(allocator_type &alloc, size_type offset) noexcept {
+ tsl_sh_assert(offset < m_nb_elements);
+
+ destroy_value(alloc, m_values + offset);
+
+ for (size_type i = offset + 1; i < m_nb_elements; i++) {
+ construct_value(alloc, m_values + i - 1, std::move(m_values[i]));
+ destroy_value(alloc, m_values + i);
+ }
+ }
+
+ template <typename... Args, typename U = value_type,
+ typename std::enable_if<!std::is_nothrow_move_constructible<
+ U>::value>::type * = nullptr>
+ void erase_at_offset(allocator_type &alloc, size_type offset) {
+ tsl_sh_assert(offset < m_nb_elements);
+
+ // Erasing the last element, don't need to reallocate. We keep the capacity.
+ if (offset + 1 == m_nb_elements) {
+ destroy_value(alloc, m_values + offset);
+ return;
+ }
+
+ tsl_sh_assert(m_nb_elements > 1);
+ const size_type new_capacity = m_nb_elements - 1;
+
+ value_type *new_values = alloc.allocate(new_capacity);
+ // Allocate should throw if there is a failure
+ tsl_sh_assert(new_values != nullptr);
+
+ size_type nb_new_values = 0;
+ try {
+ for (size_type i = 0; i < m_nb_elements; i++) {
+ if (i != offset) {
+ construct_value(alloc, new_values + nb_new_values, m_values[i]);
+ nb_new_values++;
+ }
+ }
+ } catch (...) {
+ destroy_and_deallocate_values(alloc, new_values, nb_new_values,
+ new_capacity);
+ throw;
+ }
+
+ tsl_sh_assert(nb_new_values == m_nb_elements - 1);
+
+ destroy_and_deallocate_values(alloc, m_values, m_nb_elements, m_capacity);
+
+ m_values = new_values;
+ m_capacity = new_capacity;
+ }
+
+ private:
+ value_type *m_values;
+
+ bitmap_type m_bitmap_vals;
+ bitmap_type m_bitmap_deleted_vals;
+
+ size_type m_nb_elements;
+ size_type m_capacity;
+ bool m_last_array;
+};
+
+/**
+ * Internal common class used by `sparse_map` and `sparse_set`.
+ *
+ * `ValueType` is what will be stored by `sparse_hash` (usually `std::pair<Key,
+ * T>` for map and `Key` for set).
+ *
+ * `KeySelect` should be a `FunctionObject` which takes a `ValueType` in
+ * parameter and returns a reference to the key.
+ *
+ * `ValueSelect` should be a `FunctionObject` which takes a `ValueType` in
+ * parameter and returns a reference to the value. `ValueSelect` should be void
+ * if there is no value (in a set for example).
+ *
+ * The strong exception guarantee only holds if `ExceptionSafety` is set to
+ * `tsl::sh::exception_safety::strong`.
+ *
+ * `ValueType` must be nothrow move constructible and/or copy constructible.
+ * Behaviour is undefined if the destructor of `ValueType` throws.
+ *
+ *
+ * The class holds its buckets in a 2-dimensional fashion. Instead of having a
+ * linear `std::vector<bucket>` for [0, bucket_count) where each bucket stores
+ * one value, we have a `std::vector<sparse_array>` (m_sparse_buckets_data)
+ * where each `sparse_array` stores multiple values (up to
+ * `sparse_array::BITMAP_NB_BITS`). To convert a one dimensional `ibucket`
+ * position to a position in `std::vector<sparse_array>` and a position in
+ * `sparse_array`, use respectively the methods
+ * `sparse_array::sparse_ibucket(ibucket)` and
+ * `sparse_array::index_in_sparse_bucket(ibucket)`.
+ */
+template <class ValueType, class KeySelect, class ValueSelect, class Hash,
+ class KeyEqual, class Allocator, class GrowthPolicy,
+ tsl::sh::exception_safety ExceptionSafety, tsl::sh::sparsity Sparsity,
+ tsl::sh::probing Probing>
+class sparse_hash : private Allocator,
+ private Hash,
+ private KeyEqual,
+ private GrowthPolicy {
+ private:
+ template <typename U>
+ using has_mapped_type =
+ typename std::integral_constant<bool, !std::is_same<U, void>::value>;
+
+ static_assert(
+ noexcept(std::declval<GrowthPolicy>().bucket_for_hash(std::size_t(0))),
+ "GrowthPolicy::bucket_for_hash must be noexcept.");
+ static_assert(noexcept(std::declval<GrowthPolicy>().clear()),
+ "GrowthPolicy::clear must be noexcept.");
+
+ public:
+ template <bool IsConst>
+ class sparse_iterator;
+
+ using key_type = typename KeySelect::key_type;
+ using value_type = ValueType;
+ using size_type = std::size_t;
+ using difference_type = std::ptrdiff_t;
+ using hasher = Hash;
+ using key_equal = KeyEqual;
+ using allocator_type = Allocator;
+ using reference = value_type &;
+ using const_reference = const value_type &;
+ using pointer = value_type *;
+ using const_pointer = const value_type *;
+ using iterator = sparse_iterator<false>;
+ using const_iterator = sparse_iterator<true>;
+
+ private:
+ using sparse_array =
+ tsl::detail_sparse_hash::sparse_array<ValueType, Allocator, Sparsity>;
+
+ using sparse_buckets_allocator = typename std::allocator_traits<
+ allocator_type>::template rebind_alloc<sparse_array>;
+ using sparse_buckets_container =
+ std::vector<sparse_array, sparse_buckets_allocator>;
+
+ public:
+ /**
+ * The `operator*()` and `operator->()` methods return a const reference and
+ * const pointer respectively to the stored value type (`Key` for a set,
+ * `std::pair<Key, T>` for a map).
+ *
+ * In case of a map, to get a mutable reference to the value `T` associated to
+ * a key (the `.second` in the stored pair), you have to call `value()`.
+ */
+ template <bool IsConst>
+ class sparse_iterator {
+ friend class sparse_hash;
+
+ private:
+ using sparse_bucket_iterator = typename std::conditional<
+ IsConst, typename sparse_buckets_container::const_iterator,
+ typename sparse_buckets_container::iterator>::type;
+
+ using sparse_array_iterator =
+ typename std::conditional<IsConst,
+ typename sparse_array::const_iterator,
+ typename sparse_array::iterator>::type;
+
+ /**
+ * sparse_array_it should be nullptr if sparse_bucket_it ==
+ * m_sparse_buckets_data.end(). (TODO better way?)
+ */
+ sparse_iterator(sparse_bucket_iterator sparse_bucket_it,
+ sparse_array_iterator sparse_array_it)
+ : m_sparse_buckets_it(sparse_bucket_it),
+ m_sparse_array_it(sparse_array_it) {}
+
+ public:
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = const typename sparse_hash::value_type;
+ using difference_type = std::ptrdiff_t;
+ using reference = value_type &;
+ using pointer = value_type *;
+
+ sparse_iterator() noexcept {}
+
+ // Copy constructor from iterator to const_iterator.
+ template <bool TIsConst = IsConst,
+ typename std::enable_if<TIsConst>::type * = nullptr>
+ sparse_iterator(const sparse_iterator<!TIsConst> &other) noexcept
+ : m_sparse_buckets_it(other.m_sparse_buckets_it),
+ m_sparse_array_it(other.m_sparse_array_it) {}
+
+ sparse_iterator(const sparse_iterator &other) = default;
+ sparse_iterator(sparse_iterator &&other) = default;
+ sparse_iterator &operator=(const sparse_iterator &other) = default;
+ sparse_iterator &operator=(sparse_iterator &&other) = default;
+
+ const typename sparse_hash::key_type &key() const {
+ return KeySelect()(*m_sparse_array_it);
+ }
+
+ template <class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value &&
+ IsConst>::type * = nullptr>
+ const typename U::value_type &value() const {
+ return U()(*m_sparse_array_it);
+ }
+
+ template <class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value &&
+ !IsConst>::type * = nullptr>
+ typename U::value_type &value() {
+ return U()(*m_sparse_array_it);
+ }
+
+ reference operator*() const { return *m_sparse_array_it; }
+
+ pointer operator->() const { return std::addressof(*m_sparse_array_it); }
+
+ sparse_iterator &operator++() {
+ tsl_sh_assert(m_sparse_array_it != nullptr);
+ ++m_sparse_array_it;
+
+ if (m_sparse_array_it == m_sparse_buckets_it->end()) {
+ do {
+ if (m_sparse_buckets_it->last()) {
+ ++m_sparse_buckets_it;
+ m_sparse_array_it = nullptr;
+ return *this;
+ }
+
+ ++m_sparse_buckets_it;
+ } while (m_sparse_buckets_it->empty());
+
+ m_sparse_array_it = m_sparse_buckets_it->begin();
+ }
+
+ return *this;
+ }
+
+ sparse_iterator operator++(int) {
+ sparse_iterator tmp(*this);
+ ++*this;
+
+ return tmp;
+ }
+
+ friend bool operator==(const sparse_iterator &lhs,
+ const sparse_iterator &rhs) {
+ return lhs.m_sparse_buckets_it == rhs.m_sparse_buckets_it &&
+ lhs.m_sparse_array_it == rhs.m_sparse_array_it;
+ }
+
+ friend bool operator!=(const sparse_iterator &lhs,
+ const sparse_iterator &rhs) {
+ return !(lhs == rhs);
+ }
+
+ private:
+ sparse_bucket_iterator m_sparse_buckets_it;
+ sparse_array_iterator m_sparse_array_it;
+ };
+
+ public:
+ sparse_hash(size_type bucket_count, const Hash &hash, const KeyEqual &equal,
+ const Allocator &alloc, float max_load_factor)
+ : Allocator(alloc),
+ Hash(hash),
+ KeyEqual(equal),
+ GrowthPolicy(bucket_count),
+ m_sparse_buckets_data(alloc),
+ m_sparse_buckets(static_empty_sparse_bucket_ptr()),
+ m_bucket_count(bucket_count),
+ m_nb_elements(0),
+ m_nb_deleted_buckets(0) {
+ if (m_bucket_count > max_bucket_count()) {
+ throw std::length_error("The map exceeds its maximum size.");
+ }
+
+ if (m_bucket_count > 0) {
+ /*
+ * We can't use the `vector(size_type count, const Allocator& alloc)`
+ * constructor as it's only available in C++14 and we need to support
+ * C++11. We thus must resize after using the `vector(const Allocator&
+ * alloc)` constructor.
+ *
+ * We can't use `vector(size_type count, const T& value, const Allocator&
+ * alloc)` as it requires the value T to be copyable.
+ */
+ m_sparse_buckets_data.resize(
+ sparse_array::nb_sparse_buckets(bucket_count));
+ m_sparse_buckets = m_sparse_buckets_data.data();
+
+ tsl_sh_assert(!m_sparse_buckets_data.empty());
+ m_sparse_buckets_data.back().set_as_last();
+ }
+
+ this->max_load_factor(max_load_factor);
+
+ // Check in the constructor instead of outside of a function to avoid
+ // compilation issues when value_type is not complete.
+ static_assert(std::is_nothrow_move_constructible<value_type>::value ||
+ std::is_copy_constructible<value_type>::value,
+ "Key, and T if present, must be nothrow move constructible "
+ "and/or copy constructible.");
+ }
+
+ ~sparse_hash() { clear(); }
+
+ sparse_hash(const sparse_hash &other)
+ : Allocator(std::allocator_traits<
+ Allocator>::select_on_container_copy_construction(other)),
+ Hash(other),
+ KeyEqual(other),
+ GrowthPolicy(other),
+ m_sparse_buckets_data(
+ std::allocator_traits<
+ Allocator>::select_on_container_copy_construction(other)),
+ m_bucket_count(other.m_bucket_count),
+ m_nb_elements(other.m_nb_elements),
+ m_nb_deleted_buckets(other.m_nb_deleted_buckets),
+ m_load_threshold_rehash(other.m_load_threshold_rehash),
+ m_load_threshold_clear_deleted(other.m_load_threshold_clear_deleted),
+ m_max_load_factor(other.m_max_load_factor) {
+ copy_buckets_from(other),
+ m_sparse_buckets = m_sparse_buckets_data.empty()
+ ? static_empty_sparse_bucket_ptr()
+ : m_sparse_buckets_data.data();
+ }
+
+ sparse_hash(sparse_hash &&other) noexcept(
+ std::is_nothrow_move_constructible<Allocator>::value
+ &&std::is_nothrow_move_constructible<Hash>::value
+ &&std::is_nothrow_move_constructible<KeyEqual>::value
+ &&std::is_nothrow_move_constructible<GrowthPolicy>::value
+ &&std::is_nothrow_move_constructible<
+ sparse_buckets_container>::value)
+ : Allocator(std::move(other)),
+ Hash(std::move(other)),
+ KeyEqual(std::move(other)),
+ GrowthPolicy(std::move(other)),
+ m_sparse_buckets_data(std::move(other.m_sparse_buckets_data)),
+ m_sparse_buckets(m_sparse_buckets_data.empty()
+ ? static_empty_sparse_bucket_ptr()
+ : m_sparse_buckets_data.data()),
+ m_bucket_count(other.m_bucket_count),
+ m_nb_elements(other.m_nb_elements),
+ m_nb_deleted_buckets(other.m_nb_deleted_buckets),
+ m_load_threshold_rehash(other.m_load_threshold_rehash),
+ m_load_threshold_clear_deleted(other.m_load_threshold_clear_deleted),
+ m_max_load_factor(other.m_max_load_factor) {
+ other.GrowthPolicy::clear();
+ other.m_sparse_buckets_data.clear();
+ other.m_sparse_buckets = static_empty_sparse_bucket_ptr();
+ other.m_bucket_count = 0;
+ other.m_nb_elements = 0;
+ other.m_nb_deleted_buckets = 0;
+ other.m_load_threshold_rehash = 0;
+ other.m_load_threshold_clear_deleted = 0;
+ }
+
+ sparse_hash &operator=(const sparse_hash &other) {
+ if (this != &other) {
+ clear();
+
+ if (std::allocator_traits<
+ Allocator>::propagate_on_container_copy_assignment::value) {
+ Allocator::operator=(other);
+ }
+
+ Hash::operator=(other);
+ KeyEqual::operator=(other);
+ GrowthPolicy::operator=(other);
+
+ if (std::allocator_traits<
+ Allocator>::propagate_on_container_copy_assignment::value) {
+ m_sparse_buckets_data =
+ sparse_buckets_container(static_cast<const Allocator &>(other));
+ } else {
+ if (m_sparse_buckets_data.size() !=
+ other.m_sparse_buckets_data.size()) {
+ m_sparse_buckets_data =
+ sparse_buckets_container(static_cast<const Allocator &>(*this));
+ } else {
+ m_sparse_buckets_data.clear();
+ }
+ }
+
+ copy_buckets_from(other);
+ m_sparse_buckets = m_sparse_buckets_data.empty()
+ ? static_empty_sparse_bucket_ptr()
+ : m_sparse_buckets_data.data();
+
+ m_bucket_count = other.m_bucket_count;
+ m_nb_elements = other.m_nb_elements;
+ m_nb_deleted_buckets = other.m_nb_deleted_buckets;
+ m_load_threshold_rehash = other.m_load_threshold_rehash;
+ m_load_threshold_clear_deleted = other.m_load_threshold_clear_deleted;
+ m_max_load_factor = other.m_max_load_factor;
+ }
+
+ return *this;
+ }
+
+ sparse_hash &operator=(sparse_hash &&other) {
+ clear();
+
+ if (std::allocator_traits<
+ Allocator>::propagate_on_container_move_assignment::value) {
+ static_cast<Allocator &>(*this) =
+ std::move(static_cast<Allocator &>(other));
+ m_sparse_buckets_data = std::move(other.m_sparse_buckets_data);
+ } else if (static_cast<Allocator &>(*this) !=
+ static_cast<Allocator &>(other)) {
+ move_buckets_from(std::move(other));
+ } else {
+ static_cast<Allocator &>(*this) =
+ std::move(static_cast<Allocator &>(other));
+ m_sparse_buckets_data = std::move(other.m_sparse_buckets_data);
+ }
+
+ m_sparse_buckets = m_sparse_buckets_data.empty()
+ ? static_empty_sparse_bucket_ptr()
+ : m_sparse_buckets_data.data();
+
+ static_cast<Hash &>(*this) = std::move(static_cast<Hash &>(other));
+ static_cast<KeyEqual &>(*this) = std::move(static_cast<KeyEqual &>(other));
+ static_cast<GrowthPolicy &>(*this) =
+ std::move(static_cast<GrowthPolicy &>(other));
+ m_bucket_count = other.m_bucket_count;
+ m_nb_elements = other.m_nb_elements;
+ m_nb_deleted_buckets = other.m_nb_deleted_buckets;
+ m_load_threshold_rehash = other.m_load_threshold_rehash;
+ m_load_threshold_clear_deleted = other.m_load_threshold_clear_deleted;
+ m_max_load_factor = other.m_max_load_factor;
+
+ other.GrowthPolicy::clear();
+ other.m_sparse_buckets_data.clear();
+ other.m_sparse_buckets = static_empty_sparse_bucket_ptr();
+ other.m_bucket_count = 0;
+ other.m_nb_elements = 0;
+ other.m_nb_deleted_buckets = 0;
+ other.m_load_threshold_rehash = 0;
+ other.m_load_threshold_clear_deleted = 0;
+
+ return *this;
+ }
+
+ allocator_type get_allocator() const {
+ return static_cast<const Allocator &>(*this);
+ }
+
+ /*
+ * Iterators
+ */
+ iterator begin() noexcept {
+ auto begin = m_sparse_buckets_data.begin();
+ while (begin != m_sparse_buckets_data.end() && begin->empty()) {
+ ++begin;
+ }
+
+ return iterator(begin, (begin != m_sparse_buckets_data.end())
+ ? begin->begin()
+ : nullptr);
+ }
+
+ const_iterator begin() const noexcept { return cbegin(); }
+
+ const_iterator cbegin() const noexcept {
+ auto begin = m_sparse_buckets_data.cbegin();
+ while (begin != m_sparse_buckets_data.cend() && begin->empty()) {
+ ++begin;
+ }
+
+ return const_iterator(begin, (begin != m_sparse_buckets_data.cend())
+ ? begin->cbegin()
+ : nullptr);
+ }
+
+ iterator end() noexcept {
+ return iterator(m_sparse_buckets_data.end(), nullptr);
+ }
+
+ const_iterator end() const noexcept { return cend(); }
+
+ const_iterator cend() const noexcept {
+ return const_iterator(m_sparse_buckets_data.cend(), nullptr);
+ }
+
+ /*
+ * Capacity
+ */
+ bool empty() const noexcept { return m_nb_elements == 0; }
+
+ size_type size() const noexcept { return m_nb_elements; }
+
+ size_type max_size() const noexcept {
+ return std::min(std::allocator_traits<Allocator>::max_size(),
+ m_sparse_buckets_data.max_size());
+ }
+
+ /*
+ * Modifiers
+ */
+ void clear() noexcept {
+ for (auto &bucket : m_sparse_buckets_data) {
+ bucket.clear(*this);
+ }
+
+ m_nb_elements = 0;
+ m_nb_deleted_buckets = 0;
+ }
+
+ template <typename P>
+ std::pair<iterator, bool> insert(P &&value) {
+ return insert_impl(KeySelect()(value), std::forward<P>(value));
+ }
+
+ template <typename P>
+ iterator insert_hint(const_iterator hint, P &&value) {
+ if (hint != cend() &&
+ compare_keys(KeySelect()(*hint), KeySelect()(value))) {
+ return mutable_iterator(hint);
+ }
+
+ return insert(std::forward<P>(value)).first;
+ }
+
+ template <class InputIt>
+ void insert(InputIt first, InputIt last) {
+ if (std::is_base_of<
+ std::forward_iterator_tag,
+ typename std::iterator_traits<InputIt>::iterator_category>::value) {
+ const auto nb_elements_insert = std::distance(first, last);
+ const size_type nb_free_buckets = m_load_threshold_rehash - size();
+ tsl_sh_assert(m_load_threshold_rehash >= size());
+
+ if (nb_elements_insert > 0 &&
+ nb_free_buckets < size_type(nb_elements_insert)) {
+ reserve(size() + size_type(nb_elements_insert));
+ }
+ }
+
+ for (; first != last; ++first) {
+ insert(*first);
+ }
+ }
+
+ template <class K, class M>
+ std::pair<iterator, bool> insert_or_assign(K &&key, M &&obj) {
+ auto it = try_emplace(std::forward<K>(key), std::forward<M>(obj));
+ if (!it.second) {
+ it.first.value() = std::forward<M>(obj);
+ }
+
+ return it;
+ }
+
+ template <class K, class M>
+ iterator insert_or_assign(const_iterator hint, K &&key, M &&obj) {
+ if (hint != cend() && compare_keys(KeySelect()(*hint), key)) {
+ auto it = mutable_iterator(hint);
+ it.value() = std::forward<M>(obj);
+
+ return it;
+ }
+
+ return insert_or_assign(std::forward<K>(key), std::forward<M>(obj)).first;
+ }
+
+ template <class... Args>
+ std::pair<iterator, bool> emplace(Args &&...args) {
+ return insert(value_type(std::forward<Args>(args)...));
+ }
+
+ template <class... Args>
+ iterator emplace_hint(const_iterator hint, Args &&...args) {
+ return insert_hint(hint, value_type(std::forward<Args>(args)...));
+ }
+
+ template <class K, class... Args>
+ std::pair<iterator, bool> try_emplace(K &&key, Args &&...args) {
+ return insert_impl(key, std::piecewise_construct,
+ std::forward_as_tuple(std::forward<K>(key)),
+ std::forward_as_tuple(std::forward<Args>(args)...));
+ }
+
+ template <class K, class... Args>
+ iterator try_emplace_hint(const_iterator hint, K &&key, Args &&...args) {
+ if (hint != cend() && compare_keys(KeySelect()(*hint), key)) {
+ return mutable_iterator(hint);
+ }
+
+ return try_emplace(std::forward<K>(key), std::forward<Args>(args)...).first;
+ }
+
+ /**
+ * Here to avoid `template<class K> size_type erase(const K& key)` being used
+ * when we use an iterator instead of a const_iterator.
+ */
+ iterator erase(iterator pos) {
+ tsl_sh_assert(pos != end() && m_nb_elements > 0);
+ auto it_sparse_array_next =
+ pos.m_sparse_buckets_it->erase(*this, pos.m_sparse_array_it);
+ m_nb_elements--;
+ m_nb_deleted_buckets++;
+
+ if (it_sparse_array_next == pos.m_sparse_buckets_it->end()) {
+ auto it_sparse_buckets_next = pos.m_sparse_buckets_it;
+ do {
+ ++it_sparse_buckets_next;
+ } while (it_sparse_buckets_next != m_sparse_buckets_data.end() &&
+ it_sparse_buckets_next->empty());
+
+ if (it_sparse_buckets_next == m_sparse_buckets_data.end()) {
+ return end();
+ } else {
+ return iterator(it_sparse_buckets_next,
+ it_sparse_buckets_next->begin());
+ }
+ } else {
+ return iterator(pos.m_sparse_buckets_it, it_sparse_array_next);
+ }
+ }
+
+ iterator erase(const_iterator pos) { return erase(mutable_iterator(pos)); }
+
+ iterator erase(const_iterator first, const_iterator last) {
+ if (first == last) {
+ return mutable_iterator(first);
+ }
+
+ // TODO Optimize, could avoid the call to std::distance.
+ const size_type nb_elements_to_erase =
+ static_cast<size_type>(std::distance(first, last));
+ auto to_delete = mutable_iterator(first);
+ for (size_type i = 0; i < nb_elements_to_erase; i++) {
+ to_delete = erase(to_delete);
+ }
+
+ return to_delete;
+ }
+
+ template <class K>
+ size_type erase(const K &key) {
+ return erase(key, hash_key(key));
+ }
+
+ template <class K>
+ size_type erase(const K &key, std::size_t hash) {
+ return erase_impl(key, hash);
+ }
+
+ void swap(sparse_hash &other) {
+ using std::swap;
+
+ if (std::allocator_traits<Allocator>::propagate_on_container_swap::value) {
+ swap(static_cast<Allocator &>(*this), static_cast<Allocator &>(other));
+ } else {
+ tsl_sh_assert(static_cast<Allocator &>(*this) ==
+ static_cast<Allocator &>(other));
+ }
+
+ swap(static_cast<Hash &>(*this), static_cast<Hash &>(other));
+ swap(static_cast<KeyEqual &>(*this), static_cast<KeyEqual &>(other));
+ swap(static_cast<GrowthPolicy &>(*this),
+ static_cast<GrowthPolicy &>(other));
+ swap(m_sparse_buckets_data, other.m_sparse_buckets_data);
+ swap(m_sparse_buckets, other.m_sparse_buckets);
+ swap(m_bucket_count, other.m_bucket_count);
+ swap(m_nb_elements, other.m_nb_elements);
+ swap(m_nb_deleted_buckets, other.m_nb_deleted_buckets);
+ swap(m_load_threshold_rehash, other.m_load_threshold_rehash);
+ swap(m_load_threshold_clear_deleted, other.m_load_threshold_clear_deleted);
+ swap(m_max_load_factor, other.m_max_load_factor);
+ }
+
+ /*
+ * Lookup
+ */
+ template <
+ class K, class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value>::type * = nullptr>
+ typename U::value_type &at(const K &key) {
+ return at(key, hash_key(key));
+ }
+
+ template <
+ class K, class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value>::type * = nullptr>
+ typename U::value_type &at(const K &key, std::size_t hash) {
+ return const_cast<typename U::value_type &>(
+ static_cast<const sparse_hash *>(this)->at(key, hash));
+ }
+
+ template <
+ class K, class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value>::type * = nullptr>
+ const typename U::value_type &at(const K &key) const {
+ return at(key, hash_key(key));
+ }
+
+ template <
+ class K, class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value>::type * = nullptr>
+ const typename U::value_type &at(const K &key, std::size_t hash) const {
+ auto it = find(key, hash);
+ if (it != cend()) {
+ return it.value();
+ } else {
+ throw std::out_of_range("Couldn't find key.");
+ }
+ }
+
+ template <
+ class K, class U = ValueSelect,
+ typename std::enable_if<has_mapped_type<U>::value>::type * = nullptr>
+ typename U::value_type &operator[](K &&key) {
+ return try_emplace(std::forward<K>(key)).first.value();
+ }
+
+ template <class K>
+ bool contains(const K &key) const {
+ return contains(key, hash_key(key));
+ }
+
+ template <class K>
+ bool contains(const K &key, std::size_t hash) const {
+ return count(key, hash) != 0;
+ }
+
+ template <class K>
+ size_type count(const K &key) const {
+ return count(key, hash_key(key));
+ }
+
+ template <class K>
+ size_type count(const K &key, std::size_t hash) const {
+ if (find(key, hash) != cend()) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
+
+ template <class K>
+ iterator find(const K &key) {
+ return find_impl(key, hash_key(key));
+ }
+
+ template <class K>
+ iterator find(const K &key, std::size_t hash) {
+ return find_impl(key, hash);
+ }
+
+ template <class K>
+ const_iterator find(const K &key) const {
+ return find_impl(key, hash_key(key));
+ }
+
+ template <class K>
+ const_iterator find(const K &key, std::size_t hash) const {
+ return find_impl(key, hash);
+ }
+
+ template <class K>
+ std::pair<iterator, iterator> equal_range(const K &key) {
+ return equal_range(key, hash_key(key));
+ }
+
+ template <class K>
+ std::pair<iterator, iterator> equal_range(const K &key, std::size_t hash) {
+ iterator it = find(key, hash);
+ return std::make_pair(it, (it == end()) ? it : std::next(it));
+ }
+
+ template <class K>
+ std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
+ return equal_range(key, hash_key(key));
+ }
+
+ template <class K>
+ std::pair<const_iterator, const_iterator> equal_range(
+ const K &key, std::size_t hash) const {
+ const_iterator it = find(key, hash);
+ return std::make_pair(it, (it == cend()) ? it : std::next(it));
+ }
+
+ /*
+ * Bucket interface
+ */
+ size_type bucket_count() const { return m_bucket_count; }
+
+ size_type max_bucket_count() const {
+ return m_sparse_buckets_data.max_size();
+ }
+
+ /*
+ * Hash policy
+ */
+ float load_factor() const {
+ if (bucket_count() == 0) {
+ return 0;
+ }
+
+ return float(m_nb_elements) / float(bucket_count());
+ }
+
+ float max_load_factor() const { return m_max_load_factor; }
+
+ void max_load_factor(float ml) {
+ m_max_load_factor = std::max(0.1f, std::min(ml, 0.8f));
+ m_load_threshold_rehash =
+ size_type(float(bucket_count()) * m_max_load_factor);
+
+ const float max_load_factor_with_deleted_buckets =
+ m_max_load_factor + 0.5f * (1.0f - m_max_load_factor);
+ tsl_sh_assert(max_load_factor_with_deleted_buckets > 0.0f &&
+ max_load_factor_with_deleted_buckets <= 1.0f);
+ m_load_threshold_clear_deleted =
+ size_type(float(bucket_count()) * max_load_factor_with_deleted_buckets);
+ }
+
+ void rehash(size_type count) {
+ count = std::max(count,
+ size_type(std::ceil(float(size()) / max_load_factor())));
+ rehash_impl(count);
+ }
+
+ void reserve(size_type count) {
+ rehash(size_type(std::ceil(float(count) / max_load_factor())));
+ }
+
+ /*
+ * Observers
+ */
+ hasher hash_function() const { return static_cast<const Hash &>(*this); }
+
+ key_equal key_eq() const { return static_cast<const KeyEqual &>(*this); }
+
+ /*
+ * Other
+ */
+ iterator mutable_iterator(const_iterator pos) {
+ auto it_sparse_buckets =
+ m_sparse_buckets_data.begin() +
+ std::distance(m_sparse_buckets_data.cbegin(), pos.m_sparse_buckets_it);
+
+ return iterator(it_sparse_buckets,
+ sparse_array::mutable_iterator(pos.m_sparse_array_it));
+ }
+
+ template <class Serializer>
+ void serialize(Serializer &serializer) const {
+ serialize_impl(serializer);
+ }
+
+ template <class Deserializer>
+ void deserialize(Deserializer &deserializer, bool hash_compatible) {
+ deserialize_impl(deserializer, hash_compatible);
+ }
+
+ private:
+ template <class K>
+ std::size_t hash_key(const K &key) const {
+ return Hash::operator()(key);
+ }
+
+ template <class K1, class K2>
+ bool compare_keys(const K1 &key1, const K2 &key2) const {
+ return KeyEqual::operator()(key1, key2);
+ }
+
+ size_type bucket_for_hash(std::size_t hash) const {
+ const std::size_t bucket = GrowthPolicy::bucket_for_hash(hash);
+ tsl_sh_assert(sparse_array::sparse_ibucket(bucket) <
+ m_sparse_buckets_data.size() ||
+ (bucket == 0 && m_sparse_buckets_data.empty()));
+
+ return bucket;
+ }
+
+ template <class U = GrowthPolicy,
+ typename std::enable_if<is_power_of_two_policy<U>::value>::type * =
+ nullptr>
+ size_type next_bucket(size_type ibucket, size_type iprobe) const {
+ (void)iprobe;
+ if (Probing == tsl::sh::probing::linear) {
+ return (ibucket + 1) & this->m_mask;
+ } else {
+ tsl_sh_assert(Probing == tsl::sh::probing::quadratic);
+ return (ibucket + iprobe) & this->m_mask;
+ }
+ }
+
+ template <class U = GrowthPolicy,
+ typename std::enable_if<!is_power_of_two_policy<U>::value>::type * =
+ nullptr>
+ size_type next_bucket(size_type ibucket, size_type iprobe) const {
+ (void)iprobe;
+ if (Probing == tsl::sh::probing::linear) {
+ ibucket++;
+ return (ibucket != bucket_count()) ? ibucket : 0;
+ } else {
+ tsl_sh_assert(Probing == tsl::sh::probing::quadratic);
+ ibucket += iprobe;
+ return (ibucket < bucket_count()) ? ibucket : ibucket % bucket_count();
+ }
+ }
+
+ // TODO encapsulate m_sparse_buckets_data to avoid the managing the allocator
+ void copy_buckets_from(const sparse_hash &other) {
+ m_sparse_buckets_data.reserve(other.m_sparse_buckets_data.size());
+
+ try {
+ for (const auto &bucket : other.m_sparse_buckets_data) {
+ m_sparse_buckets_data.emplace_back(bucket,
+ static_cast<Allocator &>(*this));
+ }
+ } catch (...) {
+ clear();
+ throw;
+ }
+
+ tsl_sh_assert(m_sparse_buckets_data.empty() ||
+ m_sparse_buckets_data.back().last());
+ }
+
+ void move_buckets_from(sparse_hash &&other) {
+ m_sparse_buckets_data.reserve(other.m_sparse_buckets_data.size());
+
+ try {
+ for (auto &&bucket : other.m_sparse_buckets_data) {
+ m_sparse_buckets_data.emplace_back(std::move(bucket),
+ static_cast<Allocator &>(*this));
+ }
+ } catch (...) {
+ clear();
+ throw;
+ }
+
+ tsl_sh_assert(m_sparse_buckets_data.empty() ||
+ m_sparse_buckets_data.back().last());
+ }
+
+ template <class K, class... Args>
+ std::pair<iterator, bool> insert_impl(const K &key,
+ Args &&...value_type_args) {
+ if (size() >= m_load_threshold_rehash) {
+ rehash_impl(GrowthPolicy::next_bucket_count());
+ } else if (size() + m_nb_deleted_buckets >=
+ m_load_threshold_clear_deleted) {
+ clear_deleted_buckets();
+ }
+ tsl_sh_assert(!m_sparse_buckets_data.empty());
+
+ /**
+ * We must insert the value in the first empty or deleted bucket we find. If
+ * we first find a deleted bucket, we still have to continue the search
+ * until we find an empty bucket or until we have searched all the buckets
+ * to be sure that the value is not in the hash table. We thus remember the
+ * position, if any, of the first deleted bucket we have encountered so we
+ * can insert it there if needed.
+ */
+ bool found_first_deleted_bucket = false;
+ std::size_t sparse_ibucket_first_deleted = 0;
+ typename sparse_array::size_type index_in_sparse_bucket_first_deleted = 0;
+
+ const std::size_t hash = hash_key(key);
+ std::size_t ibucket = bucket_for_hash(hash);
+
+ std::size_t probe = 0;
+ while (true) {
+ std::size_t sparse_ibucket = sparse_array::sparse_ibucket(ibucket);
+ auto index_in_sparse_bucket =
+ sparse_array::index_in_sparse_bucket(ibucket);
+
+ if (m_sparse_buckets[sparse_ibucket].has_value(index_in_sparse_bucket)) {
+ auto value_it =
+ m_sparse_buckets[sparse_ibucket].value(index_in_sparse_bucket);
+ if (compare_keys(key, KeySelect()(*value_it))) {
+ return std::make_pair(
+ iterator(m_sparse_buckets_data.begin() + sparse_ibucket,
+ value_it),
+ false);
+ }
+ } else if (m_sparse_buckets[sparse_ibucket].has_deleted_value(
+ index_in_sparse_bucket) &&
+ probe < m_bucket_count) {
+ if (!found_first_deleted_bucket) {
+ found_first_deleted_bucket = true;
+ sparse_ibucket_first_deleted = sparse_ibucket;
+ index_in_sparse_bucket_first_deleted = index_in_sparse_bucket;
+ }
+ } else if (found_first_deleted_bucket) {
+ auto it = insert_in_bucket(sparse_ibucket_first_deleted,
+ index_in_sparse_bucket_first_deleted,
+ std::forward<Args>(value_type_args)...);
+ m_nb_deleted_buckets--;
+
+ return it;
+ } else {
+ return insert_in_bucket(sparse_ibucket, index_in_sparse_bucket,
+ std::forward<Args>(value_type_args)...);
+ }
+
+ probe++;
+ ibucket = next_bucket(ibucket, probe);
+ }
+ }
+
+ template <class... Args>
+ std::pair<iterator, bool> insert_in_bucket(
+ std::size_t sparse_ibucket,
+ typename sparse_array::size_type index_in_sparse_bucket,
+ Args &&...value_type_args) {
+ auto value_it = m_sparse_buckets[sparse_ibucket].set(
+ *this, index_in_sparse_bucket, std::forward<Args>(value_type_args)...);
+ m_nb_elements++;
+
+ return std::make_pair(
+ iterator(m_sparse_buckets_data.begin() + sparse_ibucket, value_it),
+ true);
+ }
+
+ template <class K>
+ size_type erase_impl(const K &key, std::size_t hash) {
+ std::size_t ibucket = bucket_for_hash(hash);
+
+ std::size_t probe = 0;
+ while (true) {
+ const std::size_t sparse_ibucket = sparse_array::sparse_ibucket(ibucket);
+ const auto index_in_sparse_bucket =
+ sparse_array::index_in_sparse_bucket(ibucket);
+
+ if (m_sparse_buckets[sparse_ibucket].has_value(index_in_sparse_bucket)) {
+ auto value_it =
+ m_sparse_buckets[sparse_ibucket].value(index_in_sparse_bucket);
+ if (compare_keys(key, KeySelect()(*value_it))) {
+ m_sparse_buckets[sparse_ibucket].erase(*this, value_it,
+ index_in_sparse_bucket);
+ m_nb_elements--;
+ m_nb_deleted_buckets++;
+
+ return 1;
+ }
+ } else if (!m_sparse_buckets[sparse_ibucket].has_deleted_value(
+ index_in_sparse_bucket) ||
+ probe >= m_bucket_count) {
+ return 0;
+ }
+
+ probe++;
+ ibucket = next_bucket(ibucket, probe);
+ }
+ }
+
+ template <class K>
+ iterator find_impl(const K &key, std::size_t hash) {
+ return mutable_iterator(
+ static_cast<const sparse_hash *>(this)->find(key, hash));
+ }
+
+ template <class K>
+ const_iterator find_impl(const K &key, std::size_t hash) const {
+ std::size_t ibucket = bucket_for_hash(hash);
+
+ std::size_t probe = 0;
+ while (true) {
+ const std::size_t sparse_ibucket = sparse_array::sparse_ibucket(ibucket);
+ const auto index_in_sparse_bucket =
+ sparse_array::index_in_sparse_bucket(ibucket);
+
+ if (m_sparse_buckets[sparse_ibucket].has_value(index_in_sparse_bucket)) {
+ auto value_it =
+ m_sparse_buckets[sparse_ibucket].value(index_in_sparse_bucket);
+ if (compare_keys(key, KeySelect()(*value_it))) {
+ return const_iterator(m_sparse_buckets_data.cbegin() + sparse_ibucket,
+ value_it);
+ }
+ } else if (!m_sparse_buckets[sparse_ibucket].has_deleted_value(
+ index_in_sparse_bucket) ||
+ probe >= m_bucket_count) {
+ return cend();
+ }
+
+ probe++;
+ ibucket = next_bucket(ibucket, probe);
+ }
+ }
+
+ void clear_deleted_buckets() {
+ // TODO could be optimized, we could do it in-place instead of allocating a
+ // new bucket array.
+ rehash_impl(m_bucket_count);
+ tsl_sh_assert(m_nb_deleted_buckets == 0);
+ }
+
+ template <tsl::sh::exception_safety U = ExceptionSafety,
+ typename std::enable_if<U == tsl::sh::exception_safety::basic>::type
+ * = nullptr>
+ void rehash_impl(size_type count) {
+ sparse_hash new_table(count, static_cast<Hash &>(*this),
+ static_cast<KeyEqual &>(*this),
+ static_cast<Allocator &>(*this), m_max_load_factor);
+
+ for (auto &bucket : m_sparse_buckets_data) {
+ for (auto &val : bucket) {
+ new_table.insert_on_rehash(std::move(val));
+ }
+
+ // TODO try to reuse some of the memory
+ bucket.clear(*this);
+ }
+
+ new_table.swap(*this);
+ }
+
+ /**
+ * TODO: For now we copy each element into the new map. We could move
+ * them if they are nothrow_move_constructible without triggering
+ * any exception if we reserve enough space in the sparse arrays beforehand.
+ */
+ template <tsl::sh::exception_safety U = ExceptionSafety,
+ typename std::enable_if<
+ U == tsl::sh::exception_safety::strong>::type * = nullptr>
+ void rehash_impl(size_type count) {
+ sparse_hash new_table(count, static_cast<Hash &>(*this),
+ static_cast<KeyEqual &>(*this),
+ static_cast<Allocator &>(*this), m_max_load_factor);
+
+ for (const auto &bucket : m_sparse_buckets_data) {
+ for (const auto &val : bucket) {
+ new_table.insert_on_rehash(val);
+ }
+ }
+
+ new_table.swap(*this);
+ }
+
+ template <typename K>
+ void insert_on_rehash(K &&key_value) {
+ const key_type &key = KeySelect()(key_value);
+
+ const std::size_t hash = hash_key(key);
+ std::size_t ibucket = bucket_for_hash(hash);
+
+ std::size_t probe = 0;
+ while (true) {
+ std::size_t sparse_ibucket = sparse_array::sparse_ibucket(ibucket);
+ auto index_in_sparse_bucket =
+ sparse_array::index_in_sparse_bucket(ibucket);
+
+ if (!m_sparse_buckets[sparse_ibucket].has_value(index_in_sparse_bucket)) {
+ m_sparse_buckets[sparse_ibucket].set(*this, index_in_sparse_bucket,
+ std::forward<K>(key_value));
+ m_nb_elements++;
+
+ return;
+ } else {
+ tsl_sh_assert(!compare_keys(
+ key, KeySelect()(*m_sparse_buckets[sparse_ibucket].value(
+ index_in_sparse_bucket))));
+ }
+
+ probe++;
+ ibucket = next_bucket(ibucket, probe);
+ }
+ }
+
+ template <class Serializer>
+ void serialize_impl(Serializer &serializer) const {
+ const slz_size_type version = SERIALIZATION_PROTOCOL_VERSION;
+ serializer(version);
+
+ const slz_size_type bucket_count = m_bucket_count;
+ serializer(bucket_count);
+
+ const slz_size_type nb_sparse_buckets = m_sparse_buckets_data.size();
+ serializer(nb_sparse_buckets);
+
+ const slz_size_type nb_elements = m_nb_elements;
+ serializer(nb_elements);
+
+ const slz_size_type nb_deleted_buckets = m_nb_deleted_buckets;
+ serializer(nb_deleted_buckets);
+
+ const float max_load_factor = m_max_load_factor;
+ serializer(max_load_factor);
+
+ for (const auto &bucket : m_sparse_buckets_data) {
+ bucket.serialize(serializer);
+ }
+ }
+
+ template <class Deserializer>
+ void deserialize_impl(Deserializer &deserializer, bool hash_compatible) {
+ tsl_sh_assert(
+ m_bucket_count == 0 &&
+ m_sparse_buckets_data.empty()); // Current hash table must be empty
+
+ const slz_size_type version =
+ deserialize_value<slz_size_type>(deserializer);
+ // For now we only have one version of the serialization protocol.
+ // If it doesn't match there is a problem with the file.
+ if (version != SERIALIZATION_PROTOCOL_VERSION) {
+ throw std::runtime_error(
+ "Can't deserialize the sparse_map/set. The "
+ "protocol version header is invalid.");
+ }
+
+ const slz_size_type bucket_count_ds =
+ deserialize_value<slz_size_type>(deserializer);
+ const slz_size_type nb_sparse_buckets =
+ deserialize_value<slz_size_type>(deserializer);
+ const slz_size_type nb_elements =
+ deserialize_value<slz_size_type>(deserializer);
+ const slz_size_type nb_deleted_buckets =
+ deserialize_value<slz_size_type>(deserializer);
+ const float max_load_factor = deserialize_value<float>(deserializer);
+
+ if (!hash_compatible) {
+ this->max_load_factor(max_load_factor);
+ reserve(numeric_cast<size_type>(nb_elements,
+ "Deserialized nb_elements is too big."));
+ for (slz_size_type ibucket = 0; ibucket < nb_sparse_buckets; ibucket++) {
+ sparse_array::deserialize_values_into_sparse_hash(deserializer, *this);
+ }
+ } else {
+ m_bucket_count = numeric_cast<size_type>(
+ bucket_count_ds, "Deserialized bucket_count is too big.");
+
+ GrowthPolicy::operator=(GrowthPolicy(m_bucket_count));
+ // GrowthPolicy should not modify the bucket count we got from
+ // deserialization
+ if (m_bucket_count != bucket_count_ds) {
+ throw std::runtime_error(
+ "The GrowthPolicy is not the same even though "
+ "hash_compatible is true.");
+ }
+
+ if (nb_sparse_buckets !=
+ sparse_array::nb_sparse_buckets(m_bucket_count)) {
+ throw std::runtime_error("Deserialized nb_sparse_buckets is invalid.");
+ }
+
+ m_nb_elements = numeric_cast<size_type>(
+ nb_elements, "Deserialized nb_elements is too big.");
+ m_nb_deleted_buckets = numeric_cast<size_type>(
+ nb_deleted_buckets, "Deserialized nb_deleted_buckets is too big.");
+
+ m_sparse_buckets_data.reserve(numeric_cast<size_type>(
+ nb_sparse_buckets, "Deserialized nb_sparse_buckets is too big."));
+ for (slz_size_type ibucket = 0; ibucket < nb_sparse_buckets; ibucket++) {
+ m_sparse_buckets_data.emplace_back(
+ sparse_array::deserialize_hash_compatible(
+ deserializer, static_cast<Allocator &>(*this)));
+ }
+
+ if (!m_sparse_buckets_data.empty()) {
+ m_sparse_buckets_data.back().set_as_last();
+ m_sparse_buckets = m_sparse_buckets_data.data();
+ }
+
+ this->max_load_factor(max_load_factor);
+ if (load_factor() > this->max_load_factor()) {
+ throw std::runtime_error(
+ "Invalid max_load_factor. Check that the serializer and "
+ "deserializer support "
+ "floats correctly as they can be converted implicitely to ints.");
+ }
+ }
+ }
+
+ public:
+ static const size_type DEFAULT_INIT_BUCKET_COUNT = 0;
+ static constexpr float DEFAULT_MAX_LOAD_FACTOR = 0.5f;
+
+ /**
+ * Protocol version currenlty used for serialization.
+ */
+ static const slz_size_type SERIALIZATION_PROTOCOL_VERSION = 1;
+
+ /**
+ * Return an always valid pointer to an static empty bucket_entry with
+ * last_bucket() == true.
+ */
+ sparse_array *static_empty_sparse_bucket_ptr() {
+ static sparse_array empty_sparse_bucket(true);
+ return &empty_sparse_bucket;
+ }
+
+ private:
+ sparse_buckets_container m_sparse_buckets_data;
+
+ /**
+ * Points to m_sparse_buckets_data.data() if !m_sparse_buckets_data.empty()
+ * otherwise points to static_empty_sparse_bucket_ptr. This variable is useful
+ * to avoid the cost of checking if m_sparse_buckets_data is empty when trying
+ * to find an element.
+ *
+ * TODO Remove m_sparse_buckets_data and only use a pointer instead of a
+ * pointer+vector to save some space in the sparse_hash object.
+ */
+ sparse_array *m_sparse_buckets;
+
+ size_type m_bucket_count;
+ size_type m_nb_elements;
+ size_type m_nb_deleted_buckets;
+
+ /**
+ * Maximum that m_nb_elements can reach before a rehash occurs automatically
+ * to grow the hash table.
+ */
+ size_type m_load_threshold_rehash;
+
+ /**
+ * Maximum that m_nb_elements + m_nb_deleted_buckets can reach before cleaning
+ * up the buckets marked as deleted.
+ */
+ size_type m_load_threshold_clear_deleted;
+ float m_max_load_factor;
+};
+
+} // namespace detail_sparse_hash
+} // namespace tsl
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_map.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_map.h
new file mode 100644
index 0000000..601742d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_map.h
@@ -0,0 +1,800 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Thibaut Goetghebuer-Planchon <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_SPARSE_MAP_H
+#define TSL_SPARSE_MAP_H
+
+#include <cstddef>
+#include <functional>
+#include <initializer_list>
+#include <memory>
+#include <type_traits>
+#include <utility>
+
+#include "sparse_hash.h"
+
+namespace tsl {
+
+/**
+ * Implementation of a sparse hash map using open-addressing with quadratic
+ * probing. The goal on the hash map is to be the most memory efficient
+ * possible, even at low load factor, while keeping reasonable performances.
+ *
+ * `GrowthPolicy` defines how the map grows and consequently how a hash value is
+ * mapped to a bucket. By default the map uses
+ * `tsl::sh::power_of_two_growth_policy`. This policy keeps the number of
+ * buckets to a power of two and uses a mask to map the hash to a bucket instead
+ * of the slow modulo. Other growth policies are available and you may define
+ * your own growth policy, check `tsl::sh::power_of_two_growth_policy` for the
+ * interface.
+ *
+ * `ExceptionSafety` defines the exception guarantee provided by the class. By
+ * default only the basic exception safety is guaranteed which mean that all
+ * resources used by the hash map will be freed (no memory leaks) but the hash
+ * map may end-up in an undefined state if an exception is thrown (undefined
+ * here means that some elements may be missing). This can ONLY happen on rehash
+ * (either on insert or if `rehash` is called explicitly) and will occur if the
+ * Allocator can't allocate memory (`std::bad_alloc`) or if the copy constructor
+ * (when a nothrow move constructor is not available) throws an exception. This
+ * can be avoided by calling `reserve` beforehand. This basic guarantee is
+ * similar to the one of `google::sparse_hash_map` and `spp::sparse_hash_map`.
+ * It is possible to ask for the strong exception guarantee with
+ * `tsl::sh::exception_safety::strong`, the drawback is that the map will be
+ * slower on rehashes and will also need more memory on rehashes.
+ *
+ * `Sparsity` defines how much the hash set will compromise between insertion
+ * speed and memory usage. A high sparsity means less memory usage but longer
+ * insertion times, and vice-versa for low sparsity. The default
+ * `tsl::sh::sparsity::medium` sparsity offers a good compromise. It doesn't
+ * change the lookup speed.
+ *
+ * `Key` and `T` must be nothrow move constructible and/or copy constructible.
+ *
+ * If the destructor of `Key` or `T` throws an exception, the behaviour of the
+ * class is undefined.
+ *
+ * Iterators invalidation:
+ * - clear, operator=, reserve, rehash: always invalidate the iterators.
+ * - insert, emplace, emplace_hint, operator[]: if there is an effective
+ * insert, invalidate the iterators.
+ * - erase: always invalidate the iterators.
+ */
+template <class Key, class T, class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<std::pair<Key, T>>,
+ class GrowthPolicy = tsl::sh::power_of_two_growth_policy<2>,
+ tsl::sh::exception_safety ExceptionSafety =
+ tsl::sh::exception_safety::basic,
+ tsl::sh::sparsity Sparsity = tsl::sh::sparsity::medium>
+class sparse_map {
+ private:
+ template <typename U>
+ using has_is_transparent = tsl::detail_sparse_hash::has_is_transparent<U>;
+
+ class KeySelect {
+ public:
+ using key_type = Key;
+
+ const key_type &operator()(
+ const std::pair<Key, T> &key_value) const noexcept {
+ return key_value.first;
+ }
+
+ key_type &operator()(std::pair<Key, T> &key_value) noexcept {
+ return key_value.first;
+ }
+ };
+
+ class ValueSelect {
+ public:
+ using value_type = T;
+
+ const value_type &operator()(
+ const std::pair<Key, T> &key_value) const noexcept {
+ return key_value.second;
+ }
+
+ value_type &operator()(std::pair<Key, T> &key_value) noexcept {
+ return key_value.second;
+ }
+ };
+
+ using ht = detail_sparse_hash::sparse_hash<
+ std::pair<Key, T>, KeySelect, ValueSelect, Hash, KeyEqual, Allocator,
+ GrowthPolicy, ExceptionSafety, Sparsity, tsl::sh::probing::quadratic>;
+
+ public:
+ using key_type = typename ht::key_type;
+ using mapped_type = T;
+ using value_type = typename ht::value_type;
+ using size_type = typename ht::size_type;
+ using difference_type = typename ht::difference_type;
+ using hasher = typename ht::hasher;
+ using key_equal = typename ht::key_equal;
+ using allocator_type = typename ht::allocator_type;
+ using reference = typename ht::reference;
+ using const_reference = typename ht::const_reference;
+ using pointer = typename ht::pointer;
+ using const_pointer = typename ht::const_pointer;
+ using iterator = typename ht::iterator;
+ using const_iterator = typename ht::const_iterator;
+
+ public:
+ /*
+ * Constructors
+ */
+ sparse_map() : sparse_map(ht::DEFAULT_INIT_BUCKET_COUNT) {}
+
+ explicit sparse_map(size_type bucket_count, const Hash &hash = Hash(),
+ const KeyEqual &equal = KeyEqual(),
+ const Allocator &alloc = Allocator())
+ : m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR) {}
+
+ sparse_map(size_type bucket_count, const Allocator &alloc)
+ : sparse_map(bucket_count, Hash(), KeyEqual(), alloc) {}
+
+ sparse_map(size_type bucket_count, const Hash &hash, const Allocator &alloc)
+ : sparse_map(bucket_count, hash, KeyEqual(), alloc) {}
+
+ explicit sparse_map(const Allocator &alloc)
+ : sparse_map(ht::DEFAULT_INIT_BUCKET_COUNT, alloc) {}
+
+ template <class InputIt>
+ sparse_map(InputIt first, InputIt last,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKET_COUNT,
+ const Hash &hash = Hash(), const KeyEqual &equal = KeyEqual(),
+ const Allocator &alloc = Allocator())
+ : sparse_map(bucket_count, hash, equal, alloc) {
+ insert(first, last);
+ }
+
+ template <class InputIt>
+ sparse_map(InputIt first, InputIt last, size_type bucket_count,
+ const Allocator &alloc)
+ : sparse_map(first, last, bucket_count, Hash(), KeyEqual(), alloc) {}
+
+ template <class InputIt>
+ sparse_map(InputIt first, InputIt last, size_type bucket_count,
+ const Hash &hash, const Allocator &alloc)
+ : sparse_map(first, last, bucket_count, hash, KeyEqual(), alloc) {}
+
+ sparse_map(std::initializer_list<value_type> init,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKET_COUNT,
+ const Hash &hash = Hash(), const KeyEqual &equal = KeyEqual(),
+ const Allocator &alloc = Allocator())
+ : sparse_map(init.begin(), init.end(), bucket_count, hash, equal, alloc) {
+ }
+
+ sparse_map(std::initializer_list<value_type> init, size_type bucket_count,
+ const Allocator &alloc)
+ : sparse_map(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(),
+ alloc) {}
+
+ sparse_map(std::initializer_list<value_type> init, size_type bucket_count,
+ const Hash &hash, const Allocator &alloc)
+ : sparse_map(init.begin(), init.end(), bucket_count, hash, KeyEqual(),
+ alloc) {}
+
+ sparse_map &operator=(std::initializer_list<value_type> ilist) {
+ m_ht.clear();
+
+ m_ht.reserve(ilist.size());
+ m_ht.insert(ilist.begin(), ilist.end());
+
+ return *this;
+ }
+
+ allocator_type get_allocator() const { return m_ht.get_allocator(); }
+
+ /*
+ * Iterators
+ */
+ iterator begin() noexcept { return m_ht.begin(); }
+ const_iterator begin() const noexcept { return m_ht.begin(); }
+ const_iterator cbegin() const noexcept { return m_ht.cbegin(); }
+
+ iterator end() noexcept { return m_ht.end(); }
+ const_iterator end() const noexcept { return m_ht.end(); }
+ const_iterator cend() const noexcept { return m_ht.cend(); }
+
+ /*
+ * Capacity
+ */
+ bool empty() const noexcept { return m_ht.empty(); }
+ size_type size() const noexcept { return m_ht.size(); }
+ size_type max_size() const noexcept { return m_ht.max_size(); }
+
+ /*
+ * Modifiers
+ */
+ void clear() noexcept { m_ht.clear(); }
+
+ std::pair<iterator, bool> insert(const value_type &value) {
+ return m_ht.insert(value);
+ }
+
+ template <class P, typename std::enable_if<std::is_constructible<
+ value_type, P &&>::value>::type * = nullptr>
+ std::pair<iterator, bool> insert(P &&value) {
+ return m_ht.emplace(std::forward<P>(value));
+ }
+
+ std::pair<iterator, bool> insert(value_type &&value) {
+ return m_ht.insert(std::move(value));
+ }
+
+ iterator insert(const_iterator hint, const value_type &value) {
+ return m_ht.insert_hint(hint, value);
+ }
+
+ template <class P, typename std::enable_if<std::is_constructible<
+ value_type, P &&>::value>::type * = nullptr>
+ iterator insert(const_iterator hint, P &&value) {
+ return m_ht.emplace_hint(hint, std::forward<P>(value));
+ }
+
+ iterator insert(const_iterator hint, value_type &&value) {
+ return m_ht.insert_hint(hint, std::move(value));
+ }
+
+ template <class InputIt>
+ void insert(InputIt first, InputIt last) {
+ m_ht.insert(first, last);
+ }
+
+ void insert(std::initializer_list<value_type> ilist) {
+ m_ht.insert(ilist.begin(), ilist.end());
+ }
+
+ template <class M>
+ std::pair<iterator, bool> insert_or_assign(const key_type &k, M &&obj) {
+ return m_ht.insert_or_assign(k, std::forward<M>(obj));
+ }
+
+ template <class M>
+ std::pair<iterator, bool> insert_or_assign(key_type &&k, M &&obj) {
+ return m_ht.insert_or_assign(std::move(k), std::forward<M>(obj));
+ }
+
+ template <class M>
+ iterator insert_or_assign(const_iterator hint, const key_type &k, M &&obj) {
+ return m_ht.insert_or_assign(hint, k, std::forward<M>(obj));
+ }
+
+ template <class M>
+ iterator insert_or_assign(const_iterator hint, key_type &&k, M &&obj) {
+ return m_ht.insert_or_assign(hint, std::move(k), std::forward<M>(obj));
+ }
+
+ /**
+ * Due to the way elements are stored, emplace will need to move or copy the
+ * key-value once. The method is equivalent to
+ * `insert(value_type(std::forward<Args>(args)...));`.
+ *
+ * Mainly here for compatibility with the `std::unordered_map` interface.
+ */
+ template <class... Args>
+ std::pair<iterator, bool> emplace(Args &&...args) {
+ return m_ht.emplace(std::forward<Args>(args)...);
+ }
+
+ /**
+ * Due to the way elements are stored, emplace_hint will need to move or copy
+ * the key-value once. The method is equivalent to `insert(hint,
+ * value_type(std::forward<Args>(args)...));`.
+ *
+ * Mainly here for compatibility with the `std::unordered_map` interface.
+ */
+ template <class... Args>
+ iterator emplace_hint(const_iterator hint, Args &&...args) {
+ return m_ht.emplace_hint(hint, std::forward<Args>(args)...);
+ }
+
+ template <class... Args>
+ std::pair<iterator, bool> try_emplace(const key_type &k, Args &&...args) {
+ return m_ht.try_emplace(k, std::forward<Args>(args)...);
+ }
+
+ template <class... Args>
+ std::pair<iterator, bool> try_emplace(key_type &&k, Args &&...args) {
+ return m_ht.try_emplace(std::move(k), std::forward<Args>(args)...);
+ }
+
+ template <class... Args>
+ iterator try_emplace(const_iterator hint, const key_type &k, Args &&...args) {
+ return m_ht.try_emplace_hint(hint, k, std::forward<Args>(args)...);
+ }
+
+ template <class... Args>
+ iterator try_emplace(const_iterator hint, key_type &&k, Args &&...args) {
+ return m_ht.try_emplace_hint(hint, std::move(k),
+ std::forward<Args>(args)...);
+ }
+
+ iterator erase(iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator first, const_iterator last) {
+ return m_ht.erase(first, last);
+ }
+ size_type erase(const key_type &key) { return m_ht.erase(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ size_type erase(const key_type &key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type erase(const K &key) {
+ return m_ht.erase(key);
+ }
+
+ /**
+ * @copydoc erase(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type erase(const K &key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+ void swap(sparse_map &other) { other.m_ht.swap(m_ht); }
+
+ /*
+ * Lookup
+ */
+ T &at(const Key &key) { return m_ht.at(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ T &at(const Key &key, std::size_t precalculated_hash) {
+ return m_ht.at(key, precalculated_hash);
+ }
+
+ const T &at(const Key &key) const { return m_ht.at(key); }
+
+ /**
+ * @copydoc at(const Key& key, std::size_t precalculated_hash)
+ */
+ const T &at(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.at(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ T &at(const K &key) {
+ return m_ht.at(key);
+ }
+
+ /**
+ * @copydoc at(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ T &at(const K &key, std::size_t precalculated_hash) {
+ return m_ht.at(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc at(const K& key)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ const T &at(const K &key) const {
+ return m_ht.at(key);
+ }
+
+ /**
+ * @copydoc at(const K& key, std::size_t precalculated_hash)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ const T &at(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.at(key, precalculated_hash);
+ }
+
+ T &operator[](const Key &key) { return m_ht[key]; }
+ T &operator[](Key &&key) { return m_ht[std::move(key)]; }
+
+ size_type count(const Key &key) const { return m_ht.count(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ size_type count(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.count(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type count(const K &key) const {
+ return m_ht.count(key);
+ }
+
+ /**
+ * @copydoc count(const K& key) const
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type count(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.count(key, precalculated_hash);
+ }
+
+ iterator find(const Key &key) { return m_ht.find(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ iterator find(const Key &key, std::size_t precalculated_hash) {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ const_iterator find(const Key &key) const { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const Key& key, std::size_t precalculated_hash)
+ */
+ const_iterator find(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ iterator find(const K &key) {
+ return m_ht.find(key);
+ }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ iterator find(const K &key, std::size_t precalculated_hash) {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc find(const K& key)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ const_iterator find(const K &key) const {
+ return m_ht.find(key);
+ }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ const_iterator find(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ bool contains(const Key &key) const { return m_ht.contains(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The
+ * hash value should be the same as hash_function()(key). Useful to speed-up
+ * the lookup if you already have the hash.
+ */
+ bool contains(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.contains(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * KeyEqual::is_transparent exists. If so, K must be hashable and comparable
+ * to Key.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ bool contains(const K &key) const {
+ return m_ht.contains(key);
+ }
+
+ /**
+ * @copydoc contains(const K& key) const
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The
+ * hash value should be the same as hash_function()(key). Useful to speed-up
+ * the lookup if you already have the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ bool contains(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.contains(key, precalculated_hash);
+ }
+
+ std::pair<iterator, iterator> equal_range(const Key &key) {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ std::pair<iterator, iterator> equal_range(const Key &key,
+ std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ std::pair<const_iterator, const_iterator> equal_range(const Key &key) const {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * @copydoc equal_range(const Key& key, std::size_t precalculated_hash)
+ */
+ std::pair<const_iterator, const_iterator> equal_range(
+ const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<iterator, iterator> equal_range(const K &key) {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<iterator, iterator> equal_range(const K &key,
+ std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key, std::size_t precalculated_hash)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(
+ const K &key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /*
+ * Bucket interface
+ */
+ size_type bucket_count() const { return m_ht.bucket_count(); }
+ size_type max_bucket_count() const { return m_ht.max_bucket_count(); }
+
+ /*
+ * Hash policy
+ */
+ float load_factor() const { return m_ht.load_factor(); }
+ float max_load_factor() const { return m_ht.max_load_factor(); }
+ void max_load_factor(float ml) { m_ht.max_load_factor(ml); }
+
+ void rehash(size_type count) { m_ht.rehash(count); }
+ void reserve(size_type count) { m_ht.reserve(count); }
+
+ /*
+ * Observers
+ */
+ hasher hash_function() const { return m_ht.hash_function(); }
+ key_equal key_eq() const { return m_ht.key_eq(); }
+
+ /*
+ * Other
+ */
+
+ /**
+ * Convert a `const_iterator` to an `iterator`.
+ */
+ iterator mutable_iterator(const_iterator pos) {
+ return m_ht.mutable_iterator(pos);
+ }
+
+ /**
+ * Serialize the map through the `serializer` parameter.
+ *
+ * The `serializer` parameter must be a function object that supports the
+ * following call:
+ * - `template<typename U> void operator()(const U& value);` where the types
+ * `std::uint64_t`, `float` and `std::pair<Key, T>` must be supported for U.
+ *
+ * The implementation leaves binary compatibility (endianness, IEEE 754 for
+ * floats, ...) of the types it serializes in the hands of the `Serializer`
+ * function object if compatibility is required.
+ */
+ template <class Serializer>
+ void serialize(Serializer &serializer) const {
+ m_ht.serialize(serializer);
+ }
+
+ /**
+ * Deserialize a previously serialized map through the `deserializer`
+ * parameter.
+ *
+ * The `deserializer` parameter must be a function object that supports the
+ * following calls:
+ * - `template<typename U> U operator()();` where the types `std::uint64_t`,
+ * `float` and `std::pair<Key, T>` must be supported for U.
+ *
+ * If the deserialized hash map type is hash compatible with the serialized
+ * map, the deserialization process can be sped up by setting
+ * `hash_compatible` to true. To be hash compatible, the Hash, KeyEqual and
+ * GrowthPolicy must behave the same way than the ones used on the serialized
+ * map. The `std::size_t` must also be of the same size as the one on the
+ * platform used to serialize the map. If these criteria are not met, the
+ * behaviour is undefined with `hash_compatible` sets to true.
+ *
+ * The behaviour is undefined if the type `Key` and `T` of the `sparse_map`
+ * are not the same as the types used during serialization.
+ *
+ * The implementation leaves binary compatibility (endianness, IEEE 754 for
+ * floats, size of int, ...) of the types it deserializes in the hands of the
+ * `Deserializer` function object if compatibility is required.
+ */
+ template <class Deserializer>
+ static sparse_map deserialize(Deserializer &deserializer,
+ bool hash_compatible = false) {
+ sparse_map map(0);
+ map.m_ht.deserialize(deserializer, hash_compatible);
+
+ return map;
+ }
+
+ friend bool operator==(const sparse_map &lhs, const sparse_map &rhs) {
+ if (lhs.size() != rhs.size()) {
+ return false;
+ }
+
+ for (const auto &element_lhs : lhs) {
+ const auto it_element_rhs = rhs.find(element_lhs.first);
+ if (it_element_rhs == rhs.cend() ||
+ element_lhs.second != it_element_rhs->second) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ friend bool operator!=(const sparse_map &lhs, const sparse_map &rhs) {
+ return !operator==(lhs, rhs);
+ }
+
+ friend void swap(sparse_map &lhs, sparse_map &rhs) { lhs.swap(rhs); }
+
+ private:
+ ht m_ht;
+};
+
+/**
+ * Same as `tsl::sparse_map<Key, T, Hash, KeyEqual, Allocator,
+ * tsl::sh::prime_growth_policy>`.
+ */
+template <class Key, class T, class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<std::pair<Key, T>>>
+using sparse_pg_map =
+ sparse_map<Key, T, Hash, KeyEqual, Allocator, tsl::sh::prime_growth_policy>;
+
+} // end namespace tsl
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_set.h b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_set.h
new file mode 100644
index 0000000..3ce6a58
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/tsl/sparse_set.h
@@ -0,0 +1,655 @@
+/**
+ * MIT License
+ *
+ * Copyright (c) 2017 Thibaut Goetghebuer-Planchon <[email protected]>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+#ifndef TSL_SPARSE_SET_H
+#define TSL_SPARSE_SET_H
+
+#include <cstddef>
+#include <functional>
+#include <initializer_list>
+#include <memory>
+#include <type_traits>
+#include <utility>
+
+#include "sparse_hash.h"
+
+namespace tsl {
+
+/**
+ * Implementation of a sparse hash set using open-addressing with quadratic
+ * probing. The goal on the hash set is to be the most memory efficient
+ * possible, even at low load factor, while keeping reasonable performances.
+ *
+ * `GrowthPolicy` defines how the set grows and consequently how a hash value is
+ * mapped to a bucket. By default the set uses
+ * `tsl::sh::power_of_two_growth_policy`. This policy keeps the number of
+ * buckets to a power of two and uses a mask to map the hash to a bucket instead
+ * of the slow modulo. Other growth policies are available and you may define
+ * your own growth policy, check `tsl::sh::power_of_two_growth_policy` for the
+ * interface.
+ *
+ * `ExceptionSafety` defines the exception guarantee provided by the class. By
+ * default only the basic exception safety is guaranteed which mean that all
+ * resources used by the hash set will be freed (no memory leaks) but the hash
+ * set may end-up in an undefined state if an exception is thrown (undefined
+ * here means that some elements may be missing). This can ONLY happen on rehash
+ * (either on insert or if `rehash` is called explicitly) and will occur if the
+ * Allocator can't allocate memory (`std::bad_alloc`) or if the copy constructor
+ * (when a nothrow move constructor is not available) throws an exception. This
+ * can be avoided by calling `reserve` beforehand. This basic guarantee is
+ * similar to the one of `google::sparse_hash_map` and `spp::sparse_hash_map`.
+ * It is possible to ask for the strong exception guarantee with
+ * `tsl::sh::exception_safety::strong`, the drawback is that the set will be
+ * slower on rehashes and will also need more memory on rehashes.
+ *
+ * `Sparsity` defines how much the hash set will compromise between insertion
+ * speed and memory usage. A high sparsity means less memory usage but longer
+ * insertion times, and vice-versa for low sparsity. The default
+ * `tsl::sh::sparsity::medium` sparsity offers a good compromise. It doesn't
+ * change the lookup speed.
+ *
+ * `Key` must be nothrow move constructible and/or copy constructible.
+ *
+ * If the destructor of `Key` throws an exception, the behaviour of the class is
+ * undefined.
+ *
+ * Iterators invalidation:
+ * - clear, operator=, reserve, rehash: always invalidate the iterators.
+ * - insert, emplace, emplace_hint: if there is an effective insert, invalidate
+ * the iterators.
+ * - erase: always invalidate the iterators.
+ */
+template <class Key, class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<Key>,
+ class GrowthPolicy = tsl::sh::power_of_two_growth_policy<2>,
+ tsl::sh::exception_safety ExceptionSafety =
+ tsl::sh::exception_safety::basic,
+ tsl::sh::sparsity Sparsity = tsl::sh::sparsity::medium>
+class sparse_set {
+ private:
+ template <typename U>
+ using has_is_transparent = tsl::detail_sparse_hash::has_is_transparent<U>;
+
+ class KeySelect {
+ public:
+ using key_type = Key;
+
+ const key_type &operator()(const Key &key) const noexcept { return key; }
+
+ key_type &operator()(Key &key) noexcept { return key; }
+ };
+
+ using ht =
+ detail_sparse_hash::sparse_hash<Key, KeySelect, void, Hash, KeyEqual,
+ Allocator, GrowthPolicy, ExceptionSafety,
+ Sparsity, tsl::sh::probing::quadratic>;
+
+ public:
+ using key_type = typename ht::key_type;
+ using value_type = typename ht::value_type;
+ using size_type = typename ht::size_type;
+ using difference_type = typename ht::difference_type;
+ using hasher = typename ht::hasher;
+ using key_equal = typename ht::key_equal;
+ using allocator_type = typename ht::allocator_type;
+ using reference = typename ht::reference;
+ using const_reference = typename ht::const_reference;
+ using pointer = typename ht::pointer;
+ using const_pointer = typename ht::const_pointer;
+ using iterator = typename ht::iterator;
+ using const_iterator = typename ht::const_iterator;
+
+ /*
+ * Constructors
+ */
+ sparse_set() : sparse_set(ht::DEFAULT_INIT_BUCKET_COUNT) {}
+
+ explicit sparse_set(size_type bucket_count, const Hash &hash = Hash(),
+ const KeyEqual &equal = KeyEqual(),
+ const Allocator &alloc = Allocator())
+ : m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR) {}
+
+ sparse_set(size_type bucket_count, const Allocator &alloc)
+ : sparse_set(bucket_count, Hash(), KeyEqual(), alloc) {}
+
+ sparse_set(size_type bucket_count, const Hash &hash, const Allocator &alloc)
+ : sparse_set(bucket_count, hash, KeyEqual(), alloc) {}
+
+ explicit sparse_set(const Allocator &alloc)
+ : sparse_set(ht::DEFAULT_INIT_BUCKET_COUNT, alloc) {}
+
+ template <class InputIt>
+ sparse_set(InputIt first, InputIt last,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKET_COUNT,
+ const Hash &hash = Hash(), const KeyEqual &equal = KeyEqual(),
+ const Allocator &alloc = Allocator())
+ : sparse_set(bucket_count, hash, equal, alloc) {
+ insert(first, last);
+ }
+
+ template <class InputIt>
+ sparse_set(InputIt first, InputIt last, size_type bucket_count,
+ const Allocator &alloc)
+ : sparse_set(first, last, bucket_count, Hash(), KeyEqual(), alloc) {}
+
+ template <class InputIt>
+ sparse_set(InputIt first, InputIt last, size_type bucket_count,
+ const Hash &hash, const Allocator &alloc)
+ : sparse_set(first, last, bucket_count, hash, KeyEqual(), alloc) {}
+
+ sparse_set(std::initializer_list<value_type> init,
+ size_type bucket_count = ht::DEFAULT_INIT_BUCKET_COUNT,
+ const Hash &hash = Hash(), const KeyEqual &equal = KeyEqual(),
+ const Allocator &alloc = Allocator())
+ : sparse_set(init.begin(), init.end(), bucket_count, hash, equal, alloc) {
+ }
+
+ sparse_set(std::initializer_list<value_type> init, size_type bucket_count,
+ const Allocator &alloc)
+ : sparse_set(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(),
+ alloc) {}
+
+ sparse_set(std::initializer_list<value_type> init, size_type bucket_count,
+ const Hash &hash, const Allocator &alloc)
+ : sparse_set(init.begin(), init.end(), bucket_count, hash, KeyEqual(),
+ alloc) {}
+
+ sparse_set &operator=(std::initializer_list<value_type> ilist) {
+ m_ht.clear();
+
+ m_ht.reserve(ilist.size());
+ m_ht.insert(ilist.begin(), ilist.end());
+
+ return *this;
+ }
+
+ allocator_type get_allocator() const { return m_ht.get_allocator(); }
+
+ /*
+ * Iterators
+ */
+ iterator begin() noexcept { return m_ht.begin(); }
+ const_iterator begin() const noexcept { return m_ht.begin(); }
+ const_iterator cbegin() const noexcept { return m_ht.cbegin(); }
+
+ iterator end() noexcept { return m_ht.end(); }
+ const_iterator end() const noexcept { return m_ht.end(); }
+ const_iterator cend() const noexcept { return m_ht.cend(); }
+
+ /*
+ * Capacity
+ */
+ bool empty() const noexcept { return m_ht.empty(); }
+ size_type size() const noexcept { return m_ht.size(); }
+ size_type max_size() const noexcept { return m_ht.max_size(); }
+
+ /*
+ * Modifiers
+ */
+ void clear() noexcept { m_ht.clear(); }
+
+ std::pair<iterator, bool> insert(const value_type &value) {
+ return m_ht.insert(value);
+ }
+
+ std::pair<iterator, bool> insert(value_type &&value) {
+ return m_ht.insert(std::move(value));
+ }
+
+ iterator insert(const_iterator hint, const value_type &value) {
+ return m_ht.insert_hint(hint, value);
+ }
+
+ iterator insert(const_iterator hint, value_type &&value) {
+ return m_ht.insert_hint(hint, std::move(value));
+ }
+
+ template <class InputIt>
+ void insert(InputIt first, InputIt last) {
+ m_ht.insert(first, last);
+ }
+
+ void insert(std::initializer_list<value_type> ilist) {
+ m_ht.insert(ilist.begin(), ilist.end());
+ }
+
+ /**
+ * Due to the way elements are stored, emplace will need to move or copy the
+ * key-value once. The method is equivalent to
+ * `insert(value_type(std::forward<Args>(args)...));`.
+ *
+ * Mainly here for compatibility with the `std::unordered_map` interface.
+ */
+ template <class... Args>
+ std::pair<iterator, bool> emplace(Args &&...args) {
+ return m_ht.emplace(std::forward<Args>(args)...);
+ }
+
+ /**
+ * Due to the way elements are stored, emplace_hint will need to move or copy
+ * the key-value once. The method is equivalent to `insert(hint,
+ * value_type(std::forward<Args>(args)...));`.
+ *
+ * Mainly here for compatibility with the `std::unordered_map` interface.
+ */
+ template <class... Args>
+ iterator emplace_hint(const_iterator hint, Args &&...args) {
+ return m_ht.emplace_hint(hint, std::forward<Args>(args)...);
+ }
+
+ iterator erase(iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator pos) { return m_ht.erase(pos); }
+ iterator erase(const_iterator first, const_iterator last) {
+ return m_ht.erase(first, last);
+ }
+ size_type erase(const key_type &key) { return m_ht.erase(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ size_type erase(const key_type &key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type erase(const K &key) {
+ return m_ht.erase(key);
+ }
+
+ /**
+ * @copydoc erase(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type erase(const K &key, std::size_t precalculated_hash) {
+ return m_ht.erase(key, precalculated_hash);
+ }
+
+ void swap(sparse_set &other) { other.m_ht.swap(m_ht); }
+
+ /*
+ * Lookup
+ */
+ size_type count(const Key &key) const { return m_ht.count(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ size_type count(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.count(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type count(const K &key) const {
+ return m_ht.count(key);
+ }
+
+ /**
+ * @copydoc count(const K& key) const
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ size_type count(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.count(key, precalculated_hash);
+ }
+
+ iterator find(const Key &key) { return m_ht.find(key); }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ iterator find(const Key &key, std::size_t precalculated_hash) {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ const_iterator find(const Key &key) const { return m_ht.find(key); }
+
+ /**
+ * @copydoc find(const Key& key, std::size_t precalculated_hash)
+ */
+ const_iterator find(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ iterator find(const K &key) {
+ return m_ht.find(key);
+ }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ iterator find(const K &key, std::size_t precalculated_hash) {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc find(const K& key)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ const_iterator find(const K &key) const {
+ return m_ht.find(key);
+ }
+
+ /**
+ * @copydoc find(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ const_iterator find(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.find(key, precalculated_hash);
+ }
+
+ bool contains(const Key &key) const { return m_ht.contains(key); }
+
+ /**
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The
+ * hash value should be the same as hash_function()(key). Useful to speed-up
+ * the lookup if you already have the hash.
+ */
+ bool contains(const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.contains(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * KeyEqual::is_transparent exists. If so, K must be hashable and comparable
+ * to Key.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ bool contains(const K &key) const {
+ return m_ht.contains(key);
+ }
+
+ /**
+ * @copydoc contains(const K& key) const
+ *
+ * Use the hash value 'precalculated_hash' instead of hashing the key. The
+ * hash value should be the same as hash_function()(key). Useful to speed-up
+ * the lookup if you already have the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ bool contains(const K &key, std::size_t precalculated_hash) const {
+ return m_ht.contains(key, precalculated_hash);
+ }
+
+ std::pair<iterator, iterator> equal_range(const Key &key) {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ std::pair<iterator, iterator> equal_range(const Key &key,
+ std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ std::pair<const_iterator, const_iterator> equal_range(const Key &key) const {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * @copydoc equal_range(const Key& key, std::size_t precalculated_hash)
+ */
+ std::pair<const_iterator, const_iterator> equal_range(
+ const Key &key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * This overload only participates in the overload resolution if the typedef
+ * `KeyEqual::is_transparent` exists. If so, `K` must be hashable and
+ * comparable to `Key`.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<iterator, iterator> equal_range(const K &key) {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ *
+ * Use the hash value `precalculated_hash` instead of hashing the key. The
+ * hash value should be the same as `hash_function()(key)`, otherwise the
+ * behaviour is undefined. Useful to speed-up the lookup if you already have
+ * the hash.
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<iterator, iterator> equal_range(const K &key,
+ std::size_t precalculated_hash) {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
+ return m_ht.equal_range(key);
+ }
+
+ /**
+ * @copydoc equal_range(const K& key, std::size_t precalculated_hash)
+ */
+ template <
+ class K, class KE = KeyEqual,
+ typename std::enable_if<has_is_transparent<KE>::value>::type * = nullptr>
+ std::pair<const_iterator, const_iterator> equal_range(
+ const K &key, std::size_t precalculated_hash) const {
+ return m_ht.equal_range(key, precalculated_hash);
+ }
+
+ /*
+ * Bucket interface
+ */
+ size_type bucket_count() const { return m_ht.bucket_count(); }
+ size_type max_bucket_count() const { return m_ht.max_bucket_count(); }
+
+ /*
+ * Hash policy
+ */
+ float load_factor() const { return m_ht.load_factor(); }
+ float max_load_factor() const { return m_ht.max_load_factor(); }
+ void max_load_factor(float ml) { m_ht.max_load_factor(ml); }
+
+ void rehash(size_type count) { m_ht.rehash(count); }
+ void reserve(size_type count) { m_ht.reserve(count); }
+
+ /*
+ * Observers
+ */
+ hasher hash_function() const { return m_ht.hash_function(); }
+ key_equal key_eq() const { return m_ht.key_eq(); }
+
+ /*
+ * Other
+ */
+
+ /**
+ * Convert a `const_iterator` to an `iterator`.
+ */
+ iterator mutable_iterator(const_iterator pos) {
+ return m_ht.mutable_iterator(pos);
+ }
+
+ /**
+ * Serialize the set through the `serializer` parameter.
+ *
+ * The `serializer` parameter must be a function object that supports the
+ * following call:
+ * - `void operator()(const U& value);` where the types `std::uint64_t`,
+ * `float` and `Key` must be supported for U.
+ *
+ * The implementation leaves binary compatibility (endianness, IEEE 754 for
+ * floats, ...) of the types it serializes in the hands of the `Serializer`
+ * function object if compatibility is required.
+ */
+ template <class Serializer>
+ void serialize(Serializer &serializer) const {
+ m_ht.serialize(serializer);
+ }
+
+ /**
+ * Deserialize a previously serialized set through the `deserializer`
+ * parameter.
+ *
+ * The `deserializer` parameter must be a function object that supports the
+ * following calls:
+ * - `template<typename U> U operator()();` where the types `std::uint64_t`,
+ * `float` and `Key` must be supported for U.
+ *
+ * If the deserialized hash set type is hash compatible with the serialized
+ * set, the deserialization process can be sped up by setting
+ * `hash_compatible` to true. To be hash compatible, the Hash, KeyEqual and
+ * GrowthPolicy must behave the same way than the ones used on the serialized
+ * set. The `std::size_t` must also be of the same size as the one on the
+ * platform used to serialize the set. If these criteria are not met, the
+ * behaviour is undefined with `hash_compatible` sets to true.
+ *
+ * The behaviour is undefined if the type `Key` of the `sparse_set` is not the
+ * same as the type used during serialization.
+ *
+ * The implementation leaves binary compatibility (endianness, IEEE 754 for
+ * floats, size of int, ...) of the types it deserializes in the hands of the
+ * `Deserializer` function object if compatibility is required.
+ */
+ template <class Deserializer>
+ static sparse_set deserialize(Deserializer &deserializer,
+ bool hash_compatible = false) {
+ sparse_set set(0);
+ set.m_ht.deserialize(deserializer, hash_compatible);
+
+ return set;
+ }
+
+ friend bool operator==(const sparse_set &lhs, const sparse_set &rhs) {
+ if (lhs.size() != rhs.size()) {
+ return false;
+ }
+
+ for (const auto &element_lhs : lhs) {
+ const auto it_element_rhs = rhs.find(element_lhs);
+ if (it_element_rhs == rhs.cend()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ friend bool operator!=(const sparse_set &lhs, const sparse_set &rhs) {
+ return !operator==(lhs, rhs);
+ }
+
+ friend void swap(sparse_set &lhs, sparse_set &rhs) { lhs.swap(rhs); }
+
+ private:
+ ht m_ht;
+};
+
+/**
+ * Same as `tsl::sparse_set<Key, Hash, KeyEqual, Allocator,
+ * tsl::sh::prime_growth_policy>`.
+ */
+template <class Key, class Hash = std::hash<Key>,
+ class KeyEqual = std::equal_to<Key>,
+ class Allocator = std::allocator<Key>>
+using sparse_pg_set =
+ sparse_set<Key, Hash, KeyEqual, Allocator, tsl::sh::prime_growth_policy>;
+
+} // end namespace tsl
+
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/types.h b/packages/leann-backend-diskann/third_party/DiskANN/include/types.h
new file mode 100644
index 0000000..953d59a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/types.h
@@ -0,0 +1,22 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstdint>
+#include <cstddef>
+#include <any>
+#include "any_wrappers.h"
+
+namespace diskann
+{
+typedef uint32_t location_t;
+
+using DataType = std::any;
+using TagType = std::any;
+using LabelType = std::any;
+using TagVector = AnyWrapper::AnyVector;
+using DataVector = AnyWrapper::AnyVector;
+using Labelvector = AnyWrapper::AnyVector;
+using TagRobinSet = AnyWrapper::AnyRobinSet;
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/utils.h b/packages/leann-backend-diskann/third_party/DiskANN/include/utils.h
new file mode 100644
index 0000000..355a613
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/utils.h
@@ -0,0 +1,1455 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <errno.h>
+
+#include "common_includes.h"
+
+#ifdef __APPLE__
+#include <Accelerate/Accelerate.h>
+#else
+#include <malloc.h>
+#endif
+
+#ifdef _WINDOWS
+#include <Windows.h>
+typedef HANDLE FileHandle;
+#else
+#include <unistd.h>
+typedef int FileHandle;
+#endif
+
+#include "distance.h"
+#include "logger.h"
+#include "cached_io.h"
+#include "ann_exception.h"
+#include "windows_customizations.h"
+#include "tsl/robin_set.h"
+#include "types.h"
+#include "tag_uint128.h"
+#include <any>
+
+#ifdef EXEC_ENV_OLS
+#include "content_buf.h"
+#include "memory_mapped_files.h"
+#endif
+
+#ifdef __APPLE__
+#ifdef __arm64__
+#define _MM_HINT_T0 1
+#define _MM_HINT_T1 2
+
+static inline __attribute__((always_inline)) void _mm_prefetch(char const *p, int i)
+{
+ switch (i)
+ {
+ case _MM_HINT_T0:
+ __builtin_prefetch(p, 0, 3);
+ break;
+ case _MM_HINT_T1:
+ __builtin_prefetch(p, 0, 2);
+ break;
+ }
+}
+#endif
+
+#define LAPACK_COL_MAJOR 1
+#define LAPACK_ROW_MAJOR 0
+#ifdef __APPLE__
+typedef int clp_int;
+#else
+typedef __CLPK_integer clp_int;
+#endif
+
+inline void _sge_trans(int matrix_layout, clp_int m, clp_int n, const float *in, clp_int ldin, float *out,
+ clp_int ldout)
+{
+ clp_int i, j, x, y;
+
+ if (matrix_layout == LAPACK_COL_MAJOR)
+ {
+ x = n;
+ y = m;
+ }
+ else
+ {
+ x = m;
+ y = n;
+ }
+ for (i = 0; i < MIN(y, ldin); i++)
+ {
+ for (j = 0; j < MIN(x, ldout); j++)
+ {
+ out[(size_t)i * ldout + j] = in[(size_t)j * ldin + i];
+ }
+ }
+}
+inline clp_int sgesdd_rm_work(char jobz, clp_int m, clp_int n, float *a, clp_int lda, float *s, float *u, clp_int ldu,
+ float *vt, clp_int ldvt, float *work, clp_int lwork, clp_int *iwork)
+{
+ clp_int info = 0;
+ clp_int nrows_u = ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && m < n)) ? m : 1;
+ clp_int ncols_u = ((jobz == 'a') || ((jobz == 'o') && m < n)) ? m : ((jobz == 's') ? MIN(m, n) : 1);
+ clp_int nrows_vt = ((jobz == 'a') || ((jobz == 'o') && m >= n)) ? n : ((jobz == 's') ? MIN(m, n) : 1);
+
+ clp_int lda_t = MAX(1, m);
+ clp_int ldu_t = MAX(1, nrows_u);
+ clp_int ldvt_t = MAX(1, nrows_vt);
+ float *a_t = NULL;
+ float *u_t = NULL;
+ float *vt_t = NULL;
+
+ // check leading dimensions
+ if (lda < n)
+ {
+ info = -6;
+ return info;
+ }
+ if (ldu < ncols_u)
+ {
+ info = -9;
+ return info;
+ }
+ if (ldvt < n)
+ {
+ info = -11;
+ return info;
+ }
+
+ // query for optimal work size if lwork = -1
+ if (lwork == -1)
+ {
+ sgesdd_(&jobz, &m, &n, a, &lda_t, s, u, &ldu_t, vt, &ldvt_t, work, &lwork, iwork, &info);
+ return (info < 0) ? (info - 1) : info;
+ }
+
+ // setup temp arrays
+ a_t = (float *)malloc(sizeof(float) * lda_t * MAX(1, n));
+ if (a_t == NULL)
+ {
+ info = -1011;
+ return info;
+ }
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m < n)))
+ {
+ u_t = (float *)malloc(sizeof(float) * ldu_t * MAX(1, ncols_u));
+ if (u_t == NULL)
+ {
+ info = -1011;
+ free(a_t);
+ return info;
+ }
+ }
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m >= n)))
+ {
+ vt_t = (float *)malloc(sizeof(float) * ldvt_t * MAX(1, n));
+ if (vt_t == NULL)
+ {
+ info = -1011;
+ free(a_t);
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m < n)))
+ {
+ free(u_t);
+ }
+ return info;
+ }
+ }
+
+ _sge_trans(LAPACK_ROW_MAJOR, m, n, a, lda, a_t, lda_t);
+ sgesdd_(&jobz, &m, &n, a_t, &lda_t, s, u_t, &ldu_t, vt_t, &ldvt_t, work, &lwork, iwork, &info);
+
+ if (info < 0)
+ {
+ info = info - 1;
+ }
+ /* Transpose output matrices */
+ _sge_trans(LAPACK_COL_MAJOR, m, n, a_t, lda_t, a, lda);
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m < n)))
+ {
+ _sge_trans(LAPACK_COL_MAJOR, nrows_u, ncols_u, u_t, ldu_t, u, ldu);
+ }
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m >= n)))
+ {
+ _sge_trans(LAPACK_COL_MAJOR, nrows_vt, n, vt_t, ldvt_t, vt, ldvt);
+ }
+ /* Release memory and exit */
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m >= n)))
+ {
+ free(vt_t);
+ }
+ if ((jobz == 'a') || (jobz == 's') || ((jobz == 'o') && (m < n)))
+ {
+ free(u_t);
+ }
+ free(a_t);
+ return info;
+}
+
+inline clp_int LAPACKE_sgesdd(int matrix_layout, char jobz, clp_int m, clp_int n, float *a, clp_int lda, float *s,
+ float *u, clp_int ldu, float *vt, clp_int ldvt)
+{
+ // internal SGESDD vars
+ clp_int info = 0;
+ clp_int lwork = -1;
+ clp_int *iwork = NULL;
+ float *work = NULL;
+ float work_query;
+
+ // allocate space for iwork
+ iwork = (clp_int *)malloc(sizeof(clp_int) * MAX(1, 8 * MIN(m, n)));
+ if (iwork == NULL)
+ throw;
+ /* Query optimal working array(s) size */
+ info = sgesdd_rm_work(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, &work_query, lwork, iwork);
+ if (info != 0)
+ {
+ free(iwork);
+ info = -1010;
+ return info;
+ }
+
+ lwork = (clp_int)work_query;
+ /* Allocate memory for work arrays */
+ work = (float *)malloc(sizeof(float) * lwork);
+ if (work == NULL)
+ throw;
+
+ /* Call middle-level interface */
+ info = sgesdd_rm_work(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork);
+ /* Release memory and exit */
+ free(work);
+ free(iwork);
+ return info;
+}
+#endif
+
+// taken from
+// https://github.com/Microsoft/BLAS-on-flash/blob/master/include/utils.h
+// round up X to the nearest multiple of Y
+#define ROUND_UP(X, Y) ((((uint64_t)(X) / (Y)) + ((uint64_t)(X) % (Y) != 0)) * (Y))
+
+#define DIV_ROUND_UP(X, Y) (((uint64_t)(X) / (Y)) + ((uint64_t)(X) % (Y) != 0))
+
+// round down X to the nearest multiple of Y
+#define ROUND_DOWN(X, Y) (((uint64_t)(X) / (Y)) * (Y))
+
+// alignment tests
+#define IS_ALIGNED(X, Y) ((uint64_t)(X) % (uint64_t)(Y) == 0)
+#define IS_512_ALIGNED(X) IS_ALIGNED(X, 512)
+#define IS_4096_ALIGNED(X) IS_ALIGNED(X, 4096)
+#define METADATA_SIZE \
+ 4096 // all metadata of individual sub-component files is written in first
+ // 4KB for unified files
+
+#define BUFFER_SIZE_FOR_CACHED_IO (size_t)1024 * (size_t)1048576
+
+#define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
+#define PBWIDTH 60
+
+inline bool file_exists_impl(const std::string &name, bool dirCheck = false)
+{
+ int val;
+#ifndef _WINDOWS
+ struct stat buffer;
+ val = stat(name.c_str(), &buffer);
+#else
+ // It is the 21st century but Windows API still thinks in 32-bit terms.
+ // Turns out calling stat() on a file > 4GB results in errno = 132
+ // (OVERFLOW). How silly is this!? So calling _stat64()
+ struct _stat64 buffer;
+ val = _stat64(name.c_str(), &buffer);
+#endif
+
+ if (val != 0)
+ {
+ switch (errno)
+ {
+ case EINVAL:
+ diskann::cout << "Invalid argument passed to stat()" << std::endl;
+ break;
+ case ENOENT:
+ // file is not existing, not an issue, so we won't cout anything.
+ break;
+ default:
+ diskann::cout << "Unexpected error in stat():" << errno << std::endl;
+ break;
+ }
+ return false;
+ }
+ else
+ {
+ // the file entry exists. If reqd, check if this is a directory.
+ return dirCheck ? buffer.st_mode & S_IFDIR : true;
+ }
+}
+
+inline bool file_exists(const std::string &name, bool dirCheck = false)
+{
+#ifdef EXEC_ENV_OLS
+ bool exists = file_exists_impl(name, dirCheck);
+ if (exists)
+ {
+ return true;
+ }
+ if (!dirCheck)
+ {
+ // try with .enc extension
+ std::string enc_name = name + ENCRYPTED_EXTENSION;
+ return file_exists_impl(enc_name, dirCheck);
+ }
+ else
+ {
+ return exists;
+ }
+#else
+ return file_exists_impl(name, dirCheck);
+#endif
+}
+
+inline void open_file_to_write(std::ofstream &writer, const std::string &filename)
+{
+ writer.exceptions(std::ofstream::failbit | std::ofstream::badbit);
+ if (!file_exists(filename))
+ writer.open(filename, std::ios::binary | std::ios::out);
+ else
+ writer.open(filename, std::ios::binary | std::ios::in | std::ios::out);
+
+ if (writer.fail())
+ {
+ char buff[1024];
+#ifdef _WINDOWS
+ auto ret = std::to_string(strerror_s(buff, 1024, errno));
+#elif __APPLE__
+ auto ret = std::to_string(strerror_r(errno, buff, 1024));
+#else
+ auto ret = std::string(strerror_r(errno, buff, 1024));
+#endif
+ auto message = std::string("Failed to open file") + filename + " for write because " + buff + ", ret=" + ret;
+ diskann::cerr << message << std::endl;
+ throw diskann::ANNException(message, -1);
+ }
+}
+
+inline size_t get_file_size(const std::string &fname)
+{
+ std::ifstream reader(fname, std::ios::binary | std::ios::ate);
+ if (!reader.fail() && reader.is_open())
+ {
+ size_t end_pos = reader.tellg();
+ reader.close();
+ return end_pos;
+ }
+ else
+ {
+ diskann::cerr << "Could not open file: " << fname << std::endl;
+ return 0;
+ }
+}
+
+inline int delete_file(const std::string &fileName)
+{
+ if (file_exists(fileName))
+ {
+ auto rc = ::remove(fileName.c_str());
+ if (rc != 0)
+ {
+ diskann::cerr << "Could not delete file: " << fileName
+ << " even though it exists. This might indicate a permissions "
+ "issue. "
+ "If you see this message, please contact the diskann team."
+ << std::endl;
+ }
+ return rc;
+ }
+ else
+ {
+ return 0;
+ }
+}
+
+// generates formatted_label and _labels_map file.
+inline void convert_labels_string_to_int(const std::string &inFileName, const std::string &outFileName,
+ const std::string &mapFileName, const std::string &unv_label)
+{
+ std::unordered_map<std::string, uint32_t> string_int_map;
+ std::ofstream label_writer(outFileName);
+ std::ifstream label_reader(inFileName);
+ if (unv_label != "")
+ string_int_map[unv_label] = 0; // if universal label is provided map it to 0 always
+ std::string line, token;
+ while (std::getline(label_reader, line))
+ {
+ std::istringstream new_iss(line);
+ std::vector<uint32_t> lbls;
+ while (getline(new_iss, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ if (string_int_map.find(token) == string_int_map.end())
+ {
+ uint32_t nextId = (uint32_t)string_int_map.size() + 1;
+ string_int_map[token] = nextId; // nextId can never be 0
+ }
+ lbls.push_back(string_int_map[token]);
+ }
+ if (lbls.size() <= 0)
+ {
+ std::cout << "No label found";
+ exit(-1);
+ }
+ for (size_t j = 0; j < lbls.size(); j++)
+ {
+ if (j != lbls.size() - 1)
+ label_writer << lbls[j] << ",";
+ else
+ label_writer << lbls[j] << std::endl;
+ }
+ }
+ label_writer.close();
+
+ std::ofstream map_writer(mapFileName);
+ for (auto mp : string_int_map)
+ {
+ map_writer << mp.first << "\t" << mp.second << std::endl;
+ }
+ map_writer.close();
+}
+
+#ifdef EXEC_ENV_OLS
+class AlignedFileReader;
+#endif
+
+namespace diskann
+{
+static const size_t MAX_SIZE_OF_STREAMBUF = 2LL * 1024 * 1024 * 1024;
+
+inline void print_error_and_terminate(std::stringstream &error_stream)
+{
+ diskann::cerr << error_stream.str() << std::endl;
+ throw diskann::ANNException(error_stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+}
+
+inline void report_memory_allocation_failure()
+{
+ std::stringstream stream;
+ stream << "Memory Allocation Failed.";
+ print_error_and_terminate(stream);
+}
+
+inline void report_misalignment_of_requested_size(size_t align)
+{
+ std::stringstream stream;
+ stream << "Requested memory size is not a multiple of " << align << ". Can not be allocated.";
+ print_error_and_terminate(stream);
+}
+
+inline void alloc_aligned(void **ptr, size_t size, size_t align)
+{
+ *ptr = nullptr;
+ if (IS_ALIGNED(size, align) == 0)
+ report_misalignment_of_requested_size(align);
+#ifdef _WINDOWS
+ *ptr = ::_aligned_malloc(size, align); // note the swapped arguments!
+#elif __APPLE__
+ int err = posix_memalign(ptr, align, size);
+ if (err)
+ {
+ std::cout << err << std::endl;
+ throw;
+ }
+#else
+ *ptr = ::aligned_alloc(align, size);
+#endif
+ if (*ptr == nullptr)
+ report_memory_allocation_failure();
+}
+
+inline void realloc_aligned(void **ptr, size_t size, size_t align)
+{
+ if (IS_ALIGNED(size, align) == 0)
+ report_misalignment_of_requested_size(align);
+#ifdef _WINDOWS
+ *ptr = ::_aligned_realloc(*ptr, size, align);
+#else
+ diskann::cerr << "No aligned realloc on GCC. Must malloc and mem_align, "
+ "left it out for now."
+ << std::endl;
+#endif
+ if (*ptr == nullptr)
+ report_memory_allocation_failure();
+}
+
+inline void check_stop(std::string arnd)
+{
+ int brnd;
+ diskann::cout << arnd << std::endl;
+ std::cin >> brnd;
+}
+
+inline void aligned_free(void *ptr)
+{
+ // Gopal. Must have a check here if the pointer was actually allocated by
+ // _alloc_aligned
+ if (ptr == nullptr)
+ {
+ return;
+ }
+#ifndef _WINDOWS
+ free(ptr);
+#else
+ ::_aligned_free(ptr);
+#endif
+}
+
+inline void GenRandom(std::mt19937 &rng, unsigned *addr, unsigned size, unsigned N)
+{
+ for (unsigned i = 0; i < size; ++i)
+ {
+ addr[i] = rng() % (N - size);
+ }
+
+ std::sort(addr, addr + size);
+ for (unsigned i = 1; i < size; ++i)
+ {
+ if (addr[i] <= addr[i - 1])
+ {
+ addr[i] = addr[i - 1] + 1;
+ }
+ }
+ unsigned off = rng() % N;
+ for (unsigned i = 0; i < size; ++i)
+ {
+ addr[i] = (addr[i] + off) % N;
+ }
+}
+
+// get_bin_metadata functions START
+inline void get_bin_metadata_impl(std::basic_istream<char> &reader, size_t &nrows, size_t &ncols, size_t offset = 0)
+{
+ int nrows_32, ncols_32;
+ reader.seekg(offset, reader.beg);
+ reader.read((char *)&nrows_32, sizeof(int));
+ reader.read((char *)&ncols_32, sizeof(int));
+ nrows = nrows_32;
+ ncols = ncols_32;
+}
+
+#ifdef EXEC_ENV_OLS
+inline void get_bin_metadata(MemoryMappedFiles &files, const std::string &bin_file, size_t &nrows, size_t &ncols,
+ size_t offset = 0)
+{
+ diskann::cout << "Getting metadata for file: " << bin_file << std::endl;
+ auto fc = files.getContent(bin_file);
+ // auto cb = ContentBuf((char*) fc._content, fc._size);
+ // std::basic_istream<char> reader(&cb);
+ // get_bin_metadata_impl(reader, nrows, ncols, offset);
+
+ int nrows_32, ncols_32;
+ int32_t *metadata_ptr = (int32_t *)((char *)fc._content + offset);
+ nrows_32 = *metadata_ptr;
+ ncols_32 = *(metadata_ptr + 1);
+ nrows = nrows_32;
+ ncols = ncols_32;
+}
+#endif
+
+inline void get_bin_metadata(const std::string &bin_file, size_t &nrows, size_t &ncols, size_t offset = 0)
+{
+ std::ifstream reader(bin_file.c_str(), std::ios::binary);
+ get_bin_metadata_impl(reader, nrows, ncols, offset);
+}
+// get_bin_metadata functions END
+
+#ifndef EXEC_ENV_OLS
+inline size_t get_graph_num_frozen_points(const std::string &graph_file)
+{
+ size_t expected_file_size;
+ uint32_t max_observed_degree, start;
+ size_t file_frozen_pts;
+
+ std::ifstream in;
+ in.exceptions(std::ios::badbit | std::ios::failbit);
+
+ in.open(graph_file, std::ios::binary);
+ in.read((char *)&expected_file_size, sizeof(size_t));
+ in.read((char *)&max_observed_degree, sizeof(uint32_t));
+ in.read((char *)&start, sizeof(uint32_t));
+ in.read((char *)&file_frozen_pts, sizeof(size_t));
+
+ return file_frozen_pts;
+}
+#endif
+
+template <typename T> inline std::string getValues(T *data, size_t num)
+{
+ std::stringstream stream;
+ stream << "[";
+ for (size_t i = 0; i < num; i++)
+ {
+ stream << std::to_string(data[i]) << ",";
+ }
+ stream << "]" << std::endl;
+
+ return stream.str();
+}
+
+// load_bin functions START
+template <typename T>
+inline void load_bin_impl(std::basic_istream<char> &reader, T *&data, size_t &npts, size_t &dim, size_t file_offset = 0)
+{
+ int npts_i32, dim_i32;
+
+ reader.seekg(file_offset, reader.beg);
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (unsigned)npts_i32;
+ dim = (unsigned)dim_i32;
+
+ std::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "..." << std::endl;
+
+ data = new T[npts * dim];
+ reader.read((char *)data, npts * dim * sizeof(T));
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T>
+inline void load_bin(MemoryMappedFiles &files, const std::string &bin_file, T *&data, size_t &npts, size_t &dim,
+ size_t offset = 0)
+{
+ diskann::cout << "Reading bin file " << bin_file.c_str() << " at offset: " << offset << "..." << std::endl;
+ auto fc = files.getContent(bin_file);
+
+ uint32_t t_npts, t_dim;
+ uint32_t *contentAsIntPtr = (uint32_t *)((char *)fc._content + offset);
+ t_npts = *(contentAsIntPtr);
+ t_dim = *(contentAsIntPtr + 1);
+
+ npts = t_npts;
+ dim = t_dim;
+
+ data = (T *)((char *)fc._content + offset + 2 * sizeof(uint32_t)); // No need to copy!
+}
+
+DISKANN_DLLEXPORT void get_bin_metadata(AlignedFileReader &reader, size_t &npts, size_t &ndim, size_t offset = 0);
+template <typename T>
+DISKANN_DLLEXPORT void load_bin(AlignedFileReader &reader, T *&data, size_t &npts, size_t &ndim, size_t offset = 0);
+template <typename T>
+DISKANN_DLLEXPORT void load_bin(AlignedFileReader &reader, std::unique_ptr<T[]> &data, size_t &npts, size_t &ndim,
+ size_t offset = 0);
+
+template <typename T>
+DISKANN_DLLEXPORT void copy_aligned_data_from_file(AlignedFileReader &reader, T *&data, size_t &npts, size_t &dim,
+ const size_t &rounded_dim, size_t offset = 0);
+
+// Unlike load_bin, assumes that data is already allocated 'size' entries
+template <typename T>
+DISKANN_DLLEXPORT void read_array(AlignedFileReader &reader, T *data, size_t size, size_t offset = 0);
+
+template <typename T> DISKANN_DLLEXPORT void read_value(AlignedFileReader &reader, T &value, size_t offset = 0);
+#endif
+
+template <typename T>
+inline void load_bin(const std::string &bin_file, T *&data, size_t &npts, size_t &dim, size_t offset = 0)
+{
+ diskann::cout << "Reading bin file " << bin_file.c_str() << " ..." << std::endl;
+ std::ifstream reader;
+ reader.exceptions(std::ifstream::failbit | std::ifstream::badbit);
+
+ try
+ {
+ diskann::cout << "Opening bin file " << bin_file.c_str() << "... " << std::endl;
+ reader.open(bin_file, std::ios::binary | std::ios::ate);
+ reader.seekg(0);
+ load_bin_impl<T>(reader, data, npts, dim, offset);
+ }
+ catch (std::system_error &e)
+ {
+ throw FileException(bin_file, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ diskann::cout << "done." << std::endl;
+}
+
+inline void wait_for_keystroke()
+{
+ int a;
+ std::cout << "Press any number to continue.." << std::endl;
+ std::cin >> a;
+}
+// load_bin functions END
+
+inline void load_truthset(const std::string &bin_file, uint32_t *&ids, float *&dists, size_t &npts, size_t &dim)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream reader(bin_file, read_blk_size);
+ diskann::cout << "Reading truthset file " << bin_file.c_str() << " ..." << std::endl;
+ size_t actual_file_size = reader.get_file_size();
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (unsigned)npts_i32;
+ dim = (unsigned)dim_i32;
+
+ diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "... " << std::endl;
+
+ int truthset_type = -1; // 1 means truthset has ids and distances, 2 means
+ // only ids, -1 is error
+ size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_with_dists)
+ truthset_type = 1;
+
+ size_t expected_file_size_just_ids = npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_just_ids)
+ truthset_type = 2;
+
+ if (truthset_type == -1)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. File should have bin format, with "
+ "npts followed by ngt followed by npts*ngt ids and optionally "
+ "followed by npts*ngt distance values; actual size: "
+ << actual_file_size << ", expected: " << expected_file_size_with_dists << " or "
+ << expected_file_size_just_ids;
+ diskann::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ ids = new uint32_t[npts * dim];
+ reader.read((char *)ids, npts * dim * sizeof(uint32_t));
+
+ if (truthset_type == 1)
+ {
+ dists = new float[npts * dim];
+ reader.read((char *)dists, npts * dim * sizeof(float));
+ }
+}
+
+inline void prune_truthset_for_range(const std::string &bin_file, float range,
+ std::vector<std::vector<uint32_t>> &groundtruth, size_t &npts)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream reader(bin_file, read_blk_size);
+ diskann::cout << "Reading truthset file " << bin_file.c_str() << "... " << std::endl;
+ size_t actual_file_size = reader.get_file_size();
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (unsigned)npts_i32;
+ uint64_t dim = (unsigned)dim_i32;
+ uint32_t *ids;
+ float *dists;
+
+ diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "... " << std::endl;
+
+ int truthset_type = -1; // 1 means truthset has ids and distances, 2 means
+ // only ids, -1 is error
+ size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
+
+ if (actual_file_size == expected_file_size_with_dists)
+ truthset_type = 1;
+
+ if (truthset_type == -1)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. File should have bin format, with "
+ "npts followed by ngt followed by npts*ngt ids and optionally "
+ "followed by npts*ngt distance values; actual size: "
+ << actual_file_size << ", expected: " << expected_file_size_with_dists;
+ diskann::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ ids = new uint32_t[npts * dim];
+ reader.read((char *)ids, npts * dim * sizeof(uint32_t));
+
+ if (truthset_type == 1)
+ {
+ dists = new float[npts * dim];
+ reader.read((char *)dists, npts * dim * sizeof(float));
+ }
+ float min_dist = std::numeric_limits<float>::max();
+ float max_dist = 0;
+ groundtruth.resize(npts);
+ for (uint32_t i = 0; i < npts; i++)
+ {
+ groundtruth[i].clear();
+ for (uint32_t j = 0; j < dim; j++)
+ {
+ if (dists[i * dim + j] <= range)
+ {
+ groundtruth[i].emplace_back(ids[i * dim + j]);
+ }
+ min_dist = min_dist > dists[i * dim + j] ? dists[i * dim + j] : min_dist;
+ max_dist = max_dist < dists[i * dim + j] ? dists[i * dim + j] : max_dist;
+ }
+ // std::cout<<groundtruth[i].size() << " " ;
+ }
+ std::cout << "Min dist: " << min_dist << ", Max dist: " << max_dist << std::endl;
+ delete[] ids;
+ delete[] dists;
+}
+
+inline void load_range_truthset(const std::string &bin_file, std::vector<std::vector<uint32_t>> &groundtruth,
+ size_t &gt_num)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream reader(bin_file, read_blk_size);
+ diskann::cout << "Reading truthset file " << bin_file.c_str() << "... " << std::flush;
+ size_t actual_file_size = reader.get_file_size();
+
+ int nptsuint32_t, totaluint32_t;
+ reader.read((char *)&nptsuint32_t, sizeof(int));
+ reader.read((char *)&totaluint32_t, sizeof(int));
+
+ gt_num = (uint64_t)nptsuint32_t;
+ uint64_t total_res = (uint64_t)totaluint32_t;
+
+ diskann::cout << "Metadata: #pts = " << gt_num << ", #total_results = " << total_res << "..." << std::endl;
+
+ size_t expected_file_size = 2 * sizeof(uint32_t) + gt_num * sizeof(uint32_t) + total_res * sizeof(uint32_t);
+
+ if (actual_file_size != expected_file_size)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch in range truthset. actual size: " << actual_file_size
+ << ", expected: " << expected_file_size;
+ diskann::cout << stream.str();
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ groundtruth.clear();
+ groundtruth.resize(gt_num);
+ std::vector<uint32_t> gt_count(gt_num);
+
+ reader.read((char *)gt_count.data(), sizeof(uint32_t) * gt_num);
+
+ std::vector<uint32_t> gt_stats(gt_count);
+ std::sort(gt_stats.begin(), gt_stats.end());
+
+ std::cout << "GT count percentiles:" << std::endl;
+ for (uint32_t p = 0; p < 100; p += 5)
+ std::cout << "percentile " << p << ": " << gt_stats[static_cast<size_t>(std::floor((p / 100.0) * gt_num))]
+ << std::endl;
+ std::cout << "percentile 100"
+ << ": " << gt_stats[gt_num - 1] << std::endl;
+
+ for (uint32_t i = 0; i < gt_num; i++)
+ {
+ groundtruth[i].clear();
+ groundtruth[i].resize(gt_count[i]);
+ if (gt_count[i] != 0)
+ reader.read((char *)groundtruth[i].data(), sizeof(uint32_t) * gt_count[i]);
+ }
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T>
+inline void load_bin(MemoryMappedFiles &files, const std::string &bin_file, std::unique_ptr<T[]> &data, size_t &npts,
+ size_t &dim, size_t offset = 0)
+{
+ T *ptr;
+ load_bin<T>(files, bin_file, ptr, npts, dim, offset);
+ data.reset(ptr);
+}
+#endif
+
+inline void copy_file(std::string in_file, std::string out_file)
+{
+ std::ifstream source(in_file, std::ios::binary);
+ std::ofstream dest(out_file, std::ios::binary);
+
+ std::istreambuf_iterator<char> begin_source(source);
+ std::istreambuf_iterator<char> end_source;
+ std::ostreambuf_iterator<char> begin_dest(dest);
+ std::copy(begin_source, end_source, begin_dest);
+
+ source.close();
+ dest.close();
+}
+
+DISKANN_DLLEXPORT double calculate_recall(unsigned num_queries, unsigned *gold_std, float *gs_dist, unsigned dim_gs,
+ unsigned *our_results, unsigned dim_or, unsigned recall_at);
+
+DISKANN_DLLEXPORT double calculate_recall(unsigned num_queries, unsigned *gold_std, float *gs_dist, unsigned dim_gs,
+ unsigned *our_results, unsigned dim_or, unsigned recall_at,
+ const tsl::robin_set<unsigned> &active_tags);
+
+DISKANN_DLLEXPORT double calculate_range_search_recall(unsigned num_queries,
+ std::vector<std::vector<uint32_t>> &groundtruth,
+ std::vector<std::vector<uint32_t>> &our_results);
+
+template <typename T>
+inline void load_bin(const std::string &bin_file, std::unique_ptr<T[]> &data, size_t &npts, size_t &dim,
+ size_t offset = 0)
+{
+ T *ptr;
+ load_bin<T>(bin_file, ptr, npts, dim, offset);
+ data.reset(ptr);
+}
+
+inline void open_file_to_write(std::ofstream &writer, const std::string &filename)
+{
+ writer.exceptions(std::ofstream::failbit | std::ofstream::badbit);
+ if (!file_exists(filename))
+ writer.open(filename, std::ios::binary | std::ios::out);
+ else
+ writer.open(filename, std::ios::binary | std::ios::in | std::ios::out);
+
+ if (writer.fail())
+ {
+ char buff[1024];
+#ifdef _WINDOWS
+ auto ret = std::to_string(strerror_s(buff, 1024, errno));
+#elif __APPLE__
+ auto ret = std::to_string(strerror_r(errno, buff, 1024));
+#else
+ auto ret = std::string(strerror_r(errno, buff, 1024));
+#endif
+
+ std::string error_message =
+ std::string("Failed to open file") + filename + " for write because " + buff + ", ret=" + ret;
+ diskann::cerr << error_message << std::endl;
+ throw diskann::ANNException(error_message, -1);
+ }
+}
+
+template <typename T>
+inline size_t save_bin(const std::string &filename, T *data, size_t npts, size_t ndims, size_t offset = 0)
+{
+ std::ofstream writer;
+ open_file_to_write(writer, filename);
+
+ diskann::cout << "Writing bin: " << filename.c_str() << std::endl;
+ writer.seekp(offset, writer.beg);
+ int npts_i32 = (int)npts, ndims_i32 = (int)ndims;
+ size_t bytes_written = npts * ndims * sizeof(T) + 2 * sizeof(uint32_t);
+ writer.write((char *)&npts_i32, sizeof(int));
+ writer.write((char *)&ndims_i32, sizeof(int));
+ diskann::cout << "bin: #pts = " << npts << ", #dims = " << ndims << ", size = " << bytes_written << "B"
+ << std::endl;
+
+ writer.write((char *)data, npts * ndims * sizeof(T));
+ writer.close();
+ diskann::cout << "Finished writing bin." << std::endl;
+ return bytes_written;
+}
+
+inline void print_progress(double percentage)
+{
+ int val = (int)(percentage * 100);
+ int lpad = (int)(percentage * PBWIDTH);
+ int rpad = PBWIDTH - lpad;
+ printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");
+ fflush(stdout);
+}
+
+// load_aligned_bin functions START
+
+template <typename T>
+inline void load_aligned_bin_impl(std::basic_istream<char> &reader, size_t actual_file_size, T *&data, size_t &npts,
+ size_t &dim, size_t &rounded_dim)
+{
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (unsigned)npts_i32;
+ dim = (unsigned)dim_i32;
+
+ size_t expected_actual_file_size = npts * dim * sizeof(T) + 2 * sizeof(uint32_t);
+ if (actual_file_size != expected_actual_file_size)
+ {
+ std::stringstream stream;
+ stream << "Error. File size mismatch. Actual size is " << actual_file_size << " while expected size is "
+ << expected_actual_file_size << " npts = " << npts << " dim = " << dim << " size of <T>= " << sizeof(T)
+ << std::endl;
+ diskann::cout << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ rounded_dim = ROUND_UP(dim, 8);
+ diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << ", aligned_dim = " << rounded_dim << "... "
+ << std::flush;
+ size_t allocSize = npts * rounded_dim * sizeof(T);
+ diskann::cout << "allocating aligned memory of " << allocSize << " bytes... " << std::flush;
+ alloc_aligned(((void **)&data), allocSize, 8 * sizeof(T));
+ diskann::cout << "done. Copying data to mem_aligned buffer..." << std::flush;
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ reader.read((char *)(data + i * rounded_dim), dim * sizeof(T));
+ memset(data + i * rounded_dim + dim, 0, (rounded_dim - dim) * sizeof(T));
+ }
+ diskann::cout << " done." << std::endl;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T>
+inline void load_aligned_bin(MemoryMappedFiles &files, const std::string &bin_file, T *&data, size_t &npts, size_t &dim,
+ size_t &rounded_dim)
+{
+ try
+ {
+ diskann::cout << "Opening bin file " << bin_file << " ..." << std::flush;
+ FileContent fc = files.getContent(bin_file);
+ ContentBuf buf((char *)fc._content, fc._size);
+ std::basic_istream<char> reader(&buf);
+
+ size_t actual_file_size = fc._size;
+ load_aligned_bin_impl(reader, actual_file_size, data, npts, dim, rounded_dim);
+ }
+ catch (std::system_error &e)
+ {
+ throw FileException(bin_file, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+#endif
+
+template <typename T>
+inline void load_aligned_bin(const std::string &bin_file, T *&data, size_t &npts, size_t &dim, size_t &rounded_dim)
+{
+ std::ifstream reader;
+ reader.exceptions(std::ifstream::failbit | std::ifstream::badbit);
+
+ try
+ {
+ diskann::cout << "Reading (with alignment) bin file " << bin_file << " ..." << std::flush;
+ reader.open(bin_file, std::ios::binary | std::ios::ate);
+
+ uint64_t fsize = reader.tellg();
+ reader.seekg(0);
+ load_aligned_bin_impl(reader, fsize, data, npts, dim, rounded_dim);
+ }
+ catch (std::system_error &e)
+ {
+ throw FileException(bin_file, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+
+template <typename InType, typename OutType>
+void convert_types(const InType *srcmat, OutType *destmat, size_t npts, size_t dim)
+{
+#pragma omp parallel for schedule(static, 65536)
+ for (int64_t i = 0; i < (int64_t)npts; i++)
+ {
+ for (uint64_t j = 0; j < dim; j++)
+ {
+ destmat[i * dim + j] = (OutType)srcmat[i * dim + j];
+ }
+ }
+}
+
+// this function will take in_file of n*d dimensions and save the output as a
+// floating point matrix
+// with n*(d+1) dimensions. All vectors are scaled by a large value M so that
+// the norms are <=1 and the final coordinate is set so that the resulting
+// norm (in d+1 coordinates) is equal to 1 this is a classical transformation
+// from MIPS to L2 search from "On Symmetric and Asymmetric LSHs for Inner
+// Product Search" by Neyshabur and Srebro
+
+template <typename T> float prepare_base_for_inner_products(const std::string in_file, const std::string out_file)
+{
+ std::cout << "Pre-processing base file by adding extra coordinate" << std::endl;
+ std::ifstream in_reader(in_file.c_str(), std::ios::binary);
+ std::ofstream out_writer(out_file.c_str(), std::ios::binary);
+ uint64_t npts, in_dims, out_dims;
+ float max_norm = 0;
+
+ uint32_t npts32, dims32;
+ in_reader.read((char *)&npts32, sizeof(uint32_t));
+ in_reader.read((char *)&dims32, sizeof(uint32_t));
+
+ npts = npts32;
+ in_dims = dims32;
+ out_dims = in_dims + 1;
+ uint32_t outdims32 = (uint32_t)out_dims;
+
+ out_writer.write((char *)&npts32, sizeof(uint32_t));
+ out_writer.write((char *)&outdims32, sizeof(uint32_t));
+
+ size_t BLOCK_SIZE = 100000;
+ size_t block_size = npts <= BLOCK_SIZE ? npts : BLOCK_SIZE;
+ std::unique_ptr<T[]> in_block_data = std::make_unique<T[]>(block_size * in_dims);
+ std::unique_ptr<float[]> out_block_data = std::make_unique<float[]>(block_size * out_dims);
+
+ std::memset(out_block_data.get(), 0, sizeof(float) * block_size * out_dims);
+ uint64_t num_blocks = DIV_ROUND_UP(npts, block_size);
+
+ std::vector<float> norms(npts, 0);
+
+ for (uint64_t b = 0; b < num_blocks; b++)
+ {
+ uint64_t start_id = b * block_size;
+ uint64_t end_id = (b + 1) * block_size < npts ? (b + 1) * block_size : npts;
+ uint64_t block_pts = end_id - start_id;
+ in_reader.read((char *)in_block_data.get(), block_pts * in_dims * sizeof(T));
+ for (uint64_t p = 0; p < block_pts; p++)
+ {
+ for (uint64_t j = 0; j < in_dims; j++)
+ {
+ norms[start_id + p] += in_block_data[p * in_dims + j] * in_block_data[p * in_dims + j];
+ }
+ max_norm = max_norm > norms[start_id + p] ? max_norm : norms[start_id + p];
+ }
+ }
+
+ max_norm = std::sqrt(max_norm);
+
+ in_reader.seekg(2 * sizeof(uint32_t), std::ios::beg);
+ for (uint64_t b = 0; b < num_blocks; b++)
+ {
+ uint64_t start_id = b * block_size;
+ uint64_t end_id = (b + 1) * block_size < npts ? (b + 1) * block_size : npts;
+ uint64_t block_pts = end_id - start_id;
+ in_reader.read((char *)in_block_data.get(), block_pts * in_dims * sizeof(T));
+ for (uint64_t p = 0; p < block_pts; p++)
+ {
+ for (uint64_t j = 0; j < in_dims; j++)
+ {
+ out_block_data[p * out_dims + j] = in_block_data[p * in_dims + j] / max_norm;
+ }
+ float res = 1 - (norms[start_id + p] / (max_norm * max_norm));
+ res = res <= 0 ? 0 : std::sqrt(res);
+ out_block_data[p * out_dims + out_dims - 1] = res;
+ }
+ out_writer.write((char *)out_block_data.get(), block_pts * out_dims * sizeof(float));
+ }
+ out_writer.close();
+ return max_norm;
+}
+
+// plain saves data as npts X ndims array into filename
+template <typename T> void save_Tvecs(const char *filename, T *data, size_t npts, size_t ndims)
+{
+ std::string fname(filename);
+
+ // create cached ofstream with 64MB cache
+ cached_ofstream writer(fname, 64 * 1048576);
+
+ unsigned dims_u32 = (unsigned)ndims;
+
+ // start writing
+ for (size_t i = 0; i < npts; i++)
+ {
+ // write dims in u32
+ writer.write((char *)&dims_u32, sizeof(unsigned));
+
+ // get cur point in data
+ T *cur_pt = data + i * ndims;
+ writer.write((char *)cur_pt, ndims * sizeof(T));
+ }
+}
+template <typename T>
+inline size_t save_data_in_base_dimensions(const std::string &filename, T *data, size_t npts, size_t ndims,
+ size_t aligned_dim, size_t offset = 0)
+{
+ std::ofstream writer; //(filename, std::ios::binary | std::ios::out);
+ open_file_to_write(writer, filename);
+ int npts_i32 = (int)npts, ndims_i32 = (int)ndims;
+ size_t bytes_written = 2 * sizeof(uint32_t) + npts * ndims * sizeof(T);
+ writer.seekp(offset, writer.beg);
+ writer.write((char *)&npts_i32, sizeof(int));
+ writer.write((char *)&ndims_i32, sizeof(int));
+ for (size_t i = 0; i < npts; i++)
+ {
+ writer.write((char *)(data + i * aligned_dim), ndims * sizeof(T));
+ }
+ writer.close();
+ return bytes_written;
+}
+
+template <typename T>
+inline void copy_aligned_data_from_file(const char *bin_file, T *&data, size_t &npts, size_t &dim,
+ const size_t &rounded_dim, size_t offset = 0)
+{
+ if (data == nullptr)
+ {
+ diskann::cerr << "Memory was not allocated for " << data << " before calling the load function. Exiting..."
+ << std::endl;
+ throw diskann::ANNException("Null pointer passed to copy_aligned_data_from_file function", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+ std::ifstream reader;
+ reader.exceptions(std::ios::badbit | std::ios::failbit);
+ reader.open(bin_file, std::ios::binary);
+ reader.seekg(offset, reader.beg);
+
+ int npts_i32, dim_i32;
+ reader.read((char *)&npts_i32, sizeof(int));
+ reader.read((char *)&dim_i32, sizeof(int));
+ npts = (unsigned)npts_i32;
+ dim = (unsigned)dim_i32;
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ reader.read((char *)(data + i * rounded_dim), dim * sizeof(T));
+ memset(data + i * rounded_dim + dim, 0, (rounded_dim - dim) * sizeof(T));
+ }
+}
+
+// NOTE :: good efficiency when total_vec_size is integral multiple of 64
+inline void prefetch_vector(const char *vec, size_t vecsize)
+{
+ size_t max_prefetch_size = (vecsize / 64) * 64;
+ for (size_t d = 0; d < max_prefetch_size; d += 64)
+ _mm_prefetch((const char *)vec + d, _MM_HINT_T0);
+}
+
+// NOTE :: good efficiency when total_vec_size is integral multiple of 64
+inline void prefetch_vector_l2(const char *vec, size_t vecsize)
+{
+ size_t max_prefetch_size = (vecsize / 64) * 64;
+ for (size_t d = 0; d < max_prefetch_size; d += 64)
+ _mm_prefetch((const char *)vec + d, _MM_HINT_T1);
+}
+
+// NOTE: Implementation in utils.cpp.
+void block_convert(std::ofstream &writr, std::ifstream &readr, float *read_buf, uint64_t npts, uint64_t ndims);
+
+DISKANN_DLLEXPORT void normalize_data_file(const std::string &inFileName, const std::string &outFileName);
+
+inline std::string get_tag_string(std::uint64_t tag)
+{
+ return std::to_string(tag);
+}
+
+inline std::string get_tag_string(const tag_uint128 &tag)
+{
+ std::string str = std::to_string(tag._data2) + "_" + std::to_string(tag._data1);
+ return str;
+}
+
+}; // namespace diskann
+
+struct PivotContainer
+{
+ PivotContainer() = default;
+
+ PivotContainer(size_t pivo_id, float pivo_dist) : piv_id{pivo_id}, piv_dist{pivo_dist}
+ {
+ }
+
+ bool operator<(const PivotContainer &p) const
+ {
+ return p.piv_dist < piv_dist;
+ }
+
+ bool operator>(const PivotContainer &p) const
+ {
+ return p.piv_dist > piv_dist;
+ }
+
+ size_t piv_id;
+ float piv_dist;
+};
+
+inline bool validate_index_file_size(std::ifstream &in)
+{
+ if (!in.is_open())
+ throw diskann::ANNException("Index file size check called on unopened file stream", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ in.seekg(0, in.end);
+ size_t actual_file_size = in.tellg();
+ in.seekg(0, in.beg);
+ size_t expected_file_size;
+ in.read((char *)&expected_file_size, sizeof(uint64_t));
+ in.seekg(0, in.beg);
+ if (actual_file_size != expected_file_size)
+ {
+ diskann::cerr << "Index file size error. Expected size (metadata): " << expected_file_size
+ << ", actual file size : " << actual_file_size << "." << std::endl;
+ return false;
+ }
+ return true;
+}
+
+template <typename T> inline float get_norm(T *arr, const size_t dim)
+{
+ float sum = 0.0f;
+ for (uint32_t i = 0; i < dim; i++)
+ {
+ sum += arr[i] * arr[i];
+ }
+ return sqrt(sum);
+}
+
+// This function is valid only for float data type.
+template <typename T = float> inline void normalize(T *arr, const size_t dim)
+{
+ float norm = get_norm(arr, dim);
+ for (uint32_t i = 0; i < dim; i++)
+ {
+ arr[i] = (T)(arr[i] / norm);
+ }
+}
+
+inline std::vector<std::string> read_file_to_vector_of_strings(const std::string &filename, bool unique = false)
+{
+ std::vector<std::string> result;
+ std::set<std::string> elementSet;
+ if (filename != "")
+ {
+ std::ifstream file(filename);
+ if (file.fail())
+ {
+ throw diskann::ANNException(std::string("Failed to open file ") + filename, -1);
+ }
+ std::string line;
+ while (std::getline(file, line))
+ {
+ if (line.empty())
+ {
+ break;
+ }
+ if (line.find(',') != std::string::npos)
+ {
+ std::cerr << "Every query must have exactly one filter" << std::endl;
+ exit(-1);
+ }
+ if (!line.empty() && (line.back() == '\r' || line.back() == '\n'))
+ {
+ line.erase(line.size() - 1);
+ }
+ if (!elementSet.count(line))
+ {
+ result.push_back(line);
+ }
+ if (unique)
+ {
+ elementSet.insert(line);
+ }
+ }
+ file.close();
+ }
+ else
+ {
+ throw diskann::ANNException(std::string("Failed to open file. filename can not be blank"), -1);
+ }
+ return result;
+}
+
+inline void clean_up_artifacts(tsl::robin_set<std::string> paths_to_clean, tsl::robin_set<std::string> path_suffixes)
+{
+ try
+ {
+ for (const auto &path : paths_to_clean)
+ {
+ for (const auto &suffix : path_suffixes)
+ {
+ std::string curr_path_to_clean(path + "_" + suffix);
+ if (std::remove(curr_path_to_clean.c_str()) != 0)
+ diskann::cout << "Warning: Unable to remove file :" << curr_path_to_clean << std::endl;
+ }
+ }
+ diskann::cout << "Cleaned all artifacts" << std::endl;
+ }
+ catch (const std::exception &e)
+ {
+ diskann::cout << "Warning: Unable to clean all artifacts " << e.what() << std::endl;
+ }
+}
+
+template <typename T> inline const char *diskann_type_to_name() = delete;
+template <> inline const char *diskann_type_to_name<float>()
+{
+ return "float";
+}
+template <> inline const char *diskann_type_to_name<uint8_t>()
+{
+ return "uint8";
+}
+template <> inline const char *diskann_type_to_name<int8_t>()
+{
+ return "int8";
+}
+template <> inline const char *diskann_type_to_name<uint16_t>()
+{
+ return "uint16";
+}
+template <> inline const char *diskann_type_to_name<int16_t>()
+{
+ return "int16";
+}
+template <> inline const char *diskann_type_to_name<uint32_t>()
+{
+ return "uint32";
+}
+template <> inline const char *diskann_type_to_name<int32_t>()
+{
+ return "int32";
+}
+template <> inline const char *diskann_type_to_name<uint64_t>()
+{
+ return "uint64";
+}
+template <> inline const char *diskann_type_to_name<int64_t>()
+{
+ return "int64";
+}
+
+#ifdef _WINDOWS
+#include <intrin.h>
+#include <Psapi.h>
+
+extern bool AvxSupportedCPU;
+extern bool Avx2SupportedCPU;
+
+inline size_t getMemoryUsage()
+{
+ PROCESS_MEMORY_COUNTERS_EX pmc;
+ GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS *)&pmc, sizeof(pmc));
+ return pmc.PrivateUsage;
+}
+
+inline std::string getWindowsErrorMessage(DWORD lastError)
+{
+ char *errorText;
+ FormatMessageA(
+ // use system message tables to retrieve error text
+ FORMAT_MESSAGE_FROM_SYSTEM
+ // allocate buffer on local heap for error text
+ | FORMAT_MESSAGE_ALLOCATE_BUFFER
+ // Important! will fail otherwise, since we're not
+ // (and CANNOT) pass insertion parameters
+ | FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM
+ lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR)&errorText, // output
+ 0, // minimum size for output buffer
+ NULL); // arguments - see note
+
+ return errorText != nullptr ? std::string(errorText) : std::string();
+}
+
+inline void printProcessMemory(const char *message)
+{
+ PROCESS_MEMORY_COUNTERS counters;
+ HANDLE h = GetCurrentProcess();
+ GetProcessMemoryInfo(h, &counters, sizeof(counters));
+ diskann::cout << message
+ << " [Peaking Working Set size: " << counters.PeakWorkingSetSize * 1.0 / (1024.0 * 1024 * 1024)
+ << "GB Working set size: " << counters.WorkingSetSize * 1.0 / (1024.0 * 1024 * 1024)
+ << "GB Private bytes " << counters.PagefileUsage * 1.0 / (1024 * 1024 * 1024) << "GB]" << std::endl;
+}
+#else
+
+// need to check and change this
+inline bool avx2Supported()
+{
+ return true;
+}
+inline void printProcessMemory(const char *)
+{
+}
+
+inline size_t getMemoryUsage()
+{ // for non-windows, we have not implemented this function
+ return 0;
+}
+
+#endif
+
+extern bool AvxSupportedCPU;
+extern bool Avx2SupportedCPU;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/windows_aligned_file_reader.h b/packages/leann-backend-diskann/third_party/DiskANN/include/windows_aligned_file_reader.h
new file mode 100644
index 0000000..0d9a317
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/windows_aligned_file_reader.h
@@ -0,0 +1,57 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+#ifdef _WINDOWS
+#ifndef USE_BING_INFRA
+#include <Windows.h>
+#include <fcntl.h>
+#include <malloc.h>
+#include <minwinbase.h>
+
+#include <cstdio>
+#include <mutex>
+#include <thread>
+#include "aligned_file_reader.h"
+#include "tsl/robin_map.h"
+#include "utils.h"
+#include "windows_customizations.h"
+
+class WindowsAlignedFileReader : public AlignedFileReader
+{
+ private:
+#ifdef UNICODE
+ std::wstring m_filename;
+#else
+ std::string m_filename;
+#endif
+
+ protected:
+ // virtual IOContext createContext();
+
+ public:
+ DISKANN_DLLEXPORT WindowsAlignedFileReader(){};
+ DISKANN_DLLEXPORT virtual ~WindowsAlignedFileReader(){};
+
+ // Open & close ops
+ // Blocking calls
+ DISKANN_DLLEXPORT virtual void open(const std::string &fname) override;
+ DISKANN_DLLEXPORT virtual void close() override;
+
+ DISKANN_DLLEXPORT virtual void register_thread() override;
+ DISKANN_DLLEXPORT virtual void deregister_thread() override
+ {
+ // TODO: Needs implementation.
+ }
+ DISKANN_DLLEXPORT virtual void deregister_all_threads() override
+ {
+ // TODO: Needs implementation.
+ }
+ DISKANN_DLLEXPORT virtual IOContext &get_ctx() override;
+
+ // process batch of aligned requests in parallel
+ // NOTE :: blocking call for the calling thread, but can thread-safe
+ DISKANN_DLLEXPORT virtual void read(std::vector<AlignedRead> &read_reqs, IOContext &ctx, bool async) override;
+};
+#endif // USE_BING_INFRA
+#endif //_WINDOWS
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/windows_customizations.h b/packages/leann-backend-diskann/third_party/DiskANN/include/windows_customizations.h
new file mode 100644
index 0000000..e6c5846
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/windows_customizations.h
@@ -0,0 +1,16 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#ifdef _WINDOWS
+
+#ifdef _WINDLL
+#define DISKANN_DLLEXPORT __declspec(dllexport)
+#else
+#define DISKANN_DLLEXPORT __declspec(dllimport)
+#endif
+
+#else
+#define DISKANN_DLLEXPORT
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/include/windows_slim_lock.h b/packages/leann-backend-diskann/third_party/DiskANN/include/windows_slim_lock.h
new file mode 100644
index 0000000..7fc09b8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/include/windows_slim_lock.h
@@ -0,0 +1,73 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+#pragma once
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include "Windows.h"
+
+namespace diskann
+{
+// A thin C++ wrapper around Windows exclusive functionality of Windows
+// SlimReaderWriterLock.
+//
+// The SlimReaderWriterLock is simpler/more lightweight than std::mutex
+// (8 bytes vs 80 bytes), which is useful in the scenario where DiskANN has
+// one lock per vector in the index. It does not support recursive locking and
+// requires Windows Vista or later.
+//
+// Full documentation can be found at.
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa904937(v=vs.85).aspx
+class windows_exclusive_slim_lock
+{
+ public:
+ windows_exclusive_slim_lock() : _lock(SRWLOCK_INIT)
+ {
+ }
+
+ // The lock is non-copyable. This also disables move constructor/operator=.
+ windows_exclusive_slim_lock(const windows_exclusive_slim_lock &) = delete;
+ windows_exclusive_slim_lock &operator=(const windows_exclusive_slim_lock &) = delete;
+
+ void lock()
+ {
+ return AcquireSRWLockExclusive(&_lock);
+ }
+
+ bool try_lock()
+ {
+ return TryAcquireSRWLockExclusive(&_lock) != FALSE;
+ }
+
+ void unlock()
+ {
+ return ReleaseSRWLockExclusive(&_lock);
+ }
+
+ private:
+ SRWLOCK _lock;
+};
+
+// An exclusive lock over a SlimReaderWriterLock.
+class windows_exclusive_slim_lock_guard
+{
+ public:
+ windows_exclusive_slim_lock_guard(windows_exclusive_slim_lock &p_lock) : _lock(p_lock)
+ {
+ _lock.lock();
+ }
+
+ // The lock is non-copyable. This also disables move constructor/operator=.
+ windows_exclusive_slim_lock_guard(const windows_exclusive_slim_lock_guard &) = delete;
+ windows_exclusive_slim_lock_guard &operator=(const windows_exclusive_slim_lock_guard &) = delete;
+
+ ~windows_exclusive_slim_lock_guard()
+ {
+ _lock.unlock();
+ }
+
+ private:
+ windows_exclusive_slim_lock &_lock;
+};
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/pyproject.toml b/packages/leann-backend-diskann/third_party/DiskANN/pyproject.toml
new file mode 100644
index 0000000..3871c71
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/pyproject.toml
@@ -0,0 +1,58 @@
+[build-system]
+requires = [
+ "setuptools>=59.6",
+ "pybind11>=2.10.0",
+ "cmake>=3.22",
+ "numpy==1.25", # this is important to keep fixed. It also means anyone using something other than 1.25 won't be able to use this library
+ "wheel",
+ "ninja"
+]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "diskannpy"
+version = "0.7.1"
+
+description = "DiskANN Python extension module"
+readme = "python/README.md"
+requires-python = ">=3.9"
+license = {text = "MIT License"}
+dependencies = [
+ "numpy==1.25"
+]
+authors = [
+ {name = "Harsha Vardhan Simhadri", email = "[email protected]"},
+ {name = "Dax Pryce", email = "[email protected]"}
+]
+
+[project.optional-dependencies]
+dev = ["black", "isort", "mypy"]
+
+[tool.setuptools]
+package-dir = {"" = "python/src"}
+
+[tool.isort]
+profile = "black"
+multi_line_output = 3
+
+[tool.mypy]
+plugins = "numpy.typing.mypy_plugin"
+
+[tool.cibuildwheel]
+manylinux-x86_64-image = "manylinux_2_28"
+test-requires = ["scikit-learn~=1.2"]
+build-frontend = "build"
+skip = ["pp*", "*-win32", "*-manylinux_i686", "*-musllinux*"]
+test-command = "python -m unittest discover {project}/python/tests"
+
+[tool.cibuildwheel.linux]
+before-build = [
+ "rpm --import https://repo.almalinux.org/almalinux/RPM-GPG-KEY-AlmaLinux",
+ "dnf makecache --refresh",
+ "dnf upgrade -y almalinux-release",
+ "dnf install -y epel-release",
+ "dnf config-manager -y --add-repo https://yum.repos.intel.com/mkl/setup/intel-mkl.repo",
+ "rpm --import https://yum.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS.PUB",
+ "dnf makecache --refresh -y",
+ "dnf install -y wget make cmake gcc-c++ libaio-devel gperftools-libs libunwind-devel clang-tools-extra boost-devel boost-program-options intel-mkl-2020.4-912"
+]
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/python/CMakeLists.txt
new file mode 100644
index 0000000..66a5ba3
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/CMakeLists.txt
@@ -0,0 +1,82 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+cmake_minimum_required(VERSION 3.18...3.22)
+
+set(CMAKE_CXX_STANDARD 17)
+
+if (PYTHON_EXECUTABLE)
+ set(Python3_EXECUTABLE ${PYTHON_EXECUTABLE})
+endif()
+
+find_package(Python3 COMPONENTS Interpreter Development.Module NumPy REQUIRED)
+
+execute_process(COMMAND ${Python3_EXECUTABLE} -c "import pybind11; print(pybind11.get_cmake_dir())"
+ OUTPUT_VARIABLE _tmp_dir
+ OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ECHO STDOUT)
+list(APPEND CMAKE_PREFIX_PATH "${_tmp_dir}")
+
+# Now we can find pybind11
+find_package(pybind11 CONFIG REQUIRED)
+
+execute_process(COMMAND ${Python3_EXECUTABLE} -c "import numpy; print(numpy.get_include())"
+ OUTPUT_VARIABLE _numpy_include
+ OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ECHO STDOUT)
+
+# pybind11_add_module(diskannpy MODULE src/diskann_bindings.cpp)
+# the following is fairly synonymous with pybind11_add_module, but we need more target_link_libraries
+# see https://pybind11.readthedocs.io/en/latest/compiling.html#advanced-interface-library-targets for more details
+add_library(_diskannpy MODULE
+ src/module.cpp
+ src/builder.cpp
+ src/dynamic_memory_index.cpp
+ src/static_memory_index.cpp
+ src/static_disk_index.cpp
+)
+
+target_include_directories(_diskannpy AFTER PRIVATE include)
+
+if (MSVC)
+ target_compile_options(_diskannpy PRIVATE /U_WINDLL)
+endif()
+
+target_link_libraries(
+ _diskannpy
+ PRIVATE
+ pybind11::module
+ pybind11::lto
+ pybind11::windows_extras
+ ${PROJECT_NAME}
+ ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS}
+ ${DISKANN_ASYNC_LIB}
+)
+
+pybind11_extension(_diskannpy)
+if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo)
+ # Strip unnecessary sections of the binary on Linux/macOS
+ pybind11_strip(_diskannpy)
+endif()
+
+set_target_properties(_diskannpy PROPERTIES CXX_VISIBILITY_PRESET "hidden"
+ CUDA_VISIBILITY_PRESET "hidden")
+
+# generally, the VERSION_INFO flag is set by pyproject.toml, by way of setup.py.
+# attempts to locate the version within CMake fail because the version has to be available
+# to pyproject.toml for the sdist to work after we build it.
+
+if(NOT VERSION_INFO)
+ set(VERSION_INFO "0.0.0dev")
+endif()
+target_compile_definitions(_diskannpy PRIVATE VERSION_INFO="${VERSION_INFO}")
+
+# Add a post-build command to automatically copy the compiled Python module
+if(UPDATE_EDITABLE_INSTALL)
+add_custom_command(
+TARGET _diskannpy
+POST_BUILD
+COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_BINARY_DIR}/_diskannpy.cpython-*.so
+ ${CMAKE_SOURCE_DIR}/python/src/
+COMMENT "Copying Python module to python/src directory"
+)
+endif()
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/README.md b/packages/leann-backend-diskann/third_party/DiskANN/python/README.md
new file mode 100644
index 0000000..a0c9475
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/README.md
@@ -0,0 +1,55 @@
+# diskannpy
+
+[![DiskANN Paper](https://img.shields.io/badge/Paper-NeurIPS%3A_DiskANN-blue)](https://papers.nips.cc/paper/9527-rand-nsg-fast-accurate-billion-point-nearest-neighbor-search-on-a-single-node.pdf)
+[![DiskANN Paper](https://img.shields.io/badge/Paper-Arxiv%3A_Fresh--DiskANN-blue)](https://arxiv.org/abs/2105.09613)
+[![DiskANN Paper](https://img.shields.io/badge/Paper-Filtered--DiskANN-blue)](https://harsha-simhadri.org/pubs/Filtered-DiskANN23.pdf)
+[![DiskANN Main](https://github.com/microsoft/DiskANN/actions/workflows/push-test.yml/badge.svg?branch=main)](https://github.com/microsoft/DiskANN/actions/workflows/push-test.yml)
+[![PyPI version](https://img.shields.io/pypi/v/diskannpy.svg)](https://pypi.org/project/diskannpy/)
+[![Downloads shield](https://pepy.tech/badge/diskannpy)](https://pepy.tech/project/diskannpy)
+[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
+
+## Installation
+Packages published to PyPI will always be built using the latest numpy major.minor release (at this time, 1.25).
+
+Conda distributions for versions 1.19-1.25 will be completed as a future effort. In the meantime, feel free to
+clone this repository and build it yourself.
+
+## Local Build Instructions
+Please see the [Project README](https://github.com/microsoft/DiskANN/blob/main/README.md) for system dependencies and requirements.
+
+After ensuring you've followed the directions to build the project library and executables, you will be ready to also
+build `diskannpy` with these additional instructions.
+
+### Changing Numpy Version
+In the root folder of DiskANN, there is a file `pyproject.toml`. You will need to edit the version of numpy in both the
+`[build-system.requires]` section, as well as the `[project.dependencies]` section. The version numbers must match.
+
+#### Linux
+```bash
+python3.11 -m venv venv # versions from python3.9 and up should work
+source venv/bin/activate
+pip install build
+python -m build
+```
+
+#### Windows
+```powershell
+py -3.11 -m venv venv # versions from python3.9 and up should work
+venv\Scripts\Activate.ps1
+pip install build
+python -m build
+```
+
+The built wheel will be placed in the `dist` directory in your DiskANN root. Install it using `pip install dist/<wheel name>.whl`
+
+## Citations
+Please cite this software in your work as:
+```
+@misc{diskann-github,
+ author = {Simhadri, Harsha Vardhan and Krishnaswamy, Ravishankar and Srinivasa, Gopal and Subramanya, Suhas Jayaram and Antonijevic, Andrija and Pryce, Dax and Kaczynski, David and Williams, Shane and Gollapudi, Siddarth and Sivashankar, Varun and Karia, Neel and Singh, Aditi and Jaiswal, Shikhar and Mahapatro, Neelam and Adams, Philip and Tower, Bryan and Patel, Yash}},
+ title = {{DiskANN: Graph-structured Indices for Scalable, Fast, Fresh and Filtered Approximate Nearest Neighbor Search}},
+ url = {https://github.com/Microsoft/DiskANN},
+ version = {0.6.1},
+ year = {2023}
+}
+```
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/apps/cli/__main__.py b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/cli/__main__.py
new file mode 100644
index 0000000..d2c9990
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/cli/__main__.py
@@ -0,0 +1,152 @@
+import diskannpy as dap
+import numpy as np
+import numpy.typing as npt
+
+import fire
+
+from contextlib import contextmanager
+from time import perf_counter
+
+from typing import Tuple
+
+
+def _basic_setup(
+ dtype: str,
+ query_vectors_file: str
+) -> Tuple[dap.VectorDType, npt.NDArray[dap.VectorDType]]:
+ _dtype = dap.valid_dtype(dtype)
+ vectors_to_query = dap.vectors_from_binary(query_vectors_file, dtype=_dtype)
+ return _dtype, vectors_to_query
+
+
+def dynamic(
+ dtype: str,
+ index_vectors_file: str,
+ query_vectors_file: str,
+ build_complexity: int,
+ graph_degree: int,
+ K: int,
+ search_complexity: int,
+ num_insert_threads: int,
+ num_search_threads: int,
+ gt_file: str = "",
+):
+ _dtype, vectors_to_query = _basic_setup(dtype, query_vectors_file)
+ vectors_to_index = dap.vectors_from_binary(index_vectors_file, dtype=_dtype)
+
+ npts, ndims = vectors_to_index.shape
+ index = dap.DynamicMemoryIndex(
+ "l2", _dtype, ndims, npts, build_complexity, graph_degree
+ )
+
+ tags = np.arange(1, npts+1, dtype=np.uintc)
+ timer = Timer()
+
+ with timer.time("batch insert"):
+ index.batch_insert(vectors_to_index, tags, num_insert_threads)
+
+ delete_tags = np.random.choice(
+ np.array(range(1, npts + 1, 1), dtype=np.uintc),
+ size=int(0.5 * npts),
+ replace=False
+ )
+ with timer.time("mark deletion"):
+ for tag in delete_tags:
+ index.mark_deleted(tag)
+
+ with timer.time("consolidation"):
+ index.consolidate_delete()
+
+ deleted_data = vectors_to_index[delete_tags - 1, :]
+
+ with timer.time("re-insertion"):
+ index.batch_insert(deleted_data, delete_tags, num_insert_threads)
+
+ with timer.time("batch searched"):
+ tags, dists = index.batch_search(vectors_to_query, K, search_complexity, num_search_threads)
+
+ # res_ids = tags - 1
+ # if gt_file != "":
+ # recall = utils.calculate_recall_from_gt_file(K, res_ids, gt_file)
+ # print(f"recall@{K} is {recall}")
+
+def static(
+ dtype: str,
+ index_directory: str,
+ index_vectors_file: str,
+ query_vectors_file: str,
+ build_complexity: int,
+ graph_degree: int,
+ K: int,
+ search_complexity: int,
+ num_threads: int,
+ gt_file: str = "",
+ index_prefix: str = "ann"
+):
+ _dtype, vectors_to_query = _basic_setup(dtype, query_vectors_file)
+ timer = Timer()
+ with timer.time("build static index"):
+ # build index
+ dap.build_memory_index(
+ data=index_vectors_file,
+ metric="l2",
+ vector_dtype=_dtype,
+ index_directory=index_directory,
+ complexity=build_complexity,
+ graph_degree=graph_degree,
+ num_threads=num_threads,
+ index_prefix=index_prefix,
+ alpha=1.2,
+ use_pq_build=False,
+ num_pq_bytes=8,
+ use_opq=False,
+ )
+
+ with timer.time("load static index"):
+ # ready search object
+ index = dap.StaticMemoryIndex(
+ metric="l2",
+ vector_dtype=_dtype,
+ data_path=index_vectors_file,
+ index_directory=index_directory,
+ num_threads=num_threads, # this can be different at search time if you would like
+ initial_search_complexity=search_complexity,
+ index_prefix=index_prefix
+ )
+
+ ids, dists = index.batch_search(vectors_to_query, K, search_complexity, num_threads)
+
+ # if gt_file != "":
+ # recall = utils.calculate_recall_from_gt_file(K, ids, gt_file)
+ # print(f"recall@{K} is {recall}")
+
+def dynamic_clustered():
+ pass
+
+def generate_clusters():
+ pass
+
+
+class Timer:
+ def __init__(self):
+ self._start = -1
+
+ @contextmanager
+ def time(self, message: str):
+ start = perf_counter()
+ if self._start == -1:
+ self._start = start
+ yield
+ now = perf_counter()
+ print(f"Operation {message} completed in {(now - start):.3f}s, total: {(now - self._start):.3f}s")
+
+
+
+
+if __name__ == "__main__":
+ fire.Fire({
+ "in-mem-dynamic": dynamic,
+ "in-mem-static": static,
+ "in-mem-dynamic-clustered": dynamic_clustered,
+ "generate-clusters": generate_clusters
+ }, name="cli")
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/apps/cluster.py b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/cluster.py
new file mode 100644
index 0000000..27a34bb
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/cluster.py
@@ -0,0 +1,28 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import argparse
+import utils
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(
+ prog="cluster", description="kmeans cluster points in a file"
+ )
+
+ parser.add_argument("-d", "--data_type", required=True)
+ parser.add_argument("-i", "--indexdata_file", required=True)
+ parser.add_argument("-k", "--num_clusters", type=int, required=True)
+ args = parser.parse_args()
+
+ npts, ndims = get_bin_metadata(indexdata_file)
+
+ data = utils.bin_to_numpy(args.data_type, args.indexdata_file)
+
+ offsets, permutation = utils.cluster_and_permute(
+ args.data_type, npts, ndims, data, args.num_clusters
+ )
+
+ permuted_data = data[permutation]
+
+ utils.numpy_to_bin(permuted_data, args.indexdata_file + ".cluster")
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/apps/in-mem-dynamic.py b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/in-mem-dynamic.py
new file mode 100644
index 0000000..f97e131
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/in-mem-dynamic.py
@@ -0,0 +1,161 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import argparse
+
+import diskannpy
+import numpy as np
+import utils
+
+def insert_and_search(
+ dtype_str,
+ indexdata_file,
+ querydata_file,
+ Lb,
+ graph_degree,
+ K,
+ Ls,
+ num_insert_threads,
+ num_search_threads,
+ gt_file,
+) -> dict[str, float]:
+ """
+
+ :param dtype_str:
+ :param indexdata_file:
+ :param querydata_file:
+ :param Lb:
+ :param graph_degree:
+ :param K:
+ :param Ls:
+ :param num_insert_threads:
+ :param num_search_threads:
+ :param gt_file:
+ :return: Dictionary of timings. Key is the event and value is the number of seconds the event took
+ """
+ timer_results: dict[str, float] = {}
+
+ method_timer: utils.Timer = utils.Timer()
+
+ npts, ndims = utils.get_bin_metadata(indexdata_file)
+
+ if dtype_str == "float":
+ dtype = np.float32
+ elif dtype_str == "int8":
+ dtype = np.int8
+ elif dtype_str == "uint8":
+ dtype = np.uint8
+ else:
+ raise ValueError("data_type must be float, int8 or uint8")
+
+ index = diskannpy.DynamicMemoryIndex(
+ distance_metric="l2",
+ vector_dtype=dtype,
+ dimensions=ndims,
+ max_vectors=npts,
+ complexity=Lb,
+ graph_degree=graph_degree
+ )
+ queries = diskannpy.vectors_from_file(querydata_file, dtype)
+ data = diskannpy.vectors_from_file(indexdata_file, dtype)
+
+ tags = np.zeros(npts, dtype=np.uintc)
+ timer = utils.Timer()
+ for i in range(npts):
+ tags[i] = i + 1
+ index.batch_insert(data, tags, num_insert_threads)
+ compute_seconds = timer.elapsed()
+ print('batch_insert complete in', compute_seconds, 's')
+ timer_results["batch_insert_seconds"] = compute_seconds
+
+ delete_tags = np.random.choice(
+ np.array(range(1, npts + 1, 1), dtype=np.uintc),
+ size=int(0.5 * npts),
+ replace=False
+ )
+
+ timer.reset()
+ for tag in delete_tags:
+ index.mark_deleted(tag)
+ compute_seconds = timer.elapsed()
+ timer_results['mark_deletion_seconds'] = compute_seconds
+ print('mark deletion completed in', compute_seconds, 's')
+
+ timer.reset()
+ index.consolidate_delete()
+ compute_seconds = timer.elapsed()
+ print('consolidation completed in', compute_seconds, 's')
+ timer_results['consolidation_completed_seconds'] = compute_seconds
+
+ deleted_data = data[delete_tags - 1, :]
+
+ timer.reset()
+ index.batch_insert(deleted_data, delete_tags, num_insert_threads)
+ compute_seconds = timer.elapsed()
+ print('re-insertion completed in', compute_seconds, 's')
+ timer_results['re-insertion_seconds'] = compute_seconds
+
+ timer.reset()
+ tags, dists = index.batch_search(queries, K, Ls, num_search_threads)
+ compute_seconds = timer.elapsed()
+ print('Batch searched', queries.shape[0], ' queries in ', compute_seconds, 's')
+ timer_results['batch_searched_seconds'] = compute_seconds
+
+ res_ids = tags - 1
+ if gt_file != "":
+ timer.reset()
+ recall = utils.calculate_recall_from_gt_file(K, res_ids, gt_file)
+ print(f"recall@{K} is {recall}")
+ timer_results['recall_computed_seconds'] = timer.elapsed()
+
+ timer_results['total_time_seconds'] = method_timer.elapsed()
+
+ return timer_results
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(
+ prog="in-mem-dynamic",
+ description="Inserts points dynamically in a clustered order and search from vectors in a file.",
+ )
+
+ parser.add_argument("-d", "--data_type", required=True)
+ parser.add_argument("-i", "--indexdata_file", required=True)
+ parser.add_argument("-q", "--querydata_file", required=True)
+ parser.add_argument("-Lb", "--Lbuild", default=50, type=int)
+ parser.add_argument("-Ls", "--Lsearch", default=50, type=int)
+ parser.add_argument("-R", "--graph_degree", default=32, type=int)
+ parser.add_argument("-TI", "--num_insert_threads", default=8, type=int)
+ parser.add_argument("-TS", "--num_search_threads", default=8, type=int)
+ parser.add_argument("-K", default=10, type=int)
+ parser.add_argument("--gt_file", default="")
+ parser.add_argument("--json_timings_output", required=False, default=None, help="File to write out timings to as JSON. If not specified, timings will not be written out.")
+ args = parser.parse_args()
+
+ timings = insert_and_search(
+ args.data_type,
+ args.indexdata_file,
+ args.querydata_file,
+ args.Lbuild,
+ args.graph_degree, # Build args
+ args.K,
+ args.Lsearch,
+ args.num_insert_threads,
+ args.num_search_threads, # search args
+ args.gt_file,
+ )
+
+ if args.json_timings_output is not None:
+ import json
+ timings['log_file'] = args.json_timings_output
+ with open(args.json_timings_output, "w") as f:
+ json.dump(timings, f)
+
+"""
+An ingest optimized example with SIFT1M
+source venv/bin/activate
+python python/apps/in-mem-dynamic.py -d float \
+-i "$HOME/data/sift/sift_base.fbin" -q "$HOME/data/sift/sift_query.fbin" --gt_file "$HOME/data/sift/gt100_base" \
+-Lb 10 -R 30 -Ls 200
+"""
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/apps/in-mem-static.py b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/in-mem-static.py
new file mode 100644
index 0000000..9fb9a2c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/in-mem-static.py
@@ -0,0 +1,149 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import argparse
+from xml.dom.pulldom import default_bufsize
+
+import diskannpy
+import numpy as np
+import utils
+
+def build_and_search(
+ metric,
+ dtype_str,
+ index_directory,
+ indexdata_file,
+ querydata_file,
+ Lb,
+ graph_degree,
+ K,
+ Ls,
+ num_threads,
+ gt_file,
+ index_prefix,
+ search_only
+) -> dict[str, float]:
+ """
+
+ :param metric:
+ :param dtype_str:
+ :param index_directory:
+ :param indexdata_file:
+ :param querydata_file:
+ :param Lb:
+ :param graph_degree:
+ :param K:
+ :param Ls:
+ :param num_threads:
+ :param gt_file:
+ :param index_prefix:
+ :param search_only:
+ :return: Dictionary of timings. Key is the event and value is the number of seconds the event took
+ in wall-clock-time.
+ """
+ timer_results: dict[str, float] = {}
+
+ method_timer: utils.Timer = utils.Timer()
+
+ if dtype_str == "float":
+ dtype = np.single
+ elif dtype_str == "int8":
+ dtype = np.byte
+ elif dtype_str == "uint8":
+ dtype = np.ubyte
+ else:
+ raise ValueError("data_type must be float, int8 or uint8")
+
+ # build index
+ if not search_only:
+ build_index_timer = utils.Timer()
+ diskannpy.build_memory_index(
+ data=indexdata_file,
+ distance_metric=metric,
+ vector_dtype=dtype,
+ index_directory=index_directory,
+ complexity=Lb,
+ graph_degree=graph_degree,
+ num_threads=num_threads,
+ index_prefix=index_prefix,
+ alpha=1.2,
+ use_pq_build=False,
+ num_pq_bytes=8,
+ use_opq=False,
+ )
+ timer_results["build_index_seconds"] = build_index_timer.elapsed()
+
+ # ready search object
+ load_index_timer = utils.Timer()
+ index = diskannpy.StaticMemoryIndex(
+ distance_metric=metric,
+ vector_dtype=dtype,
+ index_directory=index_directory,
+ num_threads=num_threads, # this can be different at search time if you would like
+ initial_search_complexity=Ls,
+ index_prefix=index_prefix
+ )
+ timer_results["load_index_seconds"] = load_index_timer.elapsed()
+
+ queries = utils.bin_to_numpy(dtype, querydata_file)
+
+ query_timer = utils.Timer()
+ ids, dists = index.batch_search(queries, 10, Ls, num_threads)
+ query_time = query_timer.elapsed()
+ qps = round(queries.shape[0]/query_time, 1)
+ print('Batch searched', queries.shape[0], 'in', query_time, 's @', qps, 'QPS')
+ timer_results["query_seconds"] = query_time
+
+ if gt_file != "":
+ recall_timer = utils.Timer()
+ recall = utils.calculate_recall_from_gt_file(K, ids, gt_file)
+ print(f"recall@{K} is {recall}")
+ timer_results["recall_seconds"] = recall_timer.elapsed()
+
+ timer_results['total_time_seconds'] = method_timer.elapsed()
+
+ return timer_results
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(
+ prog="in-mem-static",
+ description="Static in-memory build and search from vectors in a file",
+ )
+
+ parser.add_argument("-m", "--metric", required=False, default="l2")
+ parser.add_argument("-d", "--data_type", required=True)
+ parser.add_argument("-id", "--index_directory", required=False, default=".")
+ parser.add_argument("-i", "--indexdata_file", required=True)
+ parser.add_argument("-q", "--querydata_file", required=True)
+ parser.add_argument("-Lb", "--Lbuild", default=50, type=int)
+ parser.add_argument("-Ls", "--Lsearch", default=50, type=int)
+ parser.add_argument("-R", "--graph_degree", default=32, type=int)
+ parser.add_argument("-T", "--num_threads", default=8, type=int)
+ parser.add_argument("-K", default=10, type=int)
+ parser.add_argument("-G", "--gt_file", default="")
+ parser.add_argument("-ip", "--index_prefix", required=False, default="ann")
+ parser.add_argument("--search_only", required=False, default=False)
+ parser.add_argument("--json_timings_output", required=False, default=None, help="File to write out timings to as JSON. If not specified, timings will not be written out.")
+ args = parser.parse_args()
+
+ timings: dict[str, float] = build_and_search(
+ args.metric,
+ args.data_type,
+ args.index_directory.strip(),
+ args.indexdata_file.strip(),
+ args.querydata_file.strip(),
+ args.Lbuild,
+ args.graph_degree, # Build args
+ args.K,
+ args.Lsearch,
+ args.num_threads, # search args
+ args.gt_file,
+ args.index_prefix,
+ args.search_only
+ )
+
+ if args.json_timings_output is not None:
+ import json
+ timings['log_file'] = args.json_timings_output
+ with open(args.json_timings_output, "w") as f:
+ json.dump(timings, f)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/apps/insert-in-clustered-order.py b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/insert-in-clustered-order.py
new file mode 100644
index 0000000..25cb9d5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/insert-in-clustered-order.py
@@ -0,0 +1,103 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import argparse
+
+import diskannpy
+import numpy as np
+import utils
+
+
+def insert_and_search(
+ dtype_str,
+ indexdata_file,
+ querydata_file,
+ Lb,
+ graph_degree,
+ num_clusters,
+ num_insert_threads,
+ K,
+ Ls,
+ num_search_threads,
+ gt_file,
+):
+ npts, ndims = utils.get_bin_metadata(indexdata_file)
+
+ if dtype_str == "float":
+ dtype = np.float32
+ elif dtype_str == "int8":
+ dtype = np.int8
+ elif dtype_str == "uint8":
+ dtype = np.uint8
+ else:
+ raise ValueError("data_type must be float, int8 or uint8")
+
+ index = diskannpy.DynamicMemoryIndex(
+ distance_metric="l2",
+ vector_dtype=dtype,
+ dimensions=ndims,
+ max_vectors=npts,
+ complexity=Lb,
+ graph_degree=graph_degree
+ )
+ queries = diskannpy.vectors_from_file(querydata_file, dtype)
+ data = diskannpy.vectors_from_file(indexdata_file, dtype)
+
+ offsets, permutation = utils.cluster_and_permute(
+ dtype_str, npts, ndims, data, num_clusters
+ )
+
+ i = 0
+ timer = utils.Timer()
+ for c in range(num_clusters):
+ cluster_index_range = range(offsets[c], offsets[c + 1])
+ cluster_indices = np.array(permutation[cluster_index_range], dtype=np.uint32)
+ cluster_data = data[cluster_indices, :]
+ index.batch_insert(cluster_data, cluster_indices + 1, num_insert_threads)
+ print('Inserted cluster', c, 'in', timer.elapsed(), 's')
+ tags, dists = index.batch_search(queries, K, Ls, num_search_threads)
+ print('Batch searched', queries.shape[0], 'queries in', timer.elapsed(), 's')
+ res_ids = tags - 1
+
+ if gt_file != "":
+ recall = utils.calculate_recall_from_gt_file(K, res_ids, gt_file)
+ print(f"recall@{K} is {recall}")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(
+ prog="in-mem-dynamic",
+ description="Inserts points dynamically in a clustered order and search from vectors in a file.",
+ )
+
+ parser.add_argument("-d", "--data_type", required=True)
+ parser.add_argument("-i", "--indexdata_file", required=True)
+ parser.add_argument("-q", "--querydata_file", required=True)
+ parser.add_argument("-Lb", "--Lbuild", default=50, type=int)
+ parser.add_argument("-Ls", "--Lsearch", default=50, type=int)
+ parser.add_argument("-R", "--graph_degree", default=32, type=int)
+ parser.add_argument("-TI", "--num_insert_threads", default=8, type=int)
+ parser.add_argument("-TS", "--num_search_threads", default=8, type=int)
+ parser.add_argument("-C", "--num_clusters", default=32, type=int)
+ parser.add_argument("-K", default=10, type=int)
+ parser.add_argument("--gt_file", default="")
+ args = parser.parse_args()
+
+ insert_and_search(
+ args.data_type,
+ args.indexdata_file,
+ args.querydata_file,
+ args.Lbuild,
+ args.graph_degree, # Build args
+ args.num_clusters,
+ args.num_insert_threads,
+ args.K,
+ args.Lsearch,
+ args.num_search_threads, # search args
+ args.gt_file,
+ )
+
+# An ingest optimized example with SIFT1M
+# python3 ~/DiskANN/python/apps/insert-in-clustered-order.py -d float \
+# -i sift_base.fbin -q sift_query.fbin --gt_file gt100_base \
+# -Lb 10 -R 30 -Ls 200 -C 32
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/apps/utils.py b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/utils.py
new file mode 100644
index 0000000..a526984
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/apps/utils.py
@@ -0,0 +1,120 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import numpy as np
+from scipy.cluster.vq import vq, kmeans2
+from typing import Tuple
+from time import perf_counter
+
+
+def get_bin_metadata(bin_file) -> Tuple[int, int]:
+ array = np.fromfile(file=bin_file, dtype=np.uint32, count=2)
+ return array[0], array[1]
+
+
+def bin_to_numpy(dtype, bin_file) -> np.ndarray:
+ npts, ndims = get_bin_metadata(bin_file)
+ return np.fromfile(file=bin_file, dtype=dtype, offset=8).reshape(npts, ndims)
+
+
+class Timer:
+ last = perf_counter()
+
+ def reset(self):
+ new = perf_counter()
+ self.last = new
+
+ def elapsed(self, round_digit:int = 3):
+ new = perf_counter()
+ elapsed_time = new - self.last
+ self.last = new
+ return round(elapsed_time, round_digit)
+
+
+def numpy_to_bin(array, out_file):
+ shape = np.shape(array)
+ npts = shape[0].astype(np.uint32)
+ ndims = shape[1].astype(np.uint32)
+ f = open(out_file, "wb")
+ f.write(npts.tobytes())
+ f.write(ndims.tobytes())
+ f.write(array.tobytes())
+ f.close()
+
+
+def read_gt_file(gt_file) -> Tuple[np.ndarray[int], np.ndarray[float]]:
+ """
+ Return ids and distances to queries
+ """
+ nq, K = get_bin_metadata(gt_file)
+ ids = np.fromfile(file=gt_file, dtype=np.uint32, offset=8, count=nq * K).reshape(
+ nq, K
+ )
+ dists = np.fromfile(
+ file=gt_file, dtype=np.float32, offset=8 + nq * K * 4, count=nq * K
+ ).reshape(nq, K)
+ return ids, dists
+
+
+def calculate_recall(
+ result_set_indices: np.ndarray[int],
+ truth_set_indices: np.ndarray[int],
+ recall_at: int = 5,
+) -> float:
+ """
+ result_set_indices and truth_set_indices correspond by row index. the columns in each row contain the indices of
+ the nearest neighbors, with result_set_indices being the approximate nearest neighbor results and truth_set_indices
+ being the brute force nearest neighbor calculation via sklearn's NearestNeighbor class.
+ :param result_set_indices:
+ :param truth_set_indices:
+ :param recall_at:
+ :return:
+ """
+ found = 0
+ for i in range(0, result_set_indices.shape[0]):
+ result_set_set = set(result_set_indices[i][0:recall_at])
+ truth_set_set = set(truth_set_indices[i][0:recall_at])
+ found += len(result_set_set.intersection(truth_set_set))
+ return found / (result_set_indices.shape[0] * recall_at)
+
+
+def calculate_recall_from_gt_file(K: int, ids: np.ndarray[int], gt_file: str) -> float:
+ """
+ Calculate recall from ids returned from search and those read from file
+ """
+ gt_ids, gt_dists = read_gt_file(gt_file)
+ return calculate_recall(ids, gt_ids, K)
+
+
+def cluster_and_permute(
+ dtype_str, npts, ndims, data, num_clusters
+) -> Tuple[np.ndarray[int], np.ndarray[int]]:
+ """
+ Cluster the data and return permutation of row indices
+ that would group indices of the same cluster together
+ """
+ sample_size = min(100000, npts)
+ sample_indices = np.random.choice(range(npts), size=sample_size, replace=False)
+ sampled_data = data[sample_indices, :]
+ centroids, sample_labels = kmeans2(sampled_data, num_clusters, minit="++", iter=10)
+ labels, dist = vq(data, centroids)
+
+ count = np.zeros(num_clusters)
+ for i in range(npts):
+ count[labels[i]] += 1
+ print("Cluster counts")
+ print(count)
+
+ offsets = np.zeros(num_clusters + 1, dtype=int)
+ for i in range(0, num_clusters, 1):
+ offsets[i + 1] = offsets[i] + count[i]
+
+ permutation = np.zeros(npts, dtype=int)
+ counters = np.zeros(num_clusters, dtype=int)
+ for i in range(npts):
+ label = labels[i]
+ row = offsets[label] + counters[label]
+ counters[label] += 1
+ permutation[row] = i
+
+ return offsets, permutation
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/include/builder.h b/packages/leann-backend-diskann/third_party/DiskANN/python/include/builder.h
new file mode 100644
index 0000000..56677ac
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/include/builder.h
@@ -0,0 +1,27 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+#include "common.h"
+#include "distance.h"
+
+namespace diskannpy
+{
+template <typename DT>
+void build_disk_index(diskann::Metric metric, const std::string &data_file_path, const std::string &index_prefix_path,
+ uint32_t complexity, uint32_t graph_degree, double final_index_ram_limit,
+ double indexing_ram_budget, uint32_t num_threads, uint32_t pq_disk_bytes,
+ const std::string &codebook_prefix);
+
+template <typename DT, typename TagT = DynamicIdType, typename LabelT = filterT>
+void build_memory_index(diskann::Metric metric, const std::string &vector_bin_path,
+ const std::string &index_output_path, uint32_t graph_degree, uint32_t complexity, float alpha,
+ uint32_t num_threads, bool use_pq_build, size_t num_pq_bytes, bool use_opq,
+ bool use_tags = false, const std::string &filter_labels_file = "",
+ const std::string &universal_label = "", uint32_t filter_complexity = 0);
+
+} // namespace diskannpy
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/include/common.h b/packages/leann-backend-diskann/third_party/DiskANN/python/include/common.h
new file mode 100644
index 0000000..7c63534
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/include/common.h
@@ -0,0 +1,24 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <stdint.h>
+#include <utility>
+
+#include <pybind11/pybind11.h>
+#include <pybind11/numpy.h>
+
+namespace py = pybind11;
+
+namespace diskannpy
+{
+
+typedef uint32_t filterT;
+
+typedef uint32_t StaticIdType;
+typedef uint32_t DynamicIdType;
+
+template <class IdType> using NeighborsAndDistances = std::pair<py::array_t<IdType>, py::array_t<float>>;
+
+}; // namespace diskannpy
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/include/dynamic_memory_index.h b/packages/leann-backend-diskann/third_party/DiskANN/python/include/dynamic_memory_index.h
new file mode 100644
index 0000000..02d6b8c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/include/dynamic_memory_index.h
@@ -0,0 +1,53 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+#include <pybind11/pybind11.h>
+#include <pybind11/numpy.h>
+
+#include "common.h"
+#include "index.h"
+#include "parameters.h"
+
+namespace py = pybind11;
+
+namespace diskannpy
+{
+
+template <typename DT>
+class DynamicMemoryIndex
+{
+ public:
+ DynamicMemoryIndex(diskann::Metric m, size_t dimensions, size_t max_vectors, uint32_t complexity,
+ uint32_t graph_degree, bool saturate_graph, uint32_t max_occlusion_size, float alpha,
+ uint32_t num_threads, uint32_t filter_complexity, uint32_t num_frozen_points,
+ uint32_t initial_search_complexity, uint32_t initial_search_threads,
+ bool concurrent_consolidation);
+
+ void load(const std::string &index_path);
+ int insert(const py::array_t<DT, py::array::c_style | py::array::forcecast> &vector, DynamicIdType id);
+ py::array_t<int> batch_insert(py::array_t<DT, py::array::c_style | py::array::forcecast> &vectors,
+ py::array_t<DynamicIdType, py::array::c_style | py::array::forcecast> &ids, int32_t num_inserts,
+ int num_threads = 0);
+ int mark_deleted(DynamicIdType id);
+ void save(const std::string &save_path, bool compact_before_save = false);
+ NeighborsAndDistances<DynamicIdType> search(py::array_t<DT, py::array::c_style | py::array::forcecast> &query, uint64_t knn,
+ uint64_t complexity);
+ NeighborsAndDistances<DynamicIdType> batch_search(py::array_t<DT, py::array::c_style | py::array::forcecast> &queries,
+ uint64_t num_queries, uint64_t knn, uint64_t complexity,
+ uint32_t num_threads);
+ void consolidate_delete();
+ size_t num_points();
+
+
+ private:
+ const uint32_t _initial_search_complexity;
+ const diskann::IndexWriteParameters _write_parameters;
+ diskann::Index<DT, DynamicIdType, filterT> _index;
+};
+
+}; // namespace diskannpy
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/include/static_disk_index.h b/packages/leann-backend-diskann/third_party/DiskANN/python/include/static_disk_index.h
new file mode 100644
index 0000000..a3b79c4
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/include/static_disk_index.h
@@ -0,0 +1,65 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+#include <pybind11/pybind11.h>
+#include <pybind11/numpy.h>
+
+#ifdef _WINDOWS
+#include "windows_aligned_file_reader.h"
+#elif __APPLE__
+#include "apple_aligned_file_reader.h"
+#else
+#include "linux_aligned_file_reader.h"
+#endif
+
+#include "common.h"
+#include "pq_flash_index.h"
+
+namespace py = pybind11;
+
+namespace diskannpy
+{
+
+#ifdef _WINDOWS
+typedef WindowsAlignedFileReader PlatformSpecificAlignedFileReader;
+#elif __APPLE__
+typedef AppleAlignedFileReader PlatformSpecificAlignedFileReader;
+#else
+typedef LinuxAlignedFileReader PlatformSpecificAlignedFileReader;
+#endif
+
+template <typename DT> class StaticDiskIndex
+{
+ public:
+ StaticDiskIndex(diskann::Metric metric, const std::string &index_path_prefix, uint32_t num_threads,
+ size_t num_nodes_to_cache, uint32_t cache_mechanism, const std::string &pq_prefix,
+ const std::string &partition_prefix);
+
+ void cache_bfs_levels(size_t num_nodes_to_cache);
+
+ void cache_sample_paths(size_t num_nodes_to_cache, const std::string &warmup_query_file, uint32_t num_threads);
+
+ NeighborsAndDistances<StaticIdType> search(py::array_t<DT, py::array::c_style | py::array::forcecast> &query,
+ uint64_t knn, uint64_t complexity, uint64_t beam_width,
+ bool USE_DEFERRED_FETCH = false, bool skip_search_reorder = false,
+ bool recompute_beighbor_embeddings = false, bool dedup_node_dis = false,
+ float prune_ratio = 0, bool batch_recompute = false,
+ bool global_pruning = false);
+
+ NeighborsAndDistances<StaticIdType> batch_search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &queries, uint64_t num_queries, uint64_t knn,
+ uint64_t complexity, uint64_t beam_width, uint32_t num_threads, bool USE_DEFERRED_FETCH = false,
+ bool skip_search_reorder = false, bool recompute_beighbor_embeddings = false, bool dedup_node_dis = false,
+ float prune_ratio = 0, bool batch_recompute = false, bool global_pruning = false);
+
+ private:
+ std::shared_ptr<AlignedFileReader> _reader;
+ std::shared_ptr<AlignedFileReader> _graph_reader;
+ diskann::PQFlashIndex<DT> _index;
+};
+} // namespace diskannpy
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/include/static_memory_index.h b/packages/leann-backend-diskann/third_party/DiskANN/python/include/static_memory_index.h
new file mode 100644
index 0000000..6ed5a08
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/include/static_memory_index.h
@@ -0,0 +1,40 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+#include <pybind11/pybind11.h>
+#include <pybind11/numpy.h>
+
+#include "common.h"
+#include "index.h"
+
+namespace py = pybind11;
+
+namespace diskannpy
+{
+
+template <typename DT> class StaticMemoryIndex
+{
+ public:
+ StaticMemoryIndex(diskann::Metric m, const std::string &index_prefix, size_t num_points, size_t dimensions,
+ uint32_t num_threads, uint32_t initial_search_complexity);
+
+ NeighborsAndDistances<StaticIdType> search(py::array_t<DT, py::array::c_style | py::array::forcecast> &query,
+ uint64_t knn, uint64_t complexity);
+
+ NeighborsAndDistances<StaticIdType> search_with_filter(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &query, uint64_t knn, uint64_t complexity,
+ filterT filter);
+
+ NeighborsAndDistances<StaticIdType> batch_search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &queries, uint64_t num_queries, uint64_t knn,
+ uint64_t complexity, uint32_t num_threads);
+
+ private:
+ diskann::Index<DT, StaticIdType, filterT> _index;
+};
+} // namespace diskannpy
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/__init__.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/__init__.py
new file mode 100644
index 0000000..c2e1b07
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/__init__.py
@@ -0,0 +1,138 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+"""
+# Documentation Overview
+`diskannpy` is mostly structured around 2 distinct processes: [Index Builder Functions](#index-builders) and [Search Classes](#search-classes)
+
+It also includes a few nascent [utilities](#utilities).
+
+And lastly, it makes substantial use of type hints, with various shorthand [type aliases](#parameter-and-response-type-aliases) documented.
+When reading the `diskannpy` code we refer to the type aliases, though `pdoc` helpfully expands them.
+
+## Index Builders
+- `build_disk_index` - To build an index that cannot fully fit into memory when searching
+- `build_memory_index` - To build an index that can fully fit into memory when searching
+
+## Search Classes
+- `StaticMemoryIndex` - for indices that can fully fit in memory and won't be changed during the search operations
+- `StaticDiskIndex` - for indices that cannot fully fit in memory, thus relying on disk IO to search, and also won't be changed during search operations
+- `DynamicMemoryIndex` - for indices that can fully fit in memory and will be mutated via insert/deletion operations as well as search operations
+
+## Parameter Defaults
+- `diskannpy.defaults` - Default values exported from the C++ extension for Python users
+
+## Parameter and Response Type Aliases
+- `DistanceMetric` - What distance metrics does `diskannpy` support?
+- `VectorDType` - What vector datatypes does `diskannpy` support?
+- `QueryResponse` - What can I expect as a response to my search?
+- `QueryResponseBatch` - What can I expect as a response to my batch search?
+- `VectorIdentifier` - What types do `diskannpy` support as vector identifiers?
+- `VectorIdentifierBatch` - A batch of identifiers of the exact same type. The type can change, but they must **all** change.
+- `VectorLike` - How does a vector look to `diskannpy`, to be inserted or searched with.
+- `VectorLikeBatch` - A batch of those vectors, to be inserted or searched with.
+- `Metadata` - DiskANN vector binary file metadata (num_points, vector_dim)
+
+## Utilities
+- `vectors_to_file` - Turns a 2 dimensional `numpy.typing.NDArray[VectorDType]` with shape `(number_of_points, vector_dim)` into a DiskANN vector bin file.
+- `vectors_from_file` - Reads a DiskANN vector bin file representing stored vectors into a numpy ndarray.
+- `vectors_metadata_from_file` - Reads metadata stored in a DiskANN vector bin file without reading the entire file
+- `tags_to_file` - Turns a 1 dimensional `numpy.typing.NDArray[VectorIdentifier]` into a DiskANN tags bin file.
+- `tags_from_file` - Reads a DiskANN tags bin file representing stored tags into a numpy ndarray.
+- `valid_dtype` - Checks if a given vector dtype is supported by `diskannpy`
+"""
+
+from typing import Any, Literal, NamedTuple, Type, Union
+
+import numpy as np
+from numpy import typing as npt
+
+DistanceMetric = Literal["l2", "mips", "cosine"]
+""" Type alias for one of {"l2", "mips", "cosine"} """
+VectorDType = Union[Type[np.float32], Type[np.int8], Type[np.uint8]]
+""" Type alias for one of {`numpy.float32`, `numpy.int8`, `numpy.uint8`} """
+VectorLike = npt.NDArray[VectorDType]
+""" Type alias for something that can be treated as a vector """
+VectorLikeBatch = npt.NDArray[VectorDType]
+""" Type alias for a batch of VectorLikes """
+VectorIdentifier = np.uint32
+"""
+Type alias for a vector identifier, whether it be an implicit array index identifier from StaticMemoryIndex or
+StaticDiskIndex, or an explicit tag identifier from DynamicMemoryIndex
+"""
+VectorIdentifierBatch = npt.NDArray[np.uint32]
+""" Type alias for a batch of VectorIdentifiers """
+
+
+class QueryResponse(NamedTuple):
+ """
+ Tuple with two values, identifiers and distances. Both are 1d arrays, positionally correspond, and will contain the
+ nearest neighbors from [0..k_neighbors)
+ """
+
+ identifiers: npt.NDArray[VectorIdentifier]
+ """ A `numpy.typing.NDArray[VectorIdentifier]` array of vector identifiers, 1 dimensional """
+ distances: npt.NDArray[np.float32]
+ """
+ A `numpy.typing.NDAarray[numpy.float32]` of distances as calculated by the distance metric function, 1 dimensional
+ """
+
+
+class QueryResponseBatch(NamedTuple):
+ """
+ Tuple with two values, identifiers and distances. Both are 2d arrays, with dimensionality determined by the
+ rows corresponding to the number of queries made, and the columns corresponding to the k neighbors
+ requested. The two 2d arrays have an implicit, position-based relationship
+ """
+
+ identifiers: npt.NDArray[VectorIdentifier]
+ """
+ A `numpy.typing.NDArray[VectorIdentifier]` array of vector identifiers, 2 dimensional. The row corresponds to index
+ of the query, and the column corresponds to the k neighbors requested
+ """
+ distances: np.ndarray[np.float32]
+ """
+ A `numpy.typing.NDAarray[numpy.float32]` of distances as calculated by the distance metric function, 2 dimensional.
+ The row corresponds to the index of the query, and the column corresponds to the distance of the query to the
+ *k-th* neighbor
+ """
+
+
+from . import defaults
+from ._builder import build_disk_index, build_memory_index
+from ._common import valid_dtype
+from ._dynamic_memory_index import DynamicMemoryIndex
+from ._files import (
+ Metadata,
+ tags_from_file,
+ tags_to_file,
+ vectors_from_file,
+ vectors_metadata_from_file,
+ vectors_to_file,
+)
+from ._static_disk_index import StaticDiskIndex
+from ._static_memory_index import StaticMemoryIndex
+
+__all__ = [
+ "build_disk_index",
+ "build_memory_index",
+ "StaticDiskIndex",
+ "StaticMemoryIndex",
+ "DynamicMemoryIndex",
+ "defaults",
+ "DistanceMetric",
+ "VectorDType",
+ "QueryResponse",
+ "QueryResponseBatch",
+ "VectorIdentifier",
+ "VectorIdentifierBatch",
+ "VectorLike",
+ "VectorLikeBatch",
+ "Metadata",
+ "vectors_metadata_from_file",
+ "vectors_to_file",
+ "vectors_from_file",
+ "tags_to_file",
+ "tags_from_file",
+ "valid_dtype",
+]
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_builder.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_builder.py
new file mode 100644
index 0000000..6567020
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_builder.py
@@ -0,0 +1,349 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import json
+import os
+import shutil
+from pathlib import Path
+from typing import Optional, Tuple, Union
+
+import numpy as np
+
+from . import DistanceMetric, VectorDType, VectorIdentifierBatch, VectorLikeBatch
+from . import _diskannpy as _native_dap
+from ._common import (
+ _assert,
+ _assert_is_nonnegative_uint32,
+ _assert_is_positive_uint32,
+ _castable_dtype_or_raise,
+ _valid_metric,
+ _write_index_metadata,
+ valid_dtype,
+)
+from ._diskannpy import defaults
+from ._files import tags_to_file, vectors_metadata_from_file, vectors_to_file
+
+
+def _valid_path_and_dtype(
+ data: Union[str, VectorLikeBatch],
+ vector_dtype: VectorDType,
+ index_path: str,
+ index_prefix: str,
+) -> Tuple[str, VectorDType]:
+ if isinstance(data, str):
+ vector_bin_path = data
+ _assert(
+ Path(data).exists() and Path(data).is_file(),
+ "if data is of type `str`, it must both exist and be a file",
+ )
+ vector_dtype_actual = valid_dtype(vector_dtype)
+ else:
+ vector_bin_path = os.path.join(index_path, f"{index_prefix}_vectors.bin")
+ # if Path(vector_bin_path).exists():
+ # raise ValueError(
+ # f"The path {vector_bin_path} already exists. Remove it and try again."
+ # )
+ vector_dtype_actual = valid_dtype(data.dtype)
+ # vectors_to_file(vector_file=vector_bin_path, vectors=data)
+
+ return vector_bin_path, vector_dtype_actual
+
+
+def build_disk_index(
+ data: Union[str, VectorLikeBatch],
+ distance_metric: DistanceMetric,
+ index_directory: str,
+ complexity: int,
+ graph_degree: int,
+ search_memory_maximum: float,
+ build_memory_maximum: float,
+ num_threads: int,
+ pq_disk_bytes: int = defaults.PQ_DISK_BYTES,
+ vector_dtype: Optional[VectorDType] = None,
+ index_prefix: str = "ann",
+ codebook_prefix: str = "",
+) -> None:
+ """
+ This function will construct a DiskANN disk index. Disk indices are ideal for very large datasets that
+ are too large to fit in memory. Memory is still used, but it is primarily used to provide precise disk
+ locations for fast retrieval of smaller subsets of the index without compromising much on recall.
+
+ If you provide a numpy array, it will save this array to disk in a temp location
+ in the format DiskANN's PQ Flash Index builder requires. This temp folder is deleted upon index creation completion
+ or error.
+
+ ## Distance Metric and Vector Datatype Restrictions
+ | Metric \ Datatype | np.float32 | np.uint8 | np.int8 |
+ |-------------------|------------|----------|---------|
+ | L2 | ✅ | ✅ | ✅ |
+ | MIPS | ✅ | ❌ | ❌ |
+ | Cosine [^bug-in-disk-cosine] | ❌ | ❌ | ❌ |
+
+ [^bug-in-disk-cosine]: For StaticDiskIndex, Cosine distances are not currently supported.
+
+ ### Parameters
+ - **data**: Either a `str` representing a path to a DiskANN vector bin file, or a numpy.ndarray,
+ of a supported dtype, in 2 dimensions. Note that `vector_dtype` must be provided if data is a `str`
+ - **distance_metric**: A `str`, strictly one of {"l2", "mips", "cosine"}. `l2` and `cosine` are supported for all 3
+ vector dtypes, but `mips` is only available for single precision floats.
+ - **index_directory**: The index files will be saved to this **existing** directory path
+ - **complexity**: The size of the candidate nearest neighbor list to use when building the index. Values between 75
+ and 200 are typical. Larger values will take more time to build but result in indices that provide higher recall
+ for the same search complexity. Use a value that is at least as large as `graph_degree` unless you are prepared
+ to compromise on quality
+ - **graph_degree**: The degree of the graph index, typically between 60 and 150. A larger maximum degree will
+ result in larger indices and longer indexing times, but better search quality.
+ - **search_memory_maximum**: Build index with the expectation that the search will use at most
+ `search_memory_maximum`, in gb.
+ - **build_memory_maximum**: Build index using at most `build_memory_maximum` in gb. Building processes typically
+ require more memory, while search memory can be reduced.
+ - **num_threads**: Number of threads to use when creating this index. `0` is used to indicate all available
+ logical processors should be used.
+ - **pq_disk_bytes**: Use `0` to store uncompressed data on SSD. This allows the index to asymptote to 100%
+ recall. If your vectors are too large to store in SSD, this parameter provides the option to compress the
+ vectors using PQ for storing on SSD. This will trade off recall. You would also want this to be greater
+ than the number of bytes used for the PQ compressed data stored in-memory. Default is `0`.
+ - **vector_dtype**: Required if the provided `data` is of type `str`, else we use the `data.dtype` if np array.
+ - **index_prefix**: The prefix of the index files. Defaults to "ann".
+ """
+
+ _assert(
+ (isinstance(data, str) and vector_dtype is not None)
+ or isinstance(data, np.ndarray),
+ "vector_dtype is required if data is a str representing a path to the vector bin file",
+ )
+ dap_metric = _valid_metric(distance_metric)
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_positive_uint32(graph_degree, "graph_degree")
+ _assert(search_memory_maximum > 0, "search_memory_maximum must be larger than 0")
+ _assert(build_memory_maximum > 0, "build_memory_maximum must be larger than 0")
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+ _assert_is_nonnegative_uint32(pq_disk_bytes, "pq_disk_bytes")
+ _assert(index_prefix != "", "index_prefix cannot be an empty string")
+
+ index_path = Path(index_directory)
+ _assert(
+ index_path.exists() and index_path.is_dir(),
+ "index_directory must both exist and be a directory",
+ )
+
+ vector_bin_path, vector_dtype_actual = _valid_path_and_dtype(
+ data, vector_dtype, index_directory, index_prefix
+ )
+ _assert(dap_metric != _native_dap.COSINE, "Cosine is currently not supported in StaticDiskIndex")
+ if dap_metric == _native_dap.INNER_PRODUCT:
+ _assert(
+ vector_dtype_actual == np.float32,
+ "Integral vector dtypes (np.uint8, np.int8) are not supported with distance metric mips"
+ )
+
+ num_points, dimensions = vectors_metadata_from_file(vector_bin_path)
+
+ if vector_dtype_actual == np.uint8:
+ _builder = _native_dap.build_disk_uint8_index
+ elif vector_dtype_actual == np.int8:
+ _builder = _native_dap.build_disk_int8_index
+ else:
+ _builder = _native_dap.build_disk_float_index
+
+ index_prefix_path = os.path.join(index_directory, index_prefix)
+
+ _builder(
+ distance_metric=dap_metric,
+ data_file_path=vector_bin_path,
+ index_prefix_path=index_prefix_path,
+ complexity=complexity,
+ graph_degree=graph_degree,
+ final_index_ram_limit=search_memory_maximum,
+ indexing_ram_budget=build_memory_maximum,
+ num_threads=num_threads,
+ pq_disk_bytes=pq_disk_bytes,
+ codebook_prefix=codebook_prefix,
+ )
+ _write_index_metadata(
+ index_prefix_path, vector_dtype_actual, dap_metric, num_points, dimensions
+ )
+
+
+def build_memory_index(
+ data: Union[str, VectorLikeBatch],
+ distance_metric: DistanceMetric,
+ index_directory: str,
+ complexity: int,
+ graph_degree: int,
+ num_threads: int,
+ alpha: float = defaults.ALPHA,
+ use_pq_build: bool = defaults.USE_PQ_BUILD,
+ num_pq_bytes: int = defaults.NUM_PQ_BYTES,
+ use_opq: bool = defaults.USE_OPQ,
+ vector_dtype: Optional[VectorDType] = None,
+ tags: Union[str, VectorIdentifierBatch] = "",
+ filter_labels: Optional[list[list[str]]] = None,
+ universal_label: str = "",
+ filter_complexity: int = defaults.FILTER_COMPLEXITY,
+ index_prefix: str = "ann",
+) -> None:
+ """
+ This function will construct a DiskANN memory index. Memory indices are ideal for smaller datasets whose
+ indices can fit into memory. Memory indices are faster than disk indices, but usually cannot scale to massive
+ sizes in an individual index on an individual machine.
+
+ `diskannpy`'s memory indices take two forms: a `diskannpy.StaticMemoryIndex`, which will not be mutated, only
+ searched upon, and a `diskannpy.DynamicMemoryIndex`, which can be mutated AND searched upon in the same process.
+
+ ## Important Note:
+ You **must** determine the type of index you are building for. If you are building for a
+ `diskannpy.DynamicMemoryIndex`, you **must** supply a valid value for the `tags` parameter. **Do not supply
+ tags if the index is intended to be `diskannpy.StaticMemoryIndex`**!
+
+ ## Distance Metric and Vector Datatype Restrictions
+
+ | Metric \ Datatype | np.float32 | np.uint8 | np.int8 |
+ |-------------------|------------|----------|---------|
+ | L2 | ✅ | ✅ | ✅ |
+ | MIPS | ✅ | ❌ | ❌ |
+ | Cosine | ✅ | ✅ | ✅ |
+
+ ### Parameters
+
+ - **data**: Either a `str` representing a path to an existing DiskANN vector bin file, or a numpy.ndarray of a
+ supported dtype in 2 dimensions. Note that `vector_dtype` must be provided if `data` is a `str`.
+ - **distance_metric**: A `str`, strictly one of {"l2", "mips", "cosine"}. `l2` and `cosine` are supported for all 3
+ vector dtypes, but `mips` is only available for single precision floats.
+ - **index_directory**: The index files will be saved to this **existing** directory path
+ - **complexity**: The size of the candidate nearest neighbor list to use when building the index. Values between 75
+ and 200 are typical. Larger values will take more time to build but result in indices that provide higher recall
+ for the same search complexity. Use a value that is at least as large as `graph_degree` unless you are prepared
+ to compromise on quality
+ - **graph_degree**: The degree of the graph index, typically between 60 and 150. A larger maximum degree will
+ result in larger indices and longer indexing times, but better search quality.
+ - **num_threads**: Number of threads to use when creating this index. `0` is used to indicate all available
+ logical processors should be used.
+ - **alpha**: The alpha parameter (>=1) is used to control the nature and number of points that are added to the
+ graph. A higher alpha value (e.g., 1.4) will result in fewer hops (and IOs) to convergence, but probably more
+ distance comparisons compared to a lower alpha value.
+ - **use_pq_build**: Use product quantization during build. Product quantization is a lossy compression technique
+ that can reduce the size of the index on disk. This will trade off recall. Default is `True`.
+ - **num_pq_bytes**: The number of bytes used to store the PQ compressed data in memory. This will trade off recall.
+ Default is `0`.
+ - **use_opq**: Use optimized product quantization during build.
+ - **vector_dtype**: Required if the provided `data` is of type `str`, else we use the `data.dtype` if np array.
+ - **tags**: Tags can be defined either as a path on disk to an existing .tags file, or provided as a np.array of
+ the same length as the number of vectors. Tags are used to identify vectors in the index via your *own*
+ numbering conventions, and is absolutely required for loading DynamicMemoryIndex indices `from_file`.
+ - **filter_labels**: An optional, but exhaustive list of categories for each vector. This is used to filter
+ search results by category. If provided, this must be a list of lists, where each inner list is a list of
+ categories for the corresponding vector. For example, if you have 3 vectors, and the first vector belongs to
+ categories "a" and "b", the second vector belongs to category "b", and the third vector belongs to no categories,
+ you would provide `filter_labels=[["a", "b"], ["b"], []]`. If you do not want to provide categories for a
+ particular vector, you can provide an empty list. If you do not want to provide categories for any vectors,
+ you can provide `None` for this parameter (which is the default)
+ - **universal_label**: An optional label that indicates that this vector should be included in *every* search
+ in which it also meets the knn search criteria.
+ - **filter_complexity**: Complexity to use when using filters. Default is 0. 0 is strictly invalid if you are
+ using filters.
+ - **index_prefix**: The prefix of the index files. Defaults to "ann".
+ """
+ _assert(
+ (isinstance(data, str) and vector_dtype is not None)
+ or isinstance(data, np.ndarray),
+ "vector_dtype is required if data is a str representing a path to the vector bin file",
+ )
+ dap_metric = _valid_metric(distance_metric)
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_positive_uint32(graph_degree, "graph_degree")
+ _assert(
+ alpha >= 1,
+ "alpha must be >= 1, and realistically should be kept between [1.0, 2.0)",
+ )
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+ _assert_is_nonnegative_uint32(num_pq_bytes, "num_pq_bytes")
+ _assert_is_nonnegative_uint32(filter_complexity, "filter_complexity")
+ _assert(index_prefix != "", "index_prefix cannot be an empty string")
+ _assert(
+ filter_labels is None or filter_complexity > 0,
+ "if filter_labels is provided, filter_complexity must not be 0"
+ )
+
+ index_path = Path(index_directory)
+ _assert(
+ index_path.exists() and index_path.is_dir(),
+ "index_directory must both exist and be a directory",
+ )
+
+ vector_bin_path, vector_dtype_actual = _valid_path_and_dtype(
+ data, vector_dtype, index_directory, index_prefix
+ )
+ if dap_metric == _native_dap.INNER_PRODUCT:
+ _assert(
+ vector_dtype_actual == np.float32,
+ "Integral vector dtypes (np.uint8, np.int8) are not supported with distance metric mips"
+ )
+
+ num_points, dimensions = vectors_metadata_from_file(vector_bin_path)
+ if filter_labels is not None:
+ _assert(
+ len(filter_labels) == num_points,
+ "filter_labels must be the same length as the number of points"
+ )
+
+ if vector_dtype_actual == np.uint8:
+ _builder = _native_dap.build_memory_uint8_index
+ elif vector_dtype_actual == np.int8:
+ _builder = _native_dap.build_memory_int8_index
+ else:
+ _builder = _native_dap.build_memory_float_index
+
+ index_prefix_path = os.path.join(index_directory, index_prefix)
+
+ filter_labels_file = ""
+ if filter_labels is not None:
+ label_counts = {}
+ filter_labels_file = f"{index_prefix_path}_pylabels.txt"
+ with open(filter_labels_file, "w") as labels_file:
+ for labels in filter_labels:
+ for label in labels:
+ label_counts[label] = 1 if label not in label_counts else label_counts[label] + 1
+ if len(labels) == 0:
+ print("default", file=labels_file)
+ else:
+ print(",".join(labels), file=labels_file)
+ with open(f"{index_prefix_path}_label_metadata.json", "w") as label_metadata_file:
+ json.dump(label_counts, label_metadata_file, indent=True)
+
+ if isinstance(tags, str) and tags != "":
+ use_tags = True
+ shutil.copy(tags, index_prefix_path + ".tags")
+ elif not isinstance(tags, str):
+ use_tags = True
+ tags_as_array = _castable_dtype_or_raise(tags, expected=np.uint32)
+ _assert(len(tags_as_array.shape) == 1, "Provided tags must be 1 dimensional")
+ _assert(
+ tags_as_array.shape[0] == num_points,
+ "Provided tags must contain an identical population to the number of points, "
+ f"{tags_as_array.shape[0]=}, {num_points=}",
+ )
+ tags_to_file(index_prefix_path + ".tags", tags_as_array)
+ else:
+ use_tags = False
+
+ _builder(
+ distance_metric=dap_metric,
+ data_file_path=vector_bin_path,
+ index_output_path=index_prefix_path,
+ complexity=complexity,
+ graph_degree=graph_degree,
+ alpha=alpha,
+ num_threads=num_threads,
+ use_pq_build=use_pq_build,
+ num_pq_bytes=num_pq_bytes,
+ use_opq=use_opq,
+ use_tags=use_tags,
+ filter_labels_file=filter_labels_file,
+ universal_label=universal_label,
+ filter_complexity=filter_complexity,
+ )
+
+ _write_index_metadata(
+ index_prefix_path, vector_dtype_actual, dap_metric, num_points, dimensions
+ )
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_builder.pyi b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_builder.pyi
new file mode 100644
index 0000000..223e6c9
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_builder.pyi
@@ -0,0 +1,74 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+from typing import BinaryIO, Optional, overload
+
+import numpy as np
+
+from . import DistanceMetric, VectorDType, VectorIdentifierBatch, VectorLikeBatch
+
+def numpy_to_diskann_file(vectors: np.ndarray, file_handler: BinaryIO): ...
+@overload
+def build_disk_index(
+ data: str,
+ distance_metric: DistanceMetric,
+ index_directory: str,
+ complexity: int,
+ graph_degree: int,
+ search_memory_maximum: float,
+ build_memory_maximum: float,
+ num_threads: int,
+ pq_disk_bytes: int,
+ vector_dtype: VectorDType,
+ index_prefix: str,
+) -> None: ...
+@overload
+def build_disk_index(
+ data: VectorLikeBatch,
+ distance_metric: DistanceMetric,
+ index_directory: str,
+ complexity: int,
+ graph_degree: int,
+ search_memory_maximum: float,
+ build_memory_maximum: float,
+ num_threads: int,
+ pq_disk_bytes: int,
+ index_prefix: str,
+) -> None: ...
+@overload
+def build_memory_index(
+ data: VectorLikeBatch,
+ distance_metric: DistanceMetric,
+ index_directory: str,
+ complexity: int,
+ graph_degree: int,
+ alpha: float,
+ num_threads: int,
+ use_pq_build: bool,
+ num_pq_bytes: int,
+ use_opq: bool,
+ tags: Union[str, VectorIdentifierBatch],
+ filter_labels: Optional[list[list[str]]],
+ universal_label: str,
+ filter_complexity: int,
+ index_prefix: str
+) -> None: ...
+@overload
+def build_memory_index(
+ data: str,
+ distance_metric: DistanceMetric,
+ index_directory: str,
+ complexity: int,
+ graph_degree: int,
+ alpha: float,
+ num_threads: int,
+ use_pq_build: bool,
+ num_pq_bytes: int,
+ use_opq: bool,
+ vector_dtype: VectorDType,
+ tags: Union[str, VectorIdentifierBatch],
+ filter_labels_file: Optional[list[list[str]]],
+ universal_label: str,
+ filter_complexity: int,
+ index_prefix: str
+) -> None: ...
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_common.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_common.py
new file mode 100644
index 0000000..2b28802
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_common.py
@@ -0,0 +1,251 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import os
+import warnings
+from enum import Enum
+from pathlib import Path
+from typing import Literal, NamedTuple, Optional, Tuple, Type, Union
+
+import numpy as np
+
+from . import (
+ DistanceMetric,
+ VectorDType,
+ VectorIdentifierBatch,
+ VectorLike,
+ VectorLikeBatch,
+)
+from . import _diskannpy as _native_dap
+
+__ALL__ = ["valid_dtype"]
+
+_VALID_DTYPES = [np.float32, np.int8, np.uint8]
+
+
+def valid_dtype(dtype: Type) -> VectorDType:
+ """
+ Utility method to determine whether the provided dtype is supported by `diskannpy`, and if so, the canonical
+ dtype we will use internally (e.g. np.single -> np.float32)
+ """
+ _assert_dtype(dtype)
+ if dtype == np.uint8:
+ return np.uint8
+ if dtype == np.int8:
+ return np.int8
+ if dtype == np.float32:
+ return np.float32
+
+
+def _assert(statement_eval: bool, message: str):
+ if not statement_eval:
+ raise ValueError(message)
+
+
+def _valid_metric(metric: str) -> _native_dap.Metric:
+ if not isinstance(metric, str):
+ raise ValueError("distance_metric must be a string")
+ if metric.lower() == "l2":
+ return _native_dap.L2
+ elif metric.lower() == "mips":
+ return _native_dap.INNER_PRODUCT
+ elif metric.lower() == "cosine":
+ return _native_dap.COSINE
+ else:
+ raise ValueError("distance_metric must be one of 'l2', 'mips', or 'cosine'")
+
+
+def _assert_dtype(dtype: Type):
+ _assert(
+ any(np.can_cast(dtype, _dtype) for _dtype in _VALID_DTYPES),
+ f"Vector dtype must be of one of type {{(np.single, np.float32), (np.byte, np.int8), (np.ubyte, np.uint8)}}",
+ )
+
+
+def _castable_dtype_or_raise(
+ data: Union[VectorLike, VectorLikeBatch, VectorIdentifierBatch], expected: np.dtype
+) -> np.ndarray:
+ if isinstance(data, np.ndarray) and np.can_cast(data.dtype, expected):
+ return data.astype(expected, casting="safe")
+ else:
+ raise TypeError(
+ f"expecting a numpy ndarray of dtype {expected}, not a {type(data)}"
+ )
+
+
+def _assert_2d(vectors: np.ndarray, name: str):
+ _assert(len(vectors.shape) == 2, f"{name} must be 2d numpy array")
+
+
+__MAX_UINT32_VAL = 4_294_967_295
+
+
+def _assert_is_positive_uint32(test_value: int, parameter: str):
+ _assert(
+ test_value is not None and 0 < test_value < __MAX_UINT32_VAL,
+ f"{parameter} must be a positive integer in the uint32 range",
+ )
+
+
+def _assert_is_nonnegative_uint32(test_value: int, parameter: str):
+ _assert(
+ test_value is not None and -1 < test_value < __MAX_UINT32_VAL,
+ f"{parameter} must be a non-negative integer in the uint32 range",
+ )
+
+
+def _assert_is_nonnegative_uint64(test_value: int, parameter: str):
+ _assert(
+ -1 < test_value,
+ f"{parameter} must be a non-negative integer in the uint64 range",
+ )
+
+
+def _assert_existing_directory(path: str, parameter: str):
+ _path = Path(path)
+ _assert(
+ _path.exists() and _path.is_dir(), f"{parameter} must be an existing directory"
+ )
+
+
+def _assert_existing_file(path: str, parameter: str):
+ _path = Path(path)
+ _assert(_path.exists() and _path.is_file(), f"{parameter} must be an existing file")
+
+
+class _DataType(Enum):
+ FLOAT32 = 0
+ INT8 = 1
+ UINT8 = 2
+
+ @classmethod
+ def from_type(cls, vector_dtype: VectorDType) -> "DataType":
+ if vector_dtype == np.float32:
+ return cls.FLOAT32
+ if vector_dtype == np.int8:
+ return cls.INT8
+ if vector_dtype == np.uint8:
+ return cls.UINT8
+
+ def to_type(self) -> VectorDType:
+ if self is _DataType.FLOAT32:
+ return np.float32
+ if self is _DataType.INT8:
+ return np.int8
+ if self is _DataType.UINT8:
+ return np.uint8
+
+
+class _Metric(Enum):
+ L2 = 0
+ MIPS = 1
+ COSINE = 2
+
+ @classmethod
+ def from_native(cls, metric: _native_dap.Metric) -> "_Metric":
+ if metric == _native_dap.L2:
+ return cls.L2
+ if metric == _native_dap.INNER_PRODUCT:
+ return cls.MIPS
+ if metric == _native_dap.COSINE:
+ return cls.COSINE
+
+ def to_native(self) -> _native_dap.Metric:
+ if self is _Metric.L2:
+ return _native_dap.L2
+ if self is _Metric.MIPS:
+ return _native_dap.INNER_PRODUCT
+ if self is _Metric.COSINE:
+ return _native_dap.COSINE
+
+ def to_str(self) -> _native_dap.Metric:
+ if self is _Metric.L2:
+ return "l2"
+ if self is _Metric.MIPS:
+ return "mips"
+ if self is _Metric.COSINE:
+ return "cosine"
+
+
+def _build_metadata_path(index_path_and_prefix: str) -> str:
+ return index_path_and_prefix + "_metadata.bin"
+
+
+def _write_index_metadata(
+ index_path_and_prefix: str,
+ dtype: VectorDType,
+ metric: _native_dap.Metric,
+ num_points: int,
+ dimensions: int,
+):
+ np.array(
+ [
+ _DataType.from_type(dtype).value,
+ _Metric.from_native(metric).value,
+ num_points,
+ dimensions,
+ ],
+ dtype=np.uint64,
+ ).tofile(_build_metadata_path(index_path_and_prefix))
+
+
+def _read_index_metadata(
+ index_path_and_prefix: str,
+) -> Optional[Tuple[VectorDType, str, np.uint64, np.uint64]]:
+ path = _build_metadata_path(index_path_and_prefix)
+ if not Path(path).exists():
+ return None
+ else:
+ metadata = np.fromfile(path, dtype=np.uint64, count=-1)
+ return (
+ _DataType(int(metadata[0])).to_type(),
+ _Metric(int(metadata[1])).to_str(),
+ metadata[2],
+ metadata[3],
+ )
+
+
+def _ensure_index_metadata(
+ index_path_and_prefix: str,
+ vector_dtype: Optional[VectorDType],
+ distance_metric: Optional[DistanceMetric],
+ max_vectors: int,
+ dimensions: Optional[int],
+ warn_size_exceeded: bool = False,
+) -> Tuple[VectorDType, str, np.uint64, np.uint64]:
+ possible_metadata = _read_index_metadata(index_path_and_prefix)
+ if possible_metadata is None:
+ _assert(
+ all([vector_dtype, distance_metric, dimensions]),
+ "distance_metric, vector_dtype, and dimensions must provided if a corresponding metadata file has not "
+ "been built for this index, such as when an index was built via the CLI tools or prior to the addition "
+ "of a metadata file",
+ )
+ _assert_dtype(vector_dtype)
+ _assert_is_positive_uint32(max_vectors, "max_vectors")
+ _assert_is_positive_uint32(dimensions, "dimensions")
+ return vector_dtype, distance_metric, max_vectors, dimensions # type: ignore
+ else:
+ vector_dtype, distance_metric, num_vectors, dimensions = possible_metadata
+ if warn_size_exceeded:
+ if max_vectors is not None and num_vectors > max_vectors:
+ warnings.warn(
+ "The number of vectors in the saved index exceeds the max_vectors parameter. "
+ "max_vectors is being adjusted to accommodate the dataset, but any insertions will fail."
+ )
+ max_vectors = num_vectors
+ if num_vectors == max_vectors:
+ warnings.warn(
+ "The number of vectors in the saved index equals max_vectors parameter. Any insertions will fail."
+ )
+ return possible_metadata
+
+
+def _valid_index_prefix(index_directory: str, index_prefix: str) -> str:
+ _assert(
+ index_directory is not None and index_directory != "",
+ "index_directory cannot be None or empty",
+ )
+ _assert_existing_directory(index_directory, "index_directory")
+ _assert(index_prefix != "", "index_prefix cannot be an empty string")
+ return os.path.join(index_directory, index_prefix)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_diskannpy.cpython-310-x86_64-linux-gnu.so.bak b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_diskannpy.cpython-310-x86_64-linux-gnu.so.bak
new file mode 100755
index 0000000..5741ecd
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_diskannpy.cpython-310-x86_64-linux-gnu.so.bak differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_dynamic_memory_index.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_dynamic_memory_index.py
new file mode 100644
index 0000000..cdf6432
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_dynamic_memory_index.py
@@ -0,0 +1,511 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import os
+import warnings
+from pathlib import Path
+from typing import Optional
+
+import numpy as np
+
+from . import (
+ DistanceMetric,
+ QueryResponse,
+ QueryResponseBatch,
+ VectorDType,
+ VectorIdentifier,
+ VectorIdentifierBatch,
+ VectorLike,
+ VectorLikeBatch,
+)
+from . import _diskannpy as _native_dap
+from ._common import (
+ _assert,
+ _assert_2d,
+ _assert_dtype,
+ _assert_existing_directory,
+ _assert_is_nonnegative_uint32,
+ _assert_is_positive_uint32,
+ _castable_dtype_or_raise,
+ _ensure_index_metadata,
+ _valid_index_prefix,
+ _valid_metric,
+ _write_index_metadata,
+)
+from ._diskannpy import defaults
+
+__ALL__ = ["DynamicMemoryIndex"]
+
+
+class DynamicMemoryIndex:
+ """
+ A DynamicMemoryIndex instance is used to both search and mutate a `diskannpy` memory index. This index is unlike
+ either `diskannpy.StaticMemoryIndex` or `diskannpy.StaticDiskIndex` in the following ways:
+
+ - It requires an explicit vector identifier for each vector added to it.
+ - Insert and (lazy) deletion operations are provided for a flexible, living index
+
+ The mutable aspect of this index will absolutely impact search time performance as new vectors are added and
+ old deleted. `DynamicMemoryIndex.consolidate_deletes()` should be called periodically to restructure the index
+ to remove deleted vectors and improve per-search performance, at the cost of an expensive index consolidation to
+ occur.
+ """
+
+ @classmethod
+ def from_file(
+ cls,
+ index_directory: str,
+ max_vectors: int,
+ complexity: int,
+ graph_degree: int,
+ saturate_graph: bool = defaults.SATURATE_GRAPH,
+ max_occlusion_size: int = defaults.MAX_OCCLUSION_SIZE,
+ alpha: float = defaults.ALPHA,
+ num_threads: int = defaults.NUM_THREADS,
+ filter_complexity: int = defaults.FILTER_COMPLEXITY,
+ num_frozen_points: int = defaults.NUM_FROZEN_POINTS_DYNAMIC,
+ initial_search_complexity: int = 0,
+ search_threads: int = 0,
+ concurrent_consolidation: bool = True,
+ index_prefix: str = "ann",
+ distance_metric: Optional[DistanceMetric] = None,
+ vector_dtype: Optional[VectorDType] = None,
+ dimensions: Optional[int] = None,
+ ) -> "DynamicMemoryIndex":
+ """
+ The `from_file` classmethod is used to load a previously saved index from disk. This index *must* have been
+ created with a valid `tags` file or `tags` np.ndarray of `diskannpy.VectorIdentifier`s. It is *strongly*
+ recommended that you use the same parameters as the `diskannpy.build_memory_index()` function that created
+ the index.
+
+ ### Parameters
+ - **index_directory**: The directory containing the index files. This directory must contain the following
+ files:
+ - `{index_prefix}.data`
+ - `{index_prefix}.tags`
+ - `{index_prefix}`
+
+ It may also include the following optional files:
+ - `{index_prefix}_vectors.bin`: Optional. `diskannpy` builder functions may create this file in the
+ `index_directory` if the index was created from a numpy array
+ - `{index_prefix}_metadata.bin`: Optional. `diskannpy` builder functions create this file to store metadata
+ about the index, such as vector dtype, distance metric, number of vectors and vector dimensionality.
+ If an index is built from the `diskann` cli tools, this file will not exist.
+ - **max_vectors**: Capacity of the memory index including space for future insertions.
+ - **complexity**: Complexity (a.k.a `L`) references the size of the list we store candidate approximate
+ neighbors in. It's used during save (which is an index rebuild), and it's used as an initial search size to
+ warm up our index and lower the latency for initial real searches.
+ - **graph_degree**: Graph degree (a.k.a. `R`) is the maximum degree allowed for a node in the index's graph
+ structure. This degree will be pruned throughout the course of the index build, but it will never grow beyond
+ this value. Higher R values require longer index build times, but may result in an index showing excellent
+ recall and latency characteristics.
+ - **saturate_graph**: If True, the adjacency list of each node will be saturated with neighbors to have exactly
+ `graph_degree` neighbors. If False, each node will have between 1 and `graph_degree` neighbors.
+ - **max_occlusion_size**: The maximum number of points that can be considered by occlude_list function.
+ - **alpha**: The alpha parameter (>=1) is used to control the nature and number of points that are added to the
+ graph. A higher alpha value (e.g., 1.4) will result in fewer hops (and IOs) to convergence, but probably
+ more distance comparisons compared to a lower alpha value.
+ - **num_threads**: Number of threads to use when creating this index. `0` indicates we should use all available
+ logical processors.
+ - **filter_complexity**: Complexity to use when using filters. Default is 0.
+ - **num_frozen_points**: Number of points to freeze. Default is 1.
+ - **initial_search_complexity**: Should be set to the most common `complexity` expected to be used during the
+ life of this `diskannpy.DynamicMemoryIndex` object. The working scratch memory allocated is based off of
+ `initial_search_complexity` * `search_threads`. Note that it may be resized if a `search` or `batch_search`
+ operation requests a space larger than can be accommodated by these values.
+ - **search_threads**: Should be set to the most common `num_threads` expected to be used during the
+ life of this `diskannpy.DynamicMemoryIndex` object. The working scratch memory allocated is based off of
+ `initial_search_complexity` * `search_threads`. Note that it may be resized if a `batch_search`
+ operation requests a space larger than can be accommodated by these values.
+ - **concurrent_consolidation**: This flag dictates whether consolidation can be run alongside inserts and
+ deletes, or whether the index is locked down to changes while consolidation is ongoing.
+ - **index_prefix**: The prefix of the index files. Defaults to "ann".
+ - **distance_metric**: A `str`, strictly one of {"l2", "mips", "cosine"}. `l2` and `cosine` are supported for all 3
+ vector dtypes, but `mips` is only available for single precision floats. Default is `None`. **This
+ value is only used if a `{index_prefix}_metadata.bin` file does not exist.** If it does not exist,
+ you are required to provide it.
+ - **vector_dtype**: The vector dtype this index has been built with. **This value is only used if a
+ `{index_prefix}_metadata.bin` file does not exist.** If it does not exist, you are required to provide it.
+ - **dimensions**: The vector dimensionality of this index. All new vectors inserted must be the same
+ dimensionality. **This value is only used if a `{index_prefix}_metadata.bin` file does not exist.** If it
+ does not exist, you are required to provide it.
+
+ ### Returns
+ A `diskannpy.DynamicMemoryIndex` object, with the index loaded from disk and ready to use for insertions,
+ deletions, and searches.
+
+ """
+ index_prefix_path = _valid_index_prefix(index_directory, index_prefix)
+
+ # do tags exist?
+ tags_file = index_prefix_path + ".tags"
+ _assert(
+ Path(tags_file).exists(),
+ f"The file {tags_file} does not exist in {index_directory}",
+ )
+ vector_dtype, dap_metric, num_vectors, dimensions = _ensure_index_metadata(
+ index_prefix_path, vector_dtype, distance_metric, max_vectors, dimensions, warn_size_exceeded=True
+ )
+
+ index = cls(
+ distance_metric=dap_metric, # type: ignore
+ vector_dtype=vector_dtype,
+ dimensions=dimensions,
+ max_vectors=max_vectors,
+ complexity=complexity,
+ graph_degree=graph_degree,
+ saturate_graph=saturate_graph,
+ max_occlusion_size=max_occlusion_size,
+ alpha=alpha,
+ num_threads=num_threads,
+ filter_complexity=filter_complexity,
+ num_frozen_points=num_frozen_points,
+ initial_search_complexity=initial_search_complexity,
+ search_threads=search_threads,
+ concurrent_consolidation=concurrent_consolidation,
+ )
+ index._index.load(index_prefix_path)
+ index._num_vectors = num_vectors # current number of vectors loaded
+ return index
+
+ def __init__(
+ self,
+ distance_metric: DistanceMetric,
+ vector_dtype: VectorDType,
+ dimensions: int,
+ max_vectors: int,
+ complexity: int,
+ graph_degree: int,
+ saturate_graph: bool = defaults.SATURATE_GRAPH,
+ max_occlusion_size: int = defaults.MAX_OCCLUSION_SIZE,
+ alpha: float = defaults.ALPHA,
+ num_threads: int = defaults.NUM_THREADS,
+ filter_complexity: int = defaults.FILTER_COMPLEXITY,
+ num_frozen_points: int = defaults.NUM_FROZEN_POINTS_DYNAMIC,
+ initial_search_complexity: int = 0,
+ search_threads: int = 0,
+ concurrent_consolidation: bool = True,
+ ):
+ """
+ The `diskannpy.DynamicMemoryIndex` represents our python API into a mutable DiskANN memory index.
+
+ This constructor is used to create a new, empty index. If you wish to load a previously saved index from disk,
+ please use the `diskannpy.DynamicMemoryIndex.from_file` classmethod instead.
+
+ ### Parameters
+ - **distance_metric**: A `str`, strictly one of {"l2", "mips", "cosine"}. `l2` and `cosine` are supported for all 3
+ vector dtypes, but `mips` is only available for single precision floats.
+ - **vector_dtype**: One of {`np.float32`, `np.int8`, `np.uint8`}. The dtype of the vectors this index will
+ be storing.
+ - **dimensions**: The vector dimensionality of this index. All new vectors inserted must be the same
+ dimensionality.
+ - **max_vectors**: Capacity of the data store including space for future insertions
+ - **graph_degree**: Graph degree (a.k.a. `R`) is the maximum degree allowed for a node in the index's graph
+ structure. This degree will be pruned throughout the course of the index build, but it will never grow beyond
+ this value. Higher `graph_degree` values require longer index build times, but may result in an index showing
+ excellent recall and latency characteristics.
+ - **saturate_graph**: If True, the adjacency list of each node will be saturated with neighbors to have exactly
+ `graph_degree` neighbors. If False, each node will have between 1 and `graph_degree` neighbors.
+ - **max_occlusion_size**: The maximum number of points that can be considered by occlude_list function.
+ - **alpha**: The alpha parameter (>=1) is used to control the nature and number of points that are added to the
+ graph. A higher alpha value (e.g., 1.4) will result in fewer hops (and IOs) to convergence, but probably
+ more distance comparisons compared to a lower alpha value.
+ - **num_threads**: Number of threads to use when creating this index. `0` indicates we should use all available
+ logical processors.
+ - **filter_complexity**: Complexity to use when using filters. Default is 0.
+ - **num_frozen_points**: Number of points to freeze. Default is 1.
+ - **initial_search_complexity**: Should be set to the most common `complexity` expected to be used during the
+ life of this `diskannpy.DynamicMemoryIndex` object. The working scratch memory allocated is based off of
+ `initial_search_complexity` * `search_threads`. Note that it may be resized if a `search` or `batch_search`
+ operation requests a space larger than can be accommodated by these values.
+ - **search_threads**: Should be set to the most common `num_threads` expected to be used during the
+ life of this `diskannpy.DynamicMemoryIndex` object. The working scratch memory allocated is based off of
+ `initial_search_complexity` * `search_threads`. Note that it may be resized if a `batch_search`
+ operation requests a space larger than can be accommodated by these values.
+ - **concurrent_consolidation**: This flag dictates whether consolidation can be run alongside inserts and
+ deletes, or whether the index is locked down to changes while consolidation is ongoing.
+
+ """
+ self._num_vectors = 0
+ self._removed_num_vectors = 0
+ dap_metric = _valid_metric(distance_metric)
+ self._dap_metric = dap_metric
+ _assert_dtype(vector_dtype)
+ _assert_is_positive_uint32(dimensions, "dimensions")
+
+ self._vector_dtype = vector_dtype
+ self._dimensions = dimensions
+
+ _assert_is_positive_uint32(max_vectors, "max_vectors")
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_positive_uint32(graph_degree, "graph_degree")
+ _assert(
+ alpha >= 1,
+ "alpha must be >= 1, and realistically should be kept between [1.0, 2.0)",
+ )
+ _assert_is_nonnegative_uint32(max_occlusion_size, "max_occlusion_size")
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+ _assert_is_nonnegative_uint32(filter_complexity, "filter_complexity")
+ _assert_is_nonnegative_uint32(num_frozen_points, "num_frozen_points")
+ _assert_is_nonnegative_uint32(
+ initial_search_complexity, "initial_search_complexity"
+ )
+ _assert_is_nonnegative_uint32(search_threads, "search_threads")
+
+ self._max_vectors = max_vectors
+ self._complexity = complexity
+ self._graph_degree = graph_degree
+
+ if vector_dtype == np.uint8:
+ _index = _native_dap.DynamicMemoryUInt8Index
+ elif vector_dtype == np.int8:
+ _index = _native_dap.DynamicMemoryInt8Index
+ else:
+ _index = _native_dap.DynamicMemoryFloatIndex
+
+ self._index = _index(
+ distance_metric=dap_metric,
+ dimensions=dimensions,
+ max_vectors=max_vectors,
+ complexity=complexity,
+ graph_degree=graph_degree,
+ saturate_graph=saturate_graph,
+ max_occlusion_size=max_occlusion_size,
+ alpha=alpha,
+ num_threads=num_threads,
+ filter_complexity=filter_complexity,
+ num_frozen_points=num_frozen_points,
+ initial_search_complexity=initial_search_complexity,
+ search_threads=search_threads,
+ concurrent_consolidation=concurrent_consolidation,
+ )
+ self._points_deleted = False
+
+ def search(
+ self, query: VectorLike, k_neighbors: int, complexity: int
+ ) -> QueryResponse:
+ """
+ Searches the index by a single query vector.
+
+ ### Parameters
+ - **query**: 1d numpy array of the same dimensionality and dtype of the index.
+ - **k_neighbors**: Number of neighbors to be returned. If query vector exists in index, it almost definitely
+ will be returned as well, so adjust your ``k_neighbors`` as appropriate. Must be > 0.
+ - **complexity**: Size of distance ordered list of candidate neighbors to use while searching. List size
+ increases accuracy at the cost of latency. Must be at least k_neighbors in size.
+ """
+ _query = _castable_dtype_or_raise(query, expected=self._vector_dtype)
+ _assert(len(_query.shape) == 1, "query vector must be 1-d")
+ _assert(
+ _query.shape[0] == self._dimensions,
+ f"query vector must have the same dimensionality as the index; index dimensionality: {self._dimensions}, "
+ f"query dimensionality: {_query.shape[0]}",
+ )
+ _assert_is_positive_uint32(k_neighbors, "k_neighbors")
+ _assert_is_nonnegative_uint32(complexity, "complexity")
+
+ if k_neighbors > complexity:
+ warnings.warn(
+ f"k_neighbors={k_neighbors} asked for, but list_size={complexity} was smaller. Increasing {complexity} to {k_neighbors}"
+ )
+ complexity = k_neighbors
+ neighbors, distances = self._index.search(query=_query, knn=k_neighbors, complexity=complexity)
+ return QueryResponse(identifiers=neighbors, distances=distances)
+
+ def batch_search(
+ self,
+ queries: VectorLikeBatch,
+ k_neighbors: int,
+ complexity: int,
+ num_threads: int,
+ ) -> QueryResponseBatch:
+ """
+ Searches the index by a batch of query vectors.
+
+ This search is parallelized and far more efficient than searching for each vector individually.
+
+ ### Parameters
+ - **queries**: 2d numpy array, with column dimensionality matching the index and row dimensionality being the
+ number of queries intended to search for in parallel. Dtype must match dtype of the index.
+ - **k_neighbors**: Number of neighbors to be returned. If query vector exists in index, it almost definitely
+ will be returned as well, so adjust your ``k_neighbors`` as appropriate. Must be > 0.
+ - **complexity**: Size of distance ordered list of candidate neighbors to use while searching. List size
+ increases accuracy at the cost of latency. Must be at least k_neighbors in size.
+ - **num_threads**: Number of threads to use when searching this index. (>= 0), 0 = num_threads in system
+ """
+ _queries = _castable_dtype_or_raise(queries, expected=self._vector_dtype)
+ _assert_2d(_queries, "queries")
+ _assert(
+ _queries.shape[1] == self._dimensions,
+ f"query vectors must have the same dimensionality as the index; index dimensionality: {self._dimensions}, "
+ f"query dimensionality: {_queries.shape[1]}",
+ )
+
+ _assert_is_positive_uint32(k_neighbors, "k_neighbors")
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+
+ if k_neighbors > complexity:
+ warnings.warn(
+ f"k_neighbors={k_neighbors} asked for, but list_size={complexity} was smaller. Increasing {complexity} to {k_neighbors}"
+ )
+ complexity = k_neighbors
+
+ num_queries, dim = queries.shape
+ neighbors, distances = self._index.batch_search(
+ queries=_queries,
+ num_queries=num_queries,
+ knn=k_neighbors,
+ complexity=complexity,
+ num_threads=num_threads,
+ )
+ return QueryResponseBatch(identifiers=neighbors, distances=distances)
+
+ def save(self, save_path: str, index_prefix: str = "ann"):
+ """
+ Saves this index to file.
+
+ ### Parameters
+ - **save_path**: The path to save these index files to.
+ - **index_prefix**: The prefix of the index files. Defaults to "ann".
+ """
+ if save_path == "":
+ raise ValueError("save_path cannot be empty")
+ if index_prefix == "":
+ raise ValueError("index_prefix cannot be empty")
+
+ index_prefix = index_prefix.format(complexity=self._complexity, graph_degree=self._graph_degree)
+ _assert_existing_directory(save_path, "save_path")
+ save_path = os.path.join(save_path, index_prefix)
+ if self._points_deleted is True:
+ warnings.warn(
+ "DynamicMemoryIndex.save() currently requires DynamicMemoryIndex.consolidate_delete() to be called "
+ "prior to save when items have been marked for deletion. This is being done automatically now, though"
+ "it will increase the time it takes to save; on large sets of data it can take a substantial amount of "
+ "time. In the future, we will implement a faster save with unconsolidated deletes, but for now this is "
+ "required."
+ )
+ self._index.consolidate_delete()
+ self._index.save(
+ save_path=save_path, compact_before_save=True
+ ) # we do not yet support uncompacted saves
+ _write_index_metadata(
+ save_path,
+ self._vector_dtype,
+ self._dap_metric,
+ self._index.num_points(),
+ self._dimensions,
+ )
+
+ def insert(self, vector: VectorLike, vector_id: VectorIdentifier):
+ """
+ Inserts a single vector into the index with the provided vector_id.
+
+ If this insertion will overrun the `max_vectors` count boundaries of this index, `consolidate_delete()` will
+ be executed automatically.
+
+ ### Parameters
+ - **vector**: The vector to insert. Note that dtype must match.
+ - **vector_id**: The vector_id to use for this vector.
+ """
+ _vector = _castable_dtype_or_raise(vector, expected=self._vector_dtype)
+ _assert(len(vector.shape) == 1, "insert vector must be 1-d")
+ _assert_is_positive_uint32(vector_id, "vector_id")
+ if self._num_vectors + 1 > self._max_vectors:
+ if self._removed_num_vectors > 0:
+ warnings.warn(f"Inserting this vector would overrun the max_vectors={self._max_vectors} specified at index "
+ f"construction. We are attempting to consolidate_delete() to make space.")
+ self.consolidate_delete()
+ else:
+ raise RuntimeError(f"Inserting this vector would overrun the max_vectors={self._max_vectors} specified "
+ f"at index construction. Unable to make space by consolidating deletions. The insert"
+ f"operation has failed.")
+ status = self._index.insert(_vector, np.uint32(vector_id))
+ if status == 0:
+ self._num_vectors += 1
+ else:
+ raise RuntimeError(
+ f"Insert was unable to complete successfully; error code returned from diskann C++ lib: {status}"
+ )
+
+
+ def batch_insert(
+ self,
+ vectors: VectorLikeBatch,
+ vector_ids: VectorIdentifierBatch,
+ num_threads: int = 0,
+ ):
+ """
+ Inserts a batch of vectors into the index with the provided vector_ids.
+
+ If this batch insertion will overrun the `max_vectors` count boundaries of this index, `consolidate_delete()`
+ will be executed automatically.
+
+ ### Parameters
+ - **vectors**: The 2d numpy array of vectors to insert.
+ - **vector_ids**: The 1d array of vector ids to use. This array must have the same number of elements as
+ the vectors array has rows. The dtype of vector_ids must be `np.uint32`
+ - **num_threads**: Number of threads to use when inserting into this index. (>= 0), 0 = num_threads in system
+ """
+ _query = _castable_dtype_or_raise(vectors, expected=self._vector_dtype)
+ _assert(len(vectors.shape) == 2, "vectors must be a 2-d array")
+ _assert(
+ vectors.shape[0] == vector_ids.shape[0],
+ "Number of vectors must be equal to number of ids",
+ )
+ _vectors = vectors.astype(dtype=self._vector_dtype, casting="safe", copy=False)
+ _vector_ids = vector_ids.astype(dtype=np.uint32, casting="safe", copy=False)
+
+ if self._num_vectors + _vector_ids.shape[0] > self._max_vectors:
+ if self._max_vectors + self._removed_num_vectors >= _vector_ids.shape[0]:
+ warnings.warn(f"Inserting these vectors, count={_vector_ids.shape[0]} would overrun the "
+ f"max_vectors={self._max_vectors} specified at index construction. We are attempting to "
+ f"consolidate_delete() to make space.")
+ self.consolidate_delete()
+ else:
+ raise RuntimeError(f"Inserting these vectors count={_vector_ids.shape[0]} would overrun the "
+ f"max_vectors={self._max_vectors} specified at index construction. Unable to make "
+ f"space by consolidating deletions. The batch insert operation has failed.")
+
+ statuses = self._index.batch_insert(
+ _vectors, _vector_ids, _vector_ids.shape[0], num_threads
+ )
+ successes = []
+ failures = []
+ for i in range(0, len(statuses)):
+ if statuses[i] == 0:
+ successes.append(i)
+ else:
+ failures.append(i)
+ self._num_vectors += len(successes)
+ if len(failures) == 0:
+ return
+ failed_ids = vector_ids[failures]
+ raise RuntimeError(
+ f"During batch insert, the following vector_ids were unable to be inserted into the index: {failed_ids}. "
+ f"{len(successes)} were successfully inserted"
+ )
+
+
+ def mark_deleted(self, vector_id: VectorIdentifier):
+ """
+ Mark vector for deletion. This is a soft delete that won't return the vector id in any results, but does not
+ remove it from the underlying index files or memory structure. To execute a hard delete, call this method and
+ then call the much more expensive `consolidate_delete` method on this index.
+ ### Parameters
+ - **vector_id**: The vector id to delete. Must be a uint32.
+ """
+ _assert_is_positive_uint32(vector_id, "vector_id")
+ self._points_deleted = True
+ self._removed_num_vectors += 1
+ # we do not decrement self._num_vectors until consolidate_delete
+ self._index.mark_deleted(np.uint32(vector_id))
+
+ def consolidate_delete(self):
+ """
+ This method actually restructures the DiskANN index to remove the items that have been marked for deletion.
+ """
+ self._index.consolidate_delete()
+ self._points_deleted = False
+ self._num_vectors -= self._removed_num_vectors
+ self._removed_num_vectors = 0
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_files.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_files.py
new file mode 100644
index 0000000..7740c34
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_files.py
@@ -0,0 +1,122 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import warnings
+from typing import BinaryIO, Literal, NamedTuple
+
+import numpy as np
+import numpy.typing as npt
+
+from . import VectorDType, VectorIdentifierBatch, VectorLikeBatch
+from ._common import _assert, _assert_2d, _assert_dtype, _assert_existing_file
+
+
+class Metadata(NamedTuple):
+ """DiskANN binary vector files contain a small stanza containing some metadata about them."""
+
+ num_vectors: int
+ """ The number of vectors in the file. """
+ dimensions: int
+ """ The dimensionality of the vectors in the file. """
+
+
+def vectors_metadata_from_file(vector_file: str) -> Metadata:
+ """
+ Read the metadata from a DiskANN binary vector file.
+ ### Parameters
+ - **vector_file**: The path to the vector file to read the metadata from.
+
+ ### Returns
+ `diskannpy.Metadata`
+ """
+ _assert_existing_file(vector_file, "vector_file")
+ points, dims = np.fromfile(file=vector_file, dtype=np.int32, count=2)
+ return Metadata(points, dims)
+
+
+def _write_bin(data: np.ndarray, file_handler: BinaryIO):
+ if len(data.shape) == 1:
+ _ = file_handler.write(np.array([data.shape[0], 1], dtype=np.int32).tobytes())
+ else:
+ _ = file_handler.write(np.array(data.shape, dtype=np.int32).tobytes())
+ _ = file_handler.write(data.tobytes())
+
+
+def vectors_to_file(vector_file: str, vectors: VectorLikeBatch) -> None:
+ """
+ Utility function that writes a DiskANN binary vector formatted file to the location of your choosing.
+
+ ### Parameters
+ - **vector_file**: The path to the vector file to write the vectors to.
+ - **vectors**: A 2d array of dtype `numpy.float32`, `numpy.uint8`, or `numpy.int8`
+ """
+ _assert_dtype(vectors.dtype)
+ _assert_2d(vectors, "vectors")
+ with open(vector_file, "wb") as fh:
+ _write_bin(vectors, fh)
+
+
+def vectors_from_file(
+ vector_file: str,
+ dtype: VectorDType,
+ use_memmap: bool = False,
+ mode: Literal["r", "r+"] = "r"
+) -> npt.NDArray[VectorDType]:
+ """
+ Read vectors from a DiskANN binary vector file.
+
+ ### Parameters
+ - **vector_file**: The path to the vector file to read the vectors from.
+ - **dtype**: The data type of the vectors in the file. Ensure you match the data types exactly
+ - **use_memmap**: If True, return a np.memmap, else a standard np.ndarray will be returned
+ - **mode**: Read-only (r) or read-write (r+) (memmap only). Unlike np.memmap, default is read-only (r)
+
+ ### Returns
+ `numpy.typing.NDArray[dtype] | numpy.memmap`
+ """
+ assert mode in ["r", "r+"]
+ points, dims = vectors_metadata_from_file(vector_file)
+ if not use_memmap:
+ return np.fromfile(file=vector_file, dtype=dtype, offset=8).reshape(points, dims)
+ else:
+ return np.memmap(vector_file, dtype=dtype, mode=mode, offset=8, shape=(points, dims), order='C')
+
+
+def tags_to_file(tags_file: str, tags: VectorIdentifierBatch) -> None:
+ """
+ Write tags to a DiskANN binary tag file.
+
+ ### Parameters
+ - **tags_file**: The path to the tag file to write the tags to.
+ - **tags**: A 1d array of dtype `numpy.uint32` containing the tags to write. If you have a 2d array of tags with
+ one column, you can pass it here and it will be reshaped and copied to a new array. It is more efficient for you
+ to reshape on your own without copying it first, as it should be a constant time operation vs. linear time
+
+ """
+ _assert(np.can_cast(tags.dtype, np.uint32), "valid tags must be uint32")
+ _assert(
+ len(tags.shape) == 1 or tags.shape[1] == 1,
+ "tags must be 1d or 2d with 1 column",
+ )
+ if len(tags.shape) == 2:
+ warnings.warn(
+ "Tags in 2d with one column will be reshaped and copied to a new array. "
+ "It is more efficient for you to reshape without copying first."
+ )
+ tags = tags.reshape(tags.shape[0], copy=True)
+ with open(tags_file, "wb") as fh:
+ _write_bin(tags.astype(np.uint32), fh)
+
+
+def tags_from_file(tags_file: str) -> VectorIdentifierBatch:
+ """
+ Read tags from a DiskANN binary tag file and return them as a 1d array of dtype `numpy.uint32`.
+
+ ### Parameters
+ - **tags_file**: The path to the tag file to read the tags from.
+ """
+ _assert_existing_file(tags_file, "tags_file")
+ points, dims = vectors_metadata_from_file(
+ tags_file
+ ) # tag files contain the same metadata stanza
+ return np.fromfile(file=tags_file, dtype=np.uint32, offset=8).reshape(points)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_static_disk_index.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_static_disk_index.py
new file mode 100644
index 0000000..47af362
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_static_disk_index.py
@@ -0,0 +1,244 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import os
+import warnings
+from typing import Optional
+
+import numpy as np
+
+from . import (
+ DistanceMetric,
+ QueryResponse,
+ QueryResponseBatch,
+ VectorDType,
+ VectorLike,
+ VectorLikeBatch,
+)
+from . import _diskannpy as _native_dap
+from ._common import (
+ _assert,
+ _assert_2d,
+ _assert_is_nonnegative_uint32,
+ _assert_is_positive_uint32,
+ _castable_dtype_or_raise,
+ _ensure_index_metadata,
+ _valid_index_prefix,
+ _valid_metric,
+)
+
+__ALL__ = ["StaticDiskIndex"]
+
+
+class StaticDiskIndex:
+ """
+ A StaticDiskIndex is a disk-backed index that is not mutable.
+ """
+
+ def __init__(
+ self,
+ index_directory: str,
+ num_threads: int,
+ num_nodes_to_cache: int,
+ cache_mechanism: int = 1,
+ distance_metric: Optional[DistanceMetric] = None,
+ vector_dtype: Optional[VectorDType] = None,
+ dimensions: Optional[int] = None,
+ index_prefix: str = "ann",
+ pq_prefix: str = "",
+ partition_prefix: str = "",
+ ):
+ """
+ ### Parameters
+ - **index_directory**: The directory containing the index files. This directory must contain the following
+ files:
+ - `{index_prefix}_sample_data.bin`
+ - `{index_prefix}_mem.index.data`
+ - `{index_prefix}_pq_compressed.bin`
+ - `{index_prefix}_pq_pivots.bin`
+ - `{index_prefix}_sample_ids.bin`
+ - `{index_prefix}_disk.index`
+
+ It may also include the following optional files:
+ - `{index_prefix}_vectors.bin`: Optional. `diskannpy` builder functions may create this file in the
+ `index_directory` if the index was created from a numpy array
+ - `{index_prefix}_metadata.bin`: Optional. `diskannpy` builder functions create this file to store metadata
+ about the index, such as vector dtype, distance metric, number of vectors and vector dimensionality.
+ If an index is built from the `diskann` cli tools, this file will not exist.
+ - **num_threads**: Number of threads to use when searching this index. (>= 0), 0 = num_threads in system
+ - **num_nodes_to_cache**: Number of nodes to cache in memory (> -1)
+ - **cache_mechanism**: 1 -> use the generated sample_data.bin file for
+ the index to initialize a set of cached nodes, up to `num_nodes_to_cache`, 2 -> ready the cache for up to
+ `num_nodes_to_cache`, but do not initialize it with any nodes. Any other value disables node caching.
+ - **distance_metric**: A `str`, strictly one of {"l2", "mips", "cosine"}. `l2` and `cosine` are supported for all 3
+ vector dtypes, but `mips` is only available for single precision floats. Default is `None`. **This
+ value is only used if a `{index_prefix}_metadata.bin` file does not exist.** If it does not exist,
+ you are required to provide it.
+ - **vector_dtype**: The vector dtype this index has been built with. **This value is only used if a
+ `{index_prefix}_metadata.bin` file does not exist.** If it does not exist, you are required to provide it.
+ - **dimensions**: The vector dimensionality of this index. All new vectors inserted must be the same
+ dimensionality. **This value is only used if a `{index_prefix}_metadata.bin` file does not exist.** If it
+ does not exist, you are required to provide it.
+ - **index_prefix**: The prefix of the index files. Defaults to "ann".
+ """
+ index_prefix_path = _valid_index_prefix(index_directory, index_prefix)
+ vector_dtype, metric, _, _ = _ensure_index_metadata(
+ index_prefix_path,
+ vector_dtype,
+ distance_metric,
+ 1, # it doesn't matter because we don't need it in this context anyway
+ dimensions,
+ )
+ dap_metric = _valid_metric(metric)
+
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+ _assert_is_nonnegative_uint32(num_nodes_to_cache, "num_nodes_to_cache")
+
+ self._vector_dtype = vector_dtype
+ if vector_dtype == np.uint8:
+ _index = _native_dap.StaticDiskUInt8Index
+ elif vector_dtype == np.int8:
+ _index = _native_dap.StaticDiskInt8Index
+ else:
+ _index = _native_dap.StaticDiskFloatIndex
+ self._index = _index(
+ distance_metric=dap_metric,
+ index_path_prefix=index_prefix_path,
+ num_threads=num_threads,
+ num_nodes_to_cache=num_nodes_to_cache,
+ cache_mechanism=cache_mechanism,
+ pq_prefix=pq_prefix,
+ partition_prefix=partition_prefix,
+ )
+ print("After index init")
+
+ def search(
+ self,
+ query: VectorLike,
+ k_neighbors: int,
+ complexity: int,
+ beam_width: int = 2,
+ USE_DEFERRED_FETCH: bool = False,
+ skip_search_reorder: bool = False,
+ recompute_beighbor_embeddings: bool = False,
+ dedup_node_dis: bool = False,
+ prune_ratio: float = 0,
+ batch_recompute: bool = False,
+ global_pruning: bool = False,
+ ) -> QueryResponse:
+ """
+ Searches the index by a single query vector.
+
+ ### Parameters
+ - **query**: 1d numpy array of the same dimensionality and dtype of the index.
+ - **k_neighbors**: Number of neighbors to be returned. If query vector exists in index, it almost definitely
+ will be returned as well, so adjust your ``k_neighbors`` as appropriate. Must be > 0.
+ - **complexity**: Size of distance ordered list of candidate neighbors to use while searching. List size
+ increases accuracy at the cost of latency. Must be at least k_neighbors in size.
+ - **beam_width**: The beamwidth to be used for search. This is the maximum number of IO requests each query
+ will issue per iteration of search code. Larger beamwidth will result in fewer IO round-trips per query,
+ but might result in slightly higher total number of IO requests to SSD per query. For the highest query
+ throughput with a fixed SSD IOps rating, use W=1. For best latency, use W=4,8 or higher complexity search.
+ Specifying 0 will optimize the beamwidth depending on the number of threads performing search, but will
+ involve some tuning overhead.
+ - **skip_search_reorder**: Whether to skip search reorder for diskann search.
+ - **recompute_beighbor_embeddings**: Whether to recompute the neighbor embeddings.
+ - **dedup_node_dis**: Whether to dedup node distances.
+ - **batch_recompute**: Whether to batch recompute.
+ """
+ _query = _castable_dtype_or_raise(query, expected=self._vector_dtype)
+ _assert(len(_query.shape) == 1, "query vector must be 1-d")
+ _assert_is_positive_uint32(k_neighbors, "k_neighbors")
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_positive_uint32(beam_width, "beam_width")
+
+ if k_neighbors > complexity:
+ warnings.warn(
+ f"{k_neighbors=} asked for, but {complexity=} was smaller. Increasing {complexity} to {k_neighbors}"
+ )
+ complexity = k_neighbors
+
+ neighbors, distances = self._index.search(
+ query=_query,
+ knn=k_neighbors,
+ complexity=complexity,
+ beam_width=beam_width,
+ USE_DEFERRED_FETCH=USE_DEFERRED_FETCH,
+ skip_search_reorder=skip_search_reorder,
+ recompute_beighbor_embeddings=recompute_beighbor_embeddings,
+ dedup_node_dis=dedup_node_dis,
+ prune_ratio=prune_ratio,
+ batch_recompute=batch_recompute,
+ global_pruning=global_pruning,
+ )
+ return QueryResponse(identifiers=neighbors, distances=distances)
+
+ def batch_search(
+ self,
+ queries: VectorLikeBatch,
+ k_neighbors: int,
+ complexity: int,
+ num_threads: int,
+ beam_width: int = 2,
+ USE_DEFERRED_FETCH: bool = False,
+ skip_search_reorder: bool = False,
+ recompute_beighbor_embeddings: bool = False,
+ dedup_node_dis: bool = False,
+ prune_ratio: float = 0,
+ batch_recompute: bool = False,
+ global_pruning: bool = False,
+ ) -> QueryResponseBatch:
+ """
+ Searches the index by a batch of query vectors.
+
+ This search is parallelized and far more efficient than searching for each vector individually.
+
+ ### Parameters
+ - **queries**: 2d numpy array, with column dimensionality matching the index and row dimensionality being the
+ number of queries intended to search for in parallel. Dtype must match dtype of the index.
+ - **k_neighbors**: Number of neighbors to be returned. If query vector exists in index, it almost definitely
+ will be returned as well, so adjust your ``k_neighbors`` as appropriate. Must be > 0.
+ - **complexity**: Size of distance ordered list of candidate neighbors to use while searching. List size
+ increases accuracy at the cost of latency. Must be at least k_neighbors in size.
+ - **num_threads**: Number of threads to use when searching this index. (>= 0), 0 = num_threads in system
+ - **beam_width**: The beamwidth to be used for search. This is the maximum number of IO requests each query
+ will issue per iteration of search code. Larger beamwidth will result in fewer IO round-trips per query,
+ but might result in slightly higher total number of IO requests to SSD per query. For the highest query
+ throughput with a fixed SSD IOps rating, use W=1. For best latency, use W=4,8 or higher complexity search.
+ Specifying 0 will optimize the beamwidth depending on the number of threads performing search, but will
+ involve some tuning overhead.
+ - **skip_search_reorder**: Whether to skip search reorder for diskann search.
+ """
+ _queries = _castable_dtype_or_raise(queries, expected=self._vector_dtype)
+ _assert_2d(_queries, "queries")
+ _assert_is_positive_uint32(k_neighbors, "k_neighbors")
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+ _assert_is_positive_uint32(beam_width, "beam_width")
+
+ if k_neighbors > complexity:
+ warnings.warn(
+ f"{k_neighbors=} asked for, but {complexity=} was smaller. Increasing {complexity} to {k_neighbors}"
+ )
+ complexity = k_neighbors
+
+ num_queries, dim = _queries.shape
+ print(
+ f"USE_DEFERRED_FETCH={USE_DEFERRED_FETCH} skip_search_reorder={skip_search_reorder} recompute_beighbor_embeddings={recompute_beighbor_embeddings}, dedup_node_dis={dedup_node_dis}"
+ )
+ neighbors, distances = self._index.batch_search(
+ queries=_queries,
+ num_queries=num_queries,
+ knn=k_neighbors,
+ complexity=complexity,
+ beam_width=beam_width,
+ num_threads=num_threads,
+ USE_DEFERRED_FETCH=USE_DEFERRED_FETCH,
+ skip_search_reorder=skip_search_reorder,
+ recompute_beighbor_embeddings=recompute_beighbor_embeddings,
+ dedup_node_dis=dedup_node_dis,
+ prune_ratio=prune_ratio,
+ batch_recompute=batch_recompute,
+ global_pruning=global_pruning,
+ )
+ return QueryResponseBatch(identifiers=neighbors, distances=distances)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/_static_memory_index.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_static_memory_index.py
new file mode 100644
index 0000000..1380360
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/_static_memory_index.py
@@ -0,0 +1,262 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import json
+import os
+import warnings
+from typing import Optional
+
+import numpy as np
+
+from . import (
+ DistanceMetric,
+ QueryResponse,
+ QueryResponseBatch,
+ VectorDType,
+ VectorLike,
+ VectorLikeBatch,
+)
+from . import _diskannpy as _native_dap
+from ._common import (
+ _assert,
+ _assert_is_nonnegative_uint32,
+ _assert_is_positive_uint32,
+ _castable_dtype_or_raise,
+ _ensure_index_metadata,
+ _valid_index_prefix,
+ _valid_metric,
+)
+
+__ALL__ = ["StaticMemoryIndex"]
+
+
+class StaticMemoryIndex:
+ """
+ A StaticMemoryIndex is an immutable in-memory DiskANN index.
+ """
+
+ def __init__(
+ self,
+ index_directory: str,
+ num_threads: int,
+ initial_search_complexity: int,
+ index_prefix: str = "ann",
+ distance_metric: Optional[DistanceMetric] = None,
+ vector_dtype: Optional[VectorDType] = None,
+ dimensions: Optional[int] = None,
+ enable_filters: bool = False,
+ ):
+ """
+ ### Parameters
+ - **index_directory**: The directory containing the index files. This directory must contain the following
+ files:
+ - `{index_prefix}.data`
+ - `{index_prefix}`
+
+
+ It may also include the following optional files:
+ - `{index_prefix}_vectors.bin`: Optional. `diskannpy` builder functions may create this file in the
+ `index_directory` if the index was created from a numpy array
+ - `{index_prefix}_metadata.bin`: Optional. `diskannpy` builder functions create this file to store metadata
+ about the index, such as vector dtype, distance metric, number of vectors and vector dimensionality.
+ If an index is built from the `diskann` cli tools, this file will not exist.
+ - **num_threads**: Number of threads to use when searching this index. (>= 0), 0 = num_threads in system
+ - **initial_search_complexity**: Should be set to the most common `complexity` expected to be used during the
+ life of this `diskannpy.DynamicMemoryIndex` object. The working scratch memory allocated is based off of
+ `initial_search_complexity` * `search_threads`. Note that it may be resized if a `search` or `batch_search`
+ operation requests a space larger than can be accommodated by these values.
+ - **index_prefix**: The prefix of the index files. Defaults to "ann".
+ - **distance_metric**: A `str`, strictly one of {"l2", "mips", "cosine"}. `l2` and `cosine` are supported for all 3
+ vector dtypes, but `mips` is only available for single precision floats. Default is `None`. **This
+ value is only used if a `{index_prefix}_metadata.bin` file does not exist.** If it does not exist,
+ you are required to provide it.
+ - **vector_dtype**: The vector dtype this index has been built with. **This value is only used if a
+ `{index_prefix}_metadata.bin` file does not exist.** If it does not exist, you are required to provide it.
+ - **dimensions**: The vector dimensionality of this index. All new vectors inserted must be the same
+ dimensionality. **This value is only used if a `{index_prefix}_metadata.bin` file does not exist.** If it
+ does not exist, you are required to provide it.
+ - **enable_filters**: Indexes built with filters can also be used for filtered search.
+ """
+ index_prefix_path = _valid_index_prefix(index_directory, index_prefix)
+ self._labels_map = {}
+ self._labels_metadata = {}
+ if enable_filters:
+ try:
+ with open(f"{index_prefix_path}_labels_map.txt", "r") as labels_map_if:
+ for line in labels_map_if:
+ (key, val) = line.split("\t")
+ self._labels_map[key] = int(val)
+ with open(
+ f"{index_prefix_path}_label_metadata.json", "r"
+ ) as labels_metadata_if:
+ self._labels_metadata = json.load(labels_metadata_if)
+ except: # noqa: E722
+ # exceptions are basically presumed to be either file not found or file not formatted correctly
+ raise RuntimeException("Filter labels file was unable to be processed.")
+ vector_dtype, metric, num_points, dims = _ensure_index_metadata(
+ index_prefix_path,
+ vector_dtype,
+ distance_metric,
+ 1, # it doesn't matter because we don't need it in this context anyway
+ dimensions,
+ )
+ dap_metric = _valid_metric(metric)
+
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+ _assert_is_positive_uint32(
+ initial_search_complexity, "initial_search_complexity"
+ )
+
+ self._vector_dtype = vector_dtype
+ self._dimensions = dims
+
+ if vector_dtype == np.uint8:
+ _index = _native_dap.StaticMemoryUInt8Index
+ elif vector_dtype == np.int8:
+ _index = _native_dap.StaticMemoryInt8Index
+ else:
+ _index = _native_dap.StaticMemoryFloatIndex
+
+ self._index = _index(
+ distance_metric=dap_metric,
+ num_points=num_points,
+ dimensions=dims,
+ index_path=index_prefix_path,
+ num_threads=num_threads,
+ initial_search_complexity=initial_search_complexity,
+ )
+
+ def search(
+ self,
+ query: VectorLike,
+ k_neighbors: int,
+ complexity: int,
+ filter_label: str = "",
+ USE_DEFERRED_FETCH: bool = False,
+ skip_search_reorder: bool = False,
+ recompute_beighbor_embeddings: bool = False,
+ dedup_node_dis: bool = False,
+ prune_ratio: float = 0,
+ batch_recompute: bool = False,
+ global_pruning: bool = False,
+ ) -> QueryResponse:
+ """
+ Searches the index by a single query vector.
+
+ ### Parameters
+ - **query**: 1d numpy array of the same dimensionality and dtype of the index.
+ - **k_neighbors**: Number of neighbors to be returned. If query vector exists in index, it almost definitely
+ will be returned as well, so adjust your ``k_neighbors`` as appropriate. Must be > 0.
+ - **complexity**: Size of distance ordered list of candidate neighbors to use while searching. List size
+ increases accuracy at the cost of latency. Must be at least k_neighbors in size.
+ """
+ if filter_label != "":
+ if len(self._labels_map) == 0:
+ raise ValueError(
+ f"A filter label of {filter_label} was provided, but this class was not initialized with filters "
+ "enabled, e.g. StaticDiskMemory(..., enable_filters=True)"
+ )
+ if filter_label not in self._labels_map:
+ raise ValueError(
+ f"A filter label of {filter_label} was provided, but the external(str)->internal(np.uint32) labels map "
+ f"does not include that label."
+ )
+ k_neighbors = min(k_neighbors, self._labels_metadata[filter_label])
+ _query = _castable_dtype_or_raise(query, expected=self._vector_dtype)
+ _assert(len(_query.shape) == 1, "query vector must be 1-d")
+ _assert(
+ _query.shape[0] == self._dimensions,
+ f"query vector must have the same dimensionality as the index; index dimensionality: {self._dimensions}, "
+ f"query dimensionality: {_query.shape[0]}",
+ )
+ _assert_is_positive_uint32(k_neighbors, "k_neighbors")
+ _assert_is_nonnegative_uint32(complexity, "complexity")
+
+ if k_neighbors > complexity:
+ warnings.warn(
+ f"k_neighbors={k_neighbors} asked for, but list_size={complexity} was smaller. Increasing {complexity} to {k_neighbors}"
+ )
+ complexity = k_neighbors
+
+ if filter_label == "":
+ neighbors, distances = self._index.search(
+ query=_query,
+ knn=k_neighbors,
+ complexity=complexity,
+ USE_DEFERRED_FETCH=USE_DEFERRED_FETCH,
+ skip_search_reorder=skip_search_reorder,
+ recompute_beighbor_embeddings=recompute_beighbor_embeddings,
+ dedup_node_dis=dedup_node_dis,
+ prune_ratio=prune_ratio,
+ batch_recompute=batch_recompute,
+ global_pruning=global_pruning,
+ )
+ else:
+ filter = self._labels_map[filter_label]
+ neighbors, distances = self._index.search_with_filter(
+ query=query, knn=k_neighbors, complexity=complexity, filter=filter
+ )
+ return QueryResponse(identifiers=neighbors, distances=distances)
+
+ def batch_search(
+ self,
+ queries: VectorLikeBatch,
+ k_neighbors: int,
+ complexity: int,
+ num_threads: int,
+ USE_DEFERRED_FETCH: bool = False,
+ skip_search_reorder: bool = False,
+ recompute_beighbor_embeddings: bool = False,
+ dedup_node_dis: bool = False,
+ prune_ratio: float = 0,
+ batch_recompute: bool = False,
+ global_pruning: bool = False,
+ ) -> QueryResponseBatch:
+ """
+ Searches the index by a batch of query vectors.
+
+ This search is parallelized and far more efficient than searching for each vector individually.
+
+ ### Parameters
+ - **queries**: 2d numpy array, with column dimensionality matching the index and row dimensionality being the
+ number of queries intended to search for in parallel. Dtype must match dtype of the index.
+ - **k_neighbors**: Number of neighbors to be returned. If query vector exists in index, it almost definitely
+ will be returned as well, so adjust your ``k_neighbors`` as appropriate. Must be > 0.
+ - **complexity**: Size of distance ordered list of candidate neighbors to use while searching. List size
+ increases accuracy at the cost of latency. Must be at least k_neighbors in size.
+ - **num_threads**: Number of threads to use when searching this index. (>= 0), 0 = num_threads in system
+ """
+
+ _queries = _castable_dtype_or_raise(queries, expected=self._vector_dtype)
+ _assert(len(_queries.shape) == 2, "queries must must be 2-d np array")
+ _assert(
+ _queries.shape[1] == self._dimensions,
+ f"query vectors must have the same dimensionality as the index; index dimensionality: {self._dimensions}, "
+ f"query dimensionality: {_queries.shape[1]}",
+ )
+ _assert_is_positive_uint32(k_neighbors, "k_neighbors")
+ _assert_is_positive_uint32(complexity, "complexity")
+ _assert_is_nonnegative_uint32(num_threads, "num_threads")
+
+ if k_neighbors > complexity:
+ warnings.warn(
+ f"k_neighbors={k_neighbors} asked for, but list_size={complexity} was smaller. Increasing {complexity} to {k_neighbors}"
+ )
+ complexity = k_neighbors
+
+ num_queries, dim = _queries.shape
+ neighbors, distances = self._index.batch_search(
+ queries=_queries,
+ num_queries=num_queries,
+ knn=k_neighbors,
+ complexity=complexity,
+ num_threads=num_threads,
+ USE_DEFERRED_FETCH=USE_DEFERRED_FETCH,
+ skip_search_reorder=skip_search_reorder,
+ recompute_beighbor_embeddings=recompute_beighbor_embeddings,
+ dedup_node_dis=dedup_node_dis,
+ prune_ratio=prune_ratio,
+ batch_recompute=batch_recompute,
+ global_pruning=global_pruning,
+ )
+ return QueryResponseBatch(identifiers=neighbors, distances=distances)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/builder.cpp b/packages/leann-backend-diskann/third_party/DiskANN/python/src/builder.cpp
new file mode 100644
index 0000000..2b91eac
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/builder.cpp
@@ -0,0 +1,136 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "builder.h"
+#include "common.h"
+#include "disk_utils.h"
+#include "index.h"
+#include "parameters.h"
+
+namespace diskannpy
+{
+template <typename DT>
+void build_disk_index(const diskann::Metric metric, const std::string &data_file_path,
+ const std::string &index_prefix_path, const uint32_t complexity, const uint32_t graph_degree,
+ const double final_index_ram_limit, const double indexing_ram_budget, const uint32_t num_threads,
+ const uint32_t pq_disk_bytes, const std::string &codebook_prefix)
+{
+ std::string params = std::to_string(graph_degree) + " " + std::to_string(complexity) + " " +
+ std::to_string(final_index_ram_limit) + " " + std::to_string(indexing_ram_budget) + " " +
+ std::to_string(num_threads);
+ if (pq_disk_bytes > 0)
+ params = params + " " + std::to_string(pq_disk_bytes);
+ if (!codebook_prefix.empty())
+ params = params + " " + codebook_prefix;
+ diskann::build_disk_index<DT>(data_file_path.c_str(), index_prefix_path.c_str(), params.c_str(), metric, false,
+ codebook_prefix);
+}
+
+template void build_disk_index<float>(diskann::Metric, const std::string &, const std::string &, uint32_t, uint32_t,
+ double, double, uint32_t, uint32_t, const std::string &);
+
+template void build_disk_index<uint8_t>(diskann::Metric, const std::string &, const std::string &, uint32_t, uint32_t,
+ double, double, uint32_t, uint32_t, const std::string &);
+template void build_disk_index<int8_t>(diskann::Metric, const std::string &, const std::string &, uint32_t, uint32_t,
+ double, double, uint32_t, uint32_t, const std::string &);
+
+template <typename T, typename TagT, typename LabelT>
+std::string prepare_filtered_label_map(diskann::Index<T, TagT, LabelT> &index, const std::string &index_output_path,
+ const std::string &filter_labels_file, const std::string &universal_label)
+{
+ std::string labels_file_to_use = index_output_path + "_label_formatted.txt";
+ std::string mem_labels_int_map_file = index_output_path + "_labels_map.txt";
+ convert_labels_string_to_int(filter_labels_file, labels_file_to_use, mem_labels_int_map_file, universal_label);
+ if (!universal_label.empty())
+ {
+ uint32_t unv_label_as_num = 0;
+ index.set_universal_label(unv_label_as_num);
+ }
+ return labels_file_to_use;
+}
+
+template std::string prepare_filtered_label_map<float>(diskann::Index<float, uint32_t, uint32_t> &, const std::string &,
+ const std::string &, const std::string &);
+
+template std::string prepare_filtered_label_map<int8_t>(diskann::Index<int8_t, uint32_t, uint32_t> &,
+ const std::string &, const std::string &, const std::string &);
+
+template std::string prepare_filtered_label_map<uint8_t>(diskann::Index<uint8_t, uint32_t, uint32_t> &,
+ const std::string &, const std::string &, const std::string &);
+
+template <typename T, typename TagT, typename LabelT>
+void build_memory_index(const diskann::Metric metric, const std::string &vector_bin_path,
+ const std::string &index_output_path, const uint32_t graph_degree, const uint32_t complexity,
+ const float alpha, const uint32_t num_threads, const bool use_pq_build,
+ const size_t num_pq_bytes, const bool use_opq, const bool use_tags,
+ const std::string &filter_labels_file, const std::string &universal_label,
+ const uint32_t filter_complexity)
+{
+ diskann::IndexWriteParameters index_build_params = diskann::IndexWriteParametersBuilder(complexity, graph_degree)
+ .with_filter_list_size(filter_complexity)
+ .with_alpha(alpha)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+ diskann::IndexSearchParams index_search_params =
+ diskann::IndexSearchParams(index_build_params.search_list_size, num_threads);
+ size_t data_num, data_dim;
+ diskann::get_bin_metadata(vector_bin_path, data_num, data_dim);
+
+ diskann::Index<T, TagT, LabelT> index(metric, data_dim, data_num,
+ std::make_shared<diskann::IndexWriteParameters>(index_build_params),
+ std::make_shared<diskann::IndexSearchParams>(index_search_params), 0,
+ use_tags, use_tags, false, use_pq_build, num_pq_bytes, use_opq);
+
+ if (use_tags)
+ {
+ const std::string tags_file = index_output_path + ".tags";
+ if (!file_exists(tags_file))
+ {
+ throw std::runtime_error("tags file not found at expected path: " + tags_file);
+ }
+ TagT *tags_data;
+ size_t tag_dims = 1;
+ diskann::load_bin(tags_file, tags_data, data_num, tag_dims);
+ std::vector<TagT> tags(tags_data, tags_data + data_num);
+ if (filter_labels_file.empty())
+ {
+ index.build(vector_bin_path.c_str(), data_num, tags);
+ }
+ else
+ {
+ auto labels_file = prepare_filtered_label_map<T, TagT, LabelT>(index, index_output_path, filter_labels_file,
+ universal_label);
+ index.build_filtered_index(vector_bin_path.c_str(), labels_file, data_num, tags);
+ }
+ }
+ else
+ {
+ if (filter_labels_file.empty())
+ {
+ index.build(vector_bin_path.c_str(), data_num);
+ }
+ else
+ {
+ auto labels_file = prepare_filtered_label_map<T, TagT, LabelT>(index, index_output_path, filter_labels_file,
+ universal_label);
+ index.build_filtered_index(vector_bin_path.c_str(), labels_file, data_num);
+ }
+ }
+
+ index.save(index_output_path.c_str());
+}
+
+template void build_memory_index<float>(diskann::Metric, const std::string &, const std::string &, uint32_t, uint32_t,
+ float, uint32_t, bool, size_t, bool, bool, const std::string &,
+ const std::string &, uint32_t);
+
+template void build_memory_index<int8_t>(diskann::Metric, const std::string &, const std::string &, uint32_t, uint32_t,
+ float, uint32_t, bool, size_t, bool, bool, const std::string &,
+ const std::string &, uint32_t);
+
+template void build_memory_index<uint8_t>(diskann::Metric, const std::string &, const std::string &, uint32_t, uint32_t,
+ float, uint32_t, bool, size_t, bool, bool, const std::string &,
+ const std::string &, uint32_t);
+
+} // namespace diskannpy
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/defaults.py b/packages/leann-backend-diskann/third_party/DiskANN/python/src/defaults.py
new file mode 100644
index 0000000..4e22983
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/defaults.py
@@ -0,0 +1,71 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+"""
+# Parameter Defaults
+These parameter defaults are re-exported from the C++ extension module, and used to keep the pythonic wrapper in sync with the C++.
+"""
+from ._diskannpy import defaults as _defaults
+
+ALPHA = _defaults.ALPHA
+"""
+Note that, as ALPHA is a `float32` (single precision float) in C++, when converted into Python it becomes a
+`float64` (double precision float). The actual value is 1.2f. The alpha parameter (>=1) is used to control the nature
+and number of points that are added to the graph. A higher alpha value (e.g., 1.4) will result in fewer hops (and IOs)
+to convergence, but probably more distance comparisons compared to a lower alpha value.
+"""
+NUM_THREADS = _defaults.NUM_THREADS
+""" Number of threads to use. `0` will use all available detected logical processors """
+MAX_OCCLUSION_SIZE = _defaults.MAX_OCCLUSION_SIZE
+"""
+The maximum number of points that can be occluded by a single point. This is used to prevent a single point from
+dominating the graph structure. If a point has more than `max_occlusion_size` neighbors closer to it than the current
+point, it will not be added to the graph. This is a tradeoff between index build time and search quality.
+"""
+FILTER_COMPLEXITY = _defaults.FILTER_COMPLEXITY
+"""
+Complexity (a.k.a. `L`) references the size of the list we store candidate approximate neighbors in while doing a
+filtered search. This value must be larger than `k_neighbors`, and larger values tend toward higher recall in the
+resultant ANN search at the cost of more time.
+"""
+NUM_FROZEN_POINTS_STATIC = _defaults.NUM_FROZEN_POINTS_STATIC
+""" Number of points frozen by default in a StaticMemoryIndex """
+NUM_FROZEN_POINTS_DYNAMIC = _defaults.NUM_FROZEN_POINTS_DYNAMIC
+""" Number of points frozen by default in a DynamicMemoryIndex """
+SATURATE_GRAPH = _defaults.SATURATE_GRAPH
+""" Whether to saturate the graph or not. Default is `True` """
+GRAPH_DEGREE = _defaults.GRAPH_DEGREE
+"""
+Graph degree (a.k.a. `R`) is the maximum degree allowed for a node in the index's graph structure. This degree will be
+pruned throughout the course of the index build, but it will never grow beyond this value. Higher R values require
+longer index build times, but may result in an index showing excellent recall and latency characteristics.
+"""
+COMPLEXITY = _defaults.COMPLEXITY
+"""
+Complexity (a.k.a `L`) references the size of the list we store candidate approximate neighbors in while doing build
+or search tasks. It's used during index build as part of the index optimization processes. It's used in index search
+classes both to help mitigate poor latencies during cold start, as well as on subsequent queries to conduct the search.
+Large values will likely increase latency but also may improve recall, and tuning these values for your particular
+index is certainly a reasonable choice.
+"""
+PQ_DISK_BYTES = _defaults.PQ_DISK_BYTES
+"""
+Use `0` to store uncompressed data on SSD. This allows the index to asymptote to 100% recall. If your vectors are
+too large to store in SSD, this parameter provides the option to compress the vectors using PQ for storing on SSD.
+This will trade off recall. You would also want this to be greater than the number of bytes used for the PQ
+compressed data stored in-memory. Default is `0`.
+"""
+USE_PQ_BUILD = _defaults.USE_PQ_BUILD
+"""
+ Whether to use product quantization in the index building process. Product quantization is an approximation
+technique that can vastly speed up vector computations and comparisons in a spatial neighborhood, but it is still an
+approximation technique. It should be preferred when index creation times take longer than you can afford for your
+use case.
+"""
+NUM_PQ_BYTES = _defaults.NUM_PQ_BYTES
+"""
+The number of product quantization bytes to use. More bytes requires more resources in both memory and time, but is
+like to result in better approximations.
+"""
+USE_OPQ = _defaults.USE_OPQ
+""" Whether to use Optimized Product Quantization or not. """
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/dynamic_memory_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/python/src/dynamic_memory_index.cpp
new file mode 100644
index 0000000..d05e54d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/dynamic_memory_index.cpp
@@ -0,0 +1,167 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "parameters.h"
+#include "dynamic_memory_index.h"
+
+#include "pybind11/numpy.h"
+
+namespace diskannpy
+{
+
+diskann::IndexWriteParameters dynamic_index_write_parameters(const uint32_t complexity, const uint32_t graph_degree,
+ const bool saturate_graph,
+ const uint32_t max_occlusion_size, const float alpha,
+ const uint32_t num_threads,
+ const uint32_t filter_complexity)
+{
+ return diskann::IndexWriteParametersBuilder(complexity, graph_degree)
+ .with_saturate_graph(saturate_graph)
+ .with_max_occlusion_size(max_occlusion_size)
+ .with_alpha(alpha)
+ .with_num_threads(num_threads)
+ .with_filter_list_size(filter_complexity)
+ .build();
+}
+
+template <class DT>
+diskann::Index<DT, DynamicIdType, filterT> dynamic_index_builder(
+ const diskann::Metric m, const diskann::IndexWriteParameters &write_params, const size_t dimensions,
+ const size_t max_vectors, const uint32_t initial_search_complexity, const uint32_t initial_search_threads,
+ const bool concurrent_consolidation, const uint32_t num_frozen_points)
+{
+ const uint32_t _initial_search_threads = initial_search_threads != 0 ? initial_search_threads : omp_get_num_procs();
+
+ auto index_search_params = diskann::IndexSearchParams(initial_search_complexity, _initial_search_threads);
+ return diskann::Index<DT, DynamicIdType, filterT>(
+ m, dimensions, max_vectors,
+ std::make_shared<diskann::IndexWriteParameters>(write_params), // index write params
+ std::make_shared<diskann::IndexSearchParams>(index_search_params), // index_search_params
+ num_frozen_points, // frozen_points
+ true, // dynamic_index
+ true, // enable_tags
+ concurrent_consolidation,
+ false, // pq_dist_build
+ 0, // num_pq_chunks
+ false); // use_opq = false
+}
+
+template <class DT>
+DynamicMemoryIndex<DT>::DynamicMemoryIndex(const diskann::Metric m, const size_t dimensions, const size_t max_vectors,
+ const uint32_t complexity, const uint32_t graph_degree,
+ const bool saturate_graph, const uint32_t max_occlusion_size,
+ const float alpha, const uint32_t num_threads,
+ const uint32_t filter_complexity, const uint32_t num_frozen_points,
+ const uint32_t initial_search_complexity,
+ const uint32_t initial_search_threads, const bool concurrent_consolidation)
+ : _initial_search_complexity(initial_search_complexity != 0 ? initial_search_complexity : complexity),
+ _write_parameters(dynamic_index_write_parameters(complexity, graph_degree, saturate_graph, max_occlusion_size,
+ alpha, num_threads, filter_complexity)),
+ _index(dynamic_index_builder<DT>(m, _write_parameters, dimensions, max_vectors, _initial_search_complexity,
+ initial_search_threads, concurrent_consolidation, num_frozen_points))
+{
+}
+
+template <class DT> void DynamicMemoryIndex<DT>::load(const std::string &index_path)
+{
+ const std::string tags_file = index_path + ".tags";
+ if (!file_exists(tags_file))
+ {
+ throw std::runtime_error("tags file not found at expected path: " + tags_file);
+ }
+ _index.load(index_path.c_str(), _write_parameters.num_threads, _initial_search_complexity);
+}
+
+template <class DT>
+int DynamicMemoryIndex<DT>::insert(const py::array_t<DT, py::array::c_style | py::array::forcecast> &vector,
+ const DynamicIdType id)
+{
+ return _index.insert_point(vector.data(), id);
+}
+
+template <class DT>
+py::array_t<int> DynamicMemoryIndex<DT>::batch_insert(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &vectors,
+ py::array_t<DynamicIdType, py::array::c_style | py::array::forcecast> &ids, const int32_t num_inserts,
+ const int num_threads)
+{
+ if (num_threads == 0)
+ omp_set_num_threads(omp_get_num_procs());
+ else
+ omp_set_num_threads(num_threads);
+ py::array_t<int> insert_retvals(num_inserts);
+
+#pragma omp parallel for schedule(dynamic, 1) default(none) shared(num_inserts, insert_retvals, vectors, ids)
+ for (int32_t i = 0; i < num_inserts; i++)
+ {
+ insert_retvals.mutable_data()[i] = _index.insert_point(vectors.data(i), *(ids.data(i)));
+ }
+
+ return insert_retvals;
+}
+
+template <class DT> int DynamicMemoryIndex<DT>::mark_deleted(const DynamicIdType id)
+{
+ return this->_index.lazy_delete(id);
+}
+
+template <class DT> void DynamicMemoryIndex<DT>::save(const std::string &save_path, const bool compact_before_save)
+{
+ if (save_path.empty())
+ {
+ throw std::runtime_error("A save_path must be provided");
+ }
+ _index.save(save_path.c_str(), compact_before_save);
+}
+
+template <class DT>
+NeighborsAndDistances<DynamicIdType> DynamicMemoryIndex<DT>::search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &query, const uint64_t knn, const uint64_t complexity)
+{
+ py::array_t<DynamicIdType> ids(knn);
+ py::array_t<float> dists(knn);
+ std::vector<DT *> empty_vector;
+ _index.search_with_tags(query.data(), knn, complexity, ids.mutable_data(), dists.mutable_data(), empty_vector);
+ return std::make_pair(ids, dists);
+}
+
+template <class DT>
+NeighborsAndDistances<DynamicIdType> DynamicMemoryIndex<DT>::batch_search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &queries, const uint64_t num_queries, const uint64_t knn,
+ const uint64_t complexity, const uint32_t num_threads)
+{
+ py::array_t<DynamicIdType> ids({num_queries, knn});
+ py::array_t<float> dists({num_queries, knn});
+ std::vector<DT *> empty_vector;
+
+ if (num_threads == 0)
+ omp_set_num_threads(omp_get_num_procs());
+ else
+ omp_set_num_threads(static_cast<int32_t>(num_threads));
+
+#pragma omp parallel for schedule(dynamic, 1) default(none) \
+ shared(num_queries, queries, knn, complexity, ids, dists, empty_vector)
+ for (int64_t i = 0; i < (int64_t)num_queries; i++)
+ {
+ _index.search_with_tags(queries.data(i), knn, complexity, ids.mutable_data(i), dists.mutable_data(i),
+ empty_vector);
+ }
+
+ return std::make_pair(ids, dists);
+}
+
+template <class DT> void DynamicMemoryIndex<DT>::consolidate_delete()
+{
+ _index.consolidate_deletes(_write_parameters);
+}
+
+template <class DT> size_t DynamicMemoryIndex<DT>::num_points()
+{
+ return _index.get_num_points();
+}
+
+template class DynamicMemoryIndex<float>;
+template class DynamicMemoryIndex<uint8_t>;
+template class DynamicMemoryIndex<int8_t>;
+
+}; // namespace diskannpy
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/module.cpp b/packages/leann-backend-diskann/third_party/DiskANN/python/src/module.cpp
new file mode 100644
index 0000000..0f295e1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/module.cpp
@@ -0,0 +1,142 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <string>
+
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+
+#include "defaults.h"
+#include "distance.h"
+
+#include "builder.h"
+#include "dynamic_memory_index.h"
+#include "static_disk_index.h"
+#include "static_memory_index.h"
+
+PYBIND11_MAKE_OPAQUE(std::vector<uint32_t>);
+PYBIND11_MAKE_OPAQUE(std::vector<float>);
+PYBIND11_MAKE_OPAQUE(std::vector<int8_t>);
+PYBIND11_MAKE_OPAQUE(std::vector<uint8_t>);
+
+namespace py = pybind11;
+using namespace pybind11::literals;
+
+struct Variant
+{
+ std::string disk_builder_name;
+ std::string memory_builder_name;
+ std::string dynamic_memory_index_name;
+ std::string static_memory_index_name;
+ std::string static_disk_index_name;
+};
+
+const Variant FloatVariant{"build_disk_float_index", "build_memory_float_index", "DynamicMemoryFloatIndex",
+ "StaticMemoryFloatIndex", "StaticDiskFloatIndex"};
+
+const Variant UInt8Variant{"build_disk_uint8_index", "build_memory_uint8_index", "DynamicMemoryUInt8Index",
+ "StaticMemoryUInt8Index", "StaticDiskUInt8Index"};
+
+const Variant Int8Variant{"build_disk_int8_index", "build_memory_int8_index", "DynamicMemoryInt8Index",
+ "StaticMemoryInt8Index", "StaticDiskInt8Index"};
+
+template <typename T> inline void add_variant(py::module_ &m, const Variant &variant)
+{
+ m.def(variant.disk_builder_name.c_str(), &diskannpy::build_disk_index<T>, "distance_metric"_a, "data_file_path"_a,
+ "index_prefix_path"_a, "complexity"_a, "graph_degree"_a, "final_index_ram_limit"_a, "indexing_ram_budget"_a,
+ "num_threads"_a, "pq_disk_bytes"_a, "codebook_prefix"_a = "");
+
+ m.def(variant.memory_builder_name.c_str(), &diskannpy::build_memory_index<T>, "distance_metric"_a,
+ "data_file_path"_a, "index_output_path"_a, "graph_degree"_a, "complexity"_a, "alpha"_a, "num_threads"_a,
+ "use_pq_build"_a, "num_pq_bytes"_a, "use_opq"_a, "use_tags"_a = false, "filter_labels_file"_a = "",
+ "universal_label"_a = "", "filter_complexity"_a = 0);
+
+ py::class_<diskannpy::StaticMemoryIndex<T>>(m, variant.static_memory_index_name.c_str())
+ .def(py::init<const diskann::Metric, const std::string &, const size_t, const size_t, const uint32_t,
+ const uint32_t>(),
+ "distance_metric"_a, "index_path"_a, "num_points"_a, "dimensions"_a, "num_threads"_a,
+ "initial_search_complexity"_a)
+ .def("search", &diskannpy::StaticMemoryIndex<T>::search, "query"_a, "knn"_a, "complexity"_a)
+ .def("search_with_filter", &diskannpy::StaticMemoryIndex<T>::search_with_filter, "query"_a, "knn"_a,
+ "complexity"_a, "filter"_a)
+ .def("batch_search", &diskannpy::StaticMemoryIndex<T>::batch_search, "queries"_a, "num_queries"_a, "knn"_a,
+ "complexity"_a, "num_threads"_a);
+
+ py::class_<diskannpy::DynamicMemoryIndex<T>>(m, variant.dynamic_memory_index_name.c_str())
+ .def(py::init<const diskann::Metric, const size_t, const size_t, const uint32_t, const uint32_t, const bool,
+ const uint32_t, const float, const uint32_t, const uint32_t, const uint32_t, const uint32_t,
+ const uint32_t, const bool>(),
+ "distance_metric"_a, "dimensions"_a, "max_vectors"_a, "complexity"_a, "graph_degree"_a,
+ "saturate_graph"_a = diskann::defaults::SATURATE_GRAPH,
+ "max_occlusion_size"_a = diskann::defaults::MAX_OCCLUSION_SIZE, "alpha"_a = diskann::defaults::ALPHA,
+ "num_threads"_a = diskann::defaults::NUM_THREADS,
+ "filter_complexity"_a = diskann::defaults::FILTER_LIST_SIZE,
+ "num_frozen_points"_a = diskann::defaults::NUM_FROZEN_POINTS_DYNAMIC, "initial_search_complexity"_a = 0,
+ "search_threads"_a = 0, "concurrent_consolidation"_a = true)
+ .def("search", &diskannpy::DynamicMemoryIndex<T>::search, "query"_a, "knn"_a, "complexity"_a)
+ .def("load", &diskannpy::DynamicMemoryIndex<T>::load, "index_path"_a)
+ .def("batch_search", &diskannpy::DynamicMemoryIndex<T>::batch_search, "queries"_a, "num_queries"_a, "knn"_a,
+ "complexity"_a, "num_threads"_a)
+ .def("batch_insert", &diskannpy::DynamicMemoryIndex<T>::batch_insert, "vectors"_a, "ids"_a, "num_inserts"_a,
+ "num_threads"_a)
+ .def("save", &diskannpy::DynamicMemoryIndex<T>::save, "save_path"_a = "", "compact_before_save"_a = false)
+ .def("insert", &diskannpy::DynamicMemoryIndex<T>::insert, "vector"_a, "id"_a)
+ .def("mark_deleted", &diskannpy::DynamicMemoryIndex<T>::mark_deleted, "id"_a)
+ .def("consolidate_delete", &diskannpy::DynamicMemoryIndex<T>::consolidate_delete)
+ .def("num_points", &diskannpy::DynamicMemoryIndex<T>::num_points);
+
+ py::class_<diskannpy::StaticDiskIndex<T>>(m, variant.static_disk_index_name.c_str())
+ .def(py::init<const diskann::Metric, const std::string &, const uint32_t, const size_t, const uint32_t,
+ const std::string &, const std::string &>(),
+ "distance_metric"_a, "index_path_prefix"_a, "num_threads"_a, "num_nodes_to_cache"_a,
+ "cache_mechanism"_a = 1, "pq_prefix"_a = "", "partition_prefix"_a)
+ .def("cache_bfs_levels", &diskannpy::StaticDiskIndex<T>::cache_bfs_levels, "num_nodes_to_cache"_a)
+ .def("search", &diskannpy::StaticDiskIndex<T>::search, "query"_a, "knn"_a, "complexity"_a, "beam_width"_a,
+ "USE_DEFERRED_FETCH"_a = false, "skip_search_reorder"_a = false, "recompute_beighbor_embeddings"_a = false,
+ "dedup_node_dis"_a = false, "prune_ratio"_a = 0, "batch_recompute"_a = false, "global_pruning"_a = false)
+ .def("batch_search", &diskannpy::StaticDiskIndex<T>::batch_search, "queries"_a, "num_queries"_a, "knn"_a,
+ "complexity"_a, "beam_width"_a, "num_threads"_a, "USE_DEFERRED_FETCH"_a = false,
+ "skip_search_reorder"_a = false, "recompute_beighbor_embeddings"_a = false, "dedup_node_dis"_a = false,
+ "prune_ratio"_a = 0, "batch_recompute"_a = false, "global_pruning"_a = false);
+}
+
+PYBIND11_MODULE(_diskannpy, m)
+{
+ m.doc() = "DiskANN Python Bindings";
+#ifdef VERSION_INFO
+ m.attr("__version__") = VERSION_INFO;
+#else
+ m.attr("__version__") = "dev";
+#endif
+
+ // let's re-export our defaults
+ py::module_ default_values = m.def_submodule(
+ "defaults",
+ "A collection of the default values used for common diskann operations. `GRAPH_DEGREE` and `COMPLEXITY` are not"
+ " set as defaults, but some semi-reasonable default values are selected for your convenience. We urge you to "
+ "investigate their meaning and adjust them for your use cases.");
+
+ default_values.attr("ALPHA") = diskann::defaults::ALPHA;
+ default_values.attr("NUM_THREADS") = diskann::defaults::NUM_THREADS;
+ default_values.attr("MAX_OCCLUSION_SIZE") = diskann::defaults::MAX_OCCLUSION_SIZE;
+ default_values.attr("FILTER_COMPLEXITY") = diskann::defaults::FILTER_LIST_SIZE;
+ default_values.attr("NUM_FROZEN_POINTS_STATIC") = diskann::defaults::NUM_FROZEN_POINTS_STATIC;
+ default_values.attr("NUM_FROZEN_POINTS_DYNAMIC") = diskann::defaults::NUM_FROZEN_POINTS_DYNAMIC;
+ default_values.attr("SATURATE_GRAPH") = diskann::defaults::SATURATE_GRAPH;
+ default_values.attr("GRAPH_DEGREE") = diskann::defaults::MAX_DEGREE;
+ default_values.attr("COMPLEXITY") = diskann::defaults::BUILD_LIST_SIZE;
+ default_values.attr("PQ_DISK_BYTES") = (uint32_t)0;
+ default_values.attr("USE_PQ_BUILD") = false;
+ default_values.attr("NUM_PQ_BYTES") = (uint32_t)0;
+ default_values.attr("USE_OPQ") = false;
+
+ add_variant<float>(m, FloatVariant);
+ add_variant<uint8_t>(m, UInt8Variant);
+ add_variant<int8_t>(m, Int8Variant);
+
+ py::enum_<diskann::Metric>(m, "Metric")
+ .value("L2", diskann::Metric::L2)
+ .value("INNER_PRODUCT", diskann::Metric::INNER_PRODUCT)
+ .value("COSINE", diskann::Metric::COSINE)
+ .export_values();
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/py.typed b/packages/leann-backend-diskann/third_party/DiskANN/python/src/py.typed
new file mode 100644
index 0000000..e69de29
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/static_disk_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/python/src/static_disk_index.cpp
new file mode 100644
index 0000000..47dc09b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/static_disk_index.cpp
@@ -0,0 +1,123 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "static_disk_index.h"
+
+#include "pybind11/numpy.h"
+
+namespace diskannpy
+{
+
+template <typename DT>
+StaticDiskIndex<DT>::StaticDiskIndex(const diskann::Metric metric, const std::string &index_path_prefix,
+ const uint32_t num_threads, const size_t num_nodes_to_cache,
+ const uint32_t cache_mechanism, const std::string &pq_prefix,
+ const std::string &partition_prefix)
+ : _reader(std::make_shared<PlatformSpecificAlignedFileReader>()),
+ _graph_reader(std::make_shared<PlatformSpecificAlignedFileReader>()), _index(_reader, _graph_reader, metric)
+{
+ std::cout << "Before index load" << std::endl;
+
+ const uint32_t _num_threads = num_threads != 0 ? num_threads : omp_get_num_procs();
+ int load_success =
+ _index.load(_num_threads, index_path_prefix.c_str(), pq_prefix.c_str(), partition_prefix.c_str());
+ if (load_success != 0)
+ {
+ throw std::runtime_error("index load failed, " + index_path_prefix);
+ }
+ if (cache_mechanism == 1)
+ {
+ std::string sample_file = index_path_prefix + std::string("_sample_data.bin");
+ cache_sample_paths(num_nodes_to_cache, sample_file, _num_threads);
+ }
+ else if (cache_mechanism == 2)
+ {
+ cache_bfs_levels(num_nodes_to_cache);
+ }
+ std::cout << "After index load" << std::endl;
+}
+
+template <typename DT> void StaticDiskIndex<DT>::cache_bfs_levels(const size_t num_nodes_to_cache)
+{
+ std::vector<uint32_t> node_list;
+ _index.cache_bfs_levels(num_nodes_to_cache, node_list);
+ _index.load_cache_list(node_list);
+}
+
+template <typename DT>
+void StaticDiskIndex<DT>::cache_sample_paths(const size_t num_nodes_to_cache, const std::string &warmup_query_file,
+ const uint32_t num_threads)
+{
+ if (!file_exists(warmup_query_file))
+ {
+ return;
+ }
+
+ std::vector<uint32_t> node_list;
+ _index.generate_cache_list_from_sample_queries(warmup_query_file, 15, 4, num_nodes_to_cache, num_threads,
+ node_list);
+ _index.load_cache_list(node_list);
+}
+
+template <typename DT>
+NeighborsAndDistances<StaticIdType> StaticDiskIndex<DT>::search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &query, const uint64_t knn, const uint64_t complexity,
+ const uint64_t beam_width, const bool USE_DEFERRED_FETCH, const bool skip_search_reorder,
+ const bool recompute_beighbor_embeddings, const bool dedup_node_dis, const float prune_ratio,
+ const bool batch_recompute, const bool global_pruning)
+{
+ py::array_t<StaticIdType> ids(knn);
+ py::array_t<float> dists(knn);
+
+ std::vector<uint32_t> u32_ids(knn);
+ std::vector<uint64_t> u64_ids(knn);
+ diskann::QueryStats stats;
+
+ _index.cached_beam_search(query.data(), knn, complexity, u64_ids.data(), dists.mutable_data(), beam_width, false,
+ &stats, USE_DEFERRED_FETCH, skip_search_reorder, recompute_beighbor_embeddings,
+ dedup_node_dis, prune_ratio, batch_recompute, global_pruning);
+
+ auto r = ids.mutable_unchecked<1>();
+ for (uint64_t i = 0; i < knn; ++i)
+ r(i) = (unsigned)u64_ids[i];
+
+ return std::make_pair(ids, dists);
+}
+
+template <typename DT>
+NeighborsAndDistances<StaticIdType> StaticDiskIndex<DT>::batch_search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &queries, const uint64_t num_queries, const uint64_t knn,
+ const uint64_t complexity, const uint64_t beam_width, const uint32_t num_threads, const bool USE_DEFERRED_FETCH,
+ const bool skip_search_reorder, const bool recompute_beighbor_embeddings, const bool dedup_node_dis,
+ const float prune_ratio, const bool batch_recompute, const bool global_pruning)
+{
+ py::array_t<StaticIdType> ids({num_queries, knn});
+ py::array_t<float> dists({num_queries, knn});
+
+ omp_set_num_threads(num_threads);
+
+ std::vector<uint64_t> u64_ids(knn * num_queries);
+
+#pragma omp parallel for schedule(dynamic, 1) default(none) \
+ shared(num_queries, queries, knn, complexity, u64_ids, dists, beam_width, USE_DEFERRED_FETCH, skip_search_reorder, \
+ recompute_beighbor_embeddings, dedup_node_dis, prune_ratio, batch_recompute, global_pruning)
+ for (int64_t i = 0; i < (int64_t)num_queries; i++)
+ {
+ _index.cached_beam_search(queries.data(i), knn, complexity, u64_ids.data() + i * knn, dists.mutable_data(i),
+ beam_width, false, nullptr, USE_DEFERRED_FETCH, skip_search_reorder,
+ recompute_beighbor_embeddings, dedup_node_dis, prune_ratio, batch_recompute,
+ global_pruning);
+ }
+
+ auto r = ids.mutable_unchecked();
+ for (uint64_t i = 0; i < num_queries; ++i)
+ for (uint64_t j = 0; j < knn; ++j)
+ r(i, j) = (uint32_t)u64_ids[i * knn + j];
+
+ return std::make_pair(ids, dists);
+}
+
+template class StaticDiskIndex<float>;
+template class StaticDiskIndex<uint8_t>;
+template class StaticDiskIndex<int8_t>;
+} // namespace diskannpy
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/src/static_memory_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/python/src/static_memory_index.cpp
new file mode 100644
index 0000000..d3ac079
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/src/static_memory_index.cpp
@@ -0,0 +1,91 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "static_memory_index.h"
+
+#include "pybind11/numpy.h"
+
+namespace diskannpy
+{
+
+template <class DT>
+diskann::Index<DT, StaticIdType, filterT> static_index_builder(const diskann::Metric m, const size_t num_points,
+ const size_t dimensions,
+ const uint32_t initial_search_complexity)
+{
+ if (initial_search_complexity == 0)
+ {
+ throw std::runtime_error("initial_search_complexity must be a positive uint32_t");
+ }
+ auto index_search_params = diskann::IndexSearchParams(initial_search_complexity, omp_get_num_procs());
+ return diskann::Index<DT>(m, dimensions, num_points,
+ nullptr, // index write params
+ std::make_shared<diskann::IndexSearchParams>(index_search_params), // index search params
+ 0, // num frozen points
+ false, // not a dynamic_index
+ false, // no enable_tags/ids
+ false, // no concurrent_consolidate,
+ false, // pq_dist_build
+ 0, // num_pq_chunks
+ false); // use_opq = false
+}
+
+template <class DT>
+StaticMemoryIndex<DT>::StaticMemoryIndex(const diskann::Metric m, const std::string &index_prefix,
+ const size_t num_points, const size_t dimensions, const uint32_t num_threads,
+ const uint32_t initial_search_complexity)
+ : _index(static_index_builder<DT>(m, num_points, dimensions, initial_search_complexity))
+{
+ const uint32_t _num_threads = num_threads != 0 ? num_threads : omp_get_num_procs();
+ _index.load(index_prefix.c_str(), _num_threads, initial_search_complexity);
+}
+
+template <typename DT>
+NeighborsAndDistances<StaticIdType> StaticMemoryIndex<DT>::search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &query, const uint64_t knn, const uint64_t complexity)
+{
+ py::array_t<StaticIdType> ids(knn);
+ py::array_t<float> dists(knn);
+ std::vector<DT *> empty_vector;
+ _index.search(query.data(), knn, complexity, ids.mutable_data(), dists.mutable_data());
+ return std::make_pair(ids, dists);
+}
+
+template <typename DT>
+NeighborsAndDistances<StaticIdType> StaticMemoryIndex<DT>::search_with_filter(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &query, const uint64_t knn, const uint64_t complexity,
+ const filterT filter)
+{
+ py::array_t<StaticIdType> ids(knn);
+ py::array_t<float> dists(knn);
+ std::vector<DT *> empty_vector;
+ _index.search_with_filters(query.data(), filter, knn, complexity, ids.mutable_data(), dists.mutable_data());
+ return std::make_pair(ids, dists);
+}
+
+template <typename DT>
+NeighborsAndDistances<StaticIdType> StaticMemoryIndex<DT>::batch_search(
+ py::array_t<DT, py::array::c_style | py::array::forcecast> &queries, const uint64_t num_queries, const uint64_t knn,
+ const uint64_t complexity, const uint32_t num_threads)
+{
+ const uint32_t _num_threads = num_threads != 0 ? num_threads : omp_get_num_procs();
+ py::array_t<StaticIdType> ids({num_queries, knn});
+ py::array_t<float> dists({num_queries, knn});
+ std::vector<DT *> empty_vector;
+
+ omp_set_num_threads(static_cast<int32_t>(_num_threads));
+
+#pragma omp parallel for schedule(dynamic, 1) default(none) shared(num_queries, queries, knn, complexity, ids, dists)
+ for (int64_t i = 0; i < (int64_t)num_queries; i++)
+ {
+ _index.search(queries.data(i), knn, complexity, ids.mutable_data(i), dists.mutable_data(i));
+ }
+
+ return std::make_pair(ids, dists);
+}
+
+template class StaticMemoryIndex<float>;
+template class StaticMemoryIndex<uint8_t>;
+template class StaticMemoryIndex<int8_t>;
+
+} // namespace diskannpy
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/__init__.py b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/__init__.py
new file mode 100644
index 0000000..4aeb960
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+from .build_memory_index import build_random_vectors_and_memory_index
+from .create_test_data import random_vectors, vectors_as_temp_file, write_vectors
+from .recall import calculate_recall
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/build_memory_index.py b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/build_memory_index.py
new file mode 100644
index 0000000..3c30bed
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/build_memory_index.py
@@ -0,0 +1,51 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import os
+from tempfile import mkdtemp
+
+import diskannpy as dap
+import numpy as np
+
+from .create_test_data import random_vectors
+
+
+def build_random_vectors_and_memory_index(
+ dtype, metric, with_tags: bool = False, index_prefix: str = "ann", seed: int = 12345
+):
+ query_vectors: np.ndarray = random_vectors(1000, 10, dtype=dtype, seed=seed)
+ index_vectors: np.ndarray = random_vectors(10000, 10, dtype=dtype, seed=seed)
+ ann_dir = mkdtemp()
+
+ if with_tags:
+ rng = np.random.default_rng(seed)
+ tags = np.arange(start=1, stop=10001, dtype=np.uint32)
+ rng.shuffle(tags)
+ else:
+ tags = ""
+
+ dap.build_memory_index(
+ data=index_vectors,
+ distance_metric=metric,
+ index_directory=ann_dir,
+ graph_degree=16,
+ complexity=32,
+ alpha=1.2,
+ num_threads=0,
+ use_pq_build=False,
+ num_pq_bytes=8,
+ use_opq=False,
+ filter_complexity=32,
+ tags=tags,
+ index_prefix=index_prefix,
+ )
+
+ return (
+ metric,
+ dtype,
+ query_vectors,
+ index_vectors,
+ ann_dir,
+ os.path.join(ann_dir, "vectors.bin"),
+ tags,
+ )
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/create_test_data.py b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/create_test_data.py
new file mode 100644
index 0000000..44e413e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/create_test_data.py
@@ -0,0 +1,40 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+from contextlib import contextmanager
+from pathlib import Path
+from tempfile import NamedTemporaryFile
+from typing import BinaryIO
+
+import numpy as np
+
+
+def random_vectors(rows: int, dimensions: int, dtype, seed: int = 12345) -> np.ndarray:
+ rng = np.random.default_rng(seed)
+ if dtype == np.float32:
+ vectors = rng.random((rows, dimensions), dtype=dtype)
+ elif dtype == np.uint8:
+ vectors = rng.integers(
+ low=0, high=256, size=(rows, dimensions), dtype=dtype
+ ) # low is inclusive, high is exclusive
+ elif dtype == np.int8:
+ vectors = rng.integers(
+ low=-128, high=128, size=(rows, dimensions), dtype=dtype
+ ) # low is inclusive, high is exclusive
+ else:
+ raise RuntimeError("Only np.float32, np.int8, and np.uint8 are supported")
+ return vectors
+
+
+def write_vectors(file_handler: BinaryIO, vectors: np.ndarray):
+ _ = file_handler.write(np.array(vectors.shape, dtype=np.int32).tobytes())
+ _ = file_handler.write(vectors.tobytes())
+
+
+@contextmanager
+def vectors_as_temp_file(vectors: np.ndarray) -> str:
+ temp = NamedTemporaryFile(mode="wb", delete=False)
+ write_vectors(temp, vectors)
+ temp.close()
+ yield temp.name
+ Path(temp.name).unlink()
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/recall.py b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/recall.py
new file mode 100644
index 0000000..03f38f3
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/python/tests/fixtures/recall.py
@@ -0,0 +1,24 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import numpy as np
+
+
+def calculate_recall(
+ result_set_indices: np.ndarray, truth_set_indices: np.ndarray, recall_at: int = 5
+) -> float:
+ """
+ result_set_indices and truth_set_indices correspond by row index. the columns in each row contain the indices of
+ the nearest neighbors, with result_set_indices being the approximate nearest neighbor results and truth_set_indices
+ being the brute force nearest neighbor calculation via sklearn's NearestNeighbor class.
+ :param result_set_indices:
+ :param truth_set_indices:
+ :param recall_at:
+ :return:
+ """
+ found = 0
+ for i in range(0, result_set_indices.shape[0]):
+ result_set_set = set(result_set_indices[i][0:recall_at])
+ truth_set_set = set(truth_set_indices[i][0:recall_at])
+ found += len(result_set_set.intersection(truth_set_set))
+ return found / (result_set_indices.shape[0] * recall_at)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/Cargo.lock b/packages/leann-backend-diskann/third_party/DiskANN/rust/Cargo.lock
new file mode 100644
index 0000000..3a8a252
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/Cargo.lock
@@ -0,0 +1,1820 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "adler"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
+
+[[package]]
+name = "ahash"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "version_check",
+]
+
+[[package]]
+name = "anes"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
+
+[[package]]
+name = "anstream"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is-terminal",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a30da5c5f2d5e72842e00bcb57657162cdabef0931f40e2deb9b4140440cecd"
+
+[[package]]
+name = "anstyle-parse"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b"
+dependencies = [
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188"
+dependencies = [
+ "anstyle",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.71"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
+
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+
+[[package]]
+name = "base64"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
+
+[[package]]
+name = "bincode"
+version = "1.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bitflags"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
+
+[[package]]
+name = "build_and_insert_delete_memory_index"
+version = "0.1.0"
+dependencies = [
+ "diskann",
+ "logger",
+ "vector",
+]
+
+[[package]]
+name = "build_and_insert_memory_index"
+version = "0.1.0"
+dependencies = [
+ "diskann",
+ "logger",
+ "vector",
+]
+
+[[package]]
+name = "build_disk_index"
+version = "0.1.0"
+dependencies = [
+ "diskann",
+ "logger",
+ "openblas-src",
+ "vector",
+]
+
+[[package]]
+name = "build_memory_index"
+version = "0.1.0"
+dependencies = [
+ "clap",
+ "diskann",
+ "logger",
+ "vector",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
+
+[[package]]
+name = "bytemuck"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
+
+[[package]]
+name = "byteorder"
+version = "1.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
+
+[[package]]
+name = "bytes"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
+
+[[package]]
+name = "cast"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
+
+[[package]]
+name = "cblas"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3de46dff748ed7e891bc46faae117f48d2a7911041c6630aed3c61a3fe12326f"
+dependencies = [
+ "cblas-sys",
+ "libc",
+ "num-complex",
+]
+
+[[package]]
+name = "cblas-sys"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6feecd82cce51b0204cf063f0041d69f24ce83f680d87514b004248e7b0fa65"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "cc"
+version = "1.0.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "ciborium"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "effd91f6c78e5a4ace8a5d3c0b6bfaec9e2baaef55f3efc00e45fb2e477ee926"
+dependencies = [
+ "ciborium-io",
+ "ciborium-ll",
+ "serde",
+]
+
+[[package]]
+name = "ciborium-io"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdf919175532b369853f5d5e20b26b43112613fd6fe7aee757e35f7a44642656"
+
+[[package]]
+name = "ciborium-ll"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "defaa24ecc093c77630e6c15e17c51f5e187bf35ee514f4e2d67baaa96dae22b"
+dependencies = [
+ "ciborium-io",
+ "half 1.8.2",
+]
+
+[[package]]
+name = "clap"
+version = "4.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9394150f5b4273a1763355bd1c2ec54cc5a2593f790587bcd6b2c947cfa9211"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+ "once_cell",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a78fbdd3cc2914ddf37ba444114bc7765bbdcb55ec9cbe6fa054f0137400717"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "bitflags 1.3.2",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8cd2b2a819ad6eec39e8f1d6b53001af1e5469f8c177579cdaeb313115b825f"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+]
+
+[[package]]
+name = "clap_lex"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
+
+[[package]]
+name = "convert_f32_to_bf16"
+version = "0.1.0"
+dependencies = [
+ "half 2.2.1",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
+
+[[package]]
+name = "crc32fast"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "criterion"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
+dependencies = [
+ "anes",
+ "cast",
+ "ciborium",
+ "clap",
+ "criterion-plot",
+ "is-terminal",
+ "itertools",
+ "num-traits",
+ "once_cell",
+ "oorandom",
+ "plotters",
+ "rayon",
+ "regex",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "tinytemplate",
+ "walkdir",
+]
+
+[[package]]
+name = "criterion-plot"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
+dependencies = [
+ "cast",
+ "itertools",
+]
+
+[[package]]
+name = "crossbeam"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c"
+dependencies = [
+ "cfg-if",
+ "crossbeam-channel",
+ "crossbeam-deque",
+ "crossbeam-epoch",
+ "crossbeam-queue",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef"
+dependencies = [
+ "cfg-if",
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "crossbeam-utils",
+ "memoffset",
+ "scopeguard",
+]
+
+[[package]]
+name = "crossbeam-queue"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crunchy"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
+
+[[package]]
+name = "dirs"
+version = "3.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30baa043103c9d0c2a57cf537cc2f35623889dc0d405e6c3cccfadbc81c71309"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"
+dependencies = [
+ "libc",
+ "redox_users",
+ "winapi",
+]
+
+[[package]]
+name = "diskann"
+version = "0.1.0"
+dependencies = [
+ "approx",
+ "bincode",
+ "bit-vec",
+ "byteorder",
+ "cblas",
+ "cc",
+ "criterion",
+ "crossbeam",
+ "half 2.2.1",
+ "hashbrown 0.13.2",
+ "logger",
+ "num-traits",
+ "once_cell",
+ "openblas-src",
+ "platform",
+ "rand",
+ "rayon",
+ "serde",
+ "thiserror",
+ "vector",
+ "winapi",
+]
+
+[[package]]
+name = "either"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
+
+[[package]]
+name = "errno"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a"
+dependencies = [
+ "errno-dragonfly",
+ "libc",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "errno-dragonfly"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
+dependencies = [
+ "cc",
+ "libc",
+]
+
+[[package]]
+name = "fastrand"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
+dependencies = [
+ "instant",
+]
+
+[[package]]
+name = "filetime"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5cbc844cecaee9d4443931972e1289c8ff485cb4cc2767cb03ca139ed6885153"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall 0.2.16",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "fixedbitset"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
+
+[[package]]
+name = "flate2"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+]
+
+[[package]]
+name = "foreign-types"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
+dependencies = [
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "half"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7"
+
+[[package]]
+name = "half"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02b4af3693f1b705df946e9fe5631932443781d0aabb423b62fcd4d73f6d2fd0"
+dependencies = [
+ "crunchy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+
+[[package]]
+name = "hashbrown"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
+dependencies = [
+ "ahash",
+]
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+
+[[package]]
+name = "hermit-abi"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "hermit-abi"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286"
+
+[[package]]
+name = "idna"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "indexmap"
+version = "1.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
+dependencies = [
+ "autocfg",
+ "hashbrown 0.12.3",
+]
+
+[[package]]
+name = "instant"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "io-lifetimes"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2"
+dependencies = [
+ "hermit-abi 0.3.1",
+ "libc",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "is-terminal"
+version = "0.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f"
+dependencies = [
+ "hermit-abi 0.3.1",
+ "io-lifetimes",
+ "rustix",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "itertools"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6"
+
+[[package]]
+name = "js-sys"
+version = "0.3.64"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a"
+dependencies = [
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+
+[[package]]
+name = "libc"
+version = "0.2.146"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519"
+
+[[package]]
+name = "load_and_insert_memory_index"
+version = "0.1.0"
+dependencies = [
+ "diskann",
+ "logger",
+ "vector",
+]
+
+[[package]]
+name = "log"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
+
+[[package]]
+name = "logger"
+version = "0.1.0"
+dependencies = [
+ "lazy_static",
+ "log",
+ "once_cell",
+ "prost",
+ "prost-build",
+ "prost-types",
+ "thiserror",
+ "vcpkg",
+ "win_etw_macros",
+ "win_etw_provider",
+]
+
+[[package]]
+name = "memoffset"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7"
+dependencies = [
+ "adler",
+]
+
+[[package]]
+name = "multimap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a"
+
+[[package]]
+name = "native-tls"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e"
+dependencies = [
+ "lazy_static",
+ "libc",
+ "log",
+ "openssl",
+ "openssl-probe",
+ "openssl-sys",
+ "schannel",
+ "security-framework",
+ "security-framework-sys",
+ "tempfile",
+]
+
+[[package]]
+name = "num-complex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02e0d21255c828d6f128a1e41534206671e8c3ea0c62f32291e808dc82cff17d"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num_cpus"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
+dependencies = [
+ "hermit-abi 0.2.6",
+ "libc",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+
+[[package]]
+name = "oorandom"
+version = "11.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
+
+[[package]]
+name = "openblas-build"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eba42c395477605f400a8d79ee0b756cfb82abe3eb5618e35fa70d3a36010a7f"
+dependencies = [
+ "anyhow",
+ "flate2",
+ "native-tls",
+ "tar",
+ "thiserror",
+ "ureq",
+ "walkdir",
+]
+
+[[package]]
+name = "openblas-src"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38e5d8af0b707ac2fe1574daa88b4157da73b0de3dc7c39fe3e2c0bb64070501"
+dependencies = [
+ "dirs",
+ "openblas-build",
+ "vcpkg",
+]
+
+[[package]]
+name = "openssl"
+version = "0.10.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79a4c6c3a2b158f7f8f2a2fc5a969fa3a068df6fc9dbb4a43845436e3af7c800"
+dependencies = [
+ "bitflags 2.4.1",
+ "cfg-if",
+ "foreign-types",
+ "libc",
+ "once_cell",
+ "openssl-macros",
+ "openssl-sys",
+]
+
+[[package]]
+name = "openssl-macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+]
+
+[[package]]
+name = "openssl-probe"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
+
+[[package]]
+name = "openssl-sys"
+version = "0.9.96"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3812c071ba60da8b5677cc12bcb1d42989a65553772897a7e0355545a819838f"
+dependencies = [
+ "cc",
+ "libc",
+ "pkg-config",
+ "vcpkg",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
+
+[[package]]
+name = "petgraph"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4dd7d28ee937e54fe3080c91faa1c3a46c06de6252988a7f4592ba2310ef22a4"
+dependencies = [
+ "fixedbitset",
+ "indexmap",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964"
+
+[[package]]
+name = "platform"
+version = "0.1.0"
+dependencies = [
+ "log",
+ "winapi",
+]
+
+[[package]]
+name = "plotters"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45"
+dependencies = [
+ "num-traits",
+ "plotters-backend",
+ "plotters-svg",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "plotters-backend"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609"
+
+[[package]]
+name = "plotters-svg"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab"
+dependencies = [
+ "plotters-backend",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
+
+[[package]]
+name = "prettyplease"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c8646e95016a7a6c4adea95bafa8a16baab64b583356217f2c85db4a39d9a86"
+dependencies = [
+ "proc-macro2",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "prost"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd"
+dependencies = [
+ "bytes",
+ "prost-derive",
+]
+
+[[package]]
+name = "prost-build"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "119533552c9a7ffacc21e099c24a0ac8bb19c2a2a3f363de84cd9b844feab270"
+dependencies = [
+ "bytes",
+ "heck",
+ "itertools",
+ "lazy_static",
+ "log",
+ "multimap",
+ "petgraph",
+ "prettyplease",
+ "prost",
+ "prost-types",
+ "regex",
+ "syn 1.0.109",
+ "tempfile",
+ "which",
+]
+
+[[package]]
+name = "prost-derive"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
+dependencies = [
+ "anyhow",
+ "itertools",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "prost-types"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13"
+dependencies = [
+ "prost",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rand"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+dependencies = [
+ "libc",
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom",
+]
+
+[[package]]
+name = "rayon"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d"
+dependencies = [
+ "crossbeam-channel",
+ "crossbeam-deque",
+ "crossbeam-utils",
+ "num_cpus",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b"
+dependencies = [
+ "getrandom",
+ "redox_syscall 0.2.16",
+ "thiserror",
+]
+
+[[package]]
+name = "regex"
+version = "1.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f"
+dependencies = [
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78"
+
+[[package]]
+name = "rustix"
+version = "0.37.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4eb579851244c2c03e7c24f501c3432bed80b8f720af1d6e5b0e0f01555a035"
+dependencies = [
+ "bitflags 1.3.2",
+ "errno",
+ "io-lifetimes",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00"
+dependencies = [
+ "openssl-probe",
+ "rustls-pemfile",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pemfile"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
+dependencies = [
+ "base64",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3"
+dependencies = [
+ "windows-sys 0.42.0",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
+
+[[package]]
+name = "search_memory_index"
+version = "0.1.0"
+dependencies = [
+ "bytemuck",
+ "diskann",
+ "num_cpus",
+ "rayon",
+ "vector",
+]
+
+[[package]]
+name = "security-framework"
+version = "2.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8"
+dependencies = [
+ "bitflags 1.3.2",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.164"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.164"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.97"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdf3bf93142acad5821c99197022e170842cdbc1c30482b98750c688c640842a"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha1_smol"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012"
+
+[[package]]
+name = "strsim"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tar"
+version = "0.4.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b55807c0344e1e6c04d7c965f5289c39a8d94ae23ed5c0b57aabac549f871c6"
+dependencies = [
+ "filetime",
+ "libc",
+ "xattr",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "fastrand",
+ "redox_syscall 0.3.5",
+ "rustix",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+]
+
+[[package]]
+name = "tinytemplate"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "ureq"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b11c96ac7ee530603dcdf68ed1557050f374ce55a5a07193ebf8cbc9f8927e9"
+dependencies = [
+ "base64",
+ "flate2",
+ "log",
+ "native-tls",
+ "once_cell",
+ "rustls-native-certs",
+ "url",
+]
+
+[[package]]
+name = "url"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+]
+
+[[package]]
+name = "utf8parse"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
+
+[[package]]
+name = "uuid"
+version = "1.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fa2982af2eec27de306107c027578ff7f423d65f7250e40ce0fea8f45248b81"
+dependencies = [
+ "sha1_smol",
+]
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
+[[package]]
+name = "vector"
+version = "0.1.0"
+dependencies = [
+ "approx",
+ "base64",
+ "bincode",
+ "bytemuck",
+ "cc",
+ "half 2.2.1",
+ "rand",
+ "serde",
+ "thiserror",
+]
+
+[[package]]
+name = "vector_base64"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "bincode",
+ "half 2.2.1",
+ "serde",
+]
+
+[[package]]
+name = "version_check"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+
+[[package]]
+name = "w32-error"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7c61a6bd91e168c12fc170985725340f6b458eb6f971d1cf6c34f74ffafb43"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "walkdir"
+version = "2.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.0+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.87"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342"
+dependencies = [
+ "cfg-if",
+ "wasm-bindgen-macro",
+]
+
+[[package]]
+name = "wasm-bindgen-backend"
+version = "0.2.87"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd"
+dependencies = [
+ "bumpalo",
+ "log",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.87"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.87"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.87"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
+
+[[package]]
+name = "web-sys"
+version = "0.3.64"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "which"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269"
+dependencies = [
+ "either",
+ "libc",
+ "once_cell",
+]
+
+[[package]]
+name = "widestring"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "653f141f39ec16bba3c5abe400a0c60da7468261cc2cbf36805022876bc721a8"
+
+[[package]]
+name = "win_etw_macros"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bc4c591edb4858e3445f7a60c7e0a50915aedadfa044f28f17c98c145ef54d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "sha1_smol",
+ "syn 1.0.109",
+ "uuid",
+ "win_etw_metadata",
+]
+
+[[package]]
+name = "win_etw_metadata"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e50d0fa665033a19ecefd281b4fb5481eba2972dedbb5ec129c9392a206d652f"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[package]]
+name = "win_etw_provider"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dffcc196e0e180e73a275a91f6914f173227fd627cabac3efdd8d6adec113892"
+dependencies = [
+ "w32-error",
+ "widestring",
+ "win_etw_metadata",
+ "winapi",
+ "zerocopy",
+]
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows-sys"
+version = "0.42.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
+dependencies = [
+ "windows_aarch64_gnullvm 0.42.2",
+ "windows_aarch64_msvc 0.42.2",
+ "windows_i686_gnu 0.42.2",
+ "windows_i686_msvc 0.42.2",
+ "windows_x86_64_gnu 0.42.2",
+ "windows_x86_64_gnullvm 0.42.2",
+ "windows_x86_64_msvc 0.42.2",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5"
+dependencies = [
+ "windows_aarch64_gnullvm 0.48.0",
+ "windows_aarch64_msvc 0.48.0",
+ "windows_i686_gnu 0.48.0",
+ "windows_i686_msvc 0.48.0",
+ "windows_x86_64_gnu 0.48.0",
+ "windows_x86_64_gnullvm 0.48.0",
+ "windows_x86_64_msvc 0.48.0",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
+
+[[package]]
+name = "xattr"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d1526bbe5aaeb5eb06885f4d987bcdfa5e23187055de9b83fe00156a821fabc"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6"
+dependencies = [
+ "byteorder",
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.18",
+]
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/Cargo.toml
new file mode 100644
index 0000000..5236f96
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/Cargo.toml
@@ -0,0 +1,23 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+[workspace]
+members = [
+ "cmd_drivers/build_memory_index",
+ "cmd_drivers/build_and_insert_memory_index",
+ "cmd_drivers/load_and_insert_memory_index",
+ "cmd_drivers/convert_f32_to_bf16",
+ "cmd_drivers/search_memory_index",
+ "cmd_drivers/build_disk_index",
+ "cmd_drivers/build_and_insert_delete_memory_index",
+ "vector",
+ "diskann",
+ "platform",
+ "logger",
+ "vector_base64"
+]
+resolver = "2"
+
+[profile.release]
+opt-level = 3
+codegen-units=1
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_delete_memory_index/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_delete_memory_index/Cargo.toml
new file mode 100644
index 0000000..42aa185
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_delete_memory_index/Cargo.toml
@@ -0,0 +1,14 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "build_and_insert_delete_memory_index"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+diskann = { path = "../../diskann" }
+logger = { path = "../../logger" }
+vector = { path = "../../vector" }
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_delete_memory_index/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_delete_memory_index/src/main.rs
new file mode 100644
index 0000000..4593a9e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_delete_memory_index/src/main.rs
@@ -0,0 +1,420 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::env;
+
+use diskann::{
+ common::{ANNError, ANNResult},
+ index::create_inmem_index,
+ model::{
+ configuration::index_write_parameters::IndexWriteParametersBuilder,
+ vertex::{DIM_104, DIM_128, DIM_256},
+ IndexConfiguration,
+ },
+ utils::round_up,
+ utils::{file_exists, load_ids_to_delete_from_file, load_metadata_from_file, Timer},
+};
+
+use vector::{FullPrecisionDistance, Half, Metric};
+
+// The main function to build an in-memory index
+#[allow(clippy::too_many_arguments)]
+fn build_and_insert_delete_in_memory_index<T>(
+ metric: Metric,
+ data_path: &str,
+ delta_path: &str,
+ r: u32,
+ l: u32,
+ alpha: f32,
+ save_path: &str,
+ num_threads: u32,
+ _use_pq_build: bool,
+ _num_pq_bytes: usize,
+ use_opq: bool,
+ delete_path: &str,
+) -> ANNResult<()>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
+{
+ let index_write_parameters = IndexWriteParametersBuilder::new(l, r)
+ .with_alpha(alpha)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+
+ let (data_num, data_dim) = load_metadata_from_file(data_path)?;
+
+ let config = IndexConfiguration::new(
+ metric,
+ data_dim,
+ round_up(data_dim as u64, 8_u64) as usize,
+ data_num,
+ false,
+ 0,
+ use_opq,
+ 0,
+ 2.0f32,
+ index_write_parameters,
+ );
+ let mut index = create_inmem_index::<T>(config)?;
+
+ let timer = Timer::new();
+
+ index.build(data_path, data_num)?;
+
+ let diff = timer.elapsed();
+
+ println!("Initial indexing time: {}", diff.as_secs_f64());
+
+ let (delta_data_num, _) = load_metadata_from_file(delta_path)?;
+
+ index.insert(delta_path, delta_data_num)?;
+
+ if !delete_path.is_empty() {
+ if !file_exists(delete_path) {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Data file for delete {} does not exist.",
+ delete_path
+ )));
+ }
+
+ let (num_points_to_delete, vertex_ids_to_delete) =
+ load_ids_to_delete_from_file(delete_path)?;
+ index.soft_delete(vertex_ids_to_delete, num_points_to_delete)?;
+ }
+
+ index.save(save_path)?;
+
+ Ok(())
+}
+
+fn main() -> ANNResult<()> {
+ let mut data_type = String::new();
+ let mut dist_fn = String::new();
+ let mut data_path = String::new();
+ let mut insert_path = String::new();
+ let mut index_path_prefix = String::new();
+ let mut delete_path = String::new();
+
+ let mut num_threads = 0u32;
+ let mut r = 64u32;
+ let mut l = 100u32;
+
+ let mut alpha = 1.2f32;
+ let mut build_pq_bytes = 0u32;
+ let mut _use_pq_build = false;
+ let mut use_opq = false;
+
+ let args: Vec<String> = env::args().collect();
+ let mut iter = args.iter().skip(1).peekable();
+
+ while let Some(arg) = iter.next() {
+ match arg.as_str() {
+ "--help" | "-h" => {
+ print_help();
+ return Ok(());
+ }
+ "--data_type" => {
+ data_type = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "data_type".to_string(),
+ "Missing data type".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--dist_fn" => {
+ dist_fn = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "dist_fn".to_string(),
+ "Missing distance function".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--data_path" => {
+ data_path = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "data_path".to_string(),
+ "Missing data path".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--insert_path" => {
+ insert_path = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "insert_path".to_string(),
+ "Missing insert path".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--index_path_prefix" => {
+ index_path_prefix = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "index_path_prefix".to_string(),
+ "Missing index path prefix".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--max_degree" | "-R" => {
+ r = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ "Missing max degree".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--Lbuild" | "-L" => {
+ l = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ "Missing build complexity".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--alpha" => {
+ alpha = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "alpha".to_string(),
+ "Missing alpha".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "alpha".to_string(),
+ format!("ParseFloatError: {}", err),
+ )
+ })?;
+ }
+ "--num_threads" | "-T" => {
+ num_threads = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ "Missing number of threads".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--build_PQ_bytes" => {
+ build_pq_bytes = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ "Missing PQ bytes".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--use_opq" => {
+ use_opq = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ "Missing use_opq flag".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ format!("ParseBoolError: {}", err),
+ )
+ })?;
+ }
+ "--delete_path" => {
+ delete_path = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "delete_path".to_string(),
+ "Missing delete_path".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "delete_set_path".to_string(),
+ format!("ParseStringError: {}", err),
+ )
+ })?;
+ }
+ _ => {
+ return Err(ANNError::log_index_config_error(
+ String::from(""),
+ format!("Unknown argument: {}", arg),
+ ));
+ }
+ }
+ }
+
+ if data_type.is_empty()
+ || dist_fn.is_empty()
+ || data_path.is_empty()
+ || index_path_prefix.is_empty()
+ {
+ return Err(ANNError::log_index_config_error(
+ String::from(""),
+ "Missing required arguments".to_string(),
+ ));
+ }
+
+ _use_pq_build = build_pq_bytes > 0;
+
+ let metric = dist_fn
+ .parse::<Metric>()
+ .map_err(|err| ANNError::log_index_config_error("dist_fn".to_string(), err.to_string()))?;
+
+ println!(
+ "Starting index build with R: {} Lbuild: {} alpha: {} #threads: {}",
+ r, l, alpha, num_threads
+ );
+
+ match data_type.as_str() {
+ "int8" => {
+ build_and_insert_delete_in_memory_index::<i8>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ &delete_path,
+ )?;
+ }
+ "uint8" => {
+ build_and_insert_delete_in_memory_index::<u8>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ &delete_path,
+ )?;
+ }
+ "float" => {
+ build_and_insert_delete_in_memory_index::<f32>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ &delete_path,
+ )?;
+ }
+ "f16" => {
+ build_and_insert_delete_in_memory_index::<Half>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ &delete_path,
+ )?;
+ }
+ _ => {
+ println!("Unsupported type. Use one of int8, uint8 or float.");
+ return Err(ANNError::log_index_config_error(
+ "data_type".to_string(),
+ "Invalid data type".to_string(),
+ ));
+ }
+ }
+
+ Ok(())
+}
+
+fn print_help() {
+ println!("Arguments");
+ println!("--help, -h Print information on arguments");
+ println!("--data_type data type <int8/uint8/float> (required)");
+ println!("--dist_fn distance function <l2/cosine> (required)");
+ println!(
+ "--data_path Input data file in bin format for initial build (required)"
+ );
+ println!("--insert_path Input data file in bin format for insert (required)");
+ println!("--index_path_prefix Path prefix for saving index file components (required)");
+ println!("--max_degree, -R Maximum graph degree (default: 64)");
+ println!("--Lbuild, -L Build complexity, higher value results in better graphs (default: 100)");
+ println!("--alpha alpha controls density and diameter of graph, set 1 for sparse graph, 1.2 or 1.4 for denser graphs with lower diameter (default: 1.2)");
+ println!("--num_threads, -T Number of threads used for building index (defaults to num of CPU logic cores)");
+ println!("--build_PQ_bytes Number of PQ bytes to build the index; 0 for full precision build (default: 0)");
+ println!("--use_opq Set true for OPQ compression while using PQ distance comparisons for building the index, and false for PQ compression (default: false)");
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_memory_index/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_memory_index/Cargo.toml
new file mode 100644
index 0000000..d9811fc
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_memory_index/Cargo.toml
@@ -0,0 +1,14 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "build_and_insert_memory_index"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+diskann = { path = "../../diskann" }
+logger = { path = "../../logger" }
+vector = { path = "../../vector" }
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_memory_index/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_memory_index/src/main.rs
new file mode 100644
index 0000000..46e4ba4
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_and_insert_memory_index/src/main.rs
@@ -0,0 +1,382 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::env;
+
+use diskann::{
+ common::{ANNResult, ANNError},
+ index::create_inmem_index,
+ utils::round_up,
+ model::{
+ IndexWriteParametersBuilder,
+ IndexConfiguration,
+ vertex::{DIM_128, DIM_256, DIM_104}
+ },
+ utils::{load_metadata_from_file, Timer},
+};
+
+use vector::{Metric, FullPrecisionDistance, Half};
+
+// The main function to build an in-memory index
+#[allow(clippy::too_many_arguments)]
+fn build_and_insert_in_memory_index<T> (
+ metric: Metric,
+ data_path: &str,
+ delta_path: &str,
+ r: u32,
+ l: u32,
+ alpha: f32,
+ save_path: &str,
+ num_threads: u32,
+ _use_pq_build: bool,
+ _num_pq_bytes: usize,
+ use_opq: bool
+) -> ANNResult<()>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>
+{
+ let index_write_parameters = IndexWriteParametersBuilder::new(l, r)
+ .with_alpha(alpha)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+
+ let (data_num, data_dim) = load_metadata_from_file(data_path)?;
+
+ let config = IndexConfiguration::new(
+ metric,
+ data_dim,
+ round_up(data_dim as u64, 8_u64) as usize,
+ data_num,
+ false,
+ 0,
+ use_opq,
+ 0,
+ 2.0f32,
+ index_write_parameters,
+ );
+ let mut index = create_inmem_index::<T>(config)?;
+
+ let timer = Timer::new();
+
+ index.build(data_path, data_num)?;
+
+ let diff = timer.elapsed();
+
+ println!("Initial indexing time: {}", diff.as_secs_f64());
+
+ let (delta_data_num, _) = load_metadata_from_file(delta_path)?;
+
+ index.insert(delta_path, delta_data_num)?;
+
+ index.save(save_path)?;
+
+ Ok(())
+}
+
+fn main() -> ANNResult<()> {
+ let mut data_type = String::new();
+ let mut dist_fn = String::new();
+ let mut data_path = String::new();
+ let mut insert_path = String::new();
+ let mut index_path_prefix = String::new();
+
+ let mut num_threads = 0u32;
+ let mut r = 64u32;
+ let mut l = 100u32;
+
+ let mut alpha = 1.2f32;
+ let mut build_pq_bytes = 0u32;
+ let mut _use_pq_build = false;
+ let mut use_opq = false;
+
+ let args: Vec<String> = env::args().collect();
+ let mut iter = args.iter().skip(1).peekable();
+
+ while let Some(arg) = iter.next() {
+ match arg.as_str() {
+ "--help" | "-h" => {
+ print_help();
+ return Ok(());
+ }
+ "--data_type" => {
+ data_type = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "data_type".to_string(),
+ "Missing data type".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--dist_fn" => {
+ dist_fn = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "dist_fn".to_string(),
+ "Missing distance function".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--data_path" => {
+ data_path = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "data_path".to_string(),
+ "Missing data path".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--insert_path" => {
+ insert_path = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "insert_path".to_string(),
+ "Missing insert path".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--index_path_prefix" => {
+ index_path_prefix = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "index_path_prefix".to_string(),
+ "Missing index path prefix".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--max_degree" | "-R" => {
+ r = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ "Missing max degree".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--Lbuild" | "-L" => {
+ l = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ "Missing build complexity".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--alpha" => {
+ alpha = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "alpha".to_string(),
+ "Missing alpha".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "alpha".to_string(),
+ format!("ParseFloatError: {}", err),
+ )
+ })?;
+ }
+ "--num_threads" | "-T" => {
+ num_threads = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ "Missing number of threads".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--build_PQ_bytes" => {
+ build_pq_bytes = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ "Missing PQ bytes".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--use_opq" => {
+ use_opq = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ "Missing use_opq flag".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ format!("ParseBoolError: {}", err),
+ )
+ })?;
+ }
+ _ => {
+ return Err(ANNError::log_index_config_error(
+ String::from(""),
+ format!("Unknown argument: {}", arg),
+ ));
+ }
+ }
+ }
+
+ if data_type.is_empty()
+ || dist_fn.is_empty()
+ || data_path.is_empty()
+ || index_path_prefix.is_empty()
+ {
+ return Err(ANNError::log_index_config_error(
+ String::from(""),
+ "Missing required arguments".to_string(),
+ ));
+ }
+
+ _use_pq_build = build_pq_bytes > 0;
+
+ let metric = dist_fn
+ .parse::<Metric>()
+ .map_err(|err| ANNError::log_index_config_error(
+ "dist_fn".to_string(),
+ err.to_string(),
+ ))?;
+
+ println!(
+ "Starting index build with R: {} Lbuild: {} alpha: {} #threads: {}",
+ r, l, alpha, num_threads
+ );
+
+ match data_type.as_str() {
+ "int8" => {
+ build_and_insert_in_memory_index::<i8>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ "uint8" => {
+ build_and_insert_in_memory_index::<u8>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ "float" => {
+ build_and_insert_in_memory_index::<f32>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ "f16" => {
+ build_and_insert_in_memory_index::<Half>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ _ => {
+ println!("Unsupported type. Use one of int8, uint8 or float.");
+ return Err(ANNError::log_index_config_error("data_type".to_string(), "Invalid data type".to_string()));
+ }
+ }
+
+ Ok(())
+}
+
+fn print_help() {
+ println!("Arguments");
+ println!("--help, -h Print information on arguments");
+ println!("--data_type data type <int8/uint8/float> (required)");
+ println!("--dist_fn distance function <l2/cosine> (required)");
+ println!("--data_path Input data file in bin format for initial build (required)");
+ println!("--insert_path Input data file in bin format for insert (required)");
+ println!("--index_path_prefix Path prefix for saving index file components (required)");
+ println!("--max_degree, -R Maximum graph degree (default: 64)");
+ println!("--Lbuild, -L Build complexity, higher value results in better graphs (default: 100)");
+ println!("--alpha alpha controls density and diameter of graph, set 1 for sparse graph, 1.2 or 1.4 for denser graphs with lower diameter (default: 1.2)");
+ println!("--num_threads, -T Number of threads used for building index (defaults to num of CPU logic cores)");
+ println!("--build_PQ_bytes Number of PQ bytes to build the index; 0 for full precision build (default: 0)");
+ println!("--use_opq Set true for OPQ compression while using PQ distance comparisons for building the index, and false for PQ compression (default: false)");
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_disk_index/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_disk_index/Cargo.toml
new file mode 100644
index 0000000..afe5e5b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_disk_index/Cargo.toml
@@ -0,0 +1,14 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "build_disk_index"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+diskann = { path = "../../diskann" }
+logger = { path = "../../logger" }
+vector = { path = "../../vector" }
+openblas-src = { version = "0.10.8", features = ["system", "static"] }
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_disk_index/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_disk_index/src/main.rs
new file mode 100644
index 0000000..e0b6dbe
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_disk_index/src/main.rs
@@ -0,0 +1,377 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::env;
+
+use diskann::{
+ common::{ANNError, ANNResult},
+ index::ann_disk_index::create_disk_index,
+ model::{
+ default_param_vals::ALPHA,
+ vertex::{DIM_104, DIM_128, DIM_256},
+ DiskIndexBuildParameters, IndexConfiguration, IndexWriteParametersBuilder,
+ },
+ storage::DiskIndexStorage,
+ utils::round_up,
+ utils::{load_metadata_from_file, Timer},
+};
+
+use vector::{FullPrecisionDistance, Half, Metric};
+
+/// The main function to build a disk index
+#[allow(clippy::too_many_arguments)]
+fn build_disk_index<T>(
+ metric: Metric,
+ data_path: &str,
+ r: u32,
+ l: u32,
+ index_path_prefix: &str,
+ num_threads: u32,
+ search_ram_limit_gb: f64,
+ index_build_ram_limit_gb: f64,
+ num_pq_chunks: usize,
+ use_opq: bool,
+) -> ANNResult<()>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
+{
+ let disk_index_build_parameters =
+ DiskIndexBuildParameters::new(search_ram_limit_gb, index_build_ram_limit_gb)?;
+
+ let index_write_parameters = IndexWriteParametersBuilder::new(l, r)
+ .with_saturate_graph(true)
+ .with_num_threads(num_threads)
+ .build();
+
+ let (data_num, data_dim) = load_metadata_from_file(data_path)?;
+
+ let config = IndexConfiguration::new(
+ metric,
+ data_dim,
+ round_up(data_dim as u64, 8_u64) as usize,
+ data_num,
+ num_pq_chunks > 0,
+ num_pq_chunks,
+ use_opq,
+ 0,
+ 1f32,
+ index_write_parameters,
+ );
+ let storage = DiskIndexStorage::new(data_path.to_string(), index_path_prefix.to_string())?;
+ let mut index = create_disk_index::<T>(Some(disk_index_build_parameters), config, storage)?;
+
+ let timer = Timer::new();
+
+ index.build("")?;
+
+ let diff = timer.elapsed();
+ println!("Indexing time: {}", diff.as_secs_f64());
+
+ Ok(())
+}
+
+fn main() -> ANNResult<()> {
+ let mut data_type = String::new();
+ let mut dist_fn = String::new();
+ let mut data_path = String::new();
+ let mut index_path_prefix = String::new();
+
+ let mut num_threads = 0u32;
+ let mut r = 64u32;
+ let mut l = 100u32;
+ let mut search_ram_limit_gb = 0f64;
+ let mut index_build_ram_limit_gb = 0f64;
+
+ let mut build_pq_bytes = 0u32;
+ let mut use_opq = false;
+
+ let args: Vec<String> = env::args().collect();
+ let mut iter = args.iter().skip(1).peekable();
+
+ while let Some(arg) = iter.next() {
+ match arg.as_str() {
+ "--help" | "-h" => {
+ print_help();
+ return Ok(());
+ }
+ "--data_type" => {
+ data_type = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "data_type".to_string(),
+ "Missing data type".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--dist_fn" => {
+ dist_fn = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "dist_fn".to_string(),
+ "Missing distance function".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--data_path" => {
+ data_path = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "data_path".to_string(),
+ "Missing data path".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--index_path_prefix" => {
+ index_path_prefix = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "index_path_prefix".to_string(),
+ "Missing index path prefix".to_string(),
+ )
+ })?
+ .to_owned();
+ }
+ "--max_degree" | "-R" => {
+ r = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ "Missing max degree".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--Lbuild" | "-L" => {
+ l = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ "Missing build complexity".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--num_threads" | "-T" => {
+ num_threads = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ "Missing number of threads".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--build_PQ_bytes" => {
+ build_pq_bytes = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ "Missing PQ bytes".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ format!("ParseIntError: {}", err),
+ )
+ })?;
+ }
+ "--use_opq" => {
+ use_opq = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ "Missing use_opq flag".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ format!("ParseBoolError: {}", err),
+ )
+ })?;
+ }
+ "--search_DRAM_budget" | "-B" => {
+ search_ram_limit_gb = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "search_DRAM_budget".to_string(),
+ "Missing search_DRAM_budget flag".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "search_DRAM_budget".to_string(),
+ format!("ParseBoolError: {}", err),
+ )
+ })?;
+ }
+ "--build_DRAM_budget" | "-M" => {
+ index_build_ram_limit_gb = iter
+ .next()
+ .ok_or_else(|| {
+ ANNError::log_index_config_error(
+ "build_DRAM_budget".to_string(),
+ "Missing build_DRAM_budget flag".to_string(),
+ )
+ })?
+ .parse()
+ .map_err(|err| {
+ ANNError::log_index_config_error(
+ "build_DRAM_budget".to_string(),
+ format!("ParseBoolError: {}", err),
+ )
+ })?;
+ }
+ _ => {
+ return Err(ANNError::log_index_config_error(
+ String::from(""),
+ format!("Unknown argument: {}", arg),
+ ));
+ }
+ }
+ }
+
+ if data_type.is_empty()
+ || dist_fn.is_empty()
+ || data_path.is_empty()
+ || index_path_prefix.is_empty()
+ {
+ return Err(ANNError::log_index_config_error(
+ String::from(""),
+ "Missing required arguments".to_string(),
+ ));
+ }
+
+ let metric = dist_fn
+ .parse::<Metric>()
+ .map_err(|err| ANNError::log_index_config_error("dist_fn".to_string(), err.to_string()))?;
+
+ println!(
+ "Starting index build with R: {} Lbuild: {} alpha: {} #threads: {} search_DRAM_budget: {} build_DRAM_budget: {}",
+ r, l, ALPHA, num_threads, search_ram_limit_gb, index_build_ram_limit_gb
+ );
+
+ let err = match data_type.as_str() {
+ "int8" => build_disk_index::<i8>(
+ metric,
+ &data_path,
+ r,
+ l,
+ &index_path_prefix,
+ num_threads,
+ search_ram_limit_gb,
+ index_build_ram_limit_gb,
+ build_pq_bytes as usize,
+ use_opq,
+ ),
+ "uint8" => build_disk_index::<u8>(
+ metric,
+ &data_path,
+ r,
+ l,
+ &index_path_prefix,
+ num_threads,
+ search_ram_limit_gb,
+ index_build_ram_limit_gb,
+ build_pq_bytes as usize,
+ use_opq,
+ ),
+ "float" => build_disk_index::<f32>(
+ metric,
+ &data_path,
+ r,
+ l,
+ &index_path_prefix,
+ num_threads,
+ search_ram_limit_gb,
+ index_build_ram_limit_gb,
+ build_pq_bytes as usize,
+ use_opq,
+ ),
+ "f16" => build_disk_index::<Half>(
+ metric,
+ &data_path,
+ r,
+ l,
+ &index_path_prefix,
+ num_threads,
+ search_ram_limit_gb,
+ index_build_ram_limit_gb,
+ build_pq_bytes as usize,
+ use_opq,
+ ),
+ _ => {
+ println!("Unsupported type. Use one of int8, uint8, float or f16.");
+ return Err(ANNError::log_index_config_error(
+ "data_type".to_string(),
+ "Invalid data type".to_string(),
+ ));
+ }
+ };
+
+ match err {
+ Ok(_) => {
+ println!("Index build completed successfully");
+ Ok(())
+ }
+ Err(err) => {
+ eprintln!("Error: {:?}", err);
+ Err(err)
+ }
+ }
+}
+
+fn print_help() {
+ println!("Arguments");
+ println!("--help, -h Print information on arguments");
+ println!("--data_type data type <int8/uint8/float> (required)");
+ println!("--dist_fn distance function <l2/cosine> (required)");
+ println!("--data_path Input data file in bin format (required)");
+ println!("--index_path_prefix Path prefix for saving index file components (required)");
+ println!("--max_degree, -R Maximum graph degree (default: 64)");
+ println!("--Lbuild, -L Build complexity, higher value results in better graphs (default: 100)");
+ println!("--search_DRAM_budget Bound on the memory footprint of the index at search time in GB. Once built, the index will use up only the specified RAM limit, the rest will reside on disk");
+ println!("--build_DRAM_budget Limit on the memory allowed for building the index in GB");
+ println!("--num_threads, -T Number of threads used for building index (defaults to num of CPU logic cores)");
+ println!("--build_PQ_bytes Number of PQ bytes to build the index; 0 for full precision build (default: 0)");
+ println!("--use_opq Set true for OPQ compression while using PQ distance comparisons for building the index, and false for PQ compression (default: false)");
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/Cargo.toml
new file mode 100644
index 0000000..eb4708d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/Cargo.toml
@@ -0,0 +1,15 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "build_memory_index"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+clap = { version = "4.3.8", features = ["derive"] }
+diskann = { path = "../../diskann" }
+logger = { path = "../../logger" }
+vector = { path = "../../vector" }
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/src/args.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/src/args.rs
new file mode 100644
index 0000000..ede31f2
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/src/args.rs
@@ -0,0 +1,62 @@
+use clap::{Args, Parser};
+
+#[derive(Debug, Args)]
+enum DataType {
+ /// Float data type.
+ Float,
+
+ /// Half data type.
+ FP16,
+}
+
+#[derive(Debug, Args)]
+enum DistanceFunction {
+ /// Euclidean distance.
+ L2,
+
+ /// Cosine distance.
+ Cosine,
+}
+
+#[derive(Debug, Parser)]
+struct BuildMemoryIndexArgs {
+ /// Data type of the vectors.
+ #[clap(long, default_value = "float")]
+ pub data_type: DataType,
+
+ /// Distance function to use.
+ #[clap(long, default_value = "l2")]
+ pub dist_fn: Metric,
+
+ /// Path to the data file. The file should be in the format specified by the `data_type` argument.
+ #[clap(long, short, required = true)]
+ pub data_path: String,
+
+ /// Path to the index file. The index will be saved to this prefixed name.
+ #[clap(long, short, required = true)]
+ pub index_path_prefix: String,
+
+ /// Number of max out degree from a vertex.
+ #[clap(long, default_value = "32")]
+ pub max_degree: usize,
+
+ /// Number of candidates to consider when building out edges
+ #[clap(long, short default_value = "50")]
+ pub l_build: usize,
+
+ /// Alpha to use to build diverse edges
+ #[clap(long, short default_value = "1.0")]
+ pub alpha: f32,
+
+ /// Number of threads to use.
+ #[clap(long, short, default_value = "1")]
+ pub num_threads: u8,
+
+ /// Number of PQ bytes to use.
+ #[clap(long, short, default_value = "8")]
+ pub build_pq_bytes: usize,
+
+ /// Use opq?
+ #[clap(long, short, default_value = "false")]
+ pub use_opq: bool,
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/src/main.rs
new file mode 100644
index 0000000..cdccc00
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/build_memory_index/src/main.rs
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use clap::{Parser, ValueEnum};
+use std::path::PathBuf;
+
+use diskann::{
+ common::ANNResult,
+ index::create_inmem_index,
+ model::{
+ vertex::{DIM_104, DIM_128, DIM_256},
+ IndexConfiguration, IndexWriteParametersBuilder,
+ },
+ utils::round_up,
+ utils::{load_metadata_from_file, Timer},
+};
+
+use vector::{FullPrecisionDistance, Half, Metric};
+
+/// The main function to build an in-memory index
+#[allow(clippy::too_many_arguments)]
+fn build_in_memory_index<T>(
+ metric: Metric,
+ data_path: &str,
+ r: u32,
+ l: u32,
+ alpha: f32,
+ save_path: &str,
+ num_threads: u32,
+ _use_pq_build: bool,
+ _num_pq_bytes: usize,
+ use_opq: bool,
+) -> ANNResult<()>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
+{
+ let index_write_parameters = IndexWriteParametersBuilder::new(l, r)
+ .with_alpha(alpha)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+
+ let (data_num, data_dim) = load_metadata_from_file(data_path)?;
+
+ let config = IndexConfiguration::new(
+ metric,
+ data_dim,
+ round_up(data_dim as u64, 8_u64) as usize,
+ data_num,
+ false,
+ 0,
+ use_opq,
+ 0,
+ 1f32,
+ index_write_parameters,
+ );
+ let mut index = create_inmem_index::<T>(config)?;
+
+ let timer = Timer::new();
+
+ index.build(data_path, data_num)?;
+
+ let diff = timer.elapsed();
+
+ println!("Indexing time: {}", diff.as_secs_f64());
+ index.save(save_path)?;
+
+ Ok(())
+}
+
+fn main() -> ANNResult<()> {
+ let args = BuildMemoryIndexArgs::parse();
+
+ let _use_pq_build = args.build_pq_bytes > 0;
+
+ println!(
+ "Starting index build with R: {} Lbuild: {} alpha: {} #threads: {}",
+ args.max_degree, args.l_build, args.alpha, args.num_threads
+ );
+
+ let err = match args.data_type {
+ DataType::Float => build_in_memory_index::<f32>(
+ args.dist_fn,
+ &args.data_path.to_string_lossy(),
+ args.max_degree,
+ args.l_build,
+ args.alpha,
+ &args.index_path_prefix,
+ args.num_threads,
+ _use_pq_build,
+ args.build_pq_bytes,
+ args.use_opq,
+ ),
+ DataType::FP16 => build_in_memory_index::<Half>(
+ args.dist_fn,
+ &args.data_path.to_string_lossy(),
+ args.max_degree,
+ args.l_build,
+ args.alpha,
+ &args.index_path_prefix,
+ args.num_threads,
+ _use_pq_build,
+ args.build_pq_bytes,
+ args.use_opq,
+ ),
+ };
+
+ match err {
+ Ok(_) => {
+ println!("Index build completed successfully");
+ Ok(())
+ }
+ Err(err) => {
+ eprintln!("Error: {:?}", err);
+ Err(err)
+ }
+ }
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
+enum DataType {
+ /// Float data type.
+ Float,
+
+ /// Half data type.
+ FP16,
+}
+
+#[derive(Debug, Parser)]
+struct BuildMemoryIndexArgs {
+ /// data type <int8/uint8/float / fp16> (required)
+ #[arg(long = "data_type", default_value = "float")]
+ pub data_type: DataType,
+
+ /// Distance function to use.
+ #[arg(long = "dist_fn", default_value = "l2")]
+ pub dist_fn: Metric,
+
+ /// Path to the data file. The file should be in the format specified by the `data_type` argument.
+ #[arg(long = "data_path", short, required = true)]
+ pub data_path: PathBuf,
+
+ /// Path to the index file. The index will be saved to this prefixed name.
+ #[arg(long = "index_path_prefix", short, required = true)]
+ pub index_path_prefix: String,
+
+ /// Number of max out degree from a vertex.
+ #[arg(long = "max_degree", short = 'R', default_value = "64")]
+ pub max_degree: u32,
+
+ /// Number of candidates to consider when building out edges
+ #[arg(long = "l_build", short = 'L', default_value = "100")]
+ pub l_build: u32,
+
+ /// alpha controls density and diameter of graph, set 1 for sparse graph, 1.2 or 1.4 for denser graphs with lower diameter
+ #[arg(long, short, default_value = "1.2")]
+ pub alpha: f32,
+
+ /// Number of threads to use.
+ #[arg(long = "num_threads", short = 'T', default_value = "1")]
+ pub num_threads: u32,
+
+ /// Number of PQ bytes to build the index; 0 for full precision build
+ #[arg(long = "build_pq_bytes", short, default_value = "0")]
+ pub build_pq_bytes: usize,
+
+ /// Set true for OPQ compression while using PQ distance comparisons for building the index, and false for PQ compression
+ #[arg(long = "use_opq", short, default_value = "false")]
+ pub use_opq: bool,
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/convert_f32_to_bf16/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/convert_f32_to_bf16/Cargo.toml
new file mode 100644
index 0000000..1993aab
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/convert_f32_to_bf16/Cargo.toml
@@ -0,0 +1,11 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "convert_f32_to_bf16"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+half = "2.2.1"
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/convert_f32_to_bf16/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/convert_f32_to_bf16/src/main.rs
new file mode 100644
index 0000000..87b4fba
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/convert_f32_to_bf16/src/main.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use half::{bf16, f16};
+use std::env;
+use std::fs::{File, OpenOptions};
+use std::io::{self, Read, Write, BufReader, BufWriter};
+
+enum F16OrBF16 {
+ F16(f16),
+ BF16(bf16),
+}
+
+fn main() -> io::Result<()> {
+ // Retrieve command-line arguments
+ let args: Vec<String> = env::args().collect();
+
+ match args.len() {
+ 3|4|5|6=> {},
+ _ => {
+ print_usage();
+ std::process::exit(1);
+ }
+ }
+
+ // Retrieve the input and output file paths from the arguments
+ let input_file_path = &args[1];
+ let output_file_path = &args[2];
+ let use_f16 = args.len() >= 4 && args[3] == "f16";
+ let save_as_float = args.len() >= 5 && args[4] == "save_as_float";
+ let batch_size = if args.len() >= 6 { args[5].parse::<i32>().unwrap() } else { 100000 };
+ println!("use_f16: {}", use_f16);
+ println!("save_as_float: {}", save_as_float);
+ println!("batch_size: {}", batch_size);
+
+ // Open the input file for reading
+ let mut input_file = BufReader::new(File::open(input_file_path)?);
+
+ // Open the output file for writing
+ let mut output_file = BufWriter::new(OpenOptions::new().write(true).create(true).open(output_file_path)?);
+
+ // Read the first 8 bytes as metadata
+ let mut metadata = [0; 8];
+ input_file.read_exact(&mut metadata)?;
+
+ // Write the metadata to the output file
+ output_file.write_all(&metadata)?;
+
+ // Extract the number of points and dimension from the metadata
+ let num_points = i32::from_le_bytes(metadata[..4].try_into().unwrap());
+ let dimension = i32::from_le_bytes(metadata[4..].try_into().unwrap());
+ let num_batches = num_points / batch_size;
+ // Calculate the size of one data point in bytes
+ let data_point_size = (dimension * 4 * batch_size) as usize;
+ let mut batches_processed = 0;
+ let numbers_to_print = 2;
+ let mut numbers_printed = 0;
+ let mut num_fb16_wins = 0;
+ let mut num_f16_wins = 0;
+ let mut bf16_overflow = 0;
+ let mut f16_overflow = 0;
+
+ // Process each data point
+ for _ in 0..num_batches {
+ // Read one data point from the input file
+ let mut buffer = vec![0; data_point_size];
+ match input_file.read_exact(&mut buffer){
+ Ok(()) => {
+ // Convert the float32 data to bf16
+ let half_data: Vec<F16OrBF16> = buffer
+ .chunks_exact(4)
+ .map(|chunk| {
+ let value = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
+ let converted_bf16 = bf16::from_f32(value);
+ let converted_f16 = f16::from_f32(value);
+ let distance_f16 = (converted_f16.to_f32() - value).abs();
+ let distance_bf16 = (converted_bf16.to_f32() - value).abs();
+
+ if distance_f16 < distance_bf16 {
+ num_f16_wins += 1;
+ } else {
+ num_fb16_wins += 1;
+ }
+
+ if (converted_bf16 == bf16::INFINITY) || (converted_bf16 == bf16::NEG_INFINITY) {
+ bf16_overflow += 1;
+ }
+
+ if (converted_f16 == f16::INFINITY) || (converted_f16 == f16::NEG_INFINITY) {
+ f16_overflow += 1;
+ }
+
+ if numbers_printed < numbers_to_print {
+ numbers_printed += 1;
+ println!("f32 value: {} f16 value: {} | distance {}, bf16 value: {} | distance {},",
+ value, converted_f16, converted_f16.to_f32() - value, converted_bf16, converted_bf16.to_f32() - value);
+ }
+
+ if use_f16 {
+ F16OrBF16::F16(converted_f16)
+ } else {
+ F16OrBF16::BF16(converted_bf16)
+ }
+ })
+ .collect();
+
+ batches_processed += 1;
+
+ match save_as_float {
+ true => {
+ for float_val in half_data {
+ match float_val {
+ F16OrBF16::F16(f16_val) => output_file.write_all(&f16_val.to_f32().to_le_bytes())?,
+ F16OrBF16::BF16(bf16_val) => output_file.write_all(&bf16_val.to_f32().to_le_bytes())?,
+ }
+ }
+ }
+ false => {
+ for float_val in half_data {
+ match float_val {
+ F16OrBF16::F16(f16_val) => output_file.write_all(&f16_val.to_le_bytes())?,
+ F16OrBF16::BF16(bf16_val) => output_file.write_all(&bf16_val.to_le_bytes())?,
+ }
+ }
+ }
+ }
+
+ // Print the number of points processed
+ println!("Processed {} points out of {}", batches_processed * batch_size, num_points);
+ }
+ Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => {
+ println!("Conversion completed! {} of times f16 wins | overflow count {}, {} of times bf16 wins | overflow count{}",
+ num_f16_wins, f16_overflow, num_fb16_wins, bf16_overflow);
+ break;
+ }
+ Err(err) => {
+ println!("Error: {}", err);
+ break;
+ }
+ };
+ }
+
+ Ok(())
+}
+
+/// Prints the usage information
+fn print_usage() {
+ println!("Usage: program_name input_file output_file [f16] [save_as_float] [batch_size]]");
+ println!("specify f16 to downscale to f16. otherwise, downscale to bf16.");
+ println!("specify save_as_float to downcast to f16 or bf16, and upcast to float before saving the output data. otherwise, the data will be saved as half type.");
+ println!("specify the batch_size as a int, the default value is 100000.");
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/load_and_insert_memory_index/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/load_and_insert_memory_index/Cargo.toml
new file mode 100644
index 0000000..cbb4e1e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/load_and_insert_memory_index/Cargo.toml
@@ -0,0 +1,14 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "load_and_insert_memory_index"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+diskann = { path = "../../diskann" }
+logger = { path = "../../logger" }
+vector = { path = "../../vector" }
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/load_and_insert_memory_index/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/load_and_insert_memory_index/src/main.rs
new file mode 100644
index 0000000..4168046
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/load_and_insert_memory_index/src/main.rs
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::env;
+
+use diskann::{
+ common::{ANNResult, ANNError},
+ index::create_inmem_index,
+ utils::round_up,
+ model::{
+ IndexWriteParametersBuilder,
+ IndexConfiguration,
+ vertex::{DIM_128, DIM_256, DIM_104}
+ },
+ utils::{Timer, load_metadata_from_file},
+};
+
+use vector::{Metric, FullPrecisionDistance, Half};
+
+// The main function to build an in-memory index
+#[allow(clippy::too_many_arguments)]
+fn load_and_insert_in_memory_index<T> (
+ metric: Metric,
+ data_path: &str,
+ delta_path: &str,
+ r: u32,
+ l: u32,
+ alpha: f32,
+ save_path: &str,
+ num_threads: u32,
+ _use_pq_build: bool,
+ _num_pq_bytes: usize,
+ use_opq: bool
+) -> ANNResult<()>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>
+{
+ let index_write_parameters = IndexWriteParametersBuilder::new(l, r)
+ .with_alpha(alpha)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+
+ let (data_num, data_dim) = load_metadata_from_file(&format!("{}.data", data_path))?;
+
+ let config = IndexConfiguration::new(
+ metric,
+ data_dim,
+ round_up(data_dim as u64, 8_u64) as usize,
+ data_num,
+ false,
+ 0,
+ use_opq,
+ 0,
+ 2.0f32,
+ index_write_parameters,
+ );
+ let mut index = create_inmem_index::<T>(config)?;
+
+ let timer = Timer::new();
+
+ index.load(data_path, data_num)?;
+
+ let diff = timer.elapsed();
+
+ println!("Initial indexing time: {}", diff.as_secs_f64());
+
+ let (delta_data_num, _) = load_metadata_from_file(delta_path)?;
+
+ index.insert(delta_path, delta_data_num)?;
+
+ index.save(save_path)?;
+
+ Ok(())
+}
+
+fn main() -> ANNResult<()> {
+ let mut data_type = String::new();
+ let mut dist_fn = String::new();
+ let mut data_path = String::new();
+ let mut insert_path = String::new();
+ let mut index_path_prefix = String::new();
+
+ let mut num_threads = 0u32;
+ let mut r = 64u32;
+ let mut l = 100u32;
+
+ let mut alpha = 1.2f32;
+ let mut build_pq_bytes = 0u32;
+ let mut _use_pq_build = false;
+ let mut use_opq = false;
+
+ let args: Vec<String> = env::args().collect();
+ let mut iter = args.iter().skip(1).peekable();
+
+ while let Some(arg) = iter.next() {
+ match arg.as_str() {
+ "--help" | "-h" => {
+ print_help();
+ return Ok(());
+ }
+ "--data_type" => {
+ data_type = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "data_type".to_string(),
+ "Missing data type".to_string())
+ )?
+ .to_owned();
+ }
+ "--dist_fn" => {
+ dist_fn = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "dist_fn".to_string(),
+ "Missing distance function".to_string())
+ )?
+ .to_owned();
+ }
+ "--data_path" => {
+ data_path = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "data_path".to_string(),
+ "Missing data path".to_string())
+ )?
+ .to_owned();
+ }
+ "--insert_path" => {
+ insert_path = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "insert_path".to_string(),
+ "Missing insert path".to_string())
+ )?
+ .to_owned();
+ }
+ "--index_path_prefix" => {
+ index_path_prefix = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "index_path_prefix".to_string(),
+ "Missing index path prefix".to_string()))?
+ .to_owned();
+ }
+ "--max_degree" | "-R" => {
+ r = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ "Missing max degree".to_string()))?
+ .parse()
+ .map_err(|err| ANNError::log_index_config_error(
+ "max_degree".to_string(),
+ format!("ParseIntError: {}", err))
+ )?;
+ }
+ "--Lbuild" | "-L" => {
+ l = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ "Missing build complexity".to_string()))?
+ .parse()
+ .map_err(|err| ANNError::log_index_config_error(
+ "Lbuild".to_string(),
+ format!("ParseIntError: {}", err))
+ )?;
+ }
+ "--alpha" => {
+ alpha = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "alpha".to_string(),
+ "Missing alpha".to_string()))?
+ .parse()
+ .map_err(|err| ANNError::log_index_config_error(
+ "alpha".to_string(),
+ format!("ParseFloatError: {}", err))
+ )?;
+ }
+ "--num_threads" | "-T" => {
+ num_threads = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ "Missing number of threads".to_string()))?
+ .parse()
+ .map_err(|err| ANNError::log_index_config_error(
+ "num_threads".to_string(),
+ format!("ParseIntError: {}", err))
+ )?;
+ }
+ "--build_PQ_bytes" => {
+ build_pq_bytes = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ "Missing PQ bytes".to_string()))?
+ .parse()
+ .map_err(|err| ANNError::log_index_config_error(
+ "build_PQ_bytes".to_string(),
+ format!("ParseIntError: {}", err))
+ )?;
+ }
+ "--use_opq" => {
+ use_opq = iter.next().ok_or_else(|| ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ "Missing use_opq flag".to_string()))?
+ .parse()
+ .map_err(|err| ANNError::log_index_config_error(
+ "use_opq".to_string(),
+ format!("ParseBoolError: {}", err))
+ )?;
+ }
+ _ => {
+ return Err(ANNError::log_index_config_error(String::from(""), format!("Unknown argument: {}", arg)));
+ }
+ }
+ }
+
+ if data_type.is_empty()
+ || dist_fn.is_empty()
+ || data_path.is_empty()
+ || index_path_prefix.is_empty()
+ {
+ return Err(ANNError::log_index_config_error(String::from(""), "Missing required arguments".to_string()));
+ }
+
+ _use_pq_build = build_pq_bytes > 0;
+
+ let metric = dist_fn
+ .parse::<Metric>()
+ .map_err(|err| ANNError::log_index_config_error(
+ "dist_fn".to_string(),
+ err.to_string(),
+ ))?;
+
+ println!(
+ "Starting index build with R: {} Lbuild: {} alpha: {} #threads: {}",
+ r, l, alpha, num_threads
+ );
+
+ match data_type.as_str() {
+ "int8" => {
+ load_and_insert_in_memory_index::<i8>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ "uint8" => {
+ load_and_insert_in_memory_index::<u8>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ "float" => {
+ load_and_insert_in_memory_index::<f32>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?;
+ }
+ "f16" => {
+ load_and_insert_in_memory_index::<Half>(
+ metric,
+ &data_path,
+ &insert_path,
+ r,
+ l,
+ alpha,
+ &index_path_prefix,
+ num_threads,
+ _use_pq_build,
+ build_pq_bytes as usize,
+ use_opq,
+ )?
+ }
+ _ => {
+ println!("Unsupported type. Use one of int8, uint8 or float.");
+ return Err(ANNError::log_index_config_error("data_type".to_string(), "Invalid data type".to_string()));
+ }
+ }
+
+ Ok(())
+}
+
+fn print_help() {
+ println!("Arguments");
+ println!("--help, -h Print information on arguments");
+ println!("--data_type data type <int8/uint8/float> (required)");
+ println!("--dist_fn distance function <l2/cosine> (required)");
+ println!("--data_path Input data file in bin format for initial build (required)");
+ println!("--insert_path Input data file in bin format for insert (required)");
+ println!("--index_path_prefix Path prefix for saving index file components (required)");
+ println!("--max_degree, -R Maximum graph degree (default: 64)");
+ println!("--Lbuild, -L Build complexity, higher value results in better graphs (default: 100)");
+ println!("--alpha alpha controls density and diameter of graph, set 1 for sparse graph, 1.2 or 1.4 for denser graphs with lower diameter (default: 1.2)");
+ println!("--num_threads, -T Number of threads used for building index (defaults to num of CPU logic cores)");
+ println!("--build_PQ_bytes Number of PQ bytes to build the index; 0 for full precision build (default: 0)");
+ println!("--use_opq Set true for OPQ compression while using PQ distance comparisons for building the index, and false for PQ compression (default: false)");
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/Cargo.toml
new file mode 100644
index 0000000..cba3709
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/Cargo.toml
@@ -0,0 +1,16 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "search_memory_index"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+bytemuck = "1.13.1"
+diskann = { path = "../../diskann" }
+num_cpus = "1.15.0"
+rayon = "1.7.0"
+vector = { path = "../../vector" }
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/src/main.rs
new file mode 100644
index 0000000..ca4d4cd
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/src/main.rs
@@ -0,0 +1,430 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+mod search_index_utils;
+use bytemuck::Pod;
+use diskann::{
+ common::{ANNError, ANNResult},
+ index,
+ model::{
+ configuration::index_write_parameters::{default_param_vals, IndexWriteParametersBuilder},
+ vertex::{DIM_104, DIM_128, DIM_256},
+ IndexConfiguration,
+ },
+ utils::{load_metadata_from_file, save_bin_u32},
+};
+use std::{env, path::Path, process::exit, time::Instant};
+use vector::{FullPrecisionDistance, Half, Metric};
+
+use rayon::prelude::*;
+
+#[allow(clippy::too_many_arguments)]
+fn search_memory_index<T>(
+ metric: Metric,
+ index_path: &str,
+ result_path_prefix: &str,
+ query_file: &str,
+ truthset_file: &str,
+ num_threads: u32,
+ recall_at: u32,
+ print_all_recalls: bool,
+ l_vec: &Vec<u32>,
+ show_qps_per_thread: bool,
+ fail_if_recall_below: f32,
+) -> ANNResult<i32>
+where
+ T: Default + Copy + Sized + Pod + Sync + Send + Into<f32>,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
+{
+ // Load the query file
+ let (query, query_num, query_dim, query_aligned_dim) =
+ search_index_utils::load_aligned_bin::<T>(query_file)?;
+ let mut gt_dim: usize = 0;
+ let mut gt_ids: Option<Vec<u32>> = None;
+ let mut gt_dists: Option<Vec<f32>> = None;
+
+ // Check for ground truth
+ let mut calc_recall_flag = false;
+ if !truthset_file.is_empty() && Path::new(truthset_file).exists() {
+ let ret = search_index_utils::load_truthset(truthset_file)?;
+ gt_ids = Some(ret.0);
+ gt_dists = ret.1;
+ let gt_num = ret.2;
+ gt_dim = ret.3;
+
+ if gt_num != query_num {
+ println!("Error. Mismatch in number of queries and ground truth data");
+ }
+
+ calc_recall_flag = true;
+ } else {
+ println!(
+ "Truthset file {} not found. Not computing recall",
+ truthset_file
+ );
+ }
+
+ let num_frozen_pts = search_index_utils::get_graph_num_frozen_points(index_path)?;
+
+ // C++ uses the max given L value, so we do the same here. Max degree is never specified in C++ so use the rust default
+ let index_write_params = IndexWriteParametersBuilder::new(
+ *l_vec.iter().max().unwrap(),
+ default_param_vals::MAX_DEGREE,
+ )
+ .with_num_threads(num_threads)
+ .build();
+
+ let (index_num_points, _) = load_metadata_from_file(&format!("{}.data", index_path))?;
+
+ let index_config = IndexConfiguration::new(
+ metric,
+ query_dim,
+ query_aligned_dim,
+ index_num_points,
+ false,
+ 0,
+ false,
+ num_frozen_pts,
+ 1f32,
+ index_write_params,
+ );
+ let mut index = index::create_inmem_index::<T>(index_config)?;
+
+ index.load(index_path, index_num_points)?;
+
+ println!("Using {} threads to search", num_threads);
+ let qps_title = if show_qps_per_thread {
+ "QPS/thread"
+ } else {
+ "QPS"
+ };
+ let mut table_width = 4 + 12 + 18 + 20 + 15;
+ let mut table_header_str = format!(
+ "{:>4}{:>12}{:>18}{:>20}{:>15}",
+ "Ls", qps_title, "Avg dist cmps", "Mean Latency (mus)", "99.9 Latency"
+ );
+
+ let first_recall: u32 = if print_all_recalls { 1 } else { recall_at };
+ let mut recalls_to_print: usize = 0;
+ if calc_recall_flag {
+ for curr_recall in first_recall..=recall_at {
+ let recall_str = format!("Recall@{}", curr_recall);
+ table_header_str.push_str(&format!("{:>12}", recall_str));
+ recalls_to_print = (recall_at + 1 - first_recall) as usize;
+ table_width += recalls_to_print * 12;
+ }
+ }
+
+ println!("{}", table_header_str);
+ println!("{}", "=".repeat(table_width));
+
+ let mut query_result_ids: Vec<Vec<u32>> =
+ vec![vec![0; query_num * recall_at as usize]; l_vec.len()];
+ let mut latency_stats: Vec<f32> = vec![0.0; query_num];
+ let mut cmp_stats: Vec<u32> = vec![0; query_num];
+ let mut best_recall = 0.0;
+
+ std::env::set_var("RAYON_NUM_THREADS", num_threads.to_string());
+
+ for test_id in 0..l_vec.len() {
+ let l_value = l_vec[test_id];
+
+ if l_value < recall_at {
+ println!(
+ "Ignoring search with L:{} since it's smaller than K:{}",
+ l_value, recall_at
+ );
+ continue;
+ }
+
+ let zipped = cmp_stats
+ .par_iter_mut()
+ .zip(latency_stats.par_iter_mut())
+ .zip(query_result_ids[test_id].par_chunks_mut(recall_at as usize))
+ .zip(query.par_chunks(query_aligned_dim));
+
+ let start = Instant::now();
+ zipped.for_each(|(((cmp, latency), query_result), query_chunk)| {
+ let query_start = Instant::now();
+ *cmp = index
+ .search(query_chunk, recall_at as usize, l_value, query_result)
+ .unwrap();
+
+ let query_end = Instant::now();
+ let diff = query_end.duration_since(query_start);
+ *latency = diff.as_micros() as f32;
+ });
+ let diff = Instant::now().duration_since(start);
+
+ let mut displayed_qps: f32 = query_num as f32 / diff.as_secs_f32();
+ if show_qps_per_thread {
+ displayed_qps /= num_threads as f32;
+ }
+
+ let mut recalls: Vec<f32> = Vec::new();
+ if calc_recall_flag {
+ recalls.reserve(recalls_to_print);
+ for curr_recall in first_recall..=recall_at {
+ recalls.push(search_index_utils::calculate_recall(
+ query_num,
+ gt_ids.as_ref().unwrap(),
+ &gt_dists,
+ gt_dim,
+ &query_result_ids[test_id],
+ recall_at,
+ curr_recall,
+ )? as f32);
+ }
+ }
+
+ latency_stats.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ let mean_latency = latency_stats.iter().sum::<f32>() / query_num as f32;
+ let avg_cmps = cmp_stats.iter().sum::<u32>() as f32 / query_num as f32;
+
+ let mut stat_str = format!(
+ "{: >4}{: >12.2}{: >18.2}{: >20.2}{: >15.2}",
+ l_value,
+ displayed_qps,
+ avg_cmps,
+ mean_latency,
+ latency_stats[(0.999 * query_num as f32).round() as usize]
+ );
+
+ for recall in recalls.iter() {
+ stat_str.push_str(&format!("{: >12.2}", recall));
+ best_recall = f32::max(best_recall, *recall);
+ }
+
+ println!("{}", stat_str);
+ }
+
+ println!("Done searching. Now saving results");
+ for (test_id, l_value) in l_vec.iter().enumerate() {
+ if *l_value < recall_at {
+ println!(
+ "Ignoring all search with L: {} since it's smaller than K: {}",
+ l_value, recall_at
+ );
+ }
+
+ let cur_result_path = format!("{}_{}_idx_uint32.bin", result_path_prefix, l_value);
+ save_bin_u32(
+ &cur_result_path,
+ query_result_ids[test_id].as_slice(),
+ query_num,
+ recall_at as usize,
+ 0,
+ )?;
+ }
+
+ if best_recall >= fail_if_recall_below {
+ Ok(0)
+ } else {
+ Ok(-1)
+ }
+}
+
+fn main() -> ANNResult<()> {
+ let return_val: i32;
+ {
+ let mut data_type: String = String::new();
+ let mut metric: Option<Metric> = None;
+ let mut index_path: String = String::new();
+ let mut result_path_prefix: String = String::new();
+ let mut query_file: String = String::new();
+ let mut truthset_file: String = String::new();
+ let mut num_cpus: u32 = num_cpus::get() as u32;
+ let mut recall_at: Option<u32> = None;
+ let mut print_all_recalls: bool = false;
+ let mut l_vec: Vec<u32> = Vec::new();
+ let mut show_qps_per_thread: bool = false;
+ let mut fail_if_recall_below: f32 = 0.0;
+
+ let args: Vec<String> = env::args().collect();
+ let mut iter = args.iter().skip(1).peekable();
+ while let Some(arg) = iter.next() {
+ let ann_error =
+ || ANNError::log_index_config_error(String::from(arg), format!("Missing {}", arg));
+ match arg.as_str() {
+ "--help" | "-h" => {
+ print_help();
+ return Ok(());
+ }
+ "--data_type" => {
+ data_type = iter.next().ok_or_else(ann_error)?.to_owned();
+ }
+ "--dist_fn" => {
+ metric = Some(iter.next().ok_or_else(ann_error)?.parse().map_err(|err| {
+ ANNError::log_index_config_error(
+ String::from(arg),
+ format!("ParseError: {}", err),
+ )
+ })?);
+ }
+ "--index_path_prefix" => {
+ index_path = iter.next().ok_or_else(ann_error)?.to_owned();
+ }
+ "--result_path" => {
+ result_path_prefix = iter.next().ok_or_else(ann_error)?.to_owned();
+ }
+ "--query_file" => {
+ query_file = iter.next().ok_or_else(ann_error)?.to_owned();
+ }
+ "--gt_file" => {
+ truthset_file = iter.next().ok_or_else(ann_error)?.to_owned();
+ }
+ "--recall_at" | "-K" => {
+ recall_at =
+ Some(iter.next().ok_or_else(ann_error)?.parse().map_err(|err| {
+ ANNError::log_index_config_error(
+ String::from(arg),
+ format!("ParseError: {}", err),
+ )
+ })?);
+ }
+ "--print_all_recalls" => {
+ print_all_recalls = true;
+ }
+ "--search_list" | "-L" => {
+ while iter.peek().is_some() && !iter.peek().unwrap().starts_with('-') {
+ l_vec.push(iter.next().ok_or_else(ann_error)?.parse().map_err(|err| {
+ ANNError::log_index_config_error(
+ String::from(arg),
+ format!("ParseError: {}", err),
+ )
+ })?);
+ }
+ }
+ "--num_threads" => {
+ num_cpus = iter.next().ok_or_else(ann_error)?.parse().map_err(|err| {
+ ANNError::log_index_config_error(
+ String::from(arg),
+ format!("ParseError: {}", err),
+ )
+ })?;
+ }
+ "--qps_per_thread" => {
+ show_qps_per_thread = true;
+ }
+ "--fail_if_recall_below" => {
+ fail_if_recall_below =
+ iter.next().ok_or_else(ann_error)?.parse().map_err(|err| {
+ ANNError::log_index_config_error(
+ String::from(arg),
+ format!("ParseError: {}", err),
+ )
+ })?;
+ }
+ _ => {
+ return Err(ANNError::log_index_error(format!(
+ "Unknown argument: {}",
+ arg
+ )));
+ }
+ }
+ }
+
+ if metric.is_none() {
+ return Err(ANNError::log_index_error(String::from("No metric given!")));
+ } else if recall_at.is_none() {
+ return Err(ANNError::log_index_error(String::from(
+ "No recall_at given!",
+ )));
+ }
+
+ // Seems like float is the only supported data type for FullPrecisionDistance right now,
+ // but keep the structure in place here for future data types
+ match data_type.as_str() {
+ "float" => {
+ return_val = search_memory_index::<f32>(
+ metric.unwrap(),
+ &index_path,
+ &result_path_prefix,
+ &query_file,
+ &truthset_file,
+ num_cpus,
+ recall_at.unwrap(),
+ print_all_recalls,
+ &l_vec,
+ show_qps_per_thread,
+ fail_if_recall_below,
+ )?;
+ }
+ "int8" => {
+ return_val = search_memory_index::<i8>(
+ metric.unwrap(),
+ &index_path,
+ &result_path_prefix,
+ &query_file,
+ &truthset_file,
+ num_cpus,
+ recall_at.unwrap(),
+ print_all_recalls,
+ &l_vec,
+ show_qps_per_thread,
+ fail_if_recall_below,
+ )?;
+ }
+ "uint8" => {
+ return_val = search_memory_index::<u8>(
+ metric.unwrap(),
+ &index_path,
+ &result_path_prefix,
+ &query_file,
+ &truthset_file,
+ num_cpus,
+ recall_at.unwrap(),
+ print_all_recalls,
+ &l_vec,
+ show_qps_per_thread,
+ fail_if_recall_below,
+ )?;
+ }
+ "f16" => {
+ return_val = search_memory_index::<Half>(
+ metric.unwrap(),
+ &index_path,
+ &result_path_prefix,
+ &query_file,
+ &truthset_file,
+ num_cpus,
+ recall_at.unwrap(),
+ print_all_recalls,
+ &l_vec,
+ show_qps_per_thread,
+ fail_if_recall_below,
+ )?;
+ }
+ _ => {
+ return Err(ANNError::log_index_error(format!(
+ "Unknown data type: {}!",
+ data_type
+ )));
+ }
+ }
+ }
+
+ // Rust only allows returning values with this method, but this will immediately terminate the program without running destructors on the
+ // stack. To get around this enclose main function logic in a block so that by the time we return here all destructors have been called.
+ exit(return_val);
+}
+
+fn print_help() {
+ println!("Arguments");
+ println!("--help, -h Print information on arguments");
+ println!("--data_type data type <int8/uint8/float> (required)");
+ println!("--dist_fn distance function <l2/cosine> (required)");
+ println!("--index_path_prefix Path prefix to the index (required)");
+ println!("--result_path Path prefix for saving results of the queries (required)");
+ println!("--query_file Query file in binary format");
+ println!("--gt_file Ground truth file for the queryset");
+ println!("--recall_at, -K Number of neighbors to be returned");
+ println!("--print_all_recalls Print recalls at all positions, from 1 up to specified recall_at value");
+ println!("--search_list List of L values of search");
+ println!("----num_threads, -T Number of threads used for building index (defaults to num_cpus::get())");
+ println!("--qps_per_thread Print overall QPS divided by the number of threads in the output table");
+ println!("--fail_if_recall_below If set to a value >0 and <100%, program returns -1 if best recall found is below this threshold");
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/src/search_index_utils.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/src/search_index_utils.rs
new file mode 100644
index 0000000..c7b04a4
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/cmd_drivers/search_memory_index/src/search_index_utils.rs
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use bytemuck::{cast_slice, Pod};
+use diskann::{
+ common::{ANNError, ANNResult, AlignedBoxWithSlice},
+ model::data_store::DatasetDto,
+ utils::{copy_aligned_data_from_file, is_aligned, round_up},
+};
+use std::collections::HashSet;
+use std::fs::File;
+use std::io::Read;
+use std::mem::size_of;
+
+pub(crate) fn calculate_recall(
+ num_queries: usize,
+ gold_std: &[u32],
+ gs_dist: &Option<Vec<f32>>,
+ dim_gs: usize,
+ our_results: &[u32],
+ dim_or: u32,
+ recall_at: u32,
+) -> ANNResult<f64> {
+ let mut total_recall: f64 = 0.0;
+ let (mut gt, mut res): (HashSet<u32>, HashSet<u32>) = (HashSet::new(), HashSet::new());
+
+ for i in 0..num_queries {
+ gt.clear();
+ res.clear();
+
+ let gt_slice = &gold_std[dim_gs * i..];
+ let res_slice = &our_results[dim_or as usize * i..];
+ let mut tie_breaker = recall_at as usize;
+
+ if gs_dist.is_some() {
+ tie_breaker = (recall_at - 1) as usize;
+ let gt_dist_vec = &gs_dist.as_ref().unwrap()[dim_gs * i..];
+ while tie_breaker < dim_gs
+ && gt_dist_vec[tie_breaker] == gt_dist_vec[(recall_at - 1) as usize]
+ {
+ tie_breaker += 1;
+ }
+ }
+
+ (0..tie_breaker).for_each(|idx| {
+ gt.insert(gt_slice[idx]);
+ });
+
+ (0..tie_breaker).for_each(|idx| {
+ res.insert(res_slice[idx]);
+ });
+
+ let mut cur_recall: u32 = 0;
+ for v in gt.iter() {
+ if res.contains(v) {
+ cur_recall += 1;
+ }
+ }
+
+ total_recall += cur_recall as f64;
+ }
+
+ Ok(total_recall / num_queries as f64 * (100.0 / recall_at as f64))
+}
+
+pub(crate) fn get_graph_num_frozen_points(graph_file: &str) -> ANNResult<usize> {
+ let mut file = File::open(graph_file)?;
+ let mut usize_buffer = [0; size_of::<usize>()];
+ let mut u32_buffer = [0; size_of::<u32>()];
+
+ file.read_exact(&mut usize_buffer)?;
+ file.read_exact(&mut u32_buffer)?;
+ file.read_exact(&mut u32_buffer)?;
+ file.read_exact(&mut usize_buffer)?;
+ let file_frozen_pts = usize::from_le_bytes(usize_buffer);
+
+ Ok(file_frozen_pts)
+}
+
+#[inline]
+pub(crate) fn load_truthset(
+ bin_file: &str,
+) -> ANNResult<(Vec<u32>, Option<Vec<f32>>, usize, usize)> {
+ let mut file = File::open(bin_file)?;
+ let actual_file_size = file.metadata()?.len() as usize;
+
+ let mut buffer = [0; size_of::<i32>()];
+ file.read_exact(&mut buffer)?;
+ let npts = i32::from_le_bytes(buffer) as usize;
+
+ file.read_exact(&mut buffer)?;
+ let dim = i32::from_le_bytes(buffer) as usize;
+
+ println!("Metadata: #pts = {npts}, #dims = {dim}... ");
+
+ let expected_file_size_with_dists: usize =
+ 2 * npts * dim * size_of::<u32>() + 2 * size_of::<u32>();
+ let expected_file_size_just_ids: usize = npts * dim * size_of::<u32>() + 2 * size_of::<u32>();
+
+ let truthset_type : i32 = match actual_file_size
+ {
+ // This is in the C++ code, but nothing is done in this case. Keeping it here for future reference just in case.
+ // expected_file_size_just_ids => 2,
+ x if x == expected_file_size_with_dists => 1,
+ _ => return Err(ANNError::log_index_error(format!("Error. File size mismatch. File should have bin format, with npts followed by ngt
+ followed by npts*ngt ids and optionally followed by npts*ngt distance values; actual size: {}, expected: {} or {}",
+ actual_file_size,
+ expected_file_size_with_dists,
+ expected_file_size_just_ids)))
+ };
+
+ let mut ids: Vec<u32> = vec![0; npts * dim];
+ let mut buffer = vec![0; npts * dim * size_of::<u32>()];
+ file.read_exact(&mut buffer)?;
+ ids.clone_from_slice(cast_slice::<u8, u32>(&buffer));
+
+ if truthset_type == 1 {
+ let mut dists: Vec<f32> = vec![0.0; npts * dim];
+ let mut buffer = vec![0; npts * dim * size_of::<f32>()];
+ file.read_exact(&mut buffer)?;
+ dists.clone_from_slice(cast_slice::<u8, f32>(&buffer));
+
+ return Ok((ids, Some(dists), npts, dim));
+ }
+
+ Ok((ids, None, npts, dim))
+}
+
+#[inline]
+pub(crate) fn load_aligned_bin<T: Default + Copy + Sized + Pod>(
+ bin_file: &str,
+) -> ANNResult<(AlignedBoxWithSlice<T>, usize, usize, usize)> {
+ let t_size = size_of::<T>();
+ let (npts, dim, file_size): (usize, usize, usize);
+ {
+ println!("Reading (with alignment) bin file: {bin_file}");
+ let mut file = File::open(bin_file)?;
+ file_size = file.metadata()?.len() as usize;
+
+ let mut buffer = [0; size_of::<i32>()];
+ file.read_exact(&mut buffer)?;
+ npts = i32::from_le_bytes(buffer) as usize;
+
+ file.read_exact(&mut buffer)?;
+ dim = i32::from_le_bytes(buffer) as usize;
+ }
+
+ let rounded_dim = round_up(dim, 8);
+ let expected_actual_file_size = npts * dim * size_of::<T>() + 2 * size_of::<u32>();
+
+ if file_size != expected_actual_file_size {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: File size mismatch. Actual size is {} while expected size is {}
+ npts = {}, #dims = {}, aligned_dim = {}",
+ file_size, expected_actual_file_size, npts, dim, rounded_dim
+ )));
+ }
+
+ println!("Metadata: #pts = {npts}, #dims = {dim}, aligned_dim = {rounded_dim}...");
+
+ let alloc_size = npts * rounded_dim;
+ let alignment = 8 * t_size;
+ println!(
+ "allocating aligned memory of {} bytes... ",
+ alloc_size * t_size
+ );
+ if !is_aligned(alloc_size * t_size, alignment) {
+ return Err(ANNError::log_index_error(format!(
+ "Requested memory size is not a multiple of {}. Can not be allocated.",
+ alignment
+ )));
+ }
+
+ let mut data = AlignedBoxWithSlice::<T>::new(alloc_size, alignment)?;
+ let dto = DatasetDto {
+ data: &mut data,
+ rounded_dim,
+ };
+
+ println!("done. Copying data to mem_aligned buffer...");
+
+ let (_, _) = copy_aligned_data_from_file(bin_file, dto, 0)?;
+
+ Ok((data, npts, dim, rounded_dim))
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/Cargo.toml
new file mode 100644
index 0000000..a5be547
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/Cargo.toml
@@ -0,0 +1,45 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "diskann"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+bincode = "1.3.3"
+bit-vec = "0.6.3"
+byteorder = "1.4.3"
+cblas = "0.4.0"
+crossbeam = "0.8.2"
+half = "2.2.1"
+hashbrown = "0.13.2"
+num-traits = "0.2.15"
+once_cell = "1.17.1"
+openblas-src = { version = "0.10.8", features = ["system"] }
+rand = { version = "0.8.5", features = [ "small_rng" ] }
+rayon = "1.7.0"
+serde = { version = "1.0.130", features = ["derive"] }
+thiserror = "1.0.40"
+winapi = { version = "0.3.9", features = ["errhandlingapi", "fileapi", "ioapiset", "handleapi", "winnt", "minwindef", "basetsd", "winerror", "winbase"] }
+
+logger = { path = "../logger" }
+platform = { path = "../platform" }
+vector = { path = "../vector" }
+
+[build-dependencies]
+cc = "1.0.79"
+
+[dev-dependencies]
+approx = "0.5.1"
+criterion = "0.5.1"
+
+
+[[bench]]
+name = "distance_bench"
+harness = false
+
+[[bench]]
+name = "neighbor_bench"
+harness = false
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/distance_bench.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/distance_bench.rs
new file mode 100644
index 0000000..885c95b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/distance_bench.rs
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use criterion::{black_box, criterion_group, criterion_main, Criterion};
+
+use rand::{thread_rng, Rng};
+use vector::{FullPrecisionDistance, Metric};
+
+// make sure the vector is 256-bit (32 bytes) aligned required by _mm256_load_ps
+#[repr(C, align(32))]
+struct Vector32ByteAligned {
+ v: [f32; 256],
+}
+
+fn benchmark_l2_distance_float_rust(c: &mut Criterion) {
+ let (a, b) = prepare_random_aligned_vectors();
+ let mut group = c.benchmark_group("avx-computation");
+ group.sample_size(5000);
+
+ group.bench_function("AVX Rust run", |f| {
+ f.iter(|| {
+ black_box(<[f32; 256]>::distance_compare(
+ black_box(&a.v),
+ black_box(&b.v),
+ Metric::L2,
+ ))
+ })
+ });
+}
+
+// make sure the vector is 256-bit (32 bytes) aligned required by _mm256_load_ps
+fn prepare_random_aligned_vectors() -> (Box<Vector32ByteAligned>, Box<Vector32ByteAligned>) {
+ let a = Box::new(Vector32ByteAligned {
+ v: [(); 256].map(|_| thread_rng().gen_range(0.0..100.0)),
+ });
+
+ let b = Box::new(Vector32ByteAligned {
+ v: [(); 256].map(|_| thread_rng().gen_range(0.0..100.0)),
+ });
+
+ (a, b)
+}
+
+criterion_group!(benches, benchmark_l2_distance_float_rust,);
+criterion_main!(benches);
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/kmeans_bench.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/kmeans_bench.rs
new file mode 100644
index 0000000..c69c16a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/kmeans_bench.rs
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use criterion::{criterion_group, criterion_main, Criterion};
+use diskann::utils::k_means_clustering;
+use rand::Rng;
+
+const NUM_POINTS: usize = 10000;
+const DIM: usize = 100;
+const NUM_CENTERS: usize = 256;
+const MAX_KMEANS_REPS: usize = 12;
+
+fn benchmark_kmeans_rust(c: &mut Criterion) {
+ let mut rng = rand::thread_rng();
+ let data: Vec<f32> = (0..NUM_POINTS * DIM)
+ .map(|_| rng.gen_range(-1.0..1.0))
+ .collect();
+ let centers: Vec<f32> = vec![0.0; NUM_CENTERS * DIM];
+
+ let mut group = c.benchmark_group("kmeans-computation");
+ group.sample_size(500);
+
+ group.bench_function("K-Means Rust run", |f| {
+ f.iter(|| {
+ // let mut centers_copy = centers.clone();
+ let data_copy = data.clone();
+ let mut centers_copy = centers.clone();
+ k_means_clustering(
+ &data_copy,
+ NUM_POINTS,
+ DIM,
+ &mut centers_copy,
+ NUM_CENTERS,
+ MAX_KMEANS_REPS,
+ )
+ })
+ });
+}
+
+fn benchmark_kmeans_c(c: &mut Criterion) {
+ let mut rng = rand::thread_rng();
+ let data: Vec<f32> = (0..NUM_POINTS * DIM)
+ .map(|_| rng.gen_range(-1.0..1.0))
+ .collect();
+ let centers: Vec<f32> = vec![0.0; NUM_CENTERS * DIM];
+
+ let mut group = c.benchmark_group("kmeans-computation");
+ group.sample_size(500);
+
+ group.bench_function("K-Means C++ Run", |f| {
+ f.iter(|| {
+ let data_copy = data.clone();
+ let mut centers_copy = centers.clone();
+ let _ = k_means_clustering(
+ data_copy.as_slice(),
+ NUM_POINTS,
+ DIM,
+ centers_copy.as_mut_slice(),
+ NUM_CENTERS,
+ MAX_KMEANS_REPS,
+ );
+ })
+ });
+}
+
+criterion_group!(benches, benchmark_kmeans_rust, benchmark_kmeans_c);
+
+criterion_main!(benches);
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/neighbor_bench.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/neighbor_bench.rs
new file mode 100644
index 0000000..958acdc
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/benches/neighbor_bench.rs
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::time::Duration;
+
+use criterion::{black_box, criterion_group, criterion_main, Criterion};
+
+use diskann::model::{Neighbor, NeighborPriorityQueue};
+use rand::distributions::{Distribution, Uniform};
+use rand::rngs::StdRng;
+use rand::SeedableRng;
+
+fn benchmark_priority_queue_insert(c: &mut Criterion) {
+ let vec = generate_random_floats();
+ let mut group = c.benchmark_group("neighborqueue-insert");
+ group.measurement_time(Duration::from_secs(3)).sample_size(500);
+
+ let mut queue = NeighborPriorityQueue::with_capacity(64_usize);
+ group.bench_function("Neighbor Priority Queue Insert", |f| {
+ f.iter(|| {
+ queue.clear();
+ for n in vec.iter() {
+ queue.insert(*n);
+ }
+
+ black_box(&1)
+ });
+ });
+}
+
+fn generate_random_floats() -> Vec<Neighbor> {
+ let seed: [u8; 32] = [73; 32];
+ let mut rng: StdRng = SeedableRng::from_seed(seed);
+ let range = Uniform::new(0.0, 1.0);
+ let mut random_floats = Vec::with_capacity(100);
+
+ for i in 0..100 {
+ let random_float = range.sample(&mut rng) as f32;
+ let n = Neighbor::new(i, random_float);
+ random_floats.push(n);
+ }
+
+ random_floats
+}
+
+criterion_group!(benches, benchmark_priority_queue_insert);
+criterion_main!(benches);
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/mod.rs
new file mode 100644
index 0000000..87e377c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/mod.rs
@@ -0,0 +1,7 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub mod search;
+
+pub mod prune;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/prune/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/prune/mod.rs
new file mode 100644
index 0000000..4627eeb
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/prune/mod.rs
@@ -0,0 +1,6 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+pub mod prune;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/prune/prune.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/prune/prune.rs
new file mode 100644
index 0000000..40fec4a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/prune/prune.rs
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use hashbrown::HashSet;
+use vector::{FullPrecisionDistance, Metric};
+
+use crate::common::{ANNError, ANNResult};
+use crate::index::InmemIndex;
+use crate::model::graph::AdjacencyList;
+use crate::model::neighbor::SortedNeighborVector;
+use crate::model::scratch::InMemQueryScratch;
+use crate::model::Neighbor;
+
+impl<T, const N: usize> InmemIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// A method that occludes a list of neighbors based on some criteria
+ #[allow(clippy::too_many_arguments)]
+ fn occlude_list(
+ &self,
+ location: u32,
+ pool: &mut SortedNeighborVector,
+ alpha: f32,
+ degree: u32,
+ max_candidate_size: usize,
+ result: &mut AdjacencyList,
+ scratch: &mut InMemQueryScratch<T, N>,
+ delete_set_ptr: Option<&HashSet<u32>>,
+ ) -> ANNResult<()> {
+ if pool.is_empty() {
+ return Ok(());
+ }
+
+ if !result.is_empty() {
+ return Err(ANNError::log_index_error(
+ "result is not empty.".to_string(),
+ ));
+ }
+
+ // Truncate pool at max_candidate_size and initialize scratch spaces
+ if pool.len() > max_candidate_size {
+ pool.truncate(max_candidate_size);
+ }
+
+ let occlude_factor = &mut scratch.occlude_factor;
+
+ // occlude_list can be called with the same scratch more than once by
+ // search_for_point_and_add_link through inter_insert.
+ occlude_factor.clear();
+
+ // Initialize occlude_factor to pool.len() many 0.0 values for correctness
+ occlude_factor.resize(pool.len(), 0.0);
+
+ let mut cur_alpha = 1.0;
+ while cur_alpha <= alpha && result.len() < degree as usize {
+ for (i, neighbor) in pool.iter().enumerate() {
+ if result.len() >= degree as usize {
+ break;
+ }
+ if occlude_factor[i] > cur_alpha {
+ continue;
+ }
+ // Set the entry to f32::MAX so that is not considered again
+ occlude_factor[i] = f32::MAX;
+
+ // Add the entry to the result if its not been deleted, and doesn't
+ // add a self loop
+ if delete_set_ptr.map_or(true, |delete_set| !delete_set.contains(&neighbor.id))
+ && neighbor.id != location
+ {
+ result.push(neighbor.id);
+ }
+
+ // Update occlude factor for points from i+1 to pool.len()
+ for (j, neighbor2) in pool.iter().enumerate().skip(i + 1) {
+ if occlude_factor[j] > alpha {
+ continue;
+ }
+
+ // todo - self.filtered_index
+ let djk = self.get_distance(neighbor2.id, neighbor.id)?;
+ match self.configuration.dist_metric {
+ Metric::L2 | Metric::Cosine => {
+ occlude_factor[j] = if djk == 0.0 {
+ f32::MAX
+ } else {
+ occlude_factor[j].max(neighbor2.distance / djk)
+ };
+ }
+ }
+ }
+ }
+
+ cur_alpha *= 1.2;
+ }
+
+ Ok(())
+ }
+
+ /// Prunes the neighbors of a given data point based on some criteria and returns a list of pruned ids.
+ ///
+ /// # Arguments
+ ///
+ /// * `location` - The id of the data point whose neighbors are to be pruned.
+ /// * `pool` - A vector of neighbors to be pruned, sorted by distance to the query point.
+ /// * `pruned_list` - A vector to store the ids of the pruned neighbors.
+ /// * `scratch` - A mutable reference to a scratch space for in-memory queries.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `pruned_list` contains more than `range` elements after pruning.
+ pub fn prune_neighbors(
+ &self,
+ location: u32,
+ pool: &mut Vec<Neighbor>,
+ pruned_list: &mut AdjacencyList,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> ANNResult<()> {
+ self.robust_prune(
+ location,
+ pool,
+ self.configuration.index_write_parameter.max_degree,
+ self.configuration.index_write_parameter.max_occlusion_size,
+ self.configuration.index_write_parameter.alpha,
+ pruned_list,
+ scratch,
+ )
+ }
+
+ /// Prunes the neighbors of a given data point based on some criteria and returns a list of pruned ids.
+ ///
+ /// # Arguments
+ ///
+ /// * `location` - The id of the data point whose neighbors are to be pruned.
+ /// * `pool` - A vector of neighbors to be pruned, sorted by distance to the query point.
+ /// * `range` - The maximum number of neighbors to keep after pruning.
+ /// * `max_candidate_size` - The maximum number of candidates to consider for pruning.
+ /// * `alpha` - A parameter that controls the occlusion pruning strategy.
+ /// * `pruned_list` - A vector to store the ids of the pruned neighbors.
+ /// * `scratch` - A mutable reference to a scratch space for in-memory queries.
+ ///
+ /// # Error
+ ///
+ /// Return error if `pruned_list` contains more than `range` elements after pruning.
+ #[allow(clippy::too_many_arguments)]
+ fn robust_prune(
+ &self,
+ location: u32,
+ pool: &mut Vec<Neighbor>,
+ range: u32,
+ max_candidate_size: u32,
+ alpha: f32,
+ pruned_list: &mut AdjacencyList,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> ANNResult<()> {
+ if pool.is_empty() {
+ // if the pool is empty, behave like a noop
+ pruned_list.clear();
+ return Ok(());
+ }
+
+ // If using _pq_build, over-write the PQ distances with actual distances
+ // todo : pq_dist
+
+ // sort the pool based on distance to query and prune it with occlude_list
+ let mut pool = SortedNeighborVector::new(pool);
+ pruned_list.clear();
+
+ self.occlude_list(
+ location,
+ &mut pool,
+ alpha,
+ range,
+ max_candidate_size as usize,
+ pruned_list,
+ scratch,
+ Option::None,
+ )?;
+
+ if pruned_list.len() > range as usize {
+ return Err(ANNError::log_index_error(format!(
+ "pruned_list's len {} is over range {}.",
+ pruned_list.len(),
+ range
+ )));
+ }
+
+ if self.configuration.index_write_parameter.saturate_graph && alpha > 1.0f32 {
+ for neighbor in pool.iter() {
+ if pruned_list.len() >= (range as usize) {
+ break;
+ }
+ if !pruned_list.contains(&neighbor.id) && neighbor.id != location {
+ pruned_list.push(neighbor.id);
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ /// A method that inserts a point n into the graph of its neighbors and their neighbors,
+ /// pruning the graph if necessary to keep it within the specified range
+ /// * `n` - The index of the new point
+ /// * `pruned_list` is a vector of the neighbors of n that have been pruned by a previous step
+ /// * `range` is the target number of neighbors for each point
+ /// * `scratch` is a mutable reference to a scratch space that can be reused for intermediate computations
+ pub fn inter_insert(
+ &self,
+ n: u32,
+ pruned_list: &Vec<u32>,
+ range: u32,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> ANNResult<()> {
+ // Borrow the pruned_list as a source pool of neighbors
+ let src_pool = pruned_list;
+
+ if src_pool.is_empty() {
+ return Err(ANNError::log_index_error("src_pool is empty.".to_string()));
+ }
+
+ for &vertex_id in src_pool {
+ // vertex is the index of a neighbor of n
+ // Assert that vertex is within the valid range of points
+ if (vertex_id as usize)
+ >= self.configuration.max_points + self.configuration.num_frozen_pts
+ {
+ return Err(ANNError::log_index_error(format!(
+ "vertex_id {} is out of valid range of points {}",
+ vertex_id,
+ self.configuration.max_points + self.configuration.num_frozen_pts,
+ )));
+ }
+
+ let neighbors = self.add_to_neighbors(vertex_id, n, range)?;
+
+ if let Some(copy_of_neighbors) = neighbors {
+ // Pruning is needed, create a dummy set and a dummy vector to store the unique neighbors of vertex_id
+ let mut dummy_pool = self.get_unique_neighbors(&copy_of_neighbors, vertex_id)?;
+
+ // Create a new vector to store the pruned neighbors of vertex_id
+ let mut new_out_neighbors =
+ AdjacencyList::for_range(self.configuration.write_range());
+ // Prune the neighbors of vertex_id using a helper method
+ self.prune_neighbors(vertex_id, &mut dummy_pool, &mut new_out_neighbors, scratch)?;
+
+ self.set_neighbors(vertex_id, new_out_neighbors)?;
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Adds a node to the list of neighbors for the given node.
+ ///
+ /// # Arguments
+ ///
+ /// * `vertex_id` - The ID of the node to add the neighbor to.
+ /// * `node_id` - The ID of the node to add.
+ /// * `range` - The range of the graph.
+ ///
+ /// # Return
+ ///
+ /// Returns `None` if the node is already in the list of neighbors, or a `Vec` containing the updated list of neighbors if the list of neighbors is full.
+ fn add_to_neighbors(
+ &self,
+ vertex_id: u32,
+ node_id: u32,
+ range: u32,
+ ) -> ANNResult<Option<Vec<u32>>> {
+ // vertex contains a vector of the neighbors of vertex_id
+ let mut vertex_guard = self.final_graph.write_vertex_and_neighbors(vertex_id)?;
+
+ Ok(vertex_guard.add_to_neighbors(node_id, range))
+ }
+
+ fn set_neighbors(&self, vertex_id: u32, new_out_neighbors: AdjacencyList) -> ANNResult<()> {
+ // vertex contains a vector of the neighbors of vertex_id
+ let mut vertex_guard = self.final_graph.write_vertex_and_neighbors(vertex_id)?;
+
+ vertex_guard.set_neighbors(new_out_neighbors);
+ Ok(())
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/search/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/search/mod.rs
new file mode 100644
index 0000000..9f007ab
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/search/mod.rs
@@ -0,0 +1,7 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+pub mod search;
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/search/search.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/search/search.rs
new file mode 100644
index 0000000..ab6d016
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/algorithm/search/search.rs
@@ -0,0 +1,359 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Search algorithm for index construction and query
+
+use crate::common::{ANNError, ANNResult};
+use crate::index::InmemIndex;
+use crate::model::{scratch::InMemQueryScratch, Neighbor, Vertex};
+use hashbrown::hash_set::Entry::*;
+use vector::FullPrecisionDistance;
+
+impl<T, const N: usize> InmemIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Search for query using given L value, for benchmarking purposes
+ /// # Arguments
+ /// * `query` - query vertex
+ /// * `scratch` - in-memory query scratch
+ /// * `search_list_size` - search list size to use for the benchmark
+ pub fn search_with_l_override(
+ &self,
+ query: &Vertex<T, N>,
+ scratch: &mut InMemQueryScratch<T, N>,
+ search_list_size: usize,
+ ) -> ANNResult<u32> {
+ let init_ids = self.get_init_ids()?;
+ self.init_graph_for_point(query, init_ids, scratch)?;
+ // Scratch is created using largest L val from search_memory_index, so we artifically make it smaller here
+ // This allows us to use the same scratch for all L values without having to rebuild the query scratch
+ scratch.best_candidates.set_capacity(search_list_size);
+ let (_, cmp) = self.greedy_search(query, scratch)?;
+
+ Ok(cmp)
+ }
+
+ /// search for point
+ /// # Arguments
+ /// * `query` - query vertex
+ /// * `scratch` - in-memory query scratch
+ /// TODO: use_filter, filteredLindex
+ pub fn search_for_point(
+ &self,
+ query: &Vertex<T, N>,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> ANNResult<Vec<Neighbor>> {
+ let init_ids = self.get_init_ids()?;
+ self.init_graph_for_point(query, init_ids, scratch)?;
+ let (mut visited_nodes, _) = self.greedy_search(query, scratch)?;
+
+ visited_nodes.retain(|&element| element.id != query.vertex_id());
+ Ok(visited_nodes)
+ }
+
+ /// Returns the locations of start point and frozen points suitable for use with iterate_to_fixed_point.
+ fn get_init_ids(&self) -> ANNResult<Vec<u32>> {
+ let mut init_ids = Vec::with_capacity(1 + self.configuration.num_frozen_pts);
+ init_ids.push(self.start);
+
+ for frozen in self.configuration.max_points
+ ..(self.configuration.max_points + self.configuration.num_frozen_pts)
+ {
+ let frozen_u32 = frozen.try_into()?;
+ if frozen_u32 != self.start {
+ init_ids.push(frozen_u32);
+ }
+ }
+
+ Ok(init_ids)
+ }
+
+ /// Initialize graph for point
+ /// # Arguments
+ /// * `query` - query vertex
+ /// * `init_ids` - initial nodes from which search starts
+ /// * `scratch` - in-memory query scratch
+ /// * `search_list_size_override` - override for search list size in index config
+ fn init_graph_for_point(
+ &self,
+ query: &Vertex<T, N>,
+ init_ids: Vec<u32>,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> ANNResult<()> {
+ scratch
+ .best_candidates
+ .reserve(self.configuration.index_write_parameter.search_list_size as usize);
+ scratch.query.memcpy(query.vector())?;
+
+ if !scratch.id_scratch.is_empty() {
+ return Err(ANNError::log_index_error(
+ "id_scratch is not empty.".to_string(),
+ ));
+ }
+
+ let query_vertex = Vertex::<T, N>::try_from((&scratch.query[..], query.vertex_id()))
+ .map_err(|err| {
+ ANNError::log_index_error(format!(
+ "TryFromSliceError: failed to get Vertex for query, err={}",
+ err
+ ))
+ })?;
+
+ for id in init_ids {
+ if (id as usize) >= self.configuration.max_points + self.configuration.num_frozen_pts {
+ return Err(ANNError::log_index_error(format!(
+ "vertex_id {} is out of valid range of points {}",
+ id,
+ self.configuration.max_points + self.configuration.num_frozen_pts
+ )));
+ }
+
+ if let Vacant(entry) = scratch.node_visited_robinset.entry(id) {
+ entry.insert();
+
+ let vertex = self.dataset.get_vertex(id)?;
+
+ let distance = vertex.compare(&query_vertex, self.configuration.dist_metric);
+ let neighbor = Neighbor::new(id, distance);
+ scratch.best_candidates.insert(neighbor);
+ }
+ }
+
+ Ok(())
+ }
+
+ /// GreedySearch against query node
+ /// Returns visited nodes
+ /// # Arguments
+ /// * `query` - query vertex
+ /// * `scratch` - in-memory query scratch
+ /// TODO: use_filter, filter_label, search_invocation
+ fn greedy_search(
+ &self,
+ query: &Vertex<T, N>,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> ANNResult<(Vec<Neighbor>, u32)> {
+ let mut visited_nodes =
+ Vec::with_capacity((3 * scratch.candidate_size + scratch.max_degree) as usize);
+
+ // TODO: uncomment hops?
+ // let mut hops: u32 = 0;
+ let mut cmps: u32 = 0;
+
+ let query_vertex = Vertex::<T, N>::try_from((&scratch.query[..], query.vertex_id()))
+ .map_err(|err| {
+ ANNError::log_index_error(format!(
+ "TryFromSliceError: failed to get Vertex for query, err={}",
+ err
+ ))
+ })?;
+
+ while scratch.best_candidates.has_notvisited_node() {
+ let closest_node = scratch.best_candidates.closest_notvisited();
+
+ // Add node to visited nodes to create pool for prune later
+ // TODO: search_invocation and use_filter
+ visited_nodes.push(closest_node);
+
+ // Find which of the nodes in des have not been visited before
+ scratch.id_scratch.clear();
+
+ let max_vertex_id = self.configuration.max_points + self.configuration.num_frozen_pts;
+
+ for id in self
+ .final_graph
+ .read_vertex_and_neighbors(closest_node.id)?
+ .get_neighbors()
+ {
+ let current_vertex_id = *id;
+ debug_assert!(
+ (current_vertex_id as usize) < max_vertex_id,
+ "current_vertex_id {} is out of valid range of points {}",
+ current_vertex_id,
+ max_vertex_id
+ );
+ if current_vertex_id as usize >= max_vertex_id {
+ continue;
+ }
+
+ // quickly de-dup. Remember, we are in a read lock
+ // we want to exit out of it quickly
+ if scratch.node_visited_robinset.insert(current_vertex_id) {
+ scratch.id_scratch.push(current_vertex_id);
+ }
+ }
+
+ let len = scratch.id_scratch.len();
+ for (m, &id) in scratch.id_scratch.iter().enumerate() {
+ if m + 1 < len {
+ let next_node = unsafe { *scratch.id_scratch.get_unchecked(m + 1) };
+ self.dataset.prefetch_vector(next_node);
+ }
+
+ let vertex = self.dataset.get_vertex(id)?;
+ let distance = query_vertex.compare(&vertex, self.configuration.dist_metric);
+
+ // Insert <id, dist> pairs into the pool of candidates
+ scratch.best_candidates.insert(Neighbor::new(id, distance));
+ }
+
+ cmps += len as u32;
+ }
+
+ Ok((visited_nodes, cmps))
+ }
+}
+
+#[cfg(test)]
+mod search_test {
+ use vector::Metric;
+
+ use crate::model::configuration::index_write_parameters::IndexWriteParametersBuilder;
+ use crate::model::graph::AdjacencyList;
+ use crate::model::IndexConfiguration;
+ use crate::test_utils::inmem_index_initialization::create_index_with_test_data;
+
+ use super::*;
+
+ #[test]
+ fn get_init_ids_no_forzen_pts() {
+ let index_write_parameters = IndexWriteParametersBuilder::new(50, 4)
+ .with_alpha(1.2)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ 256,
+ 256,
+ 256,
+ false,
+ 0,
+ false,
+ 0,
+ 1f32,
+ index_write_parameters,
+ );
+
+ let index = InmemIndex::<f32, 256>::new(config).unwrap();
+ let init_ids = index.get_init_ids().unwrap();
+ assert_eq!(init_ids.len(), 1);
+ assert_eq!(init_ids[0], 256);
+ }
+
+ #[test]
+ fn get_init_ids_with_forzen_pts() {
+ let index_write_parameters = IndexWriteParametersBuilder::new(50, 4)
+ .with_alpha(1.2)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ 256,
+ 256,
+ 256,
+ false,
+ 0,
+ false,
+ 2,
+ 1f32,
+ index_write_parameters,
+ );
+
+ let index = InmemIndex::<f32, 256>::new(config).unwrap();
+ let init_ids = index.get_init_ids().unwrap();
+ assert_eq!(init_ids.len(), 2);
+ assert_eq!(init_ids[0], 256);
+ assert_eq!(init_ids[1], 257);
+ }
+
+ #[test]
+ fn search_for_point_initial_call() {
+ let index = create_index_with_test_data();
+ let query = index.dataset.get_vertex(0).unwrap();
+
+ let mut scratch = InMemQueryScratch::new(
+ index.configuration.index_write_parameter.search_list_size,
+ &index.configuration.index_write_parameter,
+ false,
+ )
+ .unwrap();
+ let visited_nodes = index.search_for_point(&query, &mut scratch).unwrap();
+ assert_eq!(visited_nodes.len(), 1);
+ assert_eq!(scratch.best_candidates.size(), 1);
+ assert_eq!(scratch.best_candidates[0].id, 72);
+ assert_eq!(scratch.best_candidates[0].distance, 125678.0_f32);
+ assert!(scratch.best_candidates[0].visited);
+ }
+
+ fn set_neighbors(index: &InmemIndex<f32, 128>, vertex_id: u32, neighbors: Vec<u32>) {
+ index
+ .final_graph
+ .write_vertex_and_neighbors(vertex_id)
+ .unwrap()
+ .set_neighbors(AdjacencyList::from(neighbors));
+ }
+ #[test]
+ fn search_for_point_works_with_edges() {
+ let index = create_index_with_test_data();
+ let query = index.dataset.get_vertex(14).unwrap();
+
+ set_neighbors(&index, 0, vec![12, 72, 5, 9]);
+ set_neighbors(&index, 1, vec![2, 12, 10, 4]);
+ set_neighbors(&index, 2, vec![1, 72, 9]);
+ set_neighbors(&index, 3, vec![13, 6, 5, 11]);
+ set_neighbors(&index, 4, vec![1, 3, 7, 9]);
+ set_neighbors(&index, 5, vec![3, 0, 8, 11, 13]);
+ set_neighbors(&index, 6, vec![3, 72, 7, 10, 13]);
+ set_neighbors(&index, 7, vec![72, 4, 6]);
+ set_neighbors(&index, 8, vec![72, 5, 9, 12]);
+ set_neighbors(&index, 9, vec![8, 4, 0, 2]);
+ set_neighbors(&index, 10, vec![72, 1, 9, 6]);
+ set_neighbors(&index, 11, vec![3, 0, 5]);
+ set_neighbors(&index, 12, vec![1, 0, 8, 9]);
+ set_neighbors(&index, 13, vec![3, 72, 5, 6]);
+ set_neighbors(&index, 72, vec![7, 2, 10, 8, 13]);
+
+ let mut scratch = InMemQueryScratch::new(
+ index.configuration.index_write_parameter.search_list_size,
+ &index.configuration.index_write_parameter,
+ false,
+ )
+ .unwrap();
+ let visited_nodes = index.search_for_point(&query, &mut scratch).unwrap();
+ assert_eq!(visited_nodes.len(), 15);
+ assert_eq!(scratch.best_candidates.size(), 15);
+ assert_eq!(scratch.best_candidates[0].id, 2);
+ assert_eq!(scratch.best_candidates[0].distance, 120899.0_f32);
+ assert_eq!(scratch.best_candidates[1].id, 8);
+ assert_eq!(scratch.best_candidates[1].distance, 145538.0_f32);
+ assert_eq!(scratch.best_candidates[2].id, 72);
+ assert_eq!(scratch.best_candidates[2].distance, 146046.0_f32);
+ assert_eq!(scratch.best_candidates[3].id, 4);
+ assert_eq!(scratch.best_candidates[3].distance, 148462.0_f32);
+ assert_eq!(scratch.best_candidates[4].id, 7);
+ assert_eq!(scratch.best_candidates[4].distance, 148912.0_f32);
+ assert_eq!(scratch.best_candidates[5].id, 10);
+ assert_eq!(scratch.best_candidates[5].distance, 154570.0_f32);
+ assert_eq!(scratch.best_candidates[6].id, 1);
+ assert_eq!(scratch.best_candidates[6].distance, 159448.0_f32);
+ assert_eq!(scratch.best_candidates[7].id, 12);
+ assert_eq!(scratch.best_candidates[7].distance, 170698.0_f32);
+ assert_eq!(scratch.best_candidates[8].id, 9);
+ assert_eq!(scratch.best_candidates[8].distance, 177205.0_f32);
+ assert_eq!(scratch.best_candidates[9].id, 0);
+ assert_eq!(scratch.best_candidates[9].distance, 259996.0_f32);
+ assert_eq!(scratch.best_candidates[10].id, 6);
+ assert_eq!(scratch.best_candidates[10].distance, 371819.0_f32);
+ assert_eq!(scratch.best_candidates[11].id, 5);
+ assert_eq!(scratch.best_candidates[11].distance, 385240.0_f32);
+ assert_eq!(scratch.best_candidates[12].id, 3);
+ assert_eq!(scratch.best_candidates[12].distance, 413899.0_f32);
+ assert_eq!(scratch.best_candidates[13].id, 13);
+ assert_eq!(scratch.best_candidates[13].distance, 416386.0_f32);
+ assert_eq!(scratch.best_candidates[14].id, 11);
+ assert_eq!(scratch.best_candidates[14].distance, 449266.0_f32);
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/aligned_allocator.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/aligned_allocator.rs
new file mode 100644
index 0000000..6164a1f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/aligned_allocator.rs
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Aligned allocator
+
+use std::alloc::Layout;
+use std::ops::{Deref, DerefMut, Range};
+use std::ptr::copy_nonoverlapping;
+
+use super::{ANNResult, ANNError};
+
+#[derive(Debug)]
+/// A box that holds a slice but is aligned to the specified layout.
+///
+/// This type is useful for working with types that require a certain alignment,
+/// such as SIMD vectors or FFI structs. It allocates memory using the global allocator
+/// and frees it when dropped. It also implements Deref and DerefMut to allow access
+/// to the underlying slice.
+pub struct AlignedBoxWithSlice<T> {
+ /// The layout of the allocated memory.
+ layout: Layout,
+
+ /// The slice that points to the allocated memory.
+ val: Box<[T]>,
+}
+
+impl<T> AlignedBoxWithSlice<T> {
+ /// Creates a new `AlignedBoxWithSlice` with the given capacity and alignment.
+ /// The allocated memory are set to 0.
+ ///
+ /// # Error
+ ///
+ /// Return IndexError if the alignment is not a power of two or if the layout is invalid.
+ ///
+ /// This function is unsafe because it allocates uninitialized memory and casts it to
+ /// a slice of `T`. The caller must ensure that the capacity and alignment are valid
+ /// for the type `T` and that the memory is initialized before accessing the elements
+ /// of the slice.
+ pub fn new(capacity: usize, alignment: usize) -> ANNResult<Self> {
+ let allocsize = capacity.checked_mul(std::mem::size_of::<T>())
+ .ok_or_else(|| ANNError::log_index_error("capacity overflow".to_string()))?;
+ let layout = Layout::from_size_align(allocsize, alignment)
+ .map_err(ANNError::log_mem_alloc_layout_error)?;
+
+ let val = unsafe {
+ let mem = std::alloc::alloc_zeroed(layout);
+ let ptr = mem as *mut T;
+ let slice = std::slice::from_raw_parts_mut(ptr, capacity);
+ std::boxed::Box::from_raw(slice)
+ };
+
+ Ok(Self { layout, val })
+ }
+
+ /// Returns a reference to the slice.
+ pub fn as_slice(&self) -> &[T] {
+ &self.val
+ }
+
+ /// Returns a mutable reference to the slice.
+ pub fn as_mut_slice(&mut self) -> &mut [T] {
+ &mut self.val
+ }
+
+ /// Copies data from the source slice to the destination box.
+ pub fn memcpy(&mut self, src: &[T]) -> ANNResult<()> {
+ if src.len() > self.val.len() {
+ return Err(ANNError::log_index_error(format!("source slice is too large (src:{}, dst:{})", src.len(), self.val.len())));
+ }
+
+ // Check that they don't overlap
+ let src_ptr = src.as_ptr();
+ let src_end = unsafe { src_ptr.add(src.len()) };
+ let dst_ptr = self.val.as_mut_ptr();
+ let dst_end = unsafe { dst_ptr.add(self.val.len()) };
+
+ if src_ptr < dst_end && src_end > dst_ptr {
+ return Err(ANNError::log_index_error("Source and destination overlap".to_string()));
+ }
+
+ unsafe {
+ copy_nonoverlapping(src.as_ptr(), self.val.as_mut_ptr(), src.len());
+ }
+
+ Ok(())
+ }
+
+ /// Split the range of memory into nonoverlapping mutable slices.
+ /// The number of returned slices is (range length / slice_len) and each has a length of slice_len.
+ pub fn split_into_nonoverlapping_mut_slices(&mut self, range: Range<usize>, slice_len: usize) -> ANNResult<Vec<&mut [T]>> {
+ if range.len() % slice_len != 0 || range.end > self.len() {
+ return Err(ANNError::log_index_error(format!(
+ "Cannot split range ({:?}) of AlignedBoxWithSlice (len: {}) into nonoverlapping mutable slices with length {}",
+ range,
+ self.len(),
+ slice_len,
+ )));
+ }
+
+ let mut slices = Vec::with_capacity(range.len() / slice_len);
+ let mut remaining_slice = &mut self.val[range];
+
+ while remaining_slice.len() >= slice_len {
+ let (left, right) = remaining_slice.split_at_mut(slice_len);
+ slices.push(left);
+ remaining_slice = right;
+ }
+
+ Ok(slices)
+ }
+}
+
+
+impl<T> Drop for AlignedBoxWithSlice<T> {
+ /// Frees the memory allocated for the slice using the global allocator.
+ fn drop(&mut self) {
+ let val = std::mem::take(&mut self.val);
+ let mut val2 = std::mem::ManuallyDrop::new(val);
+ let ptr = val2.as_mut_ptr();
+
+ unsafe {
+ // let nonNull = NonNull::new_unchecked(ptr as *mut u8);
+ std::alloc::dealloc(ptr as *mut u8, self.layout)
+ }
+ }
+}
+
+impl<T> Deref for AlignedBoxWithSlice<T> {
+ type Target = [T];
+
+ fn deref(&self) -> &Self::Target {
+ &self.val
+ }
+}
+
+impl<T> DerefMut for AlignedBoxWithSlice<T> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.val
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use rand::Rng;
+
+ use crate::utils::is_aligned;
+
+ use super::*;
+
+ #[test]
+ fn create_alignedvec_works_32() {
+ (0..100).for_each(|_| {
+ let size = 1_000_000;
+ println!("Attempting {}", size);
+ let data = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ assert_eq!(data.len(), size, "Capacity should match");
+
+ let ptr = data.as_ptr() as usize;
+ assert_eq!(ptr % 32, 0, "Ptr should be aligned to 32");
+
+ // assert that the slice is initialized.
+ (0..size).for_each(|i| {
+ assert_eq!(data[i], f32::default());
+ });
+
+ drop(data);
+ });
+ }
+
+ #[test]
+ fn create_alignedvec_works_256() {
+ let mut rng = rand::thread_rng();
+
+ (0..100).for_each(|_| {
+ let n = rng.gen::<u8>();
+ let size = usize::from(n) + 1;
+ println!("Attempting {}", size);
+ let data = AlignedBoxWithSlice::<u8>::new(size, 256).unwrap();
+ assert_eq!(data.len(), size, "Capacity should match");
+
+ let ptr = data.as_ptr() as usize;
+ assert_eq!(ptr % 256, 0, "Ptr should be aligned to 32");
+
+ // assert that the slice is initialized.
+ (0..size).for_each(|i| {
+ assert_eq!(data[i], u8::default());
+ });
+
+ drop(data);
+ });
+ }
+
+ #[test]
+ fn as_slice_test() {
+ let size = 1_000_000;
+ let data = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ // assert that the slice is initialized.
+ (0..size).for_each(|i| {
+ assert_eq!(data[i], f32::default());
+ });
+
+ let slice = data.as_slice();
+ (0..size).for_each(|i| {
+ assert_eq!(slice[i], f32::default());
+ });
+ }
+
+ #[test]
+ fn as_mut_slice_test() {
+ let size = 1_000_000;
+ let mut data = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ let mut_slice = data.as_mut_slice();
+ (0..size).for_each(|i| {
+ assert_eq!(mut_slice[i], f32::default());
+ });
+ }
+
+ #[test]
+ fn memcpy_test() {
+ let size = 1_000_000;
+ let mut data = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ let mut destination = AlignedBoxWithSlice::<f32>::new(size-2, 32).unwrap();
+ let mut_destination = destination.as_mut_slice();
+ data.memcpy(mut_destination).unwrap();
+ (0..size-2).for_each(|i| {
+ assert_eq!(data[i], mut_destination[i]);
+ });
+ }
+
+ #[test]
+ #[should_panic(expected = "source slice is too large (src:1000000, dst:999998)")]
+ fn memcpy_panic_test() {
+ let size = 1_000_000;
+ let mut data = AlignedBoxWithSlice::<f32>::new(size-2, 32).unwrap();
+ let mut destination = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ let mut_destination = destination.as_mut_slice();
+ data.memcpy(mut_destination).unwrap();
+ }
+
+ #[test]
+ fn is_aligned_test() {
+ assert!(is_aligned(256,256));
+ assert!(!is_aligned(255,256));
+ }
+
+ #[test]
+ fn split_into_nonoverlapping_mut_slices_test() {
+ let size = 10;
+ let slice_len = 2;
+ let mut data = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ let slices = data.split_into_nonoverlapping_mut_slices(2..8, slice_len).unwrap();
+ assert_eq!(slices.len(), 3);
+ for (i, slice) in slices.into_iter().enumerate() {
+ assert_eq!(slice.len(), slice_len);
+ slice[0] = i as f32 + 1.0;
+ slice[1] = i as f32 + 1.0;
+ }
+ let expected_arr = [0.0f32, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 0.0, 0.0];
+ assert_eq!(data.as_ref(), &expected_arr);
+ }
+
+ #[test]
+ fn split_into_nonoverlapping_mut_slices_error_when_indivisible() {
+ let size = 10;
+ let slice_len = 2;
+ let range = 2..7;
+ let mut data = AlignedBoxWithSlice::<f32>::new(size, 32).unwrap();
+ let result = data.split_into_nonoverlapping_mut_slices(range.clone(), slice_len);
+ let expected_err_str = format!(
+ "IndexError: Cannot split range ({:?}) of AlignedBoxWithSlice (len: {}) into nonoverlapping mutable slices with length {}",
+ range,
+ size,
+ slice_len,
+ );
+ assert!(result.is_err_and(|e| e.to_string() == expected_err_str));
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/ann_result.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/ann_result.rs
new file mode 100644
index 0000000..69fcf03
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/ann_result.rs
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::alloc::LayoutError;
+use std::array::TryFromSliceError;
+use std::io;
+use std::num::TryFromIntError;
+
+use logger::error_logger::log_error;
+use logger::log_error::LogError;
+
+/// Result
+pub type ANNResult<T> = Result<T, ANNError>;
+
+/// DiskANN Error
+/// ANNError is `Send` (i.e., safe to send across threads)
+#[derive(thiserror::Error, Debug)]
+pub enum ANNError {
+ /// Index construction and search error
+ #[error("IndexError: {err}")]
+ IndexError { err: String },
+
+ /// Index configuration error
+ #[error("IndexConfigError: {parameter} is invalid, err={err}")]
+ IndexConfigError { parameter: String, err: String },
+
+ /// Integer conversion error
+ #[error("TryFromIntError: {err}")]
+ TryFromIntError {
+ #[from]
+ err: TryFromIntError,
+ },
+
+ /// IO error
+ #[error("IOError: {err}")]
+ IOError {
+ #[from]
+ err: io::Error,
+ },
+
+ /// Layout error in memory allocation
+ #[error("MemoryAllocLayoutError: {err}")]
+ MemoryAllocLayoutError {
+ #[from]
+ err: LayoutError,
+ },
+
+ /// PoisonError which can be returned whenever a lock is acquired
+ /// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock is held
+ #[error("LockPoisonError: {err}")]
+ LockPoisonError { err: String },
+
+ /// DiskIOAlignmentError which can be returned when calling windows API CreateFileA for the disk index file fails.
+ #[error("DiskIOAlignmentError: {err}")]
+ DiskIOAlignmentError { err: String },
+
+ /// Logging error
+ #[error("LogError: {err}")]
+ LogError {
+ #[from]
+ err: LogError,
+ },
+
+ // PQ construction error
+ // Error happened when we construct PQ pivot or PQ compressed table
+ #[error("PQError: {err}")]
+ PQError { err: String },
+
+ /// Array conversion error
+ #[error("Error try creating array from slice: {err}")]
+ TryFromSliceError {
+ #[from]
+ err: TryFromSliceError,
+ },
+}
+
+impl ANNError {
+ /// Create, log and return IndexError
+ #[inline]
+ pub fn log_index_error(err: String) -> Self {
+ let ann_err = ANNError::IndexError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return IndexConfigError
+ #[inline]
+ pub fn log_index_config_error(parameter: String, err: String) -> Self {
+ let ann_err = ANNError::IndexConfigError { parameter, err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return TryFromIntError
+ #[inline]
+ pub fn log_try_from_int_error(err: TryFromIntError) -> Self {
+ let ann_err = ANNError::TryFromIntError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return IOError
+ #[inline]
+ pub fn log_io_error(err: io::Error) -> Self {
+ let ann_err = ANNError::IOError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return DiskIOAlignmentError
+ /// #[inline]
+ pub fn log_disk_io_request_alignment_error(err: String) -> Self {
+ let ann_err: ANNError = ANNError::DiskIOAlignmentError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return IOError
+ #[inline]
+ pub fn log_mem_alloc_layout_error(err: LayoutError) -> Self {
+ let ann_err = ANNError::MemoryAllocLayoutError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return LockPoisonError
+ #[inline]
+ pub fn log_lock_poison_error(err: String) -> Self {
+ let ann_err = ANNError::LockPoisonError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return PQError
+ #[inline]
+ pub fn log_pq_error(err: String) -> Self {
+ let ann_err = ANNError::PQError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+
+ /// Create, log and return TryFromSliceError
+ #[inline]
+ pub fn log_try_from_slice_error(err: TryFromSliceError) -> Self {
+ let ann_err = ANNError::TryFromSliceError { err };
+ match log_error(ann_err.to_string()) {
+ Ok(()) => ann_err,
+ Err(log_err) => ANNError::LogError { err: log_err },
+ }
+ }
+}
+
+#[cfg(test)]
+mod ann_result_test {
+ use super::*;
+
+ #[test]
+ fn ann_err_is_send() {
+ fn assert_send<T: Send>() {}
+ assert_send::<ANNError>();
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/mod.rs
new file mode 100644
index 0000000..d9da72b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/common/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+mod aligned_allocator;
+pub use aligned_allocator::AlignedBoxWithSlice;
+
+mod ann_result;
+pub use ann_result::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/ann_disk_index.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/ann_disk_index.rs
new file mode 100644
index 0000000..a6e053e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/ann_disk_index.rs
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_docs)]
+
+//! ANN disk index abstraction
+
+use vector::FullPrecisionDistance;
+
+use crate::model::{IndexConfiguration, DiskIndexBuildParameters};
+use crate::storage::DiskIndexStorage;
+use crate::model::vertex::{DIM_128, DIM_256, DIM_104};
+
+use crate::common::{ANNResult, ANNError};
+
+use super::DiskIndex;
+
+/// ANN disk index abstraction for custom <T, N>
+pub trait ANNDiskIndex<T> : Sync + Send
+where T : Default + Copy + Sync + Send + Into<f32>
+ {
+ /// Build index
+ fn build(&mut self, codebook_prefix: &str) -> ANNResult<()>;
+}
+
+/// Create Index<T, N> based on configuration
+pub fn create_disk_index<'a, T>(
+ disk_build_param: Option<DiskIndexBuildParameters>,
+ config: IndexConfiguration,
+ storage: DiskIndexStorage<T>,
+) -> ANNResult<Box<dyn ANNDiskIndex<T> + 'a>>
+where
+ T: Default + Copy + Sync + Send + Into<f32> + 'a,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
+{
+ match config.aligned_dim {
+ DIM_104 => {
+ let index = Box::new(DiskIndex::<T, DIM_104>::new(disk_build_param, config, storage));
+ Ok(index as Box<dyn ANNDiskIndex<T>>)
+ },
+ DIM_128 => {
+ let index = Box::new(DiskIndex::<T, DIM_128>::new(disk_build_param, config, storage));
+ Ok(index as Box<dyn ANNDiskIndex<T>>)
+ },
+ DIM_256 => {
+ let index = Box::new(DiskIndex::<T, DIM_256>::new(disk_build_param, config, storage));
+ Ok(index as Box<dyn ANNDiskIndex<T>>)
+ },
+ _ => Err(ANNError::log_index_error(format!("Invalid dimension: {}", config.aligned_dim))),
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/disk_index.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/disk_index.rs
new file mode 100644
index 0000000..16f0d59
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/disk_index.rs
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::mem;
+
+use logger::logger::indexlog::DiskIndexConstructionCheckpoint;
+use vector::FullPrecisionDistance;
+
+use crate::common::{ANNResult, ANNError};
+use crate::index::{InmemIndex, ANNInmemIndex};
+use crate::instrumentation::DiskIndexBuildLogger;
+use crate::model::configuration::DiskIndexBuildParameters;
+use crate::model::{IndexConfiguration, MAX_PQ_TRAINING_SET_SIZE, MAX_PQ_CHUNKS, generate_quantized_data, GRAPH_SLACK_FACTOR};
+use crate::storage::DiskIndexStorage;
+use crate::utils::set_rayon_num_threads;
+
+use super::ann_disk_index::ANNDiskIndex;
+
+pub const OVERHEAD_FACTOR: f64 = 1.1f64;
+
+pub const MAX_SAMPLE_POINTS_FOR_WARMUP: usize = 100_000;
+
+pub struct DiskIndex<T, const N: usize>
+where
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Parameters for index construction
+ /// None for query path
+ disk_build_param: Option<DiskIndexBuildParameters>,
+
+ configuration: IndexConfiguration,
+
+ pub storage: DiskIndexStorage<T>,
+}
+
+impl<T, const N: usize> DiskIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ pub fn new(
+ disk_build_param: Option<DiskIndexBuildParameters>,
+ configuration: IndexConfiguration,
+ storage: DiskIndexStorage<T>,
+ ) -> Self {
+ Self {
+ disk_build_param,
+ configuration,
+ storage,
+ }
+ }
+
+ pub fn disk_build_param(&self) -> &Option<DiskIndexBuildParameters> {
+ &self.disk_build_param
+ }
+
+ pub fn index_configuration(&self) -> &IndexConfiguration {
+ &self.configuration
+ }
+
+ fn build_inmem_index(&self, num_points: usize, data_path: &str, inmem_index_path: &str) -> ANNResult<()> {
+ let estimated_index_ram = self.estimate_ram_usage(num_points);
+ if estimated_index_ram >= self.fetch_disk_build_param()?.index_build_ram_limit() * 1024_f64 * 1024_f64 * 1024_f64 {
+ return Err(ANNError::log_index_error(format!(
+ "Insufficient memory budget for index build, index_build_ram_limit={}GB estimated_index_ram={}GB",
+ self.fetch_disk_build_param()?.index_build_ram_limit(),
+ estimated_index_ram / (1024_f64 * 1024_f64 * 1024_f64),
+ )));
+ }
+
+ let mut index = InmemIndex::<T, N>::new(self.configuration.clone())?;
+ index.build(data_path, num_points)?;
+ index.save(inmem_index_path)?;
+
+ Ok(())
+ }
+
+ #[inline]
+ fn estimate_ram_usage(&self, size: usize) -> f64 {
+ let degree = self.configuration.index_write_parameter.max_degree as usize;
+ let datasize = mem::size_of::<T>();
+
+ let dataset_size = (size * N * datasize) as f64;
+ let graph_size = (size * degree * mem::size_of::<u32>()) as f64 * GRAPH_SLACK_FACTOR;
+
+ OVERHEAD_FACTOR * (dataset_size + graph_size)
+ }
+
+ #[inline]
+ fn fetch_disk_build_param(&self) -> ANNResult<&DiskIndexBuildParameters> {
+ self.disk_build_param
+ .as_ref()
+ .ok_or_else(|| ANNError::log_index_config_error(
+ "disk_build_param".to_string(),
+ "disk_build_param is None".to_string()))
+ }
+}
+
+impl<T, const N: usize> ANNDiskIndex<T> for DiskIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ fn build(&mut self, codebook_prefix: &str) -> ANNResult<()> {
+ if self.configuration.index_write_parameter.num_threads > 0 {
+ set_rayon_num_threads(self.configuration.index_write_parameter.num_threads);
+ }
+
+ println!("Starting index build: R={} L={} Query RAM budget={} Indexing RAM budget={} T={}",
+ self.configuration.index_write_parameter.max_degree,
+ self.configuration.index_write_parameter.search_list_size,
+ self.fetch_disk_build_param()?.search_ram_limit(),
+ self.fetch_disk_build_param()?.index_build_ram_limit(),
+ self.configuration.index_write_parameter.num_threads
+ );
+
+ let mut logger = DiskIndexBuildLogger::new(DiskIndexConstructionCheckpoint::PqConstruction);
+
+ // PQ memory consumption = PQ pivots + PQ compressed table
+ // PQ pivots: dim * num_centroids * sizeof::<T>()
+ // PQ compressed table: num_pts * num_pq_chunks * (dim / num_pq_chunks) * sizeof::<u8>()
+ // * Because num_centroids is 256, centroid id can be represented by u8
+ let num_points = self.configuration.max_points;
+ let dim = self.configuration.dim;
+ let p_val = MAX_PQ_TRAINING_SET_SIZE / (num_points as f64);
+ let mut num_pq_chunks = ((self.fetch_disk_build_param()?.search_ram_limit() / (num_points as f64)).floor()) as usize;
+ num_pq_chunks = if num_pq_chunks == 0 { 1 } else { num_pq_chunks };
+ num_pq_chunks = if num_pq_chunks > dim { dim } else { num_pq_chunks };
+ num_pq_chunks = if num_pq_chunks > MAX_PQ_CHUNKS { MAX_PQ_CHUNKS } else { num_pq_chunks };
+
+ println!("Compressing {}-dimensional data into {} bytes per vector.", dim, num_pq_chunks);
+
+ // TODO: Decouple PQ from file access
+ generate_quantized_data::<T>(
+ p_val,
+ num_pq_chunks,
+ codebook_prefix,
+ self.storage.get_pq_storage(),
+ )?;
+ logger.log_checkpoint(DiskIndexConstructionCheckpoint::InmemIndexBuild)?;
+
+ // TODO: Decouple index from file access
+ let inmem_index_path = self.storage.index_path_prefix().clone() + "_mem.index";
+ self.build_inmem_index(num_points, self.storage.dataset_file(), inmem_index_path.as_str())?;
+ logger.log_checkpoint(DiskIndexConstructionCheckpoint::DiskLayout)?;
+
+ self.storage.create_disk_layout()?;
+ logger.log_checkpoint(DiskIndexConstructionCheckpoint::None)?;
+
+ let ten_percent_points = ((num_points as f64) * 0.1_f64).ceil();
+ let num_sample_points = if ten_percent_points > (MAX_SAMPLE_POINTS_FOR_WARMUP as f64) { MAX_SAMPLE_POINTS_FOR_WARMUP as f64 } else { ten_percent_points };
+ let sample_sampling_rate = num_sample_points / (num_points as f64);
+ self.storage.gen_query_warmup_data(sample_sampling_rate)?;
+
+ self.storage.index_build_cleanup()?;
+
+ Ok(())
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/mod.rs
new file mode 100644
index 0000000..4f07bd7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/disk_index/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod disk_index;
+pub use disk_index::DiskIndex;
+
+pub mod ann_disk_index;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/ann_inmem_index.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/ann_inmem_index.rs
new file mode 100644
index 0000000..dc8dfc8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/ann_inmem_index.rs
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_docs)]
+
+//! ANN in-memory index abstraction
+
+use vector::FullPrecisionDistance;
+
+use crate::model::{vertex::{DIM_128, DIM_256, DIM_104}, IndexConfiguration};
+use crate::common::{ANNResult, ANNError};
+
+use super::InmemIndex;
+
+/// ANN inmem-index abstraction for custom <T, N>
+pub trait ANNInmemIndex<T> : Sync + Send
+where T : Default + Copy + Sync + Send + Into<f32>
+ {
+ /// Build index
+ fn build(&mut self, filename: &str, num_points_to_load: usize) -> ANNResult<()>;
+
+ /// Save index
+ fn save(&mut self, filename: &str) -> ANNResult<()>;
+
+ /// Load index
+ fn load(&mut self, filename: &str, expected_num_points: usize) -> ANNResult<()>;
+
+ /// insert index
+ fn insert(&mut self, filename: &str, num_points_to_insert: usize) -> ANNResult<()>;
+
+ /// Search the index for K nearest neighbors of query using given L value, for benchmarking purposes
+ fn search(&self, query : &[T], k_value : usize, l_value : u32, indices : &mut[u32]) -> ANNResult<u32>;
+
+ /// Soft deletes the nodes with the ids in the given array.
+ fn soft_delete(&mut self, vertex_ids_to_delete: Vec<u32>, num_points_to_delete: usize) -> ANNResult<()>;
+}
+
+/// Create Index<T, N> based on configuration
+pub fn create_inmem_index<'a, T>(config: IndexConfiguration) -> ANNResult<Box<dyn ANNInmemIndex<T> + 'a>>
+where
+ T: Default + Copy + Sync + Send + Into<f32> + 'a,
+ [T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
+ [T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
+ [T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
+{
+ match config.aligned_dim {
+ DIM_104 => {
+ let index = Box::new(InmemIndex::<T, DIM_104>::new(config)?);
+ Ok(index as Box<dyn ANNInmemIndex<T>>)
+ },
+ DIM_128 => {
+ let index = Box::new(InmemIndex::<T, DIM_128>::new(config)?);
+ Ok(index as Box<dyn ANNInmemIndex<T>>)
+ },
+ DIM_256 => {
+ let index = Box::new(InmemIndex::<T, DIM_256>::new(config)?);
+ Ok(index as Box<dyn ANNInmemIndex<T>>)
+ },
+ _ => Err(ANNError::log_index_error(format!("Invalid dimension: {}", config.aligned_dim))),
+ }
+}
+
+#[cfg(test)]
+mod dataset_test {
+ use vector::Metric;
+
+ use crate::model::configuration::index_write_parameters::IndexWriteParametersBuilder;
+
+ use super::*;
+
+ #[test]
+ #[should_panic(expected = "ERROR: Data file fake_file does not exist.")]
+ fn create_index_test() {
+ let index_write_parameters = IndexWriteParametersBuilder::new(50, 4)
+ .with_alpha(1.2)
+ .with_saturate_graph(false)
+ .with_num_threads(1)
+ .build();
+
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ 128,
+ 256,
+ 1_000_000,
+ false,
+ 0,
+ false,
+ 0,
+ 1f32,
+ index_write_parameters,
+ );
+ let mut index = create_inmem_index::<f32>(config).unwrap();
+ index.build("fake_file", 100).unwrap();
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/inmem_index.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/inmem_index.rs
new file mode 100644
index 0000000..871d210
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/inmem_index.rs
@@ -0,0 +1,1033 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::cmp;
+use std::sync::RwLock;
+use std::time::Duration;
+
+use hashbrown::hash_set::Entry::*;
+use hashbrown::HashSet;
+use vector::FullPrecisionDistance;
+
+use crate::common::{ANNError, ANNResult};
+use crate::index::ANNInmemIndex;
+use crate::instrumentation::IndexLogger;
+use crate::model::graph::AdjacencyList;
+use crate::model::{
+ ArcConcurrentBoxedQueue, InMemQueryScratch, InMemoryGraph, IndexConfiguration, InmemDataset,
+ Neighbor, ScratchStoreManager, Vertex,
+};
+
+use crate::utils::file_util::{file_exists, load_metadata_from_file};
+use crate::utils::rayon_util::execute_with_rayon;
+use crate::utils::{set_rayon_num_threads, Timer};
+
+/// In-memory Index
+pub struct InmemIndex<T, const N: usize>
+where
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Dataset
+ pub dataset: InmemDataset<T, N>,
+
+ /// Graph
+ pub final_graph: InMemoryGraph,
+
+ /// Index configuration
+ pub configuration: IndexConfiguration,
+
+ /// Start point of the search. When _num_frozen_pts is greater than zero,
+ /// this is the location of the first frozen point. Otherwise, this is a
+ /// location of one of the points in index.
+ pub start: u32,
+
+ /// Max observed out degree
+ pub max_observed_degree: u32,
+
+ /// Number of active points i.e. existing in the graph
+ pub num_active_pts: usize,
+
+ /// query scratch queue.
+ query_scratch_queue: ArcConcurrentBoxedQueue<InMemQueryScratch<T, N>>,
+
+ pub delete_set: RwLock<HashSet<u32>>,
+}
+
+impl<T, const N: usize> InmemIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Create Index obj based on configuration
+ pub fn new(mut config: IndexConfiguration) -> ANNResult<Self> {
+ // Sanity check. While logically it is correct, max_points = 0 causes
+ // downstream problems.
+ if config.max_points == 0 {
+ config.max_points = 1;
+ }
+
+ let total_internal_points = config.max_points + config.num_frozen_pts;
+
+ if config.use_pq_dist {
+ // TODO: pq
+ todo!("PQ is not supported now");
+ }
+
+ let start = config.max_points.try_into()?;
+
+ let query_scratch_queue = ArcConcurrentBoxedQueue::<InMemQueryScratch<T, N>>::new();
+ let delete_set = RwLock::new(HashSet::<u32>::new());
+
+ Ok(Self {
+ dataset: InmemDataset::<T, N>::new(total_internal_points, config.growth_potential)?,
+ final_graph: InMemoryGraph::new(
+ total_internal_points,
+ config.index_write_parameter.max_degree,
+ ),
+ configuration: config,
+ start,
+ max_observed_degree: 0,
+ num_active_pts: 0,
+ query_scratch_queue,
+ delete_set,
+ })
+ }
+
+ /// Get distance between two vertices.
+ pub fn get_distance(&self, id1: u32, id2: u32) -> ANNResult<f32> {
+ self.dataset
+ .get_distance(id1, id2, self.configuration.dist_metric)
+ }
+
+ fn build_with_data_populated(&mut self) -> ANNResult<()> {
+ println!(
+ "Starting index build with {} points...",
+ self.num_active_pts
+ );
+
+ if self.num_active_pts < 1 {
+ return Err(ANNError::log_index_error(
+ "Error: Trying to build an index with 0 points.".to_string(),
+ ));
+ }
+
+ if self.query_scratch_queue.size()? == 0 {
+ self.initialize_query_scratch(
+ 5 + self.configuration.index_write_parameter.num_threads,
+ self.configuration.index_write_parameter.search_list_size,
+ )?;
+ }
+
+ // TODO: generate_frozen_point()
+
+ self.link()?;
+
+ self.print_stats()?;
+
+ Ok(())
+ }
+
+ fn link(&mut self) -> ANNResult<()> {
+ // visit_order is a vector that is initialized to the entire graph
+ let mut visit_order =
+ Vec::with_capacity(self.num_active_pts + self.configuration.num_frozen_pts);
+ for i in 0..self.num_active_pts {
+ visit_order.push(i as u32);
+ }
+
+ // If there are any frozen points, add them all.
+ for frozen in self.configuration.max_points
+ ..(self.configuration.max_points + self.configuration.num_frozen_pts)
+ {
+ visit_order.push(frozen as u32);
+ }
+
+ // if there are frozen points, the first such one is set to be the _start
+ if self.configuration.num_frozen_pts > 0 {
+ self.start = self.configuration.max_points as u32;
+ } else {
+ self.start = self.dataset.calculate_medoid_point_id()?;
+ }
+
+ let timer = Timer::new();
+
+ let range = visit_order.len();
+ let logger = IndexLogger::new(range);
+
+ execute_with_rayon(
+ 0..range,
+ self.configuration.index_write_parameter.num_threads,
+ |idx| {
+ self.insert_vertex_id(visit_order[idx])?;
+ logger.vertex_processed()?;
+
+ Ok(())
+ },
+ )?;
+
+ self.cleanup_graph(&visit_order)?;
+
+ if self.num_active_pts > 0 {
+ println!("{}", timer.elapsed_seconds_for_step("Link time: "));
+ }
+
+ Ok(())
+ }
+
+ fn insert_vertex_id(&self, vertex_id: u32) -> ANNResult<()> {
+ let mut scratch_manager =
+ ScratchStoreManager::new(self.query_scratch_queue.clone(), Duration::from_millis(10))?;
+ let scratch = scratch_manager.scratch_space().ok_or_else(|| {
+ ANNError::log_index_error(
+ "ScratchStoreManager doesn't have InMemQueryScratch instance available".to_string(),
+ )
+ })?;
+
+ let new_neighbors = self.search_for_point_and_prune(scratch, vertex_id)?;
+ self.update_vertex_with_neighbors(vertex_id, new_neighbors)?;
+ self.update_neighbors_of_vertex(vertex_id, scratch)?;
+
+ Ok(())
+ }
+
+ fn update_neighbors_of_vertex(
+ &self,
+ vertex_id: u32,
+ scratch: &mut InMemQueryScratch<T, N>,
+ ) -> Result<(), ANNError> {
+ let vertex = self.final_graph.read_vertex_and_neighbors(vertex_id)?;
+ assert!(vertex.size() <= self.configuration.index_write_parameter.max_degree as usize);
+ self.inter_insert(
+ vertex_id,
+ vertex.get_neighbors(),
+ self.configuration.index_write_parameter.max_degree,
+ scratch,
+ )?;
+ Ok(())
+ }
+
+ fn update_vertex_with_neighbors(
+ &self,
+ vertex_id: u32,
+ new_neighbors: AdjacencyList,
+ ) -> Result<(), ANNError> {
+ let vertex = &mut self.final_graph.write_vertex_and_neighbors(vertex_id)?;
+ vertex.set_neighbors(new_neighbors);
+ assert!(vertex.size() <= self.configuration.index_write_parameter.max_degree as usize);
+ Ok(())
+ }
+
+ fn search_for_point_and_prune(
+ &self,
+ scratch: &mut InMemQueryScratch<T, N>,
+ vertex_id: u32,
+ ) -> ANNResult<AdjacencyList> {
+ let mut pruned_list =
+ AdjacencyList::for_range(self.configuration.index_write_parameter.max_degree as usize);
+ let vertex = self.dataset.get_vertex(vertex_id)?;
+ let mut visited_nodes = self.search_for_point(&vertex, scratch)?;
+
+ self.prune_neighbors(vertex_id, &mut visited_nodes, &mut pruned_list, scratch)?;
+
+ if pruned_list.is_empty() {
+ return Err(ANNError::log_index_error(
+ "pruned_list is empty.".to_string(),
+ ));
+ }
+
+ if self.final_graph.size()
+ != self.configuration.max_points + self.configuration.num_frozen_pts
+ {
+ return Err(ANNError::log_index_error(format!(
+ "final_graph has {} vertices instead of {}",
+ self.final_graph.size(),
+ self.configuration.max_points + self.configuration.num_frozen_pts,
+ )));
+ }
+
+ Ok(pruned_list)
+ }
+
+ fn search(
+ &self,
+ query: &Vertex<T, N>,
+ k_value: usize,
+ l_value: u32,
+ indices: &mut [u32],
+ ) -> ANNResult<u32> {
+ if k_value > l_value as usize {
+ return Err(ANNError::log_index_error(format!(
+ "Set L: {} to a value of at least K: {}",
+ l_value, k_value
+ )));
+ }
+
+ let mut scratch_manager =
+ ScratchStoreManager::new(self.query_scratch_queue.clone(), Duration::from_millis(10))?;
+
+ let scratch = scratch_manager.scratch_space().ok_or_else(|| {
+ ANNError::log_index_error(
+ "ScratchStoreManager doesn't have InMemQueryScratch instance available".to_string(),
+ )
+ })?;
+
+ if l_value > scratch.candidate_size {
+ println!("Attempting to expand query scratch_space. Was created with Lsize: {} but search L is: {}", scratch.candidate_size, l_value);
+ scratch.resize_for_new_candidate_size(l_value);
+ println!(
+ "Resize completed. New scratch size is: {}",
+ scratch.candidate_size
+ );
+ }
+
+ let cmp = self.search_with_l_override(query, scratch, l_value as usize)?;
+ let mut pos = 0;
+
+ for i in 0..scratch.best_candidates.size() {
+ if scratch.best_candidates[i].id < self.configuration.max_points as u32 {
+ // Filter out the deleted points.
+ if let Ok(delete_set_guard) = self.delete_set.read() {
+ if !delete_set_guard.contains(&scratch.best_candidates[i].id) {
+ indices[pos] = scratch.best_candidates[i].id;
+ pos += 1;
+ }
+ } else {
+ return Err(ANNError::log_lock_poison_error(
+ "failed to acquire the lock for delete_set.".to_string(),
+ ));
+ }
+ }
+
+ if pos == k_value {
+ break;
+ }
+ }
+
+ if pos < k_value {
+ eprintln!(
+ "Found fewer than K elements for query! Found: {} but K: {}",
+ pos, k_value
+ );
+ }
+
+ Ok(cmp)
+ }
+
+ fn cleanup_graph(&mut self, visit_order: &Vec<u32>) -> ANNResult<()> {
+ if self.num_active_pts > 0 {
+ println!("Starting final cleanup..");
+ }
+
+ execute_with_rayon(
+ 0..visit_order.len(),
+ self.configuration.index_write_parameter.num_threads,
+ |idx| {
+ let vertex_id = visit_order[idx];
+ let num_nbrs = self.get_neighbor_count(vertex_id)?;
+
+ if num_nbrs <= self.configuration.index_write_parameter.max_degree as usize {
+ // Neighbor list is already small enough.
+ return Ok(());
+ }
+
+ let mut scratch_manager = ScratchStoreManager::new(
+ self.query_scratch_queue.clone(),
+ Duration::from_millis(10),
+ )?;
+ let scratch = scratch_manager.scratch_space().ok_or_else(|| {
+ ANNError::log_index_error(
+ "ScratchStoreManager doesn't have InMemQueryScratch instance available"
+ .to_string(),
+ )
+ })?;
+
+ let mut dummy_pool = self.get_neighbors_for_vertex(vertex_id)?;
+
+ let mut new_out_neighbors = AdjacencyList::for_range(
+ self.configuration.index_write_parameter.max_degree as usize,
+ );
+ self.prune_neighbors(vertex_id, &mut dummy_pool, &mut new_out_neighbors, scratch)?;
+
+ self.final_graph
+ .write_vertex_and_neighbors(vertex_id)?
+ .set_neighbors(new_out_neighbors);
+
+ Ok(())
+ },
+ )
+ }
+
+ /// Get the unique neighbors for a vertex.
+ ///
+ /// This code feels out of place here. This should have nothing to do with whether this
+ /// is in memory index?
+ /// # Errors
+ ///
+ /// This function will return an error if we are not able to get the read lock.
+ fn get_neighbors_for_vertex(&self, vertex_id: u32) -> ANNResult<Vec<Neighbor>> {
+ let binding = self.final_graph.read_vertex_and_neighbors(vertex_id)?;
+ let neighbors = binding.get_neighbors();
+ let dummy_pool = self.get_unique_neighbors(neighbors, vertex_id)?;
+
+ Ok(dummy_pool)
+ }
+
+ /// Returns a vector of unique neighbors for the given vertex, along with their distances.
+ ///
+ /// # Arguments
+ ///
+ /// * `neighbors` - A vector of neighbor id index for the given vertex.
+ /// * `vertex_id` - The given vertex id.
+ ///
+ /// # Errors
+ ///
+ /// Returns an `ANNError` if there is an error retrieving the vertex or one of its neighbors.
+ pub fn get_unique_neighbors(
+ &self,
+ neighbors: &Vec<u32>,
+ vertex_id: u32,
+ ) -> Result<Vec<Neighbor>, ANNError> {
+ let vertex = self.dataset.get_vertex(vertex_id)?;
+
+ let len = neighbors.len();
+ if len == 0 {
+ return Ok(Vec::new());
+ }
+
+ self.dataset.prefetch_vector(neighbors[0]);
+
+ let mut dummy_visited: HashSet<u32> = HashSet::with_capacity(len);
+ let mut dummy_pool: Vec<Neighbor> = Vec::with_capacity(len);
+
+ // let slice = ['w', 'i', 'n', 'd', 'o', 'w', 's'];
+ // for window in slice.windows(2) {
+ // &println!{"[{}, {}]", window[0], window[1]};
+ // }
+ // prints: [w, i] -> [i, n] -> [n, d] -> [d, o] -> [o, w] -> [w, s]
+ for current in neighbors.windows(2) {
+ // Prefetch the next item.
+ self.dataset.prefetch_vector(current[1]);
+ let current = current[0];
+
+ self.insert_neighbor_if_unique(
+ &mut dummy_visited,
+ current,
+ vertex_id,
+ &vertex,
+ &mut dummy_pool,
+ )?;
+ }
+
+ // Insert the last neighbor
+ #[allow(clippy::unwrap_used)]
+ self.insert_neighbor_if_unique(
+ &mut dummy_visited,
+ *neighbors.last().unwrap(), // we know len != 0, so this is safe.
+ vertex_id,
+ &vertex,
+ &mut dummy_pool,
+ )?;
+
+ Ok(dummy_pool)
+ }
+
+ fn insert_neighbor_if_unique(
+ &self,
+ dummy_visited: &mut HashSet<u32>,
+ current: u32,
+ vertex_id: u32,
+ vertex: &Vertex<'_, T, N>,
+ dummy_pool: &mut Vec<Neighbor>,
+ ) -> Result<(), ANNError> {
+ if current != vertex_id {
+ if let Vacant(entry) = dummy_visited.entry(current) {
+ let cur_nbr_vertex = self.dataset.get_vertex(current)?;
+ let dist = vertex.compare(&cur_nbr_vertex, self.configuration.dist_metric);
+ dummy_pool.push(Neighbor::new(current, dist));
+ entry.insert();
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Get count of neighbors for a given vertex.
+ ///
+ /// # Errors
+ ///
+ /// This function will return an error if we can't get a lock.
+ fn get_neighbor_count(&self, vertex_id: u32) -> ANNResult<usize> {
+ let num_nbrs = self
+ .final_graph
+ .read_vertex_and_neighbors(vertex_id)?
+ .size();
+ Ok(num_nbrs)
+ }
+
+ fn soft_delete_vertex(&self, vertex_id_to_delete: u32) -> ANNResult<()> {
+ if vertex_id_to_delete as usize > self.num_active_pts {
+ return Err(ANNError::log_index_error(format!(
+ "vertex_id_to_delete: {} is greater than the number of active points in the graph: {}",
+ vertex_id_to_delete, self.num_active_pts
+ )));
+ }
+
+ let mut delete_set_guard = match self.delete_set.write() {
+ Ok(guard) => guard,
+ Err(_) => {
+ return Err(ANNError::log_index_error(format!(
+ "Failed to acquire delete_set lock, cannot delete vertex {}",
+ vertex_id_to_delete
+ )));
+ }
+ };
+
+ delete_set_guard.insert(vertex_id_to_delete);
+ Ok(())
+ }
+
+ fn initialize_query_scratch(
+ &mut self,
+ num_threads: u32,
+ search_candidate_size: u32,
+ ) -> ANNResult<()> {
+ self.query_scratch_queue.reserve(num_threads as usize)?;
+ for _ in 0..num_threads {
+ let scratch = Box::new(InMemQueryScratch::<T, N>::new(
+ search_candidate_size,
+ &self.configuration.index_write_parameter,
+ false,
+ )?);
+
+ self.query_scratch_queue.push(scratch)?;
+ }
+
+ Ok(())
+ }
+
+ fn print_stats(&mut self) -> ANNResult<()> {
+ let mut max = 0;
+ let mut min = usize::MAX;
+ let mut total = 0;
+ let mut cnt = 0;
+
+ for i in 0..self.num_active_pts {
+ let vertex_id = i.try_into()?;
+ let pool_size = self
+ .final_graph
+ .read_vertex_and_neighbors(vertex_id)?
+ .size();
+ max = cmp::max(max, pool_size);
+ min = cmp::min(min, pool_size);
+ total += pool_size;
+ if pool_size < 2 {
+ cnt += 1;
+ }
+ }
+
+ println!(
+ "Index built with degree: max: {} avg: {} min: {} count(deg<2): {}",
+ max,
+ (total as f32) / ((self.num_active_pts + self.configuration.num_frozen_pts) as f32),
+ min,
+ cnt
+ );
+
+ match self.delete_set.read() {
+ Ok(guard) => {
+ println!(
+ "Number of soft deleted vertices {}, soft deleted percentage: {}",
+ guard.len(),
+ (guard.len() as f32)
+ / ((self.num_active_pts + self.configuration.num_frozen_pts) as f32),
+ );
+ }
+ Err(_) => {
+ return Err(ANNError::log_lock_poison_error(
+ "Failed to acquire delete_set lock, cannot get the number of deleted vertices"
+ .to_string(),
+ ));
+ }
+ };
+
+ self.max_observed_degree = cmp::max(max as u32, self.max_observed_degree);
+
+ Ok(())
+ }
+}
+
+impl<T, const N: usize> ANNInmemIndex<T> for InmemIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ fn build(&mut self, filename: &str, num_points_to_load: usize) -> ANNResult<()> {
+ // TODO: fresh-diskANN
+ // std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+
+ if !file_exists(filename) {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Data file {} does not exist.",
+ filename
+ )));
+ }
+
+ let (file_num_points, file_dim) = load_metadata_from_file(filename)?;
+ if file_num_points > self.configuration.max_points {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Driver requests loading {} points and file has {} points,
+ but index can support only {} points as specified in configuration.",
+ num_points_to_load, file_num_points, self.configuration.max_points
+ )));
+ }
+
+ if num_points_to_load > file_num_points {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Driver requests loading {} points and file has only {} points.",
+ num_points_to_load, file_num_points
+ )));
+ }
+
+ if file_dim != self.configuration.dim {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Driver requests loading {} dimension, but file has {} dimension.",
+ self.configuration.dim, file_dim
+ )));
+ }
+
+ if self.configuration.use_pq_dist {
+ // TODO: PQ
+ todo!("PQ is not supported now");
+ }
+
+ if self.configuration.index_write_parameter.num_threads > 0 {
+ set_rayon_num_threads(self.configuration.index_write_parameter.num_threads);
+ }
+
+ self.dataset.build_from_file(filename, num_points_to_load)?;
+
+ println!("Using only first {} from file.", num_points_to_load);
+
+ // TODO: tag_lock
+
+ self.num_active_pts = num_points_to_load;
+ self.build_with_data_populated()?;
+
+ Ok(())
+ }
+
+ fn insert(&mut self, filename: &str, num_points_to_insert: usize) -> ANNResult<()> {
+ // fresh-diskANN
+ if !file_exists(filename) {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Data file {} does not exist.",
+ filename
+ )));
+ }
+
+ let (file_num_points, file_dim) = load_metadata_from_file(filename)?;
+
+ if num_points_to_insert > file_num_points {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Driver requests loading {} points and file has only {} points.",
+ num_points_to_insert, file_num_points
+ )));
+ }
+
+ if file_dim != self.configuration.dim {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Driver requests loading {} dimension, but file has {} dimension.",
+ self.configuration.dim, file_dim
+ )));
+ }
+
+ if self.configuration.use_pq_dist {
+ // TODO: PQ
+ todo!("PQ is not supported now");
+ }
+
+ if self.query_scratch_queue.size()? == 0 {
+ self.initialize_query_scratch(
+ 5 + self.configuration.index_write_parameter.num_threads,
+ self.configuration.index_write_parameter.search_list_size,
+ )?;
+ }
+
+ if self.configuration.index_write_parameter.num_threads > 0 {
+ // set the thread count of Rayon, otherwise it will use threads as many as logical cores.
+ std::env::set_var(
+ "RAYON_NUM_THREADS",
+ self.configuration
+ .index_write_parameter
+ .num_threads
+ .to_string(),
+ );
+ }
+
+ self.dataset
+ .append_from_file(filename, num_points_to_insert)?;
+ self.final_graph.extend(
+ num_points_to_insert,
+ self.configuration.index_write_parameter.max_degree,
+ );
+
+ // TODO: this should not consider frozen points
+ let previous_last_pt = self.num_active_pts;
+ self.num_active_pts += num_points_to_insert;
+ self.configuration.max_points += num_points_to_insert;
+
+ println!("Inserting {} vectors from file.", num_points_to_insert);
+
+ // TODO: tag_lock
+ let logger = IndexLogger::new(num_points_to_insert);
+ let timer = Timer::new();
+ execute_with_rayon(
+ previous_last_pt..self.num_active_pts,
+ self.configuration.index_write_parameter.num_threads,
+ |idx| {
+ self.insert_vertex_id(idx as u32)?;
+ logger.vertex_processed()?;
+
+ Ok(())
+ },
+ )?;
+
+ let mut visit_order =
+ Vec::with_capacity(self.num_active_pts + self.configuration.num_frozen_pts);
+ for i in 0..self.num_active_pts {
+ visit_order.push(i as u32);
+ }
+
+ self.cleanup_graph(&visit_order)?;
+ println!("{}", timer.elapsed_seconds_for_step("Insert time: "));
+
+ self.print_stats()?;
+
+ Ok(())
+ }
+
+ fn save(&mut self, filename: &str) -> ANNResult<()> {
+ let data_file = filename.to_string() + ".data";
+ let delete_file = filename.to_string() + ".delete";
+
+ self.save_graph(filename)?;
+ self.save_data(data_file.as_str())?;
+ self.save_delete_list(delete_file.as_str())?;
+
+ Ok(())
+ }
+
+ fn load(&mut self, filename: &str, expected_num_points: usize) -> ANNResult<()> {
+ self.num_active_pts = expected_num_points;
+ self.dataset
+ .build_from_file(&format!("{}.data", filename), expected_num_points)?;
+
+ self.load_graph(filename, expected_num_points)?;
+ self.load_delete_list(&format!("{}.delete", filename))?;
+
+ if self.query_scratch_queue.size()? == 0 {
+ self.initialize_query_scratch(
+ 5 + self.configuration.index_write_parameter.num_threads,
+ self.configuration.index_write_parameter.search_list_size,
+ )?;
+ }
+
+ Ok(())
+ }
+
+ fn search(
+ &self,
+ query: &[T],
+ k_value: usize,
+ l_value: u32,
+ indices: &mut [u32],
+ ) -> ANNResult<u32> {
+ let query_vector = Vertex::new(<&[T; N]>::try_from(query)?, 0);
+ InmemIndex::search(self, &query_vector, k_value, l_value, indices)
+ }
+
+ fn soft_delete(
+ &mut self,
+ vertex_ids_to_delete: Vec<u32>,
+ num_points_to_delete: usize,
+ ) -> ANNResult<()> {
+ println!("Deleting {} vectors from file.", num_points_to_delete);
+
+ let logger = IndexLogger::new(num_points_to_delete);
+ let timer = Timer::new();
+
+ execute_with_rayon(
+ 0..num_points_to_delete,
+ self.configuration.index_write_parameter.num_threads,
+ |idx: usize| {
+ self.soft_delete_vertex(vertex_ids_to_delete[idx])?;
+ logger.vertex_processed()?;
+
+ Ok(())
+ },
+ )?;
+
+ println!("{}", timer.elapsed_seconds_for_step("Delete time: "));
+ self.print_stats()?;
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod index_test {
+ use vector::Metric;
+
+ use super::*;
+ use crate::{
+ model::{
+ configuration::index_write_parameters::IndexWriteParametersBuilder, vertex::DIM_128,
+ },
+ test_utils::get_test_file_path,
+ utils::file_util::load_ids_to_delete_from_file,
+ utils::round_up,
+ };
+
+ const TEST_DATA_FILE: &str = "tests/data/siftsmall_learn_256pts.fbin";
+ const TRUTH_GRAPH: &str = "tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2";
+ const TEST_DELETE_FILE: &str = "tests/data/delete_set_50pts.bin";
+ const TRUTH_GRAPH_WITH_SATURATED: &str =
+ "tests/data/disk_index_siftsmall_learn_256pts_R4_L50_A1.2_mem.index";
+ const R: u32 = 4;
+ const L: u32 = 50;
+ const ALPHA: f32 = 1.2;
+
+ /// Build the index with TEST_DATA_FILE and compare the index graph with truth graph TRUTH_GRAPH
+ /// Change above constants if you want to test with different dataset
+ macro_rules! index_end_to_end_test_singlethread {
+ ($saturate_graph:expr, $truth_graph:expr) => {{
+ let (data_num, dim) =
+ load_metadata_from_file(get_test_file_path(TEST_DATA_FILE).as_str()).unwrap();
+
+ let index_write_parameters = IndexWriteParametersBuilder::new(L, R)
+ .with_alpha(ALPHA)
+ .with_num_threads(1)
+ .with_saturate_graph($saturate_graph)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ dim,
+ round_up(dim as u64, 16_u64) as usize,
+ data_num,
+ false,
+ 0,
+ false,
+ 0,
+ 1.0f32,
+ index_write_parameters,
+ );
+ let mut index: InmemIndex<f32, DIM_128> = InmemIndex::new(config.clone()).unwrap();
+
+ index
+ .build(get_test_file_path(TEST_DATA_FILE).as_str(), data_num)
+ .unwrap();
+
+ let mut truth_index: InmemIndex<f32, DIM_128> = InmemIndex::new(config).unwrap();
+ truth_index
+ .load_graph(get_test_file_path($truth_graph).as_str(), data_num)
+ .unwrap();
+
+ compare_graphs(&index, &truth_index);
+ }};
+ }
+
+ #[test]
+ fn index_end_to_end_test_singlethread() {
+ index_end_to_end_test_singlethread!(false, TRUTH_GRAPH);
+ }
+
+ #[test]
+ fn index_end_to_end_test_singlethread_with_saturate_graph() {
+ index_end_to_end_test_singlethread!(true, TRUTH_GRAPH_WITH_SATURATED);
+ }
+
+ #[test]
+ fn index_end_to_end_test_multithread() {
+ let (data_num, dim) =
+ load_metadata_from_file(get_test_file_path(TEST_DATA_FILE).as_str()).unwrap();
+
+ let index_write_parameters = IndexWriteParametersBuilder::new(L, R)
+ .with_alpha(ALPHA)
+ .with_num_threads(8)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ dim,
+ round_up(dim as u64, 16_u64) as usize,
+ data_num,
+ false,
+ 0,
+ false,
+ 0,
+ 1f32,
+ index_write_parameters,
+ );
+ let mut index: InmemIndex<f32, DIM_128> = InmemIndex::new(config).unwrap();
+
+ index
+ .build(get_test_file_path(TEST_DATA_FILE).as_str(), data_num)
+ .unwrap();
+
+ for i in 0..index.final_graph.size() {
+ assert_ne!(
+ index
+ .final_graph
+ .read_vertex_and_neighbors(i as u32)
+ .unwrap()
+ .size(),
+ 0
+ );
+ }
+ }
+
+ const TEST_DATA_FILE_2: &str = "tests/data/siftsmall_learn_256pts_2.fbin";
+ const INSERT_TRUTH_GRAPH: &str =
+ "tests/data/truth_index_siftsmall_learn_256pts_1+2_R4_L50_A1.2";
+ const INSERT_TRUTH_GRAPH_WITH_SATURATED: &str =
+ "tests/data/truth_index_siftsmall_learn_256pts_1+2_saturated_R4_L50_A1.2";
+
+ /// Build the index with TEST_DATA_FILE, insert TEST_DATA_FILE_2 and compare the index graph with truth graph TRUTH_GRAPH
+ /// Change above constants if you want to test with different dataset
+ macro_rules! index_insert_end_to_end_test_singlethread {
+ ($saturate_graph:expr, $truth_graph:expr) => {{
+ let (data_num, dim) =
+ load_metadata_from_file(get_test_file_path(TEST_DATA_FILE).as_str()).unwrap();
+
+ let index_write_parameters = IndexWriteParametersBuilder::new(L, R)
+ .with_alpha(ALPHA)
+ .with_num_threads(1)
+ .with_saturate_graph($saturate_graph)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ dim,
+ round_up(dim as u64, 16_u64) as usize,
+ data_num,
+ false,
+ 0,
+ false,
+ 0,
+ 2.0f32,
+ index_write_parameters,
+ );
+ let mut index: InmemIndex<f32, DIM_128> = InmemIndex::new(config.clone()).unwrap();
+
+ index
+ .build(get_test_file_path(TEST_DATA_FILE).as_str(), data_num)
+ .unwrap();
+ index
+ .insert(get_test_file_path(TEST_DATA_FILE_2).as_str(), data_num)
+ .unwrap();
+
+ let config2 = IndexConfiguration::new(
+ Metric::L2,
+ dim,
+ round_up(dim as u64, 16_u64) as usize,
+ data_num * 2,
+ false,
+ 0,
+ false,
+ 0,
+ 1.0f32,
+ index_write_parameters,
+ );
+ let mut truth_index: InmemIndex<f32, DIM_128> = InmemIndex::new(config2).unwrap();
+ truth_index
+ .load_graph(get_test_file_path($truth_graph).as_str(), data_num)
+ .unwrap();
+
+ compare_graphs(&index, &truth_index);
+ }};
+ }
+
+ /// Build the index with TEST_DATA_FILE, and delete the vertices with id defined in TEST_DELETE_SET
+ macro_rules! index_delete_end_to_end_test_singlethread {
+ () => {{
+ let (data_num, dim) =
+ load_metadata_from_file(get_test_file_path(TEST_DATA_FILE).as_str()).unwrap();
+
+ let index_write_parameters = IndexWriteParametersBuilder::new(L, R)
+ .with_alpha(ALPHA)
+ .with_num_threads(1)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ dim,
+ round_up(dim as u64, 16_u64) as usize,
+ data_num,
+ false,
+ 0,
+ false,
+ 0,
+ 2.0f32,
+ index_write_parameters,
+ );
+ let mut index: InmemIndex<f32, DIM_128> = InmemIndex::new(config.clone()).unwrap();
+
+ index
+ .build(get_test_file_path(TEST_DATA_FILE).as_str(), data_num)
+ .unwrap();
+
+ let (num_points_to_delete, vertex_ids_to_delete) =
+ load_ids_to_delete_from_file(TEST_DELETE_FILE).unwrap();
+ index
+ .soft_delete(vertex_ids_to_delete, num_points_to_delete)
+ .unwrap();
+ assert!(index.delete_set.read().unwrap().len() == num_points_to_delete);
+ }};
+ }
+
+ #[test]
+ fn index_insert_end_to_end_test_singlethread() {
+ index_insert_end_to_end_test_singlethread!(false, INSERT_TRUTH_GRAPH);
+ }
+
+ #[test]
+ fn index_delete_end_to_end_test_singlethread() {
+ index_delete_end_to_end_test_singlethread!();
+ }
+
+ #[test]
+ fn index_insert_end_to_end_test_saturated_singlethread() {
+ index_insert_end_to_end_test_singlethread!(true, INSERT_TRUTH_GRAPH_WITH_SATURATED);
+ }
+
+ fn compare_graphs(index: &InmemIndex<f32, DIM_128>, truth_index: &InmemIndex<f32, DIM_128>) {
+ assert_eq!(index.start, truth_index.start);
+ assert_eq!(index.max_observed_degree, truth_index.max_observed_degree);
+ assert_eq!(index.final_graph.size(), truth_index.final_graph.size());
+
+ for i in 0..index.final_graph.size() {
+ assert_eq!(
+ index
+ .final_graph
+ .read_vertex_and_neighbors(i as u32)
+ .unwrap()
+ .size(),
+ truth_index
+ .final_graph
+ .read_vertex_and_neighbors(i as u32)
+ .unwrap()
+ .size()
+ );
+ assert_eq!(
+ index
+ .final_graph
+ .read_vertex_and_neighbors(i as u32)
+ .unwrap()
+ .get_neighbors(),
+ truth_index
+ .final_graph
+ .read_vertex_and_neighbors(i as u32)
+ .unwrap()
+ .get_neighbors()
+ );
+ }
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/inmem_index_storage.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/inmem_index_storage.rs
new file mode 100644
index 0000000..fa14d70
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/inmem_index_storage.rs
@@ -0,0 +1,304 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::fs::File;
+use std::io::{BufReader, BufWriter, Seek, SeekFrom, Write};
+use std::path::Path;
+
+use byteorder::{LittleEndian, ReadBytesExt};
+use vector::FullPrecisionDistance;
+
+use crate::common::{ANNError, ANNResult};
+use crate::model::graph::AdjacencyList;
+use crate::model::InMemoryGraph;
+use crate::utils::{file_exists, save_data_in_base_dimensions};
+
+use super::InmemIndex;
+
+impl<T, const N: usize> InmemIndex<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ pub fn load_graph(&mut self, filename: &str, expected_num_points: usize) -> ANNResult<usize> {
+ // let file_offset = 0; // will need this for single file format support
+
+ let mut in_file = BufReader::new(File::open(Path::new(filename))?);
+ // in_file.seek(SeekFrom::Start(file_offset as u64))?;
+
+ let expected_file_size: usize = in_file.read_u64::<LittleEndian>()? as usize;
+ self.max_observed_degree = in_file.read_u32::<LittleEndian>()?;
+ self.start = in_file.read_u32::<LittleEndian>()?;
+ let file_frozen_pts: usize = in_file.read_u64::<LittleEndian>()? as usize;
+
+ let vamana_metadata_size = 24;
+
+ println!("From graph header, expected_file_size: {}, max_observed_degree: {}, start: {}, file_frozen_pts: {}",
+ expected_file_size, self.max_observed_degree, self.start, file_frozen_pts);
+
+ if file_frozen_pts != self.configuration.num_frozen_pts {
+ if file_frozen_pts == 1 {
+ return Err(ANNError::log_index_config_error(
+ "num_frozen_pts".to_string(),
+ "ERROR: When loading index, detected dynamic index, but constructor asks for static index. Exitting.".to_string())
+ );
+ } else {
+ return Err(ANNError::log_index_config_error(
+ "num_frozen_pts".to_string(),
+ "ERROR: When loading index, detected static index, but constructor asks for dynamic index. Exitting.".to_string())
+ );
+ }
+ }
+
+ println!("Loading vamana graph {}...", filename);
+
+ let expected_max_points = expected_num_points - file_frozen_pts;
+
+ // If user provides more points than max_points
+ // resize the _final_graph to the larger size.
+ if self.configuration.max_points < expected_max_points {
+ println!("Number of points in data: {} is greater than max_points: {} Setting max points to: {}", expected_max_points, self.configuration.max_points, expected_max_points);
+
+ self.configuration.max_points = expected_max_points;
+ self.final_graph = InMemoryGraph::new(
+ self.configuration.max_points + self.configuration.num_frozen_pts,
+ self.configuration.index_write_parameter.max_degree,
+ );
+ }
+
+ let mut bytes_read = vamana_metadata_size;
+ let mut num_edges = 0;
+ let mut nodes_read = 0;
+ let mut max_observed_degree = 0;
+
+ while bytes_read != expected_file_size {
+ let num_nbrs = in_file.read_u32::<LittleEndian>()?;
+ max_observed_degree = if num_nbrs > max_observed_degree {
+ num_nbrs
+ } else {
+ max_observed_degree
+ };
+
+ if num_nbrs == 0 {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: Point found with no out-neighbors, point# {}",
+ nodes_read
+ )));
+ }
+
+ num_edges += num_nbrs;
+ nodes_read += 1;
+ let mut tmp: Vec<u32> = Vec::with_capacity(num_nbrs as usize);
+ for _ in 0..num_nbrs {
+ tmp.push(in_file.read_u32::<LittleEndian>()?);
+ }
+
+ self.final_graph
+ .write_vertex_and_neighbors(nodes_read - 1)?
+ .set_neighbors(AdjacencyList::from(tmp));
+ bytes_read += 4 * (num_nbrs as usize + 1);
+ }
+
+ println!(
+ "Done. Index has {} nodes and {} out-edges, _start is set to {}",
+ nodes_read, num_edges, self.start
+ );
+
+ self.max_observed_degree = max_observed_degree;
+ Ok(nodes_read as usize)
+ }
+
+ /// Save the graph index on a file as an adjacency list.
+ /// For each point, first store the number of neighbors,
+ /// and then the neighbor list (each as 4 byte u32)
+ pub fn save_graph(&mut self, graph_file: &str) -> ANNResult<u64> {
+ let file: File = File::create(graph_file)?;
+ let mut out = BufWriter::new(file);
+
+ let file_offset: u64 = 0;
+ out.seek(SeekFrom::Start(file_offset))?;
+ let mut index_size: u64 = 24;
+ let mut max_degree: u32 = 0;
+ out.write_all(&index_size.to_le_bytes())?;
+ out.write_all(&self.max_observed_degree.to_le_bytes())?;
+ out.write_all(&self.start.to_le_bytes())?;
+ out.write_all(&(self.configuration.num_frozen_pts as u64).to_le_bytes())?;
+
+ // At this point, either nd == max_points or any frozen points have
+ // been temporarily moved to nd, so nd + num_frozen_points is the valid
+ // location limit
+ for i in 0..self.num_active_pts + self.configuration.num_frozen_pts {
+ let idx = i as u32;
+ let gk: u32 = self.final_graph.read_vertex_and_neighbors(idx)?.size() as u32;
+ out.write_all(&gk.to_le_bytes())?;
+ for neighbor in self
+ .final_graph
+ .read_vertex_and_neighbors(idx)?
+ .get_neighbors()
+ .iter()
+ {
+ out.write_all(&neighbor.to_le_bytes())?;
+ }
+ max_degree =
+ if self.final_graph.read_vertex_and_neighbors(idx)?.size() as u32 > max_degree {
+ self.final_graph.read_vertex_and_neighbors(idx)?.size() as u32
+ } else {
+ max_degree
+ };
+ index_size += (std::mem::size_of::<u32>() * (gk as usize + 1)) as u64;
+ }
+ out.seek(SeekFrom::Start(file_offset))?;
+ out.write_all(&index_size.to_le_bytes())?;
+ out.write_all(&max_degree.to_le_bytes())?;
+ out.flush()?;
+ Ok(index_size)
+ }
+
+ /// Save the data on a file.
+ pub fn save_data(&mut self, data_file: &str) -> ANNResult<usize> {
+ // Note: at this point, either _nd == _max_points or any frozen points have
+ // been temporarily moved to _nd, so _nd + _num_frozen_points is the valid
+ // location limit.
+ Ok(save_data_in_base_dimensions(
+ data_file,
+ &mut self.dataset.data,
+ self.num_active_pts + self.configuration.num_frozen_pts,
+ self.configuration.dim,
+ self.configuration.aligned_dim,
+ 0,
+ )?)
+ }
+
+ /// Save the delete list to a file only if the delete list length is not zero.
+ pub fn save_delete_list(&mut self, delete_list_file: &str) -> ANNResult<usize> {
+ let mut delete_file_size = 0;
+ if let Ok(delete_set) = self.delete_set.read() {
+ let delete_set_len = delete_set.len() as u32;
+
+ if delete_set_len != 0 {
+ let file: File = File::create(delete_list_file)?;
+ let mut writer = BufWriter::new(file);
+
+ // Write the length of the set.
+ writer.write_all(&delete_set_len.to_le_bytes())?;
+ delete_file_size += std::mem::size_of::<u32>();
+
+ // Write the elements of the set.
+ for &item in delete_set.iter() {
+ writer.write_all(&item.to_be_bytes())?;
+ delete_file_size += std::mem::size_of::<u32>();
+ }
+
+ writer.flush()?;
+ }
+ } else {
+ return Err(ANNError::log_lock_poison_error(
+ "Poisoned lock on delete set. Can't save deleted list.".to_string(),
+ ));
+ }
+
+ Ok(delete_file_size)
+ }
+
+ // load the deleted list from the delete file if it exists.
+ pub fn load_delete_list(&mut self, delete_list_file: &str) -> ANNResult<usize> {
+ let mut len = 0;
+
+ if file_exists(delete_list_file) {
+ let file = File::open(delete_list_file)?;
+ let mut reader = BufReader::new(file);
+
+ len = reader.read_u32::<LittleEndian>()? as usize;
+
+ if let Ok(mut delete_set) = self.delete_set.write() {
+ for _ in 0..len {
+ let item = reader.read_u32::<LittleEndian>()?;
+ delete_set.insert(item);
+ }
+ } else {
+ return Err(ANNError::log_lock_poison_error(
+ "Poisoned lock on delete set. Can't load deleted list.".to_string(),
+ ));
+ }
+ }
+
+ Ok(len)
+ }
+}
+
+#[cfg(test)]
+mod index_test {
+ use std::fs;
+
+ use vector::Metric;
+
+ use super::*;
+ use crate::{
+ index::ANNInmemIndex,
+ model::{
+ configuration::index_write_parameters::IndexWriteParametersBuilder, vertex::DIM_128,
+ IndexConfiguration,
+ },
+ utils::{load_metadata_from_file, round_up},
+ };
+
+ const TEST_DATA_FILE: &str = "tests/data/siftsmall_learn_256pts.fbin";
+ const R: u32 = 4;
+ const L: u32 = 50;
+ const ALPHA: f32 = 1.2;
+
+ #[cfg_attr(not(coverage), test)]
+ fn save_graph_test() {
+ let parameters = IndexWriteParametersBuilder::new(50, 4)
+ .with_alpha(1.2)
+ .build();
+ let config =
+ IndexConfiguration::new(Metric::L2, 10, 16, 16, false, 0, false, 8, 1f32, parameters);
+ let mut index = InmemIndex::<f32, 3>::new(config).unwrap();
+ let final_graph = InMemoryGraph::new(10, 3);
+ let num_active_pts = 2_usize;
+ index.final_graph = final_graph;
+ index.num_active_pts = num_active_pts;
+ let graph_file = "test_save_graph_data.bin";
+ let result = index.save_graph(graph_file);
+ assert!(result.is_ok());
+
+ fs::remove_file(graph_file).expect("Failed to delete file");
+ }
+
+ #[test]
+ fn save_data_test() {
+ let (data_num, dim) = load_metadata_from_file(TEST_DATA_FILE).unwrap();
+
+ let index_write_parameters = IndexWriteParametersBuilder::new(L, R)
+ .with_alpha(ALPHA)
+ .build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ dim,
+ round_up(dim as u64, 16_u64) as usize,
+ data_num,
+ false,
+ 0,
+ false,
+ 0,
+ 1f32,
+ index_write_parameters,
+ );
+ let mut index: InmemIndex<f32, DIM_128> = InmemIndex::new(config).unwrap();
+
+ index.build(TEST_DATA_FILE, data_num).unwrap();
+
+ let data_file = "test.data";
+ let result = index.save_data(data_file);
+ assert_eq!(
+ result.unwrap(),
+ 2 * std::mem::size_of::<u32>()
+ + (index.num_active_pts + index.configuration.num_frozen_pts)
+ * index.configuration.dim
+ * (std::mem::size_of::<f32>())
+ );
+ fs::remove_file(data_file).expect("Failed to delete file");
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/mod.rs
new file mode 100644
index 0000000..f2a091a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/inmem_index/mod.rs
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod inmem_index;
+pub use inmem_index::InmemIndex;
+
+mod inmem_index_storage;
+
+pub mod ann_inmem_index;
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/mod.rs
new file mode 100644
index 0000000..18c3bd5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/index/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+mod inmem_index;
+pub use inmem_index::ann_inmem_index::*;
+pub use inmem_index::InmemIndex;
+
+mod disk_index;
+pub use disk_index::*;
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/disk_index_build_logger.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/disk_index_build_logger.rs
new file mode 100644
index 0000000..d349353
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/disk_index_build_logger.rs
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use logger::logger::indexlog::DiskIndexConstructionCheckpoint;
+use logger::logger::indexlog::DiskIndexConstructionLog;
+use logger::logger::indexlog::Log;
+use logger::logger::indexlog::LogLevel;
+use logger::message_handler::send_log;
+
+use crate::{utils::Timer, common::ANNResult};
+
+pub struct DiskIndexBuildLogger {
+ timer: Timer,
+ checkpoint: DiskIndexConstructionCheckpoint,
+}
+
+impl DiskIndexBuildLogger {
+ pub fn new(checkpoint: DiskIndexConstructionCheckpoint) -> Self {
+ Self {
+ timer: Timer::new(),
+ checkpoint,
+ }
+ }
+
+ pub fn log_checkpoint(&mut self, next_checkpoint: DiskIndexConstructionCheckpoint) -> ANNResult<()> {
+ if self.checkpoint == DiskIndexConstructionCheckpoint::None {
+ return Ok(());
+ }
+
+ let mut log = Log::default();
+ let disk_index_construction_log = DiskIndexConstructionLog {
+ checkpoint: self.checkpoint as i32,
+ time_spent_in_seconds: self.timer.elapsed().as_secs_f32(),
+ g_cycles_spent: self.timer.elapsed_gcycles(),
+ log_level: LogLevel::Info as i32,
+ };
+ log.disk_index_construction_log = Some(disk_index_construction_log);
+
+ send_log(log)?;
+ self.checkpoint = next_checkpoint;
+ self.timer.reset();
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod dataset_test {
+ use super::*;
+
+ #[test]
+ fn test_log() {
+ let mut logger = DiskIndexBuildLogger::new(DiskIndexConstructionCheckpoint::PqConstruction);
+ logger.log_checkpoint(DiskIndexConstructionCheckpoint::InmemIndexBuild).unwrap();logger.log_checkpoint(logger::logger::indexlog::DiskIndexConstructionCheckpoint::DiskLayout).unwrap();
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/index_logger.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/index_logger.rs
new file mode 100644
index 0000000..dfc81ad
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/index_logger.rs
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use logger::logger::indexlog::IndexConstructionLog;
+use logger::logger::indexlog::Log;
+use logger::logger::indexlog::LogLevel;
+use logger::message_handler::send_log;
+
+use crate::common::ANNResult;
+use crate::utils::Timer;
+
+pub struct IndexLogger {
+ items_processed: AtomicUsize,
+ timer: Timer,
+ range: usize,
+}
+
+impl IndexLogger {
+ pub fn new(range: usize) -> Self {
+ Self {
+ items_processed: AtomicUsize::new(0),
+ timer: Timer::new(),
+ range,
+ }
+ }
+
+ pub fn vertex_processed(&self) -> ANNResult<()> {
+ let count = self.items_processed.fetch_add(1, Ordering::Relaxed);
+ if count % 100_000 == 0 {
+ let mut log = Log::default();
+ let index_construction_log = IndexConstructionLog {
+ percentage_complete: (100_f32 * count as f32) / (self.range as f32),
+ time_spent_in_seconds: self.timer.elapsed().as_secs_f32(),
+ g_cycles_spent: self.timer.elapsed_gcycles(),
+ log_level: LogLevel::Info as i32,
+ };
+ log.index_construction_log = Some(index_construction_log);
+
+ send_log(log)?;
+ }
+
+ Ok(())
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/mod.rs
new file mode 100644
index 0000000..234e53c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/instrumentation/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+mod index_logger;
+pub use index_logger::IndexLogger;
+
+mod disk_index_build_logger;
+pub use disk_index_build_logger::DiskIndexBuildLogger;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/lib.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/lib.rs
new file mode 100644
index 0000000..1f89e33
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/lib.rs
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![cfg_attr(
+ not(test),
+ warn(clippy::panic, clippy::unwrap_used, clippy::expect_used)
+)]
+#![cfg_attr(test, allow(clippy::unused_io_amount))]
+
+pub mod utils;
+
+pub mod algorithm;
+
+pub mod model;
+
+pub mod common;
+
+pub mod index;
+
+pub mod storage;
+
+pub mod instrumentation;
+
+#[cfg(test)]
+pub mod test_utils;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/disk_index_build_parameter.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/disk_index_build_parameter.rs
new file mode 100644
index 0000000..539192a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/disk_index_build_parameter.rs
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Parameters for disk index construction.
+
+use crate::common::{ANNResult, ANNError};
+
+/// Cached nodes size in GB
+const SPACE_FOR_CACHED_NODES_IN_GB: f64 = 0.25;
+
+/// Threshold for caching in GB
+const THRESHOLD_FOR_CACHING_IN_GB: f64 = 1.0;
+
+/// Parameters specific for disk index construction.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct DiskIndexBuildParameters {
+ /// Bound on the memory footprint of the index at search time in bytes.
+ /// Once built, the index will use up only the specified RAM limit, the rest will reside on disk.
+ /// This will dictate how aggressively we compress the data vectors to store in memory.
+ /// Larger will yield better performance at search time.
+ search_ram_limit: f64,
+
+ /// Limit on the memory allowed for building the index in bytes.
+ index_build_ram_limit: f64,
+}
+
+impl DiskIndexBuildParameters {
+ /// Create DiskIndexBuildParameters instance
+ pub fn new(search_ram_limit_gb: f64, index_build_ram_limit_gb: f64) -> ANNResult<Self> {
+ let param = Self {
+ search_ram_limit: Self::get_memory_budget(search_ram_limit_gb),
+ index_build_ram_limit: index_build_ram_limit_gb * 1024_f64 * 1024_f64 * 1024_f64,
+ };
+
+ if param.search_ram_limit <= 0f64 {
+ return Err(ANNError::log_index_config_error("search_ram_limit".to_string(), "RAM budget should be > 0".to_string()))
+ }
+
+ if param.index_build_ram_limit <= 0f64 {
+ return Err(ANNError::log_index_config_error("index_build_ram_limit".to_string(), "RAM budget should be > 0".to_string()))
+ }
+
+ Ok(param)
+ }
+
+ /// Get search_ram_limit
+ pub fn search_ram_limit(&self) -> f64 {
+ self.search_ram_limit
+ }
+
+ /// Get index_build_ram_limit
+ pub fn index_build_ram_limit(&self) -> f64 {
+ self.index_build_ram_limit
+ }
+
+ fn get_memory_budget(mut index_ram_limit_gb: f64) -> f64 {
+ if index_ram_limit_gb - SPACE_FOR_CACHED_NODES_IN_GB > THRESHOLD_FOR_CACHING_IN_GB {
+ // slack for space used by cached nodes
+ index_ram_limit_gb -= SPACE_FOR_CACHED_NODES_IN_GB;
+ }
+
+ index_ram_limit_gb * 1024_f64 * 1024_f64 * 1024_f64
+ }
+}
+
+#[cfg(test)]
+mod dataset_test {
+ use super::*;
+
+ #[test]
+ fn sufficient_ram_for_caching() {
+ let param = DiskIndexBuildParameters::new(1.26_f64, 1.0_f64).unwrap();
+ assert_eq!(param.search_ram_limit, 1.01_f64 * 1024_f64 * 1024_f64 * 1024_f64);
+ }
+
+ #[test]
+ fn insufficient_ram_for_caching() {
+ let param = DiskIndexBuildParameters::new(0.03_f64, 1.0_f64).unwrap();
+ assert_eq!(param.search_ram_limit, 0.03_f64 * 1024_f64 * 1024_f64 * 1024_f64);
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/index_configuration.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/index_configuration.rs
new file mode 100644
index 0000000..3e8c472
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/index_configuration.rs
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Index configuration.
+
+use vector::Metric;
+
+use super::index_write_parameters::IndexWriteParameters;
+
+/// The index configuration
+#[derive(Debug, Clone)]
+pub struct IndexConfiguration {
+ /// Index write parameter
+ pub index_write_parameter: IndexWriteParameters,
+
+ /// Distance metric
+ pub dist_metric: Metric,
+
+ /// Dimension of the raw data
+ pub dim: usize,
+
+ /// Aligned dimension - round up dim to the nearest multiple of 8
+ pub aligned_dim: usize,
+
+ /// Total number of points in given data set
+ pub max_points: usize,
+
+ /// Number of points which are used as initial candidates when iterating to
+ /// closest point(s). These are not visible externally and won't be returned
+ /// by search. DiskANN forces at least 1 frozen point for dynamic index.
+ /// The frozen points have consecutive locations.
+ pub num_frozen_pts: usize,
+
+ /// Calculate distance by PQ or not
+ pub use_pq_dist: bool,
+
+ /// Number of PQ chunks
+ pub num_pq_chunks: usize,
+
+ /// Use optimized product quantization
+ /// Currently not supported
+ pub use_opq: bool,
+
+ /// potential for growth. 1.2 means the index can grow by up to 20%.
+ pub growth_potential: f32,
+
+ // TODO: below settings are not supported in current iteration
+ // pub concurrent_consolidate: bool,
+ // pub has_built: bool,
+ // pub save_as_one_file: bool,
+ // pub dynamic_index: bool,
+ // pub enable_tags: bool,
+ // pub normalize_vecs: bool,
+}
+
+impl IndexConfiguration {
+ /// Create IndexConfiguration instance
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ dist_metric: Metric,
+ dim: usize,
+ aligned_dim: usize,
+ max_points: usize,
+ use_pq_dist: bool,
+ num_pq_chunks: usize,
+ use_opq: bool,
+ num_frozen_pts: usize,
+ growth_potential: f32,
+ index_write_parameter: IndexWriteParameters
+ ) -> Self {
+ Self {
+ index_write_parameter,
+ dist_metric,
+ dim,
+ aligned_dim,
+ max_points,
+ num_frozen_pts,
+ use_pq_dist,
+ num_pq_chunks,
+ use_opq,
+ growth_potential,
+ }
+ }
+
+ /// Get the size of adjacency list that we build out.
+ pub fn write_range(&self) -> usize {
+ self.index_write_parameter.max_degree as usize
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/index_write_parameters.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/index_write_parameters.rs
new file mode 100644
index 0000000..cb71f42
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/index_write_parameters.rs
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Index write parameters.
+
+/// Default parameter values.
+pub mod default_param_vals {
+ /// Default value of alpha.
+ pub const ALPHA: f32 = 1.2;
+
+ /// Default value of number of threads.
+ pub const NUM_THREADS: u32 = 0;
+
+ /// Default value of number of rounds.
+ pub const NUM_ROUNDS: u32 = 2;
+
+ /// Default value of max occlusion size.
+ pub const MAX_OCCLUSION_SIZE: u32 = 750;
+
+ /// Default value of filter list size.
+ pub const FILTER_LIST_SIZE: u32 = 0;
+
+ /// Default value of number of frozen points.
+ pub const NUM_FROZEN_POINTS: u32 = 0;
+
+ /// Default value of max degree.
+ pub const MAX_DEGREE: u32 = 64;
+
+ /// Default value of build list size.
+ pub const BUILD_LIST_SIZE: u32 = 100;
+
+ /// Default value of saturate graph.
+ pub const SATURATE_GRAPH: bool = false;
+
+ /// Default value of search list size.
+ pub const SEARCH_LIST_SIZE: u32 = 100;
+}
+
+/// Index write parameters.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct IndexWriteParameters {
+ /// Search list size - L.
+ pub search_list_size: u32,
+
+ /// Max degree - R.
+ pub max_degree: u32,
+
+ /// Saturate graph.
+ pub saturate_graph: bool,
+
+ /// Max occlusion size - C.
+ pub max_occlusion_size: u32,
+
+ /// Alpha.
+ pub alpha: f32,
+
+ /// Number of rounds.
+ pub num_rounds: u32,
+
+ /// Number of threads.
+ pub num_threads: u32,
+
+ /// Number of frozen points.
+ pub num_frozen_points: u32,
+}
+
+impl Default for IndexWriteParameters {
+ /// Create IndexWriteParameters with default values
+ fn default() -> Self {
+ Self {
+ search_list_size: default_param_vals::SEARCH_LIST_SIZE,
+ max_degree: default_param_vals::MAX_DEGREE,
+ saturate_graph: default_param_vals::SATURATE_GRAPH,
+ max_occlusion_size: default_param_vals::MAX_OCCLUSION_SIZE,
+ alpha: default_param_vals::ALPHA,
+ num_rounds: default_param_vals::NUM_ROUNDS,
+ num_threads: default_param_vals::NUM_THREADS,
+ num_frozen_points: default_param_vals::NUM_FROZEN_POINTS
+ }
+ }
+}
+
+/// The builder for IndexWriteParameters.
+#[derive(Debug)]
+pub struct IndexWriteParametersBuilder {
+ search_list_size: u32,
+ max_degree: u32,
+ max_occlusion_size: Option<u32>,
+ saturate_graph: Option<bool>,
+ alpha: Option<f32>,
+ num_rounds: Option<u32>,
+ num_threads: Option<u32>,
+ // filter_list_size: Option<u32>,
+ num_frozen_points: Option<u32>,
+}
+
+impl IndexWriteParametersBuilder {
+ /// Initialize IndexWriteParametersBuilder
+ pub fn new(search_list_size: u32, max_degree: u32) -> Self {
+ Self {
+ search_list_size,
+ max_degree,
+ max_occlusion_size: None,
+ saturate_graph: None,
+ alpha: None,
+ num_rounds: None,
+ num_threads: None,
+ // filter_list_size: None,
+ num_frozen_points: None,
+ }
+ }
+
+ /// Set max occlusion size.
+ pub fn with_max_occlusion_size(mut self, max_occlusion_size: u32) -> Self {
+ self.max_occlusion_size = Some(max_occlusion_size);
+ self
+ }
+
+ /// Set saturate graph.
+ pub fn with_saturate_graph(mut self, saturate_graph: bool) -> Self {
+ self.saturate_graph = Some(saturate_graph);
+ self
+ }
+
+ /// Set alpha.
+ pub fn with_alpha(mut self, alpha: f32) -> Self {
+ self.alpha = Some(alpha);
+ self
+ }
+
+ /// Set number of rounds.
+ pub fn with_num_rounds(mut self, num_rounds: u32) -> Self {
+ self.num_rounds = Some(num_rounds);
+ self
+ }
+
+ /// Set number of threads.
+ pub fn with_num_threads(mut self, num_threads: u32) -> Self {
+ self.num_threads = Some(num_threads);
+ self
+ }
+
+ /*
+ pub fn with_filter_list_size(mut self, filter_list_size: u32) -> Self {
+ self.filter_list_size = Some(filter_list_size);
+ self
+ }
+ */
+
+ /// Set number of frozen points.
+ pub fn with_num_frozen_points(mut self, num_frozen_points: u32) -> Self {
+ self.num_frozen_points = Some(num_frozen_points);
+ self
+ }
+
+ /// Build IndexWriteParameters from IndexWriteParametersBuilder.
+ pub fn build(self) -> IndexWriteParameters {
+ IndexWriteParameters {
+ search_list_size: self.search_list_size,
+ max_degree: self.max_degree,
+ saturate_graph: self.saturate_graph.unwrap_or(default_param_vals::SATURATE_GRAPH),
+ max_occlusion_size: self.max_occlusion_size.unwrap_or(default_param_vals::MAX_OCCLUSION_SIZE),
+ alpha: self.alpha.unwrap_or(default_param_vals::ALPHA),
+ num_rounds: self.num_rounds.unwrap_or(default_param_vals::NUM_ROUNDS),
+ num_threads: self.num_threads.unwrap_or(default_param_vals::NUM_THREADS),
+ // filter_list_size: self.filter_list_size.unwrap_or(default_param_vals::FILTER_LIST_SIZE),
+ num_frozen_points: self.num_frozen_points.unwrap_or(default_param_vals::NUM_FROZEN_POINTS),
+ }
+ }
+}
+
+/// Construct IndexWriteParametersBuilder from IndexWriteParameters.
+impl From<IndexWriteParameters> for IndexWriteParametersBuilder {
+ fn from(param: IndexWriteParameters) -> Self {
+ Self {
+ search_list_size: param.search_list_size,
+ max_degree: param.max_degree,
+ max_occlusion_size: Some(param.max_occlusion_size),
+ saturate_graph: Some(param.saturate_graph),
+ alpha: Some(param.alpha),
+ num_rounds: Some(param.num_rounds),
+ num_threads: Some(param.num_threads),
+ // filter_list_size: Some(param.filter_list_size),
+ num_frozen_points: Some(param.num_frozen_points),
+ }
+ }
+}
+
+#[cfg(test)]
+mod parameters_test {
+ use crate::model::configuration::index_write_parameters::*;
+
+ #[test]
+ fn test_default_index_params() {
+ let wp1 = IndexWriteParameters::default();
+ assert_eq!(wp1.search_list_size, default_param_vals::SEARCH_LIST_SIZE);
+ assert_eq!(wp1.max_degree, default_param_vals::MAX_DEGREE);
+ assert_eq!(wp1.saturate_graph, default_param_vals::SATURATE_GRAPH);
+ assert_eq!(wp1.max_occlusion_size, default_param_vals::MAX_OCCLUSION_SIZE);
+ assert_eq!(wp1.alpha, default_param_vals::ALPHA);
+ assert_eq!(wp1.num_rounds, default_param_vals::NUM_ROUNDS);
+ assert_eq!(wp1.num_threads, default_param_vals::NUM_THREADS);
+ assert_eq!(wp1.num_frozen_points, default_param_vals::NUM_FROZEN_POINTS);
+ }
+
+ #[test]
+ fn test_index_write_parameters_builder() {
+ // default value
+ let wp1 = IndexWriteParametersBuilder::new(10, 20).build();
+ assert_eq!(wp1.search_list_size, 10);
+ assert_eq!(wp1.max_degree, 20);
+ assert_eq!(wp1.saturate_graph, default_param_vals::SATURATE_GRAPH);
+ assert_eq!(wp1.max_occlusion_size, default_param_vals::MAX_OCCLUSION_SIZE);
+ assert_eq!(wp1.alpha, default_param_vals::ALPHA);
+ assert_eq!(wp1.num_rounds, default_param_vals::NUM_ROUNDS);
+ assert_eq!(wp1.num_threads, default_param_vals::NUM_THREADS);
+ assert_eq!(wp1.num_frozen_points, default_param_vals::NUM_FROZEN_POINTS);
+
+ // build with custom values
+ let wp2 = IndexWriteParametersBuilder::new(10, 20)
+ .with_max_occlusion_size(30)
+ .with_saturate_graph(true)
+ .with_alpha(0.5)
+ .with_num_rounds(40)
+ .with_num_threads(50)
+ .with_num_frozen_points(60)
+ .build();
+ assert_eq!(wp2.search_list_size, 10);
+ assert_eq!(wp2.max_degree, 20);
+ assert!(wp2.saturate_graph);
+ assert_eq!(wp2.max_occlusion_size, 30);
+ assert_eq!(wp2.alpha, 0.5);
+ assert_eq!(wp2.num_rounds, 40);
+ assert_eq!(wp2.num_threads, 50);
+ assert_eq!(wp2.num_frozen_points, 60);
+
+ // test from
+ let wp3 = IndexWriteParametersBuilder::from(wp2).build();
+ assert_eq!(wp3, wp2);
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/mod.rs
new file mode 100644
index 0000000..201f97e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/configuration/mod.rs
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub mod index_configuration;
+pub use index_configuration::IndexConfiguration;
+
+pub mod index_write_parameters;
+pub use index_write_parameters::*;
+
+pub mod disk_index_build_parameter;
+pub use disk_index_build_parameter::DiskIndexBuildParameters;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/disk_scratch_dataset.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/disk_scratch_dataset.rs
new file mode 100644
index 0000000..0d9a007
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/disk_scratch_dataset.rs
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Disk scratch dataset
+
+use std::mem::{size_of, size_of_val};
+use std::ptr;
+
+use crate::common::{AlignedBoxWithSlice, ANNResult};
+use crate::model::MAX_N_CMPS;
+use crate::utils::round_up;
+
+/// DiskScratchDataset alignment
+pub const DISK_SCRATCH_DATASET_ALIGN: usize = 256;
+
+/// Disk scratch dataset storing fp vectors with aligned dim
+#[derive(Debug)]
+pub struct DiskScratchDataset<T, const N: usize>
+{
+ /// fp vectors with aligned dim
+ pub data: AlignedBoxWithSlice<T>,
+
+ /// current index to store the next fp vector
+ pub cur_index: usize,
+}
+
+impl<T, const N: usize> DiskScratchDataset<T, N>
+{
+ /// Create DiskScratchDataset instance
+ pub fn new() -> ANNResult<Self> {
+ Ok(Self {
+ // C++ code allocates round_up(MAX_N_CMPS * N, 256) bytes, shouldn't it be round_up(MAX_N_CMPS * N, 256) * size_of::<T> bytes?
+ data: AlignedBoxWithSlice::new(
+ round_up(MAX_N_CMPS * N, DISK_SCRATCH_DATASET_ALIGN),
+ DISK_SCRATCH_DATASET_ALIGN)?,
+ cur_index: 0,
+ })
+ }
+
+ /// memcpy from fp vector bytes (its len should be `dim * size_of::<T>()`) to self.data
+ /// The dest slice is a fp vector with aligned dim
+ /// * fp_vector_buf's dim might not be aligned dim (N)
+ /// # Safety
+ /// Behavior is undefined if any of the following conditions are violated:
+ ///
+ /// * `fp_vector_buf`'s len must be `dim * size_of::<T>()` bytes
+ ///
+ /// * `fp_vector_buf` must be smaller than or equal to `N * size_of::<T>()` bytes.
+ ///
+ /// * `fp_vector_buf` and `self.data` must be nonoverlapping.
+ pub unsafe fn memcpy_from_fp_vector_buf(&mut self, fp_vector_buf: &[u8]) -> &[T] {
+ if self.cur_index == MAX_N_CMPS {
+ self.cur_index = 0;
+ }
+
+ let aligned_dim_vector = &mut self.data[self.cur_index * N..(self.cur_index + 1) * N];
+
+ assert!(fp_vector_buf.len() % size_of::<T>() == 0);
+ assert!(fp_vector_buf.len() <= size_of_val(aligned_dim_vector));
+
+ // memcpy from fp_vector_buf to aligned_dim_vector
+ unsafe {
+ ptr::copy_nonoverlapping(
+ fp_vector_buf.as_ptr(),
+ aligned_dim_vector.as_mut_ptr() as *mut u8,
+ fp_vector_buf.len(),
+ );
+ }
+
+ self.cur_index += 1;
+ aligned_dim_vector
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/inmem_dataset.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/inmem_dataset.rs
new file mode 100644
index 0000000..6d8b649
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/inmem_dataset.rs
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! In-memory Dataset
+
+use rayon::prelude::*;
+use std::mem;
+use vector::{FullPrecisionDistance, Metric};
+
+use crate::common::{ANNError, ANNResult, AlignedBoxWithSlice};
+use crate::model::Vertex;
+use crate::utils::copy_aligned_data_from_file;
+
+/// Dataset of all in-memory FP points
+#[derive(Debug)]
+pub struct InmemDataset<T, const N: usize>
+where
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// All in-memory points
+ pub data: AlignedBoxWithSlice<T>,
+
+ /// Number of points we anticipate to have
+ pub num_points: usize,
+
+ /// Number of active points i.e. existing in the graph
+ pub num_active_pts: usize,
+
+ /// Capacity of the dataset
+ pub capacity: usize,
+}
+
+impl<'a, T, const N: usize> InmemDataset<T, N>
+where
+ T: Default + Copy + Sync + Send + Into<f32>,
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Create the dataset with size num_points and growth factor.
+ /// growth factor=1 means no growth (provision 100% space of num_points)
+ /// growth factor=1.2 means provision 120% space of num_points (20% extra space)
+ pub fn new(num_points: usize, index_growth_factor: f32) -> ANNResult<Self> {
+ let capacity = (((num_points * N) as f32) * index_growth_factor) as usize;
+
+ Ok(Self {
+ data: AlignedBoxWithSlice::new(capacity, mem::size_of::<T>() * 16)?,
+ num_points,
+ num_active_pts: num_points,
+ capacity,
+ })
+ }
+
+ /// get immutable data slice
+ pub fn get_data(&self) -> &[T] {
+ &self.data
+ }
+
+ /// Build the dataset from file
+ pub fn build_from_file(&mut self, filename: &str, num_points_to_load: usize) -> ANNResult<()> {
+ println!(
+ "Loading {} vectors from file {} into dataset...",
+ num_points_to_load, filename
+ );
+ self.num_active_pts = num_points_to_load;
+
+ copy_aligned_data_from_file(filename, self.into_dto(), 0)?;
+
+ println!("Dataset loaded.");
+ Ok(())
+ }
+
+ /// Append the dataset from file
+ pub fn append_from_file(
+ &mut self,
+ filename: &str,
+ num_points_to_append: usize,
+ ) -> ANNResult<()> {
+ println!(
+ "Appending {} vectors from file {} into dataset...",
+ num_points_to_append, filename
+ );
+ if self.num_points + num_points_to_append > self.capacity {
+ return Err(ANNError::log_index_error(format!(
+ "Cannot append {} points to dataset of capacity {}",
+ num_points_to_append, self.capacity
+ )));
+ }
+
+ let pts_offset = self.num_active_pts;
+ copy_aligned_data_from_file(filename, self.into_dto(), pts_offset)?;
+
+ self.num_active_pts += num_points_to_append;
+ self.num_points += num_points_to_append;
+
+ println!("Dataset appended.");
+ Ok(())
+ }
+
+ /// Get vertex by id
+ pub fn get_vertex(&'a self, id: u32) -> ANNResult<Vertex<'a, T, N>> {
+ let start = id as usize * N;
+ let end = start + N;
+
+ if end <= self.data.len() {
+ let val = <&[T; N]>::try_from(&self.data[start..end]).map_err(|err| {
+ ANNError::log_index_error(format!("Failed to get vertex {}, err={}", id, err))
+ })?;
+ Ok(Vertex::new(val, id))
+ } else {
+ Err(ANNError::log_index_error(format!(
+ "Invalid vertex id {}.",
+ id
+ )))
+ }
+ }
+
+ /// Get full precision distance between two nodes
+ pub fn get_distance(&self, id1: u32, id2: u32, metric: Metric) -> ANNResult<f32> {
+ let vertex1 = self.get_vertex(id1)?;
+ let vertex2 = self.get_vertex(id2)?;
+
+ Ok(vertex1.compare(&vertex2, metric))
+ }
+
+ /// find out the medoid, the vertex in the dataset that is closest to the centroid
+ pub fn calculate_medoid_point_id(&self) -> ANNResult<u32> {
+ Ok(self.find_nearest_point_id(self.calculate_centroid_point()?))
+ }
+
+ /// calculate centroid, average of all vertices in the dataset
+ fn calculate_centroid_point(&self) -> ANNResult<[f32; N]> {
+ // Allocate and initialize the centroid vector
+ let mut center: [f32; N] = [0.0; N];
+
+ // Sum the data points' components
+ for i in 0..self.num_active_pts {
+ let vertex = self.get_vertex(i as u32)?;
+ let vertex_slice = vertex.vector();
+ for j in 0..N {
+ center[j] += vertex_slice[j].into();
+ }
+ }
+
+ // Divide by the number of points to calculate the centroid
+ let capacity = self.num_active_pts as f32;
+ for item in center.iter_mut().take(N) {
+ *item /= capacity;
+ }
+
+ Ok(center)
+ }
+
+ /// find out the vertex closest to the given point
+ fn find_nearest_point_id(&self, point: [f32; N]) -> u32 {
+ // compute all to one distance
+ let mut distances = vec![0f32; self.num_active_pts];
+ let slice = &self.data[..];
+ distances.par_iter_mut().enumerate().for_each(|(i, dist)| {
+ let start = i * N;
+ for j in 0..N {
+ let diff: f32 = (point.as_slice()[j] - slice[start + j].into())
+ * (point.as_slice()[j] - slice[start + j].into());
+ *dist += diff;
+ }
+ });
+
+ let mut min_idx = 0;
+ let mut min_dist = f32::MAX;
+ for (i, distance) in distances.iter().enumerate().take(self.num_active_pts) {
+ if *distance < min_dist {
+ min_idx = i;
+ min_dist = *distance;
+ }
+ }
+ min_idx as u32
+ }
+
+ /// Prefetch vertex data in the memory hierarchy
+ /// NOTE: good efficiency when total_vec_size is integral multiple of 64
+ #[inline]
+ pub fn prefetch_vector(&self, id: u32) {
+ let start = id as usize * N;
+ let end = start + N;
+
+ if end <= self.data.len() {
+ let vec = &self.data[start..end];
+ vector::prefetch_vector(vec);
+ }
+ }
+
+ /// Convert into dto object
+ pub fn into_dto(&mut self) -> DatasetDto<T> {
+ DatasetDto {
+ data: &mut self.data,
+ rounded_dim: N,
+ }
+ }
+}
+
+/// Dataset dto used for other layer, such as storage
+/// N is the aligned dimension
+#[derive(Debug)]
+pub struct DatasetDto<'a, T> {
+ /// data slice borrow from dataset
+ pub data: &'a mut [T],
+
+ /// rounded dimension
+ pub rounded_dim: usize,
+}
+
+#[cfg(test)]
+mod dataset_test {
+ use std::fs;
+
+ use super::*;
+ use crate::model::vertex::DIM_128;
+
+ #[test]
+ fn get_vertex_within_range() {
+ let num_points = 1_000_000;
+ let id = 999_999;
+ let dataset = InmemDataset::<f32, DIM_128>::new(num_points, 1f32).unwrap();
+
+ let vertex = dataset.get_vertex(999_999).unwrap();
+
+ assert_eq!(vertex.vertex_id(), id);
+ assert_eq!(vertex.vector().len(), DIM_128);
+ assert_eq!(vertex.vector().as_ptr(), unsafe {
+ dataset.data.as_ptr().add((id as usize) * DIM_128)
+ });
+ }
+
+ #[test]
+ fn get_vertex_out_of_range() {
+ let num_points = 1_000_000;
+ let invalid_id = 1_000_000;
+ let dataset = InmemDataset::<f32, DIM_128>::new(num_points, 1f32).unwrap();
+
+ if dataset.get_vertex(invalid_id).is_ok() {
+ panic!("id ({}) should be out of range", invalid_id)
+ };
+ }
+
+ #[test]
+ fn load_data_test() {
+ let file_name = "dataset_test_load_data_test.bin";
+ //npoints=2, dim=8, 2 vectors [1.0;8] [2.0;8]
+ let data: [u8; 72] = [
+ 2, 0, 0, 0, 8, 0, 0, 0, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
+ 0x40, 0x40, 0x00, 0x00, 0x80, 0x40, 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40,
+ 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x10, 0x41, 0x00, 0x00,
+ 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41, 0x00, 0x00, 0x50, 0x41,
+ 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x00, 0x80, 0x41,
+ ];
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+
+ let mut dataset = InmemDataset::<f32, 8>::new(2, 1f32).unwrap();
+
+ match copy_aligned_data_from_file(
+ file_name,
+ dataset.into_dto(),
+ 0,
+ ) {
+ Ok((npts, dim)) => {
+ fs::remove_file(file_name).expect("Failed to delete file");
+ assert!(npts == 2);
+ assert!(dim == 8);
+ assert!(dataset.data.len() == 16);
+
+ let first_vertex = dataset.get_vertex(0).unwrap();
+ let second_vertex = dataset.get_vertex(1).unwrap();
+
+ assert!(*first_vertex.vector() == [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
+ assert!(*second_vertex.vector() == [9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0]);
+ }
+ Err(e) => {
+ fs::remove_file(file_name).expect("Failed to delete file");
+ panic!("{}", e)
+ }
+ }
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/mod.rs
new file mode 100644
index 0000000..4e7e683
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/data_store/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod inmem_dataset;
+pub use inmem_dataset::InmemDataset;
+pub use inmem_dataset::DatasetDto;
+
+mod disk_scratch_dataset;
+pub use disk_scratch_dataset::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/adjacency_list.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/adjacency_list.rs
new file mode 100644
index 0000000..7ad2d7d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/adjacency_list.rs
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Adjacency List
+
+use std::ops::{Deref, DerefMut};
+
+#[derive(Debug, Eq, PartialEq)]
+/// Represents the out neighbors of a vertex
+pub struct AdjacencyList {
+ edges: Vec<u32>,
+}
+
+/// In-mem index related limits
+const GRAPH_SLACK_FACTOR: f32 = 1.3_f32;
+
+impl AdjacencyList {
+ /// Create AdjacencyList with capacity slack for a range.
+ pub fn for_range(range: usize) -> Self {
+ let capacity = (range as f32 * GRAPH_SLACK_FACTOR).ceil() as usize;
+ Self {
+ edges: Vec::with_capacity(capacity),
+ }
+ }
+
+ /// Push a node to the list of neighbors for the given node.
+ pub fn push(&mut self, node_id: u32) {
+ debug_assert!(self.edges.len() < self.edges.capacity());
+ self.edges.push(node_id);
+ }
+}
+
+impl From<Vec<u32>> for AdjacencyList {
+ fn from(edges: Vec<u32>) -> Self {
+ Self { edges }
+ }
+}
+
+impl Deref for AdjacencyList {
+ type Target = Vec<u32>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.edges
+ }
+}
+
+impl DerefMut for AdjacencyList {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.edges
+ }
+}
+
+impl<'a> IntoIterator for &'a AdjacencyList {
+ type Item = &'a u32;
+ type IntoIter = std::slice::Iter<'a, u32>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.edges.iter()
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/disk_graph.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/disk_graph.rs
new file mode 100644
index 0000000..49190b1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/disk_graph.rs
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_docs)]
+
+//! Disk graph
+
+use byteorder::{LittleEndian, ByteOrder};
+use vector::FullPrecisionDistance;
+
+use crate::common::{ANNResult, ANNError};
+use crate::model::data_store::DiskScratchDataset;
+use crate::model::Vertex;
+use crate::storage::DiskGraphStorage;
+
+use super::{VertexAndNeighbors, SectorGraph, AdjacencyList};
+
+/// Disk graph
+pub struct DiskGraph {
+ /// dim of fp vector in disk sector
+ dim: usize,
+
+ /// number of nodes per sector
+ num_nodes_per_sector: u64,
+
+ /// max node length in bytes
+ max_node_len: u64,
+
+ /// the len of fp vector
+ fp_vector_len: u64,
+
+ /// list of nodes (vertex_id) to fetch from disk
+ nodes_to_fetch: Vec<u32>,
+
+ /// Sector graph
+ sector_graph: SectorGraph,
+}
+
+impl<'a> DiskGraph {
+ /// Create DiskGraph instance
+ pub fn new(
+ dim: usize,
+ num_nodes_per_sector: u64,
+ max_node_len: u64,
+ fp_vector_len: u64,
+ beam_width: usize,
+ graph_storage: DiskGraphStorage,
+ ) -> ANNResult<Self> {
+ let graph = Self {
+ dim,
+ num_nodes_per_sector,
+ max_node_len,
+ fp_vector_len,
+ nodes_to_fetch: Vec::with_capacity(2 * beam_width),
+ sector_graph: SectorGraph::new(graph_storage)?,
+ };
+
+ Ok(graph)
+ }
+
+ /// Add vertex_id into the list to fetch from disk
+ pub fn add_vertex(&mut self, id: u32) {
+ self.nodes_to_fetch.push(id);
+ }
+
+ /// Fetch nodes from disk index
+ pub fn fetch_nodes(&mut self) -> ANNResult<()> {
+ let sectors_to_fetch: Vec<u64> = self.nodes_to_fetch.iter().map(|&id| self.node_sector_index(id)).collect();
+ self.sector_graph.read_graph(&sectors_to_fetch)?;
+
+ Ok(())
+ }
+
+ /// Copy disk fp vector to DiskScratchDataset
+ /// Return the fp vector with aligned dim from DiskScratchDataset
+ pub fn copy_fp_vector_to_disk_scratch_dataset<T, const N: usize>(
+ &self,
+ node_index: usize,
+ disk_scratch_dataset: &'a mut DiskScratchDataset<T, N>
+ ) -> ANNResult<Vertex<'a, T, N>>
+ where
+ [T; N]: FullPrecisionDistance<T, N>,
+ {
+ if self.dim > N {
+ return Err(ANNError::log_index_error(format!(
+ "copy_sector_fp_to_aligned_dataset: dim {} is greater than aligned dim {}",
+ self.dim, N)));
+ }
+
+ let fp_vector_buf = self.node_fp_vector_buf(node_index);
+
+ // Safety condition is met here
+ let aligned_dim_vector = unsafe { disk_scratch_dataset.memcpy_from_fp_vector_buf(fp_vector_buf) };
+
+ Vertex::<'a, T, N>::try_from((aligned_dim_vector, self.nodes_to_fetch[node_index]))
+ .map_err(|err| ANNError::log_index_error(format!("TryFromSliceError: failed to get Vertex for disk index node, err={}", err)))
+ }
+
+ /// Reset graph
+ pub fn reset(&mut self) {
+ self.nodes_to_fetch.clear();
+ self.sector_graph.reset();
+ }
+
+ fn get_vertex_and_neighbors(&self, node_index: usize) -> VertexAndNeighbors {
+ let node_disk_buf = self.node_disk_buf(node_index);
+ let buf = &node_disk_buf[self.fp_vector_len as usize..];
+ let num_neighbors = LittleEndian::read_u32(&buf[0..4]) as usize;
+ let neighbors_buf = &buf[4..4 + num_neighbors * 4];
+
+ let mut adjacency_list = AdjacencyList::for_range(num_neighbors);
+ for chunk in neighbors_buf.chunks(4) {
+ let neighbor_id = LittleEndian::read_u32(chunk);
+ adjacency_list.push(neighbor_id);
+ }
+
+ VertexAndNeighbors::new(self.nodes_to_fetch[node_index], adjacency_list)
+ }
+
+ #[inline]
+ fn node_sector_index(&self, vertex_id: u32) -> u64 {
+ vertex_id as u64 / self.num_nodes_per_sector + 1
+ }
+
+ #[inline]
+ fn node_disk_buf(&self, node_index: usize) -> &[u8] {
+ let vertex_id = self.nodes_to_fetch[node_index];
+
+ // get sector_buf where this node is located
+ let sector_buf = self.sector_graph.get_sector_buf(node_index);
+ let node_offset = (vertex_id as u64 % self.num_nodes_per_sector * self.max_node_len) as usize;
+ &sector_buf[node_offset..node_offset + self.max_node_len as usize]
+ }
+
+ #[inline]
+ fn node_fp_vector_buf(&self, node_index: usize) -> &[u8] {
+ let node_disk_buf = self.node_disk_buf(node_index);
+ &node_disk_buf[..self.fp_vector_len as usize]
+ }
+}
+
+/// Iterator for DiskGraph
+pub struct DiskGraphIntoIterator<'a> {
+ graph: &'a DiskGraph,
+ index: usize,
+}
+
+impl<'a> IntoIterator for &'a DiskGraph
+{
+ type IntoIter = DiskGraphIntoIterator<'a>;
+ type Item = ANNResult<(usize, VertexAndNeighbors)>;
+
+ #[inline]
+ fn into_iter(self) -> Self::IntoIter {
+ DiskGraphIntoIterator {
+ graph: self,
+ index: 0,
+ }
+ }
+}
+
+impl<'a> Iterator for DiskGraphIntoIterator<'a>
+{
+ type Item = ANNResult<(usize, VertexAndNeighbors)>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.index >= self.graph.nodes_to_fetch.len() {
+ return None;
+ }
+
+ let node_index = self.index;
+ let vertex_and_neighbors = self.graph.get_vertex_and_neighbors(self.index);
+
+ self.index += 1;
+ Some(Ok((node_index, vertex_and_neighbors)))
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/inmem_graph.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/inmem_graph.rs
new file mode 100644
index 0000000..3d08db8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/inmem_graph.rs
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! In-memory graph
+
+use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
+
+use crate::common::ANNError;
+
+use super::VertexAndNeighbors;
+
+/// The entire graph of in-memory index
+#[derive(Debug)]
+pub struct InMemoryGraph {
+ /// The entire graph
+ pub final_graph: Vec<RwLock<VertexAndNeighbors>>,
+}
+
+impl InMemoryGraph {
+ /// Create InMemoryGraph instance
+ pub fn new(size: usize, max_degree: u32) -> Self {
+ let mut graph = Vec::with_capacity(size);
+ for id in 0..size {
+ graph.push(RwLock::new(VertexAndNeighbors::for_range(
+ id as u32,
+ max_degree as usize,
+ )));
+ }
+ Self { final_graph: graph }
+ }
+
+ /// Size of graph
+ pub fn size(&self) -> usize {
+ self.final_graph.len()
+ }
+
+ /// Extend the graph by size vectors
+ pub fn extend(&mut self, size: usize, max_degree: u32) {
+ for id in 0..size {
+ self.final_graph
+ .push(RwLock::new(VertexAndNeighbors::for_range(
+ id as u32,
+ max_degree as usize,
+ )));
+ }
+ }
+
+ /// Get read guard of vertex_id
+ pub fn read_vertex_and_neighbors(
+ &self,
+ vertex_id: u32,
+ ) -> Result<RwLockReadGuard<VertexAndNeighbors>, ANNError> {
+ self.final_graph[vertex_id as usize].read().map_err(|err| {
+ ANNError::log_lock_poison_error(format!(
+ "PoisonError: Lock poisoned when reading final_graph for vertex_id {}, err={}",
+ vertex_id, err
+ ))
+ })
+ }
+
+ /// Get write guard of vertex_id
+ pub fn write_vertex_and_neighbors(
+ &self,
+ vertex_id: u32,
+ ) -> Result<RwLockWriteGuard<VertexAndNeighbors>, ANNError> {
+ self.final_graph[vertex_id as usize].write().map_err(|err| {
+ ANNError::log_lock_poison_error(format!(
+ "PoisonError: Lock poisoned when writing final_graph for vertex_id {}, err={}",
+ vertex_id, err
+ ))
+ })
+ }
+}
+
+#[cfg(test)]
+mod graph_tests {
+ use crate::model::{graph::AdjacencyList, GRAPH_SLACK_FACTOR};
+
+ use super::*;
+
+ #[test]
+ fn test_new() {
+ let graph = InMemoryGraph::new(10, 10);
+ let capacity = (GRAPH_SLACK_FACTOR * 10_f64).ceil() as usize;
+
+ assert_eq!(graph.final_graph.len(), 10);
+ for i in 0..10 {
+ let neighbor = graph.final_graph[i].read().unwrap();
+ assert_eq!(neighbor.vertex_id, i as u32);
+ assert_eq!(neighbor.get_neighbors().capacity(), capacity);
+ }
+ }
+
+ #[test]
+ fn test_size() {
+ let graph = InMemoryGraph::new(10, 10);
+ assert_eq!(graph.size(), 10);
+ }
+
+ #[test]
+ fn test_extend() {
+ let mut graph = InMemoryGraph::new(10, 10);
+ graph.extend(10, 10);
+
+ assert_eq!(graph.size(), 20);
+
+ let capacity = (GRAPH_SLACK_FACTOR * 10_f64).ceil() as usize;
+ let mut id: u32 = 0;
+
+ for i in 10..20 {
+ let neighbor = graph.final_graph[i].read().unwrap();
+ assert_eq!(neighbor.vertex_id, id);
+ assert_eq!(neighbor.get_neighbors().capacity(), capacity);
+ id += 1;
+ }
+ }
+
+ #[test]
+ fn test_read_vertex_and_neighbors() {
+ let graph = InMemoryGraph::new(10, 10);
+ let neighbor = graph.read_vertex_and_neighbors(0);
+ assert!(neighbor.is_ok());
+ assert_eq!(neighbor.unwrap().vertex_id, 0);
+ }
+
+ #[test]
+ fn test_write_vertex_and_neighbors() {
+ let graph = InMemoryGraph::new(10, 10);
+ {
+ let neighbor = graph.write_vertex_and_neighbors(0);
+ assert!(neighbor.is_ok());
+ neighbor.unwrap().add_to_neighbors(10, 10);
+ }
+
+ let neighbor = graph.read_vertex_and_neighbors(0).unwrap();
+ assert_eq!(neighbor.get_neighbors(), &AdjacencyList::from(vec![10_u32]));
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/mod.rs
new file mode 100644
index 0000000..d1457f1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/mod.rs
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod inmem_graph;
+pub use inmem_graph::InMemoryGraph;
+
+pub mod vertex_and_neighbors;
+pub use vertex_and_neighbors::VertexAndNeighbors;
+
+mod adjacency_list;
+pub use adjacency_list::AdjacencyList;
+
+mod sector_graph;
+pub use sector_graph::*;
+
+mod disk_graph;
+pub use disk_graph::*;
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/sector_graph.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/sector_graph.rs
new file mode 100644
index 0000000..e51e0bf
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/sector_graph.rs
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_docs)]
+
+//! Sector graph
+
+use std::ops::Deref;
+
+use crate::common::{AlignedBoxWithSlice, ANNResult, ANNError};
+use crate::model::{MAX_N_SECTOR_READS, SECTOR_LEN, AlignedRead};
+use crate::storage::DiskGraphStorage;
+
+/// Sector graph read from disk index
+pub struct SectorGraph {
+ /// Sector bytes from disk
+ /// One sector has num_nodes_per_sector nodes
+ /// Each node's layout: {full precision vector:[T; DIM]}{num_nbrs: u32}{neighbors: [u32; num_nbrs]}
+ /// The fp vector is not aligned
+ sectors_data: AlignedBoxWithSlice<u8>,
+
+ /// Graph storage to read sectors
+ graph_storage: DiskGraphStorage,
+
+ /// Current sector index into which the next read reads data
+ cur_sector_idx: u64,
+}
+
+impl SectorGraph {
+ /// Create SectorGraph instance
+ pub fn new(graph_storage: DiskGraphStorage) -> ANNResult<Self> {
+ Ok(Self {
+ sectors_data: AlignedBoxWithSlice::new(MAX_N_SECTOR_READS * SECTOR_LEN, SECTOR_LEN)?,
+ graph_storage,
+ cur_sector_idx: 0,
+ })
+ }
+
+ /// Reset SectorGraph
+ pub fn reset(&mut self) {
+ self.cur_sector_idx = 0;
+ }
+
+ /// Read sectors into sectors_data
+ /// They are in the same order as sectors_to_fetch
+ pub fn read_graph(&mut self, sectors_to_fetch: &[u64]) -> ANNResult<()> {
+ let cur_sector_idx_usize: usize = self.cur_sector_idx.try_into()?;
+ if sectors_to_fetch.len() > MAX_N_SECTOR_READS - cur_sector_idx_usize {
+ return Err(ANNError::log_index_error(format!(
+ "Trying to read too many sectors. number of sectors to read: {}, max number of sectors can read: {}",
+ sectors_to_fetch.len(),
+ MAX_N_SECTOR_READS - cur_sector_idx_usize,
+ )));
+ }
+
+ let mut sector_slices = self.sectors_data.split_into_nonoverlapping_mut_slices(
+ cur_sector_idx_usize * SECTOR_LEN..(cur_sector_idx_usize + sectors_to_fetch.len()) * SECTOR_LEN,
+ SECTOR_LEN)?;
+
+ let mut read_requests = Vec::with_capacity(sector_slices.len());
+ for (local_sector_idx, slice) in sector_slices.iter_mut().enumerate() {
+ let sector_id = sectors_to_fetch[local_sector_idx];
+ read_requests.push(AlignedRead::new(sector_id * SECTOR_LEN as u64, slice)?);
+ }
+
+ self.graph_storage.read(&mut read_requests)?;
+ self.cur_sector_idx += sectors_to_fetch.len() as u64;
+
+ Ok(())
+ }
+
+ /// Get sector data by local index
+ #[inline]
+ pub fn get_sector_buf(&self, local_sector_idx: usize) -> &[u8] {
+ &self.sectors_data[local_sector_idx * SECTOR_LEN..(local_sector_idx + 1) * SECTOR_LEN]
+ }
+}
+
+impl Deref for SectorGraph {
+ type Target = [u8];
+
+ fn deref(&self) -> &Self::Target {
+ &self.sectors_data
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/vertex_and_neighbors.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/vertex_and_neighbors.rs
new file mode 100644
index 0000000..a9fa389
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/graph/vertex_and_neighbors.rs
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Vertex and its Adjacency List
+
+use crate::model::GRAPH_SLACK_FACTOR;
+
+use super::AdjacencyList;
+
+/// The out neighbors of vertex_id
+#[derive(Debug)]
+pub struct VertexAndNeighbors {
+ /// The id of the vertex
+ pub vertex_id: u32,
+
+ /// All out neighbors (id) of vertex_id
+ neighbors: AdjacencyList,
+}
+
+impl VertexAndNeighbors {
+ /// Create VertexAndNeighbors with id and capacity
+ pub fn for_range(id: u32, range: usize) -> Self {
+ Self {
+ vertex_id: id,
+ neighbors: AdjacencyList::for_range(range),
+ }
+ }
+
+ /// Create VertexAndNeighbors with id and neighbors
+ pub fn new(vertex_id: u32, neighbors: AdjacencyList) -> Self {
+ Self {
+ vertex_id,
+ neighbors,
+ }
+ }
+
+ /// Get size of neighbors
+ #[inline(always)]
+ pub fn size(&self) -> usize {
+ self.neighbors.len()
+ }
+
+ /// Update the neighbors vector (post a pruning exercise)
+ #[inline(always)]
+ pub fn set_neighbors(&mut self, new_neighbors: AdjacencyList) {
+ // Replace the graph entry with the pruned neighbors
+ self.neighbors = new_neighbors;
+ }
+
+ /// Get the neighbors
+ #[inline(always)]
+ pub fn get_neighbors(&self) -> &AdjacencyList {
+ &self.neighbors
+ }
+
+ /// Adds a node to the list of neighbors for the given node.
+ ///
+ /// # Arguments
+ ///
+ /// * `node_id` - The ID of the node to add.
+ /// * `range` - The range of the graph.
+ ///
+ /// # Return
+ ///
+ /// Returns `None` if the node is already in the list of neighbors, or a `Vec` containing the updated list of neighbors if the list of neighbors is full.
+ pub fn add_to_neighbors(&mut self, node_id: u32, range: u32) -> Option<Vec<u32>> {
+ // Check if n is already in the graph entry
+ if self.neighbors.contains(&node_id) {
+ return None;
+ }
+
+ let neighbor_len = self.neighbors.len();
+
+ // If not, check if the graph entry has enough space
+ if neighbor_len < (GRAPH_SLACK_FACTOR * range as f64) as usize {
+ // If yes, add n to the graph entry
+ self.neighbors.push(node_id);
+ return None;
+ }
+
+ let mut copy_of_neighbors = Vec::with_capacity(neighbor_len + 1);
+ unsafe {
+ let dst = copy_of_neighbors.as_mut_ptr();
+ std::ptr::copy_nonoverlapping(self.neighbors.as_ptr(), dst, neighbor_len);
+ dst.add(neighbor_len).write(node_id);
+ copy_of_neighbors.set_len(neighbor_len + 1);
+ }
+
+ Some(copy_of_neighbors)
+ }
+}
+
+#[cfg(test)]
+mod vertex_and_neighbors_tests {
+ use crate::model::GRAPH_SLACK_FACTOR;
+
+ use super::*;
+
+ #[test]
+ fn test_set_with_capacity() {
+ let neighbors = VertexAndNeighbors::for_range(20, 10);
+ assert_eq!(neighbors.vertex_id, 20);
+ assert_eq!(
+ neighbors.neighbors.capacity(),
+ (10_f32 * GRAPH_SLACK_FACTOR as f32).ceil() as usize
+ );
+ }
+
+ #[test]
+ fn test_size() {
+ let mut neighbors = VertexAndNeighbors::for_range(20, 10);
+
+ for i in 0..5 {
+ neighbors.neighbors.push(i);
+ }
+
+ assert_eq!(neighbors.size(), 5);
+ }
+
+ #[test]
+ fn test_set_neighbors() {
+ let mut neighbors = VertexAndNeighbors::for_range(20, 10);
+ let new_vec = AdjacencyList::from(vec![1, 2, 3, 4, 5]);
+ neighbors.set_neighbors(AdjacencyList::from(new_vec.clone()));
+
+ assert_eq!(neighbors.neighbors, new_vec);
+ }
+
+ #[test]
+ fn test_get_neighbors() {
+ let mut neighbors = VertexAndNeighbors::for_range(20, 10);
+ neighbors.set_neighbors(AdjacencyList::from(vec![1, 2, 3, 4, 5]));
+ let neighbor_ref = neighbors.get_neighbors();
+
+ assert!(std::ptr::eq(&neighbors.neighbors, neighbor_ref))
+ }
+
+ #[test]
+ fn test_add_to_neighbors() {
+ let mut neighbors = VertexAndNeighbors::for_range(20, 10);
+
+ assert_eq!(neighbors.add_to_neighbors(1, 1), None);
+ assert_eq!(neighbors.neighbors, AdjacencyList::from(vec![1]));
+
+ assert_eq!(neighbors.add_to_neighbors(1, 1), None);
+ assert_eq!(neighbors.neighbors, AdjacencyList::from(vec![1]));
+
+ let ret = neighbors.add_to_neighbors(2, 1);
+ assert!(ret.is_some());
+ assert_eq!(ret.unwrap(), vec![1, 2]);
+ assert_eq!(neighbors.neighbors, AdjacencyList::from(vec![1]));
+
+ assert_eq!(neighbors.add_to_neighbors(2, 2), None);
+ assert_eq!(neighbors.neighbors, AdjacencyList::from(vec![1, 2]));
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/mod.rs
new file mode 100644
index 0000000..a4f15ee
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/mod.rs
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub mod neighbor;
+pub use neighbor::Neighbor;
+pub use neighbor::NeighborPriorityQueue;
+
+pub mod data_store;
+pub use data_store::InmemDataset;
+
+pub mod graph;
+pub use graph::InMemoryGraph;
+pub use graph::VertexAndNeighbors;
+
+pub mod configuration;
+pub use configuration::*;
+
+pub mod scratch;
+pub use scratch::*;
+
+pub mod vertex;
+pub use vertex::Vertex;
+
+pub mod pq;
+pub use pq::*;
+
+pub mod windows_aligned_file_reader;
+pub use windows_aligned_file_reader::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/mod.rs
new file mode 100644
index 0000000..cd0dbad
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/mod.rs
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod neighbor;
+pub use neighbor::*;
+
+mod neighbor_priority_queue;
+pub use neighbor_priority_queue::*;
+
+mod sorted_neighbor_vector;
+pub use sorted_neighbor_vector::SortedNeighborVector;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/neighbor.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/neighbor.rs
new file mode 100644
index 0000000..8c712bc
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/neighbor.rs
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::cmp::Ordering;
+
+/// Neighbor node
+#[derive(Debug, Clone, Copy)]
+pub struct Neighbor {
+ /// The id of the node
+ pub id: u32,
+
+ /// The distance from the query node to current node
+ pub distance: f32,
+
+ /// Whether the current is visited or not
+ pub visited: bool,
+}
+
+impl Neighbor {
+ /// Create the neighbor node and it has not been visited
+ pub fn new (id: u32, distance: f32) -> Self {
+ Self {
+ id,
+ distance,
+ visited: false
+ }
+ }
+}
+
+impl Default for Neighbor {
+ fn default() -> Self {
+ Self { id: 0, distance: 0.0_f32, visited: false }
+ }
+}
+
+impl PartialEq for Neighbor {
+ #[inline]
+ fn eq(&self, other: &Self) -> bool {
+ self.id == other.id
+ }
+}
+
+impl Eq for Neighbor {}
+
+impl Ord for Neighbor {
+ fn cmp(&self, other: &Self) -> Ordering {
+ let ord = self.distance.partial_cmp(&other.distance).unwrap_or(std::cmp::Ordering::Equal);
+
+ if ord == Ordering::Equal {
+ return self.id.cmp(&other.id);
+ }
+
+ ord
+ }
+}
+
+impl PartialOrd for Neighbor {
+ #[inline]
+ fn lt(&self, other: &Self) -> bool {
+ self.distance < other.distance || (self.distance == other.distance && self.id < other.id)
+ }
+
+ // Reason for allowing panic = "Does not support comparing Neighbor with partial_cmp"
+ #[allow(clippy::panic)]
+ fn partial_cmp(&self, _: &Self) -> Option<std::cmp::Ordering> {
+ panic!("Neighbor only allows eq and lt")
+ }
+}
+
+#[cfg(test)]
+mod neighbor_test {
+ use super::*;
+
+ #[test]
+ fn eq_lt_works() {
+ let n1 = Neighbor::new(1, 1.1);
+ let n2 = Neighbor::new(2, 2.0);
+ let n3 = Neighbor::new(1, 1.1);
+
+ assert!(n1 != n2);
+ assert!(n1 < n2);
+ assert!(n1 == n3);
+ }
+
+ #[test]
+ #[should_panic]
+ fn gt_should_panic() {
+ let n1 = Neighbor::new(1, 1.1);
+ let n2 = Neighbor::new(2, 2.0);
+
+ assert!(n2 > n1);
+ }
+
+ #[test]
+ #[should_panic]
+ fn le_should_panic() {
+ let n1 = Neighbor::new(1, 1.1);
+ let n2 = Neighbor::new(2, 2.0);
+
+ assert!(n1 <= n2);
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/neighbor_priority_queue.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/neighbor_priority_queue.rs
new file mode 100644
index 0000000..81b1610
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/neighbor_priority_queue.rs
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use crate::model::Neighbor;
+
+/// Neighbor priority Queue based on the distance to the query node
+#[derive(Debug)]
+pub struct NeighborPriorityQueue {
+ /// The size of the priority queue
+ size: usize,
+
+ /// The capacity of the priority queue
+ capacity: usize,
+
+ /// The current notvisited neighbor whose distance is smallest among all notvisited neighbor
+ cur: usize,
+
+ /// The neighbor collection
+ data: Vec<Neighbor>,
+}
+
+impl Default for NeighborPriorityQueue {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl NeighborPriorityQueue {
+ /// Create NeighborPriorityQueue without capacity
+ pub fn new() -> Self {
+ Self {
+ size: 0,
+ capacity: 0,
+ cur: 0,
+ data: Vec::new(),
+ }
+ }
+
+ /// Create NeighborPriorityQueue with capacity
+ pub fn with_capacity(capacity: usize) -> Self {
+ Self {
+ size: 0,
+ capacity,
+ cur: 0,
+ data: vec![Neighbor::default(); capacity + 1],
+ }
+ }
+
+ /// Inserts item with order.
+ /// The item will be dropped if queue is full / already exist in queue / it has a greater distance than the last item.
+ /// The set cursor that is used to pop() the next item will be set to the lowest index of an uncheck item.
+ pub fn insert(&mut self, nbr: Neighbor) {
+ if self.size == self.capacity && self.get_at(self.size - 1) < &nbr {
+ return;
+ }
+
+ let mut lo = 0;
+ let mut hi = self.size;
+ while lo < hi {
+ let mid = (lo + hi) >> 1;
+ if &nbr < self.get_at(mid) {
+ hi = mid;
+ } else if self.get_at(mid).id == nbr.id {
+ // Make sure the same neighbor isn't inserted into the set
+ return;
+ } else {
+ lo = mid + 1;
+ }
+ }
+
+ if lo < self.capacity {
+ self.data.copy_within(lo..self.size, lo + 1);
+ }
+ self.data[lo] = Neighbor::new(nbr.id, nbr.distance);
+ if self.size < self.capacity {
+ self.size += 1;
+ }
+ if lo < self.cur {
+ self.cur = lo;
+ }
+ }
+
+ /// Get the neighbor at index - SAFETY: index must be less than size
+ fn get_at(&self, index: usize) -> &Neighbor {
+ unsafe { self.data.get_unchecked(index) }
+ }
+
+ /// Get the closest and notvisited neighbor
+ pub fn closest_notvisited(&mut self) -> Neighbor {
+ self.data[self.cur].visited = true;
+ let pre = self.cur;
+ while self.cur < self.size && self.get_at(self.cur).visited {
+ self.cur += 1;
+ }
+ self.data[pre]
+ }
+
+ /// Whether there is notvisited node or not
+ pub fn has_notvisited_node(&self) -> bool {
+ self.cur < self.size
+ }
+
+ /// Get the size of the NeighborPriorityQueue
+ pub fn size(&self) -> usize {
+ self.size
+ }
+
+ /// Get the capacity of the NeighborPriorityQueue
+ pub fn capacity(&self) -> usize {
+ self.capacity
+ }
+
+ /// Sets an artificial capacity of the NeighborPriorityQueue. For benchmarking purposes only.
+ pub fn set_capacity(&mut self, capacity: usize) {
+ if capacity < self.data.len() {
+ self.capacity = capacity;
+ }
+ }
+
+ /// Reserve capacity
+ pub fn reserve(&mut self, capacity: usize) {
+ if capacity > self.capacity {
+ self.data.resize(capacity + 1, Neighbor::default());
+ self.capacity = capacity;
+ }
+ }
+
+ /// Set size and cur to 0
+ pub fn clear(&mut self) {
+ self.size = 0;
+ self.cur = 0;
+ }
+}
+
+impl std::ops::Index<usize> for NeighborPriorityQueue {
+ type Output = Neighbor;
+
+ fn index(&self, i: usize) -> &Self::Output {
+ &self.data[i]
+ }
+}
+
+#[cfg(test)]
+mod neighbor_priority_queue_test {
+ use super::*;
+
+ #[test]
+ fn test_reserve_capacity() {
+ let mut queue = NeighborPriorityQueue::with_capacity(10);
+ assert_eq!(queue.capacity(), 10);
+ queue.reserve(20);
+ assert_eq!(queue.capacity(), 20);
+ }
+
+ #[test]
+ fn test_insert() {
+ let mut queue = NeighborPriorityQueue::with_capacity(3);
+ assert_eq!(queue.size(), 0);
+ queue.insert(Neighbor::new(1, 1.0));
+ queue.insert(Neighbor::new(2, 0.5));
+ assert_eq!(queue.size(), 2);
+ queue.insert(Neighbor::new(2, 0.5)); // should be ignored as the same neighbor
+ assert_eq!(queue.size(), 2);
+ queue.insert(Neighbor::new(3, 0.9));
+ assert_eq!(queue.size(), 3);
+ assert_eq!(queue[2].id, 1);
+ queue.insert(Neighbor::new(4, 2.0)); // should be dropped as queue is full and distance is greater than last item
+ assert_eq!(queue.size(), 3);
+ assert_eq!(queue[0].id, 2); // node id in queue should be [2,3,1]
+ assert_eq!(queue[1].id, 3);
+ assert_eq!(queue[2].id, 1);
+ println!("{:?}", queue);
+ }
+
+ #[test]
+ fn test_index() {
+ let mut queue = NeighborPriorityQueue::with_capacity(3);
+ queue.insert(Neighbor::new(1, 1.0));
+ queue.insert(Neighbor::new(2, 0.5));
+ queue.insert(Neighbor::new(3, 1.5));
+ assert_eq!(queue[0].id, 2);
+ assert_eq!(queue[0].distance, 0.5);
+ }
+
+ #[test]
+ fn test_visit() {
+ let mut queue = NeighborPriorityQueue::with_capacity(3);
+ queue.insert(Neighbor::new(1, 1.0));
+ queue.insert(Neighbor::new(2, 0.5));
+ queue.insert(Neighbor::new(3, 1.5)); // node id in queue should be [2,1,3]
+ assert!(queue.has_notvisited_node());
+ let nbr = queue.closest_notvisited();
+ assert_eq!(nbr.id, 2);
+ assert_eq!(nbr.distance, 0.5);
+ assert!(nbr.visited);
+ assert!(queue.has_notvisited_node());
+ let nbr = queue.closest_notvisited();
+ assert_eq!(nbr.id, 1);
+ assert_eq!(nbr.distance, 1.0);
+ assert!(nbr.visited);
+ assert!(queue.has_notvisited_node());
+ let nbr = queue.closest_notvisited();
+ assert_eq!(nbr.id, 3);
+ assert_eq!(nbr.distance, 1.5);
+ assert!(nbr.visited);
+ assert!(!queue.has_notvisited_node());
+ }
+
+ #[test]
+ fn test_clear_queue() {
+ let mut queue = NeighborPriorityQueue::with_capacity(3);
+ queue.insert(Neighbor::new(1, 1.0));
+ queue.insert(Neighbor::new(2, 0.5));
+ assert_eq!(queue.size(), 2);
+ assert!(queue.has_notvisited_node());
+ queue.clear();
+ assert_eq!(queue.size(), 0);
+ assert!(!queue.has_notvisited_node());
+ }
+
+ #[test]
+ fn test_reserve() {
+ let mut queue = NeighborPriorityQueue::new();
+ queue.reserve(10);
+ assert_eq!(queue.data.len(), 11);
+ assert_eq!(queue.capacity, 10);
+ }
+
+ #[test]
+ fn test_set_capacity() {
+ let mut queue = NeighborPriorityQueue::with_capacity(10);
+ queue.set_capacity(5);
+ assert_eq!(queue.capacity, 5);
+ assert_eq!(queue.data.len(), 11);
+
+ queue.set_capacity(11);
+ assert_eq!(queue.capacity, 5);
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/sorted_neighbor_vector.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/sorted_neighbor_vector.rs
new file mode 100644
index 0000000..4c3eff0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/neighbor/sorted_neighbor_vector.rs
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Sorted Neighbor Vector
+
+use std::ops::{Deref, DerefMut};
+
+use super::Neighbor;
+
+/// A newtype on top of vector of neighbors, is sorted by distance
+#[derive(Debug)]
+pub struct SortedNeighborVector<'a>(&'a mut Vec<Neighbor>);
+
+impl<'a> SortedNeighborVector<'a> {
+ /// Create a new SortedNeighborVector
+ pub fn new(vec: &'a mut Vec<Neighbor>) -> Self {
+ vec.sort_unstable();
+ Self(vec)
+ }
+}
+
+impl<'a> Deref for SortedNeighborVector<'a> {
+ type Target = Vec<Neighbor>;
+
+ fn deref(&self) -> &Self::Target {
+ self.0
+ }
+}
+
+impl<'a> DerefMut for SortedNeighborVector<'a> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.0
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/fixed_chunk_pq_table.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/fixed_chunk_pq_table.rs
new file mode 100644
index 0000000..bfedcae
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/fixed_chunk_pq_table.rs
@@ -0,0 +1,483 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations)]
+
+use hashbrown::HashMap;
+use rayon::prelude::{
+ IndexedParallelIterator, IntoParallelRefMutIterator, ParallelIterator, ParallelSliceMut,
+};
+use std::arch::x86_64::{_mm_prefetch, _MM_HINT_T0};
+
+use crate::{
+ common::{ANNError, ANNResult},
+ model::NUM_PQ_CENTROIDS,
+};
+
+/// PQ Pivot table loading and calculate distance
+#[derive(Debug)]
+pub struct FixedChunkPQTable {
+ /// pq_tables = float array of size [256 * ndims]
+ pq_table: Vec<f32>,
+
+ /// ndims = true dimension of vectors
+ dim: usize,
+
+ /// num_pq_chunks = the pq chunk number
+ num_pq_chunks: usize,
+
+ /// chunk_offsets = the offset of each chunk, start from 0
+ chunk_offsets: Vec<usize>,
+
+ /// centroid of each dimension
+ centroids: Vec<f32>,
+
+ /// Becasue we're using L2 distance, this is no needed now.
+ /// Transport of pq_table. transport_pq_table = float array of size [ndims * 256].
+ /// e.g. if pa_table is 2 centroids * 3 dims
+ /// [ 1, 2, 3,
+ /// 4, 5, 6]
+ /// then transport_pq_table would be 3 dims * 2 centroids
+ /// [ 1, 4,
+ /// 2, 5,
+ /// 3, 6]
+ /// transport_pq_table: Vec<f32>,
+
+ /// Map dim offset to chunk index e.g., 8 dims in to 2 chunks
+ /// then would be [(0,0), (1,0), (2,0), (3,0), (4,1), (5,1), (6,1), (7,1)]
+ dimoffset_chunk_mapping: HashMap<usize, usize>,
+}
+
+impl FixedChunkPQTable {
+ /// Create the FixedChunkPQTable with dim and chunk numbers and pivot file data (pivot table + cenroids + chunk offsets)
+ pub fn new(
+ dim: usize,
+ num_pq_chunks: usize,
+ pq_table: Vec<f32>,
+ centroids: Vec<f32>,
+ chunk_offsets: Vec<usize>,
+ ) -> Self {
+ let mut dimoffset_chunk_mapping = HashMap::new();
+ for chunk_index in 0..num_pq_chunks {
+ for dim_offset in chunk_offsets[chunk_index]..chunk_offsets[chunk_index + 1] {
+ dimoffset_chunk_mapping.insert(dim_offset, chunk_index);
+ }
+ }
+
+ Self {
+ pq_table,
+ dim,
+ num_pq_chunks,
+ chunk_offsets,
+ centroids,
+ dimoffset_chunk_mapping,
+ }
+ }
+
+ /// Get chunk number
+ pub fn get_num_chunks(&self) -> usize {
+ self.num_pq_chunks
+ }
+
+ /// Shifting the query according to mean or the whole corpus
+ pub fn preprocess_query(&self, query_vec: &mut [f32]) {
+ for (query, &centroid) in query_vec.iter_mut().zip(self.centroids.iter()) {
+ *query -= centroid;
+ }
+ }
+
+ /// Pre-calculated the distance between query and each centroid by l2 distance
+ /// * `query_vec` - query vector: 1 * dim
+ /// * `dist_vec` - pre-calculated the distance between query and each centroid: chunk_size * num_centroids
+ #[allow(clippy::needless_range_loop)]
+ pub fn populate_chunk_distances(&self, query_vec: &[f32]) -> Vec<f32> {
+ let mut dist_vec = vec![0.0; self.num_pq_chunks * NUM_PQ_CENTROIDS];
+ for centroid_index in 0..NUM_PQ_CENTROIDS {
+ for chunk_index in 0..self.num_pq_chunks {
+ for dim_offset in
+ self.chunk_offsets[chunk_index]..self.chunk_offsets[chunk_index + 1]
+ {
+ let diff: f32 = self.pq_table[self.dim * centroid_index + dim_offset]
+ - query_vec[dim_offset];
+ dist_vec[chunk_index * NUM_PQ_CENTROIDS + centroid_index] += diff * diff;
+ }
+ }
+ }
+ dist_vec
+ }
+
+ /// Pre-calculated the distance between query and each centroid by inner product
+ /// * `query_vec` - query vector: 1 * dim
+ /// * `dist_vec` - pre-calculated the distance between query and each centroid: chunk_size * num_centroids
+ ///
+ /// Reason to allow clippy::needless_range_loop:
+ /// The inner loop is operating over a range that is different for each iteration of the outer loop.
+ /// This isn't a scenario where using iter().enumerate() would be easily applicable,
+ /// because the inner loop isn't iterating directly over the contents of a slice or array.
+ /// Thus, using indexing might be the most straightforward way to express this logic.
+ #[allow(clippy::needless_range_loop)]
+ pub fn populate_chunk_inner_products(&self, query_vec: &[f32]) -> Vec<f32> {
+ let mut dist_vec = vec![0.0; self.num_pq_chunks * NUM_PQ_CENTROIDS];
+ for centroid_index in 0..NUM_PQ_CENTROIDS {
+ for chunk_index in 0..self.num_pq_chunks {
+ for dim_offset in
+ self.chunk_offsets[chunk_index]..self.chunk_offsets[chunk_index + 1]
+ {
+ // assumes that we are not shifting the vectors to mean zero, i.e., centroid
+ // array should be all zeros returning negative to keep the search code
+ // clean (max inner product vs min distance)
+ let diff: f32 = self.pq_table[self.dim * centroid_index + dim_offset]
+ * query_vec[dim_offset];
+ dist_vec[chunk_index * NUM_PQ_CENTROIDS + centroid_index] -= diff;
+ }
+ }
+ }
+ dist_vec
+ }
+
+ /// Calculate the distance between query and given centroid by l2 distance
+ /// * `query_vec` - query vector: 1 * dim
+ /// * `base_vec` - given centroid array: 1 * num_pq_chunks
+ #[allow(clippy::needless_range_loop)]
+ pub fn l2_distance(&self, query_vec: &[f32], base_vec: &[u8]) -> f32 {
+ let mut res_vec: Vec<f32> = vec![0.0; self.num_pq_chunks];
+ res_vec
+ .par_iter_mut()
+ .enumerate()
+ .for_each(|(chunk_index, chunk_diff)| {
+ for dim_offset in
+ self.chunk_offsets[chunk_index]..self.chunk_offsets[chunk_index + 1]
+ {
+ let diff = self.pq_table
+ [self.dim * base_vec[chunk_index] as usize + dim_offset]
+ - query_vec[dim_offset];
+ *chunk_diff += diff * diff;
+ }
+ });
+
+ let res: f32 = res_vec.iter().sum::<f32>();
+
+ res
+ }
+
+ /// Calculate the distance between query and given centroid by inner product
+ /// * `query_vec` - query vector: 1 * dim
+ /// * `base_vec` - given centroid array: 1 * num_pq_chunks
+ #[allow(clippy::needless_range_loop)]
+ pub fn inner_product(&self, query_vec: &[f32], base_vec: &[u8]) -> f32 {
+ let mut res_vec: Vec<f32> = vec![0.0; self.num_pq_chunks];
+ res_vec
+ .par_iter_mut()
+ .enumerate()
+ .for_each(|(chunk_index, chunk_diff)| {
+ for dim_offset in
+ self.chunk_offsets[chunk_index]..self.chunk_offsets[chunk_index + 1]
+ {
+ *chunk_diff += self.pq_table
+ [self.dim * base_vec[chunk_index] as usize + dim_offset]
+ * query_vec[dim_offset];
+ }
+ });
+
+ let res: f32 = res_vec.iter().sum::<f32>();
+
+ // returns negative value to simulate distances (max -> min conversion)
+ -res
+ }
+
+ /// Revert vector by adding centroid
+ /// * `base_vec` - given centroid array: 1 * num_pq_chunks
+ /// * `out_vec` - reverted vector
+ pub fn inflate_vector(&self, base_vec: &[u8]) -> ANNResult<Vec<f32>> {
+ let mut out_vec: Vec<f32> = vec![0.0; self.dim];
+ for (dim_offset, value) in out_vec.iter_mut().enumerate() {
+ let chunk_index =
+ self.dimoffset_chunk_mapping
+ .get(&dim_offset)
+ .ok_or(ANNError::log_pq_error(
+ "ERROR: dim_offset not found in dimoffset_chunk_mapping".to_string(),
+ ))?;
+ *value = self.pq_table[self.dim * base_vec[*chunk_index] as usize + dim_offset]
+ + self.centroids[dim_offset];
+ }
+
+ Ok(out_vec)
+ }
+}
+
+/// Given a batch input nodes, return a batch of PQ distance
+/// * `pq_ids` - batch nodes: n_pts * pq_nchunks
+/// * `n_pts` - batch number
+/// * `pq_nchunks` - pq chunk number number
+/// * `pq_dists` - pre-calculated the distance between query and each centroid: chunk_size * num_centroids
+/// * `dists_out` - n_pts * 1
+pub fn pq_dist_lookup(
+ pq_ids: &[u8],
+ n_pts: usize,
+ pq_nchunks: usize,
+ pq_dists: &[f32],
+) -> Vec<f32> {
+ let mut dists_out: Vec<f32> = vec![0.0; n_pts];
+ unsafe {
+ _mm_prefetch(dists_out.as_ptr() as *const i8, _MM_HINT_T0);
+ _mm_prefetch(pq_ids.as_ptr() as *const i8, _MM_HINT_T0);
+ _mm_prefetch(pq_ids.as_ptr().add(64) as *const i8, _MM_HINT_T0);
+ _mm_prefetch(pq_ids.as_ptr().add(128) as *const i8, _MM_HINT_T0);
+ }
+ for chunk in 0..pq_nchunks {
+ let chunk_dists = &pq_dists[256 * chunk..];
+ if chunk < pq_nchunks - 1 {
+ unsafe {
+ _mm_prefetch(
+ chunk_dists.as_ptr().offset(256 * chunk as isize).add(256) as *const i8,
+ _MM_HINT_T0,
+ );
+ }
+ }
+ dists_out
+ .par_iter_mut()
+ .enumerate()
+ .for_each(|(n_iter, dist)| {
+ let pq_centerid = pq_ids[pq_nchunks * n_iter + chunk];
+ *dist += chunk_dists[pq_centerid as usize];
+ });
+ }
+ dists_out
+}
+
+pub fn aggregate_coords(ids: &[u32], all_coords: &[u8], ndims: usize) -> Vec<u8> {
+ let mut out: Vec<u8> = vec![0u8; ids.len() * ndims];
+ let ndim_u32 = ndims as u32;
+ out.par_chunks_mut(ndims)
+ .enumerate()
+ .for_each(|(index, chunk)| {
+ let id_compressed_pivot = &all_coords
+ [(ids[index] * ndim_u32) as usize..(ids[index] * ndim_u32 + ndim_u32) as usize];
+ let temp_slice =
+ unsafe { std::slice::from_raw_parts(id_compressed_pivot.as_ptr(), ndims) };
+ chunk.copy_from_slice(temp_slice);
+ });
+
+ out
+}
+
+#[cfg(test)]
+mod fixed_chunk_pq_table_test {
+
+ use super::*;
+ use crate::common::{ANNError, ANNResult};
+ use crate::utils::{convert_types_u32_usize, convert_types_u64_usize, file_exists, load_bin};
+
+ const DIM: usize = 128;
+
+ #[test]
+ fn load_pivot_test() {
+ let pq_pivots_path: &str = "tests/data/siftsmall_learn.bin_pq_pivots.bin";
+ let (dim, pq_table, centroids, chunk_offsets) =
+ load_pq_pivots_bin(pq_pivots_path, &1).unwrap();
+ let fixed_chunk_pq_table =
+ FixedChunkPQTable::new(dim, 1, pq_table, centroids, chunk_offsets);
+
+ assert_eq!(dim, DIM);
+ assert_eq!(fixed_chunk_pq_table.pq_table.len(), DIM * NUM_PQ_CENTROIDS);
+ assert_eq!(fixed_chunk_pq_table.centroids.len(), DIM);
+
+ assert_eq!(fixed_chunk_pq_table.chunk_offsets[0], 0);
+ assert_eq!(fixed_chunk_pq_table.chunk_offsets[1], DIM);
+ assert_eq!(fixed_chunk_pq_table.chunk_offsets.len(), 2);
+ }
+
+ #[test]
+ fn get_num_chunks_test() {
+ let num_chunks = 7;
+ let pa_table = vec![0.0; DIM * NUM_PQ_CENTROIDS];
+ let centroids = vec![0.0; DIM];
+ let chunk_offsets = vec![0, 7, 9, 11, 22, 34, 78, 127];
+ let fixed_chunk_pq_table =
+ FixedChunkPQTable::new(DIM, num_chunks, pa_table, centroids, chunk_offsets);
+ let chunk: usize = fixed_chunk_pq_table.get_num_chunks();
+ assert_eq!(chunk, num_chunks);
+ }
+
+ #[test]
+ fn preprocess_query_test() {
+ let pq_pivots_path: &str = "tests/data/siftsmall_learn.bin_pq_pivots.bin";
+ let (dim, pq_table, centroids, chunk_offsets) =
+ load_pq_pivots_bin(pq_pivots_path, &1).unwrap();
+ let fixed_chunk_pq_table =
+ FixedChunkPQTable::new(dim, 1, pq_table, centroids, chunk_offsets);
+
+ let mut query_vec: Vec<f32> = vec![
+ 32.39f32, 78.57f32, 50.32f32, 80.46f32, 6.47f32, 69.76f32, 94.2f32, 83.36f32, 5.8f32,
+ 68.78f32, 42.32f32, 61.77f32, 90.26f32, 60.41f32, 3.86f32, 61.21f32, 16.6f32, 54.46f32,
+ 7.29f32, 54.24f32, 92.49f32, 30.18f32, 65.36f32, 99.09f32, 3.8f32, 36.4f32, 86.72f32,
+ 65.18f32, 29.87f32, 62.21f32, 58.32f32, 43.23f32, 94.3f32, 79.61f32, 39.67f32,
+ 11.18f32, 48.88f32, 38.19f32, 93.95f32, 10.46f32, 36.7f32, 14.75f32, 81.64f32,
+ 59.18f32, 99.03f32, 74.23f32, 1.26f32, 82.69f32, 35.7f32, 38.39f32, 46.17f32, 64.75f32,
+ 7.15f32, 36.55f32, 77.32f32, 18.65f32, 32.8f32, 74.84f32, 18.12f32, 20.19f32, 70.06f32,
+ 48.37f32, 40.18f32, 45.69f32, 88.3f32, 39.15f32, 60.97f32, 71.29f32, 61.79f32,
+ 47.23f32, 94.71f32, 58.04f32, 52.4f32, 34.66f32, 59.1f32, 47.11f32, 30.2f32, 58.72f32,
+ 74.35f32, 83.68f32, 66.8f32, 28.57f32, 29.45f32, 52.02f32, 91.95f32, 92.44f32,
+ 65.25f32, 38.3f32, 35.6f32, 41.67f32, 91.33f32, 76.81f32, 74.88f32, 33.17f32, 48.36f32,
+ 41.42f32, 23f32, 8.31f32, 81.69f32, 80.08f32, 50.55f32, 54.46f32, 23.79f32, 43.46f32,
+ 84.5f32, 10.42f32, 29.51f32, 19.73f32, 46.48f32, 35.01f32, 52.3f32, 66.97f32, 4.8f32,
+ 74.81f32, 2.82f32, 61.82f32, 25.06f32, 17.3f32, 17.29f32, 63.2f32, 64.1f32, 61.68f32,
+ 37.42f32, 3.39f32, 97.45f32, 5.32f32, 59.02f32, 35.6f32,
+ ];
+ fixed_chunk_pq_table.preprocess_query(&mut query_vec);
+ assert_eq!(query_vec[0], 32.39f32 - fixed_chunk_pq_table.centroids[0]);
+ assert_eq!(
+ query_vec[127],
+ 35.6f32 - fixed_chunk_pq_table.centroids[127]
+ );
+ }
+
+ #[test]
+ fn calculate_distances_tests() {
+ let pq_pivots_path: &str = "tests/data/siftsmall_learn.bin_pq_pivots.bin";
+
+ let (dim, pq_table, centroids, chunk_offsets) =
+ load_pq_pivots_bin(pq_pivots_path, &1).unwrap();
+ let fixed_chunk_pq_table =
+ FixedChunkPQTable::new(dim, 1, pq_table, centroids, chunk_offsets);
+
+ let query_vec: Vec<f32> = vec![
+ 32.39f32, 78.57f32, 50.32f32, 80.46f32, 6.47f32, 69.76f32, 94.2f32, 83.36f32, 5.8f32,
+ 68.78f32, 42.32f32, 61.77f32, 90.26f32, 60.41f32, 3.86f32, 61.21f32, 16.6f32, 54.46f32,
+ 7.29f32, 54.24f32, 92.49f32, 30.18f32, 65.36f32, 99.09f32, 3.8f32, 36.4f32, 86.72f32,
+ 65.18f32, 29.87f32, 62.21f32, 58.32f32, 43.23f32, 94.3f32, 79.61f32, 39.67f32,
+ 11.18f32, 48.88f32, 38.19f32, 93.95f32, 10.46f32, 36.7f32, 14.75f32, 81.64f32,
+ 59.18f32, 99.03f32, 74.23f32, 1.26f32, 82.69f32, 35.7f32, 38.39f32, 46.17f32, 64.75f32,
+ 7.15f32, 36.55f32, 77.32f32, 18.65f32, 32.8f32, 74.84f32, 18.12f32, 20.19f32, 70.06f32,
+ 48.37f32, 40.18f32, 45.69f32, 88.3f32, 39.15f32, 60.97f32, 71.29f32, 61.79f32,
+ 47.23f32, 94.71f32, 58.04f32, 52.4f32, 34.66f32, 59.1f32, 47.11f32, 30.2f32, 58.72f32,
+ 74.35f32, 83.68f32, 66.8f32, 28.57f32, 29.45f32, 52.02f32, 91.95f32, 92.44f32,
+ 65.25f32, 38.3f32, 35.6f32, 41.67f32, 91.33f32, 76.81f32, 74.88f32, 33.17f32, 48.36f32,
+ 41.42f32, 23f32, 8.31f32, 81.69f32, 80.08f32, 50.55f32, 54.46f32, 23.79f32, 43.46f32,
+ 84.5f32, 10.42f32, 29.51f32, 19.73f32, 46.48f32, 35.01f32, 52.3f32, 66.97f32, 4.8f32,
+ 74.81f32, 2.82f32, 61.82f32, 25.06f32, 17.3f32, 17.29f32, 63.2f32, 64.1f32, 61.68f32,
+ 37.42f32, 3.39f32, 97.45f32, 5.32f32, 59.02f32, 35.6f32,
+ ];
+
+ let dist_vec = fixed_chunk_pq_table.populate_chunk_distances(&query_vec);
+ assert_eq!(dist_vec.len(), 256);
+
+ // populate_chunk_distances_test
+ let mut sampled_output = 0.0;
+ (0..DIM).for_each(|dim_offset| {
+ let diff = fixed_chunk_pq_table.pq_table[dim_offset] - query_vec[dim_offset];
+ sampled_output += diff * diff;
+ });
+ assert_eq!(sampled_output, dist_vec[0]);
+
+ // populate_chunk_inner_products_test
+ let dist_vec = fixed_chunk_pq_table.populate_chunk_inner_products(&query_vec);
+ assert_eq!(dist_vec.len(), 256);
+
+ let mut sampled_output = 0.0;
+ (0..DIM).for_each(|dim_offset| {
+ sampled_output -= fixed_chunk_pq_table.pq_table[dim_offset] * query_vec[dim_offset];
+ });
+ assert_eq!(sampled_output, dist_vec[0]);
+
+ // l2_distance_test
+ let base_vec: Vec<u8> = vec![3u8];
+ let dist = fixed_chunk_pq_table.l2_distance(&query_vec, &base_vec);
+ let mut l2_output = 0.0;
+ (0..DIM).for_each(|dim_offset| {
+ let diff = fixed_chunk_pq_table.pq_table[3 * DIM + dim_offset] - query_vec[dim_offset];
+ l2_output += diff * diff;
+ });
+ assert_eq!(l2_output, dist);
+
+ // inner_product_test
+ let dist = fixed_chunk_pq_table.inner_product(&query_vec, &base_vec);
+ let mut l2_output = 0.0;
+ (0..DIM).for_each(|dim_offset| {
+ l2_output -=
+ fixed_chunk_pq_table.pq_table[3 * DIM + dim_offset] * query_vec[dim_offset];
+ });
+ assert_eq!(l2_output, dist);
+
+ // inflate_vector_test
+ let inflate_vector = fixed_chunk_pq_table.inflate_vector(&base_vec).unwrap();
+ assert_eq!(inflate_vector.len(), DIM);
+ assert_eq!(
+ inflate_vector[0],
+ fixed_chunk_pq_table.pq_table[3 * DIM] + fixed_chunk_pq_table.centroids[0]
+ );
+ assert_eq!(
+ inflate_vector[1],
+ fixed_chunk_pq_table.pq_table[3 * DIM + 1] + fixed_chunk_pq_table.centroids[1]
+ );
+ assert_eq!(
+ inflate_vector[127],
+ fixed_chunk_pq_table.pq_table[3 * DIM + 127] + fixed_chunk_pq_table.centroids[127]
+ );
+ }
+
+ fn load_pq_pivots_bin(
+ pq_pivots_path: &str,
+ num_pq_chunks: &usize,
+ ) -> ANNResult<(usize, Vec<f32>, Vec<f32>, Vec<usize>)> {
+ if !file_exists(pq_pivots_path) {
+ return Err(ANNError::log_pq_error(
+ "ERROR: PQ k-means pivot file not found.".to_string(),
+ ));
+ }
+
+ let (data, offset_num, offset_dim) = load_bin::<u64>(pq_pivots_path, 0)?;
+ let file_offset_data = convert_types_u64_usize(&data, offset_num, offset_dim);
+ if offset_num != 4 {
+ let error_message = format!("Error reading pq_pivots file {}. Offsets don't contain correct metadata, # offsets = {}, but expecting 4.", pq_pivots_path, offset_num);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, pq_center_num, dim) = load_bin::<f32>(pq_pivots_path, file_offset_data[0])?;
+ let pq_table = data.to_vec();
+ if pq_center_num != NUM_PQ_CENTROIDS {
+ let error_message = format!(
+ "Error reading pq_pivots file {}. file_num_centers = {}, but expecting {} centers.",
+ pq_pivots_path, pq_center_num, NUM_PQ_CENTROIDS
+ );
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, centroid_dim, nc) = load_bin::<f32>(pq_pivots_path, file_offset_data[1])?;
+ let centroids = data.to_vec();
+ if centroid_dim != dim || nc != 1 {
+ let error_message = format!("Error reading pq_pivots file {}. file_dim = {}, file_cols = {} but expecting {} entries in 1 dimension.", pq_pivots_path, centroid_dim, nc, dim);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, chunk_offset_num, nc) = load_bin::<u32>(pq_pivots_path, file_offset_data[2])?;
+ let chunk_offsets = convert_types_u32_usize(&data, chunk_offset_num, nc);
+ if chunk_offset_num != num_pq_chunks + 1 || nc != 1 {
+ let error_message = format!("Error reading pq_pivots file at chunk offsets; file has nr={}, nc={} but expecting nr={} and nc=1.", chunk_offset_num, nc, num_pq_chunks + 1);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ Ok((dim, pq_table, centroids, chunk_offsets))
+ }
+}
+
+#[cfg(test)]
+mod pq_index_prune_query_test {
+
+ use super::*;
+
+ #[test]
+ fn pq_dist_lookup_test() {
+ let pq_ids: Vec<u8> = vec![1u8, 3u8, 2u8, 2u8];
+ let mut pq_dists: Vec<f32> = Vec::with_capacity(256 * 2);
+ for _ in 0..pq_dists.capacity() {
+ pq_dists.push(rand::random());
+ }
+
+ let dists_out = pq_dist_lookup(&pq_ids, 2, 2, &pq_dists);
+ assert_eq!(dists_out.len(), 2);
+ assert_eq!(dists_out[0], pq_dists[0 + 1] + pq_dists[256 + 3]);
+ assert_eq!(dists_out[1], pq_dists[0 + 2] + pq_dists[256 + 2]);
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/mod.rs
new file mode 100644
index 0000000..85daaa7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/mod.rs
@@ -0,0 +1,9 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+mod fixed_chunk_pq_table;
+pub use fixed_chunk_pq_table::*;
+
+mod pq_construction;
+pub use pq_construction::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/pq_construction.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/pq_construction.rs
new file mode 100644
index 0000000..0a7b078
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/pq/pq_construction.rs
@@ -0,0 +1,398 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations)]
+
+use rayon::prelude::{IndexedParallelIterator, ParallelIterator};
+use rayon::slice::ParallelSliceMut;
+
+use crate::common::{ANNError, ANNResult};
+use crate::storage::PQStorage;
+use crate::utils::{compute_closest_centers, file_exists, k_means_clustering};
+
+/// Max size of PQ training set
+pub const MAX_PQ_TRAINING_SET_SIZE: f64 = 256_000f64;
+
+/// Max number of PQ chunks
+pub const MAX_PQ_CHUNKS: usize = 512;
+
+pub const NUM_PQ_CENTROIDS: usize = 256;
+/// block size for reading/processing large files and matrices in blocks
+const BLOCK_SIZE: usize = 5000000;
+const NUM_KMEANS_REPS_PQ: usize = 12;
+
+/// given training data in train_data of dimensions num_train * dim, generate
+/// PQ pivots using k-means algorithm to partition the co-ordinates into
+/// num_pq_chunks (if it divides dimension, else rounded) chunks, and runs
+/// k-means in each chunk to compute the PQ pivots and stores in bin format in
+/// file pq_pivots_path as a s num_centers*dim floating point binary file
+/// PQ pivot table layout: {pivot offsets data: METADATA_SIZE}{pivot vector:[dim; num_centroid]}{centroid vector:[dim; 1]}{chunk offsets:[chunk_num+1; 1]}
+fn generate_pq_pivots(
+ train_data: &mut [f32],
+ num_train: usize,
+ dim: usize,
+ num_centers: usize,
+ num_pq_chunks: usize,
+ max_k_means_reps: usize,
+ pq_storage: &mut PQStorage,
+) -> ANNResult<()> {
+ if num_pq_chunks > dim {
+ return Err(ANNError::log_pq_error(
+ "Error: number of chunks more than dimension.".to_string(),
+ ));
+ }
+
+ if pq_storage.pivot_data_exist() {
+ let (file_num_centers, file_dim) = pq_storage.read_pivot_metadata()?;
+ if file_dim == dim && file_num_centers == num_centers {
+ // PQ pivot file exists. Not generating again.
+ return Ok(());
+ }
+ }
+
+ // Calculate centroid and center the training data
+ // If we use L2 distance, there is an option to
+ // translate all vectors to make them centered and
+ // then compute PQ. This needs to be set to false
+ // when using PQ for MIPS as such translations dont
+ // preserve inner products.
+ // Now, we're using L2 as default.
+ let mut centroid: Vec<f32> = vec![0.0; dim];
+ for dim_index in 0..dim {
+ for train_data_index in 0..num_train {
+ centroid[dim_index] += train_data[train_data_index * dim + dim_index];
+ }
+ centroid[dim_index] /= num_train as f32;
+ }
+ for dim_index in 0..dim {
+ for train_data_index in 0..num_train {
+ train_data[train_data_index * dim + dim_index] -= centroid[dim_index];
+ }
+ }
+
+ // Calculate each chunk's offset
+ // If we have 8 dimension and 3 chunk then offsets would be [0,3,6,8]
+ let mut chunk_offsets: Vec<usize> = vec![0; num_pq_chunks + 1];
+ let mut chunk_offset: usize = 0;
+ for chunk_index in 0..num_pq_chunks {
+ chunk_offset += dim / num_pq_chunks;
+ if chunk_index < (dim % num_pq_chunks) {
+ chunk_offset += 1;
+ }
+ chunk_offsets[chunk_index + 1] = chunk_offset;
+ }
+
+ let mut full_pivot_data: Vec<f32> = vec![0.0; num_centers * dim];
+ for chunk_index in 0..num_pq_chunks {
+ let chunk_size = chunk_offsets[chunk_index + 1] - chunk_offsets[chunk_index];
+
+ let mut cur_train_data: Vec<f32> = vec![0.0; num_train * chunk_size];
+ let mut cur_pivot_data: Vec<f32> = vec![0.0; num_centers * chunk_size];
+
+ cur_train_data
+ .par_chunks_mut(chunk_size)
+ .enumerate()
+ .for_each(|(train_data_index, chunk)| {
+ for (dim_offset, item) in chunk.iter_mut().enumerate() {
+ *item = train_data
+ [train_data_index * dim + chunk_offsets[chunk_index] + dim_offset];
+ }
+ });
+
+ // Run kmeans to get the centroids of this chunk.
+ let (_closest_docs, _closest_center, _residual) = k_means_clustering(
+ &cur_train_data,
+ num_train,
+ chunk_size,
+ &mut cur_pivot_data,
+ num_centers,
+ max_k_means_reps,
+ )?;
+
+ // Copy centroids from this chunk table to full table
+ for center_index in 0..num_centers {
+ full_pivot_data[center_index * dim + chunk_offsets[chunk_index]
+ ..center_index * dim + chunk_offsets[chunk_index + 1]]
+ .copy_from_slice(
+ &cur_pivot_data[center_index * chunk_size..(center_index + 1) * chunk_size],
+ );
+ }
+ }
+
+ pq_storage.write_pivot_data(
+ &full_pivot_data,
+ &centroid,
+ &chunk_offsets,
+ num_centers,
+ dim,
+ )?;
+
+ Ok(())
+}
+
+/// streams the base file (data_file), and computes the closest centers in each
+/// chunk to generate the compressed data_file and stores it in
+/// pq_compressed_vectors_path.
+/// If the numbber of centers is < 256, it stores as byte vector, else as
+/// 4-byte vector in binary format.
+/// Compressed PQ table layout: {num_points: usize}{num_chunks: usize}{compressed pq table: [num_points; num_chunks]}
+fn generate_pq_data_from_pivots<T: Copy + Into<f32>>(
+ num_centers: usize,
+ num_pq_chunks: usize,
+ pq_storage: &mut PQStorage,
+) -> ANNResult<()> {
+ let (num_points, dim) = pq_storage.read_pq_data_metadata()?;
+
+ let full_pivot_data: Vec<f32>;
+ let centroid: Vec<f32>;
+ let chunk_offsets: Vec<usize>;
+
+ if !pq_storage.pivot_data_exist() {
+ return Err(ANNError::log_pq_error(
+ "ERROR: PQ k-means pivot file not found.".to_string(),
+ ));
+ } else {
+ (full_pivot_data, centroid, chunk_offsets) =
+ pq_storage.load_pivot_data(&num_pq_chunks, &num_centers, &dim)?;
+ }
+
+ pq_storage.write_compressed_pivot_metadata(num_points as i32, num_pq_chunks as i32)?;
+
+ let block_size = if num_points <= BLOCK_SIZE {
+ num_points
+ } else {
+ BLOCK_SIZE
+ };
+ let num_blocks = (num_points / block_size) + (num_points % block_size != 0) as usize;
+
+ for block_index in 0..num_blocks {
+ let start_index: usize = block_index * block_size;
+ let end_index: usize = std::cmp::min((block_index + 1) * block_size, num_points);
+ let cur_block_size: usize = end_index - start_index;
+
+ let mut block_compressed_base: Vec<usize> = vec![0; cur_block_size * num_pq_chunks];
+
+ let block_data: Vec<T> = pq_storage.read_pq_block_data(cur_block_size, dim)?;
+
+ let mut adjusted_block_data: Vec<f32> = vec![0.0; cur_block_size * dim];
+
+ for block_data_index in 0..cur_block_size {
+ for dim_index in 0..dim {
+ adjusted_block_data[block_data_index * dim + dim_index] =
+ block_data[block_data_index * dim + dim_index].into() - centroid[dim_index];
+ }
+ }
+
+ for chunk_index in 0..num_pq_chunks {
+ let cur_chunk_size = chunk_offsets[chunk_index + 1] - chunk_offsets[chunk_index];
+ if cur_chunk_size == 0 {
+ continue;
+ }
+
+ let mut cur_pivot_data: Vec<f32> = vec![0.0; num_centers * cur_chunk_size];
+ let mut cur_data: Vec<f32> = vec![0.0; cur_block_size * cur_chunk_size];
+ let mut closest_center: Vec<u32> = vec![0; cur_block_size];
+
+ // Divide the data into chunks and process each chunk in parallel.
+ cur_data
+ .par_chunks_mut(cur_chunk_size)
+ .enumerate()
+ .for_each(|(block_data_index, chunk)| {
+ for (dim_offset, item) in chunk.iter_mut().enumerate() {
+ *item = adjusted_block_data
+ [block_data_index * dim + chunk_offsets[chunk_index] + dim_offset];
+ }
+ });
+
+ cur_pivot_data
+ .par_chunks_mut(cur_chunk_size)
+ .enumerate()
+ .for_each(|(center_index, chunk)| {
+ for (din_offset, item) in chunk.iter_mut().enumerate() {
+ *item = full_pivot_data
+ [center_index * dim + chunk_offsets[chunk_index] + din_offset];
+ }
+ });
+
+ // Compute the closet centers
+ compute_closest_centers(
+ &cur_data,
+ cur_block_size,
+ cur_chunk_size,
+ &cur_pivot_data,
+ num_centers,
+ 1,
+ &mut closest_center,
+ None,
+ None,
+ )?;
+
+ block_compressed_base
+ .par_chunks_mut(num_pq_chunks)
+ .enumerate()
+ .for_each(|(block_data_index, slice)| {
+ slice[chunk_index] = closest_center[block_data_index] as usize;
+ });
+ }
+
+ _ = pq_storage.write_compressed_pivot_data(
+ &block_compressed_base,
+ num_centers,
+ cur_block_size,
+ num_pq_chunks,
+ );
+ }
+ Ok(())
+}
+
+/// Save the data on a file.
+/// # Arguments
+/// * `p_val` - choose how many ratio sample data as trained data to get pivot
+/// * `num_pq_chunks` - pq chunk number
+/// * `codebook_prefix` - predefined pivots file named
+/// * `pq_storage` - pq file access
+pub fn generate_quantized_data<T: Default + Copy + Into<f32>>(
+ p_val: f64,
+ num_pq_chunks: usize,
+ codebook_prefix: &str,
+ pq_storage: &mut PQStorage,
+) -> ANNResult<()> {
+ // If predefined pivots already exists, skip training.
+ if !file_exists(codebook_prefix) {
+ // Instantiates train data with random sample updates train_data_vector
+ // Training data with train_size samples loaded.
+ // Each sampled file has train_dim.
+ let (mut train_data_vector, train_size, train_dim) =
+ pq_storage.gen_random_slice::<T>(p_val)?;
+
+ generate_pq_pivots(
+ &mut train_data_vector,
+ train_size,
+ train_dim,
+ NUM_PQ_CENTROIDS,
+ num_pq_chunks,
+ NUM_KMEANS_REPS_PQ,
+ pq_storage,
+ )?;
+ }
+ generate_pq_data_from_pivots::<T>(NUM_PQ_CENTROIDS, num_pq_chunks, pq_storage)?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod pq_test {
+
+ use std::fs::File;
+ use std::io::Write;
+
+ use super::*;
+ use crate::utils::{convert_types_u32_usize, convert_types_u64_usize, load_bin, METADATA_SIZE};
+
+ #[test]
+ fn generate_pq_pivots_test() {
+ let pivot_file_name = "generate_pq_pivots_test.bin";
+ let compressed_file_name = "compressed.bin";
+ let pq_training_file_name = "tests/data/siftsmall_learn.bin";
+ let mut pq_storage =
+ PQStorage::new(pivot_file_name, compressed_file_name, pq_training_file_name).unwrap();
+ let mut train_data: Vec<f32> = vec![
+ 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 2.0f32, 2.0f32, 2.0f32,
+ 2.0f32, 2.0f32, 2.0f32, 2.0f32, 2.0f32, 2.1f32, 2.1f32, 2.1f32, 2.1f32, 2.1f32, 2.1f32,
+ 2.1f32, 2.1f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32,
+ 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32,
+ ];
+ generate_pq_pivots(&mut train_data, 5, 8, 2, 2, 5, &mut pq_storage).unwrap();
+
+ let (data, nr, nc) = load_bin::<u64>(pivot_file_name, 0).unwrap();
+ let file_offset_data = convert_types_u64_usize(&data, nr, nc);
+ assert_eq!(file_offset_data[0], METADATA_SIZE);
+ assert_eq!(nr, 4);
+ assert_eq!(nc, 1);
+
+ let (data, nr, nc) = load_bin::<f32>(pivot_file_name, file_offset_data[0]).unwrap();
+ let full_pivot_data = data.to_vec();
+ assert_eq!(full_pivot_data.len(), 16);
+ assert_eq!(nr, 2);
+ assert_eq!(nc, 8);
+
+ let (data, nr, nc) = load_bin::<f32>(pivot_file_name, file_offset_data[1]).unwrap();
+ let centroid = data.to_vec();
+ assert_eq!(
+ centroid[0],
+ (1.0f32 + 2.0f32 + 2.1f32 + 2.2f32 + 100.0f32) / 5.0f32
+ );
+ assert_eq!(nr, 8);
+ assert_eq!(nc, 1);
+
+ let (data, nr, nc) = load_bin::<u32>(pivot_file_name, file_offset_data[2]).unwrap();
+ let chunk_offsets = convert_types_u32_usize(&data, nr, nc);
+ assert_eq!(chunk_offsets[0], 0);
+ assert_eq!(chunk_offsets[1], 4);
+ assert_eq!(chunk_offsets[2], 8);
+ assert_eq!(nr, 3);
+ assert_eq!(nc, 1);
+ std::fs::remove_file(pivot_file_name).unwrap();
+ }
+
+ #[test]
+ fn generate_pq_data_from_pivots_test() {
+ let data_file = "generate_pq_data_from_pivots_test_data.bin";
+ //npoints=5, dim=8, 5 vectors [1.0;8] [2.0;8] [2.1;8] [2.2;8] [100.0;8]
+ let mut train_data: Vec<f32> = vec![
+ 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 1.0f32, 2.0f32, 2.0f32, 2.0f32,
+ 2.0f32, 2.0f32, 2.0f32, 2.0f32, 2.0f32, 2.1f32, 2.1f32, 2.1f32, 2.1f32, 2.1f32, 2.1f32,
+ 2.1f32, 2.1f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32, 2.2f32,
+ 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32, 100.0f32,
+ ];
+ let my_nums_unstructured: &[u8] = unsafe {
+ std::slice::from_raw_parts(train_data.as_ptr() as *const u8, train_data.len() * 4)
+ };
+ let meta: Vec<i32> = vec![5, 8];
+ let meta_unstructured: &[u8] =
+ unsafe { std::slice::from_raw_parts(meta.as_ptr() as *const u8, meta.len() * 4) };
+ let mut data_file_writer = File::create(data_file).unwrap();
+ data_file_writer
+ .write_all(meta_unstructured)
+ .expect("Failed to write sample file");
+ data_file_writer
+ .write_all(my_nums_unstructured)
+ .expect("Failed to write sample file");
+
+ let pq_pivots_path = "generate_pq_data_from_pivots_test_pivot.bin";
+ let pq_compressed_vectors_path = "generate_pq_data_from_pivots_test.bin";
+ let mut pq_storage =
+ PQStorage::new(pq_pivots_path, pq_compressed_vectors_path, data_file).unwrap();
+ generate_pq_pivots(&mut train_data, 5, 8, 2, 2, 5, &mut pq_storage).unwrap();
+ generate_pq_data_from_pivots::<f32>(2, 2, &mut pq_storage).unwrap();
+ let (data, nr, nc) = load_bin::<u8>(pq_compressed_vectors_path, 0).unwrap();
+ assert_eq!(nr, 5);
+ assert_eq!(nc, 2);
+ assert_eq!(data[0], data[2]);
+ assert_ne!(data[0], data[8]);
+
+ std::fs::remove_file(data_file).unwrap();
+ std::fs::remove_file(pq_pivots_path).unwrap();
+ std::fs::remove_file(pq_compressed_vectors_path).unwrap();
+ }
+
+ #[test]
+ fn pq_end_to_end_validation_with_codebook_test() {
+ let data_file = "tests/data/siftsmall_learn.bin";
+ let pq_pivots_path = "tests/data/siftsmall_learn.bin_pq_pivots.bin";
+ let gound_truth_path = "tests/data/siftsmall_learn.bin_pq_compressed.bin";
+ let pq_compressed_vectors_path = "validation.bin";
+ let mut pq_storage =
+ PQStorage::new(pq_pivots_path, pq_compressed_vectors_path, data_file).unwrap();
+ generate_quantized_data::<f32>(0.5, 1, pq_pivots_path, &mut pq_storage).unwrap();
+
+ let (data, nr, nc) = load_bin::<u8>(pq_compressed_vectors_path, 0).unwrap();
+ let (gt_data, gt_nr, gt_nc) = load_bin::<u8>(gound_truth_path, 0).unwrap();
+ assert_eq!(nr, gt_nr);
+ assert_eq!(nc, gt_nc);
+ for i in 0..data.len() {
+ assert_eq!(data[i], gt_data[i]);
+ }
+ std::fs::remove_file(pq_compressed_vectors_path).unwrap();
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/concurrent_queue.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/concurrent_queue.rs
new file mode 100644
index 0000000..8c72bab
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/concurrent_queue.rs
@@ -0,0 +1,312 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Aligned allocator
+
+use std::collections::VecDeque;
+use std::ops::Deref;
+use std::sync::{Arc, Condvar, Mutex, MutexGuard};
+use std::time::Duration;
+
+use crate::common::{ANNError, ANNResult};
+
+#[derive(Debug)]
+/// Query scratch data structures
+pub struct ConcurrentQueue<T> {
+ q: Mutex<VecDeque<T>>,
+ c: Mutex<bool>,
+ push_cv: Condvar,
+}
+
+impl Default for ConcurrentQueue<usize> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<T> ConcurrentQueue<T> {
+ /// Create a concurrent queue
+ pub fn new() -> Self {
+ Self {
+ q: Mutex::new(VecDeque::new()),
+ c: Mutex::new(false),
+ push_cv: Condvar::new(),
+ }
+ }
+
+ /// Block the current thread until it is able to acquire the mutex
+ pub fn reserve(&self, size: usize) -> ANNResult<()> {
+ let mut guard = lock(&self.q)?;
+ guard.reserve(size);
+ Ok(())
+ }
+
+ /// queue stats
+ pub fn size(&self) -> ANNResult<usize> {
+ let guard = lock(&self.q)?;
+
+ Ok(guard.len())
+ }
+
+ /// empty the queue
+ pub fn is_empty(&self) -> ANNResult<bool> {
+ Ok(self.size()? == 0)
+ }
+
+ /// push back
+ pub fn push(&self, new_val: T) -> ANNResult<()> {
+ let mut guard = lock(&self.q)?;
+ self.push_internal(&mut guard, new_val);
+ self.push_cv.notify_all();
+ Ok(())
+ }
+
+ /// push back
+ fn push_internal(&self, guard: &mut MutexGuard<VecDeque<T>>, new_val: T) {
+ guard.push_back(new_val);
+ }
+
+ /// insert into queue
+ pub fn insert<I>(&self, iter: I) -> ANNResult<()>
+ where
+ I: IntoIterator<Item = T>,
+ {
+ let mut guard = lock(&self.q)?;
+ for item in iter {
+ self.push_internal(&mut guard, item);
+ }
+
+ self.push_cv.notify_all();
+ Ok(())
+ }
+
+ /// pop front
+ pub fn pop(&self) -> ANNResult<Option<T>> {
+ let mut guard = lock(&self.q)?;
+ Ok(guard.pop_front())
+ }
+
+ /// Empty - is this necessary?
+ pub fn empty_queue(&self) -> ANNResult<()> {
+ let mut guard = lock(&self.q)?;
+ while !guard.is_empty() {
+ let _ = guard.pop_front();
+ }
+ Ok(())
+ }
+
+ /// register for push notifications
+ pub fn wait_for_push_notify(&self, wait_time: Duration) -> ANNResult<()> {
+ let guard_lock = lock(&self.c)?;
+ let _ = self
+ .push_cv
+ .wait_timeout(guard_lock, wait_time)
+ .map_err(|err| {
+ ANNError::log_lock_poison_error(format!(
+ "ConcurrentQueue Lock is poisoned, err={}",
+ err
+ ))
+ })?;
+ Ok(())
+ }
+}
+
+fn lock<T>(mutex: &Mutex<T>) -> ANNResult<MutexGuard<T>> {
+ let guard = mutex.lock().map_err(|err| {
+ ANNError::log_lock_poison_error(format!("ConcurrentQueue lock is poisoned, err={}", err))
+ })?;
+ Ok(guard)
+}
+
+/// A thread-safe queue that holds instances of `T`.
+/// Each instance is stored in a `Box` to keep the size of the queue node constant.
+#[derive(Debug)]
+pub struct ArcConcurrentBoxedQueue<T> {
+ internal_queue: Arc<ConcurrentQueue<Box<T>>>,
+}
+
+impl<T> ArcConcurrentBoxedQueue<T> {
+ /// Create a new `ArcConcurrentBoxedQueue`.
+ pub fn new() -> Self {
+ Self {
+ internal_queue: Arc::new(ConcurrentQueue::new()),
+ }
+ }
+}
+
+impl<T> Default for ArcConcurrentBoxedQueue<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<T> Clone for ArcConcurrentBoxedQueue<T> {
+ /// Create a new `ArcConcurrentBoxedQueue` that shares the same internal queue
+ /// with the existing one. This allows multiple `ArcConcurrentBoxedQueue` to
+ /// operate on the same underlying queue.
+ fn clone(&self) -> Self {
+ Self {
+ internal_queue: Arc::clone(&self.internal_queue),
+ }
+ }
+}
+
+/// Deref to the ConcurrentQueue.
+impl<T> Deref for ArcConcurrentBoxedQueue<T> {
+ type Target = ConcurrentQueue<Box<T>>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.internal_queue
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::model::ConcurrentQueue;
+ use std::sync::Arc;
+ use std::thread;
+ use std::time::Duration;
+
+ #[test]
+ fn test_push_pop() {
+ let queue = ConcurrentQueue::<i32>::new();
+
+ queue.push(1).unwrap();
+ queue.push(2).unwrap();
+ queue.push(3).unwrap();
+
+ assert_eq!(queue.pop().unwrap(), Some(1));
+ assert_eq!(queue.pop().unwrap(), Some(2));
+ assert_eq!(queue.pop().unwrap(), Some(3));
+ assert_eq!(queue.pop().unwrap(), None);
+ }
+
+ #[test]
+ fn test_size_empty() {
+ let queue = ConcurrentQueue::new();
+
+ assert_eq!(queue.size().unwrap(), 0);
+ assert!(queue.is_empty().unwrap());
+
+ queue.push(1).unwrap();
+ queue.push(2).unwrap();
+
+ assert_eq!(queue.size().unwrap(), 2);
+ assert!(!queue.is_empty().unwrap());
+
+ queue.pop().unwrap();
+ queue.pop().unwrap();
+
+ assert_eq!(queue.size().unwrap(), 0);
+ assert!(queue.is_empty().unwrap());
+ }
+
+ #[test]
+ fn test_insert() {
+ let queue = ConcurrentQueue::new();
+
+ let data = vec![1, 2, 3];
+ queue.insert(data.into_iter()).unwrap();
+
+ assert_eq!(queue.pop().unwrap(), Some(1));
+ assert_eq!(queue.pop().unwrap(), Some(2));
+ assert_eq!(queue.pop().unwrap(), Some(3));
+ assert_eq!(queue.pop().unwrap(), None);
+ }
+
+ #[test]
+ fn test_notifications() {
+ let queue = Arc::new(ConcurrentQueue::new());
+ let queue_clone = Arc::clone(&queue);
+
+ let producer = thread::spawn(move || {
+ for i in 0..3 {
+ thread::sleep(Duration::from_millis(50));
+ queue_clone.push(i).unwrap();
+ }
+ });
+
+ let consumer = thread::spawn(move || {
+ let mut values = vec![];
+
+ for _ in 0..3 {
+ let mut val = -1;
+ while val == -1 {
+ queue
+ .wait_for_push_notify(Duration::from_millis(10))
+ .unwrap();
+ val = queue.pop().unwrap().unwrap_or(-1);
+ }
+
+ values.push(val);
+ }
+
+ values
+ });
+
+ producer.join().unwrap();
+ let consumer_results = consumer.join().unwrap();
+
+ assert_eq!(consumer_results, vec![0, 1, 2]);
+ }
+
+ #[test]
+ fn test_multithreaded_push_pop() {
+ let queue = Arc::new(ConcurrentQueue::new());
+ let queue_clone = Arc::clone(&queue);
+
+ let producer = thread::spawn(move || {
+ for i in 0..10 {
+ queue_clone.push(i).unwrap();
+ thread::sleep(Duration::from_millis(50));
+ }
+ });
+
+ let consumer = thread::spawn(move || {
+ let mut values = vec![];
+
+ for _ in 0..10 {
+ let mut val = -1;
+ while val == -1 {
+ val = queue.pop().unwrap().unwrap_or(-1);
+ thread::sleep(Duration::from_millis(10));
+ }
+
+ values.push(val);
+ }
+
+ values
+ });
+
+ producer.join().unwrap();
+ let consumer_results = consumer.join().unwrap();
+
+ assert_eq!(consumer_results, (0..10).collect::<Vec<_>>());
+ }
+
+ /// This is a single value test. It avoids the unlimited wait until the collectin got empty on the previous test.
+ /// It will make sure the signal mutex is matching the waiting mutex.
+ #[test]
+ fn test_wait_for_push_notify() {
+ let queue = Arc::new(ConcurrentQueue::<usize>::new());
+ let queue_clone = Arc::clone(&queue);
+
+ let producer = thread::spawn(move || {
+ thread::sleep(Duration::from_millis(100));
+ queue_clone.push(1).unwrap();
+ });
+
+ let consumer = thread::spawn(move || {
+ queue
+ .wait_for_push_notify(Duration::from_millis(200))
+ .unwrap();
+ assert_eq!(queue.pop().unwrap(), Some(1));
+ });
+
+ producer.join().unwrap();
+ consumer.join().unwrap();
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/inmem_query_scratch.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/inmem_query_scratch.rs
new file mode 100644
index 0000000..f0fa432
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/inmem_query_scratch.rs
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Scratch space for in-memory index based search
+
+use std::cmp::max;
+use std::mem;
+
+use hashbrown::HashSet;
+
+use crate::common::{ANNError, ANNResult, AlignedBoxWithSlice};
+use crate::model::configuration::index_write_parameters::IndexWriteParameters;
+use crate::model::{Neighbor, NeighborPriorityQueue, PQScratch};
+
+use super::Scratch;
+
+/// In-mem index related limits
+pub const GRAPH_SLACK_FACTOR: f64 = 1.3_f64;
+
+/// Max number of points for using bitset
+pub const MAX_POINTS_FOR_USING_BITSET: usize = 100000;
+
+/// TODO: SSD Index related limits
+pub const MAX_GRAPH_DEGREE: usize = 512;
+
+/// TODO: SSD Index related limits
+pub const MAX_N_CMPS: usize = 16384;
+
+/// TODO: SSD Index related limits
+pub const SECTOR_LEN: usize = 4096;
+
+/// TODO: SSD Index related limits
+pub const MAX_N_SECTOR_READS: usize = 128;
+
+/// The alignment required for memory access. This will be multiplied with size of T to get the actual alignment
+pub const QUERY_ALIGNMENT_OF_T_SIZE: usize = 16;
+
+/// Scratch space for in-memory index based search
+#[derive(Debug)]
+pub struct InMemQueryScratch<T, const N: usize> {
+ /// Size of the candidate queue
+ pub candidate_size: u32,
+
+ /// Max degree for each vertex
+ pub max_degree: u32,
+
+ /// Max occlusion size
+ pub max_occlusion_size: u32,
+
+ /// Query node
+ pub query: AlignedBoxWithSlice<T>,
+
+ /// Best candidates, whose size is candidate_queue_size
+ pub best_candidates: NeighborPriorityQueue,
+
+ /// Occlude factor
+ pub occlude_factor: Vec<f32>,
+
+ /// Visited neighbor id
+ pub id_scratch: Vec<u32>,
+
+ /// The distance between visited neighbor and query node
+ pub dist_scratch: Vec<f32>,
+
+ /// The PQ Scratch, keey it private since this class use the Box to own the memory. Use the function pq_scratch to get its reference
+ pub pq_scratch: Option<Box<PQScratch>>,
+
+ /// Buffers used in process delete, capacity increases as needed
+ pub expanded_nodes_set: HashSet<u32>,
+
+ /// Expanded neighbors
+ pub expanded_neighbors_vector: Vec<Neighbor>,
+
+ /// Occlude list
+ pub occlude_list_output: Vec<u32>,
+
+ /// RobinSet for larger dataset
+ pub node_visited_robinset: HashSet<u32>,
+}
+
+impl<T: Default + Copy, const N: usize> InMemQueryScratch<T, N> {
+ /// Create InMemQueryScratch instance
+ pub fn new(
+ search_candidate_size: u32,
+ index_write_parameter: &IndexWriteParameters,
+ init_pq_scratch: bool,
+ ) -> ANNResult<Self> {
+ let indexing_candidate_size = index_write_parameter.search_list_size;
+ let max_degree = index_write_parameter.max_degree;
+ let max_occlusion_size = index_write_parameter.max_occlusion_size;
+
+ if search_candidate_size == 0 || indexing_candidate_size == 0 || max_degree == 0 || N == 0 {
+ return Err(ANNError::log_index_error(format!(
+ "In InMemQueryScratch, one of search_candidate_size = {}, indexing_candidate_size = {}, dim = {} or max_degree = {} is zero.",
+ search_candidate_size, indexing_candidate_size, N, max_degree)));
+ }
+
+ let query = AlignedBoxWithSlice::new(N, mem::size_of::<T>() * QUERY_ALIGNMENT_OF_T_SIZE)?;
+ let pq_scratch = if init_pq_scratch {
+ Some(Box::new(PQScratch::new(MAX_GRAPH_DEGREE, N)?))
+ } else {
+ None
+ };
+
+ let occlude_factor = Vec::with_capacity(max_occlusion_size as usize);
+
+ let capacity = (1.5 * GRAPH_SLACK_FACTOR * (max_degree as f64)).ceil() as usize;
+ let id_scratch = Vec::with_capacity(capacity);
+ let dist_scratch = Vec::with_capacity(capacity);
+
+ let expanded_nodes_set = HashSet::<u32>::new();
+ let expanded_neighbors_vector = Vec::<Neighbor>::new();
+ let occlude_list_output = Vec::<u32>::new();
+
+ let candidate_size = max(search_candidate_size, indexing_candidate_size);
+ let node_visited_robinset = HashSet::<u32>::with_capacity(20 * candidate_size as usize);
+ let scratch = Self {
+ candidate_size,
+ max_degree,
+ max_occlusion_size,
+ query,
+ best_candidates: NeighborPriorityQueue::with_capacity(candidate_size as usize),
+ occlude_factor,
+ id_scratch,
+ dist_scratch,
+ pq_scratch,
+ expanded_nodes_set,
+ expanded_neighbors_vector,
+ occlude_list_output,
+ node_visited_robinset,
+ };
+
+ Ok(scratch)
+ }
+
+ /// Resize the scratch with new candidate size
+ pub fn resize_for_new_candidate_size(&mut self, new_candidate_size: u32) {
+ if new_candidate_size > self.candidate_size {
+ let delta = new_candidate_size - self.candidate_size;
+ self.candidate_size = new_candidate_size;
+ self.best_candidates.reserve(delta as usize);
+ self.node_visited_robinset.reserve((20 * delta) as usize);
+ }
+ }
+}
+
+impl<T: Default + Copy, const N: usize> Scratch for InMemQueryScratch<T, N> {
+ fn clear(&mut self) {
+ self.best_candidates.clear();
+ self.occlude_factor.clear();
+
+ self.node_visited_robinset.clear();
+
+ self.id_scratch.clear();
+ self.dist_scratch.clear();
+
+ self.expanded_nodes_set.clear();
+ self.expanded_neighbors_vector.clear();
+ self.occlude_list_output.clear();
+ }
+}
+
+#[cfg(test)]
+mod inmemory_query_scratch_test {
+ use crate::model::configuration::index_write_parameters::IndexWriteParametersBuilder;
+
+ use super::*;
+
+ #[test]
+ fn node_visited_robinset_test() {
+ let index_write_parameter = IndexWriteParametersBuilder::new(10, 10)
+ .with_max_occlusion_size(5)
+ .build();
+
+ let mut scratch =
+ InMemQueryScratch::<f32, 32>::new(100, &index_write_parameter, false).unwrap();
+
+ assert_eq!(scratch.node_visited_robinset.len(), 0);
+
+ scratch.clear();
+ assert_eq!(scratch.node_visited_robinset.len(), 0);
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/mod.rs
new file mode 100644
index 0000000..cf9ee29
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/mod.rs
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub mod scratch_traits;
+pub use scratch_traits::*;
+
+pub mod concurrent_queue;
+pub use concurrent_queue::*;
+
+pub mod pq_scratch;
+pub use pq_scratch::*;
+
+
+pub mod inmem_query_scratch;
+pub use inmem_query_scratch::*;
+
+pub mod scratch_store_manager;
+pub use scratch_store_manager::*;
+
+pub mod ssd_query_scratch;
+pub use ssd_query_scratch::*;
+
+pub mod ssd_thread_data;
+pub use ssd_thread_data::*;
+
+pub mod ssd_io_context;
+pub use ssd_io_context::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/pq_scratch.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/pq_scratch.rs
new file mode 100644
index 0000000..bf9d6c5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/pq_scratch.rs
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Aligned allocator
+
+use std::mem::size_of;
+
+use crate::common::{ANNResult, AlignedBoxWithSlice};
+
+const MAX_PQ_CHUNKS: usize = 512;
+
+#[derive(Debug)]
+/// PQ scratch
+pub struct PQScratch {
+ /// Aligned pq table dist scratch, must be at least [256 * NCHUNKS]
+ pub aligned_pqtable_dist_scratch: AlignedBoxWithSlice<f32>,
+ /// Aligned dist scratch, must be at least diskann MAX_DEGREE
+ pub aligned_dist_scratch: AlignedBoxWithSlice<f32>,
+ /// Aligned pq coord scratch, must be at least [N_CHUNKS * MAX_DEGREE]
+ pub aligned_pq_coord_scratch: AlignedBoxWithSlice<u8>,
+ /// Rotated query
+ pub rotated_query: AlignedBoxWithSlice<f32>,
+ /// Aligned query float
+ pub aligned_query_float: AlignedBoxWithSlice<f32>,
+}
+
+impl PQScratch {
+ const ALIGNED_ALLOC_256: usize = 256;
+
+ /// Create a new pq scratch
+ pub fn new(graph_degree: usize, aligned_dim: usize) -> ANNResult<Self> {
+ let aligned_pq_coord_scratch =
+ AlignedBoxWithSlice::new(graph_degree * MAX_PQ_CHUNKS, PQScratch::ALIGNED_ALLOC_256)?;
+ let aligned_pqtable_dist_scratch =
+ AlignedBoxWithSlice::new(256 * MAX_PQ_CHUNKS, PQScratch::ALIGNED_ALLOC_256)?;
+ let aligned_dist_scratch =
+ AlignedBoxWithSlice::new(graph_degree, PQScratch::ALIGNED_ALLOC_256)?;
+ let aligned_query_float = AlignedBoxWithSlice::new(aligned_dim, 8 * size_of::<f32>())?;
+ let rotated_query = AlignedBoxWithSlice::new(aligned_dim, 8 * size_of::<f32>())?;
+
+ Ok(Self {
+ aligned_pqtable_dist_scratch,
+ aligned_dist_scratch,
+ aligned_pq_coord_scratch,
+ rotated_query,
+ aligned_query_float,
+ })
+ }
+
+ /// Set rotated_query and aligned_query_float values
+ pub fn set<T>(&mut self, dim: usize, query: &[T], norm: f32)
+ where
+ T: Into<f32> + Copy,
+ {
+ for (d, item) in query.iter().enumerate().take(dim) {
+ let query_val: f32 = (*item).into();
+ if (norm - 1.0).abs() > f32::EPSILON {
+ self.rotated_query[d] = query_val / norm;
+ self.aligned_query_float[d] = query_val / norm;
+ } else {
+ self.rotated_query[d] = query_val;
+ self.aligned_query_float[d] = query_val;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::model::PQScratch;
+
+ #[test]
+ fn test_pq_scratch() {
+ let graph_degree = 512;
+ let aligned_dim = 8;
+
+ let mut pq_scratch: PQScratch = PQScratch::new(graph_degree, aligned_dim).unwrap();
+
+ // Check alignment
+ assert_eq!(
+ (pq_scratch.aligned_pqtable_dist_scratch.as_ptr() as usize) % 256,
+ 0
+ );
+ assert_eq!((pq_scratch.aligned_dist_scratch.as_ptr() as usize) % 256, 0);
+ assert_eq!(
+ (pq_scratch.aligned_pq_coord_scratch.as_ptr() as usize) % 256,
+ 0
+ );
+ assert_eq!((pq_scratch.rotated_query.as_ptr() as usize) % 32, 0);
+ assert_eq!((pq_scratch.aligned_query_float.as_ptr() as usize) % 32, 0);
+
+ // Test set() method
+ let query = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
+ let norm = 2.0f32;
+ pq_scratch.set::<u8>(query.len(), &query, norm);
+
+ (0..query.len()).for_each(|i| {
+ assert_eq!(pq_scratch.rotated_query[i], query[i] as f32 / norm);
+ assert_eq!(pq_scratch.aligned_query_float[i], query[i] as f32 / norm);
+ });
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/scratch_store_manager.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/scratch_store_manager.rs
new file mode 100644
index 0000000..4e2397f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/scratch_store_manager.rs
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use crate::common::ANNResult;
+
+use super::ArcConcurrentBoxedQueue;
+use super::{scratch_traits::Scratch};
+use std::time::Duration;
+
+pub struct ScratchStoreManager<T: Scratch> {
+ scratch: Option<Box<T>>,
+ scratch_pool: ArcConcurrentBoxedQueue<T>,
+}
+
+impl<T: Scratch> ScratchStoreManager<T> {
+ pub fn new(scratch_pool: ArcConcurrentBoxedQueue<T>, wait_time: Duration) -> ANNResult<Self> {
+ let mut scratch = scratch_pool.pop()?;
+ while scratch.is_none() {
+ scratch_pool.wait_for_push_notify(wait_time)?;
+ scratch = scratch_pool.pop()?;
+ }
+
+ Ok(ScratchStoreManager {
+ scratch,
+ scratch_pool,
+ })
+ }
+
+ pub fn scratch_space(&mut self) -> Option<&mut T> {
+ self.scratch.as_deref_mut()
+ }
+}
+
+impl<T: Scratch> Drop for ScratchStoreManager<T> {
+ fn drop(&mut self) {
+ if let Some(mut scratch) = self.scratch.take() {
+ scratch.clear();
+ let _ = self.scratch_pool.push(scratch);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[derive(Debug)]
+ struct MyScratch {
+ data: Vec<i32>,
+ }
+
+ impl Scratch for MyScratch {
+ fn clear(&mut self) {
+ self.data.clear();
+ }
+ }
+
+ #[test]
+ fn test_scratch_store_manager() {
+ let wait_time = Duration::from_millis(100);
+
+ let scratch_pool = ArcConcurrentBoxedQueue::new();
+ for i in 1..3 {
+ scratch_pool.push(Box::new(MyScratch {
+ data: vec![i, 2 * i, 3 * i],
+ })).unwrap();
+ }
+
+ let mut manager = ScratchStoreManager::new(scratch_pool.clone(), wait_time).unwrap();
+ let scratch_space = manager.scratch_space().unwrap();
+
+ assert_eq!(scratch_space.data, vec![1, 2, 3]);
+
+ // At this point, the ScratchStoreManager will go out of scope,
+ // causing the Drop implementation to be called, which should
+ // call the clear method on MyScratch.
+ drop(manager);
+
+ let current_scratch = scratch_pool.pop().unwrap().unwrap();
+ assert_eq!(current_scratch.data, vec![2, 4, 6]);
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/scratch_traits.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/scratch_traits.rs
new file mode 100644
index 0000000..71e4b93
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/scratch_traits.rs
@@ -0,0 +1,8 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub trait Scratch {
+ fn clear(&mut self);
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_io_context.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_io_context.rs
new file mode 100644
index 0000000..d4dff0c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_io_context.rs
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![allow(dead_code)] // Todo: Remove this when the disk index query code is complete.
+use crate::common::ANNError;
+
+use platform::{FileHandle, IOCompletionPort};
+
+// The IOContext struct for disk I/O. One for each thread.
+pub struct IOContext {
+ pub status: Status,
+ pub file_handle: FileHandle,
+ pub io_completion_port: IOCompletionPort,
+}
+
+impl Default for IOContext {
+ fn default() -> Self {
+ IOContext {
+ status: Status::ReadWait,
+ file_handle: FileHandle::default(),
+ io_completion_port: IOCompletionPort::default(),
+ }
+ }
+}
+
+impl IOContext {
+ pub fn new() -> Self {
+ Self::default()
+ }
+}
+
+pub enum Status {
+ ReadWait,
+ ReadSuccess,
+ ReadFailed(ANNError),
+ ProcessComplete,
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_query_scratch.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_query_scratch.rs
new file mode 100644
index 0000000..b366693
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_query_scratch.rs
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![allow(dead_code)] // Todo: Remove this when the disk index query code is complete.
+use std::mem;
+use std::vec::Vec;
+
+use hashbrown::HashSet;
+
+use crate::{
+ common::{ANNResult, AlignedBoxWithSlice},
+ model::{Neighbor, NeighborPriorityQueue},
+ model::data_store::DiskScratchDataset,
+};
+
+use super::{PQScratch, Scratch, MAX_GRAPH_DEGREE, QUERY_ALIGNMENT_OF_T_SIZE};
+
+// Scratch space for disk index based search.
+pub struct SSDQueryScratch<T: Default + Copy, const N: usize>
+{
+ // Disk scratch dataset storing fp vectors with aligned dim (N)
+ pub scratch_dataset: DiskScratchDataset<T, N>,
+
+ // The query scratch.
+ pub query: AlignedBoxWithSlice<T>,
+
+ /// The PQ Scratch.
+ pub pq_scratch: Option<Box<PQScratch>>,
+
+ // The visited set.
+ pub id_scratch: HashSet<u32>,
+
+ /// Best candidates, whose size is candidate_queue_size
+ pub best_candidates: NeighborPriorityQueue,
+
+ // Full return set.
+ pub full_return_set: Vec<Neighbor>,
+}
+
+//
+impl<T: Copy + Default, const N: usize> SSDQueryScratch<T, N>
+{
+ pub fn new(
+ visited_reserve: usize,
+ candidate_queue_size: usize,
+ init_pq_scratch: bool,
+ ) -> ANNResult<Self> {
+ let scratch_dataset = DiskScratchDataset::<T, N>::new()?;
+
+ let query = AlignedBoxWithSlice::<T>::new(N, mem::size_of::<T>() * QUERY_ALIGNMENT_OF_T_SIZE)?;
+
+ let id_scratch = HashSet::<u32>::with_capacity(visited_reserve);
+ let full_return_set = Vec::<Neighbor>::with_capacity(visited_reserve);
+ let best_candidates = NeighborPriorityQueue::with_capacity(candidate_queue_size);
+
+ let pq_scratch = if init_pq_scratch {
+ Some(Box::new(PQScratch::new(MAX_GRAPH_DEGREE, N)?))
+ } else {
+ None
+ };
+
+ Ok(Self {
+ scratch_dataset,
+ query,
+ pq_scratch,
+ id_scratch,
+ best_candidates,
+ full_return_set,
+ })
+ }
+
+ pub fn pq_scratch(&mut self) -> &Option<Box<PQScratch>> {
+ &self.pq_scratch
+ }
+}
+
+impl<T: Default + Copy, const N: usize> Scratch for SSDQueryScratch<T, N>
+{
+ fn clear(&mut self) {
+ self.id_scratch.clear();
+ self.best_candidates.clear();
+ self.full_return_set.clear();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_new() {
+ // Arrange
+ let visited_reserve = 100;
+ let candidate_queue_size = 10;
+ let init_pq_scratch = true;
+
+ // Act
+ let result =
+ SSDQueryScratch::<u32, 3>::new(visited_reserve, candidate_queue_size, init_pq_scratch);
+
+ // Assert
+ assert!(result.is_ok());
+
+ let scratch = result.unwrap();
+
+ // Assert the properties of the scratch instance
+ assert!(scratch.pq_scratch.is_some());
+ assert!(scratch.id_scratch.is_empty());
+ assert!(scratch.best_candidates.size() == 0);
+ assert!(scratch.full_return_set.is_empty());
+ }
+
+ #[test]
+ fn test_clear() {
+ // Arrange
+ let mut scratch = SSDQueryScratch::<u32, 3>::new(100, 10, true).unwrap();
+
+ // Add some data to scratch fields
+ scratch.id_scratch.insert(1);
+ scratch.best_candidates.insert(Neighbor::new(2, 0.5));
+ scratch.full_return_set.push(Neighbor::new(3, 0.8));
+
+ // Act
+ scratch.clear();
+
+ // Assert
+ assert!(scratch.id_scratch.is_empty());
+ assert!(scratch.best_candidates.size() == 0);
+ assert!(scratch.full_return_set.is_empty());
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_thread_data.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_thread_data.rs
new file mode 100644
index 0000000..e374959
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/scratch/ssd_thread_data.rs
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![allow(dead_code)] // Todo: Remove this when the disk index query code is complete.
+use std::sync::Arc;
+
+use super::{scratch_traits::Scratch, IOContext, SSDQueryScratch};
+use crate::common::ANNResult;
+
+// The thread data struct for SSD I/O. One for each thread, contains the ScratchSpace and the IOContext.
+pub struct SSDThreadData<T: Default + Copy, const N: usize> {
+ pub scratch: SSDQueryScratch<T, N>,
+ pub io_context: Option<Arc<IOContext>>,
+}
+
+impl<T: Default + Copy, const N: usize> SSDThreadData<T, N> {
+ pub fn new(
+ aligned_dim: usize,
+ visited_reserve: usize,
+ init_pq_scratch: bool,
+ ) -> ANNResult<Self> {
+ let scratch = SSDQueryScratch::new(aligned_dim, visited_reserve, init_pq_scratch)?;
+ Ok(SSDThreadData {
+ scratch,
+ io_context: None,
+ })
+ }
+
+ pub fn clear(&mut self) {
+ self.scratch.clear();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::model::Neighbor;
+
+ use super::*;
+
+ #[test]
+ fn test_new() {
+ // Arrange
+ let aligned_dim = 10;
+ let visited_reserve = 100;
+ let init_pq_scratch = true;
+
+ // Act
+ let result = SSDThreadData::<u32, 3>::new(aligned_dim, visited_reserve, init_pq_scratch);
+
+ // Assert
+ assert!(result.is_ok());
+
+ let thread_data = result.unwrap();
+
+ // Assert the properties of the thread data instance
+ assert!(thread_data.io_context.is_none());
+
+ let scratch = &thread_data.scratch;
+ // Assert the properties of the scratch instance
+ assert!(scratch.pq_scratch.is_some());
+ assert!(scratch.id_scratch.is_empty());
+ assert!(scratch.best_candidates.size() == 0);
+ assert!(scratch.full_return_set.is_empty());
+ }
+
+ #[test]
+ fn test_clear() {
+ // Arrange
+ let mut thread_data = SSDThreadData::<u32, 3>::new(10, 100, true).unwrap();
+
+ // Add some data to scratch fields
+ thread_data.scratch.id_scratch.insert(1);
+ thread_data
+ .scratch
+ .best_candidates
+ .insert(Neighbor::new(2, 0.5));
+ thread_data
+ .scratch
+ .full_return_set
+ .push(Neighbor::new(3, 0.8));
+
+ // Act
+ thread_data.clear();
+
+ // Assert
+ assert!(thread_data.scratch.id_scratch.is_empty());
+ assert!(thread_data.scratch.best_candidates.size() == 0);
+ assert!(thread_data.scratch.full_return_set.is_empty());
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/dimension.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/dimension.rs
new file mode 100644
index 0000000..32670a8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/dimension.rs
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Vertex dimension
+
+/// 32 vertex dimension
+pub const DIM_32: usize = 32;
+
+/// 64 vertex dimension
+pub const DIM_64: usize = 64;
+
+/// 104 vertex dimension
+pub const DIM_104: usize = 104;
+
+/// 128 vertex dimension
+pub const DIM_128: usize = 128;
+
+/// 256 vertex dimension
+pub const DIM_256: usize = 256;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/mod.rs
new file mode 100644
index 0000000..224d476
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/mod.rs
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod vertex;
+pub use vertex::Vertex;
+
+mod dimension;
+pub use dimension::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/vertex.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/vertex.rs
new file mode 100644
index 0000000..5536974
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/vertex/vertex.rs
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Vertex
+
+use std::array::TryFromSliceError;
+
+use vector::{FullPrecisionDistance, Metric};
+
+/// Vertex with data type T and dimension N
+#[derive(Debug)]
+pub struct Vertex<'a, T, const N: usize>
+where
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Vertex value
+ val: &'a [T; N],
+
+ /// Vertex Id
+ id: u32,
+}
+
+impl<'a, T, const N: usize> Vertex<'a, T, N>
+where
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ /// Create the vertex with data
+ pub fn new(val: &'a [T; N], id: u32) -> Self {
+ Self {
+ val,
+ id,
+ }
+ }
+
+ /// Compare the vertex with another.
+ #[inline(always)]
+ pub fn compare(&self, other: &Vertex<'a, T, N>, metric: Metric) -> f32 {
+ <[T; N]>::distance_compare(self.val, other.val, metric)
+ }
+
+ /// Get the vector associated with the vertex.
+ #[inline]
+ pub fn vector(&self) -> &[T; N] {
+ self.val
+ }
+
+ /// Get the vertex id.
+ #[inline]
+ pub fn vertex_id(&self) -> u32 {
+ self.id
+ }
+}
+
+impl<'a, T, const N: usize> TryFrom<(&'a [T], u32)> for Vertex<'a, T, N>
+where
+ [T; N]: FullPrecisionDistance<T, N>,
+{
+ type Error = TryFromSliceError;
+
+ fn try_from((mem_slice, id): (&'a [T], u32)) -> Result<Self, Self::Error> {
+ let array: &[T; N] = mem_slice.try_into()?;
+ Ok(Vertex::new(array, id))
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/windows_aligned_file_reader/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/windows_aligned_file_reader/mod.rs
new file mode 100644
index 0000000..0e63df0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/windows_aligned_file_reader/mod.rs
@@ -0,0 +1,7 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[allow(clippy::module_inception)]
+mod windows_aligned_file_reader;
+pub use windows_aligned_file_reader::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/windows_aligned_file_reader/windows_aligned_file_reader.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/windows_aligned_file_reader/windows_aligned_file_reader.rs
new file mode 100644
index 0000000..1cc3dc0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/model/windows_aligned_file_reader/windows_aligned_file_reader.rs
@@ -0,0 +1,414 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::sync::Arc;
+use std::time::Duration;
+use std::{ptr, thread};
+
+use crossbeam::sync::ShardedLock;
+use hashbrown::HashMap;
+use once_cell::sync::Lazy;
+
+use platform::file_handle::{AccessMode, ShareMode};
+use platform::{
+ file_handle::FileHandle,
+ file_io::{get_queued_completion_status, read_file_to_slice},
+ io_completion_port::IOCompletionPort,
+};
+
+use winapi::{
+ shared::{basetsd::ULONG_PTR, minwindef::DWORD},
+ um::minwinbase::OVERLAPPED,
+};
+
+use crate::common::{ANNError, ANNResult};
+use crate::model::IOContext;
+
+pub const MAX_IO_CONCURRENCY: usize = 128; // To do: explore the optimal value for this. The current value is taken from C++ code.
+pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x00000001;
+pub const IO_COMPLETION_TIMEOUT: DWORD = u32::MAX; // Infinite timeout.
+pub const DISK_IO_ALIGNMENT: usize = 512;
+pub const ASYNC_IO_COMPLETION_CHECK_INTERVAL: Duration = Duration::from_micros(5);
+
+/// Aligned read struct for disk IO, it takes the ownership of the AlignedBoxedSlice and returns the AlignedBoxWithSlice data immutably.
+pub struct AlignedRead<'a, T> {
+ /// where to read from
+ /// offset needs to be aligned with DISK_IO_ALIGNMENT
+ offset: u64,
+
+ /// where to read into
+ /// aligned_buf and its len need to be aligned with DISK_IO_ALIGNMENT
+ aligned_buf: &'a mut [T],
+}
+
+impl<'a, T> AlignedRead<'a, T> {
+ pub fn new(offset: u64, aligned_buf: &'a mut [T]) -> ANNResult<Self> {
+ Self::assert_is_aligned(offset as usize)?;
+ Self::assert_is_aligned(std::mem::size_of_val(aligned_buf))?;
+
+ Ok(Self {
+ offset,
+ aligned_buf,
+ })
+ }
+
+ fn assert_is_aligned(val: usize) -> ANNResult<()> {
+ match val % DISK_IO_ALIGNMENT {
+ 0 => Ok(()),
+ _ => Err(ANNError::log_disk_io_request_alignment_error(format!(
+ "The offset or length of AlignedRead request is not {} bytes aligned",
+ DISK_IO_ALIGNMENT
+ ))),
+ }
+ }
+
+ pub fn aligned_buf(&self) -> &[T] {
+ self.aligned_buf
+ }
+}
+
+pub struct WindowsAlignedFileReader {
+ file_name: String,
+
+ // ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads.
+ // ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent read access to the shared data while allowing exclusive write access.
+ // It achieves better scalability by dividing the shared data into multiple shards, and each with its own internal lock.
+ // Multiple threads can read from different shards simultaneously, reducing contention.
+ // https://docs.rs/crossbeam/0.8.2/crossbeam/sync/struct.ShardedLock.html
+ // Comparing to RwLock, ShardedLock provides higher concurrency for read operations and is suitable for read heavy workloads.
+ // The value of the hashmap is an Arc<IOContext> to allow immutable access to IOContext with automatic reference counting.
+ ctx_map: Lazy<ShardedLock<HashMap<thread::ThreadId, Arc<IOContext>>>>,
+}
+
+impl WindowsAlignedFileReader {
+ pub fn new(fname: &str) -> ANNResult<Self> {
+ let reader: WindowsAlignedFileReader = WindowsAlignedFileReader {
+ file_name: fname.to_string(),
+ ctx_map: Lazy::new(|| ShardedLock::new(HashMap::new())),
+ };
+
+ reader.register_thread()?;
+ Ok(reader)
+ }
+
+ // Register the io context for a thread if it hasn't been registered.
+ pub fn register_thread(&self) -> ANNResult<()> {
+ let mut ctx_map = self.ctx_map.write().map_err(|_| {
+ ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string())
+ })?;
+
+ let id = thread::current().id();
+ if ctx_map.contains_key(&id) {
+ println!(
+ "Warning:: Duplicate registration for thread_id : {:?}. Directly call get_ctx to get the thread context data.",
+ id);
+
+ return Ok(());
+ }
+
+ let mut ctx = IOContext::new();
+
+ match unsafe { FileHandle::new(&self.file_name, AccessMode::Read, ShareMode::Read) } {
+ Ok(file_handle) => ctx.file_handle = file_handle,
+ Err(err) => {
+ return Err(ANNError::log_io_error(err));
+ }
+ }
+
+ // Create a io completion port for the file handle, later it will be used to get the completion status.
+ match IOCompletionPort::new(&ctx.file_handle, None, 0, 0) {
+ Ok(io_completion_port) => ctx.io_completion_port = io_completion_port,
+ Err(err) => {
+ return Err(ANNError::log_io_error(err));
+ }
+ }
+
+ ctx_map.insert(id, Arc::new(ctx));
+
+ Ok(())
+ }
+
+ // Get the reference counted io context for the current thread.
+ pub fn get_ctx(&self) -> ANNResult<Arc<IOContext>> {
+ let ctx_map = self.ctx_map.read().map_err(|_| {
+ ANNError::log_lock_poison_error("unable to acquire read lock on ctx_map".to_string())
+ })?;
+
+ let id = thread::current().id();
+ match ctx_map.get(&id) {
+ Some(ctx) => Ok(Arc::clone(ctx)),
+ None => Err(ANNError::log_index_error(format!(
+ "unable to find IOContext for thread_id {:?}",
+ id
+ ))),
+ }
+ }
+
+ // Read the data from the file by sending concurrent io requests in batches.
+ pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>], ctx: &IOContext) -> ANNResult<()> {
+ let n_requests = read_requests.len();
+ let n_batches = (n_requests + MAX_IO_CONCURRENCY - 1) / MAX_IO_CONCURRENCY;
+
+ let mut overlapped_in_out =
+ vec![unsafe { std::mem::zeroed::<OVERLAPPED>() }; MAX_IO_CONCURRENCY];
+
+ for batch_idx in 0..n_batches {
+ let batch_start = MAX_IO_CONCURRENCY * batch_idx;
+ let batch_size = std::cmp::min(n_requests - batch_start, MAX_IO_CONCURRENCY);
+
+ for j in 0..batch_size {
+ let req = &mut read_requests[batch_start + j];
+ let os = &mut overlapped_in_out[j];
+
+ match unsafe {
+ read_file_to_slice(&ctx.file_handle, req.aligned_buf, os, req.offset)
+ } {
+ Ok(_) => {}
+ Err(error) => {
+ return Err(ANNError::IOError { err: (error) });
+ }
+ }
+ }
+
+ let mut n_read: DWORD = 0;
+ let mut n_complete: u64 = 0;
+ let mut completion_key: ULONG_PTR = 0;
+ let mut lp_os: *mut OVERLAPPED = ptr::null_mut();
+ while n_complete < batch_size as u64 {
+ match unsafe {
+ get_queued_completion_status(
+ &ctx.io_completion_port,
+ &mut n_read,
+ &mut completion_key,
+ &mut lp_os,
+ IO_COMPLETION_TIMEOUT,
+ )
+ } {
+ // An IO request completed.
+ Ok(true) => n_complete += 1,
+ // No IO request completed, continue to wait.
+ Ok(false) => {
+ thread::sleep(ASYNC_IO_COMPLETION_CHECK_INTERVAL);
+ }
+ // An error ocurred.
+ Err(error) => return Err(ANNError::IOError { err: (error) }),
+ }
+ }
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{fs::File, io::BufReader};
+
+ use bincode::deserialize_from;
+ use serde::{Deserialize, Serialize};
+
+ use crate::{common::AlignedBoxWithSlice, model::SECTOR_LEN};
+
+ use super::*;
+ pub const TEST_INDEX_PATH: &str =
+ "./tests/data/disk_index_siftsmall_learn_256pts_R4_L50_A1.2_alligned_reader_test.index";
+ pub const TRUTH_NODE_DATA_PATH: &str =
+ "./tests/data/disk_index_node_data_aligned_reader_truth.bin";
+
+ #[derive(Debug, Serialize, Deserialize)]
+ struct NodeData {
+ num_neighbors: u32,
+ coordinates: Vec<f32>,
+ neighbors: Vec<u32>,
+ }
+
+ impl PartialEq for NodeData {
+ fn eq(&self, other: &Self) -> bool {
+ self.num_neighbors == other.num_neighbors
+ && self.coordinates == other.coordinates
+ && self.neighbors == other.neighbors
+ }
+ }
+
+ #[test]
+ fn test_new_aligned_file_reader() {
+ // Replace "test_file_path" with actual file path
+ let result = WindowsAlignedFileReader::new(TEST_INDEX_PATH);
+ assert!(result.is_ok());
+
+ let reader = result.unwrap();
+ assert_eq!(reader.file_name, TEST_INDEX_PATH);
+ }
+
+ #[test]
+ fn test_read() {
+ let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
+ let ctx = reader.get_ctx().unwrap();
+
+ let read_length = 512; // adjust according to your logic
+ let num_read = 10;
+ let mut aligned_mem = AlignedBoxWithSlice::<u8>::new(read_length * num_read, 512).unwrap();
+
+ // create and add AlignedReads to the vector
+ let mut mem_slices = aligned_mem
+ .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length)
+ .unwrap();
+
+ let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices
+ .iter_mut()
+ .enumerate()
+ .map(|(i, slice)| {
+ let offset = (i * read_length) as u64;
+ AlignedRead::new(offset, slice).unwrap()
+ })
+ .collect();
+
+ let result = reader.read(&mut aligned_reads, &ctx);
+ assert!(result.is_ok());
+ }
+
+ #[test]
+ fn test_read_disk_index_by_sector() {
+ let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
+ let ctx = reader.get_ctx().unwrap();
+
+ let read_length = SECTOR_LEN; // adjust according to your logic
+ let num_sector = 10;
+ let mut aligned_mem =
+ AlignedBoxWithSlice::<u8>::new(read_length * num_sector, 512).unwrap();
+
+ // Each slice will be used as the buffer for a read request of a sector.
+ let mut mem_slices = aligned_mem
+ .split_into_nonoverlapping_mut_slices(0..aligned_mem.len(), read_length)
+ .unwrap();
+
+ let mut aligned_reads: Vec<AlignedRead<'_, u8>> = mem_slices
+ .iter_mut()
+ .enumerate()
+ .map(|(sector_id, slice)| {
+ let offset = (sector_id * read_length) as u64;
+ AlignedRead::new(offset, slice).unwrap()
+ })
+ .collect();
+
+ let result = reader.read(&mut aligned_reads, &ctx);
+ assert!(result.is_ok());
+
+ aligned_reads.iter().for_each(|read| {
+ assert_eq!(read.aligned_buf.len(), SECTOR_LEN);
+ });
+
+ let disk_layout_meta = reconstruct_disk_meta(aligned_reads[0].aligned_buf);
+ assert!(disk_layout_meta.len() > 9);
+
+ let dims = disk_layout_meta[1];
+ let num_pts = disk_layout_meta[0];
+ let max_node_len = disk_layout_meta[3];
+ let max_num_nodes_per_sector = disk_layout_meta[4];
+
+ assert!(max_node_len * max_num_nodes_per_sector < SECTOR_LEN as u64);
+
+ let num_nbrs_start = (dims as usize) * std::mem::size_of::<f32>();
+ let nbrs_buf_start = num_nbrs_start + std::mem::size_of::<u32>();
+
+ let mut node_data_array = Vec::with_capacity(max_num_nodes_per_sector as usize * 9);
+
+ // Only validate the first 9 sectors with graph nodes.
+ (1..9).for_each(|sector_id| {
+ let sector_data = &mem_slices[sector_id];
+ for node_data in sector_data.chunks_exact(max_node_len as usize) {
+ // Extract coordinates data from the start of the node_data
+ let coordinates_end = (dims as usize) * std::mem::size_of::<f32>();
+ let coordinates = node_data[0..coordinates_end]
+ .chunks_exact(std::mem::size_of::<f32>())
+ .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap()))
+ .collect();
+
+ // Extract number of neighbors from the node_data
+ let neighbors_num = u32::from_le_bytes(
+ node_data[num_nbrs_start..nbrs_buf_start]
+ .try_into()
+ .unwrap(),
+ );
+
+ let nbors_buf_end =
+ nbrs_buf_start + (neighbors_num as usize) * std::mem::size_of::<u32>();
+
+ // Extract neighbors from the node data.
+ let mut neighbors = Vec::new();
+ for nbors_data in node_data[nbrs_buf_start..nbors_buf_end]
+ .chunks_exact(std::mem::size_of::<u32>())
+ {
+ let nbors_id = u32::from_le_bytes(nbors_data.try_into().unwrap());
+ assert!(nbors_id < num_pts as u32);
+ neighbors.push(nbors_id);
+ }
+
+ // Create NodeData struct and push it to the node_data_array
+ node_data_array.push(NodeData {
+ num_neighbors: neighbors_num,
+ coordinates,
+ neighbors,
+ });
+ }
+ });
+
+ // Compare that each node read from the disk index are expected.
+ let node_data_truth_file = File::open(TRUTH_NODE_DATA_PATH).unwrap();
+ let reader = BufReader::new(node_data_truth_file);
+
+ let node_data_vec: Vec<NodeData> = deserialize_from(reader).unwrap();
+ for (node_from_node_data_file, node_from_disk_index) in
+ node_data_vec.iter().zip(node_data_array.iter())
+ {
+ // Verify that the NodeData from the file is equal to the NodeData in node_data_array
+ assert_eq!(node_from_node_data_file, node_from_disk_index);
+ }
+ }
+
+ #[test]
+ fn test_read_fail_invalid_file() {
+ let reader = WindowsAlignedFileReader::new("/invalid_path");
+ assert!(reader.is_err());
+ }
+
+ #[test]
+ fn test_read_no_requests() {
+ let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
+ let ctx = reader.get_ctx().unwrap();
+
+ let mut read_requests = Vec::<AlignedRead<u8>>::new();
+ let result = reader.read(&mut read_requests, &ctx);
+ assert!(result.is_ok());
+ }
+
+ #[test]
+ fn test_get_ctx() {
+ let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
+ let result = reader.get_ctx();
+ assert!(result.is_ok());
+ }
+
+ #[test]
+ fn test_register_thread() {
+ let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap();
+ let result = reader.register_thread();
+ assert!(result.is_ok());
+ }
+
+ fn reconstruct_disk_meta(buffer: &[u8]) -> Vec<u64> {
+ let size_of_u64 = std::mem::size_of::<u64>();
+
+ let num_values = buffer.len() / size_of_u64;
+ let mut disk_layout_meta = Vec::with_capacity(num_values);
+ let meta_data = &buffer[8..];
+
+ for chunk in meta_data.chunks_exact(size_of_u64) {
+ let value = u64::from_le_bytes(chunk.try_into().unwrap());
+ disk_layout_meta.push(value);
+ }
+
+ disk_layout_meta
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/disk_graph_storage.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/disk_graph_storage.rs
new file mode 100644
index 0000000..4481752
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/disk_graph_storage.rs
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_docs)]
+
+//! Disk graph storage
+
+use std::sync::Arc;
+
+use crate::{model::{WindowsAlignedFileReader, IOContext, AlignedRead}, common::ANNResult};
+
+/// Graph storage for disk index
+/// One thread has one storage instance
+pub struct DiskGraphStorage {
+ /// Disk graph reader
+ disk_graph_reader: Arc<WindowsAlignedFileReader>,
+
+ /// IOContext of current thread
+ ctx: Arc<IOContext>,
+}
+
+impl DiskGraphStorage {
+ /// Create a new DiskGraphStorage instance
+ pub fn new(disk_graph_reader: Arc<WindowsAlignedFileReader>) -> ANNResult<Self> {
+ let ctx = disk_graph_reader.get_ctx()?;
+ Ok(Self {
+ disk_graph_reader,
+ ctx,
+ })
+ }
+
+ /// Read disk graph data
+ pub fn read<T>(&self, read_requests: &mut [AlignedRead<T>]) -> ANNResult<()> {
+ self.disk_graph_reader.read(read_requests, &self.ctx)
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/disk_index_storage.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/disk_index_storage.rs
new file mode 100644
index 0000000..0c55808
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/disk_index_storage.rs
@@ -0,0 +1,363 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use byteorder::{ByteOrder, LittleEndian, ReadBytesExt};
+use std::fs::File;
+use std::io::Read;
+use std::marker::PhantomData;
+use std::{fs, mem};
+
+use crate::common::{ANNError, ANNResult};
+use crate::model::NUM_PQ_CENTROIDS;
+use crate::storage::PQStorage;
+use crate::utils::{convert_types_u32_usize, convert_types_u64_usize, load_bin, save_bin_u64};
+use crate::utils::{
+ file_exists, gen_sample_data, get_file_size, round_up, CachedReader, CachedWriter,
+};
+
+const SECTOR_LEN: usize = 4096;
+
+/// Todo: Remove the allow(dead_code) when the disk search code is complete
+#[allow(dead_code)]
+pub struct PQPivotData {
+ dim: usize,
+ pq_table: Vec<f32>,
+ centroids: Vec<f32>,
+ chunk_offsets: Vec<usize>,
+}
+
+pub struct DiskIndexStorage<T> {
+ /// Dataset file
+ dataset_file: String,
+
+ /// Index file path prefix
+ index_path_prefix: String,
+
+ // TODO: Only a placeholder for T, will be removed later
+ _marker: PhantomData<T>,
+
+ pq_storage: PQStorage,
+}
+
+impl<T> DiskIndexStorage<T> {
+ /// Create DiskIndexStorage instance
+ pub fn new(dataset_file: String, index_path_prefix: String) -> ANNResult<Self> {
+ let pq_storage: PQStorage = PQStorage::new(
+ &(index_path_prefix.clone() + ".bin_pq_pivots.bin"),
+ &(index_path_prefix.clone() + ".bin_pq_compressed.bin"),
+ &dataset_file,
+ )?;
+
+ Ok(DiskIndexStorage {
+ dataset_file,
+ index_path_prefix,
+ _marker: PhantomData,
+ pq_storage,
+ })
+ }
+
+ pub fn get_pq_storage(&mut self) -> &mut PQStorage {
+ &mut self.pq_storage
+ }
+
+ pub fn dataset_file(&self) -> &String {
+ &self.dataset_file
+ }
+
+ pub fn index_path_prefix(&self) -> &String {
+ &self.index_path_prefix
+ }
+
+ /// Create disk layout
+ /// Sector #1: disk_layout_meta
+ /// Sector #n: num_nodes_per_sector nodes
+ /// Each node's layout: {full precision vector:[T; DIM]}{num_nbrs: u32}{neighbors: [u32; num_nbrs]}
+ /// # Arguments
+ /// * `dataset_file` - dataset file containing full precision vectors
+ /// * `mem_index_file` - in-memory index graph file
+ /// * `disk_layout_file` - output disk layout file
+ pub fn create_disk_layout(&self) -> ANNResult<()> {
+ let mem_index_file = self.mem_index_file();
+ let disk_layout_file = self.disk_index_file();
+
+ // amount to read or write in one shot
+ let read_blk_size = 64 * 1024 * 1024;
+ let write_blk_size = read_blk_size;
+ let mut dataset_reader = CachedReader::new(self.dataset_file.as_str(), read_blk_size)?;
+
+ let num_pts = dataset_reader.read_u32()? as u64;
+ let dims = dataset_reader.read_u32()? as u64;
+
+ // Create cached reader + writer
+ let actual_file_size = get_file_size(mem_index_file.as_str())?;
+ println!("Vamana index file size={}", actual_file_size);
+
+ let mut vamana_reader = File::open(mem_index_file)?;
+ let mut diskann_writer = CachedWriter::new(disk_layout_file.as_str(), write_blk_size)?;
+
+ let index_file_size = vamana_reader.read_u64::<LittleEndian>()?;
+ if index_file_size != actual_file_size {
+ println!(
+ "Vamana Index file size does not match expected size per meta-data. file size from file: {}, actual file size: {}",
+ index_file_size, actual_file_size
+ );
+ }
+
+ let max_degree = vamana_reader.read_u32::<LittleEndian>()?;
+ let medoid = vamana_reader.read_u32::<LittleEndian>()?;
+ let vamana_frozen_num = vamana_reader.read_u64::<LittleEndian>()?;
+
+ let mut vamana_frozen_loc = 0;
+ if vamana_frozen_num == 1 {
+ vamana_frozen_loc = medoid;
+ }
+
+ let max_node_len = ((max_degree as u64 + 1) * (mem::size_of::<u32>() as u64))
+ + (dims * (mem::size_of::<T>() as u64));
+ let num_nodes_per_sector = (SECTOR_LEN as u64) / max_node_len;
+
+ println!("medoid: {}B", medoid);
+ println!("max_node_len: {}B", max_node_len);
+ println!("num_nodes_per_sector: {}B", num_nodes_per_sector);
+
+ // SECTOR_LEN buffer for each sector
+ let mut sector_buf = vec![0u8; SECTOR_LEN];
+ let mut node_buf = vec![0u8; max_node_len as usize];
+
+ let num_nbrs_start = (dims as usize) * mem::size_of::<T>();
+ let nbrs_buf_start = num_nbrs_start + mem::size_of::<u32>();
+
+ // number of sectors (1 for meta data)
+ let num_sectors = round_up(num_pts, num_nodes_per_sector) / num_nodes_per_sector;
+ let disk_index_file_size = (num_sectors + 1) * (SECTOR_LEN as u64);
+
+ let disk_layout_meta = vec![
+ num_pts,
+ dims,
+ medoid as u64,
+ max_node_len,
+ num_nodes_per_sector,
+ vamana_frozen_num,
+ vamana_frozen_loc as u64,
+ // append_reorder_data
+ // We are not supporting this. Temporarily write it into the layout so that
+ // we can leverage C++ query driver to test the disk index
+ false as u64,
+ disk_index_file_size,
+ ];
+
+ diskann_writer.write(&sector_buf)?;
+
+ let mut cur_node_coords = vec![0u8; (dims as usize) * mem::size_of::<T>()];
+ let mut cur_node_id = 0u64;
+
+ for sector in 0..num_sectors {
+ if sector % 100_000 == 0 {
+ println!("Sector #{} written", sector);
+ }
+ sector_buf.fill(0);
+
+ for sector_node_id in 0..num_nodes_per_sector {
+ if cur_node_id >= num_pts {
+ break;
+ }
+
+ node_buf.fill(0);
+
+ // read cur node's num_nbrs
+ let num_nbrs = vamana_reader.read_u32::<LittleEndian>()?;
+
+ // sanity checks on num_nbrs
+ debug_assert!(num_nbrs > 0);
+ debug_assert!(num_nbrs <= max_degree);
+
+ // write coords of node first
+ dataset_reader.read(&mut cur_node_coords)?;
+ node_buf[..cur_node_coords.len()].copy_from_slice(&cur_node_coords);
+
+ // write num_nbrs
+ LittleEndian::write_u32(
+ &mut node_buf[num_nbrs_start..(num_nbrs_start + mem::size_of::<u32>())],
+ num_nbrs,
+ );
+
+ // write neighbors
+ let nbrs_buf = &mut node_buf[nbrs_buf_start
+ ..(nbrs_buf_start + (num_nbrs as usize) * mem::size_of::<u32>())];
+ vamana_reader.read_exact(nbrs_buf)?;
+
+ // get offset into sector_buf
+ let sector_node_buf_start = (sector_node_id * max_node_len) as usize;
+ let sector_node_buf = &mut sector_buf
+ [sector_node_buf_start..(sector_node_buf_start + max_node_len as usize)];
+ sector_node_buf.copy_from_slice(&node_buf[..(max_node_len as usize)]);
+
+ cur_node_id += 1;
+ }
+
+ // flush sector to disk
+ diskann_writer.write(&sector_buf)?;
+ }
+
+ diskann_writer.flush()?;
+ save_bin_u64(
+ disk_layout_file.as_str(),
+ &disk_layout_meta,
+ disk_layout_meta.len(),
+ 1,
+ 0,
+ )?;
+
+ Ok(())
+ }
+
+ pub fn index_build_cleanup(&self) -> ANNResult<()> {
+ fs::remove_file(self.mem_index_file())?;
+ Ok(())
+ }
+
+ pub fn gen_query_warmup_data(&self, sampling_rate: f64) -> ANNResult<()> {
+ gen_sample_data::<T>(
+ &self.dataset_file,
+ &self.warmup_query_prefix(),
+ sampling_rate,
+ )?;
+ Ok(())
+ }
+
+ /// Load pre-trained pivot table
+ pub fn load_pq_pivots_bin(
+ &self,
+ num_pq_chunks: &usize,
+ ) -> ANNResult<PQPivotData> {
+ let pq_pivots_path = &self.pq_pivot_file();
+ if !file_exists(pq_pivots_path) {
+ return Err(ANNError::log_pq_error(
+ "ERROR: PQ k-means pivot file not found.".to_string(),
+ ));
+ }
+
+ let (data, offset_num, offset_dim) = load_bin::<u64>(pq_pivots_path, 0)?;
+ let file_offset_data = convert_types_u64_usize(&data, offset_num, offset_dim);
+ if offset_num != 4 {
+ let error_message = format!("Error reading pq_pivots file {}. Offsets don't contain correct metadata, # offsets = {}, but expecting 4.", pq_pivots_path, offset_num);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, pivot_num, dim) = load_bin::<f32>(pq_pivots_path, file_offset_data[0])?;
+ let pq_table = data.to_vec();
+ if pivot_num != NUM_PQ_CENTROIDS {
+ let error_message = format!(
+ "Error reading pq_pivots file {}. file_num_centers = {}, but expecting {} centers.",
+ pq_pivots_path, pivot_num, NUM_PQ_CENTROIDS
+ );
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, centroid_dim, nc) = load_bin::<f32>(pq_pivots_path, file_offset_data[1])?;
+ let centroids = data.to_vec();
+ if centroid_dim != dim || nc != 1 {
+ let error_message = format!("Error reading pq_pivots file {}. file_dim = {}, file_cols = {} but expecting {} entries in 1 dimension.", pq_pivots_path, centroid_dim, nc, dim);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, chunk_offset_num, nc) = load_bin::<u32>(pq_pivots_path, file_offset_data[2])?;
+ let chunk_offsets = convert_types_u32_usize(&data, chunk_offset_num, nc);
+ if chunk_offset_num != num_pq_chunks + 1 || nc != 1 {
+ let error_message = format!("Error reading pq_pivots file at chunk offsets; file has nr={}, nc={} but expecting nr={} and nc=1.", chunk_offset_num, nc, num_pq_chunks + 1);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ Ok(PQPivotData {
+ dim,
+ pq_table,
+ centroids,
+ chunk_offsets
+ })
+ }
+
+ fn mem_index_file(&self) -> String {
+ self.index_path_prefix.clone() + "_mem.index"
+ }
+
+ fn disk_index_file(&self) -> String {
+ self.index_path_prefix.clone() + "_disk.index"
+ }
+
+ fn warmup_query_prefix(&self) -> String {
+ self.index_path_prefix.clone() + "_sample"
+ }
+
+ pub fn pq_pivot_file(&self) -> String {
+ self.index_path_prefix.clone() + ".bin_pq_pivots.bin"
+ }
+
+ pub fn compressed_pq_pivot_file(&self) -> String {
+ self.index_path_prefix.clone() + ".bin_pq_compressed.bin"
+ }
+}
+
+#[cfg(test)]
+mod disk_index_storage_test {
+ use std::fs;
+
+ use crate::test_utils::get_test_file_path;
+
+ use super::*;
+
+ const TEST_DATA_FILE: &str = "tests/data/siftsmall_learn_256pts.fbin";
+ const DISK_INDEX_PATH_PREFIX: &str = "tests/data/disk_index_siftsmall_learn_256pts_R4_L50_A1.2";
+ const TRUTH_DISK_LAYOUT: &str =
+ "tests/data/truth_disk_index_siftsmall_learn_256pts_R4_L50_A1.2_disk.index";
+
+ #[test]
+ fn create_disk_layout_test() {
+ let storage = DiskIndexStorage::<f32>::new(
+ get_test_file_path(TEST_DATA_FILE),
+ get_test_file_path(DISK_INDEX_PATH_PREFIX),
+ ).unwrap();
+ storage.create_disk_layout().unwrap();
+
+ let disk_layout_file = storage.disk_index_file();
+ let rust_disk_layout = fs::read(disk_layout_file.as_str()).unwrap();
+ let truth_disk_layout = fs::read(get_test_file_path(TRUTH_DISK_LAYOUT).as_str()).unwrap();
+
+ assert!(rust_disk_layout == truth_disk_layout);
+
+ fs::remove_file(disk_layout_file.as_str()).expect("Failed to delete file");
+ }
+
+ #[test]
+ fn load_pivot_test() {
+ let dim: usize = 128;
+ let num_pq_chunk: usize = 1;
+ let pivot_file_prefix: &str = "tests/data/siftsmall_learn";
+ let storage = DiskIndexStorage::<f32>::new(
+ get_test_file_path(TEST_DATA_FILE),
+ pivot_file_prefix.to_string(),
+ ).unwrap();
+
+ let pq_pivot_data =
+ storage.load_pq_pivots_bin(&num_pq_chunk).unwrap();
+
+ assert_eq!(pq_pivot_data.pq_table.len(), NUM_PQ_CENTROIDS * dim);
+ assert_eq!(pq_pivot_data.centroids.len(), dim);
+
+ assert_eq!(pq_pivot_data.chunk_offsets[0], 0);
+ assert_eq!(pq_pivot_data.chunk_offsets[1], dim);
+ assert_eq!(pq_pivot_data.chunk_offsets.len(), num_pq_chunk + 1);
+ }
+
+ #[test]
+ #[should_panic(expected = "ERROR: PQ k-means pivot file not found.")]
+ fn load_pivot_file_not_exist_test() {
+ let num_pq_chunk: usize = 1;
+ let pivot_file_prefix: &str = "tests/data/siftsmall_learn_file_not_exist";
+ let storage = DiskIndexStorage::<f32>::new(
+ get_test_file_path(TEST_DATA_FILE),
+ pivot_file_prefix.to_string(),
+ ).unwrap();
+ let _ = storage.load_pq_pivots_bin(&num_pq_chunk).unwrap();
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/mod.rs
new file mode 100644
index 0000000..03c5b8e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/mod.rs
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+mod disk_index_storage;
+pub use disk_index_storage::*;
+
+mod disk_graph_storage;
+pub use disk_graph_storage::*;
+
+mod pq_storage;
+pub use pq_storage::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/pq_storage.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/pq_storage.rs
new file mode 100644
index 0000000..b1d3fa0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/storage/pq_storage.rs
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use byteorder::{LittleEndian, ReadBytesExt};
+use rand::distributions::{Distribution, Uniform};
+use std::fs::File;
+use std::io::{Read, Seek, SeekFrom, Write};
+use std::mem;
+
+use crate::common::{ANNError, ANNResult};
+use crate::utils::CachedReader;
+use crate::utils::{
+ convert_types_u32_usize, convert_types_u64_usize, convert_types_usize_u32,
+ convert_types_usize_u64, convert_types_usize_u8, save_bin_f32, save_bin_u32, save_bin_u64,
+};
+use crate::utils::{file_exists, load_bin, open_file_to_write, METADATA_SIZE};
+
+#[derive(Debug)]
+pub struct PQStorage {
+ /// Pivot table path
+ pivot_file: String,
+
+ /// Compressed pivot path
+ compressed_pivot_file: String,
+
+ /// Data used to construct PQ table and PQ compressed table
+ pq_data_file: String,
+
+ /// PQ data reader
+ pq_data_file_reader: File,
+}
+
+impl PQStorage {
+ pub fn new(
+ pivot_file: &str,
+ compressed_pivot_file: &str,
+ pq_data_file: &str,
+ ) -> std::io::Result<Self> {
+ let pq_data_file_reader = File::open(pq_data_file)?;
+ Ok(Self {
+ pivot_file: pivot_file.to_string(),
+ compressed_pivot_file: compressed_pivot_file.to_string(),
+ pq_data_file: pq_data_file.to_string(),
+ pq_data_file_reader,
+ })
+ }
+
+ pub fn write_compressed_pivot_metadata(&self, npts: i32, pq_chunk: i32) -> std::io::Result<()> {
+ let mut writer = open_file_to_write(&self.compressed_pivot_file)?;
+ writer.write_all(&npts.to_le_bytes())?;
+ writer.write_all(&pq_chunk.to_le_bytes())?;
+ Ok(())
+ }
+
+ pub fn write_compressed_pivot_data(
+ &self,
+ compressed_base: &[usize],
+ num_centers: usize,
+ block_size: usize,
+ num_pq_chunks: usize,
+ ) -> std::io::Result<()> {
+ let mut writer = open_file_to_write(&self.compressed_pivot_file)?;
+ writer.seek(SeekFrom::Start((std::mem::size_of::<i32>() * 2) as u64))?;
+ if num_centers > 256 {
+ writer.write_all(unsafe {
+ std::slice::from_raw_parts(
+ compressed_base.as_ptr() as *const u8,
+ block_size * num_pq_chunks * std::mem::size_of::<usize>(),
+ )
+ })?;
+ } else {
+ let compressed_base_u8 =
+ convert_types_usize_u8(compressed_base, block_size, num_pq_chunks);
+ writer.write_all(&compressed_base_u8)?;
+ }
+ Ok(())
+ }
+
+ pub fn write_pivot_data(
+ &self,
+ full_pivot_data: &[f32],
+ centroid: &[f32],
+ chunk_offsets: &[usize],
+ num_centers: usize,
+ dim: usize,
+ ) -> std::io::Result<()> {
+ let mut cumul_bytes: Vec<usize> = vec![0; 4];
+ cumul_bytes[0] = METADATA_SIZE;
+ cumul_bytes[1] = cumul_bytes[0]
+ + save_bin_f32(
+ &self.pivot_file,
+ full_pivot_data,
+ num_centers,
+ dim,
+ cumul_bytes[0],
+ )?;
+ cumul_bytes[2] =
+ cumul_bytes[1] + save_bin_f32(&self.pivot_file, centroid, dim, 1, cumul_bytes[1])?;
+
+ // Because the writer only can write u32, u64 but not usize, so we need to convert the type first.
+ let chunk_offsets_u64 = convert_types_usize_u32(chunk_offsets, chunk_offsets.len(), 1);
+ cumul_bytes[3] = cumul_bytes[2]
+ + save_bin_u32(
+ &self.pivot_file,
+ &chunk_offsets_u64,
+ chunk_offsets.len(),
+ 1,
+ cumul_bytes[2],
+ )?;
+
+ let cumul_bytes_u64 = convert_types_usize_u64(&cumul_bytes, 4, 1);
+ save_bin_u64(&self.pivot_file, &cumul_bytes_u64, cumul_bytes.len(), 1, 0)?;
+
+ Ok(())
+ }
+
+ pub fn pivot_data_exist(&self) -> bool {
+ file_exists(&self.pivot_file)
+ }
+
+ pub fn read_pivot_metadata(&self) -> std::io::Result<(usize, usize)> {
+ let (_, file_num_centers, file_dim) = load_bin::<f32>(&self.pivot_file, METADATA_SIZE)?;
+ Ok((file_num_centers, file_dim))
+ }
+
+ pub fn load_pivot_data(
+ &self,
+ num_pq_chunks: &usize,
+ num_centers: &usize,
+ dim: &usize,
+ ) -> ANNResult<(Vec<f32>, Vec<f32>, Vec<usize>)> {
+ // Load file offset data. File saved as offset data(4*1) -> pivot data(centroid num*dim) -> centroid of dim data(dim*1) -> chunk offset data(chunksize+1*1)
+ // Because we only can write u64 rather than usize, so the file stored as u64 type. Need to convert to usize when use.
+ let (data, offset_num, nc) = load_bin::<u64>(&self.pivot_file, 0)?;
+ let file_offset_data = convert_types_u64_usize(&data, offset_num, nc);
+ if offset_num != 4 {
+ let error_message = format!("Error reading pq_pivots file {}. Offsets don't contain correct metadata, # offsets = {}, but expecting 4.", &self.pivot_file, offset_num);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, pivot_num, pivot_dim) = load_bin::<f32>(&self.pivot_file, file_offset_data[0])?;
+ let full_pivot_data = data;
+ if pivot_num != *num_centers || pivot_dim != *dim {
+ let error_message = format!("Error reading pq_pivots file {}. file_num_centers = {}, file_dim = {} but expecting {} centers in {} dimensions.", &self.pivot_file, pivot_num, pivot_dim, num_centers, dim);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, centroid_dim, nc) = load_bin::<f32>(&self.pivot_file, file_offset_data[1])?;
+ let centroid = data;
+ if centroid_dim != *dim || nc != 1 {
+ let error_message = format!("Error reading pq_pivots file {}. file_dim = {}, file_cols = {} but expecting {} entries in 1 dimension.", &self.pivot_file, centroid_dim, nc, dim);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+
+ let (data, chunk_offset_number, nc) =
+ load_bin::<u32>(&self.pivot_file, file_offset_data[2])?;
+ let chunk_offsets = convert_types_u32_usize(&data, chunk_offset_number, nc);
+ if chunk_offset_number != *num_pq_chunks + 1 || nc != 1 {
+ let error_message = format!("Error reading pq_pivots file at chunk offsets; file has nr={}, nc={} but expecting nr={} and nc=1.", chunk_offset_number, nc, num_pq_chunks + 1);
+ return Err(ANNError::log_pq_error(error_message));
+ }
+ Ok((full_pivot_data, centroid, chunk_offsets))
+ }
+
+ pub fn read_pq_data_metadata(&mut self) -> std::io::Result<(usize, usize)> {
+ let npts_i32 = self.pq_data_file_reader.read_i32::<LittleEndian>()?;
+ let dim_i32 = self.pq_data_file_reader.read_i32::<LittleEndian>()?;
+ let num_points = npts_i32 as usize;
+ let dim = dim_i32 as usize;
+ Ok((num_points, dim))
+ }
+
+ pub fn read_pq_block_data<T: Copy>(
+ &mut self,
+ cur_block_size: usize,
+ dim: usize,
+ ) -> std::io::Result<Vec<T>> {
+ let mut buf = vec![0u8; cur_block_size * dim * std::mem::size_of::<T>()];
+ self.pq_data_file_reader.read_exact(&mut buf)?;
+
+ let ptr = buf.as_ptr() as *const T;
+ let block_data = unsafe { std::slice::from_raw_parts(ptr, cur_block_size * dim) };
+ Ok(block_data.to_vec())
+ }
+
+ /// streams data from the file, and samples each vector with probability p_val
+ /// and returns a matrix of size slice_size* ndims as floating point type.
+ /// the slice_size and ndims are set inside the function.
+ /// # Arguments
+ /// * `file_name` - filename where the data is
+ /// * `p_val` - possibility to sample data
+ /// * `sampled_vectors` - sampled vector chose by p_val possibility
+ /// * `slice_size` - how many sampled data return
+ /// * `dim` - each sample data dimension
+ pub fn gen_random_slice<T: Default + Copy + Into<f32>>(
+ &self,
+ mut p_val: f64,
+ ) -> ANNResult<(Vec<f32>, usize, usize)> {
+ let read_blk_size = 64 * 1024 * 1024;
+ let mut reader = CachedReader::new(&self.pq_data_file, read_blk_size)?;
+
+ let npts = reader.read_u32()? as usize;
+ let dim = reader.read_u32()? as usize;
+ let mut sampled_vectors: Vec<f32> = Vec::new();
+ let mut slice_size = 0;
+ p_val = if p_val < 1f64 { p_val } else { 1f64 };
+
+ let mut generator = rand::thread_rng();
+ let distribution = Uniform::from(0.0..1.0);
+
+ for _ in 0..npts {
+ let mut cur_vector_bytes = vec![0u8; dim * mem::size_of::<T>()];
+ reader.read(&mut cur_vector_bytes)?;
+ let random_value = distribution.sample(&mut generator);
+ if random_value < p_val {
+ let ptr = cur_vector_bytes.as_ptr() as *const T;
+ let cur_vector_t = unsafe { std::slice::from_raw_parts(ptr, dim) };
+ sampled_vectors.extend(cur_vector_t.iter().map(|&t| t.into()));
+ slice_size += 1;
+ }
+ }
+
+ Ok((sampled_vectors, slice_size, dim))
+ }
+}
+
+#[cfg(test)]
+mod pq_storage_tests {
+ use rand::Rng;
+
+ use super::*;
+ use crate::utils::gen_random_slice;
+
+ const DATA_FILE: &str = "tests/data/siftsmall_learn.bin";
+ const PQ_PIVOT_PATH: &str = "tests/data/siftsmall_learn.bin_pq_pivots.bin";
+ const PQ_COMPRESSED_PATH: &str = "tests/data/empty_pq_compressed.bin";
+
+ #[test]
+ fn new_test() {
+ let result = PQStorage::new(PQ_PIVOT_PATH, PQ_COMPRESSED_PATH, DATA_FILE);
+ assert!(result.is_ok());
+ }
+
+ #[test]
+ fn write_compressed_pivot_metadata_test() {
+ let compress_pivot_path = "write_compressed_pivot_metadata_test.bin";
+ let result = PQStorage::new(PQ_PIVOT_PATH, compress_pivot_path, DATA_FILE).unwrap();
+
+ _ = result.write_compressed_pivot_metadata(100, 20);
+ let mut result_reader = File::open(compress_pivot_path).unwrap();
+ let npts_i32 = result_reader.read_i32::<LittleEndian>().unwrap();
+ let dim_i32 = result_reader.read_i32::<LittleEndian>().unwrap();
+
+ assert_eq!(npts_i32, 100);
+ assert_eq!(dim_i32, 20);
+
+ std::fs::remove_file(compress_pivot_path).unwrap();
+ }
+
+ #[test]
+ fn write_compressed_pivot_data_test() {
+ let compress_pivot_path = "write_compressed_pivot_data_test.bin";
+ let result = PQStorage::new(PQ_PIVOT_PATH, compress_pivot_path, DATA_FILE).unwrap();
+
+ let mut rng = rand::thread_rng();
+
+ let num_centers = 256;
+ let block_size = 4;
+ let num_pq_chunks = 2;
+ let compressed_base: Vec<usize> = (0..block_size * num_pq_chunks)
+ .map(|_| rng.gen_range(0..num_centers))
+ .collect();
+ _ = result.write_compressed_pivot_data(
+ &compressed_base,
+ num_centers,
+ block_size,
+ num_pq_chunks,
+ );
+
+ let mut result_reader = File::open(compress_pivot_path).unwrap();
+ _ = result_reader.read_i32::<LittleEndian>().unwrap();
+ _ = result_reader.read_i32::<LittleEndian>().unwrap();
+ let mut buf = vec![0u8; block_size * num_pq_chunks * std::mem::size_of::<u8>()];
+ result_reader.read_exact(&mut buf).unwrap();
+
+ let ptr = buf.as_ptr() as *const u8;
+ let block_data = unsafe { std::slice::from_raw_parts(ptr, block_size * num_pq_chunks) };
+
+ for index in 0..block_data.len() {
+ assert_eq!(compressed_base[index], block_data[index] as usize);
+ }
+ std::fs::remove_file(compress_pivot_path).unwrap();
+ }
+
+ #[test]
+ fn pivot_data_exist_test() {
+ let result = PQStorage::new(PQ_PIVOT_PATH, PQ_COMPRESSED_PATH, DATA_FILE).unwrap();
+ assert!(result.pivot_data_exist());
+
+ let pivot_path = "not_exist_pivot_path.bin";
+ let result = PQStorage::new(pivot_path, PQ_COMPRESSED_PATH, DATA_FILE).unwrap();
+ assert!(!result.pivot_data_exist());
+ }
+
+ #[test]
+ fn read_pivot_metadata_test() {
+ let result = PQStorage::new(PQ_PIVOT_PATH, PQ_COMPRESSED_PATH, DATA_FILE).unwrap();
+ let (npt, dim) = result.read_pivot_metadata().unwrap();
+
+ assert_eq!(npt, 256);
+ assert_eq!(dim, 128);
+ }
+
+ #[test]
+ fn load_pivot_data_test() {
+ let result = PQStorage::new(PQ_PIVOT_PATH, PQ_COMPRESSED_PATH, DATA_FILE).unwrap();
+ let (pq_pivot_data, centroids, chunk_offsets) =
+ result.load_pivot_data(&1, &256, &128).unwrap();
+
+ assert_eq!(pq_pivot_data.len(), 256 * 128);
+ assert_eq!(centroids.len(), 128);
+ assert_eq!(chunk_offsets.len(), 2);
+ }
+
+ #[test]
+ fn read_pq_data_metadata_test() {
+ let mut result = PQStorage::new(PQ_PIVOT_PATH, PQ_COMPRESSED_PATH, DATA_FILE).unwrap();
+ let (npt, dim) = result.read_pq_data_metadata().unwrap();
+
+ assert_eq!(npt, 25000);
+ assert_eq!(dim, 128);
+ }
+
+ #[test]
+ fn gen_random_slice_test() {
+ let file_name = "gen_random_slice_test.bin";
+ //npoints=2, dim=8
+ let data: [u8; 72] = [
+ 2, 0, 0, 0, 8, 0, 0, 0, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
+ 0x40, 0x40, 0x00, 0x00, 0x80, 0x40, 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40,
+ 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x10, 0x41, 0x00, 0x00,
+ 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41, 0x00, 0x00, 0x50, 0x41,
+ 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x00, 0x80, 0x41,
+ ];
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+
+ let (sampled_vectors, slice_size, ndims) =
+ gen_random_slice::<f32>(file_name, 1f64).unwrap();
+ let mut start = 8;
+ (0..sampled_vectors.len()).for_each(|i| {
+ assert_eq!(sampled_vectors[i].to_le_bytes(), data[start..start + 4]);
+ start += 4;
+ });
+ assert_eq!(sampled_vectors.len(), 16);
+ assert_eq!(slice_size, 2);
+ assert_eq!(ndims, 8);
+
+ let (sampled_vectors, slice_size, ndims) =
+ gen_random_slice::<f32>(file_name, 0f64).unwrap();
+ assert_eq!(sampled_vectors.len(), 0);
+ assert_eq!(slice_size, 0);
+ assert_eq!(ndims, 8);
+
+ std::fs::remove_file(file_name).expect("Failed to delete file");
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/test_utils/inmem_index_initialization.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/test_utils/inmem_index_initialization.rs
new file mode 100644
index 0000000..db3b581
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/test_utils/inmem_index_initialization.rs
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use vector::Metric;
+
+use crate::index::InmemIndex;
+use crate::model::configuration::index_write_parameters::IndexWriteParametersBuilder;
+use crate::model::{IndexConfiguration};
+use crate::model::vertex::DIM_128;
+use crate::utils::{file_exists, load_metadata_from_file};
+
+use super::get_test_file_path;
+
+// f32, 128 DIM and 256 points source data
+const TEST_DATA_FILE: &str = "tests/data/siftsmall_learn_256pts.fbin";
+const NUM_POINTS_TO_LOAD: usize = 256;
+
+pub fn create_index_with_test_data() -> InmemIndex<f32, DIM_128> {
+ let index_write_parameters = IndexWriteParametersBuilder::new(50, 4).with_alpha(1.2).build();
+ let config = IndexConfiguration::new(
+ Metric::L2,
+ 128,
+ 128,
+ 256,
+ false,
+ 0,
+ false,
+ 0,
+ 1.0f32,
+ index_write_parameters);
+ let mut index: InmemIndex<f32, DIM_128> = InmemIndex::new(config).unwrap();
+
+ build_test_index(&mut index, get_test_file_path(TEST_DATA_FILE).as_str(), NUM_POINTS_TO_LOAD);
+
+ index.start = index.dataset.calculate_medoid_point_id().unwrap();
+
+ index
+}
+
+fn build_test_index(index: &mut InmemIndex<f32, DIM_128>, filename: &str, num_points_to_load: usize) {
+ if !file_exists(filename) {
+ panic!("ERROR: Data file {} does not exist.", filename);
+ }
+
+ let (file_num_points, file_dim) = load_metadata_from_file(filename).unwrap();
+ if file_num_points > index.configuration.max_points {
+ panic!(
+ "ERROR: Driver requests loading {} points and file has {} points,
+ but index can support only {} points as specified in configuration.",
+ num_points_to_load, file_num_points, index.configuration.max_points
+ );
+ }
+
+ if num_points_to_load > file_num_points {
+ panic!(
+ "ERROR: Driver requests loading {} points and file has only {} points.",
+ num_points_to_load, file_num_points
+ );
+ }
+
+ if file_dim != index.configuration.dim {
+ panic!(
+ "ERROR: Driver requests loading {} dimension, but file has {} dimension.",
+ index.configuration.dim, file_dim
+ );
+ }
+
+ index.dataset.build_from_file(filename, num_points_to_load).unwrap();
+
+ println!("Using only first {} from file.", num_points_to_load);
+
+ index.num_active_pts = num_points_to_load;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/test_utils/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/test_utils/mod.rs
new file mode 100644
index 0000000..fc8de5f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/test_utils/mod.rs
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub mod inmem_index_initialization;
+
+/// test files should be placed under tests folder
+pub fn get_test_file_path(relative_path: &str) -> String {
+ format!("{}/{}", env!("CARGO_MANIFEST_DIR"), relative_path)
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/bit_vec_extension.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/bit_vec_extension.rs
new file mode 100644
index 0000000..9571a72
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/bit_vec_extension.rs
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::cmp::Ordering;
+
+use bit_vec::BitVec;
+
+pub trait BitVecExtension {
+ fn resize(&mut self, new_len: usize, value: bool);
+}
+
+impl BitVecExtension for BitVec {
+ fn resize(&mut self, new_len: usize, value: bool) {
+ let old_len = self.len();
+ match new_len.cmp(&old_len) {
+ Ordering::Less => self.truncate(new_len),
+ Ordering::Greater => self.grow(new_len - old_len, value),
+ Ordering::Equal => {}
+ }
+ }
+}
+
+#[cfg(test)]
+mod bit_vec_extension_test {
+ use super::*;
+
+ #[test]
+ fn resize_test() {
+ let mut bitset = BitVec::new();
+
+ bitset.resize(10, false);
+ assert_eq!(bitset.len(), 10);
+ assert!(bitset.none());
+
+ bitset.resize(11, true);
+ assert_eq!(bitset.len(), 11);
+ assert!(bitset[10]);
+
+ bitset.resize(5, false);
+ assert_eq!(bitset.len(), 5);
+ assert!(bitset.none());
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/cached_reader.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/cached_reader.rs
new file mode 100644
index 0000000..1a21f1a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/cached_reader.rs
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::fs::File;
+use std::io::{Seek, Read};
+
+use crate::common::{ANNResult, ANNError};
+
+/// Sequential cached reads
+pub struct CachedReader {
+ /// File reader
+ reader: File,
+
+ /// # bytes to cache in one shot read
+ cache_size: u64,
+
+ /// Underlying buf for cache
+ cache_buf: Vec<u8>,
+
+ /// Offset into cache_buf for cur_pos
+ cur_off: u64,
+
+ /// File size
+ fsize: u64,
+}
+
+impl CachedReader {
+ pub fn new(filename: &str, cache_size: u64) -> std::io::Result<Self> {
+ let mut reader = File::open(filename)?;
+ let metadata = reader.metadata()?;
+ let fsize = metadata.len();
+
+ let cache_size = cache_size.min(fsize);
+ let mut cache_buf = vec![0; cache_size as usize];
+ reader.read_exact(&mut cache_buf)?;
+ println!("Opened: {}, size: {}, cache_size: {}", filename, fsize, cache_size);
+
+ Ok(Self {
+ reader,
+ cache_size,
+ cache_buf,
+ cur_off: 0,
+ fsize,
+ })
+ }
+
+ pub fn get_file_size(&self) -> u64 {
+ self.fsize
+ }
+
+ pub fn read(&mut self, read_buf: &mut [u8]) -> ANNResult<()> {
+ let n_bytes = read_buf.len() as u64;
+ if n_bytes <= (self.cache_size - self.cur_off) {
+ // case 1: cache contains all data
+ read_buf.copy_from_slice(&self.cache_buf[(self.cur_off as usize)..(self.cur_off as usize + n_bytes as usize)]);
+ self.cur_off += n_bytes;
+ } else {
+ // case 2: cache contains some data
+ let cached_bytes = self.cache_size - self.cur_off;
+ if n_bytes - cached_bytes > self.fsize - self.reader.stream_position()? {
+ return Err(ANNError::log_index_error(format!(
+ "Reading beyond end of file, n_bytes: {} cached_bytes: {} fsize: {} current pos: {}",
+ n_bytes, cached_bytes, self.fsize, self.reader.stream_position()?))
+ );
+ }
+
+ read_buf[..cached_bytes as usize].copy_from_slice(&self.cache_buf[self.cur_off as usize..]);
+ // go to disk and fetch more data
+ self.reader.read_exact(&mut read_buf[cached_bytes as usize..])?;
+ // reset cur off
+ self.cur_off = self.cache_size;
+
+ let size_left = self.fsize - self.reader.stream_position()?;
+ if size_left >= self.cache_size {
+ self.reader.read_exact(&mut self.cache_buf)?;
+ self.cur_off = 0;
+ }
+ // note that if size_left < cache_size, then cur_off = cache_size,
+ // so subsequent reads will all be directly from file
+ }
+ Ok(())
+ }
+
+ pub fn read_u32(&mut self) -> ANNResult<u32> {
+ let mut bytes = [0u8; 4];
+ self.read(&mut bytes)?;
+ Ok(u32::from_le_bytes(bytes))
+ }
+}
+
+#[cfg(test)]
+mod cached_reader_test {
+ use std::fs;
+
+ use super::*;
+
+ #[test]
+ fn cached_reader_works() {
+ let file_name = "cached_reader_works_test.bin";
+ //npoints=2, dim=8, 2 vectors [1.0;8] [2.0;8]
+ let data: [u8; 72] = [2, 0, 1, 2, 8, 0, 1, 3,
+ 0x00, 0x01, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x11, 0x80, 0x41];
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+
+ let mut reader = CachedReader::new(file_name, 8).unwrap();
+ assert_eq!(reader.get_file_size(), 72);
+ assert_eq!(reader.cache_size, 8);
+
+ let mut all_from_cache_buf = vec![0; 4];
+ reader.read(all_from_cache_buf.as_mut_slice()).unwrap();
+ assert_eq!(all_from_cache_buf, [2, 0, 1, 2]);
+ assert_eq!(reader.cur_off, 4);
+
+ let mut partial_from_cache_buf = vec![0; 6];
+ reader.read(partial_from_cache_buf.as_mut_slice()).unwrap();
+ assert_eq!(partial_from_cache_buf, [8, 0, 1, 3, 0x00, 0x01]);
+ assert_eq!(reader.cur_off, 0);
+
+ let mut over_cache_size_buf = vec![0; 60];
+ reader.read(over_cache_size_buf.as_mut_slice()).unwrap();
+ assert_eq!(
+ over_cache_size_buf,
+ [0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x11]
+ );
+
+ let mut remaining_less_than_cache_size_buf = vec![0; 2];
+ reader.read(remaining_less_than_cache_size_buf.as_mut_slice()).unwrap();
+ assert_eq!(remaining_less_than_cache_size_buf, [0x80, 0x41]);
+ assert_eq!(reader.cur_off, reader.cache_size);
+
+ fs::remove_file(file_name).expect("Failed to delete file");
+ }
+
+ #[test]
+ #[should_panic(expected = "n_bytes: 73 cached_bytes: 8 fsize: 72 current pos: 8")]
+ fn failed_for_reading_beyond_end_of_file() {
+ let file_name = "failed_for_reading_beyond_end_of_file_test.bin";
+ //npoints=2, dim=8, 2 vectors [1.0;8] [2.0;8]
+ let data: [u8; 72] = [2, 0, 1, 2, 8, 0, 1, 3,
+ 0x00, 0x01, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x11, 0x80, 0x41];
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+
+ let mut reader = CachedReader::new(file_name, 8).unwrap();
+ fs::remove_file(file_name).expect("Failed to delete file");
+
+ let mut over_size_buf = vec![0; 73];
+ reader.read(over_size_buf.as_mut_slice()).unwrap();
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/cached_writer.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/cached_writer.rs
new file mode 100644
index 0000000..d3929be
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/cached_writer.rs
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::io::{Write, Seek, SeekFrom};
+use std::fs::{OpenOptions, File};
+use std::path::Path;
+
+pub struct CachedWriter {
+ /// File writer
+ writer: File,
+
+ /// # bytes to cache for one shot write
+ cache_size: u64,
+
+ /// Underlying buf for cache
+ cache_buf: Vec<u8>,
+
+ /// Offset into cache_buf for cur_pos
+ cur_off: u64,
+
+ /// File size
+ fsize: u64,
+}
+
+impl CachedWriter {
+ pub fn new(filename: &str, cache_size: u64) -> std::io::Result<Self> {
+ let writer = OpenOptions::new()
+ .write(true)
+ .create(true)
+ .open(Path::new(filename))?;
+
+ if cache_size == 0 {
+ return Err(std::io::Error::new(std::io::ErrorKind::Other, "Cache size must be greater than 0"));
+ }
+
+ println!("Opened: {}, cache_size: {}", filename, cache_size);
+ Ok(Self {
+ writer,
+ cache_size,
+ cache_buf: vec![0; cache_size as usize],
+ cur_off: 0,
+ fsize: 0,
+ })
+ }
+
+ pub fn flush(&mut self) -> std::io::Result<()> {
+ // dump any remaining data in memory
+ if self.cur_off > 0 {
+ self.flush_cache()?;
+ }
+
+ self.writer.flush()?;
+ println!("Finished writing {}B", self.fsize);
+ Ok(())
+ }
+
+ pub fn get_file_size(&self) -> u64 {
+ self.fsize
+ }
+
+ /// Writes n_bytes from write_buf to the underlying cache
+ pub fn write(&mut self, write_buf: &[u8]) -> std::io::Result<()> {
+ let n_bytes = write_buf.len() as u64;
+ if n_bytes <= (self.cache_size - self.cur_off) {
+ // case 1: cache can take all data
+ self.cache_buf[(self.cur_off as usize)..((self.cur_off + n_bytes) as usize)].copy_from_slice(&write_buf[..n_bytes as usize]);
+ self.cur_off += n_bytes;
+ } else {
+ // case 2: cache cant take all data
+ // go to disk and write existing cache data
+ self.writer.write_all(&self.cache_buf[..self.cur_off as usize])?;
+ self.fsize += self.cur_off;
+ // write the new data to disk
+ self.writer.write_all(write_buf)?;
+ self.fsize += n_bytes;
+ // clear cache data and reset cur_off
+ self.cache_buf.fill(0);
+ self.cur_off = 0;
+ }
+ Ok(())
+ }
+
+ pub fn reset(&mut self) -> std::io::Result<()> {
+ self.flush_cache()?;
+ self.writer.seek(SeekFrom::Start(0))?;
+ Ok(())
+ }
+
+ fn flush_cache(&mut self) -> std::io::Result<()> {
+ self.writer.write_all(&self.cache_buf[..self.cur_off as usize])?;
+ self.fsize += self.cur_off;
+ self.cache_buf.fill(0);
+ self.cur_off = 0;
+ Ok(())
+ }
+}
+
+impl Drop for CachedWriter {
+ fn drop(&mut self) {
+ let _ = self.flush();
+ }
+}
+
+#[cfg(test)]
+mod cached_writer_test {
+ use std::fs;
+
+ use super::*;
+
+ #[test]
+ fn cached_writer_works() {
+ let file_name = "cached_writer_works_test.bin";
+ //npoints=2, dim=8, 2 vectors [1.0;8] [2.0;8]
+ let data: [u8; 72] = [2, 0, 1, 2, 8, 0, 1, 3,
+ 0x00, 0x01, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x11, 0x80, 0x41];
+
+ let mut writer = CachedWriter::new(file_name, 8).unwrap();
+ assert_eq!(writer.get_file_size(), 0);
+ assert_eq!(writer.cache_size, 8);
+ assert_eq!(writer.get_file_size(), 0);
+
+ let cache_all_buf = &data[0..4];
+ writer.write(cache_all_buf).unwrap();
+ assert_eq!(&writer.cache_buf[..4], cache_all_buf);
+ assert_eq!(&writer.cache_buf[4..], vec![0; 4]);
+ assert_eq!(writer.cur_off, 4);
+ assert_eq!(writer.get_file_size(), 0);
+
+ let write_all_buf = &data[4..10];
+ writer.write(write_all_buf).unwrap();
+ assert_eq!(writer.cache_buf, vec![0; 8]);
+ assert_eq!(writer.cur_off, 0);
+ assert_eq!(writer.get_file_size(), 10);
+
+ fs::remove_file(file_name).expect("Failed to delete file");
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/file_util.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/file_util.rs
new file mode 100644
index 0000000..f187d01
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/file_util.rs
@@ -0,0 +1,377 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! File operations
+
+use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
+use std::{mem, io};
+use std::fs::{self, File, OpenOptions};
+use std::io::{Read, BufReader, Write, Seek, SeekFrom};
+use std::path::Path;
+
+use crate::model::data_store::DatasetDto;
+
+/// Read metadata of data file.
+pub fn load_metadata_from_file(file_name: &str) -> std::io::Result<(usize, usize)> {
+ let file = File::open(file_name)?;
+ let mut reader = BufReader::new(file);
+
+ let npoints = reader.read_i32::<LittleEndian>()? as usize;
+ let ndims = reader.read_i32::<LittleEndian>()? as usize;
+
+ Ok((npoints, ndims))
+}
+
+/// Read the deleted vertex ids from file.
+pub fn load_ids_to_delete_from_file(file_name: &str) -> std::io::Result<(usize, Vec<u32>)> {
+ // The first 4 bytes are the number of vector ids.
+ // The rest of the file are the vector ids in the format of usize.
+ // The vector ids are sorted in ascending order.
+ let mut file = File::open(file_name)?;
+ let num_ids = file.read_u32::<LittleEndian>()? as usize;
+
+ let mut ids = Vec::with_capacity(num_ids);
+ for _ in 0..num_ids {
+ let id = file.read_u32::<LittleEndian>()?;
+ ids.push(id);
+ }
+
+ Ok((num_ids, ids))
+}
+
+/// Copy data from file
+/// # Arguments
+/// * `bin_file` - filename where the data is
+/// * `data` - destination dataset dto to which the data is copied
+/// * `pts_offset` - offset of points. data will be loaded after this point in dataset
+/// * `npts` - number of points read from bin_file
+/// * `dim` - point dimension read from bin_file
+/// * `rounded_dim` - rounded dimension (padding zero if it's > dim)
+/// # Return
+/// * `npts` - number of points read from bin_file
+/// * `dim` - point dimension read from bin_file
+pub fn copy_aligned_data_from_file<T: Default + Copy>(
+ bin_file: &str,
+ dataset_dto: DatasetDto<T>,
+ pts_offset: usize,
+) -> std::io::Result<(usize, usize)> {
+ let mut reader = File::open(bin_file)?;
+
+ let npts = reader.read_i32::<LittleEndian>()? as usize;
+ let dim = reader.read_i32::<LittleEndian>()? as usize;
+ let rounded_dim = dataset_dto.rounded_dim;
+ let offset = pts_offset * rounded_dim;
+
+ for i in 0..npts {
+ let data_slice = &mut dataset_dto.data[offset + i * rounded_dim..offset + i * rounded_dim + dim];
+ let mut buf = vec![0u8; dim * mem::size_of::<T>()];
+ reader.read_exact(&mut buf)?;
+
+ let ptr = buf.as_ptr() as *const T;
+ let temp_slice = unsafe { std::slice::from_raw_parts(ptr, dim) };
+ data_slice.copy_from_slice(temp_slice);
+
+ (i * rounded_dim + dim..i * rounded_dim + rounded_dim).for_each(|j| {
+ dataset_dto.data[j] = T::default();
+ });
+ }
+
+ Ok((npts, dim))
+}
+
+/// Open a file to write
+/// # Arguments
+/// * `writer` - mutable File reference
+/// * `file_name` - file name
+#[inline]
+pub fn open_file_to_write(file_name: &str) -> std::io::Result<File> {
+ OpenOptions::new()
+ .write(true)
+ .create(true)
+ .open(Path::new(file_name))
+}
+
+/// Delete a file
+/// # Arguments
+/// * `file_name` - file name
+pub fn delete_file(file_name: &str) -> std::io::Result<()> {
+ if file_exists(file_name) {
+ fs::remove_file(file_name)?;
+ }
+
+ Ok(())
+}
+
+/// Check whether file exists or not
+pub fn file_exists(filename: &str) -> bool {
+ std::path::Path::new(filename).exists()
+}
+
+/// Save data to file
+/// # Arguments
+/// * `filename` - filename where the data is
+/// * `data` - information data
+/// * `npts` - number of points
+/// * `ndims` - point dimension
+/// * `aligned_dim` - aligned dimension
+/// * `offset` - data offset in file
+pub fn save_data_in_base_dimensions<T: Default + Copy>(
+ filename: &str,
+ data: &mut [T],
+ npts: usize,
+ ndims: usize,
+ aligned_dim: usize,
+ offset: usize,
+) -> std::io::Result<usize> {
+ let mut writer = open_file_to_write(filename)?;
+ let npts_i32 = npts as i32;
+ let ndims_i32 = ndims as i32;
+ let bytes_written = 2 * std::mem::size_of::<u32>() + npts * ndims * (std::mem::size_of::<T>());
+
+ writer.seek(std::io::SeekFrom::Start(offset as u64))?;
+ writer.write_all(&npts_i32.to_le_bytes())?;
+ writer.write_all(&ndims_i32.to_le_bytes())?;
+ let data_ptr = data.as_ptr() as *const u8;
+ for i in 0..npts {
+ let middle_offset = i * aligned_dim * std::mem::size_of::<T>();
+ let middle_slice = unsafe { std::slice::from_raw_parts(data_ptr.add(middle_offset), ndims * std::mem::size_of::<T>()) };
+ writer.write_all(middle_slice)?;
+ }
+ writer.flush()?;
+ Ok(bytes_written)
+}
+
+/// Read data file
+/// # Arguments
+/// * `bin_file` - filename where the data is
+/// * `file_offset` - data offset in file
+/// * `data` - information data
+/// * `npts` - number of points
+/// * `ndims` - point dimension
+pub fn load_bin<T: Copy>(
+ bin_file: &str,
+ file_offset: usize) -> std::io::Result<(Vec<T>, usize, usize)>
+{
+ let mut reader = File::open(bin_file)?;
+ reader.seek(std::io::SeekFrom::Start(file_offset as u64))?;
+ let npts = reader.read_i32::<LittleEndian>()? as usize;
+ let dim = reader.read_i32::<LittleEndian>()? as usize;
+
+ let size = npts * dim * std::mem::size_of::<T>();
+ let mut buf = vec![0u8; size];
+ reader.read_exact(&mut buf)?;
+
+ let ptr = buf.as_ptr() as *const T;
+ let data = unsafe { std::slice::from_raw_parts(ptr, npts * dim)};
+
+ Ok((data.to_vec(), npts, dim))
+}
+
+/// Get file size
+pub fn get_file_size(filename: &str) -> io::Result<u64> {
+ let reader = File::open(filename)?;
+ let metadata = reader.metadata()?;
+ Ok(metadata.len())
+}
+
+macro_rules! save_bin {
+ ($name:ident, $t:ty, $write_func:ident) => {
+ /// Write data into file
+ pub fn $name(filename: &str, data: &[$t], num_pts: usize, dims: usize, offset: usize) -> std::io::Result<usize> {
+ let mut writer = open_file_to_write(filename)?;
+
+ println!("Writing bin: {}", filename);
+ writer.seek(SeekFrom::Start(offset as u64))?;
+ let num_pts_i32 = num_pts as i32;
+ let dims_i32 = dims as i32;
+ let bytes_written = num_pts * dims * mem::size_of::<$t>() + 2 * mem::size_of::<u32>();
+
+ writer.write_i32::<LittleEndian>(num_pts_i32)?;
+ writer.write_i32::<LittleEndian>(dims_i32)?;
+ println!("bin: #pts = {}, #dims = {}, size = {}B", num_pts, dims, bytes_written);
+
+ for item in data.iter() {
+ writer.$write_func::<LittleEndian>(*item)?;
+ }
+
+ writer.flush()?;
+
+ println!("Finished writing bin.");
+ Ok(bytes_written)
+ }
+ };
+}
+
+save_bin!(save_bin_f32, f32, write_f32);
+save_bin!(save_bin_u64, u64, write_u64);
+save_bin!(save_bin_u32, u32, write_u32);
+
+#[cfg(test)]
+mod file_util_test {
+ use crate::model::data_store::InmemDataset;
+ use std::fs;
+ use super::*;
+
+ pub const DIM_8: usize = 8;
+
+ #[test]
+ fn load_metadata_test() {
+ let file_name = "test_load_metadata_test.bin";
+ let data = [200, 0, 0, 0, 128, 0, 0, 0]; // 200 and 128 in little endian bytes
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+ match load_metadata_from_file(file_name) {
+ Ok((npoints, ndims)) => {
+ assert!(npoints == 200);
+ assert!(ndims == 128);
+ },
+ Err(_e) => {},
+ }
+ fs::remove_file(file_name).expect("Failed to delete file");
+ }
+
+ #[test]
+ fn load_data_test() {
+ let file_name = "test_load_data_test.bin";
+ //npoints=2, dim=8, 2 vectors [1.0;8] [2.0;8]
+ let data: [u8; 72] = [2, 0, 0, 0, 8, 0, 0, 0,
+ 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x00, 0x80, 0x41];
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+
+ let mut dataset = InmemDataset::<f32, DIM_8>::new(2, 1f32).unwrap();
+
+ match copy_aligned_data_from_file(file_name, dataset.into_dto(), 0) {
+ Ok((num_points, dim)) => {
+ fs::remove_file(file_name).expect("Failed to delete file");
+ assert!(num_points == 2);
+ assert!(dim == 8);
+ assert!(dataset.data.len() == 16);
+
+ let first_vertex = dataset.get_vertex(0).unwrap();
+ let second_vertex = dataset.get_vertex(1).unwrap();
+
+ assert!(*first_vertex.vector() == [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
+ assert!(*second_vertex.vector() == [9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0]);
+ },
+ Err(e) => {
+ fs::remove_file(file_name).expect("Failed to delete file");
+ panic!("{}", e)
+ },
+ }
+ }
+
+ #[test]
+ fn open_file_to_write_test() {
+ let file_name = "test_open_file_to_write_test.bin";
+ let mut writer = File::create(file_name).unwrap();
+ let data = [200, 0, 0, 0, 128, 0, 0, 0];
+ writer.write(&data).expect("Failed to write sample file");
+
+ let _ = open_file_to_write(file_name);
+
+ fs::remove_file(file_name).expect("Failed to delete file");
+ }
+
+ #[test]
+ fn delete_file_test() {
+ let file_name = "test_delete_file_test.bin";
+ let mut file = File::create(file_name).unwrap();
+ writeln!(file, "test delete file").unwrap();
+
+ let result = delete_file(file_name);
+
+ assert!(result.is_ok());
+ assert!(fs::metadata(file_name).is_err());
+ }
+
+ #[test]
+ fn save_data_in_base_dimensions_test() {
+ //npoints=2, dim=8
+ let mut data: [u8; 72] = [2, 0, 0, 0, 8, 0, 0, 0,
+ 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x00, 0x80, 0x41];
+ let num_points = 2;
+ let dim = DIM_8;
+ let data_file = "save_data_in_base_dimensions_test.data";
+ match save_data_in_base_dimensions(data_file, &mut data, num_points, dim, DIM_8, 0) {
+ Ok(num) => {
+ assert!(file_exists(data_file));
+ assert_eq!(num, 2 * std::mem::size_of::<u32>() + num_points * dim * std::mem::size_of::<u8>());
+ fs::remove_file(data_file).expect("Failed to delete file");
+ },
+ Err(e) => {
+ fs::remove_file(data_file).expect("Failed to delete file");
+ panic!("{}", e)
+ }
+ }
+ }
+
+ #[test]
+ fn save_bin_test() {
+ let filename = "save_bin_test";
+ let data = vec![0u64, 1u64, 2u64];
+ let num_pts = data.len();
+ let dims = 1;
+ let bytes_written = save_bin_u64(filename, &data, num_pts, dims, 0).unwrap();
+ assert_eq!(bytes_written, 32);
+
+ let mut file = File::open(filename).unwrap();
+ let mut buffer = vec![];
+
+ let npts_read = file.read_i32::<LittleEndian>().unwrap() as usize;
+ let dims_read = file.read_i32::<LittleEndian>().unwrap() as usize;
+
+ file.read_to_end(&mut buffer).unwrap();
+ let data_read: Vec<u64> = buffer
+ .chunks_exact(8)
+ .map(|b| u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
+ .collect();
+
+ std::fs::remove_file(filename).unwrap();
+
+ assert_eq!(num_pts, npts_read);
+ assert_eq!(dims, dims_read);
+ assert_eq!(data, data_read);
+ }
+
+ #[test]
+ fn load_bin_test() {
+ let file_name = "load_bin_test";
+ let data = vec![0u64, 1u64, 2u64];
+ let num_pts = data.len();
+ let dims = 1;
+ let bytes_written = save_bin_u64(file_name, &data, num_pts, dims, 0).unwrap();
+ assert_eq!(bytes_written, 32);
+
+ let (load_data, load_num_pts, load_dims) = load_bin::<u64>(file_name, 0).unwrap();
+ assert_eq!(load_num_pts, num_pts);
+ assert_eq!(load_dims, dims);
+ assert_eq!(load_data, data);
+ std::fs::remove_file(file_name).unwrap();
+ }
+
+ #[test]
+ fn load_bin_offset_test() {
+ let offset:usize = 32;
+ let file_name = "load_bin_offset_test";
+ let data = vec![0u64, 1u64, 2u64];
+ let num_pts = data.len();
+ let dims = 1;
+ let bytes_written = save_bin_u64(file_name, &data, num_pts, dims, offset).unwrap();
+ assert_eq!(bytes_written, 32);
+
+ let (load_data, load_num_pts, load_dims) = load_bin::<u64>(file_name, offset).unwrap();
+ assert_eq!(load_num_pts, num_pts);
+ assert_eq!(load_dims, dims);
+ assert_eq!(load_data, data);
+ std::fs::remove_file(file_name).unwrap();
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/hashset_u32.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/hashset_u32.rs
new file mode 100644
index 0000000..15db687
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/hashset_u32.rs
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use hashbrown::HashSet;
+use std::{hash::BuildHasherDefault, ops::{Deref, DerefMut}};
+use fxhash::FxHasher;
+
+lazy_static::lazy_static! {
+ /// Singleton hasher.
+ static ref HASHER: BuildHasherDefault<FxHasher> = {
+ BuildHasherDefault::<FxHasher>::default()
+ };
+}
+
+pub struct HashSetForU32 {
+ hashset: HashSet::<u32, BuildHasherDefault<FxHasher>>,
+}
+
+impl HashSetForU32 {
+ pub fn with_capacity(capacity: usize) -> HashSetForU32 {
+ let hashset = HashSet::<u32, BuildHasherDefault<FxHasher>>::with_capacity_and_hasher(capacity, HASHER.clone());
+ HashSetForU32 {
+ hashset
+ }
+ }
+}
+
+impl Deref for HashSetForU32 {
+ type Target = HashSet::<u32, BuildHasherDefault<FxHasher>>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.hashset
+ }
+}
+
+impl DerefMut for HashSetForU32 {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.hashset
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/kmeans.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/kmeans.rs
new file mode 100644
index 0000000..d1edffa
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/kmeans.rs
@@ -0,0 +1,430 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Aligned allocator
+
+use rand::{distributions::Uniform, prelude::Distribution, thread_rng};
+use rayon::prelude::*;
+use std::cmp::min;
+
+use crate::common::ANNResult;
+use crate::utils::math_util::{calc_distance, compute_closest_centers, compute_vecs_l2sq};
+
+/// Run Lloyds one iteration
+/// Given data in row-major num_points * dim, and centers in row-major
+/// num_centers * dim and squared lengths of ata points, output the closest
+/// center to each data point, update centers, and also return inverted index.
+/// If closest_centers == NULL, will allocate memory and return.
+/// Similarly, if closest_docs == NULL, will allocate memory and return.
+#[allow(clippy::too_many_arguments)]
+fn lloyds_iter(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ centers: &mut [f32],
+ num_centers: usize,
+ docs_l2sq: &[f32],
+ mut closest_docs: &mut Vec<Vec<usize>>,
+ closest_center: &mut [u32],
+) -> ANNResult<f32> {
+ let compute_residual = true;
+
+ closest_docs.iter_mut().for_each(|doc| doc.clear());
+
+ compute_closest_centers(
+ data,
+ num_points,
+ dim,
+ centers,
+ num_centers,
+ 1,
+ closest_center,
+ Some(&mut closest_docs),
+ Some(docs_l2sq),
+ )?;
+
+ centers.fill(0.0);
+
+ centers
+ .par_chunks_mut(dim)
+ .enumerate()
+ .for_each(|(c, center)| {
+ let mut cluster_sum = vec![0.0; dim];
+ for &doc_index in &closest_docs[c] {
+ let current = &data[doc_index * dim..(doc_index + 1) * dim];
+ for (j, current_val) in current.iter().enumerate() {
+ cluster_sum[j] += *current_val as f64;
+ }
+ }
+ if !closest_docs[c].is_empty() {
+ for (i, sum_val) in cluster_sum.iter().enumerate() {
+ center[i] = (*sum_val / closest_docs[c].len() as f64) as f32;
+ }
+ }
+ });
+
+ let mut residual = 0.0;
+ if compute_residual {
+ let buf_pad: usize = 32;
+ let chunk_size: usize = 2 * 8192;
+ let nchunks =
+ num_points / chunk_size + (if num_points % chunk_size == 0 { 0 } else { 1 } as usize);
+
+ let mut residuals: Vec<f32> = vec![0.0; nchunks * buf_pad];
+
+ residuals
+ .par_iter_mut()
+ .enumerate()
+ .for_each(|(chunk, res)| {
+ for d in (chunk * chunk_size)..min(num_points, (chunk + 1) * chunk_size) {
+ *res += calc_distance(
+ &data[d * dim..(d + 1) * dim],
+ &centers[closest_center[d] as usize * dim..],
+ dim,
+ );
+ }
+ });
+
+ for chunk in 0..nchunks {
+ residual += residuals[chunk * buf_pad];
+ }
+ }
+
+ Ok(residual)
+}
+
+/// Run Lloyds until max_reps or stopping criterion
+/// If you pass NULL for closest_docs and closest_center, it will NOT return
+/// the results, else it will assume appropriate allocation as closest_docs =
+/// new vec<usize> [num_centers], and closest_center = new size_t[num_points]
+/// Final centers are output in centers as row-major num_centers * dim.
+fn run_lloyds(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ centers: &mut [f32],
+ num_centers: usize,
+ max_reps: usize,
+) -> ANNResult<(Vec<Vec<usize>>, Vec<u32>, f32)> {
+ let mut residual = f32::MAX;
+
+ let mut closest_docs = vec![Vec::new(); num_centers];
+ let mut closest_center = vec![0; num_points];
+
+ let mut docs_l2sq = vec![0.0; num_points];
+ compute_vecs_l2sq(&mut docs_l2sq, data, num_points, dim);
+
+ let mut old_residual;
+
+ for i in 0..max_reps {
+ old_residual = residual;
+
+ residual = lloyds_iter(
+ data,
+ num_points,
+ dim,
+ centers,
+ num_centers,
+ &docs_l2sq,
+ &mut closest_docs,
+ &mut closest_center,
+ )?;
+
+ if (i != 0 && (old_residual - residual) / residual < 0.00001) || (residual < f32::EPSILON) {
+ println!(
+ "Residuals unchanged: {} becomes {}. Early termination.",
+ old_residual, residual
+ );
+ break;
+ }
+ }
+
+ Ok((closest_docs, closest_center, residual))
+}
+
+/// Assume memory allocated for pivot_data as new float[num_centers * dim]
+/// and select randomly num_centers points as pivots
+fn selecting_pivots(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ pivot_data: &mut [f32],
+ num_centers: usize,
+) {
+ let mut picked = Vec::new();
+ let mut rng = thread_rng();
+ let distribution = Uniform::from(0..num_points);
+
+ for j in 0..num_centers {
+ let mut tmp_pivot = distribution.sample(&mut rng);
+ while picked.contains(&tmp_pivot) {
+ tmp_pivot = distribution.sample(&mut rng);
+ }
+ picked.push(tmp_pivot);
+ let data_offset = tmp_pivot * dim;
+ let pivot_offset = j * dim;
+ pivot_data[pivot_offset..pivot_offset + dim]
+ .copy_from_slice(&data[data_offset..data_offset + dim]);
+ }
+}
+
+/// Select pivots in k-means++ algorithm
+/// Points that are farther away from the already chosen centroids
+/// have a higher probability of being selected as the next centroid.
+/// The k-means++ algorithm helps avoid poor initial centroid
+/// placement that can result in suboptimal clustering.
+fn k_meanspp_selecting_pivots(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ pivot_data: &mut [f32],
+ num_centers: usize,
+) {
+ if num_points > (1 << 23) {
+ println!("ERROR: n_pts {} currently not supported for k-means++, maximum is 8388608. Falling back to random pivot selection.", num_points);
+ selecting_pivots(data, num_points, dim, pivot_data, num_centers);
+ return;
+ }
+
+ let mut picked: Vec<usize> = Vec::new();
+ let mut rng = thread_rng();
+ let real_distribution = Uniform::from(0.0..1.0);
+ let int_distribution = Uniform::from(0..num_points);
+
+ let init_id = int_distribution.sample(&mut rng);
+ let mut num_picked = 1;
+
+ picked.push(init_id);
+ let init_data_offset = init_id * dim;
+ pivot_data[0..dim].copy_from_slice(&data[init_data_offset..init_data_offset + dim]);
+
+ let mut dist = vec![0.0; num_points];
+
+ dist.par_iter_mut().enumerate().for_each(|(i, dist_i)| {
+ *dist_i = calc_distance(
+ &data[i * dim..(i + 1) * dim],
+ &data[init_id * dim..(init_id + 1) * dim],
+ dim,
+ );
+ });
+
+ let mut dart_val: f64;
+ let mut tmp_pivot = 0;
+ let mut sum_flag = false;
+
+ while num_picked < num_centers {
+ dart_val = real_distribution.sample(&mut rng);
+
+ let mut sum: f64 = 0.0;
+ for item in dist.iter().take(num_points) {
+ sum += *item as f64;
+ }
+ if sum == 0.0 {
+ sum_flag = true;
+ }
+
+ dart_val *= sum;
+
+ let mut prefix_sum: f64 = 0.0;
+ for (i, pivot) in dist.iter().enumerate().take(num_points) {
+ tmp_pivot = i;
+ if dart_val >= prefix_sum && dart_val < (prefix_sum + *pivot as f64) {
+ break;
+ }
+
+ prefix_sum += *pivot as f64;
+ }
+
+ if picked.contains(&tmp_pivot) && !sum_flag {
+ continue;
+ }
+
+ picked.push(tmp_pivot);
+ let pivot_offset = num_picked * dim;
+ let data_offset = tmp_pivot * dim;
+ pivot_data[pivot_offset..pivot_offset + dim]
+ .copy_from_slice(&data[data_offset..data_offset + dim]);
+
+ dist.par_iter_mut().enumerate().for_each(|(i, dist_i)| {
+ *dist_i = (*dist_i).min(calc_distance(
+ &data[i * dim..(i + 1) * dim],
+ &data[tmp_pivot * dim..(tmp_pivot + 1) * dim],
+ dim,
+ ));
+ });
+
+ num_picked += 1;
+ }
+}
+
+/// k-means algorithm interface
+pub fn k_means_clustering(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ centers: &mut [f32],
+ num_centers: usize,
+ max_reps: usize,
+) -> ANNResult<(Vec<Vec<usize>>, Vec<u32>, f32)> {
+ k_meanspp_selecting_pivots(data, num_points, dim, centers, num_centers);
+ let (closest_docs, closest_center, residual) =
+ run_lloyds(data, num_points, dim, centers, num_centers, max_reps)?;
+ Ok((closest_docs, closest_center, residual))
+}
+
+#[cfg(test)]
+mod kmeans_test {
+ use super::*;
+ use approx::assert_relative_eq;
+ use rand::Rng;
+
+ #[test]
+ fn lloyds_iter_test() {
+ let dim = 2;
+ let num_points = 10;
+ let num_centers = 3;
+
+ let data: Vec<f32> = (1..=num_points * dim).map(|x| x as f32).collect();
+ let mut centers = [1.0, 2.0, 7.0, 8.0, 19.0, 20.0];
+
+ let mut closest_docs: Vec<Vec<usize>> = vec![vec![]; num_centers];
+ let mut closest_center: Vec<u32> = vec![0; num_points];
+ let docs_l2sq: Vec<f32> = data
+ .chunks(dim)
+ .map(|chunk| chunk.iter().map(|val| val.powi(2)).sum())
+ .collect();
+
+ let residual = lloyds_iter(
+ &data,
+ num_points,
+ dim,
+ &mut centers,
+ num_centers,
+ &docs_l2sq,
+ &mut closest_docs,
+ &mut closest_center,
+ )
+ .unwrap();
+
+ let expected_centers: [f32; 6] = [2.0, 3.0, 9.0, 10.0, 17.0, 18.0];
+ let expected_closest_docs: Vec<Vec<usize>> =
+ vec![vec![0, 1], vec![2, 3, 4, 5, 6], vec![7, 8, 9]];
+ let expected_closest_center: [u32; 10] = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2];
+ let expected_residual: f32 = 100.0;
+
+ // sort data for assert
+ centers.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ for inner_vec in &mut closest_docs {
+ inner_vec.sort();
+ }
+ closest_center.sort_by(|a, b| a.partial_cmp(b).unwrap());
+
+ assert_eq!(centers, expected_centers);
+ assert_eq!(closest_docs, expected_closest_docs);
+ assert_eq!(closest_center, expected_closest_center);
+ assert_relative_eq!(residual, expected_residual, epsilon = 1.0e-6_f32);
+ }
+
+ #[test]
+ fn run_lloyds_test() {
+ let dim = 2;
+ let num_points = 10;
+ let num_centers = 3;
+ let max_reps = 5;
+
+ let data: Vec<f32> = (1..=num_points * dim).map(|x| x as f32).collect();
+ let mut centers = [1.0, 2.0, 7.0, 8.0, 19.0, 20.0];
+
+ let (mut closest_docs, mut closest_center, residual) =
+ run_lloyds(&data, num_points, dim, &mut centers, num_centers, max_reps).unwrap();
+
+ let expected_centers: [f32; 6] = [3.0, 4.0, 10.0, 11.0, 17.0, 18.0];
+ let expected_closest_docs: Vec<Vec<usize>> =
+ vec![vec![0, 1, 2], vec![3, 4, 5, 6], vec![7, 8, 9]];
+ let expected_closest_center: [u32; 10] = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2];
+ let expected_residual: f32 = 72.0;
+
+ // sort data for assert
+ centers.sort_by(|a, b| a.partial_cmp(b).unwrap());
+ for inner_vec in &mut closest_docs {
+ inner_vec.sort();
+ }
+ closest_center.sort_by(|a, b| a.partial_cmp(b).unwrap());
+
+ assert_eq!(centers, expected_centers);
+ assert_eq!(closest_docs, expected_closest_docs);
+ assert_eq!(closest_center, expected_closest_center);
+ assert_relative_eq!(residual, expected_residual, epsilon = 1.0e-6_f32);
+ }
+
+ #[test]
+ fn selecting_pivots_test() {
+ let dim = 2;
+ let num_points = 10;
+ let num_centers = 3;
+
+ // Generate some random data points
+ let mut rng = rand::thread_rng();
+ let data: Vec<f32> = (0..num_points * dim).map(|_| rng.gen()).collect();
+
+ let mut pivot_data = vec![0.0; num_centers * dim];
+
+ selecting_pivots(&data, num_points, dim, &mut pivot_data, num_centers);
+
+ // Verify that each pivot point corresponds to a point in the data
+ for i in 0..num_centers {
+ let pivot_offset = i * dim;
+ let pivot = &pivot_data[pivot_offset..(pivot_offset + dim)];
+
+ // Make sure the pivot is found in the data
+ let mut found = false;
+ for j in 0..num_points {
+ let data_offset = j * dim;
+ let point = &data[data_offset..(data_offset + dim)];
+
+ if pivot == point {
+ found = true;
+ break;
+ }
+ }
+ assert!(found, "Pivot not found in data");
+ }
+ }
+
+ #[test]
+ fn k_meanspp_selecting_pivots_test() {
+ let dim = 2;
+ let num_points = 10;
+ let num_centers = 3;
+
+ // Generate some random data points
+ let mut rng = rand::thread_rng();
+ let data: Vec<f32> = (0..num_points * dim).map(|_| rng.gen()).collect();
+
+ let mut pivot_data = vec![0.0; num_centers * dim];
+
+ k_meanspp_selecting_pivots(&data, num_points, dim, &mut pivot_data, num_centers);
+
+ // Verify that each pivot point corresponds to a point in the data
+ for i in 0..num_centers {
+ let pivot_offset = i * dim;
+ let pivot = &pivot_data[pivot_offset..pivot_offset + dim];
+
+ // Make sure the pivot is found in the data
+ let mut found = false;
+ for j in 0..num_points {
+ let data_offset = j * dim;
+ let point = &data[data_offset..data_offset + dim];
+
+ if pivot == point {
+ found = true;
+ break;
+ }
+ }
+ assert!(found, "Pivot not found in data");
+ }
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/math_util.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/math_util.rs
new file mode 100644
index 0000000..ef30c76
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/math_util.rs
@@ -0,0 +1,481 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Aligned allocator
+
+extern crate cblas;
+extern crate openblas_src;
+
+use cblas::{sgemm, snrm2, Layout, Transpose};
+use rayon::prelude::*;
+use std::{
+ cmp::{min, Ordering},
+ collections::BinaryHeap,
+ sync::{Arc, Mutex},
+};
+
+use crate::common::{ANNError, ANNResult};
+
+struct PivotContainer {
+ piv_id: usize,
+ piv_dist: f32,
+}
+
+impl PartialOrd for PivotContainer {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ other.piv_dist.partial_cmp(&self.piv_dist)
+ }
+}
+
+impl Ord for PivotContainer {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ // Treat NaN as less than all other values.
+ // piv_dist should never be NaN.
+ self.partial_cmp(other).unwrap_or(Ordering::Less)
+ }
+}
+
+impl PartialEq for PivotContainer {
+ fn eq(&self, other: &Self) -> bool {
+ self.piv_dist == other.piv_dist
+ }
+}
+
+impl Eq for PivotContainer {}
+
+/// Calculate the Euclidean distance between two vectors
+pub fn calc_distance(vec_1: &[f32], vec_2: &[f32], dim: usize) -> f32 {
+ let mut dist = 0.0;
+ for j in 0..dim {
+ let diff = vec_1[j] - vec_2[j];
+ dist += diff * diff;
+ }
+ dist
+}
+
+/// Compute L2-squared norms of data stored in row-major num_points * dim,
+/// need to be pre-allocated
+pub fn compute_vecs_l2sq(vecs_l2sq: &mut [f32], data: &[f32], num_points: usize, dim: usize) {
+ assert_eq!(vecs_l2sq.len(), num_points);
+
+ vecs_l2sq
+ .par_iter_mut()
+ .enumerate()
+ .for_each(|(n_iter, vec_l2sq)| {
+ let slice = &data[n_iter * dim..(n_iter + 1) * dim];
+ let norm = unsafe { snrm2(dim as i32, slice, 1) };
+ *vec_l2sq = norm * norm;
+ });
+}
+
+/// Calculate k closest centers to data of num_points * dim (row-major)
+/// Centers is num_centers * dim (row-major)
+/// data_l2sq has pre-computed squared norms of data
+/// centers_l2sq has pre-computed squared norms of centers
+/// Pre-allocated center_index will contain id of nearest center
+/// Pre-allocated dist_matrix should be num_points * num_centers and contain squared distances
+/// Default value of k is 1
+/// Ideally used only by compute_closest_centers
+#[allow(clippy::too_many_arguments)]
+pub fn compute_closest_centers_in_block(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ centers: &[f32],
+ num_centers: usize,
+ docs_l2sq: &[f32],
+ centers_l2sq: &[f32],
+ center_index: &mut [u32],
+ dist_matrix: &mut [f32],
+ k: usize,
+) -> ANNResult<()> {
+ if k > num_centers {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: k ({}) > num_centers({})",
+ k, num_centers
+ )));
+ }
+
+ let ones_a: Vec<f32> = vec![1.0; num_centers];
+ let ones_b: Vec<f32> = vec![1.0; num_points];
+
+ unsafe {
+ sgemm(
+ Layout::RowMajor,
+ Transpose::None,
+ Transpose::Ordinary,
+ num_points as i32,
+ num_centers as i32,
+ 1,
+ 1.0,
+ docs_l2sq,
+ 1,
+ &ones_a,
+ 1,
+ 0.0,
+ dist_matrix,
+ num_centers as i32,
+ );
+ }
+
+ unsafe {
+ sgemm(
+ Layout::RowMajor,
+ Transpose::None,
+ Transpose::Ordinary,
+ num_points as i32,
+ num_centers as i32,
+ 1,
+ 1.0,
+ &ones_b,
+ 1,
+ centers_l2sq,
+ 1,
+ 1.0,
+ dist_matrix,
+ num_centers as i32,
+ );
+ }
+
+ unsafe {
+ sgemm(
+ Layout::RowMajor,
+ Transpose::None,
+ Transpose::Ordinary,
+ num_points as i32,
+ num_centers as i32,
+ dim as i32,
+ -2.0,
+ data,
+ dim as i32,
+ centers,
+ dim as i32,
+ 1.0,
+ dist_matrix,
+ num_centers as i32,
+ );
+ }
+
+ if k == 1 {
+ center_index
+ .par_iter_mut()
+ .enumerate()
+ .for_each(|(i, center_idx)| {
+ let mut min = f32::MAX;
+ let current = &dist_matrix[i * num_centers..(i + 1) * num_centers];
+ let mut min_idx = 0;
+ for (j, &distance) in current.iter().enumerate() {
+ if distance < min {
+ min = distance;
+ min_idx = j;
+ }
+ }
+ *center_idx = min_idx as u32;
+ });
+ } else {
+ center_index
+ .par_chunks_mut(k)
+ .enumerate()
+ .for_each(|(i, center_chunk)| {
+ let current = &dist_matrix[i * num_centers..(i + 1) * num_centers];
+ let mut top_k_queue = BinaryHeap::new();
+ for (j, &distance) in current.iter().enumerate() {
+ let this_piv = PivotContainer {
+ piv_id: j,
+ piv_dist: distance,
+ };
+ if top_k_queue.len() < k {
+ top_k_queue.push(this_piv);
+ } else {
+ // Safe unwrap, top_k_queue is not empty
+ #[allow(clippy::unwrap_used)]
+ let mut top = top_k_queue.peek_mut().unwrap();
+ if this_piv.piv_dist < top.piv_dist {
+ *top = this_piv;
+ }
+ }
+ }
+ for (_j, center_idx) in center_chunk.iter_mut().enumerate() {
+ if let Some(this_piv) = top_k_queue.pop() {
+ *center_idx = this_piv.piv_id as u32;
+ } else {
+ break;
+ }
+ }
+ });
+ }
+
+ Ok(())
+}
+
+/// Given data in num_points * new_dim row major
+/// Pivots stored in full_pivot_data as num_centers * new_dim row major
+/// Calculate the k closest pivot for each point and store it in vector
+/// closest_centers_ivf (row major, num_points*k) (which needs to be allocated
+/// outside) Additionally, if inverted index is not null (and pre-allocated),
+/// it will return inverted index for each center, assuming each of the inverted
+/// indices is an empty vector. Additionally, if pts_norms_squared is not null,
+/// then it will assume that point norms are pre-computed and use those values
+#[allow(clippy::too_many_arguments)]
+pub fn compute_closest_centers(
+ data: &[f32],
+ num_points: usize,
+ dim: usize,
+ pivot_data: &[f32],
+ num_centers: usize,
+ k: usize,
+ closest_centers_ivf: &mut [u32],
+ mut inverted_index: Option<&mut Vec<Vec<usize>>>,
+ pts_norms_squared: Option<&[f32]>,
+) -> ANNResult<()> {
+ if k > num_centers {
+ return Err(ANNError::log_index_error(format!(
+ "ERROR: k ({}) > num_centers({})",
+ k, num_centers
+ )));
+ }
+
+ let _is_norm_given_for_pts = pts_norms_squared.is_some();
+
+ let mut pivs_norms_squared = vec![0.0; num_centers];
+
+ let mut pts_norms_squared = if let Some(pts_norms) = pts_norms_squared {
+ pts_norms.to_vec()
+ } else {
+ let mut norms_squared = vec![0.0; num_points];
+ compute_vecs_l2sq(&mut norms_squared, data, num_points, dim);
+ norms_squared
+ };
+
+ compute_vecs_l2sq(&mut pivs_norms_squared, pivot_data, num_centers, dim);
+
+ let par_block_size = num_points;
+ let n_blocks = if num_points % par_block_size == 0 {
+ num_points / par_block_size
+ } else {
+ num_points / par_block_size + 1
+ };
+
+ let mut closest_centers = vec![0u32; par_block_size * k];
+ let mut distance_matrix = vec![0.0; num_centers * par_block_size];
+
+ for cur_blk in 0..n_blocks {
+ let data_cur_blk = &data[cur_blk * par_block_size * dim..];
+ let num_pts_blk = min(par_block_size, num_points - cur_blk * par_block_size);
+ let pts_norms_blk = &mut pts_norms_squared[cur_blk * par_block_size..];
+
+ compute_closest_centers_in_block(
+ data_cur_blk,
+ num_pts_blk,
+ dim,
+ pivot_data,
+ num_centers,
+ pts_norms_blk,
+ &pivs_norms_squared,
+ &mut closest_centers,
+ &mut distance_matrix,
+ k,
+ )?;
+
+ closest_centers_ivf.clone_from_slice(&closest_centers);
+
+ if let Some(inverted_index_inner) = inverted_index.as_mut() {
+ let inverted_index_arc = Arc::new(Mutex::new(inverted_index_inner));
+
+ (0..num_points)
+ .into_par_iter()
+ .try_for_each(|j| -> ANNResult<()> {
+ let this_center_id = closest_centers[j] as usize;
+ let mut guard = inverted_index_arc.lock().map_err(|err| {
+ ANNError::log_index_error(format!(
+ "PoisonError: Lock poisoned when acquiring inverted_index_arc, err={}",
+ err
+ ))
+ })?;
+ guard[this_center_id].push(j);
+
+ Ok(())
+ })?;
+ }
+ }
+
+ Ok(())
+}
+
+/// If to_subtract is true, will subtract nearest center from each row.
+/// Else will add.
+/// Output will be in data_load itself.
+/// Nearest centers need to be provided in closest_centers.
+pub fn process_residuals(
+ data_load: &mut [f32],
+ num_points: usize,
+ dim: usize,
+ cur_pivot_data: &[f32],
+ num_centers: usize,
+ closest_centers: &[u32],
+ to_subtract: bool,
+) {
+ println!(
+ "Processing residuals of {} points in {} dimensions using {} centers",
+ num_points, dim, num_centers
+ );
+
+ data_load
+ .par_chunks_mut(dim)
+ .enumerate()
+ .for_each(|(n_iter, chunk)| {
+ let cur_pivot_index = closest_centers[n_iter] as usize * dim;
+ for d_iter in 0..dim {
+ if to_subtract {
+ chunk[d_iter] -= cur_pivot_data[cur_pivot_index + d_iter];
+ } else {
+ chunk[d_iter] += cur_pivot_data[cur_pivot_index + d_iter];
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod math_util_test {
+ use super::*;
+ use approx::assert_abs_diff_eq;
+
+ #[test]
+ fn calc_distance_test() {
+ let vec1 = vec![1.0, 2.0, 3.0];
+ let vec2 = vec![4.0, 5.0, 6.0];
+ let dim = vec1.len();
+
+ let dist = calc_distance(&vec1, &vec2, dim);
+
+ let expected = 27.0;
+
+ assert_eq!(dist, expected);
+ }
+
+ #[test]
+ fn compute_vecs_l2sq_test() {
+ let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
+ let num_points = 2;
+ let dim = 3;
+ let mut vecs_l2sq = vec![0.0; num_points];
+
+ compute_vecs_l2sq(&mut vecs_l2sq, &data, num_points, dim);
+
+ let expected = vec![14.0, 77.0];
+
+ assert_eq!(vecs_l2sq.len(), num_points);
+ assert_abs_diff_eq!(vecs_l2sq[0], expected[0], epsilon = 1e-6);
+ assert_abs_diff_eq!(vecs_l2sq[1], expected[1], epsilon = 1e-6);
+ }
+
+ #[test]
+ fn compute_closest_centers_in_block_test() {
+ let num_points = 10;
+ let dim = 5;
+ let num_centers = 3;
+ let data = vec![
+ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
+ 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0,
+ 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0,
+ 45.0, 46.0, 47.0, 48.0, 49.0, 50.0,
+ ];
+ let centers = vec![
+ 1.0, 2.0, 3.0, 4.0, 5.0, 21.0, 22.0, 23.0, 24.0, 25.0, 31.0, 32.0, 33.0, 34.0, 35.0,
+ ];
+ let mut docs_l2sq = vec![0.0; num_points];
+ compute_vecs_l2sq(&mut docs_l2sq, &data, num_points, dim);
+ let mut centers_l2sq = vec![0.0; num_centers];
+ compute_vecs_l2sq(&mut centers_l2sq, &centers, num_centers, dim);
+ let mut center_index = vec![0; num_points];
+ let mut dist_matrix = vec![0.0; num_points * num_centers];
+ let k = 1;
+
+ compute_closest_centers_in_block(
+ &data,
+ num_points,
+ dim,
+ &centers,
+ num_centers,
+ &docs_l2sq,
+ &centers_l2sq,
+ &mut center_index,
+ &mut dist_matrix,
+ k,
+ )
+ .unwrap();
+
+ assert_eq!(center_index.len(), num_points);
+ let expected_center_index = vec![0, 0, 0, 1, 1, 1, 2, 2, 2, 2];
+ assert_abs_diff_eq!(*center_index, expected_center_index);
+
+ assert_eq!(dist_matrix.len(), num_points * num_centers);
+ let expected_dist_matrix = vec![
+ 0.0, 2000.0, 4500.0, 125.0, 1125.0, 3125.0, 500.0, 500.0, 2000.0, 1125.0, 125.0,
+ 1125.0, 2000.0, 0.0, 500.0, 3125.0, 125.0, 125.0, 4500.0, 500.0, 0.0, 6125.0, 1125.0,
+ 125.0, 8000.0, 2000.0, 500.0, 10125.0, 3125.0, 1125.0,
+ ];
+ assert_abs_diff_eq!(*dist_matrix, expected_dist_matrix, epsilon = 1e-2);
+ }
+
+ #[test]
+ fn test_compute_closest_centers() {
+ let num_points = 4;
+ let dim = 3;
+ let num_centers = 2;
+ let mut data = vec![
+ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
+ ];
+ let pivot_data = vec![1.0, 2.0, 3.0, 10.0, 11.0, 12.0];
+ let k = 1;
+
+ let mut closest_centers_ivf = vec![0u32; num_points * k];
+ let mut inverted_index: Vec<Vec<usize>> = vec![vec![], vec![]];
+
+ compute_closest_centers(
+ &data,
+ num_points,
+ dim,
+ &pivot_data,
+ num_centers,
+ k,
+ &mut closest_centers_ivf,
+ Some(&mut inverted_index),
+ None,
+ )
+ .unwrap();
+
+ assert_eq!(closest_centers_ivf, vec![0, 0, 1, 1]);
+
+ for vec in inverted_index.iter_mut() {
+ vec.sort_unstable();
+ }
+ assert_eq!(inverted_index, vec![vec![0, 1], vec![2, 3]]);
+ }
+
+ #[test]
+ fn process_residuals_test() {
+ let mut data_load = vec![1.0, 2.0, 3.0, 4.0];
+ let num_points = 2;
+ let dim = 2;
+ let cur_pivot_data = vec![0.5, 1.5, 2.5, 3.5];
+ let num_centers = 2;
+ let closest_centers = vec![0, 1];
+ let to_subtract = true;
+
+ process_residuals(
+ &mut data_load,
+ num_points,
+ dim,
+ &cur_pivot_data,
+ num_centers,
+ &closest_centers,
+ to_subtract,
+ );
+
+ assert_eq!(data_load, vec![0.5, 0.5, 0.5, 0.5]);
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/mod.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/mod.rs
new file mode 100644
index 0000000..df174f8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/mod.rs
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+pub mod file_util;
+pub use file_util::*;
+
+#[allow(clippy::module_inception)]
+pub mod utils;
+pub use utils::*;
+
+pub mod bit_vec_extension;
+pub use bit_vec_extension::*;
+
+pub mod rayon_util;
+pub use rayon_util::*;
+
+pub mod timer;
+pub use timer::*;
+
+pub mod cached_reader;
+pub use cached_reader::*;
+
+pub mod cached_writer;
+pub use cached_writer::*;
+
+pub mod partition;
+pub use partition::*;
+
+pub mod math_util;
+pub use math_util::*;
+
+pub mod kmeans;
+pub use kmeans::*;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/partition.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/partition.rs
new file mode 100644
index 0000000..dbe6862
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/partition.rs
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::mem;
+use std::{fs::File, path::Path};
+use std::io::{Write, Seek, SeekFrom};
+use rand::distributions::{Distribution, Uniform};
+
+use crate::common::ANNResult;
+
+use super::CachedReader;
+
+/// streams data from the file, and samples each vector with probability p_val
+/// and returns a matrix of size slice_size* ndims as floating point type.
+/// the slice_size and ndims are set inside the function.
+/// # Arguments
+/// * `file_name` - filename where the data is
+/// * `p_val` - possibility to sample data
+/// * `sampled_vectors` - sampled vector chose by p_val possibility
+/// * `slice_size` - how many sampled data return
+/// * `dim` - each sample data dimension
+pub fn gen_random_slice<T: Default + Copy + Into<f32>>(data_file: &str, mut p_val: f64) -> ANNResult<(Vec<f32>, usize, usize)> {
+ let read_blk_size = 64 * 1024 * 1024;
+ let mut reader = CachedReader::new(data_file, read_blk_size)?;
+
+ let npts = reader.read_u32()? as usize;
+ let dim = reader.read_u32()? as usize;
+ let mut sampled_vectors: Vec<f32> = Vec::new();
+ let mut slice_size = 0;
+ p_val = if p_val < 1f64 { p_val } else { 1f64 };
+
+ let mut generator = rand::thread_rng();
+ let distribution = Uniform::from(0.0..1.0);
+
+ for _ in 0..npts {
+ let mut cur_vector_bytes = vec![0u8; dim * mem::size_of::<T>()];
+ reader.read(&mut cur_vector_bytes)?;
+ let random_value = distribution.sample(&mut generator);
+ if random_value < p_val {
+ let ptr = cur_vector_bytes.as_ptr() as *const T;
+ let cur_vector_t = unsafe { std::slice::from_raw_parts(ptr, dim) };
+ sampled_vectors.extend(cur_vector_t.iter().map(|&t| t.into()));
+ slice_size += 1;
+ }
+ }
+
+ Ok((sampled_vectors, slice_size, dim))
+}
+
+/// Generate random sample data and write into output_file
+pub fn gen_sample_data<T>(data_file: &str, output_file: &str, sampling_rate: f64) -> ANNResult<()> {
+ let read_blk_size = 64 * 1024 * 1024;
+ let mut reader = CachedReader::new(data_file, read_blk_size)?;
+
+ let sample_data_path = format!("{}_data.bin", output_file);
+ let sample_ids_path = format!("{}_ids.bin", output_file);
+ let mut sample_data_writer = File::create(Path::new(&sample_data_path))?;
+ let mut sample_id_writer = File::create(Path::new(&sample_ids_path))?;
+
+ let mut num_sampled_pts = 0u32;
+ let one_const = 1u32;
+ let mut generator = rand::thread_rng();
+ let distribution = Uniform::from(0.0..1.0);
+
+ let npts_u32 = reader.read_u32()?;
+ let dim_u32 = reader.read_u32()?;
+ let dim = dim_u32 as usize;
+ sample_data_writer.write_all(&num_sampled_pts.to_le_bytes())?;
+ sample_data_writer.write_all(&dim_u32.to_le_bytes())?;
+ sample_id_writer.write_all(&num_sampled_pts.to_le_bytes())?;
+ sample_id_writer.write_all(&one_const.to_le_bytes())?;
+
+ for id in 0..npts_u32 {
+ let mut cur_row_bytes = vec![0u8; dim * mem::size_of::<T>()];
+ reader.read(&mut cur_row_bytes)?;
+ let random_value = distribution.sample(&mut generator);
+ if random_value < sampling_rate {
+ sample_data_writer.write_all(&cur_row_bytes)?;
+ sample_id_writer.write_all(&id.to_le_bytes())?;
+ num_sampled_pts += 1;
+ }
+ }
+
+ sample_data_writer.seek(SeekFrom::Start(0))?;
+ sample_data_writer.write_all(&num_sampled_pts.to_le_bytes())?;
+ sample_id_writer.seek(SeekFrom::Start(0))?;
+ sample_id_writer.write_all(&num_sampled_pts.to_le_bytes())?;
+ println!("Wrote {} points to sample file: {}", num_sampled_pts, sample_data_path);
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod partition_test {
+ use std::{fs, io::Read};
+ use byteorder::{ReadBytesExt, LittleEndian};
+
+ use crate::utils::file_exists;
+
+ use super::*;
+
+ #[test]
+ fn gen_sample_data_test() {
+ let file_name = "gen_sample_data_test.bin";
+ //npoints=2, dim=8
+ let data: [u8; 72] = [2, 0, 0, 0, 8, 0, 0, 0,
+ 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x80, 0x40,
+ 0x00, 0x00, 0xa0, 0x40, 0x00, 0x00, 0xc0, 0x40, 0x00, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x41,
+ 0x00, 0x00, 0x10, 0x41, 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0x30, 0x41, 0x00, 0x00, 0x40, 0x41,
+ 0x00, 0x00, 0x50, 0x41, 0x00, 0x00, 0x60, 0x41, 0x00, 0x00, 0x70, 0x41, 0x00, 0x00, 0x80, 0x41];
+ std::fs::write(file_name, data).expect("Failed to write sample file");
+
+ let sample_file_prefix = file_name.to_string() + "_sample";
+ gen_sample_data::<f32>(file_name, sample_file_prefix.as_str(), 1f64).unwrap();
+
+ let sample_data_path = format!("{}_data.bin", sample_file_prefix);
+ let sample_ids_path = format!("{}_ids.bin", sample_file_prefix);
+ assert!(file_exists(sample_data_path.as_str()));
+ assert!(file_exists(sample_ids_path.as_str()));
+
+ let mut data_file_reader = File::open(sample_data_path.as_str()).unwrap();
+ let mut ids_file_reader = File::open(sample_ids_path.as_str()).unwrap();
+
+ let mut num_sampled_pts = data_file_reader.read_u32::<LittleEndian>().unwrap();
+ assert_eq!(num_sampled_pts, 2);
+ num_sampled_pts = ids_file_reader.read_u32::<LittleEndian>().unwrap();
+ assert_eq!(num_sampled_pts, 2);
+
+ let dim = data_file_reader.read_u32::<LittleEndian>().unwrap() as usize;
+ assert_eq!(dim, 8);
+ assert_eq!(ids_file_reader.read_u32::<LittleEndian>().unwrap(), 1);
+
+ let mut start = 8;
+ for i in 0..num_sampled_pts {
+ let mut data_bytes = vec![0u8; dim * 4];
+ data_file_reader.read_exact(&mut data_bytes).unwrap();
+ assert_eq!(data_bytes, data[start..start + dim * 4]);
+
+ let id = ids_file_reader.read_u32::<LittleEndian>().unwrap();
+ assert_eq!(id, i);
+
+ start += dim * 4;
+ }
+
+ fs::remove_file(file_name).expect("Failed to delete file");
+ fs::remove_file(sample_data_path.as_str()).expect("Failed to delete file");
+ fs::remove_file(sample_ids_path.as_str()).expect("Failed to delete file");
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/rayon_util.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/rayon_util.rs
new file mode 100644
index 0000000..f8174ee
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/rayon_util.rs
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::ops::Range;
+use rayon::prelude::{IntoParallelIterator, ParallelIterator};
+
+use crate::common::ANNResult;
+
+/// based on thread_num, execute the task in parallel using Rayon or serial
+#[inline]
+pub fn execute_with_rayon<F>(range: Range<usize>, num_threads: u32, f: F) -> ANNResult<()>
+where F: Fn(usize) -> ANNResult<()> + Sync + Send + Copy
+{
+ if num_threads == 1 {
+ for i in range {
+ f(i)?;
+ }
+ Ok(())
+ } else {
+ range.into_par_iter().try_for_each(f)
+ }
+}
+
+/// set the thread count of Rayon, otherwise it will use threads as many as logical cores.
+#[inline]
+pub fn set_rayon_num_threads(num_threads: u32) {
+ std::env::set_var(
+ "RAYON_NUM_THREADS",
+ num_threads.to_string(),
+ );
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/timer.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/timer.rs
new file mode 100644
index 0000000..2f4b38b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/timer.rs
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use platform::*;
+use std::time::{Duration, Instant};
+
+#[derive(Clone)]
+pub struct Timer {
+ check_point: Instant,
+ pid: Option<usize>,
+ cycles: Option<u64>,
+}
+
+impl Default for Timer {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Timer {
+ pub fn new() -> Timer {
+ let pid = get_process_handle();
+ let cycles = get_process_cycle_time(pid);
+ Timer {
+ check_point: Instant::now(),
+ pid,
+ cycles,
+ }
+ }
+
+ pub fn reset(&mut self) {
+ self.check_point = Instant::now();
+ self.cycles = get_process_cycle_time(self.pid);
+ }
+
+ pub fn elapsed(&self) -> Duration {
+ Instant::now().duration_since(self.check_point)
+ }
+
+ pub fn elapsed_seconds(&self) -> f64 {
+ self.elapsed().as_secs_f64()
+ }
+
+ pub fn elapsed_gcycles(&self) -> f32 {
+ let cur_cycles = get_process_cycle_time(self.pid);
+ if let (Some(cur_cycles), Some(cycles)) = (cur_cycles, self.cycles) {
+ let spent_cycles =
+ ((cur_cycles - cycles) as f64 * 1.0f64) / (1024 * 1024 * 1024) as f64;
+ return spent_cycles as f32;
+ }
+
+ 0.0
+ }
+
+ pub fn elapsed_seconds_for_step(&self, step: &str) -> String {
+ format!(
+ "Time for {}: {:.3} seconds, {:.3}B cycles",
+ step,
+ self.elapsed_seconds(),
+ self.elapsed_gcycles()
+ )
+ }
+}
+
+#[cfg(test)]
+mod timer_tests {
+ use super::*;
+ use std::{thread, time};
+
+ #[test]
+ fn test_new() {
+ let timer = Timer::new();
+ assert!(timer.check_point.elapsed().as_secs() < 1);
+ if cfg!(windows) {
+ assert!(timer.pid.is_some());
+ assert!(timer.cycles.is_some());
+ }
+ else {
+ assert!(timer.pid.is_none());
+ assert!(timer.cycles.is_none());
+ }
+ }
+
+ #[test]
+ fn test_reset() {
+ let mut timer = Timer::new();
+ thread::sleep(time::Duration::from_millis(100));
+ timer.reset();
+ assert!(timer.check_point.elapsed().as_millis() < 10);
+ }
+
+ #[test]
+ fn test_elapsed() {
+ let timer = Timer::new();
+ thread::sleep(time::Duration::from_millis(100));
+ assert!(timer.elapsed().as_millis() > 100);
+ assert!(timer.elapsed_seconds() > 0.1);
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/utils.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/utils.rs
new file mode 100644
index 0000000..2e80676
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/src/utils/utils.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::sync::Mutex;
+use num_traits::Num;
+
+/// Non recursive mutex
+pub type NonRecursiveMutex = Mutex<()>;
+
+/// Round up X to the nearest multiple of Y
+#[inline]
+pub fn round_up<T>(x: T, y: T) -> T
+where T : Num + Copy
+{
+ div_round_up(x, y) * y
+}
+
+/// Rounded-up division
+#[inline]
+pub fn div_round_up<T>(x: T, y: T) -> T
+where T : Num + Copy
+{
+ (x / y) + if x % y != T::zero() {T::one()} else {T::zero()}
+}
+
+/// Round down X to the nearest multiple of Y
+#[inline]
+pub fn round_down<T>(x: T, y: T) -> T
+where T : Num + Copy
+{
+ (x / y) * y
+}
+
+/// Is aligned
+#[inline]
+pub fn is_aligned<T>(x: T, y: T) -> bool
+where T : Num + Copy
+{
+ x % y == T::zero()
+}
+
+#[inline]
+pub fn is_512_aligned(x: u64) -> bool {
+ is_aligned(x, 512)
+}
+
+#[inline]
+pub fn is_4096_aligned(x: u64) -> bool {
+ is_aligned(x, 4096)
+}
+
+/// all metadata of individual sub-component files is written in first 4KB for unified files
+pub const METADATA_SIZE: usize = 4096;
+
+pub const BUFFER_SIZE_FOR_CACHED_IO: usize = 1024 * 1048576;
+
+pub const PBSTR: &str = "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||";
+
+pub const PBWIDTH: usize = 60;
+
+macro_rules! convert_types {
+ ($name:ident, $intput_type:ty, $output_type:ty) => {
+ /// Write data into file
+ pub fn $name(srcmat: &[$intput_type], npts: usize, dim: usize) -> Vec<$output_type> {
+ let mut destmat: Vec<$output_type> = Vec::new();
+ for i in 0..npts {
+ for j in 0..dim {
+ destmat.push(srcmat[i * dim + j] as $output_type);
+ }
+ }
+ destmat
+ }
+ };
+}
+convert_types!(convert_types_usize_u8, usize, u8);
+convert_types!(convert_types_usize_u32, usize, u32);
+convert_types!(convert_types_usize_u64, usize, u64);
+convert_types!(convert_types_u64_usize, u64, usize);
+convert_types!(convert_types_u32_usize, u32, usize);
+
+#[cfg(test)]
+mod file_util_test {
+ use super::*;
+ use std::any::type_name;
+
+ #[test]
+ fn round_up_test() {
+ assert_eq!(round_up(252, 8), 256);
+ assert_eq!(round_up(256, 8), 256);
+ }
+
+ #[test]
+ fn div_round_up_test() {
+ assert_eq!(div_round_up(252, 8), 32);
+ assert_eq!(div_round_up(256, 8), 32);
+ }
+
+ #[test]
+ fn round_down_test() {
+ assert_eq!(round_down(252, 8), 248);
+ assert_eq!(round_down(256, 8), 256);
+ }
+
+ #[test]
+ fn is_aligned_test() {
+ assert!(!is_aligned(252, 8));
+ assert!(is_aligned(256, 8));
+ }
+
+ #[test]
+ fn is_512_aligned_test() {
+ assert!(!is_512_aligned(520));
+ assert!(is_512_aligned(512));
+ }
+
+ #[test]
+ fn is_4096_aligned_test() {
+ assert!(!is_4096_aligned(4090));
+ assert!(is_4096_aligned(4096));
+ }
+
+ #[test]
+ fn convert_types_test() {
+ let data = vec![0u64, 1u64, 2u64];
+ let output = convert_types_u64_usize(&data, 3, 1);
+ assert_eq!(output.len(), 3);
+ assert_eq!(type_of(output[0]), "usize");
+ assert_eq!(output[0], 0usize);
+
+ let data = vec![0usize, 1usize, 2usize];
+ let output = convert_types_usize_u8(&data, 3, 1);
+ assert_eq!(output.len(), 3);
+ assert_eq!(type_of(output[0]), "u8");
+ assert_eq!(output[0], 0u8);
+
+ let data = vec![0usize, 1usize, 2usize];
+ let output = convert_types_usize_u64(&data, 3, 1);
+ assert_eq!(output.len(), 3);
+ assert_eq!(type_of(output[0]), "u64");
+ assert_eq!(output[0], 0u64);
+
+ let data = vec![0u32, 1u32, 2u32];
+ let output = convert_types_u32_usize(&data, 3, 1);
+ assert_eq!(output.len(), 3);
+ assert_eq!(type_of(output[0]), "usize");
+ assert_eq!(output[0],0usize);
+ }
+
+ fn type_of<T>(_: T) -> &'static str {
+ type_name::<T>()
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/siftsmall_learn_256pts.fbin b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/siftsmall_learn_256pts.fbin
new file mode 100644
index 0000000..357a9db
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/siftsmall_learn_256pts.fbin differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/siftsmall_learn_256pts_2.fbin b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/siftsmall_learn_256pts_2.fbin
new file mode 100644
index 0000000..9528e4b
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/siftsmall_learn_256pts_2.fbin differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_1+2_R4_L50_A1.2 b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_1+2_R4_L50_A1.2
new file mode 100644
index 0000000..9c803c3
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_1+2_R4_L50_A1.2 differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_1+2_saturated_R4_L50_A1.2 b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_1+2_saturated_R4_L50_A1.2
new file mode 100644
index 0000000..a9dac10
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_1+2_saturated_R4_L50_A1.2 differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2 b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2
new file mode 100644
index 0000000..8170090
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2 differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2.data b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2.data
new file mode 100644
index 0000000..357a9db
Binary files /dev/null and b/packages/leann-backend-diskann/third_party/DiskANN/rust/diskann/tests/data/truth_index_siftsmall_learn_256pts_R4_L50_A1.2.data differ
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/Cargo.toml
new file mode 100644
index 0000000..e750d95
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/Cargo.toml
@@ -0,0 +1,29 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "logger"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+lazy_static = "1.4.0"
+log="0.4.17"
+once_cell = "1.17.1"
+prost = "0.11.9"
+prost-types = "0.11.9"
+thiserror = "1.0.40"
+win_etw_macros="0.1.8"
+win_etw_provider="0.1.8"
+
+[build-dependencies]
+prost-build = "0.11.9"
+
+[[example]]
+name="trace_example"
+path= "src/examples/trace_example.rs"
+
+[target."cfg(target_os=\"windows\")".build-dependencies.vcpkg]
+version = "0.2"
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/build.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/build.rs
new file mode 100644
index 0000000..76058f7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/build.rs
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::env;
+
+extern crate prost_build;
+
+fn main() {
+ let protopkg = vcpkg::find_package("protobuf").unwrap();
+ let protobuf_path = protopkg.link_paths[0].parent().unwrap();
+
+ let protobuf_bin_path = protobuf_path
+ .join("tools")
+ .join("protobuf")
+ .join("protoc.exe")
+ .to_str()
+ .unwrap()
+ .to_string();
+ env::set_var("PROTOC", protobuf_bin_path);
+
+ let protobuf_inc_path = protobuf_path
+ .join("include")
+ .join("google")
+ .join("protobuf")
+ .to_str()
+ .unwrap()
+ .to_string();
+ env::set_var("PROTOC_INCLUDE", protobuf_inc_path);
+
+ prost_build::compile_protos(&["src/indexlog.proto"], &["src/"]).unwrap();
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/error_logger.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/error_logger.rs
new file mode 100644
index 0000000..50069b4
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/error_logger.rs
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use crate::log_error::LogError;
+use crate::logger::indexlog::{ErrorLog, Log, LogLevel};
+use crate::message_handler::send_log;
+
+pub fn log_error(error_message: String) -> Result<(), LogError> {
+ let mut log = Log::default();
+ let error_log = ErrorLog {
+ log_level: LogLevel::Error as i32,
+ error_message,
+ };
+ log.error_log = Some(error_log);
+
+ send_log(log)
+}
+
+#[cfg(test)]
+mod error_logger_test {
+ use super::*;
+
+ #[test]
+ fn log_error_works() {
+ log_error(String::from("Error")).unwrap();
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/examples/trace_example.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/examples/trace_example.rs
new file mode 100644
index 0000000..7933a56
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/examples/trace_example.rs
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use log::{debug, info, log_enabled, warn, Level};
+use logger::trace_logger::TraceLogger;
+
+// cargo run --example trace_example
+
+fn main() {
+ static LOGGER: TraceLogger = TraceLogger {};
+ log::set_logger(&LOGGER)
+ .map(|()| log::set_max_level(log::LevelFilter::Trace))
+ .unwrap();
+
+ info!("Rust logging n = {}", 42);
+ warn!("This is too much fun!");
+ debug!("Maybe we can make this code work");
+
+ let error_is_enabled = log_enabled!(Level::Error);
+ let warn_is_enabled = log_enabled!(Level::Warn);
+ let info_is_enabled = log_enabled!(Level::Info);
+ let debug_is_enabled = log_enabled!(Level::Debug);
+ let trace_is_enabled = log_enabled!(Level::Trace);
+ println!(
+ "is_enabled? error: {:5?}, warn: {:5?}, info: {:5?}, debug: {:5?}, trace: {:5?}",
+ error_is_enabled, warn_is_enabled, info_is_enabled, debug_is_enabled, trace_is_enabled,
+ );
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/indexlog.proto b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/indexlog.proto
new file mode 100644
index 0000000..68310ae
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/indexlog.proto
@@ -0,0 +1,50 @@
+syntax = "proto3";
+
+package diskann_logger;
+
+message Log {
+ IndexConstructionLog IndexConstructionLog = 1;
+ DiskIndexConstructionLog DiskIndexConstructionLog = 2;
+ ErrorLog ErrorLog = 3;
+ TraceLog TraceLog = 100;
+}
+
+enum LogLevel {
+ UNSPECIFIED = 0;
+ Error = 1;
+ Warn = 2;
+ Info = 3;
+ Debug = 4;
+ Trace = 5;
+}
+
+message IndexConstructionLog {
+ float PercentageComplete = 1;
+ float TimeSpentInSeconds = 2;
+ float GCyclesSpent = 3;
+ LogLevel LogLevel = 4;
+}
+
+message DiskIndexConstructionLog {
+ DiskIndexConstructionCheckpoint checkpoint = 1;
+ float TimeSpentInSeconds = 2;
+ float GCyclesSpent = 3;
+ LogLevel LogLevel = 4;
+}
+
+enum DiskIndexConstructionCheckpoint {
+ None = 0;
+ PqConstruction = 1;
+ InmemIndexBuild = 2;
+ DiskLayout = 3;
+}
+
+message TraceLog {
+ string LogLine = 1;
+ LogLevel LogLevel = 2;
+}
+
+message ErrorLog {
+ string ErrorMessage = 1;
+ LogLevel LogLevel = 2;
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/lib.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/lib.rs
new file mode 100644
index 0000000..6cfe2d5
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/lib.rs
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![cfg_attr(
+ not(test),
+ warn(clippy::panic, clippy::unwrap_used, clippy::expect_used)
+)]
+
+pub mod logger {
+ pub mod indexlog {
+ include!(concat!(env!("OUT_DIR"), "/diskann_logger.rs"));
+ }
+}
+
+pub mod error_logger;
+pub mod log_error;
+pub mod message_handler;
+pub mod trace_logger;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/log_error.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/log_error.rs
new file mode 100644
index 0000000..149d094
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/log_error.rs
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::sync::mpsc::SendError;
+
+use crate::logger::indexlog::Log;
+
+#[derive(thiserror::Error, Debug, Clone)]
+pub enum LogError {
+ /// Sender failed to send message to the channel
+ #[error("IOError: {err}")]
+ SendError {
+ #[from]
+ err: SendError<Log>,
+ },
+
+ /// PoisonError which can be returned whenever a lock is acquired
+ /// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock is held
+ #[error("LockPoisonError: {err}")]
+ LockPoisonError { err: String },
+
+ /// Failed to create EtwPublisher
+ #[error("EtwProviderError: {err:?}")]
+ ETWProviderError { err: win_etw_provider::Error },
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/message_handler.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/message_handler.rs
new file mode 100644
index 0000000..37f352a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/message_handler.rs
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use crate::log_error::LogError;
+use crate::logger::indexlog::DiskIndexConstructionCheckpoint;
+use crate::logger::indexlog::Log;
+use crate::logger::indexlog::LogLevel;
+
+use std::sync::mpsc::{self, Sender};
+use std::sync::Mutex;
+use std::thread;
+
+use win_etw_macros::trace_logging_provider;
+
+trait MessagePublisher {
+ fn publish(&self, log_level: LogLevel, message: &str);
+}
+
+// ETW provider - the GUID specified here is that of the default provider for Geneva Metric Extensions
+// We are just using it as a placeholder until we have a version of OpenTelemetry exporter for Rust
+#[trace_logging_provider(guid = "edc24920-e004-40f6-a8e1-0e6e48f39d84")]
+trait EtwTraceProvider {
+ fn write(msg: &str);
+}
+
+struct EtwPublisher {
+ provider: EtwTraceProvider,
+ publish_to_stdout: bool,
+}
+
+impl EtwPublisher {
+ pub fn new() -> Result<Self, win_etw_provider::Error> {
+ let provider = EtwTraceProvider::new();
+ Ok(EtwPublisher {
+ provider,
+ publish_to_stdout: true,
+ })
+ }
+}
+
+fn log_level_to_etw(level: LogLevel) -> win_etw_provider::Level {
+ match level {
+ LogLevel::Error => win_etw_provider::Level::ERROR,
+ LogLevel::Warn => win_etw_provider::Level::WARN,
+ LogLevel::Info => win_etw_provider::Level::INFO,
+ LogLevel::Debug => win_etw_provider::Level::VERBOSE,
+ LogLevel::Trace => win_etw_provider::Level(6),
+ LogLevel::Unspecified => win_etw_provider::Level(6),
+ }
+}
+
+fn i32_to_log_level(value: i32) -> LogLevel {
+ match value {
+ 0 => LogLevel::Unspecified,
+ 1 => LogLevel::Error,
+ 2 => LogLevel::Warn,
+ 3 => LogLevel::Info,
+ 4 => LogLevel::Debug,
+ 5 => LogLevel::Trace,
+ _ => LogLevel::Unspecified,
+ }
+}
+
+impl MessagePublisher for EtwPublisher {
+ fn publish(&self, log_level: LogLevel, message: &str) {
+ let options = win_etw_provider::EventOptions {
+ level: Some(log_level_to_etw(log_level)),
+ ..Default::default()
+ };
+ self.provider.write(Some(&options), message);
+
+ if self.publish_to_stdout {
+ println!("{}", message);
+ }
+ }
+}
+
+struct MessageProcessor {
+ sender: Mutex<Sender<Log>>,
+}
+
+impl MessageProcessor {
+ pub fn start_processing() -> Self {
+ let (sender, receiver) = mpsc::channel::<Log>();
+ thread::spawn(move || -> Result<(), LogError> {
+ for message in receiver {
+ // Process the received message
+ if let Some(indexlog) = message.index_construction_log {
+ let str = format!(
+ "Time for {}% of index build completed: {:.3} seconds, {:.3}B cycles",
+ indexlog.percentage_complete,
+ indexlog.time_spent_in_seconds,
+ indexlog.g_cycles_spent
+ );
+ publish(i32_to_log_level(indexlog.log_level), &str)?;
+ }
+
+ if let Some(disk_index_log) = message.disk_index_construction_log {
+ let str = format!(
+ "Time for disk index build [Checkpoint: {:?}] completed: {:.3} seconds, {:.3}B cycles",
+ DiskIndexConstructionCheckpoint::from_i32(disk_index_log.checkpoint).unwrap_or(DiskIndexConstructionCheckpoint::None),
+ disk_index_log.time_spent_in_seconds,
+ disk_index_log.g_cycles_spent
+ );
+ publish(i32_to_log_level(disk_index_log.log_level), &str)?;
+ }
+
+ if let Some(tracelog) = message.trace_log {
+ let str = format!("{}:{}", tracelog.log_level, tracelog.log_line);
+ publish(i32_to_log_level(tracelog.log_level), &str)?;
+ }
+
+ if let Some(err) = message.error_log {
+ publish(i32_to_log_level(err.log_level), &err.error_message)?;
+ }
+ }
+
+ Ok(())
+ });
+
+ let sender = Mutex::new(sender);
+ MessageProcessor { sender }
+ }
+
+ /// Log the message.
+ fn log(&self, message: Log) -> Result<(), LogError> {
+ Ok(self
+ .sender
+ .lock()
+ .map_err(|err| LogError::LockPoisonError {
+ err: err.to_string(),
+ })?
+ .send(message)?)
+ }
+}
+
+lazy_static::lazy_static! {
+ /// Singleton logger.
+ static ref PROCESSOR: MessageProcessor = {
+
+ MessageProcessor::start_processing()
+ };
+}
+
+lazy_static::lazy_static! {
+ /// Singleton publisher.
+ static ref PUBLISHER: Result<EtwPublisher, win_etw_provider::Error> = {
+ EtwPublisher::new()
+ };
+}
+
+/// Send a message to the logging system.
+pub fn send_log(message: Log) -> Result<(), LogError> {
+ PROCESSOR.log(message)
+}
+
+fn publish(log_level: LogLevel, message: &str) -> Result<(), LogError> {
+ match *PUBLISHER {
+ Ok(ref etw_publisher) => {
+ etw_publisher.publish(log_level, message);
+ Ok(())
+ }
+ Err(ref err) => Err(LogError::ETWProviderError { err: err.clone() }),
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/trace_logger.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/trace_logger.rs
new file mode 100644
index 0000000..96ef386
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/logger/src/trace_logger.rs
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use crate::logger::indexlog::{Log, TraceLog};
+use crate::message_handler::send_log;
+
+use log;
+
+pub struct TraceLogger {}
+
+fn level_to_i32(value: log::Level) -> i32 {
+ match value {
+ log::Level::Error => 1,
+ log::Level::Warn => 2,
+ log::Level::Info => 3,
+ log::Level::Debug => 4,
+ log::Level::Trace => 5,
+ }
+}
+
+impl log::Log for TraceLogger {
+ fn enabled(&self, metadata: &log::Metadata) -> bool {
+ metadata.level() <= log::max_level()
+ }
+
+ fn log(&self, record: &log::Record) {
+ let message = record.args().to_string();
+ let metadata = record.metadata();
+ let mut log = Log::default();
+ let trace_log = TraceLog {
+ log_line: message,
+ log_level: level_to_i32(metadata.level()),
+ };
+ log.trace_log = Some(trace_log);
+ let _ = send_log(log);
+ }
+
+ fn flush(&self) {}
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/Cargo.toml
new file mode 100644
index 0000000..057f9e8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/Cargo.toml
@@ -0,0 +1,13 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "platform"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+log="0.4.18"
+winapi = { version = "0.3.9", features = ["errhandlingapi", "fileapi", "ioapiset", "handleapi", "winnt", "minwindef", "basetsd", "winerror", "winbase"] }
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/file_handle.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/file_handle.rs
new file mode 100644
index 0000000..23da879
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/file_handle.rs
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::ffi::CString;
+use std::{io, ptr};
+
+use winapi::um::fileapi::OPEN_EXISTING;
+use winapi::um::winbase::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED, FILE_FLAG_RANDOM_ACCESS};
+use winapi::um::winnt::{FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE};
+
+use winapi::{
+ shared::minwindef::DWORD,
+ um::{
+ errhandlingapi::GetLastError,
+ fileapi::CreateFileA,
+ handleapi::{CloseHandle, INVALID_HANDLE_VALUE},
+ winnt::HANDLE,
+ },
+};
+
+pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x00000001;
+
+/// `AccessMode` determines how a file can be accessed.
+/// These modes are used when creating or opening a file to decide what operations are allowed
+/// to be performed on the file.
+///
+/// # Variants
+///
+/// - `Read`: The file is opened in read-only mode.
+///
+/// - `Write`: The file is opened in write-only mode.
+///
+/// - `ReadWrite`: The file is opened for both reading and writing.
+pub enum AccessMode {
+ Read,
+ Write,
+ ReadWrite,
+}
+
+/// `ShareMode` determines how a file can be shared.
+///
+/// These modes are used when creating or opening a file to decide what operations other
+/// opening instances of the file can perform on it.
+/// # Variants
+/// - `None`: Prevents other processes from opening a file if they request delete,
+/// read, or write access.
+///
+/// - `Read`: Allows subsequent open operations on the same file to request read access.
+///
+/// - `Write`: Allows subsequent open operations on the same file file to request write access.
+///
+/// - `Delete`: Allows subsequent open operations on the same file file to request delete access.
+pub enum ShareMode {
+ None,
+ Read,
+ Write,
+ Delete,
+}
+
+/// # Windows File Handle Wrapper
+///
+/// Introduces a Rust-friendly wrapper around the native Windows `HANDLE` object, `FileHandle`.
+/// `FileHandle` provides safe creation and automatic cleanup of Windows file handles, leveraging Rust's ownership model.
+
+/// `FileHandle` struct that wraps a native Windows `HANDLE` object
+#[cfg(target_os = "windows")]
+pub struct FileHandle {
+ handle: HANDLE,
+}
+
+impl FileHandle {
+ /// Creates a new `FileHandle` by opening an existing file with the given access and shared mode.
+ ///
+ /// This function is marked unsafe because it creates a raw pointer to the filename and try to create
+ /// a Windows `HANDLE` object without checking if you have sufficient permissions.
+ ///
+ /// # Safety
+ ///
+ /// Ensure that the file specified by `file_name` is valid and the calling process has
+ /// sufficient permissions to perform the specified `access_mode` and `share_mode` operations.
+ ///
+ /// # Parameters
+ ///
+ /// - `file_name`: The name of the file.
+ /// - `access_mode`: The access mode to be used for the file.
+ /// - `share_mode`: The share mode to be used for the file
+ ///
+ /// # Errors
+ /// This function will return an error if the `file_name` is invalid or if the file cannot
+ /// be opened with the specified `access_mode` and `share_mode`.
+ pub unsafe fn new(
+ file_name: &str,
+ access_mode: AccessMode,
+ share_mode: ShareMode,
+ ) -> io::Result<Self> {
+ let file_name_c = CString::new(file_name).map_err(|_| {
+ io::Error::new(
+ io::ErrorKind::InvalidData,
+ format!("Invalid file name. {}", file_name),
+ )
+ })?;
+
+ let dw_desired_access = match access_mode {
+ AccessMode::Read => GENERIC_READ,
+ AccessMode::Write => GENERIC_WRITE,
+ AccessMode::ReadWrite => GENERIC_READ | GENERIC_WRITE,
+ };
+
+ let dw_share_mode = match share_mode {
+ ShareMode::None => 0,
+ ShareMode::Read => FILE_SHARE_READ,
+ ShareMode::Write => FILE_SHARE_WRITE,
+ ShareMode::Delete => FILE_SHARE_DELETE,
+ };
+
+ let dw_flags_and_attributes = FILE_ATTRIBUTE_READONLY
+ | FILE_FLAG_NO_BUFFERING
+ | FILE_FLAG_OVERLAPPED
+ | FILE_FLAG_RANDOM_ACCESS;
+
+ let handle = unsafe {
+ CreateFileA(
+ file_name_c.as_ptr(),
+ dw_desired_access,
+ dw_share_mode,
+ ptr::null_mut(),
+ OPEN_EXISTING,
+ dw_flags_and_attributes,
+ ptr::null_mut(),
+ )
+ };
+
+ if handle == INVALID_HANDLE_VALUE {
+ let error_code = unsafe { GetLastError() };
+ Err(io::Error::from_raw_os_error(error_code as i32))
+ } else {
+ Ok(Self { handle })
+ }
+ }
+
+ pub fn raw_handle(&self) -> HANDLE {
+ self.handle
+ }
+}
+
+impl Drop for FileHandle {
+ /// Automatically closes the `FileHandle` when it goes out of scope.
+ /// Any errors in closing the handle are logged, as `Drop` does not support returning `Result`.
+ fn drop(&mut self) {
+ let result = unsafe { CloseHandle(self.handle) };
+ if result == 0 {
+ let error_code = unsafe { GetLastError() };
+ let error = io::Error::from_raw_os_error(error_code as i32);
+
+ // Only log the error if dropping the handle fails, since Rust's Drop trait does not support returning Result types from the drop method,
+ // and panicking in the drop method is considered bad practice
+ log::warn!("Error when dropping IOCompletionPort: {:?}", error);
+ }
+ }
+}
+
+/// Returns a `FileHandle` with an `INVALID_HANDLE_VALUE`.
+impl Default for FileHandle {
+ fn default() -> Self {
+ Self {
+ handle: INVALID_HANDLE_VALUE,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs::File;
+ use std::path::Path;
+
+ #[test]
+ fn test_create_file() {
+ // Create a dummy file
+ let dummy_file_path = "dummy_file.txt";
+ {
+ let _file = File::create(dummy_file_path).expect("Failed to create dummy file.");
+ }
+
+ let path = Path::new(dummy_file_path);
+ {
+ let file_handle = unsafe {
+ FileHandle::new(path.to_str().unwrap(), AccessMode::Read, ShareMode::Read)
+ };
+
+ // Check that the file handle is valid
+ assert!(file_handle.is_ok());
+ }
+
+ // Try to delete the file. If the handle was correctly dropped, this should succeed.
+ match std::fs::remove_file(dummy_file_path) {
+ Ok(()) => (), // File was deleted successfully, which means the handle was closed.
+ Err(e) => panic!("Failed to delete file: {}", e), // Failed to delete the file, likely because the handle is still open.
+ }
+ }
+
+ #[test]
+ fn test_file_not_found() {
+ let path = Path::new("non_existent_file.txt");
+ let file_handle =
+ unsafe { FileHandle::new(path.to_str().unwrap(), AccessMode::Read, ShareMode::Read) };
+
+ // Check that opening a non-existent file returns an error
+ assert!(file_handle.is_err());
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/file_io.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/file_io.rs
new file mode 100644
index 0000000..e5de247
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/file_io.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+/// The module provides unsafe wrappers around two Windows API functions: `ReadFile` and `GetQueuedCompletionStatus`.
+///
+/// These wrappers aim to simplify and abstract the use of these functions, providing easier error handling and a safer interface.
+/// They return standard Rust `io::Result` types for convenience and consistency with the rest of the Rust standard library.
+use std::io;
+use std::ptr;
+
+use winapi::{
+ ctypes::c_void,
+ shared::{
+ basetsd::ULONG_PTR,
+ minwindef::{DWORD, FALSE},
+ winerror::{ERROR_IO_PENDING, WAIT_TIMEOUT},
+ },
+ um::{
+ errhandlingapi::GetLastError, fileapi::ReadFile, ioapiset::GetQueuedCompletionStatus,
+ minwinbase::OVERLAPPED,
+ },
+};
+
+use crate::FileHandle;
+use crate::IOCompletionPort;
+
+/// Asynchronously queue a read request from a file into a buffer slice.
+///
+/// Wraps the unsafe Windows API function `ReadFile`, making it safe to call only when the overlapped buffer
+/// remains valid and unchanged anywhere else during the entire async operation.
+///
+/// Returns a boolean indicating whether the read operation completed synchronously or is pending.
+///
+/// # Safety
+///
+/// This function is marked as `unsafe` because it uses raw pointers and requires the caller to ensure
+/// that the buffer slice and the overlapped buffer stay valid during the whole async operation.
+pub unsafe fn read_file_to_slice<T>(
+ file_handle: &FileHandle,
+ buffer_slice: &mut [T],
+ overlapped: *mut OVERLAPPED,
+ offset: u64,
+) -> io::Result<bool> {
+ let num_bytes = std::mem::size_of_val(buffer_slice);
+ unsafe {
+ ptr::write(overlapped, std::mem::zeroed());
+ (*overlapped).u.s_mut().Offset = offset as u32;
+ (*overlapped).u.s_mut().OffsetHigh = (offset >> 32) as u32;
+ }
+
+ let result = unsafe {
+ ReadFile(
+ file_handle.raw_handle(),
+ buffer_slice.as_mut_ptr() as *mut c_void,
+ num_bytes as DWORD,
+ ptr::null_mut(),
+ overlapped,
+ )
+ };
+
+ match result {
+ FALSE => {
+ let error = unsafe { GetLastError() };
+ if error != ERROR_IO_PENDING {
+ Err(io::Error::from_raw_os_error(error as i32))
+ } else {
+ Ok(false)
+ }
+ }
+ _ => Ok(true),
+ }
+}
+
+/// Retrieves the results of an asynchronous I/O operation on an I/O completion port.
+///
+/// Wraps the unsafe Windows API function `GetQueuedCompletionStatus`, making it safe to call only when the overlapped buffer
+/// remains valid and unchanged anywhere else during the entire async operation.
+///
+/// Returns a boolean indicating whether an I/O operation completed synchronously or is still pending.
+///
+/// # Safety
+///
+/// This function is marked as `unsafe` because it uses raw pointers and requires the caller to ensure
+/// that the overlapped buffer stays valid during the whole async operation.
+pub unsafe fn get_queued_completion_status(
+ completion_port: &IOCompletionPort,
+ lp_number_of_bytes: &mut DWORD,
+ lp_completion_key: &mut ULONG_PTR,
+ lp_overlapped: *mut *mut OVERLAPPED,
+ dw_milliseconds: DWORD,
+) -> io::Result<bool> {
+ let result = unsafe {
+ GetQueuedCompletionStatus(
+ completion_port.raw_handle(),
+ lp_number_of_bytes,
+ lp_completion_key,
+ lp_overlapped,
+ dw_milliseconds,
+ )
+ };
+
+ match result {
+ 0 => {
+ let error = unsafe { GetLastError() };
+ if error == WAIT_TIMEOUT {
+ Ok(false)
+ } else {
+ Err(io::Error::from_raw_os_error(error as i32))
+ }
+ }
+ _ => Ok(true),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::file_handle::{AccessMode, ShareMode};
+
+ use super::*;
+ use std::fs::File;
+ use std::io::Write;
+ use std::path::Path;
+
+ #[test]
+ fn test_read_file_to_slice() {
+ // Create a temporary file and write some data into it
+ let path = Path::new("temp.txt");
+ {
+ let mut file = File::create(path).unwrap();
+ file.write_all(b"Hello, world!").unwrap();
+ }
+
+ let mut buffer: [u8; 512] = [0; 512];
+ let mut overlapped = unsafe { std::mem::zeroed::<OVERLAPPED>() };
+ {
+ let file_handle = unsafe {
+ FileHandle::new(path.to_str().unwrap(), AccessMode::Read, ShareMode::Read)
+ }
+ .unwrap();
+
+ // Call the function under test
+ let result =
+ unsafe { read_file_to_slice(&file_handle, &mut buffer, &mut overlapped, 0) };
+
+ assert!(result.is_ok());
+ let result_str = std::str::from_utf8(&buffer[.."Hello, world!".len()]).unwrap();
+ assert_eq!(result_str, "Hello, world!");
+ }
+
+ // Clean up
+ std::fs::remove_file("temp.txt").unwrap();
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/io_completion_port.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/io_completion_port.rs
new file mode 100644
index 0000000..5bb3322
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/io_completion_port.rs
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::io;
+
+use winapi::{
+ ctypes::c_void,
+ shared::{basetsd::ULONG_PTR, minwindef::DWORD},
+ um::{
+ errhandlingapi::GetLastError,
+ handleapi::{CloseHandle, INVALID_HANDLE_VALUE},
+ ioapiset::CreateIoCompletionPort,
+ winnt::HANDLE,
+ },
+};
+
+use crate::FileHandle;
+
+/// This module provides a safe and idiomatic Rust interface over the IOCompletionPort handle and associated Windows API functions.
+/// This struct represents an I/O completion port, which is an object used in asynchronous I/O operations on Windows.
+pub struct IOCompletionPort {
+ io_completion_port: HANDLE,
+}
+
+impl IOCompletionPort {
+ /// Create a new IOCompletionPort.
+ /// This function wraps the Windows CreateIoCompletionPort function, providing error handling and automatic resource management.
+ ///
+ /// # Arguments
+ ///
+ /// * `file_handle` - A reference to a FileHandle to associate with the IOCompletionPort.
+ /// * `existing_completion_port` - An optional reference to an existing IOCompletionPort. If provided, the new IOCompletionPort will be associated with it.
+ /// * `completion_key` - The completion key associated with the file handle.
+ /// * `number_of_concurrent_threads` - The maximum number of threads that the operating system can allow to concurrently process I/O completion packets for the I/O completion port.
+ ///
+ /// # Return
+ ///
+ /// Returns a Result with the new IOCompletionPort if successful, or an io::Error if the function fails.
+ pub fn new(
+ file_handle: &FileHandle,
+ existing_completion_port: Option<&IOCompletionPort>,
+ completion_key: ULONG_PTR,
+ number_of_concurrent_threads: DWORD,
+ ) -> io::Result<Self> {
+ let io_completion_port = unsafe {
+ CreateIoCompletionPort(
+ file_handle.raw_handle(),
+ existing_completion_port
+ .map_or(std::ptr::null_mut::<c_void>(), |io_completion_port| {
+ io_completion_port.raw_handle()
+ }),
+ completion_key,
+ number_of_concurrent_threads,
+ )
+ };
+
+ if io_completion_port == INVALID_HANDLE_VALUE {
+ let error_code = unsafe { GetLastError() };
+ return Err(io::Error::from_raw_os_error(error_code as i32));
+ }
+
+ Ok(IOCompletionPort { io_completion_port })
+ }
+
+ pub fn raw_handle(&self) -> HANDLE {
+ self.io_completion_port
+ }
+}
+
+impl Drop for IOCompletionPort {
+ /// Drop method for IOCompletionPort.
+ /// This wraps the Windows CloseHandle function, providing automatic resource cleanup when the IOCompletionPort is dropped.
+ /// If an error occurs while dropping, it is logged and the drop continues. This is because panicking in Drop can cause unwinding issues.
+ fn drop(&mut self) {
+ let result = unsafe { CloseHandle(self.io_completion_port) };
+ if result == 0 {
+ let error_code = unsafe { GetLastError() };
+ let error = io::Error::from_raw_os_error(error_code as i32);
+
+ // Only log the error if dropping the handle fails, since Rust's Drop trait does not support returning Result types from the drop method,
+ // and panicking in the drop method is considered bad practice
+ log::warn!("Error when dropping IOCompletionPort: {:?}", error);
+ }
+ }
+}
+
+impl Default for IOCompletionPort {
+ /// Create a default IOCompletionPort, whose handle is set to INVALID_HANDLE_VALUE.
+ /// Returns a new IOCompletionPort with handle set to INVALID_HANDLE_VALUE.
+ fn default() -> Self {
+ Self {
+ io_completion_port: INVALID_HANDLE_VALUE,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::file_handle::{AccessMode, ShareMode};
+
+ #[test]
+ fn create_io_completion_port() {
+ let file_name = "../diskann/tests/data/delete_set_50pts.bin";
+ let file_handle = unsafe { FileHandle::new(file_name, AccessMode::Read, ShareMode::Read) }
+ .expect("Failed to create file handle.");
+
+ let io_completion_port = IOCompletionPort::new(&file_handle, None, 0, 0);
+
+ assert!(
+ io_completion_port.is_ok(),
+ "Failed to create IOCompletionPort."
+ );
+ }
+
+ #[test]
+ fn drop_io_completion_port() {
+ let file_name = "../diskann/tests/data/delete_set_50pts.bin";
+ let file_handle = unsafe { FileHandle::new(file_name, AccessMode::Read, ShareMode::Read) }
+ .expect("Failed to create file handle.");
+
+ let io_completion_port = IOCompletionPort::new(&file_handle, None, 0, 0)
+ .expect("Failed to create IOCompletionPort.");
+
+ // After this line, io_completion_port goes out of scope and its Drop trait will be called.
+ let _ = io_completion_port;
+ // We have no easy way to test that the Drop trait works correctly, but if it doesn't,
+ // a resource leak or other problem may become apparent in later tests or in real use of the code.
+ }
+
+ #[test]
+ fn default_io_completion_port() {
+ let io_completion_port = IOCompletionPort::default();
+ assert_eq!(
+ io_completion_port.raw_handle(),
+ INVALID_HANDLE_VALUE,
+ "Default IOCompletionPort did not have INVALID_HANDLE_VALUE."
+ );
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/lib.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/lib.rs
new file mode 100644
index 0000000..e282570
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/lib.rs
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![cfg_attr(
+ not(test),
+ warn(clippy::panic, clippy::unwrap_used, clippy::expect_used)
+)]
+
+pub mod perf;
+pub use perf::{get_process_cycle_time, get_process_handle};
+
+pub mod file_io;
+pub use file_io::{get_queued_completion_status, read_file_to_slice};
+
+pub mod file_handle;
+pub use file_handle::FileHandle;
+
+pub mod io_completion_port;
+pub use io_completion_port::IOCompletionPort;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/perf.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/perf.rs
new file mode 100644
index 0000000..1ea146f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/platform/src/perf.rs
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[cfg(target_os = "windows")]
+#[link(name = "kernel32")]
+extern "system" {
+ fn OpenProcess(dwDesiredAccess: u32, bInheritHandle: bool, dwProcessId: u32) -> usize;
+ fn QueryProcessCycleTime(hProcess: usize, lpCycleTime: *mut u64) -> bool;
+ fn GetCurrentProcessId() -> u32;
+}
+
+/// Get current process handle.
+pub fn get_process_handle() -> Option<usize> {
+ if cfg!(windows) {
+ const PROCESS_QUERY_INFORMATION: u32 = 0x0400;
+ const PROCESS_VM_READ: u32 = 0x0010;
+
+ unsafe {
+ let current_process_id = GetCurrentProcessId();
+ let handle = OpenProcess(
+ PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
+ false,
+ current_process_id,
+ );
+ if handle == 0 {
+ None
+ } else {
+ Some(handle)
+ }
+ }
+ } else {
+ None
+ }
+}
+
+pub fn get_process_cycle_time(process_handle: Option<usize>) -> Option<u64> {
+ let mut cycle_time: u64 = 0;
+ if cfg!(windows) {
+ if let Some(handle) = process_handle {
+ let result = unsafe { QueryProcessCycleTime(handle, &mut cycle_time as *mut u64) };
+ if result {
+ return Some(cycle_time);
+ }
+ }
+ }
+
+ None
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/project.code-workspace b/packages/leann-backend-diskann/third_party/DiskANN/rust/project.code-workspace
new file mode 100644
index 0000000..29bed00
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/project.code-workspace
@@ -0,0 +1,58 @@
+{
+ "folders": [
+ {
+ "path": "."
+ }
+ ],
+ "settings": {
+ "search.exclude": {
+ "target": true,
+ },
+ "files.exclude": {
+ "target": true,
+ },
+ "rust-analyzer.linkedProjects": [
+ ".\\vector\\Cargo.toml",
+ ".\\vector\\Cargo.toml",
+ ".\\vector\\Cargo.toml",
+ ".\\diskann\\Cargo.toml"
+ ],
+ "[rust]": {
+ "editor.defaultFormatter": "rust-lang.rust-analyzer",
+ "editor.formatOnSave": true,
+ }
+ },
+ "launch": {
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Build memory index",
+ "type": "cppvsdbg",
+ "request": "launch",
+ "program": "${workspaceRoot}\\target\\debug\\build_memory_index.exe",
+ "args": [
+ "--data_type",
+ "float",
+ "--dist_fn",
+ "l2",
+ "--data_path",
+ ".\\base1m.fbin",
+ "--index_path_prefix",
+ ".\\rust_index_sift_base_R32_L50_A1.2_T1",
+ "-R",
+ "64",
+ "-L",
+ "100",
+ "--alpha",
+ "1.2",
+ "-T",
+ "1"
+ ],
+ "stopAtEntry": false,
+ "cwd": "c:\\data",
+ "environment": [],
+ "externalConsole": true
+ },
+ ]
+ }
+}
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/readme.md b/packages/leann-backend-diskann/third_party/DiskANN/rust/readme.md
new file mode 100644
index 0000000..a6c5a1b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/readme.md
@@ -0,0 +1,25 @@
+
+# readme
+
+run commands under disnann_rust directory.
+
+build:
+```
+cargo build // Debug
+
+cargo build -r // Release
+```
+
+
+run:
+```
+cargo run // Debug
+
+cargo run -r // Release
+```
+
+
+test:
+```
+cargo test
+```
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/rust-toolchain.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/rust-toolchain.toml
new file mode 100644
index 0000000..183a72c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/rust-toolchain.toml
@@ -0,0 +1,4 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[toolchain]
+channel = "stable"
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/Cargo.toml
new file mode 100644
index 0000000..709a290
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/Cargo.toml
@@ -0,0 +1,24 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "vector"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+half = "2.2.1"
+thiserror = "1.0.40"
+bytemuck = "1.7.0"
+
+[build-dependencies]
+cc = "1.0.79"
+
+[dev-dependencies]
+base64 = "0.21.2"
+bincode = "1.3.3"
+serde = "1.0.163"
+approx = "0.5.1"
+rand = "0.8.5"
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/build.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/build.rs
new file mode 100644
index 0000000..2d36c21
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/build.rs
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+fn main() {
+ println!("cargo:rerun-if-changed=distance.c");
+ if cfg!(target_os = "macos") {
+ std::env::set_var("CFLAGS", "-mavx2 -mfma -Wno-error -MP -O2 -D NDEBUG -D MKL_ILP64 -D USE_AVX2 -D USE_ACCELERATED_PQ -D NOMINMAX -D _TARGET_ARM_APPLE_DARWIN");
+
+ cc::Build::new()
+ .file("distance.c")
+ .warnings_into_errors(true)
+ .debug(false)
+ .target("x86_64-apple-darwin")
+ .compile("nativefunctions.lib");
+ } else {
+ std::env::set_var("CFLAGS", "/permissive- /MP /ifcOutput /GS- /W3 /Gy /Zi /Gm- /O2 /Ob2 /Zc:inline /fp:fast /D NDEBUG /D MKL_ILP64 /D USE_AVX2 /D USE_ACCELERATED_PQ /D NOMINMAX /fp:except- /errorReport:prompt /WX /openmp:experimental /Zc:forScope /GR /arch:AVX2 /Gd /Oy /Oi /MD /std:c++14 /FC /EHsc /nologo /Ot");
+ // std::env::set_var("CFLAGS", "/permissive- /MP /ifcOutput /GS- /W3 /Gy /Zi /Gm- /Obd /Zc:inline /fp:fast /D DEBUG /D MKL_ILP64 /D USE_AVX2 /D USE_ACCELERATED_PQ /D NOMINMAX /fp:except- /errorReport:prompt /WX /openmp:experimental /Zc:forScope /GR /arch:AVX512 /Gd /Oy /Oi /MD /std:c++14 /FC /EHsc /nologo /Ot");
+
+ cc::Build::new()
+ .file("distance.c")
+ .warnings_into_errors(true)
+ .debug(false)
+ .compile("nativefunctions");
+
+ println!("cargo:rustc-link-arg=nativefunctions.lib");
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/distance.c b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/distance.c
new file mode 100644
index 0000000..ee5333a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/distance.c
@@ -0,0 +1,35 @@
+#include <immintrin.h>
+#include <math.h>
+
+inline __m256i load_128bit_to_256bit(const __m128i *ptr)
+{
+ __m128i value128 = _mm_loadu_si128(ptr);
+ __m256i value256 = _mm256_castsi128_si256(value128);
+ return _mm256_inserti128_si256(value256, _mm_setzero_si128(), 1);
+}
+
+float distance_compare_avx512f_f16(const unsigned char *vec1, const unsigned char *vec2, size_t size)
+{
+ __m512 sum_squared_diff = _mm512_setzero_ps();
+
+ for (int i = 0; i < size / 16; i += 1)
+ {
+ __m512 v1 = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(vec1 + i * 2 * 16)));
+ __m512 v2 = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(vec2 + i * 2 * 16)));
+
+ __m512 diff = _mm512_sub_ps(v1, v2);
+ sum_squared_diff = _mm512_fmadd_ps(diff, diff, sum_squared_diff);
+ }
+
+ size_t i = (size / 16) * 16;
+
+ if (i != size)
+ {
+ __m512 va = _mm512_cvtph_ps(load_128bit_to_256bit((const __m128i *)(vec1 + i * 2)));
+ __m512 vb = _mm512_cvtph_ps(load_128bit_to_256bit((const __m128i *)(vec2 + i * 2)));
+ __m512 diff512 = _mm512_sub_ps(va, vb);
+ sum_squared_diff = _mm512_fmadd_ps(diff512, diff512, sum_squared_diff);
+ }
+
+ return _mm512_reduce_add_ps(sum_squared_diff);
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/distance.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/distance.rs
new file mode 100644
index 0000000..8ca6cb2
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/distance.rs
@@ -0,0 +1,442 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use crate::l2_float_distance::{distance_l2_vector_f16, distance_l2_vector_f32};
+use crate::{Half, Metric};
+
+/// Distance contract for full-precision vertex
+pub trait FullPrecisionDistance<T, const N: usize> {
+ /// Get the distance between vertex a and vertex b
+ fn distance_compare(a: &[T; N], b: &[T; N], vec_type: Metric) -> f32;
+}
+
+// reason = "Not supported Metric type Metric::Cosine"
+#[allow(clippy::panic)]
+impl<const N: usize> FullPrecisionDistance<f32, N> for [f32; N] {
+ /// Calculate distance between two f32 Vertex
+ #[inline(always)]
+ fn distance_compare(a: &[f32; N], b: &[f32; N], metric: Metric) -> f32 {
+ match metric {
+ Metric::L2 => distance_l2_vector_f32::<N>(a, b),
+ _ => panic!("Not supported Metric type {:?}", metric),
+ }
+ }
+}
+
+// reason = "Not supported Metric type Metric::Cosine"
+#[allow(clippy::panic)]
+impl<const N: usize> FullPrecisionDistance<Half, N> for [Half; N] {
+ fn distance_compare(a: &[Half; N], b: &[Half; N], metric: Metric) -> f32 {
+ match metric {
+ Metric::L2 => distance_l2_vector_f16::<N>(a, b),
+ _ => panic!("Not supported Metric type {:?}", metric),
+ }
+ }
+}
+
+// reason = "Not yet supported Vector i8"
+#[allow(clippy::panic)]
+impl<const N: usize> FullPrecisionDistance<i8, N> for [i8; N] {
+ fn distance_compare(_a: &[i8; N], _b: &[i8; N], _metric: Metric) -> f32 {
+ panic!("Not supported VectorType i8")
+ }
+}
+
+// reason = "Not yet supported Vector u8"
+#[allow(clippy::panic)]
+impl<const N: usize> FullPrecisionDistance<u8, N> for [u8; N] {
+ fn distance_compare(_a: &[u8; N], _b: &[u8; N], _metric: Metric) -> f32 {
+ panic!("Not supported VectorType u8")
+ }
+}
+
+#[cfg(test)]
+mod distance_test {
+ use super::*;
+
+ #[repr(C, align(32))]
+ pub struct F32Slice112([f32; 112]);
+
+ #[repr(C, align(32))]
+ pub struct F16Slice112([Half; 112]);
+
+ fn get_turing_test_data() -> (F32Slice112, F32Slice112) {
+ let a_slice: [f32; 112] = [
+ 0.13961786,
+ -0.031577103,
+ -0.09567415,
+ 0.06695563,
+ -0.1588727,
+ 0.089852564,
+ -0.019837005,
+ 0.07497972,
+ 0.010418192,
+ -0.054594643,
+ 0.08613386,
+ -0.05103466,
+ 0.16568437,
+ -0.02703799,
+ 0.00728657,
+ -0.15313251,
+ 0.16462992,
+ -0.030570814,
+ 0.11635703,
+ 0.23938893,
+ 0.018022912,
+ -0.12646551,
+ 0.018048918,
+ -0.035986554,
+ 0.031986624,
+ -0.015286017,
+ 0.010117953,
+ -0.032691937,
+ 0.12163067,
+ -0.04746277,
+ 0.010213069,
+ -0.043672588,
+ -0.099362016,
+ 0.06599016,
+ -0.19397286,
+ -0.13285528,
+ -0.22040887,
+ 0.017690737,
+ -0.104262285,
+ -0.0044555613,
+ -0.07383778,
+ -0.108652934,
+ 0.13399786,
+ 0.054912474,
+ 0.20181285,
+ 0.1795591,
+ -0.05425621,
+ -0.10765217,
+ 0.1405377,
+ -0.14101997,
+ -0.12017701,
+ 0.011565498,
+ 0.06952187,
+ 0.060136646,
+ 0.0023214167,
+ 0.04204699,
+ 0.048470616,
+ 0.17398086,
+ 0.024218207,
+ -0.15626553,
+ -0.11291045,
+ -0.09688122,
+ 0.14393932,
+ -0.14713104,
+ -0.108876854,
+ 0.035279203,
+ -0.05440188,
+ 0.017205412,
+ 0.011413814,
+ 0.04009471,
+ 0.11070237,
+ -0.058998976,
+ 0.07260045,
+ -0.057893746,
+ -0.0036240944,
+ -0.0064988653,
+ -0.13842176,
+ -0.023219328,
+ 0.0035885905,
+ -0.0719257,
+ -0.21335067,
+ 0.11415403,
+ -0.0059823603,
+ 0.12091869,
+ 0.08136634,
+ -0.10769281,
+ 0.024518685,
+ 0.0009200326,
+ -0.11628049,
+ 0.07448965,
+ 0.13736208,
+ -0.04144517,
+ -0.16426727,
+ -0.06380103,
+ -0.21386267,
+ 0.022373492,
+ -0.05874115,
+ 0.017314062,
+ -0.040344074,
+ 0.01059176,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ];
+ let b_slice: [f32; 112] = [
+ -0.07209058,
+ -0.17755842,
+ -0.030627966,
+ 0.163028,
+ -0.2233766,
+ 0.057412963,
+ 0.0076995124,
+ -0.017121306,
+ -0.015759075,
+ -0.026947778,
+ -0.010282468,
+ -0.23968373,
+ -0.021486737,
+ -0.09903155,
+ 0.09361805,
+ 0.0042711576,
+ -0.08695552,
+ -0.042165346,
+ 0.064218745,
+ -0.06707651,
+ 0.07846054,
+ 0.12235762,
+ -0.060716823,
+ 0.18496591,
+ -0.13023394,
+ 0.022469055,
+ 0.056764495,
+ 0.07168404,
+ -0.08856144,
+ -0.15343173,
+ 0.099879816,
+ -0.033529017,
+ 0.0795304,
+ -0.009242254,
+ -0.10254546,
+ 0.13086525,
+ -0.101518914,
+ -0.1031299,
+ -0.056826904,
+ 0.033196196,
+ 0.044143833,
+ -0.049787212,
+ -0.018148342,
+ -0.11172959,
+ -0.06776237,
+ -0.09185828,
+ -0.24171598,
+ 0.05080982,
+ -0.0727684,
+ 0.045031235,
+ -0.11363879,
+ -0.063389264,
+ 0.105850354,
+ -0.19847773,
+ 0.08828623,
+ -0.087071925,
+ 0.033512704,
+ 0.16118294,
+ 0.14111553,
+ 0.020884402,
+ -0.088860825,
+ 0.018745849,
+ 0.047522716,
+ -0.03665169,
+ 0.15726231,
+ -0.09930561,
+ 0.057844743,
+ -0.10532736,
+ -0.091297254,
+ 0.067029804,
+ 0.04153976,
+ 0.06393326,
+ 0.054578528,
+ 0.0038539872,
+ 0.1023088,
+ -0.10653885,
+ -0.108500294,
+ -0.046606563,
+ 0.020439683,
+ -0.120957725,
+ -0.13334097,
+ -0.13425854,
+ -0.20481694,
+ 0.07009538,
+ 0.08660361,
+ -0.0096641015,
+ 0.095316306,
+ -0.002898167,
+ -0.19680002,
+ 0.08466311,
+ 0.04812689,
+ -0.028978813,
+ 0.04780206,
+ -0.2001506,
+ -0.036866356,
+ -0.023720587,
+ 0.10731964,
+ 0.05517358,
+ -0.09580819,
+ 0.14595725,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ];
+
+ (F32Slice112(a_slice), F32Slice112(b_slice))
+ }
+
+ fn get_turing_test_data_f16() -> (F16Slice112, F16Slice112) {
+ let (a_slice, b_slice) = get_turing_test_data();
+ let a_data = a_slice.0.iter().map(|x| Half::from_f32(*x));
+ let b_data = b_slice.0.iter().map(|x| Half::from_f32(*x));
+
+ (
+ F16Slice112(a_data.collect::<Vec<Half>>().try_into().unwrap()),
+ F16Slice112(b_data.collect::<Vec<Half>>().try_into().unwrap()),
+ )
+ }
+
+ use crate::test_util::*;
+ use approx::assert_abs_diff_eq;
+
+ #[test]
+ fn test_dist_l2_float_turing() {
+ // two vectors are allocated in the contiguous heap memory
+ let (a_slice, b_slice) = get_turing_test_data();
+ let distance = <[f32; 112] as FullPrecisionDistance<f32, 112>>::distance_compare(
+ &a_slice.0,
+ &b_slice.0,
+ Metric::L2,
+ );
+
+ assert_abs_diff_eq!(
+ distance,
+ no_vector_compare_f32(&a_slice.0, &b_slice.0),
+ epsilon = 1e-6
+ );
+ }
+
+ #[test]
+ fn test_dist_l2_f16_turing() {
+ // two vectors are allocated in the contiguous heap memory
+ let (a_slice, b_slice) = get_turing_test_data_f16();
+ let distance = <[Half; 112] as FullPrecisionDistance<Half, 112>>::distance_compare(
+ &a_slice.0,
+ &b_slice.0,
+ Metric::L2,
+ );
+
+ // Note the variance between the full 32 bit precision and the 16 bit precision
+ assert_eq!(distance, no_vector_compare_f16(&a_slice.0, &b_slice.0));
+ }
+
+ #[test]
+ fn distance_test() {
+ #[repr(C, align(32))]
+ struct Vector32ByteAligned {
+ v: [f32; 512],
+ }
+
+ // two vectors are allocated in the contiguous heap memory
+ let two_vec = Box::new(Vector32ByteAligned {
+ v: [
+ 69.02492, 78.84786, 63.125072, 90.90581, 79.2592, 70.81731, 3.0829668, 33.33287,
+ 20.777142, 30.147898, 23.681915, 42.553043, 12.602162, 7.3808074, 19.157589,
+ 65.6791, 76.44677, 76.89124, 86.40756, 84.70118, 87.86142, 16.126896, 5.1277637,
+ 95.11038, 83.946945, 22.735607, 11.548555, 59.51482, 24.84603, 15.573776, 78.27185,
+ 71.13179, 38.574017, 80.0228, 13.175261, 62.887978, 15.205181, 18.89392, 96.13162,
+ 87.55455, 34.179806, 62.920044, 4.9305916, 54.349373, 21.731495, 14.982187,
+ 40.262867, 20.15214, 36.61963, 72.450806, 55.565, 95.5375, 93.73356, 95.36308,
+ 66.30762, 58.0397, 18.951357, 67.11702, 43.043316, 30.65622, 99.85361, 2.5889993,
+ 27.844774, 39.72441, 46.463238, 71.303764, 90.45308, 36.390602, 63.344395,
+ 26.427078, 35.99528, 82.35505, 32.529175, 23.165905, 74.73179, 9.856939, 59.38126,
+ 35.714924, 79.81213, 46.704124, 24.47884, 36.01743, 0.46678782, 29.528152,
+ 1.8980742, 24.68853, 75.58984, 98.72279, 68.62601, 11.890173, 49.49361, 55.45572,
+ 72.71067, 34.107483, 51.357758, 76.400635, 81.32725, 66.45081, 17.848074,
+ 62.398876, 94.20444, 2.10886, 17.416393, 64.88253, 29.000723, 62.434315, 53.907238,
+ 70.51412, 78.70744, 55.181683, 64.45116, 23.419212, 53.68544, 43.506958, 46.89598,
+ 35.905994, 64.51397, 91.95555, 20.322979, 74.80128, 97.548744, 58.312725, 78.81985,
+ 31.911612, 14.445949, 49.85094, 70.87396, 40.06766, 7.129991, 78.48008, 75.21636,
+ 93.623604, 95.95479, 29.571129, 22.721554, 26.73875, 52.075504, 56.783104,
+ 94.65493, 61.778534, 85.72401, 85.369514, 29.922367, 41.410553, 94.12884,
+ 80.276855, 55.604828, 54.70947, 74.07216, 44.61955, 31.38113, 68.48596, 34.56782,
+ 14.424729, 48.204506, 9.675444, 32.01946, 92.32695, 36.292683, 78.31955, 98.05327,
+ 14.343918, 46.017002, 95.90888, 82.63626, 16.873539, 3.698051, 7.8042626,
+ 64.194405, 96.71023, 67.93692, 21.618402, 51.92182, 22.834194, 61.56986, 19.749891,
+ 55.31206, 38.29552, 67.57593, 67.145836, 38.92673, 94.95708, 72.38746, 90.70901,
+ 69.43995, 9.394085, 31.646872, 88.20112, 9.134722, 99.98214, 5.423498, 41.51995,
+ 76.94409, 77.373276, 3.2966614, 9.611201, 57.231106, 30.747868, 76.10228, 91.98308,
+ 70.893585, 0.9067178, 43.96515, 16.321218, 27.734184, 83.271835, 88.23312,
+ 87.16445, 5.556643, 15.627432, 58.547127, 93.6459, 40.539192, 49.124157, 91.13276,
+ 57.485855, 8.827019, 4.9690843, 46.511234, 53.91469, 97.71925, 20.135271,
+ 23.353004, 70.92099, 93.38748, 87.520134, 51.684677, 29.89813, 9.110392, 65.809204,
+ 34.16554, 93.398605, 84.58669, 96.409645, 9.876037, 94.767784, 99.21523, 1.9330144,
+ 94.92429, 75.12728, 17.218828, 97.89164, 35.476578, 77.629456, 69.573746,
+ 40.200542, 42.117836, 5.861628, 75.45282, 82.73633, 0.98086596, 77.24894,
+ 11.248695, 61.070026, 52.692616, 80.5449, 80.76036, 29.270136, 67.60252, 48.782394,
+ 95.18851, 83.47162, 52.068756, 46.66002, 90.12216, 15.515327, 33.694042, 96.963036,
+ 73.49627, 62.805485, 44.715607, 59.98627, 3.8921833, 37.565327, 29.69184,
+ 39.429665, 83.46899, 44.286453, 21.54851, 56.096413, 18.169249, 5.214751,
+ 14.691341, 99.779335, 26.32643, 67.69903, 36.41243, 67.27333, 12.157213, 96.18984,
+ 2.438283, 78.14289, 0.14715195, 98.769, 53.649532, 21.615898, 39.657497, 95.45616,
+ 18.578386, 71.47976, 22.348118, 17.85519, 6.3717127, 62.176777, 22.033644,
+ 23.178005, 79.44858, 89.70233, 37.21273, 71.86182, 21.284317, 52.908623, 30.095518,
+ 63.64478, 77.55823, 80.04871, 15.133011, 30.439043, 70.16561, 4.4014096, 89.28944,
+ 26.29093, 46.827854, 11.764729, 61.887516, 47.774887, 57.19503, 59.444664,
+ 28.592825, 98.70386, 1.2497544, 82.28431, 46.76423, 83.746124, 53.032673, 86.53457,
+ 99.42168, 90.184, 92.27852, 9.059965, 71.75723, 70.45299, 10.924053, 68.329704,
+ 77.27232, 6.677854, 75.63629, 57.370533, 17.09031, 10.554659, 99.56178, 37.53221,
+ 72.311104, 75.7565, 65.2042, 36.096478, 64.69502, 38.88497, 64.33723, 84.87812,
+ 66.84958, 8.508932, 79.134, 83.431015, 66.72124, 61.801838, 64.30524, 37.194263,
+ 77.94725, 89.705185, 23.643505, 19.505919, 48.40264, 43.01083, 21.171177,
+ 18.717121, 10.805857, 69.66983, 77.85261, 57.323063, 3.28964, 38.758026, 5.349946,
+ 7.46572, 57.485138, 30.822384, 33.9411, 95.53746, 65.57723, 42.1077, 28.591347,
+ 11.917269, 5.031073, 31.835615, 19.34116, 85.71027, 87.4516, 1.3798475, 70.70583,
+ 51.988052, 45.217144, 14.308596, 54.557167, 86.18323, 79.13666, 76.866745,
+ 46.010685, 79.739235, 44.667603, 39.36416, 72.605896, 73.83187, 13.137412,
+ 6.7911267, 63.952374, 10.082436, 86.00318, 99.760376, 92.84948, 63.786434,
+ 3.4429908, 18.244314, 75.65299, 14.964747, 70.126366, 80.89449, 91.266655,
+ 96.58798, 46.439327, 38.253975, 87.31036, 21.093178, 37.19671, 58.28973, 9.75231,
+ 12.350321, 25.75115, 87.65073, 53.610504, 36.850048, 18.66356, 94.48941, 83.71898,
+ 44.49315, 44.186737, 19.360733, 84.365974, 46.76272, 44.924366, 50.279808,
+ 54.868866, 91.33004, 18.683397, 75.13282, 15.070831, 47.04839, 53.780903,
+ 26.911152, 74.65651, 57.659935, 25.604189, 37.235474, 65.39667, 53.952206,
+ 40.37131, 59.173275, 96.00756, 54.591274, 10.787476, 69.51549, 31.970142,
+ 25.408005, 55.972492, 85.01888, 97.48981, 91.006134, 28.98619, 97.151276,
+ 34.388496, 47.498177, 11.985874, 64.73775, 33.877014, 13.370312, 34.79146,
+ 86.19321, 15.019405, 94.07832, 93.50433, 60.168625, 50.95409, 38.27827, 47.458614,
+ 32.83715, 69.54998, 69.0361, 84.1418, 34.270298, 74.23852, 70.707466, 78.59845,
+ 9.651399, 24.186779, 58.255756, 53.72362, 92.46477, 97.75528, 20.257462, 30.122698,
+ 50.41517, 28.156603, 42.644154,
+ ],
+ });
+
+ let distance = compare::<f32, 256>(256, Metric::L2, &two_vec.v);
+
+ assert_eq!(distance, 429141.2);
+ }
+
+ fn compare<T, const N: usize>(dim: usize, metric: Metric, v: &[f32]) -> f32
+ where
+ for<'a> [T; N]: FullPrecisionDistance<T, N>,
+ {
+ let a_ptr = v.as_ptr();
+ let b_ptr = unsafe { a_ptr.add(dim) };
+
+ let a_ref =
+ <&[f32; N]>::try_from(unsafe { std::slice::from_raw_parts(a_ptr, dim) }).unwrap();
+ let b_ref =
+ <&[f32; N]>::try_from(unsafe { std::slice::from_raw_parts(b_ptr, dim) }).unwrap();
+
+ <[f32; N]>::distance_compare(a_ref, b_ref, metric)
+ }
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/distance_test.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/distance_test.rs
new file mode 100644
index 0000000..0def026
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/distance_test.rs
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[cfg(test)]
+mod e2e_test {
+
+ #[repr(C, align(32))]
+ pub struct F32Slice104([f32; 104]);
+
+ #[repr(C, align(32))]
+ pub struct F16Slice104([Half; 104]);
+
+ use approx::assert_abs_diff_eq;
+
+ use crate::half::Half;
+ use crate::l2_float_distance::{distance_l2_vector_f16, distance_l2_vector_f32};
+
+ fn no_vector_compare_f32(a: &[f32], b: &[f32]) -> f32 {
+ let mut sum = 0.0;
+ for i in 0..a.len() {
+ let a_f32 = a[i];
+ let b_f32 = b[i];
+ let diff = a_f32 - b_f32;
+ sum += diff * diff;
+ }
+ sum
+ }
+
+ fn no_vector_compare(a: &[Half], b: &[Half]) -> f32 {
+ let mut sum = 0.0;
+ for i in 0..a.len() {
+ let a_f32 = a[i].to_f32();
+ let b_f32 = b[i].to_f32();
+ let diff = a_f32 - b_f32;
+ sum += diff * diff;
+ }
+ sum
+ }
+
+ #[test]
+ fn avx2_matches_novector() {
+ for i in 1..3 {
+ let (f1, f2) = get_test_data(0, i);
+
+ let distance_f32x8 = distance_l2_vector_f32::<104>(&f1.0, &f2.0);
+ let distance = no_vector_compare_f32(&f1.0, &f2.0);
+
+ assert_abs_diff_eq!(distance, distance_f32x8, epsilon = 1e-6);
+ }
+ }
+
+ #[test]
+ fn avx2_matches_novector_random() {
+ let (f1, f2) = get_test_data_random();
+
+ let distance_f32x8 = distance_l2_vector_f32::<104>(&f1.0, &f2.0);
+ let distance = no_vector_compare_f32(&f1.0, &f2.0);
+
+ assert_abs_diff_eq!(distance, distance_f32x8, epsilon = 1e-4);
+ }
+
+ #[test]
+ fn avx_f16_matches_novector() {
+ for i in 1..3 {
+ let (f1, f2) = get_test_data_f16(0, i);
+ let _a_slice = f1.0.map(|x| x.to_f32().to_string()).join(", ");
+ let _b_slice = f2.0.map(|x| x.to_f32().to_string()).join(", ");
+
+ let expected = no_vector_compare(f1.0[0..].as_ref(), f2.0[0..].as_ref());
+ let distance_f16x8 = distance_l2_vector_f16::<104>(&f1.0, &f2.0);
+
+ assert_abs_diff_eq!(distance_f16x8, expected, epsilon = 1e-4);
+ }
+ }
+
+ #[test]
+ fn avx_f16_matches_novector_random() {
+ let (f1, f2) = get_test_data_f16_random();
+
+ let expected = no_vector_compare(f1.0[0..].as_ref(), f2.0[0..].as_ref());
+ let distance_f16x8 = distance_l2_vector_f16::<104>(&f1.0, &f2.0);
+
+ assert_abs_diff_eq!(distance_f16x8, expected, epsilon = 1e-4);
+ }
+
+ fn get_test_data_f16(i1: usize, i2: usize) -> (F16Slice104, F16Slice104) {
+ let (a_slice, b_slice) = get_test_data(i1, i2);
+ let a_data = a_slice.0.iter().map(|x| Half::from_f32(*x));
+ let b_data = b_slice.0.iter().map(|x| Half::from_f32(*x));
+
+ (
+ F16Slice104(a_data.collect::<Vec<Half>>().try_into().unwrap()),
+ F16Slice104(b_data.collect::<Vec<Half>>().try_into().unwrap()),
+ )
+ }
+
+ fn get_test_data(i1: usize, i2: usize) -> (F32Slice104, F32Slice104) {
+ use base64::{engine::general_purpose, Engine as _};
+
+ let b64 = general_purpose::STANDARD.decode(TEST_DATA).unwrap();
+
+ let decoded: Vec<Vec<f32>> = bincode::deserialize(&b64).unwrap();
+ debug_assert!(decoded.len() > i1);
+ debug_assert!(decoded.len() > i2);
+
+ let mut f1 = F32Slice104([0.0; 104]);
+ let v1 = &decoded[i1];
+ debug_assert!(v1.len() == 104);
+ f1.0.copy_from_slice(v1);
+
+ let mut f2 = F32Slice104([0.0; 104]);
+ let v2 = &decoded[i2];
+ debug_assert!(v2.len() == 104);
+ f2.0.copy_from_slice(v2);
+
+ (f1, f2)
+ }
+
+ fn get_test_data_f16_random() -> (F16Slice104, F16Slice104) {
+ let (a_slice, b_slice) = get_test_data_random();
+ let a_data = a_slice.0.iter().map(|x| Half::from_f32(*x));
+ let b_data = b_slice.0.iter().map(|x| Half::from_f32(*x));
+
+ (
+ F16Slice104(a_data.collect::<Vec<Half>>().try_into().unwrap()),
+ F16Slice104(b_data.collect::<Vec<Half>>().try_into().unwrap()),
+ )
+ }
+
+ fn get_test_data_random() -> (F32Slice104, F32Slice104) {
+ use rand::Rng;
+
+ let mut rng = rand::thread_rng();
+ let mut f1 = F32Slice104([0.0; 104]);
+
+ for i in 0..104 {
+ f1.0[i] = rng.gen_range(-1.0..1.0);
+ }
+
+ let mut f2 = F32Slice104([0.0; 104]);
+
+ for i in 0..104 {
+ f2.0[i] = rng.gen_range(-1.0..1.0);
+ }
+
+ (f1, f2)
+ }
+
+ const TEST_DATA: &str = "BQAAAAAAAABoAAAAAAAAAPz3Dj7+VgG9z/DDvQkgiT2GryK+nwS4PTeBorz4jpk9ELEqPKKeX73zZrA9uAlRvSqpKT7Gft28LsTuO8XOHL6/lCg+pW/6vJhM7j1fInU+yaSTPC2AAb5T25M8o2YTvWgEAz00cnq8xcUlPPvnBb2AGfk9UmhCvbdUJzwH4jK9UH7Lvdklhz3SoEa+NwsIvt2yYb4q7JA8d4fVvfX/kbtDOJe9boXevbw2CT7n62A9B6hOPlfeNz7CO169vnjcvR3pDz6KZxC+XR/2vTd9PTx7YY492FF2PekiGDt3OSw9IIlGPQooMj5DZcY8EgQgvpg9572paca91GQTPoWpFr7U+t697YAQPYHUXr1d8ow8AQE7PFo6JD3tt+I96ahxvYuvlD3+IW29N4Jtu2/01Ltvvg2+dja+vI8uazvITZO9mXhavpfJ6T2tB8S7OKT3PWWjpj0Mjty9advIPFgucTp3JO69CI6YPaWoDD5pwim9rjUovh2qgr3R/lq+nUi3PI+acL041o081D8lvRCJLTwAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAA6pJO94NE1voDn+rzQ8CY+1rxkvtspaz0xTPw7+0GMvC0ZgbyWwdy8zHcovKdvdb70BLC8DtHKvdK6vz0R9Ys7vBWyvZK1LL0ehYM9aV+JveuvoD2ilvo9NLJ4vbRnPT4MXAW+BhG4POOBaD0Vz5I9s1+1vTUdHb7Kjcw9uVUJvdbgoj3TbBe8WwPSvYoBBj4m6c+9xTXTvVTDaL28+Ac9KtA0Pa3tS73Vq5S8fNLkvf/Gir0yILy9ZYR3vvUdUD2ZB5W9rHI4PXS76L070oG9EsjYPb89S75pz7Q9xFKyvZ5ECT0kDSU+l4AQPsQVqzyq/LW95ZCZPC6nQj0VIBa9XwkhPr1gy72c7mw937XXvQ76ur3sRok9mCUqPXHvgj28jV89LZN8O0eH0T0KMdq9ZzXevYbmPr0fcac8r7j3vYmKCL4Sewm+iLtRviuOjz08XbE9LlYevDI1wz0s7z278oVJvtpjrT20IEU9+mTtvBjMQz1H9Ey+LQEXva1Rwrxmyts9sf1hPRY3xL3RdRU+AAAAAAAAAAAAAAAAAAAAAGgAAAAAAAAARqSTvbYJpLx1x869cW67PeeJhb7/cBu9m0eFPQO3oL0I+L49YQDavTYSez3SmTg96hBGPuh4oL2x2ow6WdCUO6XUSz4xcU88GReAvVfekj0Ph3Y9z43hvBzT5z1I2my9UVy3vAj8jL08Gtm9CfJcPRihTr1+8Yu9TiP+PNrJa77Dfa09IhpEPesJNr0XzFU8yye3PZKFyz3uzJ09FLRUvYq3l73X4X07DDUzvq9VXjwWtg8+JrzYPcFCkr0jDCg9T9zlvZbZjz4Y8pM89xo8PgAcfbvYSnY8XoFKvO05/L36yzE8J+5yPqfe5r2AZFq8ULRDvnkTgrw+S7q9qGYLvQDZYL1T8d09bFikvZw3+jsYLdO8H3GVveHBYT4gnsE8ZBIJPpzOEj7OSDC+ZYu+vFc1Erzko4M9GqLtPBHH5TwpeRs+miC4PBHH5Tw9Z9k9VUsUPjnppj0oC5C9mcqDvY7y1rxdvZU8PdFAPov9lz0bOmq94kdyPBBokTxtOj89fu4avSsazj1P7iE+x8YkPAAAAAAAAAAAAAAAAAAAAABoAAAAAAAAAHEruT3mgKM8JnEvvAsfHL63906+ifhgvldl1r14OeO9waUyuw3yUzx+PDW9UbDhPQP4Lb4KRRk+Oky2vaLfaT30mrA9YMeZPfzPMz4h42M+XfCHva4AGr6MOSM+iBOzvdsaE7xFxgI+gJGXvVMzE75kHY+8oAWNvVqNK7yOx589fU3lvVVPg730Cwk+DKkEPWYtxjqQ2MK9H0T+vTnGQj2yq5w8L49BvrEJrzyB4Yo9AXV7PYGCLr3MxsG9oWM7PTyu8TzEOhW+dyWrvUTxHD2nL+c9+VKFPcthhLsc0PM8FdyPPeLj/z1WAHS8ZvW2PGg4Cb5u3IU9g4CovSHW+L2CWoG++nZnPAi2ST3HmUC9P5rJuxQbU765lwU+7FLBPUPTfL0uGgk+yKy2PYwXaT1I4I+9AU6VPQ5QaDx9mdE8Qg8zPfGCUjzD/io9rr+BvTNDqT0MFNi9mHatvS1iJD0nVrK78WmIPE0QsL3PAQq9cMRgPWXmmr3yTcw9UcXrPccwa76+cBq+5iVOvUg9c70AAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAB/K7k9hCsnPUJXJr2Wg4a9MEtXve33Sj0VJZ89pciEvWLqwLzUgyu8ADTGPAVenL2UZ/c96YtMved+Wr3LUro9H8a7vGTSA77C5n69Lf3pPQj4KD5cFKq9fZ0uvvYQCT7b23G9XGMCPrGuy736Z9A9kZzFPSuCSD7/9/07Y4/6POxLir3/JBS9qFKMvkSzjryPgVY+ugq8PC9yhbsXaiq+O6WfPcvFK7vZXAy+goAQvXpHHj5jwPI87eokvrySET5QoOm8h8ixOhXzKb5s8+A9sjcJPjiLAz598yQ9yCYSPq6eGz4rvjE82lvGvWuIOLx23zK9hHg8vTWOv70/Tse81fA6Pr2wNz34Eza+2Uj3PZ3trr0aXAI9PCkKPiybe721P9U9QkNLO927jT3LpRA+mpJUvUeU6rwC/Qa+lr4Cvgrpnj1pQ/i9TxhSvJqYr72RS6y8aQLTPQzPiz3vSRY94NfrPJl6LL2adjO8iYfPuhRzZz2f7R8+iVskPcUeXr12ZiI+nd3xvIYv8bwqYlg+AAAAAAAAAAAAAAAAAAAAAA==";
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/half.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/half.rs
new file mode 100644
index 0000000..87d7df6
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/half.rs
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use bytemuck::{Pod, Zeroable};
+use half::f16;
+use std::convert::AsRef;
+use std::fmt;
+
+// Define the Half type as a new type over f16.
+// the memory layout of the Half struct will be the same as the memory layout of the f16 type itself.
+// The Half struct serves as a simple wrapper around the f16 type and does not introduce any additional memory overhead.
+// Test function:
+// use half::f16;
+// pub struct Half(f16);
+// fn main() {
+// let size_of_half = std::mem::size_of::<Half>();
+// let alignment_of_half = std::mem::align_of::<Half>();
+// println!("Size of Half: {} bytes", size_of_half);
+// println!("Alignment of Half: {} bytes", alignment_of_half);
+// }
+// Output:
+// Size of Half: 2 bytes
+// Alignment of Half: 2 bytes
+pub struct Half(f16);
+
+unsafe impl Pod for Half {}
+unsafe impl Zeroable for Half {}
+
+// Implement From<f32> for Half
+impl From<Half> for f32 {
+ fn from(val: Half) -> Self {
+ val.0.to_f32()
+ }
+}
+
+// Implement AsRef<f16> for Half so that it can be used in distance_compare.
+impl AsRef<f16> for Half {
+ fn as_ref(&self) -> &f16 {
+ &self.0
+ }
+}
+
+// Implement From<f32> for Half.
+impl Half {
+ pub fn from_f32(value: f32) -> Self {
+ Self(f16::from_f32(value))
+ }
+}
+
+// Implement Default for Half.
+impl Default for Half {
+ fn default() -> Self {
+ Self(f16::from_f32(Default::default()))
+ }
+}
+
+// Implement Clone for Half.
+impl Clone for Half {
+ fn clone(&self) -> Self {
+ Half(self.0)
+ }
+}
+
+// Implement PartialEq for Half.
+impl fmt::Debug for Half {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "Half({:?})", self.0)
+ }
+}
+
+impl Copy for Half {}
+
+impl Half {
+ pub fn to_f32(&self) -> f32 {
+ self.0.to_f32()
+ }
+}
+
+unsafe impl Send for Half {}
+unsafe impl Sync for Half {}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/l2_float_distance.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/l2_float_distance.rs
new file mode 100644
index 0000000..b818899
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/l2_float_distance.rs
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+
+//! Distance calculation for L2 Metric
+
+#[cfg(not(target_feature = "avx2"))]
+compile_error!("Library must be compiled with -C target-feature=+avx2");
+
+use std::arch::x86_64::*;
+
+use crate::Half;
+
+/// Calculate the distance by vector arithmetic
+#[inline(never)]
+pub fn distance_l2_vector_f16<const N: usize>(a: &[Half; N], b: &[Half; N]) -> f32 {
+ debug_assert_eq!(N % 8, 0);
+
+ // make sure the addresses are bytes aligned
+ debug_assert_eq!(a.as_ptr().align_offset(32), 0);
+ debug_assert_eq!(b.as_ptr().align_offset(32), 0);
+
+ unsafe {
+ let mut sum = _mm256_setzero_ps();
+ let a_ptr = a.as_ptr() as *const __m128i;
+ let b_ptr = b.as_ptr() as *const __m128i;
+
+ // Iterate over the elements in steps of 8
+ for i in (0..N).step_by(8) {
+ let a_vec = _mm256_cvtph_ps(_mm_load_si128(a_ptr.add(i / 8)));
+ let b_vec = _mm256_cvtph_ps(_mm_load_si128(b_ptr.add(i / 8)));
+
+ let diff = _mm256_sub_ps(a_vec, b_vec);
+ sum = _mm256_fmadd_ps(diff, diff, sum);
+ }
+
+ let x128: __m128 = _mm_add_ps(_mm256_extractf128_ps(sum, 1), _mm256_castps256_ps128(sum));
+ /* ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 ) */
+ let x64: __m128 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128));
+ /* ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 ) */
+ let x32: __m128 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55));
+ /* Conversion to float is a no-op on x86-64 */
+ _mm_cvtss_f32(x32)
+ }
+}
+
+/// Calculate the distance by vector arithmetic
+#[inline(never)]
+pub fn distance_l2_vector_f32<const N: usize>(a: &[f32; N], b: &[f32; N]) -> f32 {
+ debug_assert_eq!(N % 8, 0);
+
+ // make sure the addresses are bytes aligned
+ debug_assert_eq!(a.as_ptr().align_offset(32), 0);
+ debug_assert_eq!(b.as_ptr().align_offset(32), 0);
+
+ unsafe {
+ let mut sum = _mm256_setzero_ps();
+
+ // Iterate over the elements in steps of 8
+ for i in (0..N).step_by(8) {
+ let a_vec = _mm256_load_ps(&a[i]);
+ let b_vec = _mm256_load_ps(&b[i]);
+ let diff = _mm256_sub_ps(a_vec, b_vec);
+ sum = _mm256_fmadd_ps(diff, diff, sum);
+ }
+
+ let x128: __m128 = _mm_add_ps(_mm256_extractf128_ps(sum, 1), _mm256_castps256_ps128(sum));
+ /* ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 ) */
+ let x64: __m128 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128));
+ /* ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 ) */
+ let x32: __m128 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55));
+ /* Conversion to float is a no-op on x86-64 */
+ _mm_cvtss_f32(x32)
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/lib.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/lib.rs
new file mode 100644
index 0000000..d221070
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/lib.rs
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![cfg_attr(
+ not(test),
+ warn(clippy::panic, clippy::unwrap_used, clippy::expect_used)
+)]
+
+// #![feature(stdsimd)]
+// mod f32x16;
+// Uncomment above 2 to experiment with f32x16
+mod distance;
+mod half;
+mod l2_float_distance;
+mod metric;
+mod utils;
+
+pub use crate::half::Half;
+pub use distance::FullPrecisionDistance;
+pub use metric::Metric;
+pub use utils::prefetch_vector;
+
+#[cfg(test)]
+mod distance_test;
+mod test_util;
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/metric.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/metric.rs
new file mode 100644
index 0000000..c60ef29
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/metric.rs
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#![warn(missing_debug_implementations, missing_docs)]
+use std::str::FromStr;
+
+/// Distance metric
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
+pub enum Metric {
+ /// Squared Euclidean (L2-Squared)
+ L2,
+
+ /// Cosine similarity
+ /// TODO: T should be float for Cosine distance
+ Cosine,
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum ParseMetricError {
+ #[error("Invalid format for Metric: {0}")]
+ InvalidFormat(String),
+}
+
+impl FromStr for Metric {
+ type Err = ParseMetricError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.to_lowercase().as_str() {
+ "l2" => Ok(Metric::L2),
+ "cosine" => Ok(Metric::Cosine),
+ _ => Err(ParseMetricError::InvalidFormat(String::from(s))),
+ }
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/test_util.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/test_util.rs
new file mode 100644
index 0000000..7cfc929
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/test_util.rs
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+#[cfg(test)]
+use crate::Half;
+
+#[cfg(test)]
+pub fn no_vector_compare_f16(a: &[Half], b: &[Half]) -> f32 {
+ let mut sum = 0.0;
+ debug_assert_eq!(a.len(), b.len());
+
+ for i in 0..a.len() {
+ sum += (a[i].to_f32() - b[i].to_f32()).powi(2);
+ }
+ sum
+}
+
+#[cfg(test)]
+pub fn no_vector_compare_f32(a: &[f32], b: &[f32]) -> f32 {
+ let mut sum = 0.0;
+ debug_assert_eq!(a.len(), b.len());
+
+ for i in 0..a.len() {
+ sum += (a[i] - b[i]).powi(2);
+ }
+ sum
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/utils.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/utils.rs
new file mode 100644
index 0000000..a61c99a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector/src/utils.rs
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::arch::x86_64::{_mm_prefetch, _MM_HINT_T0};
+
+/// Prefetch the given vector in chunks of 64 bytes, which is a cache line size
+/// NOTE: good efficiency when total_vec_size is integral multiple of 64
+#[inline]
+pub fn prefetch_vector<T>(vec: &[T]) {
+ let vec_ptr = vec.as_ptr() as *const i8;
+ let vecsize = std::mem::size_of_val(vec);
+ let max_prefetch_size = (vecsize / 64) * 64;
+
+ for d in (0..max_prefetch_size).step_by(64) {
+ unsafe {
+ _mm_prefetch(vec_ptr.add(d), _MM_HINT_T0);
+ }
+ }
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector_base64/Cargo.toml b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector_base64/Cargo.toml
new file mode 100644
index 0000000..6f50ad9
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector_base64/Cargo.toml
@@ -0,0 +1,15 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+[package]
+name = "vector_base64"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+base64 = "0.21.2"
+bincode = "1.3.3"
+half = "2.2.1"
+serde = "1.0.163"
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/rust/vector_base64/src/main.rs b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector_base64/src/main.rs
new file mode 100644
index 0000000..2867436
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/rust/vector_base64/src/main.rs
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Microsoft Corporation. All rights reserved.
+ * Licensed under the MIT license.
+ */
+use std::fs::File;
+use std::io::{self, BufReader, Read};
+use std::{env, vec};
+
+fn main() -> io::Result<()> {
+ // Retrieve command-line arguments
+ let args: Vec<String> = env::args().collect();
+
+ // Check if the correct number of arguments is provided
+ if args.len() != 4 {
+ print_usage();
+ return Ok(());
+ }
+
+ // Retrieve the input and output file paths from the arguments
+ let input_file_path = &args[1];
+ let item_count: usize = args[2].parse::<usize>().unwrap();
+ let return_dimension: usize = args[3].parse::<usize>().unwrap();
+
+ // Open the input file for reading
+ let mut input_file = BufReader::new(File::open(input_file_path)?);
+
+ // Read the first 8 bytes as metadata
+ let mut metadata = [0; 8];
+ input_file.read_exact(&mut metadata)?;
+
+ // Extract the number of points and dimension from the metadata
+ let _ = i32::from_le_bytes(metadata[..4].try_into().unwrap());
+ let mut dimension: usize = (i32::from_le_bytes(metadata[4..].try_into().unwrap())) as usize;
+ if return_dimension < dimension {
+ dimension = return_dimension;
+ }
+
+ let mut float_array = Vec::<Vec<f32>>::with_capacity(item_count);
+
+ // Process each data point
+ for _ in 0..item_count {
+ // Read one data point from the input file
+ let mut buffer = vec![0; dimension * std::mem::size_of::<f32>()];
+ match input_file.read_exact(&mut buffer) {
+ Ok(()) => {
+ let mut float_data = buffer
+ .chunks_exact(4)
+ .map(|chunk| f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
+ .collect::<Vec<f32>>();
+
+ let mut i = return_dimension;
+ while i > dimension {
+ float_data.push(0.0);
+ i -= 1;
+ }
+
+ float_array.push(float_data);
+ }
+ Err(err) => {
+ println!("Error: {}", err);
+ break;
+ }
+ }
+ }
+
+ use base64::{engine::general_purpose, Engine as _};
+
+ let encoded: Vec<u8> = bincode::serialize(&float_array).unwrap();
+ let b64 = general_purpose::STANDARD.encode(encoded);
+ println!("Float {}", b64);
+
+ Ok(())
+}
+
+/// Prints the usage information
+fn print_usage() {
+ println!("Usage: program_name input_file <itemcount> <dimensions>");
+ println!(
+ "Itemcount is the number of items to convert. Expand to dimension if provided is smaller"
+ );
+}
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/setup.py b/packages/leann-backend-diskann/third_party/DiskANN/setup.py
new file mode 100644
index 0000000..01184f8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/setup.py
@@ -0,0 +1,176 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+import os
+import re
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+from setuptools import Extension, setup
+from setuptools.command.build_ext import build_ext
+from setuptools.command.install_lib import install_lib
+
+# Convert distutils Windows platform specifiers to CMake -A arguments
+PLAT_TO_CMAKE = {
+ "win-amd64": "x64"
+}
+
+
+class CMakeExtension(Extension):
+ def __init__(self, name: str, sourcedir: str = "") -> None:
+ super().__init__(name, sources=[])
+ self.sourcedir = os.fspath(Path(sourcedir).resolve())
+
+
+class CMakeBuild(build_ext):
+ def build_extension(self, ext: CMakeExtension) -> None:
+ # Must be in this form due to bug in .resolve() only fixed in Python 3.10+
+ ext_fullpath = Path.cwd() / self.get_ext_fullpath(ext.name) # type: ignore[no-untyped-call]
+ extdir = ext_fullpath.parent.resolve()
+ # Using this requires trailing slash for auto-detection & inclusion of
+ # auxiliary "native" libs
+
+ debug = int(os.environ.get("DEBUG", 0)) if self.debug is None else self.debug
+ cfg = "Debug" if debug else "Release"
+
+ # CMake lets you override the generator - we need to check this.
+ # Can be set with Conda-Build, for example.
+ cmake_generator = os.environ.get("CMAKE_GENERATOR", "")
+
+ # Set Python_EXECUTABLE instead if you use PYBIND11_FINDPYTHON
+ # EXAMPLE_VERSION_INFO shows you how to pass a value into the C++ code
+ # from Python.
+ cmake_args = [
+ f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}{os.sep}",
+ f"-DPYTHON_EXECUTABLE={sys.executable}",
+ f"-DCMAKE_BUILD_TYPE={cfg}", # not used on MSVC, but no harm
+ f"-DVERSION_INFO={self.distribution.get_version()}" # commented out, we want this set in the CMake file
+ ]
+ build_args = []
+ # Adding CMake arguments set as environment variable
+ # (needed e.g. to build for ARM OSx on conda-forge)
+ if "CMAKE_ARGS" in os.environ:
+ cmake_args += [item for item in os.environ["CMAKE_ARGS"].split(" ") if item]
+
+ # In this example, we pass in the version to C++. You might not need to.
+ # cmake_args += [f"-DVERSION_INFO={self.distribution.get_version()}"] # type: ignore[attr-defined]
+
+ if self.compiler.compiler_type != "msvc":
+ # Using Ninja-build since it a) is available as a wheel and b)
+ # multithreads automatically. MSVC would require all variables be
+ # exported for Ninja to pick it up, which is a little tricky to do.
+ # Users can override the generator with CMAKE_GENERATOR in CMake
+ # 3.15+.
+ if not cmake_generator or cmake_generator == "Ninja":
+ try:
+ import ninja # noqa: F401
+
+ ninja_executable_path = Path(ninja.BIN_DIR) / "ninja"
+ cmake_args += [
+ "-GNinja",
+ f"-DCMAKE_MAKE_PROGRAM:FILEPATH={ninja_executable_path}",
+ ]
+ except ImportError:
+ pass
+
+ else:
+
+ # Single config generators are handled "normally"
+ single_config = any(x in cmake_generator for x in {"NMake", "Ninja"})
+
+ # CMake allows an arch-in-generator style for backward compatibility
+ contains_arch = any(x in cmake_generator for x in {"ARM", "Win64"})
+
+ # Specify the arch if using MSVC generator, but only if it doesn't
+ # contain a backward-compatibility arch spec already in the
+ # generator name.
+ if not single_config and not contains_arch:
+ cmake_args += ["-A", PLAT_TO_CMAKE[self.plat_name]]
+
+ # Multi-config generators have a different way to specify configs
+ if not single_config:
+ cmake_args += [
+ f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{cfg.upper()}={extdir}"
+ ]
+ build_args += ["--config", cfg]
+
+ if sys.platform.startswith("darwin"):
+ # Cross-compile support for macOS - respect ARCHFLAGS if set
+ archs = re.findall(r"-arch (\S+)", os.environ.get("ARCHFLAGS", ""))
+ if archs:
+ cmake_args += ["-DCMAKE_OSX_ARCHITECTURES={}".format(";".join(archs))]
+
+ # Set CMAKE_BUILD_PARALLEL_LEVEL to control the parallel build level
+ # across all generators.
+ if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ:
+ # self.parallel is a Python 3 only way to set parallel jobs by hand
+ # using -j in the build_ext call, not supported by pip or PyPA-build.
+ if hasattr(self, "parallel") and self.parallel:
+ # CMake 3.12+ only.
+ build_args += [f"-j{self.parallel}"]
+
+ build_temp = Path(self.build_temp) / ext.name
+ if not build_temp.exists():
+ build_temp.mkdir(parents=True)
+
+ # this next line is problematic. we tell it to use the ext.sourcedir but, when
+ # using `python -m build`, we actually have a copy of everything made and pushed
+ # into a venv isolation area
+ if os.environ.get("USE_CONDA", "") == '1' and os.environ.get("CONDA_PREFIX", "") != "":
+ subprocess.run(
+ ["cmake", "-DPYBIND=True", "-DCMAKE_PREFIX_PATH=" + os.environ.get("CONDA_PREFIX", ""),
+ "-DProtobuf_DIR=" + os.path.join(os.environ.get("CONDA_PREFIX", ""), "lib/cmake/protobuf"),
+ ext.sourcedir] + cmake_args, cwd=build_temp, check=True
+ )
+ else:
+ subprocess.run(
+ ["cmake", "-DPYBIND=True", ext.sourcedir] + cmake_args, cwd=build_temp, check=True
+ )
+
+ subprocess.run(
+ ["cmake", "--build", "."] + build_args, cwd=build_temp, check=True
+ )
+
+
+class InstallCMakeLibs(install_lib):
+ def run(self):
+ """
+ Windows only copy from the x64/Release directory and place them in the package
+ """
+
+ self.announce("Moving library files", level=3)
+
+ self.skip_build = True
+
+ # we only need to move the windows build output
+ windows_build_output_dir = Path('.') / 'x64' / 'Release'
+
+ if windows_build_output_dir.exists():
+ libs = [
+ os.path.join(windows_build_output_dir, _lib) for _lib in
+ os.listdir(windows_build_output_dir) if
+ os.path.isfile(os.path.join(windows_build_output_dir, _lib)) and
+ os.path.splitext(_lib)[1] in [".dll", '.lib', '.pyd', '.exp']
+ ]
+
+ for lib in libs:
+ shutil.move(
+ lib,
+ os.path.join(self.build_dir, 'diskannpy', os.path.basename(lib))
+ )
+
+ super().run()
+
+
+setup(
+ ext_modules=[CMakeExtension("diskannpy._diskannpy", ".")],
+ cmdclass={
+ "build_ext": CMakeBuild,
+ 'install_lib': InstallCMakeLibs
+ },
+ zip_safe=False,
+ package_dir={"diskannpy": "python/src"},
+ exclude_package_data={"diskannpy": ["diskann_bindings.cpp"]}
+)
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/src/CMakeLists.txt
new file mode 100644
index 0000000..97b00c7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/CMakeLists.txt
@@ -0,0 +1,26 @@
+#Copyright(c) Microsoft Corporation.All rights reserved.
+#Licensed under the MIT license.
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_COMPILE_WARNING_AS_ERROR ON)
+
+if(MSVC)
+ add_subdirectory(dll)
+else()
+ #file(GLOB CPP_SOURCES *.cpp)
+ set(CPP_SOURCES abstract_data_store.cpp ann_exception.cpp apple_aligned_file_reader.cpp disk_utils.cpp
+ distance.cpp index.cpp in_mem_graph_store.cpp in_mem_data_store.cpp
+ linux_aligned_file_reader.cpp math_utils.cpp natural_number_map.cpp
+ in_mem_data_store.cpp in_mem_graph_store.cpp
+ natural_number_set.cpp memory_mapper.cpp partition.cpp pq.cpp
+ pq_flash_index.cpp scratch.cpp logger.cpp utils.cpp filter_utils.cpp index_factory.cpp abstract_index.cpp pq_l2_distance.cpp pq_data_store.cpp)
+ if (RESTAPI)
+ list(APPEND CPP_SOURCES restapi/search_wrapper.cpp restapi/server.cpp)
+ endif()
+ add_library(${PROJECT_NAME} ${CPP_SOURCES})
+ add_library(${PROJECT_NAME}_s STATIC ${CPP_SOURCES})
+endif()
+
+if (NOT MSVC)
+ install(TARGETS ${PROJECT_NAME} LIBRARY)
+endif()
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/abstract_data_store.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/abstract_data_store.cpp
new file mode 100644
index 0000000..0cff015
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/abstract_data_store.cpp
@@ -0,0 +1,45 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <vector>
+#include "abstract_data_store.h"
+
+namespace diskann
+{
+
+template <typename data_t>
+AbstractDataStore<data_t>::AbstractDataStore(const location_t capacity, const size_t dim)
+ : _capacity(capacity), _dim(dim)
+{
+}
+
+template <typename data_t> location_t AbstractDataStore<data_t>::capacity() const
+{
+ return _capacity;
+}
+
+template <typename data_t> size_t AbstractDataStore<data_t>::get_dims() const
+{
+ return _dim;
+}
+
+template <typename data_t> location_t AbstractDataStore<data_t>::resize(const location_t new_num_points)
+{
+ if (new_num_points > _capacity)
+ {
+ return expand(new_num_points);
+ }
+ else if (new_num_points < _capacity)
+ {
+ return shrink(new_num_points);
+ }
+ else
+ {
+ return _capacity;
+ }
+}
+
+template DISKANN_DLLEXPORT class AbstractDataStore<float>;
+template DISKANN_DLLEXPORT class AbstractDataStore<int8_t>;
+template DISKANN_DLLEXPORT class AbstractDataStore<uint8_t>;
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/abstract_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/abstract_index.cpp
new file mode 100644
index 0000000..9266582
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/abstract_index.cpp
@@ -0,0 +1,334 @@
+#include "common_includes.h"
+#include "windows_customizations.h"
+#include "abstract_index.h"
+
+namespace diskann
+{
+
+template <typename data_type, typename tag_type>
+void AbstractIndex::build(const data_type *data, const size_t num_points_to_load, const std::vector<tag_type> &tags)
+{
+ auto any_data = std::any(data);
+ auto any_tags_vec = TagVector(tags);
+ this->_build(any_data, num_points_to_load, any_tags_vec);
+}
+
+template <typename data_type, typename IDType>
+std::pair<uint32_t, uint32_t> AbstractIndex::search(const data_type *query, const size_t K, const uint32_t L,
+ IDType *indices, float *distances)
+{
+ auto any_indices = std::any(indices);
+ auto any_query = std::any(query);
+ return _search(any_query, K, L, any_indices, distances);
+}
+
+template <typename data_type, typename tag_type>
+size_t AbstractIndex::search_with_tags(const data_type *query, const uint64_t K, const uint32_t L, tag_type *tags,
+ float *distances, std::vector<data_type *> &res_vectors, bool use_filters,
+ const std::string filter_label)
+{
+ auto any_query = std::any(query);
+ auto any_tags = std::any(tags);
+ auto any_res_vectors = DataVector(res_vectors);
+ return this->_search_with_tags(any_query, K, L, any_tags, distances, any_res_vectors, use_filters, filter_label);
+}
+
+template <typename IndexType>
+std::pair<uint32_t, uint32_t> AbstractIndex::search_with_filters(const DataType &query, const std::string &raw_label,
+ const size_t K, const uint32_t L, IndexType *indices,
+ float *distances)
+{
+ auto any_indices = std::any(indices);
+ return _search_with_filters(query, raw_label, K, L, any_indices, distances);
+}
+
+template <typename data_type>
+void AbstractIndex::search_with_optimized_layout(const data_type *query, size_t K, size_t L, uint32_t *indices)
+{
+ auto any_query = std::any(query);
+ this->_search_with_optimized_layout(any_query, K, L, indices);
+}
+
+template <typename data_type, typename tag_type>
+int AbstractIndex::insert_point(const data_type *point, const tag_type tag)
+{
+ auto any_point = std::any(point);
+ auto any_tag = std::any(tag);
+ return this->_insert_point(any_point, any_tag);
+}
+
+template <typename data_type, typename tag_type, typename label_type>
+int AbstractIndex::insert_point(const data_type *point, const tag_type tag, const std::vector<label_type> &labels)
+{
+ auto any_point = std::any(point);
+ auto any_tag = std::any(tag);
+ auto any_labels = Labelvector(labels);
+ return this->_insert_point(any_point, any_tag, any_labels);
+}
+
+template <typename tag_type> int AbstractIndex::lazy_delete(const tag_type &tag)
+{
+ auto any_tag = std::any(tag);
+ return this->_lazy_delete(any_tag);
+}
+
+template <typename tag_type>
+void AbstractIndex::lazy_delete(const std::vector<tag_type> &tags, std::vector<tag_type> &failed_tags)
+{
+ auto any_tags = TagVector(tags);
+ auto any_failed_tags = TagVector(failed_tags);
+ this->_lazy_delete(any_tags, any_failed_tags);
+}
+
+template <typename tag_type> void AbstractIndex::get_active_tags(tsl::robin_set<tag_type> &active_tags)
+{
+ auto any_active_tags = TagRobinSet(active_tags);
+ this->_get_active_tags(any_active_tags);
+}
+
+template <typename data_type> void AbstractIndex::set_start_points_at_random(data_type radius, uint32_t random_seed)
+{
+ auto any_radius = std::any(radius);
+ this->_set_start_points_at_random(any_radius, random_seed);
+}
+
+template <typename tag_type, typename data_type> int AbstractIndex::get_vector_by_tag(tag_type &tag, data_type *vec)
+{
+ auto any_tag = std::any(tag);
+ auto any_data_ptr = std::any(vec);
+ return this->_get_vector_by_tag(any_tag, any_data_ptr);
+}
+
+template <typename label_type> void AbstractIndex::set_universal_label(const label_type universal_label)
+{
+ auto any_label = std::any(universal_label);
+ this->_set_universal_label(any_label);
+}
+
+// exports
+template DISKANN_DLLEXPORT void AbstractIndex::build<float, int32_t>(const float *data, const size_t num_points_to_load,
+ const std::vector<int32_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<int8_t, int32_t>(const int8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<int32_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<uint8_t, int32_t>(const uint8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<int32_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<float, uint32_t>(const float *data,
+ const size_t num_points_to_load,
+ const std::vector<uint32_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<int8_t, uint32_t>(const int8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<uint32_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<uint8_t, uint32_t>(const uint8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<uint32_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<float, int64_t>(const float *data, const size_t num_points_to_load,
+ const std::vector<int64_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<int8_t, int64_t>(const int8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<int64_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<uint8_t, int64_t>(const uint8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<int64_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<float, uint64_t>(const float *data,
+ const size_t num_points_to_load,
+ const std::vector<uint64_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<int8_t, uint64_t>(const int8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<uint64_t> &tags);
+template DISKANN_DLLEXPORT void AbstractIndex::build<uint8_t, uint64_t>(const uint8_t *data,
+ const size_t num_points_to_load,
+ const std::vector<uint64_t> &tags);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search<float, uint32_t>(
+ const float *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search<uint8_t, uint32_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search<int8_t, uint32_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search<float, uint64_t>(
+ const float *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search<uint8_t, uint64_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search<int8_t, uint64_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search_with_filters<uint32_t>(
+ const DataType &query, const std::string &raw_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> AbstractIndex::search_with_filters<uint64_t>(
+ const DataType &query, const std::string &raw_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<float, int32_t>(
+ const float *query, const uint64_t K, const uint32_t L, int32_t *tags, float *distances,
+ std::vector<float *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<uint8_t, int32_t>(
+ const uint8_t *query, const uint64_t K, const uint32_t L, int32_t *tags, float *distances,
+ std::vector<uint8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<int8_t, int32_t>(
+ const int8_t *query, const uint64_t K, const uint32_t L, int32_t *tags, float *distances,
+ std::vector<int8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<float, uint32_t>(
+ const float *query, const uint64_t K, const uint32_t L, uint32_t *tags, float *distances,
+ std::vector<float *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<uint8_t, uint32_t>(
+ const uint8_t *query, const uint64_t K, const uint32_t L, uint32_t *tags, float *distances,
+ std::vector<uint8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<int8_t, uint32_t>(
+ const int8_t *query, const uint64_t K, const uint32_t L, uint32_t *tags, float *distances,
+ std::vector<int8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<float, int64_t>(
+ const float *query, const uint64_t K, const uint32_t L, int64_t *tags, float *distances,
+ std::vector<float *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<uint8_t, int64_t>(
+ const uint8_t *query, const uint64_t K, const uint32_t L, int64_t *tags, float *distances,
+ std::vector<uint8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<int8_t, int64_t>(
+ const int8_t *query, const uint64_t K, const uint32_t L, int64_t *tags, float *distances,
+ std::vector<int8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<float, uint64_t>(
+ const float *query, const uint64_t K, const uint32_t L, uint64_t *tags, float *distances,
+ std::vector<float *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<uint8_t, uint64_t>(
+ const uint8_t *query, const uint64_t K, const uint32_t L, uint64_t *tags, float *distances,
+ std::vector<uint8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT size_t AbstractIndex::search_with_tags<int8_t, uint64_t>(
+ const int8_t *query, const uint64_t K, const uint32_t L, uint64_t *tags, float *distances,
+ std::vector<int8_t *> &res_vectors, bool use_filters, const std::string filter_label);
+
+template DISKANN_DLLEXPORT void AbstractIndex::search_with_optimized_layout<float>(const float *query, size_t K,
+ size_t L, uint32_t *indices);
+template DISKANN_DLLEXPORT void AbstractIndex::search_with_optimized_layout<uint8_t>(const uint8_t *query, size_t K,
+ size_t L, uint32_t *indices);
+template DISKANN_DLLEXPORT void AbstractIndex::search_with_optimized_layout<int8_t>(const int8_t *query, size_t K,
+ size_t L, uint32_t *indices);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, int32_t>(const float *point, const int32_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, int32_t>(const uint8_t *point, const int32_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, int32_t>(const int8_t *point, const int32_t tag);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, uint32_t>(const float *point, const uint32_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, uint32_t>(const uint8_t *point, const uint32_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, uint32_t>(const int8_t *point, const uint32_t tag);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, int64_t>(const float *point, const int64_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, int64_t>(const uint8_t *point, const int64_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, int64_t>(const int8_t *point, const int64_t tag);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, uint64_t>(const float *point, const uint64_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, uint64_t>(const uint8_t *point, const uint64_t tag);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, uint64_t>(const int8_t *point, const uint64_t tag);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, int32_t, uint16_t>(
+ const float *point, const int32_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, int32_t, uint16_t>(
+ const uint8_t *point, const int32_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, int32_t, uint16_t>(
+ const int8_t *point, const int32_t tag, const std::vector<uint16_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, uint32_t, uint16_t>(
+ const float *point, const uint32_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, uint32_t, uint16_t>(
+ const uint8_t *point, const uint32_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, uint32_t, uint16_t>(
+ const int8_t *point, const uint32_t tag, const std::vector<uint16_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, int64_t, uint16_t>(
+ const float *point, const int64_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, int64_t, uint16_t>(
+ const uint8_t *point, const int64_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, int64_t, uint16_t>(
+ const int8_t *point, const int64_t tag, const std::vector<uint16_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, uint64_t, uint16_t>(
+ const float *point, const uint64_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, uint64_t, uint16_t>(
+ const uint8_t *point, const uint64_t tag, const std::vector<uint16_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, uint64_t, uint16_t>(
+ const int8_t *point, const uint64_t tag, const std::vector<uint16_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, int32_t, uint32_t>(
+ const float *point, const int32_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, int32_t, uint32_t>(
+ const uint8_t *point, const int32_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, int32_t, uint32_t>(
+ const int8_t *point, const int32_t tag, const std::vector<uint32_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, uint32_t, uint32_t>(
+ const float *point, const uint32_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, uint32_t, uint32_t>(
+ const uint8_t *point, const uint32_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, uint32_t, uint32_t>(
+ const int8_t *point, const uint32_t tag, const std::vector<uint32_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, int64_t, uint32_t>(
+ const float *point, const int64_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, int64_t, uint32_t>(
+ const uint8_t *point, const int64_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, int64_t, uint32_t>(
+ const int8_t *point, const int64_t tag, const std::vector<uint32_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<float, uint64_t, uint32_t>(
+ const float *point, const uint64_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<uint8_t, uint64_t, uint32_t>(
+ const uint8_t *point, const uint64_t tag, const std::vector<uint32_t> &labels);
+template DISKANN_DLLEXPORT int AbstractIndex::insert_point<int8_t, uint64_t, uint32_t>(
+ const int8_t *point, const uint64_t tag, const std::vector<uint32_t> &labels);
+
+template DISKANN_DLLEXPORT int AbstractIndex::lazy_delete<int32_t>(const int32_t &tag);
+template DISKANN_DLLEXPORT int AbstractIndex::lazy_delete<uint32_t>(const uint32_t &tag);
+template DISKANN_DLLEXPORT int AbstractIndex::lazy_delete<int64_t>(const int64_t &tag);
+template DISKANN_DLLEXPORT int AbstractIndex::lazy_delete<uint64_t>(const uint64_t &tag);
+
+template DISKANN_DLLEXPORT void AbstractIndex::lazy_delete<int32_t>(const std::vector<int32_t> &tags,
+ std::vector<int32_t> &failed_tags);
+template DISKANN_DLLEXPORT void AbstractIndex::lazy_delete<uint32_t>(const std::vector<uint32_t> &tags,
+ std::vector<uint32_t> &failed_tags);
+template DISKANN_DLLEXPORT void AbstractIndex::lazy_delete<int64_t>(const std::vector<int64_t> &tags,
+ std::vector<int64_t> &failed_tags);
+template DISKANN_DLLEXPORT void AbstractIndex::lazy_delete<uint64_t>(const std::vector<uint64_t> &tags,
+ std::vector<uint64_t> &failed_tags);
+
+template DISKANN_DLLEXPORT void AbstractIndex::get_active_tags<int32_t>(tsl::robin_set<int32_t> &active_tags);
+template DISKANN_DLLEXPORT void AbstractIndex::get_active_tags<uint32_t>(tsl::robin_set<uint32_t> &active_tags);
+template DISKANN_DLLEXPORT void AbstractIndex::get_active_tags<int64_t>(tsl::robin_set<int64_t> &active_tags);
+template DISKANN_DLLEXPORT void AbstractIndex::get_active_tags<uint64_t>(tsl::robin_set<uint64_t> &active_tags);
+
+template DISKANN_DLLEXPORT void AbstractIndex::set_start_points_at_random<float>(float radius, uint32_t random_seed);
+template DISKANN_DLLEXPORT void AbstractIndex::set_start_points_at_random<uint8_t>(uint8_t radius,
+ uint32_t random_seed);
+template DISKANN_DLLEXPORT void AbstractIndex::set_start_points_at_random<int8_t>(int8_t radius, uint32_t random_seed);
+
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<int32_t, float>(int32_t &tag, float *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<int32_t, uint8_t>(int32_t &tag, uint8_t *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<int32_t, int8_t>(int32_t &tag, int8_t *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<uint32_t, float>(uint32_t &tag, float *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<uint32_t, uint8_t>(uint32_t &tag, uint8_t *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<uint32_t, int8_t>(uint32_t &tag, int8_t *vec);
+
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<int64_t, float>(int64_t &tag, float *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<int64_t, uint8_t>(int64_t &tag, uint8_t *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<int64_t, int8_t>(int64_t &tag, int8_t *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<uint64_t, float>(uint64_t &tag, float *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<uint64_t, uint8_t>(uint64_t &tag, uint8_t *vec);
+template DISKANN_DLLEXPORT int AbstractIndex::get_vector_by_tag<uint64_t, int8_t>(uint64_t &tag, int8_t *vec);
+
+template DISKANN_DLLEXPORT void AbstractIndex::set_universal_label<uint16_t>(const uint16_t label);
+template DISKANN_DLLEXPORT void AbstractIndex::set_universal_label<uint32_t>(const uint32_t label);
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/ann_exception.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/ann_exception.cpp
new file mode 100644
index 0000000..ba55e36
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/ann_exception.cpp
@@ -0,0 +1,36 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "ann_exception.h"
+#include <sstream>
+#include <string>
+
+namespace diskann
+{
+ANNException::ANNException(const std::string &message, int errorCode)
+ : std::runtime_error(message), _errorCode(errorCode)
+{
+}
+
+std::string package_string(const std::string &item_name, const std::string &item_val)
+{
+ return std::string("[") + item_name + ": " + std::string(item_val) + std::string("]");
+}
+
+ANNException::ANNException(const std::string &message, int errorCode, const std::string &funcSig,
+ const std::string &fileName, uint32_t lineNum)
+ : ANNException(package_string(std::string("FUNC"), funcSig) + package_string(std::string("FILE"), fileName) +
+ package_string(std::string("LINE"), std::to_string(lineNum)) + " " + message,
+ errorCode)
+{
+}
+
+FileException::FileException(const std::string &filename, std::system_error &e, const std::string &funcSig,
+ const std::string &fileName, uint32_t lineNum)
+ : ANNException(std::string(" While opening file \'") + filename + std::string("\', error code: ") +
+ std::to_string(e.code().value()) + " " + e.code().message(),
+ e.code().value(), funcSig, fileName, lineNum)
+{
+}
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/apple_aligned_file_reader.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/apple_aligned_file_reader.cpp
new file mode 100644
index 0000000..4ef1c22
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/apple_aligned_file_reader.cpp
@@ -0,0 +1,383 @@
+#include "aligned_file_reader.h"
+#ifdef __APPLE__
+
+#include "apple_aligned_file_reader.h"
+#include "utils.h"
+
+#define SECTOR_LEN 4096
+
+AppleAlignedFileReader::AppleAlignedFileReader()
+{
+ this->file_desc = -1;
+ diskann::cout << "AppleAlignedFileReader created, this=" << this << std::endl;
+}
+
+AppleAlignedFileReader::~AppleAlignedFileReader()
+{
+ diskann::cout << "AppleAlignedFileReader destructor called, this=" << this << std::endl;
+
+ // 先解注册所有线程
+ deregister_all_threads();
+
+ // 关闭文件描述符
+ if (this->file_desc >= 0)
+ {
+ diskann::cout << "Closing file in destructor, fd=" << this->file_desc << std::endl;
+ ::close(this->file_desc);
+ this->file_desc = -1;
+ }
+}
+
+IOContext &AppleAlignedFileReader::get_ctx()
+{
+ auto thread_id = std::this_thread::get_id();
+
+ // 创建一个静态空上下文用于错误情况
+ static IOContext empty_ctx;
+ static bool initialized = false;
+
+ if (!initialized)
+ {
+ empty_ctx.queue = nullptr;
+ empty_ctx.grp = nullptr;
+ empty_ctx.channel = nullptr;
+ initialized = true;
+ }
+
+ std::unique_lock<std::mutex> lk(this->ctx_mut);
+
+ // 如果线程未注册,自动注册它
+ if (ctx_map.find(thread_id) == ctx_map.end())
+ {
+ lk.unlock();
+ diskann::cerr << "Thread " << thread_id << " not registered, auto-registering" << std::endl;
+
+ // 自动注册线程
+ if (this->file_desc >= 0)
+ {
+ this->register_thread();
+
+ // 再次检查是否注册成功
+ lk.lock();
+ if (ctx_map.find(thread_id) != ctx_map.end())
+ {
+ return ctx_map[thread_id];
+ }
+ lk.unlock();
+ }
+
+ return empty_ctx;
+ }
+
+ // 如果已注册,直接返回上下文
+ IOContext &ctx = ctx_map[thread_id];
+ lk.unlock();
+ return ctx;
+}
+
+void AppleAlignedFileReader::register_thread()
+{
+ auto current_id = std::this_thread::get_id();
+ diskann::cout << "register_thread called from thread " << current_id << " on instance " << this << std::endl;
+
+ // 检查文件描述符是否有效
+ if (this->file_desc < 0)
+ {
+ diskann::cerr << "Thread " << current_id << " - register_thread called with invalid file descriptor"
+ << std::endl;
+ return;
+ }
+
+ // 检查线程是否已注册
+ {
+ std::lock_guard<std::mutex> ctx_lock(this->ctx_mut);
+ if (ctx_map.find(current_id) != ctx_map.end())
+ {
+ diskann::cout << "Thread " << current_id << " already registered" << std::endl;
+ return;
+ }
+ }
+
+ // 创建线程上下文
+ IOContext ctx;
+ ctx.queue = nullptr;
+ ctx.grp = nullptr;
+ ctx.channel = nullptr;
+
+ std::string queue_name =
+ "diskann_io_" + std::to_string(*static_cast<unsigned int *>(static_cast<void *>(&current_id)));
+ ctx.queue = dispatch_queue_create(queue_name.c_str(), DISPATCH_QUEUE_SERIAL);
+ if (!ctx.queue)
+ {
+ diskann::cerr << "Failed to create queue for thread " << current_id << std::endl;
+ return;
+ }
+
+ ctx.grp = dispatch_group_create();
+ if (!ctx.grp)
+ {
+ diskann::cerr << "Failed to create group for thread " << current_id << std::endl;
+ dispatch_release(ctx.queue);
+ return;
+ }
+
+ // 复制文件描述符
+ int dup_fd = ::dup(this->file_desc);
+ if (dup_fd == -1)
+ {
+ diskann::cerr << "Failed to duplicate file descriptor: " << this->file_desc << ", errno=" << errno << std::endl;
+ dispatch_release(ctx.grp);
+ dispatch_release(ctx.queue);
+ return;
+ }
+
+ // 创建IO通道
+ ctx.channel = dispatch_io_create(DISPATCH_IO_RANDOM, dup_fd, ctx.queue, ^(int error) {
+ ::close(dup_fd);
+ diskann::cout << "IO channel cleanup called, closed fd=" << dup_fd << std::endl;
+ });
+
+ if (!ctx.channel)
+ {
+ diskann::cerr << "Failed to create IO channel for thread " << current_id << ", fd=" << dup_fd
+ << ", errno=" << errno << std::endl;
+ ::close(dup_fd);
+ dispatch_release(ctx.grp);
+ dispatch_release(ctx.queue);
+ return;
+ }
+
+ // 设置IO通道参数
+ dispatch_io_set_low_water(ctx.channel, SECTOR_LEN);
+ dispatch_io_set_high_water(ctx.channel, SECTOR_LEN * 16);
+
+ // 添加到线程映射
+ {
+ std::lock_guard<std::mutex> ctx_lock(this->ctx_mut);
+ ctx_map[current_id] = ctx;
+ }
+
+ diskann::cout << "Thread " << current_id << " successfully registered with fd=" << dup_fd << std::endl;
+}
+
+void AppleAlignedFileReader::deregister_thread()
+{
+ auto my_id = std::this_thread::get_id();
+ diskann::cout << "deregister_thread called from thread " << my_id << " on instance " << this << std::endl;
+
+ IOContext ctx;
+ bool found = false;
+
+ {
+ std::lock_guard<std::mutex> ctx_lock(this->ctx_mut);
+ if (ctx_map.find(my_id) != ctx_map.end())
+ {
+ ctx = ctx_map[my_id];
+ ctx_map.erase(my_id);
+ found = true;
+ }
+ }
+
+ if (!found)
+ {
+ diskann::cerr << "Thread " << my_id << " not registered, cannot deregister" << std::endl;
+ return;
+ }
+
+ if (ctx.channel)
+ {
+ dispatch_io_close(ctx.channel, DISPATCH_IO_STOP);
+ dispatch_release(ctx.channel);
+ }
+
+ if (ctx.grp)
+ {
+ dispatch_release(ctx.grp);
+ }
+
+ if (ctx.queue)
+ {
+ dispatch_release(ctx.queue);
+ }
+
+ diskann::cout << "Thread " << my_id << " deregistered" << std::endl;
+}
+
+void AppleAlignedFileReader::deregister_all_threads()
+{
+ diskann::cout << "deregister_all_threads called on instance " << this << std::endl;
+
+ std::vector<IOContext> contexts;
+
+ {
+ std::lock_guard<std::mutex> ctx_lock(this->ctx_mut);
+ diskann::cout << "Deregistering " << ctx_map.size() << " threads" << std::endl;
+ for (auto &pair : ctx_map)
+ {
+ contexts.push_back(pair.second);
+ }
+ ctx_map.clear();
+ }
+
+ for (auto &ctx : contexts)
+ {
+ if (ctx.channel)
+ {
+ dispatch_io_close(ctx.channel, DISPATCH_IO_STOP);
+ dispatch_release(ctx.channel);
+ }
+
+ if (ctx.grp)
+ {
+ dispatch_release(ctx.grp);
+ }
+
+ if (ctx.queue)
+ {
+ dispatch_release(ctx.queue);
+ }
+ }
+
+ diskann::cout << "All threads deregistered" << std::endl;
+}
+
+void AppleAlignedFileReader::open(const std::string &fname)
+{
+ diskann::cout << "open called for file: " << fname << " on instance " << this << std::endl;
+
+ // 关闭已存在的文件
+ if (this->file_desc >= 0)
+ {
+ diskann::cout << "Closing existing file descriptor: " << this->file_desc << std::endl;
+ ::close(this->file_desc);
+ this->file_desc = -1;
+ }
+
+ // 清空所有线程上下文
+ deregister_all_threads();
+
+ // 打开新文件
+ this->file_desc = ::open(fname.c_str(), O_RDONLY);
+ if (this->file_desc == -1)
+ {
+ diskann::cerr << "Failed to open file: " << fname << ", errno=" << errno << std::endl;
+ throw std::runtime_error("Failed to open file"); // 文件打开失败是致命错误
+ }
+
+ // 获取文件信息
+ struct stat file_info;
+ if (::fstat(this->file_desc, &file_info) == 0)
+ {
+ diskann::cout << "File opened successfully: " << fname << ", size: " << file_info.st_size
+ << " bytes, fd=" << this->file_desc << std::endl;
+ }
+ else
+ {
+ diskann::cout << "File opened but couldn't get file info, fd=" << this->file_desc << std::endl;
+ }
+}
+
+void AppleAlignedFileReader::close()
+{
+ diskann::cout << "close called on instance " << this << std::endl;
+
+ // 先清理线程上下文
+ deregister_all_threads();
+
+ // 关闭文件描述符
+ if (this->file_desc >= 0)
+ {
+ diskann::cout << "Closing file descriptor: " << this->file_desc << std::endl;
+ ::close(this->file_desc);
+ this->file_desc = -1;
+ }
+}
+
+void AppleAlignedFileReader::read(std::vector<AlignedRead> &read_reqs, IOContext &ctx, bool async)
+{
+ auto thread_id = std::this_thread::get_id();
+
+ // 如果通道无效,自动尝试注册线程
+ if (!ctx.channel && this->file_desc >= 0)
+ {
+ diskann::cout << "Auto-registering thread " << thread_id << " during read" << std::endl;
+ this->register_thread();
+ // 获取新的上下文
+ ctx = this->get_ctx();
+ }
+
+ // 安全检查
+ if (!ctx.channel || !ctx.queue || !ctx.grp)
+ {
+ diskann::cerr << "Invalid IO context in thread " << thread_id << std::endl;
+ return;
+ }
+
+ dispatch_io_t channel = ctx.channel;
+ dispatch_queue_t q = ctx.queue;
+ dispatch_group_t group = ctx.grp;
+
+ // 处理所有读取请求
+ uint64_t n_reqs = read_reqs.size();
+ for (uint64_t i = 0; i < n_reqs; i++)
+ {
+ AlignedRead &req = read_reqs[i];
+
+ // 检查对齐
+ if (!IS_ALIGNED(req.buf, SECTOR_LEN) || !IS_ALIGNED(req.offset, SECTOR_LEN) || !IS_ALIGNED(req.len, SECTOR_LEN))
+ {
+ diskann::cerr << "Thread " << thread_id << " - alignment error for request " << i << std::endl;
+ continue;
+ }
+
+ dispatch_group_enter(group);
+
+ dispatch_io_read(channel, req.offset, req.len, q, ^(bool done, dispatch_data_t data, int error) {
+ if (error)
+ {
+ diskann::cerr << "Thread " << thread_id << " read error: " << error << " when reading at offset "
+ << req.offset << std::endl;
+ if (done)
+ dispatch_group_leave(group);
+ return;
+ }
+
+ if (data)
+ {
+ size_t actual_size = dispatch_data_get_size(data);
+ if (actual_size > 0)
+ {
+ __block size_t total_copied = 0;
+ dispatch_data_apply(data,
+ ^(dispatch_data_t region, size_t region_offset, const void *buffer, size_t size) {
+ if (region_offset + size <= req.len)
+ {
+ memcpy((char *)req.buf + region_offset, buffer, size);
+ total_copied += size;
+ return (bool)true;
+ }
+ diskann::cerr << "Buffer overflow: region_offset=" << region_offset
+ << ", size=" << size << ", req.len=" << req.len << std::endl;
+ return (bool)false;
+ });
+
+ if (total_copied != req.len && done)
+ {
+ diskann::cerr << "Warning: Only copied " << total_copied << " of " << req.len
+ << " requested bytes" << std::endl;
+ }
+ }
+ }
+
+ // 仅在完成时离开组
+ if (done)
+ {
+ dispatch_group_leave(group);
+ }
+ });
+ }
+
+ dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
+}
+
+#endif
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/disk_utils.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/disk_utils.cpp
new file mode 100644
index 0000000..a17d126
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/disk_utils.cpp
@@ -0,0 +1,1544 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "common_includes.h"
+
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+#include "gperftools/malloc_extension.h"
+#endif
+
+#ifdef __APPLE__
+#include <Accelerate/Accelerate.h>
+#else
+#include "mkl.h"
+#endif
+
+#include "logger.h"
+#include "disk_utils.h"
+#include "cached_io.h"
+#include "index.h"
+#include "omp.h"
+#include "percentile_stats.h"
+#include "partition.h"
+#include "pq_flash_index.h"
+#include "timer.h"
+#include "tsl/robin_set.h"
+
+namespace diskann
+{
+
+void add_new_file_to_single_index(std::string index_file, std::string new_file)
+{
+ std::unique_ptr<uint64_t[]> metadata;
+ size_t nr, nc;
+ diskann::load_bin<uint64_t>(index_file, metadata, nr, nc);
+ if (nc != 1)
+ {
+ std::stringstream stream;
+ stream << "Error, index file specified does not have correct metadata. " << std::endl;
+ throw diskann::ANNException(stream.str(), -1);
+ }
+ size_t index_ending_offset = metadata[nr - 1];
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ofstream writer(index_file, read_blk_size);
+ size_t check_file_size = get_file_size(index_file);
+ if (check_file_size != index_ending_offset)
+ {
+ std::stringstream stream;
+ stream << "Error, index file specified does not have correct metadata "
+ "(last entry must match the filesize). "
+ << std::endl;
+ throw diskann::ANNException(stream.str(), -1);
+ }
+
+ cached_ifstream reader(new_file, read_blk_size);
+ size_t fsize = reader.get_file_size();
+ if (fsize == 0)
+ {
+ std::stringstream stream;
+ stream << "Error, new file specified is empty. Not appending. " << std::endl;
+ throw diskann::ANNException(stream.str(), -1);
+ }
+
+ size_t num_blocks = DIV_ROUND_UP(fsize, read_blk_size);
+ char *dump = new char[read_blk_size];
+ for (uint64_t i = 0; i < num_blocks; i++)
+ {
+ size_t cur_block_size =
+ read_blk_size > fsize - (i * read_blk_size) ? fsize - (i * read_blk_size) : read_blk_size;
+ reader.read(dump, cur_block_size);
+ writer.write(dump, cur_block_size);
+ }
+ // reader.close();
+ // writer.close();
+
+ delete[] dump;
+ std::vector<uint64_t> new_meta;
+ for (uint64_t i = 0; i < nr; i++)
+ new_meta.push_back(metadata[i]);
+ new_meta.push_back(metadata[nr - 1] + fsize);
+
+ diskann::save_bin<uint64_t>(index_file, new_meta.data(), new_meta.size(), 1);
+}
+
+double get_memory_budget(double search_ram_budget)
+{
+ double final_index_ram_limit = search_ram_budget;
+ if (search_ram_budget - SPACE_FOR_CACHED_NODES_IN_GB > THRESHOLD_FOR_CACHING_IN_GB)
+ { // slack for space used by cached
+ // nodes
+ final_index_ram_limit = search_ram_budget - SPACE_FOR_CACHED_NODES_IN_GB;
+ }
+ return final_index_ram_limit * 1024 * 1024 * 1024;
+}
+
+double get_memory_budget(const std::string &mem_budget_str)
+{
+ double search_ram_budget = atof(mem_budget_str.c_str());
+ return get_memory_budget(search_ram_budget);
+}
+
+size_t calculate_num_pq_chunks(double final_index_ram_limit, size_t points_num, uint32_t dim,
+ const std::vector<std::string> &param_list)
+{
+ size_t num_pq_chunks = (size_t)(std::floor)(uint64_t(final_index_ram_limit / (double)points_num));
+ diskann::cout << "Calculated num_pq_chunks :" << num_pq_chunks << std::endl;
+ if (param_list.size() >= 6)
+ {
+ float compress_ratio = (float)atof(param_list[5].c_str());
+ if (compress_ratio > 0 && compress_ratio <= 1)
+ {
+ size_t chunks_by_cr = (size_t)(std::floor)(compress_ratio * dim);
+
+ if (chunks_by_cr > 0 && chunks_by_cr < num_pq_chunks)
+ {
+ diskann::cout << "Compress ratio:" << compress_ratio << " new #pq_chunks:" << chunks_by_cr << std::endl;
+ num_pq_chunks = chunks_by_cr;
+ }
+ else
+ {
+ diskann::cout << "Compress ratio: " << compress_ratio << " #new pq_chunks: " << chunks_by_cr
+ << " is either zero or greater than num_pq_chunks: " << num_pq_chunks
+ << ". num_pq_chunks is unchanged. " << std::endl;
+ }
+ }
+ else
+ {
+ diskann::cerr << "Compression ratio: " << compress_ratio << " should be in (0,1]" << std::endl;
+ }
+ }
+
+ num_pq_chunks = num_pq_chunks <= 0 ? 1 : num_pq_chunks;
+ num_pq_chunks = num_pq_chunks > dim ? dim : num_pq_chunks;
+ num_pq_chunks = num_pq_chunks > MAX_PQ_CHUNKS ? MAX_PQ_CHUNKS : num_pq_chunks;
+
+ diskann::cout << "Compressing " << dim << "-dimensional data into " << num_pq_chunks << " bytes per vector."
+ << std::endl;
+ return num_pq_chunks;
+}
+
+template <typename T> T *generateRandomWarmup(uint64_t warmup_num, uint64_t warmup_dim, uint64_t warmup_aligned_dim)
+{
+ T *warmup = nullptr;
+ warmup_num = 100000;
+ diskann::cout << "Generating random warmup file with dim " << warmup_dim << " and aligned dim "
+ << warmup_aligned_dim << std::flush;
+ diskann::alloc_aligned(((void **)&warmup), warmup_num * warmup_aligned_dim * sizeof(T), 8 * sizeof(T));
+ std::memset(warmup, 0, warmup_num * warmup_aligned_dim * sizeof(T));
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<> dis(-128, 127);
+ for (uint32_t i = 0; i < warmup_num; i++)
+ {
+ for (uint32_t d = 0; d < warmup_dim; d++)
+ {
+ warmup[i * warmup_aligned_dim + d] = (T)dis(gen);
+ }
+ }
+ diskann::cout << "..done" << std::endl;
+ return warmup;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T>
+T *load_warmup(MemoryMappedFiles &files, const std::string &cache_warmup_file, uint64_t &warmup_num,
+ uint64_t warmup_dim, uint64_t warmup_aligned_dim)
+{
+ T *warmup = nullptr;
+ uint64_t file_dim, file_aligned_dim;
+
+ if (files.fileExists(cache_warmup_file))
+ {
+ diskann::load_aligned_bin<T>(files, cache_warmup_file, warmup, warmup_num, file_dim, file_aligned_dim);
+ diskann::cout << "In the warmup file: " << cache_warmup_file << " File dim: " << file_dim
+ << " File aligned dim: " << file_aligned_dim << " Expected dim: " << warmup_dim
+ << " Expected aligned dim: " << warmup_aligned_dim << std::endl;
+
+ if (file_dim != warmup_dim || file_aligned_dim != warmup_aligned_dim)
+ {
+ std::stringstream stream;
+ stream << "Mismatched dimensions in sample file. file_dim = " << file_dim
+ << " file_aligned_dim: " << file_aligned_dim << " index_dim: " << warmup_dim
+ << " index_aligned_dim: " << warmup_aligned_dim << std::endl;
+ diskann::cerr << stream.str();
+ throw diskann::ANNException(stream.str(), -1);
+ }
+ }
+ else
+ {
+ warmup = generateRandomWarmup<T>(warmup_num, warmup_dim, warmup_aligned_dim);
+ }
+ return warmup;
+}
+#endif
+
+template <typename T>
+T *load_warmup(const std::string &cache_warmup_file, uint64_t &warmup_num, uint64_t warmup_dim,
+ uint64_t warmup_aligned_dim)
+{
+ T *warmup = nullptr;
+ size_t file_dim, file_aligned_dim;
+
+ if (file_exists(cache_warmup_file))
+ {
+ diskann::load_aligned_bin<T>(cache_warmup_file, warmup, (size_t &)warmup_num, file_dim, file_aligned_dim);
+ if (file_dim != warmup_dim || file_aligned_dim != warmup_aligned_dim)
+ {
+ std::stringstream stream;
+ stream << "Mismatched dimensions in sample file. file_dim = " << file_dim
+ << " file_aligned_dim: " << file_aligned_dim << " index_dim: " << warmup_dim
+ << " index_aligned_dim: " << warmup_aligned_dim << std::endl;
+ throw diskann::ANNException(stream.str(), -1);
+ }
+ }
+ else
+ {
+ warmup = generateRandomWarmup<T>(warmup_num, warmup_dim, warmup_aligned_dim);
+ }
+ return warmup;
+}
+
+/***************************************************
+ Support for Merging Many Vamana Indices
+ ***************************************************/
+
+void read_idmap(const std::string &fname, std::vector<uint32_t> &ivecs)
+{
+ uint32_t npts32, dim;
+ size_t actual_file_size = get_file_size(fname);
+ std::ifstream reader(fname.c_str(), std::ios::binary);
+ reader.read((char *)&npts32, sizeof(uint32_t));
+ reader.read((char *)&dim, sizeof(uint32_t));
+ if (dim != 1 || actual_file_size != ((size_t)npts32) * sizeof(uint32_t) + 2 * sizeof(uint32_t))
+ {
+ std::stringstream stream;
+ stream << "Error reading idmap file. Check if the file is bin file with "
+ "1 dimensional data. Actual: "
+ << actual_file_size << ", expected: " << (size_t)npts32 + 2 * sizeof(uint32_t) << std::endl;
+
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ ivecs.resize(npts32);
+ reader.read((char *)ivecs.data(), ((size_t)npts32) * sizeof(uint32_t));
+ reader.close();
+}
+
+int merge_shards(const std::string &vamana_prefix, const std::string &vamana_suffix, const std::string &idmaps_prefix,
+ const std::string &idmaps_suffix, const uint64_t nshards, uint32_t max_degree,
+ const std::string &output_vamana, const std::string &medoids_file, bool use_filters,
+ const std::string &labels_to_medoids_file)
+{
+ // Read ID maps
+ std::vector<std::string> vamana_names(nshards);
+ std::vector<std::vector<uint32_t>> idmaps(nshards);
+ for (uint64_t shard = 0; shard < nshards; shard++)
+ {
+ vamana_names[shard] = vamana_prefix + std::to_string(shard) + vamana_suffix;
+ read_idmap(idmaps_prefix + std::to_string(shard) + idmaps_suffix, idmaps[shard]);
+ }
+
+ // find max node id
+ size_t nnodes = 0;
+ size_t nelems = 0;
+ for (auto &idmap : idmaps)
+ {
+ for (auto &id : idmap)
+ {
+ nnodes = std::max(nnodes, (size_t)id);
+ }
+ nelems += idmap.size();
+ }
+ nnodes++;
+ diskann::cout << "# nodes: " << nnodes << ", max. degree: " << max_degree << std::endl;
+
+ // compute inverse map: node -> shards
+ std::vector<std::pair<uint32_t, uint32_t>> node_shard;
+ node_shard.reserve(nelems);
+ for (size_t shard = 0; shard < nshards; shard++)
+ {
+ diskann::cout << "Creating inverse map -- shard #" << shard << std::endl;
+ for (size_t idx = 0; idx < idmaps[shard].size(); idx++)
+ {
+ size_t node_id = idmaps[shard][idx];
+ node_shard.push_back(std::make_pair((uint32_t)node_id, (uint32_t)shard));
+ }
+ }
+ std::sort(node_shard.begin(), node_shard.end(), [](const auto &left, const auto &right) {
+ return left.first < right.first || (left.first == right.first && left.second < right.second);
+ });
+ diskann::cout << "Finished computing node -> shards map" << std::endl;
+
+ // will merge all the labels to medoids files of each shard into one
+ // combined file
+ if (use_filters)
+ {
+ std::unordered_map<uint32_t, std::vector<uint32_t>> global_label_to_medoids;
+
+ for (size_t i = 0; i < nshards; i++)
+ {
+ std::ifstream mapping_reader;
+ std::string map_file = vamana_names[i] + "_labels_to_medoids.txt";
+ mapping_reader.open(map_file);
+
+ std::string line, token;
+ uint32_t line_cnt = 0;
+
+ while (std::getline(mapping_reader, line))
+ {
+ std::istringstream iss(line);
+ uint32_t cnt = 0;
+ uint32_t medoid = 0;
+ uint32_t label = 0;
+ while (std::getline(iss, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+
+ uint32_t token_as_num = std::stoul(token);
+
+ if (cnt == 0)
+ label = token_as_num;
+ else
+ medoid = token_as_num;
+ cnt++;
+ }
+ global_label_to_medoids[label].push_back(idmaps[i][medoid]);
+ line_cnt++;
+ }
+ mapping_reader.close();
+ }
+
+ std::ofstream mapping_writer(labels_to_medoids_file);
+ assert(mapping_writer.is_open());
+ for (auto iter : global_label_to_medoids)
+ {
+ mapping_writer << iter.first << ", ";
+ auto &vec = iter.second;
+ for (uint32_t idx = 0; idx < vec.size() - 1; idx++)
+ {
+ mapping_writer << vec[idx] << ", ";
+ }
+ mapping_writer << vec[vec.size() - 1] << std::endl;
+ }
+ mapping_writer.close();
+ }
+
+ // create cached vamana readers
+ std::vector<cached_ifstream> vamana_readers(nshards);
+ for (size_t i = 0; i < nshards; i++)
+ {
+ vamana_readers[i].open(vamana_names[i], BUFFER_SIZE_FOR_CACHED_IO);
+ size_t expected_file_size;
+ vamana_readers[i].read((char *)&expected_file_size, sizeof(uint64_t));
+ }
+
+ size_t vamana_metadata_size =
+ sizeof(uint64_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint64_t); // expected file size + max degree +
+ // medoid_id + frozen_point info
+
+ // create cached vamana writers
+ cached_ofstream merged_vamana_writer(output_vamana, BUFFER_SIZE_FOR_CACHED_IO);
+
+ size_t merged_index_size = vamana_metadata_size; // we initialize the size of the merged index to
+ // the metadata size
+ size_t merged_index_frozen = 0;
+ merged_vamana_writer.write((char *)&merged_index_size,
+ sizeof(uint64_t)); // we will overwrite the index size at the end
+
+ uint32_t output_width = max_degree;
+ uint32_t max_input_width = 0;
+ // read width from each vamana to advance buffer by sizeof(uint32_t) bytes
+ for (auto &reader : vamana_readers)
+ {
+ uint32_t input_width;
+ reader.read((char *)&input_width, sizeof(uint32_t));
+ max_input_width = input_width > max_input_width ? input_width : max_input_width;
+ }
+
+ diskann::cout << "Max input width: " << max_input_width << ", output width: " << output_width << std::endl;
+
+ merged_vamana_writer.write((char *)&output_width, sizeof(uint32_t));
+ std::ofstream medoid_writer(medoids_file.c_str(), std::ios::binary);
+ uint32_t nshards_u32 = (uint32_t)nshards;
+ uint32_t one_val = 1;
+ medoid_writer.write((char *)&nshards_u32, sizeof(uint32_t));
+ medoid_writer.write((char *)&one_val, sizeof(uint32_t));
+
+ uint64_t vamana_index_frozen = 0; // as of now the functionality to merge many overlapping vamana
+ // indices is supported only for bulk indices without frozen point.
+ // Hence the final index will also not have any frozen points.
+ for (uint64_t shard = 0; shard < nshards; shard++)
+ {
+ uint32_t medoid;
+ // read medoid
+ vamana_readers[shard].read((char *)&medoid, sizeof(uint32_t));
+ vamana_readers[shard].read((char *)&vamana_index_frozen, sizeof(uint64_t));
+ assert(vamana_index_frozen == false);
+ // rename medoid
+ medoid = idmaps[shard][medoid];
+
+ medoid_writer.write((char *)&medoid, sizeof(uint32_t));
+ // write renamed medoid
+ if (shard == (nshards - 1)) //--> uncomment if running hierarchical
+ merged_vamana_writer.write((char *)&medoid, sizeof(uint32_t));
+ }
+ merged_vamana_writer.write((char *)&merged_index_frozen, sizeof(uint64_t));
+ medoid_writer.close();
+
+ diskann::cout << "Starting merge" << std::endl;
+
+ // Gopal. random_shuffle() is deprecated.
+ std::random_device rng;
+ std::mt19937 urng(rng());
+
+ std::vector<bool> nhood_set(nnodes, 0);
+ std::vector<uint32_t> final_nhood;
+
+ uint32_t nnbrs = 0, shard_nnbrs = 0;
+ uint32_t cur_id = 0;
+ for (const auto &id_shard : node_shard)
+ {
+ uint32_t node_id = id_shard.first;
+ uint32_t shard_id = id_shard.second;
+ if (cur_id < node_id)
+ {
+ // Gopal. random_shuffle() is deprecated.
+ std::shuffle(final_nhood.begin(), final_nhood.end(), urng);
+ nnbrs = (uint32_t)(std::min)(final_nhood.size(), (size_t)max_degree);
+ // write into merged ofstream
+ merged_vamana_writer.write((char *)&nnbrs, sizeof(uint32_t));
+ merged_vamana_writer.write((char *)final_nhood.data(), nnbrs * sizeof(uint32_t));
+ merged_index_size += (sizeof(uint32_t) + nnbrs * sizeof(uint32_t));
+ if (cur_id % 499999 == 1)
+ {
+ diskann::cout << "." << std::flush;
+ }
+ cur_id = node_id;
+ nnbrs = 0;
+ for (auto &p : final_nhood)
+ nhood_set[p] = 0;
+ final_nhood.clear();
+ }
+ // read from shard_id ifstream
+ vamana_readers[shard_id].read((char *)&shard_nnbrs, sizeof(uint32_t));
+
+ if (shard_nnbrs == 0)
+ {
+ diskann::cout << "WARNING: shard #" << shard_id << ", node_id " << node_id << " has 0 nbrs" << std::endl;
+ }
+
+ std::vector<uint32_t> shard_nhood(shard_nnbrs);
+ if (shard_nnbrs > 0)
+ vamana_readers[shard_id].read((char *)shard_nhood.data(), shard_nnbrs * sizeof(uint32_t));
+ // rename nodes
+ for (uint64_t j = 0; j < shard_nnbrs; j++)
+ {
+ if (nhood_set[idmaps[shard_id][shard_nhood[j]]] == 0)
+ {
+ nhood_set[idmaps[shard_id][shard_nhood[j]]] = 1;
+ final_nhood.emplace_back(idmaps[shard_id][shard_nhood[j]]);
+ }
+ }
+ }
+
+ // Gopal. random_shuffle() is deprecated.
+ std::shuffle(final_nhood.begin(), final_nhood.end(), urng);
+ nnbrs = (uint32_t)(std::min)(final_nhood.size(), (size_t)max_degree);
+ // write into merged ofstream
+ merged_vamana_writer.write((char *)&nnbrs, sizeof(uint32_t));
+ if (nnbrs > 0)
+ {
+ merged_vamana_writer.write((char *)final_nhood.data(), nnbrs * sizeof(uint32_t));
+ }
+ merged_index_size += (sizeof(uint32_t) + nnbrs * sizeof(uint32_t));
+ for (auto &p : final_nhood)
+ nhood_set[p] = 0;
+ final_nhood.clear();
+
+ diskann::cout << "Expected size: " << merged_index_size << std::endl;
+
+ merged_vamana_writer.reset();
+ merged_vamana_writer.write((char *)&merged_index_size, sizeof(uint64_t));
+
+ diskann::cout << "Finished merge" << std::endl;
+ return 0;
+}
+
+// TODO: Make this a streaming implementation to avoid exceeding the memory
+// budget
+/* If the number of filters per point N exceeds the graph degree R,
+ then it is difficult to have edges to all labels from this point.
+ This function break up such dense points to have only a threshold of maximum
+ T labels per point It divides one graph nodes to multiple nodes and append
+ the new nodes at the end. The dummy map contains the real graph id of the
+ new nodes added to the graph */
+template <typename T>
+void breakup_dense_points(const std::string data_file, const std::string labels_file, uint32_t density,
+ const std::string out_data_file, const std::string out_labels_file,
+ const std::string out_metadata_file)
+{
+ std::string token, line;
+ std::ifstream labels_stream(labels_file);
+ T *data;
+ size_t npts, ndims;
+ diskann::load_bin<T>(data_file, data, npts, ndims);
+
+ std::unordered_map<uint32_t, uint32_t> dummy_pt_ids;
+ uint32_t next_dummy_id = (uint32_t)npts;
+
+ uint32_t point_cnt = 0;
+
+ std::vector<std::vector<uint32_t>> labels_per_point;
+ labels_per_point.resize(npts);
+
+ uint32_t dense_pts = 0;
+ if (labels_stream.is_open())
+ {
+ while (getline(labels_stream, line))
+ {
+ std::stringstream iss(line);
+ uint32_t lbl_cnt = 0;
+ uint32_t label_host = point_cnt;
+ while (getline(iss, token, ','))
+ {
+ if (lbl_cnt == density)
+ {
+ if (label_host == point_cnt)
+ dense_pts++;
+ label_host = next_dummy_id;
+ labels_per_point.resize(next_dummy_id + 1);
+ dummy_pt_ids[next_dummy_id] = (uint32_t)point_cnt;
+ next_dummy_id++;
+ lbl_cnt = 0;
+ }
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ uint32_t token_as_num = std::stoul(token);
+ labels_per_point[label_host].push_back(token_as_num);
+ lbl_cnt++;
+ }
+ point_cnt++;
+ }
+ }
+ diskann::cout << "fraction of dense points with >= " << density << " labels = " << (float)dense_pts / (float)npts
+ << std::endl;
+
+ if (labels_per_point.size() != 0)
+ {
+ diskann::cout << labels_per_point.size() << " is the new number of points" << std::endl;
+ std::ofstream label_writer(out_labels_file);
+ assert(label_writer.is_open());
+ for (uint32_t i = 0; i < labels_per_point.size(); i++)
+ {
+ for (uint32_t j = 0; j < (labels_per_point[i].size() - 1); j++)
+ {
+ label_writer << labels_per_point[i][j] << ",";
+ }
+ if (labels_per_point[i].size() != 0)
+ label_writer << labels_per_point[i][labels_per_point[i].size() - 1];
+ label_writer << std::endl;
+ }
+ label_writer.close();
+ }
+
+ if (dummy_pt_ids.size() != 0)
+ {
+ diskann::cout << dummy_pt_ids.size() << " is the number of dummy points created" << std::endl;
+
+ T *ptr = (T *)std::realloc((void *)data, labels_per_point.size() * ndims * sizeof(T));
+ if (ptr == nullptr)
+ {
+ diskann::cerr << "Realloc failed while creating dummy points" << std::endl;
+ free(data);
+ data = nullptr;
+ throw new diskann::ANNException("Realloc failed while expanding data.", -1, __FUNCTION__, __FILE__,
+ __LINE__);
+ }
+ else
+ {
+ data = ptr;
+ }
+
+ std::ofstream dummy_writer(out_metadata_file);
+ assert(dummy_writer.is_open());
+ for (auto i = dummy_pt_ids.begin(); i != dummy_pt_ids.end(); i++)
+ {
+ dummy_writer << i->first << "," << i->second << std::endl;
+ std::memcpy(data + i->first * ndims, data + i->second * ndims, ndims * sizeof(T));
+ }
+ dummy_writer.close();
+ }
+
+ diskann::save_bin<T>(out_data_file, data, labels_per_point.size(), ndims);
+}
+
+void extract_shard_labels(const std::string &in_label_file, const std::string &shard_ids_bin,
+ const std::string &shard_label_file)
+{ // assumes ith row is for ith
+ // point in labels file
+ diskann::cout << "Extracting labels for shard" << std::endl;
+
+ uint32_t *ids = nullptr;
+ size_t num_ids, tmp_dim;
+ diskann::load_bin(shard_ids_bin, ids, num_ids, tmp_dim);
+
+ uint32_t counter = 0, shard_counter = 0;
+ std::string cur_line;
+
+ std::ifstream label_reader(in_label_file);
+ std::ofstream label_writer(shard_label_file);
+ assert(label_reader.is_open());
+ assert(label_reader.is_open());
+ if (label_reader && label_writer)
+ {
+ while (std::getline(label_reader, cur_line))
+ {
+ if (shard_counter >= num_ids)
+ {
+ break;
+ }
+ if (counter == ids[shard_counter])
+ {
+ label_writer << cur_line << "\n";
+ shard_counter++;
+ }
+ counter++;
+ }
+ }
+ if (ids != nullptr)
+ delete[] ids;
+}
+
+template <typename T, typename LabelT>
+int build_merged_vamana_index(std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R,
+ double sampling_rate, double ram_budget, std::string mem_index_path,
+ std::string medoids_file, std::string centroids_file, size_t build_pq_bytes, bool use_opq,
+ uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label,
+ const uint32_t Lf)
+{
+ size_t base_num, base_dim;
+ diskann::get_bin_metadata(base_file, base_num, base_dim);
+
+ double full_index_ram = estimate_ram_usage(base_num, (uint32_t)base_dim, sizeof(T), R);
+
+ // TODO: Make this honest when there is filter support
+ if (full_index_ram < ram_budget * 1024 * 1024 * 1024)
+ {
+ diskann::cout << "Full index fits in RAM budget, should consume at most "
+ << full_index_ram / (1024 * 1024 * 1024) << "GiBs, so building in one shot" << std::endl;
+
+ diskann::IndexWriteParameters paras = diskann::IndexWriteParametersBuilder(L, R)
+ .with_filter_list_size(Lf)
+ .with_saturate_graph(!use_filters)
+ .with_num_threads(num_threads)
+ .build();
+ using TagT = uint32_t;
+ diskann::Index<T, TagT, LabelT> _index(compareMetric, base_dim, base_num,
+ std::make_shared<diskann::IndexWriteParameters>(paras), nullptr,
+ defaults::NUM_FROZEN_POINTS_STATIC, false, false, false,
+ build_pq_bytes > 0, build_pq_bytes, use_opq, use_filters);
+ if (!use_filters)
+ _index.build(base_file.c_str(), base_num);
+ else
+ {
+ if (universal_label != "")
+ { // indicates no universal label
+ LabelT unv_label_as_num = 0;
+ _index.set_universal_label(unv_label_as_num);
+ }
+ _index.build_filtered_index(base_file.c_str(), label_file, base_num);
+ }
+ _index.save(mem_index_path.c_str());
+
+ if (use_filters)
+ {
+ // need to copy the labels_to_medoids file to the specified input
+ // file
+ std::remove(labels_to_medoids_file.c_str());
+ std::string mem_labels_to_medoid_file = mem_index_path + "_labels_to_medoids.txt";
+ copy_file(mem_labels_to_medoid_file, labels_to_medoids_file);
+ std::remove(mem_labels_to_medoid_file.c_str());
+ }
+
+ std::remove(medoids_file.c_str());
+ std::remove(centroids_file.c_str());
+ return 0;
+ }
+
+ diskann::cout << "Full index does not fit in RAM budget, building in multiple shots" << std::endl;
+
+ // where the universal label is to be saved in the final graph
+ std::string final_index_universal_label_file = mem_index_path + "_universal_label.txt";
+
+ std::string merged_index_prefix = mem_index_path + "_tempFiles";
+
+ Timer timer;
+ int num_parts =
+ partition_with_ram_budget<T>(base_file, sampling_rate, ram_budget, 2 * R / 3, merged_index_prefix, 2);
+ diskann::cout << timer.elapsed_seconds_for_step("partitioning data ") << std::endl;
+
+ std::string cur_centroid_filepath = merged_index_prefix + "_centroids.bin";
+ std::rename(cur_centroid_filepath.c_str(), centroids_file.c_str());
+
+ timer.reset();
+ for (int p = 0; p < num_parts; p++)
+ {
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+ MallocExtension::instance()->ReleaseFreeMemory();
+#endif
+
+ std::string shard_base_file = merged_index_prefix + "_subshard-" + std::to_string(p) + ".bin";
+
+ std::string shard_ids_file = merged_index_prefix + "_subshard-" + std::to_string(p) + "_ids_uint32.bin";
+
+ std::string shard_labels_file = merged_index_prefix + "_subshard-" + std::to_string(p) + "_labels.txt";
+
+ retrieve_shard_data_from_ids<T>(base_file, shard_ids_file, shard_base_file);
+
+ std::string shard_index_file = merged_index_prefix + "_subshard-" + std::to_string(p) + "_mem.index";
+
+ diskann::IndexWriteParameters low_degree_params = diskann::IndexWriteParametersBuilder(L, 2 * R / 3)
+ .with_filter_list_size(Lf)
+ .with_saturate_graph(false)
+ .with_num_threads(num_threads)
+ .build();
+
+ size_t shard_base_dim, shard_base_pts;
+ get_bin_metadata(shard_base_file, shard_base_pts, shard_base_dim);
+
+ diskann::Index<T> _index(compareMetric, shard_base_dim, shard_base_pts,
+ std::make_shared<diskann::IndexWriteParameters>(low_degree_params), nullptr,
+ defaults::NUM_FROZEN_POINTS_STATIC, false, false, false, build_pq_bytes > 0,
+ build_pq_bytes, use_opq);
+ if (!use_filters)
+ {
+ _index.build(shard_base_file.c_str(), shard_base_pts);
+ }
+ else
+ {
+ diskann::extract_shard_labels(label_file, shard_ids_file, shard_labels_file);
+ if (universal_label != "")
+ { // indicates no universal label
+ LabelT unv_label_as_num = 0;
+ _index.set_universal_label(unv_label_as_num);
+ }
+ _index.build_filtered_index(shard_base_file.c_str(), shard_labels_file, shard_base_pts);
+ }
+
+ // cal deg stats
+ size_t max_deg = 0, min_deg = SIZE_MAX, avg_deg = 0, cnt_deg = 0;
+ _index.get_degree_stats(max_deg, min_deg, avg_deg, cnt_deg);
+ std::cout << "! For shard " << p << " Degree stats: " << max_deg << ", " << min_deg << ", " << avg_deg << ", "
+ << cnt_deg << std::endl;
+ std::string shard_degree_stats_file = shard_index_file + "_degree_stats.txt";
+ _index.dump_degree_stats(shard_degree_stats_file);
+
+ _index.save(shard_index_file.c_str());
+ // copy universal label file from first shard to the final destination
+ // index, since all shards anyway share the universal label
+ if (p == 0)
+ {
+ std::string shard_universal_label_file = shard_index_file + "_universal_label.txt";
+ if (universal_label != "")
+ {
+ copy_file(shard_universal_label_file, final_index_universal_label_file);
+ }
+ }
+
+ std::remove(shard_base_file.c_str());
+ }
+ diskann::cout << timer.elapsed_seconds_for_step("building indices on shards") << std::endl;
+
+ timer.reset();
+ diskann::merge_shards(merged_index_prefix + "_subshard-", "_mem.index", merged_index_prefix + "_subshard-",
+ "_ids_uint32.bin", num_parts, R, mem_index_path, medoids_file, use_filters,
+ labels_to_medoids_file);
+ diskann::cout << timer.elapsed_seconds_for_step("merging indices") << std::endl;
+
+ // delete tempFiles
+ for (int p = 0; p < num_parts; p++)
+ {
+ std::string shard_base_file = merged_index_prefix + "_subshard-" + std::to_string(p) + ".bin";
+ std::string shard_id_file = merged_index_prefix + "_subshard-" + std::to_string(p) + "_ids_uint32.bin";
+ std::string shard_labels_file = merged_index_prefix + "_subshard-" + std::to_string(p) + "_labels.txt";
+ std::string shard_index_file = merged_index_prefix + "_subshard-" + std::to_string(p) + "_mem.index";
+ std::string shard_index_file_data = shard_index_file + ".data";
+
+ // std::remove(shard_base_file.c_str());
+ // std::remove(shard_id_file.c_str());
+ // std::remove(shard_index_file.c_str());
+ // std::remove(shard_index_file_data.c_str());
+ if (use_filters)
+ {
+ std::string shard_index_label_file = shard_index_file + "_labels.txt";
+ std::string shard_index_univ_label_file = shard_index_file + "_universal_label.txt";
+ std::string shard_index_label_map_file = shard_index_file + "_labels_to_medoids.txt";
+ std::remove(shard_labels_file.c_str());
+ std::remove(shard_index_label_file.c_str());
+ std::remove(shard_index_label_map_file.c_str());
+ std::remove(shard_index_univ_label_file.c_str());
+ }
+ }
+ return 0;
+}
+
+// General purpose support for DiskANN interface
+
+// optimizes the beamwidth to maximize QPS for a given L_search subject to
+// 99.9 latency not blowing up
+template <typename T, typename LabelT>
+uint32_t optimize_beamwidth(std::unique_ptr<diskann::PQFlashIndex<T, LabelT>> &pFlashIndex, T *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L,
+ uint32_t nthreads, uint32_t start_bw)
+{
+ uint32_t cur_bw = start_bw;
+ double max_qps = 0;
+ uint32_t best_bw = start_bw;
+ bool stop_flag = false;
+
+ while (!stop_flag)
+ {
+ std::vector<uint64_t> tuning_sample_result_ids_64(tuning_sample_num, 0);
+ std::vector<float> tuning_sample_result_dists(tuning_sample_num, 0);
+ diskann::QueryStats *stats = new diskann::QueryStats[tuning_sample_num];
+
+ auto s = std::chrono::high_resolution_clock::now();
+#pragma omp parallel for schedule(dynamic, 1) num_threads(nthreads)
+ for (int64_t i = 0; i < (int64_t)tuning_sample_num; i++)
+ {
+ pFlashIndex->cached_beam_search(tuning_sample + (i * tuning_sample_aligned_dim), 1, L,
+ tuning_sample_result_ids_64.data() + (i * 1),
+ tuning_sample_result_dists.data() + (i * 1), cur_bw, false, stats + i);
+ }
+ auto e = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diff = e - s;
+ double qps = (1.0f * (float)tuning_sample_num) / (1.0f * (float)diff.count());
+
+ double lat_999 = diskann::get_percentile_stats<float>(
+ stats, tuning_sample_num, 0.999f, [](const diskann::QueryStats &stats) { return stats.total_us; });
+
+ double mean_latency = diskann::get_mean_stats<float>(
+ stats, tuning_sample_num, [](const diskann::QueryStats &stats) { return stats.total_us; });
+
+ if (qps > max_qps && lat_999 < (15000) + mean_latency * 2)
+ {
+ max_qps = qps;
+ best_bw = cur_bw;
+ cur_bw = (uint32_t)(std::ceil)((float)cur_bw * 1.1f);
+ }
+ else
+ {
+ stop_flag = true;
+ }
+ if (cur_bw > 64)
+ stop_flag = true;
+
+ delete[] stats;
+ }
+ return best_bw;
+}
+
+template <typename T>
+void create_disk_layout(const std::string base_file, const std::string mem_index_file, const std::string output_file,
+ const std::string reorder_data_file)
+{
+ uint32_t npts, ndims;
+
+ // amount to read or write in one shot
+ size_t read_blk_size = 64 * 1024 * 1024;
+ size_t write_blk_size = read_blk_size;
+ cached_ifstream base_reader(base_file, read_blk_size);
+ base_reader.read((char *)&npts, sizeof(uint32_t));
+ base_reader.read((char *)&ndims, sizeof(uint32_t));
+
+ size_t npts_64, ndims_64;
+ npts_64 = npts;
+ ndims_64 = ndims;
+
+ // Check if we need to append data for re-ordering
+ bool append_reorder_data = false;
+ std::ifstream reorder_data_reader;
+
+ uint32_t npts_reorder_file = 0, ndims_reorder_file = 0;
+ if (reorder_data_file != std::string(""))
+ {
+ append_reorder_data = true;
+ size_t reorder_data_file_size = get_file_size(reorder_data_file);
+ reorder_data_reader.exceptions(std::ofstream::failbit | std::ofstream::badbit);
+
+ try
+ {
+ reorder_data_reader.open(reorder_data_file, std::ios::binary);
+ reorder_data_reader.read((char *)&npts_reorder_file, sizeof(uint32_t));
+ reorder_data_reader.read((char *)&ndims_reorder_file, sizeof(uint32_t));
+ if (npts_reorder_file != npts)
+ throw ANNException("Mismatch in num_points between reorder "
+ "data file and base file",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ if (reorder_data_file_size != 8 + sizeof(float) * (size_t)npts_reorder_file * (size_t)ndims_reorder_file)
+ throw ANNException("Discrepancy in reorder data file size ", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ catch (std::system_error &e)
+ {
+ throw FileException(reorder_data_file, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+
+ // create cached reader + writer
+ size_t actual_file_size = get_file_size(mem_index_file);
+ diskann::cout << "Vamana index file size=" << actual_file_size << std::endl;
+ std::ifstream vamana_reader(mem_index_file, std::ios::binary);
+ cached_ofstream diskann_writer(output_file, write_blk_size);
+
+ // metadata: width, medoid
+ uint32_t width_u32, medoid_u32;
+ size_t index_file_size;
+
+ vamana_reader.read((char *)&index_file_size, sizeof(uint64_t));
+ if (index_file_size != actual_file_size)
+ {
+ std::stringstream stream;
+ stream << "Vamana Index file size does not match expected size per "
+ "meta-data."
+ << " file size from file: " << index_file_size << " actual file size: " << actual_file_size << std::endl;
+
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ uint64_t vamana_frozen_num = false, vamana_frozen_loc = 0;
+
+ vamana_reader.read((char *)&width_u32, sizeof(uint32_t));
+ vamana_reader.read((char *)&medoid_u32, sizeof(uint32_t));
+ vamana_reader.read((char *)&vamana_frozen_num, sizeof(uint64_t));
+ // compute
+ uint64_t medoid, max_node_len, nnodes_per_sector;
+ npts_64 = (uint64_t)npts;
+ medoid = (uint64_t)medoid_u32;
+ if (vamana_frozen_num == 1)
+ vamana_frozen_loc = medoid;
+ max_node_len = (((uint64_t)width_u32 + 1) * sizeof(uint32_t)) + (ndims_64 * sizeof(T));
+ nnodes_per_sector = defaults::SECTOR_LEN / max_node_len; // 0 if max_node_len > SECTOR_LEN
+
+ diskann::cout << "medoid: " << medoid << "B" << std::endl;
+ diskann::cout << "max_node_len: " << max_node_len << "B" << std::endl;
+ diskann::cout << "nnodes_per_sector: " << nnodes_per_sector << "B" << std::endl;
+
+ // defaults::SECTOR_LEN buffer for each sector
+ std::unique_ptr<char[]> sector_buf = std::make_unique<char[]>(defaults::SECTOR_LEN);
+ std::unique_ptr<char[]> multisector_buf = std::make_unique<char[]>(ROUND_UP(max_node_len, defaults::SECTOR_LEN));
+ std::unique_ptr<char[]> node_buf = std::make_unique<char[]>(max_node_len);
+ uint32_t &nnbrs = *(uint32_t *)(node_buf.get() + ndims_64 * sizeof(T));
+ uint32_t *nhood_buf = (uint32_t *)(node_buf.get() + (ndims_64 * sizeof(T)) + sizeof(uint32_t));
+
+ // number of sectors (1 for meta data)
+ uint64_t n_sectors = nnodes_per_sector > 0 ? ROUND_UP(npts_64, nnodes_per_sector) / nnodes_per_sector
+ : npts_64 * DIV_ROUND_UP(max_node_len, defaults::SECTOR_LEN);
+ uint64_t n_reorder_sectors = 0;
+ uint64_t n_data_nodes_per_sector = 0;
+
+ if (append_reorder_data)
+ {
+ n_data_nodes_per_sector = defaults::SECTOR_LEN / (ndims_reorder_file * sizeof(float));
+ n_reorder_sectors = ROUND_UP(npts_64, n_data_nodes_per_sector) / n_data_nodes_per_sector;
+ }
+ uint64_t disk_index_file_size = (n_sectors + n_reorder_sectors + 1) * defaults::SECTOR_LEN;
+
+ std::vector<uint64_t> output_file_meta;
+ output_file_meta.push_back(npts_64);
+ output_file_meta.push_back(ndims_64);
+ output_file_meta.push_back(medoid);
+ output_file_meta.push_back(max_node_len);
+ output_file_meta.push_back(nnodes_per_sector);
+ output_file_meta.push_back(vamana_frozen_num);
+ output_file_meta.push_back(vamana_frozen_loc);
+ output_file_meta.push_back((uint64_t)append_reorder_data);
+ if (append_reorder_data)
+ {
+ output_file_meta.push_back(n_sectors + 1);
+ output_file_meta.push_back(ndims_reorder_file);
+ output_file_meta.push_back(n_data_nodes_per_sector);
+ }
+ output_file_meta.push_back(disk_index_file_size);
+
+ diskann_writer.write(sector_buf.get(), defaults::SECTOR_LEN);
+
+ std::unique_ptr<T[]> cur_node_coords = std::make_unique<T[]>(ndims_64);
+ diskann::cout << "# sectors: " << n_sectors << std::endl;
+ uint64_t cur_node_id = 0;
+
+ if (nnodes_per_sector > 0)
+ { // Write multiple nodes per sector
+ for (uint64_t sector = 0; sector < n_sectors; sector++)
+ {
+ if (sector % 100000 == 0)
+ {
+ diskann::cout << "Sector #" << sector << "written" << std::endl;
+ }
+ memset(sector_buf.get(), 0, defaults::SECTOR_LEN);
+ for (uint64_t sector_node_id = 0; sector_node_id < nnodes_per_sector && cur_node_id < npts_64;
+ sector_node_id++)
+ {
+ memset(node_buf.get(), 0, max_node_len);
+ // read cur node's nnbrs
+ vamana_reader.read((char *)&nnbrs, sizeof(uint32_t));
+
+ // sanity checks on nnbrs
+ assert(nnbrs > 0);
+ assert(nnbrs <= width_u32);
+
+ // read node's nhood
+ vamana_reader.read((char *)nhood_buf, (std::min)(nnbrs, width_u32) * sizeof(uint32_t));
+ if (nnbrs > width_u32)
+ {
+ vamana_reader.seekg((nnbrs - width_u32) * sizeof(uint32_t), vamana_reader.cur);
+ }
+
+ // write coords of node first
+ // T *node_coords = data + ((uint64_t) ndims_64 * cur_node_id);
+ base_reader.read((char *)cur_node_coords.get(), sizeof(T) * ndims_64);
+ memcpy(node_buf.get(), cur_node_coords.get(), ndims_64 * sizeof(T));
+
+ // write nnbrs
+ *(uint32_t *)(node_buf.get() + ndims_64 * sizeof(T)) = (std::min)(nnbrs, width_u32);
+
+ // write nhood next
+ memcpy(node_buf.get() + ndims_64 * sizeof(T) + sizeof(uint32_t), nhood_buf,
+ (std::min)(nnbrs, width_u32) * sizeof(uint32_t));
+
+ // get offset into sector_buf
+ char *sector_node_buf = sector_buf.get() + (sector_node_id * max_node_len);
+
+ // copy node buf into sector_node_buf
+ memcpy(sector_node_buf, node_buf.get(), max_node_len);
+ cur_node_id++;
+ }
+ // flush sector to disk
+ diskann_writer.write(sector_buf.get(), defaults::SECTOR_LEN);
+ }
+ }
+ else
+ { // Write multi-sector nodes
+ uint64_t nsectors_per_node = DIV_ROUND_UP(max_node_len, defaults::SECTOR_LEN);
+ for (uint64_t i = 0; i < npts_64; i++)
+ {
+ if ((i * nsectors_per_node) % 100000 == 0)
+ {
+ diskann::cout << "Sector #" << i * nsectors_per_node << "written" << std::endl;
+ }
+ memset(multisector_buf.get(), 0, nsectors_per_node * defaults::SECTOR_LEN);
+
+ memset(node_buf.get(), 0, max_node_len);
+ // read cur node's nnbrs
+ vamana_reader.read((char *)&nnbrs, sizeof(uint32_t));
+
+ // sanity checks on nnbrs
+ assert(nnbrs > 0);
+ assert(nnbrs <= width_u32);
+
+ // read node's nhood
+ vamana_reader.read((char *)nhood_buf, (std::min)(nnbrs, width_u32) * sizeof(uint32_t));
+ if (nnbrs > width_u32)
+ {
+ vamana_reader.seekg((nnbrs - width_u32) * sizeof(uint32_t), vamana_reader.cur);
+ }
+
+ // write coords of node first
+ // T *node_coords = data + ((uint64_t) ndims_64 * cur_node_id);
+ base_reader.read((char *)cur_node_coords.get(), sizeof(T) * ndims_64);
+ memcpy(multisector_buf.get(), cur_node_coords.get(), ndims_64 * sizeof(T));
+
+ // write nnbrs
+ *(uint32_t *)(multisector_buf.get() + ndims_64 * sizeof(T)) = (std::min)(nnbrs, width_u32);
+
+ // write nhood next
+ memcpy(multisector_buf.get() + ndims_64 * sizeof(T) + sizeof(uint32_t), nhood_buf,
+ (std::min)(nnbrs, width_u32) * sizeof(uint32_t));
+
+ // flush sector to disk
+ diskann_writer.write(multisector_buf.get(), nsectors_per_node * defaults::SECTOR_LEN);
+ }
+ }
+
+ if (append_reorder_data)
+ {
+ diskann::cout << "Index written. Appending reorder data..." << std::endl;
+
+ auto vec_len = ndims_reorder_file * sizeof(float);
+ std::unique_ptr<char[]> vec_buf = std::make_unique<char[]>(vec_len);
+
+ for (uint64_t sector = 0; sector < n_reorder_sectors; sector++)
+ {
+ if (sector % 100000 == 0)
+ {
+ diskann::cout << "Reorder data Sector #" << sector << "written" << std::endl;
+ }
+
+ memset(sector_buf.get(), 0, defaults::SECTOR_LEN);
+
+ for (uint64_t sector_node_id = 0; sector_node_id < n_data_nodes_per_sector && sector_node_id < npts_64;
+ sector_node_id++)
+ {
+ memset(vec_buf.get(), 0, vec_len);
+ reorder_data_reader.read(vec_buf.get(), vec_len);
+
+ // copy node buf into sector_node_buf
+ memcpy(sector_buf.get() + (sector_node_id * vec_len), vec_buf.get(), vec_len);
+ }
+ // flush sector to disk
+ diskann_writer.write(sector_buf.get(), defaults::SECTOR_LEN);
+ }
+ }
+ diskann_writer.close();
+ diskann::save_bin<uint64_t>(output_file, output_file_meta.data(), output_file_meta.size(), 1, 0);
+ diskann::cout << "Output disk index file written to " << output_file << std::endl;
+}
+
+template <typename T, typename LabelT>
+int build_disk_index(const char *dataFilePath, const char *indexFilePath, const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq, const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file, const std::string &universal_label, const uint32_t filter_threshold,
+ const uint32_t Lf)
+{
+ std::stringstream parser;
+ parser << std::string(indexBuildParameters);
+ std::string cur_param;
+ std::vector<std::string> param_list;
+ while (parser >> cur_param)
+ {
+ param_list.push_back(cur_param);
+ }
+ if (param_list.size() < 5 || param_list.size() > 9)
+ {
+ diskann::cout << "Correct usage of parameters is R (max degree)\n"
+ "L (indexing list size, better if >= R)\n"
+ "B (RAM limit of final index in GB)\n" // search
+ "M (memory limit while indexing)\n" // build
+ "T (number of threads for indexing)\n"
+ "B' (PQ bytes for disk index: optional parameter for "
+ "very large dimensional data)\n"
+ "reorder (set true to include full precision in data file"
+ ": optional paramter, use only when using disk PQ\n"
+ "build_PQ_byte (number of PQ bytes for inde build; set 0 to use "
+ "full precision vectors)\n"
+ "QD Quantized Dimension to overwrite the derived dim from B "
+ << std::endl;
+ return -1;
+ }
+
+ if (!std::is_same<T, float>::value &&
+ (compareMetric == diskann::Metric::INNER_PRODUCT || compareMetric == diskann::Metric::COSINE))
+ {
+ std::stringstream stream;
+ stream << "Disk-index build currently only supports floating point data for Max "
+ "Inner Product Search/ cosine similarity. "
+ << std::endl;
+ throw diskann::ANNException(stream.str(), -1);
+ }
+
+ size_t disk_pq_dims = 0;
+ bool use_disk_pq = false;
+ size_t build_pq_bytes = 0;
+
+ // if there is a 6th parameter, it means we compress the disk index
+ // vectors also using PQ data (for very large dimensionality data). If the
+ // provided parameter is 0, it means we store full vectors.
+ if (param_list.size() > 5)
+ {
+ disk_pq_dims = atoi(param_list[5].c_str());
+ use_disk_pq = true;
+ if (disk_pq_dims == 0)
+ use_disk_pq = false;
+ }
+
+ bool reorder_data = false;
+ if (param_list.size() >= 7)
+ {
+ if (1 == atoi(param_list[6].c_str()))
+ {
+ reorder_data = true;
+ }
+ }
+
+ if (param_list.size() >= 8)
+ {
+ build_pq_bytes = atoi(param_list[7].c_str());
+ }
+
+ std::string base_file(dataFilePath);
+ std::string data_file_to_use = base_file;
+ std::string labels_file_original = label_file;
+ std::string index_prefix_path(indexFilePath);
+ std::string labels_file_to_use = index_prefix_path + "_label_formatted.txt";
+ std::string pq_pivots_path_base = codebook_prefix;
+ std::string pq_pivots_path = file_exists(pq_pivots_path_base) ? pq_pivots_path_base + "_pq_pivots.bin"
+ : index_prefix_path + "_pq_pivots.bin";
+ std::string pq_compressed_vectors_path = index_prefix_path + "_pq_compressed.bin";
+ std::string mem_index_path = index_prefix_path + "_mem.index";
+ std::string disk_index_path = index_prefix_path + "_disk.index";
+ std::string medoids_path = disk_index_path + "_medoids.bin";
+ std::string centroids_path = disk_index_path + "_centroids.bin";
+
+ std::string labels_to_medoids_path = disk_index_path + "_labels_to_medoids.txt";
+ std::string mem_labels_file = mem_index_path + "_labels.txt";
+ std::string disk_labels_file = disk_index_path + "_labels.txt";
+ std::string mem_univ_label_file = mem_index_path + "_universal_label.txt";
+ std::string disk_univ_label_file = disk_index_path + "_universal_label.txt";
+ std::string disk_labels_int_map_file = disk_index_path + "_labels_map.txt";
+ std::string dummy_remap_file = disk_index_path + "_dummy_map.txt"; // remap will be used if we break-up points of
+ // high label-density to create copies
+
+ std::string sample_base_prefix = index_prefix_path + "_sample";
+ // optional, used if disk index file must store pq data
+ std::string disk_pq_pivots_path = index_prefix_path + "_disk.index_pq_pivots.bin";
+ // optional, used if disk index must store pq data
+ std::string disk_pq_compressed_vectors_path = index_prefix_path + "_disk.index_pq_compressed.bin";
+ std::string prepped_base =
+ index_prefix_path +
+ "_prepped_base.bin"; // temp file for storing pre-processed base file for cosine/ mips metrics
+ bool created_temp_file_for_processed_data = false;
+
+ // output a new base file which contains extra dimension with sqrt(1 -
+ // ||x||^2/M^2) for every x, M is max norm of all points. Extra space on
+ // disk needed!
+ if (compareMetric == diskann::Metric::INNER_PRODUCT)
+ {
+ Timer timer;
+ std::cout << "Using Inner Product search, so need to pre-process base "
+ "data into temp file. Please ensure there is additional "
+ "(n*(d+1)*4) bytes for storing pre-processed base vectors, "
+ "apart from the interim indices created by DiskANN and the final index."
+ << std::endl;
+ data_file_to_use = prepped_base;
+ float max_norm_of_base = diskann::prepare_base_for_inner_products<T>(base_file, prepped_base);
+ std::string norm_file = disk_index_path + "_max_base_norm.bin";
+
+ diskann::save_bin<float>(norm_file, &max_norm_of_base, 1, 1);
+ diskann::cout << timer.elapsed_seconds_for_step("preprocessing data for inner product") << std::endl;
+ created_temp_file_for_processed_data = true;
+
+ diskann::cout << "Reading max_norm_of_base from " << norm_file << std::endl;
+ float *max_norm_of_base_ptr;
+ size_t npts, ndims;
+ diskann::load_bin<float>(norm_file, max_norm_of_base_ptr, npts, ndims);
+ if (max_norm_of_base != *max_norm_of_base_ptr)
+ {
+ diskann::cout << "max_norm_of_base mismatch: " << max_norm_of_base << " != " << *max_norm_of_base_ptr
+ << std::endl;
+ assert(false);
+ }
+ diskann::cout << "max_norm_of_base: " << max_norm_of_base << std::endl;
+ diskann::cout << "! Using prepped_base file at " << prepped_base << std::endl;
+ if (!file_exists(prepped_base))
+ {
+ diskann::cout << "! prepped_base file does not exist, please check the file path" << std::endl;
+ assert(false);
+ }
+ }
+ else if (compareMetric == diskann::Metric::COSINE)
+ {
+ Timer timer;
+ std::cout << "Normalizing data for cosine to temporary file, please ensure there is additional "
+ "(n*d*4) bytes for storing normalized base vectors, "
+ "apart from the interim indices created by DiskANN and the final index."
+ << std::endl;
+ data_file_to_use = prepped_base;
+ diskann::normalize_data_file(base_file, prepped_base);
+ diskann::cout << timer.elapsed_seconds_for_step("preprocessing data for cosine") << std::endl;
+ created_temp_file_for_processed_data = true;
+ }
+
+ uint32_t R = (uint32_t)atoi(param_list[0].c_str());
+ uint32_t L = (uint32_t)atoi(param_list[1].c_str());
+
+ double final_index_ram_limit = get_memory_budget(param_list[2]);
+ if (final_index_ram_limit <= 0)
+ {
+ std::cerr << "Insufficient memory budget (or string was not in right "
+ "format). Should be > 0."
+ << std::endl;
+ return -1;
+ }
+ double indexing_ram_budget = (float)atof(param_list[3].c_str());
+ if (indexing_ram_budget <= 0)
+ {
+ std::cerr << "Not building index. Please provide more RAM budget" << std::endl;
+ return -1;
+ }
+ uint32_t num_threads = (uint32_t)atoi(param_list[4].c_str());
+
+ if (num_threads != 0)
+ {
+ omp_set_num_threads(num_threads);
+#ifdef __x86_64__
+ mkl_set_num_threads(num_threads);
+#endif
+ }
+
+ diskann::cout << "Starting index build: R=" << R << " L=" << L << " Query RAM budget: " << final_index_ram_limit
+ << " Indexing ram budget: " << indexing_ram_budget << " T: " << num_threads << std::endl;
+
+ auto s = std::chrono::high_resolution_clock::now();
+
+ // If there is filter support, we break-up points which have too many labels
+ // into replica dummy points which evenly distribute the filters. The rest
+ // of index build happens on the augmented base and labels
+ std::string augmented_data_file, augmented_labels_file;
+ if (use_filters)
+ {
+ convert_labels_string_to_int(labels_file_original, labels_file_to_use, disk_labels_int_map_file,
+ universal_label);
+ augmented_data_file = index_prefix_path + "_augmented_data.bin";
+ augmented_labels_file = index_prefix_path + "_augmented_labels.txt";
+ if (filter_threshold != 0)
+ {
+ breakup_dense_points<T>(data_file_to_use, labels_file_to_use, filter_threshold, augmented_data_file,
+ augmented_labels_file,
+ dummy_remap_file); // RKNOTE: This has large memory footprint,
+ // need to make this streaming
+ data_file_to_use = augmented_data_file;
+ labels_file_to_use = augmented_labels_file;
+ }
+ }
+
+ size_t points_num, dim;
+
+ diskann::cout << "getting bin metadata" << std::endl;
+ Timer timer;
+ diskann::get_bin_metadata(data_file_to_use.c_str(), points_num, dim);
+ diskann::cout << timer.elapsed_seconds_for_step("getting bin metadata") << std::endl;
+ const double p_val = ((double)MAX_PQ_TRAINING_SET_SIZE / (double)points_num);
+
+ if (use_disk_pq)
+ {
+ generate_disk_quantized_data<T>(data_file_to_use, disk_pq_pivots_path, disk_pq_compressed_vectors_path,
+ compareMetric, p_val, disk_pq_dims);
+ }
+ size_t num_pq_chunks = (size_t)(std::floor)(uint64_t(final_index_ram_limit / points_num));
+
+ num_pq_chunks = num_pq_chunks <= 0 ? 1 : num_pq_chunks;
+ num_pq_chunks = num_pq_chunks > dim ? dim : num_pq_chunks;
+ num_pq_chunks = num_pq_chunks > MAX_PQ_CHUNKS ? MAX_PQ_CHUNKS : num_pq_chunks;
+
+ if (param_list.size() >= 9 && atoi(param_list[8].c_str()) <= MAX_PQ_CHUNKS && atoi(param_list[8].c_str()) > 0)
+ {
+ std::cout << "Use quantized dimension (QD) to overwrite derived quantized "
+ "dimension from search_DRAM_budget (B)"
+ << std::endl;
+ num_pq_chunks = atoi(param_list[8].c_str());
+ }
+
+ diskann::cout << "Compressing " << dim << "-dimensional data into " << num_pq_chunks << " bytes per vector."
+ << std::endl;
+
+ generate_quantized_data<T>(data_file_to_use, pq_pivots_path, pq_compressed_vectors_path, compareMetric, p_val,
+ num_pq_chunks, use_opq, codebook_prefix);
+ diskann::cout << timer.elapsed_seconds_for_step("generating quantized data") << std::endl;
+
+// Gopal. Splitting diskann_dll into separate DLLs for search and build.
+// This code should only be available in the "build" DLL.
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+ MallocExtension::instance()->ReleaseFreeMemory();
+#endif
+ // Whether it is cosine or inner product, we still L2 metric due to the pre-processing.
+ timer.reset();
+ diskann::build_merged_vamana_index<T, LabelT>(data_file_to_use.c_str(), diskann::Metric::L2, L, R, p_val,
+ indexing_ram_budget, mem_index_path, medoids_path, centroids_path,
+ build_pq_bytes, use_opq, num_threads, use_filters, labels_file_to_use,
+ labels_to_medoids_path, universal_label, Lf);
+ diskann::cout << timer.elapsed_seconds_for_step("building merged vamana index") << std::endl;
+
+ timer.reset();
+ if (!use_disk_pq)
+ {
+ diskann::create_disk_layout<T>(data_file_to_use.c_str(), mem_index_path, disk_index_path);
+ }
+ else
+ {
+ if (!reorder_data)
+ diskann::create_disk_layout<uint8_t>(disk_pq_compressed_vectors_path, mem_index_path, disk_index_path);
+ else
+ diskann::create_disk_layout<uint8_t>(disk_pq_compressed_vectors_path, mem_index_path, disk_index_path,
+ data_file_to_use.c_str());
+ }
+ diskann::cout << timer.elapsed_seconds_for_step("generating disk layout") << std::endl;
+
+ double ten_percent_points = std::ceil(points_num * 0.1);
+ double num_sample_points =
+ ten_percent_points > MAX_SAMPLE_POINTS_FOR_WARMUP ? MAX_SAMPLE_POINTS_FOR_WARMUP : ten_percent_points;
+ double sample_sampling_rate = num_sample_points / points_num;
+ gen_random_slice<T>(data_file_to_use.c_str(), sample_base_prefix, sample_sampling_rate);
+ if (use_filters)
+ {
+ copy_file(labels_file_to_use, disk_labels_file);
+ std::remove(mem_labels_file.c_str());
+ if (universal_label != "")
+ {
+ copy_file(mem_univ_label_file, disk_univ_label_file);
+ std::remove(mem_univ_label_file.c_str());
+ }
+ std::remove(augmented_data_file.c_str());
+ std::remove(augmented_labels_file.c_str());
+ std::remove(labels_file_to_use.c_str());
+ }
+ if (created_temp_file_for_processed_data)
+ std::remove(prepped_base.c_str());
+ std::remove(mem_index_path.c_str());
+ std::remove((mem_index_path + ".data").c_str());
+ std::remove((mem_index_path + ".tags").c_str());
+ if (use_disk_pq)
+ std::remove(disk_pq_compressed_vectors_path.c_str());
+
+ auto e = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diff = e - s;
+ diskann::cout << "Indexing time: " << diff.count() << std::endl;
+
+ return 0;
+}
+
+template DISKANN_DLLEXPORT void create_disk_layout<int8_t>(const std::string base_file,
+ const std::string mem_index_file,
+ const std::string output_file,
+ const std::string reorder_data_file);
+template DISKANN_DLLEXPORT void create_disk_layout<uint8_t>(const std::string base_file,
+ const std::string mem_index_file,
+ const std::string output_file,
+ const std::string reorder_data_file);
+template DISKANN_DLLEXPORT void create_disk_layout<float>(const std::string base_file, const std::string mem_index_file,
+ const std::string output_file,
+ const std::string reorder_data_file);
+
+template DISKANN_DLLEXPORT int8_t *load_warmup<int8_t>(const std::string &cache_warmup_file, uint64_t &warmup_num,
+ uint64_t warmup_dim, uint64_t warmup_aligned_dim);
+template DISKANN_DLLEXPORT uint8_t *load_warmup<uint8_t>(const std::string &cache_warmup_file, uint64_t &warmup_num,
+ uint64_t warmup_dim, uint64_t warmup_aligned_dim);
+template DISKANN_DLLEXPORT float *load_warmup<float>(const std::string &cache_warmup_file, uint64_t &warmup_num,
+ uint64_t warmup_dim, uint64_t warmup_aligned_dim);
+
+#ifdef EXEC_ENV_OLS
+template DISKANN_DLLEXPORT int8_t *load_warmup<int8_t>(MemoryMappedFiles &files, const std::string &cache_warmup_file,
+ uint64_t &warmup_num, uint64_t warmup_dim,
+ uint64_t warmup_aligned_dim);
+template DISKANN_DLLEXPORT uint8_t *load_warmup<uint8_t>(MemoryMappedFiles &files, const std::string &cache_warmup_file,
+ uint64_t &warmup_num, uint64_t warmup_dim,
+ uint64_t warmup_aligned_dim);
+template DISKANN_DLLEXPORT float *load_warmup<float>(MemoryMappedFiles &files, const std::string &cache_warmup_file,
+ uint64_t &warmup_num, uint64_t warmup_dim,
+ uint64_t warmup_aligned_dim);
+#endif
+
+template DISKANN_DLLEXPORT uint32_t optimize_beamwidth<int8_t, uint32_t>(
+ std::unique_ptr<diskann::PQFlashIndex<int8_t, uint32_t>> &pFlashIndex, int8_t *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads, uint32_t start_bw);
+template DISKANN_DLLEXPORT uint32_t optimize_beamwidth<uint8_t, uint32_t>(
+ std::unique_ptr<diskann::PQFlashIndex<uint8_t, uint32_t>> &pFlashIndex, uint8_t *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads, uint32_t start_bw);
+template DISKANN_DLLEXPORT uint32_t optimize_beamwidth<float, uint32_t>(
+ std::unique_ptr<diskann::PQFlashIndex<float, uint32_t>> &pFlashIndex, float *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads, uint32_t start_bw);
+
+template DISKANN_DLLEXPORT uint32_t optimize_beamwidth<int8_t, uint16_t>(
+ std::unique_ptr<diskann::PQFlashIndex<int8_t, uint16_t>> &pFlashIndex, int8_t *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads, uint32_t start_bw);
+template DISKANN_DLLEXPORT uint32_t optimize_beamwidth<uint8_t, uint16_t>(
+ std::unique_ptr<diskann::PQFlashIndex<uint8_t, uint16_t>> &pFlashIndex, uint8_t *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads, uint32_t start_bw);
+template DISKANN_DLLEXPORT uint32_t optimize_beamwidth<float, uint16_t>(
+ std::unique_ptr<diskann::PQFlashIndex<float, uint16_t>> &pFlashIndex, float *tuning_sample,
+ uint64_t tuning_sample_num, uint64_t tuning_sample_aligned_dim, uint32_t L, uint32_t nthreads, uint32_t start_bw);
+
+template DISKANN_DLLEXPORT int build_disk_index<int8_t, uint32_t>(const char *dataFilePath, const char *indexFilePath,
+ const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq,
+ const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file,
+ const std::string &universal_label,
+ const uint32_t filter_threshold, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_disk_index<uint8_t, uint32_t>(const char *dataFilePath, const char *indexFilePath,
+ const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq,
+ const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file,
+ const std::string &universal_label,
+ const uint32_t filter_threshold, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_disk_index<float, uint32_t>(const char *dataFilePath, const char *indexFilePath,
+ const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq,
+ const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file,
+ const std::string &universal_label,
+ const uint32_t filter_threshold, const uint32_t Lf);
+// LabelT = uint16
+template DISKANN_DLLEXPORT int build_disk_index<int8_t, uint16_t>(const char *dataFilePath, const char *indexFilePath,
+ const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq,
+ const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file,
+ const std::string &universal_label,
+ const uint32_t filter_threshold, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_disk_index<uint8_t, uint16_t>(const char *dataFilePath, const char *indexFilePath,
+ const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq,
+ const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file,
+ const std::string &universal_label,
+ const uint32_t filter_threshold, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_disk_index<float, uint16_t>(const char *dataFilePath, const char *indexFilePath,
+ const char *indexBuildParameters,
+ diskann::Metric compareMetric, bool use_opq,
+ const std::string &codebook_prefix, bool use_filters,
+ const std::string &label_file,
+ const std::string &universal_label,
+ const uint32_t filter_threshold, const uint32_t Lf);
+
+template DISKANN_DLLEXPORT int build_merged_vamana_index<int8_t, uint32_t>(
+ std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R, double sampling_rate,
+ double ram_budget, std::string mem_index_path, std::string medoids_path, std::string centroids_file,
+ size_t build_pq_bytes, bool use_opq, uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_merged_vamana_index<float, uint32_t>(
+ std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R, double sampling_rate,
+ double ram_budget, std::string mem_index_path, std::string medoids_path, std::string centroids_file,
+ size_t build_pq_bytes, bool use_opq, uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_merged_vamana_index<uint8_t, uint32_t>(
+ std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R, double sampling_rate,
+ double ram_budget, std::string mem_index_path, std::string medoids_path, std::string centroids_file,
+ size_t build_pq_bytes, bool use_opq, uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label, const uint32_t Lf);
+// Label=16_t
+template DISKANN_DLLEXPORT int build_merged_vamana_index<int8_t, uint16_t>(
+ std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R, double sampling_rate,
+ double ram_budget, std::string mem_index_path, std::string medoids_path, std::string centroids_file,
+ size_t build_pq_bytes, bool use_opq, uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_merged_vamana_index<float, uint16_t>(
+ std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R, double sampling_rate,
+ double ram_budget, std::string mem_index_path, std::string medoids_path, std::string centroids_file,
+ size_t build_pq_bytes, bool use_opq, uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label, const uint32_t Lf);
+template DISKANN_DLLEXPORT int build_merged_vamana_index<uint8_t, uint16_t>(
+ std::string base_file, diskann::Metric compareMetric, uint32_t L, uint32_t R, double sampling_rate,
+ double ram_budget, std::string mem_index_path, std::string medoids_path, std::string centroids_file,
+ size_t build_pq_bytes, bool use_opq, uint32_t num_threads, bool use_filters, const std::string &label_file,
+ const std::string &labels_to_medoids_file, const std::string &universal_label, const uint32_t Lf);
+}; // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/distance.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/distance.cpp
new file mode 100644
index 0000000..2fa4c7a
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/distance.cpp
@@ -0,0 +1,743 @@
+// TODO
+// CHECK COSINE ON LINUX
+
+#ifdef _WINDOWS
+#include <immintrin.h>
+#include <smmintrin.h>
+#include <tmmintrin.h>
+#include <intrin.h>
+#include <cosine_similarity.h>
+#include "simd_utils.h"
+#elif __APPLE__
+#include <Accelerate/Accelerate.h>
+#else
+#include <immintrin.h>
+#include "simd_utils.h"
+#endif
+
+#include <iostream>
+
+#include "distance.h"
+#include "utils.h"
+#include "logger.h"
+#include "ann_exception.h"
+
+namespace diskann
+{
+
+//
+// Base Class Implementatons
+//
+template <typename T>
+float Distance<T>::compare(const T *a, const T *b, const float normA, const float normB, uint32_t length) const
+{
+ throw std::logic_error("This function is not implemented.");
+}
+
+template <typename T> uint32_t Distance<T>::post_normalization_dimension(uint32_t orig_dimension) const
+{
+ return orig_dimension;
+}
+
+template <typename T> diskann::Metric Distance<T>::get_metric() const
+{
+ return _distance_metric;
+}
+
+template <typename T> bool Distance<T>::preprocessing_required() const
+{
+ return false;
+}
+
+template <typename T>
+void Distance<T>::preprocess_base_points(T *original_data, const size_t orig_dim, const size_t num_points)
+{
+}
+
+template <typename T> void Distance<T>::preprocess_query(const T *query_vec, const size_t query_dim, T *scratch_query)
+{
+ std::memcpy(scratch_query, query_vec, query_dim * sizeof(T));
+}
+
+template <typename T> size_t Distance<T>::get_required_alignment() const
+{
+ return _alignment_factor;
+}
+
+//
+// Cosine distance functions.
+//
+
+float DistanceCosineInt8::compare(const int8_t *a, const int8_t *b, uint32_t length) const
+{
+#ifdef _WINDOWS
+ return diskann::CosineSimilarity2<int8_t>(a, b, length);
+#else
+ int magA = 0, magB = 0, scalarProduct = 0;
+ for (uint32_t i = 0; i < length; i++)
+ {
+ magA += ((int32_t)a[i]) * ((int32_t)a[i]);
+ magB += ((int32_t)b[i]) * ((int32_t)b[i]);
+ scalarProduct += ((int32_t)a[i]) * ((int32_t)b[i]);
+ }
+ // similarity == 1-cosine distance
+ return 1.0f - (float)(scalarProduct / (sqrt(magA) * sqrt(magB)));
+#endif
+}
+
+float DistanceCosineFloat::compare(const float *a, const float *b, uint32_t length) const
+{
+#ifdef _WINDOWS
+ return diskann::CosineSimilarity2<float>(a, b, length);
+#else
+ float magA = 0, magB = 0, scalarProduct = 0;
+ for (uint32_t i = 0; i < length; i++)
+ {
+ magA += (a[i]) * (a[i]);
+ magB += (b[i]) * (b[i]);
+ scalarProduct += (a[i]) * (b[i]);
+ }
+ // similarity == 1-cosine distance
+ return 1.0f - (scalarProduct / (sqrt(magA) * sqrt(magB)));
+#endif
+}
+
+float SlowDistanceCosineUInt8::compare(const uint8_t *a, const uint8_t *b, uint32_t length) const
+{
+ int magA = 0, magB = 0, scalarProduct = 0;
+ for (uint32_t i = 0; i < length; i++)
+ {
+ magA += ((uint32_t)a[i]) * ((uint32_t)a[i]);
+ magB += ((uint32_t)b[i]) * ((uint32_t)b[i]);
+ scalarProduct += ((uint32_t)a[i]) * ((uint32_t)b[i]);
+ }
+ // similarity == 1-cosine distance
+ return 1.0f - (float)(scalarProduct / (sqrt(magA) * sqrt(magB)));
+}
+
+//
+// L2 distance functions.
+//
+
+float DistanceL2Int8::compare(const int8_t *a, const int8_t *b, uint32_t size) const
+{
+#ifdef _WINDOWS
+#ifdef USE_AVX2
+ __m256 r = _mm256_setzero_ps();
+ char *pX = (char *)a, *pY = (char *)b;
+ while (size >= 32)
+ {
+ __m256i r1 = _mm256_subs_epi8(_mm256_loadu_si256((__m256i *)pX), _mm256_loadu_si256((__m256i *)pY));
+ r = _mm256_add_ps(r, _mm256_mul_epi8(r1, r1));
+ pX += 32;
+ pY += 32;
+ size -= 32;
+ }
+ while (size > 0)
+ {
+ __m128i r2 = _mm_subs_epi8(_mm_loadu_si128((__m128i *)pX), _mm_loadu_si128((__m128i *)pY));
+ r = _mm256_add_ps(r, _mm256_mul32_pi8(r2, r2));
+ pX += 4;
+ pY += 4;
+ size -= 4;
+ }
+ r = _mm256_hadd_ps(_mm256_hadd_ps(r, r), r);
+ return r.m256_f32[0] + r.m256_f32[4];
+#else
+ int32_t result = 0;
+#pragma omp simd reduction(+ : result) aligned(a, b : 8)
+ for (int32_t i = 0; i < (int32_t)size; i++)
+ {
+ result += ((int32_t)((int16_t)a[i] - (int16_t)b[i])) * ((int32_t)((int16_t)a[i] - (int16_t)b[i]));
+ }
+ return (float)result;
+#endif
+#else
+ int32_t result = 0;
+#pragma omp simd reduction(+ : result) aligned(a, b : 8)
+ for (int32_t i = 0; i < (int32_t)size; i++)
+ {
+ result += ((int32_t)((int16_t)a[i] - (int16_t)b[i])) * ((int32_t)((int16_t)a[i] - (int16_t)b[i]));
+ }
+ return (float)result;
+#endif
+}
+
+float DistanceL2UInt8::compare(const uint8_t *a, const uint8_t *b, uint32_t size) const
+{
+ uint32_t result = 0;
+#ifndef _WINDOWS
+#pragma omp simd reduction(+ : result) aligned(a, b : 8)
+#endif
+ for (int32_t i = 0; i < (int32_t)size; i++)
+ {
+ result += ((int32_t)((int16_t)a[i] - (int16_t)b[i])) * ((int32_t)((int16_t)a[i] - (int16_t)b[i]));
+ }
+ return (float)result;
+}
+
+#ifndef _WINDOWS
+float DistanceL2Float::compare(const float *a, const float *b, uint32_t size) const
+{
+ a = (const float *)__builtin_assume_aligned(a, 32);
+ b = (const float *)__builtin_assume_aligned(b, 32);
+#else
+float DistanceL2Float::compare(const float *a, const float *b, uint32_t size) const
+{
+#endif
+
+ float result = 0;
+#ifdef USE_AVX2
+ // assume size is divisible by 8
+ uint16_t niters = (uint16_t)(size / 8);
+ __m256 sum = _mm256_setzero_ps();
+ for (uint16_t j = 0; j < niters; j++)
+ {
+ // scope is a[8j:8j+7], b[8j:8j+7]
+ // load a_vec
+ if (j < (niters - 1))
+ {
+ _mm_prefetch((char *)(a + 8 * (j + 1)), _MM_HINT_T0);
+ _mm_prefetch((char *)(b + 8 * (j + 1)), _MM_HINT_T0);
+ }
+ __m256 a_vec = _mm256_load_ps(a + 8 * j);
+ // load b_vec
+ __m256 b_vec = _mm256_load_ps(b + 8 * j);
+ // a_vec - b_vec
+ __m256 tmp_vec = _mm256_sub_ps(a_vec, b_vec);
+
+ sum = _mm256_fmadd_ps(tmp_vec, tmp_vec, sum);
+ }
+
+ // horizontal add sum
+ result = _mm256_reduce_add_ps(sum);
+#else
+#ifndef _WINDOWS
+#pragma omp simd reduction(+ : result) aligned(a, b : 32)
+#endif
+ for (int32_t i = 0; i < (int32_t)size; i++)
+ {
+ result += (a[i] - b[i]) * (a[i] - b[i]);
+ }
+#endif
+ return result;
+}
+
+template <typename T> float SlowDistanceL2<T>::compare(const T *a, const T *b, uint32_t length) const
+{
+ float result = 0.0f;
+ for (uint32_t i = 0; i < length; i++)
+ {
+ result += ((float)(a[i] - b[i])) * (a[i] - b[i]);
+ }
+ return result;
+}
+
+#ifdef _WINDOWS
+float AVXDistanceL2Int8::compare(const int8_t *a, const int8_t *b, uint32_t length) const
+{
+ __m128 r = _mm_setzero_ps();
+ __m128i r1;
+ while (length >= 16)
+ {
+ r1 = _mm_subs_epi8(_mm_load_si128((__m128i *)a), _mm_load_si128((__m128i *)b));
+ r = _mm_add_ps(r, _mm_mul_epi8(r1));
+ a += 16;
+ b += 16;
+ length -= 16;
+ }
+ r = _mm_hadd_ps(_mm_hadd_ps(r, r), r);
+ float res = r.m128_f32[0];
+
+ if (length >= 8)
+ {
+ __m128 r2 = _mm_setzero_ps();
+ __m128i r3 = _mm_subs_epi8(_mm_load_si128((__m128i *)(a - 8)), _mm_load_si128((__m128i *)(b - 8)));
+ r2 = _mm_add_ps(r2, _mm_mulhi_epi8(r3));
+ a += 8;
+ b += 8;
+ length -= 8;
+ r2 = _mm_hadd_ps(_mm_hadd_ps(r2, r2), r2);
+ res += r2.m128_f32[0];
+ }
+
+ if (length >= 4)
+ {
+ __m128 r2 = _mm_setzero_ps();
+ __m128i r3 = _mm_subs_epi8(_mm_load_si128((__m128i *)(a - 12)), _mm_load_si128((__m128i *)(b - 12)));
+ r2 = _mm_add_ps(r2, _mm_mulhi_epi8_shift32(r3));
+ res += r2.m128_f32[0] + r2.m128_f32[1];
+ }
+
+ return res;
+}
+
+float AVXDistanceL2Float::compare(const float *a, const float *b, uint32_t length) const
+{
+ __m128 diff, v1, v2;
+ __m128 sum = _mm_set1_ps(0);
+
+ while (length >= 4)
+ {
+ v1 = _mm_loadu_ps(a);
+ a += 4;
+ v2 = _mm_loadu_ps(b);
+ b += 4;
+ diff = _mm_sub_ps(v1, v2);
+ sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff));
+ length -= 4;
+ }
+
+ return sum.m128_f32[0] + sum.m128_f32[1] + sum.m128_f32[2] + sum.m128_f32[3];
+}
+#else
+float AVXDistanceL2Int8::compare(const int8_t *, const int8_t *, uint32_t) const
+{
+ return 0;
+}
+float AVXDistanceL2Float::compare(const float *, const float *, uint32_t) const
+{
+ return 0;
+}
+#endif
+
+template <typename T> float DistanceInnerProduct<T>::inner_product(const T *a, const T *b, uint32_t size) const
+{
+ if (!std::is_floating_point<T>::value)
+ {
+ diskann::cerr << "ERROR: Inner Product only defined for float currently." << std::endl;
+ throw diskann::ANNException("ERROR: Inner Product only defined for float currently.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ float result = 0;
+
+#ifdef __GNUC__
+#ifdef USE_AVX2
+#define AVX_DOT(addr1, addr2, dest, tmp1, tmp2) \
+ tmp1 = _mm256_loadu_ps(addr1); \
+ tmp2 = _mm256_loadu_ps(addr2); \
+ tmp1 = _mm256_mul_ps(tmp1, tmp2); \
+ dest = _mm256_add_ps(dest, tmp1);
+
+ __m256 sum;
+ __m256 l0, l1;
+ __m256 r0, r1;
+ uint32_t D = (size + 7) & ~7U;
+ uint32_t DR = D % 16;
+ uint32_t DD = D - DR;
+ const float *l = (float *)a;
+ const float *r = (float *)b;
+ const float *e_l = l + DD;
+ const float *e_r = r + DD;
+ float unpack[8] __attribute__((aligned(32))) = {0, 0, 0, 0, 0, 0, 0, 0};
+
+ sum = _mm256_loadu_ps(unpack);
+ if (DR)
+ {
+ AVX_DOT(e_l, e_r, sum, l0, r0);
+ }
+
+ for (uint32_t i = 0; i < DD; i += 16, l += 16, r += 16)
+ {
+ AVX_DOT(l, r, sum, l0, r0);
+ AVX_DOT(l + 8, r + 8, sum, l1, r1);
+ }
+ _mm256_storeu_ps(unpack, sum);
+ result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7];
+
+#else
+#ifdef __SSE2__
+#define SSE_DOT(addr1, addr2, dest, tmp1, tmp2) \
+ tmp1 = _mm128_loadu_ps(addr1); \
+ tmp2 = _mm128_loadu_ps(addr2); \
+ tmp1 = _mm128_mul_ps(tmp1, tmp2); \
+ dest = _mm128_add_ps(dest, tmp1);
+ __m128 sum;
+ __m128 l0, l1, l2, l3;
+ __m128 r0, r1, r2, r3;
+ uint32_t D = (size + 3) & ~3U;
+ uint32_t DR = D % 16;
+ uint32_t DD = D - DR;
+ const float *l = a;
+ const float *r = b;
+ const float *e_l = l + DD;
+ const float *e_r = r + DD;
+ float unpack[4] __attribute__((aligned(16))) = {0, 0, 0, 0};
+
+ sum = _mm_load_ps(unpack);
+ switch (DR)
+ {
+ case 12:
+ SSE_DOT(e_l + 8, e_r + 8, sum, l2, r2);
+ case 8:
+ SSE_DOT(e_l + 4, e_r + 4, sum, l1, r1);
+ case 4:
+ SSE_DOT(e_l, e_r, sum, l0, r0);
+ default:
+ break;
+ }
+ for (uint32_t i = 0; i < DD; i += 16, l += 16, r += 16)
+ {
+ SSE_DOT(l, r, sum, l0, r0);
+ SSE_DOT(l + 4, r + 4, sum, l1, r1);
+ SSE_DOT(l + 8, r + 8, sum, l2, r2);
+ SSE_DOT(l + 12, r + 12, sum, l3, r3);
+ }
+ _mm_storeu_ps(unpack, sum);
+ result += unpack[0] + unpack[1] + unpack[2] + unpack[3];
+#elif __APPLE__
+ vDSP_dotpr((float *)a, (vDSP_Stride)1, (float *)b, (vDSP_Stride)1, &result, size);
+#else
+
+ float dot0, dot1, dot2, dot3;
+ const float *last = a + size;
+ const float *unroll_group = last - 3;
+
+ /* Process 4 items with each loop for efficiency. */
+ while (a < unroll_group)
+ {
+ dot0 = a[0] * b[0];
+ dot1 = a[1] * b[1];
+ dot2 = a[2] * b[2];
+ dot3 = a[3] * b[3];
+ result += dot0 + dot1 + dot2 + dot3;
+ a += 4;
+ b += 4;
+ }
+ /* Process last 0-3 pixels. Not needed for standard vector lengths. */
+ while (a < last)
+ {
+ result += *a++ * *b++;
+ }
+#endif
+#endif
+#endif
+ return result;
+}
+
+template <typename T> float DistanceFastL2<T>::compare(const T *a, const T *b, float norm, uint32_t size) const
+{
+ float result = -2 * DistanceInnerProduct<T>::inner_product(a, b, size);
+ result += norm;
+ return result;
+}
+
+template <typename T> float DistanceFastL2<T>::norm(const T *a, uint32_t size) const
+{
+ if (!std::is_floating_point<T>::value)
+ {
+ diskann::cerr << "ERROR: FastL2 only defined for float currently." << std::endl;
+ throw diskann::ANNException("ERROR: FastL2 only defined for float currently.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+ float result = 0;
+#ifdef __GNUC__
+#ifdef __AVX__
+#define AVX_L2NORM(addr, dest, tmp) \
+ tmp = _mm256_loadu_ps(addr); \
+ tmp = _mm256_mul_ps(tmp, tmp); \
+ dest = _mm256_add_ps(dest, tmp);
+
+ __m256 sum;
+ __m256 l0, l1;
+ uint32_t D = (size + 7) & ~7U;
+ uint32_t DR = D % 16;
+ uint32_t DD = D - DR;
+ const float *l = (float *)a;
+ const float *e_l = l + DD;
+ float unpack[8] __attribute__((aligned(32))) = {0, 0, 0, 0, 0, 0, 0, 0};
+
+ sum = _mm256_loadu_ps(unpack);
+ if (DR)
+ {
+ AVX_L2NORM(e_l, sum, l0);
+ }
+ for (uint32_t i = 0; i < DD; i += 16, l += 16)
+ {
+ AVX_L2NORM(l, sum, l0);
+ AVX_L2NORM(l + 8, sum, l1);
+ }
+ _mm256_storeu_ps(unpack, sum);
+ result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7];
+#else
+#ifdef __SSE2__
+#define SSE_L2NORM(addr, dest, tmp) \
+ tmp = _mm128_loadu_ps(addr); \
+ tmp = _mm128_mul_ps(tmp, tmp); \
+ dest = _mm128_add_ps(dest, tmp);
+
+ __m128 sum;
+ __m128 l0, l1, l2, l3;
+ uint32_t D = (size + 3) & ~3U;
+ uint32_t DR = D % 16;
+ uint32_t DD = D - DR;
+ const float *l = a;
+ const float *e_l = l + DD;
+ float unpack[4] __attribute__((aligned(16))) = {0, 0, 0, 0};
+
+ sum = _mm_load_ps(unpack);
+ switch (DR)
+ {
+ case 12:
+ SSE_L2NORM(e_l + 8, sum, l2);
+ case 8:
+ SSE_L2NORM(e_l + 4, sum, l1);
+ case 4:
+ SSE_L2NORM(e_l, sum, l0);
+ default:
+ break;
+ }
+ for (uint32_t i = 0; i < DD; i += 16, l += 16)
+ {
+ SSE_L2NORM(l, sum, l0);
+ SSE_L2NORM(l + 4, sum, l1);
+ SSE_L2NORM(l + 8, sum, l2);
+ SSE_L2NORM(l + 12, sum, l3);
+ }
+ _mm_storeu_ps(unpack, sum);
+ result += unpack[0] + unpack[1] + unpack[2] + unpack[3];
+#elif __APPLE__
+ vDSP_dotpr((float *)a, 1, (float *)a, 1, &result, size);
+#else
+ float dot0, dot1, dot2, dot3;
+ const float *last = a + size;
+ const float *unroll_group = last - 3;
+
+ /* Process 4 items with each loop for efficiency. */
+ while (a < unroll_group)
+ {
+ dot0 = a[0] * a[0];
+ dot1 = a[1] * a[1];
+ dot2 = a[2] * a[2];
+ dot3 = a[3] * a[3];
+ result += dot0 + dot1 + dot2 + dot3;
+ a += 4;
+ }
+ /* Process last 0-3 pixels. Not needed for standard vector lengths. */
+ while (a < last)
+ {
+ result += (*a) * (*a);
+ a++;
+ }
+#endif
+#endif
+#endif
+ return result;
+}
+
+float AVXDistanceInnerProductFloat::compare(const float *a, const float *b, uint32_t size) const
+{
+ float result = 0.0f;
+#ifdef __APPLE__
+ vDSP_dotpr(a, (vDSP_Stride)1, b, (vDSP_Stride)1, &result, size);
+#else
+#define AVX_DOT(addr1, addr2, dest, tmp1, tmp2) \
+ tmp1 = _mm256_loadu_ps(addr1); \
+ tmp2 = _mm256_loadu_ps(addr2); \
+ tmp1 = _mm256_mul_ps(tmp1, tmp2); \
+ dest = _mm256_add_ps(dest, tmp1);
+
+ __m256 sum;
+ __m256 l0, l1;
+ __m256 r0, r1;
+ uint32_t D = (size + 7) & ~7U;
+ uint32_t DR = D % 16;
+ uint32_t DD = D - DR;
+ const float *l = (float *)a;
+ const float *r = (float *)b;
+ const float *e_l = l + DD;
+ const float *e_r = r + DD;
+#ifndef _WINDOWS
+ float unpack[8] __attribute__((aligned(32))) = {0, 0, 0, 0, 0, 0, 0, 0};
+#else
+ __declspec(align(32)) float unpack[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+#endif
+
+ sum = _mm256_loadu_ps(unpack);
+ if (DR)
+ {
+ AVX_DOT(e_l, e_r, sum, l0, r0);
+ }
+
+ for (uint32_t i = 0; i < DD; i += 16, l += 16, r += 16)
+ {
+ AVX_DOT(l, r, sum, l0, r0);
+ AVX_DOT(l + 8, r + 8, sum, l1, r1);
+ }
+ _mm256_storeu_ps(unpack, sum);
+ result = unpack[0] + unpack[1] + unpack[2] + unpack[3] + unpack[4] + unpack[5] + unpack[6] + unpack[7];
+#endif
+ return -result;
+}
+
+uint32_t AVXNormalizedCosineDistanceFloat::post_normalization_dimension(uint32_t orig_dimension) const
+{
+ return orig_dimension;
+}
+bool AVXNormalizedCosineDistanceFloat::preprocessing_required() const
+{
+ return true;
+}
+void AVXNormalizedCosineDistanceFloat::preprocess_base_points(float *original_data, const size_t orig_dim,
+ const size_t num_points)
+{
+ for (uint32_t i = 0; i < num_points; i++)
+ {
+ normalize((float *)(original_data + i * orig_dim), orig_dim);
+ }
+}
+
+void AVXNormalizedCosineDistanceFloat::preprocess_query(const float *query_vec, const size_t query_dim,
+ float *query_scratch)
+{
+ normalize_and_copy(query_vec, (uint32_t)query_dim, query_scratch);
+}
+
+void AVXNormalizedCosineDistanceFloat::normalize_and_copy(const float *query_vec, const uint32_t query_dim,
+ float *query_target) const
+{
+ float norm = get_norm(query_vec, query_dim);
+
+ for (uint32_t i = 0; i < query_dim; i++)
+ {
+ query_target[i] = query_vec[i] / norm;
+ }
+}
+
+// Get the right distance function for the given metric.
+template <> diskann::Distance<float> *get_distance_function(diskann::Metric m)
+{
+ if (m == diskann::Metric::L2)
+ {
+ if (Avx2SupportedCPU)
+ {
+ diskann::cout << "L2: Using AVX2 distance computation DistanceL2Float" << std::endl;
+ return new diskann::DistanceL2Float();
+ }
+ else if (AvxSupportedCPU)
+ {
+ diskann::cout << "L2: AVX2 not supported. Using AVX distance computation" << std::endl;
+ return new diskann::AVXDistanceL2Float();
+ }
+ else
+ {
+ diskann::cout << "L2: Older CPU. Using slow distance computation" << std::endl;
+ return new diskann::SlowDistanceL2<float>();
+ }
+ }
+ else if (m == diskann::Metric::COSINE)
+ {
+ diskann::cout << "Cosine: Using either AVX or AVX2 implementation" << std::endl;
+ return new diskann::DistanceCosineFloat();
+ }
+ else if (m == diskann::Metric::INNER_PRODUCT)
+ {
+ diskann::cout << "Inner product: Using AVX2 implementation "
+ "AVXDistanceInnerProductFloat"
+ << std::endl;
+ return new diskann::AVXDistanceInnerProductFloat();
+ }
+ else if (m == diskann::Metric::FAST_L2)
+ {
+ diskann::cout << "Fast_L2: Using AVX2 implementation with norm "
+ "memoization DistanceFastL2<float>"
+ << std::endl;
+ return new diskann::DistanceFastL2<float>();
+ }
+ else
+ {
+ std::stringstream stream;
+ stream << "Only L2, cosine, and inner product supported for floating "
+ "point vectors as of now."
+ << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+
+template <> diskann::Distance<int8_t> *get_distance_function(diskann::Metric m)
+{
+ if (m == diskann::Metric::L2)
+ {
+ if (Avx2SupportedCPU)
+ {
+ diskann::cout << "Using AVX2 distance computation DistanceL2Int8." << std::endl;
+ return new diskann::DistanceL2Int8();
+ }
+ else if (AvxSupportedCPU)
+ {
+ diskann::cout << "AVX2 not supported. Using AVX distance computation" << std::endl;
+ return new diskann::AVXDistanceL2Int8();
+ }
+ else
+ {
+ diskann::cout << "Older CPU. Using slow distance computation "
+ "SlowDistanceL2Int<int8_t>."
+ << std::endl;
+ return new diskann::SlowDistanceL2<int8_t>();
+ }
+ }
+ else if (m == diskann::Metric::COSINE)
+ {
+ diskann::cout << "Using either AVX or AVX2 for Cosine similarity "
+ "DistanceCosineInt8."
+ << std::endl;
+ return new diskann::DistanceCosineInt8();
+ }
+ else
+ {
+ std::stringstream stream;
+ stream << "Only L2 and cosine supported for signed byte vectors." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+
+template <> diskann::Distance<uint8_t> *get_distance_function(diskann::Metric m)
+{
+ if (m == diskann::Metric::L2)
+ {
+#ifdef _WINDOWS
+ diskann::cout << "WARNING: AVX/AVX2 distance function not defined for Uint8. "
+ "Using "
+ "slow version. "
+ "Contact [email protected] if you need AVX/AVX2 support."
+ << std::endl;
+#endif
+ return new diskann::DistanceL2UInt8();
+ }
+ else if (m == diskann::Metric::COSINE)
+ {
+ diskann::cout << "AVX/AVX2 distance function not defined for Uint8. Using "
+ "slow version SlowDistanceCosineUint8() "
+ "Contact [email protected] if you need AVX/AVX2 support."
+ << std::endl;
+ return new diskann::SlowDistanceCosineUInt8();
+ }
+ else
+ {
+ std::stringstream stream;
+ stream << "Only L2 and cosine supported for uint32_t byte vectors." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+
+template DISKANN_DLLEXPORT class DistanceInnerProduct<float>;
+template DISKANN_DLLEXPORT class DistanceInnerProduct<int8_t>;
+template DISKANN_DLLEXPORT class DistanceInnerProduct<uint8_t>;
+
+template DISKANN_DLLEXPORT class DistanceFastL2<float>;
+template DISKANN_DLLEXPORT class DistanceFastL2<int8_t>;
+template DISKANN_DLLEXPORT class DistanceFastL2<uint8_t>;
+
+template DISKANN_DLLEXPORT class SlowDistanceL2<float>;
+template DISKANN_DLLEXPORT class SlowDistanceL2<int8_t>;
+template DISKANN_DLLEXPORT class SlowDistanceL2<uint8_t>;
+
+// template DISKANN_DLLEXPORT Distance<float> *get_distance_function(Metric m);
+// template DISKANN_DLLEXPORT Distance<int8_t> *get_distance_function(Metric m);
+// template DISKANN_DLLEXPORT Distance<uint8_t> *get_distance_function(Metric m);
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/dll/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/src/dll/CMakeLists.txt
new file mode 100644
index 0000000..096d1b7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/dll/CMakeLists.txt
@@ -0,0 +1,35 @@
+#Copyright(c) Microsoft Corporation.All rights reserved.
+#Licensed under the MIT license.
+
+add_library(${PROJECT_NAME} SHARED dllmain.cpp ../abstract_data_store.cpp ../partition.cpp ../pq.cpp ../pq_flash_index.cpp ../logger.cpp ../utils.cpp
+ ../windows_aligned_file_reader.cpp ../distance.cpp ../pq_l2_distance.cpp ../memory_mapper.cpp ../index.cpp
+ ../in_mem_data_store.cpp ../pq_data_store.cpp ../in_mem_graph_store.cpp ../math_utils.cpp ../disk_utils.cpp ../filter_utils.cpp
+ ../ann_exception.cpp ../natural_number_set.cpp ../natural_number_map.cpp ../scratch.cpp ../index_factory.cpp ../abstract_index.cpp)
+
+set(TARGET_DIR "$<$<CONFIG:Debug>:${CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG}>$<$<CONFIG:Release>:${CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE}>")
+
+set(DISKANN_DLL_IMPLIB "${TARGET_DIR}/${PROJECT_NAME}.lib")
+
+if (NOT PYBIND)
+ target_compile_definitions(${PROJECT_NAME} PRIVATE DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS DISKANN_BUILD)
+endif()
+target_compile_definitions(${PROJECT_NAME} PRIVATE _USRDLL _WINDLL)
+target_compile_options(${PROJECT_NAME} PRIVATE /GL)
+target_include_directories(${PROJECT_NAME} PRIVATE ${DISKANN_MKL_INCLUDE_DIRECTORIES})
+
+target_link_options(${PROJECT_NAME} PRIVATE /DLL /IMPLIB:${DISKANN_DLL_IMPLIB} /LTCG)
+target_link_libraries(${PROJECT_NAME} PRIVATE ${DISKANN_MKL_LINK_LIBRARIES})
+target_link_libraries(${PROJECT_NAME} PRIVATE synchronization.lib)
+
+if (DISKANN_DLL_TCMALLOC_LINK_OPTIONS)
+ target_link_libraries(${PROJECT_NAME} PUBLIC ${DISKANN_DLL_TCMALLOC_LINK_OPTIONS})
+endif()
+
+# Copy OpenMP DLL and PDB.
+set(RUNTIME_FILES_TO_COPY ${OPENMP_WINDOWS_RUNTIME_FILES} ${TCMALLOC_WINDOWS_RUNTIME_FILES})
+
+foreach(RUNTIME_FILE ${RUNTIME_FILES_TO_COPY})
+ add_custom_command(TARGET ${PROJECT_NAME}
+ POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy "${RUNTIME_FILE}" "${TARGET_DIR}")
+endforeach()
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/dll/dllmain.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/dll/dllmain.cpp
new file mode 100644
index 0000000..9f5ce44
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/dll/dllmain.cpp
@@ -0,0 +1,15 @@
+// dllmain.cpp : Defines the entry point for the DLL application.
+#include <windows.h>
+
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
+{
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ case DLL_THREAD_ATTACH:
+ case DLL_THREAD_DETACH:
+ case DLL_PROCESS_DETACH:
+ break;
+ }
+ return TRUE;
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/filter_utils.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/filter_utils.cpp
new file mode 100644
index 0000000..09d740e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/filter_utils.cpp
@@ -0,0 +1,355 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <random>
+#include <string>
+#include <tuple>
+
+#include <omp.h>
+#include "filter_utils.h"
+#include "index.h"
+#include "parameters.h"
+#include "utils.h"
+
+namespace diskann
+{
+/*
+ * Using passed in parameters and files generated from step 3,
+ * builds a vanilla diskANN index for each label.
+ *
+ * Each index is saved under the following path:
+ * final_index_path_prefix + "_" + label
+ */
+template <typename T>
+void generate_label_indices(path input_data_path, path final_index_path_prefix, label_set all_labels, uint32_t R,
+ uint32_t L, float alpha, uint32_t num_threads)
+{
+ diskann::IndexWriteParameters label_index_build_parameters = diskann::IndexWriteParametersBuilder(L, R)
+ .with_saturate_graph(false)
+ .with_alpha(alpha)
+ .with_num_threads(num_threads)
+ .build();
+
+ std::cout << "Generating indices per label..." << std::endl;
+ // for each label, build an index on resp. points
+ double total_indexing_time = 0.0, indexing_percentage = 0.0;
+ std::cout.setstate(std::ios_base::failbit);
+ diskann::cout.setstate(std::ios_base::failbit);
+ for (const auto &lbl : all_labels)
+ {
+ path curr_label_input_data_path(input_data_path + "_" + lbl);
+ path curr_label_index_path(final_index_path_prefix + "_" + lbl);
+
+ size_t number_of_label_points, dimension;
+ diskann::get_bin_metadata(curr_label_input_data_path, number_of_label_points, dimension);
+
+ diskann::Index<T> index(diskann::Metric::L2, dimension, number_of_label_points,
+ std::make_shared<diskann::IndexWriteParameters>(label_index_build_parameters), nullptr,
+ 0, false, false, false, false, 0, false);
+
+ auto index_build_timer = std::chrono::high_resolution_clock::now();
+ index.build(curr_label_input_data_path.c_str(), number_of_label_points);
+ std::chrono::duration<double> current_indexing_time =
+ std::chrono::high_resolution_clock::now() - index_build_timer;
+
+ total_indexing_time += current_indexing_time.count();
+ indexing_percentage += (1 / (double)all_labels.size());
+ print_progress(indexing_percentage);
+
+ index.save(curr_label_index_path.c_str());
+ }
+ std::cout.clear();
+ diskann::cout.clear();
+
+ std::cout << "\nDone. Generated per-label indices in " << total_indexing_time << " seconds\n" << std::endl;
+}
+
+// for use on systems without writev (i.e. Windows)
+template <typename T>
+tsl::robin_map<std::string, std::vector<uint32_t>> generate_label_specific_vector_files_compat(
+ path input_data_path, tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ std::vector<label_set> point_ids_to_labels, label_set all_labels)
+{
+ auto file_writing_timer = std::chrono::high_resolution_clock::now();
+ std::ifstream input_data_stream(input_data_path);
+
+ uint32_t number_of_points, dimension;
+ input_data_stream.read((char *)&number_of_points, sizeof(uint32_t));
+ input_data_stream.read((char *)&dimension, sizeof(uint32_t));
+ const uint32_t VECTOR_SIZE = dimension * sizeof(T);
+ if (number_of_points != point_ids_to_labels.size())
+ {
+ std::cerr << "Error: number of points in labels file and data file differ." << std::endl;
+ throw;
+ }
+
+ tsl::robin_map<std::string, char *> labels_to_vectors;
+ tsl::robin_map<std::string, uint32_t> labels_to_curr_vector;
+ tsl::robin_map<std::string, std::vector<uint32_t>> label_id_to_orig_id;
+
+ for (const auto &lbl : all_labels)
+ {
+ uint32_t number_of_label_pts = labels_to_number_of_points[lbl];
+ char *vectors = (char *)malloc(number_of_label_pts * VECTOR_SIZE);
+ if (vectors == nullptr)
+ {
+ throw;
+ }
+ labels_to_vectors[lbl] = vectors;
+ labels_to_curr_vector[lbl] = 0;
+ label_id_to_orig_id[lbl].reserve(number_of_label_pts);
+ }
+
+ for (uint32_t point_id = 0; point_id < number_of_points; point_id++)
+ {
+ char *curr_vector = (char *)malloc(VECTOR_SIZE);
+ input_data_stream.read(curr_vector, VECTOR_SIZE);
+ for (const auto &lbl : point_ids_to_labels[point_id])
+ {
+ char *curr_label_vector_ptr = labels_to_vectors[lbl] + (labels_to_curr_vector[lbl] * VECTOR_SIZE);
+ memcpy(curr_label_vector_ptr, curr_vector, VECTOR_SIZE);
+ labels_to_curr_vector[lbl]++;
+ label_id_to_orig_id[lbl].push_back(point_id);
+ }
+ free(curr_vector);
+ }
+
+ for (const auto &lbl : all_labels)
+ {
+ path curr_label_input_data_path(input_data_path + "_" + lbl);
+ uint32_t number_of_label_pts = labels_to_number_of_points[lbl];
+
+ std::ofstream label_file_stream;
+ label_file_stream.exceptions(std::ios::badbit | std::ios::failbit);
+ label_file_stream.open(curr_label_input_data_path, std::ios_base::binary);
+ label_file_stream.write((char *)&number_of_label_pts, sizeof(uint32_t));
+ label_file_stream.write((char *)&dimension, sizeof(uint32_t));
+ label_file_stream.write((char *)labels_to_vectors[lbl], number_of_label_pts * VECTOR_SIZE);
+
+ label_file_stream.close();
+ free(labels_to_vectors[lbl]);
+ }
+ input_data_stream.close();
+
+ std::chrono::duration<double> file_writing_time = std::chrono::high_resolution_clock::now() - file_writing_timer;
+ std::cout << "generated " << all_labels.size() << " label-specific vector files for index building in time "
+ << file_writing_time.count() << "\n"
+ << std::endl;
+
+ return label_id_to_orig_id;
+}
+
+/*
+ * Manually loads a graph index in from a given file.
+ *
+ * Returns both the graph index and the size of the file in bytes.
+ */
+load_label_index_return_values load_label_index(path label_index_path, uint32_t label_number_of_points)
+{
+ std::ifstream label_index_stream;
+ label_index_stream.exceptions(std::ios::badbit | std::ios::failbit);
+ label_index_stream.open(label_index_path, std::ios::binary);
+
+ uint64_t index_file_size, index_num_frozen_points;
+ uint32_t index_max_observed_degree, index_entry_point;
+ const size_t INDEX_METADATA = 2 * sizeof(uint64_t) + 2 * sizeof(uint32_t);
+ label_index_stream.read((char *)&index_file_size, sizeof(uint64_t));
+ label_index_stream.read((char *)&index_max_observed_degree, sizeof(uint32_t));
+ label_index_stream.read((char *)&index_entry_point, sizeof(uint32_t));
+ label_index_stream.read((char *)&index_num_frozen_points, sizeof(uint64_t));
+ size_t bytes_read = INDEX_METADATA;
+
+ std::vector<std::vector<uint32_t>> label_index(label_number_of_points);
+ uint32_t nodes_read = 0;
+ while (bytes_read != index_file_size)
+ {
+ uint32_t current_node_num_neighbors;
+ label_index_stream.read((char *)&current_node_num_neighbors, sizeof(uint32_t));
+ nodes_read++;
+
+ std::vector<uint32_t> current_node_neighbors(current_node_num_neighbors);
+ label_index_stream.read((char *)current_node_neighbors.data(), current_node_num_neighbors * sizeof(uint32_t));
+ label_index[nodes_read - 1].swap(current_node_neighbors);
+ bytes_read += sizeof(uint32_t) * (current_node_num_neighbors + 1);
+ }
+
+ return std::make_tuple(label_index, index_file_size);
+}
+
+/*
+ * Parses the label datafile, which has comma-separated labels on
+ * each line. Line i corresponds to point id i.
+ *
+ * Returns three objects via std::tuple:
+ * 1. map: key is point id, value is vector of labels said point has
+ * 2. map: key is label, value is number of points with the label
+ * 3. the label universe as a set
+ */
+parse_label_file_return_values parse_label_file(path label_data_path, std::string universal_label)
+{
+ std::ifstream label_data_stream(label_data_path);
+ std::string line, token;
+ uint32_t line_cnt = 0;
+
+ // allows us to reserve space for the points_to_labels vector
+ while (std::getline(label_data_stream, line))
+ line_cnt++;
+ label_data_stream.clear();
+ label_data_stream.seekg(0, std::ios::beg);
+
+ // values to return
+ std::vector<label_set> point_ids_to_labels(line_cnt);
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points;
+ label_set all_labels;
+
+ std::vector<uint32_t> points_with_universal_label;
+ line_cnt = 0;
+ while (std::getline(label_data_stream, line))
+ {
+ std::istringstream current_labels_comma_separated(line);
+ label_set current_labels;
+
+ // get point id
+ uint32_t point_id = line_cnt;
+
+ // parse comma separated labels
+ bool current_universal_label_check = false;
+ while (getline(current_labels_comma_separated, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+
+ // if token is empty, there's no labels for the point
+ if (token == universal_label)
+ {
+ points_with_universal_label.push_back(point_id);
+ current_universal_label_check = true;
+ }
+ else
+ {
+ all_labels.insert(token);
+ current_labels.insert(token);
+ labels_to_number_of_points[token]++;
+ }
+ }
+
+ if (current_labels.size() <= 0 && !current_universal_label_check)
+ {
+ std::cerr << "Error: " << point_id << " has no labels." << std::endl;
+ exit(-1);
+ }
+ point_ids_to_labels[point_id] = current_labels;
+ line_cnt++;
+ }
+
+ // for every point with universal label, set its label set to all labels
+ // also, increment the count for number of points a label has
+ for (const auto &point_id : points_with_universal_label)
+ {
+ point_ids_to_labels[point_id] = all_labels;
+ for (const auto &lbl : all_labels)
+ labels_to_number_of_points[lbl]++;
+ }
+
+ std::cout << "Identified " << all_labels.size() << " distinct label(s) for " << point_ids_to_labels.size()
+ << " points\n"
+ << std::endl;
+
+ return std::make_tuple(point_ids_to_labels, labels_to_number_of_points, all_labels);
+}
+
+/*
+ * A templated function to parse a file of labels that are already represented
+ * as either uint16_t or uint32_t
+ *
+ * Returns two objects via std::tuple:
+ * 1. a vector of vectors of labels, where the outer vector is indexed by point id
+ * 2. a set of all labels
+ */
+template <typename LabelT>
+std::tuple<std::vector<std::vector<LabelT>>, tsl::robin_set<LabelT>> parse_formatted_label_file(std::string label_file)
+{
+ std::vector<std::vector<LabelT>> pts_to_labels;
+ tsl::robin_set<LabelT> labels;
+
+ // Format of Label txt file: filters with comma separators
+ std::ifstream infile(label_file);
+ if (infile.fail())
+ {
+ throw diskann::ANNException(std::string("Failed to open file ") + label_file, -1);
+ }
+
+ std::string line, token;
+ uint32_t line_cnt = 0;
+
+ while (std::getline(infile, line))
+ {
+ line_cnt++;
+ }
+ pts_to_labels.resize(line_cnt, std::vector<LabelT>());
+
+ infile.clear();
+ infile.seekg(0, std::ios::beg);
+ line_cnt = 0;
+
+ while (std::getline(infile, line))
+ {
+ std::istringstream iss(line);
+ std::vector<LabelT> lbls(0);
+ getline(iss, token, '\t');
+ std::istringstream new_iss(token);
+ while (getline(new_iss, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ LabelT token_as_num = static_cast<LabelT>(std::stoul(token));
+ lbls.push_back(token_as_num);
+ labels.insert(token_as_num);
+ }
+ if (lbls.size() <= 0)
+ {
+ diskann::cout << "No label found";
+ exit(-1);
+ }
+ std::sort(lbls.begin(), lbls.end());
+ pts_to_labels[line_cnt] = lbls;
+ line_cnt++;
+ }
+ diskann::cout << "Identified " << labels.size() << " distinct label(s)" << std::endl;
+
+ return std::make_tuple(pts_to_labels, labels);
+}
+
+template DISKANN_DLLEXPORT std::tuple<std::vector<std::vector<uint32_t>>, tsl::robin_set<uint32_t>>
+parse_formatted_label_file(path label_file);
+
+template DISKANN_DLLEXPORT std::tuple<std::vector<std::vector<uint16_t>>, tsl::robin_set<uint16_t>>
+parse_formatted_label_file(path label_file);
+
+template DISKANN_DLLEXPORT void generate_label_indices<float>(path input_data_path, path final_index_path_prefix,
+ label_set all_labels, uint32_t R, uint32_t L, float alpha,
+ uint32_t num_threads);
+template DISKANN_DLLEXPORT void generate_label_indices<uint8_t>(path input_data_path, path final_index_path_prefix,
+ label_set all_labels, uint32_t R, uint32_t L,
+ float alpha, uint32_t num_threads);
+template DISKANN_DLLEXPORT void generate_label_indices<int8_t>(path input_data_path, path final_index_path_prefix,
+ label_set all_labels, uint32_t R, uint32_t L,
+ float alpha, uint32_t num_threads);
+
+template DISKANN_DLLEXPORT tsl::robin_map<std::string, std::vector<uint32_t>>
+generate_label_specific_vector_files_compat<float>(path input_data_path,
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ std::vector<label_set> point_ids_to_labels, label_set all_labels);
+template DISKANN_DLLEXPORT tsl::robin_map<std::string, std::vector<uint32_t>>
+generate_label_specific_vector_files_compat<uint8_t>(path input_data_path,
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ std::vector<label_set> point_ids_to_labels, label_set all_labels);
+template DISKANN_DLLEXPORT tsl::robin_map<std::string, std::vector<uint32_t>>
+generate_label_specific_vector_files_compat<int8_t>(path input_data_path,
+ tsl::robin_map<std::string, uint32_t> labels_to_number_of_points,
+ std::vector<label_set> point_ids_to_labels, label_set all_labels);
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/in_mem_data_store.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/in_mem_data_store.cpp
new file mode 100644
index 0000000..cc7acf6
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/in_mem_data_store.cpp
@@ -0,0 +1,401 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <memory>
+#include "abstract_scratch.h"
+#include "in_mem_data_store.h"
+
+#include "utils.h"
+
+namespace diskann
+{
+
+template <typename data_t>
+InMemDataStore<data_t>::InMemDataStore(const location_t num_points, const size_t dim,
+ std::unique_ptr<Distance<data_t>> distance_fn)
+ : AbstractDataStore<data_t>(num_points, dim), _distance_fn(std::move(distance_fn))
+{
+ _aligned_dim = ROUND_UP(dim, _distance_fn->get_required_alignment());
+ alloc_aligned(((void **)&_data), this->_capacity * _aligned_dim * sizeof(data_t), 8 * sizeof(data_t));
+ std::memset(_data, 0, this->_capacity * _aligned_dim * sizeof(data_t));
+}
+
+template <typename data_t> InMemDataStore<data_t>::~InMemDataStore()
+{
+ if (_data != nullptr)
+ {
+ aligned_free(this->_data);
+ }
+}
+
+template <typename data_t> size_t InMemDataStore<data_t>::get_aligned_dim() const
+{
+ return _aligned_dim;
+}
+
+template <typename data_t> size_t InMemDataStore<data_t>::get_alignment_factor() const
+{
+ return _distance_fn->get_required_alignment();
+}
+
+template <typename data_t> location_t InMemDataStore<data_t>::load(const std::string &filename)
+{
+ return load_impl(filename);
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename data_t> location_t InMemDataStore<data_t>::load_impl(AlignedFileReader &reader)
+{
+ size_t file_dim, file_num_points;
+
+ diskann::get_bin_metadata(reader, file_num_points, file_dim);
+
+ if (file_dim != this->_dim)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << this->_dim << " dimension,"
+ << "but file has " << file_dim << " dimension." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ aligned_free(_data);
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (file_num_points > this->capacity())
+ {
+ this->resize((location_t)file_num_points);
+ }
+ copy_aligned_data_from_file<data_t>(reader, _data, file_num_points, file_dim, _aligned_dim);
+
+ return (location_t)file_num_points;
+}
+#endif
+
+template <typename data_t> location_t InMemDataStore<data_t>::load_impl(const std::string &filename)
+{
+ size_t file_dim, file_num_points;
+ if (!file_exists(filename))
+ {
+ std::stringstream stream;
+ stream << "ERROR: data file " << filename << " does not exist." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ aligned_free(_data);
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ diskann::get_bin_metadata(filename, file_num_points, file_dim);
+
+ if (file_dim != this->_dim)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << this->_dim << " dimension,"
+ << "but file has " << file_dim << " dimension." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ aligned_free(_data);
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (file_num_points > this->capacity())
+ {
+ this->resize((location_t)file_num_points);
+ }
+
+ copy_aligned_data_from_file<data_t>(filename.c_str(), _data, file_num_points, file_dim, _aligned_dim);
+
+ return (location_t)file_num_points;
+}
+
+template <typename data_t> size_t InMemDataStore<data_t>::save(const std::string &filename, const location_t num_points)
+{
+ return save_data_in_base_dimensions(filename, _data, num_points, this->get_dims(), this->get_aligned_dim(), 0U);
+}
+
+template <typename data_t> void InMemDataStore<data_t>::populate_data(const data_t *vectors, const location_t num_pts)
+{
+ memset(_data, 0, _aligned_dim * sizeof(data_t) * num_pts);
+ for (location_t i = 0; i < num_pts; i++)
+ {
+ std::memmove(_data + i * _aligned_dim, vectors + i * this->_dim, this->_dim * sizeof(data_t));
+ }
+
+ if (_distance_fn->preprocessing_required())
+ {
+ _distance_fn->preprocess_base_points(_data, this->_aligned_dim, num_pts);
+ }
+}
+
+template <typename data_t> void InMemDataStore<data_t>::populate_data(const std::string &filename, const size_t offset)
+{
+ size_t npts, ndim;
+ copy_aligned_data_from_file(filename.c_str(), _data, npts, ndim, _aligned_dim, offset);
+
+ if ((location_t)npts > this->capacity())
+ {
+ std::stringstream ss;
+ ss << "Number of points in the file: " << filename
+ << " is greater than the capacity of data store: " << this->capacity()
+ << ". Must invoke resize before calling populate_data()" << std::endl;
+ throw diskann::ANNException(ss.str(), -1);
+ }
+
+ if ((location_t)ndim != this->get_dims())
+ {
+ std::stringstream ss;
+ ss << "Number of dimensions of a point in the file: " << filename
+ << " is not equal to dimensions of data store: " << this->capacity() << "." << std::endl;
+ throw diskann::ANNException(ss.str(), -1);
+ }
+
+ if (_distance_fn->preprocessing_required())
+ {
+ _distance_fn->preprocess_base_points(_data, this->_aligned_dim, this->capacity());
+ }
+}
+
+template <typename data_t>
+void InMemDataStore<data_t>::extract_data_to_bin(const std::string &filename, const location_t num_points)
+{
+ save_data_in_base_dimensions(filename, _data, num_points, this->get_dims(), this->get_aligned_dim(), 0U);
+}
+
+template <typename data_t> void InMemDataStore<data_t>::get_vector(const location_t i, data_t *dest) const
+{
+ // REFACTOR TODO: Should we denormalize and return values?
+ memcpy(dest, _data + i * _aligned_dim, this->_dim * sizeof(data_t));
+}
+
+template <typename data_t> void InMemDataStore<data_t>::set_vector(const location_t loc, const data_t *const vector)
+{
+ size_t offset_in_data = loc * _aligned_dim;
+ memset(_data + offset_in_data, 0, _aligned_dim * sizeof(data_t));
+ memcpy(_data + offset_in_data, vector, this->_dim * sizeof(data_t));
+ if (_distance_fn->preprocessing_required())
+ {
+ _distance_fn->preprocess_base_points(_data + offset_in_data, _aligned_dim, 1);
+ }
+}
+
+template <typename data_t> void InMemDataStore<data_t>::prefetch_vector(const location_t loc)
+{
+ diskann::prefetch_vector((const char *)_data + _aligned_dim * (size_t)loc * sizeof(data_t),
+ sizeof(data_t) * _aligned_dim);
+}
+
+template <typename data_t>
+void InMemDataStore<data_t>::preprocess_query(const data_t *query, AbstractScratch<data_t> *query_scratch) const
+{
+ if (query_scratch != nullptr)
+ {
+ memcpy(query_scratch->aligned_query_T(), query, sizeof(data_t) * this->get_dims());
+ }
+ else
+ {
+ std::stringstream ss;
+ ss << "In InMemDataStore::preprocess_query: Query scratch is null";
+ diskann::cerr << ss.str() << std::endl;
+ throw diskann::ANNException(ss.str(), -1);
+ }
+}
+
+template <typename data_t> float InMemDataStore<data_t>::get_distance(const data_t *query, const location_t loc) const
+{
+ return _distance_fn->compare(query, _data + _aligned_dim * loc, (uint32_t)_aligned_dim);
+}
+
+template <typename data_t>
+void InMemDataStore<data_t>::get_distance(const data_t *query, const location_t *locations,
+ const uint32_t location_count, float *distances,
+ AbstractScratch<data_t> *scratch_space) const
+{
+ for (location_t i = 0; i < location_count; i++)
+ {
+ distances[i] = _distance_fn->compare(query, _data + locations[i] * _aligned_dim, (uint32_t)this->_aligned_dim);
+ }
+}
+
+template <typename data_t>
+float InMemDataStore<data_t>::get_distance(const location_t loc1, const location_t loc2) const
+{
+ return _distance_fn->compare(_data + loc1 * _aligned_dim, _data + loc2 * _aligned_dim,
+ (uint32_t)this->_aligned_dim);
+}
+
+template <typename data_t>
+void InMemDataStore<data_t>::get_distance(const data_t *preprocessed_query, const std::vector<location_t> &ids,
+ std::vector<float> &distances, AbstractScratch<data_t> *scratch_space) const
+{
+ for (int i = 0; i < ids.size(); i++)
+ {
+ distances[i] =
+ _distance_fn->compare(preprocessed_query, _data + ids[i] * _aligned_dim, (uint32_t)this->_aligned_dim);
+ }
+}
+
+template <typename data_t> location_t InMemDataStore<data_t>::expand(const location_t new_size)
+{
+ if (new_size == this->capacity())
+ {
+ return this->capacity();
+ }
+ else if (new_size < this->capacity())
+ {
+ std::stringstream ss;
+ ss << "Cannot 'expand' datastore when new capacity (" << new_size << ") < existing capacity("
+ << this->capacity() << ")" << std::endl;
+ throw diskann::ANNException(ss.str(), -1);
+ }
+#ifndef _WINDOWS
+ data_t *new_data;
+ alloc_aligned((void **)&new_data, new_size * _aligned_dim * sizeof(data_t), 8 * sizeof(data_t));
+ memcpy(new_data, _data, this->capacity() * _aligned_dim * sizeof(data_t));
+ aligned_free(_data);
+ _data = new_data;
+#else
+ realloc_aligned((void **)&_data, new_size * _aligned_dim * sizeof(data_t), 8 * sizeof(data_t));
+#endif
+ this->_capacity = new_size;
+ return this->_capacity;
+}
+
+template <typename data_t> location_t InMemDataStore<data_t>::shrink(const location_t new_size)
+{
+ if (new_size == this->capacity())
+ {
+ return this->capacity();
+ }
+ else if (new_size > this->capacity())
+ {
+ std::stringstream ss;
+ ss << "Cannot 'shrink' datastore when new capacity (" << new_size << ") > existing capacity("
+ << this->capacity() << ")" << std::endl;
+ throw diskann::ANNException(ss.str(), -1);
+ }
+#ifndef _WINDOWS
+ data_t *new_data;
+ alloc_aligned((void **)&new_data, new_size * _aligned_dim * sizeof(data_t), 8 * sizeof(data_t));
+ memcpy(new_data, _data, new_size * _aligned_dim * sizeof(data_t));
+ aligned_free(_data);
+ _data = new_data;
+#else
+ realloc_aligned((void **)&_data, new_size * _aligned_dim * sizeof(data_t), 8 * sizeof(data_t));
+#endif
+ this->_capacity = new_size;
+ return this->_capacity;
+}
+
+template <typename data_t>
+void InMemDataStore<data_t>::move_vectors(const location_t old_location_start, const location_t new_location_start,
+ const location_t num_locations)
+{
+ if (num_locations == 0 || old_location_start == new_location_start)
+ {
+ return;
+ }
+
+ /* // Update pointers to the moved nodes. Note: the computation is correct
+ even
+ // when new_location_start < old_location_start given the C++ uint32_t
+ // integer arithmetic rules.
+ const uint32_t location_delta = new_location_start - old_location_start;
+ */
+ // The [start, end) interval which will contain obsolete points to be
+ // cleared.
+ uint32_t mem_clear_loc_start = old_location_start;
+ uint32_t mem_clear_loc_end_limit = old_location_start + num_locations;
+
+ if (new_location_start < old_location_start)
+ {
+ // If ranges are overlapping, make sure not to clear the newly copied
+ // data.
+ if (mem_clear_loc_start < new_location_start + num_locations)
+ {
+ // Clear only after the end of the new range.
+ mem_clear_loc_start = new_location_start + num_locations;
+ }
+ }
+ else
+ {
+ // If ranges are overlapping, make sure not to clear the newly copied
+ // data.
+ if (mem_clear_loc_end_limit > new_location_start)
+ {
+ // Clear only up to the beginning of the new range.
+ mem_clear_loc_end_limit = new_location_start;
+ }
+ }
+
+ // Use memmove to handle overlapping ranges.
+ copy_vectors(old_location_start, new_location_start, num_locations);
+ memset(_data + _aligned_dim * mem_clear_loc_start, 0,
+ sizeof(data_t) * _aligned_dim * (mem_clear_loc_end_limit - mem_clear_loc_start));
+}
+
+template <typename data_t>
+void InMemDataStore<data_t>::copy_vectors(const location_t from_loc, const location_t to_loc,
+ const location_t num_points)
+{
+ assert(from_loc < this->_capacity);
+ assert(to_loc < this->_capacity);
+ assert(num_points < this->_capacity);
+ memmove(_data + _aligned_dim * to_loc, _data + _aligned_dim * from_loc, num_points * _aligned_dim * sizeof(data_t));
+}
+
+template <typename data_t> location_t InMemDataStore<data_t>::calculate_medoid() const
+{
+ // allocate and init centroid
+ float *center = new float[_aligned_dim];
+ for (size_t j = 0; j < _aligned_dim; j++)
+ center[j] = 0;
+
+ for (size_t i = 0; i < this->capacity(); i++)
+ for (size_t j = 0; j < _aligned_dim; j++)
+ center[j] += (float)_data[i * _aligned_dim + j];
+
+ for (size_t j = 0; j < _aligned_dim; j++)
+ center[j] /= (float)this->capacity();
+
+ // compute all to one distance
+ float *distances = new float[this->capacity()];
+
+ // TODO: REFACTOR. Removing pragma might make this slow. Must revisit.
+ // Problem is that we need to pass num_threads here, it is not clear
+ // if data store must be aware of threads!
+ // #pragma omp parallel for schedule(static, 65536)
+ for (int64_t i = 0; i < (int64_t)this->capacity(); i++)
+ {
+ // extract point and distance reference
+ float &dist = distances[i];
+ const data_t *cur_vec = _data + (i * (size_t)_aligned_dim);
+ dist = 0;
+ float diff = 0;
+ for (size_t j = 0; j < _aligned_dim; j++)
+ {
+ diff = (center[j] - (float)cur_vec[j]) * (center[j] - (float)cur_vec[j]);
+ dist += diff;
+ }
+ }
+ // find imin
+ uint32_t min_idx = 0;
+ float min_dist = distances[0];
+ for (uint32_t i = 1; i < this->capacity(); i++)
+ {
+ if (distances[i] < min_dist)
+ {
+ min_idx = i;
+ min_dist = distances[i];
+ }
+ }
+
+ delete[] distances;
+ delete[] center;
+ return min_idx;
+}
+
+template <typename data_t> Distance<data_t> *InMemDataStore<data_t>::get_dist_fn() const
+{
+ return this->_distance_fn.get();
+}
+
+template DISKANN_DLLEXPORT class InMemDataStore<float>;
+template DISKANN_DLLEXPORT class InMemDataStore<int8_t>;
+template DISKANN_DLLEXPORT class InMemDataStore<uint8_t>;
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/in_mem_graph_store.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/in_mem_graph_store.cpp
new file mode 100644
index 0000000..c12b251
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/in_mem_graph_store.cpp
@@ -0,0 +1,242 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "in_mem_graph_store.h"
+#include "utils.h"
+
+namespace diskann
+{
+InMemGraphStore::InMemGraphStore(const size_t total_pts, const size_t reserve_graph_degree)
+ : AbstractGraphStore(total_pts, reserve_graph_degree)
+{
+ this->resize_graph(total_pts);
+ for (size_t i = 0; i < total_pts; i++)
+ {
+ _graph[i].reserve(reserve_graph_degree);
+ }
+}
+
+std::tuple<uint32_t, uint32_t, size_t> InMemGraphStore::load(const std::string &index_path_prefix,
+ const size_t num_points)
+{
+ return load_impl(index_path_prefix, num_points);
+}
+int InMemGraphStore::store(const std::string &index_path_prefix, const size_t num_points,
+ const size_t num_frozen_points, const uint32_t start)
+{
+ return save_graph(index_path_prefix, num_points, num_frozen_points, start);
+}
+const std::vector<location_t> &InMemGraphStore::get_neighbours(const location_t i) const
+{
+ return _graph.at(i);
+}
+
+void InMemGraphStore::add_neighbour(const location_t i, location_t neighbour_id)
+{
+ _graph[i].emplace_back(neighbour_id);
+ if (_max_observed_degree < _graph[i].size())
+ {
+ _max_observed_degree = (uint32_t)(_graph[i].size());
+ }
+}
+
+void InMemGraphStore::clear_neighbours(const location_t i)
+{
+ _graph[i].clear();
+};
+void InMemGraphStore::swap_neighbours(const location_t a, location_t b)
+{
+ _graph[a].swap(_graph[b]);
+};
+
+void InMemGraphStore::set_neighbours(const location_t i, std::vector<location_t> &neighbours)
+{
+ _graph[i].assign(neighbours.begin(), neighbours.end());
+ if (_max_observed_degree < neighbours.size())
+ {
+ _max_observed_degree = (uint32_t)(neighbours.size());
+ }
+}
+
+size_t InMemGraphStore::resize_graph(const size_t new_size)
+{
+ _graph.resize(new_size);
+ set_total_points(new_size);
+ return _graph.size();
+}
+
+void InMemGraphStore::clear_graph()
+{
+ _graph.clear();
+}
+
+#ifdef EXEC_ENV_OLS
+std::tuple<uint32_t, uint32_t, size_t> InMemGraphStore::load_impl(AlignedFileReader &reader, size_t expected_num_points)
+{
+ size_t expected_file_size;
+ size_t file_frozen_pts;
+ uint32_t start;
+
+ auto max_points = get_max_points();
+ int header_size = 2 * sizeof(size_t) + 2 * sizeof(uint32_t);
+ std::unique_ptr<char[]> header = std::make_unique<char[]>(header_size);
+ read_array(reader, header.get(), header_size);
+
+ expected_file_size = *((size_t *)header.get());
+ _max_observed_degree = *((uint32_t *)(header.get() + sizeof(size_t)));
+ start = *((uint32_t *)(header.get() + sizeof(size_t) + sizeof(uint32_t)));
+ file_frozen_pts = *((size_t *)(header.get() + sizeof(size_t) + sizeof(uint32_t) + sizeof(uint32_t)));
+
+ diskann::cout << "From graph header, expected_file_size: " << expected_file_size
+ << ", _max_observed_degree: " << _max_observed_degree << ", _start: " << start
+ << ", file_frozen_pts: " << file_frozen_pts << std::endl;
+
+ diskann::cout << "Loading vamana graph from reader..." << std::flush;
+
+ // If user provides more points than max_points
+ // resize the _graph to the larger size.
+ if (get_total_points() < expected_num_points)
+ {
+ diskann::cout << "resizing graph to " << expected_num_points << std::endl;
+ this->resize_graph(expected_num_points);
+ }
+
+ uint32_t nodes_read = 0;
+ size_t cc = 0;
+ size_t graph_offset = header_size;
+ while (nodes_read < expected_num_points)
+ {
+ uint32_t k;
+ read_value(reader, k, graph_offset);
+ graph_offset += sizeof(uint32_t);
+ std::vector<uint32_t> tmp(k);
+ tmp.reserve(k);
+ read_array(reader, tmp.data(), k, graph_offset);
+ graph_offset += k * sizeof(uint32_t);
+ cc += k;
+ _graph[nodes_read].swap(tmp);
+ nodes_read++;
+ if (nodes_read % 1000000 == 0)
+ {
+ diskann::cout << "." << std::flush;
+ }
+ if (k > _max_range_of_graph)
+ {
+ _max_range_of_graph = k;
+ }
+ }
+
+ diskann::cout << "done. Index has " << nodes_read << " nodes and " << cc << " out-edges, _start is set to " << start
+ << std::endl;
+ return std::make_tuple(nodes_read, start, file_frozen_pts);
+}
+#endif
+
+std::tuple<uint32_t, uint32_t, size_t> InMemGraphStore::load_impl(const std::string &filename,
+ size_t expected_num_points)
+{
+ size_t expected_file_size;
+ size_t file_frozen_pts;
+ uint32_t start;
+ size_t file_offset = 0; // will need this for single file format support
+
+ std::ifstream in;
+ in.exceptions(std::ios::badbit | std::ios::failbit);
+ in.open(filename, std::ios::binary);
+ in.seekg(file_offset, in.beg);
+ in.read((char *)&expected_file_size, sizeof(size_t));
+ in.read((char *)&_max_observed_degree, sizeof(uint32_t));
+ in.read((char *)&start, sizeof(uint32_t));
+ in.read((char *)&file_frozen_pts, sizeof(size_t));
+ size_t vamana_metadata_size = sizeof(size_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(size_t);
+
+ diskann::cout << "From graph header, expected_file_size: " << expected_file_size
+ << ", _max_observed_degree: " << _max_observed_degree << ", _start: " << start
+ << ", file_frozen_pts: " << file_frozen_pts << std::endl;
+
+ diskann::cout << "Loading vamana graph " << filename << "..." << std::flush;
+
+ // If user provides more points than max_points
+ // resize the _graph to the larger size.
+ if (get_total_points() < expected_num_points)
+ {
+ diskann::cout << "resizing graph to " << expected_num_points << std::endl;
+ this->resize_graph(expected_num_points);
+ }
+
+ size_t bytes_read = vamana_metadata_size;
+ size_t cc = 0;
+ uint32_t nodes_read = 0;
+ while (bytes_read != expected_file_size)
+ {
+ uint32_t k;
+ in.read((char *)&k, sizeof(uint32_t));
+
+ if (k == 0)
+ {
+ diskann::cerr << "ERROR: Point found with no out-neighbours, point#" << nodes_read << std::endl;
+ }
+
+ cc += k;
+ ++nodes_read;
+ std::vector<uint32_t> tmp(k);
+ tmp.reserve(k);
+ in.read((char *)tmp.data(), k * sizeof(uint32_t));
+ _graph[nodes_read - 1].swap(tmp);
+ bytes_read += sizeof(uint32_t) * ((size_t)k + 1);
+ if (nodes_read % 10000000 == 0)
+ diskann::cout << "." << std::flush;
+ if (k > _max_range_of_graph)
+ {
+ _max_range_of_graph = k;
+ }
+ }
+
+ diskann::cout << "done. Index has " << nodes_read << " nodes and " << cc << " out-edges, _start is set to " << start
+ << std::endl;
+ return std::make_tuple(nodes_read, start, file_frozen_pts);
+}
+
+int InMemGraphStore::save_graph(const std::string &index_path_prefix, const size_t num_points,
+ const size_t num_frozen_points, const uint32_t start)
+{
+ std::ofstream out;
+ open_file_to_write(out, index_path_prefix);
+
+ size_t file_offset = 0;
+ out.seekp(file_offset, out.beg);
+ size_t index_size = 24;
+ uint32_t max_degree = 0;
+ out.write((char *)&index_size, sizeof(uint64_t));
+ out.write((char *)&_max_observed_degree, sizeof(uint32_t));
+ uint32_t ep_u32 = start;
+ out.write((char *)&ep_u32, sizeof(uint32_t));
+ out.write((char *)&num_frozen_points, sizeof(size_t));
+
+ // Note: num_points = _nd + _num_frozen_points
+ for (uint32_t i = 0; i < num_points; i++)
+ {
+ uint32_t GK = (uint32_t)_graph[i].size();
+ out.write((char *)&GK, sizeof(uint32_t));
+ out.write((char *)_graph[i].data(), GK * sizeof(uint32_t));
+ max_degree = _graph[i].size() > max_degree ? (uint32_t)_graph[i].size() : max_degree;
+ index_size += (size_t)(sizeof(uint32_t) * (GK + 1));
+ }
+ out.seekp(file_offset, out.beg);
+ out.write((char *)&index_size, sizeof(uint64_t));
+ out.write((char *)&max_degree, sizeof(uint32_t));
+ out.close();
+ return (int)index_size;
+}
+
+size_t InMemGraphStore::get_max_range_of_graph()
+{
+ return _max_range_of_graph;
+}
+
+uint32_t InMemGraphStore::get_max_observed_degree()
+{
+ return _max_observed_degree;
+}
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/index.cpp
new file mode 100644
index 0000000..7f26288
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/index.cpp
@@ -0,0 +1,3524 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <omp.h>
+
+#include <type_traits>
+
+#include "boost/dynamic_bitset.hpp"
+#include "index_factory.h"
+#include "memory_mapper.h"
+#include "timer.h"
+#include "tsl/robin_map.h"
+#include "tsl/robin_set.h"
+#include "windows_customizations.h"
+#include "tag_uint128.h"
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+#include "gperftools/malloc_extension.h"
+#endif
+
+#ifdef _WINDOWS
+#include <xmmintrin.h>
+#endif
+
+#include "index.h"
+
+#define MAX_POINTS_FOR_USING_BITSET 10000000
+
+namespace diskann
+{
+// Initialize an index with metric m, load the data of type T with filename
+// (bin), and initialize max_points
+template <typename T, typename TagT, typename LabelT>
+Index<T, TagT, LabelT>::Index(const IndexConfig &index_config, std::shared_ptr<AbstractDataStore<T>> data_store,
+ std::unique_ptr<AbstractGraphStore> graph_store,
+ std::shared_ptr<AbstractDataStore<T>> pq_data_store)
+ : _dist_metric(index_config.metric), _dim(index_config.dimension), _max_points(index_config.max_points),
+ _num_frozen_pts(index_config.num_frozen_pts), _dynamic_index(index_config.dynamic_index),
+ _enable_tags(index_config.enable_tags), _indexingMaxC(DEFAULT_MAXC), _query_scratch(nullptr),
+ _pq_dist(index_config.pq_dist_build), _use_opq(index_config.use_opq),
+ _filtered_index(index_config.filtered_index), _num_pq_chunks(index_config.num_pq_chunks),
+ _delete_set(new tsl::robin_set<uint32_t>), _conc_consolidate(index_config.concurrent_consolidate)
+{
+ if (_dynamic_index && !_enable_tags)
+ {
+ throw ANNException("ERROR: Dynamic Indexing must have tags enabled.", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (_pq_dist)
+ {
+ if (_dynamic_index)
+ throw ANNException("ERROR: Dynamic Indexing not supported with PQ distance based "
+ "index construction",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ if (_dist_metric == diskann::Metric::INNER_PRODUCT)
+ throw ANNException("ERROR: Inner product metrics not yet supported "
+ "with PQ distance "
+ "base index",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (_dynamic_index && _num_frozen_pts == 0)
+ {
+ _num_frozen_pts = 1;
+ }
+ // Sanity check. While logically it is correct, max_points = 0 causes
+ // downstream problems.
+ if (_max_points == 0)
+ {
+ _max_points = 1;
+ }
+ const size_t total_internal_points = _max_points + _num_frozen_pts;
+
+ _start = (uint32_t)_max_points;
+
+ _data_store = data_store;
+ _pq_data_store = pq_data_store;
+ _graph_store = std::move(graph_store);
+
+ _locks = std::vector<non_recursive_mutex>(total_internal_points);
+ if (_enable_tags)
+ {
+ _location_to_tag.reserve(total_internal_points);
+ _tag_to_location.reserve(total_internal_points);
+ }
+
+ if (_dynamic_index)
+ {
+ this->enable_delete(); // enable delete by default for dynamic index
+ if (_filtered_index)
+ {
+ _location_to_labels.resize(total_internal_points);
+ }
+ }
+
+ if (index_config.index_write_params != nullptr)
+ {
+ _indexingQueueSize = index_config.index_write_params->search_list_size;
+ _indexingRange = index_config.index_write_params->max_degree;
+ _indexingMaxC = index_config.index_write_params->max_occlusion_size;
+ _indexingAlpha = index_config.index_write_params->alpha;
+ _filterIndexingQueueSize = index_config.index_write_params->filter_list_size;
+ _indexingThreads = index_config.index_write_params->num_threads;
+ _saturate_graph = index_config.index_write_params->saturate_graph;
+
+ if (index_config.index_search_params != nullptr)
+ {
+ uint32_t num_scratch_spaces = index_config.index_search_params->num_search_threads + _indexingThreads;
+ initialize_query_scratch(num_scratch_spaces, index_config.index_search_params->initial_search_list_size,
+ _indexingQueueSize, _indexingRange, _indexingMaxC, _data_store->get_dims());
+ }
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+Index<T, TagT, LabelT>::Index(Metric m, const size_t dim, const size_t max_points,
+ const std::shared_ptr<IndexWriteParameters> index_parameters,
+ const std::shared_ptr<IndexSearchParams> index_search_params, const size_t num_frozen_pts,
+ const bool dynamic_index, const bool enable_tags, const bool concurrent_consolidate,
+ const bool pq_dist_build, const size_t num_pq_chunks, const bool use_opq,
+ const bool filtered_index)
+ : Index(
+ IndexConfigBuilder()
+ .with_metric(m)
+ .with_dimension(dim)
+ .with_max_points(max_points)
+ .with_index_write_params(index_parameters)
+ .with_index_search_params(index_search_params)
+ .with_num_frozen_pts(num_frozen_pts)
+ .is_dynamic_index(dynamic_index)
+ .is_enable_tags(enable_tags)
+ .is_concurrent_consolidate(concurrent_consolidate)
+ .is_pq_dist_build(pq_dist_build)
+ .with_num_pq_chunks(num_pq_chunks)
+ .is_use_opq(use_opq)
+ .is_filtered(filtered_index)
+ .with_data_type(diskann_type_to_name<T>())
+ .build(),
+ IndexFactory::construct_datastore<T>(DataStoreStrategy::MEMORY,
+ (max_points == 0 ? (size_t)1 : max_points) +
+ (dynamic_index && num_frozen_pts == 0 ? (size_t)1 : num_frozen_pts),
+ dim, m),
+ IndexFactory::construct_graphstore(GraphStoreStrategy::MEMORY,
+ (max_points == 0 ? (size_t)1 : max_points) +
+ (dynamic_index && num_frozen_pts == 0 ? (size_t)1 : num_frozen_pts),
+ (size_t)((index_parameters == nullptr ? 0 : index_parameters->max_degree) *
+ defaults::GRAPH_SLACK_FACTOR * 1.05)))
+{
+ if (_pq_dist)
+ {
+ _pq_data_store = IndexFactory::construct_pq_datastore<T>(DataStoreStrategy::MEMORY, max_points + num_frozen_pts,
+ dim, m, num_pq_chunks, use_opq);
+ }
+ else
+ {
+ _pq_data_store = _data_store;
+ }
+}
+
+template <typename T, typename TagT, typename LabelT> Index<T, TagT, LabelT>::~Index()
+{
+ // Ensure that no other activity is happening before dtor()
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+
+ for (auto &lock : _locks)
+ {
+ LockGuard lg(lock);
+ }
+
+ if (_opt_graph != nullptr)
+ {
+ delete[] _opt_graph;
+ }
+
+ if (!_query_scratch.empty())
+ {
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ manager.destroy();
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::initialize_query_scratch(uint32_t num_threads, uint32_t search_l, uint32_t indexing_l,
+ uint32_t r, uint32_t maxc, size_t dim)
+{
+ for (uint32_t i = 0; i < num_threads; i++)
+ {
+ auto scratch = new InMemQueryScratch<T>(search_l, indexing_l, r, maxc, dim, _data_store->get_aligned_dim(),
+ _data_store->get_alignment_factor(), _pq_dist);
+ _query_scratch.push(scratch);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::save_tags(std::string tags_file)
+{
+ if (!_enable_tags)
+ {
+ diskann::cout << "Not saving tags as they are not enabled." << std::endl;
+ return 0;
+ }
+
+ size_t tag_bytes_written;
+ TagT *tag_data = new TagT[_nd + _num_frozen_pts];
+ for (uint32_t i = 0; i < _nd; i++)
+ {
+ TagT tag;
+ if (_location_to_tag.try_get(i, tag))
+ {
+ tag_data[i] = tag;
+ }
+ else
+ {
+ // catering to future when tagT can be any type.
+ std::memset((char *)&tag_data[i], 0, sizeof(TagT));
+ }
+ }
+ if (_num_frozen_pts > 0)
+ {
+ std::memset((char *)&tag_data[_start], 0, sizeof(TagT) * _num_frozen_pts);
+ }
+ try
+ {
+ tag_bytes_written = save_bin<TagT>(tags_file, tag_data, _nd + _num_frozen_pts, 1);
+ }
+ catch (std::system_error &e)
+ {
+ throw FileException(tags_file, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ delete[] tag_data;
+ return tag_bytes_written;
+}
+
+template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::save_data(std::string data_file)
+{
+ // Note: at this point, either _nd == _max_points or any frozen points have
+ // been temporarily moved to _nd, so _nd + _num_frozen_pts is the valid
+ // location limit.
+ return _data_store->save(data_file, (location_t)(_nd + _num_frozen_pts));
+}
+
+// save the graph index on a file as an adjacency list. For each point,
+// first store the number of neighbors, and then the neighbor list (each as
+// 4 byte uint32_t)
+template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::save_graph(std::string graph_file)
+{
+ return _graph_store->store(graph_file, _nd + _num_frozen_pts, _num_frozen_pts, _start);
+}
+
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::save_delete_list(const std::string &filename)
+{
+ if (_delete_set->size() == 0)
+ {
+ return 0;
+ }
+ std::unique_ptr<uint32_t[]> delete_list = std::make_unique<uint32_t[]>(_delete_set->size());
+ uint32_t i = 0;
+ for (auto &del : *_delete_set)
+ {
+ delete_list[i++] = del;
+ }
+ return save_bin<uint32_t>(filename, delete_list.get(), _delete_set->size(), 1);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::save(const char *filename, bool compact_before_save)
+{
+ diskann::Timer timer;
+
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+
+ if (compact_before_save)
+ {
+ compact_data();
+ compact_frozen_point();
+ }
+ else
+ {
+ if (!_data_compacted)
+ {
+ throw ANNException("Index save for non-compacted index is not yet implemented", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+ }
+
+ if (!_save_as_one_file)
+ {
+ if (_filtered_index)
+ {
+ if (_label_to_start_id.size() > 0)
+ {
+ std::ofstream medoid_writer(std::string(filename) + "_labels_to_medoids.txt");
+ if (medoid_writer.fail())
+ {
+ throw diskann::ANNException(std::string("Failed to open file ") + filename, -1);
+ }
+ for (auto iter : _label_to_start_id)
+ {
+ medoid_writer << iter.first << ", " << iter.second << std::endl;
+ }
+ medoid_writer.close();
+ }
+
+ if (_use_universal_label)
+ {
+ std::ofstream universal_label_writer(std::string(filename) + "_universal_label.txt");
+ assert(universal_label_writer.is_open());
+ universal_label_writer << _universal_label << std::endl;
+ universal_label_writer.close();
+ }
+
+ if (_location_to_labels.size() > 0)
+ {
+ std::ofstream label_writer(std::string(filename) + "_labels.txt");
+ assert(label_writer.is_open());
+ for (uint32_t i = 0; i < _nd + _num_frozen_pts; i++)
+ {
+ for (uint32_t j = 0; j + 1 < _location_to_labels[i].size(); j++)
+ {
+ label_writer << _location_to_labels[i][j] << ",";
+ }
+ if (_location_to_labels[i].size() != 0)
+ label_writer << _location_to_labels[i][_location_to_labels[i].size() - 1];
+
+ label_writer << std::endl;
+ }
+ label_writer.close();
+
+ // write compacted raw_labels if data hence _location_to_labels was also compacted
+ if (compact_before_save && _dynamic_index)
+ {
+ _label_map = load_label_map(std::string(filename) + "_labels_map.txt");
+ std::unordered_map<LabelT, std::string> mapped_to_raw_labels;
+ // invert label map
+ for (const auto &[key, value] : _label_map)
+ {
+ mapped_to_raw_labels.insert({value, key});
+ }
+
+ // write updated labels
+ std::ofstream raw_label_writer(std::string(filename) + "_raw_labels.txt");
+ assert(raw_label_writer.is_open());
+ for (uint32_t i = 0; i < _nd + _num_frozen_pts; i++)
+ {
+ for (uint32_t j = 0; j + 1 < _location_to_labels[i].size(); j++)
+ {
+ raw_label_writer << mapped_to_raw_labels[_location_to_labels[i][j]] << ",";
+ }
+ if (_location_to_labels[i].size() != 0)
+ raw_label_writer
+ << mapped_to_raw_labels[_location_to_labels[i][_location_to_labels[i].size() - 1]];
+
+ raw_label_writer << std::endl;
+ }
+ raw_label_writer.close();
+ }
+ }
+ }
+
+ std::string graph_file = std::string(filename);
+ std::string tags_file = std::string(filename) + ".tags";
+ std::string data_file = std::string(filename) + ".data";
+ std::string delete_list_file = std::string(filename) + ".del";
+
+ // Because the save_* functions use append mode, ensure that
+ // the files are deleted before save. Ideally, we should check
+ // the error code for delete_file, but will ignore now because
+ // delete should succeed if save will succeed.
+ delete_file(graph_file);
+ save_graph(graph_file);
+ delete_file(data_file);
+ save_data(data_file);
+ delete_file(tags_file);
+ save_tags(tags_file);
+ delete_file(delete_list_file);
+ save_delete_list(delete_list_file);
+ }
+ else
+ {
+ diskann::cout << "Save index in a single file currently not supported. "
+ "Not saving the index."
+ << std::endl;
+ }
+
+ // If frozen points were temporarily compacted to _nd, move back to
+ // _max_points.
+ reposition_frozen_point_to_end();
+
+ diskann::cout << "Time taken for save: " << timer.elapsed() / 1000000.0 << "s." << std::endl;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::load_tags(AlignedFileReader &reader)
+{
+#else
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::load_tags(const std::string tag_filename)
+{
+ if (_enable_tags && !file_exists(tag_filename))
+ {
+ diskann::cerr << "Tag file " << tag_filename << " does not exist!" << std::endl;
+ throw diskann::ANNException("Tag file " + tag_filename + " does not exist!", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+#endif
+ if (!_enable_tags)
+ {
+ diskann::cout << "Tags not loaded as tags not enabled." << std::endl;
+ return 0;
+ }
+
+ size_t file_dim, file_num_points;
+ TagT *tag_data;
+#ifdef EXEC_ENV_OLS
+ load_bin<TagT>(reader, tag_data, file_num_points, file_dim);
+#else
+ load_bin<TagT>(std::string(tag_filename), tag_data, file_num_points, file_dim);
+#endif
+
+ if (file_dim != 1)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Found " << file_dim << " dimensions for tags,"
+ << "but tag file must have 1 dimension." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ delete[] tag_data;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ const size_t num_data_points = file_num_points - _num_frozen_pts;
+ _location_to_tag.reserve(num_data_points);
+ _tag_to_location.reserve(num_data_points);
+ for (uint32_t i = 0; i < (uint32_t)num_data_points; i++)
+ {
+ TagT tag = *(tag_data + i);
+ if (_delete_set->find(i) == _delete_set->end())
+ {
+ _location_to_tag.set(i, tag);
+ _tag_to_location[tag] = i;
+ }
+ }
+ diskann::cout << "Tags loaded." << std::endl;
+ delete[] tag_data;
+ return file_num_points;
+}
+
+template <typename T, typename TagT, typename LabelT>
+#ifdef EXEC_ENV_OLS
+size_t Index<T, TagT, LabelT>::load_data(AlignedFileReader &reader)
+{
+#else
+size_t Index<T, TagT, LabelT>::load_data(std::string filename)
+{
+#endif
+ size_t file_dim, file_num_points;
+#ifdef EXEC_ENV_OLS
+ diskann::get_bin_metadata(reader, file_num_points, file_dim);
+#else
+ if (!file_exists(filename))
+ {
+ std::stringstream stream;
+ stream << "ERROR: data file " << filename << " does not exist." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ diskann::get_bin_metadata(filename, file_num_points, file_dim);
+#endif
+
+ // since we are loading a new dataset, _empty_slots must be cleared
+ _empty_slots.clear();
+
+ if (file_dim != _dim)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << _dim << " dimension,"
+ << "but file has " << file_dim << " dimension." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (file_num_points > _max_points + _num_frozen_pts)
+ {
+ // update and tag lock acquired in load() before calling load_data
+ resize(file_num_points - _num_frozen_pts);
+ }
+
+#ifdef EXEC_ENV_OLS
+ // REFACTOR TODO: Must figure out how to support aligned reader in a clean
+ // manner.
+ copy_aligned_data_from_file<T>(reader, _data, file_num_points, file_dim, _data_store->get_aligned_dim());
+#else
+ _data_store->load(filename); // offset == 0.
+#endif
+ return file_num_points;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::load_delete_set(AlignedFileReader &reader)
+{
+#else
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::load_delete_set(const std::string &filename)
+{
+#endif
+ std::unique_ptr<uint32_t[]> delete_list;
+ size_t npts, ndim;
+
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<uint32_t>(reader, delete_list, npts, ndim);
+#else
+ diskann::load_bin<uint32_t>(filename, delete_list, npts, ndim);
+#endif
+ assert(ndim == 1);
+ for (uint32_t i = 0; i < npts; i++)
+ {
+ _delete_set->insert(delete_list[i]);
+ }
+ return npts;
+}
+
+// load the index from file and update the max_degree, cur (navigating
+// node loc), and _final_graph (adjacency list)
+template <typename T, typename TagT, typename LabelT>
+#ifdef EXEC_ENV_OLS
+void Index<T, TagT, LabelT>::load(AlignedFileReader &reader, uint32_t num_threads, uint32_t search_l)
+{
+#else
+void Index<T, TagT, LabelT>::load(const char *filename, uint32_t num_threads, uint32_t search_l)
+{
+#endif
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+
+ _has_built = true;
+
+ size_t tags_file_num_pts = 0, graph_num_pts = 0, data_file_num_pts = 0, label_num_pts = 0;
+
+ std::string mem_index_file(filename);
+ std::string labels_file = mem_index_file + "_labels.txt";
+ std::string labels_to_medoids = mem_index_file + "_labels_to_medoids.txt";
+ std::string labels_map_file = mem_index_file + "_labels_map.txt";
+
+ if (!_save_as_one_file)
+ {
+ // For DLVS Store, we will not support saving the index in multiple
+ // files.
+#ifndef EXEC_ENV_OLS
+ std::string data_file = std::string(filename) + ".data";
+ std::string tags_file = std::string(filename) + ".tags";
+ std::string delete_set_file = std::string(filename) + ".del";
+ std::string graph_file = std::string(filename);
+ data_file_num_pts = load_data(data_file);
+ if (file_exists(delete_set_file))
+ {
+ load_delete_set(delete_set_file);
+ }
+ if (_enable_tags)
+ {
+ tags_file_num_pts = load_tags(tags_file);
+ }
+ graph_num_pts = load_graph(graph_file, data_file_num_pts);
+#endif
+ }
+ else
+ {
+ diskann::cout << "Single index file saving/loading support not yet "
+ "enabled. Not loading the index."
+ << std::endl;
+ return;
+ }
+
+ if (data_file_num_pts != graph_num_pts || (data_file_num_pts != tags_file_num_pts && _enable_tags))
+ {
+ std::stringstream stream;
+ stream << "ERROR: When loading index, loaded " << data_file_num_pts << " points from datafile, "
+ << graph_num_pts << " from graph, and " << tags_file_num_pts
+ << " tags, with num_frozen_pts being set to " << _num_frozen_pts << " in constructor." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (file_exists(labels_file))
+ {
+ _label_map = load_label_map(labels_map_file);
+ parse_label_file(labels_file, label_num_pts);
+ assert(label_num_pts == data_file_num_pts - _num_frozen_pts);
+ if (file_exists(labels_to_medoids))
+ {
+ std::ifstream medoid_stream(labels_to_medoids);
+ std::string line, token;
+ uint32_t line_cnt = 0;
+
+ _label_to_start_id.clear();
+
+ while (std::getline(medoid_stream, line))
+ {
+ std::istringstream iss(line);
+ uint32_t cnt = 0;
+ uint32_t medoid = 0;
+ LabelT label;
+ while (std::getline(iss, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ LabelT token_as_num = (LabelT)std::stoul(token);
+ if (cnt == 0)
+ label = token_as_num;
+ else
+ medoid = token_as_num;
+ cnt++;
+ }
+ _label_to_start_id[label] = medoid;
+ line_cnt++;
+ }
+ }
+
+ std::string universal_label_file(filename);
+ universal_label_file += "_universal_label.txt";
+ if (file_exists(universal_label_file))
+ {
+ std::ifstream universal_label_reader(universal_label_file);
+ universal_label_reader >> _universal_label;
+ _use_universal_label = true;
+ universal_label_reader.close();
+ }
+ }
+
+ _nd = data_file_num_pts - _num_frozen_pts;
+ _empty_slots.clear();
+ _empty_slots.reserve(_max_points);
+ for (auto i = _nd; i < _max_points; i++)
+ {
+ _empty_slots.insert((uint32_t)i);
+ }
+
+ reposition_frozen_point_to_end();
+ diskann::cout << "Num frozen points:" << _num_frozen_pts << " _nd: " << _nd << " _start: " << _start
+ << " size(_location_to_tag): " << _location_to_tag.size()
+ << " size(_tag_to_location):" << _tag_to_location.size() << " Max points: " << _max_points
+ << std::endl;
+
+ // For incremental index, _query_scratch is initialized in the constructor.
+ // For the bulk index, the params required to initialize _query_scratch
+ // are known only at load time, hence this check and the call to
+ // initialize_q_s().
+ if (_query_scratch.size() == 0)
+ {
+ initialize_query_scratch(num_threads, search_l, search_l, (uint32_t)_graph_store->get_max_range_of_graph(),
+ _indexingMaxC, _dim);
+ }
+}
+
+#ifndef EXEC_ENV_OLS
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::get_graph_num_frozen_points(const std::string &graph_file)
+{
+ size_t expected_file_size;
+ uint32_t max_observed_degree, start;
+ size_t file_frozen_pts;
+
+ std::ifstream in;
+ in.exceptions(std::ios::badbit | std::ios::failbit);
+
+ in.open(graph_file, std::ios::binary);
+ in.read((char *)&expected_file_size, sizeof(size_t));
+ in.read((char *)&max_observed_degree, sizeof(uint32_t));
+ in.read((char *)&start, sizeof(uint32_t));
+ in.read((char *)&file_frozen_pts, sizeof(size_t));
+
+ return file_frozen_pts;
+}
+#endif
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::load_graph(AlignedFileReader &reader, size_t expected_num_points)
+{
+#else
+
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::load_graph(std::string filename, size_t expected_num_points)
+{
+#endif
+ auto res = _graph_store->load(filename, expected_num_points);
+ _start = std::get<1>(res);
+ _num_frozen_pts = std::get<2>(res);
+ return std::get<0>(res);
+}
+
+template <typename T, typename TagT, typename LabelT>
+int Index<T, TagT, LabelT>::_get_vector_by_tag(TagType &tag, DataType &vec)
+{
+ try
+ {
+ TagT tag_val = std::any_cast<TagT>(tag);
+ T *vec_val = std::any_cast<T *>(vec);
+ return this->get_vector_by_tag(tag_val, vec_val);
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad any cast while performing _get_vector_by_tags() " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error: " + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT> int Index<T, TagT, LabelT>::get_vector_by_tag(TagT &tag, T *vec)
+{
+ std::shared_lock<std::shared_timed_mutex> lock(_tag_lock);
+ if (_tag_to_location.find(tag) == _tag_to_location.end())
+ {
+ diskann::cout << "Tag " << get_tag_string(tag) << " does not exist" << std::endl;
+ return -1;
+ }
+
+ location_t location = _tag_to_location[tag];
+ _data_store->get_vector(location, vec);
+
+ return 0;
+}
+
+template <typename T, typename TagT, typename LabelT> uint32_t Index<T, TagT, LabelT>::calculate_entry_point()
+{
+ // REFACTOR TODO: This function does not support multi-threaded calculation of medoid.
+ // Must revisit if perf is a concern.
+ return _data_store->calculate_medoid();
+}
+
+template <typename T, typename TagT, typename LabelT> std::vector<uint32_t> Index<T, TagT, LabelT>::get_init_ids()
+{
+ std::vector<uint32_t> init_ids;
+ init_ids.reserve(1 + _num_frozen_pts);
+
+ init_ids.emplace_back(_start);
+
+ for (uint32_t frozen = (uint32_t)_max_points; frozen < _max_points + _num_frozen_pts; frozen++)
+ {
+ if (frozen != _start)
+ {
+ init_ids.emplace_back(frozen);
+ }
+ }
+
+ return init_ids;
+}
+
+// Find common filter between a node's labels and a given set of labels, while
+// taking into account universal label
+template <typename T, typename TagT, typename LabelT>
+bool Index<T, TagT, LabelT>::detect_common_filters(uint32_t point_id, bool search_invocation,
+ const std::vector<LabelT> &incoming_labels)
+{
+ auto &curr_node_labels = _location_to_labels[point_id];
+ std::vector<LabelT> common_filters;
+ std::set_intersection(incoming_labels.begin(), incoming_labels.end(), curr_node_labels.begin(),
+ curr_node_labels.end(), std::back_inserter(common_filters));
+ if (common_filters.size() > 0)
+ {
+ // This is to reduce the repetitive calls. If common_filters size is > 0 ,
+ // we dont need to check further for universal label
+ return true;
+ }
+ if (_use_universal_label)
+ {
+ if (!search_invocation)
+ {
+ if (std::find(incoming_labels.begin(), incoming_labels.end(), _universal_label) != incoming_labels.end() ||
+ std::find(curr_node_labels.begin(), curr_node_labels.end(), _universal_label) != curr_node_labels.end())
+ common_filters.push_back(_universal_label);
+ }
+ else
+ {
+ if (std::find(curr_node_labels.begin(), curr_node_labels.end(), _universal_label) != curr_node_labels.end())
+ common_filters.push_back(_universal_label);
+ }
+ }
+ return (common_filters.size() > 0);
+}
+
+template <typename T, typename TagT, typename LabelT>
+std::pair<uint32_t, uint32_t> Index<T, TagT, LabelT>::iterate_to_fixed_point(
+ InMemQueryScratch<T> *scratch, const uint32_t Lsize, const std::vector<uint32_t> &init_ids, bool use_filter,
+ const std::vector<LabelT> &filter_labels, bool search_invocation)
+{
+ std::vector<Neighbor> &expanded_nodes = scratch->pool();
+ NeighborPriorityQueue &best_L_nodes = scratch->best_l_nodes();
+ best_L_nodes.reserve(Lsize);
+ tsl::robin_set<uint32_t> &inserted_into_pool_rs = scratch->inserted_into_pool_rs();
+ boost::dynamic_bitset<> &inserted_into_pool_bs = scratch->inserted_into_pool_bs();
+ std::vector<uint32_t> &id_scratch = scratch->id_scratch();
+ std::vector<float> &dist_scratch = scratch->dist_scratch();
+ assert(id_scratch.size() == 0);
+
+ T *aligned_query = scratch->aligned_query();
+
+ float *pq_dists = nullptr;
+
+ _pq_data_store->preprocess_query(aligned_query, scratch);
+
+ if (expanded_nodes.size() > 0 || id_scratch.size() > 0)
+ {
+ throw ANNException("ERROR: Clear scratch space before passing.", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ // Decide whether to use bitset or robin set to mark visited nodes
+ auto total_num_points = _max_points + _num_frozen_pts;
+ bool fast_iterate = total_num_points <= MAX_POINTS_FOR_USING_BITSET;
+
+ if (fast_iterate)
+ {
+ if (inserted_into_pool_bs.size() < total_num_points)
+ {
+ // hopefully using 2X will reduce the number of allocations.
+ auto resize_size =
+ 2 * total_num_points > MAX_POINTS_FOR_USING_BITSET ? MAX_POINTS_FOR_USING_BITSET : 2 * total_num_points;
+ inserted_into_pool_bs.resize(resize_size);
+ }
+ }
+
+ // Lambda to determine if a node has been visited
+ auto is_not_visited = [this, fast_iterate, &inserted_into_pool_bs, &inserted_into_pool_rs](const uint32_t id) {
+ return fast_iterate ? inserted_into_pool_bs[id] == 0
+ : inserted_into_pool_rs.find(id) == inserted_into_pool_rs.end();
+ };
+
+ // Lambda to batch compute query<-> node distances in PQ space
+ auto compute_dists = [this, scratch, pq_dists](const std::vector<uint32_t> &ids, std::vector<float> &dists_out) {
+ _pq_data_store->get_distance(scratch->aligned_query(), ids, dists_out, scratch);
+ };
+
+ // Initialize the candidate pool with starting points
+ for (auto id : init_ids)
+ {
+ if (id >= _max_points + _num_frozen_pts)
+ {
+ diskann::cerr << "Out of range loc found as an edge : " << id << std::endl;
+ throw diskann::ANNException(std::string("Wrong loc") + std::to_string(id), -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ if (use_filter)
+ {
+ if (!detect_common_filters(id, search_invocation, filter_labels))
+ continue;
+ }
+
+ if (is_not_visited(id))
+ {
+ if (fast_iterate)
+ {
+ inserted_into_pool_bs[id] = 1;
+ }
+ else
+ {
+ inserted_into_pool_rs.insert(id);
+ }
+
+ float distance;
+ uint32_t ids[] = {id};
+ float distances[] = {std::numeric_limits<float>::max()};
+ _pq_data_store->get_distance(aligned_query, ids, 1, distances, scratch);
+ distance = distances[0];
+
+ Neighbor nn = Neighbor(id, distance);
+ best_L_nodes.insert(nn);
+ }
+ }
+
+ uint32_t hops = 0;
+ uint32_t cmps = 0;
+
+ while (best_L_nodes.has_unexpanded_node())
+ {
+ auto nbr = best_L_nodes.closest_unexpanded();
+ auto n = nbr.id;
+
+ // Add node to expanded nodes to create pool for prune later
+ if (!search_invocation)
+ {
+ if (!use_filter)
+ {
+ expanded_nodes.emplace_back(nbr);
+ }
+ else
+ { // in filter based indexing, the same point might invoke
+ // multiple iterate_to_fixed_points, so need to be careful
+ // not to add the same item to pool multiple times.
+ if (std::find(expanded_nodes.begin(), expanded_nodes.end(), nbr) == expanded_nodes.end())
+ {
+ expanded_nodes.emplace_back(nbr);
+ }
+ }
+ }
+
+ // Find which of the nodes in des have not been visited before
+ id_scratch.clear();
+ dist_scratch.clear();
+ if (_dynamic_index)
+ {
+ LockGuard guard(_locks[n]);
+ for (auto id : _graph_store->get_neighbours(n))
+ {
+ assert(id < _max_points + _num_frozen_pts);
+
+ if (use_filter)
+ {
+ // NOTE: NEED TO CHECK IF THIS CORRECT WITH NEW LOCKS.
+ if (!detect_common_filters(id, search_invocation, filter_labels))
+ continue;
+ }
+
+ if (is_not_visited(id))
+ {
+ id_scratch.push_back(id);
+ }
+ }
+ }
+ else
+ {
+ _locks[n].lock();
+ auto nbrs = _graph_store->get_neighbours(n);
+ _locks[n].unlock();
+ for (auto id : nbrs)
+ {
+ assert(id < _max_points + _num_frozen_pts);
+
+ if (use_filter)
+ {
+ // NOTE: NEED TO CHECK IF THIS CORRECT WITH NEW LOCKS.
+ if (!detect_common_filters(id, search_invocation, filter_labels))
+ continue;
+ }
+
+ if (is_not_visited(id))
+ {
+ id_scratch.push_back(id);
+ }
+ }
+ }
+
+ // Mark nodes visited
+ for (auto id : id_scratch)
+ {
+ if (fast_iterate)
+ {
+ inserted_into_pool_bs[id] = 1;
+ }
+ else
+ {
+ inserted_into_pool_rs.insert(id);
+ }
+ }
+
+ assert(dist_scratch.capacity() >= id_scratch.size());
+ compute_dists(id_scratch, dist_scratch);
+ cmps += (uint32_t)id_scratch.size();
+
+ // Insert <id, dist> pairs into the pool of candidates
+ for (size_t m = 0; m < id_scratch.size(); ++m)
+ {
+ best_L_nodes.insert(Neighbor(id_scratch[m], dist_scratch[m]));
+ }
+ }
+ return std::make_pair(hops, cmps);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::search_for_point_and_prune(int location, uint32_t Lindex,
+ std::vector<uint32_t> &pruned_list,
+ InMemQueryScratch<T> *scratch, bool use_filter,
+ uint32_t filteredLindex)
+{
+ const std::vector<uint32_t> init_ids = get_init_ids();
+ const std::vector<LabelT> unused_filter_label;
+
+ if (!use_filter)
+ {
+ _data_store->get_vector(location, scratch->aligned_query());
+ iterate_to_fixed_point(scratch, Lindex, init_ids, false, unused_filter_label, false);
+ }
+ else
+ {
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock, std::defer_lock);
+ if (_dynamic_index)
+ tl.lock();
+ std::vector<uint32_t> filter_specific_start_nodes;
+ for (auto &x : _location_to_labels[location])
+ filter_specific_start_nodes.emplace_back(_label_to_start_id[x]);
+
+ if (_dynamic_index)
+ tl.unlock();
+
+ _data_store->get_vector(location, scratch->aligned_query());
+ iterate_to_fixed_point(scratch, filteredLindex, filter_specific_start_nodes, true,
+ _location_to_labels[location], false);
+
+ // combine candidate pools obtained with filter and unfiltered criteria.
+ std::set<Neighbor> best_candidate_pool;
+ for (auto filtered_neighbor : scratch->pool())
+ {
+ best_candidate_pool.insert(filtered_neighbor);
+ }
+
+ // clear scratch for finding unfiltered candidates
+ scratch->clear();
+
+ _data_store->get_vector(location, scratch->aligned_query());
+ iterate_to_fixed_point(scratch, Lindex, init_ids, false, unused_filter_label, false);
+
+ for (auto unfiltered_neighbour : scratch->pool())
+ {
+ // insert if this neighbour is not already in best_candidate_pool
+ if (best_candidate_pool.find(unfiltered_neighbour) == best_candidate_pool.end())
+ {
+ best_candidate_pool.insert(unfiltered_neighbour);
+ }
+ }
+
+ scratch->pool().clear();
+ std::copy(best_candidate_pool.begin(), best_candidate_pool.end(), std::back_inserter(scratch->pool()));
+ }
+
+ auto &pool = scratch->pool();
+
+ for (uint32_t i = 0; i < pool.size(); i++)
+ {
+ if (pool[i].id == (uint32_t)location)
+ {
+ pool.erase(pool.begin() + i);
+ i--;
+ }
+ }
+
+ if (pruned_list.size() > 0)
+ {
+ throw diskann::ANNException("ERROR: non-empty pruned_list passed", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ prune_neighbors(location, pool, pruned_list, scratch);
+
+ assert(!pruned_list.empty());
+ assert(_graph_store->get_total_points() == _max_points + _num_frozen_pts);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::occlude_list(const uint32_t location, std::vector<Neighbor> &pool, const float alpha,
+ const uint32_t degree, const uint32_t maxc, std::vector<uint32_t> &result,
+ InMemQueryScratch<T> *scratch,
+ const tsl::robin_set<uint32_t> *const delete_set_ptr)
+{
+ if (pool.size() == 0)
+ return;
+
+ // Truncate pool at maxc and initialize scratch spaces
+ assert(std::is_sorted(pool.begin(), pool.end()));
+ assert(result.size() == 0);
+ if (pool.size() > maxc)
+ pool.resize(maxc);
+ std::vector<float> &occlude_factor = scratch->occlude_factor();
+ // occlude_list can be called with the same scratch more than once by
+ // search_for_point_and_add_link through inter_insert.
+ occlude_factor.clear();
+ // Initialize occlude_factor to pool.size() many 0.0f values for correctness
+ occlude_factor.insert(occlude_factor.end(), pool.size(), 0.0f);
+
+ float cur_alpha = 1;
+ while (cur_alpha <= alpha && result.size() < degree)
+ {
+ // used for MIPS, where we store a value of eps in cur_alpha to
+ // denote pruned out entries which we can skip in later rounds.
+ float eps = cur_alpha + 0.01f;
+
+ for (auto iter = pool.begin(); result.size() < degree && iter != pool.end(); ++iter)
+ {
+ if (occlude_factor[iter - pool.begin()] > cur_alpha)
+ {
+ continue;
+ }
+ // Set the entry to float::max so that is not considered again
+ occlude_factor[iter - pool.begin()] = std::numeric_limits<float>::max();
+ // Add the entry to the result if its not been deleted, and doesn't
+ // add a self loop
+ if (delete_set_ptr == nullptr || delete_set_ptr->find(iter->id) == delete_set_ptr->end())
+ {
+ if (iter->id != location)
+ {
+ result.push_back(iter->id);
+ }
+ }
+
+ // Update occlude factor for points from iter+1 to pool.end()
+ for (auto iter2 = iter + 1; iter2 != pool.end(); iter2++)
+ {
+ auto t = iter2 - pool.begin();
+ if (occlude_factor[t] > alpha)
+ continue;
+
+ bool prune_allowed = true;
+ if (_filtered_index)
+ {
+ uint32_t a = iter->id;
+ uint32_t b = iter2->id;
+ if (_location_to_labels.size() < b || _location_to_labels.size() < a)
+ continue;
+ for (auto &x : _location_to_labels[b])
+ {
+ if (std::find(_location_to_labels[a].begin(), _location_to_labels[a].end(), x) ==
+ _location_to_labels[a].end())
+ {
+ prune_allowed = false;
+ }
+ if (!prune_allowed)
+ break;
+ }
+ }
+ if (!prune_allowed)
+ continue;
+
+ float djk = _data_store->get_distance(iter2->id, iter->id);
+ if (_dist_metric == diskann::Metric::L2 || _dist_metric == diskann::Metric::COSINE)
+ {
+ occlude_factor[t] = (djk == 0) ? std::numeric_limits<float>::max()
+ : std::max(occlude_factor[t], iter2->distance / djk);
+ }
+ else if (_dist_metric == diskann::Metric::INNER_PRODUCT)
+ {
+ // Improvization for flipping max and min dist for MIPS
+ float x = -iter2->distance;
+ float y = -djk;
+ if (y > cur_alpha * x)
+ {
+ occlude_factor[t] = std::max(occlude_factor[t], eps);
+ }
+ }
+ }
+ }
+ cur_alpha *= 1.2f;
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::prune_neighbors(const uint32_t location, std::vector<Neighbor> &pool,
+ std::vector<uint32_t> &pruned_list, InMemQueryScratch<T> *scratch)
+{
+ prune_neighbors(location, pool, _indexingRange, _indexingMaxC, _indexingAlpha, pruned_list, scratch);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::prune_neighbors(const uint32_t location, std::vector<Neighbor> &pool, const uint32_t range,
+ const uint32_t max_candidate_size, const float alpha,
+ std::vector<uint32_t> &pruned_list, InMemQueryScratch<T> *scratch)
+{
+ if (pool.size() == 0)
+ {
+ // if the pool is empty, behave like a noop
+ pruned_list.clear();
+ return;
+ }
+
+ // If using _pq_build, over-write the PQ distances with actual distances
+ // REFACTOR PQ: TODO: How to get rid of this!?
+ if (_pq_dist)
+ {
+ for (auto &ngh : pool)
+ ngh.distance = _data_store->get_distance(ngh.id, location);
+ }
+
+ // sort the pool based on distance to query and prune it with occlude_list
+ std::sort(pool.begin(), pool.end());
+ pruned_list.clear();
+ pruned_list.reserve(range);
+
+ occlude_list(location, pool, alpha, range, max_candidate_size, pruned_list, scratch);
+ assert(pruned_list.size() <= range);
+
+ if (_saturate_graph && alpha > 1)
+ {
+ for (const auto &node : pool)
+ {
+ if (pruned_list.size() >= range)
+ break;
+ if ((std::find(pruned_list.begin(), pruned_list.end(), node.id) == pruned_list.end()) &&
+ node.id != location)
+ pruned_list.push_back(node.id);
+ }
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::inter_insert(uint32_t n, std::vector<uint32_t> &pruned_list, const uint32_t range,
+ InMemQueryScratch<T> *scratch)
+{
+ const auto &src_pool = pruned_list;
+
+ assert(!src_pool.empty());
+
+ for (auto des : src_pool)
+ {
+ // des.loc is the loc of the neighbors of n
+ assert(des < _max_points + _num_frozen_pts);
+ // des_pool contains the neighbors of the neighbors of n
+ std::vector<uint32_t> copy_of_neighbors;
+ bool prune_needed = false;
+ {
+ LockGuard guard(_locks[des]);
+ auto &des_pool = _graph_store->get_neighbours(des);
+ if (std::find(des_pool.begin(), des_pool.end(), n) == des_pool.end())
+ {
+ if (des_pool.size() < (uint64_t)(defaults::GRAPH_SLACK_FACTOR * range))
+ {
+ // des_pool.emplace_back(n);
+ _graph_store->add_neighbour(des, n);
+ prune_needed = false;
+ }
+ else
+ {
+ copy_of_neighbors.reserve(des_pool.size() + 1);
+ copy_of_neighbors = des_pool;
+ copy_of_neighbors.push_back(n);
+ prune_needed = true;
+ }
+ }
+ } // des lock is released by this point
+
+ if (prune_needed)
+ {
+ tsl::robin_set<uint32_t> dummy_visited(0);
+ std::vector<Neighbor> dummy_pool(0);
+
+ size_t reserveSize = (size_t)(std::ceil(1.05 * defaults::GRAPH_SLACK_FACTOR * range));
+ dummy_visited.reserve(reserveSize);
+ dummy_pool.reserve(reserveSize);
+
+ for (auto cur_nbr : copy_of_neighbors)
+ {
+ if (dummy_visited.find(cur_nbr) == dummy_visited.end() && cur_nbr != des)
+ {
+ float dist = _data_store->get_distance(des, cur_nbr);
+ dummy_pool.emplace_back(Neighbor(cur_nbr, dist));
+ dummy_visited.insert(cur_nbr);
+ }
+ }
+ std::vector<uint32_t> new_out_neighbors;
+ prune_neighbors(des, dummy_pool, new_out_neighbors, scratch);
+ {
+ LockGuard guard(_locks[des]);
+
+ _graph_store->set_neighbours(des, new_out_neighbors);
+ }
+ }
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::inter_insert(uint32_t n, std::vector<uint32_t> &pruned_list, InMemQueryScratch<T> *scratch)
+{
+ inter_insert(n, pruned_list, _indexingRange, scratch);
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::link()
+{
+ uint32_t num_threads = _indexingThreads;
+ if (num_threads != 0)
+ omp_set_num_threads(num_threads);
+
+ /* visit_order is a vector that is initialized to the entire graph */
+ std::vector<uint32_t> visit_order;
+ std::vector<diskann::Neighbor> pool, tmp;
+ tsl::robin_set<uint32_t> visited;
+ visit_order.reserve(_nd + _num_frozen_pts);
+ for (uint32_t i = 0; i < (uint32_t)_nd; i++)
+ {
+ visit_order.emplace_back(i);
+ }
+
+ // If there are any frozen points, add them all.
+ for (uint32_t frozen = (uint32_t)_max_points; frozen < _max_points + _num_frozen_pts; frozen++)
+ {
+ visit_order.emplace_back(frozen);
+ }
+
+ // if there are frozen points, the first such one is set to be the _start
+ if (_num_frozen_pts > 0)
+ _start = (uint32_t)_max_points;
+ else
+ _start = calculate_entry_point();
+
+ diskann::Timer link_timer;
+
+#pragma omp parallel for schedule(dynamic, 2048)
+ for (int64_t node_ctr = 0; node_ctr < (int64_t)(visit_order.size()); node_ctr++)
+ {
+ auto node = visit_order[node_ctr];
+
+ // Find and add appropriate graph edges
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+ std::vector<uint32_t> pruned_list;
+ if (_filtered_index)
+ {
+ search_for_point_and_prune(node, _indexingQueueSize, pruned_list, scratch, true, _filterIndexingQueueSize);
+ }
+ else
+ {
+ search_for_point_and_prune(node, _indexingQueueSize, pruned_list, scratch);
+ }
+ assert(pruned_list.size() > 0);
+
+ {
+ LockGuard guard(_locks[node]);
+
+ _graph_store->set_neighbours(node, pruned_list);
+ assert(_graph_store->get_neighbours((location_t)node).size() <= _indexingRange);
+ }
+
+ inter_insert(node, pruned_list, scratch);
+
+ if (node_ctr % 100000 == 0)
+ {
+ diskann::cout << "\r" << (100.0 * node_ctr) / (visit_order.size()) << "% of index build completed."
+ << std::flush;
+ }
+ }
+
+ if (_nd > 0)
+ {
+ diskann::cout << "Starting final cleanup.." << std::flush;
+ }
+#pragma omp parallel for schedule(dynamic, 2048)
+ for (int64_t node_ctr = 0; node_ctr < (int64_t)(visit_order.size()); node_ctr++)
+ {
+ auto node = visit_order[node_ctr];
+ if (_graph_store->get_neighbours((location_t)node).size() > _indexingRange)
+ {
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+
+ tsl::robin_set<uint32_t> dummy_visited(0);
+ std::vector<Neighbor> dummy_pool(0);
+ std::vector<uint32_t> new_out_neighbors;
+
+ for (auto cur_nbr : _graph_store->get_neighbours((location_t)node))
+ {
+ if (dummy_visited.find(cur_nbr) == dummy_visited.end() && cur_nbr != node)
+ {
+ float dist = _data_store->get_distance(node, cur_nbr);
+ dummy_pool.emplace_back(Neighbor(cur_nbr, dist));
+ dummy_visited.insert(cur_nbr);
+ }
+ }
+ prune_neighbors(node, dummy_pool, new_out_neighbors, scratch);
+
+ _graph_store->clear_neighbours((location_t)node);
+ _graph_store->set_neighbours((location_t)node, new_out_neighbors);
+ }
+ }
+ if (_nd > 0)
+ {
+ diskann::cout << "done. Link time: " << ((double)link_timer.elapsed() / (double)1000000) << "s" << std::endl;
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::prune_all_neighbors(const uint32_t max_degree, const uint32_t max_occlusion_size,
+ const float alpha)
+{
+ const uint32_t range = max_degree;
+ const uint32_t maxc = max_occlusion_size;
+
+ _filtered_index = true;
+
+ diskann::Timer timer;
+#pragma omp parallel for
+ for (int64_t node = 0; node < (int64_t)(_max_points + _num_frozen_pts); node++)
+ {
+ if ((size_t)node < _nd || (size_t)node >= _max_points)
+ {
+ if (_graph_store->get_neighbours((location_t)node).size() > range)
+ {
+ tsl::robin_set<uint32_t> dummy_visited(0);
+ std::vector<Neighbor> dummy_pool(0);
+ std::vector<uint32_t> new_out_neighbors;
+
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+
+ for (auto cur_nbr : _graph_store->get_neighbours((location_t)node))
+ {
+ if (dummy_visited.find(cur_nbr) == dummy_visited.end() && cur_nbr != node)
+ {
+ float dist = _data_store->get_distance((location_t)node, (location_t)cur_nbr);
+ dummy_pool.emplace_back(Neighbor(cur_nbr, dist));
+ dummy_visited.insert(cur_nbr);
+ }
+ }
+
+ prune_neighbors((uint32_t)node, dummy_pool, range, maxc, alpha, new_out_neighbors, scratch);
+ _graph_store->clear_neighbours((location_t)node);
+ _graph_store->set_neighbours((location_t)node, new_out_neighbors);
+ }
+ }
+ }
+
+ diskann::cout << "Prune time : " << timer.elapsed() / 1000 << "ms" << std::endl;
+ size_t max = 0, min = 1 << 30, total = 0, cnt = 0;
+ for (size_t i = 0; i < _max_points + _num_frozen_pts; i++)
+ {
+ if (i < _nd || i >= _max_points)
+ {
+ const std::vector<uint32_t> &pool = _graph_store->get_neighbours((location_t)i);
+ max = (std::max)(max, pool.size());
+ min = (std::min)(min, pool.size());
+ total += pool.size();
+ if (pool.size() < 2)
+ cnt++;
+ }
+ }
+ if (min > max)
+ min = max;
+ if (_nd > 0)
+ {
+ diskann::cout << "Index built with degree: max:" << max
+ << " avg:" << (float)total / (float)(_nd + _num_frozen_pts) << " min:" << min
+ << " count(deg<2):" << cnt << std::endl;
+ }
+}
+
+// REFACTOR
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::set_start_points(const T *data, size_t data_count)
+{
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ if (_nd > 0)
+ throw ANNException("Can not set starting point for a non-empty index", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ if (data_count != _num_frozen_pts * _dim)
+ throw ANNException("Invalid number of points", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ // memcpy(_data + _aligned_dim * _max_points, data, _aligned_dim *
+ // sizeof(T) * _num_frozen_pts);
+ for (location_t i = 0; i < _num_frozen_pts; i++)
+ {
+ _data_store->set_vector((location_t)(i + _max_points), data + i * _dim);
+ }
+ _has_built = true;
+ diskann::cout << "Index start points set: #" << _num_frozen_pts << std::endl;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::_set_start_points_at_random(DataType radius, uint32_t random_seed)
+{
+ try
+ {
+ T radius_to_use = std::any_cast<T>(radius);
+ this->set_start_points_at_random(radius_to_use, random_seed);
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException(
+ "Error: bad any cast while performing _set_start_points_at_random() " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error: " + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::set_start_points_at_random(T radius, uint32_t random_seed)
+{
+ std::mt19937 gen{random_seed};
+ std::normal_distribution<> d{0.0, 1.0};
+
+ std::vector<T> points_data;
+ points_data.reserve(_dim * _num_frozen_pts);
+ std::vector<double> real_vec(_dim);
+
+ for (size_t frozen_point = 0; frozen_point < _num_frozen_pts; frozen_point++)
+ {
+ double norm_sq = 0.0;
+ for (size_t i = 0; i < _dim; ++i)
+ {
+ auto r = d(gen);
+ real_vec[i] = r;
+ norm_sq += r * r;
+ }
+
+ const double norm = std::sqrt(norm_sq);
+ for (auto iter : real_vec)
+ points_data.push_back(static_cast<T>(iter * radius / norm));
+ }
+
+ set_start_points(points_data.data(), points_data.size());
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::build_with_data_populated(const std::vector<TagT> &tags)
+{
+ diskann::cout << "Starting index build with " << _nd << " points... " << std::endl;
+
+ if (_nd < 1)
+ throw ANNException("Error: Trying to build an index with 0 points", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ if (_enable_tags && tags.size() != _nd)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << _nd << " points from file,"
+ << "but tags vector is of size " << tags.size() << "." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ if (_enable_tags)
+ {
+ for (size_t i = 0; i < tags.size(); ++i)
+ {
+ _tag_to_location[tags[i]] = (uint32_t)i;
+ _location_to_tag.set(static_cast<uint32_t>(i), tags[i]);
+ }
+ }
+
+ uint32_t index_R = _indexingRange;
+ uint32_t num_threads_index = _indexingThreads;
+ uint32_t index_L = _indexingQueueSize;
+ uint32_t maxc = _indexingMaxC;
+
+ if (_query_scratch.size() == 0)
+ {
+ initialize_query_scratch(5 + num_threads_index, index_L, index_L, index_R, maxc,
+ _data_store->get_aligned_dim());
+ }
+
+ generate_frozen_point();
+ link();
+
+ size_t max = 0, min = SIZE_MAX, total = 0, cnt = 0;
+ for (size_t i = 0; i < _nd; i++)
+ {
+ auto &pool = _graph_store->get_neighbours((location_t)i);
+ max = std::max(max, pool.size());
+ min = std::min(min, pool.size());
+ total += pool.size();
+ if (pool.size() < 2)
+ cnt++;
+ }
+ diskann::cout << "Index built with degree: max:" << max << " avg:" << (float)total / (float)(_nd + _num_frozen_pts)
+ << " min:" << min << " count(deg<2):" << cnt << std::endl;
+
+ _has_built = true;
+}
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::_build(const DataType &data, const size_t num_points_to_load, TagVector &tags)
+{
+ try
+ {
+ this->build(std::any_cast<const T *>(data), num_points_to_load, tags.get<const std::vector<TagT>>());
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad any cast in while building index. " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error" + std::string(e.what()), -1);
+ }
+}
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::build(const T *data, const size_t num_points_to_load, const std::vector<TagT> &tags)
+{
+ if (num_points_to_load == 0)
+ {
+ throw ANNException("Do not call build with 0 points", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ if (_pq_dist)
+ {
+ throw ANNException("ERROR: DO not use this build interface with PQ distance", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+
+ {
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ _nd = num_points_to_load;
+
+ _data_store->populate_data(data, (location_t)num_points_to_load);
+ }
+
+ build_with_data_populated(tags);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::build(const char *filename, const size_t num_points_to_load, const std::vector<TagT> &tags)
+{
+ // idealy this should call build_filtered_index based on params passed
+
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+
+ // error checks
+ if (num_points_to_load == 0)
+ throw ANNException("Do not call build with 0 points", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ if (!file_exists(filename))
+ {
+ std::stringstream stream;
+ stream << "ERROR: Data file " << filename << " does not exist." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ size_t file_num_points, file_dim;
+ if (filename == nullptr)
+ {
+ throw diskann::ANNException("Can not build with an empty file", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ diskann::get_bin_metadata(filename, file_num_points, file_dim);
+ if (file_num_points > _max_points)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << num_points_to_load << " points and file has " << file_num_points
+ << " points, but "
+ << "index can support only " << _max_points << " points as specified in constructor." << std::endl;
+
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (num_points_to_load > file_num_points)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << num_points_to_load << " points and file has only "
+ << file_num_points << " points." << std::endl;
+
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (file_dim != _dim)
+ {
+ std::stringstream stream;
+ stream << "ERROR: Driver requests loading " << _dim << " dimension,"
+ << "but file has " << file_dim << " dimension." << std::endl;
+ diskann::cerr << stream.str() << std::endl;
+
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ // REFACTOR PQ TODO: We can remove this if and add a check in the InMemDataStore
+ // to not populate_data if it has been called once.
+ if (_pq_dist)
+ {
+#ifdef EXEC_ENV_OLS
+ std::stringstream ss;
+ ss << "PQ Build is not supported in DLVS environment (i.e. if EXEC_ENV_OLS is defined)" << std::endl;
+ diskann::cerr << ss.str() << std::endl;
+ throw ANNException(ss.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+#else
+ // REFACTOR TODO: Both in the previous code and in the current PQDataStore,
+ // we are writing the PQ files in the same path as the input file. Now we
+ // may not have write permissions to that folder, but we will always have
+ // write permissions to the output folder. So we should write the PQ files
+ // there. The problem is that the Index class gets the output folder prefix
+ // only at the time of save(), by which time we are too late. So leaving it
+ // as-is for now.
+ _pq_data_store->populate_data(filename, 0U);
+#endif
+ }
+
+ _data_store->populate_data(filename, 0U);
+ diskann::cout << "Using only first " << num_points_to_load << " from file.. " << std::endl;
+
+ {
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ _nd = num_points_to_load;
+ }
+ build_with_data_populated(tags);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::build(const char *filename, const size_t num_points_to_load, const char *tag_filename)
+{
+ std::vector<TagT> tags;
+
+ if (_enable_tags)
+ {
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ if (tag_filename == nullptr)
+ {
+ throw ANNException("Tag filename is null, while _enable_tags is set", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ else
+ {
+ if (file_exists(tag_filename))
+ {
+ diskann::cout << "Loading tags from " << tag_filename << " for vamana index build" << std::endl;
+ TagT *tag_data = nullptr;
+ size_t npts, ndim;
+ diskann::load_bin(tag_filename, tag_data, npts, ndim);
+ if (npts < num_points_to_load)
+ {
+ std::stringstream sstream;
+ sstream << "Loaded " << npts << " tags, insufficient to populate tags for " << num_points_to_load
+ << " points to load";
+ throw diskann::ANNException(sstream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ for (size_t i = 0; i < num_points_to_load; i++)
+ {
+ tags.push_back(tag_data[i]);
+ }
+ delete[] tag_data;
+ }
+ else
+ {
+ throw diskann::ANNException(std::string("Tag file") + tag_filename + " does not exist", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+ }
+ }
+ build(filename, num_points_to_load, tags);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::build(const std::string &data_file, const size_t num_points_to_load,
+ IndexFilterParams &filter_params)
+{
+ size_t points_to_load = num_points_to_load == 0 ? _max_points : num_points_to_load;
+
+ auto s = std::chrono::high_resolution_clock::now();
+ if (filter_params.label_file == "")
+ {
+ this->build(data_file.c_str(), points_to_load);
+ }
+ else
+ {
+ // TODO: this should ideally happen in save()
+ std::string labels_file_to_use = filter_params.save_path_prefix + "_label_formatted.txt";
+ std::string mem_labels_int_map_file = filter_params.save_path_prefix + "_labels_map.txt";
+ convert_labels_string_to_int(filter_params.label_file, labels_file_to_use, mem_labels_int_map_file,
+ filter_params.universal_label);
+ if (filter_params.universal_label != "")
+ {
+ LabelT unv_label_as_num = 0;
+ this->set_universal_label(unv_label_as_num);
+ }
+ this->build_filtered_index(data_file.c_str(), labels_file_to_use, points_to_load);
+ }
+ std::chrono::duration<double> diff = std::chrono::high_resolution_clock::now() - s;
+ std::cout << "Indexing time: " << diff.count() << "\n";
+}
+
+template <typename T, typename TagT, typename LabelT>
+std::unordered_map<std::string, LabelT> Index<T, TagT, LabelT>::load_label_map(const std::string &labels_map_file)
+{
+ std::unordered_map<std::string, LabelT> string_to_int_mp;
+ std::ifstream map_reader(labels_map_file);
+ std::string line, token;
+ LabelT token_as_num;
+ std::string label_str;
+ while (std::getline(map_reader, line))
+ {
+ std::istringstream iss(line);
+ getline(iss, token, '\t');
+ label_str = token;
+ getline(iss, token, '\t');
+ token_as_num = (LabelT)std::stoul(token);
+ string_to_int_mp[label_str] = token_as_num;
+ }
+ return string_to_int_mp;
+}
+
+template <typename T, typename TagT, typename LabelT>
+LabelT Index<T, TagT, LabelT>::get_converted_label(const std::string &raw_label)
+{
+ if (_label_map.find(raw_label) != _label_map.end())
+ {
+ return _label_map[raw_label];
+ }
+ if (_use_universal_label)
+ {
+ return _universal_label;
+ }
+ std::stringstream stream;
+ stream << "Unable to find label in the Label Map";
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::parse_label_file(const std::string &label_file, size_t &num_points)
+{
+ // Format of Label txt file: filters with comma separators
+
+ std::ifstream infile(label_file);
+ if (infile.fail())
+ {
+ throw diskann::ANNException(std::string("Failed to open file ") + label_file, -1);
+ }
+
+ std::string line, token;
+ uint32_t line_cnt = 0;
+
+ while (std::getline(infile, line))
+ {
+ line_cnt++;
+ }
+ _location_to_labels.resize(line_cnt, std::vector<LabelT>());
+
+ infile.clear();
+ infile.seekg(0, std::ios::beg);
+ line_cnt = 0;
+
+ while (std::getline(infile, line))
+ {
+ std::istringstream iss(line);
+ std::vector<LabelT> lbls(0);
+ getline(iss, token, '\t');
+ std::istringstream new_iss(token);
+ while (getline(new_iss, token, ','))
+ {
+ token.erase(std::remove(token.begin(), token.end(), '\n'), token.end());
+ token.erase(std::remove(token.begin(), token.end(), '\r'), token.end());
+ LabelT token_as_num = (LabelT)std::stoul(token);
+ lbls.push_back(token_as_num);
+ _labels.insert(token_as_num);
+ }
+
+ std::sort(lbls.begin(), lbls.end());
+ _location_to_labels[line_cnt] = lbls;
+ line_cnt++;
+ }
+ num_points = (size_t)line_cnt;
+ diskann::cout << "Identified " << _labels.size() << " distinct label(s)" << std::endl;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::_set_universal_label(const LabelType universal_label)
+{
+ this->set_universal_label(std::any_cast<const LabelT>(universal_label));
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::set_universal_label(const LabelT &label)
+{
+ _use_universal_label = true;
+ _universal_label = label;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::build_filtered_index(const char *filename, const std::string &label_file,
+ const size_t num_points_to_load, const std::vector<TagT> &tags)
+{
+ _filtered_index = true;
+ _label_to_start_id.clear();
+ size_t num_points_labels = 0;
+
+ parse_label_file(label_file,
+ num_points_labels); // determines medoid for each label and identifies
+ // the points to label mapping
+
+ std::unordered_map<LabelT, std::vector<uint32_t>> label_to_points;
+
+ for (uint32_t point_id = 0; point_id < num_points_to_load; point_id++)
+ {
+ for (auto label : _location_to_labels[point_id])
+ {
+ if (label != _universal_label)
+ {
+ label_to_points[label].emplace_back(point_id);
+ }
+ else
+ {
+ for (typename tsl::robin_set<LabelT>::size_type lbl = 0; lbl < _labels.size(); lbl++)
+ {
+ auto itr = _labels.begin();
+ std::advance(itr, lbl);
+ auto &x = *itr;
+ label_to_points[x].emplace_back(point_id);
+ }
+ }
+ }
+ }
+
+ uint32_t num_cands = 25;
+ for (auto itr = _labels.begin(); itr != _labels.end(); itr++)
+ {
+ uint32_t best_medoid_count = std::numeric_limits<uint32_t>::max();
+ auto &curr_label = *itr;
+ uint32_t best_medoid;
+ auto labeled_points = label_to_points[curr_label];
+ for (uint32_t cnd = 0; cnd < num_cands; cnd++)
+ {
+ uint32_t cur_cnd = labeled_points[rand() % labeled_points.size()];
+ uint32_t cur_cnt = std::numeric_limits<uint32_t>::max();
+ if (_medoid_counts.find(cur_cnd) == _medoid_counts.end())
+ {
+ _medoid_counts[cur_cnd] = 0;
+ cur_cnt = 0;
+ }
+ else
+ {
+ cur_cnt = _medoid_counts[cur_cnd];
+ }
+ if (cur_cnt < best_medoid_count)
+ {
+ best_medoid_count = cur_cnt;
+ best_medoid = cur_cnd;
+ }
+ }
+ _label_to_start_id[curr_label] = best_medoid;
+ _medoid_counts[best_medoid]++;
+ }
+
+ this->build(filename, num_points_to_load, tags);
+}
+
+template <typename T, typename TagT, typename LabelT>
+std::pair<uint32_t, uint32_t> Index<T, TagT, LabelT>::_search(const DataType &query, const size_t K, const uint32_t L,
+ std::any &indices, float *distances)
+{
+ try
+ {
+ auto typed_query = std::any_cast<const T *>(query);
+ if (typeid(uint32_t *) == indices.type())
+ {
+ auto u32_ptr = std::any_cast<uint32_t *>(indices);
+ return this->search(typed_query, K, L, u32_ptr, distances);
+ }
+ else if (typeid(uint64_t *) == indices.type())
+ {
+ auto u64_ptr = std::any_cast<uint64_t *>(indices);
+ return this->search(typed_query, K, L, u64_ptr, distances);
+ }
+ else
+ {
+ throw ANNException("Error: indices type can only be uint64_t or uint32_t.", -1);
+ }
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad any cast while searching. " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error: " + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+template <typename IdType>
+std::pair<uint32_t, uint32_t> Index<T, TagT, LabelT>::search(const T *query, const size_t K, const uint32_t L,
+ IdType *indices, float *distances)
+{
+ if (K > (uint64_t)L)
+ {
+ throw ANNException("Set L to a value of at least K", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+
+ if (L > scratch->get_L())
+ {
+ diskann::cout << "Attempting to expand query scratch_space. Was created "
+ << "with Lsize: " << scratch->get_L() << " but search L is: " << L << std::endl;
+ scratch->resize_for_new_L(L);
+ diskann::cout << "Resize completed. New scratch->L is " << scratch->get_L() << std::endl;
+ }
+
+ const std::vector<LabelT> unused_filter_label;
+ const std::vector<uint32_t> init_ids = get_init_ids();
+
+ std::shared_lock<std::shared_timed_mutex> lock(_update_lock);
+
+ _data_store->preprocess_query(query, scratch);
+
+ auto retval = iterate_to_fixed_point(scratch, L, init_ids, false, unused_filter_label, true);
+
+ NeighborPriorityQueue &best_L_nodes = scratch->best_l_nodes();
+
+ size_t pos = 0;
+ for (size_t i = 0; i < best_L_nodes.size(); ++i)
+ {
+ if (best_L_nodes[i].id < _max_points)
+ {
+ // safe because Index uses uint32_t ids internally
+ // and IDType will be uint32_t or uint64_t
+ indices[pos] = (IdType)best_L_nodes[i].id;
+ if (distances != nullptr)
+ {
+#ifdef EXEC_ENV_OLS
+ // DLVS expects negative distances
+ distances[pos] = best_L_nodes[i].distance;
+#else
+ distances[pos] = _dist_metric == diskann::Metric::INNER_PRODUCT ? -1 * best_L_nodes[i].distance
+ : best_L_nodes[i].distance;
+#endif
+ }
+ pos++;
+ }
+ if (pos == K)
+ break;
+ }
+ if (pos < K)
+ {
+ diskann::cerr << "Found pos: " << pos << "fewer than K elements " << K << " for query" << std::endl;
+ }
+
+ return retval;
+}
+
+template <typename T, typename TagT, typename LabelT>
+std::pair<uint32_t, uint32_t> Index<T, TagT, LabelT>::_search_with_filters(const DataType &query,
+ const std::string &raw_label, const size_t K,
+ const uint32_t L, std::any &indices,
+ float *distances)
+{
+ auto converted_label = this->get_converted_label(raw_label);
+ if (typeid(uint64_t *) == indices.type())
+ {
+ auto ptr = std::any_cast<uint64_t *>(indices);
+ return this->search_with_filters(std::any_cast<T *>(query), converted_label, K, L, ptr, distances);
+ }
+ else if (typeid(uint32_t *) == indices.type())
+ {
+ auto ptr = std::any_cast<uint32_t *>(indices);
+ return this->search_with_filters(std::any_cast<T *>(query), converted_label, K, L, ptr, distances);
+ }
+ else
+ {
+ throw ANNException("Error: Id type can only be uint64_t or uint32_t.", -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+template <typename IdType>
+std::pair<uint32_t, uint32_t> Index<T, TagT, LabelT>::search_with_filters(const T *query, const LabelT &filter_label,
+ const size_t K, const uint32_t L,
+ IdType *indices, float *distances)
+{
+ if (K > (uint64_t)L)
+ {
+ throw ANNException("Set L to a value of at least K", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+
+ if (L > scratch->get_L())
+ {
+ diskann::cout << "Attempting to expand query scratch_space. Was created "
+ << "with Lsize: " << scratch->get_L() << " but search L is: " << L << std::endl;
+ scratch->resize_for_new_L(L);
+ diskann::cout << "Resize completed. New scratch->L is " << scratch->get_L() << std::endl;
+ }
+
+ std::vector<LabelT> filter_vec;
+ std::vector<uint32_t> init_ids = get_init_ids();
+
+ std::shared_lock<std::shared_timed_mutex> lock(_update_lock);
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock, std::defer_lock);
+ if (_dynamic_index)
+ tl.lock();
+
+ if (_label_to_start_id.find(filter_label) != _label_to_start_id.end())
+ {
+ init_ids.emplace_back(_label_to_start_id[filter_label]);
+ }
+ else
+ {
+ diskann::cout << "No filtered medoid found. exitting "
+ << std::endl; // RKNOTE: If universal label found start there
+ throw diskann::ANNException("No filtered medoid found. exitting ", -1);
+ }
+ if (_dynamic_index)
+ tl.unlock();
+
+ filter_vec.emplace_back(filter_label);
+
+ _data_store->preprocess_query(query, scratch);
+ auto retval = iterate_to_fixed_point(scratch, L, init_ids, true, filter_vec, true);
+
+ auto best_L_nodes = scratch->best_l_nodes();
+
+ size_t pos = 0;
+ for (size_t i = 0; i < best_L_nodes.size(); ++i)
+ {
+ if (best_L_nodes[i].id < _max_points)
+ {
+ indices[pos] = (IdType)best_L_nodes[i].id;
+
+ if (distances != nullptr)
+ {
+#ifdef EXEC_ENV_OLS
+ // DLVS expects negative distances
+ distances[pos] = best_L_nodes[i].distance;
+#else
+ distances[pos] = _dist_metric == diskann::Metric::INNER_PRODUCT ? -1 * best_L_nodes[i].distance
+ : best_L_nodes[i].distance;
+#endif
+ }
+ pos++;
+ }
+ if (pos == K)
+ break;
+ }
+ if (pos < K)
+ {
+ diskann::cerr << "Found fewer than K elements for query" << std::endl;
+ }
+
+ return retval;
+}
+
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::_search_with_tags(const DataType &query, const uint64_t K, const uint32_t L,
+ const TagType &tags, float *distances, DataVector &res_vectors,
+ bool use_filters, const std::string filter_label)
+{
+ try
+ {
+ return this->search_with_tags(std::any_cast<const T *>(query), K, L, std::any_cast<TagT *>(tags), distances,
+ res_vectors.get<std::vector<T *>>(), use_filters, filter_label);
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad any cast while performing _search_with_tags() " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error: " + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::search_with_tags(const T *query, const uint64_t K, const uint32_t L, TagT *tags,
+ float *distances, std::vector<T *> &res_vectors, bool use_filters,
+ const std::string filter_label)
+{
+ if (K > (uint64_t)L)
+ {
+ throw ANNException("Set L to a value of at least K", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+
+ if (L > scratch->get_L())
+ {
+ diskann::cout << "Attempting to expand query scratch_space. Was created "
+ << "with Lsize: " << scratch->get_L() << " but search L is: " << L << std::endl;
+ scratch->resize_for_new_L(L);
+ diskann::cout << "Resize completed. New scratch->L is " << scratch->get_L() << std::endl;
+ }
+
+ std::shared_lock<std::shared_timed_mutex> ul(_update_lock);
+
+ const std::vector<uint32_t> init_ids = get_init_ids();
+
+ //_distance->preprocess_query(query, _data_store->get_dims(),
+ // scratch->aligned_query());
+ _data_store->preprocess_query(query, scratch);
+ if (!use_filters)
+ {
+ const std::vector<LabelT> unused_filter_label;
+ iterate_to_fixed_point(scratch, L, init_ids, false, unused_filter_label, true);
+ }
+ else
+ {
+ std::vector<LabelT> filter_vec;
+ auto converted_label = this->get_converted_label(filter_label);
+ filter_vec.push_back(converted_label);
+ iterate_to_fixed_point(scratch, L, init_ids, true, filter_vec, true);
+ }
+
+ NeighborPriorityQueue &best_L_nodes = scratch->best_l_nodes();
+ assert(best_L_nodes.size() <= L);
+
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock);
+
+ size_t pos = 0;
+ for (size_t i = 0; i < best_L_nodes.size(); ++i)
+ {
+ auto node = best_L_nodes[i];
+
+ TagT tag;
+ if (_location_to_tag.try_get(node.id, tag))
+ {
+ tags[pos] = tag;
+
+ if (res_vectors.size() > 0)
+ {
+ _data_store->get_vector(node.id, res_vectors[pos]);
+ }
+
+ if (distances != nullptr)
+ {
+#ifdef EXEC_ENV_OLS
+ distances[pos] = node.distance; // DLVS expects negative distances
+#else
+ distances[pos] = _dist_metric == INNER_PRODUCT ? -1 * node.distance : node.distance;
+#endif
+ }
+ pos++;
+ // If res_vectors.size() < k, clip at the value.
+ if (pos == K || pos == res_vectors.size())
+ break;
+ }
+ }
+
+ return pos;
+}
+
+template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::get_num_points()
+{
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock);
+ return _nd;
+}
+
+template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::get_max_points()
+{
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock);
+ return _max_points;
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::generate_frozen_point()
+{
+ if (_num_frozen_pts == 0)
+ return;
+
+ if (_num_frozen_pts > 1)
+ {
+ throw ANNException("More than one frozen point not supported in generate_frozen_point", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+
+ if (_nd == 0)
+ {
+ throw ANNException("ERROR: Can not pick a frozen point since nd=0", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ size_t res = calculate_entry_point();
+
+ // REFACTOR PQ: Not sure if we should do this for both stores.
+ if (_pq_dist)
+ {
+ // copy the PQ data corresponding to the point returned by
+ // calculate_entry_point
+ // memcpy(_pq_data + _max_points * _num_pq_chunks,
+ // _pq_data + res * _num_pq_chunks,
+ // _num_pq_chunks * DIV_ROUND_UP(NUM_PQ_BITS, 8));
+ _pq_data_store->copy_vectors((location_t)res, (location_t)_max_points, 1);
+ }
+ else
+ {
+ _data_store->copy_vectors((location_t)res, (location_t)_max_points, 1);
+ }
+ _frozen_pts_used++;
+}
+
+template <typename T, typename TagT, typename LabelT> int Index<T, TagT, LabelT>::enable_delete()
+{
+ assert(_enable_tags);
+
+ if (!_enable_tags)
+ {
+ diskann::cerr << "Tags must be instantiated for deletions" << std::endl;
+ return -2;
+ }
+
+ if (this->_deletes_enabled)
+ {
+ return 0;
+ }
+
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+
+ if (_data_compacted)
+ {
+ for (uint32_t slot = (uint32_t)_nd; slot < _max_points; ++slot)
+ {
+ _empty_slots.insert(slot);
+ }
+ }
+ this->_deletes_enabled = true;
+ return 0;
+}
+
+template <typename T, typename TagT, typename LabelT>
+inline void Index<T, TagT, LabelT>::process_delete(const tsl::robin_set<uint32_t> &old_delete_set, size_t loc,
+ const uint32_t range, const uint32_t maxc, const float alpha,
+ InMemQueryScratch<T> *scratch)
+{
+ tsl::robin_set<uint32_t> &expanded_nodes_set = scratch->expanded_nodes_set();
+ std::vector<Neighbor> &expanded_nghrs_vec = scratch->expanded_nodes_vec();
+
+ // If this condition were not true, deadlock could result
+ assert(old_delete_set.find((uint32_t)loc) == old_delete_set.end());
+
+ std::vector<uint32_t> adj_list;
+ {
+ // Acquire and release lock[loc] before acquiring locks for neighbors
+ std::unique_lock<non_recursive_mutex> adj_list_lock;
+ if (_conc_consolidate)
+ adj_list_lock = std::unique_lock<non_recursive_mutex>(_locks[loc]);
+ adj_list = _graph_store->get_neighbours((location_t)loc);
+ }
+
+ bool modify = false;
+ for (auto ngh : adj_list)
+ {
+ if (old_delete_set.find(ngh) == old_delete_set.end())
+ {
+ expanded_nodes_set.insert(ngh);
+ }
+ else
+ {
+ modify = true;
+
+ std::unique_lock<non_recursive_mutex> ngh_lock;
+ if (_conc_consolidate)
+ ngh_lock = std::unique_lock<non_recursive_mutex>(_locks[ngh]);
+ for (auto j : _graph_store->get_neighbours((location_t)ngh))
+ if (j != loc && old_delete_set.find(j) == old_delete_set.end())
+ expanded_nodes_set.insert(j);
+ }
+ }
+
+ if (modify)
+ {
+ if (expanded_nodes_set.size() <= range)
+ {
+ std::unique_lock<non_recursive_mutex> adj_list_lock(_locks[loc]);
+ _graph_store->clear_neighbours((location_t)loc);
+ for (auto &ngh : expanded_nodes_set)
+ _graph_store->add_neighbour((location_t)loc, ngh);
+ }
+ else
+ {
+ // Create a pool of Neighbor candidates from the expanded_nodes_set
+ expanded_nghrs_vec.reserve(expanded_nodes_set.size());
+ for (auto &ngh : expanded_nodes_set)
+ {
+ expanded_nghrs_vec.emplace_back(ngh, _data_store->get_distance((location_t)loc, (location_t)ngh));
+ }
+ std::sort(expanded_nghrs_vec.begin(), expanded_nghrs_vec.end());
+ std::vector<uint32_t> &occlude_list_output = scratch->occlude_list_output();
+ occlude_list((uint32_t)loc, expanded_nghrs_vec, alpha, range, maxc, occlude_list_output, scratch,
+ &old_delete_set);
+ std::unique_lock<non_recursive_mutex> adj_list_lock(_locks[loc]);
+ _graph_store->set_neighbours((location_t)loc, occlude_list_output);
+ }
+ }
+}
+
+// Returns number of live points left after consolidation
+template <typename T, typename TagT, typename LabelT>
+consolidation_report Index<T, TagT, LabelT>::consolidate_deletes(const IndexWriteParameters &params)
+{
+ if (!_enable_tags)
+ throw diskann::ANNException("Point tag array not instantiated", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ {
+ std::shared_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::shared_lock<std::shared_timed_mutex> dl(_delete_lock);
+ if (_empty_slots.size() + _nd != _max_points)
+ {
+ std::string err = "#empty slots + nd != max points";
+ diskann::cerr << err << std::endl;
+ throw ANNException(err, -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (_location_to_tag.size() + _delete_set->size() != _nd)
+ {
+ diskann::cerr << "Error: _location_to_tag.size (" << _location_to_tag.size() << ") + _delete_set->size ("
+ << _delete_set->size() << ") != _nd(" << _nd << ") ";
+ return consolidation_report(diskann::consolidation_report::status_code::INCONSISTENT_COUNT_ERROR, 0, 0, 0,
+ 0, 0, 0, 0);
+ }
+
+ if (_location_to_tag.size() != _tag_to_location.size())
+ {
+ throw diskann::ANNException("_location_to_tag and _tag_to_location not of same size", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+ }
+
+ std::unique_lock<std::shared_timed_mutex> update_lock(_update_lock, std::defer_lock);
+ if (!_conc_consolidate)
+ update_lock.lock();
+
+ std::unique_lock<std::shared_timed_mutex> cl(_consolidate_lock, std::defer_lock);
+ if (!cl.try_lock())
+ {
+ diskann::cerr << "Consildate delete function failed to acquire consolidate lock" << std::endl;
+ return consolidation_report(diskann::consolidation_report::status_code::LOCK_FAIL, 0, 0, 0, 0, 0, 0, 0);
+ }
+
+ diskann::cout << "Starting consolidate_deletes... ";
+
+ std::unique_ptr<tsl::robin_set<uint32_t>> old_delete_set(new tsl::robin_set<uint32_t>);
+ {
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+ std::swap(_delete_set, old_delete_set);
+ }
+
+ if (old_delete_set->find(_start) != old_delete_set->end())
+ {
+ throw diskann::ANNException("ERROR: start node has been deleted", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ const uint32_t range = params.max_degree;
+ const uint32_t maxc = params.max_occlusion_size;
+ const float alpha = params.alpha;
+ const uint32_t num_threads = params.num_threads == 0 ? omp_get_num_procs() : params.num_threads;
+
+ uint32_t num_calls_to_process_delete = 0;
+ diskann::Timer timer;
+#pragma omp parallel for num_threads(num_threads) schedule(dynamic, 8192) reduction(+ : num_calls_to_process_delete)
+ for (int64_t loc = 0; loc < (int64_t)_max_points; loc++)
+ {
+ if (old_delete_set->find((uint32_t)loc) == old_delete_set->end() && !_empty_slots.is_in_set((uint32_t)loc))
+ {
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+ process_delete(*old_delete_set, loc, range, maxc, alpha, scratch);
+ num_calls_to_process_delete += 1;
+ }
+ }
+ for (int64_t loc = _max_points; loc < (int64_t)(_max_points + _num_frozen_pts); loc++)
+ {
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+ process_delete(*old_delete_set, loc, range, maxc, alpha, scratch);
+ num_calls_to_process_delete += 1;
+ }
+
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ size_t ret_nd = release_locations(*old_delete_set);
+ size_t max_points = _max_points;
+ size_t empty_slots_size = _empty_slots.size();
+
+ std::shared_lock<std::shared_timed_mutex> dl(_delete_lock);
+ size_t delete_set_size = _delete_set->size();
+ size_t old_delete_set_size = old_delete_set->size();
+
+ if (!_conc_consolidate)
+ {
+ update_lock.unlock();
+ }
+
+ double duration = timer.elapsed() / 1000000.0;
+ diskann::cout << " done in " << duration << " seconds." << std::endl;
+ return consolidation_report(diskann::consolidation_report::status_code::SUCCESS, ret_nd, max_points,
+ empty_slots_size, old_delete_set_size, delete_set_size, num_calls_to_process_delete,
+ duration);
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::compact_frozen_point()
+{
+ if (_nd < _max_points && _num_frozen_pts > 0)
+ {
+ reposition_points((uint32_t)_max_points, (uint32_t)_nd, (uint32_t)_num_frozen_pts);
+ _start = (uint32_t)_nd;
+
+ if (_filtered_index && _dynamic_index)
+ {
+ // update medoid id's as frozen points are treated as medoid
+ for (auto &[label, medoid_id] : _label_to_start_id)
+ {
+ /* if (label == _universal_label)
+ continue;*/
+ _label_to_start_id[label] = (uint32_t)_nd + (medoid_id - (uint32_t)_max_points);
+ }
+ }
+ }
+}
+
+// Should be called after acquiring _update_lock
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::compact_data()
+{
+ if (!_dynamic_index)
+ throw ANNException("Can not compact a non-dynamic index", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ if (_data_compacted)
+ {
+ diskann::cerr << "Warning! Calling compact_data() when _data_compacted is true!" << std::endl;
+ return;
+ }
+
+ if (_delete_set->size() > 0)
+ {
+ throw ANNException("Can not compact data when index has non-empty _delete_set of "
+ "size: " +
+ std::to_string(_delete_set->size()),
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ diskann::Timer timer;
+
+ std::vector<uint32_t> new_location = std::vector<uint32_t>(_max_points + _num_frozen_pts, UINT32_MAX);
+
+ uint32_t new_counter = 0;
+ std::set<uint32_t> empty_locations;
+ for (uint32_t old_location = 0; old_location < _max_points; old_location++)
+ {
+ if (_location_to_tag.contains(old_location))
+ {
+ new_location[old_location] = new_counter;
+ new_counter++;
+ }
+ else
+ {
+ empty_locations.insert(old_location);
+ }
+ }
+ for (uint32_t old_location = (uint32_t)_max_points; old_location < _max_points + _num_frozen_pts; old_location++)
+ {
+ new_location[old_location] = old_location;
+ }
+
+ // If start node is removed, throw an exception
+ if (_start < _max_points && !_location_to_tag.contains(_start))
+ {
+ throw diskann::ANNException("ERROR: Start node deleted.", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ size_t num_dangling = 0;
+ for (uint32_t old = 0; old < _max_points + _num_frozen_pts; ++old)
+ {
+ // compact _final_graph
+ std::vector<uint32_t> new_adj_list;
+
+ if ((new_location[old] < _max_points) // If point continues to exist
+ || (old >= _max_points && old < _max_points + _num_frozen_pts))
+ {
+ new_adj_list.reserve(_graph_store->get_neighbours((location_t)old).size());
+ for (auto ngh_iter : _graph_store->get_neighbours((location_t)old))
+ {
+ if (empty_locations.find(ngh_iter) != empty_locations.end())
+ {
+ ++num_dangling;
+ diskann::cerr << "Error in compact_data(). _final_graph[" << old << "] has neighbor " << ngh_iter
+ << " which is a location not associated with any tag." << std::endl;
+ }
+ else
+ {
+ new_adj_list.push_back(new_location[ngh_iter]);
+ }
+ }
+ //_graph_store->get_neighbours((location_t)old).swap(new_adj_list);
+ _graph_store->set_neighbours((location_t)old, new_adj_list);
+
+ // Move the data and adj list to the correct position
+ if (new_location[old] != old)
+ {
+ assert(new_location[old] < old);
+ _graph_store->swap_neighbours(new_location[old], (location_t)old);
+
+ if (_filtered_index)
+ {
+ _location_to_labels[new_location[old]].swap(_location_to_labels[old]);
+ }
+
+ _data_store->copy_vectors(old, new_location[old], 1);
+ }
+ }
+ else
+ {
+ _graph_store->clear_neighbours((location_t)old);
+ }
+ }
+ diskann::cerr << "#dangling references after data compaction: " << num_dangling << std::endl;
+
+ _tag_to_location.clear();
+ for (auto pos = _location_to_tag.find_first(); pos.is_valid(); pos = _location_to_tag.find_next(pos))
+ {
+ const auto tag = _location_to_tag.get(pos);
+ _tag_to_location[tag] = new_location[pos._key];
+ }
+ _location_to_tag.clear();
+ for (const auto &iter : _tag_to_location)
+ {
+ _location_to_tag.set(iter.second, iter.first);
+ }
+ // remove all cleared up old
+ for (size_t old = _nd; old < _max_points; ++old)
+ {
+ _graph_store->clear_neighbours((location_t)old);
+ }
+ if (_filtered_index)
+ {
+ for (size_t old = _nd; old < _max_points; old++)
+ {
+ _location_to_labels[old].clear();
+ }
+ }
+
+ _empty_slots.clear();
+ // mark all slots after _nd as empty
+ for (auto i = _nd; i < _max_points; i++)
+ {
+ _empty_slots.insert((uint32_t)i);
+ }
+ _data_compacted = true;
+ diskann::cout << "Time taken for compact_data: " << timer.elapsed() / 1000000. << "s." << std::endl;
+}
+
+//
+// Caller must hold unique _tag_lock and _delete_lock before calling this
+//
+template <typename T, typename TagT, typename LabelT> int Index<T, TagT, LabelT>::reserve_location()
+{
+ if (_nd >= _max_points)
+ {
+ return -1;
+ }
+ uint32_t location;
+ if (_data_compacted && _empty_slots.is_empty())
+ {
+ // This code path is encountered when enable_delete hasn't been
+ // called yet, so no points have been deleted and _empty_slots
+ // hasn't been filled in. In that case, just keep assigning
+ // consecutive locations.
+ location = (uint32_t)_nd;
+ }
+ else
+ {
+ assert(_empty_slots.size() != 0);
+ assert(_empty_slots.size() + _nd == _max_points);
+
+ location = _empty_slots.pop_any();
+ _delete_set->erase(location);
+ }
+ ++_nd;
+ return location;
+}
+
+template <typename T, typename TagT, typename LabelT> size_t Index<T, TagT, LabelT>::release_location(int location)
+{
+ if (_empty_slots.is_in_set(location))
+ throw ANNException("Trying to release location, but location already in empty slots", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ _empty_slots.insert(location);
+
+ _nd--;
+ return _nd;
+}
+
+template <typename T, typename TagT, typename LabelT>
+size_t Index<T, TagT, LabelT>::release_locations(const tsl::robin_set<uint32_t> &locations)
+{
+ for (auto location : locations)
+ {
+ if (_empty_slots.is_in_set(location))
+ throw ANNException("Trying to release location, but location "
+ "already in empty slots",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ _empty_slots.insert(location);
+
+ _nd--;
+ }
+
+ if (_empty_slots.size() + _nd != _max_points)
+ throw ANNException("#empty slots + nd != max points", -1, __FUNCSIG__, __FILE__, __LINE__);
+
+ return _nd;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::reposition_points(uint32_t old_location_start, uint32_t new_location_start,
+ uint32_t num_locations)
+{
+ if (num_locations == 0 || old_location_start == new_location_start)
+ {
+ return;
+ }
+
+ // Update pointers to the moved nodes. Note: the computation is correct even
+ // when new_location_start < old_location_start given the C++ uint32_t
+ // integer arithmetic rules.
+ const uint32_t location_delta = new_location_start - old_location_start;
+
+ std::vector<location_t> updated_neighbours_location;
+ for (uint32_t i = 0; i < _max_points + _num_frozen_pts; i++)
+ {
+ auto &i_neighbours = _graph_store->get_neighbours((location_t)i);
+ std::vector<location_t> i_neighbours_copy(i_neighbours.begin(), i_neighbours.end());
+ for (auto &loc : i_neighbours_copy)
+ {
+ if (loc >= old_location_start && loc < old_location_start + num_locations)
+ loc += location_delta;
+ }
+ _graph_store->set_neighbours(i, i_neighbours_copy);
+ }
+
+ // The [start, end) interval which will contain obsolete points to be
+ // cleared.
+ uint32_t mem_clear_loc_start = old_location_start;
+ uint32_t mem_clear_loc_end_limit = old_location_start + num_locations;
+
+ // Move the adjacency lists. Make sure that overlapping ranges are handled
+ // correctly.
+ if (new_location_start < old_location_start)
+ {
+ // New location before the old location: copy the entries in order
+ // to avoid modifying locations that are yet to be copied.
+ for (uint32_t loc_offset = 0; loc_offset < num_locations; loc_offset++)
+ {
+ assert(_graph_store->get_neighbours(new_location_start + loc_offset).empty());
+ _graph_store->swap_neighbours(new_location_start + loc_offset, old_location_start + loc_offset);
+ if (_dynamic_index && _filtered_index)
+ {
+ _location_to_labels[new_location_start + loc_offset].swap(
+ _location_to_labels[old_location_start + loc_offset]);
+ }
+ }
+ // If ranges are overlapping, make sure not to clear the newly copied
+ // data.
+ if (mem_clear_loc_start < new_location_start + num_locations)
+ {
+ // Clear only after the end of the new range.
+ mem_clear_loc_start = new_location_start + num_locations;
+ }
+ }
+ else
+ {
+ // Old location after the new location: copy from the end of the range
+ // to avoid modifying locations that are yet to be copied.
+ for (uint32_t loc_offset = num_locations; loc_offset > 0; loc_offset--)
+ {
+ assert(_graph_store->get_neighbours(new_location_start + loc_offset - 1u).empty());
+ _graph_store->swap_neighbours(new_location_start + loc_offset - 1u, old_location_start + loc_offset - 1u);
+ if (_dynamic_index && _filtered_index)
+ {
+ _location_to_labels[new_location_start + loc_offset - 1u].swap(
+ _location_to_labels[old_location_start + loc_offset - 1u]);
+ }
+ }
+
+ // If ranges are overlapping, make sure not to clear the newly copied
+ // data.
+ if (mem_clear_loc_end_limit > new_location_start)
+ {
+ // Clear only up to the beginning of the new range.
+ mem_clear_loc_end_limit = new_location_start;
+ }
+ }
+ _data_store->move_vectors(old_location_start, new_location_start, num_locations);
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::reposition_frozen_point_to_end()
+{
+ if (_num_frozen_pts == 0)
+ return;
+
+ if (_nd == _max_points)
+ {
+ diskann::cout << "Not repositioning frozen point as it is already at the end." << std::endl;
+ return;
+ }
+
+ reposition_points((uint32_t)_nd, (uint32_t)_max_points, (uint32_t)_num_frozen_pts);
+ _start = (uint32_t)_max_points;
+
+ // update medoid id's as frozen points are treated as medoid
+ if (_filtered_index && _dynamic_index)
+ {
+ for (auto &[label, medoid_id] : _label_to_start_id)
+ {
+ /*if (label == _universal_label)
+ continue;*/
+ _label_to_start_id[label] = (uint32_t)_max_points + (medoid_id - (uint32_t)_nd);
+ }
+ }
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::resize(size_t new_max_points)
+{
+ const size_t new_internal_points = new_max_points + _num_frozen_pts;
+ auto start = std::chrono::high_resolution_clock::now();
+ assert(_empty_slots.size() == 0); // should not resize if there are empty slots.
+
+ _data_store->resize((location_t)new_internal_points);
+ _graph_store->resize_graph(new_internal_points);
+ _locks = std::vector<non_recursive_mutex>(new_internal_points);
+
+ if (_num_frozen_pts != 0)
+ {
+ reposition_points((uint32_t)_max_points, (uint32_t)new_max_points, (uint32_t)_num_frozen_pts);
+ _start = (uint32_t)new_max_points;
+ }
+
+ _max_points = new_max_points;
+ _empty_slots.reserve(_max_points);
+ for (auto i = _nd; i < _max_points; i++)
+ {
+ _empty_slots.insert((uint32_t)i);
+ }
+
+ auto stop = std::chrono::high_resolution_clock::now();
+ diskann::cout << "Resizing took: " << std::chrono::duration<double>(stop - start).count() << "s" << std::endl;
+}
+
+template <typename T, typename TagT, typename LabelT>
+int Index<T, TagT, LabelT>::_insert_point(const DataType &point, const TagType tag)
+{
+ try
+ {
+ return this->insert_point(std::any_cast<const T *>(point), std::any_cast<const TagT>(tag));
+ }
+ catch (const std::bad_any_cast &anycast_e)
+ {
+ throw new ANNException("Error:Trying to insert invalid data type" + std::string(anycast_e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw new ANNException("Error:" + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+int Index<T, TagT, LabelT>::_insert_point(const DataType &point, const TagType tag, Labelvector &labels)
+{
+ try
+ {
+ return this->insert_point(std::any_cast<const T *>(point), std::any_cast<const TagT>(tag),
+ labels.get<const std::vector<LabelT>>());
+ }
+ catch (const std::bad_any_cast &anycast_e)
+ {
+ throw new ANNException("Error:Trying to insert invalid data type" + std::string(anycast_e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw new ANNException("Error:" + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+int Index<T, TagT, LabelT>::insert_point(const T *point, const TagT tag)
+{
+ std::vector<LabelT> no_labels{0};
+ return insert_point(point, tag, no_labels);
+}
+
+template <typename T, typename TagT, typename LabelT>
+int Index<T, TagT, LabelT>::insert_point(const T *point, const TagT tag, const std::vector<LabelT> &labels)
+{
+
+ assert(_has_built);
+ if (tag == 0)
+ {
+ throw diskann::ANNException("Do not insert point with tag 0. That is "
+ "reserved for points hidden "
+ "from the user.",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ std::shared_lock<std::shared_timed_mutex> shared_ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+
+ auto location = reserve_location();
+ if (_filtered_index)
+ {
+ if (labels.empty())
+ {
+ release_location(location);
+ std::cerr << "Error: Can't insert point with tag " + get_tag_string(tag) +
+ " . there are no labels for the point."
+ << std::endl;
+ return -1;
+ }
+
+ _location_to_labels[location] = labels;
+
+ for (LabelT label : labels)
+ {
+ if (_labels.find(label) == _labels.end())
+ {
+ if (_frozen_pts_used >= _num_frozen_pts)
+ {
+ throw ANNException(
+ "Error: For dynamic filtered index, the number of frozen points should be atleast equal "
+ "to number of unique labels.",
+ -1);
+ }
+
+ auto fz_location = (int)(_max_points) + _frozen_pts_used; // as first _fz_point
+ _labels.insert(label);
+ _label_to_start_id[label] = (uint32_t)fz_location;
+ _location_to_labels[fz_location] = {label};
+ _data_store->set_vector((location_t)fz_location, point);
+ _frozen_pts_used++;
+ }
+ }
+ }
+
+ if (location == -1)
+ {
+#if EXPAND_IF_FULL
+ dl.unlock();
+ tl.unlock();
+ shared_ul.unlock();
+
+ {
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+ tl.lock();
+ dl.lock();
+
+ if (_nd >= _max_points)
+ {
+ auto new_max_points = (size_t)(_max_points * INDEX_GROWTH_FACTOR);
+ resize(new_max_points);
+ }
+
+ dl.unlock();
+ tl.unlock();
+ ul.unlock();
+ }
+
+ shared_ul.lock();
+ tl.lock();
+ dl.lock();
+
+ location = reserve_location();
+ if (location == -1)
+ {
+ throw diskann::ANNException("Cannot reserve location even after "
+ "expanding graph. Terminating.",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+#else
+ return -1;
+#endif
+ } // cant insert as active pts >= max_pts
+ dl.unlock();
+
+ // Insert tag and mapping to location
+ if (_enable_tags)
+ {
+ // if tags are enabled and tag is already inserted. so we can't reuse that tag.
+ if (_tag_to_location.find(tag) != _tag_to_location.end())
+ {
+ release_location(location);
+ return -1;
+ }
+
+ _tag_to_location[tag] = location;
+ _location_to_tag.set(location, tag);
+ }
+ tl.unlock();
+
+ _data_store->set_vector(location, point); // update datastore
+
+ // Find and add appropriate graph edges
+ ScratchStoreManager<InMemQueryScratch<T>> manager(_query_scratch);
+ auto scratch = manager.scratch_space();
+ std::vector<uint32_t> pruned_list; // it is the set best candidates to connect to this point
+ if (_filtered_index)
+ {
+ // when filtered the best_candidates will share the same label ( label_present > distance)
+ search_for_point_and_prune(location, _indexingQueueSize, pruned_list, scratch, true, _filterIndexingQueueSize);
+ }
+ else
+ {
+ search_for_point_and_prune(location, _indexingQueueSize, pruned_list, scratch);
+ }
+ assert(pruned_list.size() > 0); // should find atleast one neighbour (i.e frozen point acting as medoid)
+
+ {
+ std::shared_lock<std::shared_timed_mutex> tlock(_tag_lock, std::defer_lock);
+ if (_conc_consolidate)
+ tlock.lock();
+
+ LockGuard guard(_locks[location]);
+ _graph_store->clear_neighbours(location);
+
+ std::vector<uint32_t> neighbor_links;
+ for (auto link : pruned_list)
+ {
+ if (_conc_consolidate)
+ if (!_location_to_tag.contains(link))
+ continue;
+ neighbor_links.emplace_back(link);
+ }
+ _graph_store->set_neighbours(location, neighbor_links);
+ assert(_graph_store->get_neighbours(location).size() <= _indexingRange);
+
+ if (_conc_consolidate)
+ tlock.unlock();
+ }
+
+ inter_insert(location, pruned_list, scratch);
+
+ return 0;
+}
+
+template <typename T, typename TagT, typename LabelT> int Index<T, TagT, LabelT>::_lazy_delete(const TagType &tag)
+{
+ try
+ {
+ return lazy_delete(std::any_cast<const TagT>(tag));
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException(std::string("Error: ") + e.what(), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::_lazy_delete(TagVector &tags, TagVector &failed_tags)
+{
+ try
+ {
+ this->lazy_delete(tags.get<const std::vector<TagT>>(), failed_tags.get<std::vector<TagT>>());
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad any cast while performing _lazy_delete() " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error: " + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT> int Index<T, TagT, LabelT>::lazy_delete(const TagT &tag)
+{
+ std::shared_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+ _data_compacted = false;
+
+ if (_tag_to_location.find(tag) == _tag_to_location.end())
+ {
+ diskann::cerr << "Delete tag not found " << get_tag_string(tag) << std::endl;
+ return -1;
+ }
+ assert(_tag_to_location[tag] < _max_points);
+
+ const auto location = _tag_to_location[tag];
+ _delete_set->insert(location);
+ _location_to_tag.erase(location);
+ _tag_to_location.erase(tag);
+ return 0;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::lazy_delete(const std::vector<TagT> &tags, std::vector<TagT> &failed_tags)
+{
+ if (failed_tags.size() > 0)
+ {
+ throw ANNException("failed_tags should be passed as an empty list", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ std::shared_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::unique_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::unique_lock<std::shared_timed_mutex> dl(_delete_lock);
+ _data_compacted = false;
+
+ for (auto tag : tags)
+ {
+ if (_tag_to_location.find(tag) == _tag_to_location.end())
+ {
+ failed_tags.push_back(tag);
+ }
+ else
+ {
+ const auto location = _tag_to_location[tag];
+ _delete_set->insert(location);
+ _location_to_tag.erase(location);
+ _tag_to_location.erase(tag);
+ }
+ }
+}
+
+template <typename T, typename TagT, typename LabelT> bool Index<T, TagT, LabelT>::is_index_saved()
+{
+ return _is_saved;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::_get_active_tags(TagRobinSet &active_tags)
+{
+ try
+ {
+ this->get_active_tags(active_tags.get<tsl::robin_set<TagT>>());
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad_any cast while performing _get_active_tags() " + std::string(e.what()), -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error :" + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::get_active_tags(tsl::robin_set<TagT> &active_tags)
+{
+ active_tags.clear();
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock);
+ for (auto iter : _tag_to_location)
+ {
+ active_tags.insert(iter.first);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::get_degree_stats(size_t &max_deg, size_t &min_deg, size_t &avg_deg, size_t &cnt_deg)
+{
+ max_deg = 0;
+ min_deg = SIZE_MAX;
+ avg_deg = 0;
+ cnt_deg = 0;
+ size_t total = 0;
+ for (size_t i = 0; i < _nd; i++)
+ {
+ auto &pool = _graph_store->get_neighbours((location_t)i);
+ cnt_deg += (pool.size() < 2);
+ max_deg = std::max(max_deg, pool.size());
+ min_deg = std::min(min_deg, pool.size());
+ total += pool.size();
+ }
+ avg_deg = total / _nd;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::dump_degree_stats(std::string filename)
+{
+ std::ofstream file(filename);
+ if (!file.is_open())
+ {
+ std::cerr << "Error: Could not open file " << filename << " for writing" << std::endl;
+ return;
+ }
+
+ // Write each node's degree to the file, one per line
+ for (size_t i = 0; i < _nd; i++)
+ {
+ auto &pool = _graph_store->get_neighbours((location_t)i);
+ file << pool.size() << std::endl;
+ }
+
+ file.close();
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::print_status()
+{
+ std::shared_lock<std::shared_timed_mutex> ul(_update_lock);
+ std::shared_lock<std::shared_timed_mutex> cl(_consolidate_lock);
+ std::shared_lock<std::shared_timed_mutex> tl(_tag_lock);
+ std::shared_lock<std::shared_timed_mutex> dl(_delete_lock);
+
+ diskann::cout << "------------------- Index object: " << (uint64_t)this << " -------------------" << std::endl;
+ diskann::cout << "Number of points: " << _nd << std::endl;
+ diskann::cout << "Graph size: " << _graph_store->get_total_points() << std::endl;
+ diskann::cout << "Location to tag size: " << _location_to_tag.size() << std::endl;
+ diskann::cout << "Tag to location size: " << _tag_to_location.size() << std::endl;
+ diskann::cout << "Number of empty slots: " << _empty_slots.size() << std::endl;
+ diskann::cout << std::boolalpha << "Data compacted: " << this->_data_compacted << std::endl;
+ diskann::cout << "---------------------------------------------------------"
+ "------------"
+ << std::endl;
+}
+
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::count_nodes_at_bfs_levels()
+{
+ std::unique_lock<std::shared_timed_mutex> ul(_update_lock);
+
+ boost::dynamic_bitset<> visited(_max_points + _num_frozen_pts);
+
+ size_t MAX_BFS_LEVELS = 32;
+ auto bfs_sets = new tsl::robin_set<uint32_t>[MAX_BFS_LEVELS];
+
+ bfs_sets[0].insert(_start);
+ visited.set(_start);
+
+ for (uint32_t i = (uint32_t)_max_points; i < _max_points + _num_frozen_pts; ++i)
+ {
+ if (i != _start)
+ {
+ bfs_sets[0].insert(i);
+ visited.set(i);
+ }
+ }
+
+ for (size_t l = 0; l < MAX_BFS_LEVELS - 1; ++l)
+ {
+ diskann::cout << "Number of nodes at BFS level " << l << " is " << bfs_sets[l].size() << std::endl;
+ if (bfs_sets[l].size() == 0)
+ break;
+ for (auto node : bfs_sets[l])
+ {
+ for (auto nghbr : _graph_store->get_neighbours((location_t)node))
+ {
+ if (!visited.test(nghbr))
+ {
+ visited.set(nghbr);
+ bfs_sets[l + 1].insert(nghbr);
+ }
+ }
+ }
+ }
+
+ delete[] bfs_sets;
+}
+
+// REFACTOR: This should be an OptimizedDataStore class
+template <typename T, typename TagT, typename LabelT> void Index<T, TagT, LabelT>::optimize_index_layout()
+{ // use after build or load
+ if (_dynamic_index)
+ {
+ throw diskann::ANNException("Optimize_index_layout not implemented for dyanmic indices", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+
+ float *cur_vec = new float[_data_store->get_aligned_dim()];
+ std::memset(cur_vec, 0, _data_store->get_aligned_dim() * sizeof(float));
+ _data_len = (_data_store->get_aligned_dim() + 1) * sizeof(float);
+ _neighbor_len = (_graph_store->get_max_observed_degree() + 1) * sizeof(uint32_t);
+ _node_size = _data_len + _neighbor_len;
+ _opt_graph = new char[_node_size * _nd];
+ auto dist_fast = (DistanceFastL2<T> *)(_data_store->get_dist_fn());
+ for (uint32_t i = 0; i < _nd; i++)
+ {
+ char *cur_node_offset = _opt_graph + i * _node_size;
+ _data_store->get_vector(i, (T *)cur_vec);
+ float cur_norm = dist_fast->norm((T *)cur_vec, (uint32_t)_data_store->get_aligned_dim());
+ std::memcpy(cur_node_offset, &cur_norm, sizeof(float));
+ std::memcpy(cur_node_offset + sizeof(float), cur_vec, _data_len - sizeof(float));
+
+ cur_node_offset += _data_len;
+ uint32_t k = (uint32_t)_graph_store->get_neighbours(i).size();
+ std::memcpy(cur_node_offset, &k, sizeof(uint32_t));
+ std::memcpy(cur_node_offset + sizeof(uint32_t), _graph_store->get_neighbours(i).data(), k * sizeof(uint32_t));
+ // std::vector<uint32_t>().swap(_graph_store->get_neighbours(i));
+ _graph_store->clear_neighbours(i);
+ }
+ _graph_store->clear_graph();
+ _graph_store->resize_graph(0);
+ delete[] cur_vec;
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::_search_with_optimized_layout(const DataType &query, size_t K, size_t L, uint32_t *indices)
+{
+ try
+ {
+ return this->search_with_optimized_layout(std::any_cast<const T *>(query), K, L, indices);
+ }
+ catch (const std::bad_any_cast &e)
+ {
+ throw ANNException("Error: bad any cast while performing "
+ "_search_with_optimized_layout() " +
+ std::string(e.what()),
+ -1);
+ }
+ catch (const std::exception &e)
+ {
+ throw ANNException("Error: " + std::string(e.what()), -1);
+ }
+}
+
+template <typename T, typename TagT, typename LabelT>
+void Index<T, TagT, LabelT>::search_with_optimized_layout(const T *query, size_t K, size_t L, uint32_t *indices)
+{
+ DistanceFastL2<T> *dist_fast = (DistanceFastL2<T> *)(_data_store->get_dist_fn());
+
+ NeighborPriorityQueue retset(L);
+ std::vector<uint32_t> init_ids(L);
+
+ boost::dynamic_bitset<> flags{_nd, 0};
+ uint32_t tmp_l = 0;
+ uint32_t *neighbors = (uint32_t *)(_opt_graph + _node_size * _start + _data_len);
+ uint32_t MaxM_ep = *neighbors;
+ neighbors++;
+
+ for (; tmp_l < L && tmp_l < MaxM_ep; tmp_l++)
+ {
+ init_ids[tmp_l] = neighbors[tmp_l];
+ flags[init_ids[tmp_l]] = true;
+ }
+
+ while (tmp_l < L)
+ {
+ uint32_t id = rand() % _nd;
+ if (flags[id])
+ continue;
+ flags[id] = true;
+ init_ids[tmp_l] = id;
+ tmp_l++;
+ }
+
+ for (uint32_t i = 0; i < init_ids.size(); i++)
+ {
+ uint32_t id = init_ids[i];
+ if (id >= _nd)
+ continue;
+ _mm_prefetch(_opt_graph + _node_size * id, _MM_HINT_T0);
+ }
+ L = 0;
+ for (uint32_t i = 0; i < init_ids.size(); i++)
+ {
+ uint32_t id = init_ids[i];
+ if (id >= _nd)
+ continue;
+ T *x = (T *)(_opt_graph + _node_size * id);
+ float norm_x = *x;
+ x++;
+ float dist = dist_fast->compare(x, query, norm_x, (uint32_t)_data_store->get_aligned_dim());
+ retset.insert(Neighbor(id, dist));
+ flags[id] = true;
+ L++;
+ }
+
+ while (retset.has_unexpanded_node())
+ {
+ auto nbr = retset.closest_unexpanded();
+ auto n = nbr.id;
+ _mm_prefetch(_opt_graph + _node_size * n + _data_len, _MM_HINT_T0);
+ neighbors = (uint32_t *)(_opt_graph + _node_size * n + _data_len);
+ uint32_t MaxM = *neighbors;
+ neighbors++;
+ for (uint32_t m = 0; m < MaxM; ++m)
+ _mm_prefetch(_opt_graph + _node_size * neighbors[m], _MM_HINT_T0);
+ for (uint32_t m = 0; m < MaxM; ++m)
+ {
+ uint32_t id = neighbors[m];
+ if (flags[id])
+ continue;
+ flags[id] = 1;
+ T *data = (T *)(_opt_graph + _node_size * id);
+ float norm = *data;
+ data++;
+ float dist = dist_fast->compare(query, data, norm, (uint32_t)_data_store->get_aligned_dim());
+ Neighbor nn(id, dist);
+ retset.insert(nn);
+ }
+ }
+
+ for (size_t i = 0; i < K; i++)
+ {
+ indices[i] = retset[i].id;
+ }
+}
+
+/* Internals of the library */
+template <typename T, typename TagT, typename LabelT> const float Index<T, TagT, LabelT>::INDEX_GROWTH_FACTOR = 1.5f;
+
+// EXPORTS
+template DISKANN_DLLEXPORT class Index<float, int32_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, int32_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, int32_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<float, uint32_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, uint32_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, uint32_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<float, int64_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, int64_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, int64_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<float, uint64_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, uint64_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, uint64_t, uint32_t>;
+template DISKANN_DLLEXPORT class Index<float, tag_uint128, uint32_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, tag_uint128, uint32_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, tag_uint128, uint32_t>;
+// Label with short int 2 byte
+template DISKANN_DLLEXPORT class Index<float, int32_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, int32_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, int32_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<float, uint32_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, uint32_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, uint32_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<float, int64_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, int64_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, int64_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<float, uint64_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, uint64_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, uint64_t, uint16_t>;
+template DISKANN_DLLEXPORT class Index<float, tag_uint128, uint16_t>;
+template DISKANN_DLLEXPORT class Index<int8_t, tag_uint128, uint16_t>;
+template DISKANN_DLLEXPORT class Index<uint8_t, tag_uint128, uint16_t>;
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint32_t>::search<uint64_t>(
+ const float *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint32_t>::search<uint32_t>(
+ const float *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint32_t>::search<uint64_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint32_t>::search<uint32_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint32_t>::search<uint64_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint32_t>::search<uint32_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+// TagT==uint32_t
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint32_t>::search<uint64_t>(
+ const float *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint32_t>::search<uint32_t>(
+ const float *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint32_t>::search<uint64_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint32_t>::search<uint32_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint32_t>::search<uint64_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint32_t>::search<uint32_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint32_t>::search_with_filters<
+ uint64_t>(const float *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint32_t>::search_with_filters<
+ uint32_t>(const float *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint32_t>::search_with_filters<
+ uint64_t>(const uint8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint32_t>::search_with_filters<
+ uint32_t>(const uint8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint32_t>::search_with_filters<
+ uint64_t>(const int8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint32_t>::search_with_filters<
+ uint32_t>(const int8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+// TagT==uint32_t
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint32_t>::search_with_filters<
+ uint64_t>(const float *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint32_t>::search_with_filters<
+ uint32_t>(const float *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint32_t>::search_with_filters<
+ uint64_t>(const uint8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint32_t>::search_with_filters<
+ uint32_t>(const uint8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint32_t>::search_with_filters<
+ uint64_t>(const int8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint32_t>::search_with_filters<
+ uint32_t>(const int8_t *query, const uint32_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint16_t>::search<uint64_t>(
+ const float *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint16_t>::search<uint32_t>(
+ const float *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint16_t>::search<uint64_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint16_t>::search<uint32_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint16_t>::search<uint64_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint16_t>::search<uint32_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+// TagT==uint32_t
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint16_t>::search<uint64_t>(
+ const float *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint16_t>::search<uint32_t>(
+ const float *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint16_t>::search<uint64_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint16_t>::search<uint32_t>(
+ const uint8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint16_t>::search<uint64_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint64_t *indices, float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint16_t>::search<uint32_t>(
+ const int8_t *query, const size_t K, const uint32_t L, uint32_t *indices, float *distances);
+
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint16_t>::search_with_filters<
+ uint64_t>(const float *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint64_t, uint16_t>::search_with_filters<
+ uint32_t>(const float *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint16_t>::search_with_filters<
+ uint64_t>(const uint8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint64_t, uint16_t>::search_with_filters<
+ uint32_t>(const uint8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint16_t>::search_with_filters<
+ uint64_t>(const int8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint64_t, uint16_t>::search_with_filters<
+ uint32_t>(const int8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+// TagT==uint32_t
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint16_t>::search_with_filters<
+ uint64_t>(const float *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<float, uint32_t, uint16_t>::search_with_filters<
+ uint32_t>(const float *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint16_t>::search_with_filters<
+ uint64_t>(const uint8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<uint8_t, uint32_t, uint16_t>::search_with_filters<
+ uint32_t>(const uint8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint16_t>::search_with_filters<
+ uint64_t>(const int8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint64_t *indices,
+ float *distances);
+template DISKANN_DLLEXPORT std::pair<uint32_t, uint32_t> Index<int8_t, uint32_t, uint16_t>::search_with_filters<
+ uint32_t>(const int8_t *query, const uint16_t &filter_label, const size_t K, const uint32_t L, uint32_t *indices,
+ float *distances);
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/index_factory.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/index_factory.cpp
new file mode 100644
index 0000000..35790f8
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/index_factory.cpp
@@ -0,0 +1,213 @@
+#include "index_factory.h"
+#include "pq_l2_distance.h"
+
+namespace diskann
+{
+
+IndexFactory::IndexFactory(const IndexConfig &config) : _config(std::make_unique<IndexConfig>(config))
+{
+ check_config();
+}
+
+std::unique_ptr<AbstractIndex> IndexFactory::create_instance()
+{
+ return create_instance(_config->data_type, _config->tag_type, _config->label_type);
+}
+
+void IndexFactory::check_config()
+{
+ if (_config->dynamic_index && !_config->enable_tags)
+ {
+ throw ANNException("ERROR: Dynamic Indexing must have tags enabled.", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (_config->pq_dist_build)
+ {
+ if (_config->dynamic_index)
+ throw ANNException("ERROR: Dynamic Indexing not supported with PQ distance based "
+ "index construction",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ if (_config->metric == diskann::Metric::INNER_PRODUCT)
+ throw ANNException("ERROR: Inner product metrics not yet supported "
+ "with PQ distance "
+ "base index",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ if (_config->data_type != "float" && _config->data_type != "uint8" && _config->data_type != "int8")
+ {
+ throw ANNException("ERROR: invalid data type : + " + _config->data_type +
+ " is not supported. please select from [float, int8, uint8]",
+ -1);
+ }
+
+ if (_config->tag_type != "int32" && _config->tag_type != "uint32" && _config->tag_type != "int64" &&
+ _config->tag_type != "uint64")
+ {
+ throw ANNException("ERROR: invalid data type : + " + _config->tag_type +
+ " is not supported. please select from [int32, uint32, int64, uint64]",
+ -1);
+ }
+}
+
+template <typename T> Distance<T> *IndexFactory::construct_inmem_distance_fn(Metric metric)
+{
+ if (metric == diskann::Metric::COSINE && std::is_same<T, float>::value)
+ {
+ return (Distance<T> *)new AVXNormalizedCosineDistanceFloat();
+ }
+ else
+ {
+ return (Distance<T> *)get_distance_function<T>(metric);
+ }
+}
+
+template <typename T>
+std::shared_ptr<AbstractDataStore<T>> IndexFactory::construct_datastore(DataStoreStrategy strategy,
+ size_t total_internal_points, size_t dimension,
+ Metric metric)
+{
+ std::unique_ptr<Distance<T>> distance;
+ switch (strategy)
+ {
+ case DataStoreStrategy::MEMORY:
+ distance.reset(construct_inmem_distance_fn<T>(metric));
+ return std::make_shared<diskann::InMemDataStore<T>>((location_t)total_internal_points, dimension,
+ std::move(distance));
+ default:
+ break;
+ }
+ return nullptr;
+}
+
+std::unique_ptr<AbstractGraphStore> IndexFactory::construct_graphstore(const GraphStoreStrategy strategy,
+ const size_t size,
+ const size_t reserve_graph_degree)
+{
+ switch (strategy)
+ {
+ case GraphStoreStrategy::MEMORY:
+ return std::make_unique<InMemGraphStore>(size, reserve_graph_degree);
+ default:
+ throw ANNException("Error : Current GraphStoreStratagy is not supported.", -1);
+ }
+}
+
+template <typename T>
+std::shared_ptr<PQDataStore<T>> IndexFactory::construct_pq_datastore(DataStoreStrategy strategy, size_t num_points,
+ size_t dimension, Metric m, size_t num_pq_chunks,
+ bool use_opq)
+{
+ std::unique_ptr<Distance<T>> distance_fn;
+ std::unique_ptr<QuantizedDistance<T>> quantized_distance_fn;
+
+ quantized_distance_fn = std::move(std::make_unique<PQL2Distance<T>>((uint32_t)num_pq_chunks, use_opq));
+ switch (strategy)
+ {
+ case DataStoreStrategy::MEMORY:
+ distance_fn.reset(construct_inmem_distance_fn<T>(m));
+ return std::make_shared<diskann::PQDataStore<T>>(dimension, (location_t)(num_points), num_pq_chunks,
+ std::move(distance_fn), std::move(quantized_distance_fn));
+ default:
+ // REFACTOR TODO: We do support diskPQ - so we may need to add a new class for SSDPQDataStore!
+ break;
+ }
+ return nullptr;
+}
+
+template <typename data_type, typename tag_type, typename label_type>
+std::unique_ptr<AbstractIndex> IndexFactory::create_instance()
+{
+ size_t num_points = _config->max_points + _config->num_frozen_pts;
+ size_t dim = _config->dimension;
+ // auto graph_store = construct_graphstore(_config->graph_strategy, num_points);
+ auto data_store = construct_datastore<data_type>(_config->data_strategy, num_points, dim, _config->metric);
+ std::shared_ptr<AbstractDataStore<data_type>> pq_data_store = nullptr;
+
+ if (_config->data_strategy == DataStoreStrategy::MEMORY && _config->pq_dist_build)
+ {
+ pq_data_store =
+ construct_pq_datastore<data_type>(_config->data_strategy, num_points + _config->num_frozen_pts, dim,
+ _config->metric, _config->num_pq_chunks, _config->use_opq);
+ }
+ else
+ {
+ pq_data_store = data_store;
+ }
+ size_t max_reserve_degree =
+ (size_t)(defaults::GRAPH_SLACK_FACTOR * 1.05 *
+ (_config->index_write_params == nullptr ? 0 : _config->index_write_params->max_degree));
+ std::unique_ptr<AbstractGraphStore> graph_store =
+ construct_graphstore(_config->graph_strategy, num_points + _config->num_frozen_pts, max_reserve_degree);
+
+ // REFACTOR TODO: Must construct in-memory PQDatastore if strategy == ONDISK and must construct
+ // in-mem and on-disk PQDataStore if strategy == ONDISK and diskPQ is required.
+ return std::make_unique<diskann::Index<data_type, tag_type, label_type>>(*_config, data_store,
+ std::move(graph_store), pq_data_store);
+}
+
+std::unique_ptr<AbstractIndex> IndexFactory::create_instance(const std::string &data_type, const std::string &tag_type,
+ const std::string &label_type)
+{
+ if (data_type == std::string("float"))
+ {
+ return create_instance<float>(tag_type, label_type);
+ }
+ else if (data_type == std::string("uint8"))
+ {
+ return create_instance<uint8_t>(tag_type, label_type);
+ }
+ else if (data_type == std::string("int8"))
+ {
+ return create_instance<int8_t>(tag_type, label_type);
+ }
+ else
+ throw ANNException("Error: unsupported data_type please choose from [float/int8/uint8]", -1);
+}
+
+template <typename data_type>
+std::unique_ptr<AbstractIndex> IndexFactory::create_instance(const std::string &tag_type, const std::string &label_type)
+{
+ if (tag_type == std::string("int32"))
+ {
+ return create_instance<data_type, int32_t>(label_type);
+ }
+ else if (tag_type == std::string("uint32"))
+ {
+ return create_instance<data_type, uint32_t>(label_type);
+ }
+ else if (tag_type == std::string("int64"))
+ {
+ return create_instance<data_type, int64_t>(label_type);
+ }
+ else if (tag_type == std::string("uint64"))
+ {
+ return create_instance<data_type, uint64_t>(label_type);
+ }
+ else
+ throw ANNException("Error: unsupported tag_type please choose from [int32/uint32/int64/uint64]", -1);
+}
+
+template <typename data_type, typename tag_type>
+std::unique_ptr<AbstractIndex> IndexFactory::create_instance(const std::string &label_type)
+{
+ if (label_type == std::string("uint16") || label_type == std::string("ushort"))
+ {
+ return create_instance<data_type, tag_type, uint16_t>();
+ }
+ else if (label_type == std::string("uint32") || label_type == std::string("uint"))
+ {
+ return create_instance<data_type, tag_type, uint32_t>();
+ }
+ else
+ throw ANNException("Error: unsupported label_type please choose from [uint/ushort]", -1);
+}
+
+// template DISKANN_DLLEXPORT std::shared_ptr<AbstractDataStore<uint8_t>> IndexFactory::construct_datastore(
+// DataStoreStrategy stratagy, size_t num_points, size_t dimension, Metric m);
+// template DISKANN_DLLEXPORT std::shared_ptr<AbstractDataStore<int8_t>> IndexFactory::construct_datastore(
+// DataStoreStrategy stratagy, size_t num_points, size_t dimension, Metric m);
+// template DISKANN_DLLEXPORT std::shared_ptr<AbstractDataStore<float>> IndexFactory::construct_datastore(
+// DataStoreStrategy stratagy, size_t num_points, size_t dimension, Metric m);
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/linux_aligned_file_reader.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/linux_aligned_file_reader.cpp
new file mode 100644
index 0000000..64e7eee
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/linux_aligned_file_reader.cpp
@@ -0,0 +1,230 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "linux_aligned_file_reader.h"
+#ifndef __APPLE__
+
+#include <cassert>
+#include <cstdio>
+#include <iostream>
+#include "tsl/robin_map.h"
+#include "utils.h"
+#define MAX_EVENTS 1024
+
+namespace
+{
+typedef struct io_event io_event_t;
+typedef struct iocb iocb_t;
+
+void execute_io(io_context_t ctx, int fd, std::vector<AlignedRead> &read_reqs, uint64_t n_retries = 0)
+{
+#ifdef DEBUG
+ for (auto &req : read_reqs)
+ {
+ assert(IS_ALIGNED(req.len, 512));
+ // std::cout << "request:"<<req.offset<<":"<<req.len << std::endl;
+ assert(IS_ALIGNED(req.offset, 512));
+ assert(IS_ALIGNED(req.buf, 512));
+ // assert(malloc_usable_size(req.buf) >= req.len);
+ }
+#endif
+
+ // break-up requests into chunks of size MAX_EVENTS each
+ uint64_t n_iters = ROUND_UP(read_reqs.size(), MAX_EVENTS) / MAX_EVENTS;
+ for (uint64_t iter = 0; iter < n_iters; iter++)
+ {
+ uint64_t n_ops = std::min((uint64_t)read_reqs.size() - (iter * MAX_EVENTS), (uint64_t)MAX_EVENTS);
+ std::vector<iocb_t *> cbs(n_ops, nullptr);
+ std::vector<io_event_t> evts(n_ops);
+ std::vector<struct iocb> cb(n_ops);
+ for (uint64_t j = 0; j < n_ops; j++)
+ {
+ io_prep_pread(cb.data() + j, fd, read_reqs[j + iter * MAX_EVENTS].buf, read_reqs[j + iter * MAX_EVENTS].len,
+ read_reqs[j + iter * MAX_EVENTS].offset);
+ }
+
+ // initialize `cbs` using `cb` array
+ //
+
+ for (uint64_t i = 0; i < n_ops; i++)
+ {
+ cbs[i] = cb.data() + i;
+ }
+
+ uint64_t n_tries = 0;
+ while (n_tries <= n_retries)
+ {
+ // issue reads
+ int64_t ret = io_submit(ctx, (int64_t)n_ops, cbs.data());
+ // if requests didn't get accepted
+ if (ret != (int64_t)n_ops)
+ {
+ std::cerr << "io_submit() failed; returned " << ret << ", expected=" << n_ops << ", ernno=" << errno
+ << "=" << ::strerror(-ret) << ", try #" << n_tries + 1;
+ std::cout << "ctx: " << ctx << "\n";
+ exit(-1);
+ }
+ else
+ {
+ // wait on io_getevents
+ ret = io_getevents(ctx, (int64_t)n_ops, (int64_t)n_ops, evts.data(), nullptr);
+ // if requests didn't complete
+ if (ret != (int64_t)n_ops)
+ {
+ std::cerr << "io_getevents() failed; returned " << ret << ", expected=" << n_ops
+ << ", ernno=" << errno << "=" << ::strerror(-ret) << ", try #" << n_tries + 1;
+ exit(-1);
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+ // disabled since req.buf could be an offset into another buf
+ /*
+ for (auto &req : read_reqs) {
+ // corruption check
+ assert(malloc_usable_size(req.buf) >= req.len);
+ }
+ */
+ }
+}
+} // namespace
+
+LinuxAlignedFileReader::LinuxAlignedFileReader()
+{
+ this->file_desc = -1;
+}
+
+LinuxAlignedFileReader::~LinuxAlignedFileReader()
+{
+ int64_t ret;
+ // check to make sure file_desc is closed
+ ret = ::fcntl(this->file_desc, F_GETFD);
+ if (ret == -1)
+ {
+ if (errno != EBADF)
+ {
+ std::cerr << "close() not called" << std::endl;
+ // close file desc
+ ret = ::close(this->file_desc);
+ // error checks
+ if (ret == -1)
+ {
+ std::cerr << "close() failed; returned " << ret << ", errno=" << errno << ":" << ::strerror(errno)
+ << std::endl;
+ }
+ }
+ }
+}
+
+io_context_t &LinuxAlignedFileReader::get_ctx()
+{
+ std::unique_lock<std::mutex> lk(ctx_mut);
+ // perform checks only in DEBUG mode
+ if (ctx_map.find(std::this_thread::get_id()) == ctx_map.end())
+ {
+ std::cerr << "bad thread access; returning -1 as io_context_t" << std::endl;
+ return this->bad_ctx;
+ }
+ else
+ {
+ return ctx_map[std::this_thread::get_id()];
+ }
+}
+
+void LinuxAlignedFileReader::register_thread()
+{
+ auto my_id = std::this_thread::get_id();
+ std::unique_lock<std::mutex> lk(ctx_mut);
+ if (ctx_map.find(my_id) != ctx_map.end())
+ {
+ std::cerr << "multiple calls to register_thread from the same thread" << std::endl;
+ return;
+ }
+ io_context_t ctx = 0;
+ int ret = io_setup(MAX_EVENTS, &ctx);
+ if (ret != 0)
+ {
+ lk.unlock();
+ if (ret == -EAGAIN)
+ {
+ std::cerr << "io_setup() failed with EAGAIN: Consider increasing /proc/sys/fs/aio-max-nr" << std::endl;
+ }
+ else
+ {
+ std::cerr << "io_setup() failed; returned " << ret << ": " << ::strerror(-ret) << std::endl;
+ }
+ }
+ else
+ {
+ diskann::cout << "allocating ctx: " << ctx << " to thread-id:" << my_id << std::endl;
+ ctx_map[my_id] = ctx;
+ }
+ lk.unlock();
+}
+
+void LinuxAlignedFileReader::deregister_thread()
+{
+ auto my_id = std::this_thread::get_id();
+ std::unique_lock<std::mutex> lk(ctx_mut);
+ assert(ctx_map.find(my_id) != ctx_map.end());
+
+ lk.unlock();
+ io_context_t ctx = this->get_ctx();
+ io_destroy(ctx);
+ // assert(ret == 0);
+ lk.lock();
+ ctx_map.erase(my_id);
+ std::cerr << "returned ctx from thread-id:" << my_id << std::endl;
+ lk.unlock();
+}
+
+void LinuxAlignedFileReader::deregister_all_threads()
+{
+ std::unique_lock<std::mutex> lk(ctx_mut);
+ for (auto x = ctx_map.begin(); x != ctx_map.end(); x++)
+ {
+ io_context_t ctx = x.value();
+ io_destroy(ctx);
+ // assert(ret == 0);
+ // lk.lock();
+ // ctx_map.erase(my_id);
+ // std::cerr << "returned ctx from thread-id:" << my_id << std::endl;
+ }
+ ctx_map.clear();
+ // lk.unlock();
+}
+
+void LinuxAlignedFileReader::open(const std::string &fname)
+{
+ int flags = O_DIRECT | O_RDONLY | O_LARGEFILE;
+ this->file_desc = ::open(fname.c_str(), flags);
+ // error checks
+ assert(this->file_desc != -1);
+ std::cerr << "Opened file : " << fname << std::endl;
+}
+
+void LinuxAlignedFileReader::close()
+{
+ // int64_t ret;
+
+ // check to make sure file_desc is closed
+ ::fcntl(this->file_desc, F_GETFD);
+ // assert(ret != -1);
+
+ ::close(this->file_desc);
+ // assert(ret != -1);
+}
+
+void LinuxAlignedFileReader::read(std::vector<AlignedRead> &read_reqs, io_context_t &ctx, bool async)
+{
+ if (async == true)
+ {
+ diskann::cout << "Async currently not supported in linux." << std::endl;
+ }
+ assert(this->file_desc != -1);
+ execute_io(ctx, this->file_desc, read_reqs);
+}
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/logger.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/logger.cpp
new file mode 100644
index 0000000..052f548
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/logger.cpp
@@ -0,0 +1,97 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <cstring>
+#include <iostream>
+
+#include "logger_impl.h"
+#include "windows_customizations.h"
+
+namespace diskann
+{
+
+#ifdef ENABLE_CUSTOM_LOGGER
+DISKANN_DLLEXPORT ANNStreamBuf coutBuff(stdout);
+DISKANN_DLLEXPORT ANNStreamBuf cerrBuff(stderr);
+
+DISKANN_DLLEXPORT std::basic_ostream<char> cout(&coutBuff);
+DISKANN_DLLEXPORT std::basic_ostream<char> cerr(&cerrBuff);
+std::function<void(LogLevel, const char *)> g_logger;
+
+void SetCustomLogger(std::function<void(LogLevel, const char *)> logger)
+{
+ g_logger = logger;
+ diskann::cout << "Set Custom Logger" << std::endl;
+}
+
+ANNStreamBuf::ANNStreamBuf(FILE *fp)
+{
+ if (fp == nullptr)
+ {
+ throw diskann::ANNException("File pointer passed to ANNStreamBuf() cannot be null", -1);
+ }
+ if (fp != stdout && fp != stderr)
+ {
+ throw diskann::ANNException("The custom logger only supports stdout and stderr.", -1);
+ }
+ _fp = fp;
+ _logLevel = (_fp == stdout) ? LogLevel::LL_Info : LogLevel::LL_Error;
+ _buf = new char[BUFFER_SIZE + 1]; // See comment in the header
+
+ std::memset(_buf, 0, (BUFFER_SIZE) * sizeof(char));
+ setp(_buf, _buf + BUFFER_SIZE - 1);
+}
+
+ANNStreamBuf::~ANNStreamBuf()
+{
+ sync();
+ _fp = nullptr; // we'll not close because we can't.
+ delete[] _buf;
+}
+
+int ANNStreamBuf::overflow(int c)
+{
+ std::lock_guard<std::mutex> lock(_mutex);
+ if (c != EOF)
+ {
+ *pptr() = (char)c;
+ pbump(1);
+ }
+ flush();
+ return c;
+}
+
+int ANNStreamBuf::sync()
+{
+ std::lock_guard<std::mutex> lock(_mutex);
+ flush();
+ return 0;
+}
+
+int ANNStreamBuf::underflow()
+{
+ throw diskann::ANNException("Attempt to read on streambuf meant only for writing.", -1);
+}
+
+int ANNStreamBuf::flush()
+{
+ const int num = (int)(pptr() - pbase());
+ logImpl(pbase(), num);
+ pbump(-num);
+ return num;
+}
+void ANNStreamBuf::logImpl(char *str, int num)
+{
+ str[num] = '\0'; // Safe. See the c'tor.
+ // Invoke the OLS custom logging function.
+ if (g_logger)
+ {
+ g_logger(_logLevel, str);
+ }
+}
+#else
+using std::cerr;
+using std::cout;
+#endif
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/math_utils.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/math_utils.cpp
new file mode 100644
index 0000000..d8fcda3
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/math_utils.cpp
@@ -0,0 +1,465 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <limits>
+#include <math_utils.h>
+#ifdef __APPLE__
+#include <Accelerate/Accelerate.h>
+#else
+#include <mkl.h>
+#endif
+#include "logger.h"
+#include "utils.h"
+
+namespace math_utils
+{
+
+#ifdef __APPLE__
+typedef int MKL_INT;
+#endif
+
+float calc_distance(float *vec_1, float *vec_2, size_t dim)
+{
+ float dist = 0;
+ for (size_t j = 0; j < dim; j++)
+ {
+ dist += (vec_1[j] - vec_2[j]) * (vec_1[j] - vec_2[j]);
+ }
+ return dist;
+}
+
+// compute l2-squared norms of data stored in row major num_points * dim,
+// needs
+// to be pre-allocated
+void compute_vecs_l2sq(float *vecs_l2sq, float *data, const size_t num_points, const size_t dim)
+{
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t n_iter = 0; n_iter < (int64_t)num_points; n_iter++)
+ {
+ vecs_l2sq[n_iter] = cblas_snrm2((MKL_INT)dim, (data + (n_iter * dim)), 1);
+ vecs_l2sq[n_iter] *= vecs_l2sq[n_iter];
+ }
+}
+
+void rotate_data_randomly(float *data, size_t num_points, size_t dim, float *rot_mat, float *&new_mat,
+ bool transpose_rot)
+{
+ CBLAS_TRANSPOSE transpose = CblasNoTrans;
+ if (transpose_rot)
+ {
+ diskann::cout << "Transposing rotation matrix.." << std::flush;
+ transpose = CblasTrans;
+ }
+ diskann::cout << "done Rotating data with random matrix.." << std::flush;
+
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, transpose, (MKL_INT)num_points, (MKL_INT)dim, (MKL_INT)dim, 1.0, data,
+ (MKL_INT)dim, rot_mat, (MKL_INT)dim, 0, new_mat, (MKL_INT)dim);
+
+ diskann::cout << "done." << std::endl;
+}
+
+// calculate k closest centers to data of num_points * dim (row major)
+// centers is num_centers * dim (row major)
+// data_l2sq has pre-computed squared norms of data
+// centers_l2sq has pre-computed squared norms of centers
+// pre-allocated center_index will contain id of nearest center
+// pre-allocated dist_matrix shound be num_points * num_centers and contain
+// squared distances
+// Default value of k is 1
+
+// Ideally used only by compute_closest_centers
+void compute_closest_centers_in_block(const float *const data, const size_t num_points, const size_t dim,
+ const float *const centers, const size_t num_centers,
+ const float *const docs_l2sq, const float *const centers_l2sq,
+ uint32_t *center_index, float *const dist_matrix, size_t k)
+{
+ if (k > num_centers)
+ {
+ diskann::cout << "ERROR: k (" << k << ") > num_center(" << num_centers << ")" << std::endl;
+ return;
+ }
+
+ float *ones_a = new float[num_centers];
+ float *ones_b = new float[num_points];
+
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ ones_a[i] = 1.0;
+ }
+ for (size_t i = 0; i < num_points; i++)
+ {
+ ones_b[i] = 1.0;
+ }
+
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, (MKL_INT)num_points, (MKL_INT)num_centers, (MKL_INT)1, 1.0f,
+ docs_l2sq, (MKL_INT)1, ones_a, (MKL_INT)1, 0.0f, dist_matrix, (MKL_INT)num_centers);
+
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, (MKL_INT)num_points, (MKL_INT)num_centers, (MKL_INT)1, 1.0f,
+ ones_b, (MKL_INT)1, centers_l2sq, (MKL_INT)1, 1.0f, dist_matrix, (MKL_INT)num_centers);
+
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, (MKL_INT)num_points, (MKL_INT)num_centers, (MKL_INT)dim, -2.0f,
+ data, (MKL_INT)dim, centers, (MKL_INT)dim, 1.0f, dist_matrix, (MKL_INT)num_centers);
+
+ if (k == 1)
+ {
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t i = 0; i < (int64_t)num_points; i++)
+ {
+ float min = std::numeric_limits<float>::max();
+ float *current = dist_matrix + (i * num_centers);
+ for (size_t j = 0; j < num_centers; j++)
+ {
+ if (current[j] < min)
+ {
+ center_index[i] = (uint32_t)j;
+ min = current[j];
+ }
+ }
+ }
+ }
+ else
+ {
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t i = 0; i < (int64_t)num_points; i++)
+ {
+ std::priority_queue<PivotContainer> top_k_queue;
+ float *current = dist_matrix + (i * num_centers);
+ for (size_t j = 0; j < num_centers; j++)
+ {
+ PivotContainer this_piv(j, current[j]);
+ top_k_queue.push(this_piv);
+ }
+ for (size_t j = 0; j < k; j++)
+ {
+ PivotContainer this_piv = top_k_queue.top();
+ center_index[i * k + j] = (uint32_t)this_piv.piv_id;
+ top_k_queue.pop();
+ }
+ }
+ }
+ delete[] ones_a;
+ delete[] ones_b;
+}
+
+// Given data in num_points * new_dim row major
+// Pivots stored in full_pivot_data as num_centers * new_dim row major
+// Calculate the k closest pivot for each point and store it in vector
+// closest_centers_ivf (row major, num_points*k) (which needs to be allocated
+// outside) Additionally, if inverted index is not null (and pre-allocated),
+// it
+// will return inverted index for each center, assuming each of the inverted
+// indices is an empty vector. Additionally, if pts_norms_squared is not null,
+// then it will assume that point norms are pre-computed and use those values
+
+void compute_closest_centers(float *data, size_t num_points, size_t dim, float *pivot_data, size_t num_centers,
+ size_t k, uint32_t *closest_centers_ivf, std::vector<size_t> *inverted_index,
+ float *pts_norms_squared)
+{
+ if (k > num_centers)
+ {
+ diskann::cout << "ERROR: k (" << k << ") > num_center(" << num_centers << ")" << std::endl;
+ return;
+ }
+
+ bool is_norm_given_for_pts = (pts_norms_squared != NULL);
+
+ float *pivs_norms_squared = new float[num_centers];
+ if (!is_norm_given_for_pts)
+ pts_norms_squared = new float[num_points];
+
+ size_t PAR_BLOCK_SIZE = num_points;
+ size_t N_BLOCKS =
+ (num_points % PAR_BLOCK_SIZE) == 0 ? (num_points / PAR_BLOCK_SIZE) : (num_points / PAR_BLOCK_SIZE) + 1;
+
+ if (!is_norm_given_for_pts)
+ math_utils::compute_vecs_l2sq(pts_norms_squared, data, num_points, dim);
+ math_utils::compute_vecs_l2sq(pivs_norms_squared, pivot_data, num_centers, dim);
+ uint32_t *closest_centers = new uint32_t[PAR_BLOCK_SIZE * k];
+ float *distance_matrix = new float[num_centers * PAR_BLOCK_SIZE];
+
+ for (size_t cur_blk = 0; cur_blk < N_BLOCKS; cur_blk++)
+ {
+ float *data_cur_blk = data + cur_blk * PAR_BLOCK_SIZE * dim;
+ size_t num_pts_blk = std::min(PAR_BLOCK_SIZE, num_points - cur_blk * PAR_BLOCK_SIZE);
+ float *pts_norms_blk = pts_norms_squared + cur_blk * PAR_BLOCK_SIZE;
+
+ math_utils::compute_closest_centers_in_block(data_cur_blk, num_pts_blk, dim, pivot_data, num_centers,
+ pts_norms_blk, pivs_norms_squared, closest_centers,
+ distance_matrix, k);
+
+#pragma omp parallel for schedule(static, 1)
+ for (int64_t j = cur_blk * PAR_BLOCK_SIZE;
+ j < std::min((int64_t)num_points, (int64_t)((cur_blk + 1) * PAR_BLOCK_SIZE)); j++)
+ {
+ for (size_t l = 0; l < k; l++)
+ {
+ size_t this_center_id = closest_centers[(j - cur_blk * PAR_BLOCK_SIZE) * k + l];
+ closest_centers_ivf[j * k + l] = (uint32_t)this_center_id;
+ if (inverted_index != NULL)
+ {
+#pragma omp critical
+ inverted_index[this_center_id].push_back(j);
+ }
+ }
+ }
+ }
+ delete[] closest_centers;
+ delete[] distance_matrix;
+ delete[] pivs_norms_squared;
+ if (!is_norm_given_for_pts)
+ delete[] pts_norms_squared;
+}
+
+// if to_subtract is 1, will subtract nearest center from each row. Else will
+// add. Output will be in data_load iself.
+// Nearest centers need to be provided in closst_centers.
+void process_residuals(float *data_load, size_t num_points, size_t dim, float *cur_pivot_data, size_t num_centers,
+ uint32_t *closest_centers, bool to_subtract)
+{
+ diskann::cout << "Processing residuals of " << num_points << " points in " << dim << " dimensions using "
+ << num_centers << " centers " << std::endl;
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t n_iter = 0; n_iter < (int64_t)num_points; n_iter++)
+ {
+ for (size_t d_iter = 0; d_iter < dim; d_iter++)
+ {
+ if (to_subtract == 1)
+ data_load[n_iter * dim + d_iter] =
+ data_load[n_iter * dim + d_iter] - cur_pivot_data[closest_centers[n_iter] * dim + d_iter];
+ else
+ data_load[n_iter * dim + d_iter] =
+ data_load[n_iter * dim + d_iter] + cur_pivot_data[closest_centers[n_iter] * dim + d_iter];
+ }
+ }
+}
+
+} // namespace math_utils
+
+namespace kmeans
+{
+
+// run Lloyds one iteration
+// Given data in row major num_points * dim, and centers in row major
+// num_centers * dim And squared lengths of data points, output the closest
+// center to each data point, update centers, and also return inverted index.
+// If
+// closest_centers == NULL, will allocate memory and return. Similarly, if
+// closest_docs == NULL, will allocate memory and return.
+
+float lloyds_iter(float *data, size_t num_points, size_t dim, float *centers, size_t num_centers, float *docs_l2sq,
+ std::vector<size_t> *closest_docs, uint32_t *&closest_center)
+{
+ bool compute_residual = true;
+ // Timer timer;
+
+ if (closest_center == NULL)
+ closest_center = new uint32_t[num_points];
+ if (closest_docs == NULL)
+ closest_docs = new std::vector<size_t>[num_centers];
+ else
+ for (size_t c = 0; c < num_centers; ++c)
+ closest_docs[c].clear();
+
+ math_utils::compute_closest_centers(data, num_points, dim, centers, num_centers, 1, closest_center, closest_docs,
+ docs_l2sq);
+
+ memset(centers, 0, sizeof(float) * (size_t)num_centers * (size_t)dim);
+
+#pragma omp parallel for schedule(static, 1)
+ for (int64_t c = 0; c < (int64_t)num_centers; ++c)
+ {
+ float *center = centers + (size_t)c * (size_t)dim;
+ double *cluster_sum = new double[dim];
+ for (size_t i = 0; i < dim; i++)
+ cluster_sum[i] = 0.0;
+ for (size_t i = 0; i < closest_docs[c].size(); i++)
+ {
+ float *current = data + ((closest_docs[c][i]) * dim);
+ for (size_t j = 0; j < dim; j++)
+ {
+ cluster_sum[j] += (double)current[j];
+ }
+ }
+ if (closest_docs[c].size() > 0)
+ {
+ for (size_t i = 0; i < dim; i++)
+ center[i] = (float)(cluster_sum[i] / ((double)closest_docs[c].size()));
+ }
+ delete[] cluster_sum;
+ }
+
+ float residual = 0.0;
+ if (compute_residual)
+ {
+ size_t BUF_PAD = 32;
+ size_t CHUNK_SIZE = 2 * 8192;
+ size_t nchunks = num_points / CHUNK_SIZE + (num_points % CHUNK_SIZE == 0 ? 0 : 1);
+ std::vector<float> residuals(nchunks * BUF_PAD, 0.0);
+
+#pragma omp parallel for schedule(static, 32)
+ for (int64_t chunk = 0; chunk < (int64_t)nchunks; ++chunk)
+ for (size_t d = chunk * CHUNK_SIZE; d < num_points && d < (chunk + 1) * CHUNK_SIZE; ++d)
+ residuals[chunk * BUF_PAD] +=
+ math_utils::calc_distance(data + (d * dim), centers + (size_t)closest_center[d] * (size_t)dim, dim);
+
+ for (size_t chunk = 0; chunk < nchunks; ++chunk)
+ residual += residuals[chunk * BUF_PAD];
+ }
+
+ return residual;
+}
+
+// Run Lloyds until max_reps or stopping criterion
+// If you pass NULL for closest_docs and closest_center, it will NOT return
+// the
+// results, else it will assume appriate allocation as closest_docs = new
+// vector<size_t> [num_centers], and closest_center = new size_t[num_points]
+// Final centers are output in centers as row major num_centers * dim
+//
+float run_lloyds(float *data, size_t num_points, size_t dim, float *centers, const size_t num_centers,
+ const size_t max_reps, std::vector<size_t> *closest_docs, uint32_t *closest_center)
+{
+ float residual = std::numeric_limits<float>::max();
+ bool ret_closest_docs = true;
+ bool ret_closest_center = true;
+ if (closest_docs == NULL)
+ {
+ closest_docs = new std::vector<size_t>[num_centers];
+ ret_closest_docs = false;
+ }
+ if (closest_center == NULL)
+ {
+ closest_center = new uint32_t[num_points];
+ ret_closest_center = false;
+ }
+
+ float *docs_l2sq = new float[num_points];
+ math_utils::compute_vecs_l2sq(docs_l2sq, data, num_points, dim);
+
+ float old_residual;
+ // Timer timer;
+ for (size_t i = 0; i < max_reps; ++i)
+ {
+ old_residual = residual;
+
+ residual = lloyds_iter(data, num_points, dim, centers, num_centers, docs_l2sq, closest_docs, closest_center);
+
+ if (((i != 0) && ((old_residual - residual) / residual) < 0.00001) ||
+ (residual < std::numeric_limits<float>::epsilon()))
+ {
+ diskann::cout << "Residuals unchanged: " << old_residual << " becomes " << residual
+ << ". Early termination." << std::endl;
+ break;
+ }
+ }
+ delete[] docs_l2sq;
+ if (!ret_closest_docs)
+ delete[] closest_docs;
+ if (!ret_closest_center)
+ delete[] closest_center;
+ return residual;
+}
+
+// assumes memory allocated for pivot_data as new
+// float[num_centers*dim]
+// and select randomly num_centers points as pivots
+void selecting_pivots(float *data, size_t num_points, size_t dim, float *pivot_data, size_t num_centers)
+{
+ // pivot_data = new float[num_centers * dim];
+
+ std::vector<size_t> picked;
+ std::random_device rd;
+ auto x = rd();
+ std::mt19937 generator(x);
+ std::uniform_int_distribution<size_t> distribution(0, num_points - 1);
+
+ size_t tmp_pivot;
+ for (size_t j = 0; j < num_centers; j++)
+ {
+ tmp_pivot = distribution(generator);
+ if (std::find(picked.begin(), picked.end(), tmp_pivot) != picked.end())
+ continue;
+ picked.push_back(tmp_pivot);
+ std::memcpy(pivot_data + j * dim, data + tmp_pivot * dim, dim * sizeof(float));
+ }
+}
+
+void kmeanspp_selecting_pivots(float *data, size_t num_points, size_t dim, float *pivot_data, size_t num_centers)
+{
+ if (num_points > 1 << 23)
+ {
+ diskann::cout << "ERROR: n_pts " << num_points
+ << " currently not supported for k-means++, maximum is "
+ "8388608. Falling back to random pivot "
+ "selection."
+ << std::endl;
+ selecting_pivots(data, num_points, dim, pivot_data, num_centers);
+ return;
+ }
+
+ std::vector<size_t> picked;
+ std::random_device rd;
+ auto x = rd();
+ std::mt19937 generator(x);
+ std::uniform_real_distribution<> distribution(0, 1);
+ std::uniform_int_distribution<size_t> int_dist(0, num_points - 1);
+ size_t init_id = int_dist(generator);
+ size_t num_picked = 1;
+
+ picked.push_back(init_id);
+ std::memcpy(pivot_data, data + init_id * dim, dim * sizeof(float));
+
+ float *dist = new float[num_points];
+
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t i = 0; i < (int64_t)num_points; i++)
+ {
+ dist[i] = math_utils::calc_distance(data + i * dim, data + init_id * dim, dim);
+ }
+
+ double dart_val;
+ size_t tmp_pivot;
+ bool sum_flag = false;
+
+ while (num_picked < num_centers)
+ {
+ dart_val = distribution(generator);
+
+ double sum = 0;
+ for (size_t i = 0; i < num_points; i++)
+ {
+ sum = sum + dist[i];
+ }
+ if (sum == 0)
+ sum_flag = true;
+
+ dart_val *= sum;
+
+ double prefix_sum = 0;
+ for (size_t i = 0; i < (num_points); i++)
+ {
+ tmp_pivot = i;
+ if (dart_val >= prefix_sum && dart_val < prefix_sum + dist[i])
+ {
+ break;
+ }
+
+ prefix_sum += dist[i];
+ }
+
+ if (std::find(picked.begin(), picked.end(), tmp_pivot) != picked.end() && (sum_flag == false))
+ continue;
+ picked.push_back(tmp_pivot);
+ std::memcpy(pivot_data + num_picked * dim, data + tmp_pivot * dim, dim * sizeof(float));
+
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t i = 0; i < (int64_t)num_points; i++)
+ {
+ dist[i] = (std::min)(dist[i], math_utils::calc_distance(data + i * dim, data + tmp_pivot * dim, dim));
+ }
+ num_picked++;
+ }
+ delete[] dist;
+}
+
+} // namespace kmeans
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/memory_mapper.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/memory_mapper.cpp
new file mode 100644
index 0000000..d1c5ef9
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/memory_mapper.cpp
@@ -0,0 +1,107 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "logger.h"
+#include "memory_mapper.h"
+#include <iostream>
+#include <sstream>
+
+using namespace diskann;
+
+MemoryMapper::MemoryMapper(const std::string &filename) : MemoryMapper(filename.c_str())
+{
+}
+
+MemoryMapper::MemoryMapper(const char *filename)
+{
+#ifndef _WINDOWS
+ _fd = open(filename, O_RDONLY);
+ if (_fd <= 0)
+ {
+ std::cerr << "Inner vertices file not found" << std::endl;
+ return;
+ }
+ struct stat sb;
+ if (fstat(_fd, &sb) != 0)
+ {
+ std::cerr << "Inner vertices file not dound. " << std::endl;
+ return;
+ }
+ _fileSize = sb.st_size;
+ diskann::cout << "File Size: " << _fileSize << std::endl;
+ _buf = (char *)mmap(NULL, _fileSize, PROT_READ, MAP_PRIVATE, _fd, 0);
+#else
+ _bareFile =
+ CreateFileA(filename, GENERIC_READ | GENERIC_EXECUTE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (_bareFile == nullptr)
+ {
+ std::ostringstream message;
+ message << "CreateFileA(" << filename << ") failed with error " << GetLastError() << std::endl;
+ std::cerr << message.str();
+ throw std::exception(message.str().c_str());
+ }
+
+ _fd = CreateFileMapping(_bareFile, NULL, PAGE_EXECUTE_READ, 0, 0, NULL);
+ if (_fd == nullptr)
+ {
+ std::ostringstream message;
+ message << "CreateFileMapping(" << filename << ") failed with error " << GetLastError() << std::endl;
+ std::cerr << message.str() << std::endl;
+ throw std::exception(message.str().c_str());
+ }
+
+ _buf = (char *)MapViewOfFile(_fd, FILE_MAP_READ, 0, 0, 0);
+ if (_buf == nullptr)
+ {
+ std::ostringstream message;
+ message << "MapViewOfFile(" << filename << ") failed with error: " << GetLastError() << std::endl;
+ std::cerr << message.str() << std::endl;
+ throw std::exception(message.str().c_str());
+ }
+
+ LARGE_INTEGER fSize;
+ if (TRUE == GetFileSizeEx(_bareFile, &fSize))
+ {
+ _fileSize = fSize.QuadPart; // take the 64-bit value
+ diskann::cout << "File Size: " << _fileSize << std::endl;
+ }
+ else
+ {
+ std::cerr << "Failed to get size of file " << filename << std::endl;
+ }
+#endif
+}
+char *MemoryMapper::getBuf()
+{
+ return _buf;
+}
+
+size_t MemoryMapper::getFileSize()
+{
+ return _fileSize;
+}
+
+MemoryMapper::~MemoryMapper()
+{
+#ifndef _WINDOWS
+ if (munmap(_buf, _fileSize) != 0)
+ std::cerr << "ERROR unmapping. CHECK!" << std::endl;
+ close(_fd);
+#else
+ if (FALSE == UnmapViewOfFile(_buf))
+ {
+ std::cerr << "Unmap view of file failed. Error: " << GetLastError() << std::endl;
+ }
+
+ if (FALSE == CloseHandle(_fd))
+ {
+ std::cerr << "Failed to close memory mapped file. Error: " << GetLastError() << std::endl;
+ }
+
+ if (FALSE == CloseHandle(_bareFile))
+ {
+ std::cerr << "Failed to close file: " << _fileName << " Error: " << GetLastError() << std::endl;
+ }
+
+#endif
+}
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/natural_number_map.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/natural_number_map.cpp
new file mode 100644
index 0000000..a996dcf
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/natural_number_map.cpp
@@ -0,0 +1,116 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <assert.h>
+#include <boost/dynamic_bitset.hpp>
+
+#include "natural_number_map.h"
+#include "tag_uint128.h"
+
+namespace diskann
+{
+static constexpr auto invalid_position = boost::dynamic_bitset<>::npos;
+
+template <typename Key, typename Value>
+natural_number_map<Key, Value>::natural_number_map()
+ : _size(0), _values_bitset(std::make_unique<boost::dynamic_bitset<>>())
+{
+}
+
+template <typename Key, typename Value> void natural_number_map<Key, Value>::reserve(size_t count)
+{
+ _values_vector.reserve(count);
+ _values_bitset->reserve(count);
+}
+
+template <typename Key, typename Value> size_t natural_number_map<Key, Value>::size() const
+{
+ return _size;
+}
+
+template <typename Key, typename Value> void natural_number_map<Key, Value>::set(Key key, Value value)
+{
+ if (key >= _values_bitset->size())
+ {
+ _values_bitset->resize(static_cast<size_t>(key) + 1);
+ _values_vector.resize(_values_bitset->size());
+ }
+
+ _values_vector[key] = value;
+ const bool was_present = _values_bitset->test_set(key, true);
+
+ if (!was_present)
+ {
+ ++_size;
+ }
+}
+
+template <typename Key, typename Value> void natural_number_map<Key, Value>::erase(Key key)
+{
+ if (key < _values_bitset->size())
+ {
+ const bool was_present = _values_bitset->test_set(key, false);
+
+ if (was_present)
+ {
+ --_size;
+ }
+ }
+}
+
+template <typename Key, typename Value> bool natural_number_map<Key, Value>::contains(Key key) const
+{
+ return key < _values_bitset->size() && _values_bitset->test(key);
+}
+
+template <typename Key, typename Value> bool natural_number_map<Key, Value>::try_get(Key key, Value &value) const
+{
+ if (!contains(key))
+ {
+ return false;
+ }
+
+ value = _values_vector[key];
+ return true;
+}
+
+template <typename Key, typename Value>
+typename natural_number_map<Key, Value>::position natural_number_map<Key, Value>::find_first() const
+{
+ return position{_size > 0 ? _values_bitset->find_first() : invalid_position, 0};
+}
+
+template <typename Key, typename Value>
+typename natural_number_map<Key, Value>::position natural_number_map<Key, Value>::find_next(
+ const position &after_position) const
+{
+ return position{after_position._keys_already_enumerated < _size ? _values_bitset->find_next(after_position._key)
+ : invalid_position,
+ after_position._keys_already_enumerated + 1};
+}
+
+template <typename Key, typename Value> bool natural_number_map<Key, Value>::position::is_valid() const
+{
+ return _key != invalid_position;
+}
+
+template <typename Key, typename Value> Value natural_number_map<Key, Value>::get(const position &pos) const
+{
+ assert(pos.is_valid());
+ return _values_vector[pos._key];
+}
+
+template <typename Key, typename Value> void natural_number_map<Key, Value>::clear()
+{
+ _size = 0;
+ _values_vector.clear();
+ _values_bitset->clear();
+}
+
+// Instantiate used templates.
+template class natural_number_map<uint32_t, int32_t>;
+template class natural_number_map<uint32_t, uint32_t>;
+template class natural_number_map<uint32_t, int64_t>;
+template class natural_number_map<uint32_t, uint64_t>;
+template class natural_number_map<uint32_t, tag_uint128>;
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/natural_number_set.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/natural_number_set.cpp
new file mode 100644
index 0000000..b36cb52
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/natural_number_set.cpp
@@ -0,0 +1,70 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <boost/dynamic_bitset.hpp>
+
+#include "ann_exception.h"
+#include "natural_number_set.h"
+
+namespace diskann
+{
+template <typename T>
+natural_number_set<T>::natural_number_set() : _values_bitset(std::make_unique<boost::dynamic_bitset<>>())
+{
+}
+
+template <typename T> bool natural_number_set<T>::is_empty() const
+{
+ return _values_vector.empty();
+}
+
+template <typename T> void natural_number_set<T>::reserve(size_t count)
+{
+ _values_vector.reserve(count);
+ _values_bitset->reserve(count);
+}
+
+template <typename T> void natural_number_set<T>::insert(T id)
+{
+ _values_vector.emplace_back(id);
+
+ if (id >= _values_bitset->size())
+ _values_bitset->resize(static_cast<size_t>(id) + 1);
+
+ _values_bitset->set(id, true);
+}
+
+template <typename T> T natural_number_set<T>::pop_any()
+{
+ if (_values_vector.empty())
+ {
+ throw diskann::ANNException("No values available", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ const T id = _values_vector.back();
+ _values_vector.pop_back();
+
+ _values_bitset->set(id, false);
+
+ return id;
+}
+
+template <typename T> void natural_number_set<T>::clear()
+{
+ _values_vector.clear();
+ _values_bitset->clear();
+}
+
+template <typename T> size_t natural_number_set<T>::size() const
+{
+ return _values_vector.size();
+}
+
+template <typename T> bool natural_number_set<T>::is_in_set(T id) const
+{
+ return _values_bitset->test(id);
+}
+
+// Instantiate used templates.
+template class natural_number_set<unsigned>;
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/partition.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/partition.cpp
new file mode 100644
index 0000000..7e100ad
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/partition.cpp
@@ -0,0 +1,657 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <cmath>
+#include <cstdio>
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#include <omp.h>
+#include "tsl/robin_map.h"
+#include "tsl/robin_set.h"
+
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+#include "gperftools/malloc_extension.h"
+#endif
+
+#include "utils.h"
+#include "math_utils.h"
+#include "index.h"
+#include "parameters.h"
+#include "memory_mapper.h"
+#include "partition.h"
+#ifdef _WINDOWS
+#include <xmmintrin.h>
+#endif
+
+// block size for reading/ processing large files and matrices in blocks
+#define BLOCK_SIZE 5000000
+
+// #define SAVE_INFLATED_PQ true
+
+template <typename T>
+void gen_random_slice(const std::string base_file, const std::string output_prefix, double sampling_rate)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream base_reader(base_file.c_str(), read_blk_size);
+ std::ofstream sample_writer(std::string(output_prefix + "_data.bin").c_str(), std::ios::binary);
+ std::ofstream sample_id_writer(std::string(output_prefix + "_ids.bin").c_str(), std::ios::binary);
+
+ std::random_device rd; // Will be used to obtain a seed for the random number engine
+ auto x = rd();
+ std::mt19937 generator(x); // Standard mersenne_twister_engine seeded with rd()
+ std::uniform_real_distribution<float> distribution(0, 1);
+
+ size_t npts, nd;
+ uint32_t npts_u32, nd_u32;
+ uint32_t num_sampled_pts_u32 = 0;
+ uint32_t one_const = 1;
+
+ base_reader.read((char *)&npts_u32, sizeof(uint32_t));
+ base_reader.read((char *)&nd_u32, sizeof(uint32_t));
+ diskann::cout << "Loading base " << base_file << ". #points: " << npts_u32 << ". #dim: " << nd_u32 << "."
+ << std::endl;
+ sample_writer.write((char *)&num_sampled_pts_u32, sizeof(uint32_t));
+ sample_writer.write((char *)&nd_u32, sizeof(uint32_t));
+ sample_id_writer.write((char *)&num_sampled_pts_u32, sizeof(uint32_t));
+ sample_id_writer.write((char *)&one_const, sizeof(uint32_t));
+
+ npts = npts_u32;
+ nd = nd_u32;
+ std::unique_ptr<T[]> cur_row = std::make_unique<T[]>(nd);
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ base_reader.read((char *)cur_row.get(), sizeof(T) * nd);
+ float sample = distribution(generator);
+ if (sample < sampling_rate)
+ {
+ sample_writer.write((char *)cur_row.get(), sizeof(T) * nd);
+ uint32_t cur_i_u32 = (uint32_t)i;
+ sample_id_writer.write((char *)&cur_i_u32, sizeof(uint32_t));
+ num_sampled_pts_u32++;
+ }
+ }
+ sample_writer.seekp(0, std::ios::beg);
+ sample_writer.write((char *)&num_sampled_pts_u32, sizeof(uint32_t));
+ sample_id_writer.seekp(0, std::ios::beg);
+ sample_id_writer.write((char *)&num_sampled_pts_u32, sizeof(uint32_t));
+ sample_writer.close();
+ sample_id_writer.close();
+ diskann::cout << "Wrote " << num_sampled_pts_u32 << " points to sample file: " << output_prefix + "_data.bin"
+ << std::endl;
+}
+
+// streams data from the file, and samples each vector with probability p_val
+// and returns a matrix of size slice_size* ndims as floating point type.
+// the slice_size and ndims are set inside the function.
+
+/***********************************
+ * Reimplement using gen_random_slice(const T* inputdata,...)
+ ************************************/
+
+template <typename T>
+void gen_random_slice(const std::string data_file, double p_val, float *&sampled_data, size_t &slice_size,
+ size_t &ndims)
+{
+ size_t npts;
+ uint32_t npts32, ndims32;
+ std::vector<std::vector<float>> sampled_vectors;
+
+ // amount to read in one shot
+ size_t read_blk_size = 64 * 1024 * 1024;
+ // create cached reader + writer
+ cached_ifstream base_reader(data_file.c_str(), read_blk_size);
+
+ // metadata: npts, ndims
+ base_reader.read((char *)&npts32, sizeof(uint32_t));
+ base_reader.read((char *)&ndims32, sizeof(uint32_t));
+ npts = npts32;
+ ndims = ndims32;
+
+ std::unique_ptr<T[]> cur_vector_T = std::make_unique<T[]>(ndims);
+ p_val = p_val < 1 ? p_val : 1;
+
+ std::random_device rd; // Will be used to obtain a seed for the random number
+ size_t x = rd();
+ std::mt19937 generator((uint32_t)x);
+ std::uniform_real_distribution<float> distribution(0, 1);
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ base_reader.read((char *)cur_vector_T.get(), ndims * sizeof(T));
+ float rnd_val = distribution(generator);
+ if (rnd_val < p_val)
+ {
+ std::vector<float> cur_vector_float;
+ for (size_t d = 0; d < ndims; d++)
+ cur_vector_float.push_back(cur_vector_T[d]);
+ sampled_vectors.push_back(cur_vector_float);
+ }
+ }
+ slice_size = sampled_vectors.size();
+ sampled_data = new float[slice_size * ndims];
+ for (size_t i = 0; i < slice_size; i++)
+ {
+ for (size_t j = 0; j < ndims; j++)
+ {
+ sampled_data[i * ndims + j] = sampled_vectors[i][j];
+ }
+ }
+}
+
+// same as above, but samples from the matrix inputdata instead of a file of
+// npts*ndims to return sampled_data of size slice_size*ndims.
+template <typename T>
+void gen_random_slice(const T *inputdata, size_t npts, size_t ndims, double p_val, float *&sampled_data,
+ size_t &slice_size)
+{
+ std::vector<std::vector<float>> sampled_vectors;
+ const T *cur_vector_T;
+
+ p_val = p_val < 1 ? p_val : 1;
+
+ std::random_device rd; // Will be used to obtain a seed for the random number engine
+ size_t x = rd();
+ std::mt19937 generator((uint32_t)x); // Standard mersenne_twister_engine seeded with rd()
+ std::uniform_real_distribution<float> distribution(0, 1);
+
+ for (size_t i = 0; i < npts; i++)
+ {
+ cur_vector_T = inputdata + ndims * i;
+ float rnd_val = distribution(generator);
+ if (rnd_val < p_val)
+ {
+ std::vector<float> cur_vector_float;
+ for (size_t d = 0; d < ndims; d++)
+ cur_vector_float.push_back(cur_vector_T[d]);
+ sampled_vectors.push_back(cur_vector_float);
+ }
+ }
+ slice_size = sampled_vectors.size();
+ sampled_data = new float[slice_size * ndims];
+ for (size_t i = 0; i < slice_size; i++)
+ {
+ for (size_t j = 0; j < ndims; j++)
+ {
+ sampled_data[i * ndims + j] = sampled_vectors[i][j];
+ }
+ }
+}
+
+int estimate_cluster_sizes(float *test_data_float, size_t num_test, float *pivots, const size_t num_centers,
+ const size_t test_dim, const size_t k_base, std::vector<size_t> &cluster_sizes)
+{
+ cluster_sizes.clear();
+
+ size_t *shard_counts = new size_t[num_centers];
+
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ shard_counts[i] = 0;
+ }
+
+ size_t block_size = num_test <= BLOCK_SIZE ? num_test : BLOCK_SIZE;
+ uint32_t *block_closest_centers = new uint32_t[block_size * k_base];
+ float *block_data_float;
+
+ size_t num_blocks = DIV_ROUND_UP(num_test, block_size);
+
+ for (size_t block = 0; block < num_blocks; block++)
+ {
+ size_t start_id = block * block_size;
+ size_t end_id = (std::min)((block + 1) * block_size, num_test);
+ size_t cur_blk_size = end_id - start_id;
+
+ block_data_float = test_data_float + start_id * test_dim;
+
+ math_utils::compute_closest_centers(block_data_float, cur_blk_size, test_dim, pivots, num_centers, k_base,
+ block_closest_centers);
+
+ for (size_t p = 0; p < cur_blk_size; p++)
+ {
+ for (size_t p1 = 0; p1 < k_base; p1++)
+ {
+ size_t shard_id = block_closest_centers[p * k_base + p1];
+ shard_counts[shard_id]++;
+ }
+ }
+ }
+
+ diskann::cout << "Estimated cluster sizes: ";
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ uint32_t cur_shard_count = (uint32_t)shard_counts[i];
+ cluster_sizes.push_back((size_t)cur_shard_count);
+ diskann::cout << cur_shard_count << " ";
+ }
+ diskann::cout << std::endl;
+ delete[] shard_counts;
+ delete[] block_closest_centers;
+ return 0;
+}
+
+template <typename T>
+int shard_data_into_clusters(const std::string data_file, float *pivots, const size_t num_centers, const size_t dim,
+ const size_t k_base, std::string prefix_path)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ // uint64_t write_blk_size = 64 * 1024 * 1024;
+ // create cached reader + writer
+ cached_ifstream base_reader(data_file, read_blk_size);
+ uint32_t npts32;
+ uint32_t basedim32;
+ base_reader.read((char *)&npts32, sizeof(uint32_t));
+ base_reader.read((char *)&basedim32, sizeof(uint32_t));
+ size_t num_points = npts32;
+ if (basedim32 != dim)
+ {
+ diskann::cout << "Error. dimensions dont match for train set and base set" << std::endl;
+ return -1;
+ }
+
+ std::unique_ptr<size_t[]> shard_counts = std::make_unique<size_t[]>(num_centers);
+ std::vector<std::ofstream> shard_data_writer(num_centers);
+ std::vector<std::ofstream> shard_idmap_writer(num_centers);
+ uint32_t dummy_size = 0;
+ uint32_t const_one = 1;
+
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ std::string data_filename = prefix_path + "_subshard-" + std::to_string(i) + ".bin";
+ std::string idmap_filename = prefix_path + "_subshard-" + std::to_string(i) + "_ids_uint32.bin";
+ shard_data_writer[i] = std::ofstream(data_filename.c_str(), std::ios::binary);
+ shard_idmap_writer[i] = std::ofstream(idmap_filename.c_str(), std::ios::binary);
+ shard_data_writer[i].write((char *)&dummy_size, sizeof(uint32_t));
+ shard_data_writer[i].write((char *)&basedim32, sizeof(uint32_t));
+ shard_idmap_writer[i].write((char *)&dummy_size, sizeof(uint32_t));
+ shard_idmap_writer[i].write((char *)&const_one, sizeof(uint32_t));
+ shard_counts[i] = 0;
+ }
+
+ size_t block_size = num_points <= BLOCK_SIZE ? num_points : BLOCK_SIZE;
+ std::unique_ptr<uint32_t[]> block_closest_centers = std::make_unique<uint32_t[]>(block_size * k_base);
+ std::unique_ptr<T[]> block_data_T = std::make_unique<T[]>(block_size * dim);
+ std::unique_ptr<float[]> block_data_float = std::make_unique<float[]>(block_size * dim);
+
+ size_t num_blocks = DIV_ROUND_UP(num_points, block_size);
+
+ for (size_t block = 0; block < num_blocks; block++)
+ {
+ size_t start_id = block * block_size;
+ size_t end_id = (std::min)((block + 1) * block_size, num_points);
+ size_t cur_blk_size = end_id - start_id;
+
+ base_reader.read((char *)block_data_T.get(), sizeof(T) * (cur_blk_size * dim));
+ diskann::convert_types<T, float>(block_data_T.get(), block_data_float.get(), cur_blk_size, dim);
+
+ math_utils::compute_closest_centers(block_data_float.get(), cur_blk_size, dim, pivots, num_centers, k_base,
+ block_closest_centers.get());
+
+ for (size_t p = 0; p < cur_blk_size; p++)
+ {
+ for (size_t p1 = 0; p1 < k_base; p1++)
+ {
+ size_t shard_id = block_closest_centers[p * k_base + p1];
+ uint32_t original_point_map_id = (uint32_t)(start_id + p);
+ shard_data_writer[shard_id].write((char *)(block_data_T.get() + p * dim), sizeof(T) * dim);
+ shard_idmap_writer[shard_id].write((char *)&original_point_map_id, sizeof(uint32_t));
+ shard_counts[shard_id]++;
+ }
+ }
+ }
+
+ size_t total_count = 0;
+ diskann::cout << "Actual shard sizes: " << std::flush;
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ uint32_t cur_shard_count = (uint32_t)shard_counts[i];
+ total_count += cur_shard_count;
+ diskann::cout << cur_shard_count << " ";
+ shard_data_writer[i].seekp(0);
+ shard_data_writer[i].write((char *)&cur_shard_count, sizeof(uint32_t));
+ shard_data_writer[i].close();
+ shard_idmap_writer[i].seekp(0);
+ shard_idmap_writer[i].write((char *)&cur_shard_count, sizeof(uint32_t));
+ shard_idmap_writer[i].close();
+ }
+
+ diskann::cout << "\n Partitioned " << num_points << " with replication factor " << k_base << " to get "
+ << total_count << " points across " << num_centers << " shards " << std::endl;
+ return 0;
+}
+
+// useful for partitioning large dataset. we first generate only the IDS for
+// each shard, and retrieve the actual vectors on demand.
+template <typename T>
+int shard_data_into_clusters_only_ids(const std::string data_file, float *pivots, const size_t num_centers,
+ const size_t dim, const size_t k_base, std::string prefix_path)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ // uint64_t write_blk_size = 64 * 1024 * 1024;
+ // create cached reader + writer
+ cached_ifstream base_reader(data_file, read_blk_size);
+ uint32_t npts32;
+ uint32_t basedim32;
+ base_reader.read((char *)&npts32, sizeof(uint32_t));
+ base_reader.read((char *)&basedim32, sizeof(uint32_t));
+ size_t num_points = npts32;
+ if (basedim32 != dim)
+ {
+ diskann::cout << "Error. dimensions dont match for train set and base set" << std::endl;
+ return -1;
+ }
+
+ std::unique_ptr<size_t[]> shard_counts = std::make_unique<size_t[]>(num_centers);
+
+ std::vector<std::ofstream> shard_idmap_writer(num_centers);
+ uint32_t dummy_size = 0;
+ uint32_t const_one = 1;
+
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ std::string idmap_filename = prefix_path + "_subshard-" + std::to_string(i) + "_ids_uint32.bin";
+ shard_idmap_writer[i] = std::ofstream(idmap_filename.c_str(), std::ios::binary);
+ shard_idmap_writer[i].write((char *)&dummy_size, sizeof(uint32_t));
+ shard_idmap_writer[i].write((char *)&const_one, sizeof(uint32_t));
+ shard_counts[i] = 0;
+ }
+
+ size_t block_size = num_points <= BLOCK_SIZE ? num_points : BLOCK_SIZE;
+ std::unique_ptr<uint32_t[]> block_closest_centers = std::make_unique<uint32_t[]>(block_size * k_base);
+ std::unique_ptr<T[]> block_data_T = std::make_unique<T[]>(block_size * dim);
+ std::unique_ptr<float[]> block_data_float = std::make_unique<float[]>(block_size * dim);
+
+ size_t num_blocks = DIV_ROUND_UP(num_points, block_size);
+
+ for (size_t block = 0; block < num_blocks; block++)
+ {
+ size_t start_id = block * block_size;
+ size_t end_id = (std::min)((block + 1) * block_size, num_points);
+ size_t cur_blk_size = end_id - start_id;
+
+ base_reader.read((char *)block_data_T.get(), sizeof(T) * (cur_blk_size * dim));
+ diskann::convert_types<T, float>(block_data_T.get(), block_data_float.get(), cur_blk_size, dim);
+
+ math_utils::compute_closest_centers(block_data_float.get(), cur_blk_size, dim, pivots, num_centers, k_base,
+ block_closest_centers.get());
+
+ for (size_t p = 0; p < cur_blk_size; p++)
+ {
+ for (size_t p1 = 0; p1 < k_base; p1++)
+ {
+ size_t shard_id = block_closest_centers[p * k_base + p1];
+ uint32_t original_point_map_id = (uint32_t)(start_id + p);
+ shard_idmap_writer[shard_id].write((char *)&original_point_map_id, sizeof(uint32_t));
+ shard_counts[shard_id]++;
+ }
+ }
+ }
+
+ size_t total_count = 0;
+ diskann::cout << "Actual shard sizes: " << std::flush;
+ for (size_t i = 0; i < num_centers; i++)
+ {
+ uint32_t cur_shard_count = (uint32_t)shard_counts[i];
+ total_count += cur_shard_count;
+ diskann::cout << cur_shard_count << " ";
+ shard_idmap_writer[i].seekp(0);
+ shard_idmap_writer[i].write((char *)&cur_shard_count, sizeof(uint32_t));
+ shard_idmap_writer[i].close();
+ }
+
+ diskann::cout << "\n Partitioned " << num_points << " with replication factor " << k_base << " to get "
+ << total_count << " points across " << num_centers << " shards " << std::endl;
+ return 0;
+}
+
+template <typename T>
+int retrieve_shard_data_from_ids(const std::string data_file, std::string idmap_filename, std::string data_filename)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ // uint64_t write_blk_size = 64 * 1024 * 1024;
+ // create cached reader + writer
+ cached_ifstream base_reader(data_file, read_blk_size);
+ uint32_t npts32;
+ uint32_t basedim32;
+ base_reader.read((char *)&npts32, sizeof(uint32_t));
+ base_reader.read((char *)&basedim32, sizeof(uint32_t));
+ size_t num_points = npts32;
+ size_t dim = basedim32;
+
+ uint32_t dummy_size = 0;
+
+ std::ofstream shard_data_writer(data_filename.c_str(), std::ios::binary);
+ shard_data_writer.write((char *)&dummy_size, sizeof(uint32_t));
+ shard_data_writer.write((char *)&basedim32, sizeof(uint32_t));
+
+ uint32_t *shard_ids;
+ size_t shard_size, tmp;
+ diskann::load_bin<uint32_t>(idmap_filename, shard_ids, shard_size, tmp);
+
+ uint32_t cur_pos = 0;
+ uint32_t num_written = 0;
+ std::cout << "Shard has " << shard_size << " points" << std::endl;
+
+ size_t block_size = num_points <= BLOCK_SIZE ? num_points : BLOCK_SIZE;
+ std::unique_ptr<T[]> block_data_T = std::make_unique<T[]>(block_size * dim);
+
+ size_t num_blocks = DIV_ROUND_UP(num_points, block_size);
+
+ for (size_t block = 0; block < num_blocks; block++)
+ {
+ size_t start_id = block * block_size;
+ size_t end_id = (std::min)((block + 1) * block_size, num_points);
+ size_t cur_blk_size = end_id - start_id;
+
+ base_reader.read((char *)block_data_T.get(), sizeof(T) * (cur_blk_size * dim));
+
+ for (size_t p = 0; p < cur_blk_size; p++)
+ {
+ uint32_t original_point_map_id = (uint32_t)(start_id + p);
+ if (cur_pos == shard_size)
+ break;
+ if (original_point_map_id == shard_ids[cur_pos])
+ {
+ cur_pos++;
+ shard_data_writer.write((char *)(block_data_T.get() + p * dim), sizeof(T) * dim);
+ num_written++;
+ }
+ }
+ if (cur_pos == shard_size)
+ break;
+ }
+
+ diskann::cout << "Written file with " << num_written << " points" << std::endl;
+
+ shard_data_writer.seekp(0);
+ shard_data_writer.write((char *)&num_written, sizeof(uint32_t));
+ shard_data_writer.close();
+ delete[] shard_ids;
+ return 0;
+}
+
+// partitions a large base file into many shards using k-means hueristic
+// on a random sample generated using sampling_rate probability. After this, it
+// assignes each base point to the closest k_base nearest centers and creates
+// the shards.
+// The total number of points across all shards will be k_base * num_points.
+
+template <typename T>
+int partition(const std::string data_file, const float sampling_rate, size_t num_parts, size_t max_k_means_reps,
+ const std::string prefix_path, size_t k_base)
+{
+ size_t train_dim;
+ size_t num_train;
+ float *train_data_float;
+
+ gen_random_slice<T>(data_file, sampling_rate, train_data_float, num_train, train_dim);
+
+ float *pivot_data;
+
+ std::string cur_file = std::string(prefix_path);
+ std::string output_file;
+
+ // kmeans_partitioning on training data
+
+ // cur_file = cur_file + "_kmeans_partitioning-" +
+ // std::to_string(num_parts);
+ output_file = cur_file + "_centroids.bin";
+
+ pivot_data = new float[num_parts * train_dim];
+
+ // Process Global k-means for kmeans_partitioning Step
+ diskann::cout << "Processing global k-means (kmeans_partitioning Step)" << std::endl;
+ kmeans::kmeanspp_selecting_pivots(train_data_float, num_train, train_dim, pivot_data, num_parts);
+
+ kmeans::run_lloyds(train_data_float, num_train, train_dim, pivot_data, num_parts, max_k_means_reps, NULL, NULL);
+
+ diskann::cout << "Saving global k-center pivots" << std::endl;
+ diskann::save_bin<float>(output_file.c_str(), pivot_data, (size_t)num_parts, train_dim);
+
+ // now pivots are ready. need to stream base points and assign them to
+ // closest clusters.
+
+ shard_data_into_clusters<T>(data_file, pivot_data, num_parts, train_dim, k_base, prefix_path);
+ delete[] pivot_data;
+ delete[] train_data_float;
+ return 0;
+}
+
+template <typename T>
+int partition_with_ram_budget(const std::string data_file, const double sampling_rate, double ram_budget,
+ size_t graph_degree, const std::string prefix_path, size_t k_base)
+{
+ size_t train_dim;
+ size_t num_train;
+ float *train_data_float;
+ size_t max_k_means_reps = 10;
+
+ int num_parts = 3;
+ bool fit_in_ram = false;
+
+ gen_random_slice<T>(data_file, sampling_rate, train_data_float, num_train, train_dim);
+
+ size_t test_dim;
+ size_t num_test;
+ float *test_data_float;
+ gen_random_slice<T>(data_file, sampling_rate, test_data_float, num_test, test_dim);
+
+ float *pivot_data = nullptr;
+
+ std::string cur_file = std::string(prefix_path);
+ std::string output_file;
+
+ // kmeans_partitioning on training data
+
+ // cur_file = cur_file + "_kmeans_partitioning-" +
+ // std::to_string(num_parts);
+ output_file = cur_file + "_centroids.bin";
+
+ while (!fit_in_ram)
+ {
+ fit_in_ram = true;
+
+ double max_ram_usage = 0;
+ if (pivot_data != nullptr)
+ delete[] pivot_data;
+
+ pivot_data = new float[num_parts * train_dim];
+ // Process Global k-means for kmeans_partitioning Step
+ diskann::cout << "Processing global k-means (kmeans_partitioning Step)" << std::endl;
+ kmeans::kmeanspp_selecting_pivots(train_data_float, num_train, train_dim, pivot_data, num_parts);
+
+ kmeans::run_lloyds(train_data_float, num_train, train_dim, pivot_data, num_parts, max_k_means_reps, NULL, NULL);
+
+ // now pivots are ready. need to stream base points and assign them to
+ // closest clusters.
+
+ std::vector<size_t> cluster_sizes;
+ estimate_cluster_sizes(test_data_float, num_test, pivot_data, num_parts, train_dim, k_base, cluster_sizes);
+
+ for (auto &p : cluster_sizes)
+ {
+ // to account for the fact that p is the size of the shard over the
+ // testing sample.
+ p = (uint64_t)(p / sampling_rate);
+ double cur_shard_ram_estimate =
+ diskann::estimate_ram_usage(p, (uint32_t)train_dim, sizeof(T), (uint32_t)graph_degree);
+
+ if (cur_shard_ram_estimate > max_ram_usage)
+ max_ram_usage = cur_shard_ram_estimate;
+ }
+ diskann::cout << "With " << num_parts
+ << " parts, max estimated RAM usage: " << max_ram_usage / (1024 * 1024 * 1024)
+ << "GB, budget given is " << ram_budget << std::endl;
+ if (max_ram_usage > 1024 * 1024 * 1024 * ram_budget)
+ {
+ fit_in_ram = false;
+ num_parts += 2;
+ }
+ }
+
+ diskann::cout << "Saving global k-center pivots" << std::endl;
+ diskann::save_bin<float>(output_file.c_str(), pivot_data, (size_t)num_parts, train_dim);
+
+ shard_data_into_clusters_only_ids<T>(data_file, pivot_data, num_parts, train_dim, k_base, prefix_path);
+ delete[] pivot_data;
+ delete[] train_data_float;
+ delete[] test_data_float;
+ return num_parts;
+}
+
+// Instantations of supported templates
+
+template void DISKANN_DLLEXPORT gen_random_slice<int8_t>(const std::string base_file, const std::string output_prefix,
+ double sampling_rate);
+template void DISKANN_DLLEXPORT gen_random_slice<uint8_t>(const std::string base_file, const std::string output_prefix,
+ double sampling_rate);
+template void DISKANN_DLLEXPORT gen_random_slice<float>(const std::string base_file, const std::string output_prefix,
+ double sampling_rate);
+
+template void DISKANN_DLLEXPORT gen_random_slice<float>(const float *inputdata, size_t npts, size_t ndims, double p_val,
+ float *&sampled_data, size_t &slice_size);
+template void DISKANN_DLLEXPORT gen_random_slice<uint8_t>(const uint8_t *inputdata, size_t npts, size_t ndims,
+ double p_val, float *&sampled_data, size_t &slice_size);
+template void DISKANN_DLLEXPORT gen_random_slice<int8_t>(const int8_t *inputdata, size_t npts, size_t ndims,
+ double p_val, float *&sampled_data, size_t &slice_size);
+
+template void DISKANN_DLLEXPORT gen_random_slice<float>(const std::string data_file, double p_val, float *&sampled_data,
+ size_t &slice_size, size_t &ndims);
+template void DISKANN_DLLEXPORT gen_random_slice<uint8_t>(const std::string data_file, double p_val,
+ float *&sampled_data, size_t &slice_size, size_t &ndims);
+template void DISKANN_DLLEXPORT gen_random_slice<int8_t>(const std::string data_file, double p_val,
+ float *&sampled_data, size_t &slice_size, size_t &ndims);
+
+template DISKANN_DLLEXPORT int partition<int8_t>(const std::string data_file, const float sampling_rate,
+ size_t num_centers, size_t max_k_means_reps,
+ const std::string prefix_path, size_t k_base);
+template DISKANN_DLLEXPORT int partition<uint8_t>(const std::string data_file, const float sampling_rate,
+ size_t num_centers, size_t max_k_means_reps,
+ const std::string prefix_path, size_t k_base);
+template DISKANN_DLLEXPORT int partition<float>(const std::string data_file, const float sampling_rate,
+ size_t num_centers, size_t max_k_means_reps,
+ const std::string prefix_path, size_t k_base);
+
+template DISKANN_DLLEXPORT int partition_with_ram_budget<int8_t>(const std::string data_file,
+ const double sampling_rate, double ram_budget,
+ size_t graph_degree, const std::string prefix_path,
+ size_t k_base);
+template DISKANN_DLLEXPORT int partition_with_ram_budget<uint8_t>(const std::string data_file,
+ const double sampling_rate, double ram_budget,
+ size_t graph_degree, const std::string prefix_path,
+ size_t k_base);
+template DISKANN_DLLEXPORT int partition_with_ram_budget<float>(const std::string data_file, const double sampling_rate,
+ double ram_budget, size_t graph_degree,
+ const std::string prefix_path, size_t k_base);
+
+template DISKANN_DLLEXPORT int retrieve_shard_data_from_ids<float>(const std::string data_file,
+ std::string idmap_filename,
+ std::string data_filename);
+template DISKANN_DLLEXPORT int retrieve_shard_data_from_ids<uint8_t>(const std::string data_file,
+ std::string idmap_filename,
+ std::string data_filename);
+template DISKANN_DLLEXPORT int retrieve_shard_data_from_ids<int8_t>(const std::string data_file,
+ std::string idmap_filename,
+ std::string data_filename);
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/pq.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/pq.cpp
new file mode 100644
index 0000000..d8fbc7f
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/pq.cpp
@@ -0,0 +1,1214 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#ifdef __APPLE__
+#include <Accelerate/Accelerate.h>
+#else
+#include "mkl.h"
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+#include "gperftools/malloc_extension.h"
+#endif
+#endif
+#include "pq.h"
+#include "partition.h"
+#include "math_utils.h"
+#include "tsl/robin_map.h"
+
+// block size for reading/processing large files and matrices in blocks
+#define BLOCK_SIZE 5000000
+
+namespace diskann
+{
+
+#ifdef __APPLE__
+typedef long long int MKL_INT;
+#endif
+
+FixedChunkPQTable::FixedChunkPQTable()
+{
+}
+
+FixedChunkPQTable::~FixedChunkPQTable()
+{
+#ifndef EXEC_ENV_OLS
+ if (tables != nullptr)
+ delete[] tables;
+ if (tables_tr != nullptr)
+ delete[] tables_tr;
+ if (chunk_offsets != nullptr)
+ delete[] chunk_offsets;
+ if (centroid != nullptr)
+ delete[] centroid;
+ if (rotmat_tr != nullptr)
+ delete[] rotmat_tr;
+#endif
+}
+
+#ifdef EXEC_ENV_OLS
+void FixedChunkPQTable::load_pq_centroid_bin(MemoryMappedFiles &files, const char *pq_table_file, size_t num_chunks)
+{
+#else
+void FixedChunkPQTable::load_pq_centroid_bin(const char *pq_table_file, size_t num_chunks)
+{
+#endif
+
+ size_t nr, nc;
+ std::string rotmat_file = std::string(pq_table_file) + "_rotation_matrix.bin";
+
+#ifdef EXEC_ENV_OLS
+ size_t *file_offset_data; // since load_bin only sets the pointer, no need
+ // to delete.
+ diskann::load_bin<size_t>(files, pq_table_file, file_offset_data, nr, nc);
+#else
+ std::unique_ptr<size_t[]> file_offset_data;
+ diskann::load_bin<size_t>(pq_table_file, file_offset_data, nr, nc);
+#endif
+
+ bool use_old_filetype = false;
+
+ if (nr != 4 && nr != 5)
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_table_file
+ << ". Offsets dont contain correct metadata, # offsets = " << nr << ", but expecting " << 4
+ << " or " << 5;
+ throw diskann::ANNException("Error reading pq_pivots file at offsets data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ if (nr == 4)
+ {
+ diskann::cout << "Offsets: " << file_offset_data[0] << " " << file_offset_data[1] << " " << file_offset_data[2]
+ << " " << file_offset_data[3] << std::endl;
+ }
+ else if (nr == 5)
+ {
+ use_old_filetype = true;
+ diskann::cout << "Offsets: " << file_offset_data[0] << " " << file_offset_data[1] << " " << file_offset_data[2]
+ << " " << file_offset_data[3] << file_offset_data[4] << std::endl;
+ }
+ else
+ {
+ throw diskann::ANNException("Wrong number of offsets in pq_pivots", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+#ifdef EXEC_ENV_OLS
+
+ diskann::load_bin<float>(files, pq_table_file, tables, nr, nc, file_offset_data[0]);
+#else
+ diskann::load_bin<float>(pq_table_file, tables, nr, nc, file_offset_data[0]);
+#endif
+
+ if ((nr != NUM_PQ_CENTROIDS))
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_table_file << ". file_num_centers = " << nr
+ << " but expecting " << NUM_PQ_CENTROIDS << " centers";
+ throw diskann::ANNException("Error reading pq_pivots file at pivots data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ this->ndims = nc;
+
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<float>(files, pq_table_file, centroid, nr, nc, file_offset_data[1]);
+#else
+ diskann::load_bin<float>(pq_table_file, centroid, nr, nc, file_offset_data[1]);
+#endif
+
+ if ((nr != this->ndims) || (nc != 1))
+ {
+ diskann::cerr << "Error reading centroids from pq_pivots file " << pq_table_file << ". file_dim = " << nr
+ << ", file_cols = " << nc << " but expecting " << this->ndims << " entries in 1 dimension.";
+ throw diskann::ANNException("Error reading pq_pivots file at centroid data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ int chunk_offsets_index = 2;
+ if (use_old_filetype)
+ {
+ chunk_offsets_index = 3;
+ }
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<uint32_t>(files, pq_table_file, chunk_offsets, nr, nc, file_offset_data[chunk_offsets_index]);
+#else
+ diskann::load_bin<uint32_t>(pq_table_file, chunk_offsets, nr, nc, file_offset_data[chunk_offsets_index]);
+#endif
+
+ if (nc != 1 || (nr != num_chunks + 1 && num_chunks != 0))
+ {
+ diskann::cerr << "Error loading chunk offsets file. numc: " << nc << " (should be 1). numr: " << nr
+ << " (should be " << num_chunks + 1 << " or 0 if we need to infer)" << std::endl;
+ throw diskann::ANNException("Error loading chunk offsets file", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ this->n_chunks = nr - 1;
+ diskann::cout << "Loaded PQ Pivots: #ctrs: " << NUM_PQ_CENTROIDS << ", #dims: " << this->ndims
+ << ", #chunks: " << this->n_chunks << std::endl;
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(rotmat_file))
+ {
+ diskann::load_bin<float>(files, rotmat_file, (float *&)rotmat_tr, nr, nc);
+#else
+ if (file_exists(rotmat_file))
+ {
+ diskann::load_bin<float>(rotmat_file, rotmat_tr, nr, nc);
+#endif
+ if (nr != this->ndims || nc != this->ndims)
+ {
+ diskann::cerr << "Error loading rotation matrix file" << std::endl;
+ throw diskann::ANNException("Error loading rotation matrix file", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ use_rotation = true;
+ }
+
+ // alloc and compute transpose
+ tables_tr = new float[256 * this->ndims];
+ for (size_t i = 0; i < 256; i++)
+ {
+ for (size_t j = 0; j < this->ndims; j++)
+ {
+ tables_tr[j * 256 + i] = tables[i * this->ndims + j];
+ }
+ }
+}
+
+uint32_t FixedChunkPQTable::get_num_chunks()
+{
+ return static_cast<uint32_t>(n_chunks);
+}
+
+void FixedChunkPQTable::preprocess_query(float *query_vec)
+{
+ for (uint32_t d = 0; d < ndims; d++)
+ {
+ query_vec[d] -= centroid[d];
+ }
+ std::vector<float> tmp(ndims, 0);
+ if (use_rotation)
+ {
+ for (uint32_t d = 0; d < ndims; d++)
+ {
+ for (uint32_t d1 = 0; d1 < ndims; d1++)
+ {
+ tmp[d] += query_vec[d1] * rotmat_tr[d1 * ndims + d];
+ }
+ }
+ std::memcpy(query_vec, tmp.data(), ndims * sizeof(float));
+ }
+}
+
+// assumes pre-processed query
+void FixedChunkPQTable::populate_chunk_distances(const float *query_vec, float *dist_vec)
+{
+ memset(dist_vec, 0, 256 * n_chunks * sizeof(float));
+ // chunk wise distance computation
+ for (size_t chunk = 0; chunk < n_chunks; chunk++)
+ {
+ // sum (q-c)^2 for the dimensions associated with this chunk
+ float *chunk_dists = dist_vec + (256 * chunk);
+ for (size_t j = chunk_offsets[chunk]; j < chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = tables_tr + (256 * j);
+ for (size_t idx = 0; idx < 256; idx++)
+ {
+ double diff = centers_dim_vec[idx] - (query_vec[j]);
+ chunk_dists[idx] += (float)(diff * diff);
+ }
+ }
+ }
+}
+
+float FixedChunkPQTable::l2_distance(const float *query_vec, uint8_t *base_vec)
+{
+ float res = 0;
+ for (size_t chunk = 0; chunk < n_chunks; chunk++)
+ {
+ for (size_t j = chunk_offsets[chunk]; j < chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = tables_tr + (256 * j);
+ float diff = centers_dim_vec[base_vec[chunk]] - (query_vec[j]);
+ res += diff * diff;
+ }
+ }
+ return res;
+}
+
+float FixedChunkPQTable::inner_product(const float *query_vec, uint8_t *base_vec)
+{
+ float res = 0;
+ for (size_t chunk = 0; chunk < n_chunks; chunk++)
+ {
+ for (size_t j = chunk_offsets[chunk]; j < chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = tables_tr + (256 * j);
+ float diff = centers_dim_vec[base_vec[chunk]] * query_vec[j]; // assumes centroid is 0 to
+ // prevent translation errors
+ res += diff;
+ }
+ }
+ return -res; // returns negative value to simulate distances (max -> min
+ // conversion)
+}
+
+// assumes no rotation is involved
+void FixedChunkPQTable::inflate_vector(uint8_t *base_vec, float *out_vec)
+{
+ for (size_t chunk = 0; chunk < n_chunks; chunk++)
+ {
+ for (size_t j = chunk_offsets[chunk]; j < chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = tables_tr + (256 * j);
+ out_vec[j] = centers_dim_vec[base_vec[chunk]] + centroid[j];
+ }
+ }
+}
+
+void FixedChunkPQTable::populate_chunk_inner_products(const float *query_vec, float *dist_vec)
+{
+ memset(dist_vec, 0, 256 * n_chunks * sizeof(float));
+ // chunk wise distance computation
+ for (size_t chunk = 0; chunk < n_chunks; chunk++)
+ {
+ // sum (q-c)^2 for the dimensions associated with this chunk
+ float *chunk_dists = dist_vec + (256 * chunk);
+ for (size_t j = chunk_offsets[chunk]; j < chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = tables_tr + (256 * j);
+ for (size_t idx = 0; idx < 256; idx++)
+ {
+ double prod = centers_dim_vec[idx] * query_vec[j]; // assumes that we are not
+ // shifting the vectors to
+ // mean zero, i.e., centroid
+ // array should be all zeros
+ chunk_dists[idx] -= (float)prod; // returning negative to keep the search code
+ // clean (max inner product vs min distance)
+ }
+ }
+ }
+}
+
+void aggregate_coords(const std::vector<uint32_t> &ids, const uint8_t *all_coords, const uint64_t ndims, uint8_t *out)
+{
+ for (size_t i = 0; i < ids.size(); i++)
+ {
+ memcpy(out + i * ndims, all_coords + ids[i] * ndims, ndims * sizeof(uint8_t));
+ }
+}
+
+void pq_dist_lookup(const uint8_t *pq_ids, const size_t n_pts, const size_t pq_nchunks, const float *pq_dists,
+ std::vector<float> &dists_out)
+{
+ //_mm_prefetch((char*) dists_out, _MM_HINT_T0);
+ _mm_prefetch((char *)pq_ids, _MM_HINT_T0);
+ _mm_prefetch((char *)(pq_ids + 64), _MM_HINT_T0);
+ _mm_prefetch((char *)(pq_ids + 128), _MM_HINT_T0);
+ dists_out.clear();
+ dists_out.resize(n_pts, 0);
+ for (size_t chunk = 0; chunk < pq_nchunks; chunk++)
+ {
+ const float *chunk_dists = pq_dists + 256 * chunk;
+ if (chunk < pq_nchunks - 1)
+ {
+ _mm_prefetch((char *)(chunk_dists + 256), _MM_HINT_T0);
+ }
+ for (size_t idx = 0; idx < n_pts; idx++)
+ {
+ uint8_t pq_centerid = pq_ids[pq_nchunks * idx + chunk];
+ dists_out[idx] += chunk_dists[pq_centerid];
+ }
+ }
+}
+
+// Need to replace calls to these functions with calls to vector& based
+// functions above
+void aggregate_coords(const uint32_t *ids, const uint64_t n_ids, const uint8_t *all_coords, const uint64_t ndims,
+ uint8_t *out)
+{
+ for (size_t i = 0; i < n_ids; i++)
+ {
+ memcpy(out + i * ndims, all_coords + ids[i] * ndims, ndims * sizeof(uint8_t));
+ }
+}
+
+void pq_dist_lookup(const uint8_t *pq_ids, const size_t n_pts, const size_t pq_nchunks, const float *pq_dists,
+ float *dists_out)
+{
+ _mm_prefetch((char *)dists_out, _MM_HINT_T0);
+ _mm_prefetch((char *)pq_ids, _MM_HINT_T0);
+ _mm_prefetch((char *)(pq_ids + 64), _MM_HINT_T0);
+ _mm_prefetch((char *)(pq_ids + 128), _MM_HINT_T0);
+ memset(dists_out, 0, n_pts * sizeof(float));
+ for (size_t chunk = 0; chunk < pq_nchunks; chunk++)
+ {
+ const float *chunk_dists = pq_dists + 256 * chunk;
+ if (chunk < pq_nchunks - 1)
+ {
+ _mm_prefetch((char *)(chunk_dists + 256), _MM_HINT_T0);
+ }
+ for (size_t idx = 0; idx < n_pts; idx++)
+ {
+ uint8_t pq_centerid = pq_ids[pq_nchunks * idx + chunk];
+ dists_out[idx] += chunk_dists[pq_centerid];
+ }
+ }
+}
+
+// generate_pq_pivots_simplified is a simplified version of generate_pq_pivots.
+// Input is provided in the in-memory buffer train_data.
+// Output is stored in the in-memory buffer pivot_data_vector.
+// Simplification is based on the following assumptions:
+// dim % num_pq_chunks == 0
+// num_centers == 256 by default
+// KMEANS_ITERS_FOR_PQ == 15 by default
+// make_zero_mean is false by default.
+// These assumptions allow to make the function much simpler and avoid storing
+// array of chunk_offsets and centroids.
+// The compiler pragma for multi-threading support is removed from this implementation
+// for the purpose of integration into systems that strictly control resource allocation.
+int generate_pq_pivots_simplified(const float *train_data, size_t num_train, size_t dim, size_t num_pq_chunks,
+ std::vector<float> &pivot_data_vector)
+{
+ if (num_pq_chunks > dim || dim % num_pq_chunks != 0)
+ {
+ return -1;
+ }
+
+ const size_t num_centers = 256;
+ const size_t cur_chunk_size = dim / num_pq_chunks;
+ const uint32_t KMEANS_ITERS_FOR_PQ = 15;
+
+ pivot_data_vector.resize(num_centers * dim);
+ std::vector<float> cur_pivot_data_vector(num_centers * cur_chunk_size);
+ std::vector<float> cur_data_vector(num_train * cur_chunk_size);
+ std::vector<uint32_t> closest_center_vector(num_train);
+
+ float *pivot_data = &pivot_data_vector[0];
+ float *cur_pivot_data = &cur_pivot_data_vector[0];
+ float *cur_data = &cur_data_vector[0];
+ uint32_t *closest_center = &closest_center_vector[0];
+
+ for (size_t i = 0; i < num_pq_chunks; i++)
+ {
+ size_t chunk_offset = cur_chunk_size * i;
+
+ for (int32_t j = 0; j < num_train; j++)
+ {
+ std::memcpy(cur_data + j * cur_chunk_size, train_data + j * dim + chunk_offset,
+ cur_chunk_size * sizeof(float));
+ }
+
+ kmeans::kmeanspp_selecting_pivots(cur_data, num_train, cur_chunk_size, cur_pivot_data, num_centers);
+
+ kmeans::run_lloyds(cur_data, num_train, cur_chunk_size, cur_pivot_data, num_centers, KMEANS_ITERS_FOR_PQ, NULL,
+ closest_center);
+
+ for (uint64_t j = 0; j < num_centers; j++)
+ {
+ std::memcpy(pivot_data + j * dim + chunk_offset, cur_pivot_data + j * cur_chunk_size,
+ cur_chunk_size * sizeof(float));
+ }
+ }
+
+ return 0;
+}
+
+// given training data in train_data of dimensions num_train * dim, generate
+// PQ pivots using k-means algorithm to partition the co-ordinates into
+// num_pq_chunks (if it divides dimension, else rounded) chunks, and runs
+// k-means in each chunk to compute the PQ pivots and stores in bin format in
+// file pq_pivots_path as a s num_centers*dim floating point binary file
+int generate_pq_pivots(const float *const passed_train_data, size_t num_train, uint32_t dim, uint32_t num_centers,
+ uint32_t num_pq_chunks, uint32_t max_k_means_reps, std::string pq_pivots_path,
+ bool make_zero_mean)
+{
+ if (num_pq_chunks > dim)
+ {
+ diskann::cout << " Error: number of chunks more than dimension" << std::endl;
+ return -1;
+ }
+
+ std::unique_ptr<float[]> train_data = std::make_unique<float[]>(num_train * dim);
+ std::memcpy(train_data.get(), passed_train_data, num_train * dim * sizeof(float));
+
+ std::unique_ptr<float[]> full_pivot_data;
+
+ if (file_exists(pq_pivots_path))
+ {
+ size_t file_dim, file_num_centers;
+ diskann::load_bin<float>(pq_pivots_path, full_pivot_data, file_num_centers, file_dim, METADATA_SIZE);
+ if (file_dim == dim && file_num_centers == num_centers)
+ {
+ diskann::cout << "PQ pivot file exists. Not generating again" << std::endl;
+ return -1;
+ }
+ }
+
+ // Calculate centroid and center the training data
+ std::unique_ptr<float[]> centroid = std::make_unique<float[]>(dim);
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ centroid[d] = 0;
+ }
+ if (make_zero_mean)
+ { // If we use L2 distance, there is an option to
+ // translate all vectors to make them centered and
+ // then compute PQ. This needs to be set to false
+ // when using PQ for MIPS as such translations dont
+ // preserve inner products.
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ for (uint64_t p = 0; p < num_train; p++)
+ {
+ centroid[d] += train_data[p * dim + d];
+ }
+ centroid[d] /= num_train;
+ }
+
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ for (uint64_t p = 0; p < num_train; p++)
+ {
+ train_data[p * dim + d] -= centroid[d];
+ }
+ }
+ }
+
+ std::vector<uint32_t> chunk_offsets;
+
+ size_t low_val = (size_t)std::floor((double)dim / (double)num_pq_chunks);
+ size_t high_val = (size_t)std::ceil((double)dim / (double)num_pq_chunks);
+ size_t max_num_high = dim - (low_val * num_pq_chunks);
+ size_t cur_num_high = 0;
+ size_t cur_bin_threshold = high_val;
+
+ std::vector<std::vector<uint32_t>> bin_to_dims(num_pq_chunks);
+ tsl::robin_map<uint32_t, uint32_t> dim_to_bin;
+ std::vector<float> bin_loads(num_pq_chunks, 0);
+
+ // Process dimensions not inserted by previous loop
+ for (uint32_t d = 0; d < dim; d++)
+ {
+ if (dim_to_bin.find(d) != dim_to_bin.end())
+ continue;
+ auto cur_best = num_pq_chunks + 1;
+ float cur_best_load = std::numeric_limits<float>::max();
+ for (uint32_t b = 0; b < num_pq_chunks; b++)
+ {
+ if (bin_loads[b] < cur_best_load && bin_to_dims[b].size() < cur_bin_threshold)
+ {
+ cur_best = b;
+ cur_best_load = bin_loads[b];
+ }
+ }
+ bin_to_dims[cur_best].push_back(d);
+ if (bin_to_dims[cur_best].size() == high_val)
+ {
+ cur_num_high++;
+ if (cur_num_high == max_num_high)
+ cur_bin_threshold = low_val;
+ }
+ }
+
+ chunk_offsets.clear();
+ chunk_offsets.push_back(0);
+
+ for (uint32_t b = 0; b < num_pq_chunks; b++)
+ {
+ if (b > 0)
+ chunk_offsets.push_back(chunk_offsets[b - 1] + (uint32_t)bin_to_dims[b - 1].size());
+ }
+ chunk_offsets.push_back(dim);
+
+ full_pivot_data.reset(new float[num_centers * dim]);
+
+ for (size_t i = 0; i < num_pq_chunks; i++)
+ {
+ size_t cur_chunk_size = chunk_offsets[i + 1] - chunk_offsets[i];
+
+ if (cur_chunk_size == 0)
+ continue;
+ std::unique_ptr<float[]> cur_pivot_data = std::make_unique<float[]>(num_centers * cur_chunk_size);
+ std::unique_ptr<float[]> cur_data = std::make_unique<float[]>(num_train * cur_chunk_size);
+ std::unique_ptr<uint32_t[]> closest_center = std::make_unique<uint32_t[]>(num_train);
+
+ diskann::cout << "Processing chunk " << i << " with dimensions [" << chunk_offsets[i] << ", "
+ << chunk_offsets[i + 1] << ")" << std::endl;
+
+#pragma omp parallel for schedule(static, 65536)
+ for (int64_t j = 0; j < (int64_t)num_train; j++)
+ {
+ std::memcpy(cur_data.get() + j * cur_chunk_size, train_data.get() + j * dim + chunk_offsets[i],
+ cur_chunk_size * sizeof(float));
+ }
+
+ kmeans::kmeanspp_selecting_pivots(cur_data.get(), num_train, cur_chunk_size, cur_pivot_data.get(), num_centers);
+
+ kmeans::run_lloyds(cur_data.get(), num_train, cur_chunk_size, cur_pivot_data.get(), num_centers,
+ max_k_means_reps, NULL, closest_center.get());
+
+ for (uint64_t j = 0; j < num_centers; j++)
+ {
+ std::memcpy(full_pivot_data.get() + j * dim + chunk_offsets[i], cur_pivot_data.get() + j * cur_chunk_size,
+ cur_chunk_size * sizeof(float));
+ }
+ }
+
+ std::vector<size_t> cumul_bytes(4, 0);
+ cumul_bytes[0] = METADATA_SIZE;
+ cumul_bytes[1] = cumul_bytes[0] + diskann::save_bin<float>(pq_pivots_path.c_str(), full_pivot_data.get(),
+ (size_t)num_centers, dim, cumul_bytes[0]);
+ cumul_bytes[2] = cumul_bytes[1] +
+ diskann::save_bin<float>(pq_pivots_path.c_str(), centroid.get(), (size_t)dim, 1, cumul_bytes[1]);
+ cumul_bytes[3] = cumul_bytes[2] + diskann::save_bin<uint32_t>(pq_pivots_path.c_str(), chunk_offsets.data(),
+ chunk_offsets.size(), 1, cumul_bytes[2]);
+ diskann::save_bin<size_t>(pq_pivots_path.c_str(), cumul_bytes.data(), cumul_bytes.size(), 1, 0);
+
+ diskann::cout << "Saved pq pivot data to " << pq_pivots_path << " of size " << cumul_bytes[cumul_bytes.size() - 1]
+ << "B." << std::endl;
+
+ return 0;
+}
+
+int generate_opq_pivots(const float *passed_train_data, size_t num_train, uint32_t dim, uint32_t num_centers,
+ uint32_t num_pq_chunks, std::string opq_pivots_path, bool make_zero_mean)
+{
+ if (num_pq_chunks > dim)
+ {
+ diskann::cout << " Error: number of chunks more than dimension" << std::endl;
+ return -1;
+ }
+
+ std::unique_ptr<float[]> train_data = std::make_unique<float[]>(num_train * dim);
+ std::memcpy(train_data.get(), passed_train_data, num_train * dim * sizeof(float));
+
+ std::unique_ptr<float[]> rotated_train_data = std::make_unique<float[]>(num_train * dim);
+ std::unique_ptr<float[]> rotated_and_quantized_train_data = std::make_unique<float[]>(num_train * dim);
+
+ std::unique_ptr<float[]> full_pivot_data;
+
+ // rotation matrix for OPQ
+ std::unique_ptr<float[]> rotmat_tr;
+
+ // matrices for SVD
+ std::unique_ptr<float[]> Umat = std::make_unique<float[]>(dim * dim);
+ std::unique_ptr<float[]> Vmat_T = std::make_unique<float[]>(dim * dim);
+ std::unique_ptr<float[]> singular_values = std::make_unique<float[]>(dim);
+ std::unique_ptr<float[]> correlation_matrix = std::make_unique<float[]>(dim * dim);
+
+ // Calculate centroid and center the training data
+ std::unique_ptr<float[]> centroid = std::make_unique<float[]>(dim);
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ centroid[d] = 0;
+ }
+ if (make_zero_mean)
+ { // If we use L2 distance, there is an option to
+ // translate all vectors to make them centered and
+ // then compute PQ. This needs to be set to false
+ // when using PQ for MIPS as such translations dont
+ // preserve inner products.
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ for (uint64_t p = 0; p < num_train; p++)
+ {
+ centroid[d] += train_data[p * dim + d];
+ }
+ centroid[d] /= num_train;
+ }
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ for (uint64_t p = 0; p < num_train; p++)
+ {
+ train_data[p * dim + d] -= centroid[d];
+ }
+ }
+ }
+
+ std::vector<uint32_t> chunk_offsets;
+
+ size_t low_val = (size_t)std::floor((double)dim / (double)num_pq_chunks);
+ size_t high_val = (size_t)std::ceil((double)dim / (double)num_pq_chunks);
+ size_t max_num_high = dim - (low_val * num_pq_chunks);
+ size_t cur_num_high = 0;
+ size_t cur_bin_threshold = high_val;
+
+ std::vector<std::vector<uint32_t>> bin_to_dims(num_pq_chunks);
+ tsl::robin_map<uint32_t, uint32_t> dim_to_bin;
+ std::vector<float> bin_loads(num_pq_chunks, 0);
+
+ // Process dimensions not inserted by previous loop
+ for (uint32_t d = 0; d < dim; d++)
+ {
+ if (dim_to_bin.find(d) != dim_to_bin.end())
+ continue;
+ auto cur_best = num_pq_chunks + 1;
+ float cur_best_load = std::numeric_limits<float>::max();
+ for (uint32_t b = 0; b < num_pq_chunks; b++)
+ {
+ if (bin_loads[b] < cur_best_load && bin_to_dims[b].size() < cur_bin_threshold)
+ {
+ cur_best = b;
+ cur_best_load = bin_loads[b];
+ }
+ }
+ bin_to_dims[cur_best].push_back(d);
+ if (bin_to_dims[cur_best].size() == high_val)
+ {
+ cur_num_high++;
+ if (cur_num_high == max_num_high)
+ cur_bin_threshold = low_val;
+ }
+ }
+
+ chunk_offsets.clear();
+ chunk_offsets.push_back(0);
+
+ for (uint32_t b = 0; b < num_pq_chunks; b++)
+ {
+ if (b > 0)
+ chunk_offsets.push_back(chunk_offsets[b - 1] + (uint32_t)bin_to_dims[b - 1].size());
+ }
+ chunk_offsets.push_back(dim);
+
+ full_pivot_data.reset(new float[num_centers * dim]);
+ rotmat_tr.reset(new float[dim * dim]);
+
+ std::memset(rotmat_tr.get(), 0, dim * dim * sizeof(float));
+ for (uint32_t d1 = 0; d1 < dim; d1++)
+ *(rotmat_tr.get() + d1 * dim + d1) = 1;
+
+ for (uint32_t rnd = 0; rnd < MAX_OPQ_ITERS; rnd++)
+ {
+ // rotate the training data using the current rotation matrix
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (MKL_INT)num_train, (MKL_INT)dim, (MKL_INT)dim, 1.0f,
+ train_data.get(), (MKL_INT)dim, rotmat_tr.get(), (MKL_INT)dim, 0.0f, rotated_train_data.get(),
+ (MKL_INT)dim);
+
+ // compute the PQ pivots on the rotated space
+ for (size_t i = 0; i < num_pq_chunks; i++)
+ {
+ size_t cur_chunk_size = chunk_offsets[i + 1] - chunk_offsets[i];
+
+ if (cur_chunk_size == 0)
+ continue;
+ std::unique_ptr<float[]> cur_pivot_data = std::make_unique<float[]>(num_centers * cur_chunk_size);
+ std::unique_ptr<float[]> cur_data = std::make_unique<float[]>(num_train * cur_chunk_size);
+ std::unique_ptr<uint32_t[]> closest_center = std::make_unique<uint32_t[]>(num_train);
+
+ diskann::cout << "Processing chunk " << i << " with dimensions [" << chunk_offsets[i] << ", "
+ << chunk_offsets[i + 1] << ")" << std::endl;
+
+#pragma omp parallel for schedule(static, 65536)
+ for (int64_t j = 0; j < (int64_t)num_train; j++)
+ {
+ std::memcpy(cur_data.get() + j * cur_chunk_size, rotated_train_data.get() + j * dim + chunk_offsets[i],
+ cur_chunk_size * sizeof(float));
+ }
+
+ if (rnd == 0)
+ {
+ kmeans::kmeanspp_selecting_pivots(cur_data.get(), num_train, cur_chunk_size, cur_pivot_data.get(),
+ num_centers);
+ }
+ else
+ {
+ for (uint64_t j = 0; j < num_centers; j++)
+ {
+ std::memcpy(cur_pivot_data.get() + j * cur_chunk_size,
+ full_pivot_data.get() + j * dim + chunk_offsets[i], cur_chunk_size * sizeof(float));
+ }
+ }
+
+ uint32_t num_lloyds_iters = 8;
+ kmeans::run_lloyds(cur_data.get(), num_train, cur_chunk_size, cur_pivot_data.get(), num_centers,
+ num_lloyds_iters, NULL, closest_center.get());
+
+ for (uint64_t j = 0; j < num_centers; j++)
+ {
+ std::memcpy(full_pivot_data.get() + j * dim + chunk_offsets[i],
+ cur_pivot_data.get() + j * cur_chunk_size, cur_chunk_size * sizeof(float));
+ }
+
+ for (size_t j = 0; j < num_train; j++)
+ {
+ std::memcpy(rotated_and_quantized_train_data.get() + j * dim + chunk_offsets[i],
+ cur_pivot_data.get() + (size_t)closest_center[j] * cur_chunk_size,
+ cur_chunk_size * sizeof(float));
+ }
+ }
+
+ // compute the correlation matrix between the original data and the
+ // quantized data to compute the new rotation
+ cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, (MKL_INT)dim, (MKL_INT)dim, (MKL_INT)num_train, 1.0f,
+ train_data.get(), (MKL_INT)dim, rotated_and_quantized_train_data.get(), (MKL_INT)dim, 0.0f,
+ correlation_matrix.get(), (MKL_INT)dim);
+
+ // compute the SVD of the correlation matrix to help determine the new
+ // rotation matrix
+
+#ifdef __APPLE__
+ uint32_t errcode = (uint32_t)LAPACKE_sgesdd(LAPACK_ROW_MAJOR, 'A', (clp_int)dim, (clp_int)dim,
+ correlation_matrix.get(), (clp_int)dim, singular_values.get(),
+ Umat.get(), (clp_int)dim, Vmat_T.get(), (clp_int)dim);
+
+#else
+ uint32_t errcode = (uint32_t)LAPACKE_sgesdd(LAPACK_ROW_MAJOR, 'A', (MKL_INT)dim, (MKL_INT)dim,
+ correlation_matrix.get(), (MKL_INT)dim, singular_values.get(),
+ Umat.get(), (MKL_INT)dim, Vmat_T.get(), (MKL_INT)dim);
+#endif
+
+ if (errcode > 0)
+ {
+ std::cout << "SVD failed to converge." << std::endl;
+ exit(-1);
+ }
+
+ // compute the new rotation matrix from the singular vectors as R^T = U
+ // V^T
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (MKL_INT)dim, (MKL_INT)dim, (MKL_INT)dim, 1.0f,
+ Umat.get(), (MKL_INT)dim, Vmat_T.get(), (MKL_INT)dim, 0.0f, rotmat_tr.get(), (MKL_INT)dim);
+ }
+
+ std::vector<size_t> cumul_bytes(4, 0);
+ cumul_bytes[0] = METADATA_SIZE;
+ cumul_bytes[1] = cumul_bytes[0] + diskann::save_bin<float>(opq_pivots_path.c_str(), full_pivot_data.get(),
+ (size_t)num_centers, dim, cumul_bytes[0]);
+ cumul_bytes[2] = cumul_bytes[1] +
+ diskann::save_bin<float>(opq_pivots_path.c_str(), centroid.get(), (size_t)dim, 1, cumul_bytes[1]);
+ cumul_bytes[3] = cumul_bytes[2] + diskann::save_bin<uint32_t>(opq_pivots_path.c_str(), chunk_offsets.data(),
+ chunk_offsets.size(), 1, cumul_bytes[2]);
+ diskann::save_bin<size_t>(opq_pivots_path.c_str(), cumul_bytes.data(), cumul_bytes.size(), 1, 0);
+
+ diskann::cout << "Saved opq pivot data to " << opq_pivots_path << " of size " << cumul_bytes[cumul_bytes.size() - 1]
+ << "B." << std::endl;
+
+ std::string rotmat_path = opq_pivots_path + "_rotation_matrix.bin";
+ diskann::save_bin<float>(rotmat_path.c_str(), rotmat_tr.get(), dim, dim);
+
+ return 0;
+}
+
+// generate_pq_data_from_pivots_simplified is a simplified version of generate_pq_data_from_pivots.
+// Input is provided in the in-memory buffers data and pivot_data.
+// Output is stored in the in-memory buffer pq.
+// Simplification is based on the following assumptions:
+// supporting only float data type
+// dim % num_pq_chunks == 0, which results in a fixed chunk_size
+// num_centers == 256 by default
+// make_zero_mean is false by default.
+// These assumptions allow to make the function much simpler and avoid using
+// array of chunk_offsets and centroids.
+// The compiler pragma for multi-threading support is removed from this implementation
+// for the purpose of integration into systems that strictly control resource allocation.
+int generate_pq_data_from_pivots_simplified(const float *data, const size_t num, const float *pivot_data,
+ const size_t pivots_num, const size_t dim, const size_t num_pq_chunks,
+ std::vector<uint8_t> &pq)
+{
+ if (num_pq_chunks == 0 || num_pq_chunks > dim || dim % num_pq_chunks != 0)
+ {
+ return -1;
+ }
+
+ const size_t num_centers = 256;
+ const size_t chunk_size = dim / num_pq_chunks;
+
+ if (pivots_num != num_centers * dim)
+ {
+ return -1;
+ }
+
+ pq.resize(num * num_pq_chunks);
+
+ std::vector<float> cur_pivot_vector(num_centers * chunk_size);
+ std::vector<float> cur_data_vector(num * chunk_size);
+ std::vector<uint32_t> closest_center_vector(num);
+
+ float *cur_pivot_data = &cur_pivot_vector[0];
+ float *cur_data = &cur_data_vector[0];
+ uint32_t *closest_center = &closest_center_vector[0];
+
+ for (size_t i = 0; i < num_pq_chunks; i++)
+ {
+ const size_t chunk_offset = chunk_size * i;
+
+ for (int j = 0; j < num_centers; j++)
+ {
+ std::memcpy(cur_pivot_data + j * chunk_size, pivot_data + j * dim + chunk_offset,
+ chunk_size * sizeof(float));
+ }
+
+ for (int j = 0; j < num; j++)
+ {
+ for (size_t k = 0; k < chunk_size; k++)
+ {
+ cur_data[j * chunk_size + k] = data[j * dim + chunk_offset + k];
+ }
+ }
+
+ math_utils::compute_closest_centers(cur_data, num, chunk_size, cur_pivot_data, num_centers, 1, closest_center);
+
+ for (int j = 0; j < num; j++)
+ {
+ assert(closest_center[j] < num_centers);
+ pq[j * num_pq_chunks + i] = closest_center[j];
+ }
+ }
+
+ return 0;
+}
+
+// streams the base file (data_file), and computes the closest centers in each
+// chunk to generate the compressed data_file and stores it in
+// pq_compressed_vectors_path.
+// If the numbber of centers is < 256, it stores as byte vector, else as
+// 4-byte vector in binary format.
+template <typename T>
+int generate_pq_data_from_pivots(const std::string &data_file, uint32_t num_centers, uint32_t num_pq_chunks,
+ const std::string &pq_pivots_path, const std::string &pq_compressed_vectors_path,
+ bool use_opq)
+{
+ size_t read_blk_size = 64 * 1024 * 1024;
+ cached_ifstream base_reader(data_file, read_blk_size);
+ uint32_t npts32;
+ uint32_t basedim32;
+ base_reader.read((char *)&npts32, sizeof(uint32_t));
+ base_reader.read((char *)&basedim32, sizeof(uint32_t));
+ size_t num_points = npts32;
+ size_t dim = basedim32;
+
+ std::unique_ptr<float[]> full_pivot_data;
+ std::unique_ptr<float[]> rotmat_tr;
+ std::unique_ptr<float[]> centroid;
+ std::unique_ptr<uint32_t[]> chunk_offsets;
+
+ std::string inflated_pq_file = pq_compressed_vectors_path + "_inflated.bin";
+
+ if (!file_exists(pq_pivots_path))
+ {
+ std::cout << "ERROR: PQ k-means pivot file not found" << std::endl;
+ throw diskann::ANNException("PQ k-means pivot file not found", -1);
+ }
+ else
+ {
+ size_t nr, nc;
+ std::unique_ptr<size_t[]> file_offset_data;
+
+ diskann::load_bin<size_t>(pq_pivots_path.c_str(), file_offset_data, nr, nc, 0);
+
+ if (nr != 4)
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_pivots_path
+ << ". Offsets dont contain correct metadata, # offsets = " << nr << ", but expecting 4.";
+ throw diskann::ANNException("Error reading pq_pivots file at offsets data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ diskann::load_bin<float>(pq_pivots_path.c_str(), full_pivot_data, nr, nc, file_offset_data[0]);
+
+ if ((nr != num_centers) || (nc != dim))
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_pivots_path << ". file_num_centers = " << nr
+ << ", file_dim = " << nc << " but expecting " << num_centers << " centers in " << dim
+ << " dimensions.";
+ throw diskann::ANNException("Error reading pq_pivots file at pivots data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ diskann::load_bin<float>(pq_pivots_path.c_str(), centroid, nr, nc, file_offset_data[1]);
+
+ if ((nr != dim) || (nc != 1))
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_pivots_path << ". file_dim = " << nr
+ << ", file_cols = " << nc << " but expecting " << dim << " entries in 1 dimension.";
+ throw diskann::ANNException("Error reading pq_pivots file at centroid data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ diskann::load_bin<uint32_t>(pq_pivots_path.c_str(), chunk_offsets, nr, nc, file_offset_data[2]);
+
+ if (nr != (uint64_t)num_pq_chunks + 1 || nc != 1)
+ {
+ diskann::cout << "Error reading pq_pivots file at chunk offsets; file has nr=" << nr << ",nc=" << nc
+ << ", expecting nr=" << num_pq_chunks + 1 << ", nc=1." << std::endl;
+ throw diskann::ANNException("Error reading pq_pivots file at chunk offsets.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ if (use_opq)
+ {
+ std::string rotmat_path = pq_pivots_path + "_rotation_matrix.bin";
+ diskann::load_bin<float>(rotmat_path.c_str(), rotmat_tr, nr, nc);
+ if (nr != (uint64_t)dim || nc != dim)
+ {
+ diskann::cout << "Error reading rotation matrix file." << std::endl;
+ throw diskann::ANNException("Error reading rotation matrix file.", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+
+ diskann::cout << "Loaded PQ pivot information" << std::endl;
+ }
+
+ std::ofstream compressed_file_writer(pq_compressed_vectors_path, std::ios::binary);
+ uint32_t num_pq_chunks_u32 = num_pq_chunks;
+
+ compressed_file_writer.write((char *)&num_points, sizeof(uint32_t));
+ compressed_file_writer.write((char *)&num_pq_chunks_u32, sizeof(uint32_t));
+
+ size_t block_size = num_points <= BLOCK_SIZE ? num_points : BLOCK_SIZE;
+
+#ifdef SAVE_INFLATED_PQ
+ std::ofstream inflated_file_writer(inflated_pq_file, std::ios::binary);
+ inflated_file_writer.write((char *)&num_points, sizeof(uint32_t));
+ inflated_file_writer.write((char *)&basedim32, sizeof(uint32_t));
+
+ std::unique_ptr<float[]> block_inflated_base = std::make_unique<float[]>(block_size * dim);
+ std::memset(block_inflated_base.get(), 0, block_size * dim * sizeof(float));
+#endif
+
+ std::unique_ptr<uint32_t[]> block_compressed_base =
+ std::make_unique<uint32_t[]>(block_size * (size_t)num_pq_chunks);
+ std::memset(block_compressed_base.get(), 0, block_size * (size_t)num_pq_chunks * sizeof(uint32_t));
+
+ std::unique_ptr<T[]> block_data_T = std::make_unique<T[]>(block_size * dim);
+ std::unique_ptr<float[]> block_data_float = std::make_unique<float[]>(block_size * dim);
+ std::unique_ptr<float[]> block_data_tmp = std::make_unique<float[]>(block_size * dim);
+
+ size_t num_blocks = DIV_ROUND_UP(num_points, block_size);
+
+ for (size_t block = 0; block < num_blocks; block++)
+ {
+ size_t start_id = block * block_size;
+ size_t end_id = (std::min)((block + 1) * block_size, num_points);
+ size_t cur_blk_size = end_id - start_id;
+
+ base_reader.read((char *)(block_data_T.get()), sizeof(T) * (cur_blk_size * dim));
+ diskann::convert_types<T, float>(block_data_T.get(), block_data_tmp.get(), cur_blk_size, dim);
+
+ diskann::cout << "Processing points [" << start_id << ", " << end_id << ").." << std::flush;
+
+ for (size_t p = 0; p < cur_blk_size; p++)
+ {
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ block_data_tmp[p * dim + d] -= centroid[d];
+ }
+ }
+
+ for (size_t p = 0; p < cur_blk_size; p++)
+ {
+ for (uint64_t d = 0; d < dim; d++)
+ {
+ block_data_float[p * dim + d] = block_data_tmp[p * dim + d];
+ }
+ }
+
+ if (use_opq)
+ {
+ // rotate the current block with the trained rotation matrix before
+ // PQ
+ cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (MKL_INT)cur_blk_size, (MKL_INT)dim, (MKL_INT)dim,
+ 1.0f, block_data_float.get(), (MKL_INT)dim, rotmat_tr.get(), (MKL_INT)dim, 0.0f,
+ block_data_tmp.get(), (MKL_INT)dim);
+ std::memcpy(block_data_float.get(), block_data_tmp.get(), cur_blk_size * dim * sizeof(float));
+ }
+
+ for (size_t i = 0; i < num_pq_chunks; i++)
+ {
+ size_t cur_chunk_size = chunk_offsets[i + 1] - chunk_offsets[i];
+ if (cur_chunk_size == 0)
+ continue;
+
+ std::unique_ptr<float[]> cur_pivot_data = std::make_unique<float[]>(num_centers * cur_chunk_size);
+ std::unique_ptr<float[]> cur_data = std::make_unique<float[]>(cur_blk_size * cur_chunk_size);
+ std::unique_ptr<uint32_t[]> closest_center = std::make_unique<uint32_t[]>(cur_blk_size);
+
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t j = 0; j < (int64_t)cur_blk_size; j++)
+ {
+ for (size_t k = 0; k < cur_chunk_size; k++)
+ cur_data[j * cur_chunk_size + k] = block_data_float[j * dim + chunk_offsets[i] + k];
+ }
+
+#pragma omp parallel for schedule(static, 1)
+ for (int64_t j = 0; j < (int64_t)num_centers; j++)
+ {
+ std::memcpy(cur_pivot_data.get() + j * cur_chunk_size,
+ full_pivot_data.get() + j * dim + chunk_offsets[i], cur_chunk_size * sizeof(float));
+ }
+
+ math_utils::compute_closest_centers(cur_data.get(), cur_blk_size, cur_chunk_size, cur_pivot_data.get(),
+ num_centers, 1, closest_center.get());
+
+#pragma omp parallel for schedule(static, 8192)
+ for (int64_t j = 0; j < (int64_t)cur_blk_size; j++)
+ {
+ block_compressed_base[j * num_pq_chunks + i] = closest_center[j];
+#ifdef SAVE_INFLATED_PQ
+ for (size_t k = 0; k < cur_chunk_size; k++)
+ block_inflated_base[j * dim + chunk_offsets[i] + k] =
+ cur_pivot_data[closest_center[j] * cur_chunk_size + k] + centroid[chunk_offsets[i] + k];
+#endif
+ }
+ }
+
+ if (num_centers > 256)
+ {
+ compressed_file_writer.write((char *)(block_compressed_base.get()),
+ cur_blk_size * num_pq_chunks * sizeof(uint32_t));
+ }
+ else
+ {
+ std::unique_ptr<uint8_t[]> pVec = std::make_unique<uint8_t[]>(cur_blk_size * num_pq_chunks);
+ diskann::convert_types<uint32_t, uint8_t>(block_compressed_base.get(), pVec.get(), cur_blk_size,
+ num_pq_chunks);
+ compressed_file_writer.write((char *)(pVec.get()), cur_blk_size * num_pq_chunks * sizeof(uint8_t));
+ }
+#ifdef SAVE_INFLATED_PQ
+ inflated_file_writer.write((char *)(block_inflated_base.get()), cur_blk_size * dim * sizeof(float));
+#endif
+ diskann::cout << ".done." << std::endl;
+ }
+// Gopal. Splitting diskann_dll into separate DLLs for search and build.
+// This code should only be available in the "build" DLL.
+#if defined(DISKANN_RELEASE_UNUSED_TCMALLOC_MEMORY_AT_CHECKPOINTS) && defined(DISKANN_BUILD)
+ MallocExtension::instance()->ReleaseFreeMemory();
+#endif
+ compressed_file_writer.close();
+#ifdef SAVE_INFLATED_PQ
+ inflated_file_writer.close();
+#endif
+ return 0;
+}
+
+template <typename T>
+void generate_disk_quantized_data(const std::string &data_file_to_use, const std::string &disk_pq_pivots_path,
+ const std::string &disk_pq_compressed_vectors_path, diskann::Metric compareMetric,
+ const double p_val, size_t &disk_pq_dims)
+{
+ size_t train_size, train_dim;
+ float *train_data;
+
+ // instantiates train_data with random sample updates train_size
+ gen_random_slice<T>(data_file_to_use.c_str(), p_val, train_data, train_size, train_dim);
+ diskann::cout << "Training data with " << train_size << " samples loaded." << std::endl;
+
+ if (disk_pq_dims > train_dim)
+ disk_pq_dims = train_dim;
+
+ std::cout << "Compressing base for disk-PQ into " << disk_pq_dims << " chunks " << std::endl;
+ generate_pq_pivots(train_data, train_size, (uint32_t)train_dim, 256, (uint32_t)disk_pq_dims, NUM_KMEANS_REPS_PQ,
+ disk_pq_pivots_path, false);
+ if (compareMetric == diskann::Metric::INNER_PRODUCT)
+ generate_pq_data_from_pivots<float>(data_file_to_use, 256, (uint32_t)disk_pq_dims, disk_pq_pivots_path,
+ disk_pq_compressed_vectors_path);
+ else
+ generate_pq_data_from_pivots<T>(data_file_to_use, 256, (uint32_t)disk_pq_dims, disk_pq_pivots_path,
+ disk_pq_compressed_vectors_path);
+
+ delete[] train_data;
+}
+
+template <typename T>
+void generate_quantized_data(const std::string &data_file_to_use, const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path, diskann::Metric compareMetric,
+ const double p_val, const uint64_t num_pq_chunks, const bool use_opq,
+ const std::string &codebook_prefix)
+{
+ size_t train_size, train_dim;
+ float *train_data;
+ if (!file_exists(codebook_prefix))
+ {
+ // instantiates train_data with random sample updates train_size
+ gen_random_slice<T>(data_file_to_use.c_str(), p_val, train_data, train_size, train_dim);
+ diskann::cout << "Training data with " << train_size << " samples loaded." << std::endl;
+
+ bool make_zero_mean = true;
+ if (compareMetric == diskann::Metric::INNER_PRODUCT)
+ make_zero_mean = false;
+ if (use_opq) // we also do not center the data for OPQ
+ make_zero_mean = false;
+
+ if (!use_opq)
+ {
+ generate_pq_pivots(train_data, train_size, (uint32_t)train_dim, NUM_PQ_CENTROIDS, (uint32_t)num_pq_chunks,
+ NUM_KMEANS_REPS_PQ, pq_pivots_path, make_zero_mean);
+ }
+ else
+ {
+ generate_opq_pivots(train_data, train_size, (uint32_t)train_dim, NUM_PQ_CENTROIDS, (uint32_t)num_pq_chunks,
+ pq_pivots_path, make_zero_mean);
+ }
+ delete[] train_data;
+ }
+ else
+ {
+ diskann::cout << "Skip Training with predefined pivots in: " << pq_pivots_path << std::endl;
+ if (!file_exists(pq_compressed_vectors_path))
+ {
+ diskann::cout << "! Pivot exists, but compressed vectors do not exist, please check the file path"
+ << std::endl;
+ diskann::cout << "It's " << pq_compressed_vectors_path << " and " << pq_pivots_path << std::endl;
+ assert(false);
+ }
+ return;
+ }
+ generate_pq_data_from_pivots<T>(data_file_to_use, NUM_PQ_CENTROIDS, (uint32_t)num_pq_chunks, pq_pivots_path,
+ pq_compressed_vectors_path, use_opq);
+}
+
+// Instantations of supported templates
+
+template DISKANN_DLLEXPORT int generate_pq_data_from_pivots<int8_t>(const std::string &data_file, uint32_t num_centers,
+ uint32_t num_pq_chunks,
+ const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path,
+ bool use_opq);
+template DISKANN_DLLEXPORT int generate_pq_data_from_pivots<uint8_t>(const std::string &data_file, uint32_t num_centers,
+ uint32_t num_pq_chunks,
+ const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path,
+ bool use_opq);
+template DISKANN_DLLEXPORT int generate_pq_data_from_pivots<float>(const std::string &data_file, uint32_t num_centers,
+ uint32_t num_pq_chunks,
+ const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path,
+ bool use_opq);
+
+template DISKANN_DLLEXPORT void generate_disk_quantized_data<int8_t>(const std::string &data_file_to_use,
+ const std::string &disk_pq_pivots_path,
+ const std::string &disk_pq_compressed_vectors_path,
+ diskann::Metric compareMetric, const double p_val,
+ size_t &disk_pq_dims);
+
+template DISKANN_DLLEXPORT void generate_disk_quantized_data<uint8_t>(
+ const std::string &data_file_to_use, const std::string &disk_pq_pivots_path,
+ const std::string &disk_pq_compressed_vectors_path, diskann::Metric compareMetric, const double p_val,
+ size_t &disk_pq_dims);
+
+template DISKANN_DLLEXPORT void generate_disk_quantized_data<float>(const std::string &data_file_to_use,
+ const std::string &disk_pq_pivots_path,
+ const std::string &disk_pq_compressed_vectors_path,
+ diskann::Metric compareMetric, const double p_val,
+ size_t &disk_pq_dims);
+
+template DISKANN_DLLEXPORT void generate_quantized_data<int8_t>(const std::string &data_file_to_use,
+ const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path,
+ diskann::Metric compareMetric, const double p_val,
+ const uint64_t num_pq_chunks, const bool use_opq,
+ const std::string &codebook_prefix);
+
+template DISKANN_DLLEXPORT void generate_quantized_data<uint8_t>(const std::string &data_file_to_use,
+ const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path,
+ diskann::Metric compareMetric, const double p_val,
+ const uint64_t num_pq_chunks, const bool use_opq,
+ const std::string &codebook_prefix);
+
+template DISKANN_DLLEXPORT void generate_quantized_data<float>(const std::string &data_file_to_use,
+ const std::string &pq_pivots_path,
+ const std::string &pq_compressed_vectors_path,
+ diskann::Metric compareMetric, const double p_val,
+ const uint64_t num_pq_chunks, const bool use_opq,
+ const std::string &codebook_prefix);
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/pq_data_store.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/pq_data_store.cpp
new file mode 100644
index 0000000..491975e
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/pq_data_store.cpp
@@ -0,0 +1,260 @@
+#include <exception>
+
+#include "pq_data_store.h"
+#include "pq.h"
+#include "pq_scratch.h"
+#include "utils.h"
+#include "distance.h"
+
+namespace diskann
+{
+
+// REFACTOR TODO: Assuming that num_pq_chunks is known already. Must verify if
+// this is true.
+template <typename data_t>
+PQDataStore<data_t>::PQDataStore(size_t dim, location_t num_points, size_t num_pq_chunks,
+ std::unique_ptr<Distance<data_t>> distance_fn,
+ std::unique_ptr<QuantizedDistance<data_t>> pq_distance_fn)
+ : AbstractDataStore<data_t>(num_points, dim), _quantized_data(nullptr), _num_chunks(num_pq_chunks),
+ _distance_metric(distance_fn->get_metric())
+{
+ if (num_pq_chunks > dim)
+ {
+ throw diskann::ANNException("ERROR: num_pq_chunks > dim", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ _distance_fn = std::move(distance_fn);
+ _pq_distance_fn = std::move(pq_distance_fn);
+}
+
+template <typename data_t> PQDataStore<data_t>::~PQDataStore()
+{
+ if (_quantized_data != nullptr)
+ {
+ aligned_free(_quantized_data);
+ _quantized_data = nullptr;
+ }
+}
+
+template <typename data_t> location_t PQDataStore<data_t>::load(const std::string &filename)
+{
+ return load_impl(filename);
+}
+template <typename data_t> size_t PQDataStore<data_t>::save(const std::string &filename, const location_t num_points)
+{
+ return diskann::save_bin(filename, _quantized_data, this->capacity(), _num_chunks, 0);
+}
+
+template <typename data_t> size_t PQDataStore<data_t>::get_aligned_dim() const
+{
+ return this->get_dims();
+}
+
+// Populate quantized data from regular data.
+template <typename data_t> void PQDataStore<data_t>::populate_data(const data_t *vectors, const location_t num_pts)
+{
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t> void PQDataStore<data_t>::populate_data(const std::string &filename, const size_t offset)
+{
+ if (_quantized_data != nullptr)
+ {
+ aligned_free(_quantized_data);
+ }
+
+ size_t file_num_points = 0, file_dim = 0;
+ get_bin_metadata(filename, file_num_points, file_dim, offset);
+ this->_capacity = (location_t)file_num_points;
+ this->_dim = file_dim;
+
+ double p_val = std::min(1.0, ((double)MAX_PQ_TRAINING_SET_SIZE / (double)file_num_points));
+
+ auto pivots_file = _pq_distance_fn->get_pivot_data_filename(filename);
+ auto compressed_file = _pq_distance_fn->get_quantized_vectors_filename(filename);
+
+ generate_quantized_data<data_t>(filename, pivots_file, compressed_file, _distance_metric, p_val, _num_chunks,
+ _pq_distance_fn->is_opq());
+
+ // REFACTOR TODO: Not sure of the alignment. Just copying from index.cpp
+ alloc_aligned(((void **)&_quantized_data), file_num_points * _num_chunks * sizeof(uint8_t), 1);
+ copy_aligned_data_from_file<uint8_t>(compressed_file.c_str(), _quantized_data, file_num_points, _num_chunks,
+ _num_chunks);
+#ifdef EXEC_ENV_OLS
+ throw ANNException("load_pq_centroid_bin should not be called when "
+ "EXEC_ENV_OLS is defined.",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+#else
+ _pq_distance_fn->load_pivot_data(pivots_file.c_str(), _num_chunks);
+#endif
+}
+
+template <typename data_t>
+void PQDataStore<data_t>::extract_data_to_bin(const std::string &filename, const location_t num_pts)
+{
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t> void PQDataStore<data_t>::get_vector(const location_t i, data_t *target) const
+{
+ // REFACTOR TODO: Should we inflate the compressed vector here?
+ if (i < this->capacity())
+ {
+ throw std::logic_error("Not implemented yet.");
+ }
+ else
+ {
+ std::stringstream ss;
+ ss << "Requested vector " << i << " but only " << this->capacity() << " vectors are present";
+ throw diskann::ANNException(ss.str(), -1);
+ }
+}
+template <typename data_t> void PQDataStore<data_t>::set_vector(const location_t i, const data_t *const vector)
+{
+ // REFACTOR TODO: Should we accept a normal vector and compress here?
+ // memcpy (_data + i * _num_chunks, vector, _num_chunks * sizeof(data_t));
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t> void PQDataStore<data_t>::prefetch_vector(const location_t loc)
+{
+ const uint8_t *ptr = _quantized_data + ((size_t)loc) * _num_chunks * sizeof(data_t);
+ diskann::prefetch_vector((const char *)ptr, _num_chunks * sizeof(data_t));
+}
+
+template <typename data_t>
+void PQDataStore<data_t>::move_vectors(const location_t old_location_start, const location_t new_location_start,
+ const location_t num_points)
+{
+ // REFACTOR TODO: Moving vectors is only for in-mem fresh.
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t>
+void PQDataStore<data_t>::copy_vectors(const location_t from_loc, const location_t to_loc, const location_t num_points)
+{
+ // REFACTOR TODO: Is the number of bytes correct?
+ memcpy(_quantized_data + to_loc * _num_chunks, _quantized_data + from_loc * _num_chunks, _num_chunks * num_points);
+}
+
+// REFACTOR TODO: Currently, we take aligned_query as parameter, but this
+// function should also do the alignment.
+template <typename data_t>
+void PQDataStore<data_t>::preprocess_query(const data_t *aligned_query, AbstractScratch<data_t> *scratch) const
+{
+ if (scratch == nullptr)
+ {
+ throw diskann::ANNException("Scratch space is null", -1);
+ }
+
+ PQScratch<data_t> *pq_scratch = scratch->pq_scratch();
+
+ if (pq_scratch == nullptr)
+ {
+ throw diskann::ANNException("PQScratch space has not been set in the scratch object.", -1);
+ }
+
+ _pq_distance_fn->preprocess_query(aligned_query, (location_t)this->get_dims(), *pq_scratch);
+}
+
+template <typename data_t> float PQDataStore<data_t>::get_distance(const data_t *query, const location_t loc) const
+{
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t> float PQDataStore<data_t>::get_distance(const location_t loc1, const location_t loc2) const
+{
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t>
+void PQDataStore<data_t>::get_distance(const data_t *preprocessed_query, const location_t *locations,
+ const uint32_t location_count, float *distances,
+ AbstractScratch<data_t> *scratch_space) const
+{
+ if (scratch_space == nullptr)
+ {
+ throw diskann::ANNException("Scratch space is null", -1);
+ }
+ PQScratch<data_t> *pq_scratch = scratch_space->pq_scratch();
+ if (pq_scratch == nullptr)
+ {
+ throw diskann::ANNException("PQScratch not set in scratch space.", -1);
+ }
+ diskann::aggregate_coords(locations, location_count, _quantized_data, this->_num_chunks,
+ pq_scratch->aligned_pq_coord_scratch);
+ _pq_distance_fn->preprocessed_distance(*pq_scratch, location_count, distances);
+}
+
+template <typename data_t>
+void PQDataStore<data_t>::get_distance(const data_t *preprocessed_query, const std::vector<location_t> &ids,
+ std::vector<float> &distances, AbstractScratch<data_t> *scratch_space) const
+{
+ if (scratch_space == nullptr)
+ {
+ throw diskann::ANNException("Scratch space is null", -1);
+ }
+ PQScratch<data_t> *pq_scratch = scratch_space->pq_scratch();
+ if (pq_scratch == nullptr)
+ {
+ throw diskann::ANNException("PQScratch not set in scratch space.", -1);
+ }
+ diskann::aggregate_coords(ids, _quantized_data, this->_num_chunks, pq_scratch->aligned_pq_coord_scratch);
+ _pq_distance_fn->preprocessed_distance(*pq_scratch, (location_t)ids.size(), distances);
+}
+
+template <typename data_t> location_t PQDataStore<data_t>::calculate_medoid() const
+{
+ // REFACTOR TODO: Must calculate this just like we do with data store.
+ size_t r = (size_t)rand() * (size_t)RAND_MAX + (size_t)rand();
+ return (uint32_t)(r % (size_t)this->capacity());
+}
+
+template <typename data_t> size_t PQDataStore<data_t>::get_alignment_factor() const
+{
+ return 1;
+}
+
+template <typename data_t> Distance<data_t> *PQDataStore<data_t>::get_dist_fn() const
+{
+ return _distance_fn.get();
+}
+
+template <typename data_t> location_t PQDataStore<data_t>::load_impl(const std::string &file_prefix)
+{
+ if (_quantized_data != nullptr)
+ {
+ aligned_free(_quantized_data);
+ }
+ auto quantized_vectors_file = _pq_distance_fn->get_quantized_vectors_filename(file_prefix);
+
+ size_t num_points;
+ load_aligned_bin(quantized_vectors_file, _quantized_data, num_points, _num_chunks, _num_chunks);
+ this->_capacity = (location_t)num_points;
+
+ auto pivots_file = _pq_distance_fn->get_pivot_data_filename(file_prefix);
+ _pq_distance_fn->load_pivot_data(pivots_file, _num_chunks);
+
+ return this->_capacity;
+}
+
+template <typename data_t> location_t PQDataStore<data_t>::expand(const location_t new_size)
+{
+ throw std::logic_error("Not implemented yet");
+}
+
+template <typename data_t> location_t PQDataStore<data_t>::shrink(const location_t new_size)
+{
+ throw std::logic_error("Not implemented yet");
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename data_t> location_t PQDataStore<data_t>::load_impl(AlignedFileReader &reader)
+{
+}
+#endif
+
+template DISKANN_DLLEXPORT class PQDataStore<int8_t>;
+template DISKANN_DLLEXPORT class PQDataStore<float>;
+template DISKANN_DLLEXPORT class PQDataStore<uint8_t>;
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/pq_flash_index.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/pq_flash_index.cpp
new file mode 100644
index 0000000..bfb0abb
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/pq_flash_index.cpp
@@ -0,0 +1,2964 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "common_includes.h"
+
+#include <algorithm>
+#include <memory>
+#include <cmath>
+
+#include "timer.h"
+#include "pq.h"
+#include "pq_scratch.h"
+#include "pq_flash_index.h"
+#include "cosine_similarity.h"
+#include "embedding.pb.h" // from embedding.proto -> embedding.pb.h
+#include <zmq.h>
+#include <fstream>
+#include <atomic>
+#include <mutex>
+#include <filesystem>
+
+#ifdef _WINDOWS
+#include "windows_aligned_file_reader.h"
+#elif __APPLE__
+#include "apple_aligned_file_reader.h"
+#else
+#include "linux_aligned_file_reader.h"
+#endif
+
+#define READ_U64(stream, val) stream.read((char *)&val, sizeof(uint64_t))
+#define READ_U32(stream, val) stream.read((char *)&val, sizeof(uint32_t))
+#define READ_UNSIGNED(stream, val) stream.read((char *)&val, sizeof(unsigned))
+
+// sector # beyond the end of graph where data for id is present for reordering
+#define VECTOR_SECTOR_NO(id) (((uint64_t)(id)) / _nvecs_per_sector + _reorder_data_start_sector)
+
+// sector # beyond the end of graph where data for id is present for reordering
+#define VECTOR_SECTOR_OFFSET(id) ((((uint64_t)(id)) % _nvecs_per_sector) * _data_dim * sizeof(float))
+
+namespace diskann
+{
+static std::mutex log_file_mutex;
+static std::atomic<int> search_counter(0);
+
+template <typename T, typename LabelT>
+PQFlashIndex<T, LabelT>::PQFlashIndex(std::shared_ptr<AlignedFileReader> &fileReader,
+ std::shared_ptr<AlignedFileReader> &graphReader, diskann::Metric m)
+ : reader(fileReader), graph_reader(graphReader), metric(m), _thread_data(nullptr)
+{
+ diskann::Metric metric_to_invoke = m;
+ if (m == diskann::Metric::COSINE || m == diskann::Metric::INNER_PRODUCT)
+ {
+ if (std::is_floating_point<T>::value)
+ {
+ diskann::cout << "Since data is floating point, we assume that it has been appropriately pre-processed "
+ "(normalization for cosine, and convert-to-l2 by adding extra dimension for MIPS). So we "
+ "shall invoke an l2 distance function."
+ << std::endl;
+ metric_to_invoke = diskann::Metric::L2;
+ }
+ else
+ {
+ diskann::cerr << "WARNING: Cannot normalize integral data types."
+ << " This may result in erroneous results or poor recall."
+ << " Consider using L2 distance with integral data types." << std::endl;
+ }
+ }
+
+ this->_dist_cmp.reset(diskann::get_distance_function<T>(metric_to_invoke));
+ this->_dist_cmp_float.reset(diskann::get_distance_function<float>(metric_to_invoke));
+}
+
+template <typename T, typename LabelT> PQFlashIndex<T, LabelT>::~PQFlashIndex()
+{
+#ifndef EXEC_ENV_OLS
+ if (data != nullptr)
+ {
+ delete[] data;
+ }
+#endif
+
+ if (_centroid_data != nullptr)
+ aligned_free(_centroid_data);
+ // delete backing bufs for nhood and coord cache
+ if (_nhood_cache_buf != nullptr)
+ {
+ delete[] _nhood_cache_buf;
+ diskann::aligned_free(_coord_cache_buf);
+ }
+
+ if (_load_flag)
+ {
+ diskann::cout << "Clearing scratch" << std::endl;
+ ScratchStoreManager<SSDThreadData<T>> manager(this->_thread_data);
+ manager.destroy();
+ this->reader->deregister_all_threads();
+ reader->close();
+ }
+ if (_pts_to_label_offsets != nullptr)
+ {
+ delete[] _pts_to_label_offsets;
+ }
+ if (_pts_to_label_counts != nullptr)
+ {
+ delete[] _pts_to_label_counts;
+ }
+ if (_pts_to_labels != nullptr)
+ {
+ delete[] _pts_to_labels;
+ }
+ if (_medoids != nullptr)
+ {
+ delete[] _medoids;
+ }
+}
+
+template <typename T, typename LabelT> inline uint64_t PQFlashIndex<T, LabelT>::get_node_sector(uint64_t node_id)
+{
+ return 1 + (_nnodes_per_sector > 0 ? node_id / _nnodes_per_sector
+ : node_id * DIV_ROUND_UP(_max_node_len, defaults::SECTOR_LEN));
+}
+
+template <typename T, typename LabelT>
+inline char *PQFlashIndex<T, LabelT>::offset_to_node(char *sector_buf, uint64_t node_id)
+{
+ return sector_buf + (_nnodes_per_sector == 0 ? 0 : (node_id % _nnodes_per_sector) * _max_node_len);
+}
+
+template <typename T, typename LabelT> inline uint32_t *PQFlashIndex<T, LabelT>::offset_to_node_nhood(char *node_buf)
+{
+ return (unsigned *)(node_buf + _disk_bytes_per_point);
+}
+
+template <typename T, typename LabelT> inline T *PQFlashIndex<T, LabelT>::offset_to_node_coords(char *node_buf)
+{
+ return (T *)(node_buf);
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::setup_thread_data(uint64_t nthreads, uint64_t visited_reserve)
+{
+ diskann::cout << "Setting up thread-specific contexts for nthreads: " << nthreads << std::endl;
+// omp parallel for to generate unique thread IDs
+#pragma omp parallel for num_threads((int)nthreads)
+ for (int64_t thread = 0; thread < (int64_t)nthreads; thread++)
+ {
+#pragma omp critical
+ {
+ SSDThreadData<T> *data = new SSDThreadData<T>(this->_aligned_dim, visited_reserve);
+ this->reader->register_thread();
+ data->ctx = this->reader->get_ctx();
+ this->_thread_data.push(data);
+ }
+ }
+ _load_flag = true;
+}
+
+template <typename T, typename LabelT>
+std::vector<bool> PQFlashIndex<T, LabelT>::read_nodes(const std::vector<uint32_t> &node_ids,
+ std::vector<T *> &coord_buffers,
+ std::vector<std::pair<uint32_t, uint32_t *>> &nbr_buffers)
+{
+ std::vector<AlignedRead> read_reqs;
+ std::vector<bool> retval(node_ids.size(), true);
+
+ char *buf = nullptr;
+ auto num_sectors = _nnodes_per_sector > 0 ? 1 : DIV_ROUND_UP(_max_node_len, defaults::SECTOR_LEN);
+
+ // borrow thread data and issue reads
+ ScratchStoreManager<SSDThreadData<T>> manager(this->_thread_data);
+ auto this_thread_data = manager.scratch_space();
+ IOContext &ctx = this_thread_data->ctx;
+
+#if 1
+ // -- If not partition_read, this is the normal DiskANN approach:
+ if (!_use_partition)
+ {
+#endif
+ // (1) read each node's 4 KB from offset = get_node_sector(node_id)*4096
+ alloc_aligned((void **)&buf, node_ids.size() * num_sectors * defaults::SECTOR_LEN, defaults::SECTOR_LEN);
+
+ // create read requests
+ for (size_t i = 0; i < node_ids.size(); ++i)
+ {
+ auto node_id = node_ids[i];
+
+ AlignedRead read;
+ read.len = num_sectors * defaults::SECTOR_LEN;
+ read.buf = buf + i * num_sectors * defaults::SECTOR_LEN;
+ read.offset = get_node_sector(node_id) * defaults::SECTOR_LEN;
+ read_reqs.push_back(read);
+ }
+
+ reader->read(read_reqs, ctx);
+
+ // copy reads into buffers
+ for (uint32_t i = 0; i < read_reqs.size(); i++)
+ {
+#if defined(_WINDOWS) && defined(USE_BING_INFRA) // this block is to handle failed reads in
+ // production settings
+ if ((*ctx.m_pRequestsStatus)[i] != IOContext::READ_SUCCESS)
+ {
+ retval[i] = false;
+ continue;
+ }
+#endif
+
+ char *node_buf = offset_to_node((char *)read_reqs[i].buf, node_ids[i]);
+
+ if (coord_buffers[i] != nullptr)
+ {
+ T *node_coords = offset_to_node_coords(node_buf);
+ memcpy(coord_buffers[i], node_coords, _disk_bytes_per_point);
+ }
+
+ if (nbr_buffers[i].second != nullptr)
+ {
+ uint32_t *node_nhood = offset_to_node_nhood(node_buf);
+ auto num_nbrs = *node_nhood;
+ nbr_buffers[i].first = num_nbrs;
+ memcpy(nbr_buffers[i].second, node_nhood + 1, num_nbrs * sizeof(uint32_t));
+ }
+ }
+ aligned_free(buf);
+
+ if (!_use_partition)
+ {
+ // done with the normal path
+ return retval;
+ }
+#if 1
+ }
+#endif
+
+ {
+ // 计算每个节点的分区偏移
+ std::vector<std::pair<uint64_t, uint64_t>> offsets(node_ids.size());
+ std::vector<bool> valid_nodes(node_ids.size(), true);
+
+ // 按分区分组,减少重复读取相同分区
+ std::map<uint32_t, std::vector<size_t>> partition_to_indices;
+
+ // 遍历所有节点,获取其分区信息
+ for (size_t i = 0; i < node_ids.size(); i++)
+ {
+ uint32_t node_id = node_ids[i];
+ if (nbr_buffers[i].second != nullptr)
+ {
+ // 使用read_neighbors中的逻辑获取分区ID
+ uint32_t partition_id = _id2partition[node_id];
+ if (partition_id >= _num_partitions)
+ {
+ valid_nodes[i] = false;
+ retval[i] = false;
+ continue;
+ }
+
+ // 将节点按分区ID分组
+ partition_to_indices[partition_id].push_back(i);
+ }
+ }
+
+ // 对每个分区执行一次读取
+ for (const auto &pair : partition_to_indices)
+ {
+ uint32_t partition_id = pair.first;
+ const auto &indices = pair.second;
+
+ // 计算扇区偏移 (与read_neighbors中相同)
+ uint64_t sector_offset = (partition_id + 1) * defaults::SECTOR_LEN;
+
+ // 读取分区扇区
+ char *sector_buf = nullptr;
+ alloc_aligned((void **)&sector_buf, defaults::SECTOR_LEN, defaults::SECTOR_LEN);
+
+ AlignedRead read;
+ read.len = defaults::SECTOR_LEN;
+ read.buf = sector_buf;
+ read.offset = sector_offset;
+
+ std::vector<AlignedRead> single_read = {read};
+ graph_reader->read(single_read, ctx);
+
+ // 处理该分区中的所有节点
+ for (size_t idx : indices)
+ {
+ uint32_t node_id = node_ids[idx];
+
+ // 查找节点在分区内的位置 (与read_neighbors中相同)
+ const auto &part_list = _graph_partitions[partition_id];
+ auto it = std::find(part_list.begin(), part_list.end(), node_id);
+ if (it == part_list.end())
+ {
+ retval[idx] = false;
+ continue;
+ }
+ size_t j = std::distance(part_list.begin(), it);
+
+ // 计算节点在扇区内的偏移 (与read_neighbors中相同)
+ uint64_t node_offset = j * _graph_node_len;
+ if (node_offset + 4 > defaults::SECTOR_LEN)
+ {
+ retval[idx] = false;
+ continue;
+ }
+
+ // 读取邻居数量
+ char *adjacency_ptr = sector_buf + node_offset;
+ uint32_t neighbor_count = *reinterpret_cast<uint32_t *>(adjacency_ptr);
+
+ // 检查邻居数据是否超出扇区范围
+ size_t needed = neighbor_count * sizeof(uint32_t);
+ if (node_offset + 4 + needed > defaults::SECTOR_LEN)
+ {
+ retval[idx] = false;
+ continue;
+ }
+
+ // 拷贝邻居数据
+ nbr_buffers[idx].first = neighbor_count;
+ memcpy(nbr_buffers[idx].second, adjacency_ptr + 4, needed);
+ }
+
+ aligned_free(sector_buf);
+ }
+ }
+
+ return retval;
+}
+
+template <typename T, typename LabelT> void PQFlashIndex<T, LabelT>::load_cache_list(std::vector<uint32_t> &node_list)
+{
+ diskann::cout << "Loading the cache list into memory.." << std::flush;
+ size_t num_cached_nodes = node_list.size();
+
+ // Allocate space for neighborhood cache
+ _nhood_cache_buf = new uint32_t[num_cached_nodes * (_max_degree + 1)];
+ memset(_nhood_cache_buf, 0, num_cached_nodes * (_max_degree + 1));
+
+ // Allocate space for coordinate cache
+ size_t coord_cache_buf_len = num_cached_nodes * _aligned_dim;
+ diskann::alloc_aligned((void **)&_coord_cache_buf, coord_cache_buf_len * sizeof(T), 8 * sizeof(T));
+ memset(_coord_cache_buf, 0, coord_cache_buf_len * sizeof(T));
+
+ size_t BLOCK_SIZE = 8;
+ size_t num_blocks = DIV_ROUND_UP(num_cached_nodes, BLOCK_SIZE);
+ for (size_t block = 0; block < num_blocks; block++)
+ {
+ size_t start_idx = block * BLOCK_SIZE;
+ size_t end_idx = (std::min)(num_cached_nodes, (block + 1) * BLOCK_SIZE);
+
+ // Copy offset into buffers to read into
+ std::vector<uint32_t> nodes_to_read;
+ std::vector<T *> coord_buffers;
+ std::vector<std::pair<uint32_t, uint32_t *>> nbr_buffers;
+ for (size_t node_idx = start_idx; node_idx < end_idx; node_idx++)
+ {
+ nodes_to_read.push_back(node_list[node_idx]);
+ coord_buffers.push_back(_coord_cache_buf + node_idx * _aligned_dim);
+ nbr_buffers.emplace_back(0, _nhood_cache_buf + node_idx * (_max_degree + 1));
+ }
+
+ // issue the reads
+ auto read_status = read_nodes(nodes_to_read, coord_buffers, nbr_buffers);
+
+ // check for success and insert into the cache.
+ for (size_t i = 0; i < read_status.size(); i++)
+ {
+ if (read_status[i] == true)
+ {
+ _coord_cache.insert(std::make_pair(nodes_to_read[i], coord_buffers[i]));
+ _nhood_cache.insert(std::make_pair(nodes_to_read[i], nbr_buffers[i]));
+ }
+ }
+ }
+ diskann::cout << "..done." << std::endl;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::generate_cache_list_from_sample_queries(MemoryMappedFiles &files, std::string sample_bin,
+ uint64_t l_search, uint64_t beamwidth,
+ uint64_t num_nodes_to_cache, uint32_t nthreads,
+ std::vector<uint32_t> &node_list)
+{
+#else
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::generate_cache_list_from_sample_queries(std::string sample_bin, uint64_t l_search,
+ uint64_t beamwidth, uint64_t num_nodes_to_cache,
+ uint32_t nthreads,
+ std::vector<uint32_t> &node_list)
+{
+#endif
+ if (num_nodes_to_cache >= this->_num_points)
+ {
+ // for small num_points and big num_nodes_to_cache, use below way to get the node_list quickly
+ node_list.resize(this->_num_points);
+ for (uint32_t i = 0; i < this->_num_points; ++i)
+ {
+ node_list[i] = i;
+ }
+ return;
+ }
+
+ this->_count_visited_nodes = true;
+ this->_node_visit_counter.clear();
+ this->_node_visit_counter.resize(this->_num_points);
+ for (uint32_t i = 0; i < _node_visit_counter.size(); i++)
+ {
+ this->_node_visit_counter[i].first = i;
+ this->_node_visit_counter[i].second = 0;
+ }
+
+ size_t sample_num, sample_dim, sample_aligned_dim;
+ T *samples;
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(sample_bin))
+ {
+ diskann::load_aligned_bin<T>(files, sample_bin, samples, sample_num, sample_dim, sample_aligned_dim);
+ }
+#else
+ if (file_exists(sample_bin))
+ {
+ diskann::load_aligned_bin<T>(sample_bin, samples, sample_num, sample_dim, sample_aligned_dim);
+ }
+#endif
+ else
+ {
+ diskann::cerr << "Sample bin file not found. Not generating cache." << std::endl;
+ return;
+ }
+
+ std::vector<uint64_t> tmp_result_ids_64(sample_num, 0);
+ std::vector<float> tmp_result_dists(sample_num, 0);
+
+ bool filtered_search = false;
+ std::vector<LabelT> random_query_filters(sample_num);
+ if (_filter_to_medoid_ids.size() != 0)
+ {
+ filtered_search = true;
+ generate_random_labels(random_query_filters, (uint32_t)sample_num, nthreads);
+ }
+
+#pragma omp parallel for schedule(dynamic, 1) num_threads(nthreads)
+ for (int64_t i = 0; i < (int64_t)sample_num; i++)
+ {
+ auto &label_for_search = random_query_filters[i];
+ // run a search on the sample query with a random label (sampled from base label distribution), and it will
+ // concurrently update the node_visit_counter to track most visited nodes. The last false is to not use the
+ // "use_reorder_data" option which enables a final reranking if the disk index itself contains only PQ data.
+ cached_beam_search(samples + (i * sample_aligned_dim), 1, l_search, tmp_result_ids_64.data() + i,
+ tmp_result_dists.data() + i, beamwidth, filtered_search, label_for_search, false);
+ }
+
+ std::sort(this->_node_visit_counter.begin(), _node_visit_counter.end(),
+ [](std::pair<uint32_t, uint32_t> &left, std::pair<uint32_t, uint32_t> &right) {
+ return left.second > right.second;
+ });
+ node_list.clear();
+ node_list.shrink_to_fit();
+ num_nodes_to_cache = std::min((size_t)num_nodes_to_cache, this->_node_visit_counter.size());
+ node_list.reserve(num_nodes_to_cache);
+ for (uint64_t i = 0; i < num_nodes_to_cache; i++)
+ {
+ node_list.push_back(this->_node_visit_counter[i].first);
+ }
+ this->_count_visited_nodes = false;
+
+ diskann::aligned_free(samples);
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::cache_bfs_levels(uint64_t num_nodes_to_cache, std::vector<uint32_t> &node_list,
+ const bool shuffle)
+{
+ std::random_device rng;
+ std::mt19937 urng(rng());
+
+ tsl::robin_set<uint32_t> node_set;
+
+ // Do not cache more than 10% of the nodes in the index
+ uint64_t tenp_nodes = (uint64_t)(std::round(this->_num_points * 0.1));
+ if (num_nodes_to_cache > tenp_nodes)
+ {
+ diskann::cout << "Reducing nodes to cache from: " << num_nodes_to_cache << " to: " << tenp_nodes
+ << "(10 percent of total nodes:" << this->_num_points << ")" << std::endl;
+ num_nodes_to_cache = tenp_nodes == 0 ? 1 : tenp_nodes;
+ }
+ diskann::cout << "Caching " << num_nodes_to_cache << "..." << std::endl;
+
+ std::unique_ptr<tsl::robin_set<uint32_t>> cur_level, prev_level;
+ cur_level = std::make_unique<tsl::robin_set<uint32_t>>();
+ prev_level = std::make_unique<tsl::robin_set<uint32_t>>();
+
+ for (uint64_t miter = 0; miter < _num_medoids && cur_level->size() < num_nodes_to_cache; miter++)
+ {
+ cur_level->insert(_medoids[miter]);
+ }
+
+ if ((_filter_to_medoid_ids.size() > 0) && (cur_level->size() < num_nodes_to_cache))
+ {
+ for (auto &x : _filter_to_medoid_ids)
+ {
+ for (auto &y : x.second)
+ {
+ cur_level->insert(y);
+ if (cur_level->size() == num_nodes_to_cache)
+ break;
+ }
+ if (cur_level->size() == num_nodes_to_cache)
+ break;
+ }
+ }
+
+ uint64_t lvl = 1;
+ uint64_t prev_node_set_size = 0;
+ while ((node_set.size() + cur_level->size() < num_nodes_to_cache) && cur_level->size() != 0)
+ {
+ // swap prev_level and cur_level
+ std::swap(prev_level, cur_level);
+ // clear cur_level
+ cur_level->clear();
+
+ std::vector<uint32_t> nodes_to_expand;
+
+ for (const uint32_t &id : *prev_level)
+ {
+ if (node_set.find(id) != node_set.end())
+ {
+ continue;
+ }
+ node_set.insert(id);
+ nodes_to_expand.push_back(id);
+ }
+
+ if (shuffle)
+ std::shuffle(nodes_to_expand.begin(), nodes_to_expand.end(), urng);
+ else
+ std::sort(nodes_to_expand.begin(), nodes_to_expand.end());
+
+ diskann::cout << "Level: " << lvl << std::flush;
+ bool finish_flag = false;
+
+ size_t BLOCK_SIZE = 1024;
+ size_t nblocks = DIV_ROUND_UP(nodes_to_expand.size(), BLOCK_SIZE);
+ for (size_t block = 0; block < nblocks && !finish_flag; block++)
+ {
+ diskann::cout << "." << std::flush;
+ size_t start = block * BLOCK_SIZE;
+ size_t end = (std::min)((block + 1) * BLOCK_SIZE, nodes_to_expand.size());
+
+ std::vector<uint32_t> nodes_to_read;
+ std::vector<T *> coord_buffers(end - start, nullptr);
+ std::vector<std::pair<uint32_t, uint32_t *>> nbr_buffers;
+
+ for (size_t cur_pt = start; cur_pt < end; cur_pt++)
+ {
+ nodes_to_read.push_back(nodes_to_expand[cur_pt]);
+ nbr_buffers.emplace_back(0, new uint32_t[_max_degree + 1]);
+ }
+
+ // issue read requests
+ auto read_status = read_nodes(nodes_to_read, coord_buffers, nbr_buffers);
+
+ // process each nhood buf
+ for (uint32_t i = 0; i < read_status.size(); i++)
+ {
+ if (read_status[i] == false)
+ {
+ continue;
+ }
+ else
+ {
+ uint32_t nnbrs = nbr_buffers[i].first;
+ uint32_t *nbrs = nbr_buffers[i].second;
+
+ // explore next level
+ for (uint32_t j = 0; j < nnbrs && !finish_flag; j++)
+ {
+ if (node_set.find(nbrs[j]) == node_set.end())
+ {
+ cur_level->insert(nbrs[j]);
+ }
+ if (cur_level->size() + node_set.size() >= num_nodes_to_cache)
+ {
+ finish_flag = true;
+ }
+ }
+ }
+ delete[] nbr_buffers[i].second;
+ }
+ }
+
+ diskann::cout << ". #nodes: " << node_set.size() - prev_node_set_size
+ << ", #nodes thus far: " << node_set.size() << std::endl;
+ prev_node_set_size = node_set.size();
+ lvl++;
+ }
+
+ assert(node_set.size() + cur_level->size() == num_nodes_to_cache || cur_level->size() == 0);
+
+ node_list.clear();
+ node_list.reserve(node_set.size() + cur_level->size());
+ for (auto node : node_set)
+ node_list.push_back(node);
+ for (auto node : *cur_level)
+ node_list.push_back(node);
+
+ diskann::cout << "Level: " << lvl << std::flush;
+ diskann::cout << ". #nodes: " << node_list.size() - prev_node_set_size << ", #nodes thus far: " << node_list.size()
+ << std::endl;
+ diskann::cout << "done" << std::endl;
+}
+
+template <typename T, typename LabelT> void PQFlashIndex<T, LabelT>::use_medoids_data_as_centroids()
+{
+ if (_centroid_data != nullptr)
+ aligned_free(_centroid_data);
+ alloc_aligned(((void **)&_centroid_data), _num_medoids * _aligned_dim * sizeof(float), 32);
+ std::memset(_centroid_data, 0, _num_medoids * _aligned_dim * sizeof(float));
+
+ diskann::cout << "Loading centroid data from medoids vector data of " << _num_medoids << " medoid(s)" << std::endl;
+
+ std::vector<uint32_t> nodes_to_read;
+ std::vector<T *> medoid_bufs;
+ std::vector<std::pair<uint32_t, uint32_t *>> nbr_bufs;
+
+ for (uint64_t cur_m = 0; cur_m < _num_medoids; cur_m++)
+ {
+ nodes_to_read.push_back(_medoids[cur_m]);
+ medoid_bufs.push_back(new T[_data_dim]);
+ nbr_bufs.emplace_back(0, nullptr);
+ }
+
+ auto read_status = read_nodes(nodes_to_read, medoid_bufs, nbr_bufs);
+
+ for (uint64_t cur_m = 0; cur_m < _num_medoids; cur_m++)
+ {
+ if (read_status[cur_m] == true)
+ {
+ if (!_use_disk_index_pq)
+ {
+ for (uint32_t i = 0; i < _data_dim; i++)
+ _centroid_data[cur_m * _aligned_dim + i] = medoid_bufs[cur_m][i];
+ }
+ else
+ {
+ _disk_pq_table.inflate_vector((uint8_t *)medoid_bufs[cur_m], (_centroid_data + cur_m * _aligned_dim));
+ }
+ }
+ else
+ {
+ throw ANNException("Unable to read a medoid", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ delete[] medoid_bufs[cur_m];
+ }
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::generate_random_labels(std::vector<LabelT> &labels, const uint32_t num_labels,
+ const uint32_t nthreads)
+{
+ std::random_device rd;
+ labels.clear();
+ labels.resize(num_labels);
+
+ uint64_t num_total_labels = _pts_to_label_offsets[_num_points - 1] + _pts_to_label_counts[_num_points - 1];
+ std::mt19937 gen(rd());
+ if (num_total_labels == 0)
+ {
+ std::stringstream stream;
+ stream << "No labels found in data. Not sampling random labels ";
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ std::uniform_int_distribution<uint64_t> dis(0, num_total_labels - 1);
+
+#pragma omp parallel for schedule(dynamic, 1) num_threads(nthreads)
+ for (int64_t i = 0; i < num_labels; i++)
+ {
+ uint64_t rnd_loc = dis(gen);
+ labels[i] = (LabelT)_pts_to_labels[rnd_loc];
+ }
+}
+
+template <typename T, typename LabelT>
+std::unordered_map<std::string, LabelT> PQFlashIndex<T, LabelT>::load_label_map(std::basic_istream<char> &map_reader)
+{
+ std::unordered_map<std::string, LabelT> string_to_int_mp;
+ std::string line, token;
+ LabelT token_as_num;
+ std::string label_str;
+ while (std::getline(map_reader, line))
+ {
+ std::istringstream iss(line);
+ getline(iss, token, '\t');
+ label_str = token;
+ getline(iss, token, '\t');
+ token_as_num = (LabelT)std::stoul(token);
+ string_to_int_mp[label_str] = token_as_num;
+ }
+ return string_to_int_mp;
+}
+
+template <typename T, typename LabelT>
+LabelT PQFlashIndex<T, LabelT>::get_converted_label(const std::string &filter_label)
+{
+ if (_label_map.find(filter_label) != _label_map.end())
+ {
+ return _label_map[filter_label];
+ }
+ if (_use_universal_label)
+ {
+ return _universal_filter_label;
+ }
+ std::stringstream stream;
+ stream << "Unable to find label in the Label Map";
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::reset_stream_for_reading(std::basic_istream<char> &infile)
+{
+ infile.clear();
+ infile.seekg(0);
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::get_label_file_metadata(const std::string &fileContent, uint32_t &num_pts,
+ uint32_t &num_total_labels)
+{
+ num_pts = 0;
+ num_total_labels = 0;
+
+ size_t file_size = fileContent.length();
+
+ std::string label_str;
+ size_t cur_pos = 0;
+ size_t next_pos = 0;
+ while (cur_pos < file_size && cur_pos != std::string::npos)
+ {
+ next_pos = fileContent.find('\n', cur_pos);
+ if (next_pos == std::string::npos)
+ {
+ break;
+ }
+
+ size_t lbl_pos = cur_pos;
+ size_t next_lbl_pos = 0;
+ while (lbl_pos < next_pos && lbl_pos != std::string::npos)
+ {
+ next_lbl_pos = fileContent.find(',', lbl_pos);
+ if (next_lbl_pos == std::string::npos) // the last label
+ {
+ next_lbl_pos = next_pos;
+ }
+
+ num_total_labels++;
+
+ lbl_pos = next_lbl_pos + 1;
+ }
+
+ cur_pos = next_pos + 1;
+
+ num_pts++;
+ }
+
+ diskann::cout << "Labels file metadata: num_points: " << num_pts << ", #total_labels: " << num_total_labels
+ << std::endl;
+}
+
+template <typename T, typename LabelT>
+inline bool PQFlashIndex<T, LabelT>::point_has_label(uint32_t point_id, LabelT label_id)
+{
+ uint32_t start_vec = _pts_to_label_offsets[point_id];
+ uint32_t num_lbls = _pts_to_label_counts[point_id];
+ bool ret_val = false;
+ for (uint32_t i = 0; i < num_lbls; i++)
+ {
+ if (_pts_to_labels[start_vec + i] == label_id)
+ {
+ ret_val = true;
+ break;
+ }
+ }
+ return ret_val;
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::parse_label_file(std::basic_istream<char> &infile, size_t &num_points_labels)
+{
+ infile.seekg(0, std::ios::end);
+ size_t file_size = infile.tellg();
+
+ std::string buffer(file_size, ' ');
+
+ infile.seekg(0, std::ios::beg);
+ infile.read(&buffer[0], file_size);
+
+ std::string line;
+ uint32_t line_cnt = 0;
+
+ uint32_t num_pts_in_label_file;
+ uint32_t num_total_labels;
+ get_label_file_metadata(buffer, num_pts_in_label_file, num_total_labels);
+
+ _pts_to_label_offsets = new uint32_t[num_pts_in_label_file];
+ _pts_to_label_counts = new uint32_t[num_pts_in_label_file];
+ _pts_to_labels = new LabelT[num_total_labels];
+ uint32_t labels_seen_so_far = 0;
+
+ std::string label_str;
+ size_t cur_pos = 0;
+ size_t next_pos = 0;
+ while (cur_pos < file_size && cur_pos != std::string::npos)
+ {
+ next_pos = buffer.find('\n', cur_pos);
+ if (next_pos == std::string::npos)
+ {
+ break;
+ }
+
+ _pts_to_label_offsets[line_cnt] = labels_seen_so_far;
+ uint32_t &num_lbls_in_cur_pt = _pts_to_label_counts[line_cnt];
+ num_lbls_in_cur_pt = 0;
+
+ size_t lbl_pos = cur_pos;
+ size_t next_lbl_pos = 0;
+ while (lbl_pos < next_pos && lbl_pos != std::string::npos)
+ {
+ next_lbl_pos = buffer.find(',', lbl_pos);
+ if (next_lbl_pos == std::string::npos) // the last label in the whole file
+ {
+ next_lbl_pos = next_pos;
+ }
+
+ if (next_lbl_pos > next_pos) // the last label in one line, just read to the end
+ {
+ next_lbl_pos = next_pos;
+ }
+
+ label_str.assign(buffer.c_str() + lbl_pos, next_lbl_pos - lbl_pos);
+ if (label_str[label_str.length() - 1] == '\t') // '\t' won't exist in label file?
+ {
+ label_str.erase(label_str.length() - 1);
+ }
+
+ LabelT token_as_num = (LabelT)std::stoul(label_str);
+ _pts_to_labels[labels_seen_so_far++] = (LabelT)token_as_num;
+ num_lbls_in_cur_pt++;
+
+ // move to next label
+ lbl_pos = next_lbl_pos + 1;
+ }
+
+ // move to next line
+ cur_pos = next_pos + 1;
+
+ if (num_lbls_in_cur_pt == 0)
+ {
+ diskann::cout << "No label found for point " << line_cnt << std::endl;
+ exit(-1);
+ }
+
+ line_cnt++;
+ }
+
+ num_points_labels = line_cnt;
+ reset_stream_for_reading(infile);
+}
+
+template <typename T, typename LabelT> void PQFlashIndex<T, LabelT>::set_universal_label(const LabelT &label)
+{
+ _use_universal_label = true;
+ _universal_filter_label = label;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename LabelT>
+int PQFlashIndex<T, LabelT>::load(MemoryMappedFiles &files, uint32_t num_threads, const char *index_prefix,
+ const char *pq_prefix)
+{
+#else
+template <typename T, typename LabelT>
+int PQFlashIndex<T, LabelT>::load(uint32_t num_threads, const char *index_prefix, const char *pq_prefix,
+ const char *partition_prefix)
+{
+#endif
+ if (pq_prefix == nullptr || strcmp(pq_prefix, "") == 0)
+ {
+ pq_prefix = index_prefix;
+ }
+ if (partition_prefix != nullptr && strcmp(partition_prefix, "") != 0)
+ {
+ _use_partition = true;
+ }
+ std::string pq_table_bin = std::string(pq_prefix) + "_pq_pivots.bin";
+ std::string pq_compressed_vectors = std::string(pq_prefix) + "_pq_compressed.bin";
+ std::string _disk_index_file = std::string(index_prefix) + "_disk.index";
+ std::string graph_file = std::string(partition_prefix) + "_disk_graph.index";
+ std::string partition_file = std::string(partition_prefix) + "_partition.bin";
+#ifdef EXEC_ENV_OLS
+ return load_from_separate_paths(files, num_threads, _disk_index_file.c_str(), pq_table_bin.c_str(),
+ pq_compressed_vectors.c_str(), graph_file.c_str(), partition_file.c_str());
+#else
+ return load_from_separate_paths(num_threads, _disk_index_file.c_str(), pq_table_bin.c_str(),
+ pq_compressed_vectors.c_str(), graph_file.c_str(), partition_file.c_str());
+#endif
+}
+
+template <typename T, typename LabelT>
+int PQFlashIndex<T, LabelT>::read_partition_info(const std::string &partition_bin)
+{
+ std::ifstream pf(partition_bin, std::ios::binary);
+ if (!pf.is_open())
+ {
+ diskann::cout << "Cannot open partition.bin: " << partition_bin << std::endl;
+ return 1;
+ }
+ diskann::cout << "Loading partition info from " << partition_bin << std::endl;
+ uint64_t C, nd;
+ READ_U64(pf, C);
+ READ_U64(pf, _num_partitions);
+ READ_U64(pf, nd);
+ std::cout << "[partition.bin header] C=" << C << ", partition_nums=" << _num_partitions << ", nd=" << nd
+ << std::endl;
+
+ // 读取分区节点列表
+ _graph_partitions.resize(_num_partitions);
+ for (uint64_t i = 0; i < _num_partitions; i++)
+ {
+ uint32_t psize;
+ READ_U32(pf, psize);
+ _graph_partitions[i].resize(psize);
+ pf.read(reinterpret_cast<char *>(_graph_partitions[i].data()), psize * sizeof(uint32_t));
+ }
+ // 读取 _id2partition[node], 大小= nd
+ _id2partition.resize(nd);
+ pf.read(reinterpret_cast<char *>(_id2partition.data()), nd * sizeof(uint32_t));
+ pf.close();
+ std::cout << "Done loading partition info.\n";
+
+ return 0;
+}
+
+template <typename T, typename LabelT>
+int PQFlashIndex<T, LabelT>::load_graph_index(const std::string &graph_index_file)
+{
+ std::ifstream gf(graph_index_file, std::ios::binary);
+ if (!gf.is_open())
+ {
+ diskann::cout << "Cannot open disk_graph.index: " << graph_index_file << std::endl;
+ return 1;
+ }
+ diskann::cout << "Loading graph index from " << graph_index_file << std::endl;
+
+ // (a) sector0 => read 2 ints for meta_n and meta_dim
+ int meta_n, meta_dim;
+ gf.read((char *)&meta_n, sizeof(int));
+ gf.read((char *)&meta_dim, sizeof(int));
+ diskann::cout << "[debug] meta_n=" << meta_n << ", meta_dim=" << meta_dim << "\n";
+
+ // (b) Read uint64_t meta_n times
+ std::vector<uint64_t> meta_info(meta_n);
+ gf.read(reinterpret_cast<char *>(meta_info.data()), meta_n * sizeof(uint64_t));
+ for (int i = 0; i < meta_n; i++)
+ {
+ diskann::cout << " meta_info[" << i << "]= " << meta_info[i] << "\n";
+ }
+
+ size_t file_size = get_file_size(graph_index_file);
+ diskann::cout << "[disk_graph.index size] " << file_size << " bytes\n";
+
+ uint64_t nd_in_meta = meta_info[0];
+ uint64_t dim_in_meta = meta_info[1];
+ uint64_t max_node_len = meta_info[3];
+ uint64_t c_in_meta = meta_info[4];
+ uint64_t entire_file_sz = meta_info[8];
+
+ diskann::cout << "Based on meta_info:\n"
+ << " nd_in_meta= " << nd_in_meta << ", dim_in_meta= " << dim_in_meta
+ << ", max_node_len= " << max_node_len << ", c_in_meta= " << c_in_meta
+ << ", entire_file_size= " << entire_file_sz << "\n";
+
+ uint64_t dim_size = dim_in_meta * sizeof(float);
+
+ _graph_node_len = max_node_len - dim_size;
+
+#if 0
+ assert(max_node_len == _max_node_len);
+ assert(dim_size == _disk_bytes_per_point);
+ assert(_graph_node_len / sizeof(float) == _max_degree + 1);
+#endif
+
+ // Compensate the losting info from old meta_info
+ _max_degree = _graph_node_len / sizeof(float) - 1;
+ _disk_bytes_per_point = dim_size;
+ _max_node_len = max_node_len;
+
+ diskann::cout << " => graph_node_len= " << _graph_node_len << "\n\n";
+
+ return 0;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename LabelT>
+int PQFlashIndex<T, LabelT>::load_from_separate_paths(diskann::MemoryMappedFiles &files, uint32_t num_threads,
+ const char *index_filepath, const char *pivots_filepath,
+ const char *compressed_filepath, const char *graph_filepath)
+{
+#else
+template <typename T, typename LabelT>
+int PQFlashIndex<T, LabelT>::load_from_separate_paths(uint32_t num_threads, const char *index_filepath,
+ const char *pivots_filepath, const char *compressed_filepath,
+ const char *graph_file, const char *partition_file)
+{
+#endif
+ std::string pq_table_bin = pivots_filepath;
+ std::string pq_compressed_vectors = compressed_filepath;
+ std::string _disk_index_file = index_filepath;
+ // medoids, etc.
+ std::string medoids_file = std::string(_disk_index_file) + "_medoids.bin";
+ std::string centroids_file = std::string(_disk_index_file) + "_centroids.bin";
+
+ std::string labels_file = std::string(_disk_index_file) + "_labels.txt";
+ std::string labels_to_medoids = std::string(_disk_index_file) + "_labels_to_medoids.txt";
+ std::string dummy_map_file = std::string(_disk_index_file) + "_dummy_map.txt";
+ std::string labels_map_file = std::string(_disk_index_file) + "_labels_map.txt";
+
+ size_t num_pts_in_label_file = 0;
+
+ size_t pq_file_dim = 0, pq_file_num_centroids = 0;
+#ifdef EXEC_ENV_OLS
+ get_bin_metadata(files, pq_table_bin, pq_file_num_centroids, pq_file_dim, METADATA_SIZE);
+#else
+ get_bin_metadata(pq_table_bin, pq_file_num_centroids, pq_file_dim, METADATA_SIZE);
+#endif
+
+ this->_disk_index_file = _disk_index_file;
+
+ if (pq_file_num_centroids != 256)
+ {
+ diskann::cout << "Got " << pq_file_num_centroids << " PQ centroids, loading from " << pq_table_bin << std::endl;
+ diskann::cout << "Error. Number of PQ centroids is not 256. Exiting." << std::endl;
+ return -1;
+ }
+
+ this->_data_dim = pq_file_dim;
+ // will change later if we use PQ on disk or if we are using
+ // inner product without PQ
+ this->_disk_bytes_per_point = this->_data_dim * sizeof(T);
+ this->_aligned_dim = ROUND_UP(pq_file_dim, 8);
+
+ size_t npts_u64, nchunks_u64;
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<uint8_t>(files, pq_compressed_vectors, this->data, npts_u64, nchunks_u64);
+#else
+ diskann::load_bin<uint8_t>(pq_compressed_vectors, this->data, npts_u64, nchunks_u64);
+#endif
+
+ this->_num_points = npts_u64;
+ this->_n_chunks = nchunks_u64;
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(labels_file))
+ {
+ FileContent &content_labels = files.getContent(labels_file);
+ std::stringstream infile(std::string((const char *)content_labels._content, content_labels._size));
+#else
+ if (file_exists(labels_file))
+ {
+ std::ifstream infile(labels_file, std::ios::binary);
+ if (infile.fail())
+ {
+ throw diskann::ANNException(std::string("Failed to open file ") + labels_file, -1);
+ }
+#endif
+ parse_label_file(infile, num_pts_in_label_file);
+ assert(num_pts_in_label_file == this->_num_points);
+
+#ifndef EXEC_ENV_OLS
+ infile.close();
+#endif
+
+#ifdef EXEC_ENV_OLS
+ FileContent &content_labels_map = files.getContent(labels_map_file);
+ std::stringstream map_reader(std::string((const char *)content_labels_map._content, content_labels_map._size));
+#else
+ std::ifstream map_reader(labels_map_file);
+#endif
+ _label_map = load_label_map(map_reader);
+
+#ifndef EXEC_ENV_OLS
+ map_reader.close();
+#endif
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(labels_to_medoids))
+ {
+ FileContent &content_labels_to_meoids = files.getContent(labels_to_medoids);
+ std::stringstream medoid_stream(
+ std::string((const char *)content_labels_to_meoids._content, content_labels_to_meoids._size));
+#else
+ if (file_exists(labels_to_medoids))
+ {
+ std::ifstream medoid_stream(labels_to_medoids);
+ assert(medoid_stream.is_open());
+#endif
+ std::string line, token;
+
+ _filter_to_medoid_ids.clear();
+ try
+ {
+ while (std::getline(medoid_stream, line))
+ {
+ std::istringstream iss(line);
+ uint32_t cnt = 0;
+ std::vector<uint32_t> medoids;
+ LabelT label;
+ while (std::getline(iss, token, ','))
+ {
+ if (cnt == 0)
+ label = (LabelT)std::stoul(token);
+ else
+ medoids.push_back((uint32_t)stoul(token));
+ cnt++;
+ }
+ _filter_to_medoid_ids[label].swap(medoids);
+ }
+ }
+ catch (std::system_error &e)
+ {
+ throw FileException(labels_to_medoids, e, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+ std::string univ_label_file = std ::string(_disk_index_file) + "_universal_label.txt";
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(univ_label_file))
+ {
+ FileContent &content_univ_label = files.getContent(univ_label_file);
+ std::stringstream universal_label_reader(
+ std::string((const char *)content_univ_label._content, content_univ_label._size));
+#else
+ if (file_exists(univ_label_file))
+ {
+ std::ifstream universal_label_reader(univ_label_file);
+ assert(universal_label_reader.is_open());
+#endif
+ std::string univ_label;
+ universal_label_reader >> univ_label;
+#ifndef EXEC_ENV_OLS
+ universal_label_reader.close();
+#endif
+ LabelT label_as_num = (LabelT)std::stoul(univ_label);
+ set_universal_label(label_as_num);
+ }
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(dummy_map_file))
+ {
+ FileContent &content_dummy_map = files.getContent(dummy_map_file);
+ std::stringstream dummy_map_stream(
+ std::string((const char *)content_dummy_map._content, content_dummy_map._size));
+#else
+ if (file_exists(dummy_map_file))
+ {
+ std::ifstream dummy_map_stream(dummy_map_file);
+ assert(dummy_map_stream.is_open());
+#endif
+ std::string line, token;
+
+ while (std::getline(dummy_map_stream, line))
+ {
+ std::istringstream iss(line);
+ uint32_t cnt = 0;
+ uint32_t dummy_id;
+ uint32_t real_id;
+ while (std::getline(iss, token, ','))
+ {
+ if (cnt == 0)
+ dummy_id = (uint32_t)stoul(token);
+ else
+ real_id = (uint32_t)stoul(token);
+ cnt++;
+ }
+ _dummy_pts.insert(dummy_id);
+ _has_dummy_pts.insert(real_id);
+ _dummy_to_real_map[dummy_id] = real_id;
+
+ if (_real_to_dummy_map.find(real_id) == _real_to_dummy_map.end())
+ _real_to_dummy_map[real_id] = std::vector<uint32_t>();
+
+ _real_to_dummy_map[real_id].emplace_back(dummy_id);
+ }
+#ifndef EXEC_ENV_OLS
+ dummy_map_stream.close();
+#endif
+ diskann::cout << "Loaded dummy map" << std::endl;
+ }
+ }
+
+#ifdef EXEC_ENV_OLS
+ _pq_table.load_pq_centroid_bin(files, pq_table_bin.c_str(), nchunks_u64);
+#else
+ _pq_table.load_pq_centroid_bin(pq_table_bin.c_str(), nchunks_u64);
+#endif
+
+ diskann::cout << "Loaded PQ centroids and in-memory compressed vectors. #points: " << _num_points
+ << " #dim: " << _data_dim << " #aligned_dim: " << _aligned_dim << " #chunks: " << _n_chunks
+ << std::endl;
+
+ if (_n_chunks > MAX_PQ_CHUNKS)
+ {
+ std::stringstream stream;
+ stream << "Error loading index. Ensure that max PQ bytes for in-memory "
+ "PQ data does not exceed "
+ << MAX_PQ_CHUNKS << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ std::string disk_pq_pivots_path = this->_disk_index_file + "_pq_pivots.bin";
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(disk_pq_pivots_path))
+ {
+ _use_disk_index_pq = true;
+ // giving 0 chunks to make the _pq_table infer from the
+ // chunk_offsets file the correct value
+ _disk_pq_table.load_pq_centroid_bin(files, disk_pq_pivots_path.c_str(), 0);
+#else
+ if (file_exists(disk_pq_pivots_path))
+ {
+ _use_disk_index_pq = true;
+ // giving 0 chunks to make the _pq_table infer from the
+ // chunk_offsets file the correct value
+ _disk_pq_table.load_pq_centroid_bin(disk_pq_pivots_path.c_str(), 0);
+#endif
+ _disk_pq_n_chunks = _disk_pq_table.get_num_chunks();
+ _disk_bytes_per_point =
+ _disk_pq_n_chunks * sizeof(uint8_t); // revising disk_bytes_per_point since DISK PQ is used.
+ diskann::cout << "Disk index uses PQ data compressed down to " << _disk_pq_n_chunks << " bytes per point."
+ << std::endl;
+ }
+
+// read index metadata
+#ifdef EXEC_ENV_OLS
+ // This is a bit tricky. We have to read the header from the
+ // disk_index_file. But this is now exclusively a preserve of the
+ // DiskPriorityIO class. So, we need to estimate how many
+ // bytes are needed to store the header and read in that many using our
+ // 'standard' aligned file reader approach.
+ reader->open(_disk_index_file);
+ this->setup_thread_data(num_threads);
+ this->_max_nthreads = num_threads;
+
+ char *bytes = getHeaderBytes();
+ ContentBuf buf(bytes, HEADER_SIZE);
+ std::basic_istream<char> index_metadata(&buf);
+#else
+ diskann::cout << "Loading index metadata from " << _disk_index_file << std::endl;
+ std::ifstream index_metadata(_disk_index_file, std::ios::binary);
+#endif
+
+ size_t medoid_id_on_file;
+#if 1
+ if (!_use_partition)
+ {
+#endif
+ if (!index_metadata.is_open())
+ {
+ diskann::cout << "Error: Could not open index metadata file: " << _disk_index_file << std::endl;
+ return -1;
+ }
+
+ uint32_t nr, nc; // metadata itself is stored as bin format (nr is number of
+ // metadata, nc should be 1)
+ READ_U32(index_metadata, nr);
+ READ_U32(index_metadata, nc);
+
+ uint64_t disk_nnodes;
+ uint64_t disk_ndims; // can be disk PQ dim if disk_PQ is set to true
+ READ_U64(index_metadata, disk_nnodes);
+ READ_U64(index_metadata, disk_ndims);
+
+ if (disk_nnodes != _num_points)
+ {
+ diskann::cout << "Mismatch in #points for compressed data file and disk "
+ "index file: "
+ << disk_nnodes << " vs " << _num_points << std::endl;
+ return -1;
+ }
+
+ READ_U64(index_metadata, medoid_id_on_file);
+ READ_U64(index_metadata, _max_node_len);
+ READ_U64(index_metadata, _nnodes_per_sector);
+ _max_degree = ((_max_node_len - _disk_bytes_per_point) / sizeof(uint32_t)) - 1;
+
+ if (_max_degree > defaults::MAX_GRAPH_DEGREE)
+ {
+ std::stringstream stream;
+ stream << "Error loading index. Ensure that max graph degree (R) does "
+ "not exceed "
+ << defaults::MAX_GRAPH_DEGREE << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ // setting up concept of frozen points in disk index for streaming-DiskANN
+ READ_U64(index_metadata, this->_num_frozen_points);
+ uint64_t file_frozen_id;
+ READ_U64(index_metadata, file_frozen_id);
+ if (this->_num_frozen_points == 1)
+ this->_frozen_location = file_frozen_id;
+ if (this->_num_frozen_points == 1)
+ {
+ diskann::cout << " Detected frozen point in index at location " << this->_frozen_location
+ << ". Will not output it at search time." << std::endl;
+ }
+
+ READ_U64(index_metadata, this->_reorder_data_exists);
+ if (this->_reorder_data_exists)
+ {
+ if (this->_use_disk_index_pq == false)
+ {
+ throw ANNException("Reordering is designed for used with disk PQ "
+ "compression option",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ READ_U64(index_metadata, this->_reorder_data_start_sector);
+ READ_U64(index_metadata, this->_ndims_reorder_vecs);
+ READ_U64(index_metadata, this->_nvecs_per_sector);
+ }
+
+ diskann::cout << "Disk-Index File Meta-data: ";
+ diskann::cout << "# nodes per sector: " << _nnodes_per_sector;
+ diskann::cout << ", max node len (bytes): " << _max_node_len;
+ diskann::cout << ", max node degree: " << _max_degree << std::endl;
+
+#ifdef EXEC_ENV_OLS
+ delete[] bytes;
+#else
+ index_metadata.close();
+#endif
+
+#ifndef EXEC_ENV_OLS
+ // open AlignedFileReader handle to index_file
+ std::string index_fname(_disk_index_file);
+ reader->open(index_fname);
+
+ diskann::cout << "Disk-Index Meta: nodes per sector: " << _nnodes_per_sector
+ << ", max node len: " << _max_node_len << ", max node degree: " << _max_degree << std::endl;
+
+#endif
+
+#if 1
+ }
+#endif
+
+ this->setup_thread_data(num_threads);
+ this->_max_nthreads = num_threads;
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(medoids_file))
+ {
+ size_t tmp_dim;
+ diskann::load_bin<uint32_t>(files, norm_file, medoids_file, _medoids, _num_medoids, tmp_dim);
+#else
+ if (file_exists(medoids_file))
+ {
+ size_t tmp_dim;
+ diskann::load_bin<uint32_t>(medoids_file, _medoids, _num_medoids, tmp_dim);
+#endif
+
+ if (tmp_dim != 1)
+ {
+ std::stringstream stream;
+ stream << "Error loading medoids file. Expected bin format of m times "
+ "1 vector of uint32_t."
+ << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+#ifdef EXEC_ENV_OLS
+ if (!files.fileExists(centroids_file))
+ {
+#else
+ if (!file_exists(centroids_file))
+ {
+#endif
+ diskann::cout << "Centroid data file not found. Using corresponding vectors "
+ "for the medoids "
+ << std::endl;
+ use_medoids_data_as_centroids();
+ }
+ else
+ {
+ size_t num_centroids, aligned_tmp_dim;
+#ifdef EXEC_ENV_OLS
+ diskann::load_aligned_bin<float>(files, centroids_file, _centroid_data, num_centroids, tmp_dim,
+ aligned_tmp_dim);
+#else
+ diskann::load_aligned_bin<float>(centroids_file, _centroid_data, num_centroids, tmp_dim, aligned_tmp_dim);
+#endif
+ if (aligned_tmp_dim != _aligned_dim || num_centroids != _num_medoids)
+ {
+ std::stringstream stream;
+ stream << "Error loading centroids data file. Expected bin format "
+ "of "
+ "m times data_dim vector of float, where m is number of "
+ "medoids "
+ "in medoids file.";
+ diskann::cerr << stream.str() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+ }
+ else
+ {
+ if (_use_partition)
+ {
+ assert(false); // We do not have a valid medoid id in the partition file.
+ }
+ _num_medoids = 1;
+ _medoids = new uint32_t[1];
+ _medoids[0] = (uint32_t)(medoid_id_on_file);
+ use_medoids_data_as_centroids();
+ }
+
+ std::string norm_file = std::string(_disk_index_file) + "_max_base_norm.bin";
+
+#ifdef EXEC_ENV_OLS
+ if (files.fileExists(norm_file) && metric == diskann::Metric::INNER_PRODUCT)
+ {
+ uint64_t dumr, dumc;
+ float *norm_val;
+ diskann::load_bin<float>(files, norm_val, dumr, dumc);
+#else
+ if (file_exists(norm_file) && metric == diskann::Metric::INNER_PRODUCT)
+ {
+ size_t dumr, dumc;
+ float *norm_val;
+ diskann::load_bin<float>(norm_file, norm_val, dumr, dumc);
+#endif
+ this->_max_base_norm = norm_val[0];
+ diskann::cout << "Setting re-scaling factor of base vectors to " << this->_max_base_norm << std::endl;
+ delete[] norm_val;
+ }
+
+ if (_use_partition)
+ {
+ read_partition_info(partition_file);
+
+ this->_graph_index_file = graph_file;
+ graph_reader->open(this->_graph_index_file);
+ load_graph_index(this->_graph_index_file);
+ }
+
+ diskann::cout << "load_from_separate_paths done." << std::endl;
+ return 0;
+}
+
+#ifdef USE_BING_INFRA
+bool getNextCompletedRequest(std::shared_ptr<AlignedFileReader> &reader, IOContext &ctx, size_t size,
+ int &completedIndex)
+{
+ if ((*ctx.m_pRequests)[0].m_callback)
+ {
+ bool waitsRemaining = false;
+ long completeCount = ctx.m_completeCount;
+ do
+ {
+ for (int i = 0; i < size; i++)
+ {
+ auto ithStatus = (*ctx.m_pRequestsStatus)[i];
+ if (ithStatus == IOContext::Status::READ_SUCCESS)
+ {
+ completedIndex = i;
+ return true;
+ }
+ else if (ithStatus == IOContext::Status::READ_WAIT)
+ {
+ waitsRemaining = true;
+ }
+ }
+
+ // if we didn't find one in READ_SUCCESS, wait for one to complete.
+ if (waitsRemaining)
+ {
+ WaitOnAddress(&ctx.m_completeCount, &completeCount, sizeof(completeCount), 100);
+ // this assumes the knowledge of the reader behavior (implicit
+ // contract). need better factoring?
+ }
+ } while (waitsRemaining);
+
+ completedIndex = -1;
+ return false;
+ }
+ else
+ {
+ reader->wait(ctx, completedIndex);
+ return completedIndex != -1;
+ }
+}
+#endif
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::cached_beam_search(const T *query1, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *indices, float *distances, const uint64_t beam_width,
+ const bool use_reorder_data, QueryStats *stats,
+ bool USE_DEFERRED_FETCH, bool skip_search_reorder,
+ bool recompute_beighbor_embeddings, bool dedup_node_dis,
+ float prune_ratio, const bool batch_recompute, bool global_pruning)
+{
+ cached_beam_search(query1, k_search, l_search, indices, distances, beam_width, std::numeric_limits<uint32_t>::max(),
+ use_reorder_data, stats, USE_DEFERRED_FETCH, skip_search_reorder, recompute_beighbor_embeddings,
+ dedup_node_dis, prune_ratio, batch_recompute, global_pruning);
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::cached_beam_search(const T *query1, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *indices, float *distances, const uint64_t beam_width,
+ const bool use_filter, const LabelT &filter_label,
+ const bool use_reorder_data, QueryStats *stats,
+ bool USE_DEFERRED_FETCH, bool skip_search_reorder,
+ bool recompute_beighbor_embeddings, bool dedup_node_dis,
+ float prune_ratio, const bool batch_recompute, bool global_pruning)
+{
+ cached_beam_search(query1, k_search, l_search, indices, distances, beam_width, use_filter, filter_label,
+ std::numeric_limits<uint32_t>::max(), use_reorder_data, stats, USE_DEFERRED_FETCH,
+ skip_search_reorder, recompute_beighbor_embeddings, dedup_node_dis, prune_ratio, batch_recompute,
+ global_pruning);
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::cached_beam_search(const T *query1, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *indices, float *distances, const uint64_t beam_width,
+ const uint32_t io_limit, const bool use_reorder_data,
+ QueryStats *stats, bool USE_DEFERRED_FETCH, bool skip_search_reorder,
+ bool recompute_beighbor_embeddings, bool dedup_node_dis,
+ float prune_ratio, const bool batch_recompute, bool global_pruning)
+{
+ LabelT dummy_filter = 0;
+ cached_beam_search(query1, k_search, l_search, indices, distances, beam_width, false, dummy_filter, io_limit,
+ use_reorder_data, stats, USE_DEFERRED_FETCH, skip_search_reorder, recompute_beighbor_embeddings,
+ dedup_node_dis, prune_ratio, batch_recompute, global_pruning);
+}
+
+// A helper callback for cURL
+static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
+{
+ ((std::string *)userp)->append((char *)contents, size * nmemb);
+ return size * nmemb;
+}
+
+static void *g_zmq_context = zmq_ctx_new();
+
+struct ZmqContextManager
+{
+ ~ZmqContextManager()
+ {
+ if (g_zmq_context)
+ {
+ zmq_ctx_destroy(g_zmq_context);
+ g_zmq_context = nullptr;
+ }
+ }
+};
+static ZmqContextManager g_zmq_manager;
+
+bool fetch_embeddings_zmq(const std::vector<uint32_t> &node_ids, std::vector<std::vector<float>> &out_embeddings,
+ int zmq_port)
+{
+ // 1. Protobuf 序列化:创建请求消息
+ protoembedding::NodeEmbeddingRequest req_proto;
+ for (const auto id : node_ids)
+ {
+ req_proto.add_node_ids(id);
+ }
+ std::string req_str;
+ if (!req_proto.SerializeToString(&req_str))
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: Failed to serialize NodeEmbeddingRequest.\n";
+ return false;
+ }
+
+ // 2. 使用线程本地(thread_local)的 Socket,实现连接复用
+ // 每个线程将拥有自己独立的、持久化的 Socket
+ thread_local void *tl_socket = nullptr;
+
+ // 如果当前线程的 Socket 还未创建,则初始化并连接
+ if (tl_socket == nullptr)
+ {
+ // 从全局 Context 创建 Socket
+ tl_socket = zmq_socket(g_zmq_context, ZMQ_REQ);
+ if (!tl_socket)
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: zmq_socket() failed: " << zmq_strerror(zmq_errno()) << "\n";
+ return false;
+ }
+
+ int timeout = 30000; // 30 秒超时
+ zmq_setsockopt(tl_socket, ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
+ zmq_setsockopt(tl_socket, ZMQ_SNDTIMEO, &timeout, sizeof(timeout));
+
+ std::string endpoint = "tcp://127.0.0.1:" + std::to_string(zmq_port);
+ if (zmq_connect(tl_socket, endpoint.c_str()) != 0)
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: zmq_connect() to " << endpoint << " failed: " << zmq_strerror(zmq_errno())
+ << "\n";
+ zmq_close(tl_socket);
+ tl_socket = nullptr; // 重置为空指针,以便下次调用时可以尝试重建
+ return false;
+ }
+ }
+
+ // 3. 使用已建立的连接发送请求
+ if (zmq_send(tl_socket, req_str.data(), req_str.size(), 0) < 0)
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: zmq_send() failed: " << zmq_strerror(zmq_errno()) << "\n";
+ zmq_close(tl_socket); // 连接可能已失效,关闭它
+ tl_socket = nullptr; // 重置,强制下次重建
+ return false;
+ }
+
+ // 4. 接收响应
+ zmq_msg_t response_msg;
+ zmq_msg_init(&response_msg);
+ bool success = true;
+
+ if (zmq_msg_recv(&response_msg, tl_socket, 0) < 0)
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: zmq_msg_recv() failed: " << zmq_strerror(zmq_errno()) << "\n";
+ zmq_close(tl_socket); // 同样,接收超时后连接也可能无效
+ tl_socket = nullptr; // 重置,强制下次重建
+ success = false;
+ }
+ else
+ {
+ // 5. Protobuf 反序列化并提取数据
+ protoembedding::NodeEmbeddingResponse resp_proto;
+ if (!resp_proto.ParseFromArray(zmq_msg_data(&response_msg), static_cast<int>(zmq_msg_size(&response_msg))))
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: Failed to parse NodeEmbeddingResponse from server.\n";
+ success = false;
+ }
+ else
+ {
+ if (resp_proto.dimensions_size() == 2)
+ {
+ int batch_size = resp_proto.dimensions(0);
+ int embedding_dim = resp_proto.dimensions(1);
+ const std::string &emb_data = resp_proto.embeddings_data();
+ size_t expected_bytes = (size_t)batch_size * embedding_dim * sizeof(float);
+
+ if (batch_size >= 0 && emb_data.size() == expected_bytes)
+ {
+ out_embeddings.resize(batch_size);
+ if (batch_size > 0)
+ {
+ const float *float_data = reinterpret_cast<const float *>(emb_data.data());
+ for (int i = 0; i < batch_size; ++i)
+ {
+ out_embeddings[i].resize(embedding_dim);
+ std::memcpy(out_embeddings[i].data(), float_data + (size_t)i * embedding_dim,
+ embedding_dim * sizeof(float));
+ }
+ }
+ }
+ else
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: Embedding data size mismatch. Expected " << expected_bytes
+ << " bytes, got " << emb_data.size() << ".\n";
+ success = false;
+ }
+ }
+ else
+ {
+ std::cerr << "ZMQ_FETCH_ERROR: Server response has invalid dimensions size.\n";
+ success = false;
+ }
+ }
+ }
+
+ // 6. 清理消息对象,但保持 Socket 和 Context 开放以备下次复用
+ zmq_msg_close(&response_msg);
+
+ return success;
+}
+
+/**
+ * fetch_embeddings_http: Function for backward compatibility, now uses ZMQ exclusively
+ */
+bool fetch_embeddings_http(const std::vector<uint32_t> &node_ids, std::vector<std::vector<float>> &out_embeddings)
+{
+ // Use ZMQ implementation exclusively
+ return fetch_embeddings_zmq(node_ids, out_embeddings, 5555);
+}
+
+//! Should be aligned with utils.h::prepare_base_for_inner_products
+void preprocess_fetched_embeddings(std::vector<std::vector<float>> &embeddings, diskann::Metric metric,
+ float max_base_norm, uint32_t data_dim)
+{
+ for (auto &emb : embeddings)
+ {
+ // Ensure embedding has correct size
+ if (emb.size() < data_dim - 1)
+ {
+ // Pad with zeros if needed
+ emb.resize(data_dim - 1, 0);
+ }
+
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ {
+ // For inner product, apply same preprocessing as in prepare_base_for_inner_products
+
+ // Calculate original norm
+ float norm_sq = 0;
+ for (size_t i = 0; i < data_dim - 1; i++)
+ {
+ norm_sq += emb[i] * emb[i];
+ }
+
+ // Normalize by max_base_norm (same as in index construction)
+ for (size_t i = 0; i < data_dim - 1; i++)
+ {
+ emb[i] /= max_base_norm;
+ }
+
+ // Add the extra coordinate for MIPS->L2 conversion
+ float res = 1 - (norm_sq / (max_base_norm * max_base_norm));
+ res = res <= 0 ? 0 : std::sqrt(res);
+ emb.resize(data_dim, res);
+ }
+ else if (metric == diskann::Metric::COSINE)
+ {
+ // For cosine similarity, just normalize the vector
+ float norm = 0;
+ for (auto val : emb)
+ {
+ norm += val * val;
+ }
+ norm = std::sqrt(norm);
+
+ if (norm > 0)
+ {
+ for (size_t i = 0; i < emb.size(); i++)
+ {
+ emb[i] /= norm;
+ }
+ }
+ }
+ // For L2, no preprocessing needed
+ }
+}
+
+template <typename T, typename LabelT>
+void PQFlashIndex<T, LabelT>::cached_beam_search(const T *query1, const uint64_t k_search, const uint64_t l_search,
+ uint64_t *indices, float *distances, const uint64_t beam_width,
+ const bool use_filter, const LabelT &filter_label,
+ const uint32_t io_limit, const bool use_reorder_data,
+ QueryStats *stats, bool USE_DEFERRED_FETCH, bool skip_search_reorder,
+ bool recompute_beighbor_embeddings, const bool dedup_node_dis,
+ float prune_ratio, const bool batch_recompute, bool global_pruning)
+{
+ // printf("cached_beam_search\n");
+ // diskann::cout << "cached_beam_search" << std::endl;
+ // diskann out prune_ratio
+ prune_ratio = 1 - prune_ratio;
+ diskann::cout << "reserve ratio: " << prune_ratio << std::endl;
+ // prune_ratio = 0.8;
+ uint64_t num_sector_per_nodes = DIV_ROUND_UP(_max_node_len, defaults::SECTOR_LEN);
+ if (beam_width > num_sector_per_nodes * defaults::MAX_N_SECTOR_READS)
+ throw ANNException("Beamwidth can not be higher than defaults::MAX_N_SECTOR_READS", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+
+ ScratchStoreManager<SSDThreadData<T>> manager(this->_thread_data);
+ auto data = manager.scratch_space();
+ IOContext &ctx = data->ctx;
+ auto query_scratch = &(data->scratch);
+ auto pq_query_scratch = query_scratch->pq_scratch();
+
+ // reset query scratch
+ query_scratch->reset();
+
+ // copy query to thread specific aligned and allocated memory (for distance
+ // calculations we need aligned data)
+ float query_norm = 0;
+ T *aligned_query_T = query_scratch->aligned_query_T();
+ float *query_float = pq_query_scratch->aligned_query_float;
+ float *query_rotated = pq_query_scratch->rotated_query;
+
+ // Add cache hit tracking variables
+ uint64_t total_nodes_requested = 0;
+ uint64_t total_nodes_from_cache = 0;
+
+ // normalization step. for cosine, we simply normalize the query
+ // for mips, we normalize the first d-1 dims, and add a 0 for last dim, since an extra coordinate was used to
+ // convert MIPS to L2 search
+ if (metric == diskann::Metric::INNER_PRODUCT || metric == diskann::Metric::COSINE)
+ {
+ uint64_t inherent_dim = (metric == diskann::Metric::COSINE) ? this->_data_dim : (uint64_t)(this->_data_dim - 1);
+ for (size_t i = 0; i < inherent_dim; i++)
+ {
+ aligned_query_T[i] = query1[i];
+ query_norm += query1[i] * query1[i];
+ }
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ aligned_query_T[this->_data_dim - 1] = 0;
+
+ query_norm = std::sqrt(query_norm);
+
+ for (size_t i = 0; i < inherent_dim; i++)
+ {
+ aligned_query_T[i] = (T)(aligned_query_T[i] / query_norm);
+ }
+ pq_query_scratch->initialize(this->_data_dim, aligned_query_T);
+ }
+ else
+ {
+ for (size_t i = 0; i < this->_data_dim; i++)
+ {
+ aligned_query_T[i] = query1[i];
+ }
+ pq_query_scratch->initialize(this->_data_dim, aligned_query_T);
+ }
+
+ // pointers to buffers for data
+ T *data_buf = query_scratch->coord_scratch;
+ _mm_prefetch((char *)data_buf, _MM_HINT_T1);
+
+ // sector scratch
+ char *sector_scratch = query_scratch->sector_scratch;
+ size_t &sector_scratch_idx = query_scratch->sector_idx;
+ const uint64_t num_sectors_per_node =
+ _nnodes_per_sector > 0 ? 1 : DIV_ROUND_UP(_max_node_len, defaults::SECTOR_LEN);
+
+ // query <-> PQ chunk centers distances
+ _pq_table.preprocess_query(query_rotated); // center the query and rotate if
+ // we have a rotation matrix
+ float *pq_dists = pq_query_scratch->aligned_pqtable_dist_scratch;
+ _pq_table.populate_chunk_distances(query_rotated, pq_dists);
+ // Preprocess Distance b/w Query Vector and Centroids
+ // Chunk 1 | Chunk 2 | Chunk 3
+ // Centroid 1 d[1][1] d[1][2] d[1][3]
+ // Centroid 2
+ // Centroid 3
+ // Centroid 4
+ // Centroid 5
+ // Centroid 6
+ // Centroid 7
+ // Centroid 8
+
+ // query <-> neighbor list
+ float *dist_scratch = pq_query_scratch->aligned_dist_scratch;
+ uint8_t *pq_coord_scratch = pq_query_scratch->aligned_pq_coord_scratch;
+
+ std::map<int, float> node_distances;
+
+ // Lambda to batch compute query<->node distances in PQ space
+ auto compute_dists = [this, pq_coord_scratch, pq_dists, aligned_query_T, recompute_beighbor_embeddings, data_buf,
+ &node_distances, &total_nodes_requested, &total_nodes_from_cache,
+ dedup_node_dis](const uint32_t *ids, const uint64_t n_ids, float *dists_out) {
+ // Vector[0], {3, 6, 2}
+ // Distance = d[3][1] + d[6][2] + d[2][3]
+ // recompute_beighbor_embeddings = true;
+ if (!recompute_beighbor_embeddings)
+ {
+ diskann::aggregate_coords(ids, n_ids, this->data, this->_n_chunks, pq_coord_scratch);
+ diskann::pq_dist_lookup(pq_coord_scratch, n_ids, this->_n_chunks, pq_dists, dists_out);
+ }
+ else
+ {
+ // Fetch the embeddings from the embedding server using n_ids
+ std::vector<uint32_t> node_ids;
+
+ // Update total nodes requested counter
+ total_nodes_requested += n_ids;
+
+ // Build a map from node_id to original position for O(1) lookup
+ // Handle deduplication if enabled
+ std::vector<bool> cached_node_idx(n_ids, false);
+ if (dedup_node_dis)
+ {
+ // First pass: use cached distances where available
+ for (size_t i = 0; i < n_ids; i++)
+ {
+ if (node_distances.find(ids[i]) != node_distances.end())
+ {
+ // Use cached distance
+ dists_out[i] = node_distances[ids[i]];
+ cached_node_idx[i] = true;
+ total_nodes_from_cache++; // Count cache hits
+ }
+ else
+ {
+ // Not in cache, need to compute
+ node_ids.push_back(ids[i]);
+ }
+ }
+
+ // If all distances are cached, we can return early
+ if (node_ids.empty())
+ return;
+ }
+ else
+ {
+ node_ids = std::vector<uint32_t>(ids, ids + n_ids);
+ }
+
+ // Fetch embeddings from the embedding server
+ std::vector<std::vector<float>> embeddings;
+ bool success = fetch_embeddings_http(node_ids, embeddings);
+
+ if (!success || embeddings.size() != node_ids.size())
+ {
+ diskann::cout << "Failed to fetch embeddings from the embedding server" << std::endl;
+ // Fallback to PQ-based distance computation if fetching fails
+ diskann::aggregate_coords(ids, n_ids, this->data, this->_n_chunks, pq_coord_scratch);
+ diskann::pq_dist_lookup(pq_coord_scratch, n_ids, this->_n_chunks, pq_dists, dists_out);
+ return;
+ }
+
+ // Preprocess the fetched embeddings to match the format used in diskann
+ preprocess_fetched_embeddings(embeddings, this->metric, this->_max_base_norm, this->_data_dim);
+
+ // Compute distances for fetched embeddings
+ if (dedup_node_dis)
+ {
+ // Process each node that needs computation
+ uint32_t idx = 0;
+ for (size_t i = 0; i < n_ids; i++)
+ {
+ if (cached_node_idx[i])
+ {
+ continue;
+ }
+ // Prepare embedding for distance computation
+ embeddings[idx].resize(this->_aligned_dim, 0);
+ memcpy(data_buf, embeddings[idx].data(), this->_aligned_dim * sizeof(T));
+
+ // Compute distance
+ float distance =
+ this->_dist_cmp->compare(aligned_query_T, data_buf, static_cast<uint32_t>(this->_aligned_dim));
+
+ // Store results
+ dists_out[i] = distance;
+ node_distances[node_ids[i]] = distance;
+ idx++;
+ }
+ }
+ else
+ {
+ // Without deduplication, embeddings match the original order
+ for (size_t i = 0; i < n_ids; i++)
+ {
+ // Prepare embedding for distance computation
+ embeddings[i].resize(this->_aligned_dim, 0);
+ memcpy(data_buf, embeddings[i].data(), this->_aligned_dim * sizeof(T));
+
+ // Compute distance
+ float distance =
+ this->_dist_cmp->compare(aligned_query_T, data_buf, static_cast<uint32_t>(this->_aligned_dim));
+
+ // Store results
+ dists_out[i] = distance;
+ }
+ }
+ }
+ };
+
+ // Add logic of global pruning
+ // Using a priority queue to record the PQ distance - use min heap for nearest neighbors
+ std::priority_queue<std::pair<float, uint32_t>, std::vector<std::pair<float, uint32_t>>,
+ std::greater<std::pair<float, uint32_t>>>
+ aq_priority_queue;
+ tsl::robin_set<size_t> &visited = query_scratch->visited;
+
+ // TODO: implement this function
+ // 1. Based on some heristic to prune the node_nbrs and nnbrs that is not promising
+ // 1.1 heruistic 1: use higher compression PQ to prune the node_nbrs and nnbrs that is not promising in path
+ // /powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/compressed_2/
+ // 1.2 heruistic 2: use a lightweight reranker to rerank the node_nbrs and nnbrs that is not promising
+ auto prune_node_nbrs = [this, pq_coord_scratch, pq_dists, recompute_beighbor_embeddings, dedup_node_dis,
+ prune_ratio, global_pruning, &aq_priority_queue,
+ &visited](uint32_t *&node_nbrs, uint64_t &nnbrs) {
+ if (!recompute_beighbor_embeddings)
+ {
+ return;
+ }
+ if (nnbrs <= 10)
+ {
+ // Don't prune if there are very few neighbors
+ return;
+ }
+
+ // Allocate space for distance calculations
+ float *dists_out = new float[nnbrs];
+
+ // Compute distances using PQ directly instead of compute_dists
+ diskann::aggregate_coords(node_nbrs, nnbrs, this->data, this->_n_chunks, pq_coord_scratch);
+ diskann::pq_dist_lookup(pq_coord_scratch, nnbrs, this->_n_chunks, pq_dists, dists_out);
+
+ if (global_pruning)
+ {
+ // Add the distance and node_id to the priority queue
+ for (uint64_t i = 0; i < nnbrs; i++)
+ {
+ aq_priority_queue.push(std::make_pair(dists_out[i], node_nbrs[i]));
+ }
+ // select all ratio=prune_ratio in aq_priority_queue but need to check if the node_id is already visited,
+ // dont need to pop
+ std::vector<std::pair<float, uint32_t>> promising_nodes;
+
+ std::vector<std::pair<float, uint32_t>> roll_back_nodes;
+ // 1. visit top prune_ratio*length of aq_priority_queue nodes in aq_priority_queue and put the node_id not
+ // visited into a vector
+ uint64_t original_size = aq_priority_queue.size();
+ for (uint64_t i = 0; i < prune_ratio * original_size; i++)
+ {
+ auto top_node = aq_priority_queue.top();
+ roll_back_nodes.push_back(top_node);
+ aq_priority_queue.pop();
+ if (visited.find(top_node.second) == visited.end())
+ {
+ float distance = top_node.first;
+ uint32_t node_id = top_node.second;
+ promising_nodes.push_back(std::make_pair(distance, node_id));
+ }
+ }
+ // push all roll_back_nodes back to aq_priority_queue
+ for (uint64_t i = 0; i < roll_back_nodes.size(); i++)
+ {
+ aq_priority_queue.push(roll_back_nodes[i]);
+ }
+
+ // 2. assing the node_id and distance to node_nbrs and nnbrs
+ for (uint64_t i = 0; i < promising_nodes.size(); i++)
+ {
+ node_nbrs[i] = promising_nodes[i].second;
+ }
+ nnbrs = promising_nodes.size();
+ // then return corresponding node_nbrs and nnbrs
+
+ delete[] dists_out;
+ return;
+ }
+ // Create a vector of pairs (node_id, distance)
+ std::vector<std::pair<uint32_t, float>> scored_nbrs;
+ scored_nbrs.reserve(nnbrs);
+
+ for (uint64_t i = 0; i < nnbrs; i++)
+ {
+ scored_nbrs.emplace_back(node_nbrs[i], dists_out[i]);
+ }
+
+ // Sort by distance (lower is better)
+ std::sort(scored_nbrs.begin(), scored_nbrs.end(),
+ [](const std::pair<uint32_t, float> &a, const std::pair<uint32_t, float> &b) {
+ return a.second < b.second;
+ });
+
+ // Keep only the top portion of neighbors based on prune_ratio (or at least 10)
+ uint64_t new_nnbrs = std::max<uint64_t>(10UL, static_cast<uint64_t>(nnbrs * prune_ratio));
+ if (new_nnbrs < nnbrs)
+ {
+ // Update the original node_nbrs array with pruned neighbors
+ for (uint64_t i = 0; i < new_nnbrs; i++)
+ {
+ node_nbrs[i] = scored_nbrs[i].first;
+ }
+
+ // Update the count of neighbors
+ nnbrs = new_nnbrs;
+ }
+
+ // Free the allocated memory
+ delete[] dists_out;
+ };
+ Timer query_timer, io_timer, cpu_timer;
+
+ NeighborPriorityQueue &retset = query_scratch->retset;
+ retset.reserve(l_search);
+ std::vector<Neighbor> &full_retset = query_scratch->full_retset;
+ std::vector<T *> points_to_compute; // Store points for later embedding computation
+
+#if 0
+ std::vector<Neighbor> exact_dist_retset;
+ std::vector<std::vector<float>> exact_embeddings;
+#endif
+
+ uint32_t best_medoid = 0;
+ float best_dist = (std::numeric_limits<float>::max)();
+ if (!use_filter)
+ {
+ for (uint64_t cur_m = 0; cur_m < _num_medoids; cur_m++)
+ {
+ float cur_expanded_dist =
+ _dist_cmp_float->compare(query_float, _centroid_data + _aligned_dim * cur_m, (uint32_t)_aligned_dim);
+ if (cur_expanded_dist < best_dist)
+ {
+ best_medoid = _medoids[cur_m];
+ best_dist = cur_expanded_dist;
+ }
+ }
+ }
+ else
+ {
+ if (_filter_to_medoid_ids.find(filter_label) != _filter_to_medoid_ids.end())
+ {
+ const auto &medoid_ids = _filter_to_medoid_ids[filter_label];
+ for (uint64_t cur_m = 0; cur_m < medoid_ids.size(); cur_m++)
+ {
+ // for filtered index, we dont store global centroid data as for unfiltered index, so we use PQ distance
+ // as approximation to decide closest medoid matching the query filter.
+ compute_dists(&medoid_ids[cur_m], 1, dist_scratch);
+ float cur_expanded_dist = dist_scratch[0];
+ if (cur_expanded_dist < best_dist)
+ {
+ best_medoid = medoid_ids[cur_m];
+ best_dist = cur_expanded_dist;
+ }
+ }
+ }
+ else
+ {
+ throw ANNException("Cannot find medoid for specified filter.", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+
+ compute_dists(&best_medoid, 1, dist_scratch);
+ retset.insert(Neighbor(best_medoid, dist_scratch[0]));
+ visited.insert(best_medoid);
+
+ uint32_t cmps = 0;
+ uint32_t hops = 0;
+ uint32_t num_ios = 0;
+
+ // cleared every iteration
+ std::vector<uint32_t> frontier;
+ frontier.reserve(2 * beam_width);
+ std::vector<std::pair<uint32_t, char *>> frontier_nhoods;
+ frontier_nhoods.reserve(2 * beam_width);
+ std::vector<AlignedRead> frontier_read_reqs;
+ frontier_read_reqs.reserve(2 * beam_width);
+ std::vector<std::pair<uint32_t, std::pair<uint32_t, uint32_t *>>> cached_nhoods;
+ cached_nhoods.reserve(2 * beam_width);
+
+ float *batched_dists = nullptr;
+ if (batch_recompute)
+ {
+ batched_dists = new float[_max_degree * beam_width + 5];
+ }
+
+ while (retset.has_unexpanded_node() && num_ios < io_limit)
+ {
+ // clear iteration state
+ frontier.clear();
+ frontier_nhoods.clear();
+ frontier_read_reqs.clear();
+ cached_nhoods.clear();
+ sector_scratch_idx = 0;
+ // find new beam
+ uint32_t num_seen = 0;
+ while (retset.has_unexpanded_node() && frontier.size() < beam_width && num_seen < beam_width)
+ {
+ auto nbr = retset.closest_unexpanded();
+ num_seen++;
+ auto iter = _nhood_cache.find(nbr.id);
+ if (iter != _nhood_cache.end())
+ {
+ cached_nhoods.push_back(std::make_pair(nbr.id, iter->second));
+ if (stats != nullptr)
+ {
+ stats->n_cache_hits++;
+ }
+ }
+ else
+ {
+ frontier.push_back(nbr.id);
+ }
+ if (this->_count_visited_nodes)
+ {
+ reinterpret_cast<std::atomic<uint32_t> &>(this->_node_visit_counter[nbr.id].second).fetch_add(1);
+ }
+ }
+
+ std::vector<AlignedRead> graph_read_reqs;
+ std::map<uint32_t, int> node_offsets; // id -> offset
+ std::map<uint32_t, std::vector<uint32_t>> node_nbrs_ori;
+ std::map<uint32_t, std::vector<float>> node_cords;
+
+ // read nhoods of frontier ids
+ if (!frontier.empty())
+ {
+ if (stats != nullptr)
+ stats->n_hops++;
+
+ for (uint64_t i = 0; i < frontier.size(); i++)
+ {
+ auto id = frontier[i];
+ std::pair<uint32_t, char *> fnhood;
+ fnhood.first = id;
+ fnhood.second = sector_scratch + num_sectors_per_node * sector_scratch_idx * defaults::SECTOR_LEN;
+ sector_scratch_idx++;
+ frontier_nhoods.push_back(fnhood);
+#if 1
+ if (!_use_partition)
+ {
+#endif
+ frontier_read_reqs.emplace_back(get_node_sector((size_t)id) * defaults::SECTOR_LEN,
+ num_sectors_per_node * defaults::SECTOR_LEN, fnhood.second);
+#if 1
+ }
+#endif
+ if (stats != nullptr)
+ {
+ stats->n_4k++;
+ stats->n_ios++;
+ }
+ num_ios++;
+ }
+
+ if (_use_partition)
+ {
+ sector_scratch_idx = 0;
+ for (auto &frontier_nhood : frontier_nhoods)
+ {
+ uint32_t node_id = frontier_nhood.first;
+ uint32_t partition_id = _id2partition[node_id];
+ if (partition_id >= _num_partitions)
+ {
+ diskann::cout << "Warning: partition_id is invalid: " << partition_id << std::endl;
+ assert(false);
+ }
+
+ std::vector<uint32_t> part_list = _graph_partitions[partition_id];
+ auto it = std::find(part_list.begin(), part_list.end(), node_id);
+ if (it == part_list.end())
+ {
+ diskann::cerr << "Error: node " << node_id << " not found in partition " << partition_id
+ << std::endl;
+ assert(false);
+ }
+ size_t j = std::distance(part_list.begin(), it);
+ node_offsets[node_id] = j;
+
+ uint64_t sector_offset = (partition_id + 1) * defaults::SECTOR_LEN;
+ // ! Keep it same with frontier_nhood.second
+ char *sector_buffer = sector_scratch + sector_scratch_idx * defaults::SECTOR_LEN;
+ sector_scratch_idx++;
+
+ AlignedRead partition_read;
+ partition_read.len = defaults::SECTOR_LEN;
+ partition_read.buf = sector_buffer;
+ partition_read.offset = sector_offset;
+
+ graph_read_reqs.emplace_back(partition_read);
+ }
+ }
+
+ io_timer.reset();
+#if 1
+ if (!_use_partition)
+ {
+#endif
+#ifdef USE_BING_INFRA
+ reader->read(frontier_read_reqs, ctx,
+ true); // asynhronous reader for Bing.
+#else
+ reader->read(frontier_read_reqs, ctx); // synchronous IO linux
+#endif
+#if 1
+ }
+#endif
+
+#if 0
+ for (auto &[node_id, disk_buf] : frontier_nhoods)
+ {
+ char *node_disk_buf = offset_to_node(disk_buf, node_id);
+ uint32_t *nhood_buf = offset_to_node_nhood(node_disk_buf);
+ uint32_t neighbor_count = *nhood_buf;
+ node_nbrs_ori[node_id] = std::vector<uint32_t>(nhood_buf + 1, nhood_buf + 1 + neighbor_count);
+ node_cords[node_id] =
+ std::vector<float>(offset_to_node_coords(node_disk_buf),
+ offset_to_node_coords(node_disk_buf) + _disk_bytes_per_point / sizeof(float));
+ }
+#endif
+ if (_use_partition)
+ {
+ graph_reader->read(graph_read_reqs, ctx);
+ }
+
+ if (stats != nullptr)
+ {
+ stats->io_us += (float)io_timer.elapsed();
+ }
+ }
+
+ // process cached nhoods
+ for (auto &cached_nhood : cached_nhoods)
+ {
+ auto global_cache_iter = _coord_cache.find(cached_nhood.first);
+ uint32_t node_id = cached_nhood.first;
+ T *node_fp_coords_copy = global_cache_iter->second;
+ float cur_expanded_dist;
+ float exact_expanded_dist = 0;
+
+ if (skip_search_reorder)
+ {
+ compute_dists(&node_id, 1, dist_scratch);
+ cur_expanded_dist = dist_scratch[0];
+ }
+ else if (USE_DEFERRED_FETCH)
+ {
+ cur_expanded_dist = 0.0f;
+ }
+ else if (!_use_disk_index_pq)
+ {
+ cur_expanded_dist = _dist_cmp->compare(aligned_query_T, node_fp_coords_copy, (uint32_t)_aligned_dim);
+ }
+ else
+ {
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ cur_expanded_dist = _disk_pq_table.inner_product(query_float, (uint8_t *)node_fp_coords_copy);
+ else
+ cur_expanded_dist = _disk_pq_table.l2_distance( // disk_pq does not support OPQ yet
+ query_float, (uint8_t *)node_fp_coords_copy);
+ }
+ full_retset.push_back(Neighbor(node_id, cur_expanded_dist));
+
+#if 0
+ if (!_use_disk_index_pq)
+ {
+ exact_expanded_dist = _dist_cmp->compare(aligned_query_T, node_fp_coords_copy, (uint32_t)_aligned_dim);
+ }
+ else
+ {
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ exact_expanded_dist = _disk_pq_table.inner_product(query_float, (uint8_t *)node_fp_coords_copy);
+ else
+ exact_expanded_dist = _disk_pq_table.l2_distance(query_float, (uint8_t *)node_fp_coords_copy);
+ }
+ exact_dist_retset.push_back(Neighbor(node_id, exact_expanded_dist));
+ exact_embeddings.push_back(std::vector<float>(node_fp_coords_copy, node_fp_coords_copy + _aligned_dim));
+#endif
+
+ uint64_t nnbrs = cached_nhood.second.first;
+ uint32_t *node_nbrs = cached_nhood.second.second;
+
+ // compute node_nbrs <-> query dists in PQ space
+ cpu_timer.reset();
+ compute_dists(node_nbrs, nnbrs, dist_scratch);
+ if (stats != nullptr)
+ {
+ stats->n_cmps += (uint32_t)nnbrs;
+ stats->cpu_us += (float)cpu_timer.elapsed();
+ }
+
+ // process prefetched nhood
+ for (uint64_t m = 0; m < nnbrs; ++m)
+ {
+ uint32_t id = node_nbrs[m];
+ if (visited.insert(id).second)
+ {
+ if (!use_filter && _dummy_pts.find(id) != _dummy_pts.end())
+ continue;
+
+ if (use_filter && !(point_has_label(id, filter_label)) &&
+ (!_use_universal_label || !point_has_label(id, _universal_filter_label)))
+ continue;
+ cmps++;
+ float dist = dist_scratch[m];
+ Neighbor nn(id, dist);
+ retset.insert(nn);
+ }
+ }
+ }
+#ifdef USE_BING_INFRA
+ // process each frontier nhood - compute distances to unvisited nodes
+ int completedIndex = -1;
+ long requestCount = static_cast<long>(frontier_read_reqs.size());
+ // If we issued read requests and if a read is complete or there are
+ // reads in wait state, then enter the while loop.
+ while (requestCount > 0 && getNextCompletedRequest(reader, ctx, requestCount, completedIndex))
+ {
+ assert(completedIndex >= 0);
+ auto &frontier_nhood = frontier_nhoods[completedIndex];
+ (*ctx.m_pRequestsStatus)[completedIndex] = IOContext::PROCESS_COMPLETE;
+#else
+ std::vector<uint32_t> batched_node_ids;
+
+ for (auto &frontier_nhood : frontier_nhoods)
+ {
+#endif
+ uint32_t node_id = frontier_nhood.first;
+ char *disk_buf = frontier_nhood.second;
+ char *node_disk_buf = offset_to_node(disk_buf, node_id);
+
+ float cur_expanded_dist;
+
+ // If skip_reorder is true, compute both PQ distance and exact distance
+ if (skip_search_reorder)
+ {
+ compute_dists(&node_id, 1, dist_scratch);
+ cur_expanded_dist = dist_scratch[0];
+ }
+ else if (USE_DEFERRED_FETCH)
+ {
+ cur_expanded_dist = 0.0f;
+ }
+ else if (recompute_beighbor_embeddings && dedup_node_dis && _use_partition)
+ {
+ // For _use_partition = True, we must rely on node_distances to get the distance
+ // Since we are using graph-structure only reading.
+ // ! Use node_distances to get the distance
+ cur_expanded_dist = node_distances[node_id];
+ }
+ else
+ {
+#if 0
+ if (node_cords.find(node_id) == node_cords.end())
+ {
+ diskann::cout << "Warning: node " << node_id << " not found in node_cords" << std::endl;
+ diskann::cout << "Are you using deferred fetch for detached graph?" << std::endl;
+ assert(false);
+ }
+ // ! As for DEBUG mode and partition_read = True, we are overriding the node_disk_buf
+ // ! with our graph-structure only reading. So we need to use node_cords to get the correct
+ // ! coordinates.
+ T *node_fp_coords = reinterpret_cast<T *>(node_cords[node_id].data());
+ // T *node_fp_coords = offset_to_node_coords(node_disk_buf);
+#endif
+ T *node_fp_coords = offset_to_node_coords(node_disk_buf);
+ memcpy(data_buf, node_fp_coords, _disk_bytes_per_point);
+ if (!_use_disk_index_pq)
+ {
+ cur_expanded_dist = _dist_cmp->compare(aligned_query_T, data_buf, (uint32_t)_aligned_dim);
+ }
+ else
+ {
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ cur_expanded_dist = _disk_pq_table.inner_product(query_float, (uint8_t *)data_buf);
+ else
+ cur_expanded_dist = _disk_pq_table.l2_distance(query_float, (uint8_t *)data_buf);
+ }
+ }
+ full_retset.push_back(Neighbor(node_id, cur_expanded_dist));
+
+#if 0
+ T *node_fp_coords = offset_to_node_coords(node_disk_buf);
+ memcpy(data_buf, node_fp_coords, _disk_bytes_per_point);
+ float exact_expanded_dist = 0;
+ if (!_use_disk_index_pq)
+ {
+ exact_expanded_dist = _dist_cmp->compare(aligned_query_T, data_buf, (uint32_t)_aligned_dim);
+ }
+ else
+ {
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ exact_expanded_dist = _disk_pq_table.inner_product(query_float, (uint8_t *)data_buf);
+ else
+ exact_expanded_dist = _disk_pq_table.l2_distance(query_float, (uint8_t *)data_buf);
+ }
+ exact_dist_retset.push_back(Neighbor(node_id, exact_expanded_dist));
+ exact_embeddings.push_back(std::vector<float>(data_buf, data_buf + _aligned_dim));
+#endif
+
+ uint32_t *node_nbrs;
+ uint64_t nnbrs;
+
+ if (!_use_partition)
+ {
+ auto node_buf = offset_to_node_nhood(node_disk_buf);
+ nnbrs = (uint64_t)(*node_buf);
+ node_nbrs = (node_buf + 1);
+ }
+
+#if 0
+ auto node_nbrs_vec = node_nbrs_ori[node_id];
+ nnbrs = node_nbrs_vec.size();
+ node_nbrs = node_nbrs_vec.data();
+#endif
+ if (_use_partition)
+ {
+ char *sector_buffer = frontier_nhood.second;
+ int j = node_offsets[node_id];
+ uint64_t node_offset = j * _graph_node_len;
+ if (node_offset + 4 > defaults::SECTOR_LEN)
+ {
+ diskann::cerr << "Error: node offset out of range: " << node_offset << " (+4) > "
+ << defaults::SECTOR_LEN << " for node " << node_id << std::endl;
+ assert(false);
+ }
+
+ char *adjacency_ptr = sector_buffer + node_offset;
+ uint32_t neighbor_count = *reinterpret_cast<uint32_t *>(adjacency_ptr);
+
+ if (neighbor_count > 10000)
+ {
+ diskann::cerr << "Error: suspicious neighbor count: " << neighbor_count << " for node " << node_id
+ << std::endl;
+ assert(false);
+ }
+
+ size_t needed = neighbor_count * sizeof(uint32_t);
+ if (node_offset + 4 + needed > defaults::SECTOR_LEN)
+ {
+ diskann::cerr << "Error: neighbor data out of range: " << (node_offset + 4 + needed) << " > "
+ << defaults::SECTOR_LEN << " for node " << node_id << std::endl;
+ assert(false);
+ }
+
+#if 0
+ if (neighbor_count != nnbrs)
+ {
+ diskann::cout << "Warning: neighbor_count != nnbrs: " << neighbor_count << " != " << nnbrs
+ << std::endl;
+ assert(false);
+ }
+#endif
+
+ nnbrs = neighbor_count;
+
+#if 0
+ uint32_t *our_node_nbrs = (uint32_t *)(adjacency_ptr + 4);
+ for (uint32_t i = 0; i < nnbrs; i++)
+ {
+ if (our_node_nbrs[i] != node_nbrs[i])
+ {
+ diskann::cout << "Warning: our_node_nbrs[" << i << "] != node_nbrs[" << i
+ << "]: " << our_node_nbrs[i] << " != " << node_nbrs[i] << std::endl;
+ assert(false);
+ }
+ }
+#endif
+
+ node_nbrs = reinterpret_cast<uint32_t *>(adjacency_ptr + 4);
+ }
+
+ // compute node_nbrs <-> query dist in PQ space
+ cpu_timer.reset();
+ // have a function to prune the node_nbrs and nnbrs
+
+ // prune_node_nbrs(node_nbrs, nnbrs);
+
+ if (!batch_recompute)
+ {
+ prune_node_nbrs(node_nbrs, nnbrs);
+ compute_dists(node_nbrs, nnbrs, dist_scratch);
+ if (stats != nullptr)
+ {
+ stats->n_cmps += (uint32_t)nnbrs;
+ stats->cpu_us += (float)cpu_timer.elapsed();
+ }
+
+ cpu_timer.reset();
+ // process prefetch-ed nhood
+ for (uint64_t m = 0; m < nnbrs; ++m)
+ {
+ uint32_t id = node_nbrs[m];
+ if (visited.insert(id).second)
+ {
+ if (!use_filter && _dummy_pts.find(id) != _dummy_pts.end())
+ continue;
+
+ if (use_filter && !(point_has_label(id, filter_label)) &&
+ (!_use_universal_label || !point_has_label(id, _universal_filter_label)))
+ continue;
+ cmps++;
+ float dist = dist_scratch[m];
+ if (stats != nullptr)
+ {
+ stats->n_cmps++;
+ }
+
+ Neighbor nn(id, dist);
+ retset.insert(nn);
+ }
+ }
+
+ if (stats != nullptr)
+ {
+ stats->cpu_us += (float)cpu_timer.elapsed();
+ }
+ }
+ else
+ {
+ // add all the node_nbrs to the batch_requests
+ batched_node_ids.insert(batched_node_ids.end(), node_nbrs, node_nbrs + nnbrs);
+ }
+ }
+
+ if (batch_recompute)
+ {
+ auto nnbrs = batched_node_ids.size();
+ uint32_t *batched_data_ptr = batched_node_ids.data(); // Get pointer to data
+ prune_node_nbrs(batched_data_ptr, nnbrs); // Prune using the pointer, nnbrs is updated
+
+ compute_dists(batched_data_ptr, nnbrs, batched_dists); // Compute dists for the pruned set
+ // ! Not sure if dist_scratch has enough space
+
+ // process prefetch-ed nhood
+ for (uint64_t m = 0; m < nnbrs; ++m)
+ {
+ uint32_t id = batched_node_ids[m];
+ if (visited.insert(id).second)
+ {
+ if (!use_filter && _dummy_pts.find(id) != _dummy_pts.end())
+ continue;
+
+ if (use_filter && !(point_has_label(id, filter_label)) &&
+ (!_use_universal_label || !point_has_label(id, _universal_filter_label)))
+ continue;
+ cmps++;
+ float dist = batched_dists[m];
+ if (stats != nullptr)
+ {
+ stats->n_cmps++;
+ }
+
+ Neighbor nn(id, dist);
+ retset.insert(nn);
+ }
+ }
+ }
+ // }
+ // }
+ hops++;
+ }
+
+ delete[] batched_dists;
+
+ diskann::cout << "Graph traversal completed, hops: " << hops << std::endl;
+
+ if (USE_DEFERRED_FETCH)
+ {
+ diskann::cout << "hops: " << hops << std::endl;
+
+ std::vector<uint32_t> node_ids;
+ node_ids.reserve(full_retset.size());
+ for (auto &nr : full_retset)
+ {
+ node_ids.push_back(nr.id);
+ }
+
+ Timer fetch_timer;
+ std::vector<std::vector<float>> real_embeddings;
+ bool success = fetch_embeddings_http(node_ids, real_embeddings);
+ if (!success)
+ {
+ throw ANNException("Failed to fetch embeddings", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ diskann::cout << "Fetched " << real_embeddings.size() << " embeddings in " << fetch_timer.elapsed() << " us"
+ << std::endl;
+
+ // compute real-dist
+ Timer compute_timer;
+ // preprocess the real embedding to match the format of nomarlized version of diskann
+ preprocess_fetched_embeddings(real_embeddings, metric, _max_base_norm, this->_data_dim);
+
+#if 0
+ assert(real_embeddings.size() == full_retset.size());
+ assert(real_embeddings.size() == exact_dist_retset.size());
+ assert(real_embeddings.size() == exact_embeddings.size());
+#endif
+
+ for (int i = 0; i < real_embeddings.size(); i++)
+ {
+ // padding real_embeddings[i] to _aligned_dim
+ real_embeddings[i].resize(_aligned_dim, 0);
+#if 0
+ // compare real_embeddings[i] with exact_embeddings[i]
+ if (real_embeddings[i].size() != exact_embeddings[i].size())
+ {
+ diskann::cout << "real_embeddings[i].size(): " << real_embeddings[i].size() << std::endl;
+ diskann::cout << "exact_embeddings[i].size(): " << exact_embeddings[i].size() << std::endl;
+
+ // dumping to files
+ std::ofstream diff_file("./diff_embeddings.txt");
+ diff_file << "real_embeddings[i].size(): " << real_embeddings[i].size() << std::endl;
+ diff_file << "exact_embeddings[i].size(): " << exact_embeddings[i].size() << std::endl;
+ for (int j = 0; j < real_embeddings[i].size(); j++)
+ {
+ diff_file << real_embeddings[i][j] << " ";
+ }
+ diff_file << std::endl;
+ for (int j = 0; j < exact_embeddings[i].size(); j++)
+ {
+ diff_file << exact_embeddings[i][j] << " ";
+ }
+ diff_file << std::endl;
+ assert(false);
+ }
+ for (int j = 0; j < real_embeddings[i].size(); j++)
+ {
+ if (abs(real_embeddings[i][j] - exact_embeddings[i][j]) > 5e-4)
+ {
+ diskann::cout << "Difference found at node_id: " << full_retset[i].id << " and dimension: " << j
+ << std::endl;
+ diskann::cout << "real_embeddings[i][j]: " << real_embeddings[i][j] << std::endl;
+ diskann::cout << "exact_embeddings[i][j]: " << exact_embeddings[i][j] << std::endl;
+ assert(false);
+ }
+ }
+#endif
+
+ float dist;
+ assert(!_use_disk_index_pq);
+ memcpy(data_buf, real_embeddings[i].data(), real_embeddings[0].size() * sizeof(T));
+ dist = _dist_cmp->compare(aligned_query_T, data_buf, (uint32_t)_aligned_dim);
+
+ full_retset[i].distance = dist;
+
+#if 0
+ if (abs(dist - exact_dist_retset[i].distance) > 5e-4)
+ {
+ diskann::cout << "Difference found at node_id: " << full_retset[i].id << std::endl;
+ diskann::cout << "dist: " << dist << std::endl;
+ diskann::cout << "exact_dist_retset[i].distance: " << exact_dist_retset[i].distance << std::endl;
+ assert(false);
+ }
+#endif
+ }
+ diskann::cout << "compute_timer.elapsed(): " << compute_timer.elapsed() << std::endl;
+ }
+
+ std::sort(full_retset.begin(), full_retset.end());
+
+// Compare PQ results with exact results when skip_search_reorder is true
+#if 0
+ if (skip_search_reorder)
+ {
+ // Sort the exact distance results
+ std::sort(exact_dist_retset.begin(), exact_dist_retset.end());
+
+ // Create a map to find positions of IDs in the PQ-sorted list
+ std::unordered_map<uint32_t, size_t> pq_positions;
+ for (size_t i = 0; i < full_retset.size(); i++)
+ {
+ pq_positions[full_retset[i].id] = i;
+ }
+
+ int current_search_id = search_counter.fetch_add(1);
+ int thread_id = omp_get_thread_num();
+
+ std::lock_guard<std::mutex> lock(log_file_mutex);
+
+ std::ofstream log_file("./top3_positions_log.txt", std::ios::app);
+ // Write header if file is empty
+ log_file.seekp(0, std::ios::end);
+ if (log_file.tellp() == 0)
+ {
+ diskann::cout << "Saved top3 distributions to " << std::filesystem::canonical("./top3_positions_log.txt")
+ << std::endl;
+ log_file << "Search#,ThreadID,FullSetSize,Rank,ID,PQ_Rank,PQ_Distance,Exact_Distance" << std::endl;
+ }
+
+ // Log the top-k results from exact distance sorting and their positions in PQ-sorted list
+ size_t top_k = std::min((size_t)k_search, exact_dist_retset.size());
+ for (size_t i = 0; i < top_k; i++)
+ {
+ uint32_t id = exact_dist_retset[i].id;
+ float exact_dist = exact_dist_retset[i].distance;
+
+ // Find this ID's position in the PQ-sorted list
+ size_t pq_pos = pq_positions.count(id) ? pq_positions[id] : full_retset.size();
+ float pq_dist = (pq_pos < full_retset.size()) ? full_retset[pq_pos].distance : -1;
+
+ log_file << current_search_id << "," << thread_id << "," << full_retset.size() << "," << i + 1 << "," << id
+ << "," << pq_pos + 1 << "," << pq_dist << "," << exact_dist << std::endl;
+ }
+
+ log_file.close();
+ }
+#endif
+
+ if (use_reorder_data)
+ {
+ if (!(this->_reorder_data_exists))
+ {
+ throw ANNException("Requested use of reordering data which does "
+ "not exist in index "
+ "file",
+ -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ std::vector<AlignedRead> vec_read_reqs;
+
+ if (full_retset.size() > k_search * FULL_PRECISION_REORDER_MULTIPLIER)
+ full_retset.erase(full_retset.begin() + k_search * FULL_PRECISION_REORDER_MULTIPLIER, full_retset.end());
+
+ for (size_t i = 0; i < full_retset.size(); ++i)
+ {
+ // MULTISECTORFIX
+ vec_read_reqs.emplace_back(VECTOR_SECTOR_NO(((size_t)full_retset[i].id)) * defaults::SECTOR_LEN,
+ defaults::SECTOR_LEN, sector_scratch + i * defaults::SECTOR_LEN);
+
+ if (stats != nullptr)
+ {
+ stats->n_4k++;
+ stats->n_ios++;
+ }
+ }
+
+ io_timer.reset();
+#ifdef USE_BING_INFRA
+ reader->read(vec_read_reqs, ctx, true); // async reader windows.
+#else
+ reader->read(vec_read_reqs, ctx); // synchronous IO linux
+#endif
+ if (stats != nullptr)
+ {
+ stats->io_us += io_timer.elapsed();
+ }
+
+ for (size_t i = 0; i < full_retset.size(); ++i)
+ {
+ auto id = full_retset[i].id;
+ // MULTISECTORFIX
+ auto location = (sector_scratch + i * defaults::SECTOR_LEN) + VECTOR_SECTOR_OFFSET(id);
+ full_retset[i].distance = _dist_cmp->compare(aligned_query_T, (T *)location, (uint32_t)this->_data_dim);
+ }
+
+ std::sort(full_retset.begin(), full_retset.end());
+ }
+
+ // copy k_search values
+ for (uint64_t i = 0; i < k_search; i++)
+ {
+ indices[i] = full_retset[i].id;
+ auto key = (uint32_t)indices[i];
+ if (_dummy_pts.find(key) != _dummy_pts.end())
+ {
+ indices[i] = _dummy_to_real_map[key];
+ }
+
+ if (distances != nullptr)
+ {
+ distances[i] = full_retset[i].distance;
+ if (metric == diskann::Metric::INNER_PRODUCT)
+ {
+ // flip the sign to convert min to max
+ distances[i] = (-distances[i]);
+ // rescale to revert back to original norms (cancelling the
+ // effect of base and query pre-processing)
+ if (_max_base_norm != 0)
+ distances[i] *= (_max_base_norm * query_norm);
+ }
+ }
+ }
+
+#ifdef USE_BING_INFRA
+ ctx.m_completeCount = 0;
+#endif
+
+ if (stats != nullptr)
+ {
+ stats->total_us = (float)query_timer.elapsed();
+ }
+
+ // After search is complete, print cache hit rate statistics
+ if (recompute_beighbor_embeddings && dedup_node_dis && total_nodes_requested > 0)
+ {
+ float cache_hit_rate = static_cast<float>(total_nodes_from_cache) / total_nodes_requested * 100.0f;
+ diskann::cout << "Node distance cache statistics:" << std::endl;
+ diskann::cout << " Total nodes requested: " << total_nodes_requested << std::endl;
+ diskann::cout << " Nodes served from cache: " << total_nodes_from_cache << std::endl;
+ diskann::cout << " Cache hit rate: " << cache_hit_rate << "%" << std::endl;
+ }
+}
+
+// range search returns results of all neighbors within distance of range.
+// indices and distances need to be pre-allocated of size l_search and the
+// return value is the number of matching hits.
+template <typename T, typename LabelT>
+uint32_t PQFlashIndex<T, LabelT>::range_search(const T *query1, const double range, const uint64_t min_l_search,
+ const uint64_t max_l_search, std::vector<uint64_t> &indices,
+ std::vector<float> &distances, const uint64_t min_beam_width,
+ QueryStats *stats)
+{
+ uint32_t res_count = 0;
+
+ bool stop_flag = false;
+
+ uint32_t l_search = (uint32_t)min_l_search; // starting size of the candidate list
+ while (!stop_flag)
+ {
+ indices.resize(l_search);
+ distances.resize(l_search);
+ uint64_t cur_bw = min_beam_width > (l_search / 5) ? min_beam_width : l_search / 5;
+ cur_bw = (cur_bw > 100) ? 100 : cur_bw;
+ for (auto &x : distances)
+ x = std::numeric_limits<float>::max();
+ this->cached_beam_search(query1, l_search, l_search, indices.data(), distances.data(), cur_bw, false, stats);
+ for (uint32_t i = 0; i < l_search; i++)
+ {
+ if (distances[i] > (float)range)
+ {
+ res_count = i;
+ break;
+ }
+ else if (i == l_search - 1)
+ res_count = l_search;
+ }
+ if (res_count < (uint32_t)(l_search / 2.0))
+ stop_flag = true;
+ l_search = l_search * 2;
+ if (l_search > max_l_search)
+ stop_flag = true;
+ }
+ indices.resize(res_count);
+ distances.resize(res_count);
+ return res_count;
+}
+
+template <typename T, typename LabelT> uint64_t PQFlashIndex<T, LabelT>::get_data_dim()
+{
+ return _data_dim;
+}
+
+template <typename T, typename LabelT> diskann::Metric PQFlashIndex<T, LabelT>::get_metric()
+{
+ return this->metric;
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename T, typename LabelT> char *PQFlashIndex<T, LabelT>::getHeaderBytes()
+{
+ IOContext &ctx = reader->get_ctx();
+ AlignedRead readReq;
+ readReq.buf = new char[PQFlashIndex<T, LabelT>::HEADER_SIZE];
+ readReq.len = PQFlashIndex<T, LabelT>::HEADER_SIZE;
+ readReq.offset = 0;
+
+ std::vector<AlignedRead> readReqs;
+ readReqs.push_back(readReq);
+
+ reader->read(readReqs, ctx, false);
+
+ return (char *)readReq.buf;
+}
+#endif
+
+template <typename T, typename LabelT>
+std::vector<std::uint8_t> PQFlashIndex<T, LabelT>::get_pq_vector(std::uint64_t vid)
+{
+ std::uint8_t *pqVec = &this->data[vid * this->_n_chunks];
+ return std::vector<std::uint8_t>(pqVec, pqVec + this->_n_chunks);
+}
+
+template <typename T, typename LabelT> std::uint64_t PQFlashIndex<T, LabelT>::get_num_points()
+{
+ return _num_points;
+}
+
+// instantiations
+template class PQFlashIndex<uint8_t>;
+template class PQFlashIndex<int8_t>;
+template class PQFlashIndex<float>;
+template class PQFlashIndex<uint8_t, uint16_t>;
+template class PQFlashIndex<int8_t, uint16_t>;
+template class PQFlashIndex<float, uint16_t>;
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/pq_l2_distance.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/pq_l2_distance.cpp
new file mode 100644
index 0000000..9bd5311
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/pq_l2_distance.cpp
@@ -0,0 +1,284 @@
+
+#include "pq.h"
+#include "pq_l2_distance.h"
+#include "pq_scratch.h"
+
+// block size for reading/processing large files and matrices in blocks
+#define BLOCK_SIZE 5000000
+
+namespace diskann
+{
+
+template <typename data_t>
+PQL2Distance<data_t>::PQL2Distance(uint32_t num_chunks, bool use_opq) : _num_chunks(num_chunks), _is_opq(use_opq)
+{
+}
+
+template <typename data_t> PQL2Distance<data_t>::~PQL2Distance()
+{
+#ifndef EXEC_ENV_OLS
+ if (_tables != nullptr)
+ delete[] _tables;
+ if (_chunk_offsets != nullptr)
+ delete[] _chunk_offsets;
+ if (_centroid != nullptr)
+ delete[] _centroid;
+ if (_rotmat_tr != nullptr)
+ delete[] _rotmat_tr;
+#endif
+ if (_tables_tr != nullptr)
+ delete[] _tables_tr;
+}
+
+template <typename data_t> bool PQL2Distance<data_t>::is_opq() const
+{
+ return this->_is_opq;
+}
+
+template <typename data_t>
+std::string PQL2Distance<data_t>::get_quantized_vectors_filename(const std::string &prefix) const
+{
+ if (_num_chunks == 0)
+ {
+ throw diskann::ANNException("Must set num_chunks before calling get_quantized_vectors_filename", -1,
+ __FUNCSIG__, __FILE__, __LINE__);
+ }
+ return diskann::get_quantized_vectors_filename(prefix, _is_opq, (uint32_t)_num_chunks);
+}
+template <typename data_t> std::string PQL2Distance<data_t>::get_pivot_data_filename(const std::string &prefix) const
+{
+ if (_num_chunks == 0)
+ {
+ throw diskann::ANNException("Must set num_chunks before calling get_pivot_data_filename", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+ return diskann::get_pivot_data_filename(prefix, _is_opq, (uint32_t)_num_chunks);
+}
+template <typename data_t>
+std::string PQL2Distance<data_t>::get_rotation_matrix_suffix(const std::string &pq_pivots_filename) const
+{
+ return diskann::get_rotation_matrix_suffix(pq_pivots_filename);
+}
+
+#ifdef EXEC_ENV_OLS
+template <typename data_t>
+void PQL2Distance<data_t>::load_pivot_data(MemoryMappedFiles &files, const std::string &pq_table_file,
+ size_t num_chunks)
+{
+#else
+template <typename data_t>
+void PQL2Distance<data_t>::load_pivot_data(const std::string &pq_table_file, size_t num_chunks)
+{
+#endif
+ size_t nr, nc;
+ // std::string rotmat_file = get_opq_rot_matrix_filename(pq_table_file,
+ // false);
+
+#ifdef EXEC_ENV_OLS
+ size_t *file_offset_data; // since load_bin only sets the pointer, no need
+ // to delete.
+ diskann::load_bin<size_t>(files, pq_table_file, file_offset_data, nr, nc);
+#else
+ std::unique_ptr<size_t[]> file_offset_data;
+ diskann::load_bin<size_t>(pq_table_file, file_offset_data, nr, nc);
+#endif
+
+ bool use_old_filetype = false;
+
+ if (nr != 4 && nr != 5)
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_table_file
+ << ". Offsets dont contain correct metadata, # offsets = " << nr << ", but expecting " << 4
+ << " or " << 5;
+ throw diskann::ANNException("Error reading pq_pivots file at offsets data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ if (nr == 4)
+ {
+ diskann::cout << "Offsets: " << file_offset_data[0] << " " << file_offset_data[1] << " " << file_offset_data[2]
+ << " " << file_offset_data[3] << std::endl;
+ }
+ else if (nr == 5)
+ {
+ use_old_filetype = true;
+ diskann::cout << "Offsets: " << file_offset_data[0] << " " << file_offset_data[1] << " " << file_offset_data[2]
+ << " " << file_offset_data[3] << file_offset_data[4] << std::endl;
+ }
+ else
+ {
+ throw diskann::ANNException("Wrong number of offsets in pq_pivots", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<float>(files, pq_table_file, tables, nr, nc, file_offset_data[0]);
+#else
+ diskann::load_bin<float>(pq_table_file, _tables, nr, nc, file_offset_data[0]);
+#endif
+
+ if ((nr != NUM_PQ_CENTROIDS))
+ {
+ diskann::cout << "Error reading pq_pivots file " << pq_table_file << ". file_num_centers = " << nr
+ << " but expecting " << NUM_PQ_CENTROIDS << " centers";
+ throw diskann::ANNException("Error reading pq_pivots file at pivots data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ this->_ndims = nc;
+
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<float>(files, pq_table_file, centroid, nr, nc, file_offset_data[1]);
+#else
+ diskann::load_bin<float>(pq_table_file, _centroid, nr, nc, file_offset_data[1]);
+#endif
+
+ if ((nr != this->_ndims) || (nc != 1))
+ {
+ diskann::cerr << "Error reading centroids from pq_pivots file " << pq_table_file << ". file_dim = " << nr
+ << ", file_cols = " << nc << " but expecting " << this->_ndims << " entries in 1 dimension.";
+ throw diskann::ANNException("Error reading pq_pivots file at centroid data.", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ int chunk_offsets_index = 2;
+ if (use_old_filetype)
+ {
+ chunk_offsets_index = 3;
+ }
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<uint32_t>(files, pq_table_file, chunk_offsets, nr, nc, file_offset_data[chunk_offsets_index]);
+#else
+ diskann::load_bin<uint32_t>(pq_table_file, _chunk_offsets, nr, nc, file_offset_data[chunk_offsets_index]);
+#endif
+
+ if (nc != 1 || (nr != num_chunks + 1 && num_chunks != 0))
+ {
+ diskann::cerr << "Error loading chunk offsets file. numc: " << nc << " (should be 1). numr: " << nr
+ << " (should be " << num_chunks + 1 << " or 0 if we need to infer)" << std::endl;
+ throw diskann::ANNException("Error loading chunk offsets file", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ this->_num_chunks = nr - 1;
+ diskann::cout << "Loaded PQ Pivots: #ctrs: " << NUM_PQ_CENTROIDS << ", #dims: " << this->_ndims
+ << ", #chunks: " << this->_num_chunks << std::endl;
+
+ // For OPQ there will be a rotation matrix to load.
+ if (this->_is_opq)
+ {
+ std::string rotmat_file = get_rotation_matrix_suffix(pq_table_file);
+#ifdef EXEC_ENV_OLS
+ diskann::load_bin<float>(files, rotmat_file, (float *&)rotmat_tr, nr, nc);
+#else
+ diskann::load_bin<float>(rotmat_file, _rotmat_tr, nr, nc);
+#endif
+ if (nr != this->_ndims || nc != this->_ndims)
+ {
+ diskann::cerr << "Error loading rotation matrix file" << std::endl;
+ throw diskann::ANNException("Error loading rotation matrix file", -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+
+ // alloc and compute transpose
+ _tables_tr = new float[256 * this->_ndims];
+ for (size_t i = 0; i < 256; i++)
+ {
+ for (size_t j = 0; j < this->_ndims; j++)
+ {
+ _tables_tr[j * 256 + i] = _tables[i * this->_ndims + j];
+ }
+ }
+}
+
+template <typename data_t> uint32_t PQL2Distance<data_t>::get_num_chunks() const
+{
+ return static_cast<uint32_t>(_num_chunks);
+}
+
+// REFACTOR: Instead of doing half the work in the caller and half in this
+// function, we let this function
+// do all of the work, making it easier for the caller.
+template <typename data_t>
+void PQL2Distance<data_t>::preprocess_query(const data_t *aligned_query, uint32_t dim, PQScratch<data_t> &scratch)
+{
+ // Copy query vector to float and then to "rotated" query
+ for (size_t d = 0; d < dim; d++)
+ {
+ scratch.aligned_query_float[d] = (float)aligned_query[d];
+ }
+ scratch.initialize(dim, aligned_query);
+
+ for (uint32_t d = 0; d < _ndims; d++)
+ {
+ scratch.rotated_query[d] -= _centroid[d];
+ }
+ std::vector<float> tmp(_ndims, 0);
+ if (_is_opq)
+ {
+ for (uint32_t d = 0; d < _ndims; d++)
+ {
+ for (uint32_t d1 = 0; d1 < _ndims; d1++)
+ {
+ tmp[d] += scratch.rotated_query[d1] * _rotmat_tr[d1 * _ndims + d];
+ }
+ }
+ std::memcpy(scratch.rotated_query, tmp.data(), _ndims * sizeof(float));
+ }
+ this->prepopulate_chunkwise_distances(scratch.rotated_query, scratch.aligned_pqtable_dist_scratch);
+}
+
+template <typename data_t>
+void PQL2Distance<data_t>::preprocessed_distance(PQScratch<data_t> &pq_scratch, const uint32_t n_ids, float *dists_out)
+{
+ pq_dist_lookup(pq_scratch.aligned_pq_coord_scratch, n_ids, _num_chunks, pq_scratch.aligned_pqtable_dist_scratch,
+ dists_out);
+}
+
+template <typename data_t>
+void PQL2Distance<data_t>::preprocessed_distance(PQScratch<data_t> &pq_scratch, const uint32_t n_ids,
+ std::vector<float> &dists_out)
+{
+ pq_dist_lookup(pq_scratch.aligned_pq_coord_scratch, n_ids, _num_chunks, pq_scratch.aligned_pqtable_dist_scratch,
+ dists_out);
+}
+
+template <typename data_t> float PQL2Distance<data_t>::brute_force_distance(const float *query_vec, uint8_t *base_vec)
+{
+ float res = 0;
+ for (size_t chunk = 0; chunk < _num_chunks; chunk++)
+ {
+ for (size_t j = _chunk_offsets[chunk]; j < _chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = _tables_tr + (256 * j);
+ float diff = centers_dim_vec[base_vec[chunk]] - (query_vec[j]);
+ res += diff * diff;
+ }
+ }
+ return res;
+}
+
+template <typename data_t>
+void PQL2Distance<data_t>::prepopulate_chunkwise_distances(const float *query_vec, float *dist_vec)
+{
+ memset(dist_vec, 0, 256 * _num_chunks * sizeof(float));
+ // chunk wise distance computation
+ for (size_t chunk = 0; chunk < _num_chunks; chunk++)
+ {
+ // sum (q-c)^2 for the dimensions associated with this chunk
+ float *chunk_dists = dist_vec + (256 * chunk);
+ for (size_t j = _chunk_offsets[chunk]; j < _chunk_offsets[chunk + 1]; j++)
+ {
+ const float *centers_dim_vec = _tables_tr + (256 * j);
+ for (size_t idx = 0; idx < 256; idx++)
+ {
+ double diff = centers_dim_vec[idx] - (query_vec[j]);
+ chunk_dists[idx] += (float)(diff * diff);
+ }
+ }
+ }
+}
+
+template DISKANN_DLLEXPORT class PQL2Distance<int8_t>;
+template DISKANN_DLLEXPORT class PQL2Distance<uint8_t>;
+template DISKANN_DLLEXPORT class PQL2Distance<float>;
+
+} // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/restapi/search_wrapper.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/restapi/search_wrapper.cpp
new file mode 100644
index 0000000..001e36d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/restapi/search_wrapper.cpp
@@ -0,0 +1,217 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <ctime>
+#include <iomanip>
+#include <omp.h>
+
+#include "utils.h"
+#include <restapi/search_wrapper.h>
+
+#ifndef _WINDOWS
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include "linux_aligned_file_reader.h"
+#else
+#ifdef USE_BING_INFRA
+#include "bing_aligned_file_reader.h"
+#else
+#include "windows_aligned_file_reader.h"
+#endif
+#endif
+
+namespace diskann
+{
+const unsigned int DEFAULT_W = 1;
+
+SearchResult::SearchResult(unsigned int K, unsigned int elapsed_time_in_ms, const unsigned *const indices,
+ const float *const distances, const std::string *const tags,
+ const unsigned *const partitions)
+ : _K(K), _search_time_in_ms(elapsed_time_in_ms)
+{
+ for (unsigned i = 0; i < K; ++i)
+ {
+ this->_indices.push_back(indices[i]);
+ this->_distances.push_back(distances[i]);
+ if (tags != NULL)
+ this->_tags.push_back(tags[i]);
+ if (partitions != NULL)
+ this->_partitions.push_back(partitions[i]);
+ }
+ if (tags != nullptr)
+ this->_tags_enabled = true;
+ else
+ this->_tags_enabled = false;
+
+ if (partitions != nullptr)
+ this->_partitions_enabled = true;
+ else
+ this->_partitions_enabled = false;
+}
+
+BaseSearch::BaseSearch(const std::string &tagsFile)
+{
+ if (tagsFile.size() != 0)
+ {
+ std::ifstream in(tagsFile);
+
+ if (!in.is_open())
+ {
+ std::cerr << "Could not open " << tagsFile << std::endl;
+ }
+
+ std::string tag;
+ while (std::getline(in, tag))
+ {
+ _tags_str.push_back(tag);
+ }
+
+ _tags_enabled = true;
+
+ std::cout << "Loaded " << _tags_str.size() << " tags from " << tagsFile << std::endl;
+ }
+ else
+ {
+ _tags_enabled = false;
+ }
+}
+
+void BaseSearch::lookup_tags(const unsigned K, const unsigned *indices, std::string *ret_tags)
+{
+ if (_tags_enabled == false)
+ throw std::runtime_error("Can not look up tags as they are not enabled.");
+ else
+ {
+ for (unsigned k = 0; k < K; ++k)
+ {
+ if (indices[k] > _tags_str.size())
+ throw std::runtime_error("In tag lookup, index exceeded the number of tags");
+ else
+ ret_tags[k] = _tags_str[indices[k]];
+ }
+ }
+}
+
+template <typename T>
+InMemorySearch<T>::InMemorySearch(const std::string &baseFile, const std::string &indexFile,
+ const std::string &tagsFile, Metric m, uint32_t num_threads, uint32_t search_l)
+ : BaseSearch(tagsFile)
+{
+ size_t dimensions, total_points = 0;
+ diskann::get_bin_metadata(baseFile, total_points, dimensions);
+ auto search_params = diskann::IndexSearchParams(search_l, num_threads);
+ _index = std::unique_ptr<diskann::Index<T>>(
+ new diskann::Index<T>(m, dimensions, total_points, nullptr, search_params, 0, false));
+
+ _index->load(indexFile.c_str(), num_threads, search_l);
+}
+
+template <typename T>
+SearchResult InMemorySearch<T>::search(const T *query, const unsigned int dimensions, const unsigned int K,
+ const unsigned int Ls)
+{
+ unsigned int *indices = new unsigned int[K];
+ float *distances = new float[K];
+
+ auto startTime = std::chrono::high_resolution_clock::now();
+ _index->search(query, K, Ls, indices, distances);
+ auto duration =
+ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - startTime)
+ .count();
+
+ std::string *tags = nullptr;
+ if (_tags_enabled)
+ {
+ tags = new std::string[K];
+ lookup_tags(K, indices, tags);
+ }
+
+ SearchResult result(K, (unsigned int)duration, indices, distances, tags);
+
+ delete[] indices;
+ delete[] distances;
+ return result;
+}
+
+template <typename T> InMemorySearch<T>::~InMemorySearch()
+{
+}
+
+template <typename T>
+PQFlashSearch<T>::PQFlashSearch(const std::string &indexPrefix, const unsigned num_nodes_to_cache,
+ const unsigned num_threads, const std::string &tagsFile, Metric m)
+ : BaseSearch(tagsFile)
+{
+#ifdef _WINDOWS
+#ifndef USE_BING_INFRA
+ reader.reset(new WindowsAlignedFileReader());
+#else
+ reader.reset(new diskann::BingAlignedFileReader());
+#endif
+#else
+ auto ptr = new LinuxAlignedFileReader();
+ reader.reset(ptr);
+#endif
+
+ std::string index_prefix_path(indexPrefix);
+ std::string disk_index_file = index_prefix_path + "_disk.index";
+ std::string warmup_query_file = index_prefix_path + "_sample_data.bin";
+
+ _index = std::unique_ptr<diskann::PQFlashIndex<T>>(new diskann::PQFlashIndex<T>(reader, m));
+
+ int res = _index->load(num_threads, index_prefix_path.c_str());
+
+ if (res != 0)
+ {
+ std::cerr << "Unable to load index. Status code: " << res << "." << std::endl;
+ }
+
+ std::vector<uint32_t> node_list;
+ std::cout << "Caching " << num_nodes_to_cache << " BFS nodes around medoid(s)" << std::endl;
+ _index->cache_bfs_levels(num_nodes_to_cache, node_list);
+ _index->load_cache_list(node_list);
+ omp_set_num_threads(num_threads);
+}
+
+template <typename T>
+SearchResult PQFlashSearch<T>::search(const T *query, const unsigned int dimensions, const unsigned int K,
+ const unsigned int Ls)
+{
+ uint64_t *indices_u64 = new uint64_t[K];
+ unsigned *indices = new unsigned[K];
+ float *distances = new float[K];
+
+ auto startTime = std::chrono::high_resolution_clock::now();
+ _index->cached_beam_search(query, K, Ls, indices_u64, distances, DEFAULT_W);
+ auto duration =
+ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - startTime)
+ .count();
+ for (unsigned k = 0; k < K; ++k)
+ indices[k] = indices_u64[k];
+
+ std::string *tags = nullptr;
+ if (_tags_enabled)
+ {
+ tags = new std::string[K];
+ lookup_tags(K, indices, tags);
+ }
+ SearchResult result(K, (unsigned int)duration, indices, distances, tags);
+ delete[] indices_u64;
+ delete[] indices;
+ delete[] distances;
+ return result;
+}
+
+template <typename T> PQFlashSearch<T>::~PQFlashSearch()
+{
+}
+
+template class InMemorySearch<float>;
+template class InMemorySearch<int8_t>;
+template class InMemorySearch<uint8_t>;
+
+template class PQFlashSearch<float>;
+template class PQFlashSearch<int8_t>;
+template class PQFlashSearch<uint8_t>;
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/restapi/server.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/restapi/server.cpp
new file mode 100644
index 0000000..f79b0af
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/restapi/server.cpp
@@ -0,0 +1,271 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <ctime>
+#include <functional>
+#include <iomanip>
+#include <string>
+#include <cstdlib>
+#include <codecvt>
+#include <limits>
+
+#include <restapi/server.h>
+
+namespace diskann
+{
+
+Server::Server(web::uri &uri, std::vector<std::unique_ptr<diskann::BaseSearch>> &multi_searcher,
+ const std::string &typestring)
+ : _multi_search(multi_searcher.size() > 1 ? true : false)
+{
+ for (auto &searcher : multi_searcher)
+ _multi_searcher.push_back(std::move(searcher));
+
+ _listener = std::unique_ptr<web::http::experimental::listener::http_listener>(
+ new web::http::experimental::listener::http_listener(uri));
+ if (typestring == std::string("float"))
+ {
+ _listener->support(std::bind(&Server::handle_post<float>, this, std::placeholders::_1));
+ }
+ else if (typestring == std::string("int8_t"))
+ {
+ _listener->support(web::http::methods::POST,
+ std::bind(&Server::handle_post<int8_t>, this, std::placeholders::_1));
+ }
+ else if (typestring == std::string("uint8_t"))
+ {
+ _listener->support(web::http::methods::POST,
+ std::bind(&Server::handle_post<uint8_t>, this, std::placeholders::_1));
+ }
+ else
+ {
+ throw "Unsupported type in server constuctor";
+ }
+}
+
+Server::~Server()
+{
+}
+
+pplx::task<void> Server::open()
+{
+ return _listener->open();
+}
+pplx::task<void> Server::close()
+{
+ return _listener->close();
+}
+
+diskann::SearchResult Server::aggregate_results(const unsigned K, const std::vector<diskann::SearchResult> &results)
+{
+ if (_multi_search)
+ {
+ auto best_indices = new unsigned[K];
+ auto best_distances = new float[K];
+ auto best_partitions = new unsigned[K];
+ auto best_tags = results[0].tags_enabled() ? new std::string[K] : nullptr;
+
+ auto numsearchers = _multi_searcher.size();
+ std::vector<size_t> pos(numsearchers, 0);
+
+ for (size_t k = 0; k < K; ++k)
+ {
+ float best_distance = std::numeric_limits<float>::max();
+ unsigned best_partition = 0;
+
+ for (size_t i = 0; i < numsearchers; ++i)
+ {
+ if (results[i].get_distances()[pos[i]] < best_distance)
+ {
+ best_distance = results[i].get_distances()[pos[i]];
+ best_partition = i;
+ }
+ }
+ best_distances[k] = best_distance;
+ best_indices[k] = results[best_partition].get_indices()[pos[best_partition]];
+ best_partitions[k] = best_partition;
+ if (results[best_partition].tags_enabled())
+ best_tags[k] = results[best_partition].get_tags()[pos[best_partition]];
+ std::cout << best_partition << " " << pos[best_partition] << std::endl;
+ pos[best_partition]++;
+ }
+
+ unsigned int total_time = 0;
+ for (size_t i = 0; i < numsearchers; ++i)
+ total_time += results[i].get_time();
+ diskann::SearchResult result =
+ SearchResult(K, total_time, best_indices, best_distances, best_tags, best_partitions);
+
+ delete[] best_indices;
+ delete[] best_distances;
+ delete[] best_partitions;
+ delete[] best_tags;
+
+ return result;
+ }
+ else
+ {
+ return results[0];
+ }
+}
+
+template <class T> void Server::handle_post(web::http::http_request message)
+{
+ message.extract_string(true)
+ .then([=](utility::string_t body) {
+ int64_t queryId = -1;
+ unsigned int K = 0;
+ try
+ {
+ T *queryVector = nullptr;
+ unsigned int dimensions = 0;
+ unsigned int Ls;
+ parseJson(body, K, queryId, queryVector, dimensions, Ls);
+
+ auto startTime = std::chrono::high_resolution_clock::now();
+ std::vector<diskann::SearchResult> results;
+
+ for (auto &searcher : _multi_searcher)
+ results.push_back(searcher->search(queryVector, dimensions, (unsigned int)K, Ls));
+ diskann::SearchResult result = aggregate_results(K, results);
+ diskann::aligned_free(queryVector);
+ web::json::value response = prepareResponse(queryId, K);
+ response[INDICES_KEY] = idsToJsonArray(result);
+ response[DISTANCES_KEY] = distancesToJsonArray(result);
+ if (result.tags_enabled())
+ response[TAGS_KEY] = tagsToJsonArray(result);
+ if (result.partitions_enabled())
+ response[PARTITION_KEY] = partitionsToJsonArray(result);
+
+ response[TIME_TAKEN_KEY] = std::chrono::duration_cast<std::chrono::microseconds>(
+ std::chrono::high_resolution_clock::now() - startTime)
+ .count();
+
+ std::cout << "Responding to: " << queryId << std::endl;
+ return std::make_pair(web::http::status_codes::OK, response);
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Exception while processing query: " << queryId << ":" << ex.what() << std::endl;
+ web::json::value response = prepareResponse(queryId, K);
+ response[ERROR_MESSAGE_KEY] = web::json::value::string(ex.what());
+ return std::make_pair(web::http::status_codes::InternalError, response);
+ }
+ catch (...)
+ {
+ std::cerr << "Uncaught exception while processing query: " << queryId;
+ web::json::value response = prepareResponse(queryId, K);
+ response[ERROR_MESSAGE_KEY] = web::json::value::string(UNKNOWN_ERROR);
+ return std::make_pair(web::http::status_codes::InternalError, response);
+ }
+ })
+ .then([=](std::pair<short unsigned int, web::json::value> response_status) {
+ try
+ {
+ message.reply(response_status.first, response_status.second).wait();
+ }
+ catch (const std::exception &ex)
+ {
+ std::cerr << "Exception while processing reply: " << ex.what() << std::endl;
+ };
+ });
+}
+
+web::json::value Server::prepareResponse(const int64_t &queryId, const int k)
+{
+ web::json::value response = web::json::value::object();
+ response[QUERY_ID_KEY] = queryId;
+ response[K_KEY] = k;
+
+ return response;
+}
+
+template <class T>
+void Server::parseJson(const utility::string_t &body, unsigned int &k, int64_t &queryId, T *&queryVector,
+ unsigned int &dimensions, unsigned &Ls)
+{
+ std::cout << body << std::endl;
+ web::json::value val = web::json::value::parse(body);
+ web::json::array queryArr = val.at(VECTOR_KEY).as_array();
+ queryId = val.has_field(QUERY_ID_KEY) ? val.at(QUERY_ID_KEY).as_number().to_int64() : -1;
+ Ls = val.has_field(L_KEY) ? val.at(L_KEY).as_number().to_uint32() : DEFAULT_L;
+ k = val.at(K_KEY).as_integer();
+
+ if (k <= 0 || k > Ls)
+ {
+ throw new std::invalid_argument("Num of expected NN (k) must be greater than zero and less than or "
+ "equal to Ls.");
+ }
+ if (queryArr.size() == 0)
+ {
+ throw new std::invalid_argument("Query vector has zero elements.");
+ }
+
+ dimensions = static_cast<unsigned int>(queryArr.size());
+ unsigned new_dim = ROUND_UP(dimensions, 8);
+ diskann::alloc_aligned((void **)&queryVector, new_dim * sizeof(T), 8 * sizeof(T));
+ memset(queryVector, 0, new_dim * sizeof(float));
+ for (size_t i = 0; i < queryArr.size(); i++)
+ {
+ queryVector[i] = (float)queryArr[i].as_double();
+ }
+}
+
+template <typename T>
+web::json::value Server::toJsonArray(const std::vector<T> &v, std::function<web::json::value(const T &)> valConverter)
+{
+ web::json::value rslts = web::json::value::array();
+ for (size_t i = 0; i < v.size(); i++)
+ {
+ auto jsonVal = valConverter(v[i]);
+ rslts[i] = jsonVal;
+ }
+ return rslts;
+}
+
+web::json::value Server::idsToJsonArray(const diskann::SearchResult &result)
+{
+ web::json::value idArray = web::json::value::array();
+ auto ids = result.get_indices();
+ for (size_t i = 0; i < ids.size(); i++)
+ {
+ auto idVal = web::json::value::number(ids[i]);
+ idArray[i] = idVal;
+ }
+ std::cout << "Vector size: " << ids.size() << std::endl;
+ return idArray;
+}
+
+web::json::value Server::distancesToJsonArray(const diskann::SearchResult &result)
+{
+ web::json::value distArray = web::json::value::array();
+ auto distances = result.get_distances();
+ for (size_t i = 0; i < distances.size(); i++)
+ {
+ distArray[i] = web::json::value::number(distances[i]);
+ }
+ return distArray;
+}
+
+web::json::value Server::tagsToJsonArray(const diskann::SearchResult &result)
+{
+ web::json::value tagArray = web::json::value::array();
+ auto tags = result.get_tags();
+ for (size_t i = 0; i < tags.size(); i++)
+ {
+ tagArray[i] = web::json::value::string(tags[i]);
+ }
+ return tagArray;
+}
+
+web::json::value Server::partitionsToJsonArray(const diskann::SearchResult &result)
+{
+ web::json::value partitionArray = web::json::value::array();
+ auto partitions = result.get_partitions();
+ for (size_t i = 0; i < partitions.size(); i++)
+ {
+ partitionArray[i] = web::json::value::number(partitions[i]);
+ }
+ return partitionArray;
+}
+}; // namespace diskann
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/scratch.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/scratch.cpp
new file mode 100644
index 0000000..1f8a34b
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/scratch.cpp
@@ -0,0 +1,182 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <vector>
+#include <boost/dynamic_bitset.hpp>
+
+#include "scratch.h"
+#include "pq_scratch.h"
+
+namespace diskann
+{
+//
+// Functions to manage scratch space for in-memory index based search
+//
+template <typename T>
+InMemQueryScratch<T>::InMemQueryScratch(uint32_t search_l, uint32_t indexing_l, uint32_t r, uint32_t maxc, size_t dim,
+ size_t aligned_dim, size_t alignment_factor, bool init_pq_scratch)
+ : _L(0), _R(r), _maxc(maxc)
+{
+ if (search_l == 0 || indexing_l == 0 || r == 0 || dim == 0)
+ {
+ std::stringstream ss;
+ ss << "In InMemQueryScratch, one of search_l = " << search_l << ", indexing_l = " << indexing_l
+ << ", dim = " << dim << " or r = " << r << " is zero." << std::endl;
+ throw diskann::ANNException(ss.str(), -1);
+ }
+
+ alloc_aligned(((void **)&this->_aligned_query_T), aligned_dim * sizeof(T), alignment_factor * sizeof(T));
+ memset(this->_aligned_query_T, 0, aligned_dim * sizeof(T));
+
+ if (init_pq_scratch)
+ this->_pq_scratch = new PQScratch<T>(defaults::MAX_GRAPH_DEGREE, aligned_dim);
+ else
+ this->_pq_scratch = nullptr;
+
+ _occlude_factor.reserve(maxc);
+ _inserted_into_pool_bs = new boost::dynamic_bitset<>();
+ _id_scratch.reserve((size_t)std::ceil(1.5 * defaults::GRAPH_SLACK_FACTOR * _R));
+ _dist_scratch.reserve((size_t)std::ceil(1.5 * defaults::GRAPH_SLACK_FACTOR * _R));
+
+ resize_for_new_L(std::max(search_l, indexing_l));
+}
+
+template <typename T> void InMemQueryScratch<T>::clear()
+{
+ _pool.clear();
+ _best_l_nodes.clear();
+ _occlude_factor.clear();
+
+ _inserted_into_pool_rs.clear();
+ _inserted_into_pool_bs->reset();
+
+ _id_scratch.clear();
+ _dist_scratch.clear();
+
+ _expanded_nodes_set.clear();
+ _expanded_nghrs_vec.clear();
+ _occlude_list_output.clear();
+}
+
+template <typename T> void InMemQueryScratch<T>::resize_for_new_L(uint32_t new_l)
+{
+ if (new_l > _L)
+ {
+ _L = new_l;
+ _pool.reserve(3 * _L + _R);
+ _best_l_nodes.reserve(_L);
+
+ _inserted_into_pool_rs.reserve(20 * _L);
+ }
+}
+
+template <typename T> InMemQueryScratch<T>::~InMemQueryScratch()
+{
+ if (this->_aligned_query_T != nullptr)
+ {
+ aligned_free(this->_aligned_query_T);
+ this->_aligned_query_T = nullptr;
+ }
+
+ delete this->_pq_scratch;
+ delete _inserted_into_pool_bs;
+}
+
+//
+// Functions to manage scratch space for SSD based search
+//
+template <typename T> void SSDQueryScratch<T>::reset()
+{
+ sector_idx = 0;
+ visited.clear();
+ retset.clear();
+ full_retset.clear();
+}
+
+template <typename T> SSDQueryScratch<T>::SSDQueryScratch(size_t aligned_dim, size_t visited_reserve)
+{
+ size_t coord_alloc_size = ROUND_UP(sizeof(T) * aligned_dim, 256);
+
+ diskann::alloc_aligned((void **)&coord_scratch, coord_alloc_size, 256);
+ diskann::alloc_aligned((void **)&sector_scratch, defaults::MAX_N_SECTOR_READS * defaults::SECTOR_LEN,
+ defaults::SECTOR_LEN);
+ diskann::alloc_aligned((void **)&this->_aligned_query_T, aligned_dim * sizeof(T), 8 * sizeof(T));
+
+ this->_pq_scratch = new PQScratch<T>(defaults::MAX_GRAPH_DEGREE, aligned_dim);
+
+ memset(coord_scratch, 0, coord_alloc_size);
+ memset(this->_aligned_query_T, 0, aligned_dim * sizeof(T));
+
+ visited.reserve(visited_reserve);
+ full_retset.reserve(visited_reserve);
+}
+
+template <typename T> SSDQueryScratch<T>::~SSDQueryScratch()
+{
+ diskann::aligned_free((void *)coord_scratch);
+ diskann::aligned_free((void *)sector_scratch);
+ diskann::aligned_free((void *)this->_aligned_query_T);
+
+ delete this->_pq_scratch;
+}
+
+template <typename T>
+SSDThreadData<T>::SSDThreadData(size_t aligned_dim, size_t visited_reserve) : scratch(aligned_dim, visited_reserve)
+{
+}
+
+template <typename T> void SSDThreadData<T>::clear()
+{
+ scratch.reset();
+}
+
+template <typename T> PQScratch<T>::PQScratch(size_t graph_degree, size_t aligned_dim)
+{
+ diskann::alloc_aligned((void **)&aligned_pq_coord_scratch,
+ (size_t)graph_degree * (size_t)MAX_PQ_CHUNKS * sizeof(uint8_t), 256);
+ diskann::alloc_aligned((void **)&aligned_pqtable_dist_scratch, 256 * (size_t)MAX_PQ_CHUNKS * sizeof(float), 256);
+ diskann::alloc_aligned((void **)&aligned_dist_scratch, (size_t)graph_degree * sizeof(float), 256);
+ diskann::alloc_aligned((void **)&aligned_query_float, aligned_dim * sizeof(float), 8 * sizeof(float));
+ diskann::alloc_aligned((void **)&rotated_query, aligned_dim * sizeof(float), 8 * sizeof(float));
+
+ memset(aligned_query_float, 0, aligned_dim * sizeof(float));
+ memset(rotated_query, 0, aligned_dim * sizeof(float));
+}
+
+template <typename T> PQScratch<T>::~PQScratch()
+{
+ diskann::aligned_free((void *)aligned_pq_coord_scratch);
+ diskann::aligned_free((void *)aligned_pqtable_dist_scratch);
+ diskann::aligned_free((void *)aligned_dist_scratch);
+ diskann::aligned_free((void *)aligned_query_float);
+ diskann::aligned_free((void *)rotated_query);
+}
+
+template <typename T> void PQScratch<T>::initialize(size_t dim, const T *query, const float norm)
+{
+ for (size_t d = 0; d < dim; ++d)
+ {
+ if (norm != 1.0f)
+ rotated_query[d] = aligned_query_float[d] = static_cast<float>(query[d]) / norm;
+ else
+ rotated_query[d] = aligned_query_float[d] = static_cast<float>(query[d]);
+ }
+}
+
+template DISKANN_DLLEXPORT class InMemQueryScratch<int8_t>;
+template DISKANN_DLLEXPORT class InMemQueryScratch<uint8_t>;
+template DISKANN_DLLEXPORT class InMemQueryScratch<float>;
+
+template DISKANN_DLLEXPORT class SSDQueryScratch<int8_t>;
+template DISKANN_DLLEXPORT class SSDQueryScratch<uint8_t>;
+template DISKANN_DLLEXPORT class SSDQueryScratch<float>;
+
+template DISKANN_DLLEXPORT class PQScratch<int8_t>;
+template DISKANN_DLLEXPORT class PQScratch<uint8_t>;
+template DISKANN_DLLEXPORT class PQScratch<float>;
+
+template DISKANN_DLLEXPORT class SSDThreadData<int8_t>;
+template DISKANN_DLLEXPORT class SSDThreadData<uint8_t>;
+template DISKANN_DLLEXPORT class SSDThreadData<float>;
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/utils.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/utils.cpp
new file mode 100644
index 0000000..3773cda
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/utils.cpp
@@ -0,0 +1,477 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include "utils.h"
+
+#include <stdio.h>
+
+#ifdef EXEC_ENV_OLS
+#include "aligned_file_reader.h"
+#endif
+
+const uint32_t MAX_REQUEST_SIZE = 1024 * 1024 * 1024; // 64MB
+const uint32_t MAX_SIMULTANEOUS_READ_REQUESTS = 128;
+
+#ifdef _WINDOWS
+#include <intrin.h>
+
+// Taken from:
+// https://insufficientlycomplicated.wordpress.com/2011/11/07/detecting-intel-advanced-vector-extensions-avx-in-visual-studio/
+bool cpuHasAvxSupport()
+{
+ bool avxSupported = false;
+
+ // Checking for AVX requires 3 things:
+ // 1) CPUID indicates that the OS uses XSAVE and XRSTORE
+ // instructions (allowing saving YMM registers on context
+ // switch)
+ // 2) CPUID indicates support for AVX
+ // 3) XGETBV indicates the AVX registers will be saved and
+ // restored on context switch
+ //
+ // Note that XGETBV is only available on 686 or later CPUs, so
+ // the instruction needs to be conditionally run.
+ int cpuInfo[4];
+ __cpuid(cpuInfo, 1);
+
+ bool osUsesXSAVE_XRSTORE = cpuInfo[2] & (1 << 27) || false;
+ bool cpuAVXSuport = cpuInfo[2] & (1 << 28) || false;
+
+ if (osUsesXSAVE_XRSTORE && cpuAVXSuport)
+ {
+ // Check if the OS will save the YMM registers
+ unsigned long long xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
+ avxSupported = (xcrFeatureMask & 0x6) || false;
+ }
+
+ return avxSupported;
+}
+
+bool cpuHasAvx2Support()
+{
+ int cpuInfo[4];
+ __cpuid(cpuInfo, 0);
+ int n = cpuInfo[0];
+ if (n >= 7)
+ {
+ __cpuidex(cpuInfo, 7, 0);
+ static int avx2Mask = 0x20;
+ return (cpuInfo[1] & avx2Mask) > 0;
+ }
+ return false;
+}
+
+bool AvxSupportedCPU = cpuHasAvxSupport();
+bool Avx2SupportedCPU = cpuHasAvx2Support();
+
+#else
+
+bool Avx2SupportedCPU = true;
+bool AvxSupportedCPU = false;
+#endif
+
+namespace diskann
+{
+
+void block_convert(std::ofstream &writr, std::ifstream &readr, float *read_buf, size_t npts, size_t ndims)
+{
+ readr.read((char *)read_buf, npts * ndims * sizeof(float));
+ uint32_t ndims_u32 = (uint32_t)ndims;
+#pragma omp parallel for
+ for (int64_t i = 0; i < (int64_t)npts; i++)
+ {
+ float norm_pt = std::numeric_limits<float>::epsilon();
+ for (uint32_t dim = 0; dim < ndims_u32; dim++)
+ {
+ norm_pt += *(read_buf + i * ndims + dim) * *(read_buf + i * ndims + dim);
+ }
+ norm_pt = std::sqrt(norm_pt);
+ for (uint32_t dim = 0; dim < ndims_u32; dim++)
+ {
+ *(read_buf + i * ndims + dim) = *(read_buf + i * ndims + dim) / norm_pt;
+ }
+ }
+ writr.write((char *)read_buf, npts * ndims * sizeof(float));
+}
+
+void normalize_data_file(const std::string &inFileName, const std::string &outFileName)
+{
+ std::ifstream readr(inFileName, std::ios::binary);
+ std::ofstream writr(outFileName, std::ios::binary);
+
+ int npts_s32, ndims_s32;
+ readr.read((char *)&npts_s32, sizeof(int32_t));
+ readr.read((char *)&ndims_s32, sizeof(int32_t));
+
+ writr.write((char *)&npts_s32, sizeof(int32_t));
+ writr.write((char *)&ndims_s32, sizeof(int32_t));
+
+ size_t npts = (size_t)npts_s32;
+ size_t ndims = (size_t)ndims_s32;
+ diskann::cout << "Normalizing FLOAT vectors in file: " << inFileName << std::endl;
+ diskann::cout << "Dataset: #pts = " << npts << ", # dims = " << ndims << std::endl;
+
+ size_t blk_size = 131072;
+ size_t nblks = ROUND_UP(npts, blk_size) / blk_size;
+ diskann::cout << "# blks: " << nblks << std::endl;
+
+ float *read_buf = new float[npts * ndims];
+ for (size_t i = 0; i < nblks; i++)
+ {
+ size_t cblk_size = std::min(npts - i * blk_size, blk_size);
+ block_convert(writr, readr, read_buf, cblk_size, ndims);
+ }
+ delete[] read_buf;
+
+ diskann::cout << "Wrote normalized points to file: " << outFileName << std::endl;
+}
+
+double calculate_recall(uint32_t num_queries, uint32_t *gold_std, float *gs_dist, uint32_t dim_gs,
+ uint32_t *our_results, uint32_t dim_or, uint32_t recall_at)
+{
+ double total_recall = 0;
+ std::set<uint32_t> gt, res;
+
+ for (size_t i = 0; i < num_queries; i++)
+ {
+ gt.clear();
+ res.clear();
+ uint32_t *gt_vec = gold_std + dim_gs * i;
+ uint32_t *res_vec = our_results + dim_or * i;
+ size_t tie_breaker = recall_at;
+ if (gs_dist != nullptr)
+ {
+ tie_breaker = recall_at - 1;
+ float *gt_dist_vec = gs_dist + dim_gs * i;
+ while (tie_breaker < dim_gs && gt_dist_vec[tie_breaker] == gt_dist_vec[recall_at - 1])
+ tie_breaker++;
+ }
+
+ gt.insert(gt_vec, gt_vec + tie_breaker);
+ res.insert(res_vec,
+ res_vec + recall_at); // change to recall_at for recall k@k
+ // or dim_or for k@dim_or
+ uint32_t cur_recall = 0;
+ for (auto &v : gt)
+ {
+ if (res.find(v) != res.end())
+ {
+ cur_recall++;
+ }
+ }
+ total_recall += cur_recall;
+ }
+ return total_recall / (num_queries) * (100.0 / recall_at);
+}
+
+double calculate_recall(uint32_t num_queries, uint32_t *gold_std, float *gs_dist, uint32_t dim_gs,
+ uint32_t *our_results, uint32_t dim_or, uint32_t recall_at,
+ const tsl::robin_set<uint32_t> &active_tags)
+{
+ double total_recall = 0;
+ std::set<uint32_t> gt, res;
+ bool printed = false;
+ for (size_t i = 0; i < num_queries; i++)
+ {
+ gt.clear();
+ res.clear();
+ uint32_t *gt_vec = gold_std + dim_gs * i;
+ uint32_t *res_vec = our_results + dim_or * i;
+ size_t tie_breaker = recall_at;
+ uint32_t active_points_count = 0;
+ uint32_t cur_counter = 0;
+ while (active_points_count < recall_at && cur_counter < dim_gs)
+ {
+ if (active_tags.find(*(gt_vec + cur_counter)) != active_tags.end())
+ {
+ active_points_count++;
+ }
+ cur_counter++;
+ }
+ if (active_tags.empty())
+ cur_counter = recall_at;
+
+ if ((active_points_count < recall_at && !active_tags.empty()) && !printed)
+ {
+ diskann::cout << "Warning: Couldn't find enough closest neighbors " << active_points_count << "/"
+ << recall_at
+ << " from "
+ "truthset for query # "
+ << i << ". Will result in under-reported value of recall." << std::endl;
+ printed = true;
+ }
+ if (gs_dist != nullptr)
+ {
+ tie_breaker = cur_counter - 1;
+ float *gt_dist_vec = gs_dist + dim_gs * i;
+ while (tie_breaker < dim_gs && gt_dist_vec[tie_breaker] == gt_dist_vec[cur_counter - 1])
+ tie_breaker++;
+ }
+
+ gt.insert(gt_vec, gt_vec + tie_breaker);
+ res.insert(res_vec, res_vec + recall_at);
+ uint32_t cur_recall = 0;
+ for (auto &v : res)
+ {
+ if (gt.find(v) != gt.end())
+ {
+ cur_recall++;
+ }
+ }
+ total_recall += cur_recall;
+ }
+ return ((double)(total_recall / (num_queries))) * ((double)(100.0 / recall_at));
+}
+
+double calculate_range_search_recall(uint32_t num_queries, std::vector<std::vector<uint32_t>> &groundtruth,
+ std::vector<std::vector<uint32_t>> &our_results)
+{
+ double total_recall = 0;
+ std::set<uint32_t> gt, res;
+
+ for (size_t i = 0; i < num_queries; i++)
+ {
+ gt.clear();
+ res.clear();
+
+ gt.insert(groundtruth[i].begin(), groundtruth[i].end());
+ res.insert(our_results[i].begin(), our_results[i].end());
+ uint32_t cur_recall = 0;
+ for (auto &v : gt)
+ {
+ if (res.find(v) != res.end())
+ {
+ cur_recall++;
+ }
+ }
+ if (gt.size() != 0)
+ total_recall += ((100.0 * cur_recall) / gt.size());
+ else
+ total_recall += 100;
+ }
+ return total_recall / (num_queries);
+}
+
+#ifdef EXEC_ENV_OLS
+void get_bin_metadata(AlignedFileReader &reader, size_t &npts, size_t &ndim, size_t offset)
+{
+ std::vector<AlignedRead> readReqs;
+ AlignedRead readReq;
+ uint32_t buf[2]; // npts/ndim are uint32_ts.
+
+ readReq.buf = buf;
+ readReq.offset = offset;
+ readReq.len = 2 * sizeof(uint32_t);
+ readReqs.push_back(readReq);
+
+ IOContext &ctx = reader.get_ctx();
+ reader.read(readReqs, ctx); // synchronous
+ if ((*(ctx.m_pRequestsStatus))[0] == IOContext::READ_SUCCESS)
+ {
+ npts = buf[0];
+ ndim = buf[1];
+ diskann::cout << "File has: " << npts << " points, " << ndim << " dimensions at offset: " << offset
+ << std::endl;
+ }
+ else
+ {
+ std::stringstream str;
+ str << "Could not read binary metadata from index file at offset: " << offset << std::endl;
+ throw diskann::ANNException(str.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+
+template <typename T> void load_bin(AlignedFileReader &reader, T *&data, size_t &npts, size_t &ndim, size_t offset)
+{
+ // Code assumes that the reader is already setup correctly.
+ get_bin_metadata(reader, npts, ndim, offset);
+ data = new T[npts * ndim];
+
+ size_t data_size = npts * ndim * sizeof(T);
+ size_t write_offset = 0;
+ size_t read_start = offset + 2 * sizeof(uint32_t);
+
+ // BingAlignedFileReader can only read uint32_t bytes of data. So,
+ // we limit ourselves even more to reading 1GB at a time.
+ std::vector<AlignedRead> readReqs;
+ while (data_size > 0)
+ {
+ AlignedRead readReq;
+ readReq.buf = data + write_offset;
+ readReq.offset = read_start + write_offset;
+ readReq.len = data_size > MAX_REQUEST_SIZE ? MAX_REQUEST_SIZE : data_size;
+ readReqs.push_back(readReq);
+ // in the corner case, the loop will not execute
+ data_size -= readReq.len;
+ write_offset += readReq.len;
+ }
+ IOContext &ctx = reader.get_ctx();
+ reader.read(readReqs, ctx);
+ for (int i = 0; i < readReqs.size(); i++)
+ {
+ // Since we are making sync calls, no request will be in the
+ // READ_WAIT state.
+ if ((*(ctx.m_pRequestsStatus))[i] != IOContext::READ_SUCCESS)
+ {
+ std::stringstream str;
+ str << "Could not read binary data from index file at offset: " << readReqs[i].offset << std::endl;
+ throw diskann::ANNException(str.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+}
+template <typename T>
+void load_bin(AlignedFileReader &reader, std::unique_ptr<T[]> &data, size_t &npts, size_t &ndim, size_t offset)
+{
+ T *ptr = nullptr;
+ load_bin(reader, ptr, npts, ndim, offset);
+ data.reset(ptr);
+}
+
+template <typename T>
+void copy_aligned_data_from_file(AlignedFileReader &reader, T *&data, size_t &npts, size_t &ndim,
+ const size_t &rounded_dim, size_t offset)
+{
+ if (data == nullptr)
+ {
+ diskann::cerr << "Memory was not allocated for " << data << " before calling the load function. Exiting..."
+ << std::endl;
+ throw diskann::ANNException("Null pointer passed to copy_aligned_data_from_file()", -1, __FUNCSIG__, __FILE__,
+ __LINE__);
+ }
+
+ size_t pts, dim;
+ get_bin_metadata(reader, pts, dim, offset);
+
+ if (ndim != dim || npts != pts)
+ {
+ std::stringstream ss;
+ ss << "Either file dimension: " << dim << " is != passed dimension: " << ndim << " or file #pts: " << pts
+ << " is != passed #pts: " << npts << std::endl;
+ throw diskann::ANNException(ss.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+
+ // Instead of reading one point of ndim size and setting (rounded_dim - dim)
+ // values to zero We'll set everything to zero and read in chunks of data at
+ // the appropriate locations.
+ size_t read_offset = offset + 2 * sizeof(uint32_t);
+ memset(data, 0, npts * rounded_dim * sizeof(T));
+ int i = 0;
+ std::vector<AlignedRead> read_requests;
+
+ while (i < npts)
+ {
+ int j = 0;
+ read_requests.clear();
+ while (j < MAX_SIMULTANEOUS_READ_REQUESTS && i < npts)
+ {
+ AlignedRead read_req;
+ read_req.buf = data + i * rounded_dim;
+ read_req.len = dim * sizeof(T);
+ read_req.offset = read_offset + i * dim * sizeof(T);
+ read_requests.push_back(read_req);
+ i++;
+ j++;
+ }
+ IOContext &ctx = reader.get_ctx();
+ reader.read(read_requests, ctx);
+ for (int k = 0; k < read_requests.size(); k++)
+ {
+ if ((*ctx.m_pRequestsStatus)[k] != IOContext::READ_SUCCESS)
+ {
+ throw diskann::ANNException("Load data from file using AlignedReader failed.", -1, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+ }
+ }
+}
+
+// Unlike load_bin, assumes that data is already allocated 'size' entries
+template <typename T> void read_array(AlignedFileReader &reader, T *data, size_t size, size_t offset)
+{
+ if (data == nullptr)
+ {
+ throw diskann::ANNException("read_array requires an allocated buffer.", -1);
+ }
+
+ if (size * sizeof(T) > MAX_REQUEST_SIZE)
+ {
+ std::stringstream ss;
+ ss << "Cannot read more than " << MAX_REQUEST_SIZE << " bytes. Current request size: " << std::to_string(size)
+ << " sizeof(T): " << sizeof(T) << std::endl;
+ throw diskann::ANNException(ss.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ std::vector<AlignedRead> read_requests;
+ AlignedRead read_req;
+ read_req.buf = data;
+ read_req.len = size * sizeof(T);
+ read_req.offset = offset;
+ read_requests.push_back(read_req);
+ IOContext &ctx = reader.get_ctx();
+ reader.read(read_requests, ctx);
+
+ if ((*(ctx.m_pRequestsStatus))[0] != IOContext::READ_SUCCESS)
+ {
+ std::stringstream ss;
+ ss << "Failed to read_array() of size: " << size * sizeof(T) << " at offset: " << offset << " from reader. "
+ << std::endl;
+ throw diskann::ANNException(ss.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+}
+
+template <typename T> void read_value(AlignedFileReader &reader, T &value, size_t offset)
+{
+ read_array(reader, &value, 1, offset);
+}
+
+template DISKANN_DLLEXPORT void load_bin<uint8_t>(AlignedFileReader &reader, std::unique_ptr<uint8_t[]> &data,
+ size_t &npts, size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<int8_t>(AlignedFileReader &reader, std::unique_ptr<int8_t[]> &data,
+ size_t &npts, size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<uint32_t>(AlignedFileReader &reader, std::unique_ptr<uint32_t[]> &data,
+ size_t &npts, size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<uint64_t>(AlignedFileReader &reader, std::unique_ptr<uint64_t[]> &data,
+ size_t &npts, size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<int64_t>(AlignedFileReader &reader, std::unique_ptr<int64_t[]> &data,
+ size_t &npts, size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<float>(AlignedFileReader &reader, std::unique_ptr<float[]> &data, size_t &npts,
+ size_t &ndim, size_t offset);
+
+template DISKANN_DLLEXPORT void load_bin<uint8_t>(AlignedFileReader &reader, uint8_t *&data, size_t &npts, size_t &ndim,
+ size_t offset);
+template DISKANN_DLLEXPORT void load_bin<int64_t>(AlignedFileReader &reader, int64_t *&data, size_t &npts, size_t &ndim,
+ size_t offset);
+template DISKANN_DLLEXPORT void load_bin<uint64_t>(AlignedFileReader &reader, uint64_t *&data, size_t &npts,
+ size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<uint32_t>(AlignedFileReader &reader, uint32_t *&data, size_t &npts,
+ size_t &ndim, size_t offset);
+template DISKANN_DLLEXPORT void load_bin<int32_t>(AlignedFileReader &reader, int32_t *&data, size_t &npts, size_t &ndim,
+ size_t offset);
+
+template DISKANN_DLLEXPORT void copy_aligned_data_from_file<uint8_t>(AlignedFileReader &reader, uint8_t *&data,
+ size_t &npts, size_t &dim,
+ const size_t &rounded_dim, size_t offset);
+template DISKANN_DLLEXPORT void copy_aligned_data_from_file<int8_t>(AlignedFileReader &reader, int8_t *&data,
+ size_t &npts, size_t &dim,
+ const size_t &rounded_dim, size_t offset);
+template DISKANN_DLLEXPORT void copy_aligned_data_from_file<float>(AlignedFileReader &reader, float *&data,
+ size_t &npts, size_t &dim, const size_t &rounded_dim,
+ size_t offset);
+
+template DISKANN_DLLEXPORT void read_array<char>(AlignedFileReader &reader, char *data, size_t size, size_t offset);
+
+template DISKANN_DLLEXPORT void read_array<uint8_t>(AlignedFileReader &reader, uint8_t *data, size_t size,
+ size_t offset);
+template DISKANN_DLLEXPORT void read_array<int8_t>(AlignedFileReader &reader, int8_t *data, size_t size, size_t offset);
+template DISKANN_DLLEXPORT void read_array<uint32_t>(AlignedFileReader &reader, uint32_t *data, size_t size,
+ size_t offset);
+template DISKANN_DLLEXPORT void read_array<float>(AlignedFileReader &reader, float *data, size_t size, size_t offset);
+
+template DISKANN_DLLEXPORT void read_value<uint8_t>(AlignedFileReader &reader, uint8_t &value, size_t offset);
+template DISKANN_DLLEXPORT void read_value<int8_t>(AlignedFileReader &reader, int8_t &value, size_t offset);
+template DISKANN_DLLEXPORT void read_value<float>(AlignedFileReader &reader, float &value, size_t offset);
+template DISKANN_DLLEXPORT void read_value<uint32_t>(AlignedFileReader &reader, uint32_t &value, size_t offset);
+template DISKANN_DLLEXPORT void read_value<uint64_t>(AlignedFileReader &reader, uint64_t &value, size_t offset);
+
+#endif
+
+} // namespace diskann
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/src/windows_aligned_file_reader.cpp b/packages/leann-backend-diskann/third_party/DiskANN/src/windows_aligned_file_reader.cpp
new file mode 100644
index 0000000..3650b92
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/src/windows_aligned_file_reader.cpp
@@ -0,0 +1,189 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#ifdef _WINDOWS
+#ifndef USE_BING_INFRA
+#include "windows_aligned_file_reader.h"
+#include <iostream>
+#include "utils.h"
+#include <stdlib.h>
+
+#define SECTOR_LEN 4096
+
+void WindowsAlignedFileReader::open(const std::string &fname)
+{
+#ifdef UNICODE
+ m_filename = std::wstring(fname.begin(), fname.end());
+#else
+ m_filename = fname;
+#endif
+
+ this->register_thread();
+}
+
+void WindowsAlignedFileReader::close()
+{
+ for (auto &k_v : ctx_map)
+ {
+ IOContext ctx = ctx_map[k_v.first];
+ CloseHandle(ctx.fhandle);
+ }
+}
+
+void WindowsAlignedFileReader::register_thread()
+{
+ std::unique_lock<std::mutex> lk(this->ctx_mut);
+ if (this->ctx_map.find(std::this_thread::get_id()) != ctx_map.end())
+ {
+ diskann::cout << "Warning:: Duplicate registration for thread_id : " << std::this_thread::get_id() << std::endl;
+ }
+
+ IOContext ctx;
+ ctx.fhandle = CreateFile(
+ m_filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
+ FILE_ATTRIBUTE_READONLY | FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS, NULL);
+ if (ctx.fhandle == INVALID_HANDLE_VALUE)
+ {
+ const size_t c_max_filepath_len = 256;
+ size_t actual_len = 0;
+ char filePath[c_max_filepath_len];
+ if (wcstombs_s(&actual_len, filePath, c_max_filepath_len, m_filename.c_str(), m_filename.length()) == 0)
+ {
+ diskann::cout << "Error opening " << filePath << " -- error=" << GetLastError() << std::endl;
+ }
+ else
+ {
+ diskann::cout << "Error converting wchar to char -- error=" << GetLastError() << std::endl;
+ }
+ }
+
+ // create IOCompletionPort
+ ctx.iocp = CreateIoCompletionPort(ctx.fhandle, ctx.iocp, 0, 0);
+
+ // create MAX_DEPTH # of reqs
+ for (uint64_t i = 0; i < MAX_IO_DEPTH; i++)
+ {
+ OVERLAPPED os;
+ memset(&os, 0, sizeof(OVERLAPPED));
+ // os.hEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
+ ctx.reqs.push_back(os);
+ }
+ this->ctx_map.insert(std::make_pair(std::this_thread::get_id(), ctx));
+}
+
+IOContext &WindowsAlignedFileReader::get_ctx()
+{
+ std::unique_lock<std::mutex> lk(this->ctx_mut);
+ if (ctx_map.find(std::this_thread::get_id()) == ctx_map.end())
+ {
+ std::stringstream stream;
+ stream << "unable to find IOContext for thread_id : " << std::this_thread::get_id() << "\n";
+ throw diskann::ANNException(stream.str(), -2, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ IOContext &ctx = ctx_map[std::this_thread::get_id()];
+ lk.unlock();
+ return ctx;
+}
+
+void WindowsAlignedFileReader::read(std::vector<AlignedRead> &read_reqs, IOContext &ctx, bool async)
+{
+ using namespace std::chrono_literals;
+ // execute each request sequentially
+ size_t n_reqs = read_reqs.size();
+ uint64_t n_batches = ROUND_UP(n_reqs, MAX_IO_DEPTH) / MAX_IO_DEPTH;
+ for (uint64_t i = 0; i < n_batches; i++)
+ {
+ // reset all OVERLAPPED objects
+ for (auto &os : ctx.reqs)
+ {
+ // HANDLE evt = os.hEvent;
+ memset(&os, 0, sizeof(os));
+ // os.hEvent = evt;
+
+ /*
+ if (ResetEvent(os.hEvent) == 0) {
+ diskann::cerr << "ResetEvent failed" << std::endl;
+ exit(-3);
+ }
+ */
+ }
+
+ // batch start/end
+ uint64_t batch_start = MAX_IO_DEPTH * i;
+ uint64_t batch_size = std::min((uint64_t)(n_reqs - batch_start), (uint64_t)MAX_IO_DEPTH);
+
+ // fill OVERLAPPED and issue them
+ for (uint64_t j = 0; j < batch_size; j++)
+ {
+ AlignedRead &req = read_reqs[batch_start + j];
+ OVERLAPPED &os = ctx.reqs[j];
+
+ uint64_t offset = req.offset;
+ uint64_t nbytes = req.len;
+ char *read_buf = (char *)req.buf;
+ assert(IS_ALIGNED(read_buf, SECTOR_LEN));
+ assert(IS_ALIGNED(offset, SECTOR_LEN));
+ assert(IS_ALIGNED(nbytes, SECTOR_LEN));
+
+ // fill in OVERLAPPED struct
+ os.Offset = offset & 0xffffffff;
+ os.OffsetHigh = (offset >> 32);
+
+ BOOL ret = ReadFile(ctx.fhandle, read_buf, (DWORD)nbytes, NULL, &os);
+ if (ret == FALSE)
+ {
+ auto error = GetLastError();
+ if (error != ERROR_IO_PENDING)
+ {
+ diskann::cerr << "Error queuing IO -- " << error << "\n";
+ }
+ }
+ else
+ {
+ diskann::cerr << "Error queueing IO -- ReadFile returned TRUE" << std::endl;
+ }
+ }
+ DWORD n_read = 0;
+ uint64_t n_complete = 0;
+ ULONG_PTR completion_key = 0;
+ OVERLAPPED *lp_os;
+ while (n_complete < batch_size)
+ {
+ if (GetQueuedCompletionStatus(ctx.iocp, &n_read, &completion_key, &lp_os, INFINITE) != 0)
+ {
+ // successfully dequeued a completed I/O
+ n_complete++;
+ }
+ else
+ {
+ // failed to dequeue OR dequeued failed I/O
+ if (lp_os == NULL)
+ {
+ DWORD error = GetLastError();
+ if (error != WAIT_TIMEOUT)
+ {
+ diskann::cerr << "GetQueuedCompletionStatus() failed "
+ "with error = "
+ << error << std::endl;
+ throw diskann::ANNException("GetQueuedCompletionStatus failed with error: ", error, __FUNCSIG__,
+ __FILE__, __LINE__);
+ }
+ // no completion packet dequeued ==> sleep for 5us and try
+ // again
+ std::this_thread::sleep_for(5us);
+ }
+ else
+ {
+ // completion packet for failed IO dequeued
+ auto op_idx = lp_os - ctx.reqs.data();
+ std::stringstream stream;
+ stream << "I/O failed , offset: " << read_reqs[op_idx].offset
+ << "with error code: " << GetLastError() << std::endl;
+ throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__);
+ }
+ }
+ }
+ }
+}
+#endif
+#endif
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/tests/CMakeLists.txt b/packages/leann-backend-diskann/third_party/DiskANN/tests/CMakeLists.txt
new file mode 100644
index 0000000..6af8405
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/tests/CMakeLists.txt
@@ -0,0 +1,41 @@
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT license.
+
+set(CMAKE_COMPILE_WARNING_AS_ERROR ON)
+
+find_package(Boost COMPONENTS unit_test_framework)
+
+# For Windows, fall back to nuget version if find_package didn't find it.
+if (MSVC AND NOT Boost_FOUND)
+ set(DISKANN_BOOST_INCLUDE "${DISKANN_MSVC_PACKAGES}/boost/lib/native/include")
+ # Multi-threaded static library.
+ set(UNIT_TEST_FRAMEWORK_LIB_PATTERN "${DISKANN_MSVC_PACKAGES}/boost_unit_test_framework-vc${MSVC_TOOLSET_VERSION}/lib/native/libboost_unit_test_framework-vc${MSVC_TOOLSET_VERSION}-mt-x64-*.lib")
+ file(GLOB DISKANN_BOOST_UNIT_TEST_FRAMEWORK_LIB ${UNIT_TEST_FRAMEWORK_LIB_PATTERN})
+
+ set(UNIT_TEST_FRAMEWORK_DLIB_PATTERN "${DISKANN_MSVC_PACKAGES}/boost_unit_test_framework-vc${MSVC_TOOLSET_VERSION}/lib/native/libboost_unit_test_framework-vc${MSVC_TOOLSET_VERSION}-mt-gd-x64-*.lib")
+ file(GLOB DISKANN_BOOST_UNIT_TEST_FRAMEWORK_DLIB ${UNIT_TEST_FRAMEWORK_DLIB_PATTERN})
+
+ if (EXISTS ${DISKANN_BOOST_INCLUDE} AND EXISTS ${DISKANN_BOOST_UNIT_TEST_FRAMEWORK_LIB} AND EXISTS ${DISKANN_BOOST_UNIT_TEST_FRAMEWORK_DLIB})
+ set(Boost_FOUND ON)
+ set(Boost_INCLUDE_DIR ${DISKANN_BOOST_INCLUDE})
+ add_library(Boost::unit_test_framework STATIC IMPORTED)
+ set_target_properties(Boost::unit_test_framework PROPERTIES IMPORTED_LOCATION_RELEASE "${DISKANN_BOOST_UNIT_TEST_FRAMEWORK_LIB}")
+ set_target_properties(Boost::unit_test_framework PROPERTIES IMPORTED_LOCATION_DEBUG "${DISKANN_BOOST_UNIT_TEST_FRAMEWORK_DLIB}")
+ message(STATUS "Falling back to using Boost from the nuget package")
+ else()
+ message(WARNING "Couldn't find Boost. Was looking for ${DISKANN_BOOST_INCLUDE} and ${UNIT_TEST_FRAMEWORK_LIB_PATTERN}")
+ endif()
+endif()
+
+if (NOT Boost_FOUND)
+ message(FATAL_ERROR "Couldn't find Boost dependency")
+endif()
+
+
+set(DISKANN_UNIT_TEST_SOURCES main.cpp index_write_parameters_builder_tests.cpp)
+
+add_executable(${PROJECT_NAME}_unit_tests ${DISKANN_SOURCES} ${DISKANN_UNIT_TEST_SOURCES})
+target_link_libraries(${PROJECT_NAME}_unit_tests ${PROJECT_NAME} ${DISKANN_TOOLS_TCMALLOC_LINK_OPTIONS} Boost::unit_test_framework)
+
+add_test(NAME ${PROJECT_NAME}_unit_tests COMMAND ${PROJECT_NAME}_unit_tests)
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/tests/README.md b/packages/leann-backend-diskann/third_party/DiskANN/tests/README.md
new file mode 100644
index 0000000..113c998
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/tests/README.md
@@ -0,0 +1,11 @@
+# Unit Test project
+
+This unit test project is based on the [boost unit test framework](https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/index.html). Below are the simple steps to add new unit test, you could find more usage from the [boost unit test document](https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/index.html).
+
+## How to add unit test
+
+- Create new [BOOST_AUTO_TEST_SUITE](https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/boost_test/utf_reference/test_org_reference/test_org_boost_auto_test_suite.html) for each class in an individual cpp file
+
+- Add [BOOST_AUTO_TEST_CASE](https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/boost_test/utf_reference/test_org_reference/test_org_boost_auto_test_case.html) for each test case in the [BOOST_AUTO_TEST_SUITE](https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/boost_test/utf_reference/test_org_reference/test_org_boost_auto_test_suite.html)
+
+- Update the [CMakeLists.txt](CMakeLists.txt) file to add the new cpp file to the test project
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/tests/index_write_parameters_builder_tests.cpp b/packages/leann-backend-diskann/third_party/DiskANN/tests/index_write_parameters_builder_tests.cpp
new file mode 100644
index 0000000..0aa798d
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/tests/index_write_parameters_builder_tests.cpp
@@ -0,0 +1,58 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#include <boost/test/unit_test.hpp>
+
+#include "parameters.h"
+
+BOOST_AUTO_TEST_SUITE(IndexWriteParametersBuilder_tests)
+
+BOOST_AUTO_TEST_CASE(test_build)
+{
+ uint32_t search_list_size = rand();
+ uint32_t max_degree = rand();
+ float alpha = (float)rand();
+ uint32_t filter_list_size = rand();
+ uint32_t max_occlusion_size = rand();
+ bool saturate_graph = true;
+
+ diskann::IndexWriteParametersBuilder builder(search_list_size, max_degree);
+
+ builder.with_alpha(alpha)
+ .with_filter_list_size(filter_list_size)
+ .with_max_occlusion_size(max_occlusion_size)
+ .with_num_threads(0)
+ .with_saturate_graph(saturate_graph);
+
+ {
+ auto parameters = builder.build();
+
+ BOOST_TEST(search_list_size == parameters.search_list_size);
+ BOOST_TEST(max_degree == parameters.max_degree);
+ BOOST_TEST(alpha == parameters.alpha);
+ BOOST_TEST(filter_list_size == parameters.filter_list_size);
+ BOOST_TEST(max_occlusion_size == parameters.max_occlusion_size);
+ BOOST_TEST(saturate_graph == parameters.saturate_graph);
+
+ BOOST_TEST(parameters.num_threads > (uint32_t)0);
+ }
+
+ {
+ uint32_t num_threads = rand() + 1;
+ saturate_graph = false;
+ builder.with_num_threads(num_threads).with_saturate_graph(saturate_graph);
+
+ auto parameters = builder.build();
+
+ BOOST_TEST(search_list_size == parameters.search_list_size);
+ BOOST_TEST(max_degree == parameters.max_degree);
+ BOOST_TEST(alpha == parameters.alpha);
+ BOOST_TEST(filter_list_size == parameters.filter_list_size);
+ BOOST_TEST(max_occlusion_size == parameters.max_occlusion_size);
+ BOOST_TEST(saturate_graph == parameters.saturate_graph);
+
+ BOOST_TEST(num_threads == parameters.num_threads);
+ }
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/tests/main.cpp b/packages/leann-backend-diskann/third_party/DiskANN/tests/main.cpp
new file mode 100644
index 0000000..53440a1
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/tests/main.cpp
@@ -0,0 +1,6 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license.
+
+#define BOOST_TEST_MODULE diskann_unit_tests
+
+#include <boost/test/unit_test.hpp>
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/windows/packages.config.in b/packages/leann-backend-diskann/third_party/DiskANN/windows/packages.config.in
new file mode 100644
index 0000000..f8eecf0
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/windows/packages.config.in
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="boost" version="1.78.0" />
+ <!-- This will be replaced by CMake with the corresponding VisualStudio
+ version (e.g. vc142 for Visual Studio 2019). -->
+ <package id="boost_program_options-vc${MSVC_TOOLSET_VERSION}" version="1.78.0" />
+ <package id="boost_unit_test_framework-vc${MSVC_TOOLSET_VERSION}" version="1.78.0" />
+ <package id="intelopenmp.redist.win" version="2022.0.3.3747" />
+ <package id="intelopenmp.devel.win" version="2022.0.3.3747" />
+ <package id="intelmkl.static.win-x64" version="2022.0.3.171" />
+</packages>
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/windows/packages_restapi.config.in b/packages/leann-backend-diskann/third_party/DiskANN/windows/packages_restapi.config.in
new file mode 100644
index 0000000..6d1a60c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/windows/packages_restapi.config.in
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="cpprestsdk.v142" version="2.10.15" />
+</packages>
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/SSD_index.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/SSD_index.md
new file mode 100644
index 0000000..3144528
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/SSD_index.md
@@ -0,0 +1,74 @@
+**Usage for SSD-based indices**
+===============================
+
+To generate an SSD-friendly index, use the `apps/build_disk_index` program.
+----------------------------------------------------------------------------
+
+The arguments are as follows:
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **--dist_fn**: Three distance functions are supported: cosine distance, minimum Euclidean distance (l2) and maximum inner product (mips).
+3. **--data_file**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as an integer. The next 4 bytes represent the dimension of data as an integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. `sizeof(T)` is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+4. **--index_path_prefix**: the index will span a few files, all beginning with the specified prefix path. For example, if you provide `~/index_test` as the prefix path, build generates files such as `~/index_test_pq_pivots.bin, ~/index_test_pq_compressed.bin, ~/index_test_disk.index, ...`. There may be between 8 and 10 files generated with this prefix depending on how the index is constructed.
+5. **-R (--max_degree)** (default is 64): the degree of the graph index, typically between 60 and 150. Larger R will result in larger indices and longer indexing times, but better search quality.
+6. **-L (--Lbuild)** (default is 100): the size of search list during index build. Typical values are between 75 to 200. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Use a value for L value that is at least the value of R unless you need to build indices really quickly and can somewhat compromise on quality.
+7. **-B (--search_DRAM_budget)**: bound on the memory footprint of the index at search time in GB. Once built, the index will use up only the specified RAM limit, the rest will reside on disk. This will dictate how aggressively we compress the data vectors to store in memory. Larger will yield better performance at search time. For an n point index, to use b byte PQ compressed representation in memory, use `B = ((n * b) / 2^30 + (250000*(4*R + sizeof(T)*ndim)) / 2^30)`. The second term in the summation is to allow some buffer for caching about 250,000 nodes from the graph in memory while serving. If you are not sure about this term, add 0.25GB to the first term.
+8. **-M (--build_DRAM_budget)**: Limit on the memory allowed for building the index in GB. If you specify a value less than what is required to build the index in one pass, the index is built using a divide and conquer approach so that sub-graphs will fit in the RAM budget. The sub-graphs are overlayed to build the overall index. This approach can be upto 1.5 times slower than building the index in one shot. Allocate as much memory as your RAM allows.
+9. **-T (--num_threads)** (default is to get_omp_num_procs()): number of threads used by the index build process. Since the code is highly parallel, the indexing time improves almost linearly with the number of threads (subject to the cores available on the machine and DRAM bandwidth).
+10. **--PQ_disk_bytes** (default is 0): Use 0 to store uncompressed data on SSD. This allows the index to asymptote to 100% recall. If your vectors are too large to store in SSD, this parameter provides the option to compress the vectors using PQ for storing on SSD. This will trade off recall. You would also want this to be greater than the number of bytes used for the PQ compressed data stored in-memory
+11. **--build_PQ_bytes** (default is 0): Set to a positive value less than the dimensionality of the data to enable faster index build with PQ based distance comparisons.
+12. **--use_opq**: use the flag to use OPQ rather than PQ compression. OPQ is more space efficient for some high dimensional datasets, but also needs a bit more build time.
+
+To search the SSD-index, use the `apps/search_disk_index` program.
+-------------------------------------------------------------------
+
+The arguments are as follows:
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported. Use the same data type as in arg (1) above used in building the index.
+2. **--dist_fn**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips). Use the same distance as in arg (2) above used in building the index.
+3. **--index_path_prefix**: same as the prefix used in building the index (see arg 4 above).
+4. **--num_nodes_to_cache** (default is 0): While serving the index, the entire graph is stored on SSD. For faster search performance, you can cache a few frequently accessed nodes in memory.
+5. **-T (--num_threads)** (default is to get_omp_num_procs()): The number of threads used for searching. Threads run in parallel and one thread handles one query at a time. More threads will result in higher aggregate query throughput, but will also use more IOs/second across the system, which may lead to higher per-query latency. So find the balance depending on the maximum number of IOPs supported by the SSD.
+6. **-W (--beamwidth)** (default is 2): The beamwidth to be used for search. This is the maximum number of IO requests each query will issue per iteration of search code. Larger beamwidth will result in fewer IO round-trips per query, but might result in slightly higher total number of IO requests to SSD per query. For the highest query throughput with a fixed SSD IOps rating, use `W=1`. For best latency, use `W=4,8` or higher complexity search. Specifying 0 will optimize the beamwidth depending on the number of threads performing search, but will involve some tuning overhead.
+7. **--query_file**: The queries to be searched on in same binary file format as the data file in arg (2) above. The query file must be the same type as argument (1).
+8. **--gt_file**: The ground truth file for the queries in arg (7) and data file used in index construction. The binary file must start with *n*, the number of queries (4 bytes), followed by *d*, the number of ground truth elements per query (4 bytes), followed by `n*d` entries per query representing the d closest IDs per query in integer format, followed by `n*d` entries representing the corresponding distances (float). Total file size is `8 + 4*n*d + 4*n*d` bytes. The groundtruth file, if not available, can be calculated using the program `apps/utils/compute_groundtruth`. Use "null" if you do not have this file and if you do not want to compute recall.
+9. **K**: search for *K* neighbors and measure *K*-recall@*K*, meaning the intersection between the retrieved top-*K* nearest neighbors and ground truth *K* nearest neighbors.
+10. **result_output_prefix**: Search results will be stored in files with specified prefix, in bin format.
+11. **-L (--search_list)**: A list of search_list sizes to perform search with. Larger parameters will result in slower latencies, but higher accuracies. Must be at least the value of *K* in arg (9).
+
+
+Example with BIGANN:
+--------------------
+
+This example demonstrates the use of the commands above on a 100K slice of the [BIGANN dataset](http://corpus-texmex.irisa.fr/) with 128 dimensional SIFT descriptors applied to images.
+
+Download the base and query set and convert the data to binary format
+```bash
+mkdir -p DiskANN/build/data && cd DiskANN/build/data
+wget ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz
+tar -xf sift.tar.gz
+cd ..
+./apps/utils/fvecs_to_bin float data/sift/sift_learn.fvecs data/sift/sift_learn.fbin
+./apps/utils/fvecs_to_bin float data/sift/sift_query.fvecs data/sift/sift_query.fbin
+```
+
+Now build and search the index and measure the recall using ground truth computed using brutefoce.
+```bash
+./apps/utils/compute_groundtruth --data_type float --dist_fn l2 --base_file data/sift/sift_learn.fbin --query_file data/sift/sift_query.fbin --gt_file data/sift/sift_query_learn_gt100 --K 100
+# Using 0.003GB search memory budget for 100K vectors implies 32 byte PQ compression
+./apps/build_disk_index --data_type float --dist_fn l2 --data_path data/sift/sift_learn.fbin --index_path_prefix data/sift/disk_index_sift_learn_R32_L50_A1.2 -R 32 -L50 -B 0.003 -M 1
+ ./apps/search_disk_index --data_type float --dist_fn l2 --index_path_prefix data/sift/disk_index_sift_learn_R32_L50_A1.2 --query_file data/sift/sift_query.fbin --gt_file data/sift/sift_query_learn_gt100 -K 10 -L 10 20 30 40 50 100 --result_path data/sift/res --num_nodes_to_cache 10000
+ ```
+
+The search might be slower on machine with remote SSDs. The output lists the query throughput, the mean and 99.9pc latency in microseconds and mean number of 4KB IOs to disk for each `L` parameter provided.
+
+```
+ L Beamwidth QPS Mean Latency 99.9 Latency Mean IOs CPU (s) Recall@10
+======================================================================================================================
+ 10 2 27723.95 2271.92 4700.00 8.81 40.47 81.79
+ 20 2 15369.23 4121.04 7576.00 15.93 61.60 96.42
+ 30 2 10335.75 6147.14 11424.00 23.30 74.96 98.78
+ 40 2 7684.18 8278.83 14714.00 30.78 94.27 99.40
+ 50 2 6421.66 9913.28 16550.00 38.35 116.86 99.63
+ 100 2 3337.98 19107.81 29292.00 76.59 226.88 99.91
+```
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/dynamic_index.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/dynamic_index.md
new file mode 100644
index 0000000..17c3fb3
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/dynamic_index.md
@@ -0,0 +1,187 @@
+<!-- Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the MIT license. -->
+
+**Usage for dynamic indices**
+================================
+
+A "dynamic" index refers to an index which supports insertion of new points into a (possibly previously built) index as well as deletions of points.
+While eager deletes can be supported by DiskANN, `lazy_deletes` are the preferred method.
+A sequence of lazy deletions must be followed by an invocation of the `consolidate_deletes` method that frees up slots in the index and edits the graph to maintain good recall.
+
+
+The program `apps/test_insert_deletes_consolidate` demonstrates this functionality. It allows the user to specify which points from the data file will be used
+to initially build the index, which points will be deleted from the index, and which points will be inserted into the index.
+Insertions, searches and lazy deletions can be performed concurrently.
+Conslolidation of lazy deletes can be performed synchnronously or concurrently with insertions and deletions.
+When modifying the index sequentially, the user has the ability to take *snapshots*--
+that is, save the index to memory for every *m* insertions or deletions instead of only at the end of the build.
+
+The program `apps/test_streaming_scenario` simulates a scenario where the index actively maintains a sliding window of active points from a larger dataset.
+The program starts with an index build over the first `active_window` set of points from a data file.
+The program then simultaneously inserts newer points drawn from the file and deletes older points from the index
+in chunks of `consolidate_interval` points so that the number of active points in the index is approximately `active_window`.
+It terminates when the end of data file is reached, and the final index has `active_window + consolidate_interval` number of points.
+
+The index also supports filters on steaming index, you can use `insert_point` function overloads to either insert points as before or insert points with labels.
+Additional options are added to support this in `apps/test_streaming_scenario` and `apps/test_streaming_scenario` please refer to program arguments for more details.
+
+---
+> Note
+* The index does not support mixed points, that is, either all points do not have labels or all points have labels.
+* You can search the built filter index (one built with filters) without filters as well.
+
+> WARNING: Deleting points in case of filtered build may cause the quality of Index to degrade and affect recall.
+---
+
+`apps/test_insert_deletes_consolidate` to try inserting, lazy deletes and consolidate_delete
+---------------------------------------------------------------------------------------------
+
+The arguments are as follows:
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **--dist_fn**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips).
+3. **--data_file**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as integer. The next 4 bytes represent the dimension of data as integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. sizeof(T) is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+4. **--index_path_prefix**: The constructed index components will be saved to this path prefix.
+5. **-R (--max_degree)** (default is 64): the degree of the graph index, typically between 32 and 150. Larger R will result in larger indices and longer indexing times, but might yield better search quality.
+6. **-L (--Lbuild)** (default is 100): the size of search list we maintain during index building. Typical values are between 75 to 400. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Ensure that value of L is at least that of R value unless you need to build indices really quickly and can somewhat compromise on quality.
+7. **--alpha** (default is 1.2): A float value between 1.0 and 1.5 which determines the diameter of the graph, which will be approximately *log n* to the base alpha. Typical values are between 1 to 1.5. 1 will yield the sparsest graph, 1.5 will yield denser graphs.
+8. **T (--num_threads)** (default is to get_omp_num_procs()): number of threads used by the index build process. Since the code is highly parallel, the indexing time improves almost linearly with the number of threads (subject to the cores available on the machine and DRAM bandwidth).
+9. **--points_to_skip**: number of points to skip from the beginning of the data file.
+10. **--max_points_to_insert**: the maximum size of the index.
+11. **--beginning_index_size**: how many points to build the initial index with. The number of points inserted dynamically will be max_points_to_insert - beginning_index_size.
+12. **--points_per_checkpoint**: when inserting and deleting sequentially, each update is handled in points_per_checkpoint batches. When updating concurrently, insertions are handled in points_per_checkpoint batches but deletions are always processed in a single batch.
+13. **--checkpoints_per_snapshot**: when inserting and deleting sequentially, the graph is saved to memory every checkpoints_per_snapshot checkpoints. This is not currently supported for concurrent updates.
+14. **--points_to_delete_from_beginning**: how many points to delete from the index, starting in order of insertion. If deletions are concurrent with insertions, points_to_delete_from_beginning cannot be larger than beginning_index_size.
+15. **--start_point_norm**: Set the starting node to a random point on a sphere of this radius. A reasonable choice is to set this to the average norm of the data set. Use when starting an index with zero points.
+16. **--do_concurrent** (default false): whether to perform conslidate_deletes and other updates concurrently or sequentially. If concurrent is specified, half the threads are used for insertions and half the threads are used for processing deletes. Note that insertions are performed before deletions if this flag is set to false, so in this case is possible to delete more than beginning_index_size points.
+
+`apps/test_streaming_scenario` to try inserting, lazy deletes and consolidate_delete
+---------------------------------------------------------------------------------------------
+
+The arguments are as follows:
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **--dist_fn**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips).
+3. **--data_file**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as integer. The next 4 bytes represent the dimension of data as integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. sizeof(T) is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+4. **--index_path_prefix**: The constructed index components will be saved to this path prefix.
+5. **-R (--max_degree)** (default is 64): the degree of the graph index, typically between 32 and 150. Larger R will result in larger indices and longer indexing times, but might yield better search quality.
+6. **-L (--Lbuild)** (default is 100): the size of search list we maintain during index building. Typical values are between 75 to 400. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Ensure that value of L is at least that of R value unless you need to build indices really quickly and can somewhat compromise on quality.
+7. **--alpha** (default is 1.2): A float value between 1.0 and 1.5 which determines the diameter of the graph, which will be approximately *log n* to the base alpha. Typical values are between 1 to 1.5. 1 will yield the sparsest graph, 1.5 will yield denser graphs.
+8. **--insert_threads**: number of threads used for inserting points in to the index.
+9. **--consolidate_threads**: number of threads used for consolidating deletes to the index.
+10. **--max_points_to_insert**: Maximum number of points from the data file to insert in to the index.
+11. **--active_window**: Approximate number of points in the index at any point.
+12. **--consolidate_interval**: Granularity at which insert and delete functions are called.
+13. **--start_point_norm**: Set the starting node to a random point on a sphere of this radius. A reasonable choice is to set this to the average norm of the data stream.
+
+** To build with filters add these optional parameters.
+
+14. **--label_file**: Filter data for each point, in `.txt` format. Line `i` of the file consists of a comma-separated list of labels corresponding to point `i` in the file passed via `--data_file`.
+15. **--FilteredLbuild**: If building a filtered index, we maintain a separate search list from the one provided by `--Lbuild/-L`.
+16. **--num_start_points**: number of frozen points in this case should be more then number of unique labels.
+17. **--universal_label**: Optionally, the label data may contain a special "universal" label. A point with the universal label can be matched against a query with any label. Note that if a point has the universal label, then the filter data must only have the universal label on the line corresponding.
+18. **--label_type**: Optionally, type of label to be use its either uint or short, defaulted to `uint`.
+
+To search the generated index, use the `apps/search_memory_index` program:
+---------------------------------------------------------------------------
+
+
+The arguments are as follows:
+
+1. **data_type**: The type of dataset you built the index on. float(32 bit), signed int8 and unsigned uint8 are supported. Use the same data type as in arg (1) above used in building the index.
+2. **dist_fn**: There are two distance functions supported: l2 and mips. There is an additional *fast_l2* implementation that could provide faster results for small (about a million-sized) indices. Use the same distance as in arg (2) above used in building the index.
+3. **memory_index_path**: index built above in argument (4).
+4. **T**: The number of threads used for searching. Threads run in parallel and one thread handles one query at a time. More threads will result in higher aggregate query throughput, but may lead to higher per-query latency, especially if the DRAM bandwidth is a bottleneck. So find the balance depending on throughput and latency required for your application.
+5. **query_bin**: The queries to be searched on in same binary file format as the data file (ii) above. The query file must be the same type as in argument (1).
+6. **truthset.bin**: The ground truth file for the queries in arg (7) and data file used in index construction. The binary file must start with *n*, the number of queries (4 bytes), followed by *d*, the number of ground truth elements per query (4 bytes), followed by `n*d` entries per query representing the d closest IDs per query in integer format, followed by `n*d` entries representing the corresponding distances (float). Total file size is `8 + 4*n*d + 4*n*d` bytes. The groundtruth file, if not available, can be calculated using the program `apps/utils/compute_groundtruth`. Use "null" if you do not have this file and if you do not want to compute recall.
+7. **K**: search for *K* neighbors and measure *K*-recall@*K*, meaning the intersection between the retrieved top-*K* nearest neighbors and ground truth *K* nearest neighbors.
+8. **result_output_prefix**: search results will be stored in files, one per L value (see next arg), with specified prefix, in binary format.
+9. **-L (--search_list)**: A list of search_list sizes to perform search with. Larger parameters will result in slower latencies, but higher accuracies. Must be at least the value of *K* in (7).
+10. **--dynamic** (default false): whether the index being searched is dynamic or not.
+11. **--tags** (default false): whether to search with tags. This should be used if point *i* in the ground truth file does not correspond the point in the *i*th position in the loaded index.
+
+** to search with filters add these
+
+12. **--filter_label**: Filter for each query. For each query, a search is performed with this filter.
+
+Example with BIGANN:
+--------------------
+
+This example demonstrates the use of the commands above on a 100K slice of the [BIGANN dataset](http://corpus-texmex.irisa.fr/) with 128 dimensional SIFT descriptors applied to images.
+
+Download the base and query set and convert the data to binary format
+```bash
+mkdir -p DiskANN/build/data && cd DiskANN/build/data
+wget ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz
+tar -xf sift.tar.gz
+cd ..
+./apps/utils/fvecs_to_bin float data/sift/sift_learn.fvecs data/sift/sift_learn.fbin
+./apps/utils/fvecs_to_bin float data/sift/sift_query.fvecs data/sift/sift_query.fbin
+```
+
+The example below tests the following scenario: using a file with 100000 points, the index is incrementally constructed point by point. After the first 50000 ponts are inserted, another concurrent job deletes the first 25000 points from the index and consolidates the index (edit the graph and cleans up resources). At the same time an additional 25000 points (i.e. points 50001 to 75000) are concurrently inserted into the index. Note that the index should be built **before** calculating the ground truth, since the memory index returns the slice of the sift100K dataset that was used to build the final graph (that is, points 25001-75000 in the original index).
+```bash
+type='float'
+data='data/sift/sift_learn.fbin'
+query='data/sift/sift_query.fbin'
+index_prefix='data/sift/index'
+result='data/sift/res'
+deletes=25000
+inserts=75000
+deletes_after=50000
+pts_per_checkpoint=10000
+begin=0
+thr=64
+index=${index_prefix}.after-concurrent-delete-del${deletes}-${inserts}
+gt_file=data/sift/gt100_learn-conc-${deletes}-${inserts}
+
+ ~/DiskANN/build/apps/test_insert_deletes_consolidate --data_type ${type} --dist_fn l2 --data_path ${data} --index_path_prefix ${index_prefix} -R 64 -L 300 --alpha 1.2 -T ${thr} --points_to_skip 0 --max_points_to_insert ${inserts} --beginning_index_size ${begin} --points_per_checkpoint ${pts_per_checkpoint} --checkpoints_per_snapshot 0 --points_to_delete_from_beginning ${deletes} --start_deletes_after ${deletes_after} --do_concurrent true;
+
+ ~/DiskANN/build/apps/utils/compute_groundtruth --data_type ${type} --dist_fn l2 --base_file ${index}.data --query_file ${query} --K 100 --gt_file ${gt_file} --tags_file ${index}.tags
+
+~/DiskANN/build/apps/search_memory_index --data_type ${type} --dist_fn l2 --index_path_prefix ${index} --result_path ${result} --query_file ${query} --gt_file ${gt_file} -K 10 -L 20 40 60 80 100 -T ${thr} --dynamic true --tags 1
+ ```
+
+ The example below tests the following scenario: using a file with 100000 points, insert 10000 points at a time. After the first 40000
+are inserted, start deleting the first 10000 points while inserting points 40000--50000. Then delete points 10000--20000 while inserting
+points 50000--60000 and so until the index is left with points 60000-100000.
+
+
+Generate labels for filtered build like this. Generating 50 unique labels zipf's distributed for 100K point dataset.
+```
+~/DiskANN/build/apps/utils/generate_synthetic_labels --num_labels 50 --num_points 100000 --output_file data/zipf_labels_50_100K.txt --distribution_type zipf
+```
+
+```bash
+type='float'
+data='data/sift/sift_learn.fbin'
+query='data/sift/sift_query.fbin'
+index_prefix='data/sift/idx_learn_str'
+result='data/sift/res'
+ins_thr=16
+cons_thr=16
+inserts=100000
+active=20000
+cons_int=10000
+index=${index_prefix}.after-streaming-act${active}-cons${cons_int}-max${inserts}
+gt=data/sift/gt100_learn-act${active}-cons${cons_int}-max${inserts}
+filter_label=1
+
+## filter options
+universal_label = '0'
+label_file = 'data/zipf_labels_50_100K.txt'
+num_start_points = 50
+gt_filtered= data/sift/gt100_learn-act${active}-cons${cons_int}-max${inserts}_wlabel_${filter_label}
+
+
+# Without Filters (build and search)
+./apps/test_streaming_scenario --data_type ${type} --dist_fn l2 --data_path ${data} --index_path_prefix ${index_prefix} -R 64 -L 600 --alpha 1.2 --insert_threads ${ins_thr} --consolidate_threads ${cons_thr} --max_points_to_insert ${inserts} --active_window ${active} --consolidate_interval ${cons_int} --start_point_norm 508;
+./apps/utils/compute_groundtruth --data_type ${type} --dist_fn l2 --base_file ${index}.data --query_file ${query} --K 100 --gt_file ${gt} --tags_file ${index}.tags
+./apps/search_memory_index --data_type ${type} --dist_fn l2 --index_path_prefix ${index} --result_path ${result} --query_file ${query} --gt_file ${gt} -K 10 -L 20 40 60 80 100 -T 64 --dynamic true --tags 1
+
+# With filters (build and search)
+
+./apps/test_streaming_scenario --data_type ${type} --num_start_points ${num_start_points} --label_file ${label_file} --universal_label {universal_label} --dist_fn l2 --data_path ${data} --index_path_prefix ${index_prefix} -R 64 -L 600 --alpha 1.2 --insert_threads ${ins_thr} --consolidate_threads ${cons_thr} --max_points_to_insert ${inserts} --active_window ${active} --consolidate_interval ${cons_int} --start_point_norm 508;
+./apps/utils/compute_groundtruth_for_filters --data_type ${type} --dist_fn l2 --base_file ${index}.data --query_file ${query} --K 100 --gt_file ${gt_filtered} --label_file ${label_file} --universal_label {universal_label} --filter_label {filter_label}
+./apps/search_memory_index --data_type ${type} --filter_label {filter_label} --dist_fn l2 --index_path_prefix ${index} --result_path ${result} --query_file ${query} --gt_file ${gt_filtered} -K 10 -L 20 40 60 80 100 -T 64 --dynamic true --tags 1
+```
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/filtered_in_memory.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/filtered_in_memory.md
new file mode 100644
index 0000000..fe34b80
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/filtered_in_memory.md
@@ -0,0 +1,126 @@
+**Usage for filtered indices**
+================================
+## Building a filtered Index
+DiskANN provides two algorithms for building an index with filters support: filtered-vamana and stitched-vamana. Here, we describe the parameters for building both. `apps/build_memory_index.cpp` and `apps/build_stitched_index.cpp` are respectively used to build each kind of index.
+
+### 1. filtered-vamana
+
+1. **`--data_type`**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **`--dist_fn`**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips).
+3. **`--data_file`**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as integer. The next 4 bytes represent the dimension of data as integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. sizeof(T) is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+4. **`--index_path_prefix`**: The constructed index components will be saved to this path prefix.
+5. **`-R (--max_degree)`** (default is 64): the degree of the graph index, typically between 32 and 150. Larger R will result in larger indices and longer indexing times, but might yield better search quality.
+6. **`-L (--Lbuild)`** (default is 100): the size of search list we maintain during index building. Typical values are between 75 to 400. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Ensure that value of L is at least that of R value unless you need to build indices really quickly and can somewhat compromise on quality. Note that this is to be used only for building an unfiltered index. The corresponding search list parameter for a filtered index is managed by `--FilteredLbuild`.
+7. **`--alpha`** (default is 1.2): A float value between 1.0 and 1.5 which determines the diameter of the graph, which will be approximately *log n* to the base alpha. Typical values are between 1 to 1.5. 1 will yield the sparsest graph, 1.5 will yield denser graphs.
+8. **`-T (--num_threads)`** (default is to get_omp_num_procs()): number of threads used by the index build process. Since the code is highly parallel, the indexing time improves almost linearly with the number of threads (subject to the cores available on the machine and DRAM bandwidth).
+9. **`--build_PQ_bytes`** (default is 0): Set to a positive value less than the dimensionality of the data to enable faster index build with PQ based distance comparisons. Defaults to using full precision vectors for distance comparisons.
+10. **`--use_opq`**: use the flag to use OPQ rather than PQ compression. OPQ is more space efficient for some high dimensional datasets, but also needs a bit more build time.
+11. **`--label_file`**: Filter data for each point, in `.txt` format. Line `i` of the file consists of a comma-separated list of filters corresponding to point `i` in the file passed via `--data_file`.
+12. **`--universal_label`**: Optionally, the the filter data may contain a "wild-card" filter corresponding to all filters. This is referred to as a universal label. Note that if a point has the universal label, then the filter data must only have the universal label on the line corresponding to said point.
+13. **`--FilteredLbuild`**: If building a filtered index, we maintain a separate search list from the one provided by `--Lbuild`.
+
+### 2. stitched-vamana
+1. **`--data_type`**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **`--data_path`**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as integer. The next 4 bytes represent the dimension of data as integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. sizeof(T) is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+3. **`--index_path_prefix`**: The constructed index components will be saved to this path prefix.
+4. **`-R (--max_degree)`** (default is 64): Recall that stitched-vamana first builds a sub-index for each filter. This parameter sets the max degree for each sub-index.
+5. **`-L (--Lbuild)`** (default is 100): the size of search list we maintain during sub-index building. Typical values are between 75 to 400. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Ensure that value of L is at least that of R value unless you need to build indices really quickly and can somewhat compromise on quality.
+6. **`--alpha`** (default is 1.2): A float value between 1.0 and 1.5 which determines the diameter of the graph, which will be approximately *log n* to the base alpha. Typical values are between 1 to 1.5. 1 will yield the sparsest graph, 1.5 will yield denser graphs.
+7. **`-T (--num_threads)`** (default is to get_omp_num_procs()): number of threads used by the index build process. Since the code is highly parallel, the indexing time improves almost linearly with the number of threads (subject to the cores available on the machine and DRAM bandwidth).
+8. **`--label_file`**: Filter data for each point, in `.txt` format. Line `i` of the file consists of a comma-separated list of filters corresponding to point `i` in the file passed via `--data_file`.
+9. **`--universal_label`**: Optionally, the the filter data may contain a "wild-card" filter corresponding to all filters. This is referred to as a universal label. Note that if a point has the universal label, then the filter data must only have the universal label on the line corresponding to said point.
+10. **`--Stitched_R`**: Once all sub-indices are "stitched" together, we prune the resulting graph down to the degree given by this parameter.
+
+## Computing a groundtruth file for a filtered index
+In order to evaluate the performance of our algorithms, we can compare its results (i.e. the top `k` neighbors found for each query) against the results found by an exact nearest neighbor search. We provide the program `apps/utils/compute_groundtruth.cpp` to provide the results for the latter:
+
+1. **`--data_type`** The type of dataset you built an index with. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **`--dist_fn`**: There are two distance functions supported: l2 and mips.
+3. **`--base_file`**: The input data over which to build an index, in .bin format. Corresponds to the `--data_path` argument from above.
+4. **`--query_file`**: The queries to be searched on, which are stored in the same .bin format.
+5. **`--label_file`**: Filter data for each point, in `.txt` format. Line `i` of the file consists of a comma-separated list of filters corresponding to point `i` in the file passed via `--data_file`.
+6. **`--filter_label`**: Filter for each query. For each query, a search is performed with this filter.
+7. **`--universal_label`**: Corresponds to the universal label passed when building an index with filter support.
+8. **`--gt_file`**: File to output results to. The binary file starts with `n`, the number of queries (4 bytes), followed by `d`, the number of ground truth elements per query (4 bytes), followed by `n*d` entries per query representing the `d` closest IDs per query in integer format, followed by `n*d` entries representing the corresponding distances (float). Total file size is `8 + 4*n*d + 4*n*d` bytes.
+9. **`-K`**: The number of nearest neighbors to compute for each query.
+
+
+
+## Searching a Filtered Index
+
+Searching a filtered index uses the `apps/search_memory_index.cpp`:
+
+1. **`--data_type`**: The type of dataset you built the index on. float(32 bit), signed int8 and unsigned uint8 are supported. Use the same data type as in arg (1) above used in building the index.
+2. **`--dist_fn`**: There are two distance functions supported: l2 and mips. There is an additional *fast_l2* implementation that could provide faster results for small (about a million-sized) indices. Use the same distance as in arg (2) above used in building the index. Note that stitched-vamana only supports l2.
+3. **`--index_path_prefix`**: index built above in argument (4).
+4. **`--result_path`**: search results will be stored in files, one per L value (see last arg), with specified prefix, in binary format.
+5. **`-T (--num_threads)`**: The number of threads used for searching. Threads run in parallel and one thread handles one query at a time. More threads will result in higher aggregate query throughput, but may lead to higher per-query latency, especially if the DRAM bandwidth is a bottleneck. So find the balance depending on throughput and latency required for your application.
+6. **`--query_file`**: The queries to be searched on in same binary file format as the data file (ii) above. The query file must be the same type as in argument (1).
+7. **`--filter_label`**: The filter to be used when searching an index with filters. For each query, a search is performed with this filter.
+8. **`--gt_file`**: The ground truth file for the queries and data file used in index construction. Use "null" if you do not have this file and if you do not want to compute recall. Note that if building a filtered index, a special groundtruth must be computed, as described above.
+9. **`-K`**: search for *K* neighbors and measure *K*-recall@*K*, meaning the intersection between the retrieved top-*K* nearest neighbors and ground truth *K* nearest neighbors.
+10. **`-L (--search_list)`**: A list of search_list sizes to perform search with. Larger parameters will result in slower latencies, but higher accuracies. Must be atleast the value of *K* in (7).
+
+Example with SIFT10K:
+--------------------
+We demonstrate how to work through this pipeline using the SIFT10K dataset (http://corpus-texmex.irisa.fr/). Before starting, make sure you have compiled diskANN according to the instructions in the README and can see the following binaries (paths with respect to repository root):
+- `build/apps/utils/compute_groundtruth`
+- `build/apps/utils/fvecs_to_bin`
+- `build/apps/build_memory_index`
+- `build/apps/build_stitched_index`
+- `build/apps/search_memory_index`
+
+Now, download the base and query set and convert the data to binary format:
+```bash
+wget ftp://ftp.irisa.fr/local/texmex/corpus/siftsmall.tar.gz
+tar -zxvf siftsmall.tar.gz
+build/apps/utils/fvecs_to_bin float siftsmall/siftsmall_base.fvecs siftsmall/siftsmall_base.bin
+build/apps/utils/fvecs_to_bin float siftsmall/siftsmall_query.fvecs siftsmall/siftsmall_query.bin
+```
+
+We now need to make label file for our vectors. For convenience, we've included a synthetic label generator through which we can generate label file as follow
+```bash
+ build/apps/utils/generate_synthetic_labels --num_labels 50 --num_points 10000 --output_file ./rand_labels_50_10K.txt --distribution_type zipf
+```
+Note : `distribution_type` can be `rand` or `zipf`
+
+This will genearate label file with 10000 data points with 50 distinct labels, ranging from 1 to 50 assigned using zipf distribution (0 is the universal label).
+
+Label count for each unique label in the generated label file can be printed with help of following command
+```bash
+ build/apps/utils/stats_label_data.exe --labels_file ./rand_labels_50_10K.txt --universal_label 0
+```
+
+Note that neither approach is designed for use with random synthetic labels, which will lead to unpredictable accuracy at search time.
+
+Now build and search the index and measure the recall using ground truth computed using bruteforce. We search for results with the filter 35.
+```bash
+build/apps/utils/compute_groundtruth --data_type float --dist_fn l2 --base_file siftsmall/siftsmall_base.bin --query_file siftsmall/siftsmall_query.bin --gt_file siftsmall/siftsmall_gt_35.bin --K 100 --label_file ./rand_labels_50_10K.txt --filter_label 35 --universal_label 0
+build/apps/build_memory_index --data_type float --dist_fn l2 --data_path siftsmall/siftsmall_base.bin --index_path_prefix siftsmall/siftsmall_R32_L50_filtered_index -R 32 --FilteredLbuild 50 --alpha 1.2 --label_file ./rand_labels_50_10K.txt --universal_label 0
+build/apps/build_stitched_index --data_type float --data_path siftsmall/siftsmall_base.bin --index_path_prefix siftsmall/siftsmall_R20_L40_SR32_stitched_index -R 20 -L 40 --stitched_R 32 --alpha 1.2 --label_file ./rand_labels_50_10K.txt --universal_label 0
+build/apps/search_memory_index --data_type float --dist_fn l2 --index_path_prefix data/sift/siftsmall_R20_L40_SR32_filtered_index --query_file siftsmall/siftsmall_query.bin --gt_file siftsmall/siftsmall_gt_35.bin --filter_label 35 -K 10 -L 10 20 30 40 50 100 --result_path siftsmall/filtered_search_results
+build/apps/search_memory_index --data_type float --dist_fn l2 --index_path_prefix data/sift/siftsmall_R20_L40_SR32_stitched_index --query_file siftsmall/siftsmall_query.bin --gt_file siftsmall/siftsmall_gt_35.bin --filter_label 35 -K 10 -L 10 20 30 40 50 100 --result_path siftsmall/stitched_search_results
+```
+
+ The output of both searches is listed below. The throughput (Queries/sec) as well as mean and 99.9 latency in microseconds for each `L` parameter provided. (Measured on a physical machine with a Intel(R) Xeon(R) W-2145 CPU and 64 GB RAM)
+ ```
+ Stitched Index
+ Ls QPS Avg dist cmps Mean Latency (mus) 99.9 Latency Recall@10
+=================================================================================
+ 10 31324.39 37.33 116.79 311.90 17.80
+ 20 91357.57 44.36 193.06 1042.30 17.90
+ 30 69314.48 49.89 258.09 1398.00 18.20
+ 40 61421.29 60.52 289.08 1515.00 18.60
+ 50 54203.48 70.27 294.26 685.10 19.40
+ 100 52904.45 79.00 336.26 1018.80 19.50
+
+Filtered Index
+ Ls QPS Avg dist cmps Mean Latency (mus) 99.9 Latency Recall@10
+=================================================================================
+ 10 69671.84 21.48 45.25 146.20 11.60
+ 20 168577.20 38.94 100.54 547.90 18.20
+ 30 127129.41 52.95 126.83 768.40 19.70
+ 40 106349.04 62.38 167.23 899.10 20.90
+ 50 89952.33 70.95 189.12 1070.80 22.10
+ 100 56899.00 112.26 304.67 636.60 23.80
+ ```
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/filtered_ssd_index.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/filtered_ssd_index.md
new file mode 100644
index 0000000..7457d8c
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/filtered_ssd_index.md
@@ -0,0 +1,103 @@
+**Usage for filtered indices**
+================================
+
+To generate an SSD-friendly index, use the `apps/build_disk_index` program.
+----------------------------------------------------------------------------
+
+## Building a SSD based filtered Index
+
+### filtered-vamana SSD Index
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **--dist_fn**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips).
+3. **--data_file**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as an integer. The next 4 bytes represent the dimension of data as an integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. `sizeof(T)` is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+4. **--index_path_prefix**: the index will span a few files, all beginning with the specified prefix path. For example, if you provide `~/index_test` as the prefix path, build generates files such as `~/index_test_pq_pivots.bin, ~/index_test_pq_compressed.bin, ~/index_test_disk.index, ...`. There may be between 8 and 10 files generated with this prefix depending on how the index is constructed.
+5. **-R (--max_degree)** (default is 64): the degree of the graph index, typically between 60 and 150. Larger R will result in larger indices and longer indexing times, but better search quality.
+6. **-L (--Lbuild)** (default is 100): the size of search listduring index build. Typical values are between 75 to 200. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Use a value for L value that is at least the value of R unless you need to build indices really quickly and can somewhat compromise on quality. Note that this is to be used only for building an unfiltered index. The corresponding search list parameter for a filtered index is managed by `--FilteredLbuild`.
+7. **-B (--search_DRAM_budget)**: bound on the memory footprint of the index at search time in GB. Once built, the index will use up only the specified RAM limit, the rest will reside on disk. This will dictate how aggressively we compress the data vectors to store in memory. Larger will yield better performance at search time. For an n point index, to use b byte PQ compressed representation in memory, use `B = ((n * b) / 2^30 + (250000*(4*R + sizeof(T)*ndim)) / 2^30)`. The second term in the summation is to allow some buffer for caching about 250,000 nodes from the graph in memory while serving. If you are not sure about this term, add 0.25GB to the first term.
+8. **-M (--build_DRAM_budget)**: Limit on the memory allowed for building the index in GB. If you specify a value less than what is required to build the index in one pass, the index is built using a divide and conquer approach so that sub-graphs will fit in the RAM budget. The sub-graphs are overlayed to build the overall index. This approach can be upto 1.5 times slower than building the index in one shot. Allocate as much memory as your RAM allows.
+9. **-T (--num_threads)** (default is to get_omp_num_procs()): number of threads used by the index build process. Since the code is highly parallel, the indexing time improves almost linearly with the number of threads (subject to the cores available on the machine and DRAM bandwidth).
+10. **--PQ_disk_bytes** (default is 0): Use 0 to store uncompressed data on SSD. This allows the index to asymptote to 100% recall. If your vectors are too large to store in SSD, this parameter provides the option to compress the vectors using PQ for storing on SSD. This will trade off recall. You would also want this to be greater than the number of bytes used for the PQ compressed data stored in-memory
+11. **--build_PQ_bytes** (default is 0): Set to a positive value less than the dimensionality of the data to enable faster index build with PQ based distance comparisons.
+12. **--use_opq**: use the flag to use OPQ rather than PQ compression. OPQ is more space efficient for some high dimensional datasets, but also needs a bit more build time.
+13. **--label_file**: Filter data for each point, in `.txt` format. Line `i` of the file consists of a comma-separated list of filters corresponding to point `i` in the file passed via `--data_file`.
+14. **--universal_label**: Optionally, the label data may contain a special "universal" label. A point with the universal label can be matched against a query with any label. Note that if a point has the universal label, then the filter data must only have the universal label on the line corresponding.
+15. **--FilteredLbuild**: If building a filtered index, we maintain a separate search list from the one provided by `--Lbuild`.
+16. **--filter_threshold**: Threshold to break up the existing nodes to generate new graph internally by breaking dense points where each node will have a maximum F labels. Default value is zero where no break up happens for the dense points.
+
+
+## Computing a groundtruth file for a filtered index
+In order to evaluate the performance of our algorithms, we can compare its results (i.e. the top `k` neighbors found for each query) against the results found by an exact nearest neighbor search. We provide the program `apps/utils/compute_groundtruth.cpp` to provide the results for the latter:
+
+1. **`--data_type`** The type of dataset you built an index with. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **`--dist_fn`**: There are two distance functions supported: l2 and mips.
+3. **`--base_file`**: The input data over which to build an index, in .bin format. Corresponds to the `--data_path` argument from above.
+4. **`--query_file`**: The queries to be searched on, which are stored in the same .bin format.
+5. **`--label_file`**: Filter data for each point, in `.txt` format. Line `i` of the file consists of a comma-separated list of filters corresponding to point `i` in the file passed via `--data_file`.
+6. **`--filter_label`**: Filter for each query. For each query, a search is performed with this filter.
+7. **`--universal_label`**: Corresponds to the universal label passed when building an index with filter support.
+8. **`--gt_file`**: File to output results to. The binary file starts with `n`, the number of queries (4 bytes), followed by `d`, the number of ground truth elements per query (4 bytes), followed by `n*d` entries per query representing the `d` closest IDs per query in integer format, followed by `n*d` entries representing the corresponding distances (float). Total file size is `8 + 4*n*d + 4*n*d` bytes.
+9. **`-K`**: The number of nearest neighbors to compute for each query.
+
+## Searching a Filtered Index
+
+Searching a filtered index uses the `apps/search_disk_index.cpp`:
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported. Use the same data type as in arg (1) above used in building the index.
+2. **--dist_fn**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips). Use the same distance as in arg (2) above used in building the index.
+3. **--index_path_prefix**: same as the prefix used in building the index (see arg 4 above).
+4. **--num_nodes_to_cache** (default is 0): While serving the index, the entire graph is stored on SSD. For faster search performance, you can cache a few frequently accessed nodes in memory.
+5. **-T (--num_threads)** (default is to get_omp_num_procs()): The number of threads used for searching. Threads run in parallel and one thread handles one query at a time. More threads will result in higher aggregate query throughput, but will also use more IOs/second across the system, which may lead to higher per-query latency. So find the balance depending on the maximum number of IOPs supported by the SSD.
+6. **-W (--beamwidth)** (default is 2): The beamwidth to be used for search. This is the maximum number of IO requests each query will issue per iteration of search code. Larger beamwidth will result in fewer IO round-trips per query, but might result in slightly higher total number of IO requests to SSD per query. For the highest query throughput with a fixed SSD IOps rating, use `W=1`. For best latency, use `W=4,8` or higher complexity search. Specifying 0 will optimize the beamwidth depending on the number of threads performing search, but will involve some tuning overhead.
+7. **--query_file**: The queries to be searched on in same binary file format as the data file in arg (2) above. The query file must be the same type as argument (1).
+8. **--gt_file**: The ground truth file for the queries in arg (7) and data file used in index construction. The binary file must start with *n*, the number of queries (4 bytes), followed by *d*, the number of ground truth elements per query (4 bytes), followed by `n*d` entries per query representing the d closest IDs per query in integer format, followed by `n*d` entries representing the corresponding distances (float). Total file size is `8 + 4*n*d + 4*n*d` bytes. The groundtruth file, if not available, can be calculated using the program `apps/utils/compute_groundtruth`. Use "null" if you do not have this file and if you do not want to compute recall.
+9. **-K**: search for *K* neighbors and measure *K*-recall@*K*, meaning the intersection between the retrieved top-*K* nearest neighbors and ground truth *K* nearest neighbors.
+10. **--result_path**: Search results will be stored in files with specified prefix, in bin format.
+11. **-L (--search_list)**: A list of search_list sizes to perform search with. Larger parameters will result in slower latencies, but higher accuracies. Must be atleast the value of *K* in arg (9).
+12. **--filter_label**: The filter to be used when searching an index with filters. For each query, a search is performed with this filter.
+
+
+Example with SIFT10K:
+--------------------
+We demonstrate how to work through this pipeline using the SIFT10K dataset (http://corpus-texmex.irisa.fr/). Before starting, make sure you have compiled diskANN according to the instructions in the README and can see the following binaries (paths with respect to repository root):
+- `build/apps/utils/compute_groundtruth`
+- `build/apps/utils/fvecs_to_bin`
+- `build/apps/build_disk_index`
+- `build/apps/search_disk_index`
+
+Now, download the base and query set and convert the data to binary format:
+```bash
+wget ftp://ftp.irisa.fr/local/texmex/corpus/siftsmall.tar.gz
+tar -zxvf siftsmall.tar.gz
+build/apps/utils/fvecs_to_bin float siftsmall/siftsmall_base.fvecs siftsmall/siftsmall_base.bin
+build/apps/utils/fvecs_to_bin float siftsmall/siftsmall_query.fvecs siftsmall/siftsmall_query.bin
+```
+
+We now need to make label file for our vectors. For convenience, we've included a synthetic label generator through which we can generate label file as follow
+```bash
+ build/apps/utils/generate_synthetic_labels --num_labels 50 --num_points 10000 --output_file ./rand_labels_50_10K.txt --distribution_type zipf
+```
+Note : `distribution_type` can be `rand` or `zipf`
+
+This will genearate label file with 10000 data points with 50 distinct labels, ranging from 1 to 50 assigned using zipf distribution (0 is the universal label).
+
+Now build and search the index and measure the recall using ground truth computed using bruteforce. We search for results with the filter 35.
+```bash
+build/apps/utils/compute_groundtruth --data_type float --dist_fn l2 --base_file siftsmall/siftsmall_base.bin --query_file siftsmall/siftsmall_query.bin --gt_file siftsmall_gt_35.bin --K 100 --label_file rand_labels_50_10K.txt --filter_label 35 --universal_label 0
+build/apps/build_disk_index --data_type float --dist_fn l2 --data_path siftsmall/siftsmall_base.bin --index_path_prefix data/sift/siftsmall_R32_L50_filtered -R 32 --FilteredLbuild 50 -B 1 -M 1 --label_file rand_labels_50_10K.txt --universal_label 0 -F 0
+build/apps/search_disk_index --data_type float --dist_fn l2 --index_path_prefix data/sift/siftsmall_R32_L50_filtered --result_path siftsmall/search_35 --query_file siftsmall/siftsmall_query.bin --gt_file siftsmall_gt_35.bin -K 10 -L 10 20 30 40 50 100 --filter_label 35 -W 4 -T 8
+```
+
+ The output of both searches is listed below. The throughput (Queries/sec) as well as mean and 99.9 latency in microseconds for each `L` parameter provided. (Measured on a physical machine with a 11th Gen Intel(R) Core(TM) i7-1185G7 CPU and 32 GB RAM)
+
+ ```
+Filtered Disk Index
+ L Beamwidth QPS Mean Latency 99.9 Latency Mean IOs CPU (s) Recall@10
+==================================================================================================================
+ 10 4 1922.02 4062.19 12849.00 15.49 66.19 11.80
+ 20 4 4609.91 1618.68 3438.00 30.66 140.48 17.20
+ 30 4 3377.83 2250.22 4631.00 42.70 202.39 20.70
+ 40 4 2707.77 2817.21 4889.00 51.46 267.03 22.00
+ 50 4 2191.56 3509.43 5943.00 60.80 349.10 23.50
+100 4 1257.92 6113.45 7321.00 109.08 609.42 23.90
+```
\ No newline at end of file
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/in_memory_index.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/in_memory_index.md
new file mode 100644
index 0000000..6d78320
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/in_memory_index.md
@@ -0,0 +1,73 @@
+**Usage for in-memory indices**
+================================
+
+To generate index, use the `apps/build_memory_index` program.
+--------------------------------------------------------------
+
+The arguments are as follows:
+
+1. **--data_type**: The type of dataset you wish to build an index on. float(32 bit), signed int8 and unsigned uint8 are supported.
+2. **--dist_fn**: There are two distance functions supported: minimum Euclidean distance (l2) and maximum inner product (mips).
+3. **--data_file**: The input data over which to build an index, in .bin format. The first 4 bytes represent number of points as integer. The next 4 bytes represent the dimension of data as integer. The following `n*d*sizeof(T)` bytes contain the contents of the data one data point in time. sizeof(T) is 1 for byte indices, and 4 for float indices. This will be read by the program as int8_t for signed indices, uint8_t for unsigned indices or float for float indices.
+4. **--index_path_prefix**: The constructed index components will be saved to this path prefix.
+5. **-R (--max_degree)** (default is 64): the degree of the graph index, typically between 32 and 150. Larger R will result in larger indices and longer indexing times, but might yield better search quality.
+6. **-L (--Lbuild)** (default is 100): the size of search list we maintain during index building. Typical values are between 75 to 400. Larger values will take more time to build but result in indices that provide higher recall for the same search complexity. Ensure that value of L is at least that of R value unless you need to build indices really quickly and can somewhat compromise on quality.
+7. **--alpha** (default is 1.2): A float value between 1.0 and 1.5 which determines the diameter of the graph, which will be approximately *log n* to the base alpha. Typical values are between 1 to 1.5. 1 will yield the sparsest graph, 1.5 will yield denser graphs.
+8. **T (--num_threads)** (default is to get_omp_num_procs()): number of threads used by the index build process. Since the code is highly parallel, the indexing time improves almost linearly with the number of threads (subject to the cores available on the machine and DRAM bandwidth).
+9. **--build_PQ_bytes** (default is 0): Set to a positive value less than the dimensionality of the data to enable faster index build with PQ based distance comparisons. Defaults to using full precision vectors for distance comparisons.
+10.**--use_opq**: use the flag to use OPQ rather than PQ compression. OPQ is more space efficient for some high dimensional datasets, but also needs a bit more build time.
+
+
+To search the generated index, use the `apps/search_memory_index` program:
+---------------------------------------------------------------------------
+
+
+The arguments are as follows:
+
+1. **data_type**: The type of dataset you built the index on. float(32 bit), signed int8 and unsigned uint8 are supported. Use the same data type as in arg (1) above used in building the index.
+2. **dist_fn**: There are two distance functions supported: l2 and mips. There is an additional *fast_l2* implementation that could provide faster results for small (about a million-sized) indices. Use the same distance as in arg (2) above used in building the index.
+3. **memory_index_path**: index built above in argument (4).
+4. **T**: The number of threads used for searching. Threads run in parallel and one thread handles one query at a time. More threads will result in higher aggregate query throughput, but may lead to higher per-query latency, especially if the DRAM bandwidth is a bottleneck. So find the balance depending on throughput and latency required for your application.
+5. **query_bin**: The queries to be searched on in same binary file format as the data file (ii) above. The query file must be the same type as in argument (1).
+6. **truthset.bin**: The ground truth file for the queries in arg (7) and data file used in index construction. The binary file must start with *n*, the number of queries (4 bytes), followed by *d*, the number of ground truth elements per query (4 bytes), followed by `n*d` entries per query representing the d closest IDs per query in integer format, followed by `n*d` entries representing the corresponding distances (float). Total file size is `8 + 4*n*d + 4*n*d` bytes. The groundtruth file, if not available, can be calculated using the program `apps/utils/compute_groundtruth`. Use "null" if you do not have this file and if you do not want to compute recall.
+7. **K**: search for *K* neighbors and measure *K*-recall@*K*, meaning the intersection between the retrieved top-*K* nearest neighbors and ground truth *K* nearest neighbors.
+8. **result_output_prefix**: search results will be stored in files, one per L value (see next arg), with specified prefix, in binary format.
+9. **-L (--search_list)**: A list of search_list sizes to perform search with. Larger parameters will result in slower latencies, but higher accuracies. Must be atleast the value of *K* in (7).
+
+
+Example with BIGANN:
+--------------------
+
+This example demonstrates the use of the commands above on a 100K slice of the [BIGANN dataset](http://corpus-texmex.irisa.fr/) with 128 dimensional SIFT descriptors applied to images.
+
+Download the base and query set and convert the data to binary format
+```bash
+mkdir -p DiskANN/build/data && cd DiskANN/build/data
+wget ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz
+tar -xf sift.tar.gz
+cd ..
+./apps/utils/fvecs_to_bin float data/sift/sift_learn.fvecs data/sift/sift_learn.fbin
+./apps/utils/fvecs_to_bin float data/sift/sift_query.fvecs data/sift/sift_query.fbin
+```
+
+Now build and search the index and measure the recall using ground truth computed using brutefoce.
+```bash
+./apps/utils/compute_groundtruth --data_type float --dist_fn l2 --base_file data/sift/sift_learn.fbin --query_file data/sift/sift_query.fbin --gt_file data/sift/sift_query_learn_gt100 --K 100
+./apps/build_memory_index --data_type float --dist_fn l2 --data_path data/sift/sift_learn.fbin --index_path_prefix data/sift/index_sift_learn_R32_L50_A1.2 -R 32 -L 50 --alpha 1.2
+ ./apps/search_memory_index --data_type float --dist_fn l2 --index_path_prefix data/sift/index_sift_learn_R32_L50_A1.2 --query_file data/sift/sift_query.fbin --gt_file data/sift/sift_query_learn_gt100 -K 10 -L 10 20 30 40 50 100 --result_path data/sift/res
+ ```
+
+
+ The output of search lists the throughput (Queries/sec) as well as mean and 99.9 latency in microseconds for each `L` parameter provided. (We measured on a 32-core 64-vCPU D-series Azure VM)
+ ```
+ Ls QPS Avg dist cmps Mean Latency (mus) 99.9 Latency Recall@10
+=================================================================================
+ 10 319901.78 348.93 174.51 4943.35 97.80
+ 20 346572.72 525.85 183.36 376.60 98.93
+ 30 292060.12 688.86 217.73 421.60 99.30
+ 40 248945.22 841.74 255.41 476.80 99.45
+ 50 215888.81 986.67 294.62 542.21 99.56
+ 100 129711.39 1631.94 490.58 848.61 99.88
+ ```
+
+
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/python.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/python.md
new file mode 100644
index 0000000..d009cd7
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/python.md
@@ -0,0 +1,133 @@
+# `diskannpy`
+
+We publish (sporadic) builds of `diskann` with python bindings to `pypi.org`, which you can install via `pip install diskannpy`.
+
+#### Caveats
+Native python modules with cffi need to be built for *every* version of Python and *every* OS and *every* native-integration-library.
+
+This makes for a complicated build matrix that only `(ana)conda` is properly fit to solve. However, we do build wheels
+for python 3.9-3.11, across linux, Windows, and macOS (x86_64). These versions are also built against `numpy` 1.25 -
+which makes for a hard runtime requirement that can be challenging to use if you are using older or newer versions of numpy.
+
+There *are* instructions for building against other versions of numpy
+[documented in this issue response](https://github.com/microsoft/DiskANN/issues/544#issuecomment-2103437976) if you require a different build.
+
+# Basic Usage
+
+`diskannpy` provides access to both building and reading `DiskANN` indices. In all cases, the _lingua franca_ is numpy
+ndarrays. Currently, the only supported dtypes are `np.float32`, `np.int8`, and `np.uint8`.
+
+`diskannpy` provides a number of helpful functions, like reading or writing `diskann` style vector binary files via the
+`vectors_to_file` and `vectors_from_file` functions. For a full suite of python functions and their documentation,
+please be sure to read the latest documentation @ [https://microsoft.github.io/](https://microsoft.github.io/DiskANN/docs/python/latest/diskannpy.html).
+
+
+## Scenarios
+The following scenarios are supported via the `diskannpy` api.
+
+
+### Commonalities
+```python
+my_dtype = np.float32 # or np.uint8 or np.int8 ONLY
+my_set_of_vectors: np.typing.NDArray[my_dtype] = ... # your vectors come from somewhere - you need to bring these!
+index_to_identifiers_map: np.typing.NDArray[str] = ... # your vectors likely have some kind of external identifier -
+# you need to keep track of the external identifier -> index relationship somehow
+identifiers_to_index_map: dict[str, np.uint32|np.uint.64] = ... # your map of your external id to the `diskannpy` internal id
+# diskannpy `query` responses will contain the _internal id only_, and if you don't have these maps you won't be able to
+# know what this relates to
+```
+
+### Build Disk Index
+A disk index is a memory mapped, [vamana](https://proceedings.neurips.cc/paper_files/paper/2019/file/09853c7fb1d3f8ee67a61b6bf4a7f8e6-Paper.pdf)
+index that heavily leans into the hardware speeds of modern NVMe based solid state storage.
+
+This means you can build performant ANN indices that overflow plausibly available system memory!
+
+```python
+import numpy as np
+import diskannpy as dap
+
+vecs = my_set_of_vectors / np.linalg.norm(my_set_of_vectors, axis=1) # useful if your intention is to rank by a directionless
+# cosine angle distance
+
+dap.build_disk_index(
+ data=vecs,
+ distance_metric="l2", # can also be cosine, especially if you don't normalize your vectors like above
+ index_directory="/tmp/my_index",
+ complexity=128, # the larger this is, the more candidate points we consider when ranking
+ graph_degree=64, # the beauty of a vamana index is it's ability to shard and be able to transfer long distances across the grpah without navigating the whole thing. the larger this value is, the higher quality your results, but the longer it will take to build
+ search_memory_maximum=16.0, # a floating point number to represent how much memory in GB we want to optimize for @ query time
+ build_memory_maximum=100.0, # a floating point number to represent how much memory in GB we are allocating for the index building process
+ num_threads=0, # 0 means use all available threads - but if you are in a shared environment you may need to restrict how greedy you are
+ vector_dtype=my_dtype, # we specified this in the Commonalities section above
+ index_prefix="ann", # ann is the default anyway. all files generated will have the prefix `ann_`, in the form of `f"{index_prefix}_"`
+ pq_disk_bytes=0 # using product quantization of your vectors can still achieve excellent recall characteristics at a fraction of the latency, but we'll do it without PQ for now
+)
+```
+
+### Search Disk Index
+
+Now we want to search our disk index - using a completely different set of vectors that aren't necessarily guaranteed to
+be in our index. We will call this set of vectors `q`, and it is *critical* that they are the same dtype and
+dimensionality as the disk index we have just built.
+
+**Note**: If you manually normalized your indexed vectors prior to building the index, you will *also* need to normalize
+them prior to query!
+
+#### Common index query setup
+
+```python
+index = dap.StaticDiskIndex(
+ index_directory="/tmp/my_index",
+ num_threads=0,
+ num_nodes_to_cache=1_000_000,
+ index_prefix="ann"
+)
+```
+
+#### Individual Vectors
+```python
+some_index: np.uint32 = ... # the index in our `q` array of points that we will be using to query on an individual basis
+my_query_vector: np.typing.NDArray[my_dtype] = q[some_index] # make sure this is a 1-d array of the same dimensionality as your index!
+# normalize if required by my_query_vector /= np.linalg.norm(my_query_vector)
+internal_indices, distances = index.search(
+ query=my_query_vector,
+ k_neighbors=25,
+ complexity=50, # must be as big or bigger than `k_neighbors`
+)
+```
+
+#### Mapping to our External Ids
+The internal IDs that diskann returns via query aren't necessarily directly useful to you, and the onus is on you
+to figure out what they actually link to via your `index_to_identifiers_map` map.
+```python
+actual_identifiers = index_to_identifiers_map[internal_indices] # using np fancy indexing (advanced indexing?) to map them all to ids you actually understand
+```
+
+#### Batch Vectors
+```python
+import multiprocessing
+
+internal_indices, distances = index.batch_search(
+ queries=q,
+ k_neighbors=25,
+ complexity=50,
+ num_threads=multiprocessing.cpu_count(), # there's a current bug where this is not handling the value 0 properly
+ beam_width=8 # beamwidth is the parameter that indicates our parallelism of individual searches, whereas num_threads
+ # indicates the number of threads *per* query item in the batch
+)
+# note that in batch_query form, our internal_indices and distances are 2d arrays
+```
+
+#### Mapping to our External Ids
+Unlike the previous entry, I have yet to get the fancy awesome advanced indexing to work in one shot, we will have
+to do this the not-numpy-paragon way.
+
+```python
+actual_neighbors = np.full(shape=internal_indices.shape, dtype=str, fill_value="")
+for row in range(internal_indices.shape[0]):
+ actual_neighbors[row] = index_to_identifiers_map[internal_indices[row]]
+```
+
+This is only scratching the surface of what `diskannpy` can offer. Please read the API documentation @ [https://microsoft.github.io/](https://microsoft.github.io/DiskANN/docs/python/latest/diskannpy.html)
+for more details.
diff --git a/packages/leann-backend-diskann/third_party/DiskANN/workflows/rest_api.md b/packages/leann-backend-diskann/third_party/DiskANN/workflows/rest_api.md
new file mode 100644
index 0000000..b735fbe
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/DiskANN/workflows/rest_api.md
@@ -0,0 +1,72 @@
+<!-- Copyright (c) Microsoft Corporation. All rights reserved.
+ Licensed under the MIT license. -->
+**REST service set up for serving DiskANN indices and query interface**
+=======================================================================
+
+Install dependencies on Ubuntu and compile
+------------------------------------------
+In addition to the common dependencies in the [README](/README.md), install [Microsoft C++ REST SDK](https://github.com/Microsoft/cpprestsdk).
+
+```bash
+sudo apt install libcpprest-dev
+mkdir -p build && cd build
+cmake -DRESTAPI=True -DCMAKE_BUILD_TYPE=Release ..
+make -j
+```
+
+Starting an index hosting service
+---------------------------------
+Follow the instructions for [building an in-memory DiskANN index](/workflows/in_memory_index.md) or [building an SSD DiskANN index](/workflows/SSD_index.md). Then start a service bound at the appropriate IP:port. For querying from the local machine, you may want to use `http://127.0.0.1:port`. For serving queries originating from remote machines, you may want to use `http://0.0.0.0:port`.
+
+```bash
+# To start serving an in-memory index
+./apps/restapi/inmem_server --address <http://ip_addr:port> --data_type <float/int8/uint8> --data_file <data_file> --index_path_prefix <index_file> --num_threads <number of threads> --l_search <Value for L> --tags_file [tags_file]
+
+# To start serving an SSD-based index.
+./apps/restapi/ssd_server --address <http://ip_addr:port> --data_type <float/int8/uint8> --index_path_prefix <index_file_prefix> --num_nodes_to_cache <num_nodes_to_cache> --num_threads <num_threads> --tags_file [tags_file]
+```
+The `data_type` and the `data_file` should be the same as those used in the construction of the index. The server returns the ids and distances of the closests vector in the index to the query. The ids are implicitly defined by the order of the vector in the data file. If you wish to assign a different numbering or GUID or URL to the vectors in the index, use the optional `tags_file`. This should be a file which lists a "tag" string for each vector in the index. The file should contain one string per line. The string on the line `n` is considered the tag corresponding to the vector `n` in the index (in the implicit order defined in the `data_file`).
+
+For an SSD-based index, specify the number of nodes to cache in-memory to make queries faster. For large indices with over 100 million vectors, a typical value for `num_nodes_to_cache` could be 500000. Increase or decrease based on DRAM footprint desired.
+
+For an SSD-based index, also specify the number of threads used for search by setting the `num_threads` parameter.
+
+You can also query multiple SSD based indices using the following command by listing the prefix of each index in a file (one prefix per line) and passing it through the `index_prefix_paths` parameter to the following command.
+```bash
+multiple_ssdserver --address <ip_addr:port> --data_type <float/int8/uint8> --index_prefix_paths <index_prefix_paths> --num_nodes_to_cache <num_nodes_to_cache> --num_threads <num_threads> --tags_file [tags_file]
+```
+The service searches each of the indices and aggregate the results based on distances to find the closest neighbors across all indices.
+
+Querying the service
+--------------------
+Issue a json query with the following fields
+- "k" : The number of nearest neighbors needed
+- "query" : The query vector with a listing of co-ordinates.
+- "query_id" : An id to track the query. Use a unique number to keep track of queries, or "0" if you do not want to keep track.
+- "Ls" : query complexity. Higher Ls takes more milliseconds to process but offers higher recall. Default to 256 if you don't want to tune this.
+
+**Post a json query using python**
+
+```python
+import requests
+jsonquery = {"Ls": 256,
+ "query_id": 1234,
+ "query": [0.00407, 0.01534, 0.02498, ...],
+ "k": 10}
+
+response = requests.post('http://ip_addr:port', json=jsonquery)
+print(response.text)
+```
+
+The response might look like the following. The partition array indicates the ID of index from which the result was found in the case of a multi-index set up. For a single index set up, the response would not contain the information on partitions. The response may or may not contain `tags` based on whether the server was started with a `tags_file`.
+```json
+{"distances":[1.6947,1.6954,1.6972,1.6985,1.6991,1.7003,1.7008,1.7014,1.7021,1.7039],"indices":[8976853,8221762,30909336,13100282,30514543,11537860,7133262,34074869,50512601,17983301],"k":10,"partition":[20,7,20,20,6,6,11,6,6,20],"query_id":1234,"tags":["https://xyz1", "https://xyz2", "https://xyz3", "https://xyz4", "https://xyz5", "https://xyz6", "https://xyz7", "https://xyz8", "https://xyz9", "https://xyz10"],"time_taken_in_us":3245}
+```
+
+**Command line interface to issue multiple queries from a file**
+
+To issue `num_queries` queries from `query_file`, run the following command
+```bash
+client ip_addr:port data_type<float/int8/uint8> query_file num_queries Ls"
+```
+
diff --git a/packages/leann-backend-diskann/third_party/embedding.pb.cc b/packages/leann-backend-diskann/third_party/embedding.pb.cc
new file mode 100644
index 0000000..2b10e23
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/embedding.pb.cc
@@ -0,0 +1,613 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: embedding.proto
+
+#include "embedding.pb.h"
+
+#include <algorithm>
+
+#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/extension_set.h>
+#include <google/protobuf/wire_format_lite.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/generated_message_reflection.h>
+#include <google/protobuf/reflection_ops.h>
+#include <google/protobuf/wire_format.h>
+// @@protoc_insertion_point(includes)
+#include <google/protobuf/port_def.inc>
+namespace protoembedding {
+class NodeEmbeddingRequestDefaultTypeInternal {
+ public:
+ ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<NodeEmbeddingRequest> _instance;
+} _NodeEmbeddingRequest_default_instance_;
+class NodeEmbeddingResponseDefaultTypeInternal {
+ public:
+ ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<NodeEmbeddingResponse> _instance;
+} _NodeEmbeddingResponse_default_instance_;
+} // namespace protoembedding
+static void InitDefaultsscc_info_NodeEmbeddingRequest_embedding_2eproto() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ {
+ void* ptr = &::protoembedding::_NodeEmbeddingRequest_default_instance_;
+ new (ptr) ::protoembedding::NodeEmbeddingRequest();
+ ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::protoembedding::NodeEmbeddingRequest::InitAsDefaultInstance();
+}
+
+::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_NodeEmbeddingRequest_embedding_2eproto =
+ {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_NodeEmbeddingRequest_embedding_2eproto}, {}};
+
+static void InitDefaultsscc_info_NodeEmbeddingResponse_embedding_2eproto() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ {
+ void* ptr = &::protoembedding::_NodeEmbeddingResponse_default_instance_;
+ new (ptr) ::protoembedding::NodeEmbeddingResponse();
+ ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
+ }
+ ::protoembedding::NodeEmbeddingResponse::InitAsDefaultInstance();
+}
+
+::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_NodeEmbeddingResponse_embedding_2eproto =
+ {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_NodeEmbeddingResponse_embedding_2eproto}, {}};
+
+static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_embedding_2eproto[2];
+static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_embedding_2eproto = nullptr;
+static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_embedding_2eproto = nullptr;
+
+const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_embedding_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
+ ~0u, // no _has_bits_
+ PROTOBUF_FIELD_OFFSET(::protoembedding::NodeEmbeddingRequest, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ PROTOBUF_FIELD_OFFSET(::protoembedding::NodeEmbeddingRequest, node_ids_),
+ ~0u, // no _has_bits_
+ PROTOBUF_FIELD_OFFSET(::protoembedding::NodeEmbeddingResponse, _internal_metadata_),
+ ~0u, // no _extensions_
+ ~0u, // no _oneof_case_
+ ~0u, // no _weak_field_map_
+ PROTOBUF_FIELD_OFFSET(::protoembedding::NodeEmbeddingResponse, embeddings_data_),
+ PROTOBUF_FIELD_OFFSET(::protoembedding::NodeEmbeddingResponse, dimensions_),
+ PROTOBUF_FIELD_OFFSET(::protoembedding::NodeEmbeddingResponse, missing_ids_),
+};
+static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
+ { 0, -1, sizeof(::protoembedding::NodeEmbeddingRequest)},
+ { 6, -1, sizeof(::protoembedding::NodeEmbeddingResponse)},
+};
+
+static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
+ reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::protoembedding::_NodeEmbeddingRequest_default_instance_),
+ reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::protoembedding::_NodeEmbeddingResponse_default_instance_),
+};
+
+const char descriptor_table_protodef_embedding_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
+ "\n\017embedding.proto\022\016protoembedding\"(\n\024Nod"
+ "eEmbeddingRequest\022\020\n\010node_ids\030\001 \003(\r\"Y\n\025N"
+ "odeEmbeddingResponse\022\027\n\017embeddings_data\030"
+ "\001 \001(\014\022\022\n\ndimensions\030\002 \003(\005\022\023\n\013missing_ids"
+ "\030\003 \003(\rb\006proto3"
+ ;
+static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_embedding_2eproto_deps[1] = {
+};
+static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_embedding_2eproto_sccs[2] = {
+ &scc_info_NodeEmbeddingRequest_embedding_2eproto.base,
+ &scc_info_NodeEmbeddingResponse_embedding_2eproto.base,
+};
+static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_embedding_2eproto_once;
+const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_embedding_2eproto = {
+ false, false, descriptor_table_protodef_embedding_2eproto, "embedding.proto", 174,
+ &descriptor_table_embedding_2eproto_once, descriptor_table_embedding_2eproto_sccs, descriptor_table_embedding_2eproto_deps, 2, 0,
+ schemas, file_default_instances, TableStruct_embedding_2eproto::offsets,
+ file_level_metadata_embedding_2eproto, 2, file_level_enum_descriptors_embedding_2eproto, file_level_service_descriptors_embedding_2eproto,
+};
+
+// Force running AddDescriptors() at dynamic initialization time.
+static bool dynamic_init_dummy_embedding_2eproto = (static_cast<void>(::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_embedding_2eproto)), true);
+namespace protoembedding {
+
+// ===================================================================
+
+void NodeEmbeddingRequest::InitAsDefaultInstance() {
+}
+class NodeEmbeddingRequest::_Internal {
+ public:
+};
+
+NodeEmbeddingRequest::NodeEmbeddingRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ node_ids_(arena) {
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:protoembedding.NodeEmbeddingRequest)
+}
+NodeEmbeddingRequest::NodeEmbeddingRequest(const NodeEmbeddingRequest& from)
+ : ::PROTOBUF_NAMESPACE_ID::Message(),
+ node_ids_(from.node_ids_) {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
+ // @@protoc_insertion_point(copy_constructor:protoembedding.NodeEmbeddingRequest)
+}
+
+void NodeEmbeddingRequest::SharedCtor() {
+}
+
+NodeEmbeddingRequest::~NodeEmbeddingRequest() {
+ // @@protoc_insertion_point(destructor:protoembedding.NodeEmbeddingRequest)
+ SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
+}
+
+void NodeEmbeddingRequest::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
+}
+
+void NodeEmbeddingRequest::ArenaDtor(void* object) {
+ NodeEmbeddingRequest* _this = reinterpret_cast< NodeEmbeddingRequest* >(object);
+ (void)_this;
+}
+void NodeEmbeddingRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
+void NodeEmbeddingRequest::SetCachedSize(int size) const {
+ _cached_size_.Set(size);
+}
+const NodeEmbeddingRequest& NodeEmbeddingRequest::default_instance() {
+ ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_NodeEmbeddingRequest_embedding_2eproto.base);
+ return *internal_default_instance();
+}
+
+
+void NodeEmbeddingRequest::Clear() {
+// @@protoc_insertion_point(message_clear_start:protoembedding.NodeEmbeddingRequest)
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ node_ids_.Clear();
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
+}
+
+const char* NodeEmbeddingRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
+#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
+ while (!ctx->Done(&ptr)) {
+ ::PROTOBUF_NAMESPACE_ID::uint32 tag;
+ ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
+ CHK_(ptr);
+ switch (tag >> 3) {
+ // repeated uint32 node_ids = 1;
+ case 1:
+ if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
+ ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_node_ids(), ptr, ctx);
+ CHK_(ptr);
+ } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8) {
+ _internal_add_node_ids(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr));
+ CHK_(ptr);
+ } else goto handle_unusual;
+ continue;
+ default: {
+ handle_unusual:
+ if ((tag & 7) == 4 || tag == 0) {
+ ctx->SetLastTag(tag);
+ goto success;
+ }
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
+ CHK_(ptr != nullptr);
+ continue;
+ }
+ } // switch
+ } // while
+success:
+ return ptr;
+failure:
+ ptr = nullptr;
+ goto success;
+#undef CHK_
+}
+
+::PROTOBUF_NAMESPACE_ID::uint8* NodeEmbeddingRequest::_InternalSerialize(
+ ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
+ // @@protoc_insertion_point(serialize_to_array_start:protoembedding.NodeEmbeddingRequest)
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ // repeated uint32 node_ids = 1;
+ {
+ int byte_size = _node_ids_cached_byte_size_.load(std::memory_order_relaxed);
+ if (byte_size > 0) {
+ target = stream->WriteUInt32Packed(
+ 1, _internal_node_ids(), byte_size, target);
+ }
+ }
+
+ if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
+ target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:protoembedding.NodeEmbeddingRequest)
+ return target;
+}
+
+size_t NodeEmbeddingRequest::ByteSizeLong() const {
+// @@protoc_insertion_point(message_byte_size_start:protoembedding.NodeEmbeddingRequest)
+ size_t total_size = 0;
+
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ // repeated uint32 node_ids = 1;
+ {
+ size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
+ UInt32Size(this->node_ids_);
+ if (data_size > 0) {
+ total_size += 1 +
+ ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
+ static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size));
+ }
+ int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size);
+ _node_ids_cached_byte_size_.store(cached_size,
+ std::memory_order_relaxed);
+ total_size += data_size;
+ }
+
+ if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
+ return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
+ _internal_metadata_, total_size, &_cached_size_);
+ }
+ int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
+ SetCachedSize(cached_size);
+ return total_size;
+}
+
+void NodeEmbeddingRequest::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
+// @@protoc_insertion_point(generalized_merge_from_start:protoembedding.NodeEmbeddingRequest)
+ GOOGLE_DCHECK_NE(&from, this);
+ const NodeEmbeddingRequest* source =
+ ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<NodeEmbeddingRequest>(
+ &from);
+ if (source == nullptr) {
+ // @@protoc_insertion_point(generalized_merge_from_cast_fail:protoembedding.NodeEmbeddingRequest)
+ ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
+ } else {
+ // @@protoc_insertion_point(generalized_merge_from_cast_success:protoembedding.NodeEmbeddingRequest)
+ MergeFrom(*source);
+ }
+}
+
+void NodeEmbeddingRequest::MergeFrom(const NodeEmbeddingRequest& from) {
+// @@protoc_insertion_point(class_specific_merge_from_start:protoembedding.NodeEmbeddingRequest)
+ GOOGLE_DCHECK_NE(&from, this);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ node_ids_.MergeFrom(from.node_ids_);
+}
+
+void NodeEmbeddingRequest::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
+// @@protoc_insertion_point(generalized_copy_from_start:protoembedding.NodeEmbeddingRequest)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void NodeEmbeddingRequest::CopyFrom(const NodeEmbeddingRequest& from) {
+// @@protoc_insertion_point(class_specific_copy_from_start:protoembedding.NodeEmbeddingRequest)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool NodeEmbeddingRequest::IsInitialized() const {
+ return true;
+}
+
+void NodeEmbeddingRequest::InternalSwap(NodeEmbeddingRequest* other) {
+ using std::swap;
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ node_ids_.InternalSwap(&other->node_ids_);
+}
+
+::PROTOBUF_NAMESPACE_ID::Metadata NodeEmbeddingRequest::GetMetadata() const {
+ return GetMetadataStatic();
+}
+
+
+// ===================================================================
+
+void NodeEmbeddingResponse::InitAsDefaultInstance() {
+}
+class NodeEmbeddingResponse::_Internal {
+ public:
+};
+
+NodeEmbeddingResponse::NodeEmbeddingResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena)
+ : ::PROTOBUF_NAMESPACE_ID::Message(arena),
+ dimensions_(arena),
+ missing_ids_(arena) {
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:protoembedding.NodeEmbeddingResponse)
+}
+NodeEmbeddingResponse::NodeEmbeddingResponse(const NodeEmbeddingResponse& from)
+ : ::PROTOBUF_NAMESPACE_ID::Message(),
+ dimensions_(from.dimensions_),
+ missing_ids_(from.missing_ids_) {
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
+ embeddings_data_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+ if (!from._internal_embeddings_data().empty()) {
+ embeddings_data_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from._internal_embeddings_data(),
+ GetArena());
+ }
+ // @@protoc_insertion_point(copy_constructor:protoembedding.NodeEmbeddingResponse)
+}
+
+void NodeEmbeddingResponse::SharedCtor() {
+ ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_NodeEmbeddingResponse_embedding_2eproto.base);
+ embeddings_data_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+}
+
+NodeEmbeddingResponse::~NodeEmbeddingResponse() {
+ // @@protoc_insertion_point(destructor:protoembedding.NodeEmbeddingResponse)
+ SharedDtor();
+ _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
+}
+
+void NodeEmbeddingResponse::SharedDtor() {
+ GOOGLE_DCHECK(GetArena() == nullptr);
+ embeddings_data_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
+}
+
+void NodeEmbeddingResponse::ArenaDtor(void* object) {
+ NodeEmbeddingResponse* _this = reinterpret_cast< NodeEmbeddingResponse* >(object);
+ (void)_this;
+}
+void NodeEmbeddingResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) {
+}
+void NodeEmbeddingResponse::SetCachedSize(int size) const {
+ _cached_size_.Set(size);
+}
+const NodeEmbeddingResponse& NodeEmbeddingResponse::default_instance() {
+ ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_NodeEmbeddingResponse_embedding_2eproto.base);
+ return *internal_default_instance();
+}
+
+
+void NodeEmbeddingResponse::Clear() {
+// @@protoc_insertion_point(message_clear_start:protoembedding.NodeEmbeddingResponse)
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ dimensions_.Clear();
+ missing_ids_.Clear();
+ embeddings_data_.ClearToEmpty(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+ _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
+}
+
+const char* NodeEmbeddingResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
+#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
+ ::PROTOBUF_NAMESPACE_ID::Arena* arena = GetArena(); (void)arena;
+ while (!ctx->Done(&ptr)) {
+ ::PROTOBUF_NAMESPACE_ID::uint32 tag;
+ ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
+ CHK_(ptr);
+ switch (tag >> 3) {
+ // bytes embeddings_data = 1;
+ case 1:
+ if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) {
+ auto str = _internal_mutable_embeddings_data();
+ ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx);
+ CHK_(ptr);
+ } else goto handle_unusual;
+ continue;
+ // repeated int32 dimensions = 2;
+ case 2:
+ if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) {
+ ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedInt32Parser(_internal_mutable_dimensions(), ptr, ctx);
+ CHK_(ptr);
+ } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16) {
+ _internal_add_dimensions(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr));
+ CHK_(ptr);
+ } else goto handle_unusual;
+ continue;
+ // repeated uint32 missing_ids = 3;
+ case 3:
+ if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
+ ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedUInt32Parser(_internal_mutable_missing_ids(), ptr, ctx);
+ CHK_(ptr);
+ } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) {
+ _internal_add_missing_ids(::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr));
+ CHK_(ptr);
+ } else goto handle_unusual;
+ continue;
+ default: {
+ handle_unusual:
+ if ((tag & 7) == 4 || tag == 0) {
+ ctx->SetLastTag(tag);
+ goto success;
+ }
+ ptr = UnknownFieldParse(tag,
+ _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(),
+ ptr, ctx);
+ CHK_(ptr != nullptr);
+ continue;
+ }
+ } // switch
+ } // while
+success:
+ return ptr;
+failure:
+ ptr = nullptr;
+ goto success;
+#undef CHK_
+}
+
+::PROTOBUF_NAMESPACE_ID::uint8* NodeEmbeddingResponse::_InternalSerialize(
+ ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const {
+ // @@protoc_insertion_point(serialize_to_array_start:protoembedding.NodeEmbeddingResponse)
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ // bytes embeddings_data = 1;
+ if (this->embeddings_data().size() > 0) {
+ target = stream->WriteBytesMaybeAliased(
+ 1, this->_internal_embeddings_data(), target);
+ }
+
+ // repeated int32 dimensions = 2;
+ {
+ int byte_size = _dimensions_cached_byte_size_.load(std::memory_order_relaxed);
+ if (byte_size > 0) {
+ target = stream->WriteInt32Packed(
+ 2, _internal_dimensions(), byte_size, target);
+ }
+ }
+
+ // repeated uint32 missing_ids = 3;
+ {
+ int byte_size = _missing_ids_cached_byte_size_.load(std::memory_order_relaxed);
+ if (byte_size > 0) {
+ target = stream->WriteUInt32Packed(
+ 3, _internal_missing_ids(), byte_size, target);
+ }
+ }
+
+ if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
+ target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray(
+ _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:protoembedding.NodeEmbeddingResponse)
+ return target;
+}
+
+size_t NodeEmbeddingResponse::ByteSizeLong() const {
+// @@protoc_insertion_point(message_byte_size_start:protoembedding.NodeEmbeddingResponse)
+ size_t total_size = 0;
+
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ // Prevent compiler warnings about cached_has_bits being unused
+ (void) cached_has_bits;
+
+ // repeated int32 dimensions = 2;
+ {
+ size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
+ Int32Size(this->dimensions_);
+ if (data_size > 0) {
+ total_size += 1 +
+ ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
+ static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size));
+ }
+ int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size);
+ _dimensions_cached_byte_size_.store(cached_size,
+ std::memory_order_relaxed);
+ total_size += data_size;
+ }
+
+ // repeated uint32 missing_ids = 3;
+ {
+ size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::
+ UInt32Size(this->missing_ids_);
+ if (data_size > 0) {
+ total_size += 1 +
+ ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size(
+ static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size));
+ }
+ int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size);
+ _missing_ids_cached_byte_size_.store(cached_size,
+ std::memory_order_relaxed);
+ total_size += data_size;
+ }
+
+ // bytes embeddings_data = 1;
+ if (this->embeddings_data().size() > 0) {
+ total_size += 1 +
+ ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize(
+ this->_internal_embeddings_data());
+ }
+
+ if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) {
+ return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize(
+ _internal_metadata_, total_size, &_cached_size_);
+ }
+ int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
+ SetCachedSize(cached_size);
+ return total_size;
+}
+
+void NodeEmbeddingResponse::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
+// @@protoc_insertion_point(generalized_merge_from_start:protoembedding.NodeEmbeddingResponse)
+ GOOGLE_DCHECK_NE(&from, this);
+ const NodeEmbeddingResponse* source =
+ ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<NodeEmbeddingResponse>(
+ &from);
+ if (source == nullptr) {
+ // @@protoc_insertion_point(generalized_merge_from_cast_fail:protoembedding.NodeEmbeddingResponse)
+ ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
+ } else {
+ // @@protoc_insertion_point(generalized_merge_from_cast_success:protoembedding.NodeEmbeddingResponse)
+ MergeFrom(*source);
+ }
+}
+
+void NodeEmbeddingResponse::MergeFrom(const NodeEmbeddingResponse& from) {
+// @@protoc_insertion_point(class_specific_merge_from_start:protoembedding.NodeEmbeddingResponse)
+ GOOGLE_DCHECK_NE(&from, this);
+ _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_);
+ ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
+ (void) cached_has_bits;
+
+ dimensions_.MergeFrom(from.dimensions_);
+ missing_ids_.MergeFrom(from.missing_ids_);
+ if (from.embeddings_data().size() > 0) {
+ _internal_set_embeddings_data(from._internal_embeddings_data());
+ }
+}
+
+void NodeEmbeddingResponse::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
+// @@protoc_insertion_point(generalized_copy_from_start:protoembedding.NodeEmbeddingResponse)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void NodeEmbeddingResponse::CopyFrom(const NodeEmbeddingResponse& from) {
+// @@protoc_insertion_point(class_specific_copy_from_start:protoembedding.NodeEmbeddingResponse)
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool NodeEmbeddingResponse::IsInitialized() const {
+ return true;
+}
+
+void NodeEmbeddingResponse::InternalSwap(NodeEmbeddingResponse* other) {
+ using std::swap;
+ _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_);
+ dimensions_.InternalSwap(&other->dimensions_);
+ missing_ids_.InternalSwap(&other->missing_ids_);
+ embeddings_data_.Swap(&other->embeddings_data_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
+}
+
+::PROTOBUF_NAMESPACE_ID::Metadata NodeEmbeddingResponse::GetMetadata() const {
+ return GetMetadataStatic();
+}
+
+
+// @@protoc_insertion_point(namespace_scope)
+} // namespace protoembedding
+PROTOBUF_NAMESPACE_OPEN
+template<> PROTOBUF_NOINLINE ::protoembedding::NodeEmbeddingRequest* Arena::CreateMaybeMessage< ::protoembedding::NodeEmbeddingRequest >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::protoembedding::NodeEmbeddingRequest >(arena);
+}
+template<> PROTOBUF_NOINLINE ::protoembedding::NodeEmbeddingResponse* Arena::CreateMaybeMessage< ::protoembedding::NodeEmbeddingResponse >(Arena* arena) {
+ return Arena::CreateMessageInternal< ::protoembedding::NodeEmbeddingResponse >(arena);
+}
+PROTOBUF_NAMESPACE_CLOSE
+
+// @@protoc_insertion_point(global_scope)
+#include <google/protobuf/port_undef.inc>
diff --git a/packages/leann-backend-diskann/third_party/embedding.proto b/packages/leann-backend-diskann/third_party/embedding.proto
new file mode 100644
index 0000000..98e7713
--- /dev/null
+++ b/packages/leann-backend-diskann/third_party/embedding.proto
@@ -0,0 +1,13 @@
+syntax = "proto3";
+
+package protoembedding;
+
+message NodeEmbeddingRequest {
+ repeated uint32 node_ids = 1;
+}
+
+message NodeEmbeddingResponse {
+ bytes embeddings_data = 1; // All embedded binary datas
+ repeated int32 dimensions = 2; // Shape [batch_size, embedding_dim]
+ repeated uint32 missing_ids = 3; // Missing node ids
+}
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/CMakeLists.txt b/packages/leann-backend-hnsw/CMakeLists.txt
new file mode 100644
index 0000000..6865da3
--- /dev/null
+++ b/packages/leann-backend-hnsw/CMakeLists.txt
@@ -0,0 +1,12 @@
+# 最终简化版
+cmake_minimum_required(VERSION 3.24)
+project(leann_backend_hnsw_wrapper)
+
+set(FAISS_ENABLE_PYTHON ON CACHE BOOL "" FORCE)
+set(FAISS_ENABLE_GPU OFF CACHE BOOL "" FORCE)
+set(FAISS_ENABLE_EXTRAS OFF CACHE BOOL "" FORCE)
+set(BUILD_TESTING OFF CACHE BOOL "" FORCE)
+set(FAISS_ENABLE_C_API OFF CACHE BOOL "" FORCE)
+set(FAISS_OPT_LEVEL "generic" CACHE STRING "" FORCE)
+
+add_subdirectory(third_party/faiss)
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/leann_backend_hnsw/__init__.py b/packages/leann-backend-hnsw/leann_backend_hnsw/__init__.py
new file mode 100644
index 0000000..53fd67a
--- /dev/null
+++ b/packages/leann-backend-hnsw/leann_backend_hnsw/__init__.py
@@ -0,0 +1 @@
+from . import hnsw_backend
diff --git a/packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_backend.py b/packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_backend.py
new file mode 100644
index 0000000..53e7e91
--- /dev/null
+++ b/packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_backend.py
@@ -0,0 +1,313 @@
+import numpy as np
+import os
+import json
+import struct
+from pathlib import Path
+from typing import Dict
+import contextlib
+import threading
+import time
+import atexit
+import socket
+import subprocess
+import sys
+
+# 文件: packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_backend.py
+
+# ... (其他 import 保持不变) ...
+
+from leann.registry import register_backend
+from leann.interface import (
+ LeannBackendFactoryInterface,
+ LeannBackendBuilderInterface,
+ LeannBackendSearcherInterface
+)
+
+def get_metric_map():
+ from . import faiss
+ return {
+ "mips": faiss.METRIC_INNER_PRODUCT,
+ "l2": faiss.METRIC_L2,
+ "cosine": faiss.METRIC_INNER_PRODUCT, # Will need normalization
+ }
+
+def _check_port(port: int) -> bool:
+ """Check if a port is in use"""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ return s.connect_ex(('localhost', port)) == 0
+
+class HNSWEmbeddingServerManager:
+ """
+ HNSW-specific embedding server manager that handles the lifecycle of the embedding server process.
+ Mirrors the DiskANN EmbeddingServerManager architecture.
+ """
+ def __init__(self):
+ self.server_process = None
+ self.server_port = None
+ atexit.register(self.stop_server)
+
+ def start_server(self, port=5556, model_name="sentence-transformers/all-mpnet-base-v2", passages_file=None):
+ """
+ Start the HNSW embedding server process.
+
+ Args:
+ port: ZMQ port for the server
+ model_name: Name of the embedding model to use
+ passages_file: Optional path to passages JSON file
+ """
+ if self.server_process and self.server_process.poll() is None:
+ print(f"INFO: Reusing existing HNSW server process for this session (PID {self.server_process.pid})")
+ return True
+
+ # Check if port is already in use
+ if _check_port(port):
+ print(f"WARNING: Port {port} is already in use. Assuming an external HNSW server is running and connecting to it.")
+ return True
+
+ print(f"INFO: Starting session-level HNSW embedding server as a background process...")
+
+ try:
+ command = [
+ sys.executable,
+ "-m", "packages.leann-backend-hnsw.src.leann_backend_hnsw.hnsw_embedding_server",
+ "--zmq-port", str(port),
+ "--model-name", model_name
+ ]
+
+ # Add passages file if provided
+ if passages_file:
+ command.extend(["--passages-file", str(passages_file)])
+
+ project_root = Path(__file__).parent.parent.parent.parent
+ print(f"INFO: Running HNSW command from project root: {project_root}")
+
+ self.server_process = subprocess.Popen(
+ command,
+ cwd=project_root,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding='utf-8'
+ )
+ self.server_port = port
+ print(f"INFO: HNSW server process started with PID: {self.server_process.pid}")
+
+ max_wait, wait_interval = 30, 0.5
+ for _ in range(int(max_wait / wait_interval)):
+ if _check_port(port):
+ print(f"✅ HNSW embedding server is up and ready for this session.")
+ log_thread = threading.Thread(target=self._log_monitor, daemon=True)
+ log_thread.start()
+ return True
+ if self.server_process.poll() is not None:
+ print("❌ ERROR: HNSW server process terminated unexpectedly during startup.")
+ self._log_monitor()
+ return False
+ time.sleep(wait_interval)
+
+ print(f"❌ ERROR: HNSW server process failed to start listening within {max_wait} seconds.")
+ self.stop_server()
+ return False
+
+ except Exception as e:
+ print(f"❌ ERROR: Failed to start HNSW embedding server process: {e}")
+ return False
+
+ def _log_monitor(self):
+ """Monitor server logs"""
+ if not self.server_process:
+ return
+ try:
+ if self.server_process.stdout:
+ for line in iter(self.server_process.stdout.readline, ''):
+ print(f"[HNSWEmbeddingServer LOG]: {line.strip()}")
+ self.server_process.stdout.close()
+ if self.server_process.stderr:
+ for line in iter(self.server_process.stderr.readline, ''):
+ print(f"[HNSWEmbeddingServer ERROR]: {line.strip()}")
+ self.server_process.stderr.close()
+ except Exception as e:
+ print(f"HNSW Log monitor error: {e}")
+
+ def stop_server(self):
+ """Stop the HNSW embedding server process"""
+ if self.server_process and self.server_process.poll() is None:
+ print(f"INFO: Terminating HNSW session server process (PID: {self.server_process.pid})...")
+ self.server_process.terminate()
+ try:
+ self.server_process.wait(timeout=5)
+ print("INFO: HNSW server process terminated.")
+ except subprocess.TimeoutExpired:
+ print("WARNING: HNSW server process did not terminate gracefully, killing it.")
+ self.server_process.kill()
+ self.server_process = None
+
+@register_backend("hnsw")
+class HNSWBackend(LeannBackendFactoryInterface):
+ @staticmethod
+ def builder(**kwargs) -> LeannBackendBuilderInterface:
+ return HNSWBuilder(**kwargs)
+
+ @staticmethod
+ def searcher(index_path: str, **kwargs) -> LeannBackendSearcherInterface:
+ path = Path(index_path)
+ meta_path = path.parent / f"{path.stem}.hnsw.meta.json"
+ if not meta_path.exists():
+ raise FileNotFoundError(f"Leann metadata file not found at {meta_path}. Cannot infer vector dimension for searcher.")
+
+ with open(meta_path, 'r') as f:
+ meta = json.load(f)
+
+ try:
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(meta.get("embedding_model"))
+ dimensions = model.get_sentence_embedding_dimension()
+ kwargs['dimensions'] = dimensions
+ except ImportError:
+ raise ImportError("sentence-transformers is required to infer embedding dimensions. Please install it.")
+ except Exception as e:
+ raise RuntimeError(f"Could not load SentenceTransformer model to get dimension: {e}")
+
+ return HNSWSearcher(index_path, **kwargs)
+
+class HNSWBuilder(LeannBackendBuilderInterface):
+ def __init__(self, **kwargs):
+ self.build_params = kwargs
+
+ def build(self, data: np.ndarray, index_path: str, **kwargs):
+ """Build HNSW index using FAISS"""
+ from . import faiss
+
+ path = Path(index_path)
+ index_dir = path.parent
+ index_prefix = path.stem
+
+ index_dir.mkdir(parents=True, exist_ok=True)
+
+ if data.dtype != np.float32:
+ data = data.astype(np.float32)
+ if not data.flags['C_CONTIGUOUS']:
+ data = np.ascontiguousarray(data)
+
+ build_kwargs = {**self.build_params, **kwargs}
+ metric_str = build_kwargs.get("distance_metric", "mips").lower()
+ metric_enum = get_metric_map().get(metric_str)
+ if metric_enum is None:
+ raise ValueError(f"Unsupported distance_metric '{metric_str}'.")
+
+ # HNSW parameters
+ M = build_kwargs.get("M", 32) # Max connections per layer
+ efConstruction = build_kwargs.get("efConstruction", 200) # Size of the dynamic candidate list for construction
+ dim = data.shape[1]
+
+ print(f"INFO: Building HNSW index for {data.shape[0]} vectors with metric {metric_enum}...")
+
+ try:
+ # Create HNSW index
+ if metric_enum == faiss.METRIC_INNER_PRODUCT:
+ index = faiss.IndexHNSWFlat(dim, M, metric_enum)
+ else: # L2
+ index = faiss.IndexHNSWFlat(dim, M, metric_enum)
+
+ # Set construction parameters
+ index.hnsw.efConstruction = efConstruction
+
+ # Normalize vectors if using cosine similarity
+ if metric_str == "cosine":
+ faiss.normalize_L2(data)
+
+ # Add vectors to index
+ index.add(data.shape[0], faiss.swig_ptr(data))
+
+ # Save index
+ index_file = index_dir / f"{index_prefix}.index"
+ faiss.write_index(index, str(index_file))
+
+ print(f"✅ HNSW index built successfully at '{index_file}'")
+
+ except Exception as e:
+ print(f"💥 ERROR: HNSW index build failed. Exception: {e}")
+ raise
+
+class HNSWSearcher(LeannBackendSearcherInterface):
+ def __init__(self, index_path: str, **kwargs):
+ from . import faiss
+ path = Path(index_path)
+ index_dir = path.parent
+ index_prefix = path.stem
+
+ metric_str = kwargs.get("distance_metric", "mips").lower()
+ metric_enum = get_metric_map().get(metric_str)
+ if metric_enum is None:
+ raise ValueError(f"Unsupported distance_metric '{metric_str}'.")
+
+ dimensions = kwargs.get("dimensions")
+ if not dimensions:
+ raise ValueError("Vector dimension not provided to HNSWSearcher.")
+
+ try:
+ # Load FAISS HNSW index
+ index_file = index_dir / f"{index_prefix}.index"
+ if not index_file.exists():
+ raise FileNotFoundError(f"HNSW index file not found at {index_file}")
+
+ self._index = faiss.read_index(str(index_file))
+ self.metric_str = metric_str
+ self.embedding_server_manager = HNSWEmbeddingServerManager()
+ print("✅ HNSW index loaded successfully.")
+
+ except Exception as e:
+ print(f"💥 ERROR: Failed to load HNSW index. Exception: {e}")
+ raise
+
+ def search(self, query: np.ndarray, top_k: int, **kwargs) -> Dict[str, any]:
+ """Search using HNSW index with optional recompute functionality"""
+ ef = kwargs.get("ef", 200) # Size of the dynamic candidate list for search
+
+ # Recompute parameters
+ recompute_neighbor_embeddings = kwargs.get("recompute_neighbor_embeddings", False)
+ zmq_port = kwargs.get("zmq_port", 5556)
+ embedding_model = kwargs.get("embedding_model", "sentence-transformers/all-mpnet-base-v2")
+ passages_file = kwargs.get("passages_file", None)
+
+ if recompute_neighbor_embeddings:
+ print(f"INFO: HNSW ZMQ mode enabled - ensuring embedding server is running")
+
+ if not self.embedding_server_manager.start_server(zmq_port, embedding_model, passages_file):
+ print(f"WARNING: Failed to start HNSW embedding server, falling back to standard search")
+ kwargs['recompute_neighbor_embeddings'] = False
+
+ if query.dtype != np.float32:
+ query = query.astype(np.float32)
+ if query.ndim == 1:
+ query = np.expand_dims(query, axis=0)
+
+ # Normalize query if using cosine similarity
+ if self.metric_str == "cosine":
+ faiss.normalize_L2(query)
+
+ try:
+ # Set search parameter
+ self._index.hnsw.efSearch = ef
+
+ if recompute_neighbor_embeddings:
+ # Use custom search with recompute
+ # This would require implementing custom HNSW search logic
+ # For now, we'll fall back to standard search
+ print("WARNING: Recompute functionality for HNSW not yet implemented, using standard search")
+ distances, labels = self._index.search(query, top_k)
+ else:
+ # Standard FAISS search
+ distances, labels = self._index.search(query, top_k)
+
+ return {"labels": labels, "distances": distances}
+
+ except Exception as e:
+ print(f"💥 ERROR: HNSW search failed. Exception: {e}")
+ batch_size = query.shape[0]
+ return {"labels": np.full((batch_size, top_k), -1, dtype=np.int64),
+ "distances": np.full((batch_size, top_k), float('inf'), dtype=np.float32)}
+
+ def __del__(self):
+ if hasattr(self, 'embedding_server_manager'):
+ self.embedding_server_manager.stop_server()
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_embedding_server.py b/packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_embedding_server.py
new file mode 100644
index 0000000..4c1aee0
--- /dev/null
+++ b/packages/leann-backend-hnsw/leann_backend_hnsw/hnsw_embedding_server.py
@@ -0,0 +1,583 @@
+#!/usr/bin/env python3
+"""
+HNSW-specific embedding server with removed config.py dependencies
+Based on DiskANN embedding server architecture
+"""
+
+import pickle
+import argparse
+import threading
+import time
+from transformers import AutoTokenizer, AutoModel
+import os
+from contextlib import contextmanager
+import zmq
+import numpy as np
+import msgpack
+import json
+from pathlib import Path
+from typing import Dict, Any, Optional, Union
+
+RED = "\033[91m"
+RESET = "\033[0m"
+
+def is_similarity_metric():
+ """
+ Check if the metric type is similarity-based (like inner product).
+ 0 = L2 (distance metric), 1 = Inner Product (similarity metric)
+ """
+ return True # 1 is METRIC_INNER_PRODUCT in FAISS
+
+# Function for E5-style average pooling
+import torch
+from torch import Tensor
+import torch.nn.functional as F
+
+def e5_average_pool(last_hidden_states: Tensor, attention_mask: Tensor) -> Tensor:
+ last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
+ return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
+
+class SimplePassageLoader:
+ """
+ Simple passage loader that replaces config.py dependencies
+ """
+ def __init__(self, passages_data: Optional[Dict[str, Any]] = None):
+ self.passages_data = passages_data or {}
+
+ def __getitem__(self, passage_id: Union[str, int]) -> Dict[str, str]:
+ """Get passage by ID"""
+ str_id = str(passage_id)
+ if str_id in self.passages_data:
+ return {"text": self.passages_data[str_id]}
+ else:
+ # Return empty text for missing passages
+ return {"text": ""}
+
+ def __len__(self) -> int:
+ return len(self.passages_data)
+
+def load_passages_from_file(passages_file: str) -> SimplePassageLoader:
+ """
+ Load passages from a JSON file
+ Expected format: {"passage_id": "passage_text", ...}
+ """
+ if not os.path.exists(passages_file):
+ print(f"Warning: Passages file {passages_file} not found. Using empty loader.")
+ return SimplePassageLoader()
+
+ try:
+ with open(passages_file, 'r', encoding='utf-8') as f:
+ passages_data = json.load(f)
+ print(f"Loaded {len(passages_data)} passages from {passages_file}")
+ return SimplePassageLoader(passages_data)
+ except Exception as e:
+ print(f"Error loading passages from {passages_file}: {e}")
+ return SimplePassageLoader()
+
+def create_hnsw_embedding_server(
+ passages_file: Optional[str] = None,
+ passages_data: Optional[Dict[str, str]] = None,
+ embeddings_file: Optional[str] = None,
+ use_fp16: bool = True,
+ use_int8: bool = False,
+ use_cuda_graphs: bool = False,
+ zmq_port: int = 5555,
+ max_batch_size: int = 128,
+ model_name: str = "sentence-transformers/all-mpnet-base-v2",
+ custom_max_length_param: Optional[int] = None,
+):
+ """
+ Create and start a ZMQ-based embedding server for HNSW backend.
+
+ Args:
+ passages_file: Path to JSON file containing passage ID -> text mapping
+ passages_data: Direct passage data dict (alternative to passages_file)
+ embeddings_file: Path to pre-computed embeddings file (optional)
+ use_fp16: Whether to use FP16 precision
+ use_int8: Whether to use INT8 quantization
+ use_cuda_graphs: Whether to use CUDA graphs
+ zmq_port: ZMQ port to bind to
+ max_batch_size: Maximum batch size for processing
+ model_name: Transformer model name
+ custom_max_length_param: Custom max sequence length
+ """
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
+
+ # Device setup
+ mps_available = hasattr(torch.backends, 'mps') and torch.backends.mps.is_available()
+ cuda_available = torch.cuda.is_available()
+
+ print(f"MPS available: {mps_available}")
+ print(f"CUDA available: {cuda_available}")
+
+ if cuda_available:
+ device = torch.device("cuda")
+ print("Using CUDA device")
+ elif mps_available:
+ device = torch.device("mps")
+ print("Using MPS device (Apple Silicon)")
+ else:
+ device = torch.device("cpu")
+ print("Using CPU device (no GPU acceleration available)")
+
+ # Load model to the appropriate device
+ print(f"Starting HNSW server on port {zmq_port} with model {model_name}")
+ model = AutoModel.from_pretrained(model_name).to(device).eval()
+
+ # Check port availability
+ import socket
+ def check_port(port):
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ return s.connect_ex(('localhost', port)) == 0
+
+ if check_port(zmq_port):
+ print(f"{RED}Port {zmq_port} is already in use{RESET}")
+ return
+
+ # Apply model optimizations (similar to DiskANN version)
+ if use_fp16 and (cuda_available or mps_available):
+ model = model.half()
+ model = torch.compile(model)
+ print(f"Using FP16 precision with model: {model_name}")
+ elif use_int8:
+ print("- Using TorchAO for Int8 dynamic activation and Int8 weight quantization")
+ from torchao.quantization import quantize_, Int8DynamicActivationInt8WeightConfig
+ quantize_(model, Int8DynamicActivationInt8WeightConfig())
+ model = torch.compile(model)
+ model.eval()
+ print("- Model successfully quantized and compiled")
+
+ # Load passages
+ if passages_data:
+ passages = SimplePassageLoader(passages_data)
+ print(f"Using provided passages data: {len(passages)} passages")
+ elif passages_file:
+ passages = load_passages_from_file(passages_file)
+ else:
+ passages = SimplePassageLoader()
+ print("No passages provided, using empty loader")
+
+ # Load embeddings if provided
+ _embeddings = None
+ if embeddings_file and os.path.exists(embeddings_file):
+ try:
+ with open(embeddings_file, "rb") as f:
+ _embeddings = pickle.load(f)
+ print(f"Loaded embeddings from {embeddings_file}")
+ except Exception as e:
+ print(f"Error loading embeddings: {e}")
+
+ class DeviceTimer:
+ """Device event-based timer for accurate timing."""
+ def __init__(self, name="", device=device):
+ self.name = name
+ self.device = device
+ self.start_time = 0
+ self.end_time = 0
+
+ if cuda_available:
+ self.start_event = torch.cuda.Event(enable_timing=True)
+ self.end_event = torch.cuda.Event(enable_timing=True)
+ else:
+ self.start_event = None
+ self.end_event = None
+
+ @contextmanager
+ def timing(self):
+ self.start()
+ yield
+ self.end()
+
+ def start(self):
+ if cuda_available:
+ torch.cuda.synchronize()
+ self.start_event.record()
+ else:
+ if self.device.type == "mps":
+ torch.mps.synchronize()
+ self.start_time = time.time()
+
+ def end(self):
+ if cuda_available:
+ self.end_event.record()
+ torch.cuda.synchronize()
+ else:
+ if self.device.type == "mps":
+ torch.mps.synchronize()
+ self.end_time = time.time()
+
+ def elapsed_time(self):
+ if cuda_available:
+ return self.start_event.elapsed_time(self.end_event) / 1000.0
+ else:
+ return self.end_time - self.start_time
+
+ def print_elapsed(self):
+ return # Disabled for now
+
+ def process_batch(texts_batch, ids_batch, missing_ids):
+ """Process a batch of texts and return embeddings"""
+ _is_e5_model = "e5" in model_name.lower()
+ batch_size = len(texts_batch)
+
+ # E5 model preprocessing
+ if _is_e5_model:
+ processed_texts_batch = [f"passage: {text}" for text in texts_batch]
+ else:
+ processed_texts_batch = texts_batch
+
+ # Set max length
+ if _is_e5_model:
+ current_max_length = custom_max_length_param if custom_max_length_param is not None else 512
+ else:
+ current_max_length = custom_max_length_param if custom_max_length_param is not None else 256
+
+ tokenize_timer = DeviceTimer("tokenization (batch)", device)
+ to_device_timer = DeviceTimer("transfer to device (batch)", device)
+ embed_timer = DeviceTimer("embedding (batch)", device)
+ pool_timer = DeviceTimer("pooling (batch)", device)
+ norm_timer = DeviceTimer("normalization (batch)", device)
+
+ with tokenize_timer.timing():
+ encoded_batch = tokenizer(
+ processed_texts_batch,
+ padding="max_length",
+ truncation=True,
+ max_length=current_max_length,
+ return_tensors="pt",
+ return_token_type_ids=False,
+ )
+
+ seq_length = encoded_batch["input_ids"].size(1)
+
+ with to_device_timer.timing():
+ enc = {k: v.to(device) for k, v in encoded_batch.items()}
+
+ with torch.no_grad():
+ with embed_timer.timing():
+ out = model(enc["input_ids"], enc["attention_mask"])
+
+ with pool_timer.timing():
+ if not hasattr(out, 'last_hidden_state'):
+ if isinstance(out, torch.Tensor) and len(out.shape) == 2:
+ pooled_embeddings = out
+ else:
+ print(f"{RED}ERROR: Cannot determine how to pool. Output shape: {out.shape if isinstance(out, torch.Tensor) else 'N/A'}{RESET}")
+ hidden_dim = getattr(model.config, 'hidden_size', 384 if _is_e5_model else 768)
+ pooled_embeddings = torch.zeros((batch_size, hidden_dim), device=device, dtype=enc["input_ids"].dtype if hasattr(enc["input_ids"], "dtype") else torch.float32)
+ elif _is_e5_model:
+ pooled_embeddings = e5_average_pool(out.last_hidden_state, enc['attention_mask'])
+ else:
+ hidden_states = out.last_hidden_state
+ mask_expanded = enc["attention_mask"].unsqueeze(-1).expand(hidden_states.size()).float()
+ sum_embeddings = torch.sum(hidden_states * mask_expanded, 1)
+ sum_mask = torch.clamp(mask_expanded.sum(1), min=1e-9)
+ pooled_embeddings = sum_embeddings / sum_mask
+
+ final_embeddings = pooled_embeddings
+ if _is_e5_model:
+ with norm_timer.timing():
+ final_embeddings = F.normalize(pooled_embeddings, p=2, dim=1)
+
+ if torch.isnan(final_embeddings).any() or torch.isinf(final_embeddings).any():
+ print(f"{RED}!!! In process_batch: NaN or Inf detected in final_embeddings! "
+ f"Model: {model_name}, E5: {_is_e5_model}. IDs (sample): {ids_batch[:5]}...{RESET}")
+ dim_size = final_embeddings.shape[-1]
+ error_output = torch.zeros((batch_size, dim_size), device='cpu', dtype=torch.float32).numpy()
+ print(f"{RED}Returning zero embeddings of shape ({batch_size}, {dim_size}) due to NaN/Inf.{RESET}")
+ return error_output
+
+ return final_embeddings.cpu().numpy()
+
+ def client_warmup(zmq_port):
+ """Perform client-side warmup"""
+ time.sleep(2)
+ print(f"Performing client-side warmup with model {model_name}...")
+ sample_ids = ["1", "2", "3", "4", "5"]
+
+ try:
+ context = zmq.Context()
+ socket = context.socket(zmq.REQ)
+ socket.connect(f"tcp://localhost:{zmq_port}")
+ socket.setsockopt(zmq.RCVTIMEO, 30000)
+ socket.setsockopt(zmq.SNDTIMEO, 30000)
+
+ try:
+ ids_to_send = [int(x) for x in sample_ids]
+ except ValueError:
+ ids_to_send = []
+
+ if not ids_to_send:
+ print("Skipping warmup send.")
+ return
+
+ request_payload = [ids_to_send]
+ request_bytes = msgpack.packb(request_payload)
+
+ for i in range(3):
+ print(f"Sending warmup request {i+1}/3 via ZMQ (MessagePack)...")
+ socket.send(request_bytes)
+ response_bytes = socket.recv()
+
+ response_payload = msgpack.unpackb(response_bytes)
+ dimensions = response_payload[0]
+ embeddings_count = dimensions[0] if dimensions and len(dimensions) > 0 else 0
+ print(f"Warmup request {i+1}/3 successful, received {embeddings_count} embeddings")
+ time.sleep(0.1)
+
+ print("Client-side MessagePack ZMQ warmup complete")
+ socket.close()
+ context.term()
+ except Exception as e:
+ print(f"Error during MessagePack ZMQ warmup: {e}")
+
+ def zmq_server_thread():
+ """ZMQ server thread"""
+ context = zmq.Context()
+ socket = context.socket(zmq.REP)
+ socket.bind(f"tcp://*:{zmq_port}")
+ print(f"HNSW ZMQ server listening on port {zmq_port}")
+
+ socket.setsockopt(zmq.RCVTIMEO, 300000)
+ socket.setsockopt(zmq.SNDTIMEO, 300000)
+
+ while True:
+ try:
+ message_bytes = socket.recv()
+ print(f"Received ZMQ request of size {len(message_bytes)} bytes")
+
+ e2e_start = time.time()
+ lookup_timer = DeviceTimer("text lookup", device)
+
+ try:
+ request_payload = msgpack.unpackb(message_bytes)
+
+ # Handle distance calculation requests
+ if isinstance(request_payload, list) and len(request_payload) == 2 and isinstance(request_payload[0], list) and isinstance(request_payload[1], list):
+ node_ids = request_payload[0]
+ query_vector = np.array(request_payload[1], dtype=np.float32)
+
+ print(f"Request for distance calculation: {len(node_ids)} nodes, query vector dim: {len(query_vector)}")
+
+ # Get embeddings for node IDs
+ texts = []
+ missing_ids = []
+ with lookup_timer.timing():
+ for nid in node_ids:
+ txtinfo = passages[nid]
+ if txtinfo is None or txtinfo["text"] == "":
+ print(f"Warning: Passage with ID {nid} not found")
+ missing_ids.append(nid)
+ txt = ""
+ else:
+ txt = txtinfo["text"]
+ texts.append(txt)
+ lookup_timer.print_elapsed()
+
+ # Process embeddings in chunks if needed
+ all_node_embeddings = []
+ total_size = len(texts)
+
+ if total_size > max_batch_size:
+ for i in range(0, total_size, max_batch_size):
+ end_idx = min(i + max_batch_size, total_size)
+ chunk_texts = texts[i:end_idx]
+ chunk_ids = node_ids[i:end_idx]
+
+ embeddings_chunk = process_batch(chunk_texts, chunk_ids, missing_ids)
+ all_node_embeddings.append(embeddings_chunk)
+
+ if cuda_available:
+ torch.cuda.empty_cache()
+ elif device.type == "mps":
+ torch.mps.empty_cache()
+
+ node_embeddings = np.vstack(all_node_embeddings)
+ else:
+ node_embeddings = process_batch(texts, node_ids, missing_ids)
+
+ # Calculate distances
+ query_tensor = torch.tensor(query_vector, device=device).float()
+ node_embeddings_tensor = torch.tensor(node_embeddings, device=device).float()
+
+ calc_timer = DeviceTimer("distance calculation", device)
+ with calc_timer.timing():
+ with torch.no_grad():
+ if is_similarity_metric():
+ node_embeddings_np = node_embeddings_tensor.cpu().numpy()
+ query_np = query_tensor.cpu().numpy()
+ distances = -np.dot(node_embeddings_np, query_np)
+ else:
+ node_embeddings_np = node_embeddings_tensor.cpu().numpy().astype(np.float32)
+ query_np = query_tensor.cpu().numpy().astype(np.float32)
+ distances = np.sum(np.square(node_embeddings_np - query_np.reshape(1, -1)), axis=1)
+ calc_timer.print_elapsed()
+
+ try:
+ response_payload = distances.flatten().tolist()
+ response_bytes = msgpack.packb([response_payload], use_single_float=True)
+ print(f"Sending distance response with {len(distances)} distances")
+ except Exception as pack_error:
+ print(f"Error packing MessagePack distance response: {pack_error}")
+ response_bytes = msgpack.packb([[]])
+
+ socket.send(response_bytes)
+
+ if device.type == "cuda":
+ torch.cuda.synchronize()
+ elif device.type == "mps":
+ torch.mps.synchronize()
+ e2e_end = time.time()
+ print(f"Distance calculation E2E time: {e2e_end - e2e_start:.6f} seconds")
+ continue
+
+ # Standard embedding request
+ if not isinstance(request_payload, list) or len(request_payload) != 1 or not isinstance(request_payload[0], list):
+ print(f"Error: Invalid MessagePack request format. Expected [[ids...]], got: {type(request_payload)}")
+ socket.send(msgpack.packb([[], []]))
+ continue
+
+ node_ids = request_payload[0]
+ print(f"Request for {len(node_ids)} node embeddings")
+
+ except Exception as unpack_error:
+ print(f"Error unpacking MessagePack request: {unpack_error}")
+ socket.send(msgpack.packb([[], []]))
+ continue
+
+ # Look up texts by node IDs
+ texts = []
+ missing_ids = []
+ with lookup_timer.timing():
+ for nid in node_ids:
+ txtinfo = passages[nid]
+ if txtinfo is None or txtinfo["text"] == "":
+ print(f"Warning: Passage with ID {nid} not found")
+ missing_ids.append(nid)
+ txt = ""
+ else:
+ txt = txtinfo["text"]
+ texts.append(txt)
+ lookup_timer.print_elapsed()
+
+ if missing_ids:
+ print(f"Missing passages for IDs: {missing_ids}")
+
+ # Process in chunks
+ total_size = len(texts)
+ print(f"Total batch size: {total_size}, max_batch_size: {max_batch_size}")
+
+ all_embeddings = []
+
+ if total_size > max_batch_size:
+ print(f"Splitting batch of size {total_size} into chunks of {max_batch_size}")
+ for i in range(0, total_size, max_batch_size):
+ end_idx = min(i + max_batch_size, total_size)
+ print(f"Processing chunk {i//max_batch_size + 1}/{(total_size + max_batch_size - 1)//max_batch_size}: items {i} to {end_idx-1}")
+
+ chunk_texts = texts[i:end_idx]
+ chunk_ids = node_ids[i:end_idx]
+
+ embeddings_chunk = process_batch(chunk_texts, chunk_ids, missing_ids)
+ all_embeddings.append(embeddings_chunk)
+
+ if cuda_available:
+ torch.cuda.empty_cache()
+ elif device.type == "mps":
+ torch.mps.empty_cache()
+
+ hidden = np.vstack(all_embeddings)
+ print(f"Combined embeddings shape: {hidden.shape}")
+ else:
+ hidden = process_batch(texts, node_ids, missing_ids)
+
+ # Serialization and response
+ ser_start = time.time()
+
+ print(f"DEBUG zmq_server_thread: Final 'hidden' array | Shape: {hidden.shape} | Dtype: {hidden.dtype} | Has NaN/Inf: {np.isnan(hidden).any() or np.isinf(hidden).any()}")
+ if np.isnan(hidden).any() or np.isinf(hidden).any():
+ print(f"{RED}!!! ERROR: NaN or Inf detected in final 'hidden' numpy array BEFORE sending! "
+ f"Requested IDs (sample): {node_ids[:5]}...{RESET}")
+ assert False
+
+ try:
+ hidden_contiguous_f32 = np.ascontiguousarray(hidden, dtype=np.float32)
+ response_payload = [
+ list(hidden_contiguous_f32.shape),
+ hidden_contiguous_f32.flatten().tolist()
+ ]
+ response_bytes = msgpack.packb(response_payload, use_single_float=True)
+ except Exception as pack_error:
+ print(f"Error packing MessagePack response: {pack_error}")
+ response_bytes = msgpack.packb([[], []])
+
+ socket.send(response_bytes)
+ ser_end = time.time()
+
+ print(f"Serialize time: {ser_end - ser_start:.6f} seconds")
+
+ if device.type == "cuda":
+ torch.cuda.synchronize()
+ elif device.type == "mps":
+ torch.mps.synchronize()
+ e2e_end = time.time()
+ print(f"ZMQ E2E time: {e2e_end - e2e_start:.6f} seconds")
+
+ except zmq.Again:
+ print("ZMQ socket timeout, continuing to listen")
+ continue
+ except Exception as e:
+ print(f"Error in ZMQ server loop: {e}")
+ import traceback
+ traceback.print_exc()
+ try:
+ socket.send(msgpack.packb([[], []]))
+ except:
+ pass
+
+ # Start warmup and server threads
+ if len(passages) > 0:
+ warmup_thread = threading.Thread(target=client_warmup, args=(zmq_port,))
+ warmup_thread.daemon = True
+ warmup_thread.start()
+
+ zmq_thread = threading.Thread(target=zmq_server_thread, daemon=True)
+ zmq_thread.start()
+ print(f"Started HNSW ZMQ server thread on port {zmq_port}")
+
+ # Keep the main thread alive
+ try:
+ while True:
+ time.sleep(1)
+ except KeyboardInterrupt:
+ print("HNSW Server shutting down...")
+ return
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="HNSW Embedding service")
+ parser.add_argument("--zmq-port", type=int, default=5555, help="ZMQ port to run on")
+ parser.add_argument("--passages-file", type=str, help="JSON file containing passage ID to text mapping")
+ parser.add_argument("--embeddings-file", type=str, help="Pickle file containing pre-computed embeddings")
+ parser.add_argument("--use-fp16", action="store_true", default=False)
+ parser.add_argument("--use-int8", action="store_true", default=False)
+ parser.add_argument("--use-cuda-graphs", action="store_true", default=False)
+ parser.add_argument("--max-batch-size", type=int, default=128, help="Maximum batch size before splitting")
+ parser.add_argument("--model-name", type=str, default="sentence-transformers/all-mpnet-base-v2",
+ help="Embedding model name")
+ parser.add_argument("--custom-max-length", type=int, default=None, help="Override model's default max sequence length")
+
+ args = parser.parse_args()
+
+ # Create and start the HNSW embedding server
+ create_hnsw_embedding_server(
+ passages_file=args.passages_file,
+ embeddings_file=args.embeddings_file,
+ use_fp16=args.use_fp16,
+ use_int8=args.use_int8,
+ use_cuda_graphs=args.use_cuda_graphs,
+ zmq_port=args.zmq_port,
+ max_batch_size=args.max_batch_size,
+ model_name=args.model_name,
+ custom_max_length_param=args.custom_max_length,
+ )
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/pyproject.toml b/packages/leann-backend-hnsw/pyproject.toml
new file mode 100644
index 0000000..2201403
--- /dev/null
+++ b/packages/leann-backend-hnsw/pyproject.toml
@@ -0,0 +1,18 @@
+# 文件: packages/leann-backend-hnsw/pyproject.toml
+
+[build-system]
+requires = ["scikit-build-core>=0.10", "numpy", "swig"]
+build-backend = "scikit_build_core.build"
+
+[project]
+name = "leann-backend-hnsw"
+version = "0.1.0"
+description = "Custom-built HNSW (Faiss) backend for the Leann toolkit."
+dependencies = ["leann-core==0.1.0", "numpy"]
+
+# 回归到最标准的 scikit-build-core 配置
+[tool.scikit-build]
+wheel.packages = ["leann_backend_hnsw"]
+editable.mode = "redirect"
+cmake.build-type = "Debug"
+build.verbose = true
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.clang-format b/packages/leann-backend-hnsw/third_party/faiss/.clang-format
new file mode 100644
index 0000000..1fe6508
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.clang-format
@@ -0,0 +1,88 @@
+---
+AccessModifierOffset: -1
+AlignAfterOpenBracket: AlwaysBreak
+AlignConsecutiveAssignments: false
+AlignConsecutiveDeclarations: false
+AlignEscapedNewlinesLeft: true
+AlignOperands: false
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: false
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: Empty
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: true
+AlwaysBreakTemplateDeclarations: true
+BinPackArguments: false # at some point, set this to true
+BinPackParameters: false # at some point, set this to true
+BraceWrapping:
+ AfterClass: false
+ AfterControlStatement: false
+ AfterEnum: false
+ AfterFunction: false
+ AfterNamespace: false
+ AfterObjCDeclaration: false
+ AfterStruct: false
+ AfterUnion: false
+ BeforeCatch: false
+ BeforeElse: false
+ IndentBraces: false
+BreakBeforeBinaryOperators: None
+BreakBeforeBraces: Attach
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializersBeforeComma: false
+BreakAfterJavaFieldAnnotations: false
+BreakStringLiterals: false
+ColumnLimit: 80
+CommentPragmas: '^ IWYU pragma:'
+CompactNamespaces: false
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+ConstructorInitializerIndentWidth: 8
+ContinuationIndentWidth: 8
+Cpp11BracedListStyle: true
+DerivePointerAlignment: false
+DisableFormat: false
+ForEachMacros: [ FOR_EACH_RANGE, FOR_EACH, ]
+IncludeCategories:
+ - Regex: '^<.*\.h(pp)?>'
+ Priority: 1
+ - Regex: '^<.*'
+ Priority: 2
+ - Regex: '.*'
+ Priority: 3
+IndentCaseLabels: true
+IndentWidth: 4
+IndentWrappedFunctionNames: false
+KeepEmptyLinesAtTheStartOfBlocks: false
+MacroBlockBegin: ''
+MacroBlockEnd: ''
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: None
+ObjCBlockIndentWidth: 4
+ObjCSpaceAfterProperty: false
+ObjCSpaceBeforeProtocolList: false
+PenaltyBreakBeforeFirstCallParameter: 1
+PenaltyBreakComment: 300
+PenaltyBreakFirstLessLess: 120
+PenaltyBreakString: 1000
+PenaltyExcessCharacter: 1000000
+PenaltyReturnTypeOnItsOwnLine: 2000000
+PointerAlignment: Left
+ReflowComments: true
+SortIncludes: true
+SpaceAfterCStyleCast: false
+SpaceBeforeAssignmentOperators: true
+SpaceBeforeParens: ControlStatements
+SpaceInEmptyParentheses: false
+SpacesBeforeTrailingComments: 1
+SpacesInAngles: false
+SpacesInContainerLiterals: true
+SpacesInCStyleCastParentheses: false
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+Standard: Cpp11
+TabWidth: 8
+UseTab: Never
+...
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.dockerignore b/packages/leann-backend-hnsw/third_party/faiss/.dockerignore
new file mode 100644
index 0000000..7763a51
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.dockerignore
@@ -0,0 +1 @@
+sift1M
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/ISSUE_TEMPLATE.md b/packages/leann-backend-hnsw/third_party/faiss/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 0000000..132be64
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,33 @@
+# Summary
+
+<!-- Facebook has a bounty program for the safe disclosure of security bugs. In
+those cases, please go through the process outlined on that page and do not
+file a public issue. -->
+
+# Platform
+
+<!-- if the question/problem is not platform-specific, please ignore this -->
+
+OS: <!-- e.g. macOS 10.13.3 -->
+
+Faiss version: <!-- git commit, e.g. 56383610bcb982d6591e2e2bea3516cb7723e04a -->
+
+Installed from: <!-- anaconda? compiled by yourself ? -->
+
+Faiss compilation options: <!-- e.g. using MKL with compile flags ... -->
+
+Running on:
+- [ ] CPU
+- [ ] GPU
+
+Interface:
+- [ ] C++
+- [ ] Python
+
+# Reproduction instructions
+
+<!-- Please provide specific and comprehensive instructions to reproduce the
+described behavior. -->
+
+<!-- Please *do not* post screenshots of logs. They are not searchable. Copy/paste
+the text or make a gist if the text is too bulky. -->
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/actions/build_cmake/action.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/actions/build_cmake/action.yml
new file mode 100644
index 0000000..6251519
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/actions/build_cmake/action.yml
@@ -0,0 +1,189 @@
+name: Build cmake
+inputs:
+ opt_level:
+ description: 'Compile options / optimization level.'
+ required: false
+ default: generic
+ gpu:
+ description: 'Enable GPU support.'
+ required: false
+ default: OFF
+ cuvs:
+ description: 'Enable cuVS support.'
+ required: false
+ default: OFF
+ rocm:
+ description: 'Enable ROCm support.'
+ required: false
+ default: OFF
+runs:
+ using: composite
+ steps:
+ - name: Setup miniconda
+ uses: conda-incubator/setup-miniconda@v3
+ with:
+ python-version: '3.11'
+ miniforge-version: latest # ensures conda-forge channel is used.
+ channels: conda-forge
+ conda-remove-defaults: 'true'
+ # Set to aarch64 if we're on arm64 because there's no miniforge ARM64 package, just aarch64.
+ # They are the same thing, just named differently.
+ architecture: ${{ runner.arch == 'ARM64' && 'aarch64' || runner.arch }}
+ - name: Configure build environment
+ shell: bash
+ run: |
+ # initialize Conda
+ conda config --set solver libmamba
+ # Ensure starting packages are from conda-forge.
+ conda list --show-channel-urls
+ conda update -y -q conda
+ echo "$CONDA/bin" >> $GITHUB_PATH
+
+ conda install -y -q python=3.11 cmake=3.26 make=4.2 swig=4.0 "numpy<2" scipy=1.14 pytest=7.4 gflags=2.2
+
+ # install base packages for ARM64
+ if [ "${{ runner.arch }}" = "ARM64" ]; then
+ conda install -y -q -c conda-forge openblas=0.3.29 gxx_linux-aarch64=14.2 sysroot_linux-aarch64=2.17
+ fi
+
+ # install base packages for X86_64
+ if [ "${{ runner.arch }}" = "X64" ]; then
+ # TODO: merge this with ARM64
+ conda install -y -q -c conda-forge gxx_linux-64=14.2 sysroot_linux-64=2.17
+ conda install -y -q mkl=2022.2.1 mkl-devel=2022.2.1
+ fi
+
+ # no CUDA needed for ROCm so skip this
+ if [ "${{ inputs.rocm }}" = "ON" ]; then
+ :
+ # regular CUDA for GPU builds
+ elif [ "${{ inputs.gpu }}" = "ON" ] && [ "${{ inputs.cuvs }}" = "OFF" ]; then
+ conda install -y -q cuda-toolkit=12.4 -c "nvidia/label/cuda-12.4.0"
+ # and CUDA from cuVS channel for cuVS builds
+ elif [ "${{ inputs.cuvs }}" = "ON" ]; then
+ conda install -y -q libcuvs=24.12 'cuda-version>=12.0,<=12.5' cuda-toolkit=12.4.1 gxx_linux-64=12.4 -c rapidsai -c conda-forge
+ fi
+
+ # install test packages
+ if [ "${{ inputs.rocm }}" = "ON" ]; then
+ : # skip torch install via conda, we need to install via pip to get
+ # ROCm-enabled version until it's supported in conda by PyTorch
+ elif [ "${{ inputs.gpu }}" = "ON" ]; then
+ conda install -y -q "pytorch<2.5" pytorch-cuda=12.4 -c pytorch -c "nvidia/label/cuda-12.4.0"
+ else
+ conda install -y -q "pytorch<2.5" -c pytorch
+ fi
+ - name: ROCm - Install dependencies
+ if: inputs.rocm == 'ON'
+ shell: bash
+ run: |
+ # Update repos and install kmod, wget, gpg
+ sudo apt-get -qq update >/dev/null
+ sudo apt-get -qq install -y kmod wget gpg >/dev/null
+
+ # Get UBUNTU version name
+ UBUNTU_VERSION_NAME=`cat /etc/os-release | grep UBUNTU_CODENAME | awk -F= '{print $2}'`
+
+ # Set ROCm version
+ ROCM_VERSION="6.2"
+
+ # Download, prepare, and install the package signing key
+ mkdir --parents --mode=0755 /etc/apt/keyrings
+ wget https://repo.radeon.com/rocm/rocm.gpg.key -O - | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
+
+ # Add rocm repository
+ wget -qO - http://repo.radeon.com/rocm/rocm.gpg.key | sudo apt-key add -
+ rocm_baseurl="http://repo.radeon.com/rocm/apt/${ROCM_VERSION}"
+ echo "deb [arch=amd64] ${rocm_baseurl} ${UBUNTU_VERSION_NAME} main" | sudo tee /etc/apt/sources.list.d/rocm.list
+ sudo apt-get -qq update --allow-insecure-repositories >/dev/null
+ sudo apt-get -qq install -y --allow-unauthenticated \
+ "rocm-dev${ROCM_VERSION}" "rocm-utils${ROCM_VERSION}" \
+ "rocm-libs${ROCM_VERSION}" >/dev/null
+
+ # Fake presence of MI200-class accelerators
+ echo "gfx90a" | sudo tee /opt/rocm/bin/target.lst
+
+ # Cleanup
+ sudo apt-get -qq autoclean >/dev/null
+ sudo apt-get -qq clean >/dev/null
+ sudo rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
+ - name: Symblink system dependencies
+ if: inputs.rocm == 'ON'
+ shell: bash
+ run: |
+ # symblink system libraries for HIP compiler
+ sudo ln -s /lib/x86_64-linux-gnu/libc.so.6 /lib64/libc.so.6
+ sudo ln -s /lib/x86_64-linux-gnu/libc_nonshared.a /usr/lib64/libc_nonshared.a
+ sudo ln -s /usr/lib/x86_64-linux-gnu/libpthread.so.0 /lib64/libpthread.so.0
+ sudo ln -s $HOME/miniconda3/x86_64-conda-linux-gnu/sysroot/usr/lib64/libpthread_nonshared.a /usr/lib64/libpthread_nonshared.a
+ - name: Build all targets
+ shell: bash
+ run: |
+ eval "$(conda shell.bash hook)"
+ conda activate
+ cmake -B build \
+ -DBUILD_TESTING=ON \
+ -DBUILD_SHARED_LIBS=ON \
+ -DFAISS_ENABLE_GPU=${{ inputs.gpu }} \
+ -DFAISS_ENABLE_CUVS=${{ inputs.cuvs }} \
+ -DFAISS_ENABLE_ROCM=${{ inputs.rocm }} \
+ -DFAISS_OPT_LEVEL=${{ inputs.opt_level }} \
+ -DFAISS_ENABLE_C_API=ON \
+ -DPYTHON_EXECUTABLE=$CONDA/bin/python \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DBLA_VENDOR=${{ runner.arch == 'X64' && 'Intel10_64_dyn' || '' }} \
+ -DCMAKE_CUDA_FLAGS=${{ runner.arch == 'X64' && '"-gencode arch=compute_75,code=sm_75"' || '' }} \
+ .
+ make -k -C build -j$(nproc)
+ - name: C++ tests
+ shell: bash
+ run: |
+ export GTEST_OUTPUT="xml:$(realpath .)/test-results/googletest/"
+ make -C build test
+ - name: C++ perf benchmarks
+ shell: bash
+ if: inputs.rocm == 'OFF'
+ run: |
+ find ./build/perf_tests/ -executable -type f -name "bench*" -exec '{}' -v \;
+ - name: Install Python extension
+ shell: bash
+ working-directory: build/faiss/python
+ run: |
+ $CONDA/bin/python setup.py install
+ - name: ROCm - install ROCm-enabled torch via pip
+ if: inputs.rocm == 'ON'
+ shell: bash
+ run: |
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.1
+ - name: Python tests (CPU only)
+ if: inputs.gpu == 'OFF'
+ shell: bash
+ run: |
+ pytest --junitxml=test-results/pytest/results.xml tests/test_*.py
+ pytest --junitxml=test-results/pytest/results-torch.xml tests/torch_*.py
+ - name: Python tests (CPU + GPU)
+ if: inputs.gpu == 'ON'
+ shell: bash
+ run: |
+ pytest --junitxml=test-results/pytest/results.xml tests/test_*.py
+ pytest --junitxml=test-results/pytest/results-torch.xml tests/torch_*.py
+ cp tests/common_faiss_tests.py faiss/gpu/test
+ pytest --junitxml=test-results/pytest/results-gpu.xml faiss/gpu/test/test_*.py
+ pytest --junitxml=test-results/pytest/results-gpu-torch.xml faiss/gpu/test/torch_*.py
+ - name: Test avx2 loading
+ if: inputs.opt_level == 'avx2'
+ shell: bash
+ run: |
+ FAISS_DISABLE_CPU_FEATURES=AVX2 LD_DEBUG=libs $CONDA/bin/python -c "import faiss" 2>&1 | grep faiss.so
+ LD_DEBUG=libs $CONDA/bin/python -c "import faiss" 2>&1 | grep faiss_avx2.so
+ - name: Upload test results
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: test-results-arch=${{ runner.arch }}-opt=${{ inputs.opt_level }}-gpu=${{ inputs.gpu }}-cuvs=${{ inputs.cuvs }}-rocm=${{ inputs.rocm }}
+ path: test-results
+ - name: Check installed packages channel
+ shell: bash
+ run: |
+ # Shows that all installed packages are from conda-forge.
+ conda list --show-channel-urls
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/actions/build_conda/action.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/actions/build_conda/action.yml
new file mode 100644
index 0000000..14c2270
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/actions/build_conda/action.yml
@@ -0,0 +1,107 @@
+name: Conda build
+description: Builds Faiss inside a Conda environment and uploads to repository when label is provided.
+inputs:
+ label:
+ description: "The label to be used for uploads to Conda."
+ default: ""
+ required: false
+ cuda:
+ description: "CUDA toolkit version to use."
+ default: ""
+ required: false
+ cuvs:
+ description: "Enable cuVS support."
+ default: ""
+ required: false
+runs:
+ using: composite
+ steps:
+ - name: Choose shell
+ shell: bash
+ id: choose_shell
+ run: |
+ # Use pwsh on Windows; bash everywhere else
+ if [ "${{ runner.os }}" != "Windows" ]; then
+ echo "shell=bash" >> "$GITHUB_OUTPUT"
+ else
+ echo "shell=pwsh" >> "$GITHUB_OUTPUT"
+ fi
+ - name: Setup miniconda
+ uses: conda-incubator/setup-miniconda@v3
+ with:
+ python-version: '3.11'
+ miniforge-version: latest # ensures conda-forge channel is used.
+ channels: conda-forge
+ conda-remove-defaults: 'true'
+ # Set to runner.arch=aarch64 if we're on arm64 because
+ # there's no miniforge ARM64 package, just aarch64.
+ # They are the same thing, just named differently.
+ # However there is an ARM64 for macOS, so exclude that.
+ architecture: ${{ (runner.arch == 'ARM64' && runner.os != 'macOS') && 'aarch64' || runner.arch }}
+ - name: Install conda build tools
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ run: |
+ # Ensure starting packages are from conda-forge.
+ conda list --show-channel-urls
+ conda install -y -q "conda!=24.11.0"
+ conda install -y -q "conda-build!=24.11.0" "liblief=0.14.1"
+ conda list --show-channel-urls
+ - name: Enable anaconda uploads
+ if: inputs.label != ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ env:
+ PACKAGE_TYPE: ${{ inputs.label }}
+ run: |
+ conda install -y -q anaconda-client
+ conda config --set anaconda_upload yes
+ - name: Conda build (CPU)
+ if: inputs.label == '' && inputs.cuda == ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ working-directory: conda
+ run: |
+ conda build faiss --python 3.11 -c pytorch
+ - name: Conda build (CPU) w/ anaconda upload
+ if: inputs.label != '' && inputs.cuda == ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ working-directory: conda
+ env:
+ PACKAGE_TYPE: ${{ inputs.label }}
+ run: |
+ conda build faiss --user pytorch --label ${{ inputs.label }} -c pytorch
+ - name: Conda build (GPU)
+ if: inputs.label == '' && inputs.cuda != '' && inputs.cuvs == ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ working-directory: conda
+ run: |
+ conda build faiss-gpu --variants '{ "cudatoolkit": "${{ inputs.cuda }}" }' \
+ -c pytorch -c nvidia/label/cuda-${{ inputs.cuda }} -c nvidia
+ - name: Conda build (GPU) w/ anaconda upload
+ if: inputs.label != '' && inputs.cuda != '' && inputs.cuvs == ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ working-directory: conda
+ env:
+ PACKAGE_TYPE: ${{ inputs.label }}
+ run: |
+ conda build faiss-gpu --variants '{ "cudatoolkit": "${{ inputs.cuda }}" }' \
+ --user pytorch --label ${{ inputs.label }} -c pytorch -c nvidia/label/cuda-${{ inputs.cuda }} -c nvidia
+ - name: Conda build (GPU w/ cuVS)
+ if: inputs.label == '' && inputs.cuda != '' && inputs.cuvs != ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ working-directory: conda
+ run: |
+ conda build faiss-gpu-cuvs --variants '{ "cudatoolkit": "${{ inputs.cuda }}" }' \
+ -c pytorch -c rapidsai -c rapidsai-nightly -c conda-forge -c nvidia
+ - name: Conda build (GPU w/ cuVS) w/ anaconda upload
+ if: inputs.label != '' && inputs.cuda != '' && inputs.cuvs != ''
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ working-directory: conda
+ env:
+ PACKAGE_TYPE: ${{ inputs.label }}
+ run: |
+ conda build faiss-gpu-cuvs --variants '{ "cudatoolkit": "${{ inputs.cuda }}" }' \
+ --user pytorch --label ${{ inputs.label }} -c pytorch -c rapidsai -c rapidsai-nightly -c conda-forge -c nvidia
+ - name: Check installed packages channel
+ shell: ${{ steps.choose_shell.outputs.shell }}
+ run: |
+ # Shows that all installed packages are from conda-forge.
+ conda list --show-channel-urls
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/autoclose.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/autoclose.yml
new file mode 100644
index 0000000..41a5827
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/autoclose.yml
@@ -0,0 +1,23 @@
+name: Close Inactive Issues
+on:
+ schedule:
+ - cron: "30 1 * * *"
+
+jobs:
+ close-issues:
+ runs-on: ubuntu-latest
+ permissions:
+ issues: write
+ pull-requests: write
+ steps:
+ - uses: actions/stale@v5
+ with:
+ only-labels: autoclose
+ days-before-issue-stale: 7
+ days-before-issue-close: 7
+ stale-issue-label: "stale"
+ stale-issue-message: "This issue is stale because it has been open for 7 days with no activity."
+ close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
+ days-before-pr-stale: -1
+ days-before-pr-close: -1
+ repo-token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build-pull-request.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build-pull-request.yml
new file mode 100644
index 0000000..bc0d2d6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build-pull-request.yml
@@ -0,0 +1,169 @@
+on:
+ workflow_call:
+env:
+ OMP_NUM_THREADS: '10'
+ MKL_THREADING_LAYER: GNU
+jobs:
+ format:
+ name: Format
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Install clang-format
+ run: |
+ sudo apt-get update -y
+ sudo apt-get install -y wget
+ sudo apt install -y lsb-release wget software-properties-common gnupg
+ wget https://apt.llvm.org/llvm.sh
+ chmod u+x llvm.sh
+ sudo ./llvm.sh 18
+ sudo apt-get install -y git-core clang-format-18
+ - name: Verify clang-format
+ run: |
+ git ls-files | grep -E '\.(cpp|h|cu|cuh)$' | xargs clang-format-18 -i
+ if git diff --quiet; then
+ echo "Formatting OK!"
+ else
+ echo "Formatting not OK!"
+ echo "------------------"
+ git --no-pager diff --color
+ exit 1
+ fi
+ linux-x86_64-cmake:
+ name: Linux x86_64 (cmake)
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ linux-x86_64-AVX2-cmake:
+ name: Linux x86_64 AVX2 (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ opt_level: avx2
+ linux-x86_64-AVX512-cmake:
+ name: Linux x86_64 AVX512 (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: faiss-aws-m7i.large
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ opt_level: avx512
+ linux-x86_64-AVX512_SPR-cmake:
+ name: Linux x86_64 AVX512_SPR (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: faiss-aws-m7i.large
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ opt_level: avx512_spr
+ linux-x86_64-GPU-cmake:
+ name: Linux x86_64 GPU (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: 4-core-ubuntu-gpu-t4
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ gpu: ON
+ linux-x86_64-GPU-w-CUVS-cmake:
+ name: Linux x86_64 GPU w/ cuVS (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: 4-core-ubuntu-gpu-t4
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ gpu: ON
+ cuvs: ON
+ linux-x86_64-GPU-w-ROCm-cmake:
+ name: Linux x86_64 GPU w/ ROCm (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: faiss-amd-MI200
+ container:
+ image: ubuntu:22.04
+ options: --device=/dev/kfd --device=/dev/dri --ipc=host --shm-size 16G --group-add video --cap-add=SYS_PTRACE --cap-add=SYS_ADMIN
+ steps:
+ - name: Container setup
+ run: |
+ if [ -f /.dockerenv ]; then
+ apt-get update && apt-get install -y sudo && apt-get install -y git
+ git config --global --add safe.directory '*'
+ else
+ echo 'Skipping. Current job is not running inside a container.'
+ fi
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ gpu: ON
+ rocm: ON
+ linux-arm64-SVE-cmake:
+ name: Linux arm64 SVE (cmake)
+ needs: linux-x86_64-cmake
+ runs-on: faiss-aws-r8g.large
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Build and Test (cmake)
+ uses: ./.github/actions/build_cmake
+ with:
+ opt_level: sve
+ env:
+ # Context: https://github.com/facebookresearch/faiss/wiki/Troubleshooting#surprising-faiss-openmp-and-openblas-interaction
+ OPENBLAS_NUM_THREADS: '1'
+ linux-x86_64-conda:
+ name: Linux x86_64 (conda)
+ needs: linux-x86_64-cmake
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ windows-x86_64-conda:
+ name: Windows x86_64 (conda)
+ needs: linux-x86_64-cmake
+ runs-on: windows-2019
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ linux-arm64-conda:
+ name: Linux arm64 (conda)
+ needs: linux-x86_64-cmake
+ runs-on: 2-core-ubuntu-arm
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build-release.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build-release.yml
new file mode 100644
index 0000000..b5b02f2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build-release.yml
@@ -0,0 +1,144 @@
+on:
+ workflow_call:
+ secrets:
+ ANACONDA_API_TOKEN:
+ required: true
+env:
+ OMP_NUM_THREADS: '10'
+ MKL_THREADING_LAYER: GNU
+jobs:
+ linux-x86_64-packages:
+ name: Linux x86_64 packages
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ linux-x86_64-GPU-packages-CUDA-11-4-4:
+ name: Linux x86_64 GPU packages (CUDA 11.4.4)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "60-real;61-real;62-real;70-real;72-real;75-real;80;86-real"
+ FAISS_FLATTEN_CONDA_INCLUDES: "1"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ cuda: "11.4.4"
+ linux-x86_64-GPU-CUVS-packages-CUDA11-8-0:
+ name: Linux x86_64 GPU w/ cuVS packages (CUDA 11.8.0)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "70-real;72-real;75-real;80;86-real"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ cuvs: "ON"
+ cuda: "11.8.0"
+ linux-x86_64-GPU-packages-CUDA-12-1-1:
+ name: Linux x86_64 GPU packages (CUDA 12.1.1)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "70-real;72-real;75-real;80;86-real"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ cuda: "12.1.1"
+ linux-x86_64-GPU-CUVS-packages-CUDA12-4-0:
+ name: Linux x86_64 GPU w/ cuVS packages (CUDA 12.4.0)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "70-real;72-real;75-real;80;86-real"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ cuvs: "ON"
+ cuda: "12.4.0"
+ windows-x86_64-packages:
+ name: Windows x86_64 packages
+ runs-on: windows-2019
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ osx-arm64-packages:
+ name: OSX arm64 packages
+ runs-on: macos-14
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
+ linux-arm64-packages:
+ name: Linux arm64 packages
+ runs-on: 2-core-ubuntu-arm
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - name: Build and Package (conda)
+ uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: main
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build.yml
new file mode 100644
index 0000000..82792cb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/build.yml
@@ -0,0 +1,17 @@
+name: Build
+on:
+ workflow_dispatch:
+ pull_request:
+ branches:
+ - main
+ push:
+ tags:
+ - 'v*'
+jobs:
+ build-pull-request:
+ uses: ./.github/workflows/build-pull-request.yml
+ build-release:
+ uses: ./.github/workflows/build-release.yml
+ secrets:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/nightly.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/nightly.yml
new file mode 100644
index 0000000..ef1e8d2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/nightly.yml
@@ -0,0 +1,148 @@
+name: Nightly
+on:
+ schedule:
+ - cron: '10 6 * * *'
+env:
+ OMP_NUM_THREADS: '10'
+ MKL_THREADING_LAYER: GNU
+jobs:
+ linux-x86_64-nightly:
+ name: Linux x86_64 nightlies
+ runs-on: 4-core-ubuntu
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ linux-x86_64-GPU-CUDA-11-4-4-nightly:
+ name: Linux x86_64 GPU nightlies (CUDA 11.4.4)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "60-real;61-real;62-real;70-real;72-real;75-real;80;86-real"
+ FAISS_FLATTEN_CONDA_INCLUDES: "1"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ cuda: "11.4.4"
+ linux-x86_64-GPU-CUVS-CUDA11-8-0-nightly:
+ name: Linux x86_64 GPU w/ cuVS nightlies (CUDA 11.8.0)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "70-real;72-real;75-real;80;86-real"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ cuvs: "ON"
+ cuda: "11.8.0"
+ linux-x86_64-GPU-CUDA-12-1-1-nightly:
+ name: Linux x86_64 GPU nightlies (CUDA 12.1.1)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "70-real;72-real;75-real;80;86-real"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ cuda: "12.1.1"
+ linux-x86_64-GPU-CUVS-CUDA12-4-0-nightly:
+ name: Linux x86_64 GPU w/ cuVS nightlies (CUDA 12.4.0)
+ runs-on: 4-core-ubuntu-gpu-t4
+ env:
+ CUDA_ARCHS: "70-real;72-real;75-real;80;86-real"
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ cuvs: "ON"
+ cuda: "12.4.0"
+ windows-x86_64-nightly:
+ name: Windows x86_64 nightlies
+ runs-on: windows-2019
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ osx-arm64-nightly:
+ name: OSX arm64 nightlies
+ runs-on: macos-14
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ linux-arm64-nightly:
+ name: Linux arm64 nightlies
+ runs-on: 2-core-ubuntu-arm
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ fetch-tags: true
+ - uses: ./.github/actions/build_conda
+ env:
+ ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
+ with:
+ label: nightly
+ auto-retry:
+ name: Auto retry on failure
+ if: fromJSON(github.run_attempt) < 2
+ runs-on: ubuntu-latest
+ steps:
+ - name: Start rerun workflow
+ env:
+ GH_REPO: ${{ github.repository }}
+ GH_TOKEN: ${{ github.token }}
+ GH_DEBUG: api
+ run: |
+ gh workflow run retry_build.yml \
+ -F run_id=${{ github.run_id }}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/publish-docs.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/publish-docs.yml
new file mode 100644
index 0000000..a75c485
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/publish-docs.yml
@@ -0,0 +1,44 @@
+name: Publish Docs
+on:
+ page_build:
+ branches:
+ - gh-pages
+ paths-ignore:
+ - 'docs/**'
+ workflow_run:
+ workflows: [update-doxygen]
+ types:
+ - completed
+jobs:
+ build_and_publish:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Set up Python
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.8
+ - name: Checkout gh-pages
+ run: |
+ git fetch origin gh-pages
+ git checkout gh-pages
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install -r requirements.txt
+ - name: Generate html
+ run: |
+ make html
+ git rm -rf docs
+ mv _build/html docs
+ touch docs/.nojekyll
+ - name: Push changes
+ run: |
+ git config --global user.email "[email protected]"
+ git config --global user.name "$GITHUB_ACTOR"
+ git add docs
+ if [ -n "$(git status --porcelain)" ]
+ then
+ git commit docs -m "Sphinx rebuild ($(git rev-parse --short gh-pages))."
+ git push origin gh-pages
+ fi
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/retry_build.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/retry_build.yml
new file mode 100644
index 0000000..45c07ff
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/retry_build.yml
@@ -0,0 +1,33 @@
+name: Retry Build
+on:
+ workflow_dispatch:
+ inputs:
+ run_id:
+ required: true
+jobs:
+ rerun-on-failure:
+ permissions: write-all
+ runs-on: ubuntu-latest
+ steps:
+ - name: rerun ${{ inputs.run_id }}
+ env:
+ GH_REPO: ${{ github.repository }}
+ GH_TOKEN: ${{ github.token }}
+ GH_DEBUG: api
+ run: |
+ # status can be one of "queued", "in_progress", "completed", "waiting", "requested", "pending"
+ # https://docs.github.com/en/rest/checks/runs
+ # while not completed, sleep for 10 minutes
+ while gh run view ${{ inputs.run_id }} --json status | grep -v completed
+ do
+ echo Workflow in progress - sleeping for 10 minutes then checking again
+ sleep 10m
+ done
+
+ # Only retry if there are failed jobs
+ if gh run view ${{ inputs.run_id }} --exit-status; then
+ echo Workflow succeeded - no retry necessary.
+ else
+ echo Workflow failed - initiating retry.
+ gh run rerun ${{ inputs.run_id }} --failed
+ fi
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/update-doxygen.yml b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/update-doxygen.yml
new file mode 100644
index 0000000..64d9435
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.github/workflows/update-doxygen.yml
@@ -0,0 +1,40 @@
+name: Update Doxygen
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - 'faiss/**'
+jobs:
+ doxygen:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Set up Python
+ uses: actions/setup-python@v2
+ with:
+ python-version: 3.8
+ - name: Install dependencies
+ run: |
+ sudo apt-get install -y doxygen
+ python -m pip install --upgrade pip
+ pip install breathe
+ - name: Generate doxygen xml
+ run: doxygen
+ - name: Push changes
+ run: |
+ git config --global user.email "[email protected]"
+ git config --global user.name "$GITHUB_ACTOR"
+ mkdir ./tmp
+ mv xml ./tmp/xml
+ git fetch origin gh-pages
+ git checkout gh-pages
+ git rm -rf xml cpp_api
+ mv ./tmp/xml ./xml
+ breathe-apidoc -o cpp_api xml
+ git add xml cpp_api
+ if [ -n "$(git status --porcelain)" ]
+ then
+ git commit -m "Update API docs ($(git rev-parse --short main))."
+ git push origin gh-pages
+ fi
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.gitignore b/packages/leann-backend-hnsw/third_party/faiss/.gitignore
new file mode 100644
index 0000000..2d5a8dc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.gitignore
@@ -0,0 +1,26 @@
+*.swp
+*.swo
+*.o
+*.a
+*.dSYM
+*.so
+*.dylib
+*.pyc
+*~
+/build/
+/config.*
+/aclocal.m4
+/autom4te.cache/
+/makefile.inc
+/bin/
+/c_api/bin/
+/c_api/gpu/bin/
+/tests/test
+/tests/gtest/
+faiss/python/swigfaiss_avx2.swig
+faiss/python/swigfaiss_avx512.swig
+faiss/python/swigfaiss_avx512_spr.swig
+faiss/python/swigfaiss_sve.swig
+.cache/
+compile_commands.json
+sift/
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/.vscode/launch.json b/packages/leann-backend-hnsw/third_party/faiss/.vscode/launch.json
new file mode 100644
index 0000000..d6087f1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/.vscode/launch.json
@@ -0,0 +1,19 @@
+{
+ // Use IntelliSense to learn about possible attributes.
+ // Hover to view descriptions of existing attributes.
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Build Demo",
+ "type": "lldb",
+ "request": "launch",
+ "program": "${workspaceFolder}/../.venv/bin/python",
+ "console": "integratedTerminal",
+ "cwd": "${workspaceFolder}",
+ "args": [
+ "${workspaceFolder}/demo/build_demo.py"
+ ],
+ },
+ ]
+}
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/CHANGELOG.md b/packages/leann-backend-hnsw/third_party/faiss/CHANGELOG.md
new file mode 100644
index 0000000..c1771f2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/CHANGELOG.md
@@ -0,0 +1,482 @@
+# Changelog
+All notable changes to this project will be documented in this file.
+
+## [Unreleased]
+
+## [1.10.0] - 2025-01-30
+
+
+Added
+- Add desc_name to dataset descriptor (#3935)
+- implement ST_norm_from_LUT for the ResidualQuantizer (#3917)
+- Add example of how to build, link, and test an external SWIG module (#3922)
+- add copyright header (#3948)
+- Add some SVE implementations (#3933)
+- Enable linting: lint config changes plus arc lint command (#3966)
+- Re-add example of how to build, link, and test an external SWIG module (#3981)
+- demo: IndexPQ: separate codes from codebook (#3987)
+- add all wrapped indexes to the index_read (#3988)
+- add validity check AlignedTableTightAlloc clear method (#3997)
+- Add index binary to telemetry (#4001)
+- Add VectorTransform read from filename to the C API (#3970)
+- Added IndexLSH to the demo (#4009)
+- write distributed_kmeans centroids and assignments to hive tables (#4017)
+- introduce data splits in dataset descriptor (#4012)
+- Faiss GPU: bfloat16 brute-force kNN support (#4018)
+- ROCm support for bfloat16 (#4039)
+- Unit tests for distances_simd.cpp (#4058)
+- add cuda-toolkit for GPU (#4057)
+- Add more unit testing for IndexHNSW [1/n] (#4054)
+- Add more unit testing for IndexHNSW [2/n] (#4056)
+- Add more unit testing for HNSW [3/n] (#4059)
+- Add more unit testing for HNSW [4/n] (#4061)
+- Add more unit tests for index_read and index_write (#4068)
+- Add testing for utils/hamming.cpp (#4079)
+- Test sa_decode methd on IndexIVFFlat (#4098)
+- Conditionally compile extras like benchmarks and demos (#4094)
+- Add a new architecture mode: 'avx512_spr'. (#4025)
+- Use _mm512_popcnt_epi64 to speedup hamming distance evaluation. (#4020)
+- PQ with pytorch (#4116)
+- add range_search() to IndexRefine (#4022)
+- Expose accumulate_to_mem from faiss interface (#4099)
+- Windows Arm64 support (#4087)
+- add test to cover GPU (#4130)
+- Added support for building without MKL (#4147)
+
+Changed
+- Move train, build and search to their respective operators (#3934)
+- PQFS into Index trainer (#3941)
+- Place a useful cmake function 'link_to_faiss_lib' into a separate file (#3939)
+- Cache device major version value to avoid multiple calls of getCudaDeviceProperties (#3950)
+- Consolidate set_target_properties() calls in faiss/CMakeLists.txt (#3973)
+- Removing Manual Hipify Build Step (#3962)
+- Allow to replace graph structure for NSG graphs (#3975)
+- Adjust nightly build (#3978)
+- Update RAFT CI with pytorch 2.4.1 (#3980)
+- Moved add_sa_codes, sa_code_size to Index, IndexBinary base classes (#3989)
+- Update autoclose.yml (#4000)
+- Migrate from RAFT to CUVS (#3549)
+- Pin to numpy<2 (#4033)
+- (1/n) - Preload datasets in manifold so that subsequent stages of training, indexing and search can use those instead of each trainer or indexer downloading data. (#4034)
+- Constrain conda version for Windows build (#4040)
+- Updates to faiss-gpu-cuvs nightly pkg (#4032)
+- pin the dependecies version for x86_64 (#4046)
+- pin arm64 dependency (#4060)
+- Pin conda build (#4062)
+- Improve naming due to codemod (#4063)
+- Improve naming due to codemod (#4064)
+- Improve naming due to codemod (#4065)
+- separare the github build into two conditions (#4066)
+- Improve naming due to codemod (#4070)
+- improve naming due to codemod (#4067)
+- improve naming due to codemod (#4071)
+- improve naming due to codemod (#4072)
+- fix nightily build (#4080)
+- Change github action workflows name (#4083)
+- Resolve Packaging Issues (#4044)
+- Update __init__.py (#4086)
+- Exhaustive IVF probing in scalar quantizer tests (#4075)
+- Pin Nightlies with testing on PR (#4088)
+- Update benchmarking library code to work for IdMap index as well (#4093)
+- Update action.yml (#4100)
+- Upgrade CUVS to 24.12 (#4021)
+- Link cuVS Docs (#4084)
+- Set KnnDescriptor.desc_name in the Benchmarking core framework in FAISS like other descriptors (#4109)
+- enable quiet mode for conda install (#4112)
+- Disable retry build (#4124)
+- Add ngpu default argument to knn_ground_truth (#4123)
+- Update code comment to reflect the range of IF from [1, k] (#4139)
+- Reenable auto retry workflow (#4140)
+- Migration off defaults to conda-forge channel (#4126)
+- Benchmarking Scripts for cuVS Index, more docs updates (#4117)
+
+Fixed
+- Fix total_rows (#3942)
+- Fix INSTALL.md due to failure of conflict resolving (#3915)
+- Back out "Add example of how to build, link, and test an external SWIG module" (#3954)
+- Fix shadowed variable in faiss/IndexPQ.cpp (#3959)
+- Fix shadowed variable in faiss/IndexIVFAdditiveQuantizer.cpp (#3958)
+- Fix shadowed variable in faiss/impl/HNSW.cpp (#3961)
+- Fix shadowed variable in faiss/impl/simd_result_handlers.h (#3960)
+- Fix shadowed variable in faiss/utils/NeuralNet.cpp (#3952)
+- Resolve "incorrect-portions-license" errors: add no license lint to top of GPU files with both licenses (#3965)
+- Resolve "duplicate-license-header": Find and replace duplicate license headers (#3967)
+- fix some more nvidia licenses that get erased (#3977)
+- fix merge_flat_ondisk stress run failures (#3999)
+- Fix reverse_index_factory formatting of ScalarQuantizers (#4003)
+- Fix shadowed variable in faiss/IndexAdditiveQuantizer.cpp (#4011)
+- facebook-unused-include-check in fbcode/faiss (#4029)
+- fix linter (#4035)
+- Some chore fixes (#4010)
+- Fix unused variable compilation error (#4041)
+- stop dealloc of coarse quantizer when it is deleted (#4045)
+- Fix SCD Table test flakiness (#4069)
+- Fix IndexIVFFastScan reconstruct_from_offset method (#4095)
+- more fast-scan reconstruction (#4128)
+- Fix nightly cuVS 11.8.0 failure (#4149)
+- Correct capitalization of FAISS to Faiss (#4155)
+- Fix cuVS 12.4.0 nightly failure (#4153)
+
+Deprecated
+- Remove unused-variable in dumbo/backup/dumbo/service/tests/ChainReplicatorTests.cpp (#4024)
+- remove inconsistent oom exception test (#4052)
+- Remove unused(and wrong) io macro (#4122)
+
+
+## [1.9.0] - 2024-10-04
+### Added
+- Add AVX-512 implementation for the distance and scalar quantizer functions. (#3853)
+- Allow k and M suffixes in IVF indexes (#3812)
+- add reconstruct support to additive quantizers (#3752)
+- introduce options for reducing the overhead for a clustering procedure (#3731)
+- Add hnsw search params for bounded queue option (#3748)
+- ROCm support (#3462)
+- Add sve targets (#2886)
+- add get_version() for c_api (#3688)
+- QINCo implementation in CPU Faiss (#3608)
+- Add search functionality to FlatCodes (#3611)
+- add dispatcher for VectorDistance and ResultHandlers (#3627)
+- Add SQ8bit signed quantization (#3501)
+- Add ABS_INNER_PRODUCT metric (#3524)
+- Interop between CAGRA and HNSW (#3252)
+- add skip_storage flag to HNSW (#3487)
+- QT_bf16 for scalar quantizer for bfloat16 (#3444)
+- Implement METRIC.NaNEuclidean (#3414)
+- TimeoutCallback C++ and Python (#3417)
+- support big-endian machines (#3361)
+- Support for Remove ids from IVFPQFastScan index (#3354)
+- Implement reconstruct_n for GPU IVFFlat indexes (#3338)
+- Support of skip_ids in merge_from_multiple function of OnDiskInvertedLists (#3327)
+- Add the ability to clone and read binary indexes to the C API. (#3318)
+- AVX512 for PQFastScan (#3276)
+
+### Changed
+- faster hnsw CPU index training (#3822)
+- Some small improvements. (#3692)
+- First attempt at LSH matching with nbits (#3679)
+- Set verbosoe before train (#3619)
+- Remove duplicate NegativeDistanceComputer instances (#3450)
+- interrupt for NNDescent (#3432)
+- Get rid of redundant instructions in ScalarQuantizer (#3430)
+- PowerPC, improve code generation for function fvec_L2sqr (#3416)
+- Unroll loop in lookup_2_lanes (#3364)
+- Improve filtering & search parameters propagation (#3304)
+- Change index_cpu_to_gpu to throw for indices not implemented on GPU (#3336)
+- Throw when attempting to move IndexPQ to GPU (#3328)
+- Skip HNSWPQ sdc init with new io flag (#3250)
+
+### Fixed
+- FIx a bug for a non-simdlib code of ResidualQuantizer (#3868)
+- assign_index should default to null (#3855)
+- Fix an incorrectly counted the number of computed distances for HNSW (#3840)
+- Add error for overflowing nbits during PQ construction (#3833)
+- Fix radius search with HSNW and IP (#3698)
+- fix algorithm of spreading vectors over shards (#3374)
+- Fix IndexBinary.assign Python method (#3384)
+- Few fixes in bench_fw to enable IndexFromCodec (#3383)
+- Fix the endianness issue in AIX while running the benchmark. (#3345)
+- Fix faiss swig build with version > 4.2.x (#3315)
+- Fix problems when using 64-bit integers. (#3322)
+- Fix IVFPQFastScan decode function (#3312)
+- Handling FaissException in few destructors of ResultHandler.h (#3311)
+- Fix HNSW stats (#3309)
+- AIX compilation fix for io classes (#3275)
+
+
+## [1.8.0] - 2024-02-27
+### Added
+- Added a new conda package faiss-gpu-raft alongside faiss-cpu and faiss-gpu
+- Integrated IVF-Flat and IVF-PQ implementations in faiss-gpu-raft from RAFT by Nvidia [thanks Corey Nolet and Tarang Jain]
+- Added a context parameter to InvertedLists and InvertedListsIterator
+- Added Faiss on Rocksdb demo to showing how inverted lists can be persisted in a key-value store
+- Introduced Offline IVF framework powered by Faiss big batch search
+- Added SIMD NEON Optimization for QT_FP16 in Scalar Quantizer. [thanks Naveen Tatikonda]
+- Generalized ResultHandler and supported range search for HNSW and FastScan
+- Introduced avx512 optimization mode and FAISS_OPT_LEVEL env variable [thanks Alexandr Ghuzva]
+- Added search parameters for IndexRefine::search() and IndexRefineFlat::search()
+- Supported large two-level clustering
+- Added support for Python 3.11 and 3.12
+- Added support for CUDA 12
+
+### Changed
+- Used the benchmark to find Pareto optimal indices. Intentionally limited to IVF(Flat|HNSW),PQ|SQ indices
+- Splitted off RQ encoding steps to another file
+- Supported better NaN handling
+- HNSW speedup + Distance 4 points [thanks Alexandr Ghuzva]
+
+### Fixed
+- Fixed DeviceVector reallocations in Faiss GPU
+- Used efSearch from params if provided in HNSW search
+- Fixed warp synchronous behavior in Faiss GPU CUDA 12
+
+
+## [1.7.4] - 2023-04-12
+### Added
+- Added big batch IVF search for conducting efficient search with big batches of queries
+- Checkpointing in big batch search support
+- Precomputed centroids support
+- Support for iterable inverted lists for eg. key value stores
+- 64-bit indexing arithmetic support in FAISS GPU
+- IndexIVFShards now handle IVF indexes with a common quantizer
+- Jaccard distance support
+- CodePacker for non-contiguous code layouts
+- Approximate evaluation of top-k distances for ResidualQuantizer and IndexBinaryFlat
+- Added support for 12-bit PQ / IVFPQ fine quantizer decoders for standalone vector codecs (faiss/cppcontrib)
+- Conda packages for osx-arm64 (Apple M1) and linux-aarch64 (ARM64) architectures
+- Support for Python 3.10
+
+### Removed
+- CUDA 10 is no longer supported in precompiled packages
+- Removed Python 3.7 support for precompiled packages
+- Removed constraint for using fine quantizer with no greater than 8 bits for IVFPQ, for example, now it is possible to use IVF256,PQ10x12 for a CPU index
+
+### Changed
+- Various performance optimizations for PQ / IVFPQ for AVX2 and ARM for training (fused distance+nearest kernel), search (faster kernels for distance_to_code() and scan_list_*()) and vector encoding
+- A magnitude faster CPU code for LSQ/PLSQ training and vector encoding (reworked code)
+- Performance improvements for Hamming Code computations for AVX2 and ARM (reworked code)
+- Improved auto-vectorization support for IP and L2 distance computations (better handling of pragmas)
+- Improved ResidualQuantizer vector encoding (pooling memory allocations, avoid r/w to a temporary buffer)
+
+### Fixed
+- HSNW bug fixed which improves the recall rate! Special thanks to zh Wang @hhy3 for this.
+- Faiss GPU IVF large query batch fix
+- Faiss + Torch fixes, re-enable k = 2048
+- Fix the number of distance computations to match max_codes parameter
+- Fix decoding of large fast_scan blocks
+
+
+## [1.7.3] - 2022-11-3
+### Added
+- Added sparse k-means routines and moved the generic kmeans to contrib
+- Added FlatDistanceComputer for all FlatCodes indexes
+- Support for fast accumulation of 4-bit LSQ and RQ
+- Added product additive quantization
+- Support per-query search parameters for many indexes + filtering by ids
+- write_VectorTransform and read_vectorTransform were added to the public API (by @AbdelrahmanElmeniawy)
+- Support for IDMap2 in index_factory by adding "IDMap2" to prefix or suffix of the input String (by @AbdelrahmanElmeniawy)
+- Support for merging all IndexFlatCodes descendants (by @AbdelrahmanElmeniawy)
+- Remove and merge features for IndexFastScan (by @AbdelrahmanElmeniawy)
+- Performance improvements: 1) specialized the AVX2 pieces of code speeding up certain hotspots, 2) specialized kernels for vector codecs (this can be found in faiss/cppcontrib)
+
+
+### Fixed
+- Fixed memory leak in OnDiskInvertedLists::do_mmap when the file is not closed (by @AbdelrahmanElmeniawy)
+- LSH correctly throws error for metric types other than METRIC_L2 (by @AbdelrahmanElmeniawy)
+
+## [1.7.2] - 2021-12-15
+### Added
+- Support LSQ on GPU (by @KinglittleQ)
+- Support for exact 1D kmeans (by @KinglittleQ)
+
+## [1.7.1] - 2021-05-27
+### Added
+- Support for building C bindings through the `FAISS_ENABLE_C_API` CMake option.
+- Serializing the indexes with the python pickle module
+- Support for the NNDescent k-NN graph building method (by @KinglittleQ)
+- Support for the NSG graph indexing method (by @KinglittleQ)
+- Residual quantizers: support as codec and unoptimized search
+- Support for 4-bit PQ implementation for ARM (by @vorj, @n-miyamoto-fixstars, @LWisteria, and @matsui528)
+- Implementation of Local Search Quantization (by @KinglittleQ)
+
+### Changed
+- The order of xb an xq was different between `faiss.knn` and `faiss.knn_gpu`.
+Also the metric argument was called distance_type.
+- The typed vectors (LongVector, LongLongVector, etc.) of the SWIG interface have
+been deprecated. They have been replaced with Int32Vector, Int64Vector, etc. (by h-vetinari)
+
+### Fixed
+- Fixed a bug causing kNN search functions for IndexBinaryHash and
+IndexBinaryMultiHash to return results in a random order.
+- Copy constructor of AlignedTable had a bug leading to crashes when cloning
+IVFPQ indices.
+
+## [1.7.0] - 2021-01-27
+
+## [1.6.5] - 2020-11-22
+
+## [1.6.4] - 2020-10-12
+### Added
+- Arbitrary dimensions per sub-quantizer now allowed for `GpuIndexIVFPQ`.
+- Brute-force kNN on GPU (`bfKnn`) now accepts `int32` indices.
+- Nightly conda builds now available (for CPU).
+- Faiss is now supported on Windows.
+
+## [1.6.3] - 2020-03-24
+### Added
+- Support alternative distances on GPU for GpuIndexFlat, including L1, Linf and
+Lp metrics.
+- Support METRIC_INNER_PRODUCT for GpuIndexIVFPQ.
+- Support float16 coarse quantizer for GpuIndexIVFFlat and GpuIndexIVFPQ. GPU
+Tensor Core operations (mixed-precision arithmetic) are enabled on supported
+hardware when operating with float16 data.
+- Support k-means clustering with encoded vectors. This makes it possible to
+train on larger datasets without decompressing them in RAM, and is especially
+useful for binary datasets (see https://github.com/facebookresearch/faiss/blob/main/tests/test_build_blocks.py#L92).
+- Support weighted k-means. Weights can be associated to each training point
+(see https://github.com/facebookresearch/faiss/blob/main/tests/test_build_blocks.py).
+- Serialize callback in python, to write to pipes or sockets (see
+https://github.com/facebookresearch/faiss/wiki/Index-IO,-cloning-and-hyper-parameter-tuning).
+- Reconstruct arbitrary ids from IndexIVF + efficient remove of a small number
+of ids. This avoids 2 inefficiencies: O(ntotal) removal of vectors and
+IndexIDMap2 on top of indexIVF. Documentation here:
+https://github.com/facebookresearch/faiss/wiki/Special-operations-on-indexes.
+- Support inner product as a metric in IndexHNSW (see
+https://github.com/facebookresearch/faiss/blob/main/tests/test_index.py#L490).
+- Support PQ of sizes other than 8 bit in IndexIVFPQ.
+- Demo on how to perform searches sequentially on an IVF index. This is useful
+for an OnDisk index with a very large batch of queries. In that case, it is
+worthwhile to scan the index sequentially (see
+https://github.com/facebookresearch/faiss/blob/main/tests/test_ivflib.py#L62).
+- Range search support for most binary indexes.
+- Support for hashing-based binary indexes (see
+https://github.com/facebookresearch/faiss/wiki/Binary-indexes).
+
+### Changed
+- Replaced obj table in Clustering object: now it is a ClusteringIterationStats
+structure that contains additional statistics.
+
+### Removed
+- Removed support for useFloat16Accumulator for accumulators on GPU (all
+accumulations are now done in float32, regardless of whether float16 or float32
+input data is used).
+
+### Fixed
+- Some python3 fixes in benchmarks.
+- Fixed GpuCloner (some fields were not copied, default to no precomputed tables
+with IndexIVFPQ).
+- Fixed support for new pytorch versions.
+- Serialization bug with alternative distances.
+- Removed test on multiple-of-4 dimensions when switching between blas and AVX
+implementations.
+
+## [1.6.2] - 2020-03-10
+
+## [1.6.1] - 2019-12-04
+
+## [1.6.0] - 2019-09-24
+### Added
+- Faiss as a codec: We introduce a new API within Faiss to encode fixed-size
+vectors into fixed-size codes. The encoding is lossy and the tradeoff between
+compression and reconstruction accuracy can be adjusted.
+- ScalarQuantizer support for GPU, see gpu/GpuIndexIVFScalarQuantizer.h. This is
+particularly useful as GPU memory is often less abundant than CPU.
+- Added easy-to-use serialization functions for indexes to byte arrays in Python
+(faiss.serialize_index, faiss.deserialize_index).
+- The Python KMeans object can be used to use the GPU directly, just add
+gpu=True to the constuctor see gpu/test/test_gpu_index.py test TestGPUKmeans.
+
+### Changed
+- Change in the code layout: many C++ sources are now in subdirectories impl/
+and utils/.
+
+## [1.5.3] - 2019-06-24
+### Added
+- Basic support for 6 new metrics in CPU IndexFlat and IndexHNSW (https://github.com/facebookresearch/faiss/issues/848).
+- Support for IndexIDMap/IndexIDMap2 with binary indexes (https://github.com/facebookresearch/faiss/issues/780).
+
+### Changed
+- Throw python exception for OOM (https://github.com/facebookresearch/faiss/issues/758).
+- Make DistanceComputer available for all random access indexes.
+- Gradually moving from long to uint64_t for portability.
+
+### Fixed
+- Slow scanning of inverted lists (https://github.com/facebookresearch/faiss/issues/836).
+
+## [1.5.2] - 2019-05-28
+### Added
+- Support for searching several inverted lists in parallel (parallel_mode != 0).
+- Better support for PQ codes where nbit != 8 or 16.
+- IVFSpectralHash implementation: spectral hash codes inside an IVF.
+- 6-bit per component scalar quantizer (4 and 8 bit were already supported).
+- Combinations of inverted lists: HStackInvertedLists and VStackInvertedLists.
+- Configurable number of threads for OnDiskInvertedLists prefetching (including
+0=no prefetch).
+- More test and demo code compatible with Python 3 (print with parentheses).
+
+### Changed
+- License was changed from BSD+Patents to MIT.
+- Exceptions raised in sub-indexes of IndexShards and IndexReplicas are now
+propagated.
+- Refactored benchmark code: data loading is now in a single file.
+
+## [1.5.1] - 2019-04-05
+### Added
+- MatrixStats object, which reports useful statistics about a dataset.
+- Option to round coordinates during k-means optimization.
+- An alternative option for search in HNSW.
+- Support for range search in IVFScalarQuantizer.
+- Support for direct uint_8 codec in ScalarQuantizer.
+- Better support for PQ code assignment with external index.
+- Support for IMI2x16 (4B virtual centroids).
+- Support for k = 2048 search on GPU (instead of 1024).
+- Support for renaming an ondisk invertedlists.
+- Support for nterrupting computations with interrupt signal (ctrl-C) in python.
+- Simplified build system (with --with-cuda/--with-cuda-arch options).
+
+### Changed
+- Moved stats() and imbalance_factor() from IndexIVF to InvertedLists object.
+- Renamed IndexProxy to IndexReplicas.
+- Most CUDA mem alloc failures now throw exceptions instead of terminating on an
+assertion.
+- Updated example Dockerfile.
+- Conda packages now depend on the cudatoolkit packages, which fixes some
+interferences with pytorch. Consequentially, faiss-gpu should now be installed
+by conda install -c pytorch faiss-gpu cudatoolkit=10.0.
+
+## [1.5.0] - 2018-12-19
+### Added
+- New GpuIndexBinaryFlat index.
+- New IndexBinaryHNSW index.
+
+## [1.4.0] - 2018-08-30
+### Added
+- Automatic tracking of C++ references in Python.
+- Support for non-intel platforms, some functions optimized for ARM.
+- Support for overriding nprobe for concurrent searches.
+- Support for floating-point quantizers in binary indices.
+
+### Fixed
+- No more segfaults due to Python's GC.
+- GpuIndexIVFFlat issues for float32 with 64 / 128 dims.
+- Sharding of flat indexes on GPU with index_cpu_to_gpu_multiple.
+
+## [1.3.0] - 2018-07-10
+### Added
+- Support for binary indexes (IndexBinaryFlat, IndexBinaryIVF).
+- Support fp16 encoding in scalar quantizer.
+- Support for deduplication in IndexIVFFlat.
+- Support for index serialization.
+
+### Fixed
+- MMAP bug for normal indices.
+- Propagation of io_flags in read func.
+- k-selection for CUDA 9.
+- Race condition in OnDiskInvertedLists.
+
+## [1.2.1] - 2018-02-28
+### Added
+- Support for on-disk storage of IndexIVF data.
+- C bindings.
+- Extended tutorial to GPU indices.
+
+[Unreleased]: https://github.com/facebookresearch/faiss/compare/v1.9.0...HEAD
+[1.9.0]: https://github.com/facebookresearch/faiss/compare/v1.8.0...v1.9.0
+[1.8.0]: https://github.com/facebookresearch/faiss/compare/v1.7.4...v1.8.0
+[1.7.4]: https://github.com/facebookresearch/faiss/compare/v1.7.3...v1.7.4
+[1.7.3]: https://github.com/facebookresearch/faiss/compare/v1.7.2...v1.7.3
+[1.7.2]: https://github.com/facebookresearch/faiss/compare/v1.7.1...v1.7.2
+[1.7.1]: https://github.com/facebookresearch/faiss/compare/v1.7.0...v1.7.1
+[1.7.0]: https://github.com/facebookresearch/faiss/compare/v1.6.5...v1.7.0
+[1.6.5]: https://github.com/facebookresearch/faiss/compare/v1.6.4...v1.6.5
+[1.6.4]: https://github.com/facebookresearch/faiss/compare/v1.6.3...v1.6.4
+[1.6.3]: https://github.com/facebookresearch/faiss/compare/v1.6.2...v1.6.3
+[1.6.2]: https://github.com/facebookresearch/faiss/compare/v1.6.1...v1.6.2
+[1.6.1]: https://github.com/facebookresearch/faiss/compare/v1.6.0...v1.6.1
+[1.6.0]: https://github.com/facebookresearch/faiss/compare/v1.5.3...v1.6.0
+[1.5.3]: https://github.com/facebookresearch/faiss/compare/v1.5.2...v1.5.3
+[1.5.2]: https://github.com/facebookresearch/faiss/compare/v1.5.1...v1.5.2
+[1.5.1]: https://github.com/facebookresearch/faiss/compare/v1.5.0...v1.5.1
+[1.5.0]: https://github.com/facebookresearch/faiss/compare/v1.4.0...v1.5.0
+[1.4.0]: https://github.com/facebookresearch/faiss/compare/v1.3.0...v1.4.0
+[1.3.0]: https://github.com/facebookresearch/faiss/compare/v1.2.1...v1.3.0
+[1.2.1]: https://github.com/facebookresearch/faiss/releases/tag/v1.2.1
diff --git a/packages/leann-backend-hnsw/third_party/faiss/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/CMakeLists.txt
new file mode 100644
index 0000000..4a70aaf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/CMakeLists.txt
@@ -0,0 +1,126 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# =============================================================================
+# Copyright (c) 2023-2024, NVIDIA CORPORATION.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+# in compliance with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software distributed under the License
+# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+# or implied. See the License for the specific language governing permissions and limitations under
+# the License.
+# =============================================================================
+
+cmake_minimum_required(VERSION 3.24.0 FATAL_ERROR)
+
+set(FAISS_LANGUAGES CXX)
+
+if(FAISS_ENABLE_GPU)
+ if (FAISS_ENABLE_ROCM)
+ list(APPEND FAISS_LANGUAGES HIP)
+ list(PREPEND CMAKE_MODULE_PATH "/opt/rocm/lib/cmake")
+ list(PREPEND CMAKE_PREFIX_PATH "/opt/rocm")
+ else()
+ list(APPEND FAISS_LANGUAGES CUDA)
+ endif()
+endif()
+
+if(FAISS_ENABLE_CUVS)
+include(cmake/thirdparty/fetch_rapids.cmake)
+include(rapids-cmake)
+include(rapids-cpm)
+include(rapids-cuda)
+include(rapids-export)
+include(rapids-find)
+
+rapids_cuda_init_architectures(faiss)
+rapids_cuda_init_architectures(pyfaiss)
+rapids_cuda_init_architectures(faiss_c_library)
+endif()
+
+project(faiss
+ VERSION 1.10.0
+ DESCRIPTION "A library for efficient similarity search and clustering of dense vectors."
+ HOMEPAGE_URL "https://github.com/facebookresearch/faiss"
+ LANGUAGES ${FAISS_LANGUAGES})
+include(GNUInstallDirs)
+
+set(CMAKE_CXX_STANDARD 17)
+
+list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
+
+# Valid values are "generic", "avx2", "avx512", "avx512_spr", "sve".
+option(FAISS_OPT_LEVEL "" "generic")
+option(FAISS_ENABLE_GPU "Enable support for GPU indexes." ON)
+option(FAISS_ENABLE_CUVS "Enable cuVS for GPU indexes." OFF)
+option(FAISS_ENABLE_ROCM "Enable ROCm for GPU indexes." OFF)
+option(FAISS_ENABLE_MKL "Enable MKL." ON)
+option(FAISS_ENABLE_PYTHON "Build Python extension." ON)
+option(FAISS_ENABLE_C_API "Build C API." OFF)
+option(FAISS_ENABLE_EXTRAS "Build extras like benchmarks and demos" ON)
+option(FAISS_USE_LTO "Enable Link-Time optimization" OFF)
+
+if(FAISS_ENABLE_GPU)
+ if(FAISS_ENABLE_ROCM)
+ enable_language(HIP)
+ add_definitions(-DUSE_AMD_ROCM)
+ find_package(HIP REQUIRED)
+ find_package(hipBLAS REQUIRED)
+ set(GPU_EXT_PREFIX "hip")
+ execute_process(COMMAND ${PROJECT_SOURCE_DIR}/faiss/gpu/hipify.sh)
+ else ()
+ set(CMAKE_CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
+ enable_language(CUDA)
+ set(GPU_EXT_PREFIX "cu")
+ endif()
+endif()
+
+if(FAISS_ENABLE_CUVS AND NOT TARGET cuvs::cuvs)
+ find_package(cuvs)
+ endif()
+
+add_subdirectory(faiss)
+
+if(FAISS_ENABLE_GPU)
+ if(FAISS_ENABLE_ROCM)
+ add_subdirectory(faiss/gpu-rocm)
+ else()
+ add_subdirectory(faiss/gpu)
+ endif()
+endif()
+
+if(FAISS_ENABLE_PYTHON)
+ add_subdirectory(faiss/python)
+endif()
+
+if(FAISS_ENABLE_C_API)
+ add_subdirectory(c_api)
+endif()
+
+if(FAISS_ENABLE_EXTRAS)
+ add_subdirectory(demos)
+ add_subdirectory(benchs)
+ add_subdirectory(tutorial/cpp)
+endif()
+
+# CTest must be included in the top level to enable `make test` target.
+include(CTest)
+if(BUILD_TESTING)
+ add_subdirectory(tests)
+ add_subdirectory(perf_tests)
+ if(FAISS_ENABLE_GPU)
+ if(FAISS_ENABLE_ROCM)
+ add_subdirectory(faiss/gpu-rocm/test)
+ else()
+ add_subdirectory(faiss/gpu/test)
+ endif()
+ endif()
+endif()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/CODE_OF_CONDUCT.md b/packages/leann-backend-hnsw/third_party/faiss/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..ac27d8a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/CODE_OF_CONDUCT.md
@@ -0,0 +1,2 @@
+# Code of Conduct
+Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/CONTRIBUTING.md b/packages/leann-backend-hnsw/third_party/faiss/CONTRIBUTING.md
new file mode 100644
index 0000000..10fc815
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/CONTRIBUTING.md
@@ -0,0 +1,52 @@
+# Contributing to Faiss
+
+We want to make contributing to this project as easy and transparent as
+possible.
+
+## Our Development Process
+
+We mainly develop Faiss within Facebook. Sometimes, we will sync the
+github version of Faiss with the internal state.
+
+## Pull Requests
+
+We welcome pull requests that add significant value to Faiss. If you plan to do
+a major development and contribute it back to Faiss, please contact us first before
+putting too much effort into it.
+
+1. Fork the repo and create your branch from `main`.
+2. If you've added code that should be tested, add tests.
+3. If you've changed APIs, update the documentation.
+4. Ensure the test suite passes.
+5. Make sure your code lints.
+6. If you haven't already, complete the Contributor License Agreement ("CLA").
+
+There is a Facebook internal test suite for Faiss, and we need to run
+all changes to Faiss through it.
+
+## Contributor License Agreement ("CLA")
+
+In order to accept your pull request, we need you to submit a CLA. You only need
+to do this once to work on any of Facebook's open source projects.
+
+Complete your CLA here: <https://code.facebook.com/cla>
+
+## Issues
+
+We use GitHub issues to track public bugs. Please ensure your description is
+clear and has sufficient instructions to be able to reproduce the issue.
+
+Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
+disclosure of security bugs. In those cases, please go through the process
+outlined on that page and do not file a public issue.
+
+## Coding Style
+
+* 4 spaces for indentation in C++ (no tabs)
+* 80 character line length (both for C++ and Python)
+* C++ language level: C++17
+
+## License
+
+By contributing to Faiss, you agree that your contributions will be licensed
+under the LICENSE file in the root directory of this source tree.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/Doxyfile b/packages/leann-backend-hnsw/third_party/faiss/Doxyfile
new file mode 100644
index 0000000..3a112d0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/Doxyfile
@@ -0,0 +1,2282 @@
+
+
+# Doxyfile 1.8.5
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME = "Faiss"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER =
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF =
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
+# the documentation. The maximum height of the logo should not exceed 55 pixels
+# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
+# to the output directory.
+
+PROJECT_LOGO =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY =
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
+
+CREATE_SUBDIRS = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-
+# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi,
+# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en,
+# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish,
+# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish,
+# Turkish, Ukrainian and Vietnamese.
+# The default value is: English.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+# The default value is: YES.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
+
+ABBREVIATE_BRIEF =
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# doxygen will generate a detailed section even if there is only a brief
+# description.
+# The default value is: NO.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+# The default value is: NO.
+
+INLINE_INHERITED_MEMB = YES
+
+# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
+
+FULL_PATH_NAMES = YES
+
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
+
+STRIP_FROM_PATH =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
+
+JAVADOC_AUTOBRIEF = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
+
+QT_AUTOBRIEF = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
+# new page for each member. If set to NO, the documentation of a member will be
+# part of the file/class/namespace that contains it.
+# The default value is: NO.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE = 4
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
+
+ALIASES =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_FOR_C = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_JAVA = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
+# (default is Fortran), use: inc=Fortran f=C.
+#
+# Note For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT = YES
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by by putting a % sign in front of the word
+# or globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
+
+BUILTIN_STL_SUPPORT = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+# The default value is: NO.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
+
+IDL_PROPERTY_SUPPORT = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+# The default value is: NO.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
+
+SUBGROUPING = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
+
+TYPEDEF_HIDES_STRUCT = NO
+
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PRIVATE = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
+
+EXTRACT_STATIC = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
+
+EXTRACT_LOCAL_CLASSES = NO
+
+# This flag is only useful for Objective-C code. When set to YES local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO only methods in the interface are
+# included.
+# The default value is: NO.
+
+EXTRACT_LOCAL_METHODS = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO these classes will be included in the various overviews. This option has
+# no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO these declarations will be
+# included in the documentation.
+# The default value is: NO.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
+
+CASE_SENSE_NAMES = YES
+
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES the
+# scope will be hidden.
+# The default value is: NO.
+
+HIDE_SCOPE_NAMES = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: YES.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: NO.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
+
+SORT_BY_SCOPE_NAME = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING = NO
+
+# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
+# todo list. This list is created by putting \todo commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
+# test list. This list is created by putting \test commands in the
+# documentation.
+# The default value is: YES.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES the list
+# will mention the files that were used to generate the documentation.
+# The default value is: YES.
+
+SHOW_USED_FILES = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
+
+LAYOUT_FILE =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. Do not use file names with spaces, bibtex cannot handle them. See
+# also \cite for info how to create references.
+
+CITE_BIB_FILES =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
+
+QUIET = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
+
+WARNINGS = YES
+
+# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
+
+WARN_IF_UNDOCUMENTED = YES
+
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
+
+WARN_IF_DOC_ERROR = YES
+
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO doxygen will only warn about wrong or incomplete parameter
+# documentation, but not about the absence of documentation.
+# The default value is: NO.
+
+WARN_NO_PARAMDOC = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
+
+WARN_FORMAT = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces.
+# Note: If this tag is empty the current directory is searched.
+
+INPUT = ./faiss
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank the
+# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
+# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
+# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
+# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
+# *.qsf, *.as and *.js.
+
+FILE_PATTERNS = *.h *.cuh
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
+
+RECURSIVE = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE = gpu/test
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+# The default value is: NO.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
+
+EXCLUDE_PATTERNS =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
+
+EXAMPLE_PATH =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
+
+EXAMPLE_RECURSIVE = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
+
+INPUT_FILTER =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER ) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
+
+FILTER_SOURCE_FILES = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
+
+SOURCE_BROWSER = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
+
+STRIP_CODE_COMMENTS = NO
+
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
+
+REFERENCES_RELATION = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
+
+VERBATIM_HEADERS = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
+
+ALPHABETICAL_INDEX = YES
+
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+COLS_IN_ALPHA_INDEX = 5
+
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
+
+IGNORE_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
+# The default value is: YES.
+
+GENERATE_HTML = NO
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
+# standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_HEADER =
+
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_FOOTER =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_STYLESHEET =
+
+# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user-
+# defined cascading style sheet that is included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefor more robust against future updates.
+# Doxygen will copy the style sheet file to the output directory. For an example
+# see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the stylesheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP = NO
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_DOCSET = NO
+
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_HTMLHELP = NO
+
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
+# written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_FILE =
+
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler ( hhc.exe). If non-empty
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+HHC_LOCATION =
+
+# The GENERATE_CHI flag controls if a separate .chi index file is generated (
+# YES) or that it should be included in the master .chm file ( NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+GENERATE_CHI = NO
+
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+CHM_INDEX_ENCODING =
+
+# The BINARY_TOC flag controls whether a binary table of contents is generated (
+# YES) or a normal table of contents ( NO) in the .chm file.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_SECT_FILTER_ATTRS =
+
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHG_LOCATION =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+DISABLE_INDEX = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+ENUM_VALUES_PER_LINE = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+TREEVIEW_WIDTH = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_FONTSIZE = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using prerendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+SEARCHENGINE = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavours of web server based searching depending on the
+# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for
+# searching and an index file used by the script. When EXTERNAL_SEARCH is
+# enabled the indexing and searching needs to be provided by external tools. See
+# the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
+# The default value is: YES.
+
+GENERATE_LATEX = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. To get the times font for
+# instance you can specify
+# EXTRA_PACKAGES=times
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber. Doxygen will
+# replace them by respectively the title of the page, the current date and time,
+# only the current date, the version number of doxygen, the project name (see
+# PROJECT_NAME), or the project number (see PROJECT_NUMBER).
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HEADER =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PDF_HYPERLINKS = YES
+
+# If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES to get a
+# higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BATCHMODE = NO
+
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_HIDE_INDICES = NO
+
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_SOURCE_CODE = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE = plain
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_OUTPUT = rtf
+
+# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_HYPERLINKS = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_OUTPUT = man
+
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
+
+GENERATE_XML = YES
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify a XML schema, which can be used by a
+# validating XML parser to check the syntax of the XML files.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify a XML DTD, which can be used by a
+# validating XML parser to check the syntax of the XML files.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT = docbook
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
+# Definitions (see http://autogen.sf.net) file that captures the structure of
+# the code including all documentation. Note that this feature is still
+# experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
+# in the source code. If set to NO only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+MACRO_EXPANSION = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_ONLY_PREDEF = NO
+
+# If the SEARCH_INCLUDES tag is set to YES the includes files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
+
+INCLUDE_PATH =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+PREDEFINED =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all refrences to function-like macros that are alone on a line, have an
+# all uppercase name, and do not end with a semicolon. Such function macros are
+# typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have an unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
+# class index. If set to NO only the inherited external classes will be listed.
+# The default value is: NO.
+
+ALLEXTERNALS = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
+# the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS = YES
+
+# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
+# be listed.
+# The default value is: YES.
+
+EXTERNAL_PAGES = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
+
+PERL_PATH = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
+# powerful graphs.
+# The default value is: YES.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
+
+HIDE_UNDOC_RELATIONS = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: NO.
+
+HAVE_DOT = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS = 0
+
+# When you want a differently looking font n the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK = NO
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+TEMPLATE_RELATIONS = NO
+
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDE_GRAPH = YES
+
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot.
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, jpg, gif and svg.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_IMAGE_FORMAT = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_PATH =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOTFILE_DIRS =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_TRANSPARENT = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_MULTI_TARGETS = NO
+
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_CLEANUP = YES
diff --git a/packages/leann-backend-hnsw/third_party/faiss/INSTALL.md b/packages/leann-backend-hnsw/third_party/faiss/INSTALL.md
new file mode 100644
index 0000000..ca491a6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/INSTALL.md
@@ -0,0 +1,325 @@
+# Installing Faiss via conda
+
+The supported way to install Faiss is through [conda](https://docs.conda.io).
+Stable releases are pushed regularly to the pytorch conda channel, as well as
+pre-release nightly builds.
+
+- The CPU-only faiss-cpu conda package is currently available on Linux (x86-64 and aarch64), OSX (arm64 only), and Windows (x86-64)
+- faiss-gpu, containing both CPU and GPU indices, is available on Linux (x86-64 only) for CUDA 11.4 and 12.1
+- faiss-gpu-cuvs [^1] package containing GPU indices provided by [NVIDIA cuVS](https://github.com/rapidsai/cuvs/) version 24.12, is available on Linux (x86-64 only) for CUDA 11.8 and 12.4.
+
+To install the latest stable release:
+
+``` shell
+# CPU-only version
+$ conda install -c pytorch faiss-cpu=1.10.0
+
+# GPU(+CPU) version
+$ conda install -c pytorch -c nvidia faiss-gpu=1.10.0
+
+# GPU(+CPU) version with NVIDIA cuVS
+$ conda install -c pytorch -c nvidia -c rapidsai -c conda-forge libnvjitlink faiss-gpu-cuvs=1.10.0
+
+# GPU(+CPU) version using AMD ROCm not yet available
+```
+
+For faiss-gpu, the nvidia channel is required for CUDA, which is not published in the main anaconda channel.
+
+For faiss-gpu-cuvs, the rapidsai, conda-forge and nvidia channels are required.
+
+Nightly pre-release packages can be installed as follows:
+
+``` shell
+# CPU-only version
+$ conda install -c pytorch/label/nightly faiss-cpu
+
+# GPU(+CPU) version
+$ conda install -c pytorch/label/nightly -c nvidia faiss-gpu=1.10.0
+
+# GPU(+CPU) version with NVIDIA cuVS (package built with CUDA 12.4)
+conda install -c pytorch -c rapidsai -c conda-forge -c nvidia pytorch/label/nightly::faiss-gpu-cuvs 'cuda-version>=12.0,<=12.5'
+
+# GPU(+CPU) version with NVIDIA cuVS (package built with CUDA 11.8)
+conda install -c pytorch -c rapidsai -c conda-forge -c nvidia pytorch/label/nightly::faiss-gpu-cuvs 'cuda-version>=11.4,<=11.8'
+
+# GPU(+CPU) version using AMD ROCm not yet available
+```
+In the above commands, pytorch-cuda=11 or pytorch-cuda=12 would select a specific CUDA version, if it’s required.
+
+A combination of versions that installs GPU Faiss with CUDA and Pytorch (as of 2024-05-15):
+```
+conda create --name faiss_1.8.0
+conda activate faiss_1.8.0
+conda install -c pytorch -c nvidia faiss-gpu=1.8.0 pytorch=*=*cuda* pytorch-cuda=11 numpy
+```
+
+## Installing from conda-forge
+
+Faiss is also being packaged by [conda-forge](https://conda-forge.org/), the
+community-driven packaging ecosystem for conda. The packaging effort is
+collaborating with the Faiss team to ensure high-quality package builds.
+
+Due to the comprehensive infrastructure of conda-forge, it may even happen that
+certain build combinations are supported in conda-forge that are not available
+through the pytorch channel. To install, use
+
+``` shell
+# CPU version
+$ conda install -c conda-forge faiss-cpu
+
+# GPU version
+$ conda install -c conda-forge faiss-gpu
+
+# NVIDIA cuVS and AMD ROCm version not yet available
+```
+
+You can tell which channel your conda packages come from by using `conda list`.
+If you are having problems using a package built by conda-forge, please raise
+an [issue](https://github.com/conda-forge/faiss-split-feedstock/issues) on the
+conda-forge package "feedstock".
+
+# Building from source
+
+Faiss can be built from source using CMake.
+
+Faiss is supported on x86-64 machines on Linux, OSX, and Windows. It has been
+found to run on other platforms as well, see
+[other platforms](https://github.com/facebookresearch/faiss/wiki/Related-projects#bindings-to-other-languages-and-porting-to-other-platforms).
+
+The basic requirements are:
+- a C++17 compiler (with support for OpenMP support version 2 or higher),
+- a BLAS implementation (on Intel machines we strongly recommend using Intel MKL for best
+performance).
+
+The optional requirements are:
+- for GPU indices:
+ - nvcc,
+ - the CUDA toolkit,
+- for AMD GPUs:
+ - AMD ROCm,
+- for using NVIDIA cuVS implementations:
+ - libcuvs=24.12
+- for the python bindings:
+ - python 3,
+ - numpy,
+ - and swig.
+
+Indications for specific configurations are available in the [troubleshooting
+section of the wiki](https://github.com/facebookresearch/faiss/wiki/Troubleshooting).
+
+### Building with NVIDIA cuVS
+
+[cuVS](https://docs.rapids.ai/api/cuvs/nightly/) contains state-of-the-art implementations of several algorithms for running approximate nearest neighbors and clustering on the GPU. It is built on top of the [RAPIDS RAFT](https://github.com/rapidsai/raft) library of high performance machine learning primitives. Building Faiss with cuVS enabled allows a user to choose between regular GPU implementations in Faiss and cuVS implementations for specific algorithms.
+
+The libcuvs dependency should be installed via conda:
+1. With CUDA 12.0 - 12.5:
+```
+conda install -c rapidsai -c conda-forge -c nvidia libcuvs=24.12 'cuda-version>=12.0,<=12.5'
+```
+2. With CUDA 11.4 - 11.8
+```
+conda install -c rapidsai -c conda-forge -c nvidia libcuvs=24.12 'cuda-version>=11.4,<=11.8'
+```
+For more ways to install cuVS 24.12, refer to the [RAPIDS Installation Guide](https://docs.rapids.ai/install).
+
+## Step 1: invoking CMake
+
+``` shell
+$ cmake -B build .
+```
+
+This generates the system-dependent configuration/build files in the `build/`
+subdirectory.
+
+Several options can be passed to CMake, among which:
+- general options:
+ - `-DFAISS_ENABLE_GPU=OFF` in order to disable building GPU indices (possible
+ values are `ON` and `OFF`),
+ - `-DFAISS_ENABLE_PYTHON=OFF` in order to disable building python bindings
+ (possible values are `ON` and `OFF`),
+ - `-DFAISS_ENABLE_CUVS=ON` in order to use the NVIDIA cuVS implementations
+ of the IVF-Flat, IVF-PQ and [CAGRA](https://arxiv.org/pdf/2308.15136) GPU-accelerated indices (default is `OFF`, possible, values are `ON` and `OFF`).
+ Note: `-DFAISS_ENABLE_GPU` must be set to `ON` when enabling this option.
+ - `-DBUILD_TESTING=OFF` in order to disable building C++ tests,
+ - `-DBUILD_SHARED_LIBS=ON` in order to build a shared library (possible values
+ are `ON` and `OFF`),
+ - `-DFAISS_ENABLE_C_API=ON` in order to enable building [C API](c_api/INSTALL.md) (possible values
+ are `ON` and `OFF`),
+- optimization-related options:
+ - `-DCMAKE_BUILD_TYPE=Release` in order to enable generic compiler
+ optimization options (enables `-O3` on gcc for instance),
+ - `-DFAISS_OPT_LEVEL=avx2` in order to enable the required compiler flags to
+ generate code using optimized SIMD/Vector instructions. Possible values are below:
+ - On x86-64, `generic`, `avx2`, 'avx512', and `avx512_spr` (for avx512 features available since Intel(R) Sapphire Rapids), by increasing order of optimization,
+ - On aarch64, `generic` and `sve`, by increasing order of optimization,
+ - `-DFAISS_USE_LTO=ON` in order to enable [Link-Time Optimization](https://en.wikipedia.org/wiki/Link-time_optimization) (default is `OFF`, possible values are `ON` and `OFF`).
+- BLAS-related options:
+ - `-DBLA_VENDOR=Intel10_64_dyn -DMKL_LIBRARIES=/path/to/mkl/libs` to use the
+ Intel MKL BLAS implementation, which is significantly faster than OpenBLAS
+ (more information about the values for the `BLA_VENDOR` option can be found in
+ the [CMake docs](https://cmake.org/cmake/help/latest/module/FindBLAS.html)),
+- GPU-related options:
+ - `-DCUDAToolkit_ROOT=/path/to/cuda-10.1` in order to hint to the path of
+ the CUDA toolkit (for more information, see
+ [CMake docs](https://cmake.org/cmake/help/latest/module/FindCUDAToolkit.html)),
+ - `-DCMAKE_CUDA_ARCHITECTURES="75;72"` for specifying which GPU architectures
+ to build against (see [CUDA docs](https://developer.nvidia.com/cuda-gpus) to
+ determine which architecture(s) you should pick),
+ - `-DFAISS_ENABLE_ROCM=ON` in order to enable building GPU indices for AMD GPUs.
+ `-DFAISS_ENABLE_GPU` must be `ON` when using this option. (possible values are `ON` and `OFF`),
+- python-related options:
+ - `-DPython_EXECUTABLE=/path/to/python3.7` in order to build a python
+ interface for a different python than the default one (see
+ [CMake docs](https://cmake.org/cmake/help/latest/module/FindPython.html)).
+
+## Step 2: Invoking Make
+
+``` shell
+$ make -C build -j faiss
+```
+
+This builds the C++ library (`libfaiss.a` by default, and `libfaiss.so` if
+`-DBUILD_SHARED_LIBS=ON` was passed to CMake).
+
+The `-j` option enables parallel compilation of multiple units, leading to a
+faster build, but increasing the chances of running out of memory, in which case
+it is recommended to set the `-j` option to a fixed value (such as `-j4`).
+
+If making use of optimization options, build the correct target before swigfaiss.
+
+For AVX2:
+
+``` shell
+$ make -C build -j faiss_avx2
+```
+
+For AVX512:
+
+``` shell
+$ make -C build -j faiss_avx512
+```
+
+For AVX512 features available since Intel(R) Sapphire Rapids.
+
+``` shell
+$ make -C build -j faiss_avx512_spr
+```
+
+This will ensure the creation of neccesary files when building and installing the python package.
+
+## Step 3: Building the python bindings (optional)
+
+``` shell
+$ make -C build -j swigfaiss
+$ (cd build/faiss/python && python setup.py install)
+```
+
+The first command builds the python bindings for Faiss, while the second one
+generates and installs the python package.
+
+
+## Step 4: Installing the C++ library and headers (optional)
+
+``` shell
+$ make -C build install
+```
+
+This will make the compiled library (either `libfaiss.a` or `libfaiss.so` on
+Linux) available system-wide, as well as the C++ headers. This step is not
+needed to install the python package only.
+
+
+## Step 5: Testing (optional)
+
+### Running the C++ test suite
+
+To run the whole test suite, make sure that `cmake` was invoked with
+`-DBUILD_TESTING=ON`, and run:
+
+``` shell
+$ make -C build test
+```
+
+### Running the python test suite
+
+``` shell
+$ (cd build/faiss/python && python setup.py build)
+$ PYTHONPATH="$(ls -d ./build/faiss/python/build/lib*/)" pytest tests/test_*.py
+```
+
+### Basic example
+
+A basic usage example is available in
+[`demos/demo_ivfpq_indexing.cpp`](https://github.com/facebookresearch/faiss/blob/main/demos/demo_ivfpq_indexing.cpp).
+
+It creates a small index, stores it and performs some searches. A normal runtime
+is around 20s. With a fast machine and Intel MKL's BLAS it runs in 2.5s.
+
+It can be built with
+``` shell
+$ make -C build demo_ivfpq_indexing
+```
+and subsequently ran with
+``` shell
+$ ./build/demos/demo_ivfpq_indexing
+```
+
+### Basic GPU example
+
+``` shell
+$ make -C build demo_ivfpq_indexing_gpu
+$ ./build/demos/demo_ivfpq_indexing_gpu
+```
+
+This produce the GPU code equivalent to the CPU `demo_ivfpq_indexing`. It also
+shows how to translate indexes from/to a GPU.
+
+### A real-life benchmark
+
+A longer example runs and evaluates Faiss on the SIFT1M dataset. To run it,
+please download the ANN_SIFT1M dataset from http://corpus-texmex.irisa.fr/
+and unzip it to the subdirectory `sift1M` at the root of the source
+directory for this repository.
+
+Then compile and run the following (after ensuring you have installed faiss):
+
+``` shell
+$ make -C build demo_sift1M
+$ ./build/demos/demo_sift1M
+```
+
+This is a demonstration of the high-level auto-tuning API. You can try
+setting a different index_key to find the indexing structure that
+gives the best performance.
+
+### Real-life test
+
+The following script extends the demo_sift1M test to several types of
+indexes. This must be run from the root of the source directory for this
+repository:
+
+``` shell
+$ mkdir tmp # graphs of the output will be written here
+$ python demos/demo_auto_tune.py
+```
+
+It will cycle through a few types of indexes and find optimal
+operating points. You can play around with the types of indexes.
+
+### Real-life test on GPU
+
+The example above also runs on GPU. Edit `demos/demo_auto_tune.py` at line 100
+with the values
+
+``` python
+keys_to_test = keys_gpu
+use_gpu = True
+```
+
+and you can run
+``` shell
+$ python demos/demo_auto_tune.py
+```
+to test the GPU code.
+
+[^1]: The vector search and clustering algorithms in NVIDIA RAFT have been formally migrated to [NVIDIA cuVS](https://github.com/rapidsai/cuvs). This package is being renamed to `faiss-gpu-cuvs` in the next stable release, which will use these GPU implementations from the pre-compiled `libcuvs=24.12` binary.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/LICENSE b/packages/leann-backend-hnsw/third_party/faiss/LICENSE
new file mode 100644
index 0000000..b96dcb0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) Facebook, Inc. and its affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/README.md b/packages/leann-backend-hnsw/third_party/faiss/README.md
new file mode 100644
index 0000000..1a6949a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/README.md
@@ -0,0 +1,92 @@
+# Faiss
+
+Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning. Faiss is written in C++ with complete wrappers for Python/numpy. Some of the most useful algorithms are implemented on the GPU. It is developed primarily at Meta's [Fundamental AI Research](https://ai.facebook.com/) group.
+
+## News
+
+See [CHANGELOG.md](CHANGELOG.md) for detailed information about latest features.
+
+## Introduction
+
+Faiss contains several methods for similarity search. It assumes that the instances are represented as vectors and are identified by an integer, and that the vectors can be compared with L2 (Euclidean) distances or dot products. Vectors that are similar to a query vector are those that have the lowest L2 distance or the highest dot product with the query vector. It also supports cosine similarity, since this is a dot product on normalized vectors.
+
+Some of the methods, like those based on binary vectors and compact quantization codes, solely use a compressed representation of the vectors and do not require to keep the original vectors. This generally comes at the cost of a less precise search but these methods can scale to billions of vectors in main memory on a single server. Other methods, like HNSW and NSG add an indexing structure on top of the raw vectors to make searching more efficient.
+
+The GPU implementation can accept input from either CPU or GPU memory. On a server with GPUs, the GPU indexes can be used a drop-in replacement for the CPU indexes (e.g., replace `IndexFlatL2` with `GpuIndexFlatL2`) and copies to/from GPU memory are handled automatically. Results will be faster however if both input and output remain resident on the GPU. Both single and multi-GPU usage is supported.
+
+## Installing
+
+Faiss comes with precompiled libraries for Anaconda in Python, see [faiss-cpu](https://anaconda.org/pytorch/faiss-cpu), [faiss-gpu](https://anaconda.org/pytorch/faiss-gpu) and [faiss-gpu-cuvs](https://anaconda.org/pytorch/faiss-gpu-cuvs). The library is mostly implemented in C++, the only dependency is a [BLAS](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) implementation. Optional GPU support is provided via CUDA or AMD ROCm, and the Python interface is also optional. The backend GPU implementations of NVIDIA [cuVS](https://github.com/rapidsai/cuvs) can also be enabled optionally. It compiles with cmake. See [INSTALL.md](INSTALL.md) for details.
+
+## How Faiss works
+
+Faiss is built around an index type that stores a set of vectors, and provides a function to search in them with L2 and/or dot product vector comparison. Some index types are simple baselines, such as exact search. Most of the available indexing structures correspond to various trade-offs with respect to
+
+- search time
+- search quality
+- memory used per index vector
+- training time
+- adding time
+- need for external data for unsupervised training
+
+The optional GPU implementation provides what is likely (as of March 2017) the fastest exact and approximate (compressed-domain) nearest neighbor search implementation for high-dimensional vectors, fastest Lloyd's k-means, and fastest small k-selection algorithm known. [The implementation is detailed here](https://arxiv.org/abs/1702.08734).
+
+## Full documentation of Faiss
+
+The following are entry points for documentation:
+
+- the full documentation can be found on the [wiki page](http://github.com/facebookresearch/faiss/wiki), including a [tutorial](https://github.com/facebookresearch/faiss/wiki/Getting-started), a [FAQ](https://github.com/facebookresearch/faiss/wiki/FAQ) and a [troubleshooting section](https://github.com/facebookresearch/faiss/wiki/Troubleshooting)
+- the [doxygen documentation](https://faiss.ai/) gives per-class information extracted from code comments
+- to reproduce results from our research papers, [Polysemous codes](https://arxiv.org/abs/1609.01882) and [Billion-scale similarity search with GPUs](https://arxiv.org/abs/1702.08734), refer to the [benchmarks README](benchs/README.md). For [
+Link and code: Fast indexing with graphs and compact regression codes](https://arxiv.org/abs/1804.09996), see the [link_and_code README](benchs/link_and_code)
+
+## Authors
+
+The main authors of Faiss are:
+- [Hervé Jégou](https://github.com/jegou) initiated the Faiss project and wrote its first implementation
+- [Matthijs Douze](https://github.com/mdouze) implemented most of the CPU Faiss
+- [Jeff Johnson](https://github.com/wickedfoo) implemented all of the GPU Faiss
+- [Lucas Hosseini](https://github.com/beauby) implemented the binary indexes and the build system
+- [Chengqi Deng](https://github.com/KinglittleQ) implemented NSG, NNdescent and much of the additive quantization code.
+- [Alexandr Guzhva](https://github.com/alexanderguzhva) many optimizations: SIMD, memory allocation and layout, fast decoding kernels for vector codecs, etc.
+- [Gergely Szilvasy](https://github.com/algoriddle) build system, benchmarking framework.
+
+## Reference
+
+References to cite when you use Faiss in a research paper:
+```
+@article{douze2024faiss,
+ title={The Faiss library},
+ author={Matthijs Douze and Alexandr Guzhva and Chengqi Deng and Jeff Johnson and Gergely Szilvasy and Pierre-Emmanuel Mazaré and Maria Lomeli and Lucas Hosseini and Hervé Jégou},
+ year={2024},
+ eprint={2401.08281},
+ archivePrefix={arXiv},
+ primaryClass={cs.LG}
+}
+```
+For the GPU version of Faiss, please cite:
+```
+@article{johnson2019billion,
+ title={Billion-scale similarity search with {GPUs}},
+ author={Johnson, Jeff and Douze, Matthijs and J{\'e}gou, Herv{\'e}},
+ journal={IEEE Transactions on Big Data},
+ volume={7},
+ number={3},
+ pages={535--547},
+ year={2019},
+ publisher={IEEE}
+}
+```
+
+## Join the Faiss community
+
+For public discussion of Faiss or for questions, visit https://github.com/facebookresearch/faiss/discussions.
+
+We monitor the [issues page](http://github.com/facebookresearch/faiss/issues) of the repository.
+You can report bugs, ask questions, etc.
+
+## Legal
+
+Faiss is MIT-licensed, refer to the [LICENSE file](https://github.com/facebookresearch/faiss/blob/main/LICENSE) in the top level directory.
+
+Copyright © Meta Platforms, Inc.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/benchs/CMakeLists.txt
new file mode 100644
index 0000000..27bbb22
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/CMakeLists.txt
@@ -0,0 +1,10 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+
+add_executable(bench_ivf_selector EXCLUDE_FROM_ALL bench_ivf_selector.cpp)
+target_link_libraries(bench_ivf_selector PRIVATE faiss)
+
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/README.md b/packages/leann-backend-hnsw/third_party/faiss/benchs/README.md
new file mode 100644
index 0000000..2f38697
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/README.md
@@ -0,0 +1,361 @@
+
+# Benchmarking scripts
+
+This directory contains benchmarking scripts that can reproduce the
+numbers reported in the two papers
+
+```
+@inproceedings{DJP16,
+ Author = {Douze, Matthijs and J{\'e}gou, Herv{\'e} and Perronnin, Florent},
+ Booktitle = "ECCV",
+ Organization = {Springer},
+ Title = {Polysemous codes},
+ Year = {2016}
+}
+```
+and
+
+```
+@inproceedings{JDJ17,
+ Author = {Jeff Johnson and Matthijs Douze and Herv{\'e} J{\'e}gou},
+ journal= {arXiv:1702.08734},,
+ Title = {Billion-scale similarity search with GPUs},
+ Year = {2017},
+}
+```
+
+Note that the numbers (especially timings) change slightly due to changes in the implementation, different machines, etc.
+
+The scripts are self-contained. They depend only on Faiss and external training data that should be stored in sub-directories.
+
+## SIFT1M experiments
+
+The script [`bench_polysemous_sift1m.py`](bench_polysemous_sift1m.py) reproduces the numbers in
+Figure 3 from the "Polysemous" paper.
+
+### Getting SIFT1M
+
+To run it, please download the ANN_SIFT1M dataset from
+
+http://corpus-texmex.irisa.fr/
+
+and unzip it to the subdirectory sift1M.
+
+### Result
+
+The output looks like:
+
+```
+PQ training on 100000 points, remains 0 points: training polysemous on centroids
+add vectors to index
+PQ baseline 7.517 ms per query, R@1 0.4474
+Polysemous 64 9.875 ms per query, R@1 0.4474
+Polysemous 62 8.358 ms per query, R@1 0.4474
+Polysemous 58 5.531 ms per query, R@1 0.4474
+Polysemous 54 3.420 ms per query, R@1 0.4478
+Polysemous 50 2.182 ms per query, R@1 0.4475
+Polysemous 46 1.621 ms per query, R@1 0.4408
+Polysemous 42 1.448 ms per query, R@1 0.4174
+Polysemous 38 1.331 ms per query, R@1 0.3563
+Polysemous 34 1.334 ms per query, R@1 0.2661
+Polysemous 30 1.272 ms per query, R@1 0.1794
+```
+
+
+## Experiments on 1B elements dataset
+
+The script [`bench_polysemous_1bn.py`](bench_polysemous_1bn.py) reproduces a few experiments on
+two datasets of size 1B from the Polysemous codes" paper.
+
+
+### Getting BIGANN
+
+Download the four files of ANN_SIFT1B from
+http://corpus-texmex.irisa.fr/ to subdirectory bigann/
+
+### Getting Deep1B
+
+The ground-truth and queries are available here
+
+https://yadi.sk/d/11eDCm7Dsn9GA
+
+For the learning and database vectors, use the script
+
+https://github.com/arbabenko/GNOIMI/blob/master/downloadDeep1B.py
+
+to download the data to subdirectory deep1b/, then concatenate the
+database files to base.fvecs and the training files to learn.fvecs
+
+### Running the experiments
+
+These experiments are quite long. To support resuming, the script
+stores the result of training to a temporary directory, `/tmp/bench_polysemous`.
+
+The script `bench_polysemous_1bn.py` takes at least two arguments:
+
+- the dataset name: SIFT1000M (aka SIFT1B, aka BIGANN) or Deep1B. SIFT1M, SIFT2M,... are also supported to make subsets of for small experiments (note that SIFT1M as a subset of SIFT1B is not the same as the SIFT1M above)
+
+- the type of index to build, which should be a valid [index_factory key](https://github.com/facebookresearch/faiss/wiki/High-level-interface-and-auto-tuning#index-factory) (see below for examples)
+
+- the remaining arguments are parsed as search-time parameters.
+
+### Experiments of Table 2
+
+The `IMI*+PolyD+ADC` results in Table 2 can be reproduced with (for 16 bytes):
+
+```
+python bench_polysemous_1bn.par SIFT1000M IMI2x12,PQ16 nprobe=16,max_codes={10000,30000},ht={44..54}
+```
+
+Training takes about 2 minutes and adding vectors to the dataset
+takes 3.1 h. These operations are multithreaded. Note that in the command
+above, we use bash's [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) to set a grid of parameters.
+
+The search is *not* multithreaded, and the output looks like:
+
+```
+ R@1 R@10 R@100 time %pass
+nprobe=16,max_codes=10000,ht=44 0.1779 0.2994 0.3139 0.194 12.45
+nprobe=16,max_codes=10000,ht=45 0.1859 0.3183 0.3339 0.197 14.24
+nprobe=16,max_codes=10000,ht=46 0.1930 0.3366 0.3543 0.202 16.22
+nprobe=16,max_codes=10000,ht=47 0.1993 0.3550 0.3745 0.209 18.39
+nprobe=16,max_codes=10000,ht=48 0.2033 0.3694 0.3917 0.640 20.77
+nprobe=16,max_codes=10000,ht=49 0.2070 0.3839 0.4077 0.229 23.36
+nprobe=16,max_codes=10000,ht=50 0.2101 0.3949 0.4205 0.232 26.17
+nprobe=16,max_codes=10000,ht=51 0.2120 0.4042 0.4310 0.239 29.21
+nprobe=16,max_codes=10000,ht=52 0.2134 0.4113 0.4402 0.245 32.47
+nprobe=16,max_codes=10000,ht=53 0.2157 0.4184 0.4482 0.250 35.96
+nprobe=16,max_codes=10000,ht=54 0.2170 0.4240 0.4546 0.256 39.66
+nprobe=16,max_codes=30000,ht=44 0.1882 0.3327 0.3555 0.226 11.29
+nprobe=16,max_codes=30000,ht=45 0.1964 0.3525 0.3771 0.231 13.05
+nprobe=16,max_codes=30000,ht=46 0.2039 0.3713 0.3987 0.236 15.01
+nprobe=16,max_codes=30000,ht=47 0.2103 0.3907 0.4202 0.245 17.19
+nprobe=16,max_codes=30000,ht=48 0.2145 0.4055 0.4384 0.251 19.60
+nprobe=16,max_codes=30000,ht=49 0.2179 0.4198 0.4550 0.257 22.25
+nprobe=16,max_codes=30000,ht=50 0.2208 0.4305 0.4681 0.268 25.15
+nprobe=16,max_codes=30000,ht=51 0.2227 0.4402 0.4791 0.275 28.30
+nprobe=16,max_codes=30000,ht=52 0.2241 0.4473 0.4884 0.284 31.70
+nprobe=16,max_codes=30000,ht=53 0.2265 0.4544 0.4965 0.294 35.34
+nprobe=16,max_codes=30000,ht=54 0.2278 0.4601 0.5031 0.303 39.20
+```
+
+The result reported in table 2 is the one for which the %pass (percentage of code comparisons that pass the Hamming check) is around 20%, which occurs for Hamming threshold `ht=48`.
+
+The 8-byte results can be reproduced with the factory key `IMI2x12,PQ8`
+
+### Experiments of the appendix
+
+The experiments in the appendix are only in the ArXiv version of the paper (table 3).
+
+```
+python bench_polysemous_1bn.py SIFT1000M OPQ8_64,IMI2x13,PQ8 nprobe={1,2,4,8,16,32,64,128},ht={20,24,26,28,30}
+
+ R@1 R@10 R@100 time %pass
+nprobe=1,ht=20 0.0351 0.0616 0.0751 0.158 19.01
+...
+nprobe=32,ht=28 0.1256 0.3563 0.5026 0.561 52.61
+...
+```
+Here again the runs are not exactly the same but the original result was obtained from nprobe=32,ht=28.
+
+For Deep1B, we used a simple version of [auto-tuning](https://github.com/facebookresearch/faiss/wiki/High-level-interface-and-auto-tuning/_edit#auto-tuning-the-runtime-parameters) to sweep through the set of operating points:
+
+```
+python bench_polysemous_1bn.py Deep1B OPQ20_80,IMI2x14,PQ20 autotune
+...
+Done in 4067.555 s, available OPs:
+Parameters 1-R@1 time
+ 0.0000 0.000
+nprobe=1,ht=22,max_codes=256 0.0215 3.115
+nprobe=1,ht=30,max_codes=256 0.0381 3.120
+...
+nprobe=512,ht=68,max_codes=524288 0.4478 36.903
+nprobe=1024,ht=80,max_codes=131072 0.4557 46.363
+nprobe=1024,ht=78,max_codes=262144 0.4616 61.939
+...
+```
+The original results were obtained with `nprobe=1024,ht=66,max_codes=262144`.
+
+
+## GPU experiments
+
+The benchmarks below run 1 or 4 Titan X GPUs and reproduce the results of the "GPU paper". They are also a good starting point on how to use GPU Faiss.
+
+### Search on SIFT1M
+
+See above on how to get SIFT1M into subdirectory sift1M/. The script [`bench_gpu_sift1m.py`](bench_gpu_sift1m.py) reproduces the "exact k-NN time" plot in the ArXiv paper, and the SIFT1M numbers.
+
+The output is:
+```
+============ Exact search
+add vectors to index
+warmup
+benchmark
+k=1 0.715 s, R@1 0.9914
+k=2 0.729 s, R@1 0.9935
+k=4 0.731 s, R@1 0.9935
+k=8 0.732 s, R@1 0.9935
+k=16 0.742 s, R@1 0.9935
+k=32 0.737 s, R@1 0.9935
+k=64 0.753 s, R@1 0.9935
+k=128 0.761 s, R@1 0.9935
+k=256 0.799 s, R@1 0.9935
+k=512 0.975 s, R@1 0.9935
+k=1024 1.424 s, R@1 0.9935
+============ Approximate search
+train
+WARNING clustering 100000 points to 4096 centroids: please provide at least 159744 training points
+add vectors to index
+WARN: increase temp memory to avoid cudaMalloc, or decrease query/add size (alloc 256000000 B, highwater 256000000 B)
+warmup
+benchmark
+nprobe= 1 0.043 s recalls= 0.3909 0.4312 0.4312
+nprobe= 2 0.040 s recalls= 0.5041 0.5636 0.5636
+nprobe= 4 0.048 s recalls= 0.6048 0.6897 0.6897
+nprobe= 8 0.064 s recalls= 0.6879 0.8028 0.8028
+nprobe= 16 0.088 s recalls= 0.7534 0.8940 0.8940
+nprobe= 32 0.134 s recalls= 0.7957 0.9549 0.9550
+nprobe= 64 0.224 s recalls= 0.8125 0.9833 0.9834
+nprobe= 128 0.395 s recalls= 0.8205 0.9953 0.9954
+nprobe= 256 0.717 s recalls= 0.8227 0.9993 0.9994
+nprobe= 512 1.348 s recalls= 0.8228 0.9999 1.0000
+```
+The run produces two warnings:
+
+- the clustering complains that it does not have enough training data, there is not much we can do about this.
+
+- the add() function complains that there is an inefficient memory allocation, but this is a concern only when it happens often, and we are not benchmarking the add time anyways.
+
+To index small datasets, it is more efficient to use a `GpuIVFFlat`, which just stores the full vectors in the inverted lists. We did not mention this in the the paper because it is not as scalable. To experiment with this setting, change the `index_factory` string from "IVF4096,PQ64" to "IVF16384,Flat". This gives:
+
+```
+nprobe= 1 0.025 s recalls= 0.4084 0.4105 0.4105
+nprobe= 2 0.033 s recalls= 0.5235 0.5264 0.5264
+nprobe= 4 0.033 s recalls= 0.6332 0.6367 0.6367
+nprobe= 8 0.040 s recalls= 0.7358 0.7403 0.7403
+nprobe= 16 0.049 s recalls= 0.8273 0.8324 0.8324
+nprobe= 32 0.068 s recalls= 0.8957 0.9024 0.9024
+nprobe= 64 0.104 s recalls= 0.9477 0.9549 0.9549
+nprobe= 128 0.174 s recalls= 0.9760 0.9837 0.9837
+nprobe= 256 0.299 s recalls= 0.9866 0.9944 0.9944
+nprobe= 512 0.527 s recalls= 0.9907 0.9987 0.9987
+```
+
+### Clustering on MNIST8m
+
+To get the "infinite MNIST dataset", follow the instructions on [Léon Bottou's website](http://leon.bottou.org/projects/infimnist). The script assumes the file `mnist8m-patterns-idx3-ubyte` is in subdirectory `mnist8m`
+
+The script [`kmeans_mnist.py`](kmeans_mnist.py) produces the following output:
+
+```
+python kmeans_mnist.py 1 256
+...
+Clustering 8100000 points in 784D to 256 clusters, redo 1 times, 20 iterations
+ Preprocessing in 7.94526 s
+ Iteration 19 (131.697 s, search 114.78 s): objective=1.44881e+13 imbalance=1.05963 nsplit=0
+final objective: 1.449e+13
+total runtime: 140.615 s
+```
+
+### search on SIFT1B
+
+The script [`bench_gpu_1bn.py`](bench_gpu_1bn.py) runs multi-gpu searches on the two 1-billion vector datasets we considered. It is more complex than the previous scripts, because it supports many search options and decomposes the dataset build process in Python to exploit the best possible CPU/GPU parallelism and GPU distribution.
+
+Even on multiple GPUs, building the 1B datasets can last several hours. It is often a good idea to validate that everything is working fine on smaller datasets like SIFT1M, SIFT2M, etc.
+
+The search results on SIFT1B in the "GPU paper" can be obtained with
+
+<!-- see P57124181 -->
+
+```
+python bench_gpu_1bn.py SIFT1000M OPQ8_32,IVF262144,PQ8 -nnn 10 -ngpu 1 -tempmem $[1536*1024*1024]
+...
+0/10000 (0.024 s) probe=1 : 0.161 s 1-R@1: 0.0752 1-R@10: 0.1924
+0/10000 (0.005 s) probe=2 : 0.150 s 1-R@1: 0.0964 1-R@10: 0.2693
+0/10000 (0.005 s) probe=4 : 0.153 s 1-R@1: 0.1102 1-R@10: 0.3328
+0/10000 (0.005 s) probe=8 : 0.170 s 1-R@1: 0.1220 1-R@10: 0.3827
+0/10000 (0.005 s) probe=16 : 0.196 s 1-R@1: 0.1290 1-R@10: 0.4151
+0/10000 (0.006 s) probe=32 : 0.244 s 1-R@1: 0.1314 1-R@10: 0.4345
+0/10000 (0.006 s) probe=64 : 0.353 s 1-R@1: 0.1332 1-R@10: 0.4461
+0/10000 (0.005 s) probe=128: 0.587 s 1-R@1: 0.1341 1-R@10: 0.4502
+0/10000 (0.006 s) probe=256: 1.160 s 1-R@1: 0.1342 1-R@10: 0.4511
+```
+
+We use the `-tempmem` option to reduce the temporary memory allocation to 1.5G, otherwise the dataset does not fit in GPU memory
+
+### search on Deep1B
+
+The same script generates the GPU search results on Deep1B.
+
+```
+python bench_gpu_1bn.py Deep1B OPQ20_80,IVF262144,PQ20 -nnn 10 -R 2 -ngpu 4 -altadd -noptables -tempmem $[1024*1024*1024]
+...
+
+0/10000 (0.115 s) probe=1 : 0.239 s 1-R@1: 0.2387 1-R@10: 0.3420
+0/10000 (0.006 s) probe=2 : 0.103 s 1-R@1: 0.3110 1-R@10: 0.4623
+0/10000 (0.005 s) probe=4 : 0.105 s 1-R@1: 0.3772 1-R@10: 0.5862
+0/10000 (0.005 s) probe=8 : 0.116 s 1-R@1: 0.4235 1-R@10: 0.6889
+0/10000 (0.005 s) probe=16 : 0.133 s 1-R@1: 0.4517 1-R@10: 0.7693
+0/10000 (0.005 s) probe=32 : 0.168 s 1-R@1: 0.4713 1-R@10: 0.8281
+0/10000 (0.005 s) probe=64 : 0.238 s 1-R@1: 0.4841 1-R@10: 0.8649
+0/10000 (0.007 s) probe=128: 0.384 s 1-R@1: 0.4900 1-R@10: 0.8816
+0/10000 (0.005 s) probe=256: 0.736 s 1-R@1: 0.4933 1-R@10: 0.8912
+```
+
+Here we are a bit tight on memory so we disable precomputed tables (`-noptables`) and restrict the amount of temporary memory. The `-altadd` option avoids GPU memory overflows during add.
+
+
+### knn-graph on Deep1B
+
+The same script generates the KNN-graph on Deep1B. Note that the inverted file from above will not be re-used because the training sets are different. For the knngraph, the script will first do a pass over the whole dataset to compute the ground-truth knn for a subset of 10k nodes, for evaluation.
+
+```
+python bench_gpu_1bn.py Deep1B OPQ20_80,IVF262144,PQ20 -nnn 10 -altadd -knngraph -R 2 -noptables -tempmem $[1<<30] -ngpu 4
+...
+CPU index contains 1000000000 vectors, move to GPU
+Copy CPU index to 2 sharded GPU indexes
+ dispatch to GPUs 0:2
+IndexShards shard 0 indices 0:500000000
+ IndexIVFPQ size 500000000 -> GpuIndexIVFPQ indicesOptions=0 usePrecomputed=0 useFloat16=0 reserveVecs=0
+IndexShards shard 1 indices 500000000:1000000000
+ IndexIVFPQ size 500000000 -> GpuIndexIVFPQ indicesOptions=0 usePrecomputed=0 useFloat16=0 reserveVecs=0
+ dispatch to GPUs 2:4
+IndexShards shard 0 indices 0:500000000
+ IndexIVFPQ size 500000000 -> GpuIndexIVFPQ indicesOptions=0 usePrecomputed=0 useFloat16=0 reserveVecs=0
+IndexShards shard 1 indices 500000000:1000000000
+ IndexIVFPQ size 500000000 -> GpuIndexIVFPQ indicesOptions=0 usePrecomputed=0 useFloat16=0 reserveVecs=0
+move to GPU done in 151.535 s
+search...
+999997440/1000000000 (8389.961 s, 0.3379) probe=1 : 8389.990 s rank-10 intersection results: 0.3379
+999997440/1000000000 (9205.934 s, 0.4079) probe=2 : 9205.966 s rank-10 intersection results: 0.4079
+999997440/1000000000 (9741.095 s, 0.4722) probe=4 : 9741.128 s rank-10 intersection results: 0.4722
+999997440/1000000000 (10830.420 s, 0.5256) probe=8 : 10830.455 s rank-10 intersection results: 0.5256
+999997440/1000000000 (12531.716 s, 0.5603) probe=16 : 12531.758 s rank-10 intersection results: 0.5603
+999997440/1000000000 (15922.519 s, 0.5825) probe=32 : 15922.571 s rank-10 intersection results: 0.5825
+999997440/1000000000 (22774.153 s, 0.5950) probe=64 : 22774.220 s rank-10 intersection results: 0.5950
+999997440/1000000000 (36717.207 s, 0.6015) probe=128: 36717.309 s rank-10 intersection results: 0.6015
+999997440/1000000000 (70616.392 s, 0.6047) probe=256: 70616.581 s rank-10 intersection results: 0.6047
+```
+
+# Additional benchmarks
+
+This directory also contains certain additional benchmarks (and serve as an additional source of examples of how to use the Faiss code).
+Certain tests / benchmarks might be outdated.
+
+* bench_6bit_codec.cpp - tests vector codecs for SQ6 quantization on a synthetic dataset
+* bench_cppcontrib_sa_decode.cpp - benchmarks specialized kernels for vector codecs for PQ, IVFPQ and Resudial+PQ on a synthetic dataset
+* bench_for_interrupt.py - evaluates the impact of the interrupt callback handler (which can be triggered from Python code)
+* bench_hamming_computer.cpp - specialized implementations for Hamming distance computations
+* bench_heap_replace.cpp - benchmarks different implementations of certain calls for a Heap data structure
+* bench_hnsw.py - benchmarks HNSW in combination with other ones for SIFT1M dataset
+* bench_index_flat.py - benchmarks IndexFlatL2 on a synthetic dataset
+* bench_index_pq.py - benchmarks PQ on SIFT1M dataset
+* bench_ivf_fastscan_single_query.py - benchmarks a single query for different nprobe levels for IVF{nlist},PQ{M}x4fs on BIGANN dataset
+* bench_ivf_fastscan.py - compares IVF{nlist},PQ{M}x4fs against other indices on SIFT1M dataset
+* bench_ivf_selector.cpp - checks the possible overhead when using faiss::IDSelectorAll interface
+* bench_pairwise_distances.py - benchmarks pairwise distance computation between two synthetic datasets
+* bench_partition.py - benchmarks partitioning functions
+* bench_pq_tables.py - benchmarks ProductQuantizer.compute_inner_prod_tables() and ProductQuantizer.compute_distance_tables() calls
+* bench_quantizer.py - benchmarks various quantizers for SIFT1M, Deep1B, BigANN datasets
+* bench_scalar_quantizer.py - benchmarks IVF+SQ on a Sift1M dataset
+* bench_vector_ops.py - benchmarks dot product and distances computations on a synthetic dataset
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_6bit_codec.cpp b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_6bit_codec.cpp
new file mode 100644
index 0000000..94a0d72
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_6bit_codec.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <omp.h>
+#include <cstdio>
+
+#include <benchmark/benchmark.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+using namespace faiss;
+
+static void bench(benchmark::State& state) {
+ int d = 128;
+ int n = 2000;
+ state.SetLabel(faiss::get_compile_options());
+
+ std::vector<float> x(d * n);
+
+ float_rand(x.data(), d * n, 12345);
+
+ // make sure it's idempotent
+ ScalarQuantizer sq(d, ScalarQuantizer::QT_6bit);
+
+ omp_set_num_threads(1);
+
+ sq.train(n, x.data());
+
+ size_t code_size = sq.code_size;
+ state.counters["code_size"] = sq.code_size;
+
+ // encode
+ std::vector<uint8_t> codes(code_size * n);
+ sq.compute_codes(x.data(), codes.data(), n);
+
+ // decode
+ std::vector<float> x2(d * n);
+ sq.decode(codes.data(), x2.data(), n);
+
+ state.counters["sql2_recons_error"] =
+ fvec_L2sqr(x.data(), x2.data(), n * d) / n;
+
+ // encode again
+ std::vector<uint8_t> codes2(code_size * n);
+ sq.compute_codes(x2.data(), codes2.data(), n);
+
+ size_t ndiff = 0;
+ for (size_t i = 0; i < codes.size(); i++) {
+ if (codes[i] != codes2[i])
+ ndiff++;
+ }
+
+ state.counters["ndiff_for_idempotence"] = ndiff;
+
+ state.counters["code_size_two"] = codes.size();
+
+ std::unique_ptr<ScalarQuantizer::SQDistanceComputer> dc(
+ sq.get_distance_computer());
+ dc->codes = codes.data();
+ dc->code_size = sq.code_size;
+ state.counters["code_size_three"] = dc->code_size;
+
+ for (auto _ : state) {
+ float sum_dis = 0;
+ for (int i = 0; i < n; i++) {
+ dc->set_query(&x[i * d]);
+ for (int j = 0; j < n; j++) {
+ benchmark::DoNotOptimize(sum_dis += (*dc)(j));
+ }
+ }
+ }
+}
+// I think maybe n and d should be input arguments
+// for things to really make sense, idk.
+BENCHMARK(bench)->Iterations(20);
+BENCHMARK_MAIN();
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/README.md b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/README.md
new file mode 100644
index 0000000..ea6bbd6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/README.md
@@ -0,0 +1,20 @@
+# Benchmark of IVF variants
+
+This is a benchmark of IVF index variants, looking at compression vs. speed vs. accuracy.
+The results are in [this wiki chapter](https://github.com/facebookresearch/faiss/wiki/Indexing-1G-vectors)
+
+
+The code is organized as:
+
+- `datasets.py`: code to access the datafiles, compute the ground-truth and report accuracies
+
+- `bench_all_ivf.py`: evaluate one type of inverted file
+
+- `run_on_cluster_generic.bash`: call `bench_all_ivf.py` for all tested types of indices.
+Since the number of experiments is quite large the script is structured so that the benchmark can be run on a cluster.
+
+- `parse_bench_all_ivf.py`: make nice tradeoff plots from all the results.
+
+The code depends on Faiss and can use 1 to 8 GPUs to do the k-means clustering for large vocabularies.
+
+It was run in October 2018 for the results in the wiki.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/bench_all_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/bench_all_ivf.py
new file mode 100644
index 0000000..dd1ae2e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/bench_all_ivf.py
@@ -0,0 +1,567 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import os
+import sys
+import time
+import json
+
+import faiss
+import numpy as np
+
+try:
+ import datasets_fb as datasets
+except ModuleNotFoundError:
+ import datasets_oss as datasets
+
+sanitize = datasets.sanitize
+
+
+
+def unwind_index_ivf(index):
+ if isinstance(index, faiss.IndexPreTransform):
+ assert index.chain.size() == 1
+ vt = index.chain.at(0)
+ index_ivf, vt2 = unwind_index_ivf(faiss.downcast_index(index.index))
+ assert vt2 is None
+ if vt is None:
+ vt = lambda x: x
+ else:
+ vt = faiss.downcast_VectorTransform(vt)
+ return index_ivf, vt
+ if hasattr(faiss, "IndexRefine") and isinstance(index, faiss.IndexRefine):
+ return unwind_index_ivf(faiss.downcast_index(index.base_index))
+ if isinstance(index, faiss.IndexIVF):
+ return index, None
+ else:
+ return None, None
+
+
+def apply_AQ_options(index, args):
+ # if not(
+ # isinstance(index, faiss.IndexAdditiveQuantize) or
+ # isinstance(index, faiss.IndexIVFAdditiveQuantizer)):
+ # return
+ if args.RQ_train_default:
+ print("set default training for RQ")
+ index.rq.train_type
+ index.rq.train_type = faiss.ResidualQuantizer.Train_default
+ if args.RQ_beam_size != -1:
+ print("set RQ beam size to", args.RQ_beam_size)
+ index.rq.max_beam_size
+ index.rq.max_beam_size = args.RQ_beam_size
+ if args.LSQ_encode_ils_iters != -1:
+ print("set LSQ ils iterations to", args.LSQ_encode_ils_iters)
+ index.lsq.encode_ils_iters
+ index.lsq.encode_ils_iters = args.LSQ_encode_ils_iters
+ if args.RQ_use_beam_LUT != -1:
+ print("set RQ beam LUT to", args.RQ_use_beam_LUT)
+ index.rq.use_beam_LUT
+ index.rq.use_beam_LUT = args.RQ_use_beam_LUT
+
+
+
+def eval_setting(index, xq, gt, k, inter, min_time):
+ """ evaluate searching in terms of precision vs. speed """
+ nq = xq.shape[0]
+ ivf_stats = faiss.cvar.indexIVF_stats
+ ivf_stats.reset()
+ nrun = 0
+ t0 = time.time()
+ while True:
+ D, I = index.search(xq, k)
+ nrun += 1
+ t1 = time.time()
+ if t1 - t0 > min_time:
+ break
+ ms_per_query = ((t1 - t0) * 1000.0 / nq / nrun)
+ res = {
+ "ms_per_query": ms_per_query,
+ "nrun": nrun
+ }
+ res["n"] = ms_per_query
+ if inter:
+ rank = k
+ inter_measure = faiss.eval_intersection(gt[:, :rank], I[:, :rank]) / (nq * rank)
+ print("%.4f" % inter_measure, end=' ')
+ res["inter_measure"] = inter_measure
+ else:
+ res["recalls"] = {}
+ for rank in 1, 10, 100:
+ recall = (I[:, :rank] == gt[:, :1]).sum() / float(nq)
+ print("%.4f" % recall, end=' ')
+ res["recalls"][rank] = recall
+ print(" %9.5f " % ms_per_query, end=' ')
+ print("%12d " % (ivf_stats.ndis / nrun), end=' ')
+ print(nrun)
+ res["ndis"] = ivf_stats.ndis / nrun
+ return res
+
+######################################################
+# Training
+######################################################
+
+def run_train(args, ds, res):
+ nq, d = ds.nq, ds.d
+ nb, d = ds.nq, ds.d
+
+ print("build index, key=", args.indexkey)
+
+ index = faiss.index_factory(
+ d, args.indexkey, faiss.METRIC_L2 if ds.metric == "L2" else
+ faiss.METRIC_INNER_PRODUCT
+ )
+
+ index_ivf, vec_transform = unwind_index_ivf(index)
+
+ if args.by_residual != -1:
+ by_residual = args.by_residual == 1
+ print("setting by_residual = ", by_residual)
+ index_ivf.by_residual # check if field exists
+ index_ivf.by_residual = by_residual
+
+ if index_ivf:
+ print("Update add-time parameters")
+ # adjust default parameters used at add time for quantizers
+ # because otherwise the assignment is inaccurate
+ quantizer = faiss.downcast_index(index_ivf.quantizer)
+ if isinstance(quantizer, faiss.IndexRefine):
+ print(" update quantizer k_factor=", quantizer.k_factor, end=" -> ")
+ quantizer.k_factor = 32 if index_ivf.nlist < 1e6 else 64
+ print(quantizer.k_factor)
+ base_index = faiss.downcast_index(quantizer.base_index)
+ if isinstance(base_index, faiss.IndexIVF):
+ print(" update quantizer nprobe=", base_index.nprobe, end=" -> ")
+ base_index.nprobe = (
+ 16 if base_index.nlist < 1e5 else
+ 32 if base_index.nlist < 4e6 else
+ 64)
+ print(base_index.nprobe)
+ elif isinstance(quantizer, faiss.IndexHNSW):
+ hnsw = quantizer.hnsw
+ print(
+ f" update HNSW quantizer options, before: "
+ f"{hnsw.efSearch=:} {hnsw.efConstruction=:}"
+ )
+ hnsw.efSearch = 40 if index_ivf.nlist < 4e6 else 64
+ hnsw.efConstruction = 200
+ print(f" after: {hnsw.efSearch=:} {hnsw.efConstruction=:}")
+
+ apply_AQ_options(index_ivf or index, args)
+
+ if index_ivf:
+ index_ivf.verbose = True
+ index_ivf.quantizer.verbose = True
+ index_ivf.cp.verbose = True
+ else:
+ index.verbose = True
+
+ maxtrain = args.maxtrain
+ if maxtrain == 0:
+ if 'IMI' in args.indexkey:
+ maxtrain = int(256 * 2 ** (np.log2(index_ivf.nlist) / 2))
+ elif index_ivf:
+ maxtrain = 50 * index_ivf.nlist
+ else:
+ # just guess...
+ maxtrain = 256 * 100
+ maxtrain = max(maxtrain, 256 * 100)
+ print("setting maxtrain to %d" % maxtrain)
+
+ try:
+ xt2 = ds.get_train(maxtrain=maxtrain)
+ except NotImplementedError:
+ print("No training set: training on database")
+ xt2 = ds.get_database()[:maxtrain]
+
+ print("train, size", xt2.shape)
+ assert np.all(np.isfinite(xt2))
+
+ if (isinstance(vec_transform, faiss.OPQMatrix) and
+ isinstance(index_ivf, faiss.IndexIVFPQFastScan)):
+ print(" Forcing OPQ training PQ to PQ4")
+ ref_pq = index_ivf.pq
+ training_pq = faiss.ProductQuantizer(
+ ref_pq.d, ref_pq.M, ref_pq.nbits
+ )
+ vec_transform.pq
+ vec_transform.pq = training_pq
+
+
+ if args.get_centroids_from == '':
+
+ if args.clustering_niter >= 0:
+ print(("setting nb of clustering iterations to %d" %
+ args.clustering_niter))
+ index_ivf.cp.niter = args.clustering_niter
+
+ if args.train_on_gpu:
+ print("add a training index on GPU")
+ train_index = faiss.index_cpu_to_all_gpus(
+ faiss.IndexFlatL2(index_ivf.d))
+ index_ivf.clustering_index = train_index
+
+ else:
+ print("Getting centroids from", args.get_centroids_from)
+ src_index = faiss.read_index(args.get_centroids_from)
+ src_quant = faiss.downcast_index(src_index.quantizer)
+ centroids = src_quant.reconstruct_n()
+ print(" centroid table shape", centroids.shape)
+
+ if isinstance(vec_transform, faiss.VectorTransform):
+ print(" training vector transform")
+ vec_transform.train(xt2)
+ print(" transform centroids")
+ centroids = vec_transform.apply_py(centroids)
+
+ if not index_ivf.quantizer.is_trained:
+ print(" training quantizer")
+ index_ivf.quantizer.train(centroids)
+
+ print(" add centroids to quantizer")
+ index_ivf.quantizer.add(centroids)
+ del src_index
+
+ t0 = time.time()
+ index.train(xt2)
+ res.train_time = time.time() - t0
+ print(" train in %.3f s" % res.train_time)
+ return index
+
+######################################################
+# Populating index
+######################################################
+
+def run_add(args, ds, index, res):
+
+ print("adding")
+ t0 = time.time()
+ if args.add_bs == -1:
+ assert args.split == [1, 0], "split not supported with full batch add"
+ index.add(sanitize(ds.get_database()))
+ else:
+ totn = ds.nb // args.split[0] # approximate
+ i0 = 0
+ print(f"Adding in block sizes {args.add_bs} with split {args.split}")
+ for xblock in ds.database_iterator(bs=args.add_bs, split=args.split):
+ i1 = i0 + len(xblock)
+ print(" adding %d:%d / %d [%.3f s, RSS %d kiB] " % (
+ i0, i1, totn, time.time() - t0,
+ faiss.get_mem_usage_kb()))
+ index.add(xblock)
+ i0 = i1
+
+ res.t_add = time.time() - t0
+ print(f" add in {res.t_add:.3f} s index size {index.ntotal}")
+
+
+######################################################
+# Search
+######################################################
+
+def run_search(args, ds, index, res):
+
+ index_ivf, vec_transform = unwind_index_ivf(index)
+
+ if args.no_precomputed_tables:
+ if isinstance(index_ivf, faiss.IndexIVFPQ):
+ print("disabling precomputed table")
+ index_ivf.use_precomputed_table = -1
+ index_ivf.precomputed_table.clear()
+
+ if args.indexfile:
+ print("index size on disk: ", os.stat(args.indexfile).st_size)
+
+ if hasattr(index, "code_size"):
+ print("vector code_size", index.code_size)
+
+ if hasattr(index_ivf, "code_size"):
+ print("vector code_size (IVF)", index_ivf.code_size)
+
+ print("current RSS:", faiss.get_mem_usage_kb() * 1024)
+
+ precomputed_table_size = 0
+ if hasattr(index_ivf, 'precomputed_table'):
+ precomputed_table_size = index_ivf.precomputed_table.size() * 4
+
+ print("precomputed tables size:", precomputed_table_size)
+
+ # Index is ready
+
+ xq = sanitize(ds.get_queries())
+ nq, d = xq.shape
+ gt = ds.get_groundtruth(k=args.k)
+
+ if not args.accept_short_gt: # Deep1B has only a single NN per query
+ assert gt.shape[1] == args.k
+
+ if args.searchthreads != -1:
+ print("Setting nb of threads to", args.searchthreads)
+ faiss.omp_set_num_threads(args.searchthreads)
+ else:
+ print("nb search threads: ", faiss.omp_get_max_threads())
+
+ ps = faiss.ParameterSpace()
+ ps.initialize(index)
+
+ parametersets = args.searchparams
+
+ if args.inter:
+ header = (
+ '%-40s inter@%3d time(ms/q) nb distances #runs' %
+ ("parameters", args.k)
+ )
+ else:
+
+ header = (
+ '%-40s R@1 R@10 R@100 time(ms/q) nb distances #runs' %
+ "parameters"
+ )
+
+
+ res.search_results = {}
+ if parametersets == ['autotune']:
+
+ ps.n_experiments = args.n_autotune
+ ps.min_test_duration = args.min_test_duration
+
+ for kv in args.autotune_max:
+ k, vmax = kv.split(':')
+ vmax = float(vmax)
+ print("limiting %s to %g" % (k, vmax))
+ pr = ps.add_range(k)
+ values = faiss.vector_to_array(pr.values)
+ values = np.array([v for v in values if v < vmax])
+ faiss.copy_array_to_vector(values, pr.values)
+
+ for kv in args.autotune_range:
+ k, vals = kv.split(':')
+ vals = np.fromstring(vals, sep=',')
+ print("setting %s to %s" % (k, vals))
+ pr = ps.add_range(k)
+ faiss.copy_array_to_vector(vals, pr.values)
+
+ # setup the Criterion object
+ if args.inter:
+ print("Optimize for intersection @ ", args.k)
+ crit = faiss.IntersectionCriterion(nq, args.k)
+ else:
+ print("Optimize for 1-recall @ 1")
+ crit = faiss.OneRecallAtRCriterion(nq, 1)
+
+ # by default, the criterion will request only 1 NN
+ crit.nnn = args.k
+ crit.set_groundtruth(None, gt.astype('int64'))
+
+ # then we let Faiss find the optimal parameters by itself
+ print("exploring operating points, %d threads" % faiss.omp_get_max_threads());
+ ps.display()
+
+ t0 = time.time()
+ op = ps.explore(index, xq, crit)
+ res.t_explore = time.time() - t0
+ print("Done in %.3f s, available OPs:" % res.t_explore)
+
+ op.display()
+
+ print("Re-running evaluation on selected OPs")
+ print(header)
+ opv = op.optimal_pts
+ maxw = max(max(len(opv.at(i).key) for i in range(opv.size())), 40)
+ for i in range(opv.size()):
+ opt = opv.at(i)
+
+ ps.set_index_parameters(index, opt.key)
+
+ print(opt.key.ljust(maxw), end=' ')
+ sys.stdout.flush()
+
+ res_i = eval_setting(index, xq, gt, args.k, args.inter, args.min_test_duration)
+ res.search_results[opt.key] = res_i
+
+ else:
+ print(header)
+ for param in parametersets:
+ print("%-40s " % param, end=' ')
+ sys.stdout.flush()
+ ps.set_index_parameters(index, param)
+
+ res_i = eval_setting(index, xq, gt, args.k, args.inter, args.min_test_duration)
+ res.search_results[param] = res_i
+
+
+
+######################################################
+# Driver function
+######################################################
+
+def main():
+
+ parser = argparse.ArgumentParser()
+
+ def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+ group = parser.add_argument_group('general options')
+ aa('--nthreads', default=-1, type=int,
+ help='nb of threads to use at train and add time')
+ aa('--json', default=False, action="store_true",
+ help="output stats in JSON format at the end")
+ aa('--todo', default=["check_files"],
+ choices=["train", "add", "search", "check_files"],
+ nargs="+", help='what to do (check_files means decide depending on which index files exist)')
+
+ group = parser.add_argument_group('dataset options')
+ aa('--db', default='deep1M', help='dataset')
+ aa('--compute_gt', default=False, action='store_true',
+ help='compute and store the groundtruth')
+ aa('--force_IP', default=False, action="store_true",
+ help='force IP search instead of L2')
+ aa('--accept_short_gt', default=False, action='store_true',
+ help='work around a problem with Deep1B GT')
+
+ group = parser.add_argument_group('index construction')
+ aa('--indexkey', default='HNSW32', help='index_factory type')
+ aa('--trained_indexfile', default='',
+ help='file to read or write a trained index from')
+ aa('--maxtrain', default=256 * 256, type=int,
+ help='maximum number of training points (0 to set automatically)')
+ aa('--indexfile', default='', help='file to read or write index from')
+ aa('--split', default=[1, 0], type=int, nargs=2, help="database split")
+ aa('--add_bs', default=-1, type=int,
+ help='add elements index by batches of this size')
+
+ group = parser.add_argument_group('IVF options')
+ aa('--by_residual', default=-1, type=int,
+ help="set if index should use residuals (default=unchanged)")
+ aa('--no_precomputed_tables', action='store_true', default=False,
+ help='disable precomputed tables (uses less memory)')
+ aa('--get_centroids_from', default='',
+ help='get the centroids from this index (to speed up training)')
+ aa('--clustering_niter', default=-1, type=int,
+ help='number of clustering iterations (-1 = leave default)')
+ aa('--train_on_gpu', default=False, action='store_true',
+ help='do training on GPU')
+
+ group = parser.add_argument_group('index-specific options')
+ aa('--M0', default=-1, type=int, help='size of base level for HNSW')
+ aa('--RQ_train_default', default=False, action="store_true",
+ help='disable progressive dim training for RQ')
+ aa('--RQ_beam_size', default=-1, type=int,
+ help='set beam size at add time')
+ aa('--LSQ_encode_ils_iters', default=-1, type=int,
+ help='ILS iterations for LSQ')
+ aa('--RQ_use_beam_LUT', default=-1, type=int,
+ help='use beam LUT at add time')
+
+ group = parser.add_argument_group('searching')
+ aa('--k', default=100, type=int, help='nb of nearest neighbors')
+ aa('--inter', default=False, action='store_true',
+ help='use intersection measure instead of 1-recall as metric')
+ aa('--searchthreads', default=-1, type=int,
+ help='nb of threads to use at search time')
+ aa('--searchparams', nargs='+', default=['autotune'],
+ help="search parameters to use (can be autotune or a list of params)")
+ aa('--n_autotune', default=500, type=int,
+ help="max nb of autotune experiments")
+ aa('--autotune_max', default=[], nargs='*',
+ help='set max value for autotune variables format "var:val" (exclusive)')
+ aa('--autotune_range', default=[], nargs='*',
+ help='set complete autotune range, format "var:val1,val2,..."')
+ aa('--min_test_duration', default=3.0, type=float,
+ help='run test at least for so long to avoid jitter')
+ aa('--indexes_to_merge', default=[], nargs="*",
+ help="load these indexes to search and merge them before searching")
+
+ args = parser.parse_args()
+
+ if args.todo == ["check_files"]:
+ if os.path.exists(args.indexfile):
+ args.todo = ["search"]
+ elif os.path.exists(args.trained_indexfile):
+ args.todo = ["add", "search"]
+ else:
+ args.todo = ["train", "add", "search"]
+ print("setting todo to", args.todo)
+
+ print("args:", args)
+
+ os.system('echo -n "nb processors "; '
+ 'cat /proc/cpuinfo | grep ^processor | wc -l; '
+ 'cat /proc/cpuinfo | grep ^"model name" | tail -1')
+
+ # object to collect results
+ res = argparse.Namespace()
+ res.args = args.__dict__
+
+ res.cpu_model = [
+ l for l in open("/proc/cpuinfo", "r")
+ if "model name" in l][0]
+
+ print("Load dataset")
+
+ ds = datasets.load_dataset(
+ dataset=args.db, compute_gt=args.compute_gt)
+
+ if args.force_IP:
+ ds.metric = "IP"
+
+ print(ds)
+
+ if args.nthreads != -1:
+ print("Set nb of threads to", args.nthreads)
+ faiss.omp_set_num_threads(args.nthreads)
+ else:
+ print("nb threads: ", faiss.omp_get_max_threads())
+
+ index = None
+ if "train" in args.todo:
+ print("================== Training index")
+ index = run_train(args, ds, res)
+ if args.trained_indexfile:
+ print("storing trained index", args.trained_indexfile)
+ faiss.write_index(index, args.trained_indexfile)
+
+ if "add" in args.todo:
+ if not index:
+ assert args.trained_indexfile
+ print("reading trained index", args.trained_indexfile)
+ index = faiss.read_index(args.trained_indexfile)
+
+ print("================== Adding vectors to index")
+ run_add(args, ds, index, res)
+ if args.indexfile:
+ print("storing", args.indexfile)
+ faiss.write_index(index, args.indexfile)
+
+ if "search" in args.todo:
+ if not index:
+ if args.indexfile:
+ print("reading index", args.indexfile)
+ index = faiss.read_index(args.indexfile)
+ elif args.indexes_to_merge:
+ print(f"Merging {len(args.indexes_to_merge)} indexes")
+ sz = 0
+ for fname in args.indexes_to_merge:
+ print(f" reading {fname} (current size {sz})")
+ index_i = faiss.read_index(fname)
+ if index is None:
+ index = index_i
+ else:
+ index.merge_from(index_i, index.ntotal)
+ sz = index.ntotal
+ else:
+ assert False, "provide --indexfile"
+
+ print("================== Searching")
+ run_search(args, ds, index, res)
+
+ if args.json:
+ print("JSON results:", json.dumps(res.__dict__))
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/bench_kmeans.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/bench_kmeans.py
new file mode 100644
index 0000000..2438025
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/bench_kmeans.py
@@ -0,0 +1,116 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import numpy as np
+import faiss
+import argparse
+import datasets
+from datasets import sanitize
+
+######################################################
+# Command-line parsing
+######################################################
+
+parser = argparse.ArgumentParser()
+
+
+def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+
+group = parser.add_argument_group('dataset options')
+
+aa('--db', default='deep1M', help='dataset')
+aa('--nt', default=65536, type=int)
+aa('--nb', default=100000, type=int)
+aa('--nt_sample', default=0, type=int)
+
+group = parser.add_argument_group('kmeans options')
+aa('--k', default=256, type=int)
+aa('--seed', default=12345, type=int)
+aa('--pcadim', default=-1, type=int, help='PCA to this dimension')
+aa('--niter', default=25, type=int)
+aa('--eval_freq', default=100, type=int)
+
+
+args = parser.parse_args()
+
+print("args:", args)
+
+os.system('echo -n "nb processors "; '
+ 'cat /proc/cpuinfo | grep ^processor | wc -l; '
+ 'cat /proc/cpuinfo | grep ^"model name" | tail -1')
+
+ngpu = faiss.get_num_gpus()
+print("nb GPUs:", ngpu)
+
+######################################################
+# Load dataset
+######################################################
+
+xt, xb, xq, gt = datasets.load_data(dataset=args.db)
+
+
+if args.nt_sample == 0:
+ xt_pca = xt[args.nt:args.nt + 10000]
+ xt = xt[:args.nt]
+else:
+ xt_pca = xt[args.nt_sample:args.nt_sample + 10000]
+ rs = np.random.RandomState(args.seed)
+ idx = rs.choice(args.nt_sample, size=args.nt, replace=False)
+ xt = xt[idx]
+
+xb = xb[:args.nb]
+
+d = xb.shape[1]
+
+if args.pcadim != -1:
+ print("training PCA: %d -> %d" % (d, args.pcadim))
+ pca = faiss.PCAMatrix(d, args.pcadim)
+ pca.train(sanitize(xt_pca))
+ xt = pca.apply_py(sanitize(xt))
+ xb = pca.apply_py(sanitize(xb))
+ d = xb.shape[1]
+
+
+######################################################
+# Run clustering
+######################################################
+
+
+index = faiss.IndexFlatL2(d)
+
+if ngpu > 0:
+ print("moving index to GPU")
+ index = faiss.index_cpu_to_all_gpus(index)
+
+
+clustering = faiss.Clustering(d, args.k)
+
+clustering.verbose = True
+clustering.seed = args.seed
+clustering.max_points_per_centroid = 10**6
+clustering.min_points_per_centroid = 1
+
+centroids = None
+
+for iter0 in range(0, args.niter, args.eval_freq):
+ iter1 = min(args.niter, iter0 + args.eval_freq)
+ clustering.niter = iter1 - iter0
+
+ if iter0 > 0:
+ faiss.copy_array_to_vector(centroids.ravel(), clustering.centroids)
+
+ clustering.train(sanitize(xt), index)
+ index.reset()
+ centroids = faiss.vector_to_array(clustering.centroids).reshape(args.k, d)
+ index.add(centroids)
+
+ _, I = index.search(sanitize(xb), 1)
+
+ error = ((xb - centroids[I.ravel()]) ** 2).sum()
+
+ print("iter1=%d quantization error on test: %.4f" % (iter1, error))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/cmp_with_scann.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/cmp_with_scann.py
new file mode 100644
index 0000000..5d13fbd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/cmp_with_scann.py
@@ -0,0 +1,307 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import sys
+import os
+import argparse
+
+import numpy as np
+
+
+def eval_recalls(name, I, gt, times):
+ k = I.shape[1]
+ s = "%-40s recall" % name
+ nq = len(gt)
+ for rank in 1, 10, 100, 1000:
+ if rank > k:
+ break
+ recall = (I[:, :rank] == gt[:, :1]).sum() / nq
+ s += "@%d: %.4f " % (rank, recall)
+ s += "time: %.4f s (± %.4f)" % (np.mean(times), np.std(times))
+ print(s)
+
+def eval_inters(name, I, gt, times):
+ k = I.shape[1]
+ s = "%-40s inter" % name
+ nq = len(gt)
+ for rank in 1, 10, 100, 1000:
+ if rank > k:
+ break
+ ninter = 0
+ for i in range(nq):
+ ninter += np.intersect1d(I[i, :rank], gt[i, :rank]).size
+ inter = ninter / (nq * rank)
+ s += "@%d: %.4f " % (rank, inter)
+ s += "time: %.4f s (± %.4f)" % (np.mean(times), np.std(times))
+ print(s)
+
+
+def main():
+
+ parser = argparse.ArgumentParser()
+
+ def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+ group = parser.add_argument_group('dataset options')
+
+ aa('--db', default='deep1M', help='dataset')
+ aa('--measure', default="1-recall",
+ help="perf measure to use: 1-recall or inter")
+ aa('--download', default=False, action="store_true")
+ aa('--lib', default='faiss', help='library to use (faiss or scann)')
+ aa('--thenscann', default=False, action="store_true")
+ aa('--base_dir', default='/checkpoint/matthijs/faiss_improvements/cmp_ivf_scan_2')
+
+ group = parser.add_argument_group('searching')
+ aa('--k', default=10, type=int, help='nb of nearest neighbors')
+ aa('--pre_reorder_k', default="0,10,100,1000", help='values for reorder_k')
+ aa('--nprobe', default="1,2,5,10,20,50,100,200", help='values for nprobe')
+ aa('--nrun', default=5, type=int, help='nb of runs to perform')
+ args = parser.parse_args()
+
+ print("args:", args)
+ pre_reorder_k_tab = [int(x) for x in args.pre_reorder_k.split(',')]
+ nprobe_tab = [int(x) for x in args.nprobe.split(',')]
+
+ os.system('echo -n "nb processors "; '
+ 'cat /proc/cpuinfo | grep ^processor | wc -l; '
+ 'cat /proc/cpuinfo | grep ^"model name" | tail -1')
+
+ cache_dir = args.base_dir + "/" + args.db + "/"
+ k = args.k
+ nrun = args.nrun
+
+ if not os.path.exists(cache_dir + "xb.npy"):
+ # prepare cache
+ from datasets import load_dataset
+ ds = load_dataset(args.db, download=args.download)
+ print(ds)
+ # store for SCANN
+ os.system(f"rm -rf {cache_dir}; mkdir -p {cache_dir}")
+ tosave = dict(
+ xb = ds.get_database(),
+ xq = ds.get_queries(),
+ gt = ds.get_groundtruth()
+ )
+ for name, v in tosave.items():
+ fname = cache_dir + "/" + name + ".npy"
+ print("save", fname)
+ np.save(fname, v)
+
+ open(cache_dir + "metric", "w").write(ds.metric)
+
+ dataset = {}
+ for kn in "xb xq gt".split():
+ fname = cache_dir + "/" + kn + ".npy"
+ print("load", fname)
+ dataset[kn] = np.load(fname)
+ xb = dataset["xb"]
+ xq = dataset["xq"]
+ gt = dataset["gt"]
+ distance_measure = open(cache_dir + "metric").read()
+
+ if args.lib == "faiss":
+ import faiss
+
+ name1_to_metric = {
+ "IP": faiss.METRIC_INNER_PRODUCT,
+ "L2": faiss.METRIC_L2
+ }
+
+ index_fname = cache_dir + "index.faiss"
+ if not os.path.exists(index_fname):
+ index = faiss_make_index(
+ xb, name1_to_metric[distance_measure], index_fname)
+ else:
+ index = faiss.read_index(index_fname)
+
+ faiss_eval_search(
+ index, xq, xb, nprobe_tab, pre_reorder_k_tab, k, gt,
+ nrun, args.measure
+ )
+
+ if args.lib == "scann":
+ from scann.scann_ops.py import scann_ops_pybind
+
+ name1_to_name2 = {
+ "IP": "dot_product",
+ "L2": "squared_l2"
+ }
+
+ scann_dir = cache_dir + "/scann1.1.1_serialized"
+ if os.path.exists(scann_dir + "/scann_config.pb"):
+ searcher = scann_ops_pybind.load_searcher(scann_dir)
+ else:
+ searcher = scann_make_index(xb, name1_to_name2[distance_measure], scann_dir, 0)
+
+ scann_dir = cache_dir + "/scann1.1.1_serialized_reorder"
+ if os.path.exists(scann_dir + "/scann_config.pb"):
+ searcher_reo = scann_ops_pybind.load_searcher(scann_dir)
+ else:
+ searcher_reo = scann_make_index(xb, name1_to_name2[distance_measure], scann_dir, 100)
+
+ scann_eval_search(
+ searcher, searcher_reo,
+ xq, xb, nprobe_tab, pre_reorder_k_tab, k, gt,
+ nrun, args.measure
+ )
+
+ if args.lib != "scann" and args.thenscann:
+ # just append --lib scann, that will override the previous cmdline
+ # options
+ cmdline = " ".join(sys.argv) + " --lib scann"
+ cmdline = (
+ ". ~/anaconda3/etc/profile.d/conda.sh ; " +
+ "conda activate scann_1.1.1; "
+ "python -u " + cmdline)
+
+ print("running", cmdline)
+
+ os.system(cmdline)
+
+
+###############################################################
+# SCANN
+###############################################################
+
+def scann_make_index(xb, distance_measure, scann_dir, reorder_k):
+ import scann
+
+ print("build index")
+
+ if distance_measure == "dot_product":
+ thr = 0.2
+ else:
+ thr = 0
+ k = 10
+ sb = scann.scann_ops_pybind.builder(xb, k, distance_measure)
+ sb = sb.tree(num_leaves=2000, num_leaves_to_search=100, training_sample_size=250000)
+ sb = sb.score_ah(2, anisotropic_quantization_threshold=thr)
+
+ if reorder_k > 0:
+ sb = sb.reorder(reorder_k)
+
+ searcher = sb.build()
+
+ print("done")
+
+ print("write index to", scann_dir)
+
+ os.system(f"rm -rf {scann_dir}; mkdir -p {scann_dir}")
+ # os.mkdir(scann_dir)
+ searcher.serialize(scann_dir)
+ return searcher
+
+def scann_eval_search(
+ searcher, searcher_reo,
+ xq, xb, nprobe_tab, pre_reorder_k_tab, k, gt,
+ nrun, measure):
+
+ # warmup
+ for _run in range(5):
+ searcher.search_batched(xq)
+
+ for nprobe in nprobe_tab:
+
+ for pre_reorder_k in pre_reorder_k_tab:
+
+ times = []
+ for _run in range(nrun):
+ if pre_reorder_k == 0:
+ t0 = time.time()
+ I, D = searcher.search_batched(
+ xq, leaves_to_search=nprobe, final_num_neighbors=k
+ )
+ t1 = time.time()
+ else:
+ t0 = time.time()
+ I, D = searcher_reo.search_batched(
+ xq, leaves_to_search=nprobe, final_num_neighbors=k,
+ pre_reorder_num_neighbors=pre_reorder_k
+ )
+ t1 = time.time()
+
+ times.append(t1 - t0)
+ header = "SCANN nprobe=%4d reo=%4d" % (nprobe, pre_reorder_k)
+ if measure == "1-recall":
+ eval_recalls(header, I, gt, times)
+ else:
+ eval_inters(header, I, gt, times)
+
+
+
+
+###############################################################
+# Faiss
+###############################################################
+
+
+def faiss_make_index(xb, metric_type, fname):
+ import faiss
+
+ d = xb.shape[1]
+ M = d // 2
+ index = faiss.index_factory(d, f"IVF2000,PQ{M}x4fs", metric_type)
+ # if not by_residual:
+ # print("setting no residual")
+ # index.by_residual = False
+
+ print("train")
+ index.train(xb[:250000])
+ print("add")
+ index.add(xb)
+ print("write index", fname)
+ faiss.write_index(index, fname)
+
+ return index
+
+def faiss_eval_search(
+ index, xq, xb, nprobe_tab, pre_reorder_k_tab,
+ k, gt, nrun, measure
+ ):
+ import faiss
+
+ print("use precomputed table=", index.use_precomputed_table,
+ "by residual=", index.by_residual)
+
+ print("adding a refine index")
+ index_refine = faiss.IndexRefineFlat(index, faiss.swig_ptr(xb))
+
+ print("set single thread")
+ faiss.omp_set_num_threads(1)
+
+ print("warmup")
+ for _run in range(5):
+ index.search(xq, k)
+
+ print("run timing")
+ for nprobe in nprobe_tab:
+ for pre_reorder_k in pre_reorder_k_tab:
+ index.nprobe = nprobe
+ times = []
+ for _run in range(nrun):
+ if pre_reorder_k == 0:
+ t0 = time.time()
+ D, I = index.search(xq, k)
+ t1 = time.time()
+ else:
+ index_refine.k_factor = pre_reorder_k / k
+ t0 = time.time()
+ D, I = index_refine.search(xq, k)
+ t1 = time.time()
+
+ times.append(t1 - t0)
+
+ header = "Faiss nprobe=%4d reo=%4d" % (nprobe, pre_reorder_k)
+ if measure == "1-recall":
+ eval_recalls(header, I, gt, times)
+ else:
+ eval_inters(header, I, gt, times)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/datasets_oss.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/datasets_oss.py
new file mode 100644
index 0000000..43e7962
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/datasets_oss.py
@@ -0,0 +1,136 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Common functions to load datasets and compute their ground-truth
+"""
+
+import time
+import numpy as np
+import faiss
+
+from faiss.contrib import datasets as faiss_datasets
+
+print("path:", faiss_datasets.__file__)
+
+faiss_datasets.dataset_basedir = '/checkpoint/matthijs/simsearch/'
+
+def sanitize(x):
+ return np.ascontiguousarray(x, dtype='float32')
+
+
+#################################################################
+# Dataset
+#################################################################
+
+class DatasetCentroids(faiss_datasets.Dataset):
+
+ def __init__(self, ds, indexfile):
+ self.d = ds.d
+ self.metric = ds.metric
+ self.nq = ds.nq
+ self.xq = ds.get_queries()
+
+ # get the xb set
+ src_index = faiss.read_index(indexfile)
+ src_quant = faiss.downcast_index(src_index.quantizer)
+ centroids = faiss.vector_to_array(src_quant.xb)
+ self.xb = centroids.reshape(-1, self.d)
+ self.nb = self.nt = len(self.xb)
+
+ def get_queries(self):
+ return self.xq
+
+ def get_database(self):
+ return self.xb
+
+ def get_train(self, maxtrain=None):
+ return self.xb
+
+ def get_groundtruth(self, k=100):
+ return faiss.knn(
+ self.xq, self.xb, k,
+ faiss.METRIC_L2 if self.metric == 'L2' else faiss.METRIC_INNER_PRODUCT
+ )[1]
+
+
+
+
+
+
+def load_dataset(dataset='deep1M', compute_gt=False, download=False):
+
+ print("load data", dataset)
+
+ if dataset == 'sift1M':
+ return faiss_datasets.DatasetSIFT1M()
+
+ elif dataset.startswith('bigann'):
+
+ dbsize = 1000 if dataset == "bigann1B" else int(dataset[6:-1])
+
+ return faiss_datasets.DatasetBigANN(nb_M=dbsize)
+
+ elif dataset.startswith("deep_centroids_"):
+ ncent = int(dataset[len("deep_centroids_"):])
+ centdir = "/checkpoint/matthijs/bench_all_ivf/precomputed_clusters"
+ return DatasetCentroids(
+ faiss_datasets.DatasetDeep1B(nb=1000000),
+ f"{centdir}/clustering.dbdeep1M.IVF{ncent}.faissindex"
+ )
+
+ elif dataset.startswith("deep"):
+
+ szsuf = dataset[4:]
+ if szsuf[-1] == 'M':
+ dbsize = 10 ** 6 * int(szsuf[:-1])
+ elif szsuf == '1B':
+ dbsize = 10 ** 9
+ elif szsuf[-1] == 'k':
+ dbsize = 1000 * int(szsuf[:-1])
+ else:
+ assert False, "did not recognize suffix " + szsuf
+ return faiss_datasets.DatasetDeep1B(nb=dbsize)
+
+ elif dataset == "music-100":
+ return faiss_datasets.DatasetMusic100()
+
+ elif dataset == "glove":
+ return faiss_datasets.DatasetGlove(download=download)
+
+ else:
+ assert False
+
+
+#################################################################
+# Evaluation
+#################################################################
+
+
+def evaluate_DI(D, I, gt):
+ nq = gt.shape[0]
+ k = I.shape[1]
+ rank = 1
+ while rank <= k:
+ recall = (I[:, :rank] == gt[:, :1]).sum() / float(nq)
+ print("R@%d: %.4f" % (rank, recall), end=' ')
+ rank *= 10
+
+
+def evaluate(xq, gt, index, k=100, endl=True):
+ t0 = time.time()
+ D, I = index.search(xq, k)
+ t1 = time.time()
+ nq = xq.shape[0]
+ print("\t %8.4f ms per query, " % (
+ (t1 - t0) * 1000.0 / nq), end=' ')
+ rank = 1
+ while rank <= k:
+ recall = (I[:, :rank] == gt[:, :1]).sum() / float(nq)
+ print("R@%d: %.4f" % (rank, recall), end=' ')
+ rank *= 10
+ if endl:
+ print()
+ return D, I
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/make_groundtruth.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/make_groundtruth.py
new file mode 100644
index 0000000..57836b2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/make_groundtruth.py
@@ -0,0 +1,27 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+
+# https://stackoverflow.com/questions/7016056/python-logging-not-outputting-anything
+logging.basicConfig()
+logger = logging.getLogger('faiss.contrib.exhaustive_search')
+logger.setLevel(logging.INFO)
+
+from faiss.contrib import datasets
+from faiss.contrib.exhaustive_search import knn_ground_truth
+from faiss.contrib import vecs_io
+
+ds = datasets.DatasetDeep1B(nb=int(1e9))
+
+print("computing GT matches for", ds)
+
+D, I = knn_ground_truth(
+ ds.get_queries(),
+ ds.database_iterator(bs=65536),
+ k=100
+)
+
+vecs_io.ivecs_write("/tmp/tt.ivecs", I)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/parse_bench_all_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/parse_bench_all_ivf.py
new file mode 100644
index 0000000..52d59c9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/parse_bench_all_ivf.py
@@ -0,0 +1,502 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import numpy as np
+from collections import defaultdict
+from matplotlib import pyplot
+
+import re
+
+from argparse import Namespace
+
+from faiss.contrib.factory_tools import get_code_size as unitsize
+
+
+def dbsize_from_name(dbname):
+ sufs = {
+ '1B': 10**9,
+ '100M': 10**8,
+ '10M': 10**7,
+ '1M': 10**6,
+ }
+ for s in sufs:
+ if dbname.endswith(s):
+ return sufs[s]
+ else:
+ assert False
+
+
+def keep_latest_stdout(fnames):
+ fnames = [fname for fname in fnames if fname.endswith('.stdout')]
+ fnames.sort()
+ n = len(fnames)
+ fnames2 = []
+ for i, fname in enumerate(fnames):
+ if i + 1 < n and fnames[i + 1][:-8] == fname[:-8]:
+ continue
+ fnames2.append(fname)
+ return fnames2
+
+
+def parse_result_file(fname):
+ # print fname
+ st = 0
+ res = []
+ keys = []
+ stats = {}
+ stats['run_version'] = fname[-8]
+ indexkey = None
+ for l in open(fname):
+ if l.startswith("srun:"):
+ # looks like a crash...
+ if indexkey is None:
+ raise RuntimeError("instant crash")
+ break
+ elif st == 0:
+ if l.startswith("dataset in dimension"):
+ fi = l.split()
+ stats["d"] = int(fi[3][:-1])
+ stats["nq"] = int(fi[9])
+ stats["nb"] = int(fi[11])
+ stats["nt"] = int(fi[13])
+ if l.startswith('index size on disk:'):
+ stats['index_size'] = int(l.split()[-1])
+ if l.startswith('current RSS:'):
+ stats['RSS'] = int(l.split()[-1])
+ if l.startswith('precomputed tables size:'):
+ stats['tables_size'] = int(l.split()[-1])
+ if l.startswith('Setting nb of threads to'):
+ stats['n_threads'] = int(l.split()[-1])
+ if l.startswith(' add in'):
+ stats['add_time'] = float(l.split()[-2])
+ if l.startswith("vector code_size"):
+ stats['code_size'] = float(l.split()[-1])
+ if l.startswith('args:'):
+ args = eval(l[l.find(' '):])
+ indexkey = args.indexkey
+ elif "time(ms/q)" in l:
+ # result header
+ if 'R@1 R@10 R@100' in l:
+ stats["measure"] = "recall"
+ stats["ranks"] = [1, 10, 100]
+ elif 'I@1 I@10 I@100' in l:
+ stats["measure"] = "inter"
+ stats["ranks"] = [1, 10, 100]
+ elif 'inter@' in l:
+ stats["measure"] = "inter"
+ fi = l.split()
+ if fi[1] == "inter@":
+ rank = int(fi[2])
+ else:
+ rank = int(fi[1][len("inter@"):])
+ stats["ranks"] = [rank]
+
+ else:
+ assert False
+ st = 1
+ elif 'index size on disk:' in l:
+ stats["index_size"] = int(l.split()[-1])
+ elif st == 1:
+ st = 2
+ elif st == 2:
+ fi = l.split()
+ if l[0] == " ":
+ # means there are 0 parameters
+ fi = [""] + fi
+ keys.append(fi[0])
+ res.append([float(x) for x in fi[1:]])
+ return indexkey, np.array(res), keys, stats
+
+# the directory used in run_on_cluster.bash
+basedir = "/checkpoint/matthijs/bench_all_ivf/"
+logdir = basedir + 'logs/'
+
+
+def collect_results_for(db='deep1M', prefix="autotune."):
+ # run parsing
+ allres = {}
+ allstats = {}
+ missing = []
+
+ fnames = keep_latest_stdout(os.listdir(logdir))
+ # print fnames
+ # filenames are in the form <key>.x.stdout
+ # where x is a version number (from a to z)
+ # keep only latest version of each name
+
+ for fname in fnames:
+ if not (
+ 'db' + db in fname and
+ fname.startswith(prefix) and
+ fname.endswith('.stdout')
+ ):
+ continue
+ print("parse", fname, end=" ", flush=True)
+ try:
+ indexkey, res, _, stats = parse_result_file(logdir + fname)
+ except RuntimeError as e:
+ print("FAIL %s" % e)
+ res = np.zeros((2, 0))
+ except Exception as e:
+ print("PARSE ERROR " + e)
+ res = np.zeros((2, 0))
+ else:
+ print(len(res), "results")
+ if res.size == 0:
+ missing.append(fname)
+ else:
+ if indexkey in allres:
+ if allstats[indexkey]['run_version'] > stats['run_version']:
+ # don't use this run
+ continue
+
+ allres[indexkey] = res
+ allstats[indexkey] = stats
+
+ return allres, allstats
+
+def extract_pareto_optimal(allres, keys, recall_idx=0, times_idx=3):
+ bigtab = []
+ for i, k in enumerate(keys):
+ v = allres[k]
+ perf = v[:, recall_idx]
+ times = v[:, times_idx]
+ bigtab.append(
+ np.vstack((
+ np.ones(times.size) * i,
+ perf, times
+ ))
+ )
+ if bigtab == []:
+ return [], np.zeros((3, 0))
+
+ bigtab = np.hstack(bigtab)
+
+ # sort by perf
+ perm = np.argsort(bigtab[1, :])
+ bigtab_sorted = bigtab[:, perm]
+ best_times = np.minimum.accumulate(bigtab_sorted[2, ::-1])[::-1]
+ selection, = np.where(bigtab_sorted[2, :] == best_times)
+ selected_keys = [
+ keys[i] for i in
+ np.unique(bigtab_sorted[0, selection].astype(int))
+ ]
+ ops = bigtab_sorted[:, selection]
+
+ return selected_keys, ops
+
+def plot_subset(
+ allres, allstats, selected_methods, recall_idx, times_idx=3,
+ report=["overhead", "build time"]):
+
+ # important methods
+ for k in selected_methods:
+ v = allres[k]
+
+ stats = allstats[k]
+ d = stats["d"]
+ dbsize = stats["nb"]
+ if "index_size" in stats and "tables_size" in stats:
+ tot_size = stats['index_size'] + stats['tables_size']
+ else:
+ tot_size = -1
+ id_size = 8 # 64 bit
+
+ addt = ''
+ if 'add_time' in stats:
+ add_time = stats['add_time']
+ if add_time > 7200:
+ add_min = add_time / 60
+ addt = ', %dh%02d' % (add_min / 60, add_min % 60)
+ else:
+ add_sec = int(add_time)
+ addt = ', %dm%02d' % (add_sec / 60, add_sec % 60)
+
+ code_size = unitsize(d, k)
+
+ label = k
+
+ if "code_size" in report:
+ label += " %d bytes" % code_size
+
+ tight_size = (code_size + id_size) * dbsize
+
+ if tot_size < 0 or "overhead" not in report:
+ pass # don't know what the index size is
+ elif tot_size > 10 * tight_size:
+ label += " overhead x%.1f" % (tot_size / tight_size)
+ else:
+ label += " overhead+%.1f%%" % (
+ tot_size / tight_size * 100 - 100)
+
+ if "build time" in report:
+ label += " " + addt
+
+ linestyle = (':' if 'Refine' in k or 'RFlat' in k else
+ '-.' if 'SQ' in k else
+ '-' if '4fs' in k else
+ '-')
+ print(k, linestyle)
+ pyplot.semilogy(v[:, recall_idx], 1000 / v[:, times_idx], label=label,
+ linestyle=linestyle,
+ marker='o' if '4fs' in k else '+')
+
+ recall_rank = stats["ranks"][recall_idx]
+ if stats["measure"] == "recall":
+ pyplot.xlabel('1-recall at %d' % recall_rank)
+ elif stats["measure"] == "inter":
+ pyplot.xlabel('inter @ %d' % recall_rank)
+ else:
+ assert False
+ pyplot.ylabel('QPS (%d threads)' % stats["n_threads"])
+
+
+def plot_tradeoffs(db, allres, allstats, code_size, recall_rank):
+ stat0 = next(iter(allstats.values()))
+ d = stat0["d"]
+ n_threads = stat0["n_threads"]
+ recall_idx = stat0["ranks"].index(recall_rank)
+ # times come after the perf measure
+ times_idx = len(stat0["ranks"])
+
+ if type(code_size) == int:
+ if code_size == 0:
+ code_size = [0, 1e50]
+ code_size_name = "any code size"
+ else:
+ code_size_name = "code_size=%d" % code_size
+ code_size = [code_size, code_size]
+ elif type(code_size) == tuple:
+ code_size_name = "code_size in [%d, %d]" % code_size
+ else:
+ assert False
+
+ names_maxperf = []
+
+ for k in sorted(allres):
+ v = allres[k]
+ if v.ndim != 2: continue
+ us = unitsize(d, k)
+ if not code_size[0] <= us <= code_size[1]: continue
+ names_maxperf.append((v[-1, recall_idx], k))
+
+ # sort from lowest to highest topline accuracy
+ names_maxperf.sort()
+ names = [name for mp, name in names_maxperf]
+
+ selected_methods, optimal_points = \
+ extract_pareto_optimal(allres, names, recall_idx, times_idx)
+
+ not_selected = list(set(names) - set(selected_methods))
+
+ print("methods without an optimal OP: ", not_selected)
+
+ pyplot.title('database ' + db + ' ' + code_size_name)
+
+ # grayed out lines
+
+ for k in not_selected:
+ v = allres[k]
+ if v.ndim != 2: continue
+ us = unitsize(d, k)
+ if not code_size[0] <= us <= code_size[1]: continue
+
+ linestyle = (':' if 'PQ' in k else
+ '-.' if 'SQ4' in k else
+ '--' if 'SQ8' in k else '-')
+
+ pyplot.semilogy(v[:, recall_idx], 1000 / v[:, times_idx], label=None,
+ linestyle=linestyle,
+ marker='o' if 'HNSW' in k else '+',
+ color='#cccccc', linewidth=0.2)
+
+ plot_subset(allres, allstats, selected_methods, recall_idx, times_idx)
+
+
+ if len(not_selected) == 0:
+ om = ''
+ else:
+ om = '\nomitted:'
+ nc = len(om)
+ for m in not_selected:
+ if nc > 80:
+ om += '\n'
+ nc = 0
+ om += ' ' + m
+ nc += len(m) + 1
+
+ # pyplot.semilogy(optimal_points[1, :], optimal_points[2, :], marker="s")
+ # print(optimal_points[0, :])
+ pyplot.xlabel('1-recall at %d %s' % (recall_rank, om) )
+ pyplot.ylabel('QPS (%d threads)' % n_threads)
+ pyplot.legend()
+ pyplot.grid()
+ return selected_methods, not_selected
+
+
+
+if __name__ == "__main__xx":
+ # tests on centroids indexing (v1)
+
+ for k in 1, 32, 128:
+ pyplot.gcf().set_size_inches(15, 10)
+ i = 1
+ for ncent in 65536, 262144, 1048576, 4194304:
+ db = f'deep_centroids_{ncent}.k{k}.'
+ allres, allstats = collect_results_for(
+ db=db, prefix="cent_index.")
+
+ pyplot.subplot(2, 2, i)
+ plot_subset(
+ allres, allstats, list(allres.keys()),
+ recall_idx=0,
+ times_idx=1,
+ report=["code_size"]
+ )
+ i += 1
+ pyplot.title(f"{ncent} centroids")
+ pyplot.legend()
+ pyplot.xlim([0.95, 1])
+ pyplot.grid()
+
+ pyplot.savefig('figs/deep1B_centroids_k%d.png' % k)
+
+
+if __name__ == "__main__xx":
+ # centroids plot per k
+
+ pyplot.gcf().set_size_inches(15, 10)
+
+ i=1
+ for ncent in 65536, 262144, 1048576, 4194304:
+
+ xyd = defaultdict(list)
+
+ for k in 1, 4, 8, 16, 32, 64, 128, 256:
+
+ db = f'deep_centroids_{ncent}.k{k}.'
+ allres, allstats = collect_results_for(db=db, prefix="cent_index.")
+
+ for indexkey, res in allres.items():
+ idx, = np.where(res[:, 0] >= 0.99)
+ if idx.size > 0:
+ xyd[indexkey].append((k, 1000 / res[idx[0], 1]))
+
+ pyplot.subplot(2, 2, i)
+ i += 1
+ for indexkey, xy in xyd.items():
+ xy = np.array(xy)
+ pyplot.loglog(xy[:, 0], xy[:, 1], 'o-', label=indexkey)
+
+ pyplot.title(f"{ncent} centroids")
+ pyplot.xlabel("k")
+ xt = 2**np.arange(9)
+ pyplot.xticks(xt, ["%d" % x for x in xt])
+ pyplot.ylabel("QPS (32 threads)")
+ pyplot.legend()
+ pyplot.grid()
+
+ pyplot.savefig('../plots/deep1B_centroids_min99.png')
+
+
+
+
+
+if __name__ == "__main__xx":
+ # main indexing plots
+
+ i = 0
+ for db in 'bigann10M', 'deep10M', 'bigann100M', 'deep100M', 'deep1B', 'bigann1B':
+ allres, allstats = collect_results_for(
+ db=db, prefix="autotune.")
+
+ for cs in 8, 16, 32, 64:
+ pyplot.figure(i)
+ i += 1
+ pyplot.gcf().set_size_inches(15, 10)
+
+ cs_range = (
+ (0, 8) if cs == 8 else (cs // 2 + 1, cs)
+ )
+
+ plot_tradeoffs(
+ db, allres, allstats, code_size=cs_range, recall_rank=1)
+ pyplot.savefig('../plots/tradeoffs_%s_cs%d_r1.png' % (
+ db, cs))
+
+
+if __name__ == "__main__":
+ # 1M indexes
+ i = 0
+ for db in "glove", "music-100":
+ pyplot.figure(i)
+ pyplot.gcf().set_size_inches(15, 10)
+ i += 1
+ allres, allstats = collect_results_for(db=db, prefix="autotune.")
+ plot_tradeoffs(db, allres, allstats, code_size=0, recall_rank=1)
+ pyplot.savefig('../plots/1M_tradeoffs_' + db + ".png")
+
+ for db in "sift1M", "deep1M":
+ allres, allstats = collect_results_for(db=db, prefix="autotune.")
+ pyplot.figure(i)
+ pyplot.gcf().set_size_inches(15, 10)
+ i += 1
+ plot_tradeoffs(db, allres, allstats, code_size=(0, 64), recall_rank=1)
+ pyplot.savefig('../plots/1M_tradeoffs_' + db + "_small.png")
+
+ pyplot.figure(i)
+ pyplot.gcf().set_size_inches(15, 10)
+ i += 1
+ plot_tradeoffs(db, allres, allstats, code_size=(65, 10000), recall_rank=1)
+ pyplot.savefig('../plots/1M_tradeoffs_' + db + "_large.png")
+
+
+
+if __name__ == "__main__xx":
+ db = 'sift1M'
+ allres, allstats = collect_results_for(db=db, prefix="autotune.")
+ pyplot.gcf().set_size_inches(15, 10)
+
+ keys = [
+ "IVF1024,PQ32x8",
+ "IVF1024,PQ64x4",
+ "IVF1024,PQ64x4fs",
+ "IVF1024,PQ64x4fsr",
+ "IVF1024,SQ4",
+ "IVF1024,SQ8"
+ ]
+
+ plot_subset(allres, allstats, keys, recall_idx=0, report=["code_size"])
+
+ pyplot.legend()
+ pyplot.title(db)
+ pyplot.xlabel("1-recall@1")
+ pyplot.ylabel("QPS (32 threads)")
+ pyplot.grid()
+
+ pyplot.savefig('../plots/ivf1024_variants.png')
+
+ pyplot.figure(2)
+ pyplot.gcf().set_size_inches(15, 10)
+
+ keys = [
+ "HNSW32",
+ "IVF1024,PQ64x4fs",
+ "IVF1024,PQ64x4fsr",
+ "IVF1024,PQ64x4fs,RFlat",
+ "IVF1024,PQ64x4fs,Refine(SQfp16)",
+ "IVF1024,PQ64x4fs,Refine(SQ8)",
+ ]
+
+ plot_subset(allres, allstats, keys, recall_idx=0, report=["code_size"])
+
+ pyplot.legend()
+ pyplot.title(db)
+ pyplot.xlabel("1-recall@1")
+ pyplot.ylabel("QPS (32 threads)")
+ pyplot.grid()
+
+ pyplot.savefig('../plots/ivf1024_rerank.png')
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/run_on_cluster_generic.bash b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/run_on_cluster_generic.bash
new file mode 100644
index 0000000..f2007ce
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_all_ivf/run_on_cluster_generic.bash
@@ -0,0 +1,603 @@
+set -e
+
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# @nolint
+
+# This script launches the experiments on a cluster
+# It assumes two shell functions are defined:
+#
+# run_on_1machine: runs a command on one (full) machine on a cluster
+#
+# run_on_8gpu: runs a command on one machine with 8 GPUs
+#
+# the two functions are called as:
+#
+# run_on_1machine <name> <command>
+#
+# the stdout of the command should be stored in $logdir/<name>.stdout
+
+
+function run_on ()
+{
+ sys="$1"
+ shift
+ name="$1"
+ shift
+ script="$logdir/$name.sh"
+
+ if [ -e "$script" ]; then
+ echo script "$script" exists
+ return
+ fi
+
+ # srun handles special characters fine, but the shell interpreter
+ # does not
+ escaped_cmd=$( printf "%q " "$@" )
+
+ cat > $script <<EOF
+#! /bin/bash
+srun $escaped_cmd
+EOF
+
+ echo -n "$logdir/$name.stdout "
+ sbatch -n1 -J "$name" \
+ $sys \
+ --comment='priority is the only one that works' \
+ --output="$logdir/$name.stdout" \
+ "$script"
+
+}
+
+
+function run_on_1machine {
+ run_on "--cpus-per-task=80 --gres=gpu:0 --mem=500G --time=70:00:00 --partition=priority" "$@"
+}
+
+function run_on_1machine_1h {
+ run_on "--cpus-per-task=80 --gres=gpu:2 --mem=100G --time=1:00:00 --partition=priority" "$@"
+}
+
+function run_on_1machine_3h {
+ run_on "--cpus-per-task=80 --gres=gpu:2 --mem=100G --time=3:00:00 --partition=priority" "$@"
+}
+
+function run_on_4gpu_3h {
+ run_on "--cpus-per-task=40 --gres=gpu:4 --mem=100G --time=3:00:00 --partition=priority" "$@"
+}
+
+function run_on_8gpu () {
+ run_on "--cpus-per-task=80 --gres=gpu:8 --mem=100G --time=70:00:00 --partition=priority" "$@"
+}
+
+
+# prepare output directories
+# set to some directory where all indexes, can be written.
+basedir=/checkpoint/matthijs/bench_all_ivf
+
+logdir=$basedir/logs
+indexdir=$basedir/indexes
+centdir=$basedir/precomputed_clusters
+
+mkdir -p $logdir $indexdir
+
+
+# adds an option to use a pretrained quantizer
+function add_precomputed_quantizer () {
+ local db="$1"
+ local coarse="$2"
+
+ case $db in
+ bigann*) rname=bigann ;;
+ deep*) rname=deep ;;
+ sift1M) return;;
+ music-100) return ;;
+ glove) return ;;
+ *) echo "bad db"; exit 1;;
+ esac
+
+ case $coarse in
+ IVF65536*)
+ cname=clustering.db${rname}1M.IVF65536.faissindex
+ copt="--get_centroids_from $centdir/$cname"
+ ;;
+ IVF262144*)
+ cname=clustering.db${rname}1M.IVF262144.faissindex
+ copt="--get_centroids_from $centdir/$cname"
+ ;;
+ IVF1048576*)
+ cname=clustering.db${rname}1M.IVF1048576.faissindex
+ copt="--get_centroids_from $centdir/$cname"
+ ;;
+ IVF4194304*)
+ cname=clustering.db${rname}1M.IVF4194304.faissindex
+ copt="--get_centroids_from $centdir/$cname"
+ ;;
+ *)
+ copt="" ;;
+ esac
+
+ echo $copt
+}
+
+function get_db_dim () {
+ local db="$1"
+ case $db in
+ sift1M) dim=128;;
+ bigann*) dim=128;;
+ deep*) dim=96;;
+ music-100) dim=100;;
+ glove) dim=100;;
+ *) echo "bad db"; exit 1;;
+ esac
+ echo $dim
+}
+
+
+# replace HD = half dim with the half of the dimension we need to handle
+# relying that variables are global by default...
+function replace_coarse_PQHD () {
+ local coarse="$1"
+ local dim=$2
+
+
+ coarseD=${coarse//PQHD/PQ$((dim/2))}
+ coarse16=${coarse//PQHD/PQ8}
+ coarse32=${coarse//PQHD/PQ16}
+ coarse64=${coarse//PQHD/PQ32}
+ coarse128=${coarse//PQHD/PQ64}
+ coarse256=${coarse//PQHD/PQ128}
+ coarse112=${coarse//PQHD/PQ56}
+
+}
+
+
+
+if false; then
+
+
+
+###############################################
+# comparison with SCANN
+
+for db in sift1M deep1M glove music-100
+do
+ opt=""
+ if [ $db == glove ]; then
+ opt="--measure inter"
+ fi
+
+ run_on_1machine_1h cmp_with_scann.$db.c \
+ python -u cmp_with_scann.py --db $db \
+ --lib faiss $opt --thenscann
+
+done
+
+
+
+
+############################### Preliminary SIFT1M experiment
+
+
+for db in sift1M ; do
+
+ for coarse in IVF1024
+ do
+ indexkeys="
+ HNSW32
+ $coarse,SQfp16
+ $coarse,SQ4
+ $coarse,SQ8
+ $coarse,PQ32x8
+ $coarse,PQ64x4
+ $coarse,PQ64x4fs
+ $coarse,PQ64x4fs,RFlat
+ $coarse,PQ64x4fs,Refine(SQfp16)
+ $coarse,PQ64x4fs,Refine(SQ8)
+ OPQ64,$coarse,PQ64x4fs
+ OPQ64,$coarse,PQ64x4fs,RFlat
+ "
+ indexkeys="
+ $coarse,PQ64x4fsr
+ $coarse,PQ64x4fsr,RFlat
+ "
+
+ # OPQ actually degrades the results on SIFT1M, so let's ignore
+
+ for indexkey in $indexkeys
+ do
+ # escape nasty characters
+ key="autotune.db$db.${indexkey//,/_}"
+ key="${key//(/_}"
+ key="${key//)/_}"
+ run_on_1machine_1h $key.a \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey "$indexkey" \
+ --maxtrain 0 \
+ --indexfile $indexdir/$key.faissindex \
+ --searchthreads 32
+ done
+ done
+done
+
+
+
+
+############################### 1M experiments
+
+fi
+# for db in sift1M deep1M music-100 glove; do
+
+for db in glove music-100; do
+
+ dim=$( get_db_dim $db )
+
+ for coarse in IVF1024 IVF4096_HNSW32
+ do
+
+ replace_coarse_PQHD "$coarse" $dim
+
+ indexkeys="
+ $coarseD,PQ$((dim/2))x4fs
+ $coarseD,PQ$((dim/2))x4fsr
+
+ OPQ8_64,$coarse64,PQ8
+ PCAR16,$coarse16,SQ4
+ OPQ16_64,$coarse64,PQ16x4fs
+ OPQ16_64,$coarse64,PQ16x4fsr
+
+ OPQ16_64,$coarse64,PQ16
+ PCAR16,$coarse16,SQ8
+ PCAR32,$coarse32,SQ4
+ OPQ32_64,$coarse64,PQ32x4fs
+ OPQ32_64,$coarse64,PQ32x4fsr
+
+ OPQ32_128,$coarse128,PQ32
+ PCAR32,$coarse32,SQ8
+ PCAR64,$coarse64,SQ4
+ PCAR16,$coarse16,SQfp16
+ OPQ64_128,$coarse128,PQ64x4fs
+ OPQ64_128,$coarse128,PQ64x4fsr
+
+ OPQ64_128,$coarse128,PQ64
+ PCAR64,$coarse64,SQ8
+ PCAR32,$coarse32,SQfp16
+ PCAR128,$coarse128,SQ4
+ OPQ128_256,$coarse256,PQ128x4fs
+ OPQ128_256,$coarse256,PQ128x4fsr
+ OPQ16_64,$coarse64,PQ16x4fs,Refine(OPQ56_112,PQ56)
+ OPQ16_64,$coarse64,PQ16x4fs,Refine(PCAR72,SQ6)
+ OPQ32_64,$coarse64,PQ16x4fs,Refine(PCAR64,SQ6)
+ OPQ32_64,$coarse64,PQ32x4fs,Refine(OPQ48_96,PQ48)
+ OPQ64_128,$coarse,PQ64x12
+
+ OPQ64_128,$coarse,PQ64x4fs,RFlat
+ OPQ64_128,$coarse,PQ64x4fs,Refine(SQfp16)
+ OPQ64_128,$coarse,PQ64x4fs,Refine(SQ8)
+ OPQ64_128,$coarse,PQ64x4fs,Refine(SQ6)
+ OPQ64_128,$coarse,PQ64x4fs,Refine(SQ4)
+ OPQ32_64,$coarse,PQ32x4fs,Refine(SQfp16)
+ OPQ32_64,$coarse,PQ32x4fs,Refine(SQ8)
+ OPQ32_64,$coarse,PQ32x4fs,Refine(SQ6)
+ OPQ32_64,$coarse,PQ32x4fs,Refine(SQ4)
+
+ "
+
+ indexkeys="
+ $coarseD,PQ$((dim/2))x4fs
+ $coarseD,PQ$((dim/2))x4fsr
+ $coarseD,PQ$((dim/2))x4fsr,RFlat
+ $coarseD,PQ$((dim/2))x4fsr,Refine(SQfp16)
+ $coarseD,PQ$((dim/2))x4fsr,Refine(SQ8)
+ $coarseD,PQ$((dim/4))x4fs
+ $coarseD,PQ$((dim/4))x4fsr
+ $coarseD,PQ$((dim/4))x4fsr,RFlat
+ $coarseD,PQ$((dim/4))x4fsr,Refine(SQfp16)
+ $coarseD,PQ$((dim/4))x4fsr,Refine(SQ8)
+ $coarseD,PQ$((dim/2))
+ $coarseD,PQ$((dim/4))
+ HNSW32,Flat
+ "
+
+ indexkeys="HNSW32,Flat"
+
+ for indexkey in $indexkeys
+ do
+ key=autotune.db$db.${indexkey//,/_}
+ key="${key//(/_}"
+ key="${key//)/_}"
+ run_on_1machine_3h $key.q \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey "$indexkey" \
+ --maxtrain 0 \
+ --indexfile "$indexdir/$key.faissindex" \
+ $( add_precomputed_quantizer $db $coarse ) \
+ --searchthreads 32 \
+ --min_test_duration 3
+ done
+
+
+ done
+done
+
+if false; then
+
+############################################
+# precompute centroids on GPU for large vocabularies
+
+for db in deep1M bigann1M; do
+
+ for ncent in 262144 65536 1048576 4194304; do
+
+ key=clustering.db$db.IVF$ncent
+ run_on_4gpu_3h $key.e \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey IVF$ncent,SQ8 \
+ --maxtrain 100000000 \
+ --indexfile $centdir/$key.faissindex \
+ --searchthreads 32 \
+ --min_test_duration 3 \
+ --add_bs 1000000 \
+ --train_on_gpu
+
+ done
+done
+
+###############################
+## coarse quantizer experiments on the centroids of deep1B
+
+
+for k in 4 8 16 64 256; do
+
+ for ncent in 65536 262144 1048576 4194304; do
+ db=deep_centroids_$ncent
+
+ # compute square root of ncent...
+ for(( ls=0; ncent > (1 << (2 * ls)); ls++)); do
+ echo -n
+ done
+ sncent=$(( 1 << ls ))
+
+ indexkeys="
+ IVF$((sncent/2)),PQ48x4fs,RFlat
+ IVF$((sncent*2)),PQ48x4fs,RFlat
+ HNSW32
+ PQ48x4fs
+ PQ48x4fs,RFlat
+ IVF$sncent,PQ48x4fs,RFlat
+ "
+
+ for indexkey in $indexkeys; do
+ key="cent_index.db$db.k$k.$indexkey"
+ run_on_1machine_1h "$key.b" \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey "$indexkey" \
+ --maxtrain 0 \
+ --inter \
+ --searchthreads 32 \
+ --k $k
+ done
+
+ done
+done
+
+
+############################### 10M experiments
+
+
+for db in deep10M bigann10M; do
+
+ coarses="
+ IVF65536(IVF256,PQHDx4fs,RFlat)
+ IVF16384_HNSW32
+ IVF65536_HNSW32
+ IVF262144_HNSW32
+ IVF262144(IVF512,PQHDx4fs,RFlat)
+ "
+
+ dim=$( get_db_dim $db )
+
+ for coarse in $coarses
+ do
+
+ replace_coarse_PQHD "$coarse" $dim
+
+ indexkeys="
+ $coarseD,PQ$((dim/2))x4fs
+
+ OPQ8_64,$coarse64,PQ8
+ PCAR16,$coarse16,SQ4
+ OPQ16_64,$coarse64,PQ16x4fs
+ OPQ16_64,$coarse64,PQ16x4fsr
+
+ OPQ16_64,$coarse64,PQ16
+ PCAR16,$coarse16,SQ8
+ PCAR32,$coarse32,SQ4
+ OPQ32_64,$coarse64,PQ32x4fs
+ OPQ32_64,$coarse64,PQ32x4fsr
+
+ OPQ32_128,$coarse128,PQ32
+ PCAR32,$coarse32,SQ8
+ PCAR64,$coarse64,SQ4
+ PCAR16,$coarse16,SQfp16
+ OPQ64_128,$coarse128,PQ64x4fs
+ OPQ64_128,$coarse128,PQ64x4fsr
+
+ OPQ64_128,$coarse128,PQ64
+ PCAR64,$coarse64,SQ8
+ PCAR32,$coarse32,SQfp16
+ PCAR128,$coarse128,SQ4
+ OPQ128_256,$coarse256,PQ128x4fs
+ OPQ128_256,$coarse256,PQ128x4fsr
+ OPQ56_112,$coarse112,PQ7+56
+ OPQ16_64,$coarse64,PQ16x4fs,Refine(OPQ56_112,PQ56)
+ OPQ16_64,$coarse64,PQ16x4fs,Refine(PCAR72,SQ6)
+ OPQ32_64,$coarse64,PQ16x4fs,Refine(PCAR64,SQ6)
+ OPQ32_64,$coarse64,PQ32x4fs,Refine(OPQ48_96,PQ48)
+ "
+
+ indexkeys="
+ OPQ16_64,$coarse64,PQ16x4fsr
+ OPQ32_64,$coarse64,PQ32x4fsr
+ OPQ64_128,$coarse128,PQ64x4fsr
+ OPQ128_256,$coarse256,PQ128x4fsr
+ "
+
+
+ for indexkey in $indexkeys
+ do
+ key=autotune.db$db.${indexkey//,/_}
+ key="${key//(/_}"
+ key="${key//)/_}"
+ run_on_1machine_3h $key.l \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey "$indexkey" \
+ --maxtrain 0 \
+ --indexfile "$indexdir/$key.faissindex" \
+ $( add_precomputed_quantizer $db $coarse ) \
+ --searchthreads 32 \
+ --min_test_duration 3 \
+ --autotune_max nprobe:2000
+ done
+ done
+done
+
+
+############################### 100M experiments
+
+for db in deep100M bigann100M; do
+ coarses="
+ IVF65536_HNSW32
+ IVF262144_HNSW32
+ IVF262144(IVF512,PQHDx4fs,RFlat)
+ IVF1048576_HNSW32
+ IVF1048576(IVF1024,PQHDx4fs,RFlat)
+ "
+ dim=$( get_db_dim $db )
+
+ for coarse in $coarses
+ do
+ replace_coarse_PQHD "$coarse" $dim
+
+ indexkeys="
+ OPQ8_64,$coarse64,PQ8
+ OPQ16_64,$coarse64,PQ16x4fs
+
+ PCAR32,$coarse32,SQ4
+ OPQ16_64,$coarse64,PQ16
+ OPQ32_64,$coarse64,PQ32x4fs
+
+ OPQ32_128,$coarse128,PQ32
+ PCAR64,$coarse64,SQ4
+ PCAR32,$coarse32,SQ8
+ OPQ64_128,$coarse128,PQ64x4fs
+
+ PCAR128,$coarse128,SQ4
+ OPQ64_128,$coarse128,PQ64
+
+ PCAR32,$coarse32,SQfp16
+ PCAR64,$coarse64,SQ8
+ OPQ128_256,$coarse256,PQ128x4fs
+
+ OPQ56_112,$coarse112,PQ7+56
+ OPQ16_64,$coarse64,PQ16x4fs,Refine(OPQ56_112,PQ56)
+
+ $coarseD,PQ$((dim/2))x4fs
+ "
+
+ indexkeys="
+ OPQ128_256,$coarse256,PQ128x4fsr
+ OPQ64_128,$coarse128,PQ64x4fsr
+ OPQ32_64,$coarse64,PQ32x4fsr
+ OPQ16_64,$coarse64,PQ16x4fsr
+ OPQ16_64,$coarse64,PQ16x4fsr,Refine(OPQ56_112,PQ56)
+ "
+
+ for indexkey in $indexkeys
+ do
+ key=autotune.db$db.${indexkey//,/_}
+ key="${key//(/_}"
+ key="${key//)/_}"
+ run_on_1machine $key.e \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey "$indexkey" \
+ --maxtrain 0 \
+ --indexfile $indexdir/$key.faissindex \
+ --searchthreads 32 \
+ --min_test_duration 3 \
+ $( add_precomputed_quantizer $db $coarse ) \
+ --add_bs 1000000 \
+ --autotune_max nprobe:2000
+
+ done
+ done
+done
+
+
+#################################
+# 1B-scale experiment
+
+
+
+for db in deep1B bigann1B; do
+ coarses="
+ IVF1048576_HNSW32
+ IVF4194304_HNSW32
+ IVF4194304(IVF1024,PQHDx4fs,RFlat)
+ "
+ dim=$( get_db_dim $db )
+
+ for coarse in $coarses; do
+
+ replace_coarse_PQHD "$coarse" $dim
+
+
+ indexkeys="
+ OPQ8_64,$coarse64,PQ8
+ OPQ16_64,$coarse64,PQ16x4fsr
+
+ OPQ16_64,$coarse64,PQ16
+ OPQ32_64,$coarse64,PQ32x4fsr
+
+ OPQ32_128,$coarse128,PQ32
+ OPQ64_128,$coarse128,PQ64x4fsr
+
+ OPQ64_128,$coarse128,PQ64
+ OPQ128_256,$coarse256,PQ128x4fsr
+ OPQ56_112,$coarse112,PQ7+56
+ OPQ16_64,$coarse64,PQ16x4fs,Refine(OPQ56_112,PQ56)
+
+ $coarseD,PQ$((dim/2))x4fs
+ "
+
+ for indexkey in $indexkeys
+ do
+ key=autotune.db$db.${indexkey//,/_}
+ key="${key//(/_}"
+ key="${key//)/_}"
+ run_on_1machine $key.d \
+ python -u bench_all_ivf.py \
+ --db $db \
+ --indexkey "$indexkey" \
+ --maxtrain 0 \
+ --indexfile $indexdir/$key.faissindex \
+ --searchthreads 32 \
+ --min_test_duration 3 \
+ $( add_precomputed_quantizer $db $coarse ) \
+ --add_bs 1000000 \
+ --autotune_max nprobe:3000
+ done
+ done
+
+done
+
+fi
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_big_batch_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_big_batch_ivf.py
new file mode 100644
index 0000000..4456a5c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_big_batch_ivf.py
@@ -0,0 +1,109 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import time
+
+import faiss
+
+import numpy as np
+
+from faiss.contrib.datasets import SyntheticDataset
+from faiss.contrib.big_batch_search import big_batch_search
+
+parser = argparse.ArgumentParser()
+
+
+def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+
+group = parser.add_argument_group('dataset options')
+aa('--dim', type=int, default=64)
+aa('--size', default="S")
+
+group = parser.add_argument_group('index options')
+aa('--nlist', type=int, default=100)
+aa('--factory_string', default="", help="overrides nlist")
+aa('--k', type=int, default=10)
+aa('--nprobe', type=int, default=5)
+aa('--nt', type=int, default=-1, help="nb search threads")
+aa('--method', default="pairwise_distances", help="")
+
+args = parser.parse_args()
+print("args:", args)
+
+if args.size == "S":
+ ds = SyntheticDataset(32, 2000, 4000, 1000)
+elif args.size == "M":
+ ds = SyntheticDataset(32, 20000, 40000, 10000)
+elif args.size == "L":
+ ds = SyntheticDataset(32, 200000, 400000, 100000)
+else:
+ raise RuntimeError(f"dataset size {args.size} not supported")
+
+nlist = args.nlist
+nprobe = args.nprobe
+k = args.k
+
+
+def tic(name):
+ global tictoc
+ tictoc = (name, time.time())
+ print(name, end="\r", flush=True)
+
+
+def toc():
+ global tictoc
+ name, t0 = tictoc
+ dt = time.time() - t0
+ print(f"{name}: {dt:.3f} s")
+ return dt
+
+
+print(f"dataset {ds}, {nlist=:} {nprobe=:} {k=:}")
+
+if args.factory_string == "":
+ factory_string = f"IVF{nlist},Flat"
+else:
+ factory_string = args.factory_string
+
+print(f"instantiate {factory_string}")
+index = faiss.index_factory(ds.d, factory_string)
+
+if args.factory_string != "":
+ nlist = index.nlist
+
+print("nlist", nlist)
+
+tic("train")
+index.train(ds.get_train())
+toc()
+
+tic("add")
+index.add(ds.get_database())
+toc()
+
+if args.nt != -1:
+ print("setting nb of threads to", args.nt)
+ faiss.omp_set_num_threads(args.nt)
+
+tic("reference search")
+index.nprobe
+index.nprobe = nprobe
+Dref, Iref = index.search(ds.get_queries(), k)
+t_ref = toc()
+
+tic("block search")
+Dnew, Inew = big_batch_search(
+ index, ds.get_queries(),
+ k, method=args.method, verbose=10
+)
+t_tot = toc()
+
+assert (Inew != Iref).sum() / Iref.size < 1e-4
+np.testing.assert_almost_equal(Dnew, Dref, decimal=4)
+
+print(f"total block search time {t_tot:.3f} s, speedup {t_ref / t_tot:.3f}x")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_cppcontrib_sa_decode.cpp b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_cppcontrib_sa_decode.cpp
new file mode 100644
index 0000000..2de468b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_cppcontrib_sa_decode.cpp
@@ -0,0 +1,1700 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <omp.h>
+
+#include <algorithm>
+#include <chrono>
+#include <iostream>
+#include <memory>
+#include <random>
+#include <thread>
+#include <tuple>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/index_factory.h>
+
+#include <faiss/IndexRowwiseMinMax.h>
+#include <faiss/cppcontrib/SaDecodeKernels.h>
+
+// train a dataset
+std::tuple<std::shared_ptr<faiss::Index>, std::vector<uint8_t>> trainDataset(
+ const std::vector<float>& input,
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description) {
+ //
+ omp_set_num_threads(std::thread::hardware_concurrency());
+
+ // train an index
+ auto index = std::shared_ptr<faiss::Index>(
+ faiss::index_factory((int)d, description.c_str()));
+ index->train((int)n, input.data());
+
+ // encode
+ const size_t codeSize = index->sa_code_size();
+
+ std::vector<uint8_t> encodedData(n * codeSize);
+ index->sa_encode(n, input.data(), encodedData.data());
+
+ return std::make_tuple(std::move(index), std::move(encodedData));
+}
+
+// generate a dataset
+std::vector<float> generate(const size_t n, const size_t d) {
+ std::vector<float> data(n * d);
+
+ std::minstd_rand rng(345);
+ std::uniform_real_distribution<float> ux(0, 1);
+
+ //
+ for (size_t k = 0; k < n; k++) {
+ for (size_t j = 0; j < d; j++) {
+ data[k * d + j] = ux(rng);
+ }
+ }
+
+ return data;
+}
+
+double getError(
+ const uint64_t n,
+ const uint64_t d,
+ const std::vector<float>& v1,
+ const std::vector<float>& v2) {
+ double error = 0;
+ for (uint64_t i = 0; i < n; i++) {
+ double localError = 0;
+ for (uint64_t j = 0; j < d; j++) {
+ double q = v1[i * d + j] - v2[i * d + j];
+ localError += q * q;
+ }
+
+ error += localError;
+ }
+
+ return error;
+}
+
+// a timer
+struct StopWatch {
+ using timepoint_t = std::chrono::time_point<std::chrono::steady_clock>;
+
+ timepoint_t Start;
+
+ //
+ StopWatch() {
+ Start = std::chrono::steady_clock::now();
+ }
+
+ //
+ double elapsed() const {
+ const auto now = std::chrono::steady_clock::now();
+ std::chrono::duration<double> elapsed = now - Start;
+ return elapsed.count();
+ }
+};
+
+//
+bool testIfIVFPQ(
+ const faiss::Index* const index,
+ const float** pqCoarseCentroidsQ,
+ const float** pqFineCentroidsQ) {
+ if (pqFineCentroidsQ == nullptr || pqCoarseCentroidsQ == nullptr) {
+ return false;
+ }
+
+ const faiss::IndexIVFPQ* const indexQ =
+ dynamic_cast<const faiss::IndexIVFPQ*>(index);
+ if (indexQ == nullptr) {
+ return false;
+ }
+
+ const auto coarseIndexQ =
+ dynamic_cast<const faiss::IndexFlatCodes*>(indexQ->quantizer);
+ if (coarseIndexQ == nullptr) {
+ return false;
+ }
+
+ *pqFineCentroidsQ = indexQ->pq.centroids.data();
+ *pqCoarseCentroidsQ =
+ reinterpret_cast<const float*>(coarseIndexQ->codes.data());
+ return true;
+}
+
+bool testIfResidualPQ(
+ const faiss::Index* const index,
+ const float** pqCoarseCentroidsQ,
+ const float** pqFineCentroidsQ) {
+ if (pqFineCentroidsQ == nullptr || pqCoarseCentroidsQ == nullptr) {
+ return false;
+ }
+
+ const faiss::Index2Layer* const indexQ =
+ dynamic_cast<const faiss::Index2Layer*>(index);
+ if (indexQ == nullptr) {
+ return false;
+ }
+
+ const auto coarseIndexQ = dynamic_cast<const faiss::MultiIndexQuantizer*>(
+ indexQ->q1.quantizer);
+ if (coarseIndexQ == nullptr) {
+ return false;
+ }
+
+ *pqFineCentroidsQ = indexQ->pq.centroids.data();
+ *pqCoarseCentroidsQ = coarseIndexQ->pq.centroids.data();
+ return true;
+}
+
+//
+template <typename T>
+static void verifyIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData,
+ const uint64_t nIterations) {
+ //
+ const float* pqFineCentroidsQ = nullptr;
+ const float* pqCoarseCentroidsQ = nullptr;
+
+ //
+ testIfIVFPQ(index.get(), &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+ testIfResidualPQ(index.get(), &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ // initialize the random engine
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // use 1 thread
+ omp_set_num_threads(1);
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // sequential order
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ index->sa_decode(n, encodedData.data(), outputFaiss.data());
+ }
+ double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (int iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ T::store(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_seq\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random order
+
+ // generate a random order of points
+ std::uniform_int_distribution<uint64_t> un(0, n - 1);
+ std::vector<uint64_t> pointIncidesToDecode(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ pointIncidesToDecode[i] = un(rng);
+ }
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ outputFaiss.data() + i * d);
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ T::store(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ const double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ const double error = getError(n, d, outputFaiss, outputKernel1);
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random accumulate
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+ std::vector<float> outputKernel2(n * d, 0);
+ std::vector<float> outputKernel2u(n * d, 0);
+ std::vector<float> outputKernel3(n * d, 0);
+ std::vector<float> outputKernel3u(n * d, 0);
+
+ // a temporary buffer for faiss
+ std::vector<float> tempFaiss(d, 0);
+
+ // random weights
+ std::vector<float> weights(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ weights[i] = u(rng);
+ }
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ tempFaiss.data());
+ for (uint64_t j = 0; j < d; j++)
+ outputFaiss[i * d + j] += weight * tempFaiss[j];
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels: accum 1 point
+ StopWatch swKernel1;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ weight,
+ outputKernel1.data() + i * d);
+ }
+ }
+ const double timeKernel1 = swKernel1.elapsed();
+
+ // evaluate the error
+ const double error1 = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel1
+ << "\t" << error1 << std::endl;
+
+ // kernels: accum 2 points, shared centroids
+ StopWatch swKernel2;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2.data() + i * d);
+ }
+ }
+ const double timeKernel2 = swKernel2.elapsed();
+
+ // evaluate the error
+ const double error2 = getError(n, d, outputFaiss, outputKernel2);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2
+ << "\t" << error2 << std::endl;
+
+ // kernels: accum 2 points, unique centroids
+ StopWatch swKernel2u;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2u.data() + i * d);
+ }
+ }
+ const double timeKernel2u = swKernel2u.elapsed();
+
+ // evaluate the error
+ const double error2u = getError(n, d, outputFaiss, outputKernel2u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2u
+ << "\t" << error2u << std::endl;
+
+ // kernels: accum 3 points, shared centroids
+ StopWatch swKernel3;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3.data() + i * d);
+ }
+ }
+ const double timeKernel3 = swKernel3.elapsed();
+
+ // evaluate the error
+ const double error3 = getError(n, d, outputFaiss, outputKernel3);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3
+ << "\t" << error3 << std::endl;
+
+ // kernels: accum 3 points, unique centroids
+ StopWatch swKernel3u;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3u.data() + i * d);
+ }
+ }
+ const double timeKernel3u = swKernel3u.elapsed();
+
+ // evaluate the error
+ const double error3u = getError(n, d, outputFaiss, outputKernel3u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3u
+ << "\t" << error3u << std::endl;
+ }
+}
+
+//
+template <typename T>
+static void verifyMinMaxIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData,
+ const uint64_t nIterations) {
+ //
+ const float* pqFineCentroidsQ = nullptr;
+ const float* pqCoarseCentroidsQ = nullptr;
+
+ // extract an index that is wrapped with IndexRowwiseMinMaxBase
+ const std::shared_ptr<faiss::IndexRowwiseMinMaxBase> indexMinMax =
+ std::dynamic_pointer_cast<faiss::IndexRowwiseMinMaxBase>(index);
+
+ auto subIndex = indexMinMax->index;
+
+ //
+ testIfIVFPQ(subIndex, &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+ testIfResidualPQ(subIndex, &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ // initialize the random engine
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // use 1 thread
+ omp_set_num_threads(1);
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // sequential order
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ index->sa_decode(n, encodedData.data(), outputFaiss.data());
+ }
+ double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (int iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ T::store(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_seq\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random order
+
+ // generate a random order of points
+ std::uniform_int_distribution<uint64_t> un(0, n - 1);
+ std::vector<uint64_t> pointIncidesToDecode(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ pointIncidesToDecode[i] = un(rng);
+ }
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ outputFaiss.data() + i * d);
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ T::store(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ const double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ const double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random accumulate
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+ std::vector<float> outputKernel2(n * d, 0);
+ std::vector<float> outputKernel2u(n * d, 0);
+ std::vector<float> outputKernel3(n * d, 0);
+ std::vector<float> outputKernel3u(n * d, 0);
+
+ // a temporary buffer for faiss
+ std::vector<float> tempFaiss(d, 0);
+
+ // random weights
+ std::vector<float> weights(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ weights[i] = u(rng);
+ }
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ tempFaiss.data());
+ for (uint64_t j = 0; j < d; j++) {
+ outputFaiss[i * d + j] += weight * tempFaiss[j];
+ }
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels: accum 1 point
+ StopWatch swKernel1;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ weight,
+ outputKernel1.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel1[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel1 = swKernel1.elapsed();
+
+ // evaluate the error
+ const double error1 = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel1
+ << "\t" << error1 << std::endl;
+
+ // kernels: accum 2 points, shared centroids
+ StopWatch swKernel2;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel2[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel2 = swKernel2.elapsed();
+
+ // evaluate the error
+ const double error2 = getError(n, d, outputFaiss, outputKernel2);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2
+ << "\t" << error2 << std::endl;
+
+ // kernels: accum 2 points, unique centroids
+ StopWatch swKernel2u;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2u.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel2u[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel2u = swKernel2u.elapsed();
+
+ // evaluate the error
+ const double error2u = getError(n, d, outputFaiss, outputKernel2u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2u
+ << "\t" << error2u << std::endl;
+
+ // kernels: accum 3 points, shared centroids
+ StopWatch swKernel3;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel3[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel3 = swKernel3.elapsed();
+
+ // evaluate the error
+ const double error3 = getError(n, d, outputFaiss, outputKernel3);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3
+ << "\t" << error3 << std::endl;
+
+ // kernels: accum 3 points, unique centroids
+ StopWatch swKernel3u;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3u.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel3u[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel3u = swKernel3u.elapsed();
+
+ // evaluate the error
+ const double error3u = getError(n, d, outputFaiss, outputKernel3u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3u
+ << "\t" << error3u << std::endl;
+ }
+}
+
+//
+template <typename T>
+static void verifyIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData,
+ const uint64_t nIterations) {
+ //
+ const faiss::IndexPQ* const indexQ =
+ dynamic_cast<const faiss::IndexPQ*>(index.get());
+ const float* const pqFineCentroidsQ = indexQ->pq.centroids.data();
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ // initialize the random engine
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // use 1 thread
+ omp_set_num_threads(1);
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // sequential order
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ index->sa_decode(n, encodedData.data(), outputFaiss.data());
+ }
+ double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (int iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ T::store(
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_seq\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random order
+
+ // generate a random order of points
+ std::uniform_int_distribution<uint64_t> un(0, n - 1);
+ std::vector<uint64_t> pointIncidesToDecode(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ pointIncidesToDecode[i] = un(rng);
+ }
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ outputFaiss.data() + i * d);
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ T::store(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ const double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ const double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random accumulate
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+ std::vector<float> outputKernel2(n * d, 0);
+ std::vector<float> outputKernel2u(n * d, 0);
+ std::vector<float> outputKernel3(n * d, 0);
+ std::vector<float> outputKernel3u(n * d, 0);
+
+ // a temporary buffer for faiss
+ std::vector<float> tempFaiss(d, 0);
+
+ // random weights
+ std::vector<float> weights(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ weights[i] = u(rng);
+ }
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ tempFaiss.data());
+ for (uint64_t j = 0; j < d; j++) {
+ outputFaiss[i * d + j] += weight * tempFaiss[j];
+ }
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels: accum 1 point
+ StopWatch swKernel1;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ weight,
+ outputKernel1.data() + i * d);
+ }
+ }
+ const double timeKernel1 = swKernel1.elapsed();
+
+ // evaluate the error
+ const double error1 = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel1
+ << "\t" << error1 << std::endl;
+
+ // kernels: accum 2 points, shared centroids
+ StopWatch swKernel2;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2.data() + i * d);
+ }
+ }
+ const double timeKernel2 = swKernel2.elapsed();
+
+ // evaluate the error
+ const double error2 = getError(n, d, outputFaiss, outputKernel2);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2
+ << "\t" << error2 << std::endl;
+
+ // kernels: accum 2 points, unique centroids
+ StopWatch swKernel2u;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2u.data() + i * d);
+ }
+ }
+ const double timeKernel2u = swKernel2u.elapsed();
+
+ // evaluate the error
+ const double error2u = getError(n, d, outputFaiss, outputKernel2u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2u
+ << "\t" << error2u << std::endl;
+
+ // kernels: accum 3 points, shared centroids
+ StopWatch swKernel3;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3.data() + i * d);
+ }
+ }
+ const double timeKernel3 = swKernel3.elapsed();
+
+ // evaluate the error
+ const double error3 = getError(n, d, outputFaiss, outputKernel3);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3
+ << "\t" << error3 << std::endl;
+
+ // kernels: accum 3 points, unique centroids
+ StopWatch swKernel3u;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3u.data() + i * d);
+ }
+ }
+ const double timeKernel3u = swKernel3u.elapsed();
+
+ // evaluate the error
+ const double error3u = getError(n, d, outputFaiss, outputKernel3u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3u
+ << "\t" << error3u << std::endl;
+ }
+}
+
+//
+template <typename T>
+static void verifyMinMaxIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData,
+ const uint64_t nIterations) {
+ // extract an index that is wrapped with IndexRowwiseMinMaxBase
+ const std::shared_ptr<faiss::IndexRowwiseMinMaxBase> indexMinMax =
+ std::dynamic_pointer_cast<faiss::IndexRowwiseMinMaxBase>(index);
+
+ auto subIndex = indexMinMax->index;
+
+ //
+ const faiss::IndexPQ* const indexQ =
+ dynamic_cast<const faiss::IndexPQ*>(subIndex);
+ const float* const pqFineCentroidsQ = indexQ->pq.centroids.data();
+
+ //
+ const size_t codeSize = index->sa_code_size();
+ // initialize the random engine
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // use 1 thread
+ omp_set_num_threads(1);
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // sequential order
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ index->sa_decode(n, encodedData.data(), outputFaiss.data());
+ }
+ double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (int iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ T::store(
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_seq\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random order
+
+ // generate a random order of points
+ std::uniform_int_distribution<uint64_t> un(0, n - 1);
+ std::vector<uint64_t> pointIncidesToDecode(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ pointIncidesToDecode[i] = un(rng);
+ }
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ outputFaiss.data() + i * d);
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels
+ StopWatch swKernel;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ for (uint64_t i = 0; i < n; i++) {
+ const auto pointIdx = pointIncidesToDecode[i + iter * n];
+ T::store(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ outputKernel1.data() + i * d);
+ }
+ }
+ const double timeKernel = swKernel.elapsed();
+
+ // evaluate the error
+ const double error = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\tstore_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel
+ << "\t" << error << std::endl;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////////////
+ // random accumulate
+
+ {
+ std::vector<float> outputFaiss(n * d, 0);
+ std::vector<float> outputKernel1(n * d, 0);
+ std::vector<float> outputKernel2(n * d, 0);
+ std::vector<float> outputKernel2u(n * d, 0);
+ std::vector<float> outputKernel3(n * d, 0);
+ std::vector<float> outputKernel3u(n * d, 0);
+
+ // a temporary buffer for faiss
+ std::vector<float> tempFaiss(d, 0);
+
+ // random weights
+ std::vector<float> weights(nIterations * n, 0);
+ for (uint64_t i = 0; i < nIterations * n; i++) {
+ weights[i] = u(rng);
+ }
+
+ // faiss
+ StopWatch swFaiss;
+ for (uint64_t i = 0; i < n; i++) {
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ index->sa_decode(
+ 1,
+ encodedData.data() + pointIdx * codeSize,
+ tempFaiss.data());
+ for (uint64_t j = 0; j < d; j++) {
+ outputFaiss[i * d + j] += weight * tempFaiss[j];
+ }
+ }
+ }
+ const double timeFaiss = swFaiss.elapsed();
+
+ // kernels: accum 1 point
+ StopWatch swKernel1;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter++) {
+ const auto pointIdx =
+ pointIncidesToDecode[i * nIterations + iter];
+ const auto weight = weights[i * nIterations + iter];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx * codeSize,
+ weight,
+ outputKernel1.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel1[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel1 = swKernel1.elapsed();
+
+ // evaluate the error
+ const double error1 = getError(n, d, outputFaiss, outputKernel1);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel1
+ << "\t" << error1 << std::endl;
+
+ // kernels: accum 2 points, shared centroids
+ StopWatch swKernel2;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel2[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel2 = swKernel2.elapsed();
+
+ // evaluate the error
+ const double error2 = getError(n, d, outputFaiss, outputKernel2);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2
+ << "\t" << error2 << std::endl;
+
+ // kernels: accum 2 points, unique centroids
+ StopWatch swKernel2u;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 2) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ outputKernel2u.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel2u[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel2u = swKernel2u.elapsed();
+
+ // evaluate the error
+ const double error2u = getError(n, d, outputFaiss, outputKernel2u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum2u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel2u
+ << "\t" << error2u << std::endl;
+
+ // kernels: accum 3 points, shared centroids
+ StopWatch swKernel3;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel3[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel3 = swKernel3.elapsed();
+
+ // evaluate the error
+ const double error3 = getError(n, d, outputFaiss, outputKernel3);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3
+ << "\t" << error3 << std::endl;
+
+ // kernels: accum 3 points, unique centroids
+ StopWatch swKernel3u;
+ for (uint64_t i = 0; i < n; i++) {
+ float outputAccumMin = 0;
+ for (uint64_t iter = 0; iter < nIterations; iter += 3) {
+ const auto pointIdx0 =
+ pointIncidesToDecode[i * nIterations + iter + 0];
+ const auto weight0 = weights[i * nIterations + iter + 0];
+ const auto pointIdx1 =
+ pointIncidesToDecode[i * nIterations + iter + 1];
+ const auto weight1 = weights[i * nIterations + iter + 1];
+ const auto pointIdx2 =
+ pointIncidesToDecode[i * nIterations + iter + 2];
+ const auto weight2 = weights[i * nIterations + iter + 2];
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx0 * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx1 * codeSize,
+ weight1,
+ pqFineCentroidsQ,
+ encodedData.data() + pointIdx2 * codeSize,
+ weight2,
+ outputKernel3u.data() + i * d,
+ outputAccumMin);
+ }
+ for (uint64_t j = 0; j < d; j++) {
+ outputKernel3u[i * d + j] += outputAccumMin;
+ }
+ }
+ const double timeKernel3u = swKernel3u.elapsed();
+
+ // evaluate the error
+ const double error3u = getError(n, d, outputFaiss, outputKernel3u);
+
+ std::cout << description << "\t" << n << "\t" << d << "\taccum3u_rnd\t"
+ << nIterations << "\t" << timeFaiss << "\t" << timeKernel3u
+ << "\t" << error3u << std::endl;
+ }
+}
+
+template <typename T>
+void testIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const uint64_t nIterations) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyIndex2LevelDecoder<T>(
+ n, d, description, index, encodedData, nIterations);
+}
+
+template <typename T>
+void testMinMaxIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const uint64_t nIterations) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyMinMaxIndex2LevelDecoder<T>(
+ n, d, description, index, encodedData, nIterations);
+}
+
+template <typename T>
+void testIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const uint64_t nIterations) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyIndexPQDecoder<T>(n, d, description, index, encodedData, nIterations);
+}
+
+template <typename T>
+void testMinMaxIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description,
+ const uint64_t nIterations) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyMinMaxIndexPQDecoder<T>(
+ n, d, description, index, encodedData, nIterations);
+}
+
+//
+int main(int argc, char** argv) {
+ // 1 MB points
+ const uint64_t INDEX_SIZE = 65536 * 16;
+ const uint64_t N_ITERATIONS = 18;
+
+ static_assert(
+ (N_ITERATIONS % 6) == 0, "Number of iterations should be 6*x");
+
+ // print the header
+ auto delim = "\t";
+ std::cout << "Codec" << delim << "n" << delim << "d" << delim
+ << "Experiment" << delim << "Iterations" << delim << "Faiss time"
+ << delim << "SADecodeKernel time" << delim << "Error"
+ << std::endl;
+
+ // The following experiment types are available:
+ // * store_seq - decode a contiguous block of codes into vectors, one by one
+ // * store_rnd - decode a contiguous block of codes into vectors in a random
+ // order
+ // * accum_rnd - create a linear combination from decoded vectors,
+ // random order
+ // * accum2_rnd - create a linear combination from decoded vectors,
+ // random order, decode 2 codes per call, centroid tables are shared
+ // * accum2u_rnd - create a linear combination from decoded vectors,
+ // random order, decode 2 codes per call, centroid tables are not shared
+ // * accum3_rnd - create a linear combination from decoded vectors,
+ // random order, decode 3 codes per call, centroid tables are shared
+ // * accum3u_rnd - create a linear combination from decoded vectors,
+ // random order, decode 3 codes per call, centroid tables are not shared
+ //
+ // It is expected that:
+ // * store_seq is faster than store_rnd
+ // * accum2 is faster than accum
+ // * accum3 is faster than accum2
+
+ // test plain PQx8
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 2>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ64np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 4>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ32np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 8>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ16np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 16>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ8np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 32>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ4np", N_ITERATIONS);
+ }
+
+ // test PQx10
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 2, 10>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ64x10np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 4, 10>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ32x10np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 8, 10>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ16x10np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 16, 10>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ8x10np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::IndexPQDecoder<128, 32, 10>;
+ testIndexPQDecoder<T>(INDEX_SIZE, 128, "PQ4x10np", N_ITERATIONS);
+ }
+
+ // test MinMaxFP16,PQx8
+ {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<128, 2>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,PQ64np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<128, 4>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,PQ32np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<128, 8>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,PQ16np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<128, 16>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,PQ8np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<128, 32>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,PQ4np", N_ITERATIONS);
+ }
+
+ // test IVFPQ
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 2>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "IVF256,PQ64np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 4>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "IVF256,PQ32np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 8>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "IVF256,PQ16np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 16>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "IVF256,PQ8np", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 32>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "IVF256,PQ4np", N_ITERATIONS);
+ }
+
+ // test Residual,PQ
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 2>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual4x8,PQ64", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 4>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual4x8,PQ32", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 8>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual4x8,PQ16", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 16>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual4x8,PQ8", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 32>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual4x8,PQ4", N_ITERATIONS);
+ }
+
+ // test MinMaxFP16,IVFPQ
+ {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<128, 128, 2>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,IVF256,PQ64np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<128, 128, 4>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,IVF256,PQ32np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<128, 128, 8>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,IVF256,PQ16np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<128, 128, 16>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,IVF256,PQ8np", N_ITERATIONS);
+ }
+ {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<128, 128, 32>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "MinMaxFP16,IVF256,PQ4np", N_ITERATIONS);
+ }
+
+ // test Residual,PQ with unusual bits
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 2, 16, 10>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual1x10,PQ64x10", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 4, 16, 10>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual1x10,PQ32x10", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 8, 16, 10>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual1x10,PQ16x10", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 16, 16, 10>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual1x10,PQ8x10", N_ITERATIONS);
+ }
+ {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 32, 16, 10>;
+ testIndex2LevelDecoder<T>(
+ INDEX_SIZE, 128, "Residual1x10,PQ4x10", N_ITERATIONS);
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_for_interrupt.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_for_interrupt.py
new file mode 100644
index 0000000..e3a1228
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_for_interrupt.py
@@ -0,0 +1,154 @@
+#! /usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import numpy as np
+import faiss
+import time
+import os
+import argparse
+
+
+parser = argparse.ArgumentParser()
+
+def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+group = parser.add_argument_group('dataset options')
+aa('--dim', type=int, default=64)
+aa('--nb', type=int, default=int(1e6))
+aa('--subset_len', type=int, default=int(1e5))
+aa('--key', default='IVF1000,Flat')
+aa('--nprobe', type=int, default=640)
+aa('--no_intcallback', default=False, action='store_true')
+aa('--twostage', default=False, action='store_true')
+aa('--nt', type=int, default=-1)
+
+
+args = parser.parse_args()
+print("args:", args)
+
+
+d = args.dim # dimension
+nb = args.nb # database size
+nq = 1000 # nb of queries
+nt = 100000
+subset_len = args.subset_len
+
+
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32')
+xq = np.random.random((nq, d)).astype('float32')
+xt = np.random.random((nt, d)).astype('float32')
+k = 100
+
+if args.no_intcallback:
+ faiss.InterruptCallback.clear_instance()
+
+if args.nt != -1:
+ faiss.omp_set_num_threads(args.nt)
+
+nprobe = args.nprobe
+key = args.key
+#key = 'IVF1000,Flat'
+# key = 'IVF1000,PQ64'
+# key = 'IVF100_HNSW32,PQ64'
+
+# faiss.omp_set_num_threads(1)
+
+pf = 'dim%d_' % d
+if d == 64:
+ pf = ''
+
+basename = '/tmp/base%s%s.index' % (pf, key)
+
+if os.path.exists(basename):
+ print('load', basename)
+ index_1 = faiss.read_index(basename)
+else:
+ print('train + write', basename)
+ index_1 = faiss.index_factory(d, key)
+ index_1.train(xt)
+ faiss.write_index(index_1, basename)
+
+print('add')
+index_1.add(xb)
+
+print('set nprobe=', nprobe)
+faiss.ParameterSpace().set_index_parameter(index_1, 'nprobe', nprobe)
+
+class ResultHeap:
+ """ Combine query results from a sliced dataset """
+
+ def __init__(self, nq, k):
+ " nq: number of query vectors, k: number of results per query "
+ self.I = np.zeros((nq, k), dtype='int64')
+ self.D = np.zeros((nq, k), dtype='float32')
+ self.nq, self.k = nq, k
+ heaps = faiss.float_maxheap_array_t()
+ heaps.k = k
+ heaps.nh = nq
+ heaps.val = faiss.swig_ptr(self.D)
+ heaps.ids = faiss.swig_ptr(self.I)
+ heaps.heapify()
+ self.heaps = heaps
+
+ def add_batch_result(self, D, I, i0):
+ assert D.shape == (self.nq, self.k)
+ assert I.shape == (self.nq, self.k)
+ I += i0
+ self.heaps.addn_with_ids(
+ self.k, faiss.swig_ptr(D),
+ faiss.swig_ptr(I), self.k)
+
+ def finalize(self):
+ self.heaps.reorder()
+
+stats = faiss.cvar.indexIVF_stats
+stats.reset()
+
+print('index size', index_1.ntotal,
+ 'imbalance', index_1.invlists.imbalance_factor())
+start = time.time()
+Dref, Iref = index_1.search(xq, k)
+print('time of searching: %.3f s = %.3f + %.3f ms' % (
+ time.time() - start, stats.quantization_time, stats.search_time))
+
+indexes = {}
+if args.twostage:
+
+ for i in range(0, nb, subset_len):
+ index = faiss.read_index(basename)
+ faiss.ParameterSpace().set_index_parameter(index, 'nprobe', nprobe)
+ print("add %d:%d" %(i, i+subset_len))
+ index.add(xb[i:i + subset_len])
+ indexes[i] = index
+
+rh = ResultHeap(nq, k)
+sum_time = tq = ts = 0
+for i in range(0, nb, subset_len):
+ if not args.twostage:
+ index = faiss.read_index(basename)
+ faiss.ParameterSpace().set_index_parameter(index, 'nprobe', nprobe)
+ print("add %d:%d" %(i, i+subset_len))
+ index.add(xb[i:i + subset_len])
+ else:
+ index = indexes[i]
+
+ stats.reset()
+ start = time.time()
+ Di, Ii = index.search(xq, k)
+ sum_time = sum_time + time.time() - start
+ tq += stats.quantization_time
+ ts += stats.search_time
+ rh.add_batch_result(Di, Ii, i)
+
+print('time of searching separately: %.3f s = %.3f + %.3f ms' %
+ (sum_time, tq, ts))
+
+rh.finalize()
+
+print('diffs: %d / %d' % ((Iref != rh.I).sum(), Iref.size))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/__init__.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/benchmark.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/benchmark.py
new file mode 100644
index 0000000..20a0cd8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/benchmark.py
@@ -0,0 +1,1219 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+from dataclasses import dataclass, field
+from operator import itemgetter
+from statistics import mean, median
+from typing import Any, Dict, List, Optional
+
+import faiss # @manual=//faiss/python:pyfaiss
+
+import numpy as np
+
+from scipy.optimize import curve_fit
+
+from .benchmark_io import BenchmarkIO
+
+from .descriptors import (
+ CodecDescriptor,
+ DatasetDescriptor,
+ IndexDescriptor,
+ IndexDescriptorClassic,
+ KnnDescriptor,
+)
+
+from .index import Index, IndexFromCodec, IndexFromFactory
+
+from .utils import dict_merge
+
+logger = logging.getLogger(__name__)
+
+
+def range_search_pr_curve(
+ dist_ann: np.ndarray, metric_score: np.ndarray, gt_rsm: float
+):
+ assert dist_ann.shape == metric_score.shape
+ assert dist_ann.ndim == 1
+ l = len(dist_ann)
+ if l == 0:
+ return {
+ "dist_ann": [],
+ "metric_score_sample": [],
+ "cum_score": [],
+ "precision": [],
+ "recall": [],
+ "unique_key": [],
+ }
+ sort_by_dist_ann = dist_ann.argsort()
+ dist_ann = dist_ann[sort_by_dist_ann]
+ metric_score = metric_score[sort_by_dist_ann]
+ cum_score = np.cumsum(metric_score)
+ precision = cum_score / np.arange(1, len(cum_score) + 1)
+ recall = cum_score / gt_rsm
+ unique_key = np.round(precision * 100) * 100 + np.round(recall * 100)
+ tbl = np.vstack(
+ [dist_ann, metric_score, cum_score, precision, recall, unique_key]
+ )
+ group_by_dist_max_cum_score = np.empty(l, bool)
+ group_by_dist_max_cum_score[-1] = True
+ group_by_dist_max_cum_score[:-1] = dist_ann[1:] != dist_ann[:-1]
+ tbl = tbl[:, group_by_dist_max_cum_score]
+ _, unique_key_idx = np.unique(tbl[5], return_index=True)
+ dist_ann, metric_score, cum_score, precision, recall, unique_key = tbl[
+ :, np.sort(unique_key_idx)
+ ].tolist()
+ return {
+ "dist_ann": dist_ann,
+ "metric_score_sample": metric_score,
+ "cum_score": cum_score,
+ "precision": precision,
+ "recall": recall,
+ "unique_key": unique_key,
+ }
+
+
+def optimizer(op, search, cost_metric, perf_metric):
+ totex = op.num_experiments()
+ rs = np.random.RandomState(123)
+ if totex > 1:
+ experiments = rs.permutation(totex - 2) + 1
+ experiments = [0, totex - 1] + list(experiments)
+ else:
+ experiments = [0]
+
+ print(f"total nb experiments {totex}, running {len(experiments)}")
+
+ for cno in experiments:
+ key = op.cno_to_key(cno)
+ parameters = op.get_parameters(key)
+
+ (max_perf, min_cost) = op.predict_bounds(key)
+ if not op.is_pareto_optimal(max_perf, min_cost):
+ logger.info(
+ f"{cno=:4d} {str(parameters):50}: SKIP, {max_perf=:.3f} {min_cost=:.3f}",
+ )
+ continue
+
+ logger.info(f"{cno=:4d} {str(parameters):50}: RUN")
+ cost, perf, requires = search(
+ parameters,
+ cost_metric,
+ perf_metric,
+ )
+ if requires is not None:
+ return requires
+ logger.info(
+ f"{cno=:4d} {str(parameters):50}: DONE, {cost=:.3f} {perf=:.3f}"
+ )
+ op.add_operating_point(key, perf, cost)
+ return None
+
+
+# range_metric possible values:
+#
+# radius
+# [0..radius) -> 1
+# [radius..inf) -> 0
+#
+# [[radius1, score1], ...]
+# [0..radius1) -> score1
+# [radius1..radius2) -> score2
+#
+# [[radius1_from, radius1_to, score1], ...]
+# [radius1_from, radius1_to) -> score1,
+# [radius2_from, radius2_to) -> score2
+def get_range_search_metric_function(range_metric, D, R):
+ if D is not None:
+ assert R is not None
+ assert D.shape == R.shape
+ if isinstance(range_metric, list):
+ aradius, ascore, aradius_from, aradius_to = [], [], [], []
+ radius_to = 0
+ for rsd in range_metric:
+ assert isinstance(rsd, list)
+ if len(rsd) == 3:
+ radius_from, radius_to, score = rsd
+ elif len(rsd) == 2:
+ radius_from = radius_to
+ radius_to, score = rsd
+ else:
+ raise AssertionError(f"invalid range definition {rsd}")
+ # radius_from and radius_to are compressed distances,
+ # we need to convert them to real embedding distances.
+ if D is not None:
+ sample_idxs = np.argwhere((D <= radius_to) & (D > radius_from))
+ assert len(sample_idxs) > 0
+ real_radius = np.mean(R[sample_idxs]).item()
+ else:
+ real_radius = mean([radius_from, radius_to])
+ logger.info(
+ f"range_search_metric_function {radius_from=} {radius_to=} {real_radius=} {score=}"
+ )
+ aradius.append(real_radius)
+ ascore.append(score)
+ aradius_from.append(radius_from)
+ aradius_to.append(radius_to)
+
+ def sigmoid(x, a, b, c):
+ return a / (1 + np.exp(b * x - c))
+
+ cutoff = max(aradius)
+ popt, _ = curve_fit(sigmoid, aradius, ascore, [1, 5, 5])
+
+ for r in np.arange(0, cutoff + 0.05, 0.05):
+ logger.info(
+ f"range_search_metric_function {r=} {sigmoid(r, *popt)=}"
+ )
+
+ assert isinstance(cutoff, float)
+ return (
+ cutoff,
+ lambda x: np.where(x < cutoff, sigmoid(x, *popt), 0),
+ popt.tolist(),
+ list(zip(aradius, ascore, aradius_from, aradius_to, strict=True)),
+ )
+ else:
+ # Assuming that the range_metric is a float,
+ # so the range is [0..range_metric).
+ # D is the result of a range_search with a radius of range_metric,
+ # but both range_metric and D may be compressed distances.
+ # We approximate the real embedding distance as max(R).
+ if R is not None:
+ real_range = np.max(R).item()
+ else:
+ real_range = range_metric
+ logger.info(
+ f"range_search_metric_function {range_metric=} {real_range=}"
+ )
+ assert isinstance(real_range, float)
+ return real_range * 2, lambda x: np.where(x < real_range, 1, 0), [], []
+
+
+@dataclass
+class IndexOperator:
+ num_threads: int
+ distance_metric: str
+
+ def __post_init__(self):
+ if self.distance_metric == "IP":
+ self.distance_metric_type = faiss.METRIC_INNER_PRODUCT
+ elif self.distance_metric == "L2":
+ self.distance_metric_type = faiss.METRIC_L2
+ else:
+ raise ValueError
+
+ def set_io(self, benchmark_io: BenchmarkIO):
+ self.io = benchmark_io
+ self.io.distance_metric = self.distance_metric
+ self.io.distance_metric_type = self.distance_metric_type
+
+
+@dataclass
+class TrainOperator(IndexOperator):
+ codec_descs: List[CodecDescriptor] = field(default_factory=lambda: [])
+ assemble_opaque: bool = True
+
+ def get_desc(self, name: str) -> Optional[CodecDescriptor]:
+ for desc in self.codec_descs:
+ if desc.get_name() == name:
+ return desc
+ elif desc.factory == name:
+ return desc
+ return None
+
+ def get_flat_desc(self, name=None) -> Optional[CodecDescriptor]:
+ for desc in self.codec_descs:
+ desc_name = desc.get_name()
+ if desc_name == name:
+ return desc
+ if desc_name.startswith("Flat"):
+ return desc
+ return None
+
+ def build_index_wrapper(self, codec_desc: CodecDescriptor):
+ if hasattr(codec_desc, "index"):
+ return
+
+ if codec_desc.factory is not None:
+ assert (
+ codec_desc.factory == "Flat" or codec_desc.training_vectors is not None
+ )
+ index = IndexFromFactory(
+ num_threads=self.num_threads,
+ d=codec_desc.d,
+ metric=self.distance_metric,
+ construction_params=codec_desc.construction_params,
+ factory=codec_desc.factory,
+ training_vectors=codec_desc.training_vectors,
+ codec_name=codec_desc.get_name(),
+ assemble_opaque=self.assemble_opaque,
+ )
+ index.set_io(self.io)
+ codec_desc.index = index
+ else:
+ assert codec_desc.is_trained()
+
+ def train_one(
+ self, codec_desc: CodecDescriptor, results: Dict[str, Any], dry_run=False
+ ):
+ faiss.omp_set_num_threads(codec_desc.num_threads)
+ self.build_index_wrapper(codec_desc)
+ if codec_desc.is_trained():
+ return results, None
+
+ if dry_run:
+ meta, requires = codec_desc.index.fetch_meta(dry_run=dry_run)
+ else:
+ codec_desc.index.get_codec()
+ meta, requires = codec_desc.index.fetch_meta(dry_run=dry_run)
+ assert requires is None
+
+ if requires is None:
+ results["indices"][codec_desc.get_name()] = meta
+ return results, requires
+
+ def train(self, results, dry_run=False):
+ for desc in self.codec_descs:
+ results, requires = self.train_one(desc, results, dry_run=dry_run)
+ if dry_run:
+ if requires is None:
+ continue
+ return results, requires
+ assert requires is None
+ return results, None
+
+
+@dataclass
+class BuildOperator(IndexOperator):
+ index_descs: List[IndexDescriptor] = field(default_factory=lambda: [])
+ serialize_index: bool = False
+
+ def get_desc(self, name: str) -> Optional[IndexDescriptor]:
+ for desc in self.index_descs:
+ if desc.get_name() == name:
+ return desc
+ return None
+
+ def get_flat_desc(self, name=None) -> Optional[IndexDescriptor]:
+ for desc in self.index_descs:
+ desc_name = desc.get_name()
+ if desc_name == name:
+ return desc
+ if desc_name.startswith("Flat"):
+ return desc
+ return None
+
+ def build_index_wrapper(self, index_desc: IndexDescriptor):
+ if hasattr(index_desc, "index"):
+ return
+
+ if hasattr(index_desc.codec_desc, "index"):
+ index_desc.index = index_desc.codec_desc.index
+ index_desc.index.database_vectors = index_desc.database_desc
+ index_desc.index.index_name = index_desc.get_name()
+ return
+
+ if index_desc.codec_desc is not None:
+ index = IndexFromCodec(
+ num_threads=self.num_threads,
+ d=index_desc.d,
+ metric=self.distance_metric,
+ database_vectors=index_desc.database_desc,
+ bucket=index_desc.codec_desc.bucket,
+ path=index_desc.codec_desc.path,
+ index_name=index_desc.get_name(),
+ codec_name=index_desc.codec_desc.get_name(),
+ serialize_full_index=self.serialize_index,
+ )
+ index.set_io(self.io)
+ index_desc.index = index
+ else:
+ assert index_desc.is_built()
+
+ def build_one(self, index_desc: IndexDescriptor, results: Dict[str, Any]):
+ faiss.omp_set_num_threads(index_desc.num_threads)
+ self.build_index_wrapper(index_desc)
+ if index_desc.is_built():
+ return
+ index_desc.index.get_index()
+
+ def build(self, results: Dict[str, Any]):
+ # TODO: add support for dry_run
+ for index_desc in self.index_descs:
+ self.build_one(index_desc, results)
+ return results, None
+
+
+@dataclass
+class SearchOperator(IndexOperator):
+ knn_descs: List[KnnDescriptor] = field(default_factory=lambda: [])
+ range: bool = False
+ compute_gt: bool = True
+
+ def get_desc(self, name: str) -> Optional[KnnDescriptor]:
+ for desc in self.knn_descs:
+ if desc.get_name() == name:
+ return desc
+ return None
+
+ def get_flat_desc(self, name=None) -> Optional[KnnDescriptor]:
+ for desc in self.knn_descs:
+ if desc.get_name().startswith("Flat"):
+ return desc
+ return None
+
+ def build_index_wrapper(self, knn_desc: KnnDescriptor):
+ if hasattr(knn_desc, "index"):
+ return
+
+ assert knn_desc.index_desc is not None
+ if hasattr(knn_desc.index_desc, "index"):
+ knn_desc.index = knn_desc.index_desc.index
+ knn_desc.index.knn_name = knn_desc.get_name()
+ knn_desc.index.search_params = knn_desc.search_params
+ else:
+ index = Index(
+ num_threads=self.num_threads,
+ d=knn_desc.d,
+ metric=self.distance_metric,
+ bucket=knn_desc.index_desc.bucket,
+ index_path=knn_desc.index_desc.path,
+ index_name=knn_desc.index_desc.get_name(),
+ # knn_name=knn_desc.get_name(),
+ search_params=knn_desc.search_params,
+ )
+ index.set_io(self.io)
+ knn_desc.index = index
+
+ knn_desc.index.get_index()
+
+ def range_search_reference(self, index, parameters, range_metric, query_dataset):
+ logger.info("range_search_reference: begin")
+ if isinstance(range_metric, list):
+ assert len(range_metric) > 0
+ m_radius = (
+ max(rm[-2] for rm in range_metric)
+ if self.distance_metric_type == faiss.METRIC_L2
+ else min(rm[-2] for rm in range_metric)
+ )
+ else:
+ m_radius = range_metric
+
+ lims, D, I, R, P, _ = self.range_search(
+ False,
+ index,
+ parameters,
+ radius=m_radius,
+ query_dataset=query_dataset,
+ )
+ flat = index.is_flat_index()
+ (
+ gt_radius,
+ range_search_metric_function,
+ coefficients,
+ coefficients_training_data,
+ ) = get_range_search_metric_function(
+ range_metric,
+ D if not flat else None,
+ R if not flat else None,
+ )
+ logger.info("range_search_reference: end")
+ return (
+ gt_radius,
+ range_search_metric_function,
+ coefficients,
+ coefficients_training_data,
+ )
+
+ def estimate_range(self, index, parameters, range_scoring_radius, query_dataset):
+ D, I, R, P, _ = index.knn_search(
+ False,
+ parameters,
+ query_dataset,
+ self.k,
+ )
+ samples = []
+ for i, j in np.argwhere(R < range_scoring_radius):
+ samples.append((R[i, j].item(), D[i, j].item()))
+ if len(samples) > 0: # estimate range
+ samples.sort(key=itemgetter(0))
+ return median(r for _, r in samples[-3:])
+ else: # ensure at least one result
+ i, j = np.argwhere(R.min() == R)[0]
+ return D[i, j].item()
+
+ def range_search(
+ self,
+ dry_run,
+ index: Index,
+ search_parameters: Optional[Dict[str, int]],
+ query_dataset: DatasetDescriptor,
+ radius: Optional[float] = None,
+ gt_radius: Optional[float] = None,
+ range_search_metric_function=None,
+ gt_rsm=None,
+ ):
+ logger.info("range_search: begin")
+ if radius is None:
+ assert gt_radius is not None
+ radius = (
+ gt_radius
+ if index.is_flat()
+ else self.estimate_range(
+ index, search_parameters, gt_radius, query_dataset
+ )
+ )
+ logger.info(f"Radius={radius}")
+ lims, D, I, R, P, requires = index.range_search(
+ dry_run=dry_run,
+ search_parameters=search_parameters,
+ query_vectors=query_dataset,
+ radius=radius,
+ )
+ if requires is not None:
+ return None, None, None, None, None, requires
+ if range_search_metric_function is not None:
+ range_search_metric = range_search_metric_function(R)
+ range_search_pr = range_search_pr_curve(D, range_search_metric, gt_rsm)
+ range_score_sum = np.sum(range_search_metric).item()
+ P |= {
+ "range_score_sum": range_score_sum,
+ "range_score_max_recall": range_score_sum / gt_rsm,
+ "range_search_pr": range_search_pr,
+ }
+ return lims, D, I, R, P, requires
+
+ def range_ground_truth(
+ self, gt_radius, range_search_metric_function, flat_desc=None
+ ):
+ logger.info("range_ground_truth: begin")
+ if flat_desc is None:
+ flat_desc = self.get_flat_desc()
+ lims, D, I, R, P, _ = self.range_search(
+ False,
+ flat_desc.index,
+ search_parameters=None,
+ radius=gt_radius,
+ query_dataset=flat_desc.query_dataset,
+ )
+ gt_rsm = np.sum(range_search_metric_function(R)).item()
+ logger.info("range_ground_truth: end")
+ return gt_rsm
+
+ def knn_ground_truth(self, flat_desc=None):
+ logger.info("knn_ground_truth: begin")
+ if flat_desc is None:
+ flat_desc = self.get_flat_desc()
+ self.build_index_wrapper(flat_desc)
+ # TODO(kuarora): Consider moving gt results(gt_knn_D, gt_knn_I) to the index as there can be multiple ground truths.
+ (
+ self.gt_knn_D,
+ self.gt_knn_I,
+ _,
+ _,
+ requires,
+ ) = flat_desc.index.knn_search(
+ dry_run=False,
+ search_parameters=None,
+ query_vectors=flat_desc.query_dataset,
+ k=flat_desc.k,
+ )
+ assert requires is None
+ logger.info("knn_ground_truth: end")
+
+ def search_benchmark(
+ self,
+ name,
+ search_func,
+ key_func,
+ cost_metrics,
+ perf_metrics,
+ results: Dict[str, Any],
+ index: Index,
+ ):
+ index_name = index.get_index_name()
+ logger.info(f"{name}_benchmark: begin {index_name}")
+
+ def experiment(parameters, cost_metric, perf_metric):
+ nonlocal results
+ key = key_func(parameters)
+ if key in results["experiments"]:
+ metrics = results["experiments"][key]
+ else:
+ metrics, requires = search_func(parameters)
+ if requires is not None:
+ return None, None, requires
+ results["experiments"][key] = metrics
+ return metrics[cost_metric], metrics[perf_metric], None
+
+ requires = None
+ for cost_metric in cost_metrics:
+ for perf_metric in perf_metrics:
+ op = index.get_operating_points()
+ requires = optimizer(
+ op,
+ experiment,
+ cost_metric,
+ perf_metric,
+ )
+ if requires is not None:
+ break
+ logger.info(f"{name}_benchmark: end")
+ return results, requires
+
+ def knn_search_benchmark(
+ self, dry_run, results: Dict[str, Any], knn_desc: KnnDescriptor
+ ):
+ gt_knn_D = None
+ gt_knn_I = None
+ if hasattr(self, "gt_knn_D"):
+ gt_knn_D = self.gt_knn_D
+ gt_knn_I = self.gt_knn_I
+
+ assert hasattr(knn_desc, "index")
+ if not knn_desc.index.is_flat_index() and gt_knn_I is None:
+ key = knn_desc.index.get_knn_search_name(
+ search_parameters=knn_desc.search_params,
+ query_vectors=knn_desc.query_dataset,
+ k=knn_desc.k,
+ reconstruct=False,
+ )
+ metrics, requires = knn_desc.index.knn_search(
+ dry_run,
+ knn_desc.search_params,
+ knn_desc.query_dataset,
+ knn_desc.k,
+ )[3:]
+ if requires is not None:
+ return results, requires
+ results["experiments"][key] = metrics
+ return results, requires
+
+ return self.search_benchmark(
+ name="knn_search",
+ search_func=lambda parameters: knn_desc.index.knn_search(
+ dry_run,
+ parameters,
+ knn_desc.query_dataset,
+ knn_desc.k,
+ gt_knn_I,
+ gt_knn_D,
+ )[3:],
+ key_func=lambda parameters: knn_desc.index.get_knn_search_name(
+ search_parameters=parameters,
+ query_vectors=knn_desc.query_dataset,
+ k=knn_desc.k,
+ reconstruct=False,
+ ),
+ cost_metrics=["time"],
+ perf_metrics=["knn_intersection", "distance_ratio"],
+ results=results,
+ index=knn_desc.index,
+ )
+
+ def reconstruct_benchmark(
+ self, dry_run, results: Dict[str, Any], knn_desc: KnnDescriptor
+ ):
+ return self.search_benchmark(
+ name="reconstruct",
+ search_func=lambda parameters: knn_desc.index.reconstruct(
+ dry_run,
+ parameters,
+ knn_desc.query_dataset,
+ knn_desc.k,
+ self.gt_knn_I,
+ ),
+ key_func=lambda parameters: knn_desc.index.get_knn_search_name(
+ search_parameters=parameters,
+ query_vectors=knn_desc.query_dataset,
+ k=knn_desc.k,
+ reconstruct=True,
+ ),
+ cost_metrics=["encode_time"],
+ perf_metrics=["sym_recall"],
+ results=results,
+ index=knn_desc.index,
+ )
+
+ def range_search_benchmark(
+ self,
+ dry_run,
+ results: Dict[str, Any],
+ index: Index,
+ metric_key: str,
+ radius: float,
+ gt_radius: float,
+ range_search_metric_function,
+ gt_rsm: float,
+ query_dataset: DatasetDescriptor,
+ ):
+ return self.search_benchmark(
+ name="range_search",
+ search_func=lambda parameters: self.range_search(
+ dry_run=dry_run,
+ index=index,
+ search_parameters=parameters,
+ radius=radius,
+ gt_radius=gt_radius,
+ range_search_metric_function=range_search_metric_function,
+ gt_rsm=gt_rsm,
+ query_dataset=query_dataset,
+ )[4:],
+ key_func=lambda parameters: index.get_range_search_name(
+ search_parameters=parameters,
+ query_vectors=query_dataset,
+ radius=radius,
+ )
+ + metric_key,
+ cost_metrics=["time"],
+ perf_metrics=["range_score_max_recall"],
+ results=results,
+ index=index,
+ )
+
+ def search_one(
+ self,
+ knn_desc: KnnDescriptor,
+ results: Dict[str, Any],
+ dry_run=False,
+ range=False,
+ ):
+ faiss.omp_set_num_threads(knn_desc.num_threads)
+
+ self.build_index_wrapper(knn_desc)
+ # results, requires = self.reconstruct_benchmark(
+ # dry_run=True,
+ # results=results,
+ # index=index_desc.index,
+ # )
+ # if reconstruct and requires is not None:
+ # if dry_run:
+ # return results, requires
+ # else:
+ # results, requires = self.reconstruct_benchmark(
+ # dry_run=False,
+ # results=results,
+ # index=index_desc.index,
+ # )
+ # assert requires is None
+ results, requires = self.knn_search_benchmark(
+ dry_run=True,
+ results=results,
+ knn_desc=knn_desc,
+ )
+ if requires is not None:
+ if dry_run:
+ return results, requires
+ else:
+ results, requires = self.knn_search_benchmark(
+ dry_run=False,
+ results=results,
+ knn_desc=knn_desc,
+ )
+ assert requires is None
+
+ if (
+ knn_desc.range_ref_index_desc is None or
+ not knn_desc.index.supports_range_search()
+ ):
+ return results, None
+
+ ref_index_desc = self.get_desc(knn_desc.range_ref_index_desc)
+ if ref_index_desc is None:
+ raise ValueError(
+ f"{knn_desc.get_name()}: Unknown range index {knn_desc.range_ref_index_desc}"
+ )
+ if ref_index_desc.range_metrics is None:
+ raise ValueError(
+ f"Range index {ref_index_desc.factory} has no radius_score"
+ )
+ for metric_key, range_metric in ref_index_desc.range_metrics.items():
+ (
+ gt_radius,
+ range_search_metric_function,
+ coefficients,
+ coefficients_training_data,
+ ) = self.range_search_reference(
+ ref_index_desc.index,
+ ref_index_desc.search_params,
+ range_metric,
+ query_dataset=knn_desc.query_dataset,
+ )
+ gt_rsm = None
+ if self.compute_gt:
+ gt_rsm = self.range_ground_truth(
+ gt_radius, range_search_metric_function
+ )
+ results, requires = self.range_search_benchmark(
+ dry_run=True,
+ results=results,
+ index=knn_desc.index,
+ metric_key=metric_key,
+ radius=knn_desc.radius,
+ gt_radius=gt_radius,
+ range_search_metric_function=range_search_metric_function,
+ gt_rsm=gt_rsm,
+ query_dataset=knn_desc.query_dataset,
+ )
+ if range and requires is not None:
+ if dry_run:
+ return results, requires
+ else:
+ results, requires = self.range_search_benchmark(
+ dry_run=False,
+ results=results,
+ index=knn_desc.index,
+ metric_key=metric_key,
+ radius=knn_desc.radius,
+ gt_radius=gt_radius,
+ range_search_metric_function=range_search_metric_function,
+ gt_rsm=gt_rsm,
+ query_dataset=knn_desc.query_dataset,
+ )
+ assert requires is None
+
+ return results, None
+
+ def search(
+ self,
+ results: Dict[str, Any],
+ dry_run: bool = False,):
+ for knn_desc in self.knn_descs:
+ results, requires = self.search_one(
+ knn_desc=knn_desc,
+ results=results,
+ dry_run=dry_run,
+ range=self.range)
+ if dry_run:
+ if requires is None:
+ continue
+ return results, requires
+
+ assert requires is None
+ return results, None
+
+
+@dataclass
+class ExecutionOperator:
+ distance_metric: str = "L2"
+ num_threads: int = 1
+ train_op: Optional[TrainOperator] = None
+ build_op: Optional[BuildOperator] = None
+ search_op: Optional[SearchOperator] = None
+ compute_gt: bool = True
+
+ def __post_init__(self):
+ if self.distance_metric == "IP":
+ self.distance_metric_type = faiss.METRIC_INNER_PRODUCT
+ elif self.distance_metric == "L2":
+ self.distance_metric_type = faiss.METRIC_L2
+ else:
+ raise ValueError
+
+ if self.search_op is not None:
+ self.search_op.compute_gt = self.compute_gt
+
+ def set_io(self, io: BenchmarkIO):
+ self.io = io
+ self.io.distance_metric = self.distance_metric
+ self.io.distance_metric_type = self.distance_metric_type
+ if self.train_op:
+ self.train_op.set_io(io)
+ if self.build_op:
+ self.build_op.set_io(io)
+ if self.search_op:
+ self.search_op.set_io(io)
+
+ def create_gt_codec(
+ self, codec_desc, results, train=True
+ ) -> Optional[CodecDescriptor]:
+ gt_codec_desc = None
+ if self.train_op:
+ gt_codec_desc = self.train_op.get_flat_desc(codec_desc.flat_name())
+ if gt_codec_desc is None:
+ gt_codec_desc = CodecDescriptor(
+ factory="Flat",
+ d=codec_desc.d,
+ metric=codec_desc.metric,
+ num_threads=self.num_threads,
+ )
+ self.train_op.codec_descs.insert(0, gt_codec_desc)
+ if train:
+ self.train_op.train_one(gt_codec_desc, results, dry_run=False)
+
+ return gt_codec_desc
+
+ def create_gt_index(
+ self, index_desc: IndexDescriptor, results: Dict[str, Any], build=True
+ ) -> Optional[IndexDescriptor]:
+ gt_index_desc = None
+ if self.build_op:
+ gt_index_desc = self.build_op.get_flat_desc(index_desc.flat_name())
+ if gt_index_desc is None:
+ gt_codec_desc = self.train_op.get_flat_desc(
+ index_desc.codec_desc.flat_name()
+ )
+ assert gt_codec_desc is not None
+ gt_index_desc = IndexDescriptor(
+ d=index_desc.d,
+ metric=index_desc.metric,
+ num_threads=self.num_threads,
+ codec_desc=gt_codec_desc,
+ database_desc=index_desc.database_desc,
+ )
+ self.build_op.index_descs.insert(0, gt_index_desc)
+ if build:
+ self.build_op.build_one(gt_index_desc, results)
+
+ return gt_index_desc
+
+ def create_gt_knn(self, knn_desc, search=True) -> Optional[KnnDescriptor]:
+ gt_knn_desc = None
+ if self.search_op:
+ gt_knn_desc = self.search_op.get_flat_desc(knn_desc.flat_name())
+ if gt_knn_desc is None:
+ if knn_desc.gt_index_desc is not None:
+ gt_index_desc = knn_desc.gt_index_desc
+ else:
+ gt_index_desc = self.build_op.get_flat_desc(
+ knn_desc.index_desc.flat_name()
+ )
+ knn_desc.gt_index_desc = gt_index_desc
+
+ assert gt_index_desc is not None
+ gt_knn_desc = KnnDescriptor(
+ d=knn_desc.d,
+ metric=knn_desc.metric,
+ num_threads=self.num_threads,
+ index_desc=gt_index_desc,
+ query_dataset=knn_desc.query_dataset,
+ k=knn_desc.k,
+ )
+ self.search_op.knn_descs.insert(0, gt_knn_desc)
+ if search:
+ self.search_op.build_index_wrapper(gt_knn_desc)
+ self.search_op.knn_ground_truth(gt_knn_desc)
+
+ return gt_knn_desc
+
+ def create_range_ref_knn(self, knn_desc):
+ if (
+ knn_desc.range_ref_index_desc is None or
+ not knn_desc.index.supports_range_search()
+ ):
+ return
+
+ if knn_desc.range_ref_index_desc is not None:
+ ref_index_desc = (
+ self.search_op.get_desc(knn_desc.range_ref_index_desc)
+ )
+ if ref_index_desc is None:
+ raise ValueError(f"Unknown range index {knn_desc.range_ref_index_desc}")
+ if ref_index_desc.range_metrics is None:
+ raise ValueError(
+ f"Range index {knn_desc.get_name()} has no radius_score"
+ )
+ results["metrics"] = {}
+ self.build_index_wrapper(ref_index_desc)
+ for metric_key, range_metric in ref_index_desc.range_metrics.items():
+ (
+ knn_desc.gt_radius,
+ range_search_metric_function,
+ coefficients,
+ coefficients_training_data,
+ ) = self.search_op.range_search_reference(
+ knn_desc.index, knn_desc.search_params, range_metric
+ )
+ results["metrics"][metric_key] = {
+ "coefficients": coefficients,
+ "training_data": coefficients_training_data,
+ }
+ knn_desc.gt_rsm = self.search_op.range_ground_truth(
+ knn_desc.gt_radius, range_search_metric_function
+ )
+
+ def create_ground_truths(self, results: Dict[str, Any]):
+ # TODO: Create all ground truth descriptors and
+ # put them in index descriptor as reference
+ if self.train_op is not None:
+ for codec_desc in self.train_op.codec_descs:
+ self.create_gt_codec(codec_desc, results)
+
+ if self.build_op is not None:
+ for index_desc in self.build_op.index_descs:
+ self.create_gt_index(
+ index_desc, results
+ ) # may need to pass results in future
+
+ if self.search_op is not None:
+ for knn_desc in self.search_op.knn_descs:
+ self.create_gt_knn(knn_desc, results)
+ self.create_range_ref_knn(knn_desc)
+
+ def prepare_gt_or_range_knn(self, results: Dict[str, Any]):
+ if self.search_op is not None:
+ for knn_desc in self.search_op.knn_descs:
+ self.create_gt_knn(knn_desc, results)
+ self.create_range_ref_knn(knn_desc)
+
+ def execute(self, results: Dict[str, Any], dry_run: bool = False):
+ faiss.omp_set_num_threads(self.num_threads)
+ if self.train_op is not None:
+ results, requires = (
+ self.train_op.train(results=results, dry_run=dry_run)
+ )
+ if dry_run and requires:
+ return results, requires
+
+ if self.build_op is not None:
+ self.build_op.build(results)
+
+ if self.search_op is not None:
+ if not dry_run and self.compute_gt:
+ self.prepare_gt_or_range_knn(results)
+
+ results, requires = (
+ self.search_op.search(results=results, dry_run=dry_run)
+ )
+ if dry_run and requires:
+ return results, requires
+ return results, None
+
+ def execute_2(self, result_file=None):
+ results = {"indices": {}, "experiments": {}}
+ results, requires = self.execute(results=results)
+ assert requires is None
+ if result_file is not None:
+ self.io.write_json(results, result_file, overwrite=True)
+
+ def add_index_descs(self, codec_desc, index_desc, knn_desc):
+ if codec_desc is not None:
+ self.train_op.codec_descs.append(codec_desc)
+ if index_desc is not None:
+ self.build_op.index_descs.append(index_desc)
+ if knn_desc is not None:
+ self.search_op.knn_descs.append(knn_desc)
+
+
+@dataclass
+class Benchmark:
+ num_threads: int
+ training_vectors: Optional[DatasetDescriptor] = None
+ database_vectors: Optional[DatasetDescriptor] = None
+ query_vectors: Optional[DatasetDescriptor] = None
+ index_descs: Optional[List[IndexDescriptorClassic]] = None
+ range_ref_index_desc: Optional[str] = None
+ k: int = 1
+ distance_metric: str = "L2"
+
+ def set_io(self, benchmark_io):
+ self.io = benchmark_io
+
+ def get_embedding_dimension(self):
+ if self.training_vectors is not None:
+ xt = self.io.get_dataset(self.training_vectors)
+ return xt.shape[1]
+ if self.database_vectors is not None:
+ xb = self.io.get_dataset(self.database_vectors)
+ return xb.shape[1]
+ if self.query_vectors is not None:
+ xq = self.io.get_dataset(self.query_vectors)
+ return xq.shape[1]
+ raise ValueError("Failed to determine dimension of dataset")
+
+ def create_descriptors(
+ self, ci_desc: IndexDescriptorClassic, train, build, knn, reconstruct, range
+ ):
+ codec_desc = None
+ index_desc = None
+ knn_desc = None
+ dim = self.get_embedding_dimension()
+ if train and ci_desc.factory is not None:
+ codec_desc = CodecDescriptor(
+ d=dim,
+ metric=self.distance_metric,
+ num_threads=self.num_threads,
+ factory=ci_desc.factory,
+ construction_params=ci_desc.construction_params,
+ training_vectors=self.training_vectors,
+ )
+ if build:
+ if codec_desc is None:
+ assert ci_desc.path is not None
+ codec_desc = CodecDescriptor(
+ d=dim,
+ metric=self.distance_metric,
+ num_threads=self.num_threads,
+ bucket=ci_desc.bucket,
+ path=ci_desc.path,
+ )
+ index_desc = IndexDescriptor(
+ d=codec_desc.d,
+ metric=self.distance_metric,
+ num_threads=self.num_threads,
+ codec_desc=codec_desc,
+ database_desc=self.database_vectors,
+ )
+ if knn or range:
+ if index_desc is None:
+ assert ci_desc.path is not None
+ index_desc = IndexDescriptor(
+ d=dim,
+ metric=self.distance_metric,
+ num_threads=self.num_threads,
+ bucket=ci_desc.bucket,
+ path=ci_desc.path,
+ )
+ knn_desc = KnnDescriptor(
+ d=dim,
+ metric=self.distance_metric,
+ num_threads=self.num_threads,
+ index_desc=index_desc,
+ query_dataset=self.query_vectors,
+ search_params=ci_desc.search_params,
+ range_metrics=ci_desc.range_metrics,
+ radius=ci_desc.radius,
+ k=self.k,
+ )
+
+ return codec_desc, index_desc, knn_desc
+
+ def create_execution_operator(
+ self,
+ train,
+ build,
+ knn,
+ reconstruct,
+ range,
+ ) -> ExecutionOperator:
+ # all operators are created, as ground truth are always created in benchmarking
+ train_op = TrainOperator(
+ num_threads=self.num_threads, distance_metric=self.distance_metric
+ )
+ build_op = BuildOperator(
+ num_threads=self.num_threads, distance_metric=self.distance_metric
+ )
+ search_op = SearchOperator(
+ num_threads=self.num_threads, distance_metric=self.distance_metric
+ )
+ search_op.range = range
+
+ exec_op = ExecutionOperator(
+ train_op=train_op,
+ build_op=build_op,
+ search_op=search_op,
+ num_threads=self.num_threads,
+ )
+ assert hasattr(self, "io")
+ exec_op.set_io(self.io)
+
+ # iterate over classic descriptors
+ for ci_desc in self.index_descs:
+ codec_desc, index_desc, knn_desc = self.create_descriptors(
+ ci_desc, train, build, knn, reconstruct, range
+ )
+ exec_op.add_index_descs(codec_desc, index_desc, knn_desc)
+
+ return exec_op
+
+ def clone_one(self, index_desc):
+ benchmark = Benchmark(
+ num_threads=self.num_threads,
+ training_vectors=self.training_vectors,
+ database_vectors=self.database_vectors,
+ query_vectors=self.query_vectors,
+ # index_descs=[self.get_flat_desc("Flat"), index_desc],
+ index_descs=[index_desc], # Should automatically find flat descriptors
+ range_ref_index_desc=self.range_ref_index_desc,
+ k=self.k,
+ distance_metric=self.distance_metric,
+ )
+ benchmark.set_io(self.io.clone())
+ return benchmark
+
+ def benchmark(
+ self,
+ result_file=None,
+ local=False,
+ train=False,
+ reconstruct=False,
+ knn=False,
+ range=False,
+ ):
+ logger.info("begin evaluate")
+ results = {"indices": {}, "experiments": {}}
+ faiss.omp_set_num_threads(self.num_threads)
+ exec_op = self.create_execution_operator(
+ train=train,
+ build=knn or range,
+ knn=knn,
+ reconstruct=reconstruct,
+ range=range,
+ )
+ exec_op.create_ground_truths(results)
+
+ todo = self.index_descs
+ for index_desc in self.index_descs:
+ index_desc.requires = None
+
+ queued = set()
+ while todo:
+ current_todo = []
+ next_todo = []
+ for index_desc in todo:
+ results, requires = exec_op.execute(results, dry_run=False)
+ if requires is None:
+ continue
+ if requires in queued:
+ if index_desc.requires != requires:
+ index_desc.requires = requires
+ next_todo.append(index_desc)
+ else:
+ queued.add(requires)
+ index_desc.requires = requires
+ current_todo.append(index_desc)
+
+ if current_todo:
+ results_one = {"indices": {}, "experiments": {}}
+ params = [
+ (
+ index_desc,
+ self.clone_one(index_desc),
+ results_one,
+ train,
+ reconstruct,
+ knn,
+ range,
+ )
+ for index_desc in current_todo
+ ]
+ for result in self.io.launch_jobs(
+ run_benchmark_one, params, local=local
+ ):
+ dict_merge(results, result)
+
+ todo = next_todo
+
+ if result_file is not None:
+ self.io.write_json(results, result_file, overwrite=True)
+ logger.info("end evaluate")
+ return results
+
+
+def run_benchmark_one(params):
+ logger.info(params)
+ index_desc, benchmark, results, train, reconstruct, knn, range = params
+ exec_op = benchmark.create_execution_operator(
+ train=train,
+ build=knn,
+ knn=knn,
+ reconstruct=reconstruct,
+ range=range,
+ )
+ results, requires = exec_op.execute(results=results, dry_run=False)
+ assert requires is None
+ assert results is not None
+ return results
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/benchmark_io.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/benchmark_io.py
new file mode 100644
index 0000000..a67b09c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/benchmark_io.py
@@ -0,0 +1,272 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import hashlib
+import io
+import json
+import logging
+import os
+import pickle
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional
+from zipfile import ZipFile
+
+import faiss # @manual=//faiss/python:pyfaiss
+
+import numpy as np
+import submitit
+from faiss.contrib.datasets import ( # @manual=//faiss/contrib:faiss_contrib
+ dataset_from_name,
+)
+
+logger = logging.getLogger(__name__)
+
+
+# merge RCQ coarse quantizer and ITQ encoder to one Faiss index
+def merge_rcq_itq(
+ # pyre-ignore[11]: `faiss.ResidualCoarseQuantizer` is not defined as a type
+ rcq_coarse_quantizer: faiss.ResidualCoarseQuantizer,
+ itq_encoder: faiss.IndexPreTransform,
+ # pyre-ignore[11]: `faiss.IndexIVFSpectralHash` is not defined as a type.
+) -> faiss.IndexIVFSpectralHash:
+ # pyre-ignore[16]: `faiss` has no attribute `IndexIVFSpectralHash`.
+ index = faiss.IndexIVFSpectralHash(
+ rcq_coarse_quantizer,
+ rcq_coarse_quantizer.d,
+ rcq_coarse_quantizer.ntotal,
+ itq_encoder.sa_code_size() * 8,
+ 1000000, # larger than the magnitude of the vectors
+ )
+ index.replace_vt(itq_encoder)
+ return index
+
+
+@dataclass
+class BenchmarkIO:
+ path: str # local path
+
+ def __init__(self, path: str):
+ self.path = path
+ self.cached_ds: Dict[Any, Any] = {}
+
+ def clone(self):
+ return BenchmarkIO(path=self.path)
+
+ def get_local_filepath(self, filename):
+ if len(filename) > 184:
+ fn, ext = os.path.splitext(filename)
+ filename = (
+ fn[:184] + hashlib.sha256(filename.encode()).hexdigest() + ext
+ )
+ return os.path.join(self.path, filename)
+
+ def get_remote_filepath(self, filename) -> Optional[str]:
+ return None
+
+ def download_file_from_blobstore(
+ self,
+ filename: str,
+ bucket: Optional[str] = None,
+ path: Optional[str] = None,
+ ):
+ return self.get_local_filepath(filename)
+
+ def upload_file_to_blobstore(
+ self,
+ filename: str,
+ bucket: Optional[str] = None,
+ path: Optional[str] = None,
+ overwrite: bool = False,
+ ):
+ pass
+
+ def file_exist(self, filename: str):
+ fn = self.get_local_filepath(filename)
+ exists = os.path.exists(fn)
+ logger.info(f"{filename} {exists=}")
+ return exists
+
+ def read_file(self, filename: str, keys: List[str]):
+ fn = self.download_file_from_blobstore(filename)
+ logger.info(f"Loading file {fn}")
+ results = []
+ with ZipFile(fn, "r") as zip_file:
+ for key in keys:
+ with zip_file.open(key, "r") as f:
+ if key in ["D", "I", "R", "lims"]:
+ results.append(np.load(f))
+ elif key in ["P"]:
+ t = io.TextIOWrapper(f)
+ results.append(json.load(t))
+ else:
+ raise AssertionError()
+ return results
+
+ def write_file(
+ self,
+ filename: str,
+ keys: List[str],
+ values: List[Any],
+ overwrite: bool = False,
+ ):
+ fn = self.get_local_filepath(filename)
+ with ZipFile(fn, "w") as zip_file:
+ for key, value in zip(keys, values, strict=True):
+ with zip_file.open(key, "w", force_zip64=True) as f:
+ if key in ["D", "I", "R", "lims"]:
+ np.save(f, value)
+ elif key in ["P"]:
+ t = io.TextIOWrapper(f, write_through=True)
+ json.dump(value, t)
+ else:
+ raise AssertionError()
+ self.upload_file_to_blobstore(filename, overwrite=overwrite)
+
+ def get_dataset(self, dataset):
+ if dataset not in self.cached_ds:
+ if (
+ dataset.namespace is not None
+ and dataset.namespace[:4] == "std_"
+ ):
+ if dataset.tablename not in self.cached_ds:
+ self.cached_ds[dataset.tablename] = dataset_from_name(
+ dataset.tablename,
+ )
+ p = dataset.namespace[4]
+ if p == "t":
+ self.cached_ds[dataset] = self.cached_ds[
+ dataset.tablename
+ ].get_train(dataset.num_vectors)
+ elif p == "d":
+ self.cached_ds[dataset] = self.cached_ds[
+ dataset.tablename
+ ].get_database()
+ elif p == "q":
+ self.cached_ds[dataset] = self.cached_ds[
+ dataset.tablename
+ ].get_queries()
+ else:
+ raise ValueError
+ elif dataset.namespace == "syn":
+ d, seed = dataset.tablename.split("_")
+ d = int(d)
+ seed = int(seed)
+ n = dataset.num_vectors
+ # based on faiss.contrib.datasets.SyntheticDataset
+ d1 = 10
+ rs = np.random.RandomState(seed)
+ x = rs.normal(size=(n, d1))
+ x = np.dot(x, rs.rand(d1, d))
+ x = x * (rs.rand(d) * 4 + 0.1)
+ x = np.sin(x)
+ x = x.astype(np.float32)
+ self.cached_ds[dataset] = x
+ else:
+ self.cached_ds[dataset] = self.read_nparray(
+ os.path.join(self.path, dataset.tablename),
+ mmap_mode="r",
+ )[: dataset.num_vectors].copy()
+ return self.cached_ds[dataset]
+
+ def read_nparray(
+ self,
+ filename: str,
+ mmap_mode: Optional[str] = None,
+ ):
+ fn = self.download_file_from_blobstore(filename)
+ logger.info(f"Loading nparray from {fn}")
+ nparray = np.load(fn, mmap_mode=mmap_mode)
+ logger.info(f"Loaded nparray {nparray.shape} from {fn}")
+ return nparray
+
+ def write_nparray(
+ self,
+ nparray: np.ndarray,
+ filename: str,
+ ):
+ fn = self.get_local_filepath(filename)
+ logger.info(f"Saving nparray {nparray.shape} to {fn}")
+ np.save(fn, nparray)
+ self.upload_file_to_blobstore(filename)
+
+ def read_json(
+ self,
+ filename: str,
+ ):
+ fn = self.download_file_from_blobstore(filename)
+ logger.info(f"Loading json {fn}")
+ with open(fn, "r") as fp:
+ json_dict = json.load(fp)
+ logger.info(f"Loaded json {json_dict} from {fn}")
+ return json_dict
+
+ def write_json(
+ self,
+ json_dict: dict[str, Any],
+ filename: str,
+ overwrite: bool = False,
+ ):
+ fn = self.get_local_filepath(filename)
+ logger.info(f"Saving json {json_dict} to {fn}")
+ with open(fn, "w") as fp:
+ json.dump(json_dict, fp)
+ self.upload_file_to_blobstore(filename, overwrite=overwrite)
+
+ def read_index(
+ self,
+ filename: str,
+ bucket: Optional[str] = None,
+ path: Optional[str] = None,
+ ):
+ fn = self.download_file_from_blobstore(filename, bucket, path)
+ logger.info(f"Loading index {fn}")
+ ext = os.path.splitext(fn)[1]
+ if ext in [".faiss", ".codec", ".index"]:
+ index = faiss.read_index(fn)
+ elif ext == ".pkl":
+ with open(fn, "rb") as model_file:
+ model = pickle.load(model_file)
+ rcq_coarse_quantizer, itq_encoder = model["model"]
+ index = merge_rcq_itq(rcq_coarse_quantizer, itq_encoder)
+ logger.info(f"Loaded index from {fn}")
+ return index
+
+ def write_index(
+ self,
+ index: faiss.Index,
+ filename: str,
+ ):
+ fn = self.get_local_filepath(filename)
+ logger.info(f"Saving index to {fn}")
+ faiss.write_index(index, fn)
+ self.upload_file_to_blobstore(filename)
+ assert os.path.exists(fn)
+ return os.path.getsize(fn)
+
+ def launch_jobs(self, func, params, local=True):
+ if local:
+ results = [func(p) for p in params]
+ return results
+ logger.info(f"launching {len(params)} jobs")
+ executor = submitit.AutoExecutor(folder="/checkpoint/gsz/jobs")
+ executor.update_parameters(
+ nodes=1,
+ gpus_per_node=8,
+ cpus_per_task=80,
+ # mem_gb=640,
+ tasks_per_node=1,
+ name="faiss_benchmark",
+ slurm_array_parallelism=512,
+ slurm_partition="scavenge",
+ slurm_time=4 * 60,
+ slurm_constraint="bldg1",
+ )
+ jobs = executor.map_array(func, params)
+ logger.info(f"launched {len(jobs)} jobs")
+ for job, param in zip(jobs, params):
+ logger.info(f"{job.job_id=} {param[0]=}")
+ results = [job.result() for job in jobs]
+ print(f"received {len(results)} results")
+ return results
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/descriptors.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/descriptors.py
new file mode 100644
index 0000000..ca8c8c9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/descriptors.py
@@ -0,0 +1,379 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+import os
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional
+
+import faiss # @manual=//faiss/python:pyfaiss
+
+from .benchmark_io import BenchmarkIO
+from .utils import timer
+
+logger = logging.getLogger(__name__)
+
+
+# Important: filenames end with . without extension (npy, codec, index),
+# when writing files, you are required to filename + "npy" etc.
+
+@dataclass
+class IndexDescriptorClassic:
+ bucket: Optional[str] = None
+ # either path or factory should be set,
+ # but not both at the same time.
+ path: Optional[str] = None
+ factory: Optional[str] = None
+ codec_alias: Optional[str] = None
+ construction_params: Optional[List[Dict[str, int]]] = None
+ search_params: Optional[Dict[str, int]] = None
+ # range metric definitions
+ # key: name
+ # value: one of the following:
+ #
+ # radius
+ # [0..radius) -> 1
+ # [radius..inf) -> 0
+ #
+ # [[radius1, score1], ...]
+ # [0..radius1) -> score1
+ # [radius1..radius2) -> score2
+ #
+ # [[radius1_from, radius1_to, score1], ...]
+ # [radius1_from, radius1_to) -> score1,
+ # [radius2_from, radius2_to) -> score2
+ range_metrics: Optional[Dict[str, Any]] = None
+ radius: Optional[float] = None
+ training_size: Optional[int] = None
+
+ def __hash__(self):
+ return hash(str(self))
+
+@dataclass
+class DatasetDescriptor:
+ # namespace possible values:
+ # 1. a hive namespace
+ # 2. 'std_t', 'std_d', 'std_q' for the standard datasets
+ # via faiss.contrib.datasets.dataset_from_name()
+ # t - training, d - database, q - queries
+ # eg. "std_t"
+ # 3. 'syn' for synthetic data
+ # 4. None for local files
+ namespace: Optional[str] = None
+
+ # tablename possible values, corresponding to the
+ # namespace value above:
+ # 1. a hive table name
+ # 2. name of the standard dataset as recognized
+ # by faiss.contrib.datasets.dataset_from_name()
+ # eg. "bigann1M"
+ # 3. d_seed, eg. 128_1234 for 128 dimensional vectors
+ # with seed 1234
+ # 4. a local file name (relative to benchmark_io.path)
+ tablename: Optional[str] = None
+
+ # partition names and values for hive
+ # eg. ["ds=2021-09-01"]
+ partitions: Optional[List[str]] = None
+
+ # number of vectors to load from the dataset
+ num_vectors: Optional[int] = None
+
+ embedding_column: Optional[str] = None
+
+ # only when the embedding column is a map
+ embedding_column_key: Optional[Any] = None
+
+ embedding_id_column: Optional[str] = None
+
+ # filters on the dataset where each filter is a
+ # string rep of a filter expression
+ filters: Optional[List[str]] = None
+
+ # unused in open-source
+ splits_distribution: Optional[List[List[bytes]]] = None
+
+ # unused in open-source
+ splits: Optional[List[bytes]] = None
+
+ # unused in open-source
+ serialized_df: Optional[str] = None
+
+ sampling_rate: Optional[float] = None
+
+ # sampling column for xdb
+ sampling_column: Optional[str] = None
+
+ # blob store
+ bucket: Optional[str] = None
+ path: Optional[str] = None
+
+ # desc_name
+ desc_name: Optional[str] = None
+
+ normalize_L2: bool = False
+
+ def __hash__(self):
+ return hash(self.get_filename())
+
+ def get_filename(
+ self,
+ prefix: Optional[str] = None,
+ ) -> str:
+ if self.desc_name is not None:
+ return self.desc_name
+
+ filename = ""
+ if prefix is not None:
+ filename += prefix + "_"
+ if self.namespace is not None:
+ filename += self.namespace + "_"
+ assert self.tablename is not None
+ filename += self.tablename
+ if self.partitions is not None:
+ filename += "_" + "_".join(
+ self.partitions
+ ).replace("=", "_").replace("/", "_")
+ if self.num_vectors is not None:
+ filename += f"_{self.num_vectors}"
+ filename += "."
+
+ self.desc_name = filename
+ return self.desc_name
+
+ def get_kmeans_filename(self, k):
+ return f"{self.get_filename()}kmeans_{k}."
+
+ def k_means(self, io, k, dry_run):
+ logger.info(f"k_means {k} {self}")
+ kmeans_vectors = DatasetDescriptor(
+ tablename=f"{self.get_filename()}kmeans_{k}"
+ )
+ kmeans_filename = kmeans_vectors.get_filename() + "npy"
+ meta_filename = kmeans_vectors.get_filename() + "json"
+ if not io.file_exist(kmeans_filename) or not io.file_exist(
+ meta_filename
+ ):
+ if dry_run:
+ return None, None, kmeans_filename
+ x = io.get_dataset(self)
+ kmeans = faiss.Kmeans(d=x.shape[1], k=k, gpu=True)
+ _, t, _ = timer("k_means", lambda: kmeans.train(x))
+ io.write_nparray(kmeans.centroids, kmeans_filename)
+ io.write_json({"k_means_time": t}, meta_filename)
+ else:
+ t = io.read_json(meta_filename)["k_means_time"]
+ return kmeans_vectors, t, None
+
+@dataclass
+class IndexBaseDescriptor:
+ d: int
+ metric: str
+ desc_name: Optional[str] = None
+ flat_desc_name: Optional[str] = None
+ bucket: Optional[str] = None
+ path: Optional[str] = None
+ num_threads: int = 1
+
+ def get_name(self) -> str:
+ raise NotImplementedError()
+
+ def get_path(self, benchmark_io: BenchmarkIO) -> Optional[str]:
+ if self.path is not None:
+ return self.path
+ self.path = benchmark_io.get_remote_filepath(self.desc_name)
+ return self.path
+
+ @staticmethod
+ def param_dict_list_to_name(param_dict_list):
+ if not param_dict_list:
+ return ""
+ l = 0
+ n = ""
+ for param_dict in param_dict_list:
+ n += IndexBaseDescriptor.param_dict_to_name(param_dict, f"cp{l}")
+ l += 1
+ return n
+
+ @staticmethod
+ def param_dict_to_name(param_dict, prefix="sp"):
+ if not param_dict:
+ return ""
+ n = prefix
+ for name, val in param_dict.items():
+ if name == "snap":
+ continue
+ if name == "lsq_gpu" and val == 0:
+ continue
+ if name == "use_beam_LUT" and val == 0:
+ continue
+ n += f"_{name}_{val}"
+ if n == prefix:
+ return ""
+ n += "."
+ return n
+
+
+@dataclass
+class CodecDescriptor(IndexBaseDescriptor):
+ # either path or factory should be set,
+ # but not both at the same time.
+ factory: Optional[str] = None
+ construction_params: Optional[List[Dict[str, int]]] = None
+ training_vectors: Optional[DatasetDescriptor] = None
+ FILENAME_PREFIX: str = "xt"
+
+ def __post_init__(self):
+ self.get_name()
+
+ def is_trained(self):
+ return self.factory is None and self.path is not None
+
+ def is_valid(self):
+ return self.factory is not None or self.path is not None
+
+ def get_name(self) -> str:
+ if self.desc_name is not None:
+ return self.desc_name
+ if self.factory is not None:
+ self.desc_name = self.name_from_factory()
+ return self.desc_name
+ if self.path is not None:
+ self.desc_name = self.name_from_path()
+ return self.desc_name
+ raise ValueError("name, factory or path must be set")
+
+ def flat_name(self) -> str:
+ if self.flat_desc_name is not None:
+ return self.flat_desc_name
+ self.flat_desc_name = f"Flat.d_{self.d}.{self.metric.upper()}."
+ return self.flat_desc_name
+
+ def path(self, benchmark_io) -> str:
+ if self.path is not None:
+ return self.path
+ return benchmark_io.get_remote_filepath(self.get_name())
+
+ def name_from_factory(self) -> str:
+ assert self.factory is not None
+ name = f"{self.factory.replace(',', '_')}."
+ assert self.d is not None
+ assert self.metric is not None
+ name += f"d_{self.d}.{self.metric.upper()}."
+ if self.factory != "Flat":
+ assert self.training_vectors is not None
+ name += self.training_vectors.get_filename(CodecDescriptor.FILENAME_PREFIX)
+ name += IndexBaseDescriptor.param_dict_list_to_name(self.construction_params)
+ return name
+
+ def name_from_path(self):
+ assert self.path is not None
+ filename = os.path.basename(self.path)
+ ext = filename.split(".")[-1]
+ if filename.endswith(ext):
+ name = filename[:-len(ext)]
+ else: # should never hit this rather raise value error
+ name = filename
+ return name
+
+ def alias(self, benchmark_io: BenchmarkIO):
+ if hasattr(benchmark_io, "bucket"):
+ return CodecDescriptor(desc_name=self.get_name(), bucket=benchmark_io.bucket, path=self.get_path(benchmark_io), d=self.d, metric=self.metric)
+ return CodecDescriptor(desc_name=self.get_name(), d=self.d, metric=self.metric)
+
+
+@dataclass
+class IndexDescriptor(IndexBaseDescriptor):
+ codec_desc: Optional[CodecDescriptor] = None
+ database_desc: Optional[DatasetDescriptor] = None
+ FILENAME_PREFIX: str = "xb"
+
+ def __hash__(self):
+ return hash(str(self))
+
+ def __post_init__(self):
+ self.get_name()
+
+ def is_built(self):
+ return self.codec_desc is None and self.database_desc is None
+
+ def get_name(self) -> str:
+ if self.desc_name is None:
+ self.desc_name = self.codec_desc.get_name() + self.database_desc.get_filename(prefix=IndexDescriptor.FILENAME_PREFIX)
+
+ return self.desc_name
+
+ def flat_name(self):
+ if self.flat_desc_name is not None:
+ return self.flat_desc_name
+ self.flat_desc_name = self.codec_desc.flat_name() + self.database_desc.get_filename(prefix=IndexDescriptor.FILENAME_PREFIX)
+ return self.flat_desc_name
+
+ # alias is used to refer when index is uploaded to blobstore and refered again
+ def alias(self, benchmark_io: BenchmarkIO):
+ if hasattr(benchmark_io, "bucket"):
+ return IndexDescriptor(desc_name=self.get_name(), bucket=benchmark_io.bucket, path=self.get_path(benchmark_io), d=self.d, metric=self.metric)
+ return IndexDescriptor(desc_name=self.get_name(), d=self.d, metric=self.metric)
+
+@dataclass
+class KnnDescriptor(IndexBaseDescriptor):
+ index_desc: Optional[IndexDescriptor] = None
+ gt_index_desc: Optional[IndexDescriptor] = None
+ query_dataset: Optional[DatasetDescriptor] = None
+ search_params: Optional[Dict[str, int]] = None
+ reconstruct: bool = False
+ FILENAME_PREFIX: str = "q"
+ # range metric definitions
+ # key: name
+ # value: one of the following:
+ #
+ # radius
+ # [0..radius) -> 1
+ # [radius..inf) -> 0
+ #
+ # [[radius1, score1], ...]
+ # [0..radius1) -> score1
+ # [radius1..radius2) -> score2
+ #
+ # [[radius1_from, radius1_to, score1], ...]
+ # [radius1_from, radius1_to) -> score1,
+ # [radius2_from, radius2_to) -> score2
+ range_metrics: Optional[Dict[str, Any]] = None
+ radius: Optional[float] = None
+ k: int = 1
+
+ range_ref_index_desc: Optional[str] = None
+
+ def __hash__(self):
+ return hash(str(self))
+
+ def get_name(self):
+ if self.desc_name is not None:
+ return self.desc_name
+ name = self.index_desc.get_name()
+ name += IndexBaseDescriptor.param_dict_to_name(self.search_params)
+ name += self.query_dataset.get_filename(KnnDescriptor.FILENAME_PREFIX)
+ name += f"k_{self.k}."
+ name += f"t_{self.num_threads}."
+ if self.reconstruct:
+ name += "rec."
+ else:
+ name += "knn."
+ self.desc_name = name
+ return name
+
+ def flat_name(self):
+ if self.flat_desc_name is not None:
+ return self.flat_desc_name
+ name = self.index_desc.flat_name()
+ name += self.query_dataset.get_filename(KnnDescriptor.FILENAME_PREFIX)
+ name += f"k_{self.k}."
+ name += f"t_{self.num_threads}."
+ if self.reconstruct:
+ name += "rec."
+ else:
+ name += "knn."
+ self.flat_desc_name = name
+ return name
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/index.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/index.py
new file mode 100644
index 0000000..b1252ad
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/index.py
@@ -0,0 +1,1146 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+
+import logging
+import os
+from collections import OrderedDict
+from copy import copy
+from dataclasses import dataclass
+from typing import ClassVar, Dict, List, Optional
+
+import faiss # @manual=//faiss/python:pyfaiss
+import numpy as np
+from faiss.benchs.bench_fw.descriptors import IndexBaseDescriptor
+
+from faiss.contrib.evaluation import ( # @manual=//faiss/contrib:faiss_contrib
+ knn_intersection_measure,
+ OperatingPointsWithRanges,
+)
+from faiss.contrib.factory_tools import ( # @manual=//faiss/contrib:faiss_contrib
+ reverse_index_factory,
+)
+from faiss.contrib.ivf_tools import ( # @manual=//faiss/contrib:faiss_contrib
+ add_preassigned,
+ replace_ivf_quantizer,
+)
+
+from .descriptors import DatasetDescriptor
+from .utils import (
+ distance_ratio_measure,
+ get_cpu_info,
+ refine_distances_knn,
+ refine_distances_range,
+ timer,
+)
+
+logger = logging.getLogger(__name__)
+
+
+# The classes below are wrappers around Faiss indices, with different
+# implementations for the case when we start with an already trained
+# index (IndexFromCodec) vs factory strings (IndexFromFactory).
+# In both cases the classes have operations for adding to an index
+# and searching it, and outputs are cached on disk.
+# IndexFromFactory also decomposes the index (pretransform and quantizer)
+# and trains sub-indices independently.
+class IndexBase:
+ def set_io(self, benchmark_io):
+ self.io = benchmark_io
+
+ @staticmethod
+ def set_index_param_dict_list(index, param_dict_list, assert_same=False):
+ if not param_dict_list:
+ return
+ index = faiss.downcast_index(index)
+ for param_dict in param_dict_list:
+ assert index is not None
+ IndexBase.set_index_param_dict(index, param_dict, assert_same)
+ index = faiss.try_extract_index_ivf(index)
+ if index is not None:
+ index = index.quantizer
+
+ @staticmethod
+ def set_index_param_dict(index, param_dict, assert_same=False):
+ if not param_dict:
+ return
+ for name, val in param_dict.items():
+ IndexBase.set_index_param(index, name, val, assert_same)
+
+ @staticmethod
+ def set_index_param(index, name, val, assert_same=False):
+ index = faiss.downcast_index(index)
+ val = int(val)
+ if (
+ isinstance(index, faiss.IndexPreTransform)
+ or isinstance(index, faiss.IndexIDMap)
+ ):
+ Index.set_index_param(index.index, name, val)
+ return
+ elif name == "snap":
+ return
+ elif name == "lsq_gpu":
+ if val == 1:
+ ngpus = faiss.get_num_gpus()
+ icm_encoder_factory = faiss.GpuIcmEncoderFactory(ngpus)
+ if isinstance(index, faiss.IndexProductLocalSearchQuantizer):
+ for i in range(index.plsq.nsplits):
+ lsq = faiss.downcast_Quantizer(
+ index.plsq.subquantizer(i)
+ )
+ if lsq.icm_encoder_factory is None:
+ lsq.icm_encoder_factory = icm_encoder_factory
+ else:
+ if index.lsq.icm_encoder_factory is None:
+ index.lsq.icm_encoder_factory = icm_encoder_factory
+ return
+ elif name in ["efSearch", "efConstruction"]:
+ obj = index.hnsw
+ elif name in ["nprobe", "parallel_mode"]:
+ obj = faiss.extract_index_ivf(index)
+ elif name in ["use_beam_LUT", "max_beam_size"]:
+ if isinstance(index, faiss.IndexProductResidualQuantizer):
+ obj = [
+ faiss.downcast_Quantizer(index.prq.subquantizer(i))
+ for i in range(index.prq.nsplits)
+ ]
+ else:
+ obj = index.rq
+ elif name == "encode_ils_iters":
+ if isinstance(index, faiss.IndexProductLocalSearchQuantizer):
+ obj = [
+ faiss.downcast_Quantizer(index.plsq.subquantizer(i))
+ for i in range(index.plsq.nsplits)
+ ]
+ else:
+ obj = index.lsq
+ else:
+ obj = index
+
+ if not isinstance(obj, list):
+ obj = [obj]
+ for o in obj:
+ test = getattr(o, name)
+ if assert_same and not name == "use_beam_LUT":
+ assert test == val
+ else:
+ setattr(o, name, val)
+
+ @staticmethod
+ def filter_index_param_dict_list(param_dict_list):
+ if (
+ param_dict_list is not None
+ and param_dict_list[0] is not None
+ and "k_factor" in param_dict_list[0]
+ ):
+ filtered = copy(param_dict_list)
+ del filtered[0]["k_factor"]
+ return filtered
+ else:
+ return param_dict_list
+
+ def is_flat(self):
+ model = faiss.downcast_index(self.get_model())
+ return isinstance(model, faiss.IndexFlat)
+
+ def is_ivf(self):
+ return False
+ model = self.get_model()
+ return faiss.try_extract_index_ivf(model) is not None
+
+ def is_2layer(self):
+ def is_2layer_(index):
+ index = faiss.downcast_index(index)
+ if isinstance(index, faiss.IndexPreTransform):
+ return is_2layer_(index.index)
+ return isinstance(index, faiss.Index2Layer)
+
+ model = self.get_model()
+ return is_2layer_(model)
+
+ def is_decode_supported(self):
+ model = self.get_model()
+ if isinstance(model, faiss.IndexPreTransform):
+ for i in range(model.chain.size()):
+ vt = faiss.downcast_VectorTransform(model.chain.at(i))
+ if isinstance(vt, faiss.ITQTransform):
+ return False
+ return True
+
+ def is_pretransform(self):
+ codec = self.get_model()
+ if isinstance(codec, faiss.IndexRefine):
+ codec = faiss.downcast_index(codec.base_index)
+ return isinstance(codec, faiss.IndexPreTransform)
+
+ # index is a codec + database vectors
+ # in other words: a trained Faiss index
+ # that contains database vectors
+ def get_index_name(self):
+ raise NotImplementedError
+
+ def get_index(self):
+ raise NotImplementedError
+
+ # codec is a trained model
+ # in other words: a trained Faiss index
+ # without any database vectors
+ def get_codec_name(self):
+ raise NotImplementedError
+
+ def get_codec(self):
+ raise NotImplementedError
+
+ # model is an untrained Faiss index
+ # it can be used for training (see codec)
+ # or to inspect its structure
+ def get_model_name(self):
+ raise NotImplementedError
+
+ def get_model(self):
+ raise NotImplementedError
+
+ def get_construction_params(self):
+ raise NotImplementedError
+
+ def transform(self, vectors):
+ transformed_vectors = DatasetDescriptor(
+ tablename=f"{vectors.get_filename()}{self.get_codec_name()}transform.npy"
+ )
+ if not self.io.file_exist(transformed_vectors.tablename):
+ codec = self.get_codec()
+ assert isinstance(codec, faiss.IndexPreTransform)
+ transform = faiss.downcast_VectorTransform(codec.chain.at(0))
+ x = self.io.get_dataset(vectors)
+ xt = transform.apply(x)
+ self.io.write_nparray(xt, transformed_vectors.tablename)
+ return transformed_vectors
+
+ def snap(self, vectors):
+ transformed_vectors = DatasetDescriptor(
+ tablename=f"{vectors.get_filename()}{self.get_codec_name()}snap.npy"
+ )
+ if not self.io.file_exist(transformed_vectors.tablename):
+ codec = self.get_codec()
+ x = self.io.get_dataset(vectors)
+ xt = codec.sa_decode(codec.sa_encode(x))
+ self.io.write_nparray(xt, transformed_vectors.tablename)
+ return transformed_vectors
+
+ def knn_search_quantizer(self, query_vectors, k):
+ if self.is_pretransform():
+ pretransform = self.get_pretransform()
+ quantizer_query_vectors = pretransform.transform(query_vectors)
+ else:
+ pretransform = None
+ quantizer_query_vectors = query_vectors
+
+ quantizer, _, _ = self.get_quantizer(
+ dry_run=False, pretransform=pretransform
+ )
+ QD, QI, _, QP, _ = quantizer.knn_search(
+ dry_run=False,
+ search_parameters=None,
+ query_vectors=quantizer_query_vectors,
+ k=k,
+ )
+ xqt = self.io.get_dataset(quantizer_query_vectors)
+ return xqt, QD, QI, QP
+
+ def get_knn_search_name(
+ self,
+ search_parameters: Optional[Dict[str, int]],
+ query_vectors: DatasetDescriptor,
+ k: int,
+ reconstruct: bool = False,
+ ):
+ name = self.get_index_name()
+ name += IndexBaseDescriptor.param_dict_to_name(search_parameters)
+ name += query_vectors.get_filename("q")
+ name += f"k_{k}."
+ name += f"t_{self.num_threads}."
+ if reconstruct:
+ name += "rec."
+ else:
+ name += "knn."
+ return name
+
+ def knn_search(
+ self,
+ dry_run,
+ search_parameters: Optional[Dict[str, int]],
+ query_vectors: DatasetDescriptor,
+ k: int,
+ I_gt=None,
+ D_gt=None,
+ ):
+ logger.info("knn_search: begin")
+ if (
+ search_parameters is not None and
+ search_parameters.get("snap", 0) == 1
+ ):
+ query_vectors = self.snap(query_vectors)
+ filename = (
+ self.get_knn_search_name(search_parameters, query_vectors, k)
+ + "zip"
+ )
+ if self.io.file_exist(filename):
+ logger.info(f"Using cached results for {filename}")
+ D, I, R, P = self.io.read_file(filename, ["D", "I", "R", "P"])
+ else:
+ if dry_run:
+ return None, None, None, None, filename
+ index = self.get_index()
+ Index.set_index_param_dict(index, search_parameters)
+
+ if self.is_2layer():
+ # Index2Layer doesn't support search
+ xq = self.io.get_dataset(query_vectors)
+ xb = index.reconstruct_n(0, index.ntotal)
+ (D, I), t, _ = timer(
+ "knn_search 2layer", lambda: faiss.knn(xq, xb, k)
+ )
+ elif self.is_ivf() and not isinstance(index, faiss.IndexRefine):
+ index_ivf = faiss.extract_index_ivf(index)
+ nprobe = (
+ search_parameters["nprobe"]
+ if search_parameters is not None
+ and "nprobe" in search_parameters
+ else index_ivf.nprobe
+ )
+ xqt, QD, QI, QP = self.knn_search_quantizer(
+ query_vectors=query_vectors,
+ k=nprobe,
+ )
+ if index_ivf.parallel_mode != 2:
+ logger.info("Setting IVF parallel mode")
+ index_ivf.parallel_mode = 2
+
+ (D, I), t, repeat = timer(
+ "knn_search_preassigned",
+ lambda: index_ivf.search_preassigned(xqt, k, QI, QD),
+ )
+ # Dref, Iref = index.search(xq, k)
+ # np.testing.assert_array_equal(I, Iref)
+ # np.testing.assert_allclose(D, Dref)
+ else:
+ xq = self.io.get_dataset(query_vectors)
+ (D, I), t, _ = timer("knn_search", lambda: index.search(xq, k))
+ if (
+ self.is_flat() or
+ not hasattr(self, "database_vectors") or
+ (self.database_vectors is None)
+ ): # TODO
+ R = D
+ else:
+ xq = self.io.get_dataset(query_vectors)
+ xb = self.io.get_dataset(self.database_vectors)
+ R = refine_distances_knn(xq, xb, I, self.metric_type)
+ P = {
+ "time": t,
+ "k": k,
+ }
+ if self.is_ivf() and not isinstance(index, faiss.IndexRefine):
+ stats = faiss.cvar.indexIVF_stats
+ P |= {
+ "quantizer": QP,
+ "nq": int(stats.nq // repeat),
+ "nlist": int(stats.nlist // repeat),
+ "ndis": int(stats.ndis // repeat),
+ "nheap_updates": int(stats.nheap_updates // repeat),
+ "quantization_time": int(
+ stats.quantization_time // repeat
+ ),
+ "search_time": int(stats.search_time // repeat),
+ }
+ self.io.write_file(filename, ["D", "I", "R", "P"], [D, I, R, P])
+ P |= {
+ "index": self.get_index_name(),
+ "codec": self.get_codec_name(),
+ "factory": self.get_model_name(),
+ "construction_params": self.get_construction_params(),
+ "search_params": search_parameters,
+ "knn_intersection": (
+ knn_intersection_measure(
+ I,
+ I_gt,
+ )
+ if I_gt is not None
+ else None
+ ),
+ "distance_ratio": (
+ distance_ratio_measure(
+ I,
+ R,
+ D_gt,
+ self.metric_type,
+ )
+ if D_gt is not None
+ else None
+ ),
+ }
+ logger.info("knn_search: end")
+ return D, I, R, P, None
+
+ def reconstruct(
+ self,
+ dry_run,
+ parameters: Optional[Dict[str, int]],
+ query_vectors: DatasetDescriptor,
+ k: int,
+ I_gt,
+ ):
+ logger.info("reconstruct: begin")
+ filename = (
+ self.get_knn_search_name(
+ parameters, query_vectors, k, reconstruct=True
+ )
+ + "zip"
+ )
+ if self.io.file_exist(filename):
+ logger.info(f"Using cached results for {filename}")
+ (P,) = self.io.read_file(filename, ["P"])
+ P["index"] = self.get_index_name()
+ P["codec"] = self.get_codec_name()
+ P["factory"] = self.get_model_name()
+ P["reconstruct_params"] = parameters
+ P["construction_params"] = self.get_construction_params()
+ else:
+ if dry_run:
+ return None, filename
+ codec = self.get_codec()
+ codec_meta = self.fetch_meta()
+ Index.set_index_param_dict(codec, parameters)
+ xb = self.io.get_dataset(self.database_vectors)
+ xb_encoded, encode_t, _ = timer(
+ "sa_encode", lambda: codec.sa_encode(xb)
+ )
+ xq = self.io.get_dataset(query_vectors)
+ if self.is_decode_supported():
+ xb_decoded, decode_t, _ = timer(
+ "sa_decode", lambda: codec.sa_decode(xb_encoded)
+ )
+ mse = np.square(xb_decoded - xb).sum(axis=1).mean().item()
+ _, I = faiss.knn(xq, xb_decoded, k, metric=self.metric_type)
+ asym_recall = knn_intersection_measure(I, I_gt)
+ xq_decoded = codec.sa_decode(codec.sa_encode(xq))
+ _, I = faiss.knn(
+ xq_decoded, xb_decoded, k, metric=self.metric_type
+ )
+ else:
+ mse = None
+ asym_recall = None
+ decode_t = None
+ # assume hamming for sym
+ xq_encoded = codec.sa_encode(xq)
+ bin = faiss.IndexBinaryFlat(xq_encoded.shape[1] * 8)
+ bin.add(xb_encoded)
+ _, I = bin.search(xq_encoded, k)
+ sym_recall = knn_intersection_measure(I, I_gt)
+ P = {
+ "encode_time": encode_t,
+ "decode_time": decode_t,
+ "mse": mse,
+ "sym_recall": sym_recall,
+ "asym_recall": asym_recall,
+ "cpu": get_cpu_info(),
+ "num_threads": self.num_threads,
+ "index": self.get_index_name(),
+ "codec": self.get_codec_name(),
+ "factory": self.get_model_name(),
+ "reconstruct_params": parameters,
+ "construction_params": self.get_construction_params(),
+ "codec_meta": codec_meta,
+ }
+ self.io.write_file(filename, ["P"], [P])
+ logger.info("reconstruct: end")
+ return P, None
+
+ def get_range_search_name(
+ self,
+ search_parameters: Optional[Dict[str, int]],
+ query_vectors: DatasetDescriptor,
+ radius: Optional[float] = None,
+ ):
+ name = self.get_index_name()
+ name += Index.param_dict_to_name(search_parameters)
+ name += query_vectors.get_filename("q")
+ if radius is not None:
+ name += f"r_{int(radius * 1000)}."
+ else:
+ name += "r_auto."
+ return name
+
+ def range_search(
+ self,
+ dry_run,
+ search_parameters: Optional[Dict[str, int]],
+ query_vectors: DatasetDescriptor,
+ radius: Optional[float] = None,
+ ):
+ logger.info("range_search: begin")
+ if (
+ search_parameters is not None and
+ search_parameters.get("snap", 0) == 1
+ ):
+ query_vectors = self.snap(query_vectors)
+ filename = (
+ self.get_range_search_name(
+ search_parameters, query_vectors, radius
+ )
+ + "zip"
+ )
+ if self.io.file_exist(filename):
+ logger.info(f"Using cached results for {filename}")
+ lims, D, I, R, P = self.io.read_file(
+ filename, ["lims", "D", "I", "R", "P"]
+ )
+ else:
+ if dry_run:
+ return None, None, None, None, None, filename
+ xq = self.io.get_dataset(query_vectors)
+ index = self.get_index()
+ Index.set_index_param_dict(index, search_parameters)
+
+ if self.is_ivf():
+ xqt, QD, QI, QP = self.knn_search_quantizer(
+ query_vectors, search_parameters["nprobe"]
+ )
+ index_ivf = faiss.extract_index_ivf(index)
+ if index_ivf.parallel_mode != 2:
+ logger.info("Setting IVF parallel mode")
+ index_ivf.parallel_mode = 2
+
+ (lims, D, I), t, repeat = timer(
+ "range_search_preassigned",
+ lambda: index_ivf.range_search_preassigned(
+ xqt, radius, QI, QD
+ ),
+ )
+ else:
+ (lims, D, I), t, _ = timer(
+ "range_search", lambda: index.range_search(xq, radius)
+ )
+ if self.is_flat():
+ R = D
+ else:
+ xb = self.io.get_dataset(self.database_vectors)
+ R = refine_distances_range(
+ lims, D, I, xq, xb, self.metric_type
+ )
+ P = {
+ "time": t,
+ "radius": radius,
+ "count": len(I),
+ }
+ if self.is_ivf():
+ stats = faiss.cvar.indexIVF_stats
+ P |= {
+ "quantizer": QP,
+ "nq": int(stats.nq // repeat),
+ "nlist": int(stats.nlist // repeat),
+ "ndis": int(stats.ndis // repeat),
+ "nheap_updates": int(stats.nheap_updates // repeat),
+ "quantization_time": int(
+ stats.quantization_time // repeat
+ ),
+ "search_time": int(stats.search_time // repeat),
+ }
+ self.io.write_file(
+ filename, ["lims", "D", "I", "R", "P"], [lims, D, I, R, P]
+ )
+ P |= {
+ "index": self.get_index_name(),
+ "codec": self.get_codec_name(),
+ "factory": self.get_model_name(),
+ "construction_params": self.get_construction_params(),
+ "search_params": search_parameters,
+ }
+ logger.info("range_seach: end")
+ return lims, D, I, R, P, None
+
+
+# Common base for IndexFromCodec and IndexFromFactory,
+# but not for the sub-indices of codec-based indices
+# IndexFromQuantizer and IndexFromPreTransform, because
+# they share the configuration of their parent IndexFromCodec
+@dataclass
+class Index(IndexBase):
+ num_threads: int
+ d: int
+ metric: str
+ codec_name: Optional[str] = None
+ index_name: Optional[str] = None
+ database_vectors: Optional[DatasetDescriptor] = None
+ construction_params: Optional[List[Dict[str, int]]] = None
+ search_params: Optional[Dict[str, int]] = None
+ serialize_full_index: bool = False
+
+ bucket: Optional[str] = None
+ index_path: Optional[str] = None
+
+ cached_codec: ClassVar[OrderedDict[str, faiss.Index]] = OrderedDict()
+ cached_index: ClassVar[OrderedDict[str, faiss.Index]] = OrderedDict()
+
+ def __post_init__(self):
+ logger.info(f"Initializing metric_type to {self.metric}")
+ if isinstance(self.metric, str):
+ if self.metric == "IP":
+ self.metric_type = faiss.METRIC_INNER_PRODUCT
+ elif self.metric == "L2":
+ self.metric_type = faiss.METRIC_L2
+ else:
+ raise ValueError
+ elif isinstance(self.metric, int):
+ self.metric_type = self.metric
+ if self.metric_type == faiss.METRIC_INNER_PRODUCT:
+ self.metric = "IP"
+ elif self.metric_type == faiss.METRIC_L2:
+ self.metric = "L2"
+ else:
+ raise ValueError
+ else:
+ raise ValueError
+
+ def supports_range_search(self):
+ codec = self.get_codec()
+ return not type(codec) in [
+ faiss.IndexHNSWFlat,
+ faiss.IndexIVFFastScan,
+ faiss.IndexRefine,
+ faiss.IndexPQ,
+ ]
+
+ def fetch_codec(self):
+ raise NotImplementedError
+
+ def get_codec(self):
+ codec_name = self.get_codec_name()
+ if codec_name not in Index.cached_codec:
+ Index.cached_codec[codec_name], _, _ = self.fetch_codec()
+ if len(Index.cached_codec) > 1:
+ Index.cached_codec.popitem(last=False)
+ return Index.cached_codec[codec_name]
+
+ def get_model(self):
+ return self.get_index()
+
+ def get_model_name(self):
+ return self.get_index_name()
+
+ def get_codec_name(self) -> Optional[str]:
+ return self.codec_name
+
+ def get_index_name(self) -> Optional[str]:
+ return self.index_name
+
+ def fetch_index(self):
+ # read index from file if it is already available
+ index_filename = None
+ if self.index_path:
+ index_filename = os.path.basename(self.index_path)
+ elif self.index_name:
+ index_filename = self.index_name + "index"
+ if index_filename and self.io.file_exist(index_filename):
+ if self.index_path:
+ index = self.io.read_index(
+ index_filename,
+ self.bucket,
+ os.path.dirname(self.index_path),
+ )
+ else:
+ index = self.io.read_index(index_filename)
+ assert self.d == index.d
+ assert self.metric_type == index.metric_type
+ return index, 0
+
+ index = self.get_codec()
+ index.reset()
+ assert index.ntotal == 0
+ logger.info("Adding vectors to index")
+ xb = self.io.get_dataset(self.database_vectors)
+
+ if self.is_ivf() and not isinstance(index, faiss.IndexRefine):
+ xbt, QD, QI, QP = self.knn_search_quantizer(
+ query_vectors=self.database_vectors,
+ k=1,
+ )
+ index_ivf = faiss.extract_index_ivf(index)
+ if index_ivf.parallel_mode != 2:
+ logger.info("Setting IVF parallel mode")
+ index_ivf.parallel_mode = 2
+
+ _, t, _ = timer(
+ "add_preassigned",
+ lambda: add_preassigned(index_ivf, xbt, QI.ravel()),
+ once=True,
+ )
+ elif isinstance(index, faiss.IndexIDMap):
+ _, t, _ = timer(
+ "add_with_ids",
+ lambda: index.add_with_ids(
+ xb, np.arange(len(xb), dtype='int32')),
+ once=True,
+ )
+ else:
+ _, t, _ = timer(
+ "add",
+ lambda: index.add(xb),
+ once=True,
+ )
+ assert index.ntotal == xb.shape[0] or index_ivf.ntotal == xb.shape[0]
+ logger.info("Added vectors to index")
+ if self.serialize_full_index and index_filename:
+ codec_size = self.io.write_index(index, index_filename)
+ assert codec_size is not None
+
+ return index, t
+
+ def get_index(self):
+ index_name = self.index_name
+ # TODO(kuarora) : retrieve file from bucket and path.
+ if index_name not in Index.cached_index:
+ Index.cached_index[index_name], _ = self.fetch_index()
+ if len(Index.cached_index) > 3:
+ Index.cached_index.popitem(last=False)
+ return Index.cached_index[index_name]
+
+ def get_construction_params(self):
+ return self.construction_params
+
+ def get_code_size(self, codec=None):
+ def get_index_code_size(index):
+ index = faiss.downcast_index(index)
+ if isinstance(index, faiss.IndexPreTransform):
+ return get_index_code_size(index.index)
+ elif type(index) in [faiss.IndexRefine, faiss.IndexRefineFlat]:
+ return get_index_code_size(
+ index.base_index
+ ) + get_index_code_size(index.refine_index)
+ else:
+ return index.code_size if hasattr(index, "code_size") else 0
+
+ if codec is None:
+ codec = self.get_codec()
+ return get_index_code_size(codec)
+
+ def get_sa_code_size(self, codec=None):
+ if codec is None:
+ codec = self.get_codec()
+ try:
+ return codec.sa_code_size()
+ except:
+ return None
+
+ def get_operating_points(self):
+ op = OperatingPointsWithRanges()
+
+ def add_range_or_val(name, range):
+ op.add_range(
+ name,
+ (
+ [self.search_params[name]]
+ if self.search_params and name in self.search_params
+ else range
+ ),
+ )
+
+ add_range_or_val("snap", [0])
+ model = self.get_model()
+ model_ivf = faiss.try_extract_index_ivf(model)
+ if model_ivf is not None:
+ add_range_or_val(
+ "nprobe",
+ [2**i for i in range(12) if 2**i <= model_ivf.nlist * 0.5],
+ # [1, 2, 4, 6, 8, 10, 12, 14, 16, 20, 24, 28] + [
+ # i
+ # for i in range(32, 64, 8)
+ # if i <= model_ivf.nlist * 0.1
+ # ] + [
+ # i
+ # for i in range(64, 128, 16)
+ # if i <= model_ivf.nlist * 0.1
+ # ] + [
+ # i
+ # for i in range(128, 256, 32)
+ # if i <= model_ivf.nlist * 0.1
+ # ] + [
+ # i
+ # for i in range(256, 512, 64)
+ # if i <= model_ivf.nlist * 0.1
+ # ] + [
+ # 2**i
+ # for i in range(9, 12)
+ # if 2**i <= model_ivf.nlist * 0.1
+ # ],
+ )
+ model = faiss.downcast_index(model)
+ if isinstance(model, faiss.IndexRefine):
+ add_range_or_val(
+ "k_factor",
+ [2**i for i in range(13)],
+ )
+ elif isinstance(model, faiss.IndexHNSWFlat):
+ add_range_or_val(
+ "efSearch",
+ [2**i for i in range(3, 11)],
+ )
+ elif isinstance(model, faiss.IndexResidualQuantizer) or isinstance(
+ model, faiss.IndexProductResidualQuantizer
+ ):
+ add_range_or_val(
+ "max_beam_size",
+ [1, 2, 4, 8, 16, 32],
+ )
+ add_range_or_val(
+ "use_beam_LUT",
+ [1],
+ )
+ elif isinstance(model, faiss.IndexLocalSearchQuantizer) or isinstance(
+ model, faiss.IndexProductLocalSearchQuantizer
+ ):
+ add_range_or_val(
+ "encode_ils_iters",
+ [2, 4, 8, 16],
+ )
+ add_range_or_val(
+ "lsq_gpu",
+ [1],
+ )
+ return op
+
+ def is_flat_index(self):
+ return self.get_index_name().startswith("Flat")
+
+
+# IndexFromCodec, IndexFromQuantizer and IndexFromPreTransform
+# are used to wrap pre-trained Faiss indices (codecs)
+@dataclass
+class IndexFromCodec(Index):
+ path: Optional[str] = None # remote or local path to the codec
+
+ def __post_init__(self):
+ super().__post_init__()
+ if self.path is None and self.codec_name is None:
+ raise ValueError("path or desc_name is not set")
+
+ def get_quantizer(self):
+ if not self.is_ivf():
+ raise ValueError("Not an IVF index")
+ quantizer = IndexFromQuantizer(self)
+ quantizer.set_io(self.io)
+ return quantizer
+
+ def get_pretransform(self):
+ if not self.is_ivf():
+ raise ValueError("Not an IVF index")
+ quantizer = IndexFromPreTransform(self)
+ quantizer.set_io(self.io)
+ return quantizer
+
+ def get_model_name(self):
+ if self.path is not None:
+ return os.path.basename(self.path)
+ else:
+ return self.get_codec_name()
+
+ def fetch_meta(self, dry_run=False):
+ return None, None
+
+ def fetch_codec(self):
+ if self.path is not None:
+ codec_filename = os.path.basename(self.path)
+ remote_path = os.path.dirname(self.path)
+ else:
+ codec_filename = self.get_codec_name() + "codec"
+ remote_path = None
+
+ codec = self.io.read_index(
+ codec_filename,
+ self.bucket,
+ remote_path,
+ )
+ assert self.d == codec.d
+ assert self.metric_type == codec.metric_type
+ Index.set_index_param_dict_list(codec, self.construction_params)
+ return codec, None, None
+
+ def get_model(self):
+ return self.get_codec()
+
+
+class IndexFromQuantizer(IndexBase):
+ ivf_index: Index
+
+ def __init__(self, ivf_index: Index):
+ self.ivf_index = ivf_index
+ super().__init__()
+
+ def get_model_name(self):
+ return self.get_index_name()
+
+ def get_codec_name(self):
+ return self.get_index_name()
+
+ def get_codec(self):
+ return self.get_index()
+
+ def get_index_name(self):
+ ivf_codec_name = self.ivf_index.get_codec_name()
+ return f"{ivf_codec_name}quantizer."
+
+ def get_index(self):
+ ivf_codec = faiss.extract_index_ivf(self.ivf_index.get_codec())
+ return ivf_codec.quantizer
+
+
+class IndexFromPreTransform(IndexBase):
+ pre_transform_index: Index
+
+ def __init__(self, pre_transform_index: Index):
+ self.pre_transform_index = pre_transform_index
+ super().__init__()
+
+ def get_codec_name(self):
+ pre_transform_codec_name = self.pre_transform_index.get_codec_name()
+ return f"{pre_transform_codec_name}pretransform."
+
+ def get_codec(self):
+ return self.get_codec()
+
+
+# IndexFromFactory is for creating and training indices from scratch
+@dataclass
+class IndexFromFactory(Index):
+ factory: Optional[str] = None
+ training_vectors: Optional[DatasetDescriptor] = None
+ assemble_opaque: bool = True
+
+ def __post_init__(self):
+ super().__post_init__()
+ if self.factory is None:
+ raise ValueError("factory is not set")
+ if self.factory != "Flat" and self.training_vectors is None:
+ raise ValueError(f"training_vectors is not set for {self.factory}")
+
+ def get_codec_name(self):
+ codec_name = super().get_codec_name()
+ if codec_name is None:
+ codec_name = f"{self.factory.replace(',', '_')}."
+ codec_name += f"d_{self.d}.{self.metric.upper()}."
+ if self.factory != "Flat":
+ assert self.training_vectors is not None
+ codec_name += self.training_vectors.get_filename("xt")
+ if self.construction_params is not None:
+ codec_name += IndexBaseDescriptor.param_dict_list_to_name(self.construction_params)
+ self.codec_name = codec_name
+ return self.codec_name
+
+ def fetch_meta(self, dry_run=False):
+ meta_filename = self.get_codec_name() + "json"
+ if self.io.file_exist(meta_filename):
+ meta = self.io.read_json(meta_filename)
+ report = None
+ else:
+ _, meta, report = self.fetch_codec(dry_run=dry_run)
+ return meta, report
+
+ def fetch_codec(self, dry_run=False):
+ codec_filename = self.get_codec_name() + "codec"
+ meta_filename = self.get_codec_name() + "json"
+ if self.io.file_exist(codec_filename) and self.io.file_exist(
+ meta_filename
+ ):
+ codec = self.io.read_index(codec_filename)
+ assert self.d == codec.d
+ assert self.metric_type == codec.metric_type
+ meta = self.io.read_json(meta_filename)
+ else:
+ codec, training_time, requires = self.assemble(dry_run=dry_run)
+ if requires is not None:
+ assert dry_run
+ if requires == "":
+ return None, None, codec_filename
+ else:
+ return None, None, requires
+ codec_size = self.io.write_index(codec, codec_filename)
+ assert codec_size is not None
+ meta = {
+ "training_time": training_time,
+ "training_size": self.training_vectors.num_vectors if self.training_vectors else 0,
+ "codec_size": codec_size,
+ "sa_code_size": self.get_sa_code_size(codec),
+ "code_size": self.get_code_size(codec),
+ "cpu": get_cpu_info(),
+ }
+ self.io.write_json(meta, meta_filename, overwrite=True)
+
+ Index.set_index_param_dict_list(
+ codec, self.construction_params, assert_same=True
+ )
+ return codec, meta, None
+
+ def get_model_name(self):
+ return self.factory
+
+ def get_model(self):
+ model = faiss.index_factory(self.d, self.factory, self.metric_type)
+ Index.set_index_param_dict_list(model, self.construction_params)
+ return model
+
+ def get_pretransform(self):
+ model = self.get_model()
+ assert isinstance(model, faiss.IndexPreTransform)
+ sub_index = faiss.downcast_index(model.index)
+ if isinstance(sub_index, faiss.IndexFlat):
+ return self
+ # replace the sub-index with Flat
+ model.index = faiss.IndexFlat(model.index.d, model.index.metric_type)
+ pretransform = IndexFromFactory(
+ num_threads=self.num_threads,
+ d=model.d,
+ metric=model.metric_type,
+ database_vectors=self.database_vectors,
+ construction_params=self.construction_params,
+ search_params=None,
+ factory=reverse_index_factory(model),
+ training_vectors=self.training_vectors,
+ )
+ pretransform.set_io(self.io)
+ return pretransform
+
+ def get_quantizer(self, dry_run, pretransform=None):
+ model = self.get_model()
+ model_ivf = faiss.extract_index_ivf(model)
+ assert isinstance(model_ivf, faiss.IndexIVF)
+ assert ord(model_ivf.quantizer_trains_alone) in [0, 2]
+ if pretransform is None:
+ training_vectors = self.training_vectors
+ else:
+ training_vectors = pretransform.transform(self.training_vectors)
+ centroids, t, requires = training_vectors.k_means(
+ self.io, model_ivf.nlist, dry_run
+ )
+ if requires is not None:
+ return None, None, requires
+ quantizer = IndexFromFactory(
+ num_threads=self.num_threads,
+ d=model_ivf.quantizer.d,
+ metric=model_ivf.quantizer.metric_type,
+ database_vectors=centroids,
+ construction_params=(
+ self.construction_params[1:]
+ if self.construction_params is not None
+ else None
+ ),
+ search_params=None,
+ factory=reverse_index_factory(model_ivf.quantizer),
+ training_vectors=centroids,
+ )
+ quantizer.set_io(self.io)
+ return quantizer, t, None
+
+ def assemble(self, dry_run):
+ logger.info(f"assemble {self.factory}")
+ model = self.get_model()
+ t_aggregate = 0
+ # try:
+ # reverse_index_factory(model)
+ # opaque = False
+ # except NotImplementedError:
+ # opaque = True
+ if self.assemble_opaque:
+ codec = model
+ else:
+ if isinstance(model, faiss.IndexPreTransform):
+ logger.info(f"assemble: pretransform {self.factory}")
+ sub_index = faiss.downcast_index(model.index)
+ if not isinstance(sub_index, faiss.IndexFlat):
+ # replace the sub-index with Flat and fetch pre-trained
+ pretransform = self.get_pretransform()
+ codec, meta, report = pretransform.fetch_codec(
+ dry_run=dry_run
+ )
+ if report is not None:
+ return None, None, report
+ t_aggregate += meta["training_time"]
+ assert codec.is_trained
+ transformed_training_vectors = pretransform.transform(
+ self.training_vectors
+ )
+ # replace the Flat index with the required sub-index
+ wrapper = IndexFromFactory(
+ num_threads=self.num_threads,
+ d=sub_index.d,
+ metric=sub_index.metric_type,
+ database_vectors=None,
+ construction_params=self.construction_params,
+ search_params=None,
+ factory=reverse_index_factory(sub_index),
+ training_vectors=transformed_training_vectors,
+ )
+ wrapper.set_io(self.io)
+ codec.index, meta, report = wrapper.fetch_codec(
+ dry_run=dry_run
+ )
+ if report is not None:
+ return None, None, report
+ t_aggregate += meta["training_time"]
+ assert codec.index.is_trained
+ else:
+ codec = model
+ elif isinstance(model, faiss.IndexIVF):
+ logger.info(f"assemble: ivf {self.factory}")
+ # replace the quantizer
+ quantizer, t, requires = self.get_quantizer(dry_run=dry_run)
+ if requires is not None:
+ return None, None, requires
+ t_aggregate += t
+ codec = faiss.clone_index(model)
+ quantizer_index, t = quantizer.fetch_index()
+ t_aggregate += t
+ replace_ivf_quantizer(codec, quantizer_index)
+ assert codec.quantizer.is_trained
+ assert codec.nlist == codec.quantizer.ntotal
+ elif isinstance(model, faiss.IndexRefine) or isinstance(
+ model, faiss.IndexRefineFlat
+ ):
+ logger.info(f"assemble: refine {self.factory}")
+ # replace base_index
+ wrapper = IndexFromFactory(
+ num_threads=self.num_threads,
+ d=model.base_index.d,
+ metric=model.base_index.metric_type,
+ database_vectors=self.database_vectors,
+ construction_params=IndexBase.filter_index_param_dict_list(
+ self.construction_params
+ ),
+ search_params=None,
+ factory=reverse_index_factory(model.base_index),
+ training_vectors=self.training_vectors,
+ )
+ wrapper.set_io(self.io)
+ codec = faiss.clone_index(model)
+ codec.base_index, meta, requires = wrapper.fetch_codec(
+ dry_run=dry_run
+ )
+ if requires is not None:
+ return None, None, requires
+ t_aggregate += meta["training_time"]
+ assert codec.base_index.is_trained
+ else:
+ codec = model
+
+ if self.factory != "Flat":
+ if dry_run:
+ return None, None, ""
+ logger.info(f"assemble, train {self.factory}")
+ xt = self.io.get_dataset(self.training_vectors)
+ if self.training_vectors.normalize_L2:
+ faiss.normalize_L2(xt)
+ _, t, _ = timer("train", lambda: codec.train(xt), once=True)
+ t_aggregate += t
+
+ return codec, t_aggregate, None
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/optimize.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/optimize.py
new file mode 100644
index 0000000..1357d55
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/optimize.py
@@ -0,0 +1,335 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+from dataclasses import dataclass
+from typing import Dict, List, Tuple
+
+import faiss # @manual=//faiss/python:pyfaiss
+
+# from faiss.contrib.evaluation import ( # @manual=//faiss/contrib:faiss_contrib
+# OperatingPoints,
+# )
+
+from .benchmark import Benchmark
+from .descriptors import DatasetDescriptor, IndexDescriptorClassic
+from .utils import dict_merge, filter_results, ParetoMetric, ParetoMode
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class Optimizer:
+ distance_metric: str = "L2"
+ num_threads: int = 32
+ run_local: bool = True
+
+ def __post_init__(self):
+ self.cached_benchmark = None
+ if self.distance_metric == "IP":
+ self.distance_metric_type = faiss.METRIC_INNER_PRODUCT
+ elif self.distance_metric == "L2":
+ self.distance_metric_type = faiss.METRIC_L2
+ else:
+ raise ValueError
+
+ def set_io(self, benchmark_io):
+ self.io = benchmark_io
+ self.io.distance_metric = self.distance_metric
+ self.io.distance_metric_type = self.distance_metric_type
+
+ def benchmark_and_filter_candidates(
+ self,
+ index_descs,
+ training_vectors,
+ database_vectors,
+ query_vectors,
+ result_file,
+ include_flat,
+ min_accuracy,
+ pareto_metric,
+ ):
+ benchmark = Benchmark(
+ num_threads=self.num_threads,
+ training_vectors=training_vectors,
+ database_vectors=database_vectors,
+ query_vectors=query_vectors,
+ index_descs=index_descs,
+ k=10,
+ distance_metric=self.distance_metric,
+ )
+ benchmark.set_io(self.io)
+ results = benchmark.benchmark(
+ result_file=result_file, local=self.run_local, train=True, knn=True
+ )
+ assert results
+ filtered = filter_results(
+ results=results,
+ evaluation="knn",
+ accuracy_metric="knn_intersection",
+ min_accuracy=min_accuracy,
+ name_filter=None
+ if include_flat
+ else (lambda n: not n.startswith("Flat")),
+ pareto_mode=ParetoMode.GLOBAL,
+ pareto_metric=pareto_metric,
+ )
+ assert filtered
+ index_descs = [
+ IndexDescriptorClassic(
+ factory=v["factory"],
+ construction_params=v["construction_params"],
+ search_params=v["search_params"],
+ )
+ for _, _, _, _, v in filtered
+ ]
+ return index_descs, filtered
+
+ def optimize_quantizer(
+ self,
+ training_vectors: DatasetDescriptor,
+ query_vectors: DatasetDescriptor,
+ nlists: List[int],
+ min_accuracy: float,
+ ):
+ quantizer_descs = {}
+ for nlist in nlists:
+ # cluster
+ centroids, _, _ = training_vectors.k_means(
+ self.io,
+ nlist,
+ dry_run=False,
+ )
+
+ descs = [IndexDescriptorClassic(factory="Flat"),] + [
+ IndexDescriptorClassic(
+ factory="HNSW32",
+ construction_params=[{"efConstruction": 2**i}],
+ )
+ for i in range(6, 11)
+ ]
+
+ descs, _ = self.benchmark_and_filter_candidates(
+ descs,
+ training_vectors=centroids,
+ database_vectors=centroids,
+ query_vectors=query_vectors,
+ result_file=f"result_{centroids.get_filename()}json",
+ include_flat=True,
+ min_accuracy=min_accuracy,
+ pareto_metric=ParetoMetric.TIME,
+ )
+ quantizer_descs[nlist] = descs
+
+ return quantizer_descs
+
+ def optimize_ivf(
+ self,
+ result_file: str,
+ training_vectors: DatasetDescriptor,
+ database_vectors: DatasetDescriptor,
+ query_vectors: DatasetDescriptor,
+ quantizers: Dict[int, List[IndexDescriptorClassic]],
+ codecs: List[Tuple[str, str]],
+ min_accuracy: float,
+ ):
+ ivf_descs = []
+ for nlist, quantizer_descs in quantizers.items():
+ # build IVF index
+ for quantizer_desc in quantizer_descs:
+ for pretransform, fine_ivf in codecs:
+ if pretransform is None:
+ pretransform = ""
+ else:
+ pretransform = pretransform + ","
+ if quantizer_desc.construction_params is None:
+ construction_params = [
+ None,
+ quantizer_desc.search_params,
+ ]
+ else:
+ construction_params = [
+ None
+ ] + quantizer_desc.construction_params
+ if quantizer_desc.search_params is not None:
+ dict_merge(
+ construction_params[1],
+ quantizer_desc.search_params,
+ )
+ ivf_descs.append(
+ IndexDescriptorClassic(
+ factory=f"{pretransform}IVF{nlist}({quantizer_desc.factory}),{fine_ivf}",
+ construction_params=construction_params,
+ )
+ )
+ return self.benchmark_and_filter_candidates(
+ ivf_descs,
+ training_vectors,
+ database_vectors,
+ query_vectors,
+ result_file,
+ include_flat=False,
+ min_accuracy=min_accuracy,
+ pareto_metric=ParetoMetric.TIME_SPACE,
+ )
+
+ # train an IVFFlat index
+ # find the nprobe required for the given accuracy
+ def ivf_flat_nprobe_required_for_accuracy(
+ self,
+ result_file: str,
+ training_vectors: DatasetDescriptor,
+ database_vectors: DatasetDescriptor,
+ query_vectors: DatasetDescriptor,
+ nlist,
+ accuracy,
+ ):
+ _, results = self.benchmark_and_filter_candidates(
+ index_descs=[
+ IndexDescriptorClassic(factory=f"IVF{nlist}(Flat),Flat"),
+ ],
+ training_vectors=training_vectors,
+ database_vectors=database_vectors,
+ query_vectors=query_vectors,
+ result_file=result_file,
+ include_flat=False,
+ min_accuracy=accuracy,
+ pareto_metric=ParetoMetric.TIME,
+ )
+ nprobe = nlist // 2
+ for _, _, _, k, v in results:
+ if (
+ ".knn" in k
+ and "nprobe" in v["search_params"]
+ and v["knn_intersection"] >= accuracy
+ ):
+ nprobe = min(nprobe, v["search_params"]["nprobe"])
+ return nprobe
+
+ # train candidate IVF codecs
+ # benchmark them at the same nprobe
+ # keep only the space _and_ time Pareto optimal
+ def optimize_codec(
+ self,
+ result_file: str,
+ d: int,
+ training_vectors: DatasetDescriptor,
+ database_vectors: DatasetDescriptor,
+ query_vectors: DatasetDescriptor,
+ nlist: int,
+ nprobe: int,
+ min_accuracy: float,
+ ):
+ codecs = (
+ [
+ (None, "Flat"),
+ (None, "SQfp16"),
+ (None, "SQbf16"),
+ (None, "SQ8"),
+ (None, "SQ8_direct_signed"),
+ ] + [
+ (f"OPQ{M}_{M * dim}", f"PQ{M}x{b}")
+ for M in [8, 12, 16, 32, 48, 64, 96, 128, 192, 256]
+ if d % M == 0
+ for dim in range(2, 18, 2)
+ if M * dim <= d
+ for b in range(4, 14, 2)
+ if M * b < d * 8 # smaller than SQ8
+ ] + [
+ (None, f"PQ{M}x{b}")
+ for M in [8, 12, 16, 32, 48, 64, 96, 128, 192, 256]
+ if d % M == 0
+ for b in range(8, 14, 2)
+ if M * b < d * 8 # smaller than SQ8
+ ]
+ )
+ factory = {}
+ for opq, pq in codecs:
+ factory[
+ f"IVF{nlist},{pq}" if opq is None else f"{opq},IVF{nlist},{pq}"
+ ] = (
+ opq,
+ pq,
+ )
+
+ _, filtered = self.benchmark_and_filter_candidates(
+ index_descs=[
+ IndexDescriptorClassic(
+ factory=f"IVF{nlist},{pq}"
+ if opq is None
+ else f"{opq},IVF{nlist},{pq}",
+ search_params={
+ "nprobe": nprobe,
+ },
+ )
+ for opq, pq in codecs
+ ],
+ training_vectors=training_vectors,
+ database_vectors=database_vectors,
+ query_vectors=query_vectors,
+ result_file=result_file,
+ include_flat=False,
+ min_accuracy=min_accuracy,
+ pareto_metric=ParetoMetric.TIME_SPACE,
+ )
+ results = [
+ factory[r] for r in set(v["factory"] for _, _, _, k, v in filtered)
+ ]
+ return results
+
+ def optimize(
+ self,
+ d: int,
+ training_vectors: DatasetDescriptor,
+ database_vectors_list: List[DatasetDescriptor],
+ query_vectors: DatasetDescriptor,
+ min_accuracy: float,
+ ):
+ # train an IVFFlat index
+ # find the nprobe required for near perfect accuracy
+ nlist = 4096
+ nprobe_at_95 = self.ivf_flat_nprobe_required_for_accuracy(
+ result_file=f"result_ivf{nlist}_flat.json",
+ training_vectors=training_vectors,
+ database_vectors=database_vectors_list[0],
+ query_vectors=query_vectors,
+ nlist=nlist,
+ accuracy=0.95,
+ )
+
+ # train candidate IVF codecs
+ # benchmark them at the same nprobe
+ # keep only the space and time Pareto optima
+ codecs = self.optimize_codec(
+ result_file=f"result_ivf{nlist}_codec.json",
+ d=d,
+ training_vectors=training_vectors,
+ database_vectors=database_vectors_list[0],
+ query_vectors=query_vectors,
+ nlist=nlist,
+ nprobe=nprobe_at_95,
+ min_accuracy=min_accuracy,
+ )
+
+ # optimize coarse quantizers
+ quantizers = self.optimize_quantizer(
+ training_vectors=training_vectors,
+ query_vectors=query_vectors,
+ nlists=[4096, 8192, 16384, 32768],
+ min_accuracy=0.7,
+ )
+
+ # combine them with the codecs
+ # test them at different scales
+ for database_vectors in database_vectors_list:
+ self.optimize_ivf(
+ result_file=f"result_{database_vectors.get_filename()}json",
+ training_vectors=training_vectors,
+ database_vectors=database_vectors,
+ query_vectors=query_vectors,
+ quantizers=quantizers,
+ codecs=codecs,
+ min_accuracy=min_accuracy,
+ )
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/utils.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/utils.py
new file mode 100644
index 0000000..b21e8bb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw/utils.py
@@ -0,0 +1,248 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import functools
+import logging
+from enum import Enum
+from multiprocessing.pool import ThreadPool
+from time import perf_counter
+
+import faiss # @manual=//faiss/python:pyfaiss
+import numpy as np
+
+from faiss.contrib.evaluation import ( # @manual=//faiss/contrib:faiss_contrib
+ OperatingPoints,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def timer(name, func, once=False) -> float:
+ logger.info(f"Measuring {name}")
+ t1 = perf_counter()
+ res = func()
+ t2 = perf_counter()
+ t = t2 - t1
+ repeat = 1
+ if not once and t < 1.0:
+ repeat = int(2.0 // t)
+ logger.info(
+ f"Time for {name}: {t:.3f} seconds, repeating {repeat} times"
+ )
+ t1 = perf_counter()
+ for _ in range(repeat):
+ res = func()
+ t2 = perf_counter()
+ t = (t2 - t1) / repeat
+ logger.info(f"Time for {name}: {t:.3f} seconds")
+ return res, t, repeat
+
+
+def refine_distances_knn(
+ xq: np.ndarray,
+ xb: np.ndarray,
+ I: np.ndarray,
+ metric,
+):
+ """Recompute distances between xq[i] and xb[I[i, :]]"""
+ nq, k = I.shape
+ xq = np.ascontiguousarray(xq, dtype="float32")
+ nq2, d = xq.shape
+ xb = np.ascontiguousarray(xb, dtype="float32")
+ nb, d2 = xb.shape
+ I = np.ascontiguousarray(I, dtype="int64")
+ assert nq2 == nq
+ assert d2 == d
+ D = np.empty(I.shape, dtype="float32")
+ D[:] = np.inf
+ if metric == faiss.METRIC_L2:
+ faiss.fvec_L2sqr_by_idx(
+ faiss.swig_ptr(D),
+ faiss.swig_ptr(xq),
+ faiss.swig_ptr(xb),
+ faiss.swig_ptr(I),
+ d,
+ nq,
+ k,
+ )
+ else:
+ faiss.fvec_inner_products_by_idx(
+ faiss.swig_ptr(D),
+ faiss.swig_ptr(xq),
+ faiss.swig_ptr(xb),
+ faiss.swig_ptr(I),
+ d,
+ nq,
+ k,
+ )
+ return D
+
+
+def refine_distances_range(
+ lims: np.ndarray,
+ D: np.ndarray,
+ I: np.ndarray,
+ xq: np.ndarray,
+ xb: np.ndarray,
+ metric,
+):
+ with ThreadPool(32) as pool:
+ R = pool.map(
+ lambda i: (
+ np.sum(np.square(xq[i] - xb[I[lims[i] : lims[i + 1]]]), axis=1)
+ if metric == faiss.METRIC_L2
+ else np.tensordot(
+ xq[i], xb[I[lims[i] : lims[i + 1]]], axes=(0, 1)
+ )
+ )
+ if lims[i + 1] > lims[i]
+ else [],
+ range(len(lims) - 1),
+ )
+ return np.hstack(R)
+
+
+def distance_ratio_measure(I, R, D_GT, metric):
+ sum_of_R = np.sum(np.where(I >= 0, R, 0))
+ sum_of_D_GT = np.sum(np.where(I >= 0, D_GT, 0))
+ if metric == faiss.METRIC_INNER_PRODUCT:
+ return (sum_of_R / sum_of_D_GT).item()
+ elif metric == faiss.METRIC_L2:
+ return (sum_of_D_GT / sum_of_R).item()
+ else:
+ raise RuntimeError(f"unknown metric {metric}")
+
+
+def get_cpu_info():
+ return [l for l in open("/proc/cpuinfo", "r") if "model name" in l][0][
+ 13:
+ ].strip()
+
+
+def dict_merge(target, source):
+ for k, v in source.items():
+ if isinstance(v, dict) and k in target:
+ dict_merge(target[k], v)
+ else:
+ target[k] = v
+
+
+class Cost:
+ def __init__(self, values):
+ self.values = values
+
+ def __le__(self, other):
+ return all(
+ v1 <= v2 for v1, v2 in zip(self.values, other.values, strict=True)
+ )
+
+ def __lt__(self, other):
+ return all(
+ v1 < v2 for v1, v2 in zip(self.values, other.values, strict=True)
+ )
+
+
+class ParetoMode(Enum):
+ DISABLE = 1 # no Pareto filtering
+ INDEX = 2 # index-local optima
+ GLOBAL = 3 # global optima
+
+
+class ParetoMetric(Enum):
+ TIME = 0 # time vs accuracy
+ SPACE = 1 # space vs accuracy
+ TIME_SPACE = 2 # (time, space) vs accuracy
+
+
+def range_search_recall_at_precision(experiment, precision):
+ return round(
+ max(
+ r
+ for r, p in zip(
+ experiment["range_search_pr"]["recall"],
+ experiment["range_search_pr"]["precision"],
+ )
+ if p > precision
+ ),
+ 6,
+ )
+
+
+def filter_results(
+ results,
+ evaluation,
+ accuracy_metric, # str or func
+ time_metric=None, # func or None -> use default
+ space_metric=None, # func or None -> use default
+ min_accuracy=0,
+ max_space=0,
+ max_time=0,
+ scaling_factor=1.0,
+ name_filter=None, # func
+ pareto_mode=ParetoMode.DISABLE,
+ pareto_metric=ParetoMetric.TIME,
+):
+ if isinstance(accuracy_metric, str):
+ accuracy_key = accuracy_metric
+ accuracy_metric = lambda v: v[accuracy_key]
+
+ if time_metric is None:
+ time_metric = lambda v: v["time"] * scaling_factor + (
+ v["quantizer"]["time"] if "quantizer" in v else 0
+ )
+
+ if space_metric is None:
+ space_metric = lambda v: results["indices"][v["codec"]]["code_size"]
+
+ fe = []
+ ops = {}
+ if pareto_mode == ParetoMode.GLOBAL:
+ op = OperatingPoints()
+ ops["global"] = op
+ for k, v in results["experiments"].items():
+ if f".{evaluation}" in k:
+ accuracy = accuracy_metric(v)
+ if min_accuracy > 0 and accuracy < min_accuracy:
+ continue
+ space = space_metric(v)
+ if space is None:
+ space = 0
+ if max_space > 0 and space > max_space:
+ continue
+ time = time_metric(v)
+ if max_time > 0 and time > max_time:
+ continue
+ idx_name = v["index"] + (
+ "snap"
+ if "search_params" in v and v["search_params"]["snap"] == 1
+ else ""
+ )
+ if name_filter is not None and not name_filter(idx_name):
+ continue
+ experiment = (accuracy, space, time, k, v)
+ if pareto_mode == ParetoMode.DISABLE:
+ fe.append(experiment)
+ continue
+ if pareto_mode == ParetoMode.INDEX:
+ if idx_name not in ops:
+ ops[idx_name] = OperatingPoints()
+ op = ops[idx_name]
+ if pareto_metric == ParetoMetric.TIME:
+ op.add_operating_point(experiment, accuracy, time)
+ elif pareto_metric == ParetoMetric.SPACE:
+ op.add_operating_point(experiment, accuracy, space)
+ else:
+ op.add_operating_point(
+ experiment, accuracy, Cost([time, space])
+ )
+
+ if ops:
+ for op in ops.values():
+ for v, _, _ in op.operating_points:
+ fe.append(v)
+
+ fe.sort()
+ return fe
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_codecs.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_codecs.py
new file mode 100644
index 0000000..04a9897
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_codecs.py
@@ -0,0 +1,146 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import logging
+import argparse
+import os
+
+from faiss.benchs.bench_fw.benchmark import Benchmark
+from faiss.benchs.bench_fw.benchmark_io import BenchmarkIO
+from faiss.benchs.bench_fw.descriptors import DatasetDescriptor, IndexDescriptorClassic
+from faiss.benchs.bench_fw.index import IndexFromFactory
+
+logging.basicConfig(level=logging.INFO)
+
+def factory_factory(d):
+ return [
+ ("SQ4", None, 256 * (2 ** 10), None),
+ ("SQ8", None, 256 * (2 ** 10), None),
+ ("SQfp16", None, 256 * (2 ** 10), None),
+ ("ITQ64,LSH", None, 256 * (2 ** 10), None),
+ ("Pad128,ITQ128,LSH", None, 256 * (2 ** 10), None),
+ ("Pad256,ITQ256,LSH", None, 256 * (2 ** 10), None),
+ ] + [
+ (f"OPQ32_128,Residual2x14,PQ32x{b}", None, 256 * (2 ** 14), None)
+ for b in range(8, 16, 2)
+ ] + [
+ (f"PCAR{2 ** d_out},SQ{b}", None, 256 * (2 ** 10), None)
+ for d_out in range(6, 11)
+ if 2 ** d_out <= d
+ for b in [4, 8]
+ ] + [
+ (f"OPQ{M}_{M * dim},PQ{M}x{b}", None, 256 * (2 ** b), None)
+ for M in [8, 12, 16, 32, 64, 128]
+ for dim in [2, 4, 6, 8, 12, 16]
+ if M * dim <= d
+ for b in range(8, 16, 2)
+ ] + [
+ (f"RQ{cs // b}x{b}", [{"max_beam_size": 32}], 256 * (2 ** b), {"max_beam_size": bs, "use_beam_LUT": bl})
+ for cs in [64, 128, 256, 512]
+ for b in [6, 8, 10, 12]
+ for bs in [1, 2, 4, 8, 16, 32]
+ for bl in [0, 1]
+ if cs // b > 1
+ if cs // b < 65
+ if cs < d * 8 * 2
+ ] + [
+ (f"LSQ{cs // b}x{b}", [{"encode_ils_iters": 16}], 256 * (2 ** b), {"encode_ils_iters": eii, "lsq_gpu": lg})
+ for cs in [64, 128, 256, 512]
+ for b in [6, 8, 10, 12]
+ for eii in [2, 4, 8, 16]
+ for lg in [0, 1]
+ if cs // b > 1
+ if cs // b < 65
+ if cs < d * 8 * 2
+ ] + [
+ (f"PRQ{sub}x{cs // sub // b}x{b}", [{"max_beam_size": 32}], 256 * (2 ** b), {"max_beam_size": bs, "use_beam_LUT": bl})
+ for sub in [2, 3, 4, 8, 16, 32]
+ for cs in [64, 96, 128, 192, 256, 384, 512, 768, 1024, 2048]
+ for b in [6, 8, 10, 12]
+ for bs in [1, 2, 4, 8, 16, 32]
+ for bl in [0, 1]
+ if cs // sub // b > 1
+ if cs // sub // b < 65
+ if cs < d * 8 * 2
+ if d % sub == 0
+ ] + [
+ (f"PLSQ{sub}x{cs // sub // b}x{b}", [{"encode_ils_iters": 16}], 256 * (2 ** b), {"encode_ils_iters": eii, "lsq_gpu": lg})
+ for sub in [2, 3, 4, 8, 16, 32]
+ for cs in [64, 128, 256, 512, 1024, 2048]
+ for b in [6, 8, 10, 12]
+ for eii in [2, 4, 8, 16]
+ for lg in [0, 1]
+ if cs // sub // b > 1
+ if cs // sub // b < 65
+ if cs < d * 8 * 2
+ if d % sub == 0
+ ]
+
+def run_local(rp):
+ bio, d, tablename, distance_metric = rp
+ if tablename == "contriever":
+ training_vectors=DatasetDescriptor(
+ tablename="training_set.npy"
+ )
+ database_vectors=DatasetDescriptor(
+ tablename="database1M.npy",
+ )
+ query_vectors=DatasetDescriptor(
+ tablename="queries.npy",
+ )
+ else:
+ training_vectors=DatasetDescriptor(
+ namespace="std_t", tablename=tablename,
+ )
+ database_vectors=DatasetDescriptor(
+ namespace="std_d", tablename=tablename,
+ )
+ query_vectors=DatasetDescriptor(
+ namespace="std_q", tablename=tablename,
+ )
+
+ benchmark = Benchmark(
+ num_threads=32,
+ training_vectors=training_vectors,
+ database_vectors=database_vectors,
+ query_vectors=query_vectors,
+ index_descs=[
+ IndexDescriptorClassic(
+ factory=factory,
+ construction_params=construction_params,
+ training_size=training_size,
+ search_params=search_params,
+ )
+ for factory, construction_params, training_size, search_params in factory_factory(d)
+ ],
+ k=1,
+ distance_metric=distance_metric,
+ )
+ benchmark.set_io(bio)
+ benchmark.benchmark(result_file="result.json", train=True, reconstruct=False, knn=False, range=False)
+
+def run(bio, d, tablename, distance_metric):
+ bio.launch_jobs(run_local, [(bio, d, tablename, distance_metric)], local=True)
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument('experiment')
+ parser.add_argument('path')
+ args = parser.parse_args()
+ assert os.path.exists(args.path)
+ path = os.path.join(args.path, args.experiment)
+ if not os.path.exists(path):
+ os.mkdir(path)
+ bio = BenchmarkIO(
+ path=path,
+ )
+ if args.experiment == "sift1M":
+ run(bio, 128, "sift1M", "L2")
+ elif args.experiment == "bigann":
+ run(bio, 128, "bigann1M", "L2")
+ elif args.experiment == "deep1b":
+ run(bio, 96, "deep1M", "L2")
+ elif args.experiment == "contriever":
+ run(bio, 768, "contriever", "IP")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_ivf.py
new file mode 100644
index 0000000..b0c108b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_ivf.py
@@ -0,0 +1,125 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import logging
+import os
+
+from faiss.benchs.bench_fw.benchmark import Benchmark
+from faiss.benchs.bench_fw.benchmark_io import BenchmarkIO
+from faiss.benchs.bench_fw.descriptors import (
+ DatasetDescriptor,
+ IndexDescriptorClassic,
+)
+
+logging.basicConfig(level=logging.INFO)
+
+
+def sift1M(bio):
+ benchmark = Benchmark(
+ num_threads=32,
+ training_vectors=DatasetDescriptor(
+ namespace="std_d", tablename="sift1M"
+ ),
+ database_vectors=DatasetDescriptor(
+ namespace="std_d", tablename="sift1M"
+ ),
+ query_vectors=DatasetDescriptor(
+ namespace="std_q", tablename="sift1M"
+ ),
+ index_descs=[
+ IndexDescriptorClassic(
+ factory=f"IVF{2 ** nlist},Flat",
+ )
+ for nlist in range(8, 15)
+ ],
+ k=1,
+ distance_metric="L2",
+ )
+ benchmark.io = bio
+ benchmark.benchmark(result_file="result.json", local=True, train=True, reconstruct=False, knn=True, range=False)
+
+
+def bigann(bio):
+ for scale in [1, 2, 5, 10, 20, 50]:
+ benchmark = Benchmark(
+ num_threads=32,
+ training_vectors=DatasetDescriptor(
+ namespace="std_t", tablename="bigann1M"
+ ),
+ database_vectors=DatasetDescriptor(
+ namespace="std_d", tablename=f"bigann{scale}M"
+ ),
+ query_vectors=DatasetDescriptor(
+ namespace="std_q", tablename="bigann1M"
+ ),
+ index_descs=[
+ IndexDescriptorClassic(
+ factory=f"IVF{2 ** nlist},Flat",
+ ) for nlist in range(11, 19)
+ ] + [
+ IndexDescriptorClassic(
+ factory=f"IVF{2 ** nlist}_HNSW32,Flat",
+ construction_params=[None, {"efConstruction": 200, "efSearch": 40}],
+ ) for nlist in range(11, 19)
+ ],
+ k=1,
+ distance_metric="L2",
+ )
+ benchmark.set_io(bio)
+ benchmark.benchmark(f"result{scale}.json", local=False, train=True, reconstruct=False, knn=True, range=False)
+
+def ssnpp(bio):
+ benchmark = Benchmark(
+ num_threads=32,
+ training_vectors=DatasetDescriptor(
+ tablename="ssnpp_training_5M.npy"
+ ),
+ database_vectors=DatasetDescriptor(
+ tablename="ssnpp_database_5M.npy"
+ ),
+ query_vectors=DatasetDescriptor(
+ tablename="ssnpp_queries_10K.npy"
+ ),
+ index_descs=[
+ IndexDescriptorClassic(
+ factory=f"IVF{2 ** nlist},PQ256x4fs,Refine(SQfp16)",
+ ) for nlist in range(9, 16)
+ ] + [
+ IndexDescriptorClassic(
+ factory=f"IVF{2 ** nlist},Flat",
+ ) for nlist in range(9, 16)
+ ] + [
+ IndexDescriptorClassic(
+ factory=f"PQ256x4fs,Refine(SQfp16)",
+ ),
+ IndexDescriptorClassic(
+ factory=f"HNSW32",
+ ),
+ ],
+ k=1,
+ distance_metric="L2",
+ )
+ benchmark.set_io(bio)
+ benchmark.benchmark("result.json", local=False, train=True, reconstruct=False, knn=True, range=False)
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument('experiment')
+ parser.add_argument('path')
+ args = parser.parse_args()
+ assert os.path.exists(args.path)
+ path = os.path.join(args.path, args.experiment)
+ if not os.path.exists(path):
+ os.mkdir(path)
+ bio = BenchmarkIO(
+ path=path,
+ )
+ if args.experiment == "sift1M":
+ sift1M(bio)
+ elif args.experiment == "bigann":
+ bigann(bio)
+ elif args.experiment == "ssnpp":
+ ssnpp(bio)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_notebook.ipynb b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_notebook.ipynb
new file mode 100644
index 0000000..c38ed11
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_notebook.ipynb
@@ -0,0 +1,532 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "be081589-e1b2-4569-acb7-44203e273899",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "import matplotlib.pyplot as plt\n",
+ "import itertools\n",
+ "from faiss.contrib.evaluation import OperatingPoints\n",
+ "from enum import Enum\n",
+ "from faiss.benchs.bench_fw.benchmark_io import BenchmarkIO as BIO\n",
+ "from faiss.benchs.bench_fw.utils import filter_results, ParetoMode, ParetoMetric\n",
+ "from copy import copy\n",
+ "import numpy as np\n",
+ "import datetime\n",
+ "import glob\n",
+ "import io\n",
+ "import json\n",
+ "from zipfile import ZipFile\n",
+ "import tabulate"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a6492e95-24c7-4425-bf0a-27e10e879ca6",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "import getpass\n",
+ "username = getpass.getuser()\n",
+ "root = f\"/home/{username}/simsearch/data/ivf/results/sift1M\"\n",
+ "results = BIO(root).read_json(\"result.json\")\n",
+ "results.keys()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0875d269-aef4-426d-83dd-866970f43777",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "results['experiments']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "f080a6e2-1565-418b-8732-4adeff03a099",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "def plot_metric(experiments, accuracy_title, cost_title, plot_space=False, plot=None):\n",
+ " if plot is None:\n",
+ " plot = plt.subplot()\n",
+ " x = {}\n",
+ " y = {}\n",
+ " for accuracy, space, time, k, v in experiments:\n",
+ " idx_name = v['index'] + (\"snap\" if 'search_params' in v and v['search_params'][\"snap\"] == 1 else \"\")\n",
+ " if idx_name not in x:\n",
+ " x[idx_name] = []\n",
+ " y[idx_name] = []\n",
+ " x[idx_name].append(accuracy)\n",
+ " if plot_space:\n",
+ " y[idx_name].append(space)\n",
+ " else:\n",
+ " y[idx_name].append(time)\n",
+ "\n",
+ " #plt.figure(figsize=(10,6))\n",
+ " #plt.title(accuracy_title)\n",
+ " plot.set_xlabel(accuracy_title)\n",
+ " plot.set_ylabel(cost_title)\n",
+ " plot.set_yscale(\"log\")\n",
+ " marker = itertools.cycle((\"o\", \"v\", \"^\", \"<\", \">\", \"s\", \"p\", \"P\", \"*\", \"h\", \"X\", \"D\")) \n",
+ " for index in x.keys():\n",
+ " plot.plot(x[index], y[index], marker=next(marker), label=index, linewidth=0)\n",
+ " plot.legend(bbox_to_anchor=(1, 1), loc='upper left')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "61007155-5edc-449e-835e-c141a01a2ae5",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "# index local optima\n",
+ "accuracy_metric = \"knn_intersection\"\n",
+ "fr = filter_results(results, evaluation=\"knn\", accuracy_metric=accuracy_metric, pareto_mode=ParetoMode.INDEX, pareto_metric=ParetoMetric.TIME, scaling_factor=1, min_accuracy=0.95)\n",
+ "plot_metric(fr, accuracy_title=\"knn intersection\", cost_title=\"time (seconds, 32 cores)\", plot_space=False)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f9f94dcc-5abe-4cad-9619-f5d1d24fb8c1",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "# global optima\n",
+ "accuracy_metric = \"knn_intersection\"\n",
+ "fr = filter_results(results, evaluation=\"knn\", accuracy_metric=accuracy_metric, min_accuracy=0.25, name_filter=lambda n: not n.startswith(\"Flat\"), pareto_mode=ParetoMode.GLOBAL, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ "#fr = filter_results(results, evaluation=\"knn\", accuracy_metric=accuracy_metric, min_accuracy=0.90, max_space=64, max_time=0, name_filter=lambda n: not n.startswith(\"Flat\"), pareto_mode=ParetoMode.GLOBAL, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ "plot_metric(fr, accuracy_title=\"knn intersection\", cost_title=\"time (seconds, 32 cores)\", plot_space=False)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0c10f587-26ef-49ec-83a9-88f6a2a433e8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def pretty_params(p):\n",
+ " p = copy(p)\n",
+ " if 'snap' in p and p['snap'] == 0:\n",
+ " del p['snap']\n",
+ " return p\n",
+ " \n",
+ "tabulate.tabulate([(accuracy, space, time, v['factory'], pretty_params(v['construction_params'][1]), pretty_params(v['search_params'])) \n",
+ " for accuracy, space, time, k, v in fr],\n",
+ " tablefmt=\"html\",\n",
+ " headers=[\"accuracy\",\"space\", \"time\", \"factory\", \"quantizer cfg\", \"search cfg\"])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "36e82084-18f6-4546-a717-163eb0224ee8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# index local optima @ precision 0.8\n",
+ "precision = 0.8\n",
+ "accuracy_metric = lambda exp: range_search_recall_at_precision(exp, precision)\n",
+ "fr = filter_results(results, evaluation=\"weighted\", accuracy_metric=accuracy_metric, pareto_mode=ParetoMode.INDEX, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ "plot_metric(fr, accuracy_title=f\"range recall @ precision {precision}\", cost_title=\"time (seconds, 16 cores)\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "aff79376-39f7-47c0-8b83-1efe5192bb7e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# index local optima @ precision 0.2\n",
+ "precision = 0.2\n",
+ "accuracy_metric = lambda exp: range_search_recall_at_precision(exp, precision)\n",
+ "fr = filter_results(results, evaluation=\"weighted\", accuracy_metric=accuracy_metric, pareto_mode=ParetoMode.INDEX, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ "plot_metric(fr, accuracy_title=f\"range recall @ precision {precision}\", cost_title=\"time (seconds, 16 cores)\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b4834f1f-bbbe-4cae-9aa0-a459b0c842d1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# global optima @ precision 0.8\n",
+ "precision = 0.8\n",
+ "accuracy_metric = lambda exp: range_search_recall_at_precision(exp, precision)\n",
+ "fr = filter_results(results, evaluation=\"weighted\", accuracy_metric=accuracy_metric, pareto_mode=ParetoMode.GLOBAL, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ "plot_metric(fr, accuracy_title=f\"range recall @ precision {precision}\", cost_title=\"time (seconds, 16 cores)\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "9aead830-6209-4956-b7ea-4a5e0029d616",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def plot_range_search_pr_curves(experiments):\n",
+ " x = {}\n",
+ " y = {}\n",
+ " show = {\n",
+ " 'Flat': None,\n",
+ " }\n",
+ " for _, _, _, k, v in fr:\n",
+ " if \".weighted\" in k: # and v['index'] in show:\n",
+ " x[k] = v['range_search_pr']['recall']\n",
+ " y[k] = v['range_search_pr']['precision']\n",
+ " \n",
+ " plt.title(\"range search recall\")\n",
+ " plt.xlabel(\"recall\")\n",
+ " plt.ylabel(\"precision\")\n",
+ " for index in x.keys():\n",
+ " plt.plot(x[index], y[index], '.', label=index)\n",
+ " plt.legend(bbox_to_anchor=(1.0, 1.0), loc='upper left')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "92e45502-7a31-4a15-90df-fa3032d7d350",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "precision = 0.8\n",
+ "accuracy_metric = lambda exp: range_search_recall_at_precision(exp, precision)\n",
+ "fr = filter_results(results, evaluation=\"weighted\", accuracy_metric=accuracy_metric, pareto_mode=ParetoMode.GLOBAL, pareto_metric=ParetoMetric.TIME_SPACE, scaling_factor=1)\n",
+ "plot_range_search_pr_curves(fr)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "fdf8148a-0da6-4c5e-8d60-f8f85314574c",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "root = \"/checkpoint/gsz/bench_fw/ivf/bigann\"\n",
+ "scales = [1, 2, 5, 10, 20, 50]\n",
+ "fig, plots = plt.subplots(len(scales), sharex=True, figsize=(5,25))\n",
+ "fig.tight_layout()\n",
+ "for plot, scale in zip(plots, scales, strict=True):\n",
+ " results = BIO(root).read_json(f\"result{scale}.json\")\n",
+ " accuracy_metric = \"knn_intersection\"\n",
+ " fr = filter_results(results, evaluation=\"knn\", accuracy_metric=accuracy_metric, min_accuracy=0.9, pareto_mode=ParetoMode.GLOBAL, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ " plot_metric(fr, accuracy_title=\"knn intersection\", cost_title=\"time (seconds, 64 cores)\", plot=plot)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e503828c-ee61-45f7-814b-cce6461109bc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = {}\n",
+ "y = {}\n",
+ "accuracy=0.9\n",
+ "root = \"/checkpoint/gsz/bench_fw/ivf/bigann\"\n",
+ "scales = [1, 2, 5, 10, 20, 50]\n",
+ "#fig, plots = plt.subplots(len(scales), sharex=True, figsize=(5,25))\n",
+ "#fig.tight_layout()\n",
+ "for scale in scales:\n",
+ " results = BIO(root).read_json(f\"result{scale}.json\")\n",
+ " scale *= 1_000_000\n",
+ " accuracy_metric = \"knn_intersection\"\n",
+ " fr = filter_results(results, evaluation=\"knn\", accuracy_metric=accuracy_metric, min_accuracy=accuracy, pareto_mode=ParetoMode.INDEX, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ " seen = set()\n",
+ " print(scale)\n",
+ " for _, _, _, _, exp in fr:\n",
+ " fact = exp[\"factory\"]\n",
+ " # \"HNSW\" in fact or \n",
+ " if fact in seen or fact in [\"Flat\", \"IVF512,Flat\", \"IVF1024,Flat\", \"IVF2048,Flat\"]:\n",
+ " continue\n",
+ " seen.add(fact)\n",
+ " if fact not in x:\n",
+ " x[fact] = []\n",
+ " y[fact] = []\n",
+ " x[fact].append(scale)\n",
+ " y[fact].append(exp[\"time\"] + exp[\"quantizer\"][\"time\"])\n",
+ " if (exp[\"knn_intersection\"] > 0.92):\n",
+ " print(fact)\n",
+ " print(exp[\"search_params\"])\n",
+ " print(exp[\"knn_intersection\"])\n",
+ "\n",
+ " #plot_metric(fr, accuracy_title=\"knn intersection\", cost_title=\"time (seconds, 64 cores)\", plot=plot)\n",
+ " \n",
+ "plt.title(f\"recall @ 1 = {accuracy*100}%\")\n",
+ "plt.xlabel(\"database size\")\n",
+ "plt.ylabel(\"time\")\n",
+ "plt.xscale(\"log\")\n",
+ "plt.yscale(\"log\")\n",
+ "\n",
+ "marker = itertools.cycle((\"o\", \"v\", \"^\", \"<\", \">\", \"s\", \"p\", \"P\", \"*\", \"h\", \"X\", \"D\")) \n",
+ "for index in x.keys():\n",
+ " if \"HNSW\" in index:\n",
+ " plt.plot(x[index], y[index], label=index, linewidth=1, marker=next(marker), linestyle=\"dashed\")\n",
+ " else:\n",
+ " plt.plot(x[index], y[index], label=index, linewidth=1, marker=next(marker))\n",
+ "plt.legend(bbox_to_anchor=(1.0, 1.0), loc='upper left')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "37a99bb2-f998-461b-a345-7cc6e702cb3a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# global optima\n",
+ "accuracy_metric = \"sym_recall\"\n",
+ "fr = filter_results(results, evaluation=\"rec\", accuracy_metric=accuracy_metric, time_metric=lambda e:e['encode_time'], min_accuracy=0.9, pareto_mode=ParetoMode.GLOBAL, pareto_metric=ParetoMetric.SPACE, scaling_factor=1)\n",
+ "plot_metric(fr, accuracy_title=\"knn intersection\", cost_title=\"space\", plot_space=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c973ce4e-3566-4f02-bd93-f113e3e0c791",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def pretty_time(s):\n",
+ " if s is None:\n",
+ " return \"None\"\n",
+ " s = int(s * 1000) / 1000\n",
+ " m, s = divmod(s, 60)\n",
+ " h, m = divmod(m, 60)\n",
+ " d, h = divmod(h, 24)\n",
+ " r = \"\"\n",
+ " if d > 0:\n",
+ " r += f\"{int(d)}d \"\n",
+ " if h > 0:\n",
+ " r += f\"{int(h)}h \"\n",
+ " if m > 0:\n",
+ " r += f\"{int(m)}m \"\n",
+ " if s > 0 or len(r) == 0:\n",
+ " r += f\"{s:.3f}s\"\n",
+ " return r\n",
+ "\n",
+ "def pretty_size(s):\n",
+ " if s > 1024 * 1024:\n",
+ " return f\"{s / 1024 / 1024:.1f}\".rstrip('0').rstrip('.') + \"MB\"\n",
+ " if s > 1024:\n",
+ " return f\"{s / 1024:.1f}\".rstrip('0').rstrip('.') + \"KB\"\n",
+ " return f\"{s}\"\n",
+ "\n",
+ "def pretty_mse(m):\n",
+ " if m is None:\n",
+ " return \"None\"\n",
+ " else:\n",
+ " return f\"{m:.6f}\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1ddcf226-fb97-4a59-9fc3-3ed8f7d5e703",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data = {}\n",
+ "root = \"/checkpoint/gsz/bench_fw/bigann\"\n",
+ "scales = [1, 2, 5, 10, 20, 50]\n",
+ "for scale in scales:\n",
+ " results = BIO(root).read_json(f\"result{scale}.json\")\n",
+ " accuracy_metric = \"knn_intersection\"\n",
+ " fr = filter_results(results, evaluation=\"knn\", accuracy_metric=accuracy_metric, min_accuracy=0, pareto_mode=ParetoMode.INDEX, pareto_metric=ParetoMetric.TIME, scaling_factor=1)\n",
+ " d = {}\n",
+ " data[f\"{scale}M\"] = d\n",
+ " for _, _, _, _, exp in fr:\n",
+ " fact = exp[\"factory\"]\n",
+ " # \"HNSW\" in fact or \n",
+ " if fact in [\"Flat\", \"IVF512,Flat\", \"IVF1024,Flat\", \"IVF2048,Flat\"]:\n",
+ " continue\n",
+ " if fact not in d:\n",
+ " d[fact] = []\n",
+ " d[fact].append({\n",
+ " \"nprobe\": exp[\"search_params\"][\"nprobe\"],\n",
+ " \"recall\": exp[\"knn_intersection\"],\n",
+ " \"time\": exp[\"time\"] + exp[\"quantizer\"][\"time\"],\n",
+ " })\n",
+ "data\n",
+ "# with open(\"/checkpoint/gsz/bench_fw/codecs.json\", \"w\") as f:\n",
+ "# json.dump(data, f)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e54eebb6-0a9f-4a72-84d2-f12c5bd44510",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ds = \"deep1b\"\n",
+ "data = []\n",
+ "jss = []\n",
+ "root = f\"/checkpoint/gsz/bench_fw/codecs/{ds}\"\n",
+ "results = BIO(root).read_json(f\"result.json\")\n",
+ "for k, e in results[\"experiments\"].items():\n",
+ " if \"rec\" in k and e['factory'] != 'Flat': # and e['sym_recall'] > 0.0: # and \"PRQ\" in e['factory'] and e['sym_recall'] > 0.0:\n",
+ " code_size = results['indices'][e['codec']]['sa_code_size']\n",
+ " codec_size = results['indices'][e['codec']]['codec_size']\n",
+ " training_time = results['indices'][e['codec']]['training_time']\n",
+ " # training_size = results['indices'][e['codec']]['training_size']\n",
+ " cpu = e['cpu'] if 'cpu' in e else \"\"\n",
+ " ps = ', '.join([f\"{k}={v}\" for k,v in e['construction_params'][0].items()]) if e['construction_params'] else \" \"\n",
+ " eps = ', '.join([f\"{k}={v}\" for k,v in e['reconstruct_params'].items() if k != \"snap\"]) if e['reconstruct_params'] else \" \"\n",
+ " data.append((code_size, f\"|{e['factory']}|{ps}|{eps}|{code_size}|{pretty_size(codec_size)}|{pretty_time(training_time)}|{training_size}|{pretty_mse(e['mse'])}|{e['sym_recall']}|{e['asym_recall']}|{pretty_time(e['encode_time'])}|{pretty_time(e['decode_time'])}|{cpu}|\"))\n",
+ " jss.append({\n",
+ " 'factory': e['factory'],\n",
+ " 'parameters': e['construction_params'][0] if e['construction_params'] else \"\",\n",
+ " 'evaluation_params': e['reconstruct_params'],\n",
+ " 'code_size': code_size,\n",
+ " 'codec_size': codec_size,\n",
+ " 'training_time': training_time,\n",
+ " 'training_size': training_size,\n",
+ " 'mse': e['mse'],\n",
+ " 'sym_recall': e['sym_recall'],\n",
+ " 'asym_recall': e['asym_recall'],\n",
+ " 'encode_time': e['encode_time'],\n",
+ " 'decode_time': e['decode_time'],\n",
+ " 'cpu': cpu,\n",
+ " })\n",
+ "\n",
+ "print(\"|factory key|construction parameters|evaluation parameters|code size|codec size|training time|training size|mean squared error|sym recall @ 1|asym recall @ 1|encode time|decode time|cpu|\")\n",
+ "print(\"|-|-|-|-|-|-|-|-|-|\")\n",
+ "data.sort()\n",
+ "for d in data:\n",
+ " print(d[1])\n",
+ "\n",
+ "with open(f\"/checkpoint/gsz/bench_fw/codecs_{ds}_test.json\", \"w\") as f:\n",
+ " json.dump(jss, f)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d1216733-9670-407c-b3d2-5f87bce0321c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def read_file(filename: str, keys):\n",
+ " results = []\n",
+ " with ZipFile(filename, \"r\") as zip_file:\n",
+ " for key in keys:\n",
+ " with zip_file.open(key, \"r\") as f:\n",
+ " if key in [\"D\", \"I\", \"R\", \"lims\"]:\n",
+ " results.append(np.load(f))\n",
+ " elif key in [\"P\"]:\n",
+ " t = io.TextIOWrapper(f)\n",
+ " results.append(json.load(t))\n",
+ " else:\n",
+ " raise AssertionError()\n",
+ " return results"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "56de051e-22db-4bef-b242-1ddabc9e0bb9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ds = \"contriever\"\n",
+ "data = []\n",
+ "jss = []\n",
+ "root = f\"/checkpoint/gsz/bench_fw/codecs/{ds}\"\n",
+ "for lf in glob.glob(root + '/*rec*.zip'):\n",
+ " e, = read_file(lf, ['P'])\n",
+ " if e['factory'] != 'Flat': # and e['sym_recall'] > 0.0: # and \"PRQ\" in e['factory'] and e['sym_recall'] > 0.0:\n",
+ " code_size = e['codec_meta']['sa_code_size']\n",
+ " codec_size = e['codec_meta']['codec_size']\n",
+ " training_time = e['codec_meta']['training_time']\n",
+ " training_size = None # e['codec_meta']['training_size']\n",
+ " cpu = e['cpu'] if 'cpu' in e else \"\"\n",
+ " ps = ', '.join([f\"{k}={v}\" for k,v in e['construction_params'][0].items()]) if e['construction_params'] else \" \"\n",
+ " eps = ', '.join([f\"{k}={v}\" for k,v in e['reconstruct_params'].items() if k != \"snap\"]) if e['reconstruct_params'] else \" \"\n",
+ " if eps in ps and eps != \"encode_ils_iters=16\" and eps != \"max_beam_size=32\":\n",
+ " eps = \" \"\n",
+ " data.append((code_size, f\"|{e['factory']}|{ps}|{eps}|{code_size}|{pretty_size(codec_size)}|{pretty_time(training_time)}|{pretty_mse(e['mse'])}|{e['sym_recall']}|{e['asym_recall']}|{pretty_time(e['encode_time'])}|{pretty_time(e['decode_time'])}|{cpu}|\"))\n",
+ " eps = e['reconstruct_params']\n",
+ " del eps['snap']\n",
+ " params = copy(e['construction_params'][0]) if e['construction_params'] else {}\n",
+ " for k, v in e['reconstruct_params'].items():\n",
+ " params[k] = v\n",
+ " jss.append({\n",
+ " 'factory': e['factory'],\n",
+ " 'params': params,\n",
+ " 'construction_params': e['construction_params'][0] if e['construction_params'] else {},\n",
+ " 'evaluation_params': e['reconstruct_params'],\n",
+ " 'code_size': code_size,\n",
+ " 'codec_size': codec_size,\n",
+ " 'training_time': training_time,\n",
+ " # 'training_size': training_size,\n",
+ " 'mse': e['mse'],\n",
+ " 'sym_recall': e['sym_recall'],\n",
+ " 'asym_recall': e['asym_recall'],\n",
+ " 'encode_time': e['encode_time'],\n",
+ " 'decode_time': e['decode_time'],\n",
+ " 'cpu': cpu,\n",
+ " })\n",
+ "\n",
+ "print(\"|factory key|construction parameters|encode/decode parameters|code size|codec size|training time|mean squared error|sym recall @ 1|asym recall @ 1|encode time|decode time|cpu|\")\n",
+ "print(\"|-|-|-|-|-|-|-|-|-|\")\n",
+ "data.sort()\n",
+ "# for d in data:\n",
+ "# print(d[1])\n",
+ "\n",
+ "print(len(data))\n",
+ "\n",
+ "with open(f\"/checkpoint/gsz/bench_fw/codecs_{ds}_5.json\", \"w\") as f:\n",
+ " json.dump(jss, f)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "faiss_binary (local)",
+ "language": "python",
+ "name": "faiss_binary_local"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_optimize.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_optimize.py
new file mode 100644
index 0000000..11e625e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_optimize.py
@@ -0,0 +1,58 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import logging
+import os
+
+from faiss.benchs.bench_fw.benchmark_io import BenchmarkIO
+from faiss.benchs.bench_fw.descriptors import DatasetDescriptor
+from faiss.benchs.bench_fw.optimize import Optimizer
+
+logging.basicConfig(level=logging.INFO)
+
+
+def bigann(bio):
+ optimizer = Optimizer(
+ distance_metric="L2",
+ num_threads=32,
+ run_local=False,
+ )
+ optimizer.set_io(bio)
+ query_vectors = DatasetDescriptor(namespace="std_q", tablename="bigann1M")
+ xt = bio.get_dataset(query_vectors)
+ optimizer.optimize(
+ d=xt.shape[1],
+ training_vectors=DatasetDescriptor(
+ namespace="std_t",
+ tablename="bigann1M",
+ num_vectors=2_000_000,
+ ),
+ database_vectors_list=[
+ DatasetDescriptor(
+ namespace="std_d",
+ tablename="bigann1M",
+ ),
+ DatasetDescriptor(namespace="std_d", tablename="bigann10M"),
+ ],
+ query_vectors=query_vectors,
+ min_accuracy=0.85,
+ )
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("experiment")
+ parser.add_argument("path")
+ args = parser.parse_args()
+ assert os.path.exists(args.path)
+ path = os.path.join(args.path, args.experiment)
+ if not os.path.exists(path):
+ os.mkdir(path)
+ bio = BenchmarkIO(
+ path=path,
+ )
+ if args.experiment == "bigann":
+ bigann(bio)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_range.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_range.py
new file mode 100644
index 0000000..0d4b65a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_fw_range.py
@@ -0,0 +1,85 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import logging
+import os
+
+from faiss.benchs.bench_fw.benchmark import Benchmark
+from faiss.benchs.bench_fw.benchmark_io import BenchmarkIO
+from faiss.benchs.bench_fw.descriptors import DatasetDescriptor, IndexDescriptorClassic
+
+logging.basicConfig(level=logging.INFO)
+
+
+def ssnpp(bio):
+ benchmark = Benchmark(
+ num_threads=32,
+ training_vectors=DatasetDescriptor(
+ tablename="training.npy",
+ ),
+ database_vectors=DatasetDescriptor(
+ tablename="database.npy",
+ ),
+ query_vectors=DatasetDescriptor(tablename="query.npy"),
+ index_descs=[
+ IndexDescriptorClassic(
+ factory="Flat",
+ range_metrics={
+ "weighted": [
+ [0.05, 0.971],
+ [0.1, 0.956],
+ [0.15, 0.923],
+ [0.2, 0.887],
+ [0.25, 0.801],
+ [0.3, 0.729],
+ [0.35, 0.651],
+ [0.4, 0.55],
+ [0.45, 0.459],
+ [0.5, 0.372],
+ [0.55, 0.283],
+ [0.6, 0.189],
+ [0.65, 0.143],
+ [0.7, 0.106],
+ [0.75, 0.116],
+ [0.8, 0.088],
+ [0.85, 0.064],
+ [0.9, 0.05],
+ [0.95, 0.04],
+ [1.0, 0.028],
+ [1.05, 0.02],
+ [1.1, 0.013],
+ [1.15, 0.007],
+ [1.2, 0.004],
+ [1.3, 0],
+ ]
+ },
+ ),
+ IndexDescriptorClassic(
+ factory="IVF262144(PQ256x4fs),PQ32",
+ ),
+ ],
+ k=10,
+ distance_metric="L2",
+ range_ref_index_desc="Flat",
+ )
+ benchmark.set_io(bio)
+ benchmark.benchmark("result.json", local=False, train=True, reconstruct=False, knn=False, range=True)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument('experiment')
+ parser.add_argument('path')
+ args = parser.parse_args()
+ assert os.path.exists(args.path)
+ path = os.path.join(args.path, args.experiment)
+ if not os.path.exists(path):
+ os.mkdir(path)
+ bio = BenchmarkIO(
+ path=path,
+ )
+ if args.experiment == "ssnpp":
+ ssnpp(bio)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_gpu_1bn.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_gpu_1bn.py
new file mode 100644
index 0000000..935b27a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_gpu_1bn.py
@@ -0,0 +1,746 @@
+#! /usr/bin/env python2
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import numpy as np
+import time
+import os
+import sys
+import faiss
+import re
+
+from multiprocessing.pool import ThreadPool
+from datasets import ivecs_read
+
+####################################################################
+# Parse command line
+####################################################################
+
+
+def usage():
+ print("""
+
+Usage: bench_gpu_1bn.py dataset indextype [options]
+
+dataset: set of vectors to operate on.
+ Supported: SIFT1M, SIFT2M, ..., SIFT1000M or Deep1B
+
+indextype: any index type supported by index_factory that runs on GPU.
+
+ General options
+
+-ngpu ngpu nb of GPUs to use (default = all)
+-tempmem N use N bytes of temporary GPU memory
+-nocache do not read or write intermediate files
+-float16 use 16-bit floats on the GPU side
+
+ Add options
+
+-abs N split adds in blocks of no more than N vectors
+-max_add N copy sharded dataset to CPU each max_add additions
+ (to avoid memory overflows with geometric reallocations)
+-altadd Alternative add function, where the index is not stored
+ on GPU during add. Slightly faster for big datasets on
+ slow GPUs
+
+ Search options
+
+-R R: nb of replicas of the same dataset (the dataset
+ will be copied across ngpu/R, default R=1)
+-noptables do not use precomputed tables in IVFPQ.
+-qbs N split queries in blocks of no more than N vectors
+-nnn N search N neighbors for each query
+-nprobe 4,16,64 try this number of probes
+-knngraph instead of the standard setup for the dataset,
+ compute a k-nn graph with nnn neighbors per element
+-oI xx%d.npy output the search result indices to this numpy file,
+ %d will be replaced with the nprobe
+-oD xx%d.npy output the search result distances to this file
+
+""", file=sys.stderr)
+ sys.exit(1)
+
+
+# default values
+
+dbname = None
+index_key = None
+
+ngpu = faiss.get_num_gpus()
+
+replicas = 1 # nb of replicas of sharded dataset
+add_batch_size = 32768
+query_batch_size = 16384
+nprobes = [1 << l for l in range(9)]
+knngraph = False
+use_precomputed_tables = True
+tempmem = -1 # if -1, use system default
+max_add = -1
+use_float16 = False
+use_cache = True
+nnn = 10
+altadd = False
+I_fname = None
+D_fname = None
+
+args = sys.argv[1:]
+
+while args:
+ a = args.pop(0)
+ if a == '-h': usage()
+ elif a == '-ngpu': ngpu = int(args.pop(0))
+ elif a == '-R': replicas = int(args.pop(0))
+ elif a == '-noptables': use_precomputed_tables = False
+ elif a == '-abs': add_batch_size = int(args.pop(0))
+ elif a == '-qbs': query_batch_size = int(args.pop(0))
+ elif a == '-nnn': nnn = int(args.pop(0))
+ elif a == '-tempmem': tempmem = int(args.pop(0))
+ elif a == '-nocache': use_cache = False
+ elif a == '-knngraph': knngraph = True
+ elif a == '-altadd': altadd = True
+ elif a == '-float16': use_float16 = True
+ elif a == '-nprobe': nprobes = [int(x) for x in args.pop(0).split(',')]
+ elif a == '-max_add': max_add = int(args.pop(0))
+ elif not dbname: dbname = a
+ elif not index_key: index_key = a
+ else:
+ print("argument %s unknown" % a, file=sys.stderr)
+ sys.exit(1)
+
+cacheroot = '/tmp/bench_gpu_1bn'
+
+if not os.path.isdir(cacheroot):
+ print("%s does not exist, creating it" % cacheroot)
+ os.mkdir(cacheroot)
+
+#################################################################
+# Small Utility Functions
+#################################################################
+
+# we mem-map the biggest files to avoid having them in memory all at
+# once
+
+def mmap_fvecs(fname):
+ x = np.memmap(fname, dtype='int32', mode='r')
+ d = x[0]
+ return x.view('float32').reshape(-1, d + 1)[:, 1:]
+
+def mmap_bvecs(fname):
+ x = np.memmap(fname, dtype='uint8', mode='r')
+ d = x[:4].view('int32')[0]
+ return x.reshape(-1, d + 4)[:, 4:]
+
+
+def rate_limited_imap(f, l):
+ """A threaded imap that does not produce elements faster than they
+ are consumed"""
+ pool = ThreadPool(1)
+ res = None
+ for i in l:
+ res_next = pool.apply_async(f, (i, ))
+ if res:
+ yield res.get()
+ res = res_next
+ yield res.get()
+
+
+class IdentPreproc:
+ """a pre-processor is either a faiss.VectorTransform or an IndentPreproc"""
+
+ def __init__(self, d):
+ self.d_in = self.d_out = d
+
+ def apply_py(self, x):
+ return x
+
+
+def sanitize(x):
+ """ convert array to a c-contiguous float array """
+ return np.ascontiguousarray(x.astype('float32'))
+
+
+def dataset_iterator(x, preproc, bs):
+ """ iterate over the lines of x in blocks of size bs"""
+
+ nb = x.shape[0]
+ block_ranges = [(i0, min(nb, i0 + bs))
+ for i0 in range(0, nb, bs)]
+
+ def prepare_block(i01):
+ i0, i1 = i01
+ xb = sanitize(x[i0:i1])
+ return i0, preproc.apply_py(xb)
+
+ return rate_limited_imap(prepare_block, block_ranges)
+
+
+def eval_intersection_measure(gt_I, I):
+ """ measure intersection measure (used for knngraph)"""
+ inter = 0
+ rank = I.shape[1]
+ assert gt_I.shape[1] >= rank
+ for q in range(nq_gt):
+ inter += faiss.ranklist_intersection_size(
+ rank, faiss.swig_ptr(gt_I[q, :]),
+ rank, faiss.swig_ptr(I[q, :].astype('int64')))
+ return inter / float(rank * nq_gt)
+
+
+#################################################################
+# Prepare dataset
+#################################################################
+
+print("Preparing dataset", dbname)
+
+if dbname.startswith('SIFT'):
+ # SIFT1M to SIFT1000M
+ dbsize = int(dbname[4:-1])
+ xb = mmap_bvecs('bigann/bigann_base.bvecs')
+ xq = mmap_bvecs('bigann/bigann_query.bvecs')
+ xt = mmap_bvecs('bigann/bigann_learn.bvecs')
+
+ # trim xb to correct size
+ xb = xb[:dbsize * 1000 * 1000]
+
+ gt_I = ivecs_read('bigann/gnd/idx_%dM.ivecs' % dbsize)
+
+elif dbname == 'Deep1B':
+ xb = mmap_fvecs('deep1b/base.fvecs')
+ xq = mmap_fvecs('deep1b/deep1B_queries.fvecs')
+ xt = mmap_fvecs('deep1b/learn.fvecs')
+ # deep1B's train is is outrageously big
+ xt = xt[:10 * 1000 * 1000]
+ gt_I = ivecs_read('deep1b/deep1B_groundtruth.ivecs')
+
+else:
+ print('unknown dataset', dbname, file=sys.stderr)
+ sys.exit(1)
+
+
+if knngraph:
+ # convert to knn-graph dataset
+ xq = xb
+ xt = xb
+ # we compute the ground-truth on this number of queries for validation
+ nq_gt = 10000
+ gt_sl = 100
+
+ # ground truth will be computed below
+ gt_I = None
+
+
+print("sizes: B %s Q %s T %s gt %s" % (
+ xb.shape, xq.shape, xt.shape,
+ gt_I.shape if gt_I is not None else None))
+
+
+
+#################################################################
+# Parse index_key and set cache files
+#
+# The index_key is a valid factory key that would work, but we
+# decompose the training to do it faster
+#################################################################
+
+
+pat = re.compile('(OPQ[0-9]+(_[0-9]+)?,|PCAR[0-9]+,)?' +
+ '(IVF[0-9]+),' +
+ '(PQ[0-9]+|Flat)')
+
+matchobject = pat.match(index_key)
+
+assert matchobject, 'could not parse ' + index_key
+
+mog = matchobject.groups()
+
+preproc_str = mog[0]
+ivf_str = mog[2]
+pqflat_str = mog[3]
+
+ncent = int(ivf_str[3:])
+
+prefix = ''
+
+if knngraph:
+ gt_cachefile = '%s/BK_gt_%s.npy' % (cacheroot, dbname)
+ prefix = 'BK_'
+ # files must be kept distinct because the training set is not the
+ # same for the knngraph
+
+if preproc_str:
+ preproc_cachefile = '%s/%spreproc_%s_%s.vectrans' % (
+ cacheroot, prefix, dbname, preproc_str[:-1])
+else:
+ preproc_cachefile = None
+ preproc_str = ''
+
+cent_cachefile = '%s/%scent_%s_%s%s.npy' % (
+ cacheroot, prefix, dbname, preproc_str, ivf_str)
+
+index_cachefile = '%s/%s%s_%s%s,%s.index' % (
+ cacheroot, prefix, dbname, preproc_str, ivf_str, pqflat_str)
+
+
+if not use_cache:
+ preproc_cachefile = None
+ cent_cachefile = None
+ index_cachefile = None
+
+print("cachefiles:")
+print(preproc_cachefile)
+print(cent_cachefile)
+print(index_cachefile)
+
+
+#################################################################
+# Wake up GPUs
+#################################################################
+
+print("preparing resources for %d GPUs" % ngpu)
+
+gpu_resources = []
+
+for i in range(ngpu):
+ res = faiss.StandardGpuResources()
+ if tempmem >= 0:
+ res.setTempMemory(tempmem)
+ gpu_resources.append(res)
+
+
+def make_vres_vdev(i0=0, i1=-1):
+ " return vectors of device ids and resources useful for gpu_multiple"
+ vres = faiss.GpuResourcesVector()
+ vdev = faiss.IntVector()
+ if i1 == -1:
+ i1 = ngpu
+ for i in range(i0, i1):
+ vdev.push_back(i)
+ vres.push_back(gpu_resources[i])
+ return vres, vdev
+
+
+#################################################################
+# Prepare ground truth (for the knngraph)
+#################################################################
+
+
+def compute_GT():
+ print("compute GT")
+ t0 = time.time()
+
+ gt_I = np.zeros((nq_gt, gt_sl), dtype='int64')
+ gt_D = np.zeros((nq_gt, gt_sl), dtype='float32')
+ heaps = faiss.float_maxheap_array_t()
+ heaps.k = gt_sl
+ heaps.nh = nq_gt
+ heaps.val = faiss.swig_ptr(gt_D)
+ heaps.ids = faiss.swig_ptr(gt_I)
+ heaps.heapify()
+ bs = 10 ** 5
+
+ n, d = xb.shape
+ xqs = sanitize(xq[:nq_gt])
+
+ db_gt = faiss.IndexFlatL2(d)
+ vres, vdev = make_vres_vdev()
+ db_gt_gpu = faiss.index_cpu_to_gpu_multiple(
+ vres, vdev, db_gt)
+
+ # compute ground-truth by blocks of bs, and add to heaps
+ for i0, xsl in dataset_iterator(xb, IdentPreproc(d), bs):
+ db_gt_gpu.add(xsl)
+ D, I = db_gt_gpu.search(xqs, gt_sl)
+ I += i0
+ heaps.addn_with_ids(
+ gt_sl, faiss.swig_ptr(D), faiss.swig_ptr(I), gt_sl)
+ db_gt_gpu.reset()
+ print("\r %d/%d, %.3f s" % (i0, n, time.time() - t0), end=' ')
+ print()
+ heaps.reorder()
+
+ print("GT time: %.3f s" % (time.time() - t0))
+ return gt_I
+
+
+if knngraph:
+
+ if gt_cachefile and os.path.exists(gt_cachefile):
+ print("load GT", gt_cachefile)
+ gt_I = np.load(gt_cachefile)
+ else:
+ gt_I = compute_GT()
+ if gt_cachefile:
+ print("store GT", gt_cachefile)
+ np.save(gt_cachefile, gt_I)
+
+#################################################################
+# Prepare the vector transformation object (pure CPU)
+#################################################################
+
+
+def train_preprocessor():
+ print("train preproc", preproc_str)
+ d = xt.shape[1]
+ t0 = time.time()
+ if preproc_str.startswith('OPQ'):
+ fi = preproc_str[3:-1].split('_')
+ m = int(fi[0])
+ dout = int(fi[1]) if len(fi) == 2 else d
+ preproc = faiss.OPQMatrix(d, m, dout)
+ elif preproc_str.startswith('PCAR'):
+ dout = int(preproc_str[4:-1])
+ preproc = faiss.PCAMatrix(d, dout, 0, True)
+ else:
+ assert False
+ preproc.train(sanitize(xt[:1000000]))
+ print("preproc train done in %.3f s" % (time.time() - t0))
+ return preproc
+
+
+def get_preprocessor():
+ if preproc_str:
+ if not preproc_cachefile or not os.path.exists(preproc_cachefile):
+ preproc = train_preprocessor()
+ if preproc_cachefile:
+ print("store", preproc_cachefile)
+ faiss.write_VectorTransform(preproc, preproc_cachefile)
+ else:
+ print("load", preproc_cachefile)
+ preproc = faiss.read_VectorTransform(preproc_cachefile)
+ else:
+ d = xb.shape[1]
+ preproc = IdentPreproc(d)
+ return preproc
+
+
+#################################################################
+# Prepare the coarse quantizer
+#################################################################
+
+
+def train_coarse_quantizer(x, k, preproc):
+ d = preproc.d_out
+ clus = faiss.Clustering(d, k)
+ clus.verbose = True
+ # clus.niter = 2
+ clus.max_points_per_centroid = 10000000
+
+ print("apply preproc on shape", x.shape, 'k=', k)
+ t0 = time.time()
+ x = preproc.apply_py(sanitize(x))
+ print(" preproc %.3f s output shape %s" % (
+ time.time() - t0, x.shape))
+
+ vres, vdev = make_vres_vdev()
+ index = faiss.index_cpu_to_gpu_multiple(
+ vres, vdev, faiss.IndexFlatL2(d))
+
+ clus.train(x, index)
+ centroids = faiss.vector_float_to_array(clus.centroids)
+
+ return centroids.reshape(k, d)
+
+
+def prepare_coarse_quantizer(preproc):
+
+ if cent_cachefile and os.path.exists(cent_cachefile):
+ print("load centroids", cent_cachefile)
+ centroids = np.load(cent_cachefile)
+ else:
+ nt = max(1000000, 256 * ncent)
+ print("train coarse quantizer...")
+ t0 = time.time()
+ centroids = train_coarse_quantizer(xt[:nt], ncent, preproc)
+ print("Coarse train time: %.3f s" % (time.time() - t0))
+ if cent_cachefile:
+ print("store centroids", cent_cachefile)
+ np.save(cent_cachefile, centroids)
+
+ coarse_quantizer = faiss.IndexFlatL2(preproc.d_out)
+ coarse_quantizer.add(centroids)
+
+ return coarse_quantizer
+
+
+#################################################################
+# Make index and add elements to it
+#################################################################
+
+
+def prepare_trained_index(preproc):
+
+ coarse_quantizer = prepare_coarse_quantizer(preproc)
+ d = preproc.d_out
+ if pqflat_str == 'Flat':
+ print("making an IVFFlat index")
+ idx_model = faiss.IndexIVFFlat(coarse_quantizer, d, ncent,
+ faiss.METRIC_L2)
+ else:
+ m = int(pqflat_str[2:])
+ assert m < 56 or use_float16, "PQ%d will work only with -float16" % m
+ print("making an IVFPQ index, m = ", m)
+ idx_model = faiss.IndexIVFPQ(coarse_quantizer, d, ncent, m, 8)
+
+ coarse_quantizer.this.disown()
+ idx_model.own_fields = True
+
+ # finish training on CPU
+ t0 = time.time()
+ print("Training vector codes")
+ x = preproc.apply_py(sanitize(xt[:1000000]))
+ idx_model.train(x)
+ print(" done %.3f s" % (time.time() - t0))
+
+ return idx_model
+
+
+def compute_populated_index(preproc):
+ """Add elements to a sharded index. Return the index and if available
+ a sharded gpu_index that contains the same data. """
+
+ indexall = prepare_trained_index(preproc)
+
+ co = faiss.GpuMultipleClonerOptions()
+ co.useFloat16 = use_float16
+ co.useFloat16CoarseQuantizer = False
+ co.usePrecomputed = use_precomputed_tables
+ co.indicesOptions = faiss.INDICES_CPU
+ co.verbose = True
+ co.reserveVecs = max_add if max_add > 0 else xb.shape[0]
+ co.shard = True
+ assert co.shard_type in (0, 1, 2)
+ vres, vdev = make_vres_vdev()
+ gpu_index = faiss.index_cpu_to_gpu_multiple(
+ vres, vdev, indexall, co)
+
+ print("add...")
+ t0 = time.time()
+ nb = xb.shape[0]
+ for i0, xs in dataset_iterator(xb, preproc, add_batch_size):
+ i1 = i0 + xs.shape[0]
+ gpu_index.add_with_ids(xs, np.arange(i0, i1))
+ if max_add > 0 and gpu_index.ntotal > max_add:
+ print("Flush indexes to CPU")
+ for i in range(ngpu):
+ index_src_gpu = faiss.downcast_index(gpu_index.at(i))
+ index_src = faiss.index_gpu_to_cpu(index_src_gpu)
+ print(" index %d size %d" % (i, index_src.ntotal))
+ index_src.copy_subset_to(indexall, 0, 0, nb)
+ index_src_gpu.reset()
+ index_src_gpu.reserveMemory(max_add)
+ gpu_index.sync_with_shard_indexes()
+
+ print('\r%d/%d (%.3f s) ' % (
+ i0, nb, time.time() - t0), end=' ')
+ sys.stdout.flush()
+ print("Add time: %.3f s" % (time.time() - t0))
+
+ print("Aggregate indexes to CPU")
+ t0 = time.time()
+
+ if hasattr(gpu_index, 'at'):
+ # it is a sharded index
+ for i in range(ngpu):
+ index_src = faiss.index_gpu_to_cpu(gpu_index.at(i))
+ print(" index %d size %d" % (i, index_src.ntotal))
+ index_src.copy_subset_to(indexall, 0, 0, nb)
+ else:
+ # simple index
+ index_src = faiss.index_gpu_to_cpu(gpu_index)
+ index_src.copy_subset_to(indexall, 0, 0, nb)
+
+ print(" done in %.3f s" % (time.time() - t0))
+
+ if max_add > 0:
+ # it does not contain all the vectors
+ gpu_index = None
+
+ return gpu_index, indexall
+
+def compute_populated_index_2(preproc):
+
+ indexall = prepare_trained_index(preproc)
+
+ # set up a 3-stage pipeline that does:
+ # - stage 1: load + preproc
+ # - stage 2: assign on GPU
+ # - stage 3: add to index
+
+ stage1 = dataset_iterator(xb, preproc, add_batch_size)
+
+ vres, vdev = make_vres_vdev()
+ coarse_quantizer_gpu = faiss.index_cpu_to_gpu_multiple(
+ vres, vdev, indexall.quantizer)
+
+ def quantize(args):
+ (i0, xs) = args
+ _, assign = coarse_quantizer_gpu.search(xs, 1)
+ return i0, xs, assign.ravel()
+
+ stage2 = rate_limited_imap(quantize, stage1)
+
+ print("add...")
+ t0 = time.time()
+ nb = xb.shape[0]
+
+ for i0, xs, assign in stage2:
+ i1 = i0 + xs.shape[0]
+ if indexall.__class__ == faiss.IndexIVFPQ:
+ indexall.add_core_o(i1 - i0, faiss.swig_ptr(xs),
+ None, None, faiss.swig_ptr(assign))
+ elif indexall.__class__ == faiss.IndexIVFFlat:
+ indexall.add_core(i1 - i0, faiss.swig_ptr(xs), None,
+ faiss.swig_ptr(assign))
+ else:
+ assert False
+
+ print('\r%d/%d (%.3f s) ' % (
+ i0, nb, time.time() - t0), end=' ')
+ sys.stdout.flush()
+ print("Add time: %.3f s" % (time.time() - t0))
+
+ return None, indexall
+
+
+
+def get_populated_index(preproc):
+
+ if not index_cachefile or not os.path.exists(index_cachefile):
+ if not altadd:
+ gpu_index, indexall = compute_populated_index(preproc)
+ else:
+ gpu_index, indexall = compute_populated_index_2(preproc)
+ if index_cachefile:
+ print("store", index_cachefile)
+ faiss.write_index(indexall, index_cachefile)
+ else:
+ print("load", index_cachefile)
+ indexall = faiss.read_index(index_cachefile)
+ gpu_index = None
+
+ co = faiss.GpuMultipleClonerOptions()
+ co.useFloat16 = use_float16
+ co.useFloat16CoarseQuantizer = False
+ co.usePrecomputed = use_precomputed_tables
+ co.indicesOptions = 0
+ co.verbose = True
+ co.shard = True # the replicas will be made "manually"
+ t0 = time.time()
+ print("CPU index contains %d vectors, move to GPU" % indexall.ntotal)
+ if replicas == 1:
+
+ if not gpu_index:
+ print("copying loaded index to GPUs")
+ vres, vdev = make_vres_vdev()
+ index = faiss.index_cpu_to_gpu_multiple(
+ vres, vdev, indexall, co)
+ else:
+ index = gpu_index
+
+ else:
+ del gpu_index # We override the GPU index
+
+ print("Copy CPU index to %d sharded GPU indexes" % replicas)
+
+ index = faiss.IndexReplicas()
+
+ for i in range(replicas):
+ gpu0 = ngpu * i / replicas
+ gpu1 = ngpu * (i + 1) / replicas
+ vres, vdev = make_vres_vdev(gpu0, gpu1)
+
+ print(" dispatch to GPUs %d:%d" % (gpu0, gpu1))
+
+ index1 = faiss.index_cpu_to_gpu_multiple(
+ vres, vdev, indexall, co)
+ index1.this.disown()
+ index.addIndex(index1)
+ index.own_fields = True
+ del indexall
+ print("move to GPU done in %.3f s" % (time.time() - t0))
+ return index
+
+
+
+#################################################################
+# Perform search
+#################################################################
+
+
+def eval_dataset(index, preproc):
+
+ ps = faiss.GpuParameterSpace()
+ ps.initialize(index)
+
+ nq_gt = gt_I.shape[0]
+ print("search...")
+ sl = query_batch_size
+ nq = xq.shape[0]
+ for nprobe in nprobes:
+ ps.set_index_parameter(index, 'nprobe', nprobe)
+ t0 = time.time()
+
+ if sl == 0:
+ D, I = index.search(preproc.apply_py(sanitize(xq)), nnn)
+ else:
+ I = np.empty((nq, nnn), dtype='int32')
+ D = np.empty((nq, nnn), dtype='float32')
+
+ inter_res = ''
+
+ for i0, xs in dataset_iterator(xq, preproc, sl):
+ print('\r%d/%d (%.3f s%s) ' % (
+ i0, nq, time.time() - t0, inter_res), end=' ')
+ sys.stdout.flush()
+
+ i1 = i0 + xs.shape[0]
+ Di, Ii = index.search(xs, nnn)
+
+ I[i0:i1] = Ii
+ D[i0:i1] = Di
+
+ if knngraph and not inter_res and i1 >= nq_gt:
+ ires = eval_intersection_measure(
+ gt_I[:, :nnn], I[:nq_gt])
+ inter_res = ', %.4f' % ires
+
+ t1 = time.time()
+ if knngraph:
+ ires = eval_intersection_measure(gt_I[:, :nnn], I[:nq_gt])
+ print(" probe=%-3d: %.3f s rank-%d intersection results: %.4f" % (
+ nprobe, t1 - t0, nnn, ires))
+ else:
+ print(" probe=%-3d: %.3f s" % (nprobe, t1 - t0), end=' ')
+ gtc = gt_I[:, :1]
+ nq = xq.shape[0]
+ for rank in 1, 10, 100:
+ if rank > nnn: continue
+ nok = (I[:, :rank] == gtc).sum()
+ print("1-R@%d: %.4f" % (rank, nok / float(nq)), end=' ')
+ print()
+ if I_fname:
+ I_fname_i = I_fname % I
+ print("storing", I_fname_i)
+ np.save(I, I_fname_i)
+ if D_fname:
+ D_fname_i = I_fname % I
+ print("storing", D_fname_i)
+ np.save(D, D_fname_i)
+
+
+#################################################################
+# Driver
+#################################################################
+
+
+preproc = get_preprocessor()
+
+index = get_populated_index(preproc)
+
+eval_dataset(index, preproc)
+
+# make sure index is deleted before the resources
+del index
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_gpu_sift1m.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_gpu_sift1m.py
new file mode 100644
index 0000000..736ba26
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_gpu_sift1m.py
@@ -0,0 +1,92 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import time
+import numpy as np
+import pdb
+
+import faiss
+from datasets import load_sift1M, evaluate
+
+
+print("load data")
+
+xb, xq, xt, gt = load_sift1M()
+nq, d = xq.shape
+
+# we need only a StandardGpuResources per GPU
+res = faiss.StandardGpuResources()
+
+
+#################################################################
+# Exact search experiment
+#################################################################
+
+print("============ Exact search")
+
+flat_config = faiss.GpuIndexFlatConfig()
+flat_config.device = 0
+
+index = faiss.GpuIndexFlatL2(res, d, flat_config)
+
+print("add vectors to index")
+
+index.add(xb)
+
+print("warmup")
+
+index.search(xq, 123)
+
+print("benchmark")
+
+for lk in range(11):
+ k = 1 << lk
+ t, r = evaluate(index, xq, gt, k)
+
+ # the recall should be 1 at all times
+ print("k=%d %.3f ms, R@1 %.4f" % (k, t, r[1]))
+
+
+#################################################################
+# Approximate search experiment
+#################################################################
+
+print("============ Approximate search")
+
+index = faiss.index_factory(d, "IVF4096,PQ64")
+
+# faster, uses more memory
+# index = faiss.index_factory(d, "IVF16384,Flat")
+
+co = faiss.GpuClonerOptions()
+
+# here we are using a 64-byte PQ, so we must set the lookup tables to
+# 16 bit float (this is due to the limited temporary memory).
+co.useFloat16 = True
+
+index = faiss.index_cpu_to_gpu(res, 0, index, co)
+
+print("train")
+
+index.train(xt)
+
+print("add vectors to index")
+
+index.add(xb)
+
+print("warmup")
+
+index.search(xq, 123)
+
+print("benchmark")
+
+for lnprobe in range(10):
+ nprobe = 1 << lnprobe
+ index.nprobe
+ index.nprobe = nprobe
+ t, r = evaluate(index, xq, gt, 100)
+
+ print("nprobe=%4d %.3f ms recalls= %.4f %.4f %.4f" % (nprobe, t, r[1], r[10], r[100]))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hamming_computer.cpp b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hamming_computer.cpp
new file mode 100644
index 0000000..641d5ff
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hamming_computer.cpp
@@ -0,0 +1,314 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <vector>
+
+#include <cinttypes>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+using namespace faiss;
+
+// These implementations are currently slower than HammingComputerDefault so
+// they are not in the main faiss anymore.
+struct HammingComputerM8 {
+ const uint64_t* a;
+ int n;
+
+ HammingComputerM8() = default;
+
+ HammingComputerM8(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size % 8 == 0);
+ a = (uint64_t*)a8;
+ n = code_size / 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ int accu = 0;
+ for (int i = 0; i < n; i++)
+ accu += popcount64(a[i] ^ b[i]);
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return n * 8;
+ }
+};
+
+struct HammingComputerM4 {
+ const uint32_t* a;
+ int n;
+
+ HammingComputerM4() = default;
+
+ HammingComputerM4(const uint8_t* a4, int code_size) {
+ set(a4, code_size);
+ }
+
+ void set(const uint8_t* a4, int code_size) {
+ assert(code_size % 4 == 0);
+ a = (uint32_t*)a4;
+ n = code_size / 4;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ const uint32_t* b = (uint32_t*)b8;
+ int accu = 0;
+ for (int i = 0; i < n; i++)
+ accu += popcount64(a[i] ^ b[i]);
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return n * 4;
+ }
+};
+
+template <class T>
+void hamming_cpt_test(
+ int code_size,
+ uint8_t* data1,
+ uint8_t* data2,
+ int n,
+ int* rst) {
+ T computer(data1, code_size);
+ for (int i = 0; i < n; i++) {
+ rst[i] = computer.hamming(data2);
+ data2 += code_size;
+ }
+}
+
+template <int CODE_SIZE_IN_BITS>
+void hamming_func_test(
+ const uint8_t* const x1,
+ const uint8_t* const x2,
+ const size_t n1,
+ const size_t n2,
+ uint64_t& sumv,
+ uint64_t& xorv) {
+ constexpr size_t CODE_SIZE_IN_BYTES = CODE_SIZE_IN_BITS / 8;
+
+ double t0 = faiss::getmillisecs();
+
+ uint64_t sumx = 0;
+ uint64_t xorx = 0;
+
+ const size_t nruns = 10;
+ for (size_t irun = 0; irun < 10; irun++) {
+#pragma omp parallel reduction(+ : sumx, xorx)
+ {
+#pragma omp for
+ for (size_t i = 0; i < n1; i++) {
+ uint64_t local_sum = 0;
+ uint64_t local_xor = 0;
+
+ const uint64_t* data1_ptr =
+ (const uint64_t*)(x1 + i * CODE_SIZE_IN_BYTES);
+
+ for (size_t j = 0; j < n2; j++) {
+ const uint64_t* data2_ptr =
+ (const uint64_t*)(x2 + j * CODE_SIZE_IN_BYTES);
+
+ uint64_t code = faiss::hamming<CODE_SIZE_IN_BITS>(
+ data1_ptr, data2_ptr);
+ local_sum += code;
+ local_xor ^= code;
+ }
+
+ sumx += local_sum;
+ xorx ^= local_xor;
+ }
+ }
+ }
+
+ sumv = sumx;
+ xorv = xorx;
+
+ double t1 = faiss::getmillisecs();
+ printf("hamming<%d>: %.3f msec, %" PRIX64 ", %" PRIX64 "\n",
+ CODE_SIZE_IN_BITS,
+ (t1 - t0) / nruns,
+ sumx,
+ xorx);
+}
+
+template <typename HammingComputerT, int CODE_SIZE_IN_BITS>
+void hamming_computer_test(
+ const uint8_t* const x1,
+ const uint8_t* const x2,
+ const size_t n1,
+ const size_t n2,
+ uint64_t& sumv,
+ uint64_t& xorv) {
+ constexpr size_t CODE_SIZE_IN_BYTES = CODE_SIZE_IN_BITS / 8;
+
+ double t0 = faiss::getmillisecs();
+
+ uint64_t sumx = 0;
+ uint64_t xorx = 0;
+
+ const size_t nruns = 10;
+ for (size_t irun = 0; irun < nruns; irun++) {
+ sumx = 0;
+ xorx = 0;
+
+#pragma omp parallel reduction(+ : sumx, xorx)
+ {
+#pragma omp for
+ for (size_t i = 0; i < n1; i++) {
+ uint64_t local_sum = 0;
+ uint64_t local_xor = 0;
+
+ const uint8_t* data1_ptr = x1 + i * CODE_SIZE_IN_BYTES;
+ HammingComputerT hc(data1_ptr, CODE_SIZE_IN_BYTES);
+
+ for (size_t j = 0; j < n2; j++) {
+ const uint8_t* data2_ptr = x2 + j * CODE_SIZE_IN_BYTES;
+ uint64_t code = hc.hamming(data2_ptr);
+ local_sum += code;
+ local_xor ^= code;
+ }
+
+ sumx += local_sum;
+ xorx ^= local_xor;
+ }
+ }
+ }
+
+ sumv = sumx;
+ xorv = xorx;
+
+ double t1 = faiss::getmillisecs();
+ printf("HammingComputer<%zd>: %.3f msec, %" PRIX64 ", %" PRIX64 "\n",
+ CODE_SIZE_IN_BYTES,
+ (t1 - t0) / nruns,
+ sumx,
+ xorx);
+}
+
+int main() {
+ size_t n = 4 * 1000 * 1000;
+
+ std::vector<size_t> code_size = {128, 256, 512, 1000};
+
+ std::vector<uint8_t> x(n * code_size.back());
+ byte_rand(x.data(), n, 12345);
+
+ int nrun = 100;
+ for (size_t cs : code_size) {
+ printf("benchmark with code_size=%zd n=%zd nrun=%d\n", cs, n, nrun);
+
+ double tot_t1 = 0, tot_t2 = 0, tot_t3 = 0;
+#pragma omp parallel reduction(+ : tot_t1, tot_t2, tot_t3)
+ {
+ std::vector<int> rst_m4(n);
+ std::vector<int> rst_m8(n);
+ std::vector<int> rst_default(n);
+
+#pragma omp for
+ for (int run = 0; run < nrun; run++) {
+ double t0, t1, t2, t3;
+ t0 = getmillisecs();
+
+ // new implem from Zilliz
+ hamming_cpt_test<HammingComputerDefault>(
+ cs, x.data(), x.data(), n, rst_default.data());
+ t1 = getmillisecs();
+
+ // M8
+ hamming_cpt_test<HammingComputerM8>(
+ cs, x.data(), x.data(), n, rst_m8.data());
+ t2 = getmillisecs();
+
+ // M4
+ hamming_cpt_test<HammingComputerM4>(
+ cs, x.data(), x.data(), n, rst_m4.data());
+ t3 = getmillisecs();
+
+ tot_t1 += t1 - t0;
+ tot_t2 += t2 - t1;
+ tot_t3 += t3 - t2;
+ }
+
+ for (int i = 0; i < n; i++) {
+ FAISS_THROW_IF_NOT_FMT(
+ (rst_m4[i] == rst_m8[i] && rst_m4[i] == rst_default[i]),
+ "wrong result i=%d, m4 %d m8 %d default %d",
+ i,
+ rst_m4[i],
+ rst_m8[i],
+ rst_default[i]);
+ }
+ }
+
+ printf("Hamming_Dft implem: %.3f ms\n", tot_t1 / nrun);
+ printf("Hamming_M8 implem: %.3f ms\n", tot_t2 / nrun);
+ printf("Hamming_M4 implem: %.3f ms\n", tot_t3 / nrun);
+ }
+
+ // evaluate various hamming<>() function calls
+ const size_t MAX_HAMMING_FUNC_CODE_SIZE = 512;
+
+ const size_t n1 = 65536;
+ const size_t n2 = 16384;
+
+ std::vector<uint8_t> x1(n1 * MAX_HAMMING_FUNC_CODE_SIZE / 8);
+ std::vector<uint8_t> x2(n2 * MAX_HAMMING_FUNC_CODE_SIZE / 8);
+ byte_rand(x1.data(), x1.size(), 12345);
+ byte_rand(x2.data(), x2.size(), 23456);
+
+ // These two values serve as a kind of CRC.
+ uint64_t sumx = 0;
+ uint64_t xorx = 0;
+ hamming_func_test<64>(x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_func_test<128>(x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_func_test<256>(x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_func_test<384>(x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_func_test<512>(x1.data(), x2.data(), n1, n2, sumx, xorx);
+
+ // evaluate various HammingComputerXX
+ hamming_computer_test<faiss::HammingComputer4, 32>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::HammingComputer8, 64>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::HammingComputer16, 128>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::HammingComputer20, 160>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::HammingComputer32, 256>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::HammingComputer64, 512>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+
+ // evaluate various GenHammingDistanceComputerXX
+ hamming_computer_test<faiss::GenHammingComputer8, 64>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::GenHammingComputer16, 128>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::GenHammingComputer32, 256>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+
+ hamming_computer_test<faiss::GenHammingComputerM8, 64>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::GenHammingComputerM8, 128>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::GenHammingComputerM8, 256>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+ hamming_computer_test<faiss::GenHammingComputerM8, 512>(
+ x1.data(), x2.data(), n1, n2, sumx, xorx);
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hamming_knn.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hamming_knn.py
new file mode 100644
index 0000000..c20d125
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hamming_knn.py
@@ -0,0 +1,29 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import numpy as np
+import faiss
+
+if __name__ == "__main__":
+ faiss.omp_set_num_threads(1)
+
+ for d in 4, 8, 16, 13:
+ nq = 10000
+ nb = 30000
+ print('Bits per vector = 8 *', d)
+ xq = faiss.randint((nq, d // 4), seed=1234, vmax=256**4).view('uint8')
+ xb = faiss.randint((nb, d // 4), seed=1234, vmax=256**4).view('uint8')
+ for variant in "hc", "mc":
+ print(f"{variant=:}", end="\t")
+ for k in 1, 4, 16, 64, 256:
+ times = []
+ for _run in range(5):
+ t0 = time.time()
+ D, I = faiss.knn_hamming(xq, xb, k, variant=variant)
+ t1 = time.time()
+ times.append(t1 - t0)
+ print(f'| {k=:} t={np.mean(times):.3f} s ± {np.std(times):.3f} ', flush=True, end="")
+ print()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_heap_replace.cpp b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_heap_replace.cpp
new file mode 100644
index 0000000..1b3700f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_heap_replace.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+using namespace faiss;
+
+void addn_default(
+ size_t n,
+ size_t k,
+ const float* x,
+ int64_t* heap_ids,
+ float* heap_val) {
+ for (size_t i = 0; i < k; i++) {
+ minheap_push(i + 1, heap_val, heap_ids, x[i], i);
+ }
+
+ for (size_t i = k; i < n; i++) {
+ if (x[i] > heap_val[0]) {
+ minheap_pop(k, heap_val, heap_ids);
+ minheap_push(k, heap_val, heap_ids, x[i], i);
+ }
+ }
+
+ minheap_reorder(k, heap_val, heap_ids);
+}
+
+void addn_replace(
+ size_t n,
+ size_t k,
+ const float* x,
+ int64_t* heap_ids,
+ float* heap_val) {
+ for (size_t i = 0; i < k; i++) {
+ minheap_push(i + 1, heap_val, heap_ids, x[i], i);
+ }
+
+ for (size_t i = k; i < n; i++) {
+ if (x[i] > heap_val[0]) {
+ minheap_replace_top(k, heap_val, heap_ids, x[i], i);
+ }
+ }
+
+ minheap_reorder(k, heap_val, heap_ids);
+}
+
+void addn_func(
+ size_t n,
+ size_t k,
+ const float* x,
+ int64_t* heap_ids,
+ float* heap_val) {
+ minheap_heapify(k, heap_val, heap_ids);
+
+ minheap_addn(k, heap_val, heap_ids, x, nullptr, n);
+
+ minheap_reorder(k, heap_val, heap_ids);
+}
+
+int main() {
+ size_t n = 10 * 1000 * 1000;
+
+ std::vector<size_t> ks({20, 50, 100, 200, 500, 1000, 2000, 5000});
+
+ std::vector<float> x(n);
+ float_randn(x.data(), n, 12345);
+
+ int nrun = 100;
+ for (size_t k : ks) {
+ printf("benchmark with k=%zd n=%zd nrun=%d\n", k, n, nrun);
+ FAISS_THROW_IF_NOT(k < n);
+
+ double tot_t1 = 0, tot_t2 = 0, tot_t3 = 0;
+#pragma omp parallel reduction(+ : tot_t1, tot_t2, tot_t3)
+ {
+ std::vector<float> heap_dis(k);
+ std::vector<float> heap_dis_2(k);
+ std::vector<float> heap_dis_3(k);
+
+ std::vector<int64_t> heap_ids(k);
+ std::vector<int64_t> heap_ids_2(k);
+ std::vector<int64_t> heap_ids_3(k);
+
+#pragma omp for
+ for (int run = 0; run < nrun; run++) {
+ double t0, t1, t2, t3;
+
+ t0 = getmillisecs();
+
+ // default implem
+ addn_default(n, k, x.data(), heap_ids.data(), heap_dis.data());
+ t1 = getmillisecs();
+
+ // new implem from Zilliz
+ addn_replace(
+ n, k, x.data(), heap_ids_2.data(), heap_dis_2.data());
+ t2 = getmillisecs();
+
+ // with addn
+ addn_func(n, k, x.data(), heap_ids_3.data(), heap_dis_3.data());
+ t3 = getmillisecs();
+
+ tot_t1 += t1 - t0;
+ tot_t2 += t2 - t1;
+ tot_t3 += t3 - t2;
+ }
+
+ for (size_t i = 0; i < k; i++) {
+ FAISS_THROW_IF_NOT_FMT(
+ heap_ids[i] == heap_ids_2[i],
+ "i=%ld (%ld, %g) != (%ld, %g)",
+ i,
+ size_t(heap_ids[i]),
+ heap_dis[i],
+ size_t(heap_ids_2[i]),
+ heap_dis_2[i]);
+ FAISS_THROW_IF_NOT(heap_dis[i] == heap_dis_2[i]);
+ }
+
+ for (size_t i = 0; i < k; i++) {
+ FAISS_THROW_IF_NOT(heap_ids[i] == heap_ids_3[i]);
+ FAISS_THROW_IF_NOT(heap_dis[i] == heap_dis_3[i]);
+ }
+ }
+ printf("default implem: %.3f ms\n", tot_t1 / nrun);
+ printf("replace implem: %.3f ms\n", tot_t2 / nrun);
+ printf("addn implem: %.3f ms\n", tot_t3 / nrun);
+ }
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hnsw.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hnsw.py
new file mode 100644
index 0000000..f62c21c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hnsw.py
@@ -0,0 +1,192 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import sys
+import numpy as np
+import faiss
+
+try:
+ from faiss.contrib.datasets_fb import DatasetSIFT1M
+except ImportError:
+ from faiss.contrib.datasets import DatasetSIFT1M
+
+# from datasets import load_sift1M
+
+
+k = int(sys.argv[1])
+todo = sys.argv[2:]
+
+print("load data")
+
+# xb, xq, xt, gt = load_sift1M()
+
+ds = DatasetSIFT1M()
+
+xq = ds.get_queries()
+xb = ds.get_database()
+gt = ds.get_groundtruth()
+xt = ds.get_train()
+
+nq, d = xq.shape
+
+if todo == []:
+ todo = 'hnsw hnsw_sq ivf ivf_hnsw_quantizer kmeans kmeans_hnsw nsg'.split()
+
+
+def evaluate(index):
+ # for timing with a single core
+ # faiss.omp_set_num_threads(1)
+
+ t0 = time.time()
+ D, I = index.search(xq, k)
+ t1 = time.time()
+
+ missing_rate = (I == -1).sum() / float(k * nq)
+ recall_at_1 = (I == gt[:, :1]).sum() / float(nq)
+ print("\t %7.3f ms per query, R@1 %.4f, missing rate %.4f" % (
+ (t1 - t0) * 1000.0 / nq, recall_at_1, missing_rate))
+
+
+if 'hnsw' in todo:
+
+ print("Testing HNSW Flat")
+
+ index = faiss.IndexHNSWFlat(d, 32)
+
+ # training is not needed
+
+ # this is the default, higher is more accurate and slower to
+ # construct
+ index.hnsw.efConstruction = 40
+
+ print("add")
+ # to see progress
+ index.verbose = True
+ index.add(xb)
+
+ print("search")
+ for efSearch in 16, 32, 64, 128, 256:
+ for bounded_queue in [True, False]:
+ print("efSearch", efSearch, "bounded queue", bounded_queue, end=' ')
+ index.hnsw.search_bounded_queue = bounded_queue
+ index.hnsw.efSearch = efSearch
+ evaluate(index)
+
+if 'hnsw_sq' in todo:
+
+ print("Testing HNSW with a scalar quantizer")
+ # also set M so that the vectors and links both use 128 bytes per
+ # entry (total 256 bytes)
+ index = faiss.IndexHNSWSQ(d, faiss.ScalarQuantizer.QT_8bit, 16)
+
+ print("training")
+ # training for the scalar quantizer
+ index.train(xt)
+
+ # this is the default, higher is more accurate and slower to
+ # construct
+ index.hnsw.efConstruction = 40
+
+ print("add")
+ # to see progress
+ index.verbose = True
+ index.add(xb)
+
+ print("search")
+ for efSearch in 16, 32, 64, 128, 256:
+ print("efSearch", efSearch, end=' ')
+ index.hnsw.efSearch = efSearch
+ evaluate(index)
+
+if 'ivf' in todo:
+
+ print("Testing IVF Flat (baseline)")
+ quantizer = faiss.IndexFlatL2(d)
+ index = faiss.IndexIVFFlat(quantizer, d, 16384)
+ index.cp.min_points_per_centroid = 5 # quiet warning
+
+ # to see progress
+ index.verbose = True
+
+ print("training")
+ index.train(xt)
+
+ print("add")
+ index.add(xb)
+
+ print("search")
+ for nprobe in 1, 4, 16, 64, 256:
+ print("nprobe", nprobe, end=' ')
+ index.nprobe = nprobe
+ evaluate(index)
+
+if 'ivf_hnsw_quantizer' in todo:
+
+ print("Testing IVF Flat with HNSW quantizer")
+ quantizer = faiss.IndexHNSWFlat(d, 32)
+ index = faiss.IndexIVFFlat(quantizer, d, 16384)
+ index.cp.min_points_per_centroid = 5 # quiet warning
+ index.quantizer_trains_alone = 2
+
+ # to see progress
+ index.verbose = True
+
+ print("training")
+ index.train(xt)
+
+ print("add")
+ index.add(xb)
+
+ print("search")
+ quantizer.hnsw.efSearch = 64
+ for nprobe in 1, 4, 16, 64, 256:
+ print("nprobe", nprobe, end=' ')
+ index.nprobe = nprobe
+ evaluate(index)
+
+# Bonus: 2 kmeans tests
+
+if 'kmeans' in todo:
+ print("Performing kmeans on sift1M database vectors (baseline)")
+ clus = faiss.Clustering(d, 16384)
+ clus.verbose = True
+ clus.niter = 10
+ index = faiss.IndexFlatL2(d)
+ clus.train(xb, index)
+
+
+if 'kmeans_hnsw' in todo:
+ print("Performing kmeans on sift1M using HNSW assignment")
+ clus = faiss.Clustering(d, 16384)
+ clus.verbose = True
+ clus.niter = 10
+ index = faiss.IndexHNSWFlat(d, 32)
+ # increase the default efSearch, otherwise the number of empty
+ # clusters is too high.
+ index.hnsw.efSearch = 128
+ clus.train(xb, index)
+
+if 'nsg' in todo:
+
+ print("Testing NSG Flat")
+
+ index = faiss.IndexNSGFlat(d, 32)
+ index.build_type = 1
+ # training is not needed
+
+ # this is the default, higher is more accurate and slower to
+ # construct
+
+ print("add")
+ # to see progress
+ index.verbose = True
+ index.add(xb)
+
+ print("search")
+ for search_L in -1, 16, 32, 64, 128, 256:
+ print("search_L", search_L, end=' ')
+ index.nsg.search_L = search_L
+ evaluate(index)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hybrid_cpu_gpu.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hybrid_cpu_gpu.py
new file mode 100644
index 0000000..7fe3e25
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_hybrid_cpu_gpu.py
@@ -0,0 +1,599 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import os
+import pickle
+import time
+from multiprocessing.pool import ThreadPool
+
+import faiss
+import numpy as np
+
+try:
+ from faiss.contrib.datasets_fb import dataset_from_name
+except ImportError:
+ from faiss.contrib.datasets import dataset_from_name
+
+from faiss.contrib.evaluation import OperatingPointsWithRanges
+from faiss.contrib.ivf_tools import replace_ivf_quantizer
+
+#################################################################
+# Preassigned search functions
+#################################################################
+
+
+def search_preassigned(xq, k, index, quantizer, batch_size=0):
+ """
+ Explicitly call the coarse quantizer and the search_preassigned
+ on the index.
+ """
+ n, d = xq.shape
+ nprobe = index.nprobe
+ if batch_size == 0:
+ batch_size = n + 1
+ D = np.empty((n, k), dtype='float32')
+ I = np.empty((n, k), dtype='int64')
+ for i0 in range(0, n, batch_size):
+ Dq, Iq = quantizer.search(xq[i0:i0 + batch_size], nprobe)
+ D[i0:i0 + batch_size], I[i0:i0 + batch_size] = \
+ index.search_preassigned(xq[i0:i0 + batch_size], k, Iq, Dq)
+ return D, I
+
+
+def tiled_search_preassigned(xq, k, index, quantizer, batch_size=32768):
+ """
+ Explicitly call the coarse quantizer and the search_preassigned
+ on the index. Allow overlapping between coarse quantization and
+ scanning the inverted lists.
+ """
+ n, d = xq.shape
+
+ # prepare a thread that will run the quantizer
+ qq_pool = ThreadPool(1)
+ nprobe = index.nprobe
+
+ def coarse_quant(i0):
+ if i0 >= n:
+ return None
+ i1 = min(i0 + batch_size, n)
+ return quantizer.search(xq[i0:i1], nprobe)
+
+ D = np.empty((n, k), dtype='float32')
+ I = np.empty((n, k), dtype='int64')
+ qq = coarse_quant(0)
+
+ for i0 in range(0, n, batch_size):
+ i1 = min(i0 + batch_size, n)
+ qq_next = qq_pool.apply_async(coarse_quant, (i0 + batch_size, ))
+ Dq, Iq = qq
+ index.search_preassigned(
+ xq[i0:i1], k, Iq=Iq, Dq=Dq, I=I[i0:i1], D=D[i0:i1])
+ qq = qq_next.get()
+
+ qq_pool.close()
+ return D, I
+
+
+#################################################################
+# IVF index objects with a separate coarse quantizer
+#################################################################
+
+class SeparateCoarseQuantizationIndex:
+ """
+ Separately manage the coarse quantizer and the IVF index.
+ """
+
+ def __init__(self, quantizer, index, bs=-1, seq_tiling=False):
+ self.index = index
+ self.index_ivf = extract_index_ivf(index)
+ if isinstance(self.index_ivf, faiss.IndexIVF):
+ self.index_ivf.parallel_mode
+ self.index_ivf.parallel_mode = 3
+
+ self.quantizer = quantizer
+ assert self.quantizer.d == self.index_ivf.d
+ # populate quantizer if it was not done before
+ if quantizer.ntotal > 0:
+ assert quantizer.ntotal == self.index_ivf.nlist
+ else:
+ centroids = self.index_ivf.quantizer.reconstruct_n()
+ print(f"adding centroids size {centroids.shape} to quantizer")
+ quantizer.train(centroids)
+ quantizer.add(centroids)
+ self.bs = bs
+ self.seq_tiling = seq_tiling
+
+ def search(self, xq, k):
+ # perform coarse quantization
+ if isinstance(self.index, faiss.IndexPreTransform):
+ # print("applying pre-transform")
+ assert self.index.chain.size() == 1
+ xq = self.index.chain.at(0).apply(xq)
+ if self.bs <= 0:
+ # non batched
+ nprobe = self.index_ivf.nprobe
+ Dq, Iq = self.quantizer.search(xq, nprobe)
+
+ return self.index_ivf.search_preassigned(xq, k, Iq, Dq)
+ if self.seq_tiling:
+ return search_preassigned(
+ xq, k, self.index_ivf, self.quantizer, self.bs)
+ else:
+ return tiled_search_preassigned(
+ xq, k, self.index_ivf, self.quantizer, self.bs)
+
+
+class ShardedGPUIndex:
+ """
+ Multiple GPU indexes, each on its GPU, with a common coarse quantizer.
+ The Python version of IndexShardsIVF
+ """
+ def __init__(self, quantizer, index, bs=-1, seq_tiling=False):
+ self.quantizer = quantizer
+ self.cpu_index = index
+ if isinstance(index, faiss.IndexPreTransform):
+ index = faiss.downcast_index(index.index)
+ ngpu = index.count()
+ self.pool = ThreadPool(ngpu)
+ self.bs = bs
+ if bs > 0:
+ self.q_pool = ThreadPool(1)
+
+ def __del__(self):
+ self.pool.close()
+ if self.bs > 0:
+ self.q_pool.close()
+
+ def search(self, xq, k):
+ nq = len(xq)
+ # perform coarse quantization
+ index = self.cpu_index
+ if isinstance(self.cpu_index, faiss.IndexPreTransform):
+ assert index.chain.size() == 1
+ xq = self.cpu_index.chain.at(0).apply(xq)
+ index = faiss.downcast_index(index.index)
+ ngpu = index.count()
+ sub_index_0 = faiss.downcast_index(index.at(0))
+ nprobe = sub_index_0.nprobe
+
+ Dall = np.empty((ngpu, nq, k), dtype='float32')
+ Iall = np.empty((ngpu, nq, k), dtype='int64')
+ bs = self.bs
+ if bs <= 0:
+
+ Dq, Iq = self.quantizer.search(xq, nprobe)
+
+ def do_search(rank):
+ gpu_index = faiss.downcast_index(index.at(rank))
+ Dall[rank], Iall[rank] = gpu_index.search_preassigned(
+ xq, k, Iq, Dq)
+ list(self.pool.map(do_search, range(ngpu)))
+ else:
+ qq_pool = self.q_pool
+ bs = self.bs
+
+ def coarse_quant(i0):
+ if i0 >= nq:
+ return None
+ return self.quantizer.search(xq[i0:i0 + bs], nprobe)
+
+ def do_search(rank, i0, qq):
+ gpu_index = faiss.downcast_index(index.at(rank))
+ Dq, Iq = qq
+ Dall[rank, i0:i0 + bs], Iall[rank, i0:i0 + bs] = \
+ gpu_index.search_preassigned(xq[i0:i0 + bs], k, Iq, Dq)
+
+ qq = coarse_quant(0)
+
+ for i0 in range(0, nq, bs):
+ qq_next = qq_pool.apply_async(coarse_quant, (i0 + bs, ))
+ list(self.pool.map(
+ lambda rank: do_search(rank, i0, qq),
+ range(ngpu)
+ ))
+ qq = qq_next.get()
+
+ return faiss.merge_knn_results(Dall, Iall)
+
+
+def extract_index_ivf(index):
+ """ extract the IVF sub-index from the index, supporting GpuIndexes
+ as well """
+ try:
+ return faiss.extract_index_ivf(index)
+ except RuntimeError:
+ if index.__class__ == faiss.IndexPreTransform:
+ index = faiss.downcast_index(index.index)
+ if isinstance(index, faiss.GpuIndexIVF):
+ return index
+ raise RuntimeError(f"could not extract IVF index from {index}")
+
+
+def set_index_parameter(index, name, val):
+ """
+ Index parameter setting that works on the index lookalikes defined above
+ """
+ if index.__class__ == SeparateCoarseQuantizationIndex:
+ if name == "nprobe":
+ set_index_parameter(index.index_ivf, name, val)
+ elif name.startswith("quantizer_"):
+ set_index_parameter(
+ index.quantizer, name[name.find("_") + 1:], val)
+ else:
+ raise RuntimeError()
+ return
+
+ if index.__class__ == ShardedGPUIndex:
+ if name == "nprobe":
+ set_index_parameter(index.cpu_index, name, val)
+ elif name.startswith("quantizer_"):
+ set_index_parameter(
+ index.quantizer, name[name.find("_") + 1:], val)
+ else:
+ raise RuntimeError()
+ return
+
+ # then it's a Faiss index
+ index = faiss.downcast_index(index)
+
+ if isinstance(index, faiss.IndexPreTransform):
+ set_index_parameter(index.index, name, val)
+ elif isinstance(index, faiss.IndexShardsIVF):
+ if name != "nprobe" and name.startswith("quantizer_"):
+ set_index_parameter(
+ index.quantizer, name[name.find("_") + 1:], val)
+ else:
+ for i in range(index.count()):
+ sub_index = index.at(i)
+ set_index_parameter(sub_index, name, val)
+ elif (isinstance(index, faiss.IndexShards) or
+ isinstance(index, faiss.IndexReplicas)):
+ for i in range(index.count()):
+ sub_index = index.at(i)
+ set_index_parameter(sub_index, name, val)
+ elif name.startswith("quantizer_"):
+ index_ivf = extract_index_ivf(index)
+ set_index_parameter(
+ index_ivf.quantizer, name[name.find("_") + 1:], val)
+ elif name == "efSearch":
+ index.hnsw.efSearch
+ index.hnsw.efSearch = int(val)
+ elif name == "nprobe":
+ index_ivf = extract_index_ivf(index)
+ index_ivf.nprobe
+ index_ivf.nprobe = int(val)
+ else:
+ raise RuntimeError(f"could not set param {name} on {index}")
+
+
+#####################################################################
+# Driver routine
+#####################################################################
+
+
+def main():
+ parser = argparse.ArgumentParser()
+
+ def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+ group = parser.add_argument_group('dataset options')
+ aa('--nq', type=int, default=int(10e5),
+ help="nb queries (queries will be duplicated if below that number")
+ aa('--db', default='bigann10M', help='dataset')
+
+ group = parser.add_argument_group('index options')
+ aa('--indexname', default="", help="override index name")
+ aa('--mmap', default=False, action='store_true', help='mmap index')
+ aa('--shard_type', default=1, type=int, help="set type of sharding")
+ aa('--useFloat16', default=False, action='store_true',
+ help='GPU cloner options')
+ aa('--useFloat16CoarseQuantizer', default=False, action='store_true',
+ help='GPU cloner options')
+ aa('--usePrecomputed', default=False, action='store_true',
+ help='GPU cloner options')
+ group = parser.add_argument_group('search options')
+ aa('--k', type=int, default=100)
+ aa('--search_type', default="cpu",
+ choices=[
+ "cpu", "gpu", "gpu_flat_quantizer",
+ "cpu_flat_gpu_quantizer", "gpu_tiled", "gpu_ivf_quantizer",
+ "multi_gpu", "multi_gpu_flat_quantizer",
+ "multi_gpu_sharded", "multi_gpu_flat_quantizer_sharded",
+ "multi_gpu_sharded1", "multi_gpu_sharded1_flat",
+ "multi_gpu_sharded1_ivf",
+ "multi_gpu_Csharded1", "multi_gpu_Csharded1_flat",
+ "multi_gpu_Csharded1_ivf",
+ ],
+ help="how to search"
+ )
+ aa('--ivf_quant_nlist', type=int, default=1024,
+ help="nb of invlists for IVF quantizer")
+ aa('--batch_size', type=int, default=-1,
+ help="batch size for tiled CPU / GPU computation (-1= no tiling)")
+ aa('--n_autotune', type=int, default=300,
+ help="max nb of auto-tuning steps")
+ aa('--nt', type=int, default=-1, help="force number of CPU threads to this")
+
+ group = parser.add_argument_group('output options')
+ aa('--quiet', default=False, action="store_true")
+ aa('--stats', default="", help="pickle to store output stats")
+
+ args = parser.parse_args()
+ print("args:", args)
+
+ if not args.quiet:
+ # log some stats about the machine
+ os.system("grep -m1 'model name' < /proc/cpuinfo")
+ os.system("grep -E 'MemTotal|MemFree' /proc/meminfo")
+ os.system("nvidia-smi")
+
+ print("prepare dataset", args.db)
+ ds = dataset_from_name(args.db)
+ print(ds)
+
+ print("Faiss nb GPUs:", faiss.get_num_gpus())
+
+ xq = ds.get_queries()
+ if args.nq > len(xq):
+ xqx = []
+ n = 0
+ while n < args.nq:
+ xqx.append(xq[:args.nq - n])
+ n += len(xqx[-1])
+ print(f"increased nb queries from {len(xq)} to {n}")
+ xq = np.vstack(xqx)
+
+ if args.nt != -1:
+ print("setting nb openmp threads to", args.nt)
+ faiss.omp_set_num_threads(args.nt)
+
+ print("loading index")
+
+ if args.mmap:
+ io_flag = faiss.IO_FLAG_READ_ONLY | faiss.IO_FLAG_MMAP
+ else:
+ io_flag = 0
+
+ print(f"load index {args.indexname} {io_flag=:x}")
+ index = faiss.read_index(args.indexname, io_flag)
+ index_ivf = faiss.extract_index_ivf(index)
+
+ print("prepare index")
+ op = OperatingPointsWithRanges()
+ op.add_range(
+ "nprobe", [
+ 2 ** i for i in range(20)
+ if 2 ** i < index_ivf.nlist * 0.1 and 2 ** i <= 4096
+ ]
+ )
+
+ # prepare options for GPU clone
+
+ co = faiss.GpuMultipleClonerOptions()
+ co.useFloat16 = args.useFloat16
+ co.useFloat16CoarseQuantizer = args.useFloat16CoarseQuantizer
+ co.usePrecomputed = args.usePrecomputed
+ co.shard_type = args.shard_type
+
+ if args.search_type == "cpu":
+ op.add_range(
+ "quantizer_efSearch",
+ [2 ** i for i in range(10)]
+ )
+ elif args.search_type == "gpu":
+ print("move index to 1 GPU")
+ res = faiss.StandardGpuResources()
+ index = faiss.index_cpu_to_gpu(res, 0, index, co)
+ op.add_range(
+ "quantizer_efSearch",
+ [2 ** i for i in range(10)]
+ )
+ op.restrict_range("nprobe", 2049)
+ elif args.search_type == "gpu_tiled":
+ print("move index to 1 GPU")
+ new_quantizer = faiss.IndexFlatL2(index_ivf.d)
+ quantizer_hnsw = replace_ivf_quantizer(index_ivf, new_quantizer)
+ res = faiss.StandardGpuResources()
+ index = faiss.index_cpu_to_gpu(res, 0, index, co)
+ op.add_range(
+ "quantizer_efSearch",
+ [2 ** i for i in range(10)]
+ )
+ op.restrict_range("nprobe", 2049)
+ index = SeparateCoarseQuantizationIndex(
+ quantizer_hnsw, index, bs=args.batch_size)
+ elif args.search_type == "gpu_ivf_quantizer":
+ index_ivf = faiss.extract_index_ivf(index)
+ centroids = index_ivf.quantizer.reconstruct_n()
+ replace_ivf_quantizer(index_ivf, faiss.IndexFlatL2(index_ivf.d))
+ res = faiss.StandardGpuResources()
+ new_quantizer = faiss.index_factory(
+ index_ivf.d, f"IVF{args.ivf_quant_nlist},Flat")
+ new_quantizer.train(centroids)
+ new_quantizer.add(centroids)
+ index = SeparateCoarseQuantizationIndex(
+ faiss.index_cpu_to_gpu(res, 0, new_quantizer, co),
+ faiss.index_cpu_to_gpu(res, 0, index, co),
+ bs=args.batch_size, seq_tiling=True
+ )
+ op.add_range(
+ "quantizer_nprobe",
+ [2 ** i for i in range(9)]
+ )
+ op.restrict_range("nprobe", 1025)
+ elif args.search_type == "gpu_flat_quantizer":
+ index_ivf = faiss.extract_index_ivf(index)
+ new_quantizer = faiss.IndexFlatL2(index_ivf.d)
+ replace_ivf_quantizer(index_ivf, new_quantizer)
+ res = faiss.StandardGpuResources()
+ index = faiss.index_cpu_to_gpu(res, 0, index, co)
+ op.restrict_range("nprobe", 2049)
+ elif args.search_type == "cpu_flat_gpu_quantizer":
+ index_ivf = faiss.extract_index_ivf(index)
+ quantizer = faiss.IndexFlatL2(index_ivf.d)
+ res = faiss.StandardGpuResources()
+ quantizer = faiss.index_cpu_to_gpu(res, 0, quantizer, co)
+ index = SeparateCoarseQuantizationIndex(
+ quantizer, index, bs=args.batch_size)
+ op.restrict_range("nprobe", 2049)
+ elif args.search_type in ("multi_gpu", "multi_gpu_sharded"):
+ print(f"move index to {faiss.get_num_gpus()} GPU")
+ co.shard = "sharded" in args.search_type
+ index = faiss.index_cpu_to_all_gpus(index, co=co)
+ op.add_range(
+ "quantizer_efSearch",
+ [2 ** i for i in range(10)]
+ )
+ op.restrict_range("nprobe", 2049)
+ elif args.search_type in (
+ "multi_gpu_flat_quantizer", "multi_gpu_flat_quantizer_sharded"):
+ index_ivf = faiss.extract_index_ivf(index)
+ new_quantizer = faiss.IndexFlatL2(ds.d)
+ replace_ivf_quantizer(index_ivf, new_quantizer)
+ index = faiss.index_cpu_to_all_gpus(index, co=co)
+ op.restrict_range("nprobe", 2049)
+ elif args.search_type in (
+ "multi_gpu_sharded1", "multi_gpu_sharded1_flat",
+ "multi_gpu_sharded1_ivf"):
+ print(f"move index to {faiss.get_num_gpus()} GPU")
+ new_quantizer = faiss.IndexFlatL2(index_ivf.d)
+ hnsw_quantizer = replace_ivf_quantizer(index_ivf, new_quantizer)
+ co.shard
+ co.shard = True
+ gpus = list(range(faiss.get_num_gpus()))
+ res = [faiss.StandardGpuResources() for _ in gpus]
+ index = faiss.index_cpu_to_gpu_multiple_py(res, index, co, gpus)
+ op.restrict_range("nprobe", 2049)
+ if args.search_type == "multi_gpu_sharded1":
+ op.add_range(
+ "quantizer_efSearch",
+ [2 ** i for i in range(10)]
+ )
+ index = ShardedGPUIndex(hnsw_quantizer, index, bs=args.batch_size)
+ elif args.search_type == "multi_gpu_sharded1_ivf":
+ centroids = hnsw_quantizer.storage.reconstruct_n()
+ quantizer = faiss.index_factory(
+ centroids.shape[1], f"IVF{args.ivf_quant_nlist},Flat")
+ quantizer.train(centroids)
+ quantizer.add(centroids)
+ co.shard = False
+ quantizer = faiss.index_cpu_to_gpu_multiple_py(
+ res, quantizer, co, gpus)
+ index = ShardedGPUIndex(quantizer, index, bs=args.batch_size)
+
+ op.add_range(
+ "quantizer_nprobe",
+ [2 ** i for i in range(9)]
+ )
+ op.restrict_range("nprobe", 1025)
+ elif args.search_type == "multi_gpu_sharded1_flat":
+ quantizer = hnsw_quantizer.storage
+ quantizer = faiss.index_cpu_to_gpu_multiple_py(
+ res, quantizer, co, gpus)
+ index = ShardedGPUIndex(quantizer, index, bs=args.batch_size)
+ else:
+ raise RuntimeError()
+ elif args.search_type in (
+ "multi_gpu_Csharded1", "multi_gpu_Csharded1_flat",
+ "multi_gpu_Csharded1_ivf"):
+ print(f"move index to {faiss.get_num_gpus()} GPU")
+ co.shard = True
+ co.common_ivf_quantizer
+ co.common_ivf_quantizer = True
+ op.restrict_range("nprobe", 2049)
+ if args.search_type == "multi_gpu_Csharded1":
+ op.add_range(
+ "quantizer_efSearch",
+ [2 ** i for i in range(10)]
+ )
+ index = faiss.index_cpu_to_all_gpus(index, co)
+ elif args.search_type == "multi_gpu_Csharded1_flat":
+ new_quantizer = faiss.IndexFlatL2(index_ivf.d)
+ quantizer_hnsw = replace_ivf_quantizer(index_ivf, new_quantizer)
+ index = faiss.index_cpu_to_all_gpus(index, co)
+ elif args.search_type == "multi_gpu_Csharded1_ivf":
+ quantizer = faiss.index_factory(
+ index_ivf.d, f"IVF{args.ivf_quant_nlist},Flat")
+ quantizer_hnsw = replace_ivf_quantizer(index_ivf, quantizer)
+ op.add_range(
+ "quantizer_nprobe",
+ [2 ** i for i in range(9)]
+ )
+ index = faiss.index_cpu_to_all_gpus(index, co)
+ else:
+ raise RuntimeError()
+ else:
+ raise RuntimeError()
+
+ totex = op.num_experiments()
+ experiments = op.sample_experiments()
+ print(f"total nb experiments {totex}, running {len(experiments)}")
+
+ print("perform search")
+ gt = ds.get_groundtruth(100)
+
+ # piggyback on operating points so that this gets stored in the stats file
+ op.all_experiments = []
+ op.platform = {
+ "loadavg": open("/proc/loadavg", "r").readlines(),
+ "procesor": [l for l in open("/proc/cpuinfo") if "model name" in l][0],
+ "GPU": list(os.popen("nvidia-smi", "r")),
+ "mem": open("/proc/meminfo", "r").readlines(),
+ "pid": os.getpid()
+ }
+ op.args = args
+ if args.stats:
+ print(f"storing stats in {args.stats} after each experiment")
+
+ for cno in experiments:
+ key = op.cno_to_key(cno)
+ parameters = op.get_parameters(key)
+ print(f"{cno=:4d} {str(parameters):50}", end=": ", flush=True)
+
+ (max_perf, min_time) = op.predict_bounds(key)
+ if not op.is_pareto_optimal(max_perf, min_time):
+ print(f"SKIP, {max_perf=:.3f} {min_time=:.3f}", )
+ continue
+
+ for name, val in parameters.items():
+ set_index_parameter(index, name, val)
+
+ if cno == 0:
+ # warmup
+ for _ in range(5):
+ D, I = index.search(xq, 100)
+
+ t0 = time.time()
+ try:
+ D, I = index.search(xq, 100)
+ except RuntimeError as e:
+ print(f"ERROR {e}")
+ continue
+ t1 = time.time()
+
+ recalls = {}
+ for rank in 1, 10, 100:
+ recall = (gt[:, :1] == I[:ds.nq, :rank]).sum() / ds.nq
+ recalls[rank] = recall
+
+ print(f"time={t1 - t0:.3f} s recalls={recalls}")
+ perf = recalls[1]
+ op.add_operating_point(key, perf, t1 - t0)
+ op.all_experiments.append({
+ "cno": cno,
+ "key": key,
+ "parameters": parameters,
+ "time": t1 - t0,
+ "recalls": recalls
+ })
+
+ if args.stats:
+ pickle.dump(op, open(args.stats, "wb"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_index_flat.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_index_flat.py
new file mode 100644
index 0000000..a87388f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_index_flat.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import os
+import numpy as np
+import faiss
+
+from faiss.contrib.datasets import SyntheticDataset
+
+
+os.system("grep -m1 'model name' < /proc/cpuinfo")
+
+
+def format_tab(x):
+ return "\n".join("\t".join("%g" % xi for xi in row) for row in x)
+
+
+faiss.cvar.distance_compute_min_k_reservoir = 5
+
+# for have_threads in True, False:
+for have_threads in False, :
+
+ if have_threads:
+ # good config for Intel(R) Xeon(R) CPU E5-2698 v4 @ 2.20GHz
+ nthread = 32
+ else:
+ nthread = 1
+
+ faiss.omp_set_num_threads(nthread)
+ print("************ nthread=", nthread)
+
+ for nq in 100, 10000:
+
+ print("*********** nq=", nq)
+
+ if nq == 100:
+ nrun = 500
+ unit = "ms"
+ else:
+ nrun = 20
+ unit = "s"
+
+ restab = []
+ for d in 16, 32, 64, 128:
+
+ print("========== d=", d)
+
+ nb = 10000
+
+ # d = 32
+
+ ds = SyntheticDataset(d, 0, nb, nq)
+
+ print(ds)
+
+ index = faiss.IndexFlatL2(d)
+
+ index.add(ds.get_database())
+
+ nrun = 10
+ restab1 = []
+ restab.append(restab1)
+ for k in 1, 10, 100:
+ times = []
+ for run in range(nrun):
+ t0 = time.time()
+ index.search(ds.get_queries(), k)
+ t1 = time.time()
+ if run >= nrun // 5: # the rest is considered warmup
+ times.append((t1 - t0))
+ times = np.array(times)
+
+ if unit == "ms":
+ times *= 1000
+ print("search k=%3d t=%.3f ms (± %.4f)" % (
+ k, np.mean(times), np.std(times)))
+ else:
+ print("search k=%3d t=%.3f s (± %.4f)" % (
+ k, np.mean(times), np.std(times)))
+ restab1.append(np.mean(times))
+
+ print("restab=\n", format_tab(restab))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_index_pq.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_index_pq.py
new file mode 100644
index 0000000..a6bfaac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_index_pq.py
@@ -0,0 +1,22 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import faiss
+from datasets import load_sift1M, evaluate
+
+xb, xq, xt, gt = load_sift1M()
+nq, d = xq.shape
+
+k = 32
+
+for nbits in 4, 6, 8, 10, 12:
+ index = faiss.IndexPQ(d, 8, nbits)
+ index.train(xt)
+ index.add(xb)
+
+ t, r = evaluate(index, xq, gt, k)
+ print("\t %7.3f ms per query, R@1 %.4f" % (t, r[1]))
+ del index
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_fastscan.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_fastscan.py
new file mode 100644
index 0000000..038c202
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_fastscan.py
@@ -0,0 +1,112 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import time
+import os
+import multiprocessing as mp
+import numpy as np
+import matplotlib.pyplot as plt
+
+try:
+ from faiss.contrib.datasets_fb import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+except ImportError:
+ from faiss.contrib.datasets import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+
+
+# ds = DatasetDeep1B(10**6)
+# ds = DatasetBigANN(nb_M=1)
+ds = DatasetSIFT1M()
+
+xq = ds.get_queries()
+xb = ds.get_database()
+gt = ds.get_groundtruth()
+
+xt = ds.get_train()
+
+nb, d = xb.shape
+nq, d = xq.shape
+nt, d = xt.shape
+
+k = 1
+AQ = faiss.AdditiveQuantizer
+
+
+def eval_recall(index, name):
+ t0 = time.time()
+ D, I = index.search(xq, k=k)
+ t = time.time() - t0
+ speed = t * 1000 / nq
+ qps = 1000 / speed
+
+ corrects = (gt == I).sum()
+ recall = corrects / nq
+ print(
+ f'\tnprobe {index.nprobe:3d}, Recall@{k}: '
+ f'{recall:.6f}, speed: {speed:.6f} ms/query'
+ )
+
+ return recall, qps
+
+
+def eval_and_plot(name, rescale_norm=True, plot=True):
+ index = faiss.index_factory(d, name)
+ index_path = f"indices/{name}.faissindex"
+
+ if os.path.exists(index_path):
+ index = faiss.read_index(index_path)
+ else:
+ faiss.omp_set_num_threads(mp.cpu_count())
+ index.train(xt)
+ index.add(xb)
+ faiss.write_index(index, index_path)
+
+ # search params
+ if hasattr(index, 'rescale_norm'):
+ index.rescale_norm = rescale_norm
+ name += f"(rescale_norm={rescale_norm})"
+ faiss.omp_set_num_threads(1)
+
+ data = []
+ print(f"======{name}")
+ for nprobe in 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 128:
+ index.nprobe = nprobe
+ recall, qps = eval_recall(index, name)
+ data.append((recall, qps))
+
+ if plot:
+ data = np.array(data)
+ plt.plot(data[:, 0], data[:, 1], label=name) # x - recall, y - qps
+
+
+M, nlist = 32, 1024
+
+# just for warmup...
+# eval_and_plot(f"IVF{nlist},PQ{M}x4fs", plot=False)
+
+# benchmark
+plt.figure(figsize=(8, 6), dpi=80)
+
+# PQ
+eval_and_plot(f"IVF{nlist},PQ{M}x4fs")
+eval_and_plot(f"IVF{nlist},PQ{M}x4fsr")
+
+# AQ, by_residual
+eval_and_plot(f"IVF{nlist},LSQ{M-2}x4fsr_Nlsq2x4")
+eval_and_plot(f"IVF{nlist},RQ{M-2}x4fsr_Nrq2x4")
+eval_and_plot(f"IVF{nlist},LSQ{M-2}x4fsr_Nlsq2x4", rescale_norm=False)
+eval_and_plot(f"IVF{nlist},RQ{M-2}x4fsr_Nrq2x4", rescale_norm=False)
+
+# AQ, no by_residual
+eval_and_plot(f"IVF{nlist},LSQ{M-2}x4fs_Nlsq2x4")
+eval_and_plot(f"IVF{nlist},RQ{M-2}x4fs_Nrq2x4")
+
+plt.title("Indices on SIFT1M")
+plt.xlabel("Recall@1")
+plt.ylabel("QPS")
+plt.legend(bbox_to_anchor=(1.02, 0.1), loc='upper left', borderaxespad=0)
+plt.savefig("bench_ivf_fastscan.png", bbox_inches='tight')
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_fastscan_single_query.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_fastscan_single_query.py
new file mode 100644
index 0000000..b367c44
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_fastscan_single_query.py
@@ -0,0 +1,122 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import time
+import os
+import multiprocessing as mp
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+try:
+ from faiss.contrib.datasets_fb import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+except ImportError:
+ from faiss.contrib.datasets import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+
+# ds = DatasetDeep1B(10**6)
+ds = DatasetBigANN(nb_M=50)
+# ds = DatasetSIFT1M()
+
+xq = ds.get_queries()
+xb = ds.get_database()
+gt = ds.get_groundtruth()
+
+xt = ds.get_train()
+
+nb, d = xb.shape
+nq, d = xq.shape
+nt, d = xt.shape
+
+print('the dimension is {}, {}'.format(nb, d))
+
+k = 64
+
+
+def eval_recall(index, name, single_query=False):
+ t0 = time.time()
+ D, I = index.search(xq, k=k)
+
+ t = time.time() - t0
+ if single_query:
+ t0 = time.time()
+ for row in range(nq):
+ Ds, Is = index.search(xq[row:row + 1], k=k)
+ D[row, :] = Ds
+ I[row, :] = Is
+ t = time.time() - t0
+ speed = t * 1000 / nq
+ qps = 1000 / speed
+
+ corrects = (gt[:, :1] == I[:, :k]).sum()
+ recall = corrects / nq
+ print(
+ f'\tnprobe {index.nprobe:3d}, 1Recall@{k}: '
+ f'{recall:.6f}, speed: {speed:.6f} ms/query'
+ )
+
+ return recall, qps
+
+
+def eval_and_plot(
+ name, rescale_norm=True, plot=True, single_query=False,
+ implem=None, num_threads=1):
+ index = faiss.index_factory(d, name)
+ index_path = f"indices/{name}.faissindex"
+
+ if os.path.exists(index_path):
+ index = faiss.read_index(index_path)
+ else:
+ faiss.omp_set_num_threads(mp.cpu_count())
+ index.train(xt)
+ index.add(xb)
+ faiss.write_index(index, index_path)
+
+ # search params
+ if hasattr(index, 'rescale_norm'):
+ index.rescale_norm = rescale_norm
+ name += f"(rescale_norm={rescale_norm})"
+ if implem is not None and hasattr(index, 'implem'):
+ index.implem = implem
+ name += f"(implem={implem})"
+ if single_query:
+ name += f"(single_query={single_query})"
+ if num_threads > 1:
+ name += f"(num_threads={num_threads})"
+
+ faiss.omp_set_num_threads(num_threads)
+
+ data = []
+ print(f"======{name}")
+ for nprobe in 1, 4, 8, 16, 32, 64, 128, 256:
+ index.nprobe = nprobe
+ recall, qps = eval_recall(index, name, single_query=single_query)
+ data.append((recall, qps))
+
+ if plot:
+ data = np.array(data)
+ plt.plot(data[:, 0], data[:, 1], label=name) # x - recall, y - qps
+
+
+M, nlist = 64, 4096
+
+# just for warmup...
+# eval_and_plot(f"IVF{nlist},PQ{M}x4fs", plot=False)
+
+# benchmark
+plt.figure(figsize=(8, 6), dpi=80)
+
+eval_and_plot(f"IVF{nlist},PQ{M}x4fs", num_threads=8)
+eval_and_plot(f"IVF{nlist},PQ{M}x4fs", single_query=True, implem=0, num_threads=8)
+eval_and_plot(f"IVF{nlist},PQ{M}x4fs", single_query=True, implem=14, num_threads=8)
+eval_and_plot(f"IVF{nlist},PQ{M}x4fs", single_query=True, implem=15, num_threads=8)
+
+plt.title("Indices on Bigann50M")
+plt.xlabel("1Recall@{}".format(k))
+plt.ylabel("QPS")
+plt.legend(bbox_to_anchor=(1.02, 0.1), loc='upper left', borderaxespad=0)
+plt.savefig("bench_ivf_fastscan.png", bbox_inches='tight')
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_selector.cpp b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_selector.cpp
new file mode 100644
index 0000000..0bd8745
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivf_selector.cpp
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <omp.h>
+#include <unistd.h>
+#include <memory>
+
+#include <faiss/IVFlib.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/index_factory.h>
+#include <faiss/index_io.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+/************************
+ * This benchmark attempts to measure the runtime overhead to use an IDSelector
+ * over doing an unconditional sequential scan. Unfortunately the results of the
+ * benchmark also depend a lot on the parallel_mode and the way
+ * search_with_parameters works.
+ */
+
+int main() {
+ using idx_t = faiss::idx_t;
+ int d = 64;
+ size_t nb = 1024 * 1024;
+ size_t nq = 512 * 16;
+ size_t k = 10;
+ std::vector<float> data((nb + nq) * d);
+ float* xb = data.data();
+ float* xq = data.data() + nb * d;
+ faiss::rand_smooth_vectors(nb + nq, d, data.data(), 1234);
+
+ std::unique_ptr<faiss::Index> index;
+ // const char *index_key = "IVF1024,Flat";
+ const char* index_key = "IVF1024,SQ8";
+ printf("index_key=%s\n", index_key);
+ std::string stored_name =
+ std::string("/tmp/bench_ivf_selector_") + index_key + ".faissindex";
+
+ if (access(stored_name.c_str(), F_OK) != 0) {
+ printf("creating index\n");
+ index.reset(faiss::index_factory(d, index_key));
+
+ double t0 = faiss::getmillisecs();
+ index->train(nb, xb);
+ double t1 = faiss::getmillisecs();
+ index->add(nb, xb);
+ double t2 = faiss::getmillisecs();
+ printf("Write %s\n", stored_name.c_str());
+ faiss::write_index(index.get(), stored_name.c_str());
+ } else {
+ printf("Read %s\n", stored_name.c_str());
+ index.reset(faiss::read_index(stored_name.c_str()));
+ }
+ faiss::IndexIVF* index_ivf = static_cast<faiss::IndexIVF*>(index.get());
+ index->verbose = true;
+
+ for (int tt = 0; tt < 3; tt++) {
+ if (tt == 1) {
+ index_ivf->parallel_mode = 3;
+ } else {
+ index_ivf->parallel_mode = 0;
+ }
+
+ if (tt == 2) {
+ printf("set single thread\n");
+ omp_set_num_threads(1);
+ }
+ printf("parallel_mode=%d\n", index_ivf->parallel_mode);
+
+ std::vector<float> D1(nq * k);
+ std::vector<idx_t> I1(nq * k);
+ {
+ double t2 = faiss::getmillisecs();
+ index->search(nq, xq, k, D1.data(), I1.data());
+ double t3 = faiss::getmillisecs();
+
+ printf("search time, no selector: %.3f ms\n", t3 - t2);
+ }
+
+ std::vector<float> D2(nq * k);
+ std::vector<idx_t> I2(nq * k);
+ {
+ double t2 = faiss::getmillisecs();
+ faiss::IVFSearchParameters params;
+
+ faiss::ivflib::search_with_parameters(
+ index.get(), nq, xq, k, D2.data(), I2.data(), &params);
+ double t3 = faiss::getmillisecs();
+ printf("search time with nullptr selector: %.3f ms\n", t3 - t2);
+ }
+ FAISS_THROW_IF_NOT(I1 == I2);
+ FAISS_THROW_IF_NOT(D1 == D2);
+
+ {
+ double t2 = faiss::getmillisecs();
+ faiss::IVFSearchParameters params;
+ faiss::IDSelectorAll sel;
+ params.sel = &sel;
+
+ faiss::ivflib::search_with_parameters(
+ index.get(), nq, xq, k, D2.data(), I2.data(), &params);
+ double t3 = faiss::getmillisecs();
+ printf("search time with selector: %.3f ms\n", t3 - t2);
+ }
+ FAISS_THROW_IF_NOT(I1 == I2);
+ FAISS_THROW_IF_NOT(D1 == D2);
+
+ std::vector<float> D3(nq * k);
+ std::vector<idx_t> I3(nq * k);
+ {
+ int nt = omp_get_max_threads();
+ double t2 = faiss::getmillisecs();
+ faiss::IVFSearchParameters params;
+
+#pragma omp parallel for if (nt > 1)
+ for (idx_t slice = 0; slice < nt; slice++) {
+ idx_t i0 = nq * slice / nt;
+ idx_t i1 = nq * (slice + 1) / nt;
+ if (i1 > i0) {
+ faiss::ivflib::search_with_parameters(
+ index.get(),
+ i1 - i0,
+ xq + i0 * d,
+ k,
+ D3.data() + i0 * k,
+ I3.data() + i0 * k,
+ &params);
+ }
+ }
+ double t3 = faiss::getmillisecs();
+ printf("search time with null selector + manual parallel: %.3f ms\n",
+ t3 - t2);
+ }
+ FAISS_THROW_IF_NOT(I1 == I3);
+ FAISS_THROW_IF_NOT(D1 == D3);
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivfflat_cuvs.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivfflat_cuvs.py
new file mode 100644
index 0000000..0e3f742
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivfflat_cuvs.py
@@ -0,0 +1,167 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Meta Platforms, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+#
+# Copyright (c) 2024-2025, NVIDIA CORPORATION.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import numpy as np
+import faiss
+import time
+import argparse
+import rmm
+
+try:
+ from faiss.contrib.datasets_fb import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+except ImportError:
+ from faiss.contrib.datasets import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+
+
+# ds = DatasetDeep1B(10**6)
+# ds = DatasetBigANN(nb_M=1)
+ds = DatasetSIFT1M()
+
+xq = ds.get_queries()
+xb = ds.get_database()
+gt = ds.get_groundtruth()
+
+xt = ds.get_train()
+
+nb, d = xb.shape
+nq, d = xq.shape
+nt, d = xt.shape
+
+######################################################
+# Command-line parsing
+######################################################
+
+parser = argparse.ArgumentParser()
+
+
+def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+
+group = parser.add_argument_group('benchmarking options')
+
+aa('--bm_train', default=True,
+ help='whether to benchmark train operation on GPU index')
+aa('--bm_add', default=True,
+ help='whether to benchmark add operation on GPU index')
+aa('--bm_search', default=True,
+ help='whether to benchmark search operation on GPU index')
+
+
+group = parser.add_argument_group('IVF options')
+aa('--nlist', default=1024, type=int,
+ help="number of IVF centroids")
+
+
+group = parser.add_argument_group('searching')
+
+aa('--k', default=10, type=int, help='nb of nearest neighbors')
+aa('--nprobe', default=10, help='nb of IVF lists to probe')
+
+args = parser.parse_args()
+
+print("args:", args)
+
+rs = np.random.RandomState(123)
+
+res = faiss.StandardGpuResources()
+
+# Use an RMM pool memory resource for device allocations
+mr = rmm.mr.PoolMemoryResource(rmm.mr.CudaMemoryResource())
+rmm.mr.set_current_device_resource(mr)
+
+
+def bench_train_milliseconds(trainVecs, ncols, nlist, use_cuvs):
+ config = faiss.GpuIndexIVFFlatConfig()
+ config.use_cuvs = use_cuvs
+ index = faiss.GpuIndexIVFFlat(res, ncols, nlist, faiss.METRIC_L2, config)
+ t0 = time.time()
+ index.train(trainVecs)
+ return 1000*(time.time() - t0)
+
+
+#warmup
+xw = rs.rand(nt, d)
+bench_train_milliseconds(xw, d, args.nlist, True)
+
+
+if args.bm_train:
+ print("=" * 40)
+ print("GPU Train Benchmarks")
+ print("=" * 40)
+
+ cuvs_gpu_train_time = bench_train_milliseconds(xt, d, args.nlist, True)
+ classical_gpu_train_time = bench_train_milliseconds(xt, d, args.nlist, False)
+ print("Method: IVFFlat, Operation: TRAIN, dim: %d, nlist %d, numTrain: %d, classical GPU train time: %.3f milliseconds, cuVS enabled GPU train time: %.3f milliseconds" % (
+ d, args.nlist, nt, classical_gpu_train_time, cuvs_gpu_train_time))
+
+
+def bench_add_milliseconds(addVecs, q, use_cuvs):
+ # construct a GPU index using the same trained coarse quantizer
+ config = faiss.GpuIndexIVFFlatConfig()
+ config.use_cuvs = use_cuvs
+ index_gpu = faiss.GpuIndexIVFFlat(res, q, d, args.nlist, faiss.METRIC_L2, config)
+ assert(index_gpu.is_trained)
+ t0 = time.time()
+ index_gpu.add(addVecs)
+ return 1000*(time.time() - t0)
+
+
+if args.bm_add:
+ print("=" * 40)
+ print("GPU Add Benchmarks")
+ print("=" * 40)
+ quantizer = faiss.IndexFlatL2(d)
+ idx_cpu = faiss.IndexIVFFlat(quantizer, d, args.nlist)
+ idx_cpu.train(xt)
+ cuvs_gpu_add_time = bench_add_milliseconds(xb, quantizer, True)
+ classical_gpu_add_time = bench_add_milliseconds(xb, quantizer, False)
+ print("Method: IVFFlat, Operation: ADD, dim: %d, nlist %d, numAdd: %d, classical GPU add time: %.3f milliseconds, cuVS enabled GPU add time: %.3f milliseconds" % (
+ d, args.nlist, nb, classical_gpu_add_time, cuvs_gpu_add_time))
+
+
+def bench_search_milliseconds(index, queryVecs, nprobe, k, use_cuvs):
+ co = faiss.GpuClonerOptions()
+ co.use_cuvs = use_cuvs
+ index_gpu = faiss.index_cpu_to_gpu(res, 0, index, co)
+ index_gpu.nprobe = nprobe
+ t0 = time.time()
+ index_gpu.search(queryVecs, k)
+ return 1000*(time.time() - t0)
+
+
+if args.bm_search:
+ print("=" * 40)
+ print("GPU Search Benchmarks")
+ print("=" * 40)
+ idx_cpu = faiss.IndexIVFFlat(
+ faiss.IndexFlatL2(d), d, args.nlist)
+ idx_cpu.train(xt)
+ idx_cpu.add(xb)
+
+ cuvs_gpu_search_time = bench_search_milliseconds(
+ idx_cpu, xq, args.nprobe, args.k, True)
+ classical_gpu_search_time = bench_search_milliseconds(
+ idx_cpu, xq, args.nprobe, args.k, False)
+ print("Method: IVFFlat, Operation: SEARCH, dim: %d, nlist: %d, numVecs: %d, numQuery: %d, nprobe: %d, k: %d, classical GPU search time: %.3f milliseconds, cuVS enabled GPU search time: %.3f milliseconds" % (
+ d, args.nlist, nb, nq, args.nprobe, args.k, classical_gpu_search_time, cuvs_gpu_search_time))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivfpq_cuvs.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivfpq_cuvs.py
new file mode 100644
index 0000000..924f240
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_ivfpq_cuvs.py
@@ -0,0 +1,187 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Meta Platforms, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+#
+# Copyright (c) 2024-2025, NVIDIA CORPORATION.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import numpy as np
+import faiss
+import time
+import argparse
+import rmm
+import ctypes
+
+try:
+ from faiss.contrib.datasets_fb import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+except ImportError:
+ from faiss.contrib.datasets import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+
+
+# ds = DatasetDeep1B(10**6)
+# ds = DatasetBigANN(nb_M=1)
+ds = DatasetSIFT1M()
+
+xq = ds.get_queries()
+xb = ds.get_database()
+gt = ds.get_groundtruth()
+
+xt = ds.get_train()
+
+nb, d = xb.shape
+nq, d = xq.shape
+nt, d = xt.shape
+
+M = d / 2
+
+######################################################
+# Command-line parsing
+######################################################
+
+parser = argparse.ArgumentParser()
+
+
+def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+
+group = parser.add_argument_group('benchmarking options')
+
+aa('--bm_train', default=True,
+ help='whether to benchmark train operation on GPU index')
+aa('--bm_add', default=True,
+ help='whether to benchmark add operation on GPU index')
+aa('--bm_search', default=True,
+ help='whether to benchmark search operation on GPU index')
+
+
+group = parser.add_argument_group('IVF options')
+aa('--nlist', default=1024, type=np.int64,
+ help="number of IVF centroids")
+aa('--bits_per_code', default=8, type=np.int64, help='bits per code. Note that < 8 is only supported when cuVS is enabled')
+
+
+group = parser.add_argument_group('searching')
+
+aa('--k', default=10, type=int, help='nb of nearest neighbors')
+aa('--nprobe', default=10, help='nb of IVF lists to probe')
+
+args = parser.parse_args()
+
+print("args:", args)
+
+gt = gt[:, :args.k]
+nlist = args.nlist
+bits_per_code = args.bits_per_code
+
+rs = np.random.RandomState(123)
+
+res = faiss.StandardGpuResources()
+
+# Use an RMM pool memory resource for device allocations
+mr = rmm.mr.PoolMemoryResource(rmm.mr.CudaMemoryResource())
+rmm.mr.set_current_device_resource(mr)
+
+
+def eval_recall(neighbors, t):
+ speed = t * 1000 / nq
+ qps = 1000 / speed
+
+ corrects = (gt == neighbors).sum()
+ recall = corrects / (nq * args.k)
+
+ return recall, qps
+
+
+def bench_train_milliseconds(trainVecs, use_cuvs):
+ config = faiss.GpuIndexIVFPQConfig()
+ config.use_cuvs = use_cuvs
+ index = faiss.GpuIndexIVFPQ(res, d, 1024, 32, 8, faiss.METRIC_L2, config)
+ t0 = time.time()
+ index.train(trainVecs)
+ return 1000*(time.time() - t0)
+
+
+#warmup
+xw = rs.rand(nt, d)
+bench_train_milliseconds(xw, True)
+
+
+if args.bm_train:
+ print("=" * 40)
+ print("GPU Train Benchmarks")
+ print("=" * 40)
+
+ cuvs_gpu_train_time = bench_train_milliseconds(xt, True)
+ classical_gpu_train_time = bench_train_milliseconds(xt, False)
+ print("TRAIN, dim: %d, nlist %d, numTrain: %d, classical GPU train time: %.3f milliseconds, cuVS enabled GPU train time: %.3f milliseconds" % (
+ d, nlist, nt, classical_gpu_train_time, cuvs_gpu_train_time))
+
+
+def bench_add_milliseconds(addVecs, index_cpu, use_cuvs):
+ # construct a GPU index using the same trained coarse quantizer
+ config = faiss.GpuClonerOptions()
+ config.use_cuvs = use_cuvs
+ index_gpu = faiss.index_cpu_to_gpu(res, 0, index_cpu, config)
+ assert(index_gpu.is_trained)
+ t0 = time.time()
+ index_gpu.add(addVecs)
+ return 1000*(time.time() - t0)
+
+
+if args.bm_add:
+ print("=" * 40)
+ print("GPU Add Benchmarks")
+ print("=" * 40)
+ quantizer = faiss.IndexFlatL2(d)
+ index_cpu = faiss.IndexIVFPQ(quantizer, d, 1024, 32, 8, faiss.METRIC_L2)
+ index_cpu.train(xt)
+ cuvs_gpu_add_time = bench_add_milliseconds(xb, index_cpu, True)
+ classical_gpu_add_time = bench_add_milliseconds(xb, index_cpu, False)
+ print("ADD, dim: %d, nlist %d, numAdd: %d, classical GPU add time: %.3f milliseconds, cuVS enabled GPU add time: %.3f milliseconds" % (
+ d, nlist, nb, classical_gpu_add_time, cuvs_gpu_add_time))
+
+
+def bench_search_milliseconds(index, queryVecs, nprobe, k, use_cuvs):
+ co = faiss.GpuClonerOptions()
+ co.use_cuvs = use_cuvs
+ index_gpu = faiss.index_cpu_to_gpu(res, 0, index, co)
+ index_gpu.nprobe = nprobe
+ t0 = time.time()
+ _, I = index_gpu.search(queryVecs, k)
+ return I, 1000*(time.time() - t0)
+
+
+# Search benchmarks: both indexes have identical IVF centroids and lists.
+if args.bm_search:
+ print("=" * 40)
+ print("GPU Search Benchmarks")
+ print("=" * 40)
+ index_cpu = faiss.IndexIVFPQ(quantizer, d, 1024, 32, 8, faiss.METRIC_L2)
+ index_cpu.train(xt)
+ index_cpu.add(xb)
+
+ cuvs_indices, cuvs_gpu_search_time = bench_search_milliseconds(
+ index_cpu, xq, args.nprobe, args.k, True)
+ classical_gpu_indices, classical_gpu_search_time = bench_search_milliseconds(
+ index_cpu, xq, args.nprobe, args.k, False)
+ cuvs_recall, cuvs_qps = eval_recall(cuvs_indices, cuvs_gpu_search_time)
+ classical_recall, classical_qps = eval_recall(classical_gpu_indices, classical_gpu_search_time)
+ print("SEARCH, dim: %d, nlist: %d, numVecs: %d, numQuery: %d, nprobe: %d, k: %d, classical GPU qps: %.3f, cuVS enabled GPU qps: %.3f" % (
+ d, nlist, nb, nq, args.nprobe, args.k, classical_qps, cuvs_qps))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pairwise_distances.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pairwise_distances.py
new file mode 100644
index 0000000..eb3f8c1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pairwise_distances.py
@@ -0,0 +1,35 @@
+#! /usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""small test script to benchmark the SIMD implementation of the
+distance computations for the additional metrics. Call eg. with L1 to
+get L1 distance computations.
+"""
+
+import faiss
+
+import sys
+import time
+
+d = 64
+nq = 4096
+nb = 16384
+
+print("sample")
+
+xq = faiss.randn((nq, d), 123)
+xb = faiss.randn((nb, d), 123)
+
+mt_name = "L2" if len(sys.argv) < 2 else sys.argv[1]
+
+mt = getattr(faiss, "METRIC_" + mt_name)
+
+print("distances")
+t0 = time.time()
+dis = faiss.pairwise_distances(xq, xb, mt)
+t1 = time.time()
+
+print("nq=%d nb=%d d=%d %s: %.3f s" % (nq, nb, d, mt_name, t1 - t0))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_partition.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_partition.py
new file mode 100644
index 0000000..85c912e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_partition.py
@@ -0,0 +1,78 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import faiss
+import numpy as np
+
+def do_partition(n, qin, maxval=65536, seed=123, id_type='int64'):
+ print(
+ f"n={n} qin={qin} maxval={maxval} id_type={id_type} ",
+ end="\t", flush=True
+ )
+
+ # print("seed=", seed)
+ rs = np.random.RandomState(seed)
+ vals = rs.randint(maxval, size=n).astype('uint16')
+ ids = (rs.permutation(n) + 12345).astype(id_type)
+
+ sp = faiss.swig_ptr
+
+ tab_a = faiss.AlignedTableUint16()
+ faiss.copy_array_to_AlignedTable(vals, tab_a)
+
+ nrun = 2000
+
+ times = []
+ nerr = 0
+ stats = faiss.cvar.partition_stats
+ stats.reset()
+ for _run in range(nrun):
+ faiss.copy_array_to_AlignedTable(vals, tab_a)
+ t0 = time.time()
+ # print("tab a type", tab_a.get())
+ if type(qin) == int:
+ q = qin
+ faiss.CMax_uint16_partition_fuzzy(
+ tab_a.get(), sp(ids), n, q, q, None)
+ else:
+ q_min, q_max = qin
+ q = np.array([-1], dtype='uint64')
+ faiss.CMax_uint16_partition_fuzzy(
+ tab_a.get(), sp(ids), n,
+ q_min, q_max, sp(q)
+ )
+ q = q[0]
+
+ if not (q_min <= q <= q_max):
+ nerr += 1
+
+ t1 = time.time()
+
+ times.append(t1 - t0)
+
+ times = np.array(times[100:]) * 1000000
+
+
+ print(
+ f"times {times.mean():.3f} µs (± {times.std():.4f} µs) nerr={nerr} "
+ f"bissect {stats.bissect_cycles / 1e6:.3f} Mcy "
+ f"compress {stats.compress_cycles / 1e6:.3f} Mcy"
+ )
+
+do_partition(200, (100, 100))
+do_partition(200, (100, 150))
+do_partition(2000, (1000, 1000))
+do_partition(2000, (1000, 1500))
+do_partition(20000, (10000, 10000))
+do_partition(20000, (10000, 15000))
+
+
+do_partition(200, (100, 100), id_type='int32')
+do_partition(200, (100, 150), id_type='int32')
+do_partition(2000, (1000, 1000), id_type='int32')
+do_partition(2000, (1000, 1500), id_type='int32')
+do_partition(20000, (10000, 10000), id_type='int32')
+do_partition(20000, (10000, 15000), id_type='int32')
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_polysemous_1bn.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_polysemous_1bn.py
new file mode 100644
index 0000000..8cbfe0e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_polysemous_1bn.py
@@ -0,0 +1,251 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import sys
+import time
+import numpy as np
+import re
+import faiss
+from multiprocessing.pool import ThreadPool
+from datasets import ivecs_read
+
+
+# we mem-map the biggest files to avoid having them in memory all at
+# once
+
+
+def mmap_fvecs(fname):
+ x = np.memmap(fname, dtype='int32', mode='r')
+ d = x[0]
+ return x.view('float32').reshape(-1, d + 1)[:, 1:]
+
+
+def mmap_bvecs(fname):
+ x = np.memmap(fname, dtype='uint8', mode='r')
+ d = x[:4].view('int32')[0]
+ return x.reshape(-1, d + 4)[:, 4:]
+
+
+#################################################################
+# Bookkeeping
+#################################################################
+
+
+dbname = sys.argv[1]
+index_key = sys.argv[2]
+parametersets = sys.argv[3:]
+
+
+tmpdir = '/tmp/bench_polysemous'
+
+if not os.path.isdir(tmpdir):
+ print("%s does not exist, creating it" % tmpdir)
+ os.mkdir(tmpdir)
+
+
+#################################################################
+# Prepare dataset
+#################################################################
+
+
+print("Preparing dataset", dbname)
+
+if dbname.startswith('SIFT'):
+ # SIFT1M to SIFT1000M
+ dbsize = int(dbname[4:-1])
+ xb = mmap_bvecs('bigann/bigann_base.bvecs')
+ xq = mmap_bvecs('bigann/bigann_query.bvecs')
+ xt = mmap_bvecs('bigann/bigann_learn.bvecs')
+
+ # trim xb to correct size
+ xb = xb[:dbsize * 1000 * 1000]
+
+ gt = ivecs_read('bigann/gnd/idx_%dM.ivecs' % dbsize)
+
+elif dbname == 'Deep1B':
+ xb = mmap_fvecs('deep1b/base.fvecs')
+ xq = mmap_fvecs('deep1b/deep1B_queries.fvecs')
+ xt = mmap_fvecs('deep1b/learn.fvecs')
+ # deep1B's train is is outrageously big
+ xt = xt[:10 * 1000 * 1000]
+ gt = ivecs_read('deep1b/deep1B_groundtruth.ivecs')
+
+else:
+ print('unknown dataset', dbname, file=sys.stderr)
+ sys.exit(1)
+
+
+print("sizes: B %s Q %s T %s gt %s" % (
+ xb.shape, xq.shape, xt.shape, gt.shape))
+
+nq, d = xq.shape
+nb, d = xb.shape
+assert gt.shape[0] == nq
+
+
+#################################################################
+# Training
+#################################################################
+
+
+def choose_train_size(index_key):
+
+ # some training vectors for PQ and the PCA
+ n_train = 256 * 1000
+
+ if "IVF" in index_key:
+ matches = re.findall('IVF([0-9]+)', index_key)
+ ncentroids = int(matches[0])
+ n_train = max(n_train, 100 * ncentroids)
+ elif "IMI" in index_key:
+ matches = re.findall('IMI2x([0-9]+)', index_key)
+ nbit = int(matches[0])
+ n_train = max(n_train, 256 * (1 << nbit))
+ return n_train
+
+
+def get_trained_index():
+ filename = "%s/%s_%s_trained.index" % (
+ tmpdir, dbname, index_key)
+
+ if not os.path.exists(filename):
+ index = faiss.index_factory(d, index_key)
+
+ n_train = choose_train_size(index_key)
+
+ xtsub = xt[:n_train]
+ print("Keeping %d train vectors" % xtsub.shape[0])
+ # make sure the data is actually in RAM and in float
+ xtsub = xtsub.astype('float32').copy()
+ index.verbose = True
+
+ t0 = time.time()
+ index.train(xtsub)
+ index.verbose = False
+ print("train done in %.3f s" % (time.time() - t0))
+ print("storing", filename)
+ faiss.write_index(index, filename)
+ else:
+ print("loading", filename)
+ index = faiss.read_index(filename)
+ return index
+
+
+#################################################################
+# Adding vectors to dataset
+#################################################################
+
+def rate_limited_imap(f, l):
+ 'a thread pre-processes the next element'
+ pool = ThreadPool(1)
+ res = None
+ for i in l:
+ res_next = pool.apply_async(f, (i, ))
+ if res:
+ yield res.get()
+ res = res_next
+ yield res.get()
+
+
+def matrix_slice_iterator(x, bs):
+ " iterate over the lines of x in blocks of size bs"
+ nb = x.shape[0]
+ block_ranges = [(i0, min(nb, i0 + bs))
+ for i0 in range(0, nb, bs)]
+
+ return rate_limited_imap(
+ lambda i01: x[i01[0]:i01[1]].astype('float32').copy(),
+ block_ranges)
+
+
+def get_populated_index():
+
+ filename = "%s/%s_%s_populated.index" % (
+ tmpdir, dbname, index_key)
+
+ if not os.path.exists(filename):
+ index = get_trained_index()
+ i0 = 0
+ t0 = time.time()
+ for xs in matrix_slice_iterator(xb, 100000):
+ i1 = i0 + xs.shape[0]
+ print('\radd %d:%d, %.3f s' % (i0, i1, time.time() - t0), end=' ')
+ sys.stdout.flush()
+ index.add(xs)
+ i0 = i1
+ print()
+ print("Add done in %.3f s" % (time.time() - t0))
+ print("storing", filename)
+ faiss.write_index(index, filename)
+ else:
+ print("loading", filename)
+ index = faiss.read_index(filename)
+ return index
+
+
+#################################################################
+# Perform searches
+#################################################################
+
+index = get_populated_index()
+
+ps = faiss.ParameterSpace()
+ps.initialize(index)
+
+# make sure queries are in RAM
+xq = xq.astype('float32').copy()
+
+# a static C++ object that collects statistics about searches
+ivfpq_stats = faiss.cvar.indexIVFPQ_stats
+ivf_stats = faiss.cvar.indexIVF_stats
+
+
+if parametersets == ['autotune'] or parametersets == ['autotuneMT']:
+
+ if parametersets == ['autotune']:
+ faiss.omp_set_num_threads(1)
+
+ # setup the Criterion object: optimize for 1-R@1
+ crit = faiss.OneRecallAtRCriterion(nq, 1)
+ # by default, the criterion will request only 1 NN
+ crit.nnn = 100
+ crit.set_groundtruth(None, gt.astype('int64'))
+
+ # then we let Faiss find the optimal parameters by itself
+ print("exploring operating points")
+
+ t0 = time.time()
+ op = ps.explore(index, xq, crit)
+ print("Done in %.3f s, available OPs:" % (time.time() - t0))
+
+ # opv is a C++ vector, so it cannot be accessed like a Python array
+ opv = op.optimal_pts
+ print("%-40s 1-R@1 time" % "Parameters")
+ for i in range(opv.size()):
+ opt = opv.at(i)
+ print("%-40s %.4f %7.3f" % (opt.key, opt.perf, opt.t))
+
+else:
+
+ # we do queries in a single thread
+ faiss.omp_set_num_threads(1)
+
+ print(' ' * len(parametersets[0]), '\t', 'R@1 R@10 R@100 time %pass')
+
+ for param in parametersets:
+ print(param, '\t', end=' ')
+ sys.stdout.flush()
+ ps.set_index_parameters(index, param)
+ t0 = time.time()
+ ivfpq_stats.reset()
+ ivf_stats.reset()
+ D, I = index.search(xq, 100)
+ t1 = time.time()
+ for rank in 1, 10, 100:
+ n_ok = (I[:, :rank] == gt[:, :1]).sum()
+ print("%.4f" % (n_ok / float(nq)), end=' ')
+ print("%8.3f " % ((t1 - t0) * 1000.0 / nq), end=' ')
+ print("%5.2f" % (ivfpq_stats.n_hamming_pass * 100.0 / ivf_stats.ndis))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_polysemous_sift1m.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_polysemous_sift1m.py
new file mode 100644
index 0000000..9cbd4f6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_polysemous_sift1m.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import time
+import numpy as np
+
+import faiss
+from datasets import load_sift1M, evaluate
+
+
+print("load data")
+xb, xq, xt, gt = load_sift1M()
+nq, d = xq.shape
+
+# index with 16 subquantizers, 8 bit each
+index = faiss.IndexPQ(d, 16, 8)
+index.do_polysemous_training = True
+index.verbose = True
+
+print("train")
+
+index.train(xt)
+
+print("add vectors to index")
+
+index.add(xb)
+
+nt = 1
+faiss.omp_set_num_threads(1)
+
+
+print("PQ baseline", end=' ')
+index.search_type = faiss.IndexPQ.ST_PQ
+t, r = evaluate(index, xq, gt, 1)
+print("\t %7.3f ms per query, R@1 %.4f" % (t, r[1]))
+
+for ht in 64, 62, 58, 54, 50, 46, 42, 38, 34, 30:
+ print("Polysemous", ht, end=' ')
+ index.search_type = faiss.IndexPQ.ST_polysemous
+ index.polysemous_ht = ht
+ t, r = evaluate(index, xq, gt, 1)
+ print("\t %7.3f ms per query, R@1 %.4f" % (t, r[1]))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pq_tables.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pq_tables.py
new file mode 100644
index 0000000..9f4cdca
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pq_tables.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import os
+import numpy as np
+import faiss
+
+os.system("grep -m1 'model name' < /proc/cpuinfo")
+
+def format_tab(x):
+ return "\n".join("\t".join("%g" % xi for xi in row) for row in x)
+
+
+def run_bench(d, dsub, nbit=8, metric=None):
+
+ M = d // dsub
+ pq = faiss.ProductQuantizer(d, M, nbit)
+ pq.train(faiss.randn((max(1000, pq.ksub * 50), d), 123))
+
+
+ sp = faiss.swig_ptr
+
+ times = []
+ nrun = 100
+
+ print(f"d={d} dsub={dsub} ksub={pq.ksub}", end="\t")
+ res = []
+ for nx in 1, 10, 100:
+ x = faiss.randn((nx, d), 555)
+
+ times = []
+ for run in range(nrun):
+ t0 = time.time()
+ new_tab = np.zeros((nx, M, pq.ksub), "float32")
+ if metric == faiss.METRIC_INNER_PRODUCT:
+ pq.compute_inner_prod_tables(nx, sp(x), sp(new_tab))
+ elif metric == faiss.METRIC_L2:
+ pq.compute_distance_tables(nx, sp(x), sp(new_tab))
+ else:
+ assert False
+ t1 = time.time()
+ if run >= nrun // 5: # the rest is considered warmup
+ times.append((t1 - t0))
+ times = np.array(times) * 1000
+
+ print(f"nx={nx}: {np.mean(times):.3f} ms (± {np.std(times):.4f})",
+ end="\t")
+ res.append(times.mean())
+ print()
+ return res
+
+# for have_threads in True, False:
+for have_threads in False, True:
+
+ if have_threads:
+ # good config for Intel(R) Xeon(R) CPU E5-2698 v4 @ 2.20GHz
+ nthread = 32
+ else:
+ nthread = 1
+
+ faiss.omp_set_num_threads(nthread)
+
+ for metric in faiss.METRIC_INNER_PRODUCT, faiss.METRIC_L2:
+ print("============= nthread=", nthread, "metric=", metric)
+ allres = []
+ for dsub in 2, 4, 8:
+ for nbit in 4, 8:
+ for M in 8, 20:
+ res = run_bench(M * dsub, dsub, nbit, metric)
+ allres.append(res)
+ allres = np.array(allres)
+ print("formated result:")
+ print(format_tab(allres))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pq_transposed_centroid_table.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pq_transposed_centroid_table.py
new file mode 100644
index 0000000..30a3aec
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_pq_transposed_centroid_table.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import time
+import random
+
+import faiss.contrib.datasets
+
+
+# copied from benchs/bench_all_ivf/bench_all_ivf.py
+def unwind_index_ivf(index):
+ if isinstance(index, faiss.IndexPreTransform):
+ assert index.chain.size() == 1
+ vt = index.chain.at(0)
+ index_ivf, vt2 = unwind_index_ivf(faiss.downcast_index(index.index))
+ assert vt2 is None
+ return index_ivf, vt
+ if hasattr(faiss, "IndexRefine") and isinstance(index, faiss.IndexRefine):
+ return unwind_index_ivf(faiss.downcast_index(index.base_index))
+ if isinstance(index, faiss.IndexIVF):
+ return index, None
+ else:
+ return None, None
+
+
+def test_bigann10m(index_file, index_parameters):
+ ds = faiss.contrib.datasets.DatasetBigANN(nb_M=10)
+
+ xq = ds.get_queries()
+ xb = ds.get_database()
+ gt = ds.get_groundtruth()
+
+ nb, d = xb.shape
+ nq, d = xq.shape
+
+ print("Reading index {}".format(index_file))
+ index = faiss.read_index(index_file)
+
+ ps = faiss.ParameterSpace()
+ ps.initialize(index)
+
+ index_ivf, vec_transform = unwind_index_ivf(index)
+
+ print('params regular transp_centroids regular R@1 R@10 R@100')
+ for index_parameter in index_parameters:
+ ps.set_index_parameters(index, index_parameter)
+
+ print(index_parameter.ljust(70), end=' ')
+
+ k = 100
+
+ # warmup
+ D, I = index.search(xq, k)
+
+ # warmup
+ D, I = index.search(xq, k)
+
+ # eval
+ t2_0 = time.time()
+ D, I = index.search(xq, k)
+ t2_1 = time.time()
+
+ # eval
+ index_ivf.pq.sync_transposed_centroids()
+ t3_0 = time.time()
+ D, I = index.search(xq, k)
+ t3_1 = time.time()
+
+ # eval
+ index_ivf.pq.clear_transposed_centroids()
+ t4_0 = time.time()
+ D, I = index.search(xq, k)
+ t4_1 = time.time()
+
+ print(" %9.5f " % (t2_1 - t2_0), end=' ')
+ print(" %9.5f " % (t3_1 - t3_0), end=' ')
+ print(" %9.5f " % (t4_1 - t4_0), end=' ')
+
+ for rank in 1, 10, 100:
+ n_ok = (I[:, :rank] == gt[:, :1]).sum()
+ print("%.4f" % (n_ok / float(nq)), end=' ')
+ print()
+
+
+if __name__ == "__main__":
+ faiss.contrib.datasets.dataset_basedir = '/home/aguzhva/ANN_SIFT1B/'
+
+ # represents OPQ32_128,IVF65536_HNSW32,PQ32 index
+ index_file_1 = "/home/aguzhva/ANN_SIFT1B/run_tests/bench_ivf/indexes/hnsw32/.faissindex"
+
+ nprobe_values = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
+ quantizer_efsearch_values = [4, 8, 16, 32, 64, 128, 256, 512]
+ ht_values = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 256]
+
+ # represents OPQ32_128,IVF65536(IVF256,PQHDx4fs,RFlat),PQ32 index
+ index_file_2 = "/home/aguzhva/ANN_SIFT1B/run_tests/bench_ivf/indexes/pq4/.faissindex"
+
+ quantizer_k_factor_rf_values = [1, 2, 4, 8, 16, 32, 64]
+ quantizer_nprobe_values = [1, 2, 4, 8, 16, 32, 64, 128]
+
+ # test the first index
+ index_parameters_1 = []
+ for _ in range(0, 20):
+ nprobe = random.choice(nprobe_values)
+ quantizer_efsearch = random.choice(quantizer_efsearch_values)
+ ht = random.choice(ht_values)
+ index_parameters_1.append(
+ "nprobe={},quantizer_efSearch={},ht={}".format(
+ nprobe,
+ quantizer_efsearch,
+ ht)
+ )
+
+ test_bigann10m(index_file_1, index_parameters_1)
+
+ # test the second index
+ index_parameters_2 = []
+ for _ in range(0, 20):
+ nprobe = random.choice(nprobe_values)
+ quantizer_k_factor_rf = random.choice(quantizer_k_factor_rf_values)
+ quantizer_nprobe = random.choice(quantizer_nprobe_values)
+ ht = random.choice(ht_values)
+ index_parameters_2.append(
+ "nprobe={},quantizer_k_factor_rf={},quantizer_nprobe={},ht={}".format(
+ nprobe,
+ quantizer_k_factor_rf,
+ quantizer_nprobe,
+ ht)
+ )
+
+ test_bigann10m(index_file_2, index_parameters_2)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_quantizer.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_quantizer.py
new file mode 100644
index 0000000..80921c6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_quantizer.py
@@ -0,0 +1,157 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import sys
+import faiss
+import time
+import numpy as np
+
+try:
+ from faiss.contrib.datasets_fb import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+except ImportError:
+ from faiss.contrib.datasets import \
+ DatasetSIFT1M, DatasetDeep1B, DatasetBigANN
+
+
+def eval_codec(q, xq, xb, gt):
+ t0 = time.time()
+ codes = q.compute_codes(xb)
+ t1 = time.time()
+ xb_decoded = q.decode(codes)
+ recons_err = ((xb - xb_decoded) ** 2).sum() / xb.shape[0]
+ # for compatibility with the codec benchmarks
+ err_compat = np.linalg.norm(xb - xb_decoded, axis=1).mean()
+ xq_decoded = q.decode(q.compute_codes(xq))
+ D, I = faiss.knn(xq_decoded, xb_decoded, 1)
+ recall = (I[:, 0] == gt[:, 0]).sum() / nq
+ print(
+ f"\tencode time: {t1 - t0:.3f} reconstruction error: {recons_err:.3f} "
+ f"1-recall@1: {recall:.4f} recons_err_compat {err_compat:.3f}")
+
+
+def eval_quantizer(q, xq, xb, gt, xt, variants=None):
+ if variants is None:
+ variants = [(None, None)]
+ t0 = time.time()
+ q.train(xt)
+ t1 = time.time()
+ train_t = t1 - t0
+ print(f'\ttraining time: {train_t:.3f} s')
+ for name, val in variants:
+ if name is not None:
+ print(f"{name}={val}")
+
+ if isinstance(q, faiss.ProductAdditiveQuantizer):
+ for i in range(q.nsplits):
+ subq = faiss.downcast_Quantizer(q.subquantizer(i))
+ getattr(subq, name)
+ setattr(subq, name, val)
+ else:
+ getattr(q, name) # make sure field exists
+ setattr(q, name, val)
+
+ eval_codec(q, xq, xb, gt)
+
+
+todo = sys.argv[1:]
+
+if len(todo) > 0 and "deep1M" in todo[0]:
+ ds = DatasetDeep1B(10**6)
+ del todo[0]
+elif len(todo) > 0 and "bigann1M" in todo[0]:
+ ds = DatasetBigANN(nb_M=1)
+ del todo[0]
+else:
+ ds = DatasetSIFT1M()
+
+if len(todo) > 0:
+ if todo[0].count("x") == 1:
+ M, nbits = [int(x) for x in todo[0].split("x")]
+ del todo[0]
+ elif todo[0].count("x") == 2:
+ nsplits, Msub, nbits = [int(x) for x in todo[0].split("x")]
+ M = nsplits * Msub
+ del todo[0]
+
+maxtrain = max(100 << nbits, 10**5)
+print(f"eval on {M}x{nbits} maxtrain={maxtrain}")
+
+xq = ds.get_queries()
+xb = ds.get_database()
+gt = ds.get_groundtruth()
+
+xt = ds.get_train(maxtrain=maxtrain)
+
+nb, d = xb.shape
+nq, d = xq.shape
+nt, d = xt.shape
+
+
+# fastest to slowest
+
+if 'lsq-gpu' in todo:
+ lsq = faiss.LocalSearchQuantizer(d, M, nbits)
+ ngpus = faiss.get_num_gpus()
+ lsq.icm_encoder_factory = faiss.GpuIcmEncoderFactory(ngpus)
+ lsq.verbose = True
+ eval_quantizer(lsq, xb, xt, 'lsq-gpu')
+
+if 'pq' in todo:
+ pq = faiss.ProductQuantizer(d, M, nbits)
+ print("===== PQ")
+ eval_quantizer(pq, xq, xb, gt, xt)
+
+if 'opq' in todo:
+ d2 = ((d + M - 1) // M) * M
+ print("OPQ d2=", d2)
+ opq = faiss.OPQMatrix(d, M, d2)
+ opq.train(xt)
+ xq2 = opq.apply(xq)
+ xb2 = opq.apply(xb)
+ xt2 = opq.apply(xt)
+ pq = faiss.ProductQuantizer(d2, M, nbits)
+ print("===== PQ")
+ eval_quantizer(pq, xq2, xb2, gt, xt2)
+
+if 'prq' in todo:
+ print(f"===== PRQ{nsplits}x{Msub}x{nbits}")
+ prq = faiss.ProductResidualQuantizer(d, nsplits, Msub, nbits)
+ variants = [("max_beam_size", i) for i in (1, 2, 4, 8, 16, 32)]
+ eval_quantizer(prq, xq, xb, gt, xt, variants=variants)
+
+if 'plsq' in todo:
+ print(f"===== PLSQ{nsplits}x{Msub}x{nbits}")
+ plsq = faiss.ProductLocalSearchQuantizer(d, nsplits, Msub, nbits)
+ variants = [("encode_ils_iters", i) for i in (2, 3, 4, 8, 16)]
+ eval_quantizer(plsq, xq, xb, gt, xt, variants=variants)
+
+if 'rq' in todo:
+ print("===== RQ")
+ rq = faiss.ResidualQuantizer(d, M, nbits, )
+ rq.max_beam_size
+ rq.max_beam_size = 30 # for compatibility with older runs
+ # rq.train_type = faiss.ResidualQuantizer.Train_default
+ # rq.verbose = True
+ variants = [("max_beam_size", i) for i in (1, 2, 4, 8, 16, 32)]
+ eval_quantizer(rq, xq, xb, gt, xt, variants=variants)
+
+if 'rq_lut' in todo:
+ print("===== RQ")
+ rq = faiss.ResidualQuantizer(d, M, nbits, )
+ rq.max_beam_size
+ rq.max_beam_size = 30 # for compatibility with older runs
+ rq.use_beam_LUT
+ rq.use_beam_LUT = 1
+ # rq.train_type = faiss.ResidualQuantizer.Train_default
+ # rq.verbose = True
+ variants = [("max_beam_size", i) for i in (1, 2, 4, 8, 16, 32, 64)]
+ eval_quantizer(rq, xq, xb, gt, xt, variants=variants)
+
+if 'lsq' in todo:
+ print("===== LSQ")
+ lsq = faiss.LocalSearchQuantizer(d, M, nbits)
+ variants = [("encode_ils_iters", i) for i in (2, 3, 4, 8, 16)]
+ eval_quantizer(lsq, xq, xb, gt, xt, variants=variants)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_scalar_quantizer.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_scalar_quantizer.py
new file mode 100644
index 0000000..32d391f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_scalar_quantizer.py
@@ -0,0 +1,82 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import numpy as np
+import faiss
+from datasets import load_sift1M
+
+
+print("load data")
+
+xb, xq, xt, gt = load_sift1M()
+nq, d = xq.shape
+
+ncent = 256
+
+variants = [(name, getattr(faiss.ScalarQuantizer, name))
+ for name in dir(faiss.ScalarQuantizer)
+ if name.startswith('QT_')]
+
+quantizer = faiss.IndexFlatL2(d)
+# quantizer.add(np.zeros((1, d), dtype='float32'))
+
+if False:
+ for name, qtype in [('flat', 0)] + variants:
+
+ print("============== test", name)
+ t0 = time.time()
+
+ if name == 'flat':
+ index = faiss.IndexIVFFlat(quantizer, d, ncent,
+ faiss.METRIC_L2)
+ else:
+ index = faiss.IndexIVFScalarQuantizer(quantizer, d, ncent,
+ qtype, faiss.METRIC_L2)
+
+ index.nprobe = 16
+ print("[%.3f s] train" % (time.time() - t0))
+ index.train(xt)
+ print("[%.3f s] add" % (time.time() - t0))
+ index.add(xb)
+ print("[%.3f s] search" % (time.time() - t0))
+ D, I = index.search(xq, 100)
+ print("[%.3f s] eval" % (time.time() - t0))
+
+ for rank in 1, 10, 100:
+ n_ok = (I[:, :rank] == gt[:, :1]).sum()
+ print("%.4f" % (n_ok / float(nq)), end=' ')
+ print()
+
+if True:
+ for name, qtype in variants:
+
+ print("============== test", name)
+
+ for rsname, vals in [('RS_minmax',
+ [-0.4, -0.2, -0.1, -0.05, 0.0, 0.1, 0.5]),
+ ('RS_meanstd', [0.8, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0]),
+ ('RS_quantiles', [0.02, 0.05, 0.1, 0.15]),
+ ('RS_optim', [0.0])]:
+ for val in vals:
+ print("%-15s %5g " % (rsname, val), end=' ')
+ index = faiss.IndexIVFScalarQuantizer(quantizer, d, ncent,
+ qtype, faiss.METRIC_L2)
+ index.nprobe = 16
+ index.sq.rangestat = getattr(faiss.ScalarQuantizer,
+ rsname)
+
+ index.rangestat_arg = val
+
+ index.train(xt)
+ index.add(xb)
+ t0 = time.time()
+ D, I = index.search(xq, 100)
+ t1 = time.time()
+
+ for rank in 1, 10, 100:
+ n_ok = (I[:, :rank] == gt[:, :1]).sum()
+ print("%.4f" % (n_ok / float(nq)), end=' ')
+ print(" %.3f s" % (t1 - t0))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_vector_ops.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_vector_ops.py
new file mode 100644
index 0000000..96aa970
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/bench_vector_ops.py
@@ -0,0 +1,84 @@
+#! /usr/bin/env python2
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import numpy as np
+import faiss
+import time
+
+swig_ptr = faiss.swig_ptr
+
+if False:
+ a = np.arange(10, 14).astype('float32')
+ b = np.arange(20, 24).astype('float32')
+
+ faiss.fvec_inner_product (swig_ptr(a), swig_ptr(b), 4)
+
+ 1/0
+
+xd = 100
+yd = 1000000
+
+np.random.seed(1234)
+
+faiss.omp_set_num_threads(1)
+
+print('xd=%d yd=%d' % (xd, yd))
+
+print('Running inner products test..')
+for d in 3, 4, 12, 36, 64:
+
+ x = faiss.rand(xd * d).reshape(xd, d)
+ y = faiss.rand(yd * d).reshape(yd, d)
+
+ distances = np.empty((xd, yd), dtype='float32')
+
+ t0 = time.time()
+ for i in range(xd):
+ faiss.fvec_inner_products_ny(swig_ptr(distances[i]),
+ swig_ptr(x[i]),
+ swig_ptr(y),
+ d, yd)
+ t1 = time.time()
+
+ # sparse verification
+ ntry = 100
+ num, denom = 0, 0
+ for t in range(ntry):
+ xi = np.random.randint(xd)
+ yi = np.random.randint(yd)
+ num += abs(distances[xi, yi] - np.dot(x[xi], y[yi]))
+ denom += abs(distances[xi, yi])
+
+ print('d=%d t=%.3f s diff=%g' % (d, t1 - t0, num / denom))
+
+
+print('Running L2sqr test..')
+for d in 3, 4, 12, 36, 64:
+
+ x = faiss.rand(xd * d).reshape(xd, d)
+ y = faiss.rand(yd * d).reshape(yd, d)
+
+ distances = np.empty((xd, yd), dtype='float32')
+
+ t0 = time.time()
+ for i in range(xd):
+ faiss.fvec_L2sqr_ny(swig_ptr(distances[i]),
+ swig_ptr(x[i]),
+ swig_ptr(y),
+ d, yd)
+ t1 = time.time()
+
+ # sparse verification
+ ntry = 100
+ num, denom = 0, 0
+ for t in range(ntry):
+ xi = np.random.randint(xd)
+ yi = np.random.randint(yd)
+ num += abs(distances[xi, yi] - np.sum((x[xi] - y[yi]) ** 2))
+ denom += abs(distances[xi, yi])
+
+ print('d=%d t=%.3f s diff=%g' % (d, t1 - t0, num / denom))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/datasets.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/datasets.py
new file mode 100644
index 0000000..4b9002f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/datasets.py
@@ -0,0 +1,45 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import sys
+import time
+import numpy as np
+
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype='int32')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+def load_sift1M():
+ print("Loading sift1M...", end='', file=sys.stderr)
+ xt = fvecs_read("sift1M/sift_learn.fvecs")
+ xb = fvecs_read("sift1M/sift_base.fvecs")
+ xq = fvecs_read("sift1M/sift_query.fvecs")
+ gt = ivecs_read("sift1M/sift_groundtruth.ivecs")
+ print("done", file=sys.stderr)
+
+ return xb, xq, xt, gt
+
+
+def evaluate(index, xq, gt, k):
+ nq = xq.shape[0]
+ t0 = time.time()
+ D, I = index.search(xq, k) # noqa: E741
+ t1 = time.time()
+
+ recalls = {}
+ i = 1
+ while i <= k:
+ recalls[i] = (I[:, :i] == gt[:, :1]).sum() / float(nq)
+ i *= 10
+
+ return (t1 - t0) * 1000.0 / nq, recalls
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/README.md b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/README.md
new file mode 100644
index 0000000..22904f4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/README.md
@@ -0,0 +1,194 @@
+# Distributed on-disk index for 1T-scale datasets
+
+This is code corresponding to the description in [Indexing 1T vectors](https://github.com/facebookresearch/faiss/wiki/Indexing-1T-vectors).
+All the code is in python 3 (and not compatible with Python 2).
+The current code uses the Deep1B dataset for demonstration purposes, but can scale to 1000x larger.
+To run it, download the Deep1B dataset as explained [here](../#getting-deep1b), and edit paths to the dataset in the scripts.
+
+The cluster commands are written for the Slurm batch scheduling system.
+Hopefully, changing to another type of scheduler should be quite straightforward.
+
+## Distributed k-means
+
+To cluster 500M vectors to 10M centroids, it is useful to have a distributed k-means implementation.
+The distribution simply consists in splitting the training vectors across machines (servers) and have them do the assignment.
+The master/client then synthesizes the results and updates the centroids.
+
+The distributed k-means implementation here is based on 3 files:
+
+- [`distributed_kmeans.py`](distributed_kmeans.py) contains the k-means implementation.
+The main loop of k-means is re-implemented in python but follows closely the Faiss C++ implementation, and should not be significantly less efficient.
+It relies on a `DatasetAssign` object that does the assignment to centroids, which is the bulk of the computation.
+The object can be a Faiss CPU index, a GPU index or a set of remote GPU or CPU indexes.
+
+- [`run_on_cluster.bash`](run_on_cluster.bash) contains the shell code to run the distributed k-means on a cluster.
+
+The distributed k-means works with a Python install that contains faiss and scipy (for sparse matrices).
+It clusters the training data of Deep1B, this can be changed easily to any file in fvecs, bvecs or npy format that contains the training set.
+The training vectors may be too large to fit in RAM, but they are memory-mapped so that should not be a problem.
+The file is also assumed to be accessible from all server machines with eg. a distributed file system.
+
+### Local tests
+
+Edit `distributed_kmeans.py` to point `testdata` to your local copy of the dataset.
+
+Then, 4 levels of sanity check can be run:
+```bash
+# reference Faiss C++ run
+python distributed_kmeans.py --test 0
+# using the Python implementation
+python distributed_kmeans.py --test 1
+# use the dispatch object (on local datasets)
+python distributed_kmeans.py --test 2
+# same, with GPUs
+python distributed_kmeans.py --test 3
+```
+The output should look like [This gist](https://gist.github.com/mdouze/ffa01fe666a9325761266fe55ead72ad).
+
+### Distributed sanity check
+
+To run the distributed k-means, `distributed_kmeans.py` has to be run both on the servers (`--server` option) and client sides (`--client` option).
+Edit the top of `run_on_cluster.bash` to set the path of the data to cluster.
+
+Sanity checks can be run with
+```bash
+# non distributed baseline
+bash run_on_cluster.bash test_kmeans_0
+# using all the machine's GPUs
+bash run_on_cluster.bash test_kmeans_1
+# distributed run, with one local server per GPU
+bash run_on_cluster.bash test_kmeans_2
+```
+The test `test_kmeans_2` simulates a distributed run on a single machine by starting one server process per GPU and connecting to the servers via the rpc protocol.
+The output should look like [this gist](https://gist.github.com/mdouze/5b2dc69b74579ecff04e1686a277d32e).
+
+
+
+### Distributed run
+
+The way the script can be distributed depends on the cluster's scheduling system.
+Here we use Slurm, but it should be relatively easy to adapt to any scheduler that can allocate a set of machines and start the same executable on all of them.
+
+The command
+```bash
+bash run_on_cluster.bash slurm_distributed_kmeans
+```
+asks SLURM for 5 machines with 4 GPUs each with the `srun` command.
+All 5 machines run the script with the `slurm_within_kmeans_server` option.
+They determine the number of servers and their own server id via the `SLURM_NPROCS` and `SLURM_PROCID` environment variables.
+
+All machines start `distributed_kmeans.py` in server mode for the slice of the dataset they are responsible for.
+
+In addition, the machine #0 also starts the client.
+The client knows who are the other servers via the variable `SLURM_JOB_NODELIST`.
+It connects to all clients and performs the clustering.
+
+The output should look like [this gist](https://gist.github.com/mdouze/8d25e89fb4af5093057cae0f917da6cd).
+
+### Run used for deep1B
+
+For the real run, we run the clustering on 50M vectors to 1M centroids.
+This is just a matter of using as many machines / GPUs as possible in setting the output centroids with the `--out filename` option.
+Then run
+```bash
+bash run_on_cluster.bash deep1b_clustering
+```
+
+The last lines of output read like:
+```bash
+ Iteration 19 (898.92 s, search 875.71 s): objective=1.33601e+07 imbalance=1.303 nsplit=0
+ 0: writing centroids to /checkpoint/matthijs/ondisk_distributed/1M_centroids.npy
+```
+
+This means that the total training time was 899s, of which 876s were used for computation.
+However, the computation includes the I/O overhead to the assignment servers.
+In this implementation, the overhead of transmitting the data is non-negligible and so is the centroid computation stage.
+This is due to the inefficient Python implementation and the RPC protocol that is not optimized for broadcast / gather (like MPI).
+However, it is a simple implementation that should run on most clusters.
+
+## Making the trained index
+
+After the centroids are obtained, an empty trained index must be constructed.
+This is done by:
+
+- applying a pre-processing stage (a random rotation) to balance the dimensions of the vectors. This can be done after clustering, the clusters are just rotated as well.
+
+- wrapping the centroids into a HNSW index to speed up the CPU-based assignment of vectors
+
+- training the 6-bit scalar quantizer used to encode the vectors
+
+This is performed by the script [`make_trained_index.py`](make_trained_index.py).
+
+## Building the index by slices
+
+We call the slices "vslices" as they are vertical slices of the big matrix, see explanation in the wiki section [Split across database partitions](https://github.com/facebookresearch/faiss/wiki/Indexing-1T-vectors#split-across-database-partitions).
+
+The script [make_index_vslice.py](make_index_vslice.py) makes an index for a subset of the vectors of the input data and stores it as an independent index.
+There are 200 slices of 5M vectors each for Deep1B.
+It can be run in a brute-force parallel fashion, there is no constraint on ordering.
+To run the script in parallel on a slurm cluster, use:
+```bash
+bash run_on_cluster.bash make_index_vslices
+```
+For a real dataset, the data would be read from a DBMS.
+In that case, reading the data and indexing it in parallel is worthwhile because reading is very slow.
+
+## Splitting across inverted lists
+
+The 200 slices need to be merged together.
+This is done with the script [merge_to_ondisk.py](merge_to_ondisk.py), that memory maps the 200 vertical slice indexes, extracts a subset of the inverted lists and writes them to a contiguous horizontal slice.
+We slice the inverted lists into 50 horizontal slices.
+This is run with
+```bash
+bash run_on_cluster.bash make_index_hslices
+```
+
+## Querying the index
+
+At this point the index is ready.
+The horizontal slices need to be loaded in the right order and combined into an index to be usable.
+This is done in the [combined_index.py](combined_index.py) script.
+It provides a `CombinedIndexDeep1B` object that contains an index object that can be searched.
+To test, run:
+```bash
+python combined_index.py
+```
+The output should look like:
+```bash
+(faiss_1.5.2) matthijs@devfair0144:~/faiss_versions/faiss_1Tcode/faiss/benchs/distributed_ondisk$ python combined_index.py
+reading /checkpoint/matthijs/ondisk_distributed//hslices/slice49.faissindex
+loading empty index /checkpoint/matthijs/ondisk_distributed/trained.faissindex
+replace invlists
+loaded index of size 1000000000
+nprobe=1 1-recall@1=0.2904 t=12.35s
+nnprobe=10 1-recall@1=0.6499 t=17.67s
+nprobe=100 1-recall@1=0.8673 t=29.23s
+nprobe=1000 1-recall@1=0.9132 t=129.58s
+```
+ie. searching is a lot slower than from RAM.
+
+## Distributed query
+
+To reduce the bandwidth required from the machine that does the queries, it is possible to split the search across several search servers.
+This way, only the effective results are returned to the main machine.
+
+The search client and server are implemented in [`search_server.py`](search_server.py).
+It can be used as a script to start a search server for `CombinedIndexDeep1B` or as a module to load the clients.
+
+The search servers can be started with
+```bash
+bash run_on_cluster.bash run_search_servers
+```
+(adjust to the number of servers that can be used).
+
+Then an example of search client is [`distributed_query_demo.py`](distributed_query_demo.py).
+It connects to the servers and assigns subsets of inverted lists to visit to each of them.
+
+A typical output is [this gist](https://gist.github.com/mdouze/1585b9854a9a2437d71f2b2c3c05c7c5).
+The number in MiB indicates the amount of data that is read from disk to perform the search.
+In this case, the scale of the dataset is too small for the distributed search to have much impact, but on datasets > 10x larger, the difference becomes more significant.
+
+## Conclusion
+
+This code contains the core components to make an index that scales up to 1T vectors.
+There are a few simplifications wrt. the index that was effectively used in [Indexing 1T vectors](https://github.com/facebookresearch/faiss/wiki/Indexing-1T-vectors).
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/combined_index.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/combined_index.py
new file mode 100755
index 0000000..bc12cb6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/combined_index.py
@@ -0,0 +1,193 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import faiss
+import numpy as np
+
+
+class CombinedIndex:
+ """
+ combines a set of inverted lists into a hstack
+ masks part of those lists
+ adds these inverted lists to an empty index that contains
+ the info on how to perform searches
+ """
+
+ def __init__(self, invlist_fnames, empty_index_fname,
+ masked_index_fname=None):
+
+ self.indexes = indexes = []
+ ilv = faiss.InvertedListsPtrVector()
+
+ for fname in invlist_fnames:
+ if os.path.exists(fname):
+ print('reading', fname, end='\r', flush=True)
+ index = faiss.read_index(fname)
+ indexes.append(index)
+ il = faiss.extract_index_ivf(index).invlists
+ else:
+ raise AssertionError
+ ilv.push_back(il)
+ print()
+
+ self.big_il = faiss.VStackInvertedLists(ilv.size(), ilv.data())
+ if masked_index_fname:
+ self.big_il_base = self.big_il
+ print('loading', masked_index_fname)
+ self.masked_index = faiss.read_index(
+ masked_index_fname,
+ faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY)
+ self.big_il = faiss.MaskedInvertedLists(
+ faiss.extract_index_ivf(self.masked_index).invlists,
+ self.big_il_base)
+
+ print('loading empty index', empty_index_fname)
+ self.index = faiss.read_index(empty_index_fname)
+ ntotal = self.big_il.compute_ntotal()
+
+ print('replace invlists')
+ index_ivf = faiss.extract_index_ivf(self.index)
+ index_ivf.replace_invlists(self.big_il, False)
+ index_ivf.ntotal = self.index.ntotal = ntotal
+ index_ivf.parallel_mode = 1 # seems reasonable to do this all the time
+
+ quantizer = faiss.downcast_index(index_ivf.quantizer)
+ quantizer.hnsw.efSearch = 1024
+
+ ############################################################
+ # Expose fields and functions of the index as methods so that they
+ # can be called by RPC
+
+ def search(self, x, k):
+ return self.index.search(x, k)
+
+ def range_search(self, x, radius):
+ return self.index.range_search(x, radius)
+
+ def transform_and_assign(self, xq):
+ index = self.index
+
+ if isinstance(index, faiss.IndexPreTransform):
+ assert index.chain.size() == 1
+ vt = index.chain.at(0)
+ xq = vt.apply_py(xq)
+
+ # perform quantization
+ index_ivf = faiss.extract_index_ivf(index)
+ quantizer = index_ivf.quantizer
+ coarse_dis, list_nos = quantizer.search(xq, index_ivf.nprobe)
+ return xq, list_nos, coarse_dis
+
+
+ def ivf_search_preassigned(self, xq, list_nos, coarse_dis, k):
+ index_ivf = faiss.extract_index_ivf(self.index)
+ n, d = xq.shape
+ assert d == index_ivf.d
+ n2, d2 = list_nos.shape
+ assert list_nos.shape == coarse_dis.shape
+ assert n2 == n
+ assert d2 == index_ivf.nprobe
+ D = np.empty((n, k), dtype='float32')
+ I = np.empty((n, k), dtype='int64')
+ index_ivf.search_preassigned(
+ n, faiss.swig_ptr(xq), k,
+ faiss.swig_ptr(list_nos), faiss.swig_ptr(coarse_dis),
+ faiss.swig_ptr(D), faiss.swig_ptr(I), False)
+ return D, I
+
+
+ def ivf_range_search_preassigned(self, xq, list_nos, coarse_dis, radius):
+ index_ivf = faiss.extract_index_ivf(self.index)
+ n, d = xq.shape
+ assert d == index_ivf.d
+ n2, d2 = list_nos.shape
+ assert list_nos.shape == coarse_dis.shape
+ assert n2 == n
+ assert d2 == index_ivf.nprobe
+ res = faiss.RangeSearchResult(n)
+
+ index_ivf.range_search_preassigned(
+ n, faiss.swig_ptr(xq), radius,
+ faiss.swig_ptr(list_nos), faiss.swig_ptr(coarse_dis),
+ res)
+
+ lims = faiss.rev_swig_ptr(res.lims, n + 1).copy()
+ nd = int(lims[-1])
+ D = faiss.rev_swig_ptr(res.distances, nd).copy()
+ I = faiss.rev_swig_ptr(res.labels, nd).copy()
+ return lims, D, I
+
+ def set_nprobe(self, nprobe):
+ index_ivf = faiss.extract_index_ivf(self.index)
+ index_ivf.nprobe = nprobe
+
+ def set_parallel_mode(self, pm):
+ index_ivf = faiss.extract_index_ivf(self.index)
+ index_ivf.parallel_mode = pm
+
+ def get_ntotal(self):
+ return self.index.ntotal
+
+ def set_prefetch_nthread(self, nt):
+ for idx in self.indexes:
+ il = faiss.downcast_InvertedLists(
+ faiss.extract_index_ivf(idx).invlists)
+ il.prefetch_nthread
+ il.prefetch_nthread = nt
+
+ def set_omp_num_threads(self, nt):
+ faiss.omp_set_num_threads(nt)
+
+class CombinedIndexDeep1B(CombinedIndex):
+ """ loads a CombinedIndex with the data from the big photodna index """
+
+ def __init__(self):
+ # set some paths
+ workdir = "/checkpoint/matthijs/ondisk_distributed/"
+
+ # empty index with the proper quantizer
+ indexfname = workdir + 'trained.faissindex'
+
+ # index that has some invlists that override the big one
+ masked_index_fname = None
+ invlist_fnames = [
+ '%s/hslices/slice%d.faissindex' % (workdir, i)
+ for i in range(50)
+ ]
+ CombinedIndex.__init__(self, invlist_fnames, indexfname, masked_index_fname)
+
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype='int32')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+if __name__ == '__main__':
+ import time
+ ci = CombinedIndexDeep1B()
+ print('loaded index of size ', ci.index.ntotal)
+
+ deep1bdir = "/datasets01_101/simsearch/041218/deep1b/"
+
+ xq = fvecs_read(deep1bdir + "deep1B_queries.fvecs")
+ gt_fname = deep1bdir + "deep1B_groundtruth.ivecs"
+ gt = ivecs_read(gt_fname)
+
+ for nprobe in 1, 10, 100, 1000:
+ ci.set_nprobe(nprobe)
+ t0 = time.time()
+ D, I = ci.search(xq, 100)
+ t1 = time.time()
+ print('nprobe=%d 1-recall@1=%.4f t=%.2fs' % (
+ nprobe, (I[:, 0] == gt[:, 0]).sum() / len(xq),
+ t1 - t0
+ ))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/distributed_kmeans.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/distributed_kmeans.py
new file mode 100755
index 0000000..c9c47af
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/distributed_kmeans.py
@@ -0,0 +1,239 @@
+#! /usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Simple distributed kmeans implementation Relies on an abstraction
+for the training matrix, that can be sharded over several machines.
+"""
+import os
+import sys
+import argparse
+
+import numpy as np
+
+import faiss
+
+from multiprocessing.pool import ThreadPool
+from faiss.contrib import rpc
+from faiss.contrib.datasets import SyntheticDataset
+from faiss.contrib.vecs_io import bvecs_mmap, fvecs_mmap
+from faiss.contrib.clustering import DatasetAssign, DatasetAssignGPU, kmeans
+
+
+class DatasetAssignDispatch:
+ """dispatches to several other DatasetAssigns and combines the
+ results"""
+
+ def __init__(self, xes, in_parallel):
+ self.xes = xes
+ self.d = xes[0].dim()
+ if not in_parallel:
+ self.imap = map
+ else:
+ self.pool = ThreadPool(len(self.xes))
+ self.imap = self.pool.imap
+ self.sizes = list(map(lambda x: x.count(), self.xes))
+ self.cs = np.cumsum([0] + self.sizes)
+
+ def count(self):
+ return self.cs[-1]
+
+ def dim(self):
+ return self.d
+
+ def get_subset(self, indices):
+ res = np.zeros((len(indices), self.d), dtype='float32')
+ nos = np.searchsorted(self.cs[1:], indices, side='right')
+
+ def handle(i):
+ mask = nos == i
+ sub_indices = indices[mask] - self.cs[i]
+ subset = self.xes[i].get_subset(sub_indices)
+ res[mask] = subset
+
+ list(self.imap(handle, range(len(self.xes))))
+ return res
+
+ def assign_to(self, centroids, weights=None):
+ src = self.imap(
+ lambda x: x.assign_to(centroids, weights),
+ self.xes
+ )
+ I = []
+ D = []
+ sum_per_centroid = None
+ for Ii, Di, sum_per_centroid_i in src:
+ I.append(Ii)
+ D.append(Di)
+ if sum_per_centroid is None:
+ sum_per_centroid = sum_per_centroid_i
+ else:
+ sum_per_centroid += sum_per_centroid_i
+ return np.hstack(I), np.hstack(D), sum_per_centroid
+
+
+class AssignServer(rpc.Server):
+ """ Assign version that can be exposed via RPC """
+
+ def __init__(self, s, assign, log_prefix=''):
+ rpc.Server.__init__(self, s, log_prefix=log_prefix)
+ self.assign = assign
+
+ def __getattr__(self, f):
+ return getattr(self.assign, f)
+
+
+
+
+def do_test(todo):
+
+ testdata = '/datasets01_101/simsearch/041218/bigann/bigann_learn.bvecs'
+
+ if os.path.exists(testdata):
+ x = bvecs_mmap(testdata)
+ else:
+ print("using synthetic dataset")
+ ds = SyntheticDataset(128, 100000, 0, 0)
+ x = ds.get_train()
+
+ # bad distribution to stress-test split code
+ xx = x[:100000].copy()
+ xx[:50000] = x[0]
+
+ todo = sys.argv[1:]
+
+ if "0" in todo:
+ # reference C++ run
+ km = faiss.Kmeans(x.shape[1], 1000, niter=20, verbose=True)
+ km.train(xx.astype('float32'))
+
+ if "1" in todo:
+ # using the Faiss c++ implementation
+ data = DatasetAssign(xx)
+ kmeans(1000, data, 20)
+
+ if "2" in todo:
+ # use the dispatch object (on local datasets)
+ data = DatasetAssignDispatch([
+ DatasetAssign(xx[20000 * i : 20000 * (i + 1)])
+ for i in range(5)
+ ], False
+ )
+ kmeans(1000, data, 20)
+
+ if "3" in todo:
+ # same, with GPU
+ ngpu = faiss.get_num_gpus()
+ print('using %d GPUs' % ngpu)
+ data = DatasetAssignDispatch([
+ DatasetAssignGPU(xx[100000 * i // ngpu: 100000 * (i + 1) // ngpu], i)
+ for i in range(ngpu)
+ ], True
+ )
+ kmeans(1000, data, 20)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+
+ def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+ group = parser.add_argument_group('general options')
+ aa('--test', default='', help='perform tests (comma-separated numbers)')
+
+ aa('--k', default=0, type=int, help='nb centroids')
+ aa('--seed', default=1234, type=int, help='random seed')
+ aa('--niter', default=20, type=int, help='nb iterations')
+ aa('--gpu', default=-2, type=int, help='GPU to use (-2:none, -1: all)')
+
+ group = parser.add_argument_group('I/O options')
+ aa('--indata', default='',
+ help='data file to load (supported formats fvecs, bvecs, npy')
+ aa('--i0', default=0, type=int, help='first vector to keep')
+ aa('--i1', default=-1, type=int, help='last vec to keep + 1')
+ aa('--out', default='', help='file to store centroids')
+ aa('--store_each_iteration', default=False, action='store_true',
+ help='store centroid checkpoints')
+
+ group = parser.add_argument_group('server options')
+ aa('--server', action='store_true', default=False, help='run server')
+ aa('--port', default=12345, type=int, help='server port')
+ aa('--when_ready', default=None, help='store host:port to this file when ready')
+ aa('--ipv4', default=False, action='store_true', help='force ipv4')
+
+ group = parser.add_argument_group('client options')
+ aa('--client', action='store_true', default=False, help='run client')
+ aa('--servers', default='', help='list of server:port separated by spaces')
+
+ args = parser.parse_args()
+
+ if args.test:
+ do_test(args.test.split(','))
+ return
+
+ # prepare data matrix (either local or remote)
+ if args.indata:
+ print('loading ', args.indata)
+ if args.indata.endswith('.bvecs'):
+ x = bvecs_mmap(args.indata)
+ elif args.indata.endswith('.fvecs'):
+ x = fvecs_mmap(args.indata)
+ elif args.indata.endswith('.npy'):
+ x = np.load(args.indata, mmap_mode='r')
+ else:
+ raise AssertionError
+
+ if args.i1 == -1:
+ args.i1 = len(x)
+ x = x[args.i0:args.i1]
+ if args.gpu == -2:
+ data = DatasetAssign(x)
+ else:
+ print('moving to GPU')
+ data = DatasetAssignGPU(x, args.gpu)
+
+ elif args.client:
+ print('connecting to servers')
+
+ def connect_client(hostport):
+ host, port = hostport.split(':')
+ port = int(port)
+ print('connecting %s:%d' % (host, port))
+ client = rpc.Client(host, port, v6=not args.ipv4)
+ print('client %s:%d ready' % (host, port))
+ return client
+
+ hostports = args.servers.strip().split(' ')
+ # pool = ThreadPool(len(hostports))
+
+ data = DatasetAssignDispatch(
+ list(map(connect_client, hostports)),
+ True
+ )
+ else:
+ raise AssertionError
+
+
+ if args.server:
+ print('starting server')
+ log_prefix = f"{rpc.socket.gethostname()}:{args.port}"
+ rpc.run_server(
+ lambda s: AssignServer(s, data, log_prefix=log_prefix),
+ args.port, report_to_file=args.when_ready,
+ v6=not args.ipv4)
+
+ else:
+ print('running kmeans')
+ centroids = kmeans(args.k, data, niter=args.niter, seed=args.seed,
+ checkpoint=args.out if args.store_each_iteration else None)
+ if args.out != '':
+ print('writing centroids to', args.out)
+ np.save(args.out, centroids)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/distributed_query_demo.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/distributed_query_demo.py
new file mode 100644
index 0000000..91b0349
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/distributed_query_demo.py
@@ -0,0 +1,70 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import faiss
+import numpy as np
+import time
+import rpc
+import sys
+
+import combined_index
+import search_server
+
+hostnames = sys.argv[1:]
+
+print("Load local index")
+ci = combined_index.CombinedIndexDeep1B()
+
+print("connect to clients")
+clients = []
+for host in hostnames:
+ client = rpc.Client(host, 12012, v6=False)
+ clients.append(client)
+
+# check if all servers respond
+print("sizes seen by servers:", [cl.get_ntotal() for cl in clients])
+
+
+# aggregate all clients into a one that uses them all for speed
+# note that it also requires a local index ci
+sindex = search_server.SplitPerListIndex(ci, clients)
+sindex.verbose = True
+
+# set reasonable parameters
+ci.set_parallel_mode(1)
+ci.set_prefetch_nthread(0)
+ci.set_omp_num_threads(64)
+
+# initialize params
+sindex.set_parallel_mode(1)
+sindex.set_prefetch_nthread(0)
+sindex.set_omp_num_threads(64)
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype='int32')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+deep1bdir = "/datasets01_101/simsearch/041218/deep1b/"
+
+xq = fvecs_read(deep1bdir + "deep1B_queries.fvecs")
+gt_fname = deep1bdir + "deep1B_groundtruth.ivecs"
+gt = ivecs_read(gt_fname)
+
+
+for nprobe in 1, 10, 100, 1000:
+ sindex.set_nprobe(nprobe)
+ t0 = time.time()
+ D, I = sindex.search(xq, 100)
+ t1 = time.time()
+ print('nprobe=%d 1-recall@1=%.4f t=%.2fs' % (
+ nprobe, (I[:, 0] == gt[:, 0]).sum() / len(xq),
+ t1 - t0
+ ))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/make_index_vslice.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/make_index_vslice.py
new file mode 100644
index 0000000..f7f80b2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/make_index_vslice.py
@@ -0,0 +1,117 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import time
+import numpy as np
+import faiss
+import argparse
+from multiprocessing.pool import ThreadPool
+
+def ivecs_mmap(fname):
+ a = np.memmap(fname, dtype='int32', mode='r')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:]
+
+def fvecs_mmap(fname):
+ return ivecs_mmap(fname).view('float32')
+
+
+def produce_batches(args):
+
+ x = fvecs_mmap(args.input)
+
+ if args.i1 == -1:
+ args.i1 = len(x)
+
+ print("Iterating on vectors %d:%d from %s by batches of size %d" % (
+ args.i0, args.i1, args.input, args.bs))
+
+ for j0 in range(args.i0, args.i1, args.bs):
+ j1 = min(j0 + args.bs, args.i1)
+ yield np.arange(j0, j1), x[j0:j1]
+
+
+def rate_limited_iter(l):
+ 'a thread pre-processes the next element'
+ pool = ThreadPool(1)
+ res = None
+
+ def next_or_None():
+ try:
+ return next(l)
+ except StopIteration:
+ return None
+
+ while True:
+ res_next = pool.apply_async(next_or_None)
+ if res is not None:
+ res = res.get()
+ if res is None:
+ return
+ yield res
+ res = res_next
+
+deep1bdir = "/datasets01_101/simsearch/041218/deep1b/"
+workdir = "/checkpoint/matthijs/ondisk_distributed/"
+
+def main():
+ parser = argparse.ArgumentParser(
+ description='make index for a subset of the data')
+
+ def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+ group = parser.add_argument_group('index type')
+ aa('--inputindex',
+ default=workdir + 'trained.faissindex',
+ help='empty input index to fill in')
+ aa('--nt', default=-1, type=int, help='nb of openmp threads to use')
+
+ group = parser.add_argument_group('db options')
+ aa('--input', default=deep1bdir + "base.fvecs")
+ aa('--bs', default=2**18, type=int,
+ help='batch size for db access')
+ aa('--i0', default=0, type=int, help='lower bound to index')
+ aa('--i1', default=-1, type=int, help='upper bound of vectors to index')
+
+ group = parser.add_argument_group('output')
+ aa('-o', default='/tmp/x', help='output index')
+ aa('--keepquantizer', default=False, action='store_true',
+ help='by default we remove the data from the quantizer to save space')
+
+ args = parser.parse_args()
+ print('args=', args)
+
+ print('start accessing data')
+ src = produce_batches(args)
+
+ print('loading index', args.inputindex)
+ index = faiss.read_index(args.inputindex)
+
+ if args.nt != -1:
+ faiss.omp_set_num_threads(args.nt)
+
+ t0 = time.time()
+ ntot = 0
+ for ids, x in rate_limited_iter(src):
+ print('add %d:%d (%.3f s)' % (ntot, ntot + ids.size, time.time() - t0))
+ index.add_with_ids(np.ascontiguousarray(x, dtype='float32'), ids)
+ ntot += ids.size
+
+ index_ivf = faiss.extract_index_ivf(index)
+ print('invlists stats: imbalance %.3f' % index_ivf.invlists.imbalance_factor())
+ index_ivf.invlists.print_stats()
+
+ if not args.keepquantizer:
+ print('resetting quantizer content')
+ index_ivf = faiss.extract_index_ivf(index)
+ index_ivf.quantizer.reset()
+
+ print('store output', args.o)
+ faiss.write_index(index, args.o)
+
+if __name__ == '__main__':
+ main()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/make_trained_index.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/make_trained_index.py
new file mode 100644
index 0000000..843f067
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/make_trained_index.py
@@ -0,0 +1,52 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import faiss
+
+deep1bdir = "/datasets01_101/simsearch/041218/deep1b/"
+workdir = "/checkpoint/matthijs/ondisk_distributed/"
+
+
+print('Load centroids')
+centroids = np.load(workdir + '1M_centroids.npy')
+ncent, d = centroids.shape
+
+
+print('apply random rotation')
+rrot = faiss.RandomRotationMatrix(d, d)
+rrot.init(1234)
+centroids = rrot.apply_py(centroids)
+
+print('make HNSW index as quantizer')
+quantizer = faiss.IndexHNSWFlat(d, 32)
+quantizer.hnsw.efSearch = 1024
+quantizer.hnsw.efConstruction = 200
+quantizer.add(centroids)
+
+print('build index')
+index = faiss.IndexPreTransform(
+ rrot,
+ faiss.IndexIVFScalarQuantizer(
+ quantizer, d, ncent, faiss.ScalarQuantizer.QT_6bit
+ )
+ )
+
+def ivecs_mmap(fname):
+ a = np.memmap(fname, dtype='int32', mode='r')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:]
+
+def fvecs_mmap(fname):
+ return ivecs_mmap(fname).view('float32')
+
+
+print('finish training index')
+xt = fvecs_mmap(deep1bdir + 'learn.fvecs')
+xt = np.ascontiguousarray(xt[:256 * 1000], dtype='float32')
+index.train(xt)
+
+print('write output')
+faiss.write_index(index, workdir + 'trained.faissindex')
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/merge_to_ondisk.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/merge_to_ondisk.py
new file mode 100644
index 0000000..59ca269
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/merge_to_ondisk.py
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import faiss
+import argparse
+from multiprocessing.pool import ThreadPool
+
+if __name__ == '__main__':
+
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--inputs', nargs='*', required=True,
+ help='input indexes to merge')
+ parser.add_argument('--l0', type=int, default=0)
+ parser.add_argument('--l1', type=int, default=-1)
+
+ parser.add_argument('--nt', default=-1,
+ help='nb threads')
+
+ parser.add_argument('--output', required=True,
+ help='output index filename')
+ parser.add_argument('--outputIL',
+ help='output invfile filename')
+
+ args = parser.parse_args()
+
+ if args.nt != -1:
+ print('set nb of threads to', args.nt)
+
+
+ ils = faiss.InvertedListsPtrVector()
+ ils_dont_dealloc = []
+
+ pool = ThreadPool(20)
+
+ def load_index(fname):
+ print("loading", fname)
+ try:
+ index = faiss.read_index(fname, faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY)
+ except RuntimeError as e:
+ print('could not load %s: %s' % (fname, e))
+ return fname, None
+
+ print(" %d entries" % index.ntotal)
+ return fname, index
+
+ index0 = None
+
+ for _, index in pool.imap(load_index, args.inputs):
+ if index is None:
+ continue
+ index_ivf = faiss.extract_index_ivf(index)
+ il = faiss.downcast_InvertedLists(index_ivf.invlists)
+ index_ivf.invlists = None
+ il.this.own()
+ ils_dont_dealloc.append(il)
+ if (args.l0, args.l1) != (0, -1):
+ print('restricting to lists %d:%d' % (args.l0, args.l1))
+ # il = faiss.SliceInvertedLists(il, args.l0, args.l1)
+
+ il.crop_invlists(args.l0, args.l1)
+ ils_dont_dealloc.append(il)
+ ils.push_back(il)
+
+ if index0 is None:
+ index0 = index
+
+ print("loaded %d invlists" % ils.size())
+
+ if not args.outputIL:
+ args.outputIL = args.output + '_invlists'
+
+ il0 = ils.at(0)
+
+ il = faiss.OnDiskInvertedLists(
+ il0.nlist, il0.code_size,
+ args.outputIL)
+
+ print("perform merge")
+
+ ntotal = il.merge_from(ils.data(), ils.size(), True)
+
+ print("swap into index0")
+
+ index0_ivf = faiss.extract_index_ivf(index0)
+ index0_ivf.nlist = il0.nlist
+ index0_ivf.ntotal = index0.ntotal = ntotal
+ index0_ivf.invlists = il
+ index0_ivf.own_invlists = False
+
+ print("write", args.output)
+
+ faiss.write_index(index0, args.output)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/run_on_cluster.bash b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/run_on_cluster.bash
new file mode 100755
index 0000000..886fdcb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/run_on_cluster.bash
@@ -0,0 +1,263 @@
+#! /bin/bash
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+set -e
+
+todo=$1
+# other options can be transmitted
+shift
+
+# the training data of the Deep1B dataset
+deep1bdir=/datasets01_101/simsearch/041218/deep1b
+traindata=$deep1bdir/learn.fvecs
+
+# this is for small tests
+nvec=1000000
+k=4000
+
+# for the real run
+# nvec=50000000
+# k=1000000
+
+# working directory for the real run
+workdir=/checkpoint/matthijs/ondisk_distributed
+mkdir -p $workdir/{vslices,hslices}
+
+if [ -z "$todo" ]; then
+ echo "nothing to do"
+ exit 1
+elif [ $todo == test_kmeans_0 ]; then
+ # non distributed baseline
+ python distributed_kmeans.py \
+ --indata $traindata --i1 $nvec \
+ --k $k
+
+elif [ $todo == test_kmeans_1 ]; then
+ # using all the machine's GPUs
+ python distributed_kmeans.py \
+ --indata $traindata --i1 $nvec \
+ --k $k --gpu -1
+
+elif [ $todo == test_kmeans_2 ]; then
+ # distrbuted run, with one local server per GPU
+ ngpu=$( echo /dev/nvidia? | wc -w )
+ baseport=12012
+
+ # kill background porcesses on output of this script
+ trap 'kill -HUP 0' 0
+
+ hostports=''
+
+ for((gpu=0;gpu<ngpu;gpu++)); do
+ # range of vectors to assign to each sever
+ i0=$((nvec * gpu / ngpu))
+ i1=$((nvec * (gpu + 1) / ngpu))
+ port=$(( baseport + gpu ))
+
+ echo "start server $gpu for range $i0:$i1"
+
+ python distributed_kmeans.py \
+ --indata $traindata \
+ --i0 $i0 --i1 $i1 \
+ --server --gpu $gpu \
+ --port $port --ipv4 &
+
+ hostports="$hostports localhost:$port"
+ done
+
+ # lame way of making sure all servers are running
+ sleep 5s
+
+ python distributed_kmeans.py \
+ --client --servers "$hostports" \
+ --k $k --ipv4
+
+elif [ $todo == slurm_distributed_kmeans ]; then
+
+ nserv=5
+
+ srun -n$nserv \
+ --time=48:00:00 \
+ --cpus-per-task=40 --gres=gpu:4 --mem=100G \
+ --partition=priority --comment='priority is the only one that works' \
+ -l bash $( realpath $0 ) slurm_within_kmeans_server
+
+elif [ $todo == slurm_within_kmeans_server ]; then
+
+ nserv=$SLURM_NPROCS
+ [ ! -z "$nserv" ] || (echo "should be run by slurm"; exit 1)
+ rank=$SLURM_PROCID
+
+ baseport=12012
+
+ i0=$((nvec * rank / nserv))
+ i1=$((nvec * (rank + 1) / nserv))
+ port=$(( baseport + rank ))
+
+ echo "host $(hostname) start server $rank for range $i0:$i1 port $port"
+
+ if [ $rank != 0 ]; then
+
+ python -u distributed_kmeans.py \
+ --indata $traindata \
+ --i0 $i0 --i1 $i1 \
+ --server --gpu -1 \
+ --port $port --ipv4
+ else
+ # master process
+
+ # kill background processes on output of this script
+ trap 'kill -HUP 0' 0
+
+ python -u distributed_kmeans.py \
+ --indata $traindata \
+ --i0 $i0 --i1 $i1 \
+ --server --gpu -1 \
+ --port $port --ipv4 &
+
+ # Slurm has a somewhat convoluted way of specifying the nodes
+ # assigned to each task. This is to parse the SLURM_TASKS_PER_NODE variable
+ function parse_tasks_per_node () {
+ local blocks=$1
+ for block in ${blocks//,/ }; do
+ if [ ${block/x/} != $block ]; then
+ tpn="${block%(*}"
+ repeat=${block#*x}
+ repeat=${repeat%?}
+ for((i=0;i<repeat;i++)); do
+ echo $tpn
+ done
+ else
+ echo $block
+ fi
+ done
+ }
+
+ hostports=""
+ port=$baseport
+ echo VARS $SLURM_TASKS_PER_NODE $SLURM_JOB_NODELIST
+ tasks_per_node=( $( parse_tasks_per_node $SLURM_TASKS_PER_NODE ) )
+ nodes=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
+ n=${#nodes[*]}
+ for((i=0;i<n;i++)); do
+ hostname=${nodes[i]}
+ for((j=0;j<tasks_per_node[i];j++)); do
+ hostports="$hostports $hostname:$port"
+ ((port++))
+ done
+ done
+
+ echo HOSTPORTS $hostports
+
+ sleep 20s
+
+ # run client
+ python distributed_kmeans.py \
+ --client --servers "$hostports" \
+ --k $k --ipv4 "$@"
+
+ echo "Done, kill the job"
+ scancel $SLURM_JOBID
+
+ fi
+
+elif [ $todo == deep1b_clustering ]; then
+ # also set nvec=500M and k=10M in the top of the file
+ nserv=20
+
+ srun -n$nserv \
+ --time=48:00:00 \
+ --cpus-per-task=40 --gres=gpu:4 --mem=100G \
+ --partition=priority --comment='priority is the only one that works' \
+ -l bash $( realpath $0 ) slurm_within_kmeans_server \
+ --out $workdir/1M_centroids.npy
+
+elif [ $todo == make_index_vslices ]; then
+
+ # vslice: slice per database shards
+
+ nvec=1000000000
+ nslice=200
+
+ for((i=0;i<nslice;i++)); do
+ i0=$((nvec * i / nslice))
+ i1=$((nvec * (i + 1) / nslice))
+
+ # make the script to be run by sbatch
+ cat > $workdir/vslices/slice$i.bash <<EOF
+#!/bin/bash
+
+srun python -u make_index_vslice.py \
+ --inputindex $workdir/trained.faissindex \
+ --input $deep1bdir/base.fvecs \
+ --nt 40 \
+ --i0 $i0 --i1 $i1 \
+ -o $workdir/vslices/slice$i.faissindex
+
+EOF
+ # specify resources for script and run it
+ sbatch -n1 \
+ --time=48:00:00 \
+ --cpus-per-task=40 --gres=gpu:0 --mem=200G \
+ --output=$workdir/vslices/slice$i.log \
+ --job-name=vslice$i.c \
+ $workdir/vslices/slice$i.bash
+ echo "logs in $workdir/vslices/slice$i.log"
+
+ done
+
+elif [ $todo == make_index_hslices ]; then
+
+ # hslice: slice per inverted lists
+
+ nlist=1000000
+ nslice=50
+
+ for((i=0;i<nslice;i++)); do
+ i0=$((nlist * i / nslice))
+ i1=$((nlist * (i + 1) / nslice))
+
+ # make the script to be run by sbatch
+ cat > $workdir/hslices/slice$i.bash <<EOF
+#!/bin/bash
+
+srun python -u merge_to_ondisk.py \
+ --input $workdir/vslices/slice{0..199}.faissindex \
+ --nt 20 \
+ --l0 $i0 --l1 $i1 \
+ --output $workdir/hslices/slice$i.faissindex \
+ --outputIL $workdir/hslices/slice$i.invlists
+
+
+EOF
+ # specify resources for script and run it
+ sbatch -n1 \
+ --time=48:00:00 \
+ --cpus-per-task=20 --gres=gpu:0 --mem=200G \
+ --output=$workdir/hslices/slice$i.log \
+ --job-name=hslice$i.a \
+ --constraint=pascal \
+ $workdir/hslices/slice$i.bash
+ echo "logs in $workdir/hslices/slice$i.log"
+
+ done
+
+elif [ $todo == run_search_servers ]; then
+
+ nserv=3
+
+ srun -n$nserv \
+ --time=48:00:00 \
+ --cpus-per-task=64 --gres=gpu:0 --mem=100G \
+ --constraint=pascal \
+ --partition=priority --comment='priority is the only one that works' \
+ -l python -u search_server.py --port 12012
+
+
+else
+ echo "unknown todo $todo"
+ exit 1
+fi
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/search_server.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/search_server.py
new file mode 100644
index 0000000..ac01f0b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/distributed_ondisk/search_server.py
@@ -0,0 +1,222 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+
+from faiss.contrib import rpc
+
+import combined_index
+import argparse
+
+
+
+############################################################
+# Server implementation
+############################################################
+
+
+class MyServer(rpc.Server):
+ """ Assign version that can be exposed via RPC """
+ def __init__(self, s, index):
+ rpc.Server.__init__(self, s)
+ self.index = index
+
+ def __getattr__(self, f):
+ return getattr(self.index, f)
+
+def main():
+ parser = argparse.ArgumentParser()
+
+ def aa(*args, **kwargs):
+ group.add_argument(*args, **kwargs)
+
+ group = parser.add_argument_group('server options')
+ aa('--port', default=12012, type=int, help='server port')
+ aa('--when_ready_dir', default=None,
+ help='store host:port to this file when ready')
+ aa('--ipv4', default=False, action='store_true', help='force ipv4')
+ aa('--rank', default=0, type=int,
+ help='rank used as index in the client table')
+
+ args = parser.parse_args()
+
+ when_ready = None
+ if args.when_ready_dir:
+ when_ready = '%s/%d' % (args.when_ready_dir, args.rank)
+
+ print('loading index')
+
+ index = combined_index.CombinedIndexDeep1B()
+
+ print('starting server')
+ rpc.run_server(
+ lambda s: MyServer(s, index),
+ args.port, report_to_file=when_ready,
+ v6=not args.ipv4)
+
+if __name__ == '__main__':
+ main()
+
+
+############################################################
+# Client implementation
+############################################################
+
+from multiprocessing.pool import ThreadPool
+import faiss
+import numpy as np
+
+
+
+class ResultHeap:
+ """ Combine query results from a sliced dataset (for k-nn search) """
+
+ def __init__(self, nq, k):
+ " nq: number of query vectors, k: number of results per query "
+ self.I = np.zeros((nq, k), dtype='int64')
+ self.D = np.zeros((nq, k), dtype='float32')
+ self.nq, self.k = nq, k
+ heaps = faiss.float_maxheap_array_t()
+ heaps.k = k
+ heaps.nh = nq
+ heaps.val = faiss.swig_ptr(self.D)
+ heaps.ids = faiss.swig_ptr(self.I)
+ heaps.heapify()
+ self.heaps = heaps
+
+ def add_batch_result(self, D, I, i0):
+ assert D.shape == (self.nq, self.k)
+ assert I.shape == (self.nq, self.k)
+ I += i0
+ self.heaps.addn_with_ids(
+ self.k, faiss.swig_ptr(D),
+ faiss.swig_ptr(I), self.k)
+
+ def finalize(self):
+ self.heaps.reorder()
+
+def distribute_weights(weights, nbin):
+ """ assign a set of weights to a smaller set of bins to balance them """
+ nw = weights.size
+ o = weights.argsort()
+ bins = np.zeros(nbin)
+ assign = np.ones(nw, dtype=int)
+ for i in o[::-1]:
+ b = bins.argmin()
+ assign[i] = b
+ bins[b] += weights[i]
+ return bins, assign
+
+
+
+class SplitPerListIndex:
+ """manages a local index, that does the coarse quantization and a set
+ of sub_indexes. The sub_indexes search a subset of the inverted
+ lists. The SplitPerListIndex merges results from the sub-indexes"""
+
+ def __init__(self, index, sub_indexes):
+ self.index = index
+ self.code_size = faiss.extract_index_ivf(index.index).code_size
+ self.sub_indexes = sub_indexes
+ self.ni = len(self.sub_indexes)
+ # pool of threads. Each thread manages one sub-index.
+ self.pool = ThreadPool(self.ni)
+ self.verbose = False
+
+ def set_nprobe(self, nprobe):
+ self.index.set_nprobe(nprobe)
+ self.pool.map(
+ lambda i: self.sub_indexes[i].set_nprobe(nprobe),
+ range(self.ni)
+ )
+
+ def set_omp_num_threads(self, nt):
+ faiss.omp_set_num_threads(nt)
+ self.pool.map(
+ lambda idx: idx.set_omp_num_threads(nt),
+ self.sub_indexes
+ )
+
+ def set_parallel_mode(self, pm):
+ self.index.set_parallel_mode(pm)
+ self.pool.map(
+ lambda idx: idx.set_parallel_mode(pm),
+ self.sub_indexes
+ )
+
+ def set_prefetch_nthread(self, nt):
+ self.index.set_prefetch_nthread(nt)
+ self.pool.map(
+ lambda idx: idx.set_prefetch_nthread(nt),
+ self.sub_indexes
+ )
+
+ def balance_lists(self, list_nos):
+ big_il = self.index.big_il
+ weights = np.array([big_il.list_size(int(i))
+ for i in list_nos.ravel()])
+ bins, assign = distribute_weights(weights, self.ni)
+ if self.verbose:
+ print('bins weight range %d:%d total %d (%.2f MiB)' % (
+ bins.min(), bins.max(), bins.sum(),
+ bins.sum() * (self.code_size + 8) / 2 ** 20))
+ self.nscan = bins.sum()
+ return assign.reshape(list_nos.shape)
+
+ def search(self, x, k):
+ xqo, list_nos, coarse_dis = self.index.transform_and_assign(x)
+ assign = self.balance_lists(list_nos)
+
+ def do_query(i):
+ sub_index = self.sub_indexes[i]
+ list_nos_i = list_nos.copy()
+ list_nos_i[assign != i] = -1
+ t0 = time.time()
+ Di, Ii = sub_index.ivf_search_preassigned(
+ xqo, list_nos_i, coarse_dis, k)
+ #print(list_nos_i, Ii)
+ if self.verbose:
+ print('client %d: %.3f s' % (i, time.time() - t0))
+ return Di, Ii
+
+ rh = ResultHeap(x.shape[0], k)
+
+ for Di, Ii in self.pool.imap(do_query, range(self.ni)):
+ #print("ADD", Ii, rh.I)
+ rh.add_batch_result(Di, Ii, 0)
+ rh.finalize()
+ return rh.D, rh.I
+
+ def range_search(self, x, radius):
+ xqo, list_nos, coarse_dis = self.index.transform_and_assign(x)
+ assign = self.balance_lists(list_nos)
+ nq = len(x)
+
+ def do_query(i):
+ sub_index = self.sub_indexes[i]
+ list_nos_i = list_nos.copy()
+ list_nos_i[assign != i] = -1
+ t0 = time.time()
+ limi, Di, Ii = sub_index.ivf_range_search_preassigned(
+ xqo, list_nos_i, coarse_dis, radius)
+ if self.verbose:
+ print('slice %d: %.3f s' % (i, time.time() - t0))
+ return limi, Di, Ii
+
+ D = [[] for i in range(nq)]
+ I = [[] for i in range(nq)]
+
+ sizes = np.zeros(nq, dtype=int)
+ for lims, Di, Ii in self.pool.imap(do_query, range(self.ni)):
+ for i in range(nq):
+ l0, l1 = lims[i:i + 2]
+ D[i].append(Di[l0:l1])
+ I[i].append(Ii[l0:l1])
+ sizes[i] += l1 - l0
+ lims = np.zeros(nq + 1, dtype=int)
+ lims[1:] = np.cumsum(sizes)
+ D = np.hstack([j for i in D for j in i])
+ I = np.hstack([j for i in I for j in i])
+ return lims, D, I
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/kmeans_mnist.py b/packages/leann-backend-hnsw/third_party/faiss/benchs/kmeans_mnist.py
new file mode 100644
index 0000000..adf62e2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/kmeans_mnist.py
@@ -0,0 +1,88 @@
+#! /usr/bin/env python2
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import numpy as np
+import time
+import faiss
+import sys
+
+
+# Get command-line arguments
+
+k = int(sys.argv[1])
+ngpu = int(sys.argv[2])
+
+# Load Leon's file format
+
+def load_mnist(fname):
+ print("load", fname)
+ f = open(fname)
+
+ header = np.fromfile(f, dtype='int8', count=4*4)
+ header = header.reshape(4, 4)[:, ::-1].copy().view('int32')
+ print(header)
+ nim, xd, yd = [int(x) for x in header[1:]]
+
+ data = np.fromfile(f, count=nim * xd * yd,
+ dtype='uint8')
+
+ print(data.shape, nim, xd, yd)
+ data = data.reshape(nim, xd, yd)
+ return data
+
+basedir = "/path/to/mnist/data"
+
+x = load_mnist(basedir + 'mnist8m/mnist8m-patterns-idx3-ubyte')
+
+print("reshape")
+
+x = x.reshape(x.shape[0], -1).astype('float32')
+
+
+def train_kmeans(x, k, ngpu):
+ "Runs kmeans on one or several GPUs"
+ d = x.shape[1]
+ clus = faiss.Clustering(d, k)
+ clus.verbose = True
+ clus.niter = 20
+
+ # otherwise the kmeans implementation sub-samples the training set
+ clus.max_points_per_centroid = 10000000
+
+ res = [faiss.StandardGpuResources() for i in range(ngpu)]
+
+ flat_config = []
+ for i in range(ngpu):
+ cfg = faiss.GpuIndexFlatConfig()
+ cfg.useFloat16 = False
+ cfg.device = i
+ flat_config.append(cfg)
+
+ if ngpu == 1:
+ index = faiss.GpuIndexFlatL2(res[0], d, flat_config[0])
+ else:
+ indexes = [faiss.GpuIndexFlatL2(res[i], d, flat_config[i])
+ for i in range(ngpu)]
+ index = faiss.IndexReplicas()
+ for sub_index in indexes:
+ index.addIndex(sub_index)
+
+ # perform the training
+ clus.train(x, index)
+ centroids = faiss.vector_float_to_array(clus.centroids)
+
+ obj = faiss.vector_float_to_array(clus.obj)
+ print("final objective: %.4g" % obj[-1])
+
+ return centroids.reshape(k, d)
+
+print("run")
+t0 = time.time()
+train_kmeans(x, k, ngpu)
+t1 = time.time()
+
+print("total runtime: %.3f s" % (t1 - t0))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/benchs/link_and_code/README.md b/packages/leann-backend-hnsw/third_party/faiss/benchs/link_and_code/README.md
new file mode 100644
index 0000000..0c04cad
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/benchs/link_and_code/README.md
@@ -0,0 +1,25 @@
+
+
+README for the link & code implementation
+=========================================
+
+What is this?
+-------------
+
+Link & code is an indexing method that combines HNSW indexing with
+compression and exploits the neighborhood structure of the similarity
+graph to improve the reconstruction. It is described in
+
+```
+@inproceedings{link_and_code,
+ author = {Matthijs Douze and Alexandre Sablayrolles and Herv\'e J\'egou},
+ title = {Link and code: Fast indexing with graphs and compact regression codes},
+ booktitle = {CVPR},
+ year = {2018}
+}
+```
+
+ArXiV [here](https://arxiv.org/abs/1804.09996)
+
+The necessary code for this paper was removed from Faiss in version 1.8.0.
+For a functioning verinsion, use Faiss 1.7.4.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/AutoTune_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/AutoTune_c.cpp
new file mode 100644
index 0000000..7f683d6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/AutoTune_c.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "AutoTune_c.h"
+#include <faiss/AutoTune.h>
+#include <cstring>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::ParameterRange;
+using faiss::ParameterSpace;
+
+const char* faiss_ParameterRange_name(const FaissParameterRange* range) {
+ return reinterpret_cast<const ParameterRange*>(range)->name.c_str();
+}
+
+void faiss_ParameterRange_values(
+ FaissParameterRange* range,
+ double** p_values,
+ size_t* p_size) {
+ auto& values = reinterpret_cast<ParameterRange*>(range)->values;
+ *p_values = values.data();
+ *p_size = values.size();
+}
+
+int faiss_ParameterSpace_new(FaissParameterSpace** space) {
+ try {
+ auto new_space = new ParameterSpace();
+ *space = reinterpret_cast<FaissParameterSpace*>(new_space);
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(ParameterSpace)
+
+size_t faiss_ParameterSpace_n_combinations(const FaissParameterSpace* space) {
+ return reinterpret_cast<const ParameterSpace*>(space)->n_combinations();
+}
+
+int faiss_ParameterSpace_combination_name(
+ const FaissParameterSpace* space,
+ size_t cno,
+ char* char_buffer,
+ size_t size) {
+ try {
+ auto rep = reinterpret_cast<const ParameterSpace*>(space)
+ ->combination_name(cno);
+ strncpy(char_buffer, rep.c_str(), size);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_ParameterSpace_set_index_parameters(
+ const FaissParameterSpace* space,
+ FaissIndex* cindex,
+ const char* param_string) {
+ try {
+ auto index = reinterpret_cast<Index*>(cindex);
+ reinterpret_cast<const ParameterSpace*>(space)->set_index_parameters(
+ index, param_string);
+ }
+ CATCH_AND_HANDLE
+}
+
+/// set a combination of parameters on an index
+int faiss_ParameterSpace_set_index_parameters_cno(
+ const FaissParameterSpace* space,
+ FaissIndex* cindex,
+ size_t cno) {
+ try {
+ auto index = reinterpret_cast<Index*>(cindex);
+ reinterpret_cast<const ParameterSpace*>(space)->set_index_parameters(
+ index, cno);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_ParameterSpace_set_index_parameter(
+ const FaissParameterSpace* space,
+ FaissIndex* cindex,
+ const char* name,
+ double value) {
+ try {
+ auto index = reinterpret_cast<Index*>(cindex);
+ reinterpret_cast<const ParameterSpace*>(space)->set_index_parameter(
+ index, name, value);
+ }
+ CATCH_AND_HANDLE
+}
+
+void faiss_ParameterSpace_display(const FaissParameterSpace* space) {
+ reinterpret_cast<const ParameterSpace*>(space)->display();
+}
+
+int faiss_ParameterSpace_add_range(
+ FaissParameterSpace* space,
+ const char* name,
+ FaissParameterRange** p_range) {
+ try {
+ ParameterRange& range =
+ reinterpret_cast<ParameterSpace*>(space)->add_range(name);
+ if (p_range) {
+ *p_range = reinterpret_cast<FaissParameterRange*>(&range);
+ }
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/AutoTune_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/AutoTune_c.h
new file mode 100644
index 0000000..4dde348
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/AutoTune_c.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_AUTO_TUNE_C_H
+#define FAISS_AUTO_TUNE_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// possible values of a parameter, sorted from least to most expensive/accurate
+FAISS_DECLARE_CLASS(ParameterRange)
+
+FAISS_DECLARE_GETTER(ParameterRange, const char*, name)
+
+/// Getter for the values in the range. The output values are invalidated
+/// upon any other modification of the range.
+void faiss_ParameterRange_values(FaissParameterRange*, double**, size_t*);
+
+/** Uses a-priori knowledge on the Faiss indexes to extract tunable parameters.
+ */
+FAISS_DECLARE_CLASS(ParameterSpace)
+
+FAISS_DECLARE_DESTRUCTOR(ParameterSpace)
+
+/// Parameter space default constructor
+int faiss_ParameterSpace_new(FaissParameterSpace** space);
+
+/// nb of combinations, = product of values sizes
+size_t faiss_ParameterSpace_n_combinations(const FaissParameterSpace*);
+
+/// get string representation of the combination
+/// by writing it to the given character buffer.
+/// A buffer size of 1000 ensures that the full name is collected.
+int faiss_ParameterSpace_combination_name(
+ const FaissParameterSpace*,
+ size_t,
+ char*,
+ size_t);
+
+/// set a combination of parameters described by a string
+int faiss_ParameterSpace_set_index_parameters(
+ const FaissParameterSpace*,
+ FaissIndex*,
+ const char*);
+
+/// set a combination of parameters on an index
+int faiss_ParameterSpace_set_index_parameters_cno(
+ const FaissParameterSpace*,
+ FaissIndex*,
+ size_t);
+
+/// set one of the parameters
+int faiss_ParameterSpace_set_index_parameter(
+ const FaissParameterSpace*,
+ FaissIndex*,
+ const char*,
+ double);
+
+/// print a description on stdout
+void faiss_ParameterSpace_display(const FaissParameterSpace*);
+
+/// add a new parameter (or return it if it exists)
+int faiss_ParameterSpace_add_range(
+ FaissParameterSpace*,
+ const char*,
+ FaissParameterRange**);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/c_api/CMakeLists.txt
new file mode 100644
index 0000000..5ce7f56
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/CMakeLists.txt
@@ -0,0 +1,166 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+cmake_minimum_required(VERSION 3.17 FATAL_ERROR)
+
+project(faiss_c_library LANGUAGES C CXX)
+
+set(CMAKE_C_STANDARD 11)
+
+set(FAISS_C_SRC
+ AutoTune_c.cpp
+ Clustering_c.cpp
+ IndexFlat_c.cpp
+ IndexIVFFlat_c.cpp
+ IndexIVF_c.cpp
+ IndexLSH_c.cpp
+ IndexPreTransform_c.cpp
+ VectorTransform_c.cpp
+ IndexShards_c.cpp
+ IndexReplicas_c.cpp
+ Index_c.cpp
+ IndexBinary_c.cpp
+ IndexScalarQuantizer_c.cpp
+ MetaIndexes_c.cpp
+ clone_index_c.cpp
+ error_impl.cpp
+ index_factory_c.cpp
+ index_io_c.cpp
+ impl/AuxIndexStructures_c.cpp
+ utils/distances_c.cpp
+ utils/utils_c.cpp
+)
+
+add_library(faiss_c ${FAISS_C_SRC})
+target_link_libraries(faiss_c PRIVATE faiss)
+
+add_library(faiss_c_avx2 ${FAISS_C_SRC})
+target_link_libraries(faiss_c_avx2 PRIVATE faiss_avx2)
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx2" AND NOT FAISS_OPT_LEVEL STREQUAL "avx512" AND NOT FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ set_target_properties(faiss_c_avx2 PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ target_compile_options(faiss_c_avx2 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mavx2 -mfma -mf16c -mpopcnt>)
+else()
+ # MSVC enables FMA with /arch:AVX2; no separate flags for F16C, POPCNT
+ # Ref. FMA (under /arch:AVX2): https://docs.microsoft.com/en-us/cpp/build/reference/arch-x64
+ # Ref. F16C (2nd paragraph): https://walbourn.github.io/directxmath-avx2/
+ # Ref. POPCNT: https://docs.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64
+ target_compile_options(faiss_c_avx2 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX2>)
+endif()
+
+add_library(faiss_c_avx512 ${FAISS_C_SRC})
+target_link_libraries(faiss_c_avx512 PRIVATE faiss_avx512)
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx512")
+ set_target_properties(faiss_c_avx512 PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ # All modern CPUs support F, CD, VL, DQ, BW extensions.
+ # Ref: https://en.wikipedia.org/wiki/AVX512
+ target_compile_options(faiss_c_avx512 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mavx2 -mfma -mf16c -mavx512f -mavx512cd -mavx512vl -mavx512dq -mavx512bw -mpopcnt>)
+else()
+ target_compile_options(faiss_c_avx512 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
+endif()
+
+add_library(faiss_c_avx512_spr ${FAISS_C_SRC})
+target_link_libraries(faiss_c_avx512_spr PRIVATE faiss_avx512_spr)
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ set_target_properties(faiss_c_avx512_spr PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ # Architecture mode to support AVX512 extensions available since Intel(R) Sapphire Rapids.
+ # Ref: https://networkbuilders.intel.com/solutionslibrary/intel-avx-512-fp16-instruction-set-for-intel-xeon-processor-based-products-technology-guide
+ target_compile_options(faiss_c_avx512_spr PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-march=sapphirerapids -mtune=sapphirerapids>)
+else()
+ target_compile_options(faiss_c_avx512_spr PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
+endif()
+
+add_library(faiss_c_sve ${FAISS_C_SRC})
+target_link_libraries(faiss_c_sve PRIVATE faiss_sve)
+if(NOT FAISS_OPT_LEVEL STREQUAL "sve")
+ set_target_properties(faiss_c_sve PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ if("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )-march=native")
+ # Do nothing, expect SVE to be enabled by -march=native
+ elseif("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )(-march=armv[0-9]+(\\.[1-9]+)?-[^+ ](\\+[^+$ ]+)*)")
+ # Add +sve
+ target_compile_options(faiss_c_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:DEBUG>>:${CMAKE_MATCH_2}+sve>)
+ elseif(NOT "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )-march=armv")
+ # No valid -march, so specify -march=armv8-a+sve as the default
+ target_compile_options(faiss_c_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:DEBUG>>:-march=armv8-a+sve>)
+ endif()
+ if("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )-march=native")
+ # Do nothing, expect SVE to be enabled by -march=native
+ elseif("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )(-march=armv[0-9]+(\\.[1-9]+)?-[^+ ](\\+[^+$ ]+)*)")
+ # Add +sve
+ target_compile_options(faiss_c_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:RELEASE>>:${CMAKE_MATCH_2}+sve>)
+ elseif(NOT "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )-march=armv")
+ # No valid -march, so specify -march=armv8-a+sve as the default
+ target_compile_options(faiss_c_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:RELEASE>>:-march=armv8-a+sve>)
+ endif()
+endif()
+
+function(faiss_install_headers headers p)
+ foreach(h ${headers})
+ get_filename_component(f ${h} DIRECTORY)
+ install(FILES ${h}
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/faiss/${p}/${f}
+ )
+ endforeach()
+endfunction()
+
+file(GLOB FAISS_C_API_HEADERS
+ RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
+ "*.h"
+ "impl/*.h"
+ "utils/*.h")
+
+faiss_install_headers("${FAISS_C_API_HEADERS}" c_api)
+
+install(TARGETS faiss_c
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+)
+if(FAISS_OPT_LEVEL STREQUAL "avx2")
+ install(TARGETS faiss_c_avx2
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+if(FAISS_OPT_LEVEL STREQUAL "avx512")
+ install(TARGETS faiss_c_avx2 faiss_c_avx512
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+if(FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ install(TARGETS faiss_c_avx2 faiss_c_avx512_spr
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+if(FAISS_OPT_LEVEL STREQUAL "sve")
+ install(TARGETS faiss_c_sve
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+
+add_executable(example_c EXCLUDE_FROM_ALL example_c.c)
+target_link_libraries(example_c PRIVATE faiss_c)
+
+if(FAISS_ENABLE_GPU)
+ if(FAISS_ENABLE_ROCM)
+ add_subdirectory(gpu-rocm)
+ else ()
+ add_subdirectory(gpu)
+ endif()
+endif()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/Clustering_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/Clustering_c.cpp
new file mode 100644
index 0000000..e8ef72d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/Clustering_c.cpp
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "Clustering_c.h"
+#include <faiss/Clustering.h>
+#include <faiss/Index.h>
+#include <vector>
+#include "macros_impl.h"
+
+extern "C" {
+
+using faiss::Clustering;
+using faiss::ClusteringIterationStats;
+using faiss::ClusteringParameters;
+using faiss::Index;
+
+DEFINE_GETTER(Clustering, int, niter)
+DEFINE_GETTER(Clustering, int, nredo)
+DEFINE_GETTER(Clustering, int, verbose)
+DEFINE_GETTER(Clustering, int, spherical)
+DEFINE_GETTER(Clustering, int, int_centroids)
+DEFINE_GETTER(Clustering, int, update_index)
+DEFINE_GETTER(Clustering, int, frozen_centroids)
+
+DEFINE_GETTER(Clustering, int, min_points_per_centroid)
+DEFINE_GETTER(Clustering, int, max_points_per_centroid)
+
+DEFINE_GETTER(Clustering, int, seed)
+DEFINE_GETTER(Clustering, size_t, decode_block_size)
+
+/// getter for d
+DEFINE_GETTER(Clustering, size_t, d)
+
+/// getter for k
+DEFINE_GETTER(Clustering, size_t, k)
+
+DEFINE_GETTER(ClusteringIterationStats, float, obj)
+DEFINE_GETTER(ClusteringIterationStats, double, time)
+DEFINE_GETTER(ClusteringIterationStats, double, time_search)
+DEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)
+DEFINE_GETTER(ClusteringIterationStats, int, nsplit)
+
+void faiss_ClusteringParameters_init(FaissClusteringParameters* params) {
+ ClusteringParameters d;
+ params->frozen_centroids = d.frozen_centroids;
+ params->max_points_per_centroid = d.max_points_per_centroid;
+ params->min_points_per_centroid = d.min_points_per_centroid;
+ params->niter = d.niter;
+ params->nredo = d.nredo;
+ params->seed = d.seed;
+ params->spherical = d.spherical;
+ params->int_centroids = d.int_centroids;
+ params->update_index = d.update_index;
+ params->verbose = d.verbose;
+ params->decode_block_size = d.decode_block_size;
+}
+
+// This conversion is required because the two types are not memory-compatible
+inline ClusteringParameters from_faiss_c(
+ const FaissClusteringParameters* params) {
+ ClusteringParameters o;
+ o.frozen_centroids = params->frozen_centroids;
+ o.max_points_per_centroid = params->max_points_per_centroid;
+ o.min_points_per_centroid = params->min_points_per_centroid;
+ o.niter = params->niter;
+ o.nredo = params->nredo;
+ o.seed = params->seed;
+ o.spherical = params->spherical;
+ o.update_index = params->update_index;
+ o.int_centroids = params->int_centroids;
+ o.verbose = params->verbose;
+ o.decode_block_size = params->decode_block_size;
+ return o;
+}
+
+/// getter for centroids (size = k * d)
+void faiss_Clustering_centroids(
+ FaissClustering* clustering,
+ float** centroids,
+ size_t* size) {
+ std::vector<float>& v =
+ reinterpret_cast<Clustering*>(clustering)->centroids;
+ if (centroids) {
+ *centroids = v.data();
+ }
+ if (size) {
+ *size = v.size();
+ }
+}
+
+/// getter for iteration stats
+void faiss_Clustering_iteration_stats(
+ FaissClustering* clustering,
+ FaissClusteringIterationStats** iteration_stats,
+ size_t* size) {
+ std::vector<ClusteringIterationStats>& v =
+ reinterpret_cast<Clustering*>(clustering)->iteration_stats;
+ if (iteration_stats) {
+ *iteration_stats =
+ reinterpret_cast<FaissClusteringIterationStats*>(v.data());
+ }
+ if (size) {
+ *size = v.size();
+ }
+}
+
+/// the only mandatory parameters are k and d
+int faiss_Clustering_new(FaissClustering** p_clustering, int d, int k) {
+ try {
+ Clustering* c = new Clustering(d, k);
+ *p_clustering = reinterpret_cast<FaissClustering*>(c);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Clustering_new_with_params(
+ FaissClustering** p_clustering,
+ int d,
+ int k,
+ const FaissClusteringParameters* cp) {
+ try {
+ Clustering* c = new Clustering(d, k, from_faiss_c(cp));
+ *p_clustering = reinterpret_cast<FaissClustering*>(c);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+/// Index is used during the assignment stage
+int faiss_Clustering_train(
+ FaissClustering* clustering,
+ idx_t n,
+ const float* x,
+ FaissIndex* index) {
+ try {
+ reinterpret_cast<Clustering*>(clustering)
+ ->train(n, x, *reinterpret_cast<Index*>(index));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+void faiss_Clustering_free(FaissClustering* clustering) {
+ delete reinterpret_cast<Clustering*>(clustering);
+}
+
+int faiss_kmeans_clustering(
+ size_t d,
+ size_t n,
+ size_t k,
+ const float* x,
+ float* centroids,
+ float* q_error) {
+ try {
+ float out = faiss::kmeans_clustering(d, n, k, x, centroids);
+ if (q_error) {
+ *q_error = out;
+ }
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/Clustering_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/Clustering_c.h
new file mode 100644
index 0000000..5142730
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/Clustering_c.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_CLUSTERING_C_H
+#define FAISS_CLUSTERING_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Class for the clustering parameters. Can be passed to the
+ * constructor of the Clustering object.
+ */
+typedef struct FaissClusteringParameters {
+ int niter; ///< clustering iterations
+ int nredo; ///< redo clustering this many times and keep best
+
+ int verbose; ///< (bool)
+ int spherical; ///< (bool) do we want normalized centroids?
+ int int_centroids; ///< (bool) round centroids coordinates to integer
+ int update_index; ///< (bool) update index after each iteration?
+ int frozen_centroids; ///< (bool) use the centroids provided as input and do
+ ///< not change them during iterations
+
+ int min_points_per_centroid; ///< otherwise you get a warning
+ int max_points_per_centroid; ///< to limit size of dataset
+
+ int seed; ///< seed for the random number generator
+ size_t decode_block_size; ///< how many vectors at a time to decode
+} FaissClusteringParameters;
+
+/// Sets the ClusteringParameters object with reasonable defaults
+void faiss_ClusteringParameters_init(FaissClusteringParameters* params);
+
+/** clustering based on assignment - centroid update iterations
+ *
+ * The clustering is based on an Index object that assigns training
+ * points to the centroids. Therefore, at each iteration the centroids
+ * are added to the index.
+ *
+ * On output, the centroids table is set to the latest version
+ * of the centroids and they are also added to the index. If the
+ * centroids table it is not empty on input, it is also used for
+ * initialization.
+ *
+ * To do several clusterings, just call train() several times on
+ * different training sets, clearing the centroid table in between.
+ */
+FAISS_DECLARE_CLASS(Clustering)
+
+FAISS_DECLARE_GETTER(Clustering, int, niter)
+FAISS_DECLARE_GETTER(Clustering, int, nredo)
+FAISS_DECLARE_GETTER(Clustering, int, verbose)
+FAISS_DECLARE_GETTER(Clustering, int, spherical)
+FAISS_DECLARE_GETTER(Clustering, int, int_centroids)
+FAISS_DECLARE_GETTER(Clustering, int, update_index)
+FAISS_DECLARE_GETTER(Clustering, int, frozen_centroids)
+
+FAISS_DECLARE_GETTER(Clustering, int, min_points_per_centroid)
+FAISS_DECLARE_GETTER(Clustering, int, max_points_per_centroid)
+
+FAISS_DECLARE_GETTER(Clustering, int, seed)
+FAISS_DECLARE_GETTER(Clustering, size_t, decode_block_size)
+
+/// getter for d
+FAISS_DECLARE_GETTER(Clustering, size_t, d)
+
+/// getter for k
+FAISS_DECLARE_GETTER(Clustering, size_t, k)
+
+FAISS_DECLARE_CLASS(ClusteringIterationStats)
+FAISS_DECLARE_GETTER(ClusteringIterationStats, float, obj)
+FAISS_DECLARE_GETTER(ClusteringIterationStats, double, time)
+FAISS_DECLARE_GETTER(ClusteringIterationStats, double, time_search)
+FAISS_DECLARE_GETTER(ClusteringIterationStats, double, imbalance_factor)
+FAISS_DECLARE_GETTER(ClusteringIterationStats, int, nsplit)
+
+/// getter for centroids (size = k * d)
+void faiss_Clustering_centroids(
+ FaissClustering* clustering,
+ float** centroids,
+ size_t* size);
+
+/// getter for iteration stats
+void faiss_Clustering_iteration_stats(
+ FaissClustering* clustering,
+ FaissClusteringIterationStats** iteration_stats,
+ size_t* size);
+
+/// the only mandatory parameters are k and d
+int faiss_Clustering_new(FaissClustering** p_clustering, int d, int k);
+
+int faiss_Clustering_new_with_params(
+ FaissClustering** p_clustering,
+ int d,
+ int k,
+ const FaissClusteringParameters* cp);
+
+int faiss_Clustering_train(
+ FaissClustering* clustering,
+ idx_t n,
+ const float* x,
+ FaissIndex* index);
+
+void faiss_Clustering_free(FaissClustering* clustering);
+
+/** simplified interface
+ *
+ * @param d dimension of the data
+ * @param n nb of training vectors
+ * @param k nb of output centroids
+ * @param x training set (size n * d)
+ * @param centroids output centroids (size k * d)
+ * @param q_error final quantization error
+ * @return error code
+ */
+int faiss_kmeans_clustering(
+ size_t d,
+ size_t n,
+ size_t k,
+ const float* x,
+ float* centroids,
+ float* q_error);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/INSTALL.md b/packages/leann-backend-hnsw/third_party/faiss/c_api/INSTALL.md
new file mode 100644
index 0000000..4694f2a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/INSTALL.md
@@ -0,0 +1,104 @@
+Faiss C API
+===========
+
+Faiss provides a pure C interface, which can subsequently be used either in pure C programs or to produce bindings for programming languages with Foreign Function Interface (FFI) support. Although this is not required for the Python interface, some other programming languages (e.g. Rust and Julia) do not have SWIG support.
+
+Compilation instructions
+------------------------
+
+The full contents of the pure C API are in the ["c_api"](c_api/) folder.
+Please be sure to follow the instructions on [building the main C++ library](../INSTALL.md#step-1-compiling-the-c-faiss) first.
+Include `-DFAISS_ENABLE_C_API=ON` to the cmake command.
+
+`make -C build`
+
+
+This builds the dynamic library "faiss_c", containing the full implementation of Faiss and the necessary wrappers for the C interface. It does not depend on libfaiss.a or the C++ standard library.
+
+To build the example program, you should run `make -C build example_c` at the top level of
+the faiss repo. The example program will be in `build/c_api/example_c` .
+
+Using the API
+-------------
+
+The C API is composed of:
+
+- A set of C header files comprising the main Faiss interfaces, converted for use in C. Each file follows the format `«name»_c.h`, where `«name»` is the respective name from the C++ API. For example, the file [Index_c.h](./Index_c.h) file corresponds to the base `Index` API. Functions are declared with the `faiss_` prefix (e.g. `faiss_IndexFlat_new`), whereas new types have the `Faiss` prefix (e.g. `FaissIndex`, `FaissMetricType`, ...).
+- A dynamic library, compiled from the sources in the same folder, encloses the implementation of the library and wrapper functions.
+
+The index factory is available via the `faiss_index_factory` function in `AutoTune_c.h`:
+
+```c
+FaissIndex* index = NULL;
+int c = faiss_index_factory(&index, 64, "Flat", METRIC_L2);
+if (c) {
+ // operation failed
+}
+```
+
+Most operations that you would find as member functions are available with the format `faiss_«classname»_«member»`.
+
+```c
+idx_t ntotal = faiss_Index_ntotal(index);
+```
+
+Since this is C, the index needs to be freed manually in the end:
+
+```c
+faiss_Index_free(index);
+```
+
+Error handling is done by examining the error code returned by operations with recoverable errors.
+The code identifies the type of exception that rose from the implementation. Fetching the
+corresponding error message can be done by calling the function `faiss_get_last_error()` from
+`error_c.h`. Getter functions and `free` functions do not return an error code.
+
+```c
+int c = faiss_Index_add(index, nb, xb);
+if (c) {
+ printf("%s", faiss_get_last_error());
+ exit(-1);
+}
+```
+
+An example is included, which is built automatically for the target `all`. It can also be built separately:
+
+ `make bin/example_c`
+
+Building with GPU support
+-------------------------
+
+For GPU support, a separate dynamic library in the "c_api/gpu" directory needs to be built.
+
+ `make`
+
+The "gpufaiss_c" dynamic library contains the GPU and CPU implementations of Faiss, which means that
+it can be used in place of "faiss_c". The same library will dynamically link with the CUDA runtime
+and cuBLAS.
+
+Using the GPU with the C API
+----------------------------
+
+A standard GPU resources object can be obtained by the name `FaissStandardGpuResources`:
+
+```c
+FaissStandardGpuResources* gpu_res = NULL;
+int c = faiss_StandardGpuResources_new(&gpu_res);
+if (c) {
+ printf("%s", faiss_get_last_error());
+ exit(-1);
+}
+```
+
+Similarly to the C++ API, a CPU index can be converted to a GPU index:
+
+```c
+FaissIndex* cpu_index = NULL;
+int c = faiss_index_factory(&cpu_index, d, "Flat", METRIC_L2);
+if (c) { /* ... */ }
+FaissGpuIndex* gpu_index = NULL;
+c = faiss_index_cpu_to_gpu(gpu_res, 0, cpu_index, &gpu_index);
+if (c) { /* ... */ }
+```
+
+A more complete example is available by the name `bin/example_gpu_c`.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexBinary_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexBinary_c.cpp
new file mode 100644
index 0000000..6f576ca
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexBinary_c.cpp
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexBinary_c.h"
+#include <faiss/IndexBinary.h>
+#include "macros_impl.h"
+
+extern "C" {
+
+DEFINE_DESTRUCTOR(IndexBinary)
+
+DEFINE_GETTER(IndexBinary, int, d)
+
+DEFINE_GETTER(IndexBinary, int, is_trained)
+
+DEFINE_GETTER(IndexBinary, idx_t, ntotal)
+
+DEFINE_GETTER(IndexBinary, FaissMetricType, metric_type)
+
+DEFINE_GETTER(IndexBinary, int, verbose);
+DEFINE_SETTER(IndexBinary, int, verbose);
+
+int faiss_IndexBinary_train(
+ FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x) {
+ try {
+ reinterpret_cast<faiss::IndexBinary*>(index)->train(n, x);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_add(FaissIndexBinary* index, idx_t n, const uint8_t* x) {
+ try {
+ reinterpret_cast<faiss::IndexBinary*>(index)->add(n, x);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_add_with_ids(
+ FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ const idx_t* xids) {
+ try {
+ reinterpret_cast<faiss::IndexBinary*>(index)->add_with_ids(n, x, xids);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_search(
+ const FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels) {
+ try {
+ reinterpret_cast<const faiss::IndexBinary*>(index)->search(
+ n, x, k, distances, labels);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_range_search(
+ const FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ FaissRangeSearchResult* result) {
+ try {
+ reinterpret_cast<const faiss::IndexBinary*>(index)->range_search(
+ n,
+ x,
+ radius,
+ reinterpret_cast<faiss::RangeSearchResult*>(result));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_assign(
+ FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ idx_t* labels,
+ idx_t k) {
+ try {
+ reinterpret_cast<faiss::IndexBinary*>(index)->assign(n, x, labels, k);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_reset(FaissIndexBinary* index) {
+ try {
+ reinterpret_cast<faiss::IndexBinary*>(index)->reset();
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_remove_ids(
+ FaissIndexBinary* index,
+ const FaissIDSelector* sel,
+ size_t* n_removed) {
+ try {
+ size_t n{reinterpret_cast<faiss::IndexBinary*>(index)->remove_ids(
+ *reinterpret_cast<const faiss::IDSelector*>(sel))};
+ if (n_removed) {
+ *n_removed = n;
+ }
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_reconstruct(
+ const FaissIndexBinary* index,
+ idx_t key,
+ uint8_t* recons) {
+ try {
+ reinterpret_cast<const faiss::IndexBinary*>(index)->reconstruct(
+ key, recons);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexBinary_reconstruct_n(
+ const FaissIndexBinary* index,
+ idx_t i0,
+ idx_t ni,
+ uint8_t* recons) {
+ try {
+ reinterpret_cast<const faiss::IndexBinary*>(index)->reconstruct_n(
+ i0, ni, recons);
+ }
+ CATCH_AND_HANDLE
+}
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexBinary_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexBinary_c.h
new file mode 100644
index 0000000..9ad05a6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexBinary_c.h
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_BINARY_C_H
+#define FAISS_INDEX_BINARY_C_H
+
+#include <stddef.h>
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// forward declaration required here
+FAISS_DECLARE_CLASS(RangeSearchResult)
+
+// typedef struct FaissRangeSearchResult_H FaissRangeSearchResult;
+typedef struct FaissIDSelector_H FaissIDSelector;
+
+/// Opaque type for referencing to a binary index object
+FAISS_DECLARE_CLASS(IndexBinary)
+FAISS_DECLARE_DESTRUCTOR(IndexBinary)
+
+/// Getter for d
+FAISS_DECLARE_GETTER(IndexBinary, int, d)
+
+/// Getter for is_trained
+FAISS_DECLARE_GETTER(IndexBinary, int, is_trained)
+
+/// Getter for ntotal
+FAISS_DECLARE_GETTER(IndexBinary, idx_t, ntotal)
+
+/// Getter for metric_type
+FAISS_DECLARE_GETTER(IndexBinary, FaissMetricType, metric_type)
+
+FAISS_DECLARE_GETTER_SETTER(IndexBinary, int, verbose)
+
+/** Perform training on a representative set of vectors
+ *
+ * @param index opaque pointer to index object
+ * @param n nb of training vectors
+ * @param x training vectors, size n * d
+ */
+int faiss_IndexBinary_train(FaissIndexBinary* index, idx_t n, const uint8_t* x);
+
+/** Add n vectors of dimension d to the index.
+ *
+ * Vectors are implicitly assigned labels ntotal .. ntotal + n - 1
+ * This function slices the input vectors in chunks smaller than
+ * blocksize_add and calls add_core.
+ * @param index opaque pointer to index object
+ * @param x input matrix, size n * d
+ */
+int faiss_IndexBinary_add(FaissIndexBinary* index, idx_t n, const uint8_t* x);
+
+/** Same as add, but stores xids instead of sequential ids.
+ *
+ * The default implementation fails with an assertion, as it is
+ * not supported by all indexes.
+ *
+ * @param index opaque pointer to index object
+ * @param xids if non-null, ids to store for the vectors (size n)
+ */
+int faiss_IndexBinary_add_with_ids(
+ FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ const idx_t* xids);
+
+/** query n vectors of dimension d to the index.
+ *
+ * return at most k vectors. If there are not enough results for a
+ * query, the result array is padded with -1s.
+ *
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param labels output labels of the NNs, size n*k
+ * @param distances output pairwise distances, size n*k
+ */
+int faiss_IndexBinary_search(
+ const FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels);
+
+/** query n vectors of dimension d to the index.
+ *
+ * return all vectors with distance < radius. Note that many
+ * indexes do not implement the range_search (only the k-NN search
+ * is mandatory).
+ *
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param radius search radius
+ * @param result result table
+ */
+int faiss_IndexBinary_range_search(
+ const FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ FaissRangeSearchResult* result);
+
+/** return the indexes of the k vectors closest to the query x.
+ *
+ * This function is identical as search but only return labels of neighbors.
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param labels output labels of the NNs, size n*k
+ */
+int faiss_IndexBinary_assign(
+ FaissIndexBinary* index,
+ idx_t n,
+ const uint8_t* x,
+ idx_t* labels,
+ idx_t k);
+
+/** removes all elements from the database.
+ * @param index opaque pointer to index object
+ */
+int faiss_IndexBinary_reset(FaissIndexBinary* index);
+
+/** removes IDs from the index. Not supported by all indexes
+ * @param index opaque pointer to index object
+ * @param nremove output for the number of IDs removed
+ */
+int faiss_IndexBinary_remove_ids(
+ FaissIndexBinary* index,
+ const FaissIDSelector* sel,
+ size_t* n_removed);
+
+/** Reconstruct a stored vector (or an approximation if lossy coding)
+ *
+ * this function may not be defined for some indexes
+ * @param index opaque pointer to index object
+ * @param key id of the vector to reconstruct
+ * @param recons reconstructed vector (size d)
+ */
+int faiss_IndexBinary_reconstruct(
+ const FaissIndexBinary* index,
+ idx_t key,
+ uint8_t* recons);
+
+/** Reconstruct vectors i0 to i0 + ni - 1
+ *
+ * this function may not be defined for some indexes
+ * @param index opaque pointer to index object
+ * @param recons reconstructed vector (size ni * d)
+ */
+int faiss_IndexBinary_reconstruct_n(
+ const FaissIndexBinary* index,
+ idx_t i0,
+ idx_t ni,
+ uint8_t* recons);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexFlat_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexFlat_c.cpp
new file mode 100644
index 0000000..1a87cb8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexFlat_c.cpp
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexFlat_c.h"
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexRefine.h>
+#include "macros_impl.h"
+
+extern "C" {
+
+using faiss::Index;
+using faiss::IndexFlat;
+using faiss::IndexFlat1D;
+using faiss::IndexFlatIP;
+using faiss::IndexFlatL2;
+using faiss::IndexRefineFlat;
+
+DEFINE_DESTRUCTOR(IndexFlat)
+DEFINE_INDEX_DOWNCAST(IndexFlat)
+
+int faiss_IndexFlat_new(FaissIndexFlat** p_index) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexFlat*>(new IndexFlat());
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexFlat_new_with(
+ FaissIndexFlat** p_index,
+ idx_t d,
+ FaissMetricType metric) {
+ try {
+ IndexFlat* index =
+ new IndexFlat(d, static_cast<faiss::MetricType>(metric));
+ *p_index = reinterpret_cast<FaissIndexFlat*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+void faiss_IndexFlat_xb(FaissIndexFlat* index, float** p_xb, size_t* p_size) {
+ IndexFlat* indexf = reinterpret_cast<IndexFlat*>(index);
+ *p_xb = indexf->get_xb();
+ if (p_size) {
+ *p_size = indexf->codes.size() / sizeof(float);
+ }
+}
+
+int faiss_IndexFlat_compute_distance_subset(
+ FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ const idx_t* labels) {
+ try {
+ reinterpret_cast<IndexFlat*>(index)->compute_distance_subset(
+ n, x, k, distances, labels);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(IndexFlatIP)
+DEFINE_INDEX_DOWNCAST(IndexFlatIP)
+
+int faiss_IndexFlatIP_new(FaissIndexFlatIP** p_index) {
+ try {
+ IndexFlatIP* index = new IndexFlatIP();
+ *p_index = reinterpret_cast<FaissIndexFlatIP*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexFlatIP_new_with(FaissIndexFlatIP** p_index, idx_t d) {
+ try {
+ IndexFlatIP* index = new IndexFlatIP(d);
+ *p_index = reinterpret_cast<FaissIndexFlatIP*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(IndexFlatL2)
+DEFINE_INDEX_DOWNCAST(IndexFlatL2)
+
+int faiss_IndexFlatL2_new(FaissIndexFlatL2** p_index) {
+ try {
+ IndexFlatL2* index = new IndexFlatL2();
+ *p_index = reinterpret_cast<FaissIndexFlatL2*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexFlatL2_new_with(FaissIndexFlatL2** p_index, idx_t d) {
+ try {
+ IndexFlatL2* index = new IndexFlatL2(d);
+ *p_index = reinterpret_cast<FaissIndexFlatL2*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexRefineFlat_new(
+ FaissIndexRefineFlat** p_index,
+ FaissIndex* base_index) {
+ try {
+ IndexRefineFlat* index = new IndexRefineFlat(
+ reinterpret_cast<faiss::Index*>(base_index));
+ *p_index = reinterpret_cast<FaissIndexRefineFlat*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(IndexRefineFlat)
+DEFINE_INDEX_DOWNCAST(IndexRefineFlat)
+
+DEFINE_GETTER(IndexRefineFlat, int, own_fields)
+DEFINE_SETTER(IndexRefineFlat, int, own_fields)
+
+DEFINE_GETTER(IndexRefineFlat, float, k_factor)
+DEFINE_SETTER(IndexRefineFlat, float, k_factor)
+
+DEFINE_DESTRUCTOR(IndexFlat1D)
+DEFINE_INDEX_DOWNCAST(IndexFlat1D)
+
+int faiss_IndexFlat1D_new(FaissIndexFlat1D** p_index) {
+ try {
+ IndexFlat1D* index = new IndexFlat1D();
+ *p_index = reinterpret_cast<FaissIndexFlat1D*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexFlat1D_new_with(
+ FaissIndexFlat1D** p_index,
+ int continuous_update) {
+ try {
+ IndexFlat1D* index =
+ new IndexFlat1D(static_cast<bool>(continuous_update));
+ *p_index = reinterpret_cast<FaissIndexFlat1D*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexFlat1D_update_permutation(FaissIndexFlat1D* index) {
+ try {
+ reinterpret_cast<IndexFlat1D*>(index)->update_permutation();
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexFlat_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexFlat_c.h
new file mode 100644
index 0000000..0c0ff0a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexFlat_c.h
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_FLAT_C_H
+#define FAISS_INDEX_FLAT_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// forward declaration
+typedef enum FaissMetricType FaissMetricType;
+
+/** Opaque type for IndexFlat */
+FAISS_DECLARE_CLASS_INHERITED(IndexFlat, Index)
+
+int faiss_IndexFlat_new(FaissIndexFlat** p_index);
+
+int faiss_IndexFlat_new_with(
+ FaissIndexFlat** p_index,
+ idx_t d,
+ FaissMetricType metric);
+
+/** get a pointer to the index's internal data (the `xb` field). The outputs
+ * become invalid after any data addition or removal operation.
+ *
+ * @param index opaque pointer to index object
+ * @param p_xb output, the pointer to the beginning of `xb`.
+ * @param p_size output, the current size of `sb` in number of float values.
+ */
+void faiss_IndexFlat_xb(FaissIndexFlat* index, float** p_xb, size_t* p_size);
+
+/** attempt a dynamic cast to a flat index, thus checking
+ * check whether the underlying index type is `IndexFlat`.
+ *
+ * @param index opaque pointer to index object
+ * @return the same pointer if the index is a flat index, NULL otherwise
+ */
+FAISS_DECLARE_INDEX_DOWNCAST(IndexFlat)
+
+FAISS_DECLARE_DESTRUCTOR(IndexFlat)
+
+/** compute distance with a subset of vectors
+ *
+ * @param index opaque pointer to index object
+ * @param x query vectors, size n * d
+ * @param labels indices of the vectors that should be compared
+ * for each query vector, size n * k
+ * @param distances
+ * corresponding output distances, size n * k
+ */
+int faiss_IndexFlat_compute_distance_subset(
+ FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ const idx_t* labels);
+
+/** Opaque type for IndexFlatIP */
+FAISS_DECLARE_CLASS_INHERITED(IndexFlatIP, Index)
+
+FAISS_DECLARE_INDEX_DOWNCAST(IndexFlatIP)
+FAISS_DECLARE_DESTRUCTOR(IndexFlatIP)
+
+int faiss_IndexFlatIP_new(FaissIndexFlatIP** p_index);
+
+int faiss_IndexFlatIP_new_with(FaissIndexFlatIP** p_index, idx_t d);
+
+/** Opaque type for IndexFlatL2 */
+FAISS_DECLARE_CLASS_INHERITED(IndexFlatL2, Index)
+
+FAISS_DECLARE_INDEX_DOWNCAST(IndexFlatL2)
+FAISS_DECLARE_DESTRUCTOR(IndexFlatL2)
+
+int faiss_IndexFlatL2_new(FaissIndexFlatL2** p_index);
+
+int faiss_IndexFlatL2_new_with(FaissIndexFlatL2** p_index, idx_t d);
+
+/** Opaque type for IndexRefineFlat
+ *
+ * Index that queries in a base_index (a fast one) and refines the
+ * results with an exact search, hopefully improving the results.
+ */
+FAISS_DECLARE_CLASS_INHERITED(IndexRefineFlat, Index)
+
+int faiss_IndexRefineFlat_new(
+ FaissIndexRefineFlat** p_index,
+ FaissIndex* base_index);
+
+FAISS_DECLARE_DESTRUCTOR(IndexRefineFlat)
+FAISS_DECLARE_INDEX_DOWNCAST(IndexRefineFlat)
+
+FAISS_DECLARE_GETTER_SETTER(IndexRefineFlat, int, own_fields)
+
+/// factor between k requested in search and the k requested from
+/// the base_index (should be >= 1)
+FAISS_DECLARE_GETTER_SETTER(IndexRefineFlat, float, k_factor)
+
+/** Opaque type for IndexFlat1D
+ *
+ * optimized version for 1D "vectors"
+ */
+FAISS_DECLARE_CLASS_INHERITED(IndexFlat1D, Index)
+
+FAISS_DECLARE_INDEX_DOWNCAST(IndexFlat1D)
+FAISS_DECLARE_DESTRUCTOR(IndexFlat1D)
+
+int faiss_IndexFlat1D_new(FaissIndexFlat1D** p_index);
+int faiss_IndexFlat1D_new_with(
+ FaissIndexFlat1D** p_index,
+ int continuous_update);
+
+int faiss_IndexFlat1D_update_permutation(FaissIndexFlat1D* index);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVFFlat_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVFFlat_c.cpp
new file mode 100644
index 0000000..4155283
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVFFlat_c.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexIVFFlat_c.h"
+#include <faiss/IndexIVFFlat.h>
+#include "Clustering_c.h"
+#include "Index_c.h"
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexIVFFlat;
+using faiss::MetricType;
+
+DEFINE_DESTRUCTOR(IndexIVFFlat)
+DEFINE_INDEX_DOWNCAST(IndexIVFFlat)
+
+/// number of possible key values
+DEFINE_GETTER(IndexIVFFlat, size_t, nlist)
+/// number of probes at query time
+DEFINE_GETTER(IndexIVFFlat, size_t, nprobe)
+DEFINE_SETTER(IndexIVFFlat, size_t, nprobe)
+
+/// quantizer that maps vectors to inverted lists
+DEFINE_GETTER_PERMISSIVE(IndexIVFFlat, FaissIndex*, quantizer)
+
+/**
+ * = 0: use the quantizer as index in a kmeans training
+ * = 1: just pass on the training set to the train() of the quantizer
+ * = 2: kmeans training on a flat index + add the centroids to the quantizer
+ */
+DEFINE_GETTER(IndexIVFFlat, char, quantizer_trains_alone)
+
+/// whether object owns the quantizer
+DEFINE_GETTER(IndexIVFFlat, int, own_fields)
+DEFINE_SETTER(IndexIVFFlat, int, own_fields)
+
+int faiss_IndexIVFFlat_new(FaissIndexIVFFlat** p_index) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexIVFFlat*>(new IndexIVFFlat());
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVFFlat_new_with(
+ FaissIndexIVFFlat** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist) {
+ try {
+ auto q = reinterpret_cast<Index*>(quantizer);
+ *p_index = reinterpret_cast<FaissIndexIVFFlat*>(
+ new IndexIVFFlat(q, d, nlist));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVFFlat_new_with_metric(
+ FaissIndexIVFFlat** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist,
+ FaissMetricType metric) {
+ try {
+ auto q = reinterpret_cast<Index*>(quantizer);
+ auto m = static_cast<MetricType>(metric);
+ *p_index = reinterpret_cast<FaissIndexIVFFlat*>(
+ new IndexIVFFlat(q, d, nlist, m));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVFFlat_add_core(
+ FaissIndexIVFFlat* index,
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const int64_t* precomputed_idx) {
+ try {
+ reinterpret_cast<IndexIVFFlat*>(index)->add_core(
+ n, x, xids, precomputed_idx);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVFFlat_update_vectors(
+ FaissIndexIVFFlat* index,
+ int nv,
+ idx_t* idx,
+ const float* v) {
+ try {
+ reinterpret_cast<IndexIVFFlat*>(index)->update_vectors(nv, idx, v);
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVFFlat_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVFFlat_c.h
new file mode 100644
index 0000000..b535da5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVFFlat_c.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_IVF_FLAT_C_H
+#define FAISS_INDEX_IVF_FLAT_C_H
+
+#include "Clustering_c.h"
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Inverted file with stored vectors. Here the inverted file
+ * pre-selects the vectors to be searched, but they are not otherwise
+ * encoded, the code array just contains the raw float entries.
+ */
+FAISS_DECLARE_CLASS_INHERITED(IndexIVFFlat, Index)
+FAISS_DECLARE_DESTRUCTOR(IndexIVFFlat)
+FAISS_DECLARE_INDEX_DOWNCAST(IndexIVFFlat)
+
+/// number of possible key values
+FAISS_DECLARE_GETTER(IndexIVFFlat, size_t, nlist)
+/// number of probes at query time
+FAISS_DECLARE_GETTER_SETTER(IndexIVFFlat, size_t, nprobe)
+/// quantizer that maps vectors to inverted lists
+FAISS_DECLARE_GETTER(IndexIVFFlat, FaissIndex*, quantizer)
+/**
+ * = 0: use the quantizer as index in a kmeans training
+ * = 1: just pass on the training set to the train() of the quantizer
+ * = 2: kmeans training on a flat index + add the centroids to the quantizer
+ */
+FAISS_DECLARE_GETTER(IndexIVFFlat, char, quantizer_trains_alone)
+
+/// whether object owns the quantizer
+FAISS_DECLARE_GETTER_SETTER(IndexIVFFlat, int, own_fields)
+
+int faiss_IndexIVFFlat_new(FaissIndexIVFFlat** p_index);
+
+int faiss_IndexIVFFlat_new_with(
+ FaissIndexIVFFlat** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist);
+
+int faiss_IndexIVFFlat_new_with_metric(
+ FaissIndexIVFFlat** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist,
+ FaissMetricType metric);
+
+int faiss_IndexIVFFlat_add_core(
+ FaissIndexIVFFlat* index,
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const int64_t* precomputed_idx);
+
+/** Update a subset of vectors.
+ *
+ * The index must have a direct_map
+ *
+ * @param nv nb of vectors to update
+ * @param idx vector indices to update, size nv
+ * @param v vectors of new values, size nv*d
+ */
+int faiss_IndexIVFFlat_update_vectors(
+ FaissIndexIVFFlat* index,
+ int nv,
+ idx_t* idx,
+ const float* v);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVF_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVF_c.cpp
new file mode 100644
index 0000000..0e42e0f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVF_c.cpp
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexIVF_c.h"
+#include <faiss/IndexIVF.h>
+#include "Clustering_c.h"
+#include "Index_c.h"
+#include "impl/AuxIndexStructures_c.h"
+#include "macros_impl.h"
+
+using faiss::IndexIVF;
+using faiss::IndexIVFStats;
+using faiss::SearchParametersIVF;
+
+/// SearchParametersIVF definitions
+
+DEFINE_DESTRUCTOR(SearchParametersIVF)
+DEFINE_SEARCH_PARAMETERS_DOWNCAST(SearchParametersIVF)
+
+int faiss_SearchParametersIVF_new(FaissSearchParametersIVF** p_sp) {
+ try {
+ SearchParametersIVF* sp = new SearchParametersIVF;
+ *p_sp = reinterpret_cast<FaissSearchParametersIVF*>(sp);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_SearchParametersIVF_new_with(
+ FaissSearchParametersIVF** p_sp,
+ FaissIDSelector* sel,
+ size_t nprobe,
+ size_t max_codes) {
+ try {
+ SearchParametersIVF* sp = new SearchParametersIVF;
+ sp->sel = reinterpret_cast<faiss::IDSelector*>(sel);
+ sp->nprobe = nprobe;
+ sp->max_codes = max_codes;
+ *p_sp = reinterpret_cast<FaissSearchParametersIVF*>(sp);
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER_PERMISSIVE(SearchParametersIVF, const FaissIDSelector*, sel)
+
+DEFINE_GETTER(SearchParametersIVF, size_t, nprobe)
+DEFINE_SETTER(SearchParametersIVF, size_t, nprobe)
+
+DEFINE_GETTER(SearchParametersIVF, size_t, max_codes)
+DEFINE_SETTER(SearchParametersIVF, size_t, max_codes)
+
+/// IndexIVF definitions
+
+DEFINE_DESTRUCTOR(IndexIVF)
+DEFINE_INDEX_DOWNCAST(IndexIVF)
+
+/// number of possible key values
+DEFINE_GETTER(IndexIVF, size_t, nlist)
+/// number of probes at query time
+DEFINE_GETTER(IndexIVF, size_t, nprobe)
+DEFINE_SETTER(IndexIVF, size_t, nprobe)
+
+/// quantizer that maps vectors to inverted lists
+DEFINE_GETTER_PERMISSIVE(IndexIVF, FaissIndex*, quantizer)
+
+/**
+ * = 0: use the quantizer as index in a kmeans training
+ * = 1: just pass on the training set to the train() of the quantizer
+ * = 2: kmeans training on a flat index + add the centroids to the quantizer
+ */
+DEFINE_GETTER(IndexIVF, char, quantizer_trains_alone)
+
+/// whether object owns the quantizer
+DEFINE_GETTER(IndexIVF, int, own_fields)
+DEFINE_SETTER(IndexIVF, int, own_fields)
+
+using faiss::IndexIVF;
+
+int faiss_IndexIVF_merge_from(
+ FaissIndexIVF* index,
+ FaissIndexIVF* other,
+ idx_t add_id) {
+ try {
+ reinterpret_cast<IndexIVF*>(index)->merge_from(
+ *reinterpret_cast<IndexIVF*>(other), add_id);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVF_copy_subset_to(
+ const FaissIndexIVF* index,
+ FaissIndexIVF* other,
+ int subset_type,
+ idx_t a1,
+ idx_t a2) {
+ try {
+ reinterpret_cast<const IndexIVF*>(index)->copy_subset_to(
+ *reinterpret_cast<IndexIVF*>(other),
+ static_cast<faiss::InvertedLists::subset_type_t>(subset_type),
+ a1,
+ a2);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVF_search_preassigned(
+ const FaissIndexIVF* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ int store_pairs) {
+ try {
+ reinterpret_cast<const IndexIVF*>(index)->search_preassigned(
+ n, x, k, assign, centroid_dis, distances, labels, store_pairs);
+ }
+ CATCH_AND_HANDLE
+}
+
+size_t faiss_IndexIVF_get_list_size(
+ const FaissIndexIVF* index,
+ size_t list_no) {
+ return reinterpret_cast<const IndexIVF*>(index)->get_list_size(list_no);
+}
+
+int faiss_IndexIVF_make_direct_map(
+ FaissIndexIVF* index,
+ int new_maintain_direct_map) {
+ try {
+ reinterpret_cast<IndexIVF*>(index)->make_direct_map(
+ static_cast<bool>(new_maintain_direct_map));
+ }
+ CATCH_AND_HANDLE
+}
+
+double faiss_IndexIVF_imbalance_factor(const FaissIndexIVF* index) {
+ return reinterpret_cast<const IndexIVF*>(index)
+ ->invlists->imbalance_factor();
+}
+
+/// display some stats about the inverted lists
+void faiss_IndexIVF_print_stats(const FaissIndexIVF* index) {
+ reinterpret_cast<const IndexIVF*>(index)->invlists->print_stats();
+}
+
+/// get inverted lists ids
+void faiss_IndexIVF_invlists_get_ids(
+ const FaissIndexIVF* index,
+ size_t list_no,
+ idx_t* invlist) {
+ const idx_t* list =
+ reinterpret_cast<const IndexIVF*>(index)->invlists->get_ids(
+ list_no);
+ size_t list_size =
+ reinterpret_cast<const IndexIVF*>(index)->get_list_size(list_no);
+ memcpy(invlist, list, list_size * sizeof(idx_t));
+}
+
+int faiss_IndexIVF_train_encoder(
+ FaissIndexIVF* index,
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ try {
+ reinterpret_cast<IndexIVF*>(index)->train_encoder(n, x, assign);
+ }
+ CATCH_AND_HANDLE
+}
+
+void faiss_IndexIVFStats_reset(FaissIndexIVFStats* stats) {
+ reinterpret_cast<IndexIVFStats*>(stats)->reset();
+}
+
+FaissIndexIVFStats* faiss_get_indexIVF_stats() {
+ return reinterpret_cast<FaissIndexIVFStats*>(&faiss::indexIVF_stats);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVF_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVF_c.h
new file mode 100644
index 0000000..ca88336
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexIVF_c.h
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_IVF_C_H
+#define FAISS_INDEX_IVF_C_H
+
+#include "Clustering_c.h"
+#include "Index_c.h"
+#include "faiss_c.h"
+#include "impl/AuxIndexStructures_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+FAISS_DECLARE_CLASS_INHERITED(SearchParametersIVF, SearchParameters)
+FAISS_DECLARE_DESTRUCTOR(SearchParametersIVF)
+FAISS_DECLARE_SEARCH_PARAMETERS_DOWNCAST(SearchParametersIVF)
+
+int faiss_SearchParametersIVF_new(FaissSearchParametersIVF** p_sp);
+int faiss_SearchParametersIVF_new_with(
+ FaissSearchParametersIVF** p_sp,
+ FaissIDSelector* sel,
+ size_t nprobe,
+ size_t max_codes);
+
+FAISS_DECLARE_GETTER(SearchParametersIVF, const FaissIDSelector*, sel)
+FAISS_DECLARE_GETTER_SETTER(SearchParametersIVF, size_t, nprobe)
+FAISS_DECLARE_GETTER_SETTER(SearchParametersIVF, size_t, max_codes)
+
+/** Index based on a inverted file (IVF)
+ *
+ * In the inverted file, the quantizer (an Index instance) provides a
+ * quantization index for each vector to be added. The quantization
+ * index maps to a list (aka inverted list or posting list), where the
+ * id of the vector is then stored.
+ *
+ * At search time, the vector to be searched is also quantized, and
+ * only the list corresponding to the quantization index is
+ * searched. This speeds up the search by making it
+ * non-exhaustive. This can be relaxed using multi-probe search: a few
+ * (nprobe) quantization indices are selected and several inverted
+ * lists are visited.
+ *
+ * Sub-classes implement a post-filtering of the index that refines
+ * the distance estimation from the query to database vectors.
+ */
+FAISS_DECLARE_CLASS_INHERITED(IndexIVF, Index)
+FAISS_DECLARE_DESTRUCTOR(IndexIVF)
+FAISS_DECLARE_INDEX_DOWNCAST(IndexIVF)
+
+/// number of possible key values
+FAISS_DECLARE_GETTER(IndexIVF, size_t, nlist)
+/// number of probes at query time
+FAISS_DECLARE_GETTER_SETTER(IndexIVF, size_t, nprobe)
+/// quantizer that maps vectors to inverted lists
+FAISS_DECLARE_GETTER(IndexIVF, FaissIndex*, quantizer)
+/**
+ * = 0: use the quantizer as index in a kmeans training
+ * = 1: just pass on the training set to the train() of the quantizer
+ * = 2: kmeans training on a flat index + add the centroids to the quantizer
+ */
+FAISS_DECLARE_GETTER(IndexIVF, char, quantizer_trains_alone)
+
+/// whether object owns the quantizer
+FAISS_DECLARE_GETTER_SETTER(IndexIVF, int, own_fields)
+
+/** moves the entries from another dataset to self. On output,
+ * other is empty. add_id is added to all moved ids (for
+ * sequential ids, this would be this->ntotal */
+int faiss_IndexIVF_merge_from(
+ FaissIndexIVF* index,
+ FaissIndexIVF* other,
+ idx_t add_id);
+
+/** copy a subset of the entries index to the other index
+ *
+ * if subset_type == 0: copies ids in [a1, a2)
+ * if subset_type == 1: copies ids if id % a1 == a2
+ * if subset_type == 2: copies inverted lists such that a1
+ * elements are left before and a2 elements are after
+ */
+int faiss_IndexIVF_copy_subset_to(
+ const FaissIndexIVF* index,
+ FaissIndexIVF* other,
+ int subset_type,
+ idx_t a1,
+ idx_t a2);
+
+/** search a set of vectors, that are pre-quantized by the IVF
+ * quantizer. Fill in the corresponding heaps with the query
+ * results. search() calls this.
+ *
+ * @param n nb of vectors to query
+ * @param x query vectors, size nx * d
+ * @param assign coarse quantization indices, size nx * nprobe
+ * @param centroid_dis
+ * distances to coarse centroids, size nx * nprobe
+ * @param distance
+ * output distances, size n * k
+ * @param labels output labels, size n * k
+ * @param store_pairs store inv list index + inv list offset
+ * instead in upper/lower 32 bit of result,
+ * instead of ids (used for reranking).
+ */
+int faiss_IndexIVF_search_preassigned(
+ const FaissIndexIVF* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ int store_pairs);
+
+size_t faiss_IndexIVF_get_list_size(const FaissIndexIVF* index, size_t list_no);
+
+/** initialize a direct map
+ *
+ * @param new_maintain_direct_map if true, create a direct map,
+ * else clear it
+ */
+int faiss_IndexIVF_make_direct_map(
+ FaissIndexIVF* index,
+ int new_maintain_direct_map);
+
+/** Check the inverted lists' imbalance factor.
+ *
+ * 1= perfectly balanced, >1: imbalanced
+ */
+double faiss_IndexIVF_imbalance_factor(const FaissIndexIVF* index);
+
+/// display some stats about the inverted lists of the index
+void faiss_IndexIVF_print_stats(const FaissIndexIVF* index);
+
+/// Get the IDs in an inverted list. IDs are written to `invlist`, which must be
+/// large enough
+//// to accommodate the full list.
+///
+/// @param list_no the list ID
+/// @param invlist output pointer to a slice of memory, at least as long as the
+/// list's size
+/// @see faiss_IndexIVF_get_list_size(size_t)
+void faiss_IndexIVF_invlists_get_ids(
+ const FaissIndexIVF* index,
+ size_t list_no,
+ idx_t* invlist);
+
+int faiss_IndexIVF_train_encoder(
+ FaissIndexIVF* index,
+ idx_t n,
+ const float* x,
+ const idx_t* assign);
+
+typedef struct FaissIndexIVFStats {
+ size_t nq; // nb of queries run
+ size_t nlist; // nb of inverted lists scanned
+ size_t ndis; // nb of distances computed
+ size_t nheap_updates; // nb of times the heap was updated
+ double quantization_time; // time spent quantizing vectors (in ms)
+ double search_time; // time spent searching lists (in ms)
+} FaissIndexIVFStats;
+
+void faiss_IndexIVFStats_reset(FaissIndexIVFStats* stats);
+
+inline void faiss_IndexIVFStats_init(FaissIndexIVFStats* stats) {
+ faiss_IndexIVFStats_reset(stats);
+}
+
+/// global var that collects all statists
+FaissIndexIVFStats* faiss_get_indexIVF_stats();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexLSH_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexLSH_c.cpp
new file mode 100644
index 0000000..0bd52f5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexLSH_c.cpp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexLSH_c.h"
+#include <faiss/IndexLSH.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexLSH;
+
+DEFINE_DESTRUCTOR(IndexLSH)
+DEFINE_INDEX_DOWNCAST(IndexLSH)
+
+DEFINE_GETTER(IndexLSH, int, nbits)
+DEFINE_GETTER(IndexLSH, int, code_size)
+DEFINE_GETTER_PERMISSIVE(IndexLSH, int, rotate_data)
+DEFINE_GETTER_PERMISSIVE(IndexLSH, int, train_thresholds)
+
+int faiss_IndexLSH_new(FaissIndexLSH** p_index, idx_t d, int nbits) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexLSH*>(new IndexLSH(d, nbits));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexLSH_new_with_options(
+ FaissIndexLSH** p_index,
+ idx_t d,
+ int nbits,
+ int rotate_data,
+ int train_thresholds) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexLSH*>(new IndexLSH(
+ d,
+ nbits,
+ static_cast<bool>(rotate_data),
+ static_cast<bool>(train_thresholds)));
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexLSH_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexLSH_c.h
new file mode 100644
index 0000000..252dbf1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexLSH_c.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef INDEX_LSH_C_H
+#define INDEX_LSH_C_H
+
+#include "Clustering_c.h"
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** The sign of each vector component is put in a binary signature */
+FAISS_DECLARE_CLASS_INHERITED(IndexLSH, Index)
+FAISS_DECLARE_DESTRUCTOR(IndexLSH)
+FAISS_DECLARE_INDEX_DOWNCAST(IndexLSH)
+
+FAISS_DECLARE_GETTER(IndexLSH, int, nbits)
+FAISS_DECLARE_GETTER(IndexLSH, int, code_size)
+FAISS_DECLARE_GETTER(IndexLSH, int, rotate_data)
+FAISS_DECLARE_GETTER(IndexLSH, int, train_thresholds)
+
+int faiss_IndexLSH_new(FaissIndexLSH** p_index, idx_t d, int nbits);
+
+int faiss_IndexLSH_new_with_options(
+ FaissIndexLSH** p_index,
+ idx_t d,
+ int nbits,
+ int rotate_data,
+ int train_thresholds);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexPreTransform_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexPreTransform_c.cpp
new file mode 100644
index 0000000..5695564
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexPreTransform_c.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexPreTransform_c.h"
+#include <faiss/IndexPreTransform.h>
+#include <faiss/VectorTransform.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexPreTransform;
+using faiss::VectorTransform;
+
+extern "C" {
+
+DEFINE_DESTRUCTOR(IndexPreTransform)
+DEFINE_INDEX_DOWNCAST(IndexPreTransform)
+
+DEFINE_GETTER_PERMISSIVE(IndexPreTransform, FaissIndex*, index)
+
+DEFINE_GETTER(IndexPreTransform, int, own_fields)
+DEFINE_SETTER(IndexPreTransform, int, own_fields)
+
+int faiss_IndexPreTransform_new(FaissIndexPreTransform** p_index) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexPreTransform*>(
+ new IndexPreTransform());
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexPreTransform_new_with(
+ FaissIndexPreTransform** p_index,
+ FaissIndex* index) {
+ try {
+ auto ind = reinterpret_cast<Index*>(index);
+ *p_index = reinterpret_cast<FaissIndexPreTransform*>(
+ new IndexPreTransform(ind));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexPreTransform_new_with_transform(
+ FaissIndexPreTransform** p_index,
+ FaissVectorTransform* ltrans,
+ FaissIndex* index) {
+ try {
+ auto lt = reinterpret_cast<VectorTransform*>(ltrans);
+ auto ind = reinterpret_cast<Index*>(index);
+ *p_index = reinterpret_cast<FaissIndexPreTransform*>(
+ new IndexPreTransform(lt, ind));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexPreTransform_prepend_transform(
+ FaissIndexPreTransform* index,
+ FaissVectorTransform* ltrans) {
+ try {
+ auto lt = reinterpret_cast<VectorTransform*>(ltrans);
+ reinterpret_cast<IndexPreTransform*>(index)->prepend_transform(lt);
+ }
+ CATCH_AND_HANDLE
+}
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexPreTransform_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexPreTransform_c.h
new file mode 100644
index 0000000..2ac0f6b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexPreTransform_c.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_PRETRANSFORM_C_H
+#define FAISS_INDEX_PRETRANSFORM_C_H
+
+#include "Index_c.h"
+#include "VectorTransform_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Index that applies a LinearTransform transform on vectors before
+ * handing them over to a sub-index */
+FAISS_DECLARE_CLASS_INHERITED(IndexPreTransform, Index)
+FAISS_DECLARE_DESTRUCTOR(IndexPreTransform)
+FAISS_DECLARE_INDEX_DOWNCAST(IndexPreTransform)
+
+FAISS_DECLARE_GETTER(IndexPreTransform, FaissIndex*, index)
+FAISS_DECLARE_GETTER_SETTER(IndexPreTransform, int, own_fields)
+
+int faiss_IndexPreTransform_new(FaissIndexPreTransform** p_index);
+
+int faiss_IndexPreTransform_new_with(
+ FaissIndexPreTransform** p_index,
+ FaissIndex* index);
+
+int faiss_IndexPreTransform_new_with_transform(
+ FaissIndexPreTransform** p_index,
+ FaissVectorTransform* ltrans,
+ FaissIndex* index);
+
+int faiss_IndexPreTransform_prepend_transform(
+ FaissIndexPreTransform* index,
+ FaissVectorTransform* ltrans);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexReplicas_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexReplicas_c.cpp
new file mode 100644
index 0000000..37c7849
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexReplicas_c.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include "IndexReplicas_c.h"
+#include <faiss/IndexReplicas.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexReplicas;
+
+DEFINE_DESTRUCTOR(IndexReplicas)
+
+DEFINE_GETTER(IndexReplicas, int, own_indices)
+DEFINE_SETTER(IndexReplicas, int, own_indices)
+
+int faiss_IndexReplicas_new(FaissIndexReplicas** p_index, idx_t d) {
+ try {
+ auto out = new IndexReplicas(d);
+ *p_index = reinterpret_cast<FaissIndexReplicas*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexReplicas_new_with_options(
+ FaissIndexReplicas** p_index,
+ idx_t d,
+ int threaded) {
+ try {
+ auto out = new IndexReplicas(d, static_cast<bool>(threaded));
+ *p_index = reinterpret_cast<FaissIndexReplicas*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexReplicas_add_replica(
+ FaissIndexReplicas* index,
+ FaissIndex* replica) {
+ try {
+ reinterpret_cast<IndexReplicas*>(index)->add_replica(
+ reinterpret_cast<Index*>(replica));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexReplicas_remove_replica(
+ FaissIndexReplicas* index,
+ FaissIndex* replica) {
+ try {
+ reinterpret_cast<IndexReplicas*>(index)->remove_replica(
+ reinterpret_cast<Index*>(replica));
+ }
+ CATCH_AND_HANDLE
+}
+
+FaissIndex* faiss_IndexReplicas_at(FaissIndexReplicas* index, int i) {
+ auto replica = reinterpret_cast<IndexReplicas*>(index)->at(i);
+ return reinterpret_cast<FaissIndex*>(replica);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexReplicas_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexReplicas_c.h
new file mode 100644
index 0000000..179b18c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexReplicas_c.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef INDEXREPLICAS_C_H
+#define INDEXREPLICAS_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Index that concatenates the results from several sub-indexes
+ */
+FAISS_DECLARE_CLASS_INHERITED(IndexReplicas, Index)
+FAISS_DECLARE_DESTRUCTOR(IndexReplicas)
+
+FAISS_DECLARE_GETTER_SETTER(IndexReplicas, int, own_fields)
+
+int faiss_IndexReplicas_new(FaissIndexReplicas** p_index, idx_t d);
+
+int faiss_IndexReplicas_new_with_options(
+ FaissIndexReplicas** p_index,
+ idx_t d,
+ int threaded);
+
+int faiss_IndexReplicas_add_replica(
+ FaissIndexReplicas* index,
+ FaissIndex* replica);
+
+int faiss_IndexReplicas_remove_replica(
+ FaissIndexReplicas* index,
+ FaissIndex* replica);
+
+FaissIndex* faiss_IndexReplicas_at(FaissIndexReplicas* index, int i);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexScalarQuantizer_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexScalarQuantizer_c.cpp
new file mode 100644
index 0000000..2d27b43
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexScalarQuantizer_c.cpp
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "IndexScalarQuantizer_c.h"
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexIVFScalarQuantizer;
+using faiss::IndexScalarQuantizer;
+
+DEFINE_DESTRUCTOR(IndexScalarQuantizer)
+DEFINE_INDEX_DOWNCAST(IndexScalarQuantizer)
+
+int faiss_IndexScalarQuantizer_new(FaissIndexScalarQuantizer** p_index) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexScalarQuantizer*>(
+ new IndexScalarQuantizer());
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexScalarQuantizer_new_with(
+ FaissIndexScalarQuantizer** p_index,
+ idx_t d,
+ FaissQuantizerType qt,
+ FaissMetricType metric) {
+ try {
+ IndexScalarQuantizer* index = new IndexScalarQuantizer(
+ d,
+ static_cast<faiss::ScalarQuantizer::QuantizerType>(qt),
+ static_cast<faiss::MetricType>(metric));
+ *p_index = reinterpret_cast<FaissIndexScalarQuantizer*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(IndexIVFScalarQuantizer)
+DEFINE_INDEX_DOWNCAST(IndexIVFScalarQuantizer)
+
+/// quantizer that maps vectors to inverted lists
+DEFINE_GETTER_PERMISSIVE(IndexIVFScalarQuantizer, FaissIndex*, quantizer)
+
+/// number of possible key values
+DEFINE_GETTER(IndexIVFScalarQuantizer, size_t, nlist)
+/// number of probes at query time
+DEFINE_GETTER(IndexIVFScalarQuantizer, size_t, nprobe)
+DEFINE_SETTER(IndexIVFScalarQuantizer, size_t, nprobe)
+
+/// whether object owns the quantizer
+DEFINE_GETTER(IndexIVFScalarQuantizer, int, own_fields)
+DEFINE_SETTER(IndexIVFScalarQuantizer, int, own_fields)
+
+int faiss_IndexIVFScalarQuantizer_new_with(
+ FaissIndexIVFScalarQuantizer** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist,
+ FaissQuantizerType qt) {
+ try {
+ auto q = reinterpret_cast<Index*>(quantizer);
+ auto qt_ = static_cast<faiss::ScalarQuantizer::QuantizerType>(qt);
+ IndexIVFScalarQuantizer* index =
+ new IndexIVFScalarQuantizer(q, d, nlist, qt_);
+ *p_index = reinterpret_cast<FaissIndexIVFScalarQuantizer*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVFScalarQuantizer_new_with_metric(
+ FaissIndexIVFScalarQuantizer** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist,
+ FaissQuantizerType qt,
+ FaissMetricType metric,
+ int encode_residual) {
+ try {
+ auto q = reinterpret_cast<Index*>(quantizer);
+ auto mt = static_cast<faiss::MetricType>(metric);
+ auto er = static_cast<bool>(encode_residual);
+ auto qt_ = static_cast<faiss::ScalarQuantizer::QuantizerType>(qt);
+ IndexIVFScalarQuantizer* index =
+ new IndexIVFScalarQuantizer(q, d, nlist, qt_, mt, er);
+ *p_index = reinterpret_cast<FaissIndexIVFScalarQuantizer*>(index);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIVFScalarQuantizer_add_core(
+ FaissIndexIVFScalarQuantizer* index,
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx) {
+ try {
+ reinterpret_cast<IndexIVFScalarQuantizer*>(index)->add_core(
+ n, x, xids, precomputed_idx);
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexScalarQuantizer_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexScalarQuantizer_c.h
new file mode 100644
index 0000000..d0a4d10
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexScalarQuantizer_c.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_SCALAR_QUANTIZER_C_H
+#define FAISS_INDEX_SCALAR_QUANTIZER_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum FaissQuantizerType {
+ QT_8bit, ///< 8 bits per component
+ QT_4bit, ///< 4 bits per component
+ QT_8bit_uniform, ///< same, shared range for all dimensions
+ QT_4bit_uniform,
+ QT_fp16,
+ QT_8bit_direct, ///< fast indexing of uint8s
+ QT_6bit, ///< 6 bits per component
+ QT_bf16,
+ QT_8bit_direct_signed, ///< fast indexing of signed int8s ranging from [-128
+ ///< to 127]
+} FaissQuantizerType;
+
+// forward declaration
+typedef enum FaissMetricType FaissMetricType;
+
+/** Opaque type for IndexScalarQuantizer */
+FAISS_DECLARE_CLASS_INHERITED(IndexScalarQuantizer, Index)
+
+int faiss_IndexScalarQuantizer_new(FaissIndexScalarQuantizer** p_index);
+
+int faiss_IndexScalarQuantizer_new_with(
+ FaissIndexScalarQuantizer** p_index,
+ idx_t d,
+ FaissQuantizerType qt,
+ FaissMetricType metric);
+
+FAISS_DECLARE_INDEX_DOWNCAST(IndexScalarQuantizer)
+
+FAISS_DECLARE_DESTRUCTOR(IndexScalarQuantizer)
+
+/** Opaque type for IndexIVFScalarQuantizer */
+FAISS_DECLARE_CLASS_INHERITED(IndexIVFScalarQuantizer, Index)
+
+FAISS_DECLARE_INDEX_DOWNCAST(IndexIVFScalarQuantizer)
+
+FAISS_DECLARE_DESTRUCTOR(IndexIVFScalarQuantizer)
+
+int faiss_IndexIVFScalarQuantizer_new(FaissIndexIVFScalarQuantizer** p_index);
+
+int faiss_IndexIVFScalarQuantizer_new_with(
+ FaissIndexIVFScalarQuantizer** p_index,
+ FaissIndex* quantizer,
+ idx_t d,
+ size_t nlist,
+ FaissQuantizerType qt);
+
+int faiss_IndexIVFScalarQuantizer_new_with_metric(
+ FaissIndexIVFScalarQuantizer** p_index,
+ FaissIndex* quantizer,
+ size_t d,
+ size_t nlist,
+ FaissQuantizerType qt,
+ FaissMetricType metric,
+ int encode_residual);
+
+/// number of possible key values
+FAISS_DECLARE_GETTER(IndexIVFScalarQuantizer, size_t, nlist)
+/// number of probes at query time
+FAISS_DECLARE_GETTER_SETTER(IndexIVFScalarQuantizer, size_t, nprobe)
+/// quantizer that maps vectors to inverted lists
+FAISS_DECLARE_GETTER(IndexIVFScalarQuantizer, FaissIndex*, quantizer)
+
+/// whether object owns the quantizer
+FAISS_DECLARE_GETTER_SETTER(IndexIVFScalarQuantizer, int, own_fields)
+
+int faiss_IndexIVFScalarQuantizer_add_core(
+ FaissIndexIVFScalarQuantizer* index,
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexShards_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexShards_c.cpp
new file mode 100644
index 0000000..9d9c95d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexShards_c.cpp
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include "IndexShards_c.h"
+#include <faiss/IndexShards.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexShards;
+
+DEFINE_DESTRUCTOR(IndexShards)
+
+DEFINE_GETTER(IndexShards, int, own_indices)
+DEFINE_SETTER(IndexShards, int, own_indices)
+
+DEFINE_GETTER(IndexShards, int, successive_ids)
+DEFINE_SETTER(IndexShards, int, successive_ids)
+
+int faiss_IndexShards_new(FaissIndexShards** p_index, idx_t d) {
+ try {
+ auto out = new IndexShards(d);
+ *p_index = reinterpret_cast<FaissIndexShards*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexShards_new_with_options(
+ FaissIndexShards** p_index,
+ idx_t d,
+ int threaded,
+ int successive_ids) {
+ try {
+ auto out = new IndexShards(
+ d,
+ static_cast<bool>(threaded),
+ static_cast<bool>(successive_ids));
+ *p_index = reinterpret_cast<FaissIndexShards*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexShards_add_shard(FaissIndexShards* index, FaissIndex* shard) {
+ try {
+ reinterpret_cast<IndexShards*>(index)->add_shard(
+ reinterpret_cast<Index*>(shard));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexShards_remove_shard(FaissIndexShards* index, FaissIndex* shard) {
+ try {
+ reinterpret_cast<IndexShards*>(index)->remove_shard(
+ reinterpret_cast<Index*>(shard));
+ }
+ CATCH_AND_HANDLE
+}
+
+FaissIndex* faiss_IndexShards_at(FaissIndexShards* index, int i) {
+ auto shard = reinterpret_cast<IndexShards*>(index)->at(i);
+ return reinterpret_cast<FaissIndex*>(shard);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexShards_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexShards_c.h
new file mode 100644
index 0000000..578638d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/IndexShards_c.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef INDEXSHARDS_C_H
+#define INDEXSHARDS_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Index that concatenates the results from several sub-indexes
+ */
+FAISS_DECLARE_CLASS_INHERITED(IndexShards, Index)
+FAISS_DECLARE_DESTRUCTOR(IndexShards)
+
+FAISS_DECLARE_GETTER_SETTER(IndexShards, int, own_fields)
+FAISS_DECLARE_GETTER_SETTER(IndexShards, int, successive_ids)
+
+int faiss_IndexShards_new(FaissIndexShards** p_index, idx_t d);
+
+int faiss_IndexShards_new_with_options(
+ FaissIndexShards** p_index,
+ idx_t d,
+ int threaded,
+ int successive_ids);
+
+int faiss_IndexShards_add_shard(FaissIndexShards* index, FaissIndex* shard);
+
+int faiss_IndexShards_remove_shard(FaissIndexShards* index, FaissIndex* shard);
+
+FaissIndex* faiss_IndexShards_at(FaissIndexShards* index, int i);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/Index_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/Index_c.cpp
new file mode 100644
index 0000000..5df3c08
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/Index_c.cpp
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "Index_c.h"
+#include <faiss/Index.h>
+#include <faiss/impl/IDSelector.h>
+#include "macros_impl.h"
+
+extern "C" {
+
+DEFINE_DESTRUCTOR(SearchParameters)
+
+int faiss_SearchParameters_new(
+ FaissSearchParameters** p_sp,
+ FaissIDSelector* sel) {
+ try {
+ faiss::SearchParameters* params = new faiss::SearchParameters;
+ params->sel = reinterpret_cast<faiss::IDSelector*>(sel);
+ *p_sp = reinterpret_cast<FaissSearchParameters*>(params);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(Index)
+
+DEFINE_GETTER(Index, int, d)
+
+DEFINE_GETTER(Index, int, is_trained)
+
+DEFINE_GETTER(Index, idx_t, ntotal)
+
+DEFINE_GETTER(Index, FaissMetricType, metric_type)
+
+DEFINE_GETTER(Index, int, verbose);
+DEFINE_SETTER(Index, int, verbose);
+
+int faiss_Index_train(FaissIndex* index, idx_t n, const float* x) {
+ try {
+ reinterpret_cast<faiss::Index*>(index)->train(n, x);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_add(FaissIndex* index, idx_t n, const float* x) {
+ try {
+ reinterpret_cast<faiss::Index*>(index)->add(n, x);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_add_with_ids(
+ FaissIndex* index,
+ idx_t n,
+ const float* x,
+ const idx_t* xids) {
+ try {
+ reinterpret_cast<faiss::Index*>(index)->add_with_ids(n, x, xids);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_search(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->search(
+ n, x, k, distances, labels);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_search_with_params(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const FaissSearchParameters* params,
+ float* distances,
+ idx_t* labels) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->search(
+ n,
+ x,
+ k,
+ distances,
+ labels,
+ reinterpret_cast<const faiss::SearchParameters*>(params));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_range_search(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ float radius,
+ FaissRangeSearchResult* result) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->range_search(
+ n,
+ x,
+ radius,
+ reinterpret_cast<faiss::RangeSearchResult*>(result));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_assign(
+ FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t* labels,
+ idx_t k) {
+ try {
+ reinterpret_cast<faiss::Index*>(index)->assign(n, x, labels, k);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_reset(FaissIndex* index) {
+ try {
+ reinterpret_cast<faiss::Index*>(index)->reset();
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_remove_ids(
+ FaissIndex* index,
+ const FaissIDSelector* sel,
+ size_t* n_removed) {
+ try {
+ size_t n{reinterpret_cast<faiss::Index*>(index)->remove_ids(
+ *reinterpret_cast<const faiss::IDSelector*>(sel))};
+ if (n_removed) {
+ *n_removed = n;
+ }
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_reconstruct(const FaissIndex* index, idx_t key, float* recons) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->reconstruct(key, recons);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_reconstruct_n(
+ const FaissIndex* index,
+ idx_t i0,
+ idx_t ni,
+ float* recons) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->reconstruct_n(
+ i0, ni, recons);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_compute_residual(
+ const FaissIndex* index,
+ const float* x,
+ float* residual,
+ idx_t key) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->compute_residual(
+ x, residual, key);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_compute_residual_n(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ float* residuals,
+ const idx_t* keys) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->compute_residual_n(
+ n, x, residuals, keys);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_sa_code_size(const FaissIndex* index, size_t* size) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->sa_code_size();
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_sa_encode(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ uint8_t* bytes) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->sa_encode(n, x, bytes);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_Index_sa_decode(
+ const FaissIndex* index,
+ idx_t n,
+ const uint8_t* bytes,
+ float* x) {
+ try {
+ reinterpret_cast<const faiss::Index*>(index)->sa_decode(n, bytes, x);
+ }
+ CATCH_AND_HANDLE
+}
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/Index_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/Index_c.h
new file mode 100644
index 0000000..81a3da7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/Index_c.h
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_C_H
+#define FAISS_INDEX_C_H
+
+#include <stddef.h>
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// forward declaration required here
+FAISS_DECLARE_CLASS(RangeSearchResult)
+
+// typedef struct FaissRangeSearchResult_H FaissRangeSearchResult;
+typedef struct FaissIDSelector_H FaissIDSelector;
+
+/// Some algorithms support both an inner product version and a L2 search
+/// version.
+typedef enum FaissMetricType {
+ METRIC_INNER_PRODUCT = 0, ///< maximum inner product search
+ METRIC_L2 = 1, ///< squared L2 search
+ METRIC_L1, ///< L1 (aka cityblock)
+ METRIC_Linf, ///< infinity distance
+ METRIC_Lp, ///< L_p distance, p is given by metric_arg
+
+ /// some additional metrics defined in scipy.spatial.distance
+ METRIC_Canberra = 20,
+ METRIC_BrayCurtis,
+ METRIC_JensenShannon,
+} FaissMetricType;
+
+FAISS_DECLARE_CLASS(SearchParameters)
+FAISS_DECLARE_DESTRUCTOR(SearchParameters)
+
+int faiss_SearchParameters_new(
+ FaissSearchParameters** p_sp,
+ FaissIDSelector* sel);
+
+/// Opaque type for referencing to an index object
+FAISS_DECLARE_CLASS(Index)
+FAISS_DECLARE_DESTRUCTOR(Index)
+
+/// Getter for d
+FAISS_DECLARE_GETTER(Index, int, d)
+
+/// Getter for is_trained
+FAISS_DECLARE_GETTER(Index, int, is_trained)
+
+/// Getter for ntotal
+FAISS_DECLARE_GETTER(Index, idx_t, ntotal)
+
+/// Getter for metric_type
+FAISS_DECLARE_GETTER(Index, FaissMetricType, metric_type)
+
+FAISS_DECLARE_GETTER_SETTER(Index, int, verbose)
+
+/** Perform training on a representative set of vectors
+ *
+ * @param index opaque pointer to index object
+ * @param n nb of training vectors
+ * @param x training vectors, size n * d
+ */
+int faiss_Index_train(FaissIndex* index, idx_t n, const float* x);
+
+/** Add n vectors of dimension d to the index.
+ *
+ * Vectors are implicitly assigned labels ntotal .. ntotal + n - 1
+ * This function slices the input vectors in chunks smaller than
+ * blocksize_add and calls add_core.
+ * @param index opaque pointer to index object
+ * @param x input matrix, size n * d
+ */
+int faiss_Index_add(FaissIndex* index, idx_t n, const float* x);
+
+/** Same as add, but stores xids instead of sequential ids.
+ *
+ * The default implementation fails with an assertion, as it is
+ * not supported by all indexes.
+ *
+ * @param index opaque pointer to index object
+ * @param xids if non-null, ids to store for the vectors (size n)
+ */
+int faiss_Index_add_with_ids(
+ FaissIndex* index,
+ idx_t n,
+ const float* x,
+ const idx_t* xids);
+
+/** query n vectors of dimension d to the index.
+ *
+ * return at most k vectors. If there are not enough results for a
+ * query, the result array is padded with -1s.
+ *
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param labels output labels of the NNs, size n*k
+ * @param distances output pairwise distances, size n*k
+ */
+int faiss_Index_search(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels);
+
+/**
+ * query n vectors of dimension d with search parameters to the index.
+ *
+ * return at most k vectors. If there are not enough results for a query,
+ * the result is padded with -1s.
+ *
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param params input params to modify how search is done
+ * @param labels output labels of the NNs, size n*k
+ * @param distances output pairwise distances, size n*k
+ */
+int faiss_Index_search_with_params(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const FaissSearchParameters* params,
+ float* distances,
+ idx_t* labels);
+
+/** query n vectors of dimension d to the index.
+ *
+ * return all vectors with distance < radius. Note that many
+ * indexes do not implement the range_search (only the k-NN search
+ * is mandatory).
+ *
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param radius search radius
+ * @param result result table
+ */
+int faiss_Index_range_search(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ float radius,
+ FaissRangeSearchResult* result);
+
+/** return the indexes of the k vectors closest to the query x.
+ *
+ * This function is identical as search but only return labels of neighbors.
+ * @param index opaque pointer to index object
+ * @param x input vectors to search, size n * d
+ * @param labels output labels of the NNs, size n*k
+ */
+int faiss_Index_assign(
+ FaissIndex* index,
+ idx_t n,
+ const float* x,
+ idx_t* labels,
+ idx_t k);
+
+/** removes all elements from the database.
+ * @param index opaque pointer to index object
+ */
+int faiss_Index_reset(FaissIndex* index);
+
+/** removes IDs from the index. Not supported by all indexes
+ * @param index opaque pointer to index object
+ * @param nremove output for the number of IDs removed
+ */
+int faiss_Index_remove_ids(
+ FaissIndex* index,
+ const FaissIDSelector* sel,
+ size_t* n_removed);
+
+/** Reconstruct a stored vector (or an approximation if lossy coding)
+ *
+ * this function may not be defined for some indexes
+ * @param index opaque pointer to index object
+ * @param key id of the vector to reconstruct
+ * @param recons reconstructed vector (size d)
+ */
+int faiss_Index_reconstruct(const FaissIndex* index, idx_t key, float* recons);
+
+/** Reconstruct vectors i0 to i0 + ni - 1
+ *
+ * this function may not be defined for some indexes
+ * @param index opaque pointer to index object
+ * @param recons reconstructed vector (size ni * d)
+ */
+int faiss_Index_reconstruct_n(
+ const FaissIndex* index,
+ idx_t i0,
+ idx_t ni,
+ float* recons);
+
+/** Computes a residual vector after indexing encoding.
+ *
+ * The residual vector is the difference between a vector and the
+ * reconstruction that can be decoded from its representation in
+ * the index. The residual can be used for multiple-stage indexing
+ * methods, like IndexIVF's methods.
+ *
+ * @param index opaque pointer to index object
+ * @param x input vector, size d
+ * @param residual output residual vector, size d
+ * @param key encoded index, as returned by search and assign
+ */
+int faiss_Index_compute_residual(
+ const FaissIndex* index,
+ const float* x,
+ float* residual,
+ idx_t key);
+
+/** Computes a residual vector after indexing encoding.
+ *
+ * The residual vector is the difference between a vector and the
+ * reconstruction that can be decoded from its representation in
+ * the index. The residual can be used for multiple-stage indexing
+ * methods, like IndexIVF's methods.
+ *
+ * @param index opaque pointer to index object
+ * @param n number of vectors
+ * @param x input vector, size (n x d)
+ * @param residuals output residual vectors, size (n x d)
+ * @param keys encoded index, as returned by search and assign
+ */
+int faiss_Index_compute_residual_n(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ float* residuals,
+ const idx_t* keys);
+
+/* The standalone codec interface */
+
+/** The size of the produced codes in bytes.
+ *
+ * @param index opaque pointer to index object
+ * @param size the returned size in bytes
+ */
+int faiss_Index_sa_code_size(const FaissIndex* index, size_t* size);
+
+/** encode a set of vectors
+ *
+ * @param index opaque pointer to index object
+ * @param n number of vectors
+ * @param x input vectors, size n * d
+ * @param bytes output encoded vectors, size n * sa_code_size()
+ */
+int faiss_Index_sa_encode(
+ const FaissIndex* index,
+ idx_t n,
+ const float* x,
+ uint8_t* bytes);
+
+/** decode a set of vectors
+ *
+ * @param index opaque pointer to index object
+ * @param n number of vectors
+ * @param bytes input encoded vectors, size n * sa_code_size()
+ * @param x output vectors, size n * d
+ */
+int faiss_Index_sa_decode(
+ const FaissIndex* index,
+ idx_t n,
+ const uint8_t* bytes,
+ float* x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/MetaIndexes_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/MetaIndexes_c.cpp
new file mode 100644
index 0000000..f0a84a4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/MetaIndexes_c.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "MetaIndexes_c.h"
+#include <faiss/MetaIndexes.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexIDMap;
+using faiss::IndexIDMap2;
+
+DEFINE_GETTER(IndexIDMap, int, own_fields)
+DEFINE_SETTER(IndexIDMap, int, own_fields)
+
+DEFINE_INDEX_DOWNCAST(IndexIDMap)
+
+DEFINE_GETTER(IndexIDMap2, int, own_fields)
+DEFINE_SETTER(IndexIDMap2, int, own_fields)
+
+DEFINE_INDEX_DOWNCAST(IndexIDMap2)
+
+int faiss_IndexIDMap_new(FaissIndexIDMap** p_index, FaissIndex* index) {
+ try {
+ auto out = new IndexIDMap(reinterpret_cast<Index*>(index));
+ *p_index = reinterpret_cast<FaissIndexIDMap*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+void faiss_IndexIDMap_id_map(
+ FaissIndexIDMap* index,
+ idx_t** p_id_map,
+ size_t* p_size) {
+ auto idx = reinterpret_cast<IndexIDMap*>(index);
+ if (p_id_map)
+ *p_id_map = idx->id_map.data();
+ if (p_size)
+ *p_size = idx->id_map.size();
+}
+
+FaissIndex* faiss_IndexIDMap_sub_index(FaissIndexIDMap* index) {
+ auto idx = reinterpret_cast<IndexIDMap*>(index);
+ return (FaissIndex*)reinterpret_cast<Index*>(idx->index);
+}
+
+int faiss_IndexIDMap2_new(FaissIndexIDMap2** p_index, FaissIndex* index) {
+ try {
+ auto out = new IndexIDMap2(reinterpret_cast<Index*>(index));
+ *p_index = reinterpret_cast<FaissIndexIDMap2*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IndexIDMap2_construct_rev_map(FaissIndexIDMap2* index) {
+ try {
+ reinterpret_cast<IndexIDMap2*>(index)->construct_rev_map();
+ }
+ CATCH_AND_HANDLE
+}
+
+void faiss_IndexIDMap2_id_map(
+ FaissIndexIDMap2* index,
+ idx_t** p_id_map,
+ size_t* p_size) {
+ auto idx = reinterpret_cast<IndexIDMap2*>(index);
+ if (p_id_map)
+ *p_id_map = idx->id_map.data();
+ if (p_size)
+ *p_size = idx->id_map.size();
+}
+
+FaissIndex* faiss_IndexIDMap2_sub_index(FaissIndexIDMap2* index) {
+ auto idx = reinterpret_cast<IndexIDMap2*>(index);
+ return (FaissIndex*)reinterpret_cast<Index*>(idx->index);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/MetaIndexes_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/MetaIndexes_c.h
new file mode 100644
index 0000000..29f483a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/MetaIndexes_c.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef METAINDEXES_C_H
+#define METAINDEXES_C_H
+
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Index that translates search results to ids */
+FAISS_DECLARE_CLASS_INHERITED(IndexIDMap, Index)
+
+FAISS_DECLARE_GETTER_SETTER(IndexIDMap, int, own_fields)
+
+int faiss_IndexIDMap_new(FaissIndexIDMap** p_index, FaissIndex* index);
+
+/** attempt a dynamic cast to a IDMap, thus checking
+ * check whether the underlying index type is `IndexIDMap`.
+ *
+ * @param index opaque pointer to index object
+ * @return the same pointer if the index is a IDMap index, NULL otherwise
+ */
+FAISS_DECLARE_INDEX_DOWNCAST(IndexIDMap)
+
+/** get a pointer to the index map's internal ID vector (the `id_map` field).
+ * The outputs of this function become invalid after any operation that can
+ * modify the index.
+ *
+ * @param index opaque pointer to index object
+ * @param p_id_map output, the pointer to the beginning of `id_map`.
+ * @param p_size output, the current length of `id_map`.
+ */
+void faiss_IndexIDMap_id_map(
+ FaissIndexIDMap* index,
+ idx_t** p_id_map,
+ size_t* p_size);
+
+/** get a pointer to the sub-index (the `index` field).
+ * The outputs of this function become invalid after any operation that can
+ * modify the index.
+ *
+ * @param index opaque pointer to index object
+ */
+FaissIndex* faiss_IndexIDMap_sub_index(FaissIndexIDMap* index);
+
+/** same as IndexIDMap but also provides an efficient reconstruction
+ implementation via a 2-way index */
+FAISS_DECLARE_CLASS_INHERITED(IndexIDMap2, Index)
+
+FAISS_DECLARE_GETTER_SETTER(IndexIDMap2, int, own_fields)
+
+int faiss_IndexIDMap2_new(FaissIndexIDMap2** p_index, FaissIndex* index);
+
+/// make the rev_map from scratch
+int faiss_IndexIDMap2_construct_rev_map(FaissIndexIDMap2* index);
+
+/** attempt a dynamic cast to a IDMap2, thus checking
+ * check whether the underlying index type is `IndexIDMap`.
+ *
+ * @param index opaque pointer to index object
+ * @return the same pointer if the index is a IDMap2 index, NULL otherwise
+ */
+FAISS_DECLARE_INDEX_DOWNCAST(IndexIDMap2)
+
+/** get a pointer to the index map's internal ID vector (the `id_map` field).
+ * The outputs of this function become invalid after any operation that can
+ * modify the index.
+ *
+ * @param index opaque pointer to index object
+ * @param p_id_map output, the pointer to the beginning of `id_map`.
+ * @param p_size output, the current length of `id_map`.
+ */
+void faiss_IndexIDMap2_id_map(
+ FaissIndexIDMap2* index,
+ idx_t** p_id_map,
+ size_t* p_size);
+
+/** get a pointer to the sub-index (the `index` field).
+ * The outputs of this function become invalid after any operation that can
+ * modify the index.
+ *
+ * @param index opaque pointer to index object
+ */
+FaissIndex* faiss_IndexIDMap2_sub_index(FaissIndexIDMap2* index);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/VectorTransform_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/VectorTransform_c.cpp
new file mode 100644
index 0000000..01a690a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/VectorTransform_c.cpp
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "VectorTransform_c.h"
+#include <faiss/VectorTransform.h>
+#include "macros_impl.h"
+
+extern "C" {
+
+DEFINE_DESTRUCTOR(VectorTransform)
+
+DEFINE_GETTER(VectorTransform, int, is_trained)
+
+DEFINE_GETTER(VectorTransform, int, d_in)
+
+DEFINE_GETTER(VectorTransform, int, d_out)
+
+int faiss_VectorTransform_train(
+ FaissVectorTransform* vt,
+ idx_t n,
+ const float* x) {
+ try {
+ reinterpret_cast<faiss::VectorTransform*>(vt)->train(n, x);
+ }
+ CATCH_AND_HANDLE
+}
+
+float* faiss_VectorTransform_apply(
+ const FaissVectorTransform* vt,
+ idx_t n,
+ const float* x) {
+ return reinterpret_cast<const faiss::VectorTransform*>(vt)->apply(n, x);
+}
+
+void faiss_VectorTransform_apply_noalloc(
+ const FaissVectorTransform* vt,
+ idx_t n,
+ const float* x,
+ float* xt) {
+ return reinterpret_cast<const faiss::VectorTransform*>(vt)->apply_noalloc(
+ n, x, xt);
+}
+
+void faiss_VectorTransform_reverse_transform(
+ const FaissVectorTransform* vt,
+ idx_t n,
+ const float* xt,
+ float* x) {
+ return reinterpret_cast<const faiss::VectorTransform*>(vt)
+ ->reverse_transform(n, xt, x);
+}
+
+/*********************************************
+ * LinearTransform
+ *********************************************/
+
+DEFINE_DESTRUCTOR(LinearTransform)
+
+DEFINE_GETTER(LinearTransform, int, have_bias)
+
+DEFINE_GETTER(LinearTransform, int, is_orthonormal)
+
+void faiss_LinearTransform_transform_transpose(
+ const FaissLinearTransform* vt,
+ idx_t n,
+ const float* y,
+ float* x) {
+ return reinterpret_cast<const faiss::LinearTransform*>(vt)
+ ->transform_transpose(n, y, x);
+}
+
+void faiss_LinearTransform_set_is_orthonormal(FaissLinearTransform* vt) {
+ return reinterpret_cast<faiss::LinearTransform*>(vt)->set_is_orthonormal();
+}
+
+/*********************************************
+ * RandomRotationMatrix
+ *********************************************/
+
+DEFINE_DESTRUCTOR(RandomRotationMatrix)
+
+int faiss_RandomRotationMatrix_new_with(
+ FaissRandomRotationMatrix** p_vt,
+ int d_in,
+ int d_out) {
+ try {
+ *p_vt = reinterpret_cast<FaissRandomRotationMatrix*>(
+ new faiss::RandomRotationMatrix(d_in, d_out));
+ }
+ CATCH_AND_HANDLE
+}
+
+/*********************************************
+ * PCAMatrix
+ *********************************************/
+
+DEFINE_DESTRUCTOR(PCAMatrix)
+
+int faiss_PCAMatrix_new_with(
+ FaissPCAMatrix** p_vt,
+ int d_in,
+ int d_out,
+ float eigen_power,
+ int random_rotation) {
+ try {
+ bool random_rotation_ = static_cast<bool>(random_rotation);
+ *p_vt = reinterpret_cast<FaissPCAMatrix*>(new faiss::PCAMatrix(
+ d_in, d_out, eigen_power, random_rotation_));
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER(PCAMatrix, float, eigen_power)
+
+DEFINE_GETTER(PCAMatrix, int, random_rotation)
+
+/*********************************************
+ * ITQMatrix
+ *********************************************/
+
+DEFINE_DESTRUCTOR(ITQMatrix)
+
+int faiss_ITQMatrix_new_with(FaissITQMatrix** p_vt, int d) {
+ try {
+ *p_vt = reinterpret_cast<FaissITQMatrix*>(new faiss::ITQMatrix(d));
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(ITQTransform)
+
+int faiss_ITQTransform_new_with(
+ FaissITQTransform** p_vt,
+ int d_in,
+ int d_out,
+ int do_pca) {
+ try {
+ bool do_pca_ = static_cast<bool>(do_pca);
+ *p_vt = reinterpret_cast<FaissITQTransform*>(
+ new faiss::ITQTransform(d_in, d_out, do_pca_));
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER(ITQTransform, int, do_pca)
+
+/*********************************************
+ * OPQMatrix
+ *********************************************/
+
+DEFINE_DESTRUCTOR(OPQMatrix)
+
+int faiss_OPQMatrix_new_with(FaissOPQMatrix** p_vt, int d, int M, int d2) {
+ try {
+ *p_vt = reinterpret_cast<FaissOPQMatrix*>(
+ new faiss::OPQMatrix(d, M, d2));
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER(OPQMatrix, int, verbose)
+DEFINE_SETTER(OPQMatrix, int, verbose)
+
+DEFINE_GETTER(OPQMatrix, int, niter)
+DEFINE_SETTER(OPQMatrix, int, niter)
+
+DEFINE_GETTER(OPQMatrix, int, niter_pq)
+DEFINE_SETTER(OPQMatrix, int, niter_pq)
+
+/*********************************************
+ * RemapDimensionsTransform
+ *********************************************/
+
+DEFINE_DESTRUCTOR(RemapDimensionsTransform)
+
+int faiss_RemapDimensionsTransform_new_with(
+ FaissRemapDimensionsTransform** p_vt,
+ int d_in,
+ int d_out,
+ int uniform) {
+ try {
+ bool uniform_ = static_cast<bool>(uniform);
+ *p_vt = reinterpret_cast<FaissRemapDimensionsTransform*>(
+ new faiss::RemapDimensionsTransform(d_in, d_out, uniform_));
+ }
+ CATCH_AND_HANDLE
+}
+
+/*********************************************
+ * NormalizationTransform
+ *********************************************/
+
+DEFINE_DESTRUCTOR(NormalizationTransform)
+
+int faiss_NormalizationTransform_new_with(
+ FaissNormalizationTransform** p_vt,
+ int d,
+ float norm) {
+ try {
+ *p_vt = reinterpret_cast<FaissNormalizationTransform*>(
+ new faiss::NormalizationTransform(d, norm));
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER(NormalizationTransform, float, norm)
+
+/*********************************************
+ * CenteringTransform
+ *********************************************/
+
+DEFINE_DESTRUCTOR(CenteringTransform)
+
+int faiss_CenteringTransform_new_with(FaissCenteringTransform** p_vt, int d) {
+ try {
+ *p_vt = reinterpret_cast<FaissCenteringTransform*>(
+ new faiss::CenteringTransform(d));
+ }
+ CATCH_AND_HANDLE
+}
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/VectorTransform_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/VectorTransform_c.h
new file mode 100644
index 0000000..47c29cd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/VectorTransform_c.h
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_VECTOR_TRANSFORM_C_H
+#define FAISS_VECTOR_TRANSFORM_C_H
+
+/** Defines a few objects that apply transformations to a set of
+ * vectors Often these are pre-processing steps.
+ */
+
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Opaque type for referencing to a VectorTransform object
+FAISS_DECLARE_CLASS(VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(VectorTransform)
+
+/// Getter for is_trained
+FAISS_DECLARE_GETTER(VectorTransform, int, is_trained)
+
+/// Getter for input dimension
+FAISS_DECLARE_GETTER(VectorTransform, int, d_in)
+
+/// Getter for output dimension
+FAISS_DECLARE_GETTER(VectorTransform, int, d_out)
+
+/** Perform training on a representative set of vectors
+ *
+ * @param vt opaque pointer to VectorTransform object
+ * @param n nb of training vectors
+ * @param x training vectors, size n * d
+ */
+int faiss_VectorTransform_train(
+ FaissVectorTransform* vt,
+ idx_t n,
+ const float* x);
+
+/** apply the random rotation, return new allocated matrix
+ * @param x size n * d_in
+ * @return size n * d_out
+ */
+float* faiss_VectorTransform_apply(
+ const FaissVectorTransform* vt,
+ idx_t n,
+ const float* x);
+
+/** apply transformation and result is pre-allocated
+ * @param x size n * d_in
+ * @param xt size n * d_out
+ */
+void faiss_VectorTransform_apply_noalloc(
+ const FaissVectorTransform* vt,
+ idx_t n,
+ const float* x,
+ float* xt);
+
+/// reverse transformation. May not be implemented or may return
+/// approximate result
+void faiss_VectorTransform_reverse_transform(
+ const FaissVectorTransform* vt,
+ idx_t n,
+ const float* xt,
+ float* x);
+
+/// Opaque type for referencing to a LinearTransform object
+FAISS_DECLARE_CLASS_INHERITED(LinearTransform, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(LinearTransform)
+
+/// compute x = A^T * (x - b)
+/// is reverse transform if A has orthonormal lines
+void faiss_LinearTransform_transform_transpose(
+ const FaissLinearTransform* vt,
+ idx_t n,
+ const float* y,
+ float* x);
+
+/// compute A^T * A to set the is_orthonormal flag
+void faiss_LinearTransform_set_is_orthonormal(FaissLinearTransform* vt);
+
+/// Getter for have_bias
+FAISS_DECLARE_GETTER(LinearTransform, int, have_bias)
+
+/// Getter for is_orthonormal
+FAISS_DECLARE_GETTER(LinearTransform, int, is_orthonormal)
+
+FAISS_DECLARE_CLASS_INHERITED(RandomRotationMatrix, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(RandomRotationMatrix)
+
+int faiss_RandomRotationMatrix_new_with(
+ FaissRandomRotationMatrix** p_vt,
+ int d_in,
+ int d_out);
+
+FAISS_DECLARE_CLASS_INHERITED(PCAMatrix, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(PCAMatrix)
+
+int faiss_PCAMatrix_new_with(
+ FaissPCAMatrix** p_vt,
+ int d_in,
+ int d_out,
+ float eigen_power,
+ int random_rotation);
+
+/// Getter for eigen_power
+FAISS_DECLARE_GETTER(PCAMatrix, float, eigen_power)
+
+/// Getter for random_rotation
+FAISS_DECLARE_GETTER(PCAMatrix, int, random_rotation)
+
+FAISS_DECLARE_CLASS_INHERITED(ITQMatrix, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(ITQMatrix)
+
+int faiss_ITQMatrix_new_with(FaissITQMatrix** p_vt, int d);
+
+FAISS_DECLARE_CLASS_INHERITED(ITQTransform, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(ITQTransform)
+
+int faiss_ITQTransform_new_with(
+ FaissITQTransform** p_vt,
+ int d_in,
+ int d_out,
+ int do_pca);
+
+/// Getter for do_pca
+FAISS_DECLARE_GETTER(ITQTransform, int, do_pca)
+
+FAISS_DECLARE_CLASS_INHERITED(OPQMatrix, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(OPQMatrix)
+
+int faiss_OPQMatrix_new_with(FaissOPQMatrix** p_vt, int d, int M, int d2);
+
+FAISS_DECLARE_GETTER_SETTER(OPQMatrix, int, verbose)
+FAISS_DECLARE_GETTER_SETTER(OPQMatrix, int, niter)
+FAISS_DECLARE_GETTER_SETTER(OPQMatrix, int, niter_pq)
+
+FAISS_DECLARE_CLASS_INHERITED(RemapDimensionsTransform, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(RemapDimensionsTransform)
+
+int faiss_RemapDimensionsTransform_new_with(
+ FaissRemapDimensionsTransform** p_vt,
+ int d_in,
+ int d_out,
+ int uniform);
+
+FAISS_DECLARE_CLASS_INHERITED(NormalizationTransform, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(NormalizationTransform)
+
+int faiss_NormalizationTransform_new_with(
+ FaissNormalizationTransform** p_vt,
+ int d,
+ float norm);
+
+FAISS_DECLARE_GETTER(NormalizationTransform, float, norm)
+
+FAISS_DECLARE_CLASS_INHERITED(CenteringTransform, VectorTransform)
+FAISS_DECLARE_DESTRUCTOR(CenteringTransform)
+
+int faiss_CenteringTransform_new_with(FaissCenteringTransform** p_vt, int d);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/clone_index_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/clone_index_c.cpp
new file mode 100644
index 0000000..d35942e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/clone_index_c.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+// I/O code for indexes
+
+#include "clone_index_c.h"
+#include <faiss/clone_index.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexBinary;
+
+int faiss_clone_index(const FaissIndex* idx, FaissIndex** p_out) {
+ try {
+ auto out = faiss::clone_index(reinterpret_cast<const Index*>(idx));
+ *p_out = reinterpret_cast<FaissIndex*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_clone_index_binary(
+ const FaissIndexBinary* idx,
+ FaissIndexBinary** p_out) {
+ try {
+ auto out = faiss::clone_binary_index(
+ reinterpret_cast<const IndexBinary*>(idx));
+ *p_out = reinterpret_cast<FaissIndexBinary*>(out);
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/clone_index_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/clone_index_c.h
new file mode 100644
index 0000000..bc4fd46
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/clone_index_c.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+// I/O code for indexes
+
+#ifndef FAISS_CLONE_INDEX_C_H
+#define FAISS_CLONE_INDEX_C_H
+
+#include <stdio.h>
+#include "IndexBinary_c.h"
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* cloning functions */
+
+/** Clone an index. This is equivalent to `faiss::clone_index` */
+int faiss_clone_index(const FaissIndex*, FaissIndex** p_out);
+
+/** Clone a binary index. This is equivalent to `faiss::clone_index_binary` */
+int faiss_clone_index_binary(const FaissIndexBinary*, FaissIndexBinary** p_out);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/error_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/error_c.h
new file mode 100644
index 0000000..dbc553c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/error_c.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_ERROR_C_H
+#define FAISS_ERROR_C_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// An error code which depends on the exception thrown from the previous
+/// operation. See `faiss_get_last_error` to retrieve the error message.
+typedef enum FaissErrorCode {
+ /// No error
+ OK = 0,
+ /// Any exception other than Faiss or standard C++ library exceptions
+ UNKNOWN_EXCEPT = -1,
+ /// Faiss library exception
+ FAISS_EXCEPT = -2,
+ /// Standard C++ library exception
+ STD_EXCEPT = -4
+} FaissErrorCode;
+
+/**
+ * Get the error message of the last failed operation performed by Faiss.
+ * The given pointer is only invalid until another Faiss function is
+ * called.
+ */
+const char* faiss_get_last_error();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/error_impl.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/error_impl.cpp
new file mode 100644
index 0000000..a0c2d52
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/error_impl.cpp
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "error_impl.h"
+#include <faiss/impl/FaissException.h>
+#include <exception>
+#include "error_c.h"
+
+thread_local std::exception_ptr faiss_last_exception;
+
+const char* faiss_get_last_error() {
+ if (faiss_last_exception) {
+ try {
+ std::rethrow_exception(faiss_last_exception);
+ } catch (std::exception& e) {
+ return e.what();
+ }
+ }
+ return nullptr;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/error_impl.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/error_impl.h
new file mode 100644
index 0000000..5fe7c1e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/error_impl.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <exception>
+
+/** global variable for holding the last exception thrown by
+ * calls to Faiss functions through the C API
+ */
+extern thread_local std::exception_ptr faiss_last_exception;
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/example_c.c b/packages/leann-backend-hnsw/third_party/faiss/c_api/example_c.c
new file mode 100644
index 0000000..03e3c3e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/example_c.c
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include "AutoTune_c.h"
+#include "IndexFlat_c.h"
+#include "Index_c.h"
+#include "clone_index_c.h"
+#include "error_c.h"
+#include "impl/AuxIndexStructures_c.h"
+#include "index_factory_c.h"
+#include "index_io_c.h"
+
+#define FAISS_TRY(C) \
+ { \
+ if (C) { \
+ fprintf(stderr, "%s", faiss_get_last_error()); \
+ exit(-1); \
+ } \
+ }
+
+double drand() {
+ return (double)rand() / (double)RAND_MAX;
+}
+
+int main() {
+ time_t seed = time(NULL);
+ srand(seed);
+ printf("Generating some data...\n");
+ int d = 128; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+ float* xb = malloc(d * nb * sizeof(float));
+ float* xq = malloc(d * nq * sizeof(float));
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = drand();
+ xb[d * i] += i / 1000.;
+ }
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = drand();
+ xq[d * i] += i / 1000.;
+ }
+
+ printf("Building an index...\n");
+
+ FaissIndex* index = NULL;
+ FAISS_TRY(faiss_index_factory(
+ &index, d, "Flat", METRIC_L2)); // use factory to create index
+ printf("is_trained = %s\n",
+ faiss_Index_is_trained(index) ? "true" : "false");
+ FAISS_TRY(faiss_Index_add(index, nb, xb)); // add vectors to the index
+ printf("ntotal = %lld\n", faiss_Index_ntotal(index));
+
+ printf("Searching...\n");
+ int k = 5;
+
+ { // sanity check: search 5 first vectors of xb
+ idx_t* I = malloc(k * 5 * sizeof(idx_t));
+ float* D = malloc(k * 5 * sizeof(float));
+ FAISS_TRY(faiss_Index_search(index, 5, xb, k, D, I));
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5lld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ }
+ { // search xq
+ idx_t* I = malloc(k * nq * sizeof(idx_t));
+ float* D = malloc(k * nq * sizeof(float));
+ FAISS_TRY(faiss_Index_search(index, nq, xq, k, D, I));
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5lld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ }
+ { // search xb first 5 but search parameters of id range [50, 100]
+ idx_t* I = malloc(k * nq * sizeof(idx_t));
+ float* D = malloc(k * nq * sizeof(float));
+ FaissIDSelectorRange* sel = NULL;
+ FAISS_TRY(faiss_IDSelectorRange_new(&sel, 50, 100));
+ FaissSearchParameters* params = NULL;
+ FAISS_TRY(faiss_SearchParameters_new(&params, sel));
+ FAISS_TRY(
+ faiss_Index_search_with_params(index, nq, xq, k, params, D, I));
+ printf("Searching w/ IDSelectorRange [50,100]\n");
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5lld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ faiss_SearchParameters_free(params);
+ faiss_IDSelectorRange_free(sel);
+ }
+
+ { // search xb first 5 but search parameters of id range [20,40] OR
+ // [45,60]
+ idx_t* I = malloc(k * nq * sizeof(idx_t));
+ float* D = malloc(k * nq * sizeof(float));
+ FaissIDSelectorRange* lhs_sel = NULL;
+ FAISS_TRY(faiss_IDSelectorRange_new(&lhs_sel, 20, 40));
+ FaissIDSelectorRange* rhs_sel = NULL;
+ FAISS_TRY(faiss_IDSelectorRange_new(&rhs_sel, 45, 60));
+ FaissIDSelectorOr* sel = NULL;
+ FAISS_TRY(faiss_IDSelectorOr_new(&sel, lhs_sel, rhs_sel));
+ FaissSearchParameters* params = NULL;
+ FAISS_TRY(faiss_SearchParameters_new(&params, sel));
+ FAISS_TRY(
+ faiss_Index_search_with_params(index, nq, xq, k, params, D, I));
+ printf("Searching w/ IDSelectorRange [20,40] OR [45,60] \n");
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5lld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ faiss_SearchParameters_free(params);
+ faiss_IDSelectorRange_free(lhs_sel);
+ faiss_IDSelectorRange_free(rhs_sel);
+ faiss_IDSelector_free(sel);
+ }
+ { // search xb first 5 but search parameters of id range [20,40] AND
+ // [15,35] = [20,35]
+ idx_t* I = malloc(k * nq * sizeof(idx_t));
+ float* D = malloc(k * nq * sizeof(float));
+ FaissIDSelectorRange* lhs_sel = NULL;
+ FAISS_TRY(faiss_IDSelectorRange_new(&lhs_sel, 20, 40));
+ FaissIDSelectorRange* rhs_sel = NULL;
+ FAISS_TRY(faiss_IDSelectorRange_new(&rhs_sel, 15, 35));
+ FaissIDSelectorAnd* sel = NULL;
+ FAISS_TRY(faiss_IDSelectorAnd_new(&sel, lhs_sel, rhs_sel));
+ FaissSearchParameters* params = NULL;
+ FAISS_TRY(faiss_SearchParameters_new(&params, sel));
+ FAISS_TRY(
+ faiss_Index_search_with_params(index, nq, xq, k, params, D, I));
+ printf("Searching w/ IDSelectorRange [20,40] AND [15,35] = [20,35]\n");
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5lld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ faiss_SearchParameters_free(params);
+ faiss_IDSelectorRange_free(lhs_sel);
+ faiss_IDSelectorRange_free(rhs_sel);
+ faiss_IDSelector_free(sel);
+ }
+
+ printf("Saving index to disk...\n");
+ FAISS_TRY(faiss_write_index_fname(index, "example.index"));
+
+ printf("Freeing index...\n");
+ faiss_Index_free(index);
+ printf("Done.\n");
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/faiss_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/faiss_c.h
new file mode 100644
index 0000000..7d38a78
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/faiss_c.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+/// Macros and typedefs for C wrapper API declarations
+
+#ifndef FAISS_C_H
+#define FAISS_C_H
+
+#include <stdint.h>
+
+typedef int64_t faiss_idx_t; ///< all indices are this type
+typedef faiss_idx_t idx_t;
+typedef float faiss_component_t; ///< all vector components are this type
+typedef float faiss_distance_t; ///< all distances between vectors are this type
+
+/// Declare an opaque type for a class type `clazz`.
+#define FAISS_DECLARE_CLASS(clazz) typedef struct Faiss##clazz##_H Faiss##clazz;
+
+/// Declare an opaque type for a class type `clazz`, while
+/// actually aliasing it to an existing parent class type `parent`.
+#define FAISS_DECLARE_CLASS_INHERITED(clazz, parent) \
+ typedef struct Faiss##parent##_H Faiss##clazz;
+
+/// Declare a dynamic downcast operation from a base `FaissIndex*` pointer
+/// type to a more specific index type. The function returns the same pointer
+/// if the downcast is valid, and `NULL` otherwise.
+#define FAISS_DECLARE_INDEX_DOWNCAST(clazz) \
+ Faiss##clazz* faiss_##clazz##_cast(FaissIndex*);
+
+/// Declare a dynamic downcast operation from a base `FaissSearchParameters*`
+/// pointer type to a more specific search parameters type. The function returns
+/// the same pointer if the downcast is valid, and `NULL` otherwise.
+#define FAISS_DECLARE_SEARCH_PARAMETERS_DOWNCAST(clazz) \
+ Faiss##clazz* faiss_##clazz##_cast(FaissSearchParameters*);
+
+/// Declare a getter for the field `name` in class `clazz`,
+/// of return type `ty`
+#define FAISS_DECLARE_GETTER(clazz, ty, name) \
+ ty faiss_##clazz##_##name(const Faiss##clazz*);
+
+/// Declare a setter for the field `name` in class `clazz`,
+/// in which the user provides a value of type `ty`
+#define FAISS_DECLARE_SETTER(clazz, ty, name) \
+ void faiss_##clazz##_set_##name(Faiss##clazz*, ty);
+
+/// Declare a getter and setter for the field `name` in class `clazz`.
+#define FAISS_DECLARE_GETTER_SETTER(clazz, ty, name) \
+ FAISS_DECLARE_GETTER(clazz, ty, name) \
+ FAISS_DECLARE_SETTER(clazz, ty, name)
+
+/// Declare a destructor function which frees an object of
+/// type `clazz`.
+#define FAISS_DECLARE_DESTRUCTOR(clazz) \
+ void faiss_##clazz##_free(Faiss##clazz* obj);
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/CMakeLists.txt
new file mode 100644
index 0000000..3c7214a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/CMakeLists.txt
@@ -0,0 +1,34 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+target_sources(faiss_c PRIVATE
+ DeviceUtils_c.cpp
+ GpuAutoTune_c.cpp
+ GpuClonerOptions_c.cpp
+ GpuIndex_c.cpp
+ GpuResources_c.cpp
+ StandardGpuResources_c.cpp
+)
+
+file(GLOB FAISS_C_API_GPU_HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*.h")
+faiss_install_headers("${FAISS_C_API_GPU_HEADERS}" c_api/gpu)
+
+if (FAISS_ENABLE_ROCM)
+ target_link_libraries(faiss_c PUBLIC hip::host roc::hipblas)
+ target_link_libraries(faiss_c_avx2 PUBLIC hip::host roc::hipblas)
+ target_link_libraries(faiss_c_avx512 PUBLIC hip::host roc::hipblas)
+ target_link_libraries(faiss_c_avx512_spr PUBLIC hip::host roc::hipblas)
+ target_link_libraries(faiss_c_sve PUBLIC hip::host roc::hipblas)
+else()
+ find_package(CUDAToolkit REQUIRED)
+ target_link_libraries(faiss_c PUBLIC CUDA::cudart CUDA::cublas $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(faiss_c_avx2 PUBLIC CUDA::cudart CUDA::cublas $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(faiss_c_avx512 PUBLIC CUDA::cudart CUDA::cublas $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(faiss_c_avx512_spr PUBLIC CUDA::cudart CUDA::cublas $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(faiss_c_sve PUBLIC CUDA::cudart CUDA::cublas $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+endif()
+
+add_executable(example_gpu_c EXCLUDE_FROM_ALL example_gpu_c.c)
+target_link_libraries(example_gpu_c PRIVATE faiss_c)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/DeviceUtils_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/DeviceUtils_c.cpp
new file mode 100644
index 0000000..37850d3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/DeviceUtils_c.cpp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "DeviceUtils_c.h"
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include "macros_impl.h"
+
+/// Returns the number of available GPU devices
+int faiss_get_num_gpus(int* p_output) {
+ try {
+ int output = faiss::gpu::getNumDevices();
+ *p_output = output;
+ }
+ CATCH_AND_HANDLE
+}
+
+/// Starts the CUDA profiler (exposed via SWIG)
+int faiss_gpu_profiler_start() {
+ try {
+ faiss::gpu::profilerStart();
+ }
+ CATCH_AND_HANDLE
+}
+
+/// Stops the CUDA profiler (exposed via SWIG)
+int faiss_gpu_profiler_stop() {
+ try {
+ faiss::gpu::profilerStop();
+ }
+ CATCH_AND_HANDLE
+}
+
+/// Synchronizes the CPU against all devices (equivalent to
+/// cudaDeviceSynchronize for each device)
+int faiss_gpu_sync_all_devices() {
+ try {
+ faiss::gpu::synchronizeAllDevices();
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/DeviceUtils_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/DeviceUtils_c.h
new file mode 100644
index 0000000..b5c67e9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/DeviceUtils_c.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_DEVICE_UTILS_C_H
+#define FAISS_DEVICE_UTILS_C_H
+
+#include <cublas_v2.h>
+#include <cuda_runtime_api.h>
+#include "../faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Returns the number of available GPU devices
+int faiss_get_num_gpus(int* p_output);
+
+/// Starts the CUDA profiler (exposed via SWIG)
+int faiss_gpu_profiler_start();
+
+/// Stops the CUDA profiler (exposed via SWIG)
+int faiss_gpu_profiler_stop();
+
+/// Synchronizes the CPU against all devices (equivalent to
+/// cudaDeviceSynchronize for each device)
+int faiss_gpu_sync_all_devices();
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuAutoTune_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuAutoTune_c.cpp
new file mode 100644
index 0000000..d5bc7e9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuAutoTune_c.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "GpuAutoTune_c.h"
+#include <faiss/Index.h>
+#include <faiss/gpu/GpuAutoTune.h>
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/gpu/GpuClonerOptions.h>
+#include <faiss/gpu/GpuResources.h>
+#include <vector>
+#include "GpuClonerOptions_c.h"
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::gpu::GpuClonerOptions;
+using faiss::gpu::GpuMultipleClonerOptions;
+using faiss::gpu::GpuResourcesProvider;
+
+int faiss_index_gpu_to_cpu(const FaissIndex* gpu_index, FaissIndex** p_out) {
+ try {
+ auto cpu_index = faiss::gpu::index_gpu_to_cpu(
+ reinterpret_cast<const Index*>(gpu_index));
+ *p_out = reinterpret_cast<FaissIndex*>(cpu_index);
+ }
+ CATCH_AND_HANDLE
+}
+
+/// converts any CPU index that can be converted to GPU
+int faiss_index_cpu_to_gpu(
+ FaissGpuResourcesProvider* provider,
+ int device,
+ const FaissIndex* index,
+ FaissGpuIndex** p_out) {
+ try {
+ auto res = reinterpret_cast<GpuResourcesProvider*>(provider);
+ auto gpu_index = faiss::gpu::index_cpu_to_gpu(
+ res, device, reinterpret_cast<const Index*>(index));
+ *p_out = reinterpret_cast<FaissGpuIndex*>(gpu_index);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_index_cpu_to_gpu_with_options(
+ FaissGpuResourcesProvider* provider,
+ int device,
+ const FaissIndex* index,
+ const FaissGpuClonerOptions* options,
+ FaissGpuIndex** p_out) {
+ try {
+ auto res = reinterpret_cast<GpuResourcesProvider*>(provider);
+ auto gpu_index = faiss::gpu::index_cpu_to_gpu(
+ res,
+ device,
+ reinterpret_cast<const Index*>(index),
+ reinterpret_cast<const GpuClonerOptions*>(options));
+ *p_out = reinterpret_cast<FaissGpuIndex*>(gpu_index);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_index_cpu_to_gpu_multiple(
+ FaissGpuResourcesProvider* const* providers_vec,
+ const int* devices,
+ size_t devices_size,
+ const FaissIndex* index,
+ FaissGpuIndex** p_out) {
+ try {
+ std::vector<GpuResourcesProvider*> res(devices_size);
+ for (auto i = 0u; i < devices_size; ++i) {
+ res[i] = reinterpret_cast<GpuResourcesProvider*>(providers_vec[i]);
+ }
+
+ std::vector<int> dev(devices, devices + devices_size);
+
+ auto gpu_index = faiss::gpu::index_cpu_to_gpu_multiple(
+ res, dev, reinterpret_cast<const Index*>(index));
+ *p_out = reinterpret_cast<FaissGpuIndex*>(gpu_index);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_index_cpu_to_gpu_multiple_with_options(
+ FaissGpuResourcesProvider* const* providers_vec,
+ size_t providers_vec_size,
+ const int* devices,
+ size_t devices_size,
+ const FaissIndex* index,
+ const FaissGpuMultipleClonerOptions* options,
+ FaissGpuIndex** p_out) {
+ try {
+ std::vector<GpuResourcesProvider*> res(providers_vec_size);
+ for (auto i = 0u; i < providers_vec_size; ++i) {
+ res[i] = reinterpret_cast<GpuResourcesProvider*>(providers_vec[i]);
+ }
+
+ std::vector<int> dev(devices, devices + devices_size);
+
+ auto gpu_index = faiss::gpu::index_cpu_to_gpu_multiple(
+ res,
+ dev,
+ reinterpret_cast<const Index*>(index),
+ reinterpret_cast<const GpuMultipleClonerOptions*>(options));
+ *p_out = reinterpret_cast<FaissGpuIndex*>(gpu_index);
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuAutoTune_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuAutoTune_c.h
new file mode 100644
index 0000000..19b296d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuAutoTune_c.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_GPU_AUTO_TUNE_C_H
+#define FAISS_GPU_AUTO_TUNE_C_H
+
+#include <stddef.h>
+#include "../Index_c.h"
+#include "../faiss_c.h"
+#include "GpuClonerOptions_c.h"
+#include "GpuIndex_c.h"
+#include "GpuResources_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// converts any GPU index inside gpu_index to a CPU index
+int faiss_index_gpu_to_cpu(const FaissIndex* gpu_index, FaissIndex** p_out);
+
+/// converts any CPU index that can be converted to GPU
+int faiss_index_cpu_to_gpu(
+ FaissGpuResourcesProvider* provider,
+ int device,
+ const FaissIndex* index,
+ FaissGpuIndex** p_out);
+
+/// converts any CPU index that can be converted to GPU
+int faiss_index_cpu_to_gpu_with_options(
+ FaissGpuResourcesProvider* provider,
+ int device,
+ const FaissIndex* index,
+ const FaissGpuClonerOptions* options,
+ FaissGpuIndex** p_out);
+
+/// converts any CPU index that can be converted to GPU
+int faiss_index_cpu_to_gpu_multiple(
+ FaissGpuResourcesProvider* const* providers_vec,
+ const int* devices,
+ size_t devices_size,
+ const FaissIndex* index,
+ FaissGpuIndex** p_out);
+
+/// converts any CPU index that can be converted to GPU
+int faiss_index_cpu_to_gpu_multiple_with_options(
+ FaissGpuResourcesProvider* const* providers_vec,
+ size_t providers_vec_size,
+ const int* devices,
+ size_t devices_size,
+ const FaissIndex* index,
+ const FaissGpuMultipleClonerOptions* options,
+ FaissGpuIndex** p_out);
+
+/// parameter space and setters for GPU indexes
+FAISS_DECLARE_CLASS_INHERITED(GpuParameterSpace, ParameterSpace)
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuClonerOptions_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuClonerOptions_c.cpp
new file mode 100644
index 0000000..80c9d02
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuClonerOptions_c.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "GpuClonerOptions_c.h"
+#include <faiss/gpu/GpuClonerOptions.h>
+#include "macros_impl.h"
+
+using faiss::gpu::GpuClonerOptions;
+using faiss::gpu::GpuMultipleClonerOptions;
+using faiss::gpu::IndicesOptions;
+
+int faiss_GpuClonerOptions_new(FaissGpuClonerOptions** p) {
+ try {
+ *p = reinterpret_cast<FaissGpuClonerOptions*>(new GpuClonerOptions());
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuMultipleClonerOptions_new(FaissGpuMultipleClonerOptions** p) {
+ try {
+ *p = reinterpret_cast<FaissGpuMultipleClonerOptions*>(
+ new GpuMultipleClonerOptions());
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(GpuClonerOptions)
+DEFINE_DESTRUCTOR(GpuMultipleClonerOptions)
+
+DEFINE_GETTER(GpuClonerOptions, FaissIndicesOptions, indicesOptions)
+DEFINE_GETTER(GpuClonerOptions, int, useFloat16CoarseQuantizer)
+DEFINE_GETTER(GpuClonerOptions, int, useFloat16)
+DEFINE_GETTER(GpuClonerOptions, int, usePrecomputed)
+DEFINE_GETTER(GpuClonerOptions, long, reserveVecs)
+DEFINE_GETTER(GpuClonerOptions, int, storeTransposed)
+DEFINE_GETTER(GpuClonerOptions, int, verbose)
+DEFINE_GETTER(GpuMultipleClonerOptions, int, shard)
+DEFINE_GETTER(GpuMultipleClonerOptions, int, shard_type)
+
+DEFINE_SETTER_STATIC(
+ GpuClonerOptions,
+ IndicesOptions,
+ FaissIndicesOptions,
+ indicesOptions)
+DEFINE_SETTER_STATIC(GpuClonerOptions, bool, int, useFloat16CoarseQuantizer)
+DEFINE_SETTER_STATIC(GpuClonerOptions, bool, int, useFloat16)
+DEFINE_SETTER_STATIC(GpuClonerOptions, bool, int, usePrecomputed)
+DEFINE_SETTER(GpuClonerOptions, long, reserveVecs)
+DEFINE_SETTER_STATIC(GpuClonerOptions, bool, int, storeTransposed)
+DEFINE_SETTER_STATIC(GpuClonerOptions, bool, int, verbose)
+DEFINE_SETTER_STATIC(GpuMultipleClonerOptions, bool, int, shard)
+DEFINE_SETTER(GpuMultipleClonerOptions, int, shard_type)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuClonerOptions_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuClonerOptions_c.h
new file mode 100644
index 0000000..dc8b82e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuClonerOptions_c.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_GPU_CLONER_OPTIONS_C_H
+#define FAISS_GPU_CLONER_OPTIONS_C_H
+
+#include "../faiss_c.h"
+#include "GpuIndicesOptions_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+FAISS_DECLARE_CLASS(GpuClonerOptions)
+
+FAISS_DECLARE_DESTRUCTOR(GpuClonerOptions)
+
+/// Default constructor for GpuClonerOptions
+int faiss_GpuClonerOptions_new(FaissGpuClonerOptions**);
+
+/// how should indices be stored on index types that support indices
+/// (anything but GpuIndexFlat*)?
+FAISS_DECLARE_GETTER_SETTER(
+ GpuClonerOptions,
+ FaissIndicesOptions,
+ indicesOptions)
+
+/// (boolean) is the coarse quantizer in float16?
+FAISS_DECLARE_GETTER_SETTER(GpuClonerOptions, int, useFloat16CoarseQuantizer)
+
+/// (boolean) for GpuIndexIVFFlat, is storage in float16?
+/// for GpuIndexIVFPQ, are intermediate calculations in float16?
+FAISS_DECLARE_GETTER_SETTER(GpuClonerOptions, int, useFloat16)
+
+/// (boolean) use precomputed tables?
+FAISS_DECLARE_GETTER_SETTER(GpuClonerOptions, int, usePrecomputed)
+
+/// reserve vectors in the invfiles?
+FAISS_DECLARE_GETTER_SETTER(GpuClonerOptions, long, reserveVecs)
+
+/// (boolean) For GpuIndexFlat, store data in transposed layout?
+FAISS_DECLARE_GETTER_SETTER(GpuClonerOptions, int, storeTransposed)
+
+/// (boolean) Set verbose options on the index
+FAISS_DECLARE_GETTER_SETTER(GpuClonerOptions, int, verbose)
+
+FAISS_DECLARE_CLASS_INHERITED(GpuMultipleClonerOptions, GpuClonerOptions)
+
+FAISS_DECLARE_DESTRUCTOR(GpuMultipleClonerOptions)
+
+/// Default constructor for GpuMultipleClonerOptions
+int faiss_GpuMultipleClonerOptions_new(FaissGpuMultipleClonerOptions**);
+
+/// (boolean) Whether to shard the index across GPUs, versus replication
+/// across GPUs
+FAISS_DECLARE_GETTER_SETTER(GpuMultipleClonerOptions, int, shard)
+
+/// IndexIVF::copy_subset_to subset type
+FAISS_DECLARE_GETTER_SETTER(GpuMultipleClonerOptions, int, shard_type)
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndex_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndex_c.cpp
new file mode 100644
index 0000000..92d675a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndex_c.cpp
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "GpuIndex_c.h"
+#include <faiss/gpu/GpuIndex.h>
+#include "macros_impl.h"
+
+using faiss::gpu::GpuIndexConfig;
+
+DEFINE_GETTER(GpuIndexConfig, int, device)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndex_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndex_c.h
new file mode 100644
index 0000000..4b7aab0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndex_c.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_GPU_INDEX_C_H
+#define FAISS_GPU_INDEX_C_H
+
+#include "../faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+FAISS_DECLARE_CLASS(GpuIndexConfig)
+
+FAISS_DECLARE_GETTER(GpuIndexConfig, int, device)
+
+FAISS_DECLARE_CLASS_INHERITED(GpuIndex, Index)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndicesOptions_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndicesOptions_c.h
new file mode 100644
index 0000000..14ab9ae
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuIndicesOptions_c.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_GPU_INDICES_OPTIONS_C_H
+#define FAISS_GPU_INDICES_OPTIONS_C_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// How user vector index data is stored on the GPU
+typedef enum FaissIndicesOptions {
+ /// The user indices are only stored on the CPU; the GPU returns
+ /// (inverted list, offset) to the CPU which is then translated to
+ /// the real user index.
+ INDICES_CPU = 0,
+ /// The indices are not stored at all, on either the CPU or
+ /// GPU. Only (inverted list, offset) is returned to the user as the
+ /// index.
+ INDICES_IVF = 1,
+ /// Indices are stored as 32 bit integers on the GPU, but returned
+ /// as 64 bit integers
+ INDICES_32_BIT = 2,
+ /// Indices are stored as 64 bit integers on the GPU
+ INDICES_64_BIT = 3,
+} FaissIndicesOptions;
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuResources_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuResources_c.cpp
new file mode 100644
index 0000000..65baeab
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuResources_c.cpp
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "GpuResources_c.h"
+#include <faiss/gpu/GpuResources.h>
+#include "macros_impl.h"
+
+using faiss::gpu::GpuResources;
+using faiss::gpu::GpuResourcesProvider;
+
+DEFINE_DESTRUCTOR(GpuResources)
+
+int faiss_GpuResources_initializeForDevice(FaissGpuResources* res, int device) {
+ try {
+ reinterpret_cast<GpuResources*>(res)->initializeForDevice(device);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getBlasHandle(
+ FaissGpuResources* res,
+ int device,
+ cublasHandle_t* out) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)->getBlasHandle(device);
+ *out = o;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getDefaultStream(
+ FaissGpuResources* res,
+ int device,
+ cudaStream_t* out) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)->getDefaultStream(device);
+ *out = o;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getPinnedMemory(
+ FaissGpuResources* res,
+ void** p_buffer,
+ size_t* p_size) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)->getPinnedMemory();
+ *p_buffer = o.first;
+ *p_size = o.second;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getAsyncCopyStream(
+ FaissGpuResources* res,
+ int device,
+ cudaStream_t* out) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)->getAsyncCopyStream(
+ device);
+ *out = o;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getBlasHandleCurrentDevice(
+ FaissGpuResources* res,
+ cublasHandle_t* out) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)
+ ->getBlasHandleCurrentDevice();
+ *out = o;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getDefaultStreamCurrentDevice(
+ FaissGpuResources* res,
+ cudaStream_t* out) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)
+ ->getDefaultStreamCurrentDevice();
+ *out = o;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_syncDefaultStream(FaissGpuResources* res, int device) {
+ try {
+ reinterpret_cast<GpuResources*>(res)->syncDefaultStream(device);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_syncDefaultStreamCurrentDevice(FaissGpuResources* res) {
+ try {
+ reinterpret_cast<GpuResources*>(res)->syncDefaultStreamCurrentDevice();
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_GpuResources_getAsyncCopyStreamCurrentDevice(
+ FaissGpuResources* res,
+ cudaStream_t* out) {
+ try {
+ auto o = reinterpret_cast<GpuResources*>(res)
+ ->getAsyncCopyStreamCurrentDevice();
+ *out = o;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(GpuResourcesProvider)
+
+int faiss_GpuResourcesProvider_getResources(
+ FaissGpuResourcesProvider* res,
+ FaissGpuResources** out) {
+ try {
+ auto o = reinterpret_cast<GpuResourcesProvider*>(res)->getResources();
+ *out = reinterpret_cast<FaissGpuResources*>(o.get());
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuResources_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuResources_c.h
new file mode 100644
index 0000000..d3d604b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/GpuResources_c.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_GPU_RESOURCES_C_H
+#define FAISS_GPU_RESOURCES_C_H
+
+#include <cublas_v2.h>
+#include <cuda_runtime_api.h>
+#include "../faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Base class of GPU-side resource provider; hides provision of
+/// cuBLAS handles, CUDA streams and a temporary memory manager
+FAISS_DECLARE_CLASS(GpuResources)
+
+FAISS_DECLARE_DESTRUCTOR(GpuResources)
+
+/// Call to pre-allocate resources for a particular device. If this is
+/// not called, then resources will be allocated at the first time
+/// of demand
+int faiss_GpuResources_initializeForDevice(FaissGpuResources*, int);
+
+/// Returns the cuBLAS handle that we use for the given device
+int faiss_GpuResources_getBlasHandle(FaissGpuResources*, int, cublasHandle_t*);
+
+/// Returns the stream that we order all computation on for the
+/// given device
+int faiss_GpuResources_getDefaultStream(FaissGpuResources*, int, cudaStream_t*);
+
+/// Returns the available CPU pinned memory buffer
+int faiss_GpuResources_getPinnedMemory(FaissGpuResources*, void**, size_t*);
+
+/// Returns the stream on which we perform async CPU <-> GPU copies
+int faiss_GpuResources_getAsyncCopyStream(
+ FaissGpuResources*,
+ int,
+ cudaStream_t*);
+
+/// Calls getBlasHandle with the current device
+int faiss_GpuResources_getBlasHandleCurrentDevice(
+ FaissGpuResources*,
+ cublasHandle_t*);
+
+/// Calls getDefaultStream with the current device
+int faiss_GpuResources_getDefaultStreamCurrentDevice(
+ FaissGpuResources*,
+ cudaStream_t*);
+
+/// Synchronizes the CPU with respect to the default stream for the
+/// given device
+// equivalent to cudaDeviceSynchronize(getDefaultStream(device))
+int faiss_GpuResources_syncDefaultStream(FaissGpuResources*, int);
+
+/// Calls syncDefaultStream for the current device
+int faiss_GpuResources_syncDefaultStreamCurrentDevice(FaissGpuResources*);
+
+/// Calls getAsyncCopyStream for the current device
+int faiss_GpuResources_getAsyncCopyStreamCurrentDevice(
+ FaissGpuResources*,
+ cudaStream_t*);
+
+FAISS_DECLARE_CLASS(GpuResourcesProvider)
+
+FAISS_DECLARE_DESTRUCTOR(GpuResourcesProvider)
+
+int faiss_GpuResourcesProvider_getResources(
+ FaissGpuResourcesProvider*,
+ FaissGpuResources**);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/StandardGpuResources_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/StandardGpuResources_c.cpp
new file mode 100644
index 0000000..5552873
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/StandardGpuResources_c.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "StandardGpuResources_c.h"
+#include <faiss/gpu/StandardGpuResources.h>
+#include "macros_impl.h"
+
+using faiss::gpu::StandardGpuResources;
+
+DEFINE_DESTRUCTOR(StandardGpuResources)
+
+int faiss_StandardGpuResources_new(FaissStandardGpuResources** p_res) {
+ try {
+ auto p = new StandardGpuResources();
+ *p_res = reinterpret_cast<FaissStandardGpuResources*>(p);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_StandardGpuResources_noTempMemory(FaissStandardGpuResources* res) {
+ try {
+ reinterpret_cast<StandardGpuResources*>(res)->noTempMemory();
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_StandardGpuResources_setTempMemory(
+ FaissStandardGpuResources* res,
+ size_t size) {
+ try {
+ reinterpret_cast<StandardGpuResources*>(res)->setTempMemory(size);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_StandardGpuResources_setPinnedMemory(
+ FaissStandardGpuResources* res,
+ size_t size) {
+ try {
+ reinterpret_cast<StandardGpuResources*>(res)->setPinnedMemory(size);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_StandardGpuResources_setDefaultStream(
+ FaissStandardGpuResources* res,
+ int device,
+ cudaStream_t stream) {
+ try {
+ reinterpret_cast<StandardGpuResources*>(res)->setDefaultStream(
+ device, stream);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_StandardGpuResources_setDefaultNullStreamAllDevices(
+ FaissStandardGpuResources* res) {
+ try {
+ reinterpret_cast<StandardGpuResources*>(res)
+ ->setDefaultNullStreamAllDevices();
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/StandardGpuResources_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/StandardGpuResources_c.h
new file mode 100644
index 0000000..e435dac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/StandardGpuResources_c.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_STANDARD_GPURESOURCES_C_H
+#define FAISS_STANDARD_GPURESOURCES_C_H
+
+#include <cuda_runtime_api.h>
+#include "../faiss_c.h"
+#include "GpuResources_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/// Default implementation of GpuResourcesProvider that allocates a cuBLAS
+/// stream and 2 streams for use, as well as temporary memory
+FAISS_DECLARE_CLASS_INHERITED(StandardGpuResources, GpuResourcesProvider)
+
+FAISS_DECLARE_DESTRUCTOR(StandardGpuResources)
+
+/// Default constructor for StandardGpuResources
+int faiss_StandardGpuResources_new(FaissStandardGpuResources**);
+
+/// Disable allocation of temporary memory; all temporary memory
+/// requests will call cudaMalloc / cudaFree at the point of use
+int faiss_StandardGpuResources_noTempMemory(FaissStandardGpuResources*);
+
+/// Specify that we wish to use a certain fixed size of memory on
+/// all devices as temporary memory
+int faiss_StandardGpuResources_setTempMemory(
+ FaissStandardGpuResources*,
+ size_t size);
+
+/// Set amount of pinned memory to allocate, for async GPU <-> CPU
+/// transfers
+int faiss_StandardGpuResources_setPinnedMemory(
+ FaissStandardGpuResources*,
+ size_t size);
+
+/// Called to change the stream for work ordering
+int faiss_StandardGpuResources_setDefaultStream(
+ FaissStandardGpuResources*,
+ int device,
+ cudaStream_t stream);
+
+/// Called to change the work ordering streams to the null stream
+/// for all devices
+int faiss_StandardGpuResources_setDefaultNullStreamAllDevices(
+ FaissStandardGpuResources*);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/example_gpu_c.c b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/example_gpu_c.c
new file mode 100644
index 0000000..37ef54b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/example_gpu_c.c
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include "../AutoTune_c.h"
+#include "../Index_c.h"
+#include "../error_c.h"
+#include "../index_factory_c.h"
+#include "DeviceUtils_c.h"
+#include "GpuAutoTune_c.h"
+#include "StandardGpuResources_c.h"
+
+#define FAISS_TRY(C) \
+ { \
+ if (C) { \
+ fprintf(stderr, "%s", faiss_get_last_error()); \
+ exit(-1); \
+ } \
+ }
+
+double drand() {
+ return (double)rand() / (double)RAND_MAX;
+}
+
+int main() {
+ time_t seed = time(NULL);
+ srand(seed);
+
+ int gpus = -1;
+ FAISS_TRY(faiss_get_num_gpus(&gpus));
+ printf("%d GPU devices are available\n", gpus);
+
+ printf("Generating some data...\n");
+ int d = 128; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+ float* xb = malloc(d * nb * sizeof(float));
+ float* xq = malloc(d * nq * sizeof(float));
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = drand();
+ xb[d * i] += i / 1000.;
+ }
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = drand();
+ xq[d * i] += i / 1000.;
+ }
+
+ printf("Loading standard GPU resources...\n");
+ FaissStandardGpuResources* gpu_res = NULL;
+ FAISS_TRY(faiss_StandardGpuResources_new(&gpu_res));
+
+ printf("Building an index...\n");
+ FaissIndex* cpu_index = NULL;
+ FAISS_TRY(faiss_index_factory(
+ &cpu_index, d, "Flat", METRIC_L2)); // use factory to create index
+
+ printf("Moving index to the GPU...\n");
+ FaissGpuIndex* index = NULL;
+ FaissGpuClonerOptions* options = NULL;
+ FAISS_TRY(faiss_GpuClonerOptions_new(&options));
+ FAISS_TRY(faiss_index_cpu_to_gpu_with_options(
+ gpu_res, 0, cpu_index, options, &index));
+
+ printf("is_trained = %s\n",
+ faiss_Index_is_trained(index) ? "true" : "false");
+ FAISS_TRY(faiss_Index_add(index, nb, xb)); // add vectors to the index
+ printf("ntotal = %ld\n", faiss_Index_ntotal(index));
+
+ printf("Searching...\n");
+ int k = 5;
+
+ { // sanity check: search 5 first vectors of xb
+ idx_t* I = malloc(k * 5 * sizeof(idx_t));
+ float* D = malloc(k * 5 * sizeof(float));
+ FAISS_TRY(faiss_Index_search(index, 5, xb, k, D, I));
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ }
+ { // search xq
+ idx_t* I = malloc(k * nq * sizeof(idx_t));
+ float* D = malloc(k * nq * sizeof(float));
+ FAISS_TRY(faiss_Index_search(index, 5, xb, k, D, I));
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld (d=%2.3f) ", I[i * k + j], D[i * k + j]);
+ printf("\n");
+ }
+ free(I);
+ free(D);
+ }
+
+ printf("Freeing index...\n");
+ faiss_Index_free(index);
+ printf("Freeing GPU resources...\n");
+ faiss_GpuResources_free(gpu_res);
+ faiss_GpuClonerOptions_free(options);
+ printf("Done.\n");
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/macros_impl.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/macros_impl.h
new file mode 100644
index 0000000..a8cb57b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/gpu/macros_impl.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef GPU_MACROS_IMPL_H
+#define GPU_MACROS_IMPL_H
+#include "../macros_impl.h"
+
+#undef DEFINE_GETTER
+#define DEFINE_GETTER(clazz, ty, name) \
+ ty faiss_##clazz##_##name(const Faiss##clazz* obj) { \
+ return static_cast<ty>( \
+ reinterpret_cast<const faiss::gpu::clazz*>(obj)->name); \
+ }
+
+#undef DEFINE_SETTER
+#define DEFINE_SETTER(clazz, ty, name) \
+ void faiss_##clazz##_set_##name(Faiss##clazz* obj, ty val) { \
+ reinterpret_cast<faiss::gpu::clazz*>(obj)->name = val; \
+ }
+
+#undef DEFINE_SETTER_STATIC
+#define DEFINE_SETTER_STATIC(clazz, ty_to, ty_from, name) \
+ void faiss_##clazz##_set_##name(Faiss##clazz* obj, ty_from val) { \
+ reinterpret_cast<faiss::gpu::clazz*>(obj)->name = \
+ static_cast<ty_to>(val); \
+ }
+
+#undef DEFINE_DESTRUCTOR
+#define DEFINE_DESTRUCTOR(clazz) \
+ void faiss_##clazz##_free(Faiss##clazz* obj) { \
+ delete reinterpret_cast<faiss::gpu::clazz*>(obj); \
+ }
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/impl/AuxIndexStructures_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/impl/AuxIndexStructures_c.cpp
new file mode 100644
index 0000000..a7d4f4d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/impl/AuxIndexStructures_c.cpp
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "AuxIndexStructures_c.h"
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/IDSelector.h>
+#include <iostream>
+#include "../macros_impl.h"
+
+using faiss::BufferList;
+using faiss::DistanceComputer;
+using faiss::IDSelector;
+using faiss::IDSelectorAnd;
+using faiss::IDSelectorBatch;
+using faiss::IDSelectorBitmap;
+using faiss::IDSelectorNot;
+using faiss::IDSelectorOr;
+using faiss::IDSelectorRange;
+using faiss::IDSelectorXOr;
+using faiss::RangeQueryResult;
+using faiss::RangeSearchPartialResult;
+using faiss::RangeSearchResult;
+
+DEFINE_GETTER(RangeSearchResult, size_t, nq)
+
+int faiss_RangeSearchResult_new(FaissRangeSearchResult** p_rsr, idx_t nq) {
+ try {
+ *p_rsr = reinterpret_cast<FaissRangeSearchResult*>(
+ new RangeSearchResult(nq));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_RangeSearchResult_new_with(
+ FaissRangeSearchResult** p_rsr,
+ idx_t nq,
+ int alloc_lims) {
+ try {
+ *p_rsr = reinterpret_cast<FaissRangeSearchResult*>(
+ new RangeSearchResult(nq, static_cast<bool>(alloc_lims)));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+/// called when lims contains the nb of elements result entries
+/// for each query
+int faiss_RangeSearchResult_do_allocation(FaissRangeSearchResult* rsr) {
+ try {
+ reinterpret_cast<RangeSearchResult*>(rsr)->do_allocation();
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(RangeSearchResult)
+
+/// getter for buffer_size
+DEFINE_GETTER(RangeSearchResult, size_t, buffer_size)
+
+/// getter for lims: size (nq + 1)
+void faiss_RangeSearchResult_lims(FaissRangeSearchResult* rsr, size_t** lims) {
+ *lims = reinterpret_cast<RangeSearchResult*>(rsr)->lims;
+}
+
+/// getter for labels and respective distances (not sorted):
+/// result for query i is labels[lims[i]:lims[i+1]]
+void faiss_RangeSearchResult_labels(
+ FaissRangeSearchResult* rsr,
+ idx_t** labels,
+ float** distances) {
+ auto sr = reinterpret_cast<RangeSearchResult*>(rsr);
+ *labels = sr->labels;
+ *distances = sr->distances;
+}
+
+DEFINE_DESTRUCTOR(IDSelector)
+
+int faiss_IDSelector_is_member(const FaissIDSelector* sel, idx_t id) {
+ return reinterpret_cast<const IDSelector*>(sel)->is_member(id);
+}
+
+DEFINE_DESTRUCTOR(IDSelectorRange)
+
+DEFINE_GETTER(IDSelectorRange, idx_t, imin)
+DEFINE_GETTER(IDSelectorRange, idx_t, imax)
+
+int faiss_IDSelectorRange_new(
+ FaissIDSelectorRange** p_sel,
+ idx_t imin,
+ idx_t imax) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorRange*>(
+ new IDSelectorRange(imin, imax));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER(IDSelectorBatch, int, nbits)
+DEFINE_GETTER(IDSelectorBatch, idx_t, mask)
+
+int faiss_IDSelectorBatch_new(
+ FaissIDSelectorBatch** p_sel,
+ size_t n,
+ const idx_t* indices) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorBatch*>(
+ new IDSelectorBatch(n, indices));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(IDSelectorBitmap)
+
+DEFINE_GETTER(IDSelectorBitmap, size_t, n)
+DEFINE_GETTER(IDSelectorBitmap, const uint8_t*, bitmap)
+
+int faiss_IDSelectorBitmap_new(
+ FaissIDSelectorBitmap** p_sel,
+ size_t n,
+ const uint8_t* bitmap) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorBitmap*>(
+ new IDSelectorBitmap(n, bitmap));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IDSelectorNot_new(
+ FaissIDSelectorNot** p_sel,
+ const FaissIDSelector* sel) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorNot*>(
+ new IDSelectorNot(reinterpret_cast<const IDSelector*>(sel)));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IDSelectorAnd_new(
+ FaissIDSelectorAnd** p_sel,
+ const FaissIDSelector* lhs_sel,
+ const FaissIDSelector* rhs_sel) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorAnd*>(new IDSelectorAnd(
+ reinterpret_cast<const IDSelector*>(lhs_sel),
+ reinterpret_cast<const IDSelector*>(rhs_sel)));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IDSelectorOr_new(
+ FaissIDSelectorOr** p_sel,
+ const FaissIDSelector* lhs_sel,
+ const FaissIDSelector* rhs_sel) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorOr*>(new IDSelectorOr(
+ reinterpret_cast<const IDSelector*>(lhs_sel),
+ reinterpret_cast<const IDSelector*>(rhs_sel)));
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_IDSelectorXOr_new(
+ FaissIDSelectorXOr** p_sel,
+ const FaissIDSelector* lhs_sel,
+ const FaissIDSelector* rhs_sel) {
+ try {
+ *p_sel = reinterpret_cast<FaissIDSelectorXOr*>(new IDSelectorXOr(
+ reinterpret_cast<const IDSelector*>(lhs_sel),
+ reinterpret_cast<const IDSelector*>(rhs_sel)));
+ }
+ CATCH_AND_HANDLE
+}
+
+// Below are structures used only by Index implementations
+
+DEFINE_DESTRUCTOR(BufferList)
+
+DEFINE_GETTER(BufferList, size_t, buffer_size)
+DEFINE_GETTER(BufferList, size_t, wp)
+
+int faiss_BufferList_append_buffer(FaissBufferList* bl) {
+ try {
+ reinterpret_cast<BufferList*>(bl)->append_buffer();
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_BufferList_new(FaissBufferList** p_bl, size_t buffer_size) {
+ try {
+ *p_bl = reinterpret_cast<FaissBufferList*>(new BufferList(buffer_size));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_BufferList_add(FaissBufferList* bl, idx_t id, float dis) {
+ try {
+ reinterpret_cast<BufferList*>(bl)->add(id, dis);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+/// copy elemnts ofs:ofs+n-1 seen as linear data in the buffers to
+/// tables dest_ids, dest_dis
+int faiss_BufferList_copy_range(
+ FaissBufferList* bl,
+ size_t ofs,
+ size_t n,
+ idx_t* dest_ids,
+ float* dest_dis) {
+ try {
+ reinterpret_cast<BufferList*>(bl)->copy_range(
+ ofs, n, dest_ids, dest_dis);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER(RangeQueryResult, idx_t, qno)
+DEFINE_GETTER(RangeQueryResult, size_t, nres)
+DEFINE_GETTER_PERMISSIVE(RangeQueryResult, FaissRangeSearchPartialResult*, pres)
+
+int faiss_RangeQueryResult_add(FaissRangeQueryResult* qr, float dis, idx_t id) {
+ try {
+ reinterpret_cast<RangeQueryResult*>(qr)->add(dis, id);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_GETTER_PERMISSIVE(RangeSearchPartialResult, FaissRangeSearchResult*, res)
+
+int faiss_RangeSearchPartialResult_new(
+ FaissRangeSearchPartialResult** p_res,
+ FaissRangeSearchResult* res_in) {
+ try {
+ *p_res = reinterpret_cast<FaissRangeSearchPartialResult*>(
+ new RangeSearchPartialResult(
+ reinterpret_cast<RangeSearchResult*>(res_in)));
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_RangeSearchPartialResult_finalize(
+ FaissRangeSearchPartialResult* res) {
+ try {
+ reinterpret_cast<RangeSearchPartialResult*>(res)->finalize();
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+/// called by range_search before do_allocation
+int faiss_RangeSearchPartialResult_set_lims(
+ FaissRangeSearchPartialResult* res) {
+ try {
+ reinterpret_cast<RangeSearchPartialResult*>(res)->set_lims();
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_RangeSearchPartialResult_new_result(
+ FaissRangeSearchPartialResult* res,
+ idx_t qno,
+ FaissRangeQueryResult** qr) {
+ try {
+ auto q = &reinterpret_cast<RangeSearchPartialResult*>(res)->new_result(
+ qno);
+ if (qr) {
+ *qr = reinterpret_cast<FaissRangeQueryResult*>(&q);
+ }
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+DEFINE_DESTRUCTOR(DistanceComputer)
+
+int faiss_DistanceComputer_set_query(
+ FaissDistanceComputer* dc,
+ const float* x) {
+ try {
+ reinterpret_cast<DistanceComputer*>(dc)->set_query(x);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_DistanceComputer_vector_to_query_dis(
+ FaissDistanceComputer* dc,
+ idx_t i,
+ float* qd) {
+ try {
+ *qd = reinterpret_cast<DistanceComputer*>(dc)->operator()(i);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_DistanceComputer_symmetric_dis(
+ FaissDistanceComputer* dc,
+ idx_t i,
+ idx_t j,
+ float* vd) {
+ try {
+ *vd = reinterpret_cast<DistanceComputer*>(dc)->symmetric_dis(i, j);
+ return 0;
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/impl/AuxIndexStructures_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/impl/AuxIndexStructures_c.h
new file mode 100644
index 0000000..c4be631
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/impl/AuxIndexStructures_c.h
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_AUX_INDEX_STRUCTURES_C_H
+#define FAISS_AUX_INDEX_STRUCTURES_C_H
+
+#include "../Index_c.h"
+#include "../faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+FAISS_DECLARE_CLASS(RangeSearchResult)
+
+FAISS_DECLARE_GETTER(RangeSearchResult, size_t, nq)
+
+int faiss_RangeSearchResult_new(FaissRangeSearchResult** p_rsr, idx_t nq);
+
+int faiss_RangeSearchResult_new_with(
+ FaissRangeSearchResult** p_rsr,
+ idx_t nq,
+ int alloc_lims);
+
+/// called when lims contains the nb of elements result entries
+/// for each query
+int faiss_RangeSearchResult_do_allocation(FaissRangeSearchResult* rsr);
+
+FAISS_DECLARE_DESTRUCTOR(RangeSearchResult)
+
+/// getter for buffer_size
+FAISS_DECLARE_GETTER(RangeSearchResult, size_t, buffer_size)
+
+/// getter for lims: size (nq + 1)
+void faiss_RangeSearchResult_lims(FaissRangeSearchResult* rsr, size_t** lims);
+
+/// getter for labels and respective distances (not sorted):
+/// result for query i is labels[lims[i]:lims[i+1]]
+void faiss_RangeSearchResult_labels(
+ FaissRangeSearchResult* rsr,
+ idx_t** labels,
+ float** distances);
+
+/** Encapsulates a set of ids to remove. */
+FAISS_DECLARE_CLASS(IDSelector)
+FAISS_DECLARE_DESTRUCTOR(IDSelector)
+
+int faiss_IDSelector_is_member(const FaissIDSelector* sel, idx_t id);
+
+/** remove ids between [imni, imax) */
+FAISS_DECLARE_CLASS(IDSelectorRange)
+FAISS_DECLARE_DESTRUCTOR(IDSelectorRange)
+
+FAISS_DECLARE_GETTER(IDSelectorRange, idx_t, imin)
+FAISS_DECLARE_GETTER(IDSelectorRange, idx_t, imax)
+
+int faiss_IDSelectorRange_new(
+ FaissIDSelectorRange** p_sel,
+ idx_t imin,
+ idx_t imax);
+
+/** Remove ids from a set. Repetitions of ids in the indices set
+ * passed to the constructor does not hurt performance. The hash
+ * function used for the bloom filter and GCC's implementation of
+ * unordered_set are just the least significant bits of the id. This
+ * works fine for random ids or ids in sequences but will produce many
+ * hash collisions if lsb's are always the same */
+FAISS_DECLARE_CLASS(IDSelectorBatch)
+
+FAISS_DECLARE_GETTER(IDSelectorBatch, int, nbits)
+FAISS_DECLARE_GETTER(IDSelectorBatch, idx_t, mask)
+
+int faiss_IDSelectorBatch_new(
+ FaissIDSelectorBatch** p_sel,
+ size_t n,
+ const idx_t* indices);
+
+FAISS_DECLARE_CLASS(IDSelectorBitmap)
+FAISS_DECLARE_DESTRUCTOR(IDSelectorBitmap)
+
+FAISS_DECLARE_GETTER(IDSelectorBitmap, size_t, n)
+FAISS_DECLARE_GETTER(IDSelectorBitmap, const uint8_t*, bitmap)
+
+int faiss_IDSelectorBitmap_new(
+ FaissIDSelectorBitmap** p_sel,
+ size_t n,
+ const uint8_t* bitmap);
+
+FAISS_DECLARE_CLASS(IDSelectorNot)
+int faiss_IDSelectorNot_new(
+ FaissIDSelectorNot** p_sel,
+ const FaissIDSelector* sel);
+
+FAISS_DECLARE_CLASS(IDSelectorAnd)
+int faiss_IDSelectorAnd_new(
+ FaissIDSelectorAnd** p_sel,
+ const FaissIDSelector* lhs_sel,
+ const FaissIDSelector* rhs_sel);
+
+FAISS_DECLARE_CLASS(IDSelectorOr)
+int faiss_IDSelectorOr_new(
+ FaissIDSelectorOr** p_sel,
+ const FaissIDSelector* lhs_sel,
+ const FaissIDSelector* rhs_sel);
+
+FAISS_DECLARE_CLASS(IDSelectorXOr)
+int faiss_IDSelectorXOr_new(
+ FaissIDSelectorXOr** p_sel,
+ const FaissIDSelector* lhs_sel,
+ const FaissIDSelector* rhs_sel);
+
+// Below are structures used only by Index implementations
+
+/** List of temporary buffers used to store results before they are
+ * copied to the RangeSearchResult object. */
+FAISS_DECLARE_CLASS(BufferList)
+FAISS_DECLARE_DESTRUCTOR(BufferList)
+
+FAISS_DECLARE_GETTER(BufferList, size_t, buffer_size)
+FAISS_DECLARE_GETTER(BufferList, size_t, wp)
+
+typedef struct FaissBuffer {
+ idx_t* ids;
+ float* dis;
+} FaissBuffer;
+
+int faiss_BufferList_append_buffer(FaissBufferList* bl);
+
+int faiss_BufferList_new(FaissBufferList** p_bl, size_t buffer_size);
+
+int faiss_BufferList_add(FaissBufferList* bl, idx_t id, float dis);
+
+/// copy elemnts ofs:ofs+n-1 seen as linear data in the buffers to
+/// tables dest_ids, dest_dis
+int faiss_BufferList_copy_range(
+ FaissBufferList* bl,
+ size_t ofs,
+ size_t n,
+ idx_t* dest_ids,
+ float* dest_dis);
+
+/// the entries in the buffers are split per query
+FAISS_DECLARE_CLASS(RangeSearchPartialResult)
+
+/// result structure for a single query
+FAISS_DECLARE_CLASS(RangeQueryResult)
+FAISS_DECLARE_GETTER(RangeQueryResult, idx_t, qno)
+FAISS_DECLARE_GETTER(RangeQueryResult, size_t, nres)
+FAISS_DECLARE_GETTER(RangeQueryResult, FaissRangeSearchPartialResult*, pres)
+
+int faiss_RangeQueryResult_add(FaissRangeQueryResult* qr, float dis, idx_t id);
+
+FAISS_DECLARE_GETTER(RangeSearchPartialResult, FaissRangeSearchResult*, res)
+
+int faiss_RangeSearchPartialResult_new(
+ FaissRangeSearchPartialResult** p_res,
+ FaissRangeSearchResult* res_in);
+
+int faiss_RangeSearchPartialResult_finalize(FaissRangeSearchPartialResult* res);
+
+/// called by range_search before do_allocation
+int faiss_RangeSearchPartialResult_set_lims(FaissRangeSearchPartialResult* res);
+
+int faiss_RangeSearchPartialResult_new_result(
+ FaissRangeSearchPartialResult* res,
+ idx_t qno,
+ FaissRangeQueryResult** qr);
+
+FAISS_DECLARE_CLASS(DistanceComputer)
+/// called before computing distances
+int faiss_DistanceComputer_set_query(FaissDistanceComputer* dc, const float* x);
+
+/**
+ * Compute distance of vector i to current query.
+ * This function corresponds to the function call operator:
+ * DistanceComputer::operator()
+ */
+int faiss_DistanceComputer_vector_to_query_dis(
+ FaissDistanceComputer* dc,
+ idx_t i,
+ float* qd);
+/// compute distance between two stored vectors
+int faiss_DistanceComputer_symmetric_dis(
+ FaissDistanceComputer* dc,
+ idx_t i,
+ idx_t j,
+ float* vd);
+
+FAISS_DECLARE_DESTRUCTOR(DistanceComputer)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/index_factory_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_factory_c.cpp
new file mode 100644
index 0000000..6fea651
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_factory_c.cpp
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "index_factory_c.h"
+#include <faiss/index_factory.h>
+#include <cstring>
+#include "macros_impl.h"
+
+using faiss::Index;
+
+/** Build an index with the sequence of processing steps described in
+ * the string.
+ */
+int faiss_index_factory(
+ FaissIndex** p_index,
+ int d,
+ const char* description,
+ FaissMetricType metric) {
+ try {
+ *p_index = reinterpret_cast<FaissIndex*>(faiss::index_factory(
+ d, description, static_cast<faiss::MetricType>(metric)));
+ }
+ CATCH_AND_HANDLE
+}
+
+/** Build an index with the sequence of processing steps described in
+ * the string.
+ */
+int faiss_index_binary_factory(
+ FaissIndexBinary** p_index,
+ int d,
+ const char* description) {
+ try {
+ *p_index = reinterpret_cast<FaissIndexBinary*>(
+ faiss::index_binary_factory(d, description));
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/index_factory_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_factory_c.h
new file mode 100644
index 0000000..3790a0e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_factory_c.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_INDEX_FACTORY_C_H
+#define FAISS_INDEX_FACTORY_C_H
+
+#include "IndexBinary_c.h"
+#include "Index_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Build an index with the sequence of processing steps described in
+ * the string.
+ */
+int faiss_index_factory(
+ FaissIndex** p_index,
+ int d,
+ const char* description,
+ FaissMetricType metric);
+
+/** Build a binary index with the sequence of processing steps described in
+ * the string.
+ */
+int faiss_index_binary_factory(
+ FaissIndexBinary** p_index,
+ int d,
+ const char* description);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/index_io_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_io_c.cpp
new file mode 100644
index 0000000..ea3068e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_io_c.cpp
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+// I/O code for indexes
+
+#include "index_io_c.h"
+#include <faiss/index_io.h>
+#include "macros_impl.h"
+
+using faiss::Index;
+using faiss::IndexBinary;
+using faiss::VectorTransform;
+
+int faiss_write_index(const FaissIndex* idx, FILE* f) {
+ try {
+ faiss::write_index(reinterpret_cast<const Index*>(idx), f);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_write_index_fname(const FaissIndex* idx, const char* fname) {
+ try {
+ faiss::write_index(reinterpret_cast<const Index*>(idx), fname);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_read_index(FILE* f, int io_flags, FaissIndex** p_out) {
+ try {
+ auto out = faiss::read_index(f, io_flags);
+ *p_out = reinterpret_cast<FaissIndex*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_read_index_fname(
+ const char* fname,
+ int io_flags,
+ FaissIndex** p_out) {
+ try {
+ auto out = faiss::read_index(fname, io_flags);
+ *p_out = reinterpret_cast<FaissIndex*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_write_index_binary(const FaissIndexBinary* idx, FILE* f) {
+ try {
+ faiss::write_index_binary(reinterpret_cast<const IndexBinary*>(idx), f);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_write_index_binary_fname(
+ const FaissIndexBinary* idx,
+ const char* fname) {
+ try {
+ faiss::write_index_binary(
+ reinterpret_cast<const IndexBinary*>(idx), fname);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_read_index_binary(FILE* f, int io_flags, FaissIndexBinary** p_out) {
+ try {
+ auto out = faiss::read_index_binary(f, io_flags);
+ *p_out = reinterpret_cast<FaissIndexBinary*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_read_index_binary_fname(
+ const char* fname,
+ int io_flags,
+ FaissIndexBinary** p_out) {
+ try {
+ auto out = faiss::read_index_binary(fname, io_flags);
+ *p_out = reinterpret_cast<FaissIndexBinary*>(out);
+ }
+ CATCH_AND_HANDLE
+}
+
+int faiss_read_VectorTransform_fname(
+ const char* fname,
+ FaissVectorTransform** p_out) {
+ try {
+ auto out = faiss::read_VectorTransform(fname);
+ *p_out = reinterpret_cast<FaissVectorTransform*>(out);
+ }
+ CATCH_AND_HANDLE
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/index_io_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_io_c.h
new file mode 100644
index 0000000..fd4da61
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/index_io_c.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+// I/O code for indexes
+
+#ifndef FAISS_INDEX_IO_C_H
+#define FAISS_INDEX_IO_C_H
+
+#include <stdio.h>
+#include "IndexBinary_c.h"
+#include "Index_c.h"
+#include "VectorTransform_c.h"
+#include "faiss_c.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Write index to a file.
+ * This is equivalent to `faiss::write_index` when a file descriptor is
+ * provided.
+ */
+int faiss_write_index(const FaissIndex* idx, FILE* f);
+
+/** Write index to a file.
+ * This is equivalent to `faiss::write_index` when a file path is provided.
+ */
+int faiss_write_index_fname(const FaissIndex* idx, const char* fname);
+
+#define FAISS_IO_FLAG_MMAP 1
+#define FAISS_IO_FLAG_READ_ONLY 2
+
+/** Read index from a file.
+ * This is equivalent to `faiss:read_index` when a file descriptor is given.
+ */
+int faiss_read_index(FILE* f, int io_flags, FaissIndex** p_out);
+
+/** Read index from a file.
+ * This is equivalent to `faiss:read_index` when a file path is given.
+ */
+int faiss_read_index_fname(const char* fname, int io_flags, FaissIndex** p_out);
+
+/** Write index to a file.
+ * This is equivalent to `faiss::write_index_binary` when a file descriptor is
+ * provided.
+ */
+int faiss_write_index_binary(const FaissIndexBinary* idx, FILE* f);
+
+/** Write index to a file.
+ * This is equivalent to `faiss::write_index_binary` when a file path is
+ * provided.
+ */
+int faiss_write_index_binary_fname(
+ const FaissIndexBinary* idx,
+ const char* fname);
+
+/** Read index from a file.
+ * This is equivalent to `faiss:read_index_binary` when a file descriptor is
+ * given.
+ */
+int faiss_read_index_binary(FILE* f, int io_flags, FaissIndexBinary** p_out);
+
+/** Read index from a file.
+ * This is equivalent to `faiss:read_index_binary` when a file path is given.
+ */
+int faiss_read_index_binary_fname(
+ const char* fname,
+ int io_flags,
+ FaissIndexBinary** p_out);
+
+/** Read vector transform from a file.
+ * This is equivalent to `faiss:read_VectorTransform` when a file path is given.
+ */
+int faiss_read_VectorTransform_fname(
+ const char* fname,
+ FaissVectorTransform** p_out);
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/macros_impl.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/macros_impl.h
new file mode 100644
index 0000000..ade7bb1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/macros_impl.h
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/// Utility macros for the C wrapper implementation.
+
+#ifndef MACROS_IMPL_H
+#define MACROS_IMPL_H
+
+#include <faiss/impl/FaissException.h>
+#include <iostream>
+#include <stdexcept>
+#include "error_impl.h"
+#include "faiss_c.h"
+
+#ifdef NDEBUG
+#define CATCH_AND_HANDLE \
+ catch (faiss::FaissException & e) { \
+ faiss_last_exception = std::make_exception_ptr(e); \
+ return -2; \
+ } \
+ catch (std::exception & e) { \
+ faiss_last_exception = std::make_exception_ptr(e); \
+ return -4; \
+ } \
+ catch (...) { \
+ faiss_last_exception = \
+ std::make_exception_ptr(std::runtime_error("Unknown error")); \
+ return -1; \
+ } \
+ return 0;
+#else
+#define CATCH_AND_HANDLE \
+ catch (faiss::FaissException & e) { \
+ std::cerr << e.what() << '\n'; \
+ faiss_last_exception = std::make_exception_ptr(e); \
+ return -2; \
+ } \
+ catch (std::exception & e) { \
+ std::cerr << e.what() << '\n'; \
+ faiss_last_exception = std::make_exception_ptr(e); \
+ return -4; \
+ } \
+ catch (...) { \
+ std::cerr << "Unrecognized exception!\n"; \
+ faiss_last_exception = \
+ std::make_exception_ptr(std::runtime_error("Unknown error")); \
+ return -1; \
+ } \
+ return 0;
+#endif
+
+#define DEFINE_GETTER(clazz, ty, name) \
+ ty faiss_##clazz##_##name(const Faiss##clazz* obj) { \
+ return static_cast<ty>( \
+ reinterpret_cast<const faiss::clazz*>(obj)->name); \
+ }
+
+#define DEFINE_GETTER_SUBCLASS(clazz, parent, ty, name) \
+ ty faiss_##clazz##_##name(const Faiss##clazz* obj) { \
+ return static_cast<ty>( \
+ reinterpret_cast<const faiss::parent::clazz*>(obj)->name); \
+ }
+
+#define DEFINE_GETTER_PERMISSIVE(clazz, ty, name) \
+ ty faiss_##clazz##_##name(const Faiss##clazz* obj) { \
+ return (ty)(reinterpret_cast<const faiss::clazz*>(obj)->name); \
+ }
+
+#define DEFINE_GETTER_SUBCLASS_PERMISSIVE(clazz, parent, ty, name) \
+ ty faiss_##clazz##_##name(const Faiss##clazz* obj) { \
+ return (ty)(reinterpret_cast<const faiss::parent::clazz*>(obj)->name); \
+ }
+
+#define DEFINE_SETTER(clazz, ty, name) \
+ void faiss_##clazz##_set_##name(Faiss##clazz* obj, ty val) { \
+ reinterpret_cast<faiss::clazz*>(obj)->name = val; \
+ }
+
+#define DEFINE_SETTER_STATIC(clazz, ty_to, ty_from, name) \
+ void faiss_##clazz##_set_##name(Faiss##clazz* obj, ty_from val) { \
+ reinterpret_cast<faiss::clazz*>(obj)->name = static_cast<ty_to>(val); \
+ }
+
+#define DEFINE_DESTRUCTOR(clazz) \
+ void faiss_##clazz##_free(Faiss##clazz* obj) { \
+ delete reinterpret_cast<faiss::clazz*>(obj); \
+ }
+
+#define DEFINE_INDEX_DOWNCAST(clazz) \
+ Faiss##clazz* faiss_##clazz##_cast(FaissIndex* index) { \
+ return reinterpret_cast<Faiss##clazz*>(dynamic_cast<faiss::clazz*>( \
+ reinterpret_cast<faiss::Index*>(index))); \
+ }
+
+#define DEFINE_SEARCH_PARAMETERS_DOWNCAST(clazz) \
+ Faiss##clazz* faiss_##clazz##_cast(FaissSearchParameters* sp) { \
+ return reinterpret_cast<Faiss##clazz*>(dynamic_cast<faiss::clazz*>( \
+ reinterpret_cast<faiss::SearchParameters*>(sp))); \
+ }
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/distances_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/distances_c.cpp
new file mode 100644
index 0000000..025bae5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/distances_c.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "distances_c.h"
+#include <faiss/utils/distances.h>
+#include <cstdio>
+
+void faiss_pairwise_L2sqr(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis,
+ int64_t ldq,
+ int64_t ldb,
+ int64_t ldd) {
+ faiss::pairwise_L2sqr(d, nq, xq, nb, xb, dis, ldq, ldb, ldd);
+}
+
+void faiss_pairwise_L2sqr_with_defaults(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis) {
+ faiss::pairwise_L2sqr(d, nq, xq, nb, xb, dis);
+}
+
+void faiss_fvec_inner_products_ny(
+ float* ip,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ faiss::fvec_inner_products_ny(ip, x, y, d, ny);
+}
+
+void faiss_fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ faiss::fvec_L2sqr_ny(dis, x, y, d, ny);
+}
+
+float faiss_fvec_norm_L2sqr(const float* x, size_t d) {
+ return faiss::fvec_norm_L2sqr(x, d);
+}
+
+void faiss_fvec_norms_L2(float* norms, const float* x, size_t d, size_t nx) {
+ faiss::fvec_norms_L2(norms, x, d, nx);
+}
+
+void faiss_fvec_norms_L2sqr(float* norms, const float* x, size_t d, size_t nx) {
+ faiss::fvec_norms_L2sqr(norms, x, d, nx);
+}
+
+void faiss_fvec_renorm_L2(size_t d, size_t nx, float* x) {
+ faiss::fvec_renorm_L2(d, nx, x);
+}
+
+void faiss_set_distance_compute_blas_threshold(int value) {
+ faiss::distance_compute_blas_threshold = value;
+}
+
+int faiss_get_distance_compute_blas_threshold() {
+ return faiss::distance_compute_blas_threshold;
+}
+
+void faiss_set_distance_compute_blas_query_bs(int value) {
+ faiss::distance_compute_blas_query_bs = value;
+}
+
+int faiss_get_distance_compute_blas_query_bs() {
+ return faiss::distance_compute_blas_query_bs;
+}
+
+void faiss_set_distance_compute_blas_database_bs(int value) {
+ faiss::distance_compute_blas_database_bs = value;
+}
+
+int faiss_get_distance_compute_blas_database_bs() {
+ return faiss::distance_compute_blas_database_bs;
+}
+
+void faiss_set_distance_compute_min_k_reservoir(int value) {
+ faiss::distance_compute_min_k_reservoir = value;
+}
+
+int faiss_get_distance_compute_min_k_reservoir() {
+ return faiss::distance_compute_min_k_reservoir;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/distances_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/distances_c.h
new file mode 100644
index 0000000..e2ef643
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/distances_c.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_DISTANCES_C_H
+#define FAISS_DISTANCES_C_H
+
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*********************************************************
+ * Optimized distance/norm/inner prod computations
+ *********************************************************/
+
+/// Compute pairwise distances between sets of vectors
+void faiss_pairwise_L2sqr(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis,
+ int64_t ldq,
+ int64_t ldb,
+ int64_t ldd);
+
+/// Compute pairwise distances between sets of vectors
+/// arguments from "faiss_pairwise_L2sqr"
+/// ldq equal -1 by default
+/// ldb equal -1 by default
+/// ldd equal -1 by default
+void faiss_pairwise_L2sqr_with_defaults(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis);
+
+/// compute the inner product between nx vectors x and one y
+void faiss_fvec_inner_products_ny(
+ float* ip, /* output inner product */
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny);
+
+/// compute ny square L2 distance between x and a set of contiguous y vectors
+void faiss_fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny);
+
+/// squared norm of a vector
+float faiss_fvec_norm_L2sqr(const float* x, size_t d);
+
+/// compute the L2 norms for a set of vectors
+void faiss_fvec_norms_L2(float* norms, const float* x, size_t d, size_t nx);
+
+/// same as fvec_norms_L2, but computes squared norms
+void faiss_fvec_norms_L2sqr(float* norms, const float* x, size_t d, size_t nx);
+
+/// L2-renormalize a set of vector. Nothing done if the vector is 0-normed
+void faiss_fvec_renorm_L2(size_t d, size_t nx, float* x);
+
+/// Setter of threshold value on nx above which we switch to BLAS to compute
+/// distances
+void faiss_set_distance_compute_blas_threshold(int value);
+
+/// Getter of threshold value on nx above which we switch to BLAS to compute
+/// distances
+int faiss_get_distance_compute_blas_threshold();
+
+/// Setter of block sizes value for BLAS distance computations
+void faiss_set_distance_compute_blas_query_bs(int value);
+
+/// Getter of block sizes value for BLAS distance computations
+int faiss_get_distance_compute_blas_query_bs();
+
+/// Setter of block sizes value for BLAS distance computations
+void faiss_set_distance_compute_blas_database_bs(int value);
+
+/// Getter of block sizes value for BLAS distance computations
+int faiss_get_distance_compute_blas_database_bs();
+
+/// Setter of number of results we switch to a reservoir to collect results
+/// rather than a heap
+void faiss_set_distance_compute_min_k_reservoir(int value);
+
+/// Getter of number of results we switch to a reservoir to collect results
+/// rather than a heap
+int faiss_get_distance_compute_min_k_reservoir();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/utils_c.cpp b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/utils_c.cpp
new file mode 100644
index 0000000..b66a069
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/utils_c.cpp
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include "utils_c.h"
+#include <faiss/Index.h>
+
+const char* faiss_get_version() {
+ return VERSION_STRING;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/utils_c.h b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/utils_c.h
new file mode 100644
index 0000000..a8b3ffa
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/c_api/utils/utils_c.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c -*-
+
+#ifndef FAISS_UTILS_C_H
+#define FAISS_UTILS_C_H
+
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+const char* faiss_get_version();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/cmake/FindMKL.cmake b/packages/leann-backend-hnsw/third_party/faiss/cmake/FindMKL.cmake
new file mode 100644
index 0000000..4504859
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/cmake/FindMKL.cmake
@@ -0,0 +1,364 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+# Adapted from CMake's FindBLAS module.
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindMKL
+--------
+
+Find Intel MKL library.
+
+Input Variables
+^^^^^^^^^^^^^^^
+
+The following variables may be set to influence this module's behavior:
+
+``BLA_STATIC``
+ if ``ON`` use static linkage
+
+``BLA_VENDOR``
+ If set, checks only the specified vendor, if not set checks all the
+ possibilities. List of vendors valid in this module:
+
+ * ``Intel10_32`` (intel mkl v10 32 bit)
+ * ``Intel10_64lp`` (intel mkl v10+ 64 bit, threaded code, lp64 model)
+ * ``Intel10_64lp_seq`` (intel mkl v10+ 64 bit, sequential code, lp64 model)
+ * ``Intel10_64ilp`` (intel mkl v10+ 64 bit, threaded code, ilp64 model)
+ * ``Intel10_64ilp_seq`` (intel mkl v10+ 64 bit, sequential code, ilp64 model)
+ * ``Intel10_64_dyn`` (intel mkl v10+ 64 bit, single dynamic library)
+ * ``Intel`` (obsolete versions of mkl 32 and 64 bit)
+
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module defines the following variables:
+
+``MKL_FOUND``
+ library implementing the BLAS interface is found
+``MKL_LIBRARIES``
+ uncached list of libraries (using full path name) to link against
+ to use MKL (may be empty if compiler implicitly links MKL)
+
+.. note::
+
+ C or CXX must be enabled to use Intel Math Kernel Library (MKL).
+
+ For example, to use Intel MKL libraries and/or Intel compiler:
+
+ .. code-block:: cmake
+
+ set(BLA_VENDOR Intel10_64lp)
+ find_package(MKL)
+
+Hints
+^^^^^
+
+Set the ``MKLROOT`` environment variable to a directory that contains an MKL
+installation, or add the directory to the dynamic library loader environment
+variable for your platform (``LIB``, ``DYLD_LIBRARY_PATH`` or
+``LD_LIBRARY_PATH``).
+
+#]=======================================================================]
+
+include(CheckFunctionExists)
+include(CMakePushCheckState)
+include(FindPackageHandleStandardArgs)
+cmake_push_check_state()
+set(CMAKE_REQUIRED_QUIET ${BLAS_FIND_QUIETLY})
+
+
+set(_blas_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
+if(BLA_STATIC)
+ if(WIN32)
+ set(CMAKE_FIND_LIBRARY_SUFFIXES .lib ${CMAKE_FIND_LIBRARY_SUFFIXES})
+ else()
+ set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
+ endif()
+else()
+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ # for ubuntu's libblas3gf and liblapack3gf packages
+ set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES} .so.3gf)
+ endif()
+endif()
+
+macro(CHECK_BLAS_LIBRARIES LIBRARIES _prefix _name _flags _list _threadlibs _addlibdir _subdirs)
+ # This macro checks for the existence of the combination of fortran libraries
+ # given by _list. If the combination is found, this macro checks (using the
+ # Check_Fortran_Function_Exists macro) whether can link against that library
+ # combination using the name of a routine given by _name using the linker
+ # flags given by _flags. If the combination of libraries is found and passes
+ # the link test, LIBRARIES is set to the list of complete library paths that
+ # have been found. Otherwise, LIBRARIES is set to FALSE.
+
+ # N.B. _prefix is the prefix applied to the names of all cached variables that
+ # are generated internally and marked advanced by this macro.
+ # _addlibdir is a list of additional search paths. _subdirs is a list of path
+ # suffixes to be used by find_library().
+
+ set(_libraries_work TRUE)
+ set(${LIBRARIES})
+ set(_combined_name)
+
+ set(_extaddlibdir "${_addlibdir}")
+ if(WIN32)
+ list(APPEND _extaddlibdir ENV LIB)
+ elseif(APPLE)
+ list(APPEND _extaddlibdir ENV DYLD_LIBRARY_PATH)
+ else()
+ list(APPEND _extaddlibdir ENV LD_LIBRARY_PATH)
+ endif()
+ list(APPEND _extaddlibdir "${CMAKE_C_IMPLICIT_LINK_DIRECTORIES}")
+
+ foreach(_library ${_list})
+ if(_library MATCHES "^-Wl,--(start|end)-group$")
+ # Respect linker flags like --start/end-group (required by MKL)
+ set(${LIBRARIES} ${${LIBRARIES}} "${_library}")
+ else()
+ set(_combined_name ${_combined_name}_${_library})
+ if(NOT "${_threadlibs}" STREQUAL "")
+ set(_combined_name ${_combined_name}_threadlibs)
+ endif()
+ if(_libraries_work)
+ find_library(${_prefix}_${_library}_LIBRARY
+ NAMES ${_library}
+ PATHS ${_extaddlibdir}
+ PATH_SUFFIXES ${_subdirs}
+ )
+ #message("DEBUG: find_library(${_library}) got ${${_prefix}_${_library}_LIBRARY}")
+ mark_as_advanced(${_prefix}_${_library}_LIBRARY)
+ set(${LIBRARIES} ${${LIBRARIES}} ${${_prefix}_${_library}_LIBRARY})
+ set(_libraries_work ${${_prefix}_${_library}_LIBRARY})
+ endif()
+ endif()
+ endforeach()
+
+ if(_libraries_work)
+ # Test this combination of libraries.
+ set(CMAKE_REQUIRED_LIBRARIES ${_flags} ${${LIBRARIES}} ${_threadlibs})
+ #message("DEBUG: CMAKE_REQUIRED_LIBRARIES = ${CMAKE_REQUIRED_LIBRARIES}")
+ if(CMAKE_Fortran_COMPILER_LOADED)
+ check_fortran_function_exists("${_name}" ${_prefix}${_combined_name}_WORKS)
+ else()
+ check_function_exists("${_name}_" ${_prefix}${_combined_name}_WORKS)
+ endif()
+ set(CMAKE_REQUIRED_LIBRARIES)
+ set(_libraries_work ${${_prefix}${_combined_name}_WORKS})
+ endif()
+
+ if(_libraries_work)
+ if("${_list}" STREQUAL "")
+ set(${LIBRARIES} "${LIBRARIES}-PLACEHOLDER-FOR-EMPTY-LIBRARIES")
+ else()
+ set(${LIBRARIES} ${${LIBRARIES}} ${_threadlibs})
+ endif()
+ else()
+ set(${LIBRARIES} FALSE)
+ endif()
+ #message("DEBUG: ${LIBRARIES} = ${${LIBRARIES}}")
+endmacro()
+
+set(MKL_LIBRARIES)
+if(NOT $ENV{BLA_VENDOR} STREQUAL "")
+ set(BLA_VENDOR $ENV{BLA_VENDOR})
+else()
+ if(NOT BLA_VENDOR)
+ set(BLA_VENDOR "All")
+ endif()
+endif()
+if(BLA_VENDOR_THREADING)
+ set(BLAS_mkl_THREADING ${BLA_VENDOR_THREADING})
+else()
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ set(BLAS_mkl_THREADING "gnu")
+ else()
+ set(BLAS_mkl_THREADING "intel")
+ endif()
+endif()
+
+if(CMAKE_C_COMPILER_LOADED OR CMAKE_CXX_COMPILER_LOADED)
+ # System-specific settings
+ if(WIN32)
+ if(BLA_STATIC)
+ set(BLAS_mkl_DLL_SUFFIX "")
+ else()
+ set(BLAS_mkl_DLL_SUFFIX "_dll")
+ endif()
+ else()
+ if(BLA_STATIC)
+ set(BLAS_mkl_START_GROUP "-Wl,--start-group")
+ set(BLAS_mkl_END_GROUP "-Wl,--end-group")
+ else()
+ set(BLAS_mkl_START_GROUP "")
+ set(BLAS_mkl_END_GROUP "")
+ endif()
+ if(BLAS_mkl_THREADING STREQUAL "gnu")
+ set(BLAS_mkl_OMP "gomp")
+ else()
+ set(BLAS_mkl_OMP "iomp5")
+ endif()
+ set(BLAS_mkl_LM "-lm")
+ set(BLAS_mkl_LDL "-ldl")
+ endif()
+
+ if(BLAS_FIND_QUIETLY OR NOT BLAS_FIND_REQUIRED)
+ find_package(Threads)
+ else()
+ find_package(Threads REQUIRED)
+ endif()
+
+ set(BLAS_mkl_INTFACE "intel")
+ if(BLA_VENDOR MATCHES "_64ilp")
+ set(BLAS_mkl_ILP_MODE "ilp64")
+ else()
+ set(BLAS_mkl_ILP_MODE "lp64")
+ endif()
+
+ set(BLAS_SEARCH_LIBS "")
+
+ set(BLAS_mkl_SEARCH_SYMBOL sgemm)
+ set(_LIBRARIES MKL_LIBRARIES)
+ if(WIN32)
+ # Find the main file (32-bit or 64-bit)
+ set(BLAS_SEARCH_LIBS_WIN_MAIN "")
+ if(BLA_VENDOR STREQUAL "Intel10_32" OR BLA_VENDOR STREQUAL "All")
+ list(APPEND BLAS_SEARCH_LIBS_WIN_MAIN
+ "mkl_intel_c${BLAS_mkl_DLL_SUFFIX}")
+ endif()
+ if(BLA_VENDOR MATCHES "^Intel10_64i?lp" OR BLA_VENDOR STREQUAL "All")
+ list(APPEND BLAS_SEARCH_LIBS_WIN_MAIN
+ "mkl_intel_${BLAS_mkl_ILP_MODE}${BLAS_mkl_DLL_SUFFIX}")
+ endif()
+
+ # Add threading/sequential libs
+ set(BLAS_SEARCH_LIBS_WIN_THREAD "")
+ if(BLA_VENDOR MATCHES "^Intel10_64i?lp$" OR BLA_VENDOR STREQUAL "All")
+ # old version
+ list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
+ "libguide40 mkl_intel_thread${BLAS_mkl_DLL_SUFFIX}")
+ # mkl >= 10.3
+ list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
+ "libiomp5md mkl_intel_thread${BLAS_mkl_DLL_SUFFIX}")
+ endif()
+ if(BLA_VENDOR MATCHES "^Intel10_64i?lp_seq$" OR BLA_VENDOR STREQUAL "All")
+ list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
+ "mkl_sequential${BLAS_mkl_DLL_SUFFIX}")
+ endif()
+
+ # Cartesian product of the above
+ foreach(MAIN ${BLAS_SEARCH_LIBS_WIN_MAIN})
+ foreach(THREAD ${BLAS_SEARCH_LIBS_WIN_THREAD})
+ list(APPEND BLAS_SEARCH_LIBS
+ "${MAIN} ${THREAD} mkl_core${BLAS_mkl_DLL_SUFFIX}")
+ endforeach()
+ endforeach()
+ else()
+ if(BLA_VENDOR STREQUAL "Intel10_32" OR BLA_VENDOR STREQUAL "All")
+ # old version
+ list(APPEND BLAS_SEARCH_LIBS
+ "mkl_${BLAS_mkl_INTFACE} mkl_${BLAS_mkl_THREADING}_thread mkl_core guide")
+
+ # mkl >= 10.3
+ list(APPEND BLAS_SEARCH_LIBS
+ "${BLAS_mkl_START_GROUP} mkl_${BLAS_mkl_INTFACE} mkl_${BLAS_mkl_THREADING}_thread mkl_core ${BLAS_mkl_END_GROUP} ${BLAS_mkl_OMP}")
+ endif()
+ if(BLA_VENDOR MATCHES "^Intel10_64i?lp$" OR BLA_VENDOR STREQUAL "All")
+ # old version
+ list(APPEND BLAS_SEARCH_LIBS
+ "mkl_${BLAS_mkl_INTFACE}_${BLAS_mkl_ILP_MODE} mkl_${BLAS_mkl_THREADING}_thread mkl_core guide")
+
+ # mkl >= 10.3
+ list(APPEND BLAS_SEARCH_LIBS
+ "${BLAS_mkl_START_GROUP} mkl_${BLAS_mkl_INTFACE}_${BLAS_mkl_ILP_MODE} mkl_${BLAS_mkl_THREADING}_thread mkl_core ${BLAS_mkl_END_GROUP} ${BLAS_mkl_OMP}")
+ endif()
+ if(BLA_VENDOR MATCHES "^Intel10_64i?lp_seq$" OR BLA_VENDOR STREQUAL "All")
+ list(APPEND BLAS_SEARCH_LIBS
+ "${BLAS_mkl_START_GROUP} mkl_${BLAS_mkl_INTFACE}_${BLAS_mkl_ILP_MODE} mkl_sequential mkl_core ${BLAS_mkl_END_GROUP}")
+ endif()
+
+ #older vesions of intel mkl libs
+ if(BLA_VENDOR STREQUAL "Intel" OR BLA_VENDOR STREQUAL "All")
+ list(APPEND BLAS_SEARCH_LIBS
+ "mkl")
+ list(APPEND BLAS_SEARCH_LIBS
+ "mkl_ia32")
+ list(APPEND BLAS_SEARCH_LIBS
+ "mkl_em64t")
+ endif()
+ endif()
+
+ if(BLA_VENDOR MATCHES "^Intel10_64_dyn$" OR BLA_VENDOR STREQUAL "All")
+ # mkl >= 10.3 with single dynamic library
+ list(APPEND BLAS_SEARCH_LIBS
+ "mkl_rt")
+ endif()
+
+ # MKL uses a multitude of partially platform-specific subdirectories:
+ if(BLA_VENDOR STREQUAL "Intel10_32")
+ set(BLAS_mkl_ARCH_NAME "ia32")
+ else()
+ set(BLAS_mkl_ARCH_NAME "intel64")
+ endif()
+ if(WIN32)
+ set(BLAS_mkl_OS_NAME "win")
+ elseif(APPLE)
+ set(BLAS_mkl_OS_NAME "mac")
+ else()
+ set(BLAS_mkl_OS_NAME "lin")
+ endif()
+ if(DEFINED ENV{MKLROOT})
+ file(TO_CMAKE_PATH "$ENV{MKLROOT}" BLAS_mkl_MKLROOT)
+ # If MKLROOT points to the subdirectory 'mkl', use the parent directory instead
+ # so we can better detect other relevant libraries in 'compiler' or 'tbb':
+ get_filename_component(BLAS_mkl_MKLROOT_LAST_DIR "${BLAS_mkl_MKLROOT}" NAME)
+ if(BLAS_mkl_MKLROOT_LAST_DIR STREQUAL "mkl")
+ get_filename_component(BLAS_mkl_MKLROOT "${BLAS_mkl_MKLROOT}" DIRECTORY)
+ endif()
+ endif()
+ set(BLAS_mkl_LIB_PATH_SUFFIXES
+ "compiler/lib" "compiler/lib/${BLAS_mkl_ARCH_NAME}_${BLAS_mkl_OS_NAME}"
+ "mkl/lib" "mkl/lib/${BLAS_mkl_ARCH_NAME}_${BLAS_mkl_OS_NAME}"
+ "lib/${BLAS_mkl_ARCH_NAME}_${BLAS_mkl_OS_NAME}")
+
+ foreach(IT ${BLAS_SEARCH_LIBS})
+ string(REPLACE " " ";" SEARCH_LIBS ${IT})
+ if(NOT ${_LIBRARIES})
+ check_blas_libraries(
+ ${_LIBRARIES}
+ BLAS
+ ${BLAS_mkl_SEARCH_SYMBOL}
+ ""
+ "${SEARCH_LIBS}"
+ "${CMAKE_THREAD_LIBS_INIT};${BLAS_mkl_LM};${BLAS_mkl_LDL}"
+ "${BLAS_mkl_MKLROOT}"
+ "${BLAS_mkl_LIB_PATH_SUFFIXES}"
+ )
+ endif()
+ endforeach()
+
+ unset(BLAS_mkl_ILP_MODE)
+ unset(BLAS_mkl_INTFACE)
+ unset(BLAS_mkl_THREADING)
+ unset(BLAS_mkl_OMP)
+ unset(BLAS_mkl_DLL_SUFFIX)
+ unset(BLAS_mkl_LM)
+ unset(BLAS_mkl_LDL)
+ unset(BLAS_mkl_MKLROOT)
+ unset(BLAS_mkl_MKLROOT_LAST_DIR)
+ unset(BLAS_mkl_ARCH_NAME)
+ unset(BLAS_mkl_OS_NAME)
+ unset(BLAS_mkl_LIB_PATH_SUFFIXES)
+endif()
+
+
+find_package_handle_standard_args(MKL REQUIRED_VARS MKL_LIBRARIES)
+
+cmake_pop_check_state()
+set(CMAKE_FIND_LIBRARY_SUFFIXES ${_blas_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES})
diff --git a/packages/leann-backend-hnsw/third_party/faiss/cmake/faiss-config.cmake.in b/packages/leann-backend-hnsw/third_party/faiss/cmake/faiss-config.cmake.in
new file mode 100644
index 0000000..43ea9d4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/cmake/faiss-config.cmake.in
@@ -0,0 +1,7 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+
+include("${CMAKE_CURRENT_LIST_DIR}/faiss-targets.cmake")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/cmake/link_to_faiss_lib.cmake b/packages/leann-backend-hnsw/third_party/faiss/cmake/link_to_faiss_lib.cmake
new file mode 100644
index 0000000..e04453d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/cmake/link_to_faiss_lib.cmake
@@ -0,0 +1,66 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+function(link_to_faiss_lib target)
+ if(NOT FAISS_OPT_LEVEL STREQUAL "avx2" AND NOT FAISS_OPT_LEVEL STREQUAL "avx512" AND NOT FAISS_OPT_LEVEL STREQUAL "avx512_spr" AND NOT FAISS_OPT_LEVEL STREQUAL "sve")
+ target_link_libraries(${target} PRIVATE faiss)
+ endif()
+
+ if(FAISS_OPT_LEVEL STREQUAL "avx2")
+ if(NOT WIN32)
+ target_compile_options(${target} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mavx2 -mfma>)
+ else()
+ target_compile_options(${target} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX2>)
+ endif()
+ target_link_libraries(${target} PRIVATE faiss_avx2)
+ endif()
+
+ if(FAISS_OPT_LEVEL STREQUAL "avx512")
+ if(NOT WIN32)
+ target_compile_options(${target} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mavx2 -mfma -mavx512f -mavx512f -mavx512cd -mavx512vl -mavx512dq -mavx512bw>)
+ else()
+ target_compile_options(${target} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
+ endif()
+ target_link_libraries(${target} PRIVATE faiss_avx512)
+ endif()
+
+ if(FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ if(NOT WIN32)
+ # Architecture mode to support AVX512 extensions available since Intel (R) Sapphire Rapids.
+ # Ref: https://networkbuilders.intel.com/solutionslibrary/intel-avx-512-fp16-instruction-set-for-intel-xeon-processor-based-products-technology-guide
+ target_compile_options(${target} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-march=sapphirerapids -mtune=sapphirerapids>)
+ else()
+ target_compile_options(${target} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
+ endif()
+ target_link_libraries(${target} PRIVATE faiss_avx512_spr)
+ endif()
+
+ if(FAISS_OPT_LEVEL STREQUAL "sve")
+ if(NOT WIN32)
+ if("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )-march=native")
+ # Do nothing, expect SVE to be enabled by -march=native
+ elseif("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )(-march=armv[0-9]+(\\.[1-9]+)?-[^+ ](\\+[^+$ ]+)*)")
+ # Add +sve
+ target_compile_options(${target} PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:DEBUG>>:${CMAKE_MATCH_2}+sve>)
+ elseif(NOT "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )-march=armv")
+ # No valid -march, so specify -march=armv8-a+sve as the default
+ target_compile_options(${target} PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:DEBUG>>:-march=armv8-a+sve>)
+ endif()
+ if("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )-march=native")
+ # Do nothing, expect SVE to be enabled by -march=native
+ elseif("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )(-march=armv[0-9]+(\\.[1-9]+)?-[^+ ](\\+[^+$ ]+)*)")
+ # Add +sve
+ target_compile_options(${target} PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:RELEASE>>:${CMAKE_MATCH_2}+sve>)
+ elseif(NOT "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )-march=armv")
+ # No valid -march, so specify -march=armv8-a+sve as the default
+ target_compile_options(${target} PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:RELEASE>>:-march=armv8-a+sve>)
+ endif()
+ else()
+ # TODO: support Windows
+ endif()
+ target_link_libraries(${target} PRIVATE faiss_sve)
+ endif()
+endfunction()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/cmake/thirdparty/fetch_rapids.cmake b/packages/leann-backend-hnsw/third_party/faiss/cmake/thirdparty/fetch_rapids.cmake
new file mode 100644
index 0000000..2ed6a78
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/cmake/thirdparty/fetch_rapids.cmake
@@ -0,0 +1,24 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+# =============================================================================
+# Copyright (c) 2023-2024, NVIDIA CORPORATION.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+# in compliance with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software distributed under the License
+# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+# or implied. See the License for the specific language governing permissions and limitations under
+# the License.
+# =============================================================================
+set(RAPIDS_VERSION "24.12")
+
+if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/FAISS_RAPIDS.cmake)
+ file(DOWNLOAD https://raw.githubusercontent.com/rapidsai/rapids-cmake/branch-${RAPIDS_VERSION}/RAPIDS.cmake
+ ${CMAKE_CURRENT_BINARY_DIR}/FAISS_RAPIDS.cmake)
+endif()
+include(${CMAKE_CURRENT_BINARY_DIR}/FAISS_RAPIDS.cmake)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/conda/conda_build_config.yaml b/packages/leann-backend-hnsw/third_party/faiss/conda/conda_build_config.yaml
new file mode 100644
index 0000000..4df0514
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/conda/conda_build_config.yaml
@@ -0,0 +1,5 @@
+python:
+ - 3.9
+ - 3.10
+ - 3.11
+ - 3.12 # [not aarch64]
diff --git a/packages/leann-backend-hnsw/third_party/faiss/conda/faiss-gpu-cuvs/meta.yaml b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss-gpu-cuvs/meta.yaml
new file mode 100644
index 0000000..76d5350
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss-gpu-cuvs/meta.yaml
@@ -0,0 +1,136 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+{% set version = environ.get('GIT_DESCRIBE_TAG').lstrip('v') %}
+{% set suffix = "_nightly" if environ.get('PACKAGE_TYPE') == 'nightly' else "" %}
+{% set number = GIT_DESCRIBE_NUMBER %}
+{% if cudatoolkit == '11.8.0' %}
+{% set cuda_constraints=">=11.4,<12" %}
+{% set libcublas_constraints=">=11.6,<12" %}
+{% set cudart_constraints="=12.6.77" %}
+{% elif cudatoolkit == '12.4.0' %}
+{% set cuda_constraints=">=12.1,<12.5" %}
+{% set libcublas_constraints=">=12.1,<13" %}
+{% set cudart_constraints=">=12.4,<12.5" %}
+{% endif %}
+
+package:
+ name: faiss-pkg
+ version: {{ version }}
+
+build:
+ number: {{ number }}
+
+about:
+ home: https://github.com/facebookresearch/faiss
+ license: MIT
+ license_family: MIT
+ license_file: LICENSE
+ summary: A library for efficient similarity search and clustering of dense vectors.
+
+source:
+ git_url: ../../
+
+outputs:
+ - name: libfaiss
+ script: build-lib.sh # [x86_64 and not win and not osx]
+ script: build-lib-osx.sh # [x86_64 and osx]
+ script: build-lib-arm64.sh # [not x86_64]
+ script: build-lib.bat # [win]
+ build:
+ string: "h{{ PKG_HASH }}_{{ number }}_cuda{{ cudatoolkit }}_cuvs{{ suffix }}"
+ run_exports:
+ - {{ pin_compatible('libfaiss', exact=True) }}
+ script_env:
+ - CUDA_ARCHS
+ requirements:
+ build:
+ - {{ compiler('cxx') }} =12.4
+ - sysroot_linux-64 =2.17 # [linux64]
+ - llvm-openmp # [osx]
+ - cmake >=3.26.4
+ - make =4.2 # [not win]
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64]
+ - mkl =2023 # [x86_64]
+ - mkl-devel =2023 # [x86_64]
+ - cuda-toolkit {{ cudatoolkit }}
+ - cuda-cudart {{ cudart_constraints }}
+ - cuda-cudart-dev {{ cudart_constraints }}
+ - cuda-cudart-static {{ cudart_constraints }}
+ - cuda-cudart_linux-64 {{ cudart_constraints }} # [linux64]
+ - cuda-cudart-dev_linux-64 {{ cudart_constraints }} # [linux64]
+ - cuda-cudart-static_linux-64 {{ cudart_constraints }} # [linux64]
+ host:
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64]
+ - mkl =2023 # [x86_64]
+ - openblas =0.3.29 # [not x86_64]
+ - libcuvs =24.12
+ - cuda-version {{ cuda_constraints }}
+ run:
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64]
+ - mkl =2023 # [x86_64]
+ - openblas =0.3.29 # [not x86_64]
+ - cuda-cudart {{ cuda_constraints }}
+ - libcublas {{ libcublas_constraints }}
+ - libcuvs =24.12
+ - cuda-version {{ cuda_constraints }}
+ - libnvjitlink
+ test:
+ requires:
+ - conda-build
+ commands:
+ - test -f $PREFIX/lib/libfaiss$SHLIB_EXT # [not win]
+ - test -f $PREFIX/lib/libfaiss_avx2$SHLIB_EXT # [x86_64 and not win]
+ - conda inspect linkages -p $PREFIX $PKG_NAME # [not win]
+ - conda inspect objects -p $PREFIX $PKG_NAME # [osx]
+
+ - name: faiss-gpu-cuvs
+ script: build-pkg.sh # [x86_64 and not win and not osx]
+ script: build-pkg-osx.sh # [x86_64 and osx]
+ script: build-pkg-arm64.sh # [not x86_64]
+ script: build-pkg.bat # [win]
+ build:
+ string: "py{{ PY_VER }}_h{{ PKG_HASH }}_{{ number }}_cuda{{ cudatoolkit }}{{ suffix }}"
+ requirements:
+ build:
+ - {{ compiler('cxx') }} =12.4
+ - sysroot_linux-64 =2.17 # [linux64]
+ - swig =4.0
+ - cmake >=3.26.4
+ - make =4.2 # [not win]
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64]
+ - mkl =2023.0 # [x86_64]
+ - cuda-toolkit {{ cudatoolkit }}
+ host:
+ - mkl =2023.0 # [x86_64]
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64]
+ - python {{ python }}
+ - numpy >=1.19,<2
+ - {{ pin_subpackage('libfaiss', exact=True) }}
+ run:
+ - mkl =2023.0 # [x86_64]
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64]
+ - python {{ python }}
+ - numpy >=1.19,<2
+ - packaging
+ - {{ pin_subpackage('libfaiss', exact=True) }}
+ test:
+ requires:
+ - numpy >=1.19,<2
+ - scipy
+ - pytorch <2.5
+ - pytorch-cuda {{ cuda_constraints }}
+ commands:
+ - python -X faulthandler -m unittest discover -v -s tests/ -p "test_*"
+ - python -X faulthandler -m unittest discover -v -s tests/ -p "torch_*"
+ - cp tests/common_faiss_tests.py faiss/gpu/test
+ - python -X faulthandler -m unittest discover -v -s faiss/gpu/test/ -p "test_*"
+ - python -X faulthandler -m unittest discover -v -s faiss/gpu/test/ -p "torch_*"
+ - sh test_cpu_dispatch.sh # [linux64]
+ files:
+ - test_cpu_dispatch.sh # [linux64]
+ source_files:
+ - tests/
+ - faiss/gpu/test/
diff --git a/packages/leann-backend-hnsw/third_party/faiss/conda/faiss-gpu/meta.yaml b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss-gpu/meta.yaml
new file mode 100644
index 0000000..5d5b52c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss-gpu/meta.yaml
@@ -0,0 +1,122 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+{% set version = environ.get('GIT_DESCRIBE_TAG').lstrip('v') %}
+{% set suffix = "_nightly" if environ.get('PACKAGE_TYPE') == 'nightly' else "" %}
+{% set number = GIT_DESCRIBE_NUMBER %}
+{% if cudatoolkit == '11.4.4' %}
+{% set cuda_constraints=">=11.4,<12" %}
+{% set libcublas_constraints=">=11.6,<12" %}
+{% elif cudatoolkit == '12.1.1' %}
+{% set cuda_constraints=">=12.1,<13" %}
+{% set libcublas_constraints=">=12.1,<13" %}
+{% endif %}
+
+package:
+ name: faiss-pkg
+ version: {{ version }}
+
+build:
+ number: {{ number }}
+
+about:
+ home: https://github.com/facebookresearch/faiss
+ license: MIT
+ license_family: MIT
+ license_file: LICENSE
+ summary: A library for efficient similarity search and clustering of dense vectors.
+
+source:
+ git_url: ../../
+
+outputs:
+ - name: libfaiss
+ script: build-lib.sh # [x86_64 and not win and not osx]
+ script: build-lib-osx.sh # [x86_64 and osx]
+ script: build-lib-arm64.sh # [not x86_64]
+ script: build-lib.bat # [win]
+ build:
+ string: "h{{ PKG_HASH }}_{{ number }}_cuda{{ cudatoolkit }}{{ suffix }}"
+ run_exports:
+ - {{ pin_compatible('libfaiss', exact=True) }}
+ script_env:
+ - CUDA_ARCHS
+ - FAISS_FLATTEN_CONDA_INCLUDES
+ requirements:
+ build:
+ - {{ compiler('cxx') }}
+ - sysroot_linux-64 =2.17 # [linux64]
+ - llvm-openmp # [osx]
+ - cmake >=3.24.0
+ - make =4.2 # [not win and not (osx and arm64)]
+ - make =4.4 # [osx and arm64]
+ - mkl-devel =2023.0 # [x86_64]
+ - cuda-toolkit {{ cudatoolkit }}
+ - gcc_linux-64 =11.2 # [cudatoolkit == '11.4.4']
+ host:
+ - mkl =2023.0 # [x86_64]
+ - openblas =0.3.29 # [not x86_64]
+ run:
+ - mkl =2023.0 # [x86_64]
+ - openblas =0.3.29 # [not x86_64]
+ - cuda-cudart {{ cuda_constraints }}
+ - libcublas {{ libcublas_constraints }}
+ test:
+ requires:
+ - conda-build
+ commands:
+ - test -f $PREFIX/lib/libfaiss$SHLIB_EXT # [not win]
+ - test -f $PREFIX/lib/libfaiss_avx2$SHLIB_EXT # [x86_64 and not win]
+ - conda inspect linkages -p $PREFIX $PKG_NAME # [not win]
+ - conda inspect objects -p $PREFIX $PKG_NAME # [osx]
+
+ - name: faiss-gpu
+ script: build-pkg.sh # [x86_64 and not win and not osx]
+ script: build-pkg-osx.sh # [x86_64 and osx]
+ script: build-pkg-arm64.sh # [not x86_64]
+ script: build-pkg.bat # [win]
+ build:
+ string: "py{{ PY_VER }}_h{{ PKG_HASH }}_{{ number }}_cuda{{ cudatoolkit }}{{ suffix }}"
+ requirements:
+ build:
+ - {{ compiler('cxx') }}
+ - sysroot_linux-64 =2.17 # [linux64]
+ - swig =4.0
+ - cmake >=3.24.0
+ - make =4.2 # [not win and not (osx and arm64)]
+ - make =4.4 # [osx and arm64]
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64 and not win]
+ - cuda-toolkit {{ cudatoolkit }}
+ - mkl-devel =2023.0 # [x86_64]
+ host:
+ - mkl =2023.0 # [x86_64]
+ - python {{ python }}
+ - numpy >=1.19,<2
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64 and not win]
+ - {{ pin_subpackage('libfaiss', exact=True) }}
+ run:
+ - mkl =2023.0 # [x86_64]
+ - python {{ python }}
+ - numpy >=1.19,<2
+ - packaging
+ - {{ pin_subpackage('libfaiss', exact=True) }}
+ test:
+ requires:
+ - numpy >=1.19,<2
+ - scipy
+ - pytorch <2.5
+ - pytorch-cuda {{ cuda_constraints }}
+ commands:
+ - python -X faulthandler -m unittest discover -v -s tests/ -p "test_*"
+ - python -X faulthandler -m unittest discover -v -s tests/ -p "torch_*"
+ - cp tests/common_faiss_tests.py faiss/gpu/test
+ - python -X faulthandler -m unittest discover -v -s faiss/gpu/test/ -p "test_*"
+ - python -X faulthandler -m unittest discover -v -s faiss/gpu/test/ -p "torch_*"
+ - sh test_cpu_dispatch.sh # [linux64]
+ files:
+ - test_cpu_dispatch.sh # [linux64]
+ source_files:
+ - tests/
+ - faiss/gpu/test/
diff --git a/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/build-lib.bat b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/build-lib.bat
new file mode 100644
index 0000000..ff85125
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/build-lib.bat
@@ -0,0 +1,28 @@
+@REM Copyright (c) Meta Platforms, Inc. and affiliates.
+@REM
+@REM This source code is licensed under the MIT license found in the
+@REM LICENSE file in the root directory of this source tree.
+
+:: Copyright (c) Facebook, Inc. and its affiliates.
+::
+:: This source code is licensed under the MIT license found in the
+:: LICENSE file in the root directory of this source tree.
+
+:: Build libfaiss.so.
+cmake -B _build ^
+ -T v141 ^
+ -A x64 ^
+ -G "Visual Studio 16 2019" ^
+ -DBUILD_SHARED_LIBS=ON ^
+ -DBUILD_TESTING=OFF ^
+ -DFAISS_ENABLE_GPU=OFF ^
+ -DFAISS_ENABLE_PYTHON=OFF ^
+ -DBLA_VENDOR=Intel10_64_dyn ^
+ .
+if %errorlevel% neq 0 exit /b %errorlevel%
+
+cmake --build _build --config Release -j %CPU_COUNT%
+if %errorlevel% neq 0 exit /b %errorlevel%
+
+cmake --install _build --config Release --prefix %PREFIX%
+if %errorlevel% neq 0 exit /b %errorlevel%
diff --git a/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/build-pkg.bat b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/build-pkg.bat
new file mode 100644
index 0000000..b331255
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/build-pkg.bat
@@ -0,0 +1,28 @@
+@REM Copyright (c) Meta Platforms, Inc. and affiliates.
+@REM
+@REM This source code is licensed under the MIT license found in the
+@REM LICENSE file in the root directory of this source tree.
+
+:: Copyright (c) Facebook, Inc. and its affiliates.
+::
+:: This source code is licensed under the MIT license found in the
+:: LICENSE file in the root directory of this source tree.
+
+:: Build vanilla version (no avx).
+cmake -B _build_python_%PY_VER% ^
+ -T v141 ^
+ -A x64 ^
+ -G "Visual Studio 16 2019" ^
+ -DFAISS_ENABLE_GPU=OFF ^
+ -DPython_EXECUTABLE=%PYTHON% ^
+ faiss/python
+if %errorlevel% neq 0 exit /b %errorlevel%
+
+cmake --build _build_python_%PY_VER% --config Release -j %CPU_COUNT%
+if %errorlevel% neq 0 exit /b %errorlevel%
+
+
+:: Build actual python module.
+cd _build_python_%PY_VER%/
+%PYTHON% setup.py install --single-version-externally-managed --record=record.txt --prefix=%PREFIX%
+if %errorlevel% neq 0 exit /b %errorlevel%
diff --git a/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/meta.yaml b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/meta.yaml
new file mode 100644
index 0000000..81f2cc6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/conda/faiss/meta.yaml
@@ -0,0 +1,156 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+{% set version = environ.get('GIT_DESCRIBE_TAG').lstrip('v') %}
+{% set suffix = "_nightly" if environ.get('PACKAGE_TYPE') == 'nightly' else "" %}
+{% set number = GIT_DESCRIBE_NUMBER %}
+
+package:
+ name: faiss-pkg
+ version: {{ version }}
+
+build:
+ number: {{ number }}
+
+about:
+ home: https://github.com/facebookresearch/faiss
+ license: MIT
+ license_family: MIT
+ license_file: LICENSE
+ summary: A library for efficient similarity search and clustering of dense vectors.
+
+source:
+ git_url: ../../
+
+outputs:
+ - name: libfaiss
+ script: build-lib.sh # [x86_64 and not win and not osx]
+ script: build-lib-osx.sh # [x86_64 and osx]
+ script: build-lib-arm64.sh # [not x86_64]
+ script: build-lib.bat # [win]
+ build:
+ string: "py{{ PY_VER }}_h{{ PKG_HASH }}_{{ number }}_cpu{{ suffix }}"
+ run_exports:
+ - {{ pin_compatible('libfaiss', exact=True) }}
+ requirements:
+ build:
+ - python {{ python }}
+ - {{ compiler('cxx') }}
+ - sysroot_linux-64 =2.17 # [linux64]
+ - llvm-openmp # [osx or linux64]
+ - cmake >=3.24.0
+ - make =4.2 # [not win and not (osx and arm64)]
+ - make =4.4 # [osx and arm64]
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl-devel =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl-devel >=2023.2.0 # [x86_64 and not win]
+ - mkl-devel =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ host:
+ - python {{ python }}
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl >=2023.2.0 # [x86_64 and not win]
+ - mkl =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ - openblas =0.3.29 # [not x86_64]
+ run:
+ - python {{ python }}
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl >=2023.2.0 # [x86_64 and not win]
+ - mkl =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ - openblas =0.3.29 # [not x86_64]
+ test:
+ requires:
+ - conda-build =25.1.2
+ commands:
+ - test -f $PREFIX/lib/libfaiss$SHLIB_EXT # [not win]
+ - test -f $PREFIX/lib/libfaiss_avx2$SHLIB_EXT # [x86_64 and not win]
+ - conda inspect linkages -p $PREFIX $PKG_NAME # [not win]
+ - conda inspect objects -p $PREFIX $PKG_NAME # [osx]
+
+ - name: faiss-cpu
+ script: build-pkg.sh # [x86_64 and not win and not osx]
+ script: build-pkg-osx.sh # [x86_64 and osx]
+ script: build-pkg-arm64.sh # [not x86_64]
+ script: build-pkg.bat # [win]
+ build:
+ string: "py{{ PY_VER }}_h{{ PKG_HASH }}_{{ number }}_cpu{{ suffix }}"
+ requirements:
+ build:
+ - python {{ python }}
+ - {{ compiler('cxx') }}
+ - sysroot_linux-64 =2.17 # [linux64]
+ - swig =4.0
+ - cmake >=3.24.0
+ - make =4.2 # [not win and not (osx and arm64)]
+ - make =4.4 # [osx and arm64]
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64 and not win]
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl >=2023.2.0 # [x86_64 and not win]
+ - mkl =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ host:
+ - python {{ python }}
+ - numpy >=1.19,<2
+ - {{ pin_subpackage('libfaiss', exact=True) }}
+ - _openmp_mutex =4.5=2_kmp_llvm # [x86_64 and not win]
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl >=2023.2.0 # [x86_64 and not win]
+ - mkl =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ run:
+ - python {{ python }}
+ - numpy >=1.19,<2
+ - packaging
+ - {{ pin_subpackage('libfaiss', exact=True) }}
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl >=2023.2.0 # [x86_64 and not win]
+ - mkl =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ test:
+ requires:
+ - numpy >=1.19,<2
+ - scipy
+ - pytorch <2.5
+ {% if PY_VER == '3.9' or PY_VER == '3.10' or PY_VER == '3.11' %}
+ - mkl =2023.0 # [x86_64]
+ - python_abi <3.12
+ {% elif PY_VER == '3.12' %}
+ - mkl >=2023.2.0 # [x86_64 and not win]
+ - mkl =2023.1.0 # [x86_64 and win]
+ - python_abi =3.12
+ {% endif %}
+ commands:
+ - python -X faulthandler -m unittest discover -v -s tests/ -p "test_*"
+ - python -X faulthandler -m unittest discover -v -s tests/ -p "torch_*"
+ - sh test_cpu_dispatch.sh # [linux64]
+ files:
+ - test_cpu_dispatch.sh # [linux64]
+ source_files:
+ - tests/
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/README.md b/packages/leann-backend-hnsw/third_party/faiss/contrib/README.md
new file mode 100644
index 0000000..f2b7d0f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/README.md
@@ -0,0 +1,76 @@
+
+# The contrib modules
+
+The contrib directory contains helper modules for Faiss for various tasks.
+
+## Code structure
+
+The contrib directory gets compiled in the module faiss.contrib.
+Note that although some of the modules may depend on additional modules (eg. GPU Faiss, pytorch, hdf5), they are not necessarily compiled in to avoid adding dependencies. It is the user's responsibility to provide them.
+
+In contrib, we are progressively dropping python2 support.
+
+## List of contrib modules
+
+### rpc.py
+
+A very simple Remote Procedure Call library, where function parameters and results are pickled, for use with client_server.py
+
+### client_server.py
+
+The server handles requests to a Faiss index. The client calls the remote index.
+This is mainly to shard datasets over several machines, see [Distributed index](https://github.com/facebookresearch/faiss/wiki/Indexes-that-do-not-fit-in-RAM#distributed-index)
+
+### ondisk.py
+
+Encloses the main logic to merge indexes into an on-disk index.
+See [On-disk storage](https://github.com/facebookresearch/faiss/wiki/Indexes-that-do-not-fit-in-RAM#on-disk-storage)
+
+### exhaustive_search.py
+
+Computes the ground-truth search results for a dataset that possibly does not fit in RAM. Uses GPU if available.
+Tested in `tests/test_contrib.TestComputeGT`
+
+### torch_utils.py
+
+Interoperability functions for pytorch and Faiss: Importing this will allow pytorch Tensors (CPU or GPU) to be used as arguments to Faiss indexes and other functions. Torch GPU tensors can only be used with Faiss GPU indexes. If this is imported with a package that supports Faiss GPU, the necessary stream synchronization with the current pytorch stream will be automatically performed.
+
+Numpy ndarrays can continue to be used in the Faiss python interface after importing this file. All arguments must be uniformly either numpy ndarrays or Torch tensors; no mixing is allowed.
+
+Tested in `tests/test_contrib_torch.py` (CPU) and `gpu/test/test_contrib_torch_gpu.py` (GPU).
+
+### inspect_tools.py
+
+Functions to inspect C++ objects wrapped by SWIG. Most often this just means reading
+fields and converting them to the proper python array.
+
+### ivf_tools.py
+
+A few functions to override the coarse quantizer in IVF, providing additional flexibility for assignment.
+
+### datasets.py
+
+(may require h5py)
+
+Definition of how to access data for some standard datasets.
+
+### factory_tools.py
+
+Functions related to factory strings.
+
+### evaluation.py
+
+A few non-trivial evaluation functions for search results
+
+### clustering.py
+
+Contains:
+
+- a Python implementation of kmeans, that can be used for special datatypes (eg. sparse matrices).
+
+- a 2-level clustering routine and a function that can apply it to train an IndexIVF
+
+### big_batch_search.py
+
+Search IVF indexes with one centroid after another. Useful for large
+databases that do not fit in RAM *and* a large number of queries.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/__init__.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/big_batch_search.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/big_batch_search.py
new file mode 100644
index 0000000..f82fbd5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/big_batch_search.py
@@ -0,0 +1,515 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import time
+import pickle
+import os
+import logging
+from multiprocessing.pool import ThreadPool
+import threading
+import _thread
+from queue import Queue
+import traceback
+import datetime
+
+import numpy as np
+import faiss
+
+from faiss.contrib.inspect_tools import get_invlist
+
+
+class BigBatchSearcher:
+ """
+ Object that manages all the data related to the computation
+ except the actual within-bucket matching and the organization of the
+ computation (parallel or not)
+ """
+
+ def __init__(
+ self,
+ index, xq, k,
+ verbose=0,
+ use_float16=False):
+
+ # verbosity
+ self.verbose = verbose
+ self.tictoc = []
+
+ self.xq = xq
+ self.index = index
+ self.use_float16 = use_float16
+ keep_max = faiss.is_similarity_metric(index.metric_type)
+ self.rh = faiss.ResultHeap(len(xq), k, keep_max=keep_max)
+ self.t_accu = [0] * 6
+ self.t_display = self.t0 = time.time()
+
+ def start_t_accu(self):
+ self.t_accu_t0 = time.time()
+
+ def stop_t_accu(self, n):
+ self.t_accu[n] += time.time() - self.t_accu_t0
+
+ def tic(self, name):
+ self.tictoc = (name, time.time())
+ if self.verbose > 0:
+ print(name, end="\r", flush=True)
+
+ def toc(self):
+ name, t0 = self.tictoc
+ dt = time.time() - t0
+ if self.verbose > 0:
+ print(f"{name}: {dt:.3f} s")
+ return dt
+
+ def report(self, l):
+ if self.verbose == 1 or (
+ self.verbose == 2 and (
+ l > 1000 and time.time() < self.t_display + 1.0
+ )
+ ):
+ return
+ t = time.time() - self.t0
+ print(
+ f"[{t:.1f} s] list {l}/{self.index.nlist} "
+ f"times prep q {self.t_accu[0]:.3f} prep b {self.t_accu[1]:.3f} "
+ f"comp {self.t_accu[2]:.3f} res {self.t_accu[3]:.3f} "
+ f"wait in {self.t_accu[4]:.3f} "
+ f"wait out {self.t_accu[5]:.3f} "
+ f"eta {datetime.timedelta(seconds=t*self.index.nlist/(l+1)-t)} "
+ f"mem {faiss.get_mem_usage_kb()}",
+ end="\r" if self.verbose <= 2 else "\n",
+ flush=True,
+ )
+ self.t_display = time.time()
+
+ def coarse_quantization(self):
+ self.tic("coarse quantization")
+ bs = 65536
+ nq = len(self.xq)
+ q_assign = np.empty((nq, self.index.nprobe), dtype='int32')
+ for i0 in range(0, nq, bs):
+ i1 = min(nq, i0 + bs)
+ q_dis_i, q_assign_i = self.index.quantizer.search(
+ self.xq[i0:i1], self.index.nprobe)
+ # q_dis[i0:i1] = q_dis_i
+ q_assign[i0:i1] = q_assign_i
+ self.toc()
+ self.q_assign = q_assign
+
+ def reorder_assign(self):
+ self.tic("bucket sort")
+ q_assign = self.q_assign
+ q_assign += 1 # move -1 -> 0
+ self.bucket_lims = faiss.matrix_bucket_sort_inplace(
+ self.q_assign, nbucket=self.index.nlist + 1, nt=16)
+ self.query_ids = self.q_assign.ravel()
+ if self.verbose > 0:
+ print(' number of -1s:', self.bucket_lims[1])
+ self.bucket_lims = self.bucket_lims[1:] # shift back to ignore -1s
+ del self.q_assign # inplace so let's forget about the old version...
+ self.toc()
+
+ def prepare_bucket(self, l):
+ """ prepare the queries and database items for bucket l"""
+ t0 = time.time()
+ index = self.index
+ # prepare queries
+ i0, i1 = self.bucket_lims[l], self.bucket_lims[l + 1]
+ q_subset = self.query_ids[i0:i1]
+ xq_l = self.xq[q_subset]
+ if self.by_residual:
+ xq_l = xq_l - index.quantizer.reconstruct(l)
+ t1 = time.time()
+ # prepare database side
+ list_ids, xb_l = get_invlist(index.invlists, l)
+
+ if self.decode_func is None:
+ xb_l = xb_l.ravel()
+ else:
+ xb_l = self.decode_func(xb_l)
+
+ if self.use_float16:
+ xb_l = xb_l.astype('float16')
+ xq_l = xq_l.astype('float16')
+
+ t2 = time.time()
+ self.t_accu[0] += t1 - t0
+ self.t_accu[1] += t2 - t1
+ return q_subset, xq_l, list_ids, xb_l
+
+ def add_results_to_heap(self, q_subset, D, list_ids, I):
+ """add the bucket results to the heap structure"""
+ if D is None:
+ return
+ t0 = time.time()
+ if I is None:
+ I = list_ids
+ else:
+ I = list_ids[I]
+ self.rh.add_result_subset(q_subset, D, I)
+ self.t_accu[3] += time.time() - t0
+
+ def sizes_in_checkpoint(self):
+ return (self.xq.shape, self.index.nprobe, self.index.nlist)
+
+ def write_checkpoint(self, fname, completed):
+ # write to temp file then move to final file
+ tmpname = fname + ".tmp"
+ with open(tmpname, "wb") as f:
+ pickle.dump(
+ {
+ "sizes": self.sizes_in_checkpoint(),
+ "completed": completed,
+ "rh": (self.rh.D, self.rh.I),
+ }, f, -1)
+ os.replace(tmpname, fname)
+
+ def read_checkpoint(self, fname):
+ with open(fname, "rb") as f:
+ ckp = pickle.load(f)
+ assert ckp["sizes"] == self.sizes_in_checkpoint()
+ self.rh.D[:] = ckp["rh"][0]
+ self.rh.I[:] = ckp["rh"][1]
+ return ckp["completed"]
+
+
+class BlockComputer:
+ """ computation within one bucket """
+
+ def __init__(
+ self,
+ index,
+ method="knn_function",
+ pairwise_distances=faiss.pairwise_distances,
+ knn=faiss.knn):
+
+ self.index = index
+ if index.__class__ == faiss.IndexIVFFlat:
+ index_help = faiss.IndexFlat(index.d, index.metric_type)
+ decode_func = lambda x: x.view("float32")
+ by_residual = False
+ elif index.__class__ == faiss.IndexIVFPQ:
+ index_help = faiss.IndexPQ(
+ index.d, index.pq.M, index.pq.nbits, index.metric_type)
+ index_help.pq = index.pq
+ decode_func = index_help.pq.decode
+ index_help.is_trained = True
+ by_residual = index.by_residual
+ elif index.__class__ == faiss.IndexIVFScalarQuantizer:
+ index_help = faiss.IndexScalarQuantizer(
+ index.d, index.sq.qtype, index.metric_type)
+ index_help.sq = index.sq
+ decode_func = index_help.sq.decode
+ index_help.is_trained = True
+ by_residual = index.by_residual
+ else:
+ raise RuntimeError(f"index type {index.__class__} not supported")
+ self.index_help = index_help
+ self.decode_func = None if method == "index" else decode_func
+ self.by_residual = by_residual
+ self.method = method
+ self.pairwise_distances = pairwise_distances
+ self.knn = knn
+
+ def block_search(self, xq_l, xb_l, list_ids, k, **extra_args):
+ metric_type = self.index.metric_type
+ if xq_l.size == 0 or xb_l.size == 0:
+ D = I = None
+ elif self.method == "index":
+ faiss.copy_array_to_vector(xb_l, self.index_help.codes)
+ self.index_help.ntotal = len(list_ids)
+ D, I = self.index_help.search(xq_l, k)
+ elif self.method == "pairwise_distances":
+ # TODO implement blockwise to avoid mem blowup
+ D = self.pairwise_distances(xq_l, xb_l, metric=metric_type)
+ I = None
+ elif self.method == "knn_function":
+ D, I = self.knn(xq_l, xb_l, k, metric=metric_type, **extra_args)
+
+ return D, I
+
+
+def big_batch_search(
+ index, xq, k,
+ method="knn_function",
+ pairwise_distances=faiss.pairwise_distances,
+ knn=faiss.knn,
+ verbose=0,
+ threaded=0,
+ use_float16=False,
+ prefetch_threads=1,
+ computation_threads=1,
+ q_assign=None,
+ checkpoint=None,
+ checkpoint_freq=7200,
+ start_list=0,
+ end_list=None,
+ crash_at=-1
+ ):
+ """
+ Search queries xq in the IVF index, with a search function that collects
+ batches of query vectors per inverted list. This can be faster than the
+ regular search indexes.
+ Supports IVFFlat, IVFPQ and IVFScalarQuantizer.
+
+ Supports three computation methods:
+ method = "index":
+ build a flat index and populate it separately for each index
+ method = "pairwise_distances":
+ decompress codes and compute all pairwise distances for the queries
+ and index and add result to heap
+ method = "knn_function":
+ decompress codes and compute knn results for the queries
+
+ threaded=0: sequential execution
+ threaded=1: prefetch next bucket while computing the current one
+ threaded=2: prefetch prefetch_threads buckets at a time.
+
+ compute_threads>1: the knn function will get an additional thread_no that
+ tells which worker should handle this.
+
+ In threaded mode, the computation is tiled with the bucket perparation and
+ the writeback of results (useful to maximize GPU utilization).
+
+ use_float16: convert all matrices to float16 (faster for GPU gemm)
+
+ q_assign: override coarse assignment, should be a matrix of size nq * nprobe
+
+ checkpointing (only for threaded > 1):
+ checkpoint: file where the checkpoints are stored
+ checkpoint_freq: when to perform checkpoinging. Should be a multiple of threaded
+
+ start_list, end_list: process only a subset of invlists
+ """
+ nprobe = index.nprobe
+
+ assert method in ("index", "pairwise_distances", "knn_function")
+
+ mem_queries = xq.nbytes
+ mem_assign = len(xq) * nprobe * np.dtype('int32').itemsize
+ mem_res = len(xq) * k * (
+ np.dtype('int64').itemsize
+ + np.dtype('float32').itemsize
+ )
+ mem_tot = mem_queries + mem_assign + mem_res
+ if verbose > 0:
+ logging.info(
+ f"memory: queries {mem_queries} assign {mem_assign} "
+ f"result {mem_res} total {mem_tot} = {mem_tot / (1<<30):.3f} GiB"
+ )
+
+ bbs = BigBatchSearcher(
+ index, xq, k,
+ verbose=verbose,
+ use_float16=use_float16
+ )
+
+ comp = BlockComputer(
+ index,
+ method=method,
+ pairwise_distances=pairwise_distances,
+ knn=knn
+ )
+
+ bbs.decode_func = comp.decode_func
+
+ bbs.by_residual = comp.by_residual
+ if q_assign is None:
+ bbs.coarse_quantization()
+ else:
+ bbs.q_assign = q_assign
+ bbs.reorder_assign()
+
+ if end_list is None:
+ end_list = index.nlist
+
+ completed = set()
+ if checkpoint is not None:
+ assert (start_list, end_list) == (0, index.nlist)
+ if os.path.exists(checkpoint):
+ logging.info(f"recovering checkpoint: {checkpoint}")
+ completed = bbs.read_checkpoint(checkpoint)
+ logging.info(f" already completed: {len(completed)}")
+ else:
+ logging.info("no checkpoint: starting from scratch")
+
+ if threaded == 0:
+ # simple sequential version
+
+ for l in range(start_list, end_list):
+ bbs.report(l)
+ q_subset, xq_l, list_ids, xb_l = bbs.prepare_bucket(l)
+ t0i = time.time()
+ D, I = comp.block_search(xq_l, xb_l, list_ids, k)
+ bbs.t_accu[2] += time.time() - t0i
+ bbs.add_results_to_heap(q_subset, D, list_ids, I)
+
+ elif threaded == 1:
+
+ # parallel version with granularity 1
+
+ def add_results_and_prefetch(to_add, l):
+ """ perform the addition for the previous bucket and
+ prefetch the next (if applicable) """
+ if to_add is not None:
+ bbs.add_results_to_heap(*to_add)
+ if l < index.nlist:
+ return bbs.prepare_bucket(l)
+
+ prefetched_bucket = bbs.prepare_bucket(start_list)
+ to_add = None
+ pool = ThreadPool(1)
+
+ for l in range(start_list, end_list):
+ bbs.report(l)
+ prefetched_bucket_a = pool.apply_async(
+ add_results_and_prefetch, (to_add, l + 1))
+ q_subset, xq_l, list_ids, xb_l = prefetched_bucket
+ bbs.start_t_accu()
+ D, I = comp.block_search(xq_l, xb_l, list_ids, k)
+ bbs.stop_t_accu(2)
+ to_add = q_subset, D, list_ids, I
+ bbs.start_t_accu()
+ prefetched_bucket = prefetched_bucket_a.get()
+ bbs.stop_t_accu(4)
+
+ bbs.add_results_to_heap(*to_add)
+ pool.close()
+ else:
+
+ def task_manager_thread(
+ task,
+ pool_size,
+ start_task,
+ end_task,
+ completed,
+ output_queue,
+ input_queue,
+ ):
+ try:
+ with ThreadPool(pool_size) as pool:
+ res = [pool.apply_async(
+ task,
+ args=(i, output_queue, input_queue))
+ for i in range(start_task, end_task)
+ if i not in completed]
+ for r in res:
+ r.get()
+ pool.close()
+ pool.join()
+ output_queue.put(None)
+ except:
+ traceback.print_exc()
+ _thread.interrupt_main()
+ raise
+
+ def task_manager(*args):
+ task_manager = threading.Thread(
+ target=task_manager_thread,
+ args=args,
+ )
+ task_manager.daemon = True
+ task_manager.start()
+ return task_manager
+
+ def prepare_task(task_id, output_queue, input_queue=None):
+ try:
+ logging.info(f"Prepare start: {task_id}")
+ q_subset, xq_l, list_ids, xb_l = bbs.prepare_bucket(task_id)
+ output_queue.put((task_id, q_subset, xq_l, list_ids, xb_l))
+ logging.info(f"Prepare end: {task_id}")
+ except:
+ traceback.print_exc()
+ _thread.interrupt_main()
+ raise
+
+ def compute_task(task_id, output_queue, input_queue):
+ try:
+ logging.info(f"Compute start: {task_id}")
+ t_wait_out = 0
+ while True:
+ t0 = time.time()
+ logging.info(f'Compute input: task {task_id}')
+ input_value = input_queue.get()
+ t_wait_in = time.time() - t0
+ if input_value is None:
+ # signal for other compute tasks
+ input_queue.put(None)
+ break
+ centroid, q_subset, xq_l, list_ids, xb_l = input_value
+ logging.info(f'Compute work: task {task_id}, centroid {centroid}')
+ t0 = time.time()
+ if computation_threads > 1:
+ D, I = comp.block_search(
+ xq_l, xb_l, list_ids, k, thread_id=task_id
+ )
+ else:
+ D, I = comp.block_search(xq_l, xb_l, list_ids, k)
+ t_compute = time.time() - t0
+ logging.info(f'Compute output: task {task_id}, centroid {centroid}')
+ t0 = time.time()
+ output_queue.put(
+ (centroid, t_wait_in, t_wait_out, t_compute, q_subset, D, list_ids, I)
+ )
+ t_wait_out = time.time() - t0
+ logging.info(f"Compute end: {task_id}")
+ except:
+ traceback.print_exc()
+ _thread.interrupt_main()
+ raise
+
+ prepare_to_compute_queue = Queue(2)
+ compute_to_main_queue = Queue(2)
+ compute_task_manager = task_manager(
+ compute_task,
+ computation_threads,
+ 0,
+ computation_threads,
+ set(),
+ compute_to_main_queue,
+ prepare_to_compute_queue,
+ )
+ prepare_task_manager = task_manager(
+ prepare_task,
+ prefetch_threads,
+ start_list,
+ end_list,
+ completed,
+ prepare_to_compute_queue,
+ None,
+ )
+
+ t_checkpoint = time.time()
+ while True:
+ logging.info("Waiting for result")
+ value = compute_to_main_queue.get()
+ if not value:
+ break
+ centroid, t_wait_in, t_wait_out, t_compute, q_subset, D, list_ids, I = value
+ # to test checkpointing
+ if centroid == crash_at:
+ 1 / 0
+ bbs.t_accu[2] += t_compute
+ bbs.t_accu[4] += t_wait_in
+ bbs.t_accu[5] += t_wait_out
+ logging.info(f"Adding to heap start: centroid {centroid}")
+ bbs.add_results_to_heap(q_subset, D, list_ids, I)
+ logging.info(f"Adding to heap end: centroid {centroid}")
+ completed.add(centroid)
+ bbs.report(centroid)
+ if checkpoint is not None:
+ if time.time() - t_checkpoint > checkpoint_freq:
+ logging.info("writing checkpoint")
+ bbs.write_checkpoint(checkpoint, completed)
+ t_checkpoint = time.time()
+
+ prepare_task_manager.join()
+ compute_task_manager.join()
+
+ bbs.tic("finalize heap")
+ bbs.rh.finalize()
+ bbs.toc()
+
+ return bbs.rh.D, bbs.rh.I
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/client_server.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/client_server.py
new file mode 100755
index 0000000..4c3d349
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/client_server.py
@@ -0,0 +1,91 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from multiprocessing.pool import ThreadPool
+import faiss
+from typing import List, Tuple
+
+from . import rpc
+
+############################################################
+# Server implementation
+############################################################
+
+
+class SearchServer(rpc.Server):
+ """ Assign version that can be exposed via RPC """
+
+ def __init__(self, s: int, index: faiss.Index):
+ rpc.Server.__init__(self, s)
+ self.index = index
+ self.index_ivf = faiss.extract_index_ivf(index)
+
+ def set_nprobe(self, nprobe: int) -> int:
+ """ set nprobe field """
+ self.index_ivf.nprobe = nprobe
+
+ def get_ntotal(self) -> int:
+ return self.index.ntotal
+
+ def __getattr__(self, f):
+ # all other functions get forwarded to the index
+ return getattr(self.index, f)
+
+
+def run_index_server(index: faiss.Index, port: int, v6: bool = False):
+ """ serve requests for that index forerver """
+ rpc.run_server(
+ lambda s: SearchServer(s, index),
+ port, v6=v6)
+
+
+############################################################
+# Client implementation
+############################################################
+
+class ClientIndex:
+ """manages a set of distance sub-indexes. The sub_indexes search a
+ subset of the inverted lists. Searches are merged afterwards
+ """
+
+ def __init__(self, machine_ports: List[Tuple[str, int]], v6: bool = False):
+ """ connect to a series of (host, port) pairs """
+ self.sub_indexes = []
+ for machine, port in machine_ports:
+ self.sub_indexes.append(rpc.Client(machine, port, v6))
+
+ self.ni = len(self.sub_indexes)
+ # pool of threads. Each thread manages one sub-index.
+ self.pool = ThreadPool(self.ni)
+ # test connection...
+ self.ntotal = self.get_ntotal()
+ self.verbose = False
+
+ def set_nprobe(self, nprobe: int) -> None:
+ self.pool.map(
+ lambda idx: idx.set_nprobe(nprobe),
+ self.sub_indexes
+ )
+
+ def set_omp_num_threads(self, nt: int) -> None:
+ self.pool.map(
+ lambda idx: idx.set_omp_num_threads(nt),
+ self.sub_indexes
+ )
+
+ def get_ntotal(self) -> None:
+ return sum(self.pool.map(
+ lambda idx: idx.get_ntotal(),
+ self.sub_indexes
+ ))
+
+ def search(self, x, k: int):
+
+ rh = faiss.ResultHeap(x.shape[0], k)
+
+ for Di, Ii in self.pool.imap(lambda idx: idx.search(x, k), self.sub_indexes):
+ rh.add_result(Di, Ii)
+ rh.finalize()
+ return rh.D, rh.I
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/clustering.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/clustering.py
new file mode 100644
index 0000000..c2a7c77
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/clustering.py
@@ -0,0 +1,428 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This contrib module contains a few routines useful to do clustering variants.
+"""
+
+import numpy as np
+import faiss
+import time
+from multiprocessing.pool import ThreadPool
+
+
+try:
+ import scipy.sparse
+except ImportError:
+ print("scipy not accessible, Python k-means will not work")
+
+def print_nop(*arg, **kwargs):
+ pass
+
+def two_level_clustering(xt, nc1, nc2, rebalance=True, clustering_niter=25, **args):
+ """
+ perform 2-level clustering on a training set xt
+ nc1 and nc2 are the number of clusters at each level, the final number of
+ clusters is nc2. Additional arguments are passed to the Kmeans object.
+
+ Rebalance allocates the number of sub-clusters depending on the number of
+ first-level assignment.
+ """
+ d = xt.shape[1]
+
+ verbose = args.get("verbose", False)
+
+ log = print if verbose else print_nop
+
+ log(f"2-level clustering of {xt.shape} nb 1st level clusters = {nc1} total {nc2}")
+ log("perform coarse training")
+
+ km = faiss.Kmeans(
+ d, nc1, niter=clustering_niter,
+ max_points_per_centroid=2000,
+ **args
+ )
+ km.train(xt)
+
+ iteration_stats = [km.iteration_stats]
+ log()
+
+ # coarse centroids
+ centroids1 = km.centroids
+
+ log("assigning the training set")
+ t0 = time.time()
+ _, assign1 = km.assign(xt)
+ bc = np.bincount(assign1, minlength=nc1)
+ log(f"done in {time.time() - t0:.2f} s. Sizes of clusters {min(bc)}-{max(bc)}")
+ o = assign1.argsort()
+ del km
+
+ if not rebalance:
+ # make sure the sub-clusters sum up to exactly nc2
+ cc = np.arange(nc1 + 1) * nc2 // nc1
+ all_nc2 = cc[1:] - cc[:-1]
+ else:
+ bc_sum = np.cumsum(bc)
+ all_nc2 = bc_sum * nc2 // bc_sum[-1]
+ all_nc2[1:] -= all_nc2[:-1]
+ assert sum(all_nc2) == nc2
+ log(f"nb 2nd-level centroids {min(all_nc2)}-{max(all_nc2)}")
+
+ # train sub-clusters
+ i0 = 0
+ c2 = []
+ t0 = time.time()
+ for c1 in range(nc1):
+ nc2 = int(all_nc2[c1])
+ log(f"[{time.time() - t0:.2f} s] training sub-cluster {c1}/{nc1} nc2={nc2}\r", end="", flush=True)
+ i1 = i0 + bc[c1]
+ subset = o[i0:i1]
+ assert np.all(assign1[subset] == c1)
+ km = faiss.Kmeans(d, nc2, **args)
+ xtsub = xt[subset]
+ km.train(xtsub)
+ iteration_stats.append(km.iteration_stats)
+ c2.append(km.centroids)
+ del km
+ i0 = i1
+ log(f"done in {time.time() - t0:.2f} s")
+ return np.vstack(c2), iteration_stats
+
+
+def train_ivf_index_with_2level(index, xt, **args):
+ """
+ Applies 2-level clustering to an index_ivf embedded in an index.
+ """
+ # handle PreTransforms
+ index = faiss.downcast_index(index)
+ if isinstance(index, faiss.IndexPreTransform):
+ for i in range(index.chain.size()):
+ vt = index.chain.at(i)
+ vt.train(xt)
+ xt = vt.apply(xt)
+ train_ivf_index_with_2level(index.index, xt, **args)
+ index.is_trained = True
+ return
+ assert isinstance(index, faiss.IndexIVF)
+ assert index.metric_type == faiss.METRIC_L2
+ # now do 2-level clustering
+ nc1 = int(np.sqrt(index.nlist))
+ print("REBALANCE=", args)
+
+ centroids, _ = two_level_clustering(xt, nc1, index.nlist, **args)
+ index.quantizer.train(centroids)
+ index.quantizer.add(centroids)
+ # finish training
+ index.train(xt)
+
+
+###############################################################################
+# K-means implementation in Python
+#
+# It relies on DatasetAssign, an abstraction of the training vectors that offers
+# the minimal set of operations to perform k-means clustering.
+###############################################################################
+
+
+class DatasetAssign:
+ """Wrapper for a matrix that offers a function to assign the vectors
+ to centroids. All other implementations offer the same interface"""
+
+ def __init__(self, x):
+ self.x = np.ascontiguousarray(x, dtype='float32')
+
+ def count(self):
+ return self.x.shape[0]
+
+ def dim(self):
+ return self.x.shape[1]
+
+ def get_subset(self, indices):
+ return self.x[indices]
+
+ def perform_search(self, centroids):
+ return faiss.knn(self.x, centroids, 1)
+
+ def assign_to(self, centroids, weights=None):
+ D, I = self.perform_search(centroids)
+
+ I = I.ravel()
+ D = D.ravel()
+ nc, d = centroids.shape
+ sum_per_centroid = np.zeros((nc, d), dtype='float32')
+ if weights is None:
+ np.add.at(sum_per_centroid, I, self.x)
+ else:
+ np.add.at(sum_per_centroid, I, weights[:, np.newaxis] * self.x)
+
+ return I, D, sum_per_centroid
+
+
+class DatasetAssignGPU(DatasetAssign):
+ """ GPU version of the previous """
+
+ def __init__(self, x, gpu_id, verbose=False):
+ DatasetAssign.__init__(self, x)
+ index = faiss.IndexFlatL2(x.shape[1])
+ if gpu_id >= 0:
+ self.index = faiss.index_cpu_to_gpu(
+ faiss.StandardGpuResources(),
+ gpu_id, index)
+ else:
+ # -1 -> assign to all GPUs
+ self.index = faiss.index_cpu_to_all_gpus(index)
+
+ def perform_search(self, centroids):
+ self.index.reset()
+ self.index.add(centroids)
+ return self.index.search(self.x, 1)
+
+
+def sparse_assign_to_dense(xq, xb, xq_norms=None, xb_norms=None):
+ """ assignment function for xq is sparse, xb is dense
+ uses a matrix multiplication. The squared norms can be provided if
+ available.
+ """
+ nq = xq.shape[0]
+ nb = xb.shape[0]
+ if xb_norms is None:
+ xb_norms = (xb ** 2).sum(1)
+ if xq_norms is None:
+ xq_norms = np.array(xq.power(2).sum(1))
+ d2 = xb_norms - 2 * xq @ xb.T
+ I = d2.argmin(axis=1)
+ D = d2.ravel()[I + np.arange(nq) * nb] + xq_norms.ravel()
+ return D, I
+
+
+def sparse_assign_to_dense_blocks(
+ xq, xb, xq_norms=None, xb_norms=None, qbs=16384, bbs=16384, nt=None):
+ """
+ decomposes the sparse_assign_to_dense function into blocks to avoid a
+ possible memory blow up. Can be run in multithreaded mode, because scipy's
+ sparse-dense matrix multiplication is single-threaded.
+ """
+ nq = xq.shape[0]
+ nb = xb.shape[0]
+ D = np.empty(nq, dtype="float32")
+ D.fill(np.inf)
+ I = -np.ones(nq, dtype=int)
+
+ if xb_norms is None:
+ xb_norms = (xb ** 2).sum(1)
+
+ def handle_query_block(i):
+ xq_block = xq[i : i + qbs]
+ Iblock = I[i : i + qbs]
+ Dblock = D[i : i + qbs]
+ if xq_norms is None:
+ xq_norms_block = np.array(xq_block.power(2).sum(1))
+ else:
+ xq_norms_block = xq_norms[i : i + qbs]
+ for j in range(0, nb, bbs):
+ Di, Ii = sparse_assign_to_dense(
+ xq_block,
+ xb[j : j + bbs],
+ xq_norms=xq_norms_block,
+ xb_norms=xb_norms[j : j + bbs],
+ )
+ if j == 0:
+ Iblock[:] = Ii
+ Dblock[:] = Di
+ else:
+ mask = Di < Dblock
+ Iblock[mask] = Ii[mask] + j
+ Dblock[mask] = Di[mask]
+
+ if nt == 0 or nt == 1 or nq <= qbs:
+ list(map(handle_query_block, range(0, nq, qbs)))
+ else:
+ pool = ThreadPool(nt)
+ pool.map(handle_query_block, range(0, nq, qbs))
+
+ return D, I
+
+
+class DatasetAssignSparse(DatasetAssign):
+ """Wrapper for a matrix that offers a function to assign the vectors
+ to centroids. All other implementations offer the same interface"""
+
+ def __init__(self, x):
+ assert x.__class__ == scipy.sparse.csr_matrix
+ self.x = x
+ self.squared_norms = np.array(x.power(2).sum(1))
+
+ def get_subset(self, indices):
+ return np.array(self.x[indices].todense())
+
+ def perform_search(self, centroids):
+ return sparse_assign_to_dense_blocks(
+ self.x, centroids, xq_norms=self.squared_norms)
+
+ def assign_to(self, centroids, weights=None):
+ D, I = self.perform_search(centroids)
+
+ I = I.ravel()
+ D = D.ravel()
+ n = self.x.shape[0]
+ if weights is None:
+ weights = np.ones(n, dtype='float32')
+ nc = len(centroids)
+
+ m = scipy.sparse.csc_matrix(
+ (weights, I, np.arange(n + 1)),
+ shape=(nc, n))
+ sum_per_centroid = np.array((m * self.x).todense())
+
+ return I, D, sum_per_centroid
+
+
+def imbalance_factor(k, assign):
+ assign = np.ascontiguousarray(assign, dtype='int64')
+ return faiss.imbalance_factor(len(assign), k, faiss.swig_ptr(assign))
+
+
+def check_if_torch(x):
+ if x.__class__ == np.ndarray:
+ return False
+ import torch
+ if isinstance(x, torch.Tensor):
+ return True
+ raise NotImplementedError(f"Unknown tensor type {type(x)}")
+
+
+def reassign_centroids(hassign, centroids, rs=None):
+ """ reassign centroids when some of them collapse """
+ if rs is None:
+ rs = np.random
+ k, d = centroids.shape
+ nsplit = 0
+ is_torch = check_if_torch(centroids)
+
+ empty_cents = np.where(hassign == 0)[0]
+
+ if len(empty_cents) == 0:
+ return 0
+
+ if is_torch:
+ import torch
+ fac = torch.ones_like(centroids[0])
+ else:
+ fac = np.ones_like(centroids[0])
+ fac[::2] += 1 / 1024.
+ fac[1::2] -= 1 / 1024.
+
+ # this is a single pass unless there are more than k/2
+ # empty centroids
+ while len(empty_cents) > 0:
+ # choose which centroids to split (numpy)
+ probas = hassign.astype('float') - 1
+ probas[probas < 0] = 0
+ probas /= probas.sum()
+ nnz = (probas > 0).sum()
+
+ nreplace = min(nnz, empty_cents.size)
+ cjs = rs.choice(k, size=nreplace, p=probas)
+
+ for ci, cj in zip(empty_cents[:nreplace], cjs):
+
+ c = centroids[cj]
+ centroids[ci] = c * fac
+ centroids[cj] = c / fac
+
+ hassign[ci] = hassign[cj] // 2
+ hassign[cj] -= hassign[ci]
+ nsplit += 1
+
+ empty_cents = empty_cents[nreplace:]
+
+ return nsplit
+
+
+
+def kmeans(k, data, niter=25, seed=1234, checkpoint=None, verbose=True,
+ return_stats=False):
+ """Pure python kmeans implementation. Follows the Faiss C++ version
+ quite closely, but takes a DatasetAssign instead of a training data
+ matrix. Also redo is not implemented.
+
+ For the torch implementation, the centroids are tensors (possibly on GPU),
+ but the indices remain numpy on CPU.
+ """
+ n, d = data.count(), data.dim()
+ log = print if verbose else print_nop
+
+ log(("Clustering %d points in %dD to %d clusters, " +
+ "%d iterations seed %d") % (n, d, k, niter, seed))
+
+ rs = np.random.RandomState(seed)
+ print("preproc...")
+ t0 = time.time()
+ # initialization
+ perm = rs.choice(n, size=k, replace=False)
+ centroids = data.get_subset(perm)
+ is_torch = check_if_torch(centroids)
+
+ iteration_stats = []
+
+ log(" done")
+ t_search_tot = 0
+ obj = []
+ for i in range(niter):
+ t0s = time.time()
+
+ log('assigning', end='\r', flush=True)
+ assign, D, sums = data.assign_to(centroids)
+
+ log('compute centroids', end='\r', flush=True)
+
+ t_search_tot += time.time() - t0s;
+
+ err = D.sum()
+ if is_torch:
+ err = err.item()
+ obj.append(err)
+
+ hassign = np.bincount(assign, minlength=k)
+
+ fac = hassign.reshape(-1, 1).astype('float32')
+ fac[fac == 0] = 1 # quiet warning
+ if is_torch:
+ import torch
+ fac = torch.from_numpy(fac).to(sums.device)
+
+ centroids = sums / fac
+
+ nsplit = reassign_centroids(hassign, centroids, rs)
+
+ s = {
+ "obj": err,
+ "time": (time.time() - t0),
+ "time_search": t_search_tot,
+ "imbalance_factor": imbalance_factor(k, assign),
+ "nsplit": nsplit
+ }
+
+ log((" Iteration %d (%.2f s, search %.2f s): "
+ "objective=%g imbalance=%.3f nsplit=%d") % (
+ i, s["time"], s["time_search"],
+ err, s["imbalance_factor"],
+ nsplit)
+ )
+ iteration_stats.append(s)
+
+ if checkpoint is not None:
+ log('storing centroids in', checkpoint)
+ if is_torch:
+ import torch
+ torch.save(centroids, checkpoint)
+ else:
+ np.save(checkpoint, centroids)
+
+ if return_stats:
+ return centroids, iteration_stats
+ else:
+ return centroids
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/datasets.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/datasets.py
new file mode 100644
index 0000000..e830a03
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/datasets.py
@@ -0,0 +1,387 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import numpy as np
+import faiss
+import getpass
+
+
+from .vecs_io import fvecs_read, ivecs_read, bvecs_mmap, fvecs_mmap
+from .exhaustive_search import knn
+
+class Dataset:
+ """ Generic abstract class for a test dataset """
+
+ def __init__(self):
+ """ the constructor should set the following fields: """
+ self.d = -1
+ self.metric = 'L2' # or IP
+ self.nq = -1
+ self.nb = -1
+ self.nt = -1
+
+ def get_queries(self):
+ """ return the queries as a (nq, d) array """
+ raise NotImplementedError()
+
+ def get_train(self, maxtrain=None):
+ """ return the queries as a (nt, d) array """
+ raise NotImplementedError()
+
+ def get_database(self):
+ """ return the queries as a (nb, d) array """
+ raise NotImplementedError()
+
+ def database_iterator(self, bs=128, split=(1, 0)):
+ """returns an iterator on database vectors.
+ bs is the number of vectors per batch
+ split = (nsplit, rank) means the dataset is split in nsplit
+ shards and we want shard number rank
+ The default implementation just iterates over the full matrix
+ returned by get_dataset.
+ """
+ xb = self.get_database()
+ nsplit, rank = split
+ i0, i1 = self.nb * rank // nsplit, self.nb * (rank + 1) // nsplit
+ for j0 in range(i0, i1, bs):
+ yield xb[j0: min(j0 + bs, i1)]
+
+ def get_groundtruth(self, k=None):
+ """ return the ground truth for k-nearest neighbor search """
+ raise NotImplementedError()
+
+ def get_groundtruth_range(self, thresh=None):
+ """ return the ground truth for range search """
+ raise NotImplementedError()
+
+ def __str__(self):
+ return (f"dataset in dimension {self.d}, with metric {self.metric}, "
+ f"size: Q {self.nq} B {self.nb} T {self.nt}")
+
+ def check_sizes(self):
+ """ runs the previous and checks the sizes of the matrices """
+ assert self.get_queries().shape == (self.nq, self.d)
+ if self.nt > 0:
+ xt = self.get_train(maxtrain=123)
+ assert xt.shape == (123, self.d), "shape=%s" % (xt.shape, )
+ assert self.get_database().shape == (self.nb, self.d)
+ assert self.get_groundtruth(k=13).shape == (self.nq, 13)
+
+
+class SyntheticDataset(Dataset):
+ """A dataset that is not completely random but still challenging to
+ index
+ """
+
+ def __init__(self, d, nt, nb, nq, metric='L2', seed=1338):
+ Dataset.__init__(self)
+ self.d, self.nt, self.nb, self.nq = d, nt, nb, nq
+ d1 = 10 # intrinsic dimension (more or less)
+ n = nb + nt + nq
+ rs = np.random.RandomState(seed)
+ x = rs.normal(size=(n, d1))
+ x = np.dot(x, rs.rand(d1, d))
+ # now we have a d1-dim ellipsoid in d-dimensional space
+ # higher factor (>4) -> higher frequency -> less linear
+ x = x * (rs.rand(d) * 4 + 0.1)
+ x = np.sin(x)
+ x = x.astype('float32')
+ self.metric = metric
+ self.xt = x[:nt]
+ self.xb = x[nt:nt + nb]
+ self.xq = x[nt + nb:]
+
+ def get_queries(self):
+ return self.xq
+
+ def get_train(self, maxtrain=None):
+ maxtrain = maxtrain if maxtrain is not None else self.nt
+ return self.xt[:maxtrain]
+
+ def get_database(self):
+ return self.xb
+
+ def get_groundtruth(self, k=100):
+ return knn(
+ self.xq, self.xb, k,
+ faiss.METRIC_L2 if self.metric == 'L2' else faiss.METRIC_INNER_PRODUCT
+ )[1]
+
+
+############################################################################
+# The following datasets are a few standard open-source datasets
+# they should be stored in a directory, and we start by guessing where
+# that directory is
+############################################################################
+
+username = getpass.getuser()
+
+for dataset_basedir in (
+ '/datasets01/simsearch/041218/',
+ '/mnt/vol/gfsai-flash3-east/ai-group/datasets/simsearch/',
+ f'/home/{username}/simsearch/data/'):
+ if os.path.exists(dataset_basedir):
+ break
+else:
+ # users can link their data directory to `./data`
+ dataset_basedir = 'data/'
+
+
+def set_dataset_basedir(path):
+ global dataset_basedir
+ dataset_basedir = path
+
+
+class DatasetSIFT1M(Dataset):
+ """
+ The original dataset is available at: http://corpus-texmex.irisa.fr/
+ (ANN_SIFT1M)
+ """
+
+ def __init__(self):
+ Dataset.__init__(self)
+ self.d, self.nt, self.nb, self.nq = 128, 100000, 1000000, 10000
+ self.basedir = dataset_basedir + 'sift1M/'
+
+ def get_queries(self):
+ return fvecs_read(self.basedir + "sift_query.fvecs")
+
+ def get_train(self, maxtrain=None):
+ maxtrain = maxtrain if maxtrain is not None else self.nt
+ return fvecs_read(self.basedir + "sift_learn.fvecs")[:maxtrain]
+
+ def get_database(self):
+ return fvecs_read(self.basedir + "sift_base.fvecs")
+
+ def get_groundtruth(self, k=None):
+ gt = ivecs_read(self.basedir + "sift_groundtruth.ivecs")
+ if k is not None:
+ assert k <= 100
+ gt = gt[:, :k]
+ return gt
+
+
+def sanitize(x):
+ return np.ascontiguousarray(x, dtype='float32')
+
+
+class DatasetBigANN(Dataset):
+ """
+ The original dataset is available at: http://corpus-texmex.irisa.fr/
+ (ANN_SIFT1B)
+ """
+
+ def __init__(self, nb_M=1000):
+ Dataset.__init__(self)
+ assert nb_M in (1, 2, 5, 10, 20, 50, 100, 200, 500, 1000)
+ self.nb_M = nb_M
+ nb = nb_M * 10**6
+ self.d, self.nt, self.nb, self.nq = 128, 10**8, nb, 10000
+ self.basedir = dataset_basedir + 'bigann/'
+
+ def get_queries(self):
+ return sanitize(bvecs_mmap(self.basedir + 'bigann_query.bvecs')[:])
+
+ def get_train(self, maxtrain=None):
+ maxtrain = maxtrain if maxtrain is not None else self.nt
+ return sanitize(bvecs_mmap(self.basedir + 'bigann_learn.bvecs')[:maxtrain])
+
+ def get_groundtruth(self, k=None):
+ gt = ivecs_read(self.basedir + 'gnd/idx_%dM.ivecs' % self.nb_M)
+ if k is not None:
+ assert k <= 100
+ gt = gt[:, :k]
+ return gt
+
+ def get_database(self):
+ assert self.nb_M < 100, "dataset too large, use iterator"
+ return sanitize(bvecs_mmap(self.basedir + 'bigann_base.bvecs')[:self.nb])
+
+ def database_iterator(self, bs=128, split=(1, 0)):
+ xb = bvecs_mmap(self.basedir + 'bigann_base.bvecs')
+ nsplit, rank = split
+ i0, i1 = self.nb * rank // nsplit, self.nb * (rank + 1) // nsplit
+ for j0 in range(i0, i1, bs):
+ yield sanitize(xb[j0: min(j0 + bs, i1)])
+
+
+class DatasetDeep1B(Dataset):
+ """
+ See
+ https://github.com/facebookresearch/faiss/tree/main/benchs#getting-deep1b
+ on how to get the data
+ """
+
+ def __init__(self, nb=10**9):
+ Dataset.__init__(self)
+ nb_to_name = {
+ 10**5: '100k',
+ 10**6: '1M',
+ 10**7: '10M',
+ 10**8: '100M',
+ 10**9: '1B'
+ }
+ assert nb in nb_to_name
+ self.d, self.nt, self.nb, self.nq = 96, 358480000, nb, 10000
+ self.basedir = dataset_basedir + 'deep1b/'
+ self.gt_fname = "%sdeep%s_groundtruth.ivecs" % (
+ self.basedir, nb_to_name[self.nb])
+
+ def get_queries(self):
+ return sanitize(fvecs_read(self.basedir + "deep1B_queries.fvecs"))
+
+ def get_train(self, maxtrain=None):
+ maxtrain = maxtrain if maxtrain is not None else self.nt
+ return sanitize(fvecs_mmap(self.basedir + "learn.fvecs")[:maxtrain])
+
+ def get_groundtruth(self, k=None):
+ gt = ivecs_read(self.gt_fname)
+ if k is not None:
+ assert k <= 100
+ gt = gt[:, :k]
+ return gt
+
+ def get_database(self):
+ assert self.nb <= 10**8, "dataset too large, use iterator"
+ return sanitize(fvecs_mmap(self.basedir + "base.fvecs")[:self.nb])
+
+ def database_iterator(self, bs=128, split=(1, 0)):
+ xb = fvecs_mmap(self.basedir + "base.fvecs")
+ nsplit, rank = split
+ i0, i1 = self.nb * rank // nsplit, self.nb * (rank + 1) // nsplit
+ for j0 in range(i0, i1, bs):
+ yield sanitize(xb[j0: min(j0 + bs, i1)])
+
+
+class DatasetGlove(Dataset):
+ """
+ Data from http://ann-benchmarks.com/glove-100-angular.hdf5
+ """
+
+ def __init__(self, loc=None, download=False):
+ import h5py
+ assert not download, "not implemented"
+ if not loc:
+ loc = dataset_basedir + 'glove/glove-100-angular.hdf5'
+ self.glove_h5py = h5py.File(loc, 'r')
+ # IP and L2 are equivalent in this case, but it is traditionally seen as an IP dataset
+ self.metric = 'IP'
+ self.d, self.nt = 100, 0
+ self.nb = self.glove_h5py['train'].shape[0]
+ self.nq = self.glove_h5py['test'].shape[0]
+
+ def get_queries(self):
+ xq = np.array(self.glove_h5py['test'])
+ faiss.normalize_L2(xq)
+ return xq
+
+ def get_database(self):
+ xb = np.array(self.glove_h5py['train'])
+ faiss.normalize_L2(xb)
+ return xb
+
+ def get_groundtruth(self, k=None):
+ gt = self.glove_h5py['neighbors']
+ if k is not None:
+ assert k <= 100
+ gt = gt[:, :k]
+ return gt
+
+
+class DatasetMusic100(Dataset):
+ """
+ get dataset from
+ https://github.com/stanis-morozov/ip-nsw#dataset
+ """
+
+ def __init__(self):
+ Dataset.__init__(self)
+ self.d, self.nt, self.nb, self.nq = 100, 0, 10**6, 10000
+ self.metric = 'IP'
+ self.basedir = dataset_basedir + 'music-100/'
+
+ def get_queries(self):
+ xq = np.fromfile(self.basedir + 'query_music100.bin', dtype='float32')
+ xq = xq.reshape(-1, 100)
+ return xq
+
+ def get_database(self):
+ xb = np.fromfile(self.basedir + 'database_music100.bin', dtype='float32')
+ xb = xb.reshape(-1, 100)
+ return xb
+
+ def get_groundtruth(self, k=None):
+ gt = np.load(self.basedir + 'gt.npy')
+ if k is not None:
+ assert k <= 100
+ gt = gt[:, :k]
+ return gt
+
+class DatasetGIST1M(Dataset):
+ """
+ The original dataset is available at: http://corpus-texmex.irisa.fr/
+ (ANN_SIFT1M)
+ """
+
+ def __init__(self):
+ Dataset.__init__(self)
+ self.d, self.nt, self.nb, self.nq = 960, 100000, 1000000, 10000
+ self.basedir = dataset_basedir + 'gist1M/'
+
+ def get_queries(self):
+ return fvecs_read(self.basedir + "gist_query.fvecs")
+
+ def get_train(self, maxtrain=None):
+ maxtrain = maxtrain if maxtrain is not None else self.nt
+ return fvecs_read(self.basedir + "gist_learn.fvecs")[:maxtrain]
+
+ def get_database(self):
+ return fvecs_read(self.basedir + "gist_base.fvecs")
+
+ def get_groundtruth(self, k=None):
+ gt = ivecs_read(self.basedir + "gist_groundtruth.ivecs")
+ if k is not None:
+ assert k <= 100
+ gt = gt[:, :k]
+ return gt
+
+
+def dataset_from_name(dataset='deep1M', download=False):
+ """ converts a string describing a dataset to a Dataset object
+ Supports sift1M, bigann1M..bigann1B, deep1M..deep1B, music-100 and glove
+ """
+
+ if dataset == 'sift1M':
+ return DatasetSIFT1M()
+
+ elif dataset == 'gist1M':
+ return DatasetGIST1M()
+
+ elif dataset.startswith('bigann'):
+ dbsize = 1000 if dataset == "bigann1B" else int(dataset[6:-1])
+ return DatasetBigANN(nb_M=dbsize)
+
+ elif dataset.startswith("deep"):
+
+ szsuf = dataset[4:]
+ if szsuf[-1] == 'M':
+ dbsize = 10 ** 6 * int(szsuf[:-1])
+ elif szsuf == '1B':
+ dbsize = 10 ** 9
+ elif szsuf[-1] == 'k':
+ dbsize = 1000 * int(szsuf[:-1])
+ else:
+ assert False, "did not recognize suffix " + szsuf
+ return DatasetDeep1B(nb=dbsize)
+
+ elif dataset == "music-100":
+ return DatasetMusic100()
+
+ elif dataset == "glove":
+ return DatasetGlove(download=download)
+
+ else:
+ raise RuntimeError("unknown dataset " + dataset)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/evaluation.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/evaluation.py
new file mode 100644
index 0000000..a53f605
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/evaluation.py
@@ -0,0 +1,492 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import unittest
+import time
+import faiss
+
+from multiprocessing.pool import ThreadPool
+
+###############################################################
+# Simple functions to evaluate knn results
+
+def knn_intersection_measure(I1, I2):
+ """ computes the intersection measure of two result tables
+ """
+ nq, rank = I1.shape
+ assert I2.shape == (nq, rank)
+ ninter = sum(
+ np.intersect1d(I1[i], I2[i]).size
+ for i in range(nq)
+ )
+ return ninter / I1.size
+
+###############################################################
+# Range search results can be compared with Precision-Recall
+
+def filter_range_results(lims, D, I, thresh):
+ """ select a set of results """
+ nq = lims.size - 1
+ mask = D < thresh
+ new_lims = np.zeros_like(lims)
+ for i in range(nq):
+ new_lims[i + 1] = new_lims[i] + mask[lims[i] : lims[i + 1]].sum()
+ return new_lims, D[mask], I[mask]
+
+
+def range_PR(lims_ref, Iref, lims_new, Inew, mode="overall"):
+ """compute the precision and recall of range search results. The
+ function does not take the distances into account. """
+
+ def ref_result_for(i):
+ return Iref[lims_ref[i]:lims_ref[i + 1]]
+
+ def new_result_for(i):
+ return Inew[lims_new[i]:lims_new[i + 1]]
+
+ nq = lims_ref.size - 1
+ assert lims_new.size - 1 == nq
+
+ ninter = np.zeros(nq, dtype="int64")
+
+ def compute_PR_for(q):
+
+ # ground truth results for this query
+ gt_ids = ref_result_for(q)
+
+ # results for this query
+ new_ids = new_result_for(q)
+
+ # there are no set functions in numpy so let's do this
+ inter = np.intersect1d(gt_ids, new_ids)
+
+ ninter[q] = len(inter)
+
+ # run in a thread pool, which helps in spite of the GIL
+ pool = ThreadPool(20)
+ pool.map(compute_PR_for, range(nq))
+
+ return counts_to_PR(
+ lims_ref[1:] - lims_ref[:-1],
+ lims_new[1:] - lims_new[:-1],
+ ninter,
+ mode=mode
+ )
+
+
+def counts_to_PR(ngt, nres, ninter, mode="overall"):
+ """ computes a precision-recall for a ser of queries.
+ ngt = nb of GT results per query
+ nres = nb of found results per query
+ ninter = nb of correct results per query (smaller than nres of course)
+ """
+
+ if mode == "overall":
+ ngt, nres, ninter = ngt.sum(), nres.sum(), ninter.sum()
+
+ if nres > 0:
+ precision = ninter / nres
+ else:
+ precision = 1.0
+
+ if ngt > 0:
+ recall = ninter / ngt
+ elif nres == 0:
+ recall = 1.0
+ else:
+ recall = 0.0
+
+ return precision, recall
+
+ elif mode == "average":
+ # average precision and recall over queries
+
+ mask = ngt == 0
+ ngt[mask] = 1
+
+ recalls = ninter / ngt
+ recalls[mask] = (nres[mask] == 0).astype(float)
+
+ # avoid division by 0
+ mask = nres == 0
+ assert np.all(ninter[mask] == 0)
+ ninter[mask] = 1
+ nres[mask] = 1
+
+ precisions = ninter / nres
+
+ return precisions.mean(), recalls.mean()
+
+ else:
+ raise AssertionError()
+
+def sort_range_res_2(lims, D, I):
+ """ sort 2 arrays using the first as key """
+ I2 = np.empty_like(I)
+ D2 = np.empty_like(D)
+ nq = len(lims) - 1
+ for i in range(nq):
+ l0, l1 = lims[i], lims[i + 1]
+ ii = I[l0:l1]
+ di = D[l0:l1]
+ o = di.argsort()
+ I2[l0:l1] = ii[o]
+ D2[l0:l1] = di[o]
+ return I2, D2
+
+
+def sort_range_res_1(lims, I):
+ I2 = np.empty_like(I)
+ nq = len(lims) - 1
+ for i in range(nq):
+ l0, l1 = lims[i], lims[i + 1]
+ I2[l0:l1] = I[l0:l1]
+ I2[l0:l1].sort()
+ return I2
+
+
+def range_PR_multiple_thresholds(
+ lims_ref, Iref,
+ lims_new, Dnew, Inew,
+ thresholds,
+ mode="overall", do_sort="ref,new"
+ ):
+ """ compute precision-recall values for range search results
+ for several thresholds on the "new" results.
+ This is to plot PR curves
+ """
+ # ref should be sorted by ids
+ if "ref" in do_sort:
+ Iref = sort_range_res_1(lims_ref, Iref)
+
+ # new should be sorted by distances
+ if "new" in do_sort:
+ Inew, Dnew = sort_range_res_2(lims_new, Dnew, Inew)
+
+ def ref_result_for(i):
+ return Iref[lims_ref[i]:lims_ref[i + 1]]
+
+ def new_result_for(i):
+ l0, l1 = lims_new[i], lims_new[i + 1]
+ return Inew[l0:l1], Dnew[l0:l1]
+
+ nq = lims_ref.size - 1
+ assert lims_new.size - 1 == nq
+
+ nt = len(thresholds)
+ counts = np.zeros((nq, nt, 3), dtype="int64")
+
+ def compute_PR_for(q):
+ gt_ids = ref_result_for(q)
+ res_ids, res_dis = new_result_for(q)
+
+ counts[q, :, 0] = len(gt_ids)
+
+ if res_dis.size == 0:
+ # the rest remains at 0
+ return
+
+ # which offsets we are interested in
+ nres= np.searchsorted(res_dis, thresholds)
+ counts[q, :, 1] = nres
+
+ if gt_ids.size == 0:
+ return
+
+ # find number of TPs at each stage in the result list
+ ii = np.searchsorted(gt_ids, res_ids)
+ ii[ii == len(gt_ids)] = -1
+ n_ok = np.cumsum(gt_ids[ii] == res_ids)
+
+ # focus on threshold points
+ n_ok = np.hstack(([0], n_ok))
+ counts[q, :, 2] = n_ok[nres]
+
+ pool = ThreadPool(20)
+ pool.map(compute_PR_for, range(nq))
+ # print(counts.transpose(2, 1, 0))
+
+ precisions = np.zeros(nt)
+ recalls = np.zeros(nt)
+ for t in range(nt):
+ p, r = counts_to_PR(
+ counts[:, t, 0], counts[:, t, 1], counts[:, t, 2],
+ mode=mode
+ )
+ precisions[t] = p
+ recalls[t] = r
+
+ return precisions, recalls
+
+
+###############################################################
+# Functions that compare search results with a reference result.
+# They are intended for use in tests
+
+def _cluster_tables_with_tolerance(tab1, tab2, thr):
+ """ for two tables, cluster them by merging values closer than thr.
+ Returns the cluster ids for each table element """
+ tab = np.hstack([tab1, tab2])
+ tab.sort()
+ n = len(tab)
+ diffs = np.ones(n)
+ diffs[1:] = tab[1:] - tab[:-1]
+ unique_vals = tab[diffs > thr]
+ idx1 = np.searchsorted(unique_vals, tab1, side='right') - 1
+ idx2 = np.searchsorted(unique_vals, tab2, side='right') - 1
+ return idx1, idx2
+
+
+def check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, rtol=1e-5):
+ """ test that knn search results are identical, with possible ties.
+ Raise if not. """
+ np.testing.assert_allclose(Dref, Dnew, rtol=rtol)
+ # here we have to be careful because of draws
+ testcase = unittest.TestCase() # because it makes nice error messages
+ for i in range(len(Iref)):
+ if np.all(Iref[i] == Inew[i]): # easy case
+ continue
+
+ # otherwise collect elements per distance
+ r = rtol * Dref[i].max()
+
+ DrefC, DnewC = _cluster_tables_with_tolerance(Dref[i], Dnew[i], r)
+
+ for dis in np.unique(DrefC):
+ if dis == DrefC[-1]:
+ continue
+ mask = DrefC == dis
+ testcase.assertEqual(set(Iref[i, mask]), set(Inew[i, mask]))
+
+
+def check_ref_range_results(Lref, Dref, Iref,
+ Lnew, Dnew, Inew):
+ """ compare range search results wrt. a reference result,
+ throw if it fails """
+ np.testing.assert_array_equal(Lref, Lnew)
+ nq = len(Lref) - 1
+ for i in range(nq):
+ l0, l1 = Lref[i], Lref[i + 1]
+ Ii_ref = Iref[l0:l1]
+ Ii_new = Inew[l0:l1]
+ Di_ref = Dref[l0:l1]
+ Di_new = Dnew[l0:l1]
+ if np.all(Ii_ref == Ii_new): # easy
+ pass
+ else:
+ def sort_by_ids(I, D):
+ o = I.argsort()
+ return I[o], D[o]
+ # sort both
+ (Ii_ref, Di_ref) = sort_by_ids(Ii_ref, Di_ref)
+ (Ii_new, Di_new) = sort_by_ids(Ii_new, Di_new)
+ np.testing.assert_array_equal(Ii_ref, Ii_new)
+ np.testing.assert_array_almost_equal(Di_ref, Di_new, decimal=5)
+
+
+###############################################################
+# OperatingPoints functions
+# this is the Python version of the AutoTune object in C++
+
+class OperatingPoints:
+ """
+ Manages a set of search parameters with associated performance and time.
+ Keeps the Pareto optimal points.
+ """
+
+ def __init__(self):
+ # list of (key, perf, t)
+ self.operating_points = [
+ # (self.do_nothing_key(), 0.0, 0.0)
+ ]
+ self.suboptimal_points = []
+
+ def compare_keys(self, k1, k2):
+ """ return -1 if k1 > k2, 1 if k2 > k1, 0 otherwise """
+ raise NotImplemented
+
+ def do_nothing_key(self):
+ """ parameters to say we do noting, takes 0 time and has 0 performance"""
+ raise NotImplemented
+
+ def is_pareto_optimal(self, perf_new, t_new):
+ for _, perf, t in self.operating_points:
+ if perf >= perf_new and t <= t_new:
+ return False
+ return True
+
+ def predict_bounds(self, key):
+ """ predicts the bound on time and performance """
+ min_time = 0.0
+ max_perf = 1.0
+ for key2, perf, t in self.operating_points + self.suboptimal_points:
+ cmp = self.compare_keys(key, key2)
+ if cmp > 0: # key2 > key
+ if t > min_time:
+ min_time = t
+ if cmp < 0: # key2 < key
+ if perf < max_perf:
+ max_perf = perf
+ return max_perf, min_time
+
+ def should_run_experiment(self, key):
+ (max_perf, min_time) = self.predict_bounds(key)
+ return self.is_pareto_optimal(max_perf, min_time)
+
+ def add_operating_point(self, key, perf, t):
+ if self.is_pareto_optimal(perf, t):
+ i = 0
+ # maybe it shadows some other operating point completely?
+ while i < len(self.operating_points):
+ op_Ls, perf2, t2 = self.operating_points[i]
+ if perf >= perf2 and t < t2:
+ self.suboptimal_points.append(
+ self.operating_points.pop(i))
+ else:
+ i += 1
+ self.operating_points.append((key, perf, t))
+ return True
+ else:
+ self.suboptimal_points.append((key, perf, t))
+ return False
+
+
+class OperatingPointsWithRanges(OperatingPoints):
+ """
+ Set of parameters that are each picked from a discrete range of values.
+ An increase of each parameter is assumed to make the operation slower
+ and more accurate.
+ A key = int array of indices in the ordered set of parameters.
+ """
+
+ def __init__(self):
+ OperatingPoints.__init__(self)
+ # list of (name, values)
+ self.ranges = []
+
+ def add_range(self, name, values):
+ self.ranges.append((name, values))
+
+ def compare_keys(self, k1, k2):
+ if np.all(k1 >= k2):
+ return 1
+ if np.all(k2 >= k1):
+ return -1
+ return 0
+
+ def do_nothing_key(self):
+ return np.zeros(len(self.ranges), dtype=int)
+
+ def num_experiments(self):
+ return int(np.prod([len(values) for name, values in self.ranges]))
+
+ def sample_experiments(self, n_autotune, rs=np.random):
+ """ sample a set of experiments of max size n_autotune
+ (run all experiments in random order if n_autotune is 0)
+ """
+ assert n_autotune == 0 or n_autotune >= 2
+ totex = self.num_experiments()
+ rs = np.random.RandomState(123)
+ if n_autotune == 0 or totex < n_autotune:
+ experiments = rs.permutation(totex - 2)
+ else:
+ experiments = rs.choice(
+ totex - 2, size=n_autotune - 2, replace=False)
+
+ experiments = [0, totex - 1] + [int(cno) + 1 for cno in experiments]
+ return experiments
+
+ def cno_to_key(self, cno):
+ """Convert a sequential experiment number to a key"""
+ k = np.zeros(len(self.ranges), dtype=int)
+ for i, (name, values) in enumerate(self.ranges):
+ k[i] = cno % len(values)
+ cno //= len(values)
+ assert cno == 0
+ return k
+
+ def get_parameters(self, k):
+ """Convert a key to a dictionary with parameter values"""
+ return {
+ name: values[k[i]]
+ for i, (name, values) in enumerate(self.ranges)
+ }
+
+ def restrict_range(self, name, max_val):
+ """ remove too large values from a range"""
+ for name2, values in self.ranges:
+ if name == name2:
+ val2 = [v for v in values if v < max_val]
+ values[:] = val2
+ return
+ raise RuntimeError(f"parameter {name} not found")
+
+
+###############################################################
+# Timer object
+
+class TimerIter:
+ def __init__(self, timer):
+ self.ts = []
+ self.runs = timer.runs
+ self.timer = timer
+ if timer.nt >= 0:
+ faiss.omp_set_num_threads(timer.nt)
+
+ def __next__(self):
+ timer = self.timer
+ self.runs -= 1
+ self.ts.append(time.time())
+ total_time = self.ts[-1] - self.ts[0] if len(self.ts) >= 2 else 0
+ if self.runs == -1 or total_time > timer.max_secs:
+ if timer.nt >= 0:
+ faiss.omp_set_num_threads(timer.remember_nt)
+ ts = np.array(self.ts)
+ times = ts[1:] - ts[:-1]
+ if len(times) == timer.runs:
+ timer.times = times[timer.warmup :]
+ else:
+ # if timeout, we use all the runs
+ timer.times = times[:]
+ raise StopIteration
+
+class RepeatTimer:
+ """
+ This is yet another timer object. It is adapted to Faiss by
+ taking a number of openmp threads to set on input. It should be called
+ in an explicit loop as:
+
+ timer = RepeatTimer(warmup=1, nt=1, runs=6)
+
+ for _ in timer:
+ # perform operation
+
+ print(f"time={timer.get_ms():.1f} ± {timer.get_ms_std():.1f} ms")
+
+ the same timer can be re-used. In that case it is reset each time it
+ enters a loop. It focuses on ms-scale times because for second scale
+ it's usually less relevant to repeat the operation.
+ """
+ def __init__(self, warmup=0, nt=-1, runs=1, max_secs=np.inf):
+ assert warmup < runs
+ self.warmup = warmup
+ self.nt = nt
+ self.runs = runs
+ self.max_secs = max_secs
+ self.remember_nt = faiss.omp_get_max_threads()
+
+ def __iter__(self):
+ return TimerIter(self)
+
+ def ms(self):
+ return np.mean(self.times) * 1000
+
+ def ms_std(self):
+ return np.std(self.times) * 1000 if len(self.times) > 1 else 0.0
+
+ def nruns(self):
+ """ effective number of runs (may be lower than runs - warmup due to timeout)"""
+ return len(self.times)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/exhaustive_search.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/exhaustive_search.py
new file mode 100644
index 0000000..2574277
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/exhaustive_search.py
@@ -0,0 +1,367 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import time
+import numpy as np
+
+import logging
+
+LOG = logging.getLogger(__name__)
+
+def knn_ground_truth(xq, db_iterator, k, metric_type=faiss.METRIC_L2, shard=False, ngpu=-1):
+ """Computes the exact KNN search results for a dataset that possibly
+ does not fit in RAM but for which we have an iterator that
+ returns it block by block.
+ """
+ LOG.info("knn_ground_truth queries size %s k=%d" % (xq.shape, k))
+ t0 = time.time()
+ nq, d = xq.shape
+ keep_max = faiss.is_similarity_metric(metric_type)
+ rh = faiss.ResultHeap(nq, k, keep_max=keep_max)
+
+ index = faiss.IndexFlat(d, metric_type)
+ if ngpu == -1:
+ ngpu = faiss.get_num_gpus()
+
+ if ngpu:
+ LOG.info('running on %d GPUs' % ngpu)
+ co = faiss.GpuMultipleClonerOptions()
+ co.shard = shard
+ index = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)
+
+ # compute ground-truth by blocks, and add to heaps
+ i0 = 0
+ for xbi in db_iterator:
+ ni = xbi.shape[0]
+ index.add(xbi)
+ D, I = index.search(xq, k)
+ I += i0
+ rh.add_result(D, I)
+ index.reset()
+ i0 += ni
+ LOG.info("%d db elements, %.3f s" % (i0, time.time() - t0))
+
+ rh.finalize()
+ LOG.info("GT time: %.3f s (%d vectors)" % (time.time() - t0, i0))
+
+ return rh.D, rh.I
+
+# knn function used to be here
+knn = faiss.knn
+
+
+
+
+def range_search_gpu(xq, r2, index_gpu, index_cpu, gpu_k=1024):
+ """GPU does not support range search, so we emulate it with
+ knn search + fallback to CPU index.
+
+ The index_cpu can either be:
+ - a CPU index that supports range search
+ - a numpy table, that will be used to construct a Flat index if needed.
+ - None. In that case, at most gpu_k results will be returned
+ """
+ nq, d = xq.shape
+ is_binary_index = isinstance(index_gpu, faiss.IndexBinary)
+ keep_max = faiss.is_similarity_metric(index_gpu.metric_type)
+ r2 = int(r2) if is_binary_index else float(r2)
+ k = min(index_gpu.ntotal, gpu_k)
+ LOG.debug(
+ f"GPU search {nq} queries with {k=:} {is_binary_index=:} {keep_max=:}")
+ t0 = time.time()
+ D, I = index_gpu.search(xq, k)
+ t1 = time.time() - t0
+ if is_binary_index:
+ assert d * 8 < 32768 # let's compact the distance matrix
+ D = D.astype('int16')
+ t2 = 0
+ lim_remain = None
+ if index_cpu is not None:
+ if not keep_max:
+ mask = D[:, k - 1] < r2
+ else:
+ mask = D[:, k - 1] > r2
+ if mask.sum() > 0:
+ LOG.debug("CPU search remain %d" % mask.sum())
+ t0 = time.time()
+ if isinstance(index_cpu, np.ndarray):
+ # then it in fact an array that we have to make flat
+ xb = index_cpu
+ if is_binary_index:
+ index_cpu = faiss.IndexBinaryFlat(d * 8)
+ else:
+ index_cpu = faiss.IndexFlat(d, index_gpu.metric_type)
+ index_cpu.add(xb)
+ lim_remain, D_remain, I_remain = index_cpu.range_search(xq[mask], r2)
+ if is_binary_index:
+ D_remain = D_remain.astype('int16')
+ t2 = time.time() - t0
+ LOG.debug("combine")
+ t0 = time.time()
+
+ CombinerRangeKNN = (
+ faiss.CombinerRangeKNNint16 if is_binary_index else
+ faiss.CombinerRangeKNNfloat
+ )
+
+ combiner = CombinerRangeKNN(nq, k, r2, keep_max)
+ if True:
+ sp = faiss.swig_ptr
+ combiner.I = sp(I)
+ combiner.D = sp(D)
+ # combiner.set_knn_result(sp(I), sp(D))
+ if lim_remain is not None:
+ combiner.mask = sp(mask)
+ combiner.D_remain = sp(D_remain)
+ combiner.lim_remain = sp(lim_remain.view("int64"))
+ combiner.I_remain = sp(I_remain)
+ # combiner.set_range_result(sp(mask), sp(lim_remain.view("int64")), sp(D_remain), sp(I_remain))
+ L_res = np.empty(nq + 1, dtype='int64')
+ combiner.compute_sizes(sp(L_res))
+ nres = L_res[-1]
+ D_res = np.empty(nres, dtype=D.dtype)
+ I_res = np.empty(nres, dtype='int64')
+ combiner.write_result(sp(D_res), sp(I_res))
+ else:
+ D_res, I_res = [], []
+ nr = 0
+ for i in range(nq):
+ if not mask[i]:
+ if index_gpu.metric_type == faiss.METRIC_L2:
+ nv = (D[i, :] < r2).sum()
+ else:
+ nv = (D[i, :] > r2).sum()
+ D_res.append(D[i, :nv])
+ I_res.append(I[i, :nv])
+ else:
+ l0, l1 = lim_remain[nr], lim_remain[nr + 1]
+ D_res.append(D_remain[l0:l1])
+ I_res.append(I_remain[l0:l1])
+ nr += 1
+ L_res = np.cumsum([0] + [len(di) for di in D_res])
+ D_res = np.hstack(D_res)
+ I_res = np.hstack(I_res)
+ t3 = time.time() - t0
+ LOG.debug(f"times {t1:.3f}s {t2:.3f}s {t3:.3f}s")
+ return L_res, D_res, I_res
+
+
+def range_ground_truth(xq, db_iterator, threshold, metric_type=faiss.METRIC_L2,
+ shard=False, ngpu=-1):
+ """Computes the range-search search results for a dataset that possibly
+ does not fit in RAM but for which we have an iterator that
+ returns it block by block.
+ """
+ nq, d = xq.shape
+ t0 = time.time()
+ xq = np.ascontiguousarray(xq, dtype='float32')
+
+ index = faiss.IndexFlat(d, metric_type)
+ if ngpu == -1:
+ ngpu = faiss.get_num_gpus()
+ if ngpu:
+ LOG.info('running on %d GPUs' % ngpu)
+ co = faiss.GpuMultipleClonerOptions()
+ co.shard = shard
+ index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)
+
+ # compute ground-truth by blocks
+ i0 = 0
+ D = [[] for _i in range(nq)]
+ I = [[] for _i in range(nq)]
+ for xbi in db_iterator:
+ ni = xbi.shape[0]
+ if ngpu > 0:
+ index_gpu.add(xbi)
+ lims_i, Di, Ii = range_search_gpu(xq, threshold, index_gpu, xbi)
+ index_gpu.reset()
+ else:
+ index.add(xbi)
+ lims_i, Di, Ii = index.range_search(xq, threshold)
+ index.reset()
+ Ii += i0
+ for j in range(nq):
+ l0, l1 = lims_i[j], lims_i[j + 1]
+ if l1 > l0:
+ D[j].append(Di[l0:l1])
+ I[j].append(Ii[l0:l1])
+ i0 += ni
+ LOG.info("%d db elements, %.3f s" % (i0, time.time() - t0))
+
+ empty_I = np.zeros(0, dtype='int64')
+ empty_D = np.zeros(0, dtype='float32')
+ # import pdb; pdb.set_trace()
+ D = [(np.hstack(i) if i != [] else empty_D) for i in D]
+ I = [(np.hstack(i) if i != [] else empty_I) for i in I]
+ sizes = [len(i) for i in I]
+ assert len(sizes) == nq
+ lims = np.zeros(nq + 1, dtype="uint64")
+ lims[1:] = np.cumsum(sizes)
+ return lims, np.hstack(D), np.hstack(I)
+
+
+def threshold_radius_nres(nres, dis, ids, thresh, keep_max=False):
+ """ select a set of results """
+ if keep_max:
+ mask = dis > thresh
+ else:
+ mask = dis < thresh
+ new_nres = np.zeros_like(nres)
+ o = 0
+ for i, nr in enumerate(nres):
+ nr = int(nr) # avoid issues with int64 + uint64
+ new_nres[i] = mask[o:o + nr].sum()
+ o += nr
+ return new_nres, dis[mask], ids[mask]
+
+
+def threshold_radius(lims, dis, ids, thresh, keep_max=False):
+ """ restrict range-search results to those below a given radius """
+ if keep_max:
+ mask = dis > thresh
+ else:
+ mask = dis < thresh
+ new_lims = np.zeros_like(lims)
+ n = len(lims) - 1
+ for i in range(n):
+ l0, l1 = lims[i], lims[i + 1]
+ new_lims[i + 1] = new_lims[i] + mask[l0:l1].sum()
+ return new_lims, dis[mask], ids[mask]
+
+
+def apply_maxres(res_batches, target_nres, keep_max=False):
+ """find radius that reduces number of results to target_nres, and
+ applies it in-place to the result batches used in
+ range_search_max_results"""
+ alldis = np.hstack([dis for _, dis, _ in res_batches])
+ assert len(alldis) > target_nres
+ if keep_max:
+ alldis.partition(len(alldis) - target_nres - 1)
+ radius = alldis[-1 - target_nres]
+ else:
+ alldis.partition(target_nres)
+ radius = alldis[target_nres]
+
+ if alldis.dtype == 'float32':
+ radius = float(radius)
+ else:
+ radius = int(radius)
+ LOG.debug(' setting radius to %s' % radius)
+ totres = 0
+ for i, (nres, dis, ids) in enumerate(res_batches):
+ nres, dis, ids = threshold_radius_nres(
+ nres, dis, ids, radius, keep_max=keep_max)
+ totres += len(dis)
+ res_batches[i] = nres, dis, ids
+ LOG.debug(' updated previous results, new nb results %d' % totres)
+ return radius, totres
+
+
+def range_search_max_results(index, query_iterator, radius,
+ max_results=None, min_results=None,
+ shard=False, ngpu=0, clip_to_min=False):
+ """Performs a range search with many queries (given by an iterator)
+ and adjusts the threshold on-the-fly so that the total results
+ table does not grow larger than max_results.
+
+ If ngpu != 0, the function moves the index to this many GPUs to
+ speed up search.
+ """
+ # TODO: all result manipulations are in python, should move to C++ if perf
+ # critical
+ is_binary_index = isinstance(index, faiss.IndexBinary)
+
+ if min_results is None:
+ assert max_results is not None
+ min_results = int(0.8 * max_results)
+
+ if max_results is None:
+ assert min_results is not None
+ max_results = int(min_results * 1.5)
+
+ if ngpu == -1:
+ ngpu = faiss.get_num_gpus()
+
+ if ngpu:
+ LOG.info('running on %d GPUs' % ngpu)
+ co = faiss.GpuMultipleClonerOptions()
+ co.shard = shard
+ index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu)
+ else:
+ index_gpu = None
+
+ t_start = time.time()
+ t_search = t_post_process = 0
+ qtot = totres = raw_totres = 0
+ res_batches = []
+
+ for xqi in query_iterator:
+ t0 = time.time()
+ LOG.debug(f"searching {len(xqi)} vectors")
+ if index_gpu:
+ lims_i, Di, Ii = range_search_gpu(xqi, radius, index_gpu, index)
+ else:
+ lims_i, Di, Ii = index.range_search(xqi, radius)
+
+ nres_i = lims_i[1:] - lims_i[:-1]
+ raw_totres += len(Di)
+ qtot += len(xqi)
+
+ t1 = time.time()
+ if is_binary_index:
+ # weird Faiss quirk that returns floats for Hamming distances
+ Di = Di.astype('int16')
+
+ totres += len(Di)
+ res_batches.append((nres_i, Di, Ii))
+
+ if max_results is not None and totres > max_results:
+ LOG.info('too many results %d > %d, scaling back radius' %
+ (totres, max_results))
+ radius, totres = apply_maxres(
+ res_batches, min_results,
+ keep_max=index.metric_type == faiss.METRIC_INNER_PRODUCT
+ )
+ t2 = time.time()
+ t_search += t1 - t0
+ t_post_process += t2 - t1
+ LOG.debug(' [%.3f s] %d queries done, %d results' % (
+ time.time() - t_start, qtot, totres))
+
+ LOG.info(
+ 'search done in %.3f s + %.3f s, total %d results, end threshold %g' % (
+ t_search, t_post_process, totres, radius)
+ )
+
+ if clip_to_min and totres > min_results:
+ radius, totres = apply_maxres(
+ res_batches, min_results,
+ keep_max=index.metric_type == faiss.METRIC_INNER_PRODUCT
+ )
+
+ nres = np.hstack([nres_i for nres_i, dis_i, ids_i in res_batches])
+ dis = np.hstack([dis_i for nres_i, dis_i, ids_i in res_batches])
+ ids = np.hstack([ids_i for nres_i, dis_i, ids_i in res_batches])
+
+ lims = np.zeros(len(nres) + 1, dtype='uint64')
+ lims[1:] = np.cumsum(nres)
+
+ return radius, lims, dis, ids
+
+
+def exponential_query_iterator(xq, start_bs=32, max_bs=20000):
+ """ produces batches of progressively increasing sizes. This is useful to
+ adjust the search radius progressively without overflowing with
+ intermediate results """
+ nq = len(xq)
+ bs = start_bs
+ i = 0
+ while i < nq:
+ xqi = xq[i:i + bs]
+ yield xqi
+ if bs < max_bs:
+ bs *= 2
+ i += len(xqi)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/factory_tools.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/factory_tools.py
new file mode 100644
index 0000000..c8531cc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/factory_tools.py
@@ -0,0 +1,149 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import re
+
+
+def get_code_size(d, indexkey):
+ """ size of one vector in an index in dimension d
+ constructed with factory string indexkey"""
+
+ if indexkey == "Flat":
+ return d * 4
+
+ if indexkey.endswith(",RFlat"):
+ return d * 4 + get_code_size(d, indexkey[:-len(",RFlat")])
+
+ mo = re.match("IVF\\d+(_HNSW32)?,(.*)$", indexkey)
+ if mo:
+ return get_code_size(d, mo.group(2))
+
+ mo = re.match("IVF\\d+\\(.*\\)?,(.*)$", indexkey)
+ if mo:
+ return get_code_size(d, mo.group(1))
+
+ mo = re.match("IMI\\d+x2,(.*)$", indexkey)
+ if mo:
+ return get_code_size(d, mo.group(1))
+
+ mo = re.match("(.*),Refine\\((.*)\\)$", indexkey)
+ if mo:
+ return get_code_size(d, mo.group(1)) + get_code_size(d, mo.group(2))
+
+ mo = re.match('PQ(\\d+)x(\\d+)(fs|fsr)?$', indexkey)
+ if mo:
+ return (int(mo.group(1)) * int(mo.group(2)) + 7) // 8
+
+ mo = re.match('PQ(\\d+)\\+(\\d+)$', indexkey)
+ if mo:
+ return (int(mo.group(1)) + int(mo.group(2)))
+
+ mo = re.match('PQ(\\d+)$', indexkey)
+ if mo:
+ return int(mo.group(1))
+
+ if indexkey == "HNSW32" or indexkey == "HNSW32,Flat":
+ return d * 4 + 64 * 4 # roughly
+
+ if indexkey == 'SQ8':
+ return d
+ elif indexkey == 'SQ4':
+ return (d + 1) // 2
+ elif indexkey == 'SQ6':
+ return (d * 6 + 7) // 8
+ elif indexkey == 'SQfp16':
+ return d * 2
+ elif indexkey == 'SQbf16':
+ return d * 2
+
+ mo = re.match('PCAR?(\\d+),(.*)$', indexkey)
+ if mo:
+ return get_code_size(int(mo.group(1)), mo.group(2))
+ mo = re.match('OPQ\\d+_(\\d+),(.*)$', indexkey)
+ if mo:
+ return get_code_size(int(mo.group(1)), mo.group(2))
+ mo = re.match('OPQ\\d+,(.*)$', indexkey)
+ if mo:
+ return get_code_size(d, mo.group(1))
+ mo = re.match('RR(\\d+),(.*)$', indexkey)
+ if mo:
+ return get_code_size(int(mo.group(1)), mo.group(2))
+ raise RuntimeError("cannot parse " + indexkey)
+
+
+def get_hnsw_M(index):
+ return index.hnsw.cum_nneighbor_per_level.at(1) // 2
+
+
+def reverse_index_factory(index):
+ """
+ attempts to get the factory string the index was built with
+ """
+ index = faiss.downcast_index(index)
+ if isinstance(index, faiss.IndexFlat):
+ return "Flat"
+ elif isinstance(index, faiss.IndexIVF):
+ quantizer = faiss.downcast_index(index.quantizer)
+
+ if isinstance(quantizer, faiss.IndexFlat):
+ prefix = f"IVF{index.nlist}"
+ elif isinstance(quantizer, faiss.MultiIndexQuantizer):
+ prefix = f"IMI{quantizer.pq.M}x{quantizer.pq.nbits}"
+ elif isinstance(quantizer, faiss.IndexHNSW):
+ prefix = f"IVF{index.nlist}_HNSW{get_hnsw_M(quantizer)}"
+ else:
+ prefix = f"IVF{index.nlist}({reverse_index_factory(quantizer)})"
+
+ if isinstance(index, faiss.IndexIVFFlat):
+ return prefix + ",Flat"
+ if isinstance(index, faiss.IndexIVFScalarQuantizer):
+ return prefix + ",SQ8"
+ if isinstance(index, faiss.IndexIVFPQ):
+ return prefix + f",PQ{index.pq.M}x{index.pq.nbits}"
+ if isinstance(index, faiss.IndexIVFPQFastScan):
+ return prefix + f",PQ{index.pq.M}x{index.pq.nbits}fs"
+
+ elif isinstance(index, faiss.IndexPreTransform):
+ if index.chain.size() != 1:
+ raise NotImplementedError()
+ vt = faiss.downcast_VectorTransform(index.chain.at(0))
+ if isinstance(vt, faiss.OPQMatrix):
+ prefix = f"OPQ{vt.M}_{vt.d_out}"
+ elif isinstance(vt, faiss.ITQTransform):
+ prefix = f"ITQ{vt.itq.d_out}"
+ elif isinstance(vt, faiss.PCAMatrix):
+ assert vt.eigen_power == 0
+ prefix = "PCA" + ("R" if vt.random_rotation else "") + str(vt.d_out)
+ else:
+ raise NotImplementedError()
+ return f"{prefix},{reverse_index_factory(index.index)}"
+
+ elif isinstance(index, faiss.IndexHNSW):
+ return f"HNSW{get_hnsw_M(index)}"
+
+ elif isinstance(index, faiss.IndexRefine):
+ return f"{reverse_index_factory(index.base_index)},Refine({reverse_index_factory(index.refine_index)})"
+
+ elif isinstance(index, faiss.IndexPQFastScan):
+ return f"PQ{index.pq.M}x{index.pq.nbits}fs"
+
+ elif isinstance(index, faiss.IndexPQ):
+ return f"PQ{index.pq.M}x{index.pq.nbits}"
+
+ elif isinstance(index, faiss.IndexLSH):
+ return "LSH" + ("r" if index.rotate_data else "") + ("t" if index.train_thresholds else "")
+
+ elif isinstance(index, faiss.IndexScalarQuantizer):
+ sqtypes = {
+ faiss.ScalarQuantizer.QT_8bit: "8",
+ faiss.ScalarQuantizer.QT_4bit: "4",
+ faiss.ScalarQuantizer.QT_6bit: "6",
+ faiss.ScalarQuantizer.QT_fp16: "fp16",
+ faiss.ScalarQuantizer.QT_bf16: "bf16",
+ }
+ return f"SQ{sqtypes[index.sq.qtype]}"
+
+ raise NotImplementedError()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/inspect_tools.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/inspect_tools.py
new file mode 100644
index 0000000..3181559
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/inspect_tools.py
@@ -0,0 +1,117 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import faiss
+
+
+def get_invlist(invlists, l):
+ """ returns the inverted lists content as a pair of (list_ids, list_codes).
+ The codes are reshaped to a proper size
+ """
+ invlists = faiss.downcast_InvertedLists(invlists)
+ ls = invlists.list_size(l)
+ list_ids = np.zeros(ls, dtype='int64')
+ ids = codes = None
+ try:
+ ids = invlists.get_ids(l)
+ if ls > 0:
+ faiss.memcpy(faiss.swig_ptr(list_ids), ids, list_ids.nbytes)
+ codes = invlists.get_codes(l)
+ if invlists.code_size != faiss.InvertedLists.INVALID_CODE_SIZE:
+ list_codes = np.zeros((ls, invlists.code_size), dtype='uint8')
+ else:
+ # it's a BlockInvertedLists
+ npb = invlists.n_per_block
+ bs = invlists.block_size
+ ls_round = (ls + npb - 1) // npb
+ list_codes = np.zeros((ls_round, bs // npb, npb), dtype='uint8')
+ if ls > 0:
+ faiss.memcpy(faiss.swig_ptr(list_codes), codes, list_codes.nbytes)
+ finally:
+ if ids is not None:
+ invlists.release_ids(l, ids)
+ if codes is not None:
+ invlists.release_codes(l, codes)
+ return list_ids, list_codes
+
+
+def get_invlist_sizes(invlists):
+ """ return the array of sizes of the inverted lists """
+ return np.array([
+ invlists.list_size(i)
+ for i in range(invlists.nlist)
+ ], dtype='int64')
+
+
+def print_object_fields(obj):
+ """ list values all fields of an object known to SWIG """
+
+ for name in obj.__class__.__swig_getmethods__:
+ print(f"{name} = {getattr(obj, name)}")
+
+
+def get_pq_centroids(pq):
+ """ return the PQ centroids as an array """
+ cen = faiss.vector_to_array(pq.centroids)
+ return cen.reshape(pq.M, pq.ksub, pq.dsub)
+
+
+def get_LinearTransform_matrix(pca):
+ """ extract matrix + bias from the PCA object
+ works for any linear transform (OPQ, random rotation, etc.)
+ """
+ b = faiss.vector_to_array(pca.b)
+ A = faiss.vector_to_array(pca.A).reshape(pca.d_out, pca.d_in)
+ return A, b
+
+
+def make_LinearTransform_matrix(A, b=None):
+ """ make a linear transform from a matrix and a bias term (optional)"""
+ d_out, d_in = A.shape
+ if b is not None:
+ assert b.shape == (d_out, )
+ lt = faiss.LinearTransform(d_in, d_out, b is not None)
+ faiss.copy_array_to_vector(A.ravel(), lt.A)
+ if b is not None:
+ faiss.copy_array_to_vector(b, lt.b)
+ lt.is_trained = True
+ lt.set_is_orthonormal()
+ return lt
+
+
+def get_additive_quantizer_codebooks(aq):
+ """ return to codebooks of an additive quantizer """
+ codebooks = faiss.vector_to_array(aq.codebooks).reshape(-1, aq.d)
+ co = faiss.vector_to_array(aq.codebook_offsets)
+ return [
+ codebooks[co[i]:co[i + 1]]
+ for i in range(aq.M)
+ ]
+
+
+def get_flat_data(index):
+ """ copy and return the data matrix in an IndexFlat """
+ xb = faiss.vector_to_array(index.codes).view("float32")
+ return xb.reshape(index.ntotal, index.d)
+
+
+def get_flat_codes(index_flat):
+ """ get the codes from an indexFlatCodes as an array """
+ return faiss.vector_to_array(index_flat.codes).reshape(
+ index_flat.ntotal, index_flat.code_size)
+
+
+def get_NSG_neighbors(nsg):
+ """ get the neighbor list for the vectors stored in the NSG structure, as
+ a N-by-K matrix of indices """
+ graph = nsg.get_final_graph()
+ neighbors = np.zeros((graph.N, graph.K), dtype='int32')
+ faiss.memcpy(
+ faiss.swig_ptr(neighbors),
+ graph.data,
+ neighbors.nbytes
+ )
+ return neighbors
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/ivf_tools.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/ivf_tools.py
new file mode 100644
index 0000000..2cfec86
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/ivf_tools.py
@@ -0,0 +1,148 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import faiss
+
+from faiss.contrib.inspect_tools import get_invlist_sizes
+
+
+def add_preassigned(index_ivf, x, a, ids=None):
+ """
+ Add elements to an IVF index, where the assignment is already computed
+ """
+ n, d = x.shape
+ assert a.shape == (n, )
+ if isinstance(index_ivf, faiss.IndexBinaryIVF):
+ d *= 8
+ assert d == index_ivf.d
+ if ids is not None:
+ assert ids.shape == (n, )
+ ids = faiss.swig_ptr(ids)
+ index_ivf.add_core(
+ n, faiss.swig_ptr(x), ids, faiss.swig_ptr(a)
+ )
+
+
+def search_preassigned(index_ivf, xq, k, list_nos, coarse_dis=None):
+ """
+ Perform a search in the IVF index, with predefined lists to search into.
+ Supports indexes with pretransforms (as opposed to the
+ IndexIVF.search_preassigned, that cannot be applied with pretransform).
+ """
+ if isinstance(index_ivf, faiss.IndexPreTransform):
+ assert index_ivf.chain.size() == 1, "chain must have only one component"
+ transform = faiss.downcast_VectorTransform(index_ivf.chain.at(0))
+ xq = transform.apply(xq)
+ index_ivf = faiss.downcast_index(index_ivf.index)
+ n, d = xq.shape
+ if isinstance(index_ivf, faiss.IndexBinaryIVF):
+ d *= 8
+ dis_type = "int32"
+ else:
+ dis_type = "float32"
+
+ assert d == index_ivf.d
+ assert list_nos.shape == (n, index_ivf.nprobe)
+
+ # the coarse distances are used in IVFPQ with L2 distance and
+ # by_residual=True otherwise we provide dummy coarse_dis
+ if coarse_dis is None:
+ coarse_dis = np.zeros((n, index_ivf.nprobe), dtype=dis_type)
+ else:
+ assert coarse_dis.shape == (n, index_ivf.nprobe)
+
+ return index_ivf.search_preassigned(xq, k, list_nos, coarse_dis)
+
+
+def range_search_preassigned(index_ivf, x, radius, list_nos, coarse_dis=None):
+ """
+ Perform a range search in the IVF index, with predefined lists to
+ search into
+ """
+ n, d = x.shape
+ if isinstance(index_ivf, faiss.IndexBinaryIVF):
+ d *= 8
+ dis_type = "int32"
+ else:
+ dis_type = "float32"
+
+ # the coarse distances are used in IVFPQ with L2 distance and
+ # by_residual=True otherwise we provide dummy coarse_dis
+ if coarse_dis is None:
+ coarse_dis = np.empty((n, index_ivf.nprobe), dtype=dis_type)
+ else:
+ assert coarse_dis.shape == (n, index_ivf.nprobe)
+
+ assert d == index_ivf.d
+ assert list_nos.shape == (n, index_ivf.nprobe)
+
+ res = faiss.RangeSearchResult(n)
+ sp = faiss.swig_ptr
+
+ index_ivf.range_search_preassigned_c(
+ n, sp(x), radius,
+ sp(list_nos), sp(coarse_dis),
+ res
+ )
+ # get pointers and copy them
+ lims = faiss.rev_swig_ptr(res.lims, n + 1).copy()
+ num_results = int(lims[-1])
+ dist = faiss.rev_swig_ptr(res.distances, num_results).copy()
+ indices = faiss.rev_swig_ptr(res.labels, num_results).copy()
+ return lims, dist, indices
+
+
+def replace_ivf_quantizer(index_ivf, new_quantizer):
+ """ replace the IVF quantizer with a flat quantizer and return the
+ old quantizer"""
+ if new_quantizer.ntotal == 0:
+ centroids = index_ivf.quantizer.reconstruct_n()
+ new_quantizer.train(centroids)
+ new_quantizer.add(centroids)
+ else:
+ assert new_quantizer.ntotal == index_ivf.nlist
+
+ # cleanly dealloc old quantizer
+ old_own = index_ivf.own_fields
+ index_ivf.own_fields = False
+ old_quantizer = faiss.downcast_index(index_ivf.quantizer)
+ old_quantizer.this.own(old_own)
+ index_ivf.quantizer = new_quantizer
+
+ if hasattr(index_ivf, "referenced_objects"):
+ index_ivf.referenced_objects.append(new_quantizer)
+ else:
+ index_ivf.referenced_objects = [new_quantizer]
+ return old_quantizer
+
+
+def permute_invlists(index_ivf, perm):
+ """ Apply some permutation to the inverted lists, and modify the quantizer
+ entries accordingly.
+ Perm is an array of size nlist, where old_index = perm[new_index]
+ """
+ nlist, = perm.shape
+ assert index_ivf.nlist == nlist
+ quantizer = faiss.downcast_index(index_ivf.quantizer)
+ assert quantizer.ntotal == index_ivf.nlist
+ perm = np.ascontiguousarray(perm, dtype='int64')
+
+ # just make sure it's a permutation...
+ bc = np.bincount(perm, minlength=nlist)
+ assert np.all(bc == np.ones(nlist, dtype=int))
+
+ # handle quantizer
+ quantizer.permute_entries(perm)
+
+ # handle inverted lists
+ invlists = faiss.downcast_InvertedLists(index_ivf.invlists)
+ invlists.permute_invlists(faiss.swig_ptr(perm))
+
+
+def sort_invlists_by_size(index_ivf):
+ invlist_sizes = get_invlist_sizes(index_ivf.invlists)
+ perm = np.argsort(invlist_sizes)
+ permute_invlists(index_ivf, perm)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/ondisk.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/ondisk.py
new file mode 100644
index 0000000..4150091
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/ondisk.py
@@ -0,0 +1,59 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from typing import List
+import faiss
+import logging
+
+LOG = logging.getLogger(__name__)
+
+
+def merge_ondisk(
+ trained_index: faiss.Index, shard_fnames: List[str], ivfdata_fname: str, shift_ids=False
+) -> None:
+ """Add the contents of the indexes stored in shard_fnames into the index
+ trained_index. The on-disk data is stored in ivfdata_fname"""
+ assert not isinstance(
+ trained_index, faiss.IndexIVFPQR
+ ), "IndexIVFPQR is not supported as an on disk index."
+ # merge the images into an on-disk index
+ # first load the inverted lists
+ ivfs = []
+ for fname in shard_fnames:
+ # the IO_FLAG_MMAP is to avoid actually loading the data thus
+ # the total size of the inverted lists can exceed the
+ # available RAM
+ LOG.info("read " + fname)
+ index = faiss.read_index(fname, faiss.IO_FLAG_MMAP)
+ index_ivf = faiss.extract_index_ivf(index)
+ ivfs.append(index_ivf.invlists)
+
+ # avoid that the invlists get deallocated with the index
+ index_ivf.own_invlists = False
+
+ # construct the output index
+ index = trained_index
+ index_ivf = faiss.extract_index_ivf(index)
+
+ assert index.ntotal == 0, "works only on empty index"
+
+ # prepare the output inverted lists. They will be written
+ # to merged_index.ivfdata
+ invlists = faiss.OnDiskInvertedLists(
+ index_ivf.nlist, index_ivf.code_size, ivfdata_fname
+ )
+
+ # merge all the inverted lists
+ ivf_vector = faiss.InvertedListsPtrVector()
+ for ivf in ivfs:
+ ivf_vector.push_back(ivf)
+
+ LOG.info("merge %d inverted lists " % ivf_vector.size())
+ ntotal = invlists.merge_from_multiple(ivf_vector.data(), ivf_vector.size(), shift_ids)
+
+ # now replace the inverted lists in the output index
+ index.ntotal = index_ivf.ntotal = ntotal
+ index_ivf.replace_invlists(invlists, True)
+ invlists.this.disown()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/rpc.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/rpc.py
new file mode 100755
index 0000000..765d22a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/rpc.py
@@ -0,0 +1,258 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+Simplistic RPC implementation.
+Exposes all functions of a Server object.
+
+This code is for demonstration purposes only, and does not include certain
+security protections. It is not meant to be run on an untrusted network or
+in a production environment.
+"""
+
+import importlib
+import os
+import pickle
+import sys
+import _thread
+import traceback
+import socket
+import logging
+
+LOG = logging.getLogger(__name__)
+
+# default
+PORT = 12032
+
+safe_modules = {
+ 'numpy',
+ 'numpy.core.multiarray',
+}
+
+
+class RestrictedUnpickler(pickle.Unpickler):
+
+ def find_class(self, module, name):
+ # Only allow safe modules.
+ if module in safe_modules:
+ return getattr(importlib.import_module(module), name)
+ # Forbid everything else.
+ raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
+ (module, name))
+
+
+class FileSock:
+ " wraps a socket so that it is usable by pickle/cPickle "
+
+ def __init__(self,sock):
+ self.sock = sock
+ self.nr=0
+
+ def write(self, buf):
+ # print("sending %d bytes"%len(buf))
+ #self.sock.sendall(buf)
+ # print("...done")
+ bs = 512 * 1024
+ ns = 0
+ while ns < len(buf):
+ sent = self.sock.send(buf[ns:ns + bs])
+ ns += sent
+
+ def read(self,bs=512*1024):
+ #if self.nr==10000: pdb.set_trace()
+ self.nr+=1
+ # print("read bs=%d"%bs)
+ b = []
+ nb = 0
+ while len(b)<bs:
+ # print(' loop')
+ rb = self.sock.recv(bs - nb)
+ if not rb: break
+ b.append(rb)
+ nb += len(rb)
+ return b''.join(b)
+
+ def readline(self):
+ # print("readline!")
+ """may be optimized..."""
+ s=bytes()
+ while True:
+ c=self.read(1)
+ s+=c
+ if len(c)==0 or chr(c[0])=='\n':
+ return s
+
+class ClientExit(Exception):
+ pass
+
+class ServerException(Exception):
+ pass
+
+
+class Server:
+ """
+ server protocol. Methods from classes that subclass Server can be called
+ transparently from a client
+ """
+
+ def __init__(self, s, logf=sys.stderr, log_prefix=''):
+ self.logf = logf
+ self.log_prefix = log_prefix
+
+ # connection
+
+ self.conn = s
+ self.fs = FileSock(s)
+
+
+ def log(self, s):
+ self.logf.write("Sever log %s: %s\n" % (self.log_prefix, s))
+
+ def one_function(self):
+ """
+ Executes a single function with associated I/O.
+ Protocol:
+ - the arguments and results are serialized with the pickle protocol
+ - client sends : (fname,args)
+ fname = method name to call
+ args = tuple of arguments
+ - server sends result: (rid,st,ret)
+ rid = request id
+ st = None, or exception if there was during execution
+ ret = return value or None if st!=None
+ """
+
+ try:
+ (fname, args) = RestrictedUnpickler(self.fs).load()
+ except EOFError:
+ raise ClientExit("read args")
+ self.log("executing method %s"%(fname))
+ st = None
+ ret = None
+ try:
+ f=getattr(self,fname)
+ except AttributeError:
+ st = AttributeError("unknown method "+fname)
+ self.log("unknown method")
+
+ try:
+ ret = f(*args)
+ except Exception as e:
+ # due to a bug (in mod_python?), ServerException cannot be
+ # unpickled, so send the string and make the exception on the client side
+
+ #st=ServerException(
+ # "".join(traceback.format_tb(sys.exc_info()[2]))+
+ # str(e))
+ st="".join(traceback.format_tb(sys.exc_info()[2]))+str(e)
+ self.log("exception in method")
+ traceback.print_exc(50,self.logf)
+ self.logf.flush()
+
+ LOG.info("return")
+ try:
+ pickle.dump((st ,ret), self.fs, protocol=4)
+ except EOFError:
+ raise ClientExit("function return")
+
+ def exec_loop(self):
+ """ main execution loop. Loops and handles exit states"""
+
+ self.log("in exec_loop")
+ try:
+ while True:
+ self.one_function()
+ except ClientExit as e:
+ self.log("ClientExit %s"%e)
+ except socket.error as e:
+ self.log("socket error %s"%e)
+ traceback.print_exc(50,self.logf)
+ except EOFError:
+ self.log("EOF during communication")
+ traceback.print_exc(50,self.logf)
+ except BaseException:
+ # unexpected
+ traceback.print_exc(50,sys.stderr)
+ sys.exit(1)
+
+ LOG.info("exit sever")
+
+ def exec_loop_cleanup(self):
+ pass
+
+ ###################################################################
+ # spying stuff
+
+ def get_ps_stats(self):
+ ret=''
+ f=os.popen("echo ============ `hostname` uptime:; uptime;"+
+ "echo ============ self:; "+
+ "ps -p %d -o pid,vsize,rss,%%cpu,nlwp,psr; "%os.getpid()+
+ "echo ============ run queue:;"+
+ "ps ar -o user,pid,%cpu,%mem,ni,nlwp,psr,vsz,rss,cputime,command")
+ for l in f:
+ ret+=l
+ return ret
+
+class Client:
+ """
+ Methods of the server object can be called transparently. Exceptions are
+ re-raised.
+ """
+ def __init__(self, HOST, port=PORT, v6=False):
+ socktype = socket.AF_INET6 if v6 else socket.AF_INET
+
+ sock = socket.socket(socktype, socket.SOCK_STREAM)
+ LOG.info("connecting to %s:%d, socket type: %s", HOST, port, socktype)
+ sock.connect((HOST, port))
+ self.sock = sock
+ self.fs = FileSock(sock)
+
+ def generic_fun(self, fname, args):
+ # int "gen fun",fname
+ pickle.dump((fname, args), self.fs, protocol=4)
+ return self.get_result()
+
+ def get_result(self):
+ (st, ret) = RestrictedUnpickler(self.fs).load()
+ if st!=None:
+ raise ServerException(st)
+ else:
+ return ret
+
+ def __getattr__(self,name):
+ return lambda *x: self.generic_fun(name,x)
+
+
+def run_server(new_handler, port=PORT, report_to_file=None, v6=False):
+
+ HOST = '' # Symbolic name meaning the local host
+ socktype = socket.AF_INET6 if v6 else socket.AF_INET
+ s = socket.socket(socktype, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+
+ LOG.info("bind %s:%d", HOST, port)
+ s.bind((HOST, port))
+ s.listen(5)
+
+ LOG.info("accepting connections")
+ if report_to_file is not None:
+ LOG.info('storing host+port in %s', report_to_file)
+ open(report_to_file, 'w').write('%s:%d ' % (socket.gethostname(), port))
+
+ while True:
+ try:
+ conn, addr = s.accept()
+ except socket.error as e:
+ if e[1]=='Interrupted system call': continue
+ raise
+
+ LOG.info('Connected to %s', addr)
+
+ ibs = new_handler(conn)
+
+ tid = _thread.start_new_thread(ibs.exec_loop,())
+
+ LOG.debug("Thread ID: %d", tid)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/README.md b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/README.md
new file mode 100644
index 0000000..470d062
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/README.md
@@ -0,0 +1,6 @@
+# The Torch contrib
+
+This contrib directory contains a few Pytorch routines that
+are useful for similarity search. They do not necessarily depend on Faiss.
+
+The code is designed to work with CPU and GPU tensors.
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/__init__.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/clustering.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/clustering.py
new file mode 100644
index 0000000..8ff5cb2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/clustering.py
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This contrib module contains Pytorch code for k-means clustering
+"""
+import faiss
+import faiss.contrib.torch_utils
+import torch
+
+# the kmeans can produce both torch and numpy centroids
+from faiss.contrib.clustering import kmeans
+
+
+class DatasetAssign:
+ """Wrapper for a tensor that offers a function to assign the vectors
+ to centroids. All other implementations offer the same interface"""
+
+ def __init__(self, x):
+ self.x = x
+
+ def count(self):
+ return self.x.shape[0]
+
+ def dim(self):
+ return self.x.shape[1]
+
+ def get_subset(self, indices):
+ return self.x[indices]
+
+ def perform_search(self, centroids):
+ return faiss.knn(self.x, centroids, 1)
+
+ def assign_to(self, centroids, weights=None):
+ D, I = self.perform_search(centroids)
+
+ I = I.ravel()
+ D = D.ravel()
+ nc, d = centroids.shape
+
+ sum_per_centroid = torch.zeros_like(centroids)
+ if weights is None:
+ sum_per_centroid.index_add_(0, I, self.x)
+ else:
+ sum_per_centroid.index_add_(0, I, self.x * weights[:, None])
+
+ # the indices are still in numpy.
+ return I.cpu().numpy(), D, sum_per_centroid
+
+
+class DatasetAssignGPU(DatasetAssign):
+
+ def __init__(self, res, x):
+ DatasetAssign.__init__(self, x)
+ self.res = res
+
+ def perform_search(self, centroids):
+ return faiss.knn_gpu(self.res, self.x, centroids, 1)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/quantization.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/quantization.py
new file mode 100644
index 0000000..2ae6599
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch/quantization.py
@@ -0,0 +1,96 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This contrib module contains Pytorch code for quantization.
+"""
+
+import torch
+import faiss
+import math
+from faiss.contrib.torch import clustering
+# the kmeans can produce both torch and numpy centroids
+
+
+class Quantizer:
+
+ def __init__(self, d, code_size):
+ """
+ d: dimension of vectors
+ code_size: nb of bytes of the code (per vector)
+ """
+ self.d = d
+ self.code_size = code_size
+
+ def train(self, x):
+ """
+ takes a n-by-d array and peforms training
+ """
+ pass
+
+ def encode(self, x):
+ """
+ takes a n-by-d float array, encodes to an n-by-code_size uint8 array
+ """
+ pass
+
+ def decode(self, codes):
+ """
+ takes a n-by-code_size uint8 array, returns a n-by-d array
+ """
+ pass
+
+
+class VectorQuantizer(Quantizer):
+
+ def __init__(self, d, k):
+
+ code_size = int(math.ceil(torch.log2(k) / 8))
+ Quantizer.__init__(d, code_size)
+ self.k = k
+
+ def train(self, x):
+ pass
+
+
+class ProductQuantizer(Quantizer):
+ def __init__(self, d, M, nbits):
+ """ M: number of subvectors, d%M == 0
+ nbits: number of bits that each vector is encoded into
+ """
+ assert d % M == 0
+ assert nbits == 8 # todo: implement other nbits values
+ code_size = int(math.ceil(M * nbits / 8))
+ Quantizer.__init__(self, d, code_size)
+ self.M = M
+ self.nbits = nbits
+ self.code_size = code_size
+
+ def train(self, x):
+ nc = 2 ** self.nbits
+ sd = self.d // self.M
+ dev = x.device
+ dtype = x.dtype
+ self.codebook = torch.zeros((self.M, nc, sd), device=dev, dtype=dtype)
+ for m in range(self.M):
+ xsub = x[:, m * self.d // self.M: (m + 1) * self.d // self.M]
+ data = clustering.DatasetAssign(xsub.contiguous())
+ self.codebook[m] = clustering.kmeans(2 ** self.nbits, data)
+
+ def encode(self, x):
+ codes = torch.zeros((x.shape[0], self.code_size), dtype=torch.uint8)
+ for m in range(self.M):
+ xsub = x[:, m * self.d // self.M:(m + 1) * self.d // self.M]
+ _, I = faiss.knn(xsub.contiguous(), self.codebook[m], 1)
+ codes[:, m] = I.ravel()
+ return codes
+
+ def decode(self, codes):
+ idxs = [codes[:, m].long() for m in range(self.M)]
+ vectors = [self.codebook[m, idxs[m], :] for m in range(self.M)]
+ stacked_vectors = torch.stack(vectors, dim=1)
+ cbd = self.codebook.shape[-1]
+ x_rec = stacked_vectors.reshape(-1, cbd * self.M)
+ return x_rec
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/torch_utils.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch_utils.py
new file mode 100644
index 0000000..797c026
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/torch_utils.py
@@ -0,0 +1,764 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+
+This is a set of function wrappers that override the default numpy versions.
+
+Interoperability functions for pytorch and Faiss: Importing this will allow
+pytorch Tensors (CPU or GPU) to be used as arguments to Faiss indexes and
+other functions. Torch GPU tensors can only be used with Faiss GPU indexes.
+If this is imported with a package that supports Faiss GPU, the necessary
+stream synchronization with the current pytorch stream will be automatically
+performed.
+
+Numpy ndarrays can continue to be used in the Faiss python interface after
+importing this file. All arguments must be uniformly either numpy ndarrays
+or Torch tensors; no mixing is allowed.
+
+"""
+
+
+import faiss
+import torch
+import contextlib
+import inspect
+import sys
+import numpy as np
+
+##################################################################
+# Equivalent of swig_ptr for Torch tensors
+##################################################################
+
+def swig_ptr_from_UInt8Tensor(x):
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
+ assert x.is_contiguous()
+ assert x.dtype == torch.uint8
+ return faiss.cast_integer_to_uint8_ptr(
+ x.untyped_storage().data_ptr() + x.storage_offset())
+
+
+def swig_ptr_from_HalfTensor(x):
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
+ assert x.is_contiguous()
+ assert x.dtype == torch.float16
+ # no canonical half type in C/C++
+ return faiss.cast_integer_to_void_ptr(
+ x.untyped_storage().data_ptr() + x.storage_offset() * 2)
+
+
+def swig_ptr_from_FloatTensor(x):
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
+ assert x.is_contiguous()
+ assert x.dtype == torch.float32
+ return faiss.cast_integer_to_float_ptr(
+ x.untyped_storage().data_ptr() + x.storage_offset() * 4)
+
+def swig_ptr_from_BFloat16Tensor(x):
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
+ assert x.is_contiguous()
+ assert x.dtype == torch.bfloat16
+ return faiss.cast_integer_to_void_ptr(
+ x.untyped_storage().data_ptr() + x.storage_offset() * 2)
+
+
+def swig_ptr_from_IntTensor(x):
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
+ assert x.is_contiguous()
+ assert x.dtype == torch.int32, 'dtype=%s' % x.dtype
+ return faiss.cast_integer_to_int_ptr(
+ x.untyped_storage().data_ptr() + x.storage_offset() * 4)
+
+
+def swig_ptr_from_IndicesTensor(x):
+ """ gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
+ assert x.is_contiguous()
+ assert x.dtype == torch.int64, 'dtype=%s' % x.dtype
+ return faiss.cast_integer_to_idx_t_ptr(
+ x.untyped_storage().data_ptr() + x.storage_offset() * 8)
+
+##################################################################
+# utilities
+##################################################################
+
+def using_stream(res, pytorch_stream=None):
+ """ Creates a scoping object to make Faiss GPU use the same stream
+ as pytorch, based on torch.cuda.current_stream().
+ Or, a specific pytorch stream can be passed in as a second
+ argument, in which case we will use that stream.
+ """
+
+ if pytorch_stream is None:
+ pytorch_stream = torch.cuda.current_stream()
+
+ # This is the cudaStream_t that we wish to use
+ cuda_stream_s = faiss.cast_integer_to_cudastream_t(pytorch_stream.cuda_stream)
+
+ # So we can revert GpuResources stream state upon exit
+ prior_dev = torch.cuda.current_device()
+ prior_stream = res.getDefaultStream(torch.cuda.current_device())
+
+ res.setDefaultStream(torch.cuda.current_device(), cuda_stream_s)
+
+ # Do the user work
+ try:
+ yield
+ finally:
+ res.setDefaultStream(prior_dev, prior_stream)
+
+def torch_replace_method(the_class, name, replacement,
+ ignore_missing=False, ignore_no_base=False):
+ try:
+ orig_method = getattr(the_class, name)
+ except AttributeError:
+ if ignore_missing:
+ return
+ raise
+ if orig_method.__name__ == 'torch_replacement_' + name:
+ # replacement was done in parent class
+ return
+
+ # We should already have the numpy replacement methods patched
+ assert ignore_no_base or (orig_method.__name__ == 'replacement_' + name)
+ setattr(the_class, name + '_numpy', orig_method)
+ setattr(the_class, name, replacement)
+
+##################################################################
+# Setup wrappers
+##################################################################
+
+def handle_torch_Index(the_class):
+ def torch_replacement_add(self, x):
+ if type(x) is np.ndarray:
+ # forward to faiss __init__.py base method
+ return self.add_numpy(x)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.add_c(n, x_ptr)
+ else:
+ # CPU torch
+ self.add_c(n, x_ptr)
+
+ def torch_replacement_add_with_ids(self, x, ids):
+ if type(x) is np.ndarray:
+ # forward to faiss __init__.py base method
+ return self.add_with_ids_numpy(x, ids)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ assert type(ids) is torch.Tensor
+ assert ids.shape == (n, ), 'not same number of vectors as ids'
+ ids_ptr = swig_ptr_from_IndicesTensor(ids)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.add_with_ids_c(n, x_ptr, ids_ptr)
+ else:
+ # CPU torch
+ self.add_with_ids_c(n, x_ptr, ids_ptr)
+
+ def torch_replacement_assign(self, x, k, labels=None):
+ if type(x) is np.ndarray:
+ # forward to faiss __init__.py base method
+ return self.assign_numpy(x, k, labels)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if labels is None:
+ labels = torch.empty(n, k, device=x.device, dtype=torch.int64)
+ else:
+ assert type(labels) is torch.Tensor
+ assert labels.shape == (n, k)
+ L_ptr = swig_ptr_from_IndicesTensor(labels)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.assign_c(n, x_ptr, L_ptr, k)
+ else:
+ # CPU torch
+ self.assign_c(n, x_ptr, L_ptr, k)
+
+ return labels
+
+ def torch_replacement_train(self, x):
+ if type(x) is np.ndarray:
+ # forward to faiss __init__.py base method
+ return self.train_numpy(x)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.train_c(n, x_ptr)
+ else:
+ # CPU torch
+ self.train_c(n, x_ptr)
+
+ def search_methods_common(x, k, D, I):
+ n, d = x.shape
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if D is None:
+ D = torch.empty(n, k, device=x.device, dtype=torch.float32)
+ else:
+ assert type(D) is torch.Tensor
+ assert D.shape == (n, k)
+ D_ptr = swig_ptr_from_FloatTensor(D)
+
+ if I is None:
+ I = torch.empty(n, k, device=x.device, dtype=torch.int64)
+ else:
+ assert type(I) is torch.Tensor
+ assert I.shape == (n, k)
+ I_ptr = swig_ptr_from_IndicesTensor(I)
+
+ return x_ptr, D_ptr, I_ptr, D, I
+
+ def torch_replacement_search(self, x, k, D=None, I=None):
+ if type(x) is np.ndarray:
+ # forward to faiss __init__.py base method
+ return self.search_numpy(x, k, D=D, I=I)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+
+ x_ptr, D_ptr, I_ptr, D, I = search_methods_common(x, k, D, I)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.search_c(n, x_ptr, k, D_ptr, I_ptr)
+ else:
+ # CPU torch
+ self.search_c(n, x_ptr, k, D_ptr, I_ptr)
+
+ return D, I
+
+ def torch_replacement_search_and_reconstruct(self, x, k, D=None, I=None, R=None):
+ if type(x) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return self.search_and_reconstruct_numpy(x, k, D=D, I=I, R=R)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+
+ x_ptr, D_ptr, I_ptr, D, I = search_methods_common(x, k, D, I)
+
+ if R is None:
+ R = torch.empty(n, k, d, device=x.device, dtype=torch.float32)
+ else:
+ assert type(R) is torch.Tensor
+ assert R.shape == (n, k, d)
+ R_ptr = swig_ptr_from_FloatTensor(R)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.search_and_reconstruct_c(n, x_ptr, k, D_ptr, I_ptr, R_ptr)
+ else:
+ # CPU torch
+ self.search_and_reconstruct_c(n, x_ptr, k, D_ptr, I_ptr, R_ptr)
+
+ return D, I, R
+
+ def torch_replacement_search_preassigned(self, x, k, Iq, Dq, *, D=None, I=None):
+ if type(x) is np.ndarray:
+ # forward to faiss __init__.py base method
+ return self.search_preassigned_numpy(x, k, Iq, Dq, D=D, I=I)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+
+ x_ptr, D_ptr, I_ptr, D, I = search_methods_common(x, k, D, I)
+
+ assert Iq.shape == (n, self.nprobe)
+ Iq = Iq.contiguous()
+ Iq_ptr = swig_ptr_from_IndicesTensor(Iq)
+
+ if Dq is not None:
+ Dq = Dq.contiguous()
+ assert Dq.shape == Iq.shape
+ Dq_ptr = swig_ptr_from_FloatTensor(Dq)
+ else:
+ Dq_ptr = None
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.search_preassigned_c(n, x_ptr, k, Iq_ptr, Dq_ptr, D_ptr, I_ptr, False)
+ else:
+ # CPU torch
+ self.search_preassigned_c(n, x_ptr, k, Iq_ptr, Dq_ptr, D_ptr, I_ptr, False)
+
+ return D, I
+
+ def torch_replacement_remove_ids(self, x):
+ # Not yet implemented
+ assert type(x) is not torch.Tensor, 'remove_ids not yet implemented for torch'
+ return self.remove_ids_numpy(x)
+
+ def torch_replacement_reconstruct(self, key, x=None):
+ # No tensor inputs are required, but with importing this module, we
+ # assume that the default should be torch tensors. If we are passed a
+ # numpy array, however, assume that the user is overriding this default
+ if (x is not None) and (type(x) is np.ndarray):
+ # Forward to faiss __init__.py base method
+ return self.reconstruct_numpy(key, x)
+
+ # If the index is a CPU index, the default device is CPU, otherwise we
+ # produce a GPU tensor
+ device = torch.device('cpu')
+ if hasattr(self, 'getDevice'):
+ # same device as the index
+ device = torch.device('cuda', self.getDevice())
+
+ if x is None:
+ x = torch.empty(self.d, device=device, dtype=torch.float32)
+ else:
+ assert type(x) is torch.Tensor
+ assert x.shape == (self.d, )
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.reconstruct_c(key, x_ptr)
+ else:
+ # CPU torch
+ self.reconstruct_c(key, x_ptr)
+
+ return x
+
+ def torch_replacement_reconstruct_n(self, n0=0, ni=-1, x=None):
+ if ni == -1:
+ ni = self.ntotal
+
+ # No tensor inputs are required, but with importing this module, we
+ # assume that the default should be torch tensors. If we are passed a
+ # numpy array, however, assume that the user is overriding this default
+ if (x is not None) and (type(x) is np.ndarray):
+ # Forward to faiss __init__.py base method
+ return self.reconstruct_n_numpy(n0, ni, x)
+
+ # If the index is a CPU index, the default device is CPU, otherwise we
+ # produce a GPU tensor
+ device = torch.device('cpu')
+ if hasattr(self, 'getDevice'):
+ # same device as the index
+ device = torch.device('cuda', self.getDevice())
+
+ if x is None:
+ x = torch.empty(ni, self.d, device=device, dtype=torch.float32)
+ else:
+ assert type(x) is torch.Tensor
+ assert x.shape == (ni, self.d)
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.reconstruct_n_c(n0, ni, x_ptr)
+ else:
+ # CPU torch
+ self.reconstruct_n_c(n0, ni, x_ptr)
+
+ return x
+
+ def torch_replacement_update_vectors(self, keys, x):
+ if type(keys) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return self.update_vectors_numpy(keys, x)
+
+ assert type(keys) is torch.Tensor
+ (n, ) = keys.shape
+ keys_ptr = swig_ptr_from_IndicesTensor(keys)
+
+ assert type(x) is torch.Tensor
+ assert x.shape == (n, self.d)
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.update_vectors_c(n, keys_ptr, x_ptr)
+ else:
+ # CPU torch
+ self.update_vectors_c(n, keys_ptr, x_ptr)
+
+ # Until the GPU version is implemented, we do not support pre-allocated
+ # output buffers
+ def torch_replacement_range_search(self, x, thresh):
+ if type(x) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return self.range_search_numpy(x, thresh)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ assert not x.is_cuda, 'Range search using GPU tensor not yet implemented'
+ assert not hasattr(self, 'getDevice'), 'Range search on GPU index not yet implemented'
+
+ res = faiss.RangeSearchResult(n)
+ self.range_search_c(n, x_ptr, thresh, res)
+
+ # get pointers and copy them
+ # FIXME: no rev_swig_ptr equivalent for torch.Tensor, just convert
+ # np to torch
+ # NOTE: torch does not support np.uint64, just np.int64
+ lims = torch.from_numpy(faiss.rev_swig_ptr(res.lims, n + 1).copy().astype('int64'))
+ nd = int(lims[-1])
+ D = torch.from_numpy(faiss.rev_swig_ptr(res.distances, nd).copy())
+ I = torch.from_numpy(faiss.rev_swig_ptr(res.labels, nd).copy())
+
+ return lims, D, I
+
+ def torch_replacement_sa_encode(self, x, codes=None):
+ if type(x) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return self.sa_encode_numpy(x, codes)
+
+ assert type(x) is torch.Tensor
+ n, d = x.shape
+ assert d == self.d
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if codes is None:
+ codes = torch.empty(n, self.sa_code_size(), dtype=torch.uint8)
+ else:
+ assert codes.shape == (n, self.sa_code_size())
+ codes_ptr = swig_ptr_from_UInt8Tensor(codes)
+
+ if x.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.sa_encode_c(n, x_ptr, codes_ptr)
+ else:
+ # CPU torch
+ self.sa_encode_c(n, x_ptr, codes_ptr)
+
+ return codes
+
+ def torch_replacement_sa_decode(self, codes, x=None):
+ if type(codes) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return self.sa_decode_numpy(codes, x)
+
+ assert type(codes) is torch.Tensor
+ n, cs = codes.shape
+ assert cs == self.sa_code_size()
+ codes_ptr = swig_ptr_from_UInt8Tensor(codes)
+
+ if x is None:
+ x = torch.empty(n, self.d, dtype=torch.float32)
+ else:
+ assert type(x) is torch.Tensor
+ assert x.shape == (n, self.d)
+ x_ptr = swig_ptr_from_FloatTensor(x)
+
+ if codes.is_cuda:
+ assert hasattr(self, 'getDevice'), 'GPU tensor on CPU index not allowed'
+
+ # On the GPU, use proper stream ordering
+ with using_stream(self.getResources()):
+ self.sa_decode_c(n, codes_ptr, x_ptr)
+ else:
+ # CPU torch
+ self.sa_decode_c(n, codes_ptr, x_ptr)
+
+ return x
+
+
+ torch_replace_method(the_class, 'add', torch_replacement_add)
+ torch_replace_method(the_class, 'add_with_ids', torch_replacement_add_with_ids)
+ torch_replace_method(the_class, 'assign', torch_replacement_assign)
+ torch_replace_method(the_class, 'train', torch_replacement_train)
+ torch_replace_method(the_class, 'search', torch_replacement_search)
+ torch_replace_method(the_class, 'remove_ids', torch_replacement_remove_ids)
+ torch_replace_method(the_class, 'reconstruct', torch_replacement_reconstruct)
+ torch_replace_method(the_class, 'reconstruct_n', torch_replacement_reconstruct_n)
+ torch_replace_method(the_class, 'range_search', torch_replacement_range_search)
+ torch_replace_method(the_class, 'update_vectors', torch_replacement_update_vectors,
+ ignore_missing=True)
+ torch_replace_method(the_class, 'search_and_reconstruct',
+ torch_replacement_search_and_reconstruct, ignore_missing=True)
+ torch_replace_method(the_class, 'search_preassigned',
+ torch_replacement_search_preassigned, ignore_missing=True)
+ torch_replace_method(the_class, 'sa_encode', torch_replacement_sa_encode)
+ torch_replace_method(the_class, 'sa_decode', torch_replacement_sa_decode)
+
+faiss_module = sys.modules['faiss']
+
+# Re-patch anything that inherits from faiss.Index to add the torch bindings
+for symbol in dir(faiss_module):
+ obj = getattr(faiss_module, symbol)
+ if inspect.isclass(obj):
+ the_class = obj
+ if issubclass(the_class, faiss.Index):
+ handle_torch_Index(the_class)
+
+
+# allows torch tensor usage with knn
+def torch_replacement_knn(xq, xb, k, metric=faiss.METRIC_L2, metric_arg=0):
+ if type(xb) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return faiss.knn_numpy(xq, xb, k, metric=metric, metric_arg=metric_arg)
+
+ nb, d = xb.size()
+ assert xb.is_contiguous()
+ assert xb.dtype == torch.float32
+ assert not xb.is_cuda, "use knn_gpu for GPU tensors"
+
+ nq, d2 = xq.size()
+ assert d2 == d
+ assert xq.is_contiguous()
+ assert xq.dtype == torch.float32
+ assert not xq.is_cuda, "use knn_gpu for GPU tensors"
+
+ D = torch.empty(nq, k, device=xb.device, dtype=torch.float32)
+ I = torch.empty(nq, k, device=xb.device, dtype=torch.int64)
+ I_ptr = swig_ptr_from_IndicesTensor(I)
+ D_ptr = swig_ptr_from_FloatTensor(D)
+ xb_ptr = swig_ptr_from_FloatTensor(xb)
+ xq_ptr = swig_ptr_from_FloatTensor(xq)
+
+ if metric == faiss.METRIC_L2:
+ faiss.knn_L2sqr(
+ xq_ptr, xb_ptr,
+ d, nq, nb, k, D_ptr, I_ptr
+ )
+ elif metric == faiss.METRIC_INNER_PRODUCT:
+ faiss.knn_inner_product(
+ xq_ptr, xb_ptr,
+ d, nq, nb, k, D_ptr, I_ptr
+ )
+ else:
+ faiss.knn_extra_metrics(
+ xq_ptr, xb_ptr,
+ d, nq, nb, metric, metric_arg, k, D_ptr, I_ptr
+ )
+
+ return D, I
+
+
+torch_replace_method(faiss_module, 'knn', torch_replacement_knn, True, True)
+
+
+# allows torch tensor usage with bfKnn
+def torch_replacement_knn_gpu(res, xq, xb, k, D=None, I=None, metric=faiss.METRIC_L2, device=-1, use_cuvs=False):
+ if type(xb) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return faiss.knn_gpu_numpy(res, xq, xb, k, D, I, metric, device)
+
+ nb, d = xb.size()
+ if xb.is_contiguous():
+ xb_row_major = True
+ elif xb.t().is_contiguous():
+ xb = xb.t()
+ xb_row_major = False
+ else:
+ raise TypeError('matrix should be row or column-major')
+
+ if xb.dtype == torch.float32:
+ xb_type = faiss.DistanceDataType_F32
+ xb_ptr = swig_ptr_from_FloatTensor(xb)
+ elif xb.dtype == torch.float16:
+ xb_type = faiss.DistanceDataType_F16
+ xb_ptr = swig_ptr_from_HalfTensor(xb)
+ elif xb.dtype == torch.bfloat16:
+ xb_type = faiss.DistanceDataType_BF16
+ xb_ptr = swig_ptr_from_BFloat16Tensor(xb)
+ else:
+ raise TypeError('xq must be float32, float16 or bfloat16')
+
+ nq, d2 = xq.size()
+ assert d2 == d
+ if xq.is_contiguous():
+ xq_row_major = True
+ elif xq.t().is_contiguous():
+ xq = xq.t()
+ xq_row_major = False
+ else:
+ raise TypeError('matrix should be row or column-major')
+
+ if xq.dtype == torch.float32:
+ xq_type = faiss.DistanceDataType_F32
+ xq_ptr = swig_ptr_from_FloatTensor(xq)
+ elif xq.dtype == torch.float16:
+ xq_type = faiss.DistanceDataType_F16
+ xq_ptr = swig_ptr_from_HalfTensor(xq)
+ elif xq.dtype == torch.bfloat16:
+ xq_type = faiss.DistanceDataType_BF16
+ xq_ptr = swig_ptr_from_BFloat16Tensor(xq)
+ else:
+ raise TypeError('xq must be float32, float16 or bfloat16')
+
+ if D is None:
+ D = torch.empty(nq, k, device=xb.device, dtype=torch.float32)
+ else:
+ assert D.shape == (nq, k)
+ # interface takes void*, we need to check this
+ assert (D.dtype == torch.float32)
+
+ if I is None:
+ I = torch.empty(nq, k, device=xb.device, dtype=torch.int64)
+ else:
+ assert I.shape == (nq, k)
+
+ if I.dtype == torch.int64:
+ I_type = faiss.IndicesDataType_I64
+ I_ptr = swig_ptr_from_IndicesTensor(I)
+ elif I.dtype == I.dtype == torch.int32:
+ I_type = faiss.IndicesDataType_I32
+ I_ptr = swig_ptr_from_IntTensor(I)
+ else:
+ raise TypeError('I must be i64 or i32')
+
+ D_ptr = swig_ptr_from_FloatTensor(D)
+
+ args = faiss.GpuDistanceParams()
+ args.metric = metric
+ args.k = k
+ args.dims = d
+ args.vectors = xb_ptr
+ args.vectorsRowMajor = xb_row_major
+ args.vectorType = xb_type
+ args.numVectors = nb
+ args.queries = xq_ptr
+ args.queriesRowMajor = xq_row_major
+ args.queryType = xq_type
+ args.numQueries = nq
+ args.outDistances = D_ptr
+ args.outIndices = I_ptr
+ args.outIndicesType = I_type
+ args.device = device
+ args.use_cuvs = use_cuvs
+
+ with using_stream(res):
+ faiss.bfKnn(res, args)
+
+ return D, I
+
+torch_replace_method(faiss_module, 'knn_gpu', torch_replacement_knn_gpu, True, True)
+
+# allows torch tensor usage with bfKnn for all pairwise distances
+def torch_replacement_pairwise_distance_gpu(res, xq, xb, D=None, metric=faiss.METRIC_L2, device=-1):
+ if type(xb) is np.ndarray:
+ # Forward to faiss __init__.py base method
+ return faiss.pairwise_distance_gpu_numpy(res, xq, xb, D, metric)
+
+ nb, d = xb.size()
+ if xb.is_contiguous():
+ xb_row_major = True
+ elif xb.t().is_contiguous():
+ xb = xb.t()
+ xb_row_major = False
+ else:
+ raise TypeError('xb matrix should be row or column-major')
+
+ if xb.dtype == torch.float32:
+ xb_type = faiss.DistanceDataType_F32
+ xb_ptr = swig_ptr_from_FloatTensor(xb)
+ elif xb.dtype == torch.float16:
+ xb_type = faiss.DistanceDataType_F16
+ xb_ptr = swig_ptr_from_HalfTensor(xb)
+ else:
+ raise TypeError('xb must be float32 or float16')
+
+ nq, d2 = xq.size()
+ assert d2 == d
+ if xq.is_contiguous():
+ xq_row_major = True
+ elif xq.t().is_contiguous():
+ xq = xq.t()
+ xq_row_major = False
+ else:
+ raise TypeError('xq matrix should be row or column-major')
+
+ if xq.dtype == torch.float32:
+ xq_type = faiss.DistanceDataType_F32
+ xq_ptr = swig_ptr_from_FloatTensor(xq)
+ elif xq.dtype == torch.float16:
+ xq_type = faiss.DistanceDataType_F16
+ xq_ptr = swig_ptr_from_HalfTensor(xq)
+ else:
+ raise TypeError('xq must be float32 or float16')
+
+ if D is None:
+ D = torch.empty(nq, nb, device=xb.device, dtype=torch.float32)
+ else:
+ assert D.shape == (nq, nb)
+ # interface takes void*, we need to check this
+ assert (D.dtype == torch.float32)
+
+ D_ptr = swig_ptr_from_FloatTensor(D)
+
+ args = faiss.GpuDistanceParams()
+ args.metric = metric
+ args.k = -1 # selects all pairwise distance
+ args.dims = d
+ args.vectors = xb_ptr
+ args.vectorsRowMajor = xb_row_major
+ args.vectorType = xb_type
+ args.numVectors = nb
+ args.queries = xq_ptr
+ args.queriesRowMajor = xq_row_major
+ args.queryType = xq_type
+ args.numQueries = nq
+ args.outDistances = D_ptr
+ args.device = device
+
+ with using_stream(res):
+ faiss.bfKnn(res, args)
+
+ return D
+
+torch_replace_method(faiss_module, 'pairwise_distance_gpu', torch_replacement_pairwise_distance_gpu, True, True)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/contrib/vecs_io.py b/packages/leann-backend-hnsw/third_party/faiss/contrib/vecs_io.py
new file mode 100644
index 0000000..f130645
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/contrib/vecs_io.py
@@ -0,0 +1,60 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import sys
+import numpy as np
+
+"""
+I/O functions in fvecs, bvecs, ivecs formats
+definition of the formats here: http://corpus-texmex.irisa.fr/
+"""
+
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype='int32')
+ if sys.byteorder == 'big':
+ a.byteswap(inplace=True)
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+def ivecs_mmap(fname):
+ assert sys.byteorder != 'big'
+ a = np.memmap(fname, dtype='int32', mode='r')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:]
+
+
+def fvecs_mmap(fname):
+ return ivecs_mmap(fname).view('float32')
+
+
+def bvecs_mmap(fname):
+ x = np.memmap(fname, dtype='uint8', mode='r')
+ if sys.byteorder == 'big':
+ da = x[:4][::-1].copy()
+ d = da.view('int32')[0]
+ else:
+ d = x[:4].view('int32')[0]
+ return x.reshape(-1, d + 4)[:, 4:]
+
+
+def ivecs_write(fname, m):
+ n, d = m.shape
+ m1 = np.empty((n, d + 1), dtype='int32')
+ m1[:, 0] = d
+ m1[:, 1:] = m
+ if sys.byteorder == 'big':
+ m1.byteswap(inplace=True)
+ m1.tofile(fname)
+
+
+def fvecs_write(fname, m):
+ m = m.astype('float32')
+ ivecs_write(fname, m.view('int32'))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/H_hnsw_performance_comparison.png b/packages/leann-backend-hnsw/third_party/faiss/demo/H_hnsw_performance_comparison.png
new file mode 100644
index 0000000..25feddc
Binary files /dev/null and b/packages/leann-backend-hnsw/third_party/faiss/demo/H_hnsw_performance_comparison.png differ
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/H_hnsw_recall_comparison.png b/packages/leann-backend-hnsw/third_party/faiss/demo/H_hnsw_recall_comparison.png
new file mode 100644
index 0000000..dd5c7ff
Binary files /dev/null and b/packages/leann-backend-hnsw/third_party/faiss/demo/H_hnsw_recall_comparison.png differ
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/build_demo.py b/packages/leann-backend-hnsw/third_party/faiss/demo/build_demo.py
new file mode 100644
index 0000000..3490fa8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/build_demo.py
@@ -0,0 +1,67 @@
+import os
+import pickle
+import faiss
+import numpy as np
+import time
+
+EMBEDDING_FILE = "/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/passages_00.pkl"
+INDEX_OUTPUT_DIR = "/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw" # 保存索引的目录
+M_VALUES_FOR_L2 = [30, 60] # M values for L2
+EF_CONSTRUCTION_FOR_L2 = 128 # fixed efConstruction
+
+if not os.path.exists(INDEX_OUTPUT_DIR):
+ print(f"Creating index directory: {INDEX_OUTPUT_DIR}")
+ os.makedirs(INDEX_OUTPUT_DIR)
+
+print(f"Loading embeddings from {EMBEDDING_FILE}...")
+with open(EMBEDDING_FILE, 'rb') as f:
+ data = pickle.load(f)
+# Directly assume data is a tuple and the second element is embeddings
+embeddings = data[1]
+
+print(f"Converting embeddings from {embeddings.dtype} to float32.")
+embeddings = embeddings.astype(np.float32)
+print(f"Loaded embeddings, shape: {embeddings.shape}")
+dim = embeddings.shape[1]
+
+# --- Build HNSW L2 index ---
+print("\n--- Build HNSW L2 index ---")
+
+# Loop through M values
+for HNSW_M in M_VALUES_FOR_L2:
+ efConstruction = EF_CONSTRUCTION_FOR_L2
+
+ print(f"\nBuilding HNSW L2 index: M={HNSW_M}, efConstruction={efConstruction}...")
+
+ # Define the filename and path for the L2 index
+ hnsw_filename = f"hnsw_IP_M{HNSW_M}_efC{efConstruction}.index"
+ hnsw_filepath = os.path.join(INDEX_OUTPUT_DIR, hnsw_filename)
+
+ # Note: No longer check if the file exists, it will be overwritten if it exists
+
+ # Create HNSW L2 index
+ index_hnsw = faiss.IndexHNSWFlat(dim, HNSW_M, faiss.METRIC_INNER_PRODUCT)
+ index_hnsw.hnsw.efConstruction = efConstruction
+
+ index_hnsw.verbose = True
+
+ print(f"Adding {embeddings.shape[0]} vectors to HNSW L2 (M={HNSW_M}) index...")
+ start_time_build = time.time()
+
+ index_hnsw.add(embeddings)
+
+ end_time_build = time.time()
+ build_time_s = end_time_build - start_time_build
+ print(f"HNSW L2 build time: {build_time_s:.4f} seconds")
+
+ # Save L2 index (direct operation, no try-except)
+ print(f"Saving HNSW L2 index to {hnsw_filepath}")
+ faiss.write_index(index_hnsw, hnsw_filepath)
+ # Do not check storage size or handle save errors
+
+ print(f"Index {hnsw_filename} saved.")
+
+ del index_hnsw
+
+print("\n--- HNSW L2 index build completed ---")
+print("\nScript ended.")
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/build_demo_sample.py b/packages/leann-backend-hnsw/third_party/faiss/demo/build_demo_sample.py
new file mode 100644
index 0000000..0b50baf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/build_demo_sample.py
@@ -0,0 +1,250 @@
+import os
+import pickle
+import numpy as np
+import time
+import math
+from pathlib import Path
+
+# --- Configuration ---
+DOMAIN_NAME = "rpj_wiki" # Domain name used for finding passages
+EMBEDDER_NAME = "facebook/contriever-msmarco" # Used in paths
+ORIGINAL_EMBEDDING_SHARD_ID = 0 # The shard ID of the embedding file we are loading
+
+# Define the base directory
+SCALING_OUT_DIR = Path("/powerrag/scaling_out").resolve()
+
+# Original Data Paths (using functions similar to your utils)
+# Assuming embeddings for rpj_wiki are in a single file despite passage sharding
+# Adjust NUM_SHARDS_EMBEDDING if embeddings are also sharded
+NUM_SHARDS_EMBEDDING = 1
+ORIGINAL_EMBEDDING_FILE_TEMPLATE = (
+ SCALING_OUT_DIR
+ / "embeddings/{embedder_name}/{domain_name}/{total_shards}-shards/passages_{shard_id:02d}.pkl"
+)
+ORIGINAL_EMBEDDING_FILE = str(ORIGINAL_EMBEDDING_FILE_TEMPLATE).format(
+ embedder_name=EMBEDDER_NAME,
+ domain_name=DOMAIN_NAME,
+ total_shards=NUM_SHARDS_EMBEDDING,
+ shard_id=ORIGINAL_EMBEDDING_SHARD_ID,
+)
+
+# Passage Paths
+NUM_SHARDS_PASSAGE = 8 # As specified in your original utils (NUM_SHARDS['rpj_wiki'])
+ORIGINAL_PASSAGE_FILE_TEMPLATE = (
+ SCALING_OUT_DIR
+ / "passages/{domain_name}/{total_shards}-shards/raw_passages-{shard_id}-of-{total_shards}.pkl"
+)
+
+# New identifier for the sampled dataset
+NEW_DATASET_NAME = "rpj_wiki_1M"
+
+# Fraction to sample (1/60)
+SAMPLE_FRACTION = 1 / 60
+
+# Output Paths for the new sampled dataset
+OUTPUT_EMBEDDING_DIR = SCALING_OUT_DIR / "embeddings" / EMBEDDER_NAME / NEW_DATASET_NAME / "1-shards"
+OUTPUT_PASSAGE_DIR = SCALING_OUT_DIR / "passages" / NEW_DATASET_NAME / "1-shards"
+
+OUTPUT_EMBEDDING_FILE = OUTPUT_EMBEDDING_DIR / f"passages_{ORIGINAL_EMBEDDING_SHARD_ID:02d}.pkl"
+# The new passage file represents the *single* shard of the sampled data
+OUTPUT_PASSAGE_FILE = OUTPUT_PASSAGE_DIR / f"raw_passages-0-of-1.pkl"
+
+# --- Directory Setup ---
+print("Creating output directories if they don't exist...")
+OUTPUT_EMBEDDING_DIR.mkdir(parents=True, exist_ok=True)
+OUTPUT_PASSAGE_DIR.mkdir(parents=True, exist_ok=True)
+print(f"Embeddings output dir: {OUTPUT_EMBEDDING_DIR}")
+print(f"Passages output dir: {OUTPUT_PASSAGE_DIR}")
+
+
+# --- Helper Function to Load Passages ---
+def load_all_passages(domain_name, num_shards, template):
+ """Loads all passage shards and creates an ID-to-content map."""
+ all_passages_list = []
+ passage_id_to_content_map = {}
+ print(f"Loading passages for domain '{domain_name}' from {num_shards} shards...")
+ total_loaded = 0
+ start_time = time.time()
+
+ for shard_id in range(num_shards):
+ shard_path_str = str(template).format(
+ domain_name=domain_name,
+ total_shards=num_shards,
+ shard_id=shard_id,
+ )
+ shard_path = Path(shard_path_str)
+
+ if not shard_path.exists():
+ print(f"Warning: Passage shard file not found, skipping: {shard_path}")
+ continue
+
+ try:
+ print(f" Loading shard {shard_id} from {shard_path}...")
+ with open(shard_path, 'rb') as f:
+ shard_passages = pickle.load(f) # Expected: list of dicts
+ if not isinstance(shard_passages, list):
+ print(f"Warning: Shard {shard_id} data is not a list.")
+ continue
+
+ all_passages_list.extend(shard_passages)
+ # Build the map, ensuring IDs are strings for consistent lookup
+ for passage_dict in shard_passages:
+ if 'id' in passage_dict:
+ passage_id_to_content_map[str(passage_dict['id'])] = passage_dict
+ else:
+ print(f"Warning: Passage dict in shard {shard_id} missing 'id' key.")
+ print(f" Loaded {len(shard_passages)} passages from shard {shard_id}.")
+ total_loaded += len(shard_passages)
+
+ except Exception as e:
+ print(f"Error loading passage shard {shard_id} from {shard_path}: {e}")
+
+ load_time = time.time() - start_time
+ print(f"Finished loading passages. Total passages loaded: {total_loaded} in {load_time:.2f} seconds.")
+ print(f"Total unique passages mapped by ID: {len(passage_id_to_content_map)}")
+ return all_passages_list, passage_id_to_content_map
+
+
+# --- Load Original Embeddings ---
+print(f"\nLoading original embeddings from {ORIGINAL_EMBEDDING_FILE}...")
+start_load_time = time.time()
+try:
+ with open(ORIGINAL_EMBEDDING_FILE, 'rb') as f:
+ original_embedding_data = pickle.load(f)
+except FileNotFoundError:
+ print(f"Error: Original embedding file not found at {ORIGINAL_EMBEDDING_FILE}")
+ exit(1)
+except Exception as e:
+ print(f"Error loading embedding pickle file: {e}")
+ exit(1)
+load_time = time.time() - start_load_time
+print(f"Loaded original embeddings data in {load_time:.2f} seconds.")
+
+# --- Extract and Validate Embeddings ---
+try:
+ if not isinstance(original_embedding_data, (list, tuple)) or len(original_embedding_data) != 2:
+ raise TypeError("Expected embedding data to be a list or tuple of length 2 (ids, embeddings)")
+
+ original_embedding_ids = original_embedding_data[0] # Should be a list/iterable of IDs
+ original_embeddings = original_embedding_data[1] # Should be a NumPy array
+
+ # Ensure IDs are in a list for easier indexing later if they aren't already
+ if not isinstance(original_embedding_ids, list):
+ print("Converting embedding IDs to list...")
+ original_embedding_ids = list(original_embedding_ids)
+
+ if not isinstance(original_embeddings, np.ndarray):
+ raise TypeError("Expected second element of embedding data to be a NumPy array")
+
+ print(f"Original data contains {len(original_embedding_ids)} embedding IDs.")
+ print(f"Original embeddings shape: {original_embeddings.shape}, dtype: {original_embeddings.dtype}")
+
+ if len(original_embedding_ids) != original_embeddings.shape[0]:
+ raise ValueError(f"Mismatch! Number of embedding IDs ({len(original_embedding_ids)}) does not match number of embeddings ({original_embeddings.shape[0]})")
+
+except (TypeError, ValueError, IndexError) as e:
+ print(f"Error processing loaded embedding data: {e}")
+ print("Please ensure the embedding pickle file contains: (list_of_passage_ids, numpy_embedding_array)")
+ exit(1)
+
+total_embeddings = original_embeddings.shape[0]
+
+# --- Load Original Passages ---
+# This might take time and memory depending on the dataset size
+_, passage_id_to_content_map = load_all_passages(
+ DOMAIN_NAME, NUM_SHARDS_PASSAGE, ORIGINAL_PASSAGE_FILE_TEMPLATE
+)
+
+if not passage_id_to_content_map:
+ print("Error: No passages were loaded. Cannot proceed with sampling.")
+ exit(1)
+
+# --- Calculate Sample Size ---
+num_samples = math.ceil(total_embeddings * SAMPLE_FRACTION) # Use ceil to get at least 1/60th
+print(f"\nTotal original embeddings: {total_embeddings}")
+print(f"Sampling fraction: {SAMPLE_FRACTION:.6f} (1/60)")
+print(f"Target number of samples: {num_samples}")
+
+if num_samples > total_embeddings:
+ print("Warning: Calculated sample size exceeds total embeddings. Using all embeddings.")
+ num_samples = total_embeddings
+elif num_samples <= 0:
+ print("Error: Calculated sample size is zero or negative.")
+ exit(1)
+
+# --- Perform Random Sampling (Based on Embeddings) ---
+print("\nPerforming random sampling based on embeddings...")
+start_sample_time = time.time()
+
+# Set a seed for reproducibility if needed
+# np.random.seed(42)
+
+# Generate unique random indices from the embeddings list
+sampled_indices = np.random.choice(total_embeddings, size=num_samples, replace=False)
+
+# Retrieve the corresponding IDs and embeddings using the sampled indices
+sampled_embedding_ids = [original_embedding_ids[i] for i in sampled_indices]
+sampled_embeddings = original_embeddings[sampled_indices]
+
+sample_time = time.time() - start_sample_time
+print(f"Sampling completed in {sample_time:.2f} seconds.")
+print(f"Sampled {len(sampled_embedding_ids)} IDs and embeddings.")
+print(f"Sampled embeddings shape: {sampled_embeddings.shape}")
+
+# --- Retrieve Corresponding Passages ---
+print("\nRetrieving corresponding passages for sampled IDs...")
+start_passage_retrieval_time = time.time()
+sampled_passages = []
+missing_ids_count = 0
+for i, pid in enumerate(sampled_embedding_ids):
+ # Convert pid to string for lookup in the map
+ pid_str = str(pid)
+ if pid_str in passage_id_to_content_map:
+ sampled_passages.append(passage_id_to_content_map[pid_str])
+ else:
+ # This indicates an inconsistency between embedding IDs and passage IDs
+ print(f"Warning: Passage ID '{pid_str}' (from embedding index {sampled_indices[i]}) not found in passage map.")
+ missing_ids_count += 1
+
+passage_retrieval_time = time.time() - start_passage_retrieval_time
+print(f"Retrieved {len(sampled_passages)} passages in {passage_retrieval_time:.2f} seconds.")
+if missing_ids_count > 0:
+ print(f"Warning: Could not find passages for {missing_ids_count} sampled IDs.")
+
+if not sampled_passages:
+ print("Error: No corresponding passages found for the sampled embeddings. Check ID matching.")
+ exit(1)
+
+# --- Prepare Output Data ---
+# Embeddings output format: tuple(list_of_ids, numpy_array_of_embeddings)
+output_embedding_data = (sampled_embedding_ids, sampled_embeddings)
+# Passages output format: list[dict] (matching input shard format)
+output_passage_data = sampled_passages
+
+# --- Save Sampled Embeddings ---
+print(f"\nSaving sampled embeddings to {OUTPUT_EMBEDDING_FILE}...")
+start_save_time = time.time()
+try:
+ with open(OUTPUT_EMBEDDING_FILE, 'wb') as f:
+ pickle.dump(output_embedding_data, f, protocol=pickle.HIGHEST_PROTOCOL)
+except Exception as e:
+ print(f"Error saving sampled embeddings: {e}")
+ # Continue to try saving passages if desired, or exit(1)
+save_time = time.time() - start_save_time
+print(f"Saved sampled embeddings in {save_time:.2f} seconds.")
+
+# --- Save Sampled Passages ---
+print(f"\nSaving sampled passages to {OUTPUT_PASSAGE_FILE}...")
+start_save_time = time.time()
+try:
+ with open(OUTPUT_PASSAGE_FILE, 'wb') as f:
+ pickle.dump(output_passage_data, f, protocol=pickle.HIGHEST_PROTOCOL)
+except Exception as e:
+ print(f"Error saving sampled passages: {e}")
+ exit(1)
+save_time = time.time() - start_save_time
+print(f"Saved sampled passages in {save_time:.2f} seconds.")
+
+print(f"\nScript finished successfully.")
+print(f"Sampled embeddings saved to: {OUTPUT_EMBEDDING_FILE}")
+print(f"Sampled passages saved to: {OUTPUT_PASSAGE_FILE}")
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/hnsw_performance_comparison.png b/packages/leann-backend-hnsw/third_party/faiss/demo/hnsw_performance_comparison.png
new file mode 100644
index 0000000..bd2a42c
Binary files /dev/null and b/packages/leann-backend-hnsw/third_party/faiss/demo/hnsw_performance_comparison.png differ
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/hnsw_recall_comparison.png b/packages/leann-backend-hnsw/third_party/faiss/demo/hnsw_recall_comparison.png
new file mode 100644
index 0000000..7c31c40
Binary files /dev/null and b/packages/leann-backend-hnsw/third_party/faiss/demo/hnsw_recall_comparison.png differ
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/large_graph_simple_build.py b/packages/leann-backend-hnsw/third_party/faiss/demo/large_graph_simple_build.py
new file mode 100644
index 0000000..8a0636c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/large_graph_simple_build.py
@@ -0,0 +1,354 @@
+import argparse
+import sys
+import time
+
+import faiss
+import numpy as np
+import pickle
+import os
+import json
+import time
+import torch
+from tqdm import tqdm
+from pathlib import Path
+import subprocess
+
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
+sys.path.append(os.path.join(project_root, "demo"))
+from config import SCALING_OUT_DIR, get_example_path, TASK_CONFIGS
+sys.path.append(project_root)
+from contriever.src.contriever import Contriever, load_retriever
+
+M = 32
+efConstruction = 256
+K_NEIGHBORS = 3
+
+DB_EMBEDDING_FILE = "/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/passages_00.pkl"
+INDEX_SAVING_FILE = "/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/indices"
+TASK_NAME = "nq"
+EMBEDDER_MODEL_NAME = "facebook/contriever-msmarco"
+MAX_QUERIES_TO_LOAD = 1000
+QUERY_ENCODING_BATCH_SIZE = 64
+
+# 1M samples
+print(f"Loading embeddings from {DB_EMBEDDING_FILE}...")
+with open(DB_EMBEDDING_FILE, 'rb') as f:
+ data = pickle.load(f)
+
+xb = data[1]
+print(f"Original dtype: {xb.dtype}")
+
+if xb.dtype != np.float32:
+ print("Converting embeddings to float32.")
+ xb = xb.astype(np.float32)
+else:
+ print("Embeddings are already float32.")
+print(f"Loaded database embeddings (xb), shape: {xb.shape}")
+d = xb.shape[1] # Get dimension
+
+query_file_path = TASK_CONFIGS[TASK_NAME].query_path
+print(f"Using query path from TASK_CONFIGS: {query_file_path}")
+
+query_texts = []
+print(f"Reading queries from: {query_file_path}")
+with open(query_file_path, 'r') as f:
+ for i, line in enumerate(f):
+ if i >= MAX_QUERIES_TO_LOAD:
+ print(f"Stopped loading queries at limit: {MAX_QUERIES_TO_LOAD}")
+ break
+ record = json.loads(line)
+ query_texts.append(record["query"])
+print(f"Loaded {len(query_texts)} query texts.")
+
+print("\nInitializing retriever model for encoding queries...")
+device = "cuda" if torch.cuda.is_available() else "cpu"
+print(f"Using device: {device}")
+model, tokenizer, _ = load_retriever(EMBEDDER_MODEL_NAME)
+model.to(device)
+model.eval() # Set to evaluation mode
+print("Retriever model loaded.")
+
+
+def embed_queries(queries, model, tokenizer, model_name_or_path, per_gpu_batch_size=64):
+ """Embed queries using the model with batching"""
+ model = model.half()
+ model.eval()
+ embeddings = []
+ batch_question = []
+
+ with torch.no_grad():
+ for k, query in tqdm(enumerate(queries), desc="Encoding queries"):
+ batch_question.append(query)
+
+ # Process when batch is full or at the end
+ if len(batch_question) == per_gpu_batch_size or k == len(queries) - 1:
+ encoded_batch = tokenizer.batch_encode_plus(
+ batch_question,
+ return_tensors="pt",
+ max_length=512,
+ padding=True,
+ truncation=True,
+ )
+
+ encoded_batch = {k: v.to(device) for k, v in encoded_batch.items()}
+ output = model(**encoded_batch)
+
+ # Contriever typically uses output.last_hidden_state pooling or something specialized
+ if "contriever" not in model_name_or_path:
+ output = output.last_hidden_state[:, 0, :]
+
+ embeddings.append(output.cpu())
+ batch_question = [] # Reset batch
+
+ embeddings = torch.cat(embeddings, dim=0).numpy()
+ print(f"Query embeddings shape: {embeddings.shape}")
+ return embeddings
+
+print(f"\nEncoding {len(query_texts)} queries (batch size: {QUERY_ENCODING_BATCH_SIZE})...")
+xq_full = embed_queries(query_texts, model, tokenizer, EMBEDDER_MODEL_NAME, per_gpu_batch_size=QUERY_ENCODING_BATCH_SIZE)
+
+# Ensure float32 for Faiss compatibility after encoding
+if xq_full.dtype != np.float32:
+ print(f"Converting encoded queries from {xq_full.dtype} to float32.")
+ xq_full = xq_full.astype(np.float32)
+
+print(f"Encoded queries (xq_full), shape: {xq_full.shape}, dtype: {xq_full.dtype}")
+
+# Check dimension consistency
+if xq_full.shape[1] != d:
+ raise ValueError(f"Query embedding dimension ({xq_full.shape[1]}) does not match database dimension ({d})")
+
+# loading index_flat from cache
+cache_file = f"/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/flat_results_nq_k3.json"
+
+recall_idx_flat = None
+if os.path.exists(cache_file):
+ print(f"Loading cached FLAT index results from {cache_file}...")
+ start_time = time.time()
+ with open(cache_file, 'r') as f:
+ cached_results = json.load(f)
+ D_flat = np.array(cached_results["distances"])
+ recall_idx_flat = np.array(cached_results["indices"])
+ end_time = time.time()
+ print(f"Loaded cached results in {end_time - start_time:.3f} seconds")
+else:
+ print("\nBuilding FlatIP index for ground truth...")
+ index_flat = faiss.IndexFlatIP(d) # Use Inner Product
+ index_flat.add(xb)
+ print(f"Searching FlatIP index with {len(xq_full)} queries (k={K_NEIGHBORS})...")
+ start_time = time.time()
+ D_flat, recall_idx_flat = index_flat.search(xq_full, k=K_NEIGHBORS)
+ end_time = time.time()
+ print(f"Time taken for FLAT index search: {end_time - start_time:.3f} seconds")
+
+ # Save results to cache
+ # with open(cache_file, 'w') as f:
+ # json.dump({
+ # "distances": D_flat.tolist(),
+ # "indices": recall_idx_flat.tolist(),
+ # "metadata": {
+ # "task": TASK_NAME,
+ # "k": K_NEIGHBORS,
+ # "timestamp": time.strftime("%Y%m%d_%H%M%S"),
+ # }
+ # }, f)
+ # print(f"Cached FLAT index results to {cache_file}")
+
+# print(recall_idx_flat)
+
+# Create a specific directory for this index configuration
+# index_dir = f"{INDEX_SAVING_FILE}/hnsw_IP_M{M}_efC{efConstruction}"
+# os.makedirs(index_of, exist_ok=True)
+parser = argparse.ArgumentParser()
+# parser.add_argument("--index-dir", type=str, default=f"{INDEX_SAVING_FILE}/hnsw_IP_M{M}_efC{efConstruction}")
+parser.add_argument("--index-file", type=str, default=f"{INDEX_SAVING_FILE}/hnsw_IP_M{M}_efC{efConstruction}/index.faiss")
+args = parser.parse_args()
+index_filename = args.index_file
+index_dir = os.path.dirname(index_filename)
+os.makedirs(index_dir, exist_ok=True)
+
+# Check if index already exists
+if os.path.exists(index_filename):
+ print(f"Found existing index at {index_filename}, loading...")
+ index = faiss.read_index(index_filename)
+ print("Index loaded successfully.")
+else:
+ assert False, "Index does not exist"
+ print(f'Building {"NSG" if "nsg" in index_filename else "HNSW"} index (IP)...')
+ # add build time
+ start_time = time.time()
+ if 'nsg' in index_filename:
+ index = faiss.IndexNSGFlat(d, M, faiss.METRIC_INNER_PRODUCT)
+ index.verbose = True
+ else:
+ index = faiss.IndexHNSWFlat(d, M, faiss.METRIC_INNER_PRODUCT)
+ index.hnsw.efConstruction = efConstruction
+ index.hnsw.set_percentile_thresholds()
+ index.add(xb)
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+ print(f'{"NSG" if "nsg" in index_filename else "HNSW"} index built.')
+
+ # Save the index
+ print(f"Saving index to {index_filename}...")
+ faiss.write_index(index, index_filename)
+ print("Index saved successfully.")
+
+# Analyze the index
+print("\nAnalyzing index...")
+print(f"Total number of nodes: {index.ntotal}")
+print("Neighbor statistics:")
+if 'nsg' in index_filename:
+ print(index.nsg.print_neighbor_stats(0))
+else:
+ print(index.hnsw.print_neighbor_stats(0))
+
+# Save degree distribution
+distribution_filename = f"{index_dir}/degree_distribution.txt"
+print(f"Saving degree distribution to {distribution_filename}...")
+if 'nsg' in index_filename:
+ index.nsg.save_degree_distribution(distribution_filename)
+else:
+ index.hnsw.save_degree_distribution(0, distribution_filename)
+print("Degree distribution saved successfully.")
+
+# Plot the degree distribution
+plot_output_path = f"{index_dir}/degree_distribution.png"
+print(f"Generating degree distribution plot to {plot_output_path}...")
+try:
+ subprocess.run(
+ ["python", "/home/ubuntu/Power-RAG/utils/plot_degree_distribution.py", distribution_filename, "-o", plot_output_path],
+ check=True
+ )
+ print(f"Degree distribution plot saved to {plot_output_path}")
+except subprocess.CalledProcessError as e:
+ print(f"Error generating degree distribution plot: {e}")
+except FileNotFoundError:
+ print("Warning: plot_degree_distribution.py script not found in current directory")
+
+print('Searching HNSW index...')
+
+
+
+# for efSearch in [2, 4, 8, 16, 32, 64,128,256,512,1024]:
+# print(f'*************efSearch: {efSearch}*************')
+# for i in range(10):
+# index.hnsw.efSearch = efSearch
+# D, I = index.search(xq_full[i:i+1], K_NEIGHBORS)
+# exit()
+
+
+recall_result_file = f"{index_dir}/recall_result.txt"
+time_list = []
+recall_list = []
+recompute_list = []
+with open(recall_result_file, 'w') as f:
+ for efSearch in [2, 4, 8, 16, 24, 32, 48, 64, 96,114,128,144,160,176,192,208,224,240,256,384,420,440,460,480,512,768,1024,1152,1536,1792,2048,2230,2408,2880]:
+ if 'nsg' in index_filename:
+ index.nsg.efSearch = efSearch
+ else:
+ index.hnsw.efSearch = efSearch
+ # calculate the time of searching
+ start_time = time.time()
+ if not ('nsg' in index_filename):
+ faiss.cvar.hnsw_stats.reset()
+ else:
+ faiss.cvar.nsg_stats.reset()
+ D, I = index.search(xq_full, K_NEIGHBORS)
+ print('D[0]:', D[0])
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+ time_list.append(end_time - start_time)
+ if 'nsg' in index_filename:
+ print("recompute:", faiss.cvar.nsg_stats.ndis/len(I))
+ recompute_list.append(faiss.cvar.nsg_stats.ndis/len(I))
+ else:
+ print("recompute:", faiss.cvar.hnsw_stats.ndis/len(I))
+ recompute_list.append(faiss.cvar.hnsw_stats.ndis/len(I))
+ # print(I)
+
+ # calculate the recall using the flat index the formula:
+ # recall = sum(recall_idx == recall_idx_flat) / len(recall_idx)
+ recall=[]
+ for i in range(len(I)):
+ acc = 0
+ for j in range(len(I[i])):
+ if I[i][j] in recall_idx_flat[i]:
+ acc += 1
+ recall.append(acc / len(I[i]))
+ recall = sum(recall) / len(recall)
+ recall_list.append(recall)
+ print(f'efSearch: {efSearch}')
+ print(f'recall: {recall}')
+ f.write(f'efSearch: {efSearch}, recall: {recall}\n')
+print(f'Done and result saved to {recall_result_file}')
+print(f'time_list: {time_list}')
+print(f'recall_list: {recall_list}')
+print(f'recompute_list: {recompute_list}')
+exit()
+# Analyze edge stats
+print("\nAnalyzing edge statistics...")
+edge_stats_file = f"{index_dir}/edge_stats.txt"
+if not os.path.exists(edge_stats_file):
+ index.save_edge_stats(edge_stats_file)
+ print(f'Edge stats saved to {edge_stats_file}')
+else:
+ print(f'Edge stats already exists at {edge_stats_file}')
+
+
+def analyze_edge_stats(filename):
+ """
+ Analyze edge statistics from a CSV file and print thresholds at various percentiles.
+
+ Args:
+ filename: Path to the edge statistics CSV file
+ """
+ if not os.path.exists(filename):
+ print(f"Error: File {filename} does not exist")
+ return
+
+ print(f"Analyzing edge statistics from {filename}...")
+
+ # Read the file
+ distances = []
+ with open(filename, 'r') as f:
+ # Skip header
+ header = f.readline()
+
+ # Read all edges
+ for line in f:
+ parts = line.strip().split(',')
+ if len(parts) >= 4:
+ try:
+ src = int(parts[0])
+ dst = int(parts[1])
+ level = int(parts[2])
+ distance = float(parts[3])
+ distances.append(distance)
+ except ValueError:
+ continue
+
+ if not distances:
+ print("No valid edges found in file")
+ return
+
+ # Sort distances
+ distances = np.array(distances)
+ distances.sort()
+
+ # Calculate and print statistics
+ print(f"Total edges: {len(distances)}")
+ print(f"Min distance: {distances[0]:.6f}")
+ print(f"Max distance: {distances[-1]:.6f}")
+
+ # Print thresholds at specified percentiles
+ percentiles = [0.5, 1, 2, 3, 5, 8, 10, 15, 20,30,40,50,60,70]
+ print("\nDistance thresholds at percentiles:")
+ for p in percentiles:
+ idx = int(len(distances) * p / 100)
+ if idx < len(distances):
+ print(f"{p:.1f}%: {distances[idx]:.6f}")
+
+ return distances
+
+analyze_edge_stats(edge_stats_file)
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/plot_graph_struct.py b/packages/leann-backend-hnsw/third_party/faiss/demo/plot_graph_struct.py
new file mode 100644
index 0000000..cf47a3a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/plot_graph_struct.py
@@ -0,0 +1,194 @@
+import re
+import matplotlib.pyplot as plt
+import numpy as np
+
+def extract_data_from_log(log_content):
+ """Extract method names, recall lists, and recompute lists from the log file."""
+
+ # Regular expressions to find the data - modified to match the actual format
+ method_pattern = r"Building HNSW index with ([^\.]+)\.\.\.|Building HNSW index with ([^\n]+)..."
+ recall_list_pattern = r"recall_list: (\[[\d\., ]+\])"
+ recompute_list_pattern = r"recompute_list: (\[[\d\., ]+\])"
+ avg_neighbors_pattern = r"neighbors per node: ([\d\.]+)"
+
+ # Find all matches
+ method_matches = re.findall(method_pattern, log_content)
+ methods = []
+ for match in method_matches:
+ # Each match is a tuple with one empty string and one with the method name
+ method = match[0] if match[0] else match[1]
+ methods.append(method)
+
+ recall_lists_str = re.findall(recall_list_pattern, log_content)
+ recompute_lists_str = re.findall(recompute_list_pattern, log_content)
+ avg_neighbors = re.findall(avg_neighbors_pattern, log_content)
+
+ # Debug information
+ print(f"Found {len(methods)} methods: {methods}")
+ print(f"Found {len(recall_lists_str)} recall lists")
+ print(f"Found {len(recompute_lists_str)} recompute lists")
+ print(f"Found {len(avg_neighbors)} average neighbors values")
+
+ # If the regex approach fails, try a more direct approach
+ if len(methods) < 5:
+ print("Regex approach failed, trying direct extraction...")
+ sections = log_content.split("Building HNSW index with ")[1:]
+ methods = []
+ for section in sections:
+ # Extract the method name (everything up to the first newline)
+ method_name = section.split("\n")[0].strip()
+ # Remove trailing dots if present
+ method_name = method_name.rstrip('.')
+ methods.append(method_name)
+ print(f"Direct extraction found {len(methods)} methods: {methods}")
+
+ # Convert string representations of lists to actual lists
+ recall_lists = [eval(recall_list) for recall_list in recall_lists_str]
+ recompute_lists = [eval(recompute_list) for recompute_list in recompute_lists_str]
+
+ # Convert average neighbors to float
+ avg_neighbors = [float(avg) for avg in avg_neighbors]
+
+ # Make sure we have the same number of items in each list
+ min_length = min(len(methods), len(recall_lists), len(recompute_lists), len(avg_neighbors))
+ if min_length < 5:
+ print(f"Warning: Expected 5 methods, but only found {min_length}")
+
+ # Ensure all lists have the same length
+ methods = methods[:min_length]
+ recall_lists = recall_lists[:min_length]
+ recompute_lists = recompute_lists[:min_length]
+ avg_neighbors = avg_neighbors[:min_length]
+
+ return methods, recall_lists, recompute_lists, avg_neighbors
+
+def plot_performance(methods, recall_lists, recompute_lists, avg_neighbors):
+ """Create a plot comparing the performance of different HNSW methods."""
+
+ plt.figure(figsize=(12, 8))
+
+ colors = ['blue', 'green', 'red', 'purple', 'orange']
+ markers = ['o', 's', '^', 'x', 'd']
+
+ for i, method in enumerate(methods):
+ # Add average neighbors to the label
+ label = f"{method} (avg. {avg_neighbors[i]} neighbors)"
+ plt.plot(recompute_lists[i], recall_lists[i], label=label,
+ color=colors[i], marker=markers[i], markersize=8, markevery=5)
+
+ plt.xlabel('Distance Computations', fontsize=14)
+ plt.ylabel('Recall', fontsize=14)
+ plt.title('HNSW Index Performance: Recall vs. Computation Cost', fontsize=16)
+ plt.grid(True, linestyle='--', alpha=0.7)
+ plt.legend(fontsize=12)
+ plt.xscale('log')
+ plt.ylim(0, 1.0)
+
+ # Add horizontal lines for different recall levels
+ recall_levels = [0.90, 0.95, 0.96, 0.97, 0.98]
+ line_styles = [':', '--', '-.', '-', '-']
+ line_widths = [1, 1, 1, 1.5, 1.5]
+
+ for i, level in enumerate(recall_levels):
+ plt.axhline(y=level, color='gray', linestyle=line_styles[i],
+ alpha=0.7, linewidth=line_widths[i])
+ plt.text(130, level + 0.002, f'{level*100:.0f}% Recall', fontsize=10)
+
+ plt.tight_layout()
+ plt.savefig('faiss/demo/H_hnsw_performance_comparison.png')
+ plt.show()
+
+def plot_recall_comparison(methods, recall_lists, recompute_lists, avg_neighbors):
+ """Create a bar chart comparing computation costs at different recall levels."""
+
+ recall_levels = [0.90, 0.95, 0.96, 0.97, 0.98]
+
+ # Get computation costs for each method at each recall level
+ computation_costs = []
+ for i, method in enumerate(methods):
+ method_costs = []
+ for level in recall_levels:
+ # Find the first index where recall exceeds the target level
+ recall_idx = next((idx for idx, recall in enumerate(recall_lists[i]) if recall >= level), None)
+ if recall_idx is not None:
+ method_costs.append(recompute_lists[i][recall_idx])
+ else:
+ # If the method doesn't reach this recall level, use None
+ method_costs.append(None)
+ computation_costs.append(method_costs)
+
+ # Set up the plot
+ fig, ax = plt.subplots(figsize=(14, 8))
+
+ # Set width of bars
+ bar_width = 0.15
+
+ # Set positions of the bars on X axis
+ r = np.arange(len(recall_levels))
+
+ # Colors for each method
+ colors = ['blue', 'green', 'red', 'purple', 'orange']
+
+ # Create bars
+ for i, method in enumerate(methods):
+ # Filter out None values
+ valid_costs = [cost if cost is not None else 0 for cost in computation_costs[i]]
+ valid_positions = [pos for pos, cost in zip(r + i*bar_width, computation_costs[i]) if cost is not None]
+ valid_costs = [cost for cost in computation_costs[i] if cost is not None]
+
+ bars = ax.bar(valid_positions, valid_costs, width=bar_width,
+ color=colors[i], label=f"{method} (avg. {avg_neighbors[i]} neighbors)")
+
+ # Add value labels on top of bars
+ for j, bar in enumerate(bars):
+ height = bar.get_height()
+ ax.text(bar.get_x() + bar.get_width()/2., height + 500,
+ f'{height:.0f}', ha='center', va='bottom', rotation=0, fontsize=9)
+
+ # Add labels and title
+ ax.set_xlabel('Recall Level', fontsize=14)
+ ax.set_ylabel('Distance Computations', fontsize=14)
+ ax.set_title('Computation Cost Required to Achieve Different Recall Levels', fontsize=16)
+
+ # Set x-ticks
+ ax.set_xticks(r + bar_width * 2)
+ ax.set_xticklabels([f'{level*100:.0f}%' for level in recall_levels])
+
+ # Add legend
+ ax.legend(fontsize=12)
+
+ # Add grid
+ ax.grid(axis='y', linestyle='--', alpha=0.7)
+
+ plt.tight_layout()
+ plt.savefig('faiss/demo/H_hnsw_recall_comparison.png')
+ plt.show()
+
+# Read the log file
+with open('faiss/demo/output.log', 'r') as f:
+ log_content = f.read()
+
+# Extract data
+methods, recall_lists, recompute_lists, avg_neighbors = extract_data_from_log(log_content)
+
+# Plot the results
+plot_performance(methods, recall_lists, recompute_lists, avg_neighbors)
+
+# Plot the recall comparison
+plot_recall_comparison(methods, recall_lists, recompute_lists, avg_neighbors)
+
+# Print a summary of the methods and their characteristics
+print("\nMethod Summary:")
+for i, method in enumerate(methods):
+ print(f"{method}:")
+ print(f" - Average neighbors per node: {avg_neighbors[i]:.2f}")
+
+ # Find the recompute values needed for different recall levels
+ recall_levels = [0.90, 0.95, 0.96, 0.97, 0.98]
+ for level in recall_levels:
+ recall_idx = next((idx for idx, recall in enumerate(recall_lists[i]) if recall >= level), None)
+ if recall_idx is not None:
+ print(f" - Computations needed for {level*100:.0f}% recall: {recompute_lists[i][recall_idx]:.2f}")
+ else:
+ print(f" - Does not reach {level*100:.0f}% recall in the test")
+ print()
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/plot_graph_struct_big.py b/packages/leann-backend-hnsw/third_party/faiss/demo/plot_graph_struct_big.py
new file mode 100644
index 0000000..8548e2a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/plot_graph_struct_big.py
@@ -0,0 +1,202 @@
+import os
+import re
+import matplotlib.pyplot as plt
+import numpy as np
+import argparse
+
+RECALL_LEVELS = [0.85, 0.90, 0.93, 0.94, 0.95, 0.96]
+
+def extract_data_from_log(log_content):
+ """Extract method names, recall lists, and recompute lists from the log file."""
+
+ # Regular expressions to find the dataz - modified to match the actual format
+ method_pattern = r"Building HNSW index with (.*)\.\.\.|Building HNSW index with ([^\n]+)..."
+ recall_list_pattern = r"recall_list: (\[[\d\., ]+\])"
+ recompute_list_pattern = r"recompute_list: (\[[\d\., ]+\])"
+ avg_neighbors_pattern = r"neighbors per node: ([\d\.]+)"
+
+ # Find all matches
+ method_matches = re.findall(method_pattern, log_content)
+ methods = []
+ for match in method_matches:
+ # Each match is a tuple with one empty string and one with the method name
+ method = match[0] if match[0] else match[1]
+ methods.append(method)
+
+ recall_lists_str = re.findall(recall_list_pattern, log_content)
+ recompute_lists_str = re.findall(recompute_list_pattern, log_content)
+ avg_neighbors = re.findall(avg_neighbors_pattern, log_content)
+
+ # Debug information
+ print(f"Found {len(methods)} methods: {methods}")
+ print(f"Found {len(recall_lists_str)} recall lists")
+ print(f"Found {len(recompute_lists_str)} recompute lists")
+ print(f"Found {len(avg_neighbors)} average neighbors values")
+
+ # If the regex approach fails, try a more direct approach
+ if len(methods) < 5:
+ print("Regex approach failed, trying direct extraction...")
+ sections = log_content.split("Building HNSW index with ")[1:]
+ methods = []
+ for section in sections:
+ # Extract the method name (everything up to the first newline)
+ method_name = section.split("\n")[0].strip()
+ # Remove trailing dots if present
+ method_name = method_name.rstrip('.')
+ methods.append(method_name)
+ print(f"Direct extraction found {len(methods)} methods: {methods}")
+
+ # Convert string representations of lists to actual lists
+ recall_lists = [eval(recall_list) for recall_list in recall_lists_str]
+ recompute_lists = [eval(recompute_list) for recompute_list in recompute_lists_str]
+
+ # Convert average neighbors to float
+ avg_neighbors = [float(avg) for avg in avg_neighbors]
+
+ # Make sure we have the same number of items in each list
+ min_length = min(len(methods), len(recall_lists), len(recompute_lists), len(avg_neighbors))
+ if min_length < 5:
+ print(f"Warning: Expected 5 methods, but only found {min_length}")
+
+ # Ensure all lists have the same length
+ methods = methods[:min_length]
+ recall_lists = recall_lists[:min_length]
+ recompute_lists = recompute_lists[:min_length]
+ avg_neighbors = avg_neighbors[:min_length]
+
+ return methods, recall_lists, recompute_lists, avg_neighbors
+
+def plot_performance(methods, recall_lists, recompute_lists, avg_neighbors):
+ """Create a plot comparing the performance of different HNSW methods."""
+
+ plt.figure(figsize=(12, 8))
+
+ colors = ['blue', 'green', 'red', 'purple', 'orange']
+ markers = ['o', 's', '^', 'x', 'd']
+
+ for i, method in enumerate(methods):
+ # Add average neighbors to the label
+ label = f"{method} (avg. {avg_neighbors[i]} neighbors)"
+ plt.plot(recompute_lists[i], recall_lists[i], label=label,
+ color=colors[i], marker=markers[i], markersize=8, markevery=5)
+
+ plt.xlabel('Distance Computations', fontsize=14)
+ plt.ylabel('Recall', fontsize=14)
+ plt.title('HNSW Index Performance: Recall vs. Computation Cost', fontsize=16)
+ plt.grid(True, linestyle='--', alpha=0.7)
+ plt.legend(fontsize=12)
+ plt.xscale('log')
+ plt.ylim(0, 1.0)
+
+ # Add horizontal lines for different recall levels
+ line_styles = [':', '--', '-.', '-', '-', ':']
+ line_widths = [1, 1, 1, 1.5, 1.5, 1]
+
+ for i, level in enumerate(RECALL_LEVELS):
+ plt.axhline(y=level, color='gray', linestyle=line_styles[i],
+ alpha=0.7, linewidth=line_widths[i])
+ plt.text(130, level + 0.002, f'{level*100:.0f}% Recall', fontsize=10)
+
+ plt.tight_layout()
+ plt.savefig(os.path.join(os.path.dirname(__file__), 'H_hnsw_performance_comparison.png'))
+ plt.show()
+
+def plot_recall_comparison(methods, recall_lists, recompute_lists, avg_neighbors):
+ """Create a bar chart comparing computation costs at different recall levels."""
+
+ # Get computation costs for each method at each recall level
+ computation_costs = []
+ for i, method in enumerate(methods):
+ method_costs = []
+ for level in RECALL_LEVELS:
+ # Find the first index where recall exceeds the target level
+ recall_idx = next((idx for idx, recall in enumerate(recall_lists[i]) if recall >= level), None)
+ if recall_idx is not None:
+ method_costs.append(recompute_lists[i][recall_idx])
+ else:
+ # If the method doesn't reach this recall level, use None
+ method_costs.append(None)
+ computation_costs.append(method_costs)
+
+ # Set up the plot
+ fig, ax = plt.subplots(figsize=(14, 8))
+
+ # Set width of bars
+ bar_width = 0.15
+
+ # Set positions of the bars on X axis
+ r = np.arange(len(RECALL_LEVELS))
+
+ # Colors for each method
+ colors = ['blue', 'green', 'red', 'purple', 'orange']
+
+ # Create bars
+ for i, method in enumerate(methods):
+ # Filter out None values
+ valid_costs = [cost if cost is not None else 0 for cost in computation_costs[i]]
+ valid_positions = [pos for pos, cost in zip(r + i*bar_width, computation_costs[i]) if cost is not None]
+ valid_costs = [cost for cost in computation_costs[i] if cost is not None]
+
+ bars = ax.bar(valid_positions, valid_costs, width=bar_width,
+ color=colors[i], label=f"{method} (avg. {avg_neighbors[i]} neighbors)")
+
+ # Add value labels on top of bars
+ for j, bar in enumerate(bars):
+ height = bar.get_height()
+ ax.text(bar.get_x() + bar.get_width()/2., height + 500,
+ f'{height:.0f}', ha='center', va='bottom', rotation=0, fontsize=9)
+
+ # Add labels and title
+ ax.set_xlabel('Recall Level', fontsize=14)
+ ax.set_ylabel('Distance Computations', fontsize=14)
+ ax.set_title('Computation Cost Required to Achieve Different Recall Levels', fontsize=16)
+
+ # Set x-ticks
+ ax.set_xticks(r + bar_width * 2)
+ ax.set_xticklabels([f'{level*100:.0f}%' for level in RECALL_LEVELS])
+
+ # Add legend
+ ax.legend(fontsize=12)
+
+ # Add grid
+ ax.grid(axis='y', linestyle='--', alpha=0.7)
+
+ plt.tight_layout()
+ plt.savefig(os.path.join(os.path.dirname(__file__), 'H_hnsw_recall_comparison.png'))
+ plt.show()
+
+# Read the log file
+
+parser = argparse.ArgumentParser()
+parser.add_argument('log_file', type=str, default='nlevel_output.log')
+args = parser.parse_args()
+
+log_file = args.log_file
+log_file = os.path.join(os.path.dirname(__file__), log_file)
+
+with open(log_file, 'r') as f:
+ log_content = f.read()
+
+# Extract data
+methods, recall_lists, recompute_lists, avg_neighbors = extract_data_from_log(log_content)
+
+# Plot the results
+plot_performance(methods, recall_lists, recompute_lists, avg_neighbors)
+
+# Plot the recall comparison
+plot_recall_comparison(methods, recall_lists, recompute_lists, avg_neighbors)
+
+# Print a summary of the methods and their characteristics
+print("\nMethod Summary:")
+for i, method in enumerate(methods):
+ print(f"{method}:")
+ print(f" - Average neighbors per node: {avg_neighbors[i]:.2f}")
+
+ # Find the recompute values needed for different recall levels
+ for level in RECALL_LEVELS:
+ recall_idx = next((idx for idx, recall in enumerate(recall_lists[i]) if recall >= level), None)
+ if recall_idx is not None:
+ print(f" - Computations needed for {level*100:.0f}% recall: {recompute_lists[i][recall_idx]:.2f}")
+ else:
+ print(f" - Does not reach {level*100:.0f}% recall in the test")
+ print()
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build.py b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build.py
new file mode 100644
index 0000000..6d355fb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build.py
@@ -0,0 +1,329 @@
+import sys
+import time
+import faiss
+import numpy as np
+import pickle
+import os
+import json
+import time
+import torch
+import argparse
+from tqdm import tqdm
+from pathlib import Path
+import subprocess
+
+# Add argument parsing
+parser = argparse.ArgumentParser(description='Build and evaluate HNSW index')
+parser.add_argument('--config', type=str, default="0.02per_M6-7_degree_based",
+ help='Configuration name for the index (default: 0.02per_M6-7_degree_based)')
+parser.add_argument('--M', type=int, default=32,
+ help='HNSW M parameter (default: 32)')
+parser.add_argument('--efConstruction', type=int, default=256,
+ help='HNSW efConstruction parameter (default: 256)')
+parser.add_argument('--K_NEIGHBORS', type=int, default=3,
+ help='Number of neighbors to retrieve (default: 3)')
+parser.add_argument('--max_queries', type=int, default=1000,
+ help='Maximum number of queries to load (default: 1000)')
+parser.add_argument('--batch_size', type=int, default=64,
+ help='Batch size for query encoding (default: 64)')
+parser.add_argument('--db_embedding_file', type=str,
+ default="/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/passages_00.pkl",
+ help='Path to database embedding file')
+parser.add_argument('--index_saving_dir', type=str,
+ default="/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/indices",
+ help='Directory to save the index')
+parser.add_argument('--task_name', type=str, default="nq",
+ help='Task name from TASK_CONFIGS (default: nq)')
+parser.add_argument('--embedder_model', type=str, default="facebook/contriever-msmarco",
+ help='Model name for query embedding (default: facebook/contriever-msmarco)')
+
+args = parser.parse_args()
+
+# Replace hardcoded constants with arguments
+M = args.M
+efConstruction = args.efConstruction
+K_NEIGHBORS = args.K_NEIGHBORS
+DB_EMBEDDING_FILE = args.db_embedding_file
+INDEX_SAVING_FILE = args.index_saving_dir
+TASK_NAME = args.task_name
+EMBEDDER_MODEL_NAME = args.embedder_model
+MAX_QUERIES_TO_LOAD = args.max_queries
+QUERY_ENCODING_BATCH_SIZE = args.batch_size
+CONFIG_NAME = args.config
+
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
+sys.path.append(os.path.join(project_root, "demo"))
+from config import SCALING_OUT_DIR, get_example_path, TASK_CONFIGS
+sys.path.append(project_root)
+from contriever.src.contriever import Contriever, load_retriever
+
+# 1M samples
+print(f"Loading embeddings from {DB_EMBEDDING_FILE}...")
+with open(DB_EMBEDDING_FILE, 'rb') as f:
+ data = pickle.load(f)
+
+xb = data[1]
+print(f"Original dtype: {xb.dtype}")
+
+if xb.dtype != np.float32:
+ print("Converting embeddings to float32.")
+ xb = xb.astype(np.float32)
+else:
+ print("Embeddings are already float32.")
+print(f"Loaded database embeddings (xb), shape: {xb.shape}")
+d = xb.shape[1] # Get dimension
+
+query_file_path = TASK_CONFIGS[TASK_NAME].query_path
+print(f"Using query path from TASK_CONFIGS: {query_file_path}")
+
+query_texts = []
+print(f"Reading queries from: {query_file_path}")
+with open(query_file_path, 'r') as f:
+ for i, line in enumerate(f):
+ if i >= MAX_QUERIES_TO_LOAD:
+ print(f"Stopped loading queries at limit: {MAX_QUERIES_TO_LOAD}")
+ break
+ record = json.loads(line)
+ query_texts.append(record["query"])
+print(f"Loaded {len(query_texts)} query texts.")
+
+print("\nInitializing retriever model for encoding queries...")
+device = "cuda" if torch.cuda.is_available() else "cpu"
+print(f"Using device: {device}")
+model, tokenizer, _ = load_retriever(EMBEDDER_MODEL_NAME)
+model.to(device)
+model.eval() # Set to evaluation mode
+print("Retriever model loaded.")
+
+
+def embed_queries(queries, model, tokenizer, model_name_or_path, per_gpu_batch_size=64):
+ """Embed queries using the model with batching"""
+ model = model.half()
+ model.eval()
+ embeddings = []
+ batch_question = []
+
+ with torch.no_grad():
+ for k, query in tqdm(enumerate(queries), desc="Encoding queries"):
+ batch_question.append(query)
+
+ # Process when batch is full or at the end
+ if len(batch_question) == per_gpu_batch_size or k == len(queries) - 1:
+ encoded_batch = tokenizer.batch_encode_plus(
+ batch_question,
+ return_tensors="pt",
+ max_length=512,
+ padding=True,
+ truncation=True,
+ )
+
+ encoded_batch = {k: v.to(device) for k, v in encoded_batch.items()}
+ output = model(**encoded_batch)
+
+ # Contriever typically uses output.last_hidden_state pooling or something specialized
+ if "contriever" not in model_name_or_path:
+ output = output.last_hidden_state[:, 0, :]
+
+ embeddings.append(output.cpu())
+ batch_question = [] # Reset batch
+
+ embeddings = torch.cat(embeddings, dim=0).numpy()
+ print(f"Query embeddings shape: {embeddings.shape}")
+ return embeddings
+
+print(f"\nEncoding {len(query_texts)} queries (batch size: {QUERY_ENCODING_BATCH_SIZE})...")
+xq_full = embed_queries(query_texts, model, tokenizer, EMBEDDER_MODEL_NAME, per_gpu_batch_size=QUERY_ENCODING_BATCH_SIZE)
+
+# Ensure float32 for Faiss compatibility after encoding
+if xq_full.dtype != np.float32:
+ print(f"Converting encoded queries from {xq_full.dtype} to float32.")
+ xq_full = xq_full.astype(np.float32)
+
+print(f"Encoded queries (xq_full), shape: {xq_full.shape}, dtype: {xq_full.dtype}")
+
+# Check dimension consistency
+if xq_full.shape[1] != d:
+ raise ValueError(f"Query embedding dimension ({xq_full.shape[1]}) does not match database dimension ({d})")
+
+# recall_idx = []
+
+print("\nBuilding FlatIP index for ground truth...")
+index_flat = faiss.IndexFlatIP(d) # Use Inner Product
+index_flat.add(xb)
+print(f"Searching FlatIP index with {MAX_QUERIES_TO_LOAD} queries (k={K_NEIGHBORS})...")
+D_flat, recall_idx_flat = index_flat.search(xq_full, k=K_NEIGHBORS)
+
+# print(recall_idx_flat)
+
+# Create a specific directory for this index configuration
+index_dir = f"{INDEX_SAVING_FILE}/{CONFIG_NAME}_hnsw_IP_M{M}_efC{efConstruction}"
+if CONFIG_NAME == "origin":
+ index_dir = f"{INDEX_SAVING_FILE}/hnsw_IP_M{M}_efC{efConstruction}"
+os.makedirs(index_dir, exist_ok=True)
+index_filename = f"{index_dir}/index.faiss"
+
+# Check if index already exists
+if os.path.exists(index_filename):
+ print(f"Found existing index at {index_filename}, loading...")
+ index = faiss.read_index(index_filename)
+ print("Index loaded successfully.")
+else:
+ print('Building HNSW index (IP)...')
+ # add build time
+ start_time = time.time()
+ index = faiss.IndexHNSWFlat(d, M, faiss.METRIC_INNER_PRODUCT)
+ index.hnsw.efConstruction = efConstruction
+ index.hnsw.set_percentile_thresholds()
+ index.add(xb)
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+ print('HNSW index built.')
+
+ # Save the HNSW index
+ print(f"Saving index to {index_filename}...")
+ faiss.write_index(index, index_filename)
+ print("Index saved successfully.")
+# Analyze the HNSW index
+print("\nAnalyzing HNSW index...")
+print(f"Total number of nodes: {index.ntotal}")
+print("Neighbor statistics:")
+print(index.hnsw.print_neighbor_stats(0))
+
+# Save degree distribution
+distribution_filename = f"{index_dir}/degree_distribution.txt"
+print(f"Saving degree distribution to {distribution_filename}...")
+index.hnsw.save_degree_distribution(0, distribution_filename)
+print("Degree distribution saved successfully.")
+
+# Plot the degree distribution
+plot_output_path = f"{index_dir}/degree_distribution.png"
+print(f"Generating degree distribution plot to {plot_output_path}...")
+try:
+ subprocess.run(
+ ["python", "/home/ubuntu/Power-RAG/utils/plot_degree_distribution.py", distribution_filename, "-o", plot_output_path],
+ check=True
+ )
+ print(f"Degree distribution plot saved to {plot_output_path}")
+except subprocess.CalledProcessError as e:
+ print(f"Error generating degree distribution plot: {e}")
+except FileNotFoundError:
+ print("Warning: plot_degree_distribution.py script not found in current directory")
+
+print('Searching HNSW index...')
+
+
+
+# for efSearch in [2, 4, 8, 16, 32, 64,128,256,512,1024]:
+# print(f'*************efSearch: {efSearch}*************')
+# for i in range(10):
+# index.hnsw.efSearch = efSearch
+# D, I = index.search(xq_full[i:i+1], K_NEIGHBORS)
+# exit()
+
+
+recall_result_file = f"{index_dir}/recall_result.txt"
+time_list = []
+recall_list = []
+recompute_list = []
+with open(recall_result_file, 'w') as f:
+ for efSearch in [2, 4, 8, 16, 24, 32, 48, 64, 96,114,128,144,160,176,192,208,224,240,256,384,420,440,460,480,512,768,1024,1152,1536,1792,2048,2230,2408,2880]:
+ index.hnsw.efSearch = efSearch
+ # calculate the time of searching
+ start_time = time.time()
+ faiss.cvar.hnsw_stats.reset()
+ # print faiss.cvar.hnsw_stats.ndis
+ print(f'ndis: {faiss.cvar.hnsw_stats.ndis}')
+ D, I = index.search(xq_full, K_NEIGHBORS)
+ print('D[0]:', D[0])
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+ time_list.append(end_time - start_time)
+ print("recompute:", faiss.cvar.hnsw_stats.ndis/len(I))
+ recompute_list.append(faiss.cvar.hnsw_stats.ndis/len(I))
+ # print(I)
+
+ # calculate the recall using the flat index the formula:
+ # recall = sum(recall_idx == recall_idx_flat) / len(recall_idx)
+ recall=[]
+ for i in range(len(I)):
+ acc = 0
+ for j in range(len(I[i])):
+ if I[i][j] in recall_idx_flat[i]:
+ acc += 1
+ recall.append(acc / len(I[i]))
+ recall = sum(recall) / len(recall)
+ recall_list.append(recall)
+ print(f'efSearch: {efSearch}')
+ print(f'recall: {recall}')
+ f.write(f'efSearch: {efSearch}, recall: {recall}\n')
+print(f'Done and result saved to {recall_result_file}')
+print(f'time_list: {time_list}')
+print(f'recall_list: {recall_list}')
+print(f'recompute_list: {recompute_list}')
+exit()
+# Analyze edge stats
+print("\nAnalyzing edge statistics...")
+edge_stats_file = f"{index_dir}/edge_stats.txt"
+if not os.path.exists(edge_stats_file):
+ index.save_edge_stats(edge_stats_file)
+ print(f'Edge stats saved to {edge_stats_file}')
+else:
+ print(f'Edge stats already exists at {edge_stats_file}')
+
+
+def analyze_edge_stats(filename):
+ """
+ Analyze edge statistics from a CSV file and print thresholds at various percentiles.
+
+ Args:
+ filename: Path to the edge statistics CSV file
+ """
+ if not os.path.exists(filename):
+ print(f"Error: File {filename} does not exist")
+ return
+
+ print(f"Analyzing edge statistics from {filename}...")
+
+ # Read the file
+ distances = []
+ with open(filename, 'r') as f:
+ # Skip header
+ header = f.readline()
+
+ # Read all edges
+ for line in f:
+ parts = line.strip().split(',')
+ if len(parts) >= 4:
+ try:
+ src = int(parts[0])
+ dst = int(parts[1])
+ level = int(parts[2])
+ distance = float(parts[3])
+ distances.append(distance)
+ except ValueError:
+ continue
+
+ if not distances:
+ print("No valid edges found in file")
+ return
+
+ # Sort distances
+ distances = np.array(distances)
+ distances.sort()
+
+ # Calculate and print statistics
+ print(f"Total edges: {len(distances)}")
+ print(f"Min distance: {distances[0]:.6f}")
+ print(f"Max distance: {distances[-1]:.6f}")
+
+ # Print thresholds at specified percentiles
+ percentiles = [0.5, 1, 2, 3, 5, 8, 10, 15, 20,30,40,50,60,70]
+ print("\nDistance thresholds at percentiles:")
+ for p in percentiles:
+ idx = int(len(distances) * p / 100)
+ if idx < len(distances):
+ print(f"{p:.1f}%: {distances[idx]:.6f}")
+
+ return distances
+
+analyze_edge_stats(edge_stats_file)
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build_dpr.py b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build_dpr.py
new file mode 100644
index 0000000..c885720
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build_dpr.py
@@ -0,0 +1,212 @@
+import sys
+import time
+import faiss
+import numpy as np
+import pickle
+import os
+import json
+import time
+import torch
+from tqdm import tqdm
+from pathlib import Path
+import subprocess
+
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
+sys.path.append(os.path.join(project_root, "demo"))
+from config import SCALING_OUT_DIR, get_example_path, TASK_CONFIGS, get_embedding_path
+sys.path.append(project_root)
+from contriever.src.contriever import Contriever, load_retriever
+
+M = 32
+efConstruction = 256
+K_NEIGHBORS = 3
+
+# Original configuration (commented out)
+# DB_EMBEDDING_FILE = "/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/passages_00.pkl"
+# INDEX_SAVING_FILE = "/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices"
+
+# New configuration using DPR
+DOMAIN_NAME = "dpr"
+EMBEDDER_NAME = "facebook/contriever-msmarco"
+TASK_NAME = "nq"
+MAX_QUERIES_TO_LOAD = 1000
+QUERY_ENCODING_BATCH_SIZE = 64
+
+# Get the embedding path using the function from config
+embed_path = get_embedding_path(DOMAIN_NAME, EMBEDDER_NAME, 0)
+INDEX_SAVING_FILE = os.path.join(os.path.dirname(embed_path), "indices")
+os.makedirs(INDEX_SAVING_FILE, exist_ok=True)
+
+# Load embeddings
+print(f"Loading embeddings from {embed_path}...")
+with open(embed_path, 'rb') as f:
+ data = pickle.load(f)
+
+xb = data[1]
+print(f"Original dtype: {xb.dtype}")
+
+if xb.dtype != np.float32:
+ print("Converting embeddings to float32.")
+ xb = xb.astype(np.float32)
+else:
+ print("Embeddings are already float32.")
+print(f"Loaded database embeddings (xb), shape: {xb.shape}")
+d = xb.shape[1] # Get dimension
+
+query_file_path = TASK_CONFIGS[TASK_NAME].query_path
+print(f"Using query path from TASK_CONFIGS: {query_file_path}")
+
+query_texts = []
+print(f"Reading queries from: {query_file_path}")
+with open(query_file_path, 'r') as f:
+ for i, line in enumerate(f):
+ if i >= MAX_QUERIES_TO_LOAD:
+ print(f"Stopped loading queries at limit: {MAX_QUERIES_TO_LOAD}")
+ break
+ record = json.loads(line)
+ query_texts.append(record["query"])
+print(f"Loaded {len(query_texts)} query texts.")
+
+print("\nInitializing retriever model for encoding queries...")
+device = "cuda" if torch.cuda.is_available() else "cpu"
+print(f"Using device: {device}")
+model, tokenizer, _ = load_retriever(EMBEDDER_NAME)
+model.to(device)
+model.eval() # Set to evaluation mode
+print("Retriever model loaded.")
+
+
+def embed_queries(queries, model, tokenizer, model_name_or_path, per_gpu_batch_size=64):
+ """Embed queries using the model with batching"""
+ model = model.half()
+ model.eval()
+ embeddings = []
+ batch_question = []
+
+ with torch.no_grad():
+ for k, query in tqdm(enumerate(queries), desc="Encoding queries"):
+ batch_question.append(query)
+
+ # Process when batch is full or at the end
+ if len(batch_question) == per_gpu_batch_size or k == len(queries) - 1:
+ encoded_batch = tokenizer.batch_encode_plus(
+ batch_question,
+ return_tensors="pt",
+ max_length=512,
+ padding=True,
+ truncation=True,
+ )
+
+ encoded_batch = {k: v.to(device) for k, v in encoded_batch.items()}
+ output = model(**encoded_batch)
+
+ # Contriever typically uses output.last_hidden_state pooling or something specialized
+ if "contriever" not in model_name_or_path:
+ output = output.last_hidden_state[:, 0, :]
+
+ embeddings.append(output.cpu())
+ batch_question = [] # Reset batch
+
+ embeddings = torch.cat(embeddings, dim=0).numpy()
+ print(f"Query embeddings shape: {embeddings.shape}")
+ return embeddings
+
+print(f"\nEncoding {len(query_texts)} queries (batch size: {QUERY_ENCODING_BATCH_SIZE})...")
+xq_full = embed_queries(query_texts, model, tokenizer, EMBEDDER_NAME, per_gpu_batch_size=QUERY_ENCODING_BATCH_SIZE)
+
+# Ensure float32 for Faiss compatibility after encoding
+if xq_full.dtype != np.float32:
+ print(f"Converting encoded queries from {xq_full.dtype} to float32.")
+ xq_full = xq_full.astype(np.float32)
+
+print(f"Encoded queries (xq_full), shape: {xq_full.shape}, dtype: {xq_full.dtype}")
+
+# Check dimension consistency
+if xq_full.shape[1] != d:
+ raise ValueError(f"Query embedding dimension ({xq_full.shape[1]}) does not match database dimension ({d})")
+
+# Build flat index for ground truth
+print("\nBuilding FlatIP index for ground truth...")
+index_flat = faiss.IndexFlatIP(d) # Use Inner Product
+index_flat.add(xb)
+print(f"Searching FlatIP index with {len(xq_full)} queries (k={K_NEIGHBORS})...")
+D_flat, recall_idx_flat = index_flat.search(xq_full, k=K_NEIGHBORS)
+
+# Create a specific directory for this index configuration
+index_dir = f"{INDEX_SAVING_FILE}/hahahdpr_hnsw_IP_M{M}_efC{efConstruction}"
+os.makedirs(index_dir, exist_ok=True)
+index_filename = f"{index_dir}/index.faiss"
+
+# Check if index already exists
+if os.path.exists(index_filename):
+ print(f"Found existing index at {index_filename}, loading...")
+ index = faiss.read_index(index_filename)
+ print("Index loaded successfully.")
+else:
+ print('Building HNSW index (IP)...')
+ # add build time
+ start_time = time.time()
+ index = faiss.IndexHNSWFlat(d, M, faiss.METRIC_INNER_PRODUCT)
+ index.hnsw.efConstruction = efConstruction
+ index.add(xb)
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+ print('HNSW index built.')
+
+ # Save the HNSW index
+ print(f"Saving index to {index_filename}...")
+ faiss.write_index(index, index_filename)
+ print("Index saved successfully.")
+
+# Analyze the HNSW index
+print("\nAnalyzing HNSW index...")
+print(f"Total number of nodes: {index.ntotal}")
+print("Neighbor statistics:")
+print(index.hnsw.print_neighbor_stats(0))
+
+# Save degree distribution
+distribution_filename = f"{index_dir}/degree_distribution.txt"
+print(f"Saving degree distribution to {distribution_filename}...")
+index.hnsw.save_degree_distribution(0, distribution_filename)
+print("Degree distribution saved successfully.")
+
+# Plot the degree distribution
+plot_output_path = f"{index_dir}/degree_distribution.png"
+print(f"Generating degree distribution plot to {plot_output_path}...")
+try:
+ subprocess.run(
+ ["python", f"{project_root}/utils/plot_degree_distribution.py", distribution_filename, "-o", plot_output_path],
+ check=True
+ )
+ print(f"Degree distribution plot saved to {plot_output_path}")
+except subprocess.CalledProcessError as e:
+ print(f"Error generating degree distribution plot: {e}")
+except FileNotFoundError:
+ print("Warning: plot_degree_distribution.py script not found in specified path")
+
+print('Searching HNSW index...')
+
+recall_result_file = f"{index_dir}/recall_result.txt"
+with open(recall_result_file, 'w') as f:
+ for efSearch in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
+ index.hnsw.efSearch = efSearch
+ # calculate the time of searching
+ start_time = time.time()
+
+ D, I = index.search(xq_full, K_NEIGHBORS)
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+
+ # calculate the recall using the flat index
+ recall = []
+ for i in range(len(I)):
+ acc = 0
+ for j in range(len(I[i])):
+ if I[i][j] in recall_idx_flat[i]:
+ acc += 1
+ recall.append(acc / len(I[i]))
+ recall = sum(recall) / len(recall)
+ print(f'efSearch: {efSearch}')
+ print(f'recall: {recall}')
+ f.write(f'efSearch: {efSearch}, recall: {recall}\n')
+print(f'Done and result saved to {recall_result_file}')
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build_nsg.py b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build_nsg.py
new file mode 100644
index 0000000..d770fd4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_build_nsg.py
@@ -0,0 +1,212 @@
+import sys
+import time
+import faiss
+import numpy as np
+import pickle
+import os
+import json
+import time
+import torch
+from tqdm import tqdm
+from pathlib import Path
+import subprocess
+
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
+sys.path.append(os.path.join(project_root, "demo"))
+from config import SCALING_OUT_DIR, get_example_path, TASK_CONFIGS, get_embedding_path
+sys.path.append(project_root)
+from contriever.src.contriever import Contriever, load_retriever
+
+M = 20
+efConstruction = 256
+K_NEIGHBORS = 3
+
+# New configuration using DPR
+DOMAIN_NAME = "rpj_wiki"
+EMBEDDER_NAME = "facebook/contriever-msmarco"
+TASK_NAME = "nq"
+MAX_QUERIES_TO_LOAD = 1000
+QUERY_ENCODING_BATCH_SIZE = 64
+
+# Get the embedding path using the function from config
+# embed_path = get_embedding_path(DOMAIN_NAME, EMBEDDER_NAME, 0)
+# INDEX_SAVING_FILE = os.path.join(os.path.dirname(embed_path), "indices")
+# os.makedirs(INDEX_SAVING_FILE, exist_ok=True)
+
+# Original configuration (commented out)
+embed_path = "/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/passages_00.pkl"
+INDEX_SAVING_FILE = "/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/indices"
+
+# Load embeddings
+print(f"Loading embeddings from {extend_path}...")
+with open(embed_path, 'rb') as f:
+ data = pickle.load(f)
+
+xb = data[1]
+print(f"Original dtype: {xb.dtype}")
+
+if xb.dtype != np.float32:
+ print("Converting embeddings to float32.")
+ xb = xb.astype(np.float32)
+else:
+ print("Embeddings are already float32.")
+print(f"Loaded database embeddings (xb), shape: {xb.shape}")
+d = xb.shape[1] # Get dimension
+
+query_file_path = TASK_CONFIGS[TASK_NAME].query_path
+print(f"Using query path from TASK_CONFIGS: {query_file_path}")
+
+query_texts = []
+print(f"Reading queries from: {query_file_path}")
+with open(query_file_path, 'r') as f:
+ for i, line in enumerate(f):
+ if i >= MAX_QUERIES_TO_LOAD:
+ print(f"Stopped loading queries at limit: {MAX_QUERIES_TO_LOAD}")
+ break
+ record = json.loads(line)
+ query_texts.append(record["query"])
+print(f"Loaded {len(query_texts)} query texts.")
+
+print("\nInitializing retriever model for encoding queries...")
+device = "cuda" if torch.cuda.is_available() else "cpu"
+print(f"Using device: {device}")
+model, tokenizer, _ = load_retriever(EMBEDDER_NAME)
+model.to(device)
+model.eval() # Set to evaluation mode
+print("Retriever model loaded.")
+
+
+def embed_queries(queries, model, tokenizer, model_name_or_path, per_gpu_batch_size=64):
+ """Embed queries using the model with batching"""
+ model = model.half()
+ model.eval()
+ embeddings = []
+ batch_question = []
+
+ with torch.no_grad():
+ for k, query in tqdm(enumerate(queries), desc="Encoding queries"):
+ batch_question.append(query)
+
+ # Process when batch is full or at the end
+ if len(batch_question) == per_gpu_batch_size or k == len(queries) - 1:
+ encoded_batch = tokenizer.batch_encode_plus(
+ batch_question,
+ return_tensors="pt",
+ max_length=512,
+ padding=True,
+ truncation=True,
+ )
+
+ encoded_batch = {k: v.to(device) for k, v in encoded_batch.items()}
+ output = model(**encoded_batch)
+
+ # Contriever typically uses output.last_hidden_state pooling or something specialized
+ if "contriever" not in model_name_or_path:
+ output = output.last_hidden_state[:, 0, :]
+
+ embeddings.append(output.cpu())
+ batch_question = [] # Reset batch
+
+ embeddings = torch.cat(embeddings, dim=0).numpy()
+ print(f"Query embeddings shape: {embeddings.shape}")
+ return embeddings
+
+print(f"\nEncoding {len(query_texts)} queries (batch size: {QUERY_ENCODING_BATCH_SIZE})...")
+xq_full = embed_queries(query_texts, model, tokenizer, EMBEDDER_NAME, per_gpu_batch_size=QUERY_ENCODING_BATCH_SIZE)
+
+# Ensure float32 for Faiss compatibility after encoding
+if xq_full.dtype != np.float32:
+ print(f"Converting encoded queries from {xq_full.dtype} to float32.")
+ xq_full = xq_full.astype(np.float32)
+
+print(f"Encoded queries (xq_full), shape: {xq_full.shape}, dtype: {xq_full.dtype}")
+
+# Check dimension consistency
+if xq_full.shape[1] != d:
+ raise ValueError(f"Query embedding dimension ({xq_full.shape[1]}) does not match database dimension ({d})")
+
+# Build flat index for ground truth
+print("\nBuilding FlatIP index for ground truth...")
+index_flat = faiss.IndexFlatIP(d) # Use Inner Product
+index_flat.add(xb)
+print(f"Searching FlatIP index with {len(xq_full)} queries (k={K_NEIGHBORS})...")
+D_flat, recall_idx_flat = index_flat.search(xq_full, k=K_NEIGHBORS)
+
+# Create a specific directory for this index configuration
+index_dir = f"{INDEX_SAVING_FILE}/rpj_wiki_nsg_IP_M{M}"
+os.makedirs(index_dir, exist_ok=True)
+index_filename = f"{index_dir}/index.faiss"
+
+# Check if index already exists
+if os.path.exists(index_filename):
+ print(f"Found existing index at {index_filename}, loading...")
+ index = faiss.read_index(index_filename)
+ print("Index loaded successfully.")
+else:
+ print('Building HNSW index (IP)...')
+ # add build time
+ start_time = time.time()
+ index = faiss.IndexNSGFlat(d, M, faiss.METRIC_INNER_PRODUCT)
+ index.verbose = True
+ index.add(xb)
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+ print('HNSW index built.')
+
+ # Save the HNSW index
+ print(f"Saving index to {index_filename}...")
+ faiss.write_index(index, index_filename)
+ print("Index saved successfully.")
+
+# Analyze the HNSW index
+print("\nAnalyzing HNSW index...")
+print(f"Total number of nodes: {index.ntotal}")
+print("Neighbor statistics:")
+print(index.nsg.print_neighbor_stats(0))
+
+# Save degree distribution
+distribution_filename = f"{index_dir}/degree_distribution.txt"
+print(f"Saving degree distribution to {distribution_filename}...")
+index.nsg.save_degree_distribution(distribution_filename)
+print("Degree distribution saved successfully.")
+
+# Plot the degree distribution
+plot_output_path = f"{index_dir}/degree_distribution.png"
+print(f"Generating degree distribution plot to {plot_output_path}...")
+try:
+ subprocess.run(
+ ["python", f"{project_root}/utils/plot_degree_distribution.py", distribution_filename, "-o", plot_output_path],
+ check=True
+ )
+ print(f"Degree distribution plot saved to {plot_output_path}")
+except subprocess.CalledProcessError as e:
+ print(f"Error generating degree distribution plot: {e}")
+except FileNotFoundError:
+ print("Warning: plot_degree_distribution.py script not found in specified path")
+
+print('Searching HNSW index...')
+
+recall_result_file = f"{index_dir}/recall_result.txt"
+with open(recall_result_file, 'w') as f:
+ for efSearch in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
+ index.nsg.efSearch = efSearch
+ # calculate the time of searching
+ start_time = time.time()
+
+ D, I = index.search(xq_full, K_NEIGHBORS)
+ end_time = time.time()
+ print(f'time: {end_time - start_time}')
+
+ # calculate the recall using the flat index
+ recall = []
+ for i in range(len(I)):
+ acc = 0
+ for j in range(len(I[i])):
+ if I[i][j] in recall_idx_flat[i]:
+ acc += 1
+ recall.append(acc / len(I[i]))
+ recall = sum(recall) / len(recall)
+ print(f'efSearch: {efSearch}')
+ print(f'recall: {recall}')
+ f.write(f'efSearch: {efSearch}, recall: {recall}\n')
+print(f'Done and result saved to {recall_result_file}')
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demo/simple_search.fish b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_search.fish
new file mode 100644
index 0000000..9a68bde
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demo/simple_search.fish
@@ -0,0 +1,22 @@
+set -l index_dirs \
+/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/hnsw_IP_M30_efC128.index \
+/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/99_4_degree_based_hnsw_IP_M32_efC256/index.faiss \
+/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/d9_hnsw_IP_M8_efC128/index.faiss \
+/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/half_edges_IP_M32_efC128/index.faiss
+# /opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/nsg_R16.index
+
+set -l index_labels \
+origin \
+0.01per_M4_degree_based \
+M8_merge_edge \
+random_delete50
+# nsg_R16
+
+set -gx CUDA_VISIBLE_DEVICES 3
+
+for i in (seq (count $index_dirs))
+ set -l index_file $index_dirs[$i]
+ set -l index_label $index_labels[$i]
+ echo "Building HNSW index with $index_label..." >> ./large_graph_simple_build.log
+ python -u large_graph_simple_build.py --index-file $index_file | tee -a ./large_graph_simple_build.log
+end
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/demos/CMakeLists.txt
new file mode 100644
index 0000000..ec9de31
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/CMakeLists.txt
@@ -0,0 +1,25 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+add_executable(demo_imi_flat EXCLUDE_FROM_ALL demo_imi_flat.cpp)
+target_link_libraries(demo_imi_flat PRIVATE faiss)
+
+add_executable(demo_imi_pq EXCLUDE_FROM_ALL demo_imi_pq.cpp)
+target_link_libraries(demo_imi_pq PRIVATE faiss)
+
+add_executable(demo_ivfpq_indexing EXCLUDE_FROM_ALL demo_ivfpq_indexing.cpp)
+target_link_libraries(demo_ivfpq_indexing PRIVATE faiss)
+
+add_executable(demo_nndescent EXCLUDE_FROM_ALL demo_nndescent.cpp)
+target_link_libraries(demo_nndescent PRIVATE faiss)
+
+add_executable(demo_sift1M EXCLUDE_FROM_ALL demo_sift1M.cpp)
+target_link_libraries(demo_sift1M PRIVATE faiss)
+
+add_executable(demo_weighted_kmeans EXCLUDE_FROM_ALL demo_weighted_kmeans.cpp)
+target_link_libraries(demo_weighted_kmeans PRIVATE faiss)
+
+add_executable(demo_residual_quantizer EXCLUDE_FROM_ALL demo_residual_quantizer.cpp)
+target_link_libraries(demo_residual_quantizer PRIVATE faiss)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/README.md b/packages/leann-backend-hnsw/third_party/faiss/demos/README.md
new file mode 100644
index 0000000..71a23f2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/README.md
@@ -0,0 +1,28 @@
+
+
+Demos for a few Faiss functionalities
+=====================================
+
+
+demo_auto_tune.py
+-----------------
+
+Demonstrates the auto-tuning functionality of Faiss
+
+
+demo_ondisk_ivf.py
+------------------
+
+Shows how to construct a Faiss index that stores the inverted file
+data on disk, eg. when it does not fit in RAM. The script works on a
+small dataset (sift1M) for demonstration and proceeds in stages:
+
+0: train on the dataset
+
+1-4: build 4 indexes, each containing 1/4 of the dataset. This can be
+done in parallel on several machines
+
+5: merge the 4 indexes into one that is written directly to disk
+(needs not to fit in RAM)
+
+6: load and test the index
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_auto_tune.py b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_auto_tune.py
new file mode 100755
index 0000000..6b67609
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_auto_tune.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python2
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+import os
+import time
+import numpy as np
+
+try:
+ import matplotlib
+ matplotlib.use('Agg')
+ from matplotlib import pyplot
+ graphical_output = True
+except ImportError:
+ graphical_output = False
+
+import faiss
+
+#################################################################
+# Small I/O functions
+#################################################################
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype="int32")
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+def plot_OperatingPoints(ops, nq, **kwargs):
+ ops = ops.optimal_pts
+ n = ops.size() * 2 - 1
+ pyplot.plot([ops.at( i // 2).perf for i in range(n)],
+ [ops.at((i + 1) // 2).t / nq * 1000 for i in range(n)],
+ **kwargs)
+
+
+#################################################################
+# prepare common data for all indexes
+#################################################################
+
+
+
+t0 = time.time()
+
+print("load data")
+
+xt = fvecs_read("sift1M/sift_learn.fvecs")
+xb = fvecs_read("sift1M/sift_base.fvecs")
+xq = fvecs_read("sift1M/sift_query.fvecs")
+
+d = xt.shape[1]
+
+print("load GT")
+
+gt = ivecs_read("sift1M/sift_groundtruth.ivecs")
+gt = gt.astype('int64')
+k = gt.shape[1]
+
+print("prepare criterion")
+
+# criterion = 1-recall at 1
+crit = faiss.OneRecallAtRCriterion(xq.shape[0], 1)
+crit.set_groundtruth(None, gt)
+crit.nnn = k
+
+# indexes that are useful when there is no limitation on memory usage
+unlimited_mem_keys = [
+ "IMI2x10,Flat", "IMI2x11,Flat",
+ "IVF4096,Flat", "IVF16384,Flat",
+ "PCA64,IMI2x10,Flat"]
+
+# memory limited to 16 bytes / vector
+keys_mem_16 = [
+ 'IMI2x10,PQ16', 'IVF4096,PQ16',
+ 'IMI2x10,PQ8+8', 'OPQ16_64,IMI2x10,PQ16'
+ ]
+
+# limited to 32 bytes / vector
+keys_mem_32 = [
+ 'IMI2x10,PQ32', 'IVF4096,PQ32', 'IVF16384,PQ32',
+ 'IMI2x10,PQ16+16',
+ 'OPQ32,IVF4096,PQ32', 'IVF4096,PQ16+16', 'OPQ16,IMI2x10,PQ16+16'
+ ]
+
+# indexes that can run on the GPU
+keys_gpu = [
+ "PCA64,IVF4096,Flat",
+ "PCA64,Flat", "Flat", "IVF4096,Flat", "IVF16384,Flat",
+ "IVF4096,PQ32"]
+
+
+keys_to_test = unlimited_mem_keys
+use_gpu = False
+
+
+if use_gpu:
+ # if this fails, it means that the GPU version was not comp
+ assert faiss.StandardGpuResources, \
+ "Faiss was not compiled with GPU support, or loading _swigfaiss_gpu.so failed"
+ res = faiss.StandardGpuResources()
+ dev_no = 0
+
+# remember results from other index types
+op_per_key = []
+
+
+# keep track of optimal operating points seen so far
+op = faiss.OperatingPoints()
+
+
+for index_key in keys_to_test:
+
+ print("============ key", index_key)
+
+ # make the index described by the key
+ index = faiss.index_factory(d, index_key)
+
+
+ if use_gpu:
+ # transfer to GPU (may be partial)
+ index = faiss.index_cpu_to_gpu(res, dev_no, index)
+ params = faiss.GpuParameterSpace()
+ else:
+ params = faiss.ParameterSpace()
+
+ params.initialize(index)
+
+ print("[%.3f s] train & add" % (time.time() - t0))
+
+ index.train(xt)
+ index.add(xb)
+
+ print("[%.3f s] explore op points" % (time.time() - t0))
+
+ # find operating points for this index
+ opi = params.explore(index, xq, crit)
+
+ print("[%.3f s] result operating points:" % (time.time() - t0))
+ opi.display()
+
+ # update best operating points so far
+ op.merge_with(opi, index_key + " ")
+
+ op_per_key.append((index_key, opi))
+
+ if graphical_output:
+ # graphical output (to tmp/ subdirectory)
+
+ fig = pyplot.figure(figsize=(12, 9))
+ pyplot.xlabel("1-recall at 1")
+ pyplot.ylabel("search time (ms/query, %d threads)" % faiss.omp_get_max_threads())
+ pyplot.gca().set_yscale('log')
+ pyplot.grid()
+ for i2, opi2 in op_per_key:
+ plot_OperatingPoints(opi2, crit.nq, label = i2, marker = 'o')
+ # plot_OperatingPoints(op, crit.nq, label = 'best', marker = 'o', color = 'r')
+ pyplot.legend(loc=2)
+ fig.savefig('tmp/demo_auto_tune.png')
+
+
+print("[%.3f s] final result:" % (time.time() - t0))
+
+op.display()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_client_server_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_client_server_ivf.py
new file mode 100755
index 0000000..e89dd28
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_client_server_ivf.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import sys
+import numpy as np
+import faiss
+
+from faiss.contrib.client_server import run_index_server, ClientIndex
+
+
+#################################################################
+# Small I/O functions
+#################################################################
+
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype='int32')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+#################################################################
+# Main program
+#################################################################
+
+stage = int(sys.argv[1])
+
+tmpdir = '/tmp/'
+
+if stage == 0:
+ # train the index
+ xt = fvecs_read("sift1M/sift_learn.fvecs")
+ index = faiss.index_factory(xt.shape[1], "IVF4096,Flat")
+ print("training index")
+ index.train(xt)
+ print("write " + tmpdir + "trained.index")
+ faiss.write_index(index, tmpdir + "trained.index")
+
+
+if 1 <= stage <= 4:
+ # add 1/4 of the database to 4 independent indexes
+ bno = stage - 1
+ xb = fvecs_read("sift1M/sift_base.fvecs")
+ i0, i1 = int(bno * xb.shape[0] / 4), int((bno + 1) * xb.shape[0] / 4)
+ index = faiss.read_index(tmpdir + "trained.index")
+ print("adding vectors %d:%d" % (i0, i1))
+ index.add_with_ids(xb[i0:i1], np.arange(i0, i1))
+ print("write " + tmpdir + "block_%d.index" % bno)
+ faiss.write_index(index, tmpdir + "block_%d.index" % bno)
+
+
+machine_ports = [
+ ('localhost', 12010),
+ ('localhost', 12011),
+ ('localhost', 12012),
+ ('localhost', 12013),
+]
+v6 = False
+
+if 5 <= stage <= 8:
+ # load an index slice and launch index
+ bno = stage - 5
+
+ fname = tmpdir + "block_%d.index" % bno
+ print("read " + fname)
+ index = faiss.read_index(fname)
+
+ port = machine_ports[bno][1]
+ run_index_server(index, port, v6=v6)
+
+
+if stage == 9:
+ client_index = ClientIndex(machine_ports)
+ print('index size:', client_index.ntotal)
+ client_index.set_nprobe(16)
+
+ # load query vectors and ground-truth
+ xq = fvecs_read("sift1M/sift_query.fvecs")
+ gt = ivecs_read("sift1M/sift_groundtruth.ivecs")
+
+ D, I = client_index.search(xq, 5)
+
+ recall_at_1 = (I[:, :1] == gt[:, :1]).sum() / float(xq.shape[0])
+ print("recall@1: %.3f" % recall_at_1)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_distributed_kmeans_torch.py b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_distributed_kmeans_torch.py
new file mode 100644
index 0000000..c726495
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_distributed_kmeans_torch.py
@@ -0,0 +1,173 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+
+import torch
+import torch.distributed
+
+import faiss
+
+import faiss.contrib.torch_utils
+from faiss.contrib.torch import clustering
+from faiss.contrib import datasets
+
+
+class DatasetAssignDistributedGPU(clustering.DatasetAssign):
+ """
+ There is one instance per worker, each worker has a dataset shard.
+ The non-master workers do not run through the k-means function, so some
+ code has run it to keep the workers in sync.
+ """
+
+ def __init__(self, res, x, rank, nproc):
+ clustering.DatasetAssign.__init__(self, x)
+ self.res = res
+ self.rank = rank
+ self.nproc = nproc
+ self.device = x.device
+
+ n = len(x)
+ sizes = torch.zeros(nproc, device=self.device, dtype=torch.int64)
+ sizes[rank] = n
+ torch.distributed.all_gather(
+ [sizes[i:i + 1] for i in range(nproc)], sizes[rank:rank + 1])
+ self.sizes = sizes.cpu().numpy()
+
+ # begin & end of each shard
+ self.cs = np.zeros(nproc + 1, dtype='int64')
+ self.cs[1:] = np.cumsum(self.sizes)
+
+ def count(self):
+ return int(self.sizes.sum())
+
+ def int_to_slaves(self, i):
+ " broadcast an int to all workers "
+ rank = self.rank
+ tab = torch.zeros(1, device=self.device, dtype=torch.int64)
+ if rank == 0:
+ tab[0] = i
+ else:
+ assert i is None
+ torch.distributed.broadcast(tab, 0)
+ return tab.item()
+
+ def get_subset(self, indices):
+ rank = self.rank
+ assert rank == 0 or indices is None
+
+ len_indices = self.int_to_slaves(len(indices) if rank == 0 else None)
+
+ if rank == 0:
+ indices = torch.from_numpy(indices).to(self.device)
+ else:
+ indices = torch.zeros(
+ len_indices, dtype=torch.int64, device=self.device)
+ torch.distributed.broadcast(indices, 0)
+
+ # select subset of indices
+
+ i0, i1 = self.cs[rank], self.cs[rank + 1]
+
+ mask = torch.logical_and(indices < i1, indices >= i0)
+ output = torch.zeros(
+ len_indices, self.x.shape[1],
+ dtype=self.x.dtype, device=self.device)
+ output[mask] = self.x[indices[mask] - i0]
+ torch.distributed.reduce(output, 0) # sum
+ if rank == 0:
+ return output
+ else:
+ return None
+
+ def perform_search(self, centroids):
+ assert False, "shoudl not be called"
+
+ def assign_to(self, centroids, weights=None):
+ assert weights is None
+
+ rank, nproc = self.rank, self.nproc
+ assert rank == 0 or centroids is None
+ nc = self.int_to_slaves(len(centroids) if rank == 0 else None)
+
+ if rank != 0:
+ centroids = torch.zeros(
+ nc, self.x.shape[1], dtype=self.x.dtype, device=self.device)
+ torch.distributed.broadcast(centroids, 0)
+
+ # perform search
+ D, I = faiss.knn_gpu(
+ self.res, self.x, centroids, 1, device=self.device.index)
+
+ I = I.ravel()
+ D = D.ravel()
+
+ sum_per_centroid = torch.zeros_like(centroids)
+ if weights is None:
+ sum_per_centroid.index_add_(0, I, self.x)
+ else:
+ sum_per_centroid.index_add_(0, I, self.x * weights[:, None])
+
+ torch.distributed.reduce(sum_per_centroid, 0)
+
+ if rank == 0:
+ # gather deos not support tensors of different sizes
+ # should be implemented with point-to-point communication
+ assert np.all(self.sizes == self.sizes[0])
+ device = self.device
+ all_I = torch.zeros(self.count(), dtype=I.dtype, device=device)
+ all_D = torch.zeros(self.count(), dtype=D.dtype, device=device)
+ torch.distributed.gather(
+ I, [all_I[self.cs[r]:self.cs[r + 1]] for r in range(nproc)],
+ dst=0,
+ )
+ torch.distributed.gather(
+ D, [all_D[self.cs[r]:self.cs[r + 1]] for r in range(nproc)],
+ dst=0,
+ )
+ return all_I.cpu().numpy(), all_D, sum_per_centroid
+ else:
+ torch.distributed.gather(I, None, dst=0)
+ torch.distributed.gather(D, None, dst=0)
+ return None
+
+
+if __name__ == "__main__":
+
+ torch.distributed.init_process_group(
+ backend="nccl",
+ )
+ rank = torch.distributed.get_rank()
+ nproc = torch.distributed.get_world_size()
+
+ # current version does only support shards of the same size
+ ds = datasets.SyntheticDataset(32, 10000, 0, 0, seed=1234 + rank)
+ x = ds.get_train()
+
+ device = torch.device(f"cuda:{rank}")
+
+ torch.cuda.set_device(device)
+ x = torch.from_numpy(x).to(device)
+ res = faiss.StandardGpuResources()
+
+ da = DatasetAssignDistributedGPU(res, x, rank, nproc)
+
+ k = 1000
+ niter = 25
+
+ if rank == 0:
+ print(f"sizes = {da.sizes}")
+ centroids, iteration_stats = clustering.kmeans(
+ k, da, niter=niter, return_stats=True)
+ print("clusters:", centroids.cpu().numpy())
+ else:
+ # make sure the iterations are aligned with master
+ da.get_subset(None)
+
+ for _ in range(niter):
+ da.assign_to(None)
+
+ torch.distributed.barrier()
+ print("Done")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_imi_flat.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_imi_flat.cpp
new file mode 100644
index 0000000..a7f70bc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_imi_flat.cpp
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <sys/time.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexPQ.h>
+
+double elapsed() {
+ struct timeval tv;
+ gettimeofday(&tv, nullptr);
+ return tv.tv_sec + tv.tv_usec * 1e-6;
+}
+
+int main() {
+ double t0 = elapsed();
+
+ // dimension of the vectors to index
+ int d = 128;
+
+ // size of the database we plan to index
+ size_t nb = 1000 * 1000;
+
+ // make a set of nt training vectors in the unit cube
+ // (could be the database)
+ size_t nt = 100 * 1000;
+
+ //---------------------------------------------------------------
+ // Define the core quantizer
+ // We choose a multiple inverted index for faster training with less data
+ // and because it usually offers best accuracy/speed trade-offs
+ //
+ // We here assume that its lifespan of this coarse quantizer will cover the
+ // lifespan of the inverted-file quantizer IndexIVFFlat below
+ // With dynamic allocation, one may give the responsibility to free the
+ // quantizer to the inverted-file index (with attribute do_delete_quantizer)
+ //
+ // Note: a regular clustering algorithm would be defined as:
+ // faiss::IndexFlatL2 coarse_quantizer (d);
+ //
+ // Use nhash=2 subquantizers used to define the product coarse quantizer
+ // Number of bits: we will have 2^nbits_coarse centroids per subquantizer
+ // meaning (2^12)^nhash distinct inverted lists
+ size_t nhash = 2;
+ size_t nbits_subq = int(log2(nb + 1) / 2); // good choice in general
+ size_t ncentroids = 1 << (nhash * nbits_subq); // total # of centroids
+
+ faiss::MultiIndexQuantizer coarse_quantizer(d, nhash, nbits_subq);
+
+ printf("IMI (%ld,%ld): %ld virtual centroids (target: %ld base vectors)",
+ nhash,
+ nbits_subq,
+ ncentroids,
+ nb);
+
+ // the coarse quantizer should not be dealloced before the index
+ // 4 = nb of bytes per code (d must be a multiple of this)
+ // 8 = nb of bits per sub-code (almost always 8)
+ faiss::MetricType metric = faiss::METRIC_L2; // can be METRIC_INNER_PRODUCT
+ faiss::IndexIVFFlat index(&coarse_quantizer, d, ncentroids, metric);
+ index.quantizer_trains_alone = true;
+
+ // define the number of probes. 2048 is for high-dim, overkilled in practice
+ // Use 4-1024 depending on the trade-off speed accuracy that you want
+ index.nprobe = 2048;
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ { // training
+ printf("[%.3f s] Generating %ld vectors in %dD for training\n",
+ elapsed() - t0,
+ nt,
+ d);
+
+ std::vector<float> trainvecs(nt * d);
+ for (size_t i = 0; i < nt * d; i++) {
+ trainvecs[i] = distrib(rng);
+ }
+
+ printf("[%.3f s] Training the index\n", elapsed() - t0);
+ index.verbose = true;
+ index.train(nt, trainvecs.data());
+ }
+
+ size_t nq;
+ std::vector<float> queries;
+
+ { // populating the database
+ printf("[%.3f s] Building a dataset of %ld vectors to index\n",
+ elapsed() - t0,
+ nb);
+
+ std::vector<float> database(nb * d);
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+
+ printf("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
+
+ index.add(nb, database.data());
+
+ // remember a few elements from the database as queries
+ int i0 = 1234;
+ int i1 = 1244;
+
+ nq = i1 - i0;
+ queries.resize(nq * d);
+ for (int i = i0; i < i1; i++) {
+ for (int j = 0; j < d; j++) {
+ queries[(i - i0) * d + j] = database[i * d + j];
+ }
+ }
+ }
+
+ { // searching the database
+ int k = 5;
+ printf("[%.3f s] Searching the %d nearest neighbors "
+ "of %ld vectors in the index\n",
+ elapsed() - t0,
+ k,
+ nq);
+
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<float> dis(k * nq);
+
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+
+ printf("[%.3f s] Query results (vector ids, then distances):\n",
+ elapsed() - t0);
+
+ for (int i = 0; i < nq; i++) {
+ printf("query %2d: ", i);
+ for (int j = 0; j < k; j++) {
+ printf("%7ld ", nns[j + i * k]);
+ }
+ printf("\n dis: ");
+ for (int j = 0; j < k; j++) {
+ printf("%7g ", dis[j + i * k]);
+ }
+ printf("\n");
+ }
+ }
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_imi_pq.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_imi_pq.cpp
new file mode 100644
index 0000000..1e63873
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_imi_pq.cpp
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <sys/time.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/index_io.h>
+
+double elapsed() {
+ struct timeval tv;
+ gettimeofday(&tv, nullptr);
+ return tv.tv_sec + tv.tv_usec * 1e-6;
+}
+
+int main() {
+ double t0 = elapsed();
+
+ // dimension of the vectors to index
+ int d = 64;
+
+ // size of the database we plan to index
+ size_t nb = 1000 * 1000;
+ size_t add_bs = 10000; // # size of the blocks to add
+
+ // make a set of nt training vectors in the unit cube
+ // (could be the database)
+ size_t nt = 100 * 1000;
+
+ //---------------------------------------------------------------
+ // Define the core quantizer
+ // We choose a multiple inverted index for faster training with less data
+ // and because it usually offers best accuracy/speed trade-offs
+ //
+ // We here assume that its lifespan of this coarse quantizer will cover the
+ // lifespan of the inverted-file quantizer IndexIVFFlat below
+ // With dynamic allocation, one may give the responsibility to free the
+ // quantizer to the inverted-file index (with attribute do_delete_quantizer)
+ //
+ // Note: a regular clustering algorithm would be defined as:
+ // faiss::IndexFlatL2 coarse_quantizer (d);
+ //
+ // Use nhash=2 subquantizers used to define the product coarse quantizer
+ // Number of bits: we will have 2^nbits_coarse centroids per subquantizer
+ // meaning (2^12)^nhash distinct inverted lists
+ //
+ // The parameter bytes_per_code is determined by the memory
+ // constraint, the dataset will use nb * (bytes_per_code + 8)
+ // bytes.
+ //
+ // The parameter nbits_subq is determined by the size of the dataset to
+ // index.
+ //
+ size_t nhash = 2;
+ size_t nbits_subq = 9;
+ size_t ncentroids = 1 << (nhash * nbits_subq); // total # of centroids
+ int bytes_per_code = 16;
+
+ faiss::MultiIndexQuantizer coarse_quantizer(d, nhash, nbits_subq);
+
+ printf("IMI (%ld,%ld): %ld virtual centroids (target: %ld base vectors)",
+ nhash,
+ nbits_subq,
+ ncentroids,
+ nb);
+
+ // the coarse quantizer should not be dealloced before the index
+ // 4 = nb of bytes per code (d must be a multiple of this)
+ // 8 = nb of bits per sub-code (almost always 8)
+ faiss::IndexIVFPQ index(
+ &coarse_quantizer, d, ncentroids, bytes_per_code, 8);
+ index.quantizer_trains_alone = true;
+
+ // define the number of probes. 2048 is for high-dim, overkill in practice
+ // Use 4-1024 depending on the trade-off speed accuracy that you want
+ index.nprobe = 2048;
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ { // training.
+
+ // The distribution of the training vectors should be the same
+ // as the database vectors. It could be a sub-sample of the
+ // database vectors, if sampling is not biased. Here we just
+ // randomly generate the vectors.
+
+ printf("[%.3f s] Generating %ld vectors in %dD for training\n",
+ elapsed() - t0,
+ nt,
+ d);
+
+ std::vector<float> trainvecs(nt * d);
+ for (size_t i = 0; i < nt; i++) {
+ for (size_t j = 0; j < d; j++) {
+ trainvecs[i * d + j] = distrib(rng);
+ }
+ }
+
+ printf("[%.3f s] Training the index\n", elapsed() - t0);
+ index.verbose = true;
+ index.train(nt, trainvecs.data());
+ }
+
+ // the index can be re-loaded later with
+ // faiss::Index * idx = faiss::read_index("/tmp/trained_index.faissindex");
+ faiss::write_index(&index, "/tmp/trained_index.faissindex");
+
+ size_t nq;
+ std::vector<float> queries;
+
+ { // populating the database
+ printf("[%.3f s] Building a dataset of %ld vectors to index\n",
+ elapsed() - t0,
+ nb);
+
+ std::vector<float> database(nb * d);
+ std::vector<faiss::idx_t> ids(nb);
+ for (size_t i = 0; i < nb; i++) {
+ for (size_t j = 0; j < d; j++) {
+ database[i * d + j] = distrib(rng);
+ }
+ ids[i] = 8760000000L + i;
+ }
+
+ printf("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
+
+ for (size_t begin = 0; begin < nb; begin += add_bs) {
+ size_t end = std::min(begin + add_bs, nb);
+ index.add_with_ids(
+ end - begin,
+ database.data() + d * begin,
+ ids.data() + begin);
+ }
+
+ // remember a few elements from the database as queries
+ int i0 = 1234;
+ int i1 = 1244;
+
+ nq = i1 - i0;
+ queries.resize(nq * d);
+ for (int i = i0; i < i1; i++) {
+ for (int j = 0; j < d; j++) {
+ queries[(i - i0) * d + j] = database[i * d + j];
+ }
+ }
+ }
+
+ // A few notes on the internal format of the index:
+ //
+ // - the positing lists for PQ codes are index.codes, which is a
+ // std::vector < std::vector<uint8_t> >
+ // if n is the length of posting list #i, codes[i] has length
+ // bytes_per_code * n
+ //
+ // - the corresponding ids are stored in index.ids
+ //
+ // - given a vector float *x, finding which k centroids are
+ // closest to it (ie to find the nearest neighbors) can be done with
+ //
+ // faiss::idx_t *centroid_ids = new faiss::idx_t[k];
+ // float *distances = new float[k];
+ // index.quantizer->search (1, x, k, dis, centroids_ids);
+ //
+
+ faiss::write_index(&index, "/tmp/populated_index.faissindex");
+
+ { // searching the database
+ int k = 5;
+ printf("[%.3f s] Searching the %d nearest neighbors "
+ "of %ld vectors in the index\n",
+ elapsed() - t0,
+ k,
+ nq);
+
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<float> dis(k * nq);
+
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+
+ printf("[%.3f s] Query results (vector ids, then distances):\n",
+ elapsed() - t0);
+
+ for (int i = 0; i < nq; i++) {
+ printf("query %2d: ", i);
+ for (int j = 0; j < k; j++) {
+ printf("%7ld ", nns[j + i * k]);
+ }
+ printf("\n dis: ");
+ for (int j = 0; j < k; j++) {
+ printf("%7g ", dis[j + i * k]);
+ }
+ printf("\n");
+ }
+ }
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_ivfpq_indexing.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_ivfpq_indexing.cpp
new file mode 100644
index 0000000..aa84542
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_ivfpq_indexing.cpp
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <sys/time.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/index_io.h>
+
+double elapsed() {
+ struct timeval tv;
+ gettimeofday(&tv, nullptr);
+ return tv.tv_sec + tv.tv_usec * 1e-6;
+}
+
+int main() {
+ double t0 = elapsed();
+
+ // dimension of the vectors to index
+ int d = 128;
+
+ // size of the database we plan to index
+ size_t nb = 200 * 1000;
+
+ // make a set of nt training vectors in the unit cube
+ // (could be the database)
+ size_t nt = 100 * 1000;
+
+ // make the index object and train it
+ faiss::IndexFlatL2 coarse_quantizer(d);
+
+ // a reasonable number of centroids to index nb vectors
+ int ncentroids = int(4 * sqrt(nb));
+
+ // the coarse quantizer should not be dealloced before the index
+ // 4 = nb of bytes per code (d must be a multiple of this)
+ // 8 = nb of bits per sub-code (almost always 8)
+ faiss::IndexIVFPQ index(&coarse_quantizer, d, ncentroids, 4, 8);
+
+ std::mt19937 rng;
+
+ { // training
+ printf("[%.3f s] Generating %ld vectors in %dD for training\n",
+ elapsed() - t0,
+ nt,
+ d);
+
+ std::vector<float> trainvecs(nt * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nt * d; i++) {
+ trainvecs[i] = distrib(rng);
+ }
+
+ printf("[%.3f s] Training the index\n", elapsed() - t0);
+ index.verbose = true;
+
+ index.train(nt, trainvecs.data());
+ }
+
+ { // I/O demo
+ const char* outfilename = "/tmp/index_trained.faissindex";
+ printf("[%.3f s] storing the pre-trained index to %s\n",
+ elapsed() - t0,
+ outfilename);
+
+ write_index(&index, outfilename);
+ }
+
+ size_t nq;
+ std::vector<float> queries;
+
+ { // populating the database
+ printf("[%.3f s] Building a dataset of %ld vectors to index\n",
+ elapsed() - t0,
+ nb);
+
+ std::vector<float> database(nb * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+
+ printf("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
+
+ index.add(nb, database.data());
+
+ printf("[%.3f s] imbalance factor: %g\n",
+ elapsed() - t0,
+ index.invlists->imbalance_factor());
+
+ // remember a few elements from the database as queries
+ int i0 = 1234;
+ int i1 = 1243;
+
+ nq = i1 - i0;
+ queries.resize(nq * d);
+ for (int i = i0; i < i1; i++) {
+ for (int j = 0; j < d; j++) {
+ queries[(i - i0) * d + j] = database[i * d + j];
+ }
+ }
+ }
+
+ { // searching the database
+ int k = 5;
+ printf("[%.3f s] Searching the %d nearest neighbors "
+ "of %ld vectors in the index\n",
+ elapsed() - t0,
+ k,
+ nq);
+
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<float> dis(k * nq);
+
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+
+ printf("[%.3f s] Query results (vector ids, then distances):\n",
+ elapsed() - t0);
+
+ for (int i = 0; i < nq; i++) {
+ printf("query %2d: ", i);
+ for (int j = 0; j < k; j++) {
+ printf("%7ld ", nns[j + i * k]);
+ }
+ printf("\n dis: ");
+ for (int j = 0; j < k; j++) {
+ printf("%7g ", dis[j + i * k]);
+ }
+ printf("\n");
+ }
+
+ printf("note that the nearest neighbor is not at "
+ "distance 0 due to quantization errors\n");
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_nndescent.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_nndescent.cpp
new file mode 100644
index 0000000..9200a62
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_nndescent.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexNNDescent.h>
+
+using namespace std::chrono;
+
+int main(void) {
+ // dimension of the vectors to index
+ int d = 64;
+ int K = 64;
+
+ // size of the database we plan to index
+ size_t nb = 10000;
+
+ std::mt19937 rng(12345);
+
+ // make the index object and train it
+ faiss::IndexNNDescentFlat index(d, K, faiss::METRIC_L2);
+ index.nndescent.S = 10;
+ index.nndescent.R = 32;
+ index.nndescent.L = K;
+ index.nndescent.iter = 10;
+ index.verbose = true;
+
+ // generate labels by IndexFlat
+ faiss::IndexFlat bruteforce(d, faiss::METRIC_L2);
+
+ std::vector<float> database(nb * d);
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = rng() % 1024;
+ }
+
+ { // populating the database
+ index.add(nb, database.data());
+ bruteforce.add(nb, database.data());
+ }
+
+ size_t nq = 1000;
+
+ { // searching the database
+ printf("Searching ...\n");
+ index.nndescent.search_L = 50;
+
+ std::vector<float> queries(nq * d);
+ for (size_t i = 0; i < nq * d; i++) {
+ queries[i] = rng() % 1024;
+ }
+
+ int k = 5;
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<faiss::idx_t> gt_nns(k * nq);
+ std::vector<float> dis(k * nq);
+
+ auto start = high_resolution_clock::now();
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+ auto end = high_resolution_clock::now();
+
+ // find exact kNNs by brute force search
+ bruteforce.search(nq, queries.data(), k, dis.data(), gt_nns.data());
+
+ int recalls = 0;
+ for (size_t i = 0; i < nq; ++i) {
+ for (int n = 0; n < k; n++) {
+ for (int m = 0; m < k; m++) {
+ if (nns[i * k + n] == gt_nns[i * k + m]) {
+ recalls += 1;
+ }
+ }
+ }
+ }
+ float recall = 1.0f * recalls / (k * nq);
+ auto t = duration_cast<microseconds>(end - start).count();
+ int qps = nq * 1.0f * 1000 * 1000 / t;
+
+ printf("Recall@%d: %f, QPS: %d\n", k, recall, qps);
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_ondisk_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_ondisk_ivf.py
new file mode 100755
index 0000000..e2d57fa
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_ondisk_ivf.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import sys
+import numpy as np
+import faiss
+from faiss.contrib.ondisk import merge_ondisk
+
+#################################################################
+# Small I/O functions
+#################################################################
+
+
+def ivecs_read(fname):
+ a = np.fromfile(fname, dtype='int32')
+ d = a[0]
+ return a.reshape(-1, d + 1)[:, 1:].copy()
+
+
+def fvecs_read(fname):
+ return ivecs_read(fname).view('float32')
+
+
+#################################################################
+# Main program
+#################################################################
+
+stage = int(sys.argv[1])
+
+tmpdir = '/tmp/'
+
+if stage == 0:
+ # train the index
+ xt = fvecs_read("sift1M/sift_learn.fvecs")
+ index = faiss.index_factory(xt.shape[1], "IVF4096,Flat")
+ print("training index")
+ index.train(xt)
+ print("write " + tmpdir + "trained.index")
+ faiss.write_index(index, tmpdir + "trained.index")
+
+
+if 1 <= stage <= 4:
+ # add 1/4 of the database to 4 independent indexes
+ bno = stage - 1
+ xb = fvecs_read("sift1M/sift_base.fvecs")
+ i0, i1 = int(bno * xb.shape[0] / 4), int((bno + 1) * xb.shape[0] / 4)
+ index = faiss.read_index(tmpdir + "trained.index")
+ print("adding vectors %d:%d" % (i0, i1))
+ index.add_with_ids(xb[i0:i1], np.arange(i0, i1))
+ print("write " + tmpdir + "block_%d.index" % bno)
+ faiss.write_index(index, tmpdir + "block_%d.index" % bno)
+
+if stage == 5:
+
+ print('loading trained index')
+ # construct the output index
+ index = faiss.read_index(tmpdir + "trained.index")
+
+ block_fnames = [
+ tmpdir + "block_%d.index" % bno
+ for bno in range(4)
+ ]
+
+ merge_ondisk(index, block_fnames, tmpdir + "merged_index.ivfdata")
+
+ print("write " + tmpdir + "populated.index")
+ faiss.write_index(index, tmpdir + "populated.index")
+
+
+if stage == 6:
+ # perform a search from disk
+ print("read " + tmpdir + "populated.index")
+ index = faiss.read_index(tmpdir + "populated.index")
+ index.nprobe = 16
+
+ # load query vectors and ground-truth
+ xq = fvecs_read("sift1M/sift_query.fvecs")
+ gt = ivecs_read("sift1M/sift_groundtruth.ivecs")
+
+ D, I = index.search(xq, 5)
+
+ recall_at_1 = (I[:, :1] == gt[:, :1]).sum() / float(xq.shape[0])
+ print("recall@1: %.3f" % recall_at_1)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_qinco.py b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_qinco.py
new file mode 100644
index 0000000..b89bb68
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_qinco.py
@@ -0,0 +1,77 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""
+This demonstrates how to reproduce the QINCo paper results using the Faiss
+QINCo implementation. The code loads the reference model because training
+is not implemented in Faiss.
+
+Prepare the data with
+
+cd /tmp
+
+# get the reference qinco code
+git clone https://github.com/facebookresearch/Qinco.git
+
+# get the data
+wget https://dl.fbaipublicfiles.com/QINCo/datasets/bigann/bigann1M.bvecs
+
+# get the model
+wget https://dl.fbaipublicfiles.com/QINCo/models/bigann_8x8_L2.pt
+
+"""
+
+import numpy as np
+from faiss.contrib.vecs_io import bvecs_mmap
+import sys
+import time
+import torch
+import faiss
+
+# make sure pickle deserialization will work
+sys.path.append("/tmp/Qinco")
+import model_qinco
+
+with torch.no_grad():
+
+ qinco = torch.load("/tmp/bigann_8x8_L2.pt", weights_only=False)
+ qinco.eval()
+ # print(qinco)
+ if True:
+ torch.set_num_threads(1)
+ faiss.omp_set_num_threads(1)
+
+ x_base = bvecs_mmap("/tmp/bigann1M.bvecs")[:1000].astype('float32')
+ x_scaled = torch.from_numpy(x_base) / qinco.db_scale
+
+ t0 = time.time()
+ codes, _ = qinco.encode(x_scaled)
+ x_decoded_scaled = qinco.decode(codes)
+ print(f"Pytorch encode {time.time() - t0:.3f} s")
+ # multi-thread: 1.13s, single-thread: 7.744
+
+ x_decoded = x_decoded_scaled.numpy() * qinco.db_scale
+
+ err = ((x_decoded - x_base) ** 2).sum(1).mean()
+ print("MSE=", err) # = 14211.956, near the L=2 result in Fig 4 of the paper
+
+ qinco2 = faiss.QINCo(qinco)
+ t0 = time.time()
+ codes2 = qinco2.encode(faiss.Tensor2D(x_scaled))
+ x_decoded2 = qinco2.decode(codes2).numpy() * qinco.db_scale
+ print(f"Faiss encode {time.time() - t0:.3f} s")
+ # multi-thread: 3.2s, single thread: 7.019
+
+ # these tests don't work because there are outlier encodings
+ # np.testing.assert_array_equal(codes.numpy(), codes2.numpy())
+ # np.testing.assert_allclose(x_decoded, x_decoded2)
+
+ ndiff = (codes.numpy() != codes2.numpy()).sum() / codes.numel()
+ assert ndiff < 0.01
+ ndiff = (((x_decoded - x_decoded2) ** 2).sum(1) > 1e-5).sum()
+ assert ndiff / len(x_base) < 0.01
+
+ err = ((x_decoded2 - x_base) ** 2).sum(1).mean()
+ print("MSE=", err) # = 14213.551
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_residual_quantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_residual_quantizer.cpp
new file mode 100644
index 0000000..2f88be3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_residual_quantizer.cpp
@@ -0,0 +1,297 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <climits>
+#include <cstdio>
+#include <memory>
+
+#include <faiss/IVFlib.h>
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/MetricType.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+/* This demo file shows how to:
+ * - use a DistanceComputer to compute distances with encoded vectors
+ * - in the context of an IVF, how to split an additive quantizer into an
+ * AdditiveCoarseQuantizer and a ResidualQuantizer, in two different ways, with
+ * and without storing the prefix.
+ */
+
+int main() {
+ /******************************************
+ * Generate a test dataset
+ ******************************************/
+ using idx_t = faiss::idx_t;
+ size_t d = 128;
+ size_t nt = 10000;
+ size_t nb = 10000;
+ size_t nq = 100;
+ double t0 = faiss::getmillisecs();
+
+ auto tic = [t0]() {
+ printf("[%.3f s] ", (faiss::getmillisecs() - t0) / 1000);
+ };
+
+ tic();
+ printf("samping dataset of %zd dim vectors, Q %zd B %zd T %zd\n",
+ d,
+ nq,
+ nb,
+ nt);
+
+ std::vector<float> buf(d * (nq + nt + nb));
+ faiss::rand_smooth_vectors(nq + nt + nb, d, buf.data(), 1234);
+ const float* xt = buf.data();
+ const float* xb = buf.data() + nt * d;
+ const float* xq = buf.data() + (nt + nb) * d;
+
+ idx_t k = 10;
+ std::vector<idx_t> gt(k * nq);
+ std::vector<float> unused(k * nq);
+ tic();
+ printf("compute ground truth, k=%zd\n", k);
+ faiss::knn_L2sqr(xq, xb, d, nq, nb, k, unused.data(), gt.data());
+
+ // a function to compute the accuracy
+ auto accuracy = [&](const idx_t* I) {
+ idx_t accu = 0;
+ for (idx_t q = 0; q < nq; q++) {
+ accu += faiss::ranklist_intersection_size(
+ k, gt.data() + q * k, k, I + q * k);
+ }
+ return double(accu) / (k * nq);
+ };
+
+ /******************************************
+ * Prepare the residual quantizer
+ ******************************************/
+
+ faiss::ResidualQuantizer rq(
+ d, 7, 6, faiss::AdditiveQuantizer::ST_norm_qint8);
+ // do cheap an inaccurate training
+ rq.cp.niter = 5;
+ rq.max_beam_size = 5;
+ rq.train_type = 0;
+ tic();
+ printf("training the residual quantizer beam_size=%d\n", rq.max_beam_size);
+ rq.train(nt, xt);
+
+ tic();
+ printf("encoding the database, code_size=%zd\n", rq.code_size);
+ size_t code_size = rq.code_size;
+ std::vector<uint8_t> raw_codes(nb * code_size);
+ rq.compute_codes(xb, raw_codes.data(), nb);
+
+ /****************************************************************
+ * Make an index that uses that residual quantizer
+ * Verify that a distance computer gives the same distances
+ ****************************************************************/
+ {
+ faiss::IndexResidualQuantizer index(
+ rq.d, rq.nbits, faiss::METRIC_L2, rq.search_type);
+
+ // override trained index
+ index.rq = rq;
+ index.is_trained = true;
+
+ // override vectors
+ index.codes = faiss::MaybeOwnedVector<uint8_t>(raw_codes);
+ index.ntotal = nb;
+
+ tic();
+ printf("IndexResidualQuantizer ready, searching\n");
+
+ std::vector<float> D(k * nq);
+ std::vector<idx_t> I(k * nq);
+ index.search(nq, xq, k, D.data(), I.data());
+
+ tic();
+ printf("Accuracy (intersection @ %zd): %.3f\n", k, accuracy(I.data()));
+ std::unique_ptr<faiss::FlatCodesDistanceComputer> dc(
+ index.get_FlatCodesDistanceComputer());
+
+ float max_diff12 = 0, max_diff13 = 0;
+
+ for (idx_t q = 0; q < nq; q++) {
+ const float* query = xq + q * d;
+ dc->set_query(query);
+ for (int i = 0; i < k; i++) {
+ // 3 ways of computing the same distance
+
+ // distance returned by the index
+ float dis1 = D[q * k + i];
+
+ // distance returned by the DistanceComputer that accesses the
+ // index
+ idx_t db_index = I[q * k + i];
+ float dis2 = (*dc)(db_index);
+
+ // distance computer from a code that does not belong to the
+ // index
+ const uint8_t* code = raw_codes.data() + code_size * db_index;
+ float dis3 = dc->distance_to_code(code);
+
+ max_diff12 = std::max(std::abs(dis1 - dis2), max_diff12);
+ max_diff13 = std::max(std::abs(dis1 - dis3), max_diff13);
+ }
+ }
+ tic();
+ printf("Max DistanceComputer discrepancy 1-2: %g 1-3: %g\n",
+ max_diff12,
+ max_diff13);
+ }
+
+ /****************************************************************
+ * Make an IVF index that uses the first 2 levels as a coarse quantizer
+ * The IVF codes contain the full code (ie. redundant with the coarse
+ *quantizer code)
+ ****************************************************************/
+ {
+ // build a coarse quantizer from the 2 first levels of the RQ
+ std::vector<size_t> nbits(2);
+ std::copy(rq.nbits.begin(), rq.nbits.begin() + 2, nbits.begin());
+ faiss::ResidualCoarseQuantizer rcq(rq.d, nbits);
+
+ // set the coarse quantizer from the 2 first quantizers
+ rcq.rq.initialize_from(rq);
+ rcq.is_trained = true;
+ rcq.ntotal = (idx_t)1 << rcq.rq.tot_bits;
+
+ // settings for exhaustive search in RCQ
+ rcq.centroid_norms.resize(rcq.ntotal);
+ rcq.aq->compute_centroid_norms(rcq.centroid_norms.data());
+ rcq.beam_factor = -1.0; // use exact search
+ size_t nlist = rcq.ntotal;
+ tic();
+ printf("RCQ nlist = %zd tot_bits=%zd\n", nlist, rcq.rq.tot_bits);
+
+ // build a IVFResidualQuantizer from that
+ faiss::IndexIVFResidualQuantizer index(
+ &rcq, rcq.d, nlist, rq.nbits, faiss::METRIC_L2, rq.search_type);
+ index.by_residual = false;
+ index.rq = rq;
+ index.is_trained = true;
+
+ // there are 3 ways of filling up the index...
+ for (std::string filled_with : {"add", "manual", "derived"}) {
+ tic();
+ printf("filling up the index with %s, code_size=%zd\n",
+ filled_with.c_str(),
+ index.code_size);
+
+ index.reset();
+
+ if (filled_with == "add") {
+ // standard add method
+ index.add(nb, xb);
+ } else if (filled_with == "manual") {
+ // compute inverted lists and add elements manually
+ // fill in the inverted index manually
+ faiss::InvertedLists& invlists = *index.invlists;
+
+ // assign vectors to inverted lists
+ std::vector<idx_t> listnos(nb);
+ std::vector<float> unused(nb);
+ rcq.search(nb, xb, 1, unused.data(), listnos.data());
+
+ // populate inverted lists
+ for (idx_t i = 0; i < nb; i++) {
+ invlists.add_entry(
+ listnos[i], i, &raw_codes[i * code_size]);
+ }
+
+ index.ntotal = nb;
+ } else if (filled_with == "derived") {
+ // Since we have the raw codes precomputed, their prefix is the
+ // inverted list index, so let's use that.
+ faiss::InvertedLists& invlists = *index.invlists;
+
+ // populate inverted lists
+ for (idx_t i = 0; i < nb; i++) {
+ const uint8_t* code = &raw_codes[i * code_size];
+ faiss::BitstringReader rd(code, code_size);
+ idx_t list_no =
+ rd.read(rcq.rq.tot_bits); // read the list number
+ invlists.add_entry(list_no, i, code);
+ }
+
+ index.ntotal = nb;
+ }
+
+ tic();
+ printf("Index filled in\n");
+
+ for (int nprobe : {1, 4, 16, 64, int(nlist)}) {
+ printf("setting nprobe=%-4d", nprobe);
+
+ index.nprobe = nprobe;
+ std::vector<float> D(k * nq);
+ std::vector<idx_t> I(k * nq);
+ index.search(nq, xq, k, D.data(), I.data());
+
+ tic();
+ printf("Accuracy (intersection @ %zd): %.3f\n",
+ k,
+ accuracy(I.data()));
+ }
+ }
+ }
+
+ /****************************************************************
+ * Make an IVF index that uses the first 2 levels as a coarse
+ * quantizer, but this time does not store the code prefix from the index
+ ****************************************************************/
+
+ {
+ // build a coarse quantizer from the 2 first levels of the RQ
+ int nlevel = 2;
+
+ std::unique_ptr<faiss::IndexIVFResidualQuantizer> index(
+ faiss::ivflib::ivf_residual_from_quantizer(rq, nlevel));
+
+ // there are 2 ways of filling up the index...
+ for (std::string filled_with : {"add", "derived"}) {
+ tic();
+ printf("filling up the IVF index with %s, code_size=%zd\n",
+ filled_with.c_str(),
+ index->code_size);
+
+ index->reset();
+
+ if (filled_with == "add") {
+ // standard add method
+ index->add(nb, xb);
+ } else if (filled_with == "derived") {
+ faiss::ivflib::ivf_residual_add_from_flat_codes(
+ index.get(), nb, raw_codes.data(), rq.code_size);
+ }
+
+ tic();
+ printf("Index filled in\n");
+
+ for (int nprobe : {1, 4, 16, 64, int(index->nlist)}) {
+ printf("setting nprobe=%-4d", nprobe);
+
+ index->nprobe = nprobe;
+ std::vector<float> D(k * nq);
+ std::vector<idx_t> I(k * nq);
+ index->search(nq, xq, k, D.data(), I.data());
+
+ tic();
+ printf("Accuracy (intersection @ %zd): %.3f\n",
+ k,
+ accuracy(I.data()));
+ }
+ }
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_sift1M.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_sift1M.cpp
new file mode 100644
index 0000000..99a2e9c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_sift1M.cpp
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+
+#include <sys/stat.h>
+
+#include <sys/time.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/index_factory.h>
+
+/**
+ * To run this demo, please download the ANN_SIFT1M dataset from
+ *
+ * http://corpus-texmex.irisa.fr/
+ *
+ * and unzip it to the sudirectory sift1M.
+ **/
+
+/*****************************************************
+ * I/O functions for fvecs and ivecs
+ *****************************************************/
+
+float* fvecs_read(const char* fname, size_t* d_out, size_t* n_out) {
+ FILE* f = fopen(fname, "r");
+ if (!f) {
+ fprintf(stderr, "could not open %s\n", fname);
+ perror("");
+ abort();
+ }
+ int d;
+ fread(&d, 1, sizeof(int), f);
+ assert((d > 0 && d < 1000000) || !"unreasonable dimension");
+ fseek(f, 0, SEEK_SET);
+ struct stat st;
+ fstat(fileno(f), &st);
+ size_t sz = st.st_size;
+ assert(sz % ((d + 1) * 4) == 0 || !"weird file size");
+ size_t n = sz / ((d + 1) * 4);
+
+ *d_out = d;
+ *n_out = n;
+ float* x = new float[n * (d + 1)];
+ size_t nr __attribute__((unused)) = fread(x, sizeof(float), n * (d + 1), f);
+ assert(nr == n * (d + 1) || !"could not read whole file");
+
+ // shift array to remove row headers
+ for (size_t i = 0; i < n; i++)
+ memmove(x + i * d, x + 1 + i * (d + 1), d * sizeof(*x));
+
+ fclose(f);
+ return x;
+}
+
+// not very clean, but works as long as sizeof(int) == sizeof(float)
+int* ivecs_read(const char* fname, size_t* d_out, size_t* n_out) {
+ return (int*)fvecs_read(fname, d_out, n_out);
+}
+
+double elapsed() {
+ struct timeval tv;
+ gettimeofday(&tv, nullptr);
+ return tv.tv_sec + tv.tv_usec * 1e-6;
+}
+
+int main() {
+ double t0 = elapsed();
+
+ // this is typically the fastest one.
+ const char* index_key = "IVF4096,Flat";
+
+ // these ones have better memory usage
+ // const char *index_key = "Flat";
+ // const char *index_key = "PQ32";
+ // const char *index_key = "PCA80,Flat";
+ // const char *index_key = "IVF4096,PQ8+16";
+ // const char *index_key = "IVF4096,PQ32";
+ // const char *index_key = "IMI2x8,PQ32";
+ // const char *index_key = "IMI2x8,PQ8+16";
+ // const char *index_key = "OPQ16_64,IMI2x8,PQ8+16";
+
+ faiss::Index* index;
+
+ size_t d;
+
+ {
+ printf("[%.3f s] Loading train set\n", elapsed() - t0);
+
+ size_t nt;
+ float* xt = fvecs_read("sift1M/sift_learn.fvecs", &d, &nt);
+
+ printf("[%.3f s] Preparing index \"%s\" d=%ld\n",
+ elapsed() - t0,
+ index_key,
+ d);
+ index = faiss::index_factory(d, index_key);
+
+ printf("[%.3f s] Training on %ld vectors\n", elapsed() - t0, nt);
+
+ index->train(nt, xt);
+ delete[] xt;
+ }
+
+ {
+ printf("[%.3f s] Loading database\n", elapsed() - t0);
+
+ size_t nb, d2;
+ float* xb = fvecs_read("sift1M/sift_base.fvecs", &d2, &nb);
+ assert(d == d2 || !"dataset does not have same dimension as train set");
+
+ printf("[%.3f s] Indexing database, size %ld*%ld\n",
+ elapsed() - t0,
+ nb,
+ d);
+
+ index->add(nb, xb);
+
+ delete[] xb;
+ }
+
+ size_t nq;
+ float* xq;
+
+ {
+ printf("[%.3f s] Loading queries\n", elapsed() - t0);
+
+ size_t d2;
+ xq = fvecs_read("sift1M/sift_query.fvecs", &d2, &nq);
+ assert(d == d2 || !"query does not have same dimension as train set");
+ }
+
+ size_t k; // nb of results per query in the GT
+ faiss::idx_t* gt; // nq * k matrix of ground-truth nearest-neighbors
+
+ {
+ printf("[%.3f s] Loading ground truth for %ld queries\n",
+ elapsed() - t0,
+ nq);
+
+ // load ground-truth and convert int to long
+ size_t nq2;
+ int* gt_int = ivecs_read("sift1M/sift_groundtruth.ivecs", &k, &nq2);
+ assert(nq2 == nq || !"incorrect nb of ground truth entries");
+
+ gt = new faiss::idx_t[k * nq];
+ for (int i = 0; i < k * nq; i++) {
+ gt[i] = gt_int[i];
+ }
+ delete[] gt_int;
+ }
+
+ // Result of the auto-tuning
+ std::string selected_params;
+
+ { // run auto-tuning
+
+ printf("[%.3f s] Preparing auto-tune criterion 1-recall at 1 "
+ "criterion, with k=%ld nq=%ld\n",
+ elapsed() - t0,
+ k,
+ nq);
+
+ faiss::OneRecallAtRCriterion crit(nq, 1);
+ crit.set_groundtruth(k, nullptr, gt);
+ crit.nnn = k; // by default, the criterion will request only 1 NN
+
+ printf("[%.3f s] Preparing auto-tune parameters\n", elapsed() - t0);
+
+ faiss::ParameterSpace params;
+ params.initialize(index);
+
+ printf("[%.3f s] Auto-tuning over %ld parameters (%ld combinations)\n",
+ elapsed() - t0,
+ params.parameter_ranges.size(),
+ params.n_combinations());
+
+ faiss::OperatingPoints ops;
+ params.explore(index, nq, xq, crit, &ops);
+
+ printf("[%.3f s] Found the following operating points: \n",
+ elapsed() - t0);
+
+ ops.display();
+
+ // keep the first parameter that obtains > 0.5 1-recall@1
+ for (int i = 0; i < ops.optimal_pts.size(); i++) {
+ if (ops.optimal_pts[i].perf > 0.5) {
+ selected_params = ops.optimal_pts[i].key;
+ break;
+ }
+ }
+ assert(selected_params.size() >= 0 ||
+ !"could not find good enough op point");
+ }
+
+ { // Use the found configuration to perform a search
+
+ faiss::ParameterSpace params;
+
+ printf("[%.3f s] Setting parameter configuration \"%s\" on index\n",
+ elapsed() - t0,
+ selected_params.c_str());
+
+ params.set_index_parameters(index, selected_params.c_str());
+
+ printf("[%.3f s] Perform a search on %ld queries\n",
+ elapsed() - t0,
+ nq);
+
+ // output buffers
+ faiss::idx_t* I = new faiss::idx_t[nq * k];
+ float* D = new float[nq * k];
+
+ index->search(nq, xq, k, D, I);
+
+ printf("[%.3f s] Compute recalls\n", elapsed() - t0);
+
+ // evaluate result by hand.
+ int n_1 = 0, n_10 = 0, n_100 = 0;
+ for (int i = 0; i < nq; i++) {
+ int gt_nn = gt[i * k];
+ for (int j = 0; j < k; j++) {
+ if (I[i * k + j] == gt_nn) {
+ if (j < 1)
+ n_1++;
+ if (j < 10)
+ n_10++;
+ if (j < 100)
+ n_100++;
+ }
+ }
+ }
+ printf("R@1 = %.4f\n", n_1 / float(nq));
+ printf("R@10 = %.4f\n", n_10 / float(nq));
+ printf("R@100 = %.4f\n", n_100 / float(nq));
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xq;
+ delete[] gt;
+ delete index;
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/demo_weighted_kmeans.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_weighted_kmeans.cpp
new file mode 100644
index 0000000..d0041e5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/demo_weighted_kmeans.cpp
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <memory>
+
+#include <faiss/Clustering.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+
+namespace {
+
+enum WeightedKMeansType {
+ WKMT_FlatL2,
+ WKMT_FlatIP,
+ WKMT_FlatIP_spherical,
+ WKMT_HNSW,
+};
+
+float weighted_kmeans_clustering(
+ size_t d,
+ size_t n,
+ size_t k,
+ const float* input,
+ const float* weights,
+ float* centroids,
+ WeightedKMeansType index_num) {
+ using namespace faiss;
+ Clustering clus(d, k);
+ clus.verbose = true;
+
+ std::unique_ptr<Index> index;
+
+ switch (index_num) {
+ case WKMT_FlatL2:
+ index = std::make_unique<IndexFlatL2>(d);
+ break;
+ case WKMT_FlatIP:
+ index = std::make_unique<IndexFlatIP>(d);
+ break;
+ case WKMT_FlatIP_spherical:
+ index = std::make_unique<IndexFlatIP>(d);
+ clus.spherical = true;
+ break;
+ case WKMT_HNSW:
+ IndexHNSWFlat* ihnsw = new IndexHNSWFlat(d, 32);
+ ihnsw->hnsw.efSearch = 128;
+ index.reset(ihnsw);
+ break;
+ }
+
+ clus.train(n, input, *index.get(), weights);
+ // on output the index contains the centroids.
+ memcpy(centroids, clus.centroids.data(), sizeof(*centroids) * d * k);
+ return clus.iteration_stats.back().obj;
+}
+
+int d = 32;
+float sigma = 0.1;
+
+#define BIGTEST
+
+#ifdef BIGTEST
+// the production setup = setting of https://fb.quip.com/CWgnAAYbwtgs
+int nc = 200000;
+int n_big = 4;
+int n_small = 2;
+#else
+int nc = 5;
+int n_big = 100;
+int n_small = 10;
+#endif
+
+int n; // number of training points
+
+void generate_trainset(
+ std::vector<float>& ccent,
+ std::vector<float>& x,
+ std::vector<float>& weights) {
+ // same sampling as test_build_blocks.py test_weighted
+
+ ccent.resize(d * 2 * nc);
+ faiss::float_randn(ccent.data(), d * 2 * nc, 123);
+ faiss::fvec_renorm_L2(d, 2 * nc, ccent.data());
+ n = nc * n_big + nc * n_small;
+ x.resize(d * n);
+ weights.resize(n);
+ faiss::float_randn(x.data(), x.size(), 1234);
+
+ float* xi = x.data();
+ float* w = weights.data();
+ for (int ci = 0; ci < nc * 2; ci++) { // loop over centroids
+ int np = ci < nc ? n_big : n_small; // nb of points around this centroid
+ for (int i = 0; i < np; i++) {
+ for (int j = 0; j < d; j++) {
+ xi[j] = xi[j] * sigma + ccent[ci * d + j];
+ }
+ *w++ = ci < nc ? 0.1 : 10;
+ xi += d;
+ }
+ }
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ std::vector<float> ccent;
+ std::vector<float> x;
+ std::vector<float> weights;
+
+ printf("generate training set\n");
+ generate_trainset(ccent, x, weights);
+
+ std::vector<float> centroids;
+ centroids.resize(nc * d);
+
+ int the_index_num = -1;
+ int the_with_weights = -1;
+
+ if (argc == 3) {
+ the_index_num = atoi(argv[1]);
+ the_with_weights = atoi(argv[2]);
+ }
+
+ for (int index_num = WKMT_FlatL2; index_num <= WKMT_HNSW; index_num++) {
+ if (the_index_num >= 0 && index_num != the_index_num) {
+ continue;
+ }
+
+ for (int with_weights = 0; with_weights <= 1; with_weights++) {
+ if (the_with_weights >= 0 && with_weights != the_with_weights) {
+ continue;
+ }
+
+ printf("=================== index_num=%d Run %s weights\n",
+ index_num,
+ with_weights ? "with" : "without");
+
+ weighted_kmeans_clustering(
+ d,
+ n,
+ nc,
+ x.data(),
+ with_weights ? weights.data() : nullptr,
+ centroids.data(),
+ (WeightedKMeansType)index_num);
+
+ { // compute distance of points to centroids
+ faiss::IndexFlatL2 cent_index(d);
+ cent_index.add(nc, centroids.data());
+ std::vector<float> dis(n);
+ std::vector<faiss::idx_t> idx(n);
+
+ cent_index.search(
+ nc * 2, ccent.data(), 1, dis.data(), idx.data());
+
+ float dis1 = 0, dis2 = 0;
+ for (int i = 0; i < nc; i++) {
+ dis1 += dis[i];
+ }
+ printf("average distance of points from big clusters: %g\n",
+ dis1 / nc);
+
+ for (int i = 0; i < nc; i++) {
+ dis2 += dis[i + nc];
+ }
+
+ printf("average distance of points from small clusters: %g\n",
+ dis2 / nc);
+ }
+ }
+ }
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/index_pq_flat_separate_codes_from_codebook.py b/packages/leann-backend-hnsw/third_party/faiss/demos/index_pq_flat_separate_codes_from_codebook.py
new file mode 100644
index 0000000..d138a37
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/index_pq_flat_separate_codes_from_codebook.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env -S grimaldi --kernel bento_kernel_faiss
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+# fmt: off
+# flake8: noqa
+
+
+""":md
+# Serializing codes separately, with IndexLSH and IndexPQ
+
+Let's say, for example, you have a few vector embeddings per user
+and want to shard a flat index by user so you can re-use the same LSH or PQ method
+ for all users but store each user's codes independently.
+
+
+"""
+
+""":py"""
+import faiss
+import numpy as np
+
+""":py"""
+d = 768
+n = 1_000
+ids = np.arange(n).astype('int64')
+training_data = np.random.rand(n, d).astype('float32')
+
+""":py"""
+def read_ids_codes():
+ try:
+ return np.load("/tmp/ids.npy"), np.load("/tmp/codes.npy")
+ except FileNotFoundError:
+ return None, None
+
+
+def write_ids_codes(ids, codes):
+ np.save("/tmp/ids.npy", ids)
+ np.save("/tmp/codes.npy", codes.reshape(len(ids), -1))
+
+
+def write_template_index(template_index):
+ faiss.write_index(template_index, "/tmp/template.index")
+
+
+def read_template_index_instance():
+ return faiss.read_index("/tmp/template.index")
+
+""":md
+## IndexLSH: separate codes
+
+The first half of this notebook demonstrates how to store LSH codes. Unlike PQ, LSH does not require training. In fact, it's compression method, a random projections matrix, is deterministic on construction based on a random seed value that's [hardcoded](https://github.com/facebookresearch/faiss/blob/2c961cc308ade8a85b3aa10a550728ce3387f625/faiss/IndexLSH.cpp#L35).
+"""
+
+""":py"""
+nbits = 1536
+
+""":py"""
+# demonstrating encoding is deterministic
+
+codes = []
+database_vector_float32 = np.random.rand(1, d).astype(np.float32)
+for i in range(10):
+ index = faiss.IndexIDMap2(faiss.IndexLSH(d, nbits))
+ code = index.index.sa_encode(database_vector_float32)
+ codes.append(code)
+
+for i in range(1, 10):
+ assert np.array_equal(codes[0], codes[i])
+
+""":py"""
+# new database vector
+
+ids, codes = read_ids_codes()
+database_vector_id, database_vector_float32 = max(ids) + 1 if ids is not None else 1, np.random.rand(1, d).astype(np.float32)
+index = faiss.IndexIDMap2(faiss.IndexLSH(d, nbits))
+
+code = index.index.sa_encode(database_vector_float32)
+
+if ids is not None and codes is not None:
+ ids = np.concatenate((ids, [database_vector_id]))
+ codes = np.vstack((codes, code))
+else:
+ ids = np.array([database_vector_id])
+ codes = np.array([code])
+
+write_ids_codes(ids, codes)
+
+""":py '2840581589434841'"""
+# then at query time
+
+query_vector_float32 = np.random.rand(1, d).astype(np.float32)
+index = faiss.IndexIDMap2(faiss.IndexLSH(d, nbits))
+ids, codes = read_ids_codes()
+
+index.add_sa_codes(codes, ids)
+
+index.search(query_vector_float32, k=5)
+
+""":py"""
+!rm /tmp/ids.npy /tmp/codes.npy
+
+""":md
+## IndexPQ: separate codes from codebook
+
+The second half of this notebook demonstrates how to separate serializing and deserializing the PQ codebook
+ (via faiss.write_index for IndexPQ) independently of the vector codes. For example, in the case
+ where you have a few vector embeddings per user and want to shard the flat index by user you
+ can re-use the same PQ method for all users but store each user's codes independently.
+
+"""
+
+""":py"""
+M = d//8
+nbits = 8
+
+""":py"""
+# at train time
+template_index = faiss.index_factory(d, f"IDMap2,PQ{M}x{nbits}")
+template_index.train(training_data)
+write_template_index(template_index)
+
+""":py"""
+# New database vector
+
+index = read_template_index_instance()
+ids, codes = read_ids_codes()
+database_vector_id, database_vector_float32 = max(ids) + 1 if ids is not None else 1, np.random.rand(1, d).astype(np.float32)
+
+code = index.index.sa_encode(database_vector_float32)
+
+if ids is not None and codes is not None:
+ ids = np.concatenate((ids, [database_vector_id]))
+ codes = np.vstack((codes, code))
+else:
+ ids = np.array([database_vector_id])
+ codes = np.array([code])
+
+write_ids_codes(ids, codes)
+
+""":py '1858280061369209'"""
+# then at query time
+query_vector_float32 = np.random.rand(1, d).astype(np.float32)
+id_wrapper_index = read_template_index_instance()
+ids, codes = read_ids_codes()
+
+id_wrapper_index.add_sa_codes(codes, ids)
+
+id_wrapper_index.search(query_vector_float32, k=5)
+
+""":py"""
+!rm /tmp/ids.npy /tmp/codes.npy /tmp/template.index
+
+""":md
+## Comparing these methods
+
+- methods: Flat, LSH, PQ
+- vary cost: nbits, M for 1x, 2x, 4x, 8x, 16x, 32x compression
+- measure: recall@1
+
+We don't measure latency as the number of vectors per user shard is insignificant.
+
+"""
+
+""":py '2898032417027201'"""
+n, d
+
+""":py"""
+database_vector_ids, database_vector_float32s = np.arange(n), np.random.rand(n, d).astype(np.float32)
+query_vector_float32s = np.random.rand(n, d).astype(np.float32)
+
+""":py"""
+index = faiss.index_factory(d, "IDMap2,Flat")
+index.add_with_ids(database_vector_float32s, database_vector_ids)
+_, ground_truth_result_ids= index.search(query_vector_float32s, k=1)
+
+""":py '857475336204238'"""
+from dataclasses import dataclass
+
+pq_m_nbits = (
+ # 96 bytes
+ (96, 8),
+ (192, 4),
+ # 192 bytes
+ (192, 8),
+ (384, 4),
+ # 384 bytes
+ (384, 8),
+ (768, 4),
+)
+lsh_nbits = (768, 1536, 3072, 6144, 12288, 24576)
+
+
+@dataclass
+class Record:
+ type_: str
+ index: faiss.Index
+ args: tuple
+ recall: float
+
+
+results = []
+
+for m, nbits in pq_m_nbits:
+ print("pq", m, nbits)
+ index = faiss.index_factory(d, f"IDMap2,PQ{m}x{nbits}")
+ index.train(training_data)
+ index.add_with_ids(database_vector_float32s, database_vector_ids)
+ _, result_ids = index.search(query_vector_float32s, k=1)
+ recall = sum(result_ids == ground_truth_result_ids)
+ results.append(Record("pq", index, (m, nbits), recall))
+
+for nbits in lsh_nbits:
+ print("lsh", nbits)
+ index = faiss.IndexIDMap2(faiss.IndexLSH(d, nbits))
+ index.add_with_ids(database_vector_float32s, database_vector_ids)
+ _, result_ids = index.search(query_vector_float32s, k=1)
+ recall = sum(result_ids == ground_truth_result_ids)
+ results.append(Record("lsh", index, (nbits,), recall))
+
+""":py '556918346720794'"""
+import matplotlib.pyplot as plt
+import numpy as np
+
+def create_grouped_bar_chart(x_values, y_values_list, labels_list, xlabel, ylabel, title):
+ num_bars_per_group = len(x_values)
+
+ plt.figure(figsize=(12, 6))
+
+ for x, y_values, labels in zip(x_values, y_values_list, labels_list):
+ num_bars = len(y_values)
+ bar_width = 0.08 * x
+ bar_positions = np.arange(num_bars) * bar_width - (num_bars - 1) * bar_width / 2 + x
+
+ bars = plt.bar(bar_positions, y_values, width=bar_width)
+
+ for bar, label in zip(bars, labels):
+ height = bar.get_height()
+ plt.annotate(
+ label,
+ xy=(bar.get_x() + bar.get_width() / 2, height),
+ xytext=(0, 3),
+ textcoords="offset points",
+ ha='center', va='bottom'
+ )
+
+ plt.xscale('log')
+ plt.xlabel(xlabel)
+ plt.ylabel(ylabel)
+ plt.title(title)
+ plt.xticks(x_values, labels=[str(x) for x in x_values])
+ plt.tight_layout()
+ plt.show()
+
+# # Example usage:
+# x_values = [1, 2, 4, 8, 16, 32]
+# y_values_list = [
+# [2.5, 3.6, 1.8],
+# [3.0, 2.8],
+# [2.5, 3.5, 4.0, 1.0],
+# [4.2],
+# [3.0, 5.5, 2.2],
+# [6.0, 4.5]
+# ]
+# labels_list = [
+# ['A1', 'B1', 'C1'],
+# ['A2', 'B2'],
+# ['A3', 'B3', 'C3', 'D3'],
+# ['A4'],
+# ['A5', 'B5', 'C5'],
+# ['A6', 'B6']
+# ]
+
+# create_grouped_bar_chart(x_values, y_values_list, labels_list, "x axis", "y axis", "title")
+
+""":py '1630106834206134'"""
+# x-axis: compression ratio
+# y-axis: recall@1
+
+from collections import defaultdict
+
+x = defaultdict(list)
+x[1].append(("flat", 1.00))
+for r in results:
+ y_value = r.recall[0] / n
+ x_value = int(d * 4 / r.index.sa_code_size())
+ label = None
+ if r.type_ == "pq":
+ label = f"PQ{r.args[0]}x{r.args[1]}"
+ if r.type_ == "lsh":
+ label = f"LSH{r.args[0]}"
+ x[x_value].append((label, y_value))
+
+x_values = sorted(list(x.keys()))
+create_grouped_bar_chart(
+ x_values,
+ [[e[1] for e in x[x_value]] for x_value in x_values],
+ [[e[0] for e in x[x_value]] for x_value in x_values],
+ "compression ratio",
+ "recall@1 q=1,000 queries",
+ "recall@1 for a database of n=1,000 d=768 vectors",
+)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/README.md b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/README.md
new file mode 100644
index 0000000..df848ba
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/README.md
@@ -0,0 +1,52 @@
+
+# Offline IVF
+
+This folder contains the code for the offline ivf algorithm powered by faiss big batch search.
+
+Create a conda env:
+
+`conda create --name oivf python=3.10`
+
+`conda activate oivf`
+
+`conda install -c pytorch/label/nightly -c nvidia faiss-gpu=1.7.4`
+
+`conda install tqdm`
+
+`conda install pyyaml`
+
+`conda install -c conda-forge submitit`
+
+
+## Run book
+
+1. Optionally shard your dataset (see create_sharded_dataset.py) and create the corresponding yaml file `config_ssnpp.yaml`. You can use `generate_config.py` by specifying the root directory of your dataset and the files with the data shards
+
+`python generate_config`
+
+2. Run the train index command
+
+`python run.py --command train_index --config config_ssnpp.yaml --xb ssnpp_1B`
+
+
+3. Run the index-shard command so it produces sharded indexes, required for the search step
+
+`python run.py --command index_shard --config config_ssnpp.yaml --xb ssnpp_1B`
+
+
+6. Send jobs to the cluster to run search
+
+`python run.py --command search --config config_ssnpp.yaml --xb ssnpp_1B --cluster_run --partition <PARTITION-NAME>`
+
+
+Remarks about the `search` command: it is assumed that the database vectors are the query vectors when performing the search step.
+a. If the query vectors are different than the database vectors, it should be passed in the xq argument
+b. A new dataset needs to be prepared (step 1) before passing it to the query vectors argument `–xq`
+
+`python run.py --command search --config config_ssnpp.yaml --xb ssnpp_1B --xq <QUERIES_DATASET_NAME>`
+
+
+6. We can always run the consistency-check for sanity checks!
+
+`python run.py --command consistency_check--config config_ssnpp.yaml --xb ssnpp_1B`
+
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/__init__.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/config_ssnpp.yaml b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/config_ssnpp.yaml
new file mode 100644
index 0000000..88e0394
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/config_ssnpp.yaml
@@ -0,0 +1,110 @@
+d: 256
+output: /checkpoint/marialomeli/offline_faiss/ssnpp
+index:
+ prod:
+ - 'IVF8192,PQ128'
+ non-prod:
+ - 'IVF16384,PQ128'
+ - 'IVF32768,PQ128'
+ - 'OPQ64_128,IVF4096,PQ64'
+nprobe:
+ prod:
+ - 512
+ non-prod:
+ - 256
+ - 128
+ - 1024
+ - 2048
+ - 4096
+ - 8192
+
+k: 50
+index_shard_size: 50000000
+query_batch_size: 50000000
+evaluation_sample: 10000
+training_sample: 1572864
+datasets:
+ ssnpp_1B:
+ root: /checkpoint/marialomeli/ssnpp_data
+ size: 1000000000
+ files:
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000000.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000001.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000002.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000003.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000004.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000005.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000006.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000007.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000008.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000009.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000010.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000011.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000012.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000013.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000014.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000015.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000016.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000017.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000018.npy
+ size: 50000000
+ - dtype: uint8
+ format: npy
+ name: ssnpp_0000000019.npy
+ size: 50000000
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/create_sharded_ssnpp_files.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/create_sharded_ssnpp_files.py
new file mode 100644
index 0000000..1e3b36d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/create_sharded_ssnpp_files.py
@@ -0,0 +1,64 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import argparse
+import os
+
+
+def xbin_mmap(fname, dtype, maxn=-1):
+ """
+ Code from
+ https://github.com/harsha-simhadri/big-ann-benchmarks/blob/main/benchmark/dataset_io.py#L94
+ mmap the competition file format for a given type of items
+ """
+ n, d = map(int, np.fromfile(fname, dtype="uint32", count=2))
+ assert os.stat(fname).st_size == 8 + n * d * np.dtype(dtype).itemsize
+ if maxn > 0:
+ n = min(n, maxn)
+ return np.memmap(fname, dtype=dtype, mode="r", offset=8, shape=(n, d))
+
+
+def main(args: argparse.Namespace):
+ ssnpp_data = xbin_mmap(fname=args.filepath, dtype="uint8")
+ num_batches = ssnpp_data.shape[0] // args.data_batch
+ assert (
+ ssnpp_data.shape[0] % args.data_batch == 0
+ ), "num of embeddings per file should divide total num of embeddings"
+ for i in range(num_batches):
+ xb_batch = ssnpp_data[
+ i * args.data_batch:(i + 1) * args.data_batch, :
+ ]
+ filename = args.output_dir + f"/ssnpp_{(i):010}.npy"
+ np.save(filename, xb_batch)
+ print(f"File {filename} is saved!")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--data_batch",
+ dest="data_batch",
+ type=int,
+ default=50000000,
+ help="Number of embeddings per file, should be a divisor of 1B",
+ )
+ parser.add_argument(
+ "--filepath",
+ dest="filepath",
+ type=str,
+ default="/datasets01/big-ann-challenge-data/FB_ssnpp/FB_ssnpp_database.u8bin",
+ help="path of 1B ssnpp database vectors' original file",
+ )
+ parser.add_argument(
+ "--filepath",
+ dest="output_dir",
+ type=str,
+ default="/checkpoint/marialomeli/ssnpp_data",
+ help="path to put sharded files",
+ )
+
+ args = parser.parse_args()
+ main(args)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/dataset.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/dataset.py
new file mode 100644
index 0000000..5c96a83
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/dataset.py
@@ -0,0 +1,174 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import os
+import numpy as np
+import faiss
+from typing import List
+import random
+import logging
+from functools import lru_cache
+
+
+def create_dataset_from_oivf_config(cfg, ds_name):
+ normalise = cfg["normalise"] if "normalise" in cfg else False
+ return MultiFileVectorDataset(
+ cfg["datasets"][ds_name]["root"],
+ [
+ FileDescriptor(
+ f["name"], f["format"], np.dtype(f["dtype"]), f["size"]
+ )
+ for f in cfg["datasets"][ds_name]["files"]
+ ],
+ cfg["d"],
+ normalise,
+ cfg["datasets"][ds_name]["size"],
+ )
+
+
+@lru_cache(maxsize=100)
+def _memmap_vecs(
+ file_name: str, format: str, dtype: np.dtype, size: int, d: int
+) -> np.array:
+ """
+ If the file is in raw format, the file size will
+ be divisible by the dimensionality and by the size
+ of the data type.
+ Otherwise,the file contains a header and we assume
+ it is of .npy type. It the returns the memmapped file.
+ """
+
+ assert os.path.exists(file_name), f"file does not exist {file_name}"
+ if format == "raw":
+ fl = os.path.getsize(file_name)
+ nb = fl // d // dtype.itemsize
+ assert nb == size, f"{nb} is different than config's {size}"
+ assert fl == d * dtype.itemsize * nb # no header
+ return np.memmap(file_name, shape=(nb, d), dtype=dtype, mode="r")
+ elif format == "npy":
+ vecs = np.load(file_name, mmap_mode="r")
+ assert vecs.shape[0] == size, f"size:{size},shape {vecs.shape[0]}"
+ assert vecs.shape[1] == d
+ assert vecs.dtype == dtype
+ return vecs
+ else:
+ ValueError("The file cannot be loaded in the current format.")
+
+
+class FileDescriptor:
+ def __init__(self, name: str, format: str, dtype: np.dtype, size: int):
+ self.name = name
+ self.format = format
+ self.dtype = dtype
+ self.size = size
+
+
+class MultiFileVectorDataset:
+ def __init__(
+ self,
+ root: str,
+ file_descriptors: List[FileDescriptor],
+ d: int,
+ normalize: bool,
+ size: int,
+ ):
+ assert os.path.exists(root)
+ self.root = root
+ self.file_descriptors = file_descriptors
+ self.d = d
+ self.normalize = normalize
+ self.size = size
+ self.file_offsets = [0]
+ t = 0
+ for f in self.file_descriptors:
+ xb = _memmap_vecs(
+ f"{self.root}/{f.name}", f.format, f.dtype, f.size, self.d
+ )
+ t += xb.shape[0]
+ self.file_offsets.append(t)
+ assert (
+ t == self.size
+ ), "the sum of num of embeddings per file!=total num of embeddings"
+
+ def iterate(self, start: int, batch_size: int, dt: np.dtype):
+ buffer = np.empty(shape=(batch_size, self.d), dtype=dt)
+ rem = 0
+ for f in self.file_descriptors:
+ if start >= f.size:
+ start -= f.size
+ continue
+ logging.info(f"processing: {f.name}...")
+ xb = _memmap_vecs(
+ f"{self.root}/{f.name}",
+ f.format,
+ f.dtype,
+ f.size,
+ self.d,
+ )
+ if start > 0:
+ xb = xb[start:]
+ start = 0
+ req = min(batch_size - rem, xb.shape[0])
+ buffer[rem:rem + req] = xb[:req]
+ rem += req
+ if rem == batch_size:
+ if self.normalize:
+ faiss.normalize_L2(buffer)
+ yield buffer.copy()
+ rem = 0
+ for i in range(req, xb.shape[0], batch_size):
+ j = i + batch_size
+ if j <= xb.shape[0]:
+ tmp = xb[i:j].astype(dt)
+ if self.normalize:
+ faiss.normalize_L2(tmp)
+ yield tmp
+ else:
+ rem = xb.shape[0] - i
+ buffer[:rem] = xb[i:j]
+ if rem > 0:
+ tmp = buffer[:rem]
+ if self.normalize:
+ faiss.normalize_L2(tmp)
+ yield tmp
+
+ def get(self, idx: List[int]):
+ n = len(idx)
+ fidx = np.searchsorted(self.file_offsets, idx, "right")
+ res = np.empty(shape=(len(idx), self.d), dtype=np.float32)
+ for r, id, fid in zip(range(n), idx, fidx):
+ assert fid > 0 and fid <= len(self.file_descriptors), f"{fid}"
+ f = self.file_descriptors[fid - 1]
+ # deferring normalization until after reading the vec
+ vecs = _memmap_vecs(
+ f"{self.root}/{f.name}", f.format, f.dtype, f.size, self.d
+ )
+ i = id - self.file_offsets[fid - 1]
+ assert i >= 0 and i < vecs.shape[0]
+ res[r, :] = vecs[i] # TODO: find a faster way
+ if self.normalize:
+ faiss.normalize_L2(res)
+ return res
+
+ def sample(self, n, idx_fn, vecs_fn):
+ if vecs_fn and os.path.exists(vecs_fn):
+ vecs = np.load(vecs_fn)
+ assert vecs.shape == (n, self.d)
+ return vecs
+ if idx_fn and os.path.exists(idx_fn):
+ idx = np.load(idx_fn)
+ assert idx.size == n
+ else:
+ idx = np.array(sorted(random.sample(range(self.size), n)))
+ if idx_fn:
+ np.save(idx_fn, idx)
+ vecs = self.get(idx)
+ if vecs_fn:
+ np.save(vecs_fn, vecs)
+ return vecs
+
+ def get_first_n(self, n, dt):
+ assert n <= self.size
+ return next(self.iterate(0, n, dt))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/generate_config.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/generate_config.py
new file mode 100644
index 0000000..e70085c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/generate_config.py
@@ -0,0 +1,46 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import os
+import yaml
+
+# with ssnpp sharded data
+root = "/checkpoint/marialomeli/ssnpp_data"
+file_names = [f"ssnpp_{i:010}.npy" for i in range(20)]
+d = 256
+dt = np.dtype(np.uint8)
+
+
+def read_embeddings(fp):
+ fl = os.path.getsize(fp)
+ nb = fl // d // dt.itemsize
+ print(nb)
+ if fl == d * dt.itemsize * nb: # no header
+ return ("raw", np.memmap(fp, shape=(nb, d), dtype=dt, mode="r"))
+ else: # assume npy
+ vecs = np.load(fp, mmap_mode="r")
+ assert vecs.shape[1] == d
+ assert vecs.dtype == dt
+ return ("npy", vecs)
+
+
+cfg = {}
+files = []
+size = 0
+for fn in file_names:
+ fp = f"{root}/{fn}"
+ assert os.path.exists(fp), f"{fp} is missing"
+ ft, xb = read_embeddings(fp)
+ files.append(
+ {"name": fn, "size": xb.shape[0], "dtype": dt.name, "format": ft}
+ )
+ size += xb.shape[0]
+
+cfg["size"] = size
+cfg["root"] = root
+cfg["d"] = d
+cfg["files"] = files
+print(yaml.dump(cfg))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/offline_ivf.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/offline_ivf.py
new file mode 100644
index 0000000..8fe7d6b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/offline_ivf.py
@@ -0,0 +1,891 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import numpy as np
+import os
+from tqdm import tqdm, trange
+import sys
+import logging
+from faiss.contrib.ondisk import merge_ondisk
+from faiss.contrib.big_batch_search import big_batch_search
+from faiss.contrib.exhaustive_search import knn_ground_truth
+from faiss.contrib.evaluation import knn_intersection_measure
+from utils import (
+ get_intersection_cardinality_frequencies,
+ margin,
+ is_pretransform_index,
+)
+from dataset import create_dataset_from_oivf_config
+
+logging.basicConfig(
+ format=(
+ "%(asctime)s.%(msecs)03d %(levelname)-8s %(threadName)-12s %(message)s"
+ ),
+ level=logging.INFO,
+ datefmt="%Y-%m-%d %H:%M:%S",
+ force=True,
+)
+
+EMBEDDINGS_BATCH_SIZE: int = 100_000
+NUM_SUBSAMPLES: int = 100
+SMALL_DATA_SAMPLE: int = 10000
+
+
+class OfflineIVF:
+ def __init__(self, cfg, args, nprobe, index_factory_str):
+ self.input_d = cfg["d"]
+ self.dt = cfg["datasets"][args.xb]["files"][0]["dtype"]
+ assert self.input_d > 0
+ output_dir = cfg["output"]
+ assert os.path.exists(output_dir)
+ self.index_factory = index_factory_str
+ assert self.index_factory is not None
+ self.index_factory_fn = self.index_factory.replace(",", "_")
+ self.index_template_file = (
+ f"{output_dir}/{args.xb}/{self.index_factory_fn}.empty.faissindex"
+ )
+ logging.info(f"index template: {self.index_template_file}")
+
+ if not args.xq:
+ args.xq = args.xb
+
+ self.by_residual = True
+ if args.no_residuals:
+ self.by_residual = False
+
+ xb_output_dir = f"{output_dir}/{args.xb}"
+ if not os.path.exists(xb_output_dir):
+ os.makedirs(xb_output_dir)
+ xq_output_dir = f"{output_dir}/{args.xq}"
+ if not os.path.exists(xq_output_dir):
+ os.makedirs(xq_output_dir)
+ search_output_dir = f"{output_dir}/{args.xq}_in_{args.xb}"
+ if not os.path.exists(search_output_dir):
+ os.makedirs(search_output_dir)
+ self.knn_dir = f"{search_output_dir}/knn"
+ if not os.path.exists(self.knn_dir):
+ os.makedirs(self.knn_dir)
+ self.eval_dir = f"{search_output_dir}/eval"
+ if not os.path.exists(self.eval_dir):
+ os.makedirs(self.eval_dir)
+ self.index = {} # to keep a reference to opened indices,
+ self.ivls = {} # hstack inverted lists,
+ self.index_shards = {} # and index shards
+ self.index_shard_prefix = (
+ f"{xb_output_dir}/{self.index_factory_fn}.shard_"
+ )
+ self.xq_index_shard_prefix = (
+ f"{xq_output_dir}/{self.index_factory_fn}.shard_"
+ )
+ self.index_file = ( # TODO: added back temporarily for evaluate, handle name of non-sharded index file and remove.
+ f"{xb_output_dir}/{self.index_factory_fn}.faissindex"
+ )
+ self.xq_index_file = (
+ f"{xq_output_dir}/{self.index_factory_fn}.faissindex"
+ )
+ self.training_sample = cfg["training_sample"]
+ self.evaluation_sample = cfg["evaluation_sample"]
+ self.xq_ds = create_dataset_from_oivf_config(cfg, args.xq)
+ self.xb_ds = create_dataset_from_oivf_config(cfg, args.xb)
+ file_descriptors = self.xq_ds.file_descriptors
+ self.file_sizes = [fd.size for fd in file_descriptors]
+ self.shard_size = cfg["index_shard_size"] # ~100GB
+ self.nshards = self.xb_ds.size // self.shard_size
+ if self.xb_ds.size % self.shard_size != 0:
+ self.nshards += 1
+ self.xq_nshards = self.xq_ds.size // self.shard_size
+ if self.xq_ds.size % self.shard_size != 0:
+ self.xq_nshards += 1
+ self.nprobe = nprobe
+ assert self.nprobe > 0, "Invalid nprobe parameter."
+ if "deduper" in cfg:
+ self.deduper = cfg["deduper"]
+ self.deduper_codec_fn = [
+ f"{xb_output_dir}/deduper_codec_{codec.replace(',', '_')}"
+ for codec in self.deduper
+ ]
+ self.deduper_idx_fn = [
+ f"{xb_output_dir}/deduper_idx_{codec.replace(',', '_')}"
+ for codec in self.deduper
+ ]
+ else:
+ self.deduper = None
+ self.k = cfg["k"]
+ assert self.k > 0, "Invalid number of neighbours parameter."
+ self.knn_output_file_suffix = (
+ f"{self.index_factory_fn}_np{self.nprobe}.npy"
+ )
+
+ fp = 32
+ if self.dt == "float16":
+ fp = 16
+
+ self.xq_bs = cfg["query_batch_size"]
+ if "metric" in cfg:
+ self.metric = eval(f'faiss.{cfg["metric"]}')
+ else:
+ self.metric = faiss.METRIC_L2
+
+ if "evaluate_by_margin" in cfg:
+ self.evaluate_by_margin = cfg["evaluate_by_margin"]
+ else:
+ self.evaluate_by_margin = False
+
+ os.system("grep -m1 'model name' < /proc/cpuinfo")
+ os.system("grep -E 'MemTotal|MemFree' /proc/meminfo")
+ os.system("nvidia-smi")
+ os.system("nvcc --version")
+
+ self.knn_queries_memory_limit = 4 * 1024 * 1024 * 1024 # 4 GB
+ self.knn_vectors_memory_limit = 8 * 1024 * 1024 * 1024 # 8 GB
+
+ def input_stats(self):
+ """
+ Trains the index using a subsample of the first chunk of data in the database and saves it in the template file (with no vectors added).
+ """
+ xb_sample = self.xb_ds.get_first_n(self.training_sample, np.float32)
+ logging.info(f"input shape: {xb_sample.shape}")
+ logging.info("running MatrixStats on training sample...")
+ logging.info(faiss.MatrixStats(xb_sample).comments)
+ logging.info("done")
+
+ def dedupe(self):
+ logging.info(self.deduper)
+ if self.deduper is None:
+ logging.info("No deduper configured")
+ return
+ codecs = []
+ codesets = []
+ idxs = []
+ for factory, filename in zip(self.deduper, self.deduper_codec_fn):
+ if os.path.exists(filename):
+ logging.info(f"loading trained dedupe codec: {filename}")
+ codec = faiss.read_index(filename)
+ else:
+ logging.info(f"training dedupe codec: {factory}")
+ codec = faiss.index_factory(self.input_d, factory)
+ xb_sample = np.unique(
+ self.xb_ds.get_first_n(100_000, np.float32), axis=0
+ )
+ faiss.ParameterSpace().set_index_parameter(codec, "verbose", 1)
+ codec.train(xb_sample)
+ logging.info(f"writing trained dedupe codec: {filename}")
+ faiss.write_index(codec, filename)
+ codecs.append(codec)
+ codesets.append(faiss.CodeSet(codec.sa_code_size()))
+ idxs.append(np.empty((0,), dtype=np.uint32))
+ bs = 1_000_000
+ i = 0
+ for buffer in tqdm(self._iterate_transformed(self.xb_ds, 0, bs, np.float32)):
+ for j in range(len(codecs)):
+ codec, codeset, idx = codecs[j], codesets[j], idxs[j]
+ uniq = codeset.insert(codec.sa_encode(buffer))
+ idxs[j] = np.append(
+ idx,
+ np.arange(i, i + buffer.shape[0], dtype=np.uint32)[uniq],
+ )
+ i += buffer.shape[0]
+ for idx, filename in zip(idxs, self.deduper_idx_fn):
+ logging.info(f"writing {filename}, shape: {idx.shape}")
+ np.save(filename, idx)
+ logging.info("done")
+
+ def train_index(self):
+ """
+ Trains the index using a subsample of the first chunk of data in the database and saves it in the template file (with no vectors added).
+ """
+ assert not os.path.exists(self.index_template_file), (
+ "The train command has been ran, the index template file already"
+ " exists."
+ )
+ xb_sample = np.unique(
+ self.xb_ds.get_first_n(self.training_sample, np.float32), axis=0
+ )
+ logging.info(f"input shape: {xb_sample.shape}")
+ index = faiss.index_factory(
+ self.input_d, self.index_factory, self.metric
+ )
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ index_ivf.by_residual = True
+ faiss.ParameterSpace().set_index_parameter(index, "verbose", 1)
+ logging.info("running training...")
+ index.train(xb_sample)
+ logging.info(f"writing trained index {self.index_template_file}...")
+ faiss.write_index(index, self.index_template_file)
+ logging.info("done")
+
+ def _iterate_transformed(self, ds, start, batch_size, dt):
+ assert os.path.exists(self.index_template_file)
+ index = faiss.read_index(self.index_template_file)
+ if is_pretransform_index(index):
+ vt = index.chain.at(0) # fetch pretransform
+ for buffer in ds.iterate(start, batch_size, dt):
+ yield vt.apply(buffer)
+ else:
+ for buffer in ds.iterate(start, batch_size, dt):
+ yield buffer
+
+ def index_shard(self):
+ assert os.path.exists(self.index_template_file)
+ index = faiss.read_index(self.index_template_file)
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ assert self.nprobe <= index_ivf.quantizer.ntotal, (
+ f"the number of vectors {index_ivf.quantizer.ntotal} is not enough"
+ f" to retrieve {self.nprobe} neighbours, check."
+ )
+ cpu_quantizer = index_ivf.quantizer
+ gpu_quantizer = faiss.index_cpu_to_all_gpus(cpu_quantizer)
+
+ for i in range(0, self.nshards):
+ sfn = f"{self.index_shard_prefix}{i}"
+ try:
+ index.reset()
+ index_ivf.quantizer = gpu_quantizer
+ with open(sfn, "xb"):
+ start = i * self.shard_size
+ jj = 0
+ embeddings_batch_size = min(
+ EMBEDDINGS_BATCH_SIZE, self.shard_size
+ )
+ assert (
+ self.shard_size % embeddings_batch_size == 0
+ or EMBEDDINGS_BATCH_SIZE % embeddings_batch_size == 0
+ ), (
+ f"the shard size {self.shard_size} and embeddings"
+ f" shard size {EMBEDDINGS_BATCH_SIZE} are not"
+ " divisible"
+ )
+
+ for xb_j in tqdm(
+ self._iterate_transformed(
+ self.xb_ds,
+ start,
+ embeddings_batch_size,
+ np.float32,
+ ),
+ file=sys.stdout,
+ ):
+ if is_pretransform_index(index):
+ assert xb_j.shape[1] == index.chain.at(0).d_out
+ index_ivf.add_with_ids(
+ xb_j,
+ np.arange(start + jj, start + jj + xb_j.shape[0]),
+ )
+ else:
+ assert xb_j.shape[1] == index.d
+ index.add_with_ids(
+ xb_j,
+ np.arange(start + jj, start + jj + xb_j.shape[0]),
+ )
+ jj += xb_j.shape[0]
+ logging.info(jj)
+ assert (
+ jj <= self.shard_size
+ ), f"jj {jj} and shard_zide {self.shard_size}"
+ if jj == self.shard_size:
+ break
+ logging.info(f"writing {sfn}...")
+ index_ivf.quantizer = cpu_quantizer
+ faiss.write_index(index, sfn)
+ except FileExistsError:
+ logging.info(f"skipping shard: {i}")
+ continue
+ logging.info("done")
+
+ def merge_index(self):
+ ivf_file = f"{self.index_file}.ivfdata"
+
+ assert os.path.exists(self.index_template_file)
+ assert not os.path.exists(
+ ivf_file
+ ), f"file with embeddings data {ivf_file} not found, check."
+ assert not os.path.exists(self.index_file)
+ index = faiss.read_index(self.index_template_file)
+ block_fnames = [
+ f"{self.index_shard_prefix}{i}" for i in range(self.nshards)
+ ]
+ for fn in block_fnames:
+ assert os.path.exists(fn)
+ logging.info(block_fnames)
+ logging.info("merging...")
+ merge_ondisk(index, block_fnames, ivf_file)
+ logging.info("writing index...")
+ faiss.write_index(index, self.index_file)
+ logging.info("done")
+
+ def _cached_search(
+ self,
+ sample,
+ xq_ds,
+ xb_ds,
+ idx_file,
+ vecs_file,
+ I_file,
+ D_file,
+ index_file=None,
+ nprobe=None,
+ ):
+ if not os.path.exists(I_file):
+ assert not os.path.exists(I_file), f"file {I_file} does not exist "
+ assert not os.path.exists(D_file), f"file {D_file} does not exist "
+ xq = xq_ds.sample(sample, idx_file, vecs_file)
+
+ if index_file:
+ D, I = self._index_nonsharded_search(index_file, xq, nprobe)
+ else:
+ logging.info("ground truth computations")
+ db_iterator = xb_ds.iterate(0, 100_000, np.float32)
+ D, I = knn_ground_truth(
+ xq, db_iterator, self.k, metric_type=self.metric
+ )
+ assert np.amin(I) >= 0
+
+ np.save(I_file, I)
+ np.save(D_file, D)
+ else:
+ assert os.path.exists(idx_file), f"file {idx_file} does not exist "
+ assert os.path.exists(
+ vecs_file
+ ), f"file {vecs_file} does not exist "
+ assert os.path.exists(I_file), f"file {I_file} does not exist "
+ assert os.path.exists(D_file), f"file {D_file} does not exist "
+ I = np.load(I_file)
+ D = np.load(D_file)
+ assert I.shape == (sample, self.k), f"{I_file} shape mismatch"
+ assert D.shape == (sample, self.k), f"{D_file} shape mismatch"
+ return (D, I)
+
+ def _index_search(self, index_shard_prefix, xq, nprobe):
+ assert nprobe is not None
+ logging.info(
+ f"open sharded index: {index_shard_prefix}, {self.nshards}"
+ )
+ index = self._open_sharded_index(index_shard_prefix)
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ logging.info(f"setting nprobe to {nprobe}")
+ index_ivf.nprobe = nprobe
+ return index.search(xq, self.k)
+
+ def _index_nonsharded_search(self, index_file, xq, nprobe):
+ assert nprobe is not None
+ logging.info(f"index {index_file}")
+ assert os.path.exists(index_file), f"file {index_file} does not exist "
+ index = faiss.read_index(index_file, faiss.IO_FLAG_ONDISK_SAME_DIR)
+ logging.info(f"index size {index.ntotal} ")
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ logging.info(f"setting nprobe to {nprobe}")
+ index_ivf.nprobe = nprobe
+ return index.search(xq, self.k)
+
+ def _refine_distances(self, xq_ds, idx, xb_ds, I):
+ xq = xq_ds.get(idx).repeat(self.k, axis=0)
+ xb = xb_ds.get(I.reshape(-1))
+ if self.metric == faiss.METRIC_INNER_PRODUCT:
+ return (xq * xb).sum(axis=1).reshape(I.shape)
+ elif self.metric == faiss.METRIC_L2:
+ return ((xq - xb) ** 2).sum(axis=1).reshape(I.shape)
+ else:
+ raise ValueError(f"metric not supported {self.metric}")
+
+ def evaluate(self):
+ self._evaluate(
+ self.index_factory_fn,
+ self.index_file,
+ self.xq_index_file,
+ self.nprobe,
+ )
+
+ def _evaluate(self, index_factory_fn, index_file, xq_index_file, nprobe):
+ idx_a_file = f"{self.eval_dir}/idx_a.npy"
+ idx_b_gt_file = f"{self.eval_dir}/idx_b_gt.npy"
+ idx_b_ann_file = (
+ f"{self.eval_dir}/idx_b_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+ vecs_a_file = f"{self.eval_dir}/vecs_a.npy"
+ vecs_b_gt_file = f"{self.eval_dir}/vecs_b_gt.npy"
+ vecs_b_ann_file = (
+ f"{self.eval_dir}/vecs_b_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+ D_a_gt_file = f"{self.eval_dir}/D_a_gt.npy"
+ D_a_ann_file = (
+ f"{self.eval_dir}/D_a_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+ D_a_ann_refined_file = f"{self.eval_dir}/D_a_ann_refined_{index_factory_fn}_np{nprobe}.npy"
+ D_b_gt_file = f"{self.eval_dir}/D_b_gt.npy"
+ D_b_ann_file = (
+ f"{self.eval_dir}/D_b_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+ D_b_ann_gt_file = (
+ f"{self.eval_dir}/D_b_ann_gt_{index_factory_fn}_np{nprobe}.npy"
+ )
+ I_a_gt_file = f"{self.eval_dir}/I_a_gt.npy"
+ I_a_ann_file = (
+ f"{self.eval_dir}/I_a_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+ I_b_gt_file = f"{self.eval_dir}/I_b_gt.npy"
+ I_b_ann_file = (
+ f"{self.eval_dir}/I_b_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+ I_b_ann_gt_file = (
+ f"{self.eval_dir}/I_b_ann_gt_{index_factory_fn}_np{nprobe}.npy"
+ )
+ margin_gt_file = f"{self.eval_dir}/margin_gt.npy"
+ margin_refined_file = (
+ f"{self.eval_dir}/margin_refined_{index_factory_fn}_np{nprobe}.npy"
+ )
+ margin_ann_file = (
+ f"{self.eval_dir}/margin_ann_{index_factory_fn}_np{nprobe}.npy"
+ )
+
+ logging.info("exact search forward")
+ # xq -> xb AKA a -> b
+ D_a_gt, I_a_gt = self._cached_search(
+ self.evaluation_sample,
+ self.xq_ds,
+ self.xb_ds,
+ idx_a_file,
+ vecs_a_file,
+ I_a_gt_file,
+ D_a_gt_file,
+ )
+ idx_a = np.load(idx_a_file)
+
+ logging.info("approximate search forward")
+ D_a_ann, I_a_ann = self._cached_search(
+ self.evaluation_sample,
+ self.xq_ds,
+ self.xb_ds,
+ idx_a_file,
+ vecs_a_file,
+ I_a_ann_file,
+ D_a_ann_file,
+ index_file,
+ nprobe,
+ )
+
+ logging.info(
+ "calculate refined distances on approximate search forward"
+ )
+ if os.path.exists(D_a_ann_refined_file):
+ D_a_ann_refined = np.load(D_a_ann_refined_file)
+ assert D_a_ann.shape == D_a_ann_refined.shape
+ else:
+ D_a_ann_refined = self._refine_distances(
+ self.xq_ds, idx_a, self.xb_ds, I_a_ann
+ )
+ np.save(D_a_ann_refined_file, D_a_ann_refined)
+
+ if self.evaluate_by_margin:
+ k_extract = self.k
+ margin_threshold = 1.05
+ logging.info(
+ "exact search backward from the k_extract NN results of"
+ " forward search"
+ )
+ # xb -> xq AKA b -> a
+ D_a_b_gt = D_a_gt[:, :k_extract].ravel()
+ idx_b_gt = I_a_gt[:, :k_extract].ravel()
+ assert len(idx_b_gt) == self.evaluation_sample * k_extract
+ np.save(idx_b_gt_file, idx_b_gt)
+ # exact search
+ D_b_gt, _ = self._cached_search(
+ len(idx_b_gt),
+ self.xb_ds,
+ self.xq_ds,
+ idx_b_gt_file,
+ vecs_b_gt_file,
+ I_b_gt_file,
+ D_b_gt_file,
+ ) # xb and xq ^^^ are inverted
+
+ logging.info("margin on exact search")
+ margin_gt = margin(
+ self.evaluation_sample,
+ idx_a,
+ idx_b_gt,
+ D_a_b_gt,
+ D_a_gt,
+ D_b_gt,
+ self.k,
+ k_extract,
+ margin_threshold,
+ )
+ np.save(margin_gt_file, margin_gt)
+
+ logging.info(
+ "exact search backward from the k_extract NN results of"
+ " approximate forward search"
+ )
+ D_a_b_refined = D_a_ann_refined[:, :k_extract].ravel()
+ idx_b_ann = I_a_ann[:, :k_extract].ravel()
+ assert len(idx_b_ann) == self.evaluation_sample * k_extract
+ np.save(idx_b_ann_file, idx_b_ann)
+ # exact search
+ D_b_ann_gt, _ = self._cached_search(
+ len(idx_b_ann),
+ self.xb_ds,
+ self.xq_ds,
+ idx_b_ann_file,
+ vecs_b_ann_file,
+ I_b_ann_gt_file,
+ D_b_ann_gt_file,
+ ) # xb and xq ^^^ are inverted
+
+ logging.info("refined margin on approximate search")
+ margin_refined = margin(
+ self.evaluation_sample,
+ idx_a,
+ idx_b_ann,
+ D_a_b_refined,
+ D_a_gt, # not D_a_ann_refined(!)
+ D_b_ann_gt,
+ self.k,
+ k_extract,
+ margin_threshold,
+ )
+ np.save(margin_refined_file, margin_refined)
+
+ D_b_ann, I_b_ann = self._cached_search(
+ len(idx_b_ann),
+ self.xb_ds,
+ self.xq_ds,
+ idx_b_ann_file,
+ vecs_b_ann_file,
+ I_b_ann_file,
+ D_b_ann_file,
+ xq_index_file,
+ nprobe,
+ )
+
+ D_a_b_ann = D_a_ann[:, :k_extract].ravel()
+
+ logging.info("approximate search margin")
+
+ margin_ann = margin(
+ self.evaluation_sample,
+ idx_a,
+ idx_b_ann,
+ D_a_b_ann,
+ D_a_ann,
+ D_b_ann,
+ self.k,
+ k_extract,
+ margin_threshold,
+ )
+ np.save(margin_ann_file, margin_ann)
+
+ logging.info("intersection")
+ logging.info(I_a_gt)
+ logging.info(I_a_ann)
+
+ for i in range(1, self.k + 1):
+ logging.info(
+ f"{i}: {knn_intersection_measure(I_a_gt[:,:i], I_a_ann[:,:i])}"
+ )
+
+ logging.info(f"mean of gt distances: {D_a_gt.mean()}")
+ logging.info(f"mean of approx distances: {D_a_ann.mean()}")
+ logging.info(f"mean of refined distances: {D_a_ann_refined.mean()}")
+
+ logging.info("intersection cardinality frequencies")
+ logging.info(get_intersection_cardinality_frequencies(I_a_ann, I_a_gt))
+
+ logging.info("done")
+ pass
+
+ def _knn_function(self, xq, xb, k, metric, thread_id=None):
+ try:
+ return faiss.knn_gpu(
+ self.all_gpu_resources[thread_id],
+ xq,
+ xb,
+ k,
+ metric=metric,
+ device=thread_id,
+ vectorsMemoryLimit=self.knn_vectors_memory_limit,
+ queriesMemoryLimit=self.knn_queries_memory_limit,
+ )
+ except Exception:
+ logging.info(f"knn_function failed: {xq.shape}, {xb.shape}")
+ raise
+
+ def _coarse_quantize(self, index_ivf, xq, nprobe):
+ assert nprobe <= index_ivf.quantizer.ntotal
+ quantizer = faiss.index_cpu_to_all_gpus(index_ivf.quantizer)
+ bs = 100_000
+ nq = len(xq)
+ q_assign = np.empty((nq, nprobe), dtype="int32")
+ for i0 in trange(0, nq, bs):
+ i1 = min(nq, i0 + bs)
+ _, q_assign_i = quantizer.search(xq[i0:i1], nprobe)
+ q_assign[i0:i1] = q_assign_i
+ return q_assign
+
+ def search(self):
+ logging.info(f"search: {self.knn_dir}")
+ slurm_job_id = os.environ.get("SLURM_JOB_ID")
+
+ ngpu = faiss.get_num_gpus()
+ logging.info(f"number of gpus: {ngpu}")
+ self.all_gpu_resources = [
+ faiss.StandardGpuResources() for _ in range(ngpu)
+ ]
+ self._knn_function(
+ np.zeros((10, 10), dtype=np.float16),
+ np.zeros((10, 10), dtype=np.float16),
+ self.k,
+ metric=self.metric,
+ thread_id=0,
+ )
+
+ index = self._open_sharded_index()
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ logging.info(f"setting nprobe to {self.nprobe}")
+ index_ivf.nprobe = self.nprobe
+ # quantizer = faiss.index_cpu_to_all_gpus(index_ivf.quantizer)
+ for i in range(0, self.xq_ds.size, self.xq_bs):
+ Ifn = f"{self.knn_dir}/I{(i):010}_{self.knn_output_file_suffix}"
+ Dfn = f"{self.knn_dir}/D_approx{(i):010}_{self.knn_output_file_suffix}"
+ CPfn = f"{self.knn_dir}/CP{(i):010}_{self.knn_output_file_suffix}"
+
+ if slurm_job_id:
+ worker_record = (
+ self.knn_dir
+ + f"/record_{(i):010}_{self.knn_output_file_suffix}.txt"
+ )
+ if not os.path.exists(worker_record):
+ logging.info(
+ f"creating record file {worker_record} and saving job"
+ f" id: {slurm_job_id}"
+ )
+ with open(worker_record, "w") as h:
+ h.write(slurm_job_id)
+ else:
+ old_slurm_id = open(worker_record, "r").read()
+ logging.info(
+ f"old job slurm id {old_slurm_id} and current job id:"
+ f" {slurm_job_id}"
+ )
+ if old_slurm_id == slurm_job_id:
+ if os.path.getsize(Ifn) == 0:
+ logging.info(
+ f"cleaning up zero length files {Ifn} and"
+ f" {Dfn}"
+ )
+ os.remove(Ifn)
+ os.remove(Dfn)
+
+ try:
+ if is_pretransform_index(index):
+ d = index.chain.at(0).d_out
+ else:
+ d = self.input_d
+ with open(Ifn, "xb") as f, open(Dfn, "xb") as g:
+ xq_i = np.empty(
+ shape=(self.xq_bs, d), dtype=np.float16
+ )
+ q_assign = np.empty(
+ (self.xq_bs, self.nprobe), dtype=np.int32
+ )
+ j = 0
+ quantizer = faiss.index_cpu_to_all_gpus(
+ index_ivf.quantizer
+ )
+ for xq_i_j in tqdm(
+ self._iterate_transformed(
+ self.xq_ds, i, min(100_000, self.xq_bs), np.float16
+ ),
+ file=sys.stdout,
+ ):
+ xq_i[j:j + xq_i_j.shape[0]] = xq_i_j
+ (
+ _,
+ q_assign[j:j + xq_i_j.shape[0]],
+ ) = quantizer.search(xq_i_j, self.nprobe)
+ j += xq_i_j.shape[0]
+ assert j <= xq_i.shape[0]
+ if j == xq_i.shape[0]:
+ break
+ xq_i = xq_i[:j]
+ q_assign = q_assign[:j]
+
+ assert q_assign.shape == (xq_i.shape[0], index_ivf.nprobe)
+ del quantizer
+ logging.info(f"computing: {Ifn}")
+ logging.info(f"computing: {Dfn}")
+ prefetch_threads = faiss.get_num_gpus()
+ D_ann, I = big_batch_search(
+ index_ivf,
+ xq_i,
+ self.k,
+ verbose=10,
+ method="knn_function",
+ knn=self._knn_function,
+ threaded=faiss.get_num_gpus() * 8,
+ use_float16=True,
+ prefetch_threads=prefetch_threads,
+ computation_threads=faiss.get_num_gpus(),
+ q_assign=q_assign,
+ checkpoint=CPfn,
+ checkpoint_freq=7200, # in seconds
+ )
+ assert (
+ np.amin(I) >= 0
+ ), f"{I}, there exists negative indices, check"
+ logging.info(f"saving: {Ifn}")
+ np.save(f, I)
+ logging.info(f"saving: {Dfn}")
+ np.save(g, D_ann)
+
+ if os.path.exists(CPfn):
+ logging.info(f"removing: {CPfn}")
+ os.remove(CPfn)
+
+ except FileExistsError:
+ logging.info(f"skipping {Ifn}, already exists")
+ logging.info(f"skipping {Dfn}, already exists")
+ continue
+
+ def _open_index_shard(self, fn):
+ if fn in self.index_shards:
+ index_shard = self.index_shards[fn]
+ else:
+ logging.info(f"open index shard: {fn}")
+ index_shard = faiss.read_index(
+ fn, faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY
+ )
+ self.index_shards[fn] = index_shard
+ return index_shard
+
+ def _open_sharded_index(self, index_shard_prefix=None):
+ if index_shard_prefix is None:
+ index_shard_prefix = self.index_shard_prefix
+ if index_shard_prefix in self.index:
+ return self.index[index_shard_prefix]
+ assert os.path.exists(
+ self.index_template_file
+ ), f"file {self.index_template_file} does not exist "
+ logging.info(f"open index template: {self.index_template_file}")
+ index = faiss.read_index(self.index_template_file)
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ ilv = faiss.InvertedListsPtrVector()
+ for i in range(self.nshards):
+ fn = f"{index_shard_prefix}{i}"
+ assert os.path.exists(fn), f"file {fn} does not exist "
+ logging.info(fn)
+ index_shard = self._open_index_shard(fn)
+ il = faiss.downcast_index(
+ faiss.extract_index_ivf(index_shard)
+ ).invlists
+ ilv.push_back(il)
+ hsil = faiss.HStackInvertedLists(ilv.size(), ilv.data())
+ index_ivf.replace_invlists(hsil, False)
+ self.ivls[index_shard_prefix] = hsil
+ self.index[index_shard_prefix] = index
+ return index
+
+ def index_shard_stats(self):
+ for i in range(self.nshards):
+ fn = f"{self.index_shard_prefix}{i}"
+ assert os.path.exists(fn)
+ index = faiss.read_index(
+ fn, faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY
+ )
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ il = index_ivf.invlists
+ il.print_stats()
+
+ def index_stats(self):
+ index = self._open_sharded_index()
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ il = index_ivf.invlists
+ list_sizes = [il.list_size(i) for i in range(il.nlist)]
+ logging.info(np.max(list_sizes))
+ logging.info(np.mean(list_sizes))
+ logging.info(np.argmax(list_sizes))
+ logging.info("index_stats:")
+ il.print_stats()
+
+ def consistency_check(self):
+ logging.info("consistency-check")
+
+ logging.info("index template...")
+
+ assert os.path.exists(self.index_template_file)
+ index = faiss.read_index(self.index_template_file)
+
+ offset = 0 # 2**24
+ assert self.shard_size > offset + SMALL_DATA_SAMPLE
+
+ logging.info("index shards...")
+ for i in range(self.nshards):
+ r = i * self.shard_size + offset
+ xb = next(self.xb_ds.iterate(r, SMALL_DATA_SAMPLE, np.float32))
+ fn = f"{self.index_shard_prefix}{i}"
+ assert os.path.exists(fn), f"There is no index shard file {fn}"
+ index = self._open_index_shard(fn)
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ index_ivf.nprobe = 1
+ _, I = index.search(xb, 100)
+ for j in range(SMALL_DATA_SAMPLE):
+ assert np.where(I[j] == j + r)[0].size > 0, (
+ f"I[j]: {I[j]}, j: {j}, i: {i}, shard_size:"
+ f" {self.shard_size}"
+ )
+
+ logging.info("merged index...")
+ index = self._open_sharded_index()
+ index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index))
+ index_ivf.nprobe = 1
+ for i in range(self.nshards):
+ r = i * self.shard_size + offset
+ xb = next(self.xb_ds.iterate(r, SMALL_DATA_SAMPLE, np.float32))
+ _, I = index.search(xb, 100)
+ for j in range(SMALL_DATA_SAMPLE):
+ assert np.where(I[j] == j + r)[0].size > 0, (
+ f"I[j]: {I[j]}, j: {j}, i: {i}, shard_size:"
+ f" {self.shard_size}")
+
+ logging.info("search results...")
+ index_ivf.nprobe = self.nprobe
+ for i in range(0, self.xq_ds.size, self.xq_bs):
+ Ifn = f"{self.knn_dir}/I{i:010}_{self.index_factory_fn}_np{self.nprobe}.npy"
+ assert os.path.exists(Ifn)
+ assert os.path.getsize(Ifn) > 0, f"The file {Ifn} is empty."
+ logging.info(Ifn)
+ I = np.load(Ifn, mmap_mode="r")
+
+ assert I.shape[1] == self.k
+ assert I.shape[0] == min(self.xq_bs, self.xq_ds.size - i)
+ assert np.all(I[:, 1] >= 0)
+
+ Dfn = f"{self.knn_dir}/D_approx{i:010}_{self.index_factory_fn}_np{self.nprobe}.npy"
+ assert os.path.exists(Dfn)
+ assert os.path.getsize(Dfn) > 0, f"The file {Dfn} is empty."
+ logging.info(Dfn)
+ D = np.load(Dfn, mmap_mode="r")
+ assert D.shape == I.shape
+
+ xq = next(self.xq_ds.iterate(i, SMALL_DATA_SAMPLE, np.float32))
+ D_online, I_online = index.search(xq, self.k)
+ assert (
+ np.where(I[:SMALL_DATA_SAMPLE] == I_online)[0].size
+ / (self.k * SMALL_DATA_SAMPLE)
+ > 0.95
+ ), (
+ "the ratio is"
+ f" {np.where(I[:SMALL_DATA_SAMPLE] == I_online)[0].size / (self.k * SMALL_DATA_SAMPLE)}"
+ )
+ assert np.allclose(
+ D[:SMALL_DATA_SAMPLE].sum(axis=1),
+ D_online.sum(axis=1),
+ rtol=0.01,
+ ), (
+ "the difference is"
+ f" {D[:SMALL_DATA_SAMPLE].sum(axis=1), D_online.sum(axis=1)}"
+ )
+
+ logging.info("done")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/run.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/run.py
new file mode 100644
index 0000000..563a3e4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/run.py
@@ -0,0 +1,219 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+from utils import (
+ load_config,
+ add_group_args,
+)
+from offline_ivf import OfflineIVF
+import faiss
+from typing import List, Callable, Dict
+import submitit
+
+
+def join_lists_in_dict(poss: List[str]) -> List[str]:
+ """
+ Joins two lists of prod and non-prod values, checking if the prod value is already included.
+ If there is no non-prod list, it returns the prod list.
+ """
+ if "non-prod" in poss.keys():
+ all_poss = poss["non-prod"]
+ if poss["prod"][-1] not in poss["non-prod"]:
+ all_poss += poss["prod"]
+ return all_poss
+ else:
+ return poss["prod"]
+
+
+def main(
+ args: argparse.Namespace,
+ cfg: Dict[str, str],
+ nprobe: int,
+ index_factory_str: str,
+) -> None:
+ oivf = OfflineIVF(cfg, args, nprobe, index_factory_str)
+ eval(f"oivf.{args.command}()")
+
+
+def process_options_and_run_jobs(args: argparse.Namespace) -> None:
+ """
+ If "--cluster_run", it launches an array of jobs to the cluster using the submitit library for all the index strings. In
+ the case of evaluate, it launches a job for each index string and nprobe pair. Otherwise, it launches a single job
+ that is ran locally with the prod values for index string and nprobe.
+ """
+
+ cfg = load_config(args.config)
+ index_strings = cfg["index"]
+ nprobes = cfg["nprobe"]
+ if args.command == "evaluate":
+ if args.cluster_run:
+ all_nprobes = join_lists_in_dict(nprobes)
+ all_index_strings = join_lists_in_dict(index_strings)
+ for index_factory_str in all_index_strings:
+ for nprobe in all_nprobes:
+ launch_job(main, args, cfg, nprobe, index_factory_str)
+ else:
+ launch_job(
+ main, args, cfg, nprobes["prod"][-1], index_strings["prod"][-1]
+ )
+ else:
+ if args.cluster_run:
+ all_index_strings = join_lists_in_dict(index_strings)
+ for index_factory_str in all_index_strings:
+ launch_job(
+ main, args, cfg, nprobes["prod"][-1], index_factory_str
+ )
+ else:
+ launch_job(
+ main, args, cfg, nprobes["prod"][-1], index_strings["prod"][-1]
+ )
+
+
+def launch_job(
+ func: Callable,
+ args: argparse.Namespace,
+ cfg: Dict[str, str],
+ n_probe: int,
+ index_str: str,
+) -> None:
+ """
+ Launches an array of slurm jobs to the cluster using the submitit library.
+ """
+
+ if args.cluster_run:
+ assert args.num_nodes >= 1
+ executor = submitit.AutoExecutor(folder=args.logs_dir)
+
+ executor.update_parameters(
+ nodes=args.num_nodes,
+ gpus_per_node=args.gpus_per_node,
+ cpus_per_task=args.cpus_per_task,
+ tasks_per_node=args.tasks_per_node,
+ name=args.job_name,
+ slurm_partition=args.partition,
+ slurm_time=70 * 60,
+ )
+ if args.slurm_constraint:
+ executor.update_parameters(slurm_constraint=args.slurm_constrain)
+
+ job = executor.submit(func, args, cfg, n_probe, index_str)
+ print(f"Job id: {job.job_id}")
+ else:
+ func(args, cfg, n_probe, index_str)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ group = parser.add_argument_group("general")
+
+ add_group_args(group, "--command", required=True, help="command to run")
+ add_group_args(
+ group,
+ "--config",
+ required=True,
+ help="config yaml with the dataset specs",
+ )
+ add_group_args(
+ group, "--nt", type=int, default=96, help="nb search threads"
+ )
+ add_group_args(
+ group,
+ "--no_residuals",
+ action="store_false",
+ help="set index.by_residual to False during train index.",
+ )
+
+ group = parser.add_argument_group("slurm_job")
+
+ add_group_args(
+ group,
+ "--cluster_run",
+ action="store_true",
+ help=" if True, runs in cluster",
+ )
+ add_group_args(
+ group,
+ "--job_name",
+ type=str,
+ default="oivf",
+ help="cluster job name",
+ )
+ add_group_args(
+ group,
+ "--num_nodes",
+ type=str,
+ default=1,
+ help="num of nodes per job",
+ )
+ add_group_args(
+ group,
+ "--tasks_per_node",
+ type=int,
+ default=1,
+ help="tasks per job",
+ )
+
+ add_group_args(
+ group,
+ "--gpus_per_node",
+ type=int,
+ default=8,
+ help="cluster job name",
+ )
+ add_group_args(
+ group,
+ "--cpus_per_task",
+ type=int,
+ default=80,
+ help="cluster job name",
+ )
+
+ add_group_args(
+ group,
+ "--logs_dir",
+ type=str,
+ default="/checkpoint/marialomeli/offline_faiss/logs",
+ help="cluster job name",
+ )
+
+ add_group_args(
+ group,
+ "--slurm_constraint",
+ type=str,
+ default=None,
+ help="can be volta32gb for the fair cluster",
+ )
+
+ add_group_args(
+ group,
+ "--partition",
+ type=str,
+ default="learnlab",
+ help="specify which partition to use if ran on cluster with job arrays",
+ choices=[
+ "learnfair",
+ "devlab",
+ "scavenge",
+ "learnlab",
+ "nllb",
+ "seamless",
+ "seamless_medium",
+ "learnaccel",
+ "onellm_low",
+ "learn",
+ "scavenge",
+ ],
+ )
+
+ group = parser.add_argument_group("dataset")
+
+ add_group_args(group, "--xb", required=True, help="database vectors")
+ add_group_args(group, "--xq", help="query vectors")
+
+ args = parser.parse_args()
+ print("args:", args)
+ faiss.omp_set_num_threads(args.nt)
+ process_options_and_run_jobs(args=args)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/tests/testing_utils.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/tests/testing_utils.py
new file mode 100644
index 0000000..0d2dc49
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/tests/testing_utils.py
@@ -0,0 +1,181 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import yaml
+import numpy as np
+from typing import Dict, List, Optional
+
+OIVF_TEST_ARGS: List[str] = [
+ "--config",
+ "--xb",
+ "--xq",
+ "--command",
+ "--cluster_run",
+ "--no_residuals",
+]
+
+
+def get_test_parser(args) -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser()
+ for arg in args:
+ parser.add_argument(arg)
+ return parser
+
+
+class TestDataCreator:
+ def __init__(
+ self,
+ tempdir: str,
+ dimension: int,
+ data_type: np.dtype,
+ index_factory: Optional[List] = ["OPQ4,IVF256,PQ4"],
+ training_sample: Optional[int] = 9984,
+ index_shard_size: Optional[int] = 1000,
+ query_batch_size: Optional[int] = 1000,
+ evaluation_sample: Optional[int] = 100,
+ num_files: Optional[int] = None,
+ file_size: Optional[int] = None,
+ file_sizes: Optional[List] = None,
+ nprobe: Optional[int] = 64,
+ k: Optional[int] = 10,
+ metric: Optional[str] = "METRIC_L2",
+ normalise: Optional[bool] = False,
+ with_queries_ds: Optional[bool] = False,
+ evaluate_by_margin: Optional[bool] = False,
+ ) -> None:
+ self.tempdir = tempdir
+ self.dimension = dimension
+ self.data_type = np.dtype(data_type).name
+ self.index_factory = {"prod": index_factory}
+ if file_size and num_files:
+ self.file_sizes = [file_size for _ in range(num_files)]
+ elif file_sizes:
+ self.file_sizes = file_sizes
+ else:
+ raise ValueError("no file sizes provided")
+ self.num_files = len(self.file_sizes)
+ self.training_sample = training_sample
+ self.index_shard_size = index_shard_size
+ self.query_batch_size = query_batch_size
+ self.evaluation_sample = evaluation_sample
+ self.nprobe = {"prod": [nprobe]}
+ self.k = k
+ self.metric = metric
+ self.normalise = normalise
+ self.config_file = self.tempdir + "/config_test.yaml"
+ self.ds_name = "my_test_data"
+ self.qs_name = "my_queries_data"
+ self.evaluate_by_margin = evaluate_by_margin
+ self.with_queries_ds = with_queries_ds
+
+ def create_test_data(self) -> None:
+ datafiles = self._create_data_files()
+ files_info = []
+
+ for i, file in enumerate(datafiles):
+ files_info.append(
+ {
+ "dtype": self.data_type,
+ "format": "npy",
+ "name": file,
+ "size": self.file_sizes[i],
+ }
+ )
+
+ config_for_yaml = {
+ "d": self.dimension,
+ "output": self.tempdir,
+ "index": self.index_factory,
+ "nprobe": self.nprobe,
+ "k": self.k,
+ "normalise": self.normalise,
+ "metric": self.metric,
+ "training_sample": self.training_sample,
+ "evaluation_sample": self.evaluation_sample,
+ "index_shard_size": self.index_shard_size,
+ "query_batch_size": self.query_batch_size,
+ "datasets": {
+ self.ds_name: {
+ "root": self.tempdir,
+ "size": sum(self.file_sizes),
+ "files": files_info,
+ }
+ },
+ }
+ if self.evaluate_by_margin:
+ config_for_yaml["evaluate_by_margin"] = self.evaluate_by_margin
+ q_datafiles = self._create_data_files("my_q_data")
+ q_files_info = []
+
+ for i, file in enumerate(q_datafiles):
+ q_files_info.append(
+ {
+ "dtype": self.data_type,
+ "format": "npy",
+ "name": file,
+ "size": self.file_sizes[i],
+ }
+ )
+ if self.with_queries_ds:
+ config_for_yaml["datasets"][self.qs_name] = {
+ "root": self.tempdir,
+ "size": sum(self.file_sizes),
+ "files": q_files_info,
+ }
+
+ self._create_config_yaml(config_for_yaml)
+
+ def setup_cli(self, command="consistency_check") -> argparse.Namespace:
+ parser = get_test_parser(OIVF_TEST_ARGS)
+
+ if self.with_queries_ds:
+ return parser.parse_args(
+ [
+ "--xb",
+ self.ds_name,
+ "--config",
+ self.config_file,
+ "--command",
+ command,
+ "--xq",
+ self.qs_name,
+ ]
+ )
+ return parser.parse_args(
+ [
+ "--xb",
+ self.ds_name,
+ "--config",
+ self.config_file,
+ "--command",
+ command,
+ ]
+ )
+
+ def _create_data_files(self, name_of_file="my_data") -> List[str]:
+ """
+ Creates a dataset "my_test_data" with number of files (num_files), using padding in the files
+ name. If self.with_queries is True, it adds an extra dataset "my_queries_data" with the same number of files
+ as the "my_test_data". The default name for embeddings files is "my_data" + <padding>.npy.
+ """
+ filenames = []
+ for i, file_size in enumerate(self.file_sizes):
+ # np.random.seed(i)
+ db_vectors = np.random.random((file_size, self.dimension)).astype(
+ self.data_type
+ )
+ filename = name_of_file + f"{i:02}" + ".npy"
+ filenames.append(filename)
+ np.save(self.tempdir + "/" + filename, db_vectors)
+ return filenames
+
+ def _create_config_yaml(self, dict_file: Dict[str, str]) -> None:
+ """
+ Creates a yaml file in dir (can be a temporary dir for tests).
+ """
+ filename = self.tempdir + "/config_test.yaml"
+ with open(filename, "w") as file:
+ yaml.dump(dict_file, file, default_flow_style=False)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/utils.py b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/utils.py
new file mode 100644
index 0000000..c1d91c9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/offline_ivf/utils.py
@@ -0,0 +1,95 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import os
+from typing import Dict
+import yaml
+import faiss
+from faiss.contrib.datasets import SyntheticDataset
+
+
+def load_config(config):
+ assert os.path.exists(config)
+ with open(config, "r") as f:
+ return yaml.safe_load(f)
+
+
+def faiss_sanity_check():
+ ds = SyntheticDataset(256, 0, 100, 100)
+ xq = ds.get_queries()
+ xb = ds.get_database()
+ index_cpu = faiss.IndexFlat(ds.d)
+ index_gpu = faiss.index_cpu_to_all_gpus(index_cpu)
+ index_cpu.add(xb)
+ index_gpu.add(xb)
+ D_cpu, I_cpu = index_cpu.search(xq, 10)
+ D_gpu, I_gpu = index_gpu.search(xq, 10)
+ assert np.all(I_cpu == I_gpu), "faiss sanity check failed"
+ assert np.all(np.isclose(D_cpu, D_gpu)), "faiss sanity check failed"
+
+
+def margin(sample, idx_a, idx_b, D_a_b, D_a, D_b, k, k_extract, threshold):
+ """
+ two datasets: xa, xb; n = number of pairs
+ idx_a - (np,) - query vector ids in xa
+ idx_b - (np,) - query vector ids in xb
+ D_a_b - (np,) - pairwise distances between xa[idx_a] and xb[idx_b]
+ D_a - (np, k) - distances between vectors xa[idx_a] and corresponding nearest neighbours in xb
+ D_b - (np, k) - distances between vectors xb[idx_b] and corresponding nearest neighbours in xa
+ k - k nearest neighbours used for margin
+ k_extract - number of nearest neighbours of each query in xb we consider for margin calculation and filtering
+ threshold - margin threshold
+ """
+
+ n = sample
+ nk = n * k_extract
+ assert idx_a.shape == (n,)
+ idx_a_k = idx_a.repeat(k_extract)
+ assert idx_a_k.shape == (nk,)
+ assert idx_b.shape == (nk,)
+ assert D_a_b.shape == (nk,)
+ assert D_a.shape == (n, k)
+ assert D_b.shape == (nk, k)
+ mean_a = np.mean(D_a, axis=1)
+ assert mean_a.shape == (n,)
+ mean_a_k = mean_a.repeat(k_extract)
+ assert mean_a_k.shape == (nk,)
+ mean_b = np.mean(D_b, axis=1)
+ assert mean_b.shape == (nk,)
+ margin = 2 * D_a_b / (mean_a_k + mean_b)
+ above_threshold = margin > threshold
+ print(np.count_nonzero(above_threshold))
+ print(idx_a_k[above_threshold])
+ print(idx_b[above_threshold])
+ print(margin[above_threshold])
+ return margin
+
+
+def add_group_args(group, *args, **kwargs):
+ return group.add_argument(*args, **kwargs)
+
+
+def get_intersection_cardinality_frequencies(
+ I: np.ndarray, I_gt: np.ndarray
+) -> Dict[int, int]:
+ """
+ Computes the frequencies for the cardinalities of the intersection of neighbour indices.
+ """
+ nq = I.shape[0]
+ res = []
+ for ell in range(nq):
+ res.append(len(np.intersect1d(I[ell, :], I_gt[ell, :])))
+ values, counts = np.unique(res, return_counts=True)
+ return dict(zip(values, counts))
+
+
+def is_pretransform_index(index):
+ if index.__class__ == faiss.IndexPreTransform:
+ assert hasattr(index, "chain")
+ return True
+ else:
+ assert not hasattr(index, "chain")
+ return False
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/CMakeLists.txt
new file mode 100644
index 0000000..7b92fe7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/CMakeLists.txt
@@ -0,0 +1,13 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+cmake_minimum_required(VERSION 3.17 FATAL_ERROR)
+project (ROCKSDB_IVF)
+set(CMAKE_BUILD_TYPE Debug)
+find_package(faiss REQUIRED)
+find_package(RocksDB REQUIRED)
+
+add_executable(demo_rocksdb_ivf demo_rocksdb_ivf.cpp RocksDBInvertedLists.cpp)
+target_link_libraries(demo_rocksdb_ivf faiss RocksDB::rocksdb)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/README.md b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/README.md
new file mode 100644
index 0000000..cf29ee2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/README.md
@@ -0,0 +1,23 @@
+# Storing Faiss inverted lists in RocksDB
+
+Demo of storing the inverted lists of any IVF index in RocksDB or any similar key-value store which supports the prefix scan operation.
+
+# How to build
+
+We use conda to create the build environment for simplicity. Only tested on Linux x86.
+
+```
+conda create -n rocksdb_ivf
+conda activate rocksdb_ivf
+conda install pytorch::faiss-cpu conda-forge::rocksdb cmake make gxx_linux-64 sysroot_linux-64
+cd ~/faiss/demos/rocksdb_ivf
+cmake -B build .
+make -C build -j$(nproc)
+```
+
+# Run the example
+
+```
+cd ~/faiss/demos/rocksdb_ivf/build
+./rocksdb_ivf test_db
+```
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.cpp
new file mode 100644
index 0000000..a72ec75
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.cpp
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include "RocksDBInvertedLists.h"
+
+#include <faiss/impl/FaissAssert.h>
+
+using namespace faiss;
+
+namespace faiss_rocksdb {
+
+RocksDBInvertedListsIterator::RocksDBInvertedListsIterator(
+ rocksdb::DB* db,
+ size_t list_no,
+ size_t code_size)
+ : InvertedListsIterator(),
+ it(db->NewIterator(rocksdb::ReadOptions())),
+ list_no(list_no),
+ code_size(code_size),
+ codes(code_size) {
+ it->Seek(rocksdb::Slice(
+ reinterpret_cast<const char*>(&list_no), sizeof(size_t)));
+}
+
+bool RocksDBInvertedListsIterator::is_available() const {
+ return it->Valid() &&
+ it->key().starts_with(rocksdb::Slice(
+ reinterpret_cast<const char*>(&list_no), sizeof(size_t)));
+}
+
+void RocksDBInvertedListsIterator::next() {
+ it->Next();
+}
+
+std::pair<idx_t, const uint8_t*> RocksDBInvertedListsIterator::
+ get_id_and_codes() {
+ idx_t id =
+ *reinterpret_cast<const idx_t*>(&it->key().data()[sizeof(size_t)]);
+ assert(code_size == it->value().size());
+ return {id, reinterpret_cast<const uint8_t*>(it->value().data())};
+}
+
+RocksDBInvertedLists::RocksDBInvertedLists(
+ const char* db_directory,
+ size_t nlist,
+ size_t code_size)
+ : InvertedLists(nlist, code_size) {
+ use_iterator = true;
+
+ rocksdb::Options options;
+ options.create_if_missing = true;
+ rocksdb::DB* db;
+ rocksdb::Status status = rocksdb::DB::Open(options, db_directory, &db);
+ db_ = std::unique_ptr<rocksdb::DB>(db);
+ assert(status.ok());
+}
+
+size_t RocksDBInvertedLists::list_size(size_t /*list_no*/) const {
+ FAISS_THROW_MSG("list_size is not supported");
+}
+
+const uint8_t* RocksDBInvertedLists::get_codes(size_t /*list_no*/) const {
+ FAISS_THROW_MSG("get_codes is not supported");
+}
+
+const idx_t* RocksDBInvertedLists::get_ids(size_t /*list_no*/) const {
+ FAISS_THROW_MSG("get_ids is not supported");
+}
+
+size_t RocksDBInvertedLists::add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) {
+ rocksdb::WriteOptions wo;
+ std::vector<char> key(sizeof(size_t) + sizeof(idx_t));
+ memcpy(key.data(), &list_no, sizeof(size_t));
+ for (size_t i = 0; i < n_entry; i++) {
+ memcpy(key.data() + sizeof(size_t), ids + i, sizeof(idx_t));
+ rocksdb::Status status = db_->Put(
+ wo,
+ rocksdb::Slice(key.data(), key.size()),
+ rocksdb::Slice(
+ reinterpret_cast<const char*>(code + i * code_size),
+ code_size));
+ assert(status.ok());
+ }
+ return 0; // ignored
+}
+
+void RocksDBInvertedLists::update_entries(
+ size_t /*list_no*/,
+ size_t /*offset*/,
+ size_t /*n_entry*/,
+ const idx_t* /*ids*/,
+ const uint8_t* /*code*/) {
+ FAISS_THROW_MSG("update_entries is not supported");
+}
+
+void RocksDBInvertedLists::resize(size_t /*list_no*/, size_t /*new_size*/) {
+ FAISS_THROW_MSG("resize is not supported");
+}
+
+InvertedListsIterator* RocksDBInvertedLists::get_iterator(
+ size_t list_no,
+ void* inverted_list_context) const {
+ return new RocksDBInvertedListsIterator(db_.get(), list_no, code_size);
+}
+
+} // namespace faiss_rocksdb
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h
new file mode 100644
index 0000000..c52f57f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <faiss/invlists/InvertedLists.h>
+
+#include <rocksdb/db.h>
+
+namespace faiss_rocksdb {
+
+struct RocksDBInvertedListsIterator : faiss::InvertedListsIterator {
+ RocksDBInvertedListsIterator(
+ rocksdb::DB* db,
+ size_t list_no,
+ size_t code_size);
+ virtual bool is_available() const override;
+ virtual void next() override;
+ virtual std::pair<faiss::idx_t, const uint8_t*> get_id_and_codes() override;
+
+ private:
+ std::unique_ptr<rocksdb::Iterator> it;
+ size_t list_no;
+ size_t code_size;
+ std::vector<uint8_t> codes; // buffer for returning codes in next()
+};
+
+struct RocksDBInvertedLists : faiss::InvertedLists {
+ RocksDBInvertedLists(
+ const char* db_directory,
+ size_t nlist,
+ size_t code_size);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const faiss::idx_t* get_ids(size_t list_no) const override;
+
+ size_t add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const faiss::idx_t* ids,
+ const uint8_t* code) override;
+
+ void update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const faiss::idx_t* ids,
+ const uint8_t* code) override;
+
+ void resize(size_t list_no, size_t new_size) override;
+
+ faiss::InvertedListsIterator* get_iterator(
+ size_t list_no,
+ void* inverted_list_context) const override;
+
+ private:
+ std::unique_ptr<rocksdb::DB> db_;
+};
+
+} // namespace faiss_rocksdb
diff --git a/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/demo_rocksdb_ivf.cpp b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/demo_rocksdb_ivf.cpp
new file mode 100644
index 0000000..5f998d3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/demos/rocksdb_ivf/demo_rocksdb_ivf.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <exception>
+#include <iostream>
+#include <memory>
+
+#include "RocksDBInvertedLists.h"
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissException.h>
+#include <faiss/utils/random.h>
+
+using namespace faiss;
+
+int main(int argc, char* argv[]) {
+ try {
+ if (argc != 2) {
+ std::cerr << "missing db directory argument" << std::endl;
+ return -1;
+ }
+ size_t d = 128;
+ size_t nlist = 100;
+ IndexFlatL2 quantizer(d);
+ IndexIVFFlat index(&quantizer, d, nlist);
+ faiss_rocksdb::RocksDBInvertedLists ril(
+ argv[1], nlist, index.code_size);
+ index.replace_invlists(&ril, false);
+
+ idx_t nb = 10000;
+ std::vector<float> xb(d * nb);
+ float_rand(xb.data(), d * nb, 12345);
+ std::vector<idx_t> xids(nb);
+ std::iota(xids.begin(), xids.end(), 0);
+
+ index.train(nb, xb.data());
+ index.add_with_ids(nb, xb.data(), xids.data());
+
+ idx_t nq = 20; // nb;
+ index.nprobe = 2;
+
+ std::cout << "search" << std::endl;
+ idx_t k = 5;
+ std::vector<float> distances(nq * k);
+ std::vector<idx_t> labels(nq * k, -1);
+ index.search(
+ nq, xb.data(), k, distances.data(), labels.data(), nullptr);
+
+ for (idx_t iq = 0; iq < nq; iq++) {
+ std::cout << iq << ": ";
+ for (auto j = 0; j < k; j++) {
+ std::cout << labels[iq * k + j] << " " << distances[iq * k + j]
+ << " | ";
+ }
+ std::cout << std::endl;
+ }
+
+ std::cout << std::endl << "range search" << std::endl;
+ float range = 15.0f;
+ RangeSearchResult result(nq);
+ index.range_search(nq, xb.data(), range, &result);
+
+ for (idx_t iq = 0; iq < nq; iq++) {
+ std::cout << iq << ": ";
+ for (auto j = result.lims[iq]; j < result.lims[iq + 1]; j++) {
+ std::cout << result.labels[j] << " " << result.distances[j]
+ << " | ";
+ }
+ std::cout << std::endl;
+ }
+
+ } catch (FaissException& e) {
+ std::cerr << e.what() << '\n';
+ } catch (std::exception& e) {
+ std::cerr << e.what() << '\n';
+ } catch (...) {
+ std::cerr << "Unrecognized exception!\n";
+ }
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/.flake8 b/packages/leann-backend-hnsw/third_party/faiss/faiss/.flake8
new file mode 100644
index 0000000..a891d3e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/.flake8
@@ -0,0 +1,3 @@
+[flake8]
+# Ignore flakes about ambiguous variable name `I`.
+ignore = E741
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/AutoTune.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/AutoTune.cpp
new file mode 100644
index 0000000..3f73f09
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/AutoTune.cpp
@@ -0,0 +1,750 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/*
+ * implementation of Hyper-parameter auto-tuning
+ */
+
+#include <faiss/AutoTune.h>
+
+#include <cinttypes>
+#include <cmath>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexIVFPQR.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/IndexShardsIVF.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/VectorTransform.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryIVF.h>
+
+namespace faiss {
+
+AutoTuneCriterion::AutoTuneCriterion(idx_t nq, idx_t nnn)
+ : nq(nq), nnn(nnn), gt_nnn(0) {}
+
+void AutoTuneCriterion::set_groundtruth(
+ int gt_nnn,
+ const float* gt_D_in,
+ const idx_t* gt_I_in) {
+ this->gt_nnn = gt_nnn;
+ if (gt_D_in) { // allow null for this, as it is often not used
+ gt_D.resize(nq * gt_nnn);
+ memcpy(gt_D.data(), gt_D_in, sizeof(gt_D[0]) * nq * gt_nnn);
+ }
+ gt_I.resize(nq * gt_nnn);
+ memcpy(gt_I.data(), gt_I_in, sizeof(gt_I[0]) * nq * gt_nnn);
+}
+
+OneRecallAtRCriterion::OneRecallAtRCriterion(idx_t nq, idx_t R)
+ : AutoTuneCriterion(nq, R), R(R) {}
+
+double OneRecallAtRCriterion::evaluate(const float* /*D*/, const idx_t* I)
+ const {
+ FAISS_THROW_IF_NOT_MSG(
+ (gt_I.size() == gt_nnn * nq && gt_nnn >= 1 && nnn >= R),
+ "ground truth not initialized");
+ idx_t n_ok = 0;
+ for (idx_t q = 0; q < nq; q++) {
+ idx_t gt_nn = gt_I[q * gt_nnn];
+ const idx_t* I_line = I + q * nnn;
+ for (int i = 0; i < R; i++) {
+ if (I_line[i] == gt_nn) {
+ n_ok++;
+ break;
+ }
+ }
+ }
+ return n_ok / double(nq);
+}
+
+IntersectionCriterion::IntersectionCriterion(idx_t nq, idx_t R)
+ : AutoTuneCriterion(nq, R), R(R) {}
+
+double IntersectionCriterion::evaluate(const float* /*D*/, const idx_t* I)
+ const {
+ FAISS_THROW_IF_NOT_MSG(
+ (gt_I.size() == gt_nnn * nq && gt_nnn >= R && nnn >= R),
+ "ground truth not initialized");
+ int64_t n_ok = 0;
+#pragma omp parallel for reduction(+ : n_ok)
+ for (idx_t q = 0; q < nq; q++) {
+ n_ok += ranklist_intersection_size(
+ R, &gt_I[q * gt_nnn], R, I + q * nnn);
+ }
+ return n_ok / double(nq * R);
+}
+
+/***************************************************************
+ * OperatingPoints
+ ***************************************************************/
+
+OperatingPoints::OperatingPoints() {
+ clear();
+}
+
+void OperatingPoints::clear() {
+ all_pts.clear();
+ optimal_pts.clear();
+ /// default point: doing nothing gives 0 performance and takes 0 time
+ OperatingPoint op = {0, 0, "", -1};
+ optimal_pts.push_back(op);
+}
+
+/// add a performance measure
+bool OperatingPoints::add(
+ double perf,
+ double t,
+ const std::string& key,
+ size_t cno) {
+ OperatingPoint op = {perf, t, key, int64_t(cno)};
+ all_pts.push_back(op);
+ if (perf == 0) {
+ return false; // no method for 0 accuracy is faster than doing nothing
+ }
+ std::vector<OperatingPoint>& a = optimal_pts;
+ if (perf > a.back().perf) {
+ // keep unconditionally
+ a.push_back(op);
+ } else if (perf == a.back().perf) {
+ if (t < a.back().t) {
+ a.back() = op;
+ } else {
+ return false;
+ }
+ } else {
+ int i;
+ // stricto sensu this should be a bissection
+ for (i = 0; i < a.size(); i++) {
+ if (a[i].perf >= perf)
+ break;
+ }
+ assert(i < a.size());
+ if (t < a[i].t) {
+ if (a[i].perf == perf) {
+ a[i] = op;
+ } else {
+ a.insert(a.begin() + i, op);
+ }
+ } else {
+ return false;
+ }
+ }
+ // remove non-optimal points from array
+ for (int i = a.size() - 1; i > 0; --i) {
+ if (a[i].t < a[i - 1].t) {
+ a.erase(a.begin() + (i - 1));
+ }
+ }
+ return true;
+}
+
+int OperatingPoints::merge_with(
+ const OperatingPoints& other,
+ const std::string& prefix) {
+ int n_add = 0;
+ for (int i = 0; i < other.all_pts.size(); i++) {
+ const OperatingPoint& op = other.all_pts[i];
+ if (add(op.perf, op.t, prefix + op.key, op.cno))
+ n_add++;
+ }
+ return n_add;
+}
+
+/// get time required to obtain a given performance measure
+double OperatingPoints::t_for_perf(double perf) const {
+ const std::vector<OperatingPoint>& a = optimal_pts;
+ if (perf > a.back().perf)
+ return 1e50;
+ int i0 = -1, i1 = a.size() - 1;
+ while (i0 + 1 < i1) {
+ int imed = (i0 + i1 + 1) / 2;
+ if (a[imed].perf < perf)
+ i0 = imed;
+ else
+ i1 = imed;
+ }
+ return a[i1].t;
+}
+
+void OperatingPoints::all_to_gnuplot(const char* fname) const {
+ FILE* f = fopen(fname, "w");
+ if (!f) {
+ fprintf(stderr, "cannot open %s", fname);
+ perror("");
+ abort();
+ }
+ for (int i = 0; i < all_pts.size(); i++) {
+ const OperatingPoint& op = all_pts[i];
+ fprintf(f, "%g %g %s\n", op.perf, op.t, op.key.c_str());
+ }
+ fclose(f);
+}
+
+void OperatingPoints::optimal_to_gnuplot(const char* fname) const {
+ FILE* f = fopen(fname, "w");
+ if (!f) {
+ fprintf(stderr, "cannot open %s", fname);
+ perror("");
+ abort();
+ }
+ double prev_perf = 0.0;
+ for (int i = 0; i < optimal_pts.size(); i++) {
+ const OperatingPoint& op = optimal_pts[i];
+ fprintf(f, "%g %g\n", prev_perf, op.t);
+ fprintf(f, "%g %g %s\n", op.perf, op.t, op.key.c_str());
+ prev_perf = op.perf;
+ }
+ fclose(f);
+}
+
+void OperatingPoints::display(bool only_optimal) const {
+ const std::vector<OperatingPoint>& pts =
+ only_optimal ? optimal_pts : all_pts;
+ printf("Tested %zd operating points, %zd ones are Pareto-optimal:\n",
+ all_pts.size(),
+ optimal_pts.size());
+
+ for (int i = 0; i < pts.size(); i++) {
+ const OperatingPoint& op = pts[i];
+ const char* star = "";
+ if (!only_optimal) {
+ for (int j = 0; j < optimal_pts.size(); j++) {
+ if (op.cno == optimal_pts[j].cno) {
+ star = "*";
+ break;
+ }
+ }
+ }
+ printf("cno=%" PRId64 " key=%s perf=%.4f t=%.3f %s\n",
+ op.cno,
+ op.key.c_str(),
+ op.perf,
+ op.t,
+ star);
+ }
+}
+
+/***************************************************************
+ * ParameterSpace
+ ***************************************************************/
+
+ParameterSpace::ParameterSpace()
+ : verbose(1),
+ n_experiments(500),
+ batchsize(1 << 30),
+ thread_over_batches(false),
+ min_test_duration(0) {}
+
+/* not keeping this constructor as inheritors will call the parent
+ initialize()
+ */
+
+#if 0
+ParameterSpace::ParameterSpace (Index *index):
+ verbose (1), n_experiments (500),
+ batchsize (1<<30), thread_over_batches (false)
+
+{
+ initialize(index);
+}
+#endif
+
+size_t ParameterSpace::n_combinations() const {
+ size_t n = 1;
+ for (int i = 0; i < parameter_ranges.size(); i++)
+ n *= parameter_ranges[i].values.size();
+ return n;
+}
+
+/// get string representation of the combination
+std::string ParameterSpace::combination_name(size_t cno) const {
+ char buf[1000], *wp = buf;
+ *wp = 0;
+ for (int i = 0; i < parameter_ranges.size(); i++) {
+ FAISS_THROW_IF_NOT_MSG(
+ buf + 1000 - wp >= 0, "Overflow detected in snprintf");
+ const ParameterRange& pr = parameter_ranges[i];
+ size_t j = cno % pr.values.size();
+ cno /= pr.values.size();
+ wp += snprintf(
+ wp,
+ buf + 1000 - wp,
+ "%s%s=%g",
+ i == 0 ? "" : ",",
+ pr.name.c_str(),
+ pr.values[j]);
+ }
+ return std::string(buf);
+}
+
+bool ParameterSpace::combination_ge(size_t c1, size_t c2) const {
+ for (int i = 0; i < parameter_ranges.size(); i++) {
+ int nval = parameter_ranges[i].values.size();
+ size_t j1 = c1 % nval;
+ size_t j2 = c2 % nval;
+ if (!(j1 >= j2))
+ return false;
+ c1 /= nval;
+ c2 /= nval;
+ }
+ return true;
+}
+
+static void init_pq_ParameterRange(
+ const ProductQuantizer& pq,
+ ParameterRange& pr) {
+ if (pq.code_size % 4 == 0) {
+ // Polysemous not supported for code sizes that are not a
+ // multiple of 4
+ for (int i = 2; i <= pq.code_size * 8 / 2; i += 2)
+ pr.values.push_back(i);
+ }
+ pr.values.push_back(pq.code_size * 8);
+}
+
+ParameterRange& ParameterSpace::add_range(const std::string& name) {
+ for (auto& pr : parameter_ranges) {
+ if (pr.name == name) {
+ return pr;
+ }
+ }
+ parameter_ranges.emplace_back();
+ parameter_ranges.back().name = name;
+ return parameter_ranges.back();
+}
+
+// Do not use this macro if ix will be unused
+#define DC(classname) \
+ const classname* ix = dynamic_cast<const classname*>(index)
+
+/// initialize with reasonable parameters for this type of index
+void ParameterSpace::initialize(const Index* index) {
+ if (DC(IndexPreTransform)) {
+ index = ix->index;
+ }
+ if (DC(IndexRefine)) {
+ ParameterRange& pr = add_range("k_factor_rf");
+ for (int i = 0; i <= 6; i++) {
+ pr.values.push_back(1 << i);
+ }
+ index = ix->base_index;
+ }
+ if (DC(IndexPreTransform)) {
+ index = ix->index;
+ }
+
+ if (DC(IndexIVFInterface)) {
+ {
+ ParameterRange& pr = add_range("nprobe");
+ for (int i = 0; i < 13; i++) {
+ size_t nprobe = 1 << i;
+ if (nprobe >= ix->nlist)
+ break;
+ pr.values.push_back(nprobe);
+ }
+ }
+ ParameterSpace ivf_pspace;
+ ivf_pspace.initialize(ix->quantizer);
+
+ for (const ParameterRange& p : ivf_pspace.parameter_ranges) {
+ ParameterRange& pr = add_range("quantizer_" + p.name);
+ pr.values = p.values;
+ }
+ }
+ if (DC(IndexPQ)) {
+ ParameterRange& pr = add_range("ht");
+ init_pq_ParameterRange(ix->pq, pr);
+ }
+ if (DC(IndexIVFPQ)) {
+ ParameterRange& pr = add_range("ht");
+ init_pq_ParameterRange(ix->pq, pr);
+ }
+
+ if (DC(IndexIVF)) {
+ const MultiIndexQuantizer* miq =
+ dynamic_cast<const MultiIndexQuantizer*>(ix->quantizer);
+ if (miq) {
+ ParameterRange& pr_max_codes = add_range("max_codes");
+ for (int i = 8; i < 20; i++) {
+ pr_max_codes.values.push_back(1 << i);
+ }
+ pr_max_codes.values.push_back(
+ std::numeric_limits<double>::infinity());
+ }
+ }
+ if (dynamic_cast<const IndexIVFPQR*>(index)) {
+ ParameterRange& pr = add_range("k_factor");
+ for (int i = 0; i <= 6; i++) {
+ pr.values.push_back(1 << i);
+ }
+ }
+ if (dynamic_cast<const IndexHNSW*>(index)) {
+ ParameterRange& pr = add_range("efSearch");
+ for (int i = 2; i <= 9; i++) {
+ pr.values.push_back(1 << i);
+ }
+ }
+}
+
+#undef DC
+
+/// set a combination of parameters on an index
+void ParameterSpace::set_index_parameters(Index* index, size_t cno) const {
+ for (int i = 0; i < parameter_ranges.size(); i++) {
+ const ParameterRange& pr = parameter_ranges[i];
+ size_t j = cno % pr.values.size();
+ cno /= pr.values.size();
+ double val = pr.values[j];
+ set_index_parameter(index, pr.name, val);
+ }
+}
+
+/// set a combination of parameters on an index
+void ParameterSpace::set_index_parameters(
+ Index* index,
+ const char* description_in) const {
+ std::string description(description_in);
+ char* ptr;
+
+ for (char* tok = strtok_r(&description[0], " ,", &ptr); tok;
+ tok = strtok_r(nullptr, " ,", &ptr)) {
+ char name[100];
+ double val;
+ int ret = sscanf(tok, "%99[^=]=%lf", name, &val);
+ FAISS_THROW_IF_NOT_FMT(
+ ret == 2, "could not interpret parameters %s", tok);
+ set_index_parameter(index, name, val);
+ }
+}
+
+// non-const version
+// Do not use this macro if ix will be unused
+#define DC(classname) classname* ix = dynamic_cast<classname*>(index)
+
+void ParameterSpace::set_index_parameter(
+ Index* index,
+ const std::string& name,
+ double val) const {
+ if (verbose > 1) {
+ printf(" set_index_parameter %s=%g\n", name.c_str(), val);
+ }
+
+ if (name == "verbose") {
+ index->verbose = int(val);
+ // and fall through to also enable it on sub-indexes
+ }
+ if (DC(IndexIDMap)) {
+ set_index_parameter(ix->index, name, val);
+ return;
+ }
+ if (DC(IndexPreTransform)) {
+ set_index_parameter(ix->index, name, val);
+ return;
+ }
+ if (DC(IndexShardsIVF)) {
+ // special handling because the nprobe is set at the sub-class level
+ // but other params are set on the class itself
+ if (name.find("quantizer_") == 0 && name != "nprobe" &&
+ name != "quantizer_nprobe") {
+ std::string sub_name = name.substr(strlen("quantizer_"));
+ set_index_parameter(ix->quantizer, sub_name, val);
+ return;
+ }
+ }
+ if (DC(ThreadedIndex<Index>)) {
+ // call on all sub-indexes
+ auto fn = [this, name, val](int /* no */, Index* subIndex) {
+ set_index_parameter(subIndex, name, val);
+ };
+ ix->runOnIndex(fn);
+ return;
+ }
+ if (DC(IndexRefine)) {
+ if (name == "k_factor_rf") {
+ ix->k_factor = int(val);
+ return;
+ }
+ // otherwise it is for the sub-index
+ set_index_parameter(ix->base_index, name, val);
+ return;
+ }
+
+ if (name == "verbose") {
+ index->verbose = int(val);
+ return; // last verbose that we could find
+ }
+
+ if (name == "nprobe") {
+ if (DC(IndexIVF)) {
+ ix->nprobe = int(val);
+ return;
+ }
+ }
+
+ if (name == "ht") {
+ if (DC(IndexPQ)) {
+ if (val >= ix->pq.code_size * 8) {
+ ix->search_type = IndexPQ::ST_PQ;
+ } else {
+ ix->search_type = IndexPQ::ST_polysemous;
+ ix->polysemous_ht = int(val);
+ }
+ return;
+ } else if (DC(IndexIVFPQ)) {
+ if (val >= ix->pq.code_size * 8) {
+ ix->polysemous_ht = 0;
+ } else {
+ ix->polysemous_ht = int(val);
+ }
+ return;
+ }
+ }
+
+ if (name == "k_factor") {
+ if (DC(IndexIVFPQR)) {
+ ix->k_factor = val;
+ return;
+ }
+ }
+ if (name == "max_codes") {
+ if (DC(IndexIVF)) {
+ ix->max_codes = std::isfinite(val) ? size_t(val) : 0;
+ return;
+ }
+ }
+
+ if (name == "efConstruction") {
+ if (DC(IndexHNSW)) {
+ ix->hnsw.efConstruction = int(val);
+ return;
+ }
+ if (DC(IndexIVF)) {
+ if (IndexHNSW* cq = dynamic_cast<IndexHNSW*>(ix->quantizer)) {
+ cq->hnsw.efConstruction = int(val);
+ return;
+ }
+ }
+ }
+
+ if (name == "efSearch") {
+ if (DC(IndexHNSW)) {
+ ix->hnsw.efSearch = int(val);
+ return;
+ }
+ if (DC(IndexIVF)) {
+ if (IndexHNSW* cq = dynamic_cast<IndexHNSW*>(ix->quantizer)) {
+ cq->hnsw.efSearch = int(val);
+ return;
+ }
+ }
+ }
+
+ if (name.find("quantizer_") == 0) {
+ if (DC(IndexIVF)) {
+ std::string sub_name = name.substr(strlen("quantizer_"));
+ set_index_parameter(ix->quantizer, sub_name, val);
+ return;
+ }
+ }
+
+ FAISS_THROW_FMT(
+ "ParameterSpace::set_index_parameter:"
+ "could not set parameter %s",
+ name.c_str());
+}
+
+#undef DC
+
+void ParameterSpace::display() const {
+ printf("ParameterSpace, %zd parameters, %zd combinations:\n",
+ parameter_ranges.size(),
+ n_combinations());
+ for (int i = 0; i < parameter_ranges.size(); i++) {
+ const ParameterRange& pr = parameter_ranges[i];
+ printf(" %s: ", pr.name.c_str());
+ char sep = '[';
+ for (int j = 0; j < pr.values.size(); j++) {
+ printf("%c %g", sep, pr.values[j]);
+ sep = ',';
+ }
+ printf("]\n");
+ }
+}
+
+void ParameterSpace::update_bounds(
+ size_t cno,
+ const OperatingPoint& op,
+ double* upper_bound_perf,
+ double* lower_bound_t) const {
+ if (combination_ge(cno, op.cno)) {
+ if (op.t > *lower_bound_t)
+ *lower_bound_t = op.t;
+ }
+ if (combination_ge(op.cno, cno)) {
+ if (op.perf < *upper_bound_perf)
+ *upper_bound_perf = op.perf;
+ }
+}
+
+void ParameterSpace::explore(
+ Index* index,
+ size_t nq,
+ const float* xq,
+ const AutoTuneCriterion& crit,
+ OperatingPoints* ops) const {
+ FAISS_THROW_IF_NOT_MSG(
+ nq == crit.nq, "criterion does not have the same nb of queries");
+
+ size_t n_comb = n_combinations();
+
+ if (n_experiments == 0) {
+ for (size_t cno = 0; cno < n_comb; cno++) {
+ set_index_parameters(index, cno);
+ std::vector<idx_t> I(nq * crit.nnn);
+ std::vector<float> D(nq * crit.nnn);
+
+ double t0 = getmillisecs();
+ index->search(nq, xq, crit.nnn, D.data(), I.data());
+ double t_search = (getmillisecs() - t0) / 1e3;
+
+ double perf = crit.evaluate(D.data(), I.data());
+
+ bool keep = ops->add(perf, t_search, combination_name(cno), cno);
+
+ if (verbose)
+ printf(" %zd/%zd: %s perf=%.3f t=%.3f s %s\n",
+ cno,
+ n_comb,
+ combination_name(cno).c_str(),
+ perf,
+ t_search,
+ keep ? "*" : "");
+ }
+ return;
+ }
+
+ int n_exp = n_experiments;
+
+ if (n_exp > n_comb)
+ n_exp = n_comb;
+ FAISS_THROW_IF_NOT(n_comb == 1 || n_exp > 2);
+ std::vector<int> perm(n_comb);
+ // make sure the slowest and fastest experiment are run
+ perm[0] = 0;
+ if (n_comb > 1) {
+ perm[1] = n_comb - 1;
+ rand_perm(&perm[2], n_comb - 2, 1234);
+ for (int i = 2; i < perm.size(); i++)
+ perm[i]++;
+ }
+
+ for (size_t xp = 0; xp < n_exp; xp++) {
+ size_t cno = perm[xp];
+
+ if (verbose)
+ printf(" %zd/%d: cno=%zd %s ",
+ xp,
+ n_exp,
+ cno,
+ combination_name(cno).c_str());
+
+ {
+ double lower_bound_t = 0.0;
+ double upper_bound_perf = 1.0;
+ for (int i = 0; i < ops->all_pts.size(); i++) {
+ update_bounds(
+ cno,
+ ops->all_pts[i],
+ &upper_bound_perf,
+ &lower_bound_t);
+ }
+ double best_t = ops->t_for_perf(upper_bound_perf);
+ if (verbose)
+ printf("bounds [perf<=%.3f t>=%.3f] %s",
+ upper_bound_perf,
+ lower_bound_t,
+ best_t <= lower_bound_t ? "skip\n" : "");
+ if (best_t <= lower_bound_t)
+ continue;
+ }
+
+ set_index_parameters(index, cno);
+ std::vector<idx_t> I(nq * crit.nnn);
+ std::vector<float> D(nq * crit.nnn);
+
+ double t0 = getmillisecs();
+
+ int nrun = 0;
+ double t_search;
+
+ do {
+ if (thread_over_batches) {
+#pragma omp parallel for
+ for (idx_t q0 = 0; q0 < nq; q0 += batchsize) {
+ size_t q1 = q0 + batchsize;
+ if (q1 > nq)
+ q1 = nq;
+ index->search(
+ q1 - q0,
+ xq + q0 * index->d,
+ crit.nnn,
+ D.data() + q0 * crit.nnn,
+ I.data() + q0 * crit.nnn);
+ }
+ } else {
+ for (size_t q0 = 0; q0 < nq; q0 += batchsize) {
+ size_t q1 = q0 + batchsize;
+ if (q1 > nq)
+ q1 = nq;
+ index->search(
+ q1 - q0,
+ xq + q0 * index->d,
+ crit.nnn,
+ D.data() + q0 * crit.nnn,
+ I.data() + q0 * crit.nnn);
+ }
+ }
+ nrun++;
+ t_search = (getmillisecs() - t0) / 1e3;
+
+ } while (t_search < min_test_duration);
+
+ t_search /= nrun;
+
+ double perf = crit.evaluate(D.data(), I.data());
+
+ bool keep = ops->add(perf, t_search, combination_name(cno), cno);
+
+ if (verbose)
+ printf(" perf %.3f t %.3f (%d %s) %s\n",
+ perf,
+ t_search,
+ nrun,
+ nrun >= 2 ? "runs" : "run",
+ keep ? "*" : "");
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/AutoTune.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/AutoTune.h
new file mode 100644
index 0000000..57d4c69
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/AutoTune.h
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_AUTO_TUNE_H
+#define FAISS_AUTO_TUNE_H
+
+#include <stdint.h>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+
+namespace faiss {
+
+/**
+ * Evaluation criterion. Returns a performance measure in [0,1],
+ * higher is better.
+ */
+struct AutoTuneCriterion {
+ idx_t nq; ///< nb of queries this criterion is evaluated on
+ idx_t nnn; ///< nb of NNs that the query should request
+ idx_t gt_nnn; ///< nb of GT NNs required to evaluate criterion
+
+ std::vector<float> gt_D; ///< Ground-truth distances (size nq * gt_nnn)
+ std::vector<idx_t> gt_I; ///< Ground-truth indexes (size nq * gt_nnn)
+
+ AutoTuneCriterion(idx_t nq, idx_t nnn);
+
+ /** Intitializes the gt_D and gt_I vectors. Must be called before evaluating
+ *
+ * @param gt_D_in size nq * gt_nnn
+ * @param gt_I_in size nq * gt_nnn
+ */
+ void set_groundtruth(
+ int gt_nnn,
+ const float* gt_D_in,
+ const idx_t* gt_I_in);
+
+ /** Evaluate the criterion.
+ *
+ * @param D size nq * nnn
+ * @param I size nq * nnn
+ * @return the criterion, between 0 and 1. Larger is better.
+ */
+ virtual double evaluate(const float* D, const idx_t* I) const = 0;
+
+ virtual ~AutoTuneCriterion() {}
+};
+
+struct OneRecallAtRCriterion : AutoTuneCriterion {
+ idx_t R;
+
+ OneRecallAtRCriterion(idx_t nq, idx_t R);
+
+ double evaluate(const float* D, const idx_t* I) const override;
+
+ ~OneRecallAtRCriterion() override {}
+};
+
+struct IntersectionCriterion : AutoTuneCriterion {
+ idx_t R;
+
+ IntersectionCriterion(idx_t nq, idx_t R);
+
+ double evaluate(const float* D, const idx_t* I) const override;
+
+ ~IntersectionCriterion() override {}
+};
+
+/**
+ * Maintains a list of experimental results. Each operating point is a
+ * (perf, t, key) triplet, where higher perf and lower t is
+ * better. The key field is an arbitrary identifier for the operating point.
+ *
+ * Includes primitives to extract the Pareto-optimal operating points in the
+ * (perf, t) space.
+ */
+
+struct OperatingPoint {
+ double perf; ///< performance measure (output of a Criterion)
+ double t; ///< corresponding execution time (ms)
+ std::string key; ///< key that identifies this op pt
+ int64_t cno; ///< integer identifier
+};
+
+struct OperatingPoints {
+ /// all operating points
+ std::vector<OperatingPoint> all_pts;
+
+ /// optimal operating points, sorted by perf
+ std::vector<OperatingPoint> optimal_pts;
+
+ // begins with a single operating point: t=0, perf=0
+ OperatingPoints();
+
+ /// add operating points from other to this, with a prefix to the keys
+ int merge_with(
+ const OperatingPoints& other,
+ const std::string& prefix = "");
+
+ void clear();
+
+ /// add a performance measure. Return whether it is an optimal point
+ bool add(double perf, double t, const std::string& key, size_t cno = 0);
+
+ /// get time required to obtain a given performance measure
+ double t_for_perf(double perf) const;
+
+ /// easy-to-read output
+ void display(bool only_optimal = true) const;
+
+ /// output to a format easy to digest by gnuplot
+ void all_to_gnuplot(const char* fname) const;
+ void optimal_to_gnuplot(const char* fname) const;
+};
+
+/// possible values of a parameter, sorted from least to most expensive/accurate
+struct ParameterRange {
+ std::string name;
+ std::vector<double> values;
+};
+
+/** Uses a-priori knowledge on the Faiss indexes to extract tunable parameters.
+ */
+struct ParameterSpace {
+ /// all tunable parameters
+ std::vector<ParameterRange> parameter_ranges;
+
+ // exploration parameters
+
+ /// verbosity during exploration
+ int verbose;
+
+ /// nb of experiments during optimization (0 = try all combinations)
+ int n_experiments;
+
+ /// maximum number of queries to submit at a time.
+ size_t batchsize;
+
+ /// use multithreading over batches (useful to benchmark
+ /// independent single-searches)
+ bool thread_over_batches;
+
+ /// run tests several times until they reach at least this
+ /// duration (to avoid jittering in MT mode)
+ double min_test_duration;
+
+ ParameterSpace();
+
+ /// nb of combinations, = product of values sizes
+ size_t n_combinations() const;
+
+ /// returns whether combinations c1 >= c2 in the tuple sense
+ bool combination_ge(size_t c1, size_t c2) const;
+
+ /// get string representation of the combination
+ std::string combination_name(size_t cno) const;
+
+ /// print a description on stdout
+ void display() const;
+
+ /// add a new parameter (or return it if it exists)
+ ParameterRange& add_range(const std::string& name);
+
+ /// initialize with reasonable parameters for the index
+ virtual void initialize(const Index* index);
+
+ /// set a combination of parameters on an index
+ void set_index_parameters(Index* index, size_t cno) const;
+
+ /// set a combination of parameters described by a string
+ void set_index_parameters(Index* index, const char* param_string) const;
+
+ /// set one of the parameters, returns whether setting was successful
+ virtual void set_index_parameter(
+ Index* index,
+ const std::string& name,
+ double val) const;
+
+ /** find an upper bound on the performance and a lower bound on t
+ * for configuration cno given another operating point op */
+ void update_bounds(
+ size_t cno,
+ const OperatingPoint& op,
+ double* upper_bound_perf,
+ double* lower_bound_t) const;
+
+ /** explore operating points
+ * @param index index to run on
+ * @param xq query vectors (size nq * index.d)
+ * @param crit selection criterion
+ * @param ops resulting operating points
+ */
+ void explore(
+ Index* index,
+ size_t nq,
+ const float* xq,
+ const AutoTuneCriterion& crit,
+ OperatingPoints* ops) const;
+
+ virtual ~ParameterSpace() {}
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/faiss/CMakeLists.txt
new file mode 100644
index 0000000..cd30aa0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/CMakeLists.txt
@@ -0,0 +1,511 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# --- Add ZMQ and MessagePack Dependencies (Add these lines at the top) ---
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(ZeroMQ REQUIRED IMPORTED_TARGET libzmq) # Find libzmq via pkg-config
+pkg_check_modules(MSGPACK msgpack REQUIRED)
+
+if(NOT MSGPACK_FOUND)
+ message(FATAL_ERROR "msgpack-c library not found. Please install it (e.g., libmsgpack-dev on Debian/Ubuntu) or configure PKG_CONFIG_PATH.")
+endif()
+# --- End Add Dependencies ---
+
+set(FAISS_SRC
+ AutoTune.cpp
+ Clustering.cpp
+ IVFlib.cpp
+ Index.cpp
+ Index2Layer.cpp
+ IndexAdditiveQuantizer.cpp
+ IndexBinary.cpp
+ IndexBinaryFlat.cpp
+ IndexBinaryFromFloat.cpp
+ IndexBinaryHNSW.cpp
+ IndexBinaryHash.cpp
+ IndexBinaryIVF.cpp
+ IndexFlat.cpp
+ IndexFlatCodes.cpp
+ IndexHNSW.cpp
+ IndexIDMap.cpp
+ IndexIVF.cpp
+ IndexIVFAdditiveQuantizer.cpp
+ IndexIVFFlat.cpp
+ IndexIVFPQ.cpp
+ IndexIVFFastScan.cpp
+ IndexIVFAdditiveQuantizerFastScan.cpp
+ IndexIVFPQFastScan.cpp
+ IndexIVFPQR.cpp
+ IndexIVFRaBitQ.cpp
+ IndexIVFSpectralHash.cpp
+ IndexLSH.cpp
+ IndexNNDescent.cpp
+ IndexLattice.cpp
+ IndexNSG.cpp
+ IndexPQ.cpp
+ IndexFastScan.cpp
+ IndexAdditiveQuantizerFastScan.cpp
+ IndexIVFIndependentQuantizer.cpp
+ IndexPQFastScan.cpp
+ IndexPreTransform.cpp
+ IndexRaBitQ.cpp
+ IndexRefine.cpp
+ IndexReplicas.cpp
+ IndexRowwiseMinMax.cpp
+ IndexScalarQuantizer.cpp
+ IndexShards.cpp
+ IndexShardsIVF.cpp
+ IndexNeuralNetCodec.cpp
+ MatrixStats.cpp
+ MetaIndexes.cpp
+ VectorTransform.cpp
+ clone_index.cpp
+ index_factory.cpp
+ impl/AuxIndexStructures.cpp
+ impl/CodePacker.cpp
+ impl/IDSelector.cpp
+ impl/FaissException.cpp
+ impl/HNSW.cpp
+ impl/HNSW_zmq.cpp
+ impl/HNSW_search.cpp
+ impl/pq.cpp
+ impl/NSG.cpp
+ impl/PolysemousTraining.cpp
+ impl/ProductQuantizer.cpp
+ impl/AdditiveQuantizer.cpp
+ impl/RaBitQuantizer.cpp
+ impl/ResidualQuantizer.cpp
+ impl/LocalSearchQuantizer.cpp
+ impl/ProductAdditiveQuantizer.cpp
+ impl/ScalarQuantizer.cpp
+ impl/index_read.cpp
+ impl/index_write.cpp
+ impl/io.cpp
+ impl/kmeans1d.cpp
+ impl/lattice_Zn.cpp
+ impl/mapped_io.cpp
+ impl/pq4_fast_scan.cpp
+ impl/pq4_fast_scan_search_1.cpp
+ impl/pq4_fast_scan_search_qbs.cpp
+ impl/residual_quantizer_encode_steps.cpp
+ impl/zerocopy_io.cpp
+ impl/NNDescent.cpp
+ invlists/BlockInvertedLists.cpp
+ invlists/DirectMap.cpp
+ invlists/InvertedLists.cpp
+ invlists/InvertedListsIOHook.cpp
+ utils/Heap.cpp
+ utils/NeuralNet.cpp
+ utils/WorkerThread.cpp
+ utils/distances.cpp
+ utils/distances_simd.cpp
+ utils/extra_distances.cpp
+ utils/hamming.cpp
+ utils/partitioning.cpp
+ utils/quantize_lut.cpp
+ utils/random.cpp
+ utils/sorting.cpp
+ utils/utils.cpp
+ utils/distances_fused/avx512.cpp
+ utils/distances_fused/distances_fused.cpp
+ utils/distances_fused/simdlib_based.cpp
+)
+
+set(FAISS_HEADERS
+ AutoTune.h
+ Clustering.h
+ IVFlib.h
+ Index.h
+ Index2Layer.h
+ IndexAdditiveQuantizer.h
+ IndexBinary.h
+ IndexBinaryFlat.h
+ IndexBinaryFromFloat.h
+ IndexBinaryHNSW.h
+ IndexBinaryHash.h
+ IndexBinaryIVF.h
+ IndexFlat.h
+ IndexFlatCodes.h
+ IndexHNSW.h
+ IndexIDMap.h
+ IndexIVF.h
+ IndexIVFAdditiveQuantizer.h
+ IndexIVFIndependentQuantizer.h
+ IndexIVFFlat.h
+ IndexIVFPQ.h
+ IndexIVFFastScan.h
+ IndexIVFAdditiveQuantizerFastScan.h
+ IndexIVFPQFastScan.h
+ IndexIVFPQR.h
+ IndexIVFRaBitQ.h
+ IndexIVFSpectralHash.h
+ IndexLSH.h
+ IndexNeuralNetCodec.h
+ IndexLattice.h
+ IndexNNDescent.h
+ IndexNSG.h
+ IndexPQ.h
+ IndexFastScan.h
+ IndexAdditiveQuantizerFastScan.h
+ IndexPQFastScan.h
+ IndexPreTransform.h
+ IndexRefine.h
+ IndexReplicas.h
+ IndexRaBitQ.h
+ IndexRowwiseMinMax.h
+ IndexScalarQuantizer.h
+ IndexShards.h
+ IndexShardsIVF.h
+ MatrixStats.h
+ MetaIndexes.h
+ MetricType.h
+ VectorTransform.h
+ clone_index.h
+ index_factory.h
+ index_io.h
+ impl/AdditiveQuantizer.h
+ impl/AuxIndexStructures.h
+ impl/CodePacker.h
+ impl/IDSelector.h
+ impl/DistanceComputer.h
+ impl/FaissAssert.h
+ impl/FaissException.h
+ impl/HNSW.h
+ impl/HNSW_zmq.h
+ impl/pq.h
+ impl/LocalSearchQuantizer.h
+ impl/ProductAdditiveQuantizer.h
+ impl/LookupTableScaler.h
+ impl/NNDescent.h
+ impl/NSG.h
+ impl/PolysemousTraining.h
+ impl/ProductQuantizer-inl.h
+ impl/ProductQuantizer.h
+ impl/Quantizer.h
+ impl/RaBitQuantizer.h
+ impl/ResidualQuantizer.h
+ impl/ResultHandler.h
+ impl/ScalarQuantizer.h
+ impl/ThreadedIndex-inl.h
+ impl/ThreadedIndex.h
+ impl/index_read_utils.h
+ impl/io.h
+ impl/io_macros.h
+ impl/kmeans1d.h
+ impl/lattice_Zn.h
+ impl/platform_macros.h
+ impl/pq4_fast_scan.h
+ impl/residual_quantizer_encode_steps.h
+ impl/simd_result_handlers.h
+ impl/code_distance/code_distance.h
+ impl/code_distance/code_distance-generic.h
+ impl/code_distance/code_distance-avx2.h
+ impl/code_distance/code_distance-avx512.h
+ impl/code_distance/code_distance-sve.h
+ invlists/BlockInvertedLists.h
+ invlists/DirectMap.h
+ invlists/InvertedLists.h
+ invlists/InvertedListsIOHook.h
+ invlists/OnDiskInvertedLists.h
+ utils/AlignedTable.h
+ utils/bf16.h
+ utils/Heap.h
+ utils/NeuralNet.h
+ utils/WorkerThread.h
+ utils/distances.h
+ utils/extra_distances-inl.h
+ utils/extra_distances.h
+ utils/fp16-fp16c.h
+ utils/fp16-inl.h
+ utils/fp16-arm.h
+ utils/fp16.h
+ utils/hamming-inl.h
+ utils/hamming.h
+ utils/ordered_key_value.h
+ utils/partitioning.h
+ utils/prefetch.h
+ utils/quantize_lut.h
+ utils/random.h
+ utils/sorting.h
+ utils/simdlib.h
+ utils/simdlib_avx2.h
+ utils/simdlib_avx512.h
+ utils/simdlib_emulated.h
+ utils/simdlib_neon.h
+ utils/simdlib_ppc64.h
+ utils/utils.h
+ utils/distances_fused/avx512.h
+ utils/distances_fused/distances_fused.h
+ utils/distances_fused/simdlib_based.h
+ utils/approx_topk/approx_topk.h
+ utils/approx_topk/avx2-inl.h
+ utils/approx_topk/generic.h
+ utils/approx_topk/mode.h
+ utils/approx_topk_hamming/approx_topk_hamming.h
+ utils/transpose/transpose-avx2-inl.h
+ utils/transpose/transpose-avx512-inl.h
+ utils/hamming_distance/common.h
+ utils/hamming_distance/generic-inl.h
+ utils/hamming_distance/hamdis-inl.h
+ utils/hamming_distance/neon-inl.h
+ utils/hamming_distance/avx2-inl.h
+ utils/hamming_distance/avx512-inl.h
+)
+
+if(NOT WIN32)
+ list(APPEND FAISS_SRC invlists/OnDiskInvertedLists.cpp)
+ list(APPEND FAISS_HEADERS invlists/OnDiskInvertedLists.h)
+endif()
+
+# Export FAISS_HEADERS variable to parent scope.
+set(FAISS_HEADERS ${FAISS_HEADERS} PARENT_SCOPE)
+
+add_library(faiss ${FAISS_SRC})
+
+add_library(faiss_avx2 ${FAISS_SRC})
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx2" AND NOT FAISS_OPT_LEVEL STREQUAL "avx512" AND NOT FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ set_target_properties(faiss_avx2 PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ target_compile_options(faiss_avx2 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mavx2 -mfma -mf16c -mpopcnt>)
+else()
+ # MSVC enables FMA with /arch:AVX2; no separate flags for F16C, POPCNT
+ # Ref. FMA (under /arch:AVX2): https://docs.microsoft.com/en-us/cpp/build/reference/arch-x64
+ # Ref. F16C (2nd paragraph): https://walbourn.github.io/directxmath-avx2/
+ # Ref. POPCNT: https://docs.microsoft.com/en-us/cpp/intrinsics/popcnt16-popcnt-popcnt64
+ target_compile_options(faiss_avx2 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX2>)
+ # we need bigobj for the swig wrapper
+ add_compile_options(/bigobj)
+endif()
+
+add_library(faiss_avx512 ${FAISS_SRC})
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx512")
+ set_target_properties(faiss_avx512 PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ # All modern CPUs support F, CD, VL, DQ, BW extensions.
+ # Ref: https://en.wikipedia.org/wiki/AVX512
+ target_compile_options(faiss_avx512 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-mavx2 -mfma -mf16c -mavx512f -mavx512cd -mavx512vl -mavx512dq -mavx512bw -mpopcnt>)
+else()
+ target_compile_options(faiss_avx512 PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
+ # we need bigobj for the swig wrapper
+ add_compile_options(/bigobj)
+endif()
+
+add_library(faiss_avx512_spr ${FAISS_SRC})
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ set_target_properties(faiss_avx512_spr PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ # Architecture mode to support AVX512 extensions available since Intel(R) Sapphire Rapids.
+ # Ref: https://networkbuilders.intel.com/solutionslibrary/intel-avx-512-fp16-instruction-set-for-intel-xeon-processor-based-products-technology-guide
+ target_compile_options(faiss_avx512_spr PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-march=sapphirerapids -mtune=sapphirerapids>)
+else()
+ target_compile_options(faiss_avx512_spr PRIVATE $<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
+ # we need bigobj for the swig wrapper
+ add_compile_options(/bigobj)
+endif()
+
+add_library(faiss_sve ${FAISS_SRC})
+if(NOT FAISS_OPT_LEVEL STREQUAL "sve")
+ set_target_properties(faiss_sve PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+if(NOT WIN32)
+ if("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )-march=native")
+ # Do nothing, expect SVE to be enabled by -march=native
+ elseif("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )(-march=armv[0-9]+(\\.[1-9]+)?-[^+ ](\\+[^+$ ]+)*)")
+ # Add +sve
+ target_compile_options(faiss_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:DEBUG>>:${CMAKE_MATCH_2}+sve>)
+ elseif(NOT "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG} " MATCHES "(^| )-march=armv")
+ # No valid -march, so specify -march=armv8-a+sve as the default
+ target_compile_options(faiss_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:DEBUG>>:-march=armv8-a+sve>)
+ endif()
+ if("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )-march=native")
+ # Do nothing, expect SVE to be enabled by -march=native
+ elseif("${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )(-march=armv[0-9]+(\\.[1-9]+)?-[^+ ](\\+[^+$ ]+)*)")
+ # Add +sve
+ target_compile_options(faiss_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:RELEASE>>:${CMAKE_MATCH_2}+sve>)
+ elseif(NOT "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE} " MATCHES "(^| )-march=armv")
+ # No valid -march, so specify -march=armv8-a+sve as the default
+ target_compile_options(faiss_sve PRIVATE $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:RELEASE>>:-march=armv8-a+sve>)
+ endif()
+endif()
+
+# Handle `#include <faiss/foo.h>`.
+target_include_directories(faiss PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}> # Keep existing
+ ${ZeroMQ_INCLUDE_DIRS} # Add ZMQ
+ ${MSGPACK_INCLUDE_DIRS} # Add msgpack-c
+)
+target_include_directories(faiss_avx2 PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
+ ${ZeroMQ_INCLUDE_DIRS}
+ ${MSGPACK_INCLUDE_DIRS}
+)
+target_include_directories(faiss_avx512 PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
+ ${ZeroMQ_INCLUDE_DIRS}
+ ${MSGPACK_INCLUDE_DIRS}
+)
+target_include_directories(faiss_avx512_spr PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
+ ${ZeroMQ_INCLUDE_DIRS}
+ ${MSGPACK_INCLUDE_DIRS}
+)
+target_include_directories(faiss_sve PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
+ ${ZeroMQ_INCLUDE_DIRS}
+ ${MSGPACK_INCLUDE_DIRS}
+)
+
+set_target_properties(faiss faiss_avx2 faiss_avx512 faiss_avx512_spr faiss_sve PROPERTIES
+ POSITION_INDEPENDENT_CODE ON
+ WINDOWS_EXPORT_ALL_SYMBOLS ON
+)
+
+if(WIN32)
+ target_compile_definitions(faiss PRIVATE FAISS_MAIN_LIB)
+ target_compile_definitions(faiss_avx2 PRIVATE FAISS_MAIN_LIB)
+ target_compile_definitions(faiss_avx512 PRIVATE FAISS_MAIN_LIB)
+ target_compile_definitions(faiss_avx512_spr PRIVATE FAISS_MAIN_LIB)
+ target_compile_definitions(faiss_sve PRIVATE FAISS_MAIN_LIB)
+endif()
+
+if(WIN32)
+ set_target_properties(faiss PROPERTIES LINK_FLAGS "-Wl,--export-all-symbols")
+endif()
+
+string(FIND "${CMAKE_CXX_FLAGS}" "FINTEGER" finteger_idx)
+if (${finteger_idx} EQUAL -1)
+ target_compile_definitions(faiss PRIVATE FINTEGER=int)
+endif()
+target_compile_definitions(faiss_avx2 PRIVATE FINTEGER=int)
+target_compile_definitions(faiss_avx512 PRIVATE FINTEGER=int)
+target_compile_definitions(faiss_avx512_spr PRIVATE FINTEGER=int)
+target_compile_definitions(faiss_sve PRIVATE FINTEGER=int)
+
+if(FAISS_USE_LTO)
+ include(CheckIPOSupported)
+ check_ipo_supported(RESULT ipo_supported OUTPUT ipo_error)
+
+ if (ipo_supported)
+ message(STATUS "LTO enabled")
+ set_property(TARGET faiss PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
+ set_property(TARGET faiss_avx2 PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
+ set_property(TARGET faiss_avx512 PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
+ set_property(TARGET faiss_avx512_spr PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
+ else()
+ message(STATUS "LTO not supported: <${ipo_error}>")
+ endif()
+endif()
+
+find_package(OpenMP REQUIRED)
+target_link_libraries(faiss PRIVATE OpenMP::OpenMP_CXX
+${ZeroMQ_LIBRARIES} # Add ZMQ
+${MSGPACK_LIBRARIES} # Add msgpack-c
+)
+target_link_libraries(faiss_avx2 PRIVATE OpenMP::OpenMP_CXX
+${ZeroMQ_LIBRARIES} # Add ZMQ
+${MSGPACK_LIBRARIES} # Add msgpack-c
+)
+target_link_libraries(faiss_avx512 PRIVATE OpenMP::OpenMP_CXX
+${ZeroMQ_LIBRARIES} # Add ZMQ
+${MSGPACK_LIBRARIES} # Add msgpack-c
+)
+target_link_libraries(faiss_avx512_spr PRIVATE OpenMP::OpenMP_CXX
+${ZeroMQ_LIBRARIES} # Add ZMQ
+${MSGPACK_LIBRARIES} # Add msgpack-c
+)
+target_link_libraries(faiss_sve PRIVATE OpenMP::OpenMP_CXX
+${ZeroMQ_LIBRARIES} # Add ZMQ
+${MSGPACK_LIBRARIES} # Add msgpack-c
+)
+
+if(FAISS_ENABLE_MKL)
+ find_package(MKL)
+endif()
+if(MKL_FOUND)
+ target_link_libraries(faiss PRIVATE ${MKL_LIBRARIES})
+ target_link_libraries(faiss_avx2 PRIVATE ${MKL_LIBRARIES})
+ target_link_libraries(faiss_avx512 PRIVATE ${MKL_LIBRARIES})
+ target_link_libraries(faiss_avx512_spr PRIVATE ${MKL_LIBRARIES})
+else()
+ find_package(BLAS REQUIRED)
+ target_link_libraries(faiss PRIVATE ${BLAS_LIBRARIES})
+ target_link_libraries(faiss_avx2 PRIVATE ${BLAS_LIBRARIES})
+ target_link_libraries(faiss_avx512 PRIVATE ${BLAS_LIBRARIES})
+ target_link_libraries(faiss_avx512_spr PRIVATE ${BLAS_LIBRARIES})
+ target_link_libraries(faiss_sve PRIVATE ${BLAS_LIBRARIES})
+
+ find_package(LAPACK REQUIRED)
+ target_link_libraries(faiss PRIVATE ${LAPACK_LIBRARIES})
+ target_link_libraries(faiss_avx2 PRIVATE ${LAPACK_LIBRARIES})
+ target_link_libraries(faiss_avx512 PRIVATE ${LAPACK_LIBRARIES})
+ target_link_libraries(faiss_avx512_spr PRIVATE ${LAPACK_LIBRARIES})
+ target_link_libraries(faiss_sve PRIVATE ${LAPACK_LIBRARIES})
+endif()
+
+install(TARGETS faiss
+ EXPORT faiss-targets
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
+)
+if(FAISS_OPT_LEVEL STREQUAL "avx2")
+ install(TARGETS faiss_avx2
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+if(FAISS_OPT_LEVEL STREQUAL "avx512")
+ install(TARGETS faiss_avx2 faiss_avx512
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+if(FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ install(TARGETS faiss_avx2 faiss_avx512_spr
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+if(FAISS_OPT_LEVEL STREQUAL "sve")
+ install(TARGETS faiss_sve
+ EXPORT faiss-targets
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+endif()
+
+foreach(header ${FAISS_HEADERS})
+ get_filename_component(dir ${header} DIRECTORY )
+ install(FILES ${header}
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/faiss/${dir}
+ )
+endforeach()
+
+include(CMakePackageConfigHelpers)
+write_basic_package_version_file(
+ "${PROJECT_BINARY_DIR}/cmake/faiss-config-version.cmake"
+ VERSION ${CMAKE_PROJECT_VERSION}
+ COMPATIBILITY AnyNewerVersion
+)
+
+configure_file(${PROJECT_SOURCE_DIR}/cmake/faiss-config.cmake.in
+ ${PROJECT_BINARY_DIR}/cmake/faiss-config.cmake
+ COPYONLY
+)
+install(FILES ${PROJECT_BINARY_DIR}/cmake/faiss-config.cmake
+ ${PROJECT_BINARY_DIR}/cmake/faiss-config-version.cmake
+ DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/faiss
+)
+
+install(EXPORT faiss-targets
+ DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/faiss
+)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/Clustering.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/Clustering.cpp
new file mode 100644
index 0000000..33c939f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/Clustering.cpp
@@ -0,0 +1,699 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/Clustering.h>
+#include <faiss/VectorTransform.h>
+#include <faiss/impl/AuxIndexStructures.h>
+
+#include <chrono>
+#include <cinttypes>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+
+#include <omp.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/kmeans1d.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+Clustering::Clustering(int d, int k) : d(d), k(k) {}
+
+Clustering::Clustering(int d, int k, const ClusteringParameters& cp)
+ : ClusteringParameters(cp), d(d), k(k) {}
+
+void Clustering::post_process_centroids() {
+ if (spherical) {
+ fvec_renorm_L2(d, k, centroids.data());
+ }
+
+ if (int_centroids) {
+ for (size_t i = 0; i < centroids.size(); i++)
+ centroids[i] = roundf(centroids[i]);
+ }
+}
+
+void Clustering::train(
+ idx_t nx,
+ const float* x_in,
+ Index& index,
+ const float* weights) {
+ train_encoded(
+ nx,
+ reinterpret_cast<const uint8_t*>(x_in),
+ nullptr,
+ index,
+ weights);
+}
+
+namespace {
+
+uint64_t get_actual_rng_seed(const int seed) {
+ return (seed >= 0)
+ ? seed
+ : static_cast<uint64_t>(std::chrono::high_resolution_clock::now()
+ .time_since_epoch()
+ .count());
+}
+
+idx_t subsample_training_set(
+ const Clustering& clus,
+ idx_t nx,
+ const uint8_t* x,
+ size_t line_size,
+ const float* weights,
+ uint8_t** x_out,
+ float** weights_out) {
+ if (clus.verbose) {
+ printf("Sampling a subset of %zd / %" PRId64 " for training\n",
+ clus.k * clus.max_points_per_centroid,
+ nx);
+ }
+
+ const uint64_t actual_seed = get_actual_rng_seed(clus.seed);
+
+ std::vector<int> perm;
+ if (clus.use_faster_subsampling) {
+ // use subsampling with splitmix64 rng
+ SplitMix64RandomGenerator rng(actual_seed);
+
+ const idx_t new_nx = clus.k * clus.max_points_per_centroid;
+ perm.resize(new_nx);
+ for (idx_t i = 0; i < new_nx; i++) {
+ perm[i] = rng.rand_int(nx);
+ }
+ } else {
+ // use subsampling with a default std rng
+ perm.resize(nx);
+ rand_perm(perm.data(), nx, actual_seed);
+ }
+
+ nx = clus.k * clus.max_points_per_centroid;
+ uint8_t* x_new = new uint8_t[nx * line_size];
+ *x_out = x_new;
+
+ // might be worth omp-ing as well
+ for (idx_t i = 0; i < nx; i++) {
+ memcpy(x_new + i * line_size, x + perm[i] * line_size, line_size);
+ }
+ if (weights) {
+ float* weights_new = new float[nx];
+ for (idx_t i = 0; i < nx; i++) {
+ weights_new[i] = weights[perm[i]];
+ }
+ *weights_out = weights_new;
+ } else {
+ *weights_out = nullptr;
+ }
+ return nx;
+}
+
+/** compute centroids as (weighted) sum of training points
+ *
+ * @param x training vectors, size n * code_size (from codec)
+ * @param codec how to decode the vectors (if NULL then cast to float*)
+ * @param weights per-training vector weight, size n (or NULL)
+ * @param assign nearest centroid for each training vector, size n
+ * @param k_frozen do not update the k_frozen first centroids
+ * @param centroids centroid vectors (output only), size k * d
+ * @param hassign histogram of assignments per centroid (size k),
+ * should be 0 on input
+ *
+ */
+
+void compute_centroids(
+ size_t d,
+ size_t k,
+ size_t n,
+ size_t k_frozen,
+ const uint8_t* x,
+ const Index* codec,
+ const int64_t* assign,
+ const float* weights,
+ float* hassign,
+ float* centroids) {
+ k -= k_frozen;
+ centroids += k_frozen * d;
+
+ memset(centroids, 0, sizeof(*centroids) * d * k);
+
+ size_t line_size = codec ? codec->sa_code_size() : d * sizeof(float);
+
+#pragma omp parallel
+ {
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ // this thread is taking care of centroids c0:c1
+ size_t c0 = (k * rank) / nt;
+ size_t c1 = (k * (rank + 1)) / nt;
+ std::vector<float> decode_buffer(d);
+
+ for (size_t i = 0; i < n; i++) {
+ int64_t ci = assign[i];
+ assert(ci >= 0 && ci < k + k_frozen);
+ ci -= k_frozen;
+ if (ci >= c0 && ci < c1) {
+ float* c = centroids + ci * d;
+ const float* xi;
+ if (!codec) {
+ xi = reinterpret_cast<const float*>(x + i * line_size);
+ } else {
+ float* xif = decode_buffer.data();
+ codec->sa_decode(1, x + i * line_size, xif);
+ xi = xif;
+ }
+ if (weights) {
+ float w = weights[i];
+ hassign[ci] += w;
+ for (size_t j = 0; j < d; j++) {
+ c[j] += xi[j] * w;
+ }
+ } else {
+ hassign[ci] += 1.0;
+ for (size_t j = 0; j < d; j++) {
+ c[j] += xi[j];
+ }
+ }
+ }
+ }
+ }
+
+#pragma omp parallel for
+ for (idx_t ci = 0; ci < k; ci++) {
+ if (hassign[ci] == 0) {
+ continue;
+ }
+ float norm = 1 / hassign[ci];
+ float* c = centroids + ci * d;
+ for (size_t j = 0; j < d; j++) {
+ c[j] *= norm;
+ }
+ }
+}
+
+// a bit above machine epsilon for float16
+#define EPS (1 / 1024.)
+
+/** Handle empty clusters by splitting larger ones.
+ *
+ * It works by slightly changing the centroids to make 2 clusters from
+ * a single one. Takes the same arguments as compute_centroids.
+ *
+ * @return nb of spliting operations (larger is worse)
+ */
+int split_clusters(
+ size_t d,
+ size_t k,
+ size_t n,
+ size_t k_frozen,
+ float* hassign,
+ float* centroids) {
+ k -= k_frozen;
+ centroids += k_frozen * d;
+
+ /* Take care of void clusters */
+ size_t nsplit = 0;
+ RandomGenerator rng(1234);
+ for (size_t ci = 0; ci < k; ci++) {
+ if (hassign[ci] == 0) { /* need to redefine a centroid */
+ size_t cj;
+ for (cj = 0; true; cj = (cj + 1) % k) {
+ /* probability to pick this cluster for split */
+ float p = (hassign[cj] - 1.0) / (float)(n - k);
+ float r = rng.rand_float();
+ if (r < p) {
+ break; /* found our cluster to be split */
+ }
+ }
+ memcpy(centroids + ci * d,
+ centroids + cj * d,
+ sizeof(*centroids) * d);
+
+ /* small symmetric pertubation */
+ for (size_t j = 0; j < d; j++) {
+ if (j % 2 == 0) {
+ centroids[ci * d + j] *= 1 + EPS;
+ centroids[cj * d + j] *= 1 - EPS;
+ } else {
+ centroids[ci * d + j] *= 1 - EPS;
+ centroids[cj * d + j] *= 1 + EPS;
+ }
+ }
+
+ /* assume even split of the cluster */
+ hassign[ci] = hassign[cj] / 2;
+ hassign[cj] -= hassign[ci];
+ nsplit++;
+ }
+ }
+
+ return nsplit;
+}
+
+} // namespace
+
+void Clustering::train_encoded(
+ idx_t nx,
+ const uint8_t* x_in,
+ const Index* codec,
+ Index& index,
+ const float* weights) {
+ FAISS_THROW_IF_NOT_FMT(
+ nx >= k,
+ "Number of training points (%" PRId64
+ ") should be at least "
+ "as large as number of clusters (%zd)",
+ nx,
+ k);
+
+ FAISS_THROW_IF_NOT_FMT(
+ (!codec || codec->d == d),
+ "Codec dimension %d not the same as data dimension %d",
+ int(codec->d),
+ int(d));
+
+ FAISS_THROW_IF_NOT_FMT(
+ index.d == d,
+ "Index dimension %d not the same as data dimension %d",
+ int(index.d),
+ int(d));
+
+ double t0 = getmillisecs();
+
+ if (!codec && check_input_data_for_NaNs) {
+ // Check for NaNs in input data. Normally it is the user's
+ // responsibility, but it may spare us some hard-to-debug
+ // reports.
+ const float* x = reinterpret_cast<const float*>(x_in);
+ for (size_t i = 0; i < nx * d; i++) {
+ FAISS_THROW_IF_NOT_MSG(
+ std::isfinite(x[i]), "input contains NaN's or Inf's");
+ }
+ }
+
+ const uint8_t* x = x_in;
+ std::unique_ptr<uint8_t[]> del1;
+ std::unique_ptr<float[]> del3;
+ size_t line_size = codec ? codec->sa_code_size() : sizeof(float) * d;
+
+ if (nx > k * max_points_per_centroid) {
+ uint8_t* x_new;
+ float* weights_new;
+ nx = subsample_training_set(
+ *this, nx, x, line_size, weights, &x_new, &weights_new);
+ del1.reset(x_new);
+ x = x_new;
+ del3.reset(weights_new);
+ weights = weights_new;
+ } else if (nx < k * min_points_per_centroid) {
+ fprintf(stderr,
+ "WARNING clustering %" PRId64
+ " points to %zd centroids: "
+ "please provide at least %" PRId64 " training points\n",
+ nx,
+ k,
+ idx_t(k) * min_points_per_centroid);
+ }
+
+ if (nx == k) {
+ // this is a corner case, just copy training set to clusters
+ if (verbose) {
+ printf("Number of training points (%" PRId64
+ ") same as number of "
+ "clusters, just copying\n",
+ nx);
+ }
+ centroids.resize(d * k);
+ if (!codec) {
+ memcpy(centroids.data(), x_in, sizeof(float) * d * k);
+ } else {
+ codec->sa_decode(nx, x_in, centroids.data());
+ }
+
+ // one fake iteration...
+ ClusteringIterationStats stats = {0.0, 0.0, 0.0, 1.0, 0};
+ iteration_stats.push_back(stats);
+
+ index.reset();
+ index.add(k, centroids.data());
+ return;
+ }
+
+ if (verbose) {
+ printf("Clustering %" PRId64
+ " points in %zdD to %zd clusters, "
+ "redo %d times, %d iterations\n",
+ nx,
+ d,
+ k,
+ nredo,
+ niter);
+ if (codec) {
+ printf("Input data encoded in %zd bytes per vector\n",
+ codec->sa_code_size());
+ }
+ }
+
+ std::unique_ptr<idx_t[]> assign(new idx_t[nx]);
+ std::unique_ptr<float[]> dis(new float[nx]);
+
+ // remember best iteration for redo
+ bool lower_is_better = !is_similarity_metric(index.metric_type);
+ float best_obj = lower_is_better ? HUGE_VALF : -HUGE_VALF;
+ std::vector<ClusteringIterationStats> best_iteration_stats;
+ std::vector<float> best_centroids;
+
+ // support input centroids
+
+ FAISS_THROW_IF_NOT_MSG(
+ centroids.size() % d == 0,
+ "size of provided input centroids not a multiple of dimension");
+
+ size_t n_input_centroids = centroids.size() / d;
+
+ if (verbose && n_input_centroids > 0) {
+ printf(" Using %zd centroids provided as input (%sfrozen)\n",
+ n_input_centroids,
+ frozen_centroids ? "" : "not ");
+ }
+
+ double t_search_tot = 0;
+ if (verbose) {
+ printf(" Preprocessing in %.2f s\n", (getmillisecs() - t0) / 1000.);
+ }
+ t0 = getmillisecs();
+
+ // initialize seed
+ const uint64_t actual_seed = get_actual_rng_seed(seed);
+
+ // temporary buffer to decode vectors during the optimization
+ std::vector<float> decode_buffer(codec ? d * decode_block_size : 0);
+
+ for (int redo = 0; redo < nredo; redo++) {
+ if (verbose && nredo > 1) {
+ printf("Outer iteration %d / %d\n", redo, nredo);
+ }
+
+ // initialize (remaining) centroids with random points from the dataset
+ centroids.resize(d * k);
+ std::vector<int> perm(nx);
+
+ rand_perm(perm.data(), nx, actual_seed + 1 + redo * 15486557L);
+
+ if (!codec) {
+ for (int i = n_input_centroids; i < k; i++) {
+ memcpy(&centroids[i * d], x + perm[i] * line_size, line_size);
+ }
+ } else {
+ for (int i = n_input_centroids; i < k; i++) {
+ codec->sa_decode(1, x + perm[i] * line_size, &centroids[i * d]);
+ }
+ }
+
+ post_process_centroids();
+
+ // prepare the index
+
+ if (index.ntotal != 0) {
+ index.reset();
+ }
+
+ if (!index.is_trained) {
+ index.train(k, centroids.data());
+ }
+
+ index.add(k, centroids.data());
+
+ // k-means iterations
+
+ float obj = 0;
+ for (int i = 0; i < niter; i++) {
+ double t0s = getmillisecs();
+
+ if (!codec) {
+ index.search(
+ nx,
+ reinterpret_cast<const float*>(x),
+ 1,
+ dis.get(),
+ assign.get());
+ } else {
+ // search by blocks of decode_block_size vectors
+ size_t code_size = codec->sa_code_size();
+ for (size_t i0 = 0; i0 < nx; i0 += decode_block_size) {
+ size_t i1 = i0 + decode_block_size;
+ if (i1 > nx) {
+ i1 = nx;
+ }
+ codec->sa_decode(
+ i1 - i0, x + code_size * i0, decode_buffer.data());
+ index.search(
+ i1 - i0,
+ decode_buffer.data(),
+ 1,
+ dis.get() + i0,
+ assign.get() + i0);
+ }
+ }
+
+ InterruptCallback::check();
+ t_search_tot += getmillisecs() - t0s;
+
+ // accumulate objective
+ obj = 0;
+ for (int j = 0; j < nx; j++) {
+ obj += dis[j];
+ }
+
+ // update the centroids
+ std::vector<float> hassign(k);
+
+ size_t k_frozen = frozen_centroids ? n_input_centroids : 0;
+ compute_centroids(
+ d,
+ k,
+ nx,
+ k_frozen,
+ x,
+ codec,
+ assign.get(),
+ weights,
+ hassign.data(),
+ centroids.data());
+
+ int nsplit = split_clusters(
+ d, k, nx, k_frozen, hassign.data(), centroids.data());
+
+ // collect statistics
+ ClusteringIterationStats stats = {
+ obj,
+ (getmillisecs() - t0) / 1000.0,
+ t_search_tot / 1000,
+ imbalance_factor(nx, k, assign.get()),
+ nsplit};
+ iteration_stats.push_back(stats);
+
+ if (verbose) {
+ printf(" Iteration %d (%.2f s, search %.2f s): "
+ "objective=%g imbalance=%.3f nsplit=%d \r",
+ i,
+ stats.time,
+ stats.time_search,
+ stats.obj,
+ stats.imbalance_factor,
+ nsplit);
+ fflush(stdout);
+ }
+
+ post_process_centroids();
+
+ // add centroids to index for the next iteration (or for output)
+
+ index.reset();
+ if (update_index) {
+ index.train(k, centroids.data());
+ }
+
+ index.add(k, centroids.data());
+ InterruptCallback::check();
+ }
+
+ if (verbose)
+ printf("\n");
+ if (nredo > 1) {
+ if ((lower_is_better && obj < best_obj) ||
+ (!lower_is_better && obj > best_obj)) {
+ if (verbose) {
+ printf("Objective improved: keep new clusters\n");
+ }
+ best_centroids = centroids;
+ best_iteration_stats = iteration_stats;
+ best_obj = obj;
+ }
+ index.reset();
+ }
+ }
+ if (nredo > 1) {
+ centroids = best_centroids;
+ iteration_stats = best_iteration_stats;
+ index.reset();
+ index.add(k, best_centroids.data());
+ }
+}
+
+Clustering1D::Clustering1D(int k) : Clustering(1, k) {}
+
+Clustering1D::Clustering1D(int k, const ClusteringParameters& cp)
+ : Clustering(1, k, cp) {}
+
+void Clustering1D::train_exact(idx_t n, const float* x) {
+ const float* xt = x;
+
+ std::unique_ptr<uint8_t[]> del;
+ if (n > k * max_points_per_centroid) {
+ uint8_t* x_new;
+ float* weights_new;
+ n = subsample_training_set(
+ *this,
+ n,
+ (uint8_t*)x,
+ sizeof(float) * d,
+ nullptr,
+ &x_new,
+ &weights_new);
+ del.reset(x_new);
+ xt = (float*)x_new;
+ }
+
+ centroids.resize(k);
+ double uf = kmeans1d(xt, n, k, centroids.data());
+
+ ClusteringIterationStats stats = {0.0, 0.0, 0.0, uf, 0};
+ iteration_stats.push_back(stats);
+}
+
+float kmeans_clustering(
+ size_t d,
+ size_t n,
+ size_t k,
+ const float* x,
+ float* centroids) {
+ Clustering clus(d, k);
+ clus.verbose = d * n * k > (size_t(1) << 30);
+ // display logs if > 1Gflop per iteration
+ IndexFlatL2 index(d);
+ clus.train(n, x, index);
+ memcpy(centroids, clus.centroids.data(), sizeof(*centroids) * d * k);
+ return clus.iteration_stats.back().obj;
+}
+
+/******************************************************************************
+ * ProgressiveDimClustering implementation
+ ******************************************************************************/
+
+ProgressiveDimClusteringParameters::ProgressiveDimClusteringParameters() {
+ progressive_dim_steps = 10;
+ apply_pca = true; // seems a good idea to do this by default
+ niter = 10; // reduce nb of iterations per step
+}
+
+Index* ProgressiveDimIndexFactory::operator()(int dim) {
+ return new IndexFlatL2(dim);
+}
+
+ProgressiveDimClustering::ProgressiveDimClustering(int d, int k) : d(d), k(k) {}
+
+ProgressiveDimClustering::ProgressiveDimClustering(
+ int d,
+ int k,
+ const ProgressiveDimClusteringParameters& cp)
+ : ProgressiveDimClusteringParameters(cp), d(d), k(k) {}
+
+namespace {
+
+void copy_columns(idx_t n, idx_t d1, const float* src, idx_t d2, float* dest) {
+ idx_t d = std::min(d1, d2);
+ for (idx_t i = 0; i < n; i++) {
+ memcpy(dest, src, sizeof(float) * d);
+ src += d1;
+ dest += d2;
+ }
+}
+
+} // namespace
+
+void ProgressiveDimClustering::train(
+ idx_t n,
+ const float* x,
+ ProgressiveDimIndexFactory& factory) {
+ int d_prev = 0;
+
+ PCAMatrix pca(d, d);
+
+ std::vector<float> xbuf;
+ if (apply_pca) {
+ if (verbose) {
+ printf("Training PCA transform\n");
+ }
+ pca.train(n, x);
+ if (verbose) {
+ printf("Apply PCA\n");
+ }
+ xbuf.resize(n * d);
+ pca.apply_noalloc(n, x, xbuf.data());
+ x = xbuf.data();
+ }
+
+ for (int iter = 0; iter < progressive_dim_steps; iter++) {
+ int di = int(pow(d, (1. + iter) / progressive_dim_steps));
+ if (verbose) {
+ printf("Progressive dim step %d: cluster in dimension %d\n",
+ iter,
+ di);
+ }
+ std::unique_ptr<Index> clustering_index(factory(di));
+
+ Clustering clus(di, k, *this);
+ if (d_prev > 0) {
+ // copy warm-start centroids (padded with 0s)
+ clus.centroids.resize(k * di);
+ copy_columns(
+ k, d_prev, centroids.data(), di, clus.centroids.data());
+ }
+ std::vector<float> xsub(n * di);
+ copy_columns(n, d, x, di, xsub.data());
+
+ clus.train(n, xsub.data(), *clustering_index.get());
+
+ centroids = clus.centroids;
+ iteration_stats.insert(
+ iteration_stats.end(),
+ clus.iteration_stats.begin(),
+ clus.iteration_stats.end());
+
+ d_prev = di;
+ }
+
+ if (apply_pca) {
+ if (verbose) {
+ printf("Revert PCA transform on centroids\n");
+ }
+ std::vector<float> cent_transformed(d * k);
+ pca.reverse_transform(k, centroids.data(), cent_transformed.data());
+ cent_transformed.swap(centroids);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/Clustering.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/Clustering.h
new file mode 100644
index 0000000..95594d1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/Clustering.h
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/** Implementation of k-means clustering with many variants. */
+
+#ifndef FAISS_CLUSTERING_H
+#define FAISS_CLUSTERING_H
+#include <faiss/Index.h>
+
+#include <vector>
+
+namespace faiss {
+
+/** Class for the clustering parameters. Can be passed to the
+ * constructor of the Clustering object.
+ */
+struct ClusteringParameters {
+ /// number of clustering iterations
+ int niter = 25;
+ /// redo clustering this many times and keep the clusters with the best
+ /// objective
+ int nredo = 1;
+
+ bool verbose = false;
+ /// whether to normalize centroids after each iteration (useful for inner
+ /// product clustering)
+ bool spherical = false;
+ /// round centroids coordinates to integer after each iteration?
+ bool int_centroids = false;
+ /// re-train index after each iteration?
+ bool update_index = false;
+
+ /// Use the subset of centroids provided as input and do not change them
+ /// during iterations
+ bool frozen_centroids = false;
+ /// If fewer than this number of training vectors per centroid are provided,
+ /// writes a warning. Note that fewer than 1 point per centroid raises an
+ /// exception.
+ int min_points_per_centroid = 39;
+ /// to limit size of dataset, otherwise the training set is subsampled
+ int max_points_per_centroid = 256;
+ /// seed for the random number generator.
+ /// negative values lead to seeding an internal rng with
+ /// std::high_resolution_clock.
+ int seed = 1234;
+
+ /// when the training set is encoded, batch size of the codec decoder
+ size_t decode_block_size = 32768;
+
+ /// whether to check for NaNs in an input data
+ bool check_input_data_for_NaNs = true;
+
+ /// Whether to use splitmix64-based random number generator for subsampling,
+ /// which is faster, but may pick duplicate points.
+ bool use_faster_subsampling = false;
+};
+
+struct ClusteringIterationStats {
+ float obj; ///< objective values (sum of distances reported by index)
+ double time; ///< seconds for iteration
+ double time_search; ///< seconds for just search
+ double imbalance_factor; ///< imbalance factor of iteration
+ int nsplit; ///< number of cluster splits
+};
+
+/** K-means clustering based on assignment - centroid update iterations
+ *
+ * The clustering is based on an Index object that assigns training
+ * points to the centroids. Therefore, at each iteration the centroids
+ * are added to the index.
+ *
+ * On output, the centoids table is set to the latest version
+ * of the centroids and they are also added to the index. If the
+ * centroids table it is not empty on input, it is also used for
+ * initialization.
+ *
+ */
+struct Clustering : ClusteringParameters {
+ size_t d; ///< dimension of the vectors
+ size_t k; ///< nb of centroids
+
+ /** centroids (k * d)
+ * if centroids are set on input to train, they will be used as
+ * initialization
+ */
+ std::vector<float> centroids;
+
+ /// stats at every iteration of clustering
+ std::vector<ClusteringIterationStats> iteration_stats;
+
+ Clustering(int d, int k);
+ Clustering(int d, int k, const ClusteringParameters& cp);
+
+ /** run k-means training
+ *
+ * @param x training vectors, size n * d
+ * @param index index used for assignment
+ * @param x_weights weight associated to each vector: NULL or size n
+ */
+ virtual void train(
+ idx_t n,
+ const float* x,
+ faiss::Index& index,
+ const float* x_weights = nullptr);
+
+ /** run with encoded vectors
+ *
+ * win addition to train()'s parameters takes a codec as parameter
+ * to decode the input vectors.
+ *
+ * @param codec codec used to decode the vectors (nullptr =
+ * vectors are in fact floats)
+ */
+ void train_encoded(
+ idx_t nx,
+ const uint8_t* x_in,
+ const Index* codec,
+ Index& index,
+ const float* weights = nullptr);
+
+ /// Post-process the centroids after each centroid update.
+ /// includes optional L2 normalization and nearest integer rounding
+ void post_process_centroids();
+
+ virtual ~Clustering() {}
+};
+
+/** Exact 1D clustering algorithm
+ *
+ * Since it does not use an index, it does not overload the train() function
+ */
+struct Clustering1D : Clustering {
+ explicit Clustering1D(int k);
+
+ Clustering1D(int k, const ClusteringParameters& cp);
+
+ void train_exact(idx_t n, const float* x);
+
+ virtual ~Clustering1D() {}
+};
+
+struct ProgressiveDimClusteringParameters : ClusteringParameters {
+ int progressive_dim_steps; ///< number of incremental steps
+ bool apply_pca; ///< apply PCA on input
+
+ ProgressiveDimClusteringParameters();
+};
+
+/** generates an index suitable for clustering when called */
+struct ProgressiveDimIndexFactory {
+ /// ownership transferred to caller
+ virtual Index* operator()(int dim);
+
+ virtual ~ProgressiveDimIndexFactory() {}
+};
+
+/** K-means clustering with progressive dimensions used
+ *
+ * The clustering first happens in dim 1, then with exponentially increasing
+ * dimension until d (I steps). This is typically applied after a PCA
+ * transformation (optional). Reference:
+ *
+ * "Improved Residual Vector Quantization for High-dimensional Approximate
+ * Nearest Neighbor Search"
+ *
+ * Shicong Liu, Hongtao Lu, Junru Shao, AAAI'15
+ *
+ * https://arxiv.org/abs/1509.05195
+ */
+struct ProgressiveDimClustering : ProgressiveDimClusteringParameters {
+ size_t d; ///< dimension of the vectors
+ size_t k; ///< nb of centroids
+
+ /** centroids (k * d) */
+ std::vector<float> centroids;
+
+ /// stats at every iteration of clustering
+ std::vector<ClusteringIterationStats> iteration_stats;
+
+ ProgressiveDimClustering(int d, int k);
+ ProgressiveDimClustering(
+ int d,
+ int k,
+ const ProgressiveDimClusteringParameters& cp);
+
+ void train(idx_t n, const float* x, ProgressiveDimIndexFactory& factory);
+
+ virtual ~ProgressiveDimClustering() {}
+};
+
+/** simplified interface
+ *
+ * @param d dimension of the data
+ * @param n nb of training vectors
+ * @param k nb of output centroids
+ * @param x training set (size n * d)
+ * @param centroids output centroids (size k * d)
+ * @return final quantization error
+ */
+float kmeans_clustering(
+ size_t d,
+ size_t n,
+ size_t k,
+ const float* x,
+ float* centroids);
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IVFlib.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IVFlib.cpp
new file mode 100644
index 0000000..95c8a3b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IVFlib.cpp
@@ -0,0 +1,736 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IVFlib.h>
+#include <omp.h>
+
+#include <memory>
+#include <numeric>
+
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/IndexIVFIndependentQuantizer.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/clone_index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/index_io.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+namespace ivflib {
+
+void check_compatible_for_merge(const Index* index0, const Index* index1) {
+ const faiss::IndexPreTransform* pt0 =
+ dynamic_cast<const faiss::IndexPreTransform*>(index0);
+
+ if (pt0) {
+ const faiss::IndexPreTransform* pt1 =
+ dynamic_cast<const faiss::IndexPreTransform*>(index1);
+ FAISS_THROW_IF_NOT_MSG(pt1, "both indexes should be pretransforms");
+
+ FAISS_THROW_IF_NOT(pt0->chain.size() == pt1->chain.size());
+ for (int i = 0; i < pt0->chain.size(); i++) {
+ FAISS_THROW_IF_NOT(typeid(pt0->chain[i]) == typeid(pt1->chain[i]));
+ }
+
+ index0 = pt0->index;
+ index1 = pt1->index;
+ }
+ FAISS_THROW_IF_NOT(typeid(index0) == typeid(index1));
+ FAISS_THROW_IF_NOT(
+ index0->d == index1->d &&
+ index0->metric_type == index1->metric_type);
+
+ const faiss::IndexIVF* ivf0 = dynamic_cast<const faiss::IndexIVF*>(index0);
+ if (ivf0) {
+ const faiss::IndexIVF* ivf1 =
+ dynamic_cast<const faiss::IndexIVF*>(index1);
+ FAISS_THROW_IF_NOT(ivf1);
+
+ ivf0->check_compatible_for_merge(*ivf1);
+ }
+
+ // TODO: check as thoroughfully for other index types
+}
+
+const IndexIVF* try_extract_index_ivf(const Index* index) {
+ auto* ivf = dynamic_cast<const IndexIVF*>(index);
+ if (ivf != nullptr) {
+ return ivf;
+ }
+
+ if (auto* pt = dynamic_cast<const IndexPreTransform*>(index)) {
+ return try_extract_index_ivf(pt->index);
+ }
+ if (auto* idmap = dynamic_cast<const IndexIDMap*>(index)) {
+ return try_extract_index_ivf(idmap->index);
+ }
+ if (auto* idmap = dynamic_cast<const IndexIDMap2*>(index)) {
+ return try_extract_index_ivf(idmap->index);
+ }
+ if (auto* indep =
+ dynamic_cast<const IndexIVFIndependentQuantizer*>(index)) {
+ return try_extract_index_ivf(indep->index_ivf);
+ }
+ if (auto* refine = dynamic_cast<const IndexRefine*>(index)) {
+ return try_extract_index_ivf(refine->base_index);
+ }
+
+ return nullptr;
+}
+
+IndexIVF* try_extract_index_ivf(Index* index) {
+ return const_cast<IndexIVF*>(try_extract_index_ivf((const Index*)(index)));
+}
+
+const IndexIVF* extract_index_ivf(const Index* index) {
+ const IndexIVF* ivf = try_extract_index_ivf(index);
+ FAISS_THROW_IF_NOT(ivf);
+ return ivf;
+}
+
+IndexIVF* extract_index_ivf(Index* index) {
+ return const_cast<IndexIVF*>(extract_index_ivf((const Index*)(index)));
+}
+
+void merge_into(faiss::Index* index0, faiss::Index* index1, bool shift_ids) {
+ check_compatible_for_merge(index0, index1);
+ IndexIVF* ivf0 = extract_index_ivf(index0);
+ IndexIVF* ivf1 = extract_index_ivf(index1);
+
+ ivf0->merge_from(*ivf1, shift_ids ? ivf0->ntotal : 0);
+
+ // useful for IndexPreTransform
+ index0->ntotal = ivf0->ntotal;
+ index1->ntotal = ivf1->ntotal;
+}
+
+void search_centroid(
+ faiss::Index* index,
+ const float* x,
+ int n,
+ idx_t* centroid_ids) {
+ std::unique_ptr<float[]> del;
+ if (auto index_pre = dynamic_cast<faiss::IndexPreTransform*>(index)) {
+ x = index_pre->apply_chain(n, x);
+ del.reset((float*)x);
+ index = index_pre->index;
+ }
+ faiss::IndexIVF* index_ivf = dynamic_cast<faiss::IndexIVF*>(index);
+ assert(index_ivf);
+ index_ivf->quantizer->assign(n, x, centroid_ids);
+}
+
+void search_and_return_centroids(
+ faiss::Index* index,
+ size_t n,
+ const float* xin,
+ long k,
+ float* distances,
+ idx_t* labels,
+ idx_t* query_centroid_ids,
+ idx_t* result_centroid_ids) {
+ const float* x = xin;
+ std::unique_ptr<float[]> del;
+ if (auto index_pre = dynamic_cast<faiss::IndexPreTransform*>(index)) {
+ x = index_pre->apply_chain(n, x);
+ del.reset((float*)x);
+ index = index_pre->index;
+ }
+ faiss::IndexIVF* index_ivf = dynamic_cast<faiss::IndexIVF*>(index);
+ assert(index_ivf);
+
+ size_t nprobe = index_ivf->nprobe;
+ std::vector<idx_t> cent_nos(n * nprobe);
+ std::vector<float> cent_dis(n * nprobe);
+ index_ivf->quantizer->search(
+ n, x, nprobe, cent_dis.data(), cent_nos.data());
+
+ if (query_centroid_ids) {
+ for (size_t i = 0; i < n; i++)
+ query_centroid_ids[i] = cent_nos[i * nprobe];
+ }
+
+ index_ivf->search_preassigned(
+ n, x, k, cent_nos.data(), cent_dis.data(), distances, labels, true);
+
+ for (size_t i = 0; i < n * k; i++) {
+ idx_t label = labels[i];
+ if (label < 0) {
+ if (result_centroid_ids)
+ result_centroid_ids[i] = -1;
+ } else {
+ long list_no = lo_listno(label);
+ long list_index = lo_offset(label);
+ if (result_centroid_ids)
+ result_centroid_ids[i] = list_no;
+ labels[i] = index_ivf->invlists->get_single_id(list_no, list_index);
+ }
+ }
+}
+
+SlidingIndexWindow::SlidingIndexWindow(Index* index) : index(index) {
+ n_slice = 0;
+ IndexIVF* index_ivf = const_cast<IndexIVF*>(extract_index_ivf(index));
+ ils = dynamic_cast<ArrayInvertedLists*>(index_ivf->invlists);
+ FAISS_THROW_IF_NOT_MSG(
+ ils, "only supports indexes with ArrayInvertedLists");
+ nlist = ils->nlist;
+ sizes.resize(nlist);
+}
+
+template <class T>
+static void shift_and_add(
+ std::vector<T>& dst,
+ size_t remove,
+ const std::vector<T>& src) {
+ if (remove > 0)
+ memmove(dst.data(),
+ dst.data() + remove,
+ (dst.size() - remove) * sizeof(T));
+ size_t insert_point = dst.size() - remove;
+ dst.resize(insert_point + src.size());
+ memcpy(dst.data() + insert_point, src.data(), src.size() * sizeof(T));
+}
+
+template <class T>
+static void shift_and_add(
+ MaybeOwnedVector<T>& dst,
+ size_t remove,
+ const MaybeOwnedVector<T>& src) {
+ if (remove > 0)
+ memmove(dst.data(),
+ dst.data() + remove,
+ (dst.size() - remove) * sizeof(T));
+ size_t insert_point = dst.size() - remove;
+ dst.resize(insert_point + src.size());
+ memcpy(dst.data() + insert_point, src.data(), src.size() * sizeof(T));
+}
+
+template <class T>
+static void remove_from_begin(std::vector<T>& v, size_t remove) {
+ if (remove > 0)
+ v.erase(v.begin(), v.begin() + remove);
+}
+
+template <class T>
+static void remove_from_begin(MaybeOwnedVector<T>& v, size_t remove) {
+ if (remove > 0)
+ v.erase(v.begin(), v.begin() + remove);
+}
+
+void SlidingIndexWindow::step(const Index* sub_index, bool remove_oldest) {
+ FAISS_THROW_IF_NOT_MSG(
+ !remove_oldest || n_slice > 0,
+ "cannot remove slice: there is none");
+
+ const ArrayInvertedLists* ils2 = nullptr;
+ if (sub_index) {
+ check_compatible_for_merge(index, sub_index);
+ ils2 = dynamic_cast<const ArrayInvertedLists*>(
+ extract_index_ivf(sub_index)->invlists);
+ FAISS_THROW_IF_NOT_MSG(ils2, "supports only ArrayInvertedLists");
+ }
+ IndexIVF* index_ivf = extract_index_ivf(index);
+
+ if (remove_oldest && ils2) {
+ for (int i = 0; i < nlist; i++) {
+ std::vector<size_t>& sizesi = sizes[i];
+ size_t amount_to_remove = sizesi[0];
+ index_ivf->ntotal += ils2->ids[i].size() - amount_to_remove;
+
+ shift_and_add(ils->ids[i], amount_to_remove, ils2->ids[i]);
+ shift_and_add(
+ ils->codes[i],
+ amount_to_remove * ils->code_size,
+ ils2->codes[i]);
+ for (int j = 0; j + 1 < n_slice; j++) {
+ sizesi[j] = sizesi[j + 1] - amount_to_remove;
+ }
+ sizesi[n_slice - 1] = ils->ids[i].size();
+ }
+ } else if (ils2) {
+ for (int i = 0; i < nlist; i++) {
+ index_ivf->ntotal += ils2->ids[i].size();
+ shift_and_add(ils->ids[i], 0, ils2->ids[i]);
+ shift_and_add(ils->codes[i], 0, ils2->codes[i]);
+ sizes[i].push_back(ils->ids[i].size());
+ }
+ n_slice++;
+ } else if (remove_oldest) {
+ for (int i = 0; i < nlist; i++) {
+ size_t amount_to_remove = sizes[i][0];
+ index_ivf->ntotal -= amount_to_remove;
+ remove_from_begin(ils->ids[i], amount_to_remove);
+ remove_from_begin(ils->codes[i], amount_to_remove * ils->code_size);
+ for (int j = 0; j + 1 < n_slice; j++) {
+ sizes[i][j] = sizes[i][j + 1] - amount_to_remove;
+ }
+ sizes[i].pop_back();
+ }
+ n_slice--;
+ } else {
+ FAISS_THROW_MSG("nothing to do???");
+ }
+ index->ntotal = index_ivf->ntotal;
+}
+
+// Get a subset of inverted lists [i0, i1). Works on IndexIVF's and
+// IndexIVF's embedded in a IndexPreTransform
+
+ArrayInvertedLists* get_invlist_range(const Index* index, long i0, long i1) {
+ const IndexIVF* ivf = extract_index_ivf(index);
+
+ FAISS_THROW_IF_NOT(0 <= i0 && i0 <= i1 && i1 <= ivf->nlist);
+
+ const InvertedLists* src = ivf->invlists;
+
+ ArrayInvertedLists* il = new ArrayInvertedLists(i1 - i0, src->code_size);
+
+ for (long i = i0; i < i1; i++) {
+ il->add_entries(
+ i - i0,
+ src->list_size(i),
+ InvertedLists::ScopedIds(src, i).get(),
+ InvertedLists::ScopedCodes(src, i).get());
+ }
+ return il;
+}
+
+void set_invlist_range(
+ Index* index,
+ long i0,
+ long i1,
+ ArrayInvertedLists* src) {
+ IndexIVF* ivf = extract_index_ivf(index);
+
+ FAISS_THROW_IF_NOT(0 <= i0 && i0 <= i1 && i1 <= ivf->nlist);
+
+ ArrayInvertedLists* dst = dynamic_cast<ArrayInvertedLists*>(ivf->invlists);
+ FAISS_THROW_IF_NOT_MSG(dst, "only ArrayInvertedLists supported");
+ FAISS_THROW_IF_NOT(
+ src->nlist == i1 - i0 && dst->code_size == src->code_size);
+
+ size_t ntotal = index->ntotal;
+ for (long i = i0; i < i1; i++) {
+ ntotal -= dst->list_size(i);
+ ntotal += src->list_size(i - i0);
+ std::swap(src->codes[i - i0], dst->codes[i]);
+ std::swap(src->ids[i - i0], dst->ids[i]);
+ }
+ ivf->ntotal = index->ntotal = ntotal;
+}
+
+static size_t count_ndis(
+ const IndexIVF* index_ivf,
+ size_t n_list_scan,
+ const idx_t* Iq) {
+ size_t nb_dis = 0;
+ const InvertedLists* il = index_ivf->invlists;
+ for (idx_t i = 0; i < n_list_scan; i++) {
+ if (Iq[i] >= 0) {
+ nb_dis += il->list_size(Iq[i]);
+ }
+ }
+ return nb_dis;
+}
+
+void search_with_parameters(
+ const Index* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const IVFSearchParameters* params,
+ size_t* nb_dis_ptr,
+ double* ms_per_stage) {
+ FAISS_THROW_IF_NOT(params);
+ const float* prev_x = x;
+ std::unique_ptr<const float[]> del;
+
+ double t0 = getmillisecs();
+
+ if (auto ip = dynamic_cast<const IndexPreTransform*>(index)) {
+ x = ip->apply_chain(n, x);
+ if (x != prev_x) {
+ del.reset(x);
+ }
+ index = ip->index;
+ }
+
+ double t1 = getmillisecs();
+
+ std::vector<idx_t> Iq(params->nprobe * n);
+ std::vector<float> Dq(params->nprobe * n);
+
+ const IndexIVF* index_ivf = dynamic_cast<const IndexIVF*>(index);
+ FAISS_THROW_IF_NOT(index_ivf);
+
+ SearchParameters* quantizer_params =
+ (params) ? params->quantizer_params : nullptr;
+ index_ivf->quantizer->search(
+ n, x, params->nprobe, Dq.data(), Iq.data(), quantizer_params);
+
+ if (nb_dis_ptr) {
+ *nb_dis_ptr = count_ndis(index_ivf, n * params->nprobe, Iq.data());
+ }
+
+ double t2 = getmillisecs();
+
+ index_ivf->search_preassigned(
+ n, x, k, Iq.data(), Dq.data(), distances, labels, false, params);
+ double t3 = getmillisecs();
+
+ if (ms_per_stage) {
+ ms_per_stage[0] = t1 - t0;
+ ms_per_stage[1] = t2 - t1;
+ ms_per_stage[2] = t3 - t2;
+ }
+}
+
+void range_search_with_parameters(
+ const Index* index,
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const IVFSearchParameters* params,
+ size_t* nb_dis_ptr,
+ double* ms_per_stage) {
+ FAISS_THROW_IF_NOT(params);
+ const float* prev_x = x;
+ std::unique_ptr<const float[]> del;
+
+ double t0 = getmillisecs();
+
+ if (auto ip = dynamic_cast<const IndexPreTransform*>(index)) {
+ x = ip->apply_chain(n, x);
+ if (x != prev_x) {
+ del.reset(x);
+ }
+ index = ip->index;
+ }
+
+ double t1 = getmillisecs();
+
+ std::vector<idx_t> Iq(params->nprobe * n);
+ std::vector<float> Dq(params->nprobe * n);
+
+ const IndexIVF* index_ivf = dynamic_cast<const IndexIVF*>(index);
+ FAISS_THROW_IF_NOT(index_ivf);
+
+ index_ivf->quantizer->search(n, x, params->nprobe, Dq.data(), Iq.data());
+
+ if (nb_dis_ptr) {
+ *nb_dis_ptr = count_ndis(index_ivf, n * params->nprobe, Iq.data());
+ }
+
+ double t2 = getmillisecs();
+
+ index_ivf->range_search_preassigned(
+ n, x, radius, Iq.data(), Dq.data(), result, false, params);
+
+ double t3 = getmillisecs();
+ if (ms_per_stage) {
+ ms_per_stage[0] = t1 - t0;
+ ms_per_stage[1] = t2 - t1;
+ ms_per_stage[2] = t3 - t2;
+ }
+}
+
+IndexIVFResidualQuantizer* ivf_residual_from_quantizer(
+ const ResidualQuantizer& rq,
+ int nlevel) {
+ FAISS_THROW_IF_NOT(nlevel > 0 && nlevel + 1 < rq.M);
+
+ std::vector<size_t> nbits(nlevel);
+ std::copy(rq.nbits.begin(), rq.nbits.begin() + nlevel, nbits.begin());
+ std::unique_ptr<ResidualCoarseQuantizer> rcq(
+ new ResidualCoarseQuantizer(rq.d, nbits));
+
+ // set the coarse quantizer from the 2 first quantizers
+ rcq->rq.initialize_from(rq);
+ rcq->is_trained = true;
+ rcq->ntotal = (idx_t)1 << rcq->rq.tot_bits;
+
+ // settings for exhaustive search in RCQ
+ rcq->centroid_norms.resize(rcq->ntotal);
+ rcq->aq->compute_centroid_norms(rcq->centroid_norms.data());
+ rcq->beam_factor = -1.0; // use exact search
+ size_t nlist = rcq->ntotal;
+
+ // build a IVFResidualQuantizer from that
+ std::vector<size_t> nbits_refined;
+ for (int i = nlevel; i < rq.M; i++) {
+ nbits_refined.push_back(rq.nbits[i]);
+ }
+ std::unique_ptr<IndexIVFResidualQuantizer> index(
+ new IndexIVFResidualQuantizer(
+ rcq.get(),
+ rq.d,
+ nlist,
+ nbits_refined,
+ faiss::METRIC_L2,
+ rq.search_type));
+ index->own_fields = true;
+ rcq.release();
+ index->by_residual = true;
+ index->rq.initialize_from(rq, nlevel);
+ index->is_trained = true;
+
+ return index.release();
+}
+
+void ivf_residual_add_from_flat_codes(
+ IndexIVFResidualQuantizer* index,
+ size_t nb,
+ const uint8_t* raw_codes,
+ int64_t code_size) {
+ const ResidualCoarseQuantizer* rcq =
+ dynamic_cast<const faiss::ResidualCoarseQuantizer*>(
+ index->quantizer);
+ FAISS_THROW_IF_NOT_MSG(rcq, "the coarse quantizer must be a RCQ");
+ if (code_size < 0) {
+ code_size = index->code_size;
+ }
+ InvertedLists& invlists = *index->invlists;
+ const ResidualQuantizer& rq = index->rq;
+
+ // populate inverted lists
+#pragma omp parallel if (nb > 10000)
+ {
+ std::vector<uint8_t> tmp_code(index->code_size);
+ std::vector<float> tmp(rq.d);
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+#pragma omp for
+ for (idx_t i = 0; i < nb; i++) {
+ const uint8_t* code = &raw_codes[i * code_size];
+ BitstringReader rd(code, code_size);
+ idx_t list_no = rd.read(rcq->rq.tot_bits);
+
+ if (list_no % nt ==
+ rank) { // each thread takes care of 1/nt of the invlists
+ // copy AQ indexes one by one
+ BitstringWriter wr(tmp_code.data(), tmp_code.size());
+ for (int j = 0; j < rq.M; j++) {
+ int nbit = rq.nbits[j];
+ wr.write(rd.read(nbit), nbit);
+ }
+ // we need to recompute the norm
+ // decode first, does not use the norm component, so that's
+ // ok
+ index->rq.decode(tmp_code.data(), tmp.data(), 1);
+ float norm = fvec_norm_L2sqr(tmp.data(), rq.d);
+ wr.write(rq.encode_norm(norm), rq.norm_bits);
+
+ // add code to the inverted list
+ invlists.add_entry(list_no, i, tmp_code.data());
+ }
+ }
+ }
+ index->ntotal += nb;
+}
+
+int64_t DefaultShardingFunction::operator()(int64_t i, int64_t shard_count) {
+ return i % shard_count;
+}
+
+void handle_ivf(
+ faiss::IndexIVF* index,
+ int64_t shard_count,
+ const std::string& filename_template,
+ ShardingFunction* sharding_function,
+ bool generate_ids) {
+ std::vector<faiss::IndexIVF*> sharded_indexes(shard_count);
+ auto clone = static_cast<faiss::IndexIVF*>(faiss::clone_index(index));
+ clone->quantizer->reset();
+ for (int64_t i = 0; i < shard_count; i++) {
+ sharded_indexes[i] =
+ static_cast<faiss::IndexIVF*>(faiss::clone_index(clone));
+ if (generate_ids) {
+ // Assume the quantizer does not natively support add_with_ids.
+ sharded_indexes[i]->quantizer =
+ new IndexIDMap2(sharded_indexes[i]->quantizer);
+ }
+ }
+
+ // assign centroids to each sharded Index based on sharding_function, and
+ // add them to the quantizer of each sharded index
+ std::vector<std::vector<float>> sharded_centroids(shard_count);
+ std::vector<std::vector<idx_t>> xids(shard_count);
+ for (int64_t i = 0; i < index->quantizer->ntotal; i++) {
+ int64_t shard_id = (*sharding_function)(i, shard_count);
+ // Since the quantizer does not natively support add_with_ids, we simply
+ // generate them.
+ xids[shard_id].push_back(i);
+ float* reconstructed = new float[index->quantizer->d];
+ index->quantizer->reconstruct(i, reconstructed);
+ sharded_centroids[shard_id].insert(
+ sharded_centroids[shard_id].end(),
+ &reconstructed[0],
+ &reconstructed[index->quantizer->d]);
+ delete[] reconstructed;
+ }
+ for (int64_t i = 0; i < shard_count; i++) {
+ if (generate_ids) {
+ sharded_indexes[i]->quantizer->add_with_ids(
+ sharded_centroids[i].size() / index->quantizer->d,
+ sharded_centroids[i].data(),
+ xids[i].data());
+ } else {
+ sharded_indexes[i]->quantizer->add(
+ sharded_centroids[i].size() / index->quantizer->d,
+ sharded_centroids[i].data());
+ }
+ }
+
+ for (int64_t i = 0; i < shard_count; i++) {
+ char fname[256];
+ snprintf(fname, 256, filename_template.c_str(), i);
+ faiss::write_index(sharded_indexes[i], fname);
+ }
+
+ for (int64_t i = 0; i < shard_count; i++) {
+ delete sharded_indexes[i];
+ }
+}
+
+void handle_binary_ivf(
+ faiss::IndexBinaryIVF* index,
+ int64_t shard_count,
+ const std::string& filename_template,
+ ShardingFunction* sharding_function,
+ bool generate_ids) {
+ std::vector<faiss::IndexBinaryIVF*> sharded_indexes(shard_count);
+
+ auto clone = static_cast<faiss::IndexBinaryIVF*>(
+ faiss::clone_binary_index(index));
+ clone->quantizer->reset();
+
+ for (int64_t i = 0; i < shard_count; i++) {
+ sharded_indexes[i] = static_cast<faiss::IndexBinaryIVF*>(
+ faiss::clone_binary_index(clone));
+ if (generate_ids) {
+ // Assume the quantizer does not natively support add_with_ids.
+ sharded_indexes[i]->quantizer =
+ new IndexBinaryIDMap2(sharded_indexes[i]->quantizer);
+ }
+ }
+
+ // assign centroids to each sharded Index based on sharding_function, and
+ // add them to the quantizer of each sharded index
+ int64_t reconstruction_size = index->quantizer->d / 8;
+ std::vector<std::vector<uint8_t>> sharded_centroids(shard_count);
+ std::vector<std::vector<idx_t>> xids(shard_count);
+ for (int64_t i = 0; i < index->quantizer->ntotal; i++) {
+ int64_t shard_id = (*sharding_function)(i, shard_count);
+ // Since the quantizer does not natively support add_with_ids, we simply
+ // generate them.
+ xids[shard_id].push_back(i);
+ uint8_t* reconstructed = new uint8_t[reconstruction_size];
+ index->quantizer->reconstruct(i, reconstructed);
+ sharded_centroids[shard_id].insert(
+ sharded_centroids[shard_id].end(),
+ &reconstructed[0],
+ &reconstructed[reconstruction_size]);
+ delete[] reconstructed;
+ }
+ for (int64_t i = 0; i < shard_count; i++) {
+ if (generate_ids) {
+ sharded_indexes[i]->quantizer->add_with_ids(
+ sharded_centroids[i].size() / reconstruction_size,
+ sharded_centroids[i].data(),
+ xids[i].data());
+ } else {
+ sharded_indexes[i]->quantizer->add(
+ sharded_centroids[i].size() / reconstruction_size,
+ sharded_centroids[i].data());
+ }
+ }
+
+ for (int64_t i = 0; i < shard_count; i++) {
+ char fname[256];
+ snprintf(fname, 256, filename_template.c_str(), i);
+ faiss::write_index_binary(sharded_indexes[i], fname);
+ }
+
+ for (int64_t i = 0; i < shard_count; i++) {
+ delete sharded_indexes[i];
+ }
+}
+
+template <typename IndexType>
+void sharding_helper(
+ IndexType* index,
+ int64_t shard_count,
+ const std::string& filename_template,
+ ShardingFunction* sharding_function,
+ bool generate_ids) {
+ FAISS_THROW_IF_MSG(index->quantizer->ntotal == 0, "No centroids to shard.");
+ FAISS_THROW_IF_MSG(
+ filename_template.find("%d") == std::string::npos,
+ "Invalid filename_template. Must contain format specifier for shard count.");
+
+ DefaultShardingFunction default_sharding_function;
+ if (sharding_function == nullptr) {
+ sharding_function = &default_sharding_function;
+ }
+
+ if (typeid(IndexType) == typeid(faiss::IndexIVF)) {
+ handle_ivf(
+ dynamic_cast<faiss::IndexIVF*>(index),
+ shard_count,
+ filename_template,
+ sharding_function,
+ generate_ids);
+ } else if (typeid(IndexType) == typeid(faiss::IndexBinaryIVF)) {
+ handle_binary_ivf(
+ dynamic_cast<faiss::IndexBinaryIVF*>(index),
+ shard_count,
+ filename_template,
+ sharding_function,
+ generate_ids);
+ }
+}
+
+void shard_ivf_index_centroids(
+ faiss::IndexIVF* index,
+ int64_t shard_count,
+ const std::string& filename_template,
+ ShardingFunction* sharding_function,
+ bool generate_ids) {
+ sharding_helper(
+ index,
+ shard_count,
+ filename_template,
+ sharding_function,
+ generate_ids);
+}
+
+void shard_binary_ivf_index_centroids(
+ faiss::IndexBinaryIVF* index,
+ int64_t shard_count,
+ const std::string& filename_template,
+ ShardingFunction* sharding_function,
+ bool generate_ids) {
+ sharding_helper(
+ index,
+ shard_count,
+ filename_template,
+ sharding_function,
+ generate_ids);
+}
+
+} // namespace ivflib
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IVFlib.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IVFlib.h
new file mode 100644
index 0000000..8a6dd3f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IVFlib.h
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_IVFLIB_H
+#define FAISS_IVFLIB_H
+
+/** Since IVF (inverted file) indexes are of so much use for
+ * large-scale use cases, we group a few functions related to them in
+ * this small library. Most functions work both on IndexIVFs and
+ * IndexIVFs embedded within an IndexPreTransform.
+ */
+
+#include <faiss/IndexBinaryIVF.h>
+#include <faiss/IndexIVF.h>
+#include <vector>
+
+namespace faiss {
+
+struct IndexIVFResidualQuantizer;
+struct IndexResidualQuantizer;
+struct ResidualQuantizer;
+
+namespace ivflib {
+
+/** check if two indexes have the same parameters and are trained in
+ * the same way, otherwise throw. */
+void check_compatible_for_merge(const Index* index1, const Index* index2);
+
+/** get an IndexIVF from an index. The index may be an IndexIVF or
+ * some wrapper class that encloses an IndexIVF
+ *
+ * throws an exception if this is not the case.
+ */
+const IndexIVF* extract_index_ivf(const Index* index);
+IndexIVF* extract_index_ivf(Index* index);
+
+/// same as above but returns nullptr instead of throwing on failure
+const IndexIVF* try_extract_index_ivf(const Index* index);
+IndexIVF* try_extract_index_ivf(Index* index);
+
+/** Merge index1 into index0. Works on IndexIVF's and IndexIVF's
+ * embedded in a IndexPreTransform. On output, the index1 is empty.
+ *
+ * @param shift_ids: translate the ids from index1 to index0->prev_ntotal
+ */
+void merge_into(Index* index0, Index* index1, bool shift_ids);
+
+/* Returns the cluster the embeddings belong to.
+ *
+ * @param index Index, which should be an IVF index
+ * (otherwise there are no clusters)
+ * @param embeddings object descriptors for which the centroids should be found,
+ * size num_objects * d
+ * @param centroid_ids
+ * cluster id each object belongs to, size num_objects
+ */
+void search_centroid(Index* index, const float* x, int n, idx_t* centroid_ids);
+
+/* Returns the cluster the embeddings belong to.
+ *
+ * @param index Index, which should be an IVF index
+ * (otherwise there are no clusters)
+ * @param query_centroid_ids
+ * centroid ids corresponding to the query vectors (size n)
+ * @param result_centroid_ids
+ * centroid ids corresponding to the results (size n * k)
+ * other arguments are the same as the standard search function
+ */
+void search_and_return_centroids(
+ Index* index,
+ size_t n,
+ const float* xin,
+ long k,
+ float* distances,
+ idx_t* labels,
+ idx_t* query_centroid_ids,
+ idx_t* result_centroid_ids);
+
+/** A set of IndexIVFs concatenated together in a FIFO fashion.
+ * at each "step", the oldest index slice is removed and a new index is added.
+ */
+struct SlidingIndexWindow {
+ /// common index that contains the sliding window
+ Index* index;
+
+ /// InvertedLists of index
+ ArrayInvertedLists* ils;
+
+ /// number of slices currently in index
+ int n_slice;
+
+ /// same as index->nlist
+ size_t nlist;
+
+ /// cumulative list sizes at each slice
+ std::vector<std::vector<size_t>> sizes;
+
+ /// index should be initially empty and trained
+ SlidingIndexWindow(Index* index);
+
+ /** Add one index to the current index and remove the oldest one.
+ *
+ * @param sub_index slice to swap in (can be NULL)
+ * @param remove_oldest if true, remove the oldest slices */
+ void step(const Index* sub_index, bool remove_oldest);
+};
+
+/// Get a subset of inverted lists [i0, i1)
+ArrayInvertedLists* get_invlist_range(const Index* index, long i0, long i1);
+
+/// Set a subset of inverted lists
+void set_invlist_range(Index* index, long i0, long i1, ArrayInvertedLists* src);
+
+/** search an IndexIVF, possibly embedded in an IndexPreTransform with
+ * given parameters. This is a way to set the nprobe and get
+ * statdistics in a thread-safe way.
+ *
+ * Optionally returns (if non-nullptr):
+ * - nb_dis: number of distances computed
+ * - ms_per_stage: [0]: preprocessing time
+ * [1]: coarse quantization,
+ * [2]: list scanning
+ */
+void search_with_parameters(
+ const Index* index,
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const IVFSearchParameters* params,
+ size_t* nb_dis = nullptr,
+ double* ms_per_stage = nullptr);
+
+/** same as search_with_parameters but for range search */
+void range_search_with_parameters(
+ const Index* index,
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const IVFSearchParameters* params,
+ size_t* nb_dis = nullptr,
+ double* ms_per_stage = nullptr);
+
+/** Build an IndexIVFResidualQuantizer from an ResidualQuantizer, using the
+ * nlevel first components as coarse quantizer and the rest as codes in invlists
+ */
+IndexIVFResidualQuantizer* ivf_residual_from_quantizer(
+ const ResidualQuantizer&,
+ int nlevel);
+
+/** add from codes. NB that the norm component is not used, so the code_size can
+ * be provided.
+ *
+ * @param ivfrq index to populate with the codes
+ * @param codes codes to add, size (ncode, code_size)
+ * @param code_size override the ivfrq's code_size, useful if the norm encoding
+ * is different
+ */
+void ivf_residual_add_from_flat_codes(
+ IndexIVFResidualQuantizer* ivfrq,
+ size_t ncode,
+ const uint8_t* codes,
+ int64_t code_size = -1);
+
+struct ShardingFunction {
+ virtual int64_t operator()(int64_t i, int64_t shard_count) = 0;
+ virtual ~ShardingFunction() = default;
+ ShardingFunction() {}
+ ShardingFunction(const ShardingFunction&) = default;
+ ShardingFunction(ShardingFunction&&) = default;
+ ShardingFunction& operator=(const ShardingFunction&) = default;
+ ShardingFunction& operator=(ShardingFunction&&) = default;
+};
+struct DefaultShardingFunction : ShardingFunction {
+ int64_t operator()(int64_t i, int64_t shard_count) override;
+};
+
+/**
+ * Shards an IVF index centroids by the given sharding function, and writes
+ * the index to the path given by filename_generator. The centroids must already
+ * be added to the index quantizer.
+ *
+ * @param index The IVF index containing centroids to shard.
+ * @param shard_count Number of shards.
+ * @param filename_template Template for shard filenames.
+ * @param sharding_function The function to shard by. The default is ith vector
+ * mod shard_count.
+ * @param generate_ids Generates ids using IndexIDMap2. If true, ids will
+ * match the default ids in the unsharded index.
+ * @return The number of shards written.
+ */
+void shard_ivf_index_centroids(
+ IndexIVF* index,
+ int64_t shard_count = 20,
+ const std::string& filename_template = "shard.%d.index",
+ ShardingFunction* sharding_function = nullptr,
+ bool generate_ids = false);
+
+void shard_binary_ivf_index_centroids(
+ faiss::IndexBinaryIVF* index,
+ int64_t shard_count = 20,
+ const std::string& filename_template = "shard.%d.index",
+ ShardingFunction* sharding_function = nullptr,
+ bool generate_ids = false);
+
+} // namespace ivflib
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/Index.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index.cpp
new file mode 100644
index 0000000..3530fce
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index.cpp
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/Index.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+
+#include <cstring>
+
+namespace faiss {
+
+Index::~Index() = default;
+
+void Index::train(idx_t /*n*/, const float* /*x*/) {
+ // does nothing by default
+}
+
+void Index::range_search(
+ idx_t,
+ const float*,
+ float,
+ RangeSearchResult*,
+ const SearchParameters* params) const {
+ FAISS_THROW_MSG("range search not implemented");
+}
+
+void Index::assign(idx_t n, const float* x, idx_t* labels, idx_t k) const {
+ std::vector<float> distances(n * k);
+ search(n, x, k, distances.data(), labels);
+}
+
+void Index::add_with_ids(
+ idx_t /*n*/,
+ const float* /*x*/,
+ const idx_t* /*xids*/) {
+ FAISS_THROW_MSG("add_with_ids not implemented for this type of index");
+}
+
+size_t Index::remove_ids(const IDSelector& /*sel*/) {
+ FAISS_THROW_MSG("remove_ids not implemented for this type of index");
+ return -1;
+}
+
+void Index::reconstruct(idx_t, float*) const {
+ FAISS_THROW_MSG("reconstruct not implemented for this type of index");
+}
+
+void Index::reconstruct_batch(idx_t n, const idx_t* keys, float* recons) const {
+ std::mutex exception_mutex;
+ std::string exception_string;
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ try {
+ reconstruct(keys[i], &recons[i * d]);
+ } catch (const std::exception& e) {
+ std::lock_guard<std::mutex> lock(exception_mutex);
+ exception_string = e.what();
+ }
+ }
+ if (!exception_string.empty()) {
+ FAISS_THROW_MSG(exception_string.c_str());
+ }
+}
+
+void Index::reconstruct_n(idx_t i0, idx_t ni, float* recons) const {
+#pragma omp parallel for if (ni > 1000)
+ for (idx_t i = 0; i < ni; i++) {
+ reconstruct(i0 + i, recons + i * d);
+ }
+}
+
+void Index::search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+
+ search(n, x, k, distances, labels, params);
+ for (idx_t i = 0; i < n; ++i) {
+ for (idx_t j = 0; j < k; ++j) {
+ idx_t ij = i * k + j;
+ idx_t key = labels[ij];
+ float* reconstructed = recons + ij * d;
+ if (key < 0) {
+ // Fill with NaNs
+ memset(reconstructed, -1, sizeof(*reconstructed) * d);
+ } else {
+ reconstruct(key, reconstructed);
+ }
+ }
+ }
+}
+
+void Index::compute_residual(const float* x, float* residual, idx_t key) const {
+ reconstruct(key, residual);
+ for (size_t i = 0; i < d; i++) {
+ residual[i] = x[i] - residual[i];
+ }
+}
+
+void Index::compute_residual_n(
+ idx_t n,
+ const float* xs,
+ float* residuals,
+ const idx_t* keys) const {
+#pragma omp parallel for
+ for (idx_t i = 0; i < n; ++i) {
+ compute_residual(&xs[i * d], &residuals[i * d], keys[i]);
+ }
+}
+
+size_t Index::sa_code_size() const {
+ FAISS_THROW_MSG("standalone codec not implemented for this type of index");
+}
+
+void Index::sa_encode(idx_t, const float*, uint8_t*) const {
+ FAISS_THROW_MSG("standalone codec not implemented for this type of index");
+}
+
+void Index::sa_decode(idx_t, const uint8_t*, float*) const {
+ FAISS_THROW_MSG("standalone codec not implemented for this type of index");
+}
+
+void Index::add_sa_codes(idx_t, const uint8_t*, const idx_t*) {
+ FAISS_THROW_MSG("add_sa_codes not implemented for this type of index");
+}
+
+namespace {
+
+// storage that explicitly reconstructs vectors before computing distances
+struct GenericDistanceComputer : DistanceComputer {
+ size_t d;
+ const Index& storage;
+ std::vector<float> buf;
+ const float* q;
+
+ explicit GenericDistanceComputer(const Index& storage) : storage(storage) {
+ d = storage.d;
+ buf.resize(d * 2);
+ }
+
+ float operator()(idx_t i) override {
+ storage.reconstruct(i, buf.data());
+ return fvec_L2sqr(q, buf.data(), d);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ storage.reconstruct(i, buf.data());
+ storage.reconstruct(j, buf.data() + d);
+ return fvec_L2sqr(buf.data() + d, buf.data(), d);
+ }
+
+ void set_query(const float* x) override {
+ q = x;
+ }
+};
+
+} // namespace
+
+DistanceComputer* Index::get_distance_computer() const {
+ if (metric_type == METRIC_L2) {
+ return new GenericDistanceComputer(*this);
+ } else {
+ FAISS_THROW_MSG("get_distance_computer() not implemented");
+ }
+}
+
+void Index::merge_from(Index& /* otherIndex */, idx_t /* add_id */) {
+ FAISS_THROW_MSG("merge_from() not implemented");
+}
+
+void Index::check_compatible_for_merge(const Index& /* otherIndex */) const {
+ FAISS_THROW_MSG("check_compatible_for_merge() not implemented");
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/Index.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index.h
new file mode 100644
index 0000000..544086f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index.h
@@ -0,0 +1,321 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_H
+#define FAISS_INDEX_H
+
+#include <faiss/MetricType.h>
+#include <cstdio>
+#include <sstream>
+#include <string>
+#include <typeinfo>
+
+#define FAISS_VERSION_MAJOR 1
+#define FAISS_VERSION_MINOR 10
+#define FAISS_VERSION_PATCH 0
+
+// Macro to combine the version components into a single string
+#ifndef FAISS_STRINGIFY
+#define FAISS_STRINGIFY(ARG) #ARG
+#endif
+#ifndef FAISS_TOSTRING
+#define FAISS_TOSTRING(ARG) FAISS_STRINGIFY(ARG)
+#endif
+#define VERSION_STRING \
+ FAISS_TOSTRING(FAISS_VERSION_MAJOR) \
+ "." FAISS_TOSTRING(FAISS_VERSION_MINOR) "." FAISS_TOSTRING( \
+ FAISS_VERSION_PATCH)
+
+/**
+ * @namespace faiss
+ *
+ * Throughout the library, vectors are provided as float * pointers.
+ * Most algorithms can be optimized when several vectors are processed
+ * (added/searched) together in a batch. In this case, they are passed
+ * in as a matrix. When n vectors of size d are provided as float * x,
+ * component j of vector i is
+ *
+ * x[ i * d + j ]
+ *
+ * where 0 <= i < n and 0 <= j < d. In other words, matrices are
+ * always compact. When specifying the size of the matrix, we call it
+ * an n*d matrix, which implies a row-major storage.
+ */
+
+namespace faiss {
+
+/// Forward declarations see impl/AuxIndexStructures.h, impl/IDSelector.h
+/// and impl/DistanceComputer.h
+struct IDSelector;
+struct RangeSearchResult;
+struct DistanceComputer;
+
+/** Parent class for the optional search paramenters.
+ *
+ * Sub-classes with additional search parameters should inherit this class.
+ * Ownership of the object fields is always to the caller.
+ */
+struct SearchParameters {
+ /// if non-null, only these IDs will be considered during search.
+ IDSelector* sel = nullptr;
+ /// make sure we can dynamic_cast this
+ virtual ~SearchParameters() {}
+};
+
+/** Abstract structure for an index, supports adding vectors and searching
+ * them.
+ *
+ * All vectors provided at add or search time are 32-bit float arrays,
+ * although the internal representation may vary.
+ */
+struct Index {
+ using component_t = float;
+ using distance_t = float;
+
+ int d; ///< vector dimension
+ idx_t ntotal; ///< total nb of indexed vectors
+ bool verbose; ///< verbosity level
+
+ /// set if the Index does not require training, or if training is
+ /// done already
+ bool is_trained;
+
+ /// type of metric this index uses for search
+ MetricType metric_type;
+ float metric_arg; ///< argument of the metric type
+
+ explicit Index(idx_t d = 0, MetricType metric = METRIC_L2)
+ : d(d),
+ ntotal(0),
+ verbose(false),
+ is_trained(true),
+ metric_type(metric),
+ metric_arg(0) {}
+
+ virtual ~Index();
+
+ /** Perform training on a representative set of vectors
+ *
+ * @param n nb of training vectors
+ * @param x training vecors, size n * d
+ */
+ virtual void train(idx_t n, const float* x);
+
+ /** Add n vectors of dimension d to the index.
+ *
+ * Vectors are implicitly assigned labels ntotal .. ntotal + n - 1
+ * This function slices the input vectors in chunks smaller than
+ * blocksize_add and calls add_core.
+ * @param n number of vectors
+ * @param x input matrix, size n * d
+ */
+ virtual void add(idx_t n, const float* x) = 0;
+
+ /** Same as add, but stores xids instead of sequential ids.
+ *
+ * The default implementation fails with an assertion, as it is
+ * not supported by all indexes.
+ *
+ * @param n number of vectors
+ * @param x input vectors, size n * d
+ * @param xids if non-null, ids to store for the vectors (size n)
+ */
+ virtual void add_with_ids(idx_t n, const float* x, const idx_t* xids);
+
+ /** query n vectors of dimension d to the index.
+ *
+ * return at most k vectors. If there are not enough results for a
+ * query, the result array is padded with -1s.
+ *
+ * @param n number of vectors
+ * @param x input vectors to search, size n * d
+ * @param k number of extracted vectors
+ * @param distances output pairwise distances, size n*k
+ * @param labels output labels of the NNs, size n*k
+ */
+ virtual void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const = 0;
+
+ /** query n vectors of dimension d to the index.
+ *
+ * return all vectors with distance < radius. Note that many
+ * indexes do not implement the range_search (only the k-NN search
+ * is mandatory).
+ *
+ * @param n number of vectors
+ * @param x input vectors to search, size n * d
+ * @param radius search radius
+ * @param result result table
+ */
+ virtual void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const;
+
+ /** return the indexes of the k vectors closest to the query x.
+ *
+ * This function is identical as search but only return labels of
+ * neighbors.
+ * @param n number of vectors
+ * @param x input vectors to search, size n * d
+ * @param labels output labels of the NNs, size n*k
+ * @param k number of nearest neighbours
+ */
+ virtual void assign(idx_t n, const float* x, idx_t* labels, idx_t k = 1)
+ const;
+
+ /// removes all elements from the database.
+ virtual void reset() = 0;
+
+ /** removes IDs from the index. Not supported by all
+ * indexes. Returns the number of elements removed.
+ */
+ virtual size_t remove_ids(const IDSelector& sel);
+
+ /** Reconstruct a stored vector (or an approximation if lossy coding)
+ *
+ * this function may not be defined for some indexes
+ * @param key id of the vector to reconstruct
+ * @param recons reconstucted vector (size d)
+ */
+ virtual void reconstruct(idx_t key, float* recons) const;
+
+ /** Reconstruct several stored vectors (or an approximation if lossy
+ * coding)
+ *
+ * this function may not be defined for some indexes
+ * @param n number of vectors to reconstruct
+ * @param keys ids of the vectors to reconstruct (size n)
+ * @param recons reconstucted vector (size n * d)
+ */
+ virtual void reconstruct_batch(idx_t n, const idx_t* keys, float* recons)
+ const;
+
+ /** Reconstruct vectors i0 to i0 + ni - 1
+ *
+ * this function may not be defined for some indexes
+ * @param i0 index of the first vector in the sequence
+ * @param ni number of vectors in the sequence
+ * @param recons reconstucted vector (size ni * d)
+ */
+ virtual void reconstruct_n(idx_t i0, idx_t ni, float* recons) const;
+
+ /** Similar to search, but also reconstructs the stored vectors (or an
+ * approximation in the case of lossy coding) for the search results.
+ *
+ * If there are not enough results for a query, the resulting arrays
+ * is padded with -1s.
+ *
+ * @param n number of vectors
+ * @param x input vectors to search, size n * d
+ * @param k number of extracted vectors
+ * @param distances output pairwise distances, size n*k
+ * @param labels output labels of the NNs, size n*k
+ * @param recons reconstructed vectors size (n, k, d)
+ **/
+ virtual void search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params = nullptr) const;
+
+ /** Computes a residual vector after indexing encoding.
+ *
+ * The residual vector is the difference between a vector and the
+ * reconstruction that can be decoded from its representation in
+ * the index. The residual can be used for multiple-stage indexing
+ * methods, like IndexIVF's methods.
+ *
+ * @param x input vector, size d
+ * @param residual output residual vector, size d
+ * @param key encoded index, as returned by search and assign
+ */
+ virtual void compute_residual(const float* x, float* residual, idx_t key)
+ const;
+
+ /** Computes a residual vector after indexing encoding (batch form).
+ * Equivalent to calling compute_residual for each vector.
+ *
+ * The residual vector is the difference between a vector and the
+ * reconstruction that can be decoded from its representation in
+ * the index. The residual can be used for multiple-stage indexing
+ * methods, like IndexIVF's methods.
+ *
+ * @param n number of vectors
+ * @param xs input vectors, size (n x d)
+ * @param residuals output residual vectors, size (n x d)
+ * @param keys encoded index, as returned by search and assign
+ */
+ virtual void compute_residual_n(
+ idx_t n,
+ const float* xs,
+ float* residuals,
+ const idx_t* keys) const;
+
+ /** Get a DistanceComputer (defined in AuxIndexStructures) object
+ * for this kind of index.
+ *
+ * DistanceComputer is implemented for indexes that support random
+ * access of their vectors.
+ */
+ virtual DistanceComputer* get_distance_computer() const;
+
+ /* The standalone codec interface */
+
+ /** size of the produced codes in bytes */
+ virtual size_t sa_code_size() const;
+
+ /** encode a set of vectors
+ *
+ * @param n number of vectors
+ * @param x input vectors, size n * d
+ * @param bytes output encoded vectors, size n * sa_code_size()
+ */
+ virtual void sa_encode(idx_t n, const float* x, uint8_t* bytes) const;
+
+ /** decode a set of vectors
+ *
+ * @param n number of vectors
+ * @param bytes input encoded vectors, size n * sa_code_size()
+ * @param x output vectors, size n * d
+ */
+ virtual void sa_decode(idx_t n, const uint8_t* bytes, float* x) const;
+
+ /** moves the entries from another dataset to self.
+ * On output, other is empty.
+ * add_id is added to all moved ids
+ * (for sequential ids, this would be this->ntotal) */
+ virtual void merge_from(Index& otherIndex, idx_t add_id = 0);
+
+ /** check that the two indexes are compatible (ie, they are
+ * trained in the same way and have the same
+ * parameters). Otherwise throw. */
+ virtual void check_compatible_for_merge(const Index& otherIndex) const;
+
+ /** Add vectors that are computed with the standalone codec
+ *
+ * @param codes codes to add size n * sa_code_size()
+ * @param xids corresponding ids, size n
+ */
+ virtual void add_sa_codes(idx_t n, const uint8_t* codes, const idx_t* xids);
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/Index2Layer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index2Layer.cpp
new file mode 100644
index 0000000..6a1669f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index2Layer.cpp
@@ -0,0 +1,343 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/Index2Layer.h>
+
+#include <faiss/impl/platform_macros.h>
+#include <cassert>
+#include <cinttypes>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+
+#ifdef __SSE3__
+#include <immintrin.h>
+#endif
+
+#include <algorithm>
+
+#include <faiss/IndexIVFPQ.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/*************************************
+ * Index2Layer implementation
+ *************************************/
+
+Index2Layer::Index2Layer(
+ Index* quantizer,
+ size_t nlist,
+ int M,
+ int nbit,
+ MetricType metric)
+ : IndexFlatCodes(0, quantizer->d, metric),
+ q1(quantizer, nlist),
+ pq(quantizer->d, M, nbit) {
+ is_trained = false;
+ for (int nbyte = 0; nbyte < 7; nbyte++) {
+ if (((size_t)1 << (8 * nbyte)) >= nlist) {
+ code_size_1 = nbyte;
+ break;
+ }
+ }
+ code_size_2 = pq.code_size;
+ code_size = code_size_1 + code_size_2;
+}
+
+Index2Layer::Index2Layer() {
+ code_size = code_size_1 = code_size_2 = 0;
+}
+
+Index2Layer::~Index2Layer() = default;
+
+void Index2Layer::train(idx_t n, const float* x) {
+ if (verbose) {
+ printf("training level-1 quantizer %" PRId64 " vectors in %dD\n", n, d);
+ }
+
+ q1.train_q1(n, x, verbose, metric_type);
+
+ if (verbose) {
+ printf("computing residuals\n");
+ }
+
+ const float* x_in = x;
+
+ x = fvecs_maybe_subsample(
+ d,
+ (size_t*)&n,
+ pq.cp.max_points_per_centroid * pq.ksub,
+ x,
+ verbose,
+ pq.cp.seed);
+
+ std::unique_ptr<const float[]> del_x(x_in == x ? nullptr : x);
+
+ std::vector<idx_t> assign(n); // assignement to coarse centroids
+ q1.quantizer->assign(n, x, assign.data());
+ std::vector<float> residuals(n * d);
+ for (idx_t i = 0; i < n; i++) {
+ q1.quantizer->compute_residual(
+ x + i * d, residuals.data() + i * d, assign[i]);
+ }
+
+ if (verbose)
+ printf("training %zdx%zd product quantizer on %" PRId64
+ " vectors in %dD\n",
+ pq.M,
+ pq.ksub,
+ n,
+ d);
+ pq.verbose = verbose;
+ pq.train(n, residuals.data());
+
+ is_trained = true;
+}
+
+void Index2Layer::search(
+ idx_t /*n*/,
+ const float* /*x*/,
+ idx_t /*k*/,
+ float* /*distances*/,
+ idx_t* /*labels*/,
+ const SearchParameters* /* params */) const {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void Index2Layer::transfer_to_IVFPQ(IndexIVFPQ& other) const {
+ FAISS_THROW_IF_NOT(other.nlist == q1.nlist);
+ FAISS_THROW_IF_NOT(other.code_size == code_size_2);
+ FAISS_THROW_IF_NOT(other.ntotal == 0);
+
+ const uint8_t* rp = codes.data();
+
+ for (idx_t i = 0; i < ntotal; i++) {
+ idx_t key = 0;
+ memcpy(&key, rp, code_size_1);
+ rp += code_size_1;
+ other.invlists->add_entry(key, i, rp);
+ rp += code_size_2;
+ }
+
+ other.ntotal = ntotal;
+}
+
+namespace {
+
+struct Distance2Level : DistanceComputer {
+ size_t d;
+ const Index2Layer& storage;
+ std::vector<float> buf;
+ const float* q;
+
+ const float *pq_l1_tab, *pq_l2_tab;
+
+ explicit Distance2Level(const Index2Layer& storage) : storage(storage) {
+ d = storage.d;
+ FAISS_ASSERT(storage.pq.dsub == 4);
+ pq_l2_tab = storage.pq.centroids.data();
+ buf.resize(2 * d);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ storage.reconstruct(i, buf.data());
+ storage.reconstruct(j, buf.data() + d);
+ return fvec_L2sqr(buf.data() + d, buf.data(), d);
+ }
+
+ void set_query(const float* x) override {
+ q = x;
+ }
+};
+
+// well optimized for xNN+PQNN
+struct DistanceXPQ4 : Distance2Level {
+ int M, k;
+
+ explicit DistanceXPQ4(const Index2Layer& storage)
+ : Distance2Level(storage) {
+ const IndexFlat* quantizer =
+ dynamic_cast<IndexFlat*>(storage.q1.quantizer);
+
+ FAISS_ASSERT(quantizer);
+ M = storage.pq.M;
+ pq_l1_tab = quantizer->get_xb();
+ }
+
+ float operator()(idx_t i) override {
+#ifdef __SSE3__
+ const uint8_t* code = storage.codes.data() + i * storage.code_size;
+ idx_t key = 0;
+ memcpy(&key, code, storage.code_size_1);
+ code += storage.code_size_1;
+
+ // walking pointers
+ const float* qa = q;
+ const __m128* l1_t = (const __m128*)(pq_l1_tab + d * key);
+ const __m128* pq_l2_t = (const __m128*)pq_l2_tab;
+ __m128 accu = _mm_setzero_ps();
+
+ for (int m = 0; m < M; m++) {
+ __m128 qi = _mm_loadu_ps(qa);
+ __m128 recons = _mm_add_ps(l1_t[m], pq_l2_t[*code++]);
+ __m128 diff = _mm_sub_ps(qi, recons);
+ accu = _mm_add_ps(accu, _mm_mul_ps(diff, diff));
+ pq_l2_t += 256;
+ qa += 4;
+ }
+
+ accu = _mm_hadd_ps(accu, accu);
+ accu = _mm_hadd_ps(accu, accu);
+ return _mm_cvtss_f32(accu);
+#else
+ FAISS_THROW_MSG("not implemented for non-x64 platforms");
+#endif
+ }
+};
+
+// well optimized for 2xNN+PQNN
+struct Distance2xXPQ4 : Distance2Level {
+ int M_2, mi_nbits;
+
+ explicit Distance2xXPQ4(const Index2Layer& storage)
+ : Distance2Level(storage) {
+ const MultiIndexQuantizer* mi =
+ dynamic_cast<MultiIndexQuantizer*>(storage.q1.quantizer);
+
+ FAISS_ASSERT(mi);
+ FAISS_ASSERT(storage.pq.M % 2 == 0);
+ M_2 = storage.pq.M / 2;
+ mi_nbits = mi->pq.nbits;
+ pq_l1_tab = mi->pq.centroids.data();
+ }
+
+ float operator()(idx_t i) override {
+ const uint8_t* code = storage.codes.data() + i * storage.code_size;
+ int64_t key01 = 0;
+ memcpy(&key01, code, storage.code_size_1);
+ code += storage.code_size_1;
+#ifdef __SSE3__
+
+ // walking pointers
+ const float* qa = q;
+ const __m128* pq_l1_t = (const __m128*)pq_l1_tab;
+ const __m128* pq_l2_t = (const __m128*)pq_l2_tab;
+ __m128 accu = _mm_setzero_ps();
+
+ for (int mi_m = 0; mi_m < 2; mi_m++) {
+ int64_t l1_idx = key01 & (((int64_t)1 << mi_nbits) - 1);
+ const __m128* pq_l1 = pq_l1_t + M_2 * l1_idx;
+
+ for (int m = 0; m < M_2; m++) {
+ __m128 qi = _mm_loadu_ps(qa);
+ __m128 recons = _mm_add_ps(pq_l1[m], pq_l2_t[*code++]);
+ __m128 diff = _mm_sub_ps(qi, recons);
+ accu = _mm_add_ps(accu, _mm_mul_ps(diff, diff));
+ pq_l2_t += 256;
+ qa += 4;
+ }
+ pq_l1_t += M_2 << mi_nbits;
+ key01 >>= mi_nbits;
+ }
+ accu = _mm_hadd_ps(accu, accu);
+ accu = _mm_hadd_ps(accu, accu);
+ return _mm_cvtss_f32(accu);
+#else
+ FAISS_THROW_MSG("not implemented for non-x64 platforms");
+#endif
+ }
+};
+
+} // namespace
+
+DistanceComputer* Index2Layer::get_distance_computer() const {
+#ifdef __SSE3__
+ const MultiIndexQuantizer* mi =
+ dynamic_cast<MultiIndexQuantizer*>(q1.quantizer);
+
+ if (mi && pq.M % 2 == 0 && pq.dsub == 4) {
+ return new Distance2xXPQ4(*this);
+ }
+
+ const IndexFlat* fl = dynamic_cast<IndexFlat*>(q1.quantizer);
+
+ if (fl && pq.dsub == 4) {
+ return new DistanceXPQ4(*this);
+ }
+#endif
+
+ return Index::get_distance_computer();
+}
+
+/* The standalone codec interface */
+
+// block size used in Index2Layer::sa_encode
+int index2layer_sa_encode_bs = 32768;
+
+void Index2Layer::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ idx_t bs = index2layer_sa_encode_bs;
+ if (n > bs) {
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(i0 + bs, n);
+ if (verbose) {
+ printf("Index2Layer::add: adding %" PRId64 ":%" PRId64
+ " / %" PRId64 "\n",
+ i0,
+ i1,
+ n);
+ }
+ sa_encode(i1 - i0, x + i0 * d, bytes + i0 * code_size);
+ }
+ return;
+ }
+
+ std::unique_ptr<int64_t[]> list_nos(new int64_t[n]);
+ q1.quantizer->assign(n, x, list_nos.get());
+ std::vector<float> residuals(n * d);
+ for (idx_t i = 0; i < n; i++) {
+ q1.quantizer->compute_residual(
+ x + i * d, residuals.data() + i * d, list_nos[i]);
+ }
+ pq.compute_codes(residuals.data(), bytes, n);
+
+ for (idx_t i = n - 1; i >= 0; i--) {
+ uint8_t* code = bytes + i * code_size;
+ memmove(code + code_size_1, bytes + i * code_size_2, code_size_2);
+ q1.encode_listno(list_nos[i], code);
+ }
+}
+
+void Index2Layer::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+#pragma omp parallel
+ {
+ std::vector<float> residual(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = bytes + i * code_size;
+ int64_t list_no = q1.decode_listno(code);
+ float* xi = x + i * d;
+ pq.decode(code + code_size_1, xi);
+ q1.quantizer->reconstruct(list_no, residual.data());
+ for (int j = 0; j < d; j++) {
+ xi[j] += residual[j];
+ }
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/Index2Layer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index2Layer.h
new file mode 100644
index 0000000..5c727d0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/Index2Layer.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+struct IndexIVFPQ;
+
+/** Same as an IndexIVFPQ without the inverted lists: codes are stored
+ * sequentially
+ *
+ * The class is mainly inteded to store encoded vectors that can be
+ * accessed randomly, the search function is not implemented.
+ */
+struct Index2Layer : IndexFlatCodes {
+ /// first level quantizer
+ Level1Quantizer q1;
+
+ /// second level quantizer is always a PQ
+ ProductQuantizer pq;
+
+ /// size of the code for the first level (ceil(log8(q1.nlist)))
+ size_t code_size_1;
+
+ /// size of the code for the second level
+ size_t code_size_2;
+
+ Index2Layer(
+ Index* quantizer,
+ size_t nlist,
+ int M,
+ int nbit = 8,
+ MetricType metric = METRIC_L2);
+
+ Index2Layer();
+ ~Index2Layer();
+
+ void train(idx_t n, const float* x) override;
+
+ /// not implemented
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ DistanceComputer* get_distance_computer() const override;
+
+ /// transfer the flat codes to an IVFPQ index
+ void transfer_to_IVFPQ(IndexIVFPQ& other) const;
+
+ /* The standalone codec interface */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+// block size used in Index2Layer::sa_encode
+FAISS_API extern int index2layer_sa_encode_bs;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizer.cpp
new file mode 100644
index 0000000..8dc6bcd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizer.cpp
@@ -0,0 +1,634 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexAdditiveQuantizer.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/extra_distances.h>
+
+namespace faiss {
+
+/**************************************************************************************
+ * IndexAdditiveQuantizer
+ **************************************************************************************/
+
+IndexAdditiveQuantizer::IndexAdditiveQuantizer(
+ idx_t d,
+ AdditiveQuantizer* aq,
+ MetricType metric)
+ : IndexFlatCodes(aq->code_size, d, metric), aq(aq) {
+ FAISS_THROW_IF_NOT(metric == METRIC_INNER_PRODUCT || metric == METRIC_L2);
+}
+
+namespace {
+
+/************************************************************
+ * DistanceComputer implementation
+ ************************************************************/
+
+template <class VectorDistance>
+struct AQDistanceComputerDecompress : FlatCodesDistanceComputer {
+ std::vector<float> tmp;
+ const AdditiveQuantizer& aq;
+ VectorDistance vd;
+ size_t d;
+
+ AQDistanceComputerDecompress(
+ const IndexAdditiveQuantizer& iaq,
+ VectorDistance vd)
+ : FlatCodesDistanceComputer(iaq.codes.data(), iaq.code_size),
+ tmp(iaq.d * 2),
+ aq(*iaq.aq),
+ vd(vd),
+ d(iaq.d) {}
+
+ const float* q;
+ void set_query(const float* x) final {
+ q = x;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) final {
+ aq.decode(codes + i * d, tmp.data(), 1);
+ aq.decode(codes + j * d, tmp.data() + d, 1);
+ return vd(tmp.data(), tmp.data() + d);
+ }
+
+ float distance_to_code(const uint8_t* code) final {
+ aq.decode(code, tmp.data(), 1);
+ return vd(q, tmp.data());
+ }
+
+ virtual ~AQDistanceComputerDecompress() = default;
+};
+
+template <bool is_IP, AdditiveQuantizer::Search_type_t st>
+struct AQDistanceComputerLUT : FlatCodesDistanceComputer {
+ std::vector<float> LUT;
+ const AdditiveQuantizer& aq;
+ size_t d;
+
+ explicit AQDistanceComputerLUT(const IndexAdditiveQuantizer& iaq)
+ : FlatCodesDistanceComputer(iaq.codes.data(), iaq.code_size),
+ LUT(iaq.aq->total_codebook_size + iaq.d * 2),
+ aq(*iaq.aq),
+ d(iaq.d) {}
+
+ float bias;
+ void set_query(const float* x) final {
+ // this is quite sub-optimal for multiple queries
+ aq.compute_LUT(1, x, LUT.data());
+ if (is_IP) {
+ bias = 0;
+ } else {
+ bias = fvec_norm_L2sqr(x, d);
+ }
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) final {
+ float* tmp = LUT.data();
+ aq.decode(codes + i * d, tmp, 1);
+ aq.decode(codes + j * d, tmp + d, 1);
+ return fvec_L2sqr(tmp, tmp + d, d);
+ }
+
+ float distance_to_code(const uint8_t* code) final {
+ return bias + aq.compute_1_distance_LUT<is_IP, st>(code, LUT.data());
+ }
+
+ virtual ~AQDistanceComputerLUT() = default;
+};
+
+/************************************************************
+ * scanning implementation for search
+ ************************************************************/
+
+template <class VectorDistance, class BlockResultHandler>
+void search_with_decompress(
+ const IndexAdditiveQuantizer& ir,
+ const float* xq,
+ VectorDistance& vd,
+ BlockResultHandler& res) {
+ const uint8_t* codes = ir.codes.data();
+ size_t ntotal = ir.ntotal;
+ size_t code_size = ir.code_size;
+ const AdditiveQuantizer* aq = ir.aq;
+
+ using SingleResultHandler =
+ typename BlockResultHandler::SingleResultHandler;
+
+#pragma omp parallel for if (res.nq > 100)
+ for (int64_t q = 0; q < res.nq; q++) {
+ SingleResultHandler resi(res);
+ resi.begin(q);
+ std::vector<float> tmp(ir.d);
+ const float* x = xq + ir.d * q;
+ for (size_t i = 0; i < ntotal; i++) {
+ aq->decode(codes + i * code_size, tmp.data(), 1);
+ float dis = vd(x, tmp.data());
+ resi.add_result(dis, i);
+ }
+ resi.end();
+ }
+}
+
+template <
+ bool is_IP,
+ AdditiveQuantizer::Search_type_t st,
+ class BlockResultHandler>
+void search_with_LUT(
+ const IndexAdditiveQuantizer& ir,
+ const float* xq,
+ BlockResultHandler& res) {
+ const AdditiveQuantizer& aq = *ir.aq;
+ const uint8_t* codes = ir.codes.data();
+ size_t ntotal = ir.ntotal;
+ size_t code_size = aq.code_size;
+ size_t nq = res.nq;
+ size_t d = ir.d;
+
+ using SingleResultHandler =
+ typename BlockResultHandler::SingleResultHandler;
+ std::unique_ptr<float[]> LUT(new float[nq * aq.total_codebook_size]);
+
+ aq.compute_LUT(nq, xq, LUT.get());
+
+#pragma omp parallel for if (nq > 100)
+ for (int64_t q = 0; q < nq; q++) {
+ SingleResultHandler resi(res);
+ resi.begin(q);
+ std::vector<float> tmp(aq.d);
+ const float* LUT_q = LUT.get() + aq.total_codebook_size * q;
+ float bias = 0;
+ if (!is_IP) { // the LUT function returns ||y||^2 - 2 * <x, y>, need to
+ // add ||x||^2
+ bias = fvec_norm_L2sqr(xq + q * d, d);
+ }
+ for (size_t i = 0; i < ntotal; i++) {
+ float dis = aq.compute_1_distance_LUT<is_IP, st>(
+ codes + i * code_size, LUT_q);
+ resi.add_result(dis + bias, i);
+ }
+ resi.end();
+ }
+}
+
+} // anonymous namespace
+
+FlatCodesDistanceComputer* IndexAdditiveQuantizer::
+ get_FlatCodesDistanceComputer() const {
+ if (aq->search_type == AdditiveQuantizer::ST_decompress) {
+ if (metric_type == METRIC_L2) {
+ using VD = VectorDistance<METRIC_L2>;
+ VD vd = {size_t(d), metric_arg};
+ return new AQDistanceComputerDecompress<VD>(*this, vd);
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ using VD = VectorDistance<METRIC_INNER_PRODUCT>;
+ VD vd = {size_t(d), metric_arg};
+ return new AQDistanceComputerDecompress<VD>(*this, vd);
+ } else {
+ FAISS_THROW_MSG("unsupported metric");
+ }
+ } else {
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ return new AQDistanceComputerLUT<
+ true,
+ AdditiveQuantizer::ST_LUT_nonorm>(*this);
+ } else {
+ switch (aq->search_type) {
+#define DISPATCH(st) \
+ case AdditiveQuantizer::st: \
+ return new AQDistanceComputerLUT<false, AdditiveQuantizer::st>(*this); \
+ break;
+ DISPATCH(ST_norm_float)
+ DISPATCH(ST_LUT_nonorm)
+ DISPATCH(ST_norm_qint8)
+ DISPATCH(ST_norm_qint4)
+ DISPATCH(ST_norm_cqint4)
+ case AdditiveQuantizer::ST_norm_cqint8:
+ case AdditiveQuantizer::ST_norm_lsq2x4:
+ case AdditiveQuantizer::ST_norm_rq2x4:
+ return new AQDistanceComputerLUT<
+ false,
+ AdditiveQuantizer::ST_norm_cqint8>(*this);
+ break;
+#undef DISPATCH
+ default:
+ FAISS_THROW_FMT(
+ "search type %d not supported", aq->search_type);
+ }
+ }
+ }
+}
+
+void IndexAdditiveQuantizer::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+
+ if (aq->search_type == AdditiveQuantizer::ST_decompress) {
+ if (metric_type == METRIC_L2) {
+ using VD = VectorDistance<METRIC_L2>;
+ VD vd = {size_t(d), metric_arg};
+ HeapBlockResultHandler<VD::C> rh(n, distances, labels, k);
+ search_with_decompress(*this, x, vd, rh);
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ using VD = VectorDistance<METRIC_INNER_PRODUCT>;
+ VD vd = {size_t(d), metric_arg};
+ HeapBlockResultHandler<VD::C> rh(n, distances, labels, k);
+ search_with_decompress(*this, x, vd, rh);
+ }
+ } else {
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ HeapBlockResultHandler<CMin<float, idx_t>> rh(
+ n, distances, labels, k);
+ search_with_LUT<true, AdditiveQuantizer::ST_LUT_nonorm>(
+ *this, x, rh);
+ } else {
+ HeapBlockResultHandler<CMax<float, idx_t>> rh(
+ n, distances, labels, k);
+ switch (aq->search_type) {
+#define DISPATCH(st) \
+ case AdditiveQuantizer::st: \
+ search_with_LUT<false, AdditiveQuantizer::st>(*this, x, rh); \
+ break;
+ DISPATCH(ST_norm_float)
+ DISPATCH(ST_LUT_nonorm)
+ DISPATCH(ST_norm_qint8)
+ DISPATCH(ST_norm_qint4)
+ DISPATCH(ST_norm_cqint4)
+ DISPATCH(ST_norm_from_LUT)
+ case AdditiveQuantizer::ST_norm_cqint8:
+ case AdditiveQuantizer::ST_norm_lsq2x4:
+ case AdditiveQuantizer::ST_norm_rq2x4:
+ search_with_LUT<false, AdditiveQuantizer::ST_norm_cqint8>(
+ *this, x, rh);
+ break;
+#undef DISPATCH
+ default:
+ FAISS_THROW_FMT(
+ "search type %d not supported", aq->search_type);
+ }
+ }
+ }
+}
+
+void IndexAdditiveQuantizer::sa_encode(idx_t n, const float* x, uint8_t* bytes)
+ const {
+ return aq->compute_codes(x, bytes, n);
+}
+
+void IndexAdditiveQuantizer::sa_decode(idx_t n, const uint8_t* bytes, float* x)
+ const {
+ return aq->decode(bytes, x, n);
+}
+
+/**************************************************************************************
+ * IndexResidualQuantizer
+ **************************************************************************************/
+
+IndexResidualQuantizer::IndexResidualQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexResidualQuantizer(
+ d,
+ std::vector<size_t>(M, nbits),
+ metric,
+ search_type) {}
+
+IndexResidualQuantizer::IndexResidualQuantizer(
+ int d,
+ const std::vector<size_t>& nbits,
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexAdditiveQuantizer(d, &rq, metric), rq(d, nbits, search_type) {
+ code_size = rq.code_size;
+ is_trained = false;
+}
+
+IndexResidualQuantizer::IndexResidualQuantizer()
+ : IndexResidualQuantizer(0, 0, 0) {}
+
+void IndexResidualQuantizer::train(idx_t n, const float* x) {
+ rq.train(n, x);
+ is_trained = true;
+}
+
+/**************************************************************************************
+ * IndexLocalSearchQuantizer
+ **************************************************************************************/
+
+IndexLocalSearchQuantizer::IndexLocalSearchQuantizer(
+ int d,
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexAdditiveQuantizer(d, &lsq, metric),
+ lsq(d, M, nbits, search_type) {
+ code_size = lsq.code_size;
+ is_trained = false;
+}
+
+IndexLocalSearchQuantizer::IndexLocalSearchQuantizer()
+ : IndexLocalSearchQuantizer(0, 0, 0) {}
+
+void IndexLocalSearchQuantizer::train(idx_t n, const float* x) {
+ lsq.train(n, x);
+ is_trained = true;
+}
+
+/**************************************************************************************
+ * IndexProductResidualQuantizer
+ **************************************************************************************/
+
+IndexProductResidualQuantizer::IndexProductResidualQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of residual quantizers
+ size_t Msub, ///< number of subquantizers per RQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexAdditiveQuantizer(d, &prq, metric),
+ prq(d, nsplits, Msub, nbits, search_type) {
+ code_size = prq.code_size;
+ is_trained = false;
+}
+
+IndexProductResidualQuantizer::IndexProductResidualQuantizer()
+ : IndexProductResidualQuantizer(0, 0, 0, 0) {}
+
+void IndexProductResidualQuantizer::train(idx_t n, const float* x) {
+ prq.train(n, x);
+ is_trained = true;
+}
+
+/**************************************************************************************
+ * IndexProductLocalSearchQuantizer
+ **************************************************************************************/
+
+IndexProductLocalSearchQuantizer::IndexProductLocalSearchQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of local search quantizers
+ size_t Msub, ///< number of subquantizers per LSQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexAdditiveQuantizer(d, &plsq, metric),
+ plsq(d, nsplits, Msub, nbits, search_type) {
+ code_size = plsq.code_size;
+ is_trained = false;
+}
+
+IndexProductLocalSearchQuantizer::IndexProductLocalSearchQuantizer()
+ : IndexProductLocalSearchQuantizer(0, 0, 0, 0) {}
+
+void IndexProductLocalSearchQuantizer::train(idx_t n, const float* x) {
+ plsq.train(n, x);
+ is_trained = true;
+}
+
+/**************************************************************************************
+ * AdditiveCoarseQuantizer
+ **************************************************************************************/
+
+AdditiveCoarseQuantizer::AdditiveCoarseQuantizer(
+ idx_t d,
+ AdditiveQuantizer* aq,
+ MetricType metric)
+ : Index(d, metric), aq(aq) {}
+
+void AdditiveCoarseQuantizer::add(idx_t, const float*) {
+ FAISS_THROW_MSG("not applicable");
+}
+
+void AdditiveCoarseQuantizer::reconstruct(idx_t key, float* recons) const {
+ aq->decode_64bit(key, recons);
+}
+
+void AdditiveCoarseQuantizer::reset() {
+ FAISS_THROW_MSG("not applicable");
+}
+
+void AdditiveCoarseQuantizer::train(idx_t n, const float* x) {
+ if (verbose) {
+ printf("AdditiveCoarseQuantizer::train: training on %zd vectors\n",
+ size_t(n));
+ }
+ size_t norms_size = sizeof(float) << aq->tot_bits;
+
+ FAISS_THROW_IF_NOT_MSG(
+ norms_size <= aq->max_mem_distances,
+ "the RCQ norms matrix will become too large, please reduce the number of quantization steps");
+
+ aq->train(n, x);
+ is_trained = true;
+ ntotal = (idx_t)1 << aq->tot_bits;
+
+ if (metric_type == METRIC_L2) {
+ if (verbose) {
+ printf("AdditiveCoarseQuantizer::train: computing centroid norms for %zd centroids\n",
+ size_t(ntotal));
+ }
+ // this is not necessary for the residualcoarsequantizer when
+ // using beam search. We'll see if the memory overhead is too high
+ centroid_norms.resize(ntotal);
+ aq->compute_centroid_norms(centroid_norms.data());
+ }
+}
+
+void AdditiveCoarseQuantizer::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ aq->knn_centroids_inner_product(n, x, k, distances, labels);
+ } else if (metric_type == METRIC_L2) {
+ FAISS_THROW_IF_NOT(centroid_norms.size() == ntotal);
+ aq->knn_centroids_L2(n, x, k, distances, labels, centroid_norms.data());
+ }
+}
+
+/**************************************************************************************
+ * ResidualCoarseQuantizer
+ **************************************************************************************/
+
+ResidualCoarseQuantizer::ResidualCoarseQuantizer(
+ int d, ///< dimensionality of the input vectors
+ const std::vector<size_t>& nbits,
+ MetricType metric)
+ : AdditiveCoarseQuantizer(d, &rq, metric), rq(d, nbits) {
+ FAISS_THROW_IF_NOT(rq.tot_bits <= 63);
+ is_trained = false;
+}
+
+ResidualCoarseQuantizer::ResidualCoarseQuantizer(
+ int d,
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric)
+ : ResidualCoarseQuantizer(d, std::vector<size_t>(M, nbits), metric) {}
+
+ResidualCoarseQuantizer::ResidualCoarseQuantizer()
+ : ResidualCoarseQuantizer(0, 0, 0) {}
+
+void ResidualCoarseQuantizer::set_beam_factor(float new_beam_factor) {
+ beam_factor = new_beam_factor;
+ if (new_beam_factor > 0) {
+ FAISS_THROW_IF_NOT(new_beam_factor >= 1.0);
+ if (rq.codebook_cross_products.size() == 0) {
+ rq.compute_codebook_tables();
+ }
+ return;
+ } else {
+ // new_beam_factor = -1: exhaustive computation.
+ // Does not use the cross_products
+ rq.codebook_cross_products.resize(0);
+ // but the centroid norms are necessary!
+ if (metric_type == METRIC_L2 && ntotal != centroid_norms.size()) {
+ if (verbose) {
+ printf("AdditiveCoarseQuantizer::train: computing centroid norms for %zd centroids\n",
+ size_t(ntotal));
+ }
+ centroid_norms.resize(ntotal);
+ aq->compute_centroid_norms(centroid_norms.data());
+ }
+ }
+}
+
+void ResidualCoarseQuantizer::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ float actual_beam_factor = this->beam_factor;
+ if (params_in) {
+ auto params =
+ dynamic_cast<const SearchParametersResidualCoarseQuantizer*>(
+ params_in);
+ FAISS_THROW_IF_NOT_MSG(
+ params,
+ "need SearchParametersResidualCoarseQuantizer parameters");
+ actual_beam_factor = params->beam_factor;
+ }
+
+ if (actual_beam_factor < 0) {
+ AdditiveCoarseQuantizer::search(n, x, k, distances, labels);
+ return;
+ }
+
+ int beam_size = int(k * actual_beam_factor);
+ if (beam_size > ntotal) {
+ beam_size = ntotal;
+ }
+ size_t memory_per_point = rq.memory_per_point(beam_size);
+
+ /*
+
+ printf("mem per point %ld n=%d max_mem_distance=%ld mem_kb=%zd\n",
+ memory_per_point, int(n), rq.max_mem_distances, get_mem_usage_kb());
+ */
+ if (n > 1 && memory_per_point * n > rq.max_mem_distances) {
+ // then split queries to reduce temp memory
+ idx_t bs = rq.max_mem_distances / memory_per_point;
+ if (bs == 0) {
+ bs = 1; // otherwise we can't do much
+ }
+ if (verbose) {
+ printf("ResidualCoarseQuantizer::search: run %d searches in batches of size %d\n",
+ int(n),
+ int(bs));
+ }
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(n, i0 + bs);
+ search(i1 - i0,
+ x + i0 * d,
+ k,
+ distances + i0 * k,
+ labels + i0 * k,
+ params_in);
+ InterruptCallback::check();
+ }
+ return;
+ }
+
+ std::vector<int32_t> codes(beam_size * rq.M * n);
+ std::vector<float> beam_distances(n * beam_size);
+
+ rq.refine_beam(
+ n, 1, x, beam_size, codes.data(), nullptr, beam_distances.data());
+
+ // pack int32 table
+#pragma omp parallel for if (n > 4000)
+ for (idx_t i = 0; i < n; i++) {
+ memcpy(distances + i * k,
+ beam_distances.data() + beam_size * i,
+ k * sizeof(distances[0]));
+
+ const int32_t* codes_i = codes.data() + beam_size * i * rq.M;
+ for (idx_t j = 0; j < k; j++) {
+ idx_t l = 0;
+ int shift = 0;
+ for (int m = 0; m < rq.M; m++) {
+ l |= (*codes_i++) << shift;
+ shift += rq.nbits[m];
+ }
+ labels[i * k + j] = l;
+ }
+ }
+}
+
+void ResidualCoarseQuantizer::initialize_from(
+ const ResidualCoarseQuantizer& other) {
+ FAISS_THROW_IF_NOT(rq.M <= other.rq.M);
+ rq.initialize_from(other.rq);
+ set_beam_factor(other.beam_factor);
+ is_trained = other.is_trained;
+ ntotal = (idx_t)1 << aq->tot_bits;
+}
+
+/**************************************************************************************
+ * LocalSearchCoarseQuantizer
+ **************************************************************************************/
+
+LocalSearchCoarseQuantizer::LocalSearchCoarseQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric)
+ : AdditiveCoarseQuantizer(d, &lsq, metric), lsq(d, M, nbits) {
+ FAISS_THROW_IF_NOT(lsq.tot_bits <= 63);
+ is_trained = false;
+}
+
+LocalSearchCoarseQuantizer::LocalSearchCoarseQuantizer() {
+ aq = &lsq;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizer.h
new file mode 100644
index 0000000..31e3c8c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizer.h
@@ -0,0 +1,262 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_INDEX_ADDITIVE_QUANTIZER_H
+#define FAISS_INDEX_ADDITIVE_QUANTIZER_H
+
+#include <faiss/impl/AdditiveQuantizer.h>
+
+#include <cstdint>
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/ProductAdditiveQuantizer.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/// Abstract class for additive quantizers. The search functions are in common.
+struct IndexAdditiveQuantizer : IndexFlatCodes {
+ // the quantizer, this points to the relevant field in the inheriting
+ // classes
+ AdditiveQuantizer* aq;
+ using Search_type_t = AdditiveQuantizer::Search_type_t;
+
+ explicit IndexAdditiveQuantizer(
+ idx_t d,
+ AdditiveQuantizer* aq,
+ MetricType metric = METRIC_L2);
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /* The standalone codec interface */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const override;
+};
+
+/** Index based on a residual quantizer. Stored vectors are
+ * approximated by residual quantization codes.
+ * Can also be used as a codec
+ */
+struct IndexResidualQuantizer : IndexAdditiveQuantizer {
+ /// The residual quantizer used to encode the vectors
+ ResidualQuantizer rq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ IndexResidualQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexResidualQuantizer(
+ int d,
+ const std::vector<size_t>& nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexResidualQuantizer();
+
+ void train(idx_t n, const float* x) override;
+};
+
+struct IndexLocalSearchQuantizer : IndexAdditiveQuantizer {
+ LocalSearchQuantizer lsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ IndexLocalSearchQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexLocalSearchQuantizer();
+
+ void train(idx_t n, const float* x) override;
+};
+
+/** Index based on a product residual quantizer.
+ */
+struct IndexProductResidualQuantizer : IndexAdditiveQuantizer {
+ /// The product residual quantizer used to encode the vectors
+ ProductResidualQuantizer prq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of residual quantizers
+ * @param Msub number of subquantizers per RQ
+ * @param nbits number of bit per subvector index
+ */
+ IndexProductResidualQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of residual quantizers
+ size_t Msub, ///< number of subquantizers per RQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexProductResidualQuantizer();
+
+ void train(idx_t n, const float* x) override;
+};
+
+/** Index based on a product local search quantizer.
+ */
+struct IndexProductLocalSearchQuantizer : IndexAdditiveQuantizer {
+ /// The product local search quantizer used to encode the vectors
+ ProductLocalSearchQuantizer plsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of local search quantizers
+ * @param Msub number of subquantizers per LSQ
+ * @param nbits number of bit per subvector index
+ */
+ IndexProductLocalSearchQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of local search quantizers
+ size_t Msub, ///< number of subquantizers per LSQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexProductLocalSearchQuantizer();
+
+ void train(idx_t n, const float* x) override;
+};
+
+/** A "virtual" index where the elements are the residual quantizer centroids.
+ *
+ * Intended for use as a coarse quantizer in an IndexIVF.
+ */
+struct AdditiveCoarseQuantizer : Index {
+ AdditiveQuantizer* aq;
+
+ explicit AdditiveCoarseQuantizer(
+ idx_t d = 0,
+ AdditiveQuantizer* aq = nullptr,
+ MetricType metric = METRIC_L2);
+
+ /// norms of centroids, useful for knn-search
+ std::vector<float> centroid_norms;
+
+ /// N/A
+ void add(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+ void train(idx_t n, const float* x) override;
+
+ /// N/A
+ void reset() override;
+};
+
+struct SearchParametersResidualCoarseQuantizer : SearchParameters {
+ float beam_factor = 4.0f;
+ ~SearchParametersResidualCoarseQuantizer() {}
+};
+
+/** The ResidualCoarseQuantizer is a bit specialized compared to the
+ * default AdditiveCoarseQuantizer because it can use a beam search
+ * at search time (slow but may be useful for very large vocabularies) */
+struct ResidualCoarseQuantizer : AdditiveCoarseQuantizer {
+ /// The residual quantizer used to encode the vectors
+ ResidualQuantizer rq;
+
+ /// factor between the beam size and the search k
+ /// if negative, use exact search-to-centroid
+ float beam_factor = 4.0f;
+
+ /// computes centroid norms if required
+ void set_beam_factor(float new_beam_factor);
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ ResidualCoarseQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2);
+
+ ResidualCoarseQuantizer(
+ int d,
+ const std::vector<size_t>& nbits,
+ MetricType metric = METRIC_L2);
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /** Copy the M first codebook levels from other. Useful to crop a
+ * ResidualQuantizer to its first M quantizers. */
+ void initialize_from(const ResidualCoarseQuantizer& other);
+
+ ResidualCoarseQuantizer();
+};
+
+struct LocalSearchCoarseQuantizer : AdditiveCoarseQuantizer {
+ /// The residual quantizer used to encode the vectors
+ LocalSearchQuantizer lsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ LocalSearchCoarseQuantizer(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2);
+
+ LocalSearchCoarseQuantizer();
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizerFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizerFastScan.cpp
new file mode 100644
index 0000000..58d72a3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizerFastScan.cpp
@@ -0,0 +1,297 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexAdditiveQuantizerFastScan.h>
+
+#include <cassert>
+#include <memory>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/LookupTableScaler.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/utils/quantize_lut.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+inline size_t roundup(size_t a, size_t b) {
+ return (a + b - 1) / b * b;
+}
+
+IndexAdditiveQuantizerFastScan::IndexAdditiveQuantizerFastScan(
+ AdditiveQuantizer* aq,
+ MetricType metric,
+ int bbs) {
+ init(aq, metric, bbs);
+}
+
+void IndexAdditiveQuantizerFastScan::init(
+ AdditiveQuantizer* aq_init,
+ MetricType metric,
+ int bbs) {
+ FAISS_THROW_IF_NOT(aq_init != nullptr);
+ FAISS_THROW_IF_NOT(!aq_init->nbits.empty());
+ FAISS_THROW_IF_NOT(aq_init->nbits[0] == 4);
+ if (metric == METRIC_INNER_PRODUCT) {
+ FAISS_THROW_IF_NOT_MSG(
+ aq_init->search_type == AdditiveQuantizer::ST_LUT_nonorm,
+ "Search type must be ST_LUT_nonorm for IP metric");
+ } else {
+ FAISS_THROW_IF_NOT_MSG(
+ aq_init->search_type == AdditiveQuantizer::ST_norm_lsq2x4 ||
+ aq_init->search_type ==
+ AdditiveQuantizer::ST_norm_rq2x4,
+ "Search type must be lsq2x4 or rq2x4 for L2 metric");
+ }
+
+ this->aq = aq_init;
+ if (metric == METRIC_L2) {
+ M = aq_init->M + 2; // 2x4 bits AQ
+ } else {
+ M = aq_init->M;
+ }
+ init_fastscan(aq_init->d, M, 4, metric, bbs);
+
+ max_train_points = 1024 * ksub * M;
+}
+
+IndexAdditiveQuantizerFastScan::IndexAdditiveQuantizerFastScan()
+ : IndexFastScan() {
+ is_trained = false;
+ aq = nullptr;
+}
+
+IndexAdditiveQuantizerFastScan::IndexAdditiveQuantizerFastScan(
+ const IndexAdditiveQuantizer& orig,
+ int bbs) {
+ init(orig.aq, orig.metric_type, bbs);
+
+ ntotal = orig.ntotal;
+ is_trained = orig.is_trained;
+ orig_codes = orig.codes.data();
+
+ ntotal2 = roundup(ntotal, bbs);
+ codes.resize(ntotal2 * M2 / 2);
+ pq4_pack_codes(orig_codes, ntotal, M, ntotal2, bbs, M2, codes.get());
+}
+
+IndexAdditiveQuantizerFastScan::~IndexAdditiveQuantizerFastScan() = default;
+
+void IndexAdditiveQuantizerFastScan::train(idx_t n, const float* x_in) {
+ if (is_trained) {
+ return;
+ }
+
+ const int seed = 0x12345;
+ size_t nt = n;
+ const float* x = fvecs_maybe_subsample(
+ d, &nt, max_train_points, x_in, verbose, seed);
+ n = nt;
+ if (verbose) {
+ printf("training additive quantizer on %zd vectors\n", nt);
+ }
+
+ aq->verbose = verbose;
+ aq->train(n, x);
+ if (metric_type == METRIC_L2) {
+ estimate_norm_scale(n, x);
+ }
+
+ is_trained = true;
+}
+
+void IndexAdditiveQuantizerFastScan::estimate_norm_scale(
+ idx_t n,
+ const float* x_in) {
+ FAISS_THROW_IF_NOT(metric_type == METRIC_L2);
+
+ constexpr int seed = 0x980903;
+ constexpr size_t max_points_estimated = 65536;
+ size_t ns = n;
+ const float* x = fvecs_maybe_subsample(
+ d, &ns, max_points_estimated, x_in, verbose, seed);
+ n = ns;
+ std::unique_ptr<float[]> del_x;
+ if (x != x_in) {
+ del_x.reset((float*)x);
+ }
+
+ std::vector<float> dis_tables(n * M * ksub);
+ compute_float_LUT(dis_tables.data(), n, x);
+
+ // here we compute the mean of scales for each query
+ // TODO: try max of scales
+ double scale = 0;
+
+#pragma omp parallel for reduction(+ : scale)
+ for (idx_t i = 0; i < n; i++) {
+ const float* lut = dis_tables.data() + i * M * ksub;
+ scale += quantize_lut::aq_estimate_norm_scale(M, ksub, 2, lut);
+ }
+ scale /= n;
+ norm_scale = (int)std::roundf(std::max(scale, 1.0));
+
+ if (verbose) {
+ printf("estimated norm scale: %lf\n", scale);
+ printf("rounded norm scale: %d\n", norm_scale);
+ }
+}
+
+void IndexAdditiveQuantizerFastScan::compute_codes(
+ uint8_t* tmp_codes,
+ idx_t n,
+ const float* x) const {
+ aq->compute_codes(x, tmp_codes, n);
+}
+
+void IndexAdditiveQuantizerFastScan::compute_float_LUT(
+ float* lut,
+ idx_t n,
+ const float* x) const {
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ aq->compute_LUT(n, x, lut, 1.0f);
+ } else {
+ // compute inner product look-up tables
+ const size_t ip_dim12 = aq->M * ksub;
+ const size_t norm_dim12 = 2 * ksub;
+ std::vector<float> ip_lut(n * ip_dim12);
+ aq->compute_LUT(n, x, ip_lut.data(), -2.0f);
+
+ // copy and rescale norm look-up tables
+ auto norm_tabs = aq->norm_tabs;
+ if (rescale_norm && norm_scale > 1 && metric_type == METRIC_L2) {
+ for (size_t i = 0; i < norm_tabs.size(); i++) {
+ norm_tabs[i] /= norm_scale;
+ }
+ }
+ const float* norm_lut = norm_tabs.data();
+ FAISS_THROW_IF_NOT(norm_tabs.size() == norm_dim12);
+
+ // combine them
+ for (idx_t i = 0; i < n; i++) {
+ memcpy(lut, ip_lut.data() + i * ip_dim12, ip_dim12 * sizeof(*lut));
+ lut += ip_dim12;
+ memcpy(lut, norm_lut, norm_dim12 * sizeof(*lut));
+ lut += norm_dim12;
+ }
+ }
+}
+
+void IndexAdditiveQuantizerFastScan::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+ bool rescale = (rescale_norm && norm_scale > 1 && metric_type == METRIC_L2);
+ if (!rescale) {
+ IndexFastScan::search(n, x, k, distances, labels);
+ return;
+ }
+
+ NormTableScaler scaler(norm_scale);
+ if (metric_type == METRIC_L2) {
+ search_dispatch_implem<true>(n, x, k, distances, labels, &scaler);
+ } else {
+ search_dispatch_implem<false>(n, x, k, distances, labels, &scaler);
+ }
+}
+
+void IndexAdditiveQuantizerFastScan::sa_decode(
+ idx_t n,
+ const uint8_t* bytes,
+ float* x) const {
+ aq->decode(bytes, x, n);
+}
+
+/**************************************************************************************
+ * IndexResidualQuantizerFastScan
+ **************************************************************************************/
+
+IndexResidualQuantizerFastScan::IndexResidualQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : rq(d, M, nbits, search_type) {
+ init(&rq, metric, bbs);
+}
+
+IndexResidualQuantizerFastScan::IndexResidualQuantizerFastScan() {
+ aq = &rq;
+}
+
+/**************************************************************************************
+ * IndexLocalSearchQuantizerFastScan
+ **************************************************************************************/
+
+IndexLocalSearchQuantizerFastScan::IndexLocalSearchQuantizerFastScan(
+ int d,
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : lsq(d, M, nbits, search_type) {
+ init(&lsq, metric, bbs);
+}
+
+IndexLocalSearchQuantizerFastScan::IndexLocalSearchQuantizerFastScan() {
+ aq = &lsq;
+}
+
+/**************************************************************************************
+ * IndexProductResidualQuantizerFastScan
+ **************************************************************************************/
+
+IndexProductResidualQuantizerFastScan::IndexProductResidualQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of residual quantizers
+ size_t Msub, ///< number of subquantizers per RQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : prq(d, nsplits, Msub, nbits, search_type) {
+ init(&prq, metric, bbs);
+}
+
+IndexProductResidualQuantizerFastScan::IndexProductResidualQuantizerFastScan() {
+ aq = &prq;
+}
+
+/**************************************************************************************
+ * IndexProductLocalSearchQuantizerFastScan
+ **************************************************************************************/
+
+IndexProductLocalSearchQuantizerFastScan::
+ IndexProductLocalSearchQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of local search quantizers
+ size_t Msub, ///< number of subquantizers per LSQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : plsq(d, nsplits, Msub, nbits, search_type) {
+ init(&plsq, metric, bbs);
+}
+
+IndexProductLocalSearchQuantizerFastScan::
+ IndexProductLocalSearchQuantizerFastScan() {
+ aq = &plsq;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizerFastScan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizerFastScan.h
new file mode 100644
index 0000000..93a4c80
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexAdditiveQuantizerFastScan.h
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexFastScan.h>
+#include <faiss/impl/AdditiveQuantizer.h>
+#include <faiss/impl/ProductAdditiveQuantizer.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+/** Fast scan version of IndexAQ. Works for 4-bit AQ for now.
+ *
+ * The codes are not stored sequentially but grouped in blocks of size bbs.
+ * This makes it possible to compute distances quickly with SIMD instructions.
+ *
+ * Implementations:
+ * 12: blocked loop with internal loop on Q with qbs
+ * 13: same with reservoir accumulator to store results
+ * 14: no qbs with heap accumulator
+ * 15: no qbs with reservoir accumulator
+ */
+
+struct IndexAdditiveQuantizerFastScan : IndexFastScan {
+ AdditiveQuantizer* aq;
+ using Search_type_t = AdditiveQuantizer::Search_type_t;
+
+ bool rescale_norm = true;
+ int norm_scale = 1;
+
+ // max number of training vectors
+ size_t max_train_points = 0;
+
+ explicit IndexAdditiveQuantizerFastScan(
+ AdditiveQuantizer* aq,
+ MetricType metric = METRIC_L2,
+ int bbs = 32);
+
+ void init(
+ AdditiveQuantizer* aq,
+ MetricType metric = METRIC_L2,
+ int bbs = 32);
+
+ IndexAdditiveQuantizerFastScan();
+
+ ~IndexAdditiveQuantizerFastScan() override;
+
+ /// build from an existing IndexAQ
+ explicit IndexAdditiveQuantizerFastScan(
+ const IndexAdditiveQuantizer& orig,
+ int bbs = 32);
+
+ void train(idx_t n, const float* x) override;
+
+ void estimate_norm_scale(idx_t n, const float* x);
+
+ void compute_codes(uint8_t* codes, idx_t n, const float* x) const override;
+
+ void compute_float_LUT(float* lut, idx_t n, const float* x) const override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /** Decode a set of vectors.
+ *
+ * NOTE: The codes in the IndexAdditiveQuantizerFastScan object are non-
+ * contiguous. But this method requires a contiguous representation.
+ *
+ * @param n number of vectors
+ * @param bytes input encoded vectors, size n * code_size
+ * @param x output vectors, size n * d
+ */
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+/** Index based on a residual quantizer. Stored vectors are
+ * approximated by residual quantization codes.
+ * Can also be used as a codec
+ */
+struct IndexResidualQuantizerFastScan : IndexAdditiveQuantizerFastScan {
+ /// The residual quantizer used to encode the vectors
+ ResidualQuantizer rq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ * @param metric metric type
+ * @param search_type AQ search type
+ */
+ IndexResidualQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_rq2x4,
+ int bbs = 32);
+
+ IndexResidualQuantizerFastScan();
+};
+
+/** Index based on a local search quantizer. Stored vectors are
+ * approximated by local search quantization codes.
+ * Can also be used as a codec
+ */
+struct IndexLocalSearchQuantizerFastScan : IndexAdditiveQuantizerFastScan {
+ LocalSearchQuantizer lsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ * @param metric metric type
+ * @param search_type AQ search type
+ */
+ IndexLocalSearchQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_lsq2x4,
+ int bbs = 32);
+
+ IndexLocalSearchQuantizerFastScan();
+};
+
+/** Index based on a product residual quantizer. Stored vectors are
+ * approximated by product residual quantization codes.
+ * Can also be used as a codec
+ */
+struct IndexProductResidualQuantizerFastScan : IndexAdditiveQuantizerFastScan {
+ /// The product residual quantizer used to encode the vectors
+ ProductResidualQuantizer prq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of residual quantizers
+ * @param Msub number of subquantizers per RQ
+ * @param nbits number of bit per subvector index
+ * @param metric metric type
+ * @param search_type AQ search type
+ */
+ IndexProductResidualQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of residual quantizers
+ size_t Msub, ///< number of subquantizers per RQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_rq2x4,
+ int bbs = 32);
+
+ IndexProductResidualQuantizerFastScan();
+};
+
+/** Index based on a product local search quantizer. Stored vectors are
+ * approximated by product local search quantization codes.
+ * Can also be used as a codec
+ */
+struct IndexProductLocalSearchQuantizerFastScan
+ : IndexAdditiveQuantizerFastScan {
+ /// The product local search quantizer used to encode the vectors
+ ProductLocalSearchQuantizer plsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of local search quantizers
+ * @param Msub number of subquantizers per LSQ
+ * @param nbits number of bit per subvector index
+ * @param metric metric type
+ * @param search_type AQ search type
+ */
+ IndexProductLocalSearchQuantizerFastScan(
+ int d, ///< dimensionality of the input vectors
+ size_t nsplits, ///< number of local search quantizers
+ size_t Msub, ///< number of subquantizers per LSQ
+ size_t nbits, ///< number of bit per subvector index
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_rq2x4,
+ int bbs = 32);
+
+ IndexProductLocalSearchQuantizerFastScan();
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinary.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinary.cpp
new file mode 100644
index 0000000..3c8165b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinary.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexBinary.h>
+#include <faiss/impl/FaissAssert.h>
+
+#include <cinttypes>
+#include <cstring>
+
+namespace faiss {
+
+IndexBinary::IndexBinary(idx_t d, MetricType metric)
+ : d(d), code_size(d / 8), metric_type(metric) {
+ FAISS_THROW_IF_NOT(d % 8 == 0);
+}
+
+IndexBinary::~IndexBinary() = default;
+
+void IndexBinary::train(idx_t, const uint8_t*) {
+ // Does nothing by default.
+}
+
+void IndexBinary::range_search(
+ idx_t,
+ const uint8_t*,
+ int,
+ RangeSearchResult*,
+ const SearchParameters*) const {
+ FAISS_THROW_MSG("range search not implemented");
+}
+
+void IndexBinary::assign(idx_t n, const uint8_t* x, idx_t* labels, idx_t k)
+ const {
+ std::vector<int> distances(n * k);
+ search(n, x, k, distances.data(), labels);
+}
+
+void IndexBinary::add_with_ids(idx_t, const uint8_t*, const idx_t*) {
+ FAISS_THROW_MSG("add_with_ids not implemented for this type of index");
+}
+
+size_t IndexBinary::remove_ids(const IDSelector&) {
+ FAISS_THROW_MSG("remove_ids not implemented for this type of index");
+ return 0;
+}
+
+void IndexBinary::reconstruct(idx_t, uint8_t*) const {
+ FAISS_THROW_MSG("reconstruct not implemented for this type of index");
+}
+
+void IndexBinary::reconstruct_n(idx_t i0, idx_t ni, uint8_t* recons) const {
+ for (idx_t i = 0; i < ni; i++) {
+ reconstruct(i0 + i, recons + i * code_size);
+ }
+}
+
+void IndexBinary::search_and_reconstruct(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ uint8_t* recons,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+
+ search(n, x, k, distances, labels, params);
+ for (idx_t i = 0; i < n; ++i) {
+ for (idx_t j = 0; j < k; ++j) {
+ idx_t ij = i * k + j;
+ idx_t key = labels[ij];
+ uint8_t* reconstructed = recons + ij * code_size;
+ if (key < 0) {
+ // Fill with NaNs
+ memset(reconstructed, -1, code_size);
+ } else {
+ reconstruct(key, reconstructed);
+ }
+ }
+ }
+}
+
+void IndexBinary::display() const {
+ printf("Index: %s -> %" PRId64 " elements\n",
+ typeid(*this).name(),
+ ntotal);
+}
+
+void IndexBinary::merge_from(
+ IndexBinary& /* otherIndex */,
+ idx_t /* add_id */) {
+ FAISS_THROW_MSG("merge_from() not implemented");
+}
+
+void IndexBinary::check_compatible_for_merge(
+ const IndexBinary& /* otherIndex */) const {
+ FAISS_THROW_MSG("check_compatible_for_merge() not implemented");
+}
+
+size_t IndexBinary::sa_code_size() const {
+ return code_size;
+}
+
+void IndexBinary::add_sa_codes(
+ idx_t n,
+ const uint8_t* codes,
+ const idx_t* xids) {
+ add_with_ids(n, codes, xids);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinary.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinary.h
new file mode 100644
index 0000000..e9801a7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinary.h
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_INDEX_BINARY_H
+#define FAISS_INDEX_BINARY_H
+
+#include <cstdio>
+#include <sstream>
+#include <string>
+#include <typeinfo>
+
+#include <faiss/Index.h>
+
+namespace faiss {
+
+/// Forward declarations see AuxIndexStructures.h
+struct IDSelector;
+struct RangeSearchResult;
+
+/** Abstract structure for a binary index.
+ *
+ * Supports adding vertices and searching them.
+ *
+ * All queries are symmetric because there is no distinction between codes and
+ * vectors.
+ */
+struct IndexBinary {
+ using component_t = uint8_t;
+ using distance_t = int32_t;
+
+ int d = 0; ///< vector dimension
+ int code_size = 0; ///< number of bytes per vector ( = d / 8 )
+ idx_t ntotal = 0; ///< total nb of indexed vectors
+ bool verbose = false; ///< verbosity level
+
+ /// set if the Index does not require training, or if training is done
+ /// already
+ bool is_trained = true;
+
+ /// type of metric this index uses for search
+ MetricType metric_type = METRIC_L2;
+
+ explicit IndexBinary(idx_t d = 0, MetricType metric = METRIC_L2);
+
+ virtual ~IndexBinary();
+
+ /** Perform training on a representative set of vectors.
+ *
+ * @param n nb of training vectors
+ * @param x training vecors, size n * d / 8
+ */
+ virtual void train(idx_t n, const uint8_t* x);
+
+ /** Add n vectors of dimension d to the index.
+ *
+ * Vectors are implicitly assigned labels ntotal .. ntotal + n - 1
+ * @param x input matrix, size n * d / 8
+ */
+ virtual void add(idx_t n, const uint8_t* x) = 0;
+
+ /** Same as add, but stores xids instead of sequential ids.
+ *
+ * The default implementation fails with an assertion, as it is
+ * not supported by all indexes.
+ *
+ * @param xids if non-null, ids to store for the vectors (size n)
+ */
+ virtual void add_with_ids(idx_t n, const uint8_t* x, const idx_t* xids);
+
+ /** Query n vectors of dimension d to the index.
+ *
+ * return at most k vectors. If there are not enough results for a
+ * query, the result array is padded with -1s.
+ *
+ * @param x input vectors to search, size n * d / 8
+ * @param labels output labels of the NNs, size n*k
+ * @param distances output pairwise distances, size n*k
+ */
+ virtual void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const = 0;
+
+ /** Query n vectors of dimension d to the index.
+ *
+ * return all vectors with distance < radius. Note that many indexes
+ * do not implement the range_search (only the k-NN search is
+ * mandatory). The distances are converted to float to reuse the
+ * RangeSearchResult structure, but they are integer. By convention,
+ * only distances < radius (strict comparison) are returned,
+ * ie. radius = 0 does not return any result and 1 returns only
+ * exact same vectors.
+ *
+ * @param x input vectors to search, size n * d / 8
+ * @param radius search radius
+ * @param result result table
+ */
+ virtual void range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const;
+
+ /** Return the indexes of the k vectors closest to the query x.
+ *
+ * This function is identical to search but only returns labels of
+ * neighbors.
+ * @param x input vectors to search, size n * d / 8
+ * @param labels output labels of the NNs, size n*k
+ */
+ void assign(idx_t n, const uint8_t* x, idx_t* labels, idx_t k = 1) const;
+
+ /// Removes all elements from the database.
+ virtual void reset() = 0;
+
+ /** Removes IDs from the index. Not supported by all indexes.
+ */
+ virtual size_t remove_ids(const IDSelector& sel);
+
+ /** Reconstruct a stored vector.
+ *
+ * This function may not be defined for some indexes.
+ * @param key id of the vector to reconstruct
+ * @param recons reconstucted vector (size d / 8)
+ */
+ virtual void reconstruct(idx_t key, uint8_t* recons) const;
+
+ /** Reconstruct vectors i0 to i0 + ni - 1.
+ *
+ * This function may not be defined for some indexes.
+ * @param recons reconstucted vectors (size ni * d / 8)
+ */
+ virtual void reconstruct_n(idx_t i0, idx_t ni, uint8_t* recons) const;
+
+ /** Similar to search, but also reconstructs the stored vectors (or an
+ * approximation in the case of lossy coding) for the search results.
+ *
+ * If there are not enough results for a query, the resulting array
+ * is padded with -1s.
+ *
+ * @param recons reconstructed vectors size (n, k, d)
+ **/
+ virtual void search_and_reconstruct(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ uint8_t* recons,
+ const SearchParameters* params = nullptr) const;
+
+ /** Display the actual class name and some more info. */
+ void display() const;
+
+ /** moves the entries from another dataset to self.
+ * On output, other is empty.
+ * add_id is added to all moved ids
+ * (for sequential ids, this would be this->ntotal) */
+ virtual void merge_from(IndexBinary& otherIndex, idx_t add_id = 0);
+
+ /** check that the two indexes are compatible (ie, they are
+ * trained in the same way and have the same
+ * parameters). Otherwise throw. */
+ virtual void check_compatible_for_merge(
+ const IndexBinary& otherIndex) const;
+
+ /** size of the produced codes in bytes */
+ virtual size_t sa_code_size() const;
+
+ /** Same as add_with_ids for IndexBinary. */
+ virtual void add_sa_codes(idx_t n, const uint8_t* codes, const idx_t* xids);
+};
+
+} // namespace faiss
+
+#endif // FAISS_INDEX_BINARY_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFlat.cpp
new file mode 100644
index 0000000..bbb51d7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFlat.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexBinaryFlat.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/hamming.h>
+#include <cstring>
+
+namespace faiss {
+
+IndexBinaryFlat::IndexBinaryFlat(idx_t d) : IndexBinary(d) {}
+
+void IndexBinaryFlat::add(idx_t n, const uint8_t* x) {
+ xb.insert(xb.end(), x, x + n * code_size);
+ ntotal += n;
+}
+
+void IndexBinaryFlat::reset() {
+ xb.clear();
+ ntotal = 0;
+}
+
+void IndexBinaryFlat::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ // Extract IDSelector from params if present
+ const IDSelector* sel = params ? params->sel : nullptr;
+ FAISS_THROW_IF_NOT(k > 0);
+
+ const idx_t block_size = query_batch_size;
+ for (idx_t s = 0; s < n; s += block_size) {
+ idx_t nn = block_size;
+ if (s + block_size > n) {
+ nn = n - s;
+ }
+
+ if (use_heap) {
+ // We see the distances and labels as heaps.
+ int_maxheap_array_t res = {
+ size_t(nn), size_t(k), labels + s * k, distances + s * k};
+
+ hammings_knn_hc(
+ &res,
+ x + s * code_size,
+ xb.data(),
+ ntotal,
+ code_size,
+ /* ordered = */ true,
+ approx_topk_mode,
+ sel);
+ } else {
+ hammings_knn_mc(
+ x + s * code_size,
+ xb.data(),
+ nn,
+ ntotal,
+ k,
+ code_size,
+ distances + s * k,
+ labels + s * k,
+ sel);
+ }
+ }
+}
+
+size_t IndexBinaryFlat::remove_ids(const IDSelector& sel) {
+ idx_t j = 0;
+ for (idx_t i = 0; i < ntotal; i++) {
+ if (sel.is_member(i)) {
+ // should be removed
+ } else {
+ if (i > j) {
+ memmove(&xb[code_size * j],
+ &xb[code_size * i],
+ sizeof(xb[0]) * code_size);
+ }
+ j++;
+ }
+ }
+ long nremove = ntotal - j;
+ if (nremove > 0) {
+ ntotal = j;
+ xb.resize(ntotal * code_size);
+ }
+ return nremove;
+}
+
+void IndexBinaryFlat::reconstruct(idx_t key, uint8_t* recons) const {
+ memcpy(recons, &(xb[code_size * key]), sizeof(*recons) * code_size);
+}
+
+void IndexBinaryFlat::range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ const IDSelector* sel = params ? params->sel : nullptr;
+ hamming_range_search(
+ x, xb.data(), n, ntotal, radius, code_size, result, sel);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFlat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFlat.h
new file mode 100644
index 0000000..0ce43f3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFlat.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef INDEX_BINARY_FLAT_H
+#define INDEX_BINARY_FLAT_H
+
+#include <vector>
+
+#include <faiss/IndexBinary.h>
+
+#include <faiss/impl/maybe_owned_vector.h>
+#include <faiss/utils/approx_topk/mode.h>
+
+namespace faiss {
+
+/** Index that stores the full vectors and performs exhaustive search. */
+struct IndexBinaryFlat : IndexBinary {
+ /// database vectors, size ntotal * d / 8
+ MaybeOwnedVector<uint8_t> xb;
+
+ /** Select between using a heap or counting to select the k smallest values
+ * when scanning inverted lists.
+ */
+ bool use_heap = true;
+
+ size_t query_batch_size = 32;
+
+ ApproxTopK_mode_t approx_topk_mode = ApproxTopK_mode_t::EXACT_TOPK;
+
+ explicit IndexBinaryFlat(idx_t d);
+
+ void add(idx_t n, const uint8_t* x) override;
+
+ void reset() override;
+
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, uint8_t* recons) const override;
+
+ /** Remove some ids. Note that because of the indexing structure,
+ * the semantics of this operation are different from the usual ones:
+ * the new ids are shifted. */
+ size_t remove_ids(const IDSelector& sel) override;
+
+ IndexBinaryFlat() {}
+};
+
+} // namespace faiss
+
+#endif // INDEX_BINARY_FLAT_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFromFloat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFromFloat.cpp
new file mode 100644
index 0000000..efc68ff
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFromFloat.cpp
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexBinaryFromFloat.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/utils.h>
+#include <algorithm>
+#include <memory>
+
+namespace faiss {
+
+IndexBinaryFromFloat::IndexBinaryFromFloat() = default;
+
+IndexBinaryFromFloat::IndexBinaryFromFloat(Index* index)
+ : IndexBinary(index->d), index(index), own_fields(false) {
+ is_trained = index->is_trained;
+ ntotal = index->ntotal;
+}
+
+IndexBinaryFromFloat::~IndexBinaryFromFloat() {
+ if (own_fields) {
+ delete index;
+ }
+}
+
+void IndexBinaryFromFloat::add(idx_t n, const uint8_t* x) {
+ constexpr idx_t bs = 32768;
+ std::unique_ptr<float[]> xf(new float[bs * d]);
+
+ for (idx_t b = 0; b < n; b += bs) {
+ idx_t bn = std::min(bs, n - b);
+ binary_to_real(bn * d, x + b * code_size, xf.get());
+
+ index->add(bn, xf.get());
+ }
+ ntotal = index->ntotal;
+}
+
+void IndexBinaryFromFloat::reset() {
+ index->reset();
+ ntotal = index->ntotal;
+}
+
+void IndexBinaryFromFloat::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ constexpr idx_t bs = 32768;
+ std::unique_ptr<float[]> xf(new float[bs * d]);
+ std::unique_ptr<float[]> df(new float[bs * k]);
+
+ for (idx_t b = 0; b < n; b += bs) {
+ idx_t bn = std::min(bs, n - b);
+ binary_to_real(bn * d, x + b * code_size, xf.get());
+
+ index->search(bn, xf.get(), k, df.get(), labels + b * k);
+ for (int i = 0; i < bn * k; ++i) {
+ distances[b * k + i] = int32_t(std::round(df[i] / 4.0));
+ }
+ }
+}
+
+void IndexBinaryFromFloat::train(idx_t n, const uint8_t* x) {
+ std::unique_ptr<float[]> xf(new float[n * d]);
+ binary_to_real(n * d, x, xf.get());
+
+ index->train(n, xf.get());
+ is_trained = true;
+ ntotal = index->ntotal;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFromFloat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFromFloat.h
new file mode 100644
index 0000000..49e1962
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryFromFloat.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_BINARY_FROM_FLOAT_H
+#define FAISS_INDEX_BINARY_FROM_FLOAT_H
+
+#include <faiss/IndexBinary.h>
+
+namespace faiss {
+
+struct Index;
+
+/** IndexBinary backed by a float Index.
+ *
+ * Supports adding vertices and searching them.
+ *
+ * All queries are symmetric because there is no distinction between codes and
+ * vectors.
+ */
+struct IndexBinaryFromFloat : IndexBinary {
+ Index* index = nullptr;
+
+ bool own_fields = false; ///< Whether object owns the index pointer.
+
+ IndexBinaryFromFloat();
+
+ explicit IndexBinaryFromFloat(Index* index);
+
+ ~IndexBinaryFromFloat();
+
+ void add(idx_t n, const uint8_t* x) override;
+
+ void reset() override;
+
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void train(idx_t n, const uint8_t* x) override;
+};
+
+} // namespace faiss
+
+#endif // FAISS_INDEX_BINARY_FROM_FLOAT_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHNSW.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHNSW.cpp
new file mode 100644
index 0000000..119d6c0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHNSW.cpp
@@ -0,0 +1,299 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexBinaryHNSW.h>
+
+#include <omp.h>
+#include <cassert>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+
+#include <cstdint>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/random.h>
+
+namespace faiss {
+
+/**************************************************************
+ * add / search blocks of descriptors
+ **************************************************************/
+
+namespace {
+
+void hnsw_add_vertices(
+ IndexBinaryHNSW& index_hnsw,
+ size_t n0,
+ size_t n,
+ const uint8_t* x,
+ bool verbose,
+ bool preset_levels = false) {
+ HNSW& hnsw = index_hnsw.hnsw;
+ size_t ntotal = n0 + n;
+ double t0 = getmillisecs();
+ if (verbose) {
+ printf("hnsw_add_vertices: adding %zd elements on top of %zd "
+ "(preset_levels=%d)\n",
+ n,
+ n0,
+ int(preset_levels));
+ }
+
+ int max_level = hnsw.prepare_level_tab(n, preset_levels);
+
+ if (verbose) {
+ printf(" max_level = %d\n", max_level);
+ }
+
+ std::vector<omp_lock_t> locks(ntotal);
+ for (int i = 0; i < ntotal; i++) {
+ omp_init_lock(&locks[i]);
+ }
+
+ // add vectors from highest to lowest level
+ std::vector<int> hist;
+ std::vector<int> order(n);
+
+ { // make buckets with vectors of the same level
+
+ // build histogram
+ for (int i = 0; i < n; i++) {
+ HNSW::storage_idx_t pt_id = i + n0;
+ int pt_level = hnsw.levels[pt_id] - 1;
+ while (pt_level >= hist.size()) {
+ hist.push_back(0);
+ }
+ hist[pt_level]++;
+ }
+
+ // accumulate
+ std::vector<int> offsets(hist.size() + 1, 0);
+ for (int i = 0; i < hist.size() - 1; i++) {
+ offsets[i + 1] = offsets[i] + hist[i];
+ }
+
+ // bucket sort
+ for (int i = 0; i < n; i++) {
+ HNSW::storage_idx_t pt_id = i + n0;
+ int pt_level = hnsw.levels[pt_id] - 1;
+ order[offsets[pt_level]++] = pt_id;
+ }
+ }
+
+ { // perform add
+ RandomGenerator rng2(789);
+
+ int i1 = n;
+
+ for (int pt_level = hist.size() - 1; pt_level >= 0; pt_level--) {
+ int i0 = i1 - hist[pt_level];
+
+ if (verbose) {
+ printf("Adding %d elements at level %d\n", i1 - i0, pt_level);
+ }
+
+ // random permutation to get rid of dataset order bias
+ for (int j = i0; j < i1; j++) {
+ std::swap(order[j], order[j + rng2.rand_int(i1 - j)]);
+ }
+
+#pragma omp parallel
+ {
+ VisitedTable vt(ntotal);
+
+ std::unique_ptr<DistanceComputer> dis(
+ index_hnsw.get_distance_computer());
+ int prev_display =
+ verbose && omp_get_thread_num() == 0 ? 0 : -1;
+
+#pragma omp for schedule(dynamic)
+ for (int i = i0; i < i1; i++) {
+ HNSW::storage_idx_t pt_id = order[i];
+ dis->set_query(
+ (float*)(x + (pt_id - n0) * index_hnsw.code_size));
+
+ hnsw.add_with_locks(*dis, pt_level, pt_id, locks, vt);
+
+ if (prev_display >= 0 && i - i0 > prev_display + 10000) {
+ prev_display = i - i0;
+ printf(" %d / %d\r", i - i0, i1 - i0);
+ fflush(stdout);
+ }
+ }
+ }
+ i1 = i0;
+ }
+ FAISS_ASSERT(i1 == 0);
+ }
+ if (verbose) {
+ printf("Done in %.3f ms\n", getmillisecs() - t0);
+ }
+
+ for (int i = 0; i < ntotal; i++)
+ omp_destroy_lock(&locks[i]);
+}
+
+} // anonymous namespace
+
+/**************************************************************
+ * IndexBinaryHNSW implementation
+ **************************************************************/
+
+IndexBinaryHNSW::IndexBinaryHNSW() {
+ is_trained = true;
+}
+
+IndexBinaryHNSW::IndexBinaryHNSW(int d, int M)
+ : IndexBinary(d),
+ hnsw(M),
+ own_fields(true),
+ storage(new IndexBinaryFlat(d)) {
+ is_trained = true;
+}
+
+IndexBinaryHNSW::IndexBinaryHNSW(IndexBinary* storage, int M)
+ : IndexBinary(storage->d),
+ hnsw(M),
+ own_fields(false),
+ storage(storage) {
+ is_trained = true;
+}
+
+IndexBinaryHNSW::~IndexBinaryHNSW() {
+ if (own_fields) {
+ delete storage;
+ }
+}
+
+void IndexBinaryHNSW::train(idx_t n, const uint8_t* x) {
+ // hnsw structure does not require training
+ storage->train(n, x);
+ is_trained = true;
+}
+
+void IndexBinaryHNSW::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ // we use the buffer for distances as float but convert them back
+ // to int in the end
+ float* distances_f = (float*)distances;
+
+ using RH = HeapBlockResultHandler<HNSW::C>;
+ RH bres(n, distances_f, labels, k);
+
+#pragma omp parallel
+ {
+ VisitedTable vt(ntotal);
+ std::unique_ptr<DistanceComputer> dis(get_distance_computer());
+ RH::SingleResultHandler res(bres);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ res.begin(i);
+ dis->set_query((float*)(x + i * code_size));
+ hnsw.search(*dis, res, vt);
+ res.end();
+ }
+ }
+
+#pragma omp parallel for
+ for (int i = 0; i < n * k; ++i) {
+ distances[i] = std::round(distances_f[i]);
+ }
+}
+
+void IndexBinaryHNSW::add(idx_t n, const uint8_t* x) {
+ FAISS_THROW_IF_NOT(is_trained);
+ int n0 = ntotal;
+ storage->add(n, x);
+ ntotal = storage->ntotal;
+
+ hnsw_add_vertices(*this, n0, n, x, verbose, hnsw.levels.size() == ntotal);
+}
+
+void IndexBinaryHNSW::reset() {
+ hnsw.reset();
+ storage->reset();
+ ntotal = 0;
+}
+
+void IndexBinaryHNSW::reconstruct(idx_t key, uint8_t* recons) const {
+ storage->reconstruct(key, recons);
+}
+
+namespace {
+
+template <class HammingComputer>
+struct FlatHammingDis : DistanceComputer {
+ const int code_size;
+ const uint8_t* b;
+ size_t ndis;
+ HammingComputer hc;
+
+ float operator()(idx_t i) override {
+ ndis++;
+ return hc.hamming(b + i * code_size);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return HammingComputerDefault(b + j * code_size, code_size)
+ .hamming(b + i * code_size);
+ }
+
+ explicit FlatHammingDis(const IndexBinaryFlat& storage)
+ : code_size(storage.code_size),
+ b(storage.xb.data()),
+ ndis(0),
+ hc() {}
+
+ // NOTE: Pointers are cast from float in order to reuse the floating-point
+ // DistanceComputer.
+ void set_query(const float* x) override {
+ hc.set((uint8_t*)x, code_size);
+ }
+
+ ~FlatHammingDis() override {
+#pragma omp critical
+ { hnsw_stats.ndis += ndis; }
+ }
+};
+
+struct BuildDistanceComputer {
+ using T = DistanceComputer*;
+ template <class HammingComputer>
+ DistanceComputer* f(IndexBinaryFlat* flat_storage) {
+ return new FlatHammingDis<HammingComputer>(*flat_storage);
+ }
+};
+
+} // namespace
+
+DistanceComputer* IndexBinaryHNSW::get_distance_computer() const {
+ IndexBinaryFlat* flat_storage = dynamic_cast<IndexBinaryFlat*>(storage);
+ FAISS_ASSERT(flat_storage != nullptr);
+ BuildDistanceComputer bd;
+ return dispatch_HammingComputer(code_size, bd, flat_storage);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHNSW.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHNSW.h
new file mode 100644
index 0000000..a40b16e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHNSW.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/impl/HNSW.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/** The HNSW index is a normal random-access index with a HNSW
+ * link structure built on top */
+
+struct IndexBinaryHNSW : IndexBinary {
+ typedef HNSW::storage_idx_t storage_idx_t;
+
+ // the link structure
+ HNSW hnsw;
+
+ // the sequential storage
+ bool own_fields;
+ IndexBinary* storage;
+
+ explicit IndexBinaryHNSW();
+ explicit IndexBinaryHNSW(int d, int M = 32);
+ explicit IndexBinaryHNSW(IndexBinary* storage, int M = 32);
+
+ ~IndexBinaryHNSW() override;
+
+ DistanceComputer* get_distance_computer() const;
+
+ void add(idx_t n, const uint8_t* x) override;
+
+ /// Trains the storage if needed
+ void train(idx_t n, const uint8_t* x) override;
+
+ /// entry point for search
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, uint8_t* recons) const override;
+
+ void reset() override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHash.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHash.cpp
new file mode 100644
index 0000000..9cbb463
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHash.cpp
@@ -0,0 +1,481 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexBinaryHash.h>
+
+#include <cinttypes>
+#include <cstdio>
+#include <memory>
+#include <unordered_set>
+
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+void IndexBinaryHash::InvertedList::add(
+ idx_t id,
+ size_t code_size,
+ const uint8_t* code) {
+ ids.push_back(id);
+ vecs.insert(vecs.end(), code, code + code_size);
+}
+
+IndexBinaryHash::IndexBinaryHash(int d, int b)
+ : IndexBinary(d), b(b), nflip(0) {
+ is_trained = true;
+}
+
+IndexBinaryHash::IndexBinaryHash() : b(0), nflip(0) {
+ is_trained = true;
+}
+
+void IndexBinaryHash::reset() {
+ invlists.clear();
+ ntotal = 0;
+}
+
+void IndexBinaryHash::add(idx_t n, const uint8_t* x) {
+ add_with_ids(n, x, nullptr);
+}
+
+void IndexBinaryHash::add_with_ids(
+ idx_t n,
+ const uint8_t* x,
+ const idx_t* xids) {
+ uint64_t mask = ((uint64_t)1 << b) - 1;
+ // simplistic add function. Cannot really be parallelized.
+
+ for (idx_t i = 0; i < n; i++) {
+ idx_t id = xids ? xids[i] : ntotal + i;
+ const uint8_t* xi = x + i * code_size;
+ idx_t hash = *((uint64_t*)xi) & mask;
+ invlists[hash].add(id, code_size, xi);
+ }
+ ntotal += n;
+}
+
+namespace {
+
+/** Enumerate all bit vectors of size nbit with up to maxflip 1s
+ * test in P127257851 P127258235
+ */
+struct FlipEnumerator {
+ int nbit, nflip, maxflip;
+ uint64_t mask, x;
+
+ FlipEnumerator(int nbit, int maxflip) : nbit(nbit), maxflip(maxflip) {
+ nflip = 0;
+ mask = 0;
+ x = 0;
+ }
+
+ bool next() {
+ if (x == mask) {
+ if (nflip == maxflip) {
+ return false;
+ }
+ // increase Hamming radius
+ nflip++;
+ mask = (((uint64_t)1 << nflip) - 1);
+ x = mask << (nbit - nflip);
+ return true;
+ }
+
+ int i = __builtin_ctzll(x);
+
+ if (i > 0) {
+ x ^= (uint64_t)3 << (i - 1);
+ } else {
+ // nb of LSB 1s
+ int n1 = __builtin_ctzll(~x);
+ // clear them
+ x &= ((uint64_t)(-1) << n1);
+ int n2 = __builtin_ctzll(x);
+ x ^= (((uint64_t)1 << (n1 + 2)) - 1) << (n2 - n1 - 1);
+ }
+ return true;
+ }
+};
+
+struct RangeSearchResults {
+ int radius;
+ RangeQueryResult& qres;
+
+ inline void add(float dis, idx_t id) {
+ if (dis < radius) {
+ qres.add(dis, id);
+ }
+ }
+};
+
+struct KnnSearchResults {
+ // heap params
+ idx_t k;
+ int32_t* heap_sim;
+ idx_t* heap_ids;
+
+ using C = CMax<int, idx_t>;
+
+ inline void add(float dis, idx_t id) {
+ if (dis < heap_sim[0]) {
+ heap_replace_top<C>(k, heap_sim, heap_ids, dis, id);
+ }
+ }
+};
+
+template <class HammingComputer, class SearchResults>
+void search_single_query_template(
+ const IndexBinaryHash& index,
+ const uint8_t* q,
+ SearchResults& res,
+ size_t& n0,
+ size_t& nlist,
+ size_t& ndis) {
+ size_t code_size = index.code_size;
+ uint64_t mask = ((uint64_t)1 << index.b) - 1;
+ uint64_t qhash = *((uint64_t*)q) & mask;
+ HammingComputer hc(q, code_size);
+ FlipEnumerator fe(index.b, index.nflip);
+
+ // loop over neighbors that are at most at nflip bits
+ do {
+ uint64_t hash = qhash ^ fe.x;
+ auto it = index.invlists.find(hash);
+
+ if (it == index.invlists.end()) {
+ continue;
+ }
+
+ const IndexBinaryHash::InvertedList& il = it->second;
+
+ size_t nv = il.ids.size();
+
+ if (nv == 0) {
+ n0++;
+ } else {
+ const uint8_t* codes = il.vecs.data();
+ for (size_t i = 0; i < nv; i++) {
+ int dis = hc.hamming(codes);
+ res.add(dis, il.ids[i]);
+ codes += code_size;
+ }
+ ndis += nv;
+ nlist++;
+ }
+ } while (fe.next());
+}
+
+struct Run_search_single_query {
+ using T = void;
+ template <class HammingComputer, class... Types>
+ T f(Types... args) {
+ search_single_query_template<HammingComputer>(args...);
+ }
+};
+
+template <class SearchResults>
+void search_single_query(
+ const IndexBinaryHash& index,
+ const uint8_t* q,
+ SearchResults& res,
+ size_t& n0,
+ size_t& nlist,
+ size_t& ndis) {
+ Run_search_single_query r;
+ dispatch_HammingComputer(
+ index.code_size, r, index, q, res, n0, nlist, ndis);
+}
+
+} // anonymous namespace
+
+void IndexBinaryHash::range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ size_t nlist = 0, ndis = 0, n0 = 0;
+
+#pragma omp parallel if (n > 100) reduction(+ : ndis, n0, nlist)
+ {
+ RangeSearchPartialResult pres(result);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) { // loop queries
+ RangeQueryResult& qres = pres.new_result(i);
+ RangeSearchResults res = {radius, qres};
+ const uint8_t* q = x + i * code_size;
+
+ search_single_query(*this, q, res, n0, nlist, ndis);
+ }
+ pres.finalize();
+ }
+ indexBinaryHash_stats.nq += n;
+ indexBinaryHash_stats.n0 += n0;
+ indexBinaryHash_stats.nlist += nlist;
+ indexBinaryHash_stats.ndis += ndis;
+}
+
+void IndexBinaryHash::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ using HeapForL2 = CMax<int32_t, idx_t>;
+ size_t nlist = 0, ndis = 0, n0 = 0;
+
+#pragma omp parallel for if (n > 100) reduction(+ : nlist, ndis, n0)
+ for (idx_t i = 0; i < n; i++) {
+ int32_t* simi = distances + k * i;
+ idx_t* idxi = labels + k * i;
+
+ heap_heapify<HeapForL2>(k, simi, idxi);
+ KnnSearchResults res = {k, simi, idxi};
+ const uint8_t* q = x + i * code_size;
+
+ search_single_query(*this, q, res, n0, nlist, ndis);
+
+ heap_reorder<HeapForL2>(k, simi, idxi);
+ }
+ indexBinaryHash_stats.nq += n;
+ indexBinaryHash_stats.n0 += n0;
+ indexBinaryHash_stats.nlist += nlist;
+ indexBinaryHash_stats.ndis += ndis;
+}
+
+size_t IndexBinaryHash::hashtable_size() const {
+ return invlists.size();
+}
+
+void IndexBinaryHash::display() const {
+ for (auto it = invlists.begin(); it != invlists.end(); ++it) {
+ printf("%" PRId64 ": [", it->first);
+ const std::vector<idx_t>& v = it->second.ids;
+ for (auto x : v) {
+ printf("%" PRId64 " ", x);
+ }
+ printf("]\n");
+ }
+}
+
+void IndexBinaryHashStats::reset() {
+ memset((void*)this, 0, sizeof(*this));
+}
+
+IndexBinaryHashStats indexBinaryHash_stats;
+
+/*******************************************************
+ * IndexBinaryMultiHash implementation
+ ******************************************************/
+
+IndexBinaryMultiHash::IndexBinaryMultiHash(int d, int nhash, int b)
+ : IndexBinary(d),
+ storage(new IndexBinaryFlat(d)),
+ own_fields(true),
+ maps(nhash),
+ nhash(nhash),
+ b(b),
+ nflip(0) {
+ FAISS_THROW_IF_NOT(nhash * b <= d);
+}
+
+IndexBinaryMultiHash::IndexBinaryMultiHash()
+ : storage(nullptr), own_fields(true), nhash(0), b(0), nflip(0) {}
+
+IndexBinaryMultiHash::~IndexBinaryMultiHash() {
+ if (own_fields) {
+ delete storage;
+ }
+}
+
+void IndexBinaryMultiHash::reset() {
+ storage->reset();
+ ntotal = 0;
+ for (auto map : maps) {
+ map.clear();
+ }
+}
+
+void IndexBinaryMultiHash::add(idx_t n, const uint8_t* x) {
+ storage->add(n, x);
+ // populate maps
+ uint64_t mask = ((uint64_t)1 << b) - 1;
+
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* xi = x + i * code_size;
+ int ho = 0;
+ for (int h = 0; h < nhash; h++) {
+ uint64_t hash = *(uint64_t*)(xi + (ho >> 3)) >> (ho & 7);
+ hash &= mask;
+ maps[h][hash].push_back(i + ntotal);
+ ho += b;
+ }
+ }
+ ntotal += n;
+}
+
+namespace {
+
+template <class HammingComputer, class SearchResults>
+static void verify_shortlist(
+ const IndexBinaryFlat* index,
+ const uint8_t* q,
+ const std::unordered_set<idx_t>& shortlist,
+ SearchResults& res) {
+ size_t code_size = index->code_size;
+
+ HammingComputer hc(q, code_size);
+ const uint8_t* codes = index->xb.data();
+
+ for (auto i : shortlist) {
+ int dis = hc.hamming(codes + i * code_size);
+ res.add(dis, i);
+ }
+}
+
+struct Run_verify_shortlist {
+ using T = void;
+ template <class HammingComputer, class... Types>
+ void f(Types... args) {
+ verify_shortlist<HammingComputer>(args...);
+ }
+};
+
+template <class SearchResults>
+void search_1_query_multihash(
+ const IndexBinaryMultiHash& index,
+ const uint8_t* xi,
+ SearchResults& res,
+ size_t& n0,
+ size_t& nlist,
+ size_t& ndis) {
+ std::unordered_set<idx_t> shortlist;
+ int b = index.b;
+ uint64_t mask = ((uint64_t)1 << b) - 1;
+
+ int ho = 0;
+ for (int h = 0; h < index.nhash; h++) {
+ uint64_t qhash = *(uint64_t*)(xi + (ho >> 3)) >> (ho & 7);
+ qhash &= mask;
+ const IndexBinaryMultiHash::Map& map = index.maps[h];
+
+ FlipEnumerator fe(index.b, index.nflip);
+ // loop over neighbors that are at most at nflip bits
+ do {
+ uint64_t hash = qhash ^ fe.x;
+ auto it = map.find(hash);
+
+ if (it != map.end()) {
+ const std::vector<idx_t>& v = it->second;
+ for (auto i : v) {
+ shortlist.insert(i);
+ }
+ nlist++;
+ } else {
+ n0++;
+ }
+ } while (fe.next());
+
+ ho += b;
+ }
+ ndis += shortlist.size();
+
+ // verify shortlist
+ Run_verify_shortlist r;
+ dispatch_HammingComputer(
+ index.code_size, r, index.storage, xi, shortlist, res);
+}
+
+} // anonymous namespace
+
+void IndexBinaryMultiHash::range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ size_t nlist = 0, ndis = 0, n0 = 0;
+
+#pragma omp parallel if (n > 100) reduction(+ : ndis, n0, nlist)
+ {
+ RangeSearchPartialResult pres(result);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) { // loop queries
+ RangeQueryResult& qres = pres.new_result(i);
+ RangeSearchResults res = {radius, qres};
+ const uint8_t* q = x + i * code_size;
+
+ search_1_query_multihash(*this, q, res, n0, nlist, ndis);
+ }
+ pres.finalize();
+ }
+ indexBinaryHash_stats.nq += n;
+ indexBinaryHash_stats.n0 += n0;
+ indexBinaryHash_stats.nlist += nlist;
+ indexBinaryHash_stats.ndis += ndis;
+}
+
+void IndexBinaryMultiHash::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ using HeapForL2 = CMax<int32_t, idx_t>;
+ size_t nlist = 0, ndis = 0, n0 = 0;
+
+#pragma omp parallel for if (n > 100) reduction(+ : nlist, ndis, n0)
+ for (idx_t i = 0; i < n; i++) {
+ int32_t* simi = distances + k * i;
+ idx_t* idxi = labels + k * i;
+
+ heap_heapify<HeapForL2>(k, simi, idxi);
+ KnnSearchResults res = {k, simi, idxi};
+ const uint8_t* q = x + i * code_size;
+
+ search_1_query_multihash(*this, q, res, n0, nlist, ndis);
+
+ heap_reorder<HeapForL2>(k, simi, idxi);
+ }
+ indexBinaryHash_stats.nq += n;
+ indexBinaryHash_stats.n0 += n0;
+ indexBinaryHash_stats.nlist += nlist;
+ indexBinaryHash_stats.ndis += ndis;
+}
+
+size_t IndexBinaryMultiHash::hashtable_size() const {
+ size_t tot = 0;
+ for (auto map : maps) {
+ tot += map.size();
+ }
+
+ return tot;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHash.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHash.h
new file mode 100644
index 0000000..43b10cf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryHash.h
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_BINARY_HASH_H
+#define FAISS_BINARY_HASH_H
+
+#include <unordered_map>
+#include <vector>
+
+#include <faiss/IndexBinary.h>
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+struct RangeSearchResult;
+
+/** just uses the b first bits as a hash value */
+struct IndexBinaryHash : IndexBinary {
+ struct InvertedList {
+ std::vector<idx_t> ids;
+ std::vector<uint8_t> vecs;
+
+ void add(idx_t id, size_t code_size, const uint8_t* code);
+ };
+
+ using InvertedListMap = std::unordered_map<idx_t, InvertedList>;
+ InvertedListMap invlists;
+
+ int b, nflip;
+
+ IndexBinaryHash(int d, int b);
+
+ IndexBinaryHash();
+
+ void reset() override;
+
+ void add(idx_t n, const uint8_t* x) override;
+
+ void add_with_ids(idx_t n, const uint8_t* x, const idx_t* xids) override;
+
+ void range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void display() const;
+ size_t hashtable_size() const;
+};
+
+struct IndexBinaryHashStats {
+ size_t nq; // nb of queries run
+ size_t n0; // nb of empty lists
+ size_t nlist; // nb of non-empty inverted lists scanned
+ size_t ndis; // nb of distancs computed
+
+ IndexBinaryHashStats() {
+ reset();
+ }
+ void reset();
+};
+
+FAISS_API extern IndexBinaryHashStats indexBinaryHash_stats;
+
+/** just uses the b first bits as a hash value */
+struct IndexBinaryMultiHash : IndexBinary {
+ // where the vectors are actually stored
+ IndexBinaryFlat* storage;
+ bool own_fields;
+
+ // maps hash values to the ids that hash to them
+ using Map = std::unordered_map<idx_t, std::vector<idx_t>>;
+
+ // the different hashes, size nhash
+ std::vector<Map> maps;
+
+ int nhash; ///< nb of hash maps
+ int b; ///< nb bits per hash map
+ int nflip; ///< nb bit flips to use at search time
+
+ IndexBinaryMultiHash(int d, int nhash, int b);
+
+ IndexBinaryMultiHash();
+
+ ~IndexBinaryMultiHash();
+
+ void reset() override;
+
+ void add(idx_t n, const uint8_t* x) override;
+
+ void range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ size_t hashtable_size() const;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryIVF.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryIVF.cpp
new file mode 100644
index 0000000..69c37b3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryIVF.cpp
@@ -0,0 +1,904 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexBinaryIVF.h>
+
+#include <omp.h>
+#include <cinttypes>
+#include <cstdio>
+
+#include <algorithm>
+#include <memory>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/sorting.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+IndexBinaryIVF::IndexBinaryIVF(IndexBinary* quantizer, size_t d, size_t nlist)
+ : IndexBinary(d),
+ invlists(new ArrayInvertedLists(nlist, code_size)),
+ quantizer(quantizer),
+ nlist(nlist) {
+ FAISS_THROW_IF_NOT(d == quantizer->d);
+ is_trained = quantizer->is_trained && (quantizer->ntotal == nlist);
+ cp.niter = 10;
+}
+
+IndexBinaryIVF::IndexBinaryIVF() = default;
+
+void IndexBinaryIVF::add(idx_t n, const uint8_t* x) {
+ add_with_ids(n, x, nullptr);
+}
+
+void IndexBinaryIVF::add_with_ids(
+ idx_t n,
+ const uint8_t* x,
+ const idx_t* xids) {
+ add_core(n, x, xids, nullptr);
+}
+
+void IndexBinaryIVF::add_core(
+ idx_t n,
+ const uint8_t* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx) {
+ FAISS_THROW_IF_NOT(is_trained);
+ assert(invlists);
+ direct_map.check_can_add(xids);
+
+ const idx_t* idx;
+
+ std::unique_ptr<idx_t[]> scoped_idx;
+
+ if (precomputed_idx) {
+ idx = precomputed_idx;
+ } else {
+ scoped_idx.reset(new idx_t[n]);
+ quantizer->assign(n, x, scoped_idx.get());
+ idx = scoped_idx.get();
+ }
+
+ idx_t n_add = 0;
+ for (size_t i = 0; i < n; i++) {
+ idx_t id = xids ? xids[i] : ntotal + i;
+ idx_t list_no = idx[i];
+
+ if (list_no < 0) {
+ direct_map.add_single_id(id, -1, 0);
+ } else {
+ const uint8_t* xi = x + i * code_size;
+ size_t offset = invlists->add_entry(list_no, id, xi);
+
+ direct_map.add_single_id(id, list_no, offset);
+ }
+
+ n_add++;
+ }
+ if (verbose) {
+ printf("IndexBinaryIVF::add_with_ids: added "
+ "%" PRId64 " / %" PRId64 " vectors\n",
+ n_add,
+ n);
+ }
+ ntotal += n_add;
+}
+
+void IndexBinaryIVF::make_direct_map(bool b) {
+ if (b) {
+ direct_map.set_type(DirectMap::Array, invlists, ntotal);
+ } else {
+ direct_map.set_type(DirectMap::NoMap, invlists, ntotal);
+ }
+}
+
+void IndexBinaryIVF::set_direct_map_type(DirectMap::Type type) {
+ direct_map.set_type(type, invlists, ntotal);
+}
+
+void IndexBinaryIVF::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ const size_t nprobe_2 = std::min(nlist, this->nprobe);
+ std::unique_ptr<idx_t[]> idx(new idx_t[n * nprobe_2]);
+ std::unique_ptr<int32_t[]> coarse_dis(new int32_t[n * nprobe_2]);
+
+ double t0 = getmillisecs();
+ quantizer->search(n, x, nprobe_2, coarse_dis.get(), idx.get());
+ indexIVF_stats.quantization_time += getmillisecs() - t0;
+
+ t0 = getmillisecs();
+ invlists->prefetch_lists(idx.get(), n * nprobe_2);
+
+ search_preassigned(
+ n, x, k, idx.get(), coarse_dis.get(), distances, labels, false);
+ indexIVF_stats.search_time += getmillisecs() - t0;
+}
+
+void IndexBinaryIVF::reconstruct(idx_t key, uint8_t* recons) const {
+ idx_t lo = direct_map.get(key);
+ reconstruct_from_offset(lo_listno(lo), lo_offset(lo), recons);
+}
+
+void IndexBinaryIVF::reconstruct_n(idx_t i0, idx_t ni, uint8_t* recons) const {
+ FAISS_THROW_IF_NOT(ni == 0 || (i0 >= 0 && i0 + ni <= ntotal));
+
+ for (idx_t list_no = 0; list_no < nlist; list_no++) {
+ size_t list_size = invlists->list_size(list_no);
+ const idx_t* idlist = invlists->get_ids(list_no);
+
+ for (idx_t offset = 0; offset < list_size; offset++) {
+ idx_t id = idlist[offset];
+ if (!(id >= i0 && id < i0 + ni)) {
+ continue;
+ }
+
+ uint8_t* reconstructed = recons + (id - i0) * d;
+ reconstruct_from_offset(list_no, offset, reconstructed);
+ }
+ }
+}
+
+void IndexBinaryIVF::search_and_reconstruct(
+ idx_t n,
+ const uint8_t* __restrict x,
+ idx_t k,
+ int32_t* __restrict distances,
+ idx_t* __restrict labels,
+ uint8_t* __restrict recons,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ const size_t nprobe_2 = std::min(nlist, this->nprobe);
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(nprobe_2 > 0);
+
+ std::unique_ptr<idx_t[]> idx(new idx_t[n * nprobe_2]);
+ std::unique_ptr<int32_t[]> coarse_dis(new int32_t[n * nprobe_2]);
+
+ quantizer->search(n, x, nprobe_2, coarse_dis.get(), idx.get());
+
+ invlists->prefetch_lists(idx.get(), n * nprobe_2);
+
+ // search_preassigned() with `store_pairs` enabled to obtain the list_no
+ // and offset into `codes` for reconstruction
+ search_preassigned(
+ n,
+ x,
+ k,
+ idx.get(),
+ coarse_dis.get(),
+ distances,
+ labels,
+ /* store_pairs */ true);
+ for (idx_t i = 0; i < n; ++i) {
+ for (idx_t j = 0; j < k; ++j) {
+ idx_t ij = i * k + j;
+ idx_t key = labels[ij];
+ uint8_t* reconstructed = recons + ij * d;
+ if (key < 0) {
+ // Fill with NaNs
+ memset(reconstructed, -1, sizeof(*reconstructed) * d);
+ } else {
+ int list_no = key >> 32;
+ int offset = key & 0xffffffff;
+
+ // Update label to the actual id
+ labels[ij] = invlists->get_single_id(list_no, offset);
+
+ reconstruct_from_offset(list_no, offset, reconstructed);
+ }
+ }
+ }
+}
+
+void IndexBinaryIVF::reconstruct_from_offset(
+ idx_t list_no,
+ idx_t offset,
+ uint8_t* recons) const {
+ memcpy(recons, invlists->get_single_code(list_no, offset), code_size);
+}
+
+void IndexBinaryIVF::reset() {
+ direct_map.clear();
+ invlists->reset();
+ ntotal = 0;
+}
+
+size_t IndexBinaryIVF::remove_ids(const IDSelector& sel) {
+ size_t nremove = direct_map.remove_ids(sel, invlists);
+ ntotal -= nremove;
+ return nremove;
+}
+
+void IndexBinaryIVF::train(idx_t n, const uint8_t* x) {
+ if (verbose) {
+ printf("Training quantizer\n");
+ }
+
+ if (quantizer->is_trained && (quantizer->ntotal == nlist)) {
+ if (verbose) {
+ printf("IVF quantizer does not need training.\n");
+ }
+ } else {
+ if (verbose) {
+ printf("Training quantizer on %" PRId64 " vectors in %dD\n", n, d);
+ }
+
+ Clustering clus(d, nlist, cp);
+ quantizer->reset();
+
+ IndexFlatL2 index_tmp(d);
+
+ if (clustering_index && verbose) {
+ printf("using clustering_index of dimension %d to do the clustering\n",
+ clustering_index->d);
+ }
+
+ // LSH codec that is able to convert the binary vectors to floats.
+ IndexLSH codec(d, d, false, false);
+
+ clus.train_encoded(
+ n, x, &codec, clustering_index ? *clustering_index : index_tmp);
+
+ // convert clusters to binary
+ std::unique_ptr<uint8_t[]> x_b(new uint8_t[clus.k * code_size]);
+ real_to_binary(d * clus.k, clus.centroids.data(), x_b.get());
+
+ quantizer->add(clus.k, x_b.get());
+ quantizer->is_trained = true;
+ }
+
+ is_trained = true;
+}
+
+void IndexBinaryIVF::check_compatible_for_merge(
+ const IndexBinary& otherIndex) const {
+ auto other = dynamic_cast<const IndexBinaryIVF*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->d == d);
+ FAISS_THROW_IF_NOT(other->nlist == nlist);
+ FAISS_THROW_IF_NOT(other->code_size == code_size);
+ FAISS_THROW_IF_NOT_MSG(
+ direct_map.no() && other->direct_map.no(),
+ "direct map copy not implemented");
+ FAISS_THROW_IF_NOT_MSG(
+ typeid(*this) == typeid(other),
+ "can only merge indexes of the same type");
+}
+
+void IndexBinaryIVF::merge_from(IndexBinary& otherIndex, idx_t add_id) {
+ // minimal sanity checks
+ check_compatible_for_merge(otherIndex);
+ auto other = static_cast<IndexBinaryIVF*>(&otherIndex);
+ invlists->merge_from(other->invlists, add_id);
+ ntotal += other->ntotal;
+ other->ntotal = 0;
+}
+
+void IndexBinaryIVF::replace_invlists(InvertedLists* il, bool own) {
+ FAISS_THROW_IF_NOT(il->nlist == nlist && il->code_size == code_size);
+ if (own_invlists) {
+ delete invlists;
+ }
+ invlists = il;
+ own_invlists = own;
+}
+
+namespace {
+
+template <class HammingComputer>
+struct IVFBinaryScannerL2 : BinaryInvertedListScanner {
+ HammingComputer hc;
+ size_t code_size;
+ bool store_pairs;
+
+ IVFBinaryScannerL2(size_t code_size, bool store_pairs)
+ : code_size(code_size), store_pairs(store_pairs) {}
+
+ void set_query(const uint8_t* query_vector) override {
+ hc.set(query_vector, code_size);
+ }
+
+ idx_t list_no;
+ void set_list(idx_t list_no_2, uint8_t /* coarse_dis */) override {
+ this->list_no = list_no_2;
+ }
+
+ uint32_t distance_to_code(const uint8_t* code) const override {
+ return hc.hamming(code);
+ }
+
+ size_t scan_codes(
+ size_t n,
+ const uint8_t* __restrict codes,
+ const idx_t* __restrict ids,
+ int32_t* __restrict simi,
+ idx_t* __restrict idxi,
+ size_t k) const override {
+ using C = CMax<int32_t, idx_t>;
+
+ size_t nup = 0;
+ for (size_t j = 0; j < n; j++) {
+ uint32_t dis = hc.hamming(codes);
+ if (dis < simi[0]) {
+ idx_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ heap_replace_top<C>(k, simi, idxi, dis, id);
+ nup++;
+ }
+ codes += code_size;
+ }
+ return nup;
+ }
+
+ void scan_codes_range(
+ size_t n,
+ const uint8_t* __restrict codes,
+ const idx_t* __restrict ids,
+ int radius,
+ RangeQueryResult& result) const override {
+ for (size_t j = 0; j < n; j++) {
+ uint32_t dis = hc.hamming(codes);
+ if (dis < radius) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ result.add(dis, id);
+ }
+ codes += code_size;
+ }
+ }
+};
+
+void search_knn_hamming_heap(
+ const IndexBinaryIVF* ivf,
+ size_t n,
+ const uint8_t* __restrict x,
+ idx_t k,
+ const idx_t* __restrict keys,
+ const int32_t* __restrict coarse_dis,
+ int32_t* __restrict distances,
+ idx_t* __restrict labels,
+ bool store_pairs,
+ const IVFSearchParameters* params) {
+ idx_t nprobe = params ? params->nprobe : ivf->nprobe;
+ nprobe = std::min((idx_t)ivf->nlist, nprobe);
+ idx_t max_codes = params ? params->max_codes : ivf->max_codes;
+ MetricType metric_type = ivf->metric_type;
+
+ // almost verbatim copy from IndexIVF::search_preassigned
+
+ size_t nlistv = 0, ndis = 0, nheap = 0;
+ using HeapForIP = CMin<int32_t, idx_t>;
+ using HeapForL2 = CMax<int32_t, idx_t>;
+
+#pragma omp parallel if (n > 1) reduction(+ : nlistv, ndis, nheap)
+ {
+ std::unique_ptr<BinaryInvertedListScanner> scanner(
+ ivf->get_InvertedListScanner(store_pairs));
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* xi = x + i * ivf->code_size;
+ scanner->set_query(xi);
+
+ const idx_t* keysi = keys + i * nprobe;
+ int32_t* simi = distances + k * i;
+ idx_t* idxi = labels + k * i;
+
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ heap_heapify<HeapForIP>(k, simi, idxi);
+ } else {
+ heap_heapify<HeapForL2>(k, simi, idxi);
+ }
+
+ size_t nscan = 0;
+
+ for (size_t ik = 0; ik < nprobe; ik++) {
+ idx_t key = keysi[ik]; /* select the list */
+ if (key < 0) {
+ // not enough centroids for multiprobe
+ continue;
+ }
+ FAISS_THROW_IF_NOT_FMT(
+ key < (idx_t)ivf->nlist,
+ "Invalid key=%" PRId64 " at ik=%zd nlist=%zd\n",
+ key,
+ ik,
+ ivf->nlist);
+
+ scanner->set_list(key, coarse_dis[i * nprobe + ik]);
+
+ nlistv++;
+
+ size_t list_size = ivf->invlists->list_size(key);
+ InvertedLists::ScopedCodes scodes(ivf->invlists, key);
+ std::unique_ptr<InvertedLists::ScopedIds> sids;
+ const idx_t* ids = nullptr;
+
+ if (!store_pairs) {
+ sids = std::make_unique<InvertedLists::ScopedIds>(
+ ivf->invlists, key);
+ ids = sids->get();
+ }
+
+ nheap += scanner->scan_codes(
+ list_size, scodes.get(), ids, simi, idxi, k);
+
+ nscan += list_size;
+ if (max_codes && nscan >= max_codes)
+ break;
+ }
+
+ ndis += nscan;
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ heap_reorder<HeapForIP>(k, simi, idxi);
+ } else {
+ heap_reorder<HeapForL2>(k, simi, idxi);
+ }
+
+ } // parallel for
+ } // parallel
+
+ indexIVF_stats.nq += n;
+ indexIVF_stats.nlist += nlistv;
+ indexIVF_stats.ndis += ndis;
+ indexIVF_stats.nheap_updates += nheap;
+}
+
+template <class HammingComputer, bool store_pairs>
+void search_knn_hamming_count(
+ const IndexBinaryIVF* ivf,
+ size_t nx,
+ const uint8_t* __restrict x,
+ const idx_t* __restrict keys,
+ int k,
+ int32_t* __restrict distances,
+ idx_t* __restrict labels,
+ const IVFSearchParameters* params) {
+ const int nBuckets = ivf->d + 1;
+ std::vector<int> all_counters(nx * nBuckets, 0);
+ std::unique_ptr<idx_t[]> all_ids_per_dis(new idx_t[nx * nBuckets * k]);
+
+ idx_t nprobe = params ? params->nprobe : ivf->nprobe;
+ nprobe = std::min((idx_t)ivf->nlist, nprobe);
+ idx_t max_codes = params ? params->max_codes : ivf->max_codes;
+
+ std::vector<HCounterState<HammingComputer>> cs;
+ for (size_t i = 0; i < nx; ++i) {
+ cs.push_back(HCounterState<HammingComputer>(
+ all_counters.data() + i * nBuckets,
+ all_ids_per_dis.get() + i * nBuckets * k,
+ x + i * ivf->code_size,
+ ivf->d,
+ k));
+ }
+
+ size_t nlistv = 0, ndis = 0;
+
+#pragma omp parallel for reduction(+ : nlistv, ndis)
+ for (int64_t i = 0; i < nx; i++) {
+ const idx_t* keysi = keys + i * nprobe;
+ HCounterState<HammingComputer>& csi = cs[i];
+
+ size_t nscan = 0;
+
+ for (size_t ik = 0; ik < nprobe; ik++) {
+ idx_t key = keysi[ik]; /* select the list */
+ if (key < 0) {
+ // not enough centroids for multiprobe
+ continue;
+ }
+ FAISS_THROW_IF_NOT_FMT(
+ key < (idx_t)ivf->nlist,
+ "Invalid key=%" PRId64 " at ik=%zd nlist=%zd\n",
+ key,
+ ik,
+ ivf->nlist);
+
+ nlistv++;
+ size_t list_size = ivf->invlists->list_size(key);
+ InvertedLists::ScopedCodes scodes(ivf->invlists, key);
+ const uint8_t* list_vecs = scodes.get();
+ const idx_t* ids =
+ store_pairs ? nullptr : ivf->invlists->get_ids(key);
+
+ for (size_t j = 0; j < list_size; j++) {
+ const uint8_t* yj = list_vecs + ivf->code_size * j;
+
+ idx_t id = store_pairs ? (key << 32 | j) : ids[j];
+ csi.update_counter(yj, id);
+ }
+ if (ids) {
+ ivf->invlists->release_ids(key, ids);
+ }
+
+ nscan += list_size;
+ if (max_codes && nscan >= max_codes)
+ break;
+ }
+ ndis += nscan;
+
+ int nres = 0;
+ for (int b = 0; b < nBuckets && nres < k; b++) {
+ for (int l = 0; l < csi.counters[b] && nres < k; l++) {
+ labels[i * k + nres] = csi.ids_per_dis[b * k + l];
+ distances[i * k + nres] = b;
+ nres++;
+ }
+ }
+ while (nres < k) {
+ labels[i * k + nres] = -1;
+ distances[i * k + nres] = std::numeric_limits<int32_t>::max();
+ ++nres;
+ }
+ }
+
+ indexIVF_stats.nq += nx;
+ indexIVF_stats.nlist += nlistv;
+ indexIVF_stats.ndis += ndis;
+}
+
+/* Manages NQ queries at a time, stores results */
+template <class HammingComputer, int NQ, int K>
+struct BlockSearch {
+ HammingComputer hcs[NQ];
+ // heaps to update for each query
+ int32_t* distances[NQ];
+ idx_t* labels[NQ];
+ // curent top of heap
+ int32_t heap_tops[NQ];
+
+ BlockSearch(
+ size_t code_size,
+ const uint8_t* __restrict x,
+ const int32_t* __restrict keys,
+ int32_t* __restrict all_distances,
+ idx_t* __restrict all_labels) {
+ for (idx_t q = 0; q < NQ; q++) {
+ idx_t qno = keys[q];
+ hcs[q] = HammingComputer(x + qno * code_size, code_size);
+ distances[q] = all_distances + qno * K;
+ labels[q] = all_labels + qno * K;
+ heap_tops[q] = distances[q][0];
+ }
+ }
+
+ void add_bcode(const uint8_t* bcode, idx_t id) {
+ using C = CMax<int32_t, idx_t>;
+ for (int q = 0; q < NQ; q++) {
+ int dis = hcs[q].hamming(bcode);
+ if (dis < heap_tops[q]) {
+ heap_replace_top<C>(K, distances[q], labels[q], dis, id);
+ heap_tops[q] = distances[q][0];
+ }
+ }
+ }
+};
+
+template <class HammingComputer, int NQ>
+struct BlockSearchVariableK {
+ int k;
+ HammingComputer hcs[NQ];
+ // heaps to update for each query
+ int32_t* distances[NQ];
+ idx_t* labels[NQ];
+ // curent top of heap
+ int32_t heap_tops[NQ];
+
+ BlockSearchVariableK(
+ size_t code_size,
+ int k,
+ const uint8_t* __restrict x,
+ const int32_t* __restrict keys,
+ int32_t* __restrict all_distances,
+ idx_t* __restrict all_labels)
+ : k(k) {
+ for (idx_t q = 0; q < NQ; q++) {
+ idx_t qno = keys[q];
+ hcs[q] = HammingComputer(x + qno * code_size, code_size);
+ distances[q] = all_distances + qno * k;
+ labels[q] = all_labels + qno * k;
+ heap_tops[q] = distances[q][0];
+ }
+ }
+
+ void add_bcode(const uint8_t* bcode, idx_t id) {
+ using C = CMax<int32_t, idx_t>;
+ for (int q = 0; q < NQ; q++) {
+ int dis = hcs[q].hamming(bcode);
+ if (dis < heap_tops[q]) {
+ heap_replace_top<C>(k, distances[q], labels[q], dis, id);
+ heap_tops[q] = distances[q][0];
+ }
+ }
+ }
+};
+
+template <class HammingComputer>
+void search_knn_hamming_per_invlist(
+ const IndexBinaryIVF* ivf,
+ size_t n,
+ const uint8_t* __restrict x,
+ idx_t k,
+ const idx_t* __restrict keys_in,
+ const int32_t* __restrict coarse_dis,
+ int32_t* __restrict distances,
+ idx_t* __restrict labels,
+ bool store_pairs,
+ const IVFSearchParameters* params) {
+ idx_t nprobe = params ? params->nprobe : ivf->nprobe;
+ nprobe = std::min((idx_t)ivf->nlist, nprobe);
+ idx_t max_codes = params ? params->max_codes : ivf->max_codes;
+ FAISS_THROW_IF_NOT(max_codes == 0);
+ FAISS_THROW_IF_NOT(!store_pairs);
+
+ // reorder buckets
+ std::vector<int64_t> lims(n + 1);
+ int32_t* keys = new int32_t[n * nprobe];
+ std::unique_ptr<int32_t[]> delete_keys(keys);
+ for (idx_t i = 0; i < n * nprobe; i++) {
+ keys[i] = keys_in[i];
+ }
+ matrix_bucket_sort_inplace(n, nprobe, keys, ivf->nlist, lims.data(), 0);
+
+ using C = CMax<int32_t, idx_t>;
+ heap_heapify<C>(n * k, distances, labels);
+ const size_t code_size = ivf->code_size;
+
+ for (idx_t l = 0; l < ivf->nlist; l++) {
+ idx_t l0 = lims[l], nq = lims[l + 1] - l0;
+
+ InvertedLists::ScopedCodes scodes(ivf->invlists, l);
+ InvertedLists::ScopedIds sidx(ivf->invlists, l);
+ idx_t nb = ivf->invlists->list_size(l);
+ const uint8_t* bcodes = scodes.get();
+ const idx_t* ids = sidx.get();
+
+ idx_t i = 0;
+
+ // process as much as possible by blocks
+ constexpr int BS = 4;
+
+ if (k == 1) {
+ for (; i + BS <= nq; i += BS) {
+ BlockSearch<HammingComputer, BS, 1> bc(
+ code_size, x, keys + l0 + i, distances, labels);
+ for (idx_t j = 0; j < nb; j++) {
+ bc.add_bcode(bcodes + j * code_size, ids[j]);
+ }
+ }
+ } else if (k == 2) {
+ for (; i + BS <= nq; i += BS) {
+ BlockSearch<HammingComputer, BS, 2> bc(
+ code_size, x, keys + l0 + i, distances, labels);
+ for (idx_t j = 0; j < nb; j++) {
+ bc.add_bcode(bcodes + j * code_size, ids[j]);
+ }
+ }
+ } else if (k == 4) {
+ for (; i + BS <= nq; i += BS) {
+ BlockSearch<HammingComputer, BS, 4> bc(
+ code_size, x, keys + l0 + i, distances, labels);
+ for (idx_t j = 0; j < nb; j++) {
+ bc.add_bcode(bcodes + j * code_size, ids[j]);
+ }
+ }
+ } else {
+ for (; i + BS <= nq; i += BS) {
+ BlockSearchVariableK<HammingComputer, BS> bc(
+ code_size, k, x, keys + l0 + i, distances, labels);
+ for (idx_t j = 0; j < nb; j++) {
+ bc.add_bcode(bcodes + j * code_size, ids[j]);
+ }
+ }
+ }
+
+ // leftovers
+ for (; i < nq; i++) {
+ idx_t qno = keys[l0 + i];
+ HammingComputer hc(x + qno * code_size, code_size);
+ idx_t* __restrict idxi = labels + qno * k;
+ int32_t* __restrict simi = distances + qno * k;
+ int32_t simi0 = simi[0];
+ for (idx_t j = 0; j < nb; j++) {
+ int dis = hc.hamming(bcodes + j * code_size);
+
+ if (dis < simi0) {
+ idx_t id = store_pairs ? lo_build(l, j) : ids[j];
+ heap_replace_top<C>(k, simi, idxi, dis, id);
+ simi0 = simi[0];
+ }
+ }
+ }
+ }
+ for (idx_t i = 0; i < n; i++) {
+ heap_reorder<C>(k, distances + i * k, labels + i * k);
+ }
+}
+
+struct Run_search_knn_hamming_per_invlist {
+ using T = void;
+
+ template <class HammingComputer, class... Types>
+ void f(Types... args) {
+ search_knn_hamming_per_invlist<HammingComputer>(args...);
+ }
+};
+
+template <bool store_pairs>
+struct Run_search_knn_hamming_count {
+ using T = void;
+
+ template <class HammingComputer, class... Types>
+ void f(Types... args) {
+ search_knn_hamming_count<HammingComputer, store_pairs>(args...);
+ }
+};
+
+struct BuildScanner {
+ using T = BinaryInvertedListScanner*;
+
+ template <class HammingComputer>
+ T f(size_t code_size, bool store_pairs) {
+ return new IVFBinaryScannerL2<HammingComputer>(code_size, store_pairs);
+ }
+};
+
+} // anonymous namespace
+
+BinaryInvertedListScanner* IndexBinaryIVF::get_InvertedListScanner(
+ bool store_pairs) const {
+ BuildScanner bs;
+ return dispatch_HammingComputer(code_size, bs, code_size, store_pairs);
+}
+
+void IndexBinaryIVF::search_preassigned(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ const idx_t* cidx,
+ const int32_t* cdis,
+ int32_t* dis,
+ idx_t* idx,
+ bool store_pairs,
+ const IVFSearchParameters* params) const {
+ if (per_invlist_search) {
+ Run_search_knn_hamming_per_invlist r;
+ // clang-format off
+ dispatch_HammingComputer(
+ code_size, r, this, n, x, k,
+ cidx, cdis, dis, idx, store_pairs, params);
+ // clang-format on
+ } else if (use_heap) {
+ search_knn_hamming_heap(
+ this, n, x, k, cidx, cdis, dis, idx, store_pairs, params);
+ } else if (store_pairs) { // !use_heap && store_pairs
+ Run_search_knn_hamming_count<true> r;
+ dispatch_HammingComputer(
+ code_size, r, this, n, x, cidx, k, dis, idx, params);
+ } else { // !use_heap && !store_pairs
+ Run_search_knn_hamming_count<false> r;
+ dispatch_HammingComputer(
+ code_size, r, this, n, x, cidx, k, dis, idx, params);
+ }
+}
+
+void IndexBinaryIVF::range_search(
+ idx_t n,
+ const uint8_t* __restrict x,
+ int radius,
+ RangeSearchResult* __restrict res,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ const size_t nprobe_2 = std::min(nlist, this->nprobe);
+ std::unique_ptr<idx_t[]> idx(new idx_t[n * nprobe_2]);
+ std::unique_ptr<int32_t[]> coarse_dis(new int32_t[n * nprobe_2]);
+
+ double t0 = getmillisecs();
+ quantizer->search(n, x, nprobe_2, coarse_dis.get(), idx.get());
+ indexIVF_stats.quantization_time += getmillisecs() - t0;
+
+ t0 = getmillisecs();
+ invlists->prefetch_lists(idx.get(), n * nprobe_2);
+
+ range_search_preassigned(n, x, radius, idx.get(), coarse_dis.get(), res);
+
+ indexIVF_stats.search_time += getmillisecs() - t0;
+}
+
+void IndexBinaryIVF::range_search_preassigned(
+ idx_t n,
+ const uint8_t* __restrict x,
+ int radius,
+ const idx_t* __restrict assign,
+ const int32_t* __restrict centroid_dis,
+ RangeSearchResult* __restrict res) const {
+ const size_t nprobe_2 = std::min(nlist, this->nprobe);
+ bool store_pairs = false;
+ size_t nlistv = 0, ndis = 0;
+
+ std::vector<RangeSearchPartialResult*> all_pres(omp_get_max_threads());
+
+#pragma omp parallel reduction(+ : nlistv, ndis)
+ {
+ RangeSearchPartialResult pres(res);
+ std::unique_ptr<BinaryInvertedListScanner> scanner(
+ get_InvertedListScanner(store_pairs));
+ FAISS_THROW_IF_NOT(scanner.get());
+
+ all_pres[omp_get_thread_num()] = &pres;
+
+ auto scan_list_func = [&](size_t i, size_t ik, RangeQueryResult& qres) {
+ idx_t key = assign[i * nprobe_2 + ik]; /* select the list */
+ if (key < 0)
+ return;
+ FAISS_THROW_IF_NOT_FMT(
+ key < (idx_t)nlist,
+ "Invalid key=%" PRId64 " at ik=%zd nlist=%zd\n",
+ key,
+ ik,
+ nlist);
+ const size_t list_size = invlists->list_size(key);
+
+ if (list_size == 0)
+ return;
+
+ InvertedLists::ScopedCodes scodes(invlists, key);
+ InvertedLists::ScopedIds ids(invlists, key);
+
+ scanner->set_list(key, assign[i * nprobe_2 + ik]);
+ nlistv++;
+ ndis += list_size;
+ scanner->scan_codes_range(
+ list_size, scodes.get(), ids.get(), radius, qres);
+ };
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ scanner->set_query(x + i * code_size);
+
+ RangeQueryResult& qres = pres.new_result(i);
+
+ for (size_t ik = 0; ik < nprobe_2; ik++) {
+ scan_list_func(i, ik, qres);
+ }
+ }
+
+ pres.finalize();
+ }
+ indexIVF_stats.nq += n;
+ indexIVF_stats.nlist += nlistv;
+ indexIVF_stats.ndis += ndis;
+}
+
+IndexBinaryIVF::~IndexBinaryIVF() {
+ if (own_invlists) {
+ delete invlists;
+ }
+
+ if (own_fields) {
+ delete quantizer;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryIVF.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryIVF.h
new file mode 100644
index 0000000..0b563b4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexBinaryIVF.h
@@ -0,0 +1,260 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_BINARY_IVF_H
+#define FAISS_INDEX_BINARY_IVF_H
+
+#include <vector>
+
+#include <faiss/Clustering.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+struct BinaryInvertedListScanner;
+
+/** Index based on a inverted file (IVF)
+ *
+ * In the inverted file, the quantizer (an IndexBinary instance) provides a
+ * quantization index for each vector to be added. The quantization
+ * index maps to a list (aka inverted list or posting list), where the
+ * id of the vector is stored.
+ *
+ * Otherwise the object is similar to the IndexIVF
+ */
+struct IndexBinaryIVF : IndexBinary {
+ /// Access to the actual data
+ InvertedLists* invlists = nullptr;
+ bool own_invlists = true;
+
+ size_t nprobe = 1; ///< number of probes at query time
+ size_t max_codes = 0; ///< max nb of codes to visit to do a query
+
+ /** Select between using a heap or counting to select the k smallest values
+ * when scanning inverted lists.
+ */
+ bool use_heap = true;
+
+ /** collect computations per batch */
+ bool per_invlist_search = false;
+
+ /// map for direct access to the elements. Enables reconstruct().
+ DirectMap direct_map;
+
+ /// quantizer that maps vectors to inverted lists
+ IndexBinary* quantizer = nullptr;
+
+ /// number of possible key values
+ size_t nlist = 0;
+
+ /// whether object owns the quantizer
+ bool own_fields = false;
+
+ ClusteringParameters cp; ///< to override default clustering params
+
+ /// to override index used during clustering
+ Index* clustering_index = nullptr;
+
+ /** The Inverted file takes a quantizer (an IndexBinary) on input,
+ * which implements the function mapping a vector to a list
+ * identifier. The pointer is borrowed: the quantizer should not
+ * be deleted while the IndexBinaryIVF is in use.
+ */
+ IndexBinaryIVF(IndexBinary* quantizer, size_t d, size_t nlist);
+
+ IndexBinaryIVF();
+
+ ~IndexBinaryIVF() override;
+
+ void reset() override;
+
+ /// Trains the quantizer
+ void train(idx_t n, const uint8_t* x) override;
+
+ void add(idx_t n, const uint8_t* x) override;
+
+ void add_with_ids(idx_t n, const uint8_t* x, const idx_t* xids) override;
+
+ /** Implementation of vector addition where the vector assignments are
+ * predefined.
+ *
+ * @param precomputed_idx quantization indices for the input vectors
+ * (size n)
+ */
+ void add_core(
+ idx_t n,
+ const uint8_t* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx);
+
+ /** Search a set of vectors, that are pre-quantized by the IVF
+ * quantizer. Fill in the corresponding heaps with the query
+ * results. search() calls this.
+ *
+ * @param n nb of vectors to query
+ * @param x query vectors, size nx * d
+ * @param assign coarse quantization indices, size nx * nprobe
+ * @param centroid_dis
+ * distances to coarse centroids, size nx * nprobe
+ * @param distance
+ * output distances, size n * k
+ * @param labels output labels, size n * k
+ * @param store_pairs store inv list index + inv list offset
+ * instead in upper/lower 32 bit of result,
+ * instead of ids (used for reranking).
+ * @param params used to override the object's search parameters
+ */
+ void search_preassigned(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ const idx_t* assign,
+ const int32_t* centroid_dis,
+ int32_t* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params = nullptr) const;
+
+ virtual BinaryInvertedListScanner* get_InvertedListScanner(
+ bool store_pairs = false) const;
+
+ /** assign the vectors, then call search_preassign */
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search_preassigned(
+ idx_t n,
+ const uint8_t* x,
+ int radius,
+ const idx_t* assign,
+ const int32_t* centroid_dis,
+ RangeSearchResult* result) const;
+
+ void reconstruct(idx_t key, uint8_t* recons) const override;
+
+ /** Reconstruct a subset of the indexed vectors.
+ *
+ * Overrides default implementation to bypass reconstruct() which requires
+ * direct_map to be maintained.
+ *
+ * @param i0 first vector to reconstruct
+ * @param ni nb of vectors to reconstruct
+ * @param recons output array of reconstructed vectors, size ni * d / 8
+ */
+ void reconstruct_n(idx_t i0, idx_t ni, uint8_t* recons) const override;
+
+ /** Similar to search, but also reconstructs the stored vectors (or an
+ * approximation in the case of lossy coding) for the search results.
+ *
+ * Overrides default implementation to avoid having to maintain direct_map
+ * and instead fetch the code offsets through the `store_pairs` flag in
+ * search_preassigned().
+ *
+ * @param recons reconstructed vectors size (n, k, d / 8)
+ */
+ void search_and_reconstruct(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ idx_t* labels,
+ uint8_t* recons,
+ const SearchParameters* params = nullptr) const override;
+
+ /** Reconstruct a vector given the location in terms of (inv list index +
+ * inv list offset) instead of the id.
+ *
+ * Useful for reconstructing when the direct_map is not maintained and
+ * the inv list offset is computed by search_preassigned() with
+ * `store_pairs` set.
+ */
+ virtual void reconstruct_from_offset(
+ idx_t list_no,
+ idx_t offset,
+ uint8_t* recons) const;
+
+ /// Dataset manipulation functions
+ size_t remove_ids(const IDSelector& sel) override;
+
+ void merge_from(IndexBinary& other, idx_t add_id) override;
+
+ void check_compatible_for_merge(
+ const IndexBinary& otherIndex) const override;
+
+ size_t get_list_size(size_t list_no) const {
+ return invlists->list_size(list_no);
+ }
+
+ /** initialize a direct map
+ *
+ * @param new_maintain_direct_map if true, create a direct map,
+ * else clear it
+ */
+ void make_direct_map(bool new_maintain_direct_map = true);
+
+ void set_direct_map_type(DirectMap::Type type);
+
+ void replace_invlists(InvertedLists* il, bool own = false);
+};
+
+struct BinaryInvertedListScanner {
+ /// from now on we handle this query.
+ virtual void set_query(const uint8_t* query_vector) = 0;
+
+ /// following codes come from this inverted list
+ virtual void set_list(idx_t list_no, uint8_t coarse_dis) = 0;
+
+ /// compute a single query-to-code distance
+ virtual uint32_t distance_to_code(const uint8_t* code) const = 0;
+
+ /** compute the distances to codes. (distances, labels) should be
+ * organized as a min- or max-heap
+ *
+ * @param n number of codes to scan
+ * @param codes codes to scan (n * code_size)
+ * @param ids corresponding ids (ignored if store_pairs)
+ * @param distances heap distances (size k)
+ * @param labels heap labels (size k)
+ * @param k heap size
+ */
+ virtual size_t scan_codes(
+ size_t n,
+ const uint8_t* codes,
+ const idx_t* ids,
+ int32_t* distances,
+ idx_t* labels,
+ size_t k) const = 0;
+
+ virtual void scan_codes_range(
+ size_t n,
+ const uint8_t* codes,
+ const idx_t* ids,
+ int radius,
+ RangeQueryResult& result) const = 0;
+
+ virtual ~BinaryInvertedListScanner() {}
+};
+
+} // namespace faiss
+
+#endif // FAISS_INDEX_BINARY_IVF_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFastScan.cpp
new file mode 100644
index 0000000..b18d15b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFastScan.cpp
@@ -0,0 +1,574 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFastScan.h>
+
+#include <cassert>
+#include <climits>
+#include <memory>
+
+#include <omp.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/LookupTableScaler.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/hamming.h>
+
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/impl/simd_result_handlers.h>
+#include <faiss/utils/quantize_lut.h>
+
+namespace faiss {
+
+using namespace simd_result_handlers;
+
+inline size_t roundup(size_t a, size_t b) {
+ return (a + b - 1) / b * b;
+}
+
+void IndexFastScan::init_fastscan(
+ int d,
+ size_t M_init,
+ size_t nbits_init,
+ MetricType metric,
+ int bbs) {
+ FAISS_THROW_IF_NOT(nbits_init == 4);
+ FAISS_THROW_IF_NOT(bbs % 32 == 0);
+ this->d = d;
+ this->M = M_init;
+ this->nbits = nbits_init;
+ this->metric_type = metric;
+ this->bbs = bbs;
+ ksub = (1 << nbits_init);
+
+ code_size = (M_init * nbits_init + 7) / 8;
+ ntotal = ntotal2 = 0;
+ M2 = roundup(M_init, 2);
+ is_trained = false;
+}
+
+IndexFastScan::IndexFastScan()
+ : bbs(0), M(0), code_size(0), ntotal2(0), M2(0) {}
+
+void IndexFastScan::reset() {
+ codes.resize(0);
+ ntotal = 0;
+}
+
+void IndexFastScan::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ // do some blocking to avoid excessive allocs
+ constexpr idx_t bs = 65536;
+ if (n > bs) {
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(n, i0 + bs);
+ if (verbose) {
+ printf("IndexFastScan::add %zd/%zd\n", size_t(i1), size_t(n));
+ }
+ add(i1 - i0, x + i0 * d);
+ }
+ return;
+ }
+ InterruptCallback::check();
+
+ AlignedTable<uint8_t> tmp_codes(n * code_size);
+ compute_codes(tmp_codes.get(), n, x);
+
+ ntotal2 = roundup(ntotal + n, bbs);
+ size_t new_size = ntotal2 * M2 / 2; // assume nbits = 4
+ size_t old_size = codes.size();
+ if (new_size > old_size) {
+ codes.resize(new_size);
+ memset(codes.get() + old_size, 0, new_size - old_size);
+ }
+
+ pq4_pack_codes_range(
+ tmp_codes.get(), M, ntotal, ntotal + n, bbs, M2, codes.get());
+
+ ntotal += n;
+}
+
+CodePacker* IndexFastScan::get_CodePacker() const {
+ return new CodePackerPQ4(M, bbs);
+}
+
+size_t IndexFastScan::remove_ids(const IDSelector& sel) {
+ idx_t j = 0;
+ std::vector<uint8_t> buffer(code_size);
+ CodePackerPQ4 packer(M, bbs);
+ for (idx_t i = 0; i < ntotal; i++) {
+ if (sel.is_member(i)) {
+ // should be removed
+ } else {
+ if (i > j) {
+ packer.unpack_1(codes.data(), i, buffer.data());
+ packer.pack_1(buffer.data(), j, codes.data());
+ }
+ j++;
+ }
+ }
+ size_t nremove = ntotal - j;
+ if (nremove > 0) {
+ ntotal = j;
+ ntotal2 = roundup(ntotal, bbs);
+ size_t new_size = ntotal2 * M2 / 2;
+ codes.resize(new_size);
+ }
+ return nremove;
+}
+
+void IndexFastScan::check_compatible_for_merge(const Index& otherIndex) const {
+ const IndexFastScan* other =
+ dynamic_cast<const IndexFastScan*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->M == M);
+ FAISS_THROW_IF_NOT(other->bbs == bbs);
+ FAISS_THROW_IF_NOT(other->d == d);
+ FAISS_THROW_IF_NOT(other->code_size == code_size);
+ FAISS_THROW_IF_NOT_MSG(
+ typeid(*this) == typeid(*other),
+ "can only merge indexes of the same type");
+}
+
+void IndexFastScan::merge_from(Index& otherIndex, idx_t add_id) {
+ check_compatible_for_merge(otherIndex);
+ IndexFastScan* other = static_cast<IndexFastScan*>(&otherIndex);
+ ntotal2 = roundup(ntotal + other->ntotal, bbs);
+ codes.resize(ntotal2 * M2 / 2);
+ std::vector<uint8_t> buffer(code_size);
+ CodePackerPQ4 packer(M, bbs);
+
+ for (int i = 0; i < other->ntotal; i++) {
+ packer.unpack_1(other->codes.data(), i, buffer.data());
+ packer.pack_1(buffer.data(), ntotal + i, codes.data());
+ }
+ ntotal += other->ntotal;
+ other->reset();
+}
+
+namespace {
+
+template <class C, typename dis_t>
+void estimators_from_tables_generic(
+ const IndexFastScan& index,
+ const uint8_t* codes,
+ size_t ncodes,
+ const dis_t* dis_table,
+ size_t k,
+ typename C::T* heap_dis,
+ int64_t* heap_ids,
+ const NormTableScaler* scaler) {
+ using accu_t = typename C::T;
+
+ for (size_t j = 0; j < ncodes; ++j) {
+ BitstringReader bsr(codes + j * index.code_size, index.code_size);
+ accu_t dis = 0;
+ const dis_t* dt = dis_table;
+ int nscale = scaler ? scaler->nscale : 0;
+
+ for (size_t m = 0; m < index.M - nscale; m++) {
+ uint64_t c = bsr.read(index.nbits);
+ dis += dt[c];
+ dt += index.ksub;
+ }
+
+ if (nscale) {
+ for (size_t m = 0; m < nscale; m++) {
+ uint64_t c = bsr.read(index.nbits);
+ dis += scaler->scale_one(dt[c]);
+ dt += index.ksub;
+ }
+ }
+
+ if (C::cmp(heap_dis[0], dis)) {
+ heap_pop<C>(k, heap_dis, heap_ids);
+ heap_push<C>(k, heap_dis, heap_ids, dis, j);
+ }
+ }
+}
+
+template <class C>
+ResultHandlerCompare<C, false>* make_knn_handler(
+ int impl,
+ idx_t n,
+ idx_t k,
+ size_t ntotal,
+ float* distances,
+ idx_t* labels,
+ const IDSelector* sel = nullptr) {
+ using HeapHC = HeapHandler<C, false>;
+ using ReservoirHC = ReservoirHandler<C, false>;
+ using SingleResultHC = SingleResultHandler<C, false>;
+
+ if (k == 1) {
+ return new SingleResultHC(n, ntotal, distances, labels, sel);
+ } else if (impl % 2 == 0) {
+ return new HeapHC(n, ntotal, k, distances, labels, sel);
+ } else /* if (impl % 2 == 1) */ {
+ return new ReservoirHC(n, ntotal, k, 2 * k, distances, labels, sel);
+ }
+}
+
+} // anonymous namespace
+
+using namespace quantize_lut;
+
+void IndexFastScan::compute_quantized_LUT(
+ idx_t n,
+ const float* x,
+ uint8_t* lut,
+ float* normalizers) const {
+ size_t dim12 = ksub * M;
+ std::unique_ptr<float[]> dis_tables(new float[n * dim12]);
+ compute_float_LUT(dis_tables.get(), n, x);
+
+ for (uint64_t i = 0; i < n; i++) {
+ round_uint8_per_column(
+ dis_tables.get() + i * dim12,
+ M,
+ ksub,
+ &normalizers[2 * i],
+ &normalizers[2 * i + 1]);
+ }
+
+ for (uint64_t i = 0; i < n; i++) {
+ const float* t_in = dis_tables.get() + i * dim12;
+ uint8_t* t_out = lut + i * M2 * ksub;
+
+ for (int j = 0; j < dim12; j++) {
+ t_out[j] = int(t_in[j]);
+ }
+ memset(t_out + dim12, 0, (M2 - M) * ksub);
+ }
+}
+
+/******************************************************************************
+ * Search driver routine
+ ******************************************************************************/
+
+void IndexFastScan::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ if (metric_type == METRIC_L2) {
+ search_dispatch_implem<true>(n, x, k, distances, labels, nullptr);
+ } else {
+ search_dispatch_implem<false>(n, x, k, distances, labels, nullptr);
+ }
+}
+
+template <bool is_max>
+void IndexFastScan::search_dispatch_implem(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const NormTableScaler* scaler) const {
+ using Cfloat = typename std::conditional<
+ is_max,
+ CMax<float, int64_t>,
+ CMin<float, int64_t>>::type;
+
+ using C = typename std::
+ conditional<is_max, CMax<uint16_t, int>, CMin<uint16_t, int>>::type;
+
+ if (n == 0) {
+ return;
+ }
+
+ // actual implementation used
+ int impl = implem;
+
+ if (impl == 0) {
+ if (bbs == 32) {
+ impl = 12;
+ } else {
+ impl = 14;
+ }
+ if (k > 20) {
+ impl++;
+ }
+ }
+
+ if (implem == 1) {
+ FAISS_THROW_MSG("not implemented");
+ } else if (implem == 2 || implem == 3 || implem == 4) {
+ FAISS_THROW_IF_NOT(orig_codes != nullptr);
+ search_implem_234<Cfloat>(n, x, k, distances, labels, scaler);
+ } else if (impl >= 12 && impl <= 15) {
+ FAISS_THROW_IF_NOT(ntotal < INT_MAX);
+ int nt = std::min(omp_get_max_threads(), int(n));
+ if (nt < 2) {
+ if (impl == 12 || impl == 13) {
+ search_implem_12<C>(n, x, k, distances, labels, impl, scaler);
+ } else {
+ search_implem_14<C>(n, x, k, distances, labels, impl, scaler);
+ }
+ } else {
+ // explicitly slice over threads
+#pragma omp parallel for num_threads(nt)
+ for (int slice = 0; slice < nt; slice++) {
+ idx_t i0 = n * slice / nt;
+ idx_t i1 = n * (slice + 1) / nt;
+ float* dis_i = distances + i0 * k;
+ idx_t* lab_i = labels + i0 * k;
+ if (impl == 12 || impl == 13) {
+ search_implem_12<C>(
+ i1 - i0, x + i0 * d, k, dis_i, lab_i, impl, scaler);
+ } else {
+ search_implem_14<C>(
+ i1 - i0, x + i0 * d, k, dis_i, lab_i, impl, scaler);
+ }
+ }
+ }
+ } else {
+ FAISS_THROW_FMT("invalid implem %d impl=%d", implem, impl);
+ }
+}
+
+template <class Cfloat>
+void IndexFastScan::search_implem_234(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const NormTableScaler* scaler) const {
+ FAISS_THROW_IF_NOT(implem == 2 || implem == 3 || implem == 4);
+
+ const size_t dim12 = ksub * M;
+ std::unique_ptr<float[]> dis_tables(new float[n * dim12]);
+ compute_float_LUT(dis_tables.get(), n, x);
+
+ std::vector<float> normalizers(n * 2);
+
+ if (implem == 2) {
+ // default float
+ } else if (implem == 3 || implem == 4) {
+ for (uint64_t i = 0; i < n; i++) {
+ round_uint8_per_column(
+ dis_tables.get() + i * dim12,
+ M,
+ ksub,
+ &normalizers[2 * i],
+ &normalizers[2 * i + 1]);
+ }
+ }
+
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ int64_t* heap_ids = labels + i * k;
+ float* heap_dis = distances + i * k;
+
+ heap_heapify<Cfloat>(k, heap_dis, heap_ids);
+
+ estimators_from_tables_generic<Cfloat>(
+ *this,
+ orig_codes,
+ ntotal,
+ dis_tables.get() + i * dim12,
+ k,
+ heap_dis,
+ heap_ids,
+ scaler);
+
+ heap_reorder<Cfloat>(k, heap_dis, heap_ids);
+
+ if (implem == 4) {
+ float a = normalizers[2 * i];
+ float b = normalizers[2 * i + 1];
+
+ for (int j = 0; j < k; j++) {
+ heap_dis[j] = heap_dis[j] / a + b;
+ }
+ }
+ }
+}
+
+template <class C>
+void IndexFastScan::search_implem_12(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ int impl,
+ const NormTableScaler* scaler) const {
+ using RH = ResultHandlerCompare<C, false>;
+ FAISS_THROW_IF_NOT(bbs == 32);
+
+ // handle qbs2 blocking by recursive call
+ int64_t qbs2 = this->qbs == 0 ? 11 : pq4_qbs_to_nq(this->qbs);
+ if (n > qbs2) {
+ for (int64_t i0 = 0; i0 < n; i0 += qbs2) {
+ int64_t i1 = std::min(i0 + qbs2, n);
+ search_implem_12<C>(
+ i1 - i0,
+ x + d * i0,
+ k,
+ distances + i0 * k,
+ labels + i0 * k,
+ impl,
+ scaler);
+ }
+ return;
+ }
+
+ size_t dim12 = ksub * M2;
+ AlignedTable<uint8_t> quantized_dis_tables(n * dim12);
+ std::unique_ptr<float[]> normalizers(new float[2 * n]);
+
+ if (skip & 1) {
+ quantized_dis_tables.clear();
+ } else {
+ compute_quantized_LUT(
+ n, x, quantized_dis_tables.get(), normalizers.get());
+ }
+
+ AlignedTable<uint8_t> LUT(n * dim12);
+
+ // block sizes are encoded in qbs, 4 bits at a time
+
+ // caution: we override an object field
+ int qbs = this->qbs;
+
+ if (n != pq4_qbs_to_nq(qbs)) {
+ qbs = pq4_preferred_qbs(n);
+ }
+
+ int LUT_nq =
+ pq4_pack_LUT_qbs(qbs, M2, quantized_dis_tables.get(), LUT.get());
+ FAISS_THROW_IF_NOT(LUT_nq == n);
+
+ std::unique_ptr<RH> handler(
+ make_knn_handler<C>(impl, n, k, ntotal, distances, labels));
+ handler->disable = bool(skip & 2);
+ handler->normalizers = normalizers.get();
+
+ if (skip & 4) {
+ // pass
+ } else {
+ pq4_accumulate_loop_qbs(
+ qbs,
+ ntotal2,
+ M2,
+ codes.get(),
+ LUT.get(),
+ *handler.get(),
+ scaler);
+ }
+ if (!(skip & 8)) {
+ handler->end();
+ }
+}
+
+FastScanStats FastScan_stats;
+
+template <class C>
+void IndexFastScan::search_implem_14(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ int impl,
+ const NormTableScaler* scaler) const {
+ using RH = ResultHandlerCompare<C, false>;
+ FAISS_THROW_IF_NOT(bbs % 32 == 0);
+
+ int qbs2 = qbs == 0 ? 4 : qbs;
+
+ // handle qbs2 blocking by recursive call
+ if (n > qbs2) {
+ for (int64_t i0 = 0; i0 < n; i0 += qbs2) {
+ int64_t i1 = std::min(i0 + qbs2, n);
+ search_implem_14<C>(
+ i1 - i0,
+ x + d * i0,
+ k,
+ distances + i0 * k,
+ labels + i0 * k,
+ impl,
+ scaler);
+ }
+ return;
+ }
+
+ size_t dim12 = ksub * M2;
+ AlignedTable<uint8_t> quantized_dis_tables(n * dim12);
+ std::unique_ptr<float[]> normalizers(new float[2 * n]);
+
+ if (skip & 1) {
+ quantized_dis_tables.clear();
+ } else {
+ compute_quantized_LUT(
+ n, x, quantized_dis_tables.get(), normalizers.get());
+ }
+
+ AlignedTable<uint8_t> LUT(n * dim12);
+ pq4_pack_LUT(n, M2, quantized_dis_tables.get(), LUT.get());
+
+ std::unique_ptr<RH> handler(
+ make_knn_handler<C>(impl, n, k, ntotal, distances, labels));
+ handler->disable = bool(skip & 2);
+ handler->normalizers = normalizers.get();
+
+ if (skip & 4) {
+ // pass
+ } else {
+ pq4_accumulate_loop(
+ n,
+ ntotal2,
+ bbs,
+ M2,
+ codes.get(),
+ LUT.get(),
+ *handler.get(),
+ scaler);
+ }
+ if (!(skip & 8)) {
+ handler->end();
+ }
+}
+
+template void IndexFastScan::search_dispatch_implem<true>(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const NormTableScaler* scaler) const;
+
+template void IndexFastScan::search_dispatch_implem<false>(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const NormTableScaler* scaler) const;
+
+void IndexFastScan::reconstruct(idx_t key, float* recons) const {
+ std::vector<uint8_t> code(code_size, 0);
+ BitstringWriter bsw(code.data(), code_size);
+ for (size_t m = 0; m < M; m++) {
+ uint8_t c = pq4_get_packed_element(codes.data(), bbs, M2, key, m);
+ bsw.write(c, nbits);
+ }
+ sa_decode(1, code.data(), recons);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFastScan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFastScan.h
new file mode 100644
index 0000000..a0f5c59
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFastScan.h
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+struct CodePacker;
+struct NormTableScaler;
+
+/** Fast scan version of IndexPQ and IndexAQ. Works for 4-bit PQ and AQ for now.
+ *
+ * The codes are not stored sequentially but grouped in blocks of size bbs.
+ * This makes it possible to compute distances quickly with SIMD instructions.
+ * The trailing codes (padding codes that are added to complete the last code)
+ * are garbage.
+ *
+ * Implementations:
+ * 12: blocked loop with internal loop on Q with qbs
+ * 13: same with reservoir accumulator to store results
+ * 14: no qbs with heap accumulator
+ * 15: no qbs with reservoir accumulator
+ */
+struct IndexFastScan : Index {
+ // implementation to select
+ int implem = 0;
+ // skip some parts of the computation (for timing)
+ int skip = 0;
+
+ // size of the kernel
+ int bbs; // set at build time
+ int qbs = 0; // query block size 0 = use default
+
+ // vector quantizer
+ size_t M;
+ size_t nbits;
+ size_t ksub;
+ size_t code_size;
+
+ // packed version of the codes
+ size_t ntotal2;
+ size_t M2;
+
+ AlignedTable<uint8_t> codes;
+
+ // this is for testing purposes only
+ // (set when initialized by IndexPQ or IndexAQ)
+ const uint8_t* orig_codes = nullptr;
+
+ void init_fastscan(
+ int d,
+ size_t M,
+ size_t nbits,
+ MetricType metric,
+ int bbs);
+
+ IndexFastScan();
+
+ void reset() override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void add(idx_t n, const float* x) override;
+
+ virtual void compute_codes(uint8_t* codes, idx_t n, const float* x)
+ const = 0;
+
+ virtual void compute_float_LUT(float* lut, idx_t n, const float* x)
+ const = 0;
+
+ // called by search function
+ void compute_quantized_LUT(
+ idx_t n,
+ const float* x,
+ uint8_t* lut,
+ float* normalizers) const;
+
+ template <bool is_max>
+ void search_dispatch_implem(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const NormTableScaler* scaler) const;
+
+ template <class Cfloat>
+ void search_implem_234(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const NormTableScaler* scaler) const;
+
+ template <class C>
+ void search_implem_12(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ int impl,
+ const NormTableScaler* scaler) const;
+
+ template <class C>
+ void search_implem_14(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ int impl,
+ const NormTableScaler* scaler) const;
+
+ void reconstruct(idx_t key, float* recons) const override;
+ size_t remove_ids(const IDSelector& sel) override;
+
+ CodePacker* get_CodePacker() const;
+
+ void merge_from(Index& otherIndex, idx_t add_id = 0) override;
+ void check_compatible_for_merge(const Index& otherIndex) const override;
+
+ /// standalone codes interface (but the codes are flattened)
+ size_t sa_code_size() const override {
+ return code_size;
+ }
+
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override {
+ compute_codes(bytes, n, x);
+ }
+};
+
+struct FastScanStats {
+ uint64_t t0, t1, t2, t3;
+ FastScanStats() {
+ reset();
+ }
+ void reset() {
+ memset(this, 0, sizeof(*this));
+ }
+};
+
+FAISS_API extern FastScanStats FastScan_stats;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlat.cpp
new file mode 100644
index 0000000..094d268
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlat.cpp
@@ -0,0 +1,520 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexFlat.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/extra_distances.h>
+#include <faiss/utils/prefetch.h>
+#include <faiss/utils/sorting.h>
+#include <cstring>
+
+namespace faiss {
+
+IndexFlat::IndexFlat(idx_t d, MetricType metric)
+ : IndexFlatCodes(sizeof(float) * d, d, metric) {}
+
+void IndexFlat::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ IDSelector* sel = params ? params->sel : nullptr;
+ FAISS_THROW_IF_NOT(k > 0);
+
+ // we see the distances and labels as heaps
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ float_minheap_array_t res = {size_t(n), size_t(k), labels, distances};
+ knn_inner_product(x, get_xb(), d, n, ntotal, &res, sel);
+ } else if (metric_type == METRIC_L2) {
+ float_maxheap_array_t res = {size_t(n), size_t(k), labels, distances};
+ knn_L2sqr(x, get_xb(), d, n, ntotal, &res, nullptr, sel);
+ } else {
+ FAISS_THROW_IF_NOT(!sel); // TODO implement with selector
+ knn_extra_metrics(
+ x,
+ get_xb(),
+ d,
+ n,
+ ntotal,
+ metric_type,
+ metric_arg,
+ k,
+ distances,
+ labels);
+ }
+}
+
+void IndexFlat::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ IDSelector* sel = params ? params->sel : nullptr;
+
+ switch (metric_type) {
+ case METRIC_INNER_PRODUCT:
+ range_search_inner_product(
+ x, get_xb(), d, n, ntotal, radius, result, sel);
+ break;
+ case METRIC_L2:
+ range_search_L2sqr(x, get_xb(), d, n, ntotal, radius, result, sel);
+ break;
+ default:
+ FAISS_THROW_MSG("metric type not supported");
+ }
+}
+
+void IndexFlat::compute_distance_subset(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ const idx_t* labels) const {
+ switch (metric_type) {
+ case METRIC_INNER_PRODUCT:
+ fvec_inner_products_by_idx(distances, x, get_xb(), labels, d, n, k);
+ break;
+ case METRIC_L2:
+ fvec_L2sqr_by_idx(distances, x, get_xb(), labels, d, n, k);
+ break;
+ default:
+ FAISS_THROW_MSG("metric type not supported");
+ }
+}
+
+namespace {
+
+struct FlatL2Dis : FlatCodesDistanceComputer {
+ size_t d;
+ idx_t nb;
+ const float* q;
+ const float* b;
+ size_t ndis;
+
+ float distance_to_code(const uint8_t* code) final {
+ ndis++;
+ return fvec_L2sqr(q, (float*)code, d);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return fvec_L2sqr(b + j * d, b + i * d, d);
+ }
+
+ explicit FlatL2Dis(const IndexFlat& storage, const float* q = nullptr)
+ : FlatCodesDistanceComputer(
+ storage.codes.data(),
+ storage.code_size),
+ d(storage.d),
+ nb(storage.ntotal),
+ q(q),
+ b(storage.get_xb()),
+ ndis(0) {}
+
+ void set_query(const float* x) override {
+ q = x;
+ }
+
+ // compute four distances
+ void distances_batch_4(
+ const idx_t idx0,
+ const idx_t idx1,
+ const idx_t idx2,
+ const idx_t idx3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) final override {
+ ndis += 4;
+
+ // compute first, assign next
+ const float* __restrict y0 =
+ reinterpret_cast<const float*>(codes + idx0 * code_size);
+ const float* __restrict y1 =
+ reinterpret_cast<const float*>(codes + idx1 * code_size);
+ const float* __restrict y2 =
+ reinterpret_cast<const float*>(codes + idx2 * code_size);
+ const float* __restrict y3 =
+ reinterpret_cast<const float*>(codes + idx3 * code_size);
+
+ float dp0 = 0;
+ float dp1 = 0;
+ float dp2 = 0;
+ float dp3 = 0;
+ fvec_L2sqr_batch_4(q, y0, y1, y2, y3, d, dp0, dp1, dp2, dp3);
+ dis0 = dp0;
+ dis1 = dp1;
+ dis2 = dp2;
+ dis3 = dp3;
+ }
+};
+
+struct FlatIPDis : FlatCodesDistanceComputer {
+ size_t d;
+ idx_t nb;
+ const float* q;
+ const float* b;
+ size_t ndis;
+
+ float symmetric_dis(idx_t i, idx_t j) final override {
+ return fvec_inner_product(b + j * d, b + i * d, d);
+ }
+
+ float distance_to_code(const uint8_t* code) final override {
+ ndis++;
+ return fvec_inner_product(q, (const float*)code, d);
+ }
+
+ explicit FlatIPDis(const IndexFlat& storage, const float* q = nullptr)
+ : FlatCodesDistanceComputer(
+ storage.codes.data(),
+ storage.code_size),
+ d(storage.d),
+ nb(storage.ntotal),
+ q(q),
+ b(storage.get_xb()),
+ ndis(0) {}
+
+ void set_query(const float* x) override {
+ q = x;
+ }
+
+ // compute four distances
+ void distances_batch_4(
+ const idx_t idx0,
+ const idx_t idx1,
+ const idx_t idx2,
+ const idx_t idx3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) final override {
+ ndis += 4;
+
+ // compute first, assign next
+ const float* __restrict y0 =
+ reinterpret_cast<const float*>(codes + idx0 * code_size);
+ const float* __restrict y1 =
+ reinterpret_cast<const float*>(codes + idx1 * code_size);
+ const float* __restrict y2 =
+ reinterpret_cast<const float*>(codes + idx2 * code_size);
+ const float* __restrict y3 =
+ reinterpret_cast<const float*>(codes + idx3 * code_size);
+
+ float dp0 = 0;
+ float dp1 = 0;
+ float dp2 = 0;
+ float dp3 = 0;
+ fvec_inner_product_batch_4(q, y0, y1, y2, y3, d, dp0, dp1, dp2, dp3);
+ dis0 = dp0;
+ dis1 = dp1;
+ dis2 = dp2;
+ dis3 = dp3;
+ }
+};
+
+} // namespace
+
+FlatCodesDistanceComputer* IndexFlat::get_FlatCodesDistanceComputer() const {
+ if (metric_type == METRIC_L2) {
+ return new FlatL2Dis(*this);
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ return new FlatIPDis(*this);
+ } else {
+ return get_extra_distance_computer(
+ d, metric_type, metric_arg, ntotal, get_xb());
+ }
+}
+
+void IndexFlat::reconstruct(idx_t key, float* recons) const {
+ memcpy(recons, &(codes[key * code_size]), code_size);
+}
+
+void IndexFlat::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ if (n > 0) {
+ memcpy(bytes, x, sizeof(float) * d * n);
+ }
+}
+
+void IndexFlat::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ if (n > 0) {
+ memcpy(x, bytes, sizeof(float) * d * n);
+ }
+}
+
+/***************************************************
+ * IndexFlatL2
+ ***************************************************/
+
+namespace {
+struct FlatL2WithNormsDis : FlatCodesDistanceComputer {
+ size_t d;
+ idx_t nb;
+ const float* q;
+ const float* b;
+ size_t ndis;
+
+ const float* l2norms;
+ float query_l2norm;
+
+ float distance_to_code(const uint8_t* code) final override {
+ ndis++;
+ return fvec_L2sqr(q, (float*)code, d);
+ }
+
+ float operator()(const idx_t i) final override {
+ const float* __restrict y =
+ reinterpret_cast<const float*>(codes + i * code_size);
+
+ prefetch_L2(l2norms + i);
+ const float dp0 = fvec_inner_product(q, y, d);
+ return query_l2norm + l2norms[i] - 2 * dp0;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) final override {
+ const float* __restrict yi =
+ reinterpret_cast<const float*>(codes + i * code_size);
+ const float* __restrict yj =
+ reinterpret_cast<const float*>(codes + j * code_size);
+
+ prefetch_L2(l2norms + i);
+ prefetch_L2(l2norms + j);
+ const float dp0 = fvec_inner_product(yi, yj, d);
+ return l2norms[i] + l2norms[j] - 2 * dp0;
+ }
+
+ explicit FlatL2WithNormsDis(
+ const IndexFlatL2& storage,
+ const float* q = nullptr)
+ : FlatCodesDistanceComputer(
+ storage.codes.data(),
+ storage.code_size),
+ d(storage.d),
+ nb(storage.ntotal),
+ q(q),
+ b(storage.get_xb()),
+ ndis(0),
+ l2norms(storage.cached_l2norms.data()),
+ query_l2norm(0) {}
+
+ void set_query(const float* x) override {
+ q = x;
+ query_l2norm = fvec_norm_L2sqr(q, d);
+ }
+
+ // compute four distances
+ void distances_batch_4(
+ const idx_t idx0,
+ const idx_t idx1,
+ const idx_t idx2,
+ const idx_t idx3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) final override {
+ ndis += 4;
+
+ // compute first, assign next
+ const float* __restrict y0 =
+ reinterpret_cast<const float*>(codes + idx0 * code_size);
+ const float* __restrict y1 =
+ reinterpret_cast<const float*>(codes + idx1 * code_size);
+ const float* __restrict y2 =
+ reinterpret_cast<const float*>(codes + idx2 * code_size);
+ const float* __restrict y3 =
+ reinterpret_cast<const float*>(codes + idx3 * code_size);
+
+ prefetch_L2(l2norms + idx0);
+ prefetch_L2(l2norms + idx1);
+ prefetch_L2(l2norms + idx2);
+ prefetch_L2(l2norms + idx3);
+
+ float dp0 = 0;
+ float dp1 = 0;
+ float dp2 = 0;
+ float dp3 = 0;
+ fvec_inner_product_batch_4(q, y0, y1, y2, y3, d, dp0, dp1, dp2, dp3);
+ dis0 = query_l2norm + l2norms[idx0] - 2 * dp0;
+ dis1 = query_l2norm + l2norms[idx1] - 2 * dp1;
+ dis2 = query_l2norm + l2norms[idx2] - 2 * dp2;
+ dis3 = query_l2norm + l2norms[idx3] - 2 * dp3;
+ }
+};
+
+} // namespace
+
+void IndexFlatL2::sync_l2norms() {
+ cached_l2norms.resize(ntotal);
+ fvec_norms_L2sqr(
+ cached_l2norms.data(),
+ reinterpret_cast<const float*>(codes.data()),
+ d,
+ ntotal);
+}
+
+void IndexFlatL2::clear_l2norms() {
+ cached_l2norms.clear();
+ cached_l2norms.shrink_to_fit();
+}
+
+FlatCodesDistanceComputer* IndexFlatL2::get_FlatCodesDistanceComputer() const {
+ if (metric_type == METRIC_L2) {
+ if (!cached_l2norms.empty()) {
+ return new FlatL2WithNormsDis(*this);
+ }
+ }
+
+ return IndexFlat::get_FlatCodesDistanceComputer();
+}
+
+/***************************************************
+ * IndexFlat1D
+ ***************************************************/
+
+IndexFlat1D::IndexFlat1D(bool continuous_update)
+ : IndexFlatL2(1), continuous_update(continuous_update) {}
+
+/// if not continuous_update, call this between the last add and
+/// the first search
+void IndexFlat1D::update_permutation() {
+ perm.resize(ntotal);
+ if (ntotal < 1000000) {
+ fvec_argsort(ntotal, get_xb(), (size_t*)perm.data());
+ } else {
+ fvec_argsort_parallel(ntotal, get_xb(), (size_t*)perm.data());
+ }
+}
+
+void IndexFlat1D::add(idx_t n, const float* x) {
+ IndexFlatL2::add(n, x);
+ if (continuous_update)
+ update_permutation();
+}
+
+void IndexFlat1D::reset() {
+ IndexFlatL2::reset();
+ perm.clear();
+}
+
+void IndexFlat1D::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT_MSG(
+ perm.size() == ntotal, "Call update_permutation before search");
+ const float* xb = get_xb();
+
+#pragma omp parallel for if (n > 10000)
+ for (idx_t i = 0; i < n; i++) {
+ float q = x[i]; // query
+ float* D = distances + i * k;
+ idx_t* I = labels + i * k;
+
+ // binary search
+ idx_t i0 = 0, i1 = ntotal;
+ idx_t wp = 0;
+
+ if (ntotal == 0) {
+ for (idx_t j = 0; j < k; j++) {
+ I[j] = -1;
+ D[j] = HUGE_VAL;
+ }
+ goto done;
+ }
+
+ if (xb[perm[i0]] > q) {
+ i1 = 0;
+ goto finish_right;
+ }
+
+ if (xb[perm[i1 - 1]] <= q) {
+ i0 = i1 - 1;
+ goto finish_left;
+ }
+
+ while (i0 + 1 < i1) {
+ idx_t imed = (i0 + i1) / 2;
+ if (xb[perm[imed]] <= q)
+ i0 = imed;
+ else
+ i1 = imed;
+ }
+
+ // query is between xb[perm[i0]] and xb[perm[i1]]
+ // expand to nearest neighs
+
+ while (wp < k) {
+ float xleft = xb[perm[i0]];
+ float xright = xb[perm[i1]];
+
+ if (q - xleft < xright - q) {
+ D[wp] = q - xleft;
+ I[wp] = perm[i0];
+ i0--;
+ wp++;
+ if (i0 < 0) {
+ goto finish_right;
+ }
+ } else {
+ D[wp] = xright - q;
+ I[wp] = perm[i1];
+ i1++;
+ wp++;
+ if (i1 >= ntotal) {
+ goto finish_left;
+ }
+ }
+ }
+ goto done;
+
+ finish_right:
+ // grow to the right from i1
+ while (wp < k) {
+ if (i1 < ntotal) {
+ D[wp] = xb[perm[i1]] - q;
+ I[wp] = perm[i1];
+ i1++;
+ } else {
+ D[wp] = std::numeric_limits<float>::infinity();
+ I[wp] = -1;
+ }
+ wp++;
+ }
+ goto done;
+
+ finish_left:
+ // grow to the left from i0
+ while (wp < k) {
+ if (i0 >= 0) {
+ D[wp] = q - xb[perm[i0]];
+ I[wp] = perm[i0];
+ i0--;
+ } else {
+ D[wp] = std::numeric_limits<float>::infinity();
+ I[wp] = -1;
+ }
+ wp++;
+ }
+ done:;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlat.h
new file mode 100644
index 0000000..876a2ec
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlat.h
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef INDEX_FLAT_H
+#define INDEX_FLAT_H
+
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+
+namespace faiss {
+
+/** Index that stores the full vectors and performs exhaustive search */
+struct IndexFlat : IndexFlatCodes {
+ explicit IndexFlat(
+ idx_t d, ///< dimensionality of the input vectors
+ MetricType metric = METRIC_L2);
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ /** compute distance with a subset of vectors
+ *
+ * @param x query vectors, size n * d
+ * @param labels indices of the vectors that should be compared
+ * for each query vector, size n * k
+ * @param distances
+ * corresponding output distances, size n * k
+ */
+ void compute_distance_subset(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ const idx_t* labels) const;
+
+ // get pointer to the floating point data
+ float* get_xb() {
+ return (float*)codes.data();
+ }
+ const float* get_xb() const {
+ return (const float*)codes.data();
+ }
+
+ IndexFlat() {}
+
+ FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const override;
+
+ /* The stanadlone codec interface (just memcopies in this case) */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+struct IndexFlatIP : IndexFlat {
+ explicit IndexFlatIP(idx_t d) : IndexFlat(d, METRIC_INNER_PRODUCT) {}
+ IndexFlatIP() {}
+};
+
+struct IndexFlatL2 : IndexFlat {
+ // Special cache for L2 norms.
+ // If this cache is set, then get_distance_computer() returns
+ // a special version that computes the distance using dot products
+ // and l2 norms.
+ std::vector<float> cached_l2norms;
+
+ /**
+ * @param d dimensionality of the input vectors
+ */
+ explicit IndexFlatL2(idx_t d) : IndexFlat(d, METRIC_L2) {}
+ IndexFlatL2() {}
+
+ // override for l2 norms cache.
+ FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const override;
+
+ // compute L2 norms
+ void sync_l2norms();
+ // clear L2 norms
+ void clear_l2norms();
+};
+
+/// optimized version for 1D "vectors".
+struct IndexFlat1D : IndexFlatL2 {
+ bool continuous_update = true; ///< is the permutation updated continuously?
+
+ std::vector<idx_t> perm; ///< sorted database indices
+
+ explicit IndexFlat1D(bool continuous_update = true);
+
+ /// if not continuous_update, call this between the last add and
+ /// the first search
+ void update_permutation();
+
+ void add(idx_t n, const float* x) override;
+
+ void reset() override;
+
+ /// Warn: the distances returned are L1 not L2
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlatCodes.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlatCodes.cpp
new file mode 100644
index 0000000..d5b86b3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlatCodes.cpp
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlatCodes.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/CodePacker.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/extra_distances.h>
+
+namespace faiss {
+
+IndexFlatCodes::IndexFlatCodes(size_t code_size, idx_t d, MetricType metric)
+ : Index(d, metric), code_size(code_size) {}
+
+IndexFlatCodes::IndexFlatCodes() : code_size(0) {}
+
+void IndexFlatCodes::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT(is_trained);
+ if (n == 0) {
+ return;
+ }
+ codes.resize((ntotal + n) * code_size);
+ sa_encode(n, x, codes.data() + (ntotal * code_size));
+ ntotal += n;
+}
+
+void IndexFlatCodes::add_sa_codes(
+ idx_t n,
+ const uint8_t* codes_in,
+ const idx_t* /* xids */) {
+ codes.resize((ntotal + n) * code_size);
+ memcpy(codes.data() + (ntotal * code_size), codes_in, n * code_size);
+ ntotal += n;
+}
+
+void IndexFlatCodes::reset() {
+ codes.clear();
+ ntotal = 0;
+}
+
+size_t IndexFlatCodes::sa_code_size() const {
+ return code_size;
+}
+
+size_t IndexFlatCodes::remove_ids(const IDSelector& sel) {
+ idx_t j = 0;
+ for (idx_t i = 0; i < ntotal; i++) {
+ if (sel.is_member(i)) {
+ // should be removed
+ } else {
+ if (i > j) {
+ memmove(&codes[code_size * j],
+ &codes[code_size * i],
+ code_size);
+ }
+ j++;
+ }
+ }
+ size_t nremove = ntotal - j;
+ if (nremove > 0) {
+ ntotal = j;
+ codes.resize(ntotal * code_size);
+ }
+ return nremove;
+}
+
+void IndexFlatCodes::reconstruct_n(idx_t i0, idx_t ni, float* recons) const {
+ FAISS_THROW_IF_NOT(ni == 0 || (i0 >= 0 && i0 + ni <= ntotal));
+ sa_decode(ni, codes.data() + i0 * code_size, recons);
+}
+
+void IndexFlatCodes::reconstruct(idx_t key, float* recons) const {
+ reconstruct_n(key, 1, recons);
+}
+
+void IndexFlatCodes::check_compatible_for_merge(const Index& otherIndex) const {
+ // minimal sanity checks
+ const IndexFlatCodes* other =
+ dynamic_cast<const IndexFlatCodes*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->d == d);
+ FAISS_THROW_IF_NOT(other->code_size == code_size);
+ FAISS_THROW_IF_NOT_MSG(
+ typeid(*this) == typeid(*other),
+ "can only merge indexes of the same type");
+}
+
+void IndexFlatCodes::merge_from(Index& otherIndex, idx_t add_id) {
+ FAISS_THROW_IF_NOT_MSG(add_id == 0, "cannot set ids in FlatCodes index");
+ check_compatible_for_merge(otherIndex);
+ IndexFlatCodes* other = static_cast<IndexFlatCodes*>(&otherIndex);
+ codes.resize((ntotal + other->ntotal) * code_size);
+ memcpy(codes.data() + (ntotal * code_size),
+ other->codes.data(),
+ other->ntotal * code_size);
+ ntotal += other->ntotal;
+ other->reset();
+}
+
+CodePacker* IndexFlatCodes::get_CodePacker() const {
+ return new CodePackerFlat(code_size);
+}
+
+void IndexFlatCodes::permute_entries(const idx_t* perm) {
+ MaybeOwnedVector<uint8_t> new_codes(codes.size());
+
+ for (idx_t i = 0; i < ntotal; i++) {
+ memcpy(new_codes.data() + i * code_size,
+ codes.data() + perm[i] * code_size,
+ code_size);
+ }
+ std::swap(codes, new_codes);
+}
+
+namespace {
+
+template <class VD>
+struct GenericFlatCodesDistanceComputer : FlatCodesDistanceComputer {
+ const IndexFlatCodes& codec;
+ const VD vd;
+ // temp buffers
+ std::vector<uint8_t> code_buffer;
+ std::vector<float> vec_buffer;
+ const float* query = nullptr;
+
+ GenericFlatCodesDistanceComputer(const IndexFlatCodes* codec, const VD& vd)
+ : FlatCodesDistanceComputer(codec->codes.data(), codec->code_size),
+ codec(*codec),
+ vd(vd),
+ code_buffer(codec->code_size * 4),
+ vec_buffer(codec->d * 4) {}
+
+ void set_query(const float* x) override {
+ query = x;
+ }
+
+ float operator()(idx_t i) override {
+ codec.sa_decode(1, codes + i * code_size, vec_buffer.data());
+ return vd(query, vec_buffer.data());
+ }
+
+ float distance_to_code(const uint8_t* code) override {
+ codec.sa_decode(1, code, vec_buffer.data());
+ return vd(query, vec_buffer.data());
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ codec.sa_decode(1, codes + i * code_size, vec_buffer.data());
+ codec.sa_decode(1, codes + j * code_size, vec_buffer.data() + vd.d);
+ return vd(vec_buffer.data(), vec_buffer.data() + vd.d);
+ }
+
+ void distances_batch_4(
+ const idx_t idx0,
+ const idx_t idx1,
+ const idx_t idx2,
+ const idx_t idx3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) override {
+ uint8_t* cp = code_buffer.data();
+ for (idx_t i : {idx0, idx1, idx2, idx3}) {
+ memcpy(cp, codes + i * code_size, code_size);
+ cp += code_size;
+ }
+ // potential benefit is if batch decoding is more efficient than 1 by 1
+ // decoding
+ codec.sa_decode(4, code_buffer.data(), vec_buffer.data());
+ dis0 = vd(query, vec_buffer.data());
+ dis1 = vd(query, vec_buffer.data() + vd.d);
+ dis2 = vd(query, vec_buffer.data() + 2 * vd.d);
+ dis3 = vd(query, vec_buffer.data() + 3 * vd.d);
+ }
+};
+
+struct Run_get_distance_computer {
+ using T = FlatCodesDistanceComputer*;
+
+ template <class VD>
+ FlatCodesDistanceComputer* f(const VD& vd, const IndexFlatCodes* codec) {
+ return new GenericFlatCodesDistanceComputer<VD>(codec, vd);
+ }
+};
+
+template <class BlockResultHandler>
+struct Run_search_with_decompress {
+ using T = void;
+
+ template <class VectorDistance>
+ void f(VectorDistance& vd,
+ const IndexFlatCodes* index_ptr,
+ const float* xq,
+ BlockResultHandler& res) {
+ // Note that there seems to be a clang (?) bug that "sometimes" passes
+ // the const Index & parameters by value, so to be on the safe side,
+ // it's better to use pointers.
+ const IndexFlatCodes& index = *index_ptr;
+ size_t ntotal = index.ntotal;
+ using SingleResultHandler =
+ typename BlockResultHandler::SingleResultHandler;
+ using DC = GenericFlatCodesDistanceComputer<VectorDistance>;
+#pragma omp parallel // if (res.nq > 100)
+ {
+ std::unique_ptr<DC> dc(new DC(&index, vd));
+ SingleResultHandler resi(res);
+#pragma omp for
+ for (int64_t q = 0; q < res.nq; q++) {
+ resi.begin(q);
+ dc->set_query(xq + vd.d * q);
+ for (size_t i = 0; i < ntotal; i++) {
+ if (res.is_in_selection(i)) {
+ float dis = (*dc)(i);
+ resi.add_result(dis, i);
+ }
+ }
+ resi.end();
+ }
+ }
+ }
+};
+
+struct Run_search_with_decompress_res {
+ using T = void;
+
+ template <class ResultHandler>
+ void f(ResultHandler& res, const IndexFlatCodes* index, const float* xq) {
+ Run_search_with_decompress<ResultHandler> r;
+ dispatch_VectorDistance(
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ r,
+ index,
+ xq,
+ res);
+ }
+};
+
+} // anonymous namespace
+
+FlatCodesDistanceComputer* IndexFlatCodes::get_FlatCodesDistanceComputer()
+ const {
+ Run_get_distance_computer r;
+ return dispatch_VectorDistance(d, metric_type, metric_arg, r, this);
+}
+
+void IndexFlatCodes::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ Run_search_with_decompress_res r;
+ const IDSelector* sel = params ? params->sel : nullptr;
+ dispatch_knn_ResultHandler(
+ n, distances, labels, k, metric_type, sel, r, this, x);
+}
+
+void IndexFlatCodes::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ const IDSelector* sel = params ? params->sel : nullptr;
+ Run_search_with_decompress_res r;
+ dispatch_range_ResultHandler(result, radius, metric_type, sel, r, this, x);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlatCodes.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlatCodes.h
new file mode 100644
index 0000000..56a11df
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexFlatCodes.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/maybe_owned_vector.h>
+
+namespace faiss {
+
+struct CodePacker;
+
+/** Index that encodes all vectors as fixed-size codes (size code_size). Storage
+ * is in the codes vector */
+struct IndexFlatCodes : Index {
+ size_t code_size;
+
+ /// encoded dataset, size ntotal * code_size
+ MaybeOwnedVector<uint8_t> codes;
+
+ IndexFlatCodes();
+
+ IndexFlatCodes(size_t code_size, idx_t d, MetricType metric = METRIC_L2);
+
+ /// default add uses sa_encode
+ void add(idx_t n, const float* x) override;
+
+ void reset() override;
+
+ void reconstruct_n(idx_t i0, idx_t ni, float* recons) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ size_t sa_code_size() const override;
+
+ /** remove some ids. NB that because of the structure of the
+ * index, the semantics of this operation are
+ * different from the usual ones: the new ids are shifted */
+ size_t remove_ids(const IDSelector& sel) override;
+
+ /** a FlatCodesDistanceComputer offers a distance_to_code method
+ *
+ * The default implementation explicitly decodes the vector with sa_decode.
+ */
+ virtual FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const;
+
+ DistanceComputer* get_distance_computer() const override {
+ return get_FlatCodesDistanceComputer();
+ }
+
+ /** Search implemented by decoding */
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ // returns a new instance of a CodePacker
+ CodePacker* get_CodePacker() const;
+
+ void check_compatible_for_merge(const Index& otherIndex) const override;
+
+ virtual void merge_from(Index& otherIndex, idx_t add_id = 0) override;
+
+ virtual void add_sa_codes(idx_t n, const uint8_t* x, const idx_t* xids)
+ override;
+
+ // permute_entries. perm of size ntotal maps new to old positions
+ void permute_entries(const idx_t* perm);
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexHNSW.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexHNSW.cpp
new file mode 100644
index 0000000..409a487
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexHNSW.cpp
@@ -0,0 +1,1193 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexHNSW.h>
+
+#include <omp.h>
+#include <cinttypes>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+
+#include <limits>
+#include <memory>
+#include <queue>
+#include <random>
+
+#include <cstdint>
+
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/sorting.h>
+
+#include <faiss/impl/HNSW_zmq.h>
+#include <msgpack.hpp>
+
+namespace faiss {
+
+using MinimaxHeap = HNSW::MinimaxHeap;
+using storage_idx_t = HNSW::storage_idx_t;
+using NodeDistFarther = HNSW::NodeDistFarther;
+
+HNSWStats hnsw_stats;
+
+/**************************************************************
+ * add / search blocks of descriptors
+ **************************************************************/
+
+namespace {
+
+DistanceComputer* storage_distance_computer(const Index* storage) {
+ if (is_similarity_metric(storage->metric_type)) {
+ return new NegativeDistanceComputer(storage->get_distance_computer());
+ } else {
+ return storage->get_distance_computer();
+ }
+}
+
+void hnsw_add_vertices(
+ IndexHNSW& index_hnsw,
+ size_t n0,
+ size_t n,
+ const float* x,
+ bool verbose,
+ bool preset_levels = false) {
+ size_t d = index_hnsw.d;
+ HNSW& hnsw = index_hnsw.hnsw;
+ size_t ntotal = n0 + n;
+ double t0 = getmillisecs();
+ if (verbose) {
+ printf("hnsw_add_vertices: adding %zd elements on top of %zd "
+ "(preset_levels=%d)\n",
+ n,
+ n0,
+ int(preset_levels));
+ }
+
+ if (n == 0) {
+ return;
+ }
+
+ int max_level = hnsw.prepare_level_tab(n, preset_levels);
+
+ if (verbose) {
+ printf(" max_level = %d\n", max_level);
+ }
+
+ std::vector<omp_lock_t> locks(ntotal);
+ for (int i = 0; i < ntotal; i++)
+ omp_init_lock(&locks[i]);
+
+ // add vectors from highest to lowest level
+ std::vector<int> hist;
+ std::vector<int> order(n);
+
+ { // make buckets with vectors of the same level
+
+ // build histogram
+ for (int i = 0; i < n; i++) {
+ storage_idx_t pt_id = i + n0;
+ int pt_level = hnsw.levels[pt_id] - 1;
+ while (pt_level >= hist.size())
+ hist.push_back(0);
+ hist[pt_level]++;
+ }
+
+ // accumulate
+ std::vector<int> offsets(hist.size() + 1, 0);
+ for (int i = 0; i < hist.size() - 1; i++) {
+ offsets[i + 1] = offsets[i] + hist[i];
+ }
+
+ // bucket sort
+ for (int i = 0; i < n; i++) {
+ storage_idx_t pt_id = i + n0;
+ int pt_level = hnsw.levels[pt_id] - 1;
+ order[offsets[pt_level]++] = pt_id;
+ }
+ }
+
+ idx_t check_period = InterruptCallback::get_period_hint(
+ max_level * index_hnsw.d * hnsw.efConstruction);
+
+ { // perform add
+ RandomGenerator rng2(789);
+
+ int i1 = n;
+
+ for (int pt_level = hist.size() - 1;
+ pt_level >= int(!index_hnsw.init_level0);
+ pt_level--) {
+ int M = hnsw.nb_neighbors(pt_level);
+ if (pt_level == 0) {
+ printf("M: %d for level: %d\n", M, pt_level);
+ // assign new vector to ems
+ hnsw.ems = std::vector<int>(ntotal, M);
+ } else {
+ // value set to infinity
+ hnsw.ems = std::vector<int>(
+ ntotal, std::numeric_limits<int>::max());
+ }
+
+ int i0 = i1 - hist[pt_level];
+
+ if (verbose) {
+ printf("Adding %d elements at level %d\n", i1 - i0, pt_level);
+ }
+
+ // random permutation to get rid of dataset order bias
+ for (int j = i0; j < i1; j++)
+ std::swap(order[j], order[j + rng2.rand_int(i1 - j)]);
+
+ bool interrupt = false;
+ bool degree_based_prune = true;
+ std::vector<int> degree_distribution;
+ int degree_threshold;
+ if (degree_based_prune) {
+ // Read degree distribution file - contains one degree per line
+ // Line number corresponds to node ID (0-indexed)
+ // std::ifstream file(
+ // "/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/degree_distribution.txt");
+ std::ifstream file(
+ "/powerrag/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki_1M/1-shards/indices/hnsw_IP_M32_efC256/degree_distribution.txt");
+ std::string line;
+
+ // Read all degrees into the vector
+ while (std::getline(file, line)) {
+ degree_distribution.push_back(std::stoi(line));
+ }
+ // Create a copy of the degree distribution to find the
+ // threshold
+ std::vector<int> sorted_degrees = degree_distribution;
+ std::sort(
+ sorted_degrees.begin(),
+ sorted_degrees.end(),
+ std::greater<int>());
+
+ // Find the degree threshold for top 10%
+ int threshold_index =
+ std::max(0, int(sorted_degrees.size() * 0.02) - 1);
+ degree_threshold = sorted_degrees[threshold_index];
+ printf("Degree threshold: %d\n", degree_threshold);
+ }
+
+#pragma omp parallel if (i1 > i0 + 100)
+ {
+ VisitedTable vt(ntotal);
+
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(index_hnsw.storage));
+ int prev_display =
+ verbose && omp_get_thread_num() == 0 ? 0 : -1;
+ size_t counter = 0;
+
+ // here we should do schedule(dynamic) but this segfaults for
+ // some versions of LLVM. The performance impact should not be
+ // too large when (i1 - i0) / num_threads >> 1
+#pragma omp for schedule(static)
+ for (int i = i0; i < i1; i++) {
+ storage_idx_t pt_id = order[i];
+ bool prune = false;
+ if (pt_level == 0 && prune) {
+ if (!degree_based_prune) {
+ // printf("i: %d, order[i]: %d\n", i, order[i]);
+ float r = rng2.rand_float(); // Assuming rng is
+ // accessible here
+ if (r < 0.95) { // 90% probability
+ hnsw.ems[pt_id] = std::max(
+ 4,
+ 1); // Reduce to M/8 but at least 1
+ }
+ } else {
+ // get pid degree first and combine with the
+ // threshold
+ // TODO: can design a better heruistic here instead
+ // of simply cut the top 10% let me think about it
+ int pid_degree = degree_distribution[pt_id];
+ if (pid_degree < degree_threshold) {
+ // random 6 or 7
+ int random_num = rng2.rand_int(2);
+ hnsw.ems[pt_id] = std::max(6 + random_num, 1);
+ } else {
+ hnsw.ems[pt_id] = M;
+ }
+ }
+ }
+ dis->set_query(x + (pt_id - n0) * d);
+
+ // cannot break
+ if (interrupt) {
+ continue;
+ }
+
+ hnsw.add_with_locks(
+ *dis,
+ pt_level,
+ pt_id,
+ locks,
+ vt,
+ index_hnsw.keep_max_size_level0 && (pt_level == 0));
+
+ if (prev_display >= 0 && i - i0 > prev_display + 10000) {
+ prev_display = i - i0;
+ printf(" %d / %d\r", i - i0, i1 - i0);
+ fflush(stdout);
+ }
+ if (counter % check_period == 0) {
+ if (InterruptCallback::is_interrupted()) {
+ interrupt = true;
+ }
+ }
+ counter++;
+ }
+ }
+ if (interrupt) {
+ FAISS_THROW_MSG("computation interrupted");
+ }
+ i1 = i0;
+ }
+ if (index_hnsw.init_level0) {
+ FAISS_ASSERT(i1 == 0);
+ } else {
+ FAISS_ASSERT((i1 - hist[0]) == 0);
+ }
+ }
+ if (verbose) {
+ printf("Done in %.3f ms\n", getmillisecs() - t0);
+ }
+
+ for (int i = 0; i < ntotal; i++) {
+ omp_destroy_lock(&locks[i]);
+ }
+
+ // hnsw.delete_random_level0_edges_minimal(0.5);
+ // index_hnsw.save_edge_stats("edge_stats.txt");
+}
+
+} // namespace
+
+/**************************************************************
+ * IndexHNSW implementation
+ **************************************************************/
+
+IndexHNSW::IndexHNSW(int d, int M, MetricType metric, int M0)
+ : Index(d, metric), hnsw(M, M0) {
+ // Initialize the fetch counter
+ fetch_count_ptr = new std::atomic<size_t>(0);
+}
+
+IndexHNSW::IndexHNSW(Index* storage, int M, int M0)
+ : Index(storage->d, storage->metric_type),
+ hnsw(M, M0),
+ storage(storage) {
+ metric_arg = storage->metric_arg;
+ // Initialize the fetch counter
+ fetch_count_ptr = new std::atomic<size_t>(0);
+}
+
+IndexHNSW::~IndexHNSW() {
+ if (own_fields) {
+ delete storage;
+ }
+ // Delete the fetch counter
+ delete fetch_count_ptr;
+}
+
+void IndexHNSW::train(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexHNSWFlat (or variants) instead of IndexHNSW directly");
+ // hnsw structure does not require training
+ storage->train(n, x);
+ is_trained = true;
+}
+
+namespace {
+
+template <class BlockResultHandler>
+void hnsw_search(
+ const IndexHNSW* index,
+ idx_t n,
+ const float* x,
+ BlockResultHandler& bres,
+ const SearchParameters* params) {
+ // FAISS_THROW_IF_NOT_MSG(
+ // index->storage,
+ // "No storage index, please use IndexHNSWFlat (or variants) "
+ // "instead of IndexHNSW directly");
+ const HNSW& hnsw = index->hnsw;
+
+ // ---- Addition: Reset total fetch count at the beginning of search ----
+ // Ensure the pointer is valid before dereferencing
+ if (index->fetch_count_ptr) {
+ index->fetch_count_ptr->store(0, std::memory_order_relaxed);
+ }
+ // ---- End Addition ----
+
+ int efSearch = hnsw.efSearch;
+ int zmq_port = 5557;
+ if (params) {
+ if (const SearchParametersHNSW* hnsw_params =
+ dynamic_cast<const SearchParametersHNSW*>(params)) {
+ efSearch = hnsw_params->efSearch;
+ zmq_port = hnsw_params->zmq_port;
+ }
+ }
+ size_t n1 = 0, n2 = 0, ndis = 0, nhops = 0;
+
+ std::unordered_map<idx_t, size_t> node_visit_counts;
+
+ // ---- Addition: Accumulator for fetch counts ----
+ size_t total_fetches_accum = 0;
+ // ---- End Addition ----
+
+ idx_t check_period = InterruptCallback::get_period_hint(
+ hnsw.max_level * index->d * efSearch);
+
+ for (idx_t i0 = 0; i0 < n; i0 += check_period) {
+ idx_t i1 = std::min(i0 + check_period, n);
+
+#pragma omp parallel if (i1 - i0 > 1)
+ {
+ VisitedTable vt(index->ntotal);
+ typename BlockResultHandler::SingleResultHandler res(bres);
+
+ // Select the appropriate distance computer based on use_recompute
+ // flag
+ std::unique_ptr<DistanceComputer> dis;
+ if (index->is_recompute) {
+ // Use ZmqDistanceComputer for recomputation
+ dis.reset(new ZmqDistanceComputer(
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ zmq_port));
+ } else {
+ // Use standard distance computer
+ dis.reset(storage_distance_computer(index->storage));
+ }
+
+#pragma omp for reduction(+ : n1, n2, ndis, nhops, total_fetches_accum) \
+ schedule(guided)
+ for (idx_t i = i0; i < i1; i++) {
+ res.begin(i);
+ dis->set_query(x + i * index->d);
+
+ HNSWStats stats = hnsw.search(*dis, res, vt, params, index);
+ n1 += stats.n1;
+ n2 += stats.n2;
+ ndis += stats.ndis;
+ nhops += stats.nhops;
+
+ // ---- Addition: Accumulate fetch count ----
+ total_fetches_accum += dis->get_fetch_count();
+ // ---- End Addition ----
+
+ res.end();
+ }
+ }
+
+ // ---- Addition: Update the index's total count ----
+ // Use += because the search might be split over multiple check_period
+ // iterations
+ if (index->fetch_count_ptr) {
+ index->fetch_count_ptr->fetch_add(
+ total_fetches_accum, std::memory_order_relaxed);
+ }
+ // ---- End Addition ----
+
+ InterruptCallback::check();
+ }
+
+ HNSWStats hnsw_stats{n1, n2, ndis, nhops};
+ hnsw_stats.combine(hnsw_stats);
+}
+
+} // anonymous namespace
+
+void IndexHNSW::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+
+ using RH = HeapBlockResultHandler<HNSW::C>;
+ RH bres(n, distances, labels, k);
+
+ hnsw_search(this, n, x, bres, params);
+
+ if (is_similarity_metric(this->metric_type)) {
+ // we need to revert the negated distances
+ for (size_t i = 0; i < k * n; i++) {
+ distances[i] = -distances[i];
+ }
+ }
+}
+
+void IndexHNSW::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ using RH = RangeSearchBlockResultHandler<HNSW::C>;
+ RH bres(result, is_similarity_metric(metric_type) ? -radius : radius);
+
+ hnsw_search(this, n, x, bres, params);
+
+ if (is_similarity_metric(this->metric_type)) {
+ // we need to revert the negated distances
+ for (size_t i = 0; i < result->lims[result->nq]; i++) {
+ result->distances[i] = -result->distances[i];
+ }
+ }
+}
+
+void IndexHNSW::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexHNSWFlat (or variants) instead of IndexHNSW directly");
+ FAISS_THROW_IF_NOT(is_trained);
+ int n0 = ntotal;
+ storage->add(n, x);
+ ntotal = storage->ntotal;
+
+ hnsw_add_vertices(*this, n0, n, x, verbose, hnsw.levels.size() == ntotal);
+}
+
+void IndexHNSW::reset() {
+ hnsw.reset();
+ storage->reset();
+ ntotal = 0;
+}
+
+void IndexHNSW::reconstruct(idx_t key, float* recons) const {
+ if (is_recompute) {
+ ZmqDistanceComputer fetcher(storage);
+ const float* vec = fetcher.get_vector_zmq(key);
+ assert(vec);
+ memcpy(recons, vec, d * sizeof(float));
+ } else {
+ storage->reconstruct(key, recons);
+ }
+}
+
+/**************************************************************
+ * This section of functions were used during the development of HNSW support.
+ * They may be useful in the future but are dormant for now, and thus are not
+ * unit tested at the moment.
+ * shrink_level_0_neighbors
+ * search_level_0
+ * init_level_0_from_knngraph
+ * init_level_0_from_entry_points
+ * reorder_links
+ * link_singletons
+ **************************************************************/
+void IndexHNSW::shrink_level_0_neighbors(int new_size) {
+#pragma omp parallel
+ {
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+#pragma omp for
+ for (idx_t i = 0; i < ntotal; i++) {
+ size_t begin, end;
+ hnsw.neighbor_range(i, 0, &begin, &end);
+
+ std::priority_queue<NodeDistFarther> initial_list;
+
+ for (size_t j = begin; j < end; j++) {
+ int v1 = hnsw.neighbors[j];
+ if (v1 < 0)
+ break;
+ initial_list.emplace(dis->symmetric_dis(i, v1), v1);
+
+ // initial_list.emplace(qdis(v1), v1);
+ }
+
+ std::vector<NodeDistFarther> shrunk_list;
+ HNSW::shrink_neighbor_list(
+ *dis, initial_list, shrunk_list, new_size);
+
+ for (size_t j = begin; j < end; j++) {
+ if (j - begin < shrunk_list.size())
+ hnsw.neighbors[j] = shrunk_list[j - begin].id;
+ else
+ hnsw.neighbors[j] = -1;
+ }
+ }
+ }
+}
+
+void IndexHNSW::search_level_0(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const storage_idx_t* nearest,
+ const float* nearest_d,
+ float* distances,
+ idx_t* labels,
+ int nprobe,
+ int search_type,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ storage_idx_t ntotal = hnsw.levels.size();
+
+ using RH = HeapBlockResultHandler<HNSW::C>;
+ RH bres(n, distances, labels, k);
+
+#pragma omp parallel
+ {
+ std::unique_ptr<DistanceComputer> qdis(
+ storage_distance_computer(storage));
+ HNSWStats search_stats;
+ VisitedTable vt(ntotal);
+ RH::SingleResultHandler res(bres);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ res.begin(i);
+ qdis->set_query(x + i * d);
+
+ hnsw.search_level_0(
+ *qdis.get(),
+ res,
+ nprobe,
+ nearest + i * nprobe,
+ nearest_d + i * nprobe,
+ search_type,
+ search_stats,
+ vt,
+ params);
+ res.end();
+ vt.advance();
+ }
+#pragma omp critical
+ {
+ hnsw_stats.combine(search_stats);
+ }
+ }
+ if (is_similarity_metric(this->metric_type)) {
+// we need to revert the negated distances
+#pragma omp parallel for
+ for (int64_t i = 0; i < k * n; i++) {
+ distances[i] = -distances[i];
+ }
+ }
+}
+
+void IndexHNSW::init_level_0_from_knngraph(
+ int k,
+ const float* D,
+ const idx_t* I) {
+ int dest_size = hnsw.nb_neighbors(0);
+
+#pragma omp parallel for
+ for (idx_t i = 0; i < ntotal; i++) {
+ DistanceComputer* qdis = storage_distance_computer(storage);
+ std::vector<float> vec(d);
+ storage->reconstruct(i, vec.data());
+ qdis->set_query(vec.data());
+
+ std::priority_queue<NodeDistFarther> initial_list;
+
+ for (size_t j = 0; j < k; j++) {
+ int v1 = I[i * k + j];
+ if (v1 == i)
+ continue;
+ if (v1 < 0)
+ break;
+ initial_list.emplace(D[i * k + j], v1);
+ }
+
+ std::vector<NodeDistFarther> shrunk_list;
+ HNSW::shrink_neighbor_list(*qdis, initial_list, shrunk_list, dest_size);
+
+ size_t begin, end;
+ hnsw.neighbor_range(i, 0, &begin, &end);
+
+ for (size_t j = begin; j < end; j++) {
+ if (j - begin < shrunk_list.size())
+ hnsw.neighbors[j] = shrunk_list[j - begin].id;
+ else
+ hnsw.neighbors[j] = -1;
+ }
+ }
+}
+
+void IndexHNSW::init_level_0_from_entry_points(
+ int n,
+ const storage_idx_t* points,
+ const storage_idx_t* nearests) {
+ std::vector<omp_lock_t> locks(ntotal);
+ for (int i = 0; i < ntotal; i++)
+ omp_init_lock(&locks[i]);
+
+#pragma omp parallel
+ {
+ VisitedTable vt(ntotal);
+
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+ std::vector<float> vec(storage->d);
+
+#pragma omp for schedule(dynamic)
+ for (int i = 0; i < n; i++) {
+ storage_idx_t pt_id = points[i];
+ storage_idx_t nearest = nearests[i];
+ storage->reconstruct(pt_id, vec.data());
+ dis->set_query(vec.data());
+
+ hnsw.add_links_starting_from(
+ *dis, pt_id, nearest, (*dis)(nearest), 0, locks.data(), vt);
+
+ if (verbose && i % 10000 == 0) {
+ printf(" %d / %d\r", i, n);
+ fflush(stdout);
+ }
+ }
+ }
+ if (verbose) {
+ printf("\n");
+ }
+
+ for (int i = 0; i < ntotal; i++)
+ omp_destroy_lock(&locks[i]);
+}
+
+void IndexHNSW::reorder_links() {
+ int M = hnsw.nb_neighbors(0);
+
+#pragma omp parallel
+ {
+ std::vector<float> distances(M);
+ std::vector<size_t> order(M);
+ std::vector<storage_idx_t> tmp(M);
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+#pragma omp for
+ for (storage_idx_t i = 0; i < ntotal; i++) {
+ size_t begin, end;
+ hnsw.neighbor_range(i, 0, &begin, &end);
+
+ for (size_t j = begin; j < end; j++) {
+ storage_idx_t nj = hnsw.neighbors[j];
+ if (nj < 0) {
+ end = j;
+ break;
+ }
+ distances[j - begin] = dis->symmetric_dis(i, nj);
+ tmp[j - begin] = nj;
+ }
+
+ fvec_argsort(end - begin, distances.data(), order.data());
+ for (size_t j = begin; j < end; j++) {
+ hnsw.neighbors[j] = tmp[order[j - begin]];
+ }
+ }
+ }
+}
+
+void IndexHNSW::link_singletons() {
+ printf("search for singletons\n");
+
+ std::vector<bool> seen(ntotal);
+
+ for (size_t i = 0; i < ntotal; i++) {
+ size_t begin, end;
+ hnsw.neighbor_range(i, 0, &begin, &end);
+ for (size_t j = begin; j < end; j++) {
+ storage_idx_t ni = hnsw.neighbors[j];
+ if (ni >= 0)
+ seen[ni] = true;
+ }
+ }
+
+ int n_sing = 0, n_sing_l1 = 0;
+ std::vector<storage_idx_t> singletons;
+ for (storage_idx_t i = 0; i < ntotal; i++) {
+ if (!seen[i]) {
+ singletons.push_back(i);
+ n_sing++;
+ if (hnsw.levels[i] > 1)
+ n_sing_l1++;
+ }
+ }
+
+ printf(" Found %d / %" PRId64 " singletons (%d appear in a level above)\n",
+ n_sing,
+ ntotal,
+ n_sing_l1);
+
+ std::vector<float> recons(singletons.size() * d);
+ for (int i = 0; i < singletons.size(); i++) {
+ FAISS_ASSERT(!"not implemented");
+ }
+}
+
+void IndexHNSW::permute_entries(const idx_t* perm) {
+ auto flat_storage = dynamic_cast<IndexFlatCodes*>(storage);
+ FAISS_THROW_IF_NOT_MSG(
+ flat_storage, "don't know how to permute this index");
+ flat_storage->permute_entries(perm);
+ hnsw.permute_entries(perm);
+}
+
+DistanceComputer* IndexHNSW::get_distance_computer() const {
+ if (is_recompute) {
+ return new ZmqDistanceComputer(
+ this->d, this->metric_type, this->metric_arg);
+ } else {
+ return storage->get_distance_computer();
+ }
+}
+
+// ---- Addition: Implement method to get fetch count ----
+size_t IndexHNSW::get_last_total_fetch_count() const {
+ // Safety check in case the pointer is null
+ if (!fetch_count_ptr) {
+ return 0;
+ }
+ // Use load() for atomic read, although direct read might be okay on many
+ // platforms
+ return fetch_count_ptr->load(std::memory_order_relaxed);
+}
+// ---- End Addition ----
+
+/**************************************************************
+ * IndexHNSWFlat implementation
+ **************************************************************/
+
+IndexHNSWFlat::IndexHNSWFlat() {
+ is_trained = true;
+}
+
+IndexHNSWFlat::IndexHNSWFlat(int d, int M, MetricType metric, int M0)
+ : IndexHNSW(
+ (metric == METRIC_L2) ? new IndexFlatL2(d)
+ : new IndexFlat(d, metric),
+ M,
+ M0) {
+ own_fields = true;
+ is_trained = true;
+}
+
+/**************************************************************
+ * IndexHNSWPQ implementation
+ **************************************************************/
+
+IndexHNSWPQ::IndexHNSWPQ() = default;
+
+IndexHNSWPQ::IndexHNSWPQ(
+ int d,
+ int pq_m,
+ int M,
+ int pq_nbits,
+ MetricType metric)
+ : IndexHNSW(new IndexPQ(d, pq_m, pq_nbits, metric), M) {
+ own_fields = true;
+ is_trained = false;
+}
+
+void IndexHNSWPQ::train(idx_t n, const float* x) {
+ IndexHNSW::train(n, x);
+ (dynamic_cast<IndexPQ*>(storage))->pq.compute_sdc_table();
+}
+
+/**************************************************************
+ * IndexHNSWSQ implementation
+ **************************************************************/
+
+IndexHNSWSQ::IndexHNSWSQ(
+ int d,
+ ScalarQuantizer::QuantizerType qtype,
+ int M,
+ MetricType metric)
+ : IndexHNSW(new IndexScalarQuantizer(d, qtype, metric), M) {
+ is_trained = this->storage->is_trained;
+ own_fields = true;
+}
+
+IndexHNSWSQ::IndexHNSWSQ() = default;
+
+/**************************************************************
+ * IndexHNSW2Level implementation
+ **************************************************************/
+
+IndexHNSW2Level::IndexHNSW2Level(
+ Index* quantizer,
+ size_t nlist,
+ int m_pq,
+ int M)
+ : IndexHNSW(new Index2Layer(quantizer, nlist, m_pq), M) {
+ own_fields = true;
+ is_trained = false;
+}
+
+IndexHNSW2Level::IndexHNSW2Level() = default;
+
+namespace {
+
+// same as search_from_candidates but uses v
+// visno -> is in result list
+// visno + 1 -> in result list + in candidates
+int search_from_candidates_2(
+ const HNSW& hnsw,
+ DistanceComputer& qdis,
+ int k,
+ idx_t* I,
+ float* D,
+ MinimaxHeap& candidates,
+ VisitedTable& vt,
+ HNSWStats& stats,
+ int level,
+ int nres_in = 0) {
+ int nres = nres_in;
+ for (int i = 0; i < candidates.size(); i++) {
+ idx_t v1 = candidates.ids[i];
+ FAISS_ASSERT(v1 >= 0);
+ vt.visited[v1] = vt.visno + 1;
+ }
+
+ int nstep = 0;
+
+ while (candidates.size() > 0) {
+ float d0 = 0;
+ int v0 = candidates.pop_min(&d0);
+
+ size_t begin, end;
+ hnsw.neighbor_range(v0, level, &begin, &end);
+
+ for (size_t j = begin; j < end; j++) {
+ int v1 = hnsw.neighbors[j];
+ if (v1 < 0)
+ break;
+ if (vt.visited[v1] == vt.visno + 1) {
+ // nothing to do
+ } else {
+ float d = qdis(v1);
+ candidates.push(v1, d);
+
+ // never seen before --> add to heap
+ if (vt.visited[v1] < vt.visno) {
+ if (nres < k) {
+ faiss::maxheap_push(++nres, D, I, d, v1);
+ } else if (d < D[0]) {
+ faiss::maxheap_replace_top(nres, D, I, d, v1);
+ }
+ }
+ vt.visited[v1] = vt.visno + 1;
+ }
+ }
+
+ nstep++;
+ if (nstep > hnsw.efSearch) {
+ break;
+ }
+ }
+
+ stats.n1++;
+ if (candidates.size() == 0)
+ stats.n2++;
+
+ return nres;
+}
+
+} // namespace
+
+void IndexHNSW2Level::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+
+ if (dynamic_cast<const Index2Layer*>(storage)) {
+ IndexHNSW::search(n, x, k, distances, labels);
+
+ } else { // "mixed" search
+ size_t n1 = 0, n2 = 0, ndis = 0, nhops = 0;
+
+ const IndexIVFPQ* index_ivfpq =
+ dynamic_cast<const IndexIVFPQ*>(storage);
+
+ int nprobe = index_ivfpq->nprobe;
+
+ std::unique_ptr<idx_t[]> coarse_assign(new idx_t[n * nprobe]);
+ std::unique_ptr<float[]> coarse_dis(new float[n * nprobe]);
+
+ index_ivfpq->quantizer->search(
+ n, x, nprobe, coarse_dis.get(), coarse_assign.get());
+
+ index_ivfpq->search_preassigned(
+ n,
+ x,
+ k,
+ coarse_assign.get(),
+ coarse_dis.get(),
+ distances,
+ labels,
+ false);
+
+#pragma omp parallel
+ {
+ VisitedTable vt(ntotal);
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+ constexpr int candidates_size = 1;
+ MinimaxHeap candidates(candidates_size);
+
+#pragma omp for reduction(+ : n1, n2, ndis, nhops)
+ for (idx_t i = 0; i < n; i++) {
+ idx_t* idxi = labels + i * k;
+ float* simi = distances + i * k;
+ dis->set_query(x + i * d);
+
+ // mark all inverted list elements as visited
+
+ for (int j = 0; j < nprobe; j++) {
+ idx_t key = coarse_assign[j + i * nprobe];
+ if (key < 0)
+ break;
+ size_t list_length = index_ivfpq->get_list_size(key);
+ const idx_t* ids = index_ivfpq->invlists->get_ids(key);
+
+ for (int jj = 0; jj < list_length; jj++) {
+ vt.set(ids[jj]);
+ }
+ }
+
+ candidates.clear();
+
+ for (int j = 0; j < k; j++) {
+ if (idxi[j] < 0)
+ break;
+ candidates.push(idxi[j], simi[j]);
+ }
+
+ // reorder from sorted to heap
+ maxheap_heapify(k, simi, idxi, simi, idxi, k);
+
+ HNSWStats search_stats;
+ search_from_candidates_2(
+ hnsw,
+ *dis,
+ k,
+ idxi,
+ simi,
+ candidates,
+ vt,
+ search_stats,
+ 0,
+ k);
+ n1 += search_stats.n1;
+ n2 += search_stats.n2;
+ ndis += search_stats.ndis;
+ nhops += search_stats.nhops;
+
+ vt.advance();
+ vt.advance();
+
+ maxheap_reorder(k, simi, idxi);
+ }
+ }
+
+ hnsw_stats.combine({n1, n2, ndis, nhops});
+ }
+}
+
+void IndexHNSW2Level::flip_to_ivf() {
+ Index2Layer* storage2l = dynamic_cast<Index2Layer*>(storage);
+
+ FAISS_THROW_IF_NOT(storage2l);
+
+ IndexIVFPQ* index_ivfpq = new IndexIVFPQ(
+ storage2l->q1.quantizer,
+ d,
+ storage2l->q1.nlist,
+ storage2l->pq.M,
+ 8);
+ index_ivfpq->pq = storage2l->pq;
+ index_ivfpq->is_trained = storage2l->is_trained;
+ index_ivfpq->precompute_table();
+ index_ivfpq->own_fields = storage2l->q1.own_fields;
+ storage2l->transfer_to_IVFPQ(*index_ivfpq);
+ index_ivfpq->make_direct_map(true);
+
+ storage = index_ivfpq;
+ delete storage2l;
+}
+
+/**************************************************************
+ * IndexHNSWCagra implementation
+ **************************************************************/
+
+IndexHNSWCagra::IndexHNSWCagra() {
+ is_trained = true;
+}
+
+IndexHNSWCagra::IndexHNSWCagra(int d, int M, MetricType metric)
+ : IndexHNSW(
+ (metric == METRIC_L2)
+ ? static_cast<IndexFlat*>(new IndexFlatL2(d))
+ : static_cast<IndexFlat*>(new IndexFlatIP(d)),
+ M) {
+ FAISS_THROW_IF_NOT_MSG(
+ ((metric == METRIC_L2) || (metric == METRIC_INNER_PRODUCT)),
+ "unsupported metric type for IndexHNSWCagra");
+ own_fields = true;
+ is_trained = true;
+ init_level0 = true;
+ keep_max_size_level0 = true;
+}
+
+void IndexHNSWCagra::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ !base_level_only,
+ "Cannot add vectors when base_level_only is set to True");
+
+ IndexHNSW::add(n, x);
+}
+
+void IndexHNSWCagra::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ if (!base_level_only) {
+ IndexHNSW::search(n, x, k, distances, labels, params);
+ } else {
+ std::vector<storage_idx_t> nearest(n);
+ std::vector<float> nearest_d(n);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(this->storage));
+ dis->set_query(x + i * d);
+ nearest[i] = -1;
+ nearest_d[i] = std::numeric_limits<float>::max();
+
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<idx_t> distrib(0, this->ntotal - 1);
+
+ for (idx_t j = 0; j < num_base_level_search_entrypoints; j++) {
+ auto idx = distrib(gen);
+ auto distance = (*dis)(idx);
+ if (distance < nearest_d[i]) {
+ nearest[i] = idx;
+ nearest_d[i] = distance;
+ }
+ }
+ FAISS_THROW_IF_NOT_MSG(
+ nearest[i] >= 0, "Could not find a valid entrypoint.");
+ }
+
+ search_level_0(
+ n,
+ x,
+ k,
+ nearest.data(),
+ nearest_d.data(),
+ distances,
+ labels,
+ 1, // n_probes
+ 1, // search_type
+ params);
+ }
+}
+
+// Save edge statistics for the HNSW graph
+void IndexHNSW::save_edge_stats(const char* filename) const {
+ if (ntotal == 0) {
+ printf("No edges to save - index is empty\n");
+ return;
+ }
+
+ FILE* f = fopen(filename, "w");
+ if (!f) {
+ fprintf(stderr, "Could not open %s for writing\n", filename);
+ return;
+ }
+
+ // Write header
+ fprintf(f, "src,dst,level,distance\n");
+
+ // Create a distance computer for calculating distances
+ std::unique_ptr<DistanceComputer> dis(storage_distance_computer(storage));
+
+ size_t edge_count = 0;
+
+ // Iterate through all nodes and their neighbors at each level
+ for (storage_idx_t src = 0; src < ntotal; src++) {
+ int node_level = hnsw.levels[src];
+
+ // For each level the node exists in
+ for (int level = 0; level < node_level; level++) {
+ if (level != 0) {
+ continue; // Only process level 0 for now
+ }
+
+ size_t begin, end;
+ hnsw.neighbor_range(src, level, &begin, &end);
+
+ // For each neighbor at this level
+ for (size_t j = begin; j < end; j++) {
+ storage_idx_t dst = hnsw.neighbors[j];
+ if (dst < 0)
+ break; // End of neighbors list
+
+ // Calculate distance between src and dst
+ float distance = dis->symmetric_dis(src, dst);
+
+ // Write to file: src,dst,level,distance
+ fprintf(f,
+ "%d,%d,%d,%f\n",
+ (int)src,
+ (int)dst,
+ level,
+ distance);
+ edge_count++;
+ }
+ }
+
+ // Print progress every 10000 nodes
+ if (src % 10000 == 0 && src > 0) {
+ printf("Processed %d/%d nodes, %zu edges so far\r",
+ (int)src,
+ (int)ntotal,
+ edge_count);
+ fflush(stdout);
+ }
+ }
+
+ fclose(f);
+ printf("\nSaved statistics for %zu edges to %s\n", edge_count, filename);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexHNSW.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexHNSW.h
new file mode 100644
index 0000000..aa041d7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexHNSW.h
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <atomic>
+#include <vector>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/impl/HNSW.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+struct IndexHNSW;
+
+/** The HNSW index is a normal random-access index with a HNSW
+ * link structure built on top */
+
+struct IndexHNSW : Index {
+ typedef HNSW::storage_idx_t storage_idx_t;
+
+ // the link structure
+ HNSW hnsw;
+
+ // the sequential storage
+ bool own_fields = false;
+ Index* storage = nullptr;
+
+ // When set to false, level 0 in the knn graph is not initialized.
+ // This option is used by GpuIndexCagra::copyTo(IndexHNSWCagra*)
+ // as level 0 knn graph is copied over from the index built by
+ // GpuIndexCagra.
+ bool init_level0 = true;
+
+ // When set to true, all neighbors in level 0 are filled up
+ // to the maximum size allowed (2 * M). This option is used by
+ // IndexHHNSWCagra to create a full base layer graph that is
+ // used when GpuIndexCagra::copyFrom(IndexHNSWCagra*) is invoked.
+ bool keep_max_size_level0 = false;
+
+ // ---- Modifications for atomic counter ----
+ // Instead of a direct std::atomic member (which can't be copied),
+ // use a pointer to an atomic. The pointer can be copied, and each
+ // copy gets its own atomic counter.
+ mutable std::atomic<size_t>* fetch_count_ptr = nullptr;
+
+ bool is_recompute = false;
+
+ // ---- Experimental top degree disk read feature ----
+ std::string experimental_disk_storage_path = "";
+ off_t experimental_disk_data_offset = -1;
+
+ explicit IndexHNSW(
+ int d = 0,
+ int M = 32,
+ MetricType metric = METRIC_L2,
+ int M0 = -1);
+ explicit IndexHNSW(Index* storage, int M = 32, int M0 = -1);
+
+ ~IndexHNSW() override;
+
+ void add(idx_t n, const float* x) override;
+
+ /// Trains the storage if needed
+ void train(idx_t n, const float* x) override;
+
+ /// entry point for search
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ void reset() override;
+
+ void shrink_level_0_neighbors(int size);
+
+ /** Perform search only on level 0, given the starting points for
+ * each vertex.
+ *
+ * @param search_type 1:perform one search per nprobe, 2: enqueue
+ * all entry points
+ */
+ void search_level_0(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const storage_idx_t* nearest,
+ const float* nearest_d,
+ float* distances,
+ idx_t* labels,
+ int nprobe = 1,
+ int search_type = 1,
+ const SearchParameters* params = nullptr) const;
+
+ /// alternative graph building
+ void init_level_0_from_knngraph(int k, const float* D, const idx_t* I);
+
+ /// alternative graph building
+ void init_level_0_from_entry_points(
+ int npt,
+ const storage_idx_t* points,
+ const storage_idx_t* nearests);
+
+ // reorder links from nearest to farthest
+ void reorder_links();
+
+ void link_singletons();
+
+ void permute_entries(const idx_t* perm);
+
+ DistanceComputer* get_distance_computer() const override;
+
+ /// Get the total number of vector fetches performed during the last search.
+ size_t get_last_total_fetch_count() const;
+
+ void save_edge_stats(const char* filename) const;
+};
+
+/** Flat index topped with with a HNSW structure to access elements
+ * more efficiently.
+ */
+
+struct IndexHNSWFlat : IndexHNSW {
+ IndexHNSWFlat();
+ IndexHNSWFlat(int d, int M, MetricType metric = METRIC_L2, int M0 = -1);
+};
+
+/** PQ index topped with with a HNSW structure to access elements
+ * more efficiently.
+ */
+struct IndexHNSWPQ : IndexHNSW {
+ IndexHNSWPQ();
+ IndexHNSWPQ(
+ int d,
+ int pq_m,
+ int M,
+ int pq_nbits = 8,
+ MetricType metric = METRIC_L2);
+ void train(idx_t n, const float* x) override;
+};
+
+/** SQ index topped with a HNSW structure to access elements
+ * more efficiently.
+ */
+struct IndexHNSWSQ : IndexHNSW {
+ IndexHNSWSQ();
+ IndexHNSWSQ(
+ int d,
+ ScalarQuantizer::QuantizerType qtype,
+ int M,
+ MetricType metric = METRIC_L2);
+};
+
+/** 2-level code structure with fast random access
+ */
+struct IndexHNSW2Level : IndexHNSW {
+ IndexHNSW2Level();
+ IndexHNSW2Level(Index* quantizer, size_t nlist, int m_pq, int M);
+
+ void flip_to_ivf();
+
+ /// entry point for search
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+};
+
+struct IndexHNSWCagra : IndexHNSW {
+ IndexHNSWCagra();
+ IndexHNSWCagra(int d, int M, MetricType metric = METRIC_L2);
+
+ /// When set to true, the index is immutable.
+ /// This option is used to copy the knn graph from GpuIndexCagra
+ /// to the base level of IndexHNSWCagra without adding upper levels.
+ /// Doing so enables to search the HNSW index, but removes the
+ /// ability to add vectors.
+ bool base_level_only = false;
+
+ /// When `base_level_only` is set to `True`, the search function
+ /// searches only the base level knn graph of the HNSW index.
+ /// This parameter selects the entry point by randomly selecting
+ /// some points and using the best one.
+ int num_base_level_search_entrypoints = 32;
+
+ void add(idx_t n, const float* x) override;
+
+ /// Initialize or re-initialize the atomic counter
+ void init_counter() {
+ // Delete any existing counter first
+ if (fetch_count_ptr) {
+ delete fetch_count_ptr;
+ }
+ // Create a new atomic counter initialized to 0
+ fetch_count_ptr = new std::atomic<size_t>(0);
+ }
+
+ /// entry point for search
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIDMap.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIDMap.cpp
new file mode 100644
index 0000000..7c2a7ff
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIDMap.cpp
@@ -0,0 +1,304 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexIDMap.h>
+
+#include <cinttypes>
+#include <cstdint>
+#include <cstdio>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/WorkerThread.h>
+
+namespace faiss {
+
+namespace {
+
+// IndexBinary needs to update the code_size when d is set...
+
+void sync_d(Index* index) {}
+
+void sync_d(IndexBinary* index) {
+ FAISS_THROW_IF_NOT(index->d % 8 == 0);
+ index->code_size = index->d / 8;
+}
+
+} // anonymous namespace
+
+/*****************************************************
+ * IndexIDMap implementation
+ *******************************************************/
+
+template <typename IndexT>
+IndexIDMapTemplate<IndexT>::IndexIDMapTemplate(IndexT* index) : index(index) {
+ FAISS_THROW_IF_NOT_MSG(index->ntotal == 0, "index must be empty on input");
+ this->is_trained = index->is_trained;
+ this->metric_type = index->metric_type;
+ this->verbose = index->verbose;
+ this->d = index->d;
+ sync_d(this);
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::add(
+ idx_t,
+ const typename IndexT::component_t*) {
+ FAISS_THROW_MSG(
+ "add does not make sense with IndexIDMap, "
+ "use add_with_ids");
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::train(
+ idx_t n,
+ const typename IndexT::component_t* x) {
+ index->train(n, x);
+ this->is_trained = index->is_trained;
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::reset() {
+ index->reset();
+ id_map.clear();
+ this->ntotal = 0;
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::add_with_ids(
+ idx_t n,
+ const typename IndexT::component_t* x,
+ const idx_t* xids) {
+ index->add(n, x);
+ for (idx_t i = 0; i < n; i++)
+ id_map.push_back(xids[i]);
+ this->ntotal = index->ntotal;
+}
+
+template <typename IndexT>
+size_t IndexIDMapTemplate<IndexT>::sa_code_size() const {
+ return index->sa_code_size();
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::add_sa_codes(
+ idx_t n,
+ const uint8_t* codes,
+ const idx_t* xids) {
+ index->add_sa_codes(n, codes, xids);
+ for (idx_t i = 0; i < n; i++) {
+ id_map.push_back(xids[i]);
+ }
+ this->ntotal = index->ntotal;
+}
+
+namespace {
+
+/// RAII object to reset the IDSelector in the params object
+struct ScopedSelChange {
+ SearchParameters* params = nullptr;
+ IDSelector* old_sel = nullptr;
+
+ void set(SearchParameters* params_2, IDSelector* new_sel) {
+ this->params = params_2;
+ old_sel = params_2->sel;
+ params_2->sel = new_sel;
+ }
+ ~ScopedSelChange() {
+ if (params) {
+ params->sel = old_sel;
+ }
+ }
+};
+
+} // namespace
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::search(
+ idx_t n,
+ const typename IndexT::component_t* x,
+ idx_t k,
+ typename IndexT::distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ IDSelectorTranslated this_idtrans(this->id_map, nullptr);
+ ScopedSelChange sel_change;
+
+ if (params && params->sel) {
+ auto idtrans = dynamic_cast<const IDSelectorTranslated*>(params->sel);
+
+ if (!idtrans) {
+ /*
+ FAISS_THROW_IF_NOT_MSG(
+ idtrans,
+ "IndexIDMap requires an IDSelectorTranslated on input");
+ */
+ // then make an idtrans and force it into the SearchParameters
+ // (hence the const_cast)
+ auto params_non_const = const_cast<SearchParameters*>(params);
+ this_idtrans.sel = params->sel;
+ sel_change.set(params_non_const, &this_idtrans);
+ }
+ }
+ index->search(n, x, k, distances, labels, params);
+ idx_t* li = labels;
+#pragma omp parallel for
+ for (idx_t i = 0; i < n * k; i++) {
+ li[i] = li[i] < 0 ? li[i] : id_map[li[i]];
+ }
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::range_search(
+ idx_t n,
+ const typename IndexT::component_t* x,
+ typename IndexT::distance_t radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ if (params) {
+ SearchParameters internal_search_parameters;
+ IDSelectorTranslated id_selector_translated(id_map, params->sel);
+ internal_search_parameters.sel = &id_selector_translated;
+
+ index->range_search(n, x, radius, result, &internal_search_parameters);
+ } else {
+ index->range_search(n, x, radius, result);
+ }
+
+#pragma omp parallel for
+ for (idx_t i = 0; i < result->lims[result->nq]; i++) {
+ result->labels[i] = result->labels[i] < 0 ? result->labels[i]
+ : id_map[result->labels[i]];
+ }
+}
+
+template <typename IndexT>
+size_t IndexIDMapTemplate<IndexT>::remove_ids(const IDSelector& sel) {
+ // remove in sub-index first
+ IDSelectorTranslated sel2(id_map, &sel);
+ size_t nremove = index->remove_ids(sel2);
+
+ int64_t j = 0;
+ for (idx_t i = 0; i < this->ntotal; i++) {
+ if (sel.is_member(id_map[i])) {
+ // remove
+ } else {
+ id_map[j] = id_map[i];
+ j++;
+ }
+ }
+ FAISS_ASSERT(j == index->ntotal);
+ this->ntotal = j;
+ id_map.resize(this->ntotal);
+ return nremove;
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::check_compatible_for_merge(
+ const IndexT& otherIndex) const {
+ auto other = dynamic_cast<const IndexIDMapTemplate<IndexT>*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+ index->check_compatible_for_merge(*other->index);
+}
+
+template <typename IndexT>
+void IndexIDMapTemplate<IndexT>::merge_from(IndexT& otherIndex, idx_t add_id) {
+ check_compatible_for_merge(otherIndex);
+ auto other = static_cast<IndexIDMapTemplate<IndexT>*>(&otherIndex);
+ index->merge_from(*other->index);
+ for (size_t i = 0; i < other->id_map.size(); i++) {
+ id_map.push_back(other->id_map[i] + add_id);
+ }
+ other->id_map.resize(0);
+ this->ntotal = index->ntotal;
+ other->ntotal = 0;
+}
+
+template <typename IndexT>
+IndexIDMapTemplate<IndexT>::~IndexIDMapTemplate() {
+ if (own_fields)
+ delete index;
+}
+
+/*****************************************************
+ * IndexIDMap2 implementation
+ *******************************************************/
+
+template <typename IndexT>
+IndexIDMap2Template<IndexT>::IndexIDMap2Template(IndexT* index)
+ : IndexIDMapTemplate<IndexT>(index) {}
+
+template <typename IndexT>
+void IndexIDMap2Template<IndexT>::add_with_ids(
+ idx_t n,
+ const typename IndexT::component_t* x,
+ const idx_t* xids) {
+ size_t prev_ntotal = this->ntotal;
+ IndexIDMapTemplate<IndexT>::add_with_ids(n, x, xids);
+ for (size_t i = prev_ntotal; i < this->ntotal; i++) {
+ rev_map[this->id_map[i]] = i;
+ }
+}
+
+template <typename IndexT>
+void IndexIDMap2Template<IndexT>::check_consistency() const {
+ FAISS_THROW_IF_NOT(rev_map.size() == this->id_map.size());
+ FAISS_THROW_IF_NOT(this->id_map.size() == this->ntotal);
+ for (size_t i = 0; i < this->ntotal; i++) {
+ idx_t ii = rev_map.at(this->id_map[i]);
+ FAISS_THROW_IF_NOT(ii == i);
+ }
+}
+
+template <typename IndexT>
+void IndexIDMap2Template<IndexT>::merge_from(IndexT& otherIndex, idx_t add_id) {
+ size_t prev_ntotal = this->ntotal;
+ IndexIDMapTemplate<IndexT>::merge_from(otherIndex, add_id);
+ for (size_t i = prev_ntotal; i < this->ntotal; i++) {
+ rev_map[this->id_map[i]] = i;
+ }
+ static_cast<IndexIDMap2Template<IndexT>&>(otherIndex).rev_map.clear();
+}
+
+template <typename IndexT>
+void IndexIDMap2Template<IndexT>::construct_rev_map() {
+ rev_map.clear();
+ for (size_t i = 0; i < this->ntotal; i++) {
+ rev_map[this->id_map[i]] = i;
+ }
+}
+
+template <typename IndexT>
+size_t IndexIDMap2Template<IndexT>::remove_ids(const IDSelector& sel) {
+ // This is quite inefficient
+ size_t nremove = IndexIDMapTemplate<IndexT>::remove_ids(sel);
+ construct_rev_map();
+ return nremove;
+}
+
+template <typename IndexT>
+void IndexIDMap2Template<IndexT>::reconstruct(
+ idx_t key,
+ typename IndexT::component_t* recons) const {
+ try {
+ this->index->reconstruct(rev_map.at(key), recons);
+ } catch (const std::out_of_range&) {
+ FAISS_THROW_FMT("key %" PRId64 " not found", key);
+ }
+}
+
+// explicit template instantiations
+
+template struct IndexIDMapTemplate<Index>;
+template struct IndexIDMapTemplate<IndexBinary>;
+template struct IndexIDMap2Template<Index>;
+template struct IndexIDMap2Template<IndexBinary>;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIDMap.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIDMap.h
new file mode 100644
index 0000000..dd3887a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIDMap.h
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/impl/IDSelector.h>
+
+#include <unordered_map>
+#include <vector>
+
+namespace faiss {
+
+/** Index that translates search results to ids */
+template <typename IndexT>
+struct IndexIDMapTemplate : IndexT {
+ using component_t = typename IndexT::component_t;
+ using distance_t = typename IndexT::distance_t;
+
+ IndexT* index = nullptr; ///! the sub-index
+ bool own_fields = false; ///! whether pointers are deleted in destructo
+ std::vector<idx_t> id_map;
+
+ explicit IndexIDMapTemplate(IndexT* index);
+
+ /// @param xids if non-null, ids to store for the vectors (size n)
+ void add_with_ids(idx_t n, const component_t* x, const idx_t* xids)
+ override;
+
+ /// this will fail. Use add_with_ids
+ void add(idx_t n, const component_t* x) override;
+
+ void search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void train(idx_t n, const component_t* x) override;
+
+ void reset() override;
+
+ /// remove ids adapted to IndexFlat
+ size_t remove_ids(const IDSelector& sel) override;
+
+ void range_search(
+ idx_t n,
+ const component_t* x,
+ distance_t radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void merge_from(IndexT& otherIndex, idx_t add_id = 0) override;
+ void check_compatible_for_merge(const IndexT& otherIndex) const override;
+
+ size_t sa_code_size() const override;
+ void add_sa_codes(idx_t n, const uint8_t* x, const idx_t* xids) override;
+
+ ~IndexIDMapTemplate() override;
+ IndexIDMapTemplate() {
+ own_fields = false;
+ index = nullptr;
+ }
+};
+
+using IndexIDMap = IndexIDMapTemplate<Index>;
+using IndexBinaryIDMap = IndexIDMapTemplate<IndexBinary>;
+
+/** same as IndexIDMap but also provides an efficient reconstruction
+ * implementation via a 2-way index */
+template <typename IndexT>
+struct IndexIDMap2Template : IndexIDMapTemplate<IndexT> {
+ using component_t = typename IndexT::component_t;
+ using distance_t = typename IndexT::distance_t;
+
+ std::unordered_map<idx_t, idx_t> rev_map;
+
+ explicit IndexIDMap2Template(IndexT* index);
+
+ /// make the rev_map from scratch
+ void construct_rev_map();
+
+ void add_with_ids(idx_t n, const component_t* x, const idx_t* xids)
+ override;
+
+ size_t remove_ids(const IDSelector& sel) override;
+
+ void reconstruct(idx_t key, component_t* recons) const override;
+
+ /// check that the rev_map and the id_map are in sync
+ void check_consistency() const;
+
+ void merge_from(IndexT& otherIndex, idx_t add_id = 0) override;
+
+ ~IndexIDMap2Template() override {}
+ IndexIDMap2Template() {}
+};
+
+using IndexIDMap2 = IndexIDMap2Template<Index>;
+using IndexBinaryIDMap2 = IndexIDMap2Template<IndexBinary>;
+
+// IDSelector that translates the ids using an IDMap
+struct IDSelectorTranslated : IDSelector {
+ const std::vector<int64_t>& id_map;
+ const IDSelector* sel;
+
+ IDSelectorTranslated(
+ const std::vector<int64_t>& id_map,
+ const IDSelector* sel)
+ : id_map(id_map), sel(sel) {}
+
+ IDSelectorTranslated(IndexBinaryIDMap& index_idmap, const IDSelector* sel)
+ : id_map(index_idmap.id_map), sel(sel) {}
+
+ IDSelectorTranslated(IndexIDMap& index_idmap, const IDSelector* sel)
+ : id_map(index_idmap.id_map), sel(sel) {}
+
+ bool is_member(idx_t id) const override {
+ return sel->is_member(id_map[id]);
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVF.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVF.cpp
new file mode 100644
index 0000000..21819d8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVF.cpp
@@ -0,0 +1,1403 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexIVF.h>
+
+#include <omp.h>
+#include <cstdint>
+#include <memory>
+#include <mutex>
+
+#include <algorithm>
+#include <cinttypes>
+#include <cstdio>
+#include <limits>
+
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/CodePacker.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+
+namespace faiss {
+
+using ScopedIds = InvertedLists::ScopedIds;
+using ScopedCodes = InvertedLists::ScopedCodes;
+
+/*****************************************
+ * Level1Quantizer implementation
+ ******************************************/
+
+Level1Quantizer::Level1Quantizer(Index* quantizer, size_t nlist)
+ : quantizer(quantizer), nlist(nlist) {
+ // here we set a low # iterations because this is typically used
+ // for large clusterings (nb this is not used for the MultiIndex,
+ // for which quantizer_trains_alone = true)
+ cp.niter = 10;
+}
+
+Level1Quantizer::Level1Quantizer() = default;
+
+Level1Quantizer::~Level1Quantizer() {
+ if (own_fields) {
+ delete quantizer;
+ }
+}
+
+void Level1Quantizer::train_q1(
+ size_t n,
+ const float* x,
+ bool verbose,
+ MetricType metric_type) {
+ size_t d = quantizer->d;
+ if (quantizer->is_trained && (quantizer->ntotal == nlist)) {
+ if (verbose)
+ printf("IVF quantizer does not need training.\n");
+ } else if (quantizer_trains_alone == 1) {
+ if (verbose)
+ printf("IVF quantizer trains alone...\n");
+ quantizer->verbose = verbose;
+ quantizer->train(n, x);
+ FAISS_THROW_IF_NOT_MSG(
+ quantizer->ntotal == nlist,
+ "nlist not consistent with quantizer size");
+ } else if (quantizer_trains_alone == 0) {
+ if (verbose)
+ printf("Training level-1 quantizer on %zd vectors in %zdD\n", n, d);
+
+ Clustering clus(d, nlist, cp);
+ quantizer->reset();
+ if (clustering_index) {
+ clus.train(n, x, *clustering_index);
+ quantizer->add(nlist, clus.centroids.data());
+ } else {
+ clus.train(n, x, *quantizer);
+ }
+ quantizer->is_trained = true;
+ } else if (quantizer_trains_alone == 2) {
+ if (verbose) {
+ printf("Training L2 quantizer on %zd vectors in %zdD%s\n",
+ n,
+ d,
+ clustering_index ? "(user provided index)" : "");
+ }
+ // also accept spherical centroids because in that case
+ // L2 and IP are equivalent
+ FAISS_THROW_IF_NOT(
+ metric_type == METRIC_L2 ||
+ (metric_type == METRIC_INNER_PRODUCT && cp.spherical));
+
+ Clustering clus(d, nlist, cp);
+ if (!clustering_index) {
+ IndexFlatL2 assigner(d);
+ clus.train(n, x, assigner);
+ } else {
+ clus.train(n, x, *clustering_index);
+ }
+ if (verbose) {
+ printf("Adding centroids to quantizer\n");
+ }
+ if (!quantizer->is_trained) {
+ if (verbose) {
+ printf("But training it first on centroids table...\n");
+ }
+ quantizer->train(nlist, clus.centroids.data());
+ }
+ quantizer->add(nlist, clus.centroids.data());
+ }
+}
+
+size_t Level1Quantizer::coarse_code_size() const {
+ size_t nl = nlist - 1;
+ size_t nbyte = 0;
+ while (nl > 0) {
+ nbyte++;
+ nl >>= 8;
+ }
+ return nbyte;
+}
+
+void Level1Quantizer::encode_listno(idx_t list_no, uint8_t* code) const {
+ // little endian
+ size_t nl = nlist - 1;
+ while (nl > 0) {
+ *code++ = list_no & 0xff;
+ list_no >>= 8;
+ nl >>= 8;
+ }
+}
+
+idx_t Level1Quantizer::decode_listno(const uint8_t* code) const {
+ size_t nl = nlist - 1;
+ int64_t list_no = 0;
+ int nbit = 0;
+ while (nl > 0) {
+ list_no |= int64_t(*code++) << nbit;
+ nbit += 8;
+ nl >>= 8;
+ }
+ FAISS_THROW_IF_NOT(list_no >= 0 && list_no < nlist);
+ return list_no;
+}
+
+/*****************************************
+ * IndexIVF implementation
+ ******************************************/
+
+IndexIVF::IndexIVF(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t code_size,
+ MetricType metric)
+ : Index(d, metric),
+ IndexIVFInterface(quantizer, nlist),
+ invlists(new ArrayInvertedLists(nlist, code_size)),
+ own_invlists(true),
+ code_size(code_size) {
+ FAISS_THROW_IF_NOT(d == quantizer->d);
+ is_trained = quantizer->is_trained && (quantizer->ntotal == nlist);
+ // Spherical by default if the metric is inner_product
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ cp.spherical = true;
+ }
+}
+
+IndexIVF::IndexIVF() = default;
+
+void IndexIVF::add(idx_t n, const float* x) {
+ add_with_ids(n, x, nullptr);
+}
+
+void IndexIVF::add_with_ids(idx_t n, const float* x, const idx_t* xids) {
+ std::unique_ptr<idx_t[]> coarse_idx(new idx_t[n]);
+ quantizer->assign(n, x, coarse_idx.get());
+ add_core(n, x, xids, coarse_idx.get());
+}
+
+void IndexIVF::add_sa_codes(idx_t n, const uint8_t* codes, const idx_t* xids) {
+ size_t coarse_size = coarse_code_size();
+ DirectMapAdd dm_adder(direct_map, n, xids);
+
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + (code_size + coarse_size) * i;
+ idx_t list_no = decode_listno(code);
+ idx_t id = xids ? xids[i] : ntotal + i;
+ size_t ofs = invlists->add_entry(list_no, id, code + coarse_size);
+ dm_adder.add(i, list_no, ofs);
+ }
+ ntotal += n;
+}
+
+void IndexIVF::add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* coarse_idx,
+ void* inverted_list_context) {
+ // do some blocking to avoid excessive allocs
+ idx_t bs = 65536;
+ if (n > bs) {
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(n, i0 + bs);
+ if (verbose) {
+ printf(" IndexIVF::add_with_ids %" PRId64 ":%" PRId64 "\n",
+ i0,
+ i1);
+ }
+ add_core(
+ i1 - i0,
+ x + i0 * d,
+ xids ? xids + i0 : nullptr,
+ coarse_idx + i0,
+ inverted_list_context);
+ }
+ return;
+ }
+ FAISS_THROW_IF_NOT(coarse_idx);
+ FAISS_THROW_IF_NOT(is_trained);
+ direct_map.check_can_add(xids);
+
+ size_t nadd = 0, nminus1 = 0;
+
+ for (size_t i = 0; i < n; i++) {
+ if (coarse_idx[i] < 0)
+ nminus1++;
+ }
+
+ std::unique_ptr<uint8_t[]> flat_codes(new uint8_t[n * code_size]);
+ encode_vectors(n, x, coarse_idx, flat_codes.get());
+
+ DirectMapAdd dm_adder(direct_map, n, xids);
+
+#pragma omp parallel reduction(+ : nadd)
+ {
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ // each thread takes care of a subset of lists
+ for (size_t i = 0; i < n; i++) {
+ idx_t list_no = coarse_idx[i];
+ if (list_no >= 0 && list_no % nt == rank) {
+ idx_t id = xids ? xids[i] : ntotal + i;
+ size_t ofs = invlists->add_entry(
+ list_no,
+ id,
+ flat_codes.get() + i * code_size,
+ inverted_list_context);
+
+ dm_adder.add(i, list_no, ofs);
+
+ nadd++;
+ } else if (rank == 0 && list_no == -1) {
+ dm_adder.add(i, -1, 0);
+ }
+ }
+ }
+
+ if (verbose) {
+ printf(" added %zd / %" PRId64 " vectors (%zd -1s)\n",
+ nadd,
+ n,
+ nminus1);
+ }
+
+ ntotal += n;
+}
+
+void IndexIVF::make_direct_map(bool b) {
+ if (b) {
+ direct_map.set_type(DirectMap::Array, invlists, ntotal);
+ } else {
+ direct_map.set_type(DirectMap::NoMap, invlists, ntotal);
+ }
+}
+
+void IndexIVF::set_direct_map_type(DirectMap::Type type) {
+ direct_map.set_type(type, invlists, ntotal);
+}
+
+/** It is a sad fact of software that a conceptually simple function like this
+ * becomes very complex when you factor in several ways of parallelizing +
+ * interrupt/error handling + collecting stats + min/max collection. The
+ * codepath that is used 95% of time is the one for parallel_mode = 0 */
+void IndexIVF::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ const IVFSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type");
+ }
+ const size_t nprobe =
+ std::min(nlist, params ? params->nprobe : this->nprobe);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ // search function for a subset of queries
+ auto sub_search_func = [this, k, nprobe, params](
+ idx_t n,
+ const float* x,
+ float* distances,
+ idx_t* labels,
+ IndexIVFStats* ivf_stats) {
+ std::unique_ptr<idx_t[]> idx(new idx_t[n * nprobe]);
+ std::unique_ptr<float[]> coarse_dis(new float[n * nprobe]);
+
+ double t0 = getmillisecs();
+ quantizer->search(
+ n,
+ x,
+ nprobe,
+ coarse_dis.get(),
+ idx.get(),
+ params ? params->quantizer_params : nullptr);
+
+ double t1 = getmillisecs();
+ invlists->prefetch_lists(idx.get(), n * nprobe);
+
+ search_preassigned(
+ n,
+ x,
+ k,
+ idx.get(),
+ coarse_dis.get(),
+ distances,
+ labels,
+ false,
+ params,
+ ivf_stats);
+ double t2 = getmillisecs();
+ ivf_stats->quantization_time += t1 - t0;
+ ivf_stats->search_time += t2 - t0;
+ };
+
+ if ((parallel_mode & ~PARALLEL_MODE_NO_HEAP_INIT) == 0) {
+ int nt = std::min(omp_get_max_threads(), int(n));
+ std::vector<IndexIVFStats> stats(nt);
+ std::mutex exception_mutex;
+ std::string exception_string;
+
+#pragma omp parallel for if (nt > 1)
+ for (idx_t slice = 0; slice < nt; slice++) {
+ IndexIVFStats local_stats;
+ idx_t i0 = n * slice / nt;
+ idx_t i1 = n * (slice + 1) / nt;
+ if (i1 > i0) {
+ try {
+ sub_search_func(
+ i1 - i0,
+ x + i0 * d,
+ distances + i0 * k,
+ labels + i0 * k,
+ &stats[slice]);
+ } catch (const std::exception& e) {
+ std::lock_guard<std::mutex> lock(exception_mutex);
+ exception_string = e.what();
+ }
+ }
+ }
+
+ if (!exception_string.empty()) {
+ FAISS_THROW_MSG(exception_string.c_str());
+ }
+
+ // collect stats
+ for (idx_t slice = 0; slice < nt; slice++) {
+ indexIVF_stats.add(stats[slice]);
+ }
+ } else {
+ // handle parallelization at level below (or don't run in parallel at
+ // all)
+ sub_search_func(n, x, distances, labels, &indexIVF_stats);
+ }
+}
+
+void IndexIVF::search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* keys,
+ const float* coarse_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* ivf_stats) const {
+ FAISS_THROW_IF_NOT(k > 0);
+
+ idx_t nprobe = params ? params->nprobe : this->nprobe;
+ nprobe = std::min((idx_t)nlist, nprobe);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ const idx_t unlimited_list_size = std::numeric_limits<idx_t>::max();
+ idx_t max_codes = params ? params->max_codes : this->max_codes;
+ IDSelector* sel = params ? params->sel : nullptr;
+ const IDSelectorRange* selr = dynamic_cast<const IDSelectorRange*>(sel);
+ if (selr) {
+ if (selr->assume_sorted) {
+ sel = nullptr; // use special IDSelectorRange processing
+ } else {
+ selr = nullptr; // use generic processing
+ }
+ }
+
+ FAISS_THROW_IF_NOT_MSG(
+ !(sel && store_pairs),
+ "selector and store_pairs cannot be combined");
+
+ FAISS_THROW_IF_NOT_MSG(
+ !invlists->use_iterator || (max_codes == 0 && store_pairs == false),
+ "iterable inverted lists don't support max_codes and store_pairs");
+
+ size_t nlistv = 0, ndis = 0, nheap = 0;
+
+ using HeapForIP = CMin<float, idx_t>;
+ using HeapForL2 = CMax<float, idx_t>;
+
+ bool interrupt = false;
+ std::mutex exception_mutex;
+ std::string exception_string;
+
+ int pmode = this->parallel_mode & ~PARALLEL_MODE_NO_HEAP_INIT;
+ bool do_heap_init = !(this->parallel_mode & PARALLEL_MODE_NO_HEAP_INIT);
+
+ FAISS_THROW_IF_NOT_MSG(
+ max_codes == 0 || pmode == 0 || pmode == 3,
+ "max_codes supported only for parallel_mode = 0 or 3");
+
+ if (max_codes == 0) {
+ max_codes = unlimited_list_size;
+ }
+
+ [[maybe_unused]] bool do_parallel = omp_get_max_threads() >= 2 &&
+ (pmode == 0 ? false
+ : pmode == 3 ? n > 1
+ : pmode == 1 ? nprobe > 1
+ : nprobe * n > 1);
+
+ void* inverted_list_context =
+ params ? params->inverted_list_context : nullptr;
+
+#pragma omp parallel if (do_parallel) reduction(+ : nlistv, ndis, nheap)
+ {
+ std::unique_ptr<InvertedListScanner> scanner(
+ get_InvertedListScanner(store_pairs, sel, params));
+
+ /*****************************************************
+ * Depending on parallel_mode, there are two possible ways
+ * to organize the search. Here we define local functions
+ * that are in common between the two
+ ******************************************************/
+
+ // initialize + reorder a result heap
+
+ auto init_result = [&](float* simi, idx_t* idxi) {
+ if (!do_heap_init)
+ return;
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ heap_heapify<HeapForIP>(k, simi, idxi);
+ } else {
+ heap_heapify<HeapForL2>(k, simi, idxi);
+ }
+ };
+
+ auto add_local_results = [&](const float* local_dis,
+ const idx_t* local_idx,
+ float* simi,
+ idx_t* idxi) {
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ heap_addn<HeapForIP>(k, simi, idxi, local_dis, local_idx, k);
+ } else {
+ heap_addn<HeapForL2>(k, simi, idxi, local_dis, local_idx, k);
+ }
+ };
+
+ auto reorder_result = [&](float* simi, idx_t* idxi) {
+ if (!do_heap_init)
+ return;
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ heap_reorder<HeapForIP>(k, simi, idxi);
+ } else {
+ heap_reorder<HeapForL2>(k, simi, idxi);
+ }
+ };
+
+ // single list scan using the current scanner (with query
+ // set porperly) and storing results in simi and idxi
+ auto scan_one_list = [&](idx_t key,
+ float coarse_dis_i,
+ float* simi,
+ idx_t* idxi,
+ idx_t list_size_max) {
+ if (key < 0) {
+ // not enough centroids for multiprobe
+ return (size_t)0;
+ }
+ FAISS_THROW_IF_NOT_FMT(
+ key < (idx_t)nlist,
+ "Invalid key=%" PRId64 " nlist=%zd\n",
+ key,
+ nlist);
+
+ // don't waste time on empty lists
+ if (invlists->is_empty(key, inverted_list_context)) {
+ return (size_t)0;
+ }
+
+ scanner->set_list(key, coarse_dis_i);
+
+ nlistv++;
+
+ try {
+ if (invlists->use_iterator) {
+ size_t list_size = 0;
+
+ std::unique_ptr<InvertedListsIterator> it(
+ invlists->get_iterator(key, inverted_list_context));
+
+ nheap += scanner->iterate_codes(
+ it.get(), simi, idxi, k, list_size);
+
+ return list_size;
+ } else {
+ size_t list_size = invlists->list_size(key);
+ if (list_size > list_size_max) {
+ list_size = list_size_max;
+ }
+
+ InvertedLists::ScopedCodes scodes(invlists, key);
+ const uint8_t* codes = scodes.get();
+
+ std::unique_ptr<InvertedLists::ScopedIds> sids;
+ const idx_t* ids = nullptr;
+
+ if (!store_pairs) {
+ sids = std::make_unique<InvertedLists::ScopedIds>(
+ invlists, key);
+ ids = sids->get();
+ }
+
+ if (selr) { // IDSelectorRange
+ // restrict search to a section of the inverted list
+ size_t jmin, jmax;
+ selr->find_sorted_ids_bounds(
+ list_size, ids, &jmin, &jmax);
+ list_size = jmax - jmin;
+ if (list_size == 0) {
+ return (size_t)0;
+ }
+ codes += jmin * code_size;
+ ids += jmin;
+ }
+
+ nheap += scanner->scan_codes(
+ list_size, codes, ids, simi, idxi, k);
+
+ return list_size;
+ }
+ } catch (const std::exception& e) {
+ std::lock_guard<std::mutex> lock(exception_mutex);
+ exception_string =
+ demangle_cpp_symbol(typeid(e).name()) + " " + e.what();
+ interrupt = true;
+ return size_t(0);
+ }
+ };
+
+ /****************************************************
+ * Actual loops, depending on parallel_mode
+ ****************************************************/
+
+ if (pmode == 0 || pmode == 3) {
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ if (interrupt) {
+ continue;
+ }
+
+ // loop over queries
+ scanner->set_query(x + i * d);
+ float* simi = distances + i * k;
+ idx_t* idxi = labels + i * k;
+
+ init_result(simi, idxi);
+
+ idx_t nscan = 0;
+
+ // loop over probes
+ for (size_t ik = 0; ik < nprobe; ik++) {
+ nscan += scan_one_list(
+ keys[i * nprobe + ik],
+ coarse_dis[i * nprobe + ik],
+ simi,
+ idxi,
+ max_codes - nscan);
+ if (nscan >= max_codes) {
+ break;
+ }
+ }
+
+ ndis += nscan;
+ reorder_result(simi, idxi);
+
+ if (InterruptCallback::is_interrupted()) {
+ interrupt = true;
+ }
+
+ } // parallel for
+ } else if (pmode == 1) {
+ std::vector<idx_t> local_idx(k);
+ std::vector<float> local_dis(k);
+
+ for (size_t i = 0; i < n; i++) {
+ scanner->set_query(x + i * d);
+ init_result(local_dis.data(), local_idx.data());
+
+#pragma omp for schedule(dynamic)
+ for (idx_t ik = 0; ik < nprobe; ik++) {
+ ndis += scan_one_list(
+ keys[i * nprobe + ik],
+ coarse_dis[i * nprobe + ik],
+ local_dis.data(),
+ local_idx.data(),
+ unlimited_list_size);
+
+ // can't do the test on max_codes
+ }
+ // merge thread-local results
+
+ float* simi = distances + i * k;
+ idx_t* idxi = labels + i * k;
+#pragma omp single
+ init_result(simi, idxi);
+
+#pragma omp barrier
+#pragma omp critical
+ {
+ add_local_results(
+ local_dis.data(), local_idx.data(), simi, idxi);
+ }
+#pragma omp barrier
+#pragma omp single
+ reorder_result(simi, idxi);
+ }
+ } else if (pmode == 2) {
+ std::vector<idx_t> local_idx(k);
+ std::vector<float> local_dis(k);
+
+#pragma omp single
+ for (int64_t i = 0; i < n; i++) {
+ init_result(distances + i * k, labels + i * k);
+ }
+
+#pragma omp for schedule(dynamic)
+ for (int64_t ij = 0; ij < n * nprobe; ij++) {
+ size_t i = ij / nprobe;
+
+ scanner->set_query(x + i * d);
+ init_result(local_dis.data(), local_idx.data());
+ ndis += scan_one_list(
+ keys[ij],
+ coarse_dis[ij],
+ local_dis.data(),
+ local_idx.data(),
+ unlimited_list_size);
+#pragma omp critical
+ {
+ add_local_results(
+ local_dis.data(),
+ local_idx.data(),
+ distances + i * k,
+ labels + i * k);
+ }
+ }
+#pragma omp single
+ for (int64_t i = 0; i < n; i++) {
+ reorder_result(distances + i * k, labels + i * k);
+ }
+ } else {
+ FAISS_THROW_FMT("parallel_mode %d not supported\n", pmode);
+ }
+ } // parallel section
+
+ if (interrupt) {
+ if (!exception_string.empty()) {
+ FAISS_THROW_FMT(
+ "search interrupted with: %s", exception_string.c_str());
+ } else {
+ FAISS_THROW_MSG("computation interrupted");
+ }
+ }
+
+ if (ivf_stats == nullptr) {
+ ivf_stats = &indexIVF_stats;
+ }
+ ivf_stats->nq += n;
+ ivf_stats->nlist += nlistv;
+ ivf_stats->ndis += ndis;
+ ivf_stats->nheap_updates += nheap;
+}
+
+void IndexIVF::range_search(
+ idx_t nx,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params_in) const {
+ const IVFSearchParameters* params = nullptr;
+ const SearchParameters* quantizer_params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type");
+ quantizer_params = params->quantizer_params;
+ }
+ const size_t nprobe =
+ std::min(nlist, params ? params->nprobe : this->nprobe);
+ std::unique_ptr<idx_t[]> keys(new idx_t[nx * nprobe]);
+ std::unique_ptr<float[]> coarse_dis(new float[nx * nprobe]);
+
+ double t0 = getmillisecs();
+ quantizer->search(
+ nx, x, nprobe, coarse_dis.get(), keys.get(), quantizer_params);
+ indexIVF_stats.quantization_time += getmillisecs() - t0;
+
+ t0 = getmillisecs();
+ invlists->prefetch_lists(keys.get(), nx * nprobe);
+
+ range_search_preassigned(
+ nx,
+ x,
+ radius,
+ keys.get(),
+ coarse_dis.get(),
+ result,
+ false,
+ params,
+ &indexIVF_stats);
+
+ indexIVF_stats.search_time += getmillisecs() - t0;
+}
+
+void IndexIVF::range_search_preassigned(
+ idx_t nx,
+ const float* x,
+ float radius,
+ const idx_t* keys,
+ const float* coarse_dis,
+ RangeSearchResult* result,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* stats) const {
+ idx_t nprobe = params ? params->nprobe : this->nprobe;
+ nprobe = std::min((idx_t)nlist, nprobe);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ idx_t max_codes = params ? params->max_codes : this->max_codes;
+ IDSelector* sel = params ? params->sel : nullptr;
+
+ FAISS_THROW_IF_NOT_MSG(
+ !invlists->use_iterator || (max_codes == 0 && store_pairs == false),
+ "iterable inverted lists don't support max_codes and store_pairs");
+
+ size_t nlistv = 0, ndis = 0;
+
+ bool interrupt = false;
+ std::mutex exception_mutex;
+ std::string exception_string;
+
+ std::vector<RangeSearchPartialResult*> all_pres(omp_get_max_threads());
+
+ int pmode = this->parallel_mode & ~PARALLEL_MODE_NO_HEAP_INIT;
+ // don't start parallel section if single query
+ [[maybe_unused]] bool do_parallel = omp_get_max_threads() >= 2 &&
+ (pmode == 3 ? false
+ : pmode == 0 ? nx > 1
+ : pmode == 1 ? nprobe > 1
+ : nprobe * nx > 1);
+
+ void* inverted_list_context =
+ params ? params->inverted_list_context : nullptr;
+
+#pragma omp parallel if (do_parallel) reduction(+ : nlistv, ndis)
+ {
+ RangeSearchPartialResult pres(result);
+ std::unique_ptr<InvertedListScanner> scanner(
+ get_InvertedListScanner(store_pairs, sel, params));
+ FAISS_THROW_IF_NOT(scanner.get());
+ all_pres[omp_get_thread_num()] = &pres;
+
+ // prepare the list scanning function
+
+ auto scan_list_func = [&](size_t i, size_t ik, RangeQueryResult& qres) {
+ idx_t key = keys[i * nprobe + ik]; /* select the list */
+ if (key < 0)
+ return;
+ FAISS_THROW_IF_NOT_FMT(
+ key < (idx_t)nlist,
+ "Invalid key=%" PRId64 " at ik=%zd nlist=%zd\n",
+ key,
+ ik,
+ nlist);
+
+ if (invlists->is_empty(key, inverted_list_context)) {
+ return;
+ }
+
+ try {
+ size_t list_size = 0;
+ scanner->set_list(key, coarse_dis[i * nprobe + ik]);
+ if (invlists->use_iterator) {
+ std::unique_ptr<InvertedListsIterator> it(
+ invlists->get_iterator(key, inverted_list_context));
+
+ scanner->iterate_codes_range(
+ it.get(), radius, qres, list_size);
+ } else {
+ InvertedLists::ScopedCodes scodes(invlists, key);
+ InvertedLists::ScopedIds ids(invlists, key);
+ list_size = invlists->list_size(key);
+
+ scanner->scan_codes_range(
+ list_size, scodes.get(), ids.get(), radius, qres);
+ }
+ nlistv++;
+ ndis += list_size;
+ } catch (const std::exception& e) {
+ std::lock_guard<std::mutex> lock(exception_mutex);
+ exception_string =
+ demangle_cpp_symbol(typeid(e).name()) + " " + e.what();
+ interrupt = true;
+ }
+ };
+
+ if (parallel_mode == 0) {
+#pragma omp for
+ for (idx_t i = 0; i < nx; i++) {
+ scanner->set_query(x + i * d);
+
+ RangeQueryResult& qres = pres.new_result(i);
+
+ for (size_t ik = 0; ik < nprobe; ik++) {
+ scan_list_func(i, ik, qres);
+ }
+ }
+
+ } else if (parallel_mode == 1) {
+ for (size_t i = 0; i < nx; i++) {
+ scanner->set_query(x + i * d);
+
+ RangeQueryResult& qres = pres.new_result(i);
+
+#pragma omp for schedule(dynamic)
+ for (int64_t ik = 0; ik < nprobe; ik++) {
+ scan_list_func(i, ik, qres);
+ }
+ }
+ } else if (parallel_mode == 2) {
+ RangeQueryResult* qres = nullptr;
+
+#pragma omp for schedule(dynamic)
+ for (idx_t iik = 0; iik < nx * (idx_t)nprobe; iik++) {
+ idx_t i = iik / (idx_t)nprobe;
+ idx_t ik = iik % (idx_t)nprobe;
+ if (qres == nullptr || qres->qno != i) {
+ qres = &pres.new_result(i);
+ scanner->set_query(x + i * d);
+ }
+ scan_list_func(i, ik, *qres);
+ }
+ } else {
+ FAISS_THROW_FMT("parallel_mode %d not supported\n", parallel_mode);
+ }
+ if (parallel_mode == 0) {
+ pres.finalize();
+ } else {
+#pragma omp barrier
+#pragma omp single
+ RangeSearchPartialResult::merge(all_pres, false);
+#pragma omp barrier
+ }
+ }
+
+ if (interrupt) {
+ if (!exception_string.empty()) {
+ FAISS_THROW_FMT(
+ "search interrupted with: %s", exception_string.c_str());
+ } else {
+ FAISS_THROW_MSG("computation interrupted");
+ }
+ }
+
+ if (stats == nullptr) {
+ stats = &indexIVF_stats;
+ }
+ stats->nq += nx;
+ stats->nlist += nlistv;
+ stats->ndis += ndis;
+}
+
+InvertedListScanner* IndexIVF::get_InvertedListScanner(
+ bool /*store_pairs*/,
+ const IDSelector* /* sel */,
+ const IVFSearchParameters* /* params */) const {
+ FAISS_THROW_MSG("get_InvertedListScanner not implemented");
+}
+
+void IndexIVF::reconstruct(idx_t key, float* recons) const {
+ idx_t lo = direct_map.get(key);
+ reconstruct_from_offset(lo_listno(lo), lo_offset(lo), recons);
+}
+
+void IndexIVF::reconstruct_n(idx_t i0, idx_t ni, float* recons) const {
+ FAISS_THROW_IF_NOT(ni == 0 || (i0 >= 0 && i0 + ni <= ntotal));
+
+ for (idx_t list_no = 0; list_no < nlist; list_no++) {
+ size_t list_size = invlists->list_size(list_no);
+ ScopedIds idlist(invlists, list_no);
+
+ for (idx_t offset = 0; offset < list_size; offset++) {
+ idx_t id = idlist[offset];
+ if (!(id >= i0 && id < i0 + ni)) {
+ continue;
+ }
+
+ float* reconstructed = recons + (id - i0) * d;
+ reconstruct_from_offset(list_no, offset, reconstructed);
+ }
+ }
+}
+
+bool IndexIVF::check_ids_sorted() const {
+ size_t nflip = 0;
+
+ for (size_t i = 0; i < nlist; i++) {
+ size_t list_size = invlists->list_size(i);
+ InvertedLists::ScopedIds ids(invlists, i);
+ for (size_t j = 0; j + 1 < list_size; j++) {
+ if (ids[j + 1] < ids[j]) {
+ nflip++;
+ }
+ }
+ }
+ return nflip == 0;
+}
+
+/* standalone codec interface */
+size_t IndexIVF::sa_code_size() const {
+ size_t coarse_size = coarse_code_size();
+ return code_size + coarse_size;
+}
+
+void IndexIVF::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ FAISS_THROW_IF_NOT(is_trained);
+ std::unique_ptr<int64_t[]> idx(new int64_t[n]);
+ quantizer->assign(n, x, idx.get());
+ encode_vectors(n, x, idx.get(), bytes, true);
+}
+
+void IndexIVF::search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params_in) const {
+ const IVFSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type");
+ }
+ const size_t nprobe =
+ std::min(nlist, params ? params->nprobe : this->nprobe);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ std::unique_ptr<idx_t[]> idx(new idx_t[n * nprobe]);
+ std::unique_ptr<float[]> coarse_dis(new float[n * nprobe]);
+
+ quantizer->search(n, x, nprobe, coarse_dis.get(), idx.get());
+
+ invlists->prefetch_lists(idx.get(), n * nprobe);
+
+ // search_preassigned() with `store_pairs` enabled to obtain the list_no
+ // and offset into `codes` for reconstruction
+ search_preassigned(
+ n,
+ x,
+ k,
+ idx.get(),
+ coarse_dis.get(),
+ distances,
+ labels,
+ true /* store_pairs */,
+ params);
+#pragma omp parallel for if (n * k > 1000)
+ for (idx_t ij = 0; ij < n * k; ij++) {
+ idx_t key = labels[ij];
+ float* reconstructed = recons + ij * d;
+ if (key < 0) {
+ // Fill with NaNs
+ memset(reconstructed, -1, sizeof(*reconstructed) * d);
+ } else {
+ int list_no = lo_listno(key);
+ int offset = lo_offset(key);
+
+ // Update label to the actual id
+ labels[ij] = invlists->get_single_id(list_no, offset);
+
+ reconstruct_from_offset(list_no, offset, reconstructed);
+ }
+ }
+}
+
+void IndexIVF::search_and_return_codes(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ uint8_t* codes,
+ bool include_listno,
+ const SearchParameters* params_in) const {
+ const IVFSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type");
+ }
+ const size_t nprobe =
+ std::min(nlist, params ? params->nprobe : this->nprobe);
+ FAISS_THROW_IF_NOT(nprobe > 0);
+
+ std::unique_ptr<idx_t[]> idx(new idx_t[n * nprobe]);
+ std::unique_ptr<float[]> coarse_dis(new float[n * nprobe]);
+
+ quantizer->search(n, x, nprobe, coarse_dis.get(), idx.get());
+
+ invlists->prefetch_lists(idx.get(), n * nprobe);
+
+ // search_preassigned() with `store_pairs` enabled to obtain the list_no
+ // and offset into `codes` for reconstruction
+ search_preassigned(
+ n,
+ x,
+ k,
+ idx.get(),
+ coarse_dis.get(),
+ distances,
+ labels,
+ true /* store_pairs */,
+ params);
+
+ size_t code_size_1 = code_size;
+ if (include_listno) {
+ code_size_1 += coarse_code_size();
+ }
+
+#pragma omp parallel for if (n * k > 1000)
+ for (idx_t ij = 0; ij < n * k; ij++) {
+ idx_t key = labels[ij];
+ uint8_t* code1 = codes + ij * code_size_1;
+
+ if (key < 0) {
+ // Fill with 0xff
+ memset(code1, -1, code_size_1);
+ } else {
+ int list_no = lo_listno(key);
+ int offset = lo_offset(key);
+ const uint8_t* cc = invlists->get_single_code(list_no, offset);
+
+ labels[ij] = invlists->get_single_id(list_no, offset);
+
+ if (include_listno) {
+ encode_listno(list_no, code1);
+ code1 += code_size_1 - code_size;
+ }
+ memcpy(code1, cc, code_size);
+ }
+ }
+}
+
+void IndexIVF::reconstruct_from_offset(
+ int64_t /*list_no*/,
+ int64_t /*offset*/,
+ float* /*recons*/) const {
+ FAISS_THROW_MSG("reconstruct_from_offset not implemented");
+}
+
+void IndexIVF::reset() {
+ direct_map.clear();
+ invlists->reset();
+ ntotal = 0;
+}
+
+size_t IndexIVF::remove_ids(const IDSelector& sel) {
+ size_t nremove = direct_map.remove_ids(sel, invlists);
+ ntotal -= nremove;
+ return nremove;
+}
+
+void IndexIVF::update_vectors(int n, const idx_t* new_ids, const float* x) {
+ if (direct_map.type == DirectMap::Hashtable) {
+ // just remove then add
+ IDSelectorArray sel(n, new_ids);
+ size_t nremove = remove_ids(sel);
+ FAISS_THROW_IF_NOT_MSG(
+ nremove == n, "did not find all entries to remove");
+ add_with_ids(n, x, new_ids);
+ return;
+ }
+
+ FAISS_THROW_IF_NOT(direct_map.type == DirectMap::Array);
+ // here it is more tricky because we don't want to introduce holes
+ // in continuous range of ids
+
+ FAISS_THROW_IF_NOT(is_trained);
+ std::vector<idx_t> assign(n);
+ quantizer->assign(n, x, assign.data());
+
+ std::vector<uint8_t> flat_codes(n * code_size);
+ encode_vectors(n, x, assign.data(), flat_codes.data());
+
+ direct_map.update_codes(
+ invlists, n, new_ids, assign.data(), flat_codes.data());
+}
+
+void IndexIVF::train(idx_t n, const float* x) {
+ if (verbose) {
+ printf("Training level-1 quantizer\n");
+ }
+
+ train_q1(n, x, verbose, metric_type);
+
+ if (verbose) {
+ printf("Training IVF residual\n");
+ }
+
+ // optional subsampling
+ idx_t max_nt = train_encoder_num_vectors();
+ if (max_nt <= 0) {
+ max_nt = (size_t)1 << 35;
+ }
+
+ TransformedVectors tv(
+ x, fvecs_maybe_subsample(d, (size_t*)&n, max_nt, x, verbose));
+
+ if (by_residual) {
+ std::vector<idx_t> assign(n);
+ quantizer->assign(n, tv.x, assign.data());
+
+ std::vector<float> residuals(n * d);
+ quantizer->compute_residual_n(n, tv.x, residuals.data(), assign.data());
+
+ train_encoder(n, residuals.data(), assign.data());
+ } else {
+ train_encoder(n, tv.x, nullptr);
+ }
+
+ is_trained = true;
+}
+
+idx_t IndexIVF::train_encoder_num_vectors() const {
+ return 0;
+}
+
+void IndexIVF::train_encoder(
+ idx_t /*n*/,
+ const float* /*x*/,
+ const idx_t* assign) {
+ // does nothing by default
+ if (verbose) {
+ printf("IndexIVF: no residual training\n");
+ }
+}
+
+bool check_compatible_for_merge_expensive_check = true;
+
+void IndexIVF::check_compatible_for_merge(const Index& otherIndex) const {
+ // minimal sanity checks
+ const IndexIVF* other = dynamic_cast<const IndexIVF*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->d == d);
+ FAISS_THROW_IF_NOT(other->nlist == nlist);
+ FAISS_THROW_IF_NOT(quantizer->ntotal == other->quantizer->ntotal);
+ FAISS_THROW_IF_NOT(other->code_size == code_size);
+ FAISS_THROW_IF_NOT_MSG(
+ typeid(*this) == typeid(*other),
+ "can only merge indexes of the same type");
+ FAISS_THROW_IF_NOT_MSG(
+ this->direct_map.no() && other->direct_map.no(),
+ "merge direct_map not implemented");
+
+ if (check_compatible_for_merge_expensive_check) {
+ std::vector<float> v(d), v2(d);
+ for (size_t i = 0; i < nlist; i++) {
+ quantizer->reconstruct(i, v.data());
+ other->quantizer->reconstruct(i, v2.data());
+ FAISS_THROW_IF_NOT_MSG(
+ v == v2, "coarse quantizers should be the same");
+ }
+ }
+}
+
+void IndexIVF::merge_from(Index& otherIndex, idx_t add_id) {
+ check_compatible_for_merge(otherIndex);
+ IndexIVF* other = static_cast<IndexIVF*>(&otherIndex);
+ invlists->merge_from(other->invlists, add_id);
+
+ ntotal += other->ntotal;
+ other->ntotal = 0;
+}
+
+CodePacker* IndexIVF::get_CodePacker() const {
+ return new CodePackerFlat(code_size);
+}
+
+void IndexIVF::replace_invlists(InvertedLists* il, bool own) {
+ if (own_invlists) {
+ delete invlists;
+ invlists = nullptr;
+ }
+ // FAISS_THROW_IF_NOT (ntotal == 0);
+ if (il) {
+ FAISS_THROW_IF_NOT(il->nlist == nlist);
+ FAISS_THROW_IF_NOT(
+ il->code_size == code_size ||
+ il->code_size == InvertedLists::INVALID_CODE_SIZE);
+ }
+ invlists = il;
+ own_invlists = own;
+}
+
+void IndexIVF::copy_subset_to(
+ IndexIVF& other,
+ InvertedLists::subset_type_t subset_type,
+ idx_t a1,
+ idx_t a2) const {
+ other.ntotal +=
+ invlists->copy_subset_to(*other.invlists, subset_type, a1, a2);
+}
+
+IndexIVF::~IndexIVF() {
+ if (own_invlists) {
+ delete invlists;
+ }
+}
+
+/*************************************************************************
+ * IndexIVFStats
+ *************************************************************************/
+
+void IndexIVFStats::reset() {
+ memset((void*)this, 0, sizeof(*this));
+}
+
+void IndexIVFStats::add(const IndexIVFStats& other) {
+ nq += other.nq;
+ nlist += other.nlist;
+ ndis += other.ndis;
+ nheap_updates += other.nheap_updates;
+ quantization_time += other.quantization_time;
+ search_time += other.search_time;
+}
+
+IndexIVFStats indexIVF_stats;
+
+/*************************************************************************
+ * InvertedListScanner
+ *************************************************************************/
+
+size_t InvertedListScanner::scan_codes(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* simi,
+ idx_t* idxi,
+ size_t k) const {
+ size_t nup = 0;
+
+ if (!keep_max) {
+ for (size_t j = 0; j < list_size; j++) {
+ if (sel != nullptr) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ if (!sel->is_member(id)) {
+ codes += code_size;
+ continue;
+ }
+ }
+
+ float dis = distance_to_code(codes);
+ if (dis < simi[0]) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ maxheap_replace_top(k, simi, idxi, dis, id);
+ nup++;
+ }
+ codes += code_size;
+ }
+ } else {
+ for (size_t j = 0; j < list_size; j++) {
+ if (sel != nullptr) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ if (!sel->is_member(id)) {
+ codes += code_size;
+ continue;
+ }
+ }
+
+ float dis = distance_to_code(codes);
+ if (dis > simi[0]) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ minheap_replace_top(k, simi, idxi, dis, id);
+ nup++;
+ }
+ codes += code_size;
+ }
+ }
+ return nup;
+}
+
+size_t InvertedListScanner::iterate_codes(
+ InvertedListsIterator* it,
+ float* simi,
+ idx_t* idxi,
+ size_t k,
+ size_t& list_size) const {
+ size_t nup = 0;
+ list_size = 0;
+
+ if (!keep_max) {
+ for (; it->is_available(); it->next()) {
+ auto id_and_codes = it->get_id_and_codes();
+ float dis = distance_to_code(id_and_codes.second);
+ if (dis < simi[0]) {
+ maxheap_replace_top(k, simi, idxi, dis, id_and_codes.first);
+ nup++;
+ }
+ list_size++;
+ }
+ } else {
+ for (; it->is_available(); it->next()) {
+ auto id_and_codes = it->get_id_and_codes();
+ float dis = distance_to_code(id_and_codes.second);
+ if (dis > simi[0]) {
+ minheap_replace_top(k, simi, idxi, dis, id_and_codes.first);
+ nup++;
+ }
+ list_size++;
+ }
+ }
+ return nup;
+}
+
+void InvertedListScanner::scan_codes_range(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& res) const {
+ for (size_t j = 0; j < list_size; j++) {
+ float dis = distance_to_code(codes);
+ bool keep = !keep_max
+ ? dis < radius
+ : dis > radius; // TODO templatize to remove this test
+ if (keep) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ res.add(dis, id);
+ }
+ codes += code_size;
+ }
+}
+
+void InvertedListScanner::iterate_codes_range(
+ InvertedListsIterator* it,
+ float radius,
+ RangeQueryResult& res,
+ size_t& list_size) const {
+ list_size = 0;
+ for (; it->is_available(); it->next()) {
+ auto id_and_codes = it->get_id_and_codes();
+ float dis = distance_to_code(id_and_codes.second);
+ bool keep = !keep_max
+ ? dis < radius
+ : dis > radius; // TODO templatize to remove this test
+ if (keep) {
+ res.add(dis, id_and_codes.first);
+ }
+ list_size++;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVF.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVF.h
new file mode 100644
index 0000000..4e8d79b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVF.h
@@ -0,0 +1,557 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_IVF_H
+#define FAISS_INDEX_IVF_H
+
+#include <stdint.h>
+#include <memory>
+#include <unordered_map>
+#include <vector>
+
+#include <faiss/Clustering.h>
+#include <faiss/Index.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/invlists/DirectMap.h>
+#include <faiss/invlists/InvertedLists.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+/** Encapsulates a quantizer object for the IndexIVF
+ *
+ * The class isolates the fields that are independent of the storage
+ * of the lists (especially training)
+ */
+struct Level1Quantizer {
+ /// quantizer that maps vectors to inverted lists
+ Index* quantizer = nullptr;
+
+ /// number of inverted lists
+ size_t nlist = 0;
+
+ /**
+ * = 0: use the quantizer as index in a kmeans training
+ * = 1: just pass on the training set to the train() of the quantizer
+ * = 2: kmeans training on a flat index + add the centroids to the quantizer
+ */
+ char quantizer_trains_alone = 0;
+ bool own_fields = false; ///< whether object owns the quantizer
+
+ ClusteringParameters cp; ///< to override default clustering params
+ /// to override index used during clustering
+ Index* clustering_index = nullptr;
+
+ /// Trains the quantizer and calls train_residual to train sub-quantizers
+ void train_q1(
+ size_t n,
+ const float* x,
+ bool verbose,
+ MetricType metric_type);
+
+ /// compute the number of bytes required to store list ids
+ size_t coarse_code_size() const;
+ void encode_listno(idx_t list_no, uint8_t* code) const;
+ idx_t decode_listno(const uint8_t* code) const;
+
+ Level1Quantizer(Index* quantizer, size_t nlist);
+
+ Level1Quantizer();
+
+ ~Level1Quantizer();
+};
+
+struct SearchParametersIVF : SearchParameters {
+ size_t nprobe = 1; ///< number of probes at query time
+ size_t max_codes = 0; ///< max nb of codes to visit to do a query
+ SearchParameters* quantizer_params = nullptr;
+ /// context object to pass to InvertedLists
+ void* inverted_list_context = nullptr;
+
+ virtual ~SearchParametersIVF() {}
+};
+
+// the new convention puts the index type after SearchParameters
+using IVFSearchParameters = SearchParametersIVF;
+
+struct InvertedListScanner;
+struct IndexIVFStats;
+struct CodePacker;
+
+struct IndexIVFInterface : Level1Quantizer {
+ size_t nprobe = 1; ///< number of probes at query time
+ size_t max_codes = 0; ///< max nb of codes to visit to do a query
+
+ explicit IndexIVFInterface(Index* quantizer = nullptr, size_t nlist = 0)
+ : Level1Quantizer(quantizer, nlist) {}
+
+ /** search a set of vectors, that are pre-quantized by the IVF
+ * quantizer. Fill in the corresponding heaps with the query
+ * results. The default implementation uses InvertedListScanners
+ * to do the search.
+ *
+ * @param n nb of vectors to query
+ * @param x query vectors, size nx * d
+ * @param assign coarse quantization indices, size nx * nprobe
+ * @param centroid_dis
+ * distances to coarse centroids, size nx * nprobe
+ * @param distance
+ * output distances, size n * k
+ * @param labels output labels, size n * k
+ * @param store_pairs store inv list index + inv list offset
+ * instead in upper/lower 32 bit of result,
+ * instead of ids (used for reranking).
+ * @param params used to override the object's search parameters
+ * @param stats search stats to be updated (can be null)
+ */
+ virtual void search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const = 0;
+
+ /** Range search a set of vectors, that are pre-quantized by the IVF
+ * quantizer. Fill in the RangeSearchResults results. The default
+ * implementation uses InvertedListScanners to do the search.
+ *
+ * @param n nb of vectors to query
+ * @param x query vectors, size nx * d
+ * @param assign coarse quantization indices, size nx * nprobe
+ * @param centroid_dis
+ * distances to coarse centroids, size nx * nprobe
+ * @param result Output results
+ * @param store_pairs store inv list index + inv list offset
+ * instead in upper/lower 32 bit of result,
+ * instead of ids (used for reranking).
+ * @param params used to override the object's search parameters
+ * @param stats search stats to be updated (can be null)
+ */
+ virtual void range_search_preassigned(
+ idx_t nx,
+ const float* x,
+ float radius,
+ const idx_t* keys,
+ const float* coarse_dis,
+ RangeSearchResult* result,
+ bool store_pairs = false,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const = 0;
+
+ virtual ~IndexIVFInterface() {}
+};
+
+/** Index based on a inverted file (IVF)
+ *
+ * In the inverted file, the quantizer (an Index instance) provides a
+ * quantization index for each vector to be added. The quantization
+ * index maps to a list (aka inverted list or posting list), where the
+ * id of the vector is stored.
+ *
+ * The inverted list object is required only after trainng. If none is
+ * set externally, an ArrayInvertedLists is used automatically.
+ *
+ * At search time, the vector to be searched is also quantized, and
+ * only the list corresponding to the quantization index is
+ * searched. This speeds up the search by making it
+ * non-exhaustive. This can be relaxed using multi-probe search: a few
+ * (nprobe) quantization indices are selected and several inverted
+ * lists are visited.
+ *
+ * Sub-classes implement a post-filtering of the index that refines
+ * the distance estimation from the query to databse vectors.
+ */
+struct IndexIVF : Index, IndexIVFInterface {
+ /// Access to the actual data
+ InvertedLists* invlists = nullptr;
+ bool own_invlists = false;
+
+ size_t code_size = 0; ///< code size per vector in bytes
+
+ /** Parallel mode determines how queries are parallelized with OpenMP
+ *
+ * 0 (default): split over queries
+ * 1: parallelize over inverted lists
+ * 2: parallelize over both
+ * 3: split over queries with a finer granularity
+ *
+ * PARALLEL_MODE_NO_HEAP_INIT: binary or with the previous to
+ * prevent the heap to be initialized and finalized
+ */
+ int parallel_mode = 0;
+ const int PARALLEL_MODE_NO_HEAP_INIT = 1024;
+
+ /** optional map that maps back ids to invlist entries. This
+ * enables reconstruct() */
+ DirectMap direct_map;
+
+ /// do the codes in the invlists encode the vectors relative to the
+ /// centroids?
+ bool by_residual = true;
+
+ /** The Inverted file takes a quantizer (an Index) on input,
+ * which implements the function mapping a vector to a list
+ * identifier.
+ */
+ IndexIVF(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t code_size,
+ MetricType metric = METRIC_L2);
+
+ void reset() override;
+
+ /// Trains the quantizer and calls train_encoder to train sub-quantizers
+ void train(idx_t n, const float* x) override;
+
+ /// Calls add_with_ids with NULL ids
+ void add(idx_t n, const float* x) override;
+
+ /// default implementation that calls encode_vectors
+ void add_with_ids(idx_t n, const float* x, const idx_t* xids) override;
+
+ /** Implementation of vector addition where the vector assignments are
+ * predefined. The default implementation hands over the code extraction to
+ * encode_vectors.
+ *
+ * @param precomputed_idx quantization indices for the input vectors
+ * (size n)
+ */
+ virtual void add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context = nullptr);
+
+ /** Encodes a set of vectors as they would appear in the inverted lists
+ *
+ * @param list_nos inverted list ids as returned by the
+ * quantizer (size n). -1s are ignored.
+ * @param codes output codes, size n * code_size
+ * @param include_listno
+ * include the list ids in the code (in this case add
+ * ceil(log8(nlist)) to the code size)
+ */
+ virtual void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listno = false) const = 0;
+
+ /** Add vectors that are computed with the standalone codec
+ *
+ * @param codes codes to add size n * sa_code_size()
+ * @param xids corresponding ids, size n
+ */
+ void add_sa_codes(idx_t n, const uint8_t* codes, const idx_t* xids)
+ override;
+
+ /** Train the encoder for the vectors.
+ *
+ * If by_residual then it is called with residuals and corresponding assign
+ * array, otherwise x is the raw training vectors and assign=nullptr */
+ virtual void train_encoder(idx_t n, const float* x, const idx_t* assign);
+
+ /// can be redefined by subclasses to indicate how many training vectors
+ /// they need
+ virtual idx_t train_encoder_num_vectors() const;
+
+ void search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ void range_search_preassigned(
+ idx_t nx,
+ const float* x,
+ float radius,
+ const idx_t* keys,
+ const float* coarse_dis,
+ RangeSearchResult* result,
+ bool store_pairs = false,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ /** assign the vectors, then call search_preassign */
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ /** Get a scanner for this index (store_pairs means ignore labels)
+ *
+ * The default search implementation uses this to compute the distances.
+ * Use sel instead of params->sel, because sel is initialized with
+ * params->sel, but may get overridden by IndexIVF's internal logic.
+ */
+ virtual InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs = false,
+ const IDSelector* sel = nullptr,
+ const IVFSearchParameters* params = nullptr) const;
+
+ /** reconstruct a vector. Works only if maintain_direct_map is set to 1 or 2
+ */
+ void reconstruct(idx_t key, float* recons) const override;
+
+ /** Update a subset of vectors.
+ *
+ * The index must have a direct_map
+ *
+ * @param nv nb of vectors to update
+ * @param idx vector indices to update, size nv
+ * @param v vectors of new values, size nv*d
+ */
+ virtual void update_vectors(int nv, const idx_t* idx, const float* v);
+
+ /** Reconstruct a subset of the indexed vectors.
+ *
+ * Overrides default implementation to bypass reconstruct() which requires
+ * direct_map to be maintained.
+ *
+ * @param i0 first vector to reconstruct
+ * @param ni nb of vectors to reconstruct
+ * @param recons output array of reconstructed vectors, size ni * d
+ */
+ void reconstruct_n(idx_t i0, idx_t ni, float* recons) const override;
+
+ /** Similar to search, but also reconstructs the stored vectors (or an
+ * approximation in the case of lossy coding) for the search results.
+ *
+ * Overrides default implementation to avoid having to maintain direct_map
+ * and instead fetch the code offsets through the `store_pairs` flag in
+ * search_preassigned().
+ *
+ * @param recons reconstructed vectors size (n, k, d)
+ */
+ void search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params = nullptr) const override;
+
+ /** Similar to search, but also returns the codes corresponding to the
+ * stored vectors for the search results.
+ *
+ * @param codes codes (n, k, code_size)
+ * @param include_listno
+ * include the list ids in the code (in this case add
+ * ceil(log8(nlist)) to the code size)
+ */
+ void search_and_return_codes(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ uint8_t* recons,
+ bool include_listno = false,
+ const SearchParameters* params = nullptr) const;
+
+ /** Reconstruct a vector given the location in terms of (inv list index +
+ * inv list offset) instead of the id.
+ *
+ * Useful for reconstructing when the direct_map is not maintained and
+ * the inv list offset is computed by search_preassigned() with
+ * `store_pairs` set.
+ */
+ virtual void reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const;
+
+ /// Dataset manipulation functions
+
+ size_t remove_ids(const IDSelector& sel) override;
+
+ void check_compatible_for_merge(const Index& otherIndex) const override;
+
+ virtual void merge_from(Index& otherIndex, idx_t add_id) override;
+
+ // returns a new instance of a CodePacker
+ virtual CodePacker* get_CodePacker() const;
+
+ /** copy a subset of the entries index to the other index
+ * see Invlists::copy_subset_to for the meaning of subset_type
+ */
+ virtual void copy_subset_to(
+ IndexIVF& other,
+ InvertedLists::subset_type_t subset_type,
+ idx_t a1,
+ idx_t a2) const;
+
+ ~IndexIVF() override;
+
+ size_t get_list_size(size_t list_no) const {
+ return invlists->list_size(list_no);
+ }
+
+ /// are the ids sorted?
+ bool check_ids_sorted() const;
+
+ /** initialize a direct map
+ *
+ * @param new_maintain_direct_map if true, create a direct map,
+ * else clear it
+ */
+ void make_direct_map(bool new_maintain_direct_map = true);
+
+ void set_direct_map_type(DirectMap::Type type);
+
+ /// replace the inverted lists, old one is deallocated if own_invlists
+ void replace_invlists(InvertedLists* il, bool own = false);
+
+ /* The standalone codec interface (except sa_decode that is specific) */
+ size_t sa_code_size() const override;
+
+ /** encode a set of vectors
+ * sa_encode will call encode_vectors with include_listno=true
+ * @param n nb of vectors to encode
+ * @param x the vectors to encode
+ * @param bytes output array for the codes
+ * @return nb of bytes written to codes
+ */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ IndexIVF();
+};
+
+struct RangeQueryResult;
+
+/** Object that handles a query. The inverted lists to scan are
+ * provided externally. The object has a lot of state, but
+ * distance_to_code and scan_codes can be called in multiple
+ * threads */
+struct InvertedListScanner {
+ idx_t list_no = -1; ///< remember current list
+ bool keep_max = false; ///< keep maximum instead of minimum
+ /// store positions in invlists rather than labels
+ bool store_pairs;
+
+ /// search in this subset of ids
+ const IDSelector* sel;
+
+ InvertedListScanner(
+ bool store_pairs = false,
+ const IDSelector* sel = nullptr)
+ : store_pairs(store_pairs), sel(sel) {}
+
+ /// used in default implementation of scan_codes
+ size_t code_size = 0;
+
+ /// from now on we handle this query.
+ virtual void set_query(const float* query_vector) = 0;
+
+ /// following codes come from this inverted list
+ virtual void set_list(idx_t list_no, float coarse_dis) = 0;
+
+ /// compute a single query-to-code distance
+ virtual float distance_to_code(const uint8_t* code) const = 0;
+
+ /** scan a set of codes, compute distances to current query and
+ * update heap of results if necessary. Default implementation
+ * calls distance_to_code.
+ *
+ * @param n number of codes to scan
+ * @param codes codes to scan (n * code_size)
+ * @param ids corresponding ids (ignored if store_pairs)
+ * @param distances heap distances (size k)
+ * @param labels heap labels (size k)
+ * @param k heap size
+ * @return number of heap updates performed
+ */
+ virtual size_t scan_codes(
+ size_t n,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* distances,
+ idx_t* labels,
+ size_t k) const;
+
+ // same as scan_codes, using an iterator
+ virtual size_t iterate_codes(
+ InvertedListsIterator* iterator,
+ float* distances,
+ idx_t* labels,
+ size_t k,
+ size_t& list_size) const;
+
+ /** scan a set of codes, compute distances to current query and
+ * update results if distances are below radius
+ *
+ * (default implementation fails) */
+ virtual void scan_codes_range(
+ size_t n,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& result) const;
+
+ // same as scan_codes_range, using an iterator
+ virtual void iterate_codes_range(
+ InvertedListsIterator* iterator,
+ float radius,
+ RangeQueryResult& result,
+ size_t& list_size) const;
+
+ virtual ~InvertedListScanner() {}
+};
+
+// whether to check that coarse quantizers are the same
+FAISS_API extern bool check_compatible_for_merge_expensive_check;
+
+struct IndexIVFStats {
+ size_t nq; // nb of queries run
+ size_t nlist; // nb of inverted lists scanned
+ size_t ndis; // nb of distances computed
+ size_t nheap_updates; // nb of times the heap was updated
+ double quantization_time; // time spent quantizing vectors (in ms)
+ double search_time; // time spent searching lists (in ms)
+
+ IndexIVFStats() {
+ reset();
+ }
+ void reset();
+ void add(const IndexIVFStats& other);
+};
+
+// global var that collects them all
+FAISS_API extern IndexIVFStats indexIVF_stats;
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizer.cpp
new file mode 100644
index 0000000..01f5b93
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizer.cpp
@@ -0,0 +1,400 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/extra_distances.h>
+
+namespace faiss {
+
+/**************************************************************************************
+ * IndexIVFAdditiveQuantizer
+ **************************************************************************************/
+
+IndexIVFAdditiveQuantizer::IndexIVFAdditiveQuantizer(
+ AdditiveQuantizer* aq,
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ MetricType metric)
+ : IndexIVF(quantizer, d, nlist, 0, metric), aq(aq) {
+ by_residual = true;
+}
+
+IndexIVFAdditiveQuantizer::IndexIVFAdditiveQuantizer(AdditiveQuantizer* aq)
+ : IndexIVF(), aq(aq) {}
+
+void IndexIVFAdditiveQuantizer::train_encoder(
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ aq->train(n, x);
+}
+
+idx_t IndexIVFAdditiveQuantizer::train_encoder_num_vectors() const {
+ size_t max_train_points = 1024 * ((size_t)1 << aq->nbits[0]);
+ // we need more data to train LSQ
+ if (dynamic_cast<LocalSearchQuantizer*>(aq)) {
+ max_train_points = 1024 * aq->M * ((size_t)1 << aq->nbits[0]);
+ }
+ return max_train_points;
+}
+
+void IndexIVFAdditiveQuantizer::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ // first encode then possibly add listnos
+
+ if (by_residual) {
+ // subtract centroids
+ std::vector<float> residuals(n * d);
+
+#pragma omp parallel for if (n > 10000)
+ for (idx_t i = 0; i < n; i++) {
+ quantizer->compute_residual(
+ x + i * d,
+ residuals.data() + i * d,
+ list_nos[i] >= 0 ? list_nos[i] : 0);
+ }
+ aq->compute_codes(residuals.data(), codes, n);
+ } else {
+ aq->compute_codes(x, codes, n);
+ }
+
+ if (include_listnos) {
+ // write back from the end, where there is enough space
+ size_t coarse_size = coarse_code_size();
+ for (idx_t i = n - 1; i >= 0; i--) {
+ uint8_t* code = codes + i * (code_size + coarse_size);
+ memmove(code + coarse_size, codes + i * code_size, code_size);
+ encode_listno(list_nos[i], code);
+ }
+ }
+}
+
+void IndexIVFAdditiveQuantizer::sa_decode(
+ idx_t n,
+ const uint8_t* codes,
+ float* x) const {
+ const size_t coarse_size = coarse_code_size();
+
+#pragma omp parallel if (n > 1000)
+ {
+ std::vector<float> residual(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + i * (code_size + coarse_size);
+ int64_t list_no = decode_listno(code);
+ float* xi = x + i * d;
+ aq->decode(code + coarse_size, xi, 1);
+ if (by_residual) {
+ quantizer->reconstruct(list_no, residual.data());
+ for (size_t j = 0; j < d; j++) {
+ xi[j] += residual[j];
+ }
+ }
+ }
+ }
+}
+
+void IndexIVFAdditiveQuantizer::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ const uint8_t* code = invlists->get_single_code(list_no, offset);
+ aq->decode(code, recons, 1);
+ if (by_residual) {
+ std::vector<float> centroid(d);
+ quantizer->reconstruct(list_no, centroid.data());
+ for (int i = 0; i < d; ++i) {
+ recons[i] += centroid[i];
+ }
+ }
+}
+
+IndexIVFAdditiveQuantizer::~IndexIVFAdditiveQuantizer() = default;
+
+/*********************************************
+ * AQInvertedListScanner
+ *********************************************/
+
+namespace {
+
+using Search_type_t = AdditiveQuantizer::Search_type_t;
+
+struct AQInvertedListScanner : InvertedListScanner {
+ const IndexIVFAdditiveQuantizer& ia;
+ const AdditiveQuantizer& aq;
+ std::vector<float> tmp;
+
+ AQInvertedListScanner(const IndexIVFAdditiveQuantizer& ia, bool store_pairs)
+ : ia(ia), aq(*ia.aq) {
+ this->store_pairs = store_pairs;
+ this->code_size = ia.code_size;
+ keep_max = is_similarity_metric(ia.metric_type);
+ tmp.resize(ia.d);
+ }
+
+ const float* q0;
+
+ /// from now on we handle this query.
+ void set_query(const float* query_vector) override {
+ q0 = query_vector;
+ }
+
+ const float* q;
+ /// following codes come from this inverted list
+ void set_list(idx_t list_no, float coarse_dis) override {
+ this->list_no = list_no;
+ if (ia.metric_type == METRIC_L2 && ia.by_residual) {
+ ia.quantizer->compute_residual(q0, tmp.data(), list_no);
+ q = tmp.data();
+ } else {
+ q = q0;
+ }
+ }
+
+ ~AQInvertedListScanner() = default;
+};
+
+template <bool is_IP>
+struct AQInvertedListScannerDecompress : AQInvertedListScanner {
+ AQInvertedListScannerDecompress(
+ const IndexIVFAdditiveQuantizer& ia,
+ bool store_pairs)
+ : AQInvertedListScanner(ia, store_pairs) {}
+
+ float coarse_dis = 0;
+
+ /// following codes come from this inverted list
+ void set_list(idx_t list_no, float coarse_dis_2) override {
+ AQInvertedListScanner::set_list(list_no, coarse_dis_2);
+ if (ia.by_residual) {
+ this->coarse_dis = coarse_dis_2;
+ }
+ }
+
+ /// compute a single query-to-code distance
+ float distance_to_code(const uint8_t* code) const final {
+ std::vector<float> b(aq.d);
+ aq.decode(code, b.data(), 1);
+ FAISS_ASSERT(q);
+ FAISS_ASSERT(b.data());
+
+ return is_IP ? coarse_dis + fvec_inner_product(q, b.data(), aq.d)
+ : fvec_L2sqr(q, b.data(), aq.d);
+ }
+
+ ~AQInvertedListScannerDecompress() override = default;
+};
+
+template <bool is_IP, Search_type_t search_type>
+struct AQInvertedListScannerLUT : AQInvertedListScanner {
+ std::vector<float> LUT, tmp;
+ float distance_bias;
+
+ AQInvertedListScannerLUT(
+ const IndexIVFAdditiveQuantizer& ia,
+ bool store_pairs)
+ : AQInvertedListScanner(ia, store_pairs) {
+ LUT.resize(aq.total_codebook_size);
+ tmp.resize(ia.d);
+ distance_bias = 0;
+ }
+
+ /// from now on we handle this query.
+ void set_query(const float* query_vector) override {
+ AQInvertedListScanner::set_query(query_vector);
+ if (!is_IP && !ia.by_residual) {
+ distance_bias = fvec_norm_L2sqr(query_vector, ia.d);
+ }
+ }
+
+ /// following codes come from this inverted list
+ void set_list(idx_t list_no, float coarse_dis) override {
+ AQInvertedListScanner::set_list(list_no, coarse_dis);
+ // TODO find a way to provide the nprobes together to do a matmul
+ // + precompute tables
+ aq.compute_LUT(1, q, LUT.data());
+
+ if (ia.by_residual) {
+ distance_bias = coarse_dis;
+ }
+ }
+
+ /// compute a single query-to-code distance
+ float distance_to_code(const uint8_t* code) const final {
+ return distance_bias +
+ aq.compute_1_distance_LUT<is_IP, search_type>(code, LUT.data());
+ }
+
+ ~AQInvertedListScannerLUT() override = default;
+};
+
+} // anonymous namespace
+
+InvertedListScanner* IndexIVFAdditiveQuantizer::get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters*) const {
+ FAISS_THROW_IF_NOT(!sel);
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ if (aq->search_type == AdditiveQuantizer::ST_decompress) {
+ return new AQInvertedListScannerDecompress<true>(
+ *this, store_pairs);
+ } else {
+ return new AQInvertedListScannerLUT<
+ true,
+ AdditiveQuantizer::ST_LUT_nonorm>(*this, store_pairs);
+ }
+ } else {
+ switch (aq->search_type) {
+ case AdditiveQuantizer::ST_decompress:
+ return new AQInvertedListScannerDecompress<false>(
+ *this, store_pairs);
+#define A(st) \
+ case AdditiveQuantizer::st: \
+ return new AQInvertedListScannerLUT<false, AdditiveQuantizer::st>( \
+ *this, store_pairs);
+ A(ST_LUT_nonorm)
+ A(ST_norm_from_LUT)
+ A(ST_norm_float)
+ A(ST_norm_qint8)
+ A(ST_norm_qint4)
+ A(ST_norm_cqint4)
+ case AdditiveQuantizer::ST_norm_lsq2x4:
+ case AdditiveQuantizer::ST_norm_rq2x4:
+ A(ST_norm_cqint8)
+#undef A
+ default:
+ FAISS_THROW_FMT(
+ "search type %d not supported", aq->search_type);
+ }
+ }
+}
+
+/**************************************************************************************
+ * IndexIVFResidualQuantizer
+ **************************************************************************************/
+
+IndexIVFResidualQuantizer::IndexIVFResidualQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ const std::vector<size_t>& nbits,
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexIVFAdditiveQuantizer(&rq, quantizer, d, nlist, metric),
+ rq(d, nbits, search_type) {
+ code_size = invlists->code_size = rq.code_size;
+}
+
+IndexIVFResidualQuantizer::IndexIVFResidualQuantizer()
+ : IndexIVFAdditiveQuantizer(&rq) {}
+
+IndexIVFResidualQuantizer::IndexIVFResidualQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M, /* number of subquantizers */
+ size_t nbits, /* number of bit per subvector index */
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexIVFResidualQuantizer(
+ quantizer,
+ d,
+ nlist,
+ std::vector<size_t>(M, nbits),
+ metric,
+ search_type) {}
+
+IndexIVFResidualQuantizer::~IndexIVFResidualQuantizer() = default;
+
+/**************************************************************************************
+ * IndexIVFLocalSearchQuantizer
+ **************************************************************************************/
+
+IndexIVFLocalSearchQuantizer::IndexIVFLocalSearchQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M, /* number of subquantizers */
+ size_t nbits, /* number of bit per subvector index */
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexIVFAdditiveQuantizer(&lsq, quantizer, d, nlist, metric),
+ lsq(d, M, nbits, search_type) {
+ code_size = invlists->code_size = lsq.code_size;
+}
+
+IndexIVFLocalSearchQuantizer::IndexIVFLocalSearchQuantizer()
+ : IndexIVFAdditiveQuantizer(&lsq) {}
+
+IndexIVFLocalSearchQuantizer::~IndexIVFLocalSearchQuantizer() = default;
+
+/**************************************************************************************
+ * IndexIVFProductResidualQuantizer
+ **************************************************************************************/
+
+IndexIVFProductResidualQuantizer::IndexIVFProductResidualQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexIVFAdditiveQuantizer(&prq, quantizer, d, nlist, metric),
+ prq(d, nsplits, Msub, nbits, search_type) {
+ code_size = invlists->code_size = prq.code_size;
+}
+
+IndexIVFProductResidualQuantizer::IndexIVFProductResidualQuantizer()
+ : IndexIVFAdditiveQuantizer(&prq) {}
+
+IndexIVFProductResidualQuantizer::~IndexIVFProductResidualQuantizer() = default;
+
+/**************************************************************************************
+ * IndexIVFProductLocalSearchQuantizer
+ **************************************************************************************/
+
+IndexIVFProductLocalSearchQuantizer::IndexIVFProductLocalSearchQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric,
+ Search_type_t search_type)
+ : IndexIVFAdditiveQuantizer(&plsq, quantizer, d, nlist, metric),
+ plsq(d, nsplits, Msub, nbits, search_type) {
+ code_size = invlists->code_size = plsq.code_size;
+}
+
+IndexIVFProductLocalSearchQuantizer::IndexIVFProductLocalSearchQuantizer()
+ : IndexIVFAdditiveQuantizer(&plsq) {}
+
+IndexIVFProductLocalSearchQuantizer::~IndexIVFProductLocalSearchQuantizer() =
+ default;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizer.h
new file mode 100644
index 0000000..c999a3f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizer.h
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_INDEX_IVF_ADDITIVE_QUANTIZER_H
+#define FAISS_INDEX_IVF_ADDITIVE_QUANTIZER_H
+
+#include <faiss/impl/AdditiveQuantizer.h>
+
+#include <cstdint>
+#include <vector>
+
+#include <faiss/IndexIVF.h>
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/ProductAdditiveQuantizer.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/// Abstract class for IVF additive quantizers.
+/// The search functions are in common.
+struct IndexIVFAdditiveQuantizer : IndexIVF {
+ // the quantizer
+ AdditiveQuantizer* aq;
+ int use_precomputed_table = 0; // for future use
+
+ using Search_type_t = AdditiveQuantizer::Search_type_t;
+
+ IndexIVFAdditiveQuantizer(
+ AdditiveQuantizer* aq,
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ MetricType metric = METRIC_L2);
+
+ explicit IndexIVFAdditiveQuantizer(AdditiveQuantizer* aq);
+
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ idx_t train_encoder_num_vectors() const override;
+
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos = false) const override;
+
+ InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* params) const override;
+
+ void sa_decode(idx_t n, const uint8_t* codes, float* x) const override;
+
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ ~IndexIVFAdditiveQuantizer() override;
+};
+
+/** IndexIVF based on a residual quantizer. Stored vectors are
+ * approximated by residual quantization codes.
+ */
+struct IndexIVFResidualQuantizer : IndexIVFAdditiveQuantizer {
+ /// The residual quantizer used to encode the vectors
+ ResidualQuantizer rq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ IndexIVFResidualQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ const std::vector<size_t>& nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexIVFResidualQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M, /* number of subquantizers */
+ size_t nbits, /* number of bit per subvector index */
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexIVFResidualQuantizer();
+
+ virtual ~IndexIVFResidualQuantizer();
+};
+
+/** IndexIVF based on a residual quantizer. Stored vectors are
+ * approximated by residual quantization codes.
+ */
+struct IndexIVFLocalSearchQuantizer : IndexIVFAdditiveQuantizer {
+ /// The LSQ quantizer used to encode the vectors
+ LocalSearchQuantizer lsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ IndexIVFLocalSearchQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M, /* number of subquantizers */
+ size_t nbits, /* number of bit per subvector index */
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexIVFLocalSearchQuantizer();
+
+ virtual ~IndexIVFLocalSearchQuantizer();
+};
+
+/** IndexIVF based on a product residual quantizer. Stored vectors are
+ * approximated by product residual quantization codes.
+ */
+struct IndexIVFProductResidualQuantizer : IndexIVFAdditiveQuantizer {
+ /// The product residual quantizer used to encode the vectors
+ ProductResidualQuantizer prq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of residual quantizers
+ * @param Msub number of subquantizers per RQ
+ * @param nbits number of bit per subvector index
+ */
+ IndexIVFProductResidualQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexIVFProductResidualQuantizer();
+
+ virtual ~IndexIVFProductResidualQuantizer();
+};
+
+/** IndexIVF based on a product local search quantizer. Stored vectors are
+ * approximated by product local search quantization codes.
+ */
+struct IndexIVFProductLocalSearchQuantizer : IndexIVFAdditiveQuantizer {
+ /// The product local search quantizer used to encode the vectors
+ ProductLocalSearchQuantizer plsq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of local search quantizers
+ * @param Msub number of subquantizers per LSQ
+ * @param nbits number of bit per subvector index
+ */
+ IndexIVFProductLocalSearchQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_decompress);
+
+ IndexIVFProductLocalSearchQuantizer();
+
+ virtual ~IndexIVFProductLocalSearchQuantizer();
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizerFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizerFastScan.cpp
new file mode 100644
index 0000000..93fad18
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizerFastScan.cpp
@@ -0,0 +1,552 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+
+#include <cinttypes>
+#include <cstdio>
+
+#include <memory>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/LookupTableScaler.h>
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/invlists/BlockInvertedLists.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/quantize_lut.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+inline size_t roundup(size_t a, size_t b) {
+ return (a + b - 1) / b * b;
+}
+
+IndexIVFAdditiveQuantizerFastScan::IndexIVFAdditiveQuantizerFastScan(
+ Index* quantizer,
+ AdditiveQuantizer* aq,
+ size_t d,
+ size_t nlist,
+ MetricType metric,
+ int bbs)
+ : IndexIVFFastScan(quantizer, d, nlist, 0, metric) {
+ if (aq != nullptr) {
+ init(aq, nlist, metric, bbs);
+ }
+}
+
+void IndexIVFAdditiveQuantizerFastScan::init(
+ AdditiveQuantizer* aq,
+ size_t nlist,
+ MetricType metric,
+ int bbs) {
+ FAISS_THROW_IF_NOT(aq != nullptr);
+ FAISS_THROW_IF_NOT(!aq->nbits.empty());
+ FAISS_THROW_IF_NOT(aq->nbits[0] == 4);
+ if (metric == METRIC_INNER_PRODUCT) {
+ FAISS_THROW_IF_NOT_MSG(
+ aq->search_type == AdditiveQuantizer::ST_LUT_nonorm,
+ "Search type must be ST_LUT_nonorm for IP metric");
+ } else {
+ FAISS_THROW_IF_NOT_MSG(
+ aq->search_type == AdditiveQuantizer::ST_norm_lsq2x4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_rq2x4,
+ "Search type must be lsq2x4 or rq2x4 for L2 metric");
+ }
+
+ this->aq = aq;
+ if (metric_type == METRIC_L2) {
+ M = aq->M + 2; // 2x4 bits AQ
+ } else {
+ M = aq->M;
+ }
+ init_fastscan(aq, M, 4, nlist, metric, bbs);
+
+ max_train_points = 1024 * ksub * M;
+ by_residual = true;
+}
+
+IndexIVFAdditiveQuantizerFastScan::IndexIVFAdditiveQuantizerFastScan(
+ const IndexIVFAdditiveQuantizer& orig,
+ int bbs)
+ : IndexIVFFastScan(
+ orig.quantizer,
+ orig.d,
+ orig.nlist,
+ 0,
+ orig.metric_type),
+ aq(orig.aq) {
+ FAISS_THROW_IF_NOT(
+ metric_type == METRIC_INNER_PRODUCT || !orig.by_residual);
+
+ init(aq, nlist, metric_type, bbs);
+
+ is_trained = orig.is_trained;
+ ntotal = orig.ntotal;
+ nprobe = orig.nprobe;
+
+ for (size_t i = 0; i < nlist; i++) {
+ size_t nb = orig.invlists->list_size(i);
+ size_t nb2 = roundup(nb, bbs);
+ AlignedTable<uint8_t> tmp(nb2 * M2 / 2);
+ pq4_pack_codes(
+ InvertedLists::ScopedCodes(orig.invlists, i).get(),
+ nb,
+ M,
+ nb2,
+ bbs,
+ M2,
+ tmp.get());
+ invlists->add_entries(
+ i,
+ nb,
+ InvertedLists::ScopedIds(orig.invlists, i).get(),
+ tmp.get());
+ }
+
+ orig_invlists = orig.invlists;
+}
+
+IndexIVFAdditiveQuantizerFastScan::IndexIVFAdditiveQuantizerFastScan() {
+ bbs = 0;
+ M2 = 0;
+ aq = nullptr;
+
+ is_trained = false;
+}
+
+IndexIVFAdditiveQuantizerFastScan::~IndexIVFAdditiveQuantizerFastScan() =
+ default;
+
+/*********************************************************
+ * Training
+ *********************************************************/
+
+idx_t IndexIVFAdditiveQuantizerFastScan::train_encoder_num_vectors() const {
+ return max_train_points;
+}
+
+void IndexIVFAdditiveQuantizerFastScan::train_encoder(
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ if (aq->is_trained) {
+ return;
+ }
+
+ if (verbose) {
+ printf("training additive quantizer on %d vectors\n", int(n));
+ }
+
+ if (verbose) {
+ printf("training %zdx%zd additive quantizer on "
+ "%" PRId64 " vectors in %dD\n",
+ aq->M,
+ ksub,
+ n,
+ d);
+ }
+ aq->verbose = verbose;
+ aq->train(n, x);
+
+ // train norm quantizer
+ if (by_residual && metric_type == METRIC_L2) {
+ std::vector<float> decoded_x(n * d);
+ std::vector<uint8_t> x_codes(n * aq->code_size);
+ aq->compute_codes(x, x_codes.data(), n);
+ aq->decode(x_codes.data(), decoded_x.data(), n);
+
+ // add coarse centroids
+ std::vector<float> centroid(d);
+ for (idx_t i = 0; i < n; i++) {
+ auto xi = decoded_x.data() + i * d;
+ quantizer->reconstruct(assign[i], centroid.data());
+ fvec_add(d, centroid.data(), xi, xi);
+ }
+
+ std::vector<float> norms(n, 0);
+ fvec_norms_L2sqr(norms.data(), decoded_x.data(), d, n);
+
+ // re-train norm tables
+ aq->train_norm(n, norms.data());
+ }
+
+ if (metric_type == METRIC_L2) {
+ estimate_norm_scale(n, x);
+ }
+}
+
+void IndexIVFAdditiveQuantizerFastScan::estimate_norm_scale(
+ idx_t n,
+ const float* x_in) {
+ FAISS_THROW_IF_NOT(metric_type == METRIC_L2);
+
+ constexpr int seed = 0x980903;
+ constexpr size_t max_points_estimated = 65536;
+ size_t ns = n;
+ const float* x = fvecs_maybe_subsample(
+ d, &ns, max_points_estimated, x_in, verbose, seed);
+ n = ns;
+ std::unique_ptr<float[]> del_x;
+ if (x != x_in) {
+ del_x.reset((float*)x);
+ }
+
+ std::vector<idx_t> coarse_ids(n);
+ std::vector<float> coarse_dis(n);
+ quantizer->search(n, x, 1, coarse_dis.data(), coarse_ids.data());
+
+ AlignedTable<float> dis_tables;
+ AlignedTable<float> biases;
+
+ size_t index_nprobe = nprobe;
+ nprobe = 1;
+ CoarseQuantized cq{index_nprobe, coarse_dis.data(), coarse_ids.data()};
+ compute_LUT(n, x, cq, dis_tables, biases);
+ nprobe = index_nprobe;
+
+ float scale = 0;
+
+#pragma omp parallel for reduction(+ : scale)
+ for (idx_t i = 0; i < n; i++) {
+ const float* lut = dis_tables.get() + i * M * ksub;
+ scale += quantize_lut::aq_estimate_norm_scale(M, ksub, 2, lut);
+ }
+ scale /= n;
+ norm_scale = (int)std::roundf(std::max(scale, 1.0f));
+
+ if (verbose) {
+ printf("estimated norm scale: %lf\n", scale);
+ printf("rounded norm scale: %d\n", norm_scale);
+ }
+}
+
+/*********************************************************
+ * Code management functions
+ *********************************************************/
+
+void IndexIVFAdditiveQuantizerFastScan::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ idx_t bs = 65536;
+ if (n > bs) {
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(n, i0 + bs);
+ encode_vectors(
+ i1 - i0,
+ x + i0 * d,
+ list_nos + i0,
+ codes + i0 * code_size,
+ include_listnos);
+ }
+ return;
+ }
+
+ if (by_residual) {
+ std::vector<float> residuals(n * d);
+ std::vector<float> centroids(n * d);
+
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ if (list_nos[i] < 0) {
+ memset(residuals.data() + i * d, 0, sizeof(residuals[0]) * d);
+ } else {
+ quantizer->compute_residual(
+ x + i * d, residuals.data() + i * d, list_nos[i]);
+ }
+ }
+
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ auto c = centroids.data() + i * d;
+ quantizer->reconstruct(list_nos[i], c);
+ }
+
+ aq->compute_codes_add_centroids(
+ residuals.data(), codes, n, centroids.data());
+
+ } else {
+ aq->compute_codes(x, codes, n);
+ }
+
+ if (include_listnos) {
+ size_t coarse_size = coarse_code_size();
+ for (idx_t i = n - 1; i >= 0; i--) {
+ uint8_t* code = codes + i * (coarse_size + code_size);
+ memmove(code + coarse_size, codes + i * code_size, code_size);
+ encode_listno(list_nos[i], code);
+ }
+ }
+}
+
+/*********************************************************
+ * Search functions
+ *********************************************************/
+
+void IndexIVFAdditiveQuantizerFastScan::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+
+ FAISS_THROW_IF_NOT(k > 0);
+ bool rescale = (rescale_norm && norm_scale > 1 && metric_type == METRIC_L2);
+ if (!rescale) {
+ IndexIVFFastScan::search(n, x, k, distances, labels);
+ return;
+ }
+
+ NormTableScaler scaler(norm_scale);
+ IndexIVFFastScan::CoarseQuantized cq{nprobe};
+ search_dispatch_implem(n, x, k, distances, labels, cq, &scaler);
+}
+
+/*********************************************************
+ * Look-Up Table functions
+ *********************************************************/
+
+/********************************************************
+
+Let q denote the query vector,
+ x denote the quantized database vector,
+ c denote the corresponding IVF centroid,
+ r denote the residual (x - c).
+
+The L2 distance between q and x is:
+
+ d(q, x) = (q - x)^2
+ = (q - c - r)^2
+ = q^2 - 2<q, c> - 2<q, r> + x^2
+
+where q^2 is a constant for all x, <q,c> is only relevant to c,
+and x^2 is the quantized database vector norm.
+
+Different from IVFAdditiveQuantizer, we encode the quantized vector norm x^2
+instead of r^2. So that we only need to compute one LUT for each query vector:
+
+ LUT[m][k] = -2 * <q, codebooks[m][k]>
+
+`-2<q,c>` could be precomputed in `compute_LUT` and store in `biases`.
+if `by_residual=False`, `<q,c>` is simply 0.
+
+
+
+About norm look-up tables:
+
+To take advantage of the fast SIMD table lookups, we encode the norm by a 2x4
+bits 1D additive quantizer (simply treat the scalar norm as a 1D vector).
+
+Let `cm` denote the codebooks of the trained 2x4 bits 1D additive quantizer,
+size (2, 16); `bm` denote the encoding code of the norm, a 8-bit integer; `cb`
+denote the codebooks of the additive quantizer to encode the database vector,
+size (M, 16).
+
+The decoded norm is:
+
+ decoded_norm = cm[0][bm & 15] + cm[1][bm >> 4]
+
+The decoding is actually doing a table look-up.
+
+We combine the norm LUTs and the IP LUTs together:
+
+ LUT is a 2D table, size (M + 2, 16)
+ if m < M :
+ LUT[m][k] = -2 * <q, cb[m][k]>
+ else:
+ LUT[m][k] = cm[m - M][k]
+
+********************************************************/
+
+bool IndexIVFAdditiveQuantizerFastScan::lookup_table_is_3d() const {
+ return false;
+}
+
+void IndexIVFAdditiveQuantizerFastScan::compute_LUT(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<float>& dis_tables,
+ AlignedTable<float>& biases) const {
+ const size_t dim12 = ksub * M;
+ const size_t ip_dim12 = aq->M * ksub;
+ const size_t nprobe = cq.nprobe;
+
+ dis_tables.resize(n * dim12);
+
+ float coef = 1.0f;
+ if (metric_type == METRIC_L2) {
+ coef = -2.0f;
+ }
+
+ if (by_residual) {
+ // bias = coef * <q, c>
+ // NOTE: q^2 is not added to `biases`
+ biases.resize(n * nprobe);
+#pragma omp parallel
+ {
+ std::vector<float> centroid(d);
+ float* c = centroid.data();
+
+#pragma omp for
+ for (idx_t ij = 0; ij < n * nprobe; ij++) {
+ int i = ij / nprobe;
+ quantizer->reconstruct(cq.ids[ij], c);
+ biases[ij] = coef * fvec_inner_product(c, x + i * d, d);
+ }
+ }
+ }
+
+ if (metric_type == METRIC_L2) {
+ const size_t norm_dim12 = 2 * ksub;
+
+ // inner product look-up tables
+ aq->compute_LUT(n, x, dis_tables.data(), -2.0f, dim12);
+
+ // copy and rescale norm look-up tables
+ auto norm_tabs = aq->norm_tabs;
+ if (rescale_norm && norm_scale > 1 && metric_type == METRIC_L2) {
+ for (size_t i = 0; i < norm_tabs.size(); i++) {
+ norm_tabs[i] /= norm_scale;
+ }
+ }
+ const float* norm_lut = norm_tabs.data();
+ FAISS_THROW_IF_NOT(norm_tabs.size() == norm_dim12);
+
+ // combine them
+#pragma omp parallel for if (n > 100)
+ for (idx_t i = 0; i < n; i++) {
+ float* tab = dis_tables.data() + i * dim12 + ip_dim12;
+ memcpy(tab, norm_lut, norm_dim12 * sizeof(*tab));
+ }
+
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ aq->compute_LUT(n, x, dis_tables.get());
+ } else {
+ FAISS_THROW_FMT("metric %d not supported", metric_type);
+ }
+}
+
+/********** IndexIVFLocalSearchQuantizerFastScan ************/
+IndexIVFLocalSearchQuantizerFastScan::IndexIVFLocalSearchQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits,
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : IndexIVFAdditiveQuantizerFastScan(
+ quantizer,
+ nullptr,
+ d,
+ nlist,
+ metric,
+ bbs),
+ lsq(d, M, nbits, search_type) {
+ FAISS_THROW_IF_NOT(nbits == 4);
+ init(&lsq, nlist, metric, bbs);
+}
+
+IndexIVFLocalSearchQuantizerFastScan::IndexIVFLocalSearchQuantizerFastScan() {
+ aq = &lsq;
+}
+
+/********** IndexIVFResidualQuantizerFastScan ************/
+IndexIVFResidualQuantizerFastScan::IndexIVFResidualQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits,
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : IndexIVFAdditiveQuantizerFastScan(
+ quantizer,
+ nullptr,
+ d,
+ nlist,
+ metric,
+ bbs),
+ rq(d, M, nbits, search_type) {
+ FAISS_THROW_IF_NOT(nbits == 4);
+ init(&rq, nlist, metric, bbs);
+}
+
+IndexIVFResidualQuantizerFastScan::IndexIVFResidualQuantizerFastScan() {
+ aq = &rq;
+}
+
+/********** IndexIVFProductLocalSearchQuantizerFastScan ************/
+IndexIVFProductLocalSearchQuantizerFastScan::
+ IndexIVFProductLocalSearchQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : IndexIVFAdditiveQuantizerFastScan(
+ quantizer,
+ nullptr,
+ d,
+ nlist,
+ metric,
+ bbs),
+ plsq(d, nsplits, Msub, nbits, search_type) {
+ FAISS_THROW_IF_NOT(nbits == 4);
+ init(&plsq, nlist, metric, bbs);
+}
+
+IndexIVFProductLocalSearchQuantizerFastScan::
+ IndexIVFProductLocalSearchQuantizerFastScan() {
+ aq = &plsq;
+}
+
+/********** IndexIVFProductResidualQuantizerFastScan ************/
+IndexIVFProductResidualQuantizerFastScan::
+ IndexIVFProductResidualQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric,
+ Search_type_t search_type,
+ int bbs)
+ : IndexIVFAdditiveQuantizerFastScan(
+ quantizer,
+ nullptr,
+ d,
+ nlist,
+ metric,
+ bbs),
+ prq(d, nsplits, Msub, nbits, search_type) {
+ FAISS_THROW_IF_NOT(nbits == 4);
+ init(&prq, nlist, metric, bbs);
+}
+
+IndexIVFProductResidualQuantizerFastScan::
+ IndexIVFProductResidualQuantizerFastScan() {
+ aq = &prq;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizerFastScan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizerFastScan.h
new file mode 100644
index 0000000..75ec1d1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFAdditiveQuantizerFastScan.h
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <memory>
+
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/IndexIVFFastScan.h>
+#include <faiss/impl/AdditiveQuantizer.h>
+#include <faiss/impl/ProductAdditiveQuantizer.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+/** Fast scan version of IVFAQ. Works for 4-bit AQ for now.
+ *
+ * The codes in the inverted lists are not stored sequentially but
+ * grouped in blocks of size bbs. This makes it possible to very quickly
+ * compute distances with SIMD instructions.
+ *
+ * Implementations (implem):
+ * 0: auto-select implementation (default)
+ * 1: orig's search, re-implemented
+ * 2: orig's search, re-ordered by invlist
+ * 10: optimizer int16 search, collect results in heap, no qbs
+ * 11: idem, collect results in reservoir
+ * 12: optimizer int16 search, collect results in heap, uses qbs
+ * 13: idem, collect results in reservoir
+ */
+
+struct IndexIVFAdditiveQuantizerFastScan : IndexIVFFastScan {
+ using Search_type_t = AdditiveQuantizer::Search_type_t;
+
+ AdditiveQuantizer* aq;
+
+ bool rescale_norm = false;
+ int norm_scale = 1;
+
+ // max number of training vectors
+ size_t max_train_points;
+
+ IndexIVFAdditiveQuantizerFastScan(
+ Index* quantizer,
+ AdditiveQuantizer* aq,
+ size_t d,
+ size_t nlist,
+ MetricType metric = METRIC_L2,
+ int bbs = 32);
+
+ void init(AdditiveQuantizer* aq, size_t nlist, MetricType metric, int bbs);
+
+ IndexIVFAdditiveQuantizerFastScan();
+
+ ~IndexIVFAdditiveQuantizerFastScan() override;
+
+ // built from an IndexIVFAQ
+ explicit IndexIVFAdditiveQuantizerFastScan(
+ const IndexIVFAdditiveQuantizer& orig,
+ int bbs = 32);
+
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ idx_t train_encoder_num_vectors() const override;
+
+ void estimate_norm_scale(idx_t n, const float* x);
+
+ /// same as the regular IVFAQ encoder. The codes are not reorganized by
+ /// blocks a that point
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listno = false) const override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ // prepare look-up tables
+
+ bool lookup_table_is_3d() const override;
+
+ void compute_LUT(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<float>& dis_tables,
+ AlignedTable<float>& biases) const override;
+};
+
+struct IndexIVFLocalSearchQuantizerFastScan
+ : IndexIVFAdditiveQuantizerFastScan {
+ LocalSearchQuantizer lsq;
+
+ IndexIVFLocalSearchQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_lsq2x4,
+ int bbs = 32);
+
+ IndexIVFLocalSearchQuantizerFastScan();
+};
+
+struct IndexIVFResidualQuantizerFastScan : IndexIVFAdditiveQuantizerFastScan {
+ ResidualQuantizer rq;
+
+ IndexIVFResidualQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_lsq2x4,
+ int bbs = 32);
+
+ IndexIVFResidualQuantizerFastScan();
+};
+
+struct IndexIVFProductLocalSearchQuantizerFastScan
+ : IndexIVFAdditiveQuantizerFastScan {
+ ProductLocalSearchQuantizer plsq;
+
+ IndexIVFProductLocalSearchQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_lsq2x4,
+ int bbs = 32);
+
+ IndexIVFProductLocalSearchQuantizerFastScan();
+};
+
+struct IndexIVFProductResidualQuantizerFastScan
+ : IndexIVFAdditiveQuantizerFastScan {
+ ProductResidualQuantizer prq;
+
+ IndexIVFProductResidualQuantizerFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ Search_type_t search_type = AdditiveQuantizer::ST_norm_lsq2x4,
+ int bbs = 32);
+
+ IndexIVFProductResidualQuantizerFastScan();
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFastScan.cpp
new file mode 100644
index 0000000..f031a51
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFastScan.cpp
@@ -0,0 +1,1429 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFFastScan.h>
+
+#include <cassert>
+#include <cinttypes>
+#include <cstdio>
+#include <set>
+
+#include <omp.h>
+
+#include <memory>
+
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/LookupTableScaler.h>
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/impl/simd_result_handlers.h>
+#include <faiss/invlists/BlockInvertedLists.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/quantize_lut.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+using namespace simd_result_handlers;
+
+inline size_t roundup(size_t a, size_t b) {
+ return (a + b - 1) / b * b;
+}
+
+IndexIVFFastScan::IndexIVFFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t code_size,
+ MetricType metric)
+ : IndexIVF(quantizer, d, nlist, code_size, metric) {
+ // unlike other indexes, we prefer no residuals for performance reasons.
+ by_residual = false;
+ FAISS_THROW_IF_NOT(metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT);
+}
+
+IndexIVFFastScan::IndexIVFFastScan() {
+ bbs = 0;
+ M2 = 0;
+ is_trained = false;
+ by_residual = false;
+}
+
+void IndexIVFFastScan::init_fastscan(
+ Quantizer* fine_quantizer,
+ size_t M,
+ size_t nbits_init,
+ size_t nlist,
+ MetricType /* metric */,
+ int bbs_2) {
+ FAISS_THROW_IF_NOT(bbs_2 % 32 == 0);
+ FAISS_THROW_IF_NOT(nbits_init == 4);
+ FAISS_THROW_IF_NOT(fine_quantizer->d == d);
+
+ this->fine_quantizer = fine_quantizer;
+ this->M = M;
+ this->nbits = nbits_init;
+ this->bbs = bbs_2;
+ ksub = (1 << nbits_init);
+ M2 = roundup(M, 2);
+ code_size = M2 / 2;
+ FAISS_THROW_IF_NOT(code_size == fine_quantizer->code_size);
+
+ is_trained = false;
+ replace_invlists(new BlockInvertedLists(nlist, get_CodePacker()), true);
+}
+
+void IndexIVFFastScan::init_code_packer() {
+ auto bil = dynamic_cast<BlockInvertedLists*>(invlists);
+ FAISS_THROW_IF_NOT(bil);
+ delete bil->packer; // in case there was one before
+ bil->packer = get_CodePacker();
+}
+
+IndexIVFFastScan::~IndexIVFFastScan() = default;
+
+/*********************************************************
+ * Code management functions
+ *********************************************************/
+
+void IndexIVFFastScan::add_with_ids(
+ idx_t n,
+ const float* x,
+ const idx_t* xids) {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ // do some blocking to avoid excessive allocs
+ constexpr idx_t bs = 65536;
+ if (n > bs) {
+ double t0 = getmillisecs();
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(n, i0 + bs);
+ if (verbose) {
+ double t1 = getmillisecs();
+ double elapsed_time = (t1 - t0) / 1000;
+ double total_time = 0;
+ if (i0 != 0) {
+ total_time = elapsed_time / i0 * n;
+ }
+ size_t mem = get_mem_usage_kb() / (1 << 10);
+
+ printf("IndexIVFFastScan::add_with_ids %zd/%zd, time %.2f/%.2f, RSS %zdMB\n",
+ size_t(i1),
+ size_t(n),
+ elapsed_time,
+ total_time,
+ mem);
+ }
+ add_with_ids(i1 - i0, x + i0 * d, xids ? xids + i0 : nullptr);
+ }
+ return;
+ }
+ InterruptCallback::check();
+
+ direct_map.check_can_add(xids);
+ std::unique_ptr<idx_t[]> idx(new idx_t[n]);
+ quantizer->assign(n, x, idx.get());
+
+ AlignedTable<uint8_t> flat_codes(n * code_size);
+ encode_vectors(n, x, idx.get(), flat_codes.get());
+
+ DirectMapAdd dm_adder(direct_map, n, xids);
+ BlockInvertedLists* bil = dynamic_cast<BlockInvertedLists*>(invlists);
+ FAISS_THROW_IF_NOT_MSG(bil, "only block inverted lists supported");
+
+ // prepare batches
+ std::vector<idx_t> order(n);
+ for (idx_t i = 0; i < n; i++) {
+ order[i] = i;
+ }
+
+ // TODO should not need stable
+ std::stable_sort(order.begin(), order.end(), [&idx](idx_t a, idx_t b) {
+ return idx[a] < idx[b];
+ });
+
+ // TODO parallelize
+ idx_t i0 = 0;
+ while (i0 < n) {
+ idx_t list_no = idx[order[i0]];
+ idx_t i1 = i0 + 1;
+ while (i1 < n && idx[order[i1]] == list_no) {
+ i1++;
+ }
+
+ if (list_no == -1) {
+ i0 = i1;
+ continue;
+ }
+
+ // make linear array
+ AlignedTable<uint8_t> list_codes((i1 - i0) * code_size);
+ size_t list_size = bil->list_size(list_no);
+
+ bil->resize(list_no, list_size + i1 - i0);
+
+ for (idx_t i = i0; i < i1; i++) {
+ size_t ofs = list_size + i - i0;
+ idx_t id = xids ? xids[order[i]] : ntotal + order[i];
+ dm_adder.add(order[i], list_no, ofs);
+ bil->ids[list_no][ofs] = id;
+ memcpy(list_codes.data() + (i - i0) * code_size,
+ flat_codes.data() + order[i] * code_size,
+ code_size);
+ }
+ pq4_pack_codes_range(
+ list_codes.data(),
+ M,
+ list_size,
+ list_size + i1 - i0,
+ bbs,
+ M2,
+ bil->codes[list_no].data());
+
+ i0 = i1;
+ }
+
+ ntotal += n;
+}
+
+CodePacker* IndexIVFFastScan::get_CodePacker() const {
+ return new CodePackerPQ4(M, bbs);
+}
+
+/*********************************************************
+ * search
+ *********************************************************/
+
+namespace {
+
+template <class C, typename dis_t>
+void estimators_from_tables_generic(
+ const IndexIVFFastScan& index,
+ const uint8_t* codes,
+ size_t ncodes,
+ const dis_t* dis_table,
+ const int64_t* ids,
+ float bias,
+ size_t k,
+ typename C::T* heap_dis,
+ int64_t* heap_ids,
+ const NormTableScaler* scaler) {
+ using accu_t = typename C::T;
+ size_t nscale = scaler ? scaler->nscale : 0;
+ for (size_t j = 0; j < ncodes; ++j) {
+ BitstringReader bsr(codes + j * index.code_size, index.code_size);
+ accu_t dis = bias;
+ const dis_t* __restrict dt = dis_table;
+
+ for (size_t m = 0; m < index.M - nscale; m++) {
+ uint64_t c = bsr.read(index.nbits);
+ dis += dt[c];
+ dt += index.ksub;
+ }
+
+ if (scaler) {
+ for (size_t m = 0; m < nscale; m++) {
+ uint64_t c = bsr.read(index.nbits);
+ dis += scaler->scale_one(dt[c]);
+ dt += index.ksub;
+ }
+ }
+
+ if (C::cmp(heap_dis[0], dis)) {
+ heap_pop<C>(k, heap_dis, heap_ids);
+ heap_push<C>(k, heap_dis, heap_ids, dis, ids[j]);
+ }
+ }
+}
+
+using namespace quantize_lut;
+
+} // anonymous namespace
+
+/*********************************************************
+ * Look-Up Table functions
+ *********************************************************/
+
+void IndexIVFFastScan::compute_LUT_uint8(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<uint8_t>& dis_tables,
+ AlignedTable<uint16_t>& biases,
+ float* normalizers) const {
+ AlignedTable<float> dis_tables_float;
+ AlignedTable<float> biases_float;
+
+ compute_LUT(n, x, cq, dis_tables_float, biases_float);
+ size_t nprobe = cq.nprobe;
+ bool lut_is_3d = lookup_table_is_3d();
+ size_t dim123 = ksub * M;
+ size_t dim123_2 = ksub * M2;
+ if (lut_is_3d) {
+ dim123 *= nprobe;
+ dim123_2 *= nprobe;
+ }
+ dis_tables.resize(n * dim123_2);
+ if (biases_float.get()) {
+ biases.resize(n * nprobe);
+ }
+
+ // OMP for MSVC requires i to have signed integral type
+#pragma omp parallel for if (n > 100)
+ for (int64_t i = 0; i < n; i++) {
+ const float* t_in = dis_tables_float.get() + i * dim123;
+ const float* b_in = nullptr;
+ uint8_t* t_out = dis_tables.get() + i * dim123_2;
+ uint16_t* b_out = nullptr;
+ if (biases_float.get()) {
+ b_in = biases_float.get() + i * nprobe;
+ b_out = biases.get() + i * nprobe;
+ }
+
+ quantize_LUT_and_bias(
+ nprobe,
+ M,
+ ksub,
+ lut_is_3d,
+ t_in,
+ b_in,
+ t_out,
+ M2,
+ b_out,
+ normalizers + 2 * i,
+ normalizers + 2 * i + 1);
+ }
+}
+
+/*********************************************************
+ * Search functions
+ *********************************************************/
+
+void IndexIVFFastScan::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ const IVFSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(
+ params, "IndexIVFFastScan params have incorrect type");
+ }
+
+ search_preassigned(
+ n, x, k, nullptr, nullptr, distances, labels, false, params);
+}
+
+void IndexIVFFastScan::search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* stats) const {
+ size_t nprobe = this->nprobe;
+ if (params) {
+ FAISS_THROW_IF_NOT(params->max_codes == 0);
+ nprobe = params->nprobe;
+ }
+
+ FAISS_THROW_IF_NOT_MSG(
+ !store_pairs, "store_pairs not supported for this index");
+ FAISS_THROW_IF_NOT_MSG(!stats, "stats not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ const CoarseQuantized cq = {nprobe, centroid_dis, assign};
+ search_dispatch_implem(n, x, k, distances, labels, cq, nullptr, params);
+}
+
+void IndexIVFFastScan::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params_in) const {
+ size_t nprobe = this->nprobe;
+ const IVFSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(
+ params, "IndexIVFFastScan params have incorrect type");
+ nprobe = params->nprobe;
+ }
+
+ const CoarseQuantized cq = {nprobe, nullptr, nullptr};
+ range_search_dispatch_implem(n, x, radius, *result, cq, nullptr, params);
+}
+
+namespace {
+
+template <class C>
+ResultHandlerCompare<C, true>* make_knn_handler_fixC(
+ int impl,
+ idx_t n,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const IDSelector* sel) {
+ using HeapHC = HeapHandler<C, true>;
+ using ReservoirHC = ReservoirHandler<C, true>;
+ using SingleResultHC = SingleResultHandler<C, true>;
+
+ if (k == 1) {
+ return new SingleResultHC(n, 0, distances, labels, sel);
+ } else if (impl % 2 == 0) {
+ return new HeapHC(n, 0, k, distances, labels, sel);
+ } else /* if (impl % 2 == 1) */ {
+ return new ReservoirHC(n, 0, k, 2 * k, distances, labels, sel);
+ }
+}
+
+SIMDResultHandlerToFloat* make_knn_handler(
+ bool is_max,
+ int impl,
+ idx_t n,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const IDSelector* sel) {
+ if (is_max) {
+ return make_knn_handler_fixC<CMax<uint16_t, int64_t>>(
+ impl, n, k, distances, labels, sel);
+ } else {
+ return make_knn_handler_fixC<CMin<uint16_t, int64_t>>(
+ impl, n, k, distances, labels, sel);
+ }
+}
+
+using CoarseQuantized = IndexIVFFastScan::CoarseQuantized;
+
+struct CoarseQuantizedWithBuffer : CoarseQuantized {
+ explicit CoarseQuantizedWithBuffer(const CoarseQuantized& cq)
+ : CoarseQuantized(cq) {}
+
+ bool done() const {
+ return ids != nullptr;
+ }
+
+ std::vector<idx_t> ids_buffer;
+ std::vector<float> dis_buffer;
+
+ void quantize(
+ const Index* quantizer,
+ idx_t n,
+ const float* x,
+ const SearchParameters* quantizer_params) {
+ dis_buffer.resize(nprobe * n);
+ ids_buffer.resize(nprobe * n);
+ quantizer->search(
+ n,
+ x,
+ nprobe,
+ dis_buffer.data(),
+ ids_buffer.data(),
+ quantizer_params);
+ dis = dis_buffer.data();
+ ids = ids_buffer.data();
+ }
+};
+
+struct CoarseQuantizedSlice : CoarseQuantizedWithBuffer {
+ size_t i0, i1;
+ CoarseQuantizedSlice(const CoarseQuantized& cq, size_t i0, size_t i1)
+ : CoarseQuantizedWithBuffer(cq), i0(i0), i1(i1) {
+ if (done()) {
+ dis += nprobe * i0;
+ ids += nprobe * i0;
+ }
+ }
+
+ void quantize_slice(
+ const Index* quantizer,
+ const float* x,
+ const SearchParameters* quantizer_params) {
+ quantize(quantizer, i1 - i0, x + quantizer->d * i0, quantizer_params);
+ }
+};
+
+int compute_search_nslice(
+ const IndexIVFFastScan* index,
+ size_t n,
+ size_t nprobe) {
+ int nslice;
+ if (n <= omp_get_max_threads()) {
+ nslice = n;
+ } else if (index->lookup_table_is_3d()) {
+ // make sure we don't make too big LUT tables
+ size_t lut_size_per_query = index->M * index->ksub * nprobe *
+ (sizeof(float) + sizeof(uint8_t));
+
+ size_t max_lut_size = precomputed_table_max_bytes;
+ // how many queries we can handle within mem budget
+ size_t nq_ok = std::max(max_lut_size / lut_size_per_query, size_t(1));
+ nslice = roundup(
+ std::max(size_t(n / nq_ok), size_t(1)), omp_get_max_threads());
+ } else {
+ // LUTs unlikely to be a limiting factor
+ nslice = omp_get_max_threads();
+ }
+ return nslice;
+}
+
+} // namespace
+
+void IndexIVFFastScan::search_dispatch_implem(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq_in,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ const idx_t nprobe = params ? params->nprobe : this->nprobe;
+ const IDSelector* sel = (params) ? params->sel : nullptr;
+ const SearchParameters* quantizer_params =
+ params ? params->quantizer_params : nullptr;
+
+ bool is_max = !is_similarity_metric(metric_type);
+ using RH = SIMDResultHandlerToFloat;
+
+ if (n == 0) {
+ return;
+ }
+
+ // actual implementation used
+ int impl = implem;
+
+ if (impl == 0) {
+ if (bbs == 32) {
+ impl = 12;
+ } else {
+ impl = 10;
+ }
+ if (k > 20) { // use reservoir rather than heap
+ impl++;
+ }
+ }
+
+ bool multiple_threads =
+ n > 1 && impl >= 10 && impl <= 13 && omp_get_max_threads() > 1;
+ if (impl >= 100) {
+ multiple_threads = false;
+ impl -= 100;
+ }
+
+ CoarseQuantizedWithBuffer cq(cq_in);
+ cq.nprobe = nprobe;
+
+ if (!cq.done() && !multiple_threads) {
+ // we do the coarse quantization here execpt when search is
+ // sliced over threads (then it is more efficient to have each thread do
+ // its own coarse quantization)
+ cq.quantize(quantizer, n, x, quantizer_params);
+ invlists->prefetch_lists(cq.ids, n * cq.nprobe);
+ }
+
+ if (impl == 1) {
+ if (is_max) {
+ search_implem_1<CMax<float, int64_t>>(
+ n, x, k, distances, labels, cq, scaler, params);
+ } else {
+ search_implem_1<CMin<float, int64_t>>(
+ n, x, k, distances, labels, cq, scaler, params);
+ }
+ } else if (impl == 2) {
+ if (is_max) {
+ search_implem_2<CMax<uint16_t, int64_t>>(
+ n, x, k, distances, labels, cq, scaler, params);
+ } else {
+ search_implem_2<CMin<uint16_t, int64_t>>(
+ n, x, k, distances, labels, cq, scaler, params);
+ }
+ } else if (impl >= 10 && impl <= 15) {
+ size_t ndis = 0, nlist_visited = 0;
+
+ if (!multiple_threads) {
+ // clang-format off
+ if (impl == 12 || impl == 13) {
+ std::unique_ptr<RH> handler(
+ make_knn_handler(
+ is_max,
+ impl,
+ n,
+ k,
+ distances,
+ labels, sel
+ )
+ );
+ search_implem_12(
+ n, x, *handler.get(),
+ cq, &ndis, &nlist_visited, scaler, params);
+ } else if (impl == 14 || impl == 15) {
+ search_implem_14(
+ n, x, k, distances, labels,
+ cq, impl, scaler, params);
+ } else {
+ std::unique_ptr<RH> handler(
+ make_knn_handler(
+ is_max,
+ impl,
+ n,
+ k,
+ distances,
+ labels,
+ sel
+ )
+ );
+ search_implem_10(
+ n, x, *handler.get(), cq,
+ &ndis, &nlist_visited, scaler, params);
+ }
+ // clang-format on
+ } else {
+ // explicitly slice over threads
+ int nslice = compute_search_nslice(this, n, cq.nprobe);
+ if (impl == 14 || impl == 15) {
+ // this might require slicing if there are too
+ // many queries (for now we keep this simple)
+ search_implem_14(
+ n, x, k, distances, labels, cq, impl, scaler, params);
+ } else {
+#pragma omp parallel for reduction(+ : ndis, nlist_visited)
+ for (int slice = 0; slice < nslice; slice++) {
+ idx_t i0 = n * slice / nslice;
+ idx_t i1 = n * (slice + 1) / nslice;
+ float* dis_i = distances + i0 * k;
+ idx_t* lab_i = labels + i0 * k;
+ CoarseQuantizedSlice cq_i(cq, i0, i1);
+ if (!cq_i.done()) {
+ cq_i.quantize_slice(quantizer, x, quantizer_params);
+ }
+ std::unique_ptr<RH> handler(make_knn_handler(
+ is_max, impl, i1 - i0, k, dis_i, lab_i, sel));
+ // clang-format off
+ if (impl == 12 || impl == 13) {
+ search_implem_12(
+ i1 - i0, x + i0 * d, *handler.get(),
+ cq_i, &ndis, &nlist_visited, scaler, params);
+ } else {
+ search_implem_10(
+ i1 - i0, x + i0 * d, *handler.get(),
+ cq_i, &ndis, &nlist_visited, scaler, params);
+ }
+ // clang-format on
+ }
+ }
+ }
+ indexIVF_stats.nq += n;
+ indexIVF_stats.ndis += ndis;
+ indexIVF_stats.nlist += nlist_visited;
+ } else {
+ FAISS_THROW_FMT("implem %d does not exist", implem);
+ }
+}
+
+void IndexIVFFastScan::range_search_dispatch_implem(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult& rres,
+ const CoarseQuantized& cq_in,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ // const idx_t nprobe = params ? params->nprobe : this->nprobe;
+ const IDSelector* sel = (params) ? params->sel : nullptr;
+ const SearchParameters* quantizer_params =
+ params ? params->quantizer_params : nullptr;
+
+ bool is_max = !is_similarity_metric(metric_type);
+
+ if (n == 0) {
+ return;
+ }
+
+ // actual implementation used
+ int impl = implem;
+
+ if (impl == 0) {
+ if (bbs == 32) {
+ impl = 12;
+ } else {
+ impl = 10;
+ }
+ }
+
+ CoarseQuantizedWithBuffer cq(cq_in);
+
+ bool multiple_threads =
+ n > 1 && impl >= 10 && impl <= 13 && omp_get_max_threads() > 1;
+ if (impl >= 100) {
+ multiple_threads = false;
+ impl -= 100;
+ }
+
+ if (!multiple_threads && !cq.done()) {
+ cq.quantize(quantizer, n, x, quantizer_params);
+ invlists->prefetch_lists(cq.ids, n * cq.nprobe);
+ }
+
+ size_t ndis = 0, nlist_visited = 0;
+
+ if (!multiple_threads) { // single thread
+ std::unique_ptr<SIMDResultHandlerToFloat> handler;
+ if (is_max) {
+ handler.reset(new RangeHandler<CMax<uint16_t, int64_t>, true>(
+ rres, radius, 0, sel));
+ } else {
+ handler.reset(new RangeHandler<CMin<uint16_t, int64_t>, true>(
+ rres, radius, 0, sel));
+ }
+ if (impl == 12) {
+ search_implem_12(
+ n, x, *handler.get(), cq, &ndis, &nlist_visited, scaler);
+ } else if (impl == 10) {
+ search_implem_10(
+ n, x, *handler.get(), cq, &ndis, &nlist_visited, scaler);
+ } else {
+ FAISS_THROW_FMT("Range search implem %d not implemented", impl);
+ }
+ } else {
+ // explicitly slice over threads
+ int nslice = compute_search_nslice(this, n, cq.nprobe);
+#pragma omp parallel
+ {
+ RangeSearchPartialResult pres(&rres);
+
+#pragma omp for reduction(+ : ndis, nlist_visited)
+ for (int slice = 0; slice < nslice; slice++) {
+ idx_t i0 = n * slice / nslice;
+ idx_t i1 = n * (slice + 1) / nslice;
+ CoarseQuantizedSlice cq_i(cq, i0, i1);
+ if (!cq_i.done()) {
+ cq_i.quantize_slice(quantizer, x, quantizer_params);
+ }
+ std::unique_ptr<SIMDResultHandlerToFloat> handler;
+ if (is_max) {
+ handler.reset(new PartialRangeHandler<
+ CMax<uint16_t, int64_t>,
+ true>(pres, radius, 0, i0, i1, sel));
+ } else {
+ handler.reset(new PartialRangeHandler<
+ CMin<uint16_t, int64_t>,
+ true>(pres, radius, 0, i0, i1, sel));
+ }
+
+ if (impl == 12 || impl == 13) {
+ search_implem_12(
+ i1 - i0,
+ x + i0 * d,
+ *handler.get(),
+ cq_i,
+ &ndis,
+ &nlist_visited,
+ scaler,
+ params);
+ } else {
+ search_implem_10(
+ i1 - i0,
+ x + i0 * d,
+ *handler.get(),
+ cq_i,
+ &ndis,
+ &nlist_visited,
+ scaler,
+ params);
+ }
+ }
+ pres.finalize();
+ }
+ }
+
+ indexIVF_stats.nq += n;
+ indexIVF_stats.ndis += ndis;
+ indexIVF_stats.nlist += nlist_visited;
+}
+
+template <class C>
+void IndexIVFFastScan::search_implem_1(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ FAISS_THROW_IF_NOT(orig_invlists);
+
+ size_t dim12 = ksub * M;
+ AlignedTable<float> dis_tables;
+ AlignedTable<float> biases;
+
+ compute_LUT(n, x, cq, dis_tables, biases);
+
+ bool single_LUT = !lookup_table_is_3d();
+
+ size_t ndis = 0, nlist_visited = 0;
+ size_t nprobe = cq.nprobe;
+#pragma omp parallel for reduction(+ : ndis, nlist_visited)
+ for (idx_t i = 0; i < n; i++) {
+ int64_t* heap_ids = labels + i * k;
+ float* heap_dis = distances + i * k;
+ heap_heapify<C>(k, heap_dis, heap_ids);
+ float* LUT = nullptr;
+
+ if (single_LUT) {
+ LUT = dis_tables.get() + i * dim12;
+ }
+ for (idx_t j = 0; j < nprobe; j++) {
+ if (!single_LUT) {
+ LUT = dis_tables.get() + (i * nprobe + j) * dim12;
+ }
+ idx_t list_no = cq.ids[i * nprobe + j];
+ if (list_no < 0)
+ continue;
+ size_t ls = orig_invlists->list_size(list_no);
+ if (ls == 0)
+ continue;
+ InvertedLists::ScopedCodes codes(orig_invlists, list_no);
+ InvertedLists::ScopedIds ids(orig_invlists, list_no);
+
+ float bias = biases.get() ? biases[i * nprobe + j] : 0;
+
+ estimators_from_tables_generic<C>(
+ *this,
+ codes.get(),
+ ls,
+ LUT,
+ ids.get(),
+ bias,
+ k,
+ heap_dis,
+ heap_ids,
+ scaler);
+ nlist_visited++;
+ ndis++;
+ }
+ heap_reorder<C>(k, heap_dis, heap_ids);
+ }
+ indexIVF_stats.nq += n;
+ indexIVF_stats.ndis += ndis;
+ indexIVF_stats.nlist += nlist_visited;
+}
+
+template <class C>
+void IndexIVFFastScan::search_implem_2(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ FAISS_THROW_IF_NOT(orig_invlists);
+
+ size_t dim12 = ksub * M2;
+ AlignedTable<uint8_t> dis_tables;
+ AlignedTable<uint16_t> biases;
+ std::unique_ptr<float[]> normalizers(new float[2 * n]);
+
+ compute_LUT_uint8(n, x, cq, dis_tables, biases, normalizers.get());
+
+ bool single_LUT = !lookup_table_is_3d();
+
+ size_t ndis = 0, nlist_visited = 0;
+ size_t nprobe = cq.nprobe;
+
+#pragma omp parallel for reduction(+ : ndis, nlist_visited)
+ for (idx_t i = 0; i < n; i++) {
+ std::vector<uint16_t> tmp_dis(k);
+ int64_t* heap_ids = labels + i * k;
+ uint16_t* heap_dis = tmp_dis.data();
+ heap_heapify<C>(k, heap_dis, heap_ids);
+ const uint8_t* LUT = nullptr;
+
+ if (single_LUT) {
+ LUT = dis_tables.get() + i * dim12;
+ }
+ for (idx_t j = 0; j < nprobe; j++) {
+ if (!single_LUT) {
+ LUT = dis_tables.get() + (i * nprobe + j) * dim12;
+ }
+ idx_t list_no = cq.ids[i * nprobe + j];
+ if (list_no < 0)
+ continue;
+ size_t ls = orig_invlists->list_size(list_no);
+ if (ls == 0)
+ continue;
+ InvertedLists::ScopedCodes codes(orig_invlists, list_no);
+ InvertedLists::ScopedIds ids(orig_invlists, list_no);
+
+ uint16_t bias = biases.get() ? biases[i * nprobe + j] : 0;
+
+ estimators_from_tables_generic<C>(
+ *this,
+ codes.get(),
+ ls,
+ LUT,
+ ids.get(),
+ bias,
+ k,
+ heap_dis,
+ heap_ids,
+ scaler);
+
+ nlist_visited++;
+ ndis += ls;
+ }
+ heap_reorder<C>(k, heap_dis, heap_ids);
+ // convert distances to float
+ {
+ float one_a = 1 / normalizers[2 * i], b = normalizers[2 * i + 1];
+ if (skip & 16) {
+ one_a = 1;
+ b = 0;
+ }
+ float* heap_dis_float = distances + i * k;
+ for (int j = 0; j < k; j++) {
+ heap_dis_float[j] = b + heap_dis[j] * one_a;
+ }
+ }
+ }
+ indexIVF_stats.nq += n;
+ indexIVF_stats.ndis += ndis;
+ indexIVF_stats.nlist += nlist_visited;
+}
+
+void IndexIVFFastScan::search_implem_10(
+ idx_t n,
+ const float* x,
+ SIMDResultHandlerToFloat& handler,
+ const CoarseQuantized& cq,
+ size_t* ndis_out,
+ size_t* nlist_out,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ size_t dim12 = ksub * M2;
+ AlignedTable<uint8_t> dis_tables;
+ AlignedTable<uint16_t> biases;
+ std::unique_ptr<float[]> normalizers(new float[2 * n]);
+
+ compute_LUT_uint8(n, x, cq, dis_tables, biases, normalizers.get());
+
+ bool single_LUT = !lookup_table_is_3d();
+
+ size_t ndis = 0;
+ int qmap1[1];
+
+ handler.q_map = qmap1;
+ handler.begin(skip & 16 ? nullptr : normalizers.get());
+ size_t nprobe = cq.nprobe;
+
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* LUT = nullptr;
+ qmap1[0] = i;
+
+ if (single_LUT) {
+ LUT = dis_tables.get() + i * dim12;
+ }
+ for (idx_t j = 0; j < nprobe; j++) {
+ size_t ij = i * nprobe + j;
+ if (!single_LUT) {
+ LUT = dis_tables.get() + ij * dim12;
+ }
+ if (biases.get()) {
+ handler.dbias = biases.get() + ij;
+ }
+
+ idx_t list_no = cq.ids[ij];
+ if (list_no < 0) {
+ continue;
+ }
+ size_t ls = invlists->list_size(list_no);
+ if (ls == 0) {
+ continue;
+ }
+
+ InvertedLists::ScopedCodes codes(invlists, list_no);
+ InvertedLists::ScopedIds ids(invlists, list_no);
+
+ handler.ntotal = ls;
+ handler.id_map = ids.get();
+
+ pq4_accumulate_loop(
+ 1,
+ roundup(ls, bbs),
+ bbs,
+ M2,
+ codes.get(),
+ LUT,
+ handler,
+ scaler);
+
+ ndis++;
+ }
+ }
+
+ handler.end();
+ *ndis_out = ndis;
+ *nlist_out = nlist;
+}
+
+void IndexIVFFastScan::search_implem_12(
+ idx_t n,
+ const float* x,
+ SIMDResultHandlerToFloat& handler,
+ const CoarseQuantized& cq,
+ size_t* ndis_out,
+ size_t* nlist_out,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ if (n == 0) { // does not work well with reservoir
+ return;
+ }
+ FAISS_THROW_IF_NOT(bbs == 32);
+
+ size_t dim12 = ksub * M2;
+ AlignedTable<uint8_t> dis_tables;
+ AlignedTable<uint16_t> biases;
+ std::unique_ptr<float[]> normalizers(new float[2 * n]);
+
+ compute_LUT_uint8(n, x, cq, dis_tables, biases, normalizers.get());
+
+ handler.begin(skip & 16 ? nullptr : normalizers.get());
+
+ struct QC {
+ int qno; // sequence number of the query
+ int list_no; // list to visit
+ int rank; // this is the rank'th result of the coarse quantizer
+ };
+ bool single_LUT = !lookup_table_is_3d();
+ size_t nprobe = cq.nprobe;
+
+ std::vector<QC> qcs;
+ {
+ int ij = 0;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < nprobe; j++) {
+ if (cq.ids[ij] >= 0) {
+ qcs.push_back(QC{i, int(cq.ids[ij]), int(j)});
+ }
+ ij++;
+ }
+ }
+ std::sort(qcs.begin(), qcs.end(), [](const QC& a, const QC& b) {
+ return a.list_no < b.list_no;
+ });
+ }
+
+ // prepare the result handlers
+
+ int actual_qbs2 = this->qbs2 ? this->qbs2 : 11;
+
+ std::vector<uint16_t> tmp_bias;
+ if (biases.get()) {
+ tmp_bias.resize(actual_qbs2);
+ handler.dbias = tmp_bias.data();
+ }
+
+ size_t ndis = 0;
+
+ size_t i0 = 0;
+ uint64_t t_copy_pack = 0, t_scan = 0;
+ while (i0 < qcs.size()) {
+ // find all queries that access this inverted list
+ int list_no = qcs[i0].list_no;
+ size_t i1 = i0 + 1;
+
+ while (i1 < qcs.size() && i1 < i0 + actual_qbs2) {
+ if (qcs[i1].list_no != list_no) {
+ break;
+ }
+ i1++;
+ }
+
+ size_t list_size = invlists->list_size(list_no);
+
+ if (list_size == 0) {
+ i0 = i1;
+ continue;
+ }
+
+ // re-organize LUTs and biases into the right order
+ int nc = i1 - i0;
+
+ std::vector<int> q_map(nc), lut_entries(nc);
+ AlignedTable<uint8_t> LUT(nc * dim12);
+ memset(LUT.get(), -1, nc * dim12);
+ int qbs_for_list = pq4_preferred_qbs(nc);
+
+ for (size_t i = i0; i < i1; i++) {
+ const QC& qc = qcs[i];
+ q_map[i - i0] = qc.qno;
+ int ij = qc.qno * nprobe + qc.rank;
+ lut_entries[i - i0] = single_LUT ? qc.qno : ij;
+ if (biases.get()) {
+ tmp_bias[i - i0] = biases[ij];
+ }
+ }
+ pq4_pack_LUT_qbs_q_map(
+ qbs_for_list,
+ M2,
+ dis_tables.get(),
+ lut_entries.data(),
+ LUT.get());
+
+ // access the inverted list
+
+ ndis += (i1 - i0) * list_size;
+
+ InvertedLists::ScopedCodes codes(invlists, list_no);
+ InvertedLists::ScopedIds ids(invlists, list_no);
+
+ // prepare the handler
+
+ handler.ntotal = list_size;
+ handler.q_map = q_map.data();
+ handler.id_map = ids.get();
+
+ pq4_accumulate_loop_qbs(
+ qbs_for_list,
+ list_size,
+ M2,
+ codes.get(),
+ LUT.get(),
+ handler,
+ scaler);
+ // prepare for next loop
+ i0 = i1;
+ }
+
+ handler.end();
+
+ // these stats are not thread-safe
+
+ IVFFastScan_stats.t_copy_pack += t_copy_pack;
+ IVFFastScan_stats.t_scan += t_scan;
+
+ *ndis_out = ndis;
+ *nlist_out = nlist;
+}
+
+void IndexIVFFastScan::search_implem_14(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ int impl,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params) const {
+ if (n == 0) { // does not work well with reservoir
+ return;
+ }
+ FAISS_THROW_IF_NOT(bbs == 32);
+
+ const IDSelector* sel = params ? params->sel : nullptr;
+
+ size_t dim12 = ksub * M2;
+ AlignedTable<uint8_t> dis_tables;
+ AlignedTable<uint16_t> biases;
+ std::unique_ptr<float[]> normalizers(new float[2 * n]);
+
+ compute_LUT_uint8(n, x, cq, dis_tables, biases, normalizers.get());
+
+ struct QC {
+ int qno; // sequence number of the query
+ int list_no; // list to visit
+ int rank; // this is the rank'th result of the coarse quantizer
+ };
+ bool single_LUT = !lookup_table_is_3d();
+ size_t nprobe = cq.nprobe;
+
+ std::vector<QC> qcs;
+ {
+ int ij = 0;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < nprobe; j++) {
+ if (cq.ids[ij] >= 0) {
+ qcs.push_back(QC{i, int(cq.ids[ij]), int(j)});
+ }
+ ij++;
+ }
+ }
+ std::sort(qcs.begin(), qcs.end(), [](const QC& a, const QC& b) {
+ return a.list_no < b.list_no;
+ });
+ }
+
+ struct SE {
+ size_t start; // start in the QC vector
+ size_t end; // end in the QC vector
+ size_t list_size;
+ };
+ std::vector<SE> ses;
+ size_t i0_l = 0;
+ while (i0_l < qcs.size()) {
+ // find all queries that access this inverted list
+ int list_no = qcs[i0_l].list_no;
+ size_t i1 = i0_l + 1;
+
+ while (i1 < qcs.size() && i1 < i0_l + qbs2) {
+ if (qcs[i1].list_no != list_no) {
+ break;
+ }
+ i1++;
+ }
+
+ size_t list_size = invlists->list_size(list_no);
+
+ if (list_size == 0) {
+ i0_l = i1;
+ continue;
+ }
+ ses.push_back(SE{i0_l, i1, list_size});
+ i0_l = i1;
+ }
+
+ // function to handle the global heap
+ bool is_max = !is_similarity_metric(metric_type);
+ using HeapForIP = CMin<float, idx_t>;
+ using HeapForL2 = CMax<float, idx_t>;
+ auto init_result = [&](float* simi, idx_t* idxi) {
+ if (!is_max) {
+ heap_heapify<HeapForIP>(k, simi, idxi);
+ } else {
+ heap_heapify<HeapForL2>(k, simi, idxi);
+ }
+ };
+
+ auto add_local_results = [&](const float* local_dis,
+ const idx_t* local_idx,
+ float* simi,
+ idx_t* idxi) {
+ if (!is_max) {
+ heap_addn<HeapForIP>(k, simi, idxi, local_dis, local_idx, k);
+ } else {
+ heap_addn<HeapForL2>(k, simi, idxi, local_dis, local_idx, k);
+ }
+ };
+
+ auto reorder_result = [&](float* simi, idx_t* idxi) {
+ if (!is_max) {
+ heap_reorder<HeapForIP>(k, simi, idxi);
+ } else {
+ heap_reorder<HeapForL2>(k, simi, idxi);
+ }
+ };
+
+ size_t ndis = 0;
+ size_t nlist_visited = 0;
+
+#pragma omp parallel reduction(+ : ndis, nlist_visited)
+ {
+ // storage for each thread
+ std::vector<idx_t> local_idx(k * n);
+ std::vector<float> local_dis(k * n);
+
+ // prepare the result handlers
+ std::unique_ptr<SIMDResultHandlerToFloat> handler(make_knn_handler(
+ is_max, impl, n, k, local_dis.data(), local_idx.data(), sel));
+ handler->begin(normalizers.get());
+
+ int actual_qbs2 = this->qbs2 ? this->qbs2 : 11;
+
+ std::vector<uint16_t> tmp_bias;
+ if (biases.get()) {
+ tmp_bias.resize(actual_qbs2);
+ handler->dbias = tmp_bias.data();
+ }
+
+ std::set<int> q_set;
+ uint64_t t_copy_pack = 0, t_scan = 0;
+#pragma omp for schedule(dynamic)
+ for (idx_t cluster = 0; cluster < ses.size(); cluster++) {
+ size_t i0 = ses[cluster].start;
+ size_t i1 = ses[cluster].end;
+ size_t list_size = ses[cluster].list_size;
+ nlist_visited++;
+ int list_no = qcs[i0].list_no;
+
+ // re-organize LUTs and biases into the right order
+ int nc = i1 - i0;
+
+ std::vector<int> q_map(nc), lut_entries(nc);
+ AlignedTable<uint8_t> LUT(nc * dim12);
+ memset(LUT.get(), -1, nc * dim12);
+ int qbs_for_list = pq4_preferred_qbs(nc);
+
+ for (size_t i = i0; i < i1; i++) {
+ const QC& qc = qcs[i];
+ q_map[i - i0] = qc.qno;
+ q_set.insert(qc.qno);
+ int ij = qc.qno * nprobe + qc.rank;
+ lut_entries[i - i0] = single_LUT ? qc.qno : ij;
+ if (biases.get()) {
+ tmp_bias[i - i0] = biases[ij];
+ }
+ }
+ pq4_pack_LUT_qbs_q_map(
+ qbs_for_list,
+ M2,
+ dis_tables.get(),
+ lut_entries.data(),
+ LUT.get());
+
+ // access the inverted list
+
+ ndis += (i1 - i0) * list_size;
+
+ InvertedLists::ScopedCodes codes(invlists, list_no);
+ InvertedLists::ScopedIds ids(invlists, list_no);
+
+ // prepare the handler
+
+ handler->ntotal = list_size;
+ handler->q_map = q_map.data();
+ handler->id_map = ids.get();
+
+ pq4_accumulate_loop_qbs(
+ qbs_for_list,
+ list_size,
+ M2,
+ codes.get(),
+ LUT.get(),
+ *handler.get(),
+ scaler);
+ }
+
+ // labels is in-place for HeapHC
+ handler->end();
+
+ // merge per-thread results
+#pragma omp single
+ {
+ // we init the results as a heap
+ for (idx_t i = 0; i < n; i++) {
+ init_result(distances + i * k, labels + i * k);
+ }
+ }
+#pragma omp barrier
+#pragma omp critical
+ {
+ // write to global heap #go over only the queries
+ for (std::set<int>::iterator it = q_set.begin(); it != q_set.end();
+ ++it) {
+ add_local_results(
+ local_dis.data() + *it * k,
+ local_idx.data() + *it * k,
+ distances + *it * k,
+ labels + *it * k);
+ }
+
+ IVFFastScan_stats.t_copy_pack += t_copy_pack;
+ IVFFastScan_stats.t_scan += t_scan;
+ }
+#pragma omp barrier
+#pragma omp single
+ {
+ for (idx_t i = 0; i < n; i++) {
+ reorder_result(distances + i * k, labels + i * k);
+ }
+ }
+ }
+
+ indexIVF_stats.nq += n;
+ indexIVF_stats.ndis += ndis;
+ indexIVF_stats.nlist += nlist_visited;
+}
+
+void IndexIVFFastScan::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ // unpack codes
+ size_t coarse_size = coarse_code_size();
+ std::vector<uint8_t> code(coarse_size + code_size, 0);
+ encode_listno(list_no, code.data());
+ InvertedLists::ScopedCodes list_codes(invlists, list_no);
+ BitstringWriter bsw(code.data() + coarse_size, code_size);
+
+ for (size_t m = 0; m < M; m++) {
+ uint8_t c =
+ pq4_get_packed_element(list_codes.get(), bbs, M2, offset, m);
+ bsw.write(c, nbits);
+ }
+
+ sa_decode(1, code.data(), recons);
+}
+
+void IndexIVFFastScan::reconstruct_orig_invlists() {
+ FAISS_THROW_IF_NOT(orig_invlists != nullptr);
+ FAISS_THROW_IF_NOT(orig_invlists->list_size(0) == 0);
+
+#pragma omp parallel for if (nlist > 100)
+ for (idx_t list_no = 0; list_no < nlist; list_no++) {
+ InvertedLists::ScopedCodes codes(invlists, list_no);
+ InvertedLists::ScopedIds ids(invlists, list_no);
+ size_t list_size = invlists->list_size(list_no);
+ std::vector<uint8_t> code(code_size, 0);
+
+ for (size_t offset = 0; offset < list_size; offset++) {
+ // unpack codes
+ BitstringWriter bsw(code.data(), code_size);
+ for (size_t m = 0; m < M; m++) {
+ uint8_t c =
+ pq4_get_packed_element(codes.get(), bbs, M2, offset, m);
+ bsw.write(c, nbits);
+ }
+
+ // get id
+ idx_t id = ids.get()[offset];
+
+ orig_invlists->add_entry(list_no, id, code.data());
+ }
+ }
+}
+
+void IndexIVFFastScan::sa_decode(idx_t n, const uint8_t* codes, float* x)
+ const {
+ size_t coarse_size = coarse_code_size();
+
+#pragma omp parallel if (n > 1)
+ {
+ std::vector<float> residual(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + i * (code_size + coarse_size);
+ int64_t list_no = decode_listno(code);
+ float* xi = x + i * d;
+ fine_quantizer->decode(code + coarse_size, xi, 1);
+ if (by_residual) {
+ quantizer->reconstruct(list_no, residual.data());
+ for (size_t j = 0; j < d; j++) {
+ xi[j] += residual[j];
+ }
+ }
+ }
+ }
+}
+
+IVFFastScanStats IVFFastScan_stats;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFastScan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFastScan.h
new file mode 100644
index 0000000..48d6daf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFastScan.h
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <memory>
+
+#include <faiss/IndexIVF.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+struct NormTableScaler;
+struct SIMDResultHandlerToFloat;
+struct Quantizer;
+
+/** Fast scan version of IVFPQ and IVFAQ. Works for 4-bit PQ/AQ for now.
+ *
+ * The codes in the inverted lists are not stored sequentially but
+ * grouped in blocks of size bbs. This makes it possible to very quickly
+ * compute distances with SIMD instructions.
+ *
+ * Implementations (implem):
+ * 0: auto-select implementation (default)
+ * 1: orig's search, re-implemented
+ * 2: orig's search, re-ordered by invlist
+ * 10: optimizer int16 search, collect results in heap, no qbs
+ * 11: idem, collect results in reservoir
+ * 12: optimizer int16 search, collect results in heap, uses qbs
+ * 13: idem, collect results in reservoir
+ * 14: internally multithreaded implem over nq * nprobe
+ * 15: same with reservoir
+ *
+ * For range search, only 10 and 12 are supported.
+ * add 100 to the implem to force single-thread scanning (the coarse quantizer
+ * may still use multiple threads).
+ */
+
+struct IndexIVFFastScan : IndexIVF {
+ // size of the kernel
+ int bbs; // set at build time
+
+ size_t M;
+ size_t nbits;
+ size_t ksub;
+
+ // M rounded up to a multiple of 2
+ size_t M2;
+
+ // search-time implementation
+ int implem = 0;
+ // skip some parts of the computation (for timing)
+ int skip = 0;
+
+ // batching factors at search time (0 = default)
+ int qbs = 0;
+ size_t qbs2 = 0;
+
+ // quantizer used to pack the codes
+ Quantizer* fine_quantizer = nullptr;
+
+ IndexIVFFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t code_size,
+ MetricType metric = METRIC_L2);
+
+ IndexIVFFastScan();
+
+ /// called by implementations
+ void init_fastscan(
+ Quantizer* fine_quantizer,
+ size_t M,
+ size_t nbits,
+ size_t nlist,
+ MetricType metric,
+ int bbs);
+
+ // initialize the CodePacker in the InvertedLists
+ void init_code_packer();
+
+ ~IndexIVFFastScan() override;
+
+ /// orig's inverted lists (for debugging)
+ InvertedLists* orig_invlists = nullptr;
+
+ void add_with_ids(idx_t n, const float* x, const idx_t* xids) override;
+
+ // prepare look-up tables
+
+ virtual bool lookup_table_is_3d() const = 0;
+
+ // compact way of conveying coarse quantization results
+ struct CoarseQuantized {
+ size_t nprobe;
+ const float* dis = nullptr;
+ const idx_t* ids = nullptr;
+ };
+
+ virtual void compute_LUT(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<float>& dis_tables,
+ AlignedTable<float>& biases) const = 0;
+
+ void compute_LUT_uint8(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<uint8_t>& dis_tables,
+ AlignedTable<uint16_t>& biases,
+ float* normalizers) const;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ // internal search funcs
+
+ // dispatch to implementations and parallelize
+ void search_dispatch_implem(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ void range_search_dispatch_implem(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult& rres,
+ const CoarseQuantized& cq_in,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ // impl 1 and 2 are just for verification
+ template <class C>
+ void search_implem_1(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ template <class C>
+ void search_implem_2(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ // implem 10 and 12 are not multithreaded internally, so
+ // export search stats
+ void search_implem_10(
+ idx_t n,
+ const float* x,
+ SIMDResultHandlerToFloat& handler,
+ const CoarseQuantized& cq,
+ size_t* ndis_out,
+ size_t* nlist_out,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ void search_implem_12(
+ idx_t n,
+ const float* x,
+ SIMDResultHandlerToFloat& handler,
+ const CoarseQuantized& cq,
+ size_t* ndis_out,
+ size_t* nlist_out,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ // implem 14 is multithreaded internally across nprobes and queries
+ void search_implem_14(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const CoarseQuantized& cq,
+ int impl,
+ const NormTableScaler* scaler,
+ const IVFSearchParameters* params = nullptr) const;
+
+ // reconstruct vectors from packed invlists
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ CodePacker* get_CodePacker() const override;
+
+ // reconstruct orig invlists (for debugging)
+ void reconstruct_orig_invlists();
+
+ /** Decode a set of vectors.
+ *
+ * NOTE: The codes in the IndexFastScan object are non-contiguous.
+ * But this method requires a contiguous representation.
+ *
+ * @param n number of vectors
+ * @param bytes input encoded vectors, size n * code_size
+ * @param x output vectors, size n * d
+ */
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+struct IVFFastScanStats {
+ uint64_t times[10];
+ uint64_t t_compute_distance_tables, t_round;
+ uint64_t t_copy_pack, t_scan, t_to_flat;
+ uint64_t reservoir_times[4];
+ double t_aq_encode;
+ double t_aq_norm_encode;
+
+ double Mcy_at(int i) {
+ return times[i] / (1000 * 1000.0);
+ }
+
+ double Mcy_reservoir_at(int i) {
+ return reservoir_times[i] / (1000 * 1000.0);
+ }
+ IVFFastScanStats() {
+ reset();
+ }
+ void reset() {
+ memset(this, 0, sizeof(*this));
+ }
+};
+
+FAISS_API extern IVFFastScanStats IVFFastScan_stats;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFlat.cpp
new file mode 100644
index 0000000..111002c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFlat.cpp
@@ -0,0 +1,494 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexIVFFlat.h>
+
+#include <omp.h>
+
+#include <cinttypes>
+#include <cstdio>
+
+#include <faiss/IndexFlat.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/IDSelector.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/*****************************************
+ * IndexIVFFlat implementation
+ ******************************************/
+
+IndexIVFFlat::IndexIVFFlat(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ MetricType metric)
+ : IndexIVF(quantizer, d, nlist, sizeof(float) * d, metric) {
+ code_size = sizeof(float) * d;
+ by_residual = false;
+}
+
+IndexIVFFlat::IndexIVFFlat() {
+ by_residual = false;
+}
+
+void IndexIVFFlat::add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* coarse_idx,
+ void* inverted_list_context) {
+ FAISS_THROW_IF_NOT(is_trained);
+ FAISS_THROW_IF_NOT(coarse_idx);
+ FAISS_THROW_IF_NOT(!by_residual);
+ assert(invlists);
+ direct_map.check_can_add(xids);
+
+ int64_t n_add = 0;
+
+ DirectMapAdd dm_adder(direct_map, n, xids);
+
+#pragma omp parallel reduction(+ : n_add)
+ {
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ // each thread takes care of a subset of lists
+ for (size_t i = 0; i < n; i++) {
+ idx_t list_no = coarse_idx[i];
+
+ if (list_no >= 0 && list_no % nt == rank) {
+ idx_t id = xids ? xids[i] : ntotal + i;
+ const float* xi = x + i * d;
+ size_t offset = invlists->add_entry(
+ list_no, id, (const uint8_t*)xi, inverted_list_context);
+ dm_adder.add(i, list_no, offset);
+ n_add++;
+ } else if (rank == 0 && list_no == -1) {
+ dm_adder.add(i, -1, 0);
+ }
+ }
+ }
+
+ if (verbose) {
+ printf("IndexIVFFlat::add_core: added %" PRId64 " / %" PRId64
+ " vectors\n",
+ n_add,
+ n);
+ }
+ ntotal += n;
+}
+
+void IndexIVFFlat::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ FAISS_THROW_IF_NOT(!by_residual);
+ if (!include_listnos) {
+ memcpy(codes, x, code_size * n);
+ } else {
+ size_t coarse_size = coarse_code_size();
+ for (size_t i = 0; i < n; i++) {
+ int64_t list_no = list_nos[i];
+ uint8_t* code = codes + i * (code_size + coarse_size);
+ const float* xi = x + i * d;
+ if (list_no >= 0) {
+ encode_listno(list_no, code);
+ memcpy(code + coarse_size, xi, code_size);
+ } else {
+ memset(code, 0, code_size + coarse_size);
+ }
+ }
+ }
+}
+
+void IndexIVFFlat::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ size_t coarse_size = coarse_code_size();
+ for (size_t i = 0; i < n; i++) {
+ const uint8_t* code = bytes + i * (code_size + coarse_size);
+ float* xi = x + i * d;
+ memcpy(xi, code + coarse_size, code_size);
+ }
+}
+
+namespace {
+
+template <MetricType metric, class C, bool use_sel>
+struct IVFFlatScanner : InvertedListScanner {
+ size_t d;
+
+ IVFFlatScanner(size_t d, bool store_pairs, const IDSelector* sel)
+ : InvertedListScanner(store_pairs, sel), d(d) {
+ keep_max = is_similarity_metric(metric);
+ }
+
+ const float* xi;
+ void set_query(const float* query) override {
+ this->xi = query;
+ }
+
+ void set_list(idx_t list_no, float /* coarse_dis */) override {
+ this->list_no = list_no;
+ }
+
+ float distance_to_code(const uint8_t* code) const override {
+ const float* yj = (float*)code;
+ float dis = metric == METRIC_INNER_PRODUCT
+ ? fvec_inner_product(xi, yj, d)
+ : fvec_L2sqr(xi, yj, d);
+ return dis;
+ }
+
+ size_t scan_codes(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* simi,
+ idx_t* idxi,
+ size_t k) const override {
+ const float* list_vecs = (const float*)codes;
+ size_t nup = 0;
+ for (size_t j = 0; j < list_size; j++) {
+ const float* yj = list_vecs + d * j;
+ if (use_sel && !sel->is_member(ids[j])) {
+ continue;
+ }
+ float dis = metric == METRIC_INNER_PRODUCT
+ ? fvec_inner_product(xi, yj, d)
+ : fvec_L2sqr(xi, yj, d);
+ if (C::cmp(simi[0], dis)) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ heap_replace_top<C>(k, simi, idxi, dis, id);
+ nup++;
+ }
+ }
+ return nup;
+ }
+
+ void scan_codes_range(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& res) const override {
+ const float* list_vecs = (const float*)codes;
+ for (size_t j = 0; j < list_size; j++) {
+ const float* yj = list_vecs + d * j;
+ if (use_sel && !sel->is_member(ids[j])) {
+ continue;
+ }
+ float dis = metric == METRIC_INNER_PRODUCT
+ ? fvec_inner_product(xi, yj, d)
+ : fvec_L2sqr(xi, yj, d);
+ if (C::cmp(radius, dis)) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ res.add(dis, id);
+ }
+ }
+ }
+};
+
+template <bool use_sel>
+InvertedListScanner* get_InvertedListScanner1(
+ const IndexIVFFlat* ivf,
+ bool store_pairs,
+ const IDSelector* sel) {
+ if (ivf->metric_type == METRIC_INNER_PRODUCT) {
+ return new IVFFlatScanner<
+ METRIC_INNER_PRODUCT,
+ CMin<float, int64_t>,
+ use_sel>(ivf->d, store_pairs, sel);
+ } else if (ivf->metric_type == METRIC_L2) {
+ return new IVFFlatScanner<METRIC_L2, CMax<float, int64_t>, use_sel>(
+ ivf->d, store_pairs, sel);
+ } else {
+ FAISS_THROW_MSG("metric type not supported");
+ }
+}
+
+} // anonymous namespace
+
+InvertedListScanner* IndexIVFFlat::get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters*) const {
+ if (sel) {
+ return get_InvertedListScanner1<true>(this, store_pairs, sel);
+ } else {
+ return get_InvertedListScanner1<false>(this, store_pairs, sel);
+ }
+}
+
+void IndexIVFFlat::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ memcpy(recons, invlists->get_single_code(list_no, offset), code_size);
+}
+
+/*****************************************
+ * IndexIVFFlatDedup implementation
+ ******************************************/
+
+IndexIVFFlatDedup::IndexIVFFlatDedup(
+ Index* quantizer,
+ size_t d,
+ size_t nlist_,
+ MetricType metric_type)
+ : IndexIVFFlat(quantizer, d, nlist_, metric_type) {}
+
+void IndexIVFFlatDedup::train(idx_t n, const float* x) {
+ std::unordered_map<uint64_t, idx_t> map;
+ std::unique_ptr<float[]> x2(new float[n * d]);
+
+ int64_t n2 = 0;
+ for (int64_t i = 0; i < n; i++) {
+ uint64_t hash = hash_bytes((uint8_t*)(x + i * d), code_size);
+ if (map.count(hash) &&
+ !memcmp(x2.get() + map[hash] * d, x + i * d, code_size)) {
+ // is duplicate, skip
+ } else {
+ map[hash] = n2;
+ memcpy(x2.get() + n2 * d, x + i * d, code_size);
+ n2++;
+ }
+ }
+ if (verbose) {
+ printf("IndexIVFFlatDedup::train: train on %" PRId64
+ " points after dedup "
+ "(was %" PRId64 " points)\n",
+ n2,
+ n);
+ }
+ IndexIVFFlat::train(n2, x2.get());
+}
+
+void IndexIVFFlatDedup::add_with_ids(
+ idx_t na,
+ const float* x,
+ const idx_t* xids) {
+ FAISS_THROW_IF_NOT(is_trained);
+ assert(invlists);
+ FAISS_THROW_IF_NOT_MSG(
+ direct_map.no(), "IVFFlatDedup not implemented with direct_map");
+ std::unique_ptr<int64_t[]> idx(new int64_t[na]);
+ quantizer->assign(na, x, idx.get());
+
+ int64_t n_add = 0, n_dup = 0;
+
+#pragma omp parallel reduction(+ : n_add, n_dup)
+ {
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ // each thread takes care of a subset of lists
+ for (size_t i = 0; i < na; i++) {
+ int64_t list_no = idx[i];
+
+ if (list_no < 0 || list_no % nt != rank) {
+ continue;
+ }
+
+ idx_t id = xids ? xids[i] : ntotal + i;
+ const float* xi = x + i * d;
+
+ // search if there is already an entry with that id
+ InvertedLists::ScopedCodes codes(invlists, list_no);
+
+ int64_t n = invlists->list_size(list_no);
+ int64_t offset = -1;
+ for (int64_t o = 0; o < n; o++) {
+ if (!memcmp(codes.get() + o * code_size, xi, code_size)) {
+ offset = o;
+ break;
+ }
+ }
+
+ if (offset == -1) { // not found
+ invlists->add_entry(list_no, id, (const uint8_t*)xi);
+ } else {
+ // mark equivalence
+ idx_t id2 = invlists->get_single_id(list_no, offset);
+ std::pair<idx_t, idx_t> pair(id2, id);
+
+#pragma omp critical
+ // executed by one thread at a time
+ instances.insert(pair);
+
+ n_dup++;
+ }
+ n_add++;
+ }
+ }
+ if (verbose) {
+ printf("IndexIVFFlat::add_with_ids: added %" PRId64 " / %" PRId64
+ " vectors"
+ " (out of which %" PRId64 " are duplicates)\n",
+ n_add,
+ na,
+ n_dup);
+ }
+ ntotal += n_add;
+}
+
+void IndexIVFFlatDedup::search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* stats) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !store_pairs, "store_pairs not supported in IVFDedup");
+
+ IndexIVFFlat::search_preassigned(
+ n, x, k, assign, centroid_dis, distances, labels, false, params);
+
+ std::vector<idx_t> labels2(k);
+ std::vector<float> dis2(k);
+
+ for (int64_t i = 0; i < n; i++) {
+ idx_t* labels1 = labels + i * k;
+ float* dis1 = distances + i * k;
+ int64_t j = 0;
+ for (; j < k; j++) {
+ if (instances.find(labels1[j]) != instances.end()) {
+ // a duplicate: special handling
+ break;
+ }
+ }
+ if (j < k) {
+ // there are duplicates, special handling
+ int64_t j0 = j;
+ int64_t rp = j;
+ while (j < k) {
+ auto range = instances.equal_range(labels1[rp]);
+ float dis = dis1[rp];
+ labels2[j] = labels1[rp];
+ dis2[j] = dis;
+ j++;
+ for (auto it = range.first; j < k && it != range.second; ++it) {
+ labels2[j] = it->second;
+ dis2[j] = dis;
+ j++;
+ }
+ rp++;
+ }
+ memcpy(labels1 + j0,
+ labels2.data() + j0,
+ sizeof(labels1[0]) * (k - j0));
+ memcpy(dis1 + j0, dis2.data() + j0, sizeof(dis2[0]) * (k - j0));
+ }
+ }
+}
+
+size_t IndexIVFFlatDedup::remove_ids(const IDSelector& sel) {
+ std::unordered_map<idx_t, idx_t> replace;
+ std::vector<std::pair<idx_t, idx_t>> toadd;
+ for (auto it = instances.begin(); it != instances.end();) {
+ if (sel.is_member(it->first)) {
+ // then we erase this entry
+ if (!sel.is_member(it->second)) {
+ // if the second is not erased
+ if (replace.count(it->first) == 0) {
+ replace[it->first] = it->second;
+ } else { // remember we should add an element
+ std::pair<idx_t, idx_t> new_entry(
+ replace[it->first], it->second);
+ toadd.push_back(new_entry);
+ }
+ }
+ it = instances.erase(it);
+ } else {
+ if (sel.is_member(it->second)) {
+ it = instances.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ }
+
+ instances.insert(toadd.begin(), toadd.end());
+
+ // mostly copied from IndexIVF.cpp
+
+ FAISS_THROW_IF_NOT_MSG(
+ direct_map.no(), "direct map remove not implemented");
+
+ std::vector<int64_t> toremove(nlist);
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < nlist; i++) {
+ int64_t l0 = invlists->list_size(i), l = l0, j = 0;
+ InvertedLists::ScopedIds idsi(invlists, i);
+ while (j < l) {
+ if (sel.is_member(idsi[j])) {
+ if (replace.count(idsi[j]) == 0) {
+ l--;
+ invlists->update_entry(
+ i,
+ j,
+ invlists->get_single_id(i, l),
+ InvertedLists::ScopedCodes(invlists, i, l).get());
+ } else {
+ invlists->update_entry(
+ i,
+ j,
+ replace[idsi[j]],
+ InvertedLists::ScopedCodes(invlists, i, j).get());
+ j++;
+ }
+ } else {
+ j++;
+ }
+ }
+ toremove[i] = l0 - l;
+ }
+ // this will not run well in parallel on ondisk because of possible shrinks
+ int64_t nremove = 0;
+ for (int64_t i = 0; i < nlist; i++) {
+ if (toremove[i] > 0) {
+ nremove += toremove[i];
+ invlists->resize(i, invlists->list_size(i) - toremove[i]);
+ }
+ }
+ ntotal -= nremove;
+ return nremove;
+}
+
+void IndexIVFFlatDedup::range_search(
+ idx_t,
+ const float*,
+ float,
+ RangeSearchResult*,
+ const SearchParameters*) const {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void IndexIVFFlatDedup::update_vectors(int, const idx_t*, const float*) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void IndexIVFFlatDedup::reconstruct_from_offset(int64_t, int64_t, float*)
+ const {
+ FAISS_THROW_MSG("not implemented");
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFlat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFlat.h
new file mode 100644
index 0000000..c298b7b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFFlat.h
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_IVF_FLAT_H
+#define FAISS_INDEX_IVF_FLAT_H
+
+#include <stdint.h>
+#include <unordered_map>
+
+#include <faiss/IndexIVF.h>
+
+namespace faiss {
+
+/** Inverted file with stored vectors. Here the inverted file
+ * pre-selects the vectors to be searched, but they are not otherwise
+ * encoded, the code array just contains the raw float entries.
+ */
+struct IndexIVFFlat : IndexIVF {
+ IndexIVFFlat(
+ Index* quantizer,
+ size_t d,
+ size_t nlist_,
+ MetricType = METRIC_L2);
+
+ void add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context = nullptr) override;
+
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos = false) const override;
+
+ InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* params) const override;
+
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ IndexIVFFlat();
+};
+
+struct IndexIVFFlatDedup : IndexIVFFlat {
+ /** Maps ids stored in the index to the ids of vectors that are
+ * the same. When a vector is unique, it does not appear in the
+ * instances map */
+ std::unordered_multimap<idx_t, idx_t> instances;
+
+ IndexIVFFlatDedup(
+ Index* quantizer,
+ size_t d,
+ size_t nlist_,
+ MetricType = METRIC_L2);
+
+ /// also dedups the training set
+ void train(idx_t n, const float* x) override;
+
+ /// implemented for all IndexIVF* classes
+ void add_with_ids(idx_t n, const float* x, const idx_t* xids) override;
+
+ void search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ size_t remove_ids(const IDSelector& sel) override;
+
+ /// not implemented
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ /// not implemented
+ void update_vectors(int nv, const idx_t* idx, const float* v) override;
+
+ /// not implemented
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ IndexIVFFlatDedup() {}
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFIndependentQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFIndependentQuantizer.cpp
new file mode 100644
index 0000000..ae94982
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFIndependentQuantizer.cpp
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFIndependentQuantizer.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+IndexIVFIndependentQuantizer::IndexIVFIndependentQuantizer(
+ Index* quantizer,
+ IndexIVF* index_ivf,
+ VectorTransform* vt)
+ : Index(quantizer->d, index_ivf->metric_type),
+ quantizer(quantizer),
+ vt(vt),
+ index_ivf(index_ivf) {
+ if (vt) {
+ FAISS_THROW_IF_NOT_MSG(
+ vt->d_in == d && vt->d_out == index_ivf->d,
+ "invalid vector dimensions");
+ } else {
+ FAISS_THROW_IF_NOT_MSG(index_ivf->d == d, "invalid vector dimensions");
+ }
+
+ if (quantizer->is_trained && quantizer->ntotal != 0) {
+ FAISS_THROW_IF_NOT(quantizer->ntotal == index_ivf->nlist);
+ }
+ if (index_ivf->is_trained && vt) {
+ FAISS_THROW_IF_NOT(vt->is_trained);
+ }
+ ntotal = index_ivf->ntotal;
+ is_trained =
+ (quantizer->is_trained && quantizer->ntotal == index_ivf->nlist &&
+ (!vt || vt->is_trained) && index_ivf->is_trained);
+
+ // disable precomputed tables because they use the distances that are
+ // provided by the coarse quantizer (that are out of sync with the IVFPQ)
+ if (auto index_ivfpq = dynamic_cast<IndexIVFPQ*>(index_ivf)) {
+ index_ivfpq->use_precomputed_table = -1;
+ }
+}
+
+IndexIVFIndependentQuantizer::~IndexIVFIndependentQuantizer() {
+ if (own_fields) {
+ delete quantizer;
+ delete index_ivf;
+ delete vt;
+ }
+}
+
+namespace {
+
+struct VTransformedVectors : TransformedVectors {
+ VTransformedVectors(const VectorTransform* vt, idx_t n, const float* x)
+ : TransformedVectors(x, vt ? vt->apply(n, x) : x) {}
+};
+
+struct SubsampledVectors : TransformedVectors {
+ SubsampledVectors(int d, idx_t* n, idx_t max_n, const float* x)
+ : TransformedVectors(
+ x,
+ fvecs_maybe_subsample(d, (size_t*)n, max_n, x, true)) {}
+};
+
+} // anonymous namespace
+
+void IndexIVFIndependentQuantizer::add(idx_t n, const float* x) {
+ std::vector<float> D(n);
+ std::vector<idx_t> I(n);
+ quantizer->search(n, x, 1, D.data(), I.data());
+
+ VTransformedVectors tv(vt, n, x);
+
+ index_ivf->add_core(n, tv.x, nullptr, I.data());
+}
+
+void IndexIVFIndependentQuantizer::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(!params, "search parameters not supported");
+ int nprobe = index_ivf->nprobe;
+ std::vector<float> D(n * nprobe);
+ std::vector<idx_t> I(n * nprobe);
+ quantizer->search(n, x, nprobe, D.data(), I.data());
+
+ VTransformedVectors tv(vt, n, x);
+
+ index_ivf->search_preassigned(
+ n, tv.x, k, I.data(), D.data(), distances, labels, false);
+}
+
+void IndexIVFIndependentQuantizer::reset() {
+ index_ivf->reset();
+ ntotal = 0;
+}
+
+void IndexIVFIndependentQuantizer::train(idx_t n, const float* x) {
+ // quantizer training
+ size_t nlist = index_ivf->nlist;
+ Level1Quantizer l1(quantizer, nlist);
+ l1.train_q1(n, x, verbose, metric_type);
+
+ // train the VectorTransform
+ if (vt && !vt->is_trained) {
+ if (verbose) {
+ printf("IndexIVFIndependentQuantizer: train the VectorTransform\n");
+ }
+ vt->train(n, x);
+ }
+
+ // get the centroids from the quantizer, transform them and
+ // add them to the index_ivf's quantizer
+ if (verbose) {
+ printf("IndexIVFIndependentQuantizer: extract the main quantizer centroids\n");
+ }
+ std::vector<float> centroids(nlist * d);
+ quantizer->reconstruct_n(0, nlist, centroids.data());
+ VTransformedVectors tcent(vt, nlist, centroids.data());
+
+ if (verbose) {
+ printf("IndexIVFIndependentQuantizer: add centroids to the secondary quantizer\n");
+ }
+ if (!index_ivf->quantizer->is_trained) {
+ index_ivf->quantizer->train(nlist, tcent.x);
+ }
+ index_ivf->quantizer->add(nlist, tcent.x);
+
+ // train the payload
+
+ // optional subsampling
+ idx_t max_nt = index_ivf->train_encoder_num_vectors();
+ if (max_nt <= 0) {
+ max_nt = (size_t)1 << 35;
+ }
+ SubsampledVectors sv(index_ivf->d, &n, max_nt, x);
+
+ // transform subsampled vectors
+ VTransformedVectors tv(vt, n, sv.x);
+
+ if (verbose) {
+ printf("IndexIVFIndependentQuantizer: train encoder\n");
+ }
+
+ if (index_ivf->by_residual) {
+ // assign with quantizer
+ std::vector<idx_t> assign(n);
+ quantizer->assign(n, sv.x, assign.data());
+
+ // compute residual with IVF quantizer
+ std::vector<float> residuals(n * index_ivf->d);
+ index_ivf->quantizer->compute_residual_n(
+ n, tv.x, residuals.data(), assign.data());
+
+ index_ivf->train_encoder(n, residuals.data(), assign.data());
+ } else {
+ index_ivf->train_encoder(n, tv.x, nullptr);
+ }
+ index_ivf->is_trained = true;
+ is_trained = true;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFIndependentQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFIndependentQuantizer.h
new file mode 100644
index 0000000..ff3c63b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFIndependentQuantizer.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexIVF.h>
+#include <faiss/VectorTransform.h>
+
+namespace faiss {
+
+/** An IVF index with a quantizer that has a different input dimension from the
+ * payload size. The vectors to encode are obtained from the input vectors by a
+ * VectorTransform.
+ */
+struct IndexIVFIndependentQuantizer : Index {
+ /// quantizer is fed directly with the input vectors
+ Index* quantizer = nullptr;
+
+ /// transform before the IVF vectors are applied
+ VectorTransform* vt = nullptr;
+
+ /// the IVF index, controls nlist and nprobe
+ IndexIVF* index_ivf = nullptr;
+
+ /// whether *this owns the 3 fields
+ bool own_fields = false;
+
+ IndexIVFIndependentQuantizer(
+ Index* quantizer,
+ IndexIVF* index_ivf,
+ VectorTransform* vt = nullptr);
+
+ IndexIVFIndependentQuantizer() {}
+
+ void train(idx_t n, const float* x) override;
+
+ void add(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reset() override;
+
+ ~IndexIVFIndependentQuantizer() override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQ.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQ.cpp
new file mode 100644
index 0000000..ce1f5dd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQ.cpp
@@ -0,0 +1,1391 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexIVFPQ.h>
+
+#include <cassert>
+#include <cinttypes>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+
+#include <algorithm>
+
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/Clustering.h>
+
+#include <faiss/utils/hamming.h>
+
+#include <faiss/impl/FaissAssert.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/IDSelector.h>
+
+#include <faiss/impl/ProductQuantizer.h>
+
+#include <faiss/impl/code_distance/code_distance.h>
+
+namespace faiss {
+
+/*****************************************
+ * IndexIVFPQ implementation
+ ******************************************/
+
+IndexIVFPQ::IndexIVFPQ(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits_per_idx,
+ MetricType metric)
+ : IndexIVF(quantizer, d, nlist, 0, metric), pq(d, M, nbits_per_idx) {
+ code_size = pq.code_size;
+ invlists->code_size = code_size;
+ is_trained = false;
+ by_residual = true;
+ use_precomputed_table = 0;
+ scan_table_threshold = 0;
+
+ polysemous_training = nullptr;
+ do_polysemous_training = false;
+ polysemous_ht = 0;
+}
+
+/****************************************************************
+ * training */
+
+void IndexIVFPQ::train_encoder(idx_t n, const float* x, const idx_t* assign) {
+ pq.train(n, x);
+
+ if (do_polysemous_training) {
+ if (verbose)
+ printf("doing polysemous training for PQ\n");
+ PolysemousTraining default_pt;
+ PolysemousTraining* pt =
+ polysemous_training ? polysemous_training : &default_pt;
+ pt->optimize_pq_for_hamming(pq, n, x);
+ }
+
+ if (by_residual) {
+ precompute_table();
+ }
+}
+
+idx_t IndexIVFPQ::train_encoder_num_vectors() const {
+ return pq.cp.max_points_per_centroid * pq.ksub;
+}
+
+/****************************************************************
+ * IVFPQ as codec */
+
+/* produce a binary signature based on the residual vector */
+void IndexIVFPQ::encode(idx_t key, const float* x, uint8_t* code) const {
+ if (by_residual) {
+ std::vector<float> residual_vec(d);
+ quantizer->compute_residual(x, residual_vec.data(), key);
+ pq.compute_code(residual_vec.data(), code);
+ } else
+ pq.compute_code(x, code);
+}
+
+void IndexIVFPQ::encode_multiple(
+ size_t n,
+ idx_t* keys,
+ const float* x,
+ uint8_t* xcodes,
+ bool compute_keys) const {
+ if (compute_keys)
+ quantizer->assign(n, x, keys);
+
+ encode_vectors(n, x, keys, xcodes);
+}
+
+void IndexIVFPQ::decode_multiple(
+ size_t n,
+ const idx_t* keys,
+ const uint8_t* xcodes,
+ float* x) const {
+ pq.decode(xcodes, x, n);
+ if (by_residual) {
+ std::vector<float> centroid(d);
+ for (size_t i = 0; i < n; i++) {
+ quantizer->reconstruct(keys[i], centroid.data());
+ float* xi = x + i * d;
+ for (size_t j = 0; j < d; j++) {
+ xi[j] += centroid[j];
+ }
+ }
+ }
+}
+
+/****************************************************************
+ * add */
+
+void IndexIVFPQ::add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* coarse_idx,
+ void* inverted_list_context) {
+ add_core_o(n, x, xids, nullptr, coarse_idx, inverted_list_context);
+}
+
+static std::unique_ptr<float[]> compute_residuals(
+ const Index* quantizer,
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos) {
+ size_t d = quantizer->d;
+ std::unique_ptr<float[]> residuals(new float[n * d]);
+ // TODO: parallelize?
+ for (size_t i = 0; i < n; i++) {
+ if (list_nos[i] < 0)
+ memset(residuals.get() + i * d, 0, sizeof(float) * d);
+ else
+ quantizer->compute_residual(
+ x + i * d, residuals.get() + i * d, list_nos[i]);
+ }
+ return residuals;
+}
+
+void IndexIVFPQ::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ if (by_residual) {
+ std::unique_ptr<float[]> to_encode =
+ compute_residuals(quantizer, n, x, list_nos);
+ pq.compute_codes(to_encode.get(), codes, n);
+ } else {
+ pq.compute_codes(x, codes, n);
+ }
+
+ if (include_listnos) {
+ size_t coarse_size = coarse_code_size();
+ for (idx_t i = n - 1; i >= 0; i--) {
+ uint8_t* code = codes + i * (coarse_size + code_size);
+ memmove(code + coarse_size, codes + i * code_size, code_size);
+ encode_listno(list_nos[i], code);
+ }
+ }
+}
+
+void IndexIVFPQ::sa_decode(idx_t n, const uint8_t* codes, float* x) const {
+ size_t coarse_size = coarse_code_size();
+
+#pragma omp parallel
+ {
+ std::vector<float> residual(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + i * (code_size + coarse_size);
+ int64_t list_no = decode_listno(code);
+ float* xi = x + i * d;
+ pq.decode(code + coarse_size, xi);
+ if (by_residual) {
+ quantizer->reconstruct(list_no, residual.data());
+ for (size_t j = 0; j < d; j++) {
+ xi[j] += residual[j];
+ }
+ }
+ }
+ }
+}
+
+// block size used in IndexIVFPQ::add_core_o
+int index_ivfpq_add_core_o_bs = 32768;
+
+void IndexIVFPQ::add_core_o(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ float* residuals_2,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context) {
+ idx_t bs = index_ivfpq_add_core_o_bs;
+ if (n > bs) {
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(i0 + bs, n);
+ if (verbose) {
+ printf("IndexIVFPQ::add_core_o: adding %" PRId64 ":%" PRId64
+ " / %" PRId64 "\n",
+ i0,
+ i1,
+ n);
+ }
+ add_core_o(
+ i1 - i0,
+ x + i0 * d,
+ xids ? xids + i0 : nullptr,
+ residuals_2 ? residuals_2 + i0 * d : nullptr,
+ precomputed_idx ? precomputed_idx + i0 : nullptr,
+ inverted_list_context);
+ }
+ return;
+ }
+
+ InterruptCallback::check();
+
+ direct_map.check_can_add(xids);
+
+ FAISS_THROW_IF_NOT(is_trained);
+ double t0 = getmillisecs();
+ const idx_t* idx;
+ std::unique_ptr<idx_t[]> del_idx;
+
+ if (precomputed_idx) {
+ idx = precomputed_idx;
+ } else {
+ idx_t* idx0 = new idx_t[n];
+ del_idx.reset(idx0);
+ quantizer->assign(n, x, idx0);
+ idx = idx0;
+ }
+
+ double t1 = getmillisecs();
+ std::unique_ptr<uint8_t[]> xcodes(new uint8_t[n * code_size]);
+
+ const float* to_encode = nullptr;
+ std::unique_ptr<const float[]> del_to_encode;
+
+ if (by_residual) {
+ del_to_encode = compute_residuals(quantizer, n, x, idx);
+ to_encode = del_to_encode.get();
+ } else {
+ to_encode = x;
+ }
+ pq.compute_codes(to_encode, xcodes.get(), n);
+
+ double t2 = getmillisecs();
+ // TODO: parallelize?
+ size_t n_ignore = 0;
+ for (size_t i = 0; i < n; i++) {
+ idx_t key = idx[i];
+ idx_t id = xids ? xids[i] : ntotal + i;
+ if (key < 0) {
+ direct_map.add_single_id(id, -1, 0);
+ n_ignore++;
+ if (residuals_2)
+ memset(residuals_2, 0, sizeof(*residuals_2) * d);
+ continue;
+ }
+
+ uint8_t* code = xcodes.get() + i * code_size;
+ size_t offset =
+ invlists->add_entry(key, id, code, inverted_list_context);
+
+ if (residuals_2) {
+ float* res2 = residuals_2 + i * d;
+ const float* xi = to_encode + i * d;
+ pq.decode(code, res2);
+ for (int j = 0; j < d; j++)
+ res2[j] = xi[j] - res2[j];
+ }
+
+ direct_map.add_single_id(id, key, offset);
+ }
+
+ double t3 = getmillisecs();
+ if (verbose) {
+ char comment[100] = {0};
+ if (n_ignore > 0)
+ snprintf(comment, 100, "(%zd vectors ignored)", n_ignore);
+ printf(" add_core times: %.3f %.3f %.3f %s\n",
+ t1 - t0,
+ t2 - t1,
+ t3 - t2,
+ comment);
+ }
+ ntotal += n;
+}
+
+void IndexIVFPQ::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ const uint8_t* code = invlists->get_single_code(list_no, offset);
+
+ pq.decode(code, recons);
+ if (by_residual) {
+ std::vector<float> centroid(d);
+ quantizer->reconstruct(list_no, centroid.data());
+
+ for (int i = 0; i < d; ++i) {
+ recons[i] += centroid[i];
+ }
+ }
+}
+
+/// 2G by default, accommodates tables up to PQ32 w/ 65536 centroids
+size_t precomputed_table_max_bytes = ((size_t)1) << 31;
+
+/** Precomputed tables for residuals
+ *
+ * During IVFPQ search with by_residual, we compute
+ *
+ * d = || x - y_C - y_R ||^2
+ *
+ * where x is the query vector, y_C the coarse centroid, y_R the
+ * refined PQ centroid. The expression can be decomposed as:
+ *
+ * d = || x - y_C ||^2 + || y_R ||^2 + 2 * (y_C|y_R) - 2 * (x|y_R)
+ * --------------- --------------------------- -------
+ * term 1 term 2 term 3
+ *
+ * When using multiprobe, we use the following decomposition:
+ * - term 1 is the distance to the coarse centroid, that is computed
+ * during the 1st stage search.
+ * - term 2 can be precomputed, as it does not involve x. However,
+ * because of the PQ, it needs nlist * M * ksub storage. This is why
+ * use_precomputed_table is off by default
+ * - term 3 is the classical non-residual distance table.
+ *
+ * Since y_R defined by a product quantizer, it is split across
+ * subvectors and stored separately for each subvector. If the coarse
+ * quantizer is a MultiIndexQuantizer then the table can be stored
+ * more compactly.
+ *
+ * At search time, the tables for term 2 and term 3 are added up. This
+ * is faster when the length of the lists is > ksub * M.
+ */
+
+void initialize_IVFPQ_precomputed_table(
+ int& use_precomputed_table,
+ const Index* quantizer,
+ const ProductQuantizer& pq,
+ AlignedTable<float>& precomputed_table,
+ bool by_residual,
+ bool verbose) {
+ size_t nlist = quantizer->ntotal;
+ size_t d = quantizer->d;
+ FAISS_THROW_IF_NOT(d == pq.d);
+
+ if (use_precomputed_table == -1) {
+ precomputed_table.resize(0);
+ return;
+ }
+
+ if (use_precomputed_table == 0) { // then choose the type of table
+ if (!(quantizer->metric_type == METRIC_L2 && by_residual)) {
+ if (verbose) {
+ printf("IndexIVFPQ::precompute_table: precomputed "
+ "tables needed only for L2 metric and by_residual is enabled\n");
+ }
+ precomputed_table.resize(0);
+ return;
+ }
+ const MultiIndexQuantizer* miq =
+ dynamic_cast<const MultiIndexQuantizer*>(quantizer);
+ if (miq && pq.M % miq->pq.M == 0)
+ use_precomputed_table = 2;
+ else {
+ size_t table_size = pq.M * pq.ksub * nlist * sizeof(float);
+ if (table_size > precomputed_table_max_bytes) {
+ if (verbose) {
+ printf("IndexIVFPQ::precompute_table: not precomputing table, "
+ "it would be too big: %zd bytes (max %zd)\n",
+ table_size,
+ precomputed_table_max_bytes);
+ use_precomputed_table = 0;
+ }
+ return;
+ }
+ use_precomputed_table = 1;
+ }
+ } // otherwise assume user has set appropriate flag on input
+
+ if (verbose) {
+ printf("precomputing IVFPQ tables type %d\n", use_precomputed_table);
+ }
+
+ // squared norms of the PQ centroids
+ std::vector<float> r_norms(pq.M * pq.ksub, NAN);
+ for (int m = 0; m < pq.M; m++)
+ for (int j = 0; j < pq.ksub; j++)
+ r_norms[m * pq.ksub + j] =
+ fvec_norm_L2sqr(pq.get_centroids(m, j), pq.dsub);
+
+ if (use_precomputed_table == 1) {
+ precomputed_table.resize(nlist * pq.M * pq.ksub);
+ std::vector<float> centroid(d);
+
+ for (size_t i = 0; i < nlist; i++) {
+ quantizer->reconstruct(i, centroid.data());
+
+ float* tab = &precomputed_table[i * pq.M * pq.ksub];
+ pq.compute_inner_prod_table(centroid.data(), tab);
+ fvec_madd(pq.M * pq.ksub, r_norms.data(), 2.0, tab, tab);
+ }
+ } else if (use_precomputed_table == 2) {
+ const MultiIndexQuantizer* miq =
+ dynamic_cast<const MultiIndexQuantizer*>(quantizer);
+ FAISS_THROW_IF_NOT(miq);
+ const ProductQuantizer& cpq = miq->pq;
+ FAISS_THROW_IF_NOT(pq.M % cpq.M == 0);
+
+ precomputed_table.resize(cpq.ksub * pq.M * pq.ksub);
+
+ // reorder PQ centroid table
+ std::vector<float> centroids(d * cpq.ksub, NAN);
+
+ for (int m = 0; m < cpq.M; m++) {
+ for (size_t i = 0; i < cpq.ksub; i++) {
+ memcpy(centroids.data() + i * d + m * cpq.dsub,
+ cpq.get_centroids(m, i),
+ sizeof(*centroids.data()) * cpq.dsub);
+ }
+ }
+
+ pq.compute_inner_prod_tables(
+ cpq.ksub, centroids.data(), precomputed_table.data());
+
+ for (size_t i = 0; i < cpq.ksub; i++) {
+ float* tab = &precomputed_table[i * pq.M * pq.ksub];
+ fvec_madd(pq.M * pq.ksub, r_norms.data(), 2.0, tab, tab);
+ }
+ }
+}
+
+void IndexIVFPQ::precompute_table() {
+ initialize_IVFPQ_precomputed_table(
+ use_precomputed_table,
+ quantizer,
+ pq,
+ precomputed_table,
+ by_residual,
+ verbose);
+}
+
+namespace {
+
+#define TIC t0 = get_cycles()
+#define TOC get_cycles() - t0
+
+/** QueryTables manages the various ways of searching an
+ * IndexIVFPQ. The code contains a lot of branches, depending on:
+ * - metric_type: are we computing L2 or Inner product similarity?
+ * - by_residual: do we encode raw vectors or residuals?
+ * - use_precomputed_table: are x_R|x_C tables precomputed?
+ * - polysemous_ht: are we filtering with polysemous codes?
+ */
+struct QueryTables {
+ /*****************************************************
+ * General data from the IVFPQ
+ *****************************************************/
+
+ const IndexIVFPQ& ivfpq;
+ const IVFSearchParameters* params;
+
+ // copied from IndexIVFPQ for easier access
+ int d;
+ const ProductQuantizer& pq;
+ MetricType metric_type;
+ bool by_residual;
+ int use_precomputed_table;
+ int polysemous_ht;
+
+ // pre-allocated data buffers
+ float *sim_table, *sim_table_2;
+ float *residual_vec, *decoded_vec;
+
+ // single data buffer
+ std::vector<float> mem;
+
+ // for table pointers
+ std::vector<const float*> sim_table_ptrs;
+
+ explicit QueryTables(
+ const IndexIVFPQ& ivfpq,
+ const IVFSearchParameters* params)
+ : ivfpq(ivfpq),
+ d(ivfpq.d),
+ pq(ivfpq.pq),
+ metric_type(ivfpq.metric_type),
+ by_residual(ivfpq.by_residual),
+ use_precomputed_table(ivfpq.use_precomputed_table) {
+ mem.resize(pq.ksub * pq.M * 2 + d * 2);
+ sim_table = mem.data();
+ sim_table_2 = sim_table + pq.ksub * pq.M;
+ residual_vec = sim_table_2 + pq.ksub * pq.M;
+ decoded_vec = residual_vec + d;
+
+ // for polysemous
+ polysemous_ht = ivfpq.polysemous_ht;
+ if (auto ivfpq_params =
+ dynamic_cast<const IVFPQSearchParameters*>(params)) {
+ polysemous_ht = ivfpq_params->polysemous_ht;
+ }
+ if (polysemous_ht != 0) {
+ q_code.resize(pq.code_size);
+ }
+ init_list_cycles = 0;
+ sim_table_ptrs.resize(pq.M);
+ }
+
+ /*****************************************************
+ * What we do when query is known
+ *****************************************************/
+
+ // field specific to query
+ const float* qi;
+
+ // query-specific initialization
+ void init_query(const float* qi) {
+ this->qi = qi;
+ if (metric_type == METRIC_INNER_PRODUCT)
+ init_query_IP();
+ else
+ init_query_L2();
+ if (!by_residual && polysemous_ht != 0)
+ pq.compute_code(qi, q_code.data());
+ }
+
+ void init_query_IP() {
+ // precompute some tables specific to the query qi
+ pq.compute_inner_prod_table(qi, sim_table);
+ }
+
+ void init_query_L2() {
+ if (!by_residual) {
+ pq.compute_distance_table(qi, sim_table);
+ } else if (use_precomputed_table) {
+ pq.compute_inner_prod_table(qi, sim_table_2);
+ }
+ }
+
+ /*****************************************************
+ * When inverted list is known: prepare computations
+ *****************************************************/
+
+ // fields specific to list
+ idx_t key;
+ float coarse_dis;
+ std::vector<uint8_t> q_code;
+
+ uint64_t init_list_cycles;
+
+ /// once we know the query and the centroid, we can prepare the
+ /// sim_table that will be used for accumulation
+ /// and dis0, the initial value
+ float precompute_list_tables() {
+ float dis0 = 0;
+ uint64_t t0;
+ TIC;
+ if (by_residual) {
+ if (metric_type == METRIC_INNER_PRODUCT)
+ dis0 = precompute_list_tables_IP();
+ else
+ dis0 = precompute_list_tables_L2();
+ }
+ init_list_cycles += TOC;
+ return dis0;
+ }
+
+ float precompute_list_table_pointers() {
+ float dis0 = 0;
+ uint64_t t0;
+ TIC;
+ if (by_residual) {
+ if (metric_type == METRIC_INNER_PRODUCT)
+ FAISS_THROW_MSG("not implemented");
+ else
+ dis0 = precompute_list_table_pointers_L2();
+ }
+ init_list_cycles += TOC;
+ return dis0;
+ }
+
+ /*****************************************************
+ * compute tables for inner prod
+ *****************************************************/
+
+ float precompute_list_tables_IP() {
+ // prepare the sim_table that will be used for accumulation
+ // and dis0, the initial value
+ ivfpq.quantizer->reconstruct(key, decoded_vec);
+ // decoded_vec = centroid
+ float dis0 = fvec_inner_product(qi, decoded_vec, d);
+
+ if (polysemous_ht) {
+ for (int i = 0; i < d; i++) {
+ residual_vec[i] = qi[i] - decoded_vec[i];
+ }
+ pq.compute_code(residual_vec, q_code.data());
+ }
+ return dis0;
+ }
+
+ /*****************************************************
+ * compute tables for L2 distance
+ *****************************************************/
+
+ float precompute_list_tables_L2() {
+ float dis0 = 0;
+
+ if (use_precomputed_table == 0 || use_precomputed_table == -1) {
+ ivfpq.quantizer->compute_residual(qi, residual_vec, key);
+ pq.compute_distance_table(residual_vec, sim_table);
+
+ if (polysemous_ht != 0) {
+ pq.compute_code(residual_vec, q_code.data());
+ }
+
+ } else if (use_precomputed_table == 1) {
+ dis0 = coarse_dis;
+
+ fvec_madd(
+ pq.M * pq.ksub,
+ ivfpq.precomputed_table.data() + key * pq.ksub * pq.M,
+ -2.0,
+ sim_table_2,
+ sim_table);
+
+ if (polysemous_ht != 0) {
+ ivfpq.quantizer->compute_residual(qi, residual_vec, key);
+ pq.compute_code(residual_vec, q_code.data());
+ }
+
+ } else if (use_precomputed_table == 2) {
+ dis0 = coarse_dis;
+
+ const MultiIndexQuantizer* miq =
+ dynamic_cast<const MultiIndexQuantizer*>(ivfpq.quantizer);
+ FAISS_THROW_IF_NOT(miq);
+ const ProductQuantizer& cpq = miq->pq;
+ int Mf = pq.M / cpq.M;
+
+ const float* qtab = sim_table_2; // query-specific table
+ float* ltab = sim_table; // (output) list-specific table
+
+ long k = key;
+ for (int cm = 0; cm < cpq.M; cm++) {
+ // compute PQ index
+ int ki = k & ((uint64_t(1) << cpq.nbits) - 1);
+ k >>= cpq.nbits;
+
+ // get corresponding table
+ const float* pc = ivfpq.precomputed_table.data() +
+ (ki * pq.M + cm * Mf) * pq.ksub;
+
+ if (polysemous_ht == 0) {
+ // sum up with query-specific table
+ fvec_madd(Mf * pq.ksub, pc, -2.0, qtab, ltab);
+ ltab += Mf * pq.ksub;
+ qtab += Mf * pq.ksub;
+ } else {
+ for (int m = cm * Mf; m < (cm + 1) * Mf; m++) {
+ q_code[m] = fvec_madd_and_argmin(
+ pq.ksub, pc, -2, qtab, ltab);
+ pc += pq.ksub;
+ ltab += pq.ksub;
+ qtab += pq.ksub;
+ }
+ }
+ }
+ }
+
+ return dis0;
+ }
+
+ float precompute_list_table_pointers_L2() {
+ float dis0 = 0;
+
+ if (use_precomputed_table == 1) {
+ dis0 = coarse_dis;
+
+ const float* s =
+ ivfpq.precomputed_table.data() + key * pq.ksub * pq.M;
+ for (int m = 0; m < pq.M; m++) {
+ sim_table_ptrs[m] = s;
+ s += pq.ksub;
+ }
+ } else if (use_precomputed_table == 2) {
+ dis0 = coarse_dis;
+
+ const MultiIndexQuantizer* miq =
+ dynamic_cast<const MultiIndexQuantizer*>(ivfpq.quantizer);
+ FAISS_THROW_IF_NOT(miq);
+ const ProductQuantizer& cpq = miq->pq;
+ int Mf = pq.M / cpq.M;
+
+ long k = key;
+ int m0 = 0;
+ for (int cm = 0; cm < cpq.M; cm++) {
+ int ki = k & ((uint64_t(1) << cpq.nbits) - 1);
+ k >>= cpq.nbits;
+
+ const float* pc = ivfpq.precomputed_table.data() +
+ (ki * pq.M + cm * Mf) * pq.ksub;
+
+ for (int m = m0; m < m0 + Mf; m++) {
+ sim_table_ptrs[m] = pc;
+ pc += pq.ksub;
+ }
+ m0 += Mf;
+ }
+ } else {
+ FAISS_THROW_MSG("need precomputed tables");
+ }
+
+ if (polysemous_ht) {
+ FAISS_THROW_MSG("not implemented");
+ // Not clear that it makes sense to implemente this,
+ // because it costs M * ksub, which is what we wanted to
+ // avoid with the tables pointers.
+ }
+
+ return dis0;
+ }
+};
+
+// This way of handling the selector is not optimal since all distances
+// are computed even if the id would filter it out.
+template <class C, bool use_sel>
+struct KnnSearchResults {
+ idx_t key;
+ const idx_t* ids;
+ const IDSelector* sel;
+
+ // heap params
+ size_t k;
+ float* heap_sim;
+ idx_t* heap_ids;
+
+ size_t nup;
+
+ inline bool skip_entry(idx_t j) {
+ return use_sel && !sel->is_member(ids[j]);
+ }
+
+ inline void add(idx_t j, float dis) {
+ if (C::cmp(heap_sim[0], dis)) {
+ idx_t id = ids ? ids[j] : lo_build(key, j);
+ heap_replace_top<C>(k, heap_sim, heap_ids, dis, id);
+ nup++;
+ }
+ }
+};
+
+template <class C, bool use_sel>
+struct RangeSearchResults {
+ idx_t key;
+ const idx_t* ids;
+ const IDSelector* sel;
+
+ // wrapped result structure
+ float radius;
+ RangeQueryResult& rres;
+
+ inline bool skip_entry(idx_t j) {
+ return use_sel && !sel->is_member(ids[j]);
+ }
+
+ inline void add(idx_t j, float dis) {
+ if (C::cmp(radius, dis)) {
+ idx_t id = ids ? ids[j] : lo_build(key, j);
+ rres.add(dis, id);
+ }
+ }
+};
+
+/*****************************************************
+ * Scaning the codes.
+ * The scanning functions call their favorite precompute_*
+ * function to precompute the tables they need.
+ *****************************************************/
+template <typename IDType, MetricType METRIC_TYPE, class PQDecoder>
+struct IVFPQScannerT : QueryTables {
+ const uint8_t* list_codes;
+ const IDType* list_ids;
+ size_t list_size;
+
+ IVFPQScannerT(const IndexIVFPQ& ivfpq, const IVFSearchParameters* params)
+ : QueryTables(ivfpq, params) {
+ assert(METRIC_TYPE == metric_type);
+ }
+
+ float dis0;
+
+ void init_list(idx_t list_no, float coarse_dis, int mode) {
+ this->key = list_no;
+ this->coarse_dis = coarse_dis;
+
+ if (mode == 2) {
+ dis0 = precompute_list_tables();
+ } else if (mode == 1) {
+ dis0 = precompute_list_table_pointers();
+ }
+ }
+
+ /*****************************************************
+ * Scaning the codes: simple PQ scan.
+ *****************************************************/
+
+ // This is the baseline version of scan_list_with_tables().
+ // It demonstrates what this function actually does.
+ //
+ // /// version of the scan where we use precomputed tables.
+ // template <class SearchResultType>
+ // void scan_list_with_table(
+ // size_t ncode,
+ // const uint8_t* codes,
+ // SearchResultType& res) const {
+ //
+ // for (size_t j = 0; j < ncode; j++, codes += pq.code_size) {
+ // if (res.skip_entry(j)) {
+ // continue;
+ // }
+ // float dis = dis0 + distance_single_code<PQDecoder>(
+ // pq, sim_table, codes);
+ // res.add(j, dis);
+ // }
+ // }
+
+ // This is the modified version of scan_list_with_tables().
+ // It was observed that doing manual unrolling of the loop that
+ // utilizes distance_single_code() speeds up the computations.
+
+ /// version of the scan where we use precomputed tables.
+ template <class SearchResultType>
+ void scan_list_with_table(
+ size_t ncode,
+ const uint8_t* codes,
+ SearchResultType& res) const {
+ int counter = 0;
+
+ size_t saved_j[4] = {0, 0, 0, 0};
+ for (size_t j = 0; j < ncode; j++) {
+ if (res.skip_entry(j)) {
+ continue;
+ }
+
+ saved_j[0] = (counter == 0) ? j : saved_j[0];
+ saved_j[1] = (counter == 1) ? j : saved_j[1];
+ saved_j[2] = (counter == 2) ? j : saved_j[2];
+ saved_j[3] = (counter == 3) ? j : saved_j[3];
+
+ counter += 1;
+ if (counter == 4) {
+ float distance_0 = 0;
+ float distance_1 = 0;
+ float distance_2 = 0;
+ float distance_3 = 0;
+ distance_four_codes<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + saved_j[0] * pq.code_size,
+ codes + saved_j[1] * pq.code_size,
+ codes + saved_j[2] * pq.code_size,
+ codes + saved_j[3] * pq.code_size,
+ distance_0,
+ distance_1,
+ distance_2,
+ distance_3);
+
+ res.add(saved_j[0], dis0 + distance_0);
+ res.add(saved_j[1], dis0 + distance_1);
+ res.add(saved_j[2], dis0 + distance_2);
+ res.add(saved_j[3], dis0 + distance_3);
+ counter = 0;
+ }
+ }
+
+ if (counter >= 1) {
+ float dis = dis0 +
+ distance_single_code<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + saved_j[0] * pq.code_size);
+ res.add(saved_j[0], dis);
+ }
+ if (counter >= 2) {
+ float dis = dis0 +
+ distance_single_code<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + saved_j[1] * pq.code_size);
+ res.add(saved_j[1], dis);
+ }
+ if (counter >= 3) {
+ float dis = dis0 +
+ distance_single_code<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + saved_j[2] * pq.code_size);
+ res.add(saved_j[2], dis);
+ }
+ }
+
+ /// tables are not precomputed, but pointers are provided to the
+ /// relevant X_c|x_r tables
+ template <class SearchResultType>
+ void scan_list_with_pointer(
+ size_t ncode,
+ const uint8_t* codes,
+ SearchResultType& res) const {
+ for (size_t j = 0; j < ncode; j++, codes += pq.code_size) {
+ if (res.skip_entry(j)) {
+ continue;
+ }
+ PQDecoder decoder(codes, pq.nbits);
+ float dis = dis0;
+ const float* tab = sim_table_2;
+
+ for (size_t m = 0; m < pq.M; m++) {
+ int ci = decoder.decode();
+ dis += sim_table_ptrs[m][ci] - 2 * tab[ci];
+ tab += pq.ksub;
+ }
+ res.add(j, dis);
+ }
+ }
+
+ /// nothing is precomputed: access residuals on-the-fly
+ template <class SearchResultType>
+ void scan_on_the_fly_dist(
+ size_t ncode,
+ const uint8_t* codes,
+ SearchResultType& res) const {
+ const float* dvec;
+ float dis0 = 0;
+ if (by_residual) {
+ if (METRIC_TYPE == METRIC_INNER_PRODUCT) {
+ ivfpq.quantizer->reconstruct(key, residual_vec);
+ dis0 = fvec_inner_product(residual_vec, qi, d);
+ } else {
+ ivfpq.quantizer->compute_residual(qi, residual_vec, key);
+ }
+ dvec = residual_vec;
+ } else {
+ dvec = qi;
+ dis0 = 0;
+ }
+
+ for (size_t j = 0; j < ncode; j++, codes += pq.code_size) {
+ if (res.skip_entry(j)) {
+ continue;
+ }
+ pq.decode(codes, decoded_vec);
+
+ float dis;
+ if (METRIC_TYPE == METRIC_INNER_PRODUCT) {
+ dis = dis0 + fvec_inner_product(decoded_vec, qi, d);
+ } else {
+ dis = fvec_L2sqr(decoded_vec, dvec, d);
+ }
+ res.add(j, dis);
+ }
+ }
+
+ /*****************************************************
+ * Scanning codes with polysemous filtering
+ *****************************************************/
+
+ // This is the baseline version of scan_list_polysemous_hc().
+ // It demonstrates what this function actually does.
+
+ // template <class HammingComputer, class SearchResultType>
+ // void scan_list_polysemous_hc(
+ // size_t ncode,
+ // const uint8_t* codes,
+ // SearchResultType& res) const {
+ // int ht = ivfpq.polysemous_ht;
+ // size_t n_hamming_pass = 0, nup = 0;
+ //
+ // int code_size = pq.code_size;
+ //
+ // HammingComputer hc(q_code.data(), code_size);
+ //
+ // for (size_t j = 0; j < ncode; j++, codes += code_size) {
+ // if (res.skip_entry(j)) {
+ // continue;
+ // }
+ // const uint8_t* b_code = codes;
+ // int hd = hc.hamming(b_code);
+ // if (hd < ht) {
+ // n_hamming_pass++;
+ //
+ // float dis =
+ // dis0 +
+ // distance_single_code<PQDecoder>(
+ // pq, sim_table, codes);
+ //
+ // res.add(j, dis);
+ // }
+ // }
+ // #pragma omp critical
+ // { indexIVFPQ_stats.n_hamming_pass += n_hamming_pass; }
+ // }
+
+ // This is the modified version of scan_list_with_tables().
+ // It was observed that doing manual unrolling of the loop that
+ // utilizes distance_single_code() speeds up the computations.
+
+ template <class HammingComputer, class SearchResultType>
+ void scan_list_polysemous_hc(
+ size_t ncode,
+ const uint8_t* codes,
+ SearchResultType& res) const {
+ int ht = ivfpq.polysemous_ht;
+ size_t n_hamming_pass = 0;
+
+ int code_size = pq.code_size;
+
+ size_t saved_j[8];
+ int counter = 0;
+
+ HammingComputer hc(q_code.data(), code_size);
+
+ for (size_t j = 0; j < (ncode / 4) * 4; j += 4) {
+ const uint8_t* b_code = codes + j * code_size;
+
+ // Unrolling is a key. Basically, doing multiple popcount
+ // operations one after another speeds things up.
+
+ // 9999999 is just an arbitrary large number
+ int hd0 = (res.skip_entry(j + 0))
+ ? 99999999
+ : hc.hamming(b_code + 0 * code_size);
+ int hd1 = (res.skip_entry(j + 1))
+ ? 99999999
+ : hc.hamming(b_code + 1 * code_size);
+ int hd2 = (res.skip_entry(j + 2))
+ ? 99999999
+ : hc.hamming(b_code + 2 * code_size);
+ int hd3 = (res.skip_entry(j + 3))
+ ? 99999999
+ : hc.hamming(b_code + 3 * code_size);
+
+ saved_j[counter] = j + 0;
+ counter = (hd0 < ht) ? (counter + 1) : counter;
+ saved_j[counter] = j + 1;
+ counter = (hd1 < ht) ? (counter + 1) : counter;
+ saved_j[counter] = j + 2;
+ counter = (hd2 < ht) ? (counter + 1) : counter;
+ saved_j[counter] = j + 3;
+ counter = (hd3 < ht) ? (counter + 1) : counter;
+
+ if (counter >= 4) {
+ // process four codes at the same time
+ n_hamming_pass += 4;
+
+ float distance_0 = dis0;
+ float distance_1 = dis0;
+ float distance_2 = dis0;
+ float distance_3 = dis0;
+ distance_four_codes<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + saved_j[0] * pq.code_size,
+ codes + saved_j[1] * pq.code_size,
+ codes + saved_j[2] * pq.code_size,
+ codes + saved_j[3] * pq.code_size,
+ distance_0,
+ distance_1,
+ distance_2,
+ distance_3);
+
+ res.add(saved_j[0], dis0 + distance_0);
+ res.add(saved_j[1], dis0 + distance_1);
+ res.add(saved_j[2], dis0 + distance_2);
+ res.add(saved_j[3], dis0 + distance_3);
+
+ //
+ counter -= 4;
+ saved_j[0] = saved_j[4];
+ saved_j[1] = saved_j[5];
+ saved_j[2] = saved_j[6];
+ saved_j[3] = saved_j[7];
+ }
+ }
+
+ for (size_t kk = 0; kk < counter; kk++) {
+ n_hamming_pass++;
+
+ float dis = dis0 +
+ distance_single_code<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + saved_j[kk] * pq.code_size);
+
+ res.add(saved_j[kk], dis);
+ }
+
+ // process leftovers
+ for (size_t j = (ncode / 4) * 4; j < ncode; j++) {
+ if (res.skip_entry(j)) {
+ continue;
+ }
+ const uint8_t* b_code = codes + j * code_size;
+ int hd = hc.hamming(b_code);
+ if (hd < ht) {
+ n_hamming_pass++;
+
+ float dis = dis0 +
+ distance_single_code<PQDecoder>(
+ pq.M,
+ pq.nbits,
+ sim_table,
+ codes + j * code_size);
+
+ res.add(j, dis);
+ }
+ }
+
+#pragma omp critical
+ { indexIVFPQ_stats.n_hamming_pass += n_hamming_pass; }
+ }
+
+ template <class SearchResultType>
+ struct Run_scan_list_polysemous_hc {
+ using T = void;
+ template <class HammingComputer, class... Types>
+ void f(const IVFPQScannerT* scanner, Types... args) {
+ scanner->scan_list_polysemous_hc<HammingComputer, SearchResultType>(
+ args...);
+ }
+ };
+
+ template <class SearchResultType>
+ void scan_list_polysemous(
+ size_t ncode,
+ const uint8_t* codes,
+ SearchResultType& res) const {
+ Run_scan_list_polysemous_hc<SearchResultType> r;
+ dispatch_HammingComputer(pq.code_size, r, this, ncode, codes, res);
+ }
+};
+
+/* We put as many parameters as possible in template. Hopefully the
+ * gain in runtime is worth the code bloat.
+ *
+ * C is the comparator < or >, it is directly related to METRIC_TYPE.
+ *
+ * precompute_mode is how much we precompute (2 = precompute distance tables,
+ * 1 = precompute pointers to distances, 0 = compute distances one by one).
+ * Currently only 2 is supported
+ *
+ * use_sel: store or ignore the IDSelector
+ */
+template <MetricType METRIC_TYPE, class C, class PQDecoder, bool use_sel>
+struct IVFPQScanner : IVFPQScannerT<idx_t, METRIC_TYPE, PQDecoder>,
+ InvertedListScanner {
+ int precompute_mode;
+ const IDSelector* sel;
+
+ IVFPQScanner(
+ const IndexIVFPQ& ivfpq,
+ bool store_pairs,
+ int precompute_mode,
+ const IDSelector* sel)
+ : IVFPQScannerT<idx_t, METRIC_TYPE, PQDecoder>(ivfpq, nullptr),
+ precompute_mode(precompute_mode),
+ sel(sel) {
+ this->store_pairs = store_pairs;
+ this->keep_max = is_similarity_metric(METRIC_TYPE);
+ }
+
+ void set_query(const float* query) override {
+ this->init_query(query);
+ }
+
+ void set_list(idx_t list_no, float coarse_dis) override {
+ this->list_no = list_no;
+ this->init_list(list_no, coarse_dis, precompute_mode);
+ }
+
+ float distance_to_code(const uint8_t* code) const override {
+ assert(precompute_mode == 2);
+ float dis = this->dis0 +
+ distance_single_code<PQDecoder>(
+ this->pq.M, this->pq.nbits, this->sim_table, code);
+ return dis;
+ }
+
+ size_t scan_codes(
+ size_t ncode,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* heap_sim,
+ idx_t* heap_ids,
+ size_t k) const override {
+ KnnSearchResults<C, use_sel> res = {
+ /* key */ this->key,
+ /* ids */ this->store_pairs ? nullptr : ids,
+ /* sel */ this->sel,
+ /* k */ k,
+ /* heap_sim */ heap_sim,
+ /* heap_ids */ heap_ids,
+ /* nup */ 0};
+
+ if (this->polysemous_ht > 0) {
+ assert(precompute_mode == 2);
+ this->scan_list_polysemous(ncode, codes, res);
+ } else if (precompute_mode == 2) {
+ this->scan_list_with_table(ncode, codes, res);
+ } else if (precompute_mode == 1) {
+ this->scan_list_with_pointer(ncode, codes, res);
+ } else if (precompute_mode == 0) {
+ this->scan_on_the_fly_dist(ncode, codes, res);
+ } else {
+ FAISS_THROW_MSG("bad precomp mode");
+ }
+ return res.nup;
+ }
+
+ void scan_codes_range(
+ size_t ncode,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& rres) const override {
+ RangeSearchResults<C, use_sel> res = {
+ /* key */ this->key,
+ /* ids */ this->store_pairs ? nullptr : ids,
+ /* sel */ this->sel,
+ /* radius */ radius,
+ /* rres */ rres};
+
+ if (this->polysemous_ht > 0) {
+ assert(precompute_mode == 2);
+ this->scan_list_polysemous(ncode, codes, res);
+ } else if (precompute_mode == 2) {
+ this->scan_list_with_table(ncode, codes, res);
+ } else if (precompute_mode == 1) {
+ this->scan_list_with_pointer(ncode, codes, res);
+ } else if (precompute_mode == 0) {
+ this->scan_on_the_fly_dist(ncode, codes, res);
+ } else {
+ FAISS_THROW_MSG("bad precomp mode");
+ }
+ }
+};
+
+template <class PQDecoder, bool use_sel>
+InvertedListScanner* get_InvertedListScanner1(
+ const IndexIVFPQ& index,
+ bool store_pairs,
+ const IDSelector* sel) {
+ if (index.metric_type == METRIC_INNER_PRODUCT) {
+ return new IVFPQScanner<
+ METRIC_INNER_PRODUCT,
+ CMin<float, idx_t>,
+ PQDecoder,
+ use_sel>(index, store_pairs, 2, sel);
+ } else if (index.metric_type == METRIC_L2) {
+ return new IVFPQScanner<
+ METRIC_L2,
+ CMax<float, idx_t>,
+ PQDecoder,
+ use_sel>(index, store_pairs, 2, sel);
+ }
+ return nullptr;
+}
+
+template <bool use_sel>
+InvertedListScanner* get_InvertedListScanner2(
+ const IndexIVFPQ& index,
+ bool store_pairs,
+ const IDSelector* sel) {
+ if (index.pq.nbits == 8) {
+ return get_InvertedListScanner1<PQDecoder8, use_sel>(
+ index, store_pairs, sel);
+ } else if (index.pq.nbits == 16) {
+ return get_InvertedListScanner1<PQDecoder16, use_sel>(
+ index, store_pairs, sel);
+ } else {
+ return get_InvertedListScanner1<PQDecoderGeneric, use_sel>(
+ index, store_pairs, sel);
+ }
+}
+
+} // anonymous namespace
+
+InvertedListScanner* IndexIVFPQ::get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters*) const {
+ if (sel) {
+ return get_InvertedListScanner2<true>(*this, store_pairs, sel);
+ } else {
+ return get_InvertedListScanner2<false>(*this, store_pairs, sel);
+ }
+ return nullptr;
+}
+
+IndexIVFPQStats indexIVFPQ_stats;
+
+void IndexIVFPQStats::reset() {
+ memset(this, 0, sizeof(*this));
+}
+
+IndexIVFPQ::IndexIVFPQ() {
+ // initialize some runtime values
+ use_precomputed_table = 0;
+ scan_table_threshold = 0;
+ do_polysemous_training = false;
+ polysemous_ht = 0;
+ polysemous_training = nullptr;
+}
+
+struct CodeCmp {
+ const uint8_t* tab;
+ size_t code_size;
+ bool operator()(int a, int b) const {
+ return cmp(a, b) > 0;
+ }
+ int cmp(int a, int b) const {
+ return memcmp(tab + a * code_size, tab + b * code_size, code_size);
+ }
+};
+
+size_t IndexIVFPQ::find_duplicates(idx_t* dup_ids, size_t* lims) const {
+ size_t ngroup = 0;
+ lims[0] = 0;
+ for (size_t list_no = 0; list_no < nlist; list_no++) {
+ size_t n = invlists->list_size(list_no);
+ std::vector<int> ord(n);
+ for (int i = 0; i < n; i++)
+ ord[i] = i;
+ InvertedLists::ScopedCodes codes(invlists, list_no);
+ CodeCmp cs = {codes.get(), code_size};
+ std::sort(ord.begin(), ord.end(), cs);
+
+ InvertedLists::ScopedIds list_ids(invlists, list_no);
+ int prev = -1; // all elements from prev to i-1 are equal
+ for (int i = 0; i < n; i++) {
+ if (prev >= 0 && cs.cmp(ord[prev], ord[i]) == 0) {
+ // same as previous => remember
+ if (prev + 1 == i) { // start new group
+ ngroup++;
+ lims[ngroup] = lims[ngroup - 1];
+ dup_ids[lims[ngroup]++] = list_ids[ord[prev]];
+ }
+ dup_ids[lims[ngroup]++] = list_ids[ord[i]];
+ } else { // not same as previous.
+ prev = i;
+ }
+ }
+ }
+ return ngroup;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQ.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQ.h
new file mode 100644
index 0000000..1659fc4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQ.h
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_IVFPQ_H
+#define FAISS_INDEX_IVFPQ_H
+
+#include <vector>
+
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+struct IVFPQSearchParameters : IVFSearchParameters {
+ size_t scan_table_threshold; ///< use table computation or on-the-fly?
+ int polysemous_ht; ///< Hamming thresh for polysemous filtering
+ IVFPQSearchParameters() : scan_table_threshold(0), polysemous_ht(0) {}
+ ~IVFPQSearchParameters() {}
+};
+
+FAISS_API extern size_t precomputed_table_max_bytes;
+
+/** Inverted file with Product Quantizer encoding. Each residual
+ * vector is encoded as a product quantizer code.
+ */
+struct IndexIVFPQ : IndexIVF {
+ ProductQuantizer pq; ///< produces the codes
+
+ bool do_polysemous_training; ///< reorder PQ centroids after training?
+ PolysemousTraining* polysemous_training; ///< if NULL, use default
+
+ // search-time parameters
+ size_t scan_table_threshold; ///< use table computation or on-the-fly?
+ int polysemous_ht; ///< Hamming thresh for polysemous filtering
+
+ /** Precompute table that speed up query preprocessing at some
+ * memory cost (used only for by_residual with L2 metric)
+ */
+ int use_precomputed_table;
+
+ /// if use_precompute_table
+ /// size nlist * pq.M * pq.ksub
+ AlignedTable<float> precomputed_table;
+
+ IndexIVFPQ(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits_per_idx,
+ MetricType metric = METRIC_L2);
+
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos = false) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ void add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context = nullptr) override;
+
+ /// same as add_core, also:
+ /// - output 2nd level residuals if residuals_2 != NULL
+ /// - accepts precomputed_idx = nullptr
+ void add_core_o(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ float* residuals_2,
+ const idx_t* precomputed_idx = nullptr,
+ void* inverted_list_context = nullptr);
+
+ /// trains the product quantizer
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ idx_t train_encoder_num_vectors() const override;
+
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ /** Find exact duplicates in the dataset.
+ *
+ * the duplicates are returned in pre-allocated arrays (see the
+ * max sizes).
+ *
+ * @param lims limits between groups of duplicates
+ * (max size ntotal / 2 + 1)
+ * @param ids ids[lims[i]] : ids[lims[i+1]-1] is a group of
+ * duplicates (max size ntotal)
+ * @return n number of groups found
+ */
+ size_t find_duplicates(idx_t* ids, size_t* lims) const;
+
+ // map a vector to a binary code knowning the index
+ void encode(idx_t key, const float* x, uint8_t* code) const;
+
+ /** Encode multiple vectors
+ *
+ * @param n nb vectors to encode
+ * @param keys posting list ids for those vectors (size n)
+ * @param x vectors (size n * d)
+ * @param codes output codes (size n * code_size)
+ * @param compute_keys if false, assume keys are precomputed,
+ * otherwise compute them
+ */
+ void encode_multiple(
+ size_t n,
+ idx_t* keys,
+ const float* x,
+ uint8_t* codes,
+ bool compute_keys = false) const;
+
+ /// inverse of encode_multiple
+ void decode_multiple(
+ size_t n,
+ const idx_t* keys,
+ const uint8_t* xcodes,
+ float* x) const;
+
+ InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* params) const override;
+
+ /// build precomputed table
+ void precompute_table();
+
+ IndexIVFPQ();
+};
+
+// block size used in IndexIVFPQ::add_core_o
+FAISS_API extern int index_ivfpq_add_core_o_bs;
+
+/** Pre-compute distance tables for IVFPQ with by-residual and METRIC_L2
+ *
+ * @param use_precomputed_table (I/O)
+ * =-1: force disable
+ * =0: decide heuristically (default: use tables only if they are
+ * < precomputed_tables_max_bytes), set use_precomputed_table on
+ * output =1: tables that work for all quantizers (size 256 * nlist * M) =2:
+ * specific version for MultiIndexQuantizer (much more compact)
+ * @param precomputed_table precomputed table to initialize
+ */
+
+void initialize_IVFPQ_precomputed_table(
+ int& use_precomputed_table,
+ const Index* quantizer,
+ const ProductQuantizer& pq,
+ AlignedTable<float>& precomputed_table,
+ bool by_residual,
+ bool verbose);
+
+/// statistics are robust to internal threading, but not if
+/// IndexIVFPQ::search_preassigned is called by multiple threads
+struct IndexIVFPQStats {
+ size_t nrefine; ///< nb of refines (IVFPQR)
+
+ size_t n_hamming_pass;
+ ///< nb of passed Hamming distance tests (for polysemous)
+
+ // timings measured with the CPU RTC on all threads
+ size_t search_cycles;
+ size_t refine_cycles; ///< only for IVFPQR
+
+ IndexIVFPQStats() {
+ reset();
+ }
+ void reset();
+};
+
+// global var that collects them all
+FAISS_API extern IndexIVFPQStats indexIVFPQ_stats;
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQFastScan.cpp
new file mode 100644
index 0000000..95efaaa
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQFastScan.cpp
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFPQFastScan.h>
+
+#include <cassert>
+#include <cinttypes>
+#include <cstdio>
+
+#include <memory>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/simdlib.h>
+
+#include <faiss/invlists/BlockInvertedLists.h>
+
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/impl/simd_result_handlers.h>
+
+namespace faiss {
+
+using namespace simd_result_handlers;
+
+inline size_t roundup(size_t a, size_t b) {
+ return (a + b - 1) / b * b;
+}
+
+IndexIVFPQFastScan::IndexIVFPQFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits,
+ MetricType metric,
+ int bbs)
+ : IndexIVFFastScan(quantizer, d, nlist, 0, metric), pq(d, M, nbits) {
+ by_residual = false; // set to false by default because it's faster
+
+ init_fastscan(&pq, M, nbits, nlist, metric, bbs);
+}
+
+IndexIVFPQFastScan::IndexIVFPQFastScan() {
+ by_residual = false;
+ bbs = 0;
+ M2 = 0;
+}
+
+IndexIVFPQFastScan::IndexIVFPQFastScan(const IndexIVFPQ& orig, int bbs)
+ : IndexIVFFastScan(
+ orig.quantizer,
+ orig.d,
+ orig.nlist,
+ orig.pq.code_size,
+ orig.metric_type),
+ pq(orig.pq) {
+ FAISS_THROW_IF_NOT(orig.pq.nbits == 4);
+
+ init_fastscan(
+ &pq, orig.pq.M, orig.pq.nbits, orig.nlist, orig.metric_type, bbs);
+
+ by_residual = orig.by_residual;
+ ntotal = orig.ntotal;
+ is_trained = orig.is_trained;
+ nprobe = orig.nprobe;
+
+ precomputed_table.resize(orig.precomputed_table.size());
+
+ if (precomputed_table.nbytes() > 0) {
+ memcpy(precomputed_table.get(),
+ orig.precomputed_table.data(),
+ precomputed_table.nbytes());
+ }
+
+#pragma omp parallel for if (nlist > 100)
+ for (idx_t i = 0; i < nlist; i++) {
+ size_t nb = orig.invlists->list_size(i);
+ size_t nb2 = roundup(nb, bbs);
+ AlignedTable<uint8_t> tmp(nb2 * M2 / 2);
+ pq4_pack_codes(
+ InvertedLists::ScopedCodes(orig.invlists, i).get(),
+ nb,
+ M,
+ nb2,
+ bbs,
+ M2,
+ tmp.get());
+ invlists->add_entries(
+ i,
+ nb,
+ InvertedLists::ScopedIds(orig.invlists, i).get(),
+ tmp.get());
+ }
+
+ orig_invlists = orig.invlists;
+}
+
+/*********************************************************
+ * Training
+ *********************************************************/
+
+void IndexIVFPQFastScan::train_encoder(
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ pq.verbose = verbose;
+ pq.train(n, x);
+
+ if (by_residual && metric_type == METRIC_L2) {
+ precompute_table();
+ }
+}
+
+idx_t IndexIVFPQFastScan::train_encoder_num_vectors() const {
+ return pq.cp.max_points_per_centroid * pq.ksub;
+}
+
+void IndexIVFPQFastScan::precompute_table() {
+ initialize_IVFPQ_precomputed_table(
+ use_precomputed_table,
+ quantizer,
+ pq,
+ precomputed_table,
+ by_residual,
+ verbose);
+}
+
+/*********************************************************
+ * Code management functions
+ *********************************************************/
+
+void IndexIVFPQFastScan::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ if (by_residual) {
+ AlignedTable<float> residuals(n * d);
+ for (size_t i = 0; i < n; i++) {
+ if (list_nos[i] < 0) {
+ memset(residuals.data() + i * d, 0, sizeof(residuals[0]) * d);
+ } else {
+ quantizer->compute_residual(
+ x + i * d, residuals.data() + i * d, list_nos[i]);
+ }
+ }
+ pq.compute_codes(residuals.data(), codes, n);
+ } else {
+ pq.compute_codes(x, codes, n);
+ }
+
+ if (include_listnos) {
+ size_t coarse_size = coarse_code_size();
+ for (idx_t i = n - 1; i >= 0; i--) {
+ uint8_t* code = codes + i * (coarse_size + code_size);
+ memmove(code + coarse_size, codes + i * code_size, code_size);
+ encode_listno(list_nos[i], code);
+ }
+ }
+}
+
+/*********************************************************
+ * Look-Up Table functions
+ *********************************************************/
+
+void fvec_madd_simd(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ assert(is_aligned_pointer(a));
+ assert(is_aligned_pointer(b));
+ assert(is_aligned_pointer(c));
+ assert(n % 8 == 0);
+ simd8float32 bf8(bf);
+ n /= 8;
+ for (size_t i = 0; i < n; i++) {
+ simd8float32 ai(a);
+ simd8float32 bi(b);
+
+ simd8float32 ci = fmadd(bf8, bi, ai);
+ ci.store(c);
+ c += 8;
+ a += 8;
+ b += 8;
+ }
+}
+
+bool IndexIVFPQFastScan::lookup_table_is_3d() const {
+ return by_residual && metric_type == METRIC_L2;
+}
+
+void IndexIVFPQFastScan::compute_LUT(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<float>& dis_tables,
+ AlignedTable<float>& biases) const {
+ size_t dim12 = pq.ksub * pq.M;
+ size_t d = pq.d;
+ size_t nprobe = this->nprobe;
+
+ if (by_residual) {
+ if (metric_type == METRIC_L2) {
+ dis_tables.resize(n * nprobe * dim12);
+
+ if (use_precomputed_table == 1) {
+ biases.resize(n * nprobe);
+ memcpy(biases.get(), cq.dis, sizeof(float) * n * nprobe);
+
+ AlignedTable<float> ip_table(n * dim12);
+ pq.compute_inner_prod_tables(n, x, ip_table.get());
+
+#pragma omp parallel for if (n * nprobe > 8000)
+ for (idx_t ij = 0; ij < n * nprobe; ij++) {
+ idx_t i = ij / nprobe;
+ float* tab = dis_tables.get() + ij * dim12;
+ idx_t cij = cq.ids[ij];
+
+ if (cij >= 0) {
+ fvec_madd_simd(
+ dim12,
+ precomputed_table.get() + cij * dim12,
+ -2,
+ ip_table.get() + i * dim12,
+ tab);
+ } else {
+ // fill with NaNs so that they are ignored during
+ // LUT quantization
+ memset(tab, -1, sizeof(float) * dim12);
+ }
+ }
+
+ } else {
+ std::unique_ptr<float[]> xrel(new float[n * nprobe * d]);
+ biases.resize(n * nprobe);
+ memset(biases.get(), 0, sizeof(float) * n * nprobe);
+
+#pragma omp parallel for if (n * nprobe > 8000)
+ for (idx_t ij = 0; ij < n * nprobe; ij++) {
+ idx_t i = ij / nprobe;
+ float* xij = &xrel[ij * d];
+ idx_t cij = cq.ids[ij];
+
+ if (cij >= 0) {
+ quantizer->compute_residual(x + i * d, xij, cij);
+ } else {
+ // will fill with NaNs
+ memset(xij, -1, sizeof(float) * d);
+ }
+ }
+
+ pq.compute_distance_tables(
+ n * nprobe, xrel.get(), dis_tables.get());
+ }
+
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ dis_tables.resize(n * dim12);
+ pq.compute_inner_prod_tables(n, x, dis_tables.get());
+ // compute_inner_prod_tables(pq, n, x, dis_tables.get());
+
+ biases.resize(n * nprobe);
+ memcpy(biases.get(), cq.dis, sizeof(float) * n * nprobe);
+ } else {
+ FAISS_THROW_FMT("metric %d not supported", metric_type);
+ }
+
+ } else {
+ dis_tables.resize(n * dim12);
+ if (metric_type == METRIC_L2) {
+ pq.compute_distance_tables(n, x, dis_tables.get());
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ pq.compute_inner_prod_tables(n, x, dis_tables.get());
+ } else {
+ FAISS_THROW_FMT("metric %d not supported", metric_type);
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQFastScan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQFastScan.h
new file mode 100644
index 0000000..f2d722f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQFastScan.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <memory>
+
+#include <faiss/IndexIVFFastScan.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+/** Fast scan version of IVFPQ. Works for 4-bit PQ for now.
+ *
+ * The codes in the inverted lists are not stored sequentially but
+ * grouped in blocks of size bbs. This makes it possible to very quickly
+ * compute distances with SIMD instructions.
+ *
+ * Implementations (implem):
+ * 0: auto-select implementation (default)
+ * 1: orig's search, re-implemented
+ * 2: orig's search, re-ordered by invlist
+ * 10: optimizer int16 search, collect results in heap, no qbs
+ * 11: idem, collect results in reservoir
+ * 12: optimizer int16 search, collect results in heap, uses qbs
+ * 13: idem, collect results in reservoir
+ */
+
+struct IndexIVFPQFastScan : IndexIVFFastScan {
+ ProductQuantizer pq; ///< produces the codes
+
+ /// precomputed tables management
+ int use_precomputed_table = 0;
+ /// if use_precompute_table size (nlist, pq.M, pq.ksub)
+ AlignedTable<float> precomputed_table;
+
+ IndexIVFPQFastScan(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ int bbs = 32);
+
+ IndexIVFPQFastScan();
+
+ // built from an IndexIVFPQ
+ explicit IndexIVFPQFastScan(const IndexIVFPQ& orig, int bbs = 32);
+
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ idx_t train_encoder_num_vectors() const override;
+
+ /// build precomputed table, possibly updating use_precomputed_table
+ void precompute_table();
+
+ /// same as the regular IVFPQ encoder. The codes are not reorganized by
+ /// blocks a that point
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listno = false) const override;
+
+ // prepare look-up tables
+
+ bool lookup_table_is_3d() const override;
+
+ void compute_LUT(
+ size_t n,
+ const float* x,
+ const CoarseQuantized& cq,
+ AlignedTable<float>& dis_tables,
+ AlignedTable<float>& biases) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQR.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQR.cpp
new file mode 100644
index 0000000..8f76c86
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQR.cpp
@@ -0,0 +1,238 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexIVFPQR.h>
+
+#include <cinttypes>
+
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+/*****************************************
+ * IndexIVFPQR implementation
+ ******************************************/
+
+IndexIVFPQR::IndexIVFPQR(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits_per_idx,
+ size_t M_refine,
+ size_t nbits_per_idx_refine)
+ : IndexIVFPQ(quantizer, d, nlist, M, nbits_per_idx),
+ refine_pq(d, M_refine, nbits_per_idx_refine),
+ k_factor(4) {
+ by_residual = true;
+ refine_pq.cp.max_points_per_centroid = 1000;
+}
+
+IndexIVFPQR::IndexIVFPQR() : k_factor(1) {
+ by_residual = true;
+ refine_pq.cp.max_points_per_centroid = 1000;
+}
+
+void IndexIVFPQR::reset() {
+ IndexIVFPQ::reset();
+ refine_codes.clear();
+}
+
+void IndexIVFPQR::train_encoder(idx_t n, const float* x, const idx_t* assign) {
+ IndexIVFPQ::train_encoder(n, x, assign);
+ if (verbose) {
+ printf("training %zdx%zd 2nd level PQ quantizer on %" PRId64
+ " %dD-vectors\n",
+ refine_pq.M,
+ refine_pq.ksub,
+ n,
+ d);
+ }
+ refine_pq.cp.verbose = verbose;
+
+ // 2nd level residual
+ std::vector<float> residual_2(n * d);
+ std::vector<uint8_t> train_codes(pq.code_size * n);
+ pq.compute_codes(x, train_codes.data(), n);
+
+ for (idx_t i = 0; i < n; i++) {
+ const float* xx = x + i * d;
+ float* res = residual_2.data() + i * d;
+ pq.decode(train_codes.data() + i * pq.code_size, res);
+ for (int j = 0; j < d; j++) {
+ res[j] = xx[j] - res[j];
+ }
+ }
+
+ refine_pq.train(n, residual_2.data());
+}
+
+idx_t IndexIVFPQR::train_encoder_num_vectors() const {
+ return std::max(
+ pq.cp.max_points_per_centroid * pq.ksub,
+ refine_pq.cp.max_points_per_centroid * refine_pq.ksub);
+}
+
+void IndexIVFPQR::add_with_ids(idx_t n, const float* x, const idx_t* xids) {
+ add_core(n, x, xids, nullptr);
+}
+
+void IndexIVFPQR::add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* /*inverted_list_context*/) {
+ std::unique_ptr<float[]> residual_2(new float[n * d]);
+
+ idx_t n0 = ntotal;
+
+ add_core_o(n, x, xids, residual_2.get(), precomputed_idx);
+
+ refine_codes.resize(ntotal * refine_pq.code_size);
+
+ refine_pq.compute_codes(
+ residual_2.get(), &refine_codes[n0 * refine_pq.code_size], n);
+}
+#define TIC t0 = get_cycles()
+#define TOC get_cycles() - t0
+
+void IndexIVFPQR::search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* idx,
+ const float* L1_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* stats) const {
+ uint64_t t0;
+ TIC;
+ size_t k_coarse = long(k * k_factor);
+ std::unique_ptr<idx_t[]> coarse_labels(new idx_t[k_coarse * n]);
+ {
+ // query with quantizer levels 1 and 2.
+ std::unique_ptr<float[]> coarse_distances(new float[k_coarse * n]);
+
+ IndexIVFPQ::search_preassigned(
+ n,
+ x,
+ k_coarse,
+ idx,
+ L1_dis,
+ coarse_distances.get(),
+ coarse_labels.get(),
+ true,
+ params);
+ }
+
+ indexIVFPQ_stats.search_cycles += TOC;
+
+ TIC;
+
+ // 3rd level refinement
+ size_t n_refine = 0;
+#pragma omp parallel reduction(+ : n_refine)
+ {
+ // tmp buffers
+ std::unique_ptr<float[]> residual_1(new float[2 * d]);
+ float* residual_2 = residual_1.get() + d;
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const float* xq = x + i * d;
+ const idx_t* shortlist = coarse_labels.get() + k_coarse * i;
+ float* heap_sim = distances + k * i;
+ idx_t* heap_ids = labels + k * i;
+ maxheap_heapify(k, heap_sim, heap_ids);
+
+ for (int j = 0; j < k_coarse; j++) {
+ idx_t sl = shortlist[j];
+
+ if (sl == -1)
+ continue;
+
+ int list_no = lo_listno(sl);
+ int ofs = lo_offset(sl);
+
+ assert(list_no >= 0 && list_no < nlist);
+ assert(ofs >= 0 && ofs < invlists->list_size(list_no));
+
+ // 1st level residual
+ quantizer->compute_residual(xq, residual_1.get(), list_no);
+
+ // 2nd level residual
+ const uint8_t* l2code = invlists->get_single_code(list_no, ofs);
+
+ pq.decode(l2code, residual_2);
+ for (int l = 0; l < d; l++)
+ residual_2[l] = residual_1[l] - residual_2[l];
+
+ // 3rd level residual's approximation
+ idx_t id = invlists->get_single_id(list_no, ofs);
+ assert(0 <= id && id < ntotal);
+ refine_pq.decode(
+ &refine_codes[id * refine_pq.code_size],
+ residual_1.get());
+
+ float dis = fvec_L2sqr(residual_1.get(), residual_2, d);
+
+ if (dis < heap_sim[0]) {
+ idx_t id_or_pair = store_pairs ? sl : id;
+ maxheap_replace_top(k, heap_sim, heap_ids, dis, id_or_pair);
+ }
+ n_refine++;
+ }
+ maxheap_reorder(k, heap_sim, heap_ids);
+ }
+ }
+ indexIVFPQ_stats.nrefine += n_refine;
+ indexIVFPQ_stats.refine_cycles += TOC;
+}
+
+void IndexIVFPQR::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ IndexIVFPQ::reconstruct_from_offset(list_no, offset, recons);
+
+ idx_t id = invlists->get_single_id(list_no, offset);
+ assert(0 <= id && id < ntotal);
+
+ std::vector<float> r3(d);
+ refine_pq.decode(&refine_codes[id * refine_pq.code_size], r3.data());
+ for (int i = 0; i < d; ++i) {
+ recons[i] += r3[i];
+ }
+}
+
+void IndexIVFPQR::merge_from(Index& otherIndex, idx_t add_id) {
+ IndexIVFPQR* other = dynamic_cast<IndexIVFPQR*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+
+ IndexIVF::merge_from(otherIndex, add_id);
+
+ refine_codes.insert(
+ refine_codes.end(),
+ other->refine_codes.begin(),
+ other->refine_codes.end());
+ other->refine_codes.clear();
+}
+
+size_t IndexIVFPQR::remove_ids(const IDSelector& /*sel*/) {
+ FAISS_THROW_MSG("not implemented");
+ return 0;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQR.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQR.h
new file mode 100644
index 0000000..1c61d6c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFPQR.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/IndexIVFPQ.h>
+
+namespace faiss {
+
+/** Index with an additional level of PQ refinement */
+struct IndexIVFPQR : IndexIVFPQ {
+ ProductQuantizer refine_pq; ///< 3rd level quantizer
+ std::vector<uint8_t> refine_codes; ///< corresponding codes
+
+ /// factor between k requested in search and the k requested from the IVFPQ
+ float k_factor;
+
+ IndexIVFPQR(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ size_t M,
+ size_t nbits_per_idx,
+ size_t M_refine,
+ size_t nbits_per_idx_refine);
+
+ void reset() override;
+
+ size_t remove_ids(const IDSelector& sel) override;
+
+ /// trains the two product quantizers
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ idx_t train_encoder_num_vectors() const override;
+
+ void add_with_ids(idx_t n, const float* x, const idx_t* xids) override;
+
+ /// same as add_with_ids, but optionally use the precomputed list ids
+ void add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context = nullptr) override;
+
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ void merge_from(Index& otherIndex, idx_t add_id) override;
+
+ void search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ IndexIVFPQR();
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFRaBitQ.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFRaBitQ.cpp
new file mode 100644
index 0000000..5cfab63
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFRaBitQ.cpp
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFRaBitQ.h>
+
+#include <omp.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/RaBitQuantizer.h>
+
+namespace faiss {
+
+IndexIVFRaBitQ::IndexIVFRaBitQ(
+ Index* quantizer,
+ const size_t d,
+ const size_t nlist,
+ MetricType metric)
+ : IndexIVF(quantizer, d, nlist, 0, metric), rabitq(d, metric) {
+ code_size = rabitq.code_size;
+ invlists->code_size = code_size;
+ is_trained = false;
+
+ by_residual = true;
+}
+
+IndexIVFRaBitQ::IndexIVFRaBitQ() {
+ by_residual = true;
+}
+
+void IndexIVFRaBitQ::train_encoder(
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ rabitq.train(n, x);
+}
+
+void IndexIVFRaBitQ::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ size_t coarse_size = include_listnos ? coarse_code_size() : 0;
+ memset(codes, 0, (code_size + coarse_size) * n);
+
+#pragma omp parallel if (n > 1000)
+ {
+ std::vector<float> centroid(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ int64_t list_no = list_nos[i];
+ if (list_no >= 0) {
+ const float* xi = x + i * d;
+ uint8_t* code = codes + i * (code_size + coarse_size);
+
+ // both by_residual and !by_residual lead to the same code
+ quantizer->reconstruct(list_no, centroid.data());
+ rabitq.compute_codes_core(
+ xi, code + coarse_size, 1, centroid.data());
+
+ if (coarse_size) {
+ encode_listno(list_no, code);
+ }
+ }
+ }
+ }
+}
+
+void IndexIVFRaBitQ::add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context) {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ DirectMapAdd dm_add(direct_map, n, xids);
+
+#pragma omp parallel
+ {
+ std::vector<uint8_t> one_code(code_size);
+ std::vector<float> centroid(d);
+
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ // each thread takes care of a subset of lists
+ for (size_t i = 0; i < n; i++) {
+ int64_t list_no = precomputed_idx[i];
+ if (list_no >= 0 && list_no % nt == rank) {
+ int64_t id = xids ? xids[i] : ntotal + i;
+
+ const float* xi = x + i * d;
+
+ // both by_residual and !by_residual lead to the same code
+ quantizer->reconstruct(list_no, centroid.data());
+ rabitq.compute_codes_core(
+ xi, one_code.data(), 1, centroid.data());
+
+ size_t ofs = invlists->add_entry(
+ list_no, id, one_code.data(), inverted_list_context);
+
+ dm_add.add(i, list_no, ofs);
+
+ } else if (rank == 0 && list_no == -1) {
+ dm_add.add(i, -1, 0);
+ }
+ }
+ }
+
+ ntotal += n;
+}
+
+struct RaBitInvertedListScanner : InvertedListScanner {
+ const IndexIVFRaBitQ& ivf_rabitq;
+
+ std::vector<float> reconstructed_centroid;
+ std::vector<float> query_vector;
+
+ std::unique_ptr<FlatCodesDistanceComputer> dc;
+
+ uint8_t qb = 0;
+
+ RaBitInvertedListScanner(
+ const IndexIVFRaBitQ& ivf_rabitq_in,
+ bool store_pairs = false,
+ const IDSelector* sel = nullptr,
+ uint8_t qb_in = 0)
+ : InvertedListScanner(store_pairs, sel),
+ ivf_rabitq{ivf_rabitq_in},
+ qb{qb_in} {
+ keep_max = is_similarity_metric(ivf_rabitq.metric_type);
+ code_size = ivf_rabitq.code_size;
+ }
+
+ /// from now on we handle this query.
+ void set_query(const float* query_vector_in) override {
+ query_vector.assign(query_vector_in, query_vector_in + ivf_rabitq.d);
+
+ internal_try_setup_dc();
+ }
+
+ /// following codes come from this inverted list
+ void set_list(idx_t list_no, float coarse_dis) override {
+ this->list_no = list_no;
+
+ reconstructed_centroid.resize(ivf_rabitq.d);
+ ivf_rabitq.quantizer->reconstruct(
+ list_no, reconstructed_centroid.data());
+
+ internal_try_setup_dc();
+ }
+
+ /// compute a single query-to-code distance
+ float distance_to_code(const uint8_t* code) const override {
+ return dc->distance_to_code(code);
+ }
+
+ void internal_try_setup_dc() {
+ if (!query_vector.empty() && !reconstructed_centroid.empty()) {
+ // both query_vector and centroid are available!
+ // set up DistanceComputer
+ dc.reset(ivf_rabitq.rabitq.get_distance_computer(
+ qb, reconstructed_centroid.data()));
+
+ dc->set_query(query_vector.data());
+ }
+ }
+};
+
+InvertedListScanner* IndexIVFRaBitQ::get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* search_params_in) const {
+ uint8_t used_qb = qb;
+ if (search_params_in != nullptr) {
+ const auto* search_params =
+ dynamic_cast<const IVFRaBitQSearchParameters*>(
+ search_params_in);
+ FAISS_THROW_IF_NOT_MSG(search_params, "invalid search params");
+
+ used_qb = search_params->qb;
+ }
+
+ return new RaBitInvertedListScanner(*this, store_pairs, sel, used_qb);
+}
+
+void IndexIVFRaBitQ::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ const uint8_t* code = invlists->get_single_code(list_no, offset);
+
+ std::vector<float> centroid(d);
+ quantizer->reconstruct(list_no, centroid.data());
+
+ rabitq.decode_core(code, recons, 1, centroid.data());
+}
+
+void IndexIVFRaBitQ::sa_decode(idx_t n, const uint8_t* codes, float* x) const {
+ size_t coarse_size = coarse_code_size();
+
+#pragma omp parallel
+ {
+ std::vector<float> centroid(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + i * (code_size + coarse_size);
+ int64_t list_no = decode_listno(code);
+ float* xi = x + i * d;
+
+ quantizer->reconstruct(list_no, centroid.data());
+ rabitq.decode_core(code + coarse_size, xi, 1, centroid.data());
+ }
+ }
+}
+
+struct IVFRaBitDistanceComputer : DistanceComputer {
+ const float* q = nullptr;
+ const IndexIVFRaBitQ* parent = nullptr;
+
+ void set_query(const float* x) override;
+
+ float operator()(idx_t i) override;
+
+ float symmetric_dis(idx_t i, idx_t j) override;
+};
+
+void IVFRaBitDistanceComputer::set_query(const float* x) {
+ q = x;
+}
+
+float IVFRaBitDistanceComputer::operator()(idx_t i) {
+ // find the appropriate list
+ idx_t lo = parent->direct_map.get(i);
+ uint64_t list_no = lo_listno(lo);
+ uint64_t offset = lo_offset(lo);
+
+ const uint8_t* code = parent->invlists->get_single_code(list_no, offset);
+
+ // ok, we know the appropriate cluster that we need
+ std::vector<float> centroid(parent->d);
+ parent->quantizer->reconstruct(list_no, centroid.data());
+
+ // compute the distance
+ float distance = 0;
+
+ std::unique_ptr<FlatCodesDistanceComputer> dc(
+ parent->rabitq.get_distance_computer(parent->qb, centroid.data()));
+ dc->set_query(q);
+ distance = dc->distance_to_code(code);
+
+ // deallocate
+ parent->invlists->release_codes(list_no, code);
+
+ // done
+ return distance;
+}
+
+float IVFRaBitDistanceComputer::symmetric_dis(idx_t i, idx_t j) {
+ FAISS_THROW_MSG("Not implemented");
+}
+
+DistanceComputer* IndexIVFRaBitQ::get_distance_computer() const {
+ IVFRaBitDistanceComputer* dc = new IVFRaBitDistanceComputer;
+ dc->parent = this;
+ return dc;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFRaBitQ.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFRaBitQ.h
new file mode 100644
index 0000000..ca42dfc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFRaBitQ.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/Index.h>
+#include <faiss/IndexIVF.h>
+
+#include <faiss/impl/RaBitQuantizer.h>
+
+namespace faiss {
+
+struct IVFRaBitQSearchParameters : IVFSearchParameters {
+ uint8_t qb = 0;
+};
+
+// * by_residual is true, just by design
+struct IndexIVFRaBitQ : IndexIVF {
+ RaBitQuantizer rabitq;
+
+ // the default number of bits to quantize a query with.
+ // use '0' to disable quantization and use raw fp32 values.
+ uint8_t qb = 0;
+
+ IndexIVFRaBitQ(
+ Index* quantizer,
+ const size_t d,
+ const size_t nlist,
+ MetricType metric = METRIC_L2);
+
+ IndexIVFRaBitQ();
+
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos = false) const override;
+
+ void add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context = nullptr) override;
+
+ InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* params) const override;
+
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ // unfortunately
+ DistanceComputer* get_distance_computer() const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFSpectralHash.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFSpectralHash.cpp
new file mode 100644
index 0000000..a4f2325
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFSpectralHash.cpp
@@ -0,0 +1,341 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexIVFSpectralHash.h>
+
+#include <algorithm>
+#include <cstdint>
+#include <memory>
+
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/VectorTransform.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+
+namespace faiss {
+
+IndexIVFSpectralHash::IndexIVFSpectralHash(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ int nbit,
+ float period)
+ : IndexIVF(quantizer, d, nlist, (nbit + 7) / 8, METRIC_L2),
+ nbit(nbit),
+ period(period) {
+ RandomRotationMatrix* rr = new RandomRotationMatrix(d, nbit);
+ rr->init(1234);
+ vt = rr;
+ is_trained = false;
+ by_residual = false;
+}
+
+IndexIVFSpectralHash::IndexIVFSpectralHash() : IndexIVF() {
+ by_residual = false;
+}
+
+IndexIVFSpectralHash::~IndexIVFSpectralHash() {
+ if (own_fields) {
+ delete vt;
+ }
+}
+
+namespace {
+
+float median(size_t n, float* x) {
+ std::sort(x, x + n);
+ if (n % 2 == 1) {
+ return x[n / 2];
+ } else {
+ return (x[n / 2 - 1] + x[n / 2]) / 2;
+ }
+}
+
+} // namespace
+
+void IndexIVFSpectralHash::train_encoder(
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ if (!vt->is_trained) {
+ vt->train(n, x);
+ }
+ FAISS_THROW_IF_NOT(!by_residual);
+
+ if (threshold_type == Thresh_global) {
+ // nothing to do
+ return;
+ } else if (
+ threshold_type == Thresh_centroid ||
+ threshold_type == Thresh_centroid_half) {
+ // convert all centroids with vt
+ std::vector<float> centroids(nlist * d);
+ quantizer->reconstruct_n(0, nlist, centroids.data());
+ trained.resize(nlist * nbit);
+ vt->apply_noalloc(nlist, centroids.data(), trained.data());
+ if (threshold_type == Thresh_centroid_half) {
+ for (size_t i = 0; i < nlist * nbit; i++) {
+ trained[i] -= 0.25 * period;
+ }
+ }
+ return;
+ }
+ // otherwise train medians
+
+ // assign
+ std::unique_ptr<idx_t[]> idx(new idx_t[n]);
+ quantizer->assign(n, x, idx.get());
+
+ std::vector<size_t> sizes(nlist + 1);
+ for (size_t i = 0; i < n; i++) {
+ FAISS_THROW_IF_NOT(idx[i] >= 0);
+ sizes[idx[i]]++;
+ }
+
+ size_t ofs = 0;
+ for (int j = 0; j < nlist; j++) {
+ size_t o0 = ofs;
+ ofs += sizes[j];
+ sizes[j] = o0;
+ }
+
+ // transform
+ std::unique_ptr<float[]> xt(vt->apply(n, x));
+
+ // transpose + reorder
+ std::unique_ptr<float[]> xo(new float[n * nbit]);
+
+ for (size_t i = 0; i < n; i++) {
+ size_t idest = sizes[idx[i]]++;
+ for (size_t j = 0; j < nbit; j++) {
+ xo[idest + n * j] = xt[i * nbit + j];
+ }
+ }
+
+ trained.resize(n * nbit);
+ // compute medians
+#pragma omp for
+ for (int i = 0; i < nlist; i++) {
+ size_t i0 = i == 0 ? 0 : sizes[i - 1];
+ size_t i1 = sizes[i];
+ for (int j = 0; j < nbit; j++) {
+ float* xoi = xo.get() + i0 + n * j;
+ if (i0 == i1) { // nothing to train
+ trained[i * nbit + j] = 0.0;
+ } else if (i1 == i0 + 1) {
+ trained[i * nbit + j] = xoi[0];
+ } else {
+ trained[i * nbit + j] = median(i1 - i0, xoi);
+ }
+ }
+ }
+}
+
+namespace {
+
+void binarize_with_freq(
+ size_t nbit,
+ float freq,
+ const float* x,
+ const float* c,
+ uint8_t* codes) {
+ memset(codes, 0, (nbit + 7) / 8);
+ for (size_t i = 0; i < nbit; i++) {
+ float xf = (x[i] - c[i]);
+ int64_t xi = int64_t(floor(xf * freq));
+ int64_t bit = xi & 1;
+ codes[i >> 3] |= bit << (i & 7);
+ }
+}
+
+} // namespace
+
+void IndexIVFSpectralHash::encode_vectors(
+ idx_t n,
+ const float* x_in,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ FAISS_THROW_IF_NOT(is_trained);
+ FAISS_THROW_IF_NOT(!by_residual);
+ float freq = 2.0 / period;
+ size_t coarse_size = include_listnos ? coarse_code_size() : 0;
+
+ // transform with vt
+ std::unique_ptr<float[]> x(vt->apply(n, x_in));
+
+ std::vector<float> zero(nbit);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ int64_t list_no = list_nos[i];
+ uint8_t* code = codes + i * (code_size + coarse_size);
+
+ if (list_no >= 0) {
+ if (coarse_size) {
+ encode_listno(list_no, code);
+ }
+ const float* c;
+
+ if (threshold_type == Thresh_global) {
+ c = zero.data();
+ } else {
+ c = trained.data() + list_no * nbit;
+ }
+ binarize_with_freq(
+ nbit, freq, x.get() + i * nbit, c, code + coarse_size);
+ } else {
+ memset(code, 0, code_size + coarse_size);
+ }
+ }
+}
+
+namespace {
+
+template <class HammingComputer>
+struct IVFScanner : InvertedListScanner {
+ // copied from index structure
+ const IndexIVFSpectralHash* index;
+ size_t nbit;
+
+ float period, freq;
+ std::vector<float> q;
+ std::vector<float> zero;
+ std::vector<uint8_t> qcode;
+ HammingComputer hc;
+
+ IVFScanner(const IndexIVFSpectralHash* index, bool store_pairs)
+ : index(index),
+ nbit(index->nbit),
+ period(index->period),
+ freq(2.0 / index->period),
+ q(nbit),
+ zero(nbit),
+ qcode(index->code_size),
+ hc(qcode.data(), index->code_size) {
+ this->store_pairs = store_pairs;
+ this->code_size = index->code_size;
+ this->keep_max = is_similarity_metric(index->metric_type);
+ }
+
+ void set_query(const float* query) override {
+ FAISS_THROW_IF_NOT(query);
+ FAISS_THROW_IF_NOT(q.size() == nbit);
+ index->vt->apply_noalloc(1, query, q.data());
+
+ if (index->threshold_type == IndexIVFSpectralHash::Thresh_global) {
+ binarize_with_freq(nbit, freq, q.data(), zero.data(), qcode.data());
+ hc.set(qcode.data(), code_size);
+ }
+ }
+
+ void set_list(idx_t list_no, float /*coarse_dis*/) override {
+ this->list_no = list_no;
+ if (index->threshold_type != IndexIVFSpectralHash::Thresh_global) {
+ const float* c = index->trained.data() + list_no * nbit;
+ binarize_with_freq(nbit, freq, q.data(), c, qcode.data());
+ hc.set(qcode.data(), code_size);
+ }
+ }
+
+ float distance_to_code(const uint8_t* code) const final {
+ return hc.hamming(code);
+ }
+
+ size_t scan_codes(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* simi,
+ idx_t* idxi,
+ size_t k) const override {
+ size_t nup = 0;
+ for (size_t j = 0; j < list_size; j++) {
+ float dis = hc.hamming(codes);
+
+ if (dis < simi[0]) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ maxheap_replace_top(k, simi, idxi, dis, id);
+ nup++;
+ }
+ codes += code_size;
+ }
+ return nup;
+ }
+
+ void scan_codes_range(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& res) const override {
+ for (size_t j = 0; j < list_size; j++) {
+ float dis = hc.hamming(codes);
+ if (dis < radius) {
+ int64_t id = store_pairs ? lo_build(list_no, j) : ids[j];
+ res.add(dis, id);
+ }
+ codes += code_size;
+ }
+ }
+};
+
+struct BuildScanner {
+ using T = InvertedListScanner*;
+
+ template <class HammingComputer>
+ static T f(const IndexIVFSpectralHash* index, bool store_pairs) {
+ return new IVFScanner<HammingComputer>(index, store_pairs);
+ }
+};
+
+} // anonymous namespace
+
+InvertedListScanner* IndexIVFSpectralHash::get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters*) const {
+ FAISS_THROW_IF_NOT(!sel);
+ BuildScanner bs;
+ return dispatch_HammingComputer(code_size, bs, this, store_pairs);
+}
+
+void IndexIVFSpectralHash::replace_vt(VectorTransform* vt_in, bool own) {
+ FAISS_THROW_IF_NOT(vt_in->d_out == nbit);
+ FAISS_THROW_IF_NOT(vt_in->d_in == d);
+ if (own_fields) {
+ delete vt;
+ }
+ vt = vt_in;
+ threshold_type = Thresh_global;
+ is_trained = quantizer->is_trained && quantizer->ntotal == nlist &&
+ vt->is_trained;
+ own_fields = own;
+}
+
+/*
+ Check that the encoder is a single vector transform followed by a LSH
+ that just does thresholding.
+ If this is not the case, the linear transform + threhsolds of the IndexLSH
+ should be merged into the VectorTransform (which is feasible).
+*/
+
+void IndexIVFSpectralHash::replace_vt(IndexPreTransform* encoder, bool own) {
+ FAISS_THROW_IF_NOT(encoder->chain.size() == 1);
+ auto sub_index = dynamic_cast<IndexLSH*>(encoder->index);
+ FAISS_THROW_IF_NOT_MSG(sub_index, "final index should be LSH");
+ FAISS_THROW_IF_NOT(sub_index->nbits == nbit);
+ FAISS_THROW_IF_NOT(!sub_index->rotate_data);
+ FAISS_THROW_IF_NOT(!sub_index->train_thresholds);
+ replace_vt(encoder->chain[0], own);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFSpectralHash.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFSpectralHash.h
new file mode 100644
index 0000000..77541bc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexIVFSpectralHash.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_IVFSH_H
+#define FAISS_INDEX_IVFSH_H
+
+#include <vector>
+
+#include <faiss/IndexIVF.h>
+
+namespace faiss {
+
+struct VectorTransform;
+struct IndexPreTransform;
+
+/** Inverted list that stores binary codes of size nbit. Before the
+ * binary conversion, the dimension of the vectors is transformed from
+ * dim d into dim nbit by vt (a random rotation by default).
+ *
+ * Each coordinate is subtracted from a value determined by
+ * threshold_type, and split into intervals of size period. Half of
+ * the interval is a 0 bit, the other half a 1.
+ *
+ */
+struct IndexIVFSpectralHash : IndexIVF {
+ /// transformation from d to nbit dim
+ VectorTransform* vt = nullptr;
+ /// own the vt
+ bool own_fields = true;
+
+ /// nb of bits of the binary signature
+ int nbit = 0;
+ /// interval size for 0s and 1s
+ float period = 0;
+
+ enum ThresholdType {
+ Thresh_global, ///< global threshold at 0
+ Thresh_centroid, ///< compare to centroid
+ Thresh_centroid_half, ///< central interval around centroid
+ Thresh_median ///< median of training set
+ };
+ ThresholdType threshold_type = Thresh_global;
+
+ /// Trained threshold.
+ /// size nlist * nbit or 0 if Thresh_global
+ std::vector<float> trained;
+
+ IndexIVFSpectralHash(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ int nbit,
+ float period);
+
+ IndexIVFSpectralHash();
+
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos = false) const override;
+
+ InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* params) const override;
+
+ /** replace the vector transform for an empty (and possibly untrained) index
+ */
+ void replace_vt(VectorTransform* vt, bool own = false);
+
+ /** convenience function to get the VT from an index constucted by an
+ * index_factory (should end in "LSH") */
+ void replace_vt(IndexPreTransform* index, bool own = false);
+
+ ~IndexIVFSpectralHash() override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLSH.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLSH.cpp
new file mode 100644
index 0000000..a2d29f8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLSH.cpp
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexLSH.h>
+
+#include <cstdio>
+#include <cstring>
+
+#include <algorithm>
+#include <memory>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+
+namespace faiss {
+
+/***************************************************************
+ * IndexLSH
+ ***************************************************************/
+
+IndexLSH::IndexLSH(idx_t d, int nbits, bool rotate_data, bool train_thresholds)
+ : IndexFlatCodes((nbits + 7) / 8, d),
+ nbits(nbits),
+ rotate_data(rotate_data),
+ train_thresholds(train_thresholds),
+ rrot(d, nbits) {
+ is_trained = !train_thresholds;
+
+ if (rotate_data) {
+ rrot.init(5);
+ } else {
+ FAISS_THROW_IF_NOT(d >= nbits);
+ }
+}
+
+IndexLSH::IndexLSH() : nbits(0), rotate_data(false), train_thresholds(false) {}
+
+const float* IndexLSH::apply_preprocess(idx_t n, const float* x) const {
+ float* xt = nullptr;
+ if (rotate_data) {
+ // also applies bias if exists
+ xt = rrot.apply(n, x);
+ } else if (d != nbits) {
+ assert(nbits < d);
+ xt = new float[nbits * n];
+ float* xp = xt;
+ for (idx_t i = 0; i < n; i++) {
+ const float* xl = x + i * d;
+ for (int j = 0; j < nbits; j++)
+ *xp++ = xl[j];
+ }
+ }
+
+ if (train_thresholds) {
+ if (xt == nullptr) {
+ xt = new float[nbits * n];
+ memcpy(xt, x, sizeof(*x) * n * nbits);
+ }
+
+ float* xp = xt;
+ for (idx_t i = 0; i < n; i++)
+ for (int j = 0; j < nbits; j++)
+ *xp++ -= thresholds[j];
+ }
+
+ return xt ? xt : x;
+}
+
+void IndexLSH::train(idx_t n, const float* x) {
+ if (train_thresholds) {
+ thresholds.resize(nbits);
+ train_thresholds = false;
+ const float* xt = apply_preprocess(n, x);
+ std::unique_ptr<const float[]> del(xt == x ? nullptr : xt);
+ train_thresholds = true;
+
+ std::unique_ptr<float[]> transposed_x(new float[n * nbits]);
+
+ for (idx_t i = 0; i < n; i++)
+ for (idx_t j = 0; j < nbits; j++)
+ transposed_x[j * n + i] = xt[i * nbits + j];
+
+ for (idx_t i = 0; i < nbits; i++) {
+ float* xi = transposed_x.get() + i * n;
+ // std::nth_element
+ std::sort(xi, xi + n);
+ if (n % 2 == 1)
+ thresholds[i] = xi[n / 2];
+ else
+ thresholds[i] = (xi[n / 2 - 1] + xi[n / 2]) / 2;
+ }
+ }
+ is_trained = true;
+}
+
+void IndexLSH::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+ const float* xt = apply_preprocess(n, x);
+ std::unique_ptr<const float[]> del(xt == x ? nullptr : xt);
+
+ std::unique_ptr<uint8_t[]> qcodes(new uint8_t[n * code_size]);
+
+ fvecs2bitvecs(xt, qcodes.get(), nbits, n);
+
+ std::unique_ptr<int[]> idistances(new int[n * k]);
+
+ int_maxheap_array_t res = {size_t(n), size_t(k), labels, idistances.get()};
+
+ hammings_knn_hc(&res, qcodes.get(), codes.data(), ntotal, code_size, true);
+
+ // convert distances to floats
+ for (int i = 0; i < k * n; i++)
+ distances[i] = idistances[i];
+}
+
+void IndexLSH::transfer_thresholds(LinearTransform* vt) {
+ if (!train_thresholds)
+ return;
+ FAISS_THROW_IF_NOT(nbits == vt->d_out);
+ if (!vt->have_bias) {
+ vt->b.resize(nbits, 0);
+ vt->have_bias = true;
+ }
+ for (int i = 0; i < nbits; i++)
+ vt->b[i] -= thresholds[i];
+ train_thresholds = false;
+ thresholds.clear();
+}
+
+void IndexLSH::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ FAISS_THROW_IF_NOT(is_trained);
+ const float* xt = apply_preprocess(n, x);
+ std::unique_ptr<const float[]> del(xt == x ? nullptr : xt);
+ fvecs2bitvecs(xt, bytes, nbits, n);
+}
+
+void IndexLSH::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ float* xt = x;
+ std::unique_ptr<float[]> del;
+ if (rotate_data || nbits != d) {
+ xt = new float[n * nbits];
+ del.reset(xt);
+ }
+ bitvecs2fvecs(bytes, xt, nbits, n);
+
+ if (train_thresholds) {
+ float* xp = xt;
+ for (idx_t i = 0; i < n; i++) {
+ for (int j = 0; j < nbits; j++) {
+ *xp++ += thresholds[j];
+ }
+ }
+ }
+
+ if (rotate_data) {
+ rrot.reverse_transform(n, xt, x);
+ } else if (nbits != d) {
+ for (idx_t i = 0; i < n; i++) {
+ memcpy(x + i * d, xt + i * nbits, nbits * sizeof(xt[0]));
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLSH.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLSH.h
new file mode 100644
index 0000000..cc3bbcc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLSH.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef INDEX_LSH_H
+#define INDEX_LSH_H
+
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/VectorTransform.h>
+
+namespace faiss {
+
+/** The sign of each vector component is put in a binary signature */
+struct IndexLSH : IndexFlatCodes {
+ int nbits; ///< nb of bits per vector
+ bool rotate_data; ///< whether to apply a random rotation to input
+ bool train_thresholds; ///< whether we train thresholds or use 0
+
+ RandomRotationMatrix rrot; ///< optional random rotation
+
+ std::vector<float> thresholds; ///< thresholds to compare with
+
+ IndexLSH(
+ idx_t d,
+ int nbits,
+ bool rotate_data = true,
+ bool train_thresholds = false);
+
+ /** Preprocesses and resizes the input to the size required to
+ * binarize the data
+ *
+ * @param x input vectors, size n * d
+ * @return output vectors, size n * bits. May be the same pointer
+ * as x, otherwise it should be deleted by the caller
+ */
+ const float* apply_preprocess(idx_t n, const float* x) const;
+
+ void train(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /// transfer the thresholds to a pre-processing stage (and unset
+ /// train_thresholds)
+ void transfer_thresholds(LinearTransform* vt);
+
+ ~IndexLSH() override {}
+
+ IndexLSH();
+
+ /* standalone codec interface.
+ *
+ * The vectors are decoded to +/- 1 (not 0, 1) */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLattice.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLattice.cpp
new file mode 100644
index 0000000..b550e8d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLattice.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexLattice.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h> // for the bitstring routines
+
+namespace faiss {
+
+IndexLattice::IndexLattice(idx_t d, int nsq, int scale_nbit, int r2)
+ : IndexFlatCodes(0, d, METRIC_L2),
+ nsq(nsq),
+ dsq(d / nsq),
+ zn_sphere_codec(dsq, r2),
+ scale_nbit(scale_nbit) {
+ FAISS_THROW_IF_NOT(d % nsq == 0);
+
+ lattice_nbit = 0;
+ while (!(((uint64_t)1 << lattice_nbit) >= zn_sphere_codec.nv)) {
+ lattice_nbit++;
+ }
+
+ int total_nbit = (lattice_nbit + scale_nbit) * nsq;
+
+ code_size = (total_nbit + 7) / 8;
+
+ is_trained = false;
+}
+
+void IndexLattice::train(idx_t n, const float* x) {
+ // compute ranges per sub-block
+ trained.resize(nsq * 2);
+ float* mins = trained.data();
+ float* maxs = trained.data() + nsq;
+ for (int sq = 0; sq < nsq; sq++) {
+ mins[sq] = HUGE_VAL;
+ maxs[sq] = -1;
+ }
+
+ for (idx_t i = 0; i < n; i++) {
+ for (int sq = 0; sq < nsq; sq++) {
+ float norm2 = fvec_norm_L2sqr(x + i * d + sq * dsq, dsq);
+ if (norm2 > maxs[sq])
+ maxs[sq] = norm2;
+ if (norm2 < mins[sq])
+ mins[sq] = norm2;
+ }
+ }
+
+ for (int sq = 0; sq < nsq; sq++) {
+ mins[sq] = sqrtf(mins[sq]);
+ maxs[sq] = sqrtf(maxs[sq]);
+ }
+
+ is_trained = true;
+}
+
+/* The standalone codec interface */
+size_t IndexLattice::sa_code_size() const {
+ return code_size;
+}
+
+void IndexLattice::sa_encode(idx_t n, const float* x, uint8_t* codes) const {
+ const float* mins = trained.data();
+ const float* maxs = mins + nsq;
+ int64_t sc = int64_t(1) << scale_nbit;
+
+#pragma omp parallel for
+ for (idx_t i = 0; i < n; i++) {
+ BitstringWriter wr(codes + i * code_size, code_size);
+ const float* xi = x + i * d;
+ for (int j = 0; j < nsq; j++) {
+ float nj = (sqrtf(fvec_norm_L2sqr(xi, dsq)) - mins[j]) * sc /
+ (maxs[j] - mins[j]);
+ if (nj < 0)
+ nj = 0;
+ if (nj >= sc)
+ nj = sc - 1;
+ wr.write((int64_t)nj, scale_nbit);
+ wr.write(zn_sphere_codec.encode(xi), lattice_nbit);
+ xi += dsq;
+ }
+ }
+}
+
+void IndexLattice::sa_decode(idx_t n, const uint8_t* codes, float* x) const {
+ const float* mins = trained.data();
+ const float* maxs = mins + nsq;
+ float sc = int64_t(1) << scale_nbit;
+ float r = sqrtf(zn_sphere_codec.r2);
+
+#pragma omp parallel for
+ for (idx_t i = 0; i < n; i++) {
+ BitstringReader rd(codes + i * code_size, code_size);
+ float* xi = x + i * d;
+ for (int j = 0; j < nsq; j++) {
+ float norm =
+ (rd.read(scale_nbit) + 0.5) * (maxs[j] - mins[j]) / sc +
+ mins[j];
+ norm /= r;
+ zn_sphere_codec.decode(rd.read(lattice_nbit), xi);
+ for (int l = 0; l < dsq; l++) {
+ xi[l] *= norm;
+ }
+ xi += dsq;
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLattice.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLattice.h
new file mode 100644
index 0000000..beec8da
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexLattice.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/impl/lattice_Zn.h>
+
+namespace faiss {
+
+/** Index that encodes a vector with a series of Zn lattice quantizers
+ */
+struct IndexLattice : IndexFlatCodes {
+ /// number of sub-vectors
+ int nsq;
+ /// dimension of sub-vectors
+ size_t dsq;
+
+ /// the lattice quantizer
+ ZnSphereCodecAlt zn_sphere_codec;
+
+ /// nb bits used to encode the scale, per subvector
+ int scale_nbit, lattice_nbit;
+
+ /// mins and maxes of the vector norms, per subquantizer
+ std::vector<float> trained;
+
+ IndexLattice(idx_t d, int nsq, int scale_nbit, int r2);
+
+ void train(idx_t n, const float* x) override;
+
+ /* The standalone codec interface */
+ size_t sa_code_size() const override;
+
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNNDescent.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNNDescent.cpp
new file mode 100644
index 0000000..696a979
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNNDescent.cpp
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexNNDescent.h>
+
+#include <omp.h>
+
+#include <cinttypes>
+#include <cstdio>
+#include <cstdlib>
+
+#include <queue>
+#include <unordered_set>
+
+#ifdef __SSE__
+#endif
+
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+
+extern "C" {
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+using storage_idx_t = NNDescent::storage_idx_t;
+
+/**************************************************************
+ * add / search blocks of descriptors
+ **************************************************************/
+
+namespace {
+
+DistanceComputer* storage_distance_computer(const Index* storage) {
+ if (is_similarity_metric(storage->metric_type)) {
+ return new NegativeDistanceComputer(storage->get_distance_computer());
+ } else {
+ return storage->get_distance_computer();
+ }
+}
+
+} // namespace
+
+/**************************************************************
+ * IndexNNDescent implementation
+ **************************************************************/
+
+IndexNNDescent::IndexNNDescent(int d, int K, MetricType metric)
+ : Index(d, metric),
+ nndescent(d, K),
+ own_fields(false),
+ storage(nullptr) {}
+
+IndexNNDescent::IndexNNDescent(Index* storage, int K)
+ : Index(storage->d, storage->metric_type),
+ nndescent(storage->d, K),
+ own_fields(false),
+ storage(storage) {}
+
+IndexNNDescent::~IndexNNDescent() {
+ if (own_fields) {
+ delete storage;
+ }
+}
+
+void IndexNNDescent::train(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNNDescentFlat (or variants) "
+ "instead of IndexNNDescent directly");
+ // nndescent structure does not require training
+ storage->train(n, x);
+ is_trained = true;
+}
+
+void IndexNNDescent::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNNDescentFlat (or variants) "
+ "instead of IndexNNDescent directly");
+ if (verbose) {
+ printf("Parameters: k=%" PRId64 ", search_L=%d\n",
+ k,
+ nndescent.search_L);
+ }
+
+ idx_t check_period =
+ InterruptCallback::get_period_hint(d * nndescent.search_L);
+
+ for (idx_t i0 = 0; i0 < n; i0 += check_period) {
+ idx_t i1 = std::min(i0 + check_period, n);
+
+#pragma omp parallel
+ {
+ VisitedTable vt(ntotal);
+
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+#pragma omp for
+ for (idx_t i = i0; i < i1; i++) {
+ idx_t* idxi = labels + i * k;
+ float* simi = distances + i * k;
+ dis->set_query(x + i * d);
+
+ nndescent.search(*dis, k, idxi, simi, vt);
+ }
+ }
+ InterruptCallback::check();
+ }
+
+ if (metric_type == METRIC_INNER_PRODUCT) {
+ // we need to revert the negated distances
+ for (size_t i = 0; i < k * n; i++) {
+ distances[i] = -distances[i];
+ }
+ }
+}
+
+void IndexNNDescent::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNNDescentFlat (or variants) "
+ "instead of IndexNNDescent directly");
+ FAISS_THROW_IF_NOT(is_trained);
+
+ if (ntotal != 0) {
+ fprintf(stderr,
+ "WARNING NNDescent doest not support dynamic insertions,"
+ "multiple insertions would lead to re-building the index");
+ }
+
+ storage->add(n, x);
+ ntotal = storage->ntotal;
+
+ std::unique_ptr<DistanceComputer> dis(storage_distance_computer(storage));
+ nndescent.build(*dis, ntotal, verbose);
+}
+
+void IndexNNDescent::reset() {
+ nndescent.reset();
+ storage->reset();
+ ntotal = 0;
+}
+
+void IndexNNDescent::reconstruct(idx_t key, float* recons) const {
+ storage->reconstruct(key, recons);
+}
+
+/**************************************************************
+ * IndexNNDescentFlat implementation
+ **************************************************************/
+
+IndexNNDescentFlat::IndexNNDescentFlat() {
+ is_trained = true;
+}
+
+IndexNNDescentFlat::IndexNNDescentFlat(int d, int M, MetricType metric)
+ : IndexNNDescent(new IndexFlat(d, metric), M) {
+ own_fields = true;
+ is_trained = true;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNNDescent.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNNDescent.h
new file mode 100644
index 0000000..0de302b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNNDescent.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/NNDescent.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/** The NNDescent index is a normal random-access index with an NNDescent
+ * link structure built on top */
+
+struct IndexNNDescent : Index {
+ // internal storage of vectors (32 bits)
+ using storage_idx_t = NNDescent::storage_idx_t;
+
+ /// Faiss results are 64-bit
+
+ // the link structure
+ NNDescent nndescent;
+
+ // the sequential storage
+ bool own_fields;
+ Index* storage;
+
+ explicit IndexNNDescent(
+ int d = 0,
+ int K = 32,
+ MetricType metric = METRIC_L2);
+ explicit IndexNNDescent(Index* storage, int K = 32);
+
+ ~IndexNNDescent() override;
+
+ void add(idx_t n, const float* x) override;
+
+ /// Trains the storage if needed
+ void train(idx_t n, const float* x) override;
+
+ /// entry point for search
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ void reset() override;
+};
+
+/** Flat index topped with with a NNDescent structure to access elements
+ * more efficiently.
+ */
+
+struct IndexNNDescentFlat : IndexNNDescent {
+ IndexNNDescentFlat();
+ IndexNNDescentFlat(int d, int K, MetricType metric = METRIC_L2);
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNSG.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNSG.cpp
new file mode 100644
index 0000000..41e2657
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNSG.cpp
@@ -0,0 +1,342 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexNSG.h>
+
+#include <cinttypes>
+#include <memory>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexNNDescent.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+
+namespace faiss {
+
+using namespace nsg;
+
+/**************************************************************
+ * IndexNSG implementation
+ **************************************************************/
+
+IndexNSG::IndexNSG(int d, int R, MetricType metric) : Index(d, metric), nsg(R) {
+ nndescent_L = GK + 50;
+}
+
+IndexNSG::IndexNSG(Index* storage, int R)
+ : Index(storage->d, storage->metric_type),
+ nsg(R),
+ storage(storage),
+ build_type(1) {
+ nndescent_L = GK + 50;
+}
+
+IndexNSG::~IndexNSG() {
+ if (own_fields) {
+ delete storage;
+ }
+}
+
+void IndexNSG::train(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNSGFlat (or variants) instead of IndexNSG directly");
+ // nsg structure does not require training
+ storage->train(n, x);
+ is_trained = true;
+}
+
+void IndexNSG::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNSGFlat (or variants) instead of IndexNSG directly");
+
+ int L = std::max(nsg.search_L, (int)k); // in case of search L = -1
+ idx_t check_period = InterruptCallback::get_period_hint(d * L);
+
+ int ndis = 0;
+
+ for (idx_t i0 = 0; i0 < n; i0 += check_period) {
+ idx_t i1 = std::min(i0 + check_period, n);
+
+#pragma omp parallel
+ {
+ VisitedTable vt(ntotal);
+
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+#pragma omp for reduction(+ : ndis)
+ for (idx_t i = i0; i < i1; i++) {
+ idx_t* idxi = labels + i * k;
+ float* simi = distances + i * k;
+ dis->set_query(x + i * d);
+
+ NSGStats stats = nsg.search(*dis, k, idxi, simi, vt);
+ ndis += stats.ndis;
+
+ vt.advance();
+ }
+ }
+ InterruptCallback::check();
+ }
+
+ if (is_similarity_metric(metric_type)) {
+ // we need to revert the negated distances
+ for (size_t i = 0; i < k * n; i++) {
+ distances[i] = -distances[i];
+ }
+ }
+
+ nsg_stats.ndis += ndis;
+}
+
+void IndexNSG::build(idx_t n, const float* x, idx_t* knn_graph, int GK_2) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNSGFlat (or variants) instead of IndexNSG directly");
+ FAISS_THROW_IF_NOT_MSG(
+ !is_built && ntotal == 0, "The IndexNSG is already built");
+
+ storage->add(n, x);
+ ntotal = storage->ntotal;
+
+ // check the knn graph
+ check_knn_graph(knn_graph, n, GK_2);
+
+ const nsg::Graph<idx_t> knng(knn_graph, n, GK_2);
+ nsg.build(storage, n, knng, verbose);
+ is_built = true;
+}
+
+void IndexNSG::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(
+ storage,
+ "Please use IndexNSGFlat (or variants) "
+ "instead of IndexNSG directly");
+ FAISS_THROW_IF_NOT(is_trained);
+
+ FAISS_THROW_IF_NOT_MSG(
+ !is_built && ntotal == 0,
+ "NSG does not support incremental addition");
+
+ std::vector<idx_t> knng;
+ if (verbose) {
+ printf("IndexNSG::add %zd vectors\n", size_t(n));
+ }
+
+ if (build_type == 0) { // build with brute force search
+
+ if (verbose) {
+ printf(" Build knn graph with brute force search on storage index\n");
+ }
+
+ storage->add(n, x);
+ ntotal = storage->ntotal;
+ FAISS_THROW_IF_NOT(ntotal == n);
+
+ knng.resize(ntotal * (GK + 1));
+ storage->assign(ntotal, x, knng.data(), GK + 1);
+
+ // Remove itself
+ // - For metric distance, we just need to remove the first neighbor
+ // - But for non-metric, e.g. inner product, we need to check
+ // - each neighbor
+ if (storage->metric_type == METRIC_INNER_PRODUCT) {
+ for (idx_t i = 0; i < ntotal; i++) {
+ int count = 0;
+ for (int j = 0; j < GK + 1; j++) {
+ idx_t id = knng[i * (GK + 1) + j];
+ if (id != i) {
+ knng[i * GK + count] = id;
+ count += 1;
+ }
+ if (count == GK) {
+ break;
+ }
+ }
+ }
+ } else {
+ for (idx_t i = 0; i < ntotal; i++) {
+ memmove(knng.data() + i * GK,
+ knng.data() + i * (GK + 1) + 1,
+ GK * sizeof(idx_t));
+ }
+ }
+
+ } else if (build_type == 1) { // build with NNDescent
+ idx_t knng_size_nnd = (size_t)n * GK;
+ if (verbose) {
+ printf(" Resizing knng vector (n=%" PRId64 ", GK=%d)\n", n, GK);
+ }
+ try {
+ knng.resize(knng_size_nnd);
+ } catch (const std::bad_alloc& e) {
+ fprintf(stderr,
+ "FATAL: Failed to allocate memory for knng (%" PRId64
+ " * %d * %zu bytes). std::bad_alloc: %s\n",
+ n,
+ GK,
+ sizeof(idx_t),
+ e.what());
+ FAISS_THROW_FMT(
+ "Memory allocation failed for knng vector of size %zd",
+ knng_size_nnd);
+ }
+ if (verbose) {
+ printf(" Successfully resized knng vector.\n");
+ }
+
+ IndexNNDescent index(storage, GK);
+ index.nndescent.S = nndescent_S;
+ index.nndescent.R = nndescent_R;
+ index.nndescent.L = std::max(nndescent_L, GK + 50);
+ index.nndescent.iter = nndescent_iter;
+ index.verbose = verbose;
+
+ if (verbose) {
+ printf(" Build knn graph with NNdescent S=%d R=%d L=%d niter=%d\n",
+ index.nndescent.S,
+ index.nndescent.R,
+ index.nndescent.L,
+ index.nndescent.iter);
+ }
+
+ // prevent IndexNSG from deleting the storage
+ index.own_fields = false;
+
+ index.add(n, x);
+
+ // storage->add is already implicit called in IndexNSG.add
+ ntotal = storage->ntotal;
+ FAISS_THROW_IF_NOT(ntotal == n);
+
+ // cast from idx_t to int
+ printf("index.nndescent.final_graph.data() = %p\n",
+ index.nndescent.final_graph.data());
+ const int* knn_graph = index.nndescent.final_graph.data();
+#pragma omp parallel for
+ for (idx_t i = 0; i < ntotal * GK; i++) {
+ knng[i] = knn_graph[i];
+ }
+ } else {
+ FAISS_THROW_MSG("build_type should be 0 or 1");
+ }
+
+ if (verbose) {
+ printf(" Check the knn graph\n");
+ }
+
+ // check the knn graph
+ check_knn_graph(knng.data(), n, GK);
+
+ if (verbose) {
+ printf(" nsg building\n");
+ }
+
+ const nsg::Graph<idx_t> knn_graph(knng.data(), n, GK);
+ nsg.build(storage, n, knn_graph, verbose);
+ is_built = true;
+}
+
+void IndexNSG::reset() {
+ nsg.reset();
+ storage->reset();
+ ntotal = 0;
+ is_built = false;
+}
+
+void IndexNSG::reconstruct(idx_t key, float* recons) const {
+ storage->reconstruct(key, recons);
+}
+
+void IndexNSG::check_knn_graph(const idx_t* knn_graph, idx_t n, int K) const {
+ idx_t total_count = 0;
+
+#pragma omp parallel for reduction(+ : total_count)
+ for (idx_t i = 0; i < n; i++) {
+ int count = 0;
+ for (int j = 0; j < K; j++) {
+ idx_t id = knn_graph[i * K + j];
+ if (id < 0 || id >= n || id == i) {
+ count += 1;
+ }
+ }
+ total_count += count;
+ }
+
+ if (total_count > 0) {
+ fprintf(stderr,
+ "WARNING: the input knn graph "
+ "has %" PRId64 " invalid entries\n",
+ total_count);
+ }
+ FAISS_THROW_IF_NOT_MSG(
+ total_count < n / 10,
+ "There are too much invalid entries in the knn graph. "
+ "It may be an invalid knn graph.");
+}
+
+/**************************************************************
+ * IndexNSGFlat implementation
+ **************************************************************/
+
+IndexNSGFlat::IndexNSGFlat() {
+ is_trained = true;
+}
+
+IndexNSGFlat::IndexNSGFlat(int d, int R, MetricType metric)
+ : IndexNSG(new IndexFlat(d, metric), R) {
+ own_fields = true;
+ is_trained = true;
+}
+
+/**************************************************************
+ * IndexNSGPQ implementation
+ **************************************************************/
+
+IndexNSGPQ::IndexNSGPQ() = default;
+
+IndexNSGPQ::IndexNSGPQ(int d, int pq_m, int M, int pq_nbits)
+ : IndexNSG(new IndexPQ(d, pq_m, pq_nbits), M) {
+ own_fields = true;
+ is_trained = false;
+}
+
+void IndexNSGPQ::train(idx_t n, const float* x) {
+ IndexNSG::train(n, x);
+ (dynamic_cast<IndexPQ*>(storage))->pq.compute_sdc_table();
+}
+
+/**************************************************************
+ * IndexNSGSQ implementation
+ **************************************************************/
+
+IndexNSGSQ::IndexNSGSQ(
+ int d,
+ ScalarQuantizer::QuantizerType qtype,
+ int M,
+ MetricType metric)
+ : IndexNSG(new IndexScalarQuantizer(d, qtype, metric), M) {
+ is_trained = this->storage->is_trained;
+ own_fields = true;
+}
+
+IndexNSGSQ::IndexNSGSQ() = default;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNSG.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNSG.h
new file mode 100644
index 0000000..8d26968
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNSG.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexNNDescent.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/impl/NSG.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/** The NSG index is a normal random-access index with a NSG
+ * link structure built on top */
+
+struct IndexNSG : Index {
+ /// the link structure
+ NSG nsg;
+
+ /// the sequential storage
+ bool own_fields = false;
+ Index* storage = nullptr;
+
+ /// the index is built or not
+ bool is_built = false;
+
+ /// K of KNN graph for building
+ int GK = 64;
+
+ /// indicate how to build a knn graph
+ /// - 0: build NSG with brute force search
+ /// - 1: build NSG with NNDescent
+ char build_type = 0;
+
+ /// parameters for nndescent
+ int nndescent_S = 10;
+ int nndescent_R = 100;
+ int nndescent_L; // set to GK + 50
+ int nndescent_iter = 10;
+
+ explicit IndexNSG(int d = 0, int R = 32, MetricType metric = METRIC_L2);
+ explicit IndexNSG(Index* storage, int R = 32);
+
+ ~IndexNSG() override;
+
+ void build(idx_t n, const float* x, idx_t* knn_graph, int GK);
+
+ void add(idx_t n, const float* x) override;
+
+ /// Trains the storage if needed
+ void train(idx_t n, const float* x) override;
+
+ /// entry point for search
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ void reset() override;
+
+ void check_knn_graph(const idx_t* knn_graph, idx_t n, int K) const;
+};
+
+/** Flat index topped with with a NSG structure to access elements
+ * more efficiently.
+ */
+
+struct IndexNSGFlat : IndexNSG {
+ IndexNSGFlat();
+ IndexNSGFlat(int d, int R, MetricType metric = METRIC_L2);
+};
+
+/** PQ index topped with with a NSG structure to access elements
+ * more efficiently.
+ */
+struct IndexNSGPQ : IndexNSG {
+ IndexNSGPQ();
+ IndexNSGPQ(int d, int pq_m, int M, int pq_nbits = 8);
+ void train(idx_t n, const float* x) override;
+};
+
+/** SQ index topped with with a NSG structure to access elements
+ * more efficiently.
+ */
+struct IndexNSGSQ : IndexNSG {
+ IndexNSGSQ();
+ IndexNSGSQ(
+ int d,
+ ScalarQuantizer::QuantizerType qtype,
+ int M,
+ MetricType metric = METRIC_L2);
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNeuralNetCodec.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNeuralNetCodec.cpp
new file mode 100644
index 0000000..022c5b1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNeuralNetCodec.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexNeuralNetCodec.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+
+namespace faiss {
+
+/*********************************************************
+ * IndexNeuralNetCodec implementation
+ *********************************************************/
+
+IndexNeuralNetCodec::IndexNeuralNetCodec(
+ int d,
+ int M,
+ int nbits,
+ MetricType metric)
+ : IndexFlatCodes((M * nbits + 7) / 8, d, metric), M(M), nbits(nbits) {
+ is_trained = false;
+}
+
+void IndexNeuralNetCodec::train(idx_t n, const float* x) {
+ FAISS_THROW_MSG("Training not implemented in C++, use Pytorch");
+}
+
+void IndexNeuralNetCodec::sa_encode(idx_t n, const float* x, uint8_t* codes)
+ const {
+ nn::Tensor2D x_tensor(n, d, x);
+ nn::Int32Tensor2D codes_tensor = net->encode(x_tensor);
+ pack_bitstrings(n, M, nbits, codes_tensor.data(), codes, code_size);
+}
+
+void IndexNeuralNetCodec::sa_decode(idx_t n, const uint8_t* codes, float* x)
+ const {
+ nn::Int32Tensor2D codes_tensor(n, M);
+ unpack_bitstrings(n, M, nbits, codes, code_size, codes_tensor.data());
+ nn::Tensor2D x_tensor = net->decode(codes_tensor);
+ memcpy(x, x_tensor.data(), d * n * sizeof(float));
+}
+
+/*********************************************************
+ * IndexQINeuralNetCodec implementation
+ *********************************************************/
+
+IndexQINCo::IndexQINCo(int d, int M, int nbits, int L, int h, MetricType metric)
+ : IndexNeuralNetCodec(d, M, nbits, metric),
+ qinco(d, 1 << nbits, L, M, h) {
+ net = &qinco;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNeuralNetCodec.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNeuralNetCodec.h
new file mode 100644
index 0000000..6ce405a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexNeuralNetCodec.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/utils/NeuralNet.h>
+
+namespace faiss {
+
+struct IndexNeuralNetCodec : IndexFlatCodes {
+ NeuralNetCodec* net = nullptr;
+ size_t M, nbits;
+
+ explicit IndexNeuralNetCodec(
+ int d = 0,
+ int M = 0,
+ int nbits = 0,
+ MetricType metric = METRIC_L2);
+
+ void train(idx_t n, const float* x) override;
+
+ void sa_encode(idx_t n, const float* x, uint8_t* codes) const override;
+ void sa_decode(idx_t n, const uint8_t* codes, float* x) const override;
+
+ ~IndexNeuralNetCodec() {}
+};
+
+struct IndexQINCo : IndexNeuralNetCodec {
+ QINCo qinco;
+
+ IndexQINCo(
+ int d,
+ int M,
+ int nbits,
+ int L,
+ int h,
+ MetricType metric = METRIC_L2);
+
+ ~IndexQINCo() {}
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQ.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQ.cpp
new file mode 100644
index 0000000..8193e78
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQ.cpp
@@ -0,0 +1,1115 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexPQ.h>
+
+#include <cinttypes>
+#include <cmath>
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+
+#include <algorithm>
+#include <memory>
+
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+
+#include <faiss/impl/code_distance/code_distance.h>
+
+namespace faiss {
+
+/*********************************************************
+ * IndexPQ implementation
+ ********************************************************/
+
+IndexPQ::IndexPQ(int d, size_t M, size_t nbits, MetricType metric)
+ : IndexFlatCodes(0, d, metric), pq(d, M, nbits) {
+ is_trained = false;
+ do_polysemous_training = false;
+ polysemous_ht = nbits * M + 1;
+ search_type = ST_PQ;
+ encode_signs = false;
+ code_size = pq.code_size;
+}
+
+IndexPQ::IndexPQ() {
+ metric_type = METRIC_L2;
+ is_trained = false;
+ do_polysemous_training = false;
+ polysemous_ht = pq.nbits * pq.M + 1;
+ search_type = ST_PQ;
+ encode_signs = false;
+}
+
+void IndexPQ::train(idx_t n, const float* x) {
+ if (!do_polysemous_training) { // standard training
+ pq.train(n, x);
+ } else {
+ idx_t ntrain_perm = polysemous_training.ntrain_permutation;
+
+ if (ntrain_perm > n / 4)
+ ntrain_perm = n / 4;
+ if (verbose) {
+ printf("PQ training on %" PRId64 " points, remains %" PRId64
+ " points: "
+ "training polysemous on %s\n",
+ n - ntrain_perm,
+ ntrain_perm,
+ ntrain_perm == 0 ? "centroids" : "these");
+ }
+ pq.train(n - ntrain_perm, x);
+
+ polysemous_training.optimize_pq_for_hamming(
+ pq, ntrain_perm, x + (n - ntrain_perm) * d);
+ }
+ is_trained = true;
+}
+
+namespace {
+
+template <class PQDecoder>
+struct PQDistanceComputer : FlatCodesDistanceComputer {
+ size_t d;
+ MetricType metric;
+ idx_t nb;
+ const ProductQuantizer& pq;
+ const float* sdc;
+ std::vector<float> precomputed_table;
+ size_t ndis;
+
+ float distance_to_code(const uint8_t* code) final {
+ ndis++;
+
+ float dis = distance_single_code<PQDecoder>(
+ pq.M, pq.nbits, precomputed_table.data(), code);
+ return dis;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ FAISS_THROW_IF_NOT(sdc);
+ const float* sdci = sdc;
+ float accu = 0;
+ PQDecoder codei(codes + i * code_size, pq.nbits);
+ PQDecoder codej(codes + j * code_size, pq.nbits);
+
+ for (int l = 0; l < pq.M; l++) {
+ accu += sdci[codei.decode() + (codej.decode() << codei.nbits)];
+ sdci += uint64_t(1) << (2 * codei.nbits);
+ }
+ ndis++;
+ return accu;
+ }
+
+ explicit PQDistanceComputer(const IndexPQ& storage)
+ : FlatCodesDistanceComputer(
+ storage.codes.data(),
+ storage.code_size),
+ pq(storage.pq) {
+ precomputed_table.resize(pq.M * pq.ksub);
+ nb = storage.ntotal;
+ d = storage.d;
+ metric = storage.metric_type;
+ if (pq.sdc_table.size() == pq.ksub * pq.ksub * pq.M) {
+ sdc = pq.sdc_table.data();
+ } else {
+ sdc = nullptr;
+ }
+ ndis = 0;
+ }
+
+ void set_query(const float* x) override {
+ if (metric == METRIC_L2) {
+ pq.compute_distance_table(x, precomputed_table.data());
+ } else {
+ pq.compute_inner_prod_table(x, precomputed_table.data());
+ }
+ }
+};
+
+} // namespace
+
+FlatCodesDistanceComputer* IndexPQ::get_FlatCodesDistanceComputer() const {
+ if (pq.nbits == 8) {
+ return new PQDistanceComputer<PQDecoder8>(*this);
+ } else if (pq.nbits == 16) {
+ return new PQDistanceComputer<PQDecoder16>(*this);
+ } else {
+ return new PQDistanceComputer<PQDecoderGeneric>(*this);
+ }
+}
+
+/*****************************************
+ * IndexPQ polysemous search routines
+ ******************************************/
+
+void IndexPQ::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* iparams) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+
+ const SearchParametersPQ* params = nullptr;
+ Search_type_t param_search_type = this->search_type;
+
+ if (iparams) {
+ params = dynamic_cast<const SearchParametersPQ*>(iparams);
+ FAISS_THROW_IF_NOT_MSG(params, "invalid search params");
+ FAISS_THROW_IF_NOT_MSG(!params->sel, "selector not supported");
+ param_search_type = params->search_type;
+ }
+
+ if (param_search_type == ST_PQ) { // Simple PQ search
+
+ if (metric_type == METRIC_L2) {
+ float_maxheap_array_t res = {
+ size_t(n), size_t(k), labels, distances};
+ pq.search(x, n, codes.data(), ntotal, &res, true);
+ } else {
+ float_minheap_array_t res = {
+ size_t(n), size_t(k), labels, distances};
+ pq.search_ip(x, n, codes.data(), ntotal, &res, true);
+ }
+ indexPQ_stats.nq += n;
+ indexPQ_stats.ncode += n * ntotal;
+
+ } else if (
+ param_search_type == ST_polysemous ||
+ param_search_type == ST_polysemous_generalize) {
+ FAISS_THROW_IF_NOT(metric_type == METRIC_L2);
+ int param_polysemous_ht =
+ params ? params->polysemous_ht : this->polysemous_ht;
+ search_core_polysemous(
+ n,
+ x,
+ k,
+ distances,
+ labels,
+ param_polysemous_ht,
+ param_search_type == ST_polysemous_generalize);
+
+ } else { // code-to-code distances
+
+ std::unique_ptr<uint8_t[]> q_codes(new uint8_t[n * pq.code_size]);
+
+ if (!encode_signs) {
+ pq.compute_codes(x, q_codes.get(), n);
+ } else {
+ FAISS_THROW_IF_NOT(d == pq.nbits * pq.M);
+ memset(q_codes.get(), 0, n * pq.code_size);
+ for (size_t i = 0; i < n; i++) {
+ const float* xi = x + i * d;
+ uint8_t* code = q_codes.get() + i * pq.code_size;
+ for (int j = 0; j < d; j++)
+ if (xi[j] > 0)
+ code[j >> 3] |= 1 << (j & 7);
+ }
+ }
+
+ if (param_search_type == ST_SDC) {
+ float_maxheap_array_t res = {
+ size_t(n), size_t(k), labels, distances};
+
+ pq.search_sdc(q_codes.get(), n, codes.data(), ntotal, &res, true);
+
+ } else {
+ std::unique_ptr<int[]> idistances(new int[n * k]);
+
+ int_maxheap_array_t res = {
+ size_t(n), size_t(k), labels, idistances.get()};
+
+ if (param_search_type == ST_HE) {
+ hammings_knn_hc(
+ &res,
+ q_codes.get(),
+ codes.data(),
+ ntotal,
+ pq.code_size,
+ true);
+
+ } else if (param_search_type == ST_generalized_HE) {
+ generalized_hammings_knn_hc(
+ &res,
+ q_codes.get(),
+ codes.data(),
+ ntotal,
+ pq.code_size,
+ true);
+ }
+
+ // convert distances to floats
+ for (int i = 0; i < k * n; i++)
+ distances[i] = idistances[i];
+ }
+
+ indexPQ_stats.nq += n;
+ indexPQ_stats.ncode += n * ntotal;
+ }
+}
+
+void IndexPQStats::reset() {
+ nq = ncode = n_hamming_pass = 0;
+}
+
+IndexPQStats indexPQ_stats;
+
+namespace {
+
+template <class HammingComputer>
+size_t polysemous_inner_loop(
+ const IndexPQ* index,
+ const float* dis_table_qi,
+ const uint8_t* q_code,
+ size_t k,
+ float* heap_dis,
+ int64_t* heap_ids,
+ int ht) {
+ int M = index->pq.M;
+ int code_size = index->pq.code_size;
+ int ksub = index->pq.ksub;
+ size_t ntotal = index->ntotal;
+
+ const uint8_t* b_code = index->codes.data();
+
+ size_t n_pass_i = 0;
+
+ HammingComputer hc(q_code, code_size);
+
+ for (int64_t bi = 0; bi < ntotal; bi++) {
+ int hd = hc.hamming(b_code);
+
+ if (hd < ht) {
+ n_pass_i++;
+
+ float dis = 0;
+ const float* dis_table = dis_table_qi;
+ for (int m = 0; m < M; m++) {
+ dis += dis_table[b_code[m]];
+ dis_table += ksub;
+ }
+
+ if (dis < heap_dis[0]) {
+ maxheap_replace_top(k, heap_dis, heap_ids, dis, bi);
+ }
+ }
+ b_code += code_size;
+ }
+ return n_pass_i;
+}
+
+struct Run_polysemous_inner_loop {
+ using T = size_t;
+ template <class HammingComputer, class... Types>
+ size_t f(Types... args) {
+ return polysemous_inner_loop<HammingComputer>(args...);
+ }
+};
+
+} // anonymous namespace
+
+void IndexPQ::search_core_polysemous(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ int param_polysemous_ht,
+ bool generalized_hamming) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(pq.nbits == 8);
+
+ if (param_polysemous_ht == 0) {
+ param_polysemous_ht = pq.nbits * pq.M + 1;
+ }
+
+ // PQ distance tables
+ std::unique_ptr<float[]> dis_tables(new float[n * pq.ksub * pq.M]);
+ pq.compute_distance_tables(n, x, dis_tables.get());
+
+ // Hamming embedding queries
+ std::unique_ptr<uint8_t[]> q_codes(new uint8_t[n * pq.code_size]);
+
+ if (false) {
+ pq.compute_codes(x, q_codes.get(), n);
+ } else {
+#pragma omp parallel for
+ for (idx_t qi = 0; qi < n; qi++) {
+ pq.compute_code_from_distance_table(
+ dis_tables.get() + qi * pq.M * pq.ksub,
+ q_codes.get() + qi * pq.code_size);
+ }
+ }
+
+ size_t n_pass = 0;
+
+ int bad_code_size = 0;
+
+#pragma omp parallel for reduction(+ : n_pass, bad_code_size)
+ for (idx_t qi = 0; qi < n; qi++) {
+ const uint8_t* q_code = q_codes.get() + qi * pq.code_size;
+
+ const float* dis_table_qi = dis_tables.get() + qi * pq.M * pq.ksub;
+
+ int64_t* heap_ids = labels + qi * k;
+ float* heap_dis = distances + qi * k;
+ maxheap_heapify(k, heap_dis, heap_ids);
+
+ if (!generalized_hamming) {
+ Run_polysemous_inner_loop r;
+ n_pass += dispatch_HammingComputer(
+ pq.code_size,
+ r,
+ this,
+ dis_table_qi,
+ q_code,
+ k,
+ heap_dis,
+ heap_ids,
+ param_polysemous_ht);
+
+ } else { // generalized hamming
+ switch (pq.code_size) {
+#define DISPATCH(cs) \
+ case cs: \
+ n_pass += polysemous_inner_loop<GenHammingComputer##cs>( \
+ this, \
+ dis_table_qi, \
+ q_code, \
+ k, \
+ heap_dis, \
+ heap_ids, \
+ param_polysemous_ht); \
+ break;
+ DISPATCH(8)
+ DISPATCH(16)
+ DISPATCH(32)
+ default:
+ if (pq.code_size % 8 == 0) {
+ n_pass += polysemous_inner_loop<GenHammingComputerM8>(
+ this,
+ dis_table_qi,
+ q_code,
+ k,
+ heap_dis,
+ heap_ids,
+ param_polysemous_ht);
+ } else {
+ bad_code_size++;
+ }
+ break;
+#undef DISPATCH
+ }
+ }
+ maxheap_reorder(k, heap_dis, heap_ids);
+ }
+
+ if (bad_code_size) {
+ FAISS_THROW_FMT(
+ "code size %zd not supported for polysemous", pq.code_size);
+ }
+
+ indexPQ_stats.nq += n;
+ indexPQ_stats.ncode += n * ntotal;
+ indexPQ_stats.n_hamming_pass += n_pass;
+}
+
+/* The standalone codec interface (just remaps to the PQ functions) */
+
+void IndexPQ::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ pq.compute_codes(x, bytes, n);
+}
+
+void IndexPQ::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ pq.decode(bytes, x, n);
+}
+
+/*****************************************
+ * Stats of IndexPQ codes
+ ******************************************/
+
+void IndexPQ::hamming_distance_table(idx_t n, const float* x, int32_t* dis)
+ const {
+ std::unique_ptr<uint8_t[]> q_codes(new uint8_t[n * pq.code_size]);
+
+ pq.compute_codes(x, q_codes.get(), n);
+
+ hammings(q_codes.get(), codes.data(), n, ntotal, pq.code_size, dis);
+}
+
+void IndexPQ::hamming_distance_histogram(
+ idx_t n,
+ const float* x,
+ idx_t nb,
+ const float* xb,
+ int64_t* hist) {
+ FAISS_THROW_IF_NOT(metric_type == METRIC_L2);
+ FAISS_THROW_IF_NOT(pq.code_size % 8 == 0);
+ FAISS_THROW_IF_NOT(pq.nbits == 8);
+
+ // Hamming embedding queries
+ std::unique_ptr<uint8_t[]> q_codes(new uint8_t[n * pq.code_size]);
+ pq.compute_codes(x, q_codes.get(), n);
+
+ uint8_t* b_codes;
+ std::unique_ptr<uint8_t[]> del_b_codes;
+
+ if (xb) {
+ b_codes = new uint8_t[nb * pq.code_size];
+ del_b_codes.reset(b_codes);
+ pq.compute_codes(xb, b_codes, nb);
+ } else {
+ nb = ntotal;
+ b_codes = codes.data();
+ }
+ int nbits = pq.M * pq.nbits;
+ memset(hist, 0, sizeof(*hist) * (nbits + 1));
+ size_t bs = 256;
+
+#pragma omp parallel
+ {
+ std::vector<int64_t> histi(nbits + 1);
+ std::unique_ptr<hamdis_t[]> distances(new hamdis_t[nb * bs]);
+#pragma omp for
+ for (idx_t q0 = 0; q0 < n; q0 += bs) {
+ // printf ("dis stats: %zd/%zd\n", q0, n);
+ size_t q1 = q0 + bs;
+ if (q1 > n)
+ q1 = n;
+
+ hammings(
+ q_codes.get() + q0 * pq.code_size,
+ b_codes,
+ q1 - q0,
+ nb,
+ pq.code_size,
+ distances.get());
+
+ for (size_t i = 0; i < nb * (q1 - q0); i++)
+ histi[distances[i]]++;
+ }
+#pragma omp critical
+ {
+ for (int i = 0; i <= nbits; i++)
+ hist[i] += histi[i];
+ }
+ }
+}
+
+/*****************************************
+ * MultiIndexQuantizer
+ ******************************************/
+
+namespace {
+
+template <typename T>
+struct PreSortedArray {
+ const T* x;
+ int N;
+
+ explicit PreSortedArray(int N) : N(N) {}
+ void init(const T* x_2) {
+ this->x = x_2;
+ }
+ // get smallest value
+ T get_0() {
+ return x[0];
+ }
+
+ // get delta between n-smallest and n-1 -smallest
+ T get_diff(int n) {
+ return x[n] - x[n - 1];
+ }
+
+ // remap orders counted from smallest to indices in array
+ int get_ord(int n) {
+ return n;
+ }
+};
+
+template <typename T>
+struct ArgSort {
+ const T* x;
+ bool operator()(size_t i, size_t j) {
+ return x[i] < x[j];
+ }
+};
+
+/** Array that maintains a permutation of its elements so that the
+ * array's elements are sorted
+ */
+template <typename T>
+struct SortedArray {
+ const T* x;
+ int N;
+ std::vector<int> perm;
+
+ explicit SortedArray(int N) {
+ this->N = N;
+ perm.resize(N);
+ }
+
+ void init(const T* x_2) {
+ this->x = x_2;
+ for (int n = 0; n < N; n++)
+ perm[n] = n;
+ ArgSort<T> cmp = {x_2};
+ std::sort(perm.begin(), perm.end(), cmp);
+ }
+
+ // get smallest value
+ T get_0() {
+ return x[perm[0]];
+ }
+
+ // get delta between n-smallest and n-1 -smallest
+ T get_diff(int n) {
+ return x[perm[n]] - x[perm[n - 1]];
+ }
+
+ // remap orders counted from smallest to indices in array
+ int get_ord(int n) {
+ return perm[n];
+ }
+};
+
+/** Array has n values. Sort the k first ones and copy the other ones
+ * into elements k..n-1
+ */
+template <class C>
+void partial_sort(
+ int k,
+ int n,
+ const typename C::T* vals,
+ typename C::TI* perm) {
+ // insert first k elts in heap
+ for (int i = 1; i < k; i++) {
+ indirect_heap_push<C>(i + 1, vals, perm, perm[i]);
+ }
+
+ // insert next n - k elts in heap
+ for (int i = k; i < n; i++) {
+ typename C::TI id = perm[i];
+ typename C::TI top = perm[0];
+
+ if (C::cmp(vals[top], vals[id])) {
+ indirect_heap_pop<C>(k, vals, perm);
+ indirect_heap_push<C>(k, vals, perm, id);
+ perm[i] = top;
+ } else {
+ // nothing, elt at i is good where it is.
+ }
+ }
+
+ // order the k first elements in heap
+ for (int i = k - 1; i > 0; i--) {
+ typename C::TI top = perm[0];
+ indirect_heap_pop<C>(i + 1, vals, perm);
+ perm[i] = top;
+ }
+}
+
+/** same as SortedArray, but only the k first elements are sorted */
+template <typename T>
+struct SemiSortedArray {
+ const T* x;
+ int N;
+
+ // type of the heap: CMax = sort ascending
+ using HC = CMax<T, int>;
+ std::vector<int> perm;
+
+ int k; // k elements are sorted
+
+ int initial_k, k_factor;
+
+ explicit SemiSortedArray(int N) {
+ this->N = N;
+ perm.resize(N);
+ perm.resize(N);
+ initial_k = 3;
+ k_factor = 4;
+ }
+
+ void init(const T* x_2) {
+ this->x = x_2;
+ for (int n = 0; n < N; n++)
+ perm[n] = n;
+ k = 0;
+ grow(initial_k);
+ }
+
+ /// grow the sorted part of the array to size next_k
+ void grow(int next_k) {
+ if (next_k < N) {
+ partial_sort<HC>(next_k - k, N - k, x, &perm[k]);
+ k = next_k;
+ } else { // full sort of remainder of array
+ ArgSort<T> cmp = {x};
+ std::sort(perm.begin() + k, perm.end(), cmp);
+ k = N;
+ }
+ }
+
+ // get smallest value
+ T get_0() {
+ return x[perm[0]];
+ }
+
+ // get delta between n-smallest and n-1 -smallest
+ T get_diff(int n) {
+ if (n >= k) {
+ // want to keep powers of 2 - 1
+ int next_k = (k + 1) * k_factor - 1;
+ grow(next_k);
+ }
+ return x[perm[n]] - x[perm[n - 1]];
+ }
+
+ // remap orders counted from smallest to indices in array
+ int get_ord(int n) {
+ assert(n < k);
+ return perm[n];
+ }
+};
+
+/*****************************************
+ * Find the k smallest sums of M terms, where each term is taken in a
+ * table x of n values.
+ *
+ * A combination of terms is encoded as a scalar 0 <= t < n^M. The
+ * combination t0 ... t(M-1) that correspond to the sum
+ *
+ * sum = x[0, t0] + x[1, t1] + .... + x[M-1, t(M-1)]
+ *
+ * is encoded as
+ *
+ * t = t0 + t1 * n + t2 * n^2 + ... + t(M-1) * n^(M-1)
+ *
+ * MinSumK is an object rather than a function, so that storage can be
+ * re-used over several computations with the same sizes. use_seen is
+ * good when there may be ties in the x array and it is a concern if
+ * occasionally several t's are returned.
+ *
+ * @param x size M * n, values to add up
+ * @param k nb of results to retrieve
+ * @param M nb of terms
+ * @param n nb of distinct values
+ * @param sums output, size k, sorted
+ * @param terms output, size k, with encoding as above
+ *
+ ******************************************/
+template <typename T, class SSA, bool use_seen>
+struct MinSumK {
+ int K; ///< nb of sums to return
+ int M; ///< nb of elements to sum up
+ int nbit; ///< nb of bits to encode one entry
+ int N; ///< nb of possible elements for each of the M terms
+
+ /** the heap.
+ * We use a heap to maintain a queue of sums, with the associated
+ * terms involved in the sum.
+ */
+ using HC = CMin<T, int64_t>;
+ size_t heap_capacity, heap_size;
+ T* bh_val;
+ int64_t* bh_ids;
+
+ std::vector<SSA> ssx;
+
+ // all results get pushed several times. When there are ties, they
+ // are popped interleaved with others, so it is not easy to
+ // identify them. Therefore, this bit array just marks elements
+ // that were seen before.
+ std::vector<uint8_t> seen;
+
+ MinSumK(int K, int M, int nbit, int N) : K(K), M(M), nbit(nbit), N(N) {
+ heap_capacity = K * M;
+ assert(N <= (1 << nbit));
+
+ // we'll do k steps, each step pushes at most M vals
+ bh_val = new T[heap_capacity];
+ bh_ids = new int64_t[heap_capacity];
+
+ if (use_seen) {
+ int64_t n_ids = weight(M);
+ seen.resize((n_ids + 7) / 8);
+ }
+
+ for (int m = 0; m < M; m++)
+ ssx.push_back(SSA(N));
+ }
+
+ int64_t weight(int i) {
+ return 1 << (i * nbit);
+ }
+
+ bool is_seen(int64_t i) {
+ return (seen[i >> 3] >> (i & 7)) & 1;
+ }
+
+ void mark_seen(int64_t i) {
+ if (use_seen)
+ seen[i >> 3] |= 1 << (i & 7);
+ }
+
+ void run(const T* x, int64_t ldx, T* sums, int64_t* terms) {
+ heap_size = 0;
+
+ for (int m = 0; m < M; m++) {
+ ssx[m].init(x);
+ x += ldx;
+ }
+
+ { // initial result: take min for all elements
+ T sum = 0;
+ terms[0] = 0;
+ mark_seen(0);
+ for (int m = 0; m < M; m++) {
+ sum += ssx[m].get_0();
+ }
+ sums[0] = sum;
+ for (int m = 0; m < M; m++) {
+ heap_push<HC>(
+ ++heap_size,
+ bh_val,
+ bh_ids,
+ sum + ssx[m].get_diff(1),
+ weight(m));
+ }
+ }
+
+ for (int k = 1; k < K; k++) {
+ // pop smallest value from heap
+ if (use_seen) { // skip already seen elements
+ while (is_seen(bh_ids[0])) {
+ assert(heap_size > 0);
+ heap_pop<HC>(heap_size--, bh_val, bh_ids);
+ }
+ }
+ assert(heap_size > 0);
+
+ T sum = sums[k] = bh_val[0];
+ int64_t ti = terms[k] = bh_ids[0];
+
+ if (use_seen) {
+ mark_seen(ti);
+ heap_pop<HC>(heap_size--, bh_val, bh_ids);
+ } else {
+ do {
+ heap_pop<HC>(heap_size--, bh_val, bh_ids);
+ } while (heap_size > 0 && bh_ids[0] == ti);
+ }
+
+ // enqueue followers
+ int64_t ii = ti;
+ for (int m = 0; m < M; m++) {
+ int64_t n = ii & (((int64_t)1 << nbit) - 1);
+ ii >>= nbit;
+ if (n + 1 >= N)
+ continue;
+
+ enqueue_follower(ti, m, n, sum);
+ }
+ }
+
+ /*
+ for (int k = 0; k < K; k++)
+ for (int l = k + 1; l < K; l++)
+ assert (terms[k] != terms[l]);
+ */
+
+ // convert indices by applying permutation
+ for (int k = 0; k < K; k++) {
+ int64_t ii = terms[k];
+ if (use_seen) {
+ // clear seen for reuse at next loop
+ seen[ii >> 3] = 0;
+ }
+ int64_t ti = 0;
+ for (int m = 0; m < M; m++) {
+ int64_t n = ii & (((int64_t)1 << nbit) - 1);
+ ti += int64_t(ssx[m].get_ord(n)) << (nbit * m);
+ ii >>= nbit;
+ }
+ terms[k] = ti;
+ }
+ }
+
+ void enqueue_follower(int64_t ti, int m, int n, T sum) {
+ T next_sum = sum + ssx[m].get_diff(n + 1);
+ int64_t next_ti = ti + weight(m);
+ heap_push<HC>(++heap_size, bh_val, bh_ids, next_sum, next_ti);
+ }
+
+ ~MinSumK() {
+ delete[] bh_ids;
+ delete[] bh_val;
+ }
+};
+
+} // anonymous namespace
+
+MultiIndexQuantizer::MultiIndexQuantizer(int d, size_t M, size_t nbits)
+ : Index(d, METRIC_L2), pq(d, M, nbits) {
+ is_trained = false;
+ pq.verbose = verbose;
+}
+
+void MultiIndexQuantizer::train(idx_t n, const float* x) {
+ pq.verbose = verbose;
+ pq.train(n, x);
+ is_trained = true;
+ // count virtual elements in index
+ ntotal = 1;
+ for (int m = 0; m < pq.M; m++)
+ ntotal *= pq.ksub;
+}
+
+// block size used in MultiIndexQuantizer::search
+int multi_index_quantizer_search_bs = 32768;
+
+void MultiIndexQuantizer::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ if (n == 0) {
+ return;
+ }
+ FAISS_THROW_IF_NOT(k > 0);
+
+ // the allocation just below can be severe...
+ idx_t bs = multi_index_quantizer_search_bs;
+ if (n > bs) {
+ for (idx_t i0 = 0; i0 < n; i0 += bs) {
+ idx_t i1 = std::min(i0 + bs, n);
+ if (verbose) {
+ printf("MultiIndexQuantizer::search: %" PRId64 ":%" PRId64
+ " / %" PRId64 "\n",
+ i0,
+ i1,
+ n);
+ }
+ search(i1 - i0, x + i0 * d, k, distances + i0 * k, labels + i0 * k);
+ }
+ return;
+ }
+
+ std::unique_ptr<float[]> dis_tables(new float[n * pq.ksub * pq.M]);
+
+ pq.compute_distance_tables(n, x, dis_tables.get());
+
+ if (k == 1) {
+ // simple version that just finds the min in each table
+
+#pragma omp parallel for
+ for (int i = 0; i < n; i++) {
+ const float* dis_table = dis_tables.get() + i * pq.ksub * pq.M;
+ float dis = 0;
+ idx_t label = 0;
+
+ for (int s = 0; s < pq.M; s++) {
+ float vmin = HUGE_VALF;
+ idx_t lmin = -1;
+
+ for (idx_t j = 0; j < pq.ksub; j++) {
+ if (dis_table[j] < vmin) {
+ vmin = dis_table[j];
+ lmin = j;
+ }
+ }
+ dis += vmin;
+ label |= lmin << (s * pq.nbits);
+ dis_table += pq.ksub;
+ }
+
+ distances[i] = dis;
+ labels[i] = label;
+ }
+
+ } else {
+#pragma omp parallel if (n > 1)
+ {
+ MinSumK<float, SemiSortedArray<float>, false> msk(
+ k, pq.M, pq.nbits, pq.ksub);
+#pragma omp for
+ for (int i = 0; i < n; i++) {
+ msk.run(dis_tables.get() + i * pq.ksub * pq.M,
+ pq.ksub,
+ distances + i * k,
+ labels + i * k);
+ }
+ }
+ }
+}
+
+void MultiIndexQuantizer::reconstruct(idx_t key, float* recons) const {
+ int64_t jj = key;
+ for (int m = 0; m < pq.M; m++) {
+ int64_t n = jj & (((int64_t)1 << pq.nbits) - 1);
+ jj >>= pq.nbits;
+ memcpy(recons, pq.get_centroids(m, n), sizeof(recons[0]) * pq.dsub);
+ recons += pq.dsub;
+ }
+}
+
+void MultiIndexQuantizer::add(idx_t /*n*/, const float* /*x*/) {
+ FAISS_THROW_MSG(
+ "This index has virtual elements, "
+ "it does not support add");
+}
+
+void MultiIndexQuantizer::reset() {
+ FAISS_THROW_MSG(
+ "This index has virtual elements, "
+ "it does not support reset");
+}
+
+/*****************************************
+ * MultiIndexQuantizer2
+ ******************************************/
+
+MultiIndexQuantizer2::MultiIndexQuantizer2(
+ int d,
+ size_t M,
+ size_t nbits,
+ Index** indexes)
+ : MultiIndexQuantizer(d, M, nbits) {
+ assign_indexes.resize(M);
+ for (int i = 0; i < M; i++) {
+ FAISS_THROW_IF_NOT_MSG(
+ indexes[i]->d == pq.dsub,
+ "Provided sub-index has incorrect size");
+ assign_indexes[i] = indexes[i];
+ }
+ own_fields = false;
+}
+
+MultiIndexQuantizer2::MultiIndexQuantizer2(
+ int d,
+ size_t nbits,
+ Index* assign_index_0,
+ Index* assign_index_1)
+ : MultiIndexQuantizer(d, 2, nbits) {
+ FAISS_THROW_IF_NOT_MSG(
+ assign_index_0->d == pq.dsub && assign_index_1->d == pq.dsub,
+ "Provided sub-index has incorrect size");
+ assign_indexes.resize(2);
+ assign_indexes[0] = assign_index_0;
+ assign_indexes[1] = assign_index_1;
+ own_fields = false;
+}
+
+void MultiIndexQuantizer2::train(idx_t n, const float* x) {
+ MultiIndexQuantizer::train(n, x);
+ // add centroids to sub-indexes
+ for (int i = 0; i < pq.M; i++) {
+ assign_indexes[i]->add(pq.ksub, pq.get_centroids(i, 0));
+ }
+}
+
+void MultiIndexQuantizer2::search(
+ idx_t n,
+ const float* x,
+ idx_t K,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+
+ if (n == 0) {
+ return;
+ }
+
+ int k2 = std::min(K, int64_t(pq.ksub));
+ FAISS_THROW_IF_NOT(k2);
+
+ int64_t M = pq.M;
+ int64_t dsub = pq.dsub, ksub = pq.ksub;
+
+ // size (M, n, k2)
+ std::vector<idx_t> sub_ids(n * M * k2);
+ std::vector<float> sub_dis(n * M * k2);
+ std::vector<float> xsub(n * dsub);
+
+ for (int m = 0; m < M; m++) {
+ float* xdest = xsub.data();
+ const float* xsrc = x + m * dsub;
+ for (int j = 0; j < n; j++) {
+ memcpy(xdest, xsrc, dsub * sizeof(xdest[0]));
+ xsrc += d;
+ xdest += dsub;
+ }
+
+ assign_indexes[m]->search(
+ n, xsub.data(), k2, &sub_dis[k2 * n * m], &sub_ids[k2 * n * m]);
+ }
+
+ if (K == 1) {
+ // simple version that just finds the min in each table
+ assert(k2 == 1);
+
+ for (int i = 0; i < n; i++) {
+ float dis = 0;
+ idx_t label = 0;
+
+ for (int m = 0; m < M; m++) {
+ float vmin = sub_dis[i + m * n];
+ idx_t lmin = sub_ids[i + m * n];
+ dis += vmin;
+ label |= lmin << (m * pq.nbits);
+ }
+ distances[i] = dis;
+ labels[i] = label;
+ }
+
+ } else {
+#pragma omp parallel if (n > 1)
+ {
+ MinSumK<float, PreSortedArray<float>, false> msk(
+ K, pq.M, pq.nbits, k2);
+#pragma omp for
+ for (int i = 0; i < n; i++) {
+ idx_t* li = labels + i * K;
+ msk.run(&sub_dis[i * k2], k2 * n, distances + i * K, li);
+
+ // remap ids
+
+ const idx_t* idmap0 = sub_ids.data() + i * k2;
+ int64_t ld_idmap = k2 * n;
+ int64_t mask1 = ksub - (int64_t)1;
+
+ for (int k = 0; k < K; k++) {
+ const idx_t* idmap = idmap0;
+ int64_t vin = li[k];
+ int64_t vout = 0;
+ int bs = 0;
+ for (int m = 0; m < M; m++) {
+ int64_t s = vin & mask1;
+ vin >>= pq.nbits;
+ vout |= idmap[s] << bs;
+ bs += pq.nbits;
+ idmap += ld_idmap;
+ }
+ li[k] = vout;
+ }
+ }
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQ.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQ.h
new file mode 100644
index 0000000..2954f58
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQ.h
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_INDEX_PQ_H
+#define FAISS_INDEX_PQ_H
+
+#include <stdint.h>
+
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/impl/PolysemousTraining.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/** Index based on a product quantizer. Stored vectors are
+ * approximated by PQ codes. */
+struct IndexPQ : IndexFlatCodes {
+ /// The product quantizer used to encode the vectors
+ ProductQuantizer pq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ IndexPQ(int d, size_t M, size_t nbits, MetricType metric = METRIC_L2);
+
+ IndexPQ();
+
+ void train(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /* The standalone codec interface */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const override;
+
+ /******************************************************
+ * Polysemous codes implementation
+ ******************************************************/
+ bool do_polysemous_training; ///< false = standard PQ
+
+ /// parameters used for the polysemous training
+ PolysemousTraining polysemous_training;
+
+ /// how to perform the search in search_core
+ enum Search_type_t {
+ ST_PQ, ///< asymmetric product quantizer (default)
+ ST_HE, ///< Hamming distance on codes
+ ST_generalized_HE, ///< nb of same codes
+ ST_SDC, ///< symmetric product quantizer (SDC)
+ ST_polysemous, ///< HE filter (using ht) + PQ combination
+ ST_polysemous_generalize, ///< Filter on generalized Hamming
+ };
+
+ Search_type_t search_type;
+
+ // just encode the sign of the components, instead of using the PQ encoder
+ // used only for the queries
+ bool encode_signs;
+
+ /// Hamming threshold used for polysemy
+ int polysemous_ht;
+
+ // actual polysemous search
+ void search_core_polysemous(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ int polysemous_ht,
+ bool generalized_hamming) const;
+
+ /// prepare query for a polysemous search, but instead of
+ /// computing the result, just get the histogram of Hamming
+ /// distances. May be computed on a provided dataset if xb != NULL
+ /// @param dist_histogram (M * nbits + 1)
+ void hamming_distance_histogram(
+ idx_t n,
+ const float* x,
+ idx_t nb,
+ const float* xb,
+ int64_t* dist_histogram);
+
+ /** compute pairwise distances between queries and database
+ *
+ * @param n nb of query vectors
+ * @param x query vector, size n * d
+ * @param dis output distances, size n * ntotal
+ */
+ void hamming_distance_table(idx_t n, const float* x, int32_t* dis) const;
+};
+
+/// override search parameters from the class
+struct SearchParametersPQ : SearchParameters {
+ IndexPQ::Search_type_t search_type;
+ int polysemous_ht;
+};
+
+/// statistics are robust to internal threading, but not if
+/// IndexPQ::search is called by multiple threads
+struct IndexPQStats {
+ size_t nq; // nb of queries run
+ size_t ncode; // nb of codes visited
+
+ size_t n_hamming_pass; // nb of passed Hamming distance tests (for polysemy)
+
+ IndexPQStats() {
+ reset();
+ }
+ void reset();
+};
+
+FAISS_API extern IndexPQStats indexPQ_stats;
+
+/** Quantizer where centroids are virtual: they are the Cartesian
+ * product of sub-centroids. */
+struct MultiIndexQuantizer : Index {
+ ProductQuantizer pq;
+
+ MultiIndexQuantizer(
+ int d, ///< dimension of the input vectors
+ size_t M, ///< number of subquantizers
+ size_t nbits); ///< number of bit per subvector index
+
+ void train(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /// add and reset will crash at runtime
+ void add(idx_t n, const float* x) override;
+ void reset() override;
+
+ MultiIndexQuantizer() {}
+
+ void reconstruct(idx_t key, float* recons) const override;
+};
+
+// block size used in MultiIndexQuantizer::search
+FAISS_API extern int multi_index_quantizer_search_bs;
+
+/** MultiIndexQuantizer where the PQ assignmnet is performed by sub-indexes
+ */
+struct MultiIndexQuantizer2 : MultiIndexQuantizer {
+ /// M Indexes on d / M dimensions
+ std::vector<Index*> assign_indexes;
+ bool own_fields;
+
+ MultiIndexQuantizer2(int d, size_t M, size_t nbits, Index** indexes);
+
+ MultiIndexQuantizer2(
+ int d,
+ size_t nbits,
+ Index* assign_index_0,
+ Index* assign_index_1);
+
+ void train(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQFastScan.cpp
new file mode 100644
index 0000000..153a881
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQFastScan.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexPQFastScan.h>
+
+#include <cassert>
+#include <memory>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+inline size_t roundup(size_t a, size_t b) {
+ return (a + b - 1) / b * b;
+}
+
+IndexPQFastScan::IndexPQFastScan(
+ int d,
+ size_t M,
+ size_t nbits,
+ MetricType metric,
+ int bbs)
+ : pq(d, M, nbits) {
+ init_fastscan(d, M, nbits, metric, bbs);
+}
+
+IndexPQFastScan::IndexPQFastScan(const IndexPQ& orig, int bbs) : pq(orig.pq) {
+ init_fastscan(orig.d, pq.M, pq.nbits, orig.metric_type, bbs);
+ ntotal = orig.ntotal;
+ ntotal2 = roundup(ntotal, bbs);
+ is_trained = orig.is_trained;
+ orig_codes = orig.codes.data();
+
+ // pack the codes
+ codes.resize(ntotal2 * M2 / 2);
+ pq4_pack_codes(orig.codes.data(), ntotal, M, ntotal2, bbs, M2, codes.get());
+}
+
+void IndexPQFastScan::train(idx_t n, const float* x) {
+ if (is_trained) {
+ return;
+ }
+ pq.train(n, x);
+ is_trained = true;
+}
+
+void IndexPQFastScan::compute_codes(uint8_t* codes, idx_t n, const float* x)
+ const {
+ pq.compute_codes(x, codes, n);
+}
+
+void IndexPQFastScan::compute_float_LUT(float* lut, idx_t n, const float* x)
+ const {
+ if (metric_type == METRIC_L2) {
+ pq.compute_distance_tables(n, x, lut);
+ } else {
+ pq.compute_inner_prod_tables(n, x, lut);
+ }
+}
+
+void IndexPQFastScan::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ pq.decode(bytes, x, n);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQFastScan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQFastScan.h
new file mode 100644
index 0000000..be16239
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPQFastScan.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexFastScan.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+/** Fast scan version of IndexPQ. Works for 4-bit PQ for now.
+ *
+ * The codes are not stored sequentially but grouped in blocks of size bbs.
+ * This makes it possible to compute distances quickly with SIMD instructions.
+ *
+ * Implementations:
+ * 12: blocked loop with internal loop on Q with qbs
+ * 13: same with reservoir accumulator to store results
+ * 14: no qbs with heap accumulator
+ * 15: no qbs with reservoir accumulator
+ */
+
+struct IndexPQFastScan : IndexFastScan {
+ ProductQuantizer pq;
+
+ IndexPQFastScan(
+ int d,
+ size_t M,
+ size_t nbits,
+ MetricType metric = METRIC_L2,
+ int bbs = 32);
+
+ IndexPQFastScan() = default;
+
+ /// build from an existing IndexPQ
+ explicit IndexPQFastScan(const IndexPQ& orig, int bbs = 32);
+
+ void train(idx_t n, const float* x) override;
+
+ void compute_codes(uint8_t* codes, idx_t n, const float* x) const override;
+
+ void compute_float_LUT(float* lut, idx_t n, const float* x) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPreTransform.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPreTransform.cpp
new file mode 100644
index 0000000..a3b14c6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPreTransform.cpp
@@ -0,0 +1,337 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexPreTransform.h>
+
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+/*********************************************
+ * IndexPreTransform
+ *********************************************/
+
+IndexPreTransform::IndexPreTransform() : index(nullptr), own_fields(false) {}
+
+IndexPreTransform::IndexPreTransform(Index* index)
+ : Index(index->d, index->metric_type), index(index), own_fields(false) {
+ is_trained = index->is_trained;
+ ntotal = index->ntotal;
+}
+
+IndexPreTransform::IndexPreTransform(VectorTransform* ltrans, Index* index)
+ : Index(index->d, index->metric_type), index(index), own_fields(false) {
+ is_trained = index->is_trained;
+ ntotal = index->ntotal;
+ prepend_transform(ltrans);
+}
+
+void IndexPreTransform::prepend_transform(VectorTransform* ltrans) {
+ FAISS_THROW_IF_NOT(ltrans->d_out == d);
+ is_trained = is_trained && ltrans->is_trained;
+ chain.insert(chain.begin(), ltrans);
+ d = ltrans->d_in;
+}
+
+IndexPreTransform::~IndexPreTransform() {
+ if (own_fields) {
+ for (int i = 0; i < chain.size(); i++)
+ delete chain[i];
+ delete index;
+ }
+}
+
+void IndexPreTransform::train(idx_t n, const float* x) {
+ int last_untrained = 0;
+ if (!index->is_trained) {
+ last_untrained = chain.size();
+ } else {
+ for (int i = chain.size() - 1; i >= 0; i--) {
+ if (!chain[i]->is_trained) {
+ last_untrained = i;
+ break;
+ }
+ }
+ }
+ const float* prev_x = x;
+ std::unique_ptr<const float[]> del;
+
+ if (verbose) {
+ printf("IndexPreTransform::train: training chain 0 to %d\n",
+ last_untrained);
+ }
+
+ for (int i = 0; i <= last_untrained; i++) {
+ if (i < chain.size()) {
+ VectorTransform* ltrans = chain[i];
+ if (!ltrans->is_trained) {
+ if (verbose) {
+ printf(" Training chain component %d/%zd\n",
+ i,
+ chain.size());
+ if (OPQMatrix* opqm = dynamic_cast<OPQMatrix*>(ltrans)) {
+ opqm->verbose = true;
+ }
+ }
+ ltrans->train(n, prev_x);
+ }
+ } else {
+ if (verbose) {
+ printf(" Training sub-index\n");
+ }
+ index->train(n, prev_x);
+ }
+ if (i == last_untrained)
+ break;
+ if (verbose) {
+ printf(" Applying transform %d/%zd\n", i, chain.size());
+ }
+
+ float* xt = chain[i]->apply(n, prev_x);
+
+ if (prev_x != x) {
+ del.reset();
+ }
+
+ prev_x = xt;
+ del.reset(xt);
+ }
+
+ is_trained = true;
+}
+
+const float* IndexPreTransform::apply_chain(idx_t n, const float* x) const {
+ const float* prev_x = x;
+ std::unique_ptr<const float[]> del;
+
+ for (int i = 0; i < chain.size(); i++) {
+ float* xt = chain[i]->apply(n, prev_x);
+ std::unique_ptr<const float[]> del2(xt);
+ del2.swap(del);
+ prev_x = xt;
+ }
+ del.release();
+ return prev_x;
+}
+
+void IndexPreTransform::reverse_chain(idx_t n, const float* xt, float* x)
+ const {
+ const float* next_x = xt;
+ std::unique_ptr<const float[]> del;
+
+ for (int i = chain.size() - 1; i >= 0; i--) {
+ float* prev_x = (i == 0) ? x : new float[n * chain[i]->d_in];
+ std::unique_ptr<const float[]> del2((prev_x == x) ? nullptr : prev_x);
+ chain[i]->reverse_transform(n, next_x, prev_x);
+ del2.swap(del);
+ next_x = prev_x;
+ }
+}
+
+void IndexPreTransform::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT(is_trained);
+ TransformedVectors tv(x, apply_chain(n, x));
+ index->add(n, tv.x);
+ ntotal = index->ntotal;
+}
+
+void IndexPreTransform::add_with_ids(
+ idx_t n,
+ const float* x,
+ const idx_t* xids) {
+ FAISS_THROW_IF_NOT(is_trained);
+ TransformedVectors tv(x, apply_chain(n, x));
+ index->add_with_ids(n, tv.x, xids);
+ ntotal = index->ntotal;
+}
+
+namespace {
+
+const SearchParameters* extract_index_search_params(
+ const SearchParameters* params_in) {
+ auto params = dynamic_cast<const SearchParametersPreTransform*>(params_in);
+ return params ? params->index_params : params_in;
+}
+
+} // namespace
+
+void IndexPreTransform::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+ const float* xt = apply_chain(n, x);
+ std::unique_ptr<const float[]> del(xt == x ? nullptr : xt);
+ index->search(
+ n, xt, k, distances, labels, extract_index_search_params(params));
+}
+
+void IndexPreTransform::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(is_trained);
+ TransformedVectors tv(x, apply_chain(n, x));
+ index->range_search(
+ n, tv.x, radius, result, extract_index_search_params(params));
+}
+
+void IndexPreTransform::reset() {
+ index->reset();
+ ntotal = 0;
+}
+
+size_t IndexPreTransform::remove_ids(const IDSelector& sel) {
+ size_t nremove = index->remove_ids(sel);
+ ntotal = index->ntotal;
+ return nremove;
+}
+
+void IndexPreTransform::reconstruct(idx_t key, float* recons) const {
+ float* x = chain.empty() ? recons : new float[index->d];
+ std::unique_ptr<float[]> del(recons == x ? nullptr : x);
+ // Initial reconstruction
+ index->reconstruct(key, x);
+
+ // Revert transformations from last to first
+ reverse_chain(1, x, recons);
+}
+
+void IndexPreTransform::reconstruct_n(idx_t i0, idx_t ni, float* recons) const {
+ float* x = chain.empty() ? recons : new float[ni * index->d];
+ std::unique_ptr<float[]> del(recons == x ? nullptr : x);
+ // Initial reconstruction
+ index->reconstruct_n(i0, ni, x);
+
+ // Revert transformations from last to first
+ reverse_chain(ni, x, recons);
+}
+
+void IndexPreTransform::search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+
+ TransformedVectors trans(x, apply_chain(n, x));
+
+ float* recons_temp = chain.empty() ? recons : new float[n * k * index->d];
+ std::unique_ptr<float[]> del2(
+ (recons_temp == recons) ? nullptr : recons_temp);
+ index->search_and_reconstruct(
+ n,
+ trans.x,
+ k,
+ distances,
+ labels,
+ recons_temp,
+ extract_index_search_params(params));
+
+ // Revert transformations from last to first
+ reverse_chain(n * k, recons_temp, recons);
+}
+
+size_t IndexPreTransform::sa_code_size() const {
+ return index->sa_code_size();
+}
+
+void IndexPreTransform::sa_encode(idx_t n, const float* x, uint8_t* bytes)
+ const {
+ TransformedVectors tv(x, apply_chain(n, x));
+ index->sa_encode(n, tv.x, bytes);
+}
+
+void IndexPreTransform::sa_decode(idx_t n, const uint8_t* bytes, float* x)
+ const {
+ if (chain.empty()) {
+ index->sa_decode(n, bytes, x);
+ } else {
+ std::unique_ptr<float[]> x1(new float[index->d * n]);
+ index->sa_decode(n, bytes, x1.get());
+ // Revert transformations from last to first
+ reverse_chain(n, x1.get(), x);
+ }
+}
+
+void IndexPreTransform::merge_from(Index& otherIndex, idx_t add_id) {
+ check_compatible_for_merge(otherIndex);
+ auto other = static_cast<const IndexPreTransform*>(&otherIndex);
+ index->merge_from(*other->index, add_id);
+ ntotal = index->ntotal;
+}
+
+void IndexPreTransform::check_compatible_for_merge(
+ const Index& otherIndex) const {
+ auto other = dynamic_cast<const IndexPreTransform*>(&otherIndex);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(chain.size() == other->chain.size());
+ for (int i = 0; i < chain.size(); i++) {
+ chain[i]->check_identical(*other->chain[i]);
+ }
+ index->check_compatible_for_merge(*other->index);
+}
+
+namespace {
+
+struct PreTransformDistanceComputer : DistanceComputer {
+ const IndexPreTransform* index;
+ std::unique_ptr<DistanceComputer> sub_dc;
+ std::unique_ptr<const float[]> query;
+
+ explicit PreTransformDistanceComputer(const IndexPreTransform* index)
+ : index(index), sub_dc(index->index->get_distance_computer()) {}
+
+ void set_query(const float* x) override {
+ const float* xt = index->apply_chain(1, x);
+ if (xt == x) {
+ sub_dc->set_query(x);
+ } else {
+ query.reset(xt);
+ sub_dc->set_query(xt);
+ }
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return sub_dc->symmetric_dis(i, j);
+ }
+
+ float operator()(idx_t i) override {
+ return (*sub_dc)(i);
+ }
+};
+
+} // anonymous namespace
+
+DistanceComputer* IndexPreTransform::get_distance_computer() const {
+ if (chain.empty()) {
+ return index->get_distance_computer();
+ } else {
+ return new PreTransformDistanceComputer(this);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPreTransform.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPreTransform.h
new file mode 100644
index 0000000..31db101
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexPreTransform.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/VectorTransform.h>
+
+namespace faiss {
+
+struct SearchParametersPreTransform : SearchParameters {
+ // nothing to add here.
+ // as such, encapsulating the search params is considered optional
+ SearchParameters* index_params = nullptr;
+};
+
+/** Index that applies a LinearTransform transform on vectors before
+ * handing them over to a sub-index */
+struct IndexPreTransform : Index {
+ std::vector<VectorTransform*> chain; ///! chain of transforms
+ Index* index; ///! the sub-index
+
+ bool own_fields; ///! whether pointers are deleted in destructor
+
+ explicit IndexPreTransform(Index* index);
+
+ IndexPreTransform();
+
+ /// ltrans is the last transform before the index
+ IndexPreTransform(VectorTransform* ltrans, Index* index);
+
+ void prepend_transform(VectorTransform* ltrans);
+
+ void train(idx_t n, const float* x) override;
+
+ void add(idx_t n, const float* x) override;
+
+ void add_with_ids(idx_t n, const float* x, const idx_t* xids) override;
+
+ void reset() override;
+
+ /** removes IDs from the index. Not supported by all indexes.
+ */
+ size_t remove_ids(const IDSelector& sel) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /* range search, no attempt is done to change the radius */
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ void reconstruct_n(idx_t i0, idx_t ni, float* recons) const override;
+
+ void search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params = nullptr) const override;
+
+ /// apply the transforms in the chain. The returned float * may be
+ /// equal to x, otherwise it should be deallocated.
+ const float* apply_chain(idx_t n, const float* x) const;
+
+ /// Reverse the transforms in the chain. May not be implemented for
+ /// all transforms in the chain or may return approximate results.
+ void reverse_chain(idx_t n, const float* xt, float* x) const;
+
+ DistanceComputer* get_distance_computer() const override;
+
+ /* standalone codec interface */
+ size_t sa_code_size() const override;
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ void merge_from(Index& otherIndex, idx_t add_id = 0) override;
+ void check_compatible_for_merge(const Index& otherIndex) const override;
+
+ ~IndexPreTransform() override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRaBitQ.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRaBitQ.cpp
new file mode 100644
index 0000000..c4025c4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRaBitQ.cpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexRaBitQ.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResultHandler.h>
+
+namespace faiss {
+
+IndexRaBitQ::IndexRaBitQ() = default;
+
+IndexRaBitQ::IndexRaBitQ(idx_t d, MetricType metric)
+ : IndexFlatCodes(0, d, metric), rabitq(d, metric) {
+ code_size = rabitq.code_size;
+
+ is_trained = false;
+}
+
+void IndexRaBitQ::train(idx_t n, const float* x) {
+ // compute a centroid
+ std::vector<float> centroid(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < d; j++) {
+ centroid[j] += x[i * d + j];
+ }
+ }
+
+ if (n != 0) {
+ for (size_t j = 0; j < d; j++) {
+ centroid[j] /= (float)n;
+ }
+ }
+
+ center = std::move(centroid);
+
+ //
+ rabitq.train(n, x);
+ is_trained = true;
+}
+
+void IndexRaBitQ::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ FAISS_THROW_IF_NOT(is_trained);
+ rabitq.compute_codes_core(x, bytes, n, center.data());
+}
+
+void IndexRaBitQ::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ FAISS_THROW_IF_NOT(is_trained);
+ rabitq.decode_core(bytes, x, n, center.data());
+}
+
+FlatCodesDistanceComputer* IndexRaBitQ::get_FlatCodesDistanceComputer() const {
+ FlatCodesDistanceComputer* dc =
+ rabitq.get_distance_computer(qb, center.data());
+ dc->code_size = rabitq.code_size;
+ dc->codes = codes.data();
+ return dc;
+}
+
+FlatCodesDistanceComputer* IndexRaBitQ::get_quantized_distance_computer(
+ const uint8_t qb) const {
+ FlatCodesDistanceComputer* dc =
+ rabitq.get_distance_computer(qb, center.data());
+ dc->code_size = rabitq.code_size;
+ dc->codes = codes.data();
+ return dc;
+}
+
+namespace {
+
+struct Run_search_with_dc_res {
+ using T = void;
+
+ uint8_t qb = 0;
+
+ template <class BlockResultHandler>
+ void f(BlockResultHandler& res, const IndexRaBitQ* index, const float* xq) {
+ size_t ntotal = index->ntotal;
+ using SingleResultHandler =
+ typename BlockResultHandler::SingleResultHandler;
+ const int d = index->d;
+
+#pragma omp parallel // if (res.nq > 100)
+ {
+ std::unique_ptr<FlatCodesDistanceComputer> dc(
+ index->get_quantized_distance_computer(qb));
+ SingleResultHandler resi(res);
+#pragma omp for
+ for (int64_t q = 0; q < res.nq; q++) {
+ resi.begin(q);
+ dc->set_query(xq + d * q);
+ for (size_t i = 0; i < ntotal; i++) {
+ if (res.is_in_selection(i)) {
+ float dis = (*dc)(i);
+ resi.add_result(dis, i);
+ }
+ }
+ resi.end();
+ }
+ }
+ }
+};
+
+} // namespace
+
+void IndexRaBitQ::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ uint8_t used_qb = qb;
+ if (auto params = dynamic_cast<const RaBitQSearchParameters*>(params_in)) {
+ used_qb = params->qb;
+ }
+
+ const IDSelector* sel = (params_in != nullptr) ? params_in->sel : nullptr;
+ Run_search_with_dc_res r;
+ r.qb = used_qb;
+
+ dispatch_knn_ResultHandler(
+ n, distances, labels, k, metric_type, sel, r, this, x);
+}
+
+void IndexRaBitQ::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params_in) const {
+ uint8_t used_qb = qb;
+ if (auto params = dynamic_cast<const RaBitQSearchParameters*>(params_in)) {
+ used_qb = params->qb;
+ }
+
+ const IDSelector* sel = (params_in != nullptr) ? params_in->sel : nullptr;
+ Run_search_with_dc_res r;
+ r.qb = used_qb;
+
+ dispatch_range_ResultHandler(result, radius, metric_type, sel, r, this, x);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRaBitQ.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRaBitQ.h
new file mode 100644
index 0000000..8d2cb47
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRaBitQ.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/impl/RaBitQuantizer.h>
+
+namespace faiss {
+
+struct RaBitQSearchParameters : SearchParameters {
+ uint8_t qb = 0;
+};
+
+struct IndexRaBitQ : IndexFlatCodes {
+ RaBitQuantizer rabitq;
+
+ // center of all points
+ std::vector<float> center;
+
+ // the default number of bits to quantize a query with.
+ // use '0' to disable quantization and use raw fp32 values.
+ uint8_t qb = 0;
+
+ IndexRaBitQ();
+
+ IndexRaBitQ(idx_t d, MetricType metric = METRIC_L2);
+
+ void train(idx_t n, const float* x) override;
+
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ // returns a quantized-to-qb bits DC if qb > 0
+ // returns a default fp32-based DC if qb == 0
+ FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const override;
+
+ // returns a quantized-to-qb bits DC if qb_in > 0
+ // returns a default fp32-based DC if qb_in == 0
+ FlatCodesDistanceComputer* get_quantized_distance_computer(
+ const uint8_t qb_in) const;
+
+ // Don't rely on sa_decode(), bcz it is good for IP, but not for L2.
+ // As a result, use get_FlatCodesDistanceComputer() for the search.
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRefine.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRefine.cpp
new file mode 100644
index 0000000..6f1f588
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRefine.cpp
@@ -0,0 +1,339 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexRefine.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+/***************************************************
+ * IndexRefine
+ ***************************************************/
+
+IndexRefine::IndexRefine(Index* base_index, Index* refine_index)
+ : Index(base_index->d, base_index->metric_type),
+ base_index(base_index),
+ refine_index(refine_index) {
+ own_fields = own_refine_index = false;
+ if (refine_index != nullptr) {
+ FAISS_THROW_IF_NOT(base_index->d == refine_index->d);
+ FAISS_THROW_IF_NOT(
+ base_index->metric_type == refine_index->metric_type);
+ is_trained = base_index->is_trained && refine_index->is_trained;
+ FAISS_THROW_IF_NOT(base_index->ntotal == refine_index->ntotal);
+ } // other case is useful only to construct an IndexRefineFlat
+ ntotal = base_index->ntotal;
+}
+
+IndexRefine::IndexRefine()
+ : base_index(nullptr),
+ refine_index(nullptr),
+ own_fields(false),
+ own_refine_index(false) {}
+
+void IndexRefine::train(idx_t n, const float* x) {
+ base_index->train(n, x);
+ refine_index->train(n, x);
+ is_trained = true;
+}
+
+void IndexRefine::add(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT(is_trained);
+ base_index->add(n, x);
+ refine_index->add(n, x);
+ ntotal = refine_index->ntotal;
+}
+
+void IndexRefine::reset() {
+ base_index->reset();
+ refine_index->reset();
+ ntotal = 0;
+}
+
+namespace {
+
+using idx_t = faiss::idx_t;
+
+template <class C>
+static void reorder_2_heaps(
+ idx_t n,
+ idx_t k,
+ idx_t* __restrict labels,
+ float* __restrict distances,
+ idx_t k_base,
+ const idx_t* __restrict base_labels,
+ const float* __restrict base_distances) {
+#pragma omp parallel for if (n > 1)
+ for (idx_t i = 0; i < n; i++) {
+ idx_t* idxo = labels + i * k;
+ float* diso = distances + i * k;
+ const idx_t* idxi = base_labels + i * k_base;
+ const float* disi = base_distances + i * k_base;
+
+ heap_heapify<C>(k, diso, idxo, disi, idxi, k);
+ if (k_base != k) { // add remaining elements
+ heap_addn<C>(k, diso, idxo, disi + k, idxi + k, k_base - k);
+ }
+ heap_reorder<C>(k, diso, idxo);
+ }
+}
+
+} // anonymous namespace
+
+void IndexRefine::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ const IndexRefineSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IndexRefineSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(
+ params, "IndexRefine params have incorrect type");
+ }
+
+ idx_t k_base = (params != nullptr) ? idx_t(k * params->k_factor)
+ : idx_t(k * k_factor);
+ SearchParameters* base_index_params =
+ (params != nullptr) ? params->base_index_params : nullptr;
+
+ FAISS_THROW_IF_NOT(k_base >= k);
+
+ FAISS_THROW_IF_NOT(base_index);
+ FAISS_THROW_IF_NOT(refine_index);
+
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+ idx_t* base_labels = labels;
+ float* base_distances = distances;
+ std::unique_ptr<idx_t[]> del1;
+ std::unique_ptr<float[]> del2;
+
+ if (k != k_base) {
+ base_labels = new idx_t[n * k_base];
+ del1.reset(base_labels);
+ base_distances = new float[n * k_base];
+ del2.reset(base_distances);
+ }
+
+ base_index->search(
+ n, x, k_base, base_distances, base_labels, base_index_params);
+
+ for (int i = 0; i < n * k_base; i++)
+ assert(base_labels[i] >= -1 && base_labels[i] < ntotal);
+
+ // parallelize over queries
+#pragma omp parallel if (n > 1)
+ {
+ std::unique_ptr<DistanceComputer> dc(
+ refine_index->get_distance_computer());
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ dc->set_query(x + i * d);
+ idx_t ij = i * k_base;
+ for (idx_t j = 0; j < k_base; j++) {
+ idx_t idx = base_labels[ij];
+ if (idx < 0)
+ break;
+ base_distances[ij] = (*dc)(idx);
+ ij++;
+ }
+ }
+ }
+
+ // sort and store result
+ if (metric_type == METRIC_L2) {
+ typedef CMax<float, idx_t> C;
+ reorder_2_heaps<C>(
+ n, k, labels, distances, k_base, base_labels, base_distances);
+
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ typedef CMin<float, idx_t> C;
+ reorder_2_heaps<C>(
+ n, k, labels, distances, k_base, base_labels, base_distances);
+ } else {
+ FAISS_THROW_MSG("Metric type not supported");
+ }
+}
+
+void IndexRefine::range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params_in) const {
+ const IndexRefineSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IndexRefineSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(
+ params, "IndexRefine params have incorrect type");
+ }
+
+ SearchParameters* base_index_params =
+ (params != nullptr) ? params->base_index_params : nullptr;
+
+ base_index->range_search(n, x, radius, result, base_index_params);
+
+#pragma omp parallel if (n > 1)
+ {
+ std::unique_ptr<DistanceComputer> dc(
+ refine_index->get_distance_computer());
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ dc->set_query(x + i * d);
+
+ // reevaluate distances
+ const size_t idx_start = result->lims[i];
+ const size_t idx_end = result->lims[i + 1];
+
+ for (size_t j = idx_start; j < idx_end; j++) {
+ const auto label = result->labels[j];
+ result->distances[j] = (*dc)(label);
+ }
+ }
+ }
+}
+
+void IndexRefine::reconstruct(idx_t key, float* recons) const {
+ refine_index->reconstruct(key, recons);
+}
+
+size_t IndexRefine::sa_code_size() const {
+ return base_index->sa_code_size() + refine_index->sa_code_size();
+}
+
+void IndexRefine::sa_encode(idx_t n, const float* x, uint8_t* bytes) const {
+ size_t cs1 = base_index->sa_code_size(), cs2 = refine_index->sa_code_size();
+ std::unique_ptr<uint8_t[]> tmp1(new uint8_t[n * cs1]);
+ base_index->sa_encode(n, x, tmp1.get());
+ std::unique_ptr<uint8_t[]> tmp2(new uint8_t[n * cs2]);
+ refine_index->sa_encode(n, x, tmp2.get());
+ for (size_t i = 0; i < n; i++) {
+ uint8_t* b = bytes + i * (cs1 + cs2);
+ memcpy(b, tmp1.get() + cs1 * i, cs1);
+ memcpy(b + cs1, tmp2.get() + cs2 * i, cs2);
+ }
+}
+
+void IndexRefine::sa_decode(idx_t n, const uint8_t* bytes, float* x) const {
+ size_t cs1 = base_index->sa_code_size(), cs2 = refine_index->sa_code_size();
+ std::unique_ptr<uint8_t[]> tmp2(
+ new uint8_t[n * refine_index->sa_code_size()]);
+ for (size_t i = 0; i < n; i++) {
+ memcpy(tmp2.get() + i * cs2, bytes + i * (cs1 + cs2), cs2);
+ }
+
+ refine_index->sa_decode(n, tmp2.get(), x);
+}
+
+IndexRefine::~IndexRefine() {
+ if (own_fields)
+ delete base_index;
+ if (own_refine_index)
+ delete refine_index;
+}
+
+/***************************************************
+ * IndexRefineFlat
+ ***************************************************/
+
+IndexRefineFlat::IndexRefineFlat(Index* base_index)
+ : IndexRefine(
+ base_index,
+ new IndexFlat(base_index->d, base_index->metric_type)) {
+ is_trained = base_index->is_trained;
+ own_refine_index = true;
+ FAISS_THROW_IF_NOT_MSG(
+ base_index->ntotal == 0,
+ "base_index should be empty in the beginning");
+}
+
+IndexRefineFlat::IndexRefineFlat(Index* base_index, const float* xb)
+ : IndexRefine(base_index, nullptr) {
+ is_trained = base_index->is_trained;
+ refine_index = new IndexFlat(base_index->d, base_index->metric_type);
+ own_refine_index = true;
+ refine_index->add(base_index->ntotal, xb);
+}
+
+IndexRefineFlat::IndexRefineFlat() : IndexRefine() {
+ own_refine_index = true;
+}
+
+void IndexRefineFlat::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ const IndexRefineSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IndexRefineSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(
+ params, "IndexRefineFlat params have incorrect type");
+ }
+
+ idx_t k_base = (params != nullptr) ? idx_t(k * params->k_factor)
+ : idx_t(k * k_factor);
+ SearchParameters* base_index_params =
+ (params != nullptr) ? params->base_index_params : nullptr;
+
+ FAISS_THROW_IF_NOT(k_base >= k);
+
+ FAISS_THROW_IF_NOT(base_index);
+ FAISS_THROW_IF_NOT(refine_index);
+
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+ idx_t* base_labels = labels;
+ float* base_distances = distances;
+ std::unique_ptr<idx_t[]> del1;
+ std::unique_ptr<float[]> del2;
+
+ if (k != k_base) {
+ base_labels = new idx_t[n * k_base];
+ del1.reset(base_labels);
+ base_distances = new float[n * k_base];
+ del2.reset(base_distances);
+ }
+
+ base_index->search(
+ n, x, k_base, base_distances, base_labels, base_index_params);
+
+ for (int i = 0; i < n * k_base; i++)
+ assert(base_labels[i] >= -1 && base_labels[i] < ntotal);
+
+ // compute refined distances
+ auto rf = dynamic_cast<const IndexFlat*>(refine_index);
+ FAISS_THROW_IF_NOT(rf);
+
+ rf->compute_distance_subset(n, x, k_base, base_distances, base_labels);
+
+ // sort and store result
+ if (metric_type == METRIC_L2) {
+ typedef CMax<float, idx_t> C;
+ reorder_2_heaps<C>(
+ n, k, labels, distances, k_base, base_labels, base_distances);
+
+ } else if (metric_type == METRIC_INNER_PRODUCT) {
+ typedef CMin<float, idx_t> C;
+ reorder_2_heaps<C>(
+ n, k, labels, distances, k_base, base_labels, base_distances);
+ } else {
+ FAISS_THROW_MSG("Metric type not supported");
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRefine.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRefine.h
new file mode 100644
index 0000000..2552716
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRefine.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+
+namespace faiss {
+
+struct IndexRefineSearchParameters : SearchParameters {
+ float k_factor = 1;
+ SearchParameters* base_index_params = nullptr; // non-owning
+
+ virtual ~IndexRefineSearchParameters() = default;
+};
+
+/** Index that queries in a base_index (a fast one) and refines the
+ * results with an exact search, hopefully improving the results.
+ */
+struct IndexRefine : Index {
+ /// faster index to pre-select the vectors that should be filtered
+ Index* base_index;
+
+ /// refinement index
+ Index* refine_index;
+
+ bool own_fields; ///< should the base index be deallocated?
+ bool own_refine_index; ///< same with the refinement index
+
+ /// factor between k requested in search and the k requested from
+ /// the base_index (should be >= 1)
+ float k_factor = 1;
+
+ /// initialize from empty index
+ IndexRefine(Index* base_index, Index* refine_index);
+
+ IndexRefine();
+
+ void train(idx_t n, const float* x) override;
+
+ void add(idx_t n, const float* x) override;
+
+ void reset() override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void range_search(
+ idx_t n,
+ const float* x,
+ float radius,
+ RangeSearchResult* result,
+ const SearchParameters* params = nullptr) const override;
+
+ // reconstruct is routed to the refine_index
+ void reconstruct(idx_t key, float* recons) const override;
+
+ /* standalone codec interface: the base_index codes are interleaved with the
+ * refine_index ones */
+ size_t sa_code_size() const override;
+
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ /// The sa_decode decodes from the index_refine, which is assumed to be more
+ /// accurate
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+
+ ~IndexRefine() override;
+};
+
+/** Version where the refinement index is an IndexFlat. It has one additional
+ * constructor that takes a table of elements to add to the flat refinement
+ * index */
+struct IndexRefineFlat : IndexRefine {
+ explicit IndexRefineFlat(Index* base_index);
+ IndexRefineFlat(Index* base_index, const float* xb);
+
+ IndexRefineFlat();
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexReplicas.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexReplicas.cpp
new file mode 100644
index 0000000..91dd0d2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexReplicas.cpp
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cinttypes>
+
+#include <faiss/IndexReplicas.h>
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+namespace {
+
+// IndexBinary needs to update the code_size when d is set...
+
+void sync_d(Index* index) {}
+
+void sync_d(IndexBinary* index) {
+ FAISS_THROW_IF_NOT(index->d % 8 == 0);
+ index->code_size = index->d / 8;
+}
+
+} // anonymous namespace
+
+template <typename IndexT>
+IndexReplicasTemplate<IndexT>::IndexReplicasTemplate(bool threaded)
+ : ThreadedIndex<IndexT>(threaded) {}
+
+template <typename IndexT>
+IndexReplicasTemplate<IndexT>::IndexReplicasTemplate(idx_t d, bool threaded)
+ : ThreadedIndex<IndexT>(d, threaded) {
+ sync_d(this);
+}
+
+template <typename IndexT>
+IndexReplicasTemplate<IndexT>::IndexReplicasTemplate(int d, bool threaded)
+ : ThreadedIndex<IndexT>(d, threaded) {
+ sync_d(this);
+}
+
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::onAfterAddIndex(IndexT* index) {
+ // Make sure that the parameters are the same for all prior indices, unless
+ // we're the first index to be added
+ if (this->count() > 0 && this->at(0) != index) {
+ auto existing = this->at(0);
+
+ FAISS_THROW_IF_NOT_FMT(
+ index->ntotal == existing->ntotal,
+ "IndexReplicas: newly added index does "
+ "not have same number of vectors as prior index; "
+ "prior index has %" PRId64 " vectors, new index has %" PRId64,
+ existing->ntotal,
+ index->ntotal);
+
+ FAISS_THROW_IF_NOT_MSG(
+ index->is_trained == existing->is_trained,
+ "IndexReplicas: newly added index does "
+ "not have same train status as prior index");
+
+ FAISS_THROW_IF_NOT_MSG(
+ index->d == existing->d,
+ "IndexReplicas: newly added index does "
+ "not have same dimension as prior index");
+ } else {
+ syncWithSubIndexes();
+ }
+}
+
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::onAfterRemoveIndex(IndexT* index) {
+ syncWithSubIndexes();
+}
+
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::train(idx_t n, const component_t* x) {
+ auto fn = [n, x](int i, IndexT* index) {
+ if (index->verbose) {
+ printf("begin train replica %d on %" PRId64 " points\n", i, n);
+ }
+
+ index->train(n, x);
+
+ if (index->verbose) {
+ printf("end train replica %d\n", i);
+ }
+ };
+
+ this->runOnIndex(fn);
+ syncWithSubIndexes();
+}
+
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::add(idx_t n, const component_t* x) {
+ auto fn = [n, x](int i, IndexT* index) {
+ if (index->verbose) {
+ printf("begin add replica %d on %" PRId64 " points\n", i, n);
+ }
+
+ index->add(n, x);
+
+ if (index->verbose) {
+ printf("end add replica %d\n", i);
+ }
+ };
+
+ this->runOnIndex(fn);
+ syncWithSubIndexes();
+}
+
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::reconstruct(idx_t n, component_t* x) const {
+ FAISS_THROW_IF_NOT_MSG(this->count() > 0, "no replicas in index");
+
+ // Just pass to the first replica
+ this->at(0)->reconstruct(n, x);
+}
+
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT_MSG(this->count() > 0, "no replicas in index");
+
+ if (n == 0) {
+ return;
+ }
+
+ auto dim = this->d;
+ size_t componentsPerVec = sizeof(component_t) == 1 ? (dim + 7) / 8 : dim;
+
+ // Partition the query by the number of indices we have
+ faiss::idx_t queriesPerIndex =
+ (faiss::idx_t)(n + this->count() - 1) / (faiss::idx_t)this->count();
+ FAISS_ASSERT(n / queriesPerIndex <= this->count());
+
+ auto fn = [queriesPerIndex, componentsPerVec, n, x, k, distances, labels](
+ int i, const IndexT* index) {
+ faiss::idx_t base = (faiss::idx_t)i * queriesPerIndex;
+
+ if (base < n) {
+ auto numForIndex = std::min(queriesPerIndex, n - base);
+
+ if (index->verbose) {
+ printf("begin search replica %d on %" PRId64 " points\n",
+ i,
+ numForIndex);
+ }
+
+ index->search(
+ numForIndex,
+ x + base * componentsPerVec,
+ k,
+ distances + base * k,
+ labels + base * k);
+
+ if (index->verbose) {
+ printf("end search replica %d\n", i);
+ }
+ }
+ };
+
+ this->runOnIndex(fn);
+}
+
+// FIXME: assumes that nothing is currently running on the sub-indexes, which is
+// true with the normal API, but should use the runOnIndex API instead
+template <typename IndexT>
+void IndexReplicasTemplate<IndexT>::syncWithSubIndexes() {
+ if (!this->count()) {
+ this->is_trained = false;
+ this->ntotal = 0;
+
+ return;
+ }
+
+ auto firstIndex = this->at(0);
+ this->d = firstIndex->d;
+ sync_d(this);
+ this->metric_type = firstIndex->metric_type;
+ this->is_trained = firstIndex->is_trained;
+ this->ntotal = firstIndex->ntotal;
+
+ for (int i = 1; i < this->count(); ++i) {
+ auto index = this->at(i);
+ FAISS_THROW_IF_NOT(this->metric_type == index->metric_type);
+ FAISS_THROW_IF_NOT(this->d == index->d);
+ FAISS_THROW_IF_NOT(this->is_trained == index->is_trained);
+ FAISS_THROW_IF_NOT(this->ntotal == index->ntotal);
+ }
+}
+
+// explicit instantiations
+template class IndexReplicasTemplate<Index>;
+template class IndexReplicasTemplate<IndexBinary>;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexReplicas.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexReplicas.h
new file mode 100644
index 0000000..c3430ee
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexReplicas.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/impl/ThreadedIndex.h>
+
+namespace faiss {
+
+/// Takes individual faiss::Index instances, and splits queries for
+/// sending to each Index instance, and joins the results together
+/// when done.
+/// Each index is managed by a separate CPU thread.
+template <typename IndexT>
+class IndexReplicasTemplate : public ThreadedIndex<IndexT> {
+ public:
+ using component_t = typename IndexT::component_t;
+ using distance_t = typename IndexT::distance_t;
+
+ /// The dimension that all sub-indices must share will be the dimension of
+ /// the first sub-index added
+ /// @param threaded do we use one thread per sub-index or do queries
+ /// sequentially?
+ explicit IndexReplicasTemplate(bool threaded = true);
+
+ /// @param d the dimension that all sub-indices must share
+ /// @param threaded do we use one thread per sub index or do queries
+ /// sequentially?
+ explicit IndexReplicasTemplate(idx_t d, bool threaded = true);
+
+ /// int version due to the implicit bool conversion ambiguity of int as
+ /// dimension
+ explicit IndexReplicasTemplate(int d, bool threaded = true);
+
+ /// Alias for addIndex()
+ void add_replica(IndexT* index) {
+ this->addIndex(index);
+ }
+
+ /// Alias for removeIndex()
+ void remove_replica(IndexT* index) {
+ this->removeIndex(index);
+ }
+
+ /// faiss::Index API
+ /// All indices receive the same call
+ void train(idx_t n, const component_t* x) override;
+
+ /// faiss::Index API
+ /// All indices receive the same call
+ void add(idx_t n, const component_t* x) override;
+
+ /// faiss::Index API
+ /// Query is partitioned into a slice for each sub-index
+ /// split by ceil(n / #indices) for our sub-indices
+ void search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /// reconstructs from the first index
+ void reconstruct(idx_t, component_t* v) const override;
+
+ /// Synchronize the top-level index (IndexShards) with data in the
+ /// sub-indices
+ void syncWithSubIndexes();
+
+ protected:
+ /// Called just after an index is added
+ void onAfterAddIndex(IndexT* index) override;
+
+ /// Called just after an index is removed
+ void onAfterRemoveIndex(IndexT* index) override;
+};
+
+using IndexReplicas = IndexReplicasTemplate<Index>;
+using IndexBinaryReplicas = IndexReplicasTemplate<IndexBinary>;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRowwiseMinMax.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRowwiseMinMax.cpp
new file mode 100644
index 0000000..10fac48
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRowwiseMinMax.cpp
@@ -0,0 +1,445 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexRowwiseMinMax.h>
+
+#include <cstdint>
+#include <cstring>
+#include <limits>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/fp16.h>
+
+namespace faiss {
+
+namespace {
+
+using idx_t = faiss::idx_t;
+
+struct StorageMinMaxFP16 {
+ uint16_t scaler;
+ uint16_t minv;
+
+ inline void from_floats(const float float_scaler, const float float_minv) {
+ scaler = encode_fp16(float_scaler);
+ minv = encode_fp16(float_minv);
+ }
+
+ inline void to_floats(float& float_scaler, float& float_minv) const {
+ float_scaler = decode_fp16(scaler);
+ float_minv = decode_fp16(minv);
+ }
+};
+
+struct StorageMinMaxFP32 {
+ float scaler;
+ float minv;
+
+ inline void from_floats(const float float_scaler, const float float_minv) {
+ scaler = float_scaler;
+ minv = float_minv;
+ }
+
+ inline void to_floats(float& float_scaler, float& float_minv) const {
+ float_scaler = scaler;
+ float_minv = minv;
+ }
+};
+
+template <typename StorageMinMaxT>
+void sa_encode_impl(
+ const IndexRowwiseMinMaxBase* const index,
+ const idx_t n_input,
+ const float* x_input,
+ uint8_t* bytes_output) {
+ // process chunks
+ const size_t chunk_size = rowwise_minmax_sa_encode_bs;
+
+ // useful variables
+ const Index* const sub_index = index->index;
+ const int d = index->d;
+
+ // the code size of the subindex
+ const size_t old_code_size = sub_index->sa_code_size();
+ // the code size of the index
+ const size_t new_code_size = index->sa_code_size();
+
+ // allocate tmp buffers
+ std::vector<float> tmp(chunk_size * d);
+ std::vector<StorageMinMaxT> minmax(chunk_size);
+
+ // all the elements to process
+ size_t n_left = n_input;
+
+ const float* __restrict x = x_input;
+ uint8_t* __restrict bytes = bytes_output;
+
+ while (n_left > 0) {
+ // current portion to be processed
+ const idx_t n = std::min(n_left, chunk_size);
+
+ // allocate a temporary buffer and do the rescale
+ for (idx_t i = 0; i < n; i++) {
+ // compute min & max values
+ float minv = std::numeric_limits<float>::max();
+ float maxv = std::numeric_limits<float>::lowest();
+
+ const float* const vec_in = x + i * d;
+ for (idx_t j = 0; j < d; j++) {
+ minv = std::min(minv, vec_in[j]);
+ maxv = std::max(maxv, vec_in[j]);
+ }
+
+ // save the coefficients
+ const float scaler = maxv - minv;
+ minmax[i].from_floats(scaler, minv);
+
+ // and load them back, because the coefficients might
+ // be modified.
+ float actual_scaler = 0;
+ float actual_minv = 0;
+ minmax[i].to_floats(actual_scaler, actual_minv);
+
+ float* const vec_out = tmp.data() + i * d;
+ if (actual_scaler == 0) {
+ for (idx_t j = 0; j < d; j++) {
+ vec_out[j] = 0;
+ }
+ } else {
+ float inv_actual_scaler = 1.0f / actual_scaler;
+ for (idx_t j = 0; j < d; j++) {
+ vec_out[j] = (vec_in[j] - actual_minv) * inv_actual_scaler;
+ }
+ }
+ }
+
+ // do the coding
+ sub_index->sa_encode(n, tmp.data(), bytes);
+
+ // rearrange
+ for (idx_t i = n; (i--) > 0;) {
+ // move a single index
+ std::memmove(
+ bytes + i * new_code_size + (new_code_size - old_code_size),
+ bytes + i * old_code_size,
+ old_code_size);
+
+ // save min & max values
+ StorageMinMaxT* fpv = reinterpret_cast<StorageMinMaxT*>(
+ bytes + i * new_code_size);
+ *fpv = minmax[i];
+ }
+
+ // next chunk
+ x += n * d;
+ bytes += n * new_code_size;
+
+ n_left -= n;
+ }
+}
+
+template <typename StorageMinMaxT>
+void sa_decode_impl(
+ const IndexRowwiseMinMaxBase* const index,
+ const idx_t n_input,
+ const uint8_t* bytes_input,
+ float* x_output) {
+ // process chunks
+ const size_t chunk_size = rowwise_minmax_sa_decode_bs;
+
+ // useful variables
+ const Index* const sub_index = index->index;
+ const int d = index->d;
+
+ // the code size of the subindex
+ const size_t old_code_size = sub_index->sa_code_size();
+ // the code size of the index
+ const size_t new_code_size = index->sa_code_size();
+
+ // allocate tmp buffers
+ std::vector<uint8_t> tmp(
+ (chunk_size < n_input ? chunk_size : n_input) * old_code_size);
+ std::vector<StorageMinMaxFP16> minmax(
+ (chunk_size < n_input ? chunk_size : n_input));
+
+ // all the elements to process
+ size_t n_left = n_input;
+
+ const uint8_t* __restrict bytes = bytes_input;
+ float* __restrict x = x_output;
+
+ while (n_left > 0) {
+ // current portion to be processed
+ const idx_t n = std::min(n_left, chunk_size);
+
+ // rearrange
+ for (idx_t i = 0; i < n; i++) {
+ std::memcpy(
+ tmp.data() + i * old_code_size,
+ bytes + i * new_code_size + (new_code_size - old_code_size),
+ old_code_size);
+ }
+
+ // decode
+ sub_index->sa_decode(n, tmp.data(), x);
+
+ // scale back
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* const vec_in = bytes + i * new_code_size;
+ StorageMinMaxT fpv =
+ *(reinterpret_cast<const StorageMinMaxT*>(vec_in));
+
+ float scaler = 0;
+ float minv = 0;
+ fpv.to_floats(scaler, minv);
+
+ float* const __restrict vec = x + d * i;
+
+ for (idx_t j = 0; j < d; j++) {
+ vec[j] = vec[j] * scaler + minv;
+ }
+ }
+
+ // next chunk
+ bytes += n * new_code_size;
+ x += n * d;
+
+ n_left -= n;
+ }
+}
+
+//
+template <typename StorageMinMaxT>
+void train_inplace_impl(
+ IndexRowwiseMinMaxBase* const index,
+ idx_t n,
+ float* x) {
+ // useful variables
+ Index* const sub_index = index->index;
+ const int d = index->d;
+
+ // save normalizing coefficients
+ std::vector<StorageMinMaxT> minmax(n);
+
+ // normalize
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ // compute min & max values
+ float minv = std::numeric_limits<float>::max();
+ float maxv = std::numeric_limits<float>::lowest();
+
+ float* const vec = x + i * d;
+ for (idx_t j = 0; j < d; j++) {
+ minv = std::min(minv, vec[j]);
+ maxv = std::max(maxv, vec[j]);
+ }
+
+ // save the coefficients
+ const float scaler = maxv - minv;
+ minmax[i].from_floats(scaler, minv);
+
+ // and load them back, because the coefficients might
+ // be modified.
+ float actual_scaler = 0;
+ float actual_minv = 0;
+ minmax[i].to_floats(actual_scaler, actual_minv);
+
+ if (actual_scaler == 0) {
+ for (idx_t j = 0; j < d; j++) {
+ vec[j] = 0;
+ }
+ } else {
+ float inv_actual_scaler = 1.0f / actual_scaler;
+ for (idx_t j = 0; j < d; j++) {
+ vec[j] = (vec[j] - actual_minv) * inv_actual_scaler;
+ }
+ }
+ }
+
+ // train the subindex
+ sub_index->train(n, x);
+
+ // rescale data back
+ for (idx_t i = 0; i < n; i++) {
+ float scaler = 0;
+ float minv = 0;
+ minmax[i].to_floats(scaler, minv);
+
+ float* const vec = x + i * d;
+
+ for (idx_t j = 0; j < d; j++) {
+ vec[j] = vec[j] * scaler + minv;
+ }
+ }
+}
+
+//
+template <typename StorageMinMaxT>
+void train_impl(IndexRowwiseMinMaxBase* const index, idx_t n, const float* x) {
+ // the default training that creates a copy of the input data
+
+ // useful variables
+ Index* const sub_index = index->index;
+ const int d = index->d;
+
+ // temp buffer
+ std::vector<float> tmp(n * d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ // compute min & max values
+ float minv = std::numeric_limits<float>::max();
+ float maxv = std::numeric_limits<float>::lowest();
+
+ const float* const __restrict vec_in = x + i * d;
+ for (idx_t j = 0; j < d; j++) {
+ minv = std::min(minv, vec_in[j]);
+ maxv = std::max(maxv, vec_in[j]);
+ }
+
+ const float scaler = maxv - minv;
+
+ // save the coefficients
+ StorageMinMaxT storage;
+ storage.from_floats(scaler, minv);
+
+ // and load them back, because the coefficients might
+ // be modified.
+ float actual_scaler = 0;
+ float actual_minv = 0;
+ storage.to_floats(actual_scaler, actual_minv);
+
+ float* const __restrict vec_out = tmp.data() + i * d;
+ if (actual_scaler == 0) {
+ for (idx_t j = 0; j < d; j++) {
+ vec_out[j] = 0;
+ }
+ } else {
+ float inv_actual_scaler = 1.0f / actual_scaler;
+ for (idx_t j = 0; j < d; j++) {
+ vec_out[j] = (vec_in[j] - actual_minv) * inv_actual_scaler;
+ }
+ }
+ }
+
+ sub_index->train(n, tmp.data());
+}
+
+} // namespace
+
+// block size for performing sa_encode and sa_decode
+int rowwise_minmax_sa_encode_bs = 16384;
+int rowwise_minmax_sa_decode_bs = 16384;
+
+/*********************************************************
+ * IndexRowwiseMinMaxBase implementation
+ ********************************************************/
+
+IndexRowwiseMinMaxBase::IndexRowwiseMinMaxBase(Index* index)
+ : Index(index->d, index->metric_type),
+ index{index},
+ own_fields{false} {}
+
+IndexRowwiseMinMaxBase::IndexRowwiseMinMaxBase()
+ : index{nullptr}, own_fields{false} {}
+
+IndexRowwiseMinMaxBase::~IndexRowwiseMinMaxBase() {
+ if (own_fields) {
+ delete index;
+ index = nullptr;
+ }
+}
+
+void IndexRowwiseMinMaxBase::add(idx_t, const float*) {
+ FAISS_THROW_MSG("add not implemented for this type of index");
+}
+
+void IndexRowwiseMinMaxBase::search(
+ idx_t,
+ const float*,
+ idx_t,
+ float*,
+ idx_t*,
+ const SearchParameters*) const {
+ FAISS_THROW_MSG("search not implemented for this type of index");
+}
+
+void IndexRowwiseMinMaxBase::reset() {
+ FAISS_THROW_MSG("reset not implemented for this type of index");
+}
+
+/*********************************************************
+ * IndexRowwiseMinMaxFP16 implementation
+ ********************************************************/
+
+IndexRowwiseMinMaxFP16::IndexRowwiseMinMaxFP16(Index* index)
+ : IndexRowwiseMinMaxBase(index) {}
+
+IndexRowwiseMinMaxFP16::IndexRowwiseMinMaxFP16() : IndexRowwiseMinMaxBase() {}
+
+size_t IndexRowwiseMinMaxFP16::sa_code_size() const {
+ return index->sa_code_size() + 2 * sizeof(uint16_t);
+}
+
+void IndexRowwiseMinMaxFP16::sa_encode(
+ idx_t n_input,
+ const float* x_input,
+ uint8_t* bytes_output) const {
+ sa_encode_impl<StorageMinMaxFP16>(this, n_input, x_input, bytes_output);
+}
+
+void IndexRowwiseMinMaxFP16::sa_decode(
+ idx_t n_input,
+ const uint8_t* bytes_input,
+ float* x_output) const {
+ sa_decode_impl<StorageMinMaxFP16>(this, n_input, bytes_input, x_output);
+}
+
+void IndexRowwiseMinMaxFP16::train(idx_t n, const float* x) {
+ train_impl<StorageMinMaxFP16>(this, n, x);
+}
+
+void IndexRowwiseMinMaxFP16::train_inplace(idx_t n, float* x) {
+ train_inplace_impl<StorageMinMaxFP16>(this, n, x);
+}
+
+/*********************************************************
+ * IndexRowwiseMinMax implementation
+ ********************************************************/
+
+IndexRowwiseMinMax::IndexRowwiseMinMax(Index* index)
+ : IndexRowwiseMinMaxBase(index) {}
+
+IndexRowwiseMinMax::IndexRowwiseMinMax() : IndexRowwiseMinMaxBase() {}
+
+size_t IndexRowwiseMinMax::sa_code_size() const {
+ return index->sa_code_size() + 2 * sizeof(float);
+}
+
+void IndexRowwiseMinMax::sa_encode(
+ idx_t n_input,
+ const float* x_input,
+ uint8_t* bytes_output) const {
+ sa_encode_impl<StorageMinMaxFP32>(this, n_input, x_input, bytes_output);
+}
+
+void IndexRowwiseMinMax::sa_decode(
+ idx_t n_input,
+ const uint8_t* bytes_input,
+ float* x_output) const {
+ sa_decode_impl<StorageMinMaxFP32>(this, n_input, bytes_input, x_output);
+}
+
+void IndexRowwiseMinMax::train(idx_t n, const float* x) {
+ train_impl<StorageMinMaxFP32>(this, n, x);
+}
+
+void IndexRowwiseMinMax::train_inplace(idx_t n, float* x) {
+ train_inplace_impl<StorageMinMaxFP32>(this, n, x);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRowwiseMinMax.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRowwiseMinMax.h
new file mode 100644
index 0000000..bca9e07
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexRowwiseMinMax.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/// Index wrapper that performs rowwise normalization to [0,1], preserving
+/// the coefficients. This is a vector codec index only.
+///
+/// Basically, this index performs a rowwise scaling to [0,1] of every row
+/// in an input dataset before calling subindex::train() and
+/// subindex::sa_encode(). sa_encode() call stores the scaling coefficients
+/// (scaler and minv) in the very beginning of every output code. The format:
+/// [scaler][minv][subindex::sa_encode() output]
+/// The de-scaling in sa_decode() is done using:
+/// output_rescaled = scaler * output + minv
+///
+/// An additional ::train_inplace() function is provided in order to do
+/// an inplace scaling before calling subindex::train() and, thus, avoiding
+/// the cloning of the input dataset, but modifying the input dataset because
+/// of the scaling and the scaling back. It is up to user to call
+/// this function instead of ::train()
+///
+/// Derived classes provide different data types for scaling coefficients.
+/// Currently, versions with fp16 and fp32 scaling coefficients are available.
+/// * fp16 version adds 4 extra bytes per encoded vector
+/// * fp32 version adds 8 extra bytes per encoded vector
+
+/// Provides base functions for rowwise normalizing indices.
+struct IndexRowwiseMinMaxBase : Index {
+ /// sub-index
+ Index* index;
+
+ /// whether the subindex needs to be freed in the destructor.
+ bool own_fields;
+
+ explicit IndexRowwiseMinMaxBase(Index* index);
+
+ IndexRowwiseMinMaxBase();
+ ~IndexRowwiseMinMaxBase() override;
+
+ void add(idx_t n, const float* x) override;
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reset() override;
+
+ virtual void train_inplace(idx_t n, float* x) = 0;
+};
+
+/// Stores scaling coefficients as fp16 values.
+struct IndexRowwiseMinMaxFP16 : IndexRowwiseMinMaxBase {
+ explicit IndexRowwiseMinMaxFP16(Index* index);
+
+ IndexRowwiseMinMaxFP16();
+
+ void train(idx_t n, const float* x) override;
+ void train_inplace(idx_t n, float* x) override;
+
+ size_t sa_code_size() const override;
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+/// Stores scaling coefficients as fp32 values.
+struct IndexRowwiseMinMax : IndexRowwiseMinMaxBase {
+ explicit IndexRowwiseMinMax(Index* index);
+
+ IndexRowwiseMinMax();
+
+ void train(idx_t n, const float* x) override;
+ void train_inplace(idx_t n, float* x) override;
+
+ size_t sa_code_size() const override;
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+/// block size for performing sa_encode and sa_decode
+FAISS_API extern int rowwise_minmax_sa_encode_bs;
+FAISS_API extern int rowwise_minmax_sa_decode_bs;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexScalarQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexScalarQuantizer.cpp
new file mode 100644
index 0000000..296d2f0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexScalarQuantizer.cpp
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexScalarQuantizer.h>
+
+#include <algorithm>
+#include <cstdio>
+
+#include <omp.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/*******************************************************************
+ * IndexScalarQuantizer implementation
+ ********************************************************************/
+
+IndexScalarQuantizer::IndexScalarQuantizer(
+ int d,
+ ScalarQuantizer::QuantizerType qtype,
+ MetricType metric)
+ : IndexFlatCodes(0, d, metric), sq(d, qtype) {
+ is_trained = qtype == ScalarQuantizer::QT_fp16 ||
+ qtype == ScalarQuantizer::QT_8bit_direct ||
+ qtype == ScalarQuantizer::QT_bf16 ||
+ qtype == ScalarQuantizer::QT_8bit_direct_signed;
+ code_size = sq.code_size;
+}
+
+IndexScalarQuantizer::IndexScalarQuantizer()
+ : IndexScalarQuantizer(0, ScalarQuantizer::QT_8bit) {}
+
+void IndexScalarQuantizer::train(idx_t n, const float* x) {
+ sq.train(n, x);
+ is_trained = true;
+}
+
+void IndexScalarQuantizer::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ const IDSelector* sel = params ? params->sel : nullptr;
+
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(is_trained);
+ FAISS_THROW_IF_NOT(
+ metric_type == METRIC_L2 || metric_type == METRIC_INNER_PRODUCT);
+
+#pragma omp parallel
+ {
+ std::unique_ptr<InvertedListScanner> scanner(
+ sq.select_InvertedListScanner(metric_type, nullptr, true, sel));
+
+ scanner->list_no = 0; // directly the list number
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ float* D = distances + k * i;
+ idx_t* I = labels + k * i;
+ // re-order heap
+ if (metric_type == METRIC_L2) {
+ maxheap_heapify(k, D, I);
+ } else {
+ minheap_heapify(k, D, I);
+ }
+ scanner->set_query(x + i * d);
+ scanner->scan_codes(ntotal, codes.data(), nullptr, D, I, k);
+
+ // re-order heap
+ if (metric_type == METRIC_L2) {
+ maxheap_reorder(k, D, I);
+ } else {
+ minheap_reorder(k, D, I);
+ }
+ }
+ }
+}
+
+FlatCodesDistanceComputer* IndexScalarQuantizer::get_FlatCodesDistanceComputer()
+ const {
+ ScalarQuantizer::SQDistanceComputer* dc =
+ sq.get_distance_computer(metric_type);
+ dc->code_size = sq.code_size;
+ dc->codes = codes.data();
+ return dc;
+}
+
+/* Codec interface */
+
+void IndexScalarQuantizer::sa_encode(idx_t n, const float* x, uint8_t* bytes)
+ const {
+ FAISS_THROW_IF_NOT(is_trained);
+ sq.compute_codes(x, bytes, n);
+}
+
+void IndexScalarQuantizer::sa_decode(idx_t n, const uint8_t* bytes, float* x)
+ const {
+ FAISS_THROW_IF_NOT(is_trained);
+ sq.decode(bytes, x, n);
+}
+
+/*******************************************************************
+ * IndexIVFScalarQuantizer implementation
+ ********************************************************************/
+
+IndexIVFScalarQuantizer::IndexIVFScalarQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ ScalarQuantizer::QuantizerType qtype,
+ MetricType metric,
+ bool by_residual)
+ : IndexIVF(quantizer, d, nlist, 0, metric), sq(d, qtype) {
+ code_size = sq.code_size;
+ this->by_residual = by_residual;
+ // was not known at construction time
+ invlists->code_size = code_size;
+ is_trained = false;
+}
+
+IndexIVFScalarQuantizer::IndexIVFScalarQuantizer() : IndexIVF() {
+ by_residual = true;
+}
+
+void IndexIVFScalarQuantizer::train_encoder(
+ idx_t n,
+ const float* x,
+ const idx_t* assign) {
+ sq.train(n, x);
+}
+
+idx_t IndexIVFScalarQuantizer::train_encoder_num_vectors() const {
+ return 100000;
+}
+
+void IndexIVFScalarQuantizer::encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos) const {
+ std::unique_ptr<ScalarQuantizer::SQuantizer> squant(sq.select_quantizer());
+ size_t coarse_size = include_listnos ? coarse_code_size() : 0;
+ memset(codes, 0, (code_size + coarse_size) * n);
+
+#pragma omp parallel if (n > 1000)
+ {
+ std::vector<float> residual(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ int64_t list_no = list_nos[i];
+ if (list_no >= 0) {
+ const float* xi = x + i * d;
+ uint8_t* code = codes + i * (code_size + coarse_size);
+ if (by_residual) {
+ quantizer->compute_residual(xi, residual.data(), list_no);
+ xi = residual.data();
+ }
+ if (coarse_size) {
+ encode_listno(list_no, code);
+ }
+ squant->encode_vector(xi, code + coarse_size);
+ }
+ }
+ }
+}
+
+void IndexIVFScalarQuantizer::sa_decode(idx_t n, const uint8_t* codes, float* x)
+ const {
+ std::unique_ptr<ScalarQuantizer::SQuantizer> squant(sq.select_quantizer());
+ size_t coarse_size = coarse_code_size();
+
+#pragma omp parallel if (n > 1000)
+ {
+ std::vector<float> residual(d);
+
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + i * (code_size + coarse_size);
+ int64_t list_no = decode_listno(code);
+ float* xi = x + i * d;
+ squant->decode_vector(code + coarse_size, xi);
+ if (by_residual) {
+ quantizer->reconstruct(list_no, residual.data());
+ for (size_t j = 0; j < d; j++) {
+ xi[j] += residual[j];
+ }
+ }
+ }
+ }
+}
+
+void IndexIVFScalarQuantizer::add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* coarse_idx,
+ void* inverted_list_context) {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ std::unique_ptr<ScalarQuantizer::SQuantizer> squant(sq.select_quantizer());
+
+ DirectMapAdd dm_add(direct_map, n, xids);
+
+#pragma omp parallel
+ {
+ std::vector<float> residual(d);
+ std::vector<uint8_t> one_code(code_size);
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ // each thread takes care of a subset of lists
+ for (size_t i = 0; i < n; i++) {
+ int64_t list_no = coarse_idx[i];
+ if (list_no >= 0 && list_no % nt == rank) {
+ int64_t id = xids ? xids[i] : ntotal + i;
+
+ const float* xi = x + i * d;
+ if (by_residual) {
+ quantizer->compute_residual(xi, residual.data(), list_no);
+ xi = residual.data();
+ }
+
+ memset(one_code.data(), 0, code_size);
+ squant->encode_vector(xi, one_code.data());
+
+ size_t ofs = invlists->add_entry(
+ list_no, id, one_code.data(), inverted_list_context);
+
+ dm_add.add(i, list_no, ofs);
+
+ } else if (rank == 0 && list_no == -1) {
+ dm_add.add(i, -1, 0);
+ }
+ }
+ }
+
+ ntotal += n;
+}
+
+InvertedListScanner* IndexIVFScalarQuantizer::get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters*) const {
+ return sq.select_InvertedListScanner(
+ metric_type, quantizer, store_pairs, sel, by_residual);
+}
+
+void IndexIVFScalarQuantizer::reconstruct_from_offset(
+ int64_t list_no,
+ int64_t offset,
+ float* recons) const {
+ const uint8_t* code = invlists->get_single_code(list_no, offset);
+
+ if (by_residual) {
+ std::vector<float> centroid(d);
+ quantizer->reconstruct(list_no, centroid.data());
+
+ sq.decode(code, recons, 1);
+ for (int i = 0; i < d; ++i) {
+ recons[i] += centroid[i];
+ }
+ } else {
+ sq.decode(code, recons, 1);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexScalarQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexScalarQuantizer.h
new file mode 100644
index 0000000..9012ca3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexScalarQuantizer.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INDEX_SCALAR_QUANTIZER_H
+#define FAISS_INDEX_SCALAR_QUANTIZER_H
+
+#include <stdint.h>
+#include <vector>
+
+#include <faiss/IndexFlatCodes.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/impl/ScalarQuantizer.h>
+
+namespace faiss {
+
+/**
+ * Flat index built on a scalar quantizer.
+ */
+struct IndexScalarQuantizer : IndexFlatCodes {
+ /// Used to encode the vectors
+ ScalarQuantizer sq;
+
+ /** Constructor.
+ *
+ * @param d dimensionality of the input vectors
+ * @param M number of subquantizers
+ * @param nbits number of bit per subvector index
+ */
+ IndexScalarQuantizer(
+ int d,
+ ScalarQuantizer::QuantizerType qtype,
+ MetricType metric = METRIC_L2);
+
+ IndexScalarQuantizer();
+
+ void train(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ FlatCodesDistanceComputer* get_FlatCodesDistanceComputer() const override;
+
+ /* standalone codec interface */
+ void sa_encode(idx_t n, const float* x, uint8_t* bytes) const override;
+
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+/** An IVF implementation where the components of the residuals are
+ * encoded with a scalar quantizer. All distance computations
+ * are asymmetric, so the encoded vectors are decoded and approximate
+ * distances are computed.
+ */
+
+struct IndexIVFScalarQuantizer : IndexIVF {
+ ScalarQuantizer sq;
+
+ IndexIVFScalarQuantizer(
+ Index* quantizer,
+ size_t d,
+ size_t nlist,
+ ScalarQuantizer::QuantizerType qtype,
+ MetricType metric = METRIC_L2,
+ bool by_residual = true);
+
+ IndexIVFScalarQuantizer();
+
+ void train_encoder(idx_t n, const float* x, const idx_t* assign) override;
+
+ idx_t train_encoder_num_vectors() const override;
+
+ void encode_vectors(
+ idx_t n,
+ const float* x,
+ const idx_t* list_nos,
+ uint8_t* codes,
+ bool include_listnos = false) const override;
+
+ void add_core(
+ idx_t n,
+ const float* x,
+ const idx_t* xids,
+ const idx_t* precomputed_idx,
+ void* inverted_list_context = nullptr) override;
+
+ InvertedListScanner* get_InvertedListScanner(
+ bool store_pairs,
+ const IDSelector* sel,
+ const IVFSearchParameters* params) const override;
+
+ void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons)
+ const override;
+
+ /* standalone codec interface */
+ void sa_decode(idx_t n, const uint8_t* bytes, float* x) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShards.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShards.cpp
new file mode 100644
index 0000000..d7cc87a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShards.cpp
@@ -0,0 +1,270 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexShards.h>
+
+#include <cinttypes>
+#include <cstdio>
+#include <functional>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/WorkerThread.h>
+
+namespace faiss {
+
+// subroutines
+namespace {
+
+// IndexBinary needs to update the code_size when d is set...
+
+void sync_d(Index* index) {}
+
+void sync_d(IndexBinary* index) {
+ FAISS_THROW_IF_NOT(index->d % 8 == 0);
+ index->code_size = index->d / 8;
+}
+
+// add translation to all valid labels
+void translate_labels(int64_t n, idx_t* labels, int64_t translation) {
+ if (translation == 0)
+ return;
+ for (int64_t i = 0; i < n; i++) {
+ if (labels[i] < 0)
+ continue;
+ labels[i] += translation;
+ }
+}
+
+} // anonymous namespace
+
+template <typename IndexT>
+IndexShardsTemplate<IndexT>::IndexShardsTemplate(
+ idx_t d,
+ bool threaded,
+ bool successive_ids)
+ : ThreadedIndex<IndexT>(d, threaded), successive_ids(successive_ids) {
+ sync_d(this);
+}
+
+template <typename IndexT>
+IndexShardsTemplate<IndexT>::IndexShardsTemplate(
+ int d,
+ bool threaded,
+ bool successive_ids)
+ : ThreadedIndex<IndexT>(d, threaded), successive_ids(successive_ids) {
+ sync_d(this);
+}
+
+template <typename IndexT>
+IndexShardsTemplate<IndexT>::IndexShardsTemplate(
+ bool threaded,
+ bool successive_ids)
+ : ThreadedIndex<IndexT>(threaded), successive_ids(successive_ids) {
+ sync_d(this);
+}
+
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::onAfterAddIndex(IndexT* index /* unused */) {
+ syncWithSubIndexes();
+}
+
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::onAfterRemoveIndex(
+ IndexT* index /* unused */) {
+ syncWithSubIndexes();
+}
+
+// FIXME: assumes that nothing is currently running on the sub-indexes, which is
+// true with the normal API, but should use the runOnIndex API instead
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::syncWithSubIndexes() {
+ if (!this->count()) {
+ this->is_trained = false;
+ this->ntotal = 0;
+
+ return;
+ }
+
+ auto firstIndex = this->at(0);
+ this->d = firstIndex->d;
+ sync_d(this);
+ this->metric_type = firstIndex->metric_type;
+ this->is_trained = firstIndex->is_trained;
+ this->ntotal = firstIndex->ntotal;
+
+ for (int i = 1; i < this->count(); ++i) {
+ auto index = this->at(i);
+ FAISS_THROW_IF_NOT(this->metric_type == index->metric_type);
+ FAISS_THROW_IF_NOT(this->d == index->d);
+ FAISS_THROW_IF_NOT(this->is_trained == index->is_trained);
+
+ this->ntotal += index->ntotal;
+ }
+}
+
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::train(idx_t n, const component_t* x) {
+ auto fn = [n, x](int no, IndexT* index) {
+ if (index->verbose) {
+ printf("begin train shard %d on %" PRId64 " points\n", no, n);
+ }
+
+ index->train(n, x);
+
+ if (index->verbose) {
+ printf("end train shard %d\n", no);
+ }
+ };
+
+ this->runOnIndex(fn);
+ syncWithSubIndexes();
+}
+
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::add(idx_t n, const component_t* x) {
+ add_with_ids(n, x, nullptr);
+}
+
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::add_with_ids(
+ idx_t n,
+ const component_t* x,
+ const idx_t* xids) {
+ FAISS_THROW_IF_NOT_MSG(
+ !(successive_ids && xids),
+ "It makes no sense to pass in ids and "
+ "request them to be shifted");
+
+ if (successive_ids) {
+ FAISS_THROW_IF_NOT_MSG(
+ !xids,
+ "It makes no sense to pass in ids and "
+ "request them to be shifted");
+ FAISS_THROW_IF_NOT_MSG(
+ this->ntotal == 0,
+ "when adding to IndexShards with successive_ids, "
+ "only add() in a single pass is supported");
+ }
+
+ idx_t nshard = this->count();
+ const idx_t* ids = xids;
+
+ std::vector<idx_t> aids;
+
+ if (!ids && !successive_ids) {
+ aids.resize(n);
+ for (idx_t i = 0; i < n; i++) {
+ aids[i] = this->ntotal + i;
+ }
+ ids = aids.data();
+ }
+
+ size_t components_per_vec =
+ sizeof(component_t) == 1 ? (this->d + 7) / 8 : this->d;
+
+ auto fn = [n, ids, x, nshard, components_per_vec](int no, IndexT* index) {
+ idx_t i0 = (idx_t)no * n / nshard;
+ idx_t i1 = ((idx_t)no + 1) * n / nshard;
+ auto x0 = x + i0 * components_per_vec;
+
+ if (index->verbose) {
+ printf("begin add shard %d on %" PRId64 " points\n", no, n);
+ }
+
+ if (ids) {
+ index->add_with_ids(i1 - i0, x0, ids + i0);
+ } else {
+ index->add(i1 - i0, x0);
+ }
+
+ if (index->verbose) {
+ printf("end add shard %d on %" PRId64 " points\n", no, i1 - i0);
+ }
+ };
+
+ this->runOnIndex(fn);
+ syncWithSubIndexes();
+}
+
+template <typename IndexT>
+void IndexShardsTemplate<IndexT>::search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k > 0);
+
+ int64_t nshard = this->count();
+
+ std::vector<distance_t> all_distances(nshard * k * n);
+ std::vector<idx_t> all_labels(nshard * k * n);
+ std::vector<int64_t> translations(nshard, 0);
+
+ // Because we just called runOnIndex above, it is safe to access the
+ // sub-index ntotal here
+ if (successive_ids) {
+ translations[0] = 0;
+
+ for (int s = 0; s + 1 < nshard; s++) {
+ translations[s + 1] = translations[s] + this->at(s)->ntotal;
+ }
+ }
+
+ auto fn = [n, k, x, &all_distances, &all_labels, &translations](
+ int no, const IndexT* index) {
+ if (index->verbose) {
+ printf("begin query shard %d on %" PRId64 " points\n", no, n);
+ }
+
+ index->search(
+ n,
+ x,
+ k,
+ all_distances.data() + no * k * n,
+ all_labels.data() + no * k * n);
+
+ translate_labels(
+ n * k, all_labels.data() + no * k * n, translations[no]);
+
+ if (index->verbose) {
+ printf("end query shard %d\n", no);
+ }
+ };
+
+ this->runOnIndex(fn);
+
+ if (this->metric_type == METRIC_L2) {
+ merge_knn_results<idx_t, CMin<distance_t, int>>(
+ n,
+ k,
+ nshard,
+ all_distances.data(),
+ all_labels.data(),
+ distances,
+ labels);
+ } else {
+ merge_knn_results<idx_t, CMax<distance_t, int>>(
+ n,
+ k,
+ nshard,
+ all_distances.data(),
+ all_labels.data(),
+ distances,
+ labels);
+ }
+}
+
+// explicit instanciations
+template struct IndexShardsTemplate<Index>;
+template struct IndexShardsTemplate<IndexBinary>;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShards.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShards.h
new file mode 100644
index 0000000..75c716e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShards.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/impl/ThreadedIndex.h>
+
+namespace faiss {
+
+/**
+ * Index that concatenates the results from several sub-indexes
+ */
+template <typename IndexT>
+struct IndexShardsTemplate : public ThreadedIndex<IndexT> {
+ using component_t = typename IndexT::component_t;
+ using distance_t = typename IndexT::distance_t;
+
+ /**
+ * The dimension that all sub-indices must share will be the dimension of
+ * the first sub-index added
+ *
+ * @param threaded do we use one thread per sub_index or do
+ * queries sequentially?
+ * @param successive_ids should we shift the returned ids by
+ * the size of each sub-index or return them
+ * as they are?
+ */
+ explicit IndexShardsTemplate(
+ bool threaded = false,
+ bool successive_ids = true);
+
+ /**
+ * @param threaded do we use one thread per sub_index or do
+ * queries sequentially?
+ * @param successive_ids should we shift the returned ids by
+ * the size of each sub-index or return them
+ * as they are?
+ */
+ explicit IndexShardsTemplate(
+ idx_t d,
+ bool threaded = false,
+ bool successive_ids = true);
+
+ /// int version due to the implicit bool conversion ambiguity of int as
+ /// dimension
+ explicit IndexShardsTemplate(
+ int d,
+ bool threaded = false,
+ bool successive_ids = true);
+
+ /// Alias for addIndex()
+ void add_shard(IndexT* index) {
+ this->addIndex(index);
+ }
+
+ /// Alias for removeIndex()
+ void remove_shard(IndexT* index) {
+ this->removeIndex(index);
+ }
+
+ /// supported only for sub-indices that implement add_with_ids
+ void add(idx_t n, const component_t* x) override;
+
+ /**
+ * Cases (successive_ids, xids):
+ * - true, non-NULL ERROR: it makes no sense to pass in ids and
+ * request them to be shifted
+ * - true, NULL OK: but should be called only once (calls add()
+ * on sub-indexes).
+ * - false, non-NULL OK: will call add_with_ids with passed in xids
+ * distributed evenly over shards
+ * - false, NULL OK: will call add_with_ids on each sub-index,
+ * starting at ntotal
+ */
+ void add_with_ids(idx_t n, const component_t* x, const idx_t* xids)
+ override;
+
+ void search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void train(idx_t n, const component_t* x) override;
+
+ bool successive_ids;
+
+ /// Synchronize the top-level index (IndexShards) with data in the
+ /// sub-indices
+ virtual void syncWithSubIndexes();
+
+ protected:
+ /// Called just after an index is added
+ void onAfterAddIndex(IndexT* index) override;
+
+ /// Called just after an index is removed
+ void onAfterRemoveIndex(IndexT* index) override;
+};
+
+using IndexShards = IndexShardsTemplate<Index>;
+using IndexBinaryShards = IndexShardsTemplate<IndexBinary>;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShardsIVF.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShardsIVF.cpp
new file mode 100644
index 0000000..d75e051
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShardsIVF.cpp
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/IndexShardsIVF.h>
+
+#include <cinttypes>
+#include <cstdio>
+#include <functional>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/WorkerThread.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+// subroutines
+namespace {
+
+// add translation to all valid labels
+void translate_labels(int64_t n, idx_t* labels, int64_t translation) {
+ if (translation == 0) {
+ return;
+ }
+ for (int64_t i = 0; i < n; i++) {
+ if (labels[i] < 0) {
+ continue;
+ }
+ labels[i] += translation;
+ }
+}
+
+} // anonymous namespace
+
+/************************************************************
+ * IndexShardsIVF
+ ************************************************************/
+
+IndexShardsIVF::IndexShardsIVF(
+ Index* quantizer,
+ size_t nlist,
+ bool threaded,
+ bool successive_ids)
+ : IndexShardsTemplate<Index>(quantizer->d, threaded, successive_ids),
+ Level1Quantizer(quantizer, nlist) {
+ is_trained = quantizer->is_trained && quantizer->ntotal == nlist;
+}
+
+void IndexShardsIVF::addIndex(Index* index) {
+ auto index_ivf = dynamic_cast<IndexIVFInterface*>(index);
+ FAISS_THROW_IF_NOT_MSG(index_ivf, "can only add IndexIVFs");
+ FAISS_THROW_IF_NOT(index_ivf->nlist == nlist);
+ IndexShardsTemplate<Index>::addIndex(index);
+}
+
+void IndexShardsIVF::train(idx_t n, const component_t* x) {
+ if (verbose) {
+ printf("Training level-1 quantizer\n");
+ }
+ train_q1(n, x, verbose, metric_type);
+
+ // set the sub-quantizer codebooks
+ std::vector<float> centroids(nlist * d);
+ quantizer->reconstruct_n(0, nlist, centroids.data());
+
+ // probably not worth running in parallel
+ for (size_t i = 0; i < indices_.size(); i++) {
+ Index* index = indices_[i].first;
+ auto index_ivf = dynamic_cast<IndexIVFInterface*>(index);
+ Index* quantizer = index_ivf->quantizer;
+ if (!quantizer->is_trained) {
+ quantizer->train(nlist, centroids.data());
+ }
+ quantizer->add(nlist, centroids.data());
+ // finish training
+ index->train(n, x);
+ }
+
+ is_trained = true;
+}
+
+void IndexShardsIVF::add_with_ids(
+ idx_t n,
+ const component_t* x,
+ const idx_t* xids) {
+ // IndexIVF exposes add_core that we can use to factorize the
+ bool all_index_ivf = true;
+ for (size_t i = 0; i < indices_.size(); i++) {
+ Index* index = indices_[i].first;
+ all_index_ivf = all_index_ivf && dynamic_cast<IndexIVF*>(index);
+ }
+ if (!all_index_ivf) {
+ IndexShardsTemplate<Index>::add_with_ids(n, x, xids);
+ return;
+ }
+ FAISS_THROW_IF_NOT_MSG(
+ !(successive_ids && xids),
+ "It makes no sense to pass in ids and "
+ "request them to be shifted");
+
+ if (successive_ids) {
+ FAISS_THROW_IF_NOT_MSG(
+ !xids,
+ "It makes no sense to pass in ids and "
+ "request them to be shifted");
+ FAISS_THROW_IF_NOT_MSG(
+ this->ntotal == 0,
+ "when adding to IndexShards with successive_ids, "
+ "only add() in a single pass is supported");
+ }
+
+ // perform coarse quantization
+ std::vector<idx_t> Iq(n);
+ std::vector<float> Dq(n);
+ quantizer->search(n, x, 1, Dq.data(), Iq.data());
+
+ // possibly shift ids
+ idx_t nshard = this->count();
+ const idx_t* ids = xids;
+ std::vector<idx_t> aids;
+ if (!ids && !successive_ids) {
+ aids.resize(n);
+
+ for (idx_t i = 0; i < n; i++) {
+ aids[i] = this->ntotal + i;
+ }
+ ids = aids.data();
+ }
+ idx_t d = this->d;
+
+ auto fn = [n, ids, x, nshard, d, Iq](int no, Index* index) {
+ idx_t i0 = (idx_t)no * n / nshard;
+ idx_t i1 = ((idx_t)no + 1) * n / nshard;
+ auto index_ivf = dynamic_cast<IndexIVF*>(index);
+
+ if (index->verbose) {
+ printf("begin add shard %d on %" PRId64 " points\n", no, n);
+ }
+
+ index_ivf->add_core(
+ i1 - i0, x + i0 * d, ids ? ids + i0 : nullptr, Iq.data() + i0);
+
+ if (index->verbose) {
+ printf("end add shard %d on %" PRId64 " points\n", no, i1 - i0);
+ }
+ };
+
+ this->runOnIndex(fn);
+ syncWithSubIndexes();
+}
+
+void IndexShardsIVF::search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params_in) const {
+ FAISS_THROW_IF_NOT(k > 0);
+ FAISS_THROW_IF_NOT(count() > 0);
+ const IVFSearchParameters* params = nullptr;
+ if (params_in) {
+ params = dynamic_cast<const IVFSearchParameters*>(params_in);
+ FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type");
+ }
+
+ auto index0 = dynamic_cast<const IndexIVFInterface*>(at(0));
+ idx_t nprobe = params ? params->nprobe : index0->nprobe;
+
+ // coarse quantization (TODO: support tiling with search_precomputed)
+ std::vector<distance_t> Dq(n * nprobe);
+ std::vector<idx_t> Iq(n * nprobe);
+
+ quantizer->search(n, x, nprobe, Dq.data(), Iq.data());
+
+ int64_t nshard = this->count();
+
+ std::vector<distance_t> all_distances(nshard * k * n);
+ std::vector<idx_t> all_labels(nshard * k * n);
+ std::vector<int64_t> translations(nshard, 0);
+
+ if (successive_ids) {
+ translations[0] = 0;
+ for (int s = 0; s + 1 < nshard; s++) {
+ translations[s + 1] = translations[s] + this->at(s)->ntotal;
+ }
+ }
+
+ auto fn = [&](int no, const Index* indexIn) {
+ if (indexIn->verbose) {
+ printf("begin query shard %d on %" PRId64 " points\n", no, n);
+ }
+
+ auto index = dynamic_cast<const IndexIVFInterface*>(indexIn);
+
+ FAISS_THROW_IF_NOT_MSG(index->nprobe == nprobe, "inconsistent nprobe");
+
+ index->search_preassigned(
+ n,
+ x,
+ k,
+ Iq.data(),
+ Dq.data(),
+ all_distances.data() + no * k * n,
+ all_labels.data() + no * k * n,
+ false);
+
+ translate_labels(
+ n * k, all_labels.data() + no * k * n, translations[no]);
+
+ if (indexIn->verbose) {
+ printf("end query shard %d\n", no);
+ }
+ };
+
+ this->runOnIndex(fn);
+
+ if (this->metric_type == METRIC_L2) {
+ merge_knn_results<idx_t, CMin<distance_t, int>>(
+ n,
+ k,
+ nshard,
+ all_distances.data(),
+ all_labels.data(),
+ distances,
+ labels);
+ } else {
+ merge_knn_results<idx_t, CMax<distance_t, int>>(
+ n,
+ k,
+ nshard,
+ all_distances.data(),
+ all_labels.data(),
+ distances,
+ labels);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShardsIVF.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShardsIVF.h
new file mode 100644
index 0000000..bc18122
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/IndexShardsIVF.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexShards.h>
+
+namespace faiss {
+
+/**
+ * IndexShards with a common coarse quantizer. All the indexes added should be
+ * IndexIVFInterface indexes so that the search_precomputed can be called.
+ */
+struct IndexShardsIVF : public IndexShards, Level1Quantizer {
+ explicit IndexShardsIVF(
+ Index* quantizer,
+ size_t nlist,
+ bool threaded = false,
+ bool successive_ids = true);
+
+ void addIndex(Index* index) override;
+
+ void add_with_ids(idx_t n, const component_t* x, const idx_t* xids)
+ override;
+
+ void train(idx_t n, const component_t* x) override;
+
+ void search(
+ idx_t n,
+ const component_t* x,
+ idx_t k,
+ distance_t* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/MatrixStats.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/MatrixStats.cpp
new file mode 100644
index 0000000..22b6cbd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/MatrixStats.cpp
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/MatrixStats.h>
+
+#include <cstdarg> /* va_list, va_start, va_arg, va_end */
+
+#include <faiss/utils/utils.h>
+#include <cinttypes>
+#include <cmath>
+#include <cstdio>
+
+namespace faiss {
+
+/*********************************************************************
+ * MatrixStats
+ *********************************************************************/
+
+void MatrixStats::PerDimStats::add(float x) {
+ n++;
+ if (std::isnan(x)) {
+ n_nan++;
+ return;
+ }
+ if (!std::isfinite(x)) {
+ n_inf++;
+ return;
+ }
+ if (x == 0)
+ n0++;
+ if (x < min)
+ min = x;
+ if (x > max)
+ max = x;
+ sum += x;
+ sum2 += (double)x * (double)x;
+}
+
+void MatrixStats::PerDimStats::compute_mean_std() {
+ n_valid = n - n_nan - n_inf;
+ mean = sum / n_valid;
+ double var = sum2 / n_valid - mean * mean;
+ if (var < 0)
+ var = 0;
+ stddev = sqrt(var);
+}
+
+void MatrixStats::do_comment(const char* fmt, ...) {
+ va_list ap;
+
+ /* Determine required size */
+ va_start(ap, fmt);
+ size_t size = vsnprintf(buf, nbuf, fmt, ap);
+ va_end(ap);
+
+ nbuf -= size;
+ buf += size;
+}
+
+MatrixStats::MatrixStats(size_t n, size_t d, const float* x) : n(n), d(d) {
+ std::vector<char> comment_buf(10000);
+ buf = comment_buf.data();
+ nbuf = comment_buf.size();
+
+ do_comment("analyzing %zd vectors of size %zd\n", n, d);
+
+ if (d > 1024) {
+ do_comment(
+ "indexing this many dimensions is hard, "
+ "please consider dimensionality reducution (with PCAMatrix)\n");
+ }
+
+ hash_value = hash_bytes((const uint8_t*)x, n * d * sizeof(*x));
+ do_comment("hash value 0x%016" PRIx64 "\n", hash_value);
+
+ size_t nbytes = sizeof(x[0]) * d;
+ per_dim_stats.resize(d);
+
+ for (size_t i = 0; i < n; i++) {
+ const float* xi = x + d * i;
+ double sum2 = 0;
+ for (size_t j = 0; j < d; j++) {
+ per_dim_stats[j].add(xi[j]);
+ sum2 += xi[j] * (double)xi[j];
+ }
+
+ if (std::isfinite(sum2)) {
+ n_valid++;
+ if (sum2 == 0) {
+ n0++;
+ } else {
+ if (sum2 < min_norm2)
+ min_norm2 = sum2;
+ if (sum2 > max_norm2)
+ max_norm2 = sum2;
+ }
+ }
+
+ { // check hash
+ uint64_t hash = hash_bytes((const uint8_t*)xi, nbytes);
+ auto elt = occurrences.find(hash);
+ if (elt == occurrences.end()) {
+ Occurrence occ = {i, 1};
+ occurrences[hash] = occ;
+ } else {
+ if (!memcmp(xi, x + elt->second.first * d, nbytes)) {
+ elt->second.count++;
+ } else {
+ n_collision++;
+ // we should use a list of collisions but overkill
+ }
+ }
+ }
+ }
+
+ // invalid vecor stats
+ if (n_valid == n) {
+ do_comment("no NaN or Infs in data\n");
+ } else {
+ do_comment(
+ "%ld vectors contain NaN or Inf "
+ "(or have too large components), "
+ "expect bad results with indexing!\n",
+ n - n_valid);
+ }
+
+ // copies in dataset
+ if (occurrences.size() == n) {
+ do_comment("all vectors are distinct\n");
+ } else {
+ do_comment(
+ "%ld vectors are distinct (%.2f%%)\n",
+ occurrences.size(),
+ occurrences.size() * 100.0 / n);
+
+ if (n_collision > 0) {
+ do_comment(
+ "%zd collisions in hash table, "
+ "counts may be invalid\n",
+ n_collision);
+ }
+
+ Occurrence max = {0, 0};
+ for (auto it = occurrences.begin(); it != occurrences.end(); ++it) {
+ if (it->second.count > max.count) {
+ max = it->second;
+ }
+ }
+ do_comment("vector %zd has %zd copies\n", max.first, max.count);
+ }
+
+ { // norm stats
+ min_norm2 = sqrt(min_norm2);
+ max_norm2 = sqrt(max_norm2);
+ do_comment(
+ "range of L2 norms=[%g, %g] (%zd null vectors)\n",
+ min_norm2,
+ max_norm2,
+ n0);
+
+ if (max_norm2 < min_norm2 * 1.0001) {
+ do_comment(
+ "vectors are normalized, inner product and "
+ "L2 search are equivalent\n");
+ }
+
+ if (max_norm2 > min_norm2 * 100) {
+ do_comment(
+ "vectors have very large differences in norms, "
+ "is this normal?\n");
+ }
+ }
+
+ { // per dimension stats
+
+ double max_std = 0, min_std = HUGE_VAL;
+
+ size_t n_dangerous_range = 0, n_0_range = 0, n0_2 = 0;
+
+ for (size_t j = 0; j < d; j++) {
+ PerDimStats& st = per_dim_stats[j];
+ st.compute_mean_std();
+ n0_2 += st.n0;
+
+ if (st.max == st.min) {
+ n_0_range++;
+ } else if (st.max < 1.001 * st.min) {
+ n_dangerous_range++;
+ }
+
+ if (st.stddev > max_std)
+ max_std = st.stddev;
+ if (st.stddev < min_std)
+ min_std = st.stddev;
+ }
+
+ if (n0_2 == 0) {
+ do_comment("matrix contains no 0s\n");
+ } else {
+ do_comment(
+ "matrix contains %.2f %% 0 entries\n",
+ n0_2 * 100.0 / (n * d));
+ }
+
+ if (n_0_range == 0) {
+ do_comment("no constant dimensions\n");
+ } else {
+ do_comment(
+ "%zd dimensions are constant: they can be removed\n",
+ n_0_range);
+ }
+
+ if (n_dangerous_range == 0) {
+ do_comment("no dimension has a too large mean\n");
+ } else {
+ do_comment(
+ "%zd dimensions are too large "
+ "wrt. their variance, may loose precision "
+ "in IndexFlatL2 (use CenteringTransform)\n",
+ n_dangerous_range);
+ }
+
+ do_comment("stddevs per dimension are in [%g %g]\n", min_std, max_std);
+
+ size_t n_small_var = 0;
+
+ for (size_t j = 0; j < d; j++) {
+ const PerDimStats& st = per_dim_stats[j];
+ if (st.stddev < max_std * 1e-4) {
+ n_small_var++;
+ }
+ }
+
+ if (n_small_var > 0) {
+ do_comment(
+ "%ld dimensions have negligible stddev wrt. "
+ "the largest dimension, they could be ignored",
+ n_small_var);
+ }
+ }
+ comments = comment_buf.data();
+ buf = nullptr;
+ nbuf = 0;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/MatrixStats.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/MatrixStats.h
new file mode 100644
index 0000000..2fe8edb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/MatrixStats.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <stdint.h>
+#include <cmath>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+namespace faiss {
+
+/** Reports some statistics on a dataset and comments on them.
+ *
+ * It is a class rather than a function so that all stats can also be
+ * accessed from code */
+
+struct MatrixStats {
+ MatrixStats(size_t n, size_t d, const float* x);
+ std::string comments;
+
+ // raw statistics
+ size_t n = 0, d = 0;
+ size_t n_collision = 0;
+ size_t n_valid = 0;
+ size_t n0 = 0;
+ double min_norm2 = HUGE_VALF;
+ double max_norm2 = 0;
+ uint64_t hash_value = 0;
+
+ struct PerDimStats {
+ /// counts of various special entries
+ size_t n = 0;
+ size_t n_nan = 0;
+ size_t n_inf = 0;
+ size_t n0 = 0;
+
+ /// to get min/max and stddev values
+ float min = HUGE_VALF;
+ float max = -HUGE_VALF;
+ double sum = 0;
+ double sum2 = 0;
+
+ size_t n_valid = 0;
+ double mean = NAN;
+ double stddev = NAN;
+
+ void add(float x);
+ void compute_mean_std();
+ };
+
+ std::vector<PerDimStats> per_dim_stats;
+ struct Occurrence {
+ size_t first;
+ size_t count;
+ };
+ std::unordered_map<uint64_t, Occurrence> occurrences;
+
+ char* buf;
+ size_t nbuf;
+ void do_comment(const char* fmt, ...);
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/MetaIndexes.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/MetaIndexes.cpp
new file mode 100644
index 0000000..a2f1efb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/MetaIndexes.cpp
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/MetaIndexes.h>
+
+#include <cinttypes>
+#include <cstdint>
+#include <cstdio>
+#include <limits>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/WorkerThread.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/*****************************************************
+ * IndexSplitVectors implementation
+ *******************************************************/
+
+IndexSplitVectors::IndexSplitVectors(idx_t d, bool threaded)
+ : Index(d), own_fields(false), threaded(threaded), sum_d(0) {}
+
+void IndexSplitVectors::add_sub_index(Index* index) {
+ sub_indexes.push_back(index);
+ sync_with_sub_indexes();
+}
+
+void IndexSplitVectors::sync_with_sub_indexes() {
+ if (sub_indexes.empty())
+ return;
+ Index* index0 = sub_indexes[0];
+ sum_d = index0->d;
+ metric_type = index0->metric_type;
+ is_trained = index0->is_trained;
+ ntotal = index0->ntotal;
+ for (int i = 1; i < sub_indexes.size(); i++) {
+ Index* index = sub_indexes[i];
+ FAISS_THROW_IF_NOT(metric_type == index->metric_type);
+ FAISS_THROW_IF_NOT(ntotal == index->ntotal);
+ sum_d += index->d;
+ }
+}
+
+void IndexSplitVectors::add(idx_t /*n*/, const float* /*x*/) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void IndexSplitVectors::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT_MSG(k == 1, "search implemented only for k=1");
+ FAISS_THROW_IF_NOT_MSG(
+ sum_d == d, "not enough indexes compared to # dimensions");
+
+ int64_t nshard = sub_indexes.size();
+
+ std::unique_ptr<float[]> all_distances(new float[nshard * k * n]);
+ std::unique_ptr<idx_t[]> all_labels(new idx_t[nshard * k * n]);
+
+ auto query_func =
+ [n, x, k, distances, labels, &all_distances, &all_labels, this](
+ int no) {
+ const IndexSplitVectors* index = this;
+ float* distances1 =
+ no == 0 ? distances : all_distances.get() + no * k * n;
+ idx_t* labels1 =
+ no == 0 ? labels : all_labels.get() + no * k * n;
+ if (index->verbose)
+ printf("begin query shard %d on %" PRId64 " points\n",
+ no,
+ n);
+ const Index* sub_index = index->sub_indexes[no];
+ int64_t sub_d = sub_index->d, d = index->d;
+ idx_t ofs = 0;
+ for (int i = 0; i < no; i++)
+ ofs += index->sub_indexes[i]->d;
+
+ std::unique_ptr<float[]> sub_x(new float[sub_d * n]);
+ for (idx_t i = 0; i < n; i++)
+ memcpy(sub_x.get() + i * sub_d,
+ x + ofs + i * d,
+ sub_d * sizeof(float));
+ sub_index->search(n, sub_x.get(), k, distances1, labels1);
+ if (index->verbose)
+ printf("end query shard %d\n", no);
+ };
+
+ if (!threaded) {
+ for (int i = 0; i < nshard; i++) {
+ query_func(i);
+ }
+ } else {
+ std::vector<std::unique_ptr<WorkerThread>> threads;
+ std::vector<std::future<bool>> v;
+
+ for (int i = 0; i < nshard; i++) {
+ threads.emplace_back(new WorkerThread());
+ WorkerThread* wt = threads.back().get();
+ v.emplace_back(wt->add([i, query_func]() { query_func(i); }));
+ }
+
+ // Blocking wait for completion
+ for (auto& func : v) {
+ func.get();
+ }
+ }
+
+ int64_t factor = 1;
+ for (int i = 0; i < nshard; i++) {
+ if (i > 0) { // results of 0 are already in the table
+ const float* distances_i = all_distances.get() + i * k * n;
+ const idx_t* labels_i = all_labels.get() + i * k * n;
+ for (int64_t j = 0; j < n; j++) {
+ if (labels[j] >= 0 && labels_i[j] >= 0) {
+ labels[j] += labels_i[j] * factor;
+ distances[j] += distances_i[j];
+ } else {
+ labels[j] = -1;
+ distances[j] = std::numeric_limits<float>::quiet_NaN();
+ }
+ }
+ }
+ factor *= sub_indexes[i]->ntotal;
+ }
+}
+
+void IndexSplitVectors::train(idx_t /*n*/, const float* /*x*/) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void IndexSplitVectors::reset() {
+ FAISS_THROW_MSG("not implemented");
+}
+
+IndexSplitVectors::~IndexSplitVectors() {
+ if (own_fields) {
+ for (int s = 0; s < sub_indexes.size(); s++)
+ delete sub_indexes[s];
+ }
+}
+
+/********************************************************
+ * IndexRandom implementation
+ */
+
+IndexRandom::IndexRandom(
+ idx_t d,
+ idx_t ntotal,
+ int64_t seed,
+ MetricType metric_type)
+ : Index(d, metric_type), seed(seed) {
+ this->ntotal = ntotal;
+ is_trained = true;
+}
+
+void IndexRandom::add(idx_t n, const float*) {
+ ntotal += n;
+}
+
+void IndexRandom::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ FAISS_THROW_IF_NOT_MSG(
+ !params, "search params not supported for this index");
+ FAISS_THROW_IF_NOT(k <= ntotal);
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ RandomGenerator rng(
+ seed + ivec_checksum(d, (const int32_t*)(x + i * d)));
+ idx_t* I = labels + i * k;
+ float* D = distances + i * k;
+ // assumes k << ntotal
+ if (k < 100 * ntotal) {
+ std::unordered_set<idx_t> map;
+ for (int j = 0; j < k; j++) {
+ idx_t ii;
+ for (;;) {
+ // yes I know it's not strictly uniform...
+ ii = rng.rand_int64() % ntotal;
+ if (map.count(ii) == 0) {
+ break;
+ }
+ }
+ I[j] = ii;
+ map.insert(ii);
+ }
+ } else {
+ std::vector<idx_t> perm(ntotal);
+ for (idx_t j = 0; j < ntotal; j++) {
+ perm[j] = j;
+ }
+ for (int j = 0; j < k; j++) {
+ std::swap(perm[j], perm[rng.rand_int(ntotal)]);
+ I[j] = perm[j];
+ }
+ }
+ float dprev = 0;
+ for (int j = 0; j < k; j++) {
+ float step = rng.rand_float();
+ if (is_similarity_metric(metric_type)) {
+ step = -step;
+ }
+ dprev += step;
+ D[j] = dprev;
+ }
+ }
+}
+
+void IndexRandom::reconstruct(idx_t key, float* recons) const {
+ RandomGenerator rng(seed + 123332 + key);
+ for (size_t i = 0; i < d; i++) {
+ recons[i] = rng.rand_float();
+ }
+}
+
+void IndexRandom::reset() {
+ ntotal = 0;
+}
+
+IndexRandom::~IndexRandom() = default;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/MetaIndexes.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/MetaIndexes.h
new file mode 100644
index 0000000..ae6558c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/MetaIndexes.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef META_INDEXES_H
+#define META_INDEXES_H
+
+#include <faiss/Index.h>
+#include <faiss/IndexIDMap.h>
+#include <faiss/IndexReplicas.h>
+#include <faiss/IndexShards.h>
+#include <vector>
+
+namespace faiss {
+
+/** splits input vectors in segments and assigns each segment to a sub-index
+ * used to distribute a MultiIndexQuantizer
+ */
+struct IndexSplitVectors : Index {
+ bool own_fields;
+ bool threaded;
+ std::vector<Index*> sub_indexes;
+ idx_t sum_d; /// sum of dimensions seen so far
+
+ explicit IndexSplitVectors(idx_t d, bool threaded = false);
+
+ void add_sub_index(Index*);
+ void sync_with_sub_indexes();
+
+ void add(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void train(idx_t n, const float* x) override;
+
+ void reset() override;
+
+ ~IndexSplitVectors() override;
+};
+
+/** index that returns random results.
+ * used mainly for time benchmarks
+ */
+struct IndexRandom : Index {
+ int64_t seed;
+
+ explicit IndexRandom(
+ idx_t d,
+ idx_t ntotal = 0,
+ int64_t seed = 1234,
+ MetricType mt = METRIC_L2);
+
+ void add(idx_t n, const float* x) override;
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ void reconstruct(idx_t key, float* recons) const override;
+
+ void reset() override;
+
+ ~IndexRandom() override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/MetricType.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/MetricType.h
new file mode 100644
index 0000000..a09ff7a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/MetricType.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_METRIC_TYPE_H
+#define FAISS_METRIC_TYPE_H
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/// The metric space for vector comparison for Faiss indices and algorithms.
+///
+/// Most algorithms support both inner product and L2, with the flat
+/// (brute-force) indices supporting additional metric types for vector
+/// comparison.
+enum MetricType {
+ METRIC_INNER_PRODUCT = 0, ///< maximum inner product search
+ METRIC_L2 = 1, ///< squared L2 search
+ METRIC_L1, ///< L1 (aka cityblock)
+ METRIC_Linf, ///< infinity distance
+ METRIC_Lp, ///< L_p distance, p is given by a faiss::Index
+ /// metric_arg
+
+ /// some additional metrics defined in scipy.spatial.distance
+ METRIC_Canberra = 20,
+ METRIC_BrayCurtis,
+ METRIC_JensenShannon,
+
+ /// sum_i(min(a_i, b_i)) / sum_i(max(a_i, b_i)) where a_i, b_i > 0
+ METRIC_Jaccard,
+ /// Squared Eucliden distance, ignoring NaNs
+ METRIC_NaNEuclidean,
+ /// abs(x | y): the distance to a hyperplane
+ METRIC_ABS_INNER_PRODUCT,
+};
+
+/// all vector indices are this type
+using idx_t = int64_t;
+
+/// this function is used to distinguish between min and max indexes since
+/// we need to support similarity and dis-similarity metrics in a flexible way
+constexpr bool is_similarity_metric(MetricType metric_type) {
+ return ((metric_type == METRIC_INNER_PRODUCT) ||
+ (metric_type == METRIC_Jaccard));
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/VectorTransform.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/VectorTransform.cpp
new file mode 100644
index 0000000..e325562
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/VectorTransform.cpp
@@ -0,0 +1,1365 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/VectorTransform.h>
+
+#include <cinttypes>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+
+#include <faiss/IndexPQ.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+using namespace faiss;
+
+extern "C" {
+
+// this is to keep the clang syntax checker happy
+#ifndef FINTEGER
+#define FINTEGER int
+#endif
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+
+int dgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const double* alpha,
+ const double* a,
+ FINTEGER* lda,
+ const double* b,
+ FINTEGER* ldb,
+ double* beta,
+ double* c,
+ FINTEGER* ldc);
+
+int ssyrk_(
+ const char* uplo,
+ const char* trans,
+ FINTEGER* n,
+ FINTEGER* k,
+ float* alpha,
+ float* a,
+ FINTEGER* lda,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+
+/* Lapack functions from http://www.netlib.org/clapack/old/single/ */
+
+int ssyev_(
+ const char* jobz,
+ const char* uplo,
+ FINTEGER* n,
+ float* a,
+ FINTEGER* lda,
+ float* w,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+int dsyev_(
+ const char* jobz,
+ const char* uplo,
+ FINTEGER* n,
+ double* a,
+ FINTEGER* lda,
+ double* w,
+ double* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+int sgesvd_(
+ const char* jobu,
+ const char* jobvt,
+ FINTEGER* m,
+ FINTEGER* n,
+ float* a,
+ FINTEGER* lda,
+ float* s,
+ float* u,
+ FINTEGER* ldu,
+ float* vt,
+ FINTEGER* ldvt,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+int dgesvd_(
+ const char* jobu,
+ const char* jobvt,
+ FINTEGER* m,
+ FINTEGER* n,
+ double* a,
+ FINTEGER* lda,
+ double* s,
+ double* u,
+ FINTEGER* ldu,
+ double* vt,
+ FINTEGER* ldvt,
+ double* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+}
+
+/*********************************************
+ * VectorTransform
+ *********************************************/
+
+float* VectorTransform::apply(idx_t n, const float* x) const {
+ float* xt = new float[n * d_out];
+ apply_noalloc(n, x, xt);
+ return xt;
+}
+
+void VectorTransform::train(idx_t, const float*) {
+ // does nothing by default
+}
+
+void VectorTransform::reverse_transform(idx_t, const float*, float*) const {
+ FAISS_THROW_MSG("reverse transform not implemented");
+}
+
+void VectorTransform::check_identical(const VectorTransform& other) const {
+ FAISS_THROW_IF_NOT(other.d_in == d_in && other.d_in == d_in);
+}
+
+/*********************************************
+ * LinearTransform
+ *********************************************/
+
+/// both d_in > d_out and d_out < d_in are supported
+LinearTransform::LinearTransform(int d_in, int d_out, bool have_bias)
+ : VectorTransform(d_in, d_out),
+ have_bias(have_bias),
+ is_orthonormal(false),
+ verbose(false) {
+ is_trained = false; // will be trained when A and b are initialized
+}
+
+void LinearTransform::apply_noalloc(idx_t n, const float* x, float* xt) const {
+ FAISS_THROW_IF_NOT_MSG(is_trained, "Transformation not trained yet");
+
+ float c_factor;
+ if (have_bias) {
+ FAISS_THROW_IF_NOT_MSG(b.size() == d_out, "Bias not initialized");
+ float* xi = xt;
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < d_out; j++)
+ *xi++ = b[j];
+ c_factor = 1.0;
+ } else {
+ c_factor = 0.0;
+ }
+
+ FAISS_THROW_IF_NOT_MSG(
+ A.size() == d_out * d_in, "Transformation matrix not initialized");
+
+ float one = 1;
+ FINTEGER nbiti = d_out, ni = n, di = d_in;
+ sgemm_("Transposed",
+ "Not transposed",
+ &nbiti,
+ &ni,
+ &di,
+ &one,
+ A.data(),
+ &di,
+ x,
+ &di,
+ &c_factor,
+ xt,
+ &nbiti);
+}
+
+void LinearTransform::transform_transpose(idx_t n, const float* y, float* x)
+ const {
+ if (have_bias) { // allocate buffer to store bias-corrected data
+ float* y_new = new float[n * d_out];
+ const float* yr = y;
+ float* yw = y_new;
+ for (idx_t i = 0; i < n; i++) {
+ for (int j = 0; j < d_out; j++) {
+ *yw++ = *yr++ - b[j];
+ }
+ }
+ y = y_new;
+ }
+
+ {
+ FINTEGER dii = d_in, doi = d_out, ni = n;
+ float one = 1.0, zero = 0.0;
+ sgemm_("Not",
+ "Not",
+ &dii,
+ &ni,
+ &doi,
+ &one,
+ A.data(),
+ &dii,
+ y,
+ &doi,
+ &zero,
+ x,
+ &dii);
+ }
+
+ if (have_bias)
+ delete[] y;
+}
+
+void LinearTransform::set_is_orthonormal() {
+ if (d_out > d_in) {
+ // not clear what we should do in this case
+ is_orthonormal = false;
+ return;
+ }
+ if (d_out == 0) { // borderline case, unnormalized matrix
+ is_orthonormal = true;
+ return;
+ }
+
+ double eps = 4e-5;
+ FAISS_ASSERT(A.size() >= d_out * d_in);
+ {
+ std::vector<float> ATA(d_out * d_out);
+ FINTEGER dii = d_in, doi = d_out;
+ float one = 1.0, zero = 0.0;
+
+ sgemm_("Transposed",
+ "Not",
+ &doi,
+ &doi,
+ &dii,
+ &one,
+ A.data(),
+ &dii,
+ A.data(),
+ &dii,
+ &zero,
+ ATA.data(),
+ &doi);
+
+ is_orthonormal = true;
+ for (long i = 0; i < d_out; i++) {
+ for (long j = 0; j < d_out; j++) {
+ float v = ATA[i + j * d_out];
+ if (i == j)
+ v -= 1;
+ if (fabs(v) > eps) {
+ is_orthonormal = false;
+ }
+ }
+ }
+ }
+}
+
+void LinearTransform::reverse_transform(idx_t n, const float* xt, float* x)
+ const {
+ if (is_orthonormal) {
+ transform_transpose(n, xt, x);
+ } else {
+ FAISS_THROW_MSG(
+ "reverse transform not implemented for non-orthonormal matrices");
+ }
+}
+
+void LinearTransform::print_if_verbose(
+ const char* name,
+ const std::vector<double>& mat,
+ int n,
+ int d) const {
+ if (!verbose)
+ return;
+ printf("matrix %s: %d*%d [\n", name, n, d);
+ FAISS_THROW_IF_NOT(mat.size() >= n * d);
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < d; j++) {
+ printf("%10.5g ", mat[i * d + j]);
+ }
+ printf("\n");
+ }
+ printf("]\n");
+}
+
+void LinearTransform::check_identical(const VectorTransform& other_in) const {
+ VectorTransform::check_identical(other_in);
+ auto other = dynamic_cast<const LinearTransform*>(&other_in);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->A == A && other->b == b);
+}
+
+/*********************************************
+ * RandomRotationMatrix
+ *********************************************/
+
+void RandomRotationMatrix::init(int seed) {
+ if (d_out <= d_in) {
+ A.resize(d_out * d_in);
+ float* q = A.data();
+ float_randn(q, d_out * d_in, seed);
+ matrix_qr(d_in, d_out, q);
+ } else {
+ // use tight-frame transformation
+ A.resize(d_out * d_out);
+ float* q = A.data();
+ float_randn(q, d_out * d_out, seed);
+ matrix_qr(d_out, d_out, q);
+ // remove columns
+ int i, j;
+ for (i = 0; i < d_out; i++) {
+ for (j = 0; j < d_in; j++) {
+ q[i * d_in + j] = q[i * d_out + j];
+ }
+ }
+ A.resize(d_in * d_out);
+ }
+ is_orthonormal = true;
+ is_trained = true;
+}
+
+void RandomRotationMatrix::train(idx_t /*n*/, const float* /*x*/) {
+ // initialize with some arbitrary seed
+ init(12345);
+}
+
+/*********************************************
+ * PCAMatrix
+ *********************************************/
+
+PCAMatrix::PCAMatrix(
+ int d_in,
+ int d_out,
+ float eigen_power,
+ bool random_rotation)
+ : LinearTransform(d_in, d_out, true),
+ eigen_power(eigen_power),
+ random_rotation(random_rotation) {
+ is_trained = false;
+ max_points_per_d = 1000;
+ balanced_bins = 0;
+ epsilon = 0;
+}
+
+namespace {
+
+/// Compute the eigenvalue decomposition of symmetric matrix cov,
+/// dimensions d_in-by-d_in. Output eigenvectors in cov.
+
+void eig(size_t d_in, double* cov, double* eigenvalues, int verbose) {
+ { // compute eigenvalues and vectors
+ FINTEGER info = 0, lwork = -1, di = d_in;
+ double workq;
+
+ dsyev_("Vectors as well",
+ "Upper",
+ &di,
+ cov,
+ &di,
+ eigenvalues,
+ &workq,
+ &lwork,
+ &info);
+ lwork = FINTEGER(workq);
+ double* work = new double[lwork];
+
+ dsyev_("Vectors as well",
+ "Upper",
+ &di,
+ cov,
+ &di,
+ eigenvalues,
+ work,
+ &lwork,
+ &info);
+
+ delete[] work;
+
+ if (info != 0) {
+ fprintf(stderr,
+ "WARN ssyev info returns %d, "
+ "a very bad PCA matrix is learnt\n",
+ int(info));
+ // do not throw exception, as the matrix could still be useful
+ }
+
+ if (verbose && d_in <= 10) {
+ printf("info=%ld new eigvals=[", long(info));
+ for (int j = 0; j < d_in; j++)
+ printf("%g ", eigenvalues[j]);
+ printf("]\n");
+
+ double* ci = cov;
+ printf("eigenvecs=\n");
+ for (int i = 0; i < d_in; i++) {
+ for (int j = 0; j < d_in; j++)
+ printf("%10.4g ", *ci++);
+ printf("\n");
+ }
+ }
+ }
+
+ // revert order of eigenvectors & values
+
+ for (int i = 0; i < d_in / 2; i++) {
+ std::swap(eigenvalues[i], eigenvalues[d_in - 1 - i]);
+ double* v1 = cov + i * d_in;
+ double* v2 = cov + (d_in - 1 - i) * d_in;
+ for (int j = 0; j < d_in; j++)
+ std::swap(v1[j], v2[j]);
+ }
+}
+
+} // namespace
+
+void PCAMatrix::train(idx_t n, const float* x_in) {
+ const float* x = fvecs_maybe_subsample(
+ d_in, (size_t*)&n, max_points_per_d * d_in, x_in, verbose);
+ TransformedVectors tv(x_in, x);
+
+ // compute mean
+ mean.clear();
+ mean.resize(d_in, 0.0);
+ if (have_bias) { // we may want to skip the bias
+ const float* xi = x;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < d_in; j++)
+ mean[j] += *xi++;
+ }
+ for (int j = 0; j < d_in; j++)
+ mean[j] /= n;
+ }
+ if (verbose) {
+ printf("mean=[");
+ for (int j = 0; j < d_in; j++)
+ printf("%g ", mean[j]);
+ printf("]\n");
+ }
+
+ if (n >= d_in) {
+ // compute covariance matrix, store it in PCA matrix
+ PCAMat.resize(d_in * d_in);
+ float* cov = PCAMat.data();
+ { // initialize with mean * mean^T term
+ float* ci = cov;
+ for (int i = 0; i < d_in; i++) {
+ for (int j = 0; j < d_in; j++)
+ *ci++ = -n * mean[i] * mean[j];
+ }
+ }
+ {
+ FINTEGER di = d_in, ni = n;
+ float one = 1.0;
+ ssyrk_("Up",
+ "Non transposed",
+ &di,
+ &ni,
+ &one,
+ (float*)x,
+ &di,
+ &one,
+ cov,
+ &di);
+ }
+ if (verbose && d_in <= 10) {
+ float* ci = cov;
+ printf("cov=\n");
+ for (int i = 0; i < d_in; i++) {
+ for (int j = 0; j < d_in; j++)
+ printf("%10g ", *ci++);
+ printf("\n");
+ }
+ }
+
+ std::vector<double> covd(d_in * d_in);
+ for (size_t i = 0; i < d_in * d_in; i++)
+ covd[i] = cov[i];
+
+ std::vector<double> eigenvaluesd(d_in);
+
+ eig(d_in, covd.data(), eigenvaluesd.data(), verbose);
+
+ for (size_t i = 0; i < d_in * d_in; i++)
+ PCAMat[i] = covd[i];
+ eigenvalues.resize(d_in);
+
+ for (size_t i = 0; i < d_in; i++)
+ eigenvalues[i] = eigenvaluesd[i];
+
+ } else {
+ std::vector<float> xc(n * d_in);
+
+ for (size_t i = 0; i < n; i++)
+ for (size_t j = 0; j < d_in; j++)
+ xc[i * d_in + j] = x[i * d_in + j] - mean[j];
+
+ // compute Gram matrix
+ std::vector<float> gram(n * n);
+ {
+ FINTEGER di = d_in, ni = n;
+ float one = 1.0, zero = 0.0;
+ ssyrk_("Up",
+ "Transposed",
+ &ni,
+ &di,
+ &one,
+ xc.data(),
+ &di,
+ &zero,
+ gram.data(),
+ &ni);
+ }
+
+ if (verbose && d_in <= 10) {
+ float* ci = gram.data();
+ printf("gram=\n");
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < n; j++)
+ printf("%10g ", *ci++);
+ printf("\n");
+ }
+ }
+
+ std::vector<double> gramd(n * n);
+ for (size_t i = 0; i < n * n; i++)
+ gramd[i] = gram[i];
+
+ std::vector<double> eigenvaluesd(n);
+
+ // eig will fill in only the n first eigenvals
+
+ eig(n, gramd.data(), eigenvaluesd.data(), verbose);
+
+ PCAMat.resize(d_in * n);
+
+ for (size_t i = 0; i < n * n; i++)
+ gram[i] = gramd[i];
+
+ eigenvalues.resize(d_in);
+ // fill in only the n first ones
+ for (size_t i = 0; i < n; i++)
+ eigenvalues[i] = eigenvaluesd[i];
+
+ { // compute PCAMat = x' * v
+ FINTEGER di = d_in, ni = n;
+ float one = 1.0;
+
+ sgemm_("Non",
+ "Non Trans",
+ &di,
+ &ni,
+ &ni,
+ &one,
+ xc.data(),
+ &di,
+ gram.data(),
+ &ni,
+ &one,
+ PCAMat.data(),
+ &di);
+ }
+
+ if (verbose && d_in <= 10) {
+ float* ci = PCAMat.data();
+ printf("PCAMat=\n");
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < d_in; j++)
+ printf("%10g ", *ci++);
+ printf("\n");
+ }
+ }
+ fvec_renorm_L2(d_in, n, PCAMat.data());
+ }
+
+ prepare_Ab();
+ is_trained = true;
+}
+
+void PCAMatrix::copy_from(const PCAMatrix& other) {
+ FAISS_THROW_IF_NOT(other.is_trained);
+ mean = other.mean;
+ eigenvalues = other.eigenvalues;
+ PCAMat = other.PCAMat;
+ prepare_Ab();
+ is_trained = true;
+}
+
+void PCAMatrix::prepare_Ab() {
+ FAISS_THROW_IF_NOT_FMT(
+ d_out * d_in <= PCAMat.size(),
+ "PCA matrix cannot output %d dimensions from %d ",
+ d_out,
+ d_in);
+
+ if (!random_rotation) {
+ A = PCAMat;
+ A.resize(d_out * d_in); // strip off useless dimensions
+
+ // first scale the components
+ if (eigen_power != 0) {
+ float* ai = A.data();
+ for (int i = 0; i < d_out; i++) {
+ float factor = pow(eigenvalues[i] + epsilon, eigen_power);
+ for (int j = 0; j < d_in; j++)
+ *ai++ *= factor;
+ }
+ }
+
+ if (balanced_bins != 0) {
+ FAISS_THROW_IF_NOT(d_out % balanced_bins == 0);
+ int dsub = d_out / balanced_bins;
+ std::vector<float> Ain;
+ std::swap(A, Ain);
+ A.resize(d_out * d_in);
+
+ std::vector<float> accu(balanced_bins);
+ std::vector<int> counter(balanced_bins);
+
+ // greedy assignment
+ for (int i = 0; i < d_out; i++) {
+ // find best bin
+ int best_j = -1;
+ float min_w = 1e30;
+ for (int j = 0; j < balanced_bins; j++) {
+ if (counter[j] < dsub && accu[j] < min_w) {
+ min_w = accu[j];
+ best_j = j;
+ }
+ }
+ int row_dst = best_j * dsub + counter[best_j];
+ accu[best_j] += eigenvalues[i];
+ counter[best_j]++;
+ memcpy(&A[row_dst * d_in], &Ain[i * d_in], d_in * sizeof(A[0]));
+ }
+
+ if (verbose) {
+ printf(" bin accu=[");
+ for (int i = 0; i < balanced_bins; i++)
+ printf("%g ", accu[i]);
+ printf("]\n");
+ }
+ }
+
+ } else {
+ FAISS_THROW_IF_NOT_MSG(
+ balanced_bins == 0,
+ "both balancing bins and applying a random rotation "
+ "does not make sense");
+ RandomRotationMatrix rr(d_out, d_out);
+
+ rr.init(5);
+
+ // apply scaling on the rotation matrix (right multiplication)
+ if (eigen_power != 0) {
+ for (int i = 0; i < d_out; i++) {
+ float factor = pow(eigenvalues[i], eigen_power);
+ for (int j = 0; j < d_out; j++)
+ rr.A[j * d_out + i] *= factor;
+ }
+ }
+
+ A.resize(d_in * d_out);
+ {
+ FINTEGER dii = d_in, doo = d_out;
+ float one = 1.0, zero = 0.0;
+
+ sgemm_("Not",
+ "Not",
+ &dii,
+ &doo,
+ &doo,
+ &one,
+ PCAMat.data(),
+ &dii,
+ rr.A.data(),
+ &doo,
+ &zero,
+ A.data(),
+ &dii);
+ }
+ }
+
+ b.clear();
+ b.resize(d_out);
+
+ for (int i = 0; i < d_out; i++) {
+ float accu = 0;
+ for (int j = 0; j < d_in; j++)
+ accu -= mean[j] * A[j + i * d_in];
+ b[i] = accu;
+ }
+
+ is_orthonormal = eigen_power == 0;
+}
+
+/*********************************************
+ * ITQMatrix
+ *********************************************/
+
+ITQMatrix::ITQMatrix(int d)
+ : LinearTransform(d, d, false), max_iter(50), seed(123) {}
+
+/** translated from fbcode/deeplearning/catalyzer/catalyzer/quantizers.py */
+void ITQMatrix::train(idx_t n, const float* xf) {
+ size_t d = d_in;
+ std::vector<double> rotation(d * d);
+
+ if (init_rotation.size() == d * d) {
+ memcpy(rotation.data(),
+ init_rotation.data(),
+ d * d * sizeof(rotation[0]));
+ } else {
+ RandomRotationMatrix rrot(d, d);
+ rrot.init(seed);
+ for (size_t i = 0; i < d * d; i++) {
+ rotation[i] = rrot.A[i];
+ }
+ }
+
+ std::vector<double> x(n * d);
+
+ for (size_t i = 0; i < n * d; i++) {
+ x[i] = xf[i];
+ }
+
+ std::vector<double> rotated_x(n * d), cov_mat(d * d);
+ std::vector<double> u(d * d), vt(d * d), singvals(d);
+
+ for (int i = 0; i < max_iter; i++) {
+ print_if_verbose("rotation", rotation, d, d);
+ { // rotated_data = np.dot(training_data, rotation)
+ FINTEGER di = d, ni = n;
+ double one = 1, zero = 0;
+ dgemm_("N",
+ "N",
+ &di,
+ &ni,
+ &di,
+ &one,
+ rotation.data(),
+ &di,
+ x.data(),
+ &di,
+ &zero,
+ rotated_x.data(),
+ &di);
+ }
+ print_if_verbose("rotated_x", rotated_x, n, d);
+ // binarize
+ for (size_t j = 0; j < n * d; j++) {
+ rotated_x[j] = rotated_x[j] < 0 ? -1 : 1;
+ }
+ // covariance matrix
+ { // rotated_data = np.dot(training_data, rotation)
+ FINTEGER di = d, ni = n;
+ double one = 1, zero = 0;
+ dgemm_("N",
+ "T",
+ &di,
+ &di,
+ &ni,
+ &one,
+ rotated_x.data(),
+ &di,
+ x.data(),
+ &di,
+ &zero,
+ cov_mat.data(),
+ &di);
+ }
+ print_if_verbose("cov_mat", cov_mat, d, d);
+ // SVD
+ {
+ FINTEGER di = d;
+ FINTEGER lwork = -1, info;
+ double lwork1;
+
+ // workspace query
+ dgesvd_("A",
+ "A",
+ &di,
+ &di,
+ cov_mat.data(),
+ &di,
+ singvals.data(),
+ u.data(),
+ &di,
+ vt.data(),
+ &di,
+ &lwork1,
+ &lwork,
+ &info);
+
+ FAISS_THROW_IF_NOT(info == 0);
+ lwork = size_t(lwork1);
+ std::vector<double> work(lwork);
+ dgesvd_("A",
+ "A",
+ &di,
+ &di,
+ cov_mat.data(),
+ &di,
+ singvals.data(),
+ u.data(),
+ &di,
+ vt.data(),
+ &di,
+ work.data(),
+ &lwork,
+ &info);
+ FAISS_THROW_IF_NOT_FMT(info == 0, "sgesvd returned info=%d", info);
+ }
+ print_if_verbose("u", u, d, d);
+ print_if_verbose("vt", vt, d, d);
+ // update rotation
+ {
+ FINTEGER di = d;
+ double one = 1, zero = 0;
+ dgemm_("N",
+ "T",
+ &di,
+ &di,
+ &di,
+ &one,
+ u.data(),
+ &di,
+ vt.data(),
+ &di,
+ &zero,
+ rotation.data(),
+ &di);
+ }
+ print_if_verbose("final rot", rotation, d, d);
+ }
+ A.resize(d * d);
+ for (size_t i = 0; i < d; i++) {
+ for (size_t j = 0; j < d; j++) {
+ A[i + d * j] = rotation[j + d * i];
+ }
+ }
+ is_trained = true;
+}
+
+ITQTransform::ITQTransform(int d_in, int d_out, bool do_pca)
+ : VectorTransform(d_in, d_out),
+ do_pca(do_pca),
+ itq(d_out),
+ pca_then_itq(d_in, d_out, false) {
+ if (!do_pca) {
+ FAISS_THROW_IF_NOT(d_in == d_out);
+ }
+ max_train_per_dim = 10;
+ is_trained = false;
+}
+
+void ITQTransform::train(idx_t n, const float* x_in) {
+ FAISS_THROW_IF_NOT(!is_trained);
+
+ size_t max_train_points = std::max(d_in * max_train_per_dim, 32768);
+ const float* x =
+ fvecs_maybe_subsample(d_in, (size_t*)&n, max_train_points, x_in);
+ TransformedVectors tv(x_in, x);
+
+ std::unique_ptr<float[]> x_norm(new float[n * d_in]);
+ { // normalize
+ int d = d_in;
+
+ mean.resize(d, 0);
+ for (idx_t i = 0; i < n; i++) {
+ for (idx_t j = 0; j < d; j++) {
+ mean[j] += x[i * d + j];
+ }
+ }
+ for (idx_t j = 0; j < d; j++) {
+ mean[j] /= n;
+ }
+ for (idx_t i = 0; i < n; i++) {
+ for (idx_t j = 0; j < d; j++) {
+ x_norm[i * d + j] = x[i * d + j] - mean[j];
+ }
+ }
+ fvec_renorm_L2(d_in, n, x_norm.get());
+ }
+
+ // train PCA
+
+ PCAMatrix pca(d_in, d_out);
+ float* x_pca;
+ std::unique_ptr<float[]> x_pca_del;
+ if (do_pca) {
+ pca.have_bias = false; // for consistency with reference implem
+ pca.train(n, x_norm.get());
+ x_pca = pca.apply(n, x_norm.get());
+ x_pca_del.reset(x_pca);
+ } else {
+ x_pca = x_norm.get();
+ }
+
+ // train ITQ
+ itq.train(n, x_pca);
+
+ // merge PCA and ITQ
+ if (do_pca) {
+ FINTEGER di = d_out, dini = d_in;
+ float one = 1, zero = 0;
+ pca_then_itq.A.resize(d_in * d_out);
+ sgemm_("N",
+ "N",
+ &dini,
+ &di,
+ &di,
+ &one,
+ pca.A.data(),
+ &dini,
+ itq.A.data(),
+ &di,
+ &zero,
+ pca_then_itq.A.data(),
+ &dini);
+ } else {
+ pca_then_itq.A = itq.A;
+ }
+ pca_then_itq.is_trained = true;
+ is_trained = true;
+}
+
+void ITQTransform::apply_noalloc(idx_t n, const float* x, float* xt) const {
+ FAISS_THROW_IF_NOT_MSG(is_trained, "Transformation not trained yet");
+
+ std::unique_ptr<float[]> x_norm(new float[n * d_in]);
+ { // normalize
+ int d = d_in;
+ for (idx_t i = 0; i < n; i++) {
+ for (idx_t j = 0; j < d; j++) {
+ x_norm[i * d + j] = x[i * d + j] - mean[j];
+ }
+ }
+ // this is not really useful if we are going to binarize right
+ // afterwards but OK
+ fvec_renorm_L2(d_in, n, x_norm.get());
+ }
+
+ pca_then_itq.apply_noalloc(n, x_norm.get(), xt);
+}
+
+void ITQTransform::check_identical(const VectorTransform& other_in) const {
+ VectorTransform::check_identical(other_in);
+ auto other = dynamic_cast<const ITQTransform*>(&other_in);
+ FAISS_THROW_IF_NOT(other);
+ pca_then_itq.check_identical(other->pca_then_itq);
+ FAISS_THROW_IF_NOT(other->mean == mean);
+}
+
+/*********************************************
+ * OPQMatrix
+ *********************************************/
+
+OPQMatrix::OPQMatrix(int d, int M, int d2)
+ : LinearTransform(d, d2 == -1 ? d : d2, false), M(M) {
+ is_trained = false;
+ // OPQ is quite expensive to train, so set this right.
+ max_train_points = 256 * 256;
+}
+
+void OPQMatrix::train(idx_t n, const float* x_in) {
+ const float* x = fvecs_maybe_subsample(
+ d_in, (size_t*)&n, max_train_points, x_in, verbose);
+ TransformedVectors tv(x_in, x);
+
+ // To support d_out > d_in, we pad input vectors with 0s to d_out
+ size_t d = d_out <= d_in ? d_in : d_out;
+ size_t d2 = d_out;
+
+#if 0
+ // what this test shows: the only way of getting bit-exact
+ // reproducible results with sgeqrf and sgesvd seems to be forcing
+ // single-threading.
+ { // test repro
+ std::vector<float> r (d * d);
+ float * rotation = r.data();
+ float_randn (rotation, d * d, 1234);
+ printf("CS0: %016lx\n",
+ ivec_checksum (128*128, (int*)rotation));
+ matrix_qr (d, d, rotation);
+ printf("CS1: %016lx\n",
+ ivec_checksum (128*128, (int*)rotation));
+ return;
+ }
+#endif
+
+ if (verbose) {
+ printf("OPQMatrix::train: training an OPQ rotation matrix "
+ "for M=%d from %" PRId64 " vectors in %dD -> %dD\n",
+ M,
+ n,
+ d_in,
+ d_out);
+ }
+
+ std::vector<float> xtrain(n * d);
+ // center x
+ {
+ std::vector<float> sum(d);
+ const float* xi = x;
+ for (size_t i = 0; i < n; i++) {
+ for (int j = 0; j < d_in; j++)
+ sum[j] += *xi++;
+ }
+ for (int i = 0; i < d; i++)
+ sum[i] /= n;
+ float* yi = xtrain.data();
+ xi = x;
+ for (size_t i = 0; i < n; i++) {
+ for (int j = 0; j < d_in; j++)
+ *yi++ = *xi++ - sum[j];
+ yi += d - d_in;
+ }
+ }
+ float* rotation;
+
+ if (A.size() == 0) {
+ A.resize(d * d);
+ rotation = A.data();
+ if (verbose)
+ printf(" OPQMatrix::train: making random %zd*%zd rotation\n",
+ d,
+ d);
+ float_randn(rotation, d * d, 1234);
+ matrix_qr(d, d, rotation);
+ // we use only the d * d2 upper part of the matrix
+ A.resize(d * d2);
+ } else {
+ FAISS_THROW_IF_NOT(A.size() == d * d2);
+ rotation = A.data();
+ }
+
+ std::vector<float> xproj(d2 * n), pq_recons(d2 * n), xxr(d * n),
+ tmp(d * d * 4);
+
+ ProductQuantizer pq_default(d2, M, 8);
+ ProductQuantizer& pq_regular = pq ? *pq : pq_default;
+ std::vector<uint8_t> codes(pq_regular.code_size * n);
+
+ double t0 = getmillisecs();
+ for (int iter = 0; iter < niter; iter++) {
+ { // torch.mm(xtrain, rotation:t())
+ FINTEGER di = d, d2i = d2, ni = n;
+ float zero = 0, one = 1;
+ sgemm_("Transposed",
+ "Not transposed",
+ &d2i,
+ &ni,
+ &di,
+ &one,
+ rotation,
+ &di,
+ xtrain.data(),
+ &di,
+ &zero,
+ xproj.data(),
+ &d2i);
+ }
+
+ pq_regular.cp.max_points_per_centroid = 1000;
+ pq_regular.cp.niter = iter == 0 ? niter_pq_0 : niter_pq;
+ pq_regular.verbose = verbose;
+ pq_regular.train(n, xproj.data());
+
+ if (verbose) {
+ printf(" encode / decode\n");
+ }
+ if (pq_regular.assign_index) {
+ pq_regular.compute_codes_with_assign_index(
+ xproj.data(), codes.data(), n);
+ } else {
+ pq_regular.compute_codes(xproj.data(), codes.data(), n);
+ }
+ pq_regular.decode(codes.data(), pq_recons.data(), n);
+
+ float pq_err = fvec_L2sqr(pq_recons.data(), xproj.data(), n * d2) / n;
+
+ if (verbose)
+ printf(" Iteration %d (%d PQ iterations):"
+ "%.3f s, obj=%g\n",
+ iter,
+ pq_regular.cp.niter,
+ (getmillisecs() - t0) / 1000.0,
+ pq_err);
+
+ {
+ float *u = tmp.data(), *vt = &tmp[d * d];
+ float* sing_val = &tmp[2 * d * d];
+ FINTEGER di = d, d2i = d2, ni = n;
+ float one = 1, zero = 0;
+
+ if (verbose) {
+ printf(" X * recons\n");
+ }
+ // torch.mm(xtrain:t(), pq_recons)
+ sgemm_("Not",
+ "Transposed",
+ &d2i,
+ &di,
+ &ni,
+ &one,
+ pq_recons.data(),
+ &d2i,
+ xtrain.data(),
+ &di,
+ &zero,
+ xxr.data(),
+ &d2i);
+
+ FINTEGER lwork = -1, info = -1;
+ float worksz;
+ // workspace query
+ sgesvd_("All",
+ "All",
+ &d2i,
+ &di,
+ xxr.data(),
+ &d2i,
+ sing_val,
+ vt,
+ &d2i,
+ u,
+ &di,
+ &worksz,
+ &lwork,
+ &info);
+
+ lwork = int(worksz);
+ std::vector<float> work(lwork);
+ // u and vt swapped
+ sgesvd_("All",
+ "All",
+ &d2i,
+ &di,
+ xxr.data(),
+ &d2i,
+ sing_val,
+ vt,
+ &d2i,
+ u,
+ &di,
+ work.data(),
+ &lwork,
+ &info);
+
+ sgemm_("Transposed",
+ "Transposed",
+ &di,
+ &d2i,
+ &d2i,
+ &one,
+ u,
+ &di,
+ vt,
+ &d2i,
+ &zero,
+ rotation,
+ &di);
+ }
+ pq_regular.train_type = ProductQuantizer::Train_hot_start;
+ }
+
+ // revert A matrix
+ if (d > d_in) {
+ for (long i = 0; i < d_out; i++)
+ memmove(&A[i * d_in], &A[i * d], sizeof(A[0]) * d_in);
+ A.resize(d_in * d_out);
+ }
+
+ is_trained = true;
+ is_orthonormal = true;
+}
+
+/*********************************************
+ * NormalizationTransform
+ *********************************************/
+
+NormalizationTransform::NormalizationTransform(int d, float norm)
+ : VectorTransform(d, d), norm(norm) {}
+
+NormalizationTransform::NormalizationTransform()
+ : VectorTransform(-1, -1), norm(-1) {}
+
+void NormalizationTransform::apply_noalloc(idx_t n, const float* x, float* xt)
+ const {
+ if (norm == 2.0) {
+ memcpy(xt, x, sizeof(x[0]) * n * d_in);
+ fvec_renorm_L2(d_in, n, xt);
+ } else {
+ FAISS_THROW_MSG("not implemented");
+ }
+}
+
+void NormalizationTransform::reverse_transform(
+ idx_t n,
+ const float* xt,
+ float* x) const {
+ memcpy(x, xt, sizeof(xt[0]) * n * d_in);
+}
+
+void NormalizationTransform::check_identical(
+ const VectorTransform& other_in) const {
+ VectorTransform::check_identical(other_in);
+ auto other = dynamic_cast<const NormalizationTransform*>(&other_in);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->norm == norm);
+}
+
+/*********************************************
+ * CenteringTransform
+ *********************************************/
+
+CenteringTransform::CenteringTransform(int d) : VectorTransform(d, d) {
+ is_trained = false;
+}
+
+void CenteringTransform::train(idx_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(n > 0, "need at least one training vector");
+ mean.resize(d_in, 0);
+ for (idx_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < d_in; j++) {
+ mean[j] += *x++;
+ }
+ }
+
+ for (size_t j = 0; j < d_in; j++) {
+ mean[j] /= n;
+ }
+ is_trained = true;
+}
+
+void CenteringTransform::apply_noalloc(idx_t n, const float* x, float* xt)
+ const {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ for (idx_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < d_in; j++) {
+ *xt++ = *x++ - mean[j];
+ }
+ }
+}
+
+void CenteringTransform::reverse_transform(idx_t n, const float* xt, float* x)
+ const {
+ FAISS_THROW_IF_NOT(is_trained);
+
+ for (idx_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < d_in; j++) {
+ *x++ = *xt++ + mean[j];
+ }
+ }
+}
+
+void CenteringTransform::check_identical(
+ const VectorTransform& other_in) const {
+ VectorTransform::check_identical(other_in);
+ auto other = dynamic_cast<const CenteringTransform*>(&other_in);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->mean == mean);
+}
+
+/*********************************************
+ * RemapDimensionsTransform
+ *********************************************/
+
+RemapDimensionsTransform::RemapDimensionsTransform(
+ int d_in,
+ int d_out,
+ const int* map_in)
+ : VectorTransform(d_in, d_out) {
+ map.resize(d_out);
+ for (int i = 0; i < d_out; i++) {
+ map[i] = map_in[i];
+ FAISS_THROW_IF_NOT(map[i] == -1 || (map[i] >= 0 && map[i] < d_in));
+ }
+}
+
+RemapDimensionsTransform::RemapDimensionsTransform(
+ int d_in,
+ int d_out,
+ bool uniform)
+ : VectorTransform(d_in, d_out) {
+ map.resize(d_out, -1);
+
+ if (uniform) {
+ if (d_in < d_out) {
+ for (int i = 0; i < d_in; i++) {
+ map[i * d_out / d_in] = i;
+ }
+ } else {
+ for (int i = 0; i < d_out; i++) {
+ map[i] = i * d_in / d_out;
+ }
+ }
+ } else {
+ for (int i = 0; i < d_in && i < d_out; i++)
+ map[i] = i;
+ }
+}
+
+void RemapDimensionsTransform::apply_noalloc(idx_t n, const float* x, float* xt)
+ const {
+ for (idx_t i = 0; i < n; i++) {
+ for (int j = 0; j < d_out; j++) {
+ xt[j] = map[j] < 0 ? 0 : x[map[j]];
+ }
+ x += d_in;
+ xt += d_out;
+ }
+}
+
+void RemapDimensionsTransform::reverse_transform(
+ idx_t n,
+ const float* xt,
+ float* x) const {
+ memset(x, 0, sizeof(*x) * n * d_in);
+ for (idx_t i = 0; i < n; i++) {
+ for (int j = 0; j < d_out; j++) {
+ if (map[j] >= 0)
+ x[map[j]] = xt[j];
+ }
+ x += d_in;
+ xt += d_out;
+ }
+}
+
+void RemapDimensionsTransform::check_identical(
+ const VectorTransform& other_in) const {
+ VectorTransform::check_identical(other_in);
+ auto other = dynamic_cast<const RemapDimensionsTransform*>(&other_in);
+ FAISS_THROW_IF_NOT(other);
+ FAISS_THROW_IF_NOT(other->map == map);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/VectorTransform.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/VectorTransform.h
new file mode 100644
index 0000000..8c4e1e4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/VectorTransform.h
@@ -0,0 +1,313 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_VECTOR_TRANSFORM_H
+#define FAISS_VECTOR_TRANSFORM_H
+
+/** Defines a few objects that apply transformations to a set of
+ * vectors Often these are pre-processing steps.
+ */
+
+#include <stdint.h>
+#include <vector>
+
+#include <faiss/Index.h>
+
+namespace faiss {
+
+/** Any transformation applied on a set of vectors */
+struct VectorTransform {
+ int d_in; ///! input dimension
+ int d_out; ///! output dimension
+
+ explicit VectorTransform(int d_in = 0, int d_out = 0)
+ : d_in(d_in), d_out(d_out), is_trained(true) {}
+
+ /// set if the VectorTransform does not require training, or if
+ /// training is done already
+ bool is_trained;
+
+ /** Perform training on a representative set of vectors. Does
+ * nothing by default.
+ *
+ * @param n nb of training vectors
+ * @param x training vecors, size n * d
+ */
+ virtual void train(idx_t n, const float* x);
+
+ /** apply the transformation and return the result in an allocated pointer
+ * @param n number of vectors to transform
+ * @param x input vectors, size n * d_in
+ * @return output vectors, size n * d_out
+ */
+ float* apply(idx_t n, const float* x) const;
+
+ /** apply the transformation and return the result in a provided matrix
+ * @param n number of vectors to transform
+ * @param x input vectors, size n * d_in
+ * @param xt output vectors, size n * d_out
+ */
+ virtual void apply_noalloc(idx_t n, const float* x, float* xt) const = 0;
+
+ /// reverse transformation. May not be implemented or may return
+ /// approximate result
+ virtual void reverse_transform(idx_t n, const float* xt, float* x) const;
+
+ // check that the two transforms are identical (to merge indexes)
+ virtual void check_identical(const VectorTransform& other) const = 0;
+
+ virtual ~VectorTransform() {}
+};
+
+/** Generic linear transformation, with bias term applied on output
+ * y = A * x + b
+ */
+struct LinearTransform : VectorTransform {
+ bool have_bias; ///! whether to use the bias term
+
+ /// check if matrix A is orthonormal (enables reverse_transform)
+ bool is_orthonormal;
+
+ /// Transformation matrix, size d_out * d_in
+ std::vector<float> A;
+
+ /// bias vector, size d_out
+ std::vector<float> b;
+
+ /// both d_in > d_out and d_out < d_in are supported
+ explicit LinearTransform(
+ int d_in = 0,
+ int d_out = 0,
+ bool have_bias = false);
+
+ /// same as apply, but result is pre-allocated
+ void apply_noalloc(idx_t n, const float* x, float* xt) const override;
+
+ /// compute x = A^T * (x - b)
+ /// is reverse transform if A has orthonormal lines
+ void transform_transpose(idx_t n, const float* y, float* x) const;
+
+ /// works only if is_orthonormal
+ void reverse_transform(idx_t n, const float* xt, float* x) const override;
+
+ /// compute A^T * A to set the is_orthonormal flag
+ void set_is_orthonormal();
+
+ bool verbose;
+ void print_if_verbose(
+ const char* name,
+ const std::vector<double>& mat,
+ int n,
+ int d) const;
+
+ void check_identical(const VectorTransform& other) const override;
+
+ ~LinearTransform() override {}
+};
+
+/// Randomly rotate a set of vectors
+struct RandomRotationMatrix : LinearTransform {
+ /// both d_in > d_out and d_out < d_in are supported
+ RandomRotationMatrix(int d_in, int d_out)
+ : LinearTransform(d_in, d_out, false) {}
+
+ /// must be called before the transform is used
+ void init(int seed);
+
+ // initializes with an arbitrary seed
+ void train(idx_t n, const float* x) override;
+
+ RandomRotationMatrix() {}
+};
+
+/** Applies a principal component analysis on a set of vectors,
+ * with optionally whitening and random rotation. */
+struct PCAMatrix : LinearTransform {
+ /** after transformation the components are multiplied by
+ * eigenvalues^eigen_power
+ *
+ * =0: no whitening
+ * =-0.5: full whitening
+ */
+ float eigen_power;
+
+ /// value added to eigenvalues to avoid division by 0 when whitening
+ float epsilon;
+
+ /// random rotation after PCA
+ bool random_rotation;
+
+ /// ratio between # training vectors and dimension
+ size_t max_points_per_d;
+
+ /// try to distribute output eigenvectors in this many bins
+ int balanced_bins;
+
+ /// Mean, size d_in
+ std::vector<float> mean;
+
+ /// eigenvalues of covariance matrix (= squared singular values)
+ std::vector<float> eigenvalues;
+
+ /// PCA matrix, size d_in * d_in
+ std::vector<float> PCAMat;
+
+ // the final matrix is computed after random rotation and/or whitening
+ explicit PCAMatrix(
+ int d_in = 0,
+ int d_out = 0,
+ float eigen_power = 0,
+ bool random_rotation = false);
+
+ /// train on n vectors. If n < d_in then the eigenvector matrix
+ /// will be completed with 0s
+ void train(idx_t n, const float* x) override;
+
+ /// copy pre-trained PCA matrix
+ void copy_from(const PCAMatrix& other);
+
+ /// called after mean, PCAMat and eigenvalues are computed
+ void prepare_Ab();
+};
+
+/** ITQ implementation from
+ *
+ * Iterative quantization: A procrustean approach to learning binary codes
+ * for large-scale image retrieval,
+ *
+ * Yunchao Gong, Svetlana Lazebnik, Albert Gordo, Florent Perronnin,
+ * PAMI'12.
+ */
+
+struct ITQMatrix : LinearTransform {
+ int max_iter;
+ int seed;
+
+ // force initialization of the rotation (for debugging)
+ std::vector<double> init_rotation;
+
+ explicit ITQMatrix(int d = 0);
+
+ void train(idx_t n, const float* x) override;
+};
+
+/** The full ITQ transform, including normalizations and PCA transformation
+ */
+struct ITQTransform : VectorTransform {
+ std::vector<float> mean;
+ bool do_pca;
+ ITQMatrix itq;
+
+ /// max training points per dimension
+ int max_train_per_dim;
+
+ // concatenation of PCA + ITQ transformation
+ LinearTransform pca_then_itq;
+
+ explicit ITQTransform(int d_in = 0, int d_out = 0, bool do_pca = false);
+
+ void train(idx_t n, const float* x) override;
+
+ void apply_noalloc(idx_t n, const float* x, float* xt) const override;
+
+ void check_identical(const VectorTransform& other) const override;
+};
+
+struct ProductQuantizer;
+
+/** Applies a rotation to align the dimensions with a PQ to minimize
+ * the reconstruction error. Can be used before an IndexPQ or an
+ * IndexIVFPQ. The method is the non-parametric version described in:
+ *
+ * "Optimized Product Quantization for Approximate Nearest Neighbor Search"
+ * Tiezheng Ge, Kaiming He, Qifa Ke, Jian Sun, CVPR'13
+ *
+ */
+struct OPQMatrix : LinearTransform {
+ int M; ///< nb of subquantizers
+ int niter = 50; ///< Number of outer training iterations
+ int niter_pq = 4; ///< Number of training iterations for the PQ
+ int niter_pq_0 = 40; ///< same, for the first outer iteration
+
+ /// if there are too many training points, resample
+ size_t max_train_points = 256 * 256;
+ bool verbose = false;
+
+ /// if non-NULL, use this product quantizer for training
+ /// should be constructed with (d_out, M, _)
+ ProductQuantizer* pq = nullptr;
+
+ /// if d2 != -1, output vectors of this dimension
+ explicit OPQMatrix(int d = 0, int M = 1, int d2 = -1);
+
+ void train(idx_t n, const float* x) override;
+};
+
+/** remap dimensions for intput vectors, possibly inserting 0s
+ * strictly speaking this is also a linear transform but we don't want
+ * to compute it with matrix multiplies */
+struct RemapDimensionsTransform : VectorTransform {
+ /// map from output dimension to input, size d_out
+ /// -1 -> set output to 0
+ std::vector<int> map;
+
+ RemapDimensionsTransform(int d_in, int d_out, const int* map);
+
+ /// remap input to output, skipping or inserting dimensions as needed
+ /// if uniform: distribute dimensions uniformly
+ /// otherwise just take the d_out first ones.
+ RemapDimensionsTransform(int d_in, int d_out, bool uniform = true);
+
+ void apply_noalloc(idx_t n, const float* x, float* xt) const override;
+
+ /// reverse transform correct only when the mapping is a permutation
+ void reverse_transform(idx_t n, const float* xt, float* x) const override;
+
+ RemapDimensionsTransform() {}
+
+ void check_identical(const VectorTransform& other) const override;
+};
+
+/** per-vector normalization */
+struct NormalizationTransform : VectorTransform {
+ float norm;
+
+ explicit NormalizationTransform(int d, float norm = 2.0);
+ NormalizationTransform();
+
+ void apply_noalloc(idx_t n, const float* x, float* xt) const override;
+
+ /// Identity transform since norm is not revertible
+ void reverse_transform(idx_t n, const float* xt, float* x) const override;
+
+ void check_identical(const VectorTransform& other) const override;
+};
+
+/** Subtract the mean of each component from the vectors. */
+struct CenteringTransform : VectorTransform {
+ /// Mean, size d_in = d_out
+ std::vector<float> mean;
+
+ explicit CenteringTransform(int d = 0);
+
+ /// train on n vectors.
+ void train(idx_t n, const float* x) override;
+
+ /// subtract the mean
+ void apply_noalloc(idx_t n, const float* x, float* xt) const override;
+
+ /// add the mean
+ void reverse_transform(idx_t n, const float* xt, float* x) const override;
+
+ void check_identical(const VectorTransform& other) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/clone_index.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/clone_index.cpp
new file mode 100644
index 0000000..5a1e5cf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/clone_index.cpp
@@ -0,0 +1,428 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/clone_index.h>
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <faiss/impl/FaissAssert.h>
+
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexAdditiveQuantizerFastScan.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryIVF.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/IndexIVFPQR.h>
+#include <faiss/IndexIVFSpectralHash.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexLattice.h>
+#include <faiss/IndexNSG.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/IndexRowwiseMinMax.h>
+#include <faiss/IndexScalarQuantizer.h>
+
+#include <faiss/MetaIndexes.h>
+#include <faiss/VectorTransform.h>
+
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/impl/pq4_fast_scan.h>
+
+#include <faiss/invlists/BlockInvertedLists.h>
+
+namespace faiss {
+
+/*************************************************************
+ * cloning functions
+ **************************************************************/
+
+Index* clone_index(const Index* index) {
+ Cloner cl;
+ return cl.clone_Index(index);
+}
+
+// assumes there is a copy constructor ready. Always try from most
+// specific to most general. Most indexes don't have complicated
+// structs, the default copy constructor often just works.
+#define TRYCLONE(classname, obj) \
+ if (const classname* clo##classname = \
+ dynamic_cast<const classname*>(obj)) { \
+ return new classname(*clo##classname); \
+ } else
+
+VectorTransform* Cloner::clone_VectorTransform(const VectorTransform* vt) {
+ TRYCLONE(RemapDimensionsTransform, vt)
+ TRYCLONE(OPQMatrix, vt)
+ TRYCLONE(PCAMatrix, vt)
+ TRYCLONE(ITQMatrix, vt)
+ TRYCLONE(RandomRotationMatrix, vt)
+ TRYCLONE(LinearTransform, vt) {
+ FAISS_THROW_MSG("clone not supported for this type of VectorTransform");
+ }
+ return nullptr;
+}
+
+IndexIVF* Cloner::clone_IndexIVF(const IndexIVF* ivf) {
+ TRYCLONE(IndexIVFPQR, ivf)
+ TRYCLONE(IndexIVFPQ, ivf)
+
+ TRYCLONE(IndexIVFLocalSearchQuantizer, ivf)
+ TRYCLONE(IndexIVFProductLocalSearchQuantizer, ivf)
+ TRYCLONE(IndexIVFProductResidualQuantizer, ivf)
+ TRYCLONE(IndexIVFResidualQuantizer, ivf)
+
+ TRYCLONE(IndexIVFLocalSearchQuantizerFastScan, ivf)
+ TRYCLONE(IndexIVFProductLocalSearchQuantizerFastScan, ivf)
+ TRYCLONE(IndexIVFProductResidualQuantizerFastScan, ivf)
+ TRYCLONE(IndexIVFResidualQuantizerFastScan, ivf)
+ TRYCLONE(IndexIVFPQFastScan, ivf)
+
+ TRYCLONE(IndexIVFFlatDedup, ivf)
+ TRYCLONE(IndexIVFFlat, ivf)
+
+ TRYCLONE(IndexIVFSpectralHash, ivf)
+
+ TRYCLONE(IndexIVFScalarQuantizer, ivf) {
+ FAISS_THROW_MSG("clone not supported for this type of IndexIVF");
+ }
+ return nullptr;
+}
+
+IndexBinaryIVF* clone_IndexBinaryIVF(const IndexBinaryIVF* ivf) {
+ TRYCLONE(IndexBinaryIVF, ivf)
+ return nullptr;
+}
+
+IndexRefine* clone_IndexRefine(const IndexRefine* ir) {
+ TRYCLONE(IndexRefineFlat, ir)
+ TRYCLONE(IndexRefine, ir) {
+ FAISS_THROW_MSG("clone not supported for this type of IndexRefine");
+ }
+}
+
+IndexIDMap* clone_IndexIDMap(const IndexIDMap* im) {
+ TRYCLONE(IndexIDMap2, im)
+ TRYCLONE(IndexIDMap, im) {
+ FAISS_THROW_MSG("clone not supported for this type of IndexIDMap");
+ }
+}
+
+IndexHNSW* clone_IndexHNSW(const IndexHNSW* ihnsw) {
+ TRYCLONE(IndexHNSW2Level, ihnsw)
+ TRYCLONE(IndexHNSWFlat, ihnsw)
+ TRYCLONE(IndexHNSWPQ, ihnsw)
+ TRYCLONE(IndexHNSWSQ, ihnsw)
+ TRYCLONE(IndexHNSW, ihnsw) {
+ FAISS_THROW_MSG("clone not supported for this type of IndexHNSW");
+ }
+}
+
+IndexBinaryHNSW* clone_IndexBinaryHNSW(const IndexBinaryHNSW* ihnsw) {
+ TRYCLONE(IndexBinaryHNSW, ihnsw)
+ return nullptr;
+}
+
+IndexNNDescent* clone_IndexNNDescent(const IndexNNDescent* innd) {
+ TRYCLONE(IndexNNDescentFlat, innd)
+ TRYCLONE(IndexNNDescent, innd) {
+ FAISS_THROW_MSG("clone not supported for this type of IndexNNDescent");
+ }
+}
+
+IndexNSG* clone_IndexNSG(const IndexNSG* insg) {
+ TRYCLONE(IndexNSGFlat, insg)
+ TRYCLONE(IndexNSGPQ, insg)
+ TRYCLONE(IndexNSGSQ, insg)
+ TRYCLONE(IndexNSG, insg) {
+ FAISS_THROW_MSG("clone not supported for this type of IndexNNDescent");
+ }
+}
+
+IndexRowwiseMinMaxBase* clone_IndexRowwiseMinMax(
+ const IndexRowwiseMinMaxBase* irmmb) {
+ TRYCLONE(IndexRowwiseMinMaxFP16, irmmb)
+ TRYCLONE(IndexRowwiseMinMax, irmmb) {
+ FAISS_THROW_MSG(
+ "clone not supported for this type of IndexRowwiseMinMax");
+ }
+}
+
+#define TRYCAST(classname) classname* res = dynamic_cast<classname*>(index)
+
+void reset_AdditiveQuantizerIndex(Index* index) {
+ auto clone_ProductQuantizers =
+ [](std::vector<AdditiveQuantizer*>& quantizers) {
+ for (auto& q : quantizers) {
+ q = dynamic_cast<AdditiveQuantizer*>(clone_Quantizer(q));
+ }
+ };
+ if (TRYCAST(IndexIVFLocalSearchQuantizerFastScan)) {
+ res->aq = &res->lsq;
+ } else if (TRYCAST(IndexIVFResidualQuantizerFastScan)) {
+ res->aq = &res->rq;
+ } else if (TRYCAST(IndexIVFProductLocalSearchQuantizerFastScan)) {
+ res->aq = &res->plsq;
+ clone_ProductQuantizers(res->plsq.quantizers);
+ } else if (TRYCAST(IndexIVFProductResidualQuantizerFastScan)) {
+ res->aq = &res->prq;
+ clone_ProductQuantizers(res->prq.quantizers);
+ } else if (TRYCAST(IndexIVFLocalSearchQuantizer)) {
+ res->aq = &res->lsq;
+ } else if (TRYCAST(IndexIVFResidualQuantizer)) {
+ res->aq = &res->rq;
+ } else if (TRYCAST(IndexIVFProductLocalSearchQuantizer)) {
+ res->aq = &res->plsq;
+ clone_ProductQuantizers(res->plsq.quantizers);
+ } else if (TRYCAST(IndexIVFProductResidualQuantizer)) {
+ res->aq = &res->prq;
+ clone_ProductQuantizers(res->prq.quantizers);
+ } else if (TRYCAST(IndexLocalSearchQuantizerFastScan)) {
+ res->aq = &res->lsq;
+ } else if (TRYCAST(IndexResidualQuantizerFastScan)) {
+ res->aq = &res->rq;
+ } else if (TRYCAST(IndexProductLocalSearchQuantizerFastScan)) {
+ res->aq = &res->plsq;
+ clone_ProductQuantizers(res->plsq.quantizers);
+ } else if (TRYCAST(IndexProductResidualQuantizerFastScan)) {
+ res->aq = &res->prq;
+ clone_ProductQuantizers(res->prq.quantizers);
+ } else if (TRYCAST(IndexLocalSearchQuantizer)) {
+ res->aq = &res->lsq;
+ } else if (TRYCAST(IndexResidualQuantizer)) {
+ res->aq = &res->rq;
+ } else if (TRYCAST(IndexProductLocalSearchQuantizer)) {
+ res->aq = &res->plsq;
+ clone_ProductQuantizers(res->plsq.quantizers);
+ } else if (TRYCAST(IndexProductResidualQuantizer)) {
+ res->aq = &res->prq;
+ clone_ProductQuantizers(res->prq.quantizers);
+ } else if (TRYCAST(LocalSearchCoarseQuantizer)) {
+ res->aq = &res->lsq;
+ } else if (TRYCAST(ResidualCoarseQuantizer)) {
+ res->aq = &res->rq;
+ } else {
+ FAISS_THROW_MSG(
+ "clone not supported for this type of additive quantizer index");
+ }
+}
+
+Index* clone_AdditiveQuantizerIndex(const Index* index) {
+ // IndexAdditiveQuantizer
+ TRYCLONE(IndexResidualQuantizer, index)
+ TRYCLONE(IndexProductResidualQuantizer, index)
+ TRYCLONE(IndexLocalSearchQuantizer, index)
+ TRYCLONE(IndexProductLocalSearchQuantizer, index)
+
+ // IndexFastScan
+ TRYCLONE(IndexResidualQuantizerFastScan, index)
+ TRYCLONE(IndexLocalSearchQuantizerFastScan, index)
+ TRYCLONE(IndexProductResidualQuantizerFastScan, index)
+ TRYCLONE(IndexProductLocalSearchQuantizerFastScan, index)
+
+ // AdditiveCoarseQuantizer
+ TRYCLONE(ResidualCoarseQuantizer, index)
+ TRYCLONE(LocalSearchCoarseQuantizer, index) {
+ FAISS_THROW_MSG(
+ "clone not supported for this type of additive quantizer index");
+ }
+}
+
+namespace {
+
+InvertedLists* clone_InvertedLists(const InvertedLists* invlists) {
+ if (auto* ails = dynamic_cast<const ArrayInvertedLists*>(invlists)) {
+ return new ArrayInvertedLists(*ails);
+ }
+ if (auto* bils = dynamic_cast<const BlockInvertedLists*>(invlists)) {
+ auto* bils2 = new BlockInvertedLists(*bils);
+ if (bils->packer) {
+ auto* packerPQ4 = dynamic_cast<const CodePackerPQ4*>(bils->packer);
+ FAISS_THROW_IF_NOT(packerPQ4);
+ bils2->packer = new CodePackerPQ4(*packerPQ4);
+ }
+ return bils2;
+ }
+ FAISS_THROW_FMT(
+ "clone not supported for this type of inverted lists %s",
+ typeid(*invlists).name());
+}
+
+} // anonymous namespace
+
+Index* Cloner::clone_Index(const Index* index) {
+ TRYCLONE(IndexPQ, index)
+ TRYCLONE(IndexLSH, index)
+
+ // IndexFlat
+ TRYCLONE(IndexFlat1D, index)
+ TRYCLONE(IndexFlatL2, index)
+ TRYCLONE(IndexFlatIP, index)
+ TRYCLONE(IndexFlat, index)
+
+ TRYCLONE(IndexLattice, index)
+ TRYCLONE(IndexRandom, index)
+ TRYCLONE(IndexPQFastScan, index)
+
+ TRYCLONE(IndexScalarQuantizer, index)
+ TRYCLONE(MultiIndexQuantizer, index)
+
+ if (const IndexIVF* ivf = dynamic_cast<const IndexIVF*>(index)) {
+ IndexIVF* res = clone_IndexIVF(ivf);
+ if (ivf->invlists == nullptr) {
+ res->invlists = nullptr;
+ } else {
+ res->invlists = clone_InvertedLists(ivf->invlists);
+ res->own_invlists = true;
+ }
+
+ res->own_fields = true;
+ res->quantizer = clone_Index(ivf->quantizer);
+
+ if (dynamic_cast<const IndexIVFAdditiveQuantizerFastScan*>(res) ||
+ dynamic_cast<const IndexIVFAdditiveQuantizer*>(res)) {
+ reset_AdditiveQuantizerIndex(res);
+ }
+ return res;
+ } else if (
+ const IndexPreTransform* ipt =
+ dynamic_cast<const IndexPreTransform*>(index)) {
+ IndexPreTransform* res = new IndexPreTransform();
+ res->d = ipt->d;
+ res->ntotal = ipt->ntotal;
+ res->is_trained = ipt->is_trained;
+ res->metric_type = ipt->metric_type;
+ res->metric_arg = ipt->metric_arg;
+
+ res->index = clone_Index(ipt->index);
+ for (int i = 0; i < ipt->chain.size(); i++)
+ res->chain.push_back(clone_VectorTransform(ipt->chain[i]));
+ res->own_fields = true;
+ return res;
+ } else if (
+ const IndexIDMap* idmap = dynamic_cast<const IndexIDMap*>(index)) {
+ IndexIDMap* res = clone_IndexIDMap(idmap);
+ res->own_fields = true;
+ res->index = clone_Index(idmap->index);
+ return res;
+ } else if (const IndexHNSW* ihnsw = dynamic_cast<const IndexHNSW*>(index)) {
+ IndexHNSW* res = clone_IndexHNSW(ihnsw);
+ res->own_fields = true;
+ // make sure we don't get a GPU index here
+ res->storage = Cloner::clone_Index(ihnsw->storage);
+ return res;
+ } else if (const IndexNSG* insg = dynamic_cast<const IndexNSG*>(index)) {
+ IndexNSG* res = clone_IndexNSG(insg);
+
+ // copy the dynamic allocated graph
+ if (auto& old_graph = insg->nsg.final_graph) {
+ auto& new_graph = res->nsg.final_graph;
+ new_graph = std::make_shared<nsg::Graph<int>>(*old_graph);
+ }
+
+ res->own_fields = true;
+ res->storage = clone_Index(insg->storage);
+ return res;
+ } else if (
+ const IndexNNDescent* innd =
+ dynamic_cast<const IndexNNDescent*>(index)) {
+ IndexNNDescent* res = clone_IndexNNDescent(innd);
+ res->own_fields = true;
+ res->storage = clone_Index(innd->storage);
+ return res;
+ } else if (
+ const Index2Layer* i2l = dynamic_cast<const Index2Layer*>(index)) {
+ Index2Layer* res = new Index2Layer(*i2l);
+ res->q1.own_fields = true;
+ res->q1.quantizer = clone_Index(i2l->q1.quantizer);
+ return res;
+ } else if (
+ const IndexRefine* ir = dynamic_cast<const IndexRefine*>(index)) {
+ IndexRefine* res = clone_IndexRefine(ir);
+ res->own_fields = true;
+ res->base_index = clone_Index(ir->base_index);
+ if (ir->refine_index != nullptr) {
+ res->own_refine_index = true;
+ res->refine_index = clone_Index(ir->refine_index);
+ }
+ return res;
+ } else if (
+ const IndexRowwiseMinMaxBase* irmmb =
+ dynamic_cast<const IndexRowwiseMinMaxBase*>(index)) {
+ IndexRowwiseMinMaxBase* res = clone_IndexRowwiseMinMax(irmmb);
+ res->own_fields = true;
+ res->index = clone_Index(irmmb->index);
+ } else if (
+ dynamic_cast<const IndexAdditiveQuantizerFastScan*>(index) ||
+ dynamic_cast<const IndexAdditiveQuantizer*>(index) ||
+ dynamic_cast<const AdditiveCoarseQuantizer*>(index)) {
+ Index* res = clone_AdditiveQuantizerIndex(index);
+ reset_AdditiveQuantizerIndex(res);
+ return res;
+ } else {
+ FAISS_THROW_FMT(
+ "clone not supported for this Index type %s",
+ typeid(*index).name());
+ }
+ return nullptr;
+} // namespace
+
+Quantizer* clone_Quantizer(const Quantizer* quant) {
+ TRYCLONE(ResidualQuantizer, quant)
+ TRYCLONE(LocalSearchQuantizer, quant)
+ TRYCLONE(ProductQuantizer, quant)
+ TRYCLONE(ScalarQuantizer, quant)
+ FAISS_THROW_MSG("Did not recognize quantizer to clone");
+}
+
+IndexBinary* clone_binary_index(const IndexBinary* index) {
+ if (auto ii = dynamic_cast<const IndexBinaryFlat*>(index)) {
+ return new IndexBinaryFlat(*ii);
+ } else if (
+ const IndexBinaryIVF* ivf =
+ dynamic_cast<const IndexBinaryIVF*>(index)) {
+ IndexBinaryIVF* res = clone_IndexBinaryIVF(ivf);
+ if (ivf->invlists == nullptr) {
+ res->invlists = nullptr;
+ } else {
+ res->invlists = clone_InvertedLists(ivf->invlists);
+ res->own_invlists = true;
+ }
+
+ res->own_fields = true;
+ res->quantizer = clone_binary_index(ivf->quantizer);
+
+ return res;
+ } else if (
+ const IndexBinaryHNSW* ihnsw =
+ dynamic_cast<const IndexBinaryHNSW*>(index)) {
+ IndexBinaryHNSW* res = clone_IndexBinaryHNSW(ihnsw);
+ res->own_fields = true;
+ res->storage = clone_binary_index(ihnsw->storage);
+ return res;
+ } else {
+ FAISS_THROW_MSG("cannot clone this type of index");
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/clone_index.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/clone_index.h
new file mode 100644
index 0000000..a3ae0e4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/clone_index.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+// I/O code for indexes
+
+#pragma once
+
+namespace faiss {
+
+struct Index;
+struct IndexIVF;
+struct VectorTransform;
+struct Quantizer;
+struct IndexBinary;
+
+/* cloning functions */
+Index* clone_index(const Index*);
+
+/** Cloner class, useful to override classes with other cloning
+ * functions. The cloning function above just calls
+ * Cloner::clone_Index. */
+struct Cloner {
+ virtual VectorTransform* clone_VectorTransform(const VectorTransform*);
+ virtual Index* clone_Index(const Index*);
+ virtual IndexIVF* clone_IndexIVF(const IndexIVF*);
+ virtual ~Cloner() {}
+};
+
+Quantizer* clone_Quantizer(const Quantizer* quant);
+
+IndexBinary* clone_binary_index(const IndexBinary* index);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/SaDecodeKernels.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/SaDecodeKernels.h
new file mode 100644
index 0000000..b0e7efe
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/SaDecodeKernels.h
@@ -0,0 +1,322 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// This file contains a custom fast implementation of faiss::Index::sa_decode()
+// function for the following index families:
+// * IVF256,PQ[1]x8np
+// * Residual[1]x8,PQ[2]x8
+// * IVF[2^9-2^16 bit],PQ[1]x8 (such as IVF1024,PQ16np)
+// * Residual1x[9-16 bit],PQ[1]x8 (such as Residual1x9,PQ8)
+// * PQ[1]x8
+// Additionally, AVX2 and ARM versions support
+// * Residual[1]x8,PQ[2]x10
+// * Residual[1]x8,PQ[2]x12
+// * Residual[1]x8,PQ[2]x16
+// * Residual[1]x10,PQ[2]x10
+// * Residual[1]x10,PQ[2]x12
+// * Residual[1]x10,PQ[2]x16
+// * Residual[1]x12,PQ[2]x10
+// * Residual[1]x12,PQ[2]x12
+// * Residual[1]x12,PQ[2]x16
+// * Residual[1]x16,PQ[2]x10
+// * Residual[1]x16,PQ[2]x12
+// * Residual[1]x16,PQ[2]x16
+// * Residual1x[9-16 bit],PQ[1]x10 (such as Residual1x9,PQ16x10)
+// * * (use with COARSE_BITS=16)
+// * Residual1x[9-16 bit],PQ[1]x12 (such as Residual1x9,PQ16x12)
+// * * (use with COARSE_BITS=16)
+// * Residual1x[9-16 bit],PQ[1]x16 (such as Residual1x9,PQ16x16)
+// * * (use with COARSE_BITS=16)
+// * PQ[1]x10
+// * PQ[1]x12
+// * PQ[1]x16
+// * IVF256,PQ[1]x10 (such as IVF256,PQ16x10np)
+// * IVF256,PQ[1]x12 (such as IVF256,PQ16x12np)
+// * IVF256,PQ[1]x16 (such as IVF256,PQ16x16np)
+// * IVF[2^9-2^16 bit],PQ[1]x10 (such as IVF1024,PQ16x10np)
+// * IVF[2^9-2^16 bit],PQ[1]x12 (such as IVF1024,PQ16x12np)
+// * IVF[2^9-2^16 bit],PQ[1]x16 (such as IVF1024,PQ16x16np)
+//
+// The goal was to achieve the maximum performance, so the template version it
+// is. The provided index families share the same code for sa_decode.
+//
+// The front-end code provides two high-level structures.
+//
+// First one:
+// {
+// template <
+// intptr_t DIM,
+// intptr_t COARSE_SIZE,
+// intptr_t FINE_SIZE,
+// intptr_t COARSE_BITS = 8
+// intptr_t FINE_BITS = 8>
+// struct Index2LevelDecoder { /*...*/ };
+// }
+// * DIM is the dimensionality of data
+// * COARSE_SIZE is the dimensionality of the coarse quantizer (IVF, Residual)
+// * FINE_SIZE is the dimensionality of the ProductQuantizer dsq
+// * COARSE_BITS is the number of bits that are needed to represent a coarse
+// quantizer code.
+// * FINE_BITS is the number of bits that are needed to represent a fine
+// quantizer code.
+// For example, "IVF256,PQ8np" for 160-dim data translates into
+// Index2LevelDecoder<160,160,20,8>
+// For example, "Residual4x8,PQ16" for 256-dim data translates into
+// Index2LevelDecoder<256,64,1,8>
+// For example, "IVF1024,PQ16np" for 256-dim data translates into
+// Index2LevelDecoder<256,256,16,10>. But as there are only 1 coarse code
+// element, Index2LevelDecoder<256,256,16,16> can be used as a faster
+// decoder.
+// For example, "Residual4x10,PQ16x10np" for 256-dim data translates into
+// Index2LevelDecoder<256,64,16,10,10>
+// For example, "IVF1024,PQ16x10np" for 256-dim data translates into
+// Index2LevelDecoder<256,256,16,10,10>. But as there are only 1 coarse code
+// element, Index2LevelDecoder<256,256,16,16,10> can be used as a faster
+// decoder.
+//
+// Additional supported values for COARSE_BITS and FINE_BITS may be added later.
+//
+// Second one:
+// {
+// template <
+// intptr_t DIM,
+// intptr_t FINE_SIZE,
+// intptr_t FINE_BITS = 8>
+// struct IndexPQDecoder { /*...*/ };
+// }
+// * DIM is the dimensionality of data
+// * FINE_SIZE is the dimensionality of the ProductQuantizer dsq
+// * FINE_BITS is the number of bits that are needed to represent a fine
+// quantizer code.
+// For example, "PQ8np" for 160-dim data translates into
+// IndexPQDecoder<160,20>
+//
+// Unlike the general purpose version in faiss::Index::sa_decode(),
+// this version provides the following functions (please note that
+// pqCoarseCentroids params are not available for IndexPQDecoder,
+// but the functionality is the same as for Index2LevelDecoder):
+//
+// * ::store(), which is similar to sa_decode(1, input, output),
+// The method signature is the following:
+// {
+// void store(
+// const float* const __restrict pqCoarseCentroids,
+// const float* const __restrict pqFineCentroids,
+// const uint8_t* const __restrict code,
+// float* const __restrict outputStore);
+// }
+//
+// * ::accum(), which is used to create a linear combination
+// of decoded vectors:
+// {
+// const faiss::Index* const index;
+// const uint8_t* const input;
+// float weight;
+//
+// std::vector<float> buffer(d, 0);
+//
+// index->sa_decode(1, input, buffer.data());
+// for (size_t iDim = 0; iDim < d; iDim++)
+// output[iDim] += weight * buffer[iDim];
+// }
+// The method signature is the following:
+// {
+// static void accum(
+// const float* const __restrict pqCoarseCentroids,
+// const float* const __restrict pqFineCentroids,
+// const uint8_t* const __restrict code,
+// const float weight,
+// float* const __restrict outputAccum);
+// }
+//
+// * There is an additional overload for ::accum() that decodes two vectors
+// per call. This provides an additional speedup because of a CPU
+// superscalar architecture:
+// {
+// const faiss::Index* const index;
+// const uint8_t* const input0;
+// float weight0;
+// const uint8_t* const input1;
+// float weight1;
+//
+// std::vector<float> buffer(d, 0);
+//
+// index->sa_decode(1, input0, buffer.data());
+// for (size_t iDim = 0; iDim < d; iDim++)
+// output[iDim] += weight0 * buffer[iDim];
+//
+// index->sa_decode(1, input1, buffer.data());
+// for (size_t iDim = 0; iDim < d; iDim++)
+// output[iDim] += weight1 * buffer[iDim];
+// }
+// If each code uses its own coarse quantizer centroids table and its own fine
+// quantizer centroids table, then the following overload can be used:
+// {
+// static void accum(
+// const float* const __restrict pqCoarseCentroids0,
+// const float* const __restrict pqFineCentroids0,
+// const uint8_t* const __restrict code0,
+// const float weight0,
+// const float* const __restrict pqCoarseCentroids1,
+// const float* const __restrict pqFineCentroids1,
+// const uint8_t* const __restrict code1,
+// const float weight1,
+// float* const __restrict outputAccum);
+// }
+// If codes share the coarse quantizer centroids table and also share
+// the fine quantizer centroids table, then the following overload can be
+// used:
+// {
+// static void accum(
+// const float* const __restrict pqCoarseCentroids,
+// const float* const __restrict pqFineCentroids,
+// const uint8_t* const __restrict code0,
+// const float weight0,
+// const uint8_t* const __restrict code1,
+// const float weight1,
+// float* const __restrict outputAccum);
+// }
+//
+// * And one more overload for ::accum() that decodes and accumulates
+// three vectors per call.
+// {
+// const faiss::Index* const index;
+// const uint8_t* const input0;
+// float weight0;
+// const uint8_t* const input1;
+// float weight1;
+// const uint8_t* const input2;
+// float weight2;
+//
+// std::vector<float> buffer(d, 0);
+//
+// index->sa_decode(1, input0, buffer.data());
+// for (size_t iDim = 0; iDim < d; iDim++)
+// output[iDim] += weight0 * buffer[iDim];
+//
+// index->sa_decode(1, input1, buffer.data());
+// for (size_t iDim = 0; iDim < d; iDim++)
+// output[iDim] += weight1 * buffer[iDim];
+//
+// index->sa_decode(1, input2, buffer.data());
+// for (size_t iDim = 0; iDim < d; iDim++)
+// output[iDim] += weight2 * buffer[iDim];
+// }
+//
+// If each code uses its own coarse quantizer centroids table and its own fine
+// quantizer centroids table, then the following overload can be used:
+// {
+// static void accum(
+// const float* const __restrict pqCoarseCentroids0,
+// const float* const __restrict pqFineCentroids0,
+// const uint8_t* const __restrict code0,
+// const float weight0,
+// const float* const __restrict pqCoarseCentroids1,
+// const float* const __restrict pqFineCentroids1,
+// const uint8_t* const __restrict code1,
+// const float weight1,
+// const float* const __restrict pqCoarseCentroids2,
+// const float* const __restrict pqFineCentroids2,
+// const uint8_t* const __restrict code2,
+// const float weight2,
+// float* const __restrict outputAccum);
+// }
+// If codes share the coarse quantizer centroids table and also share
+// the fine quantizer centroids table, then the following overload can be
+// used:
+// {
+// static void accum(
+// const float* const __restrict pqCoarseCentroids,
+// const float* const __restrict pqFineCentroids,
+// const uint8_t* const __restrict code0,
+// const float weight0,
+// const uint8_t* const __restrict code1,
+// const float weight1,
+// const uint8_t* const __restrict code2,
+// const float weight2,
+// float* const __restrict outputAccum);
+// }
+//
+// The provided version is not multithreaded.
+//
+// Currently, an AVX2+FMA implementation is available. AVX512 version is also
+// doable, but it was found to be slower than AVX2 for real world applications
+// that I needed.
+//
+////////////////////////////////////////////////////////////////////////////////////
+//
+// It is possible to use an additional index wrapper on top of IVFPQ /
+// Residual+PQ, known as IndexRowwiseMinMax / IndexRowwiseMinMaxFP16. Index
+// wrapper that performs rowwise normalization to [0,1], preserving the
+// coefficients. This is a vector codec index only.
+// For more details please refer to the description in
+// faiss/IndexRowwiseMinMax.h file.
+//
+// If such a wrapper is used, then the quantizer will look like, say,
+// MinMaxFP16,IVF256,PQ32np
+// or
+// MinMax,PQ16np
+// In this case, please use the following contruction for the decoding,
+// basically, wrapping a kernel in a kernel:
+// {
+// using SubT = faiss::cppcontrib::Index2LevelDecoder<128, 128, 2>;
+// using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+// // do T::store(...) or T::accum(...)
+// }
+//
+// T::accum(...) contains an additional function variable which is
+// used for accumulating scaling. Thus, the code pattern is the following:
+// {
+// const float* const __restrict pqCoarseCentroidsQ;
+// const float* const __restrict pqFineCentroidsQ;
+// const uint8_t* const __restrict input;
+// const float* const __restrict weights;
+// float* const __restrict output;
+// float outputAccumMin = 0;
+//
+// for (size_t i = 0; i < n; i++) {
+// T::accum(
+// pqCoarseCentroidsQ,
+// pqFineCentroidsQ,
+// input + i * code_size,
+// weights[i],
+// output,
+// outputAccumMin);
+// }
+// for (size_t j = 0; j < d; j++)
+// output[j] += outputAccumMin;
+// }
+// This is similar to the following regular pseudo-code:
+// {
+// const faiss::Index* const index;
+// const uint8_t* const __restrict input;
+// const float* const __restrict weights;
+// float* const __restrict output;
+//
+// for (size_t i = 0; i < n; i++) {
+// std::vector<float> buffer(d, 0);
+//
+// index->sa_decode(1, input + i * code_size, buffer.data());
+// for (size_t j = 0; j < d; j++)
+// output[j] += weights[i] * buffer[j];
+// }
+
+#include <faiss/cppcontrib/sa_decode/MinMax-inl.h>
+#include <faiss/cppcontrib/sa_decode/MinMaxFP16-inl.h>
+
+#ifdef __AVX2__
+#include <faiss/cppcontrib/sa_decode/Level2-avx2-inl.h>
+#include <faiss/cppcontrib/sa_decode/PQ-avx2-inl.h>
+#elif defined(__ARM_NEON)
+#include <faiss/cppcontrib/sa_decode/Level2-neon-inl.h>
+#include <faiss/cppcontrib/sa_decode/PQ-neon-inl.h>
+#else
+#include <faiss/cppcontrib/sa_decode/Level2-inl.h>
+#include <faiss/cppcontrib/sa_decode/PQ-inl.h>
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/detail/CoarseBitType.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/detail/CoarseBitType.h
new file mode 100644
index 0000000..2fc8e8d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/detail/CoarseBitType.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+
+namespace faiss {
+namespace cppcontrib {
+namespace detail {
+
+template <int COARSE_BITS>
+struct CoarseBitType {};
+
+template <>
+struct CoarseBitType<8> {
+ using bit_type = uint8_t;
+};
+
+template <>
+struct CoarseBitType<16> {
+ using bit_type = uint16_t;
+};
+
+} // namespace detail
+} // namespace cppcontrib
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/detail/UintReader.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/detail/UintReader.h
new file mode 100644
index 0000000..b02dc41
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/detail/UintReader.h
@@ -0,0 +1,351 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/platform_macros.h>
+#include <cstdint>
+
+namespace faiss {
+namespace cppcontrib {
+namespace detail {
+
+namespace {
+
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct Uint8Reader {
+ static_assert(CPOS < N_ELEMENTS, "CPOS should be less than N_ELEMENTS");
+
+ static intptr_t get(const uint8_t* const __restrict codes) {
+ // Read using 4-bytes, if possible.
+ // Reading using 8-byte takes too many registers somewhy.
+
+ constexpr intptr_t ELEMENT_TO_READ = CPOS / 4;
+ constexpr intptr_t SUB_ELEMENT = CPOS % 4;
+
+ switch (SUB_ELEMENT) {
+ case 0: {
+ if (N_ELEMENTS > CPOS + 3) {
+ const uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 4);
+#ifdef FAISS_BIG_ENDIAN
+ return (code32) >> 24;
+#else
+ return (code32 & 0x000000FF);
+#endif
+ } else {
+ return codes[CPOS];
+ }
+ }
+ case 1: {
+ if (N_ELEMENTS > CPOS + 2) {
+ const uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 4);
+#ifdef FAISS_BIG_ENDIAN
+ return (code32 & 0x00FF0000) >> 16;
+#else
+ return (code32 & 0x0000FF00) >> 8;
+#endif
+ } else {
+ return codes[CPOS];
+ }
+ }
+ case 2: {
+ if (N_ELEMENTS > CPOS + 1) {
+ const uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 4);
+#ifdef FAISS_BIG_ENDIAN
+ return (code32 & 0x0000FF00) >> 8;
+#else
+ return (code32 & 0x00FF0000) >> 16;
+#endif
+ } else {
+ return codes[CPOS];
+ }
+ }
+ case 3: {
+ if (N_ELEMENTS > CPOS) {
+ const uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 4);
+#ifdef FAISS_BIG_ENDIAN
+ return (code32 & 0x000000FF);
+#else
+ return (code32) >> 24;
+#endif
+ } else {
+ return codes[CPOS];
+ }
+ }
+ }
+ }
+};
+
+// reduces the number of read operations from RAM
+///////////////////////////////////////////////
+// 76543210 76543210 76543210 76543210 76543210
+// 00000000 00
+// 111111 1111
+// 2222 222222
+// 33 33333333
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct Uint10Reader {
+ static_assert(CPOS < N_ELEMENTS, "CPOS should be less than N_ELEMENTS");
+
+ static intptr_t get(const uint8_t* const __restrict codes) {
+ // Read using 4-bytes or 2-bytes.
+
+ constexpr intptr_t ELEMENT_TO_READ = CPOS / 4;
+ constexpr intptr_t SUB_ELEMENT = CPOS % 4;
+
+ switch (SUB_ELEMENT) {
+ case 0: {
+ if (N_ELEMENTS > CPOS + 2) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 5);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b0000001111111111);
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 5 + 0);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b0000001111111111);
+ }
+ }
+ case 1: {
+ if (N_ELEMENTS > CPOS + 1) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 5);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b000011111111110000000000) >> 10;
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 5 + 1);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b0000111111111100) >> 2;
+ }
+ }
+ case 2: {
+ if (N_ELEMENTS > CPOS) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 5);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b00111111111100000000000000000000) >> 20;
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 5 + 2);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b0011111111110000) >> 4;
+ }
+ }
+ case 3: {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 5 + 3);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b1111111111000000) >> 6;
+ }
+ }
+ }
+};
+
+// reduces the number of read operations from RAM
+///////////////////////////////////////////////
+// 76543210 76543210 76543210 76543210 76543210 76543210
+// 00000000 0000
+// 1111 11111111
+// 22222222 2222
+// 3333 33333333
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct Uint12Reader {
+ static_assert(CPOS < N_ELEMENTS, "CPOS should be less than N_ELEMENTS");
+
+ static intptr_t get(const uint8_t* const __restrict codes) {
+ // Read using 4-bytes or 2-bytes.
+
+ constexpr intptr_t ELEMENT_TO_READ = CPOS / 4;
+ constexpr intptr_t SUB_ELEMENT = CPOS % 4;
+
+ switch (SUB_ELEMENT) {
+ case 0: {
+ if (N_ELEMENTS > CPOS + 2) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 6);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b0000111111111111);
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 6 + 0);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b0000111111111111);
+ }
+ }
+ case 1: {
+ if (N_ELEMENTS > CPOS + 1) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 6);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b111111111111000000000000) >> 12;
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 6 + 1);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b1111111111110000) >> 4;
+ }
+ }
+ case 2: {
+ if (N_ELEMENTS > CPOS + 1) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 6 + 2);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b000011111111111100000000) >> 8;
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 6 + 3);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b0000111111111111);
+ }
+ }
+ case 3: {
+ if (N_ELEMENTS > CPOS) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 6 + 2);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0b11111111111100000000000000000000) >> 20;
+ } else {
+ uint16_t code16 = *reinterpret_cast<const uint16_t*>(
+ codes + ELEMENT_TO_READ * 6 + 4);
+#ifdef FAISS_BIG_ENDIAN
+ code16 = Swap2Bytes(code16);
+#endif
+ return (code16 & 0b1111111111110000) >> 4;
+ }
+ }
+ }
+ }
+};
+
+// reduces the number of read operations from RAM
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct Uint16Reader {
+ static_assert(CPOS < N_ELEMENTS, "CPOS should be less than N_ELEMENTS");
+
+ static intptr_t get(const uint8_t* const __restrict codes) {
+ // Read using 4-bytes or 2-bytes.
+ // Reading using 8-byte takes too many registers somewhy.
+
+ constexpr intptr_t ELEMENT_TO_READ = CPOS / 2;
+ constexpr intptr_t SUB_ELEMENT = CPOS % 2;
+
+ switch (SUB_ELEMENT) {
+ case 0: {
+ if (N_ELEMENTS > CPOS + 1) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 4);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return (code32 & 0x0000FFFF);
+ } else {
+ const uint16_t* const __restrict codesFp16 =
+ reinterpret_cast<const uint16_t*>(codes);
+#ifdef FAISS_BIG_ENDIAN
+ uint16_t rt = codesFp16[CPOS];
+ rt = Swap2Bytes(rt);
+ return rt;
+#endif
+ return codesFp16[CPOS];
+ }
+ }
+ case 1: {
+ if (N_ELEMENTS > CPOS) {
+ uint32_t code32 = *reinterpret_cast<const uint32_t*>(
+ codes + ELEMENT_TO_READ * 4);
+#ifdef FAISS_BIG_ENDIAN
+ code32 = Swap4Bytes(code32);
+#endif
+ return code32 >> 16;
+ } else {
+ const uint16_t* const __restrict codesFp16 =
+ reinterpret_cast<const uint16_t*>(codes);
+#ifdef FAISS_BIG_ENDIAN
+ uint16_t rt = codesFp16[CPOS];
+ rt = Swap2Bytes(rt);
+ return rt;
+#endif
+ return codesFp16[CPOS];
+ }
+ }
+ }
+ }
+};
+
+//
+template <intptr_t N_ELEMENTS, intptr_t CODE_BITS, intptr_t CPOS>
+struct UintReaderImplType {};
+
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct UintReaderImplType<N_ELEMENTS, 8, CPOS> {
+ using reader_type = Uint8Reader<N_ELEMENTS, CPOS>;
+};
+
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct UintReaderImplType<N_ELEMENTS, 10, CPOS> {
+ using reader_type = Uint10Reader<N_ELEMENTS, CPOS>;
+};
+
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct UintReaderImplType<N_ELEMENTS, 12, CPOS> {
+ using reader_type = Uint12Reader<N_ELEMENTS, CPOS>;
+};
+
+template <intptr_t N_ELEMENTS, intptr_t CPOS>
+struct UintReaderImplType<N_ELEMENTS, 16, CPOS> {
+ using reader_type = Uint16Reader<N_ELEMENTS, CPOS>;
+};
+
+} // namespace
+
+// reduces the number of read operations from RAM
+template <intptr_t DIM, intptr_t CODE_SIZE, intptr_t CODE_BITS, intptr_t CPOS>
+using UintReader =
+ typename UintReaderImplType<DIM / CODE_SIZE, CODE_BITS, CPOS>::
+ reader_type;
+
+template <intptr_t N_ELEMENTS, intptr_t CODE_BITS, intptr_t CPOS>
+using UintReaderRaw =
+ typename UintReaderImplType<N_ELEMENTS, CODE_BITS, CPOS>::reader_type;
+
+} // namespace detail
+} // namespace cppcontrib
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/docker_dev/Dockerfile b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/docker_dev/Dockerfile
new file mode 100644
index 0000000..a31a9e3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/docker_dev/Dockerfile
@@ -0,0 +1,10 @@
+FROM ubuntu:22.04
+
+RUN apt update && apt install -y python3 python3-pip gcc g++ mc git swig sudo libomp-dev libopenblas-dev wget
+RUN pip3 install numpy==1.26.4 scipy pytest
+RUN cd /root && git clone https://github.com/facebookresearch/faiss
+RUN wget -qO- "https://cmake.org/files/v3.26/cmake-3.26.5-linux-x86_64.tar.gz" | sudo tar --strip-components=1 -xz -C /usr/local
+RUN cd /root/faiss && /usr/local/bin/cmake -B build -DFAISS_ENABLE_GPU=OFF -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release .
+RUN cd /root/faiss && make -C build -j 8 faiss
+RUN cd /root/faiss && make -C build -j 8 swigfaiss
+RUN cd /root/faiss/build/faiss/python && python3 setup.py install
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/factory_tools.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/factory_tools.cpp
new file mode 100644
index 0000000..46ffada
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/factory_tools.cpp
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/cppcontrib/factory_tools.h>
+
+#include <map>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryIVF.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/IndexIDMap.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexNSG.h>
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRefine.h>
+
+namespace faiss {
+
+namespace {
+
+const std::map<faiss::ScalarQuantizer::QuantizerType, std::string> sq_types = {
+ {faiss::ScalarQuantizer::QT_8bit, "SQ8"},
+ {faiss::ScalarQuantizer::QT_4bit, "SQ4"},
+ {faiss::ScalarQuantizer::QT_6bit, "SQ6"},
+ {faiss::ScalarQuantizer::QT_fp16, "SQfp16"},
+ {faiss::ScalarQuantizer::QT_bf16, "SQbf16"},
+ {faiss::ScalarQuantizer::QT_8bit_direct_signed, "SQ8_direct_signed"},
+ {faiss::ScalarQuantizer::QT_8bit_direct, "SQ8_direct"},
+};
+
+int get_hnsw_M(const faiss::IndexHNSW* index) {
+ if (index->hnsw.cum_nneighbor_per_level.size() > 1) {
+ return index->hnsw.cum_nneighbor_per_level[1] / 2;
+ }
+ // Avoid runtime error, just return 0.
+ return 0;
+}
+
+int get_hnsw_M(const faiss::IndexBinaryHNSW* index) {
+ if (index->hnsw.cum_nneighbor_per_level.size() > 1) {
+ return index->hnsw.cum_nneighbor_per_level[1] / 2;
+ }
+ // Avoid runtime error, just return 0.
+ return 0;
+}
+
+} // namespace
+
+// Reference for reverse_index_factory:
+// https://github.com/facebookresearch/faiss/blob/838612c9d7f2f619811434ec9209c020f44107cb/contrib/factory_tools.py#L81
+std::string reverse_index_factory(const faiss::Index* index) {
+ std::string prefix;
+ if (dynamic_cast<const faiss::IndexFlat*>(index)) {
+ return "Flat";
+ } else if (
+ const faiss::IndexIVF* ivf_index =
+ dynamic_cast<const faiss::IndexIVF*>(index)) {
+ const faiss::Index* quantizer = ivf_index->quantizer;
+
+ if (dynamic_cast<const faiss::IndexFlat*>(quantizer)) {
+ prefix = "IVF" + std::to_string(ivf_index->nlist);
+ } else if (
+ const faiss::MultiIndexQuantizer* miq =
+ dynamic_cast<const faiss::MultiIndexQuantizer*>(
+ quantizer)) {
+ prefix = "IMI" + std::to_string(miq->pq.M) + "x" +
+ std::to_string(miq->pq.nbits);
+ } else if (
+ const faiss::IndexHNSW* hnsw_index =
+ dynamic_cast<const faiss::IndexHNSW*>(quantizer)) {
+ prefix = "IVF" + std::to_string(ivf_index->nlist) + "_HNSW" +
+ std::to_string(get_hnsw_M(hnsw_index));
+ } else {
+ prefix = "IVF" + std::to_string(ivf_index->nlist) + "(" +
+ reverse_index_factory(quantizer) + ")";
+ }
+
+ if (dynamic_cast<const faiss::IndexIVFFlat*>(ivf_index)) {
+ return prefix + ",Flat";
+ } else if (
+ auto sq_index =
+ dynamic_cast<const faiss::IndexIVFScalarQuantizer*>(
+ ivf_index)) {
+ return prefix + "," + sq_types.at(sq_index->sq.qtype);
+ } else if (
+ const faiss::IndexIVFPQ* ivfpq_index =
+ dynamic_cast<const faiss::IndexIVFPQ*>(ivf_index)) {
+ return prefix + ",PQ" + std::to_string(ivfpq_index->pq.M) + "x" +
+ std::to_string(ivfpq_index->pq.nbits);
+ } else if (
+ const faiss::IndexIVFPQFastScan* ivfpqfs_index =
+ dynamic_cast<const faiss::IndexIVFPQFastScan*>(
+ ivf_index)) {
+ return prefix + ",PQ" + std::to_string(ivfpqfs_index->pq.M) + "x" +
+ std::to_string(ivfpqfs_index->pq.nbits) + "fs";
+ }
+ } else if (
+ const faiss::IndexPreTransform* pretransform_index =
+ dynamic_cast<const faiss::IndexPreTransform*>(index)) {
+ if (pretransform_index->chain.size() != 1) {
+ // Avoid runtime error, just return empty string for logging.
+ return "";
+ }
+ const faiss::VectorTransform* vt = pretransform_index->chain.at(0);
+ if (const faiss::OPQMatrix* opq_matrix =
+ dynamic_cast<const faiss::OPQMatrix*>(vt)) {
+ prefix = "OPQ" + std::to_string(opq_matrix->M) + "_" +
+ std::to_string(opq_matrix->d_out);
+ } else if (
+ const faiss::ITQTransform* itq_transform =
+ dynamic_cast<const faiss::ITQTransform*>(vt)) {
+ prefix = "ITQ" + std::to_string(itq_transform->itq.d_out);
+ } else if (
+ const faiss::PCAMatrix* pca_matrix =
+ dynamic_cast<const faiss::PCAMatrix*>(vt)) {
+ assert(pca_matrix->eigen_power == 0);
+ prefix = "PCA" +
+ std::string(pca_matrix->random_rotation ? "R" : "") +
+ std::to_string(pca_matrix->d_out);
+ } else {
+ // Avoid runtime error, just return empty string for logging.
+ return "";
+ }
+ return prefix + "," + reverse_index_factory(pretransform_index->index);
+ } else if (
+ const faiss::IndexHNSW* hnsw_index =
+ dynamic_cast<const faiss::IndexHNSW*>(index)) {
+ return "HNSW" + std::to_string(get_hnsw_M(hnsw_index));
+ } else if (
+ const faiss::IndexNSG* nsg_index =
+ dynamic_cast<const faiss::IndexNSG*>(index)) {
+ return "NSG" + std::to_string(nsg_index->nsg.R) + "," +
+ reverse_index_factory(nsg_index->storage);
+ } else if (
+ const faiss::IndexRefine* refine_index =
+ dynamic_cast<const faiss::IndexRefine*>(index)) {
+ return reverse_index_factory(refine_index->base_index) + ",Refine(" +
+ reverse_index_factory(refine_index->refine_index) + ")";
+ } else if (
+ const faiss::IndexPQFastScan* pqfs_index =
+ dynamic_cast<const faiss::IndexPQFastScan*>(index)) {
+ return std::string("PQ") + std::to_string(pqfs_index->pq.M) + "x" +
+ std::to_string(pqfs_index->pq.nbits) + "fs";
+ } else if (
+ const faiss::IndexPQ* pq_index =
+ dynamic_cast<const faiss::IndexPQ*>(index)) {
+ return std::string("PQ") + std::to_string(pq_index->pq.M) + "x" +
+ std::to_string(pq_index->pq.nbits);
+ } else if (
+ const faiss::IndexLSH* lsh_index =
+ dynamic_cast<const faiss::IndexLSH*>(index)) {
+ std::string result = "LSH";
+ if (lsh_index->rotate_data) {
+ result += "r";
+ }
+ if (lsh_index->train_thresholds) {
+ result += "t";
+ }
+ return result;
+ } else if (
+ const faiss::IndexScalarQuantizer* sq_index =
+ dynamic_cast<const faiss::IndexScalarQuantizer*>(index)) {
+ return sq_types.at(sq_index->sq.qtype);
+ } else if (
+ const faiss::IndexIDMap* idmap =
+ dynamic_cast<const faiss::IndexIDMap*>(index)) {
+ return std::string("IDMap,") + reverse_index_factory(idmap->index);
+ }
+ // Avoid runtime error, just return empty string for logging.
+ return "";
+}
+
+std::string reverse_index_factory(const faiss::IndexBinary* index) {
+ std::string prefix;
+ if (dynamic_cast<const faiss::IndexBinaryFlat*>(index)) {
+ return "BFlat";
+ } else if (
+ const faiss::IndexBinaryIVF* ivf_index =
+ dynamic_cast<const faiss::IndexBinaryIVF*>(index)) {
+ const faiss::IndexBinary* quantizer = ivf_index->quantizer;
+
+ if (dynamic_cast<const faiss::IndexBinaryFlat*>(quantizer)) {
+ return "BIVF" + std::to_string(ivf_index->nlist);
+ } else if (
+ const faiss::IndexBinaryHNSW* hnsw_index =
+ dynamic_cast<const faiss::IndexBinaryHNSW*>(
+ quantizer)) {
+ return "BIVF" + std::to_string(ivf_index->nlist) + "_HNSW" +
+ std::to_string(get_hnsw_M(hnsw_index));
+ }
+ // Add further cases for BinaryIVF here.
+ } else if (
+ const faiss::IndexBinaryHNSW* hnsw_index =
+ dynamic_cast<const faiss::IndexBinaryHNSW*>(index)) {
+ return "BHNSW" + std::to_string(get_hnsw_M(hnsw_index));
+ }
+ // Avoid runtime error, just return empty string for logging.
+ return "";
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/factory_tools.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/factory_tools.h
new file mode 100644
index 0000000..20b9237
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/factory_tools.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <string>
+
+namespace faiss {
+
+struct Index;
+struct IndexBinary;
+
+std::string reverse_index_factory(const faiss::Index* index);
+std::string reverse_index_factory(const faiss::IndexBinary* index);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-avx2-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-avx2-inl.h
new file mode 100644
index 0000000..801029e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-avx2-inl.h
@@ -0,0 +1,2072 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef LEVEL2_AVX2_INL_H
+#define LEVEL2_AVX2_INL_H
+
+#include <immintrin.h>
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/cppcontrib/detail/UintReader.h>
+
+namespace faiss {
+namespace cppcontrib {
+
+////////////////////////////////////////////////////////////////////////////////////
+/// Index2LevelDecoder
+////////////////////////////////////////////////////////////////////////////////////
+
+namespace {
+
+// Processes 8 float values.
+// Returns {
+// [0..1] = *coarse[0..1] + *fine0[0..1];
+// [2..3] = *coarse[2..3] + *fine1[0..1];
+// [4..5] = *coarse[4..5] + *fine2[0..1];
+// [6..7] = *coarse[6..7] + *fine3[0..1];
+// }
+inline __m256 elementaryBlock2x4b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float* const __restrict fine2,
+ const float* const __restrict fine3) {
+ // load fine
+ const __m256 fineValue = _mm256_castpd_ps(_mm256_setr_pd(
+ *reinterpret_cast<const double*>(fine0),
+ *reinterpret_cast<const double*>(fine1),
+ *reinterpret_cast<const double*>(fine2),
+ *reinterpret_cast<const double*>(fine3)));
+ // load coarse
+ const __m256 coarseValue = _mm256_loadu_ps(coarse);
+
+ // add coarse and fine
+ return _mm256_add_ps(fineValue, coarseValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..1] = existingValue[0..1] + weight * (*coarse[0..1] + *fine0[0..1]);
+// [2..3] = existingValue[0..1] + weight * (*coarse[2..3] + *fine1[0..1]);
+// [4..5] = existingValue[0..1] + weight * (*coarse[4..5] + *fine2[0..1]);
+// [6..7] = existingValue[0..1] + weight * (*coarse[6..7] + *fine3[0..1]);
+// }
+inline __m256 elementaryBlock2x4bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float* const __restrict fine2,
+ const float* const __restrict fine3,
+ const float weight,
+ const __m256 existingValue) {
+ // add coarse and fine
+ const __m256 combinedValue =
+ elementaryBlock2x4b(coarse, fine0, fine1, fine2, fine3);
+
+ // this operation is expected to be optimized by a compiler
+ const __m256 weightAvx2 = _mm256_set1_ps(weight);
+ // do fma
+ return _mm256_fmadd_ps(combinedValue, weightAvx2, existingValue);
+}
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = *coarse[0..3] + *fine[0..3];
+// }
+inline __m128 elementaryBlock4x1b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine) {
+ // load fine
+ const __m128 fineValue = _mm_loadu_ps(fine);
+ // load coarse
+ const __m128 coarseValue = _mm_loadu_ps(coarse);
+
+ // add coarse and fine
+ return _mm_add_ps(fineValue, coarseValue);
+}
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*coarse[0..3] + *fine[0..3]);
+// }
+inline __m128 elementaryBlock4x1bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine,
+ const float weight,
+ const __m128 existingValue) {
+ // add coarse and fine
+ const __m128 combinedValue = elementaryBlock4x1b(coarse, fine);
+
+ // this operation is expected to be optimized by a compiler
+ const __m128 weightAvx = _mm_set1_ps(weight);
+ // do fma
+ return _mm_fmadd_ps(combinedValue, weightAvx, existingValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = *coarse[0..3] + *fine0[0..3];
+// [4..7] = *coarse[4..7] + *fine1[0..3];
+// }
+inline __m256 elementaryBlock4x2b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine0,
+ const float* const __restrict fine1) {
+ // load fine
+ const __m128 fineValue0 = _mm_loadu_ps(fine0);
+ const __m128 fineValue1 = _mm_loadu_ps(fine1);
+ // load coarse
+ const __m256 coarseValue = _mm256_loadu_ps(coarse);
+
+ // combine two 4b into a single 8b
+ const __m256 combinedFineValue = _mm256_set_m128(fineValue1, fineValue0);
+ // add coarse and fine
+ return _mm256_add_ps(combinedFineValue, coarseValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*coarse[0..3] + *fine0[0..3]);
+// [4..7] = existingValue[4..7] + weight * (*coarse[4..7] + *fine1[0..3]);
+// }
+inline __m256 elementaryBlock4x2bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float weight,
+ const __m256 existingValue) {
+ // add coarse and fine
+ const __m256 combinedValue = elementaryBlock4x2b(coarse, fine0, fine1);
+
+ // this operation is expected to be optimized by a compiler
+ const __m256 weightAvx2 = _mm256_set1_ps(weight);
+ // do fma
+ return _mm256_fmadd_ps(combinedValue, weightAvx2, existingValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = *coarse[0..7] + *fine[0..7];
+// }
+inline __m256 elementaryBlock8x1b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine) {
+ // load fine
+ const __m256 fineValue = _mm256_loadu_ps(fine);
+ // load coarse
+ const __m256 coarseValue = _mm256_loadu_ps(coarse);
+
+ // add coarse and fine
+ return _mm256_add_ps(fineValue, coarseValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = existingValue[0..7] + weight * (*coarse[0..7] + *fine[0..7]);
+// }
+inline __m256 elementaryBlock8x1bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine,
+ const float weight,
+ const __m256 existingValue) {
+ // add coarse and fine
+ const __m256 combinedValue = elementaryBlock8x1b(coarse, fine);
+
+ // this operation is expected to be optimized by a compiler
+ const __m256 weightAvx2 = _mm256_set1_ps(weight);
+ // do fma
+ return _mm256_fmadd_ps(combinedValue, weightAvx2, existingValue);
+}
+
+// The following code uses template-based for-loop unrolling,
+// because the compiler does not do that on its own as needed.
+// The idea is the following:
+// template<int I, int MAX>
+// struct Foo {
+// static void bar() {
+// doSomething(I);
+// Foo<I + 1, MAX>::bar();
+// }
+// };
+//
+// template<int MAX>
+// struct Foo<MAX, MAX> {
+// static void bar() {}
+// };
+//
+// Initiate the loop:
+// Foo<0, MAX>::bar();
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool FINE_SIZE_EQ_2 = FINE_SIZE == 2,
+ bool FINE_SIZE_EQ_4 = FINE_SIZE == 4,
+ bool QPOS_LEFT_GE_8 = (FINE_SIZE - CPOS % FINE_SIZE >= 8),
+ bool QPOS_LEFT_GE_4 = (FINE_SIZE - CPOS % FINE_SIZE >= 4),
+ bool DIM_EQ_CPOS = DIM == CPOS>
+struct Index2LevelDecoderImpl;
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ 2,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ true,
+ false,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ false> {
+ static constexpr intptr_t FINE_SIZE = 2;
+
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 2 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+
+ const __m256 storeValue = elementaryBlock2x4b(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset);
+
+ _mm256_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::store(
+ pqCoarseCentroids0, pqFineCentroids0, code0,
+ outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 2 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset, weight0,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 2 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+ const intptr_t fineCode2c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine2);
+ const intptr_t fineCode2d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids2 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode2c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode2d) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ pqCoarseCentroids2, pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+ const intptr_t fineCode2c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine2);
+ const intptr_t fineCode2d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode2c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode2d) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ 4,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ false,
+ true,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ false> {
+ static constexpr intptr_t FINE_SIZE = 4;
+
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+
+ const __m256 storeValue = elementaryBlock4x2b(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset);
+
+ _mm256_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::store(
+ pqCoarseCentroids0, pqFineCentroids0, code0,
+ outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids2 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ pqCoarseCentroids2, pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ false,
+ false,
+ true,
+ true,
+ false> {
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ const __m256 storeValue = elementaryBlock8x1b(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset);
+
+ _mm256_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::store(
+ pqCoarseCentroids0, pqFineCentroids0, code0,
+ outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids2 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids2 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ pqCoarseCentroids2, pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 8>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ false,
+ false,
+ false,
+ true,
+ false> {
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ const __m128 storeValue = elementaryBlock4x1b(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset);
+
+ _mm_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 4>::store(
+ pqCoarseCentroids0, pqFineCentroids0, code0,
+ outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS,fineCentroidIdx>::get(fine0);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 4>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 4>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 4>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids0 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids1 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids2 + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids2 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 4>::accum(
+ pqCoarseCentroids0, pqFineCentroids0, code0, weight0,
+ pqCoarseCentroids1, pqFineCentroids1, code1, weight1,
+ pqCoarseCentroids2, pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse0);
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t coarseCode1 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse1);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t coarseCode2 = detail::UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::get(coarse2);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids + (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) * COARSE_SIZE + coarseCentroidOffset,
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<DIM, COARSE_SIZE, FINE_SIZE, COARSE_BITS, FINE_BITS, CPOS + 4>::accum(
+ pqCoarseCentroids, pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+// This partial specialization is expected to do nothing.
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ bool FINE_SIZE_EQ_2,
+ bool FINE_SIZE_EQ_4,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ DIM,
+ FINE_SIZE_EQ_2,
+ FINE_SIZE_EQ_4,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ true> {
+ // clang-format off
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {}
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+
+ // clang-format on
+};
+} // namespace
+
+// Suitable for IVF256,PQ[1]x8
+// Subtable for IVF256,PQ[1]x10 (such as IVF256,PQ16x10np)
+// Subtable for IVF256,PQ[1]x12 (such as IVF256,PQ16x12np)
+// Suitable for IVF256,PQ[1]x16 (such as IVF256,PQ16x16np)
+// Suitable for Residual[1]x8,PQ[2]x8
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x8 (such as IVF1024,PQ16np)
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x10 (such as IVF1024,PQ16x10np)
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x12 (such as IVF1024,PQ16x12np)
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x16 (such as IVF1024,PQ16x16np)
+// Suitable for Residual[1]x[9-16 bit],PQ[2]x[3] (such as Residual2x9,PQ8)
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS = 8,
+ intptr_t FINE_BITS = 8>
+struct Index2LevelDecoder {
+ static_assert(
+ COARSE_BITS == 8 || COARSE_BITS == 10 || COARSE_BITS == 12 ||
+ COARSE_BITS == 16,
+ "Only 8, 10, 12 or 16 bits are currently supported for COARSE_BITS");
+ static_assert(
+ FINE_BITS == 8 || FINE_BITS == 10 || FINE_BITS == 12 ||
+ FINE_BITS == 16,
+ "Only 8, 10, 12 or 16 bits are currently supported for FINE_BITS");
+
+ static constexpr intptr_t dim = DIM;
+ static constexpr intptr_t coarseSize = COARSE_SIZE;
+ static constexpr intptr_t fineSize = FINE_SIZE;
+ static constexpr intptr_t coarseBits = COARSE_BITS;
+ static constexpr intptr_t fineBits = FINE_BITS;
+
+ // Process 1 sample.
+ static void store(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ store(pqCoarseCentroids, pqFineCentroids, code, outputStore);
+ }
+
+ // Process 1 sample.
+ // Performs outputAccum += weight * decoded(code)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code,
+ weight,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1).
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
+#endif // LEVEL2_AVX2_INL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-inl.h
new file mode 100644
index 0000000..1d03e81
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-inl.h
@@ -0,0 +1,467 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef LEVEL2_INL_H
+#define LEVEL2_INL_H
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/cppcontrib/detail/CoarseBitType.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+namespace cppcontrib {
+
+bool isBigEndian() {
+#ifdef FAISS_BIG_ENDIAN
+ return true;
+#else
+ return false;
+#endif
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+/// Index2LevelDecoder
+////////////////////////////////////////////////////////////////////////////////////
+
+// Suitable for IVF256,PQ[1]x8
+// Suitable for Residual[1]x8,PQ[2]x8
+// Suitable for IVF[9-16 bit],PQ[1]x8 (such as IVF1024,PQ16np)
+// Suitable for Residual1x[9-16 bit],PQ[1]x8 (such as Residual1x9,PQ8)
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS = 8,
+ intptr_t FINE_BITS = 8>
+struct Index2LevelDecoder {
+ static_assert(
+ COARSE_BITS == 8 || COARSE_BITS == 16,
+ "Only 8 or 16 bits are currently supported for COARSE_BITS");
+ static_assert(
+ FINE_BITS == 8,
+ "Only 8 bits is currently supported for FINE_BITS");
+
+ static constexpr intptr_t dim = DIM;
+ static constexpr intptr_t coarseSize = COARSE_SIZE;
+ static constexpr intptr_t fineSize = FINE_SIZE;
+ static constexpr intptr_t coarseBits = COARSE_BITS;
+ static constexpr intptr_t fineBits = FINE_BITS;
+
+ // coarse quantizer storage
+ using coarse_storage_type =
+ typename detail::CoarseBitType<COARSE_BITS>::bit_type;
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // Process 1 sample.
+ // Performs outputStore = decoded(code)
+ static void store(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const coarse_storage_type* const __restrict coarse =
+ reinterpret_cast<const coarse_storage_type*>(code);
+
+ // fine quantizer
+ const uint8_t* const __restrict fine =
+ code + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t coarseCentroidIdx = i / COARSE_SIZE;
+ const intptr_t coarseCentroidOffset = i % COARSE_SIZE;
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+ intptr_t coarseCode, fineCode;
+ if (isBigEndian() && sizeof(coarse_storage_type) == 2) {
+ coarseCode = Swap2Bytes(coarse[coarseCentroidIdx]);
+ fineCode = Swap2Bytes(fine[fineCentroidIdx]);
+ } else {
+ coarseCode = coarse[coarseCentroidIdx];
+ fineCode = fine[fineCentroidIdx];
+ }
+
+ const float* const __restrict coarsePtr = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputStore[i] = *coarsePtr + *finePtr;
+ }
+ }
+
+ // Process 1 sample.
+ // Performs outputAccum += weight * decoded(code)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const coarse_storage_type* const __restrict coarse =
+ reinterpret_cast<const coarse_storage_type*>(code);
+
+ // fine quantizer
+ const uint8_t* const __restrict fine =
+ code + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t coarseCentroidIdx = i / COARSE_SIZE;
+ const intptr_t coarseCentroidOffset = i % COARSE_SIZE;
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ intptr_t coarseCode, fineCode;
+ if (isBigEndian() && sizeof(coarse_storage_type) == 2) {
+ coarseCode = Swap2Bytes(coarse[coarseCentroidIdx]);
+ fineCode = Swap2Bytes(fine[fineCentroidIdx]);
+ } else {
+ coarseCode = coarse[coarseCentroidIdx];
+ fineCode = fine[fineCentroidIdx];
+ }
+ const float* const __restrict coarsePtr = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight * (*coarsePtr + *finePtr);
+ }
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1).
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const coarse_storage_type* const __restrict coarse0 =
+ reinterpret_cast<const coarse_storage_type*>(code0);
+ const coarse_storage_type* const __restrict coarse1 =
+ reinterpret_cast<const coarse_storage_type*>(code1);
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 =
+ code0 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+ const uint8_t* const __restrict fine1 =
+ code1 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t coarseCentroidIdx = i / COARSE_SIZE;
+ const intptr_t coarseCentroidOffset = i % COARSE_SIZE;
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+ intptr_t coarseCode0, coarseCode1, fineCode0, fineCode1;
+ if (isBigEndian() && sizeof(coarse_storage_type) == 2) {
+ coarseCode0 = Swap2Bytes(coarse0[coarseCentroidIdx]);
+ fineCode0 = Swap2Bytes(fine0[fineCentroidIdx]);
+ coarseCode1 = Swap2Bytes(coarse1[coarseCentroidIdx]);
+ fineCode1 = Swap2Bytes(fine1[fineCentroidIdx]);
+ } else {
+ coarseCode0 = coarse0[coarseCentroidIdx];
+ fineCode0 = fine0[fineCentroidIdx];
+ coarseCode1 = coarse1[coarseCentroidIdx];
+ fineCode1 = fine1[fineCentroidIdx];
+ }
+
+ const float* const __restrict coarsePtr0 = pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr0 = pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict coarsePtr1 = pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*coarsePtr0 + *finePtr0) +
+ weight1 * (*coarsePtr1 + *finePtr1);
+ }
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const coarse_storage_type* const __restrict coarse0 =
+ reinterpret_cast<const coarse_storage_type*>(code0);
+ const coarse_storage_type* const __restrict coarse1 =
+ reinterpret_cast<const coarse_storage_type*>(code1);
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 =
+ code0 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+ const uint8_t* const __restrict fine1 =
+ code1 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t coarseCentroidIdx = i / COARSE_SIZE;
+ const intptr_t coarseCentroidOffset = i % COARSE_SIZE;
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+ intptr_t coarseCode0, coarseCode1, fineCode0, fineCode1;
+ if (isBigEndian() && sizeof(coarse_storage_type) == 2) {
+ coarseCode0 = Swap2Bytes(coarse0[coarseCentroidIdx]);
+ fineCode0 = Swap2Bytes(fine0[fineCentroidIdx]);
+ coarseCode1 = Swap2Bytes(coarse1[coarseCentroidIdx]);
+ fineCode1 = Swap2Bytes(fine1[fineCentroidIdx]);
+ } else {
+ coarseCode0 = coarse0[coarseCentroidIdx];
+ fineCode0 = fine0[fineCentroidIdx];
+ coarseCode1 = coarse1[coarseCentroidIdx];
+ fineCode1 = fine1[fineCentroidIdx];
+ }
+
+ const float* const __restrict coarsePtr0 = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr0 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict coarsePtr1 = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*coarsePtr0 + *finePtr0) +
+ weight1 * (*coarsePtr1 + *finePtr1);
+ }
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const coarse_storage_type* const __restrict coarse0 =
+ reinterpret_cast<const coarse_storage_type*>(code0);
+ const coarse_storage_type* const __restrict coarse1 =
+ reinterpret_cast<const coarse_storage_type*>(code1);
+ const coarse_storage_type* const __restrict coarse2 =
+ reinterpret_cast<const coarse_storage_type*>(code2);
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 =
+ code0 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+ const uint8_t* const __restrict fine1 =
+ code1 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+ const uint8_t* const __restrict fine2 =
+ code2 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t coarseCentroidIdx = i / COARSE_SIZE;
+ const intptr_t coarseCentroidOffset = i % COARSE_SIZE;
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+ intptr_t coarseCode0, coarseCode1, fineCode0, fineCode1;
+ intptr_t coarseCode2, fineCode2;
+ if (isBigEndian() && sizeof(coarse_storage_type) == 2) {
+ coarseCode0 = Swap2Bytes(coarse0[coarseCentroidIdx]);
+ fineCode0 = Swap2Bytes(fine0[fineCentroidIdx]);
+ coarseCode1 = Swap2Bytes(coarse1[coarseCentroidIdx]);
+ fineCode1 = Swap2Bytes(fine1[fineCentroidIdx]);
+ coarseCode2 = Swap2Bytes(coarse2[coarseCentroidIdx]);
+ fineCode2 = Swap2Bytes(fine2[fineCentroidIdx]);
+ } else {
+ coarseCode0 = coarse0[coarseCentroidIdx];
+ fineCode0 = fine0[fineCentroidIdx];
+ coarseCode1 = coarse1[coarseCentroidIdx];
+ fineCode1 = fine1[fineCentroidIdx];
+ coarseCode2 = coarse2[coarseCentroidIdx];
+ fineCode2 = fine2[fineCentroidIdx];
+ }
+
+ const float* const __restrict coarsePtr0 = pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr0 = pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict coarsePtr1 = pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict coarsePtr2 = pqCoarseCentroids2 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr2 = pqFineCentroids2 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*coarsePtr0 + *finePtr0) +
+ weight1 * (*coarsePtr1 + *finePtr1) +
+ weight2 * (*coarsePtr2 + *finePtr2);
+ }
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const coarse_storage_type* const __restrict coarse0 =
+ reinterpret_cast<const coarse_storage_type*>(code0);
+ const coarse_storage_type* const __restrict coarse1 =
+ reinterpret_cast<const coarse_storage_type*>(code1);
+ const coarse_storage_type* const __restrict coarse2 =
+ reinterpret_cast<const coarse_storage_type*>(code2);
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 =
+ code0 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+ const uint8_t* const __restrict fine1 =
+ code1 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+ const uint8_t* const __restrict fine2 =
+ code2 + (DIM / COARSE_SIZE) * sizeof(coarse_storage_type);
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t coarseCentroidIdx = i / COARSE_SIZE;
+ const intptr_t coarseCentroidOffset = i % COARSE_SIZE;
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+ intptr_t coarseCode0, fineCode0, coarseCode1, fineCode1;
+ intptr_t coarseCode2, fineCode2;
+ if (isBigEndian() && sizeof(coarse_storage_type) == 2) {
+ coarseCode0 = Swap2Bytes(coarse0[coarseCentroidIdx]);
+ fineCode0 = Swap2Bytes(fine0[fineCentroidIdx]);
+ coarseCode1 = Swap2Bytes(coarse1[coarseCentroidIdx]);
+ fineCode1 = Swap2Bytes(fine1[fineCentroidIdx]);
+ coarseCode2 = Swap2Bytes(coarse2[coarseCentroidIdx]);
+ fineCode2 = Swap2Bytes(fine2[fineCentroidIdx]);
+ } else {
+ coarseCode0 = coarse0[coarseCentroidIdx];
+ fineCode0 = fine0[fineCentroidIdx];
+ coarseCode1 = coarse1[coarseCentroidIdx];
+ fineCode1 = fine1[fineCentroidIdx];
+ coarseCode2 = coarse2[coarseCentroidIdx];
+ fineCode2 = fine2[fineCentroidIdx];
+ }
+
+ const float* const __restrict coarsePtr0 = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr0 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict coarsePtr1 = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict coarsePtr2 = pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset;
+ const float* const __restrict finePtr2 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*coarsePtr0 + *finePtr0) +
+ weight1 * (*coarsePtr1 + *finePtr1) +
+ weight2 * (*coarsePtr2 + *finePtr2);
+ }
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
+#endif // LEVEL2_INL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-neon-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-neon-inl.h
new file mode 100644
index 0000000..51daec4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/Level2-neon-inl.h
@@ -0,0 +1,2161 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef LEVEL2_NEON_INL_H
+#define LEVEL2_NEON_INL_H
+
+#include <arm_neon.h>
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/cppcontrib/detail/UintReader.h>
+
+namespace faiss {
+namespace cppcontrib {
+
+namespace {
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = *coarse[0..3] + *fine[0..3];
+// }
+inline float32x4_t elementaryBlock4x1b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine) {
+ // load fine
+ const auto fineValue = vld1q_f32(fine);
+ // load coarse
+ const auto coarseValue = vld1q_f32(coarse);
+
+ // add coarse and fine
+ return vaddq_f32(fineValue, coarseValue);
+}
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*coarse[0..3] + *fine[0..3]);
+// }
+inline float32x4_t elementaryBlock4x1bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine,
+ const float weight,
+ const float32x4_t existingValue) {
+ // add coarse and fine
+ const auto combinedValue = elementaryBlock4x1b(coarse, fine);
+
+ // this operation is expected to be optimized by a compiler
+ const auto weightNeon = vdupq_n_f32(weight);
+ // do fma
+ return vfmaq_f32(existingValue, weightNeon, combinedValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = *coarse[0..3] + *fine0[0..3];
+// [4..7] = *coarse[4..7] + *fine1[0..3];
+// }
+inline float32x4x2_t elementaryBlock4x2b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine0,
+ const float* const __restrict fine1) {
+ // load fine
+ const auto fineValue0 = vld1q_f32(fine0);
+ const auto fineValue1 = vld1q_f32(fine1);
+ // load coarse
+ const auto coarseValue0 = vld1q_f32(coarse);
+ const auto coarseValue1 = vld1q_f32(coarse + 4);
+
+ // add coarse and fine
+ const auto result0 = vaddq_f32(fineValue0, coarseValue0);
+ const auto result1 = vaddq_f32(fineValue1, coarseValue1);
+
+ return {result0, result1};
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*coarse[0..3] + *fine0[0..3]);
+// [4..7] = existingValue[4..7] + weight * (*coarse[4..7] + *fine1[0..3]);
+// }
+inline float32x4x2_t elementaryBlock4x2bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float weight,
+ const float32x4x2_t existingValue) {
+ // add coarse and fine
+ const auto combinedValue = elementaryBlock4x2b(coarse, fine0, fine1);
+
+ // this operation is expected to be optimized by a compiler
+ const auto weightNeon = vdupq_n_f32(weight);
+ // do fma
+ const auto result0 =
+ vfmaq_f32(existingValue.val[0], weightNeon, combinedValue.val[0]);
+ const auto result1 =
+ vfmaq_f32(existingValue.val[1], weightNeon, combinedValue.val[1]);
+ return {result0, result1};
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = *coarse[0..7] + *fine[0..7];
+// }
+inline float32x4x2_t elementaryBlock8x1b(
+ const float* const __restrict coarse,
+ const float* const __restrict fine) {
+ // load fine
+ const auto fineValue0 = vld1q_f32(fine);
+ const auto fineValue1 = vld1q_f32(fine + 4);
+ // load coarse
+ const auto coarseValue0 = vld1q_f32(coarse);
+ const auto coarseValue1 = vld1q_f32(coarse + 4);
+
+ // add coarse and fine
+ return {vaddq_f32(fineValue0, coarseValue0),
+ vaddq_f32(fineValue1, coarseValue1)};
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = existingValue[0..7] + weight * (*coarse[0..7] + *fine[0..7]);
+// }
+inline float32x4x2_t elementaryBlock8x1bAccum(
+ const float* const __restrict coarse,
+ const float* const __restrict fine,
+ const float weight,
+ const float32x4x2_t existingValue) {
+ // add coarse and fine
+ const auto combinedValue = elementaryBlock8x1b(coarse, fine);
+
+ // this operation is expected to be optimized by a compiler
+ const auto weightNeon = vdupq_n_f32(weight);
+ // do fma
+ const auto result0 =
+ vfmaq_f32(existingValue.val[0], weightNeon, combinedValue.val[0]);
+ const auto result1 =
+ vfmaq_f32(existingValue.val[1], weightNeon, combinedValue.val[1]);
+ return {result0, result1};
+}
+
+// The following code uses template-based for-loop unrolling,
+// because the compiler does not do that on its own as needed.
+// The idea is the following:
+// template<int I, int MAX>
+// struct Foo {
+// static void bar() {
+// doSomething(I);
+// Foo<I + 1, MAX>::bar();
+// }
+// };
+//
+// template<int MAX>
+// struct Foo<MAX, MAX> {
+// static void bar() {}
+// };
+//
+// Initiate the loop:
+// Foo<0, MAX>::bar();
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool FINE_SIZE_EQ_4 = FINE_SIZE == 4,
+ bool QPOS_LEFT_GE_8 = (FINE_SIZE - CPOS % FINE_SIZE >= 8),
+ bool QPOS_LEFT_GE_4 = (FINE_SIZE - CPOS % FINE_SIZE >= 4),
+ bool DIM_EQ_CPOS = DIM == CPOS>
+struct Index2LevelDecoderImpl;
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ 4,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ true,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ false> {
+ static constexpr intptr_t FINE_SIZE = 4;
+
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+
+ const auto storeValue = elementaryBlock4x2b(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset);
+
+ vst1q_f32(outputStore + CPOS, storeValue.val[0]);
+ vst1q_f32(outputStore + CPOS + 4, storeValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ store(pqCoarseCentroids0, pqFineCentroids0, code0, outputStore);
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+ const intptr_t coarseCode2 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse2);
+ const intptr_t fineCode2a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine2);
+ const intptr_t fineCode2b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine2);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids2 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids2 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode2a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids2 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode2b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+ const intptr_t coarseCode2 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse2);
+ const intptr_t fineCode2a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine2);
+ const intptr_t fineCode2b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine2);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode2a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode2b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ false,
+ true,
+ true,
+ false> {
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ const auto storeValue = elementaryBlock8x1b(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset);
+
+ vst1q_f32(outputStore + CPOS, storeValue.val[0]);
+ vst1q_f32(outputStore + CPOS + 4, storeValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ store(pqCoarseCentroids0, pqFineCentroids0, code0, outputStore);
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ const auto existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t coarseCode2 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse2);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids2 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids2 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 8 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t coarseCode2 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse2);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 8>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ intptr_t CPOS>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS,
+ false,
+ false,
+ true,
+ false> {
+ static constexpr intptr_t coarseCentroidIdx = CPOS / COARSE_SIZE;
+ static constexpr intptr_t coarseCentroidOffset = CPOS % COARSE_SIZE;
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ // coarse quantizer storage
+ static constexpr intptr_t COARSE_TABLE_BYTES = (1 << COARSE_BITS);
+
+ // coarse quantizer bytes start from 0
+ // fine quantizer bytes start from N_COARSE_ELEMENTS_BYTES
+ static constexpr intptr_t N_COARSE_ELEMENTS = DIM / COARSE_SIZE;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BITS =
+ N_COARSE_ELEMENTS * COARSE_BITS;
+ static constexpr intptr_t N_COARSE_ELEMENTS_BYTES =
+ (N_COARSE_ELEMENTS_BITS + 7) / 8;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ const auto storeValue = elementaryBlock4x1b(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset);
+
+ vst1q_f32(outputStore + CPOS, storeValue);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 4>::
+ store(pqCoarseCentroids0, pqFineCentroids0, code0, outputStore);
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 4>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 4>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 4>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t coarseCode2 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse2);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids0 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids1 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids2 +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids2 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 4>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // coarse quantizer
+ const uint8_t* const __restrict coarse0 = code0;
+ const uint8_t* const __restrict coarse1 = code1;
+ const uint8_t* const __restrict coarse2 = code2;
+
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine1 = code1 + N_COARSE_ELEMENTS_BYTES;
+ const uint8_t* const __restrict fine2 = code2 + N_COARSE_ELEMENTS_BYTES;
+
+ // process chunks, 4 float
+
+ const intptr_t coarseCode0 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse0);
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t coarseCode1 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse1);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t coarseCode2 = detail::
+ UintReader<DIM, COARSE_SIZE, COARSE_BITS, coarseCentroidIdx>::
+ get(coarse2);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode0) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode1) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqCoarseCentroids +
+ (coarseCentroidIdx * COARSE_TABLE_BYTES + coarseCode2) *
+ COARSE_SIZE +
+ coarseCentroidOffset,
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ CPOS + 4>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+// This partial specialization is expected to do nothing.
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS,
+ intptr_t FINE_BITS,
+ bool FINE_SIZE_EQ_4,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ DIM,
+ FINE_SIZE_EQ_4,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ true> {
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {}
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+};
+} // namespace
+
+// Suitable for IVF256,PQ[1]x8
+// Subtable for IVF256,PQ[1]x10 (such as IVF256,PQ16x10np)
+// Subtable for IVF256,PQ[1]x12 (such as IVF256,PQ16x12np)
+// Suitable for IVF256,PQ[1]x16 (such as IVF256,PQ16x16np)
+// Suitable for Residual[1]x8,PQ[2]x8
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x8 (such as IVF1024,PQ16np)
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x10 (such as IVF1024,PQ16x10np)
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x12 (such as IVF1024,PQ16x12np)
+// Suitable for IVF[2^9-2^16 bit],PQ[1]x16 (such as IVF1024,PQ16x16np)
+// Suitable for Residual[1]x[9-16 bit],PQ[2]x[3] (such as Residual2x9,PQ8)
+template <
+ intptr_t DIM,
+ intptr_t COARSE_SIZE,
+ intptr_t FINE_SIZE,
+ intptr_t COARSE_BITS = 8,
+ intptr_t FINE_BITS = 8>
+struct Index2LevelDecoder {
+ static_assert(
+ COARSE_BITS == 8 || COARSE_BITS == 10 || COARSE_BITS == 12 ||
+ COARSE_BITS == 16,
+ "Only 8, 10, 12 or 16 bits are currently supported for COARSE_BITS");
+ static_assert(
+ FINE_BITS == 8 || FINE_BITS == 10 || FINE_BITS == 12 ||
+ FINE_BITS == 16,
+ "Only 8, 10, 12 or 16 bits are currently supported for FINE_BITS");
+
+ static constexpr intptr_t dim = DIM;
+ static constexpr intptr_t coarseSize = COARSE_SIZE;
+ static constexpr intptr_t fineSize = FINE_SIZE;
+ static constexpr intptr_t coarseBits = COARSE_BITS;
+ static constexpr intptr_t fineBits = FINE_BITS;
+
+ // Process 1 sample.
+ static void store(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ store(pqCoarseCentroids, pqFineCentroids, code, outputStore);
+ }
+
+ // Process 1 sample.
+ // Performs outputAccum += weight * decoded(code)
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code,
+ weight,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1).
+ //
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ //
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ //
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ //
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ Index2LevelDecoderImpl<
+ DIM,
+ COARSE_SIZE,
+ FINE_SIZE,
+ COARSE_BITS,
+ FINE_BITS,
+ 0>::
+ accum(pqCoarseCentroids,
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
+#endif // LEVEL2_NEON_INL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/MinMax-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/MinMax-inl.h
new file mode 100644
index 0000000..90a5bf3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/MinMax-inl.h
@@ -0,0 +1,467 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace faiss {
+namespace cppcontrib {
+
+template <typename SubIndexT>
+struct IndexMinMaxDecoder {
+ static constexpr intptr_t dim = SubIndexT::dim;
+
+ // Process 1 sample.
+ // Performs outputStore = scaler * decoded(code) + minv
+ static void store(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ const float* const __restrict codeFloat =
+ reinterpret_cast<const float*>(code);
+ const float scaler = codeFloat[0];
+ const float minv = codeFloat[1];
+
+ SubIndexT::store(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code + 2 * sizeof(float),
+ outputStore);
+ for (intptr_t i = 0; i < SubIndexT::dim; i++) {
+ outputStore[i] = outputStore[i] * scaler + minv;
+ }
+ }
+
+ // Process 1 sample.
+ // Performs outputStore = scaler * decoded(code) + minv
+ static void store(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ const float* const __restrict codeFloat =
+ reinterpret_cast<const float*>(code);
+ const float scaler = codeFloat[0];
+ const float minv = codeFloat[1];
+
+ SubIndexT::store(
+ pqFineCentroids, code + 2 * sizeof(float), outputStore);
+ for (intptr_t i = 0; i < SubIndexT::dim; i++) {
+ outputStore[i] = outputStore[i] * scaler + minv;
+ }
+ }
+
+ // Process 1 sample.
+ // Performs
+ // * outputAccum += weight * scaler * decoded(code)
+ // * minvAccum += weight * minv
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict codeFloat =
+ reinterpret_cast<const float*>(code);
+ const float scaler = codeFloat[0] * weight;
+ const float minv = codeFloat[1] * weight;
+
+ SubIndexT::accum(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code + 2 * sizeof(float),
+ scaler,
+ outputAccum);
+
+ minvAccum += minv;
+ }
+
+ // Process 1 sample.
+ // Performs
+ // * outputAccum += weight * scaler * decoded(code)
+ // * minvAccum += weight * minv
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict codeFloat =
+ reinterpret_cast<const float*>(code);
+ const float scaler = codeFloat[0] * weight;
+ const float minv = codeFloat[1] * weight;
+
+ SubIndexT::accum(
+ pqFineCentroids, code + 2 * sizeof(float), scaler, outputAccum);
+
+ minvAccum += minv;
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ SubIndexT::accum(
+ pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ SubIndexT::accum(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ SubIndexT::accum(
+ pqFineCentroids0,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ SubIndexT::accum(
+ pqFineCentroids,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ const float* const __restrict code2Float =
+ reinterpret_cast<const float*>(code2);
+ const float scaler2 = code2Float[0] * weight2;
+ const float minv2 = code2Float[1] * weight2;
+
+ SubIndexT::accum(
+ pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2 + 2 * sizeof(float),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ const float* const __restrict code2Float =
+ reinterpret_cast<const float*>(code2);
+ const float scaler2 = code2Float[0] * weight2;
+ const float minv2 = code2Float[1] * weight2;
+
+ SubIndexT::accum(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ code2 + 2 * sizeof(float),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ const float* const __restrict code2Float =
+ reinterpret_cast<const float*>(code2);
+ const float scaler2 = code2Float[0] * weight2;
+ const float minv2 = code2Float[1] * weight2;
+
+ SubIndexT::accum(
+ pqFineCentroids0,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ pqFineCentroids2,
+ code2 + 2 * sizeof(float),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const float* const __restrict code0Float =
+ reinterpret_cast<const float*>(code0);
+ const float scaler0 = code0Float[0] * weight0;
+ const float minv0 = code0Float[1] * weight0;
+
+ const float* const __restrict code1Float =
+ reinterpret_cast<const float*>(code1);
+ const float scaler1 = code1Float[0] * weight1;
+ const float minv1 = code1Float[1] * weight1;
+
+ const float* const __restrict code2Float =
+ reinterpret_cast<const float*>(code2);
+ const float scaler2 = code2Float[0] * weight2;
+ const float minv2 = code2Float[1] * weight2;
+
+ SubIndexT::accum(
+ pqFineCentroids,
+ code0 + 2 * sizeof(float),
+ scaler0,
+ code1 + 2 * sizeof(float),
+ scaler1,
+ code2 + 2 * sizeof(float),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/MinMaxFP16-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/MinMaxFP16-inl.h
new file mode 100644
index 0000000..6eb542a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/MinMaxFP16-inl.h
@@ -0,0 +1,472 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/utils/fp16.h>
+
+namespace faiss {
+namespace cppcontrib {
+
+template <typename SubIndexT>
+struct IndexMinMaxFP16Decoder {
+ static constexpr intptr_t dim = SubIndexT::dim;
+
+ // Process 1 sample.
+ // Performs outputStore = scaler * decoded(code) + minv
+ static void store(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ const uint16_t* const __restrict codeFP16 =
+ reinterpret_cast<const uint16_t*>(code);
+ const float scaler = faiss::decode_fp16(codeFP16[0]);
+ const float minv = faiss::decode_fp16(codeFP16[1]);
+
+ SubIndexT::store(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code + 2 * sizeof(uint16_t),
+ outputStore);
+ for (intptr_t i = 0; i < SubIndexT::dim; i++) {
+ outputStore[i] = outputStore[i] * scaler + minv;
+ }
+ }
+
+ // Process 1 sample.
+ // Performs outputStore = scaler * decoded(code) + minv
+ static void store(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ const uint16_t* const __restrict codeFP16 =
+ reinterpret_cast<const uint16_t*>(code);
+ const float scaler = faiss::decode_fp16(codeFP16[0]);
+ const float minv = faiss::decode_fp16(codeFP16[1]);
+
+ SubIndexT::store(
+ pqFineCentroids, code + 2 * sizeof(uint16_t), outputStore);
+ for (intptr_t i = 0; i < SubIndexT::dim; i++) {
+ outputStore[i] = outputStore[i] * scaler + minv;
+ }
+ }
+
+ // Process 1 sample.
+ // Performs
+ // * outputAccum += weight * scaler * decoded(code)
+ // * minvAccum += weight * minv
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict codeFP16 =
+ reinterpret_cast<const uint16_t*>(code);
+ const float scaler = faiss::decode_fp16(codeFP16[0]) * weight;
+ const float minv = faiss::decode_fp16(codeFP16[1]) * weight;
+
+ SubIndexT::accum(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code + 2 * sizeof(uint16_t),
+ scaler,
+ outputAccum);
+
+ minvAccum += minv;
+ }
+
+ // Process 1 sample.
+ // Performs
+ // * outputAccum += weight * scaler * decoded(code)
+ // * minvAccum += weight * minv
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict codeFP16 =
+ reinterpret_cast<const uint16_t*>(code);
+ const float scaler = faiss::decode_fp16(codeFP16[0]) * weight;
+ const float minv = faiss::decode_fp16(codeFP16[1]) * weight;
+
+ SubIndexT::accum(
+ pqFineCentroids,
+ code + 2 * sizeof(uint16_t),
+ scaler,
+ outputAccum);
+
+ minvAccum += minv;
+ }
+
+ // Process 2 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ SubIndexT::accum(
+ pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 2 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ SubIndexT::accum(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ SubIndexT::accum(
+ pqFineCentroids0,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ SubIndexT::accum(
+ pqFineCentroids,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ outputAccum);
+
+ minvAccum += minv0 + minv1;
+ }
+
+ // Process 3 samples.
+ // Each code uses its own coarse pq centroids table and fine pq centroids
+ // table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqCoarseCentroids0,
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqCoarseCentroids1,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqCoarseCentroids2,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ const uint16_t* const __restrict code2FP16 =
+ reinterpret_cast<const uint16_t*>(code2);
+ const float scaler2 = faiss::decode_fp16(code2FP16[0]) * weight2;
+ const float minv2 = faiss::decode_fp16(code2FP16[1]) * weight2;
+
+ SubIndexT::accum(
+ pqCoarseCentroids0,
+ pqFineCentroids0,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ pqCoarseCentroids1,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ pqCoarseCentroids2,
+ pqFineCentroids2,
+ code2 + 2 * sizeof(uint16_t),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+
+ // Process 3 samples.
+ // Coarse pq centroids table and fine pq centroids table are shared among
+ // codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqCoarseCentroids,
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ const uint16_t* const __restrict code2FP16 =
+ reinterpret_cast<const uint16_t*>(code2);
+ const float scaler2 = faiss::decode_fp16(code2FP16[0]) * weight2;
+ const float minv2 = faiss::decode_fp16(code2FP16[1]) * weight2;
+
+ SubIndexT::accum(
+ pqCoarseCentroids,
+ pqFineCentroids,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ code2 + 2 * sizeof(uint16_t),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ const uint16_t* const __restrict code2FP16 =
+ reinterpret_cast<const uint16_t*>(code2);
+ const float scaler2 = faiss::decode_fp16(code2FP16[0]) * weight2;
+ const float minv2 = faiss::decode_fp16(code2FP16[1]) * weight2;
+
+ SubIndexT::accum(
+ pqFineCentroids0,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ pqFineCentroids1,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ pqFineCentroids2,
+ code2 + 2 * sizeof(uint16_t),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs
+ // * outputAccum += weight0 * scaler0 * decoded(code0)
+ // + weight1 * scaler1 * decoded(code1)
+ // + weight2 * scaler2 * decoded(code2)
+ // * minvAccum += weight0 * minv0 + weight1 * minv1 + weight2 * minv2
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum,
+ float& minvAccum) {
+ const uint16_t* const __restrict code0FP16 =
+ reinterpret_cast<const uint16_t*>(code0);
+ const float scaler0 = faiss::decode_fp16(code0FP16[0]) * weight0;
+ const float minv0 = faiss::decode_fp16(code0FP16[1]) * weight0;
+
+ const uint16_t* const __restrict code1FP16 =
+ reinterpret_cast<const uint16_t*>(code1);
+ const float scaler1 = faiss::decode_fp16(code1FP16[0]) * weight1;
+ const float minv1 = faiss::decode_fp16(code1FP16[1]) * weight1;
+
+ const uint16_t* const __restrict code2FP16 =
+ reinterpret_cast<const uint16_t*>(code2);
+ const float scaler2 = faiss::decode_fp16(code2FP16[0]) * weight2;
+ const float minv2 = faiss::decode_fp16(code2FP16[1]) * weight2;
+
+ SubIndexT::accum(
+ pqFineCentroids,
+ code0 + 2 * sizeof(uint16_t),
+ scaler0,
+ code1 + 2 * sizeof(uint16_t),
+ scaler1,
+ code2 + 2 * sizeof(uint16_t),
+ scaler2,
+ outputAccum);
+
+ minvAccum += minv0 + minv1 + minv2;
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-avx2-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-avx2-inl.h
new file mode 100644
index 0000000..147ef4f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-avx2-inl.h
@@ -0,0 +1,1625 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PQ_AVX2_INL_H
+#define PQ_AVX2_INL_H
+
+#include <immintrin.h>
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/cppcontrib/detail/UintReader.h>
+
+namespace faiss {
+namespace cppcontrib {
+
+////////////////////////////////////////////////////////////////////////////////////
+/// IndexPQDecoder
+////////////////////////////////////////////////////////////////////////////////////
+
+namespace {
+
+// Despite the following functions are somewhat redundant, I'd like to keep the
+// overall basic blocks similar to ones from Index2LevelDecoder.
+// A compiler will optimize away the redundant code.
+
+// Processes 8 float values.
+// Returns {
+// [0..1] = *fine0[0..1];
+// [2..3] = *fine1[0..1];
+// [4..5] = *fine2[0..1];
+// [6..7] = *fine3[0..1];
+// }
+inline __m256 elementaryBlock2x4b(
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float* const __restrict fine2,
+ const float* const __restrict fine3) {
+ // load fine
+ const __m256 fineValue = _mm256_castpd_ps(_mm256_setr_pd(
+ *reinterpret_cast<const double*>(fine0),
+ *reinterpret_cast<const double*>(fine1),
+ *reinterpret_cast<const double*>(fine2),
+ *reinterpret_cast<const double*>(fine3)));
+
+ // add coarse and fine
+ return fineValue;
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..1] = existingValue[0..1] + weight * (*fine0[0..1]);
+// [2..3] = existingValue[0..1] + weight * (*fine1[0..1]);
+// [4..5] = existingValue[0..1] + weight * (*fine2[0..1]);
+// [6..7] = existingValue[0..1] + weight * (*fine3[0..1]);
+// }
+inline __m256 elementaryBlock2x4bAccum(
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float* const __restrict fine2,
+ const float* const __restrict fine3,
+ const float weight,
+ const __m256 existingValue) {
+ // add coarse and fine
+ const __m256 fineValue = elementaryBlock2x4b(fine0, fine1, fine2, fine3);
+
+ // this operation is expected to be optimized by a compiler
+ const __m256 weightAvx2 = _mm256_set1_ps(weight);
+ // do fma
+ return _mm256_fmadd_ps(fineValue, weightAvx2, existingValue);
+}
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = *fine[0..3];
+// }
+inline __m128 elementaryBlock4x1b(const float* const __restrict fine) {
+ // load fine
+ const __m128 fineValue = _mm_loadu_ps(fine);
+ return fineValue;
+}
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*fine[0..3]);
+// }
+inline __m128 elementaryBlock4x1bAccum(
+ const float* const __restrict fine,
+ const float weight,
+ const __m128 existingValue) {
+ const __m128 fineValue = elementaryBlock4x1b(fine);
+
+ // this operation is expected to be optimized by a compiler
+ const __m128 weightAvx = _mm_set1_ps(weight);
+ // do fma
+ return _mm_fmadd_ps(fineValue, weightAvx, existingValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = *fine0[0..3];
+// [4..7] = *fine1[0..3];
+// }
+inline __m256 elementaryBlock4x2b(
+ const float* const __restrict fine0,
+ const float* const __restrict fine1) {
+ // load fine
+ const __m128 fineValue0 = _mm_loadu_ps(fine0);
+ const __m128 fineValue1 = _mm_loadu_ps(fine1);
+
+ // combine two 4b into a single 8b
+ const __m256 combinedFineValue = _mm256_set_m128(fineValue1, fineValue0);
+ return combinedFineValue;
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*fine0[0..3]);
+// [4..7] = existingValue[4..7] + weight * (*fine1[0..3]);
+// }
+inline __m256 elementaryBlock4x2bAccum(
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float weight,
+ const __m256 existingValue) {
+ const __m256 fineValue = elementaryBlock4x2b(fine0, fine1);
+
+ // this operation is expected to be optimized by a compiler
+ const __m256 weightAvx2 = _mm256_set1_ps(weight);
+ // do fma
+ return _mm256_fmadd_ps(fineValue, weightAvx2, existingValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = *fine[0..7];
+// }
+inline __m256 elementaryBlock8x1b(const float* const __restrict fine) {
+ // load fine
+ const __m256 fineValue = _mm256_loadu_ps(fine);
+ return fineValue;
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = existingValue[0..7] + weight * (*fine[0..7]);
+// }
+inline __m256 elementaryBlock8x1bAccum(
+ const float* const __restrict fine,
+ const float weight,
+ const __m256 existingValue) {
+ const __m256 fineValue = elementaryBlock8x1b(fine);
+
+ // this operation is expected to be optimized by a compiler
+ const __m256 weightAvx2 = _mm256_set1_ps(weight);
+ // do fma
+ return _mm256_fmadd_ps(fineValue, weightAvx2, existingValue);
+}
+
+// The following code uses template-based for-loop unrolling,
+// because the compiler does not do that on its own as needed.
+// The idea is the following:
+// template<int I, int MAX>
+// struct Foo {
+// static void bar() {
+// doSomething(I);
+// Foo<I + 1, MAX>::bar();
+// }
+// };
+//
+// template<int MAX>
+// struct Foo<MAX, MAX> {
+// static void bar() {}
+// };
+//
+// Initiate the loop:
+// Foo<0, MAX>::bar();
+
+template <
+ intptr_t DIM,
+ intptr_t FINE_SIZE,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool FINE_SIZE_EQ_2 = FINE_SIZE == 2,
+ bool FINE_SIZE_EQ_4 = FINE_SIZE == 4,
+ bool QPOS_LEFT_GE_8 = (FINE_SIZE - CPOS % FINE_SIZE >= 8),
+ bool QPOS_LEFT_GE_4 = (FINE_SIZE - CPOS % FINE_SIZE >= 4),
+ bool DIM_EQ_CPOS = DIM == CPOS>
+struct IndexPQDecoderImpl;
+
+template <
+ intptr_t DIM,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct IndexPQDecoderImpl<
+ DIM,
+ 2,
+ FINE_BITS,
+ CPOS,
+ true,
+ false,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ false> {
+ static constexpr intptr_t FINE_SIZE = 2;
+
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+
+ const __m256 storeValue = elementaryBlock2x4b(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset);
+
+ _mm256_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::store(
+ pqFineCentroids0, code0, outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+ const intptr_t fineCode2c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine2);
+ const intptr_t fineCode2d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids2 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode2c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode2d) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode0c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine0);
+ const intptr_t fineCode0d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode1c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine1);
+ const intptr_t fineCode1d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine1);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+ const intptr_t fineCode2c = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 2>::get(fine2);
+ const intptr_t fineCode2d = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 3>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode0c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode0d) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode1c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode1d) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock2x4bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 2) * FINE_TABLE_BYTES + fineCode2c) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 3) * FINE_TABLE_BYTES + fineCode2d) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+template <
+ intptr_t DIM,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct IndexPQDecoderImpl<
+ DIM,
+ 4,
+ FINE_BITS,
+ CPOS,
+ false,
+ true,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ false> {
+ static constexpr intptr_t FINE_SIZE = 4;
+
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+
+ const __m256 storeValue = elementaryBlock4x2b(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset);
+
+ _mm256_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::store(
+ pqFineCentroids0, code0, outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids0 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids0 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids1 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids1 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids2 + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids2 + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine0);
+ const intptr_t fineCode0b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine0);
+ const intptr_t fineCode1a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine1);
+ const intptr_t fineCode1b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine1);
+ const intptr_t fineCode2a = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(fine2);
+ const intptr_t fineCode2b = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode0a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode0b) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode1a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode1b) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids + ((fineCentroidIdx + 0) * FINE_TABLE_BYTES + fineCode2a) * FINE_SIZE + fineCentroidOffset,
+ pqFineCentroids + ((fineCentroidIdx + 1) * FINE_TABLE_BYTES + fineCode2b) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS, intptr_t CPOS>
+struct IndexPQDecoderImpl<
+ DIM,
+ FINE_SIZE,
+ FINE_BITS,
+ CPOS,
+ false,
+ false,
+ true,
+ true,
+ false> {
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ const __m256 storeValue = elementaryBlock8x1b(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset);
+
+ _mm256_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::store(
+ pqFineCentroids0, code0, outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids2 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m256 existingValue = _mm256_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm256_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS, intptr_t CPOS>
+struct IndexPQDecoderImpl<
+ DIM,
+ FINE_SIZE,
+ FINE_BITS,
+ CPOS,
+ false,
+ false,
+ false,
+ true,
+ false> {
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ const __m128 storeValue = elementaryBlock4x1b(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset);
+
+ _mm_storeu_ps(outputStore + CPOS, storeValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::store(
+ pqFineCentroids0, code0, outputStore);
+
+ // clang-format on
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids,
+ code0, weight0,
+ code1, weight1,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids0 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids1 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids2 + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids0, code0, weight0,
+ pqFineCentroids1, code1, weight1,
+ pqFineCentroids2, code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // clang-format off
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine0);
+ const intptr_t fineCode1 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine1);
+ const intptr_t fineCode2 = detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::get(fine2);
+
+ __m128 existingValue = _mm_loadu_ps(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE + fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) * FINE_SIZE + fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids + (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) * FINE_SIZE + fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ _mm_storeu_ps(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids, code0, weight0,
+ code1, weight1,
+ code2, weight2,
+ outputAccum);
+
+ // clang-format on
+ }
+};
+
+// This partial specialization is expected to do nothing.
+template <
+ intptr_t DIM,
+ intptr_t FINE_SIZE,
+ intptr_t FINE_BITS,
+ bool FINE_SIZE_EQ_2,
+ bool FINE_SIZE_EQ_4,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct IndexPQDecoderImpl<
+ DIM,
+ FINE_SIZE,
+ FINE_BITS,
+ DIM,
+ FINE_SIZE_EQ_2,
+ FINE_SIZE_EQ_4,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ true> {
+ // clang-format off
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {}
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+
+ // clang-format on
+};
+
+} // namespace
+
+// Suitable for PQ[1]x8
+// Suitable for PQ[1]x10
+// Suitable for PQ[1]x12
+// Suitable for PQ[1]x16
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS = 8>
+struct IndexPQDecoder {
+ static_assert(
+ FINE_BITS == 8 || FINE_BITS == 10 || FINE_BITS == 12 ||
+ FINE_BITS == 16,
+ "Only 8, 10, 12 or 16 bits are currently supported for FINE_BITS");
+
+ static constexpr intptr_t dim = DIM;
+ static constexpr intptr_t fineSize = FINE_SIZE;
+ static constexpr intptr_t fineBits = FINE_BITS;
+
+ // Process 1 sample.
+ static void store(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::store(
+ pqFineCentroids, code, outputStore);
+ }
+
+ // Process 1 sample.
+ // Performs outputAccum += weight * decoded(code)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids, code, weight, outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids, code0, weight0, code1, weight1, outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
+#endif // PQ_AVX2_INL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-inl.h
new file mode 100644
index 0000000..1ef0df8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-inl.h
@@ -0,0 +1,257 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PQ_INL_H
+#define PQ_INL_H
+
+#include <cstddef>
+#include <cstdint>
+
+namespace faiss {
+namespace cppcontrib {
+
+////////////////////////////////////////////////////////////////////////////////////
+/// IndexPQDecoder
+////////////////////////////////////////////////////////////////////////////////////
+
+// Suitable for PQ[1]x8
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS = 8>
+struct IndexPQDecoder {
+ static_assert(
+ FINE_BITS == 8,
+ "Only 8 bits is currently supported for FINE_BITS");
+
+ static constexpr intptr_t dim = DIM;
+ static constexpr intptr_t fineSize = FINE_SIZE;
+ static constexpr intptr_t fineBits = FINE_BITS;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // Process 1 sample.
+ // Performs outputStore = decoded(code)
+ static void store(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine = code;
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ const intptr_t fineCode = fine[fineCentroidIdx];
+
+ const float* const __restrict finePtr = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputStore[i] = *finePtr;
+ }
+ }
+
+ // Process 1 sample.
+ // Performs outputAccum += weight * decoded(code)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine = code;
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ const intptr_t fineCode = fine[fineCentroidIdx];
+
+ const float* const __restrict finePtr = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight * (*finePtr);
+ }
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs
+ // outputAccum += weight0 * decoded(code0) + weight1 * decoded(code1)
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ const intptr_t fineCode0 = fine0[fineCentroidIdx];
+ const intptr_t fineCode1 = fine1[fineCentroidIdx];
+
+ const float* const __restrict finePtr0 = pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*finePtr0) + weight1 * (*finePtr1);
+ }
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs
+ // outputAccum += weight0 * decoded(code0) + weight1 * decoded(code1)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ const intptr_t fineCode0 = fine0[fineCentroidIdx];
+ const intptr_t fineCode1 = fine1[fineCentroidIdx];
+
+ const float* const __restrict finePtr0 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*finePtr0) + weight1 * (*finePtr1);
+ }
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ const intptr_t fineCode0 = fine0[fineCentroidIdx];
+ const intptr_t fineCode1 = fine1[fineCentroidIdx];
+ const intptr_t fineCode2 = fine2[fineCentroidIdx];
+
+ const float* const __restrict finePtr0 = pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict finePtr2 = pqFineCentroids2 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*finePtr0) + weight1 * (*finePtr1) +
+ weight2 * (*finePtr2);
+ }
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+#pragma unroll
+ for (intptr_t i = 0; i < DIM; i++) {
+ const intptr_t fineCentroidIdx = i / FINE_SIZE;
+ const intptr_t fineCentroidOffset = i % FINE_SIZE;
+
+ const intptr_t fineCode0 = fine0[fineCentroidIdx];
+ const intptr_t fineCode1 = fine1[fineCentroidIdx];
+ const intptr_t fineCode2 = fine2[fineCentroidIdx];
+
+ const float* const __restrict finePtr0 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict finePtr1 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset;
+ const float* const __restrict finePtr2 = pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset;
+
+ outputAccum[i] += weight0 * (*finePtr0) + weight1 * (*finePtr1) +
+ weight2 * (*finePtr2);
+ }
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
+#endif // PQ_INL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-neon-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-neon-inl.h
new file mode 100644
index 0000000..1ee278e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/cppcontrib/sa_decode/PQ-neon-inl.h
@@ -0,0 +1,1460 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef PQ_NEON_INL_H
+#define PQ_NEON_INL_H
+
+#include <arm_neon.h>
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/cppcontrib/detail/UintReader.h>
+
+namespace faiss {
+namespace cppcontrib {
+
+////////////////////////////////////////////////////////////////////////////////////
+/// IndexPQDecoder
+////////////////////////////////////////////////////////////////////////////////////
+
+namespace {
+
+// Despite the following functions are somewhat redundant, I'd like to keep the
+// overall basic blocks similar to ones from Index2LevelDecoder.
+// A compiler will optimize away the redundant code.
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = *fine[0..3];
+// }
+inline float32x4_t elementaryBlock4x1b(const float* const __restrict fine) {
+ // load fine
+ const auto fineValue = vld1q_f32(fine);
+ return fineValue;
+}
+
+// Processes 4 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*fine[0..3]);
+// }
+inline float32x4_t elementaryBlock4x1bAccum(
+ const float* const __restrict fine,
+ const float weight,
+ const float32x4_t existingValue) {
+ const auto fineValue = elementaryBlock4x1b(fine);
+
+ // this operation is expected to be optimized by a compiler
+ const auto weightNeon = vdupq_n_f32(weight);
+ // do fma
+ return vfmaq_f32(existingValue, weightNeon, fineValue);
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = *fine0[0..3];
+// [4..7] = *fine1[0..3];
+// }
+inline float32x4x2_t elementaryBlock4x2b(
+ const float* const __restrict fine0,
+ const float* const __restrict fine1) {
+ // load fine
+ const auto fineValue0 = vld1q_f32(fine0);
+ const auto fineValue1 = vld1q_f32(fine1);
+
+ return {fineValue0, fineValue1};
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..3] = existingValue[0..3] + weight * (*fine0[0..3]);
+// [4..7] = existingValue[4..7] + weight * (*fine1[0..3]);
+// }
+inline float32x4x2_t elementaryBlock4x2bAccum(
+ const float* const __restrict fine0,
+ const float* const __restrict fine1,
+ const float weight,
+ const float32x4x2_t existingValue) {
+ const auto fineValue = elementaryBlock4x2b(fine0, fine1);
+
+ // this operation is expected to be optimized by a compiler
+ const auto weightNeon = vdupq_n_f32(weight);
+ // do fma
+ const auto result0 =
+ vfmaq_f32(existingValue.val[0], weightNeon, fineValue.val[0]);
+ const auto result1 =
+ vfmaq_f32(existingValue.val[1], weightNeon, fineValue.val[1]);
+ return {result0, result1};
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = *fine[0..7];
+// }
+inline float32x4x2_t elementaryBlock8x1b(const float* const __restrict fine) {
+ // load fine
+ const auto fineValue0 = vld1q_f32(fine);
+ const auto fineValue1 = vld1q_f32(fine + 4);
+ return {fineValue0, fineValue1};
+}
+
+// Processes 8 float values.
+// Returns {
+// [0..7] = existingValue[0..7] + weight * (*fine[0..7]);
+// }
+inline float32x4x2_t elementaryBlock8x1bAccum(
+ const float* const __restrict fine,
+ const float weight,
+ const float32x4x2_t existingValue) {
+ const auto fineValue = elementaryBlock8x1b(fine);
+
+ // this operation is expected to be optimized by a compiler
+ const auto weightNeon = vdupq_n_f32(weight);
+ // do fma
+ const auto result0 =
+ vfmaq_f32(existingValue.val[0], weightNeon, fineValue.val[0]);
+ const auto result1 =
+ vfmaq_f32(existingValue.val[1], weightNeon, fineValue.val[1]);
+ return {result0, result1};
+}
+
+// The following code uses template-based for-loop unrolling,
+// because the compiler does not do that on its own as needed.
+// The idea is the following:
+// template<int I, int MAX>
+// struct Foo {
+// static void bar() {
+// doSomething(I);
+// Foo<I + 1, MAX>::bar();
+// }
+// };
+//
+// template<int MAX>
+// struct Foo<MAX, MAX> {
+// static void bar() {}
+// };
+//
+// Initiate the loop:
+// Foo<0, MAX>::bar();
+
+template <
+ intptr_t DIM,
+ intptr_t FINE_SIZE,
+ intptr_t FINE_BITS,
+ intptr_t CPOS,
+ bool FINE_SIZE_EQ_4 = FINE_SIZE == 4,
+ bool QPOS_LEFT_GE_8 = (FINE_SIZE - CPOS % FINE_SIZE >= 8),
+ bool QPOS_LEFT_GE_4 = (FINE_SIZE - CPOS % FINE_SIZE >= 4),
+ bool DIM_EQ_CPOS = DIM == CPOS>
+struct IndexPQDecoderImpl;
+
+template <
+ intptr_t DIM,
+ intptr_t CPOS,
+ intptr_t FINE_BITS,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct IndexPQDecoderImpl<
+ DIM,
+ 4,
+ FINE_BITS,
+ CPOS,
+ true,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ false> {
+ static constexpr intptr_t FINE_SIZE = 4;
+
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+
+ const auto storeValue = elementaryBlock4x2b(
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset);
+
+ vst1q_f32(outputStore + CPOS, storeValue.val[0]);
+ vst1q_f32(outputStore + CPOS + 4, storeValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::store(
+ pqFineCentroids0, code0, outputStore);
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids, code0, weight0, code1, weight1, outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+ const intptr_t fineCode2a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine2);
+ const intptr_t fineCode2b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine2);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids0 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids1 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids2 +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode2a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids2 +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode2b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // process chunks, 4 float
+ // but 8 floats per loop
+
+ const intptr_t fineCode0a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine0);
+ const intptr_t fineCode0b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine0);
+ const intptr_t fineCode1a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine1);
+ const intptr_t fineCode1b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine1);
+ const intptr_t fineCode2a = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 0>::get(
+ fine2);
+ const intptr_t fineCode2b = detail::
+ UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx + 1>::get(
+ fine2);
+
+ auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode0a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode0b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode1a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode1b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x2bAccum(
+ pqFineCentroids +
+ ((fineCentroidIdx + 0) * FINE_TABLE_BYTES +
+ fineCode2a) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ pqFineCentroids +
+ ((fineCentroidIdx + 1) * FINE_TABLE_BYTES +
+ fineCode2b) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS, intptr_t CPOS>
+struct IndexPQDecoderImpl<
+ DIM,
+ FINE_SIZE,
+ FINE_BITS,
+ CPOS,
+ false,
+ true,
+ true,
+ false> {
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ const auto storeValue = elementaryBlock8x1b(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE +
+ fineCentroidOffset);
+
+ vst1q_f32(outputStore + CPOS, storeValue.val[0]);
+ vst1q_f32(outputStore + CPOS + 4, storeValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::store(
+ pqFineCentroids0, code0, outputStore);
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ const auto existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids, code0, weight0, code1, weight1, outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids2 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // process chunks, 8 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ const auto existingValue0 = vld1q_f32(outputAccum + CPOS);
+ const auto existingValue1 = vld1q_f32(outputAccum + CPOS + 4);
+
+ auto existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ {existingValue0, existingValue1});
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock8x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue.val[0]);
+ vst1q_f32(outputAccum + CPOS + 4, existingValue.val[1]);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 8>::accum(
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS, intptr_t CPOS>
+struct IndexPQDecoderImpl<
+ DIM,
+ FINE_SIZE,
+ FINE_BITS,
+ CPOS,
+ false,
+ false,
+ true,
+ false> {
+ static constexpr intptr_t fineCentroidIdx = CPOS / FINE_SIZE;
+ static constexpr intptr_t fineCentroidOffset = CPOS % FINE_SIZE;
+
+ static constexpr intptr_t QPOS_LEFT = FINE_SIZE - fineCentroidOffset;
+
+ static constexpr intptr_t FINE_TABLE_BYTES = (1 << FINE_BITS);
+
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ const auto storeValue = elementaryBlock4x1b(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) * FINE_SIZE +
+ fineCentroidOffset);
+
+ vst1q_f32(outputStore + CPOS, storeValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::store(
+ pqFineCentroids0, code0, outputStore);
+ }
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids0, code0, weight0, outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids, code0, weight0, code1, weight1, outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids0 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids1 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids2 +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ // fine quantizer
+ const uint8_t* const __restrict fine0 = code0;
+ const uint8_t* const __restrict fine1 = code1;
+ const uint8_t* const __restrict fine2 = code2;
+
+ // process chunks, 4 float
+
+ const intptr_t fineCode0 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine0);
+ const intptr_t fineCode1 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine1);
+ const intptr_t fineCode2 =
+ detail::UintReader<DIM, FINE_SIZE, FINE_BITS, fineCentroidIdx>::
+ get(fine2);
+
+ auto existingValue = vld1q_f32(outputAccum + CPOS);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode0) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight0,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode1) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight1,
+ existingValue);
+
+ existingValue = elementaryBlock4x1bAccum(
+ pqFineCentroids +
+ (fineCentroidIdx * FINE_TABLE_BYTES + fineCode2) *
+ FINE_SIZE +
+ fineCentroidOffset,
+ weight2,
+ existingValue);
+
+ vst1q_f32(outputAccum + CPOS, existingValue);
+
+ // next
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, CPOS + 4>::accum(
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+// This partial specialization is expected to do nothing.
+template <
+ intptr_t DIM,
+ intptr_t FINE_SIZE,
+ intptr_t FINE_BITS,
+ bool FINE_SIZE_EQ_4,
+ bool QPOS_LEFT_GE_8,
+ bool QPOS_LEFT_GE_4>
+struct IndexPQDecoderImpl<
+ DIM,
+ FINE_SIZE,
+ FINE_BITS,
+ DIM,
+ FINE_SIZE_EQ_4,
+ QPOS_LEFT_GE_8,
+ QPOS_LEFT_GE_4,
+ true> {
+ // process 1 sample
+ static void store(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ float* const __restrict outputStore) {}
+
+ // process 1 sample
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {}
+};
+} // namespace
+
+// Suitable for PQ[1]x8
+// Suitable for PQ[1]x10
+// Suitable for PQ[1]x12
+// Suitable for PQ[1]x16
+template <intptr_t DIM, intptr_t FINE_SIZE, intptr_t FINE_BITS = 8>
+struct IndexPQDecoder {
+ static_assert(
+ FINE_BITS == 8 || FINE_BITS == 10 || FINE_BITS == 12 ||
+ FINE_BITS == 16,
+ "Only 8, 10, 12 or 16 bits are currently supported for FINE_BITS");
+
+ static constexpr intptr_t dim = DIM;
+ static constexpr intptr_t fineSize = FINE_SIZE;
+ static constexpr intptr_t fineBits = FINE_BITS;
+
+ // Process 1 sample.
+ static void store(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ float* const __restrict outputStore) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::store(
+ pqFineCentroids, code, outputStore);
+ }
+
+ // Process 1 sample.
+ // Performs outputAccum += weight * decoded(code)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code,
+ const float weight,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids, code, weight, outputAccum);
+ }
+
+ // Process 2 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ outputAccum);
+ }
+
+ // Process 2 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids, code0, weight0, code1, weight1, outputAccum);
+ }
+
+ // Process 3 samples.
+ // Each code uses its own fine pq centroids table.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqFineCentroids0,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const float* const __restrict pqFineCentroids1,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const float* const __restrict pqFineCentroids2,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids0,
+ code0,
+ weight0,
+ pqFineCentroids1,
+ code1,
+ weight1,
+ pqFineCentroids2,
+ code2,
+ weight2,
+ outputAccum);
+ }
+
+ // Process 3 samples.
+ // Fine pq centroids table is shared among codes.
+ //
+ // Performs outputAccum += weight0 * decoded(code0) + weight1 *
+ // decoded(code1) + weight2 * decoded(code2)
+ static void accum(
+ const float* const __restrict pqFineCentroids,
+ const uint8_t* const __restrict code0,
+ const float weight0,
+ const uint8_t* const __restrict code1,
+ const float weight1,
+ const uint8_t* const __restrict code2,
+ const float weight2,
+ float* const __restrict outputAccum) {
+ IndexPQDecoderImpl<DIM, FINE_SIZE, FINE_BITS, 0>::accum(
+ pqFineCentroids,
+ code0,
+ weight0,
+ code1,
+ weight1,
+ code2,
+ weight2,
+ outputAccum);
+ }
+};
+
+} // namespace cppcontrib
+} // namespace faiss
+#endif // PQ_NEON_INL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/CMakeLists.txt
new file mode 100644
index 0000000..0051f04
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/CMakeLists.txt
@@ -0,0 +1,352 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Meta Platforms, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+# =============================================================================
+# Copyright (c) 2023-2024, NVIDIA CORPORATION.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+# in compliance with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software distributed under the License
+# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+# or implied. See the License for the specific language governing permissions and limitations under
+# the License.
+# =============================================================================
+
+set(FAISS_GPU_SRC
+ GpuAutoTune.cpp
+ GpuCloner.cpp
+ GpuDistance.cu
+ GpuIcmEncoder.cu
+ GpuIndex.cu
+ GpuIndexBinaryFlat.cu
+ GpuIndexFlat.cu
+ GpuIndexIVF.cu
+ GpuIndexIVFFlat.cu
+ GpuIndexIVFPQ.cu
+ GpuIndexIVFScalarQuantizer.cu
+ GpuResources.cpp
+ StandardGpuResources.cpp
+ impl/BinaryDistance.cu
+ impl/BinaryFlatIndex.cu
+ impl/BroadcastSum.cu
+ impl/Distance.cu
+ impl/FlatIndex.cu
+ impl/IndexUtils.cu
+ impl/IVFAppend.cu
+ impl/IVFBase.cu
+ impl/IVFFlat.cu
+ impl/IVFFlatScan.cu
+ impl/IVFInterleaved.cu
+ impl/IVFPQ.cu
+ impl/IVFUtils.cu
+ impl/IVFUtilsSelect1.cu
+ impl/IVFUtilsSelect2.cu
+ impl/InterleavedCodes.cpp
+ impl/L2Norm.cu
+ impl/L2Select.cu
+ impl/PQScanMultiPassPrecomputed.cu
+ impl/RemapIndices.cpp
+ impl/VectorResidual.cu
+ impl/IcmEncoder.cu
+ utils/BlockSelectFloat.cu
+ utils/DeviceUtils.cu
+ utils/StackDeviceMemory.cpp
+ utils/Timer.cpp
+ utils/WarpSelectFloat.cu
+ utils/blockselect/BlockSelectFloat1.cu
+ utils/blockselect/BlockSelectFloat32.cu
+ utils/blockselect/BlockSelectFloat64.cu
+ utils/blockselect/BlockSelectFloat128.cu
+ utils/blockselect/BlockSelectFloat256.cu
+ utils/blockselect/BlockSelectFloatF512.cu
+ utils/blockselect/BlockSelectFloatF1024.cu
+ utils/blockselect/BlockSelectFloatF2048.cu
+ utils/blockselect/BlockSelectFloatT512.cu
+ utils/blockselect/BlockSelectFloatT1024.cu
+ utils/blockselect/BlockSelectFloatT2048.cu
+ utils/warpselect/WarpSelectFloat1.cu
+ utils/warpselect/WarpSelectFloat32.cu
+ utils/warpselect/WarpSelectFloat64.cu
+ utils/warpselect/WarpSelectFloat128.cu
+ utils/warpselect/WarpSelectFloat256.cu
+ utils/warpselect/WarpSelectFloatF512.cu
+ utils/warpselect/WarpSelectFloatF1024.cu
+ utils/warpselect/WarpSelectFloatF2048.cu
+ utils/warpselect/WarpSelectFloatT512.cu
+ utils/warpselect/WarpSelectFloatT1024.cu
+ utils/warpselect/WarpSelectFloatT2048.cu
+)
+
+set(FAISS_GPU_HEADERS
+ GpuAutoTune.h
+ GpuCloner.h
+ GpuClonerOptions.h
+ GpuDistance.h
+ GpuIcmEncoder.h
+ GpuFaissAssert.h
+ GpuIndex.h
+ GpuIndexBinaryFlat.h
+ GpuIndexFlat.h
+ GpuIndexIVF.h
+ GpuIndexIVFFlat.h
+ GpuIndexIVFPQ.h
+ GpuIndexIVFScalarQuantizer.h
+ GpuIndicesOptions.h
+ GpuResources.h
+ StandardGpuResources.h
+ impl/BinaryDistance.cuh
+ impl/BinaryFlatIndex.cuh
+ impl/BroadcastSum.cuh
+ impl/Distance.cuh
+ impl/DistanceUtils.cuh
+ impl/FlatIndex.cuh
+ impl/GeneralDistance.cuh
+ impl/GpuScalarQuantizer.cuh
+ impl/IndexUtils.h
+ impl/IVFAppend.cuh
+ impl/IVFBase.cuh
+ impl/IVFFlat.cuh
+ impl/IVFFlatScan.cuh
+ impl/IVFInterleaved.cuh
+ impl/IVFPQ.cuh
+ impl/IVFUtils.cuh
+ impl/InterleavedCodes.h
+ impl/L2Norm.cuh
+ impl/L2Select.cuh
+ impl/PQCodeDistances-inl.cuh
+ impl/PQCodeDistances.cuh
+ impl/PQCodeLoad.cuh
+ impl/PQScanMultiPassNoPrecomputed-inl.cuh
+ impl/PQScanMultiPassNoPrecomputed.cuh
+ impl/PQScanMultiPassPrecomputed.cuh
+ impl/RemapIndices.h
+ impl/VectorResidual.cuh
+ impl/scan/IVFInterleavedImpl.cuh
+ impl/IcmEncoder.cuh
+ utils/BlockSelectKernel.cuh
+ utils/Comparators.cuh
+ utils/ConversionOperators.cuh
+ utils/CopyUtils.cuh
+ utils/DeviceDefs.cuh
+ utils/DeviceTensor-inl.cuh
+ utils/DeviceTensor.cuh
+ utils/DeviceUtils.h
+ utils/DeviceVector.cuh
+ utils/Float16.cuh
+ utils/HostTensor-inl.cuh
+ utils/HostTensor.cuh
+ utils/Limits.cuh
+ utils/LoadStoreOperators.cuh
+ utils/MathOperators.cuh
+ utils/MatrixMult-inl.cuh
+ utils/MatrixMult.cuh
+ utils/MergeNetworkBlock.cuh
+ utils/MergeNetworkUtils.cuh
+ utils/MergeNetworkWarp.cuh
+ utils/NoTypeTensor.cuh
+ utils/Pair.cuh
+ utils/PtxUtils.cuh
+ utils/ReductionOperators.cuh
+ utils/Reductions.cuh
+ utils/Select.cuh
+ utils/StackDeviceMemory.h
+ utils/StaticUtils.h
+ utils/Tensor-inl.cuh
+ utils/Tensor.cuh
+ utils/ThrustUtils.cuh
+ utils/Timer.h
+ utils/Transpose.cuh
+ utils/WarpPackedBits.cuh
+ utils/WarpSelectKernel.cuh
+ utils/WarpShuffles.cuh
+ utils/blockselect/BlockSelectImpl.cuh
+ utils/warpselect/WarpSelectImpl.cuh
+)
+
+function(generate_ivf_interleaved_code)
+ set(SUB_CODEC_TYPE
+ "faiss::gpu::Codec<0, 1>"
+ "faiss::gpu::Codec<1, 1>"
+ "faiss::gpu::Codec<2, 1>"
+ "faiss::gpu::Codec<3, 1>"
+ "faiss::gpu::Codec<4, 1>"
+ "faiss::gpu::Codec<5, 1>"
+ "faiss::gpu::Codec<6, 1>"
+ "faiss::gpu::CodecFloat"
+ )
+
+ set(SUB_METRIC_TYPE
+ "faiss::gpu::IPDistance"
+ "faiss::gpu::L2Distance"
+ )
+
+ # Used for SUB_THREADS, SUB_NUM_WARP_Q, SUB_NUM_THREAD_Q
+ set(THREADS_AND_WARPS
+ "128|1024|8"
+ "128|1|1"
+ "128|128|3"
+ "128|256|4"
+ "128|32|2"
+ "128|512|8"
+ "128|64|3"
+ "64|2048|8"
+ )
+
+ if (FAISS_ENABLE_ROCM)
+ list(TRANSFORM FAISS_GPU_SRC REPLACE cu$ hip)
+ endif()
+
+ # Traverse through the Cartesian product of X and Y
+ foreach(sub_codec ${SUB_CODEC_TYPE})
+ foreach(metric_type ${SUB_METRIC_TYPE})
+ foreach(threads_and_warps_str ${THREADS_AND_WARPS})
+ string(REPLACE "|" ";" threads_and_warps ${threads_and_warps_str})
+ list(GET threads_and_warps 0 sub_threads)
+ list(GET threads_and_warps 1 sub_num_warp_q)
+ list(GET threads_and_warps 2 sub_num_thread_q)
+
+ # Define the output file name
+ set(filename "template_${sub_codec}_${metric_type}_${sub_threads}_${sub_num_warp_q}_${sub_num_thread_q}")
+ # Remove illegal characters from filename
+ string(REGEX REPLACE "[^A-Za-z0-9_]" "" filename ${filename})
+ set(output_file "${CMAKE_CURRENT_BINARY_DIR}/${filename}.${GPU_EXT_PREFIX}")
+
+ # Read the template file
+ file(READ "${CMAKE_CURRENT_SOURCE_DIR}/impl/scan/IVFInterleavedScanKernelTemplate.${GPU_EXT_PREFIX}" template_content)
+
+ # Replace the placeholders
+ string(REPLACE "SUB_CODEC_TYPE" "${sub_codec}" template_content "${template_content}")
+ string(REPLACE "SUB_METRIC_TYPE" "${metric_type}" template_content "${template_content}")
+ string(REPLACE "SUB_THREADS" "${sub_threads}" template_content "${template_content}")
+ string(REPLACE "SUB_NUM_WARP_Q" "${sub_num_warp_q}" template_content "${template_content}")
+ string(REPLACE "SUB_NUM_THREAD_Q" "${sub_num_thread_q}" template_content "${template_content}")
+
+ # Write the modified content to the output file
+ file(WRITE "${output_file}" "${template_content}")
+
+ # Add the file to the sources
+ list(APPEND FAISS_GPU_SRC "${output_file}")
+ endforeach()
+ endforeach()
+ endforeach()
+ # Propagate modified variable to the parent scope
+ set(FAISS_GPU_SRC "${FAISS_GPU_SRC}" PARENT_SCOPE)
+endfunction()
+
+generate_ivf_interleaved_code()
+
+if(FAISS_ENABLE_CUVS)
+ list(APPEND FAISS_GPU_HEADERS
+ GpuIndexCagra.h
+ impl/CuvsCagra.cuh
+ impl/CuvsFlatIndex.cuh
+ impl/CuvsIVFFlat.cuh
+ impl/CuvsIVFPQ.cuh
+ utils/CuvsUtils.h)
+ list(APPEND FAISS_GPU_SRC
+ GpuIndexCagra.cu
+ impl/CuvsCagra.cu
+ impl/CuvsFlatIndex.cu
+ impl/CuvsIVFFlat.cu
+ impl/CuvsIVFPQ.cu
+ utils/CuvsUtils.cu)
+endif()
+
+add_library(faiss_gpu_objs OBJECT ${FAISS_GPU_SRC})
+set_target_properties(faiss_gpu_objs PROPERTIES
+ POSITION_INDEPENDENT_CODE ON
+ WINDOWS_EXPORT_ALL_SYMBOLS ON
+)
+target_include_directories(faiss_gpu_objs PUBLIC
+ $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>)
+
+if(FAISS_ENABLE_CUVS)
+ target_compile_definitions(faiss PUBLIC USE_NVIDIA_CUVS=1)
+ target_compile_definitions(faiss_avx2 PUBLIC USE_NVIDIA_CUVS=1)
+ target_compile_definitions(faiss_avx512 PUBLIC USE_NVIDIA_CUVS=1)
+ target_compile_definitions(faiss_avx512_spr PUBLIC USE_NVIDIA_CUVS=1)
+
+ # Mark all functions as hidden so that we don't generate
+ # global 'public' functions that also exist in libcuvs.so
+ #
+ # This ensures that faiss functions will call the local version
+ # inside libfaiss.so . This is needed to ensure that things
+ # like raft cublas resources are created and used within the same
+ # dynamic library + CUDA runtime context which are requirements
+ # for valid execution
+ #
+ # To still allow these classes to be used by consumers, the
+ # respective classes/types in the headers are explicitly marked
+ # as 'public' so they can be used by consumers
+ set_source_files_properties(
+ GpuIndexCagra.cu
+ GpuDistance.cu
+ GpuIndexIVFFlat.cu
+ GpuIndexIVFPQ.cu
+ GpuIndexFlat.cu
+ StandardGpuResources.cpp
+ impl/CuvsCagra.cu
+ impl/CuvsFlatIndex.cu
+ impl/CuvsIVFFlat.cu
+ impl/CuvsIVFPQ.cu
+ utils/CuvsUtils.cu
+ TARGET_DIRECTORY faiss
+ PROPERTIES COMPILE_OPTIONS "-fvisibility=hidden")
+ target_compile_definitions(faiss_gpu_objs PUBLIC USE_NVIDIA_CUVS=1)
+endif()
+
+if (FAISS_ENABLE_ROCM)
+ list(TRANSFORM FAISS_GPU_SRC REPLACE cu$ hip)
+endif()
+
+# Export FAISS_GPU_HEADERS variable to parent scope.
+set(FAISS_GPU_HEADERS ${FAISS_GPU_HEADERS} PARENT_SCOPE)
+
+target_link_libraries(faiss PRIVATE faiss_gpu_objs)
+target_link_libraries(faiss_avx2 PRIVATE faiss_gpu_objs)
+target_link_libraries(faiss_avx512 PRIVATE faiss_gpu_objs)
+target_link_libraries(faiss_avx512_spr PRIVATE faiss_gpu_objs)
+target_link_libraries(faiss_sve PRIVATE faiss_gpu_objs)
+
+install(TARGETS faiss_gpu_objs EXPORT faiss-targets)
+
+foreach(header ${FAISS_GPU_HEADERS})
+ get_filename_component(dir ${header} DIRECTORY )
+ install(FILES ${header}
+ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/faiss/gpu/${dir}
+ )
+endforeach()
+
+if (FAISS_ENABLE_ROCM)
+ target_link_libraries(faiss_gpu_objs PRIVATE hip::host roc::hipblas)
+ target_compile_options(faiss_gpu_objs PRIVATE)
+else()
+ # Prepares a host linker script and enables host linker to support
+ # very large device object files.
+ # This is what CUDA 11.5+ `nvcc -hls=gen-lcs -aug-hls` would generate
+ file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/fatbin.ld"
+ [=[
+ SECTIONS
+ {
+ .nvFatBinSegment : { *(.nvFatBinSegment) }
+ __nv_relfatbin : { *(__nv_relfatbin) }
+ .nv_fatbin : { *(.nv_fatbin) }
+ }
+ ]=]
+ )
+ target_link_options(faiss_gpu_objs PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/fatbin.ld")
+
+
+ find_package(CUDAToolkit REQUIRED)
+ target_link_libraries(faiss_gpu_objs PRIVATE CUDA::cudart CUDA::cublas $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs> $<$<BOOL:${FAISS_ENABLE_CUVS}>:OpenMP::OpenMP_CXX>)
+ target_compile_options(faiss_gpu_objs PRIVATE
+ $<$<COMPILE_LANGUAGE:CUDA>:-Xfatbin=-compress-all
+ --expt-extended-lambda --expt-relaxed-constexpr
+ $<$<BOOL:${FAISS_ENABLE_CUVS}>:-Xcompiler=${OpenMP_CXX_FLAGS}>>)
+endif()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuAutoTune.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuAutoTune.cpp
new file mode 100644
index 0000000..fed0132
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuAutoTune.cpp
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuAutoTune.h>
+#include <typeinfo>
+
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexReplicas.h>
+#include <faiss/IndexShards.h>
+#include <faiss/IndexShardsIVF.h>
+
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+
+namespace faiss {
+namespace gpu {
+
+using namespace ::faiss;
+
+/**********************************************************
+ * Parameters to auto-tune on GpuIndex'es
+ **********************************************************/
+
+#define DC(classname) auto ix = dynamic_cast<const classname*>(index)
+
+void GpuParameterSpace::initialize(const Index* index) {
+ if (DC(IndexPreTransform)) {
+ initialize(ix->index);
+ return;
+ }
+ if (DC(IndexShardsIVF)) {
+ ParameterSpace::initialize(index);
+ return;
+ }
+ if (DC(IndexReplicas)) {
+ if (ix->count() == 0)
+ return;
+ index = ix->at(0);
+ }
+ if (DC(IndexShards)) {
+ if (ix->count() == 0)
+ return;
+ index = ix->at(0);
+ }
+ if (DC(GpuIndexIVF)) {
+ ParameterRange& pr = add_range("nprobe");
+ for (int i = 0; i < 12; i++) {
+ size_t nprobe = 1 << i;
+ if (nprobe >= ix->getNumLists() || nprobe > getMaxKSelection())
+ break;
+ pr.values.push_back(nprobe);
+ }
+
+ ParameterSpace ivf_pspace;
+ ivf_pspace.initialize(ix->quantizer);
+
+ for (const ParameterRange& p : ivf_pspace.parameter_ranges) {
+ ParameterRange& pr = add_range("quantizer_" + p.name);
+ pr.values = p.values;
+ }
+ }
+ // not sure we should call the parent initializer
+}
+
+#undef DC
+// non-const version
+#define DC(classname) auto* ix = dynamic_cast<classname*>(index)
+
+void GpuParameterSpace::set_index_parameter(
+ Index* index,
+ const std::string& name,
+ double val) const {
+ if (DC(IndexReplicas)) {
+ for (int i = 0; i < ix->count(); i++)
+ set_index_parameter(ix->at(i), name, val);
+ return;
+ }
+ if (name == "nprobe") {
+ if (DC(GpuIndexIVF)) {
+ ix->nprobe = size_t(val);
+ return;
+ }
+ }
+ if (name == "use_precomputed_table") {
+ if (DC(GpuIndexIVFPQ)) {
+ ix->setPrecomputedCodes(bool(val));
+ return;
+ }
+ }
+
+ if (name.find("quantizer_") == 0) {
+ if (DC(GpuIndexIVF)) {
+ std::string sub_name = name.substr(strlen("quantizer_"));
+ set_index_parameter(ix->quantizer, sub_name, val);
+ return;
+ }
+ }
+
+ // maybe normal index parameters apply?
+ ParameterSpace::set_index_parameter(index, name, val);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuAutoTune.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuAutoTune.h
new file mode 100644
index 0000000..b61f015
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuAutoTune.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/AutoTune.h>
+#include <faiss/Index.h>
+
+namespace faiss {
+namespace gpu {
+
+/// parameter space and setters for GPU indexes
+struct GpuParameterSpace : faiss::ParameterSpace {
+ /// initialize with reasonable parameters for the index
+ void initialize(const faiss::Index* index) override;
+
+ /// set a combination of parameters on an index
+ void set_index_parameter(
+ faiss::Index* index,
+ const std::string& name,
+ double val) const override;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuCloner.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuCloner.cpp
new file mode 100644
index 0000000..575ee2e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuCloner.cpp
@@ -0,0 +1,592 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/impl/FaissAssert.h>
+#include <memory>
+#include <typeinfo>
+
+#include <faiss/gpu/StandardGpuResources.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexFlat.h>
+#if defined USE_NVIDIA_CUVS
+#include <faiss/IndexHNSW.h>
+#endif
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexReplicas.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/IndexShardsIVF.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexBinaryFlat.h>
+#if defined USE_NVIDIA_CUVS
+#include <faiss/gpu/GpuIndexCagra.h>
+#endif
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/GpuIndexIVFScalarQuantizer.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/index_io.h>
+
+namespace faiss {
+namespace gpu {
+
+/**********************************************************
+ * Cloning to CPU
+ **********************************************************/
+
+void ToCPUCloner::merge_index(Index* dst, Index* src, bool successive_ids) {
+ if (auto ifl = dynamic_cast<IndexFlat*>(dst)) {
+ auto ifl2 = dynamic_cast<const IndexFlat*>(src);
+ FAISS_ASSERT(ifl2);
+ FAISS_ASSERT(successive_ids);
+ ifl->add(ifl2->ntotal, ifl2->get_xb());
+ } else if (auto ifl = dynamic_cast<IndexIVFFlat*>(dst)) {
+ auto ifl2 = dynamic_cast<IndexIVFFlat*>(src);
+ FAISS_ASSERT(ifl2);
+ ifl->merge_from(*ifl2, successive_ids ? ifl->ntotal : 0);
+ } else if (auto ifl = dynamic_cast<IndexIVFScalarQuantizer*>(dst)) {
+ auto ifl2 = dynamic_cast<IndexIVFScalarQuantizer*>(src);
+ FAISS_ASSERT(ifl2);
+ ifl->merge_from(*ifl2, successive_ids ? ifl->ntotal : 0);
+ } else if (auto ifl = dynamic_cast<IndexIVFPQ*>(dst)) {
+ auto ifl2 = dynamic_cast<IndexIVFPQ*>(src);
+ FAISS_ASSERT(ifl2);
+ ifl->merge_from(*ifl2, successive_ids ? ifl->ntotal : 0);
+ } else {
+ FAISS_ASSERT(!"merging not implemented for this type of class");
+ }
+}
+
+Index* ToCPUCloner::clone_Index(const Index* index) {
+ if (auto ifl = dynamic_cast<const GpuIndexFlat*>(index)) {
+ IndexFlat* res = new IndexFlat();
+ ifl->copyTo(res);
+ return res;
+ } else if (auto ifl = dynamic_cast<const GpuIndexIVFFlat*>(index)) {
+ IndexIVFFlat* res = new IndexIVFFlat();
+ ifl->copyTo(res);
+ return res;
+ } else if (
+ auto ifl = dynamic_cast<const GpuIndexIVFScalarQuantizer*>(index)) {
+ IndexIVFScalarQuantizer* res = new IndexIVFScalarQuantizer();
+ ifl->copyTo(res);
+ return res;
+ } else if (auto ipq = dynamic_cast<const GpuIndexIVFPQ*>(index)) {
+ IndexIVFPQ* res = new IndexIVFPQ();
+ ipq->copyTo(res);
+ return res;
+
+ // for IndexShards and IndexReplicas we assume that the
+ // objective is to make a single component out of them
+ // (inverse op of ToGpuClonerMultiple)
+
+ }
+#if defined USE_NVIDIA_CUVS
+ else if (auto icg = dynamic_cast<const GpuIndexCagra*>(index)) {
+ IndexHNSWCagra* res = new IndexHNSWCagra();
+ icg->copyTo(res);
+ return res;
+ }
+#endif
+ else if (auto ish = dynamic_cast<const IndexShards*>(index)) {
+ int nshard = ish->count();
+ FAISS_ASSERT(nshard > 0);
+ Index* res = clone_Index(ish->at(0));
+ for (int i = 1; i < ish->count(); i++) {
+ Index* res_i = clone_Index(ish->at(i));
+ merge_index(res, res_i, ish->successive_ids);
+ delete res_i;
+ }
+ return res;
+ } else if (auto ipr = dynamic_cast<const IndexReplicas*>(index)) {
+ // just clone one of the replicas
+ FAISS_ASSERT(ipr->count() > 0);
+ return clone_Index(ipr->at(0));
+ } else {
+ return Cloner::clone_Index(index);
+ }
+}
+
+faiss::Index* index_gpu_to_cpu(const faiss::Index* gpu_index) {
+ ToCPUCloner cl;
+ return cl.clone_Index(gpu_index);
+}
+
+/**********************************************************
+ * Cloning to 1 GPU
+ **********************************************************/
+
+ToGpuCloner::ToGpuCloner(
+ GpuResourcesProvider* prov,
+ int device,
+ const GpuClonerOptions& options)
+ : GpuClonerOptions(options), provider(prov), device(device) {}
+
+Index* ToGpuCloner::clone_Index(const Index* index) {
+ if (auto ifl = dynamic_cast<const IndexFlat*>(index)) {
+ GpuIndexFlatConfig config;
+ config.device = device;
+ config.useFloat16 = useFloat16;
+ config.use_cuvs = use_cuvs;
+ return new GpuIndexFlat(provider, ifl, config);
+ } else if (
+ dynamic_cast<const IndexScalarQuantizer*>(index) &&
+ static_cast<const IndexScalarQuantizer*>(index)->sq.qtype ==
+ ScalarQuantizer::QT_fp16) {
+ GpuIndexFlatConfig config;
+ config.device = device;
+ config.useFloat16 = true;
+ FAISS_THROW_IF_NOT_MSG(
+ !use_cuvs, "this type of index is not implemented for cuVS");
+ GpuIndexFlat* gif = new GpuIndexFlat(
+ provider, index->d, index->metric_type, config);
+ // transfer data by blocks
+ idx_t bs = 1024 * 1024;
+ for (idx_t i0 = 0; i0 < index->ntotal; i0 += bs) {
+ idx_t i1 = std::min(i0 + bs, index->ntotal);
+ std::vector<float> buffer((i1 - i0) * index->d);
+ index->reconstruct_n(i0, i1 - i0, buffer.data());
+ gif->add(i1 - i0, buffer.data());
+ }
+ assert(gif->getNumVecs() == index->ntotal);
+ return gif;
+ } else if (auto ifl = dynamic_cast<const faiss::IndexIVFFlat*>(index)) {
+ GpuIndexIVFFlatConfig config;
+ config.device = device;
+ config.indicesOptions = indicesOptions;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ config.use_cuvs = use_cuvs;
+ config.allowCpuCoarseQuantizer = allowCpuCoarseQuantizer;
+
+ GpuIndexIVFFlat* res = new GpuIndexIVFFlat(
+ provider, ifl->d, ifl->nlist, ifl->metric_type, config);
+ if (reserveVecs > 0 && ifl->ntotal == 0) {
+ res->reserveMemory(reserveVecs);
+ }
+
+ res->copyFrom(ifl);
+ return res;
+ } else if (
+ auto ifl = dynamic_cast<const faiss::IndexIVFScalarQuantizer*>(
+ index)) {
+ GpuIndexIVFScalarQuantizerConfig config;
+ config.device = device;
+ config.indicesOptions = indicesOptions;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ FAISS_THROW_IF_NOT_MSG(
+ !use_cuvs, "this type of index is not implemented for cuVS");
+
+ GpuIndexIVFScalarQuantizer* res = new GpuIndexIVFScalarQuantizer(
+ provider,
+ ifl->d,
+ ifl->nlist,
+ ifl->sq.qtype,
+ ifl->metric_type,
+ ifl->by_residual,
+ config);
+ if (reserveVecs > 0 && ifl->ntotal == 0) {
+ res->reserveMemory(reserveVecs);
+ }
+
+ res->copyFrom(ifl);
+ return res;
+ } else if (auto ipq = dynamic_cast<const faiss::IndexIVFPQ*>(index)) {
+ if (verbose) {
+ printf(" IndexIVFPQ size %ld -> GpuIndexIVFPQ "
+ "indicesOptions=%d "
+ "usePrecomputed=%d useFloat16=%d reserveVecs=%ld\n",
+ ipq->ntotal,
+ indicesOptions,
+ usePrecomputed,
+ useFloat16,
+ reserveVecs);
+ }
+ GpuIndexIVFPQConfig config;
+ config.device = device;
+ config.indicesOptions = indicesOptions;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ config.useFloat16LookupTables = useFloat16;
+ config.usePrecomputedTables = usePrecomputed;
+ config.use_cuvs = use_cuvs;
+ config.interleavedLayout = use_cuvs;
+ config.allowCpuCoarseQuantizer = allowCpuCoarseQuantizer;
+
+ GpuIndexIVFPQ* res = new GpuIndexIVFPQ(provider, ipq, config);
+
+ if (reserveVecs > 0 && ipq->ntotal == 0) {
+ res->reserveMemory(reserveVecs);
+ }
+
+ return res;
+ }
+#if defined USE_NVIDIA_CUVS
+ else if (auto icg = dynamic_cast<const faiss::IndexHNSWCagra*>(index)) {
+ GpuIndexCagraConfig config;
+ config.device = device;
+ GpuIndexCagra* res =
+ new GpuIndexCagra(provider, icg->d, icg->metric_type, config);
+ res->copyFrom(icg);
+ return res;
+ }
+#endif
+ else {
+ // use CPU cloner for IDMap and PreTransform
+ auto index_idmap = dynamic_cast<const IndexIDMap*>(index);
+ auto index_pt = dynamic_cast<const IndexPreTransform*>(index);
+ if (index_idmap || index_pt) {
+ return Cloner::clone_Index(index);
+ }
+ FAISS_THROW_MSG("This index type is not implemented on GPU.");
+ }
+}
+
+faiss::Index* index_cpu_to_gpu(
+ GpuResourcesProvider* provider,
+ int device,
+ const faiss::Index* index,
+ const GpuClonerOptions* options) {
+ GpuClonerOptions defaults;
+ ToGpuCloner cl(provider, device, options ? *options : defaults);
+ return cl.clone_Index(index);
+}
+
+/**********************************************************
+ * Cloning to multiple GPUs
+ **********************************************************/
+
+ToGpuClonerMultiple::ToGpuClonerMultiple(
+ std::vector<GpuResourcesProvider*>& provider,
+ std::vector<int>& devices,
+ const GpuMultipleClonerOptions& options)
+ : GpuMultipleClonerOptions(options) {
+ FAISS_THROW_IF_NOT(provider.size() == devices.size());
+ for (size_t i = 0; i < provider.size(); i++) {
+ sub_cloners.emplace_back(provider[i], devices[i], options);
+ }
+}
+
+ToGpuClonerMultiple::ToGpuClonerMultiple(
+ const std::vector<ToGpuCloner>& sub_cloners,
+ const GpuMultipleClonerOptions& options)
+ : GpuMultipleClonerOptions(options), sub_cloners(sub_cloners) {}
+
+void ToGpuClonerMultiple::copy_ivf_shard(
+ const IndexIVF* index_ivf,
+ IndexIVF* idx2,
+ idx_t n,
+ idx_t i) {
+ if (shard_type == 2) {
+ idx_t i0 = i * index_ivf->ntotal / n;
+ idx_t i1 = (i + 1) * index_ivf->ntotal / n;
+
+ if (verbose)
+ printf("IndexShards shard %ld indices %ld:%ld\n", i, i0, i1);
+ index_ivf->copy_subset_to(
+ *idx2, InvertedLists::SUBSET_TYPE_ID_RANGE, i0, i1);
+ FAISS_ASSERT(idx2->ntotal == i1 - i0);
+ } else if (shard_type == 1) {
+ if (verbose)
+ printf("IndexShards shard %ld select modulo %ld = %ld\n", i, n, i);
+ index_ivf->copy_subset_to(
+ *idx2, InvertedLists::SUBSET_TYPE_ID_MOD, n, i);
+ } else if (shard_type == 4) {
+ idx_t i0 = i * index_ivf->nlist / n;
+ idx_t i1 = (i + 1) * index_ivf->nlist / n;
+ if (verbose) {
+ printf("IndexShards %ld/%ld select lists %d:%d\n",
+ i,
+ n,
+ int(i0),
+ int(i1));
+ }
+ index_ivf->copy_subset_to(
+ *idx2, InvertedLists::SUBSET_TYPE_INVLIST, i0, i1);
+ } else {
+ FAISS_THROW_FMT("shard_type %d not implemented", shard_type);
+ }
+}
+
+Index* ToGpuClonerMultiple::clone_Index_to_shards(const Index* index) {
+ idx_t n = sub_cloners.size();
+
+ auto index_ivf = dynamic_cast<const faiss::IndexIVF*>(index);
+ auto index_ivfpq = dynamic_cast<const faiss::IndexIVFPQ*>(index);
+ auto index_ivfflat = dynamic_cast<const faiss::IndexIVFFlat*>(index);
+ auto index_ivfsq =
+ dynamic_cast<const faiss::IndexIVFScalarQuantizer*>(index);
+ auto index_flat = dynamic_cast<const faiss::IndexFlat*>(index);
+ FAISS_THROW_IF_NOT_MSG(
+ index_ivfpq || index_ivfflat || index_flat || index_ivfsq,
+ "IndexShards implemented only for "
+ "IndexIVFFlat, IndexIVFScalarQuantizer, "
+ "IndexFlat and IndexIVFPQ");
+
+ // decide what coarse quantizer the sub-indexes are going to have
+ const Index* quantizer = nullptr;
+ std::unique_ptr<Index> new_quantizer;
+ if (index_ivf) {
+ quantizer = index_ivf->quantizer;
+ if (common_ivf_quantizer &&
+ !dynamic_cast<const IndexFlat*>(quantizer)) {
+ // then we flatten the coarse quantizer so that everything remains
+ // on GPU
+ new_quantizer = std::make_unique<IndexFlat>(
+ quantizer->d, quantizer->metric_type);
+ std::vector<float> centroids(quantizer->d * quantizer->ntotal);
+ quantizer->reconstruct_n(0, quantizer->ntotal, centroids.data());
+ new_quantizer->add(quantizer->ntotal, centroids.data());
+ quantizer = new_quantizer.get();
+ }
+ }
+
+ std::vector<faiss::Index*> shards(n);
+
+#pragma omp parallel for
+ for (idx_t i = 0; i < n; i++) {
+ // make a shallow copy
+ if (reserveVecs) {
+ sub_cloners[i].reserveVecs = (reserveVecs + n - 1) / n;
+ }
+ // note: const_casts here are harmless because the indexes build here
+ // are short-lived, translated immediately to GPU indexes.
+ if (index_ivfpq) {
+ faiss::IndexIVFPQ idx2(
+ const_cast<Index*>(quantizer),
+ index_ivfpq->d,
+ index_ivfpq->nlist,
+ index_ivfpq->pq.M,
+ index_ivfpq->pq.nbits);
+ idx2.metric_type = index_ivfpq->metric_type;
+ idx2.pq = index_ivfpq->pq;
+ idx2.nprobe = index_ivfpq->nprobe;
+ idx2.use_precomputed_table = 0;
+ idx2.is_trained = index->is_trained;
+ copy_ivf_shard(index_ivfpq, &idx2, n, i);
+ shards[i] = sub_cloners[i].clone_Index(&idx2);
+ } else if (index_ivfflat) {
+ faiss::IndexIVFFlat idx2(
+ const_cast<Index*>(quantizer),
+ index->d,
+ index_ivfflat->nlist,
+ index_ivfflat->metric_type);
+ idx2.nprobe = index_ivfflat->nprobe;
+ idx2.is_trained = index->is_trained;
+ copy_ivf_shard(index_ivfflat, &idx2, n, i);
+ shards[i] = sub_cloners[i].clone_Index(&idx2);
+ } else if (index_ivfsq) {
+ faiss::IndexIVFScalarQuantizer idx2(
+ const_cast<Index*>(quantizer),
+ index->d,
+ index_ivfsq->nlist,
+ index_ivfsq->sq.qtype,
+ index_ivfsq->metric_type,
+ index_ivfsq->by_residual);
+
+ idx2.nprobe = index_ivfsq->nprobe;
+ idx2.is_trained = index->is_trained;
+ idx2.sq = index_ivfsq->sq;
+ copy_ivf_shard(index_ivfsq, &idx2, n, i);
+ shards[i] = sub_cloners[i].clone_Index(&idx2);
+ } else if (index_flat) {
+ faiss::IndexFlat idx2(index->d, index->metric_type);
+ shards[i] = sub_cloners[i].clone_Index(&idx2);
+ if (index->ntotal > 0) {
+ idx_t i0 = index->ntotal * i / n;
+ idx_t i1 = index->ntotal * (i + 1) / n;
+ shards[i]->add(i1 - i0, index_flat->get_xb() + i0 * index->d);
+ }
+ }
+ }
+
+ bool successive_ids = index_flat != nullptr;
+ faiss::IndexShards* res;
+ if (common_ivf_quantizer && index_ivf) {
+ this->shard = false;
+ Index* common_quantizer = clone_Index(index_ivf->quantizer);
+ this->shard = true;
+ IndexShardsIVF* idx = new faiss::IndexShardsIVF(
+ common_quantizer, index_ivf->nlist, true, false);
+ idx->own_fields = true;
+ idx->own_indices = true;
+ res = idx;
+ } else {
+ res = new faiss::IndexShards(index->d, true, successive_ids);
+ res->own_indices = true;
+ }
+
+ for (int i = 0; i < n; i++) {
+ res->add_shard(shards[i]);
+ }
+ FAISS_ASSERT(index->ntotal == res->ntotal);
+ return res;
+}
+
+Index* ToGpuClonerMultiple::clone_Index(const Index* index) {
+ idx_t n = sub_cloners.size();
+ if (n == 1) {
+ return sub_cloners[0].clone_Index(index);
+ }
+
+ if (dynamic_cast<const IndexFlat*>(index) ||
+ dynamic_cast<const IndexIVFFlat*>(index) ||
+ dynamic_cast<const IndexIVFScalarQuantizer*>(index) ||
+ dynamic_cast<const IndexIVFPQ*>(index)) {
+ if (!shard) {
+ IndexReplicas* res = new IndexReplicas();
+ for (auto& sub_cloner : sub_cloners) {
+ res->addIndex(sub_cloner.clone_Index(index));
+ }
+ res->own_indices = true;
+ return res;
+ } else {
+ return clone_Index_to_shards(index);
+ }
+ } else if (auto miq = dynamic_cast<const MultiIndexQuantizer*>(index)) {
+ if (verbose) {
+ printf("cloning MultiIndexQuantizer: "
+ "will be valid only for search k=1\n");
+ }
+ const ProductQuantizer& pq = miq->pq;
+ IndexSplitVectors* splitv = new IndexSplitVectors(pq.d, true);
+ splitv->own_fields = true;
+
+ for (int m = 0; m < pq.M; m++) {
+ // which GPU(s) will be assigned to this sub-quantizer
+
+ idx_t i0 = m * n / pq.M;
+ idx_t i1 = pq.M <= n ? (m + 1) * n / pq.M : i0 + 1;
+ std::vector<ToGpuCloner> sub_cloners_2;
+ sub_cloners_2.insert(
+ sub_cloners_2.begin(),
+ sub_cloners.begin() + i0,
+ sub_cloners.begin() + i1);
+ ToGpuClonerMultiple cm(sub_cloners_2, *this);
+ IndexFlatL2 idxc(pq.dsub);
+ idxc.add(pq.ksub, pq.centroids.data() + m * pq.d * pq.ksub);
+ Index* idx2 = cm.clone_Index(&idxc);
+ splitv->add_sub_index(idx2);
+ }
+ return splitv;
+ } else {
+ return Cloner::clone_Index(index);
+ }
+}
+
+faiss::Index* index_cpu_to_gpu_multiple(
+ std::vector<GpuResourcesProvider*>& provider,
+ std::vector<int>& devices,
+ const faiss::Index* index,
+ const GpuMultipleClonerOptions* options) {
+ GpuMultipleClonerOptions defaults;
+ ToGpuClonerMultiple cl(provider, devices, options ? *options : defaults);
+ return cl.clone_Index(index);
+}
+
+GpuProgressiveDimIndexFactory::GpuProgressiveDimIndexFactory(int ngpu) {
+ FAISS_THROW_IF_NOT(ngpu >= 1);
+ devices.resize(ngpu);
+ vres.resize(ngpu);
+
+ for (int i = 0; i < ngpu; i++) {
+ vres[i] = new StandardGpuResources();
+ devices[i] = i;
+ }
+ ncall = 0;
+}
+
+GpuProgressiveDimIndexFactory::~GpuProgressiveDimIndexFactory() {
+ for (int i = 0; i < vres.size(); i++) {
+ delete vres[i];
+ }
+}
+
+Index* GpuProgressiveDimIndexFactory::operator()(int dim) {
+ IndexFlatL2 index(dim);
+ ncall++;
+ return index_cpu_to_gpu_multiple(vres, devices, &index, &options);
+}
+
+/*********************************************
+ * Cloning binary indexes
+ *********************************************/
+
+faiss::IndexBinary* index_binary_gpu_to_cpu(
+ const faiss::IndexBinary* gpu_index) {
+ if (auto ii = dynamic_cast<const GpuIndexBinaryFlat*>(gpu_index)) {
+ IndexBinaryFlat* ret = new IndexBinaryFlat();
+ ii->copyTo(ret);
+ return ret;
+ } else {
+ FAISS_THROW_MSG("cannot clone this type of index");
+ }
+}
+
+faiss::IndexBinary* index_binary_cpu_to_gpu(
+ GpuResourcesProvider* provider,
+ int device,
+ const faiss::IndexBinary* index,
+ const GpuClonerOptions* options) {
+ if (auto ii = dynamic_cast<const IndexBinaryFlat*>(index)) {
+ GpuIndexBinaryFlatConfig config;
+ config.device = device;
+ if (options) {
+ config.use_cuvs = options->use_cuvs;
+ }
+ return new GpuIndexBinaryFlat(provider, ii, config);
+ } else {
+ FAISS_THROW_MSG("cannot clone this type of index");
+ }
+}
+
+faiss::IndexBinary* index_binary_cpu_to_gpu_multiple(
+ std::vector<GpuResourcesProvider*>& provider,
+ std::vector<int>& devices,
+ const faiss::IndexBinary* index,
+ const GpuMultipleClonerOptions* options) {
+ GpuMultipleClonerOptions defaults;
+ FAISS_THROW_IF_NOT(devices.size() == provider.size());
+ int n = devices.size();
+ if (n == 1) {
+ return index_binary_cpu_to_gpu(provider[0], devices[0], index, options);
+ }
+ if (!options) {
+ options = &defaults;
+ }
+ if (options->shard) {
+ auto* fi = dynamic_cast<const IndexBinaryFlat*>(index);
+ FAISS_THROW_IF_NOT_MSG(fi, "only flat index cloning supported");
+ IndexBinaryShards* ret = new IndexBinaryShards(true, true);
+ for (int i = 0; i < n; i++) {
+ IndexBinaryFlat fig(fi->d);
+ size_t i0 = i * fi->ntotal / n;
+ size_t i1 = (i + 1) * fi->ntotal / n;
+ fig.add(i1 - i0, fi->xb.data() + i0 * fi->code_size);
+ ret->addIndex(index_binary_cpu_to_gpu(
+ provider[i], devices[i], &fig, options));
+ }
+ ret->own_indices = true;
+ return ret;
+ } else { // replicas
+ IndexBinaryReplicas* ret = new IndexBinaryReplicas(true);
+ for (int i = 0; i < n; i++) {
+ ret->addIndex(index_binary_cpu_to_gpu(
+ provider[i], devices[i], index, options));
+ }
+ ret->own_indices = true;
+ return ret;
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuCloner.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuCloner.h
new file mode 100644
index 0000000..d92d81f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuCloner.h
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <faiss/Clustering.h>
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/clone_index.h>
+#include <faiss/gpu/GpuClonerOptions.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResourcesProvider;
+
+/// Cloner specialized for GPU -> CPU
+struct ToCPUCloner : faiss::Cloner {
+ void merge_index(Index* dst, Index* src, bool successive_ids);
+ Index* clone_Index(const Index* index) override;
+};
+
+/// Cloner specialized for CPU -> 1 GPU
+struct ToGpuCloner : faiss::Cloner, GpuClonerOptions {
+ GpuResourcesProvider* provider;
+ int device;
+
+ ToGpuCloner(
+ GpuResourcesProvider* prov,
+ int device,
+ const GpuClonerOptions& options);
+
+ Index* clone_Index(const Index* index) override;
+};
+
+/// Cloner specialized for CPU -> multiple GPUs
+struct ToGpuClonerMultiple : faiss::Cloner, GpuMultipleClonerOptions {
+ std::vector<ToGpuCloner> sub_cloners;
+
+ ToGpuClonerMultiple(
+ std::vector<GpuResourcesProvider*>& provider,
+ std::vector<int>& devices,
+ const GpuMultipleClonerOptions& options);
+
+ ToGpuClonerMultiple(
+ const std::vector<ToGpuCloner>& sub_cloners,
+ const GpuMultipleClonerOptions& options);
+
+ void copy_ivf_shard(
+ const IndexIVF* index_ivf,
+ IndexIVF* idx2,
+ idx_t n,
+ idx_t i);
+
+ Index* clone_Index_to_shards(const Index* index);
+
+ /// main function
+ Index* clone_Index(const Index* index) override;
+};
+
+/// converts any GPU index inside gpu_index to a CPU index
+faiss::Index* index_gpu_to_cpu(const faiss::Index* gpu_index);
+
+/// converts any CPU index that can be converted to GPU
+faiss::Index* index_cpu_to_gpu(
+ GpuResourcesProvider* provider,
+ int device,
+ const faiss::Index* index,
+ const GpuClonerOptions* options = nullptr);
+
+faiss::Index* index_cpu_to_gpu_multiple(
+ std::vector<GpuResourcesProvider*>& provider,
+ std::vector<int>& devices,
+ const faiss::Index* index,
+ const GpuMultipleClonerOptions* options = nullptr);
+
+/// index factory for the ProgressiveDimClustering object
+
+struct GpuProgressiveDimIndexFactory : ProgressiveDimIndexFactory {
+ GpuMultipleClonerOptions options;
+ std::vector<GpuResourcesProvider*> vres;
+ std::vector<int> devices;
+ int ncall;
+
+ explicit GpuProgressiveDimIndexFactory(int ngpu);
+
+ Index* operator()(int dim) override;
+
+ virtual ~GpuProgressiveDimIndexFactory() override;
+};
+
+/*********************************************
+ * Cloning binary indexes
+ *********************************************/
+
+faiss::IndexBinary* index_binary_gpu_to_cpu(
+ const faiss::IndexBinary* gpu_index);
+
+/// converts any CPU index that can be converted to GPU
+faiss::IndexBinary* index_binary_cpu_to_gpu(
+ GpuResourcesProvider* provider,
+ int device,
+ const faiss::IndexBinary* index,
+ const GpuClonerOptions* options = nullptr);
+
+faiss::IndexBinary* index_binary_cpu_to_gpu_multiple(
+ std::vector<GpuResourcesProvider*>& provider,
+ std::vector<int>& devices,
+ const faiss::IndexBinary* index,
+ const GpuMultipleClonerOptions* options = nullptr);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuClonerOptions.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuClonerOptions.h
new file mode 100644
index 0000000..e524ca6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuClonerOptions.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/GpuIndicesOptions.h>
+
+namespace faiss {
+namespace gpu {
+
+/// set some options on how to copy to GPU
+struct GpuClonerOptions {
+ /// how should indices be stored on index types that support indices
+ /// (anything but GpuIndexFlat*)?
+ IndicesOptions indicesOptions = INDICES_64_BIT;
+
+ /// is the coarse quantizer in float16?
+ bool useFloat16CoarseQuantizer = false;
+
+ /// for GpuIndexIVFFlat, is storage in float16?
+ /// for GpuIndexIVFPQ, are intermediate calculations in float16?
+ bool useFloat16 = false;
+
+ /// use precomputed tables?
+ bool usePrecomputed = false;
+
+ /// reserve vectors in the invfiles?
+ long reserveVecs = 0;
+
+ /// For GpuIndexFlat, store data in transposed layout?
+ bool storeTransposed = false;
+
+ /// Set verbose options on the index
+ bool verbose = false;
+
+ /// use the cuVS implementation
+#if defined USE_NVIDIA_CUVS
+ bool use_cuvs = true;
+#else
+ bool use_cuvs = false;
+#endif
+
+ /// This flag controls the CPU fallback logic for coarse quantizer
+ /// component of the index. When set to false (default), the cloner will
+ /// throw an exception for indices not implemented on GPU. When set to
+ /// true, it will fallback to a CPU implementation.
+ bool allowCpuCoarseQuantizer = false;
+};
+
+struct GpuMultipleClonerOptions : public GpuClonerOptions {
+ /// Whether to shard the index across GPUs, versus replication
+ /// across GPUs
+ bool shard = false;
+
+ /// IndexIVF::copy_subset_to subset type
+ int shard_type = 1;
+
+ /// set to true if an IndexIVF is to be dispatched to multiple GPUs with a
+ /// single common IVF quantizer, ie. only the inverted lists are sharded on
+ /// the sub-indexes (uses an IndexShardsIVF)
+ bool common_ivf_quantizer = false;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuDistance.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuDistance.cu
new file mode 100644
index 0000000..c82c73e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuDistance.cu
@@ -0,0 +1,599 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/GpuDistance.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/gpu/impl/Distance.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <optional>
+
+#if defined USE_NVIDIA_CUVS
+#include <cuvs/neighbors/brute_force.hpp>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <raft/core/device_mdspan.hpp>
+#include <raft/core/device_resources.hpp>
+#include <raft/core/error.hpp>
+#include <raft/core/mdspan_types.hpp>
+#include <raft/core/operators.hpp>
+#include <raft/core/temporary_device_buffer.hpp>
+#include <raft/linalg/unary_op.cuh>
+#include <raft/neighbors/brute_force.cuh>
+#endif
+
+namespace faiss {
+namespace gpu {
+
+bool should_use_cuvs(GpuDistanceParams args) {
+ int dev = args.device >= 0 ? args.device : getCurrentDevice();
+ auto prop = getDeviceProperties(dev);
+
+ if (prop.major < 7)
+ return false;
+
+ return args.use_cuvs;
+}
+
+template <typename T>
+void bfKnnConvert(GpuResourcesProvider* prov, const GpuDistanceParams& args) {
+ // Validate the input data
+ FAISS_THROW_IF_NOT_MSG(
+ args.k > 0 || args.k == -1,
+ "bfKnn: k must be > 0 for top-k reduction, "
+ "or -1 for all pairwise distances");
+ FAISS_THROW_IF_NOT_MSG(args.dims > 0, "bfKnn: dims must be > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.numVectors > 0, "bfKnn: numVectors must be > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.vectors, "bfKnn: vectors must be provided (passed null)");
+ FAISS_THROW_IF_NOT_MSG(
+ args.numQueries > 0, "bfKnn: numQueries must be > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.queries, "bfKnn: queries must be provided (passed null)");
+ FAISS_THROW_IF_NOT_MSG(
+ args.outDistances,
+ "bfKnn: outDistances must be provided (passed null)");
+ FAISS_THROW_IF_NOT_MSG(
+ args.outIndices || args.k == -1,
+ "bfKnn: outIndices must be provided (passed null)");
+
+ // If the user specified a device, then ensure that it is currently set
+ int device = -1;
+ if (args.device == -1) {
+ // Original behavior if no device is specified, use the current CUDA
+ // thread local device
+ device = getCurrentDevice();
+ } else {
+ // Otherwise, use the device specified in `args`
+ device = args.device;
+
+ FAISS_THROW_IF_NOT_FMT(
+ device >= 0 && device < getNumDevices(),
+ "bfKnn: device specified must be -1 (current CUDA thread local device) "
+ "or within the range [0, %d)",
+ getNumDevices());
+ }
+
+ DeviceScope scope(device);
+
+ // Don't let the resources go out of scope
+ auto resImpl = prov->getResources();
+ auto res = resImpl.get();
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ auto tVectors = toDeviceTemporary<T, 2>(
+ res,
+ device,
+ const_cast<T*>(reinterpret_cast<const T*>(args.vectors)),
+ stream,
+ {args.vectorsRowMajor ? args.numVectors : args.dims,
+ args.vectorsRowMajor ? args.dims : args.numVectors});
+ auto tQueries = toDeviceTemporary<T, 2>(
+ res,
+ device,
+ const_cast<T*>(reinterpret_cast<const T*>(args.queries)),
+ stream,
+ {args.queriesRowMajor ? args.numQueries : args.dims,
+ args.queriesRowMajor ? args.dims : args.numQueries});
+
+ DeviceTensor<float, 1, true> tVectorNorms;
+ if (args.vectorNorms) {
+ tVectorNorms = toDeviceTemporary<float, 1>(
+ res,
+ device,
+ const_cast<float*>(args.vectorNorms),
+ stream,
+ {args.numVectors});
+ }
+
+ auto tOutDistances = toDeviceTemporary<float, 2>(
+ res,
+ device,
+ args.outDistances,
+ stream,
+ {args.numQueries, args.k == -1 ? args.numVectors : args.k});
+
+ if (args.k == -1) {
+ // Reporting all pairwise distances
+ allPairwiseDistanceOnDevice<T>(
+ res,
+ device,
+ stream,
+ tVectors,
+ args.vectorsRowMajor,
+ args.vectorNorms ? &tVectorNorms : nullptr,
+ tQueries,
+ args.queriesRowMajor,
+ args.metric,
+ args.metricArg,
+ tOutDistances);
+ } else if (args.outIndicesType == IndicesDataType::I64) {
+ auto tOutIndices = toDeviceTemporary<idx_t, 2>(
+ res,
+ device,
+ (idx_t*)args.outIndices,
+ stream,
+ {args.numQueries, args.k});
+
+ // Since we've guaranteed that all arguments are on device, call the
+ // implementation
+ bfKnnOnDevice<T>(
+ res,
+ device,
+ stream,
+ tVectors,
+ args.vectorsRowMajor,
+ args.vectorNorms ? &tVectorNorms : nullptr,
+ tQueries,
+ args.queriesRowMajor,
+ args.k,
+ args.metric,
+ args.metricArg,
+ tOutDistances,
+ tOutIndices,
+ args.ignoreOutDistances);
+
+ fromDevice<idx_t, 2>(tOutIndices, (idx_t*)args.outIndices, stream);
+
+ } else if (args.outIndicesType == IndicesDataType::I32) {
+ // The brute-force API supports i64 indices, but our output buffer is
+ // i32 so we need to temporarily allocate and then convert back to i32
+ // FIXME: convert to int32_t everywhere?
+ static_assert(sizeof(int) == 4, "");
+ DeviceTensor<idx_t, 2, true> tIntIndices(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {args.numQueries, args.k});
+
+ // Since we've guaranteed that all arguments are on device, call the
+ // implementation
+ bfKnnOnDevice<T>(
+ res,
+ device,
+ stream,
+ tVectors,
+ args.vectorsRowMajor,
+ args.vectorNorms ? &tVectorNorms : nullptr,
+ tQueries,
+ args.queriesRowMajor,
+ args.k,
+ args.metric,
+ args.metricArg,
+ tOutDistances,
+ tIntIndices,
+ args.ignoreOutDistances);
+ // Convert and copy int indices out
+ auto tOutIntIndices = toDeviceTemporary<int, 2>(
+ res,
+ device,
+ (int*)args.outIndices,
+ stream,
+ {args.numQueries, args.k});
+
+ convertTensor<idx_t, int, 2>(stream, tIntIndices, tOutIntIndices);
+
+ // Copy back if necessary
+ fromDevice<int, 2>(tOutIntIndices, (int*)args.outIndices, stream);
+ } else {
+ FAISS_THROW_MSG("unknown outIndicesType");
+ }
+
+ // Copy distances back if necessary
+ fromDevice<float, 2>(tOutDistances, args.outDistances, stream);
+}
+
+void bfKnn(GpuResourcesProvider* prov, const GpuDistanceParams& args) {
+ // For now, both vectors and queries must be of the same data type
+ FAISS_THROW_IF_NOT_MSG(
+ args.vectorType == args.queryType,
+ "limitation: both vectorType and queryType must currently "
+ "be the same (F32 / F16 / BF16");
+
+#if defined USE_NVIDIA_CUVS
+ // Note: For now, cuVS bfknn requires queries and vectors to be same layout
+ if (should_use_cuvs(args) && args.queriesRowMajor == args.vectorsRowMajor &&
+ args.outIndicesType == IndicesDataType::I64 &&
+ args.vectorType == DistanceDataType::F32 && args.k > 0) {
+ cuvsDistanceType distance = metricFaissToCuvs(args.metric, false);
+
+ auto resImpl = prov->getResources();
+ auto res = resImpl.get();
+ // If the user specified a device, then ensure that it is currently set
+ int device = -1;
+ if (args.device == -1) {
+ // Original behavior if no device is specified, use the current CUDA
+ // thread local device
+ device = getCurrentDevice();
+ } else {
+ // Otherwise, use the device specified in `args`
+ device = args.device;
+
+ FAISS_THROW_IF_NOT_FMT(
+ device >= 0 && device < getNumDevices(),
+ "bfKnn: device specified must be -1 (current CUDA thread local device) "
+ "or within the range [0, %d)",
+ getNumDevices());
+ }
+
+ DeviceScope scope(device);
+ raft::device_resources& handle = res->getRaftHandleCurrentDevice();
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ int64_t dims = args.dims;
+ int64_t num_vectors = args.numVectors;
+ int64_t num_queries = args.numQueries;
+ int k = args.k;
+ float metric_arg = args.metricArg;
+
+ auto inds =
+ raft::make_writeback_temporary_device_buffer<idx_t, int64_t>(
+ handle,
+ reinterpret_cast<idx_t*>(args.outIndices),
+ raft::matrix_extent<int64_t>(num_queries, (int64_t)k));
+ auto dists =
+ raft::make_writeback_temporary_device_buffer<float, int64_t>(
+ handle,
+ reinterpret_cast<float*>(args.outDistances),
+ raft::matrix_extent<int64_t>(num_queries, (int64_t)k));
+
+ if (args.queriesRowMajor) {
+ auto index = raft::make_readonly_temporary_device_buffer<
+ const float,
+ int64_t,
+ raft::row_major>(
+ handle,
+ const_cast<float*>(
+ reinterpret_cast<const float*>(args.vectors)),
+ raft::matrix_extent<int64_t>(num_vectors, dims));
+
+ auto search = raft::make_readonly_temporary_device_buffer<
+ const float,
+ int64_t,
+ raft::row_major>(
+ handle,
+ const_cast<float*>(
+ reinterpret_cast<const float*>(args.queries)),
+ raft::matrix_extent<int64_t>(num_queries, dims));
+
+ // get device_vector_view to the precalculate norms if available
+ std::optional<raft::temporary_device_buffer<
+ const float,
+ raft::vector_extent<int64_t>>>
+ norms;
+ std::optional<raft::device_vector_view<const float, int64_t>>
+ norms_view;
+ if (args.vectorNorms) {
+ norms = raft::make_readonly_temporary_device_buffer<
+ const float,
+ int64_t>(
+ handle,
+ args.vectorNorms,
+ raft::vector_extent<int64_t>(num_queries));
+ norms_view = norms->view();
+ }
+
+ cuvs::neighbors::brute_force::index<float> idx(
+ handle, index.view(), norms_view, distance, metric_arg);
+ cuvs::neighbors::brute_force::search(
+ handle, idx, search.view(), inds.view(), dists.view());
+ } else {
+ auto index = raft::make_readonly_temporary_device_buffer<
+ const float,
+ int64_t,
+ raft::col_major>(
+ handle,
+ const_cast<float*>(
+ reinterpret_cast<const float*>(args.vectors)),
+ raft::matrix_extent<int64_t>(num_vectors, dims));
+
+ auto search = raft::make_readonly_temporary_device_buffer<
+ const float,
+ int64_t,
+ raft::col_major>(
+ handle,
+ const_cast<float*>(
+ reinterpret_cast<const float*>(args.queries)),
+ raft::matrix_extent<int64_t>(num_queries, dims));
+
+ std::optional<raft::temporary_device_buffer<
+ const float,
+ raft::vector_extent<int64_t>>>
+ norms;
+ std::optional<raft::device_vector_view<const float, int64_t>>
+ norms_view;
+ if (args.vectorNorms) {
+ norms = raft::make_readonly_temporary_device_buffer<
+ const float,
+ int64_t>(
+ handle,
+ args.vectorNorms,
+ raft::vector_extent<int64_t>(num_queries));
+ norms_view = norms->view();
+ }
+
+ cuvs::neighbors::brute_force::index<float> idx(
+ handle, index.view(), norms_view, distance, metric_arg);
+ cuvs::neighbors::brute_force::search(
+ handle, idx, search.view(), inds.view(), dists.view());
+ }
+
+ if (args.metric == MetricType::METRIC_Lp) {
+ raft::linalg::unary_op(
+ handle,
+ raft::make_const_mdspan(dists.view()),
+ dists.view(),
+ [metric_arg] __device__(const float& a) {
+ return powf(a, metric_arg);
+ });
+ } else if (args.metric == MetricType::METRIC_JensenShannon) {
+ raft::linalg::unary_op(
+ handle,
+ raft::make_const_mdspan(dists.view()),
+ dists.view(),
+ [] __device__(const float& a) { return powf(a, 2); });
+ }
+
+ handle.sync_stream();
+ } else
+#else
+ if (should_use_cuvs(args)) {
+ FAISS_THROW_IF_NOT_MSG(
+ !should_use_cuvs(args),
+ "cuVS has not been compiled into the current version so it cannot be used.");
+ } else
+#endif
+ if (args.vectorType == DistanceDataType::F32) {
+ bfKnnConvert<float>(prov, args);
+ } else if (args.vectorType == DistanceDataType::F16) {
+ bfKnnConvert<half>(prov, args);
+ } else if (args.vectorType == DistanceDataType::BF16) {
+ if (prov->getResources()->supportsBFloat16CurrentDevice()) {
+ bfKnnConvert<__nv_bfloat16>(prov, args);
+ } else {
+ FAISS_THROW_MSG("not compiled with bfloat16 support");
+ }
+ } else {
+ FAISS_THROW_MSG("unknown vectorType");
+ }
+}
+
+template <class C>
+void bfKnn_shard_database(
+ GpuResourcesProvider* prov,
+ const GpuDistanceParams& args,
+ size_t shard_size,
+ size_t distance_size) {
+ std::vector<typename C::T> heaps_distances;
+ if (args.ignoreOutDistances) {
+ heaps_distances.resize(args.numQueries * args.k, 0);
+ }
+ HeapArray<C> heaps = {
+ (size_t)args.numQueries,
+ (size_t)args.k,
+ (typename C::TI*)args.outIndices,
+ args.ignoreOutDistances ? heaps_distances.data()
+ : args.outDistances};
+ heaps.heapify();
+ std::vector<typename C::TI> labels(args.numQueries * args.k);
+ std::vector<typename C::T> distances(args.numQueries * args.k);
+ GpuDistanceParams args_batch = args;
+ args_batch.outDistances = distances.data();
+ args_batch.ignoreOutDistances = false;
+ args_batch.outIndices = labels.data();
+ for (idx_t i = 0; i < args.numVectors; i += shard_size) {
+ args_batch.numVectors = min(shard_size, args.numVectors - i);
+ args_batch.vectors =
+ (char*)args.vectors + distance_size * args.dims * i;
+ args_batch.vectorNorms =
+ args.vectorNorms ? args.vectorNorms + i : nullptr;
+ bfKnn(prov, args_batch);
+ for (auto& label : labels) {
+ label += i;
+ }
+ heaps.addn_with_ids(args.k, distances.data(), labels.data(), args.k);
+ }
+ heaps.reorder();
+}
+
+void bfKnn_single_query_shard(
+ GpuResourcesProvider* prov,
+ const GpuDistanceParams& args,
+ size_t vectorsMemoryLimit) {
+ if (vectorsMemoryLimit == 0) {
+ bfKnn(prov, args);
+ return;
+ }
+ FAISS_THROW_IF_NOT_MSG(
+ args.numVectors > 0, "bfKnn_tiling: numVectors must be > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.vectors,
+ "bfKnn_tiling: vectors must be provided (passed null)");
+ FAISS_THROW_IF_NOT_MSG(
+ getDeviceForAddress(args.vectors) == -1,
+ "bfKnn_tiling: vectors should be in CPU memory when vectorsMemoryLimit > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.vectorsRowMajor,
+ "bfKnn_tiling: tiling vectors is only supported in row major mode");
+ FAISS_THROW_IF_NOT_MSG(
+ args.k > 0,
+ "bfKnn_tiling: tiling vectors is only supported for k > 0");
+ size_t distance_size = args.vectorType == DistanceDataType::F32 ? 4
+ : (args.vectorType == DistanceDataType::F16 ||
+ args.vectorType == DistanceDataType::BF16)
+ ? 2
+ : 0;
+ FAISS_THROW_IF_NOT_MSG(
+ distance_size > 0, "bfKnn_tiling: unknown vectorType");
+ size_t shard_size = vectorsMemoryLimit / (args.dims * distance_size);
+ FAISS_THROW_IF_NOT_MSG(
+ shard_size > 0, "bfKnn_tiling: vectorsMemoryLimit is too low");
+ if (args.numVectors <= shard_size) {
+ bfKnn(prov, args);
+ return;
+ }
+ if (is_similarity_metric(args.metric)) {
+ if (args.outIndicesType == IndicesDataType::I64) {
+ bfKnn_shard_database<CMin<float, int64_t>>(
+ prov, args, shard_size, distance_size);
+ } else if (args.outIndicesType == IndicesDataType::I32) {
+ bfKnn_shard_database<CMin<float, int32_t>>(
+ prov, args, shard_size, distance_size);
+ } else {
+ FAISS_THROW_MSG("bfKnn_tiling: unknown outIndicesType");
+ }
+ } else {
+ if (args.outIndicesType == IndicesDataType::I64) {
+ bfKnn_shard_database<CMax<float, int64_t>>(
+ prov, args, shard_size, distance_size);
+ } else if (args.outIndicesType == IndicesDataType::I32) {
+ bfKnn_shard_database<CMax<float, int32_t>>(
+ prov, args, shard_size, distance_size);
+ } else {
+ FAISS_THROW_MSG("bfKnn_tiling: unknown outIndicesType");
+ }
+ }
+}
+
+void bfKnn_tiling(
+ GpuResourcesProvider* prov,
+ const GpuDistanceParams& args,
+ size_t vectorsMemoryLimit,
+ size_t queriesMemoryLimit) {
+ if (queriesMemoryLimit == 0) {
+ bfKnn_single_query_shard(prov, args, vectorsMemoryLimit);
+ return;
+ }
+ FAISS_THROW_IF_NOT_MSG(
+ args.numQueries > 0, "bfKnn_tiling: numQueries must be > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.queries,
+ "bfKnn_tiling: queries must be provided (passed null)");
+ FAISS_THROW_IF_NOT_MSG(
+ getDeviceForAddress(args.queries) == -1,
+ "bfKnn_tiling: queries should be in CPU memory when queriesMemoryLimit > 0");
+ FAISS_THROW_IF_NOT_MSG(
+ args.queriesRowMajor,
+ "bfKnn_tiling: tiling queries is only supported in row major mode");
+ FAISS_THROW_IF_NOT_MSG(
+ args.k > 0,
+ "bfKnn_tiling: tiling queries is only supported for k > 0");
+ size_t distance_size = args.queryType == DistanceDataType::F32 ? 4
+ : (args.queryType == DistanceDataType::F16 ||
+ args.queryType == DistanceDataType::BF16)
+ ? 2
+ : 0;
+ FAISS_THROW_IF_NOT_MSG(
+ distance_size > 0, "bfKnn_tiling: unknown queryType");
+ size_t label_size = args.outIndicesType == IndicesDataType::I64 ? 8
+ : args.outIndicesType == IndicesDataType::I32 ? 4
+ : 0;
+ FAISS_THROW_IF_NOT_MSG(
+ distance_size > 0, "bfKnn_tiling: unknown outIndicesType");
+ size_t shard_size = queriesMemoryLimit /
+ (args.k * (distance_size + label_size) + args.dims * distance_size);
+ FAISS_THROW_IF_NOT_MSG(
+ shard_size > 0, "bfKnn_tiling: queriesMemoryLimit is too low");
+ FAISS_THROW_IF_NOT_MSG(
+ args.outIndices,
+ "bfKnn: outIndices must be provided (passed null)");
+ for (idx_t i = 0; i < args.numQueries; i += shard_size) {
+ GpuDistanceParams args_batch = args;
+ args_batch.numQueries = min(shard_size, args.numQueries - i);
+ args_batch.queries =
+ (char*)args.queries + distance_size * args.dims * i;
+ if (!args_batch.ignoreOutDistances) {
+ args_batch.outDistances = args.outDistances + args.k * i;
+ }
+ args_batch.outIndices =
+ (char*)args.outIndices + args.k * label_size * i;
+ bfKnn_single_query_shard(prov, args_batch, vectorsMemoryLimit);
+ }
+}
+
+// legacy version
+void bruteForceKnn(
+ GpuResourcesProvider* res,
+ faiss::MetricType metric,
+ // A region of memory size numVectors x dims, with dims
+ // innermost
+ const float* vectors,
+ bool vectorsRowMajor,
+ idx_t numVectors,
+ // A region of memory size numQueries x dims, with dims
+ // innermost
+ const float* queries,
+ bool queriesRowMajor,
+ idx_t numQueries,
+ int dims,
+ int k,
+ // A region of memory size numQueries x k, with k
+ // innermost
+ float* outDistances,
+ // A region of memory size numQueries x k, with k
+ // innermost
+ idx_t* outIndices) {
+ std::cerr << "bruteForceKnn is deprecated; call bfKnn instead" << std::endl;
+
+ GpuDistanceParams args;
+ args.metric = metric;
+ args.k = k;
+ args.dims = dims;
+ args.vectors = vectors;
+ args.vectorsRowMajor = vectorsRowMajor;
+ args.numVectors = numVectors;
+ args.queries = queries;
+ args.queriesRowMajor = queriesRowMajor;
+ args.numQueries = numQueries;
+ args.outDistances = outDistances;
+ args.outIndices = outIndices;
+
+ bfKnn(res, args);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuDistance.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuDistance.h
new file mode 100644
index 0000000..e4daf5e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuDistance.h
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+
+#pragma GCC visibility push(default)
+namespace faiss {
+namespace gpu {
+
+class GpuResourcesProvider;
+
+// Scalar type of the vector data
+enum class DistanceDataType {
+ F32 = 1,
+ F16,
+ BF16,
+};
+
+// Scalar type of the indices data
+enum class IndicesDataType {
+ I64 = 1,
+ I32,
+};
+
+/// Arguments to brute-force GPU k-nearest neighbor searching
+struct GpuDistanceParams {
+ //
+ // Search parameters
+ //
+
+ /// Search parameter: distance metric
+ faiss::MetricType metric = METRIC_L2;
+
+ /// Search parameter: distance metric argument (if applicable)
+ /// For metric == METRIC_Lp, this is the p-value
+ float metricArg = 0;
+
+ /// Search parameter: return k nearest neighbors
+ /// If the value provided is -1, then we report all pairwise distances
+ /// without top-k filtering
+ int k = 0;
+
+ /// Vector dimensionality
+ int dims = 0;
+
+ //
+ // Vectors being queried
+ //
+
+ /// If vectorsRowMajor is true, this is
+ /// numVectors x dims, with dims innermost; otherwise,
+ /// dims x numVectors, with numVectors innermost
+ const void* vectors = nullptr;
+ DistanceDataType vectorType = DistanceDataType::F32;
+ bool vectorsRowMajor = true;
+ idx_t numVectors = 0;
+
+ /// Precomputed L2 norms for each vector in `vectors`, which can be
+ /// optionally provided in advance to speed computation for METRIC_L2
+ const float* vectorNorms = nullptr;
+
+ //
+ // The query vectors (i.e., find k-nearest neighbors in `vectors` for each
+ // of the `queries`
+ //
+
+ /// If queriesRowMajor is true, this is
+ /// numQueries x dims, with dims innermost; otherwise,
+ /// dims x numQueries, with numQueries innermost
+ const void* queries = nullptr;
+ DistanceDataType queryType = DistanceDataType::F32;
+ bool queriesRowMajor = true;
+ idx_t numQueries = 0;
+
+ //
+ // Output results
+ //
+
+ /// A region of memory size numQueries x k, with k
+ /// innermost (row major) if k > 0, or if k == -1, a region of memory of
+ /// size numQueries x numVectors
+ float* outDistances = nullptr;
+
+ /// Do we only care about the indices reported, rather than the output
+ /// distances? Not used if k == -1 (all pairwise distances)
+ bool ignoreOutDistances = false;
+
+ /// A region of memory size numQueries x k, with k
+ /// innermost (row major). Not used if k == -1 (all pairwise distances)
+ IndicesDataType outIndicesType = IndicesDataType::I64;
+ void* outIndices = nullptr;
+
+ //
+ // Execution information
+ //
+
+ /// On which GPU device should the search run?
+ /// -1 indicates that the current CUDA thread-local device
+ /// (via cudaGetDevice/cudaSetDevice) is used
+ /// Otherwise, an integer 0 <= device < numDevices indicates the device for
+ /// execution
+ int device = -1;
+
+ /// Should the index dispatch down to cuVS?
+#if defined USE_NVIDIA_CUVS
+ bool use_cuvs = true;
+#else
+ bool use_cuvs = false;
+#endif
+};
+
+/// A function that determines whether cuVS should be used based on various
+/// conditions (such as unsupported architecture)
+bool should_use_cuvs(GpuDistanceParams args);
+
+/// A wrapper for gpu/impl/Distance.cuh to expose direct brute-force k-nearest
+/// neighbor searches on an externally-provided region of memory (e.g., from a
+/// pytorch tensor).
+/// The data (vectors, queries, outDistances, outIndices) can be resident on the
+/// GPU or the CPU, but all calculations are performed on the GPU. If the result
+/// buffers are on the CPU, results will be copied back when done.
+///
+/// All GPU computation is performed on the current CUDA device, and ordered
+/// with respect to resources->getDefaultStreamCurrentDevice().
+///
+/// For each vector in `queries`, searches all of `vectors` to find its k
+/// nearest neighbors with respect to the given metric
+void bfKnn(GpuResourcesProvider* resources, const GpuDistanceParams& args);
+
+// bfKnn which takes two extra parameters to control the maximum GPU
+// memory allowed for vectors and queries, the latter including the
+// memory required for the results.
+// If 0, the corresponding input must fit into GPU memory.
+// If greater than 0, the function will use at most this much GPU
+// memory (in bytes) for vectors and queries respectively.
+// Vectors are broken up into chunks of size vectorsMemoryLimit,
+// and queries are broken up into chunks of size queriesMemoryLimit.
+// The tiles resulting from the product of the query and vector
+// chunks are processed sequentially on the GPU.
+// Only supported for row major matrices and k > 0. The input that
+// needs sharding must reside on the CPU.
+void bfKnn_tiling(
+ GpuResourcesProvider* resources,
+ const GpuDistanceParams& args,
+ size_t vectorsMemoryLimit,
+ size_t queriesMemoryLimit);
+
+/// Deprecated legacy implementation
+void bruteForceKnn(
+ GpuResourcesProvider* resources,
+ faiss::MetricType metric,
+ // If vectorsRowMajor is true, this is
+ // numVectors x dims, with dims innermost; otherwise,
+ // dims x numVectors, with numVectors innermost
+ const float* vectors,
+ bool vectorsRowMajor,
+ idx_t numVectors,
+ // If queriesRowMajor is true, this is
+ // numQueries x dims, with dims innermost; otherwise,
+ // dims x numQueries, with numQueries innermost
+ const float* queries,
+ bool queriesRowMajor,
+ idx_t numQueries,
+ int dims,
+ int k,
+ // A region of memory size numQueries x k, with k
+ // innermost (row major)
+ float* outDistances,
+ // A region of memory size numQueries x k, with k
+ // innermost (row major)
+ idx_t* outIndices);
+
+} // namespace gpu
+} // namespace faiss
+#pragma GCC visibility pop
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuFaissAssert.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuFaissAssert.h
new file mode 100644
index 0000000..d17f98c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuFaissAssert.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef GPU_FAISS_ASSERT_INCLUDED
+#define GPU_FAISS_ASSERT_INCLUDED
+
+#include <cuda.h>
+#include <faiss/impl/FaissAssert.h>
+
+///
+/// Assertions
+///
+
+#if defined(__CUDA_ARCH__) || defined(USE_AMD_ROCM)
+#define GPU_FAISS_ASSERT(X) assert(X)
+#define GPU_FAISS_ASSERT_MSG(X, MSG) assert(X)
+#define GPU_FAISS_ASSERT_FMT(X, FMT, ...) assert(X)
+#else
+#define GPU_FAISS_ASSERT(X) FAISS_ASSERT(X)
+#define GPU_FAISS_ASSERT_MSG(X, MSG) FAISS_ASSERT_MSG(X, MSG)
+#define GPU_FAISS_ASSERT_FMT(X, FMT, ...) FAISS_ASSERT_FMT(X, FMT, __VA_ARGS)
+#endif // __CUDA_ARCH__
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIcmEncoder.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIcmEncoder.cu
new file mode 100644
index 0000000..999dd99
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIcmEncoder.cu
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuIcmEncoder.h>
+
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/utils/WorkerThread.h>
+#include <faiss/gpu/impl/IcmEncoder.cuh>
+
+#include <algorithm>
+
+namespace faiss {
+namespace gpu {
+
+///< A helper structure to support multi-GPU
+struct IcmEncoderShards {
+ std::vector<std::pair<
+ std::unique_ptr<IcmEncoderImpl>,
+ std::unique_ptr<WorkerThread>>>
+ workers;
+
+ void add(IcmEncoderImpl* encoder) {
+ workers.emplace_back(std::make_pair(
+ std::unique_ptr<IcmEncoderImpl>(encoder),
+ std::unique_ptr<WorkerThread>(new WorkerThread)));
+ }
+
+ IcmEncoderImpl* at(int idx) {
+ return workers[idx].first.get();
+ }
+
+ ///< call f(idx, encoder) for each encoder
+ void runOnShards(std::function<void(int, IcmEncoderImpl*)> f) {
+ std::vector<std::future<bool>> v;
+
+ for (int i = 0; i < this->workers.size(); ++i) {
+ auto& p = this->workers[i];
+ auto encoder = p.first.get();
+ v.emplace_back(p.second->add([f, i, encoder]() { f(i, encoder); }));
+ }
+
+ for (int i = 0; i < v.size(); ++i) {
+ auto& fut = v[i];
+ fut.get(); // no exception handle, crash if any thread down
+ }
+ }
+
+ size_t size() {
+ return workers.size();
+ }
+};
+
+GpuIcmEncoder::GpuIcmEncoder(
+ const LocalSearchQuantizer* lsq,
+ const std::vector<GpuResourcesProvider*>& provs,
+ const std::vector<int>& devices)
+ : lsq::IcmEncoder(lsq), shards(new IcmEncoderShards()) {
+ // create an IcmEncoderImpl instance for each device.
+ for (size_t i = 0; i < provs.size(); i++) {
+ shards->add(new IcmEncoderImpl(
+ lsq->M, lsq->K, lsq->d, provs[i], devices[i]));
+ }
+}
+
+GpuIcmEncoder::~GpuIcmEncoder() {}
+
+void GpuIcmEncoder::set_binary_term() {
+ auto fn = [=](int idx, IcmEncoderImpl* encoder) {
+ encoder->setBinaryTerm(lsq->codebooks.data());
+ };
+ shards->runOnShards(fn);
+}
+
+void GpuIcmEncoder::encode(
+ int32_t* codes,
+ const float* x,
+ std::mt19937& gen,
+ size_t n,
+ size_t ils_iters) const {
+ size_t nshards = shards->size();
+ size_t base_shard_size = n / nshards;
+
+ auto codebooks = lsq->codebooks.data();
+ auto M = lsq->M;
+ auto d = lsq->d;
+ auto nperts = lsq->nperts;
+ auto icm_iters = lsq->icm_iters;
+
+ auto seed = gen();
+
+ // split input data
+ auto fn = [=](int idx, IcmEncoderImpl* encoder) {
+ size_t i0 = idx * base_shard_size + std::min(size_t(idx), n % nshards);
+ size_t ni = base_shard_size;
+ if (ni < n % nshards) {
+ ++ni;
+ }
+ if (ni <= 0) { // only if n < nshards
+ return;
+ }
+ auto xi = x + i0 * d;
+ auto ci = codes + i0 * M;
+ std::mt19937 geni(idx + seed); // different seed for each shard
+ encoder->encode(
+ ci, xi, codebooks, geni, ni, nperts, ils_iters, icm_iters);
+ };
+ shards->runOnShards(fn);
+}
+
+GpuIcmEncoderFactory::GpuIcmEncoderFactory(int ngpus) {
+ for (int i = 0; i < ngpus; i++) {
+ provs.push_back(new StandardGpuResources());
+ devices.push_back(i);
+ }
+}
+
+lsq::IcmEncoder* GpuIcmEncoderFactory::get(const LocalSearchQuantizer* lsq) {
+ return new GpuIcmEncoder(lsq, provs, devices);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIcmEncoder.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIcmEncoder.h
new file mode 100644
index 0000000..5bf13a2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIcmEncoder.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/LocalSearchQuantizer.h>
+
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResourcesProvider;
+struct IcmEncoderShards;
+
+/** Perform LSQ encoding on GPU.
+ *
+ * Split input vectors to different devices and call IcmEncoderImpl::encode
+ * to encode them
+ */
+class GpuIcmEncoder : public lsq::IcmEncoder {
+ public:
+ GpuIcmEncoder(
+ const LocalSearchQuantizer* lsq,
+ const std::vector<GpuResourcesProvider*>& provs,
+ const std::vector<int>& devices);
+
+ ~GpuIcmEncoder();
+
+ GpuIcmEncoder(const GpuIcmEncoder&) = delete;
+ GpuIcmEncoder& operator=(const GpuIcmEncoder&) = delete;
+
+ void set_binary_term() override;
+
+ void encode(
+ int32_t* codes,
+ const float* x,
+ std::mt19937& gen,
+ size_t n,
+ size_t ils_iters) const override;
+
+ private:
+ std::unique_ptr<IcmEncoderShards> shards;
+};
+
+struct GpuIcmEncoderFactory : public lsq::IcmEncoderFactory {
+ explicit GpuIcmEncoderFactory(int ngpus = 1);
+
+ lsq::IcmEncoder* get(const LocalSearchQuantizer* lsq) override;
+
+ std::vector<GpuResourcesProvider*> provs;
+ std::vector<int> devices;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndex.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndex.cu
new file mode 100644
index 0000000..033cb9a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndex.cu
@@ -0,0 +1,548 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+
+#include <algorithm>
+#include <limits>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+/// Default CPU search size for which we use paged copies
+constexpr idx_t kMinPageSize = (idx_t)256 * 1024 * 1024;
+
+/// Size above which we page copies from the CPU to GPU (non-paged
+/// memory usage)
+constexpr idx_t kNonPinnedPageSize = (idx_t)256 * 1024 * 1024;
+
+// Default size for which we page add or search
+constexpr idx_t kAddPageSize = (idx_t)256 * 1024 * 1024;
+
+// Or, maximum number of vectors to consider per page of add or search
+constexpr idx_t kAddVecSize = (idx_t)512 * 1024;
+
+// Use a smaller search size, as precomputed code usage on IVFPQ
+// requires substantial amounts of memory
+// FIXME: parameterize based on algorithm need
+constexpr idx_t kSearchVecSize = (idx_t)32 * 1024;
+
+bool should_use_cuvs(GpuIndexConfig config_) {
+ auto prop = getDeviceProperties(config_.device);
+
+ if (prop.major < 7)
+ return false;
+
+ return config_.use_cuvs;
+}
+
+GpuIndex::GpuIndex(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ faiss::MetricType metric,
+ float metricArg,
+ GpuIndexConfig config)
+ : Index(dims, metric),
+ resources_(resources),
+ config_(config),
+ minPagedSize_(kMinPageSize) {
+ FAISS_THROW_IF_NOT_FMT(
+ config_.device < getNumDevices(),
+ "Invalid GPU device %d",
+ config_.device);
+
+ FAISS_THROW_IF_NOT_MSG(dims > 0, "Invalid number of dimensions");
+
+ FAISS_THROW_IF_NOT_FMT(
+ config_.memorySpace == MemorySpace::Device ||
+ (config_.memorySpace == MemorySpace::Unified &&
+ getFullUnifiedMemSupport(config_.device)),
+ "Device %d does not support full CUDA 8 Unified Memory (CC 6.0+)",
+ config_.device);
+
+ metric_arg = metricArg;
+
+ FAISS_ASSERT((bool)resources_);
+ resources_->initializeForDevice(config_.device);
+}
+
+int GpuIndex::getDevice() const {
+ return config_.device;
+}
+
+void GpuIndex::copyFrom(const faiss::Index* index) {
+ d = index->d;
+ metric_type = index->metric_type;
+ metric_arg = index->metric_arg;
+ ntotal = index->ntotal;
+ is_trained = index->is_trained;
+}
+
+void GpuIndex::copyTo(faiss::Index* index) const {
+ index->d = d;
+ index->metric_type = metric_type;
+ index->metric_arg = metric_arg;
+ index->ntotal = ntotal;
+ index->is_trained = is_trained;
+}
+
+void GpuIndex::setMinPagingSize(size_t size) {
+ minPagedSize_ = size;
+}
+
+size_t GpuIndex::getMinPagingSize() const {
+ return minPagedSize_;
+}
+
+void GpuIndex::add(idx_t n, const float* x) {
+ // Pass to add_with_ids
+ add_with_ids(n, x, nullptr);
+}
+
+void GpuIndex::add_with_ids(idx_t n, const float* x, const idx_t* ids) {
+ DeviceScope scope(config_.device);
+ FAISS_THROW_IF_NOT_MSG(this->is_trained, "Index not trained");
+
+ if (n == 0) {
+ // nothing to add
+ return;
+ }
+
+ std::vector<idx_t> generatedIds;
+
+ // Generate IDs if we need them
+ if (!ids && addImplRequiresIDs_()) {
+ generatedIds = std::vector<idx_t>(n);
+
+ for (idx_t i = 0; i < n; ++i) {
+ generatedIds[i] = this->ntotal + i;
+ }
+ }
+
+ addPaged_(n, x, ids ? ids : generatedIds.data());
+}
+
+void GpuIndex::addPaged_(idx_t n, const float* x, const idx_t* ids) {
+ if (n > 0) {
+ idx_t totalSize = n * this->d * sizeof(float);
+
+ if (!should_use_cuvs(config_) &&
+ (totalSize > kAddPageSize || n > kAddVecSize)) {
+ // How many vectors fit into kAddPageSize?
+ idx_t maxNumVecsForPageSize =
+ kAddPageSize / (this->d * sizeof(float));
+
+ // Always add at least 1 vector, if we have huge vectors
+ maxNumVecsForPageSize = std::max(maxNumVecsForPageSize, idx_t(1));
+
+ auto tileSize = std::min(n, maxNumVecsForPageSize);
+ tileSize = std::min(tileSize, kSearchVecSize);
+
+ for (idx_t i = 0; i < n; i += tileSize) {
+ auto curNum = std::min(tileSize, n - i);
+
+ addPage_(curNum, x + i * this->d, ids ? ids + i : nullptr);
+ }
+ } else {
+ addPage_(n, x, ids);
+ }
+ }
+}
+
+void GpuIndex::addPage_(idx_t n, const float* x, const idx_t* ids) {
+ // At this point, `x` can be resident on CPU or GPU, and `ids` may be
+ // resident on CPU, GPU or may be null.
+ //
+ // Before continuing, we guarantee that all data will be resident on the
+ // GPU.
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ auto vecs = toDeviceTemporary<float, 2>(
+ resources_.get(),
+ config_.device,
+ const_cast<float*>(x),
+ stream,
+ {n, this->d});
+
+ if (ids) {
+ auto indices = toDeviceTemporary<idx_t, 1>(
+ resources_.get(),
+ config_.device,
+ const_cast<idx_t*>(ids),
+ stream,
+ {n});
+
+ addImpl_(n, vecs.data(), ids ? indices.data() : nullptr);
+ } else {
+ addImpl_(n, vecs.data(), nullptr);
+ }
+}
+
+void GpuIndex::assign(idx_t n, const float* x, idx_t* labels, idx_t k) const {
+ DeviceScope scope(config_.device);
+ FAISS_THROW_IF_NOT_MSG(this->is_trained, "Index not trained");
+
+ validateKSelect(k);
+
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ // We need to create a throw-away buffer for distances, which we don't use
+ // but which we do need for the search call
+ DeviceTensor<float, 2, true> distances(
+ resources_.get(), makeTempAlloc(AllocType::Other, stream), {n, k});
+
+ // Forward to search
+ search(n, x, k, distances.data(), labels);
+}
+
+void GpuIndex::search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ DeviceScope scope(config_.device);
+ FAISS_THROW_IF_NOT_MSG(this->is_trained, "Index not trained");
+
+ validateKSelect(k);
+
+ if (n == 0 || k == 0) {
+ // nothing to search
+ return;
+ }
+
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ // We guarantee that the searchImpl_ will be called with device-resident
+ // pointers.
+
+ // The input vectors may be too large for the GPU, but we still
+ // assume that the output distances and labels are not.
+ // Go ahead and make space for output distances and labels on the
+ // GPU.
+ // If we reach a point where all inputs are too big, we can add
+ // another level of tiling.
+ auto outDistances = toDeviceTemporary<float, 2>(
+ resources_.get(), config_.device, distances, stream, {n, k});
+
+ auto outLabels = toDeviceTemporary<idx_t, 2>(
+ resources_.get(), config_.device, labels, stream, {n, k});
+
+ bool usePaged = false;
+
+ if (getDeviceForAddress(x) == -1) {
+ // It is possible that the user is querying for a vector set size
+ // `x` that won't fit on the GPU.
+ // In this case, we will have to handle paging of the data from CPU
+ // -> GPU.
+ // Currently, we don't handle the case where the output data won't
+ // fit on the GPU (e.g., n * k is too large for the GPU memory).
+ size_t dataSize = (size_t)n * this->d * sizeof(float);
+
+ if (dataSize >= minPagedSize_) {
+ searchFromCpuPaged_(
+ n, x, k, outDistances.data(), outLabels.data(), params);
+ usePaged = true;
+ }
+ }
+
+ if (!usePaged) {
+ searchNonPaged_(n, x, k, outDistances.data(), outLabels.data(), params);
+ }
+
+ // Copy back if necessary
+ fromDevice<float, 2>(outDistances, distances, stream);
+ fromDevice<idx_t, 2>(outLabels, labels, stream);
+}
+
+void GpuIndex::search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params) const {
+ search(n, x, k, distances, labels, params);
+ reconstruct_batch(n * k, labels, recons);
+}
+
+void GpuIndex::searchNonPaged_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* outDistancesData,
+ idx_t* outIndicesData,
+ const SearchParameters* params) const {
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ // Make sure arguments are on the device we desire; use temporary
+ // memory allocations to move it if necessary
+ auto vecs = toDeviceTemporary<float, 2>(
+ resources_.get(),
+ config_.device,
+ const_cast<float*>(x),
+ stream,
+ {n, this->d});
+
+ searchImpl_(n, vecs.data(), k, outDistancesData, outIndicesData, params);
+}
+
+void GpuIndex::searchFromCpuPaged_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* outDistancesData,
+ idx_t* outIndicesData,
+ const SearchParameters* params) const {
+ Tensor<float, 2, true> outDistances(outDistancesData, {n, k});
+ Tensor<idx_t, 2, true> outIndices(outIndicesData, {n, k});
+
+ // Is pinned memory available?
+ auto pinnedAlloc = resources_->getPinnedMemory();
+ idx_t pageSizeInVecs =
+ ((pinnedAlloc.second / 2) / (sizeof(float) * this->d));
+
+ if (!pinnedAlloc.first || pageSizeInVecs < 1) {
+ // Just page without overlapping copy with compute
+ idx_t batchSize = utils::nextHighestPowerOf2(
+ (kNonPinnedPageSize / (sizeof(float) * this->d)));
+
+ for (idx_t cur = 0; cur < n; cur += batchSize) {
+ auto num = std::min(batchSize, n - cur);
+
+ auto outDistancesSlice = outDistances.narrowOutermost(cur, num);
+ auto outIndicesSlice = outIndices.narrowOutermost(cur, num);
+
+ searchNonPaged_(
+ num,
+ x + cur * this->d,
+ k,
+ outDistancesSlice.data(),
+ outIndicesSlice.data(),
+ params);
+ }
+
+ return;
+ }
+
+ //
+ // Pinned memory is available, so we can overlap copy with compute.
+ // We use two pinned memory buffers, and triple-buffer the
+ // procedure:
+ //
+ // 1 CPU copy -> pinned
+ // 2 pinned copy -> GPU
+ // 3 GPU compute
+ //
+ // 1 2 3 1 2 3 ... (pinned buf A)
+ // 1 2 3 1 2 ... (pinned buf B)
+ // 1 2 3 1 ... (pinned buf A)
+ // time ->
+ //
+ auto defaultStream = resources_->getDefaultStream(config_.device);
+ auto copyStream = resources_->getAsyncCopyStream(config_.device);
+
+ float* bufPinnedA = (float*)pinnedAlloc.first;
+ float* bufPinnedB = bufPinnedA + (size_t)pageSizeInVecs * this->d;
+ float* bufPinned[2] = {bufPinnedA, bufPinnedB};
+
+ // Reserve space on the GPU for the destination of the pinned buffer
+ // copy
+ DeviceTensor<float, 2, true> bufGpuA(
+ resources_.get(),
+ makeTempAlloc(AllocType::Other, defaultStream),
+ {pageSizeInVecs, this->d});
+ DeviceTensor<float, 2, true> bufGpuB(
+ resources_.get(),
+ makeTempAlloc(AllocType::Other, defaultStream),
+ {pageSizeInVecs, this->d});
+ DeviceTensor<float, 2, true>* bufGpus[2] = {&bufGpuA, &bufGpuB};
+
+ // Copy completion events for the pinned buffers
+ std::unique_ptr<CudaEvent> eventPinnedCopyDone[2];
+
+ // Execute completion events for the GPU buffers
+ std::unique_ptr<CudaEvent> eventGpuExecuteDone[2];
+
+ // All offsets are in terms of number of vectors
+
+ // Current start offset for buffer 1
+ idx_t cur1 = 0;
+ idx_t cur1BufIndex = 0;
+
+ // Current start offset for buffer 2
+ idx_t cur2 = -1;
+ idx_t cur2BufIndex = 0;
+
+ // Current start offset for buffer 3
+ idx_t cur3 = -1;
+ idx_t cur3BufIndex = 0;
+
+ while (cur3 < n) {
+ // Start async pinned -> GPU copy first (buf 2)
+ if (cur2 != -1 && cur2 < n) {
+ // Copy pinned to GPU
+ auto numToCopy = std::min(pageSizeInVecs, n - cur2);
+
+ // Make sure any previous execution has completed before continuing
+ auto& eventPrev = eventGpuExecuteDone[cur2BufIndex];
+ if (eventPrev.get()) {
+ eventPrev->streamWaitOnEvent(copyStream);
+ }
+
+ CUDA_VERIFY(cudaMemcpyAsync(
+ bufGpus[cur2BufIndex]->data(),
+ bufPinned[cur2BufIndex],
+ numToCopy * this->d * sizeof(float),
+ cudaMemcpyHostToDevice,
+ copyStream));
+
+ // Mark a completion event in this stream
+ eventPinnedCopyDone[cur2BufIndex].reset(new CudaEvent(copyStream));
+
+ // We pick up from here
+ cur3 = cur2;
+ cur2 += numToCopy;
+ cur2BufIndex = (cur2BufIndex == 0) ? 1 : 0;
+ }
+
+ if (cur3 != idx_t(-1) && cur3 < n) {
+ // Process on GPU
+ auto numToProcess = std::min(pageSizeInVecs, n - cur3);
+
+ // Make sure the previous copy has completed before continuing
+ auto& eventPrev = eventPinnedCopyDone[cur3BufIndex];
+ FAISS_ASSERT(eventPrev.get());
+
+ eventPrev->streamWaitOnEvent(defaultStream);
+
+ // Create tensor wrappers
+ // DeviceTensor<float, 2, true> input(bufGpus[cur3BufIndex]->data(),
+ // {numToProcess, this->d});
+ auto outDistancesSlice =
+ outDistances.narrowOutermost(cur3, numToProcess);
+ auto outIndicesSlice =
+ outIndices.narrowOutermost(cur3, numToProcess);
+
+ searchImpl_(
+ numToProcess,
+ bufGpus[cur3BufIndex]->data(),
+ k,
+ outDistancesSlice.data(),
+ outIndicesSlice.data(),
+ params);
+
+ // Create completion event
+ eventGpuExecuteDone[cur3BufIndex].reset(
+ new CudaEvent(defaultStream));
+
+ // We pick up from here
+ cur3BufIndex = (cur3BufIndex == 0) ? 1 : 0;
+ cur3 += numToProcess;
+ }
+
+ if (cur1 < n) {
+ // Copy CPU mem to CPU pinned
+ auto numToCopy = std::min(pageSizeInVecs, n - cur1);
+
+ // Make sure any previous copy has completed before continuing
+ auto& eventPrev = eventPinnedCopyDone[cur1BufIndex];
+ if (eventPrev.get()) {
+ eventPrev->cpuWaitOnEvent();
+ }
+
+ memcpy(bufPinned[cur1BufIndex],
+ x + cur1 * this->d,
+ numToCopy * this->d * sizeof(float));
+
+ // We pick up from here
+ cur2 = cur1;
+ cur1 += numToCopy;
+ cur1BufIndex = (cur1BufIndex == 0) ? 1 : 0;
+ }
+ }
+}
+
+void GpuIndex::compute_residual(const float* x, float* residual, idx_t key)
+ const {
+ FAISS_THROW_MSG("compute_residual not implemented for this type of index");
+}
+
+void GpuIndex::compute_residual_n(
+ idx_t n,
+ const float* xs,
+ float* residuals,
+ const idx_t* keys) const {
+ FAISS_THROW_MSG(
+ "compute_residual_n not implemented for this type of index");
+}
+
+std::shared_ptr<GpuResources> GpuIndex::getResources() {
+ return resources_;
+}
+
+GpuIndex* tryCastGpuIndex(faiss::Index* index) {
+ return dynamic_cast<GpuIndex*>(index);
+}
+
+bool isGpuIndex(faiss::Index* index) {
+ return tryCastGpuIndex(index) != nullptr;
+}
+
+bool isGpuIndexImplemented(faiss::Index* index) {
+#define CHECK_INDEX(TYPE) \
+ do { \
+ if (dynamic_cast<TYPE*>(index)) { \
+ return true; \
+ } \
+ } while (false)
+
+ CHECK_INDEX(faiss::IndexFlat);
+ // FIXME: do we want recursive checking of the IVF quantizer?
+ CHECK_INDEX(faiss::IndexIVFFlat);
+ CHECK_INDEX(faiss::IndexIVFPQ);
+ CHECK_INDEX(faiss::IndexIVFScalarQuantizer);
+
+ return false;
+}
+
+} // namespace gpu
+
+// This is the one defined in utils.cpp
+// Crossing fingers that the InitGpuCompileOptions_instance will
+// be instanciated after this global variable
+extern std::string gpu_compile_options;
+
+struct InitGpuCompileOptions {
+ InitGpuCompileOptions() {
+ gpu_compile_options = "GPU ";
+#ifdef USE_NVIDIA_CUVS
+ gpu_compile_options += "NVIDIA_CUVS ";
+#endif
+
+#ifdef USE_AMD_ROCM
+ gpu_compile_options += "AMD_ROCM ";
+#endif
+ }
+};
+
+InitGpuCompileOptions InitGpuCompileOptions_instance;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndex.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndex.h
new file mode 100644
index 0000000..33fd371
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndex.h
@@ -0,0 +1,198 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/gpu/GpuResources.h>
+
+namespace faiss {
+namespace gpu {
+
+struct GpuIndexConfig {
+ /// GPU device on which the index is resident
+ int device = 0;
+
+ /// What memory space to use for primary storage.
+ /// On Pascal and above (CC 6+) architectures, allows GPUs to use
+ /// more memory than is available on the GPU.
+ MemorySpace memorySpace = MemorySpace::Device;
+
+ /// Should the index dispatch down to cuVS?
+#if defined USE_NVIDIA_CUVS
+ bool use_cuvs = true;
+#else
+ bool use_cuvs = false;
+#endif
+};
+
+/// A centralized function that determines whether cuVS should
+/// be used based on various conditions (such as unsupported architecture)
+bool should_use_cuvs(GpuIndexConfig config_);
+
+class GpuIndex : public faiss::Index {
+ public:
+ GpuIndex(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ faiss::MetricType metric,
+ float metricArg,
+ GpuIndexConfig config);
+
+ /// Returns the device that this index is resident on
+ int getDevice() const;
+
+ /// Returns a reference to our GpuResources object that manages memory,
+ /// stream and handle resources on the GPU
+ std::shared_ptr<GpuResources> getResources();
+
+ /// Set the minimum data size for searches (in MiB) for which we use
+ /// CPU -> GPU paging
+ void setMinPagingSize(size_t size);
+
+ /// Returns the current minimum data size for paged searches
+ size_t getMinPagingSize() const;
+
+ /// `x` can be resident on the CPU or any GPU; copies are performed
+ /// as needed
+ /// Handles paged adds if the add set is too large; calls addInternal_
+ void add(idx_t, const float* x) override;
+
+ /// `x` and `ids` can be resident on the CPU or any GPU; copies are
+ /// performed as needed
+ /// Handles paged adds if the add set is too large; calls addInternal_
+ void add_with_ids(idx_t n, const float* x, const idx_t* ids) override;
+
+ /// `x` and `labels` can be resident on the CPU or any GPU; copies are
+ /// performed as needed
+ void assign(idx_t n, const float* x, idx_t* labels, idx_t k = 1)
+ const override;
+
+ /// `x`, `distances` and `labels` can be resident on the CPU or any
+ /// GPU; copies are performed as needed
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params = nullptr) const override;
+
+ /// `x`, `distances` and `labels` and `recons` can be resident on the CPU or
+ /// any GPU; copies are performed as needed
+ void search_and_reconstruct(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ float* recons,
+ const SearchParameters* params = nullptr) const override;
+
+ /// Overridden to force GPU indices to provide their own GPU-friendly
+ /// implementation
+ void compute_residual(const float* x, float* residual, idx_t key)
+ const override;
+
+ /// Overridden to force GPU indices to provide their own GPU-friendly
+ /// implementation
+ void compute_residual_n(
+ idx_t n,
+ const float* xs,
+ float* residuals,
+ const idx_t* keys) const override;
+
+ protected:
+ /// Copy what we need from the CPU equivalent
+ void copyFrom(const faiss::Index* index);
+
+ /// Copy what we have to the CPU equivalent
+ void copyTo(faiss::Index* index) const;
+
+ /// Does addImpl_ require IDs? If so, and no IDs are provided, we will
+ /// generate them sequentially based on the order in which the IDs are added
+ virtual bool addImplRequiresIDs_() const = 0;
+
+ /// Overridden to actually perform the add
+ /// All data is guaranteed to be resident on our device
+ virtual void addImpl_(idx_t n, const float* x, const idx_t* ids) = 0;
+
+ /// Overridden to actually perform the search
+ /// All data is guaranteed to be resident on our device
+ virtual void searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const = 0;
+
+ private:
+ /// Handles paged adds if the add set is too large, passes to
+ /// addImpl_ to actually perform the add for the current page
+ void addPaged_(idx_t n, const float* x, const idx_t* ids);
+
+ /// Calls addImpl_ for a single page of GPU-resident data
+ void addPage_(idx_t n, const float* x, const idx_t* ids);
+
+ /// Calls searchImpl_ for a single page of GPU-resident data
+ void searchNonPaged_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* outDistancesData,
+ idx_t* outIndicesData,
+ const SearchParameters* params) const;
+
+ /// Calls searchImpl_ for a single page of GPU-resident data,
+ /// handling paging of the data and copies from the CPU
+ void searchFromCpuPaged_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* outDistancesData,
+ idx_t* outIndicesData,
+ const SearchParameters* params) const;
+
+ protected:
+ /// Manages streams, cuBLAS handles and scratch memory for devices
+ std::shared_ptr<GpuResources> resources_;
+
+ /// Our configuration options
+ const GpuIndexConfig config_;
+
+ /// Size above which we page copies from the CPU to GPU
+ size_t minPagedSize_;
+};
+
+/// If the given index is a GPU index, this returns the index instance
+GpuIndex* tryCastGpuIndex(faiss::Index* index);
+
+/// Is the given index instance a GPU index?
+bool isGpuIndex(faiss::Index* index);
+
+/// Does the given CPU index instance have a corresponding GPU implementation?
+bool isGpuIndexImplemented(faiss::Index* index);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexBinaryFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexBinaryFlat.cu
new file mode 100644
index 0000000..e72638d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexBinaryFlat.cu
@@ -0,0 +1,262 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuIndexBinaryFlat.h>
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/impl/BinaryFlatIndex.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+
+namespace faiss {
+namespace gpu {
+
+/// Default CPU search size for which we use paged copies
+constexpr size_t kMinPageSize = (size_t)256 * 1024 * 1024;
+
+GpuIndexBinaryFlat::GpuIndexBinaryFlat(
+ GpuResourcesProvider* provider,
+ const faiss::IndexBinaryFlat* index,
+ GpuIndexBinaryFlatConfig config)
+ : IndexBinary(index->d),
+ resources_(provider->getResources()),
+ binaryFlatConfig_(config) {
+ FAISS_THROW_IF_NOT_FMT(
+ this->d % 8 == 0,
+ "vector dimension (number of bits) "
+ "must be divisible by 8 (passed %d)",
+ this->d);
+
+ // Flat index doesn't need training
+ this->is_trained = true;
+
+ copyFrom(index);
+}
+
+GpuIndexBinaryFlat::GpuIndexBinaryFlat(
+ GpuResourcesProvider* provider,
+ int dims,
+ GpuIndexBinaryFlatConfig config)
+ : IndexBinary(dims),
+ resources_(provider->getResources()),
+ binaryFlatConfig_(std::move(config)) {
+ DeviceScope scope(binaryFlatConfig_.device);
+ FAISS_THROW_IF_NOT_FMT(
+ this->d % 8 == 0,
+ "vector dimension (number of bits) "
+ "must be divisible by 8 (passed %d)",
+ this->d);
+
+ // Flat index doesn't need training
+ this->is_trained = true;
+
+ // Construct index
+ data_.reset(new BinaryFlatIndex(
+ resources_.get(), this->d, binaryFlatConfig_.memorySpace));
+}
+
+GpuIndexBinaryFlat::~GpuIndexBinaryFlat() {}
+
+int GpuIndexBinaryFlat::getDevice() const {
+ return binaryFlatConfig_.device;
+}
+
+std::shared_ptr<GpuResources> GpuIndexBinaryFlat::getResources() {
+ return resources_;
+}
+
+void GpuIndexBinaryFlat::copyFrom(const faiss::IndexBinaryFlat* index) {
+ DeviceScope scope(binaryFlatConfig_.device);
+
+ this->d = index->d;
+
+ this->ntotal = index->ntotal;
+
+ // destroy old first before allocating new
+ data_.reset();
+ data_.reset(new BinaryFlatIndex(
+ resources_.get(), this->d, binaryFlatConfig_.memorySpace));
+
+ // The index could be empty
+ if (index->ntotal > 0) {
+ data_->add(
+ index->xb.data(),
+ index->ntotal,
+ resources_->getDefaultStream(binaryFlatConfig_.device));
+ }
+}
+
+void GpuIndexBinaryFlat::copyTo(faiss::IndexBinaryFlat* index) const {
+ DeviceScope scope(binaryFlatConfig_.device);
+
+ index->d = this->d;
+ index->ntotal = this->ntotal;
+
+ FAISS_ASSERT(data_);
+ FAISS_ASSERT(data_->getSize() == this->ntotal);
+ index->xb.resize(this->ntotal * (this->d / 8));
+
+ if (this->ntotal > 0) {
+ fromDevice(
+ data_->getVectorsRef(),
+ index->xb.data(),
+ resources_->getDefaultStream(binaryFlatConfig_.device));
+ }
+}
+
+void GpuIndexBinaryFlat::add(idx_t n, const uint8_t* x) {
+ DeviceScope scope(binaryFlatConfig_.device);
+
+ // To avoid multiple re-allocations, ensure we have enough storage
+ // available
+ data_->reserve(n, resources_->getDefaultStream(binaryFlatConfig_.device));
+
+ data_->add(
+ (const unsigned char*)x,
+ n,
+ resources_->getDefaultStream(binaryFlatConfig_.device));
+ this->ntotal += n;
+}
+
+void GpuIndexBinaryFlat::reset() {
+ DeviceScope scope(binaryFlatConfig_.device);
+
+ // Free the underlying memory
+ data_->reset();
+ this->ntotal = 0;
+}
+
+void GpuIndexBinaryFlat::search(
+ idx_t n,
+ const uint8_t* x,
+ idx_t k,
+ int32_t* distances,
+ faiss::idx_t* labels,
+ const SearchParameters* params) const {
+ DeviceScope scope(binaryFlatConfig_.device);
+ auto stream = resources_->getDefaultStream(binaryFlatConfig_.device);
+
+ if (n == 0) {
+ return;
+ }
+
+ FAISS_THROW_IF_NOT_MSG(!params, "params not implemented");
+
+ validateKSelect(k);
+
+ // The input vectors may be too large for the GPU, but we still
+ // assume that the output distances and labels are not.
+ // Go ahead and make space for output distances and labels on the
+ // GPU.
+ // If we reach a point where all inputs are too big, we can add
+ // another level of tiling.
+ auto outDistances = toDeviceTemporary<int32_t, 2>(
+ resources_.get(),
+ binaryFlatConfig_.device,
+ distances,
+ stream,
+ {n, k});
+
+ auto outIndices = toDeviceTemporary<idx_t, 2>(
+ resources_.get(), binaryFlatConfig_.device, labels, stream, {n, k});
+
+ bool usePaged = false;
+
+ if (getDeviceForAddress(x) == -1) {
+ // It is possible that the user is querying for a vector set size
+ // `x` that won't fit on the GPU.
+ // In this case, we will have to handle paging of the data from CPU
+ // -> GPU.
+ // Currently, we don't handle the case where the output data won't
+ // fit on the GPU (e.g., n * k is too large for the GPU memory).
+ size_t dataSize = n * (this->d / 8) * sizeof(uint8_t);
+
+ if (dataSize >= kMinPageSize) {
+ searchFromCpuPaged_(
+ n, x, k, outDistances.data(), outIndices.data());
+ usePaged = true;
+ }
+ }
+
+ if (!usePaged) {
+ searchNonPaged_(n, x, k, outDistances.data(), outIndices.data());
+ }
+
+ // Copy back if necessary
+ fromDevice<int32_t, 2>(outDistances, distances, stream);
+ fromDevice<idx_t, 2>(outIndices, labels, stream);
+}
+
+void GpuIndexBinaryFlat::searchNonPaged_(
+ idx_t n,
+ const uint8_t* x,
+ int k,
+ int32_t* outDistancesData,
+ idx_t* outIndicesData) const {
+ Tensor<int32_t, 2, true> outDistances(outDistancesData, {n, k});
+ Tensor<idx_t, 2, true> outIndices(outIndicesData, {n, k});
+
+ auto stream = resources_->getDefaultStream(binaryFlatConfig_.device);
+
+ // Make sure arguments are on the device we desire; use temporary
+ // memory allocations to move it if necessary
+ auto vecs = toDeviceTemporary<uint8_t, 2>(
+ resources_.get(),
+ binaryFlatConfig_.device,
+ const_cast<uint8_t*>(x),
+ stream,
+ {n, (this->d / 8)});
+
+ data_->query(vecs, k, outDistances, outIndices);
+}
+
+void GpuIndexBinaryFlat::searchFromCpuPaged_(
+ idx_t n,
+ const uint8_t* x,
+ int k,
+ int32_t* outDistancesData,
+ idx_t* outIndicesData) const {
+ Tensor<int32_t, 2, true> outDistances(outDistancesData, {n, k});
+ Tensor<idx_t, 2, true> outIndices(outIndicesData, {n, k});
+
+ idx_t vectorSize = sizeof(uint8_t) * (this->d / 8);
+
+ // Just page without overlapping copy with compute (as GpuIndexFlat does)
+ auto batchSize =
+ utils::nextHighestPowerOf2(((idx_t)kMinPageSize / vectorSize));
+
+ for (idx_t cur = 0; cur < n; cur += batchSize) {
+ auto num = std::min(batchSize, n - cur);
+
+ auto outDistancesSlice = outDistances.narrowOutermost(cur, num);
+ auto outIndicesSlice = outIndices.narrowOutermost(cur, num);
+
+ searchNonPaged_(
+ num,
+ x + cur * (this->d / 8),
+ k,
+ outDistancesSlice.data(),
+ outIndicesSlice.data());
+ }
+}
+
+void GpuIndexBinaryFlat::reconstruct(faiss::idx_t key, uint8_t* out) const {
+ DeviceScope scope(binaryFlatConfig_.device);
+
+ FAISS_THROW_IF_NOT_MSG(key < this->ntotal, "index out of bounds");
+ auto stream = resources_->getDefaultStream(binaryFlatConfig_.device);
+
+ auto& vecs = data_->getVectorsRef();
+ auto vec = vecs[key];
+
+ fromDevice(vec.data(), out, vecs.getSize(1), stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexBinaryFlat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexBinaryFlat.h
new file mode 100644
index 0000000..32b76d6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexBinaryFlat.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuResources.h>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+class BinaryFlatIndex;
+
+struct GpuIndexBinaryFlatConfig : public GpuIndexConfig {};
+
+/// A GPU version of IndexBinaryFlat for brute-force comparison of bit vectors
+/// via Hamming distance
+class GpuIndexBinaryFlat : public IndexBinary {
+ public:
+ /// Construct from a pre-existing faiss::IndexBinaryFlat instance, copying
+ /// data over to the given GPU
+ GpuIndexBinaryFlat(
+ GpuResourcesProvider* resources,
+ const faiss::IndexBinaryFlat* index,
+ GpuIndexBinaryFlatConfig config = GpuIndexBinaryFlatConfig());
+
+ /// Construct an empty instance that can be added to
+ GpuIndexBinaryFlat(
+ GpuResourcesProvider* resources,
+ int dims,
+ GpuIndexBinaryFlatConfig config = GpuIndexBinaryFlatConfig());
+
+ ~GpuIndexBinaryFlat() override;
+
+ /// Returns the device that this index is resident on
+ int getDevice() const;
+
+ /// Returns a reference to our GpuResources object that manages memory,
+ /// stream and handle resources on the GPU
+ std::shared_ptr<GpuResources> getResources();
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(const faiss::IndexBinaryFlat* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexBinaryFlat* index) const;
+
+ void add(faiss::idx_t n, const uint8_t* x) override;
+
+ void reset() override;
+
+ void search(
+ idx_t n,
+ const uint8_t* x,
+ // faiss::IndexBinary has idx_t for k
+ idx_t k,
+ int32_t* distances,
+ faiss::idx_t* labels,
+ const faiss::SearchParameters* params = nullptr) const override;
+
+ void reconstruct(faiss::idx_t key, uint8_t* recons) const override;
+
+ protected:
+ /// Called from search when the input data is on the CPU;
+ /// potentially allows for pinned memory usage
+ void searchFromCpuPaged_(
+ idx_t n,
+ const uint8_t* x,
+ int k,
+ int32_t* outDistancesData,
+ idx_t* outIndicesData) const;
+
+ void searchNonPaged_(
+ idx_t n,
+ const uint8_t* x,
+ int k,
+ int32_t* outDistancesData,
+ idx_t* outIndicesData) const;
+
+ protected:
+ /// Manages streans, cuBLAS handles and scratch memory for devices
+ std::shared_ptr<GpuResources> resources_;
+
+ /// Configuration options
+ const GpuIndexBinaryFlatConfig binaryFlatConfig_;
+
+ /// Holds our GPU data containing the list of vectors
+ std::unique_ptr<BinaryFlatIndex> data_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexCagra.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexCagra.cu
new file mode 100644
index 0000000..42a6092
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexCagra.cu
@@ -0,0 +1,299 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/IndexHNSW.h>
+#include <faiss/gpu/GpuIndexCagra.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <cstddef>
+#include <faiss/gpu/impl/CuvsCagra.cuh>
+#include <optional>
+
+namespace faiss {
+namespace gpu {
+
+GpuIndexCagra::GpuIndexCagra(
+ GpuResourcesProvider* provider,
+ int dims,
+ faiss::MetricType metric,
+ GpuIndexCagraConfig config)
+ : GpuIndex(provider->getResources(), dims, metric, 0.0f, config),
+ cagraConfig_(config) {
+ this->is_trained = false;
+}
+
+void GpuIndexCagra::train(idx_t n, const float* x) {
+ DeviceScope scope(config_.device);
+ if (this->is_trained) {
+ FAISS_ASSERT(index_);
+ return;
+ }
+
+ FAISS_ASSERT(!index_);
+
+ std::optional<cuvs::neighbors::ivf_pq::index_params> ivf_pq_params =
+ std::nullopt;
+ std::optional<cuvs::neighbors::ivf_pq::search_params> ivf_pq_search_params =
+ std::nullopt;
+ if (cagraConfig_.ivf_pq_params != nullptr) {
+ ivf_pq_params =
+ std::make_optional<cuvs::neighbors::ivf_pq::index_params>();
+ ivf_pq_params->n_lists = cagraConfig_.ivf_pq_params->n_lists;
+ ivf_pq_params->kmeans_n_iters =
+ cagraConfig_.ivf_pq_params->kmeans_n_iters;
+ ivf_pq_params->kmeans_trainset_fraction =
+ cagraConfig_.ivf_pq_params->kmeans_trainset_fraction;
+ ivf_pq_params->pq_bits = cagraConfig_.ivf_pq_params->pq_bits;
+ ivf_pq_params->pq_dim = cagraConfig_.ivf_pq_params->pq_dim;
+ ivf_pq_params->codebook_kind =
+ static_cast<cuvs::neighbors::ivf_pq::codebook_gen>(
+ cagraConfig_.ivf_pq_params->codebook_kind);
+ ivf_pq_params->force_random_rotation =
+ cagraConfig_.ivf_pq_params->force_random_rotation;
+ ivf_pq_params->conservative_memory_allocation =
+ cagraConfig_.ivf_pq_params->conservative_memory_allocation;
+ }
+ if (cagraConfig_.ivf_pq_search_params != nullptr) {
+ ivf_pq_search_params =
+ std::make_optional<cuvs::neighbors::ivf_pq::search_params>();
+ ivf_pq_search_params->n_probes =
+ cagraConfig_.ivf_pq_search_params->n_probes;
+ ivf_pq_search_params->lut_dtype =
+ cagraConfig_.ivf_pq_search_params->lut_dtype;
+ ivf_pq_search_params->preferred_shmem_carveout =
+ cagraConfig_.ivf_pq_search_params->preferred_shmem_carveout;
+ }
+ index_ = std::make_shared<CuvsCagra>(
+ this->resources_.get(),
+ this->d,
+ cagraConfig_.intermediate_graph_degree,
+ cagraConfig_.graph_degree,
+ static_cast<faiss::cagra_build_algo>(cagraConfig_.build_algo),
+ cagraConfig_.nn_descent_niter,
+ cagraConfig_.store_dataset,
+ this->metric_type,
+ this->metric_arg,
+ INDICES_64_BIT,
+ ivf_pq_params,
+ ivf_pq_search_params,
+ cagraConfig_.refine_rate);
+
+ index_->train(n, x);
+
+ this->is_trained = true;
+ this->ntotal = n;
+}
+
+void GpuIndexCagra::add(idx_t n, const float* x) {
+ train(n, x);
+}
+
+bool GpuIndexCagra::addImplRequiresIDs_() const {
+ return false;
+};
+
+void GpuIndexCagra::addImpl_(idx_t n, const float* x, const idx_t* ids) {
+ FAISS_THROW_MSG("adding vectors is not supported by GpuIndexCagra.");
+};
+
+void GpuIndexCagra::searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* search_params) const {
+ FAISS_ASSERT(this->is_trained && index_);
+ FAISS_ASSERT(n > 0);
+
+ Tensor<float, 2, true> queries(const_cast<float*>(x), {n, this->d});
+ Tensor<float, 2, true> outDistances(distances, {n, k});
+ Tensor<idx_t, 2, true> outLabels(const_cast<idx_t*>(labels), {n, k});
+
+ SearchParametersCagra* params;
+ if (search_params) {
+ params = dynamic_cast<SearchParametersCagra*>(
+ const_cast<SearchParameters*>(search_params));
+ } else {
+ params = new SearchParametersCagra{};
+ }
+
+ index_->search(
+ queries,
+ k,
+ outDistances,
+ outLabels,
+ params->max_queries,
+ params->itopk_size,
+ params->max_iterations,
+ static_cast<faiss::cagra_search_algo>(params->algo),
+ params->team_size,
+ params->search_width,
+ params->min_iterations,
+ params->thread_block_size,
+ static_cast<faiss::cagra_hash_mode>(params->hashmap_mode),
+ params->hashmap_min_bitlen,
+ params->hashmap_max_fill_rate,
+ params->num_random_samplings,
+ params->seed);
+
+ if (not search_params) {
+ delete params;
+ }
+}
+
+void GpuIndexCagra::copyFrom(const faiss::IndexHNSWCagra* index) {
+ FAISS_ASSERT(index);
+
+ DeviceScope scope(config_.device);
+
+ GpuIndex::copyFrom(index);
+
+ auto base_index = dynamic_cast<IndexFlat*>(index->storage);
+ FAISS_ASSERT(base_index);
+ auto distances = base_index->get_xb();
+
+ auto hnsw = index->hnsw;
+ // copy level 0 to a dense knn graph matrix
+ std::vector<idx_t> knn_graph;
+ knn_graph.reserve(index->ntotal * hnsw.nb_neighbors(0));
+
+#pragma omp parallel for
+ for (size_t i = 0; i < index->ntotal; ++i) {
+ size_t begin, end;
+ hnsw.neighbor_range(i, 0, &begin, &end);
+ for (size_t j = begin; j < end; j++) {
+ // knn_graph.push_back(hnsw.neighbors[j]);
+ knn_graph[i * hnsw.nb_neighbors(0) + (j - begin)] =
+ hnsw.neighbors[j];
+ }
+ }
+
+ index_ = std::make_shared<CuvsCagra>(
+ this->resources_.get(),
+ this->d,
+ index->ntotal,
+ hnsw.nb_neighbors(0),
+ distances,
+ knn_graph.data(),
+ this->metric_type,
+ this->metric_arg,
+ INDICES_64_BIT);
+
+ this->is_trained = true;
+}
+
+void GpuIndexCagra::copyTo(faiss::IndexHNSWCagra* index) const {
+ FAISS_ASSERT(index_ && this->is_trained && index);
+
+ DeviceScope scope(config_.device);
+
+ //
+ // Index information
+ //
+ GpuIndex::copyTo(index);
+ // This needs to be zeroed out as this implementation adds vectors to the
+ // cpuIndex instead of copying fields
+ index->ntotal = 0;
+
+ auto graph_degree = index_->get_knngraph_degree();
+ auto M = graph_degree / 2;
+ if (index->storage and index->own_fields) {
+ delete index->storage;
+ }
+
+ if (this->metric_type == METRIC_L2) {
+ index->storage = new IndexFlatL2(index->d);
+ } else if (this->metric_type == METRIC_INNER_PRODUCT) {
+ index->storage = new IndexFlatIP(index->d);
+ }
+ index->own_fields = true;
+ index->keep_max_size_level0 = true;
+ index->hnsw.reset();
+ index->hnsw.assign_probas.clear();
+ index->hnsw.cum_nneighbor_per_level.clear();
+ index->hnsw.set_default_probas(M, 1.0 / log(M));
+
+ auto n_train = this->ntotal;
+ float* train_dataset;
+ auto dataset = index_->get_training_dataset();
+ bool allocation = false;
+ if (getDeviceForAddress(dataset) >= 0) {
+ train_dataset = new float[n_train * index->d];
+ allocation = true;
+ raft::copy(
+ train_dataset,
+ dataset,
+ n_train * index->d,
+ this->resources_->getRaftHandleCurrentDevice().get_stream());
+ } else {
+ train_dataset = const_cast<float*>(dataset);
+ }
+
+ // turn off as level 0 is copied from CAGRA graph
+ index->init_level0 = false;
+ if (!index->base_level_only) {
+ index->add(n_train, train_dataset);
+ } else {
+ index->hnsw.prepare_level_tab(n_train, false);
+ index->storage->add(n_train, train_dataset);
+ index->ntotal = n_train;
+ }
+ if (allocation) {
+ delete[] train_dataset;
+ }
+
+ auto graph = get_knngraph();
+
+#pragma omp parallel for
+ for (idx_t i = 0; i < n_train; i++) {
+ size_t begin, end;
+ index->hnsw.neighbor_range(i, 0, &begin, &end);
+ for (size_t j = begin; j < end; j++) {
+ index->hnsw.neighbors[j] = graph[i * graph_degree + (j - begin)];
+ }
+ }
+
+ // turn back on to allow new vectors to be added to level 0
+ index->init_level0 = true;
+}
+
+void GpuIndexCagra::reset() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ index_->reset();
+ this->ntotal = 0;
+ this->is_trained = false;
+ } else {
+ FAISS_ASSERT(this->ntotal == 0);
+ }
+}
+
+std::vector<idx_t> GpuIndexCagra::get_knngraph() const {
+ FAISS_ASSERT(index_ && this->is_trained);
+
+ return index_->get_knngraph();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexCagra.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexCagra.h
new file mode 100644
index 0000000..c654e1b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexCagra.h
@@ -0,0 +1,295 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/IndexIVF.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+
+namespace faiss {
+struct IndexHNSWCagra;
+}
+
+namespace faiss {
+namespace gpu {
+
+class CuvsCagra;
+
+enum class graph_build_algo {
+ /// Use IVF-PQ to build all-neighbors knn graph
+ IVF_PQ,
+ /// Use NN-Descent to build all-neighbors knn graph
+ NN_DESCENT
+};
+
+/// A type for specifying how PQ codebooks are created.
+enum class codebook_gen { // NOLINT
+ PER_SUBSPACE = 0, // NOLINT
+ PER_CLUSTER = 1, // NOLINT
+};
+
+struct IVFPQBuildCagraConfig {
+ ///
+ /// The number of inverted lists (clusters)
+ ///
+ /// Hint: the number of vectors per cluster (`n_rows/n_lists`) should be
+ /// approximately 1,000 to 10,000.
+
+ uint32_t n_lists = 1024;
+ /// The number of iterations searching for kmeans centers (index building).
+ uint32_t kmeans_n_iters = 20;
+ /// The fraction of data to use during iterative kmeans building.
+ double kmeans_trainset_fraction = 0.5;
+ ///
+ /// The bit length of the vector element after compression by PQ.
+ ///
+ /// Possible values: [4, 5, 6, 7, 8].
+ ///
+ /// Hint: the smaller the 'pq_bits', the smaller the index size and the
+ /// better the search performance, but the lower the recall.
+
+ uint32_t pq_bits = 8;
+ ///
+ /// The dimensionality of the vector after compression by PQ. When zero, an
+ /// optimal value is selected using a heuristic.
+ ///
+ /// NB: `pq_dim /// pq_bits` must be a multiple of 8.
+ ///
+ /// Hint: a smaller 'pq_dim' results in a smaller index size and better
+ /// search performance, but lower recall. If 'pq_bits' is 8, 'pq_dim' can be
+ /// set to any number, but multiple of 8 are desirable for good performance.
+ /// If 'pq_bits' is not 8, 'pq_dim' should be a multiple of 8. For good
+ /// performance, it is desirable that 'pq_dim' is a multiple of 32. Ideally,
+ /// 'pq_dim' should be also a divisor of the dataset dim.
+
+ uint32_t pq_dim = 0;
+ /// How PQ codebooks are created.
+ codebook_gen codebook_kind = codebook_gen::PER_SUBSPACE;
+ ///
+ /// Apply a random rotation matrix on the input data and queries even if
+ /// `dim % pq_dim == 0`.
+ ///
+ /// Note: if `dim` is not multiple of `pq_dim`, a random rotation is always
+ /// applied to the input data and queries to transform the working space
+ /// from `dim` to `rot_dim`, which may be slightly larger than the original
+ /// space and and is a multiple of `pq_dim` (`rot_dim % pq_dim == 0`).
+ /// However, this transform is not necessary when `dim` is multiple of
+ /// `pq_dim`
+ /// (`dim == rot_dim`, hence no need in adding "extra" data columns /
+ /// features).
+ ///
+ /// By default, if `dim == rot_dim`, the rotation transform is initialized
+ /// with the identity matrix. When `force_random_rotation == true`, a random
+ /// orthogonal transform matrix is generated regardless of the values of
+ /// `dim` and `pq_dim`.
+
+ bool force_random_rotation = false;
+ ///
+ /// By default, the algorithm allocates more space than necessary for
+ /// individual clusters
+ /// (`list_data`). This allows to amortize the cost of memory allocation and
+ /// reduce the number of data copies during repeated calls to `extend`
+ /// (extending the database).
+ ///
+ /// The alternative is the conservative allocation behavior; when enabled,
+ /// the algorithm always allocates the minimum amount of memory required to
+ /// store the given number of records. Set this flag to `true` if you prefer
+ /// to use as little GPU memory for the database as possible.
+
+ bool conservative_memory_allocation = false;
+};
+
+struct IVFPQSearchCagraConfig {
+ /// The number of clusters to search.
+ uint32_t n_probes = 20;
+ ///
+ /// Data type of look up table to be created dynamically at search time.
+ ///
+ /// Possible values: [CUDA_R_32F, CUDA_R_16F, CUDA_R_8U]
+ ///
+ /// The use of low-precision types reduces the amount of shared memory
+ /// required at search time, so fast shared memory kernels can be used even
+ /// for datasets with large dimansionality. Note that the recall is slightly
+ /// degraded when low-precision type is selected.
+
+ cudaDataType_t lut_dtype = CUDA_R_32F;
+ ///
+ /// Storage data type for distance/similarity computed at search time.
+ ///
+ /// Possible values: [CUDA_R_16F, CUDA_R_32F]
+ ///
+ /// If the performance limiter at search time is device memory access,
+ /// selecting FP16 will improve performance slightly.
+
+ cudaDataType_t internal_distance_dtype = CUDA_R_32F;
+ ///
+ /// Preferred fraction of SM's unified memory / L1 cache to be used as
+ /// shared memory.
+ ///
+ /// Possible values: [0.0 - 1.0] as a fraction of the
+ /// `sharedMemPerMultiprocessor`.
+ ///
+ /// One wants to increase the carveout to make sure a good GPU occupancy for
+ /// the main search kernel, but not to keep it too high to leave some memory
+ /// to be used as L1 cache. Note, this value is interpreted only as a hint.
+ /// Moreover, a GPU usually allows only a fixed set of cache configurations,
+ /// so the provided value is rounded up to the nearest configuration. Refer
+ /// to the NVIDIA tuning guide for the target GPU architecture.
+ ///
+ /// Note, this is a low-level tuning parameter that can have drastic
+ /// negative effects on the search performance if tweaked incorrectly.
+
+ double preferred_shmem_carveout = 1.0;
+};
+
+struct GpuIndexCagraConfig : public GpuIndexConfig {
+ /// Degree of input graph for pruning.
+ size_t intermediate_graph_degree = 128;
+ /// Degree of output graph.
+ size_t graph_degree = 64;
+ /// ANN algorithm to build knn graph.
+ graph_build_algo build_algo = graph_build_algo::IVF_PQ;
+ /// Number of Iterations to run if building with NN_DESCENT
+ size_t nn_descent_niter = 20;
+
+ IVFPQBuildCagraConfig* ivf_pq_params = nullptr;
+ IVFPQSearchCagraConfig* ivf_pq_search_params = nullptr;
+ float refine_rate = 2.0f;
+ bool store_dataset = true;
+};
+
+enum class search_algo {
+ /// For large batch sizes.
+ SINGLE_CTA,
+ /// For small batch sizes.
+ MULTI_CTA,
+ MULTI_KERNEL,
+ AUTO
+};
+
+enum class hash_mode { HASH, SMALL, AUTO };
+
+struct SearchParametersCagra : SearchParameters {
+ /// Maximum number of queries to search at the same time (batch size). Auto
+ /// select when 0.
+ size_t max_queries = 0;
+
+ /// Number of intermediate search results retained during the search.
+ ///
+ /// This is the main knob to adjust trade off between accuracy and search
+ /// speed. Higher values improve the search accuracy.
+
+ size_t itopk_size = 64;
+
+ /// Upper limit of search iterations. Auto select when 0.
+ size_t max_iterations = 0;
+
+ // In the following we list additional search parameters for fine tuning.
+ // Reasonable default values are automatically chosen.
+
+ /// Which search implementation to use.
+ search_algo algo = search_algo::AUTO;
+
+ /// Number of threads used to calculate a single distance. 4, 8, 16, or 32.
+
+ size_t team_size = 0;
+
+ /// Number of graph nodes to select as the starting point for the search in
+ /// each iteration. aka search width?
+ size_t search_width = 1;
+ /// Lower limit of search iterations.
+ size_t min_iterations = 0;
+
+ /// Thread block size. 0, 64, 128, 256, 512, 1024. Auto selection when 0.
+ size_t thread_block_size = 0;
+ /// Hashmap type. Auto selection when AUTO.
+ hash_mode hashmap_mode = hash_mode::AUTO;
+ /// Lower limit of hashmap bit length. More than 8.
+ size_t hashmap_min_bitlen = 0;
+ /// Upper limit of hashmap fill rate. More than 0.1, less than 0.9.
+ float hashmap_max_fill_rate = 0.5;
+
+ /// Number of iterations of initial random seed node selection. 1 or more.
+
+ uint32_t num_random_samplings = 1;
+ /// Bit mask used for initial random seed node selection.
+ uint64_t seed = 0x128394;
+};
+
+struct GpuIndexCagra : public GpuIndex {
+ public:
+ GpuIndexCagra(
+ GpuResourcesProvider* provider,
+ int dims,
+ faiss::MetricType metric = faiss::METRIC_L2,
+ GpuIndexCagraConfig config = GpuIndexCagraConfig());
+
+ /// Trains CAGRA based on the given vector data and add them along with ids.
+ /// NB: The use of the add function here is to build the CAGRA graph on
+ /// the base dataset. Use this function when you want to add vectors with
+ /// ids. Ref: https://github.com/facebookresearch/faiss/issues/4107
+ void add(idx_t n, const float* x) override;
+
+ /// Trains CAGRA based on the given vector data.
+ /// NB: The use of the train function here is to build the CAGRA graph on
+ /// the base dataset and is currently the only function to add the full set
+ /// of vectors (without IDs) to the index. There is no external quantizer to
+ /// be trained here.
+ void train(idx_t n, const float* x) override;
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(const faiss::IndexHNSWCagra* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexHNSWCagra* index) const;
+
+ void reset() override;
+
+ std::vector<idx_t> get_knngraph() const;
+
+ protected:
+ bool addImplRequiresIDs_() const override;
+
+ void addImpl_(idx_t n, const float* x, const idx_t* ids) override;
+
+ /// Called from GpuIndex for search
+ void searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* search_params) const override;
+
+ /// Our configuration options
+ const GpuIndexCagraConfig cagraConfig_;
+
+ /// Instance that we own; contains the inverted lists
+ std::shared_ptr<CuvsCagra> index_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexFlat.cu
new file mode 100644
index 0000000..eb87e08
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexFlat.cu
@@ -0,0 +1,444 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <limits>
+
+#if defined USE_NVIDIA_CUVS
+#include <faiss/gpu/impl/CuvsFlatIndex.cuh>
+#endif
+
+namespace faiss {
+namespace gpu {
+
+GpuIndexFlat::GpuIndexFlat(
+ GpuResourcesProvider* provider,
+ const faiss::IndexFlat* index,
+ GpuIndexFlatConfig config)
+ : GpuIndex(
+ provider->getResources(),
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ config),
+ flatConfig_(config) {
+ // Flat index doesn't need training
+ this->is_trained = true;
+
+ copyFrom(index);
+}
+
+GpuIndexFlat::GpuIndexFlat(
+ std::shared_ptr<GpuResources> resources,
+ const faiss::IndexFlat* index,
+ GpuIndexFlatConfig config)
+ : GpuIndex(
+ resources,
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ config),
+ flatConfig_(config) {
+ // Flat index doesn't need training
+ this->is_trained = true;
+
+ copyFrom(index);
+}
+
+GpuIndexFlat::GpuIndexFlat(
+ GpuResourcesProvider* provider,
+ int dims,
+ faiss::MetricType metric,
+ GpuIndexFlatConfig config)
+ : GpuIndex(provider->getResources(), dims, metric, 0, config),
+ flatConfig_(config) {
+ DeviceScope scope(config_.device);
+
+ // Flat index doesn't need training
+ this->is_trained = true;
+
+ // Construct index
+ resetIndex_(dims);
+}
+
+GpuIndexFlat::GpuIndexFlat(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ faiss::MetricType metric,
+ GpuIndexFlatConfig config)
+ : GpuIndex(resources, dims, metric, 0, config), flatConfig_(config) {
+ DeviceScope scope(config_.device);
+
+ // Flat index doesn't need training
+ this->is_trained = true;
+
+ // Construct index
+ resetIndex_(dims);
+}
+
+GpuIndexFlat::~GpuIndexFlat() {}
+
+void GpuIndexFlat::resetIndex_(int dims) {
+#if defined USE_NVIDIA_CUVS
+
+ if (should_use_cuvs(config_)) {
+ data_.reset(new CuvsFlatIndex(
+ resources_.get(),
+ dims,
+ flatConfig_.useFloat16,
+ config_.memorySpace));
+ } else
+#else
+ if (should_use_cuvs(config_)) {
+ FAISS_THROW_MSG(
+ "cuVS has not been compiled into the current version so it cannot be used.");
+ } else
+#endif
+ {
+ data_.reset(new FlatIndex(
+ resources_.get(),
+ dims,
+ flatConfig_.useFloat16,
+ config_.memorySpace));
+ }
+}
+
+void GpuIndexFlat::copyFrom(const faiss::IndexFlat* index) {
+ DeviceScope scope(config_.device);
+
+ GpuIndex::copyFrom(index);
+
+ data_.reset();
+ resetIndex_(this->d);
+
+ // The index could be empty
+ if (index->ntotal > 0) {
+ data_->add(
+ index->get_xb(),
+ index->ntotal,
+ resources_->getDefaultStream(config_.device));
+ }
+}
+
+void GpuIndexFlat::copyTo(faiss::IndexFlat* index) const {
+ DeviceScope scope(config_.device);
+
+ GpuIndex::copyTo(index);
+ index->code_size = sizeof(float) * this->d;
+
+ FAISS_ASSERT(data_);
+ FAISS_ASSERT(data_->getSize() == this->ntotal);
+ index->codes.resize(this->ntotal * index->code_size);
+
+ if (this->ntotal > 0) {
+ // FIXME: there is an extra GPU allocation here and copy if the flat
+ // index is already float32
+ reconstruct_n(0, this->ntotal, index->get_xb());
+ }
+}
+
+size_t GpuIndexFlat::getNumVecs() const {
+ return this->ntotal;
+}
+
+void GpuIndexFlat::reset() {
+ DeviceScope scope(config_.device);
+
+ // Free the underlying memory
+ data_->reset();
+ this->ntotal = 0;
+}
+
+void GpuIndexFlat::train(idx_t n, const float* x) {
+ // nothing to do
+}
+
+void GpuIndexFlat::add(idx_t n, const float* x) {
+ DeviceScope scope(config_.device);
+
+ FAISS_THROW_IF_NOT_MSG(this->is_trained, "Index not trained");
+
+ if (n == 0) {
+ // nothing to add
+ return;
+ }
+
+ // To avoid multiple re-allocations, ensure we have enough storage
+ // available
+ data_->reserve(n, resources_->getDefaultStream(config_.device));
+
+ // If we're not operating in float16 mode, we don't need the input
+ // data to be resident on our device; we can add directly.
+ if (!flatConfig_.useFloat16) {
+ addImpl_(n, x, nullptr);
+ } else {
+ // Otherwise, perform the paging
+ GpuIndex::add(n, x);
+ }
+}
+
+bool GpuIndexFlat::addImplRequiresIDs_() const {
+ return false;
+}
+
+void GpuIndexFlat::addImpl_(idx_t n, const float* x, const idx_t* ids) {
+ // current device already set
+ // n already validated
+ FAISS_ASSERT(data_);
+ FAISS_ASSERT(n > 0);
+
+ // We do not support add_with_ids
+ FAISS_THROW_IF_NOT_MSG(!ids, "add_with_ids not supported");
+
+ data_->add(x, n, resources_->getDefaultStream(config_.device));
+ this->ntotal += n;
+}
+
+void GpuIndexFlat::searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ // current device already set
+ // n/k already validated
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ // Input and output data are already resident on the GPU
+ Tensor<float, 2, true> queries(const_cast<float*>(x), {n, this->d});
+ Tensor<float, 2, true> outDistances(distances, {n, k});
+ Tensor<idx_t, 2, true> outLabels(labels, {n, k});
+
+ data_->query(
+ queries, k, metric_type, metric_arg, outDistances, outLabels, true);
+}
+
+void GpuIndexFlat::reconstruct(idx_t key, float* out) const {
+ DeviceScope scope(config_.device);
+
+ FAISS_THROW_IF_NOT_FMT(
+ key < this->ntotal,
+ "index %zu out of bounds (ntotal %zu)",
+ key,
+ this->ntotal);
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ // FIXME: `out` may already be on the device, in which case this is an
+ // unneeded allocation
+ DeviceTensor<float, 2, true> vec(
+ resources_.get(),
+ makeTempAlloc(AllocType::Other, stream),
+ {1, this->d});
+
+ FAISS_ASSERT(data_);
+ data_->reconstruct(key, 1, vec);
+
+ fromDevice(vec.data(), out, this->d, stream);
+}
+
+void GpuIndexFlat::reconstruct_n(idx_t i0, idx_t n, float* out) const {
+ DeviceScope scope(config_.device);
+
+ if (n == 0) {
+ // nothing to do
+ return;
+ }
+
+ FAISS_THROW_IF_NOT_FMT(
+ i0 < this->ntotal,
+ "start index (%zu) out of bounds (ntotal %zu)",
+ i0,
+ this->ntotal);
+ FAISS_THROW_IF_NOT_FMT(
+ i0 + n - 1 < this->ntotal,
+ "max index requested (%zu) out of bounds (ntotal %zu)",
+ i0 + n - 1,
+ this->ntotal);
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ auto outDevice = toDeviceTemporary<float, 2>(
+ resources_.get(), config_.device, out, stream, {n, this->d});
+
+ FAISS_ASSERT(data_);
+ data_->reconstruct(i0, n, outDevice);
+
+ fromDevice<float, 2>(outDevice, out, stream);
+}
+
+void GpuIndexFlat::reconstruct_batch(idx_t n, const idx_t* keys, float* out)
+ const {
+ DeviceScope scope(config_.device);
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ if (n == 0) {
+ // nothing to do
+ return;
+ }
+
+ auto keysDevice = toDeviceTemporary<faiss::idx_t, 1>(
+ resources_.get(),
+ config_.device,
+ const_cast<idx_t*>(keys),
+ stream,
+ {n});
+
+ auto outDevice = toDeviceTemporary<float, 2>(
+ resources_.get(), config_.device, out, stream, {n, this->d});
+
+ FAISS_ASSERT(data_);
+ data_->reconstruct(keysDevice, outDevice);
+
+ // If the output is on the host, copy back if needed
+ fromDevice<float, 2>(outDevice, out, stream);
+}
+
+void GpuIndexFlat::compute_residual(const float* x, float* residual, idx_t key)
+ const {
+ compute_residual_n(1, x, residual, &key);
+}
+
+void GpuIndexFlat::compute_residual_n(
+ idx_t n,
+ const float* xs,
+ float* residuals,
+ const idx_t* keys) const {
+ DeviceScope scope(config_.device);
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ if (n == 0) {
+ // nothing to do
+ return;
+ }
+
+ auto vecsDevice = toDeviceTemporary<float, 2>(
+ resources_.get(),
+ config_.device,
+ const_cast<float*>(xs),
+ stream,
+ {n, this->d});
+ auto idsDevice = toDeviceTemporary<idx_t, 1>(
+ resources_.get(),
+ config_.device,
+ const_cast<idx_t*>(keys),
+ stream,
+ {n});
+ auto residualDevice = toDeviceTemporary<float, 2>(
+ resources_.get(), config_.device, residuals, stream, {n, this->d});
+
+ FAISS_ASSERT(data_);
+ data_->computeResidual(vecsDevice, idsDevice, residualDevice);
+
+ // If the output is on the host, copy back if needed
+ fromDevice<float, 2>(residualDevice, residuals, stream);
+}
+
+//
+// GpuIndexFlatL2
+//
+
+GpuIndexFlatL2::GpuIndexFlatL2(
+ GpuResourcesProvider* provider,
+ faiss::IndexFlatL2* index,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(provider, index, config) {}
+
+GpuIndexFlatL2::GpuIndexFlatL2(
+ std::shared_ptr<GpuResources> resources,
+ faiss::IndexFlatL2* index,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(resources, index, config) {}
+
+GpuIndexFlatL2::GpuIndexFlatL2(
+ GpuResourcesProvider* provider,
+ int dims,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(provider, dims, faiss::METRIC_L2, config) {}
+
+GpuIndexFlatL2::GpuIndexFlatL2(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(resources, dims, faiss::METRIC_L2, config) {}
+
+void GpuIndexFlatL2::copyFrom(faiss::IndexFlat* index) {
+ FAISS_THROW_IF_NOT_MSG(
+ index->metric_type == metric_type,
+ "Cannot copy a GpuIndexFlatL2 from an index of "
+ "different metric_type");
+
+ GpuIndexFlat::copyFrom(index);
+}
+
+void GpuIndexFlatL2::copyTo(faiss::IndexFlat* index) {
+ FAISS_THROW_IF_NOT_MSG(
+ index->metric_type == metric_type,
+ "Cannot copy a GpuIndexFlatL2 to an index of "
+ "different metric_type");
+
+ GpuIndexFlat::copyTo(index);
+}
+
+//
+// GpuIndexFlatIP
+//
+
+GpuIndexFlatIP::GpuIndexFlatIP(
+ GpuResourcesProvider* provider,
+ faiss::IndexFlatIP* index,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(provider, index, config) {}
+
+GpuIndexFlatIP::GpuIndexFlatIP(
+ std::shared_ptr<GpuResources> resources,
+ faiss::IndexFlatIP* index,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(resources, index, config) {}
+
+GpuIndexFlatIP::GpuIndexFlatIP(
+ GpuResourcesProvider* provider,
+ int dims,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(provider, dims, faiss::METRIC_INNER_PRODUCT, config) {}
+
+GpuIndexFlatIP::GpuIndexFlatIP(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ GpuIndexFlatConfig config)
+ : GpuIndexFlat(resources, dims, faiss::METRIC_INNER_PRODUCT, config) {}
+
+void GpuIndexFlatIP::copyFrom(faiss::IndexFlat* index) {
+ FAISS_THROW_IF_NOT_MSG(
+ index->metric_type == metric_type,
+ "Cannot copy a GpuIndexFlatIP from an index of "
+ "different metric_type");
+
+ GpuIndexFlat::copyFrom(index);
+}
+
+void GpuIndexFlatIP::copyTo(faiss::IndexFlat* index) {
+ // The passed in index must be IP
+ FAISS_THROW_IF_NOT_MSG(
+ index->metric_type == metric_type,
+ "Cannot copy a GpuIndexFlatIP to an index of "
+ "different metric_type");
+
+ GpuIndexFlat::copyTo(index);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexFlat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexFlat.h
new file mode 100644
index 0000000..ee4c144
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexFlat.h
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/GpuIndex.h>
+#include <memory>
+
+namespace faiss {
+
+struct IndexFlat;
+struct IndexFlatL2;
+struct IndexFlatIP;
+
+} // namespace faiss
+
+namespace faiss {
+namespace gpu {
+
+class FlatIndex;
+
+struct GpuIndexFlatConfig : public GpuIndexConfig {
+ /// Whether or not data is stored as float16
+ bool ALIGNED(8) useFloat16 = false;
+
+ /// Deprecated: no longer used
+ /// Previously used to indicate whether internal storage of vectors is
+ /// transposed
+ bool storeTransposed = false;
+};
+
+/// Wrapper around the GPU implementation that looks like
+/// faiss::IndexFlat; copies over centroid data from a given
+/// faiss::IndexFlat
+class GpuIndexFlat : public GpuIndex {
+ public:
+ /// Construct from a pre-existing faiss::IndexFlat instance, copying
+ /// data over to the given GPU
+ GpuIndexFlat(
+ GpuResourcesProvider* provider,
+ const faiss::IndexFlat* index,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ GpuIndexFlat(
+ std::shared_ptr<GpuResources> resources,
+ const faiss::IndexFlat* index,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ /// Construct an empty instance that can be added to
+ GpuIndexFlat(
+ GpuResourcesProvider* provider,
+ int dims,
+ faiss::MetricType metric,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ GpuIndexFlat(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ faiss::MetricType metric,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ ~GpuIndexFlat() override;
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(const faiss::IndexFlat* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexFlat* index) const;
+
+ /// Returns the number of vectors we contain
+ size_t getNumVecs() const;
+
+ /// Clears all vectors from this index
+ void reset() override;
+
+ /// This index is not trained, so this does nothing
+ void train(idx_t n, const float* x) override;
+
+ /// Overrides to avoid excessive copies
+ void add(idx_t, const float* x) override;
+
+ /// Reconstruction methods; prefer the batch reconstruct as it will
+ /// be more efficient
+ void reconstruct(idx_t key, float* out) const override;
+
+ /// Batch reconstruction method
+ void reconstruct_n(idx_t i0, idx_t num, float* out) const override;
+
+ /// Batch reconstruction method
+ void reconstruct_batch(idx_t n, const idx_t* keys, float* out)
+ const override;
+
+ /// Compute residual
+ void compute_residual(const float* x, float* residual, idx_t key)
+ const override;
+
+ /// Compute residual (batch mode)
+ void compute_residual_n(
+ idx_t n,
+ const float* xs,
+ float* residuals,
+ const idx_t* keys) const override;
+
+ /// For internal access
+ inline FlatIndex* getGpuData() {
+ return data_.get();
+ }
+
+ protected:
+ void resetIndex_(int dims);
+
+ /// Flat index does not require IDs as there is no storage available for
+ /// them
+ bool addImplRequiresIDs_() const override;
+
+ /// Called from GpuIndex for add
+ void addImpl_(idx_t n, const float* x, const idx_t* ids) override;
+
+ /// Called from GpuIndex for search
+ void searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const override;
+
+ protected:
+ /// Our configuration options
+ const GpuIndexFlatConfig flatConfig_;
+
+ /// Holds our GPU data containing the list of vectors
+ std::unique_ptr<FlatIndex> data_;
+};
+
+/// Wrapper around the GPU implementation that looks like
+/// faiss::IndexFlatL2; copies over centroid data from a given
+/// faiss::IndexFlat
+class GpuIndexFlatL2 : public GpuIndexFlat {
+ public:
+ /// Construct from a pre-existing faiss::IndexFlatL2 instance, copying
+ /// data over to the given GPU
+ GpuIndexFlatL2(
+ GpuResourcesProvider* provider,
+ faiss::IndexFlatL2* index,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ GpuIndexFlatL2(
+ std::shared_ptr<GpuResources> resources,
+ faiss::IndexFlatL2* index,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ /// Construct an empty instance that can be added to
+ GpuIndexFlatL2(
+ GpuResourcesProvider* provider,
+ int dims,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ GpuIndexFlatL2(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(faiss::IndexFlat* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexFlat* index);
+};
+
+/// Wrapper around the GPU implementation that looks like
+/// faiss::IndexFlatIP; copies over centroid data from a given
+/// faiss::IndexFlat
+class GpuIndexFlatIP : public GpuIndexFlat {
+ public:
+ /// Construct from a pre-existing faiss::IndexFlatIP instance, copying
+ /// data over to the given GPU
+ GpuIndexFlatIP(
+ GpuResourcesProvider* provider,
+ faiss::IndexFlatIP* index,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ GpuIndexFlatIP(
+ std::shared_ptr<GpuResources> resources,
+ faiss::IndexFlatIP* index,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ /// Construct an empty instance that can be added to
+ GpuIndexFlatIP(
+ GpuResourcesProvider* provider,
+ int dims,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ GpuIndexFlatIP(
+ std::shared_ptr<GpuResources> resources,
+ int dims,
+ GpuIndexFlatConfig config = GpuIndexFlatConfig());
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(faiss::IndexFlat* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexFlat* index);
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVF.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVF.cu
new file mode 100644
index 0000000..a882d8a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVF.cu
@@ -0,0 +1,481 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/clone_index.h>
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVF.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/impl/IVFBase.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+
+namespace faiss {
+namespace gpu {
+
+GpuIndexIVF::GpuIndexIVF(
+ GpuResourcesProvider* provider,
+ int dims,
+ faiss::MetricType metric,
+ float metricArg,
+ idx_t nlistIn,
+ GpuIndexIVFConfig config)
+ : GpuIndex(provider->getResources(), dims, metric, metricArg, config),
+ IndexIVFInterface(nullptr, nlistIn),
+ ivfConfig_(config) {
+ // Only IP and L2 are supported for now
+ if (!(metric_type == faiss::METRIC_L2 ||
+ metric_type == faiss::METRIC_INNER_PRODUCT)) {
+ FAISS_THROW_FMT("unsupported metric type %d", (int)metric_type);
+ }
+
+ init_();
+}
+
+GpuIndexIVF::GpuIndexIVF(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ faiss::MetricType metric,
+ float metricArg,
+ idx_t nlistIn,
+ GpuIndexIVFConfig config)
+ : GpuIndex(provider->getResources(), dims, metric, metricArg, config),
+ IndexIVFInterface(coarseQuantizer, nlistIn),
+ ivfConfig_(config) {
+ FAISS_THROW_IF_NOT_MSG(
+ quantizer, "expecting a coarse quantizer object; none provided");
+
+ // We are passed an external quantizer object that we do not own
+ own_fields = false;
+
+ // Only IP and L2 are supported for now
+ if (!(metric_type == faiss::METRIC_L2 ||
+ metric_type == faiss::METRIC_INNER_PRODUCT)) {
+ FAISS_THROW_FMT("unsupported metric type %d", (int)metric_type);
+ }
+
+ init_();
+}
+
+void GpuIndexIVF::init_() {
+ FAISS_THROW_IF_NOT_MSG(nlist > 0, "nlist must be > 0");
+
+ // Spherical by default if the metric is inner_product
+ // (copying IndexIVF.cpp)
+ if (metric_type == faiss::METRIC_INNER_PRODUCT) {
+ cp.spherical = true;
+ }
+
+ // here we set a low # iterations because this is typically used
+ // for large clusterings (copying IndexIVF.cpp's Level1Quantizer
+ cp.niter = 10;
+
+ cp.verbose = verbose;
+
+ if (quantizer) {
+ // The passed in quantizer may be either a CPU or GPU index
+ // Same work as IndexIVF's constructor
+ is_trained = quantizer->is_trained && quantizer->ntotal == nlist;
+ } else {
+ // we have not yet been trained
+ is_trained = false;
+
+ // Construct a GPU empty flat quantizer as our coarse quantizer
+ GpuIndexFlatConfig config = ivfConfig_.flatConfig;
+ // inherit our same device
+ config.device = config_.device;
+ config.use_cuvs = config_.use_cuvs;
+
+ if (metric_type == faiss::METRIC_L2) {
+ quantizer = new GpuIndexFlatL2(resources_, d, config);
+ } else if (metric_type == faiss::METRIC_INNER_PRODUCT) {
+ quantizer = new GpuIndexFlatIP(resources_, d, config);
+ } else {
+ // unknown metric type
+ FAISS_THROW_FMT("unsupported metric type %d", (int)metric_type);
+ }
+
+ // we instantiated the coarse quantizer here, so we destroy it as well
+ own_fields = true;
+ }
+
+ verifyIVFSettings_();
+}
+
+GpuIndexIVF::~GpuIndexIVF() {}
+
+void GpuIndexIVF::verifyIVFSettings_() const {
+ // We should always have a quantizer instance
+ FAISS_THROW_IF_NOT(quantizer);
+ FAISS_THROW_IF_NOT(d == quantizer->d);
+
+ if (is_trained) {
+ FAISS_THROW_IF_NOT(quantizer->is_trained);
+
+ // IVF quantizer should correspond to our set of lists
+ FAISS_THROW_IF_NOT_FMT(
+ quantizer->ntotal == nlist,
+ "IVF nlist count (%zu) does not match trained coarse quantizer size (%zu)",
+ nlist,
+ quantizer->ntotal);
+ } else {
+ // The coarse quantizer may or may not be trained, but if we are
+ // trained, then the coarse quantizer must also be trained (the check
+ // above)
+ FAISS_THROW_IF_NOT(ntotal == 0);
+ }
+
+ // If the quantizer is a GPU index, then it must be resident on the same
+ // device as us
+ auto gpuQuantizer = tryCastGpuIndex(quantizer);
+ if (gpuQuantizer && gpuQuantizer->getDevice() != getDevice()) {
+ FAISS_THROW_FMT(
+ "GpuIndexIVF: not allowed to instantiate a GPU IVF "
+ "index that is resident on a different GPU (%d) "
+ "than its GPU coarse quantizer (%d)",
+ getDevice(),
+ gpuQuantizer->getDevice());
+ }
+}
+
+void GpuIndexIVF::copyFrom(const faiss::IndexIVF* index) {
+ DeviceScope scope(config_.device);
+
+ GpuIndex::copyFrom(index);
+
+ FAISS_ASSERT(index->nlist > 0);
+ nlist = index->nlist;
+
+ validateNProbe(index->nprobe);
+ nprobe = index->nprobe;
+
+ // The metric type may have changed as well, so we might have to
+ // change our quantizer
+ if (own_fields) {
+ delete quantizer;
+ }
+ quantizer = nullptr;
+
+ // IVF index that we are copying from must have a coarse quantizer
+ FAISS_THROW_IF_NOT(index->quantizer);
+
+ if (!isGpuIndex(index->quantizer)) {
+ // The coarse quantizer used in the IndexIVF is non-GPU.
+ // If it is something that we support on the GPU, we wish to copy it
+ // over to the GPU, on the same device that we are on.
+ GpuResourcesProviderFromInstance pfi(getResources());
+
+ // Attempt to clone the index to GPU. If it fails because the coarse
+ // quantizer is not implemented on GPU and the flag to allow CPU
+ // fallback is set, retry it with CPU cloner and re-throw errors.
+ try {
+ GpuClonerOptions options;
+ auto cloner = ToGpuCloner(&pfi, getDevice(), options);
+ quantizer = cloner.clone_Index(index->quantizer);
+ } catch (const std::exception& e) {
+ if (strstr(e.what(), "not implemented on GPU")) {
+ if (ivfConfig_.allowCpuCoarseQuantizer) {
+ Cloner cpuCloner;
+ quantizer = cpuCloner.clone_Index(index->quantizer);
+ } else {
+ FAISS_THROW_MSG(
+ "This index type is not implemented on "
+ "GPU and allowCpuCoarseQuantizer is set to false. "
+ "Please set the flag to true to allow the CPU "
+ "fallback in cloning.");
+ }
+ } else {
+ throw;
+ }
+ }
+ own_fields = true;
+ } else {
+ // Otherwise, this is a GPU coarse quantizer index instance found in a
+ // CPU instance. It is unclear what we should do here, but for now we'll
+ // flag this as an error (we're expecting a pure CPU index)
+ FAISS_THROW_MSG(
+ "GpuIndexIVF::copyFrom: copying a CPU IVF index to GPU "
+ "that already contains a GPU coarse (level 1) quantizer "
+ "is not currently supported");
+ }
+
+ // Validate equality
+ FAISS_ASSERT(is_trained == index->is_trained);
+ FAISS_ASSERT(ntotal == index->ntotal);
+ FAISS_ASSERT(nlist == index->nlist);
+ FAISS_ASSERT(quantizer->is_trained == index->quantizer->is_trained);
+ FAISS_ASSERT(quantizer->ntotal == index->quantizer->ntotal);
+
+ // Validate IVF/quantizer settings
+ verifyIVFSettings_();
+}
+
+void GpuIndexIVF::copyTo(faiss::IndexIVF* index) const {
+ DeviceScope scope(config_.device);
+
+ //
+ // Index information
+ //
+ GpuIndex::copyTo(index);
+
+ //
+ // IndexIVF information
+ //
+ index->nlist = nlist;
+ index->nprobe = nprobe;
+
+ FAISS_ASSERT(quantizer);
+ if (index->own_fields) {
+ delete index->quantizer;
+ index->quantizer = nullptr;
+ }
+
+ index->quantizer = index_gpu_to_cpu(quantizer);
+ FAISS_THROW_IF_NOT(index->quantizer);
+
+ // Validate consistency between the coarse quantizer and the index
+ FAISS_ASSERT(
+ index->quantizer->is_trained == quantizer->is_trained &&
+ index->quantizer->is_trained == is_trained);
+ FAISS_ASSERT(index->quantizer->ntotal == quantizer->ntotal);
+
+ index->own_fields = true;
+ index->quantizer_trains_alone = 0;
+ index->cp = this->cp;
+ index->make_direct_map(false);
+}
+
+idx_t GpuIndexIVF::getNumLists() const {
+ return nlist;
+}
+
+idx_t GpuIndexIVF::getListLength(idx_t listId) const {
+ DeviceScope scope(config_.device);
+ FAISS_ASSERT(baseIndex_);
+
+ return baseIndex_->getListLength(listId);
+}
+
+std::vector<uint8_t> GpuIndexIVF::getListVectorData(
+ idx_t listId,
+ bool gpuFormat) const {
+ DeviceScope scope(config_.device);
+ FAISS_ASSERT(baseIndex_);
+
+ return baseIndex_->getListVectorData(listId, gpuFormat);
+}
+
+std::vector<idx_t> GpuIndexIVF::getListIndices(idx_t listId) const {
+ DeviceScope scope(config_.device);
+ FAISS_ASSERT(baseIndex_);
+
+ return baseIndex_->getListIndices(listId);
+}
+
+void GpuIndexIVF::addImpl_(idx_t n, const float* x, const idx_t* xids) {
+ // Device is already set in GpuIndex::add
+ FAISS_ASSERT(baseIndex_);
+ FAISS_ASSERT(n > 0);
+
+ // Data is already resident on the GPU
+ Tensor<float, 2, true> data(const_cast<float*>(x), {n, this->d});
+ Tensor<idx_t, 1, true> labels(const_cast<idx_t*>(xids), {n});
+
+ // Not all vectors may be able to be added (some may contain NaNs etc)
+ baseIndex_->addVectors(quantizer, data, labels);
+
+ // but keep the ntotal based on the total number of vectors that we
+ // attempted to add
+ ntotal += n;
+}
+
+int GpuIndexIVF::getCurrentNProbe_(const SearchParameters* params) const {
+ size_t use_nprobe = nprobe;
+ if (params) {
+ auto ivfParams = dynamic_cast<const SearchParametersIVF*>(params);
+ if (ivfParams) {
+ use_nprobe = ivfParams->nprobe;
+
+ FAISS_THROW_IF_NOT_FMT(
+ ivfParams->max_codes == 0,
+ "GPU IVF index does not currently support "
+ "SearchParametersIVF::max_codes (passed %zu, must be 0)",
+ ivfParams->max_codes);
+ } else {
+ FAISS_THROW_MSG(
+ "GPU IVF index: passed unhandled SearchParameters "
+ "class to search function; only SearchParametersIVF "
+ "implemented at present");
+ }
+ }
+
+ validateNProbe(use_nprobe);
+ // We use int internally for nprobe
+ return int(use_nprobe);
+}
+
+void GpuIndexIVF::searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const {
+ // Device was already set in GpuIndex::search
+ int use_nprobe = getCurrentNProbe_(params);
+
+ // This was previously checked
+ FAISS_ASSERT(is_trained && baseIndex_);
+ FAISS_ASSERT(n > 0);
+
+ // Data is already resident on the GPU
+ Tensor<float, 2, true> queries(const_cast<float*>(x), {n, this->d});
+ Tensor<float, 2, true> outDistances(distances, {n, k});
+ Tensor<idx_t, 2, true> outLabels(const_cast<idx_t*>(labels), {n, k});
+
+ baseIndex_->search(
+ quantizer, queries, use_nprobe, k, outDistances, outLabels);
+}
+
+void GpuIndexIVF::search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* stats) const {
+ FAISS_THROW_IF_NOT_MSG(stats == nullptr, "IVF stats not supported");
+ DeviceScope scope(config_.device);
+ auto stream = resources_->getDefaultStream(config_.device);
+
+ FAISS_THROW_IF_NOT_MSG(
+ !store_pairs,
+ "GpuIndexIVF::search_preassigned does not "
+ "currently support store_pairs");
+ FAISS_THROW_IF_NOT_MSG(this->is_trained, "GpuIndexIVF not trained");
+ FAISS_ASSERT(baseIndex_);
+
+ validateKSelect(k);
+
+ if (n == 0 || k == 0) {
+ // nothing to search
+ return;
+ }
+
+ idx_t use_nprobe = params ? params->nprobe : this->nprobe;
+ validateNProbe(use_nprobe);
+
+ size_t max_codes = params ? params->max_codes : this->max_codes;
+ FAISS_THROW_IF_NOT_FMT(
+ max_codes == 0,
+ "GPU IVF index does not currently support "
+ "SearchParametersIVF::max_codes (passed %zu, must be 0)",
+ max_codes);
+
+ // Ensure that all data/output buffers are resident on our desired device
+ auto vecsDevice = toDeviceTemporary<float, 2>(
+ resources_.get(),
+ config_.device,
+ const_cast<float*>(x),
+ stream,
+ {n, d});
+
+ auto distanceDevice = toDeviceTemporary<float, 2>(
+ resources_.get(),
+ config_.device,
+ const_cast<float*>(centroid_dis),
+ stream,
+ {n, use_nprobe});
+
+ auto assignDevice = toDeviceTemporary<idx_t, 2>(
+ resources_.get(),
+ config_.device,
+ const_cast<idx_t*>(assign),
+ stream,
+ {n, use_nprobe});
+
+ auto outDistancesDevice = toDeviceTemporary<float, 2>(
+ resources_.get(), config_.device, distances, stream, {n, k});
+
+ auto outIndicesDevice = toDeviceTemporary<idx_t, 2>(
+ resources_.get(), config_.device, labels, stream, {n, k});
+
+ baseIndex_->searchPreassigned(
+ quantizer,
+ vecsDevice,
+ distanceDevice,
+ assignDevice,
+ k,
+ outDistancesDevice,
+ outIndicesDevice,
+ store_pairs);
+
+ // If the output was not already on the GPU, copy it back
+ fromDevice<float, 2>(outDistancesDevice, distances, stream);
+ fromDevice<idx_t, 2>(outIndicesDevice, labels, stream);
+}
+
+void GpuIndexIVF::range_search_preassigned(
+ idx_t nx,
+ const float* x,
+ float radius,
+ const idx_t* keys,
+ const float* coarse_dis,
+ RangeSearchResult* result,
+ bool store_pairs,
+ const IVFSearchParameters* params,
+ IndexIVFStats* stats) const {
+ FAISS_THROW_MSG("range search not implemented");
+}
+
+bool GpuIndexIVF::addImplRequiresIDs_() const {
+ // All IVF indices have storage for IDs
+ return true;
+}
+
+void GpuIndexIVF::trainQuantizer_(idx_t n, const float* x) {
+ DeviceScope scope(config_.device);
+
+ if (n == 0) {
+ // nothing to do
+ return;
+ }
+
+ if (quantizer->is_trained && (quantizer->ntotal == nlist)) {
+ if (this->verbose) {
+ printf("IVF quantizer does not need training.\n");
+ }
+
+ return;
+ }
+
+ if (this->verbose) {
+ printf("Training IVF quantizer on %ld vectors in %dD\n", n, d);
+ }
+
+ quantizer->reset();
+
+ // leverage the CPU-side k-means code, which works for the GPU
+ // flat index as well
+ Clustering clus(this->d, nlist, this->cp);
+ clus.verbose = verbose;
+ clus.train(n, x, *quantizer);
+
+ quantizer->is_trained = true;
+ FAISS_ASSERT(quantizer->ntotal == nlist);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVF.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVF.h
new file mode 100644
index 0000000..d6fd5b6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVF.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Clustering.h>
+#include <faiss/IndexIVF.h> // for SearchParametersIVF
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+class GpuIndexFlat;
+class IVFBase;
+
+struct GpuIndexIVFConfig : public GpuIndexConfig {
+ /// Index storage options for the GPU
+ IndicesOptions indicesOptions = INDICES_64_BIT;
+
+ /// Configuration for the coarse quantizer object
+ GpuIndexFlatConfig flatConfig;
+
+ /// This flag controls the CPU fallback logic for coarse quantizer
+ /// component of the index. When set to false (default), the cloner will
+ /// throw an exception for indices not implemented on GPU. When set to
+ /// true, it will fallback to a CPU implementation.
+ bool allowCpuCoarseQuantizer = false;
+};
+
+/// Base class of all GPU IVF index types. This (for now) deliberately does not
+/// inherit from IndexIVF, as many of the public data members and functionality
+/// in IndexIVF is not supported in the same manner on the GPU.
+class GpuIndexIVF : public GpuIndex, public IndexIVFInterface {
+ public:
+ /// Version that auto-constructs a flat coarse quantizer based on the
+ /// desired metric
+ GpuIndexIVF(
+ GpuResourcesProvider* provider,
+ int dims,
+ faiss::MetricType metric,
+ float metricArg,
+ idx_t nlist,
+ GpuIndexIVFConfig config = GpuIndexIVFConfig());
+
+ /// Version that takes a coarse quantizer instance. The GpuIndexIVF does not
+ /// own the coarseQuantizer instance by default (functions like IndexIVF).
+ GpuIndexIVF(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ faiss::MetricType metric,
+ float metricArg,
+ idx_t nlist,
+ GpuIndexIVFConfig config = GpuIndexIVFConfig());
+
+ ~GpuIndexIVF() override;
+
+ private:
+ /// Shared initialization functions
+ void init_();
+
+ public:
+ /// Copy what we need from the CPU equivalent
+ void copyFrom(const faiss::IndexIVF* index);
+
+ /// Copy what we have to the CPU equivalent
+ void copyTo(faiss::IndexIVF* index) const;
+
+ /// Should be called if the user ever changes the state of the IVF coarse
+ /// quantizer manually (e.g., substitutes a new instance or changes vectors
+ /// in the coarse quantizer outside the scope of training)
+ virtual void updateQuantizer() = 0;
+
+ /// Returns the number of inverted lists we're managing
+ virtual idx_t getNumLists() const;
+
+ /// Returns the number of vectors present in a particular inverted list
+ virtual idx_t getListLength(idx_t listId) const;
+
+ /// Return the encoded vector data contained in a particular inverted list,
+ /// for debugging purposes.
+ /// If gpuFormat is true, the data is returned as it is encoded in the
+ /// GPU-side representation.
+ /// Otherwise, it is converted to the CPU format.
+ /// compliant format, while the native GPU format may differ.
+ virtual std::vector<uint8_t> getListVectorData(
+ idx_t listId,
+ bool gpuFormat = false) const;
+
+ /// Return the vector indices contained in a particular inverted list, for
+ /// debugging purposes.
+ virtual std::vector<idx_t> getListIndices(idx_t listId) const;
+
+ void search_preassigned(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ const idx_t* assign,
+ const float* centroid_dis,
+ float* distances,
+ idx_t* labels,
+ bool store_pairs,
+ const SearchParametersIVF* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ // not implemented for GPU
+ void range_search_preassigned(
+ idx_t nx,
+ const float* x,
+ float radius,
+ const idx_t* keys,
+ const float* coarse_dis,
+ RangeSearchResult* result,
+ bool store_pairs = false,
+ const IVFSearchParameters* params = nullptr,
+ IndexIVFStats* stats = nullptr) const override;
+
+ protected:
+ /// From either the current set nprobe or the SearchParameters if available,
+ /// return the nprobe that we should use for the current search
+ int getCurrentNProbe_(const SearchParameters* params) const;
+ void verifyIVFSettings_() const;
+ bool addImplRequiresIDs_() const override;
+ virtual void trainQuantizer_(idx_t n, const float* x);
+
+ /// Called from GpuIndex for add/add_with_ids
+ void addImpl_(idx_t n, const float* x, const idx_t* ids) override;
+
+ /// Called from GpuIndex for search
+ void searchImpl_(
+ idx_t n,
+ const float* x,
+ int k,
+ float* distances,
+ idx_t* labels,
+ const SearchParameters* params) const override;
+
+ protected:
+ /// Our configuration options
+ const GpuIndexIVFConfig ivfConfig_;
+
+ /// For a trained/initialized index, this is a reference to the base class
+ std::shared_ptr<IVFBase> baseIndex_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFFlat.cu
new file mode 100644
index 0000000..eb5dacc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFFlat.cu
@@ -0,0 +1,392 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/impl/IVFFlat.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+
+#if defined USE_NVIDIA_CUVS
+#include <cuvs/neighbors/ivf_flat.hpp>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <faiss/gpu/impl/CuvsIVFFlat.cuh>
+#endif
+
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+GpuIndexIVFFlat::GpuIndexIVFFlat(
+ GpuResourcesProvider* provider,
+ const faiss::IndexIVFFlat* index,
+ GpuIndexIVFFlatConfig config)
+ : GpuIndexIVF(
+ provider,
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ index->nlist,
+ config),
+ ivfFlatConfig_(config),
+ reserveMemoryVecs_(0) {
+ copyFrom(index);
+}
+
+GpuIndexIVFFlat::GpuIndexIVFFlat(
+ GpuResourcesProvider* provider,
+ int dims,
+ idx_t nlist,
+ faiss::MetricType metric,
+ GpuIndexIVFFlatConfig config)
+ : GpuIndexIVF(provider, dims, metric, 0, nlist, config),
+ ivfFlatConfig_(config),
+ reserveMemoryVecs_(0) {
+ // We haven't trained ourselves, so don't construct the IVFFlat
+ // index yet
+}
+
+GpuIndexIVFFlat::GpuIndexIVFFlat(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ idx_t nlist,
+ faiss::MetricType metric,
+ GpuIndexIVFFlatConfig config)
+ : GpuIndexIVF(
+ provider,
+ coarseQuantizer,
+ dims,
+ metric,
+ 0,
+ nlist,
+ config),
+ ivfFlatConfig_(config),
+ reserveMemoryVecs_(0) {
+ // We could have been passed an already trained coarse quantizer. There is
+ // no other quantizer that we need to train, so this is sufficient
+ if (this->is_trained) {
+ FAISS_ASSERT(this->quantizer);
+ setIndex_(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ this->metric_type,
+ this->metric_arg,
+ false, // no residual
+ nullptr, // no scalar quantizer
+ ivfFlatConfig_.interleavedLayout,
+ ivfFlatConfig_.indicesOptions,
+ config_.memorySpace);
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFFlat>(index_);
+ updateQuantizer();
+ }
+}
+
+GpuIndexIVFFlat::~GpuIndexIVFFlat() {}
+
+void GpuIndexIVFFlat::reserveMemory(size_t numVecs) {
+ DeviceScope scope(config_.device);
+
+ if (should_use_cuvs(config_)) {
+ FAISS_THROW_MSG(
+ "Pre-allocation of IVF lists is not supported with cuVS enabled.");
+ }
+
+ reserveMemoryVecs_ = numVecs;
+ if (index_) {
+ index_->reserveMemory(numVecs);
+ }
+}
+
+void GpuIndexIVFFlat::copyFrom(const faiss::IndexIVFFlat* index) {
+ DeviceScope scope(config_.device);
+
+ // This will copy GpuIndexIVF data such as the coarse quantizer
+ GpuIndexIVF::copyFrom(index);
+
+ // Clear out our old data
+ index_.reset();
+
+ // skip base class allocations if cuVS is enabled
+ if (!should_use_cuvs(config_)) {
+ baseIndex_.reset();
+ }
+
+ // The other index might not be trained
+ if (!index->is_trained) {
+ FAISS_ASSERT(!is_trained);
+ return;
+ }
+
+ // Otherwise, we can populate ourselves from the other index
+ FAISS_ASSERT(is_trained);
+
+ // Copy our lists as well
+ setIndex_(
+ resources_.get(),
+ d,
+ nlist,
+ index->metric_type,
+ index->metric_arg,
+ false, // no residual
+ nullptr, // no scalar quantizer
+ ivfFlatConfig_.interleavedLayout,
+ ivfFlatConfig_.indicesOptions,
+ config_.memorySpace);
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFFlat>(index_);
+ updateQuantizer();
+
+ // Copy all of the IVF data
+ index_->copyInvertedListsFrom(index->invlists);
+}
+
+void GpuIndexIVFFlat::copyTo(faiss::IndexIVFFlat* index) const {
+ DeviceScope scope(config_.device);
+
+ // We must have the indices in order to copy to ourselves
+ FAISS_THROW_IF_NOT_MSG(
+ ivfFlatConfig_.indicesOptions != INDICES_IVF,
+ "Cannot copy to CPU as GPU index doesn't retain "
+ "indices (INDICES_IVF)");
+
+ GpuIndexIVF::copyTo(index);
+ index->code_size = this->d * sizeof(float);
+
+ auto ivf = new ArrayInvertedLists(nlist, index->code_size);
+ index->replace_invlists(ivf, true);
+
+ if (index_) {
+ // Copy IVF lists
+ index_->copyInvertedListsTo(ivf);
+ }
+}
+
+size_t GpuIndexIVFFlat::reclaimMemory() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ return index_->reclaimMemory();
+ }
+
+ return 0;
+}
+
+void GpuIndexIVFFlat::reset() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ index_->reset();
+ this->ntotal = 0;
+ } else {
+ FAISS_ASSERT(this->ntotal == 0);
+ }
+}
+
+void GpuIndexIVFFlat::updateQuantizer() {
+ FAISS_THROW_IF_NOT_MSG(
+ quantizer, "Calling updateQuantizer without a quantizer instance");
+
+ // Only need to do something if we are already initialized
+ if (index_) {
+ index_->updateQuantizer(quantizer);
+ }
+}
+
+void GpuIndexIVFFlat::train(idx_t n, const float* x) {
+ DeviceScope scope(config_.device);
+
+ // just in case someone changed our quantizer
+ verifyIVFSettings_();
+
+ if (this->is_trained) {
+ FAISS_ASSERT(index_);
+ if (should_use_cuvs(config_)) {
+ // copy the IVF centroids to the cuVS index
+ // in case it has been reset. This is because `reset` clears the
+ // cuVS index and its centroids.
+ // TODO: change this once the coarse quantizer is separated from
+ // cuVS index
+ updateQuantizer();
+ };
+ return;
+ }
+
+ FAISS_ASSERT(!index_);
+
+ if (should_use_cuvs(config_)) {
+#if defined USE_NVIDIA_CUVS
+ setIndex_(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ this->metric_type,
+ this->metric_arg,
+ false, // no residual
+ nullptr, // no scalar quantizer
+ ivfFlatConfig_.interleavedLayout,
+ ivfFlatConfig_.indicesOptions,
+ config_.memorySpace);
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ cuvs::neighbors::ivf_flat::index_params cuvs_index_params;
+ cuvs_index_params.n_lists = nlist;
+ cuvs_index_params.metric = metricFaissToCuvs(metric_type, false);
+ cuvs_index_params.add_data_on_build = false;
+ cuvs_index_params.kmeans_trainset_fraction =
+ static_cast<double>(cp.max_points_per_centroid * nlist) /
+ static_cast<double>(n);
+ cuvs_index_params.kmeans_n_iters = cp.niter;
+
+ auto cuvsIndex_ =
+ std::static_pointer_cast<CuvsIVFFlat, IVFFlat>(index_);
+
+ std::optional<cuvs::neighbors::ivf_flat::index<float, idx_t>>
+ cuvs_ivfflat_index;
+
+ if (getDeviceForAddress(x) >= 0) {
+ auto dataset_d =
+ raft::make_device_matrix_view<const float, idx_t>(x, n, d);
+ cuvs_ivfflat_index = cuvs::neighbors::ivf_flat::build(
+ raft_handle, cuvs_index_params, dataset_d);
+ } else {
+ auto dataset_h =
+ raft::make_host_matrix_view<const float, idx_t>(x, n, d);
+ cuvs_ivfflat_index = cuvs::neighbors::ivf_flat::build(
+ raft_handle, cuvs_index_params, dataset_h);
+ }
+
+ quantizer->train(
+ nlist, cuvs_ivfflat_index.value().centers().data_handle());
+ quantizer->add(
+ nlist, cuvs_ivfflat_index.value().centers().data_handle());
+ raft_handle.sync_stream();
+
+ cuvsIndex_->setCuvsIndex(std::move(*cuvs_ivfflat_index));
+#else
+ FAISS_THROW_MSG(
+ "cuVS has not been compiled into the current version so it cannot be used.");
+#endif
+ } else {
+ // FIXME: GPUize more of this
+ // First, make sure that the data is resident on the CPU, if it is not
+ // on the CPU, as we depend upon parts of the CPU code
+ auto hostData = toHost<float, 2>(
+ (float*)x,
+ resources_->getDefaultStream(config_.device),
+ {n, this->d});
+ trainQuantizer_(n, hostData.data());
+
+ setIndex_(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ this->metric_type,
+ this->metric_arg,
+ false, // no residual
+ nullptr, // no scalar quantizer
+ ivfFlatConfig_.interleavedLayout,
+ ivfFlatConfig_.indicesOptions,
+ config_.memorySpace);
+ updateQuantizer();
+ }
+
+ // The quantizer is now trained; construct the IVF index
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFFlat>(index_);
+
+ if (reserveMemoryVecs_) {
+ if (should_use_cuvs(config_)) {
+ FAISS_THROW_MSG(
+ "Pre-allocation of IVF lists is not supported with cuVS enabled.");
+ } else
+ index_->reserveMemory(reserveMemoryVecs_);
+ }
+
+ this->is_trained = true;
+}
+
+void GpuIndexIVFFlat::setIndex_(
+ GpuResources* resources,
+ int dim,
+ int nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ /// Optional ScalarQuantizer
+ faiss::ScalarQuantizer* scalarQ,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space) {
+ if (should_use_cuvs(config_)) {
+#if defined USE_NVIDIA_CUVS
+ FAISS_THROW_IF_NOT_MSG(
+ ivfFlatConfig_.indicesOptions == INDICES_64_BIT,
+ "cuVS only supports INDICES_64_BIT");
+ if (!ivfFlatConfig_.interleavedLayout) {
+ fprintf(stderr,
+ "WARN: interleavedLayout is set to False with cuVS enabled. This will be ignored.\n");
+ }
+ index_.reset(new CuvsIVFFlat(
+ resources,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ useResidual,
+ scalarQ,
+ interleavedLayout,
+ indicesOptions,
+ space));
+#else
+ FAISS_THROW_MSG(
+ "cuVS has not been compiled into the current version so it cannot be used.");
+#endif
+ } else {
+ index_.reset(new IVFFlat(
+ resources,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ useResidual,
+ scalarQ,
+ interleavedLayout,
+ indicesOptions,
+ space));
+ }
+}
+
+void GpuIndexIVFFlat::reconstruct_n(idx_t i0, idx_t ni, float* out) const {
+ FAISS_ASSERT(index_);
+
+ if (ni == 0) {
+ // nothing to do
+ return;
+ }
+
+ FAISS_THROW_IF_NOT_FMT(
+ i0 < this->ntotal,
+ "start index (%zu) out of bounds (ntotal %zu)",
+ i0,
+ this->ntotal);
+ FAISS_THROW_IF_NOT_FMT(
+ i0 + ni - 1 < this->ntotal,
+ "max index requested (%zu) out of bounds (ntotal %zu)",
+ i0 + ni - 1,
+ this->ntotal);
+
+ index_->reconstruct_n(i0, ni, out);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFFlat.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFFlat.h
new file mode 100644
index 0000000..d6826cd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFFlat.h
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/GpuIndexIVF.h>
+#include <faiss/impl/ScalarQuantizer.h>
+
+#include <memory>
+
+namespace faiss {
+struct IndexIVFFlat;
+}
+
+namespace faiss {
+namespace gpu {
+
+class IVFFlat;
+class GpuIndexFlat;
+
+struct GpuIndexIVFFlatConfig : public GpuIndexIVFConfig {
+ /// Use the alternative memory layout for the IVF lists
+ /// (currently the default)
+ bool interleavedLayout = true;
+};
+
+/// Wrapper around the GPU implementation that looks like
+/// faiss::IndexIVFFlat
+class GpuIndexIVFFlat : public GpuIndexIVF {
+ public:
+ /// Construct from a pre-existing faiss::IndexIVFFlat instance, copying
+ /// data over to the given GPU, if the input index is trained.
+ GpuIndexIVFFlat(
+ GpuResourcesProvider* provider,
+ const faiss::IndexIVFFlat* index,
+ GpuIndexIVFFlatConfig config = GpuIndexIVFFlatConfig());
+
+ /// Constructs a new instance with an empty flat quantizer; the user
+ /// provides the number of IVF lists desired.
+ GpuIndexIVFFlat(
+ GpuResourcesProvider* provider,
+ int dims,
+ idx_t nlist,
+ faiss::MetricType metric = faiss::METRIC_L2,
+ GpuIndexIVFFlatConfig config = GpuIndexIVFFlatConfig());
+
+ /// Constructs a new instance with a provided CPU or GPU coarse quantizer;
+ /// the user provides the number of IVF lists desired.
+ GpuIndexIVFFlat(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ idx_t nlist,
+ faiss::MetricType metric = faiss::METRIC_L2,
+ GpuIndexIVFFlatConfig config = GpuIndexIVFFlatConfig());
+
+ ~GpuIndexIVFFlat() override;
+
+ /// Reserve GPU memory in our inverted lists for this number of vectors
+ void reserveMemory(size_t numVecs);
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(const faiss::IndexIVFFlat* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexIVFFlat* index) const;
+
+ /// After adding vectors, one can call this to reclaim device memory
+ /// to exactly the amount needed. Returns space reclaimed in bytes
+ size_t reclaimMemory();
+
+ /// Clears out all inverted lists, but retains the coarse centroid
+ /// information
+ void reset() override;
+
+ /// Should be called if the user ever changes the state of the IVF coarse
+ /// quantizer manually (e.g., substitutes a new instance or changes vectors
+ /// in the coarse quantizer outside the scope of training)
+ void updateQuantizer() override;
+
+ /// Trains the coarse quantizer based on the given vector data
+ void train(idx_t n, const float* x) override;
+
+ void reconstruct_n(idx_t i0, idx_t n, float* out) const override;
+
+ protected:
+ /// Initialize appropriate index
+ void setIndex_(
+ GpuResources* resources,
+ int dim,
+ int nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ /// Optional ScalarQuantizer
+ faiss::ScalarQuantizer* scalarQ,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ protected:
+ /// Our configuration options
+ const GpuIndexIVFFlatConfig ivfFlatConfig_;
+
+ /// Desired inverted list memory reservation
+ size_t reserveMemoryVecs_;
+
+ /// Instance that we own; contains the inverted lists
+ std::shared_ptr<IVFFlat> index_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFPQ.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFPQ.cu
new file mode 100644
index 0000000..da0e5ac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFPQ.cu
@@ -0,0 +1,616 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/utils/utils.h>
+#include <faiss/gpu/impl/IVFPQ.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+
+#if defined USE_NVIDIA_CUVS
+#include <cuvs/neighbors/ivf_pq.hpp>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <faiss/gpu/impl/CuvsIVFPQ.cuh>
+#endif
+
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+GpuIndexIVFPQ::GpuIndexIVFPQ(
+ GpuResourcesProvider* provider,
+ const faiss::IndexIVFPQ* index,
+ GpuIndexIVFPQConfig config)
+ : GpuIndexIVF(
+ provider,
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ index->nlist,
+ config),
+ pq(index->pq),
+ ivfpqConfig_(config),
+ usePrecomputedTables_(config.usePrecomputedTables),
+ subQuantizers_(0),
+ bitsPerCode_(0),
+ reserveMemoryVecs_(0) {
+ copyFrom(index);
+}
+
+GpuIndexIVFPQ::GpuIndexIVFPQ(
+ GpuResourcesProvider* provider,
+ int dims,
+ idx_t nlist,
+ idx_t subQuantizers,
+ idx_t bitsPerCode,
+ faiss::MetricType metric,
+ GpuIndexIVFPQConfig config)
+ : GpuIndexIVF(provider, dims, metric, 0, nlist, config),
+ pq(dims, subQuantizers, bitsPerCode),
+ ivfpqConfig_(config),
+ usePrecomputedTables_(config.usePrecomputedTables),
+ subQuantizers_(subQuantizers),
+ bitsPerCode_(bitsPerCode),
+ reserveMemoryVecs_(0) {
+ verifyPQSettings_();
+}
+
+GpuIndexIVFPQ::GpuIndexIVFPQ(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ idx_t nlist,
+ idx_t subQuantizers,
+ idx_t bitsPerCode,
+ faiss::MetricType metric,
+ GpuIndexIVFPQConfig config)
+ : GpuIndexIVF(
+ provider,
+ coarseQuantizer,
+ dims,
+ metric,
+ 0,
+ nlist,
+ config),
+ pq(dims, subQuantizers, bitsPerCode),
+ ivfpqConfig_(config),
+ usePrecomputedTables_(config.usePrecomputedTables),
+ subQuantizers_(subQuantizers),
+ bitsPerCode_(bitsPerCode),
+ reserveMemoryVecs_(0) {
+ // While we were passed an existing coarse quantizer instance (possibly
+ // trained or not), we have not yet trained our product quantizer, so we are
+ // not ourselves fully trained and we can not yet construct our index_
+ // instance
+ this->is_trained = false;
+
+ FAISS_THROW_IF_NOT_MSG(
+ !config.use_cuvs,
+ "GpuIndexIVFPQ: cuVS does not support separate coarseQuantizer");
+
+ verifyPQSettings_();
+}
+
+GpuIndexIVFPQ::~GpuIndexIVFPQ() {}
+
+void GpuIndexIVFPQ::copyFrom(const faiss::IndexIVFPQ* index) {
+ DeviceScope scope(config_.device);
+
+ // This will copy GpuIndexIVF data such as the coarse quantizer
+ GpuIndexIVF::copyFrom(index);
+
+ // Clear out our old data
+ index_.reset();
+
+ // skip base class allocations if cuVS is enabled
+ if (!should_use_cuvs(config_)) {
+ baseIndex_.reset();
+ }
+
+ pq = index->pq;
+ subQuantizers_ = index->pq.M;
+ bitsPerCode_ = index->pq.nbits;
+
+ // We only support this
+ FAISS_THROW_IF_NOT_MSG(
+ ivfpqConfig_.interleavedLayout || index->pq.nbits == 8,
+ "GPU: only pq.nbits == 8 is supported");
+ FAISS_THROW_IF_NOT_MSG(
+ index->by_residual, "GPU: only by_residual = true is supported");
+ FAISS_THROW_IF_NOT_MSG(
+ index->polysemous_ht == 0, "GPU: polysemous codes not supported");
+
+ verifyPQSettings_();
+
+ // The other index might not be trained
+ if (!index->is_trained) {
+ // copied in GpuIndex::copyFrom
+ FAISS_ASSERT(!is_trained);
+ return;
+ }
+
+ // Copy our lists as well
+ // The product quantizer must have data in it
+ FAISS_ASSERT(index->pq.centroids.size() > 0);
+ setIndex_(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ index->metric_type,
+ index->metric_arg,
+ subQuantizers_,
+ bitsPerCode_,
+ ivfpqConfig_.useFloat16LookupTables,
+ ivfpqConfig_.useMMCodeDistance,
+ ivfpqConfig_.interleavedLayout,
+ (float*)index->pq.centroids.data(),
+ ivfpqConfig_.indicesOptions,
+ config_.memorySpace);
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFPQ>(index_);
+
+ // Doesn't make sense to reserve memory here
+ FAISS_ASSERT(quantizer);
+ updateQuantizer();
+
+ index_->setPrecomputedCodes(quantizer, usePrecomputedTables_);
+
+ // Copy all of the IVF data
+ index_->copyInvertedListsFrom(index->invlists);
+}
+
+void GpuIndexIVFPQ::copyTo(faiss::IndexIVFPQ* index) const {
+ DeviceScope scope(config_.device);
+
+ // We must have the indices in order to copy to ourselves
+ FAISS_THROW_IF_NOT_MSG(
+ ivfpqConfig_.indicesOptions != INDICES_IVF,
+ "Cannot copy to CPU as GPU index doesn't retain "
+ "indices (INDICES_IVF)");
+
+ GpuIndexIVF::copyTo(index);
+
+ //
+ // IndexIVFPQ information
+ //
+ index->by_residual = true;
+ index->use_precomputed_table = 0;
+ index->code_size = utils::divUp(subQuantizers_ * bitsPerCode_, 8);
+ index->pq = faiss::ProductQuantizer(this->d, subQuantizers_, bitsPerCode_);
+
+ index->do_polysemous_training = false;
+ index->polysemous_training = nullptr;
+
+ index->scan_table_threshold = 0;
+ index->max_codes = 0;
+ index->polysemous_ht = 0;
+ index->precomputed_table.clear();
+
+ auto ivf = new ArrayInvertedLists(nlist, index->code_size);
+ index->replace_invlists(ivf, true);
+
+ if (index_) {
+ // Copy IVF lists
+ index_->copyInvertedListsTo(ivf);
+
+ // Copy PQ centroids
+ auto devPQCentroids = index_->getPQCentroids();
+ index->pq.centroids.resize(devPQCentroids.numElements());
+
+ fromDevice<float, 3>(
+ devPQCentroids,
+ index->pq.centroids.data(),
+ resources_->getDefaultStream(config_.device));
+
+ if (usePrecomputedTables_) {
+ index->precompute_table();
+ }
+ }
+}
+
+void GpuIndexIVFPQ::reserveMemory(size_t numVecs) {
+ DeviceScope scope(config_.device);
+
+ reserveMemoryVecs_ = numVecs;
+ if (index_) {
+ index_->reserveMemory(numVecs);
+ }
+}
+
+void GpuIndexIVFPQ::setPrecomputedCodes(bool enable) {
+ DeviceScope scope(config_.device);
+
+ usePrecomputedTables_ = enable;
+ if (index_) {
+ FAISS_ASSERT(quantizer);
+ index_->setPrecomputedCodes(quantizer, enable);
+ }
+
+ verifyPQSettings_();
+}
+
+bool GpuIndexIVFPQ::getPrecomputedCodes() const {
+ return usePrecomputedTables_;
+}
+
+int GpuIndexIVFPQ::getNumSubQuantizers() const {
+ return subQuantizers_;
+}
+
+int GpuIndexIVFPQ::getBitsPerCode() const {
+ return bitsPerCode_;
+}
+
+int GpuIndexIVFPQ::getCentroidsPerSubQuantizer() const {
+ return utils::pow2(bitsPerCode_);
+}
+
+size_t GpuIndexIVFPQ::reclaimMemory() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ return index_->reclaimMemory();
+ }
+
+ return 0;
+}
+
+void GpuIndexIVFPQ::reset() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ index_->reset();
+ this->ntotal = 0;
+ } else {
+ FAISS_ASSERT(this->ntotal == 0);
+ }
+}
+
+void GpuIndexIVFPQ::updateQuantizer() {
+ FAISS_THROW_IF_NOT_MSG(
+ quantizer, "Calling updateQuantizer without a quantizer instance");
+
+ // Only need to do something if we are already initialized
+ if (index_) {
+ index_->updateQuantizer(quantizer);
+ }
+}
+
+void GpuIndexIVFPQ::trainResidualQuantizer_(idx_t n, const float* x) {
+ // Code largely copied from faiss::IndexIVFPQ
+ auto x_in = x;
+
+ x = fvecs_maybe_subsample(
+ d,
+ (size_t*)&n,
+ pq.cp.max_points_per_centroid * pq.ksub,
+ x,
+ verbose,
+ pq.cp.seed);
+
+ std::unique_ptr<const float[]> del_x(x_in == x ? nullptr : x);
+
+ if (this->verbose) {
+ printf("computing residuals\n");
+ }
+
+ std::vector<idx_t> assign(n);
+ quantizer->assign(n, x, assign.data());
+
+ std::vector<float> residuals(n * d);
+ quantizer->compute_residual_n(n, x, residuals.data(), assign.data());
+
+ if (this->verbose) {
+ printf("training %d x %d product quantizer on %ld vectors in %dD\n",
+ subQuantizers_,
+ getCentroidsPerSubQuantizer(),
+ n,
+ this->d);
+ }
+
+ // For PQ training purposes, accelerate it by using a GPU clustering index
+ // if a clustering index has not already been assigned
+ if (!pq.assign_index) {
+ try {
+ GpuIndexFlatConfig config;
+ config.device = ivfpqConfig_.device;
+ config.use_cuvs = false;
+ GpuIndexFlatL2 pqIndex(resources_, pq.dsub, config);
+
+ pq.assign_index = &pqIndex;
+ pq.train(n, residuals.data());
+ } catch (...) {
+ pq.assign_index = nullptr;
+ throw;
+ }
+
+ pq.assign_index = nullptr;
+ } else {
+ // use the currently assigned clustering index
+ pq.train(n, residuals.data());
+ }
+}
+
+void GpuIndexIVFPQ::train(idx_t n, const float* x) {
+ DeviceScope scope(config_.device);
+
+ // just in case someone changed us
+ verifyPQSettings_();
+ verifyIVFSettings_();
+
+ if (this->is_trained) {
+ FAISS_ASSERT(index_);
+ if (should_use_cuvs(config_)) {
+ // if cuVS is enabled, copy the IVF centroids to the cuVS index in
+ // case it has been reset. This is because reset clears the cuVS
+ // index and its centroids.
+ // TODO: change this once the coarse quantizer is separated from
+ // cuVS index
+ updateQuantizer();
+ };
+ return;
+ }
+
+ FAISS_ASSERT(!index_);
+
+ // cuVS does not support using an external index for assignment. Fall back
+ // to the classical GPU impl
+ if (should_use_cuvs(config_)) {
+#if defined USE_NVIDIA_CUVS
+ if (pq.assign_index) {
+ fprintf(stderr,
+ "WARN: The Product Quantizer's assign_index will be ignored with cuVS enabled.\n");
+ }
+ // first initialize the index. The PQ centroids will be updated
+ // retroactively.
+ setIndex_(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ metric_type,
+ metric_arg,
+ subQuantizers_,
+ bitsPerCode_,
+ ivfpqConfig_.useFloat16LookupTables,
+ ivfpqConfig_.useMMCodeDistance,
+ ivfpqConfig_.interleavedLayout,
+ pq.centroids.data(),
+ ivfpqConfig_.indicesOptions,
+ config_.memorySpace);
+ // No need to copy the data to host
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ cuvs::neighbors::ivf_pq::index_params cuvs_index_params;
+ cuvs_index_params.n_lists = nlist;
+ cuvs_index_params.metric = metricFaissToCuvs(metric_type, false);
+ cuvs_index_params.kmeans_trainset_fraction =
+ static_cast<double>(cp.max_points_per_centroid * nlist) /
+ static_cast<double>(n);
+ cuvs_index_params.kmeans_n_iters = cp.niter;
+ cuvs_index_params.pq_bits = bitsPerCode_;
+ cuvs_index_params.pq_dim = subQuantizers_;
+ cuvs_index_params.conservative_memory_allocation = false;
+ cuvs_index_params.add_data_on_build = false;
+
+ auto cuvsIndex_ = std::static_pointer_cast<CuvsIVFPQ, IVFPQ>(index_);
+
+ std::optional<cuvs::neighbors::ivf_pq::index<idx_t>> cuvs_ivfpq_index;
+
+ if (getDeviceForAddress(x) >= 0) {
+ auto dataset_d =
+ raft::make_device_matrix_view<const float, idx_t>(x, n, d);
+ cuvs_ivfpq_index = cuvs::neighbors::ivf_pq::build(
+ raft_handle, cuvs_index_params, dataset_d);
+ } else {
+ auto dataset_h =
+ raft::make_host_matrix_view<const float, idx_t>(x, n, d);
+ cuvs_ivfpq_index = cuvs::neighbors::ivf_pq::build(
+ raft_handle, cuvs_index_params, dataset_h);
+ }
+
+ auto cluster_centers = raft::make_device_matrix<float>(
+ raft_handle,
+ cuvs_ivfpq_index.value().n_lists(),
+ cuvs_ivfpq_index.value().dim());
+ cuvs::neighbors::ivf_pq::helpers::extract_centers(
+ raft_handle, cuvs_ivfpq_index.value(), cluster_centers.view());
+
+ quantizer->train(nlist, cluster_centers.data_handle());
+ quantizer->add(nlist, cluster_centers.data_handle());
+
+ raft::copy(
+ pq.get_centroids(0, 0),
+ cuvs_ivfpq_index.value().pq_centers().data_handle(),
+ cuvs_ivfpq_index.value().pq_centers().size(),
+ raft_handle.get_stream());
+ raft_handle.sync_stream();
+ cuvsIndex_->setCuvsIndex(std::move(*cuvs_ivfpq_index));
+#else
+ FAISS_THROW_MSG(
+ "cuVS has not been compiled into the current version so it cannot be used.");
+#endif
+ } else {
+ // FIXME: GPUize more of this
+ // First, make sure that the data is resident on the CPU, if it is not
+ // on the CPU, as we depend upon parts of the CPU code
+ auto hostData = toHost<float, 2>(
+ (float*)x,
+ resources_->getDefaultStream(config_.device),
+ {n, this->d});
+
+ trainQuantizer_(n, hostData.data());
+ trainResidualQuantizer_(n, hostData.data());
+
+ setIndex_(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ metric_type,
+ metric_arg,
+ subQuantizers_,
+ bitsPerCode_,
+ ivfpqConfig_.useFloat16LookupTables,
+ ivfpqConfig_.useMMCodeDistance,
+ ivfpqConfig_.interleavedLayout,
+ pq.centroids.data(),
+ ivfpqConfig_.indicesOptions,
+ config_.memorySpace);
+ updateQuantizer();
+ }
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFPQ>(index_);
+
+ if (reserveMemoryVecs_) {
+ index_->reserveMemory(reserveMemoryVecs_);
+ }
+
+ index_->setPrecomputedCodes(quantizer, usePrecomputedTables_);
+
+ FAISS_ASSERT(index_);
+
+ this->is_trained = true;
+}
+
+void GpuIndexIVFPQ::setIndex_(
+ GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ int numSubQuantizers,
+ int bitsPerSubQuantizer,
+ bool useFloat16LookupTables,
+ bool useMMCodeDistance,
+ bool interleavedLayout,
+ float* pqCentroidData,
+ IndicesOptions indicesOptions,
+ MemorySpace space) {
+ if (should_use_cuvs(config_)) {
+#if defined USE_NVIDIA_CUVS
+ index_.reset(new CuvsIVFPQ(
+ resources,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ numSubQuantizers,
+ bitsPerSubQuantizer,
+ useFloat16LookupTables,
+ useMMCodeDistance,
+ interleavedLayout,
+ pqCentroidData,
+ indicesOptions,
+ space));
+#else
+ FAISS_THROW_MSG(
+ "cuVS has not been compiled into the current version so it cannot be used.");
+#endif
+ } else {
+ index_.reset(new IVFPQ(
+ resources,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ numSubQuantizers,
+ bitsPerSubQuantizer,
+ useFloat16LookupTables,
+ useMMCodeDistance,
+ interleavedLayout,
+ pqCentroidData,
+ indicesOptions,
+ space));
+ }
+}
+
+void GpuIndexIVFPQ::verifyPQSettings_() const {
+ // Our implementation has these restrictions:
+
+ // Must have some number of lists
+ FAISS_THROW_IF_NOT_MSG(nlist > 0, "nlist must be >0");
+
+ // up to a single byte per code
+ if (should_use_cuvs(config_)) {
+ if (!ivfpqConfig_.interleavedLayout) {
+ fprintf(stderr,
+ "WARN: interleavedLayout is set to False with cuVS enabled. This will be ignored.\n");
+ }
+ FAISS_THROW_IF_NOT_FMT(
+ bitsPerCode_ >= 4 && bitsPerCode_ <= 8,
+ "Bits per code must be within closed range [4,8] (passed %d)",
+ bitsPerCode_);
+ FAISS_THROW_IF_NOT_FMT(
+ (bitsPerCode_ * subQuantizers_) % 8 == 0,
+ "`Bits per code * number of sub-quantizers must be a multiple of 8, (passed %u * %u = %u).",
+ bitsPerCode_,
+ subQuantizers_,
+ bitsPerCode_ * subQuantizers_);
+ } else {
+ if (ivfpqConfig_.interleavedLayout) {
+ FAISS_THROW_IF_NOT_FMT(
+ bitsPerCode_ == 4 || bitsPerCode_ == 5 ||
+ bitsPerCode_ == 6 || bitsPerCode_ == 8,
+ "Bits per code must be between 4, 5, 6 or 8 (passed %d)",
+ bitsPerCode_);
+ } else {
+ FAISS_THROW_IF_NOT_FMT(
+ bitsPerCode_ == 8,
+ "Bits per code must be 8 (passed %d)",
+ bitsPerCode_);
+ }
+ }
+
+ // The number of bytes per encoded vector must be one we support
+ FAISS_THROW_IF_NOT_FMT(
+ ivfpqConfig_.interleavedLayout ||
+ IVFPQ::isSupportedPQCodeLength(subQuantizers_),
+ "Number of bytes per encoded vector / sub-quantizers (%d) "
+ "is not supported",
+ subQuantizers_);
+
+ if (!should_use_cuvs(config_)) {
+ // Sub-quantizers must evenly divide dimensions available
+ FAISS_THROW_IF_NOT_FMT(
+ this->d % subQuantizers_ == 0,
+ "Number of sub-quantizers (%d) must be an "
+ "even divisor of the number of dimensions (%d)",
+ subQuantizers_,
+ this->d);
+
+ // We must have enough shared memory on the current device to store
+ // our lookup distances
+ int lookupTableSize = sizeof(float);
+ if (ivfpqConfig_.useFloat16LookupTables) {
+ lookupTableSize = sizeof(half);
+ }
+
+ // 64 bytes per code is only supported with usage of float16, at 2^8
+ // codes per subquantizer
+ size_t requiredSmemSize =
+ lookupTableSize * subQuantizers_ * utils::pow2(bitsPerCode_);
+ size_t smemPerBlock = getMaxSharedMemPerBlock(config_.device);
+
+ FAISS_THROW_IF_NOT_FMT(
+ requiredSmemSize <= getMaxSharedMemPerBlock(config_.device),
+ "Device %d has %zu bytes of shared memory, while "
+ "%d bits per code and %d sub-quantizers requires %zu "
+ "bytes. Consider useFloat16LookupTables and/or "
+ "reduce parameters",
+ config_.device,
+ smemPerBlock,
+ bitsPerCode_,
+ subQuantizers_,
+ requiredSmemSize);
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFPQ.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFPQ.h
new file mode 100644
index 0000000..072a0d8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFPQ.h
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/GpuIndexIVF.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <memory>
+#include <vector>
+
+namespace faiss {
+struct IndexIVFPQ;
+}
+
+namespace faiss {
+namespace gpu {
+
+class GpuIndexFlat;
+class IVFPQ;
+
+struct GpuIndexIVFPQConfig : public GpuIndexIVFConfig {
+ /// Whether or not float16 residual distance tables are used in the
+ /// list scanning kernels. When subQuantizers * 2^bitsPerCode >
+ /// 16384, this is required.
+ bool useFloat16LookupTables = false;
+
+ /// Whether or not we enable the precomputed table option for
+ /// search, which can substantially increase the memory requirement.
+ bool usePrecomputedTables = false;
+
+ /// Use the alternative memory layout for the IVF lists
+ /// WARNING: this is a feature under development, and is only supported with
+ /// cuVS enabled for the index. Do not use if cuVS is not enabled.
+ bool interleavedLayout = false;
+
+ /// Use GEMM-backed computation of PQ code distances for the no precomputed
+ /// table version of IVFPQ.
+ /// This is for debugging purposes, it should not substantially affect the
+ /// results one way for another.
+ ///
+ /// Note that MM code distance is enabled automatically if one uses a number
+ /// of dimensions per sub-quantizer that is not natively specialized (an odd
+ /// number like 7 or so).
+ bool useMMCodeDistance = false;
+};
+
+/// IVFPQ index for the GPU
+class GpuIndexIVFPQ : public GpuIndexIVF {
+ public:
+ /// Construct from a pre-existing faiss::IndexIVFPQ instance, copying
+ /// data over to the given GPU, if the input index is trained.
+ GpuIndexIVFPQ(
+ GpuResourcesProvider* provider,
+ const faiss::IndexIVFPQ* index,
+ GpuIndexIVFPQConfig config = GpuIndexIVFPQConfig());
+
+ /// Constructs a new instance with an empty flat quantizer; the user
+ /// provides the number of IVF lists desired.
+ GpuIndexIVFPQ(
+ GpuResourcesProvider* provider,
+ int dims,
+ idx_t nlist,
+ idx_t subQuantizers,
+ idx_t bitsPerCode,
+ faiss::MetricType metric = faiss::METRIC_L2,
+ GpuIndexIVFPQConfig config = GpuIndexIVFPQConfig());
+
+ /// Constructs a new instance with a provided CPU or GPU coarse quantizer;
+ /// the user provides the number of IVF lists desired.
+ GpuIndexIVFPQ(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ idx_t nlist,
+ idx_t subQuantizers,
+ idx_t bitsPerCode,
+ faiss::MetricType metric = faiss::METRIC_L2,
+ GpuIndexIVFPQConfig config = GpuIndexIVFPQConfig());
+
+ ~GpuIndexIVFPQ() override;
+
+ /// Reserve space on the GPU for the inverted lists for `num`
+ /// vectors, assumed equally distributed among
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(const faiss::IndexIVFPQ* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexIVFPQ* index) const;
+
+ /// Reserve GPU memory in our inverted lists for this number of vectors
+ void reserveMemory(size_t numVecs);
+
+ /// Enable or disable pre-computed codes
+ void setPrecomputedCodes(bool enable);
+
+ /// Are pre-computed codes enabled?
+ bool getPrecomputedCodes() const;
+
+ /// Return the number of sub-quantizers we are using
+ int getNumSubQuantizers() const;
+
+ /// Return the number of bits per PQ code
+ int getBitsPerCode() const;
+
+ /// Return the number of centroids per PQ code (2^bits per code)
+ int getCentroidsPerSubQuantizer() const;
+
+ /// After adding vectors, one can call this to reclaim device memory
+ /// to exactly the amount needed. Returns space reclaimed in bytes
+ size_t reclaimMemory();
+
+ /// Clears out all inverted lists, but retains the coarse and
+ /// product centroid information
+ void reset() override;
+
+ /// Should be called if the user ever changes the state of the IVF coarse
+ /// quantizer manually (e.g., substitutes a new instance or changes vectors
+ /// in the coarse quantizer outside the scope of training)
+ void updateQuantizer() override;
+
+ /// Trains the coarse and product quantizer based on the given vector data
+ void train(idx_t n, const float* x) override;
+
+ public:
+ /// Like the CPU version, we expose a publically-visible ProductQuantizer
+ /// for manipulation
+ ProductQuantizer pq;
+
+ protected:
+ /// Initialize appropriate index
+ void setIndex_(
+ GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ int numSubQuantizers,
+ int bitsPerSubQuantizer,
+ bool useFloat16LookupTables,
+ bool useMMCodeDistance,
+ bool interleavedLayout,
+ float* pqCentroidData,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ /// Throws errors if configuration settings are improper
+ void verifyPQSettings_() const;
+
+ /// Trains the PQ quantizer based on the given vector data
+ void trainResidualQuantizer_(idx_t n, const float* x);
+
+ protected:
+ /// Our configuration options that we were initialized with
+ const GpuIndexIVFPQConfig ivfpqConfig_;
+
+ /// Runtime override: whether or not we use precomputed tables
+ bool usePrecomputedTables_;
+
+ /// Number of sub-quantizers per encoded vector
+ int subQuantizers_;
+
+ /// Bits per sub-quantizer code
+ int bitsPerCode_;
+
+ /// Desired inverted list memory reservation
+ size_t reserveMemoryVecs_;
+
+ /// The product quantizer instance that we own; contains the
+ /// inverted lists
+ std::shared_ptr<IVFPQ> index_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu
new file mode 100644
index 0000000..3c856ba
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVFScalarQuantizer.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/impl/IVFFlat.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+GpuIndexIVFScalarQuantizer::GpuIndexIVFScalarQuantizer(
+ GpuResourcesProvider* provider,
+ const faiss::IndexIVFScalarQuantizer* index,
+ GpuIndexIVFScalarQuantizerConfig config)
+ : GpuIndexIVF(
+ provider,
+ index->d,
+ index->metric_type,
+ index->metric_arg,
+ index->nlist,
+ config),
+ sq(index->sq),
+ by_residual(index->by_residual),
+ ivfSQConfig_(config),
+ reserveMemoryVecs_(0) {
+ // This will perform SQ settings verification as well
+ copyFrom(index);
+}
+
+GpuIndexIVFScalarQuantizer::GpuIndexIVFScalarQuantizer(
+ GpuResourcesProvider* provider,
+ int dims,
+ idx_t nlist,
+ faiss::ScalarQuantizer::QuantizerType qtype,
+ faiss::MetricType metric,
+ bool encodeResidual,
+ GpuIndexIVFScalarQuantizerConfig config)
+ : GpuIndexIVF(provider, dims, metric, 0, nlist, config),
+ sq(dims, qtype),
+ by_residual(encodeResidual),
+ ivfSQConfig_(config),
+ reserveMemoryVecs_(0) {
+ // We haven't trained ourselves, so don't construct the IVFFlat
+ // index yet
+ verifySQSettings_();
+}
+
+GpuIndexIVFScalarQuantizer::GpuIndexIVFScalarQuantizer(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ idx_t nlist,
+ faiss::ScalarQuantizer::QuantizerType qtype,
+ faiss::MetricType metric,
+ bool encodeResidual,
+ GpuIndexIVFScalarQuantizerConfig config)
+ : GpuIndexIVF(
+ provider,
+ coarseQuantizer,
+ dims,
+ metric,
+ 0,
+ nlist,
+ config),
+ sq(dims, qtype),
+ by_residual(encodeResidual),
+ ivfSQConfig_(config),
+ reserveMemoryVecs_(0) {
+ // While we were passed an existing coarse quantizer instance (possibly
+ // trained or not), we have not yet trained our scalar quantizer, so we
+ // can't construct our index_ instance yet
+ this->is_trained = false;
+
+ verifySQSettings_();
+}
+
+GpuIndexIVFScalarQuantizer::~GpuIndexIVFScalarQuantizer() {}
+
+void GpuIndexIVFScalarQuantizer::verifySQSettings_() const {
+ FAISS_THROW_IF_NOT_MSG(
+ isSQSupported(sq.qtype), "Unsupported scalar QuantizerType on GPU");
+
+ // Check the amount of shared memory per block available based on our type
+ // is sufficient
+ // This check was previously in IVFFlatScan.cu, moved here to apply upon
+ // index construction
+ if (sq.qtype == ScalarQuantizer::QuantizerType::QT_8bit ||
+ sq.qtype == ScalarQuantizer::QuantizerType::QT_4bit) {
+ // There are quantization parameters per each dimension for these SQ
+ // types. These parameters are retained in shared memory for access
+ int maxDim =
+ getMaxSharedMemPerBlock(config_.device) / (sizeof(float) * 2);
+
+ FAISS_THROW_IF_NOT_FMT(
+ this->d < maxDim,
+ "GpuIndexIVFScalarQuantizer: Insufficient shared memory "
+ "available on the GPU for QT_8bit or QT_4bit with %d "
+ "dimensions; maximum dimensions possible is %d",
+ this->d,
+ maxDim);
+ }
+}
+
+void GpuIndexIVFScalarQuantizer::reserveMemory(size_t numVecs) {
+ DeviceScope scope(config_.device);
+
+ reserveMemoryVecs_ = numVecs;
+ if (index_) {
+ index_->reserveMemory(numVecs);
+ }
+}
+
+void GpuIndexIVFScalarQuantizer::copyFrom(
+ const faiss::IndexIVFScalarQuantizer* index) {
+ DeviceScope scope(config_.device);
+
+ // Clear out our old data
+ index_.reset();
+ baseIndex_.reset();
+
+ // Copy what we need from the CPU index
+ GpuIndexIVF::copyFrom(index);
+ sq = index->sq;
+ by_residual = index->by_residual;
+
+ // The other index might not be trained, in which case we don't need to copy
+ // over the lists
+ if (!index->is_trained) {
+ return;
+ }
+
+ // Otherwise, we can populate ourselves from the other index
+ this->is_trained = true;
+
+ // Copy our lists as well
+ index_.reset(new IVFFlat(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ index->metric_type,
+ index->metric_arg,
+ by_residual,
+ &sq,
+ ivfSQConfig_.interleavedLayout,
+ ivfSQConfig_.indicesOptions,
+ config_.memorySpace));
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFFlat>(index_);
+ updateQuantizer();
+
+ // Copy all of the IVF data
+ index_->copyInvertedListsFrom(index->invlists);
+
+ verifySQSettings_();
+}
+
+void GpuIndexIVFScalarQuantizer::copyTo(
+ faiss::IndexIVFScalarQuantizer* index) const {
+ DeviceScope scope(config_.device);
+
+ // We must have the indices in order to copy to ourselves
+ FAISS_THROW_IF_NOT_MSG(
+ ivfSQConfig_.indicesOptions != INDICES_IVF,
+ "Cannot copy to CPU as GPU index doesn't retain "
+ "indices (INDICES_IVF)");
+
+ GpuIndexIVF::copyTo(index);
+ index->sq = sq;
+ index->code_size = sq.code_size;
+ index->by_residual = by_residual;
+
+ auto ivf = new ArrayInvertedLists(nlist, index->code_size);
+ index->replace_invlists(ivf, true);
+
+ if (index_) {
+ // Copy IVF lists
+ index_->copyInvertedListsTo(ivf);
+ }
+}
+
+size_t GpuIndexIVFScalarQuantizer::reclaimMemory() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ return index_->reclaimMemory();
+ }
+
+ return 0;
+}
+
+void GpuIndexIVFScalarQuantizer::updateQuantizer() {
+ FAISS_THROW_IF_NOT_MSG(
+ quantizer, "Calling updateQuantizer without a quantizer instance");
+
+ // Only need to do something if we are already initialized
+ if (index_) {
+ index_->updateQuantizer(quantizer);
+ }
+}
+
+void GpuIndexIVFScalarQuantizer::reset() {
+ DeviceScope scope(config_.device);
+
+ if (index_) {
+ index_->reset();
+ this->ntotal = 0;
+ } else {
+ FAISS_ASSERT(this->ntotal == 0);
+ }
+}
+
+void GpuIndexIVFScalarQuantizer::trainResiduals_(idx_t n, const float* x) {
+ // The input is already guaranteed to be on the CPU
+ if (!by_residual) {
+ sq.train(n, x);
+ } else {
+ std::vector<idx_t> assign(n);
+ quantizer->assign(n, x, assign.data());
+
+ std::vector<float> residuals(n * d);
+ quantizer->compute_residual_n(n, x, residuals.data(), assign.data());
+
+ sq.train(n, residuals.data());
+ }
+}
+
+void GpuIndexIVFScalarQuantizer::train(idx_t n, const float* x) {
+ DeviceScope scope(config_.device);
+
+ // just in case someone changed us
+ verifySQSettings_();
+ verifyIVFSettings_();
+
+ if (this->is_trained) {
+ FAISS_ASSERT(index_);
+ return;
+ }
+
+ FAISS_ASSERT(!index_);
+
+ // FIXME: GPUize more of this
+ // First, make sure that the data is resident on the CPU, if it is not on
+ // the CPU, as we depend upon parts of the CPU code
+ auto hostData = toHost<float, 2>(
+ (float*)x,
+ resources_->getDefaultStream(config_.device),
+ {n, this->d});
+
+ trainQuantizer_(n, hostData.data());
+ trainResiduals_(n, hostData.data());
+
+ // The quantizer is now trained; construct the IVF index
+ index_.reset(new IVFFlat(
+ resources_.get(),
+ this->d,
+ this->nlist,
+ this->metric_type,
+ this->metric_arg,
+ by_residual,
+ &sq,
+ ivfSQConfig_.interleavedLayout,
+ ivfSQConfig_.indicesOptions,
+ config_.memorySpace));
+ baseIndex_ = std::static_pointer_cast<IVFBase, IVFFlat>(index_);
+ updateQuantizer();
+
+ if (reserveMemoryVecs_) {
+ index_->reserveMemory(reserveMemoryVecs_);
+ }
+
+ this->is_trained = true;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.h
new file mode 100644
index 0000000..44a8c1b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/gpu/GpuIndexIVF.h>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+class IVFFlat;
+class GpuIndexFlat;
+
+struct GpuIndexIVFScalarQuantizerConfig : public GpuIndexIVFConfig {
+ /// Use the alternative memory layout for the IVF lists
+ /// (currently the default)
+ bool interleavedLayout = true;
+};
+
+/// Wrapper around the GPU implementation that looks like
+/// faiss::IndexIVFScalarQuantizer
+class GpuIndexIVFScalarQuantizer : public GpuIndexIVF {
+ public:
+ /// Construct from a pre-existing faiss::IndexIVFScalarQuantizer instance,
+ /// copying data over to the given GPU, if the input index is trained.
+ GpuIndexIVFScalarQuantizer(
+ GpuResourcesProvider* provider,
+ const faiss::IndexIVFScalarQuantizer* index,
+ GpuIndexIVFScalarQuantizerConfig config =
+ GpuIndexIVFScalarQuantizerConfig());
+
+ /// Constructs a new instance with an empty flat quantizer; the user
+ /// provides the number of IVF lists desired.
+ GpuIndexIVFScalarQuantizer(
+ GpuResourcesProvider* provider,
+ int dims,
+ idx_t nlist,
+ faiss::ScalarQuantizer::QuantizerType qtype,
+ faiss::MetricType metric = MetricType::METRIC_L2,
+ bool encodeResidual = true,
+ GpuIndexIVFScalarQuantizerConfig config =
+ GpuIndexIVFScalarQuantizerConfig());
+
+ /// Constructs a new instance with a provided CPU or GPU coarse quantizer;
+ /// the user provides the number of IVF lists desired.
+ GpuIndexIVFScalarQuantizer(
+ GpuResourcesProvider* provider,
+ Index* coarseQuantizer,
+ int dims,
+ idx_t nlist,
+ faiss::ScalarQuantizer::QuantizerType qtype,
+ faiss::MetricType metric = MetricType::METRIC_L2,
+ bool encodeResidual = true,
+ GpuIndexIVFScalarQuantizerConfig config =
+ GpuIndexIVFScalarQuantizerConfig());
+
+ ~GpuIndexIVFScalarQuantizer() override;
+
+ /// Reserve GPU memory in our inverted lists for this number of vectors
+ void reserveMemory(size_t numVecs);
+
+ /// Initialize ourselves from the given CPU index; will overwrite
+ /// all data in ourselves
+ void copyFrom(const faiss::IndexIVFScalarQuantizer* index);
+
+ /// Copy ourselves to the given CPU index; will overwrite all data
+ /// in the index instance
+ void copyTo(faiss::IndexIVFScalarQuantizer* index) const;
+
+ /// After adding vectors, one can call this to reclaim device memory
+ /// to exactly the amount needed. Returns space reclaimed in bytes
+ size_t reclaimMemory();
+
+ /// Clears out all inverted lists, but retains the coarse and scalar
+ /// quantizer information
+ void reset() override;
+
+ /// Should be called if the user ever changes the state of the IVF coarse
+ /// quantizer manually (e.g., substitutes a new instance or changes vectors
+ /// in the coarse quantizer outside the scope of training)
+ void updateQuantizer() override;
+
+ /// Trains the coarse and scalar quantizer based on the given vector data
+ void train(idx_t n, const float* x) override;
+
+ protected:
+ /// Validates index SQ parameters
+ void verifySQSettings_() const;
+
+ /// Called from train to handle SQ residual training
+ void trainResiduals_(idx_t n, const float* x);
+
+ public:
+ /// Exposed like the CPU version
+ faiss::ScalarQuantizer sq;
+
+ /// Exposed like the CPU version
+ bool by_residual;
+
+ protected:
+ /// Our configuration options
+ const GpuIndexIVFScalarQuantizerConfig ivfSQConfig_;
+
+ /// Desired inverted list memory reservation
+ size_t reserveMemoryVecs_;
+
+ /// Instance that we own; contains the inverted list
+ std::shared_ptr<IVFFlat> index_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndicesOptions.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndicesOptions.h
new file mode 100644
index 0000000..2d305ab
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuIndicesOptions.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+namespace faiss {
+namespace gpu {
+
+/// How user vector index data is stored on the GPU
+enum IndicesOptions {
+ /// The user indices are only stored on the CPU; the GPU returns
+ /// (inverted list, offset) to the CPU which is then translated to
+ /// the real user index.
+ INDICES_CPU = 0,
+ /// The indices are not stored at all, on either the CPU or
+ /// GPU. Only (inverted list, offset) is returned to the user as the
+ /// index.
+ INDICES_IVF = 1,
+ /// Indices are stored as 32 bit integers on the GPU, but returned
+ /// as 64 bit integers
+ INDICES_32_BIT = 2,
+ /// Indices are stored as 64 bit integers on the GPU
+ INDICES_64_BIT = 3,
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuResources.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuResources.cpp
new file mode 100644
index 0000000..8d39fa6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuResources.cpp
@@ -0,0 +1,228 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <sstream>
+
+namespace faiss {
+namespace gpu {
+
+std::string allocTypeToString(AllocType t) {
+ switch (t) {
+ case AllocType::Other:
+ return "Other";
+ case AllocType::FlatData:
+ return "FlatData";
+ case AllocType::IVFLists:
+ return "IVFLists";
+ case AllocType::Quantizer:
+ return "Quantizer";
+ case AllocType::QuantizerPrecomputedCodes:
+ return "QuantizerPrecomputedCodes";
+ case AllocType::TemporaryMemoryBuffer:
+ return "TemporaryMemoryBuffer";
+ case AllocType::TemporaryMemoryOverflow:
+ return "TemporaryMemoryOverflow";
+ default:
+ return "Unknown";
+ }
+}
+
+std::string memorySpaceToString(MemorySpace s) {
+ switch (s) {
+ case MemorySpace::Temporary:
+ return "Temporary";
+ case MemorySpace::Device:
+ return "Device";
+ case MemorySpace::Unified:
+ return "Unified";
+ default:
+ return "Unknown";
+ }
+}
+
+std::string AllocInfo::toString() const {
+ std::stringstream ss;
+ ss << "type " << allocTypeToString(type) << " dev " << device << " space "
+ << memorySpaceToString(space) << " stream " << (void*)stream;
+
+ return ss.str();
+}
+
+std::string AllocRequest::toString() const {
+ std::stringstream ss;
+ ss << AllocInfo::toString() << " size " << size << " bytes";
+
+ return ss.str();
+}
+
+AllocInfo makeDevAlloc(AllocType at, cudaStream_t st) {
+ return AllocInfo(at, getCurrentDevice(), MemorySpace::Device, st);
+}
+
+AllocInfo makeTempAlloc(AllocType at, cudaStream_t st) {
+ return AllocInfo(at, getCurrentDevice(), MemorySpace::Temporary, st);
+}
+
+AllocInfo makeSpaceAlloc(AllocType at, MemorySpace sp, cudaStream_t st) {
+ return AllocInfo(at, getCurrentDevice(), sp, st);
+}
+
+//
+// GpuMemoryReservation
+//
+
+GpuMemoryReservation::GpuMemoryReservation()
+ : res(nullptr), device(0), stream(nullptr), data(nullptr), size(0) {}
+
+GpuMemoryReservation::GpuMemoryReservation(
+ GpuResources* r,
+ int dev,
+ cudaStream_t str,
+ void* p,
+ size_t sz)
+ : res(r), device(dev), stream(str), data(p), size(sz) {}
+
+GpuMemoryReservation::GpuMemoryReservation(GpuMemoryReservation&& m) noexcept {
+ res = m.res;
+ m.res = nullptr;
+ device = m.device;
+ m.device = 0;
+ stream = m.stream;
+ m.stream = nullptr;
+ data = m.data;
+ m.data = nullptr;
+ size = m.size;
+ m.size = 0;
+}
+
+GpuMemoryReservation& GpuMemoryReservation::operator=(
+ GpuMemoryReservation&& m) {
+ // Can't be both a valid allocation and the same allocation
+ FAISS_ASSERT(
+ !(res && res == m.res && device == m.device && data == m.data));
+
+ release();
+ res = m.res;
+ m.res = nullptr;
+ device = m.device;
+ m.device = 0;
+ stream = m.stream;
+ m.stream = nullptr;
+ data = m.data;
+ m.data = nullptr;
+ size = m.size;
+ m.size = 0;
+
+ return *this;
+}
+
+void GpuMemoryReservation::release() {
+ if (res) {
+ res->deallocMemory(device, data);
+ res = nullptr;
+ device = 0;
+ stream = nullptr;
+ data = nullptr;
+ size = 0;
+ }
+}
+
+GpuMemoryReservation::~GpuMemoryReservation() {
+ if (res) {
+ res->deallocMemory(device, data);
+ }
+}
+
+//
+// GpuResources
+//
+
+GpuResources::~GpuResources() = default;
+
+bool GpuResources::supportsBFloat16CurrentDevice() {
+ return supportsBFloat16(getCurrentDevice());
+}
+
+cublasHandle_t GpuResources::getBlasHandleCurrentDevice() {
+ return getBlasHandle(getCurrentDevice());
+}
+
+cudaStream_t GpuResources::getDefaultStreamCurrentDevice() {
+ return getDefaultStream(getCurrentDevice());
+}
+
+#if defined USE_NVIDIA_CUVS
+raft::device_resources& GpuResources::getRaftHandleCurrentDevice() {
+ return getRaftHandle(getCurrentDevice());
+}
+#endif
+
+std::vector<cudaStream_t> GpuResources::getAlternateStreamsCurrentDevice() {
+ return getAlternateStreams(getCurrentDevice());
+}
+
+cudaStream_t GpuResources::getAsyncCopyStreamCurrentDevice() {
+ return getAsyncCopyStream(getCurrentDevice());
+}
+
+void GpuResources::syncDefaultStream(int device) {
+ CUDA_VERIFY(cudaStreamSynchronize(getDefaultStream(device)));
+}
+
+void GpuResources::syncDefaultStreamCurrentDevice() {
+ syncDefaultStream(getCurrentDevice());
+}
+
+GpuMemoryReservation GpuResources::allocMemoryHandle(const AllocRequest& req) {
+ return GpuMemoryReservation(
+ this, req.device, req.stream, allocMemory(req), req.size);
+}
+
+size_t GpuResources::getTempMemoryAvailableCurrentDevice() const {
+ return getTempMemoryAvailable(getCurrentDevice());
+}
+
+//
+// GpuResourcesProvider
+//
+
+GpuResourcesProvider::~GpuResourcesProvider() = default;
+
+//
+// GpuResourcesProviderFromResourceInstance
+//
+
+GpuResourcesProviderFromInstance::GpuResourcesProviderFromInstance(
+ std::shared_ptr<GpuResources> p)
+ : res_(p) {}
+
+GpuResourcesProviderFromInstance::~GpuResourcesProviderFromInstance() = default;
+
+std::shared_ptr<GpuResources> GpuResourcesProviderFromInstance::getResources() {
+ return res_;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuResources.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuResources.h
new file mode 100644
index 0000000..c0c851a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/GpuResources.h
@@ -0,0 +1,312 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <cublas_v2.h>
+#include <cuda_runtime.h>
+#include <faiss/impl/FaissAssert.h>
+
+#include <memory>
+#include <utility>
+#include <vector>
+
+#if defined USE_NVIDIA_CUVS
+#include <raft/core/device_resources.hpp>
+#include <rmm/mr/device/device_memory_resource.hpp>
+#endif
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+enum AllocType {
+ /// Unknown allocation type or miscellaneous (not currently categorized)
+ Other = 0,
+
+ /// Primary data storage for GpuIndexFlat (the raw matrix of vectors and
+ /// vector norms if needed)
+ FlatData = 1,
+
+ /// Primary data storage for GpuIndexIVF* (the storage for each individual
+ /// IVF list)
+ IVFLists = 2,
+
+ /// Quantizer (PQ, SQ) dictionary information
+ Quantizer = 3,
+
+ /// For GpuIndexIVFPQ, "precomputed codes" for more efficient PQ lookup
+ /// require the use of possibly large tables. These are marked separately
+ /// from
+ /// Quantizer as these can frequently be 100s - 1000s of MiB in size
+ QuantizerPrecomputedCodes = 4,
+
+ ///
+ /// StandardGpuResources implementation specific types
+ ///
+
+ /// When using StandardGpuResources, temporary memory allocations
+ /// (MemorySpace::Temporary) come out of a stack region of memory that is
+ /// allocated up front for each gpu (e.g., 1.5 GiB upon initialization).
+ /// This
+ /// allocation by StandardGpuResources is marked with this AllocType.
+ TemporaryMemoryBuffer = 10,
+
+ /// When using StandardGpuResources, any MemorySpace::Temporary allocations
+ /// that cannot be satisfied within the TemporaryMemoryBuffer region fall
+ /// back
+ /// to calling cudaMalloc which are sized to just the request at hand. These
+ /// "overflow" temporary allocations are marked with this AllocType.
+ TemporaryMemoryOverflow = 11,
+};
+
+/// Convert an AllocType to string
+std::string allocTypeToString(AllocType t);
+
+/// Memory regions accessible to the GPU
+enum MemorySpace {
+ /// Temporary device memory (guaranteed to no longer be used upon exit of a
+ /// top-level index call, and where the streams using it have completed GPU
+ /// work). Typically backed by Device memory (cudaMalloc/cudaFree).
+ Temporary = 0,
+
+ /// Managed using cudaMalloc/cudaFree (typical GPU device memory)
+ Device = 1,
+
+ /// Managed using cudaMallocManaged/cudaFree (typical Unified CPU/GPU
+ /// memory)
+ Unified = 2,
+};
+
+/// Convert a MemorySpace to string
+std::string memorySpaceToString(MemorySpace s);
+
+/// Information on what/where an allocation is
+struct AllocInfo {
+ inline AllocInfo() {}
+
+ inline AllocInfo(AllocType at, int dev, MemorySpace sp, cudaStream_t st)
+ : type(at), device(dev), space(sp), stream(st) {}
+
+ /// Returns a string representation of this info
+ std::string toString() const;
+
+ /// The internal category of the allocation
+ AllocType type = AllocType::Other;
+
+ /// The device on which the allocation is happening
+ int device = 0;
+
+ /// The memory space of the allocation
+ MemorySpace space = MemorySpace::Device;
+
+ /// The stream on which new work on the memory will be ordered (e.g., if a
+ /// piece of memory cached and to be returned for this call was last used on
+ /// stream 3 and a new memory request is for stream 4, the memory manager
+ /// will synchronize stream 4 to wait for the completion of stream 3 via
+ /// events or other stream synchronization.
+ ///
+ /// The memory manager guarantees that the returned memory is free to use
+ /// without data races on this stream specified.
+ cudaStream_t stream = nullptr;
+};
+
+/// Create an AllocInfo for the current device with MemorySpace::Device
+AllocInfo makeDevAlloc(AllocType at, cudaStream_t st);
+
+/// Create an AllocInfo for the current device with MemorySpace::Temporary
+AllocInfo makeTempAlloc(AllocType at, cudaStream_t st);
+
+/// Create an AllocInfo for the current device
+AllocInfo makeSpaceAlloc(AllocType at, MemorySpace sp, cudaStream_t st);
+
+/// Information on what/where an allocation is, along with how big it should be
+struct AllocRequest : public AllocInfo {
+ inline AllocRequest() {}
+
+ inline AllocRequest(const AllocInfo& info, size_t sz)
+ : AllocInfo(info), size(sz) {}
+
+ inline AllocRequest(
+ AllocType at,
+ int dev,
+ MemorySpace sp,
+ cudaStream_t st,
+ size_t sz)
+ : AllocInfo(at, dev, sp, st), size(sz) {}
+
+ /// Returns a string representation of this request
+ std::string toString() const;
+
+ /// The size in bytes of the allocation
+ size_t size = 0;
+
+#if defined USE_NVIDIA_CUVS
+ rmm::mr::device_memory_resource* mr = nullptr;
+#endif
+};
+
+/// A RAII object that manages a temporary memory request
+struct GpuMemoryReservation {
+ GpuMemoryReservation();
+ GpuMemoryReservation(
+ GpuResources* r,
+ int dev,
+ cudaStream_t str,
+ void* p,
+ size_t sz);
+ GpuMemoryReservation(GpuMemoryReservation&& m) noexcept;
+ ~GpuMemoryReservation();
+
+ GpuMemoryReservation& operator=(GpuMemoryReservation&& m);
+
+ inline void* get() {
+ return data;
+ }
+
+ void release();
+
+ GpuResources* res;
+ int device;
+ cudaStream_t stream;
+ void* data;
+ size_t size;
+};
+
+/// Base class of GPU-side resource provider; hides provision of
+/// cuBLAS handles, CUDA streams and all device memory allocation performed
+class GpuResources {
+ public:
+ virtual ~GpuResources();
+
+ /// Call to pre-allocate resources for a particular device. If this is
+ /// not called, then resources will be allocated at the first time
+ /// of demand
+ virtual void initializeForDevice(int device) = 0;
+
+ /// Does the given GPU support bfloat16?
+ virtual bool supportsBFloat16(int device) = 0;
+
+ /// Returns the cuBLAS handle that we use for the given device
+ virtual cublasHandle_t getBlasHandle(int device) = 0;
+
+ /// Returns the stream that we order all computation on for the
+ /// given device
+ virtual cudaStream_t getDefaultStream(int device) = 0;
+
+#if defined USE_NVIDIA_CUVS
+ /// Returns the raft handle for the given device which can be used to
+ /// make calls to other raft primitives.
+ virtual raft::device_resources& getRaftHandle(int device) = 0;
+ raft::device_resources& getRaftHandleCurrentDevice();
+#endif
+
+ /// Overrides the default stream for a device to the user-supplied stream.
+ /// The resources object does not own this stream (i.e., it will not destroy
+ /// it).
+ virtual void setDefaultStream(int device, cudaStream_t stream) = 0;
+
+ /// Returns the set of alternative streams that we use for the given device
+ virtual std::vector<cudaStream_t> getAlternateStreams(int device) = 0;
+
+ /// Memory management
+ /// Returns an allocation from the given memory space, ordered with respect
+ /// to the given stream (i.e., the first user will be a kernel in this
+ /// stream). All allocations are sized internally to be the next highest
+ /// multiple of 16 bytes, and all allocations returned are guaranteed to be
+ /// 16 byte aligned.
+ virtual void* allocMemory(const AllocRequest& req) = 0;
+
+ /// Returns a previous allocation
+ virtual void deallocMemory(int device, void* in) = 0;
+
+ /// For MemorySpace::Temporary, how much space is immediately available
+ /// without cudaMalloc allocation?
+ virtual size_t getTempMemoryAvailable(int device) const = 0;
+
+ /// Returns the available CPU pinned memory buffer
+ virtual std::pair<void*, size_t> getPinnedMemory() = 0;
+
+ /// Returns the stream on which we perform async CPU <-> GPU copies
+ virtual cudaStream_t getAsyncCopyStream(int device) = 0;
+
+ ///
+ /// Functions provided by default
+ ///
+
+ /// Does the current GPU support bfloat16?
+ bool supportsBFloat16CurrentDevice();
+
+ /// Calls getBlasHandle with the current device
+ cublasHandle_t getBlasHandleCurrentDevice();
+
+ /// Calls getDefaultStream with the current device
+ cudaStream_t getDefaultStreamCurrentDevice();
+
+ /// Calls getTempMemoryAvailable with the current device
+ size_t getTempMemoryAvailableCurrentDevice() const;
+
+ /// Returns a temporary memory allocation via a RAII object
+ GpuMemoryReservation allocMemoryHandle(const AllocRequest& req);
+
+ /// Synchronizes the CPU with respect to the default stream for the
+ /// given device
+ // equivalent to cudaDeviceSynchronize(getDefaultStream(device))
+ void syncDefaultStream(int device);
+
+ /// Calls syncDefaultStream for the current device
+ void syncDefaultStreamCurrentDevice();
+
+ /// Calls getAlternateStreams for the current device
+ std::vector<cudaStream_t> getAlternateStreamsCurrentDevice();
+
+ /// Calls getAsyncCopyStream for the current device
+ cudaStream_t getAsyncCopyStreamCurrentDevice();
+};
+
+/// Interface for a provider of a shared resources object. This is to avoid
+/// interfacing std::shared_ptr to Python
+class GpuResourcesProvider {
+ public:
+ virtual ~GpuResourcesProvider();
+
+ /// Returns the shared resources object
+ virtual std::shared_ptr<GpuResources> getResources() = 0;
+};
+
+/// A simple wrapper for a GpuResources object to make a GpuResourcesProvider
+/// out of it again
+class GpuResourcesProviderFromInstance : public GpuResourcesProvider {
+ public:
+ explicit GpuResourcesProviderFromInstance(std::shared_ptr<GpuResources> p);
+ ~GpuResourcesProviderFromInstance() override;
+
+ std::shared_ptr<GpuResources> getResources() override;
+
+ private:
+ std::shared_ptr<GpuResources> res_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/StandardGpuResources.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/StandardGpuResources.cpp
new file mode 100644
index 0000000..649b7cb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/StandardGpuResources.cpp
@@ -0,0 +1,771 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#if defined USE_NVIDIA_CUVS
+#include <raft/core/device_resources.hpp>
+#include <rmm/mr/device/managed_memory_resource.hpp>
+#include <rmm/mr/device/per_device_resource.hpp>
+#include <rmm/mr/host/pinned_memory_resource.hpp>
+#include <memory>
+#endif
+
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <iostream>
+#include <limits>
+#include <sstream>
+
+namespace faiss {
+namespace gpu {
+
+namespace {
+
+// How many streams per device we allocate by default (for multi-streaming)
+constexpr int kNumStreams = 2;
+
+// Use 256 MiB of pinned memory for async CPU <-> GPU copies by default
+constexpr size_t kDefaultPinnedMemoryAllocation = (size_t)256 * 1024 * 1024;
+
+// Default temporary memory allocation for <= 4 GiB memory GPUs
+constexpr size_t k4GiBTempMem = (size_t)512 * 1024 * 1024;
+
+// Default temporary memory allocation for <= 8 GiB memory GPUs
+constexpr size_t k8GiBTempMem = (size_t)1024 * 1024 * 1024;
+
+// Maximum temporary memory allocation for all GPUs
+constexpr size_t kMaxTempMem = (size_t)1536 * 1024 * 1024;
+
+std::string allocsToString(const std::unordered_map<void*, AllocRequest>& map) {
+ // Produce a sorted list of all outstanding allocations by type
+ std::unordered_map<AllocType, std::pair<int, size_t>> stats;
+
+ for (auto& entry : map) {
+ auto& a = entry.second;
+
+ auto it = stats.find(a.type);
+ if (it != stats.end()) {
+ stats[a.type].first++;
+ stats[a.type].second += a.size;
+ } else {
+ stats[a.type] = std::make_pair(1, a.size);
+ }
+ }
+
+ std::stringstream ss;
+ for (auto& entry : stats) {
+ ss << "Alloc type " << allocTypeToString(entry.first) << ": "
+ << entry.second.first << " allocations, " << entry.second.second
+ << " bytes\n";
+ }
+
+ return ss.str();
+}
+
+} // namespace
+
+//
+// StandardGpuResourcesImpl
+//
+
+StandardGpuResourcesImpl::StandardGpuResourcesImpl()
+ :
+#if defined USE_NVIDIA_CUVS
+ mmr_(new rmm::mr::managed_memory_resource),
+ pmr_(new rmm::mr::pinned_memory_resource),
+#endif
+ pinnedMemAlloc_(nullptr),
+ pinnedMemAllocSize_(0),
+ // let the adjustment function determine the memory size for us by
+ // passing in a huge value that will then be adjusted
+ tempMemSize_(getDefaultTempMemForGPU(
+ -1,
+ std::numeric_limits<size_t>::max())),
+ pinnedMemSize_(kDefaultPinnedMemoryAllocation),
+ allocLogging_(false) {
+}
+
+StandardGpuResourcesImpl::~StandardGpuResourcesImpl() {
+ // The temporary memory allocator has allocated memory through us, so clean
+ // that up before we finish fully de-initializing ourselves
+ tempMemory_.clear();
+
+ // Make sure all allocations have been freed
+ bool allocError = false;
+
+ for (auto& entry : allocs_) {
+ auto& map = entry.second;
+
+ if (!map.empty()) {
+ std::cerr
+ << "StandardGpuResources destroyed with allocations outstanding:\n"
+ << "Device " << entry.first
+ << " outstanding allocations:\n";
+ std::cerr << allocsToString(map);
+ allocError = true;
+ }
+ }
+
+ FAISS_ASSERT_MSG(
+ !allocError, "GPU memory allocations not properly cleaned up");
+
+#if defined USE_NVIDIA_CUVS
+ raftHandles_.clear();
+#endif
+
+ for (auto& entry : defaultStreams_) {
+ DeviceScope scope(entry.first);
+
+ // We created these streams, so are responsible for destroying them
+ CUDA_VERIFY(cudaStreamDestroy(entry.second));
+ }
+
+ for (auto& entry : alternateStreams_) {
+ DeviceScope scope(entry.first);
+
+ for (auto stream : entry.second) {
+ CUDA_VERIFY(cudaStreamDestroy(stream));
+ }
+ }
+
+ for (auto& entry : asyncCopyStreams_) {
+ DeviceScope scope(entry.first);
+
+ CUDA_VERIFY(cudaStreamDestroy(entry.second));
+ }
+
+ for (auto& entry : blasHandles_) {
+ DeviceScope scope(entry.first);
+
+ auto blasStatus = cublasDestroy(entry.second);
+ FAISS_ASSERT(blasStatus == CUBLAS_STATUS_SUCCESS);
+ }
+
+ if (pinnedMemAlloc_) {
+#if defined USE_NVIDIA_CUVS
+ pmr_->deallocate(pinnedMemAlloc_, pinnedMemAllocSize_);
+#else
+ auto err = cudaFreeHost(pinnedMemAlloc_);
+ FAISS_ASSERT_FMT(
+ err == cudaSuccess,
+ "Failed to cudaFreeHost pointer %p (error %d %s)",
+ pinnedMemAlloc_,
+ (int)err,
+ cudaGetErrorString(err));
+#endif
+ }
+}
+
+size_t StandardGpuResourcesImpl::getDefaultTempMemForGPU(
+ int device,
+ size_t requested) {
+ auto totalMem = device != -1 ? getDeviceProperties(device).totalGlobalMem
+ : std::numeric_limits<size_t>::max();
+
+ if (totalMem <= (size_t)4 * 1024 * 1024 * 1024) {
+ // If the GPU has <= 4 GiB of memory, reserve 512 MiB
+
+ if (requested > k4GiBTempMem) {
+ return k4GiBTempMem;
+ }
+ } else if (totalMem <= (size_t)8 * 1024 * 1024 * 1024) {
+ // If the GPU has <= 8 GiB of memory, reserve 1 GiB
+
+ if (requested > k8GiBTempMem) {
+ return k8GiBTempMem;
+ }
+ } else {
+ // Never use more than 1.5 GiB
+ if (requested > kMaxTempMem) {
+ return kMaxTempMem;
+ }
+ }
+
+ // use whatever lower limit the user requested
+ return requested;
+}
+
+/// Does the given GPU support bfloat16?
+bool StandardGpuResourcesImpl::supportsBFloat16(int device) {
+ initializeForDevice(device);
+ auto& prop = getDeviceProperties(device);
+ return prop.major >= 8;
+}
+
+void StandardGpuResourcesImpl::noTempMemory() {
+ setTempMemory(0);
+}
+
+void StandardGpuResourcesImpl::setTempMemory(size_t size) {
+ if (tempMemSize_ != size) {
+ // adjust based on general limits
+ tempMemSize_ = getDefaultTempMemForGPU(-1, size);
+
+ // We need to re-initialize memory resources for all current devices
+ // that have been initialized. This should be safe to do, even if we are
+ // currently running work, because the cudaFree call that this implies
+ // will force-synchronize all GPUs with the CPU
+ for (auto& p : tempMemory_) {
+ int device = p.first;
+ // Free the existing memory first
+ p.second.reset();
+
+ // Allocate new
+ p.second = std::make_unique<StackDeviceMemory>(
+ this,
+ p.first,
+ // adjust for this specific device
+ getDefaultTempMemForGPU(device, tempMemSize_));
+ }
+ }
+}
+
+void StandardGpuResourcesImpl::setPinnedMemory(size_t size) {
+ // Should not call this after devices have been initialized
+ FAISS_ASSERT(defaultStreams_.size() == 0);
+ FAISS_ASSERT(!pinnedMemAlloc_);
+
+ pinnedMemSize_ = size;
+}
+
+void StandardGpuResourcesImpl::setDefaultStream(
+ int device,
+ cudaStream_t stream) {
+ if (isInitialized(device)) {
+ // A new series of calls may not be ordered with what was the previous
+ // stream, so if the stream being specified is different, then we need
+ // to ensure ordering between the two (new stream waits on old).
+ auto it = userDefaultStreams_.find(device);
+ cudaStream_t prevStream = nullptr;
+
+ if (it != userDefaultStreams_.end()) {
+ prevStream = it->second;
+ } else {
+ FAISS_ASSERT(defaultStreams_.count(device));
+ prevStream = defaultStreams_[device];
+ }
+
+ if (prevStream != stream) {
+ streamWait({stream}, {prevStream});
+ }
+#if defined USE_NVIDIA_CUVS
+ // delete the raft handle for this device, which will be initialized
+ // with the updated stream during any subsequent calls to getRaftHandle
+ auto it2 = raftHandles_.find(device);
+ if (it2 != raftHandles_.end()) {
+ raft::resource::set_cuda_stream(it2->second, stream);
+ }
+#endif
+ }
+
+ userDefaultStreams_[device] = stream;
+}
+
+void StandardGpuResourcesImpl::revertDefaultStream(int device) {
+ if (isInitialized(device)) {
+ auto it = userDefaultStreams_.find(device);
+
+ if (it != userDefaultStreams_.end()) {
+ // There was a user stream set that we need to synchronize against
+ cudaStream_t prevStream = userDefaultStreams_[device];
+
+ FAISS_ASSERT(defaultStreams_.count(device));
+ cudaStream_t newStream = defaultStreams_[device];
+
+ streamWait({newStream}, {prevStream});
+
+#if defined USE_NVIDIA_CUVS
+ // update the stream on the raft handle for this device
+ auto it2 = raftHandles_.find(device);
+ if (it2 != raftHandles_.end()) {
+ raft::resource::set_cuda_stream(it2->second, newStream);
+ }
+#endif
+ } else {
+#if defined USE_NVIDIA_CUVS
+ // delete the raft handle for this device, which will be initialized
+ // with the updated stream during any subsequent calls to
+ // getRaftHandle
+ auto it2 = raftHandles_.find(device);
+ if (it2 != raftHandles_.end()) {
+ raftHandles_.erase(it2);
+ }
+#endif
+ }
+ }
+
+ userDefaultStreams_.erase(device);
+}
+
+void StandardGpuResourcesImpl::setDefaultNullStreamAllDevices() {
+ for (int dev = 0; dev < getNumDevices(); ++dev) {
+ setDefaultStream(dev, nullptr);
+ }
+}
+
+void StandardGpuResourcesImpl::setLogMemoryAllocations(bool enable) {
+ allocLogging_ = enable;
+}
+
+bool StandardGpuResourcesImpl::isInitialized(int device) const {
+ // Use default streams as a marker for whether or not a certain
+ // device has been initialized
+ return defaultStreams_.count(device) != 0;
+}
+
+void StandardGpuResourcesImpl::initializeForDevice(int device) {
+ if (isInitialized(device)) {
+ return;
+ }
+
+ FAISS_ASSERT(device < getNumDevices());
+ DeviceScope scope(device);
+
+ // If this is the first device that we're initializing, create our
+ // pinned memory allocation
+ if (defaultStreams_.empty() && pinnedMemSize_ > 0) {
+#if defined USE_NVIDIA_CUVS
+ // If this is the first device that we're initializing, create our
+ // pinned memory allocation
+ if (defaultStreams_.empty() && pinnedMemSize_ > 0) {
+ try {
+ pinnedMemAlloc_ = pmr_->allocate(pinnedMemSize_);
+ } catch (const std::bad_alloc& rmm_ex) {
+ FAISS_THROW_MSG("CUDA memory allocation error");
+ }
+
+ pinnedMemAllocSize_ = pinnedMemSize_;
+ }
+#else
+ auto err = cudaHostAlloc(
+ &pinnedMemAlloc_, pinnedMemSize_, cudaHostAllocDefault);
+
+ FAISS_THROW_IF_NOT_FMT(
+ err == cudaSuccess,
+ "failed to cudaHostAlloc %zu bytes for CPU <-> GPU "
+ "async copy buffer (error %d %s)",
+ pinnedMemSize_,
+ (int)err,
+ cudaGetErrorString(err));
+
+ pinnedMemAllocSize_ = pinnedMemSize_;
+#endif
+ }
+
+ // Make sure that device properties for all devices are cached
+ auto& prop = getDeviceProperties(device);
+
+ // Also check to make sure we meet our minimum compute capability (3.0)
+ FAISS_ASSERT_FMT(
+ prop.major >= 3,
+ "Device id %d with CC %d.%d not supported, "
+ "need 3.0+ compute capability",
+ device,
+ prop.major,
+ prop.minor);
+
+#if USE_AMD_ROCM
+ // Our code is pre-built with and expects warpSize == 32 or 64, validate
+ // that
+ FAISS_ASSERT_FMT(
+ prop.warpSize == 32 || prop.warpSize == 64,
+ "Device id %d does not have expected warpSize of 32 or 64",
+ device);
+#else
+ // Our code is pre-built with and expects warpSize == 32, validate that
+ FAISS_ASSERT_FMT(
+ prop.warpSize == 32,
+ "Device id %d does not have expected warpSize of 32",
+ device);
+#endif
+
+ // Create streams
+ cudaStream_t defaultStream = nullptr;
+ CUDA_VERIFY(
+ cudaStreamCreateWithFlags(&defaultStream, cudaStreamNonBlocking));
+
+ defaultStreams_[device] = defaultStream;
+
+#if defined USE_NVIDIA_CUVS
+ raftHandles_.emplace(std::make_pair(device, defaultStream));
+#endif
+
+ cudaStream_t asyncCopyStream = nullptr;
+ CUDA_VERIFY(
+ cudaStreamCreateWithFlags(&asyncCopyStream, cudaStreamNonBlocking));
+
+ asyncCopyStreams_[device] = asyncCopyStream;
+
+ std::vector<cudaStream_t> deviceStreams;
+ for (int j = 0; j < kNumStreams; ++j) {
+ cudaStream_t stream = nullptr;
+ CUDA_VERIFY(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
+
+ deviceStreams.push_back(stream);
+ }
+
+ alternateStreams_[device] = std::move(deviceStreams);
+
+ // Create cuBLAS handle
+ cublasHandle_t blasHandle = nullptr;
+ auto blasStatus = cublasCreate(&blasHandle);
+ FAISS_ASSERT(blasStatus == CUBLAS_STATUS_SUCCESS);
+ blasHandles_[device] = blasHandle;
+
+ // For CUDA 10 on V100, enabling tensor core usage would enable automatic
+ // rounding down of inputs to f16 (though accumulate in f32) which results
+ // in unacceptable loss of precision in general. For CUDA 11 / A100, only
+ // enable tensor core support if it doesn't result in a loss of precision.
+#if CUDA_VERSION >= 11000
+ cublasSetMathMode(
+ blasHandle, CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION);
+#endif
+
+ FAISS_ASSERT(allocs_.count(device) == 0);
+ allocs_[device] = std::unordered_map<void*, AllocRequest>();
+
+ FAISS_ASSERT(tempMemory_.count(device) == 0);
+ auto mem = std::make_unique<StackDeviceMemory>(
+ this,
+ device,
+ // adjust for this specific device
+ getDefaultTempMemForGPU(device, tempMemSize_));
+
+ tempMemory_.emplace(device, std::move(mem));
+}
+
+cublasHandle_t StandardGpuResourcesImpl::getBlasHandle(int device) {
+ initializeForDevice(device);
+ return blasHandles_[device];
+}
+
+cudaStream_t StandardGpuResourcesImpl::getDefaultStream(int device) {
+ initializeForDevice(device);
+
+ auto it = userDefaultStreams_.find(device);
+ if (it != userDefaultStreams_.end()) {
+ // There is a user override stream set
+ return it->second;
+ }
+
+ // Otherwise, our base default stream
+ return defaultStreams_[device];
+}
+
+#if defined USE_NVIDIA_CUVS
+raft::device_resources& StandardGpuResourcesImpl::getRaftHandle(int device) {
+ initializeForDevice(device);
+
+ auto it = raftHandles_.find(device);
+ if (it == raftHandles_.end()) {
+ // Make sure we are using the stream the user may have already assigned
+ // to the current GpuResources
+ raftHandles_.emplace(device, getDefaultStream(device));
+
+ // Initialize cublas handle
+ raftHandles_[device].get_cublas_handle();
+ }
+
+ // Otherwise, our base default handle
+ return raftHandles_[device];
+}
+#endif
+
+std::vector<cudaStream_t> StandardGpuResourcesImpl::getAlternateStreams(
+ int device) {
+ initializeForDevice(device);
+ return alternateStreams_[device];
+}
+
+std::pair<void*, size_t> StandardGpuResourcesImpl::getPinnedMemory() {
+ return std::make_pair(pinnedMemAlloc_, pinnedMemAllocSize_);
+}
+
+cudaStream_t StandardGpuResourcesImpl::getAsyncCopyStream(int device) {
+ initializeForDevice(device);
+ return asyncCopyStreams_[device];
+}
+
+void* StandardGpuResourcesImpl::allocMemory(const AllocRequest& req) {
+ initializeForDevice(req.device);
+
+ // We don't allocate a placeholder for zero-sized allocations
+ if (req.size == 0) {
+ return nullptr;
+ }
+
+ // cudaMalloc guarantees allocation alignment to 256 bytes; do the same here
+ // for alignment purposes (to reduce memory transaction overhead etc)
+ auto adjReq = req;
+ adjReq.size = utils::roundUp(adjReq.size, (size_t)256);
+
+ void* p = nullptr;
+
+ if (adjReq.space == MemorySpace::Temporary) {
+ auto& tempMem = tempMemory_[adjReq.device];
+
+ if (adjReq.size > tempMem->getSizeAvailable()) {
+ // We need to allocate this ourselves
+ AllocRequest newReq = adjReq;
+ newReq.space = MemorySpace::Device;
+ newReq.type = AllocType::TemporaryMemoryOverflow;
+
+ if (allocLogging_) {
+ std::cout
+ << "StandardGpuResources: alloc fail "
+ << adjReq.toString()
+ << " (no temp space); retrying as MemorySpace::Device\n";
+ }
+
+ return allocMemory(newReq);
+ }
+
+ // Otherwise, we can handle this locally
+ p = tempMemory_[adjReq.device]->allocMemory(adjReq.stream, adjReq.size);
+ } else if (adjReq.space == MemorySpace::Device) {
+#if defined USE_NVIDIA_CUVS
+ try {
+ rmm::mr::device_memory_resource* current_mr =
+ rmm::mr::get_per_device_resource(
+ rmm::cuda_device_id{adjReq.device});
+ p = current_mr->allocate_async(adjReq.size, adjReq.stream);
+ adjReq.mr = current_mr;
+ } catch (const std::bad_alloc& rmm_ex) {
+ FAISS_THROW_MSG("CUDA memory allocation error");
+ }
+#else
+ auto err = cudaMalloc(&p, adjReq.size);
+
+ // Throw if we fail to allocate
+ if (err != cudaSuccess) {
+ // FIXME: as of CUDA 11, a memory allocation error appears to be
+ // presented via cudaGetLastError as well, and needs to be
+ // cleared. Just call the function to clear it
+ cudaGetLastError();
+
+ std::stringstream ss;
+ ss << "StandardGpuResources: alloc fail " << adjReq.toString()
+ << " (cudaMalloc error " << cudaGetErrorString(err) << " ["
+ << (int)err << "])\n";
+ auto str = ss.str();
+
+ if (allocLogging_) {
+ std::cout << str;
+ }
+
+ FAISS_THROW_IF_NOT_FMT(err == cudaSuccess, "%s", str.c_str());
+ }
+#endif
+ } else if (adjReq.space == MemorySpace::Unified) {
+#if defined USE_NVIDIA_CUVS
+ try {
+ // for now, use our own managed MR to do Unified Memory allocations.
+ // TODO: change this to use the current device resource once RMM has
+ // a way to retrieve a "guaranteed" managed memory resource for a
+ // device.
+ p = mmr_->allocate_async(adjReq.size, adjReq.stream);
+ adjReq.mr = mmr_.get();
+ } catch (const std::bad_alloc& rmm_ex) {
+ FAISS_THROW_MSG("CUDA memory allocation error");
+ }
+#else
+ auto err = cudaMallocManaged(&p, adjReq.size);
+
+ if (err != cudaSuccess) {
+ // FIXME: as of CUDA 11, a memory allocation error appears to be
+ // presented via cudaGetLastError as well, and needs to be cleared.
+ // Just call the function to clear it
+ cudaGetLastError();
+
+ std::stringstream ss;
+ ss << "StandardGpuResources: alloc fail " << adjReq.toString()
+ << " failed (cudaMallocManaged error " << cudaGetErrorString(err)
+ << " [" << (int)err << "])\n";
+ auto str = ss.str();
+
+ if (allocLogging_) {
+ std::cout << str;
+ }
+
+ FAISS_THROW_IF_NOT_FMT(err == cudaSuccess, "%s", str.c_str());
+ }
+#endif
+ } else {
+ FAISS_ASSERT_FMT(false, "unknown MemorySpace %d", (int)adjReq.space);
+ }
+
+ if (allocLogging_) {
+ std::cout << "StandardGpuResources: alloc ok " << adjReq.toString()
+ << " ptr 0x" << p << "\n";
+ }
+
+ allocs_[adjReq.device][p] = adjReq;
+
+ return p;
+}
+
+void StandardGpuResourcesImpl::deallocMemory(int device, void* p) {
+ FAISS_ASSERT(isInitialized(device));
+
+ if (!p) {
+ return;
+ }
+
+ auto& a = allocs_[device];
+ auto it = a.find(p);
+ FAISS_ASSERT(it != a.end());
+
+ auto& req = it->second;
+
+ if (allocLogging_) {
+ std::cout << "StandardGpuResources: dealloc " << req.toString() << "\n";
+ }
+
+ if (req.space == MemorySpace::Temporary) {
+ tempMemory_[device]->deallocMemory(device, req.stream, req.size, p);
+ } else if (
+ req.space == MemorySpace::Device ||
+ req.space == MemorySpace::Unified) {
+#if defined USE_NVIDIA_CUVS
+ req.mr->deallocate_async(p, req.size, req.stream);
+#else
+ auto err = cudaFree(p);
+ FAISS_ASSERT_FMT(
+ err == cudaSuccess,
+ "Failed to cudaFree pointer %p (error %d %s)",
+ p,
+ (int)err,
+ cudaGetErrorString(err));
+#endif
+ } else {
+ FAISS_ASSERT_FMT(false, "unknown MemorySpace %d", (int)req.space);
+ }
+
+ a.erase(it);
+}
+
+size_t StandardGpuResourcesImpl::getTempMemoryAvailable(int device) const {
+ FAISS_ASSERT(isInitialized(device));
+
+ auto it = tempMemory_.find(device);
+ FAISS_ASSERT(it != tempMemory_.end());
+
+ return it->second->getSizeAvailable();
+}
+
+std::map<int, std::map<std::string, std::pair<int, size_t>>>
+StandardGpuResourcesImpl::getMemoryInfo() const {
+ using AT = std::map<std::string, std::pair<int, size_t>>;
+
+ std::map<int, AT> out;
+
+ for (auto& entry : allocs_) {
+ AT outDevice;
+
+ for (auto& a : entry.second) {
+ auto& v = outDevice[allocTypeToString(a.second.type)];
+ v.first++;
+ v.second += a.second.size;
+ }
+
+ out[entry.first] = std::move(outDevice);
+ }
+
+ return out;
+}
+
+//
+// StandardGpuResources
+//
+
+StandardGpuResources::StandardGpuResources()
+ : res_(new StandardGpuResourcesImpl) {}
+
+StandardGpuResources::~StandardGpuResources() = default;
+
+std::shared_ptr<GpuResources> StandardGpuResources::getResources() {
+ return res_;
+}
+
+bool StandardGpuResources::supportsBFloat16(int device) {
+ return res_->supportsBFloat16(device);
+}
+
+bool StandardGpuResources::supportsBFloat16CurrentDevice() {
+ return res_->supportsBFloat16CurrentDevice();
+}
+
+void StandardGpuResources::noTempMemory() {
+ res_->noTempMemory();
+}
+
+void StandardGpuResources::setTempMemory(size_t size) {
+ res_->setTempMemory(size);
+}
+
+void StandardGpuResources::setPinnedMemory(size_t size) {
+ res_->setPinnedMemory(size);
+}
+
+void StandardGpuResources::setDefaultStream(int device, cudaStream_t stream) {
+ res_->setDefaultStream(device, stream);
+}
+
+void StandardGpuResources::revertDefaultStream(int device) {
+ res_->revertDefaultStream(device);
+}
+
+void StandardGpuResources::setDefaultNullStreamAllDevices() {
+ res_->setDefaultNullStreamAllDevices();
+}
+
+std::map<int, std::map<std::string, std::pair<int, size_t>>>
+StandardGpuResources::getMemoryInfo() const {
+ return res_->getMemoryInfo();
+}
+
+cudaStream_t StandardGpuResources::getDefaultStream(int device) {
+ return res_->getDefaultStream(device);
+}
+
+#if defined USE_NVIDIA_CUVS
+raft::device_resources& StandardGpuResources::getRaftHandle(int device) {
+ return res_->getRaftHandle(device);
+}
+#endif
+
+size_t StandardGpuResources::getTempMemoryAvailable(int device) const {
+ return res_->getTempMemoryAvailable(device);
+}
+
+void StandardGpuResources::syncDefaultStreamCurrentDevice() {
+ res_->syncDefaultStreamCurrentDevice();
+}
+
+void StandardGpuResources::setLogMemoryAllocations(bool enable) {
+ res_->setLogMemoryAllocations(enable);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/StandardGpuResources.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/StandardGpuResources.h
new file mode 100644
index 0000000..f23ca19
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/StandardGpuResources.h
@@ -0,0 +1,269 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#if defined USE_NVIDIA_CUVS
+#include <raft/core/device_resources.hpp>
+#include <rmm/mr/host/pinned_memory_resource.hpp>
+#endif
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StackDeviceMemory.h>
+#include <functional>
+#include <map>
+#include <unordered_map>
+#include <vector>
+
+#pragma GCC visibility push(default)
+namespace faiss {
+namespace gpu {
+
+/// Standard implementation of the GpuResources object that provides for a
+/// temporary memory manager
+class StandardGpuResourcesImpl : public GpuResources {
+ public:
+ StandardGpuResourcesImpl();
+
+ ~StandardGpuResourcesImpl() override;
+
+ /// Does the given GPU support bfloat16?
+ bool supportsBFloat16(int device) override;
+
+ /// Disable allocation of temporary memory; all temporary memory
+ /// requests will call cudaMalloc / cudaFree at the point of use
+ void noTempMemory();
+
+ /// Specify that we wish to use a certain fixed size of memory on
+ /// all devices as temporary memory. This is the upper bound for the GPU
+ /// memory that we will reserve. We will never go above 1.5 GiB on any GPU;
+ /// smaller GPUs (with <= 4 GiB or <= 8 GiB) will use less memory than that.
+ /// To avoid any temporary memory allocation, pass 0.
+ void setTempMemory(size_t size);
+
+ /// Set amount of pinned memory to allocate, for async GPU <-> CPU
+ /// transfers
+ void setPinnedMemory(size_t size);
+
+ /// Called to change the stream for work ordering. We do not own `stream`;
+ /// i.e., it will not be destroyed when the GpuResources object gets cleaned
+ /// up.
+ /// We are guaranteed that all Faiss GPU work is ordered with respect to
+ /// this stream upon exit from an index or other Faiss GPU call.
+ void setDefaultStream(int device, cudaStream_t stream) override;
+
+ /// Revert the default stream to the original stream managed by this
+ /// resources object, in case someone called `setDefaultStream`.
+ void revertDefaultStream(int device);
+
+ /// Returns the stream for the given device on which all Faiss GPU work is
+ /// ordered.
+ /// We are guaranteed that all Faiss GPU work is ordered with respect to
+ /// this stream upon exit from an index or other Faiss GPU call.
+ cudaStream_t getDefaultStream(int device) override;
+
+#if defined USE_NVIDIA_CUVS
+ /// Returns the raft handle for the given device which can be used to
+ /// make calls to other raft primitives.
+ raft::device_resources& getRaftHandle(int device) override;
+#endif
+
+ /// Called to change the work ordering streams to the null stream
+ /// for all devices
+ void setDefaultNullStreamAllDevices();
+
+ /// If enabled, will print every GPU memory allocation and deallocation to
+ /// standard output
+ void setLogMemoryAllocations(bool enable);
+
+ public:
+ /// Internal system calls
+
+ /// Initialize resources for this device
+ void initializeForDevice(int device) override;
+
+ cublasHandle_t getBlasHandle(int device) override;
+
+ std::vector<cudaStream_t> getAlternateStreams(int device) override;
+
+ /// Allocate non-temporary GPU memory
+ void* allocMemory(const AllocRequest& req) override;
+
+ /// Returns a previous allocation
+ void deallocMemory(int device, void* in) override;
+
+ size_t getTempMemoryAvailable(int device) const override;
+
+ /// Export a description of memory used for Python
+ std::map<int, std::map<std::string, std::pair<int, size_t>>> getMemoryInfo()
+ const;
+
+ std::pair<void*, size_t> getPinnedMemory() override;
+
+ cudaStream_t getAsyncCopyStream(int device) override;
+
+ protected:
+ /// Have GPU resources been initialized for this device yet?
+ bool isInitialized(int device) const;
+
+ /// Adjust the default temporary memory allocation based on the total GPU
+ /// memory size
+ static size_t getDefaultTempMemForGPU(int device, size_t requested);
+
+ protected:
+ /// Set of currently outstanding memory allocations per device
+ /// device -> (alloc request, allocated ptr)
+ std::unordered_map<int, std::unordered_map<void*, AllocRequest>> allocs_;
+
+ /// Temporary memory provider, per each device
+ std::unordered_map<int, std::unique_ptr<StackDeviceMemory>> tempMemory_;
+
+ /// Our default stream that work is ordered on, one per each device
+ std::unordered_map<int, cudaStream_t> defaultStreams_;
+
+ /// This contains particular streams as set by the user for
+ /// ordering, if any
+ std::unordered_map<int, cudaStream_t> userDefaultStreams_;
+
+ /// Other streams we can use, per each device
+ std::unordered_map<int, std::vector<cudaStream_t>> alternateStreams_;
+
+ /// Async copy stream to use for GPU <-> CPU pinned memory copies
+ std::unordered_map<int, cudaStream_t> asyncCopyStreams_;
+
+ /// cuBLAS handle for each device
+ std::unordered_map<int, cublasHandle_t> blasHandles_;
+
+#if defined USE_NVIDIA_CUVS
+ /// raft handle for each device
+ std::unordered_map<int, raft::device_resources> raftHandles_;
+
+ /**
+ * FIXME: Integrating these in a separate code path for now. Ultimately,
+ * it would be nice if we use a simple memory resource abstraction
+ * in Faiss so we could plug in whether to use RMM's memory resources
+ * or the default.
+ *
+ * There's enough duplicated logic that it doesn't *seem* to make sense
+ * to create a subclass only for the RMM memory resources.
+ */
+
+ // managed_memory_resource
+ std::unique_ptr<rmm::mr::device_memory_resource> mmr_;
+
+ // pinned_memory_resource
+ std::unique_ptr<rmm::mr::host_memory_resource> pmr_;
+#endif
+
+ /// Pinned memory allocation for use with this GPU
+ void* pinnedMemAlloc_;
+ size_t pinnedMemAllocSize_;
+
+ /// Another option is to use a specified amount of memory on all
+ /// devices
+ size_t tempMemSize_;
+
+ /// Amount of pinned memory we should allocate
+ size_t pinnedMemSize_;
+
+ /// Whether or not we log every GPU memory allocation and deallocation
+ bool allocLogging_;
+};
+
+/// Default implementation of GpuResources that allocates a cuBLAS
+/// stream and 2 streams for use, as well as temporary memory.
+/// Internally, the Faiss GPU code uses the instance managed by getResources,
+/// but this is the user-facing object that is internally reference counted.
+class StandardGpuResources : public GpuResourcesProvider {
+ public:
+ StandardGpuResources();
+ ~StandardGpuResources() override;
+
+ std::shared_ptr<GpuResources> getResources() override;
+
+ /// Whether or not the given device supports native bfloat16 arithmetic
+ bool supportsBFloat16(int device);
+
+ /// Whether or not the current device supports native bfloat16 arithmetic
+ bool supportsBFloat16CurrentDevice();
+
+ /// Disable allocation of temporary memory; all temporary memory
+ /// requests will call cudaMalloc / cudaFree at the point of use
+ void noTempMemory();
+
+ /// Specify that we wish to use a certain fixed size of memory on
+ /// all devices as temporary memory. This is the upper bound for the GPU
+ /// memory that we will reserve. We will never go above 1.5 GiB on any GPU;
+ /// smaller GPUs (with <= 4 GiB or <= 8 GiB) will use less memory than that.
+ /// To avoid any temporary memory allocation, pass 0.
+ void setTempMemory(size_t size);
+
+ /// Set amount of pinned memory to allocate, for async GPU <-> CPU
+ /// transfers
+ void setPinnedMemory(size_t size);
+
+ /// Called to change the stream for work ordering. We do not own `stream`;
+ /// i.e., it will not be destroyed when the GpuResources object gets cleaned
+ /// up.
+ /// We are guaranteed that all Faiss GPU work is ordered with respect to
+ /// this stream upon exit from an index or other Faiss GPU call.
+ void setDefaultStream(int device, cudaStream_t stream);
+
+ /// Revert the default stream to the original stream managed by this
+ /// resources object, in case someone called `setDefaultStream`.
+ void revertDefaultStream(int device);
+
+ /// Called to change the work ordering streams to the null stream
+ /// for all devices
+ void setDefaultNullStreamAllDevices();
+
+ /// Export a description of memory used for Python
+ std::map<int, std::map<std::string, std::pair<int, size_t>>> getMemoryInfo()
+ const;
+ /// Returns the current default stream
+ cudaStream_t getDefaultStream(int device);
+
+#if defined USE_NVIDIA_CUVS
+ /// Returns the raft handle for the given device which can be used to
+ /// make calls to other raft primitives.
+ raft::device_resources& getRaftHandle(int device);
+#endif
+
+ /// Returns the current amount of temp memory available
+ size_t getTempMemoryAvailable(int device) const;
+
+ /// Synchronize our default stream with the CPU
+ void syncDefaultStreamCurrentDevice();
+
+ /// If enabled, will print every GPU memory allocation and deallocation to
+ /// standard output
+ void setLogMemoryAllocations(bool enable);
+
+ private:
+ std::shared_ptr<StandardGpuResourcesImpl> res_;
+};
+
+} // namespace gpu
+} // namespace faiss
+#pragma GCC visibility pop
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryDistance.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryDistance.cu
new file mode 100644
index 0000000..5061e47
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryDistance.cu
@@ -0,0 +1,330 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Select.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// Number of warps that the kernel is instantiated with
+constexpr int kWarps = 8;
+constexpr int kLanes = kWarpSize;
+
+constexpr int kMaxDistance = std::numeric_limits<int>::max();
+
+// Performs a binary matrix multiplication, returning the lowest k results in
+// `vecs` for each `query` in terms of Hamming distance (a fused kernel)
+// Each warp calculates distance for a single query
+template <int NumWarpQ, int NumThreadQ, typename BinaryType>
+__launch_bounds__(kWarps* kLanes) __global__ void binaryDistanceAnySize(
+ const Tensor<BinaryType, 2, true> vecs,
+ const Tensor<BinaryType, 2, true> query,
+ Tensor<int, 2, true> outK,
+ Tensor<idx_t, 2, true> outV,
+ int k) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ // A matrix tile (query, k)
+ __shared__ BinaryType
+ queryTile[kWarps][kLanes + 1]; // avoid bank conflict
+
+ // B matrix tile (vec, k)
+ __shared__ BinaryType
+ vecTile[kLanes][kLanes + 1]; // avoid bank conflict
+
+ WarpSelect<
+ int,
+ idx_t,
+ false,
+ Comparator<int>,
+ NumWarpQ,
+ NumThreadQ,
+ kWarps * kLanes>
+ heap(kMaxDistance, -1, k);
+
+ int warpId = threadIdx.y;
+ int laneId = threadIdx.x;
+
+ // Each warp handles a single query
+ idx_t warpQuery = idx_t(blockIdx.x) * kWarps + warpId;
+ bool queryInBounds = warpQuery < query.getSize(0);
+
+ // Each warp loops through the entire chunk of vectors
+ for (idx_t blockVec = 0; blockVec < vecs.getSize(0);
+ blockVec += kLanes) {
+ int threadDistance = 0;
+
+ // Reduction dimension
+ for (idx_t blockK = 0; blockK < vecs.getSize(1); blockK += kLanes) {
+ idx_t laneK = blockK + laneId;
+ bool kInBounds = laneK < vecs.getSize(1);
+
+ queryTile[warpId][laneId] = queryInBounds && kInBounds
+ ? query[warpQuery][laneK]
+ : 0;
+
+ // kWarps warps are responsible for loading 32 vecs
+#pragma unroll
+ for (int i = 0; i < kLanes / kWarps; ++i) {
+ int warpVec = i * kWarps + warpId;
+ idx_t vec = blockVec + warpVec;
+ bool vecInBounds = vec < vecs.getSize(0);
+
+ vecTile[warpVec][laneId] =
+ vecInBounds && kInBounds ? vecs[vec][laneK] : 0;
+ }
+
+ __syncthreads();
+
+ // Compare distances
+#pragma unroll
+ for (int i = 0; i < kLanes; ++i) {
+ threadDistance +=
+ __popc(queryTile[warpId][i] ^ vecTile[laneId][i]);
+ }
+
+ __syncthreads();
+ }
+
+ // Lanes within a warp are different vec results against the same
+ // query Only submit distances which represent real (query, vec)
+ // pairs
+ bool valInBounds =
+ queryInBounds && (blockVec + laneId < vecs.getSize(0));
+ threadDistance = valInBounds ? threadDistance : kMaxDistance;
+ idx_t id = valInBounds ? blockVec + laneId : idx_t(-1);
+
+ heap.add(threadDistance, id);
+ }
+
+ heap.reduce();
+
+ if (warpQuery < query.getSize(0)) {
+ heap.writeOut(outK[warpQuery].data(), outV[warpQuery].data(), k);
+ }
+ }
+}
+
+// Version of the kernel that avoids a loop over the reduction dimension, and
+// thus avoids reloading the query vectors
+template <
+ int NumWarpQ,
+ int NumThreadQ,
+ typename BinaryType,
+ int ReductionLimit = kLanes>
+__global__ void __launch_bounds__(kWarps* kLanes) binaryDistanceLimitSize(
+ const Tensor<BinaryType, 2, true> vecs,
+ const Tensor<BinaryType, 2, true> query,
+ Tensor<int, 2, true> outK,
+ Tensor<idx_t, 2, true> outV,
+ int k) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ // A matrix tile (query, k)
+ __shared__ BinaryType
+ queryTile[kWarps][kLanes + 1]; // avoid bank conflict
+
+ // B matrix tile (vec, k)
+ __shared__ BinaryType
+ vecTile[kLanes][kLanes + 1]; // avoid bank conflict
+
+ WarpSelect<
+ int,
+ idx_t,
+ false,
+ Comparator<int>,
+ NumWarpQ,
+ NumThreadQ,
+ kWarps * kLanes>
+ heap(kMaxDistance, -1, k);
+
+ int warpId = threadIdx.y;
+ int laneId = threadIdx.x;
+
+ // Each warp handles a single query
+ int laneK = laneId;
+ idx_t warpQuery = idx_t(blockIdx.x) * kWarps + warpId;
+ bool kInBounds = laneK < vecs.getSize(1);
+ bool queryInBounds = warpQuery < query.getSize(0);
+
+ queryTile[warpId][laneId] =
+ queryInBounds && kInBounds ? query[warpQuery][laneK] : 0;
+
+ // Each warp loops through the entire chunk of vectors
+ for (idx_t blockVec = 0; blockVec < vecs.getSize(0);
+ blockVec += kLanes) {
+ int threadDistance = 0;
+
+ // kWarps warps are responsible for loading 32 vecs
+#pragma unroll
+ for (int i = 0; i < kLanes / kWarps; ++i) {
+ int warpVec = i * kWarps + warpId;
+ idx_t vec = blockVec + warpVec;
+ bool vecInBounds = vec < vecs.getSize(0);
+
+ vecTile[warpVec][laneId] =
+ vecInBounds && kInBounds ? vecs[vec][laneK] : 0;
+ }
+
+ __syncthreads();
+
+ // Compare distances
+#pragma unroll
+ for (int i = 0; i < ReductionLimit; ++i) {
+ threadDistance +=
+ __popc(queryTile[warpId][i] ^ vecTile[laneId][i]);
+ }
+
+ __syncthreads();
+
+ // Lanes within a warp are different vec results against the same
+ // query Only submit distances which represent real (query, vec)
+ // pairs
+ bool valInBounds =
+ queryInBounds && (blockVec + laneId < vecs.getSize(0));
+ threadDistance = valInBounds ? threadDistance : kMaxDistance;
+ idx_t id = valInBounds ? blockVec + laneId : idx_t(-1);
+
+ heap.add(threadDistance, id);
+ }
+
+ heap.reduce();
+
+ if (warpQuery < query.getSize(0)) {
+ heap.writeOut(outK[warpQuery].data(), outV[warpQuery].data(), k);
+ }
+ }
+}
+
+template <typename BinaryType>
+void runBinaryDistanceAnySize(
+ Tensor<BinaryType, 2, true>& vecs,
+ Tensor<BinaryType, 2, true>& query,
+ Tensor<int, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ int k,
+ cudaStream_t stream) {
+ dim3 grid(utils::divUp(query.getSize(0), kWarps));
+ dim3 block(getWarpSizeCurrentDevice(), kWarps);
+
+ if (k == 1) {
+ binaryDistanceAnySize<1, 1, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ binaryDistanceAnySize<32, 2, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 64) {
+ binaryDistanceAnySize<64, 3, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 128) {
+ binaryDistanceAnySize<128, 3, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 256) {
+ binaryDistanceAnySize<256, 4, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 512) {
+ binaryDistanceAnySize<512, 8, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 1024) {
+ binaryDistanceAnySize<1024, 8, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ }
+#if GPU_MAX_SELECTION_K >= 2048
+ else if (k <= 2048) {
+ binaryDistanceAnySize<2048, 8, BinaryType>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ }
+#endif
+}
+
+template <typename BinaryType, int ReductionLimit>
+void runBinaryDistanceLimitSize(
+ Tensor<BinaryType, 2, true>& vecs,
+ Tensor<BinaryType, 2, true>& query,
+ Tensor<int, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ int k,
+ cudaStream_t stream) {
+ dim3 grid(utils::divUp(query.getSize(0), kWarps));
+ dim3 block(getWarpSizeCurrentDevice(), kWarps);
+
+ if (k == 1) {
+ binaryDistanceLimitSize<1, 1, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ binaryDistanceLimitSize<32, 2, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 64) {
+ binaryDistanceLimitSize<64, 3, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 128) {
+ binaryDistanceLimitSize<128, 3, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 256) {
+ binaryDistanceLimitSize<256, 4, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 512) {
+ binaryDistanceLimitSize<512, 8, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ } else if (k <= 1024) {
+ binaryDistanceLimitSize<1024, 8, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ }
+#if GPU_MAX_SELECTION_K >= 2048
+ else if (k <= 2048) {
+ binaryDistanceLimitSize<2048, 8, BinaryType, ReductionLimit>
+ <<<grid, block, 0, stream>>>(vecs, query, outK, outV, k);
+ }
+#endif
+}
+
+void runBinaryDistance(
+ Tensor<unsigned char, 2, true>& vecs,
+ Tensor<unsigned char, 2, true>& query,
+ Tensor<int, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ int k,
+ cudaStream_t stream) {
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+ FAISS_ASSERT(vecs.getSize(1) == query.getSize(1));
+
+ FAISS_ASSERT(outK.getSize(1) == k);
+ FAISS_ASSERT(outV.getSize(1) == k);
+
+ // For the optimized uint32 kernel, we handle 32 * 8 = 256 max dims
+ constexpr int kReductionLimit32 = 8;
+
+ // For the optimized uint8 kernel, we handle 8 * 16 = 128 max dims
+ constexpr int kReductionLimit8 = 16;
+
+ // All other cases (large or small) go through the general kernel
+
+ if (vecs.getSize(1) % sizeof(unsigned int) == 0 &&
+ (vecs.getSize(1) / sizeof(unsigned int)) <= kReductionLimit32) {
+ auto vecs32 = vecs.castResize<unsigned int>();
+ auto query32 = query.castResize<unsigned int>();
+
+ // Optimize for vectors with dimensions a multiple of 32 that are less
+ // than 32 * kReductionLimit (256) dimensions in size
+ runBinaryDistanceLimitSize<unsigned int, kReductionLimit32>(
+ vecs32, query32, outK, outV, k, stream);
+
+ } else if (vecs.getSize(1) <= kReductionLimit8) {
+ // Optimize for vectors with dimensions a multiple of 32 that are less
+ // than 32 * kReductionLimit (256) dimensions in size
+ runBinaryDistanceLimitSize<unsigned char, kReductionLimit8>(
+ vecs, query, outK, outV, k, stream);
+ } else {
+ // Arbitrary size kernel
+ runBinaryDistanceAnySize<unsigned char>(
+ vecs, query, outK, outV, k, stream);
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryDistance.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryDistance.cuh
new file mode 100644
index 0000000..7524353
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryDistance.cuh
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// Performs brute-force k-NN comparison between `vecs` and `query`, where they
+// are encoded as binary vectors
+void runBinaryDistance(
+ Tensor<unsigned char, 2, true>& vecs,
+ Tensor<unsigned char, 2, true>& query,
+ Tensor<int, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ int k,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryFlatIndex.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryFlatIndex.cu
new file mode 100644
index 0000000..fd148b3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryFlatIndex.cu
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/impl/BinaryDistance.cuh>
+#include <faiss/gpu/impl/BinaryFlatIndex.cuh>
+
+namespace faiss {
+namespace gpu {
+
+constexpr int kBitsPerByte = 8;
+
+BinaryFlatIndex::BinaryFlatIndex(GpuResources* res, int dim, MemorySpace space)
+ : resources_(res),
+ dim_(dim),
+ num_(0),
+ rawData_(
+ res,
+ makeSpaceAlloc(
+ AllocType::FlatData,
+ space,
+ res->getDefaultStreamCurrentDevice())) {
+ // Like the CPU version, dimensions must be evenly divisible by 8 (fit into
+ // an integral number of bytes)
+ FAISS_ASSERT(dim % kBitsPerByte == 0);
+}
+
+/// Returns the number of vectors we contain
+idx_t BinaryFlatIndex::getSize() const {
+ return vectors_.getSize(0);
+}
+
+idx_t BinaryFlatIndex::getDim() const {
+ return vectors_.getSize(1) * kBitsPerByte;
+}
+
+void BinaryFlatIndex::reserve(size_t numVecs, cudaStream_t stream) {
+ // Like the CPU version, dimensions must be evenly divisible by 8 (fit into
+ // an integral number of bytes)
+ rawData_.reserve(
+ numVecs * (dim_ / kBitsPerByte) * sizeof(unsigned char), stream);
+}
+
+Tensor<unsigned char, 2, true>& BinaryFlatIndex::getVectorsRef() {
+ return vectors_;
+}
+
+void BinaryFlatIndex::query(
+ Tensor<unsigned char, 2, true>& input,
+ int k,
+ Tensor<int, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ runBinaryDistance(vectors_, input, outDistances, outIndices, k, stream);
+}
+
+void BinaryFlatIndex::add(
+ const unsigned char* data,
+ idx_t numVecs,
+ cudaStream_t stream) {
+ if (numVecs == 0) {
+ return;
+ }
+
+ rawData_.append(
+ (char*)data,
+ (size_t)(dim_ / kBitsPerByte) * numVecs * sizeof(unsigned char),
+ stream,
+ true /* reserve exactly */);
+
+ num_ += numVecs;
+
+ DeviceTensor<unsigned char, 2, true> vectors(
+ (unsigned char*)rawData_.data(), {num_, (dim_ / kBitsPerByte)});
+ vectors_ = std::move(vectors);
+}
+
+void BinaryFlatIndex::reset() {
+ rawData_.clear();
+ vectors_ = DeviceTensor<unsigned char, 2, true>();
+ num_ = 0;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryFlatIndex.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryFlatIndex.cuh
new file mode 100644
index 0000000..4047618
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BinaryFlatIndex.cuh
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+/// Holder of GPU resources for a particular flat index
+class BinaryFlatIndex {
+ public:
+ BinaryFlatIndex(GpuResources* res, int dim, MemorySpace space);
+
+ /// Returns the number of vectors we contain
+ idx_t getSize() const;
+
+ idx_t getDim() const;
+
+ /// Reserve storage that can contain at least this many vectors
+ void reserve(size_t numVecs, cudaStream_t stream);
+
+ /// Returns a reference to our vectors currently in use
+ Tensor<unsigned char, 2, true>& getVectorsRef();
+
+ void query(
+ Tensor<unsigned char, 2, true>& vecs,
+ int k,
+ Tensor<int, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices);
+
+ /// Add vectors to ourselves; the pointer passed can be on the host
+ /// or the device
+ void add(const unsigned char* data, idx_t numVecs, cudaStream_t stream);
+
+ /// Free all storage
+ void reset();
+
+ private:
+ /// Collection of GPU resources that we use
+ GpuResources* resources_;
+
+ /// Dimensionality of our vectors
+ const int dim_;
+
+ /// How many vectors we have
+ idx_t num_;
+
+ /// The underlying expandable storage
+ DeviceVector<char> rawData_;
+
+ /// Vectors currently in rawData_
+ DeviceTensor<unsigned char, 2, true> vectors_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BroadcastSum.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BroadcastSum.cu
new file mode 100644
index 0000000..9a0a927
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BroadcastSum.cu
@@ -0,0 +1,377 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <algorithm>
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T, int kRowsPerBlock, int kRowUnroll, int kColLoad>
+__global__ void sumAlongColumns(
+ Tensor<T, 1, true> input,
+ Tensor<T, 2, true> output) {
+ static_assert(kRowsPerBlock % kRowUnroll == 0, "must fit rows");
+
+ // blockIdx.x: which chunk of rows we are responsible for updating
+ // blockIdx.y: which chunk of columns we are responsible for
+ // updating
+ idx_t rowStart = idx_t(blockIdx.x) * kRowsPerBlock;
+ idx_t rowEnd = rowStart + kRowsPerBlock;
+ idx_t colStart = idx_t(blockIdx.y) * blockDim.x * kColLoad;
+
+ // FIXME: if we have exact multiples, don't need this
+ bool endRow = (blockIdx.x == gridDim.x - 1);
+ bool endCol = (blockIdx.y == gridDim.y - 1);
+
+ if (endRow) {
+ if (output.getSize(0) % kRowsPerBlock == 0) {
+ endRow = false;
+ }
+ }
+
+ if (endCol) {
+ for (idx_t col = colStart + threadIdx.x; col < input.getSize(0);
+ col += blockDim.x) {
+ T val = input[col];
+
+ if (endRow) {
+ for (idx_t row = rowStart; row < output.getSize(0); ++row) {
+ T out = output[row][col];
+ out = Math<T>::add(out, val);
+ output[row][col] = out;
+ }
+ } else {
+ T rows[kRowUnroll];
+
+ for (idx_t row = rowStart; row < rowEnd; row += kRowUnroll) {
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+ rows[i] = output[row + i][col];
+ }
+
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+ rows[i] = Math<T>::add(rows[i], val);
+ }
+
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+ output[row + i][col] = rows[i];
+ }
+ }
+ }
+ }
+ } else {
+ idx_t col = colStart + threadIdx.x;
+
+ T val[kColLoad];
+
+#pragma unroll
+ for (int i = 0; i < kColLoad; ++i) {
+ val[i] = input[col + i * blockDim.x];
+ }
+
+ if (endRow) {
+ for (idx_t row = rowStart; row < output.getSize(0); ++row) {
+#pragma unroll
+ for (int i = 0; i < kColLoad; ++i) {
+ T out = output[row][col + i * blockDim.x];
+ out = Math<T>::add(out, val[i]);
+ output[row][col + i * blockDim.x] = out;
+ }
+ }
+ } else {
+ T rows[kRowUnroll * kColLoad];
+
+ for (idx_t row = rowStart; row < rowEnd; row += kRowUnroll) {
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < kColLoad; ++j) {
+ rows[i * kColLoad + j] =
+ output[row + i][col + j * blockDim.x];
+ }
+ }
+
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < kColLoad; ++j) {
+ rows[i * kColLoad + j] =
+ Math<T>::add(rows[i * kColLoad + j], val[j]);
+ }
+ }
+
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < kColLoad; ++j) {
+ output[row + i][col + j * blockDim.x] =
+ rows[i * kColLoad + j];
+ }
+ }
+ }
+ }
+ }
+}
+
+template <typename T, int kRowsPerBlock, int kRowUnroll, int kColLoad>
+__global__ void assignAlongColumns(
+ Tensor<T, 1, true> input,
+ Tensor<T, 2, true> output) {
+ static_assert(kRowsPerBlock % kRowUnroll == 0, "must fit rows");
+
+ // blockIdx.x: which chunk of rows we are responsible for updating
+ // blockIdx.y: which chunk of columns we are responsible for
+ // updating
+ idx_t rowStart = idx_t(blockIdx.x) * kRowsPerBlock;
+ idx_t rowEnd = rowStart + kRowsPerBlock;
+ idx_t colStart = idx_t(blockIdx.y) * blockDim.x * kColLoad;
+
+ // FIXME: if we have exact multiples, don't need this
+ bool endRow = (blockIdx.x == gridDim.x - 1);
+ bool endCol = (blockIdx.y == gridDim.y - 1);
+
+ if (endRow) {
+ if (output.getSize(0) % kRowsPerBlock == 0) {
+ endRow = false;
+ }
+ }
+
+ if (endCol) {
+ for (idx_t col = colStart + threadIdx.x; col < input.getSize(0);
+ col += blockDim.x) {
+ T val = input[col];
+
+ if (endRow) {
+ for (idx_t row = rowStart; row < output.getSize(0); ++row) {
+ output[row][col] = val;
+ }
+ } else {
+ for (idx_t row = rowStart; row < rowEnd; row += kRowUnroll) {
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+ output[row + i][col] = val;
+ }
+ }
+ }
+ }
+ } else {
+ idx_t col = colStart + threadIdx.x;
+
+ T val[kColLoad];
+
+#pragma unroll
+ for (int i = 0; i < kColLoad; ++i) {
+ val[i] = input[col + i * blockDim.x];
+ }
+
+ if (endRow) {
+ for (idx_t row = rowStart; row < output.getSize(0); ++row) {
+#pragma unroll
+ for (int i = 0; i < kColLoad; ++i) {
+ output[row][col + i * blockDim.x] = val[i];
+ }
+ }
+ } else {
+ for (idx_t row = rowStart; row < rowEnd; row += kRowUnroll) {
+#pragma unroll
+ for (int i = 0; i < kRowUnroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < kColLoad; ++j) {
+ output[row + i][col + j * blockDim.x] = val[j];
+ }
+ }
+ }
+ }
+ }
+}
+
+template <typename T, bool ZeroClamp>
+__global__ void sumAlongRows(
+ Tensor<T, 1, true> input,
+ Tensor<T, 2, true> output) {
+ __shared__ T sval;
+
+ idx_t row = blockIdx.x;
+
+ if (threadIdx.x == 0) {
+ sval = input[row];
+ }
+
+ __syncthreads();
+
+ T val = sval;
+
+ // FIXME: speed up
+ for (idx_t i = threadIdx.x; i < output.getSize(1); i += blockDim.x) {
+ T out = output[row][i];
+ out = Math<T>::add(out, val);
+ if (ZeroClamp) {
+ out = Math<T>::lt(out, Math<T>::zero()) ? Math<T>::zero() : out;
+ }
+
+ output[row][i] = out;
+ }
+}
+
+template <typename T, typename TVec>
+void runSumAlongColumns(
+ Tensor<T, 1, true>& input,
+ Tensor<T, 2, true>& output,
+ cudaStream_t stream) {
+ FAISS_ASSERT(input.getSize(0) == output.getSize(1));
+
+ int threadsPerBlock = 256;
+ constexpr int kRowUnroll = 4;
+ constexpr int kRowsPerBlock = kRowUnroll * 4;
+ constexpr int kColLoad = 4;
+
+ auto block = dim3(threadsPerBlock);
+
+ if (input.template canCastResize<TVec>() &&
+ output.template canCastResize<TVec>()) {
+ auto inputV = input.template castResize<TVec>();
+ auto outputV = output.template castResize<TVec>();
+
+ auto rowTiles = utils::divUp(outputV.getSize(0), kRowsPerBlock);
+ auto colTiles =
+ utils::divUp(outputV.getSize(1), threadsPerBlock * kColLoad);
+ FAISS_ASSERT(colTiles <= getMaxGridCurrentDevice().y);
+ auto grid = dim3(rowTiles, colTiles);
+
+ sumAlongColumns<TVec, kRowsPerBlock, kRowUnroll, kColLoad>
+ <<<grid, block, 0, stream>>>(inputV, outputV);
+ } else {
+ auto rowTiles = utils::divUp(output.getSize(0), kRowsPerBlock);
+ auto colTiles =
+ utils::divUp(output.getSize(1), threadsPerBlock * kColLoad);
+ FAISS_ASSERT(colTiles <= getMaxGridCurrentDevice().y);
+ auto grid = dim3(rowTiles, colTiles);
+
+ sumAlongColumns<T, kRowsPerBlock, kRowUnroll, kColLoad>
+ <<<grid, block, 0, stream>>>(input, output);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+void runSumAlongColumns(
+ Tensor<float, 1, true>& input,
+ Tensor<float, 2, true>& output,
+ cudaStream_t stream) {
+ runSumAlongColumns<float, float4>(input, output, stream);
+}
+
+void runSumAlongColumns(
+ Tensor<half, 1, true>& input,
+ Tensor<half, 2, true>& output,
+ cudaStream_t stream) {
+ runSumAlongColumns<half, half2>(input, output, stream);
+}
+
+template <typename T, typename TVec>
+void runAssignAlongColumns(
+ Tensor<T, 1, true>& input,
+ Tensor<T, 2, true>& output,
+ cudaStream_t stream) {
+ FAISS_ASSERT(input.getSize(0) == output.getSize(1));
+
+ int threadsPerBlock = 256;
+ constexpr int kRowUnroll = 4;
+ constexpr int kRowsPerBlock = kRowUnroll * 4;
+ constexpr int kColLoad = 4;
+
+ auto block = dim3(threadsPerBlock);
+
+ if (input.template canCastResize<TVec>() &&
+ output.template canCastResize<TVec>()) {
+ auto inputV = input.template castResize<TVec>();
+ auto outputV = output.template castResize<TVec>();
+
+ auto rowTiles = utils::divUp(outputV.getSize(0), kRowsPerBlock);
+ auto colTiles =
+ utils::divUp(outputV.getSize(1), threadsPerBlock * kColLoad);
+ FAISS_ASSERT(colTiles <= getMaxGridCurrentDevice().y);
+ auto grid = dim3(rowTiles, colTiles);
+
+ assignAlongColumns<TVec, kRowsPerBlock, kRowUnroll, kColLoad>
+ <<<grid, block, 0, stream>>>(inputV, outputV);
+ } else {
+ auto rowTiles = utils::divUp(output.getSize(0), kRowsPerBlock);
+ auto colTiles =
+ utils::divUp(output.getSize(1), threadsPerBlock * kColLoad);
+ FAISS_ASSERT(colTiles <= getMaxGridCurrentDevice().y);
+ auto grid = dim3(rowTiles, colTiles);
+
+ assignAlongColumns<T, kRowsPerBlock, kRowUnroll, kColLoad>
+ <<<grid, block, 0, stream>>>(input, output);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+void runAssignAlongColumns(
+ Tensor<float, 1, true>& input,
+ Tensor<float, 2, true>& output,
+ cudaStream_t stream) {
+ runAssignAlongColumns<float, float4>(input, output, stream);
+}
+
+void runAssignAlongColumns(
+ Tensor<half, 1, true>& input,
+ Tensor<half, 2, true>& output,
+ cudaStream_t stream) {
+ runAssignAlongColumns<half, half2>(input, output, stream);
+}
+
+template <typename T>
+void runSumAlongRows(
+ Tensor<T, 1, true>& input,
+ Tensor<T, 2, true>& output,
+ bool zeroClamp,
+ cudaStream_t stream) {
+ FAISS_ASSERT(input.getSize(0) == output.getSize(0));
+
+ idx_t threadsPerBlock =
+ std::min(output.getSize(1), (idx_t)getMaxThreadsCurrentDevice());
+ auto grid = dim3(output.getSize(0));
+ auto block = dim3(threadsPerBlock);
+
+ if (zeroClamp) {
+ sumAlongRows<T, true><<<grid, block, 0, stream>>>(input, output);
+ } else {
+ sumAlongRows<T, false><<<grid, block, 0, stream>>>(input, output);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+void runSumAlongRows(
+ Tensor<float, 1, true>& input,
+ Tensor<float, 2, true>& output,
+ bool zeroClamp,
+ cudaStream_t stream) {
+ runSumAlongRows<float>(input, output, zeroClamp, stream);
+}
+
+void runSumAlongRows(
+ Tensor<half, 1, true>& input,
+ Tensor<half, 2, true>& output,
+ bool zeroClamp,
+ cudaStream_t stream) {
+ runSumAlongRows<half>(input, output, zeroClamp, stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BroadcastSum.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BroadcastSum.cuh
new file mode 100644
index 0000000..9a421f1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/BroadcastSum.cuh
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda_fp16.h>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// output[x][i] += input[i] for all x
+void runSumAlongColumns(
+ Tensor<float, 1, true>& input,
+ Tensor<float, 2, true>& output,
+ cudaStream_t stream);
+
+void runSumAlongColumns(
+ Tensor<half, 1, true>& input,
+ Tensor<half, 2, true>& output,
+ cudaStream_t stream);
+
+// output[x][i] = input[i] for all x
+void runAssignAlongColumns(
+ Tensor<float, 1, true>& input,
+ Tensor<float, 2, true>& output,
+ cudaStream_t stream);
+
+void runAssignAlongColumns(
+ Tensor<half, 1, true>& input,
+ Tensor<half, 2, true>& output,
+ cudaStream_t stream);
+
+// output[i][x] += input[i] for all x
+// If zeroClamp, output[i][x] = max(output[i][x] + input[i], 0) for all x
+void runSumAlongRows(
+ Tensor<float, 1, true>& input,
+ Tensor<float, 2, true>& output,
+ bool zeroClamp,
+ cudaStream_t stream);
+
+void runSumAlongRows(
+ Tensor<half, 1, true>& input,
+ Tensor<half, 2, true>& output,
+ bool zeroClamp,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsCagra.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsCagra.cu
new file mode 100644
index 0000000..f60e1e3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsCagra.cu
@@ -0,0 +1,327 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/impl/CuvsCagra.cuh>
+
+#include <cuvs/neighbors/cagra.hpp>
+#include <raft/core/device_mdspan.hpp>
+#include <raft/core/device_resources.hpp>
+#include <raft/core/resource/thrust_policy.hpp>
+
+namespace faiss {
+namespace gpu {
+
+CuvsCagra::CuvsCagra(
+ GpuResources* resources,
+ int dim,
+ idx_t intermediate_graph_degree,
+ idx_t graph_degree,
+ faiss::cagra_build_algo graph_build_algo,
+ size_t nn_descent_niter,
+ bool store_dataset,
+ faiss::MetricType metric,
+ float metricArg,
+ IndicesOptions indicesOptions,
+ std::optional<cuvs::neighbors::ivf_pq::index_params> ivf_pq_params,
+ std::optional<cuvs::neighbors::ivf_pq::search_params>
+ ivf_pq_search_params,
+ float refine_rate)
+ : resources_(resources),
+ dim_(dim),
+ graph_build_algo_(graph_build_algo),
+ nn_descent_niter_(nn_descent_niter),
+ store_dataset_(store_dataset),
+ metric_(metric),
+ metricArg_(metricArg),
+ index_params_(),
+ ivf_pq_params_(ivf_pq_params),
+ ivf_pq_search_params_(ivf_pq_search_params),
+ refine_rate_(refine_rate) {
+ FAISS_THROW_IF_NOT_MSG(
+ metric == faiss::METRIC_L2 || metric == faiss::METRIC_INNER_PRODUCT,
+ "CAGRA currently only supports L2 or Inner Product metric.");
+ FAISS_THROW_IF_NOT_MSG(
+ indicesOptions == faiss::gpu::INDICES_64_BIT,
+ "only INDICES_64_BIT is supported for cuVS CAGRA index");
+
+ index_params_.intermediate_graph_degree = intermediate_graph_degree;
+ index_params_.graph_degree = graph_degree;
+ index_params_.attach_dataset_on_build = store_dataset;
+
+ if (!ivf_pq_search_params_) {
+ ivf_pq_search_params_ =
+ std::make_optional<cuvs::neighbors::ivf_pq::search_params>();
+ }
+ index_params_.metric = metricFaissToCuvs(metric_, false);
+
+ reset();
+}
+
+CuvsCagra::CuvsCagra(
+ GpuResources* resources,
+ int dim,
+ idx_t n,
+ int graph_degree,
+ const float* distances,
+ const idx_t* knn_graph,
+ faiss::MetricType metric,
+ float metricArg,
+ IndicesOptions indicesOptions)
+ : resources_(resources),
+ dim_(dim),
+ metric_(metric),
+ metricArg_(metricArg) {
+ FAISS_THROW_IF_NOT_MSG(
+ metric == faiss::METRIC_L2 || metric == faiss::METRIC_INNER_PRODUCT,
+ "CAGRA currently only supports L2 or Inner Product metric.");
+ FAISS_THROW_IF_NOT_MSG(
+ indicesOptions == faiss::gpu::INDICES_64_BIT,
+ "only INDICES_64_BIT is supported for cuVS CAGRA index");
+
+ auto distances_on_gpu = getDeviceForAddress(distances) >= 0;
+ auto knn_graph_on_gpu = getDeviceForAddress(knn_graph) >= 0;
+
+ FAISS_ASSERT(distances_on_gpu == knn_graph_on_gpu);
+
+ storage_ = distances;
+ n_ = n;
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ if (distances_on_gpu && knn_graph_on_gpu) {
+ raft_handle.sync_stream();
+ // Copying to host so that cuvs::neighbors::cagra::index
+ // creates an owning copy of the knn graph on device
+ auto knn_graph_copy =
+ raft::make_host_matrix<uint32_t, int64_t>(n, graph_degree);
+ thrust::copy(
+ thrust::device_ptr<const idx_t>(knn_graph),
+ thrust::device_ptr<const idx_t>(knn_graph + (n * graph_degree)),
+ knn_graph_copy.data_handle());
+
+ auto distances_mds =
+ raft::make_device_matrix_view<const float, int64_t>(
+ distances, n, dim);
+
+ cuvs_index = std::make_shared<
+ cuvs::neighbors::cagra::index<float, uint32_t>>(
+ raft_handle,
+ metricFaissToCuvs(metric_, false),
+ distances_mds,
+ raft::make_const_mdspan(knn_graph_copy.view()));
+ } else if (!distances_on_gpu && !knn_graph_on_gpu) {
+ // copy idx_t (int64_t) host knn_graph to uint32_t host knn_graph
+ auto knn_graph_copy =
+ raft::make_host_matrix<uint32_t, int64_t>(n, graph_degree);
+ std::copy(
+ knn_graph,
+ knn_graph + (n * graph_degree),
+ knn_graph_copy.data_handle());
+
+ auto distances_mds = raft::make_host_matrix_view<const float, int64_t>(
+ distances, n, dim);
+
+ cuvs_index = std::make_shared<
+ cuvs::neighbors::cagra::index<float, uint32_t>>(
+ raft_handle,
+ metricFaissToCuvs(metric_, false),
+ distances_mds,
+ raft::make_const_mdspan(knn_graph_copy.view()));
+ } else {
+ FAISS_THROW_MSG(
+ "distances and knn_graph must both be in device or host memory");
+ }
+}
+
+void CuvsCagra::train(idx_t n, const float* x) {
+ storage_ = x;
+ n_ = n;
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ if (!ivf_pq_params_) {
+ ivf_pq_params_ = cuvs::neighbors::ivf_pq::index_params::from_dataset(
+ raft::make_extents<uint32_t>(
+ static_cast<uint32_t>(n_), static_cast<uint32_t>(dim_)),
+ metricFaissToCuvs(metric_, false));
+ }
+ if (graph_build_algo_ == faiss::cagra_build_algo::IVF_PQ) {
+ cuvs::neighbors::cagra::graph_build_params::ivf_pq_params
+ graph_build_params;
+ graph_build_params.build_params = ivf_pq_params_.value();
+ graph_build_params.search_params = ivf_pq_search_params_.value();
+ graph_build_params.refinement_rate = refine_rate_.value();
+ index_params_.graph_build_params = graph_build_params;
+ if (index_params_.graph_degree ==
+ index_params_.intermediate_graph_degree) {
+ index_params_.intermediate_graph_degree =
+ 1.5 * index_params_.graph_degree;
+ }
+ } else {
+ cuvs::neighbors::cagra::graph_build_params::nn_descent_params
+ graph_build_params(index_params_.intermediate_graph_degree);
+ graph_build_params.max_iterations = nn_descent_niter_;
+ index_params_.graph_build_params = graph_build_params;
+ }
+
+ if (getDeviceForAddress(x) >= 0) {
+ auto dataset =
+ raft::make_device_matrix_view<const float, int64_t>(x, n, dim_);
+ cuvs_index = std::make_shared<
+ cuvs::neighbors::cagra::index<float, uint32_t>>(
+ cuvs::neighbors::cagra::build(
+ raft_handle, index_params_, dataset));
+ } else {
+ auto dataset =
+ raft::make_host_matrix_view<const float, int64_t>(x, n, dim_);
+ cuvs_index = std::make_shared<
+ cuvs::neighbors::cagra::index<float, uint32_t>>(
+ cuvs::neighbors::cagra::build(
+ raft_handle, index_params_, dataset));
+ }
+}
+
+void CuvsCagra::search(
+ Tensor<float, 2, true>& queries,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ idx_t max_queries,
+ idx_t itopk_size,
+ idx_t max_iterations,
+ faiss::cagra_search_algo graph_search_algo,
+ idx_t team_size,
+ idx_t search_width,
+ idx_t min_iterations,
+ idx_t thread_block_size,
+ faiss::cagra_hash_mode hash_mode,
+ idx_t hashmap_min_bitlen,
+ float hashmap_max_fill_rate,
+ idx_t num_random_samplings,
+ idx_t rand_xor_mask) {
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ idx_t numQueries = queries.getSize(0);
+ idx_t cols = queries.getSize(1);
+ idx_t k_ = k;
+
+ FAISS_ASSERT(cuvs_index);
+ FAISS_ASSERT(numQueries > 0);
+ FAISS_ASSERT(cols == dim_);
+
+ if (!store_dataset_) {
+ if (getDeviceForAddress(storage_) >= 0) {
+ auto dataset = raft::make_device_matrix_view<const float, int64_t>(
+ storage_, n_, dim_);
+ cuvs_index->update_dataset(raft_handle, dataset);
+ } else {
+ auto dataset = raft::make_host_matrix_view<const float, int64_t>(
+ storage_, n_, dim_);
+ cuvs_index->update_dataset(raft_handle, dataset);
+ }
+ store_dataset_ = true;
+ }
+
+ auto queries_view = raft::make_device_matrix_view<const float, int64_t>(
+ queries.data(), numQueries, cols);
+ auto distances_view = raft::make_device_matrix_view<float, int64_t>(
+ outDistances.data(), numQueries, k_);
+ auto indices_view = raft::make_device_matrix_view<idx_t, int64_t>(
+ outIndices.data(), numQueries, k_);
+
+ cuvs::neighbors::cagra::search_params search_pams;
+ search_pams.max_queries = max_queries;
+ search_pams.itopk_size = itopk_size;
+ search_pams.max_iterations = max_iterations;
+ search_pams.algo =
+ static_cast<cuvs::neighbors::cagra::search_algo>(graph_search_algo);
+ search_pams.team_size = team_size;
+ search_pams.search_width = search_width;
+ search_pams.min_iterations = min_iterations;
+ search_pams.thread_block_size = thread_block_size;
+ search_pams.hashmap_mode =
+ static_cast<cuvs::neighbors::cagra::hash_mode>(hash_mode);
+ search_pams.hashmap_min_bitlen = hashmap_min_bitlen;
+ search_pams.hashmap_max_fill_rate = hashmap_max_fill_rate;
+ search_pams.num_random_samplings = num_random_samplings;
+ search_pams.rand_xor_mask = rand_xor_mask;
+
+ auto indices_copy = raft::make_device_matrix<uint32_t, int64_t>(
+ raft_handle, numQueries, k_);
+
+ cuvs::neighbors::cagra::search(
+ raft_handle,
+ search_pams,
+ *cuvs_index,
+ queries_view,
+ indices_copy.view(),
+ distances_view);
+ thrust::copy(
+ raft::resource::get_thrust_policy(raft_handle),
+ indices_copy.data_handle(),
+ indices_copy.data_handle() + indices_copy.size(),
+ indices_view.data_handle());
+}
+
+void CuvsCagra::reset() {
+ cuvs_index.reset();
+}
+
+idx_t CuvsCagra::get_knngraph_degree() const {
+ FAISS_ASSERT(cuvs_index);
+ return static_cast<idx_t>(cuvs_index->graph_degree());
+}
+
+std::vector<idx_t> CuvsCagra::get_knngraph() const {
+ FAISS_ASSERT(cuvs_index);
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ auto stream = raft_handle.get_stream();
+
+ auto device_graph = cuvs_index->graph();
+
+ std::vector<idx_t> host_graph(
+ device_graph.extent(0) * device_graph.extent(1));
+
+ raft_handle.sync_stream();
+
+ thrust::copy(
+ thrust::device_ptr<const uint32_t>(device_graph.data_handle()),
+ thrust::device_ptr<const uint32_t>(
+ device_graph.data_handle() + device_graph.size()),
+ host_graph.data());
+
+ return host_graph;
+}
+
+const float* CuvsCagra::get_training_dataset() const {
+ return storage_;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsCagra.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsCagra.cuh
new file mode 100644
index 0000000..8e458d8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsCagra.cuh
@@ -0,0 +1,151 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/GpuResources.h>
+#include <cstddef>
+#include <faiss/gpu/utils/Tensor.cuh>
+#include <optional>
+
+#include <faiss/MetricType.h>
+
+#include <cuvs/neighbors/cagra.hpp>
+#include <cuvs/neighbors/ivf_pq.hpp>
+
+namespace faiss {
+
+/// Algorithm used to build underlying CAGRA graph
+enum class cagra_build_algo { IVF_PQ, NN_DESCENT };
+
+enum class cagra_search_algo { SINGLE_CTA, MULTI_CTA };
+
+enum class cagra_hash_mode { HASH, SMALL, AUTO };
+
+namespace gpu {
+
+class CuvsCagra {
+ public:
+ CuvsCagra(
+ GpuResources* resources,
+ int dim,
+ idx_t intermediate_graph_degree,
+ idx_t graph_degree,
+ faiss::cagra_build_algo graph_build_algo,
+ size_t nn_descent_niter,
+ bool store_dataset,
+ faiss::MetricType metric,
+ float metricArg,
+ IndicesOptions indicesOptions,
+ std::optional<cuvs::neighbors::ivf_pq::index_params> ivf_pq_params =
+ std::nullopt,
+ std::optional<cuvs::neighbors::ivf_pq::search_params>
+ ivf_pq_search_params = std::nullopt,
+ float refine_rate = 2.0f);
+
+ CuvsCagra(
+ GpuResources* resources,
+ int dim,
+ idx_t n,
+ int graph_degree,
+ const float* distances,
+ const idx_t* knn_graph,
+ faiss::MetricType metric,
+ float metricArg,
+ IndicesOptions indicesOptions);
+
+ ~CuvsCagra() = default;
+
+ void train(idx_t n, const float* x);
+
+ void search(
+ Tensor<float, 2, true>& queries,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ idx_t max_queries,
+ idx_t itopk_size,
+ idx_t max_iterations,
+ faiss::cagra_search_algo graph_search_algo,
+ idx_t team_size,
+ idx_t search_width,
+ idx_t min_iterations,
+ idx_t thread_block_size,
+ faiss::cagra_hash_mode hash_mode,
+ idx_t hashmap_min_bitlen,
+ float hashmap_max_fill_rate,
+ idx_t num_random_samplings,
+ idx_t rand_xor_mask);
+
+ void reset();
+
+ idx_t get_knngraph_degree() const;
+
+ std::vector<idx_t> get_knngraph() const;
+
+ const float* get_training_dataset() const;
+
+ private:
+ /// Collection of GPU resources that we use
+ GpuResources* resources_;
+
+ /// Training dataset
+ const float* storage_;
+ int n_;
+
+ /// Expected dimensionality of the vectors
+ const int dim_;
+
+ /// Controls the underlying cuVS index if it should store the dataset in
+ /// device memory. Default set to true for enabling search capabilities on
+ /// the index.
+ /// NB: This is also required to be set to true for deserializing
+ /// an IndexHNSWCagra object.
+ bool store_dataset_ = true;
+
+ /// Metric type of the index
+ faiss::MetricType metric_;
+
+ /// Metric arg
+ float metricArg_;
+
+ /// Parameters to build cuVS CAGRA index
+ faiss::cagra_build_algo graph_build_algo_;
+ cuvs::neighbors::cagra::index_params index_params_;
+
+ /// Parameters to build CAGRA graph using IVF PQ
+ std::optional<cuvs::neighbors::ivf_pq::index_params> ivf_pq_params_;
+ std::optional<cuvs::neighbors::ivf_pq::search_params> ivf_pq_search_params_;
+ std::optional<float> refine_rate_;
+
+ /// Parameters to build CAGRA graph using NN Descent
+ size_t nn_descent_niter_ = 20;
+
+ /// Instance of trained cuVS CAGRA index
+ std::shared_ptr<cuvs::neighbors::cagra::index<float, uint32_t>> cuvs_index{
+ nullptr};
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsFlatIndex.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsFlatIndex.cu
new file mode 100644
index 0000000..15cf427
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsFlatIndex.cu
@@ -0,0 +1,145 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <faiss/gpu/impl/CuvsFlatIndex.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+
+#include <optional>
+#include <vector>
+
+#include <cuvs/neighbors/brute_force.hpp>
+#include <raft/core/device_mdspan.hpp>
+#include <raft/core/logger.hpp>
+#include <raft/distance/distance_types.hpp>
+#include <raft/linalg/unary_op.cuh>
+
+namespace faiss {
+namespace gpu {
+
+using namespace cuvs::distance;
+using namespace cuvs::neighbors;
+
+CuvsFlatIndex::CuvsFlatIndex(
+ GpuResources* res,
+ int dim,
+ bool useFloat16,
+ MemorySpace space)
+ : FlatIndex(res, dim, useFloat16, space) {}
+
+void CuvsFlatIndex::query(
+ Tensor<float, 2, true>& input,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance) {
+ /**
+ * cuVS doesn't yet support half-precision in bfknn.
+ * Use FlatIndex for float16 for now
+ */
+ if (useFloat16_) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // We need to convert the input to float16 for comparison to ourselves
+ auto inputHalf = convertTensorTemporary<float, half, 2>(
+ resources_, stream, input);
+
+ FlatIndex::query(
+ inputHalf,
+ k,
+ metric,
+ metricArg,
+ outDistances,
+ outIndices,
+ exactDistance);
+ } else {
+ raft::device_resources& handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ auto index = raft::make_device_matrix_view<const float, int64_t>(
+ vectors_.data(), vectors_.getSize(0), vectors_.getSize(1));
+ auto search = raft::make_device_matrix_view<const float, int64_t>(
+ input.data(), input.getSize(0), input.getSize(1));
+
+ auto inds = raft::make_device_matrix_view<idx_t, int64_t>(
+ outIndices.data(),
+ outIndices.getSize(0),
+ outIndices.getSize(1));
+ auto dists = raft::make_device_matrix_view<float, int64_t>(
+ outDistances.data(),
+ outDistances.getSize(0),
+ outDistances.getSize(1));
+
+ cuvsDistanceType distance = metricFaissToCuvs(metric, exactDistance);
+
+ std::optional<raft::device_vector_view<const float, int64_t>>
+ norms_view = raft::make_device_vector_view(
+ norms_.data(), norms_.getSize(0));
+
+ cuvs::neighbors::brute_force::index idx(
+ handle, index, norms_view, distance, metricArg);
+ cuvs::neighbors::brute_force::search(handle, idx, search, inds, dists);
+
+ if (metric == MetricType::METRIC_Lp) {
+ raft::linalg::unary_op(
+ handle,
+ raft::make_const_mdspan(dists),
+ dists,
+ [metricArg] __device__(const float& a) {
+ return powf(a, metricArg);
+ });
+ } else if (metric == MetricType::METRIC_JensenShannon) {
+ raft::linalg::unary_op(
+ handle,
+ raft::make_const_mdspan(dists),
+ dists,
+ [] __device__(const float& a) { return powf(a, 2); });
+ }
+ }
+}
+
+void CuvsFlatIndex::query(
+ Tensor<half, 2, true>& vecs,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance) {
+ FAISS_ASSERT(useFloat16_);
+
+ // FIXME: ref https://github.com/rapidsai/raft/issues/1280
+ FlatIndex::query(
+ vecs,
+ k,
+ metric,
+ metricArg,
+ outDistances,
+ outIndices,
+ exactDistance);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsFlatIndex.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsFlatIndex.cuh
new file mode 100644
index 0000000..b856351
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsFlatIndex.cuh
@@ -0,0 +1,72 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+
+#pragma GCC visibility push(default)
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+/// Holder of GPU resources for a particular flat index
+/// Can be in either float16 or float32 mode. If float32, we only store
+/// the vectors in float32.
+/// If float16, we store the vectors in both float16 and float32, where float32
+/// data is possibly needed for certain residual operations
+class CuvsFlatIndex : public FlatIndex {
+ public:
+ CuvsFlatIndex(
+ GpuResources* res,
+ int dim,
+ bool useFloat16,
+ MemorySpace space);
+
+ void query(
+ Tensor<float, 2, true>& vecs,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance) override;
+
+ void query(
+ Tensor<half, 2, true>& vecs,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance) override;
+};
+
+} // namespace gpu
+} // namespace faiss
+#pragma GCC visibility pop
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFFlat.cu
new file mode 100644
index 0000000..2cccee8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFFlat.cu
@@ -0,0 +1,555 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <faiss/gpu/impl/CuvsIVFFlat.cuh>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/impl/IVFFlat.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+
+#include <cuvs/neighbors/common.hpp>
+#include <cuvs/neighbors/ivf_flat.hpp>
+#include <raft/linalg/map.cuh>
+#include <raft/linalg/norm.cuh>
+
+#include <limits>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+CuvsIVFFlat::CuvsIVFFlat(
+ GpuResources* res,
+ int dim,
+ int nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ faiss::ScalarQuantizer* scalarQ,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space)
+ : IVFFlat(res,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ useResidual,
+ scalarQ,
+ interleavedLayout,
+ // skip ptr allocations in base class (handled by cuVS
+ // internally)
+ indicesOptions,
+ space) {
+ FAISS_THROW_IF_NOT_MSG(
+ indicesOptions == INDICES_64_BIT,
+ "only INDICES_64_BIT is supported for cuVS index");
+}
+
+CuvsIVFFlat::~CuvsIVFFlat() {}
+
+void CuvsIVFFlat::reserveMemory(idx_t numVecs) {
+ fprintf(stderr,
+ "WARN: reserveMemory is NOP. Pre-allocation of IVF lists is not supported with cuVS enabled.\n");
+}
+
+void CuvsIVFFlat::reset() {
+ cuvs_index.reset();
+}
+
+void CuvsIVFFlat::setCuvsIndex(
+ cuvs::neighbors::ivf_flat::index<float, idx_t>&& idx) {
+ cuvs_index =
+ std::make_shared<cuvs::neighbors::ivf_flat::index<float, idx_t>>(
+ std::move(idx));
+}
+
+void CuvsIVFFlat::search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ /// NB: The coarse quantizer is ignored here. The user is assumed to have
+ /// called updateQuantizer() to modify the cuVS index if the quantizer was
+ /// modified externally
+
+ uint32_t numQueries = queries.getSize(0);
+ uint32_t cols = queries.getSize(1);
+ uint32_t k_ = k;
+
+ // Device is already set in GpuIndex::search
+ FAISS_ASSERT(cuvs_index != nullptr);
+ FAISS_ASSERT(numQueries > 0);
+ FAISS_ASSERT(cols == dim_);
+ FAISS_THROW_IF_NOT(nprobe > 0 && nprobe <= numLists_);
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ cuvs::neighbors::ivf_flat::search_params pams;
+ pams.n_probes = nprobe;
+
+ auto queries_view = raft::make_device_matrix_view<const float, idx_t>(
+ queries.data(), (idx_t)numQueries, (idx_t)cols);
+ auto out_inds_view = raft::make_device_matrix_view<idx_t, idx_t>(
+ outIndices.data(), (idx_t)numQueries, (idx_t)k_);
+ auto out_dists_view = raft::make_device_matrix_view<float, idx_t>(
+ outDistances.data(), (idx_t)numQueries, (idx_t)k_);
+
+ cuvs::neighbors::ivf_flat::search(
+ raft_handle,
+ pams,
+ *cuvs_index,
+ queries_view,
+ out_inds_view,
+ out_dists_view);
+
+ /// Identify NaN rows and mask their nearest neighbors
+ auto nan_flag = raft::make_device_vector<bool>(raft_handle, numQueries);
+
+ validRowIndices(resources_, queries, nan_flag.data_handle());
+
+ raft::linalg::map_offset(
+ raft_handle,
+ raft::make_device_vector_view(outIndices.data(), numQueries * k_),
+ [nan_flag = nan_flag.data_handle(),
+ out_inds = outIndices.data(),
+ k_] __device__(uint32_t i) {
+ uint32_t row = i / k_;
+ if (!nan_flag[row])
+ return idx_t(-1);
+ return out_inds[i];
+ });
+
+ float max_val = std::numeric_limits<float>::max();
+ raft::linalg::map_offset(
+ raft_handle,
+ raft::make_device_vector_view(outDistances.data(), numQueries * k_),
+ [nan_flag = nan_flag.data_handle(),
+ out_dists = outDistances.data(),
+ max_val,
+ k_] __device__(uint32_t i) {
+ uint32_t row = i / k_;
+ if (!nan_flag[row])
+ return max_val;
+ return out_dists[i];
+ });
+}
+
+idx_t CuvsIVFFlat::addVectors(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices) {
+ /// NB: The coarse quantizer is ignored here. The user is assumed to have
+ /// called updateQuantizer() to update the cuVS index if the quantizer was
+ /// modified externally
+
+ FAISS_ASSERT(cuvs_index != nullptr);
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ /// Remove rows containing NaNs
+ idx_t n_rows_valid = inplaceGatherFilteredRows(resources_, vecs, indices);
+
+ cuvs::neighbors::ivf_flat::extend(
+ raft_handle,
+ raft::make_device_matrix_view<const float, idx_t>(
+ vecs.data(), n_rows_valid, dim_),
+ std::make_optional<raft::device_vector_view<const idx_t, idx_t>>(
+ raft::make_device_vector_view<const idx_t, idx_t>(
+ indices.data(), n_rows_valid)),
+ cuvs_index.get());
+
+ return n_rows_valid;
+}
+
+idx_t CuvsIVFFlat::getListLength(idx_t listId) const {
+ FAISS_ASSERT(cuvs_index != nullptr);
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ uint32_t size;
+ raft::update_host(
+ &size,
+ cuvs_index->list_sizes().data_handle() + listId,
+ 1,
+ raft_handle.get_stream());
+ raft_handle.sync_stream();
+
+ return static_cast<int>(size);
+}
+
+/// Return the list indices of a particular list back to the CPU
+std::vector<idx_t> CuvsIVFFlat::getListIndices(idx_t listId) const {
+ FAISS_ASSERT(cuvs_index != nullptr);
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ auto stream = raft_handle.get_stream();
+
+ idx_t listSize = getListLength(listId);
+
+ std::vector<idx_t> vec(listSize);
+
+ // fetch the list indices ptr on host
+ idx_t* list_indices_ptr;
+
+ raft::update_host(
+ &list_indices_ptr,
+ const_cast<idx_t**>(cuvs_index->inds_ptrs().data_handle()) + listId,
+ 1,
+ stream);
+ raft_handle.sync_stream();
+
+ raft::update_host(vec.data(), list_indices_ptr, listSize, stream);
+ raft_handle.sync_stream();
+
+ return vec;
+}
+
+/// Return the encoded vectors of a particular list back to the CPU
+std::vector<uint8_t> CuvsIVFFlat::getListVectorData(
+ idx_t listId,
+ bool gpuFormat) const {
+ if (gpuFormat) {
+ FAISS_THROW_MSG("gpuFormat should be false for cuVS indices");
+ }
+ FAISS_ASSERT(cuvs_index != nullptr);
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ auto stream = raft_handle.get_stream();
+
+ idx_t listSize = getListLength(listId);
+
+ // the interleaved block can be slightly larger than the list size (it's
+ // rounded up)
+ auto gpuListSizeInBytes = getGpuVectorsEncodingSize_(listSize);
+ auto cpuListSizeInBytes = getCpuVectorsEncodingSize_(listSize);
+
+ std::vector<uint8_t> interleaved_codes(gpuListSizeInBytes);
+ std::vector<uint8_t> flat_codes(cpuListSizeInBytes);
+
+ float* list_data_ptr;
+
+ // fetch the list data ptr on host
+ raft::update_host(
+ &list_data_ptr,
+ cuvs_index->data_ptrs().data_handle() + listId,
+ 1,
+ stream);
+ raft_handle.sync_stream();
+
+ raft::update_host(
+ interleaved_codes.data(),
+ reinterpret_cast<uint8_t*>(list_data_ptr),
+ gpuListSizeInBytes,
+ stream);
+ raft_handle.sync_stream();
+
+ CuvsIVFFlatCodePackerInterleaved packer(
+ (size_t)listSize, dim_, cuvs_index->veclen());
+ packer.unpack_all(interleaved_codes.data(), flat_codes.data());
+ return flat_codes;
+}
+
+/// Performs search when we are already given the IVF cells to look at
+/// (GpuIndexIVF::search_preassigned implementation)
+void CuvsIVFFlat::searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) {
+ // TODO: Fill this in!
+ // Reference issue: https://github.com/facebookresearch/faiss/issues/3243
+ FAISS_THROW_MSG("searchPreassigned is not implemented for cuVS index");
+}
+
+void CuvsIVFFlat::updateQuantizer(Index* quantizer) {
+ FAISS_THROW_IF_NOT(quantizer->is_trained);
+
+ // Must match our basic IVF parameters
+ FAISS_THROW_IF_NOT(quantizer->d == getDim());
+ FAISS_THROW_IF_NOT(quantizer->ntotal == getNumLists());
+
+ size_t total_elems = quantizer->ntotal * quantizer->d;
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ cuvs::neighbors::ivf_flat::index_params pams;
+ pams.add_data_on_build = false;
+ pams.metric = metricFaissToCuvs(metric_, false);
+ pams.n_lists = numLists_;
+ cuvs_index =
+ std::make_shared<cuvs::neighbors::ivf_flat::index<float, idx_t>>(
+ raft_handle, pams, static_cast<uint32_t>(dim_));
+ cuvs::neighbors::ivf_flat::helpers::reset_index(
+ raft_handle, cuvs_index.get());
+
+ // If the index instance is a GpuIndexFlat, then we can use direct access to
+ // the centroids within.
+ auto gpuQ = dynamic_cast<GpuIndexFlat*>(quantizer);
+ if (gpuQ) {
+ auto gpuData = gpuQ->getGpuData();
+
+ if (gpuData->getUseFloat16()) {
+ // The FlatIndex keeps its data in float16; we need to reconstruct
+ // as float32 and store locally
+ DeviceTensor<float, 2, true> centroids(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {getNumLists(), getDim()});
+
+ gpuData->reconstruct(0, gpuData->getSize(), centroids);
+
+ raft::update_device(
+ cuvs_index->centers().data_handle(),
+ centroids.data(),
+ total_elems,
+ stream);
+ } else {
+ /// No reconstruct needed since the centers are already in float32
+ auto centroids = gpuData->getVectorsFloat32Ref();
+
+ raft::update_device(
+ cuvs_index->centers().data_handle(),
+ centroids.data(),
+ total_elems,
+ stream);
+ }
+ } else {
+ // Otherwise, we need to reconstruct all vectors from the index and copy
+ // them to the GPU, in order to have access as needed for residual
+ // computation
+ auto vecs = std::vector<float>(getNumLists() * getDim());
+ quantizer->reconstruct_n(0, quantizer->ntotal, vecs.data());
+
+ raft::update_device(
+ cuvs_index->centers().data_handle(),
+ vecs.data(),
+ total_elems,
+ stream);
+ }
+}
+
+void CuvsIVFFlat::copyInvertedListsFrom(const InvertedLists* ivf) {
+ size_t nlist = ivf ? ivf->nlist : 0;
+ size_t ntotal = ivf ? ivf->compute_ntotal() : 0;
+
+ raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ std::vector<uint32_t> list_sizes_(nlist);
+ std::vector<idx_t> indices_(ntotal);
+
+ // the index must already exist
+ FAISS_ASSERT(cuvs_index != nullptr);
+
+ auto& cuvs_index_lists = cuvs_index->lists();
+
+ // conservative memory alloc for cloning cpu inverted lists
+ cuvs::neighbors::ivf_flat::list_spec<uint32_t, float, idx_t> ivf_list_spec{
+ static_cast<uint32_t>(dim_), true};
+
+ for (size_t i = 0; i < nlist; ++i) {
+ size_t listSize = ivf->list_size(i);
+
+ // GPU index can only support max int entries per list
+ FAISS_THROW_IF_NOT_FMT(
+ listSize <= (size_t)std::numeric_limits<int>::max(),
+ "GPU inverted list can only support "
+ "%zu entries; %zu found",
+ (size_t)std::numeric_limits<int>::max(),
+ listSize);
+
+ // store the list size
+ list_sizes_[i] = static_cast<uint32_t>(listSize);
+
+ // This cuVS list must currently be empty
+ FAISS_ASSERT(getListLength(i) == 0);
+
+ cuvs::neighbors::ivf::resize_list(
+ raft_handle,
+ cuvs_index_lists[i],
+ ivf_list_spec,
+ (uint32_t)listSize,
+ (uint32_t)0);
+ }
+
+ // Update the pointers and the sizes
+ cuvs::neighbors::ivf_flat::helpers::recompute_internal_state(
+ raft_handle, cuvs_index.get());
+
+ for (size_t i = 0; i < nlist; ++i) {
+ size_t listSize = ivf->list_size(i);
+ addEncodedVectorsToList_(
+ i, ivf->get_codes(i), ivf->get_ids(i), listSize);
+ }
+
+ raft::update_device(
+ cuvs_index->list_sizes().data_handle(),
+ list_sizes_.data(),
+ nlist,
+ raft_handle.get_stream());
+
+ // Precompute the centers vector norms for L2Expanded distance
+ if (this->metric_ == faiss::METRIC_L2) {
+ cuvs_index->allocate_center_norms(raft_handle);
+ raft::linalg::rowNorm(
+ cuvs_index->center_norms().value().data_handle(),
+ cuvs_index->centers().data_handle(),
+ cuvs_index->dim(),
+ (uint32_t)nlist,
+ raft::linalg::L2Norm,
+ true,
+ raft_handle.get_stream());
+ }
+}
+
+size_t CuvsIVFFlat::getGpuVectorsEncodingSize_(idx_t numVecs) const {
+ idx_t bits = 32 /* float */;
+
+ // bytes to encode a block of 32 vectors (single dimension)
+ idx_t bytesPerDimBlock = bits * 32 / 8; // = 128
+
+ // bytes to fully encode 32 vectors
+ idx_t bytesPerBlock = bytesPerDimBlock * dim_;
+
+ // number of blocks of 32 vectors we have
+ idx_t numBlocks =
+ utils::divUp(numVecs, cuvs::neighbors::ivf_flat::kIndexGroupSize);
+
+ // total size to encode numVecs
+ return bytesPerBlock * numBlocks;
+}
+
+void CuvsIVFFlat::addEncodedVectorsToList_(
+ idx_t listId,
+ const void* codes,
+ const idx_t* indices,
+ idx_t numVecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // If there's nothing to add, then there's nothing we have to do
+ if (numVecs == 0) {
+ return;
+ }
+
+ // The GPU might have a different layout of the memory
+ auto gpuListSizeInBytes = getGpuVectorsEncodingSize_(numVecs);
+
+ // We only have int32 length representations on the GPU per each
+ // list; the length is in sizeof(char)
+ FAISS_ASSERT(gpuListSizeInBytes <= (size_t)std::numeric_limits<int>::max());
+
+ std::vector<uint8_t> interleaved_codes(gpuListSizeInBytes);
+ CuvsIVFFlatCodePackerInterleaved packer(
+ (size_t)numVecs, (uint32_t)dim_, cuvs_index->veclen());
+
+ packer.pack_all(
+ reinterpret_cast<const uint8_t*>(codes), interleaved_codes.data());
+
+ float* list_data_ptr;
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ /// fetch the list data ptr on host
+ raft::update_host(
+ &list_data_ptr,
+ cuvs_index->data_ptrs().data_handle() + listId,
+ 1,
+ stream);
+ raft_handle.sync_stream();
+
+ raft::update_device(
+ reinterpret_cast<uint8_t*>(list_data_ptr),
+ interleaved_codes.data(),
+ gpuListSizeInBytes,
+ stream);
+
+ /// Handle the indices as well
+ idx_t* list_indices_ptr;
+
+ // fetch the list indices ptr on host
+ raft::update_host(
+ &list_indices_ptr,
+ cuvs_index->inds_ptrs().data_handle() + listId,
+ 1,
+ stream);
+ raft_handle.sync_stream();
+
+ raft::update_device(list_indices_ptr, indices, numVecs, stream);
+}
+
+CuvsIVFFlatCodePackerInterleaved::CuvsIVFFlatCodePackerInterleaved(
+ size_t list_size,
+ uint32_t dim,
+ uint32_t chunk_size) {
+ this->dim = dim;
+ this->chunk_size = chunk_size;
+ // NB: dim should be divisible by the number of 4 byte records in one chunk
+ FAISS_ASSERT(dim % chunk_size == 0);
+ nvec = list_size;
+ code_size = dim * 4;
+ block_size =
+ utils::roundUp(nvec, cuvs::neighbors::ivf_flat::kIndexGroupSize);
+}
+
+void CuvsIVFFlatCodePackerInterleaved::pack_1(
+ const uint8_t* flat_code,
+ size_t offset,
+ uint8_t* block) const {
+ cuvs::neighbors::ivf_flat::helpers::codepacker::pack_1(
+ reinterpret_cast<const float*>(flat_code),
+ reinterpret_cast<float*>(block),
+ dim,
+ chunk_size,
+ static_cast<uint32_t>(offset));
+}
+
+void CuvsIVFFlatCodePackerInterleaved::unpack_1(
+ const uint8_t* block,
+ size_t offset,
+ uint8_t* flat_code) const {
+ cuvs::neighbors::ivf_flat::helpers::codepacker::unpack_1(
+ reinterpret_cast<const float*>(block),
+ reinterpret_cast<float*>(flat_code),
+ dim,
+ chunk_size,
+ static_cast<uint32_t>(offset));
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFFlat.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFFlat.cuh
new file mode 100644
index 0000000..72764c8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFFlat.cuh
@@ -0,0 +1,151 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/impl/CodePacker.h>
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/impl/IVFFlat.cuh>
+
+#include <cuvs/neighbors/ivf_flat.hpp>
+
+#include <optional>
+
+#pragma GCC visibility push(default)
+namespace faiss {
+namespace gpu {
+
+class CuvsIVFFlat : public IVFFlat {
+ public:
+ CuvsIVFFlat(
+ GpuResources* resources,
+ int dim,
+ int nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ /// Optional ScalarQuantizer
+ faiss::ScalarQuantizer* scalarQ,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ ~CuvsIVFFlat() override;
+
+ /// Reserve GPU memory in our inverted lists for this number of vectors
+ void reserveMemory(idx_t numVecs) override;
+
+ /// Find the approximate k nearest neigbors for `queries` against
+ /// our database
+ void search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) override;
+
+ /// Performs search when we are already given the IVF cells to look at
+ /// (GpuIndexIVF::search_preassigned implementation)
+ void searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) override;
+
+ /// Classify and encode/add vectors to our IVF lists.
+ /// The input data must be on our current device.
+ /// Returns the number of vectors successfully added. Vectors may
+ /// not be able to be added because they contain NaNs.
+ idx_t addVectors(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices) override;
+
+ /// Clear out the cuVS index
+ void reset() override;
+
+ /// For debugging purposes, return the list length of a particular
+ /// list
+ idx_t getListLength(idx_t listId) const override;
+
+ /// Return the list indices of a particular list back to the CPU
+ std::vector<idx_t> getListIndices(idx_t listId) const override;
+
+ /// Return the encoded vectors of a particular list back to the CPU
+ std::vector<uint8_t> getListVectorData(idx_t listId, bool gpuFormat)
+ const override;
+
+ /// Update our cuVS index with this quantizer instance; may be a CPU
+ /// or GPU quantizer
+ void updateQuantizer(Index* quantizer) override;
+
+ /// Copy all inverted lists from a CPU representation to ourselves
+ void copyInvertedListsFrom(const InvertedLists* ivf) override;
+
+ /// Replace the cuVS index
+ void setCuvsIndex(cuvs::neighbors::ivf_flat::index<float, idx_t>&& idx);
+
+ private:
+ /// Adds a set of codes and indices to a list, with the representation
+ /// coming from the CPU equivalent
+ void addEncodedVectorsToList_(
+ idx_t listId,
+ // resident on the host
+ const void* codes,
+ // resident on the host
+ const idx_t* indices,
+ idx_t numVecs) override;
+
+ /// Returns the number of bytes in which an IVF list containing numVecs
+ /// vectors is encoded on the device. Note that due to padding this is not
+ /// the same as the encoding size for a subset of vectors in an IVF list;
+ /// this is the size for an entire IVF list
+ size_t getGpuVectorsEncodingSize_(idx_t numVecs) const override;
+
+ std::shared_ptr<cuvs::neighbors::ivf_flat::index<float, idx_t>> cuvs_index{
+ nullptr};
+};
+
+struct CuvsIVFFlatCodePackerInterleaved : CodePacker {
+ CuvsIVFFlatCodePackerInterleaved(
+ size_t list_size,
+ uint32_t dim,
+ uint32_t chuk_size);
+ void pack_1(const uint8_t* flat_code, size_t offset, uint8_t* block)
+ const final;
+ void unpack_1(const uint8_t* block, size_t offset, uint8_t* flat_code)
+ const final;
+
+ protected:
+ uint32_t chunk_size;
+ uint32_t dim;
+};
+
+} // namespace gpu
+} // namespace faiss
+#pragma GCC visibility pop
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFPQ.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFPQ.cu
new file mode 100644
index 0000000..1e2fef2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFPQ.cu
@@ -0,0 +1,550 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <faiss/gpu/impl/CuvsIVFPQ.cuh>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+
+#include <cuvs/neighbors/common.hpp>
+#include <cuvs/neighbors/ivf_pq.hpp>
+#include <raft/linalg/map.cuh>
+
+#include <limits>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+CuvsIVFPQ::CuvsIVFPQ(
+ GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ int numSubQuantizers,
+ int bitsPerSubQuantizer,
+ bool useFloat16LookupTables,
+ bool useMMCodeDistance,
+ bool interleavedLayout,
+ float* pqCentroidData,
+ IndicesOptions indicesOptions,
+ MemorySpace space)
+ : IVFPQ(resources,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ numSubQuantizers,
+ bitsPerSubQuantizer,
+ useFloat16LookupTables,
+ useMMCodeDistance,
+ interleavedLayout,
+ // skip ptr allocations in base class (handled by cuVS
+ // internally) false,
+ pqCentroidData,
+ indicesOptions,
+ space) {
+ FAISS_THROW_IF_NOT_MSG(
+ indicesOptions == INDICES_64_BIT,
+ "only INDICES_64_BIT is supported for cuVS index");
+}
+
+CuvsIVFPQ::~CuvsIVFPQ() {}
+
+void CuvsIVFPQ::reserveMemory(idx_t numVecs) {
+ fprintf(stderr,
+ "WARN: reserveMemory is NOP. Pre-allocation of IVF lists is not supported with cuVS enabled.\n");
+}
+
+void CuvsIVFPQ::reset() {
+ cuvs_index.reset();
+}
+
+size_t CuvsIVFPQ::reclaimMemory() {
+ fprintf(stderr,
+ "WARN: reclaimMemory is NOP. reclaimMemory is not supported with cuVS enabled.\n");
+ return 0;
+}
+
+void CuvsIVFPQ::setPrecomputedCodes(Index* quantizer, bool enable) {}
+
+idx_t CuvsIVFPQ::getListLength(idx_t listId) const {
+ FAISS_ASSERT(cuvs_index);
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ uint32_t size;
+ raft::update_host(
+ &size,
+ cuvs_index->list_sizes().data_handle() + listId,
+ 1,
+ raft_handle.get_stream());
+ raft_handle.sync_stream();
+
+ return static_cast<int>(size);
+}
+
+void CuvsIVFPQ::updateQuantizer(Index* quantizer) {
+ FAISS_THROW_IF_NOT(quantizer->is_trained);
+
+ // Must match our basic IVF parameters
+ FAISS_THROW_IF_NOT(quantizer->d == getDim());
+ FAISS_THROW_IF_NOT(quantizer->ntotal == getNumLists());
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ cuvs::neighbors::ivf_pq::index_params pams;
+ pams.metric = metricFaissToCuvs(metric_, false);
+ pams.codebook_kind = cuvs::neighbors::ivf_pq::codebook_gen::PER_SUBSPACE;
+ pams.n_lists = numLists_;
+ pams.pq_bits = bitsPerSubQuantizer_;
+ pams.pq_dim = numSubQuantizers_;
+ cuvs_index = std::make_shared<cuvs::neighbors::ivf_pq::index<idx_t>>(
+ raft_handle, pams, static_cast<uint32_t>(dim_));
+
+ cuvs::neighbors::ivf_pq::helpers::reset_index(
+ raft_handle, cuvs_index.get());
+ cuvs::neighbors::ivf_pq::helpers::make_rotation_matrix(
+ raft_handle, cuvs_index.get(), false);
+
+ // If the index instance is a GpuIndexFlat, then we can use direct access to
+ // the centroids within.
+ auto gpuQ = dynamic_cast<GpuIndexFlat*>(quantizer);
+
+ if (gpuQ) {
+ auto gpuData = gpuQ->getGpuData();
+
+ if (gpuData->getUseFloat16()) {
+ DeviceTensor<float, 2, true> centroids(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {getNumLists(), getDim()});
+
+ // The FlatIndex keeps its data in float16; we need to reconstruct
+ // as float32 and store locally
+ gpuData->reconstruct(0, gpuData->getSize(), centroids);
+
+ cuvs::neighbors::ivf_pq::helpers::set_centers(
+ raft_handle,
+ cuvs_index.get(),
+ raft::make_device_matrix_view<float, uint32_t>(
+ centroids.data(), numLists_, dim_));
+ } else {
+ /// No reconstruct needed since the centers are already in float32
+ // The FlatIndex keeps its data in float32, so we can merely
+ // reference it
+ auto centroids = gpuData->getVectorsFloat32Ref();
+
+ cuvs::neighbors::ivf_pq::helpers::set_centers(
+ raft_handle,
+ cuvs_index.get(),
+ raft::make_device_matrix_view<float, uint32_t>(
+ centroids.data(), numLists_, dim_));
+ }
+ } else {
+ DeviceTensor<float, 2, true> centroids(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {getNumLists(), getDim()});
+
+ // Otherwise, we need to reconstruct all vectors from the index and copy
+ // them to the GPU, in order to have access as needed for residual
+ // computation
+ auto vecs = std::vector<float>(getNumLists() * getDim());
+ quantizer->reconstruct_n(0, quantizer->ntotal, vecs.data());
+
+ centroids.copyFrom(vecs, stream);
+
+ cuvs::neighbors::ivf_pq::helpers::set_centers(
+ raft_handle,
+ cuvs_index.get(),
+ raft::make_device_matrix_view<float, uint32_t>(
+ centroids.data(), numLists_, dim_));
+ }
+
+ setPQCentroids_();
+}
+
+/// Return the list indices of a particular list back to the CPU
+std::vector<idx_t> CuvsIVFPQ::getListIndices(idx_t listId) const {
+ FAISS_ASSERT(cuvs_index);
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ auto stream = raft_handle.get_stream();
+
+ idx_t listSize = getListLength(listId);
+
+ std::vector<idx_t> vec(listSize);
+
+ // fetch the list indices ptr on host
+ idx_t* list_indices_ptr;
+
+ raft::update_host(
+ &list_indices_ptr,
+ const_cast<idx_t**>(cuvs_index->inds_ptrs().data_handle()) + listId,
+ 1,
+ stream);
+ raft_handle.sync_stream();
+
+ raft::update_host(vec.data(), list_indices_ptr, listSize, stream);
+ raft_handle.sync_stream();
+
+ return vec;
+}
+
+/// Performs search when we are already given the IVF cells to look at
+/// (GpuIndexIVF::search_preassigned implementation)
+void CuvsIVFPQ::searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) {
+ // TODO: Fill this in!
+ // Reference issue: https://github.com/facebookresearch/faiss/issues/3243
+ FAISS_THROW_MSG("searchPreassigned is not implemented for cuVS index");
+}
+
+size_t CuvsIVFPQ::getGpuListEncodingSize_(idx_t listId) {
+ return static_cast<size_t>(cuvs_index->get_list_size_in_bytes(listId));
+}
+
+/// Return the encoded vectors of a particular list back to the CPU
+std::vector<uint8_t> CuvsIVFPQ::getListVectorData(idx_t listId, bool gpuFormat)
+ const {
+ if (gpuFormat) {
+ FAISS_THROW_MSG(
+ "gpuFormat should be false for cuVS indices. Unpacked codes are flat.");
+ }
+ FAISS_ASSERT(cuvs_index);
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ auto stream = raft_handle.get_stream();
+
+ idx_t listSize = getListLength(listId);
+
+ auto cpuListSizeInBytes = getCpuVectorsEncodingSize_(listSize);
+
+ std::vector<uint8_t> flat_codes(
+ cpuListSizeInBytes, static_cast<uint8_t>(0));
+
+ idx_t maxBatchSize = 65536;
+ for (idx_t offset_b = 0; offset_b < listSize; offset_b += maxBatchSize) {
+ uint32_t batchSize = min(maxBatchSize, listSize - offset_b);
+ uint32_t bufferSize = getCpuVectorsEncodingSize_(batchSize);
+ uint32_t codesOffset = getCpuVectorsEncodingSize_(offset_b);
+
+ // Fetch flat PQ codes for the current batch
+ auto codes_d = raft::make_device_vector<uint8_t>(
+ raft_handle, static_cast<uint32_t>(bufferSize));
+
+ cuvs::neighbors::ivf_pq::helpers::codepacker::
+ unpack_contiguous_list_data(
+ raft_handle,
+ *cuvs_index,
+ codes_d.data_handle(),
+ batchSize,
+ listId,
+ offset_b);
+
+ // Copy the flat PQ codes to host
+ raft::update_host(
+ flat_codes.data() + codesOffset,
+ codes_d.data_handle(),
+ bufferSize,
+ stream);
+ raft_handle.sync_stream();
+ }
+
+ return flat_codes;
+}
+
+/// Find the approximate k nearest neighbors for `queries` against
+/// our database
+void CuvsIVFPQ::search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ uint32_t numQueries = queries.getSize(0);
+ uint32_t cols = queries.getSize(1);
+ idx_t k_ = std::min(static_cast<idx_t>(k), cuvs_index->size());
+
+ // Device is already set in GpuIndex::search
+ FAISS_ASSERT(cuvs_index);
+ FAISS_ASSERT(numQueries > 0);
+ FAISS_ASSERT(cols == dim_);
+ FAISS_THROW_IF_NOT(nprobe > 0 && nprobe <= numLists_);
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+ cuvs::neighbors::ivf_pq::search_params pams;
+ pams.n_probes = nprobe;
+ pams.lut_dtype = useFloat16LookupTables_ ? CUDA_R_16F : CUDA_R_32F;
+
+ auto queries_view = raft::make_device_matrix_view<const float, idx_t>(
+ queries.data(), (idx_t)numQueries, (idx_t)cols);
+ auto out_inds_view = raft::make_device_matrix_view<idx_t, idx_t>(
+ outIndices.data(), (idx_t)numQueries, (idx_t)k_);
+ auto out_dists_view = raft::make_device_matrix_view<float, idx_t>(
+ outDistances.data(), (idx_t)numQueries, (idx_t)k_);
+
+ cuvs::neighbors::ivf_pq::search(
+ raft_handle,
+ pams,
+ *cuvs_index,
+ queries_view,
+ out_inds_view,
+ out_dists_view);
+
+ /// Identify NaN rows and mask their nearest neighbors
+ auto nan_flag = raft::make_device_vector<bool>(raft_handle, numQueries);
+
+ validRowIndices(resources_, queries, nan_flag.data_handle());
+
+ raft::linalg::map_offset(
+ raft_handle,
+ raft::make_device_vector_view(outIndices.data(), numQueries * k_),
+ [nan_flag = nan_flag.data_handle(),
+ out_inds = outIndices.data(),
+ k_] __device__(uint32_t i) {
+ uint32_t row = i / k_;
+ if (!nan_flag[row])
+ return idx_t(-1);
+ return out_inds[i];
+ });
+
+ float max_val = std::numeric_limits<float>::max();
+ raft::linalg::map_offset(
+ raft_handle,
+ raft::make_device_vector_view(outDistances.data(), numQueries * k_),
+ [nan_flag = nan_flag.data_handle(),
+ out_dists = outDistances.data(),
+ max_val,
+ k_] __device__(uint32_t i) {
+ uint32_t row = i / k_;
+ if (!nan_flag[row])
+ return max_val;
+ return out_dists[i];
+ });
+ raft_handle.sync_stream();
+}
+
+idx_t CuvsIVFPQ::addVectors(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices) {
+ /// NB: The coarse quantizer is ignored here. The user is assumed to have
+ /// called updateQuantizer() to update the cuVS index if the quantizer was
+ /// modified externally
+
+ FAISS_ASSERT(cuvs_index);
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ /// Remove rows containing NaNs
+ idx_t n_rows_valid = inplaceGatherFilteredRows(resources_, vecs, indices);
+
+ cuvs::neighbors::ivf_pq::extend(
+ raft_handle,
+ raft::make_device_matrix_view<const float, idx_t>(
+ vecs.data(), n_rows_valid, dim_),
+ raft::make_device_vector_view<const idx_t, idx_t>(
+ indices.data(), n_rows_valid),
+ cuvs_index.get());
+
+ return n_rows_valid;
+}
+
+void CuvsIVFPQ::copyInvertedListsFrom(const InvertedLists* ivf) {
+ size_t nlist = ivf ? ivf->nlist : 0;
+ size_t ntotal = ivf ? ivf->compute_ntotal() : 0;
+
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ std::vector<uint32_t> list_sizes_(nlist);
+ std::vector<idx_t> indices_(ntotal);
+
+ // the index must already exist
+ FAISS_ASSERT(cuvs_index);
+
+ auto& cuvs_index_lists = cuvs_index->lists();
+
+ // conservative memory alloc for cloning cpu inverted lists
+ cuvs::neighbors::ivf_pq::list_spec<uint32_t, idx_t> ivf_list_spec{
+ static_cast<uint32_t>(bitsPerSubQuantizer_),
+ static_cast<uint32_t>(numSubQuantizers_),
+ true};
+
+ for (size_t i = 0; i < nlist; ++i) {
+ size_t listSize = ivf->list_size(i);
+
+ // GPU index can only support max int entries per list
+ FAISS_THROW_IF_NOT_FMT(
+ listSize <= (size_t)std::numeric_limits<int>::max(),
+ "GPU inverted list can only support "
+ "%zu entries; %zu found",
+ (size_t)std::numeric_limits<int>::max(),
+ listSize);
+
+ // store the list size
+ list_sizes_[i] = static_cast<uint32_t>(listSize);
+
+ // This cuVS list must currently be empty
+ FAISS_ASSERT(getListLength(i) == 0);
+
+ cuvs::neighbors::ivf::resize_list(
+ raft_handle,
+ cuvs_index_lists[i],
+ ivf_list_spec,
+ static_cast<uint32_t>(listSize),
+ static_cast<uint32_t>(0));
+ }
+
+ raft::update_device(
+ cuvs_index->list_sizes().data_handle(),
+ list_sizes_.data(),
+ nlist,
+ raft_handle.get_stream());
+
+ // Update the pointers and the sizes
+ cuvs::neighbors::ivf_pq::helpers::recompute_internal_state(
+ raft_handle, cuvs_index.get());
+
+ for (size_t i = 0; i < nlist; ++i) {
+ size_t listSize = ivf->list_size(i);
+ addEncodedVectorsToList_(
+ i, ivf->get_codes(i), ivf->get_ids(i), listSize);
+ }
+}
+
+void CuvsIVFPQ::setCuvsIndex(cuvs::neighbors::ivf_pq::index<idx_t>&& idx) {
+ cuvs_index = std::make_shared<cuvs::neighbors::ivf_pq::index<idx_t>>(
+ std::move(idx));
+ setBasePQCentroids_();
+}
+
+void CuvsIVFPQ::addEncodedVectorsToList_(
+ idx_t listId,
+ const void* codes,
+ const idx_t* indices,
+ idx_t numVecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+ const raft::device_resources& raft_handle =
+ resources_->getRaftHandleCurrentDevice();
+
+ // If there's nothing to add, then there's nothing we have to do
+ if (numVecs == 0) {
+ return;
+ }
+
+ // The GPU might have a different layout of the memory
+ auto gpuListSizeInBytes = getGpuListEncodingSize_(listId);
+
+ // We only have int32 length representations on the GPU per each
+ // list; the length is in sizeof(char)
+ FAISS_ASSERT(gpuListSizeInBytes <= (size_t)std::numeric_limits<int>::max());
+
+ idx_t maxBatchSize = 4096;
+ for (idx_t offset_b = 0; offset_b < numVecs; offset_b += maxBatchSize) {
+ uint32_t batchSize = min(maxBatchSize, numVecs - offset_b);
+ uint32_t bufferSize = getCpuVectorsEncodingSize_(batchSize);
+ uint32_t codesOffset = getCpuVectorsEncodingSize_(offset_b);
+
+ // Translate the codes as needed to our preferred form
+ auto codes_d = raft::make_device_vector<uint8_t>(
+ raft_handle, static_cast<uint32_t>(bufferSize));
+ raft::update_device(
+ codes_d.data_handle(),
+ static_cast<const uint8_t*>(codes) + codesOffset,
+ bufferSize,
+ stream);
+
+ cuvs::neighbors::ivf_pq::helpers::codepacker::pack_contiguous_list_data(
+ raft_handle,
+ cuvs_index.get(),
+ codes_d.data_handle(),
+ batchSize,
+ listId,
+ offset_b);
+ }
+
+ /// Handle the indices as well
+ idx_t* list_indices_ptr;
+
+ // fetch the list indices ptr on host
+ raft::update_host(
+ &list_indices_ptr,
+ cuvs_index->inds_ptrs().data_handle() + listId,
+ 1,
+ stream);
+ raft_handle.sync_stream();
+
+ raft::update_device(list_indices_ptr, indices, numVecs, stream);
+}
+
+void CuvsIVFPQ::setPQCentroids_() {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ raft::copy(
+ cuvs_index->pq_centers().data_handle(),
+ pqCentroidsInnermostCode_.data(),
+ pqCentroidsInnermostCode_.numElements(),
+ stream);
+}
+
+void CuvsIVFPQ::setBasePQCentroids_() {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ raft::copy(
+ pqCentroidsInnermostCode_.data(),
+ cuvs_index->pq_centers().data_handle(),
+ cuvs_index->pq_centers().size(),
+ stream);
+
+ DeviceTensor<float, 3, true> pqCentroidsMiddleCode(
+ resources_,
+ makeDevAlloc(AllocType::Quantizer, stream),
+ {numSubQuantizers_, numSubQuantizerCodes_, dimPerSubQuantizer_});
+
+ runTransposeAny(
+ pqCentroidsInnermostCode_, 1, 2, pqCentroidsMiddleCode, stream);
+
+ pqCentroidsMiddleCode_ = std::move(pqCentroidsMiddleCode);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFPQ.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFPQ.cuh
new file mode 100644
index 0000000..e6a3e1e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/CuvsIVFPQ.cuh
@@ -0,0 +1,151 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/impl/IVFPQ.cuh>
+
+#include <cuvs/neighbors/ivf_pq.hpp>
+
+#include <memory>
+#include <optional>
+
+#pragma GCC visibility push(default)
+namespace faiss {
+namespace gpu {
+/// Implementing class for IVFPQ on the GPU
+class CuvsIVFPQ : public IVFPQ {
+ public:
+ CuvsIVFPQ(
+ GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ int numSubQuantizers,
+ int bitsPerSubQuantizer,
+ bool useFloat16LookupTables,
+ bool useMMCodeDistance,
+ bool interleavedLayout,
+ float* pqCentroidData,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ ~CuvsIVFPQ() override;
+
+ /// Reserve GPU memory in our inverted lists for this number of vectors
+ void reserveMemory(idx_t numVecs) override;
+
+ /// Clear out the cuVS index
+ void reset() override;
+
+ /// After adding vectors, one can call this to reclaim device memory
+ /// to exactly the amount needed. Returns space reclaimed in bytes
+ size_t reclaimMemory() override;
+
+ /// Enable or disable pre-computed codes. The quantizer is needed to gather
+ /// the IVF centroids for use
+ void setPrecomputedCodes(Index* coarseQuantizer, bool enable) override;
+
+ /// Find the approximate k nearest neigbors for `queries` against
+ /// our database
+ void search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) override;
+
+ /// Performs search when we are already given the IVF cells to look at
+ /// (GpuIndexIVF::search_preassigned implementation)
+ void searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) override;
+
+ /// Return the encoded vectors of a particular list back to the CPU
+ std::vector<uint8_t> getListVectorData(idx_t listId, bool gpuFormat)
+ const override;
+
+ /// Update our cuVS index with this quantizer instance; may be a CPU
+ /// or GPU quantizer
+ void updateQuantizer(Index* quantizer) override;
+
+ /// Copy all inverted lists from a CPU representation to ourselves
+ void copyInvertedListsFrom(const InvertedLists* ivf) override;
+
+ /// Replace the cuVS index
+ void setCuvsIndex(cuvs::neighbors::ivf_pq::index<idx_t>&& idx);
+
+ /// Classify and encode/add vectors to our IVF lists.
+ /// The input data must be on our current device.
+ /// Returns the number of vectors successfully added. Vectors may
+ /// not be able to be added because they contain NaNs.
+ idx_t addVectors(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices) override;
+
+ /// For debugging purposes, return the list length of a particular
+ /// list
+ idx_t getListLength(idx_t listId) const override;
+
+ /// Return the list indices of a particular list back to the CPU
+ std::vector<idx_t> getListIndices(idx_t listId) const override;
+
+ private:
+ /// Adds a set of codes and indices to a list, with the representation
+ /// coming from the CPU equivalent
+ void addEncodedVectorsToList_(
+ idx_t listId,
+ // resident on the host
+ const void* codes,
+ // resident on the host
+ const idx_t* indices,
+ idx_t numVecs) override;
+
+ /// Returns the encoding size for a PQ-encoded IVF list
+ size_t getGpuListEncodingSize_(idx_t listId);
+
+ /// Copy the PQ centroids to the cuVS index. The data is already in the
+ /// preferred format with the transpose performed by the IVFPQ class helper.
+ void setPQCentroids_();
+
+ /// Update the product quantizer centroids buffer held in the IVFPQ class.
+ /// Used when the cuVS index was updated externally.
+ void setBasePQCentroids_();
+
+ /// cuVS IVF-PQ index
+ std::shared_ptr<cuvs::neighbors::ivf_pq::index<idx_t>> cuvs_index{nullptr};
+};
+
+} // namespace gpu
+} // namespace faiss
+#pragma GCC visibility pop
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/Distance.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/Distance.cu
new file mode 100644
index 0000000..9d943b1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/Distance.cu
@@ -0,0 +1,733 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/impl/BroadcastSum.cuh>
+#include <faiss/gpu/impl/Distance.cuh>
+#include <faiss/gpu/impl/DistanceUtils.cuh>
+#include <faiss/gpu/impl/L2Norm.cuh>
+#include <faiss/gpu/impl/L2Select.cuh>
+#include <faiss/gpu/utils/BlockSelectKernel.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/Limits.cuh>
+#include <faiss/gpu/utils/MatrixMult.cuh>
+
+#include <thrust/device_ptr.h>
+#include <thrust/execution_policy.h>
+#include <thrust/fill.h>
+#include <thrust/for_each.h>
+#include <algorithm>
+#include <memory>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+void runAllPairwiseDistance(
+ bool computeL2,
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<T, 2, true>& centroids,
+ bool centroidsRowMajor,
+ Tensor<float, 1, true>* centroidNorms,
+ Tensor<T, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ // The # of centroids in `centroids` based on memory layout
+ auto numCentroids = centroids.getSize(centroidsRowMajor ? 0 : 1);
+
+ // The # of queries in `queries` based on memory layout
+ auto numQueries = queries.getSize(queriesRowMajor ? 0 : 1);
+
+ // The dimensions of the vectors to consider
+ auto dim = queries.getSize(queriesRowMajor ? 1 : 0);
+ FAISS_ASSERT(
+ (numQueries == 0 || numCentroids == 0) ||
+ dim == centroids.getSize(centroidsRowMajor ? 1 : 0));
+
+ FAISS_ASSERT(outDistances.getSize(0) == numQueries);
+ FAISS_ASSERT(outDistances.getSize(1) == numCentroids);
+
+ // If we're querying against a 0 sized set, just return empty results
+ if (centroids.numElements() == 0) {
+ thrust::fill(
+ thrust::cuda::par.on(stream),
+ outDistances.data(),
+ outDistances.end(),
+ Limits<float>::getMax());
+
+ return;
+ }
+
+ // L2: If ||c||^2 is not pre-computed, calculate it
+ DeviceTensor<float, 1, true> cNorms;
+ if (computeL2 && !centroidNorms) {
+ cNorms = DeviceTensor<float, 1, true>(
+ res, makeTempAlloc(AllocType::Other, stream), {numCentroids});
+ runL2Norm(centroids, centroidsRowMajor, cNorms, true, stream);
+ centroidNorms = &cNorms;
+ }
+
+ //
+ // Prepare norm vector ||q||^2; ||c||^2 is already pre-computed
+ //
+ DeviceTensor<float, 1, true> queryNorms(
+ res, makeTempAlloc(AllocType::Other, stream), {numQueries});
+
+ // ||q||^2
+ if (computeL2) {
+ runL2Norm(queries, queriesRowMajor, queryNorms, true, stream);
+ }
+
+ // L2: distance is ||c||^2 - 2qc + ||q||^2, we compute -2qc
+ // IP: just compute qc
+ // (query id x dim) x (centroid id, dim)' = (query id, centroid id)
+ runMatrixMult(
+ outDistances,
+ false, // not transposed
+ queries,
+ !queriesRowMajor, // transposed MM if col major
+ centroids,
+ centroidsRowMajor, // transposed MM if row major
+ computeL2 ? -2.0f : 1.0f,
+ 0.0f,
+ res->getBlasHandleCurrentDevice(),
+ stream);
+
+ if (computeL2) {
+ // Need to add ||q||^2 along rows
+ // Need to add ||c||^2 along columns
+ // FIXME: optimize with a dedicated kernel
+ runSumAlongColumns(*centroidNorms, outDistances, stream);
+
+ runSumAlongRows(
+ queryNorms,
+ outDistances,
+ true, // L2 distances should not go below zero
+ // due to roundoff error
+ stream);
+ }
+}
+
+template <typename T>
+void runDistance(
+ bool computeL2,
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<T, 2, true>& centroids,
+ bool centroidsRowMajor,
+ Tensor<float, 1, true>* centroidNorms,
+ Tensor<T, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances) {
+ // The # of centroids in `centroids` based on memory layout
+ auto numCentroids = centroids.getSize(centroidsRowMajor ? 0 : 1);
+
+ // The # of queries in `queries` based on memory layout
+ auto numQueries = queries.getSize(queriesRowMajor ? 0 : 1);
+
+ // The dimensions of the vectors to consider
+ auto dim = queries.getSize(queriesRowMajor ? 1 : 0);
+ FAISS_ASSERT(
+ (numQueries == 0 || numCentroids == 0) ||
+ dim == centroids.getSize(centroidsRowMajor ? 1 : 0));
+
+ FAISS_ASSERT(outDistances.getSize(0) == numQueries);
+ FAISS_ASSERT(outIndices.getSize(0) == numQueries);
+ FAISS_ASSERT(outDistances.getSize(1) == k);
+ FAISS_ASSERT(outIndices.getSize(1) == k);
+
+ // If we're querying against a 0 sized set, just return empty results
+ if (centroids.numElements() == 0) {
+ thrust::fill(
+ thrust::cuda::par.on(stream),
+ outDistances.data(),
+ outDistances.end(),
+ Limits<float>::getMax());
+
+ thrust::fill(
+ thrust::cuda::par.on(stream),
+ outIndices.data(),
+ outIndices.end(),
+ -1);
+
+ return;
+ }
+
+ // L2: If ||c||^2 is not pre-computed, calculate it
+ DeviceTensor<float, 1, true> cNorms;
+ if (computeL2 && !centroidNorms) {
+ cNorms = DeviceTensor<float, 1, true>(
+ res, makeTempAlloc(AllocType::Other, stream), {numCentroids});
+ runL2Norm(centroids, centroidsRowMajor, cNorms, true, stream);
+ centroidNorms = &cNorms;
+ }
+
+ //
+ // Prepare norm vector ||q||^2; ||c||^2 is already pre-computed
+ //
+ DeviceTensor<float, 1, true> queryNorms(
+ res, makeTempAlloc(AllocType::Other, stream), {numQueries});
+
+ // ||q||^2
+ if (computeL2) {
+ runL2Norm(queries, queriesRowMajor, queryNorms, true, stream);
+ }
+
+ // By default, aim to use up to 512 MB of memory for the processing, with
+ // both number of queries and number of centroids being at least 512.
+ idx_t tileRows = 0;
+ idx_t tileCols = 0;
+ chooseTileSize(
+ numQueries,
+ numCentroids,
+ dim,
+ sizeof(T),
+ res->getTempMemoryAvailableCurrentDevice(),
+ tileRows,
+ tileCols);
+
+ idx_t numColTiles = utils::divUp(numCentroids, tileCols);
+
+ // We can have any number of vectors to query against, even less than k, in
+ // which case we'll return -1 for the index
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K); // select limitation
+
+ // Temporary output memory space we'll use
+ DeviceTensor<float, 2, true> distanceBuf1(
+ res, makeTempAlloc(AllocType::Other, stream), {tileRows, tileCols});
+ DeviceTensor<float, 2, true> distanceBuf2(
+ res, makeTempAlloc(AllocType::Other, stream), {tileRows, tileCols});
+ DeviceTensor<float, 2, true>* distanceBufs[2] = {
+ &distanceBuf1, &distanceBuf2};
+
+ DeviceTensor<float, 2, true> outDistanceBuf1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<float, 2, true> outDistanceBuf2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<float, 2, true>* outDistanceBufs[2] = {
+ &outDistanceBuf1, &outDistanceBuf2};
+
+ DeviceTensor<idx_t, 2, true> outIndexBuf1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<idx_t, 2, true> outIndexBuf2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<idx_t, 2, true>* outIndexBufs[2] = {
+ &outIndexBuf1, &outIndexBuf2};
+
+ auto streams = res->getAlternateStreamsCurrentDevice();
+ streamWait(streams, {stream});
+
+ int curStream = 0;
+ bool interrupt = false;
+
+ // Tile over the input queries
+ for (idx_t i = 0; i < numQueries; i += tileRows) {
+ if (interrupt || InterruptCallback::is_interrupted()) {
+ interrupt = true;
+ break;
+ }
+
+ idx_t curQuerySize = std::min(tileRows, numQueries - i);
+
+ auto outDistanceView = outDistances.narrow(0, i, curQuerySize);
+ auto outIndexView = outIndices.narrow(0, i, curQuerySize);
+
+ auto queryView =
+ queries.narrow(queriesRowMajor ? 0 : 1, i, curQuerySize);
+ auto queryNormNiew = queryNorms.narrow(0, i, curQuerySize);
+
+ auto outDistanceBufRowView =
+ outDistanceBufs[curStream]->narrow(0, 0, curQuerySize);
+ auto outIndexBufRowView =
+ outIndexBufs[curStream]->narrow(0, 0, curQuerySize);
+
+ // Tile over the centroids
+ for (idx_t j = 0; j < numCentroids; j += tileCols) {
+ if (InterruptCallback::is_interrupted()) {
+ interrupt = true;
+ break;
+ }
+
+ auto curCentroidSize = std::min(tileCols, numCentroids - j);
+ auto curColTile = j / tileCols;
+
+ auto centroidsView = sliceCentroids(
+ centroids, centroidsRowMajor, j, curCentroidSize);
+
+ auto distanceBufView = distanceBufs[curStream]
+ ->narrow(0, 0, curQuerySize)
+ .narrow(1, 0, curCentroidSize);
+
+ auto outDistanceBufColView =
+ outDistanceBufRowView.narrow(1, k * curColTile, k);
+ auto outIndexBufColView =
+ outIndexBufRowView.narrow(1, k * curColTile, k);
+
+ // L2: distance is ||c||^2 - 2qc + ||q||^2, we compute -2qc
+ // IP: just compute qc
+ // (query id x dim) x (centroid id, dim)' = (query id, centroid id)
+ runMatrixMult(
+ distanceBufView,
+ false, // not transposed
+ queryView,
+ !queriesRowMajor, // transposed MM if col major
+ centroidsView,
+ centroidsRowMajor, // transposed MM if row major
+ computeL2 ? -2.0f : 1.0f,
+ 0.0f,
+ res->getBlasHandleCurrentDevice(),
+ streams[curStream]);
+
+ if (computeL2) {
+ // For L2 distance, we use this fused kernel that performs both
+ // adding ||c||^2 to -2qc and k-selection, so we only need two
+ // passes (one write by the gemm, one read here) over the huge
+ // region of output memory
+ //
+ // If we aren't tiling along the number of centroids, we can
+ // perform the output work directly
+ if (tileCols == numCentroids) {
+ // Write into the final output
+ runL2SelectMin(
+ distanceBufView,
+ *centroidNorms,
+ outDistanceView,
+ outIndexView,
+ k,
+ streams[curStream]);
+
+ if (!ignoreOutDistances) {
+ // expand (query id) to (query id, k) by duplicating
+ // along rows top-k ||c||^2 - 2qc + ||q||^2 in the form
+ // (query id, k)
+ runSumAlongRows(
+ queryNormNiew,
+ outDistanceView,
+ true, // L2 distances should not go below zero
+ // due to roundoff error
+ streams[curStream]);
+ }
+ } else {
+ auto centroidNormsView =
+ centroidNorms->narrow(0, j, curCentroidSize);
+
+ // Write into our intermediate output
+ runL2SelectMin(
+ distanceBufView,
+ centroidNormsView,
+ outDistanceBufColView,
+ outIndexBufColView,
+ k,
+ streams[curStream]);
+
+ if (!ignoreOutDistances) {
+ // expand (query id) to (query id, k) by duplicating
+ // along rows top-k ||c||^2 - 2qc + ||q||^2 in the form
+ // (query id, k)
+ runSumAlongRows(
+ queryNormNiew,
+ outDistanceBufColView,
+ true, // L2 distances should not go below zero
+ // due to roundoff error
+ streams[curStream]);
+ }
+ }
+ } else {
+ // For IP, just k-select the output for this tile
+ if (tileCols == numCentroids) {
+ // Write into the final output
+ runBlockSelect(
+ distanceBufView,
+ outDistanceView,
+ outIndexView,
+ true,
+ k,
+ streams[curStream]);
+ } else {
+ // Write into the intermediate output
+ runBlockSelect(
+ distanceBufView,
+ outDistanceBufColView,
+ outIndexBufColView,
+ true,
+ k,
+ streams[curStream]);
+ }
+ }
+ }
+
+ // As we're finished with processing a full set of centroids, perform
+ // the final k-selection
+ if (tileCols != numCentroids) {
+ // The indices are tile-relative; for each tile of k, we need to add
+ // tileCols to the index
+ runIncrementIndex(
+ outIndexBufRowView, k, tileCols, streams[curStream]);
+
+ runBlockSelectPair(
+ outDistanceBufRowView,
+ outIndexBufRowView,
+ outDistanceView,
+ outIndexView,
+ computeL2 ? false : true,
+ k,
+ streams[curStream]);
+ }
+
+ curStream = (curStream + 1) % 2;
+ }
+
+ // Have the desired ordering stream wait on the multi-stream
+ streamWait({stream}, streams);
+
+ if (interrupt) {
+ FAISS_THROW_MSG("interrupted");
+ }
+}
+
+template <typename T>
+void runL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<T, 2, true>& centroids,
+ bool centroidsRowMajor,
+ Tensor<float, 1, true>* centroidNorms,
+ Tensor<T, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances = false) {
+ runDistance<T>(
+ true, // L2
+ res,
+ stream,
+ centroids,
+ centroidsRowMajor,
+ centroidNorms,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices,
+ ignoreOutDistances);
+}
+
+template <typename T>
+void runIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<T, 2, true>& centroids,
+ bool centroidsRowMajor,
+ Tensor<T, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ runDistance<T>(
+ false, // IP
+ res,
+ stream,
+ centroids,
+ centroidsRowMajor,
+ nullptr, // no centroid norms provided
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices,
+ false);
+}
+
+//
+// Instantiations of the distance templates
+//
+
+void runAllPairwiseL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ runAllPairwiseDistance<float>(
+ true,
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ outDistances);
+}
+
+void runAllPairwiseL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ runAllPairwiseDistance<half>(
+ true,
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ outDistances);
+}
+
+void runAllPairwiseL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ runAllPairwiseDistance<__nv_bfloat16>(
+ true,
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ outDistances);
+}
+
+void runAllPairwiseIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ runAllPairwiseDistance<float>(
+ false,
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ nullptr,
+ queries,
+ queriesRowMajor,
+ outDistances);
+}
+
+void runAllPairwiseIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ runAllPairwiseDistance<half>(
+ false,
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ nullptr,
+ queries,
+ queriesRowMajor,
+ outDistances);
+}
+
+void runAllPairwiseIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances) {
+ runAllPairwiseDistance<__nv_bfloat16>(
+ false,
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ nullptr,
+ queries,
+ queriesRowMajor,
+ outDistances);
+}
+
+void runL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances) {
+ runL2Distance<float>(
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices,
+ ignoreOutDistances);
+}
+
+void runL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances) {
+ runL2Distance<half>(
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices,
+ ignoreOutDistances);
+}
+
+void runL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances) {
+ runL2Distance<__nv_bfloat16>(
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices,
+ ignoreOutDistances);
+}
+
+void runIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ runIPDistance<float>(
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices);
+}
+
+void runIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ runIPDistance<half>(
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices);
+}
+
+void runIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ runIPDistance<__nv_bfloat16>(
+ res,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/Distance.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/Distance.cuh
new file mode 100644
index 0000000..07f2f02
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/Distance.cuh
@@ -0,0 +1,445 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/impl/GeneralDistance.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+/// Calculates brute-force L2 distance between `vectors` and `queries`, not
+/// performing top-k filtering.
+/// FIXME: the output distances must fit in GPU memory
+void runAllPairwiseL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ // can be optionally pre-computed; nullptr if we
+ // have to compute it upon the call
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances);
+
+void runAllPairwiseL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances);
+
+void runAllPairwiseL2Distance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances);
+
+void runAllPairwiseIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances);
+
+void runAllPairwiseIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances);
+
+void runAllPairwiseIPDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ Tensor<float, 2, true>& outDistances);
+
+/// Calculates brute-force L2 distance between `vectors` and
+/// `queries`, returning the k closest results seen
+void runL2Distance(
+ GpuResources* resources,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ // can be optionally pre-computed; nullptr if we
+ // have to compute it upon the call
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ // Do we care about `outDistances`? If not, we can
+ // take shortcuts.
+ bool ignoreOutDistances = false);
+
+void runL2Distance(
+ GpuResources* resources,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances = false);
+
+void runL2Distance(
+ GpuResources* resources,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances = false);
+
+/// Calculates brute-force inner product distance between `vectors`
+/// and `queries`, returning the k closest results seen
+void runIPDistance(
+ GpuResources* resources,
+ cudaStream_t stream,
+ Tensor<float, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices);
+
+void runIPDistance(
+ GpuResources* resources,
+ cudaStream_t stream,
+ Tensor<half, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<half, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices);
+
+void runIPDistance(
+ GpuResources* resources,
+ cudaStream_t stream,
+ Tensor<__nv_bfloat16, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<__nv_bfloat16, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices);
+
+//
+// General distance implementation, assumes that all arguments are on the
+// device. This is the top-level internal distance function to call to dispatch
+// based on metric type.
+//
+template <typename T>
+void allPairwiseDistanceOnDevice(
+ GpuResources* resources,
+ int device,
+ cudaStream_t stream,
+ Tensor<T, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<T, 2, true>& queries,
+ bool queriesRowMajor,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances) {
+ DeviceScope ds(device);
+ // We are guaranteed that all data arguments are resident on our preferred
+ // `device` here
+
+ // L2 and IP are specialized to use GEMM and an optimized L2 + selection or
+ // pure k-selection kernel.
+ if ((metric == faiss::MetricType::METRIC_L2) ||
+ (metric == faiss::MetricType::METRIC_Lp && metricArg == 2)) {
+ runAllPairwiseL2Distance(
+ resources,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ outDistances);
+ } else if (metric == faiss::MetricType::METRIC_INNER_PRODUCT) {
+ runAllPairwiseIPDistance(
+ resources,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ queries,
+ queriesRowMajor,
+ outDistances);
+ } else {
+ //
+ // General pairwise distance kernel
+ //
+ // The general distance kernel does not have specializations for
+ // transpositions (NN, NT, TN); instead, the transposition is just
+ // handled upon data load for now, which could result in poor data
+ // loading behavior for NT / TN. This can be fixed at a later date if
+ // desired, but efficiency is low versus GEMM anyways.
+ //
+
+ Tensor<T, 2> tVectorsDimInnermost = vectorsRowMajor
+ ? vectors.transposeInnermost(1)
+ : vectors.transposeInnermost(0);
+ Tensor<T, 2> tQueriesDimInnermost = queriesRowMajor
+ ? queries.transposeInnermost(1)
+ : queries.transposeInnermost(0);
+
+ if ((metric == faiss::MetricType::METRIC_L1) ||
+ (metric == faiss::MetricType::METRIC_Lp && metricArg == 1)) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ L1Distance(),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_Lp && metricArg == -1) {
+ // A way to test L2 distance
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ L2Distance(),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_Lp) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ LpDistance(metricArg),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_Linf) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ LinfDistance(),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_Canberra) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ CanberraDistance(),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_BrayCurtis) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ BrayCurtisDistance(),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_JensenShannon) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ JensenShannonDistance(),
+ stream);
+ } else if (metric == faiss::MetricType::METRIC_Jaccard) {
+ runGeneralDistanceKernel(
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ outDistances,
+ JaccardSimilarity(),
+ stream);
+ } else {
+ FAISS_THROW_FMT("unimplemented metric type %d", metric);
+ }
+ }
+}
+
+//
+// General distance implementation, assumes that all arguments are on the
+// device. This is the top-level internal distance function to call to dispatch
+// based on metric type.
+//
+template <typename T>
+void bfKnnOnDevice(
+ GpuResources* resources,
+ int device,
+ cudaStream_t stream,
+ Tensor<T, 2, true>& vectors,
+ bool vectorsRowMajor,
+ Tensor<float, 1, true>* vectorNorms,
+ Tensor<T, 2, true>& queries,
+ bool queriesRowMajor,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool ignoreOutDistances) {
+ DeviceScope ds(device);
+ // We are guaranteed that all data arguments are resident on our preferred
+ // `device` here
+
+ // L2 and IP are specialized to use GEMM and an optimized L2 + selection or
+ // pure k-selection kernel.
+ if ((metric == faiss::MetricType::METRIC_L2) ||
+ (metric == faiss::MetricType::METRIC_Lp && metricArg == 2)) {
+ runL2Distance(
+ resources,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ vectorNorms,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_INNER_PRODUCT) {
+ runIPDistance(
+ resources,
+ stream,
+ vectors,
+ vectorsRowMajor,
+ queries,
+ queriesRowMajor,
+ k,
+ outDistances,
+ outIndices);
+ } else {
+ //
+ // General pairwise distance kernel
+ //
+ // The general distance kernel does not have specializations for
+ // transpositions (NN, NT, TN); instead, the transposition is just
+ // handled upon data load for now, which could result in poor data
+ // loading behavior for NT / TN. This can be fixed at a later date if
+ // desired, but efficiency is low versus GEMM anyways.
+ //
+
+ Tensor<T, 2> tVectorsDimInnermost = vectorsRowMajor
+ ? vectors.transposeInnermost(1)
+ : vectors.transposeInnermost(0);
+ Tensor<T, 2> tQueriesDimInnermost = queriesRowMajor
+ ? queries.transposeInnermost(1)
+ : queries.transposeInnermost(0);
+
+ if ((metric == faiss::MetricType::METRIC_L1) ||
+ (metric == faiss::MetricType::METRIC_Lp && metricArg == 1)) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ L1Distance(),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_Lp && metricArg == -1) {
+ // A way to test L2 distance
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ L2Distance(),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_Lp) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ LpDistance(metricArg),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_Linf) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ LinfDistance(),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_Canberra) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ CanberraDistance(),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_BrayCurtis) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ BrayCurtisDistance(),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_JensenShannon) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ JensenShannonDistance(),
+ outDistances,
+ outIndices);
+ } else if (metric == faiss::MetricType::METRIC_Jaccard) {
+ runGeneralDistance(
+ resources,
+ stream,
+ tVectorsDimInnermost,
+ tQueriesDimInnermost,
+ k,
+ JaccardSimilarity(),
+ outDistances,
+ outIndices);
+ } else {
+ FAISS_THROW_FMT("unimplemented metric type %d", metric);
+ }
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/DistanceUtils.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/DistanceUtils.cuh
new file mode 100644
index 0000000..4ea899c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/DistanceUtils.cuh
@@ -0,0 +1,377 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+
+#include <faiss/gpu/utils/Tensor.cuh>
+
+//
+// Shared utilities for brute-force distance calculations
+//
+
+namespace faiss {
+namespace gpu {
+
+struct IPDistance {
+ __host__ __device__ IPDistance() : dist(0) {}
+
+ static constexpr bool kDirection = true; // maximize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = -std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ dist += a * b;
+ }
+
+ __host__ __device__ float reduce() {
+ return dist;
+ }
+
+ __host__ __device__ void combine(const IPDistance& v) {
+ dist += v.dist;
+ }
+
+ __host__ __device__ IPDistance zero() const {
+ return IPDistance();
+ }
+
+ float dist;
+};
+
+struct L1Distance {
+ __host__ __device__ L1Distance() : dist(0) {}
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ dist += fabsf(a - b);
+ }
+
+ __host__ __device__ float reduce() {
+ return dist;
+ }
+
+ __host__ __device__ void combine(const L1Distance& v) {
+ dist += v.dist;
+ }
+
+ __host__ __device__ L1Distance zero() const {
+ return L1Distance();
+ }
+
+ float dist;
+};
+
+struct L2Distance {
+ __host__ __device__ L2Distance() : dist(0) {}
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ float v = a - b;
+ dist += v * v;
+ }
+
+ __host__ __device__ float reduce() {
+ return dist;
+ }
+
+ __host__ __device__ void combine(const L2Distance& v) {
+ dist += v.dist;
+ }
+
+ __host__ __device__ L2Distance zero() const {
+ return L2Distance();
+ }
+
+ float dist;
+};
+
+struct LpDistance {
+ __host__ __device__ LpDistance() : p(2), dist(0) {}
+
+ __host__ __device__ LpDistance(float arg) : p(arg), dist(0) {}
+
+ __host__ __device__ LpDistance(const LpDistance& v)
+ : p(v.p), dist(v.dist) {}
+
+ __host__ __device__ LpDistance& operator=(const LpDistance& v) {
+ p = v.p;
+ dist = v.dist;
+ return *this;
+ }
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ dist += powf(fabsf(a - b), p);
+ }
+
+ __host__ __device__ float reduce() {
+ return dist;
+ }
+
+ __host__ __device__ void combine(const LpDistance& v) {
+ dist += v.dist;
+ }
+
+ __host__ __device__ LpDistance zero() const {
+ return LpDistance(p);
+ }
+
+ float p;
+ float dist;
+};
+
+struct LinfDistance {
+ __host__ __device__ LinfDistance() : dist(0) {}
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ dist = fmaxf(dist, fabsf(a - b));
+ }
+
+ __host__ __device__ float reduce() {
+ return dist;
+ }
+
+ __host__ __device__ void combine(const LinfDistance& v) {
+ dist = fmaxf(dist, v.dist);
+ }
+
+ __host__ __device__ LinfDistance zero() const {
+ return LinfDistance();
+ }
+
+ float dist;
+};
+
+struct CanberraDistance {
+ __host__ __device__ CanberraDistance() : dist(0) {}
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ float denom = fabsf(a) + fabsf(b);
+ dist += fabsf(a - b) / denom;
+ }
+
+ __host__ __device__ float reduce() {
+ return dist;
+ }
+
+ __host__ __device__ void combine(const CanberraDistance& v) {
+ dist += v.dist;
+ }
+
+ __host__ __device__ CanberraDistance zero() const {
+ return CanberraDistance();
+ }
+
+ float dist;
+};
+
+struct BrayCurtisDistance {
+ __host__ __device__ BrayCurtisDistance() : numerator(0), denominator(0) {}
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ numerator += fabsf(a - b);
+ denominator += fabsf(a + b);
+ }
+
+ __host__ __device__ float reduce() {
+ return (numerator / denominator);
+ }
+
+ __host__ __device__ void combine(const BrayCurtisDistance& v) {
+ numerator += v.numerator;
+ denominator += v.denominator;
+ }
+
+ __host__ __device__ BrayCurtisDistance zero() const {
+ return BrayCurtisDistance();
+ }
+
+ float numerator;
+ float denominator;
+};
+
+struct JensenShannonDistance {
+ __host__ __device__ JensenShannonDistance() : dist(0) {}
+
+ static constexpr bool kDirection = false; // minimize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ float m = 0.5f * (a + b);
+
+ float x = m / a;
+ float y = m / b;
+
+ float kl1 = -a * log(x);
+ float kl2 = -b * log(y);
+
+ dist += kl1 + kl2;
+ }
+
+ __host__ __device__ float reduce() {
+ return 0.5 * dist;
+ }
+
+ __host__ __device__ void combine(const JensenShannonDistance& v) {
+ dist += v.dist;
+ }
+
+ __host__ __device__ JensenShannonDistance zero() const {
+ return JensenShannonDistance();
+ }
+
+ float dist;
+};
+
+struct JaccardSimilarity {
+ __host__ __device__ JaccardSimilarity() : numerator(0), denominator(0) {}
+
+ static constexpr bool kDirection = true; // maximize
+ static constexpr float kIdentityData = 0;
+ static constexpr float kMaxDistance = -std::numeric_limits<float>::max();
+
+ __host__ __device__ void handle(float a, float b) {
+ numerator += fmin(a, b);
+ denominator += fmax(a, b);
+ }
+
+ __host__ __device__ float reduce() {
+ return numerator / denominator;
+ }
+
+ __host__ __device__ void combine(const JaccardSimilarity& v) {
+ numerator += v.numerator;
+ denominator += v.denominator;
+ }
+
+ __host__ __device__ JaccardSimilarity zero() const {
+ return JaccardSimilarity();
+ }
+
+ float numerator;
+ float denominator;
+};
+
+template <typename T, bool InnerContig>
+Tensor<T, 2, InnerContig> sliceCentroids(
+ Tensor<T, 2, InnerContig>& centroids,
+ bool centroidsRowMajor,
+ idx_t startCentroid,
+ idx_t num) {
+ // Row major is (num, dim)
+ // Col major is (dim, num)
+ if (startCentroid == 0 &&
+ num == centroids.getSize(centroidsRowMajor ? 0 : 1)) {
+ return centroids;
+ }
+
+ return centroids.narrow(centroidsRowMajor ? 0 : 1, startCentroid, num);
+}
+
+// For each chunk of k indices, increment the index by chunk * increment
+template <typename T>
+__global__ void incrementIndex(
+ Tensor<T, 2, true> indices,
+ int k,
+ idx_t increment) {
+ for (idx_t i = blockIdx.y; i < indices.getSize(0); i += gridDim.y) {
+ for (auto j = threadIdx.x; j < k; j += blockDim.x) {
+ indices[i][idx_t(blockIdx.x) * k + j] += blockIdx.x * increment;
+ }
+ }
+}
+
+// Used to update result indices in distance computation where the number of
+// centroids is high, and is tiled
+template <typename T>
+void runIncrementIndex(
+ Tensor<T, 2, true>& indices,
+ int k,
+ idx_t increment,
+ cudaStream_t stream) {
+ // Input should be an even divisor of k
+ FAISS_ASSERT(indices.getSize(1) % k == 0);
+
+ dim3 grid(indices.getSize(1) / k, indices.getSize(0));
+ auto block = std::min(k, getMaxThreadsCurrentDevice());
+
+ incrementIndex<<<grid, block, 0, stream>>>(indices, k, increment);
+ CUDA_TEST_ERROR();
+}
+
+// If the inner size (dim) of the vectors is small, we want a larger query tile
+// size, like 1024
+inline void chooseTileSize(
+ idx_t numQueries,
+ idx_t numCentroids,
+ int dim,
+ idx_t elementSize,
+ size_t tempMemAvailable,
+ idx_t& tileRows,
+ idx_t& tileCols) {
+ // The matrix multiplication should be large enough to be efficient, but if
+ // it is too large, we seem to lose efficiency as opposed to
+ // double-streaming. Each tile size here defines 1/2 of the memory use due
+ // to double streaming. We ignore available temporary memory, as that is
+ // adjusted independently by the user and can thus meet these requirements
+ // (or not). For <= 4 GB GPUs, prefer 512 MB of usage. For <= 8 GB GPUs,
+ // prefer 768 MB of usage. Otherwise, prefer 1 GB of usage.
+ auto totalMem = getCurrentDeviceProperties().totalGlobalMem;
+
+ idx_t targetUsage = 0;
+
+ if (totalMem <= ((size_t)4) * 1024 * 1024 * 1024) {
+ targetUsage = 512 * 1024 * 1024;
+ } else if (totalMem <= ((size_t)8) * 1024 * 1024 * 1024) {
+ targetUsage = 768 * 1024 * 1024;
+ } else {
+ targetUsage = 1024 * 1024 * 1024;
+ }
+
+ targetUsage /= 2 * elementSize;
+
+ // 512 seems to be a batch size sweetspot for float32.
+ // If we are on float16, increase to 512.
+ // If the k size (vec dim) of the matrix multiplication is small (<= 32),
+ // increase to 1024.
+ idx_t preferredTileRows = 512;
+ if (dim <= 32) {
+ preferredTileRows = 1024;
+ }
+
+ tileRows = std::min(preferredTileRows, numQueries);
+
+ // tileCols is the remainder size
+ tileCols = std::min(targetUsage / preferredTileRows, numCentroids);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/FlatIndex.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/FlatIndex.cu
new file mode 100644
index 0000000..0f22737
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/FlatIndex.cu
@@ -0,0 +1,305 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/impl/Distance.cuh>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/impl/L2Norm.cuh>
+#include <faiss/gpu/impl/VectorResidual.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+
+namespace faiss {
+namespace gpu {
+
+FlatIndex::FlatIndex(
+ GpuResources* res,
+ int dim,
+ bool useFloat16,
+ MemorySpace space)
+ : resources_(res),
+ dim_(dim),
+ useFloat16_(useFloat16),
+ space_(space),
+ num_(0),
+ rawData32_(
+ res,
+ AllocInfo(
+ AllocType::FlatData,
+ getCurrentDevice(),
+ space,
+ res->getDefaultStreamCurrentDevice())),
+ rawData16_(
+ res,
+ AllocInfo(
+ AllocType::FlatData,
+ getCurrentDevice(),
+ space,
+ res->getDefaultStreamCurrentDevice())) {}
+
+bool FlatIndex::getUseFloat16() const {
+ return useFloat16_;
+}
+
+/// Returns the number of vectors we contain
+idx_t FlatIndex::getSize() const {
+ if (useFloat16_) {
+ return vectorsHalf_.getSize(0);
+ } else {
+ return vectors_.getSize(0);
+ }
+}
+
+int FlatIndex::getDim() const {
+ return dim_;
+}
+
+void FlatIndex::reserve(size_t numVecs, cudaStream_t stream) {
+ if (useFloat16_) {
+ rawData16_.reserve(numVecs * dim_ * sizeof(half), stream);
+ } else {
+ rawData32_.reserve(numVecs * dim_ * sizeof(float), stream);
+ }
+
+ // The above may have caused a reallocation, we need to update the vector
+ // types
+ if (useFloat16_) {
+ DeviceTensor<half, 2, true> vectors16(
+ (half*)rawData16_.data(), {num_, dim_});
+ vectorsHalf_ = std::move(vectors16);
+ } else {
+ DeviceTensor<float, 2, true> vectors32(
+ (float*)rawData32_.data(), {num_, dim_});
+ vectors_ = std::move(vectors32);
+ }
+}
+
+Tensor<float, 2, true>& FlatIndex::getVectorsFloat32Ref() {
+ // Should not call this unless we are in float32 mode
+ FAISS_ASSERT(!useFloat16_);
+
+ return vectors_;
+}
+
+Tensor<half, 2, true>& FlatIndex::getVectorsFloat16Ref() {
+ // Should not call this unless we are in float16 mode
+ FAISS_ASSERT(useFloat16_);
+
+ return vectorsHalf_;
+}
+
+void FlatIndex::query(
+ Tensor<float, 2, true>& input,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ if (useFloat16_) {
+ // We need to convert the input to float16 for comparison to ourselves
+ auto inputHalf = convertTensorTemporary<float, half, 2>(
+ resources_, stream, input);
+
+ query(inputHalf,
+ k,
+ metric,
+ metricArg,
+ outDistances,
+ outIndices,
+ exactDistance);
+ } else {
+ bfKnnOnDevice(
+ resources_,
+ getCurrentDevice(),
+ stream,
+ vectors_,
+ true, // is vectors row major?
+ &norms_,
+ input,
+ true, // input is row major
+ k,
+ metric,
+ metricArg,
+ outDistances,
+ outIndices,
+ !exactDistance);
+ }
+}
+
+void FlatIndex::query(
+ Tensor<half, 2, true>& input,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance) {
+ FAISS_ASSERT(useFloat16_);
+
+ bfKnnOnDevice(
+ resources_,
+ getCurrentDevice(),
+ resources_->getDefaultStreamCurrentDevice(),
+ vectorsHalf_,
+ true, // is vectors row major?
+ &norms_,
+ input,
+ true, // input is row major
+ k,
+ metric,
+ metricArg,
+ outDistances,
+ outIndices,
+ !exactDistance);
+}
+
+void FlatIndex::computeResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& ids,
+ Tensor<float, 2, true>& residuals) {
+ if (useFloat16_) {
+ runCalcResidual(
+ vecs,
+ getVectorsFloat16Ref(),
+ ids,
+ residuals,
+ resources_->getDefaultStreamCurrentDevice());
+ } else {
+ runCalcResidual(
+ vecs,
+ getVectorsFloat32Ref(),
+ ids,
+ residuals,
+ resources_->getDefaultStreamCurrentDevice());
+ }
+}
+
+void FlatIndex::reconstruct(
+ idx_t start,
+ idx_t num,
+ Tensor<float, 2, true>& vecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ FAISS_ASSERT(vecs.getSize(0) == num);
+ FAISS_ASSERT(vecs.getSize(1) == dim_);
+
+ if (useFloat16_) {
+ runReconstruct(start, num, getVectorsFloat16Ref(), vecs, stream);
+ } else {
+ runReconstruct(start, num, getVectorsFloat32Ref(), vecs, stream);
+ }
+}
+
+void FlatIndex::reconstruct(
+ Tensor<idx_t, 1, true>& ids,
+ Tensor<float, 2, true>& vecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ FAISS_ASSERT(vecs.getSize(0) == ids.getSize(0));
+ FAISS_ASSERT(vecs.getSize(1) == dim_);
+
+ if (useFloat16_) {
+ runReconstruct(ids, getVectorsFloat16Ref(), vecs, stream);
+ } else {
+ runReconstruct(ids, getVectorsFloat32Ref(), vecs, stream);
+ }
+}
+
+void FlatIndex::add(const float* data, idx_t numVecs, cudaStream_t stream) {
+ if (numVecs == 0) {
+ return;
+ }
+
+ // convert and add to float16 data if needed
+ if (useFloat16_) {
+ // Make sure that `data` is on our device; we'll run the
+ // conversion on our device
+ auto devData = toDeviceTemporary<float, 2>(
+ resources_,
+ getCurrentDevice(),
+ (float*)data,
+ stream,
+ {numVecs, dim_});
+
+ auto devDataHalf = convertTensorTemporary<float, half, 2>(
+ resources_, stream, devData);
+
+ rawData16_.append(
+ (char*)devDataHalf.data(),
+ devDataHalf.getSizeInBytes(),
+ stream,
+ true /* reserve exactly */);
+ } else {
+ // add to float32 data
+ rawData32_.append(
+ (char*)data,
+ (size_t)dim_ * numVecs * sizeof(float),
+ stream,
+ true /* reserve exactly */);
+ }
+
+ num_ += numVecs;
+
+ if (useFloat16_) {
+ DeviceTensor<half, 2, true> vectors16(
+ (half*)rawData16_.data(), {num_, dim_});
+ vectorsHalf_ = std::move(vectors16);
+ } else {
+ DeviceTensor<float, 2, true> vectors32(
+ (float*)rawData32_.data(), {num_, dim_});
+ vectors_ = std::move(vectors32);
+ }
+
+ // Precompute L2 norms of our database
+ if (useFloat16_) {
+ DeviceTensor<float, 1, true> norms(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {num_});
+ runL2Norm(vectorsHalf_, true, norms, true, stream);
+ norms_ = std::move(norms);
+ } else {
+ DeviceTensor<float, 1, true> norms(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {num_});
+ runL2Norm(vectors_, true, norms, true, stream);
+ norms_ = std::move(norms);
+ }
+}
+
+void FlatIndex::reset() {
+ rawData32_.clear();
+ rawData16_.clear();
+ vectors_ = DeviceTensor<float, 2, true>();
+ vectorsHalf_ = DeviceTensor<half, 2, true>();
+ norms_ = DeviceTensor<float, 1, true>();
+ num_ = 0;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/FlatIndex.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/FlatIndex.cuh
new file mode 100644
index 0000000..7b92976
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/FlatIndex.cuh
@@ -0,0 +1,133 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+/// Holder of GPU resources for a particular flat index
+/// Can be in either float16 or float32 mode. If float32, we only store
+/// the vectors in float32.
+/// If float16, we store the vectors in both float16 and float32, where float32
+/// data is possibly needed for certain residual operations
+class FlatIndex {
+ public:
+ FlatIndex(GpuResources* res, int dim, bool useFloat16, MemorySpace space);
+
+ /// Whether or not this flat index primarily stores data in float16
+ bool getUseFloat16() const;
+
+ /// Returns the number of vectors we contain
+ idx_t getSize() const;
+
+ /// Returns the dimensionality of the vectors
+ int getDim() const;
+
+ /// Reserve storage that can contain at least this many vectors
+ void reserve(size_t numVecs, cudaStream_t stream);
+
+ /// Returns a reference to our vectors currently in use
+ Tensor<float, 2, true>& getVectorsFloat32Ref();
+
+ /// Returns a reference to our vectors currently in use (if useFloat16 mode)
+ Tensor<half, 2, true>& getVectorsFloat16Ref();
+
+ virtual void query(
+ Tensor<float, 2, true>& vecs,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance);
+
+ virtual void query(
+ Tensor<half, 2, true>& vecs,
+ int k,
+ faiss::MetricType metric,
+ float metricArg,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool exactDistance);
+
+ /// Compute residual for set of vectors
+ void computeResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& ids,
+ Tensor<float, 2, true>& residuals);
+
+ /// Gather vectors given the set of IDs
+ void reconstruct(Tensor<idx_t, 1, true>& ids, Tensor<float, 2, true>& vecs);
+
+ /// Gather vectors given a range of IDs
+ void reconstruct(idx_t start, idx_t num, Tensor<float, 2, true>& vecs);
+
+ /// Add vectors to ourselves; the pointer passed can be on the host
+ /// or the device
+ void add(const float* data, idx_t numVecs, cudaStream_t stream);
+
+ /// Free all storage
+ void reset();
+
+ protected:
+ /// Collection of GPU resources that we use
+ GpuResources* resources_;
+
+ /// Dimensionality of our vectors
+ const int dim_;
+
+ /// Float16 data format
+ const bool useFloat16_;
+
+ /// Memory space for our allocations
+ MemorySpace space_;
+
+ /// How many vectors we have
+ idx_t num_;
+
+ /// The underlying expandable storage for float32 data
+ DeviceVector<char> rawData32_;
+
+ /// The underlying expandable storage for float16 data
+ DeviceVector<char> rawData16_;
+
+ /// Vectors currently in rawData32_
+ DeviceTensor<float, 2, true> vectors_;
+
+ /// Vectors currently in rawData16_, float16 form
+ DeviceTensor<half, 2, true> vectorsHalf_;
+
+ /// Precomputed L2 norms
+ DeviceTensor<float, 1, true> norms_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/GeneralDistance.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/GeneralDistance.cuh
new file mode 100644
index 0000000..208d3a8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/GeneralDistance.cuh
@@ -0,0 +1,460 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/MetricType.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/gpu/impl/DistanceUtils.cuh>
+#include <faiss/gpu/utils/BlockSelectKernel.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Select.cuh>
+
+#include <thrust/device_ptr.h>
+#include <thrust/execution_policy.h>
+#include <thrust/fill.h>
+#include <thrust/for_each.h>
+#include <algorithm>
+#include <iostream>
+#include <memory>
+
+//
+// Kernels for non-L2 / inner product distances
+//
+
+namespace faiss {
+namespace gpu {
+
+// Initially kWarpSize was used for the x and y tile shape.
+// This works when kWarpSize is 32 but for kWarpSize 64,
+// this results in an invalid launch configuration of 64x64 block size.
+// 32 is a reasonable tile size for both kWarpSize options.
+constexpr int TILE_SIZE = 32;
+
+// Reduction tree operator
+template <typename DistanceOp, int N>
+struct ReduceDistanceOp {
+ __device__ static DistanceOp reduce(DistanceOp ops[N]) {
+ DistanceOp vals[N / 2];
+#pragma unroll
+ for (int i = 0; i < N / 2; ++i) {
+ vals[i] = ops[i * 2];
+ vals[i].combine(ops[i * 2 + 1]);
+ }
+
+ return ReduceDistanceOp<DistanceOp, N / 2>::reduce(vals);
+ }
+};
+
+template <typename DistanceOp>
+struct ReduceDistanceOp<DistanceOp, 1> {
+ __device__ static DistanceOp reduce(DistanceOp ops[1]) {
+ return ops[0];
+ }
+};
+
+// Implements a pairwise reduction tree
+template <typename T, int Unroll, int DimMultiple, typename DistanceOp>
+inline __device__ DistanceOp
+reduce(const DistanceOp& in,
+ const T queryTile[TILE_SIZE][DimMultiple * TILE_SIZE + 1],
+ const T vecTile[TILE_SIZE][DimMultiple * TILE_SIZE + 1]) {
+ DistanceOp accs[Unroll];
+#pragma unroll
+ for (int i = 0; i < Unroll; ++i) {
+ accs[i] = in.zero();
+ }
+
+ auto vecTileBase = vecTile[threadIdx.x];
+ auto queryTileBase = queryTile[threadIdx.y];
+
+#pragma unroll
+ for (int i = 0; i < Unroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < (TILE_SIZE * DimMultiple / Unroll); ++j) {
+ int idx = i * (TILE_SIZE * DimMultiple / Unroll) + j;
+ accs[i].handle(
+ ConvertTo<float>::to(queryTileBase[idx]),
+ ConvertTo<float>::to(vecTileBase[idx]));
+ }
+ }
+
+ return ReduceDistanceOp<DistanceOp, Unroll>::reduce(accs);
+}
+
+// Our general distance matrix "multiplication" kernel
+template <typename T, typename DistanceOp, bool InnerContig>
+__launch_bounds__(TILE_SIZE* TILE_SIZE) __global__ void generalDistance(
+ Tensor<T, 2, InnerContig> query, // m x k
+ Tensor<T, 2, InnerContig> vec, // n x k
+ DistanceOp op,
+ Tensor<float, 2, true> out) { // m x n
+ constexpr int kDimMultiple = 1;
+
+ __shared__ T queryTile[TILE_SIZE][TILE_SIZE * kDimMultiple + 1];
+ __shared__ T vecTile[TILE_SIZE][TILE_SIZE * kDimMultiple + 1];
+
+ // block y -> query
+ // block x -> vector
+
+ idx_t queryBlock = idx_t(blockIdx.y) * TILE_SIZE;
+ idx_t queryThread = queryBlock + threadIdx.y;
+
+ idx_t vecBlock = idx_t(blockIdx.x) * TILE_SIZE;
+ idx_t vecThreadLoad = vecBlock + threadIdx.y;
+ idx_t vecThreadSave = vecBlock + threadIdx.x;
+
+ DistanceOp acc = op.zero();
+
+ auto queryTileBase = queryTile[threadIdx.y];
+ auto vecTileBase = vecTile[threadIdx.y];
+
+ auto queryBase = query[queryThread];
+ auto vecBase = vec[vecThreadLoad];
+
+ if ((blockIdx.x != (gridDim.x - 1)) && (blockIdx.y != (gridDim.y - 1))) {
+ //
+ // Interior tile
+ //
+ idx_t limit =
+ utils::roundDown(query.getSize(1), TILE_SIZE * kDimMultiple);
+
+ for (idx_t k = threadIdx.x; k < limit; k += TILE_SIZE * kDimMultiple) {
+ // Load query tile
+#pragma unroll
+ for (int i = 0; i < kDimMultiple; ++i) {
+ queryTileBase[threadIdx.x + i * TILE_SIZE] =
+ queryBase[k + i * TILE_SIZE];
+ vecTileBase[threadIdx.x + i * TILE_SIZE] =
+ vecBase[k + i * TILE_SIZE];
+ }
+
+ __syncthreads();
+
+ // thread (y, x) does (query y, vec x)
+ acc.combine(reduce<T, 8, kDimMultiple, DistanceOp>(
+ op, queryTile, vecTile));
+
+ __syncthreads();
+ }
+
+ // Handle remainder
+ if (limit < query.getSize(1)) {
+#pragma unroll
+ for (int i = 0; i < kDimMultiple; ++i) {
+ idx_t k = limit + threadIdx.x + i * TILE_SIZE;
+ bool kInBounds = k < query.getSize(1);
+
+ queryTileBase[threadIdx.x + i * TILE_SIZE] =
+ kInBounds ? queryBase[k] : ConvertTo<T>::to(0.0f);
+
+ vecTileBase[threadIdx.x + i * TILE_SIZE] =
+ kInBounds ? vecBase[k] : ConvertTo<T>::to(0.0f);
+ }
+
+ __syncthreads();
+
+ idx_t remainder = query.getSize(1) - limit;
+
+ // thread (y, x) does (query y, vec x)
+#pragma unroll
+ for (idx_t i = 0; i < remainder; ++i) {
+ acc.handle(
+ ConvertTo<float>::to(queryTileBase[i]),
+ ConvertTo<float>::to(vecTile[threadIdx.x][i]));
+ }
+ }
+
+ // Write out results
+ out[queryThread][vecThreadSave] = acc.reduce();
+ } else {
+ //
+ // Otherwise, we're an exterior tile
+ //
+
+ bool queryThreadInBounds = queryThread < query.getSize(0);
+ bool vecThreadInBoundsLoad = vecThreadLoad < vec.getSize(0);
+ bool vecThreadInBoundsSave = vecThreadSave < vec.getSize(0);
+ idx_t limit = utils::roundDown(query.getSize(1), TILE_SIZE);
+
+ for (idx_t k = threadIdx.x; k < limit; k += TILE_SIZE) {
+ // Load query tile
+ queryTileBase[threadIdx.x] =
+ queryThreadInBounds ? queryBase[k] : ConvertTo<T>::to(0.0f);
+
+ vecTileBase[threadIdx.x] =
+ vecThreadInBoundsLoad ? vecBase[k] : ConvertTo<T>::to(0.0f);
+
+ __syncthreads();
+
+ // thread (y, x) does (query y, vec x)
+#pragma unroll
+ for (int i = 0; i < TILE_SIZE; ++i) {
+ acc.handle(
+ ConvertTo<float>::to(queryTileBase[i]),
+ ConvertTo<float>::to(vecTile[threadIdx.x][i]));
+ }
+
+ __syncthreads();
+ }
+
+ // Handle remainder
+ if (limit < query.getSize(1)) {
+ idx_t k = limit + threadIdx.x;
+ bool kInBounds = k < query.getSize(1);
+
+ // Load query tile
+ queryTileBase[threadIdx.x] = queryThreadInBounds && kInBounds
+ ? queryBase[k]
+ : ConvertTo<T>::to(0.0f);
+
+ vecTileBase[threadIdx.x] = vecThreadInBoundsLoad && kInBounds
+ ? vecBase[k]
+ : ConvertTo<T>::to(0.0f);
+
+ __syncthreads();
+
+ idx_t remainder = query.getSize(1) - limit;
+
+ // thread (y, x) does (query y, vec x)
+ for (int i = 0; i < remainder; ++i) {
+ acc.handle(
+ ConvertTo<float>::to(queryTileBase[i]),
+ ConvertTo<float>::to(vecTile[threadIdx.x][i]));
+ }
+ }
+
+ // Write out results
+ if (queryThreadInBounds && vecThreadInBoundsSave) {
+ out[queryThread][vecThreadSave] = acc.reduce();
+ }
+ }
+}
+
+template <typename T, typename DistanceOp, bool InnerContig>
+void runGeneralDistanceKernel(
+ Tensor<T, 2, InnerContig>& vecs,
+ Tensor<T, 2, InnerContig>& query,
+ Tensor<float, 2, true>& out,
+ const DistanceOp& op,
+ cudaStream_t stream) {
+ FAISS_ASSERT(vecs.getSize(1) == query.getSize(1));
+ FAISS_ASSERT(out.getSize(0) == query.getSize(0));
+ FAISS_ASSERT(out.getSize(1) == vecs.getSize(0));
+
+ dim3 grid(
+ utils::divUp(vecs.getSize(0), TILE_SIZE),
+ utils::divUp(query.getSize(0), TILE_SIZE));
+ FAISS_ASSERT(grid.y <= getMaxGridCurrentDevice().y);
+ dim3 block(TILE_SIZE, TILE_SIZE);
+
+ generalDistance<<<grid, block, 0, stream>>>(query, vecs, op, out);
+}
+
+template <typename T, typename DistanceOp, bool InnerContig>
+void runGeneralDistance(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<T, 2, InnerContig>& centroids,
+ Tensor<T, 2, InnerContig>& queries,
+ int k,
+ const DistanceOp& op,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ // The # of centroids in `centroids` based on memory layout
+ auto numCentroids = centroids.getSize(0);
+
+ // The # of queries in `queries` based on memory layout
+ auto numQueries = queries.getSize(0);
+
+ // The dimensions of the vectors to consider
+ auto dim = queries.getSize(1);
+ FAISS_ASSERT(
+ (numQueries == 0 || numCentroids == 0) ||
+ dim == centroids.getSize(1));
+
+ FAISS_ASSERT(outDistances.getSize(0) == numQueries);
+ FAISS_ASSERT(outIndices.getSize(0) == numQueries);
+ FAISS_ASSERT(outDistances.getSize(1) == k);
+ FAISS_ASSERT(outIndices.getSize(1) == k);
+
+ // If we're quering against a 0 sized set, just return empty results
+ if (centroids.numElements() == 0) {
+ thrust::fill(
+ thrust::cuda::par.on(stream),
+ outDistances.data(),
+ outDistances.end(),
+ Limits<float>::getMax());
+
+ thrust::fill(
+ thrust::cuda::par.on(stream),
+ outIndices.data(),
+ outIndices.end(),
+ -1);
+
+ return;
+ }
+
+ // By default, aim to use up to 512 MB of memory for the processing, with
+ // both number of queries and number of centroids being at least 512.
+ idx_t tileRows = 0;
+ idx_t tileCols = 0;
+ chooseTileSize(
+ numQueries,
+ numCentroids,
+ dim,
+ sizeof(T),
+ res->getTempMemoryAvailableCurrentDevice(),
+ tileRows,
+ tileCols);
+
+ auto numColTiles = utils::divUp(numCentroids, tileCols);
+
+ // We can have any number of vectors to query against, even less than k, in
+ // which case we'll return -1 for the index
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K); // select limitation
+
+ // Temporary output memory space we'll use
+ DeviceTensor<float, 2, true> distanceBuf1(
+ res, makeTempAlloc(AllocType::Other, stream), {tileRows, tileCols});
+ DeviceTensor<float, 2, true> distanceBuf2(
+ res, makeTempAlloc(AllocType::Other, stream), {tileRows, tileCols});
+ DeviceTensor<float, 2, true>* distanceBufs[2] = {
+ &distanceBuf1, &distanceBuf2};
+
+ DeviceTensor<float, 2, true> outDistanceBuf1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<float, 2, true> outDistanceBuf2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<float, 2, true>* outDistanceBufs[2] = {
+ &outDistanceBuf1, &outDistanceBuf2};
+
+ DeviceTensor<idx_t, 2, true> outIndexBuf1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<idx_t, 2, true> outIndexBuf2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {tileRows, numColTiles * k});
+ DeviceTensor<idx_t, 2, true>* outIndexBufs[2] = {
+ &outIndexBuf1, &outIndexBuf2};
+
+ auto streams = res->getAlternateStreamsCurrentDevice();
+ streamWait(streams, {stream});
+
+ int curStream = 0;
+ bool interrupt = false;
+
+ // Tile over the input queries
+ for (idx_t i = 0; i < numQueries; i += tileRows) {
+ if (interrupt || InterruptCallback::is_interrupted()) {
+ interrupt = true;
+ break;
+ }
+
+ auto curQuerySize = std::min(tileRows, numQueries - i);
+
+ auto outDistanceView = outDistances.narrow(0, i, curQuerySize);
+ auto outIndexView = outIndices.narrow(0, i, curQuerySize);
+
+ auto queryView = queries.narrow(0, i, curQuerySize);
+
+ auto outDistanceBufRowView =
+ outDistanceBufs[curStream]->narrow(0, 0, curQuerySize);
+ auto outIndexBufRowView =
+ outIndexBufs[curStream]->narrow(0, 0, curQuerySize);
+
+ // Tile over the centroids
+ for (idx_t j = 0; j < numCentroids; j += tileCols) {
+ if (InterruptCallback::is_interrupted()) {
+ interrupt = true;
+ break;
+ }
+
+ auto curCentroidSize = std::min(tileCols, numCentroids - j);
+ auto curColTile = j / tileCols;
+
+ auto centroidsView =
+ sliceCentroids(centroids, true, j, curCentroidSize);
+
+ auto distanceBufView = distanceBufs[curStream]
+ ->narrow(0, 0, curQuerySize)
+ .narrow(1, 0, curCentroidSize);
+
+ auto outDistanceBufColView =
+ outDistanceBufRowView.narrow(1, k * curColTile, k);
+ auto outIndexBufColView =
+ outIndexBufRowView.narrow(1, k * curColTile, k);
+
+ runGeneralDistanceKernel(
+ centroidsView,
+ queryView,
+ distanceBufView,
+ op,
+ streams[curStream]);
+
+ // For IP, just k-select the output for this tile
+ if (tileCols == numCentroids) {
+ // Write into the final output
+ runBlockSelect(
+ distanceBufView,
+ outDistanceView,
+ outIndexView,
+ DistanceOp::kDirection,
+ k,
+ streams[curStream]);
+ } else {
+ // Write into the intermediate output
+ runBlockSelect(
+ distanceBufView,
+ outDistanceBufColView,
+ outIndexBufColView,
+ DistanceOp::kDirection,
+ k,
+ streams[curStream]);
+ }
+ }
+
+ // As we're finished with processing a full set of centroids, perform
+ // the final k-selection
+ if (tileCols != numCentroids) {
+ // The indices are tile-relative; for each tile of k, we need to add
+ // tileCols to the index
+ runIncrementIndex(
+ outIndexBufRowView, k, tileCols, streams[curStream]);
+
+ runBlockSelectPair(
+ outDistanceBufRowView,
+ outIndexBufRowView,
+ outDistanceView,
+ outIndexView,
+ DistanceOp::kDirection,
+ k,
+ streams[curStream]);
+ }
+
+ curStream = (curStream + 1) % 2;
+ }
+
+ // Have the desired ordering stream wait on the multi-stream
+ streamWait({stream}, streams);
+
+ if (interrupt) {
+ FAISS_THROW_MSG("interrupted");
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/GpuScalarQuantizer.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/GpuScalarQuantizer.cuh
new file mode 100644
index 0000000..186ecac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/GpuScalarQuantizer.cuh
@@ -0,0 +1,852 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+namespace faiss {
+namespace gpu {
+
+inline bool isSQSupported(ScalarQuantizer::QuantizerType qtype) {
+ switch (qtype) {
+ case ScalarQuantizer::QuantizerType::QT_8bit:
+ case ScalarQuantizer::QuantizerType::QT_8bit_uniform:
+ case ScalarQuantizer::QuantizerType::QT_8bit_direct:
+ case ScalarQuantizer::QuantizerType::QT_4bit:
+ case ScalarQuantizer::QuantizerType::QT_4bit_uniform:
+ case ScalarQuantizer::QuantizerType::QT_6bit:
+ case ScalarQuantizer::QuantizerType::QT_fp16:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// Wrapper around the CPU ScalarQuantizer that allows storage of parameters in
+// GPU memory
+struct GpuScalarQuantizer : public ScalarQuantizer {
+ GpuScalarQuantizer(GpuResources* res, const ScalarQuantizer& sq)
+ : ScalarQuantizer(sq),
+ gpuTrained(DeviceTensor<float, 1, true>(
+ res,
+ makeDevAlloc(AllocType::Quantizer, 0),
+ {(idx_t)sq.trained.size()})) {
+ HostTensor<float, 1, true> cpuTrained(
+ (float*)sq.trained.data(), {(idx_t)sq.trained.size()});
+
+ auto stream = res->getDefaultStreamCurrentDevice();
+ gpuTrained.copyFrom(cpuTrained, stream);
+ }
+
+ // ScalarQuantizer::trained copied to GPU memory
+ DeviceTensor<float, 1, true> gpuTrained;
+};
+
+//
+// Quantizer codecs
+//
+
+// QT is the quantizer type implemented
+// DimMultiple is the minimum guaranteed dimension multiple of the vectors
+// encoded (used for ensuring alignment for memory load/stores)
+template <int QT, int DimMultiple>
+struct Codec {};
+
+/////
+//
+// 32 bit encodings
+// (does not use qtype)
+//
+/////
+
+struct CodecFloat {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = 1;
+
+ CodecFloat(int vecBytes) : bytesPerVec(vecBytes) {}
+
+ size_t getSmemSize(int dim) {
+ return 0;
+ }
+ inline __device__ void initKernel(float* smem, int dim) {}
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ float* p = (float*)&((uint8_t*)data)[vec * bytesPerVec];
+ out[0] = p[d];
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD) const {
+ // doesn't need implementing (kDimPerIter == 1)
+ return 0.0f;
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ float* p = (float*)&((uint8_t*)data)[vec * bytesPerVec];
+ p[d] = v[0];
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining,
+ float v[kDimPerIter]) const {
+ // doesn't need implementing (kDimPerIter == 1)
+ }
+
+ //
+ // new implementation
+ //
+ using EncodeT = float;
+ static constexpr int kEncodeBits = 32;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return v;
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return v;
+ }
+
+ int bytesPerVec;
+};
+
+/////
+//
+// 16 bit encodings
+//
+/////
+
+// Arbitrary dimension fp16
+template <>
+struct Codec<ScalarQuantizer::QuantizerType::QT_fp16, 1> {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = 1;
+
+ Codec(int vecBytes) : bytesPerVec(vecBytes) {}
+
+ size_t getSmemSize(int dim) {
+ return 0;
+ }
+ inline __device__ void initKernel(float* smem, int dim) {}
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ half* p = (half*)&((uint8_t*)data)[vec * bytesPerVec];
+ out[0] = ConvertTo<float>::to(p[d]);
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD) const {
+ // doesn't need implementing (kDimPerIter == 1)
+ return 0.0f;
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ half* p = (half*)&((uint8_t*)data)[vec * bytesPerVec];
+ p[d] = ConvertTo<half>::to(v[0]);
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining,
+ float v[kDimPerIter]) const {
+ // doesn't need implementing (kDimPerIter == 1)
+ }
+
+ //
+ // new implementation
+ //
+ using EncodeT = half;
+ static constexpr int kEncodeBits = 16;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return ConvertTo<half>::to(v);
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return ConvertTo<float>::to(v);
+ }
+
+ int bytesPerVec;
+};
+
+/////
+//
+// 8 bit encodings
+//
+/////
+
+template <int DimPerIter>
+struct Get8BitType {};
+
+template <>
+struct Get8BitType<1> {
+ using T = uint8_t;
+};
+
+template <>
+struct Get8BitType<2> {
+ using T = uint16_t;
+};
+
+template <>
+struct Get8BitType<4> {
+ using T = uint32_t;
+};
+
+// Uniform quantization across all dimensions
+template <int DimMultiple>
+struct Codec<ScalarQuantizer::QuantizerType::QT_8bit_uniform, DimMultiple> {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = DimMultiple;
+ using MemT = typename Get8BitType<DimMultiple>::T;
+
+ Codec(int vecBytes, float min, float diff)
+ : bytesPerVec(vecBytes), vmin(min), vdiff(diff) {}
+
+ size_t getSmemSize(int dim) {
+ return 0;
+ }
+ inline __device__ void initKernel(float* smem, int dim) {
+ // We are performing vmin + vdiff * (v + 0.5) / (2^bits - 1)
+ // This can be simplified to vmin' + vdiff' * v where:
+ // vdiff' = vdiff / (2^bits - 1)
+ // vmin' = vmin + 0.5 * vdiff'
+ auto vd = vdiff * (1.0f / 255.0f);
+ vmin = vmin + 0.5f * vd;
+ vdiff = vd;
+ }
+
+ inline __device__ float decodeHelper(uint8_t v) const {
+ return vmin + (float)v * vdiff;
+ }
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ MemT* p = (MemT*)&((uint8_t*)data)[vec * bytesPerVec];
+ MemT pv = p[d];
+
+ uint8_t x[kDimPerIter];
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ x[i] = (uint8_t)((pv >> (i * 8)) & 0xffU);
+ }
+
+ float xDec[kDimPerIter];
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ xDec[i] = decodeHelper(x[i]);
+ }
+
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ out[i] = xDec[i];
+ }
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD) const {
+ if (DimMultiple > 1) {
+ // should not be called
+ assert(false);
+ }
+
+ // otherwise does not need implementing
+ return 0;
+ }
+
+ inline __device__ uint8_t encodeHelper(float v) const {
+ float x = (v - vmin) / vdiff;
+ x = fminf(1.0f, fmaxf(0.0f, x));
+ return (uint8_t)(x * 255.0f);
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ MemT* p = (MemT*)&((uint8_t*)data)[vec * bytesPerVec];
+
+ MemT x[kDimPerIter];
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ x[i] = encodeHelper(v[i]);
+ }
+
+ MemT out = 0;
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ out |= (x[i] << (i * 8));
+ }
+
+ p[d] = out;
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining,
+ float v[kDimPerIter]) const {
+ if (DimMultiple > 1) {
+ // should not be called
+ assert(false);
+ }
+
+ // otherwise does not need implementing
+ }
+
+ //
+ // interleaved code implementation
+ //
+ using EncodeT = uint8_t;
+ static constexpr int kEncodeBits = 8;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return encodeHelper(v);
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return decodeHelper(v);
+ }
+
+ int bytesPerVec;
+ float vmin;
+ float vdiff;
+};
+
+// Uniform quantization per each dimension
+template <int DimMultiple>
+struct Codec<ScalarQuantizer::QuantizerType::QT_8bit, DimMultiple> {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = DimMultiple;
+ using MemT = typename Get8BitType<DimMultiple>::T;
+
+ Codec(int vecBytes, float* min, float* diff)
+ : bytesPerVec(vecBytes),
+ vmin(min),
+ vdiff(diff),
+ smemVmin(nullptr),
+ smemVdiff(nullptr) {}
+
+ size_t getSmemSize(int dim) {
+ return sizeof(float) * dim * 2;
+ }
+
+ // Initialize shared memory and local storage
+ // It is up to the user to call a trailing syncthreads (after any other
+ // initialization required has been done)
+ inline __device__ void initKernel(float* smem, int dim) {
+ smemVmin = smem;
+ smemVdiff = smem + dim;
+
+ for (auto i = threadIdx.x; i < dim; i += blockDim.x) {
+ // We are performing vmin + vdiff * (v + 0.5) / (2^bits - 1)
+ // This can be simplified to vmin' + vdiff' * v where:
+ // vdiff' = vdiff / (2^bits - 1)
+ // vmin' = vmin + 0.5 * vdiff'
+ auto vd = vdiff[i] * (1.0f / 255.0f);
+ smemVmin[i] = vmin[i] + 0.5f * vd;
+ smemVdiff[i] = vd;
+ }
+ }
+
+ inline __device__ float decodeHelper(uint8_t v, int realDim) const {
+ return smemVmin[realDim] + (float)v * smemVdiff[realDim];
+ }
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ MemT* p = (MemT*)&((uint8_t*)data)[vec * bytesPerVec];
+ MemT pv = p[d];
+ int realDim = d * kDimPerIter;
+
+ uint8_t x[kDimPerIter];
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ x[i] = (uint8_t)((pv >> (i * 8)) & 0xffU);
+ }
+
+ float xDec[kDimPerIter];
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ xDec[i] = decodeHelper(x[i], realDim + i);
+ }
+
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ out[i] = xDec[i];
+ }
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD) const {
+ if (DimMultiple > 1) {
+ // should not be called
+ assert(false);
+ }
+
+ // otherwise does not need implementing
+ return 0;
+ }
+
+ inline __device__ uint8_t encodeHelper(float v, int realDim) const {
+ float x = (v - vmin[realDim]) / vdiff[realDim];
+ x = fminf(1.0f, fmaxf(0.0f, x));
+ return (uint8_t)(x * 255.0f);
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ MemT* p = (MemT*)&((uint8_t*)data)[vec * bytesPerVec];
+ int realDim = d * kDimPerIter;
+
+ MemT x[kDimPerIter];
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ x[i] = encodeHelper(v[i], realDim + i);
+ }
+
+ MemT out = 0;
+#pragma unroll
+ for (int i = 0; i < kDimPerIter; ++i) {
+ out |= (x[i] << (i * 8));
+ }
+
+ p[d] = out;
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining,
+ float v[kDimPerIter]) const {
+ if (DimMultiple > 1) {
+ // should not be called
+ assert(false);
+ }
+
+ // otherwise does not need implementing
+ }
+
+ //
+ // interleaved code implementation
+ //
+ using EncodeT = uint8_t;
+ static constexpr int kEncodeBits = 8;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return encodeHelper(v, dim);
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return decodeHelper(v, dim);
+ }
+
+ int bytesPerVec;
+
+ // gmem pointers
+ const float* vmin;
+ const float* vdiff;
+
+ // smem pointers (configured in the kernel)
+ float* smemVmin;
+ float* smemVdiff;
+};
+
+template <>
+struct Codec<ScalarQuantizer::QuantizerType::QT_8bit_direct, 1> {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = 1;
+
+ Codec(int vecBytes) : bytesPerVec(vecBytes) {}
+
+ size_t getSmemSize(int dim) {
+ return 0;
+ }
+ inline __device__ void initKernel(float* smem, int dim) {}
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ out[0] = (float)p[d];
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD) const {
+ // doesn't need implementing (kDimPerIter == 1)
+ return 0.0f;
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ p[d] = (uint8_t)v[0];
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining,
+ float v[kDimPerIter]) const {
+ // doesn't need implementing (kDimPerIter == 1)
+ }
+
+ //
+ // interleaved code implementation
+ //
+ using EncodeT = uint8_t;
+ static constexpr int kEncodeBits = 8;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return (uint8_t)v;
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return (float)v;
+ }
+
+ int bytesPerVec;
+};
+
+/////
+//
+// 6 bit encodings
+//
+/////
+
+template <>
+struct Codec<ScalarQuantizer::QuantizerType::QT_6bit, 1> {
+ Codec(int vecBytes, float* min, float* diff)
+ : bytesPerVec(vecBytes),
+ vmin(min),
+ vdiff(diff),
+ smemVmin(nullptr),
+ smemVdiff(nullptr) {}
+
+ size_t getSmemSize(int dim) {
+ return sizeof(float) * dim * 2;
+ }
+
+ // Initialize shared memory and local storage
+ // It is up to the user to call a trailing syncthreads (after any other
+ // initialization required has been done)
+ inline __device__ void initKernel(float* smem, int dim) {
+ smemVmin = smem;
+ smemVdiff = smem + dim;
+
+ for (auto i = threadIdx.x; i < dim; i += blockDim.x) {
+ // We are performing vmin + vdiff * (v + 0.5) / (2^bits - 1)
+ // This can be simplified to vmin' + vdiff' * v where:
+ // vdiff' = vdiff / (2^bits - 1)
+ // vmin' = vmin + 0.5 * vdiff'
+ auto vd = vdiff[i] * (1.0f / 63.0f);
+ smemVmin[i] = vmin[i] + 0.5f * vd;
+ smemVdiff[i] = vd;
+ }
+ }
+
+ inline __device__ float decodeHelper(uint8_t v, int realDim) const {
+ return smemVmin[realDim] + (float)v * smemVdiff[realDim];
+ }
+
+ inline __device__ uint8_t encodeHelper(float v, int realDim) const {
+ float x = (v - vmin[realDim]) / vdiff[realDim];
+ x = fminf(1.0f, fmaxf(0.0f, x));
+ return (uint8_t)(x * 63.0f);
+ }
+
+ //
+ // interleaved code implementation
+ //
+ using EncodeT = uint8_t;
+ static constexpr int kEncodeBits = 6;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return encodeHelper(v, dim);
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return decodeHelper(v, dim);
+ }
+
+ int bytesPerVec;
+
+ // gmem pointers
+ const float* vmin;
+ const float* vdiff;
+
+ // smem pointers
+ float* smemVmin;
+ float* smemVdiff;
+};
+
+/////
+//
+// 4 bit encodings
+//
+/////
+
+// Uniform quantization across all dimensions
+template <>
+struct Codec<ScalarQuantizer::QuantizerType::QT_4bit_uniform, 1> {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = 2;
+
+ Codec(int vecBytes, float min, float diff)
+ : bytesPerVec(vecBytes), vmin(min), vdiff(diff) {}
+
+ size_t getSmemSize(int dim) {
+ return 0;
+ }
+ inline __device__ void initKernel(float* smem, int dim) {
+ // We are performing vmin + vdiff * (v + 0.5) / (2^bits - 1)
+ // This can be simplified to vmin' + vdiff' * v where:
+ // vdiff' = vdiff / (2^bits - 1)
+ // vmin' = vmin + 0.5 * vdiff'
+ auto vd = vdiff * (1.0f / 15.0f);
+ vmin = vmin + 0.5f * vd;
+ vdiff = vd;
+ }
+
+ inline __device__ float decodeHelper(uint8_t v) const {
+ return vmin + (float)v * vdiff;
+ }
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ uint8_t pv = p[d];
+
+ out[0] = decodeHelper(pv & 0xf);
+ out[1] = decodeHelper(pv >> 4);
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD /* unused */) const {
+ // We can only be called for a single input
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ uint8_t pv = p[d];
+
+ return decodeHelper(pv & 0xf);
+ }
+
+ inline __device__ uint8_t encodeHelper(float v) const {
+ float x = (v - vmin) / vdiff;
+ x = fminf(1.0f, fmaxf(0.0f, x));
+ return (uint8_t)(x * 15.0f);
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ p[d] = encodeHelper(v[0]) | (encodeHelper(v[1]) << 4);
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining, /* unused */
+ float v[kDimPerIter]) const {
+ // We can only be called for a single output
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ p[d] = encodeHelper(v[0]);
+ }
+
+ //
+ // interleaved code implementation
+ //
+ using EncodeT = uint8_t;
+ static constexpr int kEncodeBits = 4;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return encodeHelper(v);
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return decodeHelper(v);
+ }
+
+ int bytesPerVec;
+ float vmin;
+ float vdiff;
+};
+
+template <>
+struct Codec<ScalarQuantizer::QuantizerType::QT_4bit, 1> {
+ /// How many dimensions per iteration we are handling for encoding or
+ /// decoding
+ static constexpr int kDimPerIter = 2;
+
+ Codec(int vecBytes, float* min, float* diff)
+ : bytesPerVec(vecBytes),
+ vmin(min),
+ vdiff(diff),
+ smemVmin(nullptr),
+ smemVdiff(nullptr) {}
+
+ size_t getSmemSize(int dim) {
+ return sizeof(float) * dim * 2;
+ }
+
+ inline __device__ void initKernel(float* smem, int dim) {
+ smemVmin = smem;
+ smemVdiff = smem + dim;
+
+ for (auto i = threadIdx.x; i < dim; i += blockDim.x) {
+ // We are performing vmin + vdiff * (v + 0.5) / (2^bits - 1)
+ // This can be simplified to vmin' + vdiff' * v where:
+ // vdiff' = vdiff / (2^bits - 1)
+ // vmin' = vmin + 0.5 * vdiff'
+ auto vd = vdiff[i] / 15.0f;
+ smemVmin[i] = vmin[i] + 0.5f * vd;
+ smemVdiff[i] = vd;
+ }
+
+ __syncthreads();
+ }
+
+ inline __device__ float decodeHelper(uint8_t v, int realDim) const {
+ return smemVmin[realDim] + (float)v * smemVdiff[realDim];
+ }
+
+ inline __device__ void decode(void* data, idx_t vec, int d, float* out)
+ const {
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ uint8_t pv = p[d];
+ int realDim = d * kDimPerIter;
+
+ out[0] = decodeHelper(pv & 0xf, realDim);
+ out[1] = decodeHelper(pv >> 4, realDim + 1);
+ }
+
+ inline __device__ float decodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int subD /* unused */) const {
+ // We can only be called for a single input
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ uint8_t pv = p[d];
+ int realDim = d * kDimPerIter;
+
+ return decodeHelper(pv & 0xf, realDim);
+ }
+
+ inline __device__ uint8_t encodeHelper(float v, int realDim) const {
+ float x = (v - vmin[realDim]) / vdiff[realDim];
+ x = fminf(1.0f, fmaxf(0.0f, x));
+ return (uint8_t)(x * 15.0f);
+ }
+
+ inline __device__ void encode(
+ void* data,
+ idx_t vec,
+ int d,
+ float v[kDimPerIter]) const {
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ int realDim = d * kDimPerIter;
+ p[d] = encodeHelper(v[0], realDim) |
+ (encodeHelper(v[1], realDim + 1) << 4);
+ }
+
+ inline __device__ void encodePartial(
+ void* data,
+ idx_t vec,
+ int d,
+ int remaining, /* unused */
+ float v[kDimPerIter]) const {
+ // We can only be called for a single output
+ uint8_t* p = &((uint8_t*)data)[vec * bytesPerVec];
+ int realDim = d * kDimPerIter;
+
+ p[d] = encodeHelper(v[0], realDim);
+ }
+
+ //
+ // interleaved code implementation
+ //
+ using EncodeT = uint8_t;
+ static constexpr int kEncodeBits = 4;
+
+ inline __device__ EncodeT encodeNew(int dim, float v) const {
+ return encodeHelper(v, dim);
+ }
+
+ inline __device__ float decodeNew(int dim, EncodeT v) const {
+ return decodeHelper(v, dim);
+ }
+
+ int bytesPerVec;
+
+ // gmem pointers
+ const float* vmin;
+ const float* vdiff;
+
+ // smem pointers
+ float* smemVmin;
+ float* smemVdiff;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFAppend.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFAppend.cu
new file mode 100644
index 0000000..dd1c907
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFAppend.cu
@@ -0,0 +1,646 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/impl/IVFAppend.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+#include <faiss/gpu/utils/WarpPackedBits.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+#include <algorithm>
+
+namespace faiss {
+namespace gpu {
+
+//
+// IVF list metadata aupdate
+//
+
+// Updates the device-size array of list start pointers for codes and indices
+__global__ void runUpdateListPointers(
+ Tensor<idx_t, 1, true> listIds,
+ Tensor<idx_t, 1, true> newListLength,
+ Tensor<void*, 1, true> newCodePointers,
+ Tensor<void*, 1, true> newIndexPointers,
+ idx_t* listLengths,
+ void** listCodes,
+ void** listIndices) {
+ idx_t i = idx_t(blockIdx.x) * blockDim.x + threadIdx.x;
+
+ if (i < listIds.getSize(0)) {
+ idx_t listId = listIds[i];
+ listLengths[listId] = newListLength[i];
+ listCodes[listId] = newCodePointers[i];
+ listIndices[listId] = newIndexPointers[i];
+ }
+}
+
+void runUpdateListPointers(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& newListLength,
+ Tensor<void*, 1, true>& newCodePointers,
+ Tensor<void*, 1, true>& newIndexPointers,
+ DeviceVector<idx_t>& listLengths,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ cudaStream_t stream) {
+ auto numThreads =
+ std::min(listIds.getSize(0), (idx_t)getMaxThreadsCurrentDevice());
+ auto numBlocks = utils::divUp(listIds.getSize(0), numThreads);
+
+ dim3 grid(numBlocks);
+ dim3 block(numThreads);
+
+ runUpdateListPointers<<<grid, block, 0, stream>>>(
+ listIds,
+ newListLength,
+ newCodePointers,
+ newIndexPointers,
+ listLengths.data(),
+ listCodes.data(),
+ listIndices.data());
+
+ CUDA_TEST_ERROR();
+}
+
+// Appends new indices for vectors being added to the IVF indices lists
+__global__ void ivfIndicesAppend(
+ Tensor<idx_t, 1, true> listIds,
+ Tensor<idx_t, 1, true> listOffset,
+ Tensor<idx_t, 1, true> indices,
+ IndicesOptions opt,
+ void** listIndices) {
+ idx_t vec = idx_t(blockIdx.x) * blockDim.x + threadIdx.x;
+
+ if (vec >= listIds.getSize(0)) {
+ return;
+ }
+
+ idx_t listId = listIds[vec];
+ idx_t offset = listOffset[vec];
+
+ // Add vector could be invalid (contains NaNs etc)
+ if (listId == -1 || offset == -1) {
+ return;
+ }
+
+ idx_t index = indices[vec];
+
+ if (opt == INDICES_32_BIT) {
+ // FIXME: there could be overflow here, but where should we check this?
+ ((int*)listIndices[listId])[offset] = (int)index;
+ } else if (opt == INDICES_64_BIT) {
+ ((idx_t*)listIndices[listId])[offset] = index;
+ }
+}
+
+void runIVFIndicesAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<idx_t, 1, true>& indices,
+ IndicesOptions opt,
+ DeviceVector<void*>& listIndices,
+ cudaStream_t stream) {
+ FAISS_ASSERT(
+ opt == INDICES_CPU || opt == INDICES_IVF || opt == INDICES_32_BIT ||
+ opt == INDICES_64_BIT);
+
+ if (opt != INDICES_CPU && opt != INDICES_IVF) {
+ auto num = listIds.getSize(0);
+ auto threads = std::min(num, (idx_t)getMaxThreadsCurrentDevice());
+ auto blocks = utils::divUp(num, threads);
+
+ ivfIndicesAppend<<<blocks, threads, 0, stream>>>(
+ listIds, listOffset, indices, opt, listIndices.data());
+
+ CUDA_TEST_ERROR();
+ }
+}
+
+//
+// IVF non-interleaved append
+//
+
+template <typename Codec>
+__global__ void ivfFlatAppend(
+ Tensor<idx_t, 1, true> listIds,
+ Tensor<idx_t, 1, true> listOffset,
+ Tensor<float, 2, true> vecs,
+ void** listData,
+ Codec codec) {
+ idx_t vec = blockIdx.x;
+
+ idx_t listId = listIds[vec];
+ idx_t offset = listOffset[vec];
+
+ // Add vector could be invalid (contains NaNs etc)
+ if (listId == -1 || offset == -1) {
+ return;
+ }
+
+ // Handle whole encoding (only thread 0 will handle the remainder)
+ // FIXME: dimension < max int?
+ idx_t limit = utils::divDown(vecs.getSize(1), Codec::kDimPerIter);
+
+ idx_t i;
+ for (i = threadIdx.x; i < limit; i += blockDim.x) {
+ int realDim = i * Codec::kDimPerIter;
+ float toEncode[Codec::kDimPerIter];
+
+#pragma unroll
+ for (int j = 0; j < Codec::kDimPerIter; ++j) {
+ toEncode[j] = vecs[vec][realDim + j];
+ }
+
+ codec.encode(listData[listId], offset, i, toEncode);
+ }
+
+ // Handle remainder with a single thread, if any
+ if (Codec::kDimPerIter > 1) {
+ int realDim = limit * Codec::kDimPerIter;
+
+ // Was there any remainder?
+ if (realDim < vecs.getSize(1)) {
+ if (threadIdx.x == 0) {
+ float toEncode[Codec::kDimPerIter];
+
+ // How many remaining that we need to encode
+ int remaining = vecs.getSize(1) - realDim;
+
+#pragma unroll
+ for (int j = 0; j < Codec::kDimPerIter; ++j) {
+ int idx = realDim + j;
+ toEncode[j] = idx < vecs.getSize(1) ? vecs[vec][idx] : 0.0f;
+ }
+
+ codec.encodePartial(
+ listData[listId], offset, i, remaining, toEncode);
+ }
+ }
+ }
+}
+
+void runIVFFlatAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<float, 2, true>& vecs,
+ GpuScalarQuantizer* scalarQ,
+ DeviceVector<void*>& listData,
+ cudaStream_t stream) {
+ auto dim = vecs.getSize(1);
+ idx_t maxThreads = getMaxThreadsCurrentDevice();
+
+ // Each block will handle appending a single vector
+#define RUN_APPEND \
+ do { \
+ dim3 grid(vecs.getSize(0)); \
+ dim3 block(std::min(dim / codec.kDimPerIter, maxThreads)); \
+ ivfFlatAppend<<<grid, block, 0, stream>>>( \
+ listIds, listOffset, vecs, listData.data(), codec); \
+ } while (0)
+
+ if (!scalarQ) {
+ CodecFloat codec(dim * sizeof(float));
+ RUN_APPEND;
+ } else {
+ switch (scalarQ->qtype) {
+ case ScalarQuantizer::QuantizerType::QT_8bit: {
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit, 1> codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ RUN_APPEND;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_uniform: {
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_uniform, 1> codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+ RUN_APPEND;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_fp16: {
+ Codec<ScalarQuantizer::QuantizerType::QT_fp16, 1> codec(
+ scalarQ->code_size);
+ RUN_APPEND;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_direct: {
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_direct, 1> codec(
+ scalarQ->code_size);
+ RUN_APPEND;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit: {
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit, 1> codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ RUN_APPEND;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit_uniform: {
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit_uniform, 1> codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+ RUN_APPEND;
+ } break;
+ default:
+ // unimplemented, should be handled at a higher level
+ FAISS_ASSERT(false);
+ }
+ }
+
+ CUDA_TEST_ERROR();
+
+#undef RUN_APPEND
+}
+
+__global__ void ivfpqAppend(
+ Tensor<idx_t, 1, true> listIds,
+ Tensor<idx_t, 1, true> listOffset,
+ Tensor<uint8_t, 2, true> encodings,
+ void** listCodes) {
+ idx_t encodingToAdd = idx_t(blockIdx.x) * blockDim.x + threadIdx.x;
+
+ if (encodingToAdd >= listIds.getSize(0)) {
+ return;
+ }
+
+ idx_t listId = listIds[encodingToAdd];
+ idx_t vectorNumInList = listOffset[encodingToAdd];
+
+ // Add vector could be invalid (contains NaNs etc)
+ if (listId == -1 || vectorNumInList == -1) {
+ return;
+ }
+
+ auto encoding = encodings[encodingToAdd];
+
+ // Layout with dimensions innermost
+ uint8_t* codeStart = ((uint8_t*)listCodes[listId]) +
+ vectorNumInList * encodings.getSize(1);
+
+ // FIXME: stride with threads instead of single thread
+ for (idx_t i = 0; i < encodings.getSize(1); ++i) {
+ codeStart[i] = encoding[i];
+ }
+}
+
+void runIVFPQAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<uint8_t, 2, true>& encodings,
+ DeviceVector<void*>& listCodes,
+ cudaStream_t stream) {
+ idx_t threads =
+ std::min(listIds.getSize(0), (idx_t)getMaxThreadsCurrentDevice());
+ idx_t blocks = utils::divUp(listIds.getSize(0), threads);
+
+ ivfpqAppend<<<threads, blocks, 0, stream>>>(
+ listIds, listOffset, encodings, listCodes.data());
+
+ CUDA_TEST_ERROR();
+}
+
+//
+// IVF interleaved append
+//
+
+// Scalar encode a vector to Codec::EncodeT word-sized values; previously this
+// was fused into a single append kernel but was refactored so that Flat, SQ and
+// PQ all use the same arbitrary bitwidth append kernel
+template <typename Codec>
+__global__ void sqEncode(
+ Tensor<float, 2, true> vecs,
+ Tensor<typename Codec::EncodeT, 2, true> encodedVecs,
+ Codec codec) {
+ idx_t vec = blockIdx.x;
+
+ for (idx_t d = threadIdx.x; d < vecs.getSize(1); d += blockDim.x) {
+ encodedVecs[vec][d] = codec.encodeNew(d, vecs[vec][d]);
+ }
+}
+
+template <typename Codec>
+void runSQEncode(
+ Tensor<float, 2, true>& vecs,
+ Tensor<typename Codec::EncodeT, 2, true>& encodedVecs,
+ Codec codec,
+ cudaStream_t stream) {
+ idx_t threads =
+ std::min(vecs.getSize(1), (idx_t)getMaxThreadsCurrentDevice());
+ idx_t blocks = vecs.getSize(0);
+
+ sqEncode<<<blocks, threads, 0, stream>>>(vecs, encodedVecs, codec);
+}
+
+// Handles appending encoded vectors (one per EncodeT word) packed into
+// EncodeBits interleaved by kWarpSize vectors.
+// This is used by Flat, SQ and PQ code for the interleaved format.
+template <typename EncodeT, int EncodeBits>
+__global__ void ivfInterleavedAppend(
+ // the IDs (offset in listData) of the unique lists
+ // being added to
+ Tensor<idx_t, 1, true> uniqueLists,
+ // For each of the list IDs in uniqueLists, the start
+ // offset in vectorsByUniqueList for the vectors that
+ // we are adding to that list
+ Tensor<idx_t, 1, true> uniqueListVectorStart,
+ // IDs in vecs of the vectors being added to each
+ // unique list
+ // The vectors (offset in vecs) added to
+ // uniqueLists[i] is:
+ // {vBUL[uLVS[i]], ..., vBUL[uLVS[i+1] - 1]}
+ Tensor<idx_t, 1, true> vectorsByUniqueList,
+ // For each of the list IDs in uniqueLists, the start
+ // offset (by vector) within that list where we begin
+ // appending
+ Tensor<idx_t, 1, true> uniqueListStartOffset,
+ // The EncodeT-sized encoded vectors
+ Tensor<EncodeT, 2, true> encodedVecs,
+ // The set of addresses for each of the lists
+ void** listData) {
+ // FIXME: some issue with getLaneId() and CUDA 10.1 and P4 GPUs?
+ auto laneId = threadIdx.x % kWarpSize;
+ auto warpId = threadIdx.x / kWarpSize;
+ auto warpsPerBlock = blockDim.x / kWarpSize;
+
+ // Each block is dedicated to a separate list
+ idx_t listId = uniqueLists[blockIdx.x];
+
+ // The vecs we add to the list are at indices [vBUL[vecIdStart],
+ // vBUL[vecIdEnd])
+ idx_t vecIdStart = uniqueListVectorStart[blockIdx.x];
+ // uLVS is explicitly terminated for us with one more than the number of
+ // blocks that we have
+ idx_t vecIdEnd = uniqueListVectorStart[blockIdx.x + 1];
+
+ // How many vectors we are adding to this list
+ auto numVecsAdding = vecIdEnd - vecIdStart;
+
+ // The first vector we are updating within the list
+ auto listVecStart = uniqueListStartOffset[blockIdx.x];
+
+ // These are the actual vec IDs that we are adding (in vecs)
+ auto listVecIds = vectorsByUniqueList[vecIdStart].data();
+
+ // All data is written by groups of kWarpSize vectors (to mirror the warp).
+ // listVecStart could be in the middle of this, or even, for sub-byte
+ // encodings, mean that the first vector piece of data that we need to
+ // update is in the high part of a byte.
+ //
+ // WarpPackedBits allows writing of arbitrary bit packed data in groups of
+ // kWarpSize, but we ensure that it only operates on the group of kWarpSize
+ // vectors. In order to do this we need to actually start updating vectors
+ // at the next lower multiple of kWarpSize from listVecStart.
+ auto alignedListVecStart = utils::roundDown(listVecStart, kWarpSize);
+
+ // Each block of kWarpSize vectors fully encodes into this many bytes
+ constexpr int bytesPerVectorBlockDim = EncodeBits * kWarpSize / 8;
+ constexpr int wordsPerVectorBlockDim =
+ bytesPerVectorBlockDim / sizeof(EncodeT);
+ auto wordsPerVectorBlock = wordsPerVectorBlockDim * encodedVecs.getSize(1);
+
+ EncodeT* listStart = ((EncodeT*)listData[listId]);
+
+ // Each warp within the block handles a different chunk of kWarpSize
+ auto warpVec = alignedListVecStart +
+ (faiss::gpu::Tensor<long, 1, true>::DataType)warpId * kWarpSize;
+
+ // The warp data starts here
+ EncodeT* warpData = listStart + (warpVec / kWarpSize) * wordsPerVectorBlock;
+
+ // Each warp encodes a single block
+ for (; warpVec < listVecStart + numVecsAdding;
+ // but block stride
+ warpVec += blockDim.x,
+ // the new warp data base strides by how many vector blocks we are
+ // encoding, which is one per warp
+ warpData += warpsPerBlock * wordsPerVectorBlock) {
+ // This lane is adding this vec (if it is within bounds)
+ auto laneVec = warpVec + laneId;
+
+ // Which vector does this correspond to in the set of vectors that we
+ // need to add? If this is < 0, then this particular thread is not
+ // encoding / appending a new vector
+ auto laneVecAdding = laneVec - listVecStart;
+
+ // We are actually adding a new vector if this is within range
+ bool valid = laneVecAdding >= 0 && laneVecAdding < numVecsAdding;
+
+ // Now, which actual vector in vecs is this?
+ auto vecId = valid ? listVecIds[laneVecAdding] : 0;
+
+ // Each warp that has some vector data available needs to write out the
+ // vector components
+ EncodeT* data = warpData;
+
+ for (int dim = 0; dim < encodedVecs.getSize(1); ++dim) {
+ EncodeT enc = valid ? encodedVecs[vecId][dim] : (EncodeT)0;
+ WarpPackedBits<EncodeT, EncodeBits>::write(
+ laneId, enc, valid, data);
+
+ data += wordsPerVectorBlockDim;
+ }
+ }
+}
+
+void runIVFFlatInterleavedAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<float, 2, true>& vecs,
+ GpuScalarQuantizer* scalarQ,
+ DeviceVector<void*>& listData,
+ GpuResources* res,
+ cudaStream_t stream) {
+ auto dim = vecs.getSize(1);
+
+#define RUN_APPEND(ENCODE_T, ENCODE_BITS, DATA) \
+ do { \
+ dim3 grid(uniqueLists.getSize(0)); \
+ dim3 block(128); \
+ ivfInterleavedAppend<ENCODE_T, ENCODE_BITS> \
+ <<<grid, block, 0, stream>>>( \
+ uniqueLists, \
+ uniqueListVectorStart, \
+ vectorsByUniqueList, \
+ uniqueListStartOffset, \
+ DATA, \
+ listData.data()); \
+ } while (0)
+
+ if (!scalarQ) {
+ // No encoding is needed, we just append directly
+ RUN_APPEND(float, 32, vecs);
+ return;
+ }
+
+ // only implemented at the moment
+ FAISS_ASSERT(scalarQ->bits == 16 || scalarQ->bits <= 8);
+
+ if (scalarQ->bits == 16) {
+ FAISS_ASSERT(scalarQ->qtype == ScalarQuantizer::QuantizerType::QT_fp16);
+
+ using CodecT = Codec<ScalarQuantizer::QuantizerType::QT_fp16, 1>;
+ CodecT codec(scalarQ->qtype);
+
+ DeviceTensor<half, 2, true> encodedVecs(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), vecs.getSize(1)});
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+
+ } else if (scalarQ->bits <= 8) {
+ DeviceTensor<uint8_t, 2, true> encodedVecs(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), vecs.getSize(1)});
+
+ switch (scalarQ->qtype) {
+ case ScalarQuantizer::QuantizerType::QT_8bit: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit, 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_uniform: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_uniform,
+ 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_direct: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_direct,
+ 1>;
+ CodecT codec(scalarQ->code_size);
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_6bit: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_6bit, 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit, 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit_uniform: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit_uniform,
+ 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+
+ runSQEncode(vecs, encodedVecs, codec, stream);
+ RUN_APPEND(CodecT::EncodeT, CodecT::kEncodeBits, encodedVecs);
+ } break;
+ default:
+ // unimplemented, should be handled at a higher level
+ FAISS_ASSERT(false);
+ }
+ }
+
+#undef RUN_APPEND
+ CUDA_TEST_ERROR();
+}
+
+void runIVFPQInterleavedAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ int bitsPerCode,
+ Tensor<uint8_t, 2, true>& encodings,
+ DeviceVector<void*>& listCodes,
+ cudaStream_t stream) {
+ // limitation for now
+ FAISS_ASSERT(bitsPerCode <= 8);
+
+#define RUN_APPEND(ENCODE_T, ENCODE_BITS) \
+ do { \
+ dim3 grid(uniqueLists.getSize(0)); \
+ dim3 block(128); \
+ \
+ ivfInterleavedAppend<ENCODE_T, ENCODE_BITS> \
+ <<<grid, block, 0, stream>>>( \
+ uniqueLists, \
+ uniqueListVectorStart, \
+ vectorsByUniqueList, \
+ uniqueListStartOffset, \
+ encodings, \
+ listCodes.data()); \
+ } while (0)
+
+ switch (bitsPerCode) {
+ case 4: {
+ RUN_APPEND(uint8_t, 4);
+ break;
+ }
+ case 5: {
+ RUN_APPEND(uint8_t, 5);
+ break;
+ }
+ case 6: {
+ RUN_APPEND(uint8_t, 6);
+ break;
+ }
+ case 8: {
+ RUN_APPEND(uint8_t, 8);
+ break;
+ }
+ default:
+ // unhandled
+ FAISS_ASSERT(false);
+ break;
+ }
+
+#undef RUN_APPEND
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFAppend.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFAppend.cuh
new file mode 100644
index 0000000..330957f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFAppend.cuh
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+/// Append user indices to IVF lists
+void runIVFIndicesAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<idx_t, 1, true>& indices,
+ IndicesOptions opt,
+ DeviceVector<void*>& listIndices,
+ cudaStream_t stream);
+
+/// Update device-side list pointers in a batch
+void runUpdateListPointers(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& newListLength,
+ Tensor<void*, 1, true>& newCodePointers,
+ Tensor<void*, 1, true>& newIndexPointers,
+ DeviceVector<idx_t>& listLengths,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ cudaStream_t stream);
+
+/// Append PQ codes to IVF lists (non-interleaved format)
+void runIVFPQAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<uint8_t, 2, true>& encodings,
+ DeviceVector<void*>& listCodes,
+ cudaStream_t stream);
+
+/// Append PQ codes to IVF lists (interleaved format)
+void runIVFPQInterleavedAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ int bitsPerCode,
+ Tensor<uint8_t, 2, true>& encodings,
+ DeviceVector<void*>& listCodes,
+ cudaStream_t stream);
+
+/// Append SQ codes to IVF lists (non-interleaved, old format)
+void runIVFFlatAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<float, 2, true>& vecs,
+ GpuScalarQuantizer* scalarQ,
+ DeviceVector<void*>& listData,
+ cudaStream_t stream);
+
+/// Append SQ codes to IVF lists (interleaved)
+void runIVFFlatInterleavedAppend(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<float, 2, true>& vecs,
+ GpuScalarQuantizer* scalarQ,
+ DeviceVector<void*>& listData,
+ GpuResources* res,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFBase.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFBase.cu
new file mode 100644
index 0000000..4023aac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFBase.cu
@@ -0,0 +1,837 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/RemapIndices.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/invlists/InvertedLists.h>
+#include <thrust/host_vector.h>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/impl/IVFAppend.cuh>
+#include <faiss/gpu/impl/IVFBase.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/ThrustUtils.cuh>
+#include <limits>
+#include <unordered_map>
+
+namespace faiss {
+namespace gpu {
+
+IVFBase::DeviceIVFList::DeviceIVFList(GpuResources* res, const AllocInfo& info)
+ : data(res, info), numVecs(0) {}
+
+IVFBase::IVFBase(
+ GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space)
+ : resources_(resources),
+ metric_(metric),
+ metricArg_(metricArg),
+ dim_(dim),
+ numLists_(nlist),
+ useResidual_(useResidual),
+ interleavedLayout_(interleavedLayout),
+ indicesOptions_(indicesOptions),
+ space_(space),
+ deviceListDataPointers_(
+ resources,
+ AllocInfo(
+ AllocType::IVFLists,
+ getCurrentDevice(),
+ space,
+ resources->getDefaultStreamCurrentDevice())),
+ deviceListIndexPointers_(
+ resources,
+ AllocInfo(
+ AllocType::IVFLists,
+ getCurrentDevice(),
+ space,
+ resources->getDefaultStreamCurrentDevice())),
+ deviceListLengths_(
+ resources,
+ AllocInfo(
+ AllocType::IVFLists,
+ getCurrentDevice(),
+ space,
+ resources->getDefaultStreamCurrentDevice())),
+ maxListLength_(0) {
+ reset();
+}
+
+IVFBase::~IVFBase() {}
+
+void IVFBase::reserveMemory(idx_t numVecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ auto vecsPerList = numVecs / deviceListData_.size();
+ if (vecsPerList < 1) {
+ return;
+ }
+
+ auto bytesPerDataList = getGpuVectorsEncodingSize_(vecsPerList);
+
+ for (auto& list : deviceListData_) {
+ list->data.reserve(bytesPerDataList, stream);
+ }
+
+ if ((indicesOptions_ == INDICES_32_BIT) ||
+ (indicesOptions_ == INDICES_64_BIT)) {
+ // Reserve for index lists as well
+ size_t bytesPerIndexList = vecsPerList *
+ (indicesOptions_ == INDICES_32_BIT ? sizeof(int)
+ : sizeof(idx_t));
+
+ for (auto& list : deviceListIndices_) {
+ list->data.reserve(bytesPerIndexList, stream);
+ }
+ }
+
+ // Update device info for all lists, since the base pointers may
+ // have changed
+ updateDeviceListInfo_(stream);
+}
+
+void IVFBase::reset() {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ deviceListData_.clear();
+ deviceListIndices_.clear();
+ deviceListDataPointers_.clear();
+ deviceListIndexPointers_.clear();
+ deviceListLengths_.clear();
+ listOffsetToUserIndex_.clear();
+
+ auto info =
+ AllocInfo(AllocType::IVFLists, getCurrentDevice(), space_, stream);
+
+ for (idx_t i = 0; i < numLists_; ++i) {
+ deviceListData_.emplace_back(std::unique_ptr<DeviceIVFList>(
+ new DeviceIVFList(resources_, info)));
+
+ deviceListIndices_.emplace_back(std::unique_ptr<DeviceIVFList>(
+ new DeviceIVFList(resources_, info)));
+
+ listOffsetToUserIndex_.emplace_back(std::vector<idx_t>());
+ }
+
+ deviceListDataPointers_.resize(numLists_, stream);
+ deviceListDataPointers_.setAll(nullptr, stream);
+
+ deviceListIndexPointers_.resize(numLists_, stream);
+ deviceListIndexPointers_.setAll(nullptr, stream);
+
+ deviceListLengths_.resize(numLists_, stream);
+ deviceListLengths_.setAll(0, stream);
+
+ maxListLength_ = 0;
+}
+
+idx_t IVFBase::getDim() const {
+ return dim_;
+}
+
+size_t IVFBase::reclaimMemory() {
+ // Reclaim all unused memory exactly
+ return reclaimMemory_(true);
+}
+
+size_t IVFBase::reclaimMemory_(bool exact) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ size_t totalReclaimed = 0;
+
+ for (idx_t i = 0; i < deviceListData_.size(); ++i) {
+ auto& data = deviceListData_[i]->data;
+ totalReclaimed += data.reclaim(exact, stream);
+
+ deviceListDataPointers_.setAt(i, (void*)data.data(), stream);
+ }
+
+ for (idx_t i = 0; i < deviceListIndices_.size(); ++i) {
+ auto& indices = deviceListIndices_[i]->data;
+ totalReclaimed += indices.reclaim(exact, stream);
+
+ deviceListIndexPointers_.setAt(i, (void*)indices.data(), stream);
+ }
+
+ // Update device info for all lists, since the base pointers may
+ // have changed
+ updateDeviceListInfo_(stream);
+
+ return totalReclaimed;
+}
+
+void IVFBase::updateDeviceListInfo_(cudaStream_t stream) {
+ std::vector<idx_t> listIds(deviceListData_.size());
+ for (idx_t i = 0; i < deviceListData_.size(); ++i) {
+ listIds[i] = i;
+ }
+
+ updateDeviceListInfo_(listIds, stream);
+}
+
+void IVFBase::updateDeviceListInfo_(
+ const std::vector<idx_t>& listIds,
+ cudaStream_t stream) {
+ idx_t listSize = listIds.size();
+ HostTensor<idx_t, 1, true> hostListsToUpdate({listSize});
+ HostTensor<idx_t, 1, true> hostNewListLength({listSize});
+ HostTensor<void*, 1, true> hostNewDataPointers({listSize});
+ HostTensor<void*, 1, true> hostNewIndexPointers({listSize});
+
+ for (idx_t i = 0; i < listSize; ++i) {
+ auto listId = listIds[i];
+ auto& data = deviceListData_[listId];
+ auto& indices = deviceListIndices_[listId];
+
+ hostListsToUpdate[i] = listId;
+ hostNewListLength[i] = data->numVecs;
+ hostNewDataPointers[i] = data->data.data();
+ hostNewIndexPointers[i] = indices->data.data();
+ }
+
+ // Copy the above update sets to the GPU
+ DeviceTensor<idx_t, 1, true> listsToUpdate(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ hostListsToUpdate);
+ DeviceTensor<idx_t, 1, true> newListLength(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ hostNewListLength);
+ DeviceTensor<void*, 1, true> newDataPointers(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ hostNewDataPointers);
+ DeviceTensor<void*, 1, true> newIndexPointers(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ hostNewIndexPointers);
+
+ // Update all pointers to the lists on the device that may have
+ // changed
+ runUpdateListPointers(
+ listsToUpdate,
+ newListLength,
+ newDataPointers,
+ newIndexPointers,
+ deviceListLengths_,
+ deviceListDataPointers_,
+ deviceListIndexPointers_,
+ stream);
+}
+
+idx_t IVFBase::getNumLists() const {
+ return numLists_;
+}
+
+idx_t IVFBase::getListLength(idx_t listId) const {
+ FAISS_THROW_IF_NOT_FMT(
+ listId < numLists_,
+ "IVF list %ld is out of bounds (%ld lists total)",
+ listId,
+ numLists_);
+ FAISS_ASSERT(listId < deviceListLengths_.size());
+ FAISS_ASSERT(listId < deviceListData_.size());
+
+ return deviceListData_[listId]->numVecs;
+}
+
+std::vector<idx_t> IVFBase::getListIndices(idx_t listId) const {
+ FAISS_THROW_IF_NOT_FMT(
+ listId < numLists_,
+ "IVF list %ld is out of bounds (%ld lists total)",
+ listId,
+ numLists_);
+ FAISS_ASSERT(listId < deviceListData_.size());
+ FAISS_ASSERT(listId < deviceListLengths_.size());
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ if (indicesOptions_ == INDICES_32_BIT) {
+ // The data is stored as int32 on the GPU
+ FAISS_ASSERT(listId < deviceListIndices_.size());
+
+ auto intInd = deviceListIndices_[listId]->data.copyToHost<int>(stream);
+
+ std::vector<idx_t> out(intInd.size());
+ for (size_t i = 0; i < intInd.size(); ++i) {
+ out[i] = (idx_t)intInd[i];
+ }
+
+ return out;
+ } else if (indicesOptions_ == INDICES_64_BIT) {
+ // The data is stored as int64 on the GPU
+ FAISS_ASSERT(listId < deviceListIndices_.size());
+
+ return deviceListIndices_[listId]->data.copyToHost<idx_t>(stream);
+ } else if (indicesOptions_ == INDICES_CPU) {
+ // The data is not stored on the GPU
+ FAISS_ASSERT(listId < listOffsetToUserIndex_.size());
+
+ auto& userIds = listOffsetToUserIndex_[listId];
+
+ // We should have the same number of indices on the CPU as we do vectors
+ // encoded on the GPU
+ FAISS_ASSERT(userIds.size() == deviceListData_[listId]->numVecs);
+
+ // this will return a copy
+ return userIds;
+ } else {
+ // unhandled indices type (includes INDICES_IVF)
+ FAISS_ASSERT(false);
+ return std::vector<idx_t>();
+ }
+}
+
+std::vector<uint8_t> IVFBase::getListVectorData(idx_t listId, bool gpuFormat)
+ const {
+ FAISS_THROW_IF_NOT_FMT(
+ listId < numLists_,
+ "IVF list %ld is out of bounds (%ld lists total)",
+ listId,
+ numLists_);
+ FAISS_ASSERT(listId < deviceListData_.size());
+ FAISS_ASSERT(listId < deviceListLengths_.size());
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ auto& list = deviceListData_[listId];
+ auto gpuCodes = list->data.copyToHost<uint8_t>(stream);
+
+ if (gpuFormat) {
+ return gpuCodes;
+ } else {
+ // The GPU layout may be different than the CPU layout (e.g., vectors
+ // rather than dimensions interleaved), translate back if necessary
+ return translateCodesFromGpu_(std::move(gpuCodes), list->numVecs);
+ }
+}
+
+void IVFBase::copyInvertedListsFrom(const InvertedLists* ivf) {
+ idx_t nlist = ivf ? ivf->nlist : 0;
+ for (idx_t i = 0; i < nlist; ++i) {
+ addEncodedVectorsToList_(
+ i, ivf->get_codes(i), ivf->get_ids(i), ivf->list_size(i));
+ }
+}
+
+void IVFBase::copyInvertedListsTo(InvertedLists* ivf) {
+ for (idx_t i = 0; i < numLists_; ++i) {
+ auto listIndices = getListIndices(i);
+ auto listData = getListVectorData(i, false);
+
+ ivf->add_entries(
+ i, listIndices.size(), listIndices.data(), listData.data());
+ }
+}
+
+void IVFBase::reconstruct_n(idx_t i0, idx_t n, float* out) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void IVFBase::addEncodedVectorsToList_(
+ idx_t listId,
+ const void* codes,
+ const idx_t* indices,
+ idx_t numVecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // This list must already exist
+ FAISS_ASSERT(listId < deviceListData_.size());
+
+ // This list must currently be empty
+ auto& listCodes = deviceListData_[listId];
+ FAISS_ASSERT(listCodes->data.size() == 0);
+ FAISS_ASSERT(listCodes->numVecs == 0);
+
+ // If there's nothing to add, then there's nothing we have to do
+ if (numVecs == 0) {
+ return;
+ }
+
+ // The GPU might have a different layout of the memory
+ auto gpuListSizeInBytes = getGpuVectorsEncodingSize_(numVecs);
+ auto cpuListSizeInBytes = getCpuVectorsEncodingSize_(numVecs);
+
+ // Translate the codes as needed to our preferred form
+ std::vector<uint8_t> codesV(cpuListSizeInBytes);
+ std::memcpy(codesV.data(), codes, cpuListSizeInBytes);
+ auto translatedCodes = translateCodesToGpu_(std::move(codesV), numVecs);
+
+ listCodes->data.append(
+ translatedCodes.data(),
+ gpuListSizeInBytes,
+ stream,
+ true /* exact reserved size */);
+ listCodes->numVecs = numVecs;
+
+ // Handle the indices as well
+ addIndicesFromCpu_(listId, indices, numVecs);
+
+ deviceListDataPointers_.setAt(
+ listId, (void*)listCodes->data.data(), stream);
+ deviceListLengths_.setAt(listId, numVecs, stream);
+
+ // We update this as well, since the multi-pass algorithm uses it
+ maxListLength_ = std::max(maxListLength_, numVecs);
+}
+
+void IVFBase::addIndicesFromCpu_(
+ idx_t listId,
+ const idx_t* indices,
+ idx_t numVecs) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // This list must currently be empty
+ auto& listIndices = deviceListIndices_[listId];
+ FAISS_ASSERT(listIndices->data.size() == 0);
+ FAISS_ASSERT(listIndices->numVecs == 0);
+
+ if (indicesOptions_ == INDICES_32_BIT) {
+ // Make sure that all indices are in bounds
+ std::vector<int> indices32(numVecs);
+ for (idx_t i = 0; i < numVecs; ++i) {
+ auto ind = indices[i];
+ FAISS_ASSERT(ind <= (idx_t)std::numeric_limits<int>::max());
+ indices32[i] = (int)ind;
+ }
+
+ static_assert(sizeof(int) == 4, "");
+
+ listIndices->data.append(
+ (uint8_t*)indices32.data(),
+ numVecs * sizeof(int),
+ stream,
+ true /* exact reserved size */);
+
+ // We have added the given indices to the raw data vector; update the
+ // count as well
+ listIndices->numVecs = numVecs;
+ } else if (indicesOptions_ == INDICES_64_BIT) {
+ listIndices->data.append(
+ (uint8_t*)indices,
+ numVecs * sizeof(idx_t),
+ stream,
+ true /* exact reserved size */);
+
+ // We have added the given indices to the raw data vector; update the
+ // count as well
+ listIndices->numVecs = numVecs;
+ } else if (indicesOptions_ == INDICES_CPU) {
+ // indices are stored on the CPU
+ FAISS_ASSERT(listId < listOffsetToUserIndex_.size());
+
+ auto& userIndices = listOffsetToUserIndex_[listId];
+ userIndices.insert(userIndices.begin(), indices, indices + numVecs);
+ } else {
+ // indices are not stored
+ FAISS_ASSERT(indicesOptions_ == INDICES_IVF);
+ }
+
+ deviceListIndexPointers_.setAt(
+ listId, (void*)listIndices->data.data(), stream);
+}
+
+void IVFBase::updateQuantizer(Index* quantizer) {
+ FAISS_THROW_IF_NOT(quantizer->is_trained);
+
+ // Must match our basic IVF parameters
+ FAISS_THROW_IF_NOT(quantizer->d == getDim());
+ FAISS_THROW_IF_NOT(quantizer->ntotal == getNumLists());
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // If the index instance is a GpuIndexFlat, then we can use direct access to
+ // the centroids within.
+ auto gpuQ = dynamic_cast<GpuIndexFlat*>(quantizer);
+ if (gpuQ) {
+ auto gpuData = gpuQ->getGpuData();
+
+ if (gpuData->getUseFloat16()) {
+ // The FlatIndex keeps its data in float16; we need to reconstruct
+ // as float32 and store locally
+ DeviceTensor<float, 2, true> centroids(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {getNumLists(), getDim()});
+
+ gpuData->reconstruct(0, gpuData->getSize(), centroids);
+
+ ivfCentroids_ = std::move(centroids);
+ } else {
+ // The FlatIndex keeps its data in float32, so we can merely
+ // reference it
+ auto ref32 = gpuData->getVectorsFloat32Ref();
+
+ // Create a DeviceTensor that merely references, doesn't own the
+ // data
+ auto refOnly = DeviceTensor<float, 2, true>(
+ ref32.data(), {ref32.getSize(0), ref32.getSize(1)});
+
+ ivfCentroids_ = std::move(refOnly);
+ }
+ } else {
+ // Otherwise, we need to reconstruct all vectors from the index and copy
+ // them to the GPU, in order to have access as needed for residual
+ // computation
+ auto vecs = std::vector<float>(getNumLists() * getDim());
+ quantizer->reconstruct_n(0, quantizer->ntotal, vecs.data());
+
+ // Copy to a new DeviceTensor; this will own the data
+ DeviceTensor<float, 2, true> centroids(
+ resources_,
+ makeSpaceAlloc(AllocType::FlatData, space_, stream),
+ {quantizer->ntotal, quantizer->d});
+ centroids.copyFrom(vecs, stream);
+
+ ivfCentroids_ = std::move(centroids);
+ }
+}
+
+void IVFBase::searchCoarseQuantizer_(
+ Index* coarseQuantizer,
+ int nprobe,
+ // Guaranteed to be on device
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& distances,
+ Tensor<idx_t, 2, true>& indices,
+ Tensor<float, 3, true>* residuals,
+ Tensor<float, 3, true>* centroids) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // The provided IVF quantizer may be CPU or GPU resident.
+ // If GPU resident, we can simply call it passing the above output device
+ // pointers.
+ auto gpuQuantizer = tryCastGpuIndex(coarseQuantizer);
+ if (gpuQuantizer) {
+ // We can pass device pointers directly
+ gpuQuantizer->search(
+ vecs.getSize(0),
+ vecs.data(),
+ nprobe,
+ distances.data(),
+ indices.data());
+
+ if (residuals) {
+ gpuQuantizer->compute_residual_n(
+ vecs.getSize(0) * nprobe,
+ vecs.data(),
+ residuals->data(),
+ indices.data());
+ }
+
+ if (centroids) {
+ gpuQuantizer->reconstruct_batch(
+ vecs.getSize(0) * nprobe,
+ indices.data(),
+ centroids->data());
+ }
+ } else {
+ // temporary host storage for querying a CPU index
+ auto cpuVecs = toHost<float, 2>(
+ vecs.data(), stream, {vecs.getSize(0), vecs.getSize(1)});
+ auto cpuDistances = std::vector<float>(vecs.getSize(0) * nprobe);
+ auto cpuIndices = std::vector<idx_t>(vecs.getSize(0) * nprobe);
+
+ coarseQuantizer->search(
+ vecs.getSize(0),
+ cpuVecs.data(),
+ nprobe,
+ cpuDistances.data(),
+ cpuIndices.data());
+
+ distances.copyFrom(cpuDistances, stream);
+
+ // Did we also want to return IVF cell residuals for the query vectors?
+ if (residuals) {
+ // we need space for the residuals as well
+ auto cpuResiduals =
+ std::vector<float>(vecs.getSize(0) * nprobe * dim_);
+
+ coarseQuantizer->compute_residual_n(
+ vecs.getSize(0) * nprobe,
+ cpuVecs.data(),
+ cpuResiduals.data(),
+ cpuIndices.data());
+
+ residuals->copyFrom(cpuResiduals, stream);
+ }
+
+ // Did we also want to return the IVF cell centroids themselves?
+ if (centroids) {
+ auto cpuCentroids =
+ std::vector<float>(vecs.getSize(0) * nprobe * dim_);
+
+ coarseQuantizer->reconstruct_batch(
+ vecs.getSize(0) * nprobe,
+ cpuIndices.data(),
+ cpuCentroids.data());
+
+ centroids->copyFrom(cpuCentroids, stream);
+ }
+
+ indices.copyFrom(cpuIndices, stream);
+ }
+}
+
+idx_t IVFBase::addVectors(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices) {
+ FAISS_ASSERT(vecs.getSize(0) == indices.getSize(0));
+ FAISS_ASSERT(vecs.getSize(1) == dim_);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // Determine which IVF lists we need to append to
+ // We report distances from the shared query function, but we don't need
+ // them
+ DeviceTensor<float, 2, true> unusedIVFDistances(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), 1});
+
+ // We do need the closest IVF cell IDs though
+ DeviceTensor<idx_t, 2, true> ivfIndices(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), 1});
+
+ // Calculate residuals for these vectors, if needed
+ DeviceTensor<float, 3, true> residuals(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), 1, dim_});
+
+ searchCoarseQuantizer_(
+ coarseQuantizer,
+ 1, // nprobe
+ vecs,
+ unusedIVFDistances,
+ ivfIndices,
+ useResidual_ ? &residuals : nullptr,
+ nullptr);
+
+ // Copy the lists that we wish to append to back to the CPU
+ // FIXME: really this can be into pinned memory and a true async
+ // copy on a different stream; we can start the copy early, but it's
+ // tiny
+ auto ivfIndicesHost = ivfIndices.copyToVector(stream);
+
+ // Now we add the encoded vectors to the individual lists
+ // First, make sure that there is space available for adding the new
+ // encoded vectors and indices
+
+ // list id -> vectors being added
+ std::unordered_map<idx_t, std::vector<idx_t>> listToVectorIds;
+
+ // vector id -> which list it is being appended to
+ std::vector<idx_t> vectorIdToList(vecs.getSize(0));
+
+ // vector id -> offset in list
+ // (we already have vector id -> list id in listIds)
+ std::vector<idx_t> listOffsetHost(ivfIndicesHost.size());
+
+ // Number of valid vectors that we actually add; we return this
+ idx_t numAdded = 0;
+
+ for (idx_t i = 0; i < ivfIndicesHost.size(); ++i) {
+ auto listId = ivfIndicesHost[i];
+
+ // Add vector could be invalid (contains NaNs etc)
+ if (listId < 0) {
+ listOffsetHost[i] = -1;
+ vectorIdToList[i] = -1;
+ continue;
+ }
+
+ FAISS_ASSERT(listId < numLists_);
+ ++numAdded;
+ vectorIdToList[i] = listId;
+
+ auto offset = deviceListData_[listId]->numVecs;
+
+ auto it = listToVectorIds.find(listId);
+ if (it != listToVectorIds.end()) {
+ offset += it->second.size();
+ it->second.push_back(i);
+ } else {
+ listToVectorIds[listId] = std::vector<idx_t>{i};
+ }
+
+ listOffsetHost[i] = offset;
+ }
+
+ // If we didn't add anything (all invalid vectors that didn't map to IVF
+ // clusters), no need to continue
+ if (numAdded == 0) {
+ return 0;
+ }
+
+ // unique lists being added to
+ std::vector<idx_t> uniqueLists;
+
+ for (auto& vecs : listToVectorIds) {
+ uniqueLists.push_back(vecs.first);
+ }
+
+ std::sort(uniqueLists.begin(), uniqueLists.end());
+
+ // In the same order as uniqueLists, list the vectors being added to that
+ // list contiguously (unique list 0 vectors ...)(unique list 1 vectors ...)
+ // ...
+ std::vector<idx_t> vectorsByUniqueList;
+
+ // For each of the unique lists, the start offset in vectorsByUniqueList
+ std::vector<idx_t> uniqueListVectorStart;
+
+ // For each of the unique lists, where we start appending in that list by
+ // the vector offset
+ std::vector<idx_t> uniqueListStartOffset;
+
+ // For each of the unique lists, find the vectors which should be appended
+ // to that list
+ for (auto ul : uniqueLists) {
+ uniqueListVectorStart.push_back(vectorsByUniqueList.size());
+
+ FAISS_ASSERT(listToVectorIds.count(ul) != 0);
+
+ // The vectors we are adding to this list
+ auto& vecs = listToVectorIds[ul];
+ vectorsByUniqueList.insert(
+ vectorsByUniqueList.end(), vecs.begin(), vecs.end());
+
+ // How many vectors we previously had (which is where we start appending
+ // on the device)
+ uniqueListStartOffset.push_back(deviceListData_[ul]->numVecs);
+ }
+
+ // We terminate uniqueListVectorStart with the overall number of vectors
+ // being added, which could be different than vecs.getSize(0) as some
+ // vectors could be invalid
+ uniqueListVectorStart.push_back(vectorsByUniqueList.size());
+
+ // We need to resize the data structures for the inverted lists on
+ // the GPUs, which means that they might need reallocation, which
+ // means that their base address may change. Figure out the new base
+ // addresses, and update those in a batch on the device
+ {
+ // Resize all of the lists that we are appending to
+ for (auto& counts : listToVectorIds) {
+ auto listId = counts.first;
+ idx_t numVecsToAdd = counts.second.size();
+
+ auto& codes = deviceListData_[listId];
+ auto oldNumVecs = codes->numVecs;
+ auto newNumVecs = codes->numVecs + numVecsToAdd;
+
+ auto newSizeBytes = getGpuVectorsEncodingSize_(newNumVecs);
+ codes->data.resize(newSizeBytes, stream);
+ codes->numVecs = newNumVecs;
+
+ auto& indices = deviceListIndices_[listId];
+ if ((indicesOptions_ == INDICES_32_BIT) ||
+ (indicesOptions_ == INDICES_64_BIT)) {
+ size_t indexSize = (indicesOptions_ == INDICES_32_BIT)
+ ? sizeof(int)
+ : sizeof(idx_t);
+
+ indices->data.resize(
+ indices->data.size() + numVecsToAdd * indexSize,
+ stream);
+ FAISS_ASSERT(indices->numVecs == oldNumVecs);
+ indices->numVecs = newNumVecs;
+
+ } else if (indicesOptions_ == INDICES_CPU) {
+ // indices are stored on the CPU side
+ FAISS_ASSERT(listId < listOffsetToUserIndex_.size());
+
+ auto& userIndices = listOffsetToUserIndex_[listId];
+ userIndices.resize(newNumVecs);
+ } else {
+ // indices are not stored on the GPU or CPU side
+ FAISS_ASSERT(indicesOptions_ == INDICES_IVF);
+ }
+
+ // This is used by the multi-pass query to decide how much scratch
+ // space to allocate for intermediate results
+ maxListLength_ = std::max(maxListLength_, newNumVecs);
+ }
+
+ // Update all pointers and sizes on the device for lists that we
+ // appended to
+ updateDeviceListInfo_(uniqueLists, stream);
+ }
+
+ // If we're maintaining the indices on the CPU side, update our
+ // map. We already resized our map above.
+ if (indicesOptions_ == INDICES_CPU) {
+ // We need to maintain the indices on the CPU side
+ HostTensor<idx_t, 1, true> hostIndices(indices, stream);
+
+ for (idx_t i = 0; i < hostIndices.getSize(0); ++i) {
+ idx_t listId = ivfIndicesHost[i];
+
+ // Add vector could be invalid (contains NaNs etc)
+ if (listId < 0) {
+ continue;
+ }
+
+ auto offset = listOffsetHost[i];
+ FAISS_ASSERT(offset >= 0);
+
+ FAISS_ASSERT(listId < listOffsetToUserIndex_.size());
+ auto& userIndices = listOffsetToUserIndex_[listId];
+
+ FAISS_ASSERT(offset < userIndices.size());
+ userIndices[offset] = hostIndices[i];
+ }
+ }
+
+ // Copy the offsets to the GPU
+ auto ivfIndices1dDevice = ivfIndices.downcastOuter<1>();
+ auto residuals2dDevice = residuals.downcastOuter<2>();
+ auto listOffsetDevice =
+ toDeviceTemporary(resources_, listOffsetHost, stream);
+ auto uniqueListsDevice = toDeviceTemporary(resources_, uniqueLists, stream);
+ auto vectorsByUniqueListDevice =
+ toDeviceTemporary(resources_, vectorsByUniqueList, stream);
+ auto uniqueListVectorStartDevice =
+ toDeviceTemporary(resources_, uniqueListVectorStart, stream);
+ auto uniqueListStartOffsetDevice =
+ toDeviceTemporary(resources_, uniqueListStartOffset, stream);
+
+ // Actually encode and append the vectors
+ appendVectors_(
+ vecs,
+ residuals2dDevice,
+ indices,
+ uniqueListsDevice,
+ vectorsByUniqueListDevice,
+ uniqueListVectorStartDevice,
+ uniqueListStartOffsetDevice,
+ ivfIndices1dDevice,
+ listOffsetDevice,
+ stream);
+
+ // We added this number
+ return numAdded;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFBase.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFBase.cuh
new file mode 100644
index 0000000..965c655
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFBase.cuh
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <memory>
+#include <vector>
+
+namespace faiss {
+struct InvertedLists;
+}
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+class FlatIndex;
+
+/// Base inverted list functionality for IVFFlat and IVFPQ
+class IVFBase {
+ public:
+ IVFBase(GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool interleavedLayout,
+ bool useResidual,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ virtual ~IVFBase();
+
+ /// Reserve GPU memory in our inverted lists for this number of vectors
+ virtual void reserveMemory(idx_t numVecs);
+
+ /// Clear out all inverted lists, but retain the coarse quantizer
+ /// and the product quantizer info
+ virtual void reset();
+
+ /// Return the number of dimensions we are indexing
+ idx_t getDim() const;
+
+ /// After adding vectors, one can call this to reclaim device memory
+ /// to exactly the amount needed. Returns space reclaimed in bytes
+ virtual size_t reclaimMemory();
+
+ /// Returns the number of inverted lists
+ idx_t getNumLists() const;
+
+ /// For debugging purposes, return the list length of a particular
+ /// list
+ virtual idx_t getListLength(idx_t listId) const;
+
+ /// Return the list indices of a particular list back to the CPU
+ virtual std::vector<idx_t> getListIndices(idx_t listId) const;
+
+ /// Return the encoded vectors of a particular list back to the CPU
+ virtual std::vector<uint8_t> getListVectorData(idx_t listId, bool gpuFormat)
+ const;
+
+ /// Copy all inverted lists from a CPU representation to ourselves
+ virtual void copyInvertedListsFrom(const InvertedLists* ivf);
+
+ /// Copy all inverted lists from ourselves to a CPU representation
+ virtual void copyInvertedListsTo(InvertedLists* ivf);
+
+ /// Update our coarse quantizer with this quantizer instance; may be a CPU
+ /// or GPU quantizer
+ virtual void updateQuantizer(Index* quantizer);
+
+ /// Classify and encode/add vectors to our IVF lists.
+ /// The input data must be on our current device.
+ /// Returns the number of vectors successfully added. Vectors may
+ /// not be able to be added because they contain NaNs.
+ virtual idx_t addVectors(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices);
+
+ /// Find the approximate k nearest neigbors for `queries` against
+ /// our database
+ virtual void search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) = 0;
+
+ /// Performs search when we are already given the IVF cells to look at
+ /// (GpuIndexIVF::search_preassigned implementation)
+ virtual void searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) = 0;
+
+ /* It is used to reconstruct a given number of vectors in an Inverted File
+ * (IVF) index
+ * @param i0 index of the first vector to reconstruct
+ * @param n number of vectors to reconstruct
+ * @param out This is a pointer to a buffer where the reconstructed
+ * vectors will be stored.
+ */
+ virtual void reconstruct_n(idx_t i0, idx_t n, float* out);
+
+ protected:
+ /// Adds a set of codes and indices to a list, with the
+ /// representation coming from the CPU equivalent
+ virtual void addEncodedVectorsToList_(
+ idx_t listId,
+ // resident on the host
+ const void* codes,
+ // resident on the host
+ const idx_t* indices,
+ idx_t numVecs);
+
+ /// Performs search in a CPU or GPU coarse quantizer for IVF cells,
+ /// returning residuals as well if necessary
+ void searchCoarseQuantizer_(
+ Index* coarseQuantizer,
+ int nprobe,
+ // guaranteed resident on device
+ Tensor<float, 2, true>& vecs,
+ // Output: the distances to the closest nprobe IVF cell centroids
+ // for the query vectors
+ // size (#vecs, nprobe)
+ Tensor<float, 2, true>& distances,
+ // Output: the closest nprobe IVF cells the query vectors lie in
+ // size (#vecs, nprobe)
+ Tensor<idx_t, 2, true>& indices,
+ // optionally compute the residual relative to the IVF cell centroid
+ // if passed
+ // size (#vecs, nprobe, dim)
+ Tensor<float, 3, true>* residuals,
+ // optionally return the IVF cell centroids to which the input
+ // vectors were assigned
+ // size (#vecs, nprobe, dim)
+ Tensor<float, 3, true>* centroids);
+
+ /// Returns the number of bytes in which an IVF list containing numVecs
+ /// vectors is encoded on the device. Note that due to padding this is not
+ /// the same as the encoding size for a subset of vectors in an IVF list;
+ /// this is the size for an entire IVF list
+ virtual size_t getGpuVectorsEncodingSize_(idx_t numVecs) const = 0;
+ virtual size_t getCpuVectorsEncodingSize_(idx_t numVecs) const = 0;
+
+ /// Translate to our preferred GPU encoding
+ virtual std::vector<uint8_t> translateCodesToGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const = 0;
+
+ /// Translate from our preferred GPU encoding
+ virtual std::vector<uint8_t> translateCodesFromGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const = 0;
+
+ /// Append vectors to our on-device lists
+ virtual void appendVectors_(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfCentroidResiduals,
+ Tensor<idx_t, 1, true>& indices,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ cudaStream_t stream) = 0;
+
+ /// Reclaim memory consumed on the device for our inverted lists
+ /// `exact` means we trim exactly to the memory needed
+ size_t reclaimMemory_(bool exact);
+
+ /// Update all device-side list pointer and size information
+ void updateDeviceListInfo_(cudaStream_t stream);
+
+ /// For a set of list IDs, update device-side list pointer and size
+ /// information
+ void updateDeviceListInfo_(
+ const std::vector<idx_t>& listIds,
+ cudaStream_t stream);
+
+ /// Shared function to copy indices from CPU to GPU
+ void addIndicesFromCpu_(idx_t listId, const idx_t* indices, idx_t numVecs);
+
+ protected:
+ /// Collection of GPU resources that we use
+ GpuResources* resources_;
+
+ /// Metric type of the index
+ faiss::MetricType metric_;
+
+ /// Metric arg
+ float metricArg_;
+
+ /// Expected dimensionality of the vectors
+ const int dim_;
+
+ /// Number of inverted lists we maintain
+ const idx_t numLists_;
+
+ /// Do we need to also compute residuals when processing vectors?
+ bool useResidual_;
+
+ /// Coarse quantizer centroids available on GPU
+ DeviceTensor<float, 2, true> ivfCentroids_;
+
+ /// Whether or not our index uses an interleaved by kWarpSize layout:
+ /// The default memory layout is [vector][PQ/SQ component]:
+ /// (v0 d0) (v0 d1) ... (v0 dD-1) (v1 d0) (v1 d1) ...
+ ///
+ /// The interleaved by kWarpSize memory layout is:
+ /// [vector / kWarpSize][PQ/SQ component][vector % kWarpSize] with padding:
+ /// (v0 d0) (v1 d0) ... (v31 d0) (v0 d1) (v1 d1) ... (v31 dD-1) (v32 d0)
+ /// (v33 d0) ... so the list length is always a multiple of num quantizers *
+ /// kWarpSize
+ bool interleavedLayout_;
+
+ /// How are user indices stored on the GPU?
+ const IndicesOptions indicesOptions_;
+
+ /// What memory space our inverted list storage is in
+ const MemorySpace space_;
+
+ /// Device representation of all inverted list data
+ /// id -> data
+ DeviceVector<void*> deviceListDataPointers_;
+
+ /// Device representation of all inverted list index pointers
+ /// id -> data
+ DeviceVector<void*> deviceListIndexPointers_;
+
+ /// Device representation of all inverted list lengths
+ /// id -> length in number of vectors
+ DeviceVector<idx_t> deviceListLengths_;
+
+ /// Maximum list length seen
+ idx_t maxListLength_;
+
+ struct DeviceIVFList {
+ DeviceIVFList(GpuResources* res, const AllocInfo& info);
+
+ /// The on-device memory for this particular IVF list
+ DeviceVector<uint8_t> data;
+
+ /// The number of vectors encoded in this list, which may be unrelated
+ /// to the above allocated data size
+ idx_t numVecs;
+ };
+
+ /// Device memory for each separate list, as managed by the host.
+ /// Device memory as stored in DeviceVector is stored as unique_ptr
+ /// since deviceList*Pointers_ must remain valid despite
+ /// resizing (and potential re-allocation) of deviceList*_
+ std::vector<std::unique_ptr<DeviceIVFList>> deviceListData_;
+ std::vector<std::unique_ptr<DeviceIVFList>> deviceListIndices_;
+
+ /// If we are storing indices on the CPU (indicesOptions_ is
+ /// INDICES_CPU), then this maintains a CPU-side map of what
+ /// (inverted list id, offset) maps to which user index
+ std::vector<std::vector<idx_t>> listOffsetToUserIndex_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlat.cu
new file mode 100644
index 0000000..b6a8a3f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlat.cu
@@ -0,0 +1,405 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/InterleavedCodes.h>
+#include <faiss/gpu/impl/RemapIndices.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <thrust/host_vector.h>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/impl/IVFAppend.cuh>
+#include <faiss/gpu/impl/IVFFlat.cuh>
+#include <faiss/gpu/impl/IVFFlatScan.cuh>
+#include <faiss/gpu/impl/IVFInterleaved.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+#include <limits>
+#include <unordered_map>
+
+namespace faiss {
+namespace gpu {
+
+IVFFlat::IVFFlat(
+ GpuResources* res,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ faiss::ScalarQuantizer* scalarQ,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space)
+ : IVFBase(res,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ useResidual,
+ interleavedLayout,
+ indicesOptions,
+ space),
+ scalarQ_(scalarQ ? new GpuScalarQuantizer(res, *scalarQ) : nullptr) {}
+
+IVFFlat::~IVFFlat() {}
+
+size_t IVFFlat::getGpuVectorsEncodingSize_(idx_t numVecs) const {
+ if (interleavedLayout_) {
+ // bits per scalar code
+ idx_t bits = scalarQ_ ? scalarQ_->bits : 32 /* float */;
+
+ int warpSize = getWarpSizeCurrentDevice();
+
+ // bytes to encode a block of warpSize vectors (single dimension)
+ idx_t bytesPerDimBlock = bits * warpSize / 8;
+
+ // bytes to fully encode warpSize vectors
+ idx_t bytesPerBlock = bytesPerDimBlock * dim_;
+
+ // number of blocks of warpSize vectors we have
+ idx_t numBlocks = utils::divUp(numVecs, warpSize);
+
+ // total size to encode numVecs
+ return bytesPerBlock * numBlocks;
+ } else {
+ size_t sizePerVector =
+ (scalarQ_ ? scalarQ_->code_size : sizeof(float) * dim_);
+
+ return (size_t)numVecs * sizePerVector;
+ }
+}
+
+size_t IVFFlat::getCpuVectorsEncodingSize_(idx_t numVecs) const {
+ size_t sizePerVector =
+ (scalarQ_ ? scalarQ_->code_size : sizeof(float) * dim_);
+
+ return (size_t)numVecs * sizePerVector;
+}
+
+std::vector<uint8_t> IVFFlat::translateCodesToGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const {
+ if (!interleavedLayout_) {
+ // same format
+ return codes;
+ }
+
+ int bitsPerCode = scalarQ_ ? scalarQ_->bits : 32;
+
+ auto up =
+ unpackNonInterleaved(std::move(codes), numVecs, dim_, bitsPerCode);
+ return packInterleaved(std::move(up), numVecs, dim_, bitsPerCode);
+}
+
+std::vector<uint8_t> IVFFlat::translateCodesFromGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const {
+ if (!interleavedLayout_) {
+ // same format
+ return codes;
+ }
+
+ int bitsPerCode = scalarQ_ ? scalarQ_->bits : 32;
+
+ auto up = unpackInterleaved(std::move(codes), numVecs, dim_, bitsPerCode);
+ return packNonInterleaved(std::move(up), numVecs, dim_, bitsPerCode);
+}
+
+void IVFFlat::appendVectors_(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfCentroidResiduals,
+ Tensor<idx_t, 1, true>& indices,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ cudaStream_t stream) {
+ //
+ // Append the new encodings
+ //
+
+ // Append indices to the IVF lists
+ runIVFIndicesAppend(
+ listIds,
+ listOffset,
+ indices,
+ indicesOptions_,
+ deviceListIndexPointers_,
+ stream);
+
+ // Append the encoded vectors to the IVF lists
+ if (interleavedLayout_) {
+ runIVFFlatInterleavedAppend(
+ listIds,
+ listOffset,
+ uniqueLists,
+ vectorsByUniqueList,
+ uniqueListVectorStart,
+ uniqueListStartOffset,
+ useResidual_ ? ivfCentroidResiduals : vecs,
+ scalarQ_.get(),
+ deviceListDataPointers_,
+ resources_,
+ stream);
+ } else {
+ runIVFFlatAppend(
+ listIds,
+ listOffset,
+ useResidual_ ? ivfCentroidResiduals : vecs,
+ scalarQ_.get(),
+ deviceListDataPointers_,
+ stream);
+ }
+}
+
+void IVFFlat::search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // These are caught at a higher level
+ FAISS_ASSERT(nprobe <= GPU_MAX_SELECTION_K);
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+ nprobe = int(std::min(idx_t(nprobe), getNumLists()));
+
+ FAISS_ASSERT(queries.getSize(1) == dim_);
+
+ FAISS_ASSERT(outDistances.getSize(0) == queries.getSize(0));
+ FAISS_ASSERT(outIndices.getSize(0) == queries.getSize(0));
+
+ // Reserve space for the quantized information
+ DeviceTensor<float, 2, true> coarseDistances(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), nprobe});
+ DeviceTensor<idx_t, 2, true> coarseIndices(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), nprobe});
+ // in case we also want/need residuals, we need the original centroids as
+ // well
+ // FIXME: why centroids instead of calculating residuals in one go?
+ DeviceTensor<float, 3, true> residualBase(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), nprobe, dim_});
+
+ searchCoarseQuantizer_(
+ coarseQuantizer,
+ nprobe,
+ queries,
+ coarseDistances,
+ coarseIndices,
+ nullptr,
+ // we need the IVF centroids to which vectors were assigned if
+ // vectors are encoded using the residual
+ useResidual_ ? &residualBase : nullptr);
+
+ searchImpl_(
+ queries,
+ coarseDistances,
+ coarseIndices,
+ residualBase,
+ k,
+ outDistances,
+ outIndices,
+ false);
+}
+
+void IVFFlat::searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) {
+ FAISS_ASSERT(ivfDistances.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(ivfAssignments.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(outDistances.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(outIndices.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(vecs.getSize(1) == dim_);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+ auto nprobe = ivfAssignments.getSize(1);
+ FAISS_ASSERT(nprobe <= numLists_);
+
+ // Based on the IVF assignments, we need the IVF centroids to which vectors
+ // were assigned
+ // FIXME: IVFPQ doesn't need this information as it has direct reference to
+ // all IVF centroids and within the various kernels can look it up by index
+ // as needed. Can we convert IVFFlat to do the same thing?
+ DeviceTensor<float, 3, true> ivfCentroids(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), nprobe, dim_});
+
+ auto gpuQuantizer = tryCastGpuIndex(coarseQuantizer);
+ if (gpuQuantizer) {
+ // We can pass device pointers directly
+ gpuQuantizer->reconstruct_batch(
+ vecs.getSize(0) * nprobe,
+ ivfAssignments.data(),
+ ivfCentroids.data());
+ } else {
+ // CPU coarse quantizer
+ auto cpuIVFCentroids =
+ std::vector<float>(vecs.getSize(0) * nprobe * dim_);
+
+ // We need to copy `ivfAssignments` to the CPU, in order to pass to a
+ // CPU index
+ auto cpuIVFAssignments = ivfAssignments.copyToVector(stream);
+
+ coarseQuantizer->reconstruct_batch(
+ vecs.getSize(0) * nprobe,
+ cpuIVFAssignments.data(),
+ cpuIVFCentroids.data());
+
+ ivfCentroids.copyFrom(cpuIVFCentroids, stream);
+ }
+
+ searchImpl_(
+ vecs,
+ ivfDistances,
+ ivfAssignments,
+ ivfCentroids,
+ k,
+ outDistances,
+ outIndices,
+ storePairs);
+}
+
+void IVFFlat::reconstruct_n(idx_t i0, idx_t ni, float* out) {
+ if (ni == 0) {
+ // nothing to do
+ return;
+ }
+
+ int warpSize = getWarpSizeCurrentDevice();
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ for (idx_t list_no = 0; list_no < numLists_; list_no++) {
+ size_t list_size = deviceListData_[list_no]->numVecs;
+
+ auto idlist = getListIndices(list_no);
+
+ for (idx_t offset = 0; offset < list_size; offset++) {
+ idx_t id = idlist[offset];
+ if (!(id >= i0 && id < i0 + ni)) {
+ continue;
+ }
+
+ // vector data in the non-interleaved format is laid out like:
+ // v0d0 v0d1 ... v0d(dim-1) v1d0 v1d1 ... v1d(dim-1)
+
+ // vector data in the interleaved format is laid out like:
+ // (v0d0 v1d0 ... v31d0) (v0d1 v1d1 ... v31d1)
+ // (v0d(dim - 1) ... v31d(dim-1))
+ // (v32d0 v33d0 ... v63d0) (... v63d(dim-1)) (v64d0 ...)
+
+ // where vectors are chunked into groups of 32, and each dimension
+ // for each of the 32 vectors is contiguous
+
+ auto vectorChunk = offset / warpSize;
+ auto vectorWithinChunk = offset % warpSize;
+
+ auto listDataPtr = (float*)deviceListData_[list_no]->data.data();
+ listDataPtr += vectorChunk * warpSize * dim_ + vectorWithinChunk;
+
+ for (int d = 0; d < dim_; ++d) {
+ fromDevice<float>(
+ listDataPtr + warpSize * d,
+ out + (id - i0) * dim_ + d,
+ 1,
+ stream);
+ }
+ }
+ }
+}
+
+void IVFFlat::searchImpl_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ Tensor<float, 3, true>& ivfCentroids,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) {
+ FAISS_ASSERT(storePairs == false);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ if (interleavedLayout_) {
+ runIVFInterleavedScan(
+ queries,
+ coarseIndices,
+ deviceListDataPointers_,
+ deviceListIndexPointers_,
+ indicesOptions_,
+ deviceListLengths_,
+ k,
+ metric_,
+ useResidual_,
+ ivfCentroids,
+ scalarQ_.get(),
+ outDistances,
+ outIndices,
+ resources_);
+ } else {
+ runIVFFlatScan(
+ queries,
+ coarseIndices,
+ deviceListDataPointers_,
+ deviceListIndexPointers_,
+ indicesOptions_,
+ deviceListLengths_,
+ maxListLength_,
+ k,
+ metric_,
+ useResidual_,
+ ivfCentroids,
+ scalarQ_.get(),
+ outDistances,
+ outIndices,
+ resources_);
+ }
+
+ // If the GPU isn't storing indices (they are on the CPU side), we
+ // need to perform the re-mapping here
+ // FIXME: we might ultimately be calling this function with inputs
+ // from the CPU, these are unnecessary copies
+ if (indicesOptions_ == INDICES_CPU) {
+ HostTensor<idx_t, 2, true> hostOutIndices(outIndices, stream);
+
+ ivfOffsetToUserIndex(
+ hostOutIndices.data(),
+ numLists_,
+ hostOutIndices.getSize(0),
+ hostOutIndices.getSize(1),
+ listOffsetToUserIndex_);
+
+ // Copy back to GPU, since the input to this function is on the
+ // GPU
+ outIndices.copyFrom(hostOutIndices, stream);
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlat.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlat.cuh
new file mode 100644
index 0000000..cd592cd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlat.cuh
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/impl/IVFBase.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class IVFFlat : public IVFBase {
+ public:
+ IVFFlat(GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ bool useResidual,
+ /// Optional ScalarQuantizer
+ faiss::ScalarQuantizer* scalarQ,
+ bool interleavedLayout,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ ~IVFFlat() override;
+
+ /// Find the approximate k nearest neigbors for `queries` against
+ /// our database
+ void search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) override;
+
+ /// Performs search when we are already given the IVF cells to look at
+ /// (GpuIndexIVF::search_preassigned implementation)
+ void searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) override;
+
+ void reconstruct_n(idx_t i0, idx_t n, float* out) override;
+
+ protected:
+ /// Returns the number of bytes in which an IVF list containing numVecs
+ /// vectors is encoded on the device. Note that due to padding this is not
+ /// the same as the encoding size for a subset of vectors in an IVF list;
+ /// this is the size for an entire IVF list
+ size_t getGpuVectorsEncodingSize_(idx_t numVecs) const override;
+ size_t getCpuVectorsEncodingSize_(idx_t numVecs) const override;
+
+ /// Translate to our preferred GPU encoding
+ virtual std::vector<uint8_t> translateCodesToGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const override;
+
+ /// Translate from our preferred GPU encoding
+ virtual std::vector<uint8_t> translateCodesFromGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const override;
+
+ /// Encode the vectors that we're adding and append to our IVF lists
+ virtual void appendVectors_(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfCentroidResiduals,
+ Tensor<idx_t, 1, true>& indices,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ cudaStream_t stream) override;
+
+ /// Shared IVF search implementation, used by both search and
+ /// searchPreassigned
+ virtual void searchImpl_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ Tensor<float, 3, true>& ivfCentroids,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs);
+
+ protected:
+ /// Scalar quantizer for encoded vectors, if any
+ std::unique_ptr<GpuScalarQuantizer> scalarQ_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlatScan.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlatScan.cu
new file mode 100644
index 0000000..5c6307b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlatScan.cu
@@ -0,0 +1,494 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/DistanceUtils.cuh>
+#include <faiss/gpu/impl/IVFFlatScan.cuh>
+#include <faiss/gpu/impl/IVFUtils.cuh>
+#include <faiss/gpu/utils/Comparators.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/Reductions.cuh>
+
+#include <algorithm>
+
+namespace faiss {
+namespace gpu {
+
+namespace {
+
+/// Sort direction per each metric
+inline bool metricToSortDirection(MetricType mt) {
+ switch (mt) {
+ case MetricType::METRIC_INNER_PRODUCT:
+ // highest
+ return true;
+ case MetricType::METRIC_L2:
+ // lowest
+ return false;
+ default:
+ // unhandled metric
+ FAISS_ASSERT(false);
+ return false;
+ }
+}
+
+} // namespace
+
+// Number of warps we create per block of IVFFlatScan
+constexpr int kIVFFlatScanWarps = 4;
+
+// Works for any dimension size
+template <typename Codec, typename Metric>
+struct IVFFlatScan {
+ static __device__ void scan(
+ float* query,
+ bool useResidual,
+ float* residualBaseSlice,
+ void* vecData,
+ const Codec& codec,
+ const Metric& metric,
+ idx_t numVecs,
+ int dim,
+ float* distanceOut) {
+ // How many separate loading points are there for the decoder?
+ int limit = utils::divDown(dim, Codec::kDimPerIter);
+
+ // Each warp handles a separate chunk of vectors
+ auto warpId = threadIdx.x / kWarpSize;
+ // FIXME: why does getLaneId() not work when we write out below!?!?!
+ auto laneId = threadIdx.x % kWarpSize; // getLaneId();
+
+ // Divide the set of vectors among the warps
+ idx_t vecsPerWarp = utils::divUp(numVecs, kIVFFlatScanWarps);
+
+ idx_t vecStart = vecsPerWarp * warpId;
+ idx_t vecEnd = min(vecsPerWarp * (warpId + 1), numVecs);
+
+ // Walk the list of vectors for this warp
+ for (idx_t vec = vecStart; vec < vecEnd; ++vec) {
+ Metric dist = metric.zero();
+
+ // Scan the dimensions available that have whole units for the
+ // decoder, as the decoder may handle more than one dimension at
+ // once (leaving the remainder to be handled separately)
+ for (int d = laneId; d < limit; d += kWarpSize) {
+ int realDim = d * Codec::kDimPerIter;
+ float vecVal[Codec::kDimPerIter];
+
+ // Decode the kDimPerIter dimensions
+ codec.decode(vecData, vec, d, vecVal);
+
+#pragma unroll
+ for (int j = 0; j < Codec::kDimPerIter; ++j) {
+ vecVal[j] +=
+ useResidual ? residualBaseSlice[realDim + j] : 0.0f;
+ }
+
+#pragma unroll
+ for (int j = 0; j < Codec::kDimPerIter; ++j) {
+ dist.handle(query[realDim + j], vecVal[j]);
+ }
+ }
+
+ // Handle remainder by a single thread, if any
+ // Not needed if we decode 1 dim per time
+ if (Codec::kDimPerIter > 1) {
+ int realDim = limit * Codec::kDimPerIter;
+
+ // Was there any remainder?
+ if (realDim < dim) {
+ // Let the first threads in the block sequentially perform
+ // it
+ int remainderDim = realDim + laneId;
+
+ if (remainderDim < dim) {
+ float vecVal = codec.decodePartial(
+ vecData, vec, limit, laneId);
+ vecVal += useResidual ? residualBaseSlice[remainderDim]
+ : 0.0f;
+ dist.handle(query[remainderDim], vecVal);
+ }
+ }
+ }
+
+ // Reduce distance within warp
+ auto warpDist = warpReduceAllSum(dist.reduce());
+
+ if (laneId == 0) {
+ distanceOut[vec] = warpDist;
+ }
+ }
+ }
+};
+
+template <typename Codec, typename Metric>
+__global__ void ivfFlatScan(
+ Tensor<float, 2, true> queries,
+ bool useResidual,
+ Tensor<float, 3, true> residualBase,
+ Tensor<idx_t, 2, true> listIds,
+ void** allListData,
+ idx_t* listLengths,
+ Codec codec,
+ Metric metric,
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<float, 1, true> distance) {
+ extern __shared__ float smem[];
+
+ auto queryId = blockIdx.y;
+ auto probeId = blockIdx.x;
+
+ // This is where we start writing out data
+ // We ensure that before the array (at offset -1), there is a 0 value
+ auto outBase = *(prefixSumOffsets[queryId][probeId].data() - 1);
+
+ idx_t listId = listIds[queryId][probeId];
+ // Safety guard in case NaNs in input cause no list ID to be generated
+ if (listId == -1) {
+ return;
+ }
+
+ auto query = queries[queryId].data();
+ auto vecs = allListData[listId];
+ auto numVecs = listLengths[listId];
+ auto dim = queries.getSize(1);
+ auto distanceOut = distance[outBase].data();
+
+ auto residualBaseSlice = residualBase[queryId][probeId].data();
+
+ codec.initKernel(smem, dim);
+ __syncthreads();
+
+ IVFFlatScan<Codec, Metric>::scan(
+ query,
+ useResidual,
+ residualBaseSlice,
+ vecs,
+ codec,
+ metric,
+ numVecs,
+ dim,
+ distanceOut);
+}
+
+void runIVFFlatScanTile(
+ GpuResources* res,
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ Tensor<char, 1, true>& thrustMem,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<float, 1, true>& allDistances,
+ Tensor<float, 3, true>& heapDistances,
+ Tensor<idx_t, 3, true>& heapIndices,
+ int k,
+ bool use64BitSelection,
+ faiss::MetricType metricType,
+ bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ cudaStream_t stream) {
+ auto dim = queries.getSize(1);
+
+ // Calculate offset lengths, so we know where to write out
+ // intermediate results
+ runCalcListOffsets(
+ res, listIds, listLengths, prefixSumOffsets, thrustMem, stream);
+
+ int warpSize = getWarpSizeCurrentDevice();
+ auto grid = dim3(listIds.getSize(1), listIds.getSize(0));
+ auto block = dim3(warpSize * kIVFFlatScanWarps);
+
+#define RUN_IVF_FLAT \
+ do { \
+ ivfFlatScan<<<grid, block, codec.getSmemSize(dim), stream>>>( \
+ queries, \
+ useResidual, \
+ residualBase, \
+ listIds, \
+ listData.data(), \
+ listLengths.data(), \
+ codec, \
+ metric, \
+ prefixSumOffsets, \
+ allDistances); \
+ } while (0)
+
+#define HANDLE_METRICS \
+ do { \
+ if (metricType == MetricType::METRIC_L2) { \
+ L2Distance metric; \
+ RUN_IVF_FLAT; \
+ } else { \
+ IPDistance metric; \
+ RUN_IVF_FLAT; \
+ } \
+ } while (0)
+
+ if (!scalarQ) {
+ CodecFloat codec(dim * sizeof(float));
+ HANDLE_METRICS;
+ } else {
+ switch (scalarQ->qtype) {
+ case ScalarQuantizer::QuantizerType::QT_8bit: {
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit, 1> codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ HANDLE_METRICS;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_uniform: {
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_uniform, 1> codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+ HANDLE_METRICS;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_fp16: {
+ Codec<ScalarQuantizer::QuantizerType::QT_fp16, 1> codec(
+ scalarQ->code_size);
+ HANDLE_METRICS;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_direct: {
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_direct, 1> codec(
+ scalarQ->code_size);
+ HANDLE_METRICS;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit: {
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit, 1> codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ HANDLE_METRICS;
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit_uniform: {
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit_uniform, 1> codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+ HANDLE_METRICS;
+ } break;
+ default:
+ // unimplemented, should be handled at a higher level
+ FAISS_ASSERT(false);
+ }
+ }
+
+ CUDA_TEST_ERROR();
+
+#undef HANDLE_METRICS
+#undef RUN_IVF_FLAT
+
+ // k-select the output in chunks, to increase parallelism
+ runPass1SelectLists(
+ prefixSumOffsets,
+ allDistances,
+ listIds.getSize(1),
+ k,
+ use64BitSelection,
+ metricToSortDirection(metricType),
+ heapDistances,
+ heapIndices,
+ stream);
+
+ // k-select final output
+ auto flatHeapDistances = heapDistances.downcastInner<2>();
+ auto flatHeapIndices = heapIndices.downcastInner<2>();
+
+ runPass2SelectLists(
+ flatHeapDistances,
+ flatHeapIndices,
+ listIndices,
+ indicesOptions,
+ prefixSumOffsets,
+ listIds,
+ k,
+ use64BitSelection,
+ metricToSortDirection(metricType),
+ outDistances,
+ outIndices,
+ stream);
+}
+
+void runIVFFlatScan(
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ idx_t maxListLength,
+ int k,
+ faiss::MetricType metric,
+ bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ auto nprobe = listIds.getSize(1);
+
+ // If the maximum list length (in terms of number of vectors) times nprobe
+ // (number of lists) is > 2^31 - 1, then we will use 64-bit indexing in the
+ // selection kernels
+ bool use64BitSelection =
+ maxListLength * nprobe > idx_t(std::numeric_limits<int32_t>::max());
+
+ // Make a reservation for Thrust to do its dirty work (global memory
+ // cross-block reduction space); hopefully this is large enough.
+ constexpr idx_t kThrustMemSize = 16384;
+
+ DeviceTensor<char, 1, true> thrustMem1(
+ res, makeTempAlloc(AllocType::Other, stream), {kThrustMemSize});
+ DeviceTensor<char, 1, true> thrustMem2(
+ res, makeTempAlloc(AllocType::Other, stream), {kThrustMemSize});
+ DeviceTensor<char, 1, true>* thrustMem[2] = {&thrustMem1, &thrustMem2};
+
+ // How much temporary memory would we need to handle a single query?
+ size_t sizePerQuery = getIVFPerQueryTempMemory(k, nprobe, maxListLength);
+
+ // How many queries do we wish to run at once?
+ idx_t queryTileSize = getIVFQueryTileSize(
+ queries.getSize(0),
+ res->getTempMemoryAvailableCurrentDevice(),
+ sizePerQuery);
+
+ // Temporary memory buffers
+ // Make sure there is space prior to the start which will be 0, and
+ // will handle the boundary condition without branches
+ DeviceTensor<idx_t, 1, true> prefixSumOffsetSpace1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe + 1});
+ DeviceTensor<idx_t, 1, true> prefixSumOffsetSpace2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe + 1});
+
+ DeviceTensor<idx_t, 2, true> prefixSumOffsets1(
+ prefixSumOffsetSpace1[1].data(), {queryTileSize, nprobe});
+ DeviceTensor<idx_t, 2, true> prefixSumOffsets2(
+ prefixSumOffsetSpace2[1].data(), {queryTileSize, nprobe});
+ DeviceTensor<idx_t, 2, true>* prefixSumOffsets[2] = {
+ &prefixSumOffsets1, &prefixSumOffsets2};
+
+ // Make sure the element before prefixSumOffsets is 0, since we
+ // depend upon simple, boundary-less indexing to get proper results
+ CUDA_VERIFY(cudaMemsetAsync(
+ prefixSumOffsetSpace1.data(), 0, sizeof(idx_t), stream));
+ CUDA_VERIFY(cudaMemsetAsync(
+ prefixSumOffsetSpace2.data(), 0, sizeof(idx_t), stream));
+
+ DeviceTensor<float, 1, true> allDistances1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe * maxListLength});
+ DeviceTensor<float, 1, true> allDistances2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe * maxListLength});
+ DeviceTensor<float, 1, true>* allDistances[2] = {
+ &allDistances1, &allDistances2};
+
+ idx_t pass2Chunks = getIVFKSelectionPass2Chunks(nprobe);
+ DeviceTensor<float, 3, true> heapDistances1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<float, 3, true> heapDistances2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<float, 3, true>* heapDistances[2] = {
+ &heapDistances1, &heapDistances2};
+
+ DeviceTensor<idx_t, 3, true> heapIndices1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<idx_t, 3, true> heapIndices2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<idx_t, 3, true>* heapIndices[2] = {
+ &heapIndices1, &heapIndices2};
+
+ auto streams = res->getAlternateStreamsCurrentDevice();
+ streamWait(streams, {stream});
+
+ int curStream = 0;
+
+ for (idx_t query = 0; query < queries.getSize(0); query += queryTileSize) {
+ auto numQueriesInTile =
+ std::min(queryTileSize, queries.getSize(0) - query);
+
+ auto prefixSumOffsetsView =
+ prefixSumOffsets[curStream]->narrowOutermost(
+ 0, numQueriesInTile);
+
+ auto listIdsView = listIds.narrowOutermost(query, numQueriesInTile);
+ auto queryView = queries.narrowOutermost(query, numQueriesInTile);
+ auto residualBaseView =
+ residualBase.narrowOutermost(query, numQueriesInTile);
+
+ auto heapDistancesView =
+ heapDistances[curStream]->narrowOutermost(0, numQueriesInTile);
+ auto heapIndicesView =
+ heapIndices[curStream]->narrowOutermost(0, numQueriesInTile);
+
+ auto outDistanceView =
+ outDistances.narrowOutermost(query, numQueriesInTile);
+ auto outIndicesView =
+ outIndices.narrowOutermost(query, numQueriesInTile);
+
+ runIVFFlatScanTile(
+ res,
+ queryView,
+ listIdsView,
+ listData,
+ listIndices,
+ indicesOptions,
+ listLengths,
+ *thrustMem[curStream],
+ prefixSumOffsetsView,
+ *allDistances[curStream],
+ heapDistancesView,
+ heapIndicesView,
+ k,
+ use64BitSelection,
+ metric,
+ useResidual,
+ residualBaseView,
+ scalarQ,
+ outDistanceView,
+ outIndicesView,
+ streams[curStream]);
+
+ curStream = (curStream + 1) % 2;
+ }
+
+ streamWait({stream}, streams);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlatScan.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlatScan.cuh
new file mode 100644
index 0000000..c00c4b4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFFlatScan.cuh
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+void runIVFFlatScan(
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ idx_t maxListLength,
+ int k,
+ faiss::MetricType metric,
+ bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFInterleaved.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFInterleaved.cu
new file mode 100644
index 0000000..fc99a49
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFInterleaved.cu
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/IVFInterleaved.cuh>
+#include <faiss/gpu/impl/scan/IVFInterleavedImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+constexpr uint32_t kMaxUInt32 = std::numeric_limits<uint32_t>::max();
+
+// Second-pass kernel to further k-select the results from the first pass across
+// IVF lists and produce the final results
+template <int ThreadsPerBlock, int NumWarpQ, int NumThreadQ>
+__global__ void ivfInterleavedScan2(
+ Tensor<float, 3, true> distanceIn,
+ Tensor<idx_t, 3, true> indicesIn,
+ Tensor<idx_t, 2, true> listIds,
+ int k,
+ void** listIndices,
+ IndicesOptions opt,
+ bool dir,
+ Tensor<float, 2, true> distanceOut,
+ Tensor<idx_t, 2, true> indicesOut) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ auto queryId = blockIdx.x;
+
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __shared__ float smemK[kNumWarps * NumWarpQ];
+ // The BlockSelect value type is uint32_t, as we pack together which
+ // probe (up to nprobe - 1) and which k (up to k - 1) from each
+ // individual list together, and both nprobe and k are limited to
+ // GPU_MAX_SELECTION_K.
+ __shared__ uint32_t smemV[kNumWarps * NumWarpQ];
+
+ // To avoid creating excessive specializations, we combine direction
+ // kernels, selecting for the smallest element. If `dir` is true, we
+ // negate all values being selected (so that we are selecting the
+ // largest element).
+ BlockSelect<
+ float,
+ uint32_t,
+ false,
+ Comparator<float>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(kFloatMax, kMaxUInt32, smemK, smemV, k);
+
+ // nprobe x k
+ idx_t num = distanceIn.getSize(1) * distanceIn.getSize(2);
+
+ const float* distanceBase = distanceIn[queryId].data();
+ idx_t limit = utils::roundDown(num, kWarpSize);
+
+ // This will keep our negation factor
+ float adj = dir ? -1 : 1;
+
+ idx_t i = threadIdx.x;
+ for (; i < limit; i += blockDim.x) {
+ // We represent the index as (probe id)(k)
+ // Right now, both are limited to a maximum of 2048, but we will
+ // dedicate each to the high and low words of a uint32_t
+ static_assert(GPU_MAX_SELECTION_K <= 65536, "");
+
+ uint32_t curProbe = i / k;
+ uint32_t curK = i % k;
+ // Since nprobe and k are limited, we can pack both of these
+ // together into a uint32_t
+ uint32_t index = (curProbe << 16) | (curK & (uint32_t)0xffff);
+
+ // The IDs reported from the list may be -1, if a particular IVF
+ // list doesn't even have k entries in it
+ if (listIds[queryId][curProbe] != -1) {
+ // Adjust the value we are selecting based on the sorting order
+ heap.addThreadQ(distanceBase[i] * adj, index);
+ }
+
+ heap.checkThreadQ();
+ }
+
+ // Handle warp divergence separately
+ if (i < num) {
+ uint32_t curProbe = i / k;
+ uint32_t curK = i % k;
+ uint32_t index = (curProbe << 16) | (curK & (uint32_t)0xffff);
+
+ idx_t listId = listIds[queryId][curProbe];
+ if (listId != -1) {
+ heap.addThreadQ(distanceBase[i] * adj, index);
+ }
+ }
+
+ // Merge all final results
+ heap.reduce();
+
+ for (auto i = threadIdx.x; i < k; i += blockDim.x) {
+ // Re-adjust the value we are selecting based on the sorting order
+ distanceOut[queryId][i] = smemK[i] * adj;
+ auto packedIndex = smemV[i];
+
+ // We need to remap to the user-provided indices
+ idx_t index = -1;
+
+ // We may not have at least k values to return; in this function,
+ // max uint32 is our sentinel value
+ if (packedIndex != kMaxUInt32) {
+ uint32_t curProbe = packedIndex >> 16;
+ uint32_t curK = packedIndex & 0xffff;
+
+ idx_t listId = listIds[queryId][curProbe];
+ idx_t listOffset = indicesIn[queryId][curProbe][curK];
+
+ if (opt == INDICES_32_BIT) {
+ index = (idx_t)((int*)listIndices[listId])[listOffset];
+ } else if (opt == INDICES_64_BIT) {
+ index = ((idx_t*)listIndices[listId])[listOffset];
+ } else {
+ index = (listId << 32 | (idx_t)listOffset);
+ }
+ }
+
+ indicesOut[queryId][i] = index;
+ }
+ }
+}
+
+void runIVFInterleavedScan2(
+ Tensor<float, 3, true>& distanceIn,
+ Tensor<idx_t, 3, true>& indicesIn,
+ Tensor<idx_t, 2, true>& listIds,
+ int k,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ bool dir,
+ Tensor<float, 2, true>& distanceOut,
+ Tensor<idx_t, 2, true>& indicesOut,
+ cudaStream_t stream) {
+#define IVF_SCAN_2(THREADS, NUM_WARP_Q, NUM_THREAD_Q) \
+ ivfInterleavedScan2<THREADS, NUM_WARP_Q, NUM_THREAD_Q> \
+ <<<distanceIn.getSize(0), THREADS, 0, stream>>>( \
+ distanceIn, \
+ indicesIn, \
+ listIds, \
+ k, \
+ listIndices.data(), \
+ indicesOptions, \
+ dir, \
+ distanceOut, \
+ indicesOut)
+
+ if (k == 1) {
+ IVF_SCAN_2(128, 1, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ IVF_SCAN_2(128, 32, 2);
+ } else if (k <= 64) {
+ IVF_SCAN_2(128, 64, 3);
+ } else if (k <= 128) {
+ IVF_SCAN_2(128, 128, 3);
+ } else if (k <= 256) {
+ IVF_SCAN_2(128, 256, 4);
+ } else if (k <= 512) {
+ IVF_SCAN_2(128, 512, 8);
+ } else if (k <= 1024) {
+ IVF_SCAN_2(128, 1024, 8);
+ }
+#if GPU_MAX_SELECTION_K >= 2048
+ else if (k <= 2048) {
+ IVF_SCAN_2(64, 2048, 8);
+ }
+#endif
+}
+
+void runIVFInterleavedScan(
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ int k,
+ faiss::MetricType metric,
+ bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ // caught for exceptions at a higher level
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ const auto ivf_interleaved_call = [&](const auto func) {
+ func(queries,
+ listIds,
+ listData,
+ listIndices,
+ indicesOptions,
+ listLengths,
+ k,
+ metric,
+ useResidual,
+ residualBase,
+ scalarQ,
+ outDistances,
+ outIndices,
+ res);
+ };
+
+ if (k == 1) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 1, 1>);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 32, 2>);
+ } else if (k <= 64) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 64, 3>);
+ } else if (k <= 128) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 128, 3>);
+ } else if (k <= 256) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 256, 4>);
+ } else if (k <= 512) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 512, 8>);
+ } else if (k <= 1024) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<128, 1024, 8>);
+ }
+#if GPU_MAX_SELECTION_K >= 2048
+ else if (k <= 2048) {
+ ivf_interleaved_call(ivfInterleavedScanImpl<64, 2048, 8>);
+ }
+#endif
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFInterleaved.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFInterleaved.cuh
new file mode 100644
index 0000000..1b7fbbe
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFInterleaved.cuh
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/DistanceUtils.cuh>
+#include <faiss/gpu/impl/GpuScalarQuantizer.cuh>
+#include <faiss/gpu/utils/Comparators.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/Select.cuh>
+#include <faiss/gpu/utils/WarpPackedBits.cuh>
+
+namespace faiss {
+namespace gpu {
+
+/// First pass kernel to perform scanning of IVF lists to produce top-k
+/// candidates
+template <
+ typename Codec,
+ typename Metric,
+ int ThreadsPerBlock,
+ int NumWarpQ,
+ int NumThreadQ>
+__global__ void ivfInterleavedScan(
+ Tensor<float, 2, true> queries,
+ Tensor<float, 3, true> residualBase,
+ Tensor<idx_t, 2, true> listIds,
+ void** allListData,
+ idx_t* listLengths,
+ Codec codec,
+ Metric metric,
+ int k,
+ // [query][probe][k]
+ Tensor<float, 3, true> distanceOut,
+ Tensor<idx_t, 3, true> indicesOut,
+ const bool Residual) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ extern __shared__ float smem[];
+
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ for (idx_t queryId = blockIdx.y; queryId < queries.getSize(0);
+ queryId += gridDim.y) {
+ auto probeId = blockIdx.x;
+ idx_t listId = listIds[queryId][probeId];
+
+ // Safety guard in case NaNs in input cause no list ID to be
+ // generated, or we have more nprobe than nlist
+ if (listId == -1) {
+ return;
+ }
+
+ // Vector dimension is currently limited to 32 bit
+ int dim = queries.getSize(1);
+
+ // FIXME: some issue with getLaneId() and CUDA 10.1 and P4 GPUs?
+ auto laneId = threadIdx.x % kWarpSize;
+ auto warpId = threadIdx.x / kWarpSize;
+
+ using EncodeT = typename Codec::EncodeT;
+
+ auto query = queries[queryId].data();
+ auto vecsBase = (EncodeT*)allListData[listId];
+ int numVecs = listLengths[listId];
+ auto residualBaseSlice = residualBase[queryId][probeId].data();
+
+ constexpr auto kInit = Metric::kDirection ? kFloatMin : kFloatMax;
+
+ __shared__ float smemK[kNumWarps * NumWarpQ];
+ __shared__ idx_t smemV[kNumWarps * NumWarpQ];
+
+ BlockSelect<
+ float,
+ idx_t,
+ Metric::kDirection,
+ Comparator<float>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(kInit, -1, smemK, smemV, k);
+
+ // The codec might be dependent upon data that we need to reference
+ // or store in shared memory
+ codec.initKernel(smem, dim);
+ __syncthreads();
+
+ // How many vector blocks of kWarpSize are in this list?
+ idx_t numBlocks = utils::divUp(numVecs, (idx_t)kWarpSize);
+
+ // Number of EncodeT words per each dimension of block of kWarpSize
+ // vecs
+ constexpr int bytesPerVectorBlockDim =
+ Codec::kEncodeBits * kWarpSize / 8;
+ constexpr int wordsPerVectorBlockDim =
+ bytesPerVectorBlockDim / sizeof(EncodeT);
+ int wordsPerVectorBlock = wordsPerVectorBlockDim * dim;
+
+ int dimBlocks = utils::roundDown(dim, kWarpSize);
+
+ for (idx_t block = warpId; block < numBlocks; block += kNumWarps) {
+ // We're handling a new vector
+ Metric dist = metric.zero();
+
+ // This is the vector a given lane/thread handles
+ idx_t vec = block * kWarpSize + laneId;
+ bool valid = vec < numVecs;
+
+ // This is where this warp begins reading data
+ EncodeT* data = vecsBase + block * wordsPerVectorBlock;
+
+ // whole blocks
+ for (int dBase = 0; dBase < dimBlocks; dBase += kWarpSize) {
+ const int loadDim = dBase + laneId;
+ const float queryReg = query[loadDim];
+ const float residualReg =
+ Residual ? residualBaseSlice[loadDim] : 0;
+
+ constexpr int kUnroll = 4;
+
+#pragma unroll
+ for (int i = 0; i < kWarpSize / kUnroll;
+ ++i, data += kUnroll * wordsPerVectorBlockDim) {
+ EncodeT encV[kUnroll];
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ encV[j] = WarpPackedBits<
+ EncodeT,
+ Codec::kEncodeBits>::
+ read(laneId,
+ data + j * wordsPerVectorBlockDim);
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ encV[j] = WarpPackedBits<
+ EncodeT,
+ Codec::kEncodeBits>::
+ postRead(laneId, encV[j]);
+ }
+
+ float decV[kUnroll];
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ int d = i * kUnroll + j;
+ decV[j] = codec.decodeNew(dBase + d, encV[j]);
+ }
+
+ if (Residual) {
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ int d = i * kUnroll + j;
+ decV[j] += SHFL_SYNC(residualReg, d, kWarpSize);
+ }
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ int d = i * kUnroll + j;
+ float q = SHFL_SYNC(queryReg, d, kWarpSize);
+ dist.handle(q, decV[j]);
+ }
+ }
+ }
+
+ // remainder
+ const int loadDim = dimBlocks + laneId;
+ const bool loadDimInBounds = loadDim < dim;
+
+ const float queryReg = loadDimInBounds ? query[loadDim] : 0;
+ const float residualReg = Residual && loadDimInBounds
+ ? residualBaseSlice[loadDim]
+ : 0;
+
+ for (int d = 0; d < dim - dimBlocks;
+ ++d, data += wordsPerVectorBlockDim) {
+ float q = SHFL_SYNC(queryReg, d, kWarpSize);
+
+ EncodeT enc =
+ WarpPackedBits<EncodeT, Codec::kEncodeBits>::read(
+ laneId, data);
+ enc = WarpPackedBits<EncodeT, Codec::kEncodeBits>::postRead(
+ laneId, enc);
+ float dec = codec.decodeNew(dimBlocks + d, enc);
+ if (Residual) {
+ dec += SHFL_SYNC(residualReg, d, kWarpSize);
+ }
+
+ dist.handle(q, dec);
+ }
+
+ if (valid) {
+ heap.addThreadQ(dist.reduce(), vec);
+ }
+
+ heap.checkThreadQ();
+ }
+
+ heap.reduce();
+
+ auto distanceOutBase = distanceOut[queryId][probeId].data();
+ auto indicesOutBase = indicesOut[queryId][probeId].data();
+
+ for (auto i = threadIdx.x; i < k; i += blockDim.x) {
+ distanceOutBase[i] = smemK[i];
+ indicesOutBase[i] = smemV[i];
+ }
+ }
+ }
+}
+
+//
+// We split up the scan function into multiple compilation units to cut down on
+// compile time using these macros to define the function body
+//
+
+// Top-level IVF scan function for the interleaved by kWarpSize layout
+// with all implementations
+void runIVFInterleavedScan(
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ int k,
+ faiss::MetricType metric,
+ bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res);
+
+// Second pass of IVF list scanning to perform final k-selection and look up the
+// user indices
+void runIVFInterleavedScan2(
+ Tensor<float, 3, true>& distanceIn,
+ Tensor<idx_t, 3, true>& indicesIn,
+ Tensor<idx_t, 2, true>& listIds,
+ int k,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ bool dir,
+ Tensor<float, 2, true>& distanceOut,
+ Tensor<idx_t, 2, true>& indicesOut,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFPQ.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFPQ.cu
new file mode 100644
index 0000000..f20e6e6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFPQ.cu
@@ -0,0 +1,739 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/impl/InterleavedCodes.h>
+#include <faiss/gpu/impl/RemapIndices.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <thrust/host_vector.h>
+#include <faiss/gpu/impl/BroadcastSum.cuh>
+#include <faiss/gpu/impl/Distance.cuh>
+#include <faiss/gpu/impl/FlatIndex.cuh>
+#include <faiss/gpu/impl/IVFAppend.cuh>
+#include <faiss/gpu/impl/IVFPQ.cuh>
+#include <faiss/gpu/impl/L2Norm.cuh>
+#include <faiss/gpu/impl/PQCodeDistances.cuh>
+#include <faiss/gpu/impl/PQScanMultiPassNoPrecomputed.cuh>
+#include <faiss/gpu/impl/PQScanMultiPassPrecomputed.cuh>
+#include <faiss/gpu/impl/VectorResidual.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/MatrixMult.cuh>
+#include <faiss/gpu/utils/NoTypeTensor.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+#include <limits>
+#include <type_traits>
+#include <unordered_map>
+
+namespace faiss {
+namespace gpu {
+
+IVFPQ::IVFPQ(
+ GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ int numSubQuantizers,
+ int bitsPerSubQuantizer,
+ bool useFloat16LookupTables,
+ bool useMMCodeDistance,
+ bool interleavedLayout,
+ float* pqCentroidData,
+ IndicesOptions indicesOptions,
+ MemorySpace space)
+ : IVFBase(resources,
+ dim,
+ nlist,
+ metric,
+ metricArg,
+ // we use IVF cell residuals for encoding vectors
+ true,
+ interleavedLayout,
+ indicesOptions,
+ space),
+ numSubQuantizers_(numSubQuantizers),
+ bitsPerSubQuantizer_(bitsPerSubQuantizer),
+ numSubQuantizerCodes_(utils::pow2(bitsPerSubQuantizer_)),
+ dimPerSubQuantizer_(dim_ / numSubQuantizers),
+ useFloat16LookupTables_(useFloat16LookupTables),
+ useMMCodeDistance_(useMMCodeDistance),
+ precomputedCodes_(false) {
+ FAISS_ASSERT(pqCentroidData);
+
+ FAISS_ASSERT(bitsPerSubQuantizer_ <= 8);
+ FAISS_ASSERT(dim_ % numSubQuantizers_ == 0);
+ FAISS_ASSERT(
+ interleavedLayout || isSupportedPQCodeLength(numSubQuantizers_));
+
+ setPQCentroids_(pqCentroidData);
+}
+
+IVFPQ::~IVFPQ() {}
+
+bool IVFPQ::isSupportedPQCodeLength(int size) {
+ switch (size) {
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 8:
+ case 12:
+ case 16:
+ case 20:
+ case 24:
+ case 28:
+ case 32:
+ case 40:
+ case 48:
+ case 56: // only supported with float16
+ case 64: // only supported with float16
+ case 96: // only supported with float16
+ return true;
+ default:
+ return false;
+ }
+}
+
+void IVFPQ::setPrecomputedCodes(Index* quantizer, bool enable) {
+ if (enable && metric_ == MetricType::METRIC_INNER_PRODUCT) {
+ fprintf(stderr,
+ "Precomputed codes are not needed for GpuIndexIVFPQ "
+ "with METRIC_INNER_PRODUCT");
+ return;
+ }
+
+ if (precomputedCodes_ != enable) {
+ precomputedCodes_ = enable;
+
+ if (precomputedCodes_) {
+ precomputeCodes_(quantizer);
+ } else {
+ // Clear out old precomputed code data
+ precomputedCode_ = DeviceTensor<float, 3, true>();
+ precomputedCodeHalf_ = DeviceTensor<half, 3, true>();
+ }
+ }
+}
+
+Tensor<float, 3, true> IVFPQ::getPQCentroids() {
+ return pqCentroidsMiddleCode_;
+}
+
+void IVFPQ::appendVectors_(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfCentroidResiduals,
+ Tensor<idx_t, 1, true>& indices,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ cudaStream_t stream) {
+ //
+ // Determine the encodings of the vectors
+ //
+
+ // For now we are restricted to <= 8 bits per code (hence uint8_t in the
+ // encodings)
+ FAISS_ASSERT(bitsPerSubQuantizer_ <= 8);
+
+ DeviceTensor<uint8_t, 2, true> encodings(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {vecs.getSize(0), numSubQuantizers_});
+
+ {
+ // Residuals are in the form
+ // (vec x numSubQuantizer x dimPerSubQuantizer)
+ // transpose to
+ // (numSubQuantizer x vec x dimPerSubQuantizer)
+ auto residualsView = ivfCentroidResiduals.view<3>(
+ {ivfCentroidResiduals.getSize(0),
+ numSubQuantizers_,
+ dimPerSubQuantizer_});
+
+ DeviceTensor<float, 3, true> residualsTranspose(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {numSubQuantizers_,
+ ivfCentroidResiduals.getSize(0),
+ dimPerSubQuantizer_});
+
+ runTransposeAny(residualsView, 0, 1, residualsTranspose, stream);
+
+ // Get the product quantizer centroids in the form
+ // (numSubQuantizer x numSubQuantizerCodes x dimPerSubQuantizer)
+ // which is pqCentroidsMiddleCode_
+
+ // We now have a batch operation to find the top-1 distances:
+ // batch size: numSubQuantizer
+ // centroids: (numSubQuantizerCodes x dimPerSubQuantizer)
+ // residuals: (vec x dimPerSubQuantizer)
+ // => (numSubQuantizer x vec x 1)
+ DeviceTensor<float, 3, true> closestSubQDistance(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {numSubQuantizers_, ivfCentroidResiduals.getSize(0), 1});
+ DeviceTensor<idx_t, 3, true> closestSubQIndex(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {numSubQuantizers_, ivfCentroidResiduals.getSize(0), 1});
+
+ for (int subQ = 0; subQ < numSubQuantizers_; ++subQ) {
+ auto closestSubQDistanceView = closestSubQDistance[subQ].view();
+ auto closestSubQIndexView = closestSubQIndex[subQ].view();
+
+ auto pqCentroidsMiddleCodeView =
+ pqCentroidsMiddleCode_[subQ].view();
+ auto residualsTransposeView = residualsTranspose[subQ].view();
+
+ runL2Distance(
+ resources_,
+ stream,
+ pqCentroidsMiddleCodeView,
+ true, // pqCentroidsMiddleCodeView is row major
+ nullptr, // no precomputed norms
+ residualsTransposeView,
+ true, // residualsTransposeView is row major
+ 1,
+ closestSubQDistanceView,
+ closestSubQIndexView,
+ // We don't care about distances
+ true);
+ }
+
+ // The L2 distance function only returns idx_t indices. As we are
+ // restricted to <= 8 bits per code, convert to uint8
+ auto closestSubQIndex8 = convertTensorTemporary<idx_t, uint8_t, 3>(
+ resources_, stream, closestSubQIndex);
+
+ // Now, we have the nearest sub-q centroid for each slice of the
+ // residual vector.
+ auto closestSubQIndex8View = closestSubQIndex8.view<2>(
+ {numSubQuantizers_, ivfCentroidResiduals.getSize(0)});
+
+ // The encodings are finally a transpose of this data
+ runTransposeAny(closestSubQIndex8View, 0, 1, encodings, stream);
+ }
+
+ // Append indices to the IVF lists
+ runIVFIndicesAppend(
+ listIds,
+ listOffset,
+ indices,
+ indicesOptions_,
+ deviceListIndexPointers_,
+ stream);
+
+ // Append the encoded vectors to the IVF lists
+ if (interleavedLayout_) {
+ runIVFPQInterleavedAppend(
+ listIds,
+ listOffset,
+ uniqueLists,
+ vectorsByUniqueList,
+ uniqueListVectorStart,
+ uniqueListStartOffset,
+ bitsPerSubQuantizer_,
+ encodings,
+ deviceListDataPointers_,
+ stream);
+ } else {
+ runIVFPQAppend(
+ listIds,
+ listOffset,
+ encodings,
+ deviceListDataPointers_,
+ stream);
+ }
+}
+
+size_t IVFPQ::getGpuVectorsEncodingSize_(idx_t numVecs) const {
+ if (interleavedLayout_) {
+ // bits per PQ code
+ idx_t bits = bitsPerSubQuantizer_;
+
+ int warpSize = getWarpSizeCurrentDevice();
+
+ // bytes to encode a block of warpSize vectors (single PQ code)
+ idx_t bytesPerDimBlock = bits * warpSize / 8;
+
+ // bytes to fully encode warpSize vectors
+ idx_t bytesPerBlock = bytesPerDimBlock * numSubQuantizers_;
+
+ // number of blocks of warpSize vectors we have
+ idx_t numBlocks = utils::divUp(numVecs, idx_t(warpSize));
+
+ // total size to encode numVecs
+ return bytesPerBlock * numBlocks;
+ } else {
+ return (size_t)numVecs * numSubQuantizers_;
+ }
+}
+
+size_t IVFPQ::getCpuVectorsEncodingSize_(idx_t numVecs) const {
+ size_t sizePerVector =
+ utils::divUp(numSubQuantizers_ * bitsPerSubQuantizer_, 8);
+
+ return numVecs * sizePerVector;
+}
+
+// Convert the CPU layout to the GPU layout
+std::vector<uint8_t> IVFPQ::translateCodesToGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const {
+ if (!interleavedLayout_) {
+ return codes;
+ }
+
+ auto up = unpackNonInterleaved(
+ std::move(codes), numVecs, numSubQuantizers_, bitsPerSubQuantizer_);
+ return packInterleaved(
+ std::move(up), numVecs, numSubQuantizers_, bitsPerSubQuantizer_);
+}
+
+// Conver the GPU layout to the CPU layout
+std::vector<uint8_t> IVFPQ::translateCodesFromGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const {
+ if (!interleavedLayout_) {
+ return codes;
+ }
+
+ auto up = unpackInterleaved(
+ std::move(codes), numVecs, numSubQuantizers_, bitsPerSubQuantizer_);
+ return packNonInterleaved(
+ std::move(up), numVecs, numSubQuantizers_, bitsPerSubQuantizer_);
+}
+
+void IVFPQ::setPQCentroids_(float* data) {
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ size_t pqSize =
+ numSubQuantizers_ * numSubQuantizerCodes_ * dimPerSubQuantizer_;
+
+ // Make sure the data is on the host
+ // FIXME: why are we doing this?
+ thrust::host_vector<float> hostMemory;
+ hostMemory.insert(hostMemory.end(), data, data + pqSize);
+
+ HostTensor<float, 3, true> pqHost(
+ hostMemory.data(),
+ {numSubQuantizers_, numSubQuantizerCodes_, dimPerSubQuantizer_});
+
+ DeviceTensor<float, 3, true> pqDeviceTranspose(
+ resources_,
+ makeDevAlloc(AllocType::Quantizer, stream),
+ {numSubQuantizers_, dimPerSubQuantizer_, numSubQuantizerCodes_});
+
+ {
+ // Only needed for the duration of the transposition
+ DeviceTensor<float, 3, true> pqDevice(
+ resources_,
+ makeTempAlloc(AllocType::Quantizer, stream),
+ pqHost);
+
+ runTransposeAny(pqDevice, 1, 2, pqDeviceTranspose, stream);
+ }
+
+ pqCentroidsInnermostCode_ = std::move(pqDeviceTranspose);
+
+ // Also maintain the PQ centroids in the form
+ // (sub q)(code id)(sub dim)
+ DeviceTensor<float, 3, true> pqCentroidsMiddleCode(
+ resources_,
+ makeDevAlloc(AllocType::Quantizer, stream),
+ {numSubQuantizers_, numSubQuantizerCodes_, dimPerSubQuantizer_});
+
+ runTransposeAny(
+ pqCentroidsInnermostCode_, 1, 2, pqCentroidsMiddleCode, stream);
+
+ pqCentroidsMiddleCode_ = std::move(pqCentroidsMiddleCode);
+}
+
+void IVFPQ::precomputeCodes_(Index* quantizer) {
+ FAISS_ASSERT(metric_ == MetricType::METRIC_L2);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ //
+ // d = || x - y_C ||^2 + || y_R ||^2 + 2 * (y_C|y_R) - 2 * (x|y_R)
+ // --------------- --------------------------- -------
+ // term 1 term 2 term 3
+ //
+
+ // Terms 1 and 3 are available only at query time. We compute term 2
+ // here.
+
+ // Compute 2 * (y_C|y_R) via batch matrix multiplication
+ // batch size (sub q) x {(centroid id)(sub dim) x (code id)(sub dim)'}
+ // => (sub q) x {(centroid id)(code id)}
+ // => (sub q)(centroid id)(code id)
+
+ // Whether or not there is a CPU or GPU coarse quantizer, updateQuantizer()
+ // should have been called to reconstruct as float32 the IVF centroids to
+ // have the data available on the GPU
+ FAISS_THROW_IF_NOT_MSG(
+ ivfCentroids_.getSize(0) == getNumLists() &&
+ ivfCentroids_.getSize(1) == getDim(),
+ "IVFPQ::precomputeCodes: coarse quantizer data "
+ "not synchronized on GPU; must call updateQuantizer() "
+ "before continuing");
+
+ // View (centroid id)(dim) as
+ // (centroid id)(sub q)(dim)
+ // Transpose (centroid id)(sub q)(sub dim) to
+ // (sub q)(centroid id)(sub dim)
+
+ // Create the coarse PQ product
+ DeviceTensor<float, 3, true> coarsePQProduct(
+ resources_,
+ makeTempAlloc(AllocType::QuantizerPrecomputedCodes, stream),
+ {numSubQuantizers_,
+ ivfCentroids_.getSize(0),
+ numSubQuantizerCodes_});
+
+ {
+ auto centroidView = ivfCentroids_.template view<3>(
+ {ivfCentroids_.getSize(0),
+ numSubQuantizers_,
+ dimPerSubQuantizer_});
+
+ // This is only needed temporarily
+ DeviceTensor<float, 3, true> centroidsTransposed(
+ resources_,
+ makeTempAlloc(AllocType::QuantizerPrecomputedCodes, stream),
+ {numSubQuantizers_,
+ ivfCentroids_.getSize(0),
+ dimPerSubQuantizer_});
+
+ runTransposeAny(centroidView, 0, 1, centroidsTransposed, stream);
+
+ runBatchMatrixMult(
+ coarsePQProduct,
+ false,
+ centroidsTransposed,
+ false,
+ pqCentroidsMiddleCode_,
+ true,
+ 2.0f,
+ 0.0f,
+ resources_->getBlasHandleCurrentDevice(),
+ stream);
+ }
+
+ // Transpose (sub q)(centroid id)(code id) to
+ // (centroid id)(sub q)(code id)
+ // This will become our precomputed code output
+ DeviceTensor<float, 3, true> coarsePQProductTransposed(
+ resources_,
+ makeDevAlloc(AllocType::QuantizerPrecomputedCodes, stream),
+ {ivfCentroids_.getSize(0),
+ numSubQuantizers_,
+ numSubQuantizerCodes_});
+ runTransposeAny(coarsePQProduct, 0, 1, coarsePQProductTransposed, stream);
+
+ // View (centroid id)(sub q)(code id) as
+ // (centroid id)(sub q * code id)
+ auto coarsePQProductTransposedView = coarsePQProductTransposed.view<2>(
+ {ivfCentroids_.getSize(0),
+ numSubQuantizers_ * numSubQuantizerCodes_});
+
+ // Sum || y_R ||^2 + 2 * (y_C|y_R)
+ // i.e., add norms (sub q * code id)
+ // along columns of inner product (centroid id)(sub q * code id)
+ {
+ // Compute ||y_R||^2 by treating
+ // (sub q)(code id)(sub dim) as (sub q * code id)(sub dim)
+ auto pqCentroidsMiddleCodeView = pqCentroidsMiddleCode_.view<2>(
+ {numSubQuantizers_ * numSubQuantizerCodes_,
+ dimPerSubQuantizer_});
+ DeviceTensor<float, 1, true> subQuantizerNorms(
+ resources_,
+ makeTempAlloc(AllocType::QuantizerPrecomputedCodes, stream),
+ {numSubQuantizers_ * numSubQuantizerCodes_});
+
+ runL2Norm(
+ pqCentroidsMiddleCodeView,
+ true,
+ subQuantizerNorms,
+ true,
+ stream);
+
+ runSumAlongColumns(
+ subQuantizerNorms, coarsePQProductTransposedView, stream);
+ }
+
+ // We added into the view, so `coarsePQProductTransposed` is now our
+ // precomputed term 2.
+ if (useFloat16LookupTables_) {
+ precomputedCodeHalf_ = DeviceTensor<half, 3, true>(
+ resources_,
+ makeDevAlloc(AllocType::QuantizerPrecomputedCodes, stream),
+ {ivfCentroids_.getSize(0),
+ numSubQuantizers_,
+ numSubQuantizerCodes_});
+
+ convertTensor(stream, coarsePQProductTransposed, precomputedCodeHalf_);
+ } else {
+ precomputedCode_ = std::move(coarsePQProductTransposed);
+ }
+}
+
+void IVFPQ::search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ // These are caught at a higher level
+ FAISS_ASSERT(nprobe <= GPU_MAX_SELECTION_K);
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+ nprobe = int(std::min(idx_t(nprobe), getNumLists()));
+
+ FAISS_ASSERT(queries.getSize(1) == dim_);
+ FAISS_ASSERT(outDistances.getSize(0) == queries.getSize(0));
+ FAISS_ASSERT(outIndices.getSize(0) == queries.getSize(0));
+
+ // Reserve space for the closest coarse centroids
+ DeviceTensor<float, 2, true> coarseDistances(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), nprobe});
+ DeviceTensor<idx_t, 2, true> coarseIndices(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), nprobe});
+
+ searchCoarseQuantizer_(
+ coarseQuantizer,
+ nprobe,
+ queries,
+ coarseDistances,
+ coarseIndices,
+ nullptr /* don't need IVF centroid residuals */,
+ nullptr /* don't need IVF centroids */);
+
+ searchImpl_(
+ queries,
+ coarseDistances,
+ coarseIndices,
+ k,
+ outDistances,
+ outIndices,
+ false);
+}
+
+void IVFPQ::searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) {
+ FAISS_ASSERT(ivfDistances.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(ivfAssignments.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(outDistances.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(outIndices.getSize(0) == vecs.getSize(0));
+ FAISS_ASSERT(vecs.getSize(1) == dim_);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+ auto nprobe = ivfAssignments.getSize(1);
+ FAISS_ASSERT(nprobe <= numLists_);
+
+ searchImpl_(
+ vecs,
+ ivfDistances,
+ ivfAssignments,
+ k,
+ outDistances,
+ outIndices,
+ storePairs);
+}
+
+void IVFPQ::searchImpl_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) {
+ FAISS_ASSERT(storePairs == false);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ if (precomputedCodes_) {
+ FAISS_ASSERT(metric_ == MetricType::METRIC_L2);
+
+ runPQPrecomputedCodes_(
+ queries,
+ coarseDistances,
+ coarseIndices,
+ k,
+ outDistances,
+ outIndices);
+ } else {
+ runPQNoPrecomputedCodes_(
+ queries,
+ coarseDistances,
+ coarseIndices,
+ k,
+ outDistances,
+ outIndices);
+ }
+
+ // If the GPU isn't storing indices (they are on the CPU side), we
+ // need to perform the re-mapping here
+ // FIXME: we might ultimately be calling this function with inputs
+ // from the CPU, these are unnecessary copies
+ if (indicesOptions_ == INDICES_CPU) {
+ HostTensor<idx_t, 2, true> hostOutIndices(outIndices, stream);
+
+ ivfOffsetToUserIndex(
+ hostOutIndices.data(),
+ numLists_,
+ hostOutIndices.getSize(0),
+ hostOutIndices.getSize(1),
+ listOffsetToUserIndex_);
+
+ // Copy back to GPU, since the input to this function is on the
+ // GPU
+ outIndices.copyFrom(hostOutIndices, stream);
+ }
+}
+
+void IVFPQ::runPQPrecomputedCodes_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ FAISS_ASSERT(metric_ == MetricType::METRIC_L2);
+
+ auto stream = resources_->getDefaultStreamCurrentDevice();
+
+ // Compute precomputed code term 3, - 2 * (x|y_R)
+ // This is done via batch MM
+ // {sub q} x {(query id)(sub dim) * (code id)(sub dim)'} =>
+ // {sub q} x {(query id)(code id)}
+ DeviceTensor<float, 3, true> term3Transposed(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), numSubQuantizers_, numSubQuantizerCodes_});
+
+ // These allocations within are only temporary, so release them when
+ // we're done to maximize free space
+ {
+ auto querySubQuantizerView = queries.view<3>(
+ {queries.getSize(0), numSubQuantizers_, dimPerSubQuantizer_});
+ DeviceTensor<float, 3, true> queriesTransposed(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {numSubQuantizers_, queries.getSize(0), dimPerSubQuantizer_});
+ runTransposeAny(querySubQuantizerView, 0, 1, queriesTransposed, stream);
+
+ DeviceTensor<float, 3, true> term3(
+ resources_,
+ makeTempAlloc(AllocType::Other, stream),
+ {numSubQuantizers_, queries.getSize(0), numSubQuantizerCodes_});
+
+ runBatchMatrixMult(
+ term3,
+ false,
+ queriesTransposed,
+ false,
+ pqCentroidsMiddleCode_,
+ true,
+ -2.0f,
+ 0.0f,
+ resources_->getBlasHandleCurrentDevice(),
+ stream);
+
+ runTransposeAny(term3, 0, 1, term3Transposed, stream);
+ }
+
+ NoTypeTensor<3, true> term2;
+ NoTypeTensor<3, true> term3;
+ DeviceTensor<half, 3, true> term3Half;
+
+ if (useFloat16LookupTables_) {
+ term3Half = convertTensorTemporary<float, half, 3>(
+ resources_, stream, term3Transposed);
+
+ term2 = NoTypeTensor<3, true>(precomputedCodeHalf_);
+ term3 = NoTypeTensor<3, true>(term3Half);
+ } else {
+ term2 = NoTypeTensor<3, true>(precomputedCode_);
+ term3 = NoTypeTensor<3, true>(term3Transposed);
+ }
+
+ runPQScanMultiPassPrecomputed(
+ queries,
+ coarseDistances, // term 1
+ term2, // term 2
+ term3, // term 3
+ coarseIndices,
+ useFloat16LookupTables_,
+ interleavedLayout_,
+ bitsPerSubQuantizer_,
+ numSubQuantizers_,
+ numSubQuantizerCodes_,
+ deviceListDataPointers_,
+ deviceListIndexPointers_,
+ indicesOptions_,
+ deviceListLengths_,
+ maxListLength_,
+ k,
+ outDistances,
+ outIndices,
+ resources_);
+}
+
+void IVFPQ::runPQNoPrecomputedCodes_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) {
+ runPQScanMultiPassNoPrecomputed(
+ queries,
+ ivfCentroids_,
+ pqCentroidsInnermostCode_,
+ coarseDistances,
+ coarseIndices,
+ useFloat16LookupTables_,
+ useMMCodeDistance_,
+ interleavedLayout_,
+ bitsPerSubQuantizer_,
+ numSubQuantizers_,
+ numSubQuantizerCodes_,
+ deviceListDataPointers_,
+ deviceListIndexPointers_,
+ indicesOptions_,
+ deviceListLengths_,
+ maxListLength_,
+ k,
+ metric_,
+ outDistances,
+ outIndices,
+ resources_);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFPQ.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFPQ.cuh
new file mode 100644
index 0000000..a9bf4b8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFPQ.cuh
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/MetricType.h>
+#include <faiss/gpu/impl/IVFBase.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+
+namespace faiss {
+namespace gpu {
+
+/// Implementing class for IVFPQ on the GPU
+class IVFPQ : public IVFBase {
+ public:
+ IVFPQ(GpuResources* resources,
+ int dim,
+ idx_t nlist,
+ faiss::MetricType metric,
+ float metricArg,
+ int numSubQuantizers,
+ int bitsPerSubQuantizer,
+ bool useFloat16LookupTables,
+ bool useMMCodeDistance,
+ bool interleavedLayout,
+ float* pqCentroidData,
+ IndicesOptions indicesOptions,
+ MemorySpace space);
+
+ /// Returns true if we support PQ in this size
+ static bool isSupportedPQCodeLength(int size);
+
+ ~IVFPQ() override;
+
+ /// Enable or disable pre-computed codes. The quantizer is needed to gather
+ /// the IVF centroids for use
+ virtual void setPrecomputedCodes(Index* coarseQuantizer, bool enable);
+
+ /// Returns our set of sub-quantizers of the form
+ /// (sub q)(code id)(sub dim)
+ Tensor<float, 3, true> getPQCentroids();
+
+ /// Find the approximate k nearest neigbors for `queries` against
+ /// our database
+ void search(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& queries,
+ int nprobe,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices) override;
+
+ /// Performs search when we are already given the IVF cells to look at
+ /// (GpuIndexIVF::search_preassigned implementation)
+ void searchPreassigned(
+ Index* coarseQuantizer,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfDistances,
+ Tensor<idx_t, 2, true>& ivfAssignments,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs) override;
+
+ protected:
+ /// Returns the encoding size for a PQ-encoded IVF list
+ size_t getGpuVectorsEncodingSize_(idx_t numVecs) const override;
+ size_t getCpuVectorsEncodingSize_(idx_t numVecs) const override;
+
+ /// Translate to our preferred GPU encoding
+ std::vector<uint8_t> translateCodesToGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const override;
+
+ /// Translate from our preferred GPU encoding
+ std::vector<uint8_t> translateCodesFromGpu_(
+ std::vector<uint8_t> codes,
+ idx_t numVecs) const override;
+
+ /// Encode the vectors that we're adding and append to our IVF lists
+ void appendVectors_(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& ivfCentroidResiduals,
+ Tensor<idx_t, 1, true>& indices,
+ Tensor<idx_t, 1, true>& uniqueLists,
+ Tensor<idx_t, 1, true>& vectorsByUniqueList,
+ Tensor<idx_t, 1, true>& uniqueListVectorStart,
+ Tensor<idx_t, 1, true>& uniqueListStartOffset,
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<idx_t, 1, true>& listOffset,
+ cudaStream_t stream) override;
+
+ /// Shared IVF search implementation, used by both search and
+ /// searchPreassigned
+ void searchImpl_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool storePairs);
+
+ /// Sets the current product quantizer centroids; the data can be
+ /// resident on either the host or the device. It will be transposed
+ /// into our preferred data layout
+ /// Data must be a row-major, 3-d array of size
+ /// (numSubQuantizers, numSubQuantizerCodes, dim / numSubQuantizers)
+ void setPQCentroids_(float* data);
+
+ /// Calculate precomputed residual distance information
+ void precomputeCodes_(Index* quantizer);
+
+ /// Runs kernels for scanning inverted lists with precomputed codes
+ void runPQPrecomputedCodes_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices);
+
+ /// Runs kernels for scanning inverted lists without precomputed codes
+ void runPQNoPrecomputedCodes_(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ int k,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices);
+
+ protected:
+ /// Number of sub-quantizers per vector
+ const int numSubQuantizers_;
+
+ /// Number of bits per sub-quantizer
+ const int bitsPerSubQuantizer_;
+
+ /// Number of per sub-quantizer codes (2^bits)
+ const int numSubQuantizerCodes_;
+
+ /// Number of dimensions per each sub-quantizer
+ const int dimPerSubQuantizer_;
+
+ /// Do we maintain precomputed terms and lookup tables in float16
+ /// form?
+ const bool useFloat16LookupTables_;
+
+ /// For usage without precomputed codes, do we force usage of the
+ /// general-purpose MM code distance computation? This is for testing
+ /// purposes.
+ const bool useMMCodeDistance_;
+
+ /// On the GPU, we prefer different PQ centroid data layouts for
+ /// different purposes.
+ ///
+ /// (sub q)(sub dim)(code id)
+ DeviceTensor<float, 3, true> pqCentroidsInnermostCode_;
+
+ /// (sub q)(code id)(sub dim)
+ DeviceTensor<float, 3, true> pqCentroidsMiddleCode_;
+
+ /// Are precomputed codes enabled? (additional factoring and
+ /// precomputation of the residual distance, to reduce query-time work)
+ bool precomputedCodes_;
+
+ /// Precomputed term 2 in float form
+ /// (centroid id)(sub q)(code id)
+ DeviceTensor<float, 3, true> precomputedCode_;
+
+ /// Precomputed term 2 in half form
+ DeviceTensor<half, 3, true> precomputedCodeHalf_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtils.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtils.cu
new file mode 100644
index 0000000..b5ce9e4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtils.cu
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <thrust/execution_policy.h>
+#include <thrust/scan.h>
+#include <faiss/gpu/impl/IVFUtils.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+#include <faiss/gpu/utils/ThrustUtils.cuh>
+
+#include <algorithm>
+
+namespace faiss {
+namespace gpu {
+
+size_t getIVFKSelectionPass2Chunks(size_t nprobe) {
+ // We run two passes of heap selection
+ // This is the size of the second-level heap passes
+ constexpr size_t kNProbeSplit = 8;
+ return std::min(nprobe, kNProbeSplit);
+}
+
+size_t getIVFPerQueryTempMemory(size_t k, size_t nprobe, size_t maxListLength) {
+ size_t pass2Chunks = getIVFKSelectionPass2Chunks(nprobe);
+
+ size_t sizeForFirstSelectPass =
+ pass2Chunks * k * (sizeof(float) + sizeof(idx_t));
+
+ // Each IVF list being scanned concurrently needs a separate array to
+ // indicate where the per-IVF list distances are being stored via prefix
+ // sum. There is one per each nprobe, plus 1 more entry at the end
+ size_t prefixSumOffsets = nprobe * sizeof(idx_t) + sizeof(idx_t);
+
+ // Storage for all distances from all the IVF lists we are processing
+ size_t allDistances = nprobe * maxListLength * sizeof(float);
+
+ // There are 2 streams on which computations is performed (hence the 2 *)
+ return 2 * (prefixSumOffsets + allDistances + sizeForFirstSelectPass);
+}
+
+size_t getIVFPQPerQueryTempMemory(
+ size_t k,
+ size_t nprobe,
+ size_t maxListLength,
+ bool usePrecomputedCodes,
+ size_t numSubQuantizers,
+ size_t numSubQuantizerCodes) {
+ // Residual PQ distances per each IVF partition (in case we are not using
+ // precomputed codes;
+ size_t residualDistances = usePrecomputedCodes
+ ? 0
+ : (nprobe * numSubQuantizers * numSubQuantizerCodes *
+ sizeof(float));
+
+ // There are 2 streams on which computations is performed (hence the 2 *)
+ // The IVF-generic temp memory allocation already takes this multi-streaming
+ // into account, but we need to do so for the PQ residual distances too
+ return (2 * residualDistances) +
+ getIVFPerQueryTempMemory(k, nprobe, maxListLength);
+}
+
+size_t getIVFQueryTileSize(
+ size_t numQueries,
+ size_t tempMemoryAvailable,
+ size_t sizePerQuery) {
+ // Our ideal minimum number of queries that we'd like to run concurrently
+ constexpr size_t kMinQueryTileSize = 8;
+
+ // Our absolute maximum number of queries that we can run concurrently
+ // (based on max Y grid dimension)
+ constexpr size_t kMaxQueryTileSize = 65536;
+
+ // First, see how many queries we can run within the limit of our available
+ // temporary memory. If all queries can run within the temporary memory
+ // limit, we'll just use that.
+ size_t withinTempMemoryNumQueries =
+ std::min(tempMemoryAvailable / sizePerQuery, numQueries);
+
+ // However, there is a maximum cap on the number of queries that we can run
+ // at once, even if memory were unlimited (due to max Y grid dimension)
+ withinTempMemoryNumQueries =
+ std::min(withinTempMemoryNumQueries, kMaxQueryTileSize);
+
+ // However. withinTempMemoryNumQueries could be really small, or even zero
+ // (in the case where there is no temporary memory available, or the memory
+ // resources for a single query required are really large). If we are below
+ // the ideal minimum number of queries to run concurrently, then we will
+ // ignore the temporary memory limit and fall back to a general device
+ // allocation.
+ // Note that if we only had a single query, then this is ok to run as-is
+ if (withinTempMemoryNumQueries < numQueries &&
+ withinTempMemoryNumQueries < kMinQueryTileSize) {
+ // Either the amount of temporary memory available is too low, or the
+ // amount of memory needed to run a single query is really high. Ignore
+ // the temporary memory available, and always attempt to use this amount
+ // of memory for temporary results
+ //
+ // FIXME: could look at amount of memory available on the current
+ // device, but there is no guarantee that all that memory available
+ // could be done in a single allocation, so we just pick a suitably
+ // large allocation that can yield enough efficiency but something that
+ // the GPU can likely allocate.
+ constexpr size_t kMinMemoryAllocation = 512 * 1024 * 1024; // 512 MiB
+
+ size_t withinMemoryNumQueries =
+ std::min(kMinMemoryAllocation / sizePerQuery, numQueries);
+
+ // It is possible that the per-query size is incredibly huge, in which
+ // case even the 512 MiB allocation will not fit it. In this case, we
+ // have no option except to try running a single one.
+ return std::max(withinMemoryNumQueries, size_t(1));
+ } else {
+ // withinTempMemoryNumQueries cannot be > numQueries.
+ // Either:
+ // 1. == numQueries, >= kMinQueryTileSize (i.e., we can satisfy all
+ // queries in one go, or are limited by max query tile size)
+ // 2. < numQueries, >= kMinQueryTileSize (i.e., we can't satisfy all
+ // queries in one go, but we have a large enough batch to run which is
+ // ok
+ return withinTempMemoryNumQueries;
+ }
+}
+
+// Calculates the total number of intermediate distances to consider
+// for all queries
+__global__ void getResultLengths(
+ Tensor<idx_t, 2, true> ivfListIds,
+ idx_t* listLengths,
+ idx_t totalSize,
+ Tensor<idx_t, 2, true> length) {
+ idx_t linearThreadId = idx_t(blockIdx.x) * blockDim.x + threadIdx.x;
+ if (linearThreadId >= totalSize) {
+ return;
+ }
+
+ auto nprobe = ivfListIds.getSize(1);
+ auto queryId = linearThreadId / nprobe;
+ auto listId = linearThreadId % nprobe;
+
+ idx_t centroidId = ivfListIds[queryId][listId];
+
+ // Safety guard in case NaNs in input cause no list ID to be generated
+ length[queryId][listId] = (centroidId != -1) ? listLengths[centroidId] : 0;
+}
+
+void runCalcListOffsets(
+ GpuResources* res,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ DeviceVector<idx_t>& listLengths,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<char, 1, true>& thrustMem,
+ cudaStream_t stream) {
+ FAISS_ASSERT(ivfListIds.getSize(0) == prefixSumOffsets.getSize(0));
+ FAISS_ASSERT(ivfListIds.getSize(1) == prefixSumOffsets.getSize(1));
+
+ idx_t totalSize = ivfListIds.numElements();
+
+ idx_t numThreads = std::min(totalSize, (idx_t)getMaxThreadsCurrentDevice());
+ idx_t numBlocks = utils::divUp(totalSize, numThreads);
+
+ auto grid = dim3(numBlocks);
+ auto block = dim3(numThreads);
+
+ getResultLengths<<<grid, block, 0, stream>>>(
+ ivfListIds, listLengths.data(), totalSize, prefixSumOffsets);
+ CUDA_TEST_ERROR();
+
+ // Prefix sum of the indices, so we know where the intermediate
+ // results should be maintained
+ // Thrust wants a place for its temporary allocations, so provide
+ // one, so it won't call cudaMalloc/Free if we size it sufficiently
+ ThrustAllocator alloc(
+ res, stream, thrustMem.data(), thrustMem.getSizeInBytes());
+
+ thrust::inclusive_scan(
+ thrust::cuda::par(alloc).on(stream),
+ prefixSumOffsets.data(),
+ prefixSumOffsets.data() + totalSize,
+ prefixSumOffsets.data());
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtils.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtils.cuh
new file mode 100644
index 0000000..b5a664e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtils.cuh
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+// A collection of utility functions for IVFPQ and IVFFlat, for
+// post-processing and k-selecting the results
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+/// For the final k-selection of IVF query distances, we perform two passes.
+/// The first pass scans some number of per-IVF list distances reducing them to
+/// at most 8, then a second pass processes these <= 8 to the single final list
+/// of NN candidates
+size_t getIVFKSelectionPass2Chunks(size_t nprobe);
+
+/// Function to determine amount of temporary space that we allocate
+/// for storing basic IVF list scanning distances during query, based on the
+/// memory allocation per query. This is the memory requirement for
+/// IVFFlat/IVFSQ but IVFPQ will add some additional allocation as well (see
+/// getIVFPQPerQueryTempMemory)
+size_t getIVFPerQueryTempMemory(size_t k, size_t nprobe, size_t maxListLength);
+
+/// Function to determine amount of temporary space that we allocate
+/// for storing basic IVFPQ list scanning distances during query, based on the
+/// memory allocation per query.
+size_t getIVFPQPerQueryTempMemory(
+ size_t k,
+ size_t nprobe,
+ size_t maxListLength,
+ bool usePrecomputedCodes,
+ size_t numSubQuantizers,
+ size_t numSubQuantizerCodes);
+
+/// Based on the amount of temporary memory needed per IVF query (determined by
+/// one of the above functions) and the amount of current temporary memory
+/// available, determine how many queries we will run concurrently in a single
+/// tile so as to stay within reasonable temporary memory allocation limits.
+size_t getIVFQueryTileSize(
+ size_t numQueries,
+ size_t tempMemoryAvailable,
+ size_t sizePerQuery);
+
+/// Function for multi-pass scanning that collects the length of
+/// intermediate results for all (query, probe) pair
+void runCalcListOffsets(
+ GpuResources* res,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ DeviceVector<idx_t>& listLengths,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<char, 1, true>& thrustMem,
+ cudaStream_t stream);
+
+/// Performs a first pass of k-selection on the results
+void runPass1SelectLists(
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<float, 1, true>& distance,
+ int nprobe,
+ int k,
+ bool use64BitSelection,
+ bool chooseLargest,
+ Tensor<float, 3, true>& heapDistances,
+ Tensor<idx_t, 3, true>& heapIndices,
+ cudaStream_t stream);
+
+/// Performs a final pass of k-selection on the results, producing the
+/// final indices
+void runPass2SelectLists(
+ Tensor<float, 2, true>& heapDistances,
+ Tensor<idx_t, 2, true>& heapIndices,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ int k,
+ bool use64BitSelection,
+ bool chooseLargest,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtilsSelect1.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtilsSelect1.cu
new file mode 100644
index 0000000..c4f65ba
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtilsSelect1.cu
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/IVFUtils.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/Limits.cuh>
+#include <faiss/gpu/utils/Select.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+//
+// This kernel is split into a separate compilation unit to cut down
+// on compile time
+//
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename IndexT,
+ int ThreadsPerBlock,
+ int NumWarpQ,
+ int NumThreadQ,
+ bool Dir>
+__global__ void pass1SelectLists(
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<float, 1, true> distance,
+ int nprobe,
+ int k,
+ Tensor<float, 3, true> heapDistances,
+ Tensor<idx_t, 3, true> heapIndices) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __shared__ float smemK[kNumWarps * NumWarpQ];
+ __shared__ IndexT smemV[kNumWarps * NumWarpQ];
+
+ for (IndexT queryId = blockIdx.y; queryId < prefixSumOffsets.getSize(0);
+ queryId += gridDim.y) {
+ constexpr auto kInit = Dir ? kFloatMin : kFloatMax;
+ BlockSelect<
+ float,
+ IndexT,
+ Dir,
+ Comparator<float>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(kInit, -1, smemK, smemV, k);
+
+ auto sliceId = blockIdx.x;
+ auto numSlices = gridDim.x;
+
+ IndexT sliceSize = (nprobe / numSlices);
+ IndexT sliceStart = sliceSize * sliceId;
+ IndexT sliceEnd = sliceId == (numSlices - 1)
+ ? nprobe
+ : sliceStart + sliceSize;
+ auto offsets = prefixSumOffsets[queryId].data();
+
+ // We ensure that before the array (at offset -1), there is a 0
+ // value
+ auto start = *(&offsets[sliceStart] - 1);
+ auto end = offsets[sliceEnd - 1];
+
+ auto num = end - start;
+ auto limit = utils::roundDown(num, (IndexT)kWarpSize);
+
+ IndexT i = threadIdx.x;
+ auto distanceStart = distance[start].data();
+
+ // BlockSelect add cannot be used in a warp divergent circumstance;
+ // we handle the remainder warp below
+ for (; i < limit; i += blockDim.x) {
+ heap.add(distanceStart[i], IndexT(start + i));
+ }
+
+ // Handle the remainder if any separately (warp is divergent)
+ if (i < num) {
+ heap.addThreadQ(distanceStart[i], IndexT(start + i));
+ }
+
+ // Merge all final results
+ heap.reduce();
+
+ // Write out the final k-selected values; they should be all
+ // together
+ for (auto i = threadIdx.x; i < k; i += blockDim.x) {
+ heapDistances[queryId][sliceId][i] = smemK[i];
+ heapIndices[queryId][sliceId][i] = idx_t(smemV[i]);
+ }
+ }
+ }
+}
+
+void runPass1SelectLists(
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<float, 1, true>& distance,
+ int nprobe,
+ int k,
+ bool use64BitSelection,
+ bool chooseLargest,
+ Tensor<float, 3, true>& heapDistances,
+ Tensor<idx_t, 3, true>& heapIndices,
+ cudaStream_t stream) {
+ // This is also caught at a higher level
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ auto grid =
+ dim3(heapDistances.getSize(1),
+ std::min(
+ prefixSumOffsets.getSize(0),
+ (idx_t)getMaxGridCurrentDevice().y));
+
+#define RUN_PASS(INDEX_T, BLOCK, NUM_WARP_Q, NUM_THREAD_Q, DIR) \
+ do { \
+ pass1SelectLists<INDEX_T, BLOCK, NUM_WARP_Q, NUM_THREAD_Q, DIR> \
+ <<<grid, BLOCK, 0, stream>>>( \
+ prefixSumOffsets, \
+ distance, \
+ nprobe, \
+ k, \
+ heapDistances, \
+ heapIndices); \
+ return; /* success */ \
+ } while (0)
+
+#if GPU_MAX_SELECTION_K >= 2048
+
+ // block size 128 for k <= 1024, 64 for k = 2048
+#define RUN_PASS_DIR(INDEX_T, DIR) \
+ do { \
+ if (k == 1) { \
+ RUN_PASS(INDEX_T, 128, 1, 1, DIR); \
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) { \
+ RUN_PASS(INDEX_T, 128, 32, 2, DIR); \
+ } else if (k <= 64) { \
+ RUN_PASS(INDEX_T, 128, 64, 3, DIR); \
+ } else if (k <= 128) { \
+ RUN_PASS(INDEX_T, 128, 128, 3, DIR); \
+ } else if (k <= 256) { \
+ RUN_PASS(INDEX_T, 128, 256, 4, DIR); \
+ } else if (k <= 512) { \
+ RUN_PASS(INDEX_T, 128, 512, 8, DIR); \
+ } else if (k <= 1024) { \
+ RUN_PASS(INDEX_T, 128, 1024, 8, DIR); \
+ } else if (k <= 2048) { \
+ RUN_PASS(INDEX_T, 64, 2048, 8, DIR); \
+ } \
+ } while (0)
+
+#else
+
+#define RUN_PASS_DIR(INDEX_T, DIR) \
+ do { \
+ if (k == 1) { \
+ RUN_PASS(INDEX_T, 128, 1, 1, DIR); \
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) { \
+ RUN_PASS(INDEX_T, 128, 32, 2, DIR); \
+ } else if (k <= 64) { \
+ RUN_PASS(INDEX_T, 128, 64, 3, DIR); \
+ } else if (k <= 128) { \
+ RUN_PASS(INDEX_T, 128, 128, 3, DIR); \
+ } else if (k <= 256) { \
+ RUN_PASS(INDEX_T, 128, 256, 4, DIR); \
+ } else if (k <= 512) { \
+ RUN_PASS(INDEX_T, 128, 512, 8, DIR); \
+ } else if (k <= 1024) { \
+ RUN_PASS(INDEX_T, 128, 1024, 8, DIR); \
+ } \
+ } while (0)
+
+#endif // GPU_MAX_SELECTION_K
+
+ if (use64BitSelection) {
+ if (chooseLargest) {
+ RUN_PASS_DIR(idx_t, true);
+ } else {
+ RUN_PASS_DIR(idx_t, false);
+ }
+ } else {
+ if (chooseLargest) {
+ RUN_PASS_DIR(int32_t, true);
+ } else {
+ RUN_PASS_DIR(int32_t, false);
+ }
+ }
+
+#undef RUN_PASS_DIR
+#undef RUN_PASS
+
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtilsSelect2.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtilsSelect2.cu
new file mode 100644
index 0000000..2dbf3c0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IVFUtilsSelect2.cu
@@ -0,0 +1,258 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/IVFUtils.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/Limits.cuh>
+#include <faiss/gpu/utils/Select.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+//
+// This kernel is split into a separate compilation unit to cut down
+// on compile time
+//
+
+namespace faiss {
+namespace gpu {
+
+// This is warp divergence central, but this is really a final step
+// and happening a small number of times
+template <typename T>
+__device__ int binarySearchForBucket(T* prefixSumOffsets, T size, T val) {
+ T start = 0;
+ T end = size;
+
+ while (end - start > 0) {
+ T mid = start + (end - start) / 2;
+ T midVal = prefixSumOffsets[mid];
+
+ // Find the first bucket that we are <=
+ if (midVal <= val) {
+ start = mid + 1;
+ } else {
+ end = mid;
+ }
+ }
+
+ // We must find the bucket that it is in
+ assert(start != size);
+
+ return start;
+}
+
+template <
+ typename IndexT,
+ int ThreadsPerBlock,
+ int NumWarpQ,
+ int NumThreadQ,
+ bool Dir>
+__global__ void pass2SelectLists(
+ Tensor<float, 2, true> heapDistances,
+ Tensor<idx_t, 2, true> heapIndices,
+ void** listIndices,
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<idx_t, 2, true> ivfListIds,
+ int k,
+ IndicesOptions opt,
+ Tensor<float, 2, true> outDistances,
+ Tensor<idx_t, 2, true> outIndices) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __shared__ float smemK[kNumWarps * NumWarpQ];
+ __shared__ IndexT smemV[kNumWarps * NumWarpQ];
+
+ constexpr auto kInit = Dir ? kFloatMin : kFloatMax;
+ BlockSelect<
+ float,
+ IndexT,
+ Dir,
+ Comparator<float>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(kInit, -1, smemK, smemV, k);
+
+ auto queryId = blockIdx.x;
+ idx_t num = heapDistances.getSize(1);
+ idx_t limit = utils::roundDown(num, kWarpSize);
+
+ idx_t i = threadIdx.x;
+ auto heapDistanceStart = heapDistances[queryId];
+
+ // BlockSelect add cannot be used in a warp divergent circumstance; we
+ // handle the remainder warp below
+ for (; i < limit; i += blockDim.x) {
+ heap.add(heapDistanceStart[i], IndexT(i));
+ }
+
+ // Handle warp divergence separately
+ if (i < num) {
+ heap.addThreadQ(heapDistanceStart[i], IndexT(i));
+ }
+
+ // Merge all final results
+ heap.reduce();
+
+ for (auto i = threadIdx.x; i < k; i += blockDim.x) {
+ outDistances[queryId][i] = smemK[i];
+
+ // `v` is the index in `heapIndices`
+ // We need to translate this into an original user index. The
+ // reason why we don't maintain intermediate results in terms of
+ // user indices is to substantially reduce temporary memory
+ // requirements and global memory write traffic for the list
+ // scanning.
+ // This code is highly divergent, but it's probably ok, since this
+ // is the very last step and it is happening a small number of
+ // times (#queries x k).
+ idx_t v = smemV[i];
+ idx_t index = -1;
+
+ if (v != -1) {
+ // `offset` is the offset of the intermediate result, as
+ // calculated by the original scan.
+ idx_t offset = heapIndices[queryId][v];
+
+ // In order to determine the actual user index, we need to first
+ // determine what list it was in.
+ // We do this by binary search in the prefix sum list.
+ idx_t probe = binarySearchForBucket(
+ prefixSumOffsets[queryId].data(),
+ prefixSumOffsets.getSize(1),
+ offset);
+
+ // This is then the probe for the query; we can find the actual
+ // list ID from this
+ idx_t listId = ivfListIds[queryId][probe];
+
+ // Now, we need to know the offset within the list
+ // We ensure that before the array (at offset -1), there is a 0
+ // value
+ idx_t listStart =
+ *(prefixSumOffsets[queryId][probe].data() - 1);
+ idx_t listOffset = offset - listStart;
+
+ // This gives us our final index
+ if (opt == INDICES_32_BIT) {
+ index = (idx_t)((int*)listIndices[listId])[listOffset];
+ } else if (opt == INDICES_64_BIT) {
+ index = ((idx_t*)listIndices[listId])[listOffset];
+ } else {
+ index = (listId << 32 | (idx_t)listOffset);
+ }
+ }
+
+ outIndices[queryId][i] = index;
+ }
+ }
+}
+
+void runPass2SelectLists(
+ Tensor<float, 2, true>& heapDistances,
+ Tensor<idx_t, 2, true>& heapIndices,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ int k,
+ bool use64BitSelection,
+ bool chooseLargest,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ cudaStream_t stream) {
+ // This is also caught at a higher level
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ auto grid = dim3(ivfListIds.getSize(0));
+
+#define RUN_PASS(INDEX_T, BLOCK, NUM_WARP_Q, NUM_THREAD_Q, DIR) \
+ do { \
+ pass2SelectLists<INDEX_T, BLOCK, NUM_WARP_Q, NUM_THREAD_Q, DIR> \
+ <<<grid, BLOCK, 0, stream>>>( \
+ heapDistances, \
+ heapIndices, \
+ listIndices.data(), \
+ prefixSumOffsets, \
+ ivfListIds, \
+ k, \
+ indicesOptions, \
+ outDistances, \
+ outIndices); \
+ } while (0)
+
+#if GPU_MAX_SELECTION_K >= 2048
+
+ // block size 128 for k <= 1024, 64 for k = 2048
+#define RUN_PASS_DIR(INDEX_T, DIR) \
+ do { \
+ if (k == 1) { \
+ RUN_PASS(INDEX_T, 128, 1, 1, DIR); \
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) { \
+ RUN_PASS(INDEX_T, 128, 32, 2, DIR); \
+ } else if (k <= 64) { \
+ RUN_PASS(INDEX_T, 128, 64, 3, DIR); \
+ } else if (k <= 128) { \
+ RUN_PASS(INDEX_T, 128, 128, 3, DIR); \
+ } else if (k <= 256) { \
+ RUN_PASS(INDEX_T, 128, 256, 4, DIR); \
+ } else if (k <= 512) { \
+ RUN_PASS(INDEX_T, 128, 512, 8, DIR); \
+ } else if (k <= 1024) { \
+ RUN_PASS(INDEX_T, 128, 1024, 8, DIR); \
+ } else if (k <= 2048) { \
+ RUN_PASS(INDEX_T, 64, 2048, 8, DIR); \
+ } \
+ } while (0)
+
+#else
+
+#define RUN_PASS_DIR(INDEX_T, DIR) \
+ do { \
+ if (k == 1) { \
+ RUN_PASS(INDEX_T, 128, 1, 1, DIR); \
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) { \
+ RUN_PASS(INDEX_T, 128, 32, 2, DIR); \
+ } else if (k <= 64) { \
+ RUN_PASS(INDEX_T, 128, 64, 3, DIR); \
+ } else if (k <= 128) { \
+ RUN_PASS(INDEX_T, 128, 128, 3, DIR); \
+ } else if (k <= 256) { \
+ RUN_PASS(INDEX_T, 128, 256, 4, DIR); \
+ } else if (k <= 512) { \
+ RUN_PASS(INDEX_T, 128, 512, 8, DIR); \
+ } else if (k <= 1024) { \
+ RUN_PASS(INDEX_T, 128, 1024, 8, DIR); \
+ } \
+ } while (0)
+
+#endif // GPU_MAX_SELECTION_K
+
+ if (use64BitSelection) {
+ if (chooseLargest) {
+ RUN_PASS_DIR(idx_t, true);
+ } else {
+ RUN_PASS_DIR(idx_t, false);
+ }
+ } else {
+ if (chooseLargest) {
+ RUN_PASS_DIR(int32_t, true);
+ } else {
+ RUN_PASS_DIR(int32_t, false);
+ }
+ }
+
+#undef RUN_PASS_DIR
+#undef RUN_PASS
+
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IcmEncoder.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IcmEncoder.cu
new file mode 100644
index 0000000..b86e390
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IcmEncoder.cu
@@ -0,0 +1,380 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/IcmEncoder.cuh>
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/impl/L2Norm.cuh>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/MatrixMult.cuh>
+#include <faiss/gpu/utils/Pair.cuh>
+#include <faiss/gpu/utils/Reductions.cuh>
+
+#include <curand_kernel.h>
+
+namespace faiss {
+namespace gpu {
+
+extern __shared__ char smem[];
+
+/** encode using iterative conditional mode
+ *
+ * For subcode cm of a vector, we fix the other subcodes cj (j != m)
+ * and then find the optimal value of cm (cm = 1,...,K) such that
+ * minimizing the objective function.
+ *
+ * @param uterm precomputed unary terms, size (M, n, K)
+ * @param bterm precomputed binary terms, size (M1, M2, K1, K2)
+ * @param codes output vector encodings, size (n, M)
+ * @param M number of codebooks
+ * @param K number of codewords in a codebook
+ * @param m identify which subcode to condition on
+ */
+__global__ void runIcmEncodeStep(
+ const float* uterm,
+ const float* bterm,
+ int32_t* codes,
+ int M,
+ int K,
+ int m) {
+ using KVPair = Pair<float, int>;
+
+ auto id = blockIdx.x; // each block takes care of one vector
+ auto code = threadIdx.x; // each thread takes care of one possible code
+
+ // compute the objective value by look-up tables
+ KVPair obj(0.0f, code);
+ obj.k = uterm[id * K + code];
+
+#pragma unroll
+ for (int m2 = 0; m2 < M; m2++) {
+ if (m2 == m) {
+ continue;
+ }
+ int32_t code2 = codes[id * M + m2];
+ obj.k += bterm[m2 * K * K + code * K + code2];
+ }
+
+ // find the minimum objective value and the corresponding code
+ __syncthreads();
+ obj = blockReduceAll<KVPair, Min<KVPair>, false, false>(
+ obj, Min<KVPair>(), (KVPair*)smem);
+
+ if (code == 0) {
+ codes[id * M + m] = obj.v;
+ }
+}
+
+/** compute reconstruction error for each vector
+ *
+ * decoded_x[i] = \sum codebooks[m][codes[i][m]], m = 1,..,M
+ * obj[i] = ||x[i] - decoded_x[i]||^2
+ *
+ * @param x input vectors, size [n, dims]
+ * @param codebooks codebooks, size [M, K, dims]
+ * @param codes vector codes, size [n, M]
+ * @param obj output reconstruction errors, size [n]
+ * @param n number of input vectors
+ * @param K number of codewords in a codebook
+ * @param M number of codebooks
+ */
+__global__ void runEvaluation(
+ const float* x,
+ const float* codebooks,
+ const int32_t* codes,
+ float* obj, // output
+ int n,
+ int M,
+ int K,
+ int dims) {
+ auto id = blockIdx.x; // each block takes care of one vector
+ auto d = threadIdx.x; // each thread takes care of one dimension
+ float acc = 0.0f;
+
+#pragma unroll
+ for (int m = 0; m < M; m++) {
+ int32_t code = codes[id * M + m];
+ acc += codebooks[m * K * dims + code * dims + d];
+ }
+
+ acc -= x[id * dims + d];
+ acc = acc * acc;
+
+ // sum values of all dimensions together
+ __syncthreads();
+ acc = blockReduceAllSum<float, false, false>(acc, (float*)smem);
+
+ if (d == 0) {
+ obj[id] = acc;
+ }
+}
+
+/** perturb vector codes
+ *
+ * repeat nperts times:
+ * codes[i][randint(0, M)] = randint(0, K)
+ *
+ * @param seed random seed
+ * @param codes vector codes, size [n, M]
+ * @param n number of input vectors
+ * @param M number of codebooks
+ * @param K number of codewords in a codebook
+ * @param nperts number of subcode to be perturbed in a vector
+ */
+__global__ void runCodesPerturbation(
+ int seed,
+ int32_t* codes,
+ int n,
+ int M,
+ int K,
+ int nperts) {
+ // each thread takes care of one vector
+ auto id = blockIdx.x * blockDim.x + threadIdx.x;
+
+ if (id >= n) {
+ return;
+ }
+
+ // we have to initialize the state
+ curandState_t state;
+ curand_init(seed, id, 0, &state);
+
+ for (int i = 0; i < nperts; i++) {
+ int pos = int(curand_uniform(&state) * M);
+ int32_t val = int32_t(curand_uniform(&state) * K);
+ codes[id * M + pos] = val;
+ }
+}
+
+/** select the best codes by reconstruction errors
+ *
+ * if objs[i] < best_objs[i]:
+ * best_objs[i] = objs[i]
+ * best_codes[i] = codes[i]
+ *
+ * @param bestCodes the best codes we've encountered, size [n, M]
+ * @param bestObjs min reconstruction errors we've encountered, size [n]
+ * @param codes input vector codes, size [n, M]
+ * @param objs reconstruction errors of input vector codes, size [n]
+ * @param n number of input vectors
+ */
+__global__ void runCodesSelection(
+ int32_t* bestCodes,
+ float* bestObjs,
+ const int32_t* codes,
+ const float* objs,
+ int n,
+ int M) {
+ // each thread takes care of one vector
+ auto id = blockIdx.x * blockDim.x + threadIdx.x;
+
+ if (id >= n || objs[id] >= bestObjs[id]) {
+ return;
+ }
+
+ bestObjs[id] = objs[id];
+#pragma unroll
+ for (int m = 0; m < M; m++) {
+ bestCodes[id * M + m] = codes[id * M + m];
+ }
+}
+
+/** add L2 norm of codewords in a codebook to the unary terms
+ *
+ * uterm[i][k] = norm[k]
+ *
+ * @param uterm unary terms, size [n, K]
+ * @param norm L2 norm of each codeword in a codebook, size [K]
+ * @param K number of codewords in a codebook
+ */
+__global__ void runNormAddition(float* uterm, const float* norm, int K) {
+ auto id = blockIdx.x;
+ auto code = threadIdx.x;
+
+ uterm[id * K + code] += norm[code];
+}
+
+IcmEncoderImpl::IcmEncoderImpl(
+ int M,
+ int K,
+ int dims,
+ GpuResourcesProvider* prov,
+ int device)
+ : M(M), K(K), dims(dims), prov(prov), device(device) {
+ res = prov->getResources();
+}
+
+void IcmEncoderImpl::computeUnaryTerms(
+ float* uterm, // output, [M, n, K]
+ const float* x, // [n, d]
+ const float* codebooks, // [M, K, d]
+ int n) const {
+ auto stream = res->getDefaultStreamCurrentDevice();
+ auto handle = res->getBlasHandleCurrentDevice();
+
+ DeviceTensor<float, 2, true> vecs(const_cast<float*>(x), {n, dims});
+ for (int m = 0; m < M; m++) {
+ auto cPtr = const_cast<float*>(codebooks + m * K * dims);
+ auto bPtr = uterm + m * n * K;
+ DeviceTensor<float, 2, true> ci(cPtr, {K, dims});
+ DeviceTensor<float, 2, true> bi(bPtr, {n, K});
+ runMatrixMult(
+ bi, false, vecs, false, ci, true, -2.0f, 0.0f, handle, stream);
+ }
+
+ DeviceTensor<float, 2, true> c(
+ const_cast<float*>(codebooks), {M * K, dims});
+ DeviceTensor<float, 1, true> norm(
+ res.get(), makeTempAlloc(AllocType::Other, stream), {M * K});
+ runL2Norm(c, true, norm, true, stream);
+
+ for (int m = 0; m < M; m++) {
+ auto uPtr = uterm + m * n * K;
+ auto nPtr = norm.data() + m * K;
+ runNormAddition<<<n, K, 0, stream>>>(uPtr, nPtr, K);
+ }
+}
+
+void IcmEncoderImpl::computeBinaryTerms(float* bterm, const float* codebooks)
+ const {
+ auto stream = res->getDefaultStreamCurrentDevice();
+ auto handle = res->getBlasHandleCurrentDevice();
+
+ for (int m1 = 0; m1 < M; m1++) {
+ for (int m2 = 0; m2 < M; m2++) {
+ auto ptr1 = const_cast<float*>(codebooks + m1 * K * dims);
+ auto ptr2 = const_cast<float*>(codebooks + m2 * K * dims);
+ auto ptr3 = bterm + m1 * M * K * K + m2 * K * K;
+ DeviceTensor<float, 2, true> c1(ptr1, {K, dims});
+ DeviceTensor<float, 2, true> c2(ptr2, {K, dims});
+ DeviceTensor<float, 2, true> b(ptr3, {K, K});
+ runMatrixMult(
+ b, false, c1, false, c2, true, 2.0f, 0.0f, handle, stream);
+ }
+ }
+}
+
+void IcmEncoderImpl::setBinaryTerm(const float* codebooksHost) {
+ DeviceScope scope(device);
+ auto device = getCurrentDevice();
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ // copy from host to device memory
+ codebooks = toDeviceNonTemporary<float, 3>(
+ res.get(),
+ device,
+ const_cast<float*>(codebooksHost),
+ stream,
+ {M, K, dims});
+ bterm = DeviceTensor<float, 4, true>(
+ res.get(), makeDevAlloc(AllocType::Other, stream), {M, M, K, K});
+ computeBinaryTerms(bterm.data(), codebooks.data());
+}
+
+void IcmEncoderImpl::encode(
+ int32_t* codesHost,
+ const float* xHost,
+ const float* codebooksHost,
+ std::mt19937& gen,
+ int n,
+ int nperts,
+ int ilsIters,
+ int icmIters) const {
+ DeviceScope scope(device);
+ auto device = getCurrentDevice();
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ // copy from host to device memory
+ auto codes = toDeviceTemporary<int32_t, 2>(
+ res.get(), device, const_cast<int32_t*>(codesHost), stream, {n, M});
+ auto x = toDeviceTemporary<float, 2>(
+ res.get(), device, const_cast<float*>(xHost), stream, {n, dims});
+
+ // compute unary terms
+ DeviceTensor<float, 3, true> uterm(
+ res.get(), makeTempAlloc(AllocType::Other, stream), {M, n, K});
+ computeUnaryTerms(uterm.data(), x.data(), codebooks.data(), n);
+
+ DeviceTensor<int32_t, 2, true> bestCodes(
+ res.get(), makeTempAlloc(AllocType::Other, stream), {n, M});
+ fromDevice<int32_t, 2>(codes, bestCodes.data(), stream);
+
+ DeviceTensor<float, 1, true> bestObjs(
+ res.get(), makeTempAlloc(AllocType::Other, stream), {n});
+
+ DeviceTensor<float, 1, true> objs(
+ res.get(), makeTempAlloc(AllocType::Other, stream), {n});
+
+ // compute how much shared memory we need
+ int warpSize = getWarpSizeCurrentDevice();
+ const int evaluateSmem = sizeof(float) * (dims + warpSize - 1) / warpSize;
+ const int encodeSmem =
+ sizeof(Pair<float, int>) * (K + warpSize - 1) / warpSize;
+
+ // compute the reconstruction error for each vector
+ runEvaluation<<<n, dims, evaluateSmem, stream>>>(
+ x.data(),
+ codebooks.data(),
+ codes.data(),
+ bestObjs.data(),
+ n,
+ M,
+ K,
+ dims);
+
+ int blockSize = 256;
+ int numBlocks = (n + blockSize - 1) / blockSize;
+
+ for (int i = 0; i < ilsIters; i++) {
+ runCodesPerturbation<<<numBlocks, blockSize, 0, stream>>>(
+ gen(), codes.data(), n, M, K, nperts);
+
+ // perform icm encoding
+ for (int j = 0; j < icmIters; j++) {
+ for (int m = 0; m < M; m++) {
+ runIcmEncodeStep<<<n, K, encodeSmem, stream>>>(
+ uterm[m].data(),
+ bterm[m].data(),
+ codes.data(),
+ M,
+ K,
+ m);
+ }
+ }
+
+ // compute the reconstruction error for each vector given codes
+ runEvaluation<<<n, dims, evaluateSmem, stream>>>(
+ x.data(),
+ codebooks.data(),
+ codes.data(),
+ objs.data(),
+ n,
+ M,
+ K,
+ dims);
+
+ // if objs[i] < best_objs[i], replace best_codes[i] with codes[i]
+ runCodesSelection<<<numBlocks, blockSize, 0, stream>>>(
+ bestCodes.data(),
+ bestObjs.data(),
+ codes.data(),
+ objs.data(),
+ n,
+ M);
+
+ codes.copyFrom(bestCodes, stream);
+ }
+
+ // copy back to host memory
+ fromDevice<int32_t, 2>(bestCodes, codesHost, stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IcmEncoder.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IcmEncoder.cuh
new file mode 100644
index 0000000..7e3171c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IcmEncoder.cuh
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+
+#include <random>
+
+namespace faiss {
+namespace gpu {
+
+struct IcmEncoderImpl {
+ int M; ///< number of codebooks
+ int K; ///< number of codewords in a codebook
+ int dims; ///< dimensions of a codeword
+
+ GpuResourcesProvider* prov;
+ std::shared_ptr<GpuResources> res;
+ int device;
+
+ DeviceTensor<float, 4, true> bterm; ///< bianry terms, size [M, M, K, K]
+ DeviceTensor<float, 3, true> codebooks; ///< codebooks, size [M, K, dims]
+
+ IcmEncoderImpl(
+ int M,
+ int K,
+ int dims,
+ GpuResourcesProvider* prov,
+ int device);
+
+ ~IcmEncoderImpl() {}
+
+ ///< copy codebooks to device memory and compute unary terms
+ void setBinaryTerm(const float* codebooks);
+
+ /** Compute unary terms.
+ *
+ * uterm[i] = x * codebook[i]^T, i = 1,...,M
+ *
+ * @param uterm output unary terms, size [M, n, K]
+ * @param x input vectors, size [n, dims]
+ * @param codebooks codebooks, size [M, K, dims]
+ * @param n number of input vectors
+ */
+ void computeUnaryTerms(
+ float* bterm,
+ const float* x,
+ const float* codebooks,
+ int n) const;
+
+ /** Compute binary terms.
+ *
+ * bterm[i][j] = codebooks[i] * codebooks[j]^T. i, j = 1,...,M
+ *
+ * @param bterm output binary terms, size [M, M, K, K]
+ * @param codebooks codebooks, size [M, K, dims]
+ */
+ void computeBinaryTerms(float* bterm, const float* codebooks) const;
+
+ ///< icm encode method
+ void encode(
+ int32_t* codes,
+ const float* x,
+ const float* codebooks,
+ std::mt19937& gen,
+ int n,
+ int nperts,
+ int ilsIters,
+ int icmIters) const;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IndexUtils.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IndexUtils.cu
new file mode 100644
index 0000000..013c00b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IndexUtils.cu
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+/// A collection of various utility functions for index implementation
+
+/// Returns the maximum k-selection value supported based on the CUDA SDK that
+/// we were compiled with. .cu files can use DeviceDefs.cuh, but this is for
+/// non-CUDA files
+int getMaxKSelection() {
+ return GPU_MAX_SELECTION_K;
+}
+
+void validateKSelect(int k) {
+ FAISS_THROW_IF_NOT_FMT(
+ k > 0 && k <= getMaxKSelection(),
+ "GPU index only supports min/max-K selection up to %d (requested %d)",
+ getMaxKSelection(),
+ k);
+}
+
+void validateNProbe(size_t nprobe) {
+ FAISS_THROW_IF_NOT_FMT(
+ nprobe > 0 && nprobe <= (size_t)getMaxKSelection(),
+ "GPU IVF index only supports nprobe selection up to %d (requested %zu)",
+ getMaxKSelection(),
+ nprobe);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IndexUtils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IndexUtils.h
new file mode 100644
index 0000000..7d930f1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/IndexUtils.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+
+namespace faiss {
+namespace gpu {
+
+/// A collection of various utility functions for index implementation
+
+/// Returns the maximum k-selection value supported based on the CUDA SDK that
+/// we were compiled with. .cu files can use DeviceDefs.cuh, but this is for
+/// non-CUDA files
+int getMaxKSelection();
+
+// Validate the k parameter for search
+void validateKSelect(int k);
+
+// Validate the nprobe parameter for search
+void validateNProbe(size_t nprobe);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/InterleavedCodes.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/InterleavedCodes.cpp
new file mode 100644
index 0000000..6bb2c05
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/InterleavedCodes.cpp
@@ -0,0 +1,564 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/InterleavedCodes.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+namespace gpu {
+
+inline uint8_t unpack5(int i, uint8_t vLower, uint8_t vUpper) {
+ uint8_t v = 0;
+
+ // lsb ... msb
+ // 0: 0 0 0 0 0 1 1 1
+ // 1: 1 1 2 2 2 2 2 3
+ // 2: 3 3 3 3 4 4 4 4
+ // 3: 4 5 5 5 5 5 6 6
+ // 4: 6 6 6 7 7 7 7 7
+ switch (i % 8) {
+ case 0:
+ // 5 lsbs of lower
+ v = vLower & 0x1f;
+ break;
+ case 1:
+ // 3 msbs of lower as v lsbs
+ // 2 msbs of upper as v msbs
+ v = (vLower >> 5) | ((vUpper & 0x3) << 3);
+ break;
+ case 2:
+ // 5 of lower
+ v = (vLower >> 2) & 0x1f;
+ break;
+ case 3:
+ // 1 msbs of lower as v lsbs
+ // 4 lsbs of upper as v msbs
+ v = (vLower >> 7) | ((vUpper & 0xf) << 1);
+ break;
+ case 4:
+ // 4 msbs of lower as v lsbs
+ // 1 lsbs of upper as v msbs
+ v = (vLower >> 4) | ((vUpper & 0x1) << 4);
+ break;
+ case 5:
+ // 5 of lower
+ v = (vLower >> 1) & 0x1f;
+ break;
+ case 6:
+ // 2 msbs of lower as v lsbs
+ // 3 lsbs of upper as v msbs
+ v = (vLower >> 6) | ((vUpper & 0x7) << 2);
+ break;
+ case 7:
+ // 5 of lower
+ v = (vLower >> 3);
+ break;
+ }
+
+ return v;
+}
+
+inline uint8_t unpack6(int i, uint8_t vLower, uint8_t vUpper) {
+ uint8_t v = 0;
+
+ switch (i % 4) {
+ case 0:
+ // 6 lsbs of lower
+ v = vLower & 0x3f;
+ break;
+ case 1:
+ // 2 msbs of lower as v lsbs
+ // 4 lsbs of upper as v msbs
+ v = (vLower >> 6) | ((vUpper & 0xf) << 2);
+ break;
+ case 2:
+ // 4 msbs of lower as v lsbs
+ // 2 lsbs of upper as v msbs
+ v = (vLower >> 4) | ((vUpper & 0x3) << 4);
+ break;
+ case 3:
+ // 6 msbs of lower
+ v = (vLower >> 2);
+ break;
+ }
+
+ return v;
+}
+
+std::vector<uint8_t> unpackNonInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode) {
+ int srcVecSize = utils::divUp(dims * bitsPerCode, 8);
+ FAISS_ASSERT(data.size() == numVecs * srcVecSize);
+
+ if (bitsPerCode == 8 || bitsPerCode == 16 || bitsPerCode == 32) {
+ // nothing to do
+ return data;
+ }
+
+ // bit codes padded to whole bytes
+ std::vector<uint8_t> out(numVecs * dims * utils::divUp(bitsPerCode, 8));
+
+ if (bitsPerCode == 4) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ int srcIdx = i * srcVecSize + (j / 2);
+ FAISS_ASSERT(srcIdx < data.size());
+
+ uint8_t v = data[srcIdx];
+ v = (j % 2 == 0) ? v & 0xf : v >> 4;
+
+ out[i * dims + j] = v;
+ }
+ }
+ } else if (bitsPerCode == 5) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ int lo = i * srcVecSize + (j * 5) / 8;
+ int hi = lo + 1;
+
+ FAISS_ASSERT(lo < data.size());
+ FAISS_ASSERT(hi <= data.size());
+
+ auto vLower = data[lo];
+ auto vUpper = hi < data.size() ? data[hi] : 0;
+
+ out[i * dims + j] = unpack5(j, vLower, vUpper);
+ }
+ }
+ } else if (bitsPerCode == 6) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ int lo = i * srcVecSize + (j * 6) / 8;
+ int hi = lo + 1;
+
+ FAISS_ASSERT(lo < data.size());
+ FAISS_ASSERT(hi <= data.size());
+
+ auto vLower = data[lo];
+ auto vUpper = hi < data.size() ? data[hi] : 0;
+
+ out[i * dims + j] = unpack6(j, vLower, vUpper);
+ }
+ }
+ } else {
+ // unhandled
+ FAISS_ASSERT(false);
+ }
+
+ return out;
+}
+
+template <typename T>
+void unpackInterleavedWord(
+ const T* in,
+ T* out,
+ int numVecs,
+ int dims,
+ int bitsPerCode) {
+ int warpSize = getWarpSizeCurrentDevice();
+ int wordsPerDimBlock = (size_t)warpSize * bitsPerCode / (8 * sizeof(T));
+ int wordsPerBlock = wordsPerDimBlock * dims;
+ int numBlocks = utils::divUp(numVecs, warpSize);
+
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ int block = i / warpSize;
+ FAISS_ASSERT(block < numBlocks);
+ int lane = i % warpSize;
+
+ for (int j = 0; j < dims; ++j) {
+ int srcOffset = block * wordsPerBlock + j * wordsPerDimBlock + lane;
+ out[i * dims + j] = in[srcOffset];
+ }
+ }
+}
+
+std::vector<uint8_t> unpackInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode) {
+ int warpSize = getWarpSizeCurrentDevice();
+ int bytesPerDimBlock = warpSize * bitsPerCode / 8;
+ int bytesPerBlock = bytesPerDimBlock * dims;
+ int numBlocks = utils::divUp(numVecs, warpSize);
+ size_t totalSize = (size_t)bytesPerBlock * numBlocks;
+ FAISS_ASSERT(data.size() == totalSize);
+
+ // bit codes padded to whole bytes
+ std::vector<uint8_t> out(numVecs * dims * utils::divUp(bitsPerCode, 8));
+
+ if (bitsPerCode == 8) {
+ unpackInterleavedWord<uint8_t>(
+ data.data(), out.data(), numVecs, dims, bitsPerCode);
+ } else if (bitsPerCode == 16) {
+ unpackInterleavedWord<uint16_t>(
+ (uint16_t*)data.data(),
+ (uint16_t*)out.data(),
+ numVecs,
+ dims,
+ bitsPerCode);
+ } else if (bitsPerCode == 32) {
+ unpackInterleavedWord<uint32_t>(
+ (uint32_t*)data.data(),
+ (uint32_t*)out.data(),
+ numVecs,
+ dims,
+ bitsPerCode);
+ } else if (bitsPerCode == 4) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ int block = i / warpSize;
+ int lane = i % warpSize;
+
+ int word = lane / 2;
+ int subWord = lane % 2;
+
+ for (int j = 0; j < dims; ++j) {
+ auto v =
+ data[block * bytesPerBlock + j * bytesPerDimBlock +
+ word];
+
+ v = (subWord == 0) ? v & 0xf : v >> 4;
+ out[i * dims + j] = v;
+ }
+ }
+ } else if (bitsPerCode == 5) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ int block = i / warpSize;
+ int blockVector = i % warpSize;
+
+ for (int j = 0; j < dims; ++j) {
+ uint8_t* dimBlock =
+ &data[block * bytesPerBlock + j * bytesPerDimBlock];
+
+ int lo = (blockVector * 5) / 8;
+ int hi = lo + 1;
+
+ FAISS_ASSERT(lo < bytesPerDimBlock);
+ FAISS_ASSERT(hi <= bytesPerDimBlock);
+
+ auto vLower = dimBlock[lo];
+ auto vUpper = hi < bytesPerDimBlock ? dimBlock[hi] : 0;
+
+ out[i * dims + j] = unpack5(blockVector, vLower, vUpper);
+ }
+ }
+ } else if (bitsPerCode == 6) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ int block = i / warpSize;
+ int blockVector = i % warpSize;
+
+ for (int j = 0; j < dims; ++j) {
+ uint8_t* dimBlock =
+ &data[block * bytesPerBlock + j * bytesPerDimBlock];
+
+ int lo = (blockVector * 6) / 8;
+ int hi = lo + 1;
+
+ FAISS_ASSERT(lo < bytesPerDimBlock);
+ FAISS_ASSERT(hi <= bytesPerDimBlock);
+
+ auto vLower = dimBlock[lo];
+ auto vUpper = hi < bytesPerDimBlock ? dimBlock[hi] : 0;
+
+ out[i * dims + j] = unpack6(blockVector, vLower, vUpper);
+ }
+ }
+ } else {
+ // unimplemented
+ FAISS_ASSERT(false);
+ }
+
+ return out;
+}
+
+inline uint8_t pack5(int i, uint8_t lo, uint8_t hi, uint8_t hi2) {
+ FAISS_ASSERT((lo & 0x1f) == lo);
+ FAISS_ASSERT((hi & 0x1f) == hi);
+ FAISS_ASSERT((hi2 & 0x1f) == hi2);
+
+ uint8_t v = 0;
+
+ // lsb ... msb
+ // 0: 0 0 0 0 0 1 1 1
+ // 1: 1 1 2 2 2 2 2 3
+ // 2: 3 3 3 3 4 4 4 4
+ // 3: 4 5 5 5 5 5 6 6
+ // 4: 6 6 6 7 7 7 7 7
+ switch (i % 5) {
+ case 0:
+ // 5 msbs of lower as vOut lsbs
+ // 3 lsbs of upper as vOut msbs
+ v = (lo & 0x1f) | (hi << 5);
+ break;
+ case 1:
+ // 2 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ // 1 lsbs of upper2 as vOut msb
+ v = (lo >> 3) | (hi << 2) | (hi2 << 7);
+ break;
+ case 2:
+ // 4 msbs of lower as vOut lsbs
+ // 4 lsbs of upper as vOut msbs
+ v = (lo >> 1) | (hi << 4);
+ break;
+ case 3:
+ // 1 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ // 2 lsbs of upper2 as vOut msb
+ v = (lo >> 4) | (hi << 1) | (hi2 << 6);
+ break;
+ case 4:
+ // 3 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ v = (lo >> 2) | (hi << 3);
+ break;
+ }
+
+ return v;
+}
+
+inline uint8_t pack6(int i, uint8_t lo, uint8_t hi) {
+ FAISS_ASSERT((lo & 0x3f) == lo);
+ FAISS_ASSERT((hi & 0x3f) == hi);
+
+ uint8_t v = 0;
+
+ // lsb ... msb
+ // 0: 0 0 0 0 0 0 1 1
+ // 1: 1 1 1 1 2 2 2 2
+ // 2: 2 2 3 3 3 3 3 3
+ switch (i % 3) {
+ case 0:
+ // 6 msbs of lower as vOut lsbs
+ // 2 lsbs of upper as vOut msbs
+ v = (lo & 0x3f) | (hi << 6);
+ break;
+ case 1:
+ // 4 msbs of lower as vOut lsbs
+ // 4 lsbs of upper as vOut msbs
+ v = (lo >> 2) | (hi << 4);
+ break;
+ case 2:
+ // 2 msbs of lower as vOut lsbs
+ // 6 lsbs of upper as vOut msbs
+ v = (lo >> 4) | (hi << 2);
+ break;
+ }
+
+ return v;
+}
+
+std::vector<uint8_t> packNonInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode) {
+ // bit codes padded to whole bytes
+ FAISS_ASSERT(data.size() == numVecs * dims * utils::divUp(bitsPerCode, 8));
+
+ if (bitsPerCode == 8 || bitsPerCode == 16 || bitsPerCode == 32) {
+ // nothing to do, whole words are already where they need to be
+ return data;
+ }
+
+ // bits packed into a whole number of bytes
+ int bytesPerVec = utils::divUp(dims * bitsPerCode, 8);
+
+ std::vector<uint8_t> out(numVecs * bytesPerVec);
+
+ if (bitsPerCode == 4) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ for (int j = 0; j < bytesPerVec; ++j) {
+ int dimLo = j * 2;
+ int dimHi = dimLo + 1;
+ FAISS_ASSERT(dimLo < dims);
+ FAISS_ASSERT(dimHi <= dims);
+
+ uint8_t lo = data[i * dims + dimLo];
+ uint8_t hi = dimHi < dims ? data[i * dims + dimHi] : 0;
+
+ out[i * bytesPerVec + j] = (hi << 4) | (lo & 0xf);
+ }
+ }
+ } else if (bitsPerCode == 5) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ for (int j = 0; j < bytesPerVec; ++j) {
+ int dimLo = (j * 8) / 5;
+ int dimHi = dimLo + 1;
+ int dimHi2 = dimHi + 1;
+ FAISS_ASSERT(dimLo < dims);
+ FAISS_ASSERT(dimHi <= dims);
+ FAISS_ASSERT(dimHi <= dims + 1);
+
+ uint8_t lo = data[i * dims + dimLo];
+ uint8_t hi = dimHi < dims ? data[i * dims + dimHi] : 0;
+ uint8_t hi2 = dimHi2 < dims ? data[i * dims + dimHi2] : 0;
+
+ out[i * bytesPerVec + j] = pack5(j, lo, hi, hi2);
+ }
+ }
+ } else if (bitsPerCode == 6) {
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ for (int j = 0; j < bytesPerVec; ++j) {
+ int dimLo = (j * 8) / 6;
+ int dimHi = dimLo + 1;
+ FAISS_ASSERT(dimLo < dims);
+ FAISS_ASSERT(dimHi <= dims);
+
+ uint8_t lo = data[i * dims + dimLo];
+ uint8_t hi = dimHi < dims ? data[i * dims + dimHi] : 0;
+
+ out[i * bytesPerVec + j] = pack6(j, lo, hi);
+ }
+ }
+ } else {
+ // unhandled
+ FAISS_ASSERT(false);
+ }
+
+ return out;
+}
+
+template <typename T>
+void packInterleavedWord(
+ const T* in,
+ T* out,
+ int numVecs,
+ int dims,
+ int bitsPerCode) {
+ int warpSize = getWarpSizeCurrentDevice();
+ int wordsPerDimBlock = (size_t)warpSize * bitsPerCode / (8 * sizeof(T));
+ int wordsPerBlock = wordsPerDimBlock * dims;
+ int numBlocks = utils::divUp(numVecs, warpSize);
+
+ // We're guaranteed that all other slots not filled by the vectors present
+ // are initialized to zero (from the vector constructor in packInterleaved)
+#pragma omp parallel for
+ for (int i = 0; i < numVecs; ++i) {
+ int block = i / warpSize;
+ FAISS_ASSERT(block < numBlocks);
+ int lane = i % warpSize;
+
+ for (int j = 0; j < dims; ++j) {
+ int dstOffset = block * wordsPerBlock + j * wordsPerDimBlock + lane;
+ out[dstOffset] = in[i * dims + j];
+ }
+ }
+}
+
+std::vector<uint8_t> packInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode) {
+ int warpSize = getWarpSizeCurrentDevice();
+ int bytesPerDimBlock = warpSize * bitsPerCode / 8;
+ int bytesPerBlock = bytesPerDimBlock * dims;
+ int numBlocks = utils::divUp(numVecs, warpSize);
+ size_t totalSize = (size_t)bytesPerBlock * numBlocks;
+
+ // bit codes padded to whole bytes
+ FAISS_ASSERT(data.size() == numVecs * dims * utils::divUp(bitsPerCode, 8));
+
+ // packs based on blocks
+ std::vector<uint8_t> out(totalSize, 0);
+
+ if (bitsPerCode == 8) {
+ packInterleavedWord<uint8_t>(
+ data.data(), out.data(), numVecs, dims, bitsPerCode);
+ } else if (bitsPerCode == 16) {
+ packInterleavedWord<uint16_t>(
+ (uint16_t*)data.data(),
+ (uint16_t*)out.data(),
+ numVecs,
+ dims,
+ bitsPerCode);
+ } else if (bitsPerCode == 32) {
+ packInterleavedWord<uint32_t>(
+ (uint32_t*)data.data(),
+ (uint32_t*)out.data(),
+ numVecs,
+ dims,
+ bitsPerCode);
+ } else if (bitsPerCode == 4) {
+#pragma omp parallel for
+ for (int i = 0; i < numBlocks; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ for (int k = 0; k < bytesPerDimBlock; ++k) {
+ int loVec = i * warpSize + k * 2;
+ int hiVec = loVec + 1;
+
+ uint8_t lo = loVec < numVecs ? data[loVec * dims + j] : 0;
+ uint8_t hi = hiVec < numVecs ? data[hiVec * dims + j] : 0;
+
+ out[i * bytesPerBlock + j * bytesPerDimBlock + k] =
+ (hi << 4) | (lo & 0xf);
+ }
+ }
+ }
+ } else if (bitsPerCode == 5) {
+#pragma omp parallel for
+ for (int i = 0; i < numBlocks; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ for (int k = 0; k < bytesPerDimBlock; ++k) {
+ // What input vectors we are pulling from
+ int loVec = i * warpSize + (k * 8) / 5;
+ int hiVec = loVec + 1;
+ int hiVec2 = hiVec + 1;
+
+ uint8_t lo = loVec < numVecs ? data[loVec * dims + j] : 0;
+ uint8_t hi = hiVec < numVecs ? data[hiVec * dims + j] : 0;
+ uint8_t hi2 =
+ hiVec2 < numVecs ? data[hiVec2 * dims + j] : 0;
+
+ out[i * bytesPerBlock + j * bytesPerDimBlock + k] =
+ pack5(k, lo, hi, hi2);
+ }
+ }
+ }
+ } else if (bitsPerCode == 6) {
+#pragma omp parallel for
+ for (int i = 0; i < numBlocks; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ for (int k = 0; k < bytesPerDimBlock; ++k) {
+ // What input vectors we are pulling from
+ int loVec = i * warpSize + (k * 8) / 6;
+ int hiVec = loVec + 1;
+
+ uint8_t lo = loVec < numVecs ? data[loVec * dims + j] : 0;
+ uint8_t hi = hiVec < numVecs ? data[hiVec * dims + j] : 0;
+
+ out[i * bytesPerBlock + j * bytesPerDimBlock + k] =
+ pack6(k, lo, hi);
+ }
+ }
+ }
+ } else {
+ // unimplemented
+ FAISS_ASSERT(false);
+ }
+
+ return out;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/InterleavedCodes.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/InterleavedCodes.h
new file mode 100644
index 0000000..2badce1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/InterleavedCodes.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <vector>
+
+// Utilities for bit packing and unpacking CPU non-interleaved and GPU
+// interleaved by 32 encodings
+namespace faiss {
+namespace gpu {
+
+// Unpacks arbitrary bitwidth codes to a whole number of bytes per code
+// The layout of the input is (v0 d0)(v0 d1) ... (v0 dD)(v1 d0) ...
+// (bit packed)
+// The layout of the output is the same (byte packed to roundUp(bitsPerCode, 8)
+// / 8 bytes)
+std::vector<uint8_t> unpackNonInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode);
+
+// Unpacks arbitrary bitwidth codes to a whole number of bytes per scalar code
+// The layout of the input is (v0 d0)(v1 d0) ... (v31 d0)(v0 d1) ...
+// (bit packed)
+// The layout of the input is (v0 d0)(v0 d1) ... (v0 dD)(v1 d0) ...
+// (byte packed)
+std::vector<uint8_t> unpackInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode);
+
+// Packs data in the byte packed non-interleaved form to bit packed
+// non-interleaved form
+std::vector<uint8_t> packNonInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode);
+
+// Packs data in the byte packed non-interleaved form to bit packed
+// interleaved form
+std::vector<uint8_t> packInterleaved(
+ std::vector<uint8_t> data,
+ int numVecs,
+ int dims,
+ int bitsPerCode);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Norm.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Norm.cu
new file mode 100644
index 0000000..0e65015
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Norm.cu
@@ -0,0 +1,289 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/impl/L2Norm.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/Reductions.cuh>
+
+#include <algorithm>
+
+namespace faiss {
+namespace gpu {
+
+// Input: (batch x dim)
+// Output: (batch norm)
+// Done under the presumption that the dimension size is not too large
+// (<10k or so), since there wouldn't be enough parallelism applying a
+// single block to the problem. Also that each vector is large enough
+// (>64), since a single block works on multiple rows' norms at the
+// same time.
+// T: the type we are doing the math in (e.g., float, half)
+// TVec: the potentially vectorized type we are loading in (e.g.,
+// float4, half2)
+template <typename T, typename TVec, int RowTileSize, bool NormSquared>
+__global__ void l2NormRowMajor(
+ Tensor<TVec, 2, true> input,
+ Tensor<float, 1, true> output) {
+ extern __shared__ char smemByte[]; // #warps * RowTileSize elements
+ float* smem = (float*)smemByte;
+
+ // these are fine to be int (just based on block dimensions)
+ int numWarps = utils::divUp(blockDim.x, kWarpSize);
+ int laneId = getLaneId();
+ auto warpId = threadIdx.x / kWarpSize;
+
+ bool lastRowTile = (blockIdx.x == (gridDim.x - 1));
+ idx_t rowStart = idx_t(blockIdx.x) * RowTileSize;
+ // accumulate in f32
+ float rowNorm[RowTileSize];
+
+ if (lastRowTile) {
+ // We are handling the very end of the input matrix rows
+ for (idx_t row = 0; row < input.getSize(0) - rowStart; ++row) {
+ rowNorm[0] = 0;
+
+ for (idx_t col = threadIdx.x; col < input.getSize(1);
+ col += blockDim.x) {
+ TVec val = input[rowStart + row][col];
+ val = Math<TVec>::mul(val, val);
+ rowNorm[0] = rowNorm[0] + Math<TVec>::reduceAdd(val);
+ }
+
+ rowNorm[0] = warpReduceAllSum(rowNorm[0]);
+ if (laneId == 0) {
+ smem[row * numWarps + warpId] = rowNorm[0];
+ }
+ }
+ } else {
+ // We are guaranteed that all RowTileSize rows are available in
+ // [rowStart, rowStart + RowTileSize)
+ TVec tmp[RowTileSize];
+
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ rowNorm[row] = 0;
+ }
+
+ for (idx_t col = threadIdx.x; col < input.getSize(1);
+ col += blockDim.x) {
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ tmp[row] = input[rowStart + row][col];
+ }
+
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ tmp[row] = Math<TVec>::mul(tmp[row], tmp[row]);
+ }
+
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ rowNorm[row] = rowNorm[row] + Math<TVec>::reduceAdd(tmp[row]);
+ }
+ }
+
+ // Sum up all parts in each warp
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ rowNorm[row] = warpReduceAllSum(rowNorm[row]);
+ }
+
+ if (laneId == 0) {
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ smem[row * numWarps + warpId] = rowNorm[row];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ // Sum across warps
+ if (warpId == 0) {
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ rowNorm[row] =
+ laneId < numWarps ? smem[row * numWarps + laneId] : 0;
+ }
+
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ rowNorm[row] = warpReduceAllSum(rowNorm[row]);
+ }
+
+ // Write out answer
+ if (laneId == 0) {
+#pragma unroll
+ for (int row = 0; row < RowTileSize; ++row) {
+ idx_t outCol = rowStart + row;
+
+ if (lastRowTile) {
+ if (outCol < output.getSize(0)) {
+ output[outCol] = NormSquared
+ ? ConvertTo<float>::to(rowNorm[row])
+ : sqrtf(ConvertTo<float>::to(rowNorm[row]));
+ }
+ } else {
+ output[outCol] = NormSquared
+ ? ConvertTo<float>::to(rowNorm[row])
+ : sqrtf(ConvertTo<float>::to(rowNorm[row]));
+ }
+ }
+ }
+ }
+}
+
+// Input: (dim x batch)
+// Output: (batch norm)
+// Handles the case where `input` is column major. A single thread calculates
+// the norm of each vector instead of a block-wide reduction.
+template <typename T, bool NormSquared>
+__global__ void l2NormColMajor(
+ Tensor<T, 2, true> input,
+ Tensor<float, 1, true> output) {
+ // grid-stride loop to handle all batch elements
+ for (idx_t batch = idx_t(blockIdx.x) * blockDim.x + threadIdx.x;
+ batch < input.getSize(1);
+ batch += gridDim.x * blockDim.x) {
+ float sum = 0;
+
+ // This is still a coalesced load from the memory
+ for (idx_t dim = 0; dim < input.getSize(0); ++dim) {
+ // Just do the math in float32, even if the input is float16
+ float v = ConvertTo<float>::to(input[dim][batch]);
+ sum += v * v;
+ }
+
+ if (!NormSquared) {
+ sum = sqrtf(sum);
+ }
+
+ output[batch] = ConvertTo<float>::to(sum);
+ }
+}
+
+template <typename T, typename TVec>
+void runL2Norm(
+ Tensor<T, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream) {
+ idx_t maxThreads = (idx_t)getMaxThreadsCurrentDevice();
+ constexpr int rowTileSize = 8;
+
+#define RUN_L2_ROW_MAJOR(TYPE_T, TYPE_TVEC, INPUT) \
+ do { \
+ if (normSquared) { \
+ l2NormRowMajor<TYPE_T, TYPE_TVEC, rowTileSize, true> \
+ <<<grid, block, smem, stream>>>(INPUT, output); \
+ } else { \
+ l2NormRowMajor<TYPE_T, TYPE_TVEC, rowTileSize, false> \
+ <<<grid, block, smem, stream>>>(INPUT, output); \
+ } \
+ } while (0)
+
+ if (inputRowMajor) {
+ //
+ // Row-major kernel
+ ///
+
+ int warpSize = getWarpSizeCurrentDevice();
+ if (input.template canCastResize<TVec>()) {
+ // Can load using the vectorized type
+ auto inputV = input.template castResize<TVec>();
+ auto dim = inputV.getSize(1);
+
+ // We must always have full warps present
+ auto numThreads =
+ std::min(utils::roundUp(dim, kWarpSize), maxThreads);
+
+ auto grid = dim3(utils::divUp(inputV.getSize(0), rowTileSize));
+ auto block = dim3(numThreads);
+
+ auto smem = sizeof(float) * rowTileSize *
+ utils::divUp(numThreads, warpSize);
+
+ RUN_L2_ROW_MAJOR(T, TVec, inputV);
+ } else {
+ // Can't load using the vectorized type
+ auto dim = input.getSize(1);
+
+ // We must always have full warps present
+ auto numThreads =
+ std::min(utils::roundUp(dim, kWarpSize), maxThreads);
+
+ auto grid = dim3(utils::divUp(input.getSize(0), rowTileSize));
+ auto block = dim3(numThreads);
+
+ auto smem = sizeof(float) * rowTileSize *
+ utils::divUp(numThreads, warpSize);
+
+ RUN_L2_ROW_MAJOR(T, T, input);
+ }
+ } else {
+ //
+ // Column-major kernel
+ //
+
+ // Just use a fixed-sized block, since the kernel threads are fully
+ // independent
+ auto block = 128;
+
+ // Cap the grid size at 2^16 since there is a grid-stride loop to handle
+ // processing everything
+ auto grid = (int)std::min(
+ utils::divUp(input.getSize(1), (idx_t)block), (idx_t)65536);
+
+ if (normSquared) {
+ l2NormColMajor<T, true><<<grid, block, 0, stream>>>(input, output);
+ } else {
+ l2NormColMajor<T, false><<<grid, block, 0, stream>>>(input, output);
+ }
+ }
+
+#undef RUN_L2
+
+ CUDA_TEST_ERROR();
+}
+
+void runL2Norm(
+ Tensor<float, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream) {
+ runL2Norm<float, float4>(input, inputRowMajor, output, normSquared, stream);
+}
+
+void runL2Norm(
+ Tensor<half, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream) {
+ runL2Norm<half, half2>(input, inputRowMajor, output, normSquared, stream);
+}
+
+void runL2Norm(
+ Tensor<__nv_bfloat16, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream) {
+ runL2Norm<__nv_bfloat16, __nv_bfloat162>(
+ input, inputRowMajor, output, normSquared, stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Norm.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Norm.cuh
new file mode 100644
index 0000000..abd35fd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Norm.cuh
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+void runL2Norm(
+ Tensor<float, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream);
+
+void runL2Norm(
+ Tensor<half, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream);
+
+void runL2Norm(
+ Tensor<__nv_bfloat16, 2, true>& input,
+ bool inputRowMajor,
+ Tensor<float, 1, true>& output,
+ bool normSquared,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Select.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Select.cu
new file mode 100644
index 0000000..9c7f001
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Select.cu
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/impl/L2Select.cuh>
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/Pair.cuh>
+#include <faiss/gpu/utils/Reductions.cuh>
+#include <faiss/gpu/utils/Select.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// L2 + select kernel for k == 1, implements re-use of ||c||^2
+template <typename T, int kRowsPerBlock, int kBlockSize>
+__global__ void l2SelectMin1(
+ Tensor<T, 2, true> productDistances,
+ Tensor<T, 1, true> centroidDistances,
+ Tensor<T, 2, true> outDistances,
+ Tensor<idx_t, 2, true> outIndices) {
+ // Each block handles kRowsPerBlock rows of the distances (results)
+ Pair<T, idx_t> threadMin[kRowsPerBlock];
+ __shared__ Pair<T, idx_t>
+ blockMin[kRowsPerBlock * (kBlockSize / kWarpSize)];
+
+ T distance[kRowsPerBlock];
+
+#pragma unroll
+ for (int i = 0; i < kRowsPerBlock; ++i) {
+ threadMin[i].k = Limits<T>::getMax();
+ threadMin[i].v = -1;
+ }
+
+ // blockIdx.x: which chunk of rows we are responsible for updating
+ idx_t rowStart = idx_t(blockIdx.x) * kRowsPerBlock;
+
+ // FIXME: if we have exact multiples, don't need this
+ bool endRow = (blockIdx.x == gridDim.x - 1);
+
+ if (endRow) {
+ if (productDistances.getSize(0) % kRowsPerBlock == 0) {
+ endRow = false;
+ }
+ }
+
+ if (endRow) {
+ for (idx_t row = rowStart; row < productDistances.getSize(0); ++row) {
+ for (idx_t col = threadIdx.x; col < productDistances.getSize(1);
+ col += blockDim.x) {
+ distance[0] = Math<T>::add(
+ centroidDistances[col], productDistances[row][col]);
+
+ if (Math<T>::lt(distance[0], threadMin[0].k)) {
+ threadMin[0].k = distance[0];
+ threadMin[0].v = col;
+ }
+ }
+
+ // Reduce within the block
+ threadMin[0] = blockReduceAll<
+ Pair<T, idx_t>,
+ Min<Pair<T, idx_t>>,
+ false,
+ false>(threadMin[0], Min<Pair<T, idx_t>>(), blockMin);
+
+ if (threadIdx.x == 0) {
+ outDistances[row][0] = threadMin[0].k;
+ outIndices[row][0] = threadMin[0].v;
+ }
+
+ // so we can use the shared memory again
+ __syncthreads();
+
+ threadMin[0].k = Limits<T>::getMax();
+ threadMin[0].v = -1;
+ }
+ } else {
+ for (idx_t col = threadIdx.x; col < productDistances.getSize(1);
+ col += blockDim.x) {
+ T centroidDistance = centroidDistances[col];
+
+#pragma unroll
+ for (idx_t row = 0; row < kRowsPerBlock; ++row) {
+ distance[row] = productDistances[rowStart + row][col];
+ }
+
+#pragma unroll
+ for (idx_t row = 0; row < kRowsPerBlock; ++row) {
+ distance[row] = Math<T>::add(distance[row], centroidDistance);
+ }
+
+#pragma unroll
+ for (idx_t row = 0; row < kRowsPerBlock; ++row) {
+ if (Math<T>::lt(distance[row], threadMin[row].k)) {
+ threadMin[row].k = distance[row];
+ threadMin[row].v = col;
+ }
+ }
+ }
+
+ // Reduce within the block
+ blockReduceAll<
+ kRowsPerBlock,
+ Pair<T, idx_t>,
+ Min<Pair<T, idx_t>>,
+ false,
+ false>(threadMin, Min<Pair<T, idx_t>>(), blockMin);
+
+ if (threadIdx.x == 0) {
+#pragma unroll
+ for (idx_t row = 0; row < kRowsPerBlock; ++row) {
+ outDistances[rowStart + row][0] = threadMin[row].k;
+ outIndices[rowStart + row][0] = threadMin[row].v;
+ }
+ }
+ }
+}
+
+// L2 + select kernel for k > 1, no re-use of ||c||^2
+// IndexT is either int32_t or idx_t (int64_t) depending upon maximum sizes of
+// inputs
+template <
+ typename IndexT,
+ typename T,
+ int NumWarpQ,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+__global__ void l2SelectMinK(
+ Tensor<T, 2, true> productDistances,
+ Tensor<T, 1, true> centroidDistances,
+ Tensor<T, 2, true> outDistances,
+ Tensor<idx_t, 2, true> outIndices,
+ int k,
+ T initK) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ // Each block handles a single row of the distances (results)
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __shared__ T smemK[kNumWarps * NumWarpQ];
+ __shared__ IndexT smemV[kNumWarps * NumWarpQ];
+
+ BlockSelect<
+ T,
+ IndexT,
+ false,
+ Comparator<T>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(initK, -1, smemK, smemV, k);
+
+ IndexT row = blockIdx.x;
+
+ // Whole warps must participate in the selection
+ IndexT limit = utils::roundDown(productDistances.getSize(1), kWarpSize);
+ IndexT i = threadIdx.x;
+
+ for (; i < limit; i += blockDim.x) {
+ T v = Math<T>::add(centroidDistances[i], productDistances[row][i]);
+ heap.add(v, IndexT(i));
+ }
+
+ // Handle the remainder if any separately (warp is divergent)
+ if (i < productDistances.getSize(1)) {
+ T v = Math<T>::add(centroidDistances[i], productDistances[row][i]);
+ heap.addThreadQ(v, IndexT(i));
+ }
+
+ // Merge all final results
+ heap.reduce();
+
+ for (int i = threadIdx.x; i < k; i += blockDim.x) {
+ outDistances[row][i] = smemK[i];
+ outIndices[row][i] = idx_t(smemV[i]);
+ }
+ }
+}
+
+template <typename T>
+void runL2SelectMin(
+ Tensor<T, 2, true>& productDistances,
+ Tensor<T, 1, true>& centroidDistances,
+ Tensor<T, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ int k,
+ cudaStream_t stream) {
+ FAISS_ASSERT(productDistances.getSize(0) == outDistances.getSize(0));
+ FAISS_ASSERT(productDistances.getSize(0) == outIndices.getSize(0));
+ FAISS_ASSERT(centroidDistances.getSize(0) == productDistances.getSize(1));
+ FAISS_ASSERT(outDistances.getSize(1) == k);
+ FAISS_ASSERT(outIndices.getSize(1) == k);
+
+ // This is also caught at a higher level
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ if (k == 1) {
+ constexpr int kThreadsPerBlock = 256;
+ constexpr int kRowsPerBlock = 8;
+
+ auto block = dim3(kThreadsPerBlock);
+ auto grid = dim3(utils::divUp(outDistances.getSize(0), kRowsPerBlock));
+
+ l2SelectMin1<T, kRowsPerBlock, kThreadsPerBlock>
+ <<<grid, block, 0, stream>>>(
+ productDistances,
+ centroidDistances,
+ outDistances,
+ outIndices);
+ } else {
+ auto grid = dim3(outDistances.getSize(0));
+
+ constexpr int kIndexMax = std::numeric_limits<int>::max();
+
+#define L2_KERNEL(INDEX_T, BLOCK, NUM_WARP_Q, NUM_THREAD_Q) \
+ l2SelectMinK<INDEX_T, T, NUM_WARP_Q, NUM_THREAD_Q, BLOCK> \
+ <<<grid, BLOCK, 0, stream>>>( \
+ productDistances, \
+ centroidDistances, \
+ outDistances, \
+ outIndices, \
+ k, \
+ Limits<T>::getMax())
+
+ // Choose which k-selection index (k-select values) type we should use
+ // if our problem fits into int32, in order to improve kernel occupancy
+#define RUN_L2_SELECT(BLOCK, NUM_WARP_Q, NUM_THREAD_Q) \
+ do { \
+ if (productDistances.getSize(1) > kIndexMax || \
+ centroidDistances.getSize(0) > kIndexMax) { \
+ L2_KERNEL(idx_t, BLOCK, NUM_WARP_Q, NUM_THREAD_Q); \
+ } else { \
+ L2_KERNEL(int32_t, BLOCK, NUM_WARP_Q, NUM_THREAD_Q); \
+ } \
+ } while (false)
+
+ // block size 128 for everything <= 1024
+ if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ RUN_L2_SELECT(128, 32, 2);
+ } else if (k <= 64) {
+ RUN_L2_SELECT(128, 64, 3);
+ } else if (k <= 128) {
+ RUN_L2_SELECT(128, 128, 3);
+ } else if (k <= 256) {
+ RUN_L2_SELECT(128, 256, 4);
+ } else if (k <= 512) {
+ RUN_L2_SELECT(128, 512, 8);
+ } else if (k <= 1024) {
+ RUN_L2_SELECT(128, 1024, 8);
+
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ // smaller block for less shared memory
+ RUN_L2_SELECT(64, 2048, 8);
+#endif
+ } else {
+ FAISS_ASSERT(false);
+ }
+ }
+
+#undef L2_KERNEL
+#undef RUN_L2_SELECT
+
+ CUDA_TEST_ERROR();
+}
+
+void runL2SelectMin(
+ Tensor<float, 2, true>& productDistances,
+ Tensor<float, 1, true>& centroidDistances,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ int k,
+ cudaStream_t stream) {
+ runL2SelectMin<float>(
+ productDistances,
+ centroidDistances,
+ outDistances,
+ outIndices,
+ k,
+ stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Select.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Select.cuh
new file mode 100644
index 0000000..c537edd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/L2Select.cuh
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+void runL2SelectMin(
+ Tensor<float, 2, true>& productDistances,
+ Tensor<float, 1, true>& centroidDistances,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ int k,
+ cudaStream_t stream);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeDistances-inl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeDistances-inl.cuh
new file mode 100644
index 0000000..e2e66f3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeDistances-inl.cuh
@@ -0,0 +1,741 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/BroadcastSum.cuh>
+#include <faiss/gpu/impl/Distance.cuh>
+#include <faiss/gpu/impl/L2Norm.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/MatrixMult.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+
+namespace faiss {
+namespace gpu {
+
+#if defined(USE_AMD_ROCM) && __AMDGCN_WAVEFRONT_SIZE == 64u
+#define LAUNCH_BOUND 320
+#else
+#define LAUNCH_BOUND 288
+#endif
+
+// Kernel responsible for calculating distance from residual vector to
+// each product quantizer code centroid
+template <
+ typename OutCodeT,
+ typename CentroidT,
+ int DimsPerSubQuantizer,
+ bool L2Distance>
+__global__ void __launch_bounds__(LAUNCH_BOUND, 3) pqCodeDistances(
+ Tensor<float, 2, true> queries,
+ int queriesPerBlock,
+ Tensor<CentroidT, 2, true> coarseCentroids,
+ Tensor<float, 3, true> pqCentroids,
+ Tensor<idx_t, 2, true> coarseIndices,
+ // (query id)(coarse)(subquantizer)(code) -> dist
+ Tensor<OutCodeT, 4, true> outCodeDistances) {
+ const auto numSubQuantizers = pqCentroids.getSize(0);
+ const auto dimsPerSubQuantizer = pqCentroids.getSize(1);
+ assert(DimsPerSubQuantizer == dimsPerSubQuantizer);
+ const auto codesPerSubQuantizer = pqCentroids.getSize(2);
+
+ bool isLoadingThread = threadIdx.x >= codesPerSubQuantizer;
+ int loadingThreadId = threadIdx.x - codesPerSubQuantizer;
+
+ extern __shared__ float smem[];
+
+ // Each thread calculates a single code
+ float subQuantizerData[DimsPerSubQuantizer];
+
+ auto code = threadIdx.x;
+ auto subQuantizer = blockIdx.y;
+
+ // Each thread will load the pq centroid data for the code that it
+ // is processing
+ // The loading threads are out of bounds for the number of codes available
+ if (!isLoadingThread) {
+#pragma unroll
+ for (int i = 0; i < DimsPerSubQuantizer; ++i) {
+ subQuantizerData[i] = pqCentroids[subQuantizer][i][code].ldg();
+ }
+ }
+
+ // Where we store our query vector
+ float* smemQuery = smem;
+
+ // Where we store our residual vector; this is double buffered so we
+ // can be loading the next one while processing the current one
+ float* smemResidual1 = &smemQuery[DimsPerSubQuantizer];
+ float* smemResidual2 = &smemResidual1[DimsPerSubQuantizer];
+
+ // Where we pre-load the coarse centroid IDs
+ int* coarseIds = (int*)&smemResidual2[DimsPerSubQuantizer];
+
+ // Each thread is calculating the distance for a single code,
+ // performing the reductions locally
+
+ // Handle multiple queries per block
+ auto startQueryId = idx_t(blockIdx.x) * queriesPerBlock;
+ auto numQueries = queries.getSize(0) - startQueryId;
+ if (numQueries > queriesPerBlock) {
+ numQueries = queriesPerBlock;
+ }
+
+ for (int query = 0; query < numQueries; ++query) {
+ auto queryId = startQueryId + query;
+
+ auto querySubQuantizer =
+ queries[queryId][subQuantizer * DimsPerSubQuantizer].data();
+
+ // Load current query vector
+ for (int i = threadIdx.x; i < DimsPerSubQuantizer; i += blockDim.x) {
+ smemQuery[i] = querySubQuantizer[i];
+ }
+
+ // Load list of coarse centroids found
+ for (int i = threadIdx.x; i < coarseIndices.getSize(1);
+ i += blockDim.x) {
+ // FIXME: coarseIndices is now idx_t but the smem allocation
+ // of coarseIds is still int. In practical limitation, everything
+ // should still fit into int32
+ coarseIds[i] = (int)coarseIndices[queryId][i];
+ }
+
+ // We need coarseIds below
+ // FIXME: investigate loading separately, so we don't need this
+ __syncthreads();
+
+ // Preload first buffer of residual data
+ if (isLoadingThread) {
+ for (int i = loadingThreadId; i < DimsPerSubQuantizer;
+ i += blockDim.x - codesPerSubQuantizer) {
+ auto coarseId = coarseIds[0];
+ // In case NaNs were in the original query data
+ coarseId = coarseId == -1 ? 0 : coarseId;
+ auto coarseCentroidSubQuantizer =
+ coarseCentroids[coarseId]
+ [subQuantizer * dimsPerSubQuantizer]
+ .data();
+
+ if (L2Distance) {
+ smemResidual1[i] = smemQuery[i] -
+ ConvertTo<float>::to(coarseCentroidSubQuantizer[i]);
+ } else {
+ smemResidual1[i] =
+ ConvertTo<float>::to(coarseCentroidSubQuantizer[i]);
+ }
+ }
+ }
+
+ // The block walks the list for a single query
+ for (int coarse = 0; coarse < coarseIndices.getSize(1); ++coarse) {
+ // Wait for smemResidual1 to be loaded
+ __syncthreads();
+
+ if (isLoadingThread) {
+ // Preload second buffer of residual data
+ for (int i = loadingThreadId; i < DimsPerSubQuantizer;
+ i += blockDim.x - codesPerSubQuantizer) {
+ // FIXME: try always making this centroid id 0 so we can
+ // terminate
+ if (coarse != (coarseIndices.getSize(1) - 1)) {
+ auto coarseId = coarseIds[coarse + 1];
+ // In case NaNs were in the original query data
+ coarseId = coarseId == -1 ? 0 : coarseId;
+
+ auto coarseCentroidSubQuantizer =
+ coarseCentroids[coarseId]
+ [subQuantizer *
+ dimsPerSubQuantizer]
+ .data();
+
+ if (L2Distance) {
+ smemResidual2[i] =
+ smemQuery[i] -
+ ConvertTo<float>::to(
+ coarseCentroidSubQuantizer[i]);
+ } else {
+ smemResidual2[i] = ConvertTo<float>::to(
+ coarseCentroidSubQuantizer[i]);
+ }
+ }
+ }
+ } else {
+ // These are the processing threads
+ float dist = 0.0f;
+
+ constexpr int kUnroll = 4;
+ constexpr int kRemainder = DimsPerSubQuantizer % kUnroll;
+ constexpr int kRemainderBase = DimsPerSubQuantizer - kRemainder;
+ float vals[kUnroll];
+
+ // Calculate residual - pqCentroid for each dim that we're
+ // processing
+
+ // Unrolled loop
+ if (L2Distance) {
+#pragma unroll
+ for (int i = 0; i < DimsPerSubQuantizer / kUnroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = smemResidual1[i * kUnroll + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] -= subQuantizerData[i * kUnroll + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] *= vals[j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ dist += vals[j];
+ }
+ }
+ } else {
+ // Inner product: query slice against the reconstructed
+ // sub-quantizer for this coarse cell (query o (centroid +
+ // subQCentroid))
+#pragma unroll
+ for (int i = 0; i < DimsPerSubQuantizer / kUnroll; ++i) {
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = smemResidual1[i * kUnroll + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] += subQuantizerData[i * kUnroll + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] *= smemQuery[i * kUnroll + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ dist += vals[j];
+ }
+ }
+ }
+
+ // Remainder loop
+ if (L2Distance) {
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ vals[j] = smemResidual1[kRemainderBase + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ vals[j] -= subQuantizerData[kRemainderBase + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ vals[j] *= vals[j];
+ }
+ } else {
+ // Inner product
+ // Inner product: query slice against the reconstructed
+ // sub-quantizer for this coarse cell (query o (centroid +
+ // subQCentroid))
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ vals[j] = smemResidual1[kRemainderBase + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ vals[j] += subQuantizerData[kRemainderBase + j];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ vals[j] *= smemQuery[kRemainderBase + j];
+ }
+ }
+
+#pragma unroll
+ for (int j = 0; j < kRemainder; ++j) {
+ dist += vals[j];
+ }
+
+ // We have the distance for our code; write it out
+ outCodeDistances[queryId][coarse][subQuantizer][code] =
+ ConvertTo<OutCodeT>::to(dist);
+ } // !isLoadingThread
+
+ // Swap residual buffers
+ float* tmp = smemResidual1;
+ smemResidual1 = smemResidual2;
+ smemResidual2 = tmp;
+ }
+ }
+}
+
+template <typename CentroidT, bool L2Residual>
+__global__ void pqResidualVector(
+ Tensor<float, 2, true> queries,
+ Tensor<CentroidT, 2, true> coarseCentroids,
+ Tensor<idx_t, 2, true> coarseIndices,
+ int numSubDim,
+ // output is transposed:
+ // (sub q)(query id)(centroid id)(sub dim)
+ Tensor<float, 4, true> residual) {
+ auto queryId = blockIdx.x;
+ auto centroidId = blockIdx.y;
+
+ idx_t realCentroidId = coarseIndices[queryId][centroidId];
+
+ for (int dim = threadIdx.x; dim < queries.getSize(1); dim += blockDim.x) {
+ float q = queries[queryId][dim];
+ float c = ConvertTo<float>::to(coarseCentroids[realCentroidId][dim]);
+
+ float r;
+
+ if (L2Residual) {
+ r = q - c;
+ } else {
+ // IP does not use a residual. Instead, the estimated distance is
+ // (query . (centroid + sub quantizer centroid).
+ //
+ // This kernel is used to calculate (query . sub quantizer
+ // centroid), providing the query value replicated across all of the
+ // sub quantizers. The batch matrix multiplication in
+ // runPQCodeDistancesMM will perform this inner product. The
+ // adjustment (query . centroid) is added later.
+ r = q;
+ }
+
+ residual[dim / numSubDim][queryId][centroidId][dim % numSubDim] = r;
+ }
+}
+
+template <typename CentroidT>
+void runPQResidualVector(
+ Tensor<float, 3, true>& pqCentroids,
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& coarseCentroids,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ Tensor<float, 4, true>& residual,
+ bool l2Residual,
+ cudaStream_t stream) {
+ // blockDim.y is limited by nprobe
+ auto grid = dim3(coarseIndices.getSize(0), coarseIndices.getSize(1));
+ auto block = dim3(
+ std::min(queries.getSize(1), (idx_t)getMaxThreadsCurrentDevice()));
+
+ if (l2Residual) {
+ pqResidualVector<CentroidT, true><<<grid, block, 0, stream>>>(
+ queries,
+ coarseCentroids,
+ coarseIndices,
+ pqCentroids.getSize(1),
+ residual);
+ } else {
+ pqResidualVector<CentroidT, false><<<grid, block, 0, stream>>>(
+ queries,
+ coarseCentroids,
+ coarseIndices,
+ pqCentroids.getSize(1),
+ residual);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+template <typename T>
+__global__ void pqDistanceIPCorrection(
+ Tensor<T, 3, true> codeDistances,
+ Tensor<T, 2, true> coarseDistances,
+ int numSubQ) {
+ int centroid = blockIdx.x;
+ int query = blockIdx.y;
+
+ // We need to add the (query . centroid) correction factor (coarseDistances)
+ // to all output code distances (q)(c)(sub q)(code).
+ // However, there are numSubQ code distance sums per each approximated
+ // distance, so we need to divide this correction by numSubQ since we will
+ // be adding it numSubQ times.
+ auto d = coarseDistances[query][centroid] / (float)numSubQ;
+
+ auto base = codeDistances[query][centroid].data();
+
+ for (int i = threadIdx.x; i < codeDistances.getSize(2); i += blockDim.x) {
+ base[i] += d;
+ }
+}
+
+// We have previously calculated (query . sub quantizer centroid), but we
+// need to calculate (query . (centroid + sub quantizer centroid). This will add
+// in the correction factor to each calculated code distance.
+template <typename T>
+void runPQDistanceIPCorrection(
+ Tensor<T, 4, true>& codeDistances,
+ Tensor<T, 2, true>& coarseDistances,
+ cudaStream_t stream) {
+ // blockDim.y is limited by nprobe
+ auto grid = dim3(coarseDistances.getSize(1), coarseDistances.getSize(0));
+ auto block = 512;
+
+ auto codeView = codeDistances.template downcastInner<3>();
+
+ pqDistanceIPCorrection<<<grid, block, 0, stream>>>(
+ codeView, coarseDistances, codeDistances.getSize(2));
+}
+
+// This is a general purpose implementation that leverages GEMM to calculate
+// code distances for PQ codes for any number of dimensions per sub-quantizer /
+// number of sub-quantizers
+template <typename CentroidT>
+void runPQCodeDistancesMM(
+ GpuResources* res,
+ Tensor<float, 3, true>& pqCentroids,
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& coarseCentroids,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ // Output is (query)(centroid)(sub q)(code)
+ NoTypeTensor<4, true>& outCodeDistances,
+ bool l2Distance,
+ bool useFloat16Lookup,
+ cudaStream_t stream) {
+ // We construct our float32 output in outCodeDistancesF
+ Tensor<float, 4, true> outCodeDistancesF;
+ DeviceTensor<float, 4, true> outCodeDistancesFloatMem;
+
+ if (useFloat16Lookup) {
+ // outCodeDistances has half memory, we need to allocate a buffer for
+ // float
+ outCodeDistancesFloatMem = DeviceTensor<float, 4, true>(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {outCodeDistances.getSize(0),
+ outCodeDistances.getSize(1),
+ outCodeDistances.getSize(2),
+ outCodeDistances.getSize(3)});
+
+ outCodeDistancesF = outCodeDistancesFloatMem;
+ } else {
+ // We can use the memory that we were given
+ outCodeDistancesF = outCodeDistances.toTensor<float>();
+ }
+
+ // Calculate (q - c) residual vector if L2. Otherwise, for IP, this kernel
+ // will just replicate q
+ //
+ // (sub q)(query id)(centroid id)(sub dim)
+ DeviceTensor<float, 4, true> residual(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {pqCentroids.getSize(0),
+ coarseIndices.getSize(0),
+ coarseIndices.getSize(1),
+ pqCentroids.getSize(1)});
+
+ runPQResidualVector(
+ pqCentroids,
+ queries,
+ coarseCentroids,
+ coarseIndices,
+ residual,
+ l2Distance,
+ stream);
+
+ // Perform a batch MM:
+ // (sub q) x {(q * c)(sub dim) x (sub dim)(code)} =>
+ // (sub q) x {(q * c)(code)}
+ auto residualView3 = residual.view<3>(
+ {pqCentroids.getSize(0),
+ coarseIndices.getSize(0) * coarseIndices.getSize(1),
+ pqCentroids.getSize(1)});
+
+ DeviceTensor<float, 3, true> residualDistance(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {pqCentroids.getSize(0),
+ coarseIndices.getSize(0) * coarseIndices.getSize(1),
+ pqCentroids.getSize(2)});
+
+ runBatchMatrixMult(
+ residualDistance,
+ false,
+ residualView3,
+ false,
+ pqCentroids,
+ false,
+ l2Distance ? -2.0f : 1.0f,
+ 0.0f,
+ res->getBlasHandleCurrentDevice(),
+ stream);
+
+ if (l2Distance) {
+ // Calculate ||q - c||^2
+ DeviceTensor<float, 1, true> residualNorms(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {pqCentroids.getSize(0) * coarseIndices.getSize(0) *
+ coarseIndices.getSize(1)});
+
+ auto residualView2 = residual.view<2>(
+ {pqCentroids.getSize(0) * coarseIndices.getSize(0) *
+ coarseIndices.getSize(1),
+ pqCentroids.getSize(1)});
+
+ runL2Norm(residualView2, true, residualNorms, true, stream);
+
+ // Sum ||q - c||^2 along rows
+ auto residualDistanceView2 = residualDistance.view<2>(
+ {pqCentroids.getSize(0) * coarseIndices.getSize(0) *
+ coarseIndices.getSize(1),
+ pqCentroids.getSize(2)});
+
+ runSumAlongRows(residualNorms, residualDistanceView2, false, stream);
+ }
+
+ // Transpose (sub q)(q * c)(code) to (q * c)(sub q)(code) (which
+ // is where we build our output distances). L2 version of this has an added
+ // -2 multiplicative factor
+ auto outCodeDistancesView = outCodeDistancesF.view<3>(
+ {coarseIndices.getSize(0) * coarseIndices.getSize(1),
+ outCodeDistances.getSize(2),
+ outCodeDistances.getSize(3)});
+
+ runTransposeAny(residualDistance, 0, 1, outCodeDistancesView, stream);
+
+ if (l2Distance) {
+ // Calculate code norms per each sub-dim
+ // (sub q)(sub dim)(code) is pqCentroids
+ // transpose to (sub q)(code)(sub dim)
+ DeviceTensor<float, 3, true> pqCentroidsTranspose(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {pqCentroids.getSize(0),
+ pqCentroids.getSize(2),
+ pqCentroids.getSize(1)});
+
+ runTransposeAny(pqCentroids, 1, 2, pqCentroidsTranspose, stream);
+
+ auto pqCentroidsTransposeView = pqCentroidsTranspose.view<2>(
+ {pqCentroids.getSize(0) * pqCentroids.getSize(2),
+ pqCentroids.getSize(1)});
+
+ // The norm of each (sub q)(code)
+ DeviceTensor<float, 1, true> pqCentroidsNorm(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {pqCentroids.getSize(0) * pqCentroids.getSize(2)});
+
+ runL2Norm(
+ pqCentroidsTransposeView, true, pqCentroidsNorm, true, stream);
+
+ // View output as (q * c)(sub q * code), and add centroid norm to
+ // each row
+ auto outDistancesCodeViewCols = outCodeDistancesView.view<2>(
+ {coarseIndices.getSize(0) * coarseIndices.getSize(1),
+ outCodeDistances.getSize(2) * outCodeDistances.getSize(3)});
+
+ runSumAlongColumns(pqCentroidsNorm, outDistancesCodeViewCols, stream);
+ } else {
+ // We have previously calculated (query . sub quantizer centroid), but
+ // we need to calculate (query . (centroid + sub quantizer centroid).
+ //
+ // We need to add the (query . centroid) correction factor
+ // (coarseDistances) to all output code distances (q)(c)(sub q)(code).
+ runPQDistanceIPCorrection(outCodeDistancesF, coarseDistances, stream);
+ }
+
+ if (useFloat16Lookup) {
+ // Need to convert back to half in the output memory
+ auto outCodeDistancesH = outCodeDistances.toTensor<half>();
+ convertTensor<float, half, 4>(
+ stream, outCodeDistancesF, outCodeDistancesH);
+ }
+}
+
+// Must be kept in sync with runPQDistances
+inline bool isSpecializedPQCodeDistanceDims(int dims) {
+ switch (dims) {
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 8:
+ case 10:
+ case 12:
+ case 16:
+ case 20:
+ case 24:
+ case 28:
+ case 32:
+ return true;
+ default:
+ return false;
+ }
+}
+
+template <typename CentroidT>
+void runPQCodeDistances(
+ GpuResources* res,
+ Tensor<float, 3, true>& pqCentroids,
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& coarseCentroids,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ NoTypeTensor<4, true>& outCodeDistances,
+ bool useMMImplementation,
+ bool l2Distance,
+ bool useFloat16Lookup,
+ cudaStream_t stream) {
+ const auto numSubQuantizers = pqCentroids.getSize(0);
+ const auto dimsPerSubQuantizer = pqCentroids.getSize(1);
+ const auto codesPerSubQuantizer = pqCentroids.getSize(2);
+
+ // Only a certain number of dimensions per sub quantizer are supported by
+ // the specialized implementation. Every other value falls back to the
+ // generalized MM implementation.
+ if (!isSpecializedPQCodeDistanceDims(dimsPerSubQuantizer) ||
+ useMMImplementation) {
+ // Use the general purpose matrix multiplication implementation which
+ // handles any number of sub-quantizers and dimensions per sub-quantizer
+ runPQCodeDistancesMM<CentroidT>(
+ res,
+ pqCentroids,
+ queries,
+ coarseCentroids,
+ coarseDistances,
+ coarseIndices,
+ outCodeDistances,
+ l2Distance,
+ useFloat16Lookup,
+ stream);
+ return;
+ }
+
+ // FIXME: tune
+ // Reuse of pq centroid data is based on both # of queries * nprobe,
+ // and we should really be tiling in both dimensions
+ constexpr int kQueriesPerBlock = 8;
+
+ auto grid =
+ dim3(utils::divUp(queries.getSize(0), kQueriesPerBlock),
+ numSubQuantizers);
+
+ // Reserve one block of threads for double buffering
+ // FIXME: probably impractical for large # of dims?
+ int warpSize = getWarpSizeCurrentDevice();
+ auto loadingThreads = utils::roundUp(dimsPerSubQuantizer, warpSize);
+ auto block = dim3(codesPerSubQuantizer + loadingThreads);
+
+ auto smem = (3 * dimsPerSubQuantizer) * sizeof(float) +
+ coarseIndices.getSize(1) * sizeof(int);
+
+#define RUN_CODE(DIMS, L2) \
+ do { \
+ if (useFloat16Lookup) { \
+ auto outCodeDistancesT = outCodeDistances.toTensor<half>(); \
+ \
+ pqCodeDistances<half, CentroidT, DIMS, L2> \
+ <<<grid, block, smem, stream>>>( \
+ queries, \
+ kQueriesPerBlock, \
+ coarseCentroids, \
+ pqCentroids, \
+ coarseIndices, \
+ outCodeDistancesT); \
+ } else { \
+ auto outCodeDistancesT = outCodeDistances.toTensor<float>(); \
+ \
+ pqCodeDistances<float, CentroidT, DIMS, L2> \
+ <<<grid, block, smem, stream>>>( \
+ queries, \
+ kQueriesPerBlock, \
+ coarseCentroids, \
+ pqCentroids, \
+ coarseIndices, \
+ outCodeDistancesT); \
+ } \
+ } while (0)
+
+#define CODE_L2(DIMS) \
+ do { \
+ if (l2Distance) { \
+ RUN_CODE(DIMS, true); \
+ } else { \
+ RUN_CODE(DIMS, false); \
+ } \
+ } while (0)
+
+ switch (dimsPerSubQuantizer) {
+ case 1:
+ CODE_L2(1);
+ break;
+ case 2:
+ CODE_L2(2);
+ break;
+ case 3:
+ CODE_L2(3);
+ break;
+ case 4:
+ CODE_L2(4);
+ break;
+ case 5:
+ CODE_L2(5);
+ break;
+ case 6:
+ CODE_L2(6);
+ break;
+ case 8:
+ CODE_L2(8);
+ break;
+ case 10:
+ CODE_L2(10);
+ break;
+ case 12:
+ CODE_L2(12);
+ break;
+ case 16:
+ CODE_L2(16);
+ break;
+ case 20:
+ CODE_L2(20);
+ break;
+ case 24:
+ CODE_L2(24);
+ break;
+ case 28:
+ CODE_L2(28);
+ break;
+ case 32:
+ CODE_L2(32);
+ break;
+ default:
+ // This should not be reached, we should fall back to the MM
+ // implementation
+ FAISS_ASSERT(false);
+ break;
+ }
+
+#undef RUN_CODE
+#undef CODE_L2
+
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeDistances.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeDistances.cuh
new file mode 100644
index 0000000..9d21082
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeDistances.cuh
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cublas_v2.h>
+#include <faiss/Index.h>
+#include <faiss/gpu/utils/NoTypeTensor.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class DeviceMemory;
+
+/// pqCentroids is of the form (sub q)(sub dim)(code id)
+/// Calculates the distance from the (query - centroid) residual to
+/// each sub-code vector, for the given list of query results in
+/// coarseIndices
+template <typename CentroidT>
+void runPQCodeDistances(
+ GpuResources* res,
+ Tensor<float, 3, true>& pqCentroids,
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& coarseCentroids,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ NoTypeTensor<4, true>& outCodeDistances,
+ bool useMMImplementation,
+ bool l2Distance,
+ bool useFloat16Lookup);
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/impl/PQCodeDistances-inl.cuh>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeLoad.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeLoad.cuh
new file mode 100644
index 0000000..4669bf4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQCodeLoad.cuh
@@ -0,0 +1,615 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/PtxUtils.cuh>
+
+namespace faiss {
+namespace gpu {
+
+#if __CUDA_ARCH__ >= 350
+// Use the CC 3.5+ read-only texture cache (nc)
+#define LD_NC_V1 "ld.global.cs.nc.u32"
+#define LD_NC_V2 "ld.global.cs.nc.v2.u32"
+#define LD_NC_V4 "ld.global.cs.nc.v4.u32"
+#else
+// Read normally
+#define LD_NC_V1 "ld.global.cs.u32"
+#define LD_NC_V2 "ld.global.cs.v2.u32"
+#define LD_NC_V4 "ld.global.cs.v4.u32"
+#endif // __CUDA_ARCH__
+
+///
+/// This file contains loader functions for PQ codes of various byte
+/// length.
+///
+
+// Type-specific wrappers around the PTX bfe.* instruction, for
+// quantization code extraction
+inline __device__ unsigned int getByte(unsigned char v, int pos, int width) {
+ return v;
+}
+
+inline __device__ unsigned int getByte(unsigned short v, int pos, int width) {
+ return getBitfield((unsigned int)v, pos, width);
+}
+
+inline __device__ unsigned int getByte(unsigned int v, int pos, int width) {
+ return getBitfield(v, pos, width);
+}
+
+inline __device__ unsigned int getByte(uint64_t v, int pos, int width) {
+ return getBitfield(v, pos, width);
+}
+
+#ifdef USE_AMD_ROCM
+
+template <int NumSubQuantizers>
+struct LoadCode32 {};
+
+template <>
+struct LoadCode32<1> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 1;
+ // using T = uint8_t __attribute__((ext_vector_type(1)));
+ // T* t = reinterpret_cast<T*>(p);
+ uint8_t* u = reinterpret_cast<uint8_t*>(code32);
+ u[0] = __builtin_nontemporal_load(p);
+ }
+};
+
+template <>
+struct LoadCode32<2> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 2;
+ using T = uint8_t __attribute__((ext_vector_type(2)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<3> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 3;
+ using T = uint8_t __attribute__((ext_vector_type(3)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[1] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<4> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 4;
+ using T = uint32_t __attribute__((ext_vector_type(1)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<8> {
+ static inline __device__ void load(
+ unsigned int code32[2],
+ uint8_t* p,
+ int offset) {
+ p += offset * 8;
+ using T = uint32_t __attribute__((ext_vector_type(2)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<12> {
+ static inline __device__ void load(
+ unsigned int code32[3],
+ uint8_t* p,
+ int offset) {
+ p += offset * 12;
+ using T = uint32_t __attribute__((ext_vector_type(3)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<16> {
+ static inline __device__ void load(
+ unsigned int code32[4],
+ uint8_t* p,
+ int offset) {
+ p += offset * 16;
+ using T = uint32_t __attribute__((ext_vector_type(4)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<20> {
+ static inline __device__ void load(
+ unsigned int code32[5],
+ uint8_t* p,
+ int offset) {
+ p += offset * 20;
+ using T = uint32_t __attribute__((ext_vector_type(5)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<24> {
+ static inline __device__ void load(
+ unsigned int code32[6],
+ uint8_t* p,
+ int offset) {
+ p += offset * 24;
+ using T = uint32_t __attribute__((ext_vector_type(6)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<28> {
+ static inline __device__ void load(
+ unsigned int code32[7],
+ uint8_t* p,
+ int offset) {
+ p += offset * 28;
+ using T = uint32_t __attribute__((ext_vector_type(7)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<32> {
+ static inline __device__ void load(
+ unsigned int code32[8],
+ uint8_t* p,
+ int offset) {
+ p += offset * 32;
+ using T = uint32_t __attribute__((ext_vector_type(8)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<40> {
+ static inline __device__ void load(
+ unsigned int code32[10],
+ uint8_t* p,
+ int offset) {
+ p += offset * 40;
+ using T = uint32_t __attribute__((ext_vector_type(10)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<48> {
+ static inline __device__ void load(
+ unsigned int code32[12],
+ uint8_t* p,
+ int offset) {
+ p += offset * 48;
+ using T = uint32_t __attribute__((ext_vector_type(12)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<56> {
+ static inline __device__ void load(
+ unsigned int code32[14],
+ uint8_t* p,
+ int offset) {
+ p += offset * 56;
+ using T = uint32_t __attribute__((ext_vector_type(14)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<64> {
+ static inline __device__ void load(
+ unsigned int code32[16],
+ uint8_t* p,
+ int offset) {
+ p += offset * 64;
+ using T = uint32_t __attribute__((ext_vector_type(16)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+template <>
+struct LoadCode32<96> {
+ static inline __device__ void load(
+ unsigned int code32[24],
+ uint8_t* p,
+ int offset) {
+ p += offset * 96;
+ using T = uint32_t __attribute__((ext_vector_type(24)));
+ T* t = reinterpret_cast<T*>(p);
+ T* u = reinterpret_cast<T*>(code32);
+ u[0] = __builtin_nontemporal_load(t);
+ }
+};
+
+#else // USE_AMD_ROCM
+
+template <int NumSubQuantizers>
+struct LoadCode32 {};
+
+template <>
+struct LoadCode32<1> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 1;
+ asm("ld.global.cs.u8 {%0}, [%1];" : "=r"(code32[0]) : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<2> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 2;
+ asm("ld.global.cs.u16 {%0}, [%1];" : "=r"(code32[0]) : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<3> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 3;
+ unsigned int a;
+ unsigned int b;
+ unsigned int c;
+
+ // FIXME: this is a non-coalesced, unaligned, non-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm("ld.global.cs.u8 {%0}, [%1 + 0];" : "=r"(a) : "l"(p));
+ asm("ld.global.cs.u8 {%0}, [%1 + 1];" : "=r"(b) : "l"(p));
+ asm("ld.global.cs.u8 {%0}, [%1 + 2];" : "=r"(c) : "l"(p));
+
+ // FIXME: this is also slow, since we have to recover the
+ // individual bytes loaded
+ code32[0] = (c << 16) | (b << 8) | a;
+ }
+};
+
+template <>
+struct LoadCode32<4> {
+ static inline __device__ void load(
+ unsigned int code32[1],
+ uint8_t* p,
+ int offset) {
+ p += offset * 4;
+ asm("ld.global.cs.u32 {%0}, [%1];" : "=r"(code32[0]) : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<8> {
+ static inline __device__ void load(
+ unsigned int code32[2],
+ uint8_t* p,
+ int offset) {
+ p += offset * 8;
+ asm("ld.global.cs.v2.u32 {%0, %1}, [%2];"
+ : "=r"(code32[0]), "=r"(code32[1])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<12> {
+ static inline __device__ void load(
+ unsigned int code32[3],
+ uint8_t* p,
+ int offset) {
+ p += offset * 12;
+ // FIXME: this is a non-coalesced, unaligned, non-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V1 " {%0}, [%1 + 0];" : "=r"(code32[0]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 4];" : "=r"(code32[1]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 8];" : "=r"(code32[2]) : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<16> {
+ static inline __device__ void load(
+ unsigned int code32[4],
+ uint8_t* p,
+ int offset) {
+ p += offset * 16;
+ asm("ld.global.cs.v4.u32 {%0, %1, %2, %3}, [%4];"
+ : "=r"(code32[0]), "=r"(code32[1]), "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<20> {
+ static inline __device__ void load(
+ unsigned int code32[5],
+ uint8_t* p,
+ int offset) {
+ p += offset * 20;
+ // FIXME: this is a non-coalesced, unaligned, non-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V1 " {%0}, [%1 + 0];" : "=r"(code32[0]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 4];" : "=r"(code32[1]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 8];" : "=r"(code32[2]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 12];" : "=r"(code32[3]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 16];" : "=r"(code32[4]) : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<24> {
+ static inline __device__ void load(
+ unsigned int code32[6],
+ uint8_t* p,
+ int offset) {
+ p += offset * 24;
+ // FIXME: this is a non-coalesced, unaligned, 2-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 0];"
+ : "=r"(code32[0]), "=r"(code32[1])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 8];"
+ : "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<28> {
+ static inline __device__ void load(
+ unsigned int code32[7],
+ uint8_t* p,
+ int offset) {
+ p += offset * 28;
+ // FIXME: this is a non-coalesced, unaligned, non-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V1 " {%0}, [%1 + 0];" : "=r"(code32[0]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 4];" : "=r"(code32[1]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 8];" : "=r"(code32[2]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 12];" : "=r"(code32[3]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 16];" : "=r"(code32[4]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 20];" : "=r"(code32[5]) : "l"(p));
+ asm(LD_NC_V1 " {%0}, [%1 + 24];" : "=r"(code32[6]) : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<32> {
+ static inline __device__ void load(
+ unsigned int code32[8],
+ uint8_t* p,
+ int offset) {
+ p += offset * 32;
+ // FIXME: this is a non-coalesced load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4];"
+ : "=r"(code32[0]), "=r"(code32[1]), "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5]), "=r"(code32[6]), "=r"(code32[7])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<40> {
+ static inline __device__ void load(
+ unsigned int code32[10],
+ uint8_t* p,
+ int offset) {
+ p += offset * 40;
+ // FIXME: this is a non-coalesced, unaligned, 2-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 0];"
+ : "=r"(code32[0]), "=r"(code32[1])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 8];"
+ : "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 24];"
+ : "=r"(code32[6]), "=r"(code32[7])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 32];"
+ : "=r"(code32[8]), "=r"(code32[9])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<48> {
+ static inline __device__ void load(
+ unsigned int code32[12],
+ uint8_t* p,
+ int offset) {
+ p += offset * 48;
+ // FIXME: this is a non-coalesced load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4];"
+ : "=r"(code32[0]), "=r"(code32[1]), "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5]), "=r"(code32[6]), "=r"(code32[7])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 32];"
+ : "=r"(code32[8]),
+ "=r"(code32[9]),
+ "=r"(code32[10]),
+ "=r"(code32[11])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<56> {
+ static inline __device__ void load(
+ unsigned int code32[14],
+ uint8_t* p,
+ int offset) {
+ p += offset * 56;
+ // FIXME: this is a non-coalesced, unaligned, 2-vectorized load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 0];"
+ : "=r"(code32[0]), "=r"(code32[1])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 8];"
+ : "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 24];"
+ : "=r"(code32[6]), "=r"(code32[7])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 32];"
+ : "=r"(code32[8]), "=r"(code32[9])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 40];"
+ : "=r"(code32[10]), "=r"(code32[11])
+ : "l"(p));
+ asm(LD_NC_V2 " {%0, %1}, [%2 + 48];"
+ : "=r"(code32[12]), "=r"(code32[13])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<64> {
+ static inline __device__ void load(
+ unsigned int code32[16],
+ uint8_t* p,
+ int offset) {
+ p += offset * 64;
+ // FIXME: this is a non-coalesced load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4];"
+ : "=r"(code32[0]), "=r"(code32[1]), "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5]), "=r"(code32[6]), "=r"(code32[7])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 32];"
+ : "=r"(code32[8]),
+ "=r"(code32[9]),
+ "=r"(code32[10]),
+ "=r"(code32[11])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 48];"
+ : "=r"(code32[12]),
+ "=r"(code32[13]),
+ "=r"(code32[14]),
+ "=r"(code32[15])
+ : "l"(p));
+ }
+};
+
+template <>
+struct LoadCode32<96> {
+ static inline __device__ void load(
+ unsigned int code32[24],
+ uint8_t* p,
+ int offset) {
+ p += offset * 96;
+ // FIXME: this is a non-coalesced load
+ // unfortunately need to reorganize memory layout by warp
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4];"
+ : "=r"(code32[0]), "=r"(code32[1]), "=r"(code32[2]), "=r"(code32[3])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 16];"
+ : "=r"(code32[4]), "=r"(code32[5]), "=r"(code32[6]), "=r"(code32[7])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 32];"
+ : "=r"(code32[8]),
+ "=r"(code32[9]),
+ "=r"(code32[10]),
+ "=r"(code32[11])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 48];"
+ : "=r"(code32[12]),
+ "=r"(code32[13]),
+ "=r"(code32[14]),
+ "=r"(code32[15])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 64];"
+ : "=r"(code32[16]),
+ "=r"(code32[17]),
+ "=r"(code32[18]),
+ "=r"(code32[19])
+ : "l"(p));
+ asm(LD_NC_V4 " {%0, %1, %2, %3}, [%4 + 80];"
+ : "=r"(code32[20]),
+ "=r"(code32[21]),
+ "=r"(code32[22]),
+ "=r"(code32[23])
+ : "l"(p));
+ }
+};
+
+#endif // USE_AMD_ROCM
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassNoPrecomputed-inl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassNoPrecomputed-inl.cuh
new file mode 100644
index 0000000..8a48ef4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassNoPrecomputed-inl.cuh
@@ -0,0 +1,743 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/IVFUtils.cuh>
+#include <faiss/gpu/impl/PQCodeDistances.cuh>
+#include <faiss/gpu/impl/PQCodeLoad.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/LoadStoreOperators.cuh>
+#include <faiss/gpu/utils/NoTypeTensor.cuh>
+#include <faiss/gpu/utils/WarpPackedBits.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// A basic implementation that works for the interleaved by vector layout for
+// any number of sub-quantizers
+template <typename EncodeT, int EncodeBits, typename CodeDistanceT>
+__global__ void pqScanInterleaved(
+ Tensor<float, 2, true> queries,
+ Tensor<float, 3, true> pqCentroids,
+ Tensor<idx_t, 2, true> ivfListIds,
+ Tensor<CodeDistanceT, 4, true> codeDistances,
+ void** listCodes,
+ idx_t* listLengths,
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<float, 1, true> distance) {
+ // Each block handles a single query
+ auto queryId = blockIdx.y;
+ auto probeId = blockIdx.x;
+
+ idx_t listId = ivfListIds[queryId][probeId];
+ // Safety guard in case NaNs in input cause no list ID to be generated
+ if (listId == -1) {
+ return;
+ }
+
+ int numWarps = blockDim.x / kWarpSize;
+ // FIXME: some issue with getLaneId() and CUDA 10.1 and P4 GPUs?
+ int laneId = threadIdx.x % kWarpSize;
+ int warpId = threadIdx.x / kWarpSize;
+
+ int numSubQuantizers = codeDistances.getSize(2);
+
+ // This is where we start writing out data
+ // We ensure that before the array (at offset -1), there is a 0 value
+ auto outBase = *(prefixSumOffsets[queryId][probeId].data() - 1);
+ float* distanceOut = distance[outBase].data();
+ auto localCodeDistances = codeDistances[queryId][probeId];
+
+ // This is where the codes for our list start
+ auto vecsBase = (EncodeT*)listCodes[listId];
+ auto numVecs = listLengths[listId];
+
+ // How many vector blocks of kWarpSize are in this list?
+ idx_t numBlocks = utils::divUp(numVecs, (idx_t)kWarpSize);
+
+ // Number of EncodeT words per each dimension of block of kWarpSize vecs
+ constexpr int bytesPerVectorBlockDim = EncodeBits * kWarpSize / 8;
+ constexpr int wordsPerVectorBlockDim =
+ bytesPerVectorBlockDim / sizeof(EncodeT);
+ int wordsPerVectorBlock = wordsPerVectorBlockDim * numSubQuantizers;
+
+ for (idx_t block = warpId; block < numBlocks; block += numWarps) {
+ float dist = 0;
+
+ // This is the vector a given lane/thread handles
+ idx_t vec = block * kWarpSize + laneId;
+ bool valid = vec < numVecs;
+
+ EncodeT* data = vecsBase + block * wordsPerVectorBlock;
+
+ for (int sq = 0; sq < numSubQuantizers; ++sq) {
+ EncodeT enc =
+ WarpPackedBits<EncodeT, EncodeBits>::read(laneId, data);
+ EncodeT code =
+ WarpPackedBits<EncodeT, EncodeBits>::postRead(laneId, enc);
+
+ dist += valid ? ConvertTo<float>::to(localCodeDistances[sq][code])
+ : 0;
+ data += wordsPerVectorBlockDim;
+ }
+
+ if (valid) {
+ distanceOut[vec] = dist;
+ }
+ }
+}
+
+template <typename LookupT, typename LookupVecT>
+struct LoadCodeDistances {
+ static inline __device__ void load(
+ LookupT* smem,
+ LookupT* codes,
+ int numCodes) {
+ constexpr int kWordSize = sizeof(LookupVecT) / sizeof(LookupT);
+
+ // We can only use the vector type if the data is guaranteed to be
+ // aligned. The codes are innermost, so if it is evenly divisible,
+ // then any slice will be aligned.
+ if (numCodes % kWordSize == 0) {
+ // Load the data by float4 for efficiency, and then handle any
+ // remainder limitVec is the number of whole vec words we can load,
+ // in terms of whole blocks performing the load
+ constexpr int kUnroll = 2;
+ int limitVec = numCodes / (kUnroll * kWordSize * blockDim.x);
+ limitVec *= kUnroll * blockDim.x;
+
+ LookupVecT* smemV = (LookupVecT*)smem;
+ LookupVecT* codesV = (LookupVecT*)codes;
+
+ for (int i = threadIdx.x; i < limitVec; i += kUnroll * blockDim.x) {
+ LookupVecT vals[kUnroll];
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = LoadStore<LookupVecT>::load(
+ &codesV[i + j * blockDim.x]);
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ LoadStore<LookupVecT>::store(
+ &smemV[i + j * blockDim.x], vals[j]);
+ }
+ }
+
+ // This is where we start loading the remainder that does not evenly
+ // fit into kUnroll x blockDim.x
+ int remainder = limitVec * kWordSize;
+
+ for (int i = remainder + threadIdx.x; i < numCodes;
+ i += blockDim.x) {
+ smem[i] = codes[i];
+ }
+ } else {
+ // Potential unaligned load
+ constexpr int kUnroll = 4;
+
+ int limit = utils::roundDown(numCodes, kUnroll * blockDim.x);
+
+ int i = threadIdx.x;
+ for (; i < limit; i += kUnroll * blockDim.x) {
+ LookupT vals[kUnroll];
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = codes[i + j * blockDim.x];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ smem[i + j * blockDim.x] = vals[j];
+ }
+ }
+
+ for (; i < numCodes; i += blockDim.x) {
+ smem[i] = codes[i];
+ }
+ }
+ }
+};
+
+template <int NumSubQuantizers, typename LookupT, typename LookupVecT>
+__global__ void pqScanNoPrecomputedMultiPass(
+ Tensor<float, 2, true> queries,
+ Tensor<float, 3, true> pqCentroids,
+ Tensor<idx_t, 2, true> ivfListIds,
+ Tensor<LookupT, 4, true> codeDistances,
+ void** listCodes,
+ idx_t* listLengths,
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<float, 1, true> distance) {
+ const auto codesPerSubQuantizer = pqCentroids.getSize(2);
+
+ // Where the pq code -> residual distance is stored
+ extern __shared__ char smemCodeDistances[];
+ LookupT* codeDist = (LookupT*)smemCodeDistances;
+
+ // Each block handles a single query
+ auto queryId = blockIdx.y;
+ auto probeId = blockIdx.x;
+
+ // This is where we start writing out data
+ // We ensure that before the array (at offset -1), there is a 0 value
+ auto outBase = *(prefixSumOffsets[queryId][probeId].data() - 1);
+ float* distanceOut = distance[outBase].data();
+
+ idx_t listId = ivfListIds[queryId][probeId];
+ // Safety guard in case NaNs in input cause no list ID to be generated
+ if (listId == -1) {
+ return;
+ }
+
+ uint8_t* codeList = (uint8_t*)listCodes[listId];
+ auto limit = listLengths[listId];
+
+ constexpr int kNumCode32 =
+ NumSubQuantizers <= 4 ? 1 : (NumSubQuantizers / 4);
+ unsigned int code32[kNumCode32];
+ unsigned int nextCode32[kNumCode32];
+
+ // We double-buffer the code loading, which improves memory utilization
+ if (threadIdx.x < limit) {
+ LoadCode32<NumSubQuantizers>::load(code32, codeList, threadIdx.x);
+ }
+
+ LoadCodeDistances<LookupT, LookupVecT>::load(
+ codeDist,
+ codeDistances[queryId][probeId].data(),
+ codeDistances.getSize(2) * codeDistances.getSize(3));
+
+ // Prevent WAR dependencies
+ __syncthreads();
+
+ // Each thread handles one code element in the list, with a
+ // block-wide stride
+ for (idx_t codeIndex = threadIdx.x; codeIndex < limit;
+ codeIndex += blockDim.x) {
+ // Prefetch next codes
+ if (codeIndex + blockDim.x < limit) {
+ LoadCode32<NumSubQuantizers>::load(
+ nextCode32, codeList, codeIndex + blockDim.x);
+ }
+
+ float dist = 0.0f;
+
+#pragma unroll
+ for (int word = 0; word < kNumCode32; ++word) {
+ constexpr int kBytesPerCode32 =
+ NumSubQuantizers < 4 ? NumSubQuantizers : 4;
+
+ if (kBytesPerCode32 == 1) {
+ auto code = code32[0];
+ dist = ConvertTo<float>::to(codeDist[code]);
+
+ } else {
+#pragma unroll
+ for (int byte = 0; byte < kBytesPerCode32; ++byte) {
+ auto code = getByte(code32[word], byte * 8, 8);
+
+ auto offset = codesPerSubQuantizer *
+ (word * kBytesPerCode32 + byte);
+
+ dist += ConvertTo<float>::to(codeDist[offset + code]);
+ }
+ }
+ }
+
+ // Write out intermediate distance result
+ // We do not maintain indices here, in order to reduce global
+ // memory traffic. Those are recovered in the final selection step.
+ distanceOut[codeIndex] = dist;
+
+ // Rotate buffers
+#pragma unroll
+ for (int word = 0; word < kNumCode32; ++word) {
+ code32[word] = nextCode32[word];
+ }
+ }
+}
+
+template <typename CentroidT>
+void runMultiPassTile(
+ GpuResources* res,
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& centroids,
+ Tensor<float, 3, true>& pqCentroidsInnermostCode,
+ NoTypeTensor<4, true>& codeDistances,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ bool useFloat16Lookup,
+ bool useMMCodeDistance,
+ bool interleavedCodeLayout,
+ int bitsPerSubQuantizer,
+ int numSubQuantizers,
+ int numSubQuantizerCodes,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ Tensor<char, 1, true>& thrustMem,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<float, 1, true>& allDistances,
+ Tensor<float, 3, true>& heapDistances,
+ Tensor<idx_t, 3, true>& heapIndices,
+ int k,
+ bool use64BitSelection,
+ faiss::MetricType metric,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ cudaStream_t stream) {
+ // We only support two metrics at the moment
+ FAISS_ASSERT(
+ metric == MetricType::METRIC_INNER_PRODUCT ||
+ metric == MetricType::METRIC_L2);
+
+ bool l2Distance = metric == MetricType::METRIC_L2;
+
+ // Calculate offset lengths, so we know where to write out
+ // intermediate results
+ runCalcListOffsets(
+ res,
+ coarseIndices,
+ listLengths,
+ prefixSumOffsets,
+ thrustMem,
+ stream);
+
+ // Calculate residual code distances, since this is without
+ // precomputed codes
+ runPQCodeDistances(
+ res,
+ pqCentroidsInnermostCode,
+ queries,
+ centroids,
+ coarseDistances,
+ coarseIndices,
+ codeDistances,
+ useMMCodeDistance,
+ l2Distance,
+ useFloat16Lookup,
+ stream);
+
+ if (interleavedCodeLayout) {
+ // The vector interleaved layout implementation
+ auto kThreadsPerBlock = 256;
+
+ auto grid = dim3(coarseIndices.getSize(1), coarseIndices.getSize(0));
+ auto block = dim3(kThreadsPerBlock);
+
+#define RUN_INTERLEAVED(BITS_PER_CODE, CODE_DIST_T) \
+ do { \
+ pqScanInterleaved<uint8_t, BITS_PER_CODE, CODE_DIST_T> \
+ <<<grid, block, 0, stream>>>( \
+ queries, \
+ pqCentroidsInnermostCode, \
+ coarseIndices, \
+ codeDistancesT, \
+ listCodes.data(), \
+ listLengths.data(), \
+ prefixSumOffsets, \
+ allDistances); \
+ } while (0)
+
+ if (useFloat16Lookup) {
+ auto codeDistancesT = codeDistances.toTensor<half>();
+
+ switch (bitsPerSubQuantizer) {
+ case 4: {
+ RUN_INTERLEAVED(4, half);
+ } break;
+ case 5: {
+ RUN_INTERLEAVED(5, half);
+ } break;
+ case 6: {
+ RUN_INTERLEAVED(6, half);
+ } break;
+ case 8: {
+ RUN_INTERLEAVED(8, half);
+ } break;
+ default:
+ FAISS_ASSERT(false);
+ break;
+ }
+ } else {
+ auto codeDistancesT = codeDistances.toTensor<float>();
+
+ switch (bitsPerSubQuantizer) {
+ case 4: {
+ RUN_INTERLEAVED(4, float);
+ } break;
+ case 5: {
+ RUN_INTERLEAVED(5, float);
+ } break;
+ case 6: {
+ RUN_INTERLEAVED(6, float);
+ } break;
+ case 8: {
+ RUN_INTERLEAVED(8, float);
+ } break;
+ default:
+ FAISS_ASSERT(false);
+ break;
+ }
+ }
+ } else {
+ // Convert all codes to a distance, and write out (distance,
+ // index) values for all intermediate results
+ auto kThreadsPerBlock = 256;
+
+ auto grid = dim3(coarseIndices.getSize(1), coarseIndices.getSize(0));
+ auto block = dim3(kThreadsPerBlock);
+
+ // pq centroid distances
+ auto smem = useFloat16Lookup ? sizeof(half) : sizeof(float);
+
+ smem *= numSubQuantizers * numSubQuantizerCodes;
+ FAISS_ASSERT(smem <= getMaxSharedMemPerBlockCurrentDevice());
+
+#define RUN_PQ_OPT(NUM_SUB_Q, LOOKUP_T, LOOKUP_VEC_T) \
+ do { \
+ auto codeDistancesT = codeDistances.toTensor<LOOKUP_T>(); \
+ \
+ pqScanNoPrecomputedMultiPass<NUM_SUB_Q, LOOKUP_T, LOOKUP_VEC_T> \
+ <<<grid, block, smem, stream>>>( \
+ queries, \
+ pqCentroidsInnermostCode, \
+ coarseIndices, \
+ codeDistancesT, \
+ listCodes.data(), \
+ listLengths.data(), \
+ prefixSumOffsets, \
+ allDistances); \
+ } while (0)
+
+#define RUN_PQ(NUM_SUB_Q) \
+ do { \
+ if (useFloat16Lookup) { \
+ RUN_PQ_OPT(NUM_SUB_Q, half, Half8); \
+ } else { \
+ RUN_PQ_OPT(NUM_SUB_Q, float, float4); \
+ } \
+ } while (0)
+
+ switch (numSubQuantizers) {
+ case 1:
+ RUN_PQ(1);
+ break;
+ case 2:
+ RUN_PQ(2);
+ break;
+ case 3:
+ RUN_PQ(3);
+ break;
+ case 4:
+ RUN_PQ(4);
+ break;
+ case 8:
+ RUN_PQ(8);
+ break;
+ case 12:
+ RUN_PQ(12);
+ break;
+ case 16:
+ RUN_PQ(16);
+ break;
+ case 20:
+ RUN_PQ(20);
+ break;
+ case 24:
+ RUN_PQ(24);
+ break;
+ case 28:
+ RUN_PQ(28);
+ break;
+ case 32:
+ RUN_PQ(32);
+ break;
+ case 40:
+ RUN_PQ(40);
+ break;
+ case 48:
+ RUN_PQ(48);
+ break;
+ case 56:
+ RUN_PQ(56);
+ break;
+ case 64:
+ RUN_PQ(64);
+ break;
+ case 96:
+ RUN_PQ(96);
+ break;
+ default:
+ FAISS_ASSERT(false);
+ break;
+ }
+
+#undef RUN_PQ
+#undef RUN_PQ_OPT
+ }
+
+ CUDA_TEST_ERROR();
+
+ // k-select the output in chunks, to increase parallelism
+ runPass1SelectLists(
+ prefixSumOffsets,
+ allDistances,
+ coarseIndices.getSize(1),
+ k,
+ use64BitSelection,
+ !l2Distance, // L2 distance chooses smallest
+ heapDistances,
+ heapIndices,
+ stream);
+
+ // k-select final output
+ auto flatHeapDistances = heapDistances.downcastInner<2>();
+ auto flatHeapIndices = heapIndices.downcastInner<2>();
+
+ runPass2SelectLists(
+ flatHeapDistances,
+ flatHeapIndices,
+ listIndices,
+ indicesOptions,
+ prefixSumOffsets,
+ coarseIndices,
+ k,
+ use64BitSelection,
+ !l2Distance, // L2 distance chooses smallest
+ outDistances,
+ outIndices,
+ stream);
+}
+
+template <typename CentroidT>
+void runPQScanMultiPassNoPrecomputed(
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& centroids,
+ Tensor<float, 3, true>& pqCentroidsInnermostCode,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ bool useFloat16Lookup,
+ bool useMMCodeDistance,
+ bool interleavedCodeLayout,
+ int bitsPerSubQuantizer,
+ int numSubQuantizers,
+ int numSubQuantizerCodes,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ idx_t maxListLength,
+ int k,
+ faiss::MetricType metric,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ auto nprobe = coarseIndices.getSize(1);
+
+ // If the maximum list length (in terms of number of vectors) times nprobe
+ // (number of lists) is > 2^31 - 1, then we will use 64-bit indexing in the
+ // selection kernels
+ constexpr int k32Limit = idx_t(std::numeric_limits<int32_t>::max());
+
+ bool use64BitSelection = (maxListLength * nprobe > k32Limit) ||
+ (queries.getSize(0) > k32Limit);
+
+ // Make a reservation for Thrust to do its dirty work (global memory
+ // cross-block reduction space); hopefully this is large enough.
+ constexpr idx_t kThrustMemSize = 16384;
+
+ DeviceTensor<char, 1, true> thrustMem1(
+ res, makeTempAlloc(AllocType::Other, stream), {kThrustMemSize});
+ DeviceTensor<char, 1, true> thrustMem2(
+ res, makeTempAlloc(AllocType::Other, stream), {kThrustMemSize});
+ DeviceTensor<char, 1, true>* thrustMem[2] = {&thrustMem1, &thrustMem2};
+
+ // How much temporary memory would we need to handle a single query?
+ size_t sizePerQuery = getIVFPQPerQueryTempMemory(
+ k,
+ nprobe,
+ maxListLength,
+ false, /* no precomputed codes */
+ numSubQuantizers,
+ numSubQuantizerCodes);
+
+ // How many queries do we wish to run at once?
+ idx_t queryTileSize = getIVFQueryTileSize(
+ queries.getSize(0),
+ res->getTempMemoryAvailableCurrentDevice(),
+ sizePerQuery);
+
+ // Temporary memory buffers
+ // Make sure there is space prior to the start which will be 0, and
+ // will handle the boundary condition without branches
+ DeviceTensor<idx_t, 1, true> prefixSumOffsetSpace1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe + 1});
+ DeviceTensor<idx_t, 1, true> prefixSumOffsetSpace2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe + 1});
+
+ DeviceTensor<idx_t, 2, true> prefixSumOffsets1(
+ prefixSumOffsetSpace1[1].data(), {queryTileSize, nprobe});
+ DeviceTensor<idx_t, 2, true> prefixSumOffsets2(
+ prefixSumOffsetSpace2[1].data(), {queryTileSize, nprobe});
+ DeviceTensor<idx_t, 2, true>* prefixSumOffsets[2] = {
+ &prefixSumOffsets1, &prefixSumOffsets2};
+
+ // Make sure the element before prefixSumOffsets is 0, since we
+ // depend upon simple, boundary-less indexing to get proper results
+ CUDA_VERIFY(cudaMemsetAsync(
+ prefixSumOffsetSpace1.data(), 0, sizeof(idx_t), stream));
+ CUDA_VERIFY(cudaMemsetAsync(
+ prefixSumOffsetSpace2.data(), 0, sizeof(idx_t), stream));
+
+ idx_t codeDistanceTypeSize =
+ useFloat16Lookup ? sizeof(half) : sizeof(float);
+
+ idx_t totalCodeDistancesSize = queryTileSize * nprobe * numSubQuantizers *
+ numSubQuantizerCodes * codeDistanceTypeSize;
+
+ DeviceTensor<char, 1, true> codeDistances1Mem(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {totalCodeDistancesSize});
+ NoTypeTensor<4, true> codeDistances1(
+ codeDistances1Mem.data(),
+ codeDistanceTypeSize,
+ {queryTileSize, nprobe, numSubQuantizers, numSubQuantizerCodes});
+
+ DeviceTensor<char, 1, true> codeDistances2Mem(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {totalCodeDistancesSize});
+ NoTypeTensor<4, true> codeDistances2(
+ codeDistances2Mem.data(),
+ codeDistanceTypeSize,
+ {queryTileSize, nprobe, numSubQuantizers, numSubQuantizerCodes});
+
+ NoTypeTensor<4, true>* codeDistances[2] = {
+ &codeDistances1, &codeDistances2};
+
+ DeviceTensor<float, 1, true> allDistances1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe * maxListLength});
+ DeviceTensor<float, 1, true> allDistances2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe * maxListLength});
+ DeviceTensor<float, 1, true>* allDistances[2] = {
+ &allDistances1, &allDistances2};
+
+ idx_t pass2Chunks = getIVFKSelectionPass2Chunks(nprobe);
+ DeviceTensor<float, 3, true> heapDistances1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<float, 3, true> heapDistances2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<float, 3, true>* heapDistances[2] = {
+ &heapDistances1, &heapDistances2};
+
+ DeviceTensor<idx_t, 3, true> heapIndices1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<idx_t, 3, true> heapIndices2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<idx_t, 3, true>* heapIndices[2] = {
+ &heapIndices1, &heapIndices2};
+
+ auto streams = res->getAlternateStreamsCurrentDevice();
+ streamWait(streams, {stream});
+
+ int curStream = 0;
+
+ for (idx_t query = 0; query < queries.getSize(0); query += queryTileSize) {
+ idx_t numQueriesInTile =
+ std::min(queryTileSize, queries.getSize(0) - query);
+
+ auto prefixSumOffsetsView =
+ prefixSumOffsets[curStream]->narrowOutermost(
+ 0, numQueriesInTile);
+
+ auto codeDistancesView =
+ codeDistances[curStream]->narrowOutermost(0, numQueriesInTile);
+ auto coarseDistancesView =
+ coarseDistances.narrowOutermost(query, numQueriesInTile);
+ auto coarseIndicesView =
+ coarseIndices.narrowOutermost(query, numQueriesInTile);
+ auto queryView = queries.narrowOutermost(query, numQueriesInTile);
+
+ auto heapDistancesView =
+ heapDistances[curStream]->narrowOutermost(0, numQueriesInTile);
+ auto heapIndicesView =
+ heapIndices[curStream]->narrowOutermost(0, numQueriesInTile);
+
+ auto outDistanceView =
+ outDistances.narrowOutermost(query, numQueriesInTile);
+ auto outIndicesView =
+ outIndices.narrowOutermost(query, numQueriesInTile);
+
+ runMultiPassTile(
+ res,
+ queryView,
+ centroids,
+ pqCentroidsInnermostCode,
+ codeDistancesView,
+ coarseDistancesView,
+ coarseIndicesView,
+ useFloat16Lookup,
+ useMMCodeDistance,
+ interleavedCodeLayout,
+ bitsPerSubQuantizer,
+ numSubQuantizers,
+ numSubQuantizerCodes,
+ listCodes,
+ listIndices,
+ indicesOptions,
+ listLengths,
+ *thrustMem[curStream],
+ prefixSumOffsetsView,
+ *allDistances[curStream],
+ heapDistancesView,
+ heapIndicesView,
+ k,
+ use64BitSelection,
+ metric,
+ outDistanceView,
+ outIndicesView,
+ streams[curStream]);
+
+ curStream = (curStream + 1) % 2;
+ }
+
+ streamWait({stream}, streams);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassNoPrecomputed.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassNoPrecomputed.cuh
new file mode 100644
index 0000000..bed1321
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassNoPrecomputed.cuh
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+template <typename CentroidT>
+void runPQScanMultiPassNoPrecomputed(
+ Tensor<float, 2, true>& queries,
+ Tensor<CentroidT, 2, true>& centroids,
+ Tensor<float, 3, true>& pqCentroidsInnermostCode,
+ Tensor<float, 2, true>& coarseDistances,
+ Tensor<idx_t, 2, true>& coarseIndices,
+ bool useFloat16Lookup,
+ bool useMMCodeDistance,
+ bool interleavedCodeLayout,
+ int bitsPerSubQuantizer,
+ int numSubQuantizers,
+ int numSubQuantizerCodes,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ idx_t maxListLength,
+ int k,
+ faiss::MetricType metric,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res);
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/impl/PQScanMultiPassNoPrecomputed-inl.cuh>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassPrecomputed.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassPrecomputed.cu
new file mode 100644
index 0000000..4c4cdc4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassPrecomputed.cu
@@ -0,0 +1,723 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/impl/IVFUtils.cuh>
+#include <faiss/gpu/impl/PQCodeLoad.cuh>
+#include <faiss/gpu/impl/PQScanMultiPassPrecomputed.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/LoadStoreOperators.cuh>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/WarpPackedBits.cuh>
+
+#include <algorithm>
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+// A basic implementation that works for the interleaved by vector layout for
+// any number of sub-quantizers
+template <typename EncodeT, int EncodeBits, typename CodeDistanceT>
+__global__ void pqScanPrecomputedInterleaved(
+ Tensor<float, 2, true> queries,
+ // (query id)(probe id)
+ Tensor<float, 2, true> precompTerm1,
+ // (centroid id)(sub q)(code id)
+ Tensor<CodeDistanceT, 3, true> precompTerm2,
+ // (query id)(sub q)(code id)
+ Tensor<CodeDistanceT, 3, true> precompTerm3,
+ Tensor<idx_t, 2, true> ivfListIds,
+ void** listCodes,
+ idx_t* listLengths,
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<float, 1, true> distance) {
+ // Each block handles a single query versus single list
+ auto queryId = blockIdx.y;
+ auto probeId = blockIdx.x;
+
+ idx_t listId = ivfListIds[queryId][probeId];
+ // Safety guard in case NaNs in input cause no list ID to be generated
+ if (listId == -1) {
+ return;
+ }
+
+ int numWarps = blockDim.x / kWarpSize;
+ // FIXME: some issue with getLaneId() and CUDA 10.1 and P4 GPUs?
+ int laneId = threadIdx.x % kWarpSize;
+ int warpId = threadIdx.x / kWarpSize;
+
+ auto numSubQuantizers = precompTerm2.getSize(1);
+ auto codesPerSubQuantizer = precompTerm2.getSize(2);
+
+ // This is where we start writing out data
+ // We ensure that before the array (at offset -1), there is a 0 value
+ auto outBase = *(prefixSumOffsets[queryId][probeId].data() - 1);
+ float* distanceOut = distance[outBase].data();
+
+ auto vecsBase = (EncodeT*)listCodes[listId];
+ idx_t numVecs = listLengths[listId];
+
+ // How many vector blocks of kWarpSize are in this list?
+ idx_t numBlocks = utils::divUp(numVecs, idx_t(kWarpSize));
+
+ // Number of EncodeT words per each dimension of block of kWarpSize vecs
+ constexpr idx_t bytesPerVectorBlockDim = EncodeBits * kWarpSize / 8;
+ constexpr idx_t wordsPerVectorBlockDim =
+ bytesPerVectorBlockDim / sizeof(EncodeT);
+ idx_t wordsPerVectorBlock = wordsPerVectorBlockDim * numSubQuantizers;
+
+ // This is constant for the (query, probe)
+ float term1 = precompTerm1[queryId][probeId];
+
+ for (idx_t block = warpId; block < numBlocks; block += numWarps) {
+ float dist = term1;
+
+ // This is the vector a given lane/thread handles
+ idx_t vec = block * kWarpSize + laneId;
+ bool valid = vec < numVecs;
+
+ EncodeT* data = vecsBase + block * wordsPerVectorBlock;
+ auto term2Base = precompTerm2[listId].data();
+ auto term3Base = precompTerm3[queryId].data();
+
+ for (int sq = 0; sq < numSubQuantizers; ++sq) {
+ EncodeT enc =
+ WarpPackedBits<EncodeT, EncodeBits>::read(laneId, data);
+ EncodeT code =
+ WarpPackedBits<EncodeT, EncodeBits>::postRead(laneId, enc);
+
+ dist += valid ? (ConvertTo<float>::to(term2Base[code]) +
+ ConvertTo<float>::to(term3Base[code]))
+ : 0;
+
+ data += wordsPerVectorBlockDim;
+ term2Base += codesPerSubQuantizer;
+ term3Base += codesPerSubQuantizer;
+ }
+
+ if (valid) {
+ distanceOut[vec] = dist;
+ }
+ }
+}
+
+// For precomputed codes, this calculates and loads code distances
+// into smem
+template <typename LookupT, typename LookupVecT>
+inline __device__ void loadPrecomputedTerm(
+ LookupT* smem,
+ LookupT* term2Start,
+ LookupT* term3Start,
+ int numCodes) {
+ constexpr int kWordSize = sizeof(LookupVecT) / sizeof(LookupT);
+
+ // We can only use vector loads if the data is guaranteed to be
+ // aligned. The codes are innermost, so if it is evenly divisible,
+ // then any slice will be aligned.
+ if (numCodes % kWordSize == 0) {
+ constexpr int kUnroll = 2;
+
+ // Load the data by float4 for efficiency, and then handle any remainder
+ // limitVec is the number of whole vec words we can load, in terms
+ // of whole blocks performing the load
+ idx_t limitVec = numCodes / (kUnroll * kWordSize * blockDim.x);
+ limitVec *= kUnroll * blockDim.x;
+
+ LookupVecT* smemV = (LookupVecT*)smem;
+ LookupVecT* term2StartV = (LookupVecT*)term2Start;
+ LookupVecT* term3StartV = (LookupVecT*)term3Start;
+
+ for (idx_t i = threadIdx.x; i < limitVec; i += kUnroll * blockDim.x) {
+ LookupVecT vals[kUnroll];
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = LoadStore<LookupVecT>::load(
+ &term2StartV[i + j * blockDim.x]);
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ LookupVecT q = LoadStore<LookupVecT>::load(
+ &term3StartV[i + j * blockDim.x]);
+
+ vals[j] = Math<LookupVecT>::add(vals[j], q);
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ LoadStore<LookupVecT>::store(
+ &smemV[i + j * blockDim.x], vals[j]);
+ }
+ }
+
+ // This is where we start loading the remainder that does not evenly
+ // fit into kUnroll x blockDim.x
+ int remainder = limitVec * kWordSize;
+
+ for (idx_t i = remainder + threadIdx.x; i < numCodes; i += blockDim.x) {
+ smem[i] = Math<LookupT>::add(term2Start[i], term3Start[i]);
+ }
+ } else {
+ // Potential unaligned load
+ constexpr int kUnroll = 4;
+
+ idx_t limit = utils::roundDown(numCodes, kUnroll * blockDim.x);
+
+ idx_t i = threadIdx.x;
+ for (; i < limit; i += kUnroll * blockDim.x) {
+ LookupT vals[kUnroll];
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = term2Start[i + j * blockDim.x];
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ vals[j] = Math<LookupT>::add(
+ vals[j], term3Start[i + j * blockDim.x]);
+ }
+
+#pragma unroll
+ for (int j = 0; j < kUnroll; ++j) {
+ smem[i + j * blockDim.x] = vals[j];
+ }
+ }
+
+ for (; i < numCodes; i += blockDim.x) {
+ smem[i] = Math<LookupT>::add(term2Start[i], term3Start[i]);
+ }
+ }
+}
+
+template <int NumSubQuantizers, typename LookupT, typename LookupVecT>
+__global__ void pqScanPrecomputedMultiPass(
+ Tensor<float, 2, true> queries,
+ Tensor<float, 2, true> precompTerm1,
+ Tensor<LookupT, 3, true> precompTerm2,
+ Tensor<LookupT, 3, true> precompTerm3,
+ Tensor<idx_t, 2, true> ivfListIds,
+ void** listCodes,
+ idx_t* listLengths,
+ Tensor<idx_t, 2, true> prefixSumOffsets,
+ Tensor<float, 1, true> distance) {
+ // precomputed term 2 + 3 storage
+ // (sub q)(code id)
+ extern __shared__ char smemTerm23[];
+ LookupT* term23 = (LookupT*)smemTerm23;
+
+ // Each block handles a single query
+ auto queryId = blockIdx.y;
+ auto probeId = blockIdx.x;
+ auto codesPerSubQuantizer = precompTerm2.getSize(2);
+ auto precompTermSize = precompTerm2.getSize(1) * codesPerSubQuantizer;
+
+ // This is where we start writing out data
+ // We ensure that before the array (at offset -1), there is a 0 value
+ idx_t outBase = *(prefixSumOffsets[queryId][probeId].data() - 1);
+ float* distanceOut = distance[outBase].data();
+
+ idx_t listId = ivfListIds[queryId][probeId];
+ // Safety guard in case NaNs in input cause no list ID to be generated
+ if (listId == -1) {
+ return;
+ }
+
+ uint8_t* codeList = (uint8_t*)listCodes[listId];
+ idx_t limit = listLengths[listId];
+
+ constexpr idx_t kNumCode32 =
+ NumSubQuantizers <= 4 ? 1 : (NumSubQuantizers / 4);
+ unsigned int code32[kNumCode32];
+ unsigned int nextCode32[kNumCode32];
+
+ // We double-buffer the code loading, which improves memory utilization
+ if (threadIdx.x < limit) {
+ LoadCode32<NumSubQuantizers>::load(code32, codeList, threadIdx.x);
+ }
+
+ // Load precomputed terms 1, 2, 3
+ float term1 = precompTerm1[queryId][probeId];
+ loadPrecomputedTerm<LookupT, LookupVecT>(
+ term23,
+ precompTerm2[listId].data(),
+ precompTerm3[queryId].data(),
+ precompTermSize);
+
+ // Prevent WAR dependencies
+ __syncthreads();
+
+ // Each thread handles one code element in the list, with a
+ // block-wide stride
+ for (idx_t codeIndex = threadIdx.x; codeIndex < limit;
+ codeIndex += blockDim.x) {
+ // Prefetch next codes
+ if (codeIndex + blockDim.x < limit) {
+ LoadCode32<NumSubQuantizers>::load(
+ nextCode32, codeList, codeIndex + blockDim.x);
+ }
+
+ float dist = term1;
+
+#pragma unroll
+ for (int word = 0; word < kNumCode32; ++word) {
+ constexpr int kBytesPerCode32 =
+ NumSubQuantizers < 4 ? NumSubQuantizers : 4;
+
+ if (kBytesPerCode32 == 1) {
+ auto code = code32[0];
+ dist = ConvertTo<float>::to(term23[code]);
+
+ } else {
+#pragma unroll
+ for (int byte = 0; byte < kBytesPerCode32; ++byte) {
+ auto code = getByte(code32[word], byte * 8, 8);
+
+ auto offset = codesPerSubQuantizer *
+ (word * kBytesPerCode32 + byte);
+
+ dist += ConvertTo<float>::to(term23[offset + code]);
+ }
+ }
+ }
+
+ // Write out intermediate distance result
+ // We do not maintain indices here, in order to reduce global
+ // memory traffic. Those are recovered in the final selection step.
+ distanceOut[codeIndex] = dist;
+
+ // Rotate buffers
+#pragma unroll
+ for (int word = 0; word < kNumCode32; ++word) {
+ code32[word] = nextCode32[word];
+ }
+ }
+}
+
+void runMultiPassTile(
+ GpuResources* res,
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& precompTerm1,
+ NoTypeTensor<3, true>& precompTerm2,
+ NoTypeTensor<3, true>& precompTerm3,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ bool useFloat16Lookup,
+ bool interleavedCodeLayout,
+ int bitsPerSubQuantizer,
+ int numSubQuantizers,
+ int numSubQuantizerCodes,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ Tensor<char, 1, true>& thrustMem,
+ Tensor<idx_t, 2, true>& prefixSumOffsets,
+ Tensor<float, 1, true>& allDistances,
+ Tensor<float, 3, true>& heapDistances,
+ Tensor<idx_t, 3, true>& heapIndices,
+ int k,
+ bool use64BitSelection,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ cudaStream_t stream) {
+ // Calculate offset lengths, so we know where to write out
+ // intermediate results
+ runCalcListOffsets(
+ res, ivfListIds, listLengths, prefixSumOffsets, thrustMem, stream);
+
+ // The vector interleaved layout implementation
+ if (interleavedCodeLayout) {
+ auto kThreadsPerBlock = 256;
+
+ auto grid = dim3(ivfListIds.getSize(1), ivfListIds.getSize(0));
+ auto block = dim3(kThreadsPerBlock);
+
+#define RUN_INTERLEAVED(BITS_PER_CODE, CODE_DIST_T) \
+ do { \
+ pqScanPrecomputedInterleaved<uint8_t, BITS_PER_CODE, CODE_DIST_T> \
+ <<<grid, block, 0, stream>>>( \
+ queries, \
+ precompTerm1, \
+ precompTerm2T, \
+ precompTerm3T, \
+ ivfListIds, \
+ listCodes.data(), \
+ listLengths.data(), \
+ prefixSumOffsets, \
+ allDistances); \
+ } while (0)
+
+ if (useFloat16Lookup) {
+ auto precompTerm2T = precompTerm2.toTensor<half>();
+ auto precompTerm3T = precompTerm3.toTensor<half>();
+
+ switch (bitsPerSubQuantizer) {
+ case 4: {
+ RUN_INTERLEAVED(4, half);
+ } break;
+ case 5: {
+ RUN_INTERLEAVED(5, half);
+ } break;
+ case 6: {
+ RUN_INTERLEAVED(6, half);
+ } break;
+ case 8: {
+ RUN_INTERLEAVED(8, half);
+ } break;
+ default:
+ FAISS_ASSERT(false);
+ break;
+ }
+ } else {
+ auto precompTerm2T = precompTerm2.toTensor<float>();
+ auto precompTerm3T = precompTerm3.toTensor<float>();
+
+ switch (bitsPerSubQuantizer) {
+ case 4: {
+ RUN_INTERLEAVED(4, float);
+ } break;
+ case 5: {
+ RUN_INTERLEAVED(5, float);
+ } break;
+ case 6: {
+ RUN_INTERLEAVED(6, float);
+ } break;
+ case 8: {
+ RUN_INTERLEAVED(8, float);
+ } break;
+ default:
+ FAISS_ASSERT(false);
+ break;
+ }
+ }
+ } else {
+ // Convert all codes to a distance, and write out (distance,
+ // index) values for all intermediate results
+ auto kThreadsPerBlock = 256;
+
+ auto grid = dim3(ivfListIds.getSize(1), ivfListIds.getSize(0));
+ auto block = dim3(kThreadsPerBlock);
+
+ // pq precomputed terms (2 + 3)
+ auto smem = useFloat16Lookup ? sizeof(half) : sizeof(float);
+
+ smem *= numSubQuantizers * numSubQuantizerCodes;
+ FAISS_ASSERT(smem <= getMaxSharedMemPerBlockCurrentDevice());
+
+#define RUN_PQ_OPT(NUM_SUB_Q, LOOKUP_T, LOOKUP_VEC_T) \
+ do { \
+ auto precompTerm2T = precompTerm2.toTensor<LOOKUP_T>(); \
+ auto precompTerm3T = precompTerm3.toTensor<LOOKUP_T>(); \
+ \
+ pqScanPrecomputedMultiPass<NUM_SUB_Q, LOOKUP_T, LOOKUP_VEC_T> \
+ <<<grid, block, smem, stream>>>( \
+ queries, \
+ precompTerm1, \
+ precompTerm2T, \
+ precompTerm3T, \
+ ivfListIds, \
+ listCodes.data(), \
+ listLengths.data(), \
+ prefixSumOffsets, \
+ allDistances); \
+ } while (0)
+
+#define RUN_PQ(NUM_SUB_Q) \
+ do { \
+ if (useFloat16Lookup) { \
+ RUN_PQ_OPT(NUM_SUB_Q, half, Half8); \
+ } else { \
+ RUN_PQ_OPT(NUM_SUB_Q, float, float4); \
+ } \
+ } while (0)
+
+ switch (numSubQuantizers) {
+ case 1:
+ RUN_PQ(1);
+ break;
+ case 2:
+ RUN_PQ(2);
+ break;
+ case 3:
+ RUN_PQ(3);
+ break;
+ case 4:
+ RUN_PQ(4);
+ break;
+ case 8:
+ RUN_PQ(8);
+ break;
+ case 12:
+ RUN_PQ(12);
+ break;
+ case 16:
+ RUN_PQ(16);
+ break;
+ case 20:
+ RUN_PQ(20);
+ break;
+ case 24:
+ RUN_PQ(24);
+ break;
+ case 28:
+ RUN_PQ(28);
+ break;
+ case 32:
+ RUN_PQ(32);
+ break;
+ case 40:
+ RUN_PQ(40);
+ break;
+ case 48:
+ RUN_PQ(48);
+ break;
+ case 56:
+ RUN_PQ(56);
+ break;
+ case 64:
+ RUN_PQ(64);
+ break;
+ case 96:
+ RUN_PQ(96);
+ break;
+ default:
+ FAISS_ASSERT(false);
+ break;
+ }
+
+ CUDA_TEST_ERROR();
+
+#undef RUN_PQ
+#undef RUN_PQ_OPT
+#undef RUN_INTERLEAVED
+ }
+
+ // k-select the output in chunks, to increase parallelism
+ runPass1SelectLists(
+ prefixSumOffsets,
+ allDistances,
+ ivfListIds.getSize(1),
+ k,
+ use64BitSelection,
+ false, // L2 distance chooses smallest
+ heapDistances,
+ heapIndices,
+ stream);
+
+ // k-select final output
+ auto flatHeapDistances = heapDistances.downcastInner<2>();
+ auto flatHeapIndices = heapIndices.downcastInner<2>();
+
+ runPass2SelectLists(
+ flatHeapDistances,
+ flatHeapIndices,
+ listIndices,
+ indicesOptions,
+ prefixSumOffsets,
+ ivfListIds,
+ k,
+ use64BitSelection,
+ false, // L2 distance chooses smallest
+ outDistances,
+ outIndices,
+ stream);
+
+ CUDA_TEST_ERROR();
+}
+
+void runPQScanMultiPassPrecomputed(
+ Tensor<float, 2, true>& queries,
+ // (query id)(probe id)
+ Tensor<float, 2, true>& precompTerm1,
+ // (centroid id)(sub q)(code id)
+ NoTypeTensor<3, true>& precompTerm2,
+ // (query id)(sub q)(code id)
+ NoTypeTensor<3, true>& precompTerm3,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ bool useFloat16Lookup,
+ bool interleavedCodeLayout,
+ int bitsPerSubQuantizer,
+ int numSubQuantizers,
+ int numSubQuantizerCodes,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ idx_t maxListLength,
+ int k,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ auto stream = res->getDefaultStreamCurrentDevice();
+
+ auto nprobe = ivfListIds.getSize(1);
+
+ // If the maximum list length (in terms of number of vectors) times nprobe
+ // (number of lists) is > 2^31 - 1, then we will use 64-bit indexing in the
+ // selection kernels
+ constexpr int k32Limit = idx_t(std::numeric_limits<int32_t>::max());
+
+ bool use64BitSelection = (maxListLength * nprobe > k32Limit) ||
+ (queries.getSize(0) > k32Limit);
+
+ // Make a reservation for Thrust to do its dirty work (global memory
+ // cross-block reduction space); hopefully this is large enough.
+ constexpr idx_t kThrustMemSize = 16384;
+
+ DeviceTensor<char, 1, true> thrustMem1(
+ res, makeTempAlloc(AllocType::Other, stream), {kThrustMemSize});
+ DeviceTensor<char, 1, true> thrustMem2(
+ res, makeTempAlloc(AllocType::Other, stream), {kThrustMemSize});
+ DeviceTensor<char, 1, true>* thrustMem[2] = {&thrustMem1, &thrustMem2};
+
+ // How much temporary memory would we need to handle a single query?
+ size_t sizePerQuery = getIVFPQPerQueryTempMemory(
+ k,
+ nprobe,
+ maxListLength,
+ true, /* precomputed codes */
+ numSubQuantizers,
+ numSubQuantizerCodes);
+
+ // How many queries do we wish to run at once?
+ idx_t queryTileSize = getIVFQueryTileSize(
+ queries.getSize(0),
+ res->getTempMemoryAvailableCurrentDevice(),
+ sizePerQuery);
+
+ // Temporary memory buffers
+ // Make sure there is space prior to the start which will be 0, and
+ // will handle the boundary condition without branches
+ DeviceTensor<idx_t, 1, true> prefixSumOffsetSpace1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe + 1});
+ DeviceTensor<idx_t, 1, true> prefixSumOffsetSpace2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe + 1});
+
+ DeviceTensor<idx_t, 2, true> prefixSumOffsets1(
+ prefixSumOffsetSpace1[1].data(), {queryTileSize, nprobe});
+ DeviceTensor<idx_t, 2, true> prefixSumOffsets2(
+ prefixSumOffsetSpace2[1].data(), {queryTileSize, nprobe});
+ DeviceTensor<idx_t, 2, true>* prefixSumOffsets[2] = {
+ &prefixSumOffsets1, &prefixSumOffsets2};
+
+ // Make sure the element before prefixSumOffsets is 0, since we
+ // depend upon simple, boundary-less indexing to get proper results
+ CUDA_VERIFY(cudaMemsetAsync(
+ prefixSumOffsetSpace1.data(), 0, sizeof(idx_t), stream));
+ CUDA_VERIFY(cudaMemsetAsync(
+ prefixSumOffsetSpace2.data(), 0, sizeof(idx_t), stream));
+
+ DeviceTensor<float, 1, true> allDistances1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe * maxListLength});
+ DeviceTensor<float, 1, true> allDistances2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize * nprobe * maxListLength});
+ DeviceTensor<float, 1, true>* allDistances[2] = {
+ &allDistances1, &allDistances2};
+
+ idx_t pass2Chunks = getIVFKSelectionPass2Chunks(nprobe);
+ DeviceTensor<float, 3, true> heapDistances1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<float, 3, true> heapDistances2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<float, 3, true>* heapDistances[2] = {
+ &heapDistances1, &heapDistances2};
+
+ DeviceTensor<idx_t, 3, true> heapIndices1(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<idx_t, 3, true> heapIndices2(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queryTileSize, pass2Chunks, k});
+ DeviceTensor<idx_t, 3, true>* heapIndices[2] = {
+ &heapIndices1, &heapIndices2};
+
+ auto streams = res->getAlternateStreamsCurrentDevice();
+ streamWait(streams, {stream});
+
+ int curStream = 0;
+
+ for (idx_t query = 0; query < queries.getSize(0); query += queryTileSize) {
+ idx_t numQueriesInTile =
+ std::min(queryTileSize, queries.getSize(0) - query);
+
+ auto prefixSumOffsetsView =
+ prefixSumOffsets[curStream]->narrowOutermost(
+ 0, numQueriesInTile);
+
+ auto coarseIndicesView =
+ ivfListIds.narrowOutermost(query, numQueriesInTile);
+ auto queryView = queries.narrowOutermost(query, numQueriesInTile);
+ auto term1View = precompTerm1.narrowOutermost(query, numQueriesInTile);
+ auto term3View = precompTerm3.narrowOutermost(query, numQueriesInTile);
+
+ auto heapDistancesView =
+ heapDistances[curStream]->narrowOutermost(0, numQueriesInTile);
+ auto heapIndicesView =
+ heapIndices[curStream]->narrowOutermost(0, numQueriesInTile);
+
+ auto outDistanceView =
+ outDistances.narrowOutermost(query, numQueriesInTile);
+ auto outIndicesView =
+ outIndices.narrowOutermost(query, numQueriesInTile);
+
+ runMultiPassTile(
+ res,
+ queryView,
+ term1View,
+ precompTerm2,
+ term3View,
+ coarseIndicesView,
+ useFloat16Lookup,
+ interleavedCodeLayout,
+ bitsPerSubQuantizer,
+ numSubQuantizers,
+ numSubQuantizerCodes,
+ listCodes,
+ listIndices,
+ indicesOptions,
+ listLengths,
+ *thrustMem[curStream],
+ prefixSumOffsetsView,
+ *allDistances[curStream],
+ heapDistancesView,
+ heapIndicesView,
+ k,
+ use64BitSelection,
+ outDistanceView,
+ outIndicesView,
+ streams[curStream]);
+
+ curStream = (curStream + 1) % 2;
+ }
+
+ streamWait({stream}, streams);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassPrecomputed.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassPrecomputed.cuh
new file mode 100644
index 0000000..7da19aa
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/PQScanMultiPassPrecomputed.cuh
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+#include <faiss/gpu/utils/NoTypeTensor.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+void runPQScanMultiPassPrecomputed(
+ Tensor<float, 2, true>& queries,
+ Tensor<float, 2, true>& precompTerm1,
+ NoTypeTensor<3, true>& precompTerm2,
+ NoTypeTensor<3, true>& precompTerm3,
+ Tensor<idx_t, 2, true>& ivfListIds,
+ bool useFloat16Lookup,
+ bool interleavedCodeLayout,
+ int bitsPerSubQuantizer,
+ int numSubQuantizers,
+ int numSubQuantizerCodes,
+ DeviceVector<void*>& listCodes,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ idx_t maxListLength,
+ int k,
+ // output
+ Tensor<float, 2, true>& outDistances,
+ // output
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/RemapIndices.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/RemapIndices.cpp
new file mode 100644
index 0000000..42d5e52
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/RemapIndices.cpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/RemapIndices.h>
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+namespace gpu {
+
+// Utility function to translate (list id, offset) to a user index on
+// the CPU. In a cpp in order to use OpenMP
+void ivfOffsetToUserIndex(
+ idx_t* indices,
+ idx_t numLists,
+ idx_t queries,
+ int k,
+ const std::vector<std::vector<idx_t>>& listOffsetToUserIndex) {
+ FAISS_ASSERT(numLists == listOffsetToUserIndex.size());
+
+#pragma omp parallel for
+ for (idx_t q = 0; q < queries; ++q) {
+ for (idx_t r = 0; r < k; ++r) {
+ auto offsetIndex = indices[q * k + r];
+
+ if (offsetIndex < 0) {
+ continue;
+ }
+
+ // FIXME: implicit limit on list and list offset length
+ int listId = (int)(offsetIndex >> 32);
+ int listOffset = (int)(offsetIndex & 0xffffffff);
+
+ FAISS_ASSERT(listId < numLists);
+ auto& listIndices = listOffsetToUserIndex[listId];
+
+ FAISS_ASSERT(listOffset < listIndices.size());
+ indices[q * k + r] = listIndices[listOffset];
+ }
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/RemapIndices.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/RemapIndices.h
new file mode 100644
index 0000000..997339e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/RemapIndices.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <vector>
+
+namespace faiss {
+namespace gpu {
+
+/// Utility function to translate (list id, offset) to a user index on
+/// the CPU. In a cpp in order to use OpenMP.
+void ivfOffsetToUserIndex(
+ idx_t* indices,
+ idx_t numLists,
+ idx_t queries,
+ int k,
+ const std::vector<std::vector<idx_t>>& listOffsetToUserIndex);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/VectorResidual.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/VectorResidual.cu
new file mode 100644
index 0000000..4250365
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/VectorResidual.cu
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#ifdef USE_AMD_ROCM
+#define CUDART_NAN_F __int_as_float(0x7fffffff)
+#else
+#include <math_constants.h> // in CUDA SDK, for CUDART_NAN_F
+#endif
+#include <faiss/gpu/impl/VectorResidual.cuh>
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+#include <algorithm>
+
+namespace faiss {
+namespace gpu {
+
+template <typename CentroidT, bool LargeDim>
+__global__ void calcResidual(
+ Tensor<float, 2, true> vecs,
+ Tensor<CentroidT, 2, true> centroids,
+ Tensor<idx_t, 1, true> vecToCentroid,
+ Tensor<float, 2, true> residuals) {
+ auto vec = vecs[blockIdx.x];
+ auto residual = residuals[blockIdx.x];
+ auto centroidId = vecToCentroid[blockIdx.x];
+
+ // Vector could be invalid (containing NaNs), so -1 was the
+ // classified centroid
+ if (centroidId == -1) {
+ if (LargeDim) {
+ for (idx_t i = threadIdx.x; i < vecs.getSize(1); i += blockDim.x) {
+ residual[i] = CUDART_NAN_F;
+ }
+ } else {
+ residual[threadIdx.x] = CUDART_NAN_F;
+ }
+
+ return;
+ }
+
+ auto centroid = centroids[centroidId];
+
+ if (LargeDim) {
+ for (idx_t i = threadIdx.x; i < vecs.getSize(1); i += blockDim.x) {
+ residual[i] = vec[i] - ConvertTo<float>::to(centroid[i]);
+ }
+ } else {
+ residual[threadIdx.x] =
+ vec[threadIdx.x] - ConvertTo<float>::to(centroid[threadIdx.x]);
+ }
+}
+
+template <typename CentroidT>
+void calcResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<CentroidT, 2, true>& centroids,
+ Tensor<idx_t, 1, true>& vecToCentroid,
+ Tensor<float, 2, true>& residuals,
+ cudaStream_t stream) {
+ FAISS_ASSERT(vecs.getSize(1) == centroids.getSize(1));
+ FAISS_ASSERT(vecs.getSize(1) == residuals.getSize(1));
+ FAISS_ASSERT(vecs.getSize(0) == vecToCentroid.getSize(0));
+ FAISS_ASSERT(vecs.getSize(0) == residuals.getSize(0));
+
+ dim3 grid(vecs.getSize(0));
+
+ idx_t maxThreads = getMaxThreadsCurrentDevice();
+ bool largeDim = vecs.getSize(1) > maxThreads;
+ dim3 block(std::min(vecs.getSize(1), maxThreads));
+
+ if (largeDim) {
+ calcResidual<CentroidT, true><<<grid, block, 0, stream>>>(
+ vecs, centroids, vecToCentroid, residuals);
+ } else {
+ calcResidual<CentroidT, false><<<grid, block, 0, stream>>>(
+ vecs, centroids, vecToCentroid, residuals);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+void runCalcResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& centroids,
+ Tensor<idx_t, 1, true>& vecToCentroid,
+ Tensor<float, 2, true>& residuals,
+ cudaStream_t stream) {
+ calcResidual<float>(vecs, centroids, vecToCentroid, residuals, stream);
+}
+
+void runCalcResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<half, 2, true>& centroids,
+ Tensor<idx_t, 1, true>& vecToCentroid,
+ Tensor<float, 2, true>& residuals,
+ cudaStream_t stream) {
+ calcResidual<half>(vecs, centroids, vecToCentroid, residuals, stream);
+}
+
+template <typename T>
+__global__ void gatherReconstructByIds(
+ Tensor<idx_t, 1, true> ids,
+ Tensor<T, 2, true> vecs,
+ Tensor<float, 2, true> out) {
+ auto id = ids[blockIdx.x];
+ auto vec = vecs[id];
+ auto outVec = out[blockIdx.x];
+
+ for (idx_t i = threadIdx.x; i < vecs.getSize(1); i += blockDim.x) {
+ outVec[i] = id == idx_t(-1) ? 0.0f : ConvertTo<float>::to(vec[i]);
+ }
+}
+
+template <typename T>
+__global__ void gatherReconstructByRange(
+ idx_t start,
+ idx_t num,
+ Tensor<T, 2, true> vecs,
+ Tensor<float, 2, true> out) {
+ auto id = start + blockIdx.x;
+ auto vec = vecs[id];
+ auto outVec = out[blockIdx.x];
+
+ for (idx_t i = threadIdx.x; i < vecs.getSize(1); i += blockDim.x) {
+ outVec[i] = id == idx_t(-1) ? 0.0f : ConvertTo<float>::to(vec[i]);
+ }
+}
+
+template <typename T>
+void gatherReconstructByIds(
+ Tensor<idx_t, 1, true>& ids,
+ Tensor<T, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream) {
+ FAISS_ASSERT(ids.getSize(0) == out.getSize(0));
+ FAISS_ASSERT(vecs.getSize(1) == out.getSize(1));
+
+ dim3 grid(ids.getSize(0));
+
+ idx_t maxThreads = getMaxThreadsCurrentDevice();
+ dim3 block(std::min(vecs.getSize(1), maxThreads));
+
+ gatherReconstructByIds<T><<<grid, block, 0, stream>>>(ids, vecs, out);
+
+ CUDA_TEST_ERROR();
+}
+
+template <typename T>
+void gatherReconstructByRange(
+ idx_t start,
+ idx_t num,
+ Tensor<T, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream) {
+ FAISS_ASSERT(num > 0);
+ FAISS_ASSERT(num == out.getSize(0));
+ FAISS_ASSERT(vecs.getSize(1) == out.getSize(1));
+ FAISS_ASSERT(start + num <= vecs.getSize(0));
+
+ dim3 grid(num);
+
+ idx_t maxThreads = getMaxThreadsCurrentDevice();
+ dim3 block(std::min(vecs.getSize(1), maxThreads));
+
+ gatherReconstructByRange<T>
+ <<<grid, block, 0, stream>>>(start, num, vecs, out);
+
+ CUDA_TEST_ERROR();
+}
+
+void runReconstruct(
+ Tensor<idx_t, 1, true>& ids,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream) {
+ gatherReconstructByIds<float>(ids, vecs, out, stream);
+}
+
+void runReconstruct(
+ Tensor<idx_t, 1, true>& ids,
+ Tensor<half, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream) {
+ gatherReconstructByIds<half>(ids, vecs, out, stream);
+}
+
+void runReconstruct(
+ idx_t start,
+ idx_t num,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream) {
+ gatherReconstructByRange<float>(start, num, vecs, out, stream);
+}
+
+void runReconstruct(
+ idx_t start,
+ idx_t num,
+ Tensor<half, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream) {
+ gatherReconstructByRange<half>(start, num, vecs, out, stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/VectorResidual.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/VectorResidual.cuh
new file mode 100644
index 0000000..2206e9a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/VectorResidual.cuh
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+#include <cuda_fp16.h>
+
+namespace faiss {
+namespace gpu {
+
+// Calculates residual v_i - c_j for all v_i in vecs where j = vecToCentroid[i]
+void runCalcResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& centroids,
+ Tensor<idx_t, 1, true>& vecToCentroid,
+ Tensor<float, 2, true>& residuals,
+ cudaStream_t stream);
+
+void runCalcResidual(
+ Tensor<float, 2, true>& vecs,
+ Tensor<half, 2, true>& centroids,
+ Tensor<idx_t, 1, true>& vecToCentroid,
+ Tensor<float, 2, true>& residuals,
+ cudaStream_t stream);
+
+// Gather vectors
+void runReconstruct(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream);
+
+void runReconstruct(
+ Tensor<idx_t, 1, true>& listIds,
+ Tensor<half, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream);
+
+void runReconstruct(
+ idx_t start,
+ idx_t num,
+ Tensor<float, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream);
+
+void runReconstruct(
+ idx_t start,
+ idx_t num,
+ Tensor<half, 2, true>& vecs,
+ Tensor<float, 2, true>& out,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh
new file mode 100644
index 0000000..75c228c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh
@@ -0,0 +1,259 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/impl/IVFInterleaved.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/DeviceVector.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename CODEC_TYPE,
+ typename METRIC_TYPE,
+ int THREADS,
+ int NUM_WARP_Q,
+ int NUM_THREAD_Q>
+void IVFINT_RUN(
+ CODEC_TYPE& codec,
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ const int k,
+ METRIC_TYPE metric,
+ const bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res);
+
+template <typename METRIC_TYPE, int THREADS, int NUM_WARP_Q, int NUM_THREAD_Q>
+void IVFINT_CODECS(
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ const int k,
+ METRIC_TYPE metric,
+ const bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ const auto dim = queries.getSize(1);
+
+ const auto call_ivfint_run = [&](const auto& func, auto& codec) {
+ func(codec,
+ queries,
+ listIds,
+ listData,
+ listIndices,
+ indicesOptions,
+ listLengths,
+ k,
+ metric,
+ useResidual,
+ residualBase,
+ scalarQ,
+ outDistances,
+ outIndices,
+ res);
+ };
+
+ if (!scalarQ) {
+ using CodecT = CodecFloat;
+ CodecT codec(dim * sizeof(float));
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } else {
+ switch (scalarQ->qtype) {
+ case ScalarQuantizer::QuantizerType::QT_8bit: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit, 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_uniform: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_uniform,
+ 1>;
+ CodecT codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_fp16: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_fp16, 1>;
+ CodecT codec(scalarQ->code_size);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_8bit_direct: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_direct,
+ 1>;
+ Codec<ScalarQuantizer::QuantizerType::QT_8bit_direct, 1> codec(
+ scalarQ->code_size);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_6bit: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_6bit, 1>;
+ Codec<ScalarQuantizer::QuantizerType::QT_6bit, 1> codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit, 1>;
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit, 1> codec(
+ scalarQ->code_size,
+ scalarQ->gpuTrained.data(),
+ scalarQ->gpuTrained.data() + dim);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ case ScalarQuantizer::QuantizerType::QT_4bit_uniform: {
+ using CodecT =
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit_uniform,
+ 1>;
+ Codec<ScalarQuantizer::QuantizerType::QT_4bit_uniform, 1> codec(
+ scalarQ->code_size,
+ scalarQ->trained[0],
+ scalarQ->trained[1]);
+ call_ivfint_run(
+ IVFINT_RUN<
+ CodecT,
+ METRIC_TYPE,
+ THREADS,
+ NUM_WARP_Q,
+ NUM_THREAD_Q>,
+ codec);
+ } break;
+ default:
+ FAISS_ASSERT(false);
+ }
+ }
+}
+
+template <int THREADS, int NUM_WARP_Q, int NUM_THREAD_Q>
+void ivfInterleavedScanImpl(
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ const int k,
+ faiss::MetricType metric_name,
+ const bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ FAISS_ASSERT(k <= NUM_WARP_Q);
+
+ const auto call_codec = [&](const auto& func, const auto& metric) {
+ func(queries,
+ listIds,
+ listData,
+ listIndices,
+ indicesOptions,
+ listLengths,
+ k,
+ metric,
+ useResidual,
+ residualBase,
+ scalarQ,
+ outDistances,
+ outIndices,
+ res);
+ };
+
+ if (metric_name == MetricType::METRIC_L2) {
+ L2Distance metric;
+ call_codec(
+ IVFINT_CODECS<L2Distance, THREADS, NUM_WARP_Q, NUM_THREAD_Q>,
+ metric);
+ } else if (metric_name == MetricType::METRIC_INNER_PRODUCT) {
+ IPDistance metric;
+ call_codec(
+ IVFINT_CODECS<IPDistance, THREADS, NUM_WARP_Q, NUM_THREAD_Q>,
+ metric);
+ } else {
+ FAISS_ASSERT(false);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu
new file mode 100644
index 0000000..1481f4d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/scan/IVFInterleavedImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <>
+void IVFINT_RUN<
+ SUB_CODEC_TYPE,
+ SUB_METRIC_TYPE,
+ SUB_THREADS,
+ SUB_NUM_WARP_Q,
+ SUB_NUM_THREAD_Q>(
+ SUB_CODEC_TYPE& codec,
+ Tensor<float, 2, true>& queries,
+ Tensor<idx_t, 2, true>& listIds,
+ DeviceVector<void*>& listData,
+ DeviceVector<void*>& listIndices,
+ IndicesOptions indicesOptions,
+ DeviceVector<idx_t>& listLengths,
+ const int k,
+ SUB_METRIC_TYPE metric,
+ const bool useResidual,
+ Tensor<float, 3, true>& residualBase,
+ GpuScalarQuantizer* scalarQ,
+ Tensor<float, 2, true>& outDistances,
+ Tensor<idx_t, 2, true>& outIndices,
+ GpuResources* res) {
+ const auto nq = queries.getSize(0);
+ const auto dim = queries.getSize(1);
+ const auto nprobe = listIds.getSize(1);
+
+ const auto stream = res->getDefaultStreamCurrentDevice();
+
+ DeviceTensor<float, 3, true> distanceTemp(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), listIds.getSize(1), k});
+ DeviceTensor<idx_t, 3, true> indicesTemp(
+ res,
+ makeTempAlloc(AllocType::Other, stream),
+ {queries.getSize(0), listIds.getSize(1), k});
+
+ const dim3 grid(nprobe, std::min(nq, (idx_t)getMaxGridCurrentDevice().y));
+
+ ivfInterleavedScan<
+ SUB_CODEC_TYPE,
+ SUB_METRIC_TYPE,
+ SUB_THREADS,
+ SUB_NUM_WARP_Q,
+ SUB_NUM_THREAD_Q>
+ <<<grid, SUB_THREADS, codec.getSmemSize(dim), stream>>>(
+ queries,
+ residualBase,
+ listIds,
+ listData.data(),
+ listLengths.data(),
+ codec,
+ metric,
+ k,
+ distanceTemp,
+ indicesTemp,
+ useResidual);
+
+ runIVFInterleavedScan2(
+ distanceTemp,
+ indicesTemp,
+ listIds,
+ k,
+ listIndices,
+ indicesOptions,
+ SUB_METRIC_TYPE::kDirection,
+ outDistances,
+ outIndices,
+ stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/IndexWrapper-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/IndexWrapper-inl.h
new file mode 100644
index 0000000..b43a5b3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/IndexWrapper-inl.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+namespace gpu {
+
+template <typename GpuIndex>
+IndexWrapper<GpuIndex>::IndexWrapper(
+ int numGpus,
+ std::function<std::unique_ptr<GpuIndex>(GpuResourcesProvider*, int)>
+ init) {
+ FAISS_ASSERT(numGpus <= faiss::gpu::getNumDevices());
+ for (int i = 0; i < numGpus; ++i) {
+ auto res = std::unique_ptr<faiss::gpu::StandardGpuResources>(
+ new StandardGpuResources);
+
+ subIndex.emplace_back(init(res.get(), i));
+ resources.emplace_back(std::move(res));
+ }
+
+ if (numGpus > 1) {
+ // create proxy
+ replicaIndex =
+ std::unique_ptr<faiss::IndexReplicas>(new faiss::IndexReplicas);
+
+ for (auto& index : subIndex) {
+ replicaIndex->addIndex(index.get());
+ }
+ }
+}
+
+template <typename GpuIndex>
+faiss::Index* IndexWrapper<GpuIndex>::getIndex() {
+ if ((bool)replicaIndex) {
+ return replicaIndex.get();
+ } else {
+ FAISS_ASSERT(!subIndex.empty());
+ return subIndex.front().get();
+ }
+}
+
+template <typename GpuIndex>
+void IndexWrapper<GpuIndex>::runOnIndices(std::function<void(GpuIndex*)> f) {
+ if ((bool)replicaIndex) {
+ replicaIndex->runOnIndex([f](int, faiss::Index* index) {
+ f(dynamic_cast<GpuIndex*>(index));
+ });
+ } else {
+ FAISS_ASSERT(!subIndex.empty());
+ f(subIndex.front().get());
+ }
+}
+
+template <typename GpuIndex>
+void IndexWrapper<GpuIndex>::setNumProbes(size_t nprobe) {
+ runOnIndices([nprobe](GpuIndex* index) { index->nprobe = nprobe; });
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/IndexWrapper.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/IndexWrapper.h
new file mode 100644
index 0000000..bfc2cc9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/IndexWrapper.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IndexReplicas.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <functional>
+#include <memory>
+#include <vector>
+
+namespace faiss {
+namespace gpu {
+
+// If we want to run multi-GPU, create a proxy to wrap the indices.
+// If we don't want multi-GPU, don't involve the proxy, so it doesn't
+// affect the timings.
+template <typename GpuIndex>
+struct IndexWrapper {
+ std::vector<std::unique_ptr<faiss::gpu::StandardGpuResources>> resources;
+ std::vector<std::unique_ptr<GpuIndex>> subIndex;
+ std::unique_ptr<faiss::IndexReplicas> replicaIndex;
+
+ IndexWrapper(
+ int numGpus,
+ std::function<std::unique_ptr<GpuIndex>(GpuResourcesProvider*, int)>
+ init);
+ faiss::Index* getIndex();
+
+ void runOnIndices(std::function<void(GpuIndex*)> f);
+ void setNumProbes(size_t nprobe);
+};
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/perf/IndexWrapper-inl.h>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfBinaryFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfBinaryFlat.cu
new file mode 100644
index 0000000..7ac6a93
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfBinaryFlat.cu
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/gpu/GpuIndexBinaryFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <faiss/utils/random.h>
+#include <gflags/gflags.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <map>
+#include <memory>
+#include <vector>
+
+#include <cuda_profiler_api.h>
+
+DEFINE_int32(k, 3, "final number of closest results returned");
+DEFINE_int32(num, 128, "# of vecs");
+DEFINE_int32(dim, 128, "# of dimensions");
+DEFINE_int32(num_queries, 3, "number of query vectors");
+DEFINE_int64(seed, -1, "specify random seed");
+DEFINE_int64(pinned_mem, 0, "pinned memory allocation to use");
+DEFINE_bool(cpu, true, "run the CPU code for timing and comparison");
+DEFINE_bool(use_unified_mem, false, "use Pascal unified memory for the index");
+
+using namespace faiss::gpu;
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ cudaProfilerStop();
+
+ auto seed = FLAGS_seed != -1L ? FLAGS_seed : time(nullptr);
+ printf("using seed %ld\n", seed);
+
+ auto numQueries = FLAGS_num_queries;
+
+ auto index = std::unique_ptr<faiss::IndexBinaryFlat>(
+ new faiss::IndexBinaryFlat(FLAGS_dim));
+
+ HostTensor<unsigned char, 2, true> vecs({FLAGS_num, FLAGS_dim / 8});
+ faiss::byte_rand(vecs.data(), vecs.numElements(), seed);
+
+ index->add(FLAGS_num, vecs.data());
+
+ printf("Database: dim %d num vecs %d\n", FLAGS_dim, FLAGS_num);
+ printf("Hamming lookup: %d queries, total k %d\n", numQueries, FLAGS_k);
+
+ // Convert to GPU index
+ printf("Copying index to GPU...\n");
+
+ GpuIndexBinaryFlatConfig config;
+ config.memorySpace =
+ FLAGS_use_unified_mem ? MemorySpace::Unified : MemorySpace::Device;
+
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexBinaryFlat gpuIndex(&res, index.get(), config);
+ printf("copy done\n");
+
+ // Build query vectors
+ HostTensor<unsigned char, 2, true> cpuQuery({numQueries, FLAGS_dim / 8});
+ faiss::byte_rand(cpuQuery.data(), cpuQuery.numElements(), seed);
+
+ // Time faiss CPU
+ HostTensor<int, 2, true> cpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> cpuIndices({numQueries, FLAGS_k});
+
+ if (FLAGS_cpu) {
+ float cpuTime = 0.0f;
+
+ CpuTimer timer;
+ index->search(
+ numQueries,
+ cpuQuery.data(),
+ FLAGS_k,
+ cpuDistances.data(),
+ cpuIndices.data());
+
+ cpuTime = timer.elapsedMilliseconds();
+ printf("CPU time %.3f ms\n", cpuTime);
+ }
+
+ HostTensor<int, 2, true> gpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> gpuIndices({numQueries, FLAGS_k});
+
+ CUDA_VERIFY(cudaProfilerStart());
+ faiss::gpu::synchronizeAllDevices();
+
+ float gpuTime = 0.0f;
+
+ // Time GPU
+ {
+ CpuTimer timer;
+
+ gpuIndex.search(
+ cpuQuery.getSize(0),
+ cpuQuery.data(),
+ FLAGS_k,
+ gpuDistances.data(),
+ gpuIndices.data());
+
+ // There is a device -> host copy above, so no need to time
+ // additional synchronization with the GPU
+ gpuTime = timer.elapsedMilliseconds();
+ }
+
+ CUDA_VERIFY(cudaProfilerStop());
+ printf("GPU time %.3f ms\n", gpuTime);
+
+ CUDA_VERIFY(cudaDeviceSynchronize());
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfClustering.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfClustering.cpp
new file mode 100644
index 0000000..72bc738
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfClustering.cpp
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/Clustering.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/perf/IndexWrapper.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <faiss/utils/random.h>
+#include <gflags/gflags.h>
+#include <memory>
+#include <vector>
+
+#include <cuda_profiler_api.h>
+#include <faiss/impl/AuxIndexStructures.h>
+
+DEFINE_int32(num, 10000, "# of vecs");
+DEFINE_int32(k, 100, "# of clusters");
+DEFINE_int32(dim, 128, "# of dimensions");
+DEFINE_int32(niter, 10, "# of iterations");
+DEFINE_bool(L2_metric, true, "If true, use L2 metric. If false, use IP metric");
+DEFINE_bool(use_float16, false, "use float16 vectors and math");
+DEFINE_bool(transposed, false, "transposed vector storage");
+DEFINE_bool(verbose, false, "turn on clustering logging");
+DEFINE_int64(seed, -1, "specify random seed");
+DEFINE_int32(num_gpus, 1, "number of gpus to use");
+DEFINE_int64(
+ min_paging_size,
+ -1,
+ "minimum size to use CPU -> GPU paged copies");
+DEFINE_int64(pinned_mem, -1, "pinned memory allocation to use");
+DEFINE_int32(max_points, -1, "max points per centroid");
+DEFINE_double(timeout, 0, "timeout in seconds");
+
+using namespace faiss::gpu;
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ cudaProfilerStop();
+
+ auto seed = FLAGS_seed != -1 ? FLAGS_seed : time(nullptr);
+ printf("using seed %ld\n", seed);
+
+ std::vector<float> vecs((size_t)FLAGS_num * FLAGS_dim);
+ faiss::float_rand(vecs.data(), vecs.size(), seed);
+
+ printf("K-means metric %s dim %d centroids %d num train %d niter %d\n",
+ FLAGS_L2_metric ? "L2" : "IP",
+ FLAGS_dim,
+ FLAGS_k,
+ FLAGS_num,
+ FLAGS_niter);
+ printf("float16 math %s\n", FLAGS_use_float16 ? "enabled" : "disabled");
+ printf("transposed storage %s\n",
+ FLAGS_transposed ? "enabled" : "disabled");
+ printf("verbose %s\n", FLAGS_verbose ? "enabled" : "disabled");
+
+ auto initFn = [](faiss::gpu::GpuResourcesProvider* res,
+ int dev) -> std::unique_ptr<faiss::gpu::GpuIndexFlat> {
+ if (FLAGS_pinned_mem >= 0) {
+ ((faiss::gpu::StandardGpuResources*)res)
+ ->setPinnedMemory(FLAGS_pinned_mem);
+ }
+
+ GpuIndexFlatConfig config;
+ config.device = dev;
+ config.useFloat16 = FLAGS_use_float16;
+ config.storeTransposed = FLAGS_transposed;
+
+ auto p = std::unique_ptr<faiss::gpu::GpuIndexFlat>(
+ FLAGS_L2_metric
+ ? (faiss::gpu::GpuIndexFlat*)new faiss::gpu::
+ GpuIndexFlatL2(res, FLAGS_dim, config)
+ : (faiss::gpu::GpuIndexFlat*)new faiss::gpu::
+ GpuIndexFlatIP(res, FLAGS_dim, config));
+
+ if (FLAGS_min_paging_size >= 0) {
+ p->setMinPagingSize(FLAGS_min_paging_size);
+ }
+ return p;
+ };
+
+ IndexWrapper<faiss::gpu::GpuIndexFlat> gpuIndex(FLAGS_num_gpus, initFn);
+
+ CUDA_VERIFY(cudaProfilerStart());
+ faiss::gpu::synchronizeAllDevices();
+
+ float gpuTime = 0.0f;
+
+ faiss::ClusteringParameters cp;
+ cp.niter = FLAGS_niter;
+ cp.verbose = FLAGS_verbose;
+
+ if (FLAGS_max_points > 0) {
+ cp.max_points_per_centroid = FLAGS_max_points;
+ }
+
+ auto tc = new faiss::TimeoutCallback();
+ faiss::InterruptCallback::instance.reset(tc);
+
+ faiss::Clustering kmeans(FLAGS_dim, FLAGS_k, cp);
+
+ // Time k-means
+ {
+ tc->set_timeout(FLAGS_timeout);
+ CpuTimer timer;
+
+ kmeans.train(FLAGS_num, vecs.data(), *(gpuIndex.getIndex()));
+
+ // There is a device -> host copy above, so no need to time
+ // additional synchronization with the GPU
+ gpuTime = timer.elapsedMilliseconds();
+ }
+
+ CUDA_VERIFY(cudaProfilerStop());
+ printf("k-means time %.3f ms\n", gpuTime);
+
+ CUDA_VERIFY(cudaDeviceSynchronize());
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfFlat.cu
new file mode 100644
index 0000000..ee40aa7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfFlat.cu
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/perf/IndexWrapper.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <faiss/utils/random.h>
+#include <gflags/gflags.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <map>
+#include <memory>
+#include <vector>
+
+#include <cuda_profiler_api.h>
+
+DEFINE_bool(l2, true, "L2 or inner product");
+DEFINE_int32(k, 3, "final number of closest results returned");
+DEFINE_int32(num, 128, "# of vecs");
+DEFINE_int32(dim, 128, "# of dimensions");
+DEFINE_int32(num_queries, 3, "number of query vectors");
+DEFINE_bool(diff, true, "show exact distance + index output discrepancies");
+DEFINE_bool(use_float16, false, "use encodings in float16");
+DEFINE_bool(use_float16_math, false, "perform math in float16");
+DEFINE_bool(transposed, false, "store vectors transposed");
+DEFINE_int64(seed, -1, "specify random seed");
+DEFINE_int32(num_gpus, 1, "number of gpus to use");
+DEFINE_int64(pinned_mem, 0, "pinned memory allocation to use");
+DEFINE_bool(cpu, true, "run the CPU code for timing and comparison");
+DEFINE_bool(use_unified_mem, false, "use Pascal unified memory for the index");
+
+using namespace faiss::gpu;
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ cudaProfilerStop();
+
+ auto seed = FLAGS_seed != -1L ? FLAGS_seed : time(nullptr);
+ printf("using seed %ld\n", seed);
+
+ auto numQueries = FLAGS_num_queries;
+
+ auto index = std::unique_ptr<faiss::IndexFlat>(new faiss::IndexFlat(
+ FLAGS_dim,
+ FLAGS_l2 ? faiss::METRIC_L2 : faiss::METRIC_INNER_PRODUCT));
+
+ HostTensor<float, 2, true> vecs({FLAGS_num, FLAGS_dim});
+ faiss::float_rand(vecs.data(), vecs.numElements(), seed);
+
+ index->add(FLAGS_num, vecs.data());
+
+ printf("Database: dim %d num vecs %d\n", FLAGS_dim, FLAGS_num);
+ printf("%s lookup: %d queries, total k %d\n",
+ FLAGS_l2 ? "L2" : "IP",
+ numQueries,
+ FLAGS_k);
+ printf("float16 encoding %s\n", FLAGS_use_float16 ? "enabled" : "disabled");
+ printf("transposed storage %s\n",
+ FLAGS_transposed ? "enabled" : "disabled");
+
+ // Convert to GPU index
+ printf("Copying index to %d GPU(s)...\n", FLAGS_num_gpus);
+
+ auto initFn = [&index](faiss::gpu::GpuResourcesProvider* res, int dev)
+ -> std::unique_ptr<faiss::gpu::GpuIndexFlat> {
+ ((faiss::gpu::StandardGpuResources*)res)
+ ->setPinnedMemory(FLAGS_pinned_mem);
+
+ GpuIndexFlatConfig config;
+ config.device = dev;
+ config.useFloat16 = FLAGS_use_float16;
+ config.storeTransposed = FLAGS_transposed;
+ config.memorySpace = FLAGS_use_unified_mem ? MemorySpace::Unified
+ : MemorySpace::Device;
+
+ auto p = std::unique_ptr<faiss::gpu::GpuIndexFlat>(
+ new faiss::gpu::GpuIndexFlat(res, index.get(), config));
+ return p;
+ };
+
+ IndexWrapper<faiss::gpu::GpuIndexFlat> gpuIndex(FLAGS_num_gpus, initFn);
+ printf("copy done\n");
+
+ // Build query vectors
+ HostTensor<float, 2, true> cpuQuery({numQueries, FLAGS_dim});
+ faiss::float_rand(cpuQuery.data(), cpuQuery.numElements(), seed);
+
+ // Time faiss CPU
+ HostTensor<float, 2, true> cpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> cpuIndices({numQueries, FLAGS_k});
+
+ if (FLAGS_cpu) {
+ float cpuTime = 0.0f;
+
+ CpuTimer timer;
+ index->search(
+ numQueries,
+ cpuQuery.data(),
+ FLAGS_k,
+ cpuDistances.data(),
+ cpuIndices.data());
+
+ cpuTime = timer.elapsedMilliseconds();
+ printf("CPU time %.3f ms\n", cpuTime);
+ }
+
+ HostTensor<float, 2, true> gpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> gpuIndices({numQueries, FLAGS_k});
+
+ CUDA_VERIFY(cudaProfilerStart());
+ faiss::gpu::synchronizeAllDevices();
+
+ float gpuTime = 0.0f;
+
+ // Time GPU
+ {
+ CpuTimer timer;
+
+ gpuIndex.getIndex()->search(
+ cpuQuery.getSize(0),
+ cpuQuery.data(),
+ FLAGS_k,
+ gpuDistances.data(),
+ gpuIndices.data());
+
+ // There is a device -> host copy above, so no need to time
+ // additional synchronization with the GPU
+ gpuTime = timer.elapsedMilliseconds();
+ }
+
+ CUDA_VERIFY(cudaProfilerStop());
+ printf("GPU time %.3f ms\n", gpuTime);
+
+ if (FLAGS_cpu) {
+ compareLists(
+ cpuDistances.data(),
+ cpuIndices.data(),
+ gpuDistances.data(),
+ gpuIndices.data(),
+ numQueries,
+ FLAGS_k,
+ "",
+ true,
+ FLAGS_diff,
+ false);
+ }
+
+ CUDA_VERIFY(cudaDeviceSynchronize());
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFFlat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFFlat.cu
new file mode 100644
index 0000000..b73fed3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFFlat.cu
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/index_io.h>
+#include <faiss/utils/random.h>
+
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/perf/IndexWrapper.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <gflags/gflags.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <map>
+#include <memory>
+#include <vector>
+
+#include <cuda_profiler_api.h>
+
+DEFINE_int32(nprobe, 5, "number of coarse centroids to probe");
+DEFINE_int32(k, 3, "final number of closest results returned");
+DEFINE_int32(num_queries, 3, "number of query vectors");
+DEFINE_string(in, "/home/jhj/local/index.out", "index file for input");
+DEFINE_bool(diff, true, "show exact distance + index output discrepancies");
+DEFINE_bool(use_float16_coarse, false, "coarse quantizer in float16");
+DEFINE_int64(seed, -1, "specify random seed");
+DEFINE_int32(num_gpus, 1, "number of gpus to use");
+DEFINE_int32(index, 2, "0 = no indices on GPU; 1 = 32 bit, 2 = 64 bit on GPU");
+
+using namespace faiss::gpu;
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ cudaProfilerStop();
+
+ auto seed = FLAGS_seed != -1L ? FLAGS_seed : time(nullptr);
+ printf("using seed %ld\n", seed);
+
+ auto numQueries = FLAGS_num_queries;
+
+ auto index = std::unique_ptr<faiss::IndexIVFFlat>(
+ dynamic_cast<faiss::IndexIVFFlat*>(
+ faiss::read_index(FLAGS_in.c_str())));
+ FAISS_ASSERT((bool)index);
+ index->nprobe = FLAGS_nprobe;
+
+ auto dim = index->d;
+
+ printf("Database: dim %d num vecs %ld\n", dim, index->ntotal);
+ printf("Coarse centroids: %ld\n", index->quantizer->ntotal);
+ printf("L2 lookup: %d queries, nprobe %d, total k %d\n",
+ numQueries,
+ FLAGS_nprobe,
+ FLAGS_k);
+ printf("float16 coarse quantizer %s\n",
+ FLAGS_use_float16_coarse ? "enabled" : "disabled");
+
+ // Convert to GPU index
+ printf("Copying index to %d GPU(s)...\n", FLAGS_num_gpus);
+
+ auto initFn = [&index](faiss::gpu::GpuResourcesProvider* res, int dev)
+ -> std::unique_ptr<faiss::gpu::GpuIndexIVFFlat> {
+ GpuIndexIVFFlatConfig config;
+ config.device = dev;
+ config.indicesOptions = (faiss::gpu::IndicesOptions)FLAGS_index;
+ config.flatConfig.useFloat16 = FLAGS_use_float16_coarse;
+
+ auto p = std::unique_ptr<faiss::gpu::GpuIndexIVFFlat>(
+ new faiss::gpu::GpuIndexIVFFlat(
+ res,
+ index->d,
+ index->nlist,
+ index->metric_type,
+ config));
+ p->copyFrom(index.get());
+ return p;
+ };
+
+ IndexWrapper<faiss::gpu::GpuIndexIVFFlat> gpuIndex(FLAGS_num_gpus, initFn);
+ gpuIndex.setNumProbes(FLAGS_nprobe);
+ printf("copy done\n");
+
+ // Build query vectors
+ HostTensor<float, 2, true> cpuQuery({numQueries, dim});
+ faiss::float_rand(cpuQuery.data(), cpuQuery.numElements(), seed);
+
+ // Time faiss CPU
+ HostTensor<float, 2, true> cpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> cpuIndices({numQueries, FLAGS_k});
+
+ float cpuTime = 0.0f;
+
+ {
+ CpuTimer timer;
+ index->search(
+ numQueries,
+ cpuQuery.data(),
+ FLAGS_k,
+ cpuDistances.data(),
+ cpuIndices.data());
+
+ cpuTime = timer.elapsedMilliseconds();
+ }
+
+ printf("CPU time %.3f ms\n", cpuTime);
+
+ HostTensor<float, 2, true> gpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> gpuIndices({numQueries, FLAGS_k});
+
+ CUDA_VERIFY(cudaProfilerStart());
+ faiss::gpu::synchronizeAllDevices();
+
+ float gpuTime = 0.0f;
+
+ // Time GPU
+ {
+ CpuTimer timer;
+
+ gpuIndex.getIndex()->search(
+ cpuQuery.getSize(0),
+ cpuQuery.data(),
+ FLAGS_k,
+ gpuDistances.data(),
+ gpuIndices.data());
+
+ // There is a device -> host copy above, so no need to time
+ // additional synchronization with the GPU
+ gpuTime = timer.elapsedMilliseconds();
+ }
+
+ CUDA_VERIFY(cudaProfilerStop());
+ printf("GPU time %.3f ms\n", gpuTime);
+
+ compareLists(
+ cpuDistances.data(),
+ cpuIndices.data(),
+ gpuDistances.data(),
+ gpuIndices.data(),
+ numQueries,
+ FLAGS_k,
+ "",
+ true,
+ FLAGS_diff,
+ false);
+
+ CUDA_VERIFY(cudaDeviceSynchronize());
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFPQ.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFPQ.cu
new file mode 100644
index 0000000..7404ee2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFPQ.cu
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/index_io.h>
+#include <faiss/utils/random.h>
+
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/perf/IndexWrapper.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+
+#include <cuda_profiler_api.h>
+#include <gflags/gflags.h>
+#include <map>
+#include <memory>
+#include <vector>
+
+DEFINE_int32(nprobe, 5, "number of coarse centroids to probe");
+DEFINE_int32(k, 3, "final number of closest results returned");
+DEFINE_int32(num_queries, 3, "number of query vectors");
+DEFINE_string(in, "/home/jhj/local/index.out", "index file for input");
+DEFINE_bool(diff, true, "show exact distance + index output discrepancies");
+DEFINE_bool(use_precomputed, true, "enable or disable precomputed codes");
+DEFINE_bool(float16_lookup, false, "use float16 residual distance tables");
+DEFINE_int64(seed, -1, "specify random seed");
+DEFINE_int32(num_gpus, 1, "number of gpus to use");
+DEFINE_int32(index, 2, "0 = no indices on GPU; 1 = 32 bit, 2 = 64 bit on GPU");
+
+using namespace faiss::gpu;
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ CUDA_VERIFY(cudaProfilerStop());
+
+ auto seed = FLAGS_seed != -1L ? FLAGS_seed : time(nullptr);
+ printf("using seed %ld\n", seed);
+
+ auto numQueries = FLAGS_num_queries;
+
+ auto index =
+ std::unique_ptr<faiss::IndexIVFPQ>(dynamic_cast<faiss::IndexIVFPQ*>(
+ faiss::read_index(FLAGS_in.c_str())));
+ FAISS_ASSERT((bool)index);
+ index->nprobe = FLAGS_nprobe;
+
+ if (!FLAGS_use_precomputed) {
+ index->use_precomputed_table = 0;
+ }
+
+ auto dim = index->d;
+ auto codes = index->pq.M;
+ auto bitsPerCode = index->pq.nbits;
+
+ printf("Database: dim %d num vecs %ld\n", dim, index->ntotal);
+ printf("Coarse centroids: %ld\n", index->quantizer->ntotal);
+ printf("PQ centroids: codes %ld bits per code %ld\n", codes, bitsPerCode);
+ printf("L2 lookup: %d queries, nprobe %d, total k %d, "
+ "precomputed codes %d\n\n",
+ numQueries,
+ FLAGS_nprobe,
+ FLAGS_k,
+ FLAGS_use_precomputed);
+
+ // Convert to GPU index
+ printf("Copying index to %d GPU(s)...\n", FLAGS_num_gpus);
+
+ auto precomp = FLAGS_use_precomputed;
+ auto indicesOpt = (faiss::gpu::IndicesOptions)FLAGS_index;
+ auto useFloat16Lookup = FLAGS_float16_lookup;
+
+ auto initFn =
+ [precomp, indicesOpt, useFloat16Lookup, &index](
+ faiss::gpu::GpuResourcesProvider* res,
+ int dev) -> std::unique_ptr<faiss::gpu::GpuIndexIVFPQ> {
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = dev;
+ config.usePrecomputedTables = precomp;
+ config.indicesOptions = indicesOpt;
+ config.useFloat16LookupTables = useFloat16Lookup;
+
+ auto p = std::unique_ptr<faiss::gpu::GpuIndexIVFPQ>(
+ new faiss::gpu::GpuIndexIVFPQ(res, index.get(), config));
+
+ return p;
+ };
+
+ IndexWrapper<faiss::gpu::GpuIndexIVFPQ> gpuIndex(FLAGS_num_gpus, initFn);
+ gpuIndex.setNumProbes(FLAGS_nprobe);
+ printf("copy done\n");
+
+ // Build query vectors
+ HostTensor<float, 2, true> cpuQuery({numQueries, dim});
+ faiss::float_rand(cpuQuery.data(), cpuQuery.numElements(), seed);
+
+ // Time faiss CPU
+ HostTensor<float, 2, true> cpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> cpuIndices({numQueries, FLAGS_k});
+
+ float cpuTime = 0.0f;
+
+ {
+ CpuTimer timer;
+ index->search(
+ numQueries,
+ cpuQuery.data(),
+ FLAGS_k,
+ cpuDistances.data(),
+ cpuIndices.data());
+
+ cpuTime = timer.elapsedMilliseconds();
+ }
+
+ printf("CPU time %.3f ms\n", cpuTime);
+
+ HostTensor<float, 2, true> gpuDistances({numQueries, FLAGS_k});
+ HostTensor<faiss::idx_t, 2, true> gpuIndices({numQueries, FLAGS_k});
+
+ CUDA_VERIFY(cudaProfilerStart());
+ faiss::gpu::synchronizeAllDevices();
+
+ float gpuTime = 0.0f;
+
+ // Time GPU
+ {
+ CpuTimer timer;
+
+ gpuIndex.getIndex()->search(
+ cpuQuery.getSize(0),
+ cpuQuery.data(),
+ FLAGS_k,
+ gpuDistances.data(),
+ gpuIndices.data());
+
+ // There is a device -> host copy above, so no need to time
+ // additional synchronization with the GPU
+ gpuTime = timer.elapsedMilliseconds();
+ }
+
+ CUDA_VERIFY(cudaProfilerStop());
+ printf("GPU time %.3f ms\n", gpuTime);
+
+ compareLists(
+ cpuDistances.data(),
+ cpuIndices.data(),
+ gpuDistances.data(),
+ gpuIndices.data(),
+ numQueries,
+ FLAGS_k,
+ "",
+ true,
+ FLAGS_diff,
+ false);
+
+ CUDA_VERIFY(cudaDeviceSynchronize());
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFPQAdd.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFPQAdd.cpp
new file mode 100644
index 0000000..08aaf01
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfIVFPQAdd.cpp
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cuda_profiler_api.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <gflags/gflags.h>
+#include <vector>
+
+DEFINE_int32(batches, 10, "number of batches of vectors to add");
+DEFINE_int32(batch_size, 10000, "number of vectors in each batch");
+DEFINE_int32(dim, 256, "dimension of vectors");
+DEFINE_int32(centroids, 4096, "num coarse centroids to use");
+DEFINE_int32(bytes_per_vec, 32, "bytes per encoded vector");
+DEFINE_int32(bits_per_code, 8, "bits per PQ code");
+DEFINE_int32(index, 2, "0 = no indices on GPU; 1 = 32 bit, 2 = 64 bit on GPU");
+DEFINE_bool(time_gpu, true, "time add to GPU");
+DEFINE_bool(time_cpu, false, "time add to CPU");
+DEFINE_bool(per_batch_time, false, "print per-batch times");
+DEFINE_bool(reserve_memory, false, "whether or not to pre-reserve memory");
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ cudaProfilerStop();
+
+ int dim = FLAGS_dim;
+ int numCentroids = FLAGS_centroids;
+ int bytesPerVec = FLAGS_bytes_per_vec;
+ int bitsPerCode = FLAGS_bits_per_code;
+
+ faiss::gpu::StandardGpuResources res;
+
+ // IndexIVFPQ will complain, but just give us enough to get through this
+ int numTrain = 4 * numCentroids;
+ std::vector<float> trainVecs = faiss::gpu::randVecs(numTrain, dim);
+
+ faiss::IndexFlatL2 coarseQuantizer(dim);
+ faiss::IndexIVFPQ cpuIndex(
+ &coarseQuantizer, dim, numCentroids, bytesPerVec, bitsPerCode);
+ if (FLAGS_time_cpu) {
+ cpuIndex.train(numTrain, trainVecs.data());
+ }
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = 0;
+ config.indicesOptions = (faiss::gpu::IndicesOptions)FLAGS_index;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(
+ &res,
+ dim,
+ numCentroids,
+ bytesPerVec,
+ bitsPerCode,
+ faiss::METRIC_L2,
+ config);
+
+ if (FLAGS_time_gpu) {
+ gpuIndex.train(numTrain, trainVecs.data());
+ if (FLAGS_reserve_memory) {
+ size_t numVecs = (size_t)FLAGS_batches * (size_t)FLAGS_batch_size;
+ gpuIndex.reserveMemory(numVecs);
+ }
+ }
+
+ cudaDeviceSynchronize();
+ CUDA_VERIFY(cudaProfilerStart());
+
+ float totalGpuTime = 0.0f;
+ float totalCpuTime = 0.0f;
+
+ for (int i = 0; i < FLAGS_batches; ++i) {
+ if (!FLAGS_per_batch_time) {
+ if (i % 10 == 0) {
+ printf("Adding batch %d\n", i + 1);
+ }
+ }
+
+ auto addVecs = faiss::gpu::randVecs(FLAGS_batch_size, dim);
+
+ if (FLAGS_time_gpu) {
+ faiss::gpu::CpuTimer timer;
+ gpuIndex.add(FLAGS_batch_size, addVecs.data());
+ CUDA_VERIFY(cudaDeviceSynchronize());
+ auto time = timer.elapsedMilliseconds();
+
+ totalGpuTime += time;
+
+ if (FLAGS_per_batch_time) {
+ printf("Batch %d | GPU time to add %d vecs: %.3f ms (%.5f ms per)\n",
+ i + 1,
+ FLAGS_batch_size,
+ time,
+ time / (float)FLAGS_batch_size);
+ }
+ }
+
+ if (FLAGS_time_cpu) {
+ faiss::gpu::CpuTimer timer;
+ cpuIndex.add(FLAGS_batch_size, addVecs.data());
+ auto time = timer.elapsedMilliseconds();
+
+ totalCpuTime += time;
+
+ if (FLAGS_per_batch_time) {
+ printf("Batch %d | CPU time to add %d vecs: %.3f ms (%.5f ms per)\n",
+ i + 1,
+ FLAGS_batch_size,
+ time,
+ time / (float)FLAGS_batch_size);
+ }
+ }
+ }
+
+ CUDA_VERIFY(cudaProfilerStop());
+
+ int total = FLAGS_batch_size * FLAGS_batches;
+
+ if (FLAGS_time_gpu) {
+ printf("%d dim, %d centroids, %d x %d encoding\n"
+ "GPU time to add %d vectors (%d batches, %d per batch): "
+ "%.3f ms (%.3f us per)\n",
+ dim,
+ numCentroids,
+ bytesPerVec,
+ bitsPerCode,
+ total,
+ FLAGS_batches,
+ FLAGS_batch_size,
+ totalGpuTime,
+ totalGpuTime * 1000.0f / (float)total);
+ }
+
+ if (FLAGS_time_cpu) {
+ printf("%d dim, %d centroids, %d x %d encoding\n"
+ "CPU time to add %d vectors (%d batches, %d per batch): "
+ "%.3f ms (%.3f us per)\n",
+ dim,
+ numCentroids,
+ bytesPerVec,
+ bitsPerCode,
+ total,
+ FLAGS_batches,
+ FLAGS_batch_size,
+ totalCpuTime,
+ totalCpuTime * 1000.0f / (float)total);
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfSelect.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfSelect.cu
new file mode 100644
index 0000000..64c9a01
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/PerfSelect.cu
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gflags/gflags.h>
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <faiss/gpu/utils/BlockSelectKernel.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/WarpSelectKernel.cuh>
+#include <sstream>
+#include <unordered_map>
+#include <vector>
+
+DEFINE_int32(rows, 10000, "rows in matrix");
+DEFINE_int32(cols, 40000, "cols in matrix");
+DEFINE_int32(k, 100, "k");
+DEFINE_bool(dir, false, "direction of sort");
+DEFINE_bool(warp, false, "warp select");
+DEFINE_int32(iter, 5, "iterations to run");
+DEFINE_bool(k_powers, false, "test k powers of 2 from 1 -> max k");
+
+int main(int argc, char** argv) {
+ using namespace faiss::gpu;
+
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ std::vector<float> v = randVecs(FLAGS_rows, FLAGS_cols);
+ HostTensor<float, 2, true> hostVal({FLAGS_rows, FLAGS_cols});
+
+ for (int r = 0; r < FLAGS_rows; ++r) {
+ for (int c = 0; c < FLAGS_cols; ++c) {
+ hostVal[r][c] = v[r * FLAGS_cols + c];
+ }
+ }
+
+ StandardGpuResources res;
+ res.noTempMemory();
+
+ auto resUse = res.getResources();
+
+ // Select top-k on GPU
+ DeviceTensor<float, 2, true> gpuVal(
+ resUse.get(), makeDevAlloc(AllocType::Other, 0), hostVal);
+
+ int startK = FLAGS_k;
+ int limitK = FLAGS_k;
+
+ if (FLAGS_k_powers) {
+ startK = 1;
+ limitK = GPU_MAX_SELECTION_K;
+ }
+
+ for (int k = startK; k <= limitK; k *= 2) {
+ DeviceTensor<float, 2, true> gpuOutVal(
+ resUse.get(),
+ makeDevAlloc(AllocType::Other, 0),
+ {FLAGS_rows, k});
+ DeviceTensor<faiss::idx_t, 2, true> gpuOutInd(
+ resUse.get(),
+ makeDevAlloc(AllocType::Other, 0),
+ {FLAGS_rows, k});
+
+ for (int i = 0; i < FLAGS_iter; ++i) {
+ if (FLAGS_warp) {
+ runWarpSelect(gpuVal, gpuOutVal, gpuOutInd, FLAGS_dir, k, 0);
+ } else {
+ runBlockSelect(gpuVal, gpuOutVal, gpuOutInd, FLAGS_dir, k, 0);
+ }
+ }
+ }
+
+ cudaDeviceSynchronize();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/WriteIndex.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/WriteIndex.cpp
new file mode 100644
index 0000000..c5912c6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/WriteIndex.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/index_io.h>
+#include <gflags/gflags.h>
+#include <vector>
+
+// For IVFPQ:
+DEFINE_bool(ivfpq, false, "use IVFPQ encoding");
+DEFINE_int32(codes, 4, "number of PQ codes per vector");
+DEFINE_int32(bits_per_code, 8, "number of bits per PQ code");
+
+// For IVFFlat:
+DEFINE_bool(l2, true, "use L2 metric (versus IP metric)");
+DEFINE_bool(ivfflat, false, "use IVF flat encoding");
+
+// For both:
+DEFINE_string(out, "/home/jhj/local/index.out", "index file for output");
+DEFINE_int32(dim, 128, "vector dimension");
+DEFINE_int32(num_coarse, 100, "number of coarse centroids");
+DEFINE_int32(num, 100000, "total database size");
+DEFINE_int32(num_train, -1, "number of database vecs to train on");
+
+template <typename T>
+void fillAndSave(T& index, int numTrain, int num, int dim) {
+ auto trainVecs = faiss::gpu::randVecs(numTrain, dim);
+ index.train(numTrain, trainVecs.data());
+
+ constexpr int kAddChunk = 1000000;
+
+ for (int i = 0; i < num; i += kAddChunk) {
+ int numRemaining = (num - i) < kAddChunk ? (num - i) : kAddChunk;
+ auto vecs = faiss::gpu::randVecs(numRemaining, dim);
+
+ printf("adding at %d: %d\n", i, numRemaining);
+ index.add(numRemaining, vecs.data());
+ }
+
+ faiss::write_index(&index, FLAGS_out.c_str());
+}
+
+int main(int argc, char** argv) {
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+
+ // Either ivfpq or ivfflat must be set
+ if ((FLAGS_ivfpq && FLAGS_ivfflat) || (!FLAGS_ivfpq && !FLAGS_ivfflat)) {
+ printf("must specify either ivfpq or ivfflat\n");
+ return 1;
+ }
+
+ auto dim = FLAGS_dim;
+ auto numCentroids = FLAGS_num_coarse;
+ auto num = FLAGS_num;
+ auto numTrain = FLAGS_num_train;
+ numTrain = numTrain == -1 ? std::max((num / 4), 1) : numTrain;
+ numTrain = std::min(num, numTrain);
+
+ if (FLAGS_ivfpq) {
+ faiss::IndexFlatL2 quantizer(dim);
+ faiss::IndexIVFPQ index(
+ &quantizer,
+ dim,
+ numCentroids,
+ FLAGS_codes,
+ FLAGS_bits_per_code);
+ index.verbose = true;
+
+ printf("IVFPQ: codes %d bits per code %d\n",
+ FLAGS_codes,
+ FLAGS_bits_per_code);
+ printf("Lists: %d\n", numCentroids);
+ printf("Database: dim %d num vecs %d trained on %d\n",
+ dim,
+ num,
+ numTrain);
+ printf("output file: %s\n", FLAGS_out.c_str());
+
+ fillAndSave(index, numTrain, num, dim);
+ } else if (FLAGS_ivfflat) {
+ faiss::IndexFlatL2 quantizerL2(dim);
+ faiss::IndexFlatIP quantizerIP(dim);
+
+ faiss::IndexFlat* quantizer = FLAGS_l2
+ ? (faiss::IndexFlat*)&quantizerL2
+ : (faiss::IndexFlat*)&quantizerIP;
+
+ faiss::IndexIVFFlat index(
+ quantizer,
+ dim,
+ numCentroids,
+ FLAGS_l2 ? faiss::METRIC_L2 : faiss::METRIC_INNER_PRODUCT);
+
+ printf("IVFFlat: metric %s\n", FLAGS_l2 ? "L2" : "IP");
+ printf("Lists: %d\n", numCentroids);
+ printf("Database: dim %d num vecs %d trained on %d\n",
+ dim,
+ num,
+ numTrain);
+ printf("output file: %s\n", FLAGS_out.c_str());
+
+ fillAndSave(index, numTrain, num, dim);
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/slow.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/slow.py
new file mode 100755
index 0000000..5369dc0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/perf/slow.py
@@ -0,0 +1,24 @@
+#! /usr/bin/env python3
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# this is a slow computation to test whether ctrl-C handling works
+import faiss
+import numpy as np
+
+def test_slow():
+ d = 256
+ index = faiss.index_cpu_to_gpu(faiss.StandardGpuResources(),
+ 0, faiss.IndexFlatL2(d))
+ x = np.random.rand(10 ** 6, d).astype('float32')
+ print('add')
+ index.add(x)
+ print('search')
+ index.search(x, 10)
+ print('done')
+
+
+if __name__ == '__main__':
+ test_slow()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/CMakeLists.txt
new file mode 100644
index 0000000..c549af3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/CMakeLists.txt
@@ -0,0 +1,64 @@
+# @lint-ignore-every LICENSELINT
+# Copyright (c) Meta Platforms, Inc. and its affiliates.
+# All rights reserved.
+#
+# This source code is licensed under the BSD-style license found in the
+# LICENSE file in the root directory of this source tree.
+# =============================================================================
+# Copyright (c) 2023, NVIDIA CORPORATION.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+# in compliance with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software distributed under the License
+# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+# or implied. See the License for the specific language governing permissions and limitations under
+# the License.
+# =============================================================================
+
+# Defines `gtest_discover_tests()`.
+include(GoogleTest)
+add_library(faiss_gpu_test_helper TestUtils.cpp)
+if(FAISS_ENABLE_ROCM)
+ target_link_libraries(faiss_gpu_test_helper PUBLIC faiss gtest hip::host)
+else()
+ find_package(CUDAToolkit REQUIRED)
+ target_link_libraries(faiss_gpu_test_helper PUBLIC faiss gtest CUDA::cudart $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs> $<$<BOOL:${FAISS_ENABLE_CUVS}>:OpenMP::OpenMP_CXX>)
+endif()
+
+macro(faiss_gpu_test file)
+ get_filename_component(test_name ${file} NAME_WE)
+ add_executable(${test_name} ${file})
+ target_link_libraries(${test_name} PRIVATE faiss_gpu_test_helper)
+ target_compile_options(${test_name} PRIVATE
+ $<$<COMPILE_LANGUAGE:CUDA>:$<$<BOOL:${FAISS_ENABLE_CUVS}>:-Xcompiler=${OpenMP_CXX_FLAGS}>>)
+ gtest_discover_tests(${test_name})
+endmacro()
+
+
+faiss_gpu_test(TestCodePacking.cpp)
+faiss_gpu_test(TestGpuIndexFlat.cpp)
+faiss_gpu_test(TestGpuIndexIVFFlat.cpp)
+faiss_gpu_test(TestGpuIndexBinaryFlat.cpp)
+faiss_gpu_test(TestGpuMemoryException.cpp)
+faiss_gpu_test(TestGpuIndexIVFPQ.cpp)
+faiss_gpu_test(TestGpuIndexIVFScalarQuantizer.cpp)
+faiss_gpu_test(TestGpuResidualQuantizer.cpp)
+faiss_gpu_test(TestGpuDistance.${GPU_EXT_PREFIX})
+faiss_gpu_test(TestGpuSelect.${GPU_EXT_PREFIX})
+if(FAISS_ENABLE_CUVS)
+ faiss_gpu_test(TestGpuIndexCagra.cu)
+endif()
+
+add_executable(demo_ivfpq_indexing_gpu EXCLUDE_FROM_ALL
+ demo_ivfpq_indexing_gpu.cpp)
+
+if (FAISS_ENABLE_ROCM)
+ target_link_libraries(demo_ivfpq_indexing_gpu
+ PRIVATE faiss gtest_main hip::host)
+else()
+ target_link_libraries(demo_ivfpq_indexing_gpu
+ PRIVATE faiss gtest_main CUDA::cudart)
+endif()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestCodePacking.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestCodePacking.cpp
new file mode 100644
index 0000000..4b08b62
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestCodePacking.cpp
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/impl/InterleavedCodes.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <gtest/gtest.h>
+#include <cmath>
+#include <random>
+#include <sstream>
+#include <vector>
+
+TEST(TestCodePacking, NonInterleavedCodes_UnpackPack) {
+ using namespace faiss::gpu;
+
+ // We are fine using non-fixed seeds here, the results should be fully
+ // deterministic
+ auto seed = std::random_device()();
+ std::mt19937 gen(seed);
+ std::uniform_int_distribution<uint8_t> dist;
+
+ std::cout << "seed " << seed << "\n";
+
+ for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) {
+ for (auto dims : {1, 7, 8, 31, 32}) {
+ for (auto numVecs : {1, 3, 4, 5, 6, 8, 31, 32, 33, 65}) {
+ std::cout << bitsPerCode << " " << dims << " " << numVecs
+ << "\n";
+
+ int srcVecSize = utils::divUp(dims * bitsPerCode, 8);
+ std::vector<uint8_t> data(numVecs * srcVecSize);
+
+ for (auto& v : data) {
+ v = dist(gen);
+ }
+
+ // currently unimplemented
+ EXPECT_FALSE(bitsPerCode > 8 && bitsPerCode % 8 != 0);
+
+ // Due to bit packing, mask out bits that should be zero based
+ // on dimensions we shouldn't have present
+ int vectorSizeBits = dims * bitsPerCode;
+ int vectorSizeBytes = utils::divUp(vectorSizeBits, 8);
+ int remainder = vectorSizeBits % 8;
+
+ if (remainder > 0) {
+ uint8_t mask = 0xff >> (8 - remainder);
+
+ for (int i = 0; i < numVecs; ++i) {
+ int lastVecByte = (i + 1) * vectorSizeBytes - 1;
+ data[lastVecByte] &= mask;
+ }
+ }
+
+ auto up =
+ unpackNonInterleaved(data, numVecs, dims, bitsPerCode);
+ auto p = packNonInterleaved(up, numVecs, dims, bitsPerCode);
+
+ EXPECT_EQ(data, p);
+ }
+ }
+ }
+}
+
+TEST(TestCodePacking, NonInterleavedCodes_PackUnpack) {
+ using namespace faiss::gpu;
+
+ // We are fine using non-fixed seeds here, the results should be fully
+ // deterministic
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<uint8_t> dist;
+
+ for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) {
+ for (auto dims : {1, 7, 8, 31, 32}) {
+ for (auto numVecs : {1, 3, 4, 5, 6, 8, 31, 32, 33, 65}) {
+ std::cout << bitsPerCode << " " << dims << " " << numVecs
+ << "\n";
+
+ std::vector<uint8_t> data(
+ numVecs * dims * utils::divUp(bitsPerCode, 8));
+
+ // currently unimplemented
+ EXPECT_FALSE(bitsPerCode > 8 && bitsPerCode % 8 != 0);
+
+ // Mask out high bits we shouldn't have based on code size
+ uint8_t mask =
+ bitsPerCode < 8 ? (0xff >> (8 - bitsPerCode)) : 0xff;
+
+ for (auto& v : data) {
+ v = dist(gen) & mask;
+ }
+
+ auto p = packNonInterleaved(data, numVecs, dims, bitsPerCode);
+ auto up = unpackNonInterleaved(p, numVecs, dims, bitsPerCode);
+
+ EXPECT_EQ(data, up);
+ }
+ }
+ }
+}
+
+TEST(TestCodePacking, InterleavedCodes_UnpackPack) {
+ using namespace faiss::gpu;
+
+ // We are fine using non-fixed seeds here, the results should be fully
+ // deterministic
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<uint8_t> dist;
+
+ for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) {
+ for (auto dims : {1, 7, 8, 31, 32}) {
+ for (auto numVecs : {1, 3, 4, 5, 6, 8, 31, 32, 33, 65}) {
+ std::cout << bitsPerCode << " " << dims << " " << numVecs
+ << "\n";
+
+ int warpSize = getWarpSizeCurrentDevice();
+ int blocks = utils::divUp(numVecs, warpSize);
+ int bytesPerDimBlock = warpSize * bitsPerCode / 8;
+ int bytesPerBlock = bytesPerDimBlock * dims;
+ int size = blocks * bytesPerBlock;
+
+ std::vector<uint8_t> data(size);
+
+ if (bitsPerCode == 8 || bitsPerCode == 16 ||
+ bitsPerCode == 32) {
+ int bytesPerCode = bitsPerCode / 8;
+
+ for (int i = 0; i < blocks; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ for (int k = 0; k < warpSize; ++k) {
+ for (int l = 0; l < bytesPerCode; ++l) {
+ int vec = i * warpSize + k;
+ if (vec < numVecs) {
+ data[i * bytesPerBlock +
+ j * bytesPerDimBlock +
+ k * bytesPerCode + l] = dist(gen);
+ }
+ }
+ }
+ }
+ }
+ } else if (bitsPerCode < 8) {
+ for (int i = 0; i < blocks; ++i) {
+ for (int j = 0; j < dims; ++j) {
+ for (int k = 0; k < bytesPerDimBlock; ++k) {
+ int loVec =
+ i * warpSize + (k * 8) / bitsPerCode;
+ int hiVec = loVec + 1;
+ int hiVec2 = hiVec + 1;
+
+ uint8_t lo = loVec < numVecs ? dist(gen) &
+ (0xff >> (8 - bitsPerCode))
+ : 0;
+ uint8_t hi = hiVec < numVecs ? dist(gen) &
+ (0xff >> (8 - bitsPerCode))
+ : 0;
+ uint8_t hi2 = hiVec2 < numVecs ? dist(gen) &
+ (0xff >> (8 - bitsPerCode))
+ : 0;
+
+ uint8_t v = 0;
+ if (bitsPerCode == 4) {
+ v = lo | (hi << 4);
+ } else if (bitsPerCode == 5) {
+ switch (k % 5) {
+ case 0:
+ // 5 msbs of lower as vOut lsbs
+ // 3 lsbs of upper as vOut msbs
+ v = (lo & 0x1f) | (hi << 5);
+ break;
+ case 1:
+ // 2 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ // 1 lsbs of upper2 as vOut msb
+ v = (lo >> 3) | (hi << 2) |
+ (hi2 << 7);
+ break;
+ case 2:
+ // 4 msbs of lower as vOut lsbs
+ // 4 lsbs of upper as vOut msbs
+ v = (lo >> 1) | (hi << 4);
+ break;
+ case 3:
+ // 1 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ // 2 lsbs of upper2 as vOut msb
+ v = (lo >> 4) | (hi << 1) |
+ (hi2 << 6);
+ break;
+ case 4:
+ // 3 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ v = (lo >> 2) | (hi << 3);
+ break;
+ }
+ } else if (bitsPerCode == 6) {
+ switch (k % 3) {
+ case 0:
+ // 6 msbs of lower as vOut lsbs
+ // 2 lsbs of upper as vOut msbs
+ v = (lo & 0x3f) | (hi << 6);
+ break;
+ case 1:
+ // 4 msbs of lower as vOut lsbs
+ // 4 lsbs of upper as vOut msbs
+ v = (lo >> 2) | (hi << 4);
+ break;
+ case 2:
+ // 2 msbs of lower as vOut lsbs
+ // 6 lsbs of upper as vOut msbs
+ v = (lo >> 4) | (hi << 2);
+ break;
+ }
+ } else {
+ // unimplemented
+ EXPECT_TRUE(false);
+ }
+
+ data[i * bytesPerBlock + j * bytesPerDimBlock +
+ k] = v;
+ }
+ }
+ }
+ } else {
+ // unimplemented
+ EXPECT_TRUE(false);
+ }
+
+ auto up = unpackInterleaved(data, numVecs, dims, bitsPerCode);
+ auto p = packInterleaved(up, numVecs, dims, bitsPerCode);
+
+ EXPECT_EQ(data, p);
+ }
+ }
+ }
+}
+
+TEST(TestCodePacking, InterleavedCodes_PackUnpack) {
+ using namespace faiss::gpu;
+
+ // We are fine using non-fixed seeds here, the results should be fully
+ // deterministic
+ std::random_device rd;
+ std::mt19937 gen(rd());
+ std::uniform_int_distribution<uint8_t> dist;
+
+ for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) {
+ for (auto dims : {1, 7, 8, 31, 32}) {
+ for (auto numVecs : {1, 3, 4, 5, 6, 8, 31, 32, 33, 65}) {
+ std::cout << bitsPerCode << " " << dims << " " << numVecs
+ << "\n";
+
+ std::vector<uint8_t> data(
+ numVecs * dims * utils::divUp(bitsPerCode, 8));
+
+ if (bitsPerCode == 8 || bitsPerCode == 16 ||
+ bitsPerCode == 32) {
+ for (auto& v : data) {
+ v = dist(gen);
+ }
+ } else if (bitsPerCode < 8) {
+ uint8_t mask = 0xff >> (8 - bitsPerCode);
+
+ for (auto& v : data) {
+ v = dist(gen) & mask;
+ }
+ } else {
+ // unimplemented
+ EXPECT_TRUE(false);
+ }
+
+ auto p = packInterleaved(data, numVecs, dims, bitsPerCode);
+ auto up = unpackInterleaved(p, numVecs, dims, bitsPerCode);
+
+ EXPECT_EQ(data, up);
+ }
+ }
+ }
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuDistance.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuDistance.cu
new file mode 100644
index 0000000..6c5526b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuDistance.cu
@@ -0,0 +1,571 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuDistance.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/Transpose.cuh>
+#include <sstream>
+#include <vector>
+
+enum class TestThresholds {
+ Normal,
+ BF16,
+ // Linf has worse error than the other metrics for bf16
+ BF16_Linf,
+};
+
+void evaluate_bfknn(
+ faiss::gpu::GpuDistanceParams& args,
+ faiss::gpu::GpuResourcesProvider* res,
+ std::vector<float>& cpuDistance,
+ std::vector<faiss::idx_t>& cpuIndices,
+ std::vector<float>& gpuDistance,
+ std::vector<faiss::idx_t>& gpuIndices,
+ int numQuery,
+ int k,
+ bool colMajorVecs,
+ bool colMajorQueries,
+ faiss::MetricType metric,
+ TestThresholds thresh = TestThresholds::Normal) {
+ using namespace faiss::gpu;
+
+ bfKnn(res, args);
+
+ std::stringstream str;
+ str << "using cuVS " << args.use_cuvs << " metric " << metric
+ << " colMajorVecs " << colMajorVecs << " colMajorQueries "
+ << colMajorQueries;
+
+ float maxRelativeError;
+ float pctMaxDiff1;
+ float pctMaxDiffN;
+
+ switch (thresh) {
+ case TestThresholds::Normal:
+ maxRelativeError = 6e-3f;
+ pctMaxDiff1 = 0.1f;
+ pctMaxDiffN = 0.015f;
+ break;
+ case TestThresholds::BF16:
+ maxRelativeError = 1.5e-2f;
+ pctMaxDiff1 = 0.3f;
+ pctMaxDiffN = 0.1f;
+ break;
+ case TestThresholds::BF16_Linf:
+ maxRelativeError = 1.5e-2f;
+ pctMaxDiff1 = 0.53f;
+ pctMaxDiffN = 0.2f;
+ break;
+ }
+
+ compareLists(
+ cpuDistance.data(),
+ cpuIndices.data(),
+ gpuDistance.data(),
+ gpuIndices.data(),
+ numQuery,
+ k,
+ str.str(),
+ false,
+ false,
+ true,
+ maxRelativeError,
+ pctMaxDiff1,
+ pctMaxDiffN);
+}
+
+void testTransposition(
+ bool colMajorVecs,
+ bool colMajorQueries,
+ faiss::MetricType metric,
+ bool use_cuvs = false,
+ float metricArg = 0) {
+ using namespace faiss::gpu;
+
+ int device = randVal(0, getNumDevices() - 1);
+
+ StandardGpuResources res;
+ res.noTempMemory();
+
+ // The transpose and distance code assumes the desired device is already set
+ DeviceScope scope(device);
+ auto stream = res.getDefaultStream(device);
+
+ int dim = randVal(20, 150);
+ int numVecs = randVal(10, 30000);
+ int numQuery = randVal(1, 1024);
+ int k = std::min(numVecs, randVal(20, 70));
+
+ // Input data for CPU
+ std::vector<float> vecs = randVecs(numVecs, dim);
+ std::vector<float> queries = randVecs(numQuery, dim);
+
+ if ((metric == faiss::MetricType::METRIC_JensenShannon) ||
+ (metric == faiss::MetricType::METRIC_Jaccard)) {
+ // make values positive
+ for (auto& v : vecs) {
+ v = std::abs(v);
+ if (v == 0) {
+ v = 1e-6;
+ }
+ }
+
+ for (auto& q : queries) {
+ q = std::abs(q);
+ if (q == 0) {
+ q = 1e-6;
+ }
+ }
+ }
+
+ // The CPU index is our reference for the results
+ faiss::IndexFlat cpuIndex(dim, metric);
+ cpuIndex.metric_arg = metricArg;
+ cpuIndex.add(numVecs, vecs.data());
+
+ std::vector<float> cpuDistance(numQuery * k, 0);
+ std::vector<faiss::idx_t> cpuIndices(numQuery * k, -1);
+
+ cpuIndex.search(
+ numQuery, queries.data(), k, cpuDistance.data(), cpuIndices.data());
+
+ // Copy input data to GPU, and pre-transpose both vectors and queries for
+ // passing
+ auto gpuVecs = toDeviceNonTemporary<float, 2>(
+ res.getResources().get(),
+ device,
+ vecs.data(),
+ stream,
+ {numVecs, dim});
+ auto gpuQueries = toDeviceNonTemporary<float, 2>(
+ res.getResources().get(),
+ device,
+ queries.data(),
+ stream,
+ {numQuery, dim});
+
+ DeviceTensor<float, 2, true> vecsT(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, stream),
+ {dim, numVecs});
+ runTransposeAny(gpuVecs, 0, 1, vecsT, stream);
+
+ DeviceTensor<float, 2, true> queriesT(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, stream),
+ {dim, numQuery});
+ runTransposeAny(gpuQueries, 0, 1, queriesT, stream);
+
+ std::vector<float> gpuDistance(numQuery * k, 0);
+ std::vector<faiss::idx_t> gpuIndices(numQuery * k, -1);
+
+ GpuDistanceParams args;
+ args.metric = metric;
+ args.metricArg = metricArg;
+ args.k = k;
+ args.dims = dim;
+ args.vectors = colMajorVecs ? vecsT.data() : gpuVecs.data();
+ args.vectorsRowMajor = !colMajorVecs;
+ args.numVectors = numVecs;
+ args.queries = colMajorQueries ? queriesT.data() : gpuQueries.data();
+ args.queriesRowMajor = !colMajorQueries;
+ args.numQueries = numQuery;
+ args.outDistances = gpuDistance.data();
+ args.outIndices = gpuIndices.data();
+ args.device = device;
+
+#if defined USE_NVIDIA_CUVS
+ args.use_cuvs = use_cuvs;
+#else
+ FAISS_THROW_IF_NOT_MSG(
+ !use_cuvs,
+ "cuVS has not been compiled into the current version so it cannot be used.");
+#endif
+
+ evaluate_bfknn(
+ args,
+ &res,
+ cpuDistance,
+ cpuIndices,
+ gpuDistance,
+ gpuIndices,
+ numQuery,
+ k,
+ colMajorVecs,
+ colMajorQueries,
+ metric);
+}
+
+void testTransposition_bf16(
+ bool colMajorVecs,
+ bool colMajorQueries,
+ faiss::MetricType metric,
+ bool use_raft = false,
+ float metricArg = 0) {
+ using namespace faiss::gpu;
+
+#ifdef USE_AMD_ROCM
+ std::cout << "skipping bfloat16 test (no bfloat16 support on AMD)\n";
+ EXPECT_TRUE(true);
+ return;
+#else
+ int device = randVal(0, getNumDevices() - 1);
+
+ StandardGpuResources res;
+ if (!res.supportsBFloat16(device)) {
+ std::cout << "skipping bfloat16 test (no bfloat16 support on device)\n";
+ return;
+ }
+
+ res.noTempMemory();
+ // The transpose and distance code assumes the desired device is already set
+ DeviceScope scope(device);
+ auto stream = res.getDefaultStream(device);
+
+ int dim = randVal(20, 150);
+ int numVecs = randVal(10, 30000);
+ int numQuery = randVal(1, 1024);
+ int k = std::min(numVecs, randVal(20, 70));
+
+ // Input data for CPU
+ std::vector<float> vecs = randVecs(numVecs, dim);
+ std::vector<float> queries = randVecs(numQuery, dim);
+
+ if ((metric == faiss::MetricType::METRIC_JensenShannon) ||
+ (metric == faiss::MetricType::METRIC_Jaccard)) {
+ // make values positive
+ for (auto& v : vecs) {
+ v = std::abs(v);
+ if (v == 0) {
+ v = 1e-6;
+ }
+ }
+
+ for (auto& q : queries) {
+ q = std::abs(q);
+ if (q == 0) {
+ q = 1e-6;
+ }
+ }
+ }
+
+ // The CPU index is our reference for the results
+ faiss::IndexFlat cpuIndex(dim, metric);
+ cpuIndex.metric_arg = metricArg;
+ cpuIndex.add(numVecs, vecs.data());
+
+ std::vector<float> cpuDistance(numQuery * k, 0);
+ std::vector<faiss::idx_t> cpuIndices(numQuery * k, -1);
+
+ cpuIndex.search(
+ numQuery, queries.data(), k, cpuDistance.data(), cpuIndices.data());
+
+ // Convert float32 data to bfloat16 via truncation not rounding
+ // (just copy high 2 bytes)
+ std::vector<uint16_t> bf16_vecs(vecs.size());
+ std::vector<uint16_t> bf16_queries(queries.size());
+
+ auto fn_f32_bf16 = [](float v) {
+ uint32_t vi;
+ std::memcpy(&vi, &v, sizeof(uint32_t));
+ return uint16_t(vi >> 16);
+ };
+
+ std::transform(vecs.begin(), vecs.end(), bf16_vecs.begin(), fn_f32_bf16);
+ std::transform(
+ queries.begin(), queries.end(), bf16_queries.begin(), fn_f32_bf16);
+
+ // Copy input data to GPU, and pre-transpose both vectors and queries for
+ // passing. Just use uint16_t in lieu of __nv_bfloat16
+ auto gpuVecs = toDeviceNonTemporary<uint16_t, 2>(
+ res.getResources().get(),
+ device,
+ bf16_vecs.data(),
+ stream,
+ {numVecs, dim});
+ auto gpuQueries = toDeviceNonTemporary<uint16_t, 2>(
+ res.getResources().get(),
+ device,
+ bf16_queries.data(),
+ stream,
+ {numQuery, dim});
+
+ DeviceTensor<uint16_t, 2, true> vecsT(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, stream),
+ {dim, numVecs});
+ runTransposeAny(gpuVecs, 0, 1, vecsT, stream);
+
+ DeviceTensor<uint16_t, 2, true> queriesT(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, stream),
+ {dim, numQuery});
+ runTransposeAny(gpuQueries, 0, 1, queriesT, stream);
+
+ std::vector<float> gpuDistance(numQuery * k, 0);
+ std::vector<faiss::idx_t> gpuIndices(numQuery * k, -1);
+
+ GpuDistanceParams args;
+ args.metric = metric;
+ args.metricArg = metricArg;
+ args.k = k;
+ args.dims = dim;
+ args.vectors = colMajorVecs ? vecsT.data() : gpuVecs.data();
+ args.vectorType = DistanceDataType::BF16;
+ args.vectorsRowMajor = !colMajorVecs;
+ args.numVectors = numVecs;
+ args.queries = colMajorQueries ? queriesT.data() : gpuQueries.data();
+ args.queryType = DistanceDataType::BF16;
+ args.queriesRowMajor = !colMajorQueries;
+ args.numQueries = numQuery;
+ args.outDistances = gpuDistance.data();
+ args.outIndices = gpuIndices.data();
+ args.device = device;
+
+ evaluate_bfknn(
+ args,
+ &res,
+ cpuDistance,
+ cpuIndices,
+ gpuDistance,
+ gpuIndices,
+ numQuery,
+ k,
+ colMajorVecs,
+ colMajorQueries,
+ metric,
+ metric == faiss::MetricType::METRIC_Linf ? TestThresholds::BF16_Linf
+ : TestThresholds::BF16);
+#endif
+}
+
+// Test different memory layouts for brute-force k-NN
+TEST(TestGpuDistance, Transposition_RR) {
+ testTransposition(false, false, faiss::MetricType::METRIC_L2);
+ testTransposition(false, false, faiss::MetricType::METRIC_INNER_PRODUCT);
+}
+
+TEST(TestGpuDistance, Transposition_RR_BF16) {
+ testTransposition_bf16(false, false, faiss::MetricType::METRIC_L2);
+ testTransposition_bf16(
+ false, false, faiss::MetricType::METRIC_INNER_PRODUCT);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, Transposition_RR) {
+ testTransposition(false, false, faiss::MetricType::METRIC_L2, true);
+ testTransposition(
+ false, false, faiss::MetricType::METRIC_INNER_PRODUCT, true);
+}
+#endif
+
+TEST(TestGpuDistance, Transposition_RC) {
+ testTransposition(false, true, faiss::MetricType::METRIC_L2);
+}
+
+TEST(TestGpuDistance, Transposition_RC_BF16) {
+ testTransposition_bf16(false, true, faiss::MetricType::METRIC_L2);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, Transposition_RC) {
+ testTransposition(false, true, faiss::MetricType::METRIC_L2, true);
+}
+#endif
+
+TEST(TestGpuDistance, Transposition_CR) {
+ testTransposition(true, false, faiss::MetricType::METRIC_L2);
+}
+
+TEST(TestGpuDistance, Transposition_CR_BF16) {
+ testTransposition_bf16(true, false, faiss::MetricType::METRIC_L2);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, Transposition_CR) {
+ testTransposition(true, false, faiss::MetricType::METRIC_L2, true);
+}
+#endif
+
+TEST(TestGpuDistance, Transposition_CC) {
+ testTransposition(true, true, faiss::MetricType::METRIC_L2);
+}
+
+TEST(TestGpuDistance, Transposition_CC_BF16) {
+ testTransposition_bf16(true, true, faiss::MetricType::METRIC_L2);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, Transposition_CC) {
+ testTransposition(true, true, faiss::MetricType::METRIC_L2, true);
+}
+#endif
+
+TEST(TestGpuDistance, L1) {
+ testTransposition(false, false, faiss::MetricType::METRIC_L1);
+}
+
+TEST(TestGpuDistance, L1_BF16) {
+ testTransposition_bf16(false, false, faiss::MetricType::METRIC_L1);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, L1) {
+ testTransposition(false, false, faiss::MetricType::METRIC_L1, true);
+}
+#endif
+
+// Test other transpositions with the general distance kernel
+TEST(TestGpuDistance, L1_RC) {
+ testTransposition(false, true, faiss::MetricType::METRIC_L1);
+}
+
+#if defined USE_NVIDIA_CUVS
+// Test other transpositions with the general distance kernel
+TEST(TestCuvsGpuDistance, L1_RC) {
+ testTransposition(false, true, faiss::MetricType::METRIC_L1, true);
+}
+#endif
+
+TEST(TestGpuDistance, L1_RC_BF16) {
+ testTransposition_bf16(false, true, faiss::MetricType::METRIC_L1);
+}
+
+TEST(TestGpuDistance, L1_CR) {
+ testTransposition(true, false, faiss::MetricType::METRIC_L1);
+}
+
+TEST(TestGpuDistance, L1_CR_BF16) {
+ testTransposition_bf16(true, false, faiss::MetricType::METRIC_L1);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, L1_CR) {
+ testTransposition(true, false, faiss::MetricType::METRIC_L1, true);
+}
+#endif
+
+TEST(TestGpuDistance, L1_CC) {
+ testTransposition(true, true, faiss::MetricType::METRIC_L1);
+}
+
+TEST(TestGpuDistance, L1_CC_BF16) {
+ testTransposition_bf16(true, true, faiss::MetricType::METRIC_L1);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, L1_CC) {
+ testTransposition(true, true, faiss::MetricType::METRIC_L1, true);
+}
+#endif
+
+// Test remainder of metric types
+TEST(TestGpuDistance, Linf) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Linf);
+}
+
+#if defined USE_NVIDIA_CUVS
+// Test remainder of metric types
+TEST(TestCuvsGpuDistance, Linf) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Linf, true);
+}
+#endif
+
+TEST(TestGpuDistance, Linf_BF16) {
+ testTransposition_bf16(false, false, faiss::MetricType::METRIC_Linf);
+}
+
+TEST(TestGpuDistance, Lp) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Lp, false, 3);
+}
+
+TEST(TestGpuDistance, Lp_BF16) {
+ testTransposition_bf16(
+ false, false, faiss::MetricType::METRIC_Lp, false, 3);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, Lp) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Lp, true, 3);
+}
+#endif
+
+TEST(TestGpuDistance, Canberra) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Canberra);
+}
+
+TEST(TestGpuDistance, Canberra_BF16) {
+ testTransposition_bf16(false, false, faiss::MetricType::METRIC_Canberra);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, Canberra) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Canberra, true);
+}
+#endif
+
+TEST(TestGpuDistance, BrayCurtis) {
+ testTransposition(false, false, faiss::MetricType::METRIC_BrayCurtis);
+}
+
+TEST(TestGpuDistance, BrayCurtis_BF16) {
+ testTransposition_bf16(false, false, faiss::MetricType::METRIC_BrayCurtis);
+}
+
+TEST(TestGpuDistance, JensenShannon) {
+ testTransposition(false, false, faiss::MetricType::METRIC_JensenShannon);
+}
+
+TEST(TestGpuDistance, JensenShannon_BF16) {
+ testTransposition_bf16(
+ false, false, faiss::MetricType::METRIC_JensenShannon);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuDistance, JensenShannon) {
+ testTransposition(
+ false, false, faiss::MetricType::METRIC_JensenShannon, true);
+}
+#endif
+
+TEST(TestGpuDistance, Jaccard) {
+ testTransposition(false, false, faiss::MetricType::METRIC_Jaccard);
+}
+
+TEST(TestGpuDistance, Jaccard_BF16) {
+ testTransposition_bf16(false, false, faiss::MetricType::METRIC_Jaccard);
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexBinaryFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexBinaryFlat.cpp
new file mode 100644
index 0000000..064464a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexBinaryFlat.cpp
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/gpu/GpuIndexBinaryFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+#include <gtest/gtest.h>
+#include <sstream>
+#include <vector>
+
+void compareBinaryDist(
+ const std::vector<int>& cpuDist,
+ const std::vector<faiss::idx_t>& cpuLabels,
+ const std::vector<int>& gpuDist,
+ const std::vector<faiss::idx_t>& gpuLabels,
+ int numQuery,
+ int k) {
+ for (int i = 0; i < numQuery; ++i) {
+ // The index order can be permuted within a group that has the same
+ // distance, since this is based on the order in which the algorithm
+ // encounters the values. The last set of equivalent distances seen in
+ // the min-k might be truncated, so we can't check that set, but all
+ // others we can check.
+ std::set<faiss::idx_t> cpuLabelSet;
+ std::set<faiss::idx_t> gpuLabelSet;
+
+ int curDist = -1;
+
+ for (int j = 0; j < k; ++j) {
+ int idx = i * k + j;
+
+ if (curDist == -1) {
+ curDist = cpuDist[idx];
+ }
+
+ if (curDist != cpuDist[idx]) {
+ // Distances must be monotonically increasing
+ EXPECT_LT(curDist, cpuDist[idx]);
+
+ // This is a new set of distances
+ EXPECT_EQ(cpuLabelSet, gpuLabelSet);
+ curDist = cpuDist[idx];
+ cpuLabelSet.clear();
+ gpuLabelSet.clear();
+ }
+
+ cpuLabelSet.insert(cpuLabels[idx]);
+ gpuLabelSet.insert(gpuLabels[idx]);
+
+ // Because the distances are reproducible, they must be exactly the
+ // same
+ EXPECT_EQ(cpuDist[idx], gpuDist[idx]);
+ }
+ }
+}
+
+template <int DimMultiple>
+void testGpuIndexBinaryFlat(int kOverride = -1) {
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexBinaryFlatConfig config;
+ config.device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ // multiples of 8 and multiples of 32 use different implementations
+ int dims = faiss::gpu::randVal(1, 20) * DimMultiple;
+ faiss::gpu::GpuIndexBinaryFlat gpuIndex(&res, dims, config);
+
+ faiss::IndexBinaryFlat cpuIndex(dims);
+
+ int k = kOverride > 0
+ ? kOverride
+ : faiss::gpu::randVal(1, faiss::gpu::getMaxKSelection());
+ int numVecs = faiss::gpu::randVal(k + 1, 20000);
+ int numQuery = faiss::gpu::randVal(1, 1000);
+
+ auto data = faiss::gpu::randBinaryVecs(numVecs, dims);
+ gpuIndex.add(numVecs, data.data());
+ cpuIndex.add(numVecs, data.data());
+
+ auto query = faiss::gpu::randBinaryVecs(numQuery, dims);
+
+ std::vector<int> cpuDist(numQuery * k);
+ std::vector<faiss::idx_t> cpuLabels(numQuery * k);
+
+ cpuIndex.search(
+ numQuery, query.data(), k, cpuDist.data(), cpuLabels.data());
+
+ std::vector<int> gpuDist(numQuery * k);
+ std::vector<faiss::idx_t> gpuLabels(numQuery * k);
+
+ gpuIndex.search(
+ numQuery, query.data(), k, gpuDist.data(), gpuLabels.data());
+
+ compareBinaryDist(cpuDist, cpuLabels, gpuDist, gpuLabels, numQuery, k);
+}
+
+TEST(TestGpuIndexBinaryFlat, Test8) {
+ for (int tries = 0; tries < 4; ++tries) {
+ testGpuIndexBinaryFlat<8>();
+ }
+}
+
+TEST(TestGpuIndexBinaryFlat, Test32) {
+ for (int tries = 0; tries < 4; ++tries) {
+ testGpuIndexBinaryFlat<32>();
+ }
+}
+
+TEST(TestGpuIndexBinaryFlat, LargeIndex) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ // Skip this device if we do not have sufficient memory
+ constexpr size_t kMem = size_t(8) * 1024 * 1024 * 1024;
+
+ if (faiss::gpu::getFreeMemory(device) < kMem) {
+ std::cerr << "TestGpuIndexFlat.LargeIndex: skipping due "
+ "to insufficient device memory\n";
+ return;
+ }
+
+ std::cerr << "Running LargeIndex test\n";
+
+ faiss::gpu::GpuIndexBinaryFlatConfig config;
+ config.device = device;
+
+ int dims = 1250 * 8;
+ faiss::gpu::GpuIndexBinaryFlat gpuIndex(&res, dims, config);
+
+ faiss::IndexBinaryFlat cpuIndex(dims);
+
+ int k = 10;
+ int nb = 4000000;
+ int nq = 10;
+
+ auto xb = faiss::gpu::randBinaryVecs(nb, dims);
+ auto xq = faiss::gpu::randBinaryVecs(nq, dims);
+ gpuIndex.add(nb, xb.data());
+ cpuIndex.add(nb, xb.data());
+
+ std::vector<int> cpuDist(nq * k);
+ std::vector<faiss::idx_t> cpuLabels(nq * k);
+
+ cpuIndex.search(nq, xq.data(), k, cpuDist.data(), cpuLabels.data());
+
+ std::vector<int> gpuDist(nq * k);
+ std::vector<faiss::idx_t> gpuLabels(nq * k);
+
+ gpuIndex.search(nq, xq.data(), k, gpuDist.data(), gpuLabels.data());
+
+ compareBinaryDist(cpuDist, cpuLabels, gpuDist, gpuLabels, nq, k);
+}
+
+TEST(TestGpuIndexBinaryFlat, Reconstruct) {
+ int n = 1000;
+ std::vector<uint8_t> xb(8 * n);
+ faiss::byte_rand(xb.data(), xb.size(), 123);
+ std::unique_ptr<faiss::IndexBinaryFlat> index(
+ new faiss::IndexBinaryFlat(64));
+ index->add(n, xb.data());
+
+ std::vector<uint8_t> xb3(8 * n);
+ index->reconstruct_n(0, index->ntotal, xb3.data());
+ EXPECT_EQ(xb, xb3);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ std::unique_ptr<faiss::gpu::GpuIndexBinaryFlat> index2(
+ new faiss::gpu::GpuIndexBinaryFlat(&res, index.get()));
+
+ std::vector<uint8_t> xb2(8 * n);
+
+ index2->reconstruct_n(0, index->ntotal, xb2.data());
+ EXPECT_EQ(xb2, xb3);
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexCagra.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexCagra.cu
new file mode 100644
index 0000000..16b9470
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexCagra.cu
@@ -0,0 +1,475 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/IndexHNSW.h>
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuIndexCagra.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/utils/distances.h>
+#include <cstddef>
+#include <faiss/gpu/utils/CopyUtils.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <optional>
+#include <vector>
+
+#include <raft/core/resource/cuda_stream.hpp>
+#include <raft/stats/neighborhood_recall.cuh>
+
+struct Options {
+ Options() {
+ numTrain = 2 * faiss::gpu::randVal(2000, 5000);
+ dim = faiss::gpu::randVal(4, 10);
+ numAdd = faiss::gpu::randVal(1000, 3000);
+
+ graphDegree = faiss::gpu::randSelect({32, 64});
+ intermediateGraphDegree = faiss::gpu::randSelect({64, 98});
+ buildAlgo = faiss::gpu::randSelect(
+ {faiss::gpu::graph_build_algo::IVF_PQ,
+ faiss::gpu::graph_build_algo::NN_DESCENT});
+
+ numQuery = faiss::gpu::randVal(32, 100);
+ k = faiss::gpu::randVal(10, 30);
+
+ device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+ }
+
+ std::string toString() const {
+ std::stringstream str;
+ str << "CAGRA device " << device << " numVecs " << numTrain << " dim "
+ << dim << " graphDegree " << graphDegree
+ << " intermediateGraphDegree " << intermediateGraphDegree
+ << "buildAlgo " << static_cast<int>(buildAlgo) << " numQuery "
+ << numQuery << " k " << k;
+
+ return str.str();
+ }
+
+ int numTrain;
+ int numAdd;
+ int dim;
+ size_t graphDegree;
+ size_t intermediateGraphDegree;
+ faiss::gpu::graph_build_algo buildAlgo;
+ int numQuery;
+ int k;
+ int device;
+};
+
+void queryTest(faiss::MetricType metric, double expected_recall) {
+ for (int tries = 0; tries < 5; ++tries) {
+ Options opt;
+ if (opt.buildAlgo == faiss::gpu::graph_build_algo::NN_DESCENT &&
+ metric == faiss::METRIC_INNER_PRODUCT) {
+ continue;
+ }
+
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numTrain, opt.dim, trainVecs.data());
+ }
+
+ // train cpu index
+ faiss::IndexHNSWFlat cpuIndex(opt.dim, opt.graphDegree / 2, metric);
+ cpuIndex.hnsw.efConstruction = opt.k * 2;
+ cpuIndex.add(opt.numTrain, trainVecs.data());
+
+ // train gpu index
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexCagraConfig config;
+ config.device = opt.device;
+ config.graph_degree = opt.graphDegree;
+ config.intermediate_graph_degree = opt.intermediateGraphDegree;
+ config.build_algo = opt.buildAlgo;
+
+ faiss::gpu::GpuIndexCagra gpuIndex(&res, cpuIndex.d, metric, config);
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // query
+ auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numQuery, opt.dim, queryVecs.data());
+ }
+
+ std::vector<float> refDistance(opt.numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> refIndices(opt.numQuery * opt.k, -1);
+ faiss::SearchParametersHNSW cpuSearchParams;
+ cpuSearchParams.efSearch = opt.k * 2;
+ cpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ refDistance.data(),
+ refIndices.data(),
+ &cpuSearchParams);
+
+ // test quality of searches
+ auto gpuRes = res.getResources();
+ auto devAlloc = faiss::gpu::makeDevAlloc(
+ faiss::gpu::AllocType::FlatData,
+ gpuRes->getDefaultStreamCurrentDevice());
+ faiss::gpu::DeviceTensor<float, 2, true> testDistance(
+ gpuRes.get(), devAlloc, {opt.numQuery, opt.k});
+ faiss::gpu::DeviceTensor<faiss::idx_t, 2, true> testIndices(
+ gpuRes.get(), devAlloc, {opt.numQuery, opt.k});
+ gpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ testDistance.data(),
+ testIndices.data());
+
+ auto refDistanceDev = faiss::gpu::toDeviceTemporary(
+ gpuRes.get(),
+ refDistance,
+ gpuRes->getDefaultStreamCurrentDevice());
+ auto refIndicesDev = faiss::gpu::toDeviceTemporary(
+ gpuRes.get(),
+ refIndices,
+ gpuRes->getDefaultStreamCurrentDevice());
+
+ auto raft_handle = gpuRes->getRaftHandleCurrentDevice();
+
+ auto ref_dis_mds = raft::make_device_matrix_view<const float, int>(
+ refDistanceDev.data(), opt.numQuery, opt.k);
+ auto ref_dis_mds_opt =
+ std::optional<raft::device_matrix_view<const float, int>>(
+ ref_dis_mds);
+ auto ref_ind_mds =
+ raft::make_device_matrix_view<const faiss::idx_t, int>(
+ refIndicesDev.data(), opt.numQuery, opt.k);
+
+ auto test_dis_mds = raft::make_device_matrix_view<const float, int>(
+ testDistance.data(), opt.numQuery, opt.k);
+ auto test_dis_mds_opt =
+ std::optional<raft::device_matrix_view<const float, int>>(
+ test_dis_mds);
+
+ auto test_ind_mds =
+ raft::make_device_matrix_view<const faiss::idx_t, int>(
+ testIndices.data(), opt.numQuery, opt.k);
+
+ double scalar_init = 0;
+ auto recall_score = raft::make_host_scalar(scalar_init);
+
+ raft::stats::neighborhood_recall(
+ raft_handle,
+ test_ind_mds,
+ ref_ind_mds,
+ recall_score.view(),
+ test_dis_mds_opt,
+ ref_dis_mds_opt);
+ ASSERT_TRUE(*recall_score.data_handle() > expected_recall);
+ }
+}
+
+TEST(TestGpuIndexCagra, Float32_Query_L2) {
+ queryTest(faiss::METRIC_L2, 0.98);
+}
+
+TEST(TestGpuIndexCagra, Float32_Query_IP) {
+ queryTest(faiss::METRIC_INNER_PRODUCT, 0.98);
+}
+
+void copyToTest(
+ faiss::MetricType metric,
+ double expected_recall,
+ bool base_level_only) {
+ for (int tries = 0; tries < 5; ++tries) {
+ Options opt;
+ if (opt.buildAlgo == faiss::gpu::graph_build_algo::NN_DESCENT &&
+ metric == faiss::METRIC_INNER_PRODUCT) {
+ continue;
+ }
+
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numTrain, opt.dim, trainVecs.data());
+ }
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numAdd, opt.dim, addVecs.data());
+ }
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ // train gpu index and copy to cpu index
+ faiss::gpu::GpuIndexCagraConfig config;
+ config.device = opt.device;
+ config.graph_degree = opt.graphDegree;
+ config.intermediate_graph_degree = opt.intermediateGraphDegree;
+ config.build_algo = opt.buildAlgo;
+
+ faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config);
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+
+ faiss::IndexHNSWCagra copiedCpuIndex(
+ opt.dim, opt.graphDegree / 2, metric);
+ copiedCpuIndex.base_level_only = base_level_only;
+ gpuIndex.copyTo(&copiedCpuIndex);
+ copiedCpuIndex.hnsw.efConstruction = opt.k * 2;
+
+ // add more vecs to copied cpu index
+ if (!base_level_only) {
+ copiedCpuIndex.add(opt.numAdd, addVecs.data());
+ }
+
+ // train cpu index
+ faiss::IndexHNSWFlat cpuIndex(opt.dim, opt.graphDegree / 2, metric);
+ cpuIndex.hnsw.efConstruction = opt.k * 2;
+ cpuIndex.add(opt.numTrain, trainVecs.data());
+
+ // add more vecs to cpu index
+ if (!base_level_only) {
+ cpuIndex.add(opt.numAdd, addVecs.data());
+ }
+
+ // query indexes
+ auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numQuery, opt.dim, queryVecs.data());
+ }
+
+ std::vector<float> refDistance(opt.numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> refIndices(opt.numQuery * opt.k, -1);
+ faiss::SearchParametersHNSW cpuSearchParams;
+ cpuSearchParams.efSearch = opt.k * 2;
+ cpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ refDistance.data(),
+ refIndices.data(),
+ &cpuSearchParams);
+
+ std::vector<float> copyRefDistance(opt.numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> copyRefIndices(opt.numQuery * opt.k, -1);
+ faiss::SearchParametersHNSW cpuSearchParamstwo;
+ cpuSearchParamstwo.efSearch = opt.k * 2;
+ copiedCpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ copyRefDistance.data(),
+ copyRefIndices.data(),
+ &cpuSearchParamstwo);
+
+ // test quality of search
+ auto gpuRes = res.getResources();
+
+ auto refDistanceDev = faiss::gpu::toDeviceTemporary(
+ gpuRes.get(),
+ refDistance,
+ gpuRes->getDefaultStreamCurrentDevice());
+ auto refIndicesDev = faiss::gpu::toDeviceTemporary(
+ gpuRes.get(),
+ refIndices,
+ gpuRes->getDefaultStreamCurrentDevice());
+
+ auto copyRefDistanceDev = faiss::gpu::toDeviceTemporary(
+ gpuRes.get(),
+ copyRefDistance,
+ gpuRes->getDefaultStreamCurrentDevice());
+ auto copyRefIndicesDev = faiss::gpu::toDeviceTemporary(
+ gpuRes.get(),
+ copyRefIndices,
+ gpuRes->getDefaultStreamCurrentDevice());
+
+ auto raft_handle = gpuRes->getRaftHandleCurrentDevice();
+
+ auto ref_dis_mds = raft::make_device_matrix_view<const float, int>(
+ refDistanceDev.data(), opt.numQuery, opt.k);
+ auto ref_dis_mds_opt =
+ std::optional<raft::device_matrix_view<const float, int>>(
+ ref_dis_mds);
+ auto ref_ind_mds =
+ raft::make_device_matrix_view<const faiss::idx_t, int>(
+ refIndicesDev.data(), opt.numQuery, opt.k);
+
+ auto copy_ref_dis_mds = raft::make_device_matrix_view<const float, int>(
+ copyRefDistanceDev.data(), opt.numQuery, opt.k);
+ auto copy_ref_dis_mds_opt =
+ std::optional<raft::device_matrix_view<const float, int>>(
+ copy_ref_dis_mds);
+ auto copy_ref_ind_mds =
+ raft::make_device_matrix_view<const faiss::idx_t, int>(
+ copyRefIndicesDev.data(), opt.numQuery, opt.k);
+
+ double scalar_init = 0;
+ auto recall_score = raft::make_host_scalar(scalar_init);
+
+ raft::stats::neighborhood_recall(
+ raft_handle,
+ copy_ref_ind_mds,
+ ref_ind_mds,
+ recall_score.view(),
+ copy_ref_dis_mds_opt,
+ ref_dis_mds_opt);
+ ASSERT_TRUE(*recall_score.data_handle() > expected_recall);
+ }
+}
+
+TEST(TestGpuIndexCagra, Float32_CopyTo_L2) {
+ copyToTest(faiss::METRIC_L2, 0.98, false);
+}
+
+TEST(TestGpuIndexCagra, Float32_CopyTo_L2_BaseLevelOnly) {
+ copyToTest(faiss::METRIC_L2, 0.98, true);
+}
+
+TEST(TestGpuIndexCagra, Float32_CopyTo_IP) {
+ copyToTest(faiss::METRIC_INNER_PRODUCT, 0.98, false);
+}
+
+TEST(TestGpuIndexCagra, Float32_CopyTo_IP_BaseLevelOnly) {
+ copyToTest(faiss::METRIC_INNER_PRODUCT, 0.98, true);
+}
+
+void copyFromTest(faiss::MetricType metric, double expected_recall) {
+ for (int tries = 0; tries < 5; ++tries) {
+ Options opt;
+ if (opt.buildAlgo == faiss::gpu::graph_build_algo::NN_DESCENT &&
+ metric == faiss::METRIC_INNER_PRODUCT) {
+ continue;
+ }
+
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numTrain, opt.dim, trainVecs.data());
+ }
+
+ // train cpu index
+ faiss::IndexHNSWCagra cpuIndex(opt.dim, opt.graphDegree / 2, metric);
+ cpuIndex.hnsw.efConstruction = opt.k * 2;
+ cpuIndex.add(opt.numTrain, trainVecs.data());
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ // convert to gpu index
+ faiss::gpu::GpuIndexCagra copiedGpuIndex(&res, cpuIndex.d, metric);
+ copiedGpuIndex.copyFrom(&cpuIndex);
+
+ // train gpu index
+ faiss::gpu::GpuIndexCagraConfig config;
+ config.device = opt.device;
+ config.graph_degree = opt.graphDegree;
+ config.intermediate_graph_degree = opt.intermediateGraphDegree;
+ config.build_algo = opt.buildAlgo;
+
+ faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config);
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // query
+ auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim);
+ if (metric == faiss::METRIC_INNER_PRODUCT) {
+ faiss::fvec_renorm_L2(opt.numQuery, opt.dim, queryVecs.data());
+ }
+
+ auto gpuRes = res.getResources();
+ auto devAlloc = faiss::gpu::makeDevAlloc(
+ faiss::gpu::AllocType::FlatData,
+ gpuRes->getDefaultStreamCurrentDevice());
+ faiss::gpu::DeviceTensor<float, 2, true> copyTestDistance(
+ gpuRes.get(), devAlloc, {opt.numQuery, opt.k});
+ faiss::gpu::DeviceTensor<faiss::idx_t, 2, true> copyTestIndices(
+ gpuRes.get(), devAlloc, {opt.numQuery, opt.k});
+ copiedGpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ copyTestDistance.data(),
+ copyTestIndices.data());
+
+ faiss::gpu::DeviceTensor<float, 2, true> testDistance(
+ gpuRes.get(), devAlloc, {opt.numQuery, opt.k});
+ faiss::gpu::DeviceTensor<faiss::idx_t, 2, true> testIndices(
+ gpuRes.get(), devAlloc, {opt.numQuery, opt.k});
+ gpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ testDistance.data(),
+ testIndices.data());
+
+ // test quality of searches
+ auto raft_handle = gpuRes->getRaftHandleCurrentDevice();
+
+ auto test_dis_mds = raft::make_device_matrix_view<const float, int>(
+ testDistance.data(), opt.numQuery, opt.k);
+ auto test_dis_mds_opt =
+ std::optional<raft::device_matrix_view<const float, int>>(
+ test_dis_mds);
+
+ auto test_ind_mds =
+ raft::make_device_matrix_view<const faiss::idx_t, int>(
+ testIndices.data(), opt.numQuery, opt.k);
+
+ auto copy_test_dis_mds =
+ raft::make_device_matrix_view<const float, int>(
+ copyTestDistance.data(), opt.numQuery, opt.k);
+ auto copy_test_dis_mds_opt =
+ std::optional<raft::device_matrix_view<const float, int>>(
+ copy_test_dis_mds);
+
+ auto copy_test_ind_mds =
+ raft::make_device_matrix_view<const faiss::idx_t, int>(
+ copyTestIndices.data(), opt.numQuery, opt.k);
+
+ double scalar_init = 0;
+ auto recall_score = raft::make_host_scalar(scalar_init);
+
+ raft::stats::neighborhood_recall(
+ raft_handle,
+ copy_test_ind_mds,
+ test_ind_mds,
+ recall_score.view(),
+ copy_test_dis_mds_opt,
+ test_dis_mds_opt);
+ ASSERT_TRUE(*recall_score.data_handle() > expected_recall);
+ }
+}
+
+TEST(TestGpuIndexCagra, Float32_CopyFrom_L2) {
+ copyFromTest(faiss::METRIC_L2, 0.98);
+}
+
+TEST(TestGpuIndexCagra, Float32_CopyFrom_IP) {
+ copyFromTest(faiss::METRIC_INNER_PRODUCT, 0.98);
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp
new file mode 100644
index 0000000..3146e78
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp
@@ -0,0 +1,770 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/impl/IndexUtils.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+#include <sstream>
+#include <unordered_map>
+#include <vector>
+
+// FIXME: figure out a better way to test fp16
+constexpr float kF16MaxRelErr = 0.07f;
+constexpr float kF32MaxRelErr = 6e-3f;
+
+struct TestFlatOptions {
+ TestFlatOptions()
+ : metric(faiss::MetricType::METRIC_L2),
+ metricArg(0),
+ useFloat16(false),
+ numVecsOverride(-1),
+ numQueriesOverride(-1),
+ kOverride(-1),
+ dimOverride(-1),
+ use_cuvs(false) {}
+
+ faiss::MetricType metric;
+ float metricArg;
+
+ bool useFloat16;
+ int numVecsOverride;
+ int numQueriesOverride;
+ int kOverride;
+ int dimOverride;
+ bool use_cuvs;
+};
+
+void testFlat(const TestFlatOptions& opt) {
+ int numVecs = opt.numVecsOverride > 0 ? opt.numVecsOverride
+ : faiss::gpu::randVal(1000, 5000);
+ int dim = opt.dimOverride > 0 ? opt.dimOverride
+ : faiss::gpu::randVal(50, 800);
+ int numQuery = opt.numQueriesOverride > 0 ? opt.numQueriesOverride
+ : faiss::gpu::randVal(1, 512);
+
+ // Due to loss of precision in a float16 accumulator, for large k,
+ // the number of differences is pretty huge. Restrict ourselves to a
+ // fairly small `k` for float16
+ int k = opt.useFloat16
+ ? std::min(faiss::gpu::randVal(1, 50), numVecs)
+ : std::min(
+ faiss::gpu::randVal(1, faiss::gpu::getMaxKSelection()),
+ numVecs);
+ if (opt.kOverride > 0) {
+ k = opt.kOverride;
+ }
+
+ faiss::IndexFlat cpuIndex(dim, opt.metric);
+ cpuIndex.metric_arg = opt.metricArg;
+
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.useFloat16 = opt.useFloat16;
+ config.use_cuvs = opt.use_cuvs;
+
+ faiss::gpu::GpuIndexFlat gpuIndex(&res, dim, opt.metric, config);
+ gpuIndex.metric_arg = opt.metricArg;
+
+ std::vector<float> vecs = faiss::gpu::randVecs(numVecs, dim);
+ cpuIndex.add(numVecs, vecs.data());
+ gpuIndex.add(numVecs, vecs.data());
+
+ std::stringstream str;
+ str << "metric " << opt.metric << " marg " << opt.metricArg << " numVecs "
+ << numVecs << " dim " << dim << " useFloat16 " << opt.useFloat16
+ << " numQuery " << numQuery << " k " << k;
+
+ // To some extent, we depend upon the relative error for the test
+ // for float16
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ numQuery,
+ dim,
+ k,
+ str.str(),
+ opt.useFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ // FIXME: the fp16 bounds are
+ // useless when math (the accumulator) is
+ // in fp16. Figure out another way to test
+ opt.useFloat16 ? 0.99f : 0.1f,
+ opt.useFloat16 ? 0.65f : 0.015f);
+}
+
+TEST(TestGpuIndexFlat, IP_Float32) {
+ for (int tries = 0; tries < 3; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_INNER_PRODUCT;
+ opt.useFloat16 = false;
+
+ testFlat(opt);
+
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+TEST(TestGpuIndexFlat, L1_Float32) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L1;
+ opt.useFloat16 = false;
+
+ testFlat(opt);
+
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+}
+
+TEST(TestGpuIndexFlat, Lp_Float32) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_Lp;
+ opt.metricArg = 5;
+ opt.useFloat16 = false;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+}
+
+TEST(TestGpuIndexFlat, L2_Float32) {
+ for (int tries = 0; tries < 3; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L2;
+
+ opt.useFloat16 = false;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+// At least one test for the k > 1024 select
+TEST(TestGpuIndexFlat, L2_k_2048) {
+ if (faiss::gpu::getMaxKSelection() >= 2048) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L2;
+ opt.useFloat16 = false;
+ opt.kOverride = 2048;
+ opt.dimOverride = 128;
+ opt.numVecsOverride = 10000;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+// test specialized k == 1 codepath
+TEST(TestGpuIndexFlat, L2_Float32_K1) {
+ for (int tries = 0; tries < 3; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L2;
+ opt.useFloat16 = false;
+ opt.kOverride = 1;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+TEST(TestGpuIndexFlat, IP_Float16) {
+ for (int tries = 0; tries < 3; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_INNER_PRODUCT;
+ opt.useFloat16 = true;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+TEST(TestGpuIndexFlat, L2_Float16) {
+ for (int tries = 0; tries < 3; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L2;
+ opt.useFloat16 = true;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+// test specialized k == 1 codepath
+TEST(TestGpuIndexFlat, L2_Float16_K1) {
+ for (int tries = 0; tries < 3; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L2;
+ opt.useFloat16 = true;
+ opt.kOverride = 1;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+// test tiling along a huge vector set
+TEST(TestGpuIndexFlat, L2_Tiling) {
+ for (int tries = 0; tries < 2; ++tries) {
+ TestFlatOptions opt;
+ opt.metric = faiss::MetricType::METRIC_L2;
+ opt.useFloat16 = false;
+ opt.numVecsOverride = 1000000;
+
+ // keep the rest of the problem reasonably small
+ opt.numQueriesOverride = 4;
+ opt.dimOverride = 64;
+ opt.kOverride = 64;
+
+ testFlat(opt);
+#if defined USE_NVIDIA_CUVS
+ opt.use_cuvs = true;
+ testFlat(opt);
+#endif
+ }
+}
+
+TEST(TestGpuIndexFlat, QueryEmpty) {
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = 0;
+ config.useFloat16 = false;
+ config.use_cuvs = false;
+ int dim = 128;
+ faiss::gpu::GpuIndexFlatL2 gpuIndex(&res, dim, config);
+
+ // Querying an empty index should not blow up, and just return
+ // (FLT_MAX, -1)
+ int numQuery = 10;
+ int k = 50;
+ std::vector<float> queries(numQuery * dim, 1.0f);
+
+ std::vector<float> dist(numQuery * k, 0);
+ std::vector<faiss::idx_t> ind(numQuery * k);
+
+ gpuIndex.search(numQuery, queries.data(), k, dist.data(), ind.data());
+
+ for (auto d : dist) {
+ EXPECT_EQ(d, std::numeric_limits<float>::max());
+ }
+
+ for (auto i : ind) {
+ EXPECT_EQ(i, -1);
+ }
+}
+
+void testCopyFrom(bool use_cuvs) {
+ int numVecs = faiss::gpu::randVal(100, 200);
+ int dim = faiss::gpu::randVal(1, 1000);
+
+ std::vector<float> vecs = faiss::gpu::randVecs(numVecs, dim);
+
+ faiss::IndexFlatL2 cpuIndex(dim);
+ cpuIndex.add(numVecs, vecs.data());
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ for (bool useFloat16 : {false, true}) {
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.useFloat16 = useFloat16;
+ config.use_cuvs = use_cuvs;
+
+ // Fill with garbage values
+ faiss::gpu::GpuIndexFlatL2 gpuIndex(&res, 2000, config);
+ gpuIndex.copyFrom(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, numVecs);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.d, dim);
+
+ std::vector<float> gpuVals(numVecs * dim);
+ gpuIndex.reconstruct_n(0, gpuIndex.ntotal, gpuVals.data());
+
+ std::vector<float> cpuVals(numVecs * dim);
+ cpuIndex.reconstruct_n(0, gpuIndex.ntotal, cpuVals.data());
+
+ // The CPU is the source of (float32) truth here, while the GPU index
+ // may be in float16 mode and thus was subject to rounding
+ if (useFloat16) {
+ EXPECT_EQ(gpuVals, faiss::gpu::roundToHalf(cpuVals));
+ } else {
+ // Should be exactly the same
+ EXPECT_EQ(gpuVals, cpuVals);
+ }
+ }
+}
+
+TEST(TestGpuIndexFlat, CopyFrom) {
+ testCopyFrom(false);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, CopyFrom) {
+ testCopyFrom(true);
+}
+#endif
+
+void testCopyTo(bool use_cuvs) {
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ int numVecs = faiss::gpu::randVal(100, 200);
+ int dim = faiss::gpu::randVal(1, 1000);
+
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+ std::vector<float> vecs = faiss::gpu::randVecs(numVecs, dim);
+
+ for (bool useFloat16 : {false, true}) {
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.useFloat16 = useFloat16;
+ config.use_cuvs = use_cuvs;
+
+ faiss::gpu::GpuIndexFlatL2 gpuIndex(&res, dim, config);
+ gpuIndex.add(numVecs, vecs.data());
+
+ // Fill with garbage values
+ faiss::IndexFlatL2 cpuIndex(2000);
+ gpuIndex.copyTo(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, numVecs);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.d, dim);
+
+ std::vector<float> gpuVals(numVecs * dim);
+ gpuIndex.reconstruct_n(0, gpuIndex.ntotal, gpuVals.data());
+
+ std::vector<float> cpuVals(numVecs * dim);
+ cpuIndex.reconstruct_n(0, gpuIndex.ntotal, cpuVals.data());
+
+ // The GPU is the source of truth here, so the float32 exact comparison
+ // even if the index uses float16 is ok
+ EXPECT_EQ(gpuVals, cpuVals);
+ }
+}
+
+TEST(TestGpuIndexFlat, CopyTo) {
+ testCopyTo(false);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, CopyTo) {
+ testCopyTo(true);
+}
+#endif
+
+void testUnifiedMemory(bool use_cuvs) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ if (!faiss::gpu::getFullUnifiedMemSupport(device)) {
+ return;
+ }
+
+ int dim = 256;
+
+ // FIXME: GpuIndexFlat doesn't support > 2^31 (vecs * dims) due to
+ // kernel indexing, so we can't test unified memory for memory
+ // oversubscription.
+ size_t numVecs = 50000;
+ int numQuery = 10;
+ int k = 10;
+
+ faiss::IndexFlatL2 cpuIndexL2(dim);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.memorySpace = faiss::gpu::MemorySpace::Unified;
+ config.use_cuvs = use_cuvs;
+
+ faiss::gpu::GpuIndexFlatL2 gpuIndexL2(&res, dim, config);
+
+ std::vector<float> vecs = faiss::gpu::randVecs(numVecs, dim);
+ cpuIndexL2.add(numVecs, vecs.data());
+ gpuIndexL2.add(numVecs, vecs.data());
+
+ // To some extent, we depend upon the relative error for the test
+ // for float16
+ faiss::gpu::compareIndices(
+ cpuIndexL2,
+ gpuIndexL2,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+}
+
+TEST(TestGpuIndexFlat, UnifiedMemory) {
+ testUnifiedMemory(false);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, UnifiedMemory) {
+ testUnifiedMemory(true);
+}
+#endif
+
+void testLargeIndex(bool use_cuvs) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ // Skip this device if we do not have sufficient memory
+ constexpr size_t kMem = size_t(8) * 1024 * 1024 * 1024;
+
+ if (faiss::gpu::getFreeMemory(device) < kMem) {
+ std::cout << "TestGpuIndexFlat.LargeIndex: skipping due "
+ "to insufficient device memory\n";
+ return;
+ }
+
+ std::cout << "Running LargeIndex test\n";
+
+ size_t dim = 256; // each vec is sizeof(float) * 256 = 1 KiB in size
+ size_t nb = 5000000;
+ size_t nq = 10;
+
+ auto xb = faiss::gpu::randVecs(nb, dim);
+
+ int k = 10;
+
+ faiss::IndexFlatL2 cpuIndexL2(dim);
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.use_cuvs = use_cuvs;
+ faiss::gpu::GpuIndexFlatL2 gpuIndexL2(&res, dim, config);
+
+ cpuIndexL2.add(nb, xb.data());
+ gpuIndexL2.add(nb, xb.data());
+
+ // To some extent, we depend upon the relative error for the test
+ // for float16
+ faiss::gpu::compareIndices(
+ cpuIndexL2,
+ gpuIndexL2,
+ nq,
+ dim,
+ k,
+ "LargeIndex",
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+}
+
+TEST(TestGpuIndexFlat, LargeIndex) {
+ testLargeIndex(false);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, LargeIndex) {
+ testLargeIndex(true);
+}
+#endif
+
+void testResidual(bool use_cuvs) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.use_cuvs = use_cuvs;
+
+ int dim = 32;
+ faiss::IndexFlat cpuIndex(dim, faiss::MetricType::METRIC_L2);
+ faiss::gpu::GpuIndexFlat gpuIndex(
+ &res, dim, faiss::MetricType::METRIC_L2, config);
+
+ int numVecs = 100;
+ auto vecs = faiss::gpu::randVecs(numVecs, dim);
+ cpuIndex.add(numVecs, vecs.data());
+ gpuIndex.add(numVecs, vecs.data());
+
+ auto indexVecs = std::vector<faiss::idx_t>{0, 2, 4, 6, 8};
+ auto queryVecs = faiss::gpu::randVecs(indexVecs.size(), dim);
+
+ auto residualsCpu = std::vector<float>(indexVecs.size() * dim);
+ auto residualsGpu = std::vector<float>(indexVecs.size() * dim);
+
+ cpuIndex.compute_residual_n(
+ indexVecs.size(),
+ queryVecs.data(),
+ residualsCpu.data(),
+ indexVecs.data());
+ gpuIndex.compute_residual_n(
+ indexVecs.size(),
+ queryVecs.data(),
+ residualsGpu.data(),
+ indexVecs.data());
+
+ // Should be exactly the same, as this is just a single float32 subtraction
+ EXPECT_EQ(residualsCpu, residualsGpu);
+}
+
+TEST(TestGpuIndexFlat, Residual) {
+ testResidual(false);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, Residual) {
+ testResidual(true);
+}
+#endif
+
+void testReconstruct(bool use_cuvs) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ int dim = 32;
+ int numVecs = 100;
+ auto vecs = faiss::gpu::randVecs(numVecs, dim);
+ auto vecs16 = faiss::gpu::roundToHalf(vecs);
+
+ for (bool useFloat16 : {false, true}) {
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.useFloat16 = useFloat16;
+ config.use_cuvs = use_cuvs;
+
+ faiss::gpu::GpuIndexFlat gpuIndex(
+ &res, dim, faiss::MetricType::METRIC_L2, config);
+
+ gpuIndex.add(numVecs, vecs.data());
+
+ // Test reconstruct
+ {
+ auto reconstructVecs = std::vector<float>(dim);
+ gpuIndex.reconstruct(15, reconstructVecs.data());
+
+ auto& ref = useFloat16 ? vecs16 : vecs;
+
+ for (int i = 0; i < dim; ++i) {
+ EXPECT_EQ(reconstructVecs[i], ref[15 * dim + i]);
+ }
+ }
+
+ // Test reconstruct_n
+ if (false) {
+ auto reconstructVecs = std::vector<float>((numVecs - 1) * dim);
+
+ int startVec = 5;
+ int endVec = numVecs - 1;
+ int numReconstructVec = endVec - startVec + 1;
+
+ gpuIndex.reconstruct_n(
+ startVec, numReconstructVec, reconstructVecs.data());
+
+ auto& ref = useFloat16 ? vecs16 : vecs;
+
+ for (int i = 0; i < numReconstructVec; ++i) {
+ for (int j = 0; j < dim; ++j) {
+ EXPECT_EQ(
+ reconstructVecs[i * dim + j],
+ ref[(i + startVec) * dim + j]);
+ }
+ }
+ }
+
+ // Test reconstruct_batch
+ if (false) {
+ auto reconstructKeys = std::vector<faiss::idx_t>{1, 3, 5};
+ auto reconstructVecs =
+ std::vector<float>(reconstructKeys.size() * dim);
+
+ gpuIndex.reconstruct_batch(
+ reconstructKeys.size(),
+ reconstructKeys.data(),
+ reconstructVecs.data());
+
+ auto& ref = useFloat16 ? vecs16 : vecs;
+
+ for (int i = 0; i < reconstructKeys.size(); ++i) {
+ for (int j = 0; j < dim; ++j) {
+ EXPECT_EQ(
+ reconstructVecs[i * dim + j],
+ ref[reconstructKeys[i] * dim + j]);
+ }
+ }
+ }
+ }
+}
+
+TEST(TestGpuIndexFlat, Reconstruct) {
+ testReconstruct(false);
+}
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, Reconstruct) {
+ testReconstruct(true);
+}
+#endif
+
+void testSearchAndReconstruct(bool use_cuvs) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ size_t dim = 32;
+ size_t nb = 5000;
+ size_t nq = 10;
+ int k = 10;
+
+ auto xb = faiss::gpu::randVecs(nb, dim);
+ auto xq = faiss::gpu::randVecs(nq, dim);
+
+ faiss::IndexFlatL2 cpuIndex(dim);
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = device;
+ config.use_cuvs = use_cuvs;
+ faiss::gpu::GpuIndexFlatL2 gpuIndex(&res, dim, config);
+
+ cpuIndex.add(nb, xb.data());
+ gpuIndex.add(nb, xb.data());
+
+ std::vector<float> refDistance(nq * k, 0);
+ std::vector<faiss::idx_t> refIndices(nq * k, -1);
+ std::vector<float> refReconstruct(nq * k * dim, 0);
+ cpuIndex.search_and_reconstruct(
+ nq,
+ xq.data(),
+ k,
+ refDistance.data(),
+ refIndices.data(),
+ refReconstruct.data());
+
+ std::vector<float> testDistance(nq * k, 0);
+ std::vector<faiss::idx_t> testIndices(nq * k, -1);
+ std::vector<float> testReconstruct(nq * k * dim, 0);
+ gpuIndex.search_and_reconstruct(
+ nq,
+ xq.data(),
+ k,
+ testDistance.data(),
+ testIndices.data(),
+ testReconstruct.data());
+
+ // This handles the search results
+ faiss::gpu::compareLists(
+ refDistance.data(),
+ refIndices.data(),
+ testDistance.data(),
+ testIndices.data(),
+ nq,
+ k,
+ "SearchAndReconstruct",
+ true,
+ false,
+ true,
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+
+ // As the search results may be slightly different (though compareLists
+ // above will ensure a decent number of matches), reconstruction should be
+ // the same for the vectors that do match
+ for (int i = 0; i < nq; ++i) {
+ std::unordered_map<faiss::idx_t, int> refLocation;
+
+ for (int j = 0; j < k; ++j) {
+ refLocation.insert(std::make_pair(refIndices[i * k + j], j));
+ }
+
+ for (int j = 0; j < k; ++j) {
+ auto idx = testIndices[i * k + j];
+ auto it = refLocation.find(idx);
+ if (it != refLocation.end()) {
+ for (int d = 0; d < dim; ++d) {
+ EXPECT_EQ(
+ refReconstruct[(i * k + it->second) * dim + d],
+ testReconstruct[(i * k + j) * dim + d]);
+ }
+ }
+ }
+ }
+}
+TEST(TestGpuIndexFlat, SearchAndReconstruct) {
+ testSearchAndReconstruct(false);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestCuvsGpuIndexFlat, SearchAndReconstruct) {
+ testSearchAndReconstruct(true);
+}
+#endif
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp
new file mode 100644
index 0000000..19f15e5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp
@@ -0,0 +1,919 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2023-2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+#include <cmath>
+#include <sstream>
+#include <vector>
+
+// FIXME: figure out a better way to test fp16
+constexpr float kF16MaxRelErr = 0.3f;
+constexpr float kF32MaxRelErr = 0.03f;
+
+struct Options {
+ Options() {
+ numAdd = 2 * faiss::gpu::randVal(2000, 5000);
+ dim = faiss::gpu::randVal(64, 200);
+
+ numCentroids = std::sqrt((float)numAdd / 2);
+ numTrain = numCentroids * 40;
+ nprobe = faiss::gpu::randVal(std::min(10, numCentroids), numCentroids);
+ numQuery = faiss::gpu::randVal(32, 100);
+
+ // Due to the approximate nature of the query and of floating point
+ // differences between GPU and CPU, to stay within our error bounds,
+ // only use a small k
+ k = std::min(faiss::gpu::randVal(10, 30), numAdd / 40);
+ indicesOpt = faiss::gpu::randSelect(
+ {faiss::gpu::INDICES_CPU,
+ faiss::gpu::INDICES_32_BIT,
+ faiss::gpu::INDICES_64_BIT});
+
+ device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ useCuvs = false;
+ }
+
+ std::string toString() const {
+ std::stringstream str;
+ str << "IVFFlat device " << device << " numVecs " << numAdd << " dim "
+ << dim << " numCentroids " << numCentroids << " nprobe " << nprobe
+ << " numQuery " << numQuery << " k " << k << " indicesOpt "
+ << indicesOpt << " useCuvs " << useCuvs;
+
+ return str.str();
+ }
+
+ int numAdd;
+ int dim;
+ int numCentroids;
+ int numTrain;
+ int nprobe;
+ int numQuery;
+ int k;
+ int device;
+ faiss::gpu::IndicesOptions indicesOpt;
+ bool useCuvs;
+};
+
+void queryTest(
+ Options opt,
+ faiss::MetricType metricType,
+ bool useFloat16CoarseQuantizer) {
+ for (int tries = 0; tries < 2; ++tries) {
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 quantizerL2(opt.dim);
+ faiss::IndexFlatIP quantizerIP(opt.dim);
+ faiss::Index* quantizer = metricType == faiss::METRIC_L2
+ ? (faiss::Index*)&quantizerL2
+ : (faiss::Index*)&quantizerIP;
+
+ faiss::IndexIVFFlat cpuIndex(
+ quantizer, opt.dim, opt.numCentroids, metricType);
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+ cpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions = opt.indicesOpt;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ config.use_cuvs = opt.useCuvs;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, cpuIndex.d, cpuIndex.nlist, cpuIndex.metric_type, config);
+ gpuIndex.copyFrom(&cpuIndex);
+ gpuIndex.nprobe = opt.nprobe;
+
+ bool compFloat16 = useFloat16CoarseQuantizer;
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ compFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ // FIXME: the fp16 bounds are
+ // useless when math (the accumulator) is
+ // in fp16. Figure out another way to test
+ compFloat16 ? 0.70f : 0.1f,
+ compFloat16 ? 0.65f : 0.015f);
+ }
+}
+
+void addTest(
+ faiss::MetricType metricType,
+ bool useFloat16CoarseQuantizer,
+ bool useCuvs) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ opt.useCuvs = useCuvs;
+
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 quantizerL2(opt.dim);
+ faiss::IndexFlatIP quantizerIP(opt.dim);
+ faiss::Index* quantizer = metricType == faiss::METRIC_L2
+ ? (faiss::Index*)&quantizerL2
+ : (faiss::Index*)&quantizerIP;
+
+ faiss::IndexIVFFlat cpuIndex(
+ quantizer, opt.dim, opt.numCentroids, metricType);
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions =
+ opt.useCuvs ? faiss::gpu::INDICES_64_BIT : opt.indicesOpt;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ config.use_cuvs = opt.useCuvs;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, cpuIndex.d, cpuIndex.nlist, cpuIndex.metric_type, config);
+ gpuIndex.copyFrom(&cpuIndex);
+ gpuIndex.nprobe = opt.nprobe;
+
+ cpuIndex.add(opt.numAdd, addVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+
+ bool compFloat16 = useFloat16CoarseQuantizer;
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ compFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ compFloat16 ? 0.70f : 0.1f,
+ compFloat16 ? 0.30f : 0.015f);
+ }
+}
+
+void copyToTest(bool useFloat16CoarseQuantizer, bool useCuvs) {
+ Options opt;
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions =
+ useCuvs ? faiss::gpu::INDICES_64_BIT : opt.indicesOpt;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ config.use_cuvs = useCuvs;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+ gpuIndex.nprobe = opt.nprobe;
+
+ // use garbage values to see if we overwrite then
+ faiss::IndexFlatL2 cpuQuantizer(1);
+ faiss::IndexIVFFlat cpuIndex(&cpuQuantizer, 1, 1, faiss::METRIC_L2);
+ cpuIndex.nprobe = 1;
+
+ gpuIndex.copyTo(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, opt.numAdd);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.quantizer->d, gpuIndex.quantizer->d);
+ EXPECT_EQ(cpuIndex.d, opt.dim);
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.getNumLists());
+ EXPECT_EQ(cpuIndex.nprobe, gpuIndex.nprobe);
+
+ testIVFEquality(cpuIndex, gpuIndex);
+
+ // Query both objects; results should be equivalent
+ bool compFloat16 = useFloat16CoarseQuantizer;
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ compFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ compFloat16 ? 0.70f : 0.1f,
+ compFloat16 ? 0.30f : 0.015f);
+}
+
+void copyFromTest(bool useFloat16CoarseQuantizer, bool useCuvs) {
+ Options opt;
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 cpuQuantizer(opt.dim);
+ faiss::IndexIVFFlat cpuIndex(
+ &cpuQuantizer, opt.dim, opt.numCentroids, faiss::METRIC_L2);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ // use garbage values to see if we overwrite then
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions =
+ useCuvs ? faiss::gpu::INDICES_64_BIT : opt.indicesOpt;
+ config.flatConfig.useFloat16 = useFloat16CoarseQuantizer;
+ config.use_cuvs = useCuvs;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(&res, 1, 1, faiss::METRIC_L2, config);
+ gpuIndex.nprobe = 1;
+
+ gpuIndex.copyFrom(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, opt.numAdd);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.d, opt.dim);
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.getNumLists());
+ EXPECT_EQ(cpuIndex.nprobe, gpuIndex.nprobe);
+
+ testIVFEquality(cpuIndex, gpuIndex);
+
+ // Query both objects; results should be equivalent
+ bool compFloat16 = useFloat16CoarseQuantizer;
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ compFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ compFloat16 ? 0.70f : 0.1f,
+ compFloat16 ? 0.30f : 0.015f);
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_32_Add_L2) {
+ addTest(faiss::METRIC_L2, false, false);
+
+#if defined USE_NVIDIA_CUVS
+ addTest(faiss::METRIC_L2, false, true);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_32_Add_IP) {
+ addTest(faiss::METRIC_INNER_PRODUCT, false, false);
+
+#if defined USE_NVIDIA_CUVS
+ addTest(faiss::METRIC_INNER_PRODUCT, false, true);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float16_32_Add_L2) {
+ addTest(faiss::METRIC_L2, true, false);
+
+#if defined USE_NVIDIA_CUVS
+ addTest(faiss::METRIC_L2, true, true);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float16_32_Add_IP) {
+ addTest(faiss::METRIC_INNER_PRODUCT, true, false);
+
+#if defined USE_NVIDIA_CUVS
+ addTest(faiss::METRIC_INNER_PRODUCT, true, true);
+#endif
+}
+
+//
+// General query tests
+//
+
+TEST(TestGpuIndexIVFFlat, Float32_Query_L2) {
+ Options opt;
+ queryTest(opt, faiss::METRIC_L2, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_L2, false);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_Query_IP) {
+ Options opt;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, false);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, LargeBatch) {
+ Options opt;
+ opt.dim = 3;
+ opt.numQuery = 100000;
+ queryTest(opt, faiss::METRIC_L2, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_L2, false);
+#endif
+}
+
+// float16 coarse quantizer
+
+TEST(TestGpuIndexIVFFlat, Float16_32_Query_L2) {
+ Options opt;
+ queryTest(opt, faiss::METRIC_L2, true);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_L2, true);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float16_32_Query_IP) {
+ Options opt;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, true);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, true);
+#endif
+}
+
+//
+// There are IVF list scanning specializations for 64-d and 128-d that we
+// make sure we explicitly test here
+//
+
+TEST(TestGpuIndexIVFFlat, Float32_Query_L2_64) {
+ Options opt;
+ opt.dim = 64;
+ queryTest(opt, faiss::METRIC_L2, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_L2, false);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_Query_IP_64) {
+ Options opt;
+ opt.dim = 64;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, false);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_Query_L2_128) {
+ Options opt;
+ opt.dim = 128;
+ queryTest(opt, faiss::METRIC_L2, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_L2, false);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_Query_IP_128) {
+ Options opt;
+ opt.dim = 128;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, false);
+
+#if defined USE_NVIDIA_CUVS
+ opt.useCuvs = true;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ queryTest(opt, faiss::METRIC_INNER_PRODUCT, false);
+#endif
+}
+
+//
+// Copy tests
+//
+
+TEST(TestGpuIndexIVFFlat, Float32_32_CopyTo) {
+ copyToTest(false, false);
+
+#if defined USE_NVIDIA_CUVS
+ copyToTest(false, true);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_32_CopyFrom) {
+ copyFromTest(false, false);
+
+#if defined USE_NVIDIA_CUVS
+ copyFromTest(false, true);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Float32_negative) {
+ Options opt;
+
+ auto trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ auto addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ // Put all vecs on negative side
+ for (auto& f : trainVecs) {
+ f = std::abs(f) * -1.0f;
+ }
+
+ for (auto& f : addVecs) {
+ f *= std::abs(f) * -1.0f;
+ }
+
+ faiss::IndexFlatIP quantizerIP(opt.dim);
+ faiss::Index* quantizer = (faiss::Index*)&quantizerIP;
+
+ faiss::IndexIVFFlat cpuIndex(
+ quantizer, opt.dim, opt.numCentroids, faiss::METRIC_INNER_PRODUCT);
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+ cpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ // Construct a positive test set
+ auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim);
+
+ // Put all vecs on positive size
+ for (auto& f : queryVecs) {
+ f = std::abs(f);
+ }
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions = opt.indicesOpt;
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, cpuIndex.d, cpuIndex.nlist, cpuIndex.metric_type, config);
+ gpuIndex.copyFrom(&cpuIndex);
+ gpuIndex.nprobe = opt.nprobe;
+
+ bool compFloat16 = false;
+ faiss::gpu::compareIndices(
+ queryVecs,
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ compFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ // FIXME: the fp16 bounds are
+ // useless when math (the accumulator) is
+ // in fp16. Figure out another way to test
+ compFloat16 ? 0.99f : 0.1f,
+ compFloat16 ? 0.65f : 0.015f);
+
+#if defined USE_NVIDIA_CUVS
+ config.use_cuvs = true;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+
+ faiss::gpu::GpuIndexIVFFlat cuvsGpuIndex(
+ &res, cpuIndex.d, cpuIndex.nlist, cpuIndex.metric_type, config);
+ cuvsGpuIndex.copyFrom(&cpuIndex);
+ cuvsGpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::compareIndices(
+ queryVecs,
+ cpuIndex,
+ cuvsGpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ compFloat16 ? kF16MaxRelErr : kF32MaxRelErr,
+ // FIXME: the fp16 bounds are
+ // useless when math (the accumulator) is
+ // in fp16. Figure out another way to test
+ compFloat16 ? 0.99f : 0.1f,
+ compFloat16 ? 0.65f : 0.015f);
+#endif
+}
+
+//
+// NaN tests
+//
+
+TEST(TestGpuIndexIVFFlat, QueryNaN) {
+ Options opt;
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ int numQuery = 10;
+ std::vector<float> nans(
+ numQuery * opt.dim, std::numeric_limits<float>::quiet_NaN());
+
+ std::vector<float> distances(numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> indices(numQuery * opt.k, 0);
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions = opt.indicesOpt;
+ config.flatConfig.useFloat16 = faiss::gpu::randBool();
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+
+ gpuIndex.search(
+ numQuery, nans.data(), opt.k, distances.data(), indices.data());
+
+ for (int q = 0; q < numQuery; ++q) {
+ for (int k = 0; k < opt.k; ++k) {
+ EXPECT_EQ(indices[q * opt.k + k], -1);
+ EXPECT_EQ(
+ distances[q * opt.k + k],
+ std::numeric_limits<float>::max());
+ }
+ }
+
+#if defined USE_NVIDIA_CUVS
+ config.use_cuvs = true;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+ std::fill(distances.begin(), distances.end(), 0);
+ std::fill(indices.begin(), indices.end(), 0);
+ faiss::gpu::GpuIndexIVFFlat cuvsGpuIndex(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ cuvsGpuIndex.nprobe = opt.nprobe;
+
+ cuvsGpuIndex.train(opt.numTrain, trainVecs.data());
+ cuvsGpuIndex.add(opt.numAdd, addVecs.data());
+
+ cuvsGpuIndex.search(
+ numQuery, nans.data(), opt.k, distances.data(), indices.data());
+
+ for (int q = 0; q < numQuery; ++q) {
+ for (int k = 0; k < opt.k; ++k) {
+ EXPECT_EQ(indices[q * opt.k + k], -1);
+ EXPECT_EQ(
+ distances[q * opt.k + k],
+ std::numeric_limits<float>::max());
+ }
+ }
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, AddNaN) {
+ Options opt;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ int numNans = 10;
+ std::vector<float> nans(
+ numNans * opt.dim, std::numeric_limits<float>::quiet_NaN());
+
+ // Make one vector valid (not the first vector, in order to test offset
+ // issues), which should actually add
+ for (int i = 0; i < opt.dim; ++i) {
+ nans[opt.dim + i] = i;
+ }
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions = opt.indicesOpt;
+ config.flatConfig.useFloat16 = faiss::gpu::randBool();
+ config.use_cuvs = false;
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ gpuIndex.nprobe = opt.nprobe;
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // should not crash
+ EXPECT_EQ(gpuIndex.ntotal, 0);
+ gpuIndex.add(numNans, nans.data());
+
+ std::vector<float> queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim);
+ std::vector<float> distance(opt.numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> indices(opt.numQuery * opt.k, 0);
+
+ // should not crash
+ gpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ distance.data(),
+ indices.data());
+
+#if defined USE_NVIDIA_CUVS
+ config.use_cuvs = true;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+ faiss::gpu::GpuIndexIVFFlat cuvsGpuIndex(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ cuvsGpuIndex.nprobe = opt.nprobe;
+ cuvsGpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // should not crash
+ EXPECT_EQ(cuvsGpuIndex.ntotal, 0);
+ cuvsGpuIndex.add(numNans, nans.data());
+
+ // should not crash
+ cuvsGpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ distance.data(),
+ indices.data());
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, UnifiedMemory) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ if (!faiss::gpu::getFullUnifiedMemSupport(device)) {
+ return;
+ }
+
+ int dim = 128;
+
+ int numCentroids = 256;
+ // Unfortunately it would take forever to add 24 GB in IVFPQ data,
+ // so just perform a small test with data allocated in the unified
+ // memory address space
+ size_t numAdd = 10000;
+ size_t numTrain = numCentroids * 40;
+ int numQuery = 10;
+ int k = 10;
+ int nprobe = 8;
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(numTrain, dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(numAdd, dim);
+
+ faiss::IndexFlatL2 quantizer(dim);
+ faiss::IndexIVFFlat cpuIndex(
+ &quantizer, dim, numCentroids, faiss::METRIC_L2);
+
+ cpuIndex.train(numTrain, trainVecs.data());
+ cpuIndex.add(numAdd, addVecs.data());
+ cpuIndex.nprobe = nprobe;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = device;
+ config.memorySpace = faiss::gpu::MemorySpace::Unified;
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, dim, numCentroids, faiss::METRIC_L2, config);
+ gpuIndex.copyFrom(&cpuIndex);
+ gpuIndex.nprobe = nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+
+#if defined USE_NVIDIA_CUVS
+ config.use_cuvs = true;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+ faiss::gpu::GpuIndexIVFFlat cuvsGpuIndex(
+ &res, dim, numCentroids, faiss::METRIC_L2, config);
+ cuvsGpuIndex.copyFrom(&cpuIndex);
+ cuvsGpuIndex.nprobe = nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ cuvsGpuIndex,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, LongIVFList) {
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ // Skip this device if we do not have sufficient memory
+ constexpr size_t kMem = size_t(24) * 1024 * 1024 * 1024;
+
+ if (faiss::gpu::getFreeMemory(device) < kMem) {
+ std::cout << "TestGpuIndexIVFFlat.LongIVFList: skipping due "
+ "to insufficient device memory\n";
+ return;
+ }
+
+ std::cout << "Running LongIVFList test\n";
+
+ // Test functionality where a single IVF list has more than 2B code values
+ int dim = 64;
+
+ int numCentroids = 1;
+ size_t numAdd = (size_t(1024) * 1024 * 1024 * 2 + 100000) / dim;
+ size_t numTrain = 100;
+ int numQuery = 5;
+ int k = 10;
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(numTrain, dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(numAdd, dim);
+
+ faiss::IndexFlatL2 quantizer(dim);
+ faiss::IndexIVFFlat cpuIndex(
+ &quantizer, dim, numCentroids, faiss::METRIC_L2);
+
+ cpuIndex.train(numTrain, trainVecs.data());
+ cpuIndex.add(numAdd, addVecs.data());
+ cpuIndex.nprobe = 1;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = device;
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, dim, numCentroids, faiss::METRIC_L2, config);
+ gpuIndex.train(numTrain, trainVecs.data());
+ gpuIndex.add(numAdd, addVecs.data());
+ gpuIndex.nprobe = 1;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+
+#if defined USE_NVIDIA_CUVS
+ config.use_cuvs = true;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+ faiss::gpu::GpuIndexIVFFlat cuvsGpuIndex(
+ &res, dim, numCentroids, faiss::METRIC_L2, config);
+ cuvsGpuIndex.train(numTrain, trainVecs.data());
+ cuvsGpuIndex.add(numAdd, addVecs.data());
+ cuvsGpuIndex.nprobe = 1;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ cuvsGpuIndex,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+#endif
+}
+
+TEST(TestGpuIndexIVFFlat, Reconstruct_n) {
+ Options opt;
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 cpuQuantizer(opt.dim);
+ faiss::IndexIVFFlat cpuIndex(
+ &cpuQuantizer, opt.dim, opt.numCentroids, faiss::METRIC_L2);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFFlatConfig config;
+ config.device = opt.device;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+
+ std::vector<float> gpuVals(opt.numAdd * opt.dim);
+
+ gpuIndex.reconstruct_n(0, gpuIndex.ntotal, gpuVals.data());
+
+ std::vector<float> cpuVals(opt.numAdd * opt.dim);
+
+ cpuIndex.reconstruct_n(0, cpuIndex.ntotal, cpuVals.data());
+
+ EXPECT_EQ(gpuVals, cpuVals);
+
+ config.indicesOptions = faiss::gpu::INDICES_32_BIT;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex1(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ gpuIndex1.nprobe = opt.nprobe;
+
+ gpuIndex1.train(opt.numTrain, trainVecs.data());
+ gpuIndex1.add(opt.numAdd, addVecs.data());
+
+ gpuIndex1.reconstruct_n(0, gpuIndex1.ntotal, gpuVals.data());
+
+ EXPECT_EQ(gpuVals, cpuVals);
+
+ config.indicesOptions = faiss::gpu::INDICES_CPU;
+
+ faiss::gpu::GpuIndexIVFFlat gpuIndex2(
+ &res, opt.dim, opt.numCentroids, faiss::METRIC_L2, config);
+ gpuIndex2.nprobe = opt.nprobe;
+
+ gpuIndex2.train(opt.numTrain, trainVecs.data());
+ gpuIndex2.add(opt.numAdd, addVecs.data());
+
+ gpuIndex2.reconstruct_n(0, gpuIndex2.ntotal, gpuVals.data());
+
+ EXPECT_EQ(gpuVals, cpuVals);
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFPQ.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFPQ.cpp
new file mode 100644
index 0000000..cf1af7f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFPQ.cpp
@@ -0,0 +1,887 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+#include <cmath>
+#include <sstream>
+#include <vector>
+
+void pickEncoding(int& codes, int& dim) {
+ std::vector<int> codeSizes{
+ 3, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 96};
+
+ // Above 32 doesn't work with no precomputed codes
+ std::vector<int> dimSizes{4, 8, 10, 12, 16, 20, 24, 28, 32};
+
+ while (true) {
+ codes = codeSizes[faiss::gpu::randVal(0, codeSizes.size() - 1)];
+ dim = codes * dimSizes[faiss::gpu::randVal(0, dimSizes.size() - 1)];
+
+ // for such a small test, super-low or high dim is more likely to
+ // generate comparison errors
+ if (dim < 256 && dim >= 64) {
+ return;
+ }
+ }
+}
+
+void pickCuvsEncoding(int& codes, int& dim, int bitsPerCode) {
+ // Above 32 doesn't work with no precomputed codes
+ std::vector<int> dimSizes{4, 8, 10, 12, 16, 20, 24, 28, 32};
+
+ while (true) {
+ codes = faiss::gpu::randVal(0, 96);
+ dim = codes * dimSizes[faiss::gpu::randVal(0, dimSizes.size() - 1)];
+
+ // for such a small test, super-low or high dim is more likely to
+ // generate comparison errors
+ if (dim < 256 && dim >= 64 && (codes * bitsPerCode) % 8 == 0) {
+ return;
+ }
+ }
+}
+
+struct Options {
+ Options() {
+ numAdd = faiss::gpu::randVal(2000, 5000);
+ numCentroids = std::sqrt((float)numAdd);
+ numTrain = numCentroids * 40;
+
+ pickEncoding(codes, dim);
+
+ // TODO: Change back to `faiss::gpu::randVal(3, 7)` when we
+ // officially support non-multiple of 8 subcodes for IVFPQ.
+ bitsPerCode = 8;
+
+ nprobe = std::min(faiss::gpu::randVal(40, 1000), numCentroids);
+ numQuery = faiss::gpu::randVal(4, 8);
+
+ // Due to the approximate nature of the query and of floating point
+ // differences between GPU and CPU, to stay within our error bounds,
+ // only use a small k
+ k = std::min(faiss::gpu::randVal(5, 20), numAdd / 40);
+ usePrecomputed = faiss::gpu::randBool();
+ indicesOpt = faiss::gpu::randSelect(
+ {faiss::gpu::INDICES_CPU,
+ faiss::gpu::INDICES_32_BIT,
+ faiss::gpu::INDICES_64_BIT});
+ if (codes > 48) {
+ // large codes can only fit using float16
+ useFloat16 = true;
+ } else {
+ useFloat16 = faiss::gpu::randBool();
+ }
+
+ device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ interleavedLayout = false;
+ useCuvs = false;
+ }
+
+ std::string toString() const {
+ std::stringstream str;
+ str << "IVFPQ device " << device << " numVecs " << numAdd << " dim "
+ << dim << " numCentroids " << numCentroids << " codes " << codes
+ << " bitsPerCode " << bitsPerCode << " nprobe " << nprobe
+ << " numQuery " << numQuery << " k " << k << " usePrecomputed "
+ << usePrecomputed << " indicesOpt " << indicesOpt << " useFloat16 "
+ << useFloat16;
+
+ return str.str();
+ }
+
+ float getCompareEpsilon() const {
+ return 0.035f;
+ }
+
+ float getPctMaxDiff1() const {
+ return useFloat16 ? 0.30f : 0.10f;
+ }
+
+ float getPctMaxDiffN() const {
+ return useFloat16 ? 0.05f : 0.02f;
+ }
+
+ int numAdd;
+ int numCentroids;
+ int numTrain;
+ int codes;
+ int dim;
+ int bitsPerCode;
+ int nprobe;
+ int numQuery;
+ int k;
+ bool usePrecomputed;
+ faiss::gpu::IndicesOptions indicesOpt;
+ bool useFloat16;
+ int device;
+ bool interleavedLayout;
+ bool useCuvs;
+};
+
+void queryTest(Options opt, faiss::MetricType metricType) {
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 coarseQuantizerL2(opt.dim);
+ faiss::IndexFlatIP coarseQuantizerIP(opt.dim);
+ faiss::Index* quantizer = metricType == faiss::METRIC_L2
+ ? (faiss::Index*)&coarseQuantizerL2
+ : (faiss::Index*)&coarseQuantizerIP;
+
+ faiss::IndexIVFPQ cpuIndex(
+ quantizer, opt.dim, opt.numCentroids, opt.codes, opt.bitsPerCode);
+ cpuIndex.metric_type = metricType;
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ // Use the default temporary memory management to test the memory
+ // manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = opt.usePrecomputed;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.interleavedLayout = opt.interleavedLayout;
+ config.use_cuvs = opt.useCuvs;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(&res, &cpuIndex, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+}
+
+TEST(TestGpuIndexIVFPQ, Query_L2) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ opt.usePrecomputed = (tries % 2 == 0);
+ queryTest(opt, faiss::MetricType::METRIC_L2);
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, Query_IP) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ queryTest(opt, faiss::MetricType::METRIC_INNER_PRODUCT);
+ }
+}
+
+// Large batch sizes (>= 65536) should also work
+TEST(TestGpuIndexIVFPQ, LargeBatch) {
+ for (bool usePrecomputed : {false, true}) {
+ Options opt;
+
+ // override for large sizes
+ opt.dim = 4;
+ opt.numQuery = 100000;
+ opt.codes = 2;
+ opt.usePrecomputed = usePrecomputed;
+ opt.useFloat16 = false;
+
+ queryTest(opt, faiss::MetricType::METRIC_L2);
+ }
+}
+
+void testMMCodeDistance(faiss::MetricType mt) {
+ // Explicitly test the code distance via batch matrix multiplication route
+ // (even for dimension sizes that would otherwise be handled by the
+ // specialized route (via enabling `useMMCodeDistance`)
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlat coarseQuantizer(opt.dim, mt);
+ faiss::IndexIVFPQ cpuIndex(
+ &coarseQuantizer,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ // Use the default temporary memory management to test the memory
+ // manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = false;
+ config.useMMCodeDistance = true;
+ config.indicesOptions = opt.indicesOpt;
+ config.use_cuvs = false;
+
+ // Make sure that the float16 version works as well
+ config.useFloat16LookupTables = (tries % 2 == 0);
+ config.flatConfig.useFloat16 = (tries % 2 == 1);
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(&res, &cpuIndex, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+ }
+
+ // These sizes are not specialized, they will fall back to the MM version
+ for (int dimPerSubQ : {7, 11}) {
+ Options opt;
+
+ opt.codes = 12;
+ opt.dim = dimPerSubQ * opt.codes;
+
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlat coarseQuantizer(opt.dim, mt);
+ faiss::IndexIVFPQ cpuIndex(
+ &coarseQuantizer,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ // Use the default temporary memory management to test the memory
+ // manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = false;
+ config.indicesOptions = opt.indicesOpt;
+ config.use_cuvs = false;
+
+ // Make sure that the float16 version works as well
+ config.useFloat16LookupTables = (dimPerSubQ == 7);
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(&res, &cpuIndex, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, Query_L2_MMCodeDistance) {
+ testMMCodeDistance(faiss::MetricType::METRIC_L2);
+}
+
+TEST(TestGpuIndexIVFPQ, Query_IP_MMCodeDistance) {
+ testMMCodeDistance(faiss::MetricType::METRIC_INNER_PRODUCT);
+}
+
+TEST(TestGpuIndexIVFPQ, Float16Coarse) {
+ Options opt;
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 coarseQuantizer(opt.dim);
+ faiss::IndexIVFPQ cpuIndex(
+ &coarseQuantizer,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // Use the default temporary memory management to test the memory manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.flatConfig.useFloat16 = true;
+ config.usePrecomputedTables = opt.usePrecomputed;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(&res, &cpuIndex, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ gpuIndex.add(opt.numAdd, addVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+}
+
+void addTest(Options opt, faiss::MetricType metricType) {
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 coarseQuantizerL2(opt.dim);
+ faiss::IndexFlatIP coarseQuantizerIP(opt.dim);
+ faiss::Index* quantizer = metricType == faiss::METRIC_L2
+ ? (faiss::Index*)&coarseQuantizerL2
+ : (faiss::Index*)&coarseQuantizerIP;
+
+ faiss::IndexIVFPQ cpuIndex(
+ quantizer, opt.dim, opt.numCentroids, opt.codes, opt.bitsPerCode);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.metric_type = metricType;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // Use the default temporary memory management to test the memory
+ // manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = opt.usePrecomputed;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.interleavedLayout = opt.interleavedLayout;
+ config.use_cuvs = opt.useCuvs;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(&res, &cpuIndex, config);
+ gpuIndex.nprobe = opt.nprobe;
+
+ gpuIndex.add(opt.numAdd, addVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+}
+
+TEST(TestGpuIndexIVFPQ, Add_L2) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ addTest(opt, faiss::METRIC_L2);
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, Add_IP) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ addTest(opt, faiss::METRIC_INNER_PRODUCT);
+ }
+}
+
+void copyToTest(Options opt) {
+ for (int tries = 0; tries < 2; ++tries) {
+ std::vector<float> trainVecs =
+ faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ // Use the default temporary memory management to test the memory
+ // manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = false;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.interleavedLayout = opt.interleavedLayout;
+ config.use_cuvs = opt.useCuvs;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(
+ &res,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode,
+ faiss::METRIC_L2,
+ config);
+ gpuIndex.nprobe = opt.nprobe;
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+
+ // Use garbage values to see if we overwrite them
+ faiss::IndexFlatL2 cpuQuantizer(1);
+ faiss::IndexIVFPQ cpuIndex(&cpuQuantizer, 1, 1, 1, 1);
+
+ gpuIndex.copyTo(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, opt.numAdd);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.d, opt.dim);
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.getNumLists());
+ EXPECT_EQ(cpuIndex.nprobe, gpuIndex.nprobe);
+ EXPECT_EQ(cpuIndex.pq.M, gpuIndex.getNumSubQuantizers());
+ EXPECT_EQ(gpuIndex.getNumSubQuantizers(), opt.codes);
+ EXPECT_EQ(cpuIndex.pq.nbits, gpuIndex.getBitsPerCode());
+ EXPECT_EQ(gpuIndex.getBitsPerCode(), opt.bitsPerCode);
+
+ testIVFEquality(cpuIndex, gpuIndex);
+
+ // Query both objects; results should be equivalent
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, CopyTo) {
+ Options opt;
+ copyToTest(opt);
+}
+
+void copyFromTest(Options opt) {
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ faiss::IndexFlatL2 coarseQuantizer(opt.dim);
+ faiss::IndexIVFPQ cpuIndex(
+ &coarseQuantizer,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode);
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ // Use the default temporary memory management to test the memory manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = opt.usePrecomputed;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.interleavedLayout = opt.interleavedLayout;
+ config.use_cuvs = opt.useCuvs;
+
+ // Use garbage values to see if we overwrite them
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(
+ &res, 1, 1, 1, 8, faiss::METRIC_L2, config);
+ gpuIndex.nprobe = 1;
+
+ gpuIndex.copyFrom(&cpuIndex);
+
+ // Make sure we are equivalent
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, opt.numAdd);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.d, opt.dim);
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.getNumLists());
+ EXPECT_EQ(cpuIndex.nprobe, gpuIndex.nprobe);
+ EXPECT_EQ(cpuIndex.pq.M, gpuIndex.getNumSubQuantizers());
+ EXPECT_EQ(gpuIndex.getNumSubQuantizers(), opt.codes);
+ EXPECT_EQ(cpuIndex.pq.nbits, gpuIndex.getBitsPerCode());
+ EXPECT_EQ(gpuIndex.getBitsPerCode(), opt.bitsPerCode);
+
+ testIVFEquality(cpuIndex, gpuIndex);
+
+ // Query both objects; results should be equivalent
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ opt.getCompareEpsilon(),
+ opt.getPctMaxDiff1(),
+ opt.getPctMaxDiffN());
+}
+
+TEST(TestGpuIndexIVFPQ, CopyFrom) {
+ Options opt;
+ copyFromTest(opt);
+}
+
+void queryNaNTest(Options opt) {
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(opt.numAdd, opt.dim);
+
+ // Use the default temporary memory management to test the memory manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = opt.usePrecomputed;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.use_cuvs = opt.useCuvs;
+ config.interleavedLayout = opt.useCuvs ? true : opt.interleavedLayout;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(
+ &res,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode,
+ faiss::METRIC_L2,
+ config);
+
+ gpuIndex.nprobe = opt.nprobe;
+
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+
+ int numQuery = 5;
+ std::vector<float> nans(
+ numQuery * opt.dim, std::numeric_limits<float>::quiet_NaN());
+
+ std::vector<float> distances(numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> indices(numQuery * opt.k, 0);
+
+ gpuIndex.search(
+ numQuery, nans.data(), opt.k, distances.data(), indices.data());
+
+ for (int q = 0; q < numQuery; ++q) {
+ for (int k = 0; k < opt.k; ++k) {
+ EXPECT_EQ(indices[q * opt.k + k], -1);
+ EXPECT_EQ(
+ distances[q * opt.k + k],
+ std::numeric_limits<float>::max());
+ }
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, QueryNaN) {
+ Options opt;
+ opt.useCuvs = false;
+ queryNaNTest(opt);
+}
+
+void addNaNTest(Options opt) {
+ // Use the default temporary memory management to test the memory manager
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = opt.device;
+ config.usePrecomputedTables = opt.usePrecomputed;
+ config.indicesOptions = opt.indicesOpt;
+ config.useFloat16LookupTables = opt.useFloat16;
+ config.interleavedLayout = opt.interleavedLayout;
+ config.use_cuvs = opt.useCuvs;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(
+ &res,
+ opt.dim,
+ opt.numCentroids,
+ opt.codes,
+ opt.bitsPerCode,
+ faiss::METRIC_L2,
+ config);
+
+ gpuIndex.nprobe = opt.nprobe;
+
+ int numNans = 10;
+ std::vector<float> nans(
+ numNans * opt.dim, std::numeric_limits<float>::quiet_NaN());
+
+ // Make one vector valid, which should actually add
+ for (int i = 0; i < opt.dim; ++i) {
+ nans[i] = 0.0f;
+ }
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(opt.numTrain, opt.dim);
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+
+ // should not crash
+ EXPECT_EQ(gpuIndex.ntotal, 0);
+ gpuIndex.add(numNans, nans.data());
+
+ std::vector<float> queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim);
+ std::vector<float> distance(opt.numQuery * opt.k, 0);
+ std::vector<faiss::idx_t> indices(opt.numQuery * opt.k, 0);
+
+ // should not crash
+ gpuIndex.search(
+ opt.numQuery,
+ queryVecs.data(),
+ opt.k,
+ distance.data(),
+ indices.data());
+}
+
+TEST(TestGpuIndexIVFPQ, AddNaN) {
+ Options opt;
+ opt.useCuvs = false;
+ addNaNTest(opt);
+}
+
+#if defined USE_NVIDIA_CUVS
+TEST(TestGpuIndexIVFPQ, Query_L2_Cuvs) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ queryTest(opt, faiss::MetricType::METRIC_L2);
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, Query_IP_Cuvs) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ queryTest(opt, faiss::MetricType::METRIC_INNER_PRODUCT);
+ }
+}
+
+// Large batch sizes (>= 65536) should also work
+TEST(TestGpuIndexIVFPQ, LargeBatch_Cuvs) {
+ Options opt;
+
+ // override for large sizes
+ opt.dim = 4;
+ opt.numQuery = 100000;
+ opt.codes = 2;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.usePrecomputed = false;
+ opt.useFloat16 = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ opt.bitsPerCode = 8;
+
+ queryTest(opt, faiss::MetricType::METRIC_L2);
+}
+
+TEST(TestGpuIndexIVFPQ, CopyFrom_Cuvs) {
+ Options opt;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ copyFromTest(opt);
+}
+
+TEST(TestGpuIndexIVFPQ, Add_L2_Cuvs) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ addTest(opt, faiss::METRIC_L2);
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, Add_IP_Cuvs) {
+ for (int tries = 0; tries < 2; ++tries) {
+ Options opt;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ addTest(opt, faiss::METRIC_INNER_PRODUCT);
+ }
+}
+
+TEST(TestGpuIndexIVFPQ, QueryNaN_Cuvs) {
+ Options opt;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ queryNaNTest(opt);
+}
+
+TEST(TestGpuIndexIVFPQ, AddNaN_Cuvs) {
+ Options opt;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ addNaNTest(opt);
+}
+
+TEST(TestGpuIndexIVFPQ, CopyTo_Cuvs) {
+ Options opt;
+ opt.useCuvs = true;
+ opt.interleavedLayout = true;
+ opt.bitsPerCode = faiss::gpu::randVal(4, 8);
+ opt.usePrecomputed = false;
+ opt.indicesOpt = faiss::gpu::INDICES_64_BIT;
+ pickCuvsEncoding(opt.codes, opt.dim, opt.bitsPerCode);
+ copyToTest(opt);
+}
+#endif
+
+TEST(TestGpuIndexIVFPQ, UnifiedMemory) {
+ // Construct on a random device to test multi-device, if we have
+ // multiple devices
+ int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+
+ if (!faiss::gpu::getFullUnifiedMemSupport(device)) {
+ return;
+ }
+
+ int dim = 128;
+
+ int numCentroids = 256;
+ // Unfortunately it would take forever to add 24 GB in IVFPQ data,
+ // so just perform a small test with data allocated in the unified
+ // memory address space
+ size_t numAdd = 10000;
+ size_t numTrain = numCentroids * 40;
+ int numQuery = 10;
+ int k = 10;
+ int nprobe = 8;
+ int codes = 8;
+ int bitsPerCode = 8;
+
+ std::vector<float> trainVecs = faiss::gpu::randVecs(numTrain, dim);
+ std::vector<float> addVecs = faiss::gpu::randVecs(numAdd, dim);
+
+ faiss::IndexFlatL2 quantizer(dim);
+ faiss::IndexIVFPQ cpuIndex(
+ &quantizer, dim, numCentroids, codes, bitsPerCode);
+
+ cpuIndex.train(numTrain, trainVecs.data());
+ cpuIndex.add(numAdd, addVecs.data());
+ cpuIndex.nprobe = nprobe;
+
+ faiss::gpu::StandardGpuResources res;
+ res.noTempMemory();
+
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = device;
+ config.memorySpace = faiss::gpu::MemorySpace::Unified;
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexIVFPQ gpuIndex(
+ &res,
+ dim,
+ numCentroids,
+ codes,
+ bitsPerCode,
+ faiss::METRIC_L2,
+ config);
+ gpuIndex.copyFrom(&cpuIndex);
+ gpuIndex.nprobe = nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ gpuIndex,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ 0.015f,
+ 0.1f,
+ 0.015f);
+
+#if defined USE_NVIDIA_CUVS
+ config.interleavedLayout = true;
+ config.use_cuvs = true;
+ config.indicesOptions = faiss::gpu::INDICES_64_BIT;
+
+ faiss::gpu::GpuIndexIVFPQ cuvsGpuIndex(
+ &res,
+ dim,
+ numCentroids,
+ codes,
+ bitsPerCode,
+ faiss::METRIC_L2,
+ config);
+ cuvsGpuIndex.copyFrom(&cpuIndex);
+ cuvsGpuIndex.nprobe = nprobe;
+
+ faiss::gpu::compareIndices(
+ cpuIndex,
+ cuvsGpuIndex,
+ numQuery,
+ dim,
+ k,
+ "Unified Memory",
+ 0.015f,
+ 0.1f,
+ 0.015f);
+#endif
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFScalarQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFScalarQuantizer.cpp
new file mode 100644
index 0000000..9cb69dc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuIndexIVFScalarQuantizer.cpp
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/gpu/GpuIndexIVFScalarQuantizer.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+#include <cmath>
+#include <sstream>
+#include <vector>
+
+constexpr float kF32MaxRelErr = 0.03f;
+
+struct Options {
+ Options() {
+ numAdd = 2 * faiss::gpu::randVal(2000, 5000);
+ dim = faiss::gpu::randVal(64, 200);
+
+ numCentroids = std::sqrt((float)numAdd / 2);
+ numTrain = numCentroids * 40;
+ nprobe = faiss::gpu::randVal(std::min(10, numCentroids), numCentroids);
+ numQuery = faiss::gpu::randVal(32, 100);
+
+ // Due to the approximate nature of the query and of floating point
+ // differences between GPU and CPU, to stay within our error bounds,
+ // only use a small k
+ k = std::min(faiss::gpu::randVal(10, 30), numAdd / 40);
+ indicesOpt = faiss::gpu::randSelect(
+ {faiss::gpu::INDICES_CPU,
+ faiss::gpu::INDICES_32_BIT,
+ faiss::gpu::INDICES_64_BIT});
+
+ device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+ }
+
+ std::string toString() const {
+ std::stringstream str;
+ str << "IVFFlat device " << device << " numVecs " << numAdd << " dim "
+ << dim << " numCentroids " << numCentroids << " nprobe " << nprobe
+ << " numQuery " << numQuery << " k " << k << " indicesOpt "
+ << indicesOpt;
+
+ return str.str();
+ }
+
+ int numAdd;
+ int dim;
+ int numCentroids;
+ int numTrain;
+ int nprobe;
+ int numQuery;
+ int k;
+ int device;
+ faiss::gpu::IndicesOptions indicesOpt;
+};
+
+void runCopyToTest(faiss::ScalarQuantizer::QuantizerType qtype) {
+ using namespace faiss;
+ using namespace faiss::gpu;
+
+ Options opt;
+ std::vector<float> trainVecs = randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = randVecs(opt.numAdd, opt.dim);
+
+ StandardGpuResources res;
+ res.noTempMemory();
+
+ auto config = GpuIndexIVFScalarQuantizerConfig();
+ config.device = opt.device;
+
+ GpuIndexIVFScalarQuantizer gpuIndex(
+ &res, opt.dim, opt.numCentroids, qtype, METRIC_L2, true, config);
+ gpuIndex.train(opt.numTrain, trainVecs.data());
+ gpuIndex.add(opt.numAdd, addVecs.data());
+ gpuIndex.nprobe = opt.nprobe;
+
+ // use garbage values to see if we overwrite then
+ IndexFlatL2 cpuQuantizer(1);
+ IndexIVFScalarQuantizer cpuIndex(
+ &cpuQuantizer,
+ 1,
+ 1,
+ ScalarQuantizer::QuantizerType::QT_6bit,
+ METRIC_L2);
+ cpuIndex.nprobe = 1;
+
+ gpuIndex.copyTo(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, opt.numAdd);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.quantizer->d, gpuIndex.quantizer->d);
+ EXPECT_EQ(cpuIndex.d, opt.dim);
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.getNumLists());
+ EXPECT_EQ(cpuIndex.nprobe, gpuIndex.nprobe);
+
+ testIVFEquality(cpuIndex, gpuIndex);
+
+ // Query both objects; results should be equivalent
+ compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyTo_fp16) {
+ runCopyToTest(faiss::ScalarQuantizer::QuantizerType::QT_fp16);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyTo_8bit) {
+ runCopyToTest(faiss::ScalarQuantizer::QuantizerType::QT_8bit);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyTo_8bit_uniform) {
+ runCopyToTest(faiss::ScalarQuantizer::QuantizerType::QT_8bit_uniform);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyTo_6bit) {
+ runCopyToTest(faiss::ScalarQuantizer::QuantizerType::QT_6bit);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyTo_4bit) {
+ runCopyToTest(faiss::ScalarQuantizer::QuantizerType::QT_4bit);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyTo_4bit_uniform) {
+ runCopyToTest(faiss::ScalarQuantizer::QuantizerType::QT_4bit_uniform);
+}
+
+void runCopyFromTest(faiss::ScalarQuantizer::QuantizerType qtype) {
+ using namespace faiss;
+ using namespace faiss::gpu;
+
+ Options opt;
+ std::vector<float> trainVecs = randVecs(opt.numTrain, opt.dim);
+ std::vector<float> addVecs = randVecs(opt.numAdd, opt.dim);
+
+ IndexFlatL2 cpuQuantizer(opt.dim);
+ IndexIVFScalarQuantizer cpuIndex(
+ &cpuQuantizer, opt.dim, opt.numCentroids, qtype, METRIC_L2);
+
+ cpuIndex.nprobe = opt.nprobe;
+ cpuIndex.train(opt.numTrain, trainVecs.data());
+ cpuIndex.add(opt.numAdd, addVecs.data());
+
+ // use garbage values to see if we overwrite then
+ StandardGpuResources res;
+ res.noTempMemory();
+
+ auto config = GpuIndexIVFScalarQuantizerConfig();
+ config.device = opt.device;
+
+ GpuIndexIVFScalarQuantizer gpuIndex(
+ &res,
+ 1,
+ 1,
+ ScalarQuantizer::QuantizerType::QT_4bit,
+ METRIC_L2,
+ false,
+ config);
+ gpuIndex.nprobe = 1;
+
+ gpuIndex.copyFrom(&cpuIndex);
+
+ EXPECT_EQ(cpuIndex.ntotal, gpuIndex.ntotal);
+ EXPECT_EQ(gpuIndex.ntotal, opt.numAdd);
+
+ EXPECT_EQ(cpuIndex.d, gpuIndex.d);
+ EXPECT_EQ(cpuIndex.d, opt.dim);
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.getNumLists());
+ EXPECT_EQ(cpuIndex.nprobe, gpuIndex.nprobe);
+
+ testIVFEquality(cpuIndex, gpuIndex);
+
+ // Query both objects; results should be equivalent
+ compareIndices(
+ cpuIndex,
+ gpuIndex,
+ opt.numQuery,
+ opt.dim,
+ opt.k,
+ opt.toString(),
+ kF32MaxRelErr,
+ 0.1f,
+ 0.015f);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyFrom_fp16) {
+ runCopyFromTest(faiss::ScalarQuantizer::QuantizerType::QT_fp16);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyFrom_8bit) {
+ runCopyFromTest(faiss::ScalarQuantizer::QuantizerType::QT_8bit);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyFrom_8bit_uniform) {
+ runCopyFromTest(faiss::ScalarQuantizer::QuantizerType::QT_8bit_uniform);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyFrom_6bit) {
+ runCopyFromTest(faiss::ScalarQuantizer::QuantizerType::QT_6bit);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyFrom_4bit) {
+ runCopyFromTest(faiss::ScalarQuantizer::QuantizerType::QT_4bit);
+}
+
+TEST(TestGpuIndexIVFScalarQuantizer, CopyFrom_4bit_uniform) {
+ runCopyFromTest(faiss::ScalarQuantizer::QuantizerType::QT_4bit_uniform);
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuMemoryException.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuMemoryException.cpp
new file mode 100644
index 0000000..d0f23ac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuMemoryException.cpp
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+
+// Test to see if we can recover after attempting to allocate too much GPU
+// memory
+TEST(TestGpuMemoryException, AddException) {
+ size_t numBrokenAdd = std::numeric_limits<int>::max();
+ size_t numRealAdd = 10000;
+ size_t devFree = 0;
+ size_t devTotal = 0;
+
+ CUDA_VERIFY(cudaMemGetInfo(&devFree, &devTotal));
+
+ // Figure out the dimensionality needed to get at least greater than
+ // devTotal
+ size_t brokenAddDims = ((devTotal / sizeof(float)) / numBrokenAdd) + 1;
+ size_t realAddDims = 128;
+
+ faiss::gpu::StandardGpuResources res;
+
+ faiss::gpu::GpuIndexFlatConfig config;
+ config.device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1);
+ config.use_cuvs = false;
+
+ faiss::gpu::GpuIndexFlatL2 gpuIndexL2Broken(
+ &res, (int)brokenAddDims, config);
+ faiss::gpu::GpuIndexFlatL2 gpuIndexL2(&res, (int)realAddDims, config);
+ faiss::IndexFlatL2 cpuIndex((int)realAddDims);
+
+ // Should throw on attempting to allocate too much data
+ {
+ // allocate memory without initialization
+ auto vecs = std::unique_ptr<float[]>(
+ new float[numBrokenAdd * brokenAddDims]);
+ EXPECT_THROW(
+ gpuIndexL2Broken.add(numBrokenAdd, vecs.get()),
+ faiss::FaissException);
+ }
+
+ // Should be able to add a smaller set of data now
+ {
+ auto vecs = faiss::gpu::randVecs(numRealAdd, realAddDims);
+ EXPECT_NO_THROW(gpuIndexL2.add(numRealAdd, vecs.data()));
+ cpuIndex.add(numRealAdd, vecs.data());
+ }
+
+ // Should throw on attempting to allocate too much data
+ {
+ // allocate memory without initialization
+ auto vecs = std::unique_ptr<float[]>(
+ new float[numBrokenAdd * brokenAddDims]);
+ EXPECT_THROW(
+ gpuIndexL2Broken.add(numBrokenAdd, vecs.get()),
+ faiss::FaissException);
+ }
+
+ // Should be able to query results from what we had before
+ {
+ size_t numQuery = 10;
+ auto vecs = faiss::gpu::randVecs(numQuery, realAddDims);
+ EXPECT_NO_THROW(compareIndices(
+ vecs,
+ cpuIndex,
+ gpuIndexL2,
+ numQuery,
+ realAddDims,
+ 50,
+ "",
+ 6e-3f,
+ 0.1f,
+ 0.015f));
+ }
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuResidualQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuResidualQuantizer.cpp
new file mode 100644
index 0000000..3cb4f7b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuResidualQuantizer.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <gtest/gtest.h>
+
+using namespace ::testing;
+
+float eval_codec(faiss::ResidualQuantizer* q, int nb, float* xb) {
+ // Compute codes
+ uint8_t* codes = new uint8_t[q->code_size * nb];
+ std::cout << "code size: " << q->code_size << std::endl;
+ q->compute_codes(xb, codes, nb);
+ // Decode codes
+ float* decoded = new float[nb * q->d];
+ q->decode(codes, decoded, nb);
+ // Compute reconstruction error
+ float err = 0.0f;
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < q->d; j++) {
+ float diff = xb[i * q->d + j] - decoded[i * q->d + j];
+ err = err + (diff * diff);
+ }
+ }
+ delete[] codes;
+ delete[] decoded;
+ return err;
+}
+
+TEST(TestGpuResidualQuantizer, TestNcall) {
+ int d = 32;
+ int nt = 3000;
+ int nb = 1000;
+ // Assuming get_dataset_2 is a function that returns xt and xb
+ std::vector<float> xt = faiss::gpu::randVecs(nt, d);
+ std::vector<float> xb = faiss::gpu::randVecs(nb, d);
+ faiss::ResidualQuantizer rq0(d, 4, 6);
+ rq0.train(nt, xt.data());
+ float err_rq0 = eval_codec(&rq0, nb, xb.data());
+ faiss::ResidualQuantizer rq1(d, 4, 6);
+ faiss::gpu::GpuProgressiveDimIndexFactory fac(1);
+ rq1.assign_index_factory = &fac;
+ rq1.train(nt, xt.data());
+ ASSERT_GT(fac.ncall, 0);
+ int ncall_train = fac.ncall;
+ float err_rq1 = eval_codec(&rq1, nb, xb.data());
+ ASSERT_GT(fac.ncall, ncall_train);
+ std::cout << "Error RQ0: " << err_rq0 << ", Error RQ1: " << err_rq1
+ << std::endl;
+ ASSERT_TRUE(0.9 * err_rq0 < err_rq1);
+ ASSERT_TRUE(err_rq1 < 1.1 * err_rq0);
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuSelect.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuSelect.cu
new file mode 100644
index 0000000..cb8b7cb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestGpuSelect.cu
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/Index.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <faiss/gpu/utils/BlockSelectKernel.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/WarpSelectKernel.cuh>
+#include <sstream>
+#include <unordered_map>
+#include <vector>
+
+void testForSize(int rows, int cols, int k, bool dir, bool warp) {
+ using namespace faiss;
+ using namespace faiss::gpu;
+
+ StandardGpuResources res;
+
+ std::vector<float> v = randVecs(rows, cols);
+ HostTensor<float, 2, true> hostVal({rows, cols});
+
+ for (int r = 0; r < rows; ++r) {
+ for (int c = 0; c < cols; ++c) {
+ hostVal[r][c] = v[r * cols + c];
+ }
+ }
+
+ // row -> (val -> idx)
+ std::unordered_map<int, std::vector<std::pair<int, float>>>
+ hostOutValAndInd;
+ for (int r = 0; r < rows; ++r) {
+ std::vector<std::pair<int, float>> closest;
+
+ for (int c = 0; c < cols; ++c) {
+ closest.emplace_back(c, (float)hostVal[r][c]);
+ }
+
+ auto dirFalseFn = [](std::pair<int, float>& a,
+ std::pair<int, float>& b) {
+ return a.second < b.second;
+ };
+ auto dirTrueFn = [](std::pair<int, float>& a,
+ std::pair<int, float>& b) {
+ return a.second > b.second;
+ };
+
+ std::sort(closest.begin(), closest.end(), dir ? dirTrueFn : dirFalseFn);
+ hostOutValAndInd.emplace(r, closest);
+ }
+
+ // Select top-k on GPU
+ DeviceTensor<float, 2, true> gpuVal(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, 0),
+ hostVal);
+ DeviceTensor<float, 2, true> gpuOutVal(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, 0),
+ {rows, k});
+ DeviceTensor<idx_t, 2, true> gpuOutInd(
+ res.getResources().get(),
+ makeDevAlloc(AllocType::Other, 0),
+ {rows, k});
+
+ if (warp) {
+ runWarpSelect(gpuVal, gpuOutVal, gpuOutInd, dir, k, 0);
+ } else {
+ runBlockSelect(gpuVal, gpuOutVal, gpuOutInd, dir, k, 0);
+ }
+
+ // Copy back to CPU
+ HostTensor<float, 2, true> outVal(gpuOutVal, 0);
+ HostTensor<idx_t, 2, true> outInd(gpuOutInd, 0);
+
+ for (int r = 0; r < rows; ++r) {
+ std::unordered_map<idx_t, idx_t> seenIndices;
+
+ for (int i = 0; i < k; ++i) {
+ float gpuV = outVal[r][i];
+ float cpuV = hostOutValAndInd[r][i].second;
+
+ EXPECT_EQ(gpuV, cpuV)
+ << "rows " << rows << " cols " << cols << " k " << k
+ << " dir " << dir << " row " << r << " ind " << i;
+
+ // If there are identical elements in a row that should be
+ // within the top-k, then it is possible that the index can
+ // differ, because the order in which the GPU will see the
+ // equivalent values is different than the CPU (and will remain
+ // unspecified, since this is affected by the choice of
+ // k-selection algorithm that we use)
+ idx_t gpuInd = outInd[r][i];
+ idx_t cpuInd = hostOutValAndInd[r][i].first;
+
+ // We should never see duplicate indices, however
+ auto itSeenIndex = seenIndices.find(gpuInd);
+
+ EXPECT_EQ(itSeenIndex, seenIndices.end())
+ << "Row " << r << " user index " << gpuInd
+ << " was seen at both " << itSeenIndex->second << " and "
+ << i;
+
+ seenIndices[gpuInd] = i;
+
+ if (gpuInd != cpuInd) {
+ // Gather the values from the original data via index; the
+ // values should be the same
+ float gpuGatherV = hostVal[r][gpuInd];
+ float cpuGatherV = hostVal[r][cpuInd];
+
+ EXPECT_EQ(gpuGatherV, cpuGatherV)
+ << "rows " << rows << " cols " << cols << " k " << k
+ << " dir " << dir << " row " << r << " ind " << i
+ << " source ind " << gpuInd << " " << cpuInd;
+ }
+ }
+ }
+}
+
+// General test
+TEST(TestGpuSelect, test) {
+ for (int i = 0; i < 10; ++i) {
+ int rows = faiss::gpu::randVal(10, 100);
+ int cols = faiss::gpu::randVal(1, 30000);
+ int k = std::min(cols, faiss::gpu::randVal(1, GPU_MAX_SELECTION_K));
+ bool dir = faiss::gpu::randBool();
+
+ testForSize(rows, cols, k, dir, false);
+ }
+}
+
+// Test for k = 1
+TEST(TestGpuSelect, test1) {
+ for (int i = 0; i < 5; ++i) {
+ int rows = faiss::gpu::randVal(10, 100);
+ int cols = faiss::gpu::randVal(1, 30000);
+ bool dir = faiss::gpu::randBool();
+
+ testForSize(rows, cols, 1, dir, false);
+ }
+}
+
+// Test for where k = #cols exactly (we are returning all the values,
+// just sorted)
+TEST(TestGpuSelect, testExact) {
+ for (int i = 0; i < 5; ++i) {
+ int rows = faiss::gpu::randVal(10, 100);
+ int cols = faiss::gpu::randVal(1, GPU_MAX_SELECTION_K);
+ bool dir = faiss::gpu::randBool();
+
+ testForSize(rows, cols, cols, dir, false);
+ }
+}
+
+// General test
+TEST(TestGpuSelect, testWarp) {
+ for (int i = 0; i < 10; ++i) {
+ int rows = faiss::gpu::randVal(10, 100);
+ int cols = faiss::gpu::randVal(1, 30000);
+ int k = std::min(cols, faiss::gpu::randVal(1, GPU_MAX_SELECTION_K));
+ bool dir = faiss::gpu::randBool();
+
+ testForSize(rows, cols, k, dir, true);
+ }
+}
+
+// Test for k = 1
+TEST(TestGpuSelect, test1Warp) {
+ for (int i = 0; i < 5; ++i) {
+ int rows = faiss::gpu::randVal(10, 100);
+ int cols = faiss::gpu::randVal(1, 30000);
+ bool dir = faiss::gpu::randBool();
+
+ testForSize(rows, cols, 1, dir, true);
+ }
+}
+
+// Test for where k = #cols exactly (we are returning all the values,
+// just sorted)
+TEST(TestGpuSelect, testExactWarp) {
+ for (int i = 0; i < 5; ++i) {
+ int rows = faiss::gpu::randVal(10, 100);
+ int cols = faiss::gpu::randVal(1, GPU_MAX_SELECTION_K);
+ bool dir = faiss::gpu::randBool();
+
+ testForSize(rows, cols, cols, dir, true);
+ }
+}
+
+int main(int argc, char** argv) {
+ testing::InitGoogleTest(&argc, argv);
+
+ // just run with a fixed test seed
+ faiss::gpu::setTestSeed(100);
+
+ return RUN_ALL_TESTS();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestUtils.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestUtils.cpp
new file mode 100644
index 0000000..1357cfc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestUtils.cpp
@@ -0,0 +1,433 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/test/TestUtils.h>
+#include <faiss/utils/random.h>
+#include <gtest/gtest.h>
+#include <time.h>
+#include <cmath>
+#include <set>
+#include <sstream>
+#include <unordered_map>
+
+namespace faiss {
+namespace gpu {
+
+inline float half2float(const unsigned short h) {
+ unsigned int sign = ((static_cast<unsigned int>(h) >> 15U) & 1U);
+ unsigned int exponent = ((static_cast<unsigned int>(h) >> 10U) & 0x1fU);
+ unsigned int mantissa = ((static_cast<unsigned int>(h) & 0x3ffU) << 13U);
+ float f;
+ if (exponent == 0x1fU) { /* NaN or Inf */
+ /* discard sign of a NaN */
+ sign = ((mantissa != 0U) ? (sign >> 1U) : sign);
+ mantissa = ((mantissa != 0U) ? 0x7fffffU : 0U);
+ exponent = 0xffU;
+ } else if (exponent == 0U) { /* Denorm or Zero */
+ if (mantissa != 0U) {
+ unsigned int msb;
+ exponent = 0x71U;
+ do {
+ msb = (mantissa & 0x400000U);
+ mantissa <<= 1U; /* normalize */
+ --exponent;
+ } while (msb == 0U);
+ mantissa &= 0x7fffffU; /* 1.mantissa is implicit */
+ }
+ } else {
+ exponent += 0x70U;
+ }
+ const unsigned int u = ((sign << 31U) | (exponent << 23U) | mantissa);
+ std::memcpy(&f, &u, sizeof(u));
+ return f;
+}
+
+unsigned short float2half(const float f) {
+ unsigned int sign;
+ unsigned int remainder;
+ unsigned int x;
+ unsigned int u;
+ unsigned int result;
+ (void)std::memcpy(&x, &f, sizeof(f));
+
+ u = (x & 0x7fffffffU);
+ sign = ((x >> 16U) & 0x8000U);
+ // NaN/+Inf/-Inf
+ if (u >= 0x7f800000U) {
+ remainder = 0U;
+ result = ((u == 0x7f800000U) ? (sign | 0x7c00U) : 0x7fffU);
+ } else if (u > 0x477fefffU) { // Overflows
+ remainder = 0x80000000U;
+ result = (sign | 0x7bffU);
+ } else if (u >= 0x38800000U) { // Normal numbers
+ remainder = u << 19U;
+ u -= 0x38000000U;
+ result = (sign | (u >> 13U));
+ } else if (u < 0x33000001U) { // +0/-0
+ remainder = u;
+ result = sign;
+ } else { // Denormal numbers
+ const unsigned int exponent = u >> 23U;
+ const unsigned int shift = 0x7eU - exponent;
+ unsigned int mantissa = (u & 0x7fffffU);
+ mantissa |= 0x800000U;
+ remainder = mantissa << (32U - shift);
+ result = (sign | (mantissa >> shift));
+ result &= 0x0000FFFFU;
+ }
+
+ if ((remainder > 0x80000000U) ||
+ ((remainder == 0x80000000U) && ((result & 0x1U) != 0U))) {
+ return static_cast<unsigned short>(result) + 1;
+ } else {
+ return static_cast<unsigned short>(result);
+ }
+}
+
+inline float relativeError(float a, float b) {
+ return std::abs(a - b) / (0.5f * (std::abs(a) + std::abs(b)));
+}
+
+// This seed is also used for the faiss float_rand API; in a test it
+// is all within a single thread, so it is ok
+long s_seed = 1;
+std::mt19937 rng(1);
+std::uniform_int_distribution<> distrib;
+
+void newTestSeed() {
+ struct timespec t;
+ clock_gettime(CLOCK_REALTIME, &t);
+
+ setTestSeed(t.tv_nsec);
+}
+
+void setTestSeed(long seed) {
+ printf("testing with random seed %ld\n", seed);
+
+ rng = std::mt19937(seed);
+ s_seed = seed;
+}
+
+int randVal(int a, int b) {
+ EXPECT_GE(a, 0);
+ EXPECT_LE(a, b);
+
+ return a + (distrib(rng) % (b + 1 - a));
+}
+
+bool randBool() {
+ return randSelect<bool>({true, false});
+}
+
+std::vector<float> randVecs(size_t num, size_t dim) {
+ std::vector<float> v(num * dim);
+
+ faiss::float_rand(v.data(), v.size(), s_seed);
+ // unfortunately we generate separate sets of vectors, and don't
+ // want the same values
+ ++s_seed;
+
+ return v;
+}
+
+std::vector<unsigned char> randBinaryVecs(size_t num, size_t dim) {
+ std::vector<unsigned char> v(num * (dim / 8));
+
+ faiss::byte_rand(v.data(), v.size(), s_seed);
+ // unfortunately we generate separate sets of vectors, and don't
+ // want the same values
+ ++s_seed;
+
+ return v;
+}
+
+std::vector<float> roundToHalf(const std::vector<float>& v) {
+ auto out = std::vector<float>(v.size());
+ for (int i = 0; i < v.size(); ++i) {
+ out[i] = half2float(float2half(v[i]));
+ }
+
+ return out;
+}
+
+void compareIndices(
+ const std::vector<float>& queryVecs,
+ faiss::Index& refIndex,
+ faiss::Index& testIndex,
+ int numQuery,
+ int /*dim*/,
+ int k,
+ const std::string& configMsg,
+ float maxRelativeError,
+ float pctMaxDiff1,
+ float pctMaxDiffN) {
+ // Compare
+ std::vector<float> refDistance(numQuery * k, 0);
+ std::vector<faiss::idx_t> refIndices(numQuery * k, -1);
+ refIndex.search(
+ numQuery,
+ queryVecs.data(),
+ k,
+ refDistance.data(),
+ refIndices.data());
+
+ std::vector<float> testDistance(numQuery * k, 0);
+ std::vector<faiss::idx_t> testIndices(numQuery * k, -1);
+ testIndex.search(
+ numQuery,
+ queryVecs.data(),
+ k,
+ testDistance.data(),
+ testIndices.data());
+
+ faiss::gpu::compareLists(
+ refDistance.data(),
+ refIndices.data(),
+ testDistance.data(),
+ testIndices.data(),
+ numQuery,
+ k,
+ configMsg,
+ true,
+ false,
+ true,
+ maxRelativeError,
+ pctMaxDiff1,
+ pctMaxDiffN);
+}
+
+void compareIndices(
+ faiss::Index& refIndex,
+ faiss::Index& testIndex,
+ int numQuery,
+ int dim,
+ int k,
+ const std::string& configMsg,
+ float maxRelativeError,
+ float pctMaxDiff1,
+ float pctMaxDiffN) {
+ auto queryVecs = faiss::gpu::randVecs(numQuery, dim);
+
+ compareIndices(
+ queryVecs,
+ refIndex,
+ testIndex,
+ numQuery,
+ dim,
+ k,
+ configMsg,
+ maxRelativeError,
+ pctMaxDiff1,
+ pctMaxDiffN);
+}
+
+template <typename T>
+inline T lookup(const T* p, int i, int j, int /*dim1*/, int dim2) {
+ return p[i * dim2 + j];
+}
+
+void compareLists(
+ const float* refDist,
+ const faiss::idx_t* refInd,
+ const float* testDist,
+ const faiss::idx_t* testInd,
+ int dim1,
+ int dim2,
+ const std::string& configMsg,
+ bool printBasicStats,
+ bool printDiffs,
+ bool assertOnErr,
+ float maxRelativeError,
+ float pctMaxDiff1,
+ float pctMaxDiffN) {
+ float maxAbsErr = 0.0f;
+ for (int i = 0; i < dim1 * dim2; ++i) {
+ maxAbsErr = std::max(maxAbsErr, std::abs(refDist[i] - testDist[i]));
+ }
+ int numResults = dim1 * dim2;
+
+ // query -> {index -> result position}
+ std::vector<std::unordered_map<faiss::idx_t, int>> refIndexMap;
+
+ for (int query = 0; query < dim1; ++query) {
+ std::unordered_map<faiss::idx_t, int> indices;
+
+ for (int result = 0; result < dim2; ++result) {
+ indices[lookup(refInd, query, result, dim1, dim2)] = result;
+ }
+
+ refIndexMap.emplace_back(std::move(indices));
+ }
+
+ // See how far off the indices are
+ // Keep track of the difference for each entry
+ std::vector<std::vector<int>> indexDiffs;
+
+ int diff1 = 0; // index differs by 1
+ int diffN = 0; // index differs by >1
+ int diffInf = 0; // index not found in the other
+ int nonUniqueIndices = 0;
+
+ double avgDiff = 0.0;
+ int maxDiff = 0;
+ float maxRelErr = 0.0f;
+
+ for (int query = 0; query < dim1; ++query) {
+ std::vector<int> diffs;
+ std::set<faiss::idx_t> uniqueIndices;
+
+ auto& indices = refIndexMap[query];
+
+ for (int result = 0; result < dim2; ++result) {
+ auto t = lookup(testInd, query, result, dim1, dim2);
+
+ // All indices reported within a query should be unique; this is
+ // a serious error if is otherwise the case.
+ // If -1 is reported (no result due to IVF partitioning or not
+ // enough entries in the index), then duplicates are allowed, but
+ // both the reference and test must have -1 in the same position.
+ if (t == -1) {
+ EXPECT_EQ(lookup(refInd, query, result, dim1, dim2), t);
+ } else {
+ bool uniqueIndex = uniqueIndices.count(t) == 0;
+ if (assertOnErr) {
+ EXPECT_TRUE(uniqueIndex) << configMsg << " " << query << " "
+ << result << " " << t;
+ }
+
+ if (!uniqueIndex) {
+ ++nonUniqueIndices;
+ } else {
+ uniqueIndices.insert(t);
+ }
+
+ auto it = indices.find(t);
+ if (it != indices.end()) {
+ int diff = std::abs(result - it->second);
+ diffs.push_back(diff);
+
+ if (diff == 1) {
+ ++diff1;
+ maxDiff = std::max(diff, maxDiff);
+ } else if (diff > 1) {
+ ++diffN;
+ maxDiff = std::max(diff, maxDiff);
+ }
+
+ avgDiff += (double)diff;
+ } else {
+ ++diffInf;
+ diffs.push_back(-1);
+ // don't count this for maxDiff
+ }
+ }
+
+ auto refD = lookup(refDist, query, result, dim1, dim2);
+ auto testD = lookup(testDist, query, result, dim1, dim2);
+
+ float relErr = relativeError(refD, testD);
+
+ if (assertOnErr) {
+ EXPECT_LE(relErr, maxRelativeError)
+ << configMsg << " (" << query << ", " << result
+ << ") refD: " << refD << " testD: " << testD;
+ }
+
+ maxRelErr = std::max(maxRelErr, relErr);
+ }
+
+ indexDiffs.emplace_back(std::move(diffs));
+ }
+
+ if (assertOnErr) {
+ EXPECT_LE(
+ (float)(diff1 + diffN + diffInf),
+ (float)numResults * pctMaxDiff1)
+ << configMsg;
+
+ // Don't count diffInf because that could be diff1 as far as we
+ // know
+ EXPECT_LE((float)diffN, (float)numResults * pctMaxDiffN) << configMsg;
+ }
+
+ avgDiff /= (double)numResults;
+
+ if (printBasicStats) {
+ if (!configMsg.empty()) {
+ printf("Config\n"
+ "----------------------------\n"
+ "%s\n",
+ configMsg.c_str());
+ }
+
+ printf("Result error and differences\n"
+ "----------------------------\n"
+ "max abs diff %.7f rel diff %.7f\n"
+ "idx diff avg: %.5g max: %d\n"
+ "idx diff of 1: %d (%.3f%% of queries)\n"
+ "idx diff of >1: %d (%.3f%% of queries)\n"
+ "idx diff not found: %d (%.3f%% of queries)"
+ " [typically a last element inversion]\n"
+ "non-unique indices: %d (a serious error if >0)\n",
+ maxAbsErr,
+ maxRelErr,
+ avgDiff,
+ maxDiff,
+ diff1,
+ 100.0f * (float)diff1 / (float)numResults,
+ diffN,
+ 100.0f * (float)diffN / (float)numResults,
+ diffInf,
+ 100.0f * (float)diffInf / (float)numResults,
+ nonUniqueIndices);
+ }
+
+ if (printDiffs) {
+ printf("differences:\n");
+ printf("==================\n");
+ for (int query = 0; query < dim1; ++query) {
+ for (int result = 0; result < dim2; ++result) {
+ long refI = lookup(refInd, query, result, dim1, dim2);
+ long testI = lookup(testInd, query, result, dim1, dim2);
+
+ if (refI != testI) {
+ float refD = lookup(refDist, query, result, dim1, dim2);
+ float testD = lookup(testDist, query, result, dim1, dim2);
+
+ float maxDist = std::max(refD, testD);
+ float delta = std::abs(refD - testD);
+
+ float relErr = delta / maxDist;
+
+ if (refD == testD) {
+ printf("(%d, %d [%d]) (ref %ld tst %ld dist ==)\n",
+ query,
+ result,
+ indexDiffs[query][result],
+ refI,
+ testI);
+ } else {
+ printf("(%d, %d [%d]) (ref %ld tst %ld abs %.8f "
+ "rel %.8f ref %a tst %a)\n",
+ query,
+ result,
+ indexDiffs[query][result],
+ refI,
+ testI,
+ delta,
+ relErr,
+ refD,
+ testD);
+ }
+ }
+ }
+ }
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestUtils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestUtils.h
new file mode 100644
index 0000000..02ef37c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/TestUtils.h
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/invlists/InvertedLists.h>
+#include <gtest/gtest.h>
+#include <cstring>
+#include <initializer_list>
+#include <memory>
+#include <string>
+#include <vector>
+
+namespace faiss {
+namespace gpu {
+
+/// Generates and displays a new seed for the test
+void newTestSeed();
+
+/// Uses an explicit seed for the test
+void setTestSeed(long seed);
+
+/// Returns the relative error in difference between a and b
+/// (|a - b| / (0.5 * (|a| + |b|))
+float relativeError(float a, float b);
+
+/// Generates a random integer in the range [a, b]
+int randVal(int a, int b);
+
+/// Generates a random bool
+bool randBool();
+
+/// Select a random value from the given list of values provided as an
+/// initializer_list
+template <typename T>
+T randSelect(std::initializer_list<T> vals) {
+ FAISS_ASSERT(vals.size() > 0);
+ int sel = randVal(0, vals.size());
+
+ int i = 0;
+ for (auto v : vals) {
+ if (i++ == sel) {
+ return v;
+ }
+ }
+
+ // should not get here
+ return *vals.begin();
+}
+
+/// Generates a collection of random vectors in the range [0, 1]
+std::vector<float> randVecs(size_t num, size_t dim);
+
+/// Generates a collection of random bit vectors
+std::vector<unsigned char> randBinaryVecs(size_t num, size_t dim);
+
+// returns to_fp32(to_fp16(v)); useful in comparing fp16 results on CPU
+std::vector<float> roundToHalf(const std::vector<float>& v);
+
+/// Compare two indices via query for similarity, with a user-specified set of
+/// query vectors
+void compareIndices(
+ const std::vector<float>& queryVecs,
+ faiss::Index& refIndex,
+ faiss::Index& testIndex,
+ int numQuery,
+ int dim,
+ int k,
+ const std::string& configMsg,
+ float maxRelativeError = 6e-5f,
+ float pctMaxDiff1 = 0.1f,
+ float pctMaxDiffN = 0.005f);
+
+/// Compare two indices via query for similarity, generating random query
+/// vectors
+void compareIndices(
+ faiss::Index& refIndex,
+ faiss::Index& testIndex,
+ int numQuery,
+ int dim,
+ int k,
+ const std::string& configMsg,
+ float maxRelativeError = 6e-5f,
+ float pctMaxDiff1 = 0.1f,
+ float pctMaxDiffN = 0.005f);
+
+/// Display specific differences in the two (distance, index) lists
+void compareLists(
+ const float* refDist,
+ const faiss::idx_t* refInd,
+ const float* testDist,
+ const faiss::idx_t* testInd,
+ int dim1,
+ int dim2,
+ const std::string& configMsg,
+ bool printBasicStats,
+ bool printDiffs,
+ bool assertOnErr,
+ float maxRelativeError = 6e-5f,
+ float pctMaxDiff1 = 0.1f,
+ float pctMaxDiffN = 0.005f);
+
+/// Compare IVF lists between a CPU and GPU index
+template <typename A, typename B>
+void testIVFEquality(A& cpuIndex, B& gpuIndex) {
+ // Ensure equality of the inverted lists
+ EXPECT_EQ(cpuIndex.nlist, gpuIndex.nlist);
+
+ for (int i = 0; i < cpuIndex.nlist; ++i) {
+ auto cpuLists = cpuIndex.invlists;
+
+ // Code equality
+ EXPECT_EQ(cpuLists->list_size(i), gpuIndex.getListLength(i));
+ std::vector<uint8_t> cpuCodes(
+ cpuLists->list_size(i) * cpuLists->code_size);
+
+ auto sc = faiss::InvertedLists::ScopedCodes(cpuLists, i);
+ std::memcpy(
+ cpuCodes.data(),
+ sc.get(),
+ cpuLists->list_size(i) * cpuLists->code_size);
+
+ auto gpuCodes = gpuIndex.getListVectorData(i, false);
+ EXPECT_EQ(cpuCodes, gpuCodes);
+
+ // Index equality
+ std::vector<idx_t> cpuIndices(cpuLists->list_size(i));
+
+ auto si = faiss::InvertedLists::ScopedIds(cpuLists, i);
+ std::memcpy(
+ cpuIndices.data(),
+ si.get(),
+ cpuLists->list_size(i) * sizeof(faiss::idx_t));
+ EXPECT_EQ(cpuIndices, gpuIndex.getListIndices(i));
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/demo_ivfpq_indexing_gpu.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/demo_ivfpq_indexing_gpu.cpp
new file mode 100644
index 0000000..596c3f0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/demo_ivfpq_indexing_gpu.cpp
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <sys/time.h>
+
+#include <faiss/gpu/GpuAutoTune.h>
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/index_io.h>
+
+double elapsed() {
+ struct timeval tv;
+ gettimeofday(&tv, nullptr);
+ return tv.tv_sec + tv.tv_usec * 1e-6;
+}
+
+int main() {
+ double t0 = elapsed();
+
+ // dimension of the vectors to index
+ int d = 128;
+
+ // size of the database we plan to index
+ size_t nb = 200 * 1000;
+
+ // make a set of nt training vectors in the unit cube
+ // (could be the database)
+ size_t nt = 100 * 1000;
+
+ int dev_no = 0;
+ /*
+ printf ("[%.3f s] Begin d=%d nb=%ld nt=%nt dev_no=%d\n",
+ elapsed() - t0, d, nb, nt, dev_no);
+ */
+ // a reasonable number of centroids to index nb vectors
+ int ncentroids = int(4 * sqrt(nb));
+
+ faiss::gpu::StandardGpuResources resources;
+
+ // the coarse quantizer should not be dealloced before the index
+ // 4 = nb of bytes per code (d must be a multiple of this)
+ // 8 = nb of bits per sub-code (almost always 8)
+ faiss::gpu::GpuIndexIVFPQConfig config;
+ config.device = dev_no;
+
+ faiss::gpu::GpuIndexIVFPQ index(
+ &resources, d, ncentroids, 4, 8, faiss::METRIC_L2, config);
+
+ std::mt19937 rng;
+
+ { // training
+ printf("[%.3f s] Generating %ld vectors in %dD for training\n",
+ elapsed() - t0,
+ nt,
+ d);
+
+ std::vector<float> trainvecs(nt * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nt * d; i++) {
+ trainvecs[i] = distrib(rng);
+ }
+
+ printf("[%.3f s] Training the index\n", elapsed() - t0);
+ index.verbose = true;
+
+ index.train(nt, trainvecs.data());
+ }
+
+ { // I/O demo
+ const char* outfilename = "/tmp/index_trained.faissindex";
+ printf("[%.3f s] storing the pre-trained index to %s\n",
+ elapsed() - t0,
+ outfilename);
+
+ faiss::Index* cpu_index = faiss::gpu::index_gpu_to_cpu(&index);
+
+ write_index(cpu_index, outfilename);
+
+ delete cpu_index;
+ }
+
+ size_t nq;
+ std::vector<float> queries;
+
+ { // populating the database
+ printf("[%.3f s] Building a dataset of %ld vectors to index\n",
+ elapsed() - t0,
+ nb);
+
+ std::vector<float> database(nb * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+
+ printf("[%.3f s] Adding the vectors to the index\n", elapsed() - t0);
+
+ index.add(nb, database.data());
+
+ printf("[%.3f s] done\n", elapsed() - t0);
+
+ // remember a few elements from the database as queries
+ int i0 = 1234;
+ int i1 = 1243;
+
+ nq = i1 - i0;
+ queries.resize(nq * d);
+ for (int i = i0; i < i1; i++) {
+ for (int j = 0; j < d; j++) {
+ queries[(i - i0) * d + j] = database[i * d + j];
+ }
+ }
+ }
+
+ { // searching the database
+ int k = 5;
+ printf("[%.3f s] Searching the %d nearest neighbors "
+ "of %ld vectors in the index\n",
+ elapsed() - t0,
+ k,
+ nq);
+
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<float> dis(k * nq);
+
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+
+ printf("[%.3f s] Query results (vector ids, then distances):\n",
+ elapsed() - t0);
+
+ for (int i = 0; i < nq; i++) {
+ printf("query %2d: ", i);
+ for (int j = 0; j < k; j++) {
+ printf("%7ld ", nns[j + i * k]);
+ }
+ printf("\n dis: ");
+ for (int j = 0; j < k; j++) {
+ printf("%7g ", dis[j + i * k]);
+ }
+ printf("\n");
+ }
+
+ printf("note that the nearest neighbor is not at "
+ "distance 0 due to quantization errors\n");
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/torch_test_contrib_gpu.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/torch_test_contrib_gpu.py
new file mode 100644
index 0000000..e24e511
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/test/torch_test_contrib_gpu.py
@@ -0,0 +1,509 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import unittest
+import numpy as np
+import faiss
+import faiss.contrib.torch_utils
+
+from faiss.contrib import datasets
+from faiss.contrib.torch import clustering
+
+
+def to_column_major_torch(x):
+ if hasattr(torch, 'contiguous_format'):
+ return x.t().clone(memory_format=torch.contiguous_format).t()
+ else:
+ # was default setting before memory_format was introduced
+ return x.t().clone().t()
+
+def to_column_major_numpy(x):
+ return x.T.copy().T
+
+class TestTorchUtilsGPU(unittest.TestCase):
+ # tests add, search
+ def test_lookup(self):
+ cpu_index = faiss.IndexFlatL2(128)
+
+ # Add to CPU index with np
+ xb_torch = torch.rand(10000, 128)
+ cpu_index.add(xb_torch.numpy())
+
+ # Add to CPU index with torch GPU (should fail)
+ xb_torch_gpu = torch.rand(10000, 128, device=torch.device('cuda', 0), dtype=torch.float32)
+ with self.assertRaises(AssertionError):
+ cpu_index.add(xb_torch_gpu)
+
+ # Add to GPU with torch GPU
+ res = faiss.StandardGpuResources()
+ gpu_index = faiss.GpuIndexFlatL2(res, 128)
+ gpu_index.add(xb_torch.cuda())
+
+ # Search with torch CPU
+ xq_torch_cpu = torch.rand(10, 128, dtype=torch.float32)
+ d_torch_cpu, i_torch_cpu = gpu_index.search(xq_torch_cpu, 10)
+
+ # Search with torch GPU
+ xq_torch_gpu = xq_torch_cpu.cuda()
+ d_torch_gpu, i_torch_gpu = gpu_index.search(xq_torch_gpu, 10)
+ self.assertTrue(d_torch_gpu.is_cuda)
+ self.assertTrue(i_torch_gpu.is_cuda)
+
+ # Should be equivalent
+ self.assertTrue(torch.equal(d_torch_cpu.cuda(), d_torch_gpu))
+ self.assertTrue(torch.equal(i_torch_cpu.cuda(), i_torch_gpu))
+
+ # Search with torch GPU using pre-allocated arrays
+ new_d_torch_gpu = torch.zeros(10, 10, device=torch.device('cuda', 0), dtype=torch.float32)
+ new_i_torch_gpu = torch.zeros(10, 10, device=torch.device('cuda', 0), dtype=torch.int64)
+ gpu_index.search(xq_torch_gpu, 10, new_d_torch_gpu, new_i_torch_gpu)
+
+ self.assertTrue(torch.equal(d_torch_cpu.cuda(), new_d_torch_gpu))
+ self.assertTrue(torch.equal(i_torch_cpu.cuda(), new_i_torch_gpu))
+
+ # Search with numpy CPU
+ xq_np_cpu = xq_torch_cpu.numpy()
+ d_np_cpu, i_np_cpu = gpu_index.search(xq_np_cpu, 10)
+ self.assertEqual(type(d_np_cpu), np.ndarray)
+ self.assertEqual(type(i_np_cpu), np.ndarray)
+
+ self.assertTrue(np.array_equal(d_torch_cpu.numpy(), d_np_cpu))
+ self.assertTrue(np.array_equal(i_torch_cpu.numpy(), i_np_cpu))
+
+ # tests train, add_with_ids
+ def test_train_add_with_ids(self):
+ d = 32
+ nlist = 5
+ res = faiss.StandardGpuResources()
+ res.noTempMemory()
+
+ config = faiss.GpuIndexIVFFlatConfig()
+ # FIXME: triage failure when use_cuvs is set to True (issue #3968)
+ config.use_cuvs = False
+
+ index = faiss.GpuIndexIVFFlat(res, d, nlist, faiss.METRIC_L2, config)
+ xb = torch.rand(1000, d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.train(xb)
+
+ ids = torch.arange(1000, 1000 + xb.shape[0], device=torch.device('cuda', 0), dtype=torch.int64)
+
+ # Test add_with_ids with torch gpu
+ index.add_with_ids(xb, ids)
+ _, I = index.search(xb[10:20], 1)
+ self.assertTrue(torch.equal(I.view(10), ids[10:20]))
+
+ # Test add_with_ids with torch cpu
+ index.reset()
+ xb_cpu = xb.cpu()
+ ids_cpu = ids.cpu()
+
+ index.train(xb_cpu)
+ index.add_with_ids(xb_cpu, ids_cpu)
+ _, I = index.search(xb_cpu[10:20], 1)
+ self.assertTrue(torch.equal(I.view(10), ids_cpu[10:20]))
+
+ # Test add_with_ids with numpy
+ index.reset()
+ xb_np = xb.cpu().numpy()
+ ids_np = ids.cpu().numpy()
+
+ index.train(xb_np)
+ index.add_with_ids(xb_np, ids_np)
+ _, I = index.search(xb_np[10:20], 1)
+ self.assertTrue(np.array_equal(I.reshape(10), ids_np[10:20]))
+
+ # tests reconstruct, reconstruct_n
+ def test_flat_reconstruct(self):
+ d = 32
+ res = faiss.StandardGpuResources()
+ res.noTempMemory()
+ index = faiss.GpuIndexFlatL2(res, d)
+
+ xb = torch.rand(100, d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.add(xb)
+
+ # Test reconstruct with torch gpu (native return)
+ y = index.reconstruct(7)
+ self.assertTrue(y.is_cuda)
+ self.assertTrue(torch.equal(xb[7], y))
+
+ # Test reconstruct with numpy output provided
+ y = np.empty(d, dtype='float32')
+ index.reconstruct(11, y)
+ self.assertTrue(np.array_equal(xb.cpu().numpy()[11], y))
+
+ # Test reconstruct with torch cpu output providesd
+ y = torch.empty(d, dtype=torch.float32)
+ index.reconstruct(12, y)
+ self.assertTrue(torch.equal(xb[12].cpu(), y))
+
+ # Test reconstruct with torch gpu output providesd
+ y = torch.empty(d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.reconstruct(13, y)
+ self.assertTrue(torch.equal(xb[13], y))
+
+ # Test reconstruct_n with torch gpu (native return)
+ y = index.reconstruct_n(10, 10)
+ self.assertTrue(y.is_cuda)
+ self.assertTrue(torch.equal(xb[10:20], y))
+
+ # Test reconstruct with numpy output provided
+ y = np.empty((10, d), dtype='float32')
+ index.reconstruct_n(20, 10, y)
+ self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y))
+
+ # Test reconstruct_n with torch cpu output provided
+ y = torch.empty(10, d, dtype=torch.float32)
+ index.reconstruct_n(40, 10, y)
+ self.assertTrue(torch.equal(xb[40:50].cpu(), y))
+
+ # Test reconstruct_n with torch gpu output provided
+ y = torch.empty(10, d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.reconstruct_n(50, 10, y)
+ self.assertTrue(torch.equal(xb[50:60], y))
+
+ def test_ivfflat_reconstruct(self):
+ d = 32
+ nlist = 5
+ res = faiss.StandardGpuResources()
+ res.noTempMemory()
+ config = faiss.GpuIndexIVFFlatConfig()
+ config.use_cuvs = False
+
+ index = faiss.GpuIndexIVFFlat(res, d, nlist, faiss.METRIC_L2, config)
+
+ xb = torch.rand(100, d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.train(xb)
+ index.add(xb)
+
+ # Test reconstruct_n with torch gpu (native return)
+ y = index.reconstruct_n(10, 10)
+ self.assertTrue(y.is_cuda)
+ self.assertTrue(torch.equal(xb[10:20], y))
+
+ # Test reconstruct with numpy output provided
+ y = np.empty((10, d), dtype='float32')
+ index.reconstruct_n(20, 10, y)
+ self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y))
+
+ # Test reconstruct_n with torch cpu output provided
+ y = torch.empty(10, d, dtype=torch.float32)
+ index.reconstruct_n(40, 10, y)
+ self.assertTrue(torch.equal(xb[40:50].cpu(), y))
+
+ # Test reconstruct_n with torch gpu output provided
+ y = torch.empty(10, d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.reconstruct_n(50, 10, y)
+ self.assertTrue(torch.equal(xb[50:60], y))
+
+ # tests assign
+ def test_assign(self):
+ d = 32
+ res = faiss.StandardGpuResources()
+ res.noTempMemory()
+
+ index = faiss.GpuIndexFlatL2(res, d)
+ xb = torch.rand(10000, d, device=torch.device('cuda', 0), dtype=torch.float32)
+ index.add(xb)
+
+ index_cpu = faiss.IndexFlatL2(d)
+ index.copyTo(index_cpu)
+
+ # Test assign with native gpu output
+ # both input as gpu torch and input as cpu torch
+ xq = torch.rand(10, d, device=torch.device('cuda', 0), dtype=torch.float32)
+
+ labels = index.assign(xq, 5)
+ labels_cpu = index_cpu.assign(xq.cpu(), 5)
+ self.assertTrue(torch.equal(labels.cpu(), labels_cpu))
+
+ # Test assign with np input
+ labels = index.assign(xq.cpu().numpy(), 5)
+ labels_cpu = index_cpu.assign(xq.cpu().numpy(), 5)
+ self.assertTrue(np.array_equal(labels, labels_cpu))
+
+ # Test assign with numpy output provided
+ labels = np.empty((xq.shape[0], 5), dtype='int64')
+ index.assign(xq.cpu().numpy(), 5, labels)
+ self.assertTrue(np.array_equal(labels, labels_cpu))
+
+ # Test assign with torch cpu output provided
+ labels = torch.empty(xq.shape[0], 5, dtype=torch.int64)
+ index.assign(xq.cpu(), 5, labels)
+ labels_cpu = index_cpu.assign(xq.cpu(), 5)
+ self.assertTrue(torch.equal(labels, labels_cpu))
+
+ # tests remove_ids
+ def test_remove_ids(self):
+ # This is not currently implemented on GPU indices
+ return
+
+ # tests range_search
+ def test_range_search(self):
+ # This is not currently implemented on GPU indices
+ return
+
+ # tests search_and_reconstruct
+ def test_search_and_reconstruct(self):
+ # This is not currently implemented on GPU indices
+ return
+
+ # tests sa_encode, sa_decode
+ def test_sa_encode_decode(self):
+ # This is not currently implemented on GPU indices
+ return
+
+class TestTorchUtilsKnnGpu(unittest.TestCase):
+ def test_knn_gpu(self, use_cuvs=False):
+ torch.manual_seed(10)
+ d = 32
+ nb = 1024
+ nq = 10
+ k = 10
+ res = faiss.StandardGpuResources()
+
+ # make GT on torch cpu and test using IndexFlatL2
+ xb = torch.rand(nb, d, dtype=torch.float32)
+ xq = torch.rand(nq, d, dtype=torch.float32)
+
+ index = faiss.IndexFlatL2(d)
+ index.add(xb)
+ gt_D, gt_I = index.search(xq, k)
+
+ # for the GPU, we'll use a non-default stream
+ s = torch.cuda.Stream()
+ with torch.cuda.stream(s):
+ # test numpy inputs
+ xb_np = xb.numpy()
+ xq_np = xq.numpy()
+
+ for xq_row_major in True, False:
+ for xb_row_major in True, False:
+ if not xq_row_major:
+ xq_c = to_column_major_numpy(xq_np)
+ assert not xq_c.flags.contiguous
+ else:
+ xq_c = xq_np
+
+ if not xb_row_major:
+ xb_c = to_column_major_numpy(xb_np)
+ assert not xb_c.flags.contiguous
+ else:
+ xb_c = xb_np
+
+ D, I = faiss.knn_gpu(res, xq_c, xb_c, k, use_cuvs=use_cuvs)
+
+ self.assertTrue(torch.equal(torch.from_numpy(I), gt_I))
+ self.assertLess((torch.from_numpy(D) - gt_D).abs().max(), 1e-4)
+
+ # test torch (cpu, gpu) inputs
+ for is_cuda in True, False:
+ for xq_row_major in True, False:
+ for xb_row_major in True, False:
+
+ if is_cuda:
+ xq_c = xq.cuda()
+ xb_c = xb.cuda()
+ else:
+ # also test torch cpu tensors
+ xq_c = xq
+ xb_c = xb
+
+ if not xq_row_major:
+ xq_c = to_column_major_torch(xq)
+ assert not xq_c.is_contiguous()
+
+ if not xb_row_major:
+ xb_c = to_column_major_torch(xb)
+ assert not xb_c.is_contiguous()
+
+ D, I = faiss.knn_gpu(res, xq_c, xb_c, k, use_cuvs=use_cuvs)
+
+ self.assertTrue(torch.equal(I.cpu(), gt_I))
+ self.assertLess((D.cpu() - gt_D).abs().max(), 1e-4)
+
+ # test on subset
+ try:
+ # This internally uses the current pytorch stream
+ D, I = faiss.knn_gpu(res, xq_c[6:8], xb_c, k, use_cuvs=use_cuvs)
+ except TypeError:
+ if not xq_row_major:
+ # then it is expected
+ continue
+ # otherwise it is an error
+ raise
+
+ self.assertTrue(torch.equal(I.cpu(), gt_I[6:8]))
+ self.assertLess((D.cpu() - gt_D[6:8]).abs().max(), 1e-4)
+
+ @unittest.skipUnless(
+ "CUVS" in faiss.get_compile_options(),
+ "only if CUVS is compiled in")
+ def test_knn_gpu_cuvs(self):
+ self.test_knn_gpu(use_cuvs=True)
+
+ def test_knn_gpu_datatypes(self, use_cuvs=False):
+ torch.manual_seed(10)
+ d = 10
+ nb = 1024
+ nq = 5
+ k = 10
+ res = faiss.StandardGpuResources()
+
+ # make GT on torch cpu and test using IndexFlatL2
+ xb = torch.rand(nb, d, dtype=torch.float32)
+ xq = torch.rand(nq, d, dtype=torch.float32)
+
+ index = faiss.IndexFlatL2(d)
+ index.add(xb)
+ gt_D, gt_I = index.search(xq, k)
+
+ xb_c = xb.cuda().half()
+ xq_c = xq.cuda().half()
+
+ # use i32 output indices
+ D = torch.zeros(nq, k, device=xb_c.device, dtype=torch.float32)
+ I = torch.zeros(nq, k, device=xb_c.device, dtype=torch.int32)
+
+ faiss.knn_gpu(res, xq_c, xb_c, k, D, I, use_cuvs=use_cuvs)
+
+ self.assertTrue(torch.equal(I.long().cpu(), gt_I))
+ self.assertLess((D.float().cpu() - gt_D).abs().max(), 1.5e-3)
+
+ # Test using numpy
+ D = np.zeros((nq, k), dtype=np.float32)
+ I = np.zeros((nq, k), dtype=np.int32)
+
+ xb_c = xb.half().numpy()
+ xq_c = xq.half().numpy()
+
+ faiss.knn_gpu(res, xq_c, xb_c, k, D, I, use_cuvs=use_cuvs)
+
+ self.assertTrue(torch.equal(torch.from_numpy(I).long(), gt_I))
+ self.assertLess((torch.from_numpy(D) - gt_D).abs().max(), 1.5e-3)
+
+
+class TestTorchUtilsPairwiseDistanceGpu(unittest.TestCase):
+ def test_pairwise_distance_gpu(self):
+ torch.manual_seed(10)
+ d = 32
+ k = 100
+ # To compare against IndexFlat, use nb == k
+ nb = k
+ nq = 10
+ res = faiss.StandardGpuResources()
+
+ # make GT on torch cpu and test using IndexFlatL2
+ xb = torch.rand(nb, d, dtype=torch.float32)
+ xq = torch.rand(nq, d, dtype=torch.float32)
+
+ index = faiss.IndexFlatL2(d)
+ index.add(xb)
+ gt_D, _ = index.search(xq, k)
+
+ # for the GPU, we'll use a non-default stream
+ s = torch.cuda.Stream()
+ with torch.cuda.stream(s):
+ # test numpy inputs
+ xb_np = xb.numpy()
+ xq_np = xq.numpy()
+
+ for xq_row_major in True, False:
+ for xb_row_major in True, False:
+ if not xq_row_major:
+ xq_c = to_column_major_numpy(xq_np)
+ assert not xq_c.flags.contiguous
+ else:
+ xq_c = xq_np
+
+ if not xb_row_major:
+ xb_c = to_column_major_numpy(xb_np)
+ assert not xb_c.flags.contiguous
+ else:
+ xb_c = xb_np
+
+ D = faiss.pairwise_distance_gpu(res, xq_c, xb_c)
+
+ # IndexFlat will sort the results, so we need to
+ # do the same on our end
+ D = np.sort(D, axis=1)
+
+ self.assertLess((torch.from_numpy(D) - gt_D).abs().max(), 1e-4)
+
+ # test torch (cpu, gpu) inputs
+ for is_cuda in True, False:
+ for xq_row_major in True, False:
+ for xb_row_major in True, False:
+
+ if is_cuda:
+ xq_c = xq.cuda()
+ xb_c = xb.cuda()
+ else:
+ # also test torch cpu tensors
+ xq_c = xq
+ xb_c = xb
+
+ if not xq_row_major:
+ xq_c = to_column_major_torch(xq)
+ assert not xq_c.is_contiguous()
+
+ if not xb_row_major:
+ xb_c = to_column_major_torch(xb)
+ assert not xb_c.is_contiguous()
+
+ D = faiss.pairwise_distance_gpu(res, xq_c, xb_c)
+
+ # IndexFlat will sort the results, so we need to
+ # do the same on our end
+ D, _ = torch.sort(D, dim=1)
+
+ self.assertLess((D.cpu() - gt_D).abs().max(), 1e-4)
+
+ # test on subset
+ try:
+ # This internally uses the current pytorch stream
+ D = faiss.pairwise_distance_gpu(res, xq_c[4:8], xb_c)
+ except TypeError:
+ if not xq_row_major:
+ # then it is expected
+ continue
+ # otherwise it is an error
+ raise
+
+ # IndexFlat will sort the results, so we need to
+ # do the same on our end
+ print(D)
+ D, _ = torch.sort(D, dim=1)
+
+ self.assertLess((D.cpu() - gt_D[4:8]).abs().max(), 1e-4)
+
+
+class TestClustering(unittest.TestCase):
+
+ def test_python_kmeans(self):
+ """ Test the python implementation of kmeans """
+ ds = datasets.SyntheticDataset(32, 10000, 0, 0)
+ x = ds.get_train()
+
+ # bad distribution to stress-test split code
+ xt = x[:10000].copy()
+ xt[:5000] = x[0]
+
+ # CPU baseline
+ km_ref = faiss.Kmeans(ds.d, 100, niter=10)
+ km_ref.train(xt)
+ err = faiss.knn(xt, km_ref.centroids, 1)[0].sum()
+
+ xt_torch = torch.from_numpy(xt).to("cuda:0")
+ res = faiss.StandardGpuResources()
+ data = clustering.DatasetAssignGPU(res, xt_torch)
+ centroids = clustering.kmeans(100, data, 10)
+ centroids = centroids.cpu().numpy()
+ err2 = faiss.knn(xt, centroids, 1)[0].sum()
+
+ # 33498.332 33380.477
+ print(err, err2)
+ self.assertLess(err2, err * 1.1)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/BlockSelectFloat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/BlockSelectFloat.cu
new file mode 100644
index 0000000..82260f0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/BlockSelectFloat.cu
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// warp Q to thread Q:
+// 1, 1
+// 32, 2
+// 64, 3
+// 128, 3
+// 256, 4
+// 512, 8
+// 1024, 8
+// 2048, 8
+
+BLOCK_SELECT_DECL(float, true, 1);
+BLOCK_SELECT_DECL(float, true, 32);
+BLOCK_SELECT_DECL(float, true, 64);
+BLOCK_SELECT_DECL(float, true, 128);
+BLOCK_SELECT_DECL(float, true, 256);
+BLOCK_SELECT_DECL(float, true, 512);
+BLOCK_SELECT_DECL(float, true, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+BLOCK_SELECT_DECL(float, true, 2048);
+#endif
+
+BLOCK_SELECT_DECL(float, false, 1);
+BLOCK_SELECT_DECL(float, false, 32);
+BLOCK_SELECT_DECL(float, false, 64);
+BLOCK_SELECT_DECL(float, false, 128);
+BLOCK_SELECT_DECL(float, false, 256);
+BLOCK_SELECT_DECL(float, false, 512);
+BLOCK_SELECT_DECL(float, false, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+BLOCK_SELECT_DECL(float, false, 2048);
+#endif
+
+void runBlockSelect(
+ Tensor<float, 2, true>& in,
+ Tensor<float, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ bool dir,
+ int k,
+ cudaStream_t stream) {
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ if (dir) {
+ if (k == 1) {
+ BLOCK_SELECT_CALL(float, true, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ BLOCK_SELECT_CALL(float, true, 32);
+ } else if (k <= 64) {
+ BLOCK_SELECT_CALL(float, true, 64);
+ } else if (k <= 128) {
+ BLOCK_SELECT_CALL(float, true, 128);
+ } else if (k <= 256) {
+ BLOCK_SELECT_CALL(float, true, 256);
+ } else if (k <= 512) {
+ BLOCK_SELECT_CALL(float, true, 512);
+ } else if (k <= 1024) {
+ BLOCK_SELECT_CALL(float, true, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ BLOCK_SELECT_CALL(float, true, 2048);
+#endif
+ }
+ } else {
+ if (k == 1) {
+ BLOCK_SELECT_CALL(float, false, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ BLOCK_SELECT_CALL(float, false, 32);
+ } else if (k <= 64) {
+ BLOCK_SELECT_CALL(float, false, 64);
+ } else if (k <= 128) {
+ BLOCK_SELECT_CALL(float, false, 128);
+ } else if (k <= 256) {
+ BLOCK_SELECT_CALL(float, false, 256);
+ } else if (k <= 512) {
+ BLOCK_SELECT_CALL(float, false, 512);
+ } else if (k <= 1024) {
+ BLOCK_SELECT_CALL(float, false, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ BLOCK_SELECT_CALL(float, false, 2048);
+#endif
+ }
+ }
+}
+
+void runBlockSelectPair(
+ Tensor<float, 2, true>& inK,
+ Tensor<idx_t, 2, true>& inV,
+ Tensor<float, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ bool dir,
+ int k,
+ cudaStream_t stream) {
+ FAISS_ASSERT(k <= GPU_MAX_SELECTION_K);
+
+ if (dir) {
+ if (k == 1) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 32);
+ } else if (k <= 64) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 64);
+ } else if (k <= 128) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 128);
+ } else if (k <= 256) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 256);
+ } else if (k <= 512) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 512);
+ } else if (k <= 1024) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ BLOCK_SELECT_PAIR_CALL(float, true, 2048);
+#endif
+ }
+ } else {
+ if (k == 1) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 32);
+ } else if (k <= 64) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 64);
+ } else if (k <= 128) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 128);
+ } else if (k <= 256) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 256);
+ } else if (k <= 512) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 512);
+ } else if (k <= 1024) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ BLOCK_SELECT_PAIR_CALL(float, false, 2048);
+#endif
+ }
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/BlockSelectKernel.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/BlockSelectKernel.cuh
new file mode 100644
index 0000000..43c1471
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/BlockSelectKernel.cuh
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Select.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename K,
+ typename IndexType,
+ bool Dir,
+ int NumWarpQ,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+__global__ void blockSelect(
+ Tensor<K, 2, true> in,
+ Tensor<K, 2, true> outK,
+ Tensor<IndexType, 2, true> outV,
+ K initK,
+ IndexType initV,
+ int k) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __shared__ K smemK[kNumWarps * NumWarpQ];
+ __shared__ IndexType smemV[kNumWarps * NumWarpQ];
+
+ BlockSelect<
+ K,
+ IndexType,
+ Dir,
+ Comparator<K>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(initK, initV, smemK, smemV, k);
+
+ // Grid is exactly sized to rows available
+ idx_t row = blockIdx.x;
+
+ idx_t i = threadIdx.x;
+ K* inStart = in[row][i].data();
+
+ // Whole warps must participate in the selection
+ idx_t limit = utils::roundDown(in.getSize(1), kWarpSize);
+
+ for (; i < limit; i += ThreadsPerBlock) {
+ heap.add(*inStart, (IndexType)i);
+ inStart += ThreadsPerBlock;
+ }
+
+ // Handle last remainder fraction of a warp of elements
+ if (i < in.getSize(1)) {
+ heap.addThreadQ(*inStart, (IndexType)i);
+ }
+
+ heap.reduce();
+
+ for (int i = threadIdx.x; i < k; i += ThreadsPerBlock) {
+ outK[row][i] = smemK[i];
+ outV[row][i] = smemV[i];
+ }
+ }
+}
+
+template <
+ typename K,
+ typename IndexType,
+ bool Dir,
+ int NumWarpQ,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+__global__ void blockSelectPair(
+ Tensor<K, 2, true> inK,
+ Tensor<IndexType, 2, true> inV,
+ Tensor<K, 2, true> outK,
+ Tensor<IndexType, 2, true> outV,
+ K initK,
+ IndexType initV,
+ int k) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __shared__ K smemK[kNumWarps * NumWarpQ];
+ __shared__ IndexType smemV[kNumWarps * NumWarpQ];
+
+ BlockSelect<
+ K,
+ IndexType,
+ Dir,
+ Comparator<K>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(initK, initV, smemK, smemV, k);
+
+ // Grid is exactly sized to rows available
+ idx_t row = blockIdx.x;
+
+ idx_t i = threadIdx.x;
+ K* inKStart = inK[row][i].data();
+ IndexType* inVStart = inV[row][i].data();
+
+ // Whole warps must participate in the selection
+ idx_t limit = utils::roundDown(inK.getSize(1), (idx_t)kWarpSize);
+
+ for (; i < limit; i += ThreadsPerBlock) {
+ heap.add(*inKStart, *inVStart);
+ inKStart += ThreadsPerBlock;
+ inVStart += ThreadsPerBlock;
+ }
+
+ // Handle last remainder fraction of a warp of elements
+ if (i < inK.getSize(1)) {
+ heap.addThreadQ(*inKStart, *inVStart);
+ }
+
+ heap.reduce();
+
+ for (int i = threadIdx.x; i < k; i += ThreadsPerBlock) {
+ outK[row][i] = smemK[i];
+ outV[row][i] = smemV[i];
+ }
+ }
+}
+
+void runBlockSelect(
+ Tensor<float, 2, true>& in,
+ Tensor<float, 2, true>& outKeys,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool dir,
+ int k,
+ cudaStream_t stream);
+
+void runBlockSelectPair(
+ Tensor<float, 2, true>& inKeys,
+ Tensor<idx_t, 2, true>& inIndices,
+ Tensor<float, 2, true>& outKeys,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool dir,
+ int k,
+ cudaStream_t stream);
+
+void runBlockSelect(
+ Tensor<half, 2, true>& in,
+ Tensor<half, 2, true>& outKeys,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool dir,
+ int k,
+ cudaStream_t stream);
+
+void runBlockSelectPair(
+ Tensor<half, 2, true>& inKeys,
+ Tensor<idx_t, 2, true>& inIndices,
+ Tensor<half, 2, true>& outKeys,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool dir,
+ int k,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Comparators.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Comparators.cuh
new file mode 100644
index 0000000..6144eb2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Comparators.cuh
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/Float16.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+struct Comparator {
+ __device__ static inline bool lt(T a, T b) {
+ return a < b;
+ }
+
+ __device__ static inline bool gt(T a, T b) {
+ return a > b;
+ }
+};
+
+template <>
+struct Comparator<half> {
+ __device__ static inline bool lt(half a, half b) {
+#if FAISS_USE_FULL_FLOAT16
+ return __hlt(a, b);
+#else
+ return __half2float(a) < __half2float(b);
+#endif // FAISS_USE_FULL_FLOAT16
+ }
+
+ __device__ static inline bool gt(half a, half b) {
+#if FAISS_USE_FULL_FLOAT16
+ return __hgt(a, b);
+#else
+ return __half2float(a) > __half2float(b);
+#endif // FAISS_USE_FULL_FLOAT16
+ }
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ConversionOperators.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ConversionOperators.cuh
new file mode 100644
index 0000000..524b6ae
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ConversionOperators.cuh
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/MetricType.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+
+#include <cuda.h>
+#include <thrust/execution_policy.h>
+#include <thrust/transform.h>
+
+namespace faiss {
+namespace gpu {
+
+//
+// Conversion utilities
+//
+
+template <typename T>
+struct ConvertTo {
+ template <typename U>
+ static inline __device__ T to(U v) {
+ return T(v);
+ }
+};
+
+template <>
+struct ConvertTo<float> {
+ static inline __device__ float to(float v) {
+ return v;
+ }
+ static inline __device__ float to(half v) {
+ return __half2float(v);
+ }
+ static inline __device__ float to(__nv_bfloat16 v) {
+ return __bfloat162float(v);
+ }
+};
+
+template <>
+struct ConvertTo<float2> {
+ static inline __device__ float2 to(float2 v) {
+ return v;
+ }
+ static inline __device__ float2 to(half2 v) {
+ return __half22float2(v);
+ }
+};
+
+template <>
+struct ConvertTo<float4> {
+ static inline __device__ float4 to(float4 v) {
+ return v;
+ }
+ static inline __device__ float4 to(Half4 v) {
+ return half4ToFloat4(v);
+ }
+};
+
+template <>
+struct ConvertTo<half> {
+ static inline __device__ half to(float v) {
+ return __float2half(v);
+ }
+ static inline __device__ half to(half v) {
+ return v;
+ }
+};
+
+template <>
+struct ConvertTo<half2> {
+ static inline __device__ half2 to(float2 v) {
+ return __float22half2_rn(v);
+ }
+ static inline __device__ half2 to(half2 v) {
+ return v;
+ }
+};
+
+template <>
+struct ConvertTo<Half4> {
+ static inline __device__ Half4 to(float4 v) {
+ return float4ToHalf4(v);
+ }
+ static inline __device__ Half4 to(Half4 v) {
+ return v;
+ }
+};
+
+template <>
+struct ConvertTo<__nv_bfloat16> {
+ static inline __device__ __nv_bfloat16 to(float v) {
+ return __float2bfloat16(v);
+ }
+ static inline __device__ __nv_bfloat16 to(half v) {
+ return __float2bfloat16(__half2float(v));
+ }
+ static inline __device__ __nv_bfloat16 to(__nv_bfloat16 v) {
+ return v;
+ }
+};
+
+template <typename From, typename To>
+struct Convert {
+ inline __device__ To operator()(From v) const {
+ return ConvertTo<To>::to(v);
+ }
+};
+
+// Tensor conversion
+template <typename From, typename To>
+void runConvert(const From* in, To* out, size_t num, cudaStream_t stream) {
+ thrust::transform(
+ thrust::cuda::par.on(stream),
+ in,
+ in + num,
+ out,
+ Convert<From, To>());
+}
+
+template <typename From, typename To, int Dim>
+void convertTensor(
+ cudaStream_t stream,
+ Tensor<From, Dim, true>& in,
+ Tensor<To, Dim, true>& out) {
+ FAISS_ASSERT(in.numElements() == out.numElements());
+
+ runConvert<From, To>(in.data(), out.data(), in.numElements(), stream);
+}
+
+template <typename From, typename To, int Dim>
+DeviceTensor<To, Dim, true> convertTensorTemporary(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<From, Dim, true>& in) {
+ FAISS_ASSERT(res);
+ DeviceTensor<To, Dim, true> out(
+ res, makeTempAlloc(AllocType::Other, stream), in.sizes());
+
+ convertTensor(stream, in, out);
+ return out;
+}
+
+template <typename From, typename To, int Dim>
+DeviceTensor<To, Dim, true> convertTensorNonTemporary(
+ GpuResources* res,
+ cudaStream_t stream,
+ Tensor<From, Dim, true>& in) {
+ FAISS_ASSERT(res);
+ DeviceTensor<To, Dim, true> out(
+ res, makeDevAlloc(AllocType::Other, stream), in.sizes());
+
+ convertTensor(stream, in, out);
+ return out;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CopyUtils.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CopyUtils.cuh
new file mode 100644
index 0000000..19a07f9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CopyUtils.cuh
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+/// Ensure the memory at `p` is either on the given device, or copy it
+/// to the device in a new temporary allocation.
+template <typename T, int Dim>
+DeviceTensor<T, Dim, true> toDeviceTemporary(
+ GpuResources* resources,
+ int dstDevice,
+ T* src,
+ cudaStream_t stream,
+ std::initializer_list<idx_t> sizes) {
+ int dev = getDeviceForAddress(src);
+ DeviceTensor<T, Dim, true> oldT(src, sizes);
+
+ if (dev == dstDevice) {
+ // On device we expect
+ return oldT;
+ } else {
+ // On different device or on host
+ DeviceScope scope(dstDevice);
+
+ DeviceTensor<T, Dim, true> newT(
+ resources, makeTempAlloc(AllocType::Other, stream), sizes);
+
+ newT.copyFrom(oldT, stream);
+ return newT;
+ }
+}
+
+template <typename T, int Dim>
+DeviceTensor<T, Dim, true> toDeviceNonTemporary(
+ GpuResources* resources,
+ int dstDevice,
+ T* src,
+ cudaStream_t stream,
+ std::initializer_list<idx_t> sizes) {
+ int dev = getDeviceForAddress(src);
+ DeviceTensor<T, Dim, true> oldT(src, sizes);
+
+ if (dev == dstDevice) {
+ // On device we expect
+ return oldT;
+ } else {
+ // On different device or on host
+ DeviceScope scope(dstDevice);
+
+ DeviceTensor<T, Dim, true> newT(
+ resources, makeDevAlloc(AllocType::Other, stream), sizes);
+
+ newT.copyFrom(oldT, stream);
+ return newT;
+ }
+}
+
+template <typename T>
+DeviceTensor<T, 1, true> toDeviceTemporary(
+ GpuResources* resources,
+ const std::vector<T>& src,
+ cudaStream_t stream,
+ int device = -1) {
+ // Uses the current device if device == -1
+ DeviceScope scope(device);
+
+ DeviceTensor<T, 1, true> out(
+ resources,
+ makeTempAlloc(AllocType::Other, stream),
+ {(idx_t)src.size()});
+
+ out.copyFrom(src, stream);
+
+ return out;
+}
+
+/// Copies data to the CPU, if it is not already on the CPU
+template <typename T, int Dim>
+HostTensor<T, Dim, true> toHost(
+ T* src,
+ cudaStream_t stream,
+ std::initializer_list<idx_t> sizes) {
+ int dev = getDeviceForAddress(src);
+
+ if (dev == -1) {
+ // Already on the CPU, just wrap in a HostTensor that doesn't own this
+ // memory
+ return HostTensor<T, Dim, true>(src, sizes);
+ } else {
+ HostTensor<T, Dim, true> out(sizes);
+ Tensor<T, Dim, true> devData(src, sizes);
+ out.copyFrom(devData, stream);
+
+ return out;
+ }
+}
+
+/// Copies a device array's allocation to an address, if necessary
+template <typename T>
+inline void fromDevice(T* src, T* dst, size_t num, cudaStream_t stream) {
+ // It is possible that the array already represents memory at `p`,
+ // in which case no copy is needed
+ if (src == dst) {
+ return;
+ }
+
+ int dev = getDeviceForAddress(dst);
+
+ if (dev == -1) {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ dst, src, num * sizeof(T), cudaMemcpyDeviceToHost, stream));
+ cudaStreamSynchronize(stream);
+ } else {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ dst, src, num * sizeof(T), cudaMemcpyDeviceToDevice, stream));
+ }
+}
+
+/// Copies a device array's allocation to an address, if necessary
+template <typename T, int Dim>
+void fromDevice(Tensor<T, Dim, true>& src, T* dst, cudaStream_t stream) {
+ FAISS_ASSERT(src.isContiguous());
+ fromDevice(src.data(), dst, src.numElements(), stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CuvsUtils.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CuvsUtils.cu
new file mode 100644
index 0000000..1ec3217
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CuvsUtils.cu
@@ -0,0 +1,118 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/utils/CuvsUtils.h>
+#include <raft/core/device_mdarray.hpp>
+#include <raft/core/device_mdspan.hpp>
+#include <raft/linalg/coalesced_reduction.cuh>
+#include <raft/linalg/map.cuh>
+#include <raft/matrix/gather.cuh>
+
+#include <thrust/copy.h>
+#include <thrust/gather.h>
+#include <thrust/reduce.h>
+
+namespace faiss {
+namespace gpu {
+
+void validRowIndices(
+ GpuResources* res,
+ Tensor<float, 2, true>& vecs,
+ bool* validRows) {
+ idx_t n_rows = vecs.getSize(0);
+ idx_t dim = vecs.getSize(1);
+
+ raft::linalg::coalescedReduction(
+ validRows,
+ vecs.data(),
+ dim,
+ n_rows,
+ true,
+ res->getDefaultStreamCurrentDevice(),
+ false,
+ [] __device__(float v, idx_t i) { return isfinite(v); },
+ raft::mul_op());
+}
+
+idx_t inplaceGatherFilteredRows(
+ GpuResources* res,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices) {
+ raft::device_resources& raft_handle = res->getRaftHandleCurrentDevice();
+ idx_t n_rows = vecs.getSize(0);
+ idx_t dim = vecs.getSize(1);
+
+ auto valid_rows =
+ raft::make_device_vector<bool, idx_t>(raft_handle, n_rows);
+
+ validRowIndices(res, vecs, valid_rows.data_handle());
+
+ idx_t n_rows_valid = thrust::reduce(
+ raft_handle.get_thrust_policy(),
+ valid_rows.data_handle(),
+ valid_rows.data_handle() + n_rows,
+ 0);
+
+ if (n_rows_valid < n_rows) {
+ auto gather_indices = raft::make_device_vector<idx_t, idx_t>(
+ raft_handle, n_rows_valid);
+
+ auto count = thrust::make_counting_iterator(0);
+
+ thrust::copy_if(
+ raft_handle.get_thrust_policy(),
+ count,
+ count + n_rows,
+ gather_indices.data_handle(),
+ [valid_rows = valid_rows.data_handle()] __device__(auto i) {
+ return valid_rows[i];
+ });
+
+ raft::matrix::gather(
+ raft_handle,
+ raft::make_device_matrix_view<float, idx_t>(
+ vecs.data(), n_rows, dim),
+ raft::make_const_mdspan(gather_indices.view()),
+ (idx_t)16);
+
+ auto validIndices = raft::make_device_vector<idx_t, idx_t>(
+ raft_handle, n_rows_valid);
+
+ thrust::gather(
+ raft_handle.get_thrust_policy(),
+ gather_indices.data_handle(),
+ gather_indices.data_handle() + gather_indices.size(),
+ indices.data(),
+ validIndices.data_handle());
+ thrust::copy(
+ raft_handle.get_thrust_policy(),
+ validIndices.data_handle(),
+ validIndices.data_handle() + n_rows_valid,
+ indices.data());
+ }
+ return n_rows_valid;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CuvsUtils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CuvsUtils.h
new file mode 100644
index 0000000..e44e5f1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/CuvsUtils.h
@@ -0,0 +1,76 @@
+// @lint-ignore-every LICENSELINT
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ * Copyright (c) 2024, NVIDIA CORPORATION.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <faiss/MetricType.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+#include <cuvs/distance/distance.h>
+
+#pragma GCC visibility push(default)
+namespace faiss {
+namespace gpu {
+
+inline cuvsDistanceType metricFaissToCuvs(
+ MetricType metric,
+ bool exactDistance) {
+ switch (metric) {
+ case MetricType::METRIC_INNER_PRODUCT:
+ return cuvsDistanceType::InnerProduct;
+ case MetricType::METRIC_L2:
+ return cuvsDistanceType::L2Expanded;
+ case MetricType::METRIC_L1:
+ return cuvsDistanceType::L1;
+ case MetricType::METRIC_Linf:
+ return cuvsDistanceType::Linf;
+ case MetricType::METRIC_Lp:
+ return cuvsDistanceType::LpUnexpanded;
+ case MetricType::METRIC_Canberra:
+ return cuvsDistanceType::Canberra;
+ case MetricType::METRIC_BrayCurtis:
+ return cuvsDistanceType::BrayCurtis;
+ case MetricType::METRIC_JensenShannon:
+ return cuvsDistanceType::JensenShannon;
+ default:
+ RAFT_FAIL("Distance type not supported");
+ }
+}
+
+/// Identify matrix rows containing non NaN values. validRows[i] is false if row
+/// i contains a NaN value and true otherwise.
+void validRowIndices(
+ GpuResources* res,
+ Tensor<float, 2, true>& vecs,
+ bool* validRows);
+
+/// Filter out matrix rows containing NaN values. The vectors and indices are
+/// updated in-place.
+idx_t inplaceGatherFilteredRows(
+ GpuResources* res,
+ Tensor<float, 2, true>& vecs,
+ Tensor<idx_t, 1, true>& indices);
+} // namespace gpu
+} // namespace faiss
+#pragma GCC visibility pop
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceDefs.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceDefs.cuh
new file mode 100644
index 0000000..dc4c469
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceDefs.cuh
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+
+namespace faiss {
+namespace gpu {
+
+#ifdef USE_AMD_ROCM
+
+#if __AMDGCN_WAVEFRONT_SIZE == 32u
+constexpr int kWarpSize = 32;
+#else
+constexpr int kWarpSize = 64;
+#endif
+
+// This is a memory barrier for intra-warp writes to shared memory.
+__forceinline__ __device__ void warpFence() {
+ __threadfence_block();
+}
+
+#define GPU_MAX_SELECTION_K 2048
+
+#else // USE_AMD_ROCM
+
+// We require at least CUDA 8.0 for compilation
+#if CUDA_VERSION < 8000
+#error "CUDA >= 8.0 is required"
+#endif
+
+// We validate this against the actual architecture in device initialization
+constexpr int kWarpSize = 32;
+
+// This is a memory barrier for intra-warp writes to shared memory.
+__forceinline__ __device__ void warpFence() {
+#if CUDA_VERSION >= 9000
+ __syncwarp();
+#else
+ // For the time being, assume synchronicity.
+ // __threadfence_block();
+#endif
+}
+
+#if CUDA_VERSION > 9000
+// Based on the CUDA version (we assume what version of nvcc/ptxas we were
+// compiled with), the register allocation algorithm is much better, so only
+// enable the 2048 selection code if we are above 9.0 (9.2 seems to be ok)
+#define GPU_MAX_SELECTION_K 2048
+#else
+#define GPU_MAX_SELECTION_K 1024
+#endif
+
+#endif // USE_AMD_ROCM
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceTensor-inl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceTensor-inl.cuh
new file mode 100644
index 0000000..df51414
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceTensor-inl.cuh
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <utility> // std::move
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor()
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>() {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>() {
+ this->operator=(std::move(t));
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>& DeviceTensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::
+operator=(DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t) {
+ this->Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::operator=(
+ std::move(t));
+
+ this->reservation_ = std::move(t.reservation_);
+ return *this;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::~DeviceTensor() {
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ GpuResources* res,
+ const AllocInfo& info,
+ const IndexT sizes[Dim])
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(nullptr, sizes) {
+ this->reservation_ = std::move(
+ res->allocMemoryHandle(AllocRequest(info, this->getSizeInBytes())));
+ this->data_ = (T*)reservation_.get();
+
+ FAISS_ASSERT(this->data_ || (this->getSizeInBytes() == 0));
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ GpuResources* res,
+ const AllocInfo& info,
+ std::initializer_list<IndexT> sizes)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(nullptr, sizes) {
+ this->reservation_ = std::move(
+ res->allocMemoryHandle(AllocRequest(info, this->getSizeInBytes())));
+ this->data_ = (T*)reservation_.get();
+
+ FAISS_ASSERT(this->data_ || (this->getSizeInBytes() == 0));
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ DataPtrType data,
+ const IndexT sizes[Dim])
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(data, sizes) {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ DataPtrType data,
+ std::initializer_list<IndexT> sizes)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(data, sizes) {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ DataPtrType data,
+ const IndexT sizes[Dim],
+ const IndexT strides[Dim])
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(data, sizes, strides) {
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>::DeviceTensor(
+ GpuResources* res,
+ const AllocInfo& info,
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(
+ nullptr,
+ t.sizes(),
+ t.strides()) {
+ this->reservation_ = std::move(
+ res->allocMemoryHandle(AllocRequest(info, this->getSizeInBytes())));
+ this->data_ = (T*)reservation_.get();
+
+ FAISS_ASSERT(this->data_ || (this->getSizeInBytes() == 0));
+
+ this->copyFrom(t, info.stream);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>& DeviceTensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::zero(cudaStream_t stream) {
+ if (this->data_) {
+ // Region must be contiguous
+ FAISS_ASSERT(this->isContiguous());
+
+ CUDA_VERIFY(cudaMemsetAsync(
+ this->data_, 0, this->getSizeInBytes(), stream));
+ }
+
+ return *this;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceTensor.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceTensor.cuh
new file mode 100644
index 0000000..197570f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceTensor.cuh
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h> // idx_t
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig = false,
+ typename IndexT = idx_t,
+ template <typename U> class PtrTraits = traits::DefaultPtrTraits>
+class DeviceTensor : public Tensor<T, Dim, InnerContig, IndexT, PtrTraits> {
+ public:
+ typedef IndexT IndexType;
+ typedef typename PtrTraits<T>::PtrType DataPtrType;
+
+ /// Default constructor
+ __host__ DeviceTensor();
+
+ /// Destructor
+ __host__ ~DeviceTensor();
+
+ /// Move constructor
+ __host__ DeviceTensor(
+ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t);
+
+ /// Move assignment
+ __host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>& operator=(
+ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t);
+
+ /// Constructs a tensor of the given size, allocating memory for it
+ /// via temporary or other allocation.
+ /// `stream` specifies the stream on which the memory will be used
+ __host__ DeviceTensor(
+ GpuResources* res,
+ const AllocInfo& info,
+ const IndexT sizes[Dim]);
+
+ /// Constructs a tensor of the given size, allocating memory for it
+ /// via temporary or other allocation.
+ /// `stream` specifies the stream on which the memory will be used
+ __host__ DeviceTensor(
+ GpuResources* res,
+ const AllocInfo& info,
+ std::initializer_list<IndexT> sizes);
+
+ /// Constructs a tensor of the given size and stride, referencing a
+ /// memory region we do not own
+ __host__ DeviceTensor(DataPtrType data, const IndexT sizes[Dim]);
+
+ /// Constructs a tensor of the given size and stride, referencing a
+ /// memory region we do not own
+ __host__ DeviceTensor(
+ DataPtrType data,
+ std::initializer_list<IndexT> sizes);
+
+ /// Constructs a tensor of the given size and stride, referencing a
+ /// memory region we do not own
+ __host__ DeviceTensor(
+ DataPtrType data,
+ const IndexT sizes[Dim],
+ const IndexT strides[Dim]);
+
+ /// Copies a tensor into ourselves, allocating memory for it.
+ /// `stream` specifies the stream of the copy and thus the stream on which
+ /// the memory will initially be used.
+ __host__ DeviceTensor(
+ GpuResources* res,
+ const AllocInfo& info,
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t);
+
+ /// Call to zero out memory
+ __host__ DeviceTensor<T, Dim, InnerContig, IndexT, PtrTraits>& zero(
+ cudaStream_t stream);
+
+ private:
+ /// If we own the memory (temporary or non-temporary memory reservation),
+ /// this holds the memory and will release it when we are destroyed
+ GpuMemoryReservation reservation_;
+};
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/utils/DeviceTensor-inl.cuh>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceUtils.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceUtils.cu
new file mode 100644
index 0000000..15036d3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceUtils.cu
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cuda_profiler_api.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <mutex>
+#include <unordered_map>
+
+namespace faiss {
+namespace gpu {
+
+int getCurrentDevice() {
+ int dev = -1;
+ CUDA_VERIFY(cudaGetDevice(&dev));
+ FAISS_ASSERT(dev != -1);
+
+ return dev;
+}
+
+void setCurrentDevice(int device) {
+ CUDA_VERIFY(cudaSetDevice(device));
+}
+
+int getNumDevices() {
+ int numDev = -1;
+ cudaError_t err = cudaGetDeviceCount(&numDev);
+ if (cudaErrorNoDevice == err) {
+ numDev = 0;
+ } else {
+ CUDA_VERIFY(err);
+ }
+ FAISS_ASSERT(numDev != -1);
+
+ return numDev;
+}
+
+void profilerStart() {
+ CUDA_VERIFY(cudaProfilerStart());
+}
+
+void profilerStop() {
+ CUDA_VERIFY(cudaProfilerStop());
+}
+
+void synchronizeAllDevices() {
+ for (int i = 0; i < getNumDevices(); ++i) {
+ DeviceScope scope(i);
+
+ CUDA_VERIFY(cudaDeviceSynchronize());
+ }
+}
+
+const cudaDeviceProp& getDeviceProperties(int device) {
+ static std::mutex mutex;
+ static std::unordered_map<int, cudaDeviceProp> properties;
+
+ std::lock_guard<std::mutex> guard(mutex);
+
+ auto it = properties.find(device);
+ if (it == properties.end()) {
+ cudaDeviceProp prop;
+ CUDA_VERIFY(cudaGetDeviceProperties(&prop, device));
+
+ properties[device] = prop;
+ it = properties.find(device);
+ }
+
+ return it->second;
+}
+
+const cudaDeviceProp& getCurrentDeviceProperties() {
+ return getDeviceProperties(getCurrentDevice());
+}
+
+int getMaxThreads(int device) {
+ return getDeviceProperties(device).maxThreadsPerBlock;
+}
+
+int getMaxThreadsCurrentDevice() {
+ return getMaxThreads(getCurrentDevice());
+}
+
+dim3 getMaxGrid(int device) {
+ auto& prop = getDeviceProperties(device);
+
+ return dim3(prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]);
+}
+
+dim3 getMaxGridCurrentDevice() {
+ return getMaxGrid(getCurrentDevice());
+}
+
+size_t getMaxSharedMemPerBlock(int device) {
+ return getDeviceProperties(device).sharedMemPerBlock;
+}
+
+size_t getMaxSharedMemPerBlockCurrentDevice() {
+ return getMaxSharedMemPerBlock(getCurrentDevice());
+}
+
+int getDeviceForAddress(const void* p) {
+ if (!p) {
+ return -1;
+ }
+
+ cudaPointerAttributes att;
+ cudaError_t err = cudaPointerGetAttributes(&att, p);
+ FAISS_ASSERT_FMT(
+ err == cudaSuccess || err == cudaErrorInvalidValue,
+ "unknown error %d",
+ (int)err);
+
+ if (err == cudaErrorInvalidValue) {
+ // Make sure the current thread error status has been reset
+ err = cudaGetLastError();
+ FAISS_ASSERT_FMT(
+ err == cudaErrorInvalidValue, "unknown error %d", (int)err);
+ return -1;
+ }
+
+#if USE_AMD_ROCM
+ if (att.type != hipMemoryTypeHost &&
+ att.type != hipMemoryTypeUnregistered) {
+ return att.device;
+ } else {
+ return -1;
+ }
+#else
+ // memoryType is deprecated for CUDA 10.0+
+#if CUDA_VERSION < 10000
+ if (att.memoryType == cudaMemoryTypeHost) {
+ return -1;
+ } else {
+ return att.device;
+ }
+#else
+ // FIXME: what to use for managed memory?
+ if (att.type == cudaMemoryTypeDevice) {
+ return att.device;
+ } else {
+ return -1;
+ }
+#endif
+#endif
+}
+
+bool getFullUnifiedMemSupport(int device) {
+ const auto& prop = getDeviceProperties(device);
+ return (prop.major >= 6);
+}
+
+bool getFullUnifiedMemSupportCurrentDevice() {
+ return getFullUnifiedMemSupport(getCurrentDevice());
+}
+
+bool getTensorCoreSupport(int device) {
+ const auto& prop = getDeviceProperties(device);
+ return (prop.major >= 7);
+}
+
+bool getTensorCoreSupportCurrentDevice() {
+ return getTensorCoreSupport(getCurrentDevice());
+}
+
+int getWarpSize(int device) {
+ const auto& prop = getDeviceProperties(device);
+ return prop.warpSize;
+}
+
+int getWarpSizeCurrentDevice() {
+ return getWarpSize(getCurrentDevice());
+}
+
+size_t getFreeMemory(int device) {
+ DeviceScope scope(device);
+
+ size_t free = 0;
+ size_t total = 0;
+
+ CUDA_VERIFY(cudaMemGetInfo(&free, &total));
+
+ return free;
+}
+
+size_t getFreeMemoryCurrentDevice() {
+ size_t free = 0;
+ size_t total = 0;
+
+ CUDA_VERIFY(cudaMemGetInfo(&free, &total));
+
+ return free;
+}
+
+DeviceScope::DeviceScope(int device) {
+ if (device >= 0) {
+ int curDevice = getCurrentDevice();
+
+ if (curDevice != device) {
+ prevDevice_ = curDevice;
+ setCurrentDevice(device);
+ return;
+ }
+ }
+
+ // Otherwise, we keep the current device
+ prevDevice_ = -1;
+}
+
+DeviceScope::~DeviceScope() {
+ if (prevDevice_ != -1) {
+ setCurrentDevice(prevDevice_);
+ }
+}
+
+CublasHandleScope::CublasHandleScope() {
+ auto blasStatus = cublasCreate(&blasHandle_);
+ FAISS_ASSERT(blasStatus == CUBLAS_STATUS_SUCCESS);
+}
+
+CublasHandleScope::~CublasHandleScope() {
+ auto blasStatus = cublasDestroy(blasHandle_);
+ FAISS_ASSERT(blasStatus == CUBLAS_STATUS_SUCCESS);
+}
+
+CudaEvent::CudaEvent(cudaStream_t stream, bool timer) : event_(0) {
+ CUDA_VERIFY(cudaEventCreateWithFlags(
+ &event_, timer ? cudaEventDefault : cudaEventDisableTiming));
+ CUDA_VERIFY(cudaEventRecord(event_, stream));
+}
+
+CudaEvent::CudaEvent(CudaEvent&& event) noexcept
+ : event_(std::move(event.event_)) {
+ event.event_ = 0;
+}
+
+CudaEvent::~CudaEvent() {
+ if (event_) {
+ CUDA_VERIFY(cudaEventDestroy(event_));
+ }
+}
+
+CudaEvent& CudaEvent::operator=(CudaEvent&& event) noexcept {
+ event_ = std::move(event.event_);
+ event.event_ = 0;
+
+ return *this;
+}
+
+void CudaEvent::streamWaitOnEvent(cudaStream_t stream) {
+ CUDA_VERIFY(cudaStreamWaitEvent(stream, event_, 0));
+}
+
+void CudaEvent::cpuWaitOnEvent() {
+ CUDA_VERIFY(cudaEventSynchronize(event_));
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceUtils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceUtils.h
new file mode 100644
index 0000000..edb1b71
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceUtils.h
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cublas_v2.h>
+#include <cuda_runtime.h>
+#include <faiss/impl/FaissAssert.h>
+#include <vector>
+
+namespace faiss {
+namespace gpu {
+
+/// Returns the current thread-local GPU device
+int getCurrentDevice();
+
+/// Sets the current thread-local GPU device
+void setCurrentDevice(int device);
+
+/// Returns the number of available GPU devices
+int getNumDevices();
+
+/// Starts the CUDA profiler (exposed via SWIG)
+void profilerStart();
+
+/// Stops the CUDA profiler (exposed via SWIG)
+void profilerStop();
+
+/// Synchronizes the CPU against all devices (equivalent to
+/// cudaDeviceSynchronize for each device)
+void synchronizeAllDevices();
+
+/// Returns a cached cudaDeviceProp for the given device
+const cudaDeviceProp& getDeviceProperties(int device);
+
+/// Returns the cached cudaDeviceProp for the current device
+const cudaDeviceProp& getCurrentDeviceProperties();
+
+/// Returns the maximum number of threads available for the given GPU
+/// device
+int getMaxThreads(int device);
+
+/// Equivalent to getMaxThreads(getCurrentDevice())
+int getMaxThreadsCurrentDevice();
+
+/// Returns the maximum grid size for the given GPU device
+dim3 getMaxGrid(int device);
+
+/// Equivalent to getMaxGrid(getCurrentDevice())
+dim3 getMaxGridCurrentDevice();
+
+/// Returns the maximum smem available for the given GPU device
+size_t getMaxSharedMemPerBlock(int device);
+
+/// Equivalent to getMaxSharedMemPerBlock(getCurrentDevice())
+size_t getMaxSharedMemPerBlockCurrentDevice();
+
+/// For a given pointer, returns whether or not it is located on
+/// a device (deviceId >= 0) or the host (-1).
+int getDeviceForAddress(const void* p);
+
+/// Does the given device support full unified memory sharing host
+/// memory?
+bool getFullUnifiedMemSupport(int device);
+
+/// Equivalent to getFullUnifiedMemSupport(getCurrentDevice())
+bool getFullUnifiedMemSupportCurrentDevice();
+
+/// Does the given device support tensor core operations?
+bool getTensorCoreSupport(int device);
+
+/// Equivalent to getTensorCoreSupport(getCurrentDevice())
+bool getTensorCoreSupportCurrentDevice();
+
+/// Returns the warp size of the given GPU device
+int getWarpSize(int device);
+
+/// Equivalent to getWarpSize(getCurrentDevice())
+int getWarpSizeCurrentDevice();
+
+/// Returns the amount of currently available memory on the given device
+size_t getFreeMemory(int device);
+
+/// Equivalent to getFreeMemory(getCurrentDevice())
+size_t getFreeMemoryCurrentDevice();
+
+/// RAII object to set the current device, and restore the previous
+/// device upon destruction
+class DeviceScope {
+ public:
+ explicit DeviceScope(int device);
+ ~DeviceScope();
+
+ private:
+ int prevDevice_;
+};
+
+/// RAII object to manage a cublasHandle_t
+class CublasHandleScope {
+ public:
+ CublasHandleScope();
+ ~CublasHandleScope();
+
+ cublasHandle_t get() {
+ return blasHandle_;
+ }
+
+ private:
+ cublasHandle_t blasHandle_;
+};
+
+// RAII object to manage a cudaEvent_t
+class CudaEvent {
+ public:
+ /// Creates an event and records it in this stream
+ explicit CudaEvent(cudaStream_t stream, bool timer = false);
+ CudaEvent(const CudaEvent& event) = delete;
+ CudaEvent(CudaEvent&& event) noexcept;
+ ~CudaEvent();
+
+ inline cudaEvent_t get() {
+ return event_;
+ }
+
+ /// Wait on this event in this stream
+ void streamWaitOnEvent(cudaStream_t stream);
+
+ /// Have the CPU wait for the completion of this event
+ void cpuWaitOnEvent();
+
+ CudaEvent& operator=(CudaEvent&& event) noexcept;
+ CudaEvent& operator=(CudaEvent& event) = delete;
+
+ private:
+ cudaEvent_t event_;
+};
+
+/// Wrapper to test return status of CUDA functions
+#define CUDA_VERIFY(X) \
+ do { \
+ auto err__ = (X); \
+ FAISS_ASSERT_FMT( \
+ err__ == cudaSuccess, \
+ "CUDA error %d %s", \
+ (int)err__, \
+ cudaGetErrorString(err__)); \
+ } while (0)
+
+/// Wrapper to synchronously probe for CUDA errors
+// #define FAISS_GPU_SYNC_ERROR 1
+
+#ifdef FAISS_GPU_SYNC_ERROR
+#define CUDA_TEST_ERROR() \
+ do { \
+ CUDA_VERIFY(cudaDeviceSynchronize()); \
+ } while (0)
+#else
+#define CUDA_TEST_ERROR() \
+ do { \
+ CUDA_VERIFY(cudaGetLastError()); \
+ } while (0)
+#endif
+
+/// Call for a collection of streams to wait on
+template <typename L1, typename L2>
+void streamWaitBase(const L1& listWaiting, const L2& listWaitOn) {
+ // For all the streams we are waiting on, create an event
+ std::vector<cudaEvent_t> events;
+ for (auto& stream : listWaitOn) {
+ cudaEvent_t event;
+ CUDA_VERIFY(cudaEventCreateWithFlags(&event, cudaEventDisableTiming));
+ CUDA_VERIFY(cudaEventRecord(event, stream));
+ events.push_back(event);
+ }
+
+ // For all the streams that are waiting, issue a wait
+ for (auto& stream : listWaiting) {
+ for (auto& event : events) {
+ CUDA_VERIFY(cudaStreamWaitEvent(stream, event, 0));
+ }
+ }
+
+ for (auto& event : events) {
+ CUDA_VERIFY(cudaEventDestroy(event));
+ }
+}
+
+/// These versions allow usage of initializer_list as arguments, since
+/// otherwise {...} doesn't have a type
+template <typename L1>
+void streamWait(const L1& a, const std::initializer_list<cudaStream_t>& b) {
+ streamWaitBase(a, b);
+}
+
+template <typename L2>
+void streamWait(const std::initializer_list<cudaStream_t>& a, const L2& b) {
+ streamWaitBase(a, b);
+}
+
+inline void streamWait(
+ const std::initializer_list<cudaStream_t>& a,
+ const std::initializer_list<cudaStream_t>& b) {
+ streamWaitBase(a, b);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceVector.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceVector.cuh
new file mode 100644
index 0000000..20c58ff
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/DeviceVector.cuh
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <thrust/execution_policy.h>
+#include <thrust/fill.h>
+#include <algorithm>
+#include <vector>
+
+namespace faiss {
+namespace gpu {
+
+// For growing GPU allocations:
+// Below this size, we always round the allocation size up to the next highest
+// power of 2
+constexpr size_t kDeviceVector_2x_Limit = 4 * 1024 * 1024;
+
+// Otherwise, below this size, we always round the allocation size up by a
+// factor of 1.25. Otherwise, all reallocations are exact to the newly requested
+// size.
+constexpr size_t kDeviceVector_1_25x_Limit = 128 * 1024 * 1024;
+
+/// A simple version of thrust::device_vector<T>, but has more control
+/// over streams, whether resize() initializes new space with T() (which we
+/// don't want), and control on how much the reserved space grows by
+/// upon resize/reserve. It is also meant for POD types only.
+///
+/// Any new memory allocated is automatically zeroed before being presented to
+/// the user.
+template <typename T>
+class DeviceVector {
+ public:
+ DeviceVector(GpuResources* res, AllocInfo allocInfo)
+ : num_(0), capacity_(0), res_(res), allocInfo_(allocInfo) {
+ FAISS_ASSERT(res_);
+ }
+
+ ~DeviceVector() {
+ clear();
+ }
+
+ // Clear all allocated memory; reset to zero size
+ void clear() {
+ alloc_.release();
+ num_ = 0;
+ capacity_ = 0;
+ }
+
+ size_t size() const {
+ return num_;
+ }
+ size_t capacity() const {
+ return capacity_;
+ }
+ T* data() {
+ return (T*)alloc_.data;
+ }
+ const T* data() const {
+ return (const T*)alloc_.data;
+ }
+
+ template <typename OutT>
+ std::vector<OutT> copyToHost(cudaStream_t stream) const {
+ FAISS_ASSERT(num_ * sizeof(T) % sizeof(OutT) == 0);
+
+ std::vector<OutT> out((num_ * sizeof(T)) / sizeof(OutT));
+
+ if (num_ > 0) {
+ FAISS_ASSERT(data());
+ CUDA_VERIFY(cudaMemcpyAsync(
+ out.data(),
+ data(),
+ num_ * sizeof(T),
+ cudaMemcpyDeviceToHost,
+ stream));
+ }
+
+ return out;
+ }
+
+ // Returns true if we actually reallocated memory
+ // If `reserveExact` is true, then we reserve only the memory that
+ // we need for what we're appending
+ bool append(
+ const T* d,
+ size_t n,
+ cudaStream_t stream,
+ bool reserveExact = false) {
+ bool mem = false;
+
+ if (n > 0) {
+ size_t reserveSize = num_ + n;
+ if (!reserveExact) {
+ reserveSize = getNewCapacity_(reserveSize);
+ }
+
+ mem = reserve(reserveSize, stream);
+
+ int dev = getDeviceForAddress(d);
+ if (dev == -1) {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ data() + num_,
+ d,
+ n * sizeof(T),
+ cudaMemcpyHostToDevice,
+ stream));
+ } else {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ data() + num_,
+ d,
+ n * sizeof(T),
+ cudaMemcpyDeviceToDevice,
+ stream));
+ }
+ num_ += n;
+ }
+
+ return mem;
+ }
+
+ // Returns true if we actually reallocated memory
+ bool resize(size_t newSize, cudaStream_t stream) {
+ bool mem = false;
+
+ if (newSize > capacity_) {
+ mem = reserve(getNewCapacity_(newSize), stream);
+ }
+
+ // Don't bother zero initializing the newly accessible memory
+ // (unlike thrust::device_vector)
+ num_ = newSize;
+
+ return mem;
+ }
+
+ // Set all entries in the vector to `value`
+ void setAll(const T& value, cudaStream_t stream) {
+ if (num_ > 0) {
+ thrust::fill(
+ thrust::cuda::par.on(stream), data(), data() + num_, value);
+ }
+ }
+
+ // Set the specific value at a given index to `value`
+ void setAt(size_t idx, const T& value, cudaStream_t stream) {
+ FAISS_ASSERT(idx < num_);
+ CUDA_VERIFY(cudaMemcpyAsync(
+ data() + idx,
+ &value,
+ sizeof(T),
+ cudaMemcpyHostToDevice,
+ stream));
+ }
+
+ // Copy a specific value at a given index to the host
+ T getAt(size_t idx, cudaStream_t stream) {
+ FAISS_ASSERT(idx < num_);
+
+ T out;
+ CUDA_VERIFY(cudaMemcpyAsync(
+ &out, data() + idx, sizeof(T), cudaMemcpyDeviceToHost, stream));
+
+ return out;
+ }
+
+ // Clean up after oversized allocations, while leaving some space to
+ // remain for subsequent allocations (if `exact` false) or to
+ // exactly the space we need (if `exact` true); returns space
+ // reclaimed in bytes
+ size_t reclaim(bool exact, cudaStream_t stream) {
+ size_t free = capacity_ - num_;
+
+ if (exact) {
+ realloc_(num_, stream);
+ return free * sizeof(T);
+ }
+
+ // If more than 1/4th of the space is free, then we want to
+ // truncate to only having 1/8th of the space free; this still
+ // preserves some space for new elements, but won't force us to
+ // double our size right away
+ if (free > (capacity_ / 4)) {
+ size_t newFree = capacity_ / 8;
+ size_t newCapacity = num_ + newFree;
+
+ size_t oldCapacity = capacity_;
+ FAISS_ASSERT(newCapacity < oldCapacity);
+
+ realloc_(newCapacity, stream);
+
+ return (oldCapacity - newCapacity) * sizeof(T);
+ }
+
+ return 0;
+ }
+
+ // Returns true if we actually reallocated memory
+ bool reserve(size_t newCapacity, cudaStream_t stream) {
+ if (newCapacity <= capacity_) {
+ return false;
+ }
+
+ // Otherwise, we need new space.
+ realloc_(newCapacity, stream);
+ return true;
+ }
+
+ private:
+ void realloc_(size_t newCapacity, cudaStream_t stream) {
+ FAISS_ASSERT(num_ <= newCapacity);
+
+ size_t newSizeInBytes = newCapacity * sizeof(T);
+ size_t oldSizeInBytes = num_ * sizeof(T);
+
+ // The new allocation will occur on this stream
+ allocInfo_.stream = stream;
+
+ auto newAlloc = res_->allocMemoryHandle(
+ AllocRequest(allocInfo_, newSizeInBytes));
+
+ // Copy over any old data
+ CUDA_VERIFY(cudaMemcpyAsync(
+ newAlloc.data,
+ data(),
+ oldSizeInBytes,
+ cudaMemcpyDeviceToDevice,
+ stream));
+
+ // Zero out the new space past the data we just copied
+ CUDA_VERIFY(cudaMemsetAsync(
+ (uint8_t*)newAlloc.data + oldSizeInBytes,
+ 0,
+ newSizeInBytes - oldSizeInBytes,
+ stream));
+
+ alloc_ = std::move(newAlloc);
+ capacity_ = newCapacity;
+ }
+
+ size_t getNewCapacity_(size_t preferredSize) {
+ if (preferredSize <= kDeviceVector_2x_Limit) {
+ return utils::nextHighestPowerOf2(preferredSize);
+ } else if (preferredSize <= kDeviceVector_1_25x_Limit) {
+ return preferredSize + (preferredSize >> 2);
+ } else {
+ return preferredSize;
+ }
+ }
+
+ /// Our current memory allocation, if any
+ GpuMemoryReservation alloc_;
+
+ /// current valid number of T present
+ size_t num_;
+
+ /// current space of T present (bytes is sizeof(T) * capacity_)
+ size_t capacity_;
+
+ /// Where we should allocate memory
+ GpuResources* res_;
+
+ /// How we should allocate memory
+ AllocInfo allocInfo_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Float16.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Float16.cuh
new file mode 100644
index 0000000..cfe405c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Float16.cuh
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/GpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+
+// Some compute capabilities have full float16 ALUs.
+#if __CUDA_ARCH__ >= 530
+#define FAISS_USE_FULL_FLOAT16 1
+#endif // __CUDA_ARCH__ types
+
+// Some compute capabilities have full bfloat16 ALUs.
+#if __CUDA_ARCH__ >= 800 || defined(USE_AMD_ROCM)
+#define FAISS_USE_FULL_BFLOAT16 1
+#endif // __CUDA_ARCH__ types
+
+#if !defined(USE_AMD_ROCM)
+#include <cuda_bf16.h>
+#include <cuda_fp16.h>
+#else
+#include <hip/hip_bf16.h>
+#include <hip/hip_fp16.h>
+#endif // !defined(USE_AMD_ROCM)
+
+namespace faiss {
+namespace gpu {
+
+// 64 bytes containing 4 half (float16) values
+struct Half4 {
+ half2 a;
+ half2 b;
+};
+
+inline __device__ float4 half4ToFloat4(Half4 v) {
+ float2 a = __half22float2(v.a);
+ float2 b = __half22float2(v.b);
+
+ float4 out;
+ out.x = a.x;
+ out.y = a.y;
+ out.z = b.x;
+ out.w = b.y;
+
+ return out;
+}
+
+inline __device__ Half4 float4ToHalf4(float4 v) {
+ float2 a;
+ a.x = v.x;
+ a.y = v.y;
+
+ float2 b;
+ b.x = v.z;
+ b.y = v.w;
+
+ Half4 out;
+ out.a = __float22half2_rn(a);
+ out.b = __float22half2_rn(b);
+
+ return out;
+}
+
+// 128 bytes containing 8 half (float16) values
+struct Half8 {
+ Half4 a;
+ Half4 b;
+};
+
+/// Returns true if the given device supports native float16 math
+inline bool getDeviceSupportsFloat16Math(int device) {
+ const auto& prop = getDeviceProperties(device);
+
+ return (prop.major >= 6 || (prop.major == 5 && prop.minor >= 3));
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/HostTensor-inl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/HostTensor-inl.cuh
new file mode 100644
index 0000000..9a6083e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/HostTensor-inl.cuh
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor()
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(),
+ state_(AllocState::NotOwner) {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::~HostTensor() {
+ if (state_ == AllocState::Owner) {
+ FAISS_ASSERT(this->data_ != nullptr);
+ delete[] this->data_;
+ this->data_ = nullptr;
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(),
+ state_(AllocState::NotOwner) {
+ this->operator=(std::move(t));
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& HostTensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::
+operator=(HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t) {
+ if (this->state_ == AllocState::Owner) {
+ FAISS_ASSERT(this->data_ != nullptr);
+ delete[] this->data_;
+ this->data_ = nullptr;
+ }
+
+ this->Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::operator=(
+ std::move(t));
+
+ this->state_ = t.state_;
+ t.state_ = AllocState::NotOwner;
+
+ return *this;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ const IndexT sizes[Dim])
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(nullptr, sizes),
+ state_(AllocState::Owner) {
+ this->data_ = new T[this->numElements()];
+ FAISS_ASSERT(this->data_ != nullptr);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ std::initializer_list<IndexT> sizes)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(nullptr, sizes),
+ state_(AllocState::Owner) {
+ this->data_ = new T[this->numElements()];
+ FAISS_ASSERT(this->data_ != nullptr);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ DataPtrType data,
+ const IndexT sizes[Dim])
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(data, sizes),
+ state_(AllocState::NotOwner) {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ DataPtrType data,
+ std::initializer_list<IndexT> sizes)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(data, sizes),
+ state_(AllocState::NotOwner) {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ DataPtrType data,
+ const IndexT sizes[Dim],
+ const IndexT strides[Dim])
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(data, sizes, strides),
+ state_(AllocState::NotOwner) {}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::HostTensor(
+ const Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t,
+ cudaStream_t stream)
+ : Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(
+ nullptr,
+ t.sizes(),
+ t.strides()),
+ state_(AllocState::Owner) {
+ // Only contiguous arrays handled for now
+ FAISS_ASSERT(t.isContiguous());
+
+ this->data_ = new T[t.numElements()];
+ this->copyFrom(t, stream);
+}
+
+/// Call to zero out memory
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& HostTensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::zero() {
+ // Region must be contiguous
+ FAISS_ASSERT(this->isContiguous());
+
+ if (this->data_ != nullptr) {
+ memset(this->data_, 0, this->getSizeInBytes());
+ }
+
+ return *this;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ T HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>::maxDiff(
+ const HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& t) const {
+ auto size = this->numElements();
+
+ FAISS_ASSERT(size == t.numElements());
+ FAISS_ASSERT(size > 0);
+
+ if (InnerContig) {
+ auto a = this->data();
+ auto b = t.data();
+
+ T maxDiff = a[0] - b[0];
+ // FIXME: type-specific abs()
+ maxDiff = maxDiff < 0 ? maxDiff * (T)-1 : maxDiff;
+
+ for (IndexT i = 1; i < size; ++i) {
+ auto diff = a[i] - b[i];
+ // FIXME: type-specific abs
+ diff = diff < 0 ? diff * (T)-1 : diff;
+ if (diff > maxDiff) {
+ maxDiff = diff;
+ }
+ }
+
+ return maxDiff;
+ } else {
+ // non-contiguous
+ // FIXME
+ FAISS_ASSERT(false);
+ return (T)0;
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/HostTensor.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/HostTensor.cuh
new file mode 100644
index 0000000..5c7f96d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/HostTensor.cuh
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h> // idx_t
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig = false,
+ typename IndexT = idx_t,
+ template <typename U> class PtrTraits = traits::DefaultPtrTraits>
+class HostTensor : public Tensor<T, Dim, InnerContig, IndexT, PtrTraits> {
+ public:
+ typedef IndexT IndexType;
+ typedef typename PtrTraits<T>::PtrType DataPtrType;
+
+ /// Default constructor
+ __host__ HostTensor();
+
+ /// Destructor
+ __host__ ~HostTensor();
+
+ /// Move constructor
+ __host__ HostTensor(HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t);
+
+ /// Move assignment
+ __host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& operator=(
+ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t);
+
+ /// Constructs a tensor of the given size, allocating memory for it
+ /// locally
+ __host__ HostTensor(const IndexT sizes[Dim]);
+ __host__ HostTensor(std::initializer_list<IndexT> sizes);
+
+ /// Constructs a tensor of the given size and stride, referencing a
+ /// memory region we do not own
+ __host__ HostTensor(DataPtrType data, const IndexT sizes[Dim]);
+ __host__ HostTensor(DataPtrType data, std::initializer_list<IndexT> sizes);
+
+ /// Constructs a tensor of the given size and stride, referencing a
+ /// memory region we do not own
+ __host__ HostTensor(
+ DataPtrType data,
+ const IndexT sizes[Dim],
+ const IndexT strides[Dim]);
+
+ /// Copies a tensor into ourselves, allocating memory for it
+ /// locally. If the tensor is on the GPU, then we will copy it to
+ /// ourselves wrt the given stream.
+ __host__ HostTensor(
+ const Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t,
+ cudaStream_t stream);
+
+ /// Call to zero out memory
+ __host__ HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& zero();
+
+ /// Returns the maximum difference seen between two tensors
+ __host__ T
+ maxDiff(const HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& t) const;
+
+ /// Are the two tensors exactly equal?
+ __host__ bool equal(
+ const HostTensor<T, Dim, InnerContig, IndexT, PtrTraits>& t) const {
+ return (maxDiff(t) == (T)0);
+ }
+
+ private:
+ enum AllocState {
+ /// This tensor itself owns the memory, which must be freed via
+ /// cudaFree
+ Owner,
+
+ /// This tensor itself is not an owner of the memory; there is
+ /// nothing to free
+ NotOwner,
+ };
+
+ AllocState state_;
+};
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/utils/HostTensor-inl.cuh>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Limits.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Limits.cuh
new file mode 100644
index 0000000..849e5c2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Limits.cuh
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Pair.cuh>
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+struct Limits {};
+
+// Unfortunately we can't use constexpr because there is no
+// constexpr constructor for half
+// FIXME: faiss CPU uses +/-FLT_MAX instead of +/-infinity
+constexpr float kFloatMax = std::numeric_limits<float>::max();
+constexpr float kFloatMin = std::numeric_limits<float>::lowest();
+
+template <>
+struct Limits<float> {
+ static __device__ __host__ inline float getMin() {
+ return kFloatMin;
+ }
+ static __device__ __host__ inline float getMax() {
+ return kFloatMax;
+ }
+};
+
+inline __device__ __host__ half kGetHalf(unsigned short v) {
+#if CUDA_VERSION >= 9000 || defined(USE_AMD_ROCM)
+ __half_raw h;
+ h.x = v;
+ return __half(h);
+#else
+ half h;
+ h.x = v;
+ return h;
+#endif
+}
+
+template <>
+struct Limits<half> {
+ static __device__ __host__ inline half getMin() {
+ return kGetHalf(0xfbffU);
+ }
+ static __device__ __host__ inline half getMax() {
+ return kGetHalf(0x7bffU);
+ }
+};
+
+constexpr int kIntMax = std::numeric_limits<int>::max();
+constexpr int kIntMin = std::numeric_limits<int>::lowest();
+
+template <>
+struct Limits<int> {
+ static __device__ __host__ inline int getMin() {
+ return kIntMin;
+ }
+ static __device__ __host__ inline int getMax() {
+ return kIntMax;
+ }
+};
+
+constexpr idx_t kIdxTMax = std::numeric_limits<idx_t>::max();
+constexpr idx_t kIdxTMin = std::numeric_limits<idx_t>::lowest();
+
+template <>
+struct Limits<idx_t> {
+ static __device__ __host__ inline idx_t getMin() {
+ return kIdxTMin;
+ }
+ static __device__ __host__ inline idx_t getMax() {
+ return kIdxTMax;
+ }
+};
+
+template <typename K, typename V>
+struct Limits<Pair<K, V>> {
+ static __device__ __host__ inline Pair<K, V> getMin() {
+ return Pair<K, V>(Limits<K>::getMin(), Limits<V>::getMin());
+ }
+
+ static __device__ __host__ inline Pair<K, V> getMax() {
+ return Pair<K, V>(Limits<K>::getMax(), Limits<V>::getMax());
+ }
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/LoadStoreOperators.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/LoadStoreOperators.cuh
new file mode 100644
index 0000000..e0c87d0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/LoadStoreOperators.cuh
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Float16.cuh>
+
+#ifndef __HALF2_TO_UI
+// cuda_fp16.hpp doesn't export this
+#define __HALF2_TO_UI(var) *(reinterpret_cast<unsigned int*>(&(var)))
+#endif
+
+//
+// Templated wrappers to express load/store for different scalar and vector
+// types, so kernels can have the same written form but can operate
+// over half and float, and on vector types transparently
+//
+
+namespace faiss {
+namespace gpu {
+
+#ifdef USE_AMD_ROCM
+
+template <typename T>
+struct LoadStore {
+ static inline __device__ T load(void* p) {
+ return *((T*)p);
+ }
+
+ static inline __device__ void store(void* p, const T& v) {
+ *((T*)p) = v;
+ }
+};
+
+template <>
+struct LoadStore<Half4> {
+ static inline __device__ Half4 load(void* p) {
+ Half4 out;
+ Half4* t = reinterpret_cast<Half4*>(p);
+ out = *t;
+ return out;
+ }
+
+ static inline __device__ void store(void* p, Half4& v) {
+ Half4* t = reinterpret_cast<Half4*>(p);
+ *t = v;
+ }
+};
+
+template <>
+struct LoadStore<Half8> {
+ static inline __device__ Half8 load(void* p) {
+ Half8 out;
+ Half8* t = reinterpret_cast<Half8*>(p);
+ out = *t;
+ return out;
+ }
+
+ static inline __device__ void store(void* p, Half8& v) {
+ Half8* t = reinterpret_cast<Half8*>(p);
+ *t = v;
+ }
+};
+
+#else // USE_AMD_ROCM
+
+template <typename T>
+struct LoadStore {
+ static inline __device__ T load(void* p) {
+ return *((T*)p);
+ }
+
+ static inline __device__ void store(void* p, const T& v) {
+ *((T*)p) = v;
+ }
+};
+
+template <>
+struct LoadStore<Half4> {
+ static inline __device__ Half4 load(void* p) {
+ Half4 out;
+#if CUDA_VERSION >= 9000
+ asm("ld.global.v2.u32 {%0, %1}, [%2];"
+ : "=r"(__HALF2_TO_UI(out.a)), "=r"(__HALF2_TO_UI(out.b))
+ : "l"(p));
+#else
+ asm("ld.global.v2.u32 {%0, %1}, [%2];"
+ : "=r"(out.a.x), "=r"(out.b.x)
+ : "l"(p));
+#endif
+ return out;
+ }
+
+ static inline __device__ void store(void* p, Half4& v) {
+#if CUDA_VERSION >= 9000
+ asm("st.v2.u32 [%0], {%1, %2};"
+ :
+ : "l"(p), "r"(__HALF2_TO_UI(v.a)), "r"(__HALF2_TO_UI(v.b)));
+#else
+ asm("st.v2.u32 [%0], {%1, %2};" : : "l"(p), "r"(v.a.x), "r"(v.b.x));
+#endif
+ }
+};
+
+template <>
+struct LoadStore<Half8> {
+ static inline __device__ Half8 load(void* p) {
+ Half8 out;
+#if CUDA_VERSION >= 9000
+ asm("ld.global.v4.u32 {%0, %1, %2, %3}, [%4];"
+ : "=r"(__HALF2_TO_UI(out.a.a)),
+ "=r"(__HALF2_TO_UI(out.a.b)),
+ "=r"(__HALF2_TO_UI(out.b.a)),
+ "=r"(__HALF2_TO_UI(out.b.b))
+ : "l"(p));
+#else
+ asm("ld.global.v4.u32 {%0, %1, %2, %3}, [%4];"
+ : "=r"(out.a.a.x), "=r"(out.a.b.x), "=r"(out.b.a.x), "=r"(out.b.b.x)
+ : "l"(p));
+#endif
+ return out;
+ }
+
+ static inline __device__ void store(void* p, Half8& v) {
+#if CUDA_VERSION >= 9000
+ asm("st.v4.u32 [%0], {%1, %2, %3, %4};"
+ :
+ : "l"(p),
+ "r"(__HALF2_TO_UI(v.a.a)),
+ "r"(__HALF2_TO_UI(v.a.b)),
+ "r"(__HALF2_TO_UI(v.b.a)),
+ "r"(__HALF2_TO_UI(v.b.b)));
+#else
+ asm("st.v4.u32 [%0], {%1, %2, %3, %4};"
+ :
+ : "l"(p), "r"(v.a.a.x), "r"(v.a.b.x), "r"(v.b.a.x), "r"(v.b.b.x));
+#endif
+ }
+};
+
+#endif // USE_AMD_ROCM
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MathOperators.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MathOperators.cuh
new file mode 100644
index 0000000..ce1e234
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MathOperators.cuh
@@ -0,0 +1,791 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/ConversionOperators.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+
+//
+// Templated wrappers to express math for different scalar and vector
+// types, so kernels can have the same written form but can operate
+// over half, bfloat16 and float, and on vector types transparently
+//
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+struct Math {
+ typedef T ScalarType;
+
+ static inline __device__ T add(T a, T b) {
+ return a + b;
+ }
+
+ static inline __device__ T sub(T a, T b) {
+ return a - b;
+ }
+
+ static inline __device__ T mul(T a, T b) {
+ return a * b;
+ }
+
+ static inline __device__ T neg(T v) {
+ return -v;
+ }
+
+ /// For a vector type, this is a horizontal add, returning sum(v_i)
+ static inline __device__ float reduceAdd(T v) {
+ return ConvertTo<float>::to(v);
+ }
+
+ static inline __device__ bool lt(T a, T b) {
+ return a < b;
+ }
+
+ static inline __device__ bool gt(T a, T b) {
+ return a > b;
+ }
+
+ static inline __device__ bool eq(T a, T b) {
+ return a == b;
+ }
+
+ static inline __device__ T zero() {
+ return (T)0;
+ }
+};
+
+template <>
+struct Math<float2> {
+ typedef float ScalarType;
+
+ static inline __device__ float2 add(float2 a, float2 b) {
+ float2 v;
+ v.x = a.x + b.x;
+ v.y = a.y + b.y;
+ return v;
+ }
+
+ static inline __device__ float2 sub(float2 a, float2 b) {
+ float2 v;
+ v.x = a.x - b.x;
+ v.y = a.y - b.y;
+ return v;
+ }
+
+ static inline __device__ float2 add(float2 a, float b) {
+ float2 v;
+ v.x = a.x + b;
+ v.y = a.y + b;
+ return v;
+ }
+
+ static inline __device__ float2 sub(float2 a, float b) {
+ float2 v;
+ v.x = a.x - b;
+ v.y = a.y - b;
+ return v;
+ }
+
+ static inline __device__ float2 mul(float2 a, float2 b) {
+ float2 v;
+ v.x = a.x * b.x;
+ v.y = a.y * b.y;
+ return v;
+ }
+
+ static inline __device__ float2 mul(float2 a, float b) {
+ float2 v;
+ v.x = a.x * b;
+ v.y = a.y * b;
+ return v;
+ }
+
+ static inline __device__ float2 neg(float2 v) {
+ v.x = -v.x;
+ v.y = -v.y;
+ return v;
+ }
+
+ /// For a vector type, this is a horizontal add, returning sum(v_i)
+ static inline __device__ float reduceAdd(float2 v) {
+ return v.x + v.y;
+ }
+
+ // not implemented for vector types
+ // static inline __device__ bool lt(float2 a, float2 b);
+ // static inline __device__ bool gt(float2 a, float2 b);
+ // static inline __device__ bool eq(float2 a, float2 b);
+
+ static inline __device__ float2 zero() {
+ float2 v;
+ v.x = 0.0f;
+ v.y = 0.0f;
+ return v;
+ }
+};
+
+template <>
+struct Math<float4> {
+ typedef float ScalarType;
+
+ static inline __device__ float4 add(float4 a, float4 b) {
+ float4 v;
+ v.x = a.x + b.x;
+ v.y = a.y + b.y;
+ v.z = a.z + b.z;
+ v.w = a.w + b.w;
+ return v;
+ }
+
+ static inline __device__ float4 sub(float4 a, float4 b) {
+ float4 v;
+ v.x = a.x - b.x;
+ v.y = a.y - b.y;
+ v.z = a.z - b.z;
+ v.w = a.w - b.w;
+ return v;
+ }
+
+ static inline __device__ float4 add(float4 a, float b) {
+ float4 v;
+ v.x = a.x + b;
+ v.y = a.y + b;
+ v.z = a.z + b;
+ v.w = a.w + b;
+ return v;
+ }
+
+ static inline __device__ float4 sub(float4 a, float b) {
+ float4 v;
+ v.x = a.x - b;
+ v.y = a.y - b;
+ v.z = a.z - b;
+ v.w = a.w - b;
+ return v;
+ }
+
+ static inline __device__ float4 mul(float4 a, float4 b) {
+ float4 v;
+ v.x = a.x * b.x;
+ v.y = a.y * b.y;
+ v.z = a.z * b.z;
+ v.w = a.w * b.w;
+ return v;
+ }
+
+ static inline __device__ float4 mul(float4 a, float b) {
+ float4 v;
+ v.x = a.x * b;
+ v.y = a.y * b;
+ v.z = a.z * b;
+ v.w = a.w * b;
+ return v;
+ }
+
+ static inline __device__ float4 neg(float4 v) {
+ v.x = -v.x;
+ v.y = -v.y;
+ v.z = -v.z;
+ v.w = -v.w;
+ return v;
+ }
+
+ /// For a vector type, this is a horizontal add, returning sum(v_i)
+ static inline __device__ float reduceAdd(float4 v) {
+ return v.x + v.y + v.z + v.w;
+ }
+
+ // not implemented for vector types
+ // static inline __device__ bool lt(float4 a, float4 b);
+ // static inline __device__ bool gt(float4 a, float4 b);
+ // static inline __device__ bool eq(float4 a, float4 b);
+
+ static inline __device__ float4 zero() {
+ float4 v;
+ v.x = 0.0f;
+ v.y = 0.0f;
+ v.z = 0.0f;
+ v.w = 0.0f;
+ return v;
+ }
+};
+
+template <>
+struct Math<half> {
+ typedef half ScalarType;
+
+ static inline __device__ half add(half a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hadd(a, b);
+#else
+ return __float2half(__half2float(a) + __half2float(b));
+#endif
+ }
+
+ static inline __device__ half sub(half a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hsub(a, b);
+#else
+ return __float2half(__half2float(a) - __half2float(b));
+#endif
+ }
+
+ static inline __device__ half mul(half a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hmul(a, b);
+#else
+ return __float2half(__half2float(a) * __half2float(b));
+#endif
+ }
+
+ static inline __device__ half neg(half v) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hneg(v);
+#else
+ return __float2half(-__half2float(v));
+#endif
+ }
+
+ static inline __device__ float reduceAdd(half v) {
+ return ConvertTo<float>::to(v);
+ }
+
+ static inline __device__ bool lt(half a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hlt(a, b);
+#else
+ return __half2float(a) < __half2float(b);
+#endif
+ }
+
+ static inline __device__ bool gt(half a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hgt(a, b);
+#else
+ return __half2float(a) > __half2float(b);
+#endif
+ }
+
+ static inline __device__ bool eq(half a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __heq(a, b);
+#else
+ return __half2float(a) == __half2float(b);
+#endif
+ }
+
+ static inline __device__ half zero() {
+#if CUDA_VERSION >= 9000 || defined(USE_AMD_ROCM)
+ return 0;
+#else
+ half h;
+ h.x = 0;
+ return h;
+#endif
+ }
+};
+
+template <>
+struct Math<half2> {
+ typedef half ScalarType;
+
+ static inline __device__ half2 add(half2 a, half2 b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hadd2(a, b);
+#else
+ float2 af = __half22float2(a);
+ float2 bf = __half22float2(b);
+
+ af.x += bf.x;
+ af.y += bf.y;
+
+ return __float22half2_rn(af);
+#endif
+ }
+
+ static inline __device__ half2 sub(half2 a, half2 b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hsub2(a, b);
+#else
+ float2 af = __half22float2(a);
+ float2 bf = __half22float2(b);
+
+ af.x -= bf.x;
+ af.y -= bf.y;
+
+ return __float22half2_rn(af);
+#endif
+ }
+
+ static inline __device__ half2 add(half2 a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ half2 b2 = __half2half2(b);
+ return __hadd2(a, b2);
+#else
+ float2 af = __half22float2(a);
+ float bf = __half2float(b);
+
+ af.x += bf;
+ af.y += bf;
+
+ return __float22half2_rn(af);
+#endif
+ }
+
+ static inline __device__ half2 sub(half2 a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ half2 b2 = __half2half2(b);
+ return __hsub2(a, b2);
+#else
+ float2 af = __half22float2(a);
+ float bf = __half2float(b);
+
+ af.x -= bf;
+ af.y -= bf;
+
+ return __float22half2_rn(af);
+#endif
+ }
+
+ static inline __device__ half2 mul(half2 a, half2 b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hmul2(a, b);
+#else
+ float2 af = __half22float2(a);
+ float2 bf = __half22float2(b);
+
+ af.x *= bf.x;
+ af.y *= bf.y;
+
+ return __float22half2_rn(af);
+#endif
+ }
+
+ static inline __device__ half2 mul(half2 a, half b) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ half2 b2 = __half2half2(b);
+ return __hmul2(a, b2);
+#else
+ float2 af = __half22float2(a);
+ float bf = __half2float(b);
+
+ af.x *= bf;
+ af.y *= bf;
+
+ return __float22half2_rn(af);
+#endif
+ }
+
+ static inline __device__ half2 neg(half2 v) {
+#ifdef FAISS_USE_FULL_FLOAT16
+ return __hneg2(v);
+#else
+ float2 vf = __half22float2(v);
+ vf.x = -vf.x;
+ vf.y = -vf.y;
+
+ return __float22half2_rn(vf);
+#endif
+ }
+
+ static inline __device__ float reduceAdd(half2 v) {
+ float2 vf = __half22float2(v);
+ vf.x += vf.y;
+
+ return vf.x;
+ }
+
+ // not implemented for vector types
+ // static inline __device__ bool lt(half2 a, half2 b);
+ // static inline __device__ bool gt(half2 a, half2 b);
+ // static inline __device__ bool eq(half2 a, half2 b);
+
+ static inline __device__ half2 zero() {
+ return __half2half2(Math<half>::zero());
+ }
+};
+
+template <>
+struct Math<Half4> {
+ typedef half ScalarType;
+
+ static inline __device__ Half4 add(Half4 a, Half4 b) {
+ Half4 h;
+ h.a = Math<half2>::add(a.a, b.a);
+ h.b = Math<half2>::add(a.b, b.b);
+ return h;
+ }
+
+ static inline __device__ Half4 sub(Half4 a, Half4 b) {
+ Half4 h;
+ h.a = Math<half2>::sub(a.a, b.a);
+ h.b = Math<half2>::sub(a.b, b.b);
+ return h;
+ }
+
+ static inline __device__ Half4 add(Half4 a, half b) {
+ Half4 h;
+ h.a = Math<half2>::add(a.a, b);
+ h.b = Math<half2>::add(a.b, b);
+ return h;
+ }
+
+ static inline __device__ Half4 sub(Half4 a, half b) {
+ Half4 h;
+ h.a = Math<half2>::sub(a.a, b);
+ h.b = Math<half2>::sub(a.b, b);
+ return h;
+ }
+
+ static inline __device__ Half4 mul(Half4 a, Half4 b) {
+ Half4 h;
+ h.a = Math<half2>::mul(a.a, b.a);
+ h.b = Math<half2>::mul(a.b, b.b);
+ return h;
+ }
+
+ static inline __device__ Half4 mul(Half4 a, half b) {
+ Half4 h;
+ h.a = Math<half2>::mul(a.a, b);
+ h.b = Math<half2>::mul(a.b, b);
+ return h;
+ }
+
+ static inline __device__ Half4 neg(Half4 v) {
+ Half4 h;
+ h.a = Math<half2>::neg(v.a);
+ h.b = Math<half2>::neg(v.b);
+ return h;
+ }
+
+ static inline __device__ float reduceAdd(Half4 v) {
+ float x = Math<half2>::reduceAdd(v.a);
+ float y = Math<half2>::reduceAdd(v.b);
+ return x + y;
+ }
+
+ // not implemented for vector types
+ // static inline __device__ bool lt(Half4 a, Half4 b);
+ // static inline __device__ bool gt(Half4 a, Half4 b);
+ // static inline __device__ bool eq(Half4 a, Half4 b);
+
+ static inline __device__ Half4 zero() {
+ Half4 h;
+ h.a = Math<half2>::zero();
+ h.b = Math<half2>::zero();
+ return h;
+ }
+};
+
+template <>
+struct Math<Half8> {
+ typedef half ScalarType;
+
+ static inline __device__ Half8 add(Half8 a, Half8 b) {
+ Half8 h;
+ h.a = Math<Half4>::add(a.a, b.a);
+ h.b = Math<Half4>::add(a.b, b.b);
+ return h;
+ }
+
+ static inline __device__ Half8 sub(Half8 a, Half8 b) {
+ Half8 h;
+ h.a = Math<Half4>::sub(a.a, b.a);
+ h.b = Math<Half4>::sub(a.b, b.b);
+ return h;
+ }
+
+ static inline __device__ Half8 add(Half8 a, half b) {
+ Half8 h;
+ h.a = Math<Half4>::add(a.a, b);
+ h.b = Math<Half4>::add(a.b, b);
+ return h;
+ }
+
+ static inline __device__ Half8 sub(Half8 a, half b) {
+ Half8 h;
+ h.a = Math<Half4>::sub(a.a, b);
+ h.b = Math<Half4>::sub(a.b, b);
+ return h;
+ }
+
+ static inline __device__ Half8 mul(Half8 a, Half8 b) {
+ Half8 h;
+ h.a = Math<Half4>::mul(a.a, b.a);
+ h.b = Math<Half4>::mul(a.b, b.b);
+ return h;
+ }
+
+ static inline __device__ Half8 mul(Half8 a, half b) {
+ Half8 h;
+ h.a = Math<Half4>::mul(a.a, b);
+ h.b = Math<Half4>::mul(a.b, b);
+ return h;
+ }
+
+ static inline __device__ Half8 neg(Half8 v) {
+ Half8 h;
+ h.a = Math<Half4>::neg(v.a);
+ h.b = Math<Half4>::neg(v.b);
+ return h;
+ }
+
+ static inline __device__ float reduceAdd(Half8 v) {
+ float x = Math<Half4>::reduceAdd(v.a);
+ float y = Math<Half4>::reduceAdd(v.b);
+ return x + y;
+ }
+
+ // not implemented for vector types
+ // static inline __device__ bool lt(Half8 a, Half8 b);
+ // static inline __device__ bool gt(Half8 a, Half8 b);
+ // static inline __device__ bool eq(Half8 a, Half8 b);
+
+ static inline __device__ Half8 zero() {
+ Half8 h;
+ h.a = Math<Half4>::zero();
+ h.b = Math<Half4>::zero();
+ return h;
+ }
+};
+
+template <>
+struct Math<__nv_bfloat16> {
+ typedef __nv_bfloat16 ScalarType;
+
+ static inline __device__ __nv_bfloat16
+ add(__nv_bfloat16 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hadd(a, b);
+#else
+ return __float2bfloat16(__bfloat162float(a) + __bfloat162float(b));
+#endif
+ }
+
+ static inline __device__ __nv_bfloat16
+ sub(__nv_bfloat16 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hsub(a, b);
+#else
+ return __float2bfloat16(__bfloat162float(a) - __bfloat162float(b));
+#endif
+ }
+
+ static inline __device__ __nv_bfloat16
+ mul(__nv_bfloat16 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hmul(a, b);
+#else
+ return __float2bfloat16(__bfloat162float(a) * __bfloat162float(b));
+#endif
+ }
+
+ static inline __device__ __nv_bfloat16 neg(__nv_bfloat16 v) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hneg(v);
+#else
+ return __float2bfloat16(-__bfloat162float(v));
+#endif
+ }
+
+ static inline __device__ float reduceAdd(__nv_bfloat16 v) {
+ return ConvertTo<float>::to(v);
+ }
+
+ static inline __device__ bool lt(__nv_bfloat16 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hlt(a, b);
+#else
+ return __bfloat162float(a) < __bfloat162float(b);
+#endif
+ }
+
+ static inline __device__ bool gt(__nv_bfloat16 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hgt(a, b);
+#else
+ return __bfloat162float(a) > __bfloat162float(b);
+#endif
+ }
+
+ static inline __device__ bool eq(__nv_bfloat16 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __heq(a, b);
+#else
+ return __bfloat162float(a) == __bfloat162float(b);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat16 zero() {
+#if CUDA_VERSION >= 9000 || defined(USE_AMD_ROCM)
+ return 0.0f;
+#else
+ __nv_bfloat16 h;
+ h.x = 0;
+ return h;
+#endif
+ }
+};
+
+template <>
+struct Math<__nv_bfloat162> {
+ typedef __nv_bfloat16 ScalarType;
+
+#ifndef FAISS_USE_FULL_BFLOAT16
+ // define a few conversion functions that don't exist on cuda 11
+ // this overrides their definition in cuda 12 but we use native bf16 on this
+ // platform anyways.
+ static inline __device__ float2 __bfloat1622float2(__nv_bfloat162 a) {
+ float2 af;
+ af.x = __bfloat162float(a.x);
+ af.y = __bfloat162float(a.y);
+ return af;
+ }
+
+ static inline __device__ __nv_bfloat162 __float22bfloat162_rn(float2 af) {
+ __nv_bfloat162 a;
+ a.x = __float2bfloat16_rn(af.x);
+ a.y = __float2bfloat16_rn(af.y);
+ return a;
+ }
+
+ static inline __device__ __nv_bfloat162
+ __bfloat162bfloat162(__nv_bfloat16 v) {
+ __nv_bfloat162 a;
+ a.x = v;
+ a.y = v;
+ return a;
+ }
+#endif
+
+ static inline __device__ __nv_bfloat162
+ add(__nv_bfloat162 a, __nv_bfloat162 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hadd2(a, b);
+#else
+ float2 af = __bfloat1622float2(a);
+ float2 bf = __bfloat1622float2(b);
+
+ af.x += bf.x;
+ af.y += bf.y;
+
+ return __float22bfloat162_rn(af);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat162
+ sub(__nv_bfloat162 a, __nv_bfloat162 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hsub2(a, b);
+#else
+ float2 af = __bfloat1622float2(a);
+ float2 bf = __bfloat1622float2(b);
+
+ af.x -= bf.x;
+ af.y -= bf.y;
+
+ return __float22bfloat162_rn(af);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat162
+ add(__nv_bfloat162 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ __nv_bfloat162 b2 = __bfloat162bfloat162(b);
+ return __hadd2(a, b2);
+#else
+ float2 af = __bfloat1622float2(a);
+ float bf = __bfloat162float(b);
+
+ af.x += bf;
+ af.y += bf;
+
+ return __float22bfloat162_rn(af);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat162
+ sub(__nv_bfloat162 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ __nv_bfloat162 b2 = __bfloat162bfloat162(b);
+ return __hsub2(a, b2);
+#else
+ float2 af = __bfloat1622float2(a);
+ float bf = __bfloat162float(b);
+
+ af.x -= bf;
+ af.y -= bf;
+
+ return __float22bfloat162_rn(af);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat162
+ mul(__nv_bfloat162 a, __nv_bfloat162 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hmul2(a, b);
+#else
+ float2 af = __bfloat1622float2(a);
+ float2 bf = __bfloat1622float2(b);
+
+ af.x *= bf.x;
+ af.y *= bf.y;
+
+ return __float22bfloat162_rn(af);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat162
+ mul(__nv_bfloat162 a, __nv_bfloat16 b) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ __nv_bfloat162 b2 = __bfloat162bfloat162(b);
+ return __hmul2(a, b2);
+#else
+ float2 af = __bfloat1622float2(a);
+ float bf = __bfloat162float(b);
+
+ af.x *= bf;
+ af.y *= bf;
+
+ return __float22bfloat162_rn(af);
+#endif
+ }
+
+ static inline __device__ __nv_bfloat162 neg(__nv_bfloat162 v) {
+#ifdef FAISS_USE_FULL_BFLOAT16
+ return __hneg2(v);
+#else
+ float2 vf = __bfloat1622float2(v);
+ vf.x = -vf.x;
+ vf.y = -vf.y;
+
+ return __float22bfloat162_rn(vf);
+#endif
+ }
+
+ static inline __device__ float reduceAdd(__nv_bfloat162 v) {
+ float2 vf = __bfloat1622float2(v);
+ vf.x += vf.y;
+
+ return vf.x;
+ }
+
+ // not implemented for vector types
+ // static inline __device__ bool lt(__nv_bfloat162 a, __nv_bfloat162 b);
+ // static inline __device__ bool gt(__nv_bfloat162 a, __nv_bfloat162 b);
+ // static inline __device__ bool eq(__nv_bfloat162 a, __nv_bfloat162 b);
+
+ static inline __device__ __nv_bfloat162 zero() {
+ return __bfloat162bfloat162(Math<__nv_bfloat16>::zero());
+ }
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MatrixMult-inl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MatrixMult-inl.cuh
new file mode 100644
index 0000000..b28ea56
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MatrixMult-inl.cuh
@@ -0,0 +1,461 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cublas_v2.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+struct GetCudaType;
+
+#ifdef USE_AMD_ROCM
+
+template <>
+struct GetCudaType<float> {
+ static constexpr hipblasDatatype_t Type = HIPBLAS_R_32F;
+};
+
+template <>
+struct GetCudaType<half> {
+ static constexpr hipblasDatatype_t Type = HIPBLAS_R_16F;
+};
+
+template <>
+struct GetCudaType<__hip_bfloat16> {
+ static constexpr hipblasDatatype_t Type = HIPBLAS_R_16B;
+};
+
+#else
+
+template <>
+struct GetCudaType<float> {
+ static constexpr cudaDataType_t Type = CUDA_R_32F;
+};
+
+template <>
+struct GetCudaType<half> {
+ static constexpr cudaDataType_t Type = CUDA_R_16F;
+};
+
+template <>
+struct GetCudaType<__nv_bfloat16> {
+ static constexpr cudaDataType_t Type = CUDA_R_16BF;
+};
+
+#endif
+
+template <typename AT, typename BT>
+cublasStatus_t rawGemm(
+ cublasHandle_t handle,
+ cublasOperation_t transa,
+ cublasOperation_t transb,
+ int m,
+ int n,
+ int k,
+ const float fAlpha,
+ const void* A,
+ int lda,
+ const void* B,
+ int ldb,
+ const float fBeta,
+ float* C,
+ int ldc) {
+ auto cAT = GetCudaType<AT>::Type;
+ auto cBT = GetCudaType<BT>::Type;
+
+#ifdef USE_AMD_ROCM
+ return hipblasGemmEx(
+ handle,
+ transa,
+ transb,
+ m,
+ n,
+ k,
+ &fAlpha,
+ A,
+ cAT,
+ lda,
+ B,
+ cBT,
+ ldb,
+ &fBeta,
+ C,
+ HIPBLAS_R_32F,
+ ldc,
+ HIPBLAS_R_32F,
+ HIPBLAS_GEMM_DEFAULT);
+#else
+
+ // FIXME: some weird CUDA 11 bug? where cublasSgemmEx on
+ // f16 (8, 64) x f16 (64, 64)' = f32 (8, 64) returns "not supported".
+ // cublasGemmEx using CUBLAS_COMPUTE_32F also fails, but
+ // CUBLAS_COMPUTE_32F_PEDANTIC does not fail (as seen on a V100).
+ //
+ // Only use the PEDANTIC implementation if the input matrices are f16
+ // and we are on CUDA 11+
+#if CUDA_VERSION >= 11000
+ if (cAT == CUDA_R_16F || cBT == CUDA_R_16F) {
+ return cublasGemmEx(
+ handle,
+ transa,
+ transb,
+ m,
+ n,
+ k,
+ &fAlpha,
+ A,
+ cAT,
+ lda,
+ B,
+ cBT,
+ ldb,
+ &fBeta,
+ C,
+ CUDA_R_32F,
+ ldc,
+ CUBLAS_COMPUTE_32F_PEDANTIC,
+ CUBLAS_GEMM_DEFAULT);
+ }
+#endif
+
+ // Always accumulate in f32
+ return cublasSgemmEx(
+ handle,
+ transa,
+ transb,
+ m,
+ n,
+ k,
+ &fAlpha,
+ A,
+ cAT,
+ lda,
+ B,
+ cBT,
+ ldb,
+ &fBeta,
+ C,
+ CUDA_R_32F,
+ ldc);
+#endif // USE_AMD_ROCM
+}
+
+template <typename AT, typename BT>
+cublasStatus_t rawBatchGemm(
+ cublasHandle_t handle,
+ cublasOperation_t transa,
+ cublasOperation_t transb,
+ int m,
+ int n,
+ int k,
+ const float fAlpha,
+ const void* A,
+ int lda,
+ long long int strideA,
+ const void* B,
+ int ldb,
+ long long int strideB,
+ const float fBeta,
+ float* C,
+ int ldc,
+ long long int strideC,
+ int batchCount) {
+ auto cAT = GetCudaType<AT>::Type;
+ auto cBT = GetCudaType<BT>::Type;
+
+ // Always accumulate in f32
+#ifdef USE_AMD_ROCM
+ return hipblasGemmStridedBatchedEx(
+ handle,
+ transa,
+ transb,
+ m,
+ n,
+ k,
+ &fAlpha,
+ A,
+ cAT,
+ lda,
+ strideA,
+ B,
+ cBT,
+ ldb,
+ strideB,
+ &fBeta,
+ C,
+ HIPBLAS_R_32F,
+ ldc,
+ strideC,
+ batchCount,
+ HIPBLAS_R_32F,
+ HIPBLAS_GEMM_DEFAULT);
+#else
+ return cublasGemmStridedBatchedEx(
+ handle,
+ transa,
+ transb,
+ m,
+ n,
+ k,
+ &fAlpha,
+ A,
+ cAT,
+ lda,
+ strideA,
+ B,
+ cBT,
+ ldb,
+ strideB,
+ &fBeta,
+ C,
+ CUDA_R_32F,
+ ldc,
+ strideC,
+ batchCount,
+ CUDA_R_32F,
+ CUBLAS_GEMM_DEFAULT);
+#endif
+}
+
+template <typename AT, typename BT>
+void runMatrixMult(
+ Tensor<float, 2, true>& c,
+ bool transC,
+ Tensor<AT, 2, true>& a,
+ bool transA,
+ Tensor<BT, 2, true>& b,
+ bool transB,
+ float alpha,
+ float beta,
+ cublasHandle_t handle,
+ cudaStream_t stream) {
+ // All sizes must be within int bounds
+ FAISS_ASSERT(c.getSize(0) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(c.getSize(1) <= std::numeric_limits<int>::max());
+
+ FAISS_ASSERT(b.getSize(0) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(b.getSize(1) <= std::numeric_limits<int>::max());
+
+ FAISS_ASSERT(a.getSize(0) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(a.getSize(1) <= std::numeric_limits<int>::max());
+
+ cublasSetStream(handle, stream);
+
+ // Check that we have (m x k) * (k x n) = (m x n)
+ // using the input row-major layout
+ int aM = transA ? a.getSize(1) : a.getSize(0);
+ int aK = transA ? a.getSize(0) : a.getSize(1);
+
+ int bK = transB ? b.getSize(1) : b.getSize(0);
+ int bN = transB ? b.getSize(0) : b.getSize(1);
+
+ int cM = transC ? c.getSize(1) : c.getSize(0);
+ int cN = transC ? c.getSize(0) : c.getSize(1);
+
+ FAISS_ASSERT(aM == cM);
+ FAISS_ASSERT(aK == bK);
+ FAISS_ASSERT(bN == cN);
+
+ FAISS_ASSERT(a.getStride(1) == 1);
+ FAISS_ASSERT(b.getStride(1) == 1);
+ FAISS_ASSERT(c.getStride(1) == 1);
+
+ // Now, we have to represent the matrix multiplication in
+ // column-major layout
+ float* pC = c.data();
+
+ int m = c.getSize(1); // stride 1 size
+ int n = c.getSize(0); // other size
+ int k = transA ? a.getSize(0) : a.getSize(1);
+
+ int lda = transC ? a.getStride(0) : b.getStride(0);
+ int ldb = transC ? b.getStride(0) : a.getStride(0);
+ int ldc = c.getStride(0);
+
+ auto gemmTrA = transB ? CUBLAS_OP_T : CUBLAS_OP_N;
+ auto gemmTrB = transA ? CUBLAS_OP_T : CUBLAS_OP_N;
+
+ if (transC) {
+ gemmTrA = transA ? CUBLAS_OP_N : CUBLAS_OP_T;
+ gemmTrB = transB ? CUBLAS_OP_N : CUBLAS_OP_T;
+ }
+
+ cublasStatus_t err;
+
+ if (transC) {
+ err = rawGemm<AT, BT>(
+ handle,
+ gemmTrA,
+ gemmTrB,
+ m,
+ n,
+ k,
+ alpha,
+ a.data(),
+ lda,
+ b.data(),
+ ldb,
+ beta,
+ pC,
+ ldc);
+ } else {
+ err = rawGemm<AT, BT>(
+ handle,
+ gemmTrA,
+ gemmTrB,
+ m,
+ n,
+ k,
+ alpha,
+ b.data(),
+ lda,
+ a.data(),
+ ldb,
+ beta,
+ pC,
+ ldc);
+ }
+
+ FAISS_ASSERT_FMT(
+ err == CUBLAS_STATUS_SUCCESS,
+ "cublas failed (%d): "
+ "(%ld, %ld)%s x (%ld, %ld)%s = (%ld, %ld)%s "
+ "gemm params m %d n %d k %d trA %s trB %s lda %d ldb %d ldc %d",
+ (int)err,
+ a.getSize(0),
+ a.getSize(1),
+ transA ? "'" : "",
+ b.getSize(0),
+ b.getSize(1),
+ transB ? "'" : "",
+ c.getSize(0),
+ c.getSize(1),
+ transC ? "'" : "",
+ m,
+ n,
+ k,
+ gemmTrA == CUBLAS_OP_T ? "T" : "N",
+ gemmTrB == CUBLAS_OP_T ? "T" : "N",
+ lda,
+ ldb,
+ ldc);
+ CUDA_TEST_ERROR();
+}
+
+template <typename AT, typename BT>
+void runBatchMatrixMult(
+ Tensor<float, 3, true>& c,
+ bool transC,
+ Tensor<AT, 3, true>& a,
+ bool transA,
+ Tensor<BT, 3, true>& b,
+ bool transB,
+ float alpha,
+ float beta,
+ cublasHandle_t handle,
+ cudaStream_t stream) {
+ // All sizes must be within int bounds
+ FAISS_ASSERT(c.getSize(0) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(c.getSize(1) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(c.getSize(2) <= std::numeric_limits<int>::max());
+
+ FAISS_ASSERT(a.getSize(0) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(a.getSize(1) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(a.getSize(2) <= std::numeric_limits<int>::max());
+
+ FAISS_ASSERT(a.getSize(0) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(a.getSize(1) <= std::numeric_limits<int>::max());
+ FAISS_ASSERT(a.getSize(2) <= std::numeric_limits<int>::max());
+
+ FAISS_ASSERT(c.getSize(0) == a.getSize(0));
+ FAISS_ASSERT(a.getSize(0) == b.getSize(0));
+
+ // This uses the strided batch MM, which assumes a uniform stride
+ FAISS_ASSERT(a.getStride(0) == a.getSize(1) * a.getSize(2));
+ FAISS_ASSERT(b.getStride(0) == b.getSize(1) * b.getSize(2));
+ FAISS_ASSERT(c.getStride(0) == c.getSize(1) * c.getSize(2));
+
+ cublasSetStream(handle, stream);
+
+ // Check that we have (m x k) * (k x n) = (m x n)
+ // using the input row-major layout
+ int aM = transA ? a.getSize(2) : a.getSize(1);
+ int aK = transA ? a.getSize(1) : a.getSize(2);
+
+ int bK = transB ? b.getSize(2) : b.getSize(1);
+ int bN = transB ? b.getSize(1) : b.getSize(2);
+
+ int cM = transC ? c.getSize(2) : c.getSize(1);
+ int cN = transC ? c.getSize(1) : c.getSize(2);
+
+ FAISS_ASSERT(aM == cM);
+ FAISS_ASSERT(aK == bK);
+ FAISS_ASSERT(bN == cN);
+
+ // Now, we have to represent the matrix multiplication in
+ // column-major layout
+ void* pA = transC ? (void*)a.data() : (void*)b.data();
+ void* pB = transC ? (void*)b.data() : (void*)a.data();
+ float* pC = c.data();
+
+ int m = c.getSize(2); // stride 1 size
+ int n = c.getSize(1); // other size
+ int k = transA ? a.getSize(1) : a.getSize(2);
+
+ int lda = transC ? a.getStride(1) : b.getStride(1);
+ int ldb = transC ? b.getStride(1) : a.getStride(1);
+ int ldc = c.getStride(1);
+
+ auto gemmTrA = transB ? CUBLAS_OP_T : CUBLAS_OP_N;
+ auto gemmTrB = transA ? CUBLAS_OP_T : CUBLAS_OP_N;
+
+ if (transC) {
+ gemmTrA = transA ? CUBLAS_OP_N : CUBLAS_OP_T;
+ gemmTrB = transB ? CUBLAS_OP_N : CUBLAS_OP_T;
+ }
+
+ long long int gemmStrideA = transC ? a.getStride(0) : b.getStride(0);
+ long long int gemmStrideB = transC ? b.getStride(0) : a.getStride(0);
+ long long int gemmStrideC = c.getStride(0);
+
+ auto err = rawBatchGemm<AT, BT>(
+ handle,
+ gemmTrA,
+ gemmTrB,
+ m,
+ n,
+ k,
+ alpha,
+ pA,
+ lda,
+ gemmStrideA,
+ pB,
+ ldb,
+ gemmStrideB,
+ beta,
+ pC,
+ ldc,
+ gemmStrideC,
+ a.getSize(0));
+
+ FAISS_ASSERT_FMT(
+ err == CUBLAS_STATUS_SUCCESS,
+ "cublasGemmStridedBatchedEx failed (%d)",
+ (int)err);
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MatrixMult.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MatrixMult.cuh
new file mode 100644
index 0000000..28f0d41
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MatrixMult.cuh
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cublas_v2.h>
+#include <faiss/gpu/utils/DeviceTensor.cuh>
+#include <faiss/gpu/utils/Float16.cuh>
+#include <faiss/gpu/utils/HostTensor.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+class GpuResources;
+
+/// C = alpha * A * B + beta * C
+/// Expects row major layout, not fortran/blas column major!
+template <typename AT, typename BT>
+void runMatrixMult(
+ Tensor<float, 2, true>& c,
+ bool transC,
+ Tensor<AT, 2, true>& a,
+ bool transA,
+ Tensor<BT, 2, true>& b,
+ bool transB,
+ float alpha,
+ float beta,
+ cublasHandle_t handle,
+ cudaStream_t stream);
+
+/// C_i = alpha * A_i * B_i + beta * C_i
+/// where `i` is the outermost dimension, via iterated gemm
+/// Expects row major layout, not fortran/blas column major!
+template <typename AT, typename BT>
+void runIteratedMatrixMult(
+ Tensor<float, 3, true>& c,
+ bool transC,
+ Tensor<AT, 3, true>& a,
+ bool transA,
+ Tensor<BT, 3, true>& b,
+ bool transB,
+ float alpha,
+ float beta,
+ cublasHandle_t handle,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/utils/MatrixMult-inl.cuh>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh
new file mode 100644
index 0000000..dbc2308
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh
@@ -0,0 +1,321 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/MergeNetworkUtils.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// Merge pairs of lists smaller than blockDim.x (NumThreads)
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int N,
+ int L,
+ bool AllThreads,
+ bool Dir,
+ typename Comp,
+ bool FullMerge>
+inline __device__ void blockMergeSmall(K* listK, V* listV) {
+ static_assert(utils::isPowerOf2(L), "L must be a power-of-2");
+ static_assert(
+ utils::isPowerOf2(NumThreads), "NumThreads must be a power-of-2");
+ static_assert(L <= NumThreads, "merge list size must be <= NumThreads");
+
+ // Which pair of lists we are merging
+ int mergeId = threadIdx.x / L;
+
+ // Which thread we are within the merge
+ int tid = threadIdx.x % L;
+
+ // listK points to a region of size N * 2 * L
+ listK += 2 * L * mergeId;
+ listV += 2 * L * mergeId;
+
+ // It's not a bitonic merge, both lists are in the same direction,
+ // so handle the first swap assuming the second list is reversed
+ int pos = L - 1 - tid;
+ int stride = 2 * tid + 1;
+
+ if (AllThreads || (threadIdx.x < N * L)) {
+ K ka = listK[pos];
+ K kb = listK[pos + stride];
+
+ bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ listK[pos] = swap ? kb : ka;
+ listK[pos + stride] = swap ? ka : kb;
+
+ V va = listV[pos];
+ V vb = listV[pos + stride];
+ listV[pos] = swap ? vb : va;
+ listV[pos + stride] = swap ? va : vb;
+
+ // FIXME: is this a CUDA 9 compiler bug?
+ // K& ka = listK[pos];
+ // K& kb = listK[pos + stride];
+
+ // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ // swap(s, ka, kb);
+
+ // V& va = listV[pos];
+ // V& vb = listV[pos + stride];
+ // swap(s, va, vb);
+ }
+
+ __syncthreads();
+
+#pragma unroll
+ for (int stride = L / 2; stride > 0; stride /= 2) {
+ int pos = 2 * tid - (tid & (stride - 1));
+
+ if (AllThreads || (threadIdx.x < N * L)) {
+ K ka = listK[pos];
+ K kb = listK[pos + stride];
+
+ bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ listK[pos] = swap ? kb : ka;
+ listK[pos + stride] = swap ? ka : kb;
+
+ V va = listV[pos];
+ V vb = listV[pos + stride];
+ listV[pos] = swap ? vb : va;
+ listV[pos + stride] = swap ? va : vb;
+
+ // FIXME: is this a CUDA 9 compiler bug?
+ // K& ka = listK[pos];
+ // K& kb = listK[pos + stride];
+
+ // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ // swap(s, ka, kb);
+
+ // V& va = listV[pos];
+ // V& vb = listV[pos + stride];
+ // swap(s, va, vb);
+ }
+
+ __syncthreads();
+ }
+}
+
+// Merge pairs of sorted lists larger than blockDim.x (NumThreads)
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int L,
+ bool Dir,
+ typename Comp,
+ bool FullMerge>
+inline __device__ void blockMergeLarge(K* listK, V* listV) {
+ static_assert(utils::isPowerOf2(L), "L must be a power-of-2");
+ static_assert(L >= kWarpSize, "merge list size must be >= 32");
+ static_assert(
+ utils::isPowerOf2(NumThreads), "NumThreads must be a power-of-2");
+ static_assert(L >= NumThreads, "merge list size must be >= NumThreads");
+
+ // For L > NumThreads, each thread has to perform more work
+ // per each stride.
+ constexpr int kLoopPerThread = L / NumThreads;
+
+ // It's not a bitonic merge, both lists are in the same direction,
+ // so handle the first swap assuming the second list is reversed
+#pragma unroll
+ for (int loop = 0; loop < kLoopPerThread; ++loop) {
+ int tid = loop * NumThreads + threadIdx.x;
+ int pos = L - 1 - tid;
+ int stride = 2 * tid + 1;
+
+ K ka = listK[pos];
+ K kb = listK[pos + stride];
+
+ bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ listK[pos] = swap ? kb : ka;
+ listK[pos + stride] = swap ? ka : kb;
+
+ V va = listV[pos];
+ V vb = listV[pos + stride];
+ listV[pos] = swap ? vb : va;
+ listV[pos + stride] = swap ? va : vb;
+
+ // FIXME: is this a CUDA 9 compiler bug?
+ // K& ka = listK[pos];
+ // K& kb = listK[pos + stride];
+
+ // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ // swap(s, ka, kb);
+
+ // V& va = listV[pos];
+ // V& vb = listV[pos + stride];
+ // swap(s, va, vb);
+ }
+
+ __syncthreads();
+
+ constexpr int kSecondLoopPerThread =
+ FullMerge ? kLoopPerThread : kLoopPerThread / 2;
+
+#pragma unroll
+ for (int stride = L / 2; stride > 0; stride /= 2) {
+#pragma unroll
+ for (int loop = 0; loop < kSecondLoopPerThread; ++loop) {
+ int tid = loop * NumThreads + threadIdx.x;
+ int pos = 2 * tid - (tid & (stride - 1));
+
+ K ka = listK[pos];
+ K kb = listK[pos + stride];
+
+ bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ listK[pos] = swap ? kb : ka;
+ listK[pos + stride] = swap ? ka : kb;
+
+ V va = listV[pos];
+ V vb = listV[pos + stride];
+ listV[pos] = swap ? vb : va;
+ listV[pos + stride] = swap ? va : vb;
+
+ // FIXME: is this a CUDA 9 compiler bug?
+ // K& ka = listK[pos];
+ // K& kb = listK[pos + stride];
+
+ // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ // swap(s, ka, kb);
+
+ // V& va = listV[pos];
+ // V& vb = listV[pos + stride];
+ // swap(s, va, vb);
+ }
+
+ __syncthreads();
+ }
+}
+
+/// Class template to prevent static_assert from firing for
+/// mixing smaller/larger than block cases
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int N,
+ int L,
+ bool Dir,
+ typename Comp,
+ bool SmallerThanBlock,
+ bool FullMerge>
+struct BlockMerge {};
+
+/// Merging lists smaller than a block
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int N,
+ int L,
+ bool Dir,
+ typename Comp,
+ bool FullMerge>
+struct BlockMerge<NumThreads, K, V, N, L, Dir, Comp, true, FullMerge> {
+ static inline __device__ void merge(K* listK, V* listV) {
+ constexpr int kNumParallelMerges = NumThreads / L;
+ constexpr int kNumIterations = N / kNumParallelMerges;
+
+ static_assert(L <= NumThreads, "list must be <= NumThreads");
+ static_assert(
+ (N < kNumParallelMerges) ||
+ (kNumIterations * kNumParallelMerges == N),
+ "improper selection of N and L");
+
+ if (N < kNumParallelMerges) {
+ // We only need L threads per each list to perform the merge
+ blockMergeSmall<
+ NumThreads,
+ K,
+ V,
+ N,
+ L,
+ false,
+ Dir,
+ Comp,
+ FullMerge>(listK, listV);
+ } else {
+ // All threads participate
+#pragma unroll
+ for (int i = 0; i < kNumIterations; ++i) {
+ int start = i * kNumParallelMerges * 2 * L;
+
+ blockMergeSmall<
+ NumThreads,
+ K,
+ V,
+ N,
+ L,
+ true,
+ Dir,
+ Comp,
+ FullMerge>(listK + start, listV + start);
+ }
+ }
+ }
+};
+
+/// Merging lists larger than a block
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int N,
+ int L,
+ bool Dir,
+ typename Comp,
+ bool FullMerge>
+struct BlockMerge<NumThreads, K, V, N, L, Dir, Comp, false, FullMerge> {
+ static inline __device__ void merge(K* listK, V* listV) {
+ // Each pair of lists is merged sequentially
+#pragma unroll
+ for (int i = 0; i < N; ++i) {
+ int start = i * 2 * L;
+
+ blockMergeLarge<NumThreads, K, V, L, Dir, Comp, FullMerge>(
+ listK + start, listV + start);
+ }
+ }
+};
+
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int N,
+ int L,
+ bool Dir,
+ typename Comp,
+ bool FullMerge = true>
+inline __device__ void blockMerge(K* listK, V* listV) {
+ constexpr bool kSmallerThanBlock = (L <= NumThreads);
+
+ BlockMerge<
+ NumThreads,
+ K,
+ V,
+ N,
+ L,
+ Dir,
+ Comp,
+ kSmallerThanBlock,
+ FullMerge>::merge(listK, listV);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkUtils.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkUtils.cuh
new file mode 100644
index 0000000..44f4fd8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkUtils.cuh
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+inline __device__ void swap(bool swap, T& x, T& y) {
+ T tmp = x;
+ x = swap ? y : x;
+ y = swap ? tmp : y;
+}
+
+template <typename T>
+inline __device__ void assign(bool assign, T& x, T y) {
+ x = assign ? y : x;
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh
new file mode 100644
index 0000000..e48dd18
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh
@@ -0,0 +1,558 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/MergeNetworkUtils.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+namespace faiss {
+namespace gpu {
+
+//
+// This file contains functions to:
+//
+// -perform bitonic merges on pairs of sorted lists, held in
+// registers. Each list contains N * kWarpSize (multiple of 32)
+// elements for some N.
+// The bitonic merge is implemented for arbitrary sizes;
+// sorted list A of size N1 * kWarpSize registers
+// sorted list B of size N2 * kWarpSize registers =>
+// sorted list C if size (N1 + N2) * kWarpSize registers. N1 and N2
+// are >= 1 and don't have to be powers of 2.
+//
+// -perform bitonic sorts on a set of N * kWarpSize key/value pairs
+// held in registers, by using the above bitonic merge as a
+// primitive.
+// N can be an arbitrary N >= 1; i.e., the bitonic sort here supports
+// odd sizes and doesn't require the input to be a power of 2.
+//
+// The sort or merge network is completely statically instantiated via
+// template specialization / expansion and constexpr, and it uses warp
+// shuffles to exchange values between warp lanes.
+//
+// A note about comparsions:
+//
+// For a sorting network of keys only, we only need one
+// comparison (a < b). However, what we really need to know is
+// if one lane chooses to exchange a value, then the
+// corresponding lane should also do the exchange.
+// Thus, if one just uses the negation !(x < y) in the higher
+// lane, this will also include the case where (x == y). Thus, one
+// lane in fact performs an exchange and the other doesn't, but
+// because the only value being exchanged is equivalent, nothing has
+// changed.
+// So, you can get away with just one comparison and its negation.
+//
+// If we're sorting keys and values, where equivalent keys can
+// exist, then this is a problem, since we want to treat (x, v1)
+// as not equivalent to (x, v2).
+//
+// To remedy this, you can either compare with a lexicographic
+// ordering (a.k < b.k || (a.k == b.k && a.v < b.v)), which since
+// we're predicating all of the choices results in 3 comparisons
+// being executed, or we can invert the selection so that there is no
+// middle choice of equality; the other lane will likewise
+// check that (b.k > a.k) (the higher lane has the values
+// swapped). Then, the first lane swaps if and only if the
+// second lane swaps; if both lanes have equivalent keys, no
+// swap will be performed. This results in only two comparisons
+// being executed.
+//
+// If you don't consider values as well, then this does not produce a
+// consistent ordering among (k, v) pairs with equivalent keys but
+// different values; for us, we don't really care about ordering or
+// stability here.
+//
+// I have tried both re-arranging the order in the higher lane to get
+// away with one comparison or adding the value to the check; both
+// result in greater register consumption or lower speed than just
+// perfoming both < and > comparisons with the variables, so I just
+// stick with this.
+
+// This function merges kWarpSize / 2L lists in parallel using warp
+// shuffles.
+// It works on at most size-16 lists, as we need 32 threads for this
+// shuffle merge.
+//
+// If IsBitonic is false, the first stage is reversed, so we don't
+// need to sort directionally. It's still technically a bitonic sort.
+template <
+ typename K,
+ typename V,
+ int L,
+ bool Dir,
+ typename Comp,
+ bool IsBitonic>
+inline __device__ void warpBitonicMergeLE16(K& k, V& v) {
+ static_assert(utils::isPowerOf2(L), "L must be a power-of-2");
+ static_assert(L <= kWarpSize / 2, "merge list size must be <= 16");
+
+ int laneId = getLaneId();
+
+ if (!IsBitonic) {
+ // Reverse the first comparison stage.
+ // For example, merging a list of size 8 has the exchanges:
+ // 0 <-> 15, 1 <-> 14, ...
+ K otherK = shfl_xor(k, 2 * L - 1);
+ V otherV = shfl_xor(v, 2 * L - 1);
+
+ // Whether we are the lesser thread in the exchange
+ bool small = !(laneId & L);
+
+ if (Dir) {
+ // See the comment above how performing both of these
+ // comparisons in the warp seems to win out over the
+ // alternatives in practice
+ bool s = small ? Comp::gt(k, otherK) : Comp::lt(k, otherK);
+ assign(s, k, otherK);
+ assign(s, v, otherV);
+
+ } else {
+ bool s = small ? Comp::lt(k, otherK) : Comp::gt(k, otherK);
+ assign(s, k, otherK);
+ assign(s, v, otherV);
+ }
+ }
+
+#pragma unroll
+ for (int stride = IsBitonic ? L : L / 2; stride > 0; stride /= 2) {
+ K otherK = shfl_xor(k, stride);
+ V otherV = shfl_xor(v, stride);
+
+ // Whether we are the lesser thread in the exchange
+ bool small = !(laneId & stride);
+
+ if (Dir) {
+ bool s = small ? Comp::gt(k, otherK) : Comp::lt(k, otherK);
+ assign(s, k, otherK);
+ assign(s, v, otherV);
+
+ } else {
+ bool s = small ? Comp::lt(k, otherK) : Comp::gt(k, otherK);
+ assign(s, k, otherK);
+ assign(s, v, otherV);
+ }
+ }
+}
+
+// Template for performing a bitonic merge of an arbitrary set of
+// registers
+template <
+ typename K,
+ typename V,
+ int N,
+ bool Dir,
+ typename Comp,
+ bool Low,
+ bool Pow2>
+struct BitonicMergeStep {};
+
+//
+// Power-of-2 merge specialization
+//
+
+// All merges eventually call this
+template <typename K, typename V, bool Dir, typename Comp, bool Low>
+struct BitonicMergeStep<K, V, 1, Dir, Comp, Low, true> {
+ static inline __device__ void merge(K k[1], V v[1]) {
+ // Use warp shuffles
+ if constexpr (kWarpSize == 32) {
+ warpBitonicMergeLE16<K, V, 16, Dir, Comp, true>(k[0], v[0]);
+ } else {
+ warpBitonicMergeLE16<K, V, 32, Dir, Comp, true>(k[0], v[0]);
+ }
+ }
+};
+
+template <typename K, typename V, int N, bool Dir, typename Comp, bool Low>
+struct BitonicMergeStep<K, V, N, Dir, Comp, Low, true> {
+ static inline __device__ void merge(K k[N], V v[N]) {
+ static_assert(utils::isPowerOf2(N), "must be power of 2");
+ static_assert(N > 1, "must be N > 1");
+
+#pragma unroll
+ for (int i = 0; i < N / 2; ++i) {
+ K& ka = k[i];
+ V& va = v[i];
+
+ K& kb = k[i + N / 2];
+ V& vb = v[i + N / 2];
+
+ bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ swap(s, ka, kb);
+ swap(s, va, vb);
+ }
+
+ {
+ K newK[N / 2];
+ V newV[N / 2];
+
+#pragma unroll
+ for (int i = 0; i < N / 2; ++i) {
+ newK[i] = k[i];
+ newV[i] = v[i];
+ }
+
+ BitonicMergeStep<K, V, N / 2, Dir, Comp, true, true>::merge(
+ newK, newV);
+
+#pragma unroll
+ for (int i = 0; i < N / 2; ++i) {
+ k[i] = newK[i];
+ v[i] = newV[i];
+ }
+ }
+
+ {
+ K newK[N / 2];
+ V newV[N / 2];
+
+#pragma unroll
+ for (int i = 0; i < N / 2; ++i) {
+ newK[i] = k[i + N / 2];
+ newV[i] = v[i + N / 2];
+ }
+
+ BitonicMergeStep<K, V, N / 2, Dir, Comp, false, true>::merge(
+ newK, newV);
+
+#pragma unroll
+ for (int i = 0; i < N / 2; ++i) {
+ k[i + N / 2] = newK[i];
+ v[i + N / 2] = newV[i];
+ }
+ }
+ }
+};
+
+//
+// Non-power-of-2 merge specialization
+//
+
+// Low recursion
+template <typename K, typename V, int N, bool Dir, typename Comp>
+struct BitonicMergeStep<K, V, N, Dir, Comp, true, false> {
+ static inline __device__ void merge(K k[N], V v[N]) {
+ static_assert(!utils::isPowerOf2(N), "must be non-power-of-2");
+ static_assert(N >= 3, "must be N >= 3");
+
+ constexpr int kNextHighestPowerOf2 = utils::nextHighestPowerOf2(N);
+
+#pragma unroll
+ for (int i = 0; i < N - kNextHighestPowerOf2 / 2; ++i) {
+ K& ka = k[i];
+ V& va = v[i];
+
+ K& kb = k[i + kNextHighestPowerOf2 / 2];
+ V& vb = v[i + kNextHighestPowerOf2 / 2];
+
+ bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ swap(s, ka, kb);
+ swap(s, va, vb);
+ }
+
+ constexpr int kLowSize = N - kNextHighestPowerOf2 / 2;
+ constexpr int kHighSize = kNextHighestPowerOf2 / 2;
+ {
+ K newK[kLowSize];
+ V newV[kLowSize];
+
+#pragma unroll
+ for (int i = 0; i < kLowSize; ++i) {
+ newK[i] = k[i];
+ newV[i] = v[i];
+ }
+
+ constexpr bool kLowIsPowerOf2 =
+ utils::isPowerOf2(N - kNextHighestPowerOf2 / 2);
+ // FIXME: compiler doesn't like this expression? compiler bug?
+ // constexpr bool kLowIsPowerOf2 = utils::isPowerOf2(kLowSize);
+ BitonicMergeStep<
+ K,
+ V,
+ kLowSize,
+ Dir,
+ Comp,
+ true, // low
+ kLowIsPowerOf2>::merge(newK, newV);
+
+#pragma unroll
+ for (int i = 0; i < kLowSize; ++i) {
+ k[i] = newK[i];
+ v[i] = newV[i];
+ }
+ }
+
+ {
+ K newK[kHighSize];
+ V newV[kHighSize];
+
+#pragma unroll
+ for (int i = 0; i < kHighSize; ++i) {
+ newK[i] = k[i + kLowSize];
+ newV[i] = v[i + kLowSize];
+ }
+
+ constexpr bool kHighIsPowerOf2 =
+ utils::isPowerOf2(kNextHighestPowerOf2 / 2);
+ // FIXME: compiler doesn't like this expression? compiler bug?
+ // constexpr bool kHighIsPowerOf2 =
+ // utils::isPowerOf2(kHighSize);
+ BitonicMergeStep<
+ K,
+ V,
+ kHighSize,
+ Dir,
+ Comp,
+ false, // high
+ kHighIsPowerOf2>::merge(newK, newV);
+
+#pragma unroll
+ for (int i = 0; i < kHighSize; ++i) {
+ k[i + kLowSize] = newK[i];
+ v[i + kLowSize] = newV[i];
+ }
+ }
+ }
+};
+
+// High recursion
+template <typename K, typename V, int N, bool Dir, typename Comp>
+struct BitonicMergeStep<K, V, N, Dir, Comp, false, false> {
+ static inline __device__ void merge(K k[N], V v[N]) {
+ static_assert(!utils::isPowerOf2(N), "must be non-power-of-2");
+ static_assert(N >= 3, "must be N >= 3");
+
+ constexpr int kNextHighestPowerOf2 = utils::nextHighestPowerOf2(N);
+
+#pragma unroll
+ for (int i = 0; i < N - kNextHighestPowerOf2 / 2; ++i) {
+ K& ka = k[i];
+ V& va = v[i];
+
+ K& kb = k[i + kNextHighestPowerOf2 / 2];
+ V& vb = v[i + kNextHighestPowerOf2 / 2];
+
+ bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb);
+ swap(s, ka, kb);
+ swap(s, va, vb);
+ }
+
+ constexpr int kLowSize = kNextHighestPowerOf2 / 2;
+ constexpr int kHighSize = N - kNextHighestPowerOf2 / 2;
+ {
+ K newK[kLowSize];
+ V newV[kLowSize];
+
+#pragma unroll
+ for (int i = 0; i < kLowSize; ++i) {
+ newK[i] = k[i];
+ newV[i] = v[i];
+ }
+
+ constexpr bool kLowIsPowerOf2 =
+ utils::isPowerOf2(kNextHighestPowerOf2 / 2);
+ // FIXME: compiler doesn't like this expression? compiler bug?
+ // constexpr bool kLowIsPowerOf2 = utils::isPowerOf2(kLowSize);
+ BitonicMergeStep<
+ K,
+ V,
+ kLowSize,
+ Dir,
+ Comp,
+ true, // low
+ kLowIsPowerOf2>::merge(newK, newV);
+
+#pragma unroll
+ for (int i = 0; i < kLowSize; ++i) {
+ k[i] = newK[i];
+ v[i] = newV[i];
+ }
+ }
+
+ {
+ K newK[kHighSize];
+ V newV[kHighSize];
+
+#pragma unroll
+ for (int i = 0; i < kHighSize; ++i) {
+ newK[i] = k[i + kLowSize];
+ newV[i] = v[i + kLowSize];
+ }
+
+ constexpr bool kHighIsPowerOf2 =
+ utils::isPowerOf2(N - kNextHighestPowerOf2 / 2);
+ // FIXME: compiler doesn't like this expression? compiler bug?
+ // constexpr bool kHighIsPowerOf2 =
+ // utils::isPowerOf2(kHighSize);
+ BitonicMergeStep<
+ K,
+ V,
+ kHighSize,
+ Dir,
+ Comp,
+ false, // high
+ kHighIsPowerOf2>::merge(newK, newV);
+
+#pragma unroll
+ for (int i = 0; i < kHighSize; ++i) {
+ k[i + kLowSize] = newK[i];
+ v[i + kLowSize] = newV[i];
+ }
+ }
+ }
+};
+
+/// Merges two sets of registers across the warp of any size;
+/// i.e., merges a sorted k/v list of size kWarpSize * N1 with a
+/// sorted k/v list of size kWarpSize * N2, where N1 and N2 are any
+/// value >= 1
+template <
+ typename K,
+ typename V,
+ int N1,
+ int N2,
+ bool Dir,
+ typename Comp,
+ bool FullMerge = true>
+inline __device__ void warpMergeAnyRegisters(
+ K k1[N1],
+ V v1[N1],
+ K k2[N2],
+ V v2[N2]) {
+ constexpr int kSmallestN = N1 < N2 ? N1 : N2;
+
+#pragma unroll
+ for (int i = 0; i < kSmallestN; ++i) {
+ K& ka = k1[N1 - 1 - i];
+ V& va = v1[N1 - 1 - i];
+
+ K& kb = k2[i];
+ V& vb = v2[i];
+
+ K otherKa;
+ V otherVa;
+
+ if (FullMerge) {
+ // We need the other values
+ otherKa = shfl_xor(ka, kWarpSize - 1);
+ otherVa = shfl_xor(va, kWarpSize - 1);
+ }
+
+ K otherKb = shfl_xor(kb, kWarpSize - 1);
+ V otherVb = shfl_xor(vb, kWarpSize - 1);
+
+ // ka is always first in the list, so we needn't use our lane
+ // in this comparison
+ bool swapa = Dir ? Comp::gt(ka, otherKb) : Comp::lt(ka, otherKb);
+ assign(swapa, ka, otherKb);
+ assign(swapa, va, otherVb);
+
+ // kb is always second in the list, so we needn't use our lane
+ // in this comparison
+ if (FullMerge) {
+ bool swapb = Dir ? Comp::lt(kb, otherKa) : Comp::gt(kb, otherKa);
+ assign(swapb, kb, otherKa);
+ assign(swapb, vb, otherVa);
+
+ } else {
+ // We don't care about updating elements in the second list
+ }
+ }
+
+ BitonicMergeStep<K, V, N1, Dir, Comp, true, utils::isPowerOf2(N1)>::merge(
+ k1, v1);
+ if (FullMerge) {
+ // Only if we care about N2 do we need to bother merging it fully
+ BitonicMergeStep<K, V, N2, Dir, Comp, false, utils::isPowerOf2(N2)>::
+ merge(k2, v2);
+ }
+}
+
+// Recursive template that uses the above bitonic merge to perform a
+// bitonic sort
+template <typename K, typename V, int N, bool Dir, typename Comp>
+struct BitonicSortStep {
+ static inline __device__ void sort(K k[N], V v[N]) {
+ static_assert(N > 1, "did not hit specialized case");
+
+ // Sort recursively
+ constexpr int kSizeA = N / 2;
+ constexpr int kSizeB = N - kSizeA;
+
+ K aK[kSizeA];
+ V aV[kSizeA];
+
+#pragma unroll
+ for (int i = 0; i < kSizeA; ++i) {
+ aK[i] = k[i];
+ aV[i] = v[i];
+ }
+
+ BitonicSortStep<K, V, kSizeA, Dir, Comp>::sort(aK, aV);
+
+ K bK[kSizeB];
+ V bV[kSizeB];
+
+#pragma unroll
+ for (int i = 0; i < kSizeB; ++i) {
+ bK[i] = k[i + kSizeA];
+ bV[i] = v[i + kSizeA];
+ }
+
+ BitonicSortStep<K, V, kSizeB, Dir, Comp>::sort(bK, bV);
+
+ // Merge halves
+ warpMergeAnyRegisters<K, V, kSizeA, kSizeB, Dir, Comp>(aK, aV, bK, bV);
+
+#pragma unroll
+ for (int i = 0; i < kSizeA; ++i) {
+ k[i] = aK[i];
+ v[i] = aV[i];
+ }
+
+#pragma unroll
+ for (int i = 0; i < kSizeB; ++i) {
+ k[i + kSizeA] = bK[i];
+ v[i + kSizeA] = bV[i];
+ }
+ }
+};
+
+// Single warp (N == 1) sorting specialization
+template <typename K, typename V, bool Dir, typename Comp>
+struct BitonicSortStep<K, V, 1, Dir, Comp> {
+ static inline __device__ void sort(K k[1], V v[1]) {
+ // Update this code if this changes
+ // should go from 1 -> kWarpSize in multiples of 2
+ static_assert(
+ kWarpSize == 32 || kWarpSize == 64, "unexpected warp size");
+
+ warpBitonicMergeLE16<K, V, 1, Dir, Comp, false>(k[0], v[0]);
+ warpBitonicMergeLE16<K, V, 2, Dir, Comp, false>(k[0], v[0]);
+ warpBitonicMergeLE16<K, V, 4, Dir, Comp, false>(k[0], v[0]);
+ warpBitonicMergeLE16<K, V, 8, Dir, Comp, false>(k[0], v[0]);
+ warpBitonicMergeLE16<K, V, 16, Dir, Comp, false>(k[0], v[0]);
+ if constexpr (kWarpSize == 64) {
+ warpBitonicMergeLE16<K, V, 32, Dir, Comp, false>(k[0], v[0]);
+ }
+ }
+};
+
+/// Sort a list of kWarpSize * N elements in registers, where N is an
+/// arbitrary >= 1
+template <typename K, typename V, int N, bool Dir, typename Comp>
+inline __device__ void warpSortAnyRegisters(K k[N], V v[N]) {
+ BitonicSortStep<K, V, N, Dir, Comp>::sort(k, v);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/NoTypeTensor.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/NoTypeTensor.cuh
new file mode 100644
index 0000000..9867111
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/NoTypeTensor.cuh
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/gpu/utils/Tensor.cuh>
+#include <initializer_list>
+
+namespace faiss {
+namespace gpu {
+
+template <int Dim, bool InnerContig = false, typename IndexT = idx_t>
+class NoTypeTensor {
+ public:
+ NoTypeTensor() : mem_(nullptr), typeSize_(0) {}
+
+ template <typename T>
+ NoTypeTensor(Tensor<T, Dim, InnerContig, IndexT>& t)
+ : mem_(t.data()), typeSize_(sizeof(T)) {
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = t.getSize(i);
+ stride_[i] = t.getStride(i);
+ }
+ }
+
+ NoTypeTensor(void* mem, int typeSize, std::initializer_list<IndexT> sizes)
+ : mem_(mem), typeSize_(typeSize) {
+ int i = 0;
+ for (auto s : sizes) {
+ size_[i++] = s;
+ }
+
+ stride_[Dim - 1] = (IndexT)1;
+ for (int j = Dim - 2; j >= 0; --j) {
+ stride_[j] = stride_[j + 1] * size_[j + 1];
+ }
+ }
+
+ NoTypeTensor(void* mem, int typeSize, IndexT sizes[Dim])
+ : mem_(mem), typeSize_(typeSize) {
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = sizes[i];
+ }
+
+ stride_[Dim - 1] = (IndexT)1;
+ for (int i = Dim - 2; i >= 0; --i) {
+ stride_[i] = stride_[i + 1] * sizes[i + 1];
+ }
+ }
+
+ NoTypeTensor(
+ void* mem,
+ int typeSize,
+ IndexT sizes[Dim],
+ IndexT strides[Dim])
+ : mem_(mem), typeSize_(typeSize) {
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = sizes[i];
+ stride_[i] = strides[i];
+ }
+ }
+
+ int getTypeSize() const {
+ return typeSize_;
+ }
+
+ IndexT getSize(int dim) const {
+ FAISS_ASSERT(dim < Dim);
+ return size_[dim];
+ }
+
+ IndexT getStride(int dim) const {
+ FAISS_ASSERT(dim < Dim);
+ return stride_[dim];
+ }
+
+ template <typename T>
+ Tensor<T, Dim, InnerContig, IndexT> toTensor() {
+ FAISS_ASSERT(sizeof(T) == typeSize_);
+
+ return Tensor<T, Dim, InnerContig, IndexT>((T*)mem_, size_, stride_);
+ }
+
+ NoTypeTensor<Dim, InnerContig, IndexT> narrowOutermost(
+ IndexT start,
+ IndexT size) {
+ char* newPtr = (char*)mem_;
+
+ if (start > 0) {
+ newPtr += typeSize_ * start * stride_[0];
+ }
+
+ IndexT newSize[Dim];
+ for (int i = 0; i < Dim; ++i) {
+ if (i == 0) {
+ assert(start + size <= size_[0]);
+ newSize[i] = size;
+ } else {
+ newSize[i] = size_[i];
+ }
+ }
+
+ return NoTypeTensor<Dim, InnerContig, IndexT>(
+ newPtr, typeSize_, newSize, stride_);
+ }
+
+ private:
+ void* mem_;
+ int typeSize_;
+ IndexT size_[Dim];
+ IndexT stride_[Dim];
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Pair.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Pair.cuh
new file mode 100644
index 0000000..8c7a6e6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Pair.cuh
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+namespace faiss {
+namespace gpu {
+
+/// A simple pair type for CUDA device usage
+template <typename K, typename V>
+struct Pair {
+ constexpr __device__ inline Pair() {}
+
+ constexpr __device__ inline Pair(K key, V value) : k(key), v(value) {}
+
+ __device__ inline bool operator==(const Pair<K, V>& rhs) const {
+ return Math<K>::eq(k, rhs.k) && Math<V>::eq(v, rhs.v);
+ }
+
+ __device__ inline bool operator!=(const Pair<K, V>& rhs) const {
+ return !operator==(rhs);
+ }
+
+ __device__ inline bool operator<(const Pair<K, V>& rhs) const {
+ return Math<K>::lt(k, rhs.k) ||
+ (Math<K>::eq(k, rhs.k) && Math<V>::lt(v, rhs.v));
+ }
+
+ __device__ inline bool operator>(const Pair<K, V>& rhs) const {
+ return Math<K>::gt(k, rhs.k) ||
+ (Math<K>::eq(k, rhs.k) && Math<V>::gt(v, rhs.v));
+ }
+
+ K k;
+ V v;
+};
+
+template <typename T, typename U>
+inline __device__ Pair<T, U> shfl_up(
+ const Pair<T, U>& pair,
+ unsigned int delta,
+ int width = kWarpSize) {
+ return Pair<T, U>(
+ shfl_up(pair.k, delta, width), shfl_up(pair.v, delta, width));
+}
+
+template <typename T, typename U>
+inline __device__ Pair<T, U> shfl_xor(
+ const Pair<T, U>& pair,
+ int laneMask,
+ int width = kWarpSize) {
+ return Pair<T, U>(
+ shfl_xor(pair.k, laneMask, width),
+ shfl_xor(pair.v, laneMask, width));
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/PtxUtils.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/PtxUtils.cuh
new file mode 100644
index 0000000..c40fea2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/PtxUtils.cuh
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#ifdef USE_AMD_ROCM
+#include <device_functions.h>
+#endif
+
+namespace faiss {
+namespace gpu {
+
+#ifdef USE_AMD_ROCM
+
+#define GET_BITFIELD_U32(OUT, VAL, POS, LEN) \
+ do { \
+ OUT = getBitfield((uint32_t)VAL, POS, LEN); \
+ } while (0)
+
+#define GET_BITFIELD_U64(OUT, VAL, POS, LEN) \
+ do { \
+ OUT = getBitfield((uint64_t)VAL, POS, LEN); \
+ } while (0)
+
+__device__ __forceinline__ uint32_t
+getBitfield(uint32_t val, int pos, int len) {
+ return __bitextract_u32(val, pos, len);
+}
+
+__device__ __forceinline__ uint64_t
+getBitfield(uint64_t val, int pos, int len) {
+ return __bitextract_u64(val, pos, len);
+}
+
+__device__ __forceinline__ unsigned int setBitfield(
+ unsigned int val,
+ unsigned int toInsert,
+ int pos,
+ int len) {
+ unsigned int ret{0};
+ printf("Runtime Error of %s: Unimplemented\n", __PRETTY_FUNCTION__);
+ return ret;
+}
+
+__device__ __forceinline__ int getLaneId() {
+ return ::__lane_id();
+}
+
+#else // USE_AMD_ROCM
+
+// defines to simplify the SASS assembly structure file/line in the profiler
+#define GET_BITFIELD_U32(OUT, VAL, POS, LEN) \
+ asm("bfe.u32 %0, %1, %2, %3;" : "=r"(OUT) : "r"(VAL), "r"(POS), "r"(LEN));
+
+#define GET_BITFIELD_U64(OUT, VAL, POS, LEN) \
+ asm("bfe.u64 %0, %1, %2, %3;" : "=l"(OUT) : "l"(VAL), "r"(POS), "r"(LEN));
+
+__device__ __forceinline__ unsigned int getBitfield(
+ unsigned int val,
+ int pos,
+ int len) {
+ unsigned int ret;
+ asm("bfe.u32 %0, %1, %2, %3;" : "=r"(ret) : "r"(val), "r"(pos), "r"(len));
+ return ret;
+}
+
+__device__ __forceinline__ uint64_t
+getBitfield(uint64_t val, int pos, int len) {
+ uint64_t ret;
+ asm("bfe.u64 %0, %1, %2, %3;" : "=l"(ret) : "l"(val), "r"(pos), "r"(len));
+ return ret;
+}
+
+__device__ __forceinline__ unsigned int setBitfield(
+ unsigned int val,
+ unsigned int toInsert,
+ int pos,
+ int len) {
+ unsigned int ret;
+ asm("bfi.b32 %0, %1, %2, %3, %4;"
+ : "=r"(ret)
+ : "r"(toInsert), "r"(val), "r"(pos), "r"(len));
+ return ret;
+}
+
+__device__ __forceinline__ int getLaneId() {
+ int laneId;
+ asm("mov.u32 %0, %%laneid;" : "=r"(laneId));
+ return laneId;
+}
+
+__device__ __forceinline__ unsigned getLaneMaskLt() {
+ unsigned mask;
+ asm("mov.u32 %0, %%lanemask_lt;" : "=r"(mask));
+ return mask;
+}
+
+__device__ __forceinline__ unsigned getLaneMaskLe() {
+ unsigned mask;
+ asm("mov.u32 %0, %%lanemask_le;" : "=r"(mask));
+ return mask;
+}
+
+__device__ __forceinline__ unsigned getLaneMaskGt() {
+ unsigned mask;
+ asm("mov.u32 %0, %%lanemask_gt;" : "=r"(mask));
+ return mask;
+}
+
+__device__ __forceinline__ unsigned getLaneMaskGe() {
+ unsigned mask;
+ asm("mov.u32 %0, %%lanemask_ge;" : "=r"(mask));
+ return mask;
+}
+
+__device__ __forceinline__ void namedBarrierWait(int name, int numThreads) {
+ asm volatile("bar.sync %0, %1;" : : "r"(name), "r"(numThreads) : "memory");
+}
+
+__device__ __forceinline__ void namedBarrierArrived(int name, int numThreads) {
+ asm volatile("bar.arrive %0, %1;"
+ :
+ : "r"(name), "r"(numThreads)
+ : "memory");
+}
+
+#endif // USE_AMD_ROCM
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ReductionOperators.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ReductionOperators.cuh
new file mode 100644
index 0000000..8e721a1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ReductionOperators.cuh
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/Limits.cuh>
+#include <faiss/gpu/utils/MathOperators.cuh>
+#include <faiss/gpu/utils/Pair.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+struct Sum {
+ __device__ inline T operator()(T a, T b) const {
+ return Math<T>::add(a, b);
+ }
+
+ inline __device__ T identity() const {
+ return Math<T>::zero();
+ }
+};
+
+template <typename T>
+struct Min {
+ __device__ inline T operator()(T a, T b) const {
+ return Math<T>::lt(a, b) ? a : b;
+ }
+
+ inline __device__ T identity() const {
+ return Limits<T>::getMax();
+ }
+};
+
+template <typename T>
+struct Max {
+ __device__ inline T operator()(T a, T b) const {
+ return Math<T>::gt(a, b) ? a : b;
+ }
+
+ inline __device__ T identity() const {
+ return Limits<T>::getMin();
+ }
+};
+
+/// Used for producing segmented prefix scans; the value of the Pair
+/// denotes the start of a new segment for the scan
+template <typename T, typename ReduceOp>
+struct SegmentedReduce {
+ inline __device__ SegmentedReduce(const ReduceOp& o) : op(o) {}
+
+ __device__ inline Pair<T, bool> operator()(
+ const Pair<T, bool>& a,
+ const Pair<T, bool>& b) const {
+ return Pair<T, bool>(b.v ? b.k : op(a.k, b.k), a.v || b.v);
+ }
+
+ inline __device__ Pair<T, bool> identity() const {
+ return Pair<T, bool>(op.identity(), false);
+ }
+
+ ReduceOp op;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Reductions.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Reductions.cuh
new file mode 100644
index 0000000..8f31c4a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Reductions.cuh
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/ReductionOperators.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T, typename Op, int ReduceWidth = kWarpSize>
+__device__ inline T warpReduceAll(T val, Op op) {
+#pragma unroll
+ for (int mask = ReduceWidth / 2; mask > 0; mask >>= 1) {
+ val = op(val, shfl_xor(val, mask));
+ }
+
+ return val;
+}
+
+/// Sums a register value across all warp threads
+template <typename T, int ReduceWidth = kWarpSize>
+__device__ inline T warpReduceAllSum(T val) {
+ return warpReduceAll<T, Sum<T>, ReduceWidth>(val, Sum<T>());
+}
+
+/// Performs a block-wide reduction
+template <typename T, typename Op, bool BroadcastAll, bool KillWARDependency>
+__device__ inline T blockReduceAll(T val, Op op, T* smem) {
+ int laneId = getLaneId();
+ int warpId = threadIdx.x / kWarpSize;
+
+ val = warpReduceAll<T, Op>(val, op);
+ if (laneId == 0) {
+ smem[warpId] = val;
+ }
+ __syncthreads();
+
+ if (warpId == 0) {
+ val = laneId < utils::divUp(blockDim.x, kWarpSize) ? smem[laneId]
+ : op.identity();
+ val = warpReduceAll<T, Op>(val, op);
+
+ if (BroadcastAll) {
+ __threadfence_block();
+
+ if (laneId == 0) {
+ smem[0] = val;
+ }
+ }
+ }
+
+ if (BroadcastAll) {
+ __syncthreads();
+ val = smem[0];
+ }
+
+ if (KillWARDependency) {
+ __syncthreads();
+ }
+
+ return val;
+}
+
+/// Performs a block-wide reduction of multiple values simultaneously
+template <
+ int Num,
+ typename T,
+ typename Op,
+ bool BroadcastAll,
+ bool KillWARDependency>
+__device__ inline void blockReduceAll(T val[Num], Op op, T* smem) {
+ int laneId = getLaneId();
+ int warpId = threadIdx.x / kWarpSize;
+
+#pragma unroll
+ for (int i = 0; i < Num; ++i) {
+ val[i] = warpReduceAll<T, Op>(val[i], op);
+ }
+
+ if (laneId == 0) {
+#pragma unroll
+ for (int i = 0; i < Num; ++i) {
+ smem[warpId * Num + i] = val[i];
+ }
+ }
+
+ __syncthreads();
+
+ if (warpId == 0) {
+#pragma unroll
+ for (int i = 0; i < Num; ++i) {
+ val[i] = laneId < utils::divUp(blockDim.x, kWarpSize)
+ ? smem[laneId * Num + i]
+ : op.identity();
+ val[i] = warpReduceAll<T, Op>(val[i], op);
+ }
+
+ if (BroadcastAll) {
+ __threadfence_block();
+
+ if (laneId == 0) {
+#pragma unroll
+ for (int i = 0; i < Num; ++i) {
+ smem[i] = val[i];
+ }
+ }
+ }
+ }
+
+ if (BroadcastAll) {
+ __syncthreads();
+#pragma unroll
+ for (int i = 0; i < Num; ++i) {
+ val[i] = smem[i];
+ }
+ }
+
+ if (KillWARDependency) {
+ __syncthreads();
+ }
+}
+
+/// Sums a register value across the entire block
+template <typename T, bool BroadcastAll, bool KillWARDependency>
+__device__ inline T blockReduceAllSum(T val, T* smem) {
+ return blockReduceAll<T, Sum<T>, BroadcastAll, KillWARDependency>(
+ val, Sum<T>(), smem);
+}
+
+template <int Num, typename T, bool BroadcastAll, bool KillWARDependency>
+__device__ inline void blockReduceAllSum(T vals[Num], T* smem) {
+ return blockReduceAll<Num, T, Sum<T>, BroadcastAll, KillWARDependency>(
+ vals, Sum<T>(), smem);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Select.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Select.cuh
new file mode 100644
index 0000000..19ae65e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Select.cuh
@@ -0,0 +1,647 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Comparators.cuh>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/MergeNetworkBlock.cuh>
+#include <faiss/gpu/utils/MergeNetworkWarp.cuh>
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/ReductionOperators.cuh>
+#include <faiss/gpu/utils/Reductions.cuh>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// Specialization for block-wide monotonic merges producing a merge sort
+// since what we really want is a constexpr loop expansion
+template <
+ int NumWarps,
+ int NumThreads,
+ typename K,
+ typename V,
+ int NumWarpQ,
+ bool Dir,
+ typename Comp>
+struct FinalBlockMerge {};
+
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int NumWarpQ,
+ bool Dir,
+ typename Comp>
+struct FinalBlockMerge<1, NumThreads, K, V, NumWarpQ, Dir, Comp> {
+ static inline __device__ void merge(K* sharedK, V* sharedV) {
+ // no merge required; single warp
+ }
+};
+
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int NumWarpQ,
+ bool Dir,
+ typename Comp>
+struct FinalBlockMerge<2, NumThreads, K, V, NumWarpQ, Dir, Comp> {
+ static inline __device__ void merge(K* sharedK, V* sharedV) {
+ // Final merge doesn't need to fully merge the second list
+ blockMerge<
+ NumThreads,
+ K,
+ V,
+ NumThreads / (kWarpSize * 2),
+ NumWarpQ,
+ !Dir,
+ Comp,
+ false>(sharedK, sharedV);
+ }
+};
+
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int NumWarpQ,
+ bool Dir,
+ typename Comp>
+struct FinalBlockMerge<4, NumThreads, K, V, NumWarpQ, Dir, Comp> {
+ static inline __device__ void merge(K* sharedK, V* sharedV) {
+ blockMerge<
+ NumThreads,
+ K,
+ V,
+ NumThreads / (kWarpSize * 2),
+ NumWarpQ,
+ !Dir,
+ Comp>(sharedK, sharedV);
+ // Final merge doesn't need to fully merge the second list
+ blockMerge<
+ NumThreads,
+ K,
+ V,
+ NumThreads / (kWarpSize * 4),
+ NumWarpQ * 2,
+ !Dir,
+ Comp,
+ false>(sharedK, sharedV);
+ }
+};
+
+template <
+ int NumThreads,
+ typename K,
+ typename V,
+ int NumWarpQ,
+ bool Dir,
+ typename Comp>
+struct FinalBlockMerge<8, NumThreads, K, V, NumWarpQ, Dir, Comp> {
+ static inline __device__ void merge(K* sharedK, V* sharedV) {
+ blockMerge<
+ NumThreads,
+ K,
+ V,
+ NumThreads / (kWarpSize * 2),
+ NumWarpQ,
+ !Dir,
+ Comp>(sharedK, sharedV);
+ blockMerge<
+ NumThreads,
+ K,
+ V,
+ NumThreads / (kWarpSize * 4),
+ NumWarpQ * 2,
+ !Dir,
+ Comp>(sharedK, sharedV);
+ // Final merge doesn't need to fully merge the second list
+ blockMerge<
+ NumThreads,
+ K,
+ V,
+ NumThreads / (kWarpSize * 8),
+ NumWarpQ * 4,
+ !Dir,
+ Comp,
+ false>(sharedK, sharedV);
+ }
+};
+
+// `Dir` true, produce largest values.
+// `Dir` false, produce smallest values.
+template <
+ typename K,
+ typename V,
+ bool Dir,
+ typename Comp,
+ int NumWarpQ,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+struct BlockSelect {
+ static constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+ static constexpr int kTotalWarpSortSize = NumWarpQ;
+
+ __device__ inline BlockSelect(
+ K initKVal,
+ V initVVal,
+ K* smemK,
+ V* smemV,
+ int k)
+ : initK(initKVal),
+ initV(initVVal),
+ numVals(0),
+ warpKTop(initKVal),
+ sharedK(smemK),
+ sharedV(smemV),
+ kMinus1(k - 1) {
+ static_assert(
+ utils::isPowerOf2(ThreadsPerBlock),
+ "threads must be a power-of-2");
+ static_assert(
+ utils::isPowerOf2(NumWarpQ), "warp queue must be power-of-2");
+
+ // Fill the per-thread queue keys with the default value
+#pragma unroll
+ for (int i = 0; i < NumThreadQ; ++i) {
+ threadK[i] = initK;
+ threadV[i] = initV;
+ }
+
+ int laneId = getLaneId();
+ int warpId = threadIdx.x / kWarpSize;
+ warpK = sharedK + warpId * kTotalWarpSortSize;
+ warpV = sharedV + warpId * kTotalWarpSortSize;
+
+ // Fill warp queue (only the actual queue space is fine, not where
+ // we write the per-thread queues for merging)
+ for (int i = laneId; i < NumWarpQ; i += kWarpSize) {
+ warpK[i] = initK;
+ warpV[i] = initV;
+ }
+
+ warpFence();
+ }
+
+ __device__ inline void addThreadQ(K k, V v) {
+ if (Dir ? Comp::gt(k, warpKTop) : Comp::lt(k, warpKTop)) {
+ // Rotate right
+#pragma unroll
+ for (int i = NumThreadQ - 1; i > 0; --i) {
+ threadK[i] = threadK[i - 1];
+ threadV[i] = threadV[i - 1];
+ }
+
+ threadK[0] = k;
+ threadV[0] = v;
+ ++numVals;
+ }
+ }
+
+ __device__ inline void checkThreadQ() {
+ bool needSort = (numVals == NumThreadQ);
+
+#if CUDA_VERSION < 9000 || defined(USE_AMD_ROCM)
+ needSort = __any(needSort);
+#else
+ needSort = __any_sync(0xffffffff, needSort);
+#endif
+
+ if (!needSort) {
+ // no lanes have triggered a sort
+ return;
+ }
+
+ // This has a trailing warpFence
+ mergeWarpQ();
+
+ // Any top-k elements have been merged into the warp queue; we're
+ // free to reset the thread queues
+ numVals = 0;
+
+#pragma unroll
+ for (int i = 0; i < NumThreadQ; ++i) {
+ threadK[i] = initK;
+ threadV[i] = initV;
+ }
+
+ // We have to beat at least this element
+ warpKTop = warpK[kMinus1];
+
+ warpFence();
+ }
+
+ /// This function handles sorting and merging together the
+ /// per-thread queues with the warp-wide queue, creating a sorted
+ /// list across both
+ __device__ inline void mergeWarpQ() {
+ int laneId = getLaneId();
+
+ // Sort all of the per-thread queues
+ warpSortAnyRegisters<K, V, NumThreadQ, !Dir, Comp>(threadK, threadV);
+
+ constexpr int kNumWarpQRegisters = NumWarpQ / kWarpSize;
+ K warpKRegisters[kNumWarpQRegisters];
+ V warpVRegisters[kNumWarpQRegisters];
+
+#pragma unroll
+ for (int i = 0; i < kNumWarpQRegisters; ++i) {
+ warpKRegisters[i] = warpK[i * kWarpSize + laneId];
+ warpVRegisters[i] = warpV[i * kWarpSize + laneId];
+ }
+
+ warpFence();
+
+ // The warp queue is already sorted, and now that we've sorted the
+ // per-thread queue, merge both sorted lists together, producing
+ // one sorted list
+ warpMergeAnyRegisters<
+ K,
+ V,
+ kNumWarpQRegisters,
+ NumThreadQ,
+ !Dir,
+ Comp,
+ false>(warpKRegisters, warpVRegisters, threadK, threadV);
+
+ // Write back out the warp queue
+#pragma unroll
+ for (int i = 0; i < kNumWarpQRegisters; ++i) {
+ warpK[i * kWarpSize + laneId] = warpKRegisters[i];
+ warpV[i * kWarpSize + laneId] = warpVRegisters[i];
+ }
+
+ warpFence();
+ }
+
+ /// WARNING: all threads in a warp must participate in this.
+ /// Otherwise, you must call the constituent parts separately.
+ __device__ inline void add(K k, V v) {
+ addThreadQ(k, v);
+ checkThreadQ();
+ }
+
+ __device__ inline void reduce() {
+ // Have all warps dump and merge their queues; this will produce
+ // the final per-warp results
+ mergeWarpQ();
+
+ // block-wide dep; thus far, all warps have been completely
+ // independent
+ __syncthreads();
+
+ // All warp queues are contiguous in smem.
+ // Now, we have kNumWarps lists of NumWarpQ elements.
+ // This is a power of 2.
+ FinalBlockMerge<kNumWarps, ThreadsPerBlock, K, V, NumWarpQ, Dir, Comp>::
+ merge(sharedK, sharedV);
+
+ // The block-wide merge has a trailing syncthreads
+ }
+
+ // Default element key
+ const K initK;
+
+ // Default element value
+ const V initV;
+
+ // Number of valid elements in our thread queue
+ int numVals;
+
+ // The k-th highest (Dir) or lowest (!Dir) element
+ K warpKTop;
+
+ // Thread queue values
+ K threadK[NumThreadQ];
+ V threadV[NumThreadQ];
+
+ // Queues for all warps
+ K* sharedK;
+ V* sharedV;
+
+ // Our warp's queue (points into sharedK/sharedV)
+ // warpK[0] is highest (Dir) or lowest (!Dir)
+ K* warpK;
+ V* warpV;
+
+ // This is a cached k-1 value
+ int kMinus1;
+};
+
+/// Specialization for k == 1 (NumWarpQ == 1)
+template <
+ typename K,
+ typename V,
+ bool Dir,
+ typename Comp,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+struct BlockSelect<K, V, Dir, Comp, 1, NumThreadQ, ThreadsPerBlock> {
+ static constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __device__ inline BlockSelect(K initK, V initV, K* smemK, V* smemV, int k)
+ : threadK(initK), threadV(initV), sharedK(smemK), sharedV(smemV) {}
+
+ __device__ inline void addThreadQ(K k, V v) {
+ bool swap = Dir ? Comp::gt(k, threadK) : Comp::lt(k, threadK);
+ threadK = swap ? k : threadK;
+ threadV = swap ? v : threadV;
+ }
+
+ __device__ inline void checkThreadQ() {
+ // We don't need to do anything here, since the warp doesn't
+ // cooperate until the end
+ }
+
+ __device__ inline void add(K k, V v) {
+ addThreadQ(k, v);
+ }
+
+ __device__ inline void reduce() {
+ // Reduce within the warp
+ Pair<K, V> pair(threadK, threadV);
+
+ if (Dir) {
+ pair = warpReduceAll<Pair<K, V>, Max<Pair<K, V>>>(
+ pair, Max<Pair<K, V>>());
+ } else {
+ pair = warpReduceAll<Pair<K, V>, Min<Pair<K, V>>>(
+ pair, Min<Pair<K, V>>());
+ }
+
+ // Each warp writes out a single value
+ int laneId = getLaneId();
+ int warpId = threadIdx.x / kWarpSize;
+
+ if (laneId == 0) {
+ sharedK[warpId] = pair.k;
+ sharedV[warpId] = pair.v;
+ }
+
+ __syncthreads();
+
+ // We typically use this for small blocks (<= 128), just having the
+ // first thread in the block perform the reduction across warps is
+ // faster
+ if (threadIdx.x == 0) {
+ threadK = sharedK[0];
+ threadV = sharedV[0];
+
+#pragma unroll
+ for (int i = 1; i < kNumWarps; ++i) {
+ K k = sharedK[i];
+ V v = sharedV[i];
+
+ bool swap = Dir ? Comp::gt(k, threadK) : Comp::lt(k, threadK);
+ threadK = swap ? k : threadK;
+ threadV = swap ? v : threadV;
+ }
+
+ // Hopefully a thread's smem reads/writes are ordered wrt
+ // itself, so no barrier needed :)
+ sharedK[0] = threadK;
+ sharedV[0] = threadV;
+ }
+
+ // In case other threads wish to read this value
+ __syncthreads();
+ }
+
+ // threadK is lowest (Dir) or highest (!Dir)
+ K threadK;
+ V threadV;
+
+ // Where we reduce in smem
+ K* sharedK;
+ V* sharedV;
+};
+
+//
+// per-warp WarpSelect
+//
+
+// `Dir` true, produce largest values.
+// `Dir` false, produce smallest values.
+template <
+ typename K,
+ typename V,
+ bool Dir,
+ typename Comp,
+ int NumWarpQ,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+struct WarpSelect {
+ static constexpr int kNumWarpQRegisters = NumWarpQ / kWarpSize;
+
+ __device__ inline WarpSelect(K initKVal, V initVVal, int k)
+ : initK(initKVal),
+ initV(initVVal),
+ numVals(0),
+ warpKTop(initKVal),
+ kLane((k - 1) % kWarpSize) {
+ static_assert(
+ utils::isPowerOf2(ThreadsPerBlock),
+ "threads must be a power-of-2");
+ static_assert(
+ utils::isPowerOf2(NumWarpQ), "warp queue must be power-of-2");
+
+ // Fill the per-thread queue keys with the default value
+#pragma unroll
+ for (int i = 0; i < NumThreadQ; ++i) {
+ threadK[i] = initK;
+ threadV[i] = initV;
+ }
+
+ // Fill the warp queue with the default value
+#pragma unroll
+ for (int i = 0; i < kNumWarpQRegisters; ++i) {
+ warpK[i] = initK;
+ warpV[i] = initV;
+ }
+ }
+
+ __device__ inline void addThreadQ(K k, V v) {
+ if (Dir ? Comp::gt(k, warpKTop) : Comp::lt(k, warpKTop)) {
+ // Rotate right
+#pragma unroll
+ for (int i = NumThreadQ - 1; i > 0; --i) {
+ threadK[i] = threadK[i - 1];
+ threadV[i] = threadV[i - 1];
+ }
+
+ threadK[0] = k;
+ threadV[0] = v;
+ ++numVals;
+ }
+ }
+
+ __device__ inline void checkThreadQ() {
+ bool needSort = (numVals == NumThreadQ);
+
+#if CUDA_VERSION < 9000 || defined(USE_AMD_ROCM)
+ needSort = __any(needSort);
+#else
+ needSort = __any_sync(0xffffffff, needSort);
+#endif
+
+ if (!needSort) {
+ // no lanes have triggered a sort
+ return;
+ }
+
+ mergeWarpQ();
+
+ // Any top-k elements have been merged into the warp queue; we're
+ // free to reset the thread queues
+ numVals = 0;
+
+#pragma unroll
+ for (int i = 0; i < NumThreadQ; ++i) {
+ threadK[i] = initK;
+ threadV[i] = initV;
+ }
+
+ // We have to beat at least this element
+ warpKTop = shfl(warpK[kNumWarpQRegisters - 1], kLane);
+ }
+
+ /// This function handles sorting and merging together the
+ /// per-thread queues with the warp-wide queue, creating a sorted
+ /// list across both
+ __device__ inline void mergeWarpQ() {
+ // Sort all of the per-thread queues
+ warpSortAnyRegisters<K, V, NumThreadQ, !Dir, Comp>(threadK, threadV);
+
+ // The warp queue is already sorted, and now that we've sorted the
+ // per-thread queue, merge both sorted lists together, producing
+ // one sorted list
+ warpMergeAnyRegisters<
+ K,
+ V,
+ kNumWarpQRegisters,
+ NumThreadQ,
+ !Dir,
+ Comp,
+ false>(warpK, warpV, threadK, threadV);
+ }
+
+ /// WARNING: all threads in a warp must participate in this.
+ /// Otherwise, you must call the constituent parts separately.
+ __device__ inline void add(K k, V v) {
+ addThreadQ(k, v);
+ checkThreadQ();
+ }
+
+ __device__ inline void reduce() {
+ // Have all warps dump and merge their queues; this will produce
+ // the final per-warp results
+ mergeWarpQ();
+ }
+
+ /// Dump final k selected values for this warp out
+ __device__ inline void writeOut(K* outK, V* outV, int k) {
+ int laneId = getLaneId();
+
+#pragma unroll
+ for (int i = 0; i < kNumWarpQRegisters; ++i) {
+ int idx = i * kWarpSize + laneId;
+
+ if (idx < k) {
+ outK[idx] = warpK[i];
+ outV[idx] = warpV[i];
+ }
+ }
+ }
+
+ // Default element key
+ const K initK;
+
+ // Default element value
+ const V initV;
+
+ // Number of valid elements in our thread queue
+ int numVals;
+
+ // The k-th highest (Dir) or lowest (!Dir) element
+ K warpKTop;
+
+ // Thread queue values
+ K threadK[NumThreadQ];
+ V threadV[NumThreadQ];
+
+ // warpK[0] is highest (Dir) or lowest (!Dir)
+ K warpK[kNumWarpQRegisters];
+ V warpV[kNumWarpQRegisters];
+
+ // This is what lane we should load an approximation (>=k) to the
+ // kth element from the last register in the warp queue (i.e.,
+ // warpK[kNumWarpQRegisters - 1]).
+ int kLane;
+};
+
+/// Specialization for k == 1 (NumWarpQ == 1)
+template <
+ typename K,
+ typename V,
+ bool Dir,
+ typename Comp,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+struct WarpSelect<K, V, Dir, Comp, 1, NumThreadQ, ThreadsPerBlock> {
+ static constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ __device__ inline WarpSelect(K initK, V initV, int k)
+ : threadK(initK), threadV(initV) {}
+
+ __device__ inline void addThreadQ(K k, V v) {
+ bool swap = Dir ? Comp::gt(k, threadK) : Comp::lt(k, threadK);
+ threadK = swap ? k : threadK;
+ threadV = swap ? v : threadV;
+ }
+
+ __device__ inline void checkThreadQ() {
+ // We don't need to do anything here, since the warp doesn't
+ // cooperate until the end
+ }
+
+ __device__ inline void add(K k, V v) {
+ addThreadQ(k, v);
+ }
+
+ __device__ inline void reduce() {
+ // Reduce within the warp
+ Pair<K, V> pair(threadK, threadV);
+
+ if (Dir) {
+ pair = warpReduceAll<Pair<K, V>, Max<Pair<K, V>>>(
+ pair, Max<Pair<K, V>>());
+ } else {
+ pair = warpReduceAll<Pair<K, V>, Min<Pair<K, V>>>(
+ pair, Min<Pair<K, V>>());
+ }
+
+ threadK = pair.k;
+ threadV = pair.v;
+ }
+
+ /// Dump final k selected values for this warp out
+ __device__ inline void writeOut(K* outK, V* outV, int k) {
+ if (getLaneId() == 0) {
+ *outK = threadK;
+ *outV = threadV;
+ }
+ }
+
+ // threadK is lowest (Dir) or highest (!Dir)
+ K threadK;
+ V threadV;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StackDeviceMemory.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StackDeviceMemory.cpp
new file mode 100644
index 0000000..f218a1c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StackDeviceMemory.cpp
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StackDeviceMemory.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <algorithm>
+#include <sstream>
+
+namespace faiss {
+namespace gpu {
+
+namespace {
+
+size_t adjustStackSize(size_t sz) {
+ if (sz == 0) {
+ return 0;
+ } else {
+ // ensure that we have at least 16 bytes, as all allocations are bumped
+ // up to 16
+ return utils::roundUp(sz, (size_t)16);
+ }
+}
+
+} // namespace
+
+StackDeviceMemory::Stack::Stack(GpuResources* res, int d, size_t sz)
+ : res_(res),
+ device_(d),
+ alloc_(nullptr),
+ allocSize_(adjustStackSize(sz)),
+ start_(nullptr),
+ end_(nullptr),
+ head_(nullptr),
+ highWaterMemoryUsed_(0) {
+ if (allocSize_ == 0) {
+ return;
+ }
+
+ DeviceScope s(device_);
+ auto req = AllocRequest(
+ AllocType::TemporaryMemoryBuffer,
+ device_,
+ MemorySpace::Device,
+ res_->getDefaultStream(device_),
+ allocSize_);
+
+ alloc_ = (char*)res_->allocMemory(req);
+ FAISS_ASSERT_FMT(
+ alloc_,
+ "could not reserve temporary memory region of size %zu",
+ allocSize_);
+
+ // In order to disambiguate between our entire region of temporary memory
+ // versus the first allocation in the temporary memory region, ensure that
+ // the first address returned is +16 bytes from the beginning
+ start_ = alloc_ + 16;
+ head_ = start_;
+ end_ = alloc_ + allocSize_;
+}
+
+StackDeviceMemory::Stack::~Stack() {
+ DeviceScope s(device_);
+
+ // FIXME: make sure there are no outstanding memory allocations?
+ if (alloc_) {
+ res_->deallocMemory(device_, alloc_);
+ }
+}
+
+size_t StackDeviceMemory::Stack::getSizeAvailable() const {
+ return (end_ - head_);
+}
+
+char* StackDeviceMemory::Stack::getAlloc(size_t size, cudaStream_t stream) {
+ // The user must check to see that the allocation fit within us
+ auto sizeRemaining = getSizeAvailable();
+
+ FAISS_ASSERT(size <= sizeRemaining);
+
+ // We can make the allocation out of our stack
+ // Find all the ranges that we overlap that may have been
+ // previously allocated; our allocation will be [head, endAlloc)
+ char* startAlloc = head_;
+ char* endAlloc = head_ + size;
+
+ while (lastUsers_.size() > 0) {
+ auto& prevUser = lastUsers_.back();
+
+ // Because there is a previous user, we must overlap it
+ FAISS_ASSERT(
+ prevUser.start_ <= endAlloc && prevUser.end_ >= startAlloc);
+
+ if (stream != prevUser.stream_) {
+ // Synchronization required
+ streamWait({stream}, {prevUser.stream_});
+ }
+
+ if (endAlloc < prevUser.end_) {
+ // Update the previous user info
+ prevUser.start_ = endAlloc;
+
+ break;
+ }
+
+ // If we're the exact size of the previous request, then we
+ // don't need to continue
+ bool done = (prevUser.end_ == endAlloc);
+
+ lastUsers_.pop_back();
+
+ if (done) {
+ break;
+ }
+ }
+
+ head_ = endAlloc;
+ FAISS_ASSERT(head_ <= end_);
+
+ highWaterMemoryUsed_ =
+ std::max(highWaterMemoryUsed_, (size_t)(head_ - start_));
+ FAISS_ASSERT(startAlloc);
+ return startAlloc;
+}
+
+void StackDeviceMemory::Stack::returnAlloc(
+ char* p,
+ size_t size,
+ cudaStream_t stream) {
+ // This allocation should be within ourselves
+ FAISS_ASSERT(p >= start_ && p < end_);
+
+ // All allocations should have been adjusted to a multiple of 16 bytes
+ FAISS_ASSERT(size % 16 == 0);
+
+ // This is on our stack
+ // Allocations should be freed in the reverse order they are made
+ if (p + size != head_) {
+ FAISS_ASSERT(p + size == head_);
+ }
+
+ head_ = p;
+ lastUsers_.push_back(Range(p, p + size, stream));
+}
+
+std::string StackDeviceMemory::Stack::toString() const {
+ std::stringstream s;
+
+ s << "SDM device " << device_ << ": Total memory " << allocSize_ << " ["
+ << (void*)start_ << ", " << (void*)end_ << ")\n";
+ s << " Available memory " << (size_t)(end_ - head_) << " ["
+ << (void*)head_ << ", " << (void*)end_ << ")\n";
+ s << " High water temp alloc " << highWaterMemoryUsed_ << "\n";
+
+ int i = lastUsers_.size();
+ for (auto it = lastUsers_.rbegin(); it != lastUsers_.rend(); ++it) {
+ s << i-- << ": size " << (size_t)(it->end_ - it->start_) << " stream "
+ << it->stream_ << " [" << (void*)it->start_ << ", " << (void*)it->end_
+ << ")\n";
+ }
+
+ return s.str();
+}
+
+StackDeviceMemory::StackDeviceMemory(
+ GpuResources* res,
+ int device,
+ size_t allocPerDevice)
+ : device_(device), stack_(res, device, allocPerDevice) {}
+
+StackDeviceMemory::~StackDeviceMemory() {}
+
+int StackDeviceMemory::getDevice() const {
+ return device_;
+}
+
+size_t StackDeviceMemory::getSizeAvailable() const {
+ return stack_.getSizeAvailable();
+}
+
+std::string StackDeviceMemory::toString() const {
+ return stack_.toString();
+}
+
+void* StackDeviceMemory::allocMemory(cudaStream_t stream, size_t size) {
+ // All allocations should have been adjusted to a multiple of 16 bytes
+ FAISS_ASSERT(size % 16 == 0);
+ return stack_.getAlloc(size, stream);
+}
+
+void StackDeviceMemory::deallocMemory(
+ int device,
+ cudaStream_t stream,
+ size_t size,
+ void* p) {
+ FAISS_ASSERT(p);
+ FAISS_ASSERT(device == device_);
+
+ stack_.returnAlloc((char*)p, size, stream);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StackDeviceMemory.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StackDeviceMemory.h
new file mode 100644
index 0000000..aacec60
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StackDeviceMemory.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda_runtime.h>
+#include <faiss/gpu/GpuResources.h>
+#include <list>
+#include <memory>
+#include <tuple>
+#include <unordered_map>
+
+namespace faiss {
+namespace gpu {
+
+/// Device memory manager that provides temporary memory allocations
+/// out of a region of memory, for a single device
+class StackDeviceMemory {
+ public:
+ /// Allocate a new region of memory that we manage
+ StackDeviceMemory(GpuResources* res, int device, size_t allocPerDevice);
+
+ /// Manage a region of memory for a particular device, with or
+ /// without ownership
+ StackDeviceMemory(int device, void* p, size_t size, bool isOwner);
+
+ ~StackDeviceMemory();
+
+ int getDevice() const;
+
+ /// All allocations requested should be a multiple of 16 bytes
+ void* allocMemory(cudaStream_t stream, size_t size);
+ void deallocMemory(int device, cudaStream_t, size_t size, void* p);
+
+ size_t getSizeAvailable() const;
+ std::string toString() const;
+
+ protected:
+ /// Previous allocation ranges and the streams for which
+ /// synchronization is required
+ struct Range {
+ inline Range(char* s, char* e, cudaStream_t str)
+ : start_(s), end_(e), stream_(str) {}
+
+ // References a memory range [start, end)
+ char* start_;
+ char* end_;
+ cudaStream_t stream_;
+ };
+
+ struct Stack {
+ /// Constructor that allocates memory via cudaMalloc
+ Stack(GpuResources* res, int device, size_t size);
+
+ ~Stack();
+
+ /// Returns how much size is available for an allocation without
+ /// calling cudaMalloc
+ size_t getSizeAvailable() const;
+
+ /// Obtains an allocation; all allocations are guaranteed to be 16
+ /// byte aligned
+ char* getAlloc(size_t size, cudaStream_t stream);
+
+ /// Returns an allocation
+ void returnAlloc(char* p, size_t size, cudaStream_t stream);
+
+ /// Returns the stack state
+ std::string toString() const;
+
+ /// Our GpuResources object
+ GpuResources* res_;
+
+ /// Device this allocation is on
+ int device_;
+
+ /// Where our temporary memory buffer is allocated; we allocate starting
+ /// 16 bytes into this
+ char* alloc_;
+
+ /// Total size of our allocation
+ size_t allocSize_;
+
+ /// Our temporary memory region; [start_, end_) is valid
+ char* start_;
+ char* end_;
+
+ /// Stack head within [start, end)
+ char* head_;
+
+ /// List of previous last users of allocations on our stack, for
+ /// possible synchronization purposes
+ std::list<Range> lastUsers_;
+
+ /// What's the high water mark in terms of memory used from the
+ /// temporary buffer?
+ size_t highWaterMemoryUsed_;
+ };
+
+ /// Our device
+ int device_;
+
+ /// Memory stack
+ Stack stack_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StaticUtils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StaticUtils.h
new file mode 100644
index 0000000..93f1f70
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/StaticUtils.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+
+// allow usage for non-CUDA files
+#ifndef __host__
+#define __host__
+#define __device__
+#endif
+
+namespace faiss {
+namespace gpu {
+namespace utils {
+
+template <typename U, typename V>
+constexpr __host__ __device__ auto divDown(U a, V b) -> decltype(a + b) {
+ return (a / b);
+}
+
+template <typename U, typename V>
+constexpr __host__ __device__ auto divUp(U a, V b) -> decltype(a + b) {
+ return (a + b - 1) / b;
+}
+
+template <typename U, typename V>
+constexpr __host__ __device__ auto roundDown(U a, V b) -> decltype(a + b) {
+ return divDown(a, b) * b;
+}
+
+template <typename U, typename V>
+constexpr __host__ __device__ auto roundUp(U a, V b) -> decltype(a + b) {
+ return divUp(a, b) * b;
+}
+
+template <class T>
+constexpr __host__ __device__ T pow(T n, T power) {
+ return (power > 0 ? n * pow(n, power - 1) : 1);
+}
+
+template <class T>
+constexpr __host__ __device__ T pow2(T n) {
+ return pow(2, (T)n);
+}
+
+static_assert(pow2(8) == 256, "pow2");
+
+template <typename T>
+constexpr __host__ __device__ int log2(T n, int p = 0) {
+ return (n <= 1) ? p : log2(n / 2, p + 1);
+}
+
+static_assert(log2(2) == 1, "log2");
+static_assert(log2(3) == 1, "log2");
+static_assert(log2(4) == 2, "log2");
+
+template <typename T>
+constexpr __host__ __device__ bool isPowerOf2(T v) {
+ return (v && !(v & (v - 1)));
+}
+
+static_assert(isPowerOf2(2048), "isPowerOf2");
+static_assert(!isPowerOf2(3333), "isPowerOf2");
+
+template <typename T>
+constexpr __host__ __device__ T nextHighestPowerOf2(T v) {
+ return (isPowerOf2(v) ? (T)2 * v : ((T)1 << (log2(v) + 1)));
+}
+
+static_assert(nextHighestPowerOf2(1) == 2, "nextHighestPowerOf2");
+static_assert(nextHighestPowerOf2(2) == 4, "nextHighestPowerOf2");
+static_assert(nextHighestPowerOf2(3) == 4, "nextHighestPowerOf2");
+static_assert(nextHighestPowerOf2(4) == 8, "nextHighestPowerOf2");
+
+static_assert(nextHighestPowerOf2(15) == 16, "nextHighestPowerOf2");
+static_assert(nextHighestPowerOf2(16) == 32, "nextHighestPowerOf2");
+static_assert(nextHighestPowerOf2(17) == 32, "nextHighestPowerOf2");
+
+static_assert(
+ nextHighestPowerOf2(1536000000u) == 2147483648u,
+ "nextHighestPowerOf2");
+static_assert(
+ nextHighestPowerOf2((size_t)2147483648ULL) == (size_t)4294967296ULL,
+ "nextHighestPowerOf2");
+
+} // namespace utils
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Tensor-inl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Tensor-inl.cuh
new file mode 100644
index 0000000..6f575cf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Tensor-inl.cuh
@@ -0,0 +1,1052 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/GpuFaissAssert.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <cstring>
+#include <limits>
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::Tensor()
+ : data_(nullptr) {
+ static_assert(Dim > 0, "must have > 0 dimensions");
+
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = 0;
+ stride_[i] = (IndexT)1;
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::Tensor(
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t) {
+ this->operator=(t);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::Tensor(
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t) {
+ this->operator=(std::move(t));
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::operator=(Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&
+ t) {
+ data_ = t.data_;
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = t.size_[i];
+ stride_[i] = t.stride_[i];
+ }
+
+ return *this;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::operator=(Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&&
+ t) {
+ data_ = t.data_;
+ t.data_ = nullptr;
+ for (int i = 0; i < Dim; ++i) {
+ stride_[i] = t.stride_[i];
+ t.stride_[i] = 0;
+ size_[i] = t.size_[i];
+ t.size_[i] = 0;
+ }
+
+ return *this;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::Tensor(
+ DataPtrType data,
+ const IndexT sizes[Dim])
+ : data_(data) {
+ static_assert(Dim > 0, "must have > 0 dimensions");
+
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = sizes[i];
+ }
+
+ stride_[Dim - 1] = (IndexT)1;
+ for (int i = Dim - 2; i >= 0; --i) {
+ stride_[i] = stride_[i + 1] * sizes[i + 1];
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::Tensor(
+ DataPtrType data,
+ std::initializer_list<IndexT> sizes)
+ : data_(data) {
+ GPU_FAISS_ASSERT(sizes.size() == Dim);
+ static_assert(Dim > 0, "must have > 0 dimensions");
+
+ int i = 0;
+ for (auto s : sizes) {
+ size_[i++] = s;
+ }
+
+ stride_[Dim - 1] = (IndexT)1;
+ for (int j = Dim - 2; j >= 0; --j) {
+ stride_[j] = stride_[j + 1] * size_[j + 1];
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::Tensor(
+ DataPtrType data,
+ const IndexT sizes[Dim],
+ const IndexT strides[Dim])
+ : data_(data) {
+ static_assert(Dim > 0, "must have > 0 dimensions");
+
+ for (int i = 0; i < Dim; ++i) {
+ size_[i] = sizes[i];
+ stride_[i] = strides[i];
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ void Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::copyFrom(
+ const Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t,
+ cudaStream_t stream) {
+ // The tensor must be fully contiguous
+ GPU_FAISS_ASSERT(this->isContiguous());
+
+ // Size must be the same (since dimensions are checked and
+ // continuity is assumed, we need only check total number of
+ // elements
+ GPU_FAISS_ASSERT(this->numElements() == t.numElements());
+
+ if (t.numElements() > 0) {
+ GPU_FAISS_ASSERT(this->data_);
+ GPU_FAISS_ASSERT(t.data());
+
+ int ourDev = getDeviceForAddress(this->data_);
+ int tDev = getDeviceForAddress(t.data());
+
+ if (tDev == -1) {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ this->data_,
+ t.data(),
+ this->getSizeInBytes(),
+ ourDev == -1 ? cudaMemcpyHostToHost
+ : cudaMemcpyHostToDevice,
+ stream));
+ } else {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ this->data_,
+ t.data(),
+ this->getSizeInBytes(),
+ ourDev == -1 ? cudaMemcpyDeviceToHost
+ : cudaMemcpyDeviceToDevice,
+ stream));
+ }
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ void Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::copyTo(
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t,
+ cudaStream_t stream) {
+ // The tensor must be fully contiguous
+ GPU_FAISS_ASSERT(this->isContiguous());
+
+ // Size must be the same (since dimensions are checked and
+ // continuity is assumed, we need only check total number of
+ // elements
+ GPU_FAISS_ASSERT(this->numElements() == t.numElements());
+
+ if (t.numElements() > 0) {
+ GPU_FAISS_ASSERT(this->data_);
+ GPU_FAISS_ASSERT(t.data());
+
+ int ourDev = getDeviceForAddress(this->data_);
+ int tDev = getDeviceForAddress(t.data());
+
+ if (tDev == -1) {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ t.data(),
+ this->data_,
+ this->getSizeInBytes(),
+ ourDev == -1 ? cudaMemcpyHostToHost
+ : cudaMemcpyDeviceToHost,
+ stream));
+ } else {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ t.data(),
+ this->data_,
+ this->getSizeInBytes(),
+ ourDev == -1 ? cudaMemcpyHostToDevice
+ : cudaMemcpyDeviceToDevice,
+ stream));
+ }
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ void Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::copyFrom(
+ const std::vector<T>& v,
+ cudaStream_t stream) {
+ // The tensor must be fully contiguous
+ GPU_FAISS_ASSERT(this->isContiguous());
+
+ // Size must be the same
+ GPU_FAISS_ASSERT(this->numElements() == v.size());
+
+ if (v.size() > 0) {
+ GPU_FAISS_ASSERT(this->data_);
+ int ourDev = getDeviceForAddress(this->data_);
+
+ CUDA_VERIFY(cudaMemcpyAsync(
+ this->data_,
+ v.data(),
+ this->getSizeInBytes(),
+ ourDev == -1 ? cudaMemcpyHostToHost : cudaMemcpyHostToDevice,
+ stream));
+ }
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ std::vector<T> Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ copyToVector(cudaStream_t stream) {
+ // The tensor must be fully contiguous
+ GPU_FAISS_ASSERT(this->isContiguous());
+
+ std::vector<T> out(this->numElements());
+
+ if (!out.empty()) {
+ int ourDev = getDeviceForAddress(this->data_);
+
+ if (ourDev == -1) {
+ std::memcpy(
+ out.data(), this->data_, this->numElements() * sizeof(T));
+ } else {
+ CUDA_VERIFY(cudaMemcpyAsync(
+ out.data(),
+ this->data_,
+ this->numElements() * sizeof(T),
+ cudaMemcpyDeviceToHost,
+ stream));
+ }
+ }
+
+ return out;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename OtherT, int OtherDim>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::isSame(
+ const Tensor<OtherT, OtherDim, InnerContig, IndexT, PtrTraits>& rhs)
+ const {
+ if (Dim != OtherDim) {
+ return false;
+ }
+
+ for (int i = 0; i < Dim; ++i) {
+ if (this->getSize(i) != rhs.getSize(i)) {
+ return false;
+ }
+
+ if (this->getStride(i) != rhs.getStride(i)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename OtherT, int OtherDim>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ isSameSize(
+ const Tensor<OtherT, OtherDim, InnerContig, IndexT, PtrTraits>&
+ rhs) const {
+ if (Dim != OtherDim) {
+ return false;
+ }
+
+ for (int i = 0; i < Dim; ++i) {
+ if (this->getSize(i) != rhs.getSize(i)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename U>
+__host__ __device__ Tensor<U, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::cast() {
+ static_assert(sizeof(U) == sizeof(T), "cast must be to same size object");
+
+ return Tensor<U, Dim, InnerContig, IndexT, PtrTraits>(
+ reinterpret_cast<U*>(data_), size_, stride_);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename U>
+__host__ __device__ const Tensor<U, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::cast() const {
+ static_assert(sizeof(U) == sizeof(T), "cast must be to same size object");
+
+ return Tensor<U, Dim, InnerContig, IndexT, PtrTraits>(
+ reinterpret_cast<U*>(data_), size_, stride_);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename U>
+__host__ __device__ Tensor<U, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::castResize() {
+ static_assert(sizeof(U) >= sizeof(T), "only handles greater sizes");
+ constexpr int kMultiple = sizeof(U) / sizeof(T);
+
+ GPU_FAISS_ASSERT(canCastResize<U>());
+
+ IndexT newSize[Dim];
+ IndexT newStride[Dim];
+
+ for (int i = 0; i < Dim - 1; ++i) {
+ newSize[i] = size_[i];
+ newStride[i] = stride_[i] / kMultiple;
+ }
+
+ newStride[Dim - 1] = 1; // this is the same as the old stride
+ newSize[Dim - 1] = size_[Dim - 1] / kMultiple;
+
+ return Tensor<U, Dim, InnerContig, IndexT, PtrTraits>(
+ reinterpret_cast<U*>(data_), newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename U>
+__host__ __device__ const Tensor<U, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::castResize() const {
+ return const_cast<Tensor<T, Dim, InnerContig, IndexT, PtrTraits>*>(this)
+ ->castResize<U>();
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename U>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ canCastResize() const {
+ static_assert(sizeof(U) >= sizeof(T), "only handles greater sizes");
+ constexpr int kMultiple = sizeof(U) / sizeof(T);
+
+ // Ensure that the base pointer is sizeof(U) aligned
+ if (((uintptr_t)data_) % sizeof(U) != 0) {
+ return false;
+ }
+
+ // Check all outer strides
+ for (int i = 0; i < Dim - 1; ++i) {
+ if (stride_[i] % kMultiple != 0) {
+ return false;
+ }
+ }
+
+ // Check inner size
+ if (size_[Dim - 1] % kMultiple != 0) {
+ return false;
+ }
+
+ if (stride_[Dim - 1] != 1) {
+ return false;
+ }
+
+ return true;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename NewIndexT>
+__host__ Tensor<T, Dim, InnerContig, NewIndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::castIndexType() const {
+ if (sizeof(NewIndexT) < sizeof(IndexT)) {
+ GPU_FAISS_ASSERT(this->canUseIndexType<NewIndexT>());
+ }
+
+ NewIndexT newSize[Dim];
+ NewIndexT newStride[Dim];
+ for (int i = 0; i < Dim; ++i) {
+ newSize[i] = (NewIndexT)size_[i];
+ newStride[i] = (NewIndexT)stride_[i];
+ }
+
+ return Tensor<T, Dim, InnerContig, NewIndexT, PtrTraits>(
+ data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <typename NewIndexT>
+__host__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::canUseIndexType()
+ const {
+ static_assert(sizeof(size_t) >= sizeof(IndexT), "index size too large");
+ static_assert(
+ sizeof(size_t) >= sizeof(NewIndexT), "new index size too large");
+
+ // Find maximum offset that can be calculated
+ // FIXME: maybe also consider offset in bytes? multiply by sizeof(T)?
+ size_t maxOffset = 0;
+
+ for (int i = 0; i < Dim; ++i) {
+ size_t curMaxOffset = (size_t)size_[i] * (size_t)stride_[i];
+ if (curMaxOffset > maxOffset) {
+ maxOffset = curMaxOffset;
+ }
+ }
+
+ if (maxOffset > (size_t)std::numeric_limits<NewIndexT>::max()) {
+ return false;
+ }
+
+ return true;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ IndexT
+Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::numElements() const {
+ auto size = getSize(0);
+
+ for (int i = 1; i < Dim; ++i) {
+ size *= getSize(i);
+ }
+
+ return size;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ isContiguous() const {
+ IndexT prevSize = 1;
+
+ for (int i = Dim - 1; i >= 0; --i) {
+ if (getSize(i) != 1) {
+ if (getStride(i) == prevSize) {
+ prevSize *= getSize(i);
+ } else {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ isConsistentlySized(int i) const {
+ if (i == 0 && getStride(i) > 0 && getSize(i) > 0) {
+ return true;
+ } else if (
+ (i > 0) && (i < Dim) && (getStride(i) > 0) &&
+ ((getStride(i - 1) / getStride(i)) >= getSize(i))) {
+ return true;
+ }
+
+ return false;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ isConsistentlySized() const {
+ for (int i = 0; i < Dim; ++i) {
+ if (!isConsistentlySized(i)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ bool Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::
+ isContiguousDim(int i) const {
+ return (i == Dim - 1) || // just in case
+ ((i < Dim - 1) &&
+ ((getStride(i) / getStride(i + 1)) == getSize(i + 1)));
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::transpose(int dim1, int dim2) const {
+ GPU_FAISS_ASSERT(dim1 >= 0 && dim1 < Dim);
+ GPU_FAISS_ASSERT(dim2 >= 0 && dim2 < Dim);
+
+ // If a tensor is innermost contiguous, one cannot transpose the innermost
+ // dimension
+ if (InnerContig) {
+ GPU_FAISS_ASSERT(dim1 != Dim - 1 && dim2 != Dim - 1);
+ }
+
+ IndexT newSize[Dim];
+ IndexT newStride[Dim];
+
+ for (int i = 0; i < Dim; ++i) {
+ newSize[i] = size_[i];
+ newStride[i] = stride_[i];
+ }
+
+ IndexT tmp = newSize[dim1];
+ newSize[dim1] = newSize[dim2];
+ newSize[dim2] = tmp;
+
+ tmp = newStride[dim1];
+ newStride[dim1] = newStride[dim2];
+ newStride[dim2] = tmp;
+
+ return Tensor<T, Dim, true, IndexT, PtrTraits>(data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, false, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::transposeInnermost(int dim1) const {
+ GPU_FAISS_ASSERT(dim1 >= 0 && dim1 < Dim);
+
+ // We are exchanging with the innermost dimension
+ int dim2 = 1;
+
+ IndexT newSize[Dim];
+ IndexT newStride[Dim];
+
+ for (int i = 0; i < Dim; ++i) {
+ newSize[i] = size_[i];
+ newStride[i] = stride_[i];
+ }
+
+ IndexT tmp = newSize[dim1];
+ newSize[dim1] = newSize[dim2];
+ newSize[dim2] = tmp;
+
+ tmp = newStride[dim1];
+ newStride[dim1] = newStride[dim2];
+ newStride[dim2] = tmp;
+
+ return Tensor<T, Dim, false, IndexT, PtrTraits>(data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int NewDim>
+__host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::upcastOuter() {
+ // Can only create tensors of greater dimension
+ static_assert(NewDim > Dim, "Can only upcast to greater dim");
+
+ IndexT newSize[NewDim];
+ IndexT newStride[NewDim];
+
+ int shift = NewDim - Dim;
+
+ for (int i = 0; i < NewDim; ++i) {
+ if (i < shift) {
+ // These are the extended dimensions
+ newSize[i] = (IndexT)1;
+ newStride[i] = size_[0] * stride_[0];
+ } else {
+ // Shift the remaining dimensions
+ newSize[i] = size_[i - shift];
+ newStride[i] = stride_[i - shift];
+ }
+ }
+
+ return Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>(
+ data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int NewDim>
+__host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::upcastInner() {
+ // Can only create tensors of greater dimension
+ static_assert(NewDim > Dim, "Can only upcast to greater dim");
+
+ IndexT newSize[NewDim];
+ IndexT newStride[NewDim];
+
+ for (int i = 0; i < NewDim; ++i) {
+ if (i < Dim) {
+ // Existing dimensions get copied over
+ newSize[i] = size_[i];
+ newStride[i] = stride_[i];
+ } else {
+ // Extended dimensions
+ newSize[i] = (IndexT)1;
+ newStride[i] = (IndexT)1;
+ }
+ }
+
+ return Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>(
+ data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int NewDim>
+__host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::downcastOuter() {
+ // Can only create tensors of lesser dimension
+ static_assert(NewDim < Dim, "Can only downcast to lesser dim");
+
+ // We can't downcast non-contiguous tensors, since it leaves
+ // garbage data in the tensor. The tensor needs to be contiguous
+ // in all of the dimensions we are collapsing (no padding in
+ // them).
+ for (int i = 0; i < Dim - NewDim; ++i) {
+ bool cont = isContiguousDim(i);
+ GPU_FAISS_ASSERT(cont);
+ }
+
+ IndexT newSize[NewDim];
+ IndexT newStride[NewDim];
+
+ int ignoredDims = Dim - NewDim;
+ IndexT collapsedSize = 1;
+
+ for (int i = 0; i < Dim; ++i) {
+ if (i < ignoredDims) {
+ // Collapse these dimensions
+ collapsedSize *= getSize(i);
+ } else {
+ // Non-collapsed dimensions
+ if (i == ignoredDims) {
+ // This is the first non-collapsed dimension
+ newSize[i - ignoredDims] = collapsedSize * getSize(i);
+ } else {
+ // Subsequent non-collapsed dimensions
+ newSize[i - ignoredDims] = getSize(i);
+ }
+
+ newStride[i - ignoredDims] = getStride(i);
+ }
+ }
+
+ return Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>(
+ data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int NewDim>
+__host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::downcastInner() {
+ // Can only create tensors of lesser dimension
+ static_assert(NewDim < Dim, "Can only downcast to lesser dim");
+
+ // We can't downcast non-contiguous tensors, since it leaves
+ // garbage data in the tensor. The tensor needs to be contiguous
+ // in all of the dimensions we are collapsing (no padding in
+ // them).
+ for (int i = NewDim; i < Dim; ++i) {
+ GPU_FAISS_ASSERT(isContiguousDim(i));
+ }
+
+ IndexT newSize[NewDim];
+ IndexT newStride[NewDim];
+
+ IndexT collapsedSize = 1;
+
+ for (int i = Dim - 1; i >= 0; --i) {
+ if (i >= NewDim) {
+ // Collapse these dimensions
+ collapsedSize *= getSize(i);
+ } else {
+ // Non-collapsed dimensions
+ if (i == NewDim - 1) {
+ // This is the first non-collapsed dimension
+ newSize[i] = collapsedSize * getSize(i);
+ newStride[i] = getStride(Dim - 1);
+ } else {
+ // Subsequent non-collapsed dimensions
+ newSize[i] = getSize(i);
+ newStride[i] = getStride(i);
+ }
+ }
+ }
+
+ return Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>(
+ data_, newSize, newStride);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int SubDim>
+__host__ __device__ Tensor<T, SubDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::view(DataPtrType at) {
+ static_assert(
+ SubDim >= 1 && SubDim < Dim, "can only create view of lesser dim");
+
+ IndexT viewSizes[SubDim];
+ IndexT viewStrides[SubDim];
+
+ for (int i = 0; i < SubDim; ++i) {
+ viewSizes[i] = size_[Dim - SubDim + i];
+ viewStrides[i] = stride_[Dim - SubDim + i];
+ }
+
+ return Tensor<T, SubDim, InnerContig, IndexT, PtrTraits>(
+ at, viewSizes, viewStrides);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int SubDim>
+__host__ __device__ Tensor<T, SubDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::view() {
+ return view<SubDim>(data_);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::narrowOutermost(IndexT start, IndexT size) {
+ return this->narrow(0, start, size);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::narrow(int dim, IndexT start, IndexT size) {
+ DataPtrType newData = data_;
+
+ GPU_FAISS_ASSERT(
+ start >= 0 && start < size_[dim] && (start + size) <= size_[dim]);
+
+ if (start > 0) {
+ newData += (size_t)start * stride_[dim];
+ }
+
+ IndexT newSize[Dim];
+ for (int i = 0; i < Dim; ++i) {
+ if (i == dim) {
+ GPU_FAISS_ASSERT(start + size <= size_[dim]);
+ newSize[i] = size;
+ } else {
+ newSize[i] = size_[i];
+ }
+ }
+
+ // If we were innermost contiguous before, we are still innermost contiguous
+ return Tensor<T, Dim, InnerContig, IndexT, PtrTraits>(
+ newData, newSize, stride_);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+template <int NewDim>
+__host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits> Tensor<
+ T,
+ Dim,
+ InnerContig,
+ IndexT,
+ PtrTraits>::view(std::initializer_list<IndexT> sizes) {
+ GPU_FAISS_ASSERT(this->isContiguous());
+
+ GPU_FAISS_ASSERT(sizes.size() == NewDim);
+
+ // The total size of the new view must be the same as the total size
+ // of the old view
+ size_t curSize = numElements();
+ size_t newSize = 1;
+
+ for (auto s : sizes) {
+ newSize *= s;
+ }
+
+ GPU_FAISS_ASSERT(curSize == newSize);
+ return Tensor<T, NewDim, true, IndexT, PtrTraits>(data(), sizes);
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Tensor.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Tensor.cuh
new file mode 100644
index 0000000..37c0e91
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Tensor.cuh
@@ -0,0 +1,698 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <assert.h>
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <faiss/Index.h> // idx_t
+#include <stdint.h>
+#include <initializer_list>
+#include <vector>
+
+/// Multi-dimensional array class for CUDA device and host usage.
+/// Originally from Facebook's fbcunn, since added to the Torch GPU
+/// library cutorch as well.
+
+namespace faiss {
+namespace gpu {
+
+/// Our tensor type
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+class Tensor;
+
+/// Type of a subspace of a tensor
+namespace detail {
+template <
+ typename TensorType,
+ int SubDim,
+ template <typename U>
+ class PtrTraits>
+class SubTensor;
+}
+
+namespace traits {
+
+template <typename T>
+struct RestrictPtrTraits {
+ typedef T* __restrict__ PtrType;
+};
+
+template <typename T>
+struct DefaultPtrTraits {
+ typedef T* PtrType;
+};
+
+} // namespace traits
+
+/**
+ Templated multi-dimensional array that supports strided access of
+ elements. Main access is through `operator[]`; e.g.,
+ `tensor[x][y][z]`.
+
+ - `T` is the contained type (e.g., `float`)
+ - `Dim` is the tensor rank
+ - If `InnerContig` is true, then the tensor is assumed to be innermost
+ - contiguous, and only operations that make sense on contiguous
+ - arrays are allowed (e.g., no transpose). Strides are still
+ - calculated, but innermost stride is assumed to be 1.
+ - `IndexT` is the integer type used for size/stride arrays, and for
+ - all indexing math. Default is `int`, but for large tensors, `long`
+ - can be used instead.
+ - `PtrTraits` are traits applied to our data pointer (T*). By default,
+ - this is just T*, but RestrictPtrTraits can be used to apply T*
+ - __restrict__ for alias-free analysis.
+*/
+template <
+ typename T,
+ int Dim,
+ bool InnerContig = false,
+ typename IndexT = idx_t,
+ template <typename U> class PtrTraits = traits::DefaultPtrTraits>
+class Tensor {
+ public:
+ enum { NumDim = Dim };
+ typedef T DataType;
+ typedef IndexT IndexType;
+ enum { IsInnerContig = InnerContig };
+ typedef typename PtrTraits<T>::PtrType DataPtrType;
+ typedef Tensor<T, Dim, InnerContig, IndexT, PtrTraits> TensorType;
+
+ /// Default constructor
+ __host__ __device__ Tensor();
+
+ /// Copy constructor
+ __host__ __device__
+ Tensor(Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t);
+
+ /// Move constructor
+ __host__ __device__
+ Tensor(Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t);
+
+ /// Assignment
+ __host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&
+ operator=(Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t);
+
+ /// Move assignment
+ __host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&
+ operator=(Tensor<T, Dim, InnerContig, IndexT, PtrTraits>&& t);
+
+ /// Constructor that calculates strides with no padding
+ __host__ __device__ Tensor(DataPtrType data, const IndexT sizes[Dim]);
+ __host__ __device__
+ Tensor(DataPtrType data, std::initializer_list<IndexT> sizes);
+
+ /// Constructor that takes arbitrary size/stride arrays.
+ /// Errors if you attempt to pass non-contiguous strides to a
+ /// contiguous tensor.
+ __host__ __device__
+ Tensor(DataPtrType data,
+ const IndexT sizes[Dim],
+ const IndexT strides[Dim]);
+
+ /// Copies a tensor into ourselves; sizes must match
+ __host__ void copyFrom(
+ const Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t,
+ cudaStream_t stream);
+
+ /// Copies ourselves into a tensor; sizes must match
+ __host__ void copyTo(
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>& t,
+ cudaStream_t stream);
+
+ /// Copies a CPU std::vector<T> into ourselves, allocating memory for it.
+ /// The total size of our Tensor must match vector<T>::size(), though
+ /// we are not restricted to 1D Tensors to match the 1D vector<T>.
+ /// `stream` specifies the stream of the copy and thus the stream on which
+ /// the memory will initially be used.
+ __host__ void copyFrom(const std::vector<T>& v, cudaStream_t stream);
+
+ /// Copies ourselves into a flattened (1D) std::vector, using the given
+ /// stream
+ __host__ std::vector<T> copyToVector(cudaStream_t stream);
+
+ /// Returns true if the two tensors are of the same dimensionality,
+ /// size and stride.
+ template <typename OtherT, int OtherDim>
+ __host__ __device__ bool isSame(
+ const Tensor<OtherT, OtherDim, InnerContig, IndexT, PtrTraits>& rhs)
+ const;
+
+ /// Returns true if the two tensors are of the same dimensionality and size
+ template <typename OtherT, int OtherDim>
+ __host__ __device__ bool isSameSize(
+ const Tensor<OtherT, OtherDim, InnerContig, IndexT, PtrTraits>& rhs)
+ const;
+
+ /// Cast to a tensor of a different type of the same size and
+ /// stride. U and our type T must be of the same size
+ template <typename U>
+ __host__ __device__ Tensor<U, Dim, InnerContig, IndexT, PtrTraits> cast();
+
+ /// Const version of `cast`
+ template <typename U>
+ __host__ __device__ const Tensor<U, Dim, InnerContig, IndexT, PtrTraits>
+ cast() const;
+
+ /// Cast to a tensor of a different type which is potentially a
+ /// different size than our type T. Tensor must be aligned and the
+ /// innermost dimension must be a size that is a multiple of
+ /// sizeof(U) / sizeof(T), and the stride of the innermost dimension
+ /// must be contiguous. The stride of all outer dimensions must be a
+ /// multiple of sizeof(U) / sizeof(T) as well.
+ template <typename U>
+ __host__ __device__ Tensor<U, Dim, InnerContig, IndexT, PtrTraits>
+ castResize();
+
+ /// Const version of `castResize`
+ template <typename U>
+ __host__ __device__ const Tensor<U, Dim, InnerContig, IndexT, PtrTraits>
+ castResize() const;
+
+ /// Returns true if we can castResize() this tensor to the new type
+ template <typename U>
+ __host__ __device__ bool canCastResize() const;
+
+ /// Attempts to cast this tensor to a tensor of a different IndexT.
+ /// Fails if size or stride entries are not representable in the new
+ /// IndexT.
+ template <typename NewIndexT>
+ __host__ Tensor<T, Dim, InnerContig, NewIndexT, PtrTraits> castIndexType()
+ const;
+
+ /// Returns true if we can use this indexing type to access all elements
+ /// index type
+ template <typename NewIndexT>
+ __host__ bool canUseIndexType() const;
+
+ /// Returns a raw pointer to the start of our data.
+ __host__ __device__ inline DataPtrType data() {
+ return data_;
+ }
+
+ /// Returns a raw pointer to the end of our data, assuming
+ /// continuity
+ __host__ __device__ inline DataPtrType end() {
+ return data() + numElements();
+ }
+
+ /// Returns a raw pointer to the start of our data (const).
+ __host__ __device__ inline const DataPtrType data() const {
+ return data_;
+ }
+
+ /// Returns a raw pointer to the end of our data, assuming
+ /// continuity (const)
+ __host__ __device__ inline DataPtrType end() const {
+ return data() + numElements();
+ }
+
+ /// Cast to a different datatype
+ template <typename U>
+ __host__ __device__ inline typename PtrTraits<U>::PtrType dataAs() {
+ return reinterpret_cast<typename PtrTraits<U>::PtrType>(data_);
+ }
+
+ /// Cast to a different datatype
+ template <typename U>
+ __host__ __device__ inline const typename PtrTraits<const U>::PtrType
+ dataAs() const {
+ return reinterpret_cast<typename PtrTraits<const U>::PtrType>(data_);
+ }
+
+ /// Returns a read/write view of a portion of our tensor.
+ __host__ __device__ inline detail::
+ SubTensor<TensorType, Dim - 1, PtrTraits> operator[](IndexT);
+
+ /// Returns a read/write view of a portion of our tensor (const).
+ __host__ __device__ inline const detail::
+ SubTensor<TensorType, Dim - 1, PtrTraits> operator[](IndexT) const;
+
+ /// Returns the size of a given dimension, `[0, Dim - 1]`. No bounds
+ /// checking.
+ __host__ __device__ inline IndexT getSize(int i) const {
+ return size_[i];
+ }
+
+ /// Returns the stride of a given dimension, `[0, Dim - 1]`. No bounds
+ /// checking.
+ __host__ __device__ inline IndexT getStride(int i) const {
+ return stride_[i];
+ }
+
+ /// Returns the total number of elements contained within our data
+ /// (product of `getSize(i)`)
+ __host__ __device__ IndexT numElements() const;
+
+ /// If we are contiguous, returns the total size in bytes of our
+ /// data
+ __host__ __device__ size_t getSizeInBytes() const {
+ return numElements() * sizeof(T);
+ }
+
+ /// Returns the size array.
+ __host__ __device__ inline const IndexT* sizes() const {
+ return size_;
+ }
+
+ /// Returns the stride array.
+ __host__ __device__ inline const IndexT* strides() const {
+ return stride_;
+ }
+
+ /// Returns true if there is no padding within the tensor and no
+ /// re-ordering of the dimensions.
+ /// ~~~
+ /// (stride(i) == size(i + 1) * stride(i + 1)) && stride(dim - 1) == 0
+ /// ~~~
+ __host__ __device__ bool isContiguous() const;
+
+ /// Returns whether a given dimension has only increasing stride
+ /// from the previous dimension. A tensor that was permuted by
+ /// exchanging size and stride only will fail this check.
+ /// If `i == 0` just check `size > 0`. Returns `false` if `stride` is `<=
+ /// 0`.
+ __host__ __device__ bool isConsistentlySized(int i) const;
+
+ // Returns whether at each dimension `stride <= size`.
+ // If this is not the case then iterating once over the size space will
+ // touch the same memory locations multiple times.
+ __host__ __device__ bool isConsistentlySized() const;
+
+ /// Returns true if the given dimension index has no padding
+ __host__ __device__ bool isContiguousDim(int i) const;
+
+ /// Returns a tensor of the same dimension after transposing the two
+ /// dimensions given. Does not actually move elements; transposition
+ /// is made by permuting the size/stride arrays.
+ /// If the dimensions are not valid, asserts.
+ __host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits> transpose(
+ int dim1,
+ int dim2) const;
+
+ /// Transpose a tensor, exchanging a non-innermost dimension with the
+ /// innermost dimension, returning a no longer innermost contiguous tensor
+ __host__ __device__ Tensor<T, Dim, false, IndexT, PtrTraits>
+ transposeInnermost(int dim1) const;
+
+ /// Upcast a tensor of dimension `D` to some tensor of dimension
+ /// D' > D by padding the leading dimensions by 1
+ /// e.g., upcasting a 2-d tensor `[2][3]` to a 4-d tensor `[1][1][2][3]`
+ template <int NewDim>
+ __host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>
+ upcastOuter();
+
+ /// Upcast a tensor of dimension `D` to some tensor of dimension
+ /// D' > D by padding the lowest/most varying dimensions by 1
+ /// e.g., upcasting a 2-d tensor `[2][3]` to a 4-d tensor `[2][3][1][1]`
+ template <int NewDim>
+ __host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>
+ upcastInner();
+
+ /// Downcast a tensor of dimension `D` to some tensor of dimension
+ /// D' < D by collapsing the leading dimensions. asserts if there is
+ /// padding on the leading dimensions.
+ template <int NewDim>
+ __host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>
+ downcastOuter();
+
+ /// Downcast a tensor of dimension `D` to some tensor of dimension
+ /// D' < D by collapsing the leading dimensions. asserts if there is
+ /// padding on the leading dimensions.
+ template <int NewDim>
+ __host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits>
+ downcastInner();
+
+ /// Returns a tensor that is a view of the `SubDim`-dimensional slice
+ /// of this tensor, starting at `at`.
+ template <int SubDim>
+ __host__ __device__ Tensor<T, SubDim, InnerContig, IndexT, PtrTraits> view(
+ DataPtrType at);
+
+ /// Returns a tensor that is a view of the `SubDim`-dimensional slice
+ /// of this tensor, starting where our data begins
+ template <int SubDim>
+ __host__ __device__ Tensor<T, SubDim, InnerContig, IndexT, PtrTraits> view();
+
+ /// Returns a tensor of the same dimension that is a view of the
+ /// original tensor with the specified dimension restricted to the
+ /// elements in the range [start, start + size)
+ __host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>
+ narrowOutermost(IndexT start, IndexT size);
+
+ /// Returns a tensor of the same dimension that is a view of the
+ /// original tensor with the specified dimension restricted to the
+ /// elements in the range [start, start + size).
+ /// Can occur in an arbitrary dimension
+ __host__ __device__ Tensor<T, Dim, InnerContig, IndexT, PtrTraits> narrow(
+ int dim,
+ IndexT start,
+ IndexT size);
+
+ /// Returns a view of the given tensor expressed as a tensor of a
+ /// different number of dimensions.
+ /// Only works if we are contiguous.
+ template <int NewDim>
+ __host__ __device__ Tensor<T, NewDim, InnerContig, IndexT, PtrTraits> view(
+ std::initializer_list<IndexT> sizes);
+
+ protected:
+ /// Raw pointer to where the tensor data begins
+ DataPtrType data_;
+
+ /// Array of strides (in sizeof(T) terms) per each dimension
+ IndexT stride_[Dim];
+
+ /// Size per each dimension
+ IndexT size_[Dim];
+};
+
+// Utilities for checking a collection of tensors
+namespace detail {
+
+template <typename IndexType>
+bool canUseIndexType() {
+ return true;
+}
+
+template <typename IndexType, typename T, typename... U>
+bool canUseIndexType(const T& arg, const U&... args) {
+ return arg.template canUseIndexType<IndexType>() &&
+ canUseIndexType(args...);
+}
+
+} // namespace detail
+
+template <typename IndexType, typename... T>
+bool canUseIndexType(const T&... args) {
+ return detail::canUseIndexType(args...);
+}
+
+namespace detail {
+
+/// Specialization for a view of a single value (0-dimensional)
+template <typename TensorType, template <typename U> class PtrTraits>
+class SubTensor<TensorType, 0, PtrTraits> {
+ public:
+ __host__ __device__ SubTensor<TensorType, 0, PtrTraits> operator=(
+ typename TensorType::DataType val) {
+ *data_ = val;
+ return *this;
+ }
+
+ // operator T&
+ __host__ __device__ operator typename TensorType::DataType &() {
+ return *data_;
+ }
+
+ // const operator T& returning const T&
+ __host__ __device__ operator const typename TensorType::DataType &() const {
+ return *data_;
+ }
+
+ // operator& returning T*
+ __host__ __device__ typename TensorType::DataType* operator&() {
+ return data_;
+ }
+
+ // const operator& returning const T*
+ __host__ __device__ const typename TensorType::DataType* operator&() const {
+ return data_;
+ }
+
+ /// Returns a raw accessor to our slice.
+ __host__ __device__ inline typename TensorType::DataPtrType data() {
+ return data_;
+ }
+
+ /// Returns a raw accessor to our slice (const).
+ __host__ __device__ inline const typename TensorType::DataPtrType data()
+ const {
+ return data_;
+ }
+
+ /// Cast to a different datatype.
+ template <typename T>
+ __host__ __device__ T& as() {
+ return *dataAs<T>();
+ }
+
+ /// Cast to a different datatype (const).
+ template <typename T>
+ __host__ __device__ const T& as() const {
+ return *dataAs<T>();
+ }
+
+ /// Cast to a different datatype
+ template <typename T>
+ __host__ __device__ inline typename PtrTraits<T>::PtrType dataAs() {
+ return reinterpret_cast<typename PtrTraits<T>::PtrType>(data_);
+ }
+
+ /// Cast to a different datatype (const)
+ template <typename T>
+ __host__ __device__ inline typename PtrTraits<const T>::PtrType dataAs()
+ const {
+ return reinterpret_cast<typename PtrTraits<const T>::PtrType>(data_);
+ }
+
+ /// Use the texture cache for reads
+ __device__ inline typename TensorType::DataType ldg() const {
+#if __CUDA_ARCH__ >= 350 || defined(USE_AMD_ROCM)
+ return __ldg(data_);
+#else
+ return *data_;
+#endif
+ }
+
+ /// Use the texture cache for reads; cast as a particular type
+ template <typename T>
+ __device__ inline T ldgAs() const {
+#if __CUDA_ARCH__ >= 350 || defined(USE_AMD_ROCM)
+ return __ldg(dataAs<T>());
+#else
+ return as<T>();
+#endif
+ }
+
+ protected:
+ /// One dimension greater can create us
+ friend class SubTensor<TensorType, 1, PtrTraits>;
+
+ /// Our parent tensor can create us
+ friend class Tensor<
+ typename TensorType::DataType,
+ 1,
+ TensorType::IsInnerContig,
+ typename TensorType::IndexType,
+ PtrTraits>;
+
+ __host__ __device__ inline SubTensor(
+ TensorType& t,
+ typename TensorType::DataPtrType data)
+ : tensor_(t), data_(data) {}
+
+ /// The tensor we're referencing
+ TensorType& tensor_;
+
+ /// Where our value is located
+ typename TensorType::DataPtrType const data_;
+};
+
+/// A `SubDim`-rank slice of a parent Tensor
+template <
+ typename TensorType,
+ int SubDim,
+ template <typename U>
+ class PtrTraits>
+class SubTensor {
+ public:
+ /// Returns a view of the data located at our offset (the dimension
+ /// `SubDim` - 1 tensor).
+ __host__ __device__ inline SubTensor<TensorType, SubDim - 1, PtrTraits>
+ operator[](typename TensorType::IndexType index) {
+ if (TensorType::IsInnerContig && SubDim == 1) {
+ // Innermost dimension is stride 1 for contiguous arrays
+ return SubTensor<TensorType, SubDim - 1, PtrTraits>(
+ tensor_, data_ + index);
+ } else {
+ return SubTensor<TensorType, SubDim - 1, PtrTraits>(
+ tensor_,
+ data_ +
+ index *
+ tensor_.getStride(
+ TensorType::NumDim - SubDim));
+ }
+ }
+
+ /// Returns a view of the data located at our offset (the dimension
+ /// `SubDim` - 1 tensor) (const).
+ __host__ __device__ inline const SubTensor<
+ TensorType,
+ SubDim - 1,
+ PtrTraits>
+ operator[](typename TensorType::IndexType index) const {
+ if (TensorType::IsInnerContig && SubDim == 1) {
+ // Innermost dimension is stride 1 for contiguous arrays
+ return SubTensor<TensorType, SubDim - 1, PtrTraits>(
+ tensor_, data_ + index);
+ } else {
+ return SubTensor<TensorType, SubDim - 1, PtrTraits>(
+ tensor_,
+ data_ +
+ index *
+ tensor_.getStride(
+ TensorType::NumDim - SubDim));
+ }
+ }
+
+ // operator& returning T*
+ __host__ __device__ typename TensorType::DataType* operator&() {
+ return data_;
+ }
+
+ // const operator& returning const T*
+ __host__ __device__ const typename TensorType::DataType* operator&() const {
+ return data_;
+ }
+
+ /// Returns a raw accessor to our slice.
+ __host__ __device__ inline typename TensorType::DataPtrType data() {
+ return data_;
+ }
+
+ /// Returns a raw accessor to our slice (const).
+ __host__ __device__ inline const typename TensorType::DataPtrType data()
+ const {
+ return data_;
+ }
+
+ /// Cast to a different datatype.
+ template <typename T>
+ __host__ __device__ T& as() {
+ return *dataAs<T>();
+ }
+
+ /// Cast to a different datatype (const).
+ template <typename T>
+ __host__ __device__ const T& as() const {
+ return *dataAs<T>();
+ }
+
+ /// Cast to a different datatype
+ template <typename T>
+ __host__ __device__ inline typename PtrTraits<T>::PtrType dataAs() {
+ return reinterpret_cast<typename PtrTraits<T>::PtrType>(data_);
+ }
+
+ /// Cast to a different datatype (const)
+ template <typename T>
+ __host__ __device__ inline typename PtrTraits<const T>::PtrType dataAs()
+ const {
+ return reinterpret_cast<typename PtrTraits<const T>::PtrType>(data_);
+ }
+
+ /// Use the texture cache for reads
+ __device__ inline typename TensorType::DataType ldg() const {
+#if __CUDA_ARCH__ >= 350 || defined(USE_AMD_ROCM)
+ return __ldg(data_);
+#else
+ return *data_;
+#endif
+ }
+
+ /// Use the texture cache for reads; cast as a particular type
+ template <typename T>
+ __device__ inline T ldgAs() const {
+#if __CUDA_ARCH__ >= 350 || defined(USE_AMD_ROCM)
+ return __ldg(dataAs<T>());
+#else
+ return as<T>();
+#endif
+ }
+
+ /// Returns a tensor that is a view of the SubDim-dimensional slice
+ /// of this tensor, starting where our data begins
+ Tensor<typename TensorType::DataType,
+ SubDim,
+ TensorType::IsInnerContig,
+ typename TensorType::IndexType,
+ PtrTraits>
+ view() {
+ return tensor_.template view<SubDim>(data_);
+ }
+
+ protected:
+ /// One dimension greater can create us
+ friend class SubTensor<TensorType, SubDim + 1, PtrTraits>;
+
+ /// Our parent tensor can create us
+ friend class Tensor<
+ typename TensorType::DataType,
+ TensorType::NumDim,
+ TensorType::IsInnerContig,
+ typename TensorType::IndexType,
+ PtrTraits>;
+
+ __host__ __device__ inline SubTensor(
+ TensorType& t,
+ typename TensorType::DataPtrType data)
+ : tensor_(t), data_(data) {}
+
+ /// The tensor we're referencing
+ TensorType& tensor_;
+
+ /// The start of our sub-region
+ typename TensorType::DataPtrType const data_;
+};
+
+} // namespace detail
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ inline detail::SubTensor<
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>,
+ Dim - 1,
+ PtrTraits>
+Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::operator[](IndexT index) {
+ return detail::SubTensor<TensorType, Dim - 1, PtrTraits>(
+ detail::SubTensor<TensorType, Dim, PtrTraits>(*this, data_)[index]);
+}
+
+template <
+ typename T,
+ int Dim,
+ bool InnerContig,
+ typename IndexT,
+ template <typename U>
+ class PtrTraits>
+__host__ __device__ inline const detail::SubTensor<
+ Tensor<T, Dim, InnerContig, IndexT, PtrTraits>,
+ Dim - 1,
+ PtrTraits>
+Tensor<T, Dim, InnerContig, IndexT, PtrTraits>::operator[](IndexT index) const {
+ return detail::SubTensor<TensorType, Dim - 1, PtrTraits>(
+ detail::SubTensor<TensorType, Dim, PtrTraits>(
+ const_cast<TensorType&>(*this), data_)[index]);
+}
+
+} // namespace gpu
+} // namespace faiss
+
+#include <faiss/gpu/utils/Tensor-inl.cuh>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ThrustUtils.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ThrustUtils.cuh
new file mode 100644
index 0000000..1bf4805
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/ThrustUtils.cuh
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/GpuResources.h>
+#include <thrust/device_vector.h>
+#include <unordered_set>
+
+namespace faiss {
+namespace gpu {
+
+/// Allocator for Thrust that comes out of a specified memory space
+class ThrustAllocator {
+ public:
+ typedef char value_type;
+
+ inline ThrustAllocator(
+ GpuResources* res,
+ cudaStream_t stream,
+ void* mem,
+ size_t size)
+ : res_(res),
+ stream_(stream),
+ start_((char*)mem),
+ cur_((char*)mem),
+ end_((char*)mem + size) {}
+
+ inline ~ThrustAllocator() {
+ // In the case of an exception being thrown, we may not have called
+ // deallocate on all of our sub-allocations. Free them here
+ for (auto p : mallocAllocs_) {
+ res_->deallocMemory(getCurrentDevice(), p);
+ }
+ }
+
+ inline char* allocate(std::ptrdiff_t size) {
+ if (size <= (end_ - cur_)) {
+ char* p = cur_;
+ cur_ += size;
+ FAISS_ASSERT(cur_ <= end_);
+
+ return p;
+ } else {
+ // FIXME: we cannot use temporary memory for new requests because
+ // the current temporary memory allocator cannot handle stream
+ // synchronization at present, so just allocate through the general
+ // device
+ char* p = (char*)res_->allocMemory(AllocRequest(
+ makeDevAlloc(AllocType::Other, stream_), size));
+
+ mallocAllocs_.insert(p);
+ return p;
+ }
+ }
+
+ inline void deallocate(char* p, size_t size) {
+ // Allocations could be returned out-of-order; ignore those we
+ // didn't cudaMalloc
+ auto it = mallocAllocs_.find(p);
+ if (it != mallocAllocs_.end()) {
+ res_->deallocMemory(getCurrentDevice(), p);
+ mallocAllocs_.erase(it);
+ }
+ }
+
+ private:
+ GpuResources* res_;
+ cudaStream_t stream_;
+ char* start_;
+ char* cur_;
+ char* end_;
+ std::unordered_set<char*> mallocAllocs_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Timer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Timer.cpp
new file mode 100644
index 0000000..6993257
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Timer.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/Timer.h>
+#include <faiss/impl/FaissAssert.h>
+#include <chrono>
+
+namespace faiss {
+namespace gpu {
+
+KernelTimer::KernelTimer(cudaStream_t stream)
+ : startEvent_(nullptr),
+ stopEvent_(nullptr),
+ stream_(stream),
+ valid_(true) {
+ CUDA_VERIFY(cudaEventCreate(&startEvent_));
+ CUDA_VERIFY(cudaEventCreate(&stopEvent_));
+
+ CUDA_VERIFY(cudaEventRecord(startEvent_, stream_));
+}
+
+KernelTimer::~KernelTimer() {
+ CUDA_VERIFY(cudaEventDestroy(startEvent_));
+ CUDA_VERIFY(cudaEventDestroy(stopEvent_));
+}
+
+float KernelTimer::elapsedMilliseconds() {
+ FAISS_ASSERT(valid_);
+
+ CUDA_VERIFY(cudaEventRecord(stopEvent_, stream_));
+ CUDA_VERIFY(cudaEventSynchronize(stopEvent_));
+
+ auto time = 0.0f;
+ CUDA_VERIFY(cudaEventElapsedTime(&time, startEvent_, stopEvent_));
+ valid_ = false;
+
+ return time;
+}
+
+CpuTimer::CpuTimer() {
+ start_ = std::chrono::steady_clock::now();
+}
+
+float CpuTimer::elapsedMilliseconds() {
+ auto end = std::chrono::steady_clock::now();
+
+ std::chrono::duration<float, std::milli> duration = end - start_;
+
+ return duration.count();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Timer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Timer.h
new file mode 100644
index 0000000..8b52e6c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Timer.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda_runtime.h>
+#include <chrono>
+
+namespace faiss {
+namespace gpu {
+
+/// Utility class for timing execution of a kernel
+class KernelTimer {
+ public:
+ /// Constructor starts the timer and adds an event into the current
+ /// device stream
+ KernelTimer(cudaStream_t stream = nullptr);
+
+ /// Destructor releases event resources
+ ~KernelTimer();
+
+ /// Adds a stop event then synchronizes on the stop event to get the
+ /// actual GPU-side kernel timings for any kernels launched in the
+ /// current stream. Returns the number of milliseconds elapsed.
+ /// Can only be called once.
+ float elapsedMilliseconds();
+
+ private:
+ cudaEvent_t startEvent_;
+ cudaEvent_t stopEvent_;
+ cudaStream_t stream_;
+ bool valid_;
+};
+
+/// CPU wallclock elapsed timer
+class CpuTimer {
+ public:
+ /// Creates and starts a new timer
+ CpuTimer();
+
+ /// Returns elapsed time in milliseconds
+ float elapsedMilliseconds();
+
+ private:
+ std::chrono::time_point<std::chrono::steady_clock> start_;
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Transpose.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Transpose.cuh
new file mode 100644
index 0000000..9ab90bb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/Transpose.cuh
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+#include <faiss/gpu/utils/StaticUtils.h>
+#include <faiss/impl/FaissAssert.h>
+#include <stdint.h>
+#include <faiss/gpu/utils/Tensor.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <typename T>
+struct TensorInfo {
+ static constexpr int kMaxDims = 8;
+
+ T* data;
+ idx_t sizes[kMaxDims];
+ idx_t strides[kMaxDims];
+ int dims;
+};
+
+template <typename T, int Dim>
+struct TensorInfoOffset {
+ __device__ inline static idx_t get(
+ const TensorInfo<T>& info,
+ idx_t linearId) {
+ idx_t offset = 0;
+
+#pragma unroll
+ for (int i = Dim - 1; i >= 0; --i) {
+ auto curDimIndex = linearId % info.sizes[i];
+ auto curDimOffset = curDimIndex * info.strides[i];
+
+ offset += curDimOffset;
+
+ if (i > 0) {
+ linearId /= info.sizes[i];
+ }
+ }
+
+ return offset;
+ }
+};
+
+template <typename T>
+struct TensorInfoOffset<T, -1> {
+ __device__ inline static idx_t get(
+ const TensorInfo<T>& info,
+ idx_t linearId) {
+ return linearId;
+ }
+};
+
+template <typename T, int Dim>
+TensorInfo<T> getTensorInfo(const Tensor<T, Dim, true>& t) {
+ TensorInfo<T> info;
+
+ for (int i = 0; i < Dim; ++i) {
+ info.sizes[i] = t.getSize(i);
+ info.strides[i] = t.getStride(i);
+ }
+
+ info.data = t.data();
+ info.dims = Dim;
+
+ return info;
+}
+
+template <typename T, int DimInput, int DimOutput>
+__global__ void transposeAny(
+ TensorInfo<T> input,
+ TensorInfo<T> output,
+ idx_t totalSize) {
+ for (idx_t i = idx_t(blockIdx.x) * blockDim.x + threadIdx.x; i < totalSize;
+ i += gridDim.x * blockDim.x) {
+ auto inputOffset = TensorInfoOffset<T, DimInput>::get(input, i);
+ auto outputOffset = TensorInfoOffset<T, DimOutput>::get(output, i);
+
+#if __CUDA_ARCH__ >= 350 || defined(USE_AMD_ROCM)
+ output.data[outputOffset] = __ldg(&input.data[inputOffset]);
+#else
+ output.data[outputOffset] = input.data[inputOffset];
+#endif
+ }
+}
+
+// Transpose contiguous t1 t2 i1 -> t2 t1 i1
+template <typename T>
+__global__ void transposeOuter(
+ const T* in,
+ T* out,
+ idx_t t1,
+ idx_t t2,
+ idx_t i1) {
+ idx_t gt2 = blockIdx.x;
+ for (idx_t gt1 = blockIdx.y; gt1 < t1; gt1 += gridDim.y) {
+ auto curIn = in + i1 * (gt1 * t2 + gt2);
+ auto curOut = out + i1 * (gt2 * t1 + gt1);
+
+ for (idx_t i = threadIdx.x; i < i1; i += blockDim.x) {
+ curOut[i] = curIn[i];
+ }
+ }
+}
+
+/// Performs an out-of-place transposition between any two dimensions.
+/// Best performance is if the transposed dimensions are not
+/// innermost, since the reads and writes will be coalesced.
+/// Could include a shared memory transposition if the dimensions
+/// being transposed are innermost, but would require support for
+/// arbitrary rectangular matrices.
+/// This linearized implementation seems to perform well enough,
+/// especially for cases that we care about (outer dimension
+/// transpositions).
+template <typename T, int Dim>
+void runTransposeAny(
+ Tensor<T, Dim, true>& in,
+ int dim1,
+ int dim2,
+ Tensor<T, Dim, true>& out,
+ cudaStream_t stream) {
+ static_assert(Dim <= TensorInfo<T>::kMaxDims, "too many dimensions");
+
+ FAISS_ASSERT(dim1 != dim2);
+ FAISS_ASSERT(dim1 < Dim && dim2 < Dim);
+
+ // Rearrange dim1 and dim2 in increasing order in order to see if this is an
+ // outer dimension transposition (below)
+ if (dim1 > dim2) {
+ std::swap(dim1, dim2);
+ }
+
+ idx_t outSize[Dim];
+
+ for (int i = 0; i < Dim; ++i) {
+ outSize[i] = in.getSize(i);
+ }
+
+ std::swap(outSize[dim1], outSize[dim2]);
+
+ for (int i = 0; i < Dim; ++i) {
+ FAISS_ASSERT(out.getSize(i) == outSize[i]);
+ }
+
+ idx_t maxThreads = getMaxThreadsCurrentDevice();
+ auto totalSize = in.numElements();
+
+ // Is this a transposition of the two outer dimensions?
+ bool isTransposeOuter = (Dim >= 3) && (dim1 == 0) && (dim2 == 1);
+ if (isTransposeOuter) {
+ // Outer dimension transposition only (there is a contiguous inner
+ // dimension)
+ size_t innerSize = 1;
+ for (int i = 2; i < Dim; ++i) {
+ innerSize *= in.getSize(i);
+ }
+
+ // The grid y dimension is more limited; we do a grid loop if necessary
+ idx_t maxGridY = getCurrentDeviceProperties().maxGridSize[1];
+ auto grid = dim3(in.getSize(1), std::min(in.getSize(0), maxGridY));
+
+ int block = (innerSize < maxThreads) ? innerSize : maxThreads;
+
+ transposeOuter<T><<<grid, block, 0, stream>>>(
+ in.data(), out.data(), in.getSize(0), in.getSize(1), innerSize);
+ } else {
+ idx_t block = (totalSize < maxThreads) ? totalSize : maxThreads;
+
+ auto inInfo = getTensorInfo<T, Dim>(in);
+ auto outInfo = getTensorInfo<T, Dim>(out);
+
+ std::swap(inInfo.sizes[dim1], inInfo.sizes[dim2]);
+ std::swap(inInfo.strides[dim1], inInfo.strides[dim2]);
+
+ auto grid = std::min(utils::divUp(totalSize, block), (idx_t)4096);
+
+ transposeAny<T, Dim, -1>
+ <<<grid, block, 0, stream>>>(inInfo, outInfo, totalSize);
+ }
+
+ CUDA_TEST_ERROR();
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpPackedBits.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpPackedBits.cuh
new file mode 100644
index 0000000..1588efb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpPackedBits.cuh
@@ -0,0 +1,281 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/PtxUtils.cuh>
+#include <faiss/gpu/utils/WarpShuffles.cuh>
+
+namespace faiss {
+namespace gpu {
+
+//
+// Warp-coalesced parallel reading and writing of packed bits
+//
+
+// Read/write native word sizes
+template <typename WordT, int Bits>
+struct WarpPackedBits {
+ static __device__ void write(int laneId, WordT v, bool valid, WordT* out) {
+ static_assert(sizeof(WordT) == Bits / 8 && (Bits % 8) == 0, "");
+ // We can just write directly
+ if (valid) {
+ out[laneId] = v;
+ }
+ }
+
+ static inline __device__ WordT read(int laneId, WordT* in) {
+ return in[laneId];
+ }
+
+ static inline __device__ WordT postRead(int laneId, WordT v) {
+ return v;
+ }
+};
+
+// Read/write 6 bit fields, packed across the warp into 24 bytes
+template <>
+struct WarpPackedBits<uint8_t, 6> {
+ static __device__ void write(
+ int laneId,
+ uint8_t v,
+ bool valid,
+ uint8_t* out) {
+ // Lower kWarpSize*3/4 lanes (24 or 48) write out packed data
+ int laneFrom = (laneId * 8) / 6;
+
+ v = valid ? v : 0;
+ v &= 0x3f; // ensure we have only 6 bits
+
+ uint8_t vLower =
+ (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom, kWarpSize);
+ uint8_t vUpper =
+ (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom + 1, kWarpSize);
+
+ // lsb ... msb
+ // 0: 0 0 0 0 0 0 1 1
+ // 1: 1 1 1 1 2 2 2 2
+ // 2: 2 2 3 3 3 3 3 3
+ int typeLane = laneId % 3;
+ uint8_t vOut = 0;
+ switch (typeLane) {
+ case 0:
+ // 6 msbs of lower as vOut lsbs
+ // 2 lsbs of upper as vOut msbs
+ vOut = vLower | (vUpper << 6);
+ break;
+ case 1:
+ // 4 msbs of lower as vOut lsbs
+ // 4 lsbs of upper as vOut msbs
+ vOut = (vLower >> 2) | (vUpper << 4);
+ break;
+ case 2:
+ // 2 msbs of lower as vOut lsbs
+ // 6 lsbs of upper as vOut msbs
+ vOut = (vLower >> 4) | (vUpper << 2);
+ break;
+ }
+
+ if (laneId < kWarpSize * 3 / 4) {
+ // There could be prior data
+ out[laneId] |= vOut;
+ }
+ }
+
+ static inline __device__ uint8_t read(int laneId, uint8_t* in) {
+ uint8_t v = 0;
+
+ if (laneId < kWarpSize * 3 / 4) {
+ v = in[laneId];
+ }
+
+ return v;
+ }
+
+ static inline __device__ uint8_t postRead(int laneId, uint8_t v) {
+ int laneFrom = (laneId * 6) / 8;
+
+ auto vLower = SHFL_SYNC((unsigned int)v, laneFrom, kWarpSize);
+ auto vUpper = SHFL_SYNC((unsigned int)v, laneFrom + 1, kWarpSize);
+ auto vConcat = (vUpper << 8) | vLower;
+
+ // Now, this is weird. Each lane reads two uint8, but we wish to use the
+ // bfe.u32 instruction to read a 6 bit value from the concatenated
+ // uint32. The offset in which we wish to read in the concatenated word
+ // is the following:
+ //
+ // 0: 0, 1: offset 0 size 6
+ // 1: 0, 1: offset 6 size 6
+ // 2: 1, 2: offset 4 size 6
+ // 3: 2, 3: offset 2 size 6
+ //
+ // The offsets are the following (concatenated together):
+ // 0x2460
+ // We can thus use bfe.u32 as a lookup table for the above sequence.
+ unsigned int pos;
+ GET_BITFIELD_U32(pos, 0x2460, (laneId & 0x3) * 4, 4);
+
+ unsigned int out;
+ GET_BITFIELD_U32(out, vConcat, pos, 6);
+
+ return out;
+ }
+};
+
+// Read/write 5 bit fields, packed across the warp into 20 bytes
+template <>
+struct WarpPackedBits<uint8_t, 5> {
+ static __device__ void write(
+ int laneId,
+ uint8_t v,
+ bool valid,
+ uint8_t* out) {
+ // Lower 24 lanes wwrite out packed data
+ int laneFrom = (laneId * 8) / 5;
+
+ v = valid ? v : 0;
+ v &= 0x1f; // ensure we have only 6 bits
+
+ uint8_t lo = (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom, kWarpSize);
+ uint8_t hi =
+ (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom + 1, kWarpSize);
+ uint8_t hi2 =
+ (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom + 2, kWarpSize);
+
+ uint8_t vOut = 0;
+
+ // lsb ... msb
+ // 0: 0 0 0 0 0 1 1 1
+ // 1: 1 1 2 2 2 2 2 3
+ // 2: 3 3 3 3 4 4 4 4
+ // 3: 4 5 5 5 5 5 6 6
+ // 4: 6 6 6 7 7 7 7 7
+ switch (laneId % 5) {
+ case 0:
+ // 5 msbs of lower as vOut lsbs
+ // 3 lsbs of upper as vOut msbs
+ vOut = (lo & 0x1f) | (hi << 5);
+ break;
+ case 1:
+ // 2 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ // 1 lsbs of upper2 as vOut msb
+ vOut = (lo >> 3) | (hi << 2) | (hi2 << 7);
+ break;
+ case 2:
+ // 4 msbs of lower as vOut lsbs
+ // 4 lsbs of upper as vOut msbs
+ vOut = (lo >> 1) | (hi << 4);
+ break;
+ case 3:
+ // 1 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ // 2 lsbs of upper2 as vOut msb
+ vOut = (lo >> 4) | (hi << 1) | (hi2 << 6);
+ break;
+ case 4:
+ // 3 msbs of lower as vOut lsbs
+ // 5 lsbs of upper as vOut msbs
+ vOut = (lo >> 2) | (hi << 3);
+ break;
+ }
+
+ if (laneId < 20) {
+ // There could be prior data
+ out[laneId] |= vOut;
+ }
+ }
+
+ static inline __device__ uint8_t read(int laneId, uint8_t* in) {
+ uint8_t v = 0;
+
+ if (laneId < 20) {
+ v = in[laneId];
+ }
+
+ return v;
+ }
+
+ static inline __device__ uint8_t postRead(int laneId, uint8_t v) {
+ int laneFrom = (laneId * 5) / 8;
+
+ auto vLower = SHFL_SYNC((unsigned int)v, laneFrom, kWarpSize);
+ auto vUpper = SHFL_SYNC((unsigned int)v, laneFrom + 1, kWarpSize);
+ auto vConcat = (vUpper << 8) | vLower;
+
+ // Now, this is weird. Each lane reads two uint8, but we wish to use the
+ // bfe.u32 instruction to read a 5 bit value from the concatenated
+ // uint32. The offset in which we wish to read in the concatenated word
+ // is the following:
+ //
+ // 0: 0, 1: offset 0 size 5
+ // 1: 0, 1: offset 5 size 5
+ // 2: 1, 2: offset 2 size 5
+ // 3: 1, 2: offset 7 size 5
+ // 4: 2, 3: offset 4 size 5
+ // 5: 3, 4: offset 1 size 5
+ // 6: 3, 4: offset 6 size 5
+ // 7: 4, 5: offset 3 size 5
+ //
+ // The offsets are the following (concatenated together):
+ // 0x36147250
+ // We can thus use bfe.u32 as a lookup table for the above sequence.
+ unsigned int pos;
+ GET_BITFIELD_U32(pos, 0x36147250, (laneId & 0x7) * 4, 4);
+
+ unsigned int out;
+ GET_BITFIELD_U32(out, vConcat, pos, 5);
+
+ return out;
+ }
+};
+
+// Read/write 4 bit fields, packed across the warp into 16 bytes
+template <>
+struct WarpPackedBits<uint8_t, 4> {
+ static __device__ void write(
+ int laneId,
+ uint8_t v,
+ bool valid,
+ uint8_t* out) {
+ // Lower kWarpSize/2 (16 or 32) lanes write out packed data
+ int laneFrom = laneId * 2;
+
+ v = valid ? v : 0;
+
+ uint8_t vLower =
+ (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom, kWarpSize);
+ uint8_t vUpper =
+ (uint8_t)SHFL_SYNC((unsigned int)v, laneFrom + 1, kWarpSize);
+
+ uint8_t vOut = (vLower & 0xf) | (vUpper << 4);
+
+ if (laneId < kWarpSize / 2) {
+ // There could be prior data
+ out[laneId] |= vOut;
+ }
+ }
+
+ static inline __device__ uint8_t read(int laneId, uint8_t* in) {
+ uint8_t v = 0;
+
+ if (laneId < kWarpSize / 2) {
+ v = in[laneId];
+ }
+
+ return v;
+ }
+
+ static inline __device__ uint8_t postRead(int laneId, uint8_t v) {
+ int laneFrom = laneId / 2;
+ auto v2 = shfl((unsigned int)v, laneFrom);
+ return getBitfield(v2, (laneId & 0x1) * 4, 4);
+ }
+};
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpSelectFloat.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpSelectFloat.cu
new file mode 100644
index 0000000..62af91a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpSelectFloat.cu
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// warp Q to thread Q:
+// 1, 1
+// 32, 2
+// 64, 3
+// 128, 3
+// 256, 4
+// 512, 8
+// 1024, 8
+// 2048, 8
+
+WARP_SELECT_DECL(float, true, 1);
+WARP_SELECT_DECL(float, true, 32);
+WARP_SELECT_DECL(float, true, 64);
+WARP_SELECT_DECL(float, true, 128);
+WARP_SELECT_DECL(float, true, 256);
+WARP_SELECT_DECL(float, true, 512);
+WARP_SELECT_DECL(float, true, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+WARP_SELECT_DECL(float, true, 2048);
+#endif
+
+WARP_SELECT_DECL(float, false, 1);
+WARP_SELECT_DECL(float, false, 32);
+WARP_SELECT_DECL(float, false, 64);
+WARP_SELECT_DECL(float, false, 128);
+WARP_SELECT_DECL(float, false, 256);
+WARP_SELECT_DECL(float, false, 512);
+WARP_SELECT_DECL(float, false, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+WARP_SELECT_DECL(float, false, 2048);
+#endif
+
+void runWarpSelect(
+ Tensor<float, 2, true>& in,
+ Tensor<float, 2, true>& outK,
+ Tensor<idx_t, 2, true>& outV,
+ bool dir,
+ int k,
+ cudaStream_t stream) {
+ FAISS_ASSERT(k <= 2048);
+
+ if (dir) {
+ if (k == 1) {
+ WARP_SELECT_CALL(float, true, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ WARP_SELECT_CALL(float, true, 32);
+ } else if (k <= 64) {
+ WARP_SELECT_CALL(float, true, 64);
+ } else if (k <= 128) {
+ WARP_SELECT_CALL(float, true, 128);
+ } else if (k <= 256) {
+ WARP_SELECT_CALL(float, true, 256);
+ } else if (k <= 512) {
+ WARP_SELECT_CALL(float, true, 512);
+ } else if (k <= 1024) {
+ WARP_SELECT_CALL(float, true, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ WARP_SELECT_CALL(float, true, 2048);
+#endif
+ }
+ } else {
+ if (k == 1) {
+ WARP_SELECT_CALL(float, false, 1);
+ } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) {
+ WARP_SELECT_CALL(float, false, 32);
+ } else if (k <= 64) {
+ WARP_SELECT_CALL(float, false, 64);
+ } else if (k <= 128) {
+ WARP_SELECT_CALL(float, false, 128);
+ } else if (k <= 256) {
+ WARP_SELECT_CALL(float, false, 256);
+ } else if (k <= 512) {
+ WARP_SELECT_CALL(float, false, 512);
+ } else if (k <= 1024) {
+ WARP_SELECT_CALL(float, false, 1024);
+#if GPU_MAX_SELECTION_K >= 2048
+ } else if (k <= 2048) {
+ WARP_SELECT_CALL(float, false, 2048);
+#endif
+ }
+ }
+}
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpSelectKernel.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpSelectKernel.cuh
new file mode 100644
index 0000000..bb5a7a1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpSelectKernel.cuh
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/Select.cuh>
+
+namespace faiss {
+namespace gpu {
+
+template <
+ typename K,
+ typename IndexType,
+ bool Dir,
+ int NumWarpQ,
+ int NumThreadQ,
+ int ThreadsPerBlock>
+__global__ void warpSelect(
+ Tensor<K, 2, true> in,
+ Tensor<K, 2, true> outK,
+ Tensor<IndexType, 2, true> outV,
+ K initK,
+ IndexType initV,
+ int k) {
+ if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) {
+ constexpr int kNumWarps = ThreadsPerBlock / kWarpSize;
+
+ WarpSelect<
+ K,
+ IndexType,
+ Dir,
+ Comparator<K>,
+ NumWarpQ,
+ NumThreadQ,
+ ThreadsPerBlock>
+ heap(initK, initV, k);
+
+ int warpId = threadIdx.x / kWarpSize;
+ idx_t row = idx_t(blockIdx.x) * kNumWarps + warpId;
+
+ if (row >= in.getSize(0)) {
+ return;
+ }
+
+ idx_t i = getLaneId();
+ K* inStart = in[row][i].data();
+
+ // Whole warps must participate in the selection
+ idx_t limit = utils::roundDown(in.getSize(1), kWarpSize);
+
+ for (; i < limit; i += kWarpSize) {
+ heap.add(*inStart, (IndexType)i);
+ inStart += kWarpSize;
+ }
+
+ // Handle non-warp multiple remainder
+ if (i < in.getSize(1)) {
+ heap.addThreadQ(*inStart, (IndexType)i);
+ }
+
+ heap.reduce();
+ heap.writeOut(outK[row].data(), outV[row].data(), k);
+ }
+}
+
+void runWarpSelect(
+ Tensor<float, 2, true>& in,
+ Tensor<float, 2, true>& outKeys,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool dir,
+ int k,
+ cudaStream_t stream);
+
+void runWarpSelect(
+ Tensor<half, 2, true>& in,
+ Tensor<half, 2, true>& outKeys,
+ Tensor<idx_t, 2, true>& outIndices,
+ bool dir,
+ int k,
+ cudaStream_t stream);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpShuffles.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpShuffles.cuh
new file mode 100644
index 0000000..3c70b07
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/WarpShuffles.cuh
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cuda.h>
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+
+namespace faiss {
+namespace gpu {
+
+// defines to simplify the SASS assembly structure file/line in the profiler
+#if CUDA_VERSION >= 9000
+#define SHFL_SYNC(VAL, SRC_LANE, WIDTH) \
+ __shfl_sync(0xffffffff, VAL, SRC_LANE, WIDTH)
+#else
+#define SHFL_SYNC(VAL, SRC_LANE, WIDTH) __shfl(VAL, SRC_LANE, WIDTH)
+#endif
+
+template <typename T>
+inline __device__ T shfl(const T val, int srcLane, int width = kWarpSize) {
+#if CUDA_VERSION >= 9000
+ return __shfl_sync(0xffffffff, val, srcLane, width);
+#else
+ return __shfl(val, srcLane, width);
+#endif
+}
+
+// CUDA SDK does not provide specializations for T*
+template <typename T>
+inline __device__ T* shfl(T* const val, int srcLane, int width = kWarpSize) {
+ static_assert(sizeof(T*) == sizeof(long long), "pointer size");
+ long long v = (long long)val;
+
+ return (T*)shfl(v, srcLane, width);
+}
+
+template <typename T>
+inline __device__ T
+shfl_up(const T val, unsigned int delta, int width = kWarpSize) {
+#if CUDA_VERSION >= 9000
+ return __shfl_up_sync(0xffffffff, val, delta, width);
+#else
+ return __shfl_up(val, delta, width);
+#endif
+}
+
+// CUDA SDK does not provide specializations for T*
+template <typename T>
+inline __device__ T* shfl_up(
+ T* const val,
+ unsigned int delta,
+ int width = kWarpSize) {
+ static_assert(sizeof(T*) == sizeof(long long), "pointer size");
+ long long v = (long long)val;
+
+ return (T*)shfl_up(v, delta, width);
+}
+
+template <typename T>
+inline __device__ T
+shfl_down(const T val, unsigned int delta, int width = kWarpSize) {
+#if CUDA_VERSION >= 9000
+ return __shfl_down_sync(0xffffffff, val, delta, width);
+#else
+ return __shfl_down(val, delta, width);
+#endif
+}
+
+// CUDA SDK does not provide specializations for T*
+template <typename T>
+inline __device__ T* shfl_down(
+ T* const val,
+ unsigned int delta,
+ int width = kWarpSize) {
+ static_assert(sizeof(T*) == sizeof(long long), "pointer size");
+ long long v = (long long)val;
+ return (T*)shfl_down(v, delta, width);
+}
+
+template <typename T>
+inline __device__ T shfl_xor(const T val, int laneMask, int width = kWarpSize) {
+#if CUDA_VERSION >= 9000
+ return __shfl_xor_sync(0xffffffff, val, laneMask, width);
+#else
+ return __shfl_xor(val, laneMask, width);
+#endif
+}
+
+// CUDA SDK does not provide specializations for T*
+template <typename T>
+inline __device__ T* shfl_xor(
+ T* const val,
+ int laneMask,
+ int width = kWarpSize) {
+ static_assert(sizeof(T*) == sizeof(long long), "pointer size");
+ long long v = (long long)val;
+ return (T*)shfl_xor(v, laneMask, width);
+}
+
+#ifdef USE_AMD_ROCM
+
+inline __device__ half shfl(half v, int srcLane, int width = kWarpSize) {
+ unsigned int vu = __half2uint_rn(v);
+ vu = __shfl(vu, srcLane, width);
+ return __uint2half_rn(vu);
+}
+
+inline __device__ half shfl_xor(half v, int laneMask, int width = kWarpSize) {
+ unsigned int vu = __half2uint_rn(v);
+ vu = __shfl_xor(vu, laneMask, width);
+ return __uint2half_rn(vu);
+}
+
+#else
+
+// CUDA 9.0+ has half shuffle
+#if CUDA_VERSION < 9000
+inline __device__ half shfl(half v, int srcLane, int width = kWarpSize) {
+ unsigned int vu = v.x;
+ vu = __shfl(vu, srcLane, width);
+
+ half h;
+ h.x = (unsigned short)vu;
+ return h;
+}
+
+inline __device__ half shfl_xor(half v, int laneMask, int width = kWarpSize) {
+ unsigned int vu = v.x;
+ vu = __shfl_xor(vu, laneMask, width);
+
+ half h;
+ h.x = (unsigned short)vu;
+ return h;
+}
+#endif // CUDA_VERSION
+
+#endif // USE_AMD_ROCM
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat1.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat1.cu
new file mode 100644
index 0000000..a76aeea
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat1.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 1, 1);
+BLOCK_SELECT_IMPL(float, false, 1, 1);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat128.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat128.cu
new file mode 100644
index 0000000..e0174cf
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat128.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 128, 3);
+BLOCK_SELECT_IMPL(float, false, 128, 3);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat256.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat256.cu
new file mode 100644
index 0000000..50f41d2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat256.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 256, 4);
+BLOCK_SELECT_IMPL(float, false, 256, 4);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat32.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat32.cu
new file mode 100644
index 0000000..9d091ce
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat32.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 32, 2);
+BLOCK_SELECT_IMPL(float, false, 32, 2);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat64.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat64.cu
new file mode 100644
index 0000000..e9b7438
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloat64.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 64, 3);
+BLOCK_SELECT_IMPL(float, false, 64, 3);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF1024.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF1024.cu
new file mode 100644
index 0000000..88c5d02
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF1024.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, false, 1024, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF2048.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF2048.cu
new file mode 100644
index 0000000..c49f9a8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF2048.cu
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+#if GPU_MAX_SELECTION_K >= 2048
+BLOCK_SELECT_IMPL(float, false, 2048, 8);
+#endif
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF512.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF512.cu
new file mode 100644
index 0000000..c8060af
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatF512.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, false, 512, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT1024.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT1024.cu
new file mode 100644
index 0000000..3d0fb65
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT1024.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 1024, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT2048.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT2048.cu
new file mode 100644
index 0000000..1215220
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT2048.cu
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+#if GPU_MAX_SELECTION_K >= 2048
+BLOCK_SELECT_IMPL(float, true, 2048, 8);
+#endif
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT512.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT512.cu
new file mode 100644
index 0000000..485d13c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectFloatT512.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/blockselect/BlockSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+BLOCK_SELECT_IMPL(float, true, 512, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectImpl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectImpl.cuh
new file mode 100644
index 0000000..4790c15
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/blockselect/BlockSelectImpl.cuh
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/gpu/utils/BlockSelectKernel.cuh>
+#include <faiss/gpu/utils/Limits.cuh>
+
+#define BLOCK_SELECT_DECL(TYPE, DIR, WARP_Q) \
+ extern void runBlockSelect_##TYPE##_##DIR##_##WARP_Q##_( \
+ Tensor<TYPE, 2, true>& in, \
+ Tensor<TYPE, 2, true>& outK, \
+ Tensor<idx_t, 2, true>& outV, \
+ bool dir, \
+ int k, \
+ cudaStream_t stream); \
+ \
+ extern void runBlockSelectPair_##TYPE##_##DIR##_##WARP_Q##_( \
+ Tensor<TYPE, 2, true>& inK, \
+ Tensor<idx_t, 2, true>& inV, \
+ Tensor<TYPE, 2, true>& outK, \
+ Tensor<idx_t, 2, true>& outV, \
+ bool dir, \
+ int k, \
+ cudaStream_t stream)
+
+#define BLOCK_SELECT_IMPL(TYPE, DIR, WARP_Q, THREAD_Q) \
+ void runBlockSelect_##TYPE##_##DIR##_##WARP_Q##_( \
+ Tensor<TYPE, 2, true>& in, \
+ Tensor<TYPE, 2, true>& outK, \
+ Tensor<idx_t, 2, true>& outV, \
+ bool dir, \
+ int k, \
+ cudaStream_t stream) { \
+ FAISS_ASSERT(in.getSize(0) == outK.getSize(0)); \
+ FAISS_ASSERT(in.getSize(0) == outV.getSize(0)); \
+ FAISS_ASSERT(outK.getSize(1) == k); \
+ FAISS_ASSERT(outV.getSize(1) == k); \
+ \
+ auto grid = dim3(in.getSize(0)); \
+ \
+ constexpr int kBlockSelectNumThreads = (WARP_Q <= 1024) ? 128 : 64; \
+ auto block = dim3(kBlockSelectNumThreads); \
+ \
+ FAISS_ASSERT(k <= WARP_Q); \
+ FAISS_ASSERT(dir == DIR); \
+ \
+ auto kInit = dir ? Limits<TYPE>::getMin() : Limits<TYPE>::getMax(); \
+ auto vInit = -1; \
+ \
+ blockSelect< \
+ TYPE, \
+ idx_t, \
+ DIR, \
+ WARP_Q, \
+ THREAD_Q, \
+ kBlockSelectNumThreads> \
+ <<<grid, block, 0, stream>>>(in, outK, outV, kInit, vInit, k); \
+ CUDA_TEST_ERROR(); \
+ } \
+ \
+ void runBlockSelectPair_##TYPE##_##DIR##_##WARP_Q##_( \
+ Tensor<TYPE, 2, true>& inK, \
+ Tensor<idx_t, 2, true>& inV, \
+ Tensor<TYPE, 2, true>& outK, \
+ Tensor<idx_t, 2, true>& outV, \
+ bool dir, \
+ int k, \
+ cudaStream_t stream) { \
+ FAISS_ASSERT(inK.isSameSize(inV)); \
+ FAISS_ASSERT(outK.isSameSize(outV)); \
+ \
+ auto grid = dim3(inK.getSize(0)); \
+ \
+ constexpr int kBlockSelectNumThreads = (WARP_Q <= 1024) ? 128 : 64; \
+ auto block = dim3(kBlockSelectNumThreads); \
+ \
+ FAISS_ASSERT(k <= WARP_Q); \
+ FAISS_ASSERT(dir == DIR); \
+ \
+ auto kInit = dir ? Limits<TYPE>::getMin() : Limits<TYPE>::getMax(); \
+ auto vInit = -1; \
+ \
+ blockSelectPair< \
+ TYPE, \
+ idx_t, \
+ DIR, \
+ WARP_Q, \
+ THREAD_Q, \
+ kBlockSelectNumThreads><<<grid, block, 0, stream>>>( \
+ inK, inV, outK, outV, kInit, vInit, k); \
+ CUDA_TEST_ERROR(); \
+ }
+
+#define BLOCK_SELECT_CALL(TYPE, DIR, WARP_Q) \
+ runBlockSelect_##TYPE##_##DIR##_##WARP_Q##_(in, outK, outV, dir, k, stream)
+
+#define BLOCK_SELECT_PAIR_CALL(TYPE, DIR, WARP_Q) \
+ runBlockSelectPair_##TYPE##_##DIR##_##WARP_Q##_( \
+ inK, inV, outK, outV, dir, k, stream)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat1.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat1.cu
new file mode 100644
index 0000000..56275c1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat1.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 1, 1);
+WARP_SELECT_IMPL(float, false, 1, 1);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat128.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat128.cu
new file mode 100644
index 0000000..83838b6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat128.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 128, 3);
+WARP_SELECT_IMPL(float, false, 128, 3);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat256.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat256.cu
new file mode 100644
index 0000000..4698a98
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat256.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 256, 4);
+WARP_SELECT_IMPL(float, false, 256, 4);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat32.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat32.cu
new file mode 100644
index 0000000..2b665c9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat32.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 32, 2);
+WARP_SELECT_IMPL(float, false, 32, 2);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat64.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat64.cu
new file mode 100644
index 0000000..25743a9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloat64.cu
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 64, 3);
+WARP_SELECT_IMPL(float, false, 64, 3);
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF1024.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF1024.cu
new file mode 100644
index 0000000..5b70761
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF1024.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, false, 1024, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF2048.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF2048.cu
new file mode 100644
index 0000000..de30d8c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF2048.cu
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+#if GPU_MAX_SELECTION_K >= 2048
+WARP_SELECT_IMPL(float, false, 2048, 8);
+#endif
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF512.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF512.cu
new file mode 100644
index 0000000..c35dce5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatF512.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, false, 512, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT1024.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT1024.cu
new file mode 100644
index 0000000..f803b1b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT1024.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 1024, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT2048.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT2048.cu
new file mode 100644
index 0000000..be630c1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT2048.cu
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/DeviceDefs.cuh>
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+#if GPU_MAX_SELECTION_K >= 2048
+WARP_SELECT_IMPL(float, true, 2048, 8);
+#endif
+
+} // namespace gpu
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT512.cu b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT512.cu
new file mode 100644
index 0000000..10782f6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectFloatT512.cu
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/warpselect/WarpSelectImpl.cuh>
+
+namespace faiss {
+namespace gpu {
+
+WARP_SELECT_IMPL(float, true, 512, 8);
+
+}
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectImpl.cuh b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectImpl.cuh
new file mode 100644
index 0000000..3db7b40
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/gpu/utils/warpselect/WarpSelectImpl.cuh
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/gpu/utils/Limits.cuh>
+#include <faiss/gpu/utils/WarpSelectKernel.cuh>
+
+#define WARP_SELECT_DECL(TYPE, DIR, WARP_Q) \
+ extern void runWarpSelect_##TYPE##_##DIR##_##WARP_Q##_( \
+ Tensor<TYPE, 2, true>& in, \
+ Tensor<TYPE, 2, true>& outK, \
+ Tensor<idx_t, 2, true>& outV, \
+ bool dir, \
+ int k, \
+ cudaStream_t stream)
+
+#define WARP_SELECT_IMPL(TYPE, DIR, WARP_Q, THREAD_Q) \
+ void runWarpSelect_##TYPE##_##DIR##_##WARP_Q##_( \
+ Tensor<TYPE, 2, true>& in, \
+ Tensor<TYPE, 2, true>& outK, \
+ Tensor<idx_t, 2, true>& outV, \
+ bool dir, \
+ int k, \
+ cudaStream_t stream) { \
+ int warpSize = getWarpSizeCurrentDevice(); \
+ constexpr int kWarpSelectNumThreads = 128; \
+ auto grid = dim3(utils::divUp( \
+ in.getSize(0), (kWarpSelectNumThreads / warpSize))); \
+ auto block = dim3(kWarpSelectNumThreads); \
+ \
+ FAISS_ASSERT(k <= WARP_Q); \
+ FAISS_ASSERT(dir == DIR); \
+ \
+ auto kInit = dir ? Limits<TYPE>::getMin() : Limits<TYPE>::getMax(); \
+ auto vInit = -1; \
+ \
+ warpSelect<TYPE, idx_t, DIR, WARP_Q, THREAD_Q, kWarpSelectNumThreads> \
+ <<<grid, block, 0, stream>>>(in, outK, outV, kInit, vInit, k); \
+ CUDA_TEST_ERROR(); \
+ }
+
+#define WARP_SELECT_CALL(TYPE, DIR, WARP_Q) \
+ runWarpSelect_##TYPE##_##DIR##_##WARP_Q##_(in, outK, outV, dir, k, stream)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AdditiveQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AdditiveQuantizer.cpp
new file mode 100644
index 0000000..ff4ead4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AdditiveQuantizer.cpp
@@ -0,0 +1,635 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/AdditiveQuantizer.h>
+
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+#include <random>
+
+#include <algorithm>
+
+#include <faiss/Clustering.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+
+extern "C" {
+
+// general matrix multiplication
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+AdditiveQuantizer::AdditiveQuantizer(
+ size_t d,
+ const std::vector<size_t>& nbits,
+ Search_type_t search_type)
+ : Quantizer(d),
+ M(nbits.size()),
+ nbits(nbits),
+ search_type(search_type) {
+ set_derived_values();
+}
+
+AdditiveQuantizer::AdditiveQuantizer()
+ : AdditiveQuantizer(0, std::vector<size_t>()) {}
+
+void AdditiveQuantizer::set_derived_values() {
+ tot_bits = 0;
+ only_8bit = true;
+ codebook_offsets.resize(M + 1, 0);
+ for (int i = 0; i < M; i++) {
+ int nbit = nbits[i];
+ size_t k = 1 << nbit;
+ codebook_offsets[i + 1] = codebook_offsets[i] + k;
+ tot_bits += nbit;
+ if (nbit != 0) {
+ only_8bit = false;
+ }
+ }
+ total_codebook_size = codebook_offsets[M];
+ switch (search_type) {
+ case ST_norm_float:
+ norm_bits = 32;
+ break;
+ case ST_norm_qint8:
+ case ST_norm_cqint8:
+ case ST_norm_lsq2x4:
+ case ST_norm_rq2x4:
+ norm_bits = 8;
+ break;
+ case ST_norm_qint4:
+ case ST_norm_cqint4:
+ norm_bits = 4;
+ break;
+ case ST_decompress:
+ case ST_LUT_nonorm:
+ case ST_norm_from_LUT:
+ default:
+ norm_bits = 0;
+ break;
+ }
+ tot_bits += norm_bits;
+
+ // convert bits to bytes
+ code_size = (tot_bits + 7) / 8;
+}
+
+void AdditiveQuantizer::train_norm(size_t n, const float* norms) {
+ norm_min = HUGE_VALF;
+ norm_max = -HUGE_VALF;
+ for (idx_t i = 0; i < n; i++) {
+ if (norms[i] < norm_min) {
+ norm_min = norms[i];
+ }
+ if (norms[i] > norm_max) {
+ norm_max = norms[i];
+ }
+ }
+
+ if (search_type == ST_norm_cqint8 || search_type == ST_norm_cqint4) {
+ size_t k = (1 << 8);
+ if (search_type == ST_norm_cqint4) {
+ k = (1 << 4);
+ }
+ Clustering1D clus(k);
+ clus.train_exact(n, norms);
+ qnorm.add(clus.k, clus.centroids.data());
+ } else if (search_type == ST_norm_lsq2x4 || search_type == ST_norm_rq2x4) {
+ std::unique_ptr<AdditiveQuantizer> aq;
+ if (search_type == ST_norm_lsq2x4) {
+ aq.reset(new LocalSearchQuantizer(1, 2, 4));
+ } else {
+ aq.reset(new ResidualQuantizer(1, 2, 4));
+ }
+
+ aq->train(n, norms);
+ // flatten aq codebooks
+ std::vector<float> flat_codebooks(1 << 8);
+ FAISS_THROW_IF_NOT(aq->codebooks.size() == 32);
+
+ // save norm tables for 4-bit fastscan search
+ norm_tabs = aq->codebooks;
+
+ // assume big endian
+ const float* c = norm_tabs.data();
+ for (size_t i = 0; i < 16; i++) {
+ for (size_t j = 0; j < 16; j++) {
+ flat_codebooks[i * 16 + j] = c[j] + c[16 + i];
+ }
+ }
+
+ qnorm.reset();
+ qnorm.add(1 << 8, flat_codebooks.data());
+ FAISS_THROW_IF_NOT(qnorm.ntotal == (1 << 8));
+ }
+}
+
+void AdditiveQuantizer::compute_codebook_tables() {
+ centroid_norms.resize(total_codebook_size);
+ fvec_norms_L2sqr(
+ centroid_norms.data(), codebooks.data(), d, total_codebook_size);
+ size_t cross_table_size = 0;
+ for (int m = 0; m < M; m++) {
+ size_t K = (size_t)1 << nbits[m];
+ cross_table_size += K * codebook_offsets[m];
+ }
+ codebook_cross_products.resize(cross_table_size);
+ size_t ofs = 0;
+ for (int m = 1; m < M; m++) {
+ FINTEGER ki = (size_t)1 << nbits[m];
+ FINTEGER kk = codebook_offsets[m];
+ FINTEGER di = d;
+ float zero = 0, one = 1;
+ assert(ofs + ki * kk <= cross_table_size);
+ sgemm_("Transposed",
+ "Not transposed",
+ &ki,
+ &kk,
+ &di,
+ &one,
+ codebooks.data() + d * kk,
+ &di,
+ codebooks.data(),
+ &di,
+ &zero,
+ codebook_cross_products.data() + ofs,
+ &ki);
+ ofs += ki * kk;
+ }
+}
+
+namespace {
+
+// TODO
+// https://stackoverflow.com/questions/31631224/hacks-for-clamping-integer-to-0-255-and-doubles-to-0-0-1-0
+
+uint8_t encode_qint8(float x, float amin, float amax) {
+ float x1 = (x - amin) / (amax - amin) * 256;
+ int32_t xi = int32_t(floor(x1));
+
+ return xi < 0 ? 0 : xi > 255 ? 255 : xi;
+}
+
+uint8_t encode_qint4(float x, float amin, float amax) {
+ float x1 = (x - amin) / (amax - amin) * 16;
+ int32_t xi = int32_t(floor(x1));
+
+ return xi < 0 ? 0 : xi > 15 ? 15 : xi;
+}
+
+float decode_qint8(uint8_t i, float amin, float amax) {
+ return (i + 0.5) / 256 * (amax - amin) + amin;
+}
+
+float decode_qint4(uint8_t i, float amin, float amax) {
+ return (i + 0.5) / 16 * (amax - amin) + amin;
+}
+
+} // anonymous namespace
+
+uint32_t AdditiveQuantizer::encode_qcint(float x) const {
+ idx_t id;
+ qnorm.assign(1, &x, &id, 1);
+ return uint32_t(id);
+}
+
+float AdditiveQuantizer::decode_qcint(uint32_t c) const {
+ return qnorm.get_xb()[c];
+}
+
+uint64_t AdditiveQuantizer::encode_norm(float norm) const {
+ switch (search_type) {
+ case ST_norm_float:
+ uint32_t inorm;
+ memcpy(&inorm, &norm, 4);
+ return inorm;
+ case ST_norm_qint8:
+ return encode_qint8(norm, norm_min, norm_max);
+ case ST_norm_qint4:
+ return encode_qint4(norm, norm_min, norm_max);
+ case ST_norm_lsq2x4:
+ case ST_norm_rq2x4:
+ case ST_norm_cqint8:
+ return encode_qcint(norm);
+ case ST_norm_cqint4:
+ return encode_qcint(norm);
+ case ST_decompress:
+ case ST_LUT_nonorm:
+ case ST_norm_from_LUT:
+ default:
+ return 0;
+ }
+}
+
+void AdditiveQuantizer::pack_codes(
+ size_t n,
+ const int32_t* codes,
+ uint8_t* packed_codes,
+ int64_t ld_codes,
+ const float* norms,
+ const float* centroids) const {
+ if (ld_codes == -1) {
+ ld_codes = M;
+ }
+ std::vector<float> norm_buf;
+ if (search_type == ST_norm_float || search_type == ST_norm_qint4 ||
+ search_type == ST_norm_qint8 || search_type == ST_norm_cqint8 ||
+ search_type == ST_norm_cqint4 || search_type == ST_norm_lsq2x4 ||
+ search_type == ST_norm_rq2x4) {
+ if (centroids != nullptr || !norms) {
+ norm_buf.resize(n);
+ std::vector<float> x_recons(n * d);
+ decode_unpacked(codes, x_recons.data(), n, ld_codes);
+
+ if (centroids != nullptr) {
+ // x = x + c
+ fvec_add(n * d, x_recons.data(), centroids, x_recons.data());
+ }
+ fvec_norms_L2sqr(norm_buf.data(), x_recons.data(), d, n);
+ norms = norm_buf.data();
+ }
+ }
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const int32_t* codes1 = codes + i * ld_codes;
+ BitstringWriter bsw(packed_codes + i * code_size, code_size);
+ for (int m = 0; m < M; m++) {
+ bsw.write(codes1[m], nbits[m]);
+ }
+ if (norm_bits != 0) {
+ bsw.write(encode_norm(norms[i]), norm_bits);
+ }
+ }
+}
+
+void AdditiveQuantizer::decode(const uint8_t* code, float* x, size_t n) const {
+ FAISS_THROW_IF_NOT_MSG(
+ is_trained, "The additive quantizer is not trained yet.");
+
+ // standard additive quantizer decoding
+#pragma omp parallel for if (n > 100)
+ for (int64_t i = 0; i < n; i++) {
+ BitstringReader bsr(code + i * code_size, code_size);
+ float* xi = x + i * d;
+ for (int m = 0; m < M; m++) {
+ int idx = bsr.read(nbits[m]);
+ const float* c = codebooks.data() + d * (codebook_offsets[m] + idx);
+ if (m == 0) {
+ memcpy(xi, c, sizeof(*x) * d);
+ } else {
+ fvec_add(d, xi, c, xi);
+ }
+ }
+ }
+}
+
+void AdditiveQuantizer::decode_unpacked(
+ const int32_t* code,
+ float* x,
+ size_t n,
+ int64_t ld_codes) const {
+ FAISS_THROW_IF_NOT_MSG(
+ is_trained, "The additive quantizer is not trained yet.");
+
+ if (ld_codes == -1) {
+ ld_codes = M;
+ }
+
+ // standard additive quantizer decoding
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const int32_t* codesi = code + i * ld_codes;
+ float* xi = x + i * d;
+ for (int m = 0; m < M; m++) {
+ int idx = codesi[m];
+ const float* c = codebooks.data() + d * (codebook_offsets[m] + idx);
+ if (m == 0) {
+ memcpy(xi, c, sizeof(*x) * d);
+ } else {
+ fvec_add(d, xi, c, xi);
+ }
+ }
+ }
+}
+
+AdditiveQuantizer::~AdditiveQuantizer() {}
+
+/****************************************************************************
+ * Support for fast distance computations in centroids
+ ****************************************************************************/
+
+void AdditiveQuantizer::compute_centroid_norms(float* norms) const {
+ size_t ntotal = (size_t)1 << tot_bits;
+ // TODO: make tree of partial sums
+#pragma omp parallel
+ {
+ std::vector<float> tmp(d);
+#pragma omp for
+ for (int64_t i = 0; i < ntotal; i++) {
+ decode_64bit(i, tmp.data());
+ norms[i] = fvec_norm_L2sqr(tmp.data(), d);
+ }
+ }
+}
+
+void AdditiveQuantizer::decode_64bit(idx_t bits, float* xi) const {
+ for (int m = 0; m < M; m++) {
+ idx_t idx = bits & (((size_t)1 << nbits[m]) - 1);
+ bits >>= nbits[m];
+ const float* c = codebooks.data() + d * (codebook_offsets[m] + idx);
+ if (m == 0) {
+ memcpy(xi, c, sizeof(*xi) * d);
+ } else {
+ fvec_add(d, xi, c, xi);
+ }
+ }
+}
+
+void AdditiveQuantizer::compute_LUT(
+ size_t n,
+ const float* xq,
+ float* LUT,
+ float alpha,
+ long ld_lut) const {
+ // in all cases, it is large matrix multiplication
+
+ FINTEGER ncenti = total_codebook_size;
+ FINTEGER di = d;
+ FINTEGER nqi = n;
+ FINTEGER ldc = ld_lut > 0 ? ld_lut : ncenti;
+ float zero = 0;
+
+ sgemm_("Transposed",
+ "Not transposed",
+ &ncenti,
+ &nqi,
+ &di,
+ &alpha,
+ codebooks.data(),
+ &di,
+ xq,
+ &di,
+ &zero,
+ LUT,
+ &ldc);
+}
+
+namespace {
+
+/* compute inner products of one query with all centroids, given a look-up
+ * table of all inner producst with codebook entries */
+void compute_inner_prod_with_LUT(
+ const AdditiveQuantizer& aq,
+ const float* LUT,
+ float* ips) {
+ size_t prev_size = 1;
+ for (int m = 0; m < aq.M; m++) {
+ const float* LUTm = LUT + aq.codebook_offsets[m];
+ int nb = aq.nbits[m];
+ size_t nc = (size_t)1 << nb;
+
+ if (m == 0) {
+ memcpy(ips, LUT, sizeof(*ips) * nc);
+ } else {
+ for (int64_t i = nc - 1; i >= 0; i--) {
+ float v = LUTm[i];
+ fvec_add(prev_size, ips, v, ips + i * prev_size);
+ }
+ }
+ prev_size *= nc;
+ }
+}
+
+} // anonymous namespace
+
+void AdditiveQuantizer::knn_centroids_inner_product(
+ idx_t n,
+ const float* xq,
+ idx_t k,
+ float* distances,
+ idx_t* labels) const {
+ std::unique_ptr<float[]> LUT(new float[n * total_codebook_size]);
+ compute_LUT(n, xq, LUT.get());
+ size_t ntotal = (size_t)1 << tot_bits;
+
+#pragma omp parallel if (n > 100)
+ {
+ std::vector<float> dis(ntotal);
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const float* LUTi = LUT.get() + i * total_codebook_size;
+ compute_inner_prod_with_LUT(*this, LUTi, dis.data());
+ float* distances_i = distances + i * k;
+ idx_t* labels_i = labels + i * k;
+ minheap_heapify(k, distances_i, labels_i);
+ minheap_addn(k, distances_i, labels_i, dis.data(), nullptr, ntotal);
+ minheap_reorder(k, distances_i, labels_i);
+ }
+ }
+}
+
+void AdditiveQuantizer::knn_centroids_L2(
+ idx_t n,
+ const float* xq,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const float* norms) const {
+ std::unique_ptr<float[]> LUT(new float[n * total_codebook_size]);
+ compute_LUT(n, xq, LUT.get());
+ std::unique_ptr<float[]> q_norms(new float[n]);
+ fvec_norms_L2sqr(q_norms.get(), xq, d, n);
+ size_t ntotal = (size_t)1 << tot_bits;
+
+#pragma omp parallel if (n > 100)
+ {
+ std::vector<float> dis(ntotal);
+#pragma omp for
+ for (idx_t i = 0; i < n; i++) {
+ const float* LUTi = LUT.get() + i * total_codebook_size;
+ float* distances_i = distances + i * k;
+ idx_t* labels_i = labels + i * k;
+
+ compute_inner_prod_with_LUT(*this, LUTi, dis.data());
+
+ // update distances using
+ // ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * <x,y>
+
+ maxheap_heapify(k, distances_i, labels_i);
+ for (idx_t j = 0; j < ntotal; j++) {
+ float disj = q_norms[i] + norms[j] - 2 * dis[j];
+ if (disj < distances_i[0]) {
+ heap_replace_top<CMax<float, int64_t>>(
+ k, distances_i, labels_i, disj, j);
+ }
+ }
+ maxheap_reorder(k, distances_i, labels_i);
+ }
+ }
+}
+
+/****************************************************************************
+ * Support for fast distance computations in codes
+ ****************************************************************************/
+
+namespace {
+
+float accumulate_IPs(
+ const AdditiveQuantizer& aq,
+ BitstringReader& bs,
+ const float* LUT) {
+ float accu = 0;
+ for (int m = 0; m < aq.M; m++) {
+ size_t nbit = aq.nbits[m];
+ int idx = bs.read(nbit);
+ accu += LUT[idx];
+ LUT += (uint64_t)1 << nbit;
+ }
+ return accu;
+}
+
+float compute_norm_from_LUT(const AdditiveQuantizer& aq, BitstringReader& bs) {
+ float accu = 0;
+ std::vector<int> idx(aq.M);
+ const float* c = aq.codebook_cross_products.data();
+ for (int m = 0; m < aq.M; m++) {
+ size_t nbit = aq.nbits[m];
+ int i = bs.read(nbit);
+ size_t K = 1 << nbit;
+ idx[m] = i;
+
+ accu += aq.centroid_norms[aq.codebook_offsets[m] + i];
+
+ for (int l = 0; l < m; l++) {
+ int j = idx[l];
+ accu += 2 * c[j * K + i];
+ c += (1 << aq.nbits[l]) * K;
+ }
+ }
+ // FAISS_THROW_IF_NOT(c == aq.codebook_cross_products.data() +
+ // aq.codebook_cross_products.size());
+ return accu;
+}
+
+} // anonymous namespace
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<true, AdditiveQuantizer::ST_LUT_nonorm>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ return accumulate_IPs(*this, bs, LUT);
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_LUT_nonorm>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ return -accumulate_IPs(*this, bs, LUT);
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_norm_float>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ float accu = accumulate_IPs(*this, bs, LUT);
+ uint32_t norm_i = bs.read(32);
+ float norm2;
+ memcpy(&norm2, &norm_i, 4);
+ return norm2 - 2 * accu;
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_norm_cqint8>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ float accu = accumulate_IPs(*this, bs, LUT);
+ uint32_t norm_i = bs.read(8);
+ float norm2 = decode_qcint(norm_i);
+ return norm2 - 2 * accu;
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_norm_cqint4>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ float accu = accumulate_IPs(*this, bs, LUT);
+ uint32_t norm_i = bs.read(4);
+ float norm2 = decode_qcint(norm_i);
+ return norm2 - 2 * accu;
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_norm_qint8>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ float accu = accumulate_IPs(*this, bs, LUT);
+ uint32_t norm_i = bs.read(8);
+ float norm2 = decode_qint8(norm_i, norm_min, norm_max);
+ return norm2 - 2 * accu;
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_norm_qint4>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ BitstringReader bs(codes, code_size);
+ float accu = accumulate_IPs(*this, bs, LUT);
+ uint32_t norm_i = bs.read(4);
+ float norm2 = decode_qint4(norm_i, norm_min, norm_max);
+ return norm2 - 2 * accu;
+}
+
+template <>
+float AdditiveQuantizer::
+ compute_1_distance_LUT<false, AdditiveQuantizer::ST_norm_from_LUT>(
+ const uint8_t* codes,
+ const float* LUT) const {
+ FAISS_THROW_IF_NOT(codebook_cross_products.size() > 0);
+ BitstringReader bs(codes, code_size);
+ float accu = accumulate_IPs(*this, bs, LUT);
+ BitstringReader bs2(codes, code_size);
+ float norm2 = compute_norm_from_LUT(*this, bs2);
+ return norm2 - 2 * accu;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AdditiveQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AdditiveQuantizer.h
new file mode 100644
index 0000000..813cdd7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AdditiveQuantizer.h
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cmath>
+#include <cstdint>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/Quantizer.h>
+
+namespace faiss {
+
+/** Abstract structure for additive quantizers
+ *
+ * Different from the product quantizer in which the decoded vector is the
+ * concatenation of M sub-vectors, additive quantizers sum M sub-vectors
+ * to get the decoded vector.
+ */
+struct AdditiveQuantizer : Quantizer {
+ size_t M; ///< number of codebooks
+ std::vector<size_t> nbits; ///< bits for each step
+ std::vector<float> codebooks; ///< codebooks
+
+ // derived values
+ /// codebook #1 is stored in rows codebook_offsets[i]:codebook_offsets[i+1]
+ /// in the codebooks table of size total_codebook_size by d
+ std::vector<uint64_t> codebook_offsets;
+ size_t tot_bits = 0; ///< total number of bits (indexes + norms)
+ size_t norm_bits = 0; ///< bits allocated for the norms
+ size_t total_codebook_size = 0; ///< size of the codebook in vectors
+ bool only_8bit = false; ///< are all nbits = 8 (use faster decoder)
+
+ bool verbose = false; ///< verbose during training?
+ bool is_trained = false; ///< is trained or not
+
+ /// auxiliary data for ST_norm_lsq2x4 and ST_norm_rq2x4
+ /// store norms of codebook entries for 4-bit fastscan
+ std::vector<float> norm_tabs;
+ IndexFlat1D qnorm; ///< store and search norms
+
+ void compute_codebook_tables();
+
+ /// norms of all codebook entries (size total_codebook_size)
+ std::vector<float> centroid_norms;
+
+ /// dot products of all codebook entries with the previous codebooks
+ /// size sum(codebook_offsets[m] * 2^nbits[m], m=0..M-1)
+ std::vector<float> codebook_cross_products;
+
+ /// norms and distance matrixes with beam search can get large, so use this
+ /// to control for the amount of memory that can be allocated
+ size_t max_mem_distances = 5 * (size_t(1) << 30);
+
+ /// encode a norm into norm_bits bits
+ uint64_t encode_norm(float norm) const;
+
+ /// encode norm by non-uniform scalar quantization
+ uint32_t encode_qcint(float x) const;
+
+ /// decode norm by non-uniform scalar quantization
+ float decode_qcint(uint32_t c) const;
+
+ /// Encodes how search is performed and how vectors are encoded
+ enum Search_type_t {
+ ST_decompress, ///< decompress database vector
+ ST_LUT_nonorm, ///< use a LUT, don't include norms (OK for IP or
+ ///< normalized vectors)
+ ST_norm_from_LUT, ///< compute the norms from the look-up tables (cost
+ ///< is in O(M^2))
+ ST_norm_float, ///< use a LUT, and store float32 norm with the vectors
+ ST_norm_qint8, ///< use a LUT, and store 8bit-quantized norm
+ ST_norm_qint4,
+ ST_norm_cqint8, ///< use a LUT, and store non-uniform quantized norm
+ ST_norm_cqint4,
+
+ ST_norm_lsq2x4, ///< use a 2x4 bits lsq as norm quantizer (for fast
+ ///< scan)
+ ST_norm_rq2x4, ///< use a 2x4 bits rq as norm quantizer (for fast scan)
+ };
+
+ AdditiveQuantizer(
+ size_t d,
+ const std::vector<size_t>& nbits,
+ Search_type_t search_type = ST_decompress);
+
+ AdditiveQuantizer();
+
+ ///< compute derived values when d, M and nbits have been set
+ void set_derived_values();
+
+ ///< Train the norm quantizer
+ void train_norm(size_t n, const float* norms);
+
+ void compute_codes(const float* x, uint8_t* codes, size_t n)
+ const override {
+ compute_codes_add_centroids(x, codes, n);
+ }
+
+ /** Encode a set of vectors
+ *
+ * @param x vectors to encode, size n * d
+ * @param codes output codes, size n * code_size
+ * @param centroids centroids to be added to x, size n * d
+ */
+ virtual void compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes,
+ size_t n,
+ const float* centroids = nullptr) const = 0;
+
+ /** pack a series of code to bit-compact format
+ *
+ * @param codes codes to be packed, size n * code_size
+ * @param packed_codes output bit-compact codes
+ * @param ld_codes leading dimension of codes
+ * @param norms norms of the vectors (size n). Will be computed if
+ * needed but not provided
+ * @param centroids centroids to be added to x, size n * d
+ */
+ void pack_codes(
+ size_t n,
+ const int32_t* codes,
+ uint8_t* packed_codes,
+ int64_t ld_codes = -1,
+ const float* norms = nullptr,
+ const float* centroids = nullptr) const;
+
+ /** Decode a set of vectors
+ *
+ * @param codes codes to decode, size n * code_size
+ * @param x output vectors, size n * d
+ */
+ void decode(const uint8_t* codes, float* x, size_t n) const override;
+
+ /** Decode a set of vectors in non-packed format
+ *
+ * @param codes codes to decode, size n * ld_codes
+ * @param x output vectors, size n * d
+ */
+ virtual void decode_unpacked(
+ const int32_t* codes,
+ float* x,
+ size_t n,
+ int64_t ld_codes = -1) const;
+
+ /****************************************************************************
+ * Search functions in an external set of codes.
+ ****************************************************************************/
+
+ /// Also determines what's in the codes
+ Search_type_t search_type;
+
+ /// min/max for quantization of norms
+ float norm_min = NAN, norm_max = NAN;
+
+ template <bool is_IP, Search_type_t effective_search_type>
+ float compute_1_distance_LUT(const uint8_t* codes, const float* LUT) const;
+
+ /*
+ float compute_1_L2sqr(const uint8_t* codes, const float* LUT);
+ */
+ /****************************************************************************
+ * Support for exhaustive distance computations with all the centroids.
+ * Hence, the number of these centroids should not be too large.
+ ****************************************************************************/
+
+ /// decoding function for a code in a 64-bit word
+ void decode_64bit(idx_t n, float* x) const;
+
+ /** Compute inner-product look-up tables. Used in the centroid search
+ * functions.
+ *
+ * @param xq query vector, size (n, d)
+ * @param LUT look-up table, size (n, total_codebook_size)
+ * @param alpha compute alpha * inner-product
+ * @param ld_lut leading dimension of LUT
+ */
+ virtual void compute_LUT(
+ size_t n,
+ const float* xq,
+ float* LUT,
+ float alpha = 1.0f,
+ long ld_lut = -1) const;
+
+ /// exact IP search
+ void knn_centroids_inner_product(
+ idx_t n,
+ const float* xq,
+ idx_t k,
+ float* distances,
+ idx_t* labels) const;
+
+ /** For L2 search we need the L2 norms of the centroids
+ *
+ * @param norms output norms table, size total_codebook_size
+ */
+ void compute_centroid_norms(float* norms) const;
+
+ /** Exact L2 search, with precomputed norms */
+ void knn_centroids_L2(
+ idx_t n,
+ const float* xq,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const float* centroid_norms) const;
+
+ virtual ~AdditiveQuantizer();
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AuxIndexStructures.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AuxIndexStructures.cpp
new file mode 100644
index 0000000..d37507a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AuxIndexStructures.cpp
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <algorithm>
+#include <cstring>
+
+#include <faiss/impl/AuxIndexStructures.h>
+
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+/***********************************************************************
+ * RangeSearchResult
+ ***********************************************************************/
+
+RangeSearchResult::RangeSearchResult(size_t nq, bool alloc_lims) : nq(nq) {
+ if (alloc_lims) {
+ lims = new size_t[nq + 1];
+ memset(lims, 0, sizeof(*lims) * (nq + 1));
+ } else {
+ lims = nullptr;
+ }
+ labels = nullptr;
+ distances = nullptr;
+ buffer_size = 1024 * 256;
+}
+
+/// called when lims contains the nb of elements result entries
+/// for each query
+void RangeSearchResult::do_allocation() {
+ // works only if all the partial results are aggregated
+ // simulatenously
+ FAISS_THROW_IF_NOT(labels == nullptr && distances == nullptr);
+ size_t ofs = 0;
+ for (int i = 0; i < nq; i++) {
+ size_t n = lims[i];
+ lims[i] = ofs;
+ ofs += n;
+ }
+ lims[nq] = ofs;
+ labels = new idx_t[ofs];
+ distances = new float[ofs];
+}
+
+RangeSearchResult::~RangeSearchResult() {
+ delete[] labels;
+ delete[] distances;
+ delete[] lims;
+}
+
+/***********************************************************************
+ * BufferList
+ ***********************************************************************/
+
+BufferList::BufferList(size_t buffer_size) : buffer_size(buffer_size) {
+ wp = buffer_size;
+}
+
+BufferList::~BufferList() {
+ for (int i = 0; i < buffers.size(); i++) {
+ delete[] buffers[i].ids;
+ delete[] buffers[i].dis;
+ }
+}
+
+void BufferList::add(idx_t id, float dis) {
+ if (wp == buffer_size) { // need new buffer
+ append_buffer();
+ }
+ Buffer& buf = buffers.back();
+ buf.ids[wp] = id;
+ buf.dis[wp] = dis;
+ wp++;
+}
+
+void BufferList::append_buffer() {
+ Buffer buf = {new idx_t[buffer_size], new float[buffer_size]};
+ buffers.push_back(buf);
+ wp = 0;
+}
+
+/// copy elemnts ofs:ofs+n-1 seen as linear data in the buffers to
+/// tables dest_ids, dest_dis
+void BufferList::copy_range(
+ size_t ofs,
+ size_t n,
+ idx_t* dest_ids,
+ float* dest_dis) {
+ size_t bno = ofs / buffer_size;
+ ofs -= bno * buffer_size;
+ while (n > 0) {
+ size_t ncopy = ofs + n < buffer_size ? n : buffer_size - ofs;
+ Buffer buf = buffers[bno];
+ memcpy(dest_ids, buf.ids + ofs, ncopy * sizeof(*dest_ids));
+ memcpy(dest_dis, buf.dis + ofs, ncopy * sizeof(*dest_dis));
+ dest_ids += ncopy;
+ dest_dis += ncopy;
+ ofs = 0;
+ bno++;
+ n -= ncopy;
+ }
+}
+
+/***********************************************************************
+ * RangeSearchPartialResult
+ ***********************************************************************/
+
+void RangeQueryResult::add(float dis, idx_t id) {
+ nres++;
+ pres->add(id, dis);
+}
+
+RangeSearchPartialResult::RangeSearchPartialResult(RangeSearchResult* res_in)
+ : BufferList(res_in->buffer_size), res(res_in) {}
+
+/// begin a new result
+RangeQueryResult& RangeSearchPartialResult::new_result(idx_t qno) {
+ RangeQueryResult qres = {qno, 0, this};
+ queries.push_back(qres);
+ return queries.back();
+}
+
+void RangeSearchPartialResult::finalize() {
+ set_lims();
+#pragma omp barrier
+
+#pragma omp single
+ res->do_allocation();
+
+#pragma omp barrier
+ copy_result();
+}
+
+/// called by range_search before do_allocation
+void RangeSearchPartialResult::set_lims() {
+ for (int i = 0; i < queries.size(); i++) {
+ RangeQueryResult& qres = queries[i];
+ res->lims[qres.qno] = qres.nres;
+ }
+}
+
+/// called by range_search after do_allocation
+void RangeSearchPartialResult::copy_result(bool incremental) {
+ size_t ofs = 0;
+ for (int i = 0; i < queries.size(); i++) {
+ RangeQueryResult& qres = queries[i];
+
+ copy_range(
+ ofs,
+ qres.nres,
+ res->labels + res->lims[qres.qno],
+ res->distances + res->lims[qres.qno]);
+ if (incremental) {
+ res->lims[qres.qno] += qres.nres;
+ }
+ ofs += qres.nres;
+ }
+}
+
+void RangeSearchPartialResult::merge(
+ std::vector<RangeSearchPartialResult*>& partial_results,
+ bool do_delete) {
+ int npres = partial_results.size();
+ if (npres == 0)
+ return;
+ RangeSearchResult* result = partial_results[0]->res;
+ size_t nx = result->nq;
+
+ // count
+ for (const RangeSearchPartialResult* pres : partial_results) {
+ if (!pres)
+ continue;
+ for (const RangeQueryResult& qres : pres->queries) {
+ result->lims[qres.qno] += qres.nres;
+ }
+ }
+ result->do_allocation();
+ for (int j = 0; j < npres; j++) {
+ if (!partial_results[j])
+ continue;
+ partial_results[j]->copy_result(true);
+ if (do_delete) {
+ delete partial_results[j];
+ partial_results[j] = nullptr;
+ }
+ }
+
+ // reset the limits
+ for (size_t i = nx; i > 0; i--) {
+ result->lims[i] = result->lims[i - 1];
+ }
+ result->lims[0] = 0;
+}
+
+/***********************************************************
+ * Interrupt callback
+ ***********************************************************/
+
+std::unique_ptr<InterruptCallback> InterruptCallback::instance;
+
+std::mutex InterruptCallback::lock;
+
+void InterruptCallback::clear_instance() {
+ delete instance.release();
+}
+
+void InterruptCallback::check() {
+ if (!instance.get()) {
+ return;
+ }
+ if (instance->want_interrupt()) {
+ FAISS_THROW_MSG("computation interrupted");
+ }
+}
+
+bool InterruptCallback::is_interrupted() {
+ if (!instance.get()) {
+ return false;
+ }
+ std::lock_guard<std::mutex> guard(lock);
+ return instance->want_interrupt();
+}
+
+size_t InterruptCallback::get_period_hint(size_t flops) {
+ if (!instance.get()) {
+ return (size_t)1 << 30; // never check
+ }
+ // for 10M flops, it is reasonable to check once every 10 iterations
+ return std::max((size_t)10 * 10 * 1000 * 1000 / (flops + 1), (size_t)1);
+}
+
+void TimeoutCallback::set_timeout(double timeout_in_seconds) {
+ timeout = timeout_in_seconds;
+ start = std::chrono::steady_clock::now();
+}
+
+bool TimeoutCallback::want_interrupt() {
+ if (timeout == 0) {
+ return false;
+ }
+ auto end = std::chrono::steady_clock::now();
+ std::chrono::duration<float, std::milli> duration = end - start;
+ float elapsed_in_seconds = duration.count() / 1000.0;
+ if (elapsed_in_seconds > timeout) {
+ timeout = 0;
+ return true;
+ }
+ return false;
+}
+
+void TimeoutCallback::reset(double timeout_in_seconds) {
+ auto tc(new faiss::TimeoutCallback());
+ faiss::InterruptCallback::instance.reset(tc);
+ tc->set_timeout(timeout_in_seconds);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AuxIndexStructures.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AuxIndexStructures.h
new file mode 100644
index 0000000..e1825c2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/AuxIndexStructures.h
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// Auxiliary index structures, that are used in indexes but that can
+// be forward-declared
+
+#ifndef FAISS_AUX_INDEX_STRUCTURES_H
+#define FAISS_AUX_INDEX_STRUCTURES_H
+
+#include <stdint.h>
+
+#include <cstring>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include <faiss/MetricType.h>
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/** The objective is to have a simple result structure while
+ * minimizing the number of mem copies in the result. The method
+ * do_allocation can be overloaded to allocate the result tables in
+ * the matrix type of a scripting language like Lua or Python. */
+struct RangeSearchResult {
+ size_t nq; ///< nb of queries
+ size_t* lims; ///< size (nq + 1)
+
+ idx_t* labels; ///< result for query i is labels[lims[i]:lims[i+1]]
+ float* distances; ///< corresponding distances (not sorted)
+
+ size_t buffer_size; ///< size of the result buffers used
+
+ /// lims must be allocated on input to range_search.
+ explicit RangeSearchResult(size_t nq, bool alloc_lims = true);
+
+ /// called when lims contains the nb of elements result entries
+ /// for each query
+ virtual void do_allocation();
+
+ virtual ~RangeSearchResult();
+};
+
+/****************************************************************
+ * Result structures for range search.
+ *
+ * The main constraint here is that we want to support parallel
+ * queries from different threads in various ways: 1 thread per query,
+ * several threads per query. We store the actual results in blocks of
+ * fixed size rather than exponentially increasing memory. At the end,
+ * we copy the block content to a linear result array.
+ *****************************************************************/
+
+/** List of temporary buffers used to store results before they are
+ * copied to the RangeSearchResult object. */
+struct BufferList {
+ // buffer sizes in # entries
+ size_t buffer_size;
+
+ struct Buffer {
+ idx_t* ids;
+ float* dis;
+ };
+
+ std::vector<Buffer> buffers;
+ size_t wp; ///< write pointer in the last buffer.
+
+ explicit BufferList(size_t buffer_size);
+
+ ~BufferList();
+
+ /// create a new buffer
+ void append_buffer();
+
+ /// add one result, possibly appending a new buffer if needed
+ void add(idx_t id, float dis);
+
+ /// copy elemnts ofs:ofs+n-1 seen as linear data in the buffers to
+ /// tables dest_ids, dest_dis
+ void copy_range(size_t ofs, size_t n, idx_t* dest_ids, float* dest_dis);
+};
+
+struct RangeSearchPartialResult;
+
+/// result structure for a single query
+struct RangeQueryResult {
+ idx_t qno; //< id of the query
+ size_t nres; //< nb of results for this query
+ RangeSearchPartialResult* pres;
+
+ /// called by search function to report a new result
+ void add(float dis, idx_t id);
+};
+
+/// the entries in the buffers are split per query
+struct RangeSearchPartialResult : BufferList {
+ RangeSearchResult* res;
+
+ /// eventually the result will be stored in res_in
+ explicit RangeSearchPartialResult(RangeSearchResult* res_in);
+
+ /// query ids + nb of results per query.
+ std::vector<RangeQueryResult> queries;
+
+ /// begin a new result
+ RangeQueryResult& new_result(idx_t qno);
+
+ /*****************************************
+ * functions used at the end of the search to merge the result
+ * lists */
+ void finalize();
+
+ /// called by range_search before do_allocation
+ void set_lims();
+
+ /// called by range_search after do_allocation
+ void copy_result(bool incremental = false);
+
+ /// merge a set of PartialResult's into one RangeSearchResult
+ /// on output the partialresults are empty!
+ static void merge(
+ std::vector<RangeSearchPartialResult*>& partial_results,
+ bool do_delete = true);
+};
+
+/***********************************************************
+ * Interrupt callback
+ ***********************************************************/
+
+struct FAISS_API InterruptCallback {
+ virtual bool want_interrupt() = 0;
+ virtual ~InterruptCallback() {}
+
+ // lock that protects concurrent calls to is_interrupted
+ static std::mutex lock;
+
+ static std::unique_ptr<InterruptCallback> instance;
+
+ static void clear_instance();
+
+ /** check if:
+ * - an interrupt callback is set
+ * - the callback returns true
+ * if this is the case, then throw an exception. Should not be called
+ * from multiple threads.
+ */
+ static void check();
+
+ /// same as check() but return true if is interrupted instead of
+ /// throwing. Can be called from multiple threads.
+ static bool is_interrupted();
+
+ /** assuming each iteration takes a certain number of flops, what
+ * is a reasonable interval to check for interrupts?
+ */
+ static size_t get_period_hint(size_t flops);
+};
+
+struct TimeoutCallback : InterruptCallback {
+ std::chrono::time_point<std::chrono::steady_clock> start;
+ double timeout;
+ bool want_interrupt() override;
+ void set_timeout(double timeout_in_seconds);
+ static void reset(double timeout_in_seconds);
+};
+
+/// set implementation optimized for fast access.
+struct VisitedTable {
+ std::vector<uint8_t> visited;
+ uint8_t visno;
+
+ explicit VisitedTable(int size) : visited(size), visno(1) {}
+
+ /// set flag #no to true
+ void set(int no) {
+ visited[no] = visno;
+ }
+
+ /// get flag #no
+ bool get(int no) const {
+ return visited[no] == visno;
+ }
+
+ /// reset all flags to false
+ void advance() {
+ visno++;
+ if (visno == 250) {
+ // 250 rather than 255 because sometimes we use visno and visno+1
+ memset(visited.data(), 0, sizeof(visited[0]) * visited.size());
+ visno = 1;
+ }
+ }
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/CodePacker.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/CodePacker.cpp
new file mode 100644
index 0000000..ee7b702
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/CodePacker.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/CodePacker.h>
+
+#include <cassert>
+#include <cstring>
+
+namespace faiss {
+
+/*********************************************
+ * CodePacker
+ * default of pack_all / unpack_all loops over the _1 versions
+ */
+
+void CodePacker::pack_all(const uint8_t* flat_codes, uint8_t* block) const {
+ for (size_t i = 0; i < nvec; i++) {
+ pack_1(flat_codes + code_size * i, i, block);
+ }
+}
+
+void CodePacker::unpack_all(const uint8_t* block, uint8_t* flat_codes) const {
+ for (size_t i = 0; i < nvec; i++) {
+ unpack_1(block, i, flat_codes + code_size * i);
+ }
+}
+
+/*********************************************
+ * CodePackerFlat
+ */
+
+CodePackerFlat::CodePackerFlat(size_t code_size) {
+ this->code_size = code_size;
+ nvec = 1;
+ block_size = code_size;
+}
+
+void CodePackerFlat::pack_all(const uint8_t* flat_codes, uint8_t* block) const {
+ memcpy(block, flat_codes, code_size);
+}
+
+void CodePackerFlat::unpack_all(const uint8_t* block, uint8_t* flat_codes)
+ const {
+ memcpy(flat_codes, block, code_size);
+}
+
+void CodePackerFlat::pack_1(
+ const uint8_t* flat_code,
+ size_t offset,
+ uint8_t* block) const {
+ assert(offset == 0);
+ pack_all(flat_code, block);
+}
+
+void CodePackerFlat::unpack_1(
+ const uint8_t* block,
+ size_t offset,
+ uint8_t* flat_code) const {
+ assert(offset == 0);
+ unpack_all(block, flat_code);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/CodePacker.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/CodePacker.h
new file mode 100644
index 0000000..60b42f5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/CodePacker.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/MetricType.h>
+
+namespace faiss {
+
+/**
+ * Packing consists in combining a fixed number of codes of constant size
+ * (code_size) into a block of data where they may (or may not) be interleaved
+ * for efficient consumption by distance computation kernels. This exists for
+ * the "fast_scan" indexes on CPU and for some GPU kernels.
+ */
+struct CodePacker {
+ size_t code_size; // input code size in bytes
+ size_t nvec; // number of vectors per block
+ size_t block_size; // size of one block in bytes (>= code_size * nvec)
+
+ // pack a single code to a block
+ virtual void pack_1(
+ const uint8_t*
+ flat_code, // code to write to the block, size code_size
+ size_t offset, // offset in the block (0 <= offset < nvec)
+ uint8_t* block // block to write to (size block_size)
+ ) const = 0;
+
+ // unpack a single code from a block
+ virtual void unpack_1(
+ const uint8_t* block, // block to read from (size block_size)
+ size_t offset, // offset in the block (0 <= offset < nvec)
+ uint8_t* flat_code // where to write the resulting code, size
+ // code_size
+ ) const = 0;
+
+ // pack all code in a block
+ virtual void pack_all(
+ const uint8_t* flat_codes, // codes to write to the block, size
+ // (nvec * code_size)
+ uint8_t* block // block to write to (size block_size)
+ ) const;
+
+ // unpack all code in a block
+ virtual void unpack_all(
+ const uint8_t* block, // block to read from (size block_size)
+ uint8_t* flat_codes // where to write the resulting codes size (nvec
+ // * code_size)
+ ) const;
+
+ virtual ~CodePacker() {}
+};
+
+/** Trivial code packer where codes are stored one by one */
+struct CodePackerFlat : CodePacker {
+ explicit CodePackerFlat(size_t code_size);
+
+ void pack_1(const uint8_t* flat_code, size_t offset, uint8_t* block)
+ const final;
+ void unpack_1(const uint8_t* block, size_t offset, uint8_t* flat_code)
+ const final;
+
+ void pack_all(const uint8_t* flat_codes, uint8_t* block) const final;
+ void unpack_all(const uint8_t* block, uint8_t* flat_codes) const final;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/DistanceComputer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/DistanceComputer.h
new file mode 100644
index 0000000..a8a822a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/DistanceComputer.h
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <vector>
+
+namespace faiss {
+
+/***********************************************************
+ * The distance computer maintains a current query and computes
+ * distances to elements in an index that supports random access.
+ *
+ * The DistanceComputer is not intended to be thread-safe (eg. because
+ * it maintains counters) so the distance functions are not const,
+ * instantiate one from each thread if needed.
+ *
+ * Note that the equivalent for IVF indexes is the InvertedListScanner,
+ * that has additional methods to handle the inverted list context.
+ ***********************************************************/
+struct DistanceComputer {
+ /// called before computing distances. Pointer x should remain valid
+ /// while operator () is called
+ virtual void set_query(const float* x) = 0;
+
+ virtual const float* get_query() {
+ return nullptr;
+ }
+
+ /// compute distance of vector i to current query
+ virtual float operator()(idx_t i) = 0;
+
+ /// compute distances of current query to 4 stored vectors.
+ /// certain DistanceComputer implementations may benefit
+ /// heavily from this.
+ virtual void distances_batch_4(
+ const idx_t idx0,
+ const idx_t idx1,
+ const idx_t idx2,
+ const idx_t idx3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) {
+ // compute first, assign next
+ const float d0 = this->operator()(idx0);
+ const float d1 = this->operator()(idx1);
+ const float d2 = this->operator()(idx2);
+ const float d3 = this->operator()(idx3);
+ dis0 = d0;
+ dis1 = d1;
+ dis2 = d2;
+ dis3 = d3;
+ }
+
+ /// compute distances of current query to a batch of stored vectors.
+ /// DistanceComputer implementations that can fetch data in batches
+ /// will benefit significantly from this.
+ virtual void distances_batch(
+ const std::vector<idx_t>& ids,
+ std::vector<float>& distances_out) {
+ size_t counter = 0;
+ for (counter = 0; counter < (ids.size() / 4) * 4; counter += 4) {
+ distances_batch_4(
+ ids[counter],
+ ids[counter + 1],
+ ids[counter + 2],
+ ids[counter + 3],
+ distances_out[counter],
+ distances_out[counter + 1],
+ distances_out[counter + 2],
+ distances_out[counter + 3]);
+ }
+ for (size_t i = counter; i < ids.size(); i++) {
+ distances_out[i] = this->operator()(ids[i]);
+ }
+ }
+
+ /// compute distance between two stored vectors
+ virtual float symmetric_dis(idx_t i, idx_t j) = 0;
+
+ /// Get statistics specific to this DistanceComputer instance (e.g., fetch
+ /// count).
+ virtual size_t get_fetch_count() const {
+ return 0; // Base implementation returns 0
+ }
+
+ /// Reset any internal counters or state related to statistics.
+ virtual void reset_fetch_count() {
+ // Base implementation does nothing
+ }
+
+ virtual ~DistanceComputer() {}
+};
+
+/* Wrap the distance computer into one that negates the
+ distances. This makes supporting INNER_PRODUCE search easier */
+
+struct NegativeDistanceComputer : DistanceComputer {
+ /// owned by this
+ DistanceComputer* basedis;
+
+ explicit NegativeDistanceComputer(DistanceComputer* basedis)
+ : basedis(basedis) {}
+
+ void set_query(const float* x) override {
+ basedis->set_query(x);
+ }
+
+ /// compute distance of vector i to current query
+ float operator()(idx_t i) override {
+ return -(*basedis)(i);
+ }
+
+ void distances_batch_4(
+ const idx_t idx0,
+ const idx_t idx1,
+ const idx_t idx2,
+ const idx_t idx3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) override {
+ basedis->distances_batch_4(
+ idx0, idx1, idx2, idx3, dis0, dis1, dis2, dis3);
+ dis0 = -dis0;
+ dis1 = -dis1;
+ dis2 = -dis2;
+ dis3 = -dis3;
+ }
+
+ /// compute distances of current query to a batch of stored vectors.
+ /// DistanceComputer implementations that can fetch data in batches
+ /// will benefit significantly from this.
+ // void distances_batch(
+ // const std::vector<idx_t>& ids,
+ // std::vector<float>& distances_out) override {
+ // basedis->distances_batch(ids, distances_out);
+ // for (float& dis : distances_out) {
+ // dis = -dis;
+ // }
+ // }
+
+ /// compute distance between two stored vectors
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return -basedis->symmetric_dis(i, j);
+ }
+
+ virtual ~NegativeDistanceComputer() {
+ delete basedis;
+ }
+};
+
+/*************************************************************
+ * Specialized version of the DistanceComputer when we know that codes are
+ * laid out in a flat index.
+ */
+struct FlatCodesDistanceComputer : DistanceComputer {
+ const uint8_t* codes;
+ size_t code_size;
+
+ FlatCodesDistanceComputer(const uint8_t* codes, size_t code_size)
+ : codes(codes), code_size(code_size) {}
+
+ FlatCodesDistanceComputer() : codes(nullptr), code_size(0) {}
+
+ float operator()(idx_t i) override {
+ return distance_to_code(codes + i * code_size);
+ }
+
+ /// compute distance of current query to an encoded vector
+ virtual float distance_to_code(const uint8_t* code) = 0;
+
+ virtual ~FlatCodesDistanceComputer() {}
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissAssert.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissAssert.h
new file mode 100644
index 0000000..0c56bc0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissAssert.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_ASSERT_INCLUDED
+#define FAISS_ASSERT_INCLUDED
+
+#include <faiss/impl/FaissException.h>
+#include <faiss/impl/platform_macros.h>
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+
+///
+/// Assertions
+///
+
+#define FAISS_ASSERT(X) \
+ do { \
+ if (!(X)) { \
+ fprintf(stderr, \
+ "Faiss assertion '%s' failed in %s " \
+ "at %s:%d\n", \
+ #X, \
+ __PRETTY_FUNCTION__, \
+ __FILE__, \
+ __LINE__); \
+ abort(); \
+ } \
+ } while (false)
+
+#define FAISS_ASSERT_MSG(X, MSG) \
+ do { \
+ if (!(X)) { \
+ fprintf(stderr, \
+ "Faiss assertion '%s' failed in %s " \
+ "at %s:%d; details: " MSG "\n", \
+ #X, \
+ __PRETTY_FUNCTION__, \
+ __FILE__, \
+ __LINE__); \
+ abort(); \
+ } \
+ } while (false)
+
+#define FAISS_ASSERT_FMT(X, FMT, ...) \
+ do { \
+ if (!(X)) { \
+ fprintf(stderr, \
+ "Faiss assertion '%s' failed in %s " \
+ "at %s:%d; details: " FMT "\n", \
+ #X, \
+ __PRETTY_FUNCTION__, \
+ __FILE__, \
+ __LINE__, \
+ __VA_ARGS__); \
+ abort(); \
+ } \
+ } while (false)
+
+///
+/// Exceptions for returning user errors
+///
+
+#define FAISS_THROW_MSG(MSG) \
+ do { \
+ throw faiss::FaissException( \
+ MSG, __PRETTY_FUNCTION__, __FILE__, __LINE__); \
+ } while (false)
+
+#define FAISS_THROW_FMT(FMT, ...) \
+ do { \
+ std::string __s; \
+ int __size = snprintf(nullptr, 0, FMT, __VA_ARGS__); \
+ __s.resize(__size + 1); \
+ snprintf(&__s[0], __s.size(), FMT, __VA_ARGS__); \
+ throw faiss::FaissException( \
+ __s, __PRETTY_FUNCTION__, __FILE__, __LINE__); \
+ } while (false)
+
+///
+/// Exceptions thrown upon a conditional failure
+///
+
+#define FAISS_THROW_IF_NOT(X) \
+ do { \
+ if (!(X)) { \
+ FAISS_THROW_FMT("Error: '%s' failed", #X); \
+ } \
+ } while (false)
+
+#define FAISS_THROW_IF_MSG(X, MSG) \
+ do { \
+ if (X) { \
+ FAISS_THROW_FMT("Error: '%s' failed: " MSG, #X); \
+ } \
+ } while (false)
+
+#define FAISS_THROW_IF_NOT_MSG(X, MSG) FAISS_THROW_IF_MSG(!(X), MSG)
+
+#define FAISS_THROW_IF_NOT_FMT(X, FMT, ...) \
+ do { \
+ if (!(X)) { \
+ FAISS_THROW_FMT("Error: '%s' failed: " FMT, #X, __VA_ARGS__); \
+ } \
+ } while (false)
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissException.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissException.cpp
new file mode 100644
index 0000000..5f99694
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissException.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/FaissException.h>
+#include <sstream>
+
+#ifdef __GNUG__
+#include <cxxabi.h>
+#endif
+
+namespace faiss {
+
+FaissException::FaissException(const std::string& m) : msg(m) {}
+
+FaissException::FaissException(
+ const std::string& m,
+ const char* funcName,
+ const char* file,
+ int line) {
+ int size = snprintf(
+ nullptr,
+ 0,
+ "Error in %s at %s:%d: %s",
+ funcName,
+ file,
+ line,
+ m.c_str());
+ msg.resize(size + 1);
+ snprintf(
+ &msg[0],
+ msg.size(),
+ "Error in %s at %s:%d: %s",
+ funcName,
+ file,
+ line,
+ m.c_str());
+}
+
+const char* FaissException::what() const noexcept {
+ return msg.c_str();
+}
+
+void handleExceptions(
+ std::vector<std::pair<int, std::exception_ptr>>& exceptions) {
+ if (exceptions.size() == 1) {
+ // throw the single received exception directly
+ std::rethrow_exception(exceptions.front().second);
+
+ } else if (exceptions.size() > 1) {
+ // multiple exceptions; aggregate them and return a single exception
+ std::stringstream ss;
+
+ for (auto& p : exceptions) {
+ try {
+ std::rethrow_exception(p.second);
+ } catch (std::exception& ex) {
+ if (ex.what()) {
+ // exception message available
+ ss << "Exception thrown from index " << p.first << ": "
+ << ex.what() << "\n";
+ } else {
+ // No message available
+ ss << "Unknown exception thrown from index " << p.first
+ << "\n";
+ }
+ } catch (...) {
+ ss << "Unknown exception thrown from index " << p.first << "\n";
+ }
+ }
+
+ throw FaissException(ss.str());
+ }
+}
+
+// From
+// https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname
+
+std::string demangle_cpp_symbol(const char* name) {
+#ifdef __GNUG__
+ int status = -1;
+ const char* res = abi::__cxa_demangle(name, nullptr, nullptr, &status);
+ std::string sres;
+ if (status == 0) {
+ sres = res;
+ }
+ free((void*)res);
+ return sres;
+#else
+ // don't know how to do this on other platforms
+ return std::string(name);
+#endif
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissException.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissException.h
new file mode 100644
index 0000000..de943a3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/FaissException.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_EXCEPTION_INCLUDED
+#define FAISS_EXCEPTION_INCLUDED
+
+#include <exception>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace faiss {
+
+/// Base class for Faiss exceptions
+class FaissException : public std::exception {
+ public:
+ explicit FaissException(const std::string& msg);
+
+ FaissException(
+ const std::string& msg,
+ const char* funcName,
+ const char* file,
+ int line);
+
+ /// from std::exception
+ const char* what() const noexcept override;
+
+ std::string msg;
+};
+
+/// Handle multiple exceptions from worker threads, throwing an appropriate
+/// exception that aggregates the information
+/// The pair int is the thread that generated the exception
+void handleExceptions(
+ std::vector<std::pair<int, std::exception_ptr>>& exceptions);
+
+/** RAII object for a set of possibly transformed vectors (deallocated only if
+ * they are indeed transformed)
+ */
+struct TransformedVectors {
+ const float* x;
+ bool own_x;
+ TransformedVectors(const float* x_orig, const float* x) : x(x) {
+ own_x = x_orig != x;
+ }
+
+ ~TransformedVectors() {
+ if (own_x) {
+ delete[] x;
+ }
+ }
+};
+
+/// make typeids more readable
+std::string demangle_cpp_symbol(const char* name);
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW.cpp
new file mode 100644
index 0000000..5622452
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW.cpp
@@ -0,0 +1,1511 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/HNSW.h>
+
+#include <cstddef>
+#include "faiss/IndexHNSW.h"
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/prefetch.h>
+
+#include <faiss/impl/platform_macros.h>
+
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/stat.h> // For file size check
+#include <unistd.h>
+#include <algorithm>
+#include <cerrno>
+#include <cmath>
+#include <cstring>
+#include "faiss/impl/FaissAssert.h"
+
+#ifdef __AVX2__
+#include <immintrin.h>
+
+#include <limits>
+#include <type_traits>
+#endif
+
+namespace faiss {
+
+/**************************************************************
+ * HNSW structure implementation
+ **************************************************************/
+// merge nodes
+void HNSW::merge_nodes(float merge_threshold) {
+ // only merge nodes in the last layer
+}
+
+// Minimal, level-0 only, non-compact edge deletion
+void HNSW::delete_random_level0_edges_minimal(float prune_ratio) {
+ // --- Assert assumptions ---
+ FAISS_THROW_IF_NOT_FMT(
+ !storage_is_compact,
+ "Function %s requires non-compact storage",
+ __func__);
+
+ if (prune_ratio == 0) {
+ return; // Nothing to do
+ }
+ if (levels.empty()) {
+ return; // No nodes
+ }
+
+ // --- Step 1: Identify all valid level 0 edge locations ---
+ std::vector<Level0EdgeLocation> candidates;
+ // Simple estimate, could be refined
+ candidates.reserve(levels.size() * nb_neighbors(0));
+
+ for (storage_idx_t node_id = 0; node_id < levels.size(); ++node_id) {
+ // Skip nodes that don't exist at level 0 (shouldn't happen if
+ // levels[node_id] >= 1)
+ if (levels[node_id] <= 0)
+ continue;
+
+ size_t begin, end;
+ neighbor_range(node_id, 0, &begin, &end); // Get level 0 range
+
+ for (size_t idx = begin; idx < end; ++idx) {
+ if (neighbors[idx] != -1) {
+ candidates.emplace_back(node_id, idx);
+ } else {
+ // Found the -1 sentinel, stop searching for this node's level 0
+ // neighbors
+ break;
+ }
+ }
+ }
+
+ // --- Step 2: Shuffle and Select ---
+ if (candidates.empty()) {
+ printf("No valid level 0 edges found to delete.\n");
+ return;
+ }
+
+ size_t actual_num_to_delete = prune_ratio * candidates.size();
+ printf("Found %zd level 0 edges. Attempting to delete %zd.\n",
+ candidates.size(),
+ actual_num_to_delete);
+
+ std::random_device rd;
+ std::default_random_engine engine(rd());
+ std::shuffle(candidates.begin(), candidates.end(), engine);
+
+ // --- Step 3: Delete using "swap with last" ---
+ size_t deleted_count = 0;
+ for (size_t i = 0; i < actual_num_to_delete; ++i) {
+ const auto& loc = candidates[i];
+ storage_idx_t node_id = loc.node_id;
+ size_t index_to_delete = loc.neighbor_array_index;
+
+ // Minimal check: Skip if it somehow already got deleted
+ // if (neighbors[index_to_delete] == -1) {
+ // continue;
+ // }
+ while (neighbors[index_to_delete] == -1 && index_to_delete > 0) {
+ index_to_delete--;
+ }
+ assert(neighbors[index_to_delete] != -1);
+ size_t begin, end;
+ neighbor_range(node_id, 0, &begin, &end); // Level 0 range
+
+ // Find last valid neighbor index in [begin, end)
+ size_t idx_last_valid = begin; // Initialize, will be overwritten
+ bool found_last = false;
+ for (size_t j = end; j > begin; --j) {
+ if (neighbors[j - 1] != -1) {
+ idx_last_valid = j - 1;
+ found_last = true;
+ break;
+ }
+ }
+
+ // If no valid neighbor found (only possible if list was already all
+ // -1s?) Or if somehow the target index is beyond last valid (should not
+ // happen)
+ if (!found_last || index_to_delete > idx_last_valid) {
+ assert(false);
+ }
+
+ // Swap-and-delete
+ if (index_to_delete == idx_last_valid) {
+ neighbors[index_to_delete] = -1;
+ } else {
+ std::swap(neighbors[index_to_delete], neighbors[idx_last_valid]);
+ neighbors[idx_last_valid] = -1;
+ }
+ deleted_count++;
+ }
+
+ printf("Minimal delete: %zd level 0 edges processed.\n", deleted_count);
+}
+
+int HNSW::nb_neighbors(int layer_no) const {
+ FAISS_THROW_IF_NOT(layer_no + 1 < cum_nneighbor_per_level.size());
+ return cum_nneighbor_per_level[layer_no + 1] -
+ cum_nneighbor_per_level[layer_no];
+}
+
+void HNSW::set_nb_neighbors(int level_no, int n) {
+ FAISS_THROW_IF_NOT(levels.size() == 0);
+ int cur_n = nb_neighbors(level_no);
+ for (int i = level_no + 1; i < cum_nneighbor_per_level.size(); i++) {
+ cum_nneighbor_per_level[i] += n - cur_n;
+ }
+}
+
+int HNSW::cum_nb_neighbors(int layer_no) const {
+ return cum_nneighbor_per_level[layer_no];
+}
+
+HNSW::HNSW(int M, int M0) : rng(12345) {
+ set_default_probas(M, 1.0 / log(M), M0);
+ offsets.push_back(0);
+
+ // Initialize disk/mmap access fields
+ neighbors_on_disk = false;
+ graph_fd = -1;
+ neighbors_start_offset = -1;
+ neighbors_mmap_ptr = nullptr;
+ neighbors_use_mmap = false;
+}
+
+int HNSW::random_level() {
+ double f = rng.rand_float();
+ // could be a bit faster with bissection
+ for (int level = 0; level < assign_probas.size(); level++) {
+ if (f < assign_probas[level]) {
+ return level;
+ }
+ f -= assign_probas[level];
+ }
+ // happens with exponentially low probability
+ return assign_probas.size() - 1;
+}
+
+void HNSW::set_default_probas(int M, float levelMult, int M0) {
+ int nn = 0;
+ // printf("M0: %d\n", M0);
+ // printf("M: %d\n", M);
+ if (M0 == -1) {
+ M0 = M * 2;
+ }
+ cum_nneighbor_per_level.push_back(0);
+ for (int level = 0;; level++) {
+ float proba = exp(-level / levelMult) * (1 - exp(-1 / levelMult));
+ if (proba < 1e-9)
+ break;
+ assign_probas.push_back(proba);
+ nn += level == 0 ? M0 : M;
+ // printf("level %d, proba %f, nn %d\n", level, proba, nn);
+ cum_nneighbor_per_level.push_back(nn);
+ }
+}
+
+void HNSW::clear_neighbor_tables(int level) {
+ for (int i = 0; i < levels.size(); i++) {
+ size_t begin, end;
+ neighbor_range(i, level, &begin, &end);
+ for (size_t j = begin; j < end; j++) {
+ neighbors[j] = -1;
+ }
+ }
+}
+
+void HNSW::reset() {
+ max_level = -1;
+ entry_point = -1;
+ offsets.clear();
+ offsets.push_back(0);
+ levels.clear();
+ neighbors.clear();
+
+ // Clear compact storage fields
+ storage_is_compact = false; // Reset flag to default
+ compact_neighbors_data.clear();
+ compact_level_ptr.clear();
+ compact_node_offsets.clear();
+
+ // Reset disk/mmap access fields
+ neighbors_on_disk = false;
+ if (graph_fd != -1) {
+ close(graph_fd);
+ graph_fd = -1;
+ }
+ hnsw_index_filename.clear();
+ neighbors_start_offset = -1;
+ neighbors_mmap_ptr = nullptr;
+ neighbors_use_mmap = false;
+}
+
+void HNSW::save_degree_distribution(int level, const char* filename) const {
+ // Check if level is valid
+ if (level < 0 || level >= cum_nneighbor_per_level.size() - 1) {
+ fprintf(stderr,
+ "Invalid level %d (max level is %d)\n",
+ level,
+ (int)cum_nneighbor_per_level.size() - 2);
+ return;
+ }
+
+ // Open file for writing
+ FILE* f = fopen(filename, "w");
+ if (!f) {
+ fprintf(stderr, "Could not open %s for writing\n", filename);
+ return;
+ }
+
+ // For each node, count actual neighbors at the specified level
+ printf("Computing degree distribution for level %d\n", level);
+
+ // Only consider nodes that exist at this level or above
+ int nodes_at_level = 0;
+ for (int i = 0; i < levels.size(); i++) {
+ if (levels[i] > level) {
+ nodes_at_level++;
+
+ // Count actual neighbors (not -1)
+ size_t begin, end;
+ neighbor_range(i, level, &begin, &end);
+
+ int degree = 0;
+ for (size_t j = begin; j < end; j++) {
+ if (neighbors[j] >= 0) {
+ degree++;
+ } else {
+ break; // Stop at first -1
+ }
+ }
+
+ // Write the degree to the file
+ fprintf(f, "%d\n", degree);
+ }
+ }
+
+ fclose(f);
+ printf("Saved degree distribution for %d nodes at level %d to %s\n",
+ nodes_at_level,
+ level,
+ filename);
+
+ // Print command to generate the plot
+ printf("To visualize the distribution, run:\n");
+ printf("python -m faiss.contrib.plot_degree_distribution %s\n", filename);
+}
+
+void HNSW::print_neighbor_stats(int level) const {
+ FAISS_THROW_IF_NOT(level < cum_nneighbor_per_level.size());
+ printf("stats on level %d, max %d neighbors per vertex:\n",
+ level,
+ nb_neighbors(level));
+ size_t tot_neigh = 0, tot_common = 0, tot_reciprocal = 0, n_node = 0;
+#pragma omp parallel for reduction(+ : tot_neigh) reduction(+ : tot_common) \
+ reduction(+ : tot_reciprocal) reduction(+ : n_node)
+ for (int i = 0; i < levels.size(); i++) {
+ if (levels[i] > level) {
+ n_node++;
+ size_t begin, end;
+ neighbor_range(i, level, &begin, &end);
+ std::unordered_set<int> neighset;
+ for (size_t j = begin; j < end; j++) {
+ if (neighbors[j] < 0)
+ break;
+ neighset.insert(neighbors[j]);
+ }
+ int n_neigh = neighset.size();
+ int n_common = 0;
+ int n_reciprocal = 0;
+ for (size_t j = begin; j < end; j++) {
+ storage_idx_t i2 = neighbors[j];
+ if (i2 < 0)
+ break;
+ FAISS_ASSERT(i2 != i);
+ size_t begin2, end2;
+ neighbor_range(i2, level, &begin2, &end2);
+ for (size_t j2 = begin2; j2 < end2; j2++) {
+ storage_idx_t i3 = neighbors[j2];
+ if (i3 < 0)
+ break;
+ if (i3 == i) {
+ n_reciprocal++;
+ continue;
+ }
+ if (neighset.count(i3)) {
+ neighset.erase(i3);
+ n_common++;
+ }
+ }
+ }
+ tot_neigh += n_neigh;
+ tot_common += n_common;
+ tot_reciprocal += n_reciprocal;
+ }
+ }
+ float normalizer = n_node;
+ printf(" nb of nodes at that level %zd\n", n_node);
+ printf(" neighbors per node: %.2f (%zd)\n",
+ tot_neigh / normalizer,
+ tot_neigh);
+ printf(" nb of reciprocal neighbors: %.2f\n",
+ tot_reciprocal / normalizer);
+ printf(" nb of neighbors that are also neighbor-of-neighbors: %.2f (%zd)\n",
+ tot_common / normalizer,
+ tot_common);
+}
+
+void HNSW::fill_with_random_links(size_t n) {
+ int max_level_2 = prepare_level_tab(n);
+ RandomGenerator rng2(456);
+
+ for (int level = max_level_2 - 1; level >= 0; --level) {
+ std::vector<int> elts;
+ for (int i = 0; i < n; i++) {
+ if (levels[i] > level) {
+ elts.push_back(i);
+ }
+ }
+ printf("linking %zd elements in level %d\n", elts.size(), level);
+
+ if (elts.size() == 1)
+ continue;
+
+ for (int ii = 0; ii < elts.size(); ii++) {
+ int i = elts[ii];
+ size_t begin, end;
+ neighbor_range(i, 0, &begin, &end);
+ for (size_t j = begin; j < end; j++) {
+ int other = 0;
+ do {
+ other = elts[rng2.rand_int(elts.size())];
+ } while (other == i);
+
+ neighbors[j] = other;
+ }
+ }
+ }
+}
+
+int HNSW::prepare_level_tab(size_t n, bool preset_levels) {
+ size_t n0 = offsets.size() - 1;
+
+ if (preset_levels) {
+ FAISS_ASSERT(n0 + n == levels.size());
+ } else {
+ FAISS_ASSERT(n0 == levels.size());
+ for (int i = 0; i < n; i++) {
+ int pt_level = random_level();
+ levels.push_back(pt_level + 1);
+ }
+ }
+
+ int max_level_2 = 0;
+ for (int i = 0; i < n; i++) {
+ int pt_level = levels[i + n0] - 1;
+ if (pt_level > max_level_2)
+ max_level_2 = pt_level;
+ offsets.push_back(offsets.back() + cum_nb_neighbors(pt_level + 1));
+ }
+ neighbors.resize(offsets.back(), -1);
+
+ return max_level_2;
+}
+
+/** Enumerate vertices from nearest to farthest from query, keep a
+ * neighbor only if there is no previous neighbor that is closer to
+ * that vertex than the query.
+ */
+void HNSW::shrink_neighbor_list(
+ DistanceComputer& qdis,
+ std::priority_queue<NodeDistFarther>& input,
+ std::vector<NodeDistFarther>& output,
+ int max_size,
+ bool keep_max_size_level0) {
+ // RNG pruning
+ // This prevents number of neighbors at
+ // level 0 from being shrunk to less than 2 * M.
+ // This is essential in making sure
+ // `faiss::gpu::GpuIndexCagra::copyFrom(IndexHNSWCagra*)` is functional
+ std::vector<NodeDistFarther> outsiders;
+
+ while (input.size() > 0) {
+ NodeDistFarther v1 = input.top();
+ input.pop();
+ float dist_v1_q = v1.d;
+
+ bool good = true;
+ for (NodeDistFarther v2 : output) {
+ float dist_v1_v2 = qdis.symmetric_dis(v2.id, v1.id);
+
+ if (dist_v1_v2 < dist_v1_q) {
+ good = false;
+ break;
+ }
+ }
+
+ if (good) {
+ output.push_back(v1);
+ if (output.size() >= max_size) {
+ return;
+ }
+ } else if (keep_max_size_level0) {
+ outsiders.push_back(v1);
+ }
+ }
+ size_t idx = 0;
+ while (keep_max_size_level0 && (output.size() < max_size) &&
+ (idx < outsiders.size())) {
+ output.push_back(outsiders[idx++]);
+ }
+}
+
+namespace {
+
+using storage_idx_t = HNSW::storage_idx_t;
+using NodeDistCloser = HNSW::NodeDistCloser;
+using NodeDistFarther = HNSW::NodeDistFarther;
+
+/**************************************************************
+ * Addition subroutines
+ **************************************************************/
+
+/// remove neighbors from the list to make it smaller than max_size
+void shrink_neighbor_list(
+ DistanceComputer& qdis,
+ std::priority_queue<NodeDistCloser>& resultSet1,
+ int max_size,
+ bool keep_max_size_level0 = false) {
+ // if remove this, which menas we will enforce RNG check no matter if the
+ // degree is too high this does not work to save degree()may because nodes
+ // with low degree already hvae strict go though RNG test
+ if (resultSet1.size() < max_size) {
+ return;
+ }
+ std::priority_queue<NodeDistFarther> resultSet;
+ std::vector<NodeDistFarther> returnlist;
+
+ while (resultSet1.size() > 0) {
+ resultSet.emplace(resultSet1.top().d, resultSet1.top().id);
+ resultSet1.pop();
+ }
+
+ HNSW::shrink_neighbor_list(
+ qdis, resultSet, returnlist, max_size, keep_max_size_level0);
+
+ for (NodeDistFarther curen2 : returnlist) {
+ resultSet1.emplace(curen2.d, curen2.id);
+ }
+}
+
+/// add a link between two elements, possibly shrinking the list
+/// of links to make room for it.
+void add_link(
+ HNSW& hnsw,
+ DistanceComputer& qdis,
+ storage_idx_t src,
+ storage_idx_t dest,
+ int level,
+ bool keep_max_size_level0 = false) {
+ size_t begin, end;
+ hnsw.neighbor_range(src, level, &begin, &end);
+ if (hnsw.neighbors[end - 1] == -1) {
+ // there is enough room, find a slot to add it
+ size_t i = end;
+ while (i > begin) {
+ if (hnsw.neighbors[i - 1] != -1)
+ break;
+ i--;
+ }
+ hnsw.neighbors[i] = dest;
+ return;
+ }
+
+ // otherwise we let them fight out which to keep
+
+ // copy to resultSet...
+ std::priority_queue<NodeDistCloser> resultSet;
+ resultSet.emplace(qdis.symmetric_dis(src, dest), dest);
+ for (size_t i = begin; i < end; i++) { // HERE WAS THE BUG
+ storage_idx_t neigh = hnsw.neighbors[i];
+ resultSet.emplace(qdis.symmetric_dis(src, neigh), neigh);
+ }
+
+ shrink_neighbor_list(qdis, resultSet, end - begin, keep_max_size_level0);
+
+ // ...and back
+ size_t i = begin;
+ while (resultSet.size()) {
+ hnsw.neighbors[i++] = resultSet.top().id;
+ resultSet.pop();
+ }
+ // they may have shrunk more than just by 1 element
+ while (i < end) {
+ hnsw.neighbors[i++] = -1;
+ }
+}
+
+/// add a link between two elements, possibly shrinking the list
+/// of links to make room for it.
+// this is a variant of add_link that prunes the list with 90% probability
+void add_link_pruned(
+ HNSW& hnsw,
+ DistanceComputer& qdis,
+ storage_idx_t src,
+ storage_idx_t dest,
+ int level,
+ bool keep_max_size_level0 = false) {
+ assert(level == 0);
+ size_t begin, end;
+ hnsw.neighbor_range(src, level, &begin, &end);
+
+ int strict_end = end;
+ if (hnsw.neighbors[end - 1] == -1) {
+ // there is enough room, find a slot to add it
+ size_t i = end;
+ while (i > begin) {
+ if (hnsw.neighbors[i - 1] != -1)
+ break;
+ i--;
+ }
+ strict_end = i;
+ if (level == 0 && strict_end - begin < hnsw.ems[src]) {
+ hnsw.neighbors[i] = dest;
+ return;
+ }
+ }
+ // printf("strict_end: %d\n", strict_end);
+
+ // otherwise we let them fight out which to keep
+
+ // copy to resultSet...
+ std::priority_queue<NodeDistCloser> resultSet;
+ resultSet.emplace(qdis.symmetric_dis(src, dest), dest);
+ for (size_t i = begin; i < strict_end; i++) { // HERE WAS THE BUG
+ storage_idx_t neigh = hnsw.neighbors[i];
+ resultSet.emplace(qdis.symmetric_dis(src, neigh), neigh);
+ }
+
+ // printf("end - begin: %zd, strict_end - begin: %zd\n", end - begin,
+ // strict_end - begin);
+ int len = strict_end - begin;
+ len = std::min(len, hnsw.ems[src]);
+ printf("len: %d, ems[src]: %d\n", len, hnsw.ems[src]);
+ // assert (len != 64);
+ // assert (len==8);
+ shrink_neighbor_list(qdis, resultSet, len, keep_max_size_level0);
+
+ // ...and back
+ size_t i = begin;
+ while (resultSet.size()) {
+ hnsw.neighbors[i++] = resultSet.top().id;
+ resultSet.pop();
+ }
+ // they may have shrunk more than just by 1 element
+ while (i < end) {
+ hnsw.neighbors[i++] = -1;
+ }
+}
+
+} // namespace
+
+/// search neighbors on a single level, starting from an entry point
+void search_neighbors_to_add(
+ HNSW& hnsw,
+ DistanceComputer& qdis,
+ std::priority_queue<NodeDistCloser>& results,
+ int entry_point,
+ float d_entry_point,
+ int level,
+ VisitedTable& vt,
+ bool reference_version) {
+ // top is nearest candidate
+ std::priority_queue<NodeDistFarther> candidates;
+
+ NodeDistFarther ev(d_entry_point, entry_point);
+ candidates.push(ev);
+ results.emplace(d_entry_point, entry_point);
+ vt.set(entry_point);
+
+ while (!candidates.empty()) {
+ // get nearest
+ const NodeDistFarther& currEv = candidates.top();
+
+ if (currEv.d > results.top().d) {
+ break;
+ }
+ int currNode = currEv.id;
+ candidates.pop();
+
+ // loop over neighbors
+ size_t begin, end;
+ hnsw.neighbor_range(currNode, level, &begin, &end);
+
+ // The reference version is not used, but kept here because:
+ // 1. It is easier to switch back if the optimized version has a problem
+ // 2. It serves as a starting point for new optimizations
+ // 3. It helps understand the code
+ // 4. It ensures the reference version is still compilable if the
+ // optimized version changes
+ // The reference and the optimized versions' results are compared in
+ // test_hnsw.cpp
+ if (reference_version) {
+ // a reference version
+ for (size_t i = begin; i < end; i++) {
+ storage_idx_t nodeId = hnsw.neighbors[i];
+ if (nodeId < 0)
+ break;
+ if (vt.get(nodeId))
+ continue;
+ vt.set(nodeId);
+
+ float dis = qdis(nodeId);
+ NodeDistFarther evE1(dis, nodeId);
+
+ if (results.size() < hnsw.efConstruction ||
+ results.top().d > dis) {
+ results.emplace(dis, nodeId);
+ candidates.emplace(dis, nodeId);
+ if (results.size() > hnsw.efConstruction) {
+ results.pop();
+ }
+ }
+ }
+ } else {
+ // a faster version
+
+ // the following version processes 4 neighbors at a time
+ auto update_with_candidate = [&](const storage_idx_t idx,
+ const float dis) {
+ if (results.size() < hnsw.efConstruction ||
+ results.top().d > dis) {
+ results.emplace(dis, idx);
+ candidates.emplace(dis, idx);
+ if (results.size() > hnsw.efConstruction) {
+ results.pop();
+ }
+ }
+ };
+
+ int n_buffered = 0;
+ storage_idx_t buffered_ids[4];
+
+ for (size_t j = begin; j < end; j++) {
+ storage_idx_t nodeId = hnsw.neighbors[j];
+ if (nodeId < 0)
+ break;
+ if (vt.get(nodeId)) {
+ continue;
+ }
+ vt.set(nodeId);
+
+ buffered_ids[n_buffered] = nodeId;
+ n_buffered += 1;
+
+ if (n_buffered == 4) {
+ float dis[4];
+ qdis.distances_batch_4(
+ buffered_ids[0],
+ buffered_ids[1],
+ buffered_ids[2],
+ buffered_ids[3],
+ dis[0],
+ dis[1],
+ dis[2],
+ dis[3]);
+
+ for (size_t id4 = 0; id4 < 4; id4++) {
+ update_with_candidate(buffered_ids[id4], dis[id4]);
+ }
+
+ n_buffered = 0;
+ }
+ }
+
+ // process leftovers
+ for (size_t icnt = 0; icnt < n_buffered; icnt++) {
+ float dis = qdis(buffered_ids[icnt]);
+ update_with_candidate(buffered_ids[icnt], dis);
+ }
+ }
+ }
+
+ vt.advance();
+}
+
+/// Finds neighbors and builds links with them, starting from an entry
+/// point. The own neighbor list is assumed to be locked.
+void HNSW::add_links_starting_from(
+ DistanceComputer& ptdis,
+ storage_idx_t pt_id,
+ storage_idx_t nearest,
+ float d_nearest,
+ int level,
+ omp_lock_t* locks,
+ VisitedTable& vt,
+ bool keep_max_size_level0) {
+ std::priority_queue<NodeDistCloser> link_targets;
+
+ search_neighbors_to_add(
+ *this, ptdis, link_targets, nearest, d_nearest, level, vt);
+
+ // but we can afford only this many neighbors
+ int M = nb_neighbors(level);
+
+ ::faiss::shrink_neighbor_list(
+ ptdis, link_targets, ems[pt_id], keep_max_size_level0);
+
+ std::vector<storage_idx_t> neighbors_to_add;
+ neighbors_to_add.reserve(link_targets.size());
+ bool prune_in_add_link = false;
+
+ // Check if we should apply node merging based on distance threshold
+ bool apply_merging = !percentile_thresholds.empty() && level == 0;
+ float merge_threshold =
+ apply_merging ? get_threshold_for_percentile(50.0f) : 0.0f;
+ bool pass_first_node = false;
+ bool merged_node = false;
+
+ while (!link_targets.empty()) {
+ storage_idx_t other_id = link_targets.top().id;
+ float distance = link_targets.top().d;
+
+ // If this is the first node and its distance is below threshold, add it
+ // and break
+ if (merged_node && apply_merging && !pass_first_node && distance < -1.8) {
+ if (level == 0 && M > ems[pt_id] && prune_in_add_link) {
+ add_link_pruned(
+ *this,
+ ptdis,
+ pt_id,
+ other_id,
+ level,
+ keep_max_size_level0);
+ } else {
+ add_link(
+ *this,
+ ptdis,
+ pt_id,
+ other_id,
+ level,
+ keep_max_size_level0);
+ }
+ neighbors_to_add.push_back(other_id);
+ pass_first_node = true;
+ link_targets.pop();
+ printf("add_link_pruned src, dst, distance: %d, %d, %f\n", pt_id, other_id, distance);
+ break; // Only add this one node and stop
+ }
+
+ // Normal processing for nodes above threshold or when merging is not
+ // applied
+ if (level == 0 && M > ems[pt_id] && prune_in_add_link) {
+ add_link_pruned(
+ *this, ptdis, pt_id, other_id, level, keep_max_size_level0);
+ } else {
+ add_link(
+ *this, ptdis, pt_id, other_id, level, keep_max_size_level0);
+ }
+ neighbors_to_add.push_back(other_id);
+ link_targets.pop();
+ }
+
+ omp_unset_lock(&locks[pt_id]);
+ for (storage_idx_t other_id : neighbors_to_add) {
+ omp_set_lock(&locks[other_id]);
+ if (level == 0 && M > ems[other_id] && prune_in_add_link) {
+ add_link_pruned(
+ *this, ptdis, other_id, pt_id, level, keep_max_size_level0);
+ } else {
+ add_link(
+ *this, ptdis, other_id, pt_id, level, keep_max_size_level0);
+ }
+ omp_unset_lock(&locks[other_id]);
+ }
+ omp_set_lock(&locks[pt_id]);
+}
+
+/**************************************************************
+ * Building, parallel
+ **************************************************************/
+
+void HNSW::add_with_locks(
+ DistanceComputer& ptdis,
+ int pt_level,
+ int pt_id,
+ std::vector<omp_lock_t>& locks,
+ VisitedTable& vt,
+ bool keep_max_size_level0) {
+ // greedy search on upper levels
+
+ storage_idx_t nearest;
+#pragma omp critical
+ {
+ nearest = entry_point;
+
+ if (nearest == -1) {
+ max_level = pt_level;
+ entry_point = pt_id;
+ }
+ }
+
+ if (nearest < 0) {
+ return;
+ }
+
+ omp_set_lock(&locks[pt_id]);
+
+ int level = max_level; // level at which we start adding neighbors
+ float d_nearest = ptdis(nearest);
+
+ for (; level > pt_level; level--) {
+ greedy_update_nearest(*this, ptdis, level, nearest, d_nearest);
+ }
+
+ for (; level >= 0; level--) {
+ add_links_starting_from(
+ ptdis,
+ pt_id,
+ nearest,
+ d_nearest,
+ level,
+ locks.data(),
+ vt,
+ keep_max_size_level0);
+ }
+
+ omp_unset_lock(&locks[pt_id]);
+
+ if (pt_level > max_level) {
+ max_level = pt_level;
+ entry_point = pt_id;
+ }
+}
+
+/**************************************************************
+ * Searching
+ **************************************************************/
+
+inline HNSW::storage_idx_t get_neighbor_id_internal(
+ const HNSW& hnsw,
+ size_t index_in_neighbor_array) {
+ // assumes index_in_neighbor_array is valid based on begin/end from
+ // neighbor_range
+ return hnsw.storage_is_compact
+ ? hnsw.compact_neighbors_data[index_in_neighbor_array]
+ : hnsw.neighbors[index_in_neighbor_array];
+}
+
+using MinimaxHeap = HNSW::MinimaxHeap;
+using Node = HNSW::Node;
+using C = HNSW::C;
+
+std::priority_queue<HNSW::Node> search_from_candidate_unbounded(
+ const HNSW& hnsw,
+ const Node& node,
+ DistanceComputer& qdis,
+ int ef,
+ VisitedTable* vt,
+ HNSWStats& stats) {
+ int ndis = 0;
+ std::priority_queue<Node> top_candidates;
+ std::priority_queue<Node, std::vector<Node>, std::greater<Node>> candidates;
+
+ top_candidates.push(node);
+ candidates.push(node);
+
+ vt->set(node.second);
+
+ while (!candidates.empty()) {
+ float d0;
+ storage_idx_t v0;
+ std::tie(d0, v0) = candidates.top();
+
+ if (d0 > top_candidates.top().first) {
+ break;
+ }
+
+ candidates.pop();
+
+ size_t begin, end;
+ hnsw.neighbor_range(v0, 0, &begin, &end);
+
+ // a faster version: reference version in unit test test_hnsw.cpp
+ // the following version processes 4 neighbors at a time
+ size_t jmax = begin;
+ for (size_t j = begin; j < end; j++) {
+ // *** CSR Change: Conditional neighbor access ***
+ int v1 = hnsw.storage_is_compact ? hnsw.compact_neighbors_data[j]
+ : hnsw.neighbors[j];
+ // *** CSR Change: Conditional break for original format ***
+ if (!hnsw.storage_is_compact && v1 < 0)
+ break;
+
+ if (v1 >= 0) {
+ prefetch_L2(vt->visited.data() + v1);
+ }
+ jmax += 1;
+ }
+
+ int counter = 0;
+ size_t saved_j[4];
+
+ auto add_to_heap = [&](const size_t idx, const float dis) {
+ if (top_candidates.top().first > dis ||
+ top_candidates.size() < ef) {
+ candidates.emplace(dis, idx);
+ top_candidates.emplace(dis, idx);
+
+ if (top_candidates.size() > ef) {
+ top_candidates.pop();
+ }
+ }
+ };
+
+ std::vector<idx_t> ids_to_process;
+ ids_to_process.reserve(jmax - begin);
+
+ for (size_t j = begin; j < jmax; j++) {
+ // *** CSR Change: Conditional neighbor access ***
+ int v1 = hnsw.storage_is_compact ? hnsw.compact_neighbors_data[j]
+ : hnsw.neighbors[j];
+
+ bool vget = vt->get(v1);
+ vt->set(v1);
+ if (!vget) {
+ vt->set(v1);
+ ids_to_process.push_back(v1);
+ }
+ }
+
+ if (!ids_to_process.empty()) {
+ std::vector<float> batch_distances;
+ qdis.distances_batch(ids_to_process, batch_distances);
+
+ for (size_t i = 0; i < ids_to_process.size(); i++) {
+ add_to_heap(ids_to_process[i], batch_distances[i]);
+ }
+
+ ndis += ids_to_process.size();
+ }
+
+ stats.nhops += 1;
+ }
+
+ ++stats.n1;
+ if (candidates.size() == 0) {
+ ++stats.n2;
+ }
+ stats.ndis += ndis;
+
+ return top_candidates;
+}
+
+/// greedily update a nearest vector at a given level
+HNSWStats greedy_update_nearest(
+ const HNSW& hnsw,
+ DistanceComputer& qdis,
+ int level,
+ storage_idx_t& nearest,
+ float& d_nearest) {
+ HNSWStats stats;
+
+ // printf("greedy_update_nearest level: %d\n", level);
+ int level_neighbors = 0;
+
+ size_t max_degree_at_level = hnsw.nb_neighbors(level);
+ std::vector<HNSW::storage_idx_t> neighbor_read_buffer(max_degree_at_level);
+ for (;;) {
+ storage_idx_t prev_nearest = nearest;
+
+ size_t ndis = 0;
+ ssize_t neighbors_read_count =
+ hnsw.fetch_neighbors(nearest, level, neighbor_read_buffer);
+ stats.n_ios++;
+
+ std::vector<idx_t> neighbors_to_process(neighbors_read_count);
+ size_t valid_neighbor_count = 0;
+ for (ssize_t i = 0; i < neighbors_read_count; ++i) {
+ storage_idx_t v_storage = neighbor_read_buffer[i];
+ assert(v_storage >= 0 && v_storage < hnsw.levels.size());
+ neighbors_to_process[valid_neighbor_count++] =
+ static_cast<idx_t>(v_storage);
+ }
+ neighbors_to_process.resize(valid_neighbor_count);
+
+ std::vector<float> batch_distances(valid_neighbor_count);
+ qdis.distances_batch(neighbors_to_process, batch_distances);
+ stats.ndis += valid_neighbor_count;
+
+ for (size_t i = 0; i < valid_neighbor_count; ++i) {
+ idx_t neighbor_id = neighbors_to_process[i];
+ float neighbor_dist = batch_distances[i];
+
+ if (neighbor_dist < d_nearest) {
+ d_nearest = neighbor_dist;
+ nearest = static_cast<storage_idx_t>(neighbor_id);
+ }
+ }
+
+ stats.nhops++;
+
+ if (nearest == prev_nearest) {
+ return stats;
+ }
+ }
+}
+
+namespace {
+using MinimaxHeap = HNSW::MinimaxHeap;
+using Node = HNSW::Node;
+using C = HNSW::C;
+
+// just used as a lower bound for the minmaxheap, but it is set for heap search
+int extract_k_from_ResultHandler(ResultHandler<C>& res) {
+ using RH = HeapBlockResultHandler<C>;
+ if (auto hres = dynamic_cast<RH::SingleResultHandler*>(&res)) {
+ return hres->k;
+ }
+ return 1;
+}
+
+} // namespace
+
+HNSWStats HNSW::search(
+ DistanceComputer& qdis,
+ ResultHandler<C>& res,
+ VisitedTable& vt,
+ const SearchParameters* params,
+ const IndexHNSW* hnsw_index) const {
+ HNSWStats stats;
+ if (entry_point == -1) {
+ return stats;
+ }
+ int k = extract_k_from_ResultHandler(res);
+
+ bool bounded_queue = this->search_bounded_queue;
+ int efSearch = this->efSearch;
+ if (params) {
+ if (const SearchParametersHNSW* hnsw_params =
+ dynamic_cast<const SearchParametersHNSW*>(params)) {
+ bounded_queue = hnsw_params->bounded_queue;
+ efSearch = hnsw_params->efSearch;
+ }
+ }
+
+ // greedy search on upper levels
+ storage_idx_t nearest = entry_point;
+ float d_nearest = qdis(nearest);
+
+ // printf("max_level: %d\n", max_level);
+ for (int level = max_level; level >= 1; level--) {
+ HNSWStats local_stats =
+ greedy_update_nearest(*this, qdis, level, nearest, d_nearest);
+ stats.combine(local_stats);
+ }
+ if (hnsw_index) {
+ // printf("initial fetch count: %ld\n", qdis.get_fetch_count());
+ }
+
+ int ef = std::max(efSearch, k);
+ if (bounded_queue) { // this is the most common branch
+ MinimaxHeap candidates(ef);
+
+ candidates.push(nearest, d_nearest);
+
+ search_from_candidates(
+ *this,
+ qdis,
+ res,
+ candidates,
+ vt,
+ stats,
+ 0,
+ 0,
+ params,
+ hnsw_index);
+ } else {
+ std::priority_queue<Node> top_candidates =
+ search_from_candidate_unbounded(
+ *this, Node(d_nearest, nearest), qdis, ef, &vt, stats);
+
+ while (top_candidates.size() > k) {
+ top_candidates.pop();
+ }
+
+ while (!top_candidates.empty()) {
+ float d;
+ storage_idx_t label;
+ std::tie(d, label) = top_candidates.top();
+ res.add_result(d, label);
+ top_candidates.pop();
+ }
+ }
+
+ vt.advance();
+
+ return stats;
+}
+
+void HNSW::search_level_0(
+ DistanceComputer& qdis,
+ ResultHandler<C>& res,
+ idx_t nprobe,
+ const storage_idx_t* nearest_i,
+ const float* nearest_d,
+ int search_type,
+ HNSWStats& search_stats,
+ VisitedTable& vt,
+ const SearchParameters* params) const {
+ const HNSW& hnsw = *this;
+
+ auto efSearch = hnsw.efSearch;
+ if (params) {
+ if (const SearchParametersHNSW* hnsw_params =
+ dynamic_cast<const SearchParametersHNSW*>(params)) {
+ efSearch = hnsw_params->efSearch;
+ }
+ }
+
+ int k = extract_k_from_ResultHandler(res);
+
+ if (search_type == 1) {
+ int nres = 0;
+
+ for (int j = 0; j < nprobe; j++) {
+ storage_idx_t cj = nearest_i[j];
+
+ if (cj < 0)
+ break;
+
+ if (vt.get(cj))
+ continue;
+
+ int candidates_size = std::max(efSearch, k);
+ MinimaxHeap candidates(candidates_size);
+
+ candidates.push(cj, nearest_d[j]);
+
+ nres = search_from_candidates(
+ hnsw,
+ qdis,
+ res,
+ candidates,
+ vt,
+ search_stats,
+ 0,
+ nres,
+ params);
+ nres = std::min(nres, candidates_size);
+ }
+ } else if (search_type == 2) {
+ int candidates_size = std::max(efSearch, int(k));
+ candidates_size = std::max(candidates_size, int(nprobe));
+
+ MinimaxHeap candidates(candidates_size);
+ for (int j = 0; j < nprobe; j++) {
+ storage_idx_t cj = nearest_i[j];
+
+ if (cj < 0)
+ break;
+ candidates.push(cj, nearest_d[j]);
+ }
+
+ search_from_candidates(
+ hnsw, qdis, res, candidates, vt, search_stats, 0, 0, params);
+ }
+}
+
+void HNSW::permute_entries(const idx_t* map) {
+ // remap levels
+ storage_idx_t ntotal = levels.size();
+ std::vector<storage_idx_t> imap(ntotal); // inverse mapping
+ // map: new index -> old index
+ // imap: old index -> new index
+ for (int i = 0; i < ntotal; i++) {
+ assert(map[i] >= 0 && map[i] < ntotal);
+ imap[map[i]] = i;
+ }
+ if (entry_point != -1) {
+ entry_point = imap[entry_point];
+ }
+ std::vector<int> new_levels(ntotal);
+ std::vector<size_t> new_offsets(ntotal + 1);
+ std::vector<storage_idx_t> new_neighbors(neighbors.size());
+ size_t no = 0;
+ for (int i = 0; i < ntotal; i++) {
+ storage_idx_t o = map[i]; // corresponding "old" index
+ new_levels[i] = levels[o];
+ for (size_t j = offsets[o]; j < offsets[o + 1]; j++) {
+ storage_idx_t neigh = neighbors[j];
+ new_neighbors[no++] = neigh >= 0 ? imap[neigh] : neigh;
+ }
+ new_offsets[i + 1] = no;
+ }
+ assert(new_offsets[ntotal] == offsets[ntotal]);
+ // swap everyone
+ std::swap(levels, new_levels);
+ std::swap(offsets, new_offsets);
+ neighbors = std::move(new_neighbors);
+}
+
+/**************************************************************
+ * MinimaxHeap
+ **************************************************************/
+
+void HNSW::MinimaxHeap::push(storage_idx_t i, float v) {
+ if (k == n) {
+ if (v >= dis[0])
+ return;
+ if (ids[0] != -1) {
+ --nvalid;
+ }
+ faiss::heap_pop<HC>(k--, dis.data(), ids.data());
+ }
+ faiss::heap_push<HC>(++k, dis.data(), ids.data(), v, i);
+ ++nvalid;
+}
+
+float HNSW::MinimaxHeap::max() const {
+ return dis[0];
+}
+
+int HNSW::MinimaxHeap::size() const {
+ return nvalid;
+}
+
+void HNSW::MinimaxHeap::clear() {
+ nvalid = k = 0;
+}
+
+#ifdef __AVX512F__
+
+int HNSW::MinimaxHeap::pop_min(float* vmin_out) {
+ assert(k > 0);
+ static_assert(
+ std::is_same<storage_idx_t, int32_t>::value,
+ "This code expects storage_idx_t to be int32_t");
+
+ int32_t min_idx = -1;
+ float min_dis = std::numeric_limits<float>::infinity();
+
+ __m512i min_indices = _mm512_set1_epi32(-1);
+ __m512 min_distances =
+ _mm512_set1_ps(std::numeric_limits<float>::infinity());
+ __m512i current_indices = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ __m512i offset = _mm512_set1_epi32(16);
+
+ // The following loop tracks the rightmost index with the min distance.
+ // -1 index values are ignored.
+ const int k16 = (k / 16) * 16;
+ for (size_t iii = 0; iii < k16; iii += 16) {
+ __m512i indices =
+ _mm512_loadu_si512((const __m512i*)(ids.data() + iii));
+ __m512 distances = _mm512_loadu_ps(dis.data() + iii);
+
+ // This mask filters out -1 values among indices.
+ __mmask16 m1mask =
+ _mm512_cmpgt_epi32_mask(_mm512_setzero_si512(), indices);
+
+ __mmask16 dmask =
+ _mm512_cmp_ps_mask(min_distances, distances, _CMP_LT_OS);
+ __mmask16 finalmask = m1mask | dmask;
+
+ const __m512i min_indices_new = _mm512_mask_blend_epi32(
+ finalmask, current_indices, min_indices);
+ const __m512 min_distances_new =
+ _mm512_mask_blend_ps(finalmask, distances, min_distances);
+
+ min_indices = min_indices_new;
+ min_distances = min_distances_new;
+
+ current_indices = _mm512_add_epi32(current_indices, offset);
+ }
+
+ // leftovers
+ if (k16 != k) {
+ const __mmask16 kmask = (1 << (k - k16)) - 1;
+
+ __m512i indices = _mm512_mask_loadu_epi32(
+ _mm512_set1_epi32(-1), kmask, ids.data() + k16);
+ __m512 distances = _mm512_maskz_loadu_ps(kmask, dis.data() + k16);
+
+ // This mask filters out -1 values among indices.
+ __mmask16 m1mask =
+ _mm512_cmpgt_epi32_mask(_mm512_setzero_si512(), indices);
+
+ __mmask16 dmask =
+ _mm512_cmp_ps_mask(min_distances, distances, _CMP_LT_OS);
+ __mmask16 finalmask = m1mask | dmask;
+
+ const __m512i min_indices_new = _mm512_mask_blend_epi32(
+ finalmask, current_indices, min_indices);
+ const __m512 min_distances_new =
+ _mm512_mask_blend_ps(finalmask, distances, min_distances);
+
+ min_indices = min_indices_new;
+ min_distances = min_distances_new;
+ }
+
+ // grab min distance
+ min_dis = _mm512_reduce_min_ps(min_distances);
+ // blend
+ __mmask16 mindmask =
+ _mm512_cmpeq_ps_mask(min_distances, _mm512_set1_ps(min_dis));
+ // pick the max one
+ min_idx = _mm512_mask_reduce_max_epi32(mindmask, min_indices);
+
+ if (min_idx == -1) {
+ return -1;
+ }
+
+ if (vmin_out) {
+ *vmin_out = min_dis;
+ }
+ int ret = ids[min_idx];
+ ids[min_idx] = -1;
+ --nvalid;
+ return ret;
+}
+
+#elif __AVX2__
+
+int HNSW::MinimaxHeap::pop_min(float* vmin_out) {
+ assert(k > 0);
+ static_assert(
+ std::is_same<storage_idx_t, int32_t>::value,
+ "This code expects storage_idx_t to be int32_t");
+
+ int32_t min_idx = -1;
+ float min_dis = std::numeric_limits<float>::infinity();
+
+ size_t iii = 0;
+
+ __m256i min_indices = _mm256_setr_epi32(-1, -1, -1, -1, -1, -1, -1, -1);
+ __m256 min_distances =
+ _mm256_set1_ps(std::numeric_limits<float>::infinity());
+ __m256i current_indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ __m256i offset = _mm256_set1_epi32(8);
+
+ // The baseline version is available in non-AVX2 branch.
+
+ // The following loop tracks the rightmost index with the min distance.
+ // -1 index values are ignored.
+ const int k8 = (k / 8) * 8;
+ for (; iii < k8; iii += 8) {
+ __m256i indices =
+ _mm256_loadu_si256((const __m256i*)(ids.data() + iii));
+ __m256 distances = _mm256_loadu_ps(dis.data() + iii);
+
+ // This mask filters out -1 values among indices.
+ __m256i m1mask = _mm256_cmpgt_epi32(_mm256_setzero_si256(), indices);
+
+ __m256i dmask = _mm256_castps_si256(
+ _mm256_cmp_ps(min_distances, distances, _CMP_LT_OS));
+ __m256 finalmask = _mm256_castsi256_ps(_mm256_or_si256(m1mask, dmask));
+
+ const __m256i min_indices_new = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ finalmask));
+
+ const __m256 min_distances_new =
+ _mm256_blendv_ps(distances, min_distances, finalmask);
+
+ min_indices = min_indices_new;
+ min_distances = min_distances_new;
+
+ current_indices = _mm256_add_epi32(current_indices, offset);
+ }
+
+ // Vectorizing is doable, but is not practical
+ int32_t vidx8[8];
+ float vdis8[8];
+ _mm256_storeu_ps(vdis8, min_distances);
+ _mm256_storeu_si256((__m256i*)vidx8, min_indices);
+
+ for (size_t j = 0; j < 8; j++) {
+ if (min_dis > vdis8[j] || (min_dis == vdis8[j] && min_idx < vidx8[j])) {
+ min_idx = vidx8[j];
+ min_dis = vdis8[j];
+ }
+ }
+
+ // process last values. Vectorizing is doable, but is not practical
+ for (; iii < k; iii++) {
+ if (ids[iii] != -1 && dis[iii] <= min_dis) {
+ min_dis = dis[iii];
+ min_idx = iii;
+ }
+ }
+
+ if (min_idx == -1) {
+ return -1;
+ }
+
+ if (vmin_out) {
+ *vmin_out = min_dis;
+ }
+ int ret = ids[min_idx];
+ ids[min_idx] = -1;
+ --nvalid;
+ return ret;
+}
+
+#else
+
+// baseline non-vectorized version
+int HNSW::MinimaxHeap::pop_min(float* vmin_out) {
+ assert(k > 0);
+ // returns min. This is an O(n) operation
+ int i = k - 1;
+ while (i >= 0) {
+ if (ids[i] != -1) {
+ break;
+ }
+ i--;
+ }
+ if (i == -1) {
+ return -1;
+ }
+ int imin = i;
+ float vmin = dis[i];
+ i--;
+ while (i >= 0) {
+ if (ids[i] != -1 && dis[i] < vmin) {
+ vmin = dis[i];
+ imin = i;
+ }
+ i--;
+ }
+ if (vmin_out) {
+ *vmin_out = vmin;
+ }
+ int ret = ids[imin];
+ ids[imin] = -1;
+ --nvalid;
+
+ return ret;
+}
+#endif
+
+int HNSW::MinimaxHeap::count_below(float thresh) {
+ int n_below = 0;
+ for (int i = 0; i < k; i++) {
+ if (dis[i] < thresh) {
+ n_below++;
+ }
+ }
+
+ return n_below;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW.h
new file mode 100644
index 0000000..bd51f23
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW.h
@@ -0,0 +1,499 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <memory>
+#include <queue>
+#include <unordered_map>
+#include <unordered_set>
+#include <vector>
+
+#include <omp.h>
+
+#include <faiss/Index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/io.h>
+#include <faiss/impl/maybe_owned_vector.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/random.h>
+#include <unistd.h>
+
+#include "pq.h"
+
+namespace faiss {
+
+/** Implementation of the Hierarchical Navigable Small World
+ * datastructure.
+ *
+ * Efficient and robust approximate nearest neighbor search using
+ * Hierarchical Navigable Small World graphs
+ *
+ * Yu. A. Malkov, D. A. Yashunin, arXiv 2017
+ *
+ * This implementation is heavily influenced by the NMSlib
+ * implementation by Yury Malkov and Leonid Boystov
+ * (https://github.com/searchivarius/nmslib)
+ *
+ * The HNSW object stores only the neighbor link structure, see
+ * IndexHNSW.h for the full index object.
+ */
+
+struct VisitedTable;
+struct DistanceComputer; // from AuxIndexStructures
+struct HNSWStats;
+template <class C>
+struct ResultHandler;
+
+struct SearchParametersHNSW : SearchParameters {
+ int efSearch = 16;
+ bool check_relative_distance = true;
+ bool bounded_queue = true;
+
+ // Batch processing and beam size
+ int beam_size = 1; // Beam size for beam search (1 = original)
+ int batch_size = 0; // Batch size for neighbor processing (0 = no batching)
+
+ // PQ-instructed pruning
+ float pq_pruning_ratio = 0; // Ratio of candidates to select via PQ
+
+ bool local_prune = false;
+ float send_neigh_times_ratio = 0;
+
+ int zmq_port = 5557;
+ // bool cache_distances = false;
+
+ ~SearchParametersHNSW() {}
+};
+
+class IndexHNSW;
+struct HNSW {
+ /// internal storage of vectors (32 bits: this is expensive)
+ using storage_idx_t = int32_t;
+
+ struct Level0EdgeLocation {
+ storage_idx_t node_id;
+ size_t neighbor_array_index; // Index in the flat neighbors array
+
+ Level0EdgeLocation(int n, size_t idx)
+ : node_id(n), neighbor_array_index(idx) {}
+ };
+
+ // Add a struct to store percentile-to-distance mapping
+ struct PercentileThreshold {
+ float percentile; // Percentile value (e.g., 0.5, 1.0, etc.)
+ float threshold; // Distance threshold at this percentile
+
+ PercentileThreshold(float p, float t) : percentile(p), threshold(t) {}
+ };
+
+ // Store the percentile thresholds
+ std::vector<PercentileThreshold> percentile_thresholds;
+
+ // Method to set the percentile thresholds with predefined values
+ void set_percentile_thresholds() {
+ percentile_thresholds.clear();
+ // Add the predefined percentile-threshold pairs
+ percentile_thresholds.emplace_back(0.5f, -2.801647f);
+ percentile_thresholds.emplace_back(1.0f, -2.708753f);
+ percentile_thresholds.emplace_back(2.0f, -2.625265f);
+ percentile_thresholds.emplace_back(3.0f, -2.576904f);
+ percentile_thresholds.emplace_back(5.0f, -2.515250f);
+ percentile_thresholds.emplace_back(8.0f, -2.451823f);
+ percentile_thresholds.emplace_back(10.0f, -2.417586f);
+ percentile_thresholds.emplace_back(15.0f, -2.345697f);
+ percentile_thresholds.emplace_back(20.0f, -2.287264f);
+ percentile_thresholds.emplace_back(30.0f, -2.191441f);
+ percentile_thresholds.emplace_back(40.0f, -2.104487f);
+ percentile_thresholds.emplace_back(50.0f, -2.012791f);
+ percentile_thresholds.emplace_back(60.0f, -1.909652f);
+ percentile_thresholds.emplace_back(70.0f, -1.803186f);
+ }
+
+ // Method to get the threshold for a specific percentile
+ float get_threshold_for_percentile(float percentile) const {
+ for (const auto& pt : percentile_thresholds) {
+ if (std::abs(pt.percentile - percentile) < 0.001f) {
+ return pt.threshold;
+ }
+ }
+ return 0.0f; // Default if not found
+ }
+
+ void delete_random_level0_edges_minimal(float prune_ratio = 0.5);
+ void merge_nodes(float merge_threshold);
+ // void save_edge_stats(const char* filename) ;
+
+ // for now we do only these distances
+ using C = CMax<float, int64_t>;
+
+ typedef std::pair<float, storage_idx_t> Node;
+
+ /** Heap structure that allows fast
+ */
+ struct MinimaxHeap {
+ int n;
+ int k;
+ int nvalid;
+
+ std::vector<storage_idx_t> ids;
+ std::vector<float> dis;
+ typedef faiss::CMax<float, storage_idx_t> HC;
+
+ explicit MinimaxHeap(int n) : n(n), k(0), nvalid(0), ids(n), dis(n) {}
+
+ void push(storage_idx_t i, float v);
+
+ float max() const;
+
+ int size() const;
+
+ void clear();
+
+ int pop_min(float* vmin_out = nullptr);
+
+ int count_below(float thresh);
+ };
+
+ /// to sort pairs of (id, distance) from nearest to fathest or the reverse
+ struct NodeDistCloser {
+ float d;
+ int id;
+ NodeDistCloser(float d, int id) : d(d), id(id) {}
+ bool operator<(const NodeDistCloser& obj1) const {
+ return d < obj1.d;
+ }
+ };
+
+ struct NodeDistFarther {
+ float d;
+ int id;
+ NodeDistFarther(float d, int id) : d(d), id(id) {}
+ bool operator<(const NodeDistFarther& obj1) const {
+ return d > obj1.d;
+ }
+ };
+
+ /// assignment probability to each layer (sum=1)
+ std::vector<double> assign_probas;
+
+ /// number of neighbors stored per layer (cumulative), should not
+ /// be changed after first add
+ std::vector<int> cum_nneighbor_per_level;
+
+ /// level of each vector (base level = 1), size = ntotal
+ std::vector<int> levels;
+
+ /// offsets[i] is the offset in the neighbors array where vector i is stored
+ /// size ntotal + 1
+ std::vector<size_t> offsets;
+
+ /// neighbors[offsets[i]:offsets[i+1]] is the list of neighbors of vector i
+ /// for all levels. this is where all storage goes.
+ MaybeOwnedVector<storage_idx_t> neighbors;
+
+ // --- Compact CSR Storage (New) ---
+ bool storage_is_compact = false; // Flag read from file
+ MaybeOwnedVector<storage_idx_t> compact_neighbors_data; // CSR data
+ MaybeOwnedVector<size_t> compact_level_ptr; // CSR indptr part 1
+ MaybeOwnedVector<size_t> compact_node_offsets; // CSR indptr part 2
+
+ /// entry point in the search structure (one of the points with maximum
+ /// level
+ storage_idx_t entry_point = -1;
+
+ faiss::RandomGenerator rng;
+
+ /// maximum level
+ int max_level = -1;
+
+ /// expansion factor at construction time
+ int efConstruction = 40;
+
+ /// expansion factor at search time
+ int efSearch = 16;
+
+ bool neighbors_on_disk = false;
+ std::string hnsw_index_filename; // Used for pread
+ int graph_fd = -1; // File descriptor for pread
+
+ // --- New members for disk/mmap access ---
+ off_t neighbors_start_offset = -1; // For pread: offset to size field; For
+ // mmap: relative offset (debug)
+ storage_idx_t* neighbors_mmap_ptr =
+ nullptr; // For mmap: pointer to neighbor data in memory
+ bool neighbors_use_mmap =
+ false; // Whether to use mmap pointer instead of pread
+
+ /// during search: do we check whether the next best distance is good
+ /// enough?
+ bool check_relative_distance = true;
+
+ /// use bounded queue during exploration
+ bool search_bounded_queue = true;
+
+ // methods that initialize the tree sizes
+
+ /// initialize the assign_probas and cum_nneighbor_per_level to
+ /// have 2*M links on level 0 and M links on levels > 0
+ void set_default_probas(int M, float levelMult, int M0 = -1);
+
+ /// set nb of neighbors for this level (before adding anything)
+ void set_nb_neighbors(int level_no, int n);
+
+ // methods that access the tree sizes
+
+ /// nb of neighbors for this level
+ int nb_neighbors(int layer_no) const;
+
+ /// cumumlative nb up to (and excluding) this level
+ int cum_nb_neighbors(int layer_no) const;
+
+ /// range of entries in the neighbors table of vertex no at layer_no
+ void neighbor_range(idx_t no, int layer_no, size_t* begin, size_t* end)
+ const;
+
+ /// only mandatory parameter: nb of neighbors
+ explicit HNSW(int M = 32, int M0 = -1);
+
+ /// pick a random level for a new point
+ int random_level();
+
+ /// add n random levels to table (for debugging...)
+ void fill_with_random_links(size_t n);
+
+ void add_links_starting_from(
+ DistanceComputer& ptdis,
+ storage_idx_t pt_id,
+ storage_idx_t nearest,
+ float d_nearest,
+ int level,
+ omp_lock_t* locks,
+ VisitedTable& vt,
+ bool keep_max_size_level0 = false);
+
+ /** add point pt_id on all levels <= pt_level and build the link
+ * structure for them. */
+ void add_with_locks(
+ DistanceComputer& ptdis,
+ int pt_level,
+ int pt_id,
+ std::vector<omp_lock_t>& locks,
+ VisitedTable& vt,
+ bool keep_max_size_level0 = false);
+
+ /// search interface for 1 point, single thread
+ HNSWStats search(
+ DistanceComputer& qdis,
+ ResultHandler<C>& res,
+ VisitedTable& vt,
+ const SearchParameters* params = nullptr,
+ const IndexHNSW* hnsw = nullptr) const;
+
+ /// search only in level 0 from a given vertex
+ void search_level_0(
+ DistanceComputer& qdis,
+ ResultHandler<C>& res,
+ idx_t nprobe,
+ const storage_idx_t* nearest_i,
+ const float* nearest_d,
+ int search_type,
+ HNSWStats& search_stats,
+ VisitedTable& vt,
+ const SearchParameters* params = nullptr) const;
+
+ void reset();
+
+ void clear_neighbor_tables(int level);
+ void print_neighbor_stats(int level) const;
+
+ int prepare_level_tab(size_t n, bool preset_levels = false);
+
+ static void shrink_neighbor_list(
+ DistanceComputer& qdis,
+ std::priority_queue<NodeDistFarther>& input,
+ std::vector<NodeDistFarther>& output,
+ int max_size,
+ bool keep_max_size_level0 = false);
+
+ void permute_entries(const idx_t* map);
+
+ void save_degree_distribution(int level, const char* filename) const;
+
+ float pq_pruning_ratio = 0;
+
+ std::shared_ptr<PQPrunerDataLoader> pq_data_loader;
+ std::vector<uint8_t> pq_codes; // PQ codes of all vectors (N * code_size)
+ size_t code_size = 0; // number of chunks per vector
+
+ bool load_pq_pruning_data(
+ const std::string& pq_pivots_path,
+ const std::string& pq_compressed_path);
+
+ bool pq_loaded = false;
+
+ // On-demand neighbor fetch method
+ size_t fetch_neighbors(
+ idx_t node_id,
+ int level,
+ std::vector<storage_idx_t>& buffer) const;
+
+ void initialize_graph(const std::string& index_filename);
+
+ ~HNSW(); // Close file descriptor
+ std::vector<int> ems;
+};
+
+struct HNSWStats {
+ size_t n1 = 0; /// number of vectors searched
+ size_t n2 =
+ 0; /// number of queries for which the candidate list is exhausted
+ size_t ndis = 0; /// number of distances computed
+ size_t nhops = 0; /// number of hops aka number of edges traversed
+ size_t npq = 0; /// number of PQ candidates
+ size_t nfetch = 0; /// number of neighbors fetched
+ size_t n_ios = 0; /// number of neighbors fetched on demand
+ size_t n_pq_calcs = 0;
+
+ // Track visited node counts
+ std::unordered_map<idx_t, size_t> node_visit_counts;
+
+ void reset() {
+ n1 = n2 = 0;
+ ndis = 0;
+ nhops = 0;
+ npq = 0;
+ nfetch = 0;
+ n_ios = 0;
+ n_pq_calcs = 0;
+ // printf("Resetting node visit counts\n");
+ // printf("Original size: %zu\n", node_visit_counts.size());
+ node_visit_counts.clear();
+ }
+
+ void combine(const HNSWStats& other) {
+ n1 += other.n1;
+ n2 += other.n2;
+ ndis += other.ndis;
+ nhops += other.nhops;
+ npq += other.npq;
+ nfetch += other.nfetch;
+ n_ios += other.n_ios;
+ n_pq_calcs += other.n_pq_calcs;
+
+ // Combine node visit counts
+ // printf("Two sizes: %zu, %zu\n",
+ // node_visit_counts.size(),
+ // other.node_visit_counts.size());
+ for (const auto& [node_id, count] : other.node_visit_counts) {
+ node_visit_counts[node_id] += count;
+ }
+ }
+
+ // Dump node visit frequency distribution to a file
+ void dump_node_visit_stats(const char* filename) const {
+ FILE* f = fopen(filename, "w");
+ if (!f) {
+ fprintf(stderr,
+ "Could not open %s for writing: %s\n",
+ filename,
+ strerror(errno));
+ return;
+ }
+
+ fprintf(f, "node_id,visit_count\n");
+ for (const auto& [node_id, count] : node_visit_counts) {
+ fprintf(f, "%ld,%ld\n", (long)node_id, (long)count);
+ }
+
+ fclose(f);
+ }
+
+ // Dump distribution of visit frequencies (how many nodes were visited X
+ // times)
+ void dump_visit_frequency_distribution(const char* filename) const {
+ std::unordered_map<size_t, size_t> frequency_counts;
+
+ // Count how many nodes had each visit count
+ for (const auto& [node_id, visits] : node_visit_counts) {
+ frequency_counts[visits]++;
+ }
+
+ // Write to file
+ FILE* f = fopen(filename, "w");
+ if (!f) {
+ fprintf(stderr,
+ "Could not open %s for writing: %s\n",
+ filename,
+ strerror(errno));
+ return;
+ }
+
+ fprintf(f, "visit_frequency,node_count,percentage\n");
+
+ // Sort by visit frequency for better readability
+ std::vector<std::pair<size_t, size_t>> sorted_counts(
+ frequency_counts.begin(), frequency_counts.end());
+ std::sort(sorted_counts.begin(), sorted_counts.end());
+
+ size_t total_nodes = node_visit_counts.size();
+ for (const auto& [visits, count] : sorted_counts) {
+ double percentage = (100.0 * count) / total_nodes;
+ fprintf(f,
+ "%ld,%ld,%.4f%%\n",
+ (long)visits,
+ (long)count,
+ percentage);
+ }
+
+ fclose(f);
+ }
+};
+
+// global var that collects them all
+FAISS_API extern HNSWStats hnsw_stats;
+
+int search_from_candidates(
+ const HNSW& hnsw,
+ DistanceComputer& qdis,
+ ResultHandler<HNSW::C>& res,
+ HNSW::MinimaxHeap& candidates,
+ VisitedTable& vt,
+ HNSWStats& stats,
+ int level,
+ int nres_in = 0,
+ const SearchParameters* params = nullptr,
+ const IndexHNSW* hnsw_index = nullptr);
+
+HNSWStats greedy_update_nearest(
+ const HNSW& hnsw,
+ DistanceComputer& qdis,
+ int level,
+ HNSW::storage_idx_t& nearest,
+ float& d_nearest);
+
+std::priority_queue<HNSW::Node> search_from_candidate_unbounded(
+ const HNSW& hnsw,
+ const HNSW::Node& node,
+ DistanceComputer& qdis,
+ int ef,
+ VisitedTable* vt,
+ HNSWStats& stats);
+
+void search_neighbors_to_add(
+ HNSW& hnsw,
+ DistanceComputer& qdis,
+ std::priority_queue<HNSW::NodeDistCloser>& results,
+ int entry_point,
+ float d_entry_point,
+ int level,
+ VisitedTable& vt,
+ bool reference_version = false);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_search.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_search.cpp
new file mode 100644
index 0000000..89f8ff9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_search.cpp
@@ -0,0 +1,851 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/HNSW.h>
+
+#include <cstddef>
+#include "faiss/IndexHNSW.h"
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/prefetch.h>
+#include "HNSW_zmq.h"
+
+#include <faiss/impl/platform_macros.h>
+
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/stat.h> // For file size check
+#include <unistd.h>
+#include <algorithm>
+#include <cerrno>
+#include <cmath>
+#include <cstring>
+#include <iostream>
+#include <map>
+#include <set>
+#include "faiss/impl/FaissAssert.h"
+#include "faiss/impl/pq.h"
+
+namespace faiss {
+
+ssize_t read_direct_and_extract(
+ int fd,
+ void* user_buffer,
+ size_t desired_bytes,
+ off_t desired_offset) {
+ struct stat stat_buf;
+
+ // Get block size for alignment
+ if (fstat(fd, &stat_buf) != 0) {
+ return -1; // errno is set by fstat
+ }
+
+ size_t block_size = stat_buf.st_blksize;
+
+ // Calculate aligned offsets
+ off_t aligned_start_offset = (desired_offset / block_size) * block_size;
+ off_t aligned_end_offset =
+ std::ceil((desired_offset + desired_bytes) / (double)block_size) *
+ block_size;
+ size_t bytes_to_read_aligned = aligned_end_offset - aligned_start_offset;
+
+ // Allocate aligned buffer
+ void* temp_buffer = nullptr;
+ if (posix_memalign(&temp_buffer, block_size, bytes_to_read_aligned) != 0) {
+ errno = ENOMEM;
+ return -1;
+ }
+
+ // Seek to the aligned offset
+ if (lseek(fd, aligned_start_offset, SEEK_SET) == -1) {
+ int saved_errno = errno;
+ free(temp_buffer);
+ errno = saved_errno;
+ return -1;
+ }
+
+ // Read aligned data
+ ssize_t actual_bytes_read = read(fd, temp_buffer, bytes_to_read_aligned);
+
+ if (actual_bytes_read < 0) {
+ int saved_errno = errno;
+ free(temp_buffer);
+ errno = saved_errno;
+ return -1;
+ }
+
+ if (actual_bytes_read == 0 && desired_bytes > 0) {
+ // End of file
+ free(temp_buffer);
+ return 0;
+ }
+
+ // Calculate internal offset and bytes to copy
+ size_t internal_offset = desired_offset - aligned_start_offset;
+ size_t bytes_to_copy = std::min(
+ desired_bytes,
+ (size_t)actual_bytes_read > internal_offset
+ ? (size_t)actual_bytes_read - internal_offset
+ : 0);
+
+ // Copy the requested portion to user buffer
+ memcpy(user_buffer, (char*)temp_buffer + internal_offset, bytes_to_copy);
+
+ // Free the temporary buffer
+ free(temp_buffer);
+
+ return bytes_to_copy;
+}
+
+HNSW::~HNSW() {
+ // Close file descriptor
+ if (graph_fd != -1) {
+ close(graph_fd);
+ }
+}
+
+void HNSW::initialize_graph(const std::string& index_filename) {
+ assert(neighbors_on_disk);
+ this->hnsw_index_filename = index_filename;
+ if (this->graph_fd != -1) {
+ close(this->graph_fd);
+ }
+#ifdef __linux__
+ this->graph_fd = open(
+ this->hnsw_index_filename.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECT);
+#else
+ this->graph_fd =
+ open(this->hnsw_index_filename.c_str(), O_RDONLY | O_CLOEXEC);
+#endif
+
+ if (this->graph_fd == -1) {
+ int RTERRNO = errno;
+ FAISS_THROW_FMT(
+ "Failed to open HNSW index file '%s' for pread during initialization. errno=%d (%s)",
+ this->hnsw_index_filename.c_str(),
+ RTERRNO,
+ strerror(RTERRNO));
+ }
+ printf("[InitOnDemand] Opened HNSW index file descriptor: %d\n",
+ this->graph_fd);
+}
+
+size_t HNSW::fetch_neighbors(
+ idx_t node_id,
+ int level,
+ std::vector<storage_idx_t>& buffer) const {
+ // Basic bounds check for node_id and level
+ FAISS_THROW_IF_NOT_FMT(
+ node_id >= 0 && (size_t)node_id < levels.size(),
+ "fetch_neighbors: node_id %ld out of range [0, %zu)",
+ (long)node_id,
+ levels.size());
+ FAISS_THROW_IF_NOT_FMT(
+ level >= 0 && level <= max_level,
+ "fetch_neighbors: level %d out of range [0, %d]",
+ level,
+ max_level);
+
+ size_t begin_idx, end_idx;
+ neighbor_range(node_id, level, &begin_idx, &end_idx);
+ size_t num_neighbors = end_idx - begin_idx;
+ buffer.resize(num_neighbors);
+
+ if (num_neighbors == 0) {
+ return 0;
+ }
+
+ if (!neighbors_on_disk) {
+ // Case 1: Neighbors are in memory (either compact_neighbors_data or
+ // original neighbors)
+ if (!storage_is_compact) {
+ // Original storage format
+ size_t count = 0;
+ for (size_t j = begin_idx; j < end_idx; j++) {
+ if (neighbors[j] < 0)
+ break;
+ buffer[count++] = neighbors[j];
+ }
+ buffer.resize(count);
+ return count;
+ } else {
+ // Compact storage format with data in memory
+ memcpy(buffer.data(),
+ compact_neighbors_data.data() + begin_idx,
+ num_neighbors * sizeof(storage_idx_t));
+ return num_neighbors;
+ }
+ } else {
+ // Case 2: Neighbors are either on disk or in mmap region
+ FAISS_THROW_IF_NOT_MSG(
+ storage_is_compact,
+ "Disk/mmap neighbors access requires compact storage format");
+
+ if (neighbors_use_mmap) {
+ // Case 2a: Access via memory-mapped region
+ FAISS_THROW_IF_NOT_MSG(
+ neighbors_mmap_ptr != nullptr,
+ "neighbors_use_mmap is true but neighbors_mmap_ptr is null");
+
+ // Direct memory copy from mapped region
+ memcpy(buffer.data(),
+ neighbors_mmap_ptr + begin_idx,
+ num_neighbors * sizeof(storage_idx_t));
+
+ return num_neighbors;
+ } else {
+ // Case 2b: Access via pread from disk
+ FAISS_THROW_IF_NOT_MSG(
+ graph_fd != -1,
+ "Graph file descriptor is not valid (file not opened?)");
+ FAISS_THROW_IF_NOT_MSG(
+ neighbors_start_offset >= 0,
+ "Invalid neighbors_start_offset for pread");
+
+ // Calculate file offsets
+ // neighbors_start_offset points to the size field (uint64_t/size_t)
+ off_t desired_offset = neighbors_start_offset + sizeof(size_t) +
+ (off_t)(begin_idx * sizeof(storage_idx_t));
+ size_t desired_bytes = num_neighbors * sizeof(storage_idx_t);
+
+ // Note: When using this method in a multi-threaded context, access
+ // to graph_fd should be synchronized since lseek+read is not
+ // thread-safe on the same file descriptor.
+ ssize_t bytes_copied = read_direct_and_extract(
+ graph_fd, buffer.data(), desired_bytes, desired_offset);
+
+ // Check for errors
+ if (bytes_copied < 0) {
+ int RTERRNO = errno;
+ FAISS_THROW_FMT(
+ "read_direct_and_extract failed: node %ld, level %d, offset %ld. errno=%d (%s)",
+ (long)node_id,
+ level,
+ (long)desired_offset,
+ RTERRNO,
+ strerror(RTERRNO));
+ }
+
+ // Check if we got all the data we expected
+ if ((size_t)bytes_copied != desired_bytes) {
+ FAISS_THROW_FMT(
+ "Short copy from read_direct_and_extract: node %ld, level %d, offset %ld. Copied %zd bytes, expected %zu",
+ (long)node_id,
+ level,
+ (long)desired_offset,
+ bytes_copied,
+ desired_bytes);
+ }
+
+ return num_neighbors;
+ }
+ }
+}
+
+bool HNSW::load_pq_pruning_data(
+ const std::string& pq_pivots_path,
+ const std::string& pq_compressed_path) {
+ pq_data_loader = nullptr;
+
+ auto loader = std::make_shared<PQPrunerDataLoader>();
+
+ if (!loader->load_pq_pivots(pq_pivots_path)) {
+ std::cerr
+ << "Failed to load PQ pivots for pruning. PQ pruning disabled."
+ << std::endl;
+ return false;
+ }
+
+ uint8_t* loaded_codes_ptr = nullptr;
+ size_t num_vectors, codes_per_vector;
+ if (!load_simple_bin<uint8_t>(
+ pq_compressed_path,
+ loaded_codes_ptr,
+ num_vectors,
+ codes_per_vector)) {
+ std::cerr
+ << "Failed to load PQ compressed codes for pruning. PQ pruning disabled."
+ << std::endl;
+ return false;
+ }
+ if (codes_per_vector != loader->get_num_chunks()) {
+ std::cerr << "Error: Chunk count mismatch between pivots ("
+ << loader->get_num_chunks() << ") and compressed codes ("
+ << codes_per_vector << "). PQ pruning disabled." << std::endl;
+ delete[] loaded_codes_ptr;
+ return false;
+ }
+
+ code_size = codes_per_vector;
+ pq_codes.resize(num_vectors * code_size);
+ memcpy(pq_codes.data(), loaded_codes_ptr, num_vectors * code_size);
+ delete[] loaded_codes_ptr;
+
+ pq_data_loader = loader;
+ pq_loaded = true;
+ std::cout << "Successfully loaded data for PQ pruning: " << num_vectors
+ << " vectors, " << code_size << " bytes/vector." << std::endl;
+ return true;
+}
+
+void HNSW::neighbor_range(idx_t no, int layer_no, size_t* begin, size_t* end)
+ const {
+ if (storage_is_compact) {
+ // CSR Format Logic
+ // Basic bounds check for the node index itself
+ FAISS_THROW_IF_NOT_FMT(
+ no < compact_node_offsets.size() - 1,
+ "Node index %ld out of bounds for compact_node_offsets (size %zd)",
+ no,
+ compact_node_offsets.size());
+
+ size_t ptr_start = compact_node_offsets[no];
+ size_t ptr_end =
+ compact_node_offsets[no + 1]; // Exclusive end for level
+ // pointers of this node
+
+ // Calculate the number of levels stored for this node in the ptr array
+ // Each level needs two entries in level_ptr (start and end offset),
+ // so (ptr_end - ptr_start) gives num_levels + 1 entries.
+ int num_level_entries = ptr_end - ptr_start;
+ int num_levels_for_node =
+ (num_level_entries > 0) ? (num_level_entries - 1) : 0;
+
+ // Check if the requested layer exists for this node
+ if (layer_no < 0 || layer_no >= num_levels_for_node) {
+ // Layer does not exist for this node or invalid layer index
+ *begin = 0;
+ *end = 0; // Indicate empty range
+ } else {
+ // Valid layer, get data pointers from compact_level_ptr
+ size_t level_ptr_index_begin = ptr_start + layer_no;
+ size_t level_ptr_index_end = ptr_start + layer_no + 1;
+
+ // Bounds check for level_ptr access
+ FAISS_THROW_IF_NOT_FMT(
+ level_ptr_index_end < compact_level_ptr.size(),
+ "Level pointer index %zd out of bounds for compact_level_ptr (size %zd)",
+ level_ptr_index_end,
+ compact_level_ptr.size());
+
+ *begin = compact_level_ptr[level_ptr_index_begin];
+ *end = compact_level_ptr
+ [level_ptr_index_end]; // Exclusive end for neighbors at
+ // this level in
+ // compact_neighbors_data
+ }
+ } else {
+ // Original Format Logic
+ FAISS_THROW_IF_NOT_FMT(
+ no < offsets.size() - 1,
+ "Node index %ld out of bounds for offsets (size %zd)",
+ no,
+ offsets.size());
+ FAISS_THROW_IF_NOT_FMT(
+ layer_no + 1 < cum_nneighbor_per_level.size(),
+ "Layer index %d out of bounds for cum_nneighbor_per_level (size %zd)",
+ layer_no,
+ cum_nneighbor_per_level.size());
+
+ size_t o = offsets[no];
+ *begin = o + cum_nb_neighbors(layer_no);
+ *end = o + cum_nb_neighbors(layer_no + 1);
+ }
+}
+
+// Candidates: Main Candidate Heap, stored the accurate distance
+using MinimaxHeap = HNSW::MinimaxHeap;
+using Node = HNSW::Node;
+using C = HNSW::C;
+/** Do a BFS on the candidates list */
+int search_from_candidates(
+ const HNSW& hnsw,
+ DistanceComputer& qdis,
+ ResultHandler<C>& res,
+ MinimaxHeap& candidates,
+ VisitedTable& vt,
+ HNSWStats& stats,
+ int level,
+ int nres_in,
+ const SearchParameters* params,
+ const IndexHNSW* hnsw_index) {
+ FAISS_THROW_IF_NOT(level == 0);
+
+ fetch_disk_cache_counts = 0;
+
+ int nres = nres_in;
+ int ndis = 0;
+ int nfetch = 0;
+ int npq = 0;
+
+ int beam_size = 1; // Default beam width
+ int batch_size = 0;
+ bool use_batching = false; // Whether to use batching
+ // bool cache_distances = false;
+
+ // Original search settings
+ bool do_dis_check = hnsw.check_relative_distance;
+ int efSearch = hnsw.efSearch;
+ const IDSelector* sel = nullptr;
+
+ // PQ pruning setup
+ float pq_select_ratio = 1;
+ std::vector<float> pq_dists_lookup;
+ std::vector<float> query_preprocessed;
+ std::vector<uint8_t> pq_code_scratch;
+ std::vector<float> pq_dists_out;
+
+ std::vector<HNSW::storage_idx_t> neighbor_read_buffer; // For pread
+ size_t max_deg_l0 = hnsw.nb_neighbors(0);
+
+ bool local_prune = false;
+ float send_neigh_times_ratio = 0;
+
+ if (params) {
+ if (const SearchParametersHNSW* hnsw_params =
+ dynamic_cast<const SearchParametersHNSW*>(params)) {
+ do_dis_check = hnsw_params->check_relative_distance;
+ efSearch = hnsw_params->efSearch;
+
+ // Setup beam search parameters
+ if (hnsw_params->beam_size > 0) {
+ beam_size = hnsw_params->beam_size;
+ }
+
+ // Setup batching parameters
+ if (hnsw_params->batch_size > 0) {
+ batch_size = hnsw_params->batch_size;
+ use_batching = true;
+ } else {
+ use_batching = false; // Explicitly disable if batch_size <= 0
+ }
+
+ // PQ pruning settings
+ pq_select_ratio = 1 - hnsw_params->pq_pruning_ratio;
+
+ local_prune = hnsw_params->local_prune;
+ send_neigh_times_ratio = hnsw_params->send_neigh_times_ratio;
+
+ // cache_distances = hnsw_params->cache_distances;
+ }
+ sel = params->sel;
+ }
+
+ bool perform_pq_pruning =
+ (hnsw.pq_data_loader && hnsw.pq_data_loader->is_initialized() &&
+ (pq_select_ratio < 1 || local_prune ||
+ send_neigh_times_ratio != 0));
+ // Initialize PQ data if needed
+ if (perform_pq_pruning) {
+ size_t dim = hnsw.pq_data_loader->get_dims();
+ size_t n_chunks = hnsw.pq_data_loader->get_num_chunks();
+ const float* original_query = qdis.get_query();
+
+ query_preprocessed.resize(dim);
+ memcpy(query_preprocessed.data(),
+ original_query,
+ (dim - 1) * sizeof(float));
+ query_preprocessed[dim - 1] = 0;
+ hnsw.pq_data_loader->preprocess_query(
+ query_preprocessed.data(), query_preprocessed.data());
+ pq_dists_lookup.resize(256 * n_chunks);
+ hnsw.pq_data_loader->populate_chunk_distances(
+ query_preprocessed.data(), pq_dists_lookup.data());
+
+ pq_code_scratch.resize(max_deg_l0 * hnsw.code_size);
+ pq_dists_out.resize(max_deg_l0);
+ }
+ neighbor_read_buffer.resize(max_deg_l0);
+
+ // Global PQ candidate queue (min-heap)
+ using PQCandidate = std::pair<float, idx_t>; // (pq_distance, node_id)
+ using PQCandidateQueue = std::priority_queue<
+ PQCandidate,
+ std::vector<PQCandidate>,
+ std::greater<PQCandidate>>;
+ PQCandidateQueue pq_candidate_queue;
+ std::set<PQCandidate> pq_candidate_set;
+ // set the order of the pq_candidate_set, the smallest distance is the first
+ C::T threshold = res.threshold;
+ for (int i = 0; i < candidates.size(); i++) {
+ idx_t v1 = candidates.ids[i];
+ float d = candidates.dis[i];
+ FAISS_ASSERT(v1 >= 0);
+ if (!sel || sel->is_member(v1)) {
+ if (d < threshold) {
+ if (res.add_result(d, v1)) {
+ threshold = res.threshold;
+ }
+ }
+ }
+ vt.set(v1);
+
+ // Track this node visit
+ stats.node_visit_counts[v1]++;
+ // printf("Visted node: %ld\n", v1);
+
+ // // Add initial candidates to PQ queue if using PQ pruning
+ // if (perform_pq_pruning) {
+ // pq_code_scratch.resize(hnsw.code_size);
+ // pq_dists_out.resize(1);
+
+ // size_t aggregated_count = aggregate_pq_codes(
+ // &v1,
+ // 1,
+ // hnsw.pq_codes.data(),
+ // hnsw.levels.size(),
+ // hnsw.code_size,
+ // pq_code_scratch.data());
+
+ // FAISS_ASSERT(aggregated_count == 1);
+ // pq_distance_lookup(
+ // pq_code_scratch.data(),
+ // 1,
+ // hnsw.pq_data_loader->get_num_chunks(),
+ // pq_dists_lookup.data(),
+ // pq_dists_out.data());
+ // npq++;
+ // pq_candidate_queue.push({pq_dists_out[0], v1});
+ // }
+ }
+
+ int nstep = 0;
+
+ while (candidates.size() > 0) {
+ // Process nodes based on strategy
+ std::vector<int> beam_nodes;
+ std::vector<float> beam_distances;
+ std::map<idx_t, std::vector<idx_t>> beam_fetched_neighbors;
+ int total_neighbors = 0;
+
+ // 1. Get all beam nodes - either batch mode or fixed beam mode
+ if (use_batching) {
+ // Batch mode - get nodes until we reach batch_size neighbors
+ while (candidates.size() > 0 &&
+ (beam_nodes.empty() || total_neighbors < batch_size)) {
+ float d0 = 0;
+ int v0 = candidates.pop_min(&d0);
+ assert(v0 >= 0);
+
+ // Track this node visit
+ stats.node_visit_counts[v0]++;
+ // printf("Visted node: %ld\n", v0);
+ if (do_dis_check) {
+ // tricky stopping condition: there are more that ef
+ // distances that are processed already that are smaller
+ // than d0
+
+ int n_dis_below = candidates.count_below(d0);
+ if (n_dis_below >= efSearch) {
+ break;
+ }
+ }
+
+ size_t node_neighbor_count =
+ hnsw.fetch_neighbors(v0, 0, neighbor_read_buffer);
+ nfetch++;
+
+ std::vector<idx_t> current_node_neighbors;
+ FAISS_ASSERT(node_neighbor_count >= 0);
+ for (size_t i = 0; i < node_neighbor_count; ++i) {
+ if (!vt.get(neighbor_read_buffer[i])) {
+ current_node_neighbors.push_back(
+ static_cast<idx_t>(neighbor_read_buffer[i]));
+ }
+ }
+
+ beam_nodes.push_back(v0);
+ beam_distances.push_back(d0);
+ total_neighbors +=
+ current_node_neighbors.size() * pq_select_ratio;
+ beam_fetched_neighbors[v0] = std::move(current_node_neighbors);
+ }
+ // printf("get beam_nodes: %d\n", beam_nodes.size());
+ // printf("total_neighbors: %d\n", total_neighbors);
+ } else {
+ for (int b = 0; b < beam_size && candidates.size() > 0; b++) {
+ float d0 = 0;
+ int v0 = candidates.pop_min(&d0);
+ FAISS_ASSERT(v0 >= 0);
+
+ // Track this node visit
+ stats.node_visit_counts[v0]++;
+ // printf("Visted node: %ld\n", v0);
+
+ if (do_dis_check) {
+ // tricky stopping condition: there are more that ef
+ // distances that are processed already that are smaller
+ // than d0
+
+ int n_dis_below = candidates.count_below(d0);
+ if (n_dis_below >= efSearch) {
+ break;
+ }
+ }
+
+ std::vector<idx_t> current_node_neighbors;
+ size_t node_neighbor_count =
+ hnsw.fetch_neighbors(v0, 0, neighbor_read_buffer);
+ nfetch++;
+
+ FAISS_ASSERT(node_neighbor_count >= 0);
+
+ for (size_t i = 0; i < node_neighbor_count; ++i) {
+ if (!vt.get(neighbor_read_buffer[i])) {
+ current_node_neighbors.push_back(
+ static_cast<idx_t>(neighbor_read_buffer[i]));
+ }
+ }
+ beam_nodes.push_back(v0);
+ beam_distances.push_back(d0);
+ total_neighbors +=
+ current_node_neighbors.size() * pq_select_ratio;
+ beam_fetched_neighbors[v0] = std::move(current_node_neighbors);
+ }
+ // printf("get beam_nodes: %d\n", beam_nodes.size());
+ // printf("total_neighbors: %d\n", total_neighbors);
+ }
+
+ // Continue if we couldn't pop any valid nodes
+ if (beam_nodes.empty()) {
+ continue;
+ }
+
+ threshold = res.threshold;
+ std::set<idx_t> all_new_neighbors_set;
+
+ // 2. Process neighbors of all nodes in the beam
+ for (size_t b = 0; b < beam_nodes.size(); b++) {
+ int v0 = beam_nodes[b];
+
+ const auto& neighbors_of_v0 = beam_fetched_neighbors[v0];
+ for (idx_t v1 : neighbors_of_v0) {
+ assert(v1 >= 0);
+ assert(!vt.get(v1)); // Since the current_node_neighbors is
+ // already filtered by vt
+ all_new_neighbors_set.insert(v1);
+ }
+ }
+
+ std::vector<idx_t> unique_new_neighbors(
+ all_new_neighbors_set.begin(), all_new_neighbors_set.end());
+ std::vector<idx_t> nodes_to_compute;
+ size_t n_new = unique_new_neighbors.size();
+
+ // Calculate PQ distances for unvisited neighbors and add to global PQ
+ // queue
+ if (perform_pq_pruning) {
+ pq_code_scratch.resize(n_new * hnsw.code_size);
+ pq_dists_out.resize(n_new);
+
+ size_t aggregated_count = aggregate_pq_codes(
+ unique_new_neighbors.data(),
+ n_new,
+ hnsw.pq_codes.data(),
+ hnsw.levels.size(),
+ hnsw.code_size,
+ pq_code_scratch.data());
+
+ FAISS_ASSERT(aggregated_count == unique_new_neighbors.size());
+ pq_distance_lookup(
+ pq_code_scratch.data(),
+ aggregated_count,
+ hnsw.pq_data_loader->get_num_chunks(),
+ pq_dists_lookup.data(),
+ pq_dists_out.data());
+ npq += aggregated_count;
+
+ assert(pq_dists_out.size() == unique_new_neighbors.size());
+ PQCandidateQueue local_pq_indices;
+ for (size_t i = 0; i < aggregated_count; i++) {
+ assert(!vt.get(unique_new_neighbors[i]));
+ local_pq_indices.push(
+ {pq_dists_out[i], unique_new_neighbors[i]});
+ pq_candidate_queue.push(
+ {pq_dists_out[i], unique_new_neighbors[i]});
+ pq_candidate_set.insert(
+ {pq_dists_out[i], unique_new_neighbors[i]});
+ // printf("pq_dists_out[i]: %f\n", pq_dists_out[i]);
+ // printf("unique_new_neighbors[i]: %ld\n",
+ // unique_new_neighbors[i]);
+ }
+ if (local_prune) {
+ // Convert priority queue to vector for sorting
+ std::vector<PQCandidate> sorted_candidates;
+ while (!local_pq_indices.empty()) {
+ sorted_candidates.push_back(local_pq_indices.top());
+ local_pq_indices.pop();
+ }
+
+ // Sort the vector
+ std::sort(
+ sorted_candidates.begin(),
+ sorted_candidates.end(),
+ [](const PQCandidate& a, const PQCandidate& b) {
+ return a.first < b.first;
+ });
+
+ // Choose top pq_select_ratio * sorted_candidates.size() closest
+ // ones
+ size_t num_to_select =
+ pq_select_ratio * sorted_candidates.size();
+ for (size_t i = 0;
+ i < num_to_select && i < sorted_candidates.size();
+ i++) {
+ nodes_to_compute.push_back(sorted_candidates[i].second);
+ vt.set(sorted_candidates[i].second);
+ }
+ } else {
+ // Another worker: select top candidates from PQ queue for exact
+ // distance calculation
+ int num_to_select = std::max(
+ 1, int(pq_candidate_queue.size() * pq_select_ratio));
+ std::vector<PQCandidate> popped_pq_nodes;
+ popped_pq_nodes.reserve(num_to_select);
+ if (send_neigh_times_ratio > 1e-6) {
+ num_to_select = std::max(1, int(n_new * pq_select_ratio));
+
+ for (int i = 0;
+ i < num_to_select && !pq_candidate_set.empty();
+ i++) {
+ PQCandidate top_pq = *pq_candidate_set.begin();
+ pq_candidate_set.erase(pq_candidate_set.begin());
+ FAISS_THROW_IF_NOT_FMT(
+ !vt.get(top_pq.second),
+ "Node %ld already visited but appeared in PQ candidate queue. This suggests a duplicate entry or incorrect visited table state.",
+ (long)top_pq.second);
+ nodes_to_compute.push_back(top_pq.second);
+ vt.set(top_pq.second);
+ }
+ } else {
+ for (int i = 0;
+ i < num_to_select && !pq_candidate_queue.empty();
+ i++) {
+ PQCandidate top_pq = pq_candidate_queue.top();
+ pq_candidate_queue.pop();
+
+ if (!vt.get(top_pq.second)) {
+ nodes_to_compute.push_back(top_pq.second);
+ vt.set(top_pq.second);
+ }
+ popped_pq_nodes.push_back(std::move(top_pq));
+ }
+
+ // Push back popped nodes
+ for (const auto& pq_node : popped_pq_nodes) {
+ pq_candidate_queue.push(pq_node);
+ }
+ // printf("nodes_to_compute size: %zu\n",
+ // nodes_to_compute.size()); print n_new printf("n_new:
+ // %zu\n", n_new);
+ }
+ }
+ } else {
+ // If not using PQ pruning, process all new neighbors normally
+ for (idx_t v1 : unique_new_neighbors) {
+ assert(!vt.get(v1));
+ if (!vt.get(v1)) {
+ nodes_to_compute.push_back(v1);
+ vt.set(v1);
+ }
+ }
+ }
+
+ std::vector<float> batch_distances(nodes_to_compute.size());
+ qdis.distances_batch(nodes_to_compute, batch_distances);
+
+ auto add_to_heap = [&](const size_t idx, const float dis) {
+ if (!sel || sel->is_member(idx)) {
+ if (dis < threshold) {
+ if (res.add_result(dis, idx)) {
+ threshold = res.threshold;
+ nres += 1;
+ }
+ }
+ }
+ candidates.push(idx, dis);
+ };
+
+ for (size_t i = 0; i < nodes_to_compute.size(); i++) {
+ add_to_heap(nodes_to_compute[i], batch_distances[i]);
+ }
+
+ ndis += nodes_to_compute.size();
+
+ nstep += beam_nodes.size();
+ // printf("nstep: %d\n", nstep);
+ if (!do_dis_check && nstep > efSearch) {
+ break;
+ }
+ }
+
+ // printf("fetch_disk_cache_counts: %d\n", fetch_disk_cache_counts);
+ // printf("total_neigh_fetch: %d\n", ndis);
+
+ if (level == 0) {
+ stats.n1++;
+ if (candidates.size() == 0) {
+ stats.n2++;
+ }
+ stats.ndis += ndis;
+ stats.nhops += nstep;
+ stats.n_ios = nfetch;
+ stats.n_pq_calcs = npq;
+
+ // Periodically dump node visit statistics to a file
+ // static const size_t NODE_THRESHOLD =
+ // 10000; // Dump when we have at least this many unique nodes
+ // static const size_t SEARCH_INTERVAL = 100; // Or dump every N
+ // static int dump_counter = 0;
+ // static size_t search_counter = 0;
+
+ // search_counter++;
+
+ // bool should_dump = stats.node_visit_counts.size() >= NODE_THRESHOLD
+ // ||
+ // search_counter % SEARCH_INTERVAL == 0;
+
+ // if (should_dump) {
+ // char filename[256];
+ // // Dump individual node visit counts
+ // snprintf(
+ // filename,
+ // sizeof(filename),
+ // "node_visits_%d.csv",
+ // dump_counter);
+ // stats.dump_node_visit_stats(filename);
+
+ // // Dump frequency distribution
+ // snprintf(
+ // filename,
+ // sizeof(filename),
+ // "visit_frequency_%d.csv",
+ // dump_counter);
+ // stats.dump_visit_frequency_distribution(filename);
+
+ // printf("Dumped node visit statistics (dump #%d, unique nodes:%zu,
+ // searches: %zu)\n",
+ // dump_counter,
+ // stats.node_visit_counts.size(),
+ // search_counter);
+
+ // dump_counter++;
+
+ // // Don't clear the counters so we can see cumulative data
+ // // If you want to reset after each dump, uncomment the following:
+ // // stats.node_visit_counts.clear();
+ // // search_counter = 0;
+ // }
+ }
+
+ return nres;
+}
+} // namespace faiss
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_zmq.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_zmq.cpp
new file mode 100644
index 0000000..826d583
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_zmq.cpp
@@ -0,0 +1,657 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexHNSW.h>
+
+#include <omp.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+
+#include <limits>
+#include <memory>
+
+#include <cstdint>
+
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/sorting.h>
+
+#include <fcntl.h>
+#include <msgpack.hpp>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <zmq.h>
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <fstream>
+#include <future>
+#include <sstream> // For msgpack stringstream buffer
+#include <thread>
+
+#include "HNSW_zmq.h"
+
+namespace faiss {
+
+namespace {
+std::string experimental_disk_storage_path;
+off_t experimental_disk_data_offset;
+int experimental_block_size;
+std::vector<bool> experimental_is_in_top_degree_set;
+} // namespace
+
+void setup_experimental_top_degree_disk_read(
+ const std::string& degree_path,
+ float top_percent,
+ const std::string& storage_path,
+ off_t data_offset,
+ idx_t ntotal) {
+ FAISS_THROW_IF_NOT_FMT(
+ data_offset >= 0, "Data offset (%ld) invalid.", data_offset);
+ FAISS_THROW_IF_NOT_MSG(
+ top_percent >= 0.0f && top_percent <= 100.0f,
+ "top_percent invalid.");
+ FAISS_THROW_IF_NOT_FMT(
+ ntotal > 0, "ntotal (%ld) must be positive.", ntotal);
+
+ // 3. Determine threshold and build the boolean set
+ if (abs(top_percent - 0.0f) <= 1e-6) {
+ return;
+ }
+
+ // 1. Get block size
+ struct stat file_stat;
+ int block_size = 4096;
+ if (stat(storage_path.c_str(), &file_stat) == 0) {
+ block_size = (file_stat.st_blksize > 0) ? file_stat.st_blksize : 4096;
+ } else {
+ // Fail fast on stat error as block size is critical for O_DIRECT
+ FAISS_THROW_FMT(
+ "Setup Error: Cannot stat storage file %s: %s",
+ storage_path.c_str(),
+ strerror(errno));
+ }
+ FAISS_THROW_IF_NOT(block_size > 0);
+
+ // 2. Load degree distribution temporarily
+ std::vector<int> degrees;
+ std::ifstream degree_file(degree_path);
+ if (degree_file.is_open()) {
+ std::string line;
+ if (ntotal > 0)
+ degrees.reserve(ntotal);
+ while (std::getline(degree_file, line)) {
+ if (line.empty())
+ continue;
+ try {
+ degrees.push_back(std::stoi(line));
+ } catch (...) { /* ignore */
+ }
+ }
+ degree_file.close();
+ } else {
+ FAISS_THROW_FMT(
+ "Setup Error: Degree file not found: %s", degree_path.c_str());
+ }
+ FAISS_THROW_IF_NOT_FMT(
+ !degrees.empty(), "Degree file %s empty.", degree_path.c_str());
+ if ((idx_t)degrees.size() != ntotal) {
+ FAISS_THROW_FMT(
+ "Setup Error: Degree file size (%zu) != ntotal (%ld).",
+ degrees.size(),
+ ntotal);
+ }
+
+ std::vector<int> sorted_degrees = degrees;
+ std::sort(
+ sorted_degrees.begin(), sorted_degrees.end(), std::greater<int>());
+
+ float percentile = top_percent / 100.0f;
+ size_t threshold_idx = std::min(
+ (size_t)(sorted_degrees.size() * percentile) - 1,
+ sorted_degrees.size() - 1); // Clamp index
+
+ int degree_threshold =
+ sorted_degrees[threshold_idx]; // Store threshold for info
+
+ std::vector<bool> is_in_top_degree_set(ntotal, false);
+ size_t top_node_count = 0;
+ for (idx_t i = 0; i < ntotal; ++i) {
+ if (degrees[i] >= degree_threshold) {
+ is_in_top_degree_set[i] = true;
+ top_node_count++;
+ }
+ }
+ experimental_disk_storage_path = storage_path;
+ experimental_disk_data_offset = data_offset;
+ experimental_block_size = block_size;
+ experimental_is_in_top_degree_set = is_in_top_degree_set;
+
+ printf("ZmqDC Setup: Disk logic Top %.2f%% (deg>=%d). %zu nodes. Offset=%ld, BlkSize=%d\n",
+ top_percent,
+ degree_threshold,
+ top_node_count,
+ data_offset,
+ block_size);
+}
+
+bool fetch_embeddings_zmq(
+ const std::vector<uint32_t>& node_ids,
+ std::vector<std::vector<float>>& out_embeddings,
+ int zmq_port = 5557); // Default port kept
+
+float read_disk_and_compute_local_ip(idx_t i, size_t d, const float* query) {
+ size_t vector_bytes = d * sizeof(float);
+ std::vector<float> vec_buffer(d);
+ void* aligned_buffer = nullptr;
+ size_t block_size = experimental_block_size;
+
+ int fd;
+#ifdef __linux__
+ // O_DIRECT is Linux-specific
+ fd =
+ open(experimental_disk_storage_path.c_str(),
+ O_RDONLY | O_CLOEXEC | O_DIRECT);
+#else
+ // macOS doesn't have O_DIRECT
+ fd = open(experimental_disk_storage_path.c_str(), O_RDONLY | O_CLOEXEC);
+#endif
+ if (fd == -1) {
+ assert(false);
+ }
+
+ off_t desired_start =
+ experimental_disk_data_offset + (off_t)i * vector_bytes;
+ off_t desired_end = desired_start + vector_bytes;
+ off_t aligned_start = (desired_start / block_size) * block_size;
+ off_t aligned_end =
+ ((desired_end + block_size - 1) / block_size) * block_size;
+ size_t bytes_to_read_aligned = aligned_end - aligned_start;
+
+ assert(bytes_to_read_aligned > 0);
+ if (posix_memalign(&aligned_buffer, block_size, bytes_to_read_aligned) !=
+ 0) {
+ assert(false);
+ }
+
+ ssize_t bytes_read =
+ pread(fd, aligned_buffer, bytes_to_read_aligned, aligned_start);
+ close(fd);
+
+ assert(bytes_read == (ssize_t)bytes_to_read_aligned);
+ size_t internal_offset = desired_start - aligned_start;
+ // Check bounds before memcpy
+ assert(internal_offset + vector_bytes <= bytes_to_read_aligned);
+ memcpy(vec_buffer.data(),
+ (char*)aligned_buffer + internal_offset,
+ vector_bytes);
+ // For IP metric, we need to return negative IP
+ // fetch embeddings to check
+ // std::vector<std::vector<float>> out_embeddings;
+ // bool success = fetch_embeddings_zmq(
+ // std::vector<uint32_t>{(uint32_t)i}, out_embeddings, 5557);
+ // assert(success);
+ // assert(out_embeddings.size() == 1);
+ // assert(out_embeddings[0].size() == d);
+ // for (auto i = 0; i < out_embeddings.size(); i++) {
+ // for (auto j = 0; j < out_embeddings[i].size(); j++) {
+ // if (abs(out_embeddings[i][j] - vec_buffer[j]) > 1e-3) {
+ // printf("ERROR: disk and remote fetched embeddings mismatch
+ // for id %ld, error: %f\n",
+ // i,
+ // abs(out_embeddings[i][j] - vec_buffer[j]));
+ // }
+ // }
+ // printf("\n");
+ // }
+ float distance = -fvec_inner_product(query, vec_buffer.data(), d);
+ free(aligned_buffer);
+ return distance;
+}
+
+// --- MessagePack Data Structures (Define simple structs for serialization) ---
+struct EmbeddingRequestMsgpack {
+ std::vector<uint32_t> node_ids;
+ MSGPACK_DEFINE_ARRAY(node_ids); // Use array format [ [ids] ]
+};
+
+struct EmbeddingResponseMsgpack {
+ // Store dimensions as separate fields for clarity with msgpack map
+ // Or keep as vector [batch_size, dim] if using array format
+ // Let's use array format for simplicity matching MSGPACK_DEFINE_ARRAY
+ std::vector<uint32_t> dimensions; // [batch_size, embedding_dim]
+ // Store flat embedding data as raw bytes or vector<float>
+ // Using vector<float> is easier to handle with msgpack-c directly
+ std::vector<float>
+ embeddings_data; // Flattened [batch_size * embedding_dim]
+ // Optional: Add missing_ids if needed
+ // std::vector<uint32_t> missing_ids;
+
+ MSGPACK_DEFINE_ARRAY(dimensions, embeddings_data); // [ [dims], [data] ]
+};
+
+struct DistanceRequestMsgpack {
+ std::vector<uint32_t> node_ids;
+ std::vector<float> query_vector;
+ MSGPACK_DEFINE_ARRAY(node_ids, query_vector); // [ [ids], [query_vector] ]
+};
+
+struct DistanceResponseMsgpack {
+ std::vector<float> distances; // Direct distances between query and nodes
+ MSGPACK_DEFINE_ARRAY(distances); // [ [distances] ]
+};
+
+// --- ZMQ Fetch Function (Using MessagePack) ---
+bool fetch_embeddings_zmq(
+ const std::vector<uint32_t>& node_ids,
+ std::vector<std::vector<float>>& out_embeddings,
+ int zmq_port) // Default port kept
+{
+ EmbeddingRequestMsgpack req_msgpack;
+ req_msgpack.node_ids = node_ids;
+
+ std::stringstream buffer;
+ try {
+ msgpack::pack(buffer, req_msgpack);
+ } catch (const std::exception& e) {
+ std::cerr << "MessagePack pack failed: " << e.what() << std::endl;
+ return false;
+ }
+ std::string req_str = buffer.str();
+
+ void* context = zmq_ctx_new();
+ if (!context) {
+ // fprintf(stderr,
+ // "[fetch_zmq] zmq_ctx_new failed: %s\n",
+ // zmq_strerror(zmq_errno()));
+ return false;
+ }
+ void* socket = zmq_socket(context, ZMQ_REQ);
+ if (!socket) {
+ // fprintf(stderr,
+ // "[fetch_zmq] zmq_socket failed: %s\n",
+ // zmq_strerror(zmq_errno()));
+ zmq_ctx_destroy(context);
+ return false;
+ }
+ int timeout = 30000;
+ zmq_setsockopt(socket, ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
+ zmq_setsockopt(socket, ZMQ_SNDTIMEO, &timeout, sizeof(timeout));
+ std::string endpoint = "tcp://127.0.0.1:" + std::to_string(zmq_port);
+ if (zmq_connect(socket, endpoint.c_str()) != 0) {
+ // fprintf(stderr,
+ // "[fetch_zmq] zmq_connect failed: %s\n",
+ // zmq_strerror(zmq_errno()));
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ if (zmq_send(socket, req_str.data(), req_str.size(), 0) < 0) { /*...*/
+ // fprintf(stderr,
+ // "[fetch_zmq] zmq_msg_recv failed: %s\n",
+ // zmq_strerror(zmq_errno()));
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ zmq_msg_t response;
+ zmq_msg_init(&response);
+ if (zmq_msg_recv(&response, socket, 0) < 0) { /*...*/
+ // fprintf(stderr,
+ // "[fetch_zmq] zmq_msg_recv failed: %s\n",
+ // zmq_strerror(zmq_errno()));
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ EmbeddingResponseMsgpack resp_msgpack;
+ const char* resp_data = static_cast<const char*>(zmq_msg_data(&response));
+ size_t resp_size = zmq_msg_size(&response);
+ // printf("[fetch_zmq] Raw response bytes (first %d): ",
+ // (int)std::min((size_t)64, resp_size));
+
+ msgpack::object_handle oh = msgpack::unpack(resp_data, resp_size);
+ msgpack::object obj = oh.get();
+ obj.convert(resp_msgpack); // Convert msgpack object to our struct
+ // for (size_t k = 0; k < std::min((size_t)64, resp_size); ++k)
+ // printf("%02x ", (unsigned char)resp_data[k]);
+ // printf("\n");
+
+ // --- Print parsed values BEFORE NaN check ---
+ // printf("[fetch_zmq] Parsed response. Dimensions: %d x %d. Data floats:
+ // %zu\n",
+ // resp_msgpack.dimensions.empty() ? 0 : resp_msgpack.dimensions[0],
+ // resp_msgpack.dimensions.size() < 2 ? 0 :
+ // resp_msgpack.dimensions[1], resp_msgpack.embeddings_data.size());
+ // printf("[fetch_zmq] Parsed embeddings_data (first %d floats): ",
+ // (int)std::min((size_t)10, resp_msgpack.embeddings_data.size()));
+ // bool parse_contains_nan = false;
+ // for (size_t k = 0;
+ // k < std::min((size_t)10, resp_msgpack.embeddings_data.size());
+ // ++k) {
+ // printf("%.6f ", resp_msgpack.embeddings_data[k]);
+ // if (std::isnan(resp_msgpack.embeddings_data[k]))
+ // parse_contains_nan = true;
+ // }
+ // printf("%s\n",
+ // parse_contains_nan ? "!!! CONTAINS NaN AFTER PARSE !!!"
+ // : "(Checked first 10 for NaN)");
+
+ if (resp_msgpack.dimensions.size() != 2) {
+ // std::cerr << "Server response has invalid dimensions size: "
+ // << resp_msgpack.dimensions.size() << std::endl;
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+ int batch_size = resp_msgpack.dimensions[0];
+ int embedding_dim = resp_msgpack.dimensions[1];
+
+ // Handle empty response
+ if (batch_size == 0) {
+ out_embeddings.clear();
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return true; // Successful communication, no data returned
+ }
+
+ size_t expected_floats = (size_t)batch_size * embedding_dim;
+ if (resp_msgpack.embeddings_data.size() != expected_floats) {
+ // std::cerr << "Embedding data size mismatch: Got "
+ // << resp_msgpack.embeddings_data.size() << " floats,
+ // expected "
+ // << expected_floats << " (" << batch_size << "x"
+ // << embedding_dim << ")" << std::endl;
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ bool received_nan = false;
+ for (float val : resp_msgpack.embeddings_data) {
+ if (std::isnan(val)) {
+ received_nan = true;
+ break;
+ }
+ }
+ if (received_nan) {
+ // fprintf(stderr,
+ // "!!! [fetch_zmq] ERROR: Final check confirms NaN values in
+ // parsed embeddings_data! First requested ID: %u !!!\n",
+ // node_ids.empty() ? 0 : node_ids[0]);
+ return false; // Decide whether to fail here
+ } else {
+ // printf("[fetch_zmq] Final check confirms embeddings data appears
+ // clean (no NaNs checked).\n"); // Can be verbose
+ }
+
+ out_embeddings.clear();
+ out_embeddings.resize(batch_size);
+ const float* flat_data_ptr = resp_msgpack.embeddings_data.data();
+ for (int i = 0; i < batch_size; i++) {
+ out_embeddings[i].assign(
+ flat_data_ptr + (size_t)i * embedding_dim,
+ flat_data_ptr + ((size_t)i + 1) * embedding_dim);
+ }
+
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+
+ return true;
+}
+
+const float* ZmqDistanceComputer::get_vector_zmq(idx_t id) {
+ std::vector<uint32_t> ids_to_fetch = {(uint32_t)id};
+ std::vector<std::vector<float>>
+ fetched_embeddings; // fetch_embeddings_zmq expects this
+ // structure
+
+ if (!fetch_embeddings_zmq(ids_to_fetch, fetched_embeddings, zmq_port)) {
+ // fprintf(stderr,
+ // "!!! ERROR get_vector_zmq: fetch_embeddings_zmq call
+ // failed for ID %ld !!!\n", (long)id);
+ // Fill member with NaN to indicate failure?
+ std::fill(
+ last_fetched_zmq_vector.begin(),
+ last_fetched_zmq_vector.end(),
+ std::numeric_limits<float>::quiet_NaN());
+ return nullptr; // Indicate failure upstream
+ }
+ if (fetched_embeddings.empty() || fetched_embeddings[0].size() != d) {
+ // fprintf(stderr,
+ // "!!! ERROR get_vector_zmq: fetch_embeddings_zmq returned
+ // incorrect data for ID %ld !!!\n", (long)id);
+ std::fill(
+ last_fetched_zmq_vector.begin(),
+ last_fetched_zmq_vector.end(),
+ std::numeric_limits<float>::quiet_NaN());
+ return nullptr;
+ }
+
+ // --- Copy fetched data to member variable ---
+ // fetched_embeddings[0] contains the vector data
+ FAISS_ASSERT(fetched_embeddings[0].size() == d);
+ memcpy(last_fetched_zmq_vector.data(),
+ fetched_embeddings[0].data(),
+ d * sizeof(float));
+
+ // ---- Addition: Increment fetch count on success ----
+ fetch_count++;
+ // ---- End Addition ----
+
+ // --- Log values RIGHT BEFORE returning pointer ---
+ const float* return_ptr = last_fetched_zmq_vector.data();
+ // bool has_nan_before_return = false;
+ // printf("DEBUG get_vector_zmq: Fetched ID %ld. Values BEFORE return
+ // (ptr %p) [0..%d]: ",
+ // (long)id,
+ // (void*)return_ptr,
+ // (int)std::min((size_t)4, d - 1));
+ // for (size_t k = 0; k < std::min((size_t)5, d); ++k) {
+ // printf("%.6f ", return_ptr[k]);
+ // if (std::isnan(return_ptr[k]) || std::isinf(return_ptr[k]))
+ // has_nan_before_return = true;
+ // }
+ // printf("%s\n",
+ // has_nan_before_return ? "!!! HAS NaN/Inf BEFORE RETURN !!!"
+ // : "(OK Before Return)");
+ // -------------------------------------------
+
+ return return_ptr; // Return pointer to member data
+}
+
+// --- ZMQ Distance Calculation Function (Using MessagePack) ---
+bool fetch_distances_zmq(
+ const std::vector<uint32_t>& node_ids,
+ const float* query_vector,
+ size_t query_dim,
+ std::vector<float>& out_distances,
+ int zmq_port = 5557) {
+ DistanceRequestMsgpack req_msgpack;
+ req_msgpack.node_ids = node_ids;
+
+ // Copy query vector
+ req_msgpack.query_vector.resize(query_dim);
+ memcpy(req_msgpack.query_vector.data(),
+ query_vector,
+ query_dim * sizeof(float));
+
+ std::stringstream buffer;
+ try {
+ msgpack::pack(buffer, req_msgpack);
+ } catch (const std::exception& e) {
+ std::cerr << "MessagePack pack failed for distance request: "
+ << e.what() << std::endl;
+ return false;
+ }
+ std::string req_str = buffer.str();
+
+ void* context = zmq_ctx_new();
+ if (!context) {
+ return false;
+ }
+ void* socket = zmq_socket(context, ZMQ_REQ);
+ if (!socket) {
+ zmq_ctx_destroy(context);
+ return false;
+ }
+ int timeout = 30000;
+ zmq_setsockopt(socket, ZMQ_RCVTIMEO, &timeout, sizeof(timeout));
+ zmq_setsockopt(socket, ZMQ_SNDTIMEO, &timeout, sizeof(timeout));
+ std::string endpoint = "tcp://127.0.0.1:" + std::to_string(zmq_port);
+ if (zmq_connect(socket, endpoint.c_str()) != 0) {
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ if (zmq_send(socket, req_str.data(), req_str.size(), 0) < 0) {
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ zmq_msg_t response;
+ zmq_msg_init(&response);
+ if (zmq_msg_recv(&response, socket, 0) < 0) {
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ DistanceResponseMsgpack resp_msgpack;
+ const char* resp_data = static_cast<const char*>(zmq_msg_data(&response));
+ size_t resp_size = zmq_msg_size(&response);
+
+ try {
+ msgpack::object_handle oh = msgpack::unpack(resp_data, resp_size);
+ msgpack::object obj = oh.get();
+ obj.convert(resp_msgpack); // Convert msgpack object to our struct
+ } catch (const std::exception& e) {
+ std::cerr << "MessagePack unpack failed for distance response: "
+ << e.what() << std::endl;
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ if (resp_msgpack.distances.size() != node_ids.size()) {
+ std::cerr << "Distance response size mismatch: Got "
+ << resp_msgpack.distances.size() << " distances, expected "
+ << node_ids.size() << std::endl;
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+ return false;
+ }
+
+ // Copy distances to output vector
+ out_distances = resp_msgpack.distances;
+
+ zmq_msg_close(&response);
+ zmq_close(socket);
+ zmq_ctx_destroy(context);
+
+ return true;
+}
+
+void ZmqDistanceComputer::distances_batch(
+ const std::vector<idx_t>& ids,
+ std::vector<float>& distances_out) {
+ // Resize output vector
+ distances_out.resize(ids.size());
+
+ // Separate nodes into disk-read and remote-read groups
+ std::vector<uint32_t> remote_nodes;
+ std::vector<size_t> remote_orig_indices;
+ std::vector<uint32_t> disk_nodes;
+ std::vector<size_t> disk_orig_indices;
+
+ for (size_t j = 0; j < ids.size(); ++j) {
+ idx_t id = ids[j];
+ if (experimental_is_in_top_degree_set.empty()) {
+ remote_nodes.push_back(id);
+ remote_orig_indices.push_back(j);
+ } else {
+ assert(id >= 0 &&
+ (size_t)id < experimental_is_in_top_degree_set.size());
+ if (experimental_is_in_top_degree_set[id]) {
+ // Mark for disk read
+ disk_nodes.push_back(id);
+ disk_orig_indices.push_back(j);
+ } else {
+ // Mark for remote read
+ remote_nodes.push_back(id);
+ remote_orig_indices.push_back(j);
+ }
+ }
+ }
+
+ // Process remote nodes via ZMQ if any
+ if (!remote_nodes.empty()) {
+ // Call the original ZMQ batch function
+ std::vector<float> fetched_distances;
+ bool success = fetch_distances_zmq(
+ remote_nodes, query.data(), d, fetched_distances, zmq_port);
+ assert(success);
+ assert(fetched_distances.size() == remote_nodes.size());
+
+ for (size_t j = 0; j < remote_nodes.size(); ++j) {
+ distances_out[remote_orig_indices[j]] = fetched_distances[j];
+ }
+ fetch_count += remote_nodes.size(); // Count these as fetches
+ }
+
+ // timing
+ std::chrono::steady_clock::time_point disk_start =
+ std::chrono::steady_clock::now();
+
+ // Process disk nodes locally
+ for (size_t j = 0; j < disk_nodes.size(); ++j) {
+ float disk_dist =
+ read_disk_and_compute_local_ip(disk_nodes[j], d, query.data());
+
+ // sanity check with remote fetched ones
+ // if (abs(disk_dist - distances_out[disk_orig_indices[j]]) > 1e-4) {
+ // printf("ERROR: disk and remote fetched distances mismatch for id
+ // %ld, error: %f\n",
+ // disk_nodes[j],
+ // abs(disk_dist - distances_out[disk_orig_indices[j]]));
+ // // assert(false);
+ // }
+ distances_out[disk_orig_indices[j]] = disk_dist;
+ }
+ fetch_disk_cache_counts += disk_nodes.size();
+
+ // timing
+ std::chrono::steady_clock::time_point disk_end =
+ std::chrono::steady_clock::now();
+ std::chrono::duration<double> disk_duration = disk_end - disk_start;
+ // printf("ZmqDC Distances Batch Time: %f seconds\n",
+ // disk_duration.count());
+}
+
+// --- Implementation of new experimental methods ---
+
+} // namespace faiss
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_zmq.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_zmq.h
new file mode 100644
index 0000000..162734b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/HNSW_zmq.h
@@ -0,0 +1,155 @@
+#pragma once
+
+#include <sys/types.h> // For off_t
+#include <cassert>
+#include <cstddef>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+namespace faiss {
+void setup_experimental_top_degree_disk_read(
+ const std::string& degree_path,
+ float top_percent,
+ const std::string& storage_path,
+ off_t data_offset,
+ idx_t ntotal);
+
+float read_disk_and_compute_local_ip(idx_t i, size_t d, const float* query);
+
+inline int fetch_disk_cache_counts = 0;
+
+struct ZmqDistanceComputer : DistanceComputer {
+ size_t d;
+ int zmq_port;
+ MetricType metric_type;
+ float metric_arg;
+ const Index* storage;
+ std::unique_ptr<DistanceComputer> storage_dc_orig;
+ std::unique_ptr<DistanceComputer> storage_dc_search;
+ std::vector<float> query;
+
+ std::vector<float> last_fetched_zmq_vector;
+
+ const float* get_query() override {
+ return query.data();
+ }
+ mutable size_t fetch_count = 0;
+ ZmqDistanceComputer(
+ size_t dim,
+ MetricType mt,
+ float marg = 0,
+ int zmq_port = 5557)
+ : d(dim), metric_type(mt), metric_arg(marg), zmq_port(zmq_port) {
+ FAISS_THROW_IF_NOT_MSG(d > 0, "Dimension must be positive");
+ query.resize(d);
+ last_fetched_zmq_vector.resize(d); // Preallocate
+ reset_fetch_count(); // Initialize count
+ printf("ZmqDistanceComputer initialized: d=%zu, metric=%d\n",
+ d,
+ (int)mt);
+ }
+ ZmqDistanceComputer(const Index* storage_ref)
+ : d(storage_ref->d),
+ metric_type(storage_ref->metric_type),
+ metric_arg(storage_ref->metric_arg),
+ storage(storage_ref),
+ storage_dc_orig(storage_ref->get_distance_computer()),
+ storage_dc_search(
+ is_similarity_metric(storage_ref->metric_type)
+ ? new NegativeDistanceComputer(
+ storage_ref->get_distance_computer())
+ : storage_ref->get_distance_computer()) {
+ query.resize(d);
+ last_fetched_zmq_vector.resize(d); // Preallocate
+ FAISS_THROW_IF_NOT_MSG(
+ storage != nullptr,
+ "Storage cannot be null for ZmqDistanceComputer");
+ FAISS_THROW_IF_NOT(storage_dc_orig && storage_dc_search);
+ reset_fetch_count(); // Initialize count
+ }
+ size_t get_fetch_count() const override {
+ return fetch_count;
+ }
+
+ void reset_fetch_count() override {
+ fetch_count = 0;
+ }
+
+ float operator()(idx_t i) override {
+ // TODO: should apply disk_cache
+ const float* vec_zmq = get_vector_zmq(i);
+ if (!vec_zmq)
+ return (metric_type == METRIC_INNER_PRODUCT)
+ ? -std::numeric_limits<float>::max()
+ : std::numeric_limits<float>::max();
+ if (is_similarity_metric(metric_type)) {
+ return -fvec_inner_product(query.data(), vec_zmq, d);
+ } else {
+ return fvec_L2sqr(query.data(), vec_zmq, d);
+ }
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ const float* vec_i_zmq = get_vector_zmq(i);
+ const float* vec_j_zmq = get_vector_zmq(j);
+ if (!vec_i_zmq || !vec_j_zmq)
+ return std::numeric_limits<float>::max();
+ return fvec_L2sqr(vec_i_zmq, vec_j_zmq, d);
+ }
+
+ float distance_func(const float* vec_zmq) {
+ if (!vec_zmq) // Handle case where ZMQ fetch failed
+ return (metric_type == METRIC_INNER_PRODUCT)
+ ? -std::numeric_limits<float>::max()
+ : std::numeric_limits<float>::max();
+
+ switch (metric_type) {
+ case METRIC_INNER_PRODUCT:
+ return -fvec_inner_product(
+ query.data(), vec_zmq, d); // Return negative IP
+ case METRIC_L2:
+ return fvec_L2sqr(
+ query.data(), vec_zmq, d); // Return L2 squared
+ default:
+ return std::numeric_limits<float>::max();
+ }
+ }
+
+ void set_query(const float* x) override {
+ reset_fetch_count();
+ memcpy(query.data(), x, d * sizeof(float));
+ }
+ ~ZmqDistanceComputer() override = default;
+
+ void distances_batch_4(
+ idx_t id0,
+ idx_t id1,
+ idx_t id2,
+ idx_t id3,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) override {
+ std::vector<idx_t> batch_ids = {id0, id1, id2, id3};
+ std::vector<float> batch_distances;
+
+ this->distances_batch(batch_ids, batch_distances);
+
+ dis0 = batch_distances[0];
+ dis1 = batch_distances[1];
+ dis2 = batch_distances[2];
+ dis3 = batch_distances[3];
+ }
+
+ const float* get_vector_zmq(idx_t id);
+ void distances_batch(
+ const std::vector<idx_t>& ids,
+ std::vector<float>& distances_out) override;
+};
+
+} // namespace faiss
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/IDSelector.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/IDSelector.cpp
new file mode 100644
index 0000000..f3aea42
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/IDSelector.cpp
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+
+namespace faiss {
+
+/***********************************************************************
+ * IDSelectorRange
+ ***********************************************************************/
+
+IDSelectorRange::IDSelectorRange(idx_t imin, idx_t imax, bool assume_sorted)
+ : imin(imin), imax(imax), assume_sorted(assume_sorted) {}
+
+bool IDSelectorRange::is_member(idx_t id) const {
+ return id >= imin && id < imax;
+}
+
+void IDSelectorRange::find_sorted_ids_bounds(
+ size_t list_size,
+ const idx_t* ids,
+ size_t* jmin_out,
+ size_t* jmax_out) const {
+ FAISS_ASSERT(assume_sorted);
+ if (list_size == 0 || imax <= ids[0] || imin > ids[list_size - 1]) {
+ *jmin_out = *jmax_out = 0;
+ return;
+ }
+ // bissection to find imin
+ if (ids[0] >= imin) {
+ *jmin_out = 0;
+ } else {
+ size_t j0 = 0, j1 = list_size;
+ while (j1 > j0 + 1) {
+ size_t jmed = (j0 + j1) / 2;
+ if (ids[jmed] >= imin) {
+ j1 = jmed;
+ } else {
+ j0 = jmed;
+ }
+ }
+ *jmin_out = j1;
+ }
+ // bissection to find imax
+ if (*jmin_out == list_size || ids[*jmin_out] >= imax) {
+ *jmax_out = *jmin_out;
+ } else {
+ size_t j0 = *jmin_out, j1 = list_size;
+ while (j1 > j0 + 1) {
+ size_t jmed = (j0 + j1) / 2;
+ if (ids[jmed] >= imax) {
+ j1 = jmed;
+ } else {
+ j0 = jmed;
+ }
+ }
+ *jmax_out = j1;
+ }
+}
+
+/***********************************************************************
+ * IDSelectorArray
+ ***********************************************************************/
+
+IDSelectorArray::IDSelectorArray(size_t n, const idx_t* ids) : n(n), ids(ids) {}
+
+bool IDSelectorArray::is_member(idx_t id) const {
+ for (idx_t i = 0; i < n; i++) {
+ if (ids[i] == id)
+ return true;
+ }
+ return false;
+}
+
+/***********************************************************************
+ * IDSelectorBatch
+ ***********************************************************************/
+
+IDSelectorBatch::IDSelectorBatch(size_t n, const idx_t* indices) {
+ nbits = 0;
+ while (n > ((idx_t)1 << nbits)) {
+ nbits++;
+ }
+ nbits += 5;
+ // for n = 1M, nbits = 25 is optimal, see P56659518
+
+ mask = ((idx_t)1 << nbits) - 1;
+ bloom.resize((idx_t)1 << (nbits - 3), 0);
+ for (idx_t i = 0; i < n; i++) {
+ idx_t id = indices[i];
+ set.insert(id);
+ id &= mask;
+ bloom[id >> 3] |= 1 << (id & 7);
+ }
+}
+
+bool IDSelectorBatch::is_member(idx_t i) const {
+ long im = i & mask;
+ if (!(bloom[im >> 3] & (1 << (im & 7)))) {
+ return 0;
+ }
+ return set.count(i);
+}
+
+/***********************************************************************
+ * IDSelectorBitmap
+ ***********************************************************************/
+
+IDSelectorBitmap::IDSelectorBitmap(size_t n, const uint8_t* bitmap)
+ : n(n), bitmap(bitmap) {}
+
+bool IDSelectorBitmap::is_member(idx_t ii) const {
+ uint64_t i = ii;
+ if ((i >> 3) >= n) {
+ return false;
+ }
+ return (bitmap[i >> 3] >> (i & 7)) & 1;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/IDSelector.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/IDSelector.h
new file mode 100644
index 0000000..b79569c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/IDSelector.h
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <unordered_set>
+#include <vector>
+
+#include <faiss/MetricType.h>
+
+/** IDSelector is intended to define a subset of vectors to handle (for removal
+ * or as subset to search) */
+
+namespace faiss {
+
+/** Encapsulates a set of ids to handle. */
+struct IDSelector {
+ virtual bool is_member(idx_t id) const = 0;
+ virtual ~IDSelector() {}
+};
+
+/** ids between [imin, imax) */
+struct IDSelectorRange : IDSelector {
+ idx_t imin, imax;
+
+ /// Assume that the ids to handle are sorted. In some cases this can speed
+ /// up processing
+ bool assume_sorted;
+
+ IDSelectorRange(idx_t imin, idx_t imax, bool assume_sorted = false);
+
+ bool is_member(idx_t id) const final;
+
+ /// for sorted ids, find the range of list indices where the valid ids are
+ /// stored
+ void find_sorted_ids_bounds(
+ size_t list_size,
+ const idx_t* ids,
+ size_t* jmin,
+ size_t* jmax) const;
+
+ ~IDSelectorRange() override {}
+};
+
+/** Simple array of elements
+ *
+ * is_member calls are very inefficient, but some operations can use the ids
+ * directly.
+ */
+struct IDSelectorArray : IDSelector {
+ size_t n;
+ const idx_t* ids;
+
+ /** Construct with an array of ids to process
+ *
+ * @param n number of ids to store
+ * @param ids elements to store. The pointer should remain valid during
+ * IDSelectorArray's lifetime
+ */
+ IDSelectorArray(size_t n, const idx_t* ids);
+ bool is_member(idx_t id) const final;
+ ~IDSelectorArray() override {}
+};
+
+/** Ids from a set.
+ *
+ * Repetitions of ids in the indices set passed to the constructor does not hurt
+ * performance.
+ *
+ * The hash function used for the bloom filter and GCC's implementation of
+ * unordered_set are just the least significant bits of the id. This works fine
+ * for random ids or ids in sequences but will produce many hash collisions if
+ * lsb's are always the same
+ */
+struct IDSelectorBatch : IDSelector {
+ std::unordered_set<idx_t> set;
+
+ // Bloom filter to avoid accessing the unordered set if it is unlikely
+ // to be true
+ std::vector<uint8_t> bloom;
+ int nbits;
+ idx_t mask;
+
+ /** Construct with an array of ids to process
+ *
+ * @param n number of ids to store
+ * @param ids elements to store. The pointer can be released after
+ * construction
+ */
+ IDSelectorBatch(size_t n, const idx_t* indices);
+ bool is_member(idx_t id) const final;
+ ~IDSelectorBatch() override {}
+};
+
+/** One bit per element. Constructed with a bitmap, size ceil(n / 8).
+ */
+struct IDSelectorBitmap : IDSelector {
+ size_t n;
+ const uint8_t* bitmap;
+
+ /** Construct with a binary mask
+ *
+ * @param n size of the bitmap array
+ * @param bitmap id will be selected iff id / 8 < n and bit number
+ * (i%8) of bitmap[floor(i / 8)] is 1.
+ */
+ IDSelectorBitmap(size_t n, const uint8_t* bitmap);
+ bool is_member(idx_t id) const final;
+ ~IDSelectorBitmap() override {}
+};
+
+/** reverts the membership test of another selector */
+struct IDSelectorNot : IDSelector {
+ const IDSelector* sel;
+ IDSelectorNot(const IDSelector* sel) : sel(sel) {}
+ bool is_member(idx_t id) const final {
+ return !sel->is_member(id);
+ }
+ virtual ~IDSelectorNot() {}
+};
+
+/// selects all entries (useful for benchmarking)
+struct IDSelectorAll : IDSelector {
+ bool is_member(idx_t id) const final {
+ return true;
+ }
+ virtual ~IDSelectorAll() {}
+};
+
+/// does an AND operation on the the two given IDSelector's is_membership
+/// results.
+struct IDSelectorAnd : IDSelector {
+ const IDSelector* lhs;
+ const IDSelector* rhs;
+ IDSelectorAnd(const IDSelector* lhs, const IDSelector* rhs)
+ : lhs(lhs), rhs(rhs) {}
+ bool is_member(idx_t id) const final {
+ return lhs->is_member(id) && rhs->is_member(id);
+ }
+ virtual ~IDSelectorAnd() {}
+};
+
+/// does an OR operation on the the two given IDSelector's is_membership
+/// results.
+struct IDSelectorOr : IDSelector {
+ const IDSelector* lhs;
+ const IDSelector* rhs;
+ IDSelectorOr(const IDSelector* lhs, const IDSelector* rhs)
+ : lhs(lhs), rhs(rhs) {}
+ bool is_member(idx_t id) const final {
+ return lhs->is_member(id) || rhs->is_member(id);
+ }
+ virtual ~IDSelectorOr() {}
+};
+
+/// does an XOR operation on the the two given IDSelector's is_membership
+/// results.
+struct IDSelectorXOr : IDSelector {
+ const IDSelector* lhs;
+ const IDSelector* rhs;
+ IDSelectorXOr(const IDSelector* lhs, const IDSelector* rhs)
+ : lhs(lhs), rhs(rhs) {}
+ bool is_member(idx_t id) const final {
+ return lhs->is_member(id) ^ rhs->is_member(id);
+ }
+ virtual ~IDSelectorXOr() {}
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LocalSearchQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LocalSearchQuantizer.cpp
new file mode 100644
index 0000000..b5bcc3c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LocalSearchQuantizer.cpp
@@ -0,0 +1,846 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/LocalSearchQuantizer.h>
+
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+#include <random>
+
+#include <algorithm>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h> // BitstringWriter
+#include <faiss/utils/utils.h>
+
+#include <faiss/utils/approx_topk/approx_topk.h>
+
+// this is needed for prefetching
+#include <faiss/impl/platform_macros.h>
+
+#ifdef __AVX2__
+#include <xmmintrin.h>
+#endif
+
+extern "C" {
+// LU decomoposition of a general matrix
+void sgetrf_(
+ FINTEGER* m,
+ FINTEGER* n,
+ float* a,
+ FINTEGER* lda,
+ FINTEGER* ipiv,
+ FINTEGER* info);
+
+// generate inverse of a matrix given its LU decomposition
+void sgetri_(
+ FINTEGER* n,
+ float* a,
+ FINTEGER* lda,
+ FINTEGER* ipiv,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+// general matrix multiplication
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+
+// LU decomoposition of a general matrix
+void dgetrf_(
+ FINTEGER* m,
+ FINTEGER* n,
+ double* a,
+ FINTEGER* lda,
+ FINTEGER* ipiv,
+ FINTEGER* info);
+
+// generate inverse of a matrix given its LU decomposition
+void dgetri_(
+ FINTEGER* n,
+ double* a,
+ FINTEGER* lda,
+ FINTEGER* ipiv,
+ double* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+// general matrix multiplication
+int dgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const double* alpha,
+ const double* a,
+ FINTEGER* lda,
+ const double* b,
+ FINTEGER* ldb,
+ double* beta,
+ double* c,
+ FINTEGER* ldc);
+}
+
+namespace {
+
+void fmat_inverse(float* a, FINTEGER n) {
+ FINTEGER info;
+ FINTEGER lwork = n * n;
+ std::vector<FINTEGER> ipiv(n);
+ std::vector<float> workspace(lwork);
+
+ sgetrf_(&n, &n, a, &n, ipiv.data(), &info);
+ FAISS_THROW_IF_NOT(info == 0);
+ sgetri_(&n, a, &n, ipiv.data(), workspace.data(), &lwork, &info);
+ FAISS_THROW_IF_NOT(info == 0);
+}
+
+// c and a and b can overlap
+void dfvec_add(size_t d, const double* a, const float* b, double* c) {
+ for (size_t i = 0; i < d; i++) {
+ c[i] = a[i] + b[i];
+ }
+}
+
+void dmat_inverse(double* a, FINTEGER n) {
+ FINTEGER info;
+ FINTEGER lwork = n * n;
+ std::vector<FINTEGER> ipiv(n);
+ std::vector<double> workspace(lwork);
+
+ dgetrf_(&n, &n, a, &n, ipiv.data(), &info);
+ FAISS_THROW_IF_NOT(info == 0);
+ dgetri_(&n, a, &n, ipiv.data(), workspace.data(), &lwork, &info);
+ FAISS_THROW_IF_NOT(info == 0);
+}
+
+void random_int32(
+ std::vector<int32_t>& x,
+ int32_t min,
+ int32_t max,
+ std::mt19937& gen) {
+ std::uniform_int_distribution<int32_t> distrib(min, max);
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = distrib(gen);
+ }
+}
+
+} // anonymous namespace
+
+namespace faiss {
+
+lsq::LSQTimer lsq_timer;
+using lsq::LSQTimerScope;
+
+LocalSearchQuantizer::LocalSearchQuantizer(
+ size_t d,
+ size_t M,
+ size_t nbits,
+ Search_type_t search_type)
+ : AdditiveQuantizer(d, std::vector<size_t>(M, nbits), search_type) {
+ K = (1 << nbits);
+ std::srand(random_seed);
+}
+
+LocalSearchQuantizer::~LocalSearchQuantizer() {
+ delete icm_encoder_factory;
+}
+
+LocalSearchQuantizer::LocalSearchQuantizer() : LocalSearchQuantizer(0, 0, 0) {}
+
+void LocalSearchQuantizer::train(size_t n, const float* x) {
+ FAISS_THROW_IF_NOT(K == (1 << nbits[0]));
+ nperts = std::min(nperts, M);
+
+ lsq_timer.reset();
+ LSQTimerScope scope(&lsq_timer, "train");
+ if (verbose) {
+ printf("Training LSQ, with %zd subcodes on %zd %zdD vectors\n",
+ M,
+ n,
+ d);
+ }
+
+ // allocate memory for codebooks, size [M, K, d]
+ codebooks.resize(M * K * d);
+
+ // randomly initialize codes
+ std::mt19937 gen(random_seed);
+ std::vector<int32_t> codes(n * M); // [n, M]
+ random_int32(codes, 0, K - 1, gen);
+
+ // compute standard derivations of each dimension
+ std::vector<float> stddev(d, 0);
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < d; i++) {
+ float mean = 0;
+ for (size_t j = 0; j < n; j++) {
+ mean += x[j * d + i];
+ }
+ mean = mean / n;
+
+ float sum = 0;
+ for (size_t j = 0; j < n; j++) {
+ float xi = x[j * d + i] - mean;
+ sum += xi * xi;
+ }
+ stddev[i] = sqrtf(sum / n);
+ }
+
+ if (verbose) {
+ float obj = evaluate(codes.data(), x, n);
+ printf("Before training: obj = %lf\n", obj);
+ }
+
+ for (size_t i = 0; i < train_iters; i++) {
+ // 1. update codebooks given x and codes
+ // 2. add perturbation to codebooks (SR-D)
+ // 3. refine codes given x and codebooks using icm
+
+ // update codebooks
+ update_codebooks(x, codes.data(), n);
+
+ if (verbose) {
+ float obj = evaluate(codes.data(), x, n);
+ printf("iter %zd:\n", i);
+ printf("\tafter updating codebooks: obj = %lf\n", obj);
+ }
+
+ // SR-D: perturb codebooks
+ float T = pow((1.0f - (i + 1.0f) / train_iters), p);
+ perturb_codebooks(T, stddev, gen);
+
+ if (verbose) {
+ float obj = evaluate(codes.data(), x, n);
+ printf("\tafter perturbing codebooks: obj = %lf\n", obj);
+ }
+
+ // refine codes
+ icm_encode(codes.data(), x, n, train_ils_iters, gen);
+
+ if (verbose) {
+ float obj = evaluate(codes.data(), x, n);
+ printf("\tafter updating codes: obj = %lf\n", obj);
+ }
+ }
+
+ is_trained = true;
+ {
+ std::vector<float> x_recons(n * d);
+ std::vector<float> norms(n);
+ decode_unpacked(codes.data(), x_recons.data(), n);
+ fvec_norms_L2sqr(norms.data(), x_recons.data(), d, n);
+
+ train_norm(n, norms.data());
+ }
+
+ if (verbose) {
+ float obj = evaluate(codes.data(), x, n);
+ scope.finish();
+ printf("After training: obj = %lf\n", obj);
+
+ printf("Time statistic:\n");
+ for (const auto& it : lsq_timer.t) {
+ printf("\t%s time: %lf s\n", it.first.data(), it.second / 1000);
+ }
+ }
+}
+
+void LocalSearchQuantizer::perturb_codebooks(
+ float T,
+ const std::vector<float>& stddev,
+ std::mt19937& gen) {
+ LSQTimerScope scope(&lsq_timer, "perturb_codebooks");
+
+ std::vector<std::normal_distribution<float>> distribs;
+ for (size_t i = 0; i < d; i++) {
+ distribs.emplace_back(0.0f, stddev[i]);
+ }
+
+ for (size_t m = 0; m < M; m++) {
+ for (size_t k = 0; k < K; k++) {
+ for (size_t i = 0; i < d; i++) {
+ codebooks[m * K * d + k * d + i] += T * distribs[i](gen) / M;
+ }
+ }
+ }
+}
+
+void LocalSearchQuantizer::compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids) const {
+ FAISS_THROW_IF_NOT_MSG(is_trained, "LSQ is not trained yet.");
+
+ lsq_timer.reset();
+ LSQTimerScope scope(&lsq_timer, "encode");
+ if (verbose) {
+ printf("Encoding %zd vectors...\n", n);
+ }
+
+ std::vector<int32_t> codes(n * M);
+ std::mt19937 gen(random_seed);
+ random_int32(codes, 0, K - 1, gen);
+
+ icm_encode(codes.data(), x, n, encode_ils_iters, gen);
+ pack_codes(n, codes.data(), codes_out, -1, nullptr, centroids);
+
+ if (verbose) {
+ scope.finish();
+ printf("Time statistic:\n");
+ for (const auto& it : lsq_timer.t) {
+ printf("\t%s time: %lf s\n", it.first.data(), it.second / 1000);
+ }
+ }
+}
+
+/** update codebooks given x and codes
+ *
+ * Let B denote the sparse matrix of codes, size [n, M * K].
+ * Let C denote the codebooks, size [M * K, d].
+ * Let X denote the training vectors, size [n, d]
+ *
+ * objective function:
+ * L = (X - BC)^2
+ *
+ * To minimize L, we have:
+ * C = (B'B)^(-1)B'X
+ * where ' denote transposed
+ *
+ * Add a regularization term to make B'B inversible:
+ * C = (B'B + lambd * I)^(-1)B'X
+ */
+void LocalSearchQuantizer::update_codebooks(
+ const float* x,
+ const int32_t* codes,
+ size_t n) {
+ LSQTimerScope scope(&lsq_timer, "update_codebooks");
+
+ if (!update_codebooks_with_double) {
+ // allocate memory
+ // bb = B'B, bx = BX
+ std::vector<float> bb(M * K * M * K, 0.0f); // [M * K, M * K]
+ std::vector<float> bx(M * K * d, 0.0f); // [M * K, d]
+
+ // compute B'B
+ for (size_t i = 0; i < n; i++) {
+ for (size_t m = 0; m < M; m++) {
+ int32_t code1 = codes[i * M + m];
+ int32_t idx1 = m * K + code1;
+ bb[idx1 * M * K + idx1] += 1;
+
+ for (size_t m2 = m + 1; m2 < M; m2++) {
+ int32_t code2 = codes[i * M + m2];
+ int32_t idx2 = m2 * K + code2;
+ bb[idx1 * M * K + idx2] += 1;
+ bb[idx2 * M * K + idx1] += 1;
+ }
+ }
+ }
+
+ // add a regularization term to B'B
+ for (int64_t i = 0; i < M * K; i++) {
+ bb[i * (M * K) + i] += lambd;
+ }
+
+ // compute (B'B)^(-1)
+ fmat_inverse(bb.data(), M * K); // [M*K, M*K]
+
+ // compute BX
+ for (size_t i = 0; i < n; i++) {
+ for (size_t m = 0; m < M; m++) {
+ int32_t code = codes[i * M + m];
+ float* data = bx.data() + (m * K + code) * d;
+ fvec_add(d, data, x + i * d, data);
+ }
+ }
+
+ // compute C = (B'B)^(-1) @ BX
+ //
+ // NOTE: LAPACK use column major order
+ // out = alpha * op(A) * op(B) + beta * C
+ FINTEGER nrows_A = d;
+ FINTEGER ncols_A = M * K;
+
+ FINTEGER nrows_B = M * K;
+ FINTEGER ncols_B = M * K;
+
+ float alpha = 1.0f;
+ float beta = 0.0f;
+ sgemm_("Not Transposed",
+ "Not Transposed",
+ &nrows_A, // nrows of op(A)
+ &ncols_B, // ncols of op(B)
+ &ncols_A, // ncols of op(A)
+ &alpha,
+ bx.data(),
+ &nrows_A, // nrows of A
+ bb.data(),
+ &nrows_B, // nrows of B
+ &beta,
+ codebooks.data(),
+ &nrows_A); // nrows of output
+
+ } else {
+ // allocate memory
+ // bb = B'B, bx = BX
+ std::vector<double> bb(M * K * M * K, 0.0f); // [M * K, M * K]
+ std::vector<double> bx(M * K * d, 0.0f); // [M * K, d]
+
+ // compute B'B
+ for (size_t i = 0; i < n; i++) {
+ for (size_t m = 0; m < M; m++) {
+ int32_t code1 = codes[i * M + m];
+ int32_t idx1 = m * K + code1;
+ bb[idx1 * M * K + idx1] += 1;
+
+ for (size_t m2 = m + 1; m2 < M; m2++) {
+ int32_t code2 = codes[i * M + m2];
+ int32_t idx2 = m2 * K + code2;
+ bb[idx1 * M * K + idx2] += 1;
+ bb[idx2 * M * K + idx1] += 1;
+ }
+ }
+ }
+
+ // add a regularization term to B'B
+ for (int64_t i = 0; i < M * K; i++) {
+ bb[i * (M * K) + i] += lambd;
+ }
+
+ // compute (B'B)^(-1)
+ dmat_inverse(bb.data(), M * K); // [M*K, M*K]
+
+ // compute BX
+ for (size_t i = 0; i < n; i++) {
+ for (size_t m = 0; m < M; m++) {
+ int32_t code = codes[i * M + m];
+ double* data = bx.data() + (m * K + code) * d;
+ dfvec_add(d, data, x + i * d, data);
+ }
+ }
+
+ // compute C = (B'B)^(-1) @ BX
+ //
+ // NOTE: LAPACK use column major order
+ // out = alpha * op(A) * op(B) + beta * C
+ FINTEGER nrows_A = d;
+ FINTEGER ncols_A = M * K;
+
+ FINTEGER nrows_B = M * K;
+ FINTEGER ncols_B = M * K;
+
+ std::vector<double> d_codebooks(M * K * d);
+
+ double alpha = 1.0f;
+ double beta = 0.0f;
+ dgemm_("Not Transposed",
+ "Not Transposed",
+ &nrows_A, // nrows of op(A)
+ &ncols_B, // ncols of op(B)
+ &ncols_A, // ncols of op(A)
+ &alpha,
+ bx.data(),
+ &nrows_A, // nrows of A
+ bb.data(),
+ &nrows_B, // nrows of B
+ &beta,
+ d_codebooks.data(),
+ &nrows_A); // nrows of output
+
+ for (size_t i = 0; i < M * K * d; i++) {
+ codebooks[i] = (float)d_codebooks[i];
+ }
+ }
+}
+
+/** encode using iterative conditional mode
+ *
+ * iterative conditional mode:
+ * For every subcode ci (i = 1, ..., M) of a vector, we fix the other
+ * subcodes cj (j != i) and then find the optimal value of ci such
+ * that minimizing the objective function.
+
+ * objective function:
+ * L = (X - \sum cj)^2, j = 1, ..., M
+ * L = X^2 - 2X * \sum cj + (\sum cj)^2
+ *
+ * X^2 is negligable since it is the same for all possible value
+ * k of the m-th subcode.
+ *
+ * 2X * \sum cj is the unary term
+ * (\sum cj)^2 is the binary term
+ * These two terms can be precomputed and store in a look up table.
+ */
+void LocalSearchQuantizer::icm_encode(
+ int32_t* codes,
+ const float* x,
+ size_t n,
+ size_t ils_iters,
+ std::mt19937& gen) const {
+ LSQTimerScope scope(&lsq_timer, "icm_encode");
+
+ auto factory = icm_encoder_factory;
+ std::unique_ptr<lsq::IcmEncoder> icm_encoder;
+ if (factory == nullptr) {
+ icm_encoder.reset(lsq::IcmEncoderFactory().get(this));
+ } else {
+ icm_encoder.reset(factory->get(this));
+ }
+
+ // precompute binary terms for all chunks
+ icm_encoder->set_binary_term();
+
+ const size_t n_chunks = (n + chunk_size - 1) / chunk_size;
+ for (size_t i = 0; i < n_chunks; i++) {
+ size_t ni = std::min(chunk_size, n - i * chunk_size);
+
+ if (verbose) {
+ printf("\r\ticm encoding %zd/%zd ...", i * chunk_size + ni, n);
+ fflush(stdout);
+ if (i == n_chunks - 1 || i == 0) {
+ printf("\n");
+ }
+ }
+
+ const float* xi = x + i * chunk_size * d;
+ int32_t* codesi = codes + i * chunk_size * M;
+ icm_encoder->verbose = (verbose && i == 0);
+ icm_encoder->encode(codesi, xi, gen, ni, ils_iters);
+ }
+}
+
+void LocalSearchQuantizer::icm_encode_impl(
+ int32_t* codes,
+ const float* x,
+ const float* binaries,
+ std::mt19937& gen,
+ size_t n,
+ size_t ils_iters,
+ bool verbose) const {
+ std::vector<float> unaries(n * M * K); // [M, n, K]
+ compute_unary_terms(x, unaries.data(), n);
+
+ std::vector<int32_t> best_codes;
+ best_codes.assign(codes, codes + n * M);
+
+ std::vector<float> best_objs(n, 0.0f);
+ evaluate(codes, x, n, best_objs.data());
+
+ FAISS_THROW_IF_NOT(nperts <= M);
+ for (size_t iter1 = 0; iter1 < ils_iters; iter1++) {
+ // add perturbation to codes
+ perturb_codes(codes, n, gen);
+
+ icm_encode_step(codes, unaries.data(), binaries, n, icm_iters);
+
+ std::vector<float> icm_objs(n, 0.0f);
+ evaluate(codes, x, n, icm_objs.data());
+ size_t n_betters = 0;
+ float mean_obj = 0.0f;
+
+ // select the best code for every vector xi
+#pragma omp parallel for reduction(+ : n_betters, mean_obj)
+ for (int64_t i = 0; i < n; i++) {
+ if (icm_objs[i] < best_objs[i]) {
+ best_objs[i] = icm_objs[i];
+ memcpy(best_codes.data() + i * M,
+ codes + i * M,
+ sizeof(int32_t) * M);
+ n_betters += 1;
+ }
+ mean_obj += best_objs[i];
+ }
+ mean_obj /= n;
+
+ memcpy(codes, best_codes.data(), sizeof(int32_t) * n * M);
+
+ if (verbose) {
+ printf("\tils_iter %zd: obj = %lf, n_betters/n = %zd/%zd\n",
+ iter1,
+ mean_obj,
+ n_betters,
+ n);
+ }
+ } // loop ils_iters
+}
+
+void LocalSearchQuantizer::icm_encode_step(
+ int32_t* codes,
+ const float* unaries,
+ const float* binaries,
+ size_t n,
+ size_t n_iters) const {
+ FAISS_THROW_IF_NOT(M != 0 && K != 0);
+ FAISS_THROW_IF_NOT(binaries != nullptr);
+
+#pragma omp parallel for schedule(dynamic)
+ for (int64_t i = 0; i < n; i++) {
+ std::vector<float> objs(K);
+
+ for (size_t iter = 0; iter < n_iters; iter++) {
+ // condition on the m-th subcode
+ for (size_t m = 0; m < M; m++) {
+ // copy
+ auto u = unaries + m * n * K + i * K;
+ for (size_t code = 0; code < K; code++) {
+ objs[code] = u[code];
+ }
+
+ // compute objective function by adding unary
+ // and binary terms together
+ for (size_t other_m = 0; other_m < M; other_m++) {
+ if (other_m == m) {
+ continue;
+ }
+
+#ifdef __AVX2__
+ // TODO: add platform-independent compiler-independent
+ // prefetch utilities.
+ if (other_m + 1 < M) {
+ // do a single prefetch
+ int32_t code2 = codes[i * M + other_m + 1];
+ // for (int32_t code = 0; code < K; code += 64) {
+ int32_t code = 0;
+ {
+ size_t binary_idx = (other_m + 1) * M * K * K +
+ m * K * K + code2 * K + code;
+ _mm_prefetch(
+ (const char*)(binaries + binary_idx),
+ _MM_HINT_T0);
+ }
+ }
+#endif
+
+ for (int32_t code = 0; code < K; code++) {
+ int32_t code2 = codes[i * M + other_m];
+ size_t binary_idx = other_m * M * K * K + m * K * K +
+ code2 * K + code;
+ // binaries[m, other_m, code, code2].
+ // It is symmetric over (m <-> other_m)
+ // and (code <-> code2).
+ // So, replace the op with
+ // binaries[other_m, m, code2, code].
+ objs[code] += binaries[binary_idx];
+ }
+ }
+
+ // find the optimal value of the m-th subcode
+ float best_obj = HUGE_VALF;
+ int32_t best_code = 0;
+
+ // find one using SIMD. The following operation is similar
+ // to the search of the smallest element in objs
+ using C = CMax<float, int>;
+ HeapWithBuckets<C, 16, 1>::addn(
+ K, objs.data(), 1, &best_obj, &best_code);
+
+ // done
+ codes[i * M + m] = best_code;
+
+ } // loop M
+ }
+ }
+}
+void LocalSearchQuantizer::perturb_codes(
+ int32_t* codes,
+ size_t n,
+ std::mt19937& gen) const {
+ LSQTimerScope scope(&lsq_timer, "perturb_codes");
+
+ std::uniform_int_distribution<size_t> m_distrib(0, M - 1);
+ std::uniform_int_distribution<int32_t> k_distrib(0, K - 1);
+
+ for (size_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < nperts; j++) {
+ size_t m = m_distrib(gen);
+ codes[i * M + m] = k_distrib(gen);
+ }
+ }
+}
+
+void LocalSearchQuantizer::compute_binary_terms(float* binaries) const {
+ LSQTimerScope scope(&lsq_timer, "compute_binary_terms");
+
+#pragma omp parallel for
+ for (int64_t m12 = 0; m12 < M * M; m12++) {
+ size_t m1 = m12 / M;
+ size_t m2 = m12 % M;
+
+ for (size_t code1 = 0; code1 < K; code1++) {
+ for (size_t code2 = 0; code2 < K; code2++) {
+ const float* c1 = codebooks.data() + m1 * K * d + code1 * d;
+ const float* c2 = codebooks.data() + m2 * K * d + code2 * d;
+ float ip = fvec_inner_product(c1, c2, d);
+ // binaries[m1, m2, code1, code2] = ip * 2
+ binaries[m1 * M * K * K + m2 * K * K + code1 * K + code2] =
+ ip * 2;
+ }
+ }
+ }
+}
+
+void LocalSearchQuantizer::compute_unary_terms(
+ const float* x,
+ float* unaries, // [M, n, K]
+ size_t n) const {
+ LSQTimerScope scope(&lsq_timer, "compute_unary_terms");
+
+ // compute x * codebook^T for each codebook
+ //
+ // NOTE: LAPACK use column major order
+ // out = alpha * op(A) * op(B) + beta * C
+
+ for (size_t m = 0; m < M; m++) {
+ FINTEGER nrows_A = K;
+ FINTEGER ncols_A = d;
+
+ FINTEGER nrows_B = d;
+ FINTEGER ncols_B = n;
+
+ float alpha = -2.0f;
+ float beta = 0.0f;
+ sgemm_("Transposed",
+ "Not Transposed",
+ &nrows_A, // nrows of op(A)
+ &ncols_B, // ncols of op(B)
+ &ncols_A, // ncols of op(A)
+ &alpha,
+ codebooks.data() + m * K * d,
+ &ncols_A, // nrows of A
+ x,
+ &nrows_B, // nrows of B
+ &beta,
+ unaries + m * n * K,
+ &nrows_A); // nrows of output
+ }
+
+ std::vector<float> norms(M * K);
+ fvec_norms_L2sqr(norms.data(), codebooks.data(), d, M * K);
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++) {
+ for (size_t m = 0; m < M; m++) {
+ float* u = unaries + m * n * K + i * K;
+ fvec_add(K, u, norms.data() + m * K, u);
+ }
+ }
+}
+
+float LocalSearchQuantizer::evaluate(
+ const int32_t* codes,
+ const float* x,
+ size_t n,
+ float* objs) const {
+ LSQTimerScope scope(&lsq_timer, "evaluate");
+
+ // decode
+ std::vector<float> decoded_x(n * d, 0.0f);
+ float obj = 0.0f;
+
+#pragma omp parallel for reduction(+ : obj)
+ for (int64_t i = 0; i < n; i++) {
+ const auto code = codes + i * M;
+ const auto decoded_i = decoded_x.data() + i * d;
+ for (size_t m = 0; m < M; m++) {
+ // c = codebooks[m, code[m]]
+ const auto c = codebooks.data() + m * K * d + code[m] * d;
+ fvec_add(d, decoded_i, c, decoded_i);
+ }
+
+ float err = faiss::fvec_L2sqr(x + i * d, decoded_i, d);
+ obj += err;
+
+ if (objs) {
+ objs[i] = err;
+ }
+ }
+
+ obj = obj / n;
+ return obj;
+}
+
+namespace lsq {
+
+IcmEncoder::IcmEncoder(const LocalSearchQuantizer* lsq)
+ : verbose(false), lsq(lsq) {}
+
+void IcmEncoder::set_binary_term() {
+ auto M = lsq->M;
+ auto K = lsq->K;
+ binaries.resize(M * M * K * K);
+ lsq->compute_binary_terms(binaries.data());
+}
+
+void IcmEncoder::encode(
+ int32_t* codes,
+ const float* x,
+ std::mt19937& gen,
+ size_t n,
+ size_t ils_iters) const {
+ lsq->icm_encode_impl(codes, x, binaries.data(), gen, n, ils_iters, verbose);
+}
+
+double LSQTimer::get(const std::string& name) {
+ if (t.count(name) == 0) {
+ return 0.0;
+ } else {
+ return t[name];
+ }
+}
+
+void LSQTimer::add(const std::string& name, double delta) {
+ if (t.count(name) == 0) {
+ t[name] = delta;
+ } else {
+ t[name] += delta;
+ }
+}
+
+void LSQTimer::reset() {
+ t.clear();
+}
+
+LSQTimerScope::LSQTimerScope(LSQTimer* timer, std::string name)
+ : timer(timer), name(name), finished(false) {
+ t0 = getmillisecs();
+}
+
+void LSQTimerScope::finish() {
+ if (!finished) {
+ auto delta = getmillisecs() - t0;
+ timer->add(name, delta);
+ finished = true;
+ }
+}
+
+LSQTimerScope::~LSQTimerScope() {
+ finish();
+}
+
+} // namespace lsq
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LocalSearchQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LocalSearchQuantizer.h
new file mode 100644
index 0000000..39d7d6c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LocalSearchQuantizer.h
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+#include <random>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <faiss/impl/AdditiveQuantizer.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+namespace lsq {
+
+struct IcmEncoderFactory;
+
+} // namespace lsq
+
+/** Implementation of LSQ/LSQ++ described in the following two papers:
+ *
+ * Revisiting additive quantization
+ * Julieta Martinez, et al. ECCV 2016
+ *
+ * LSQ++: Lower running time and higher recall in multi-codebook quantization
+ * Julieta Martinez, et al. ECCV 2018
+ *
+ * This implementation is mostly translated from the Julia implementations
+ * by Julieta Martinez:
+ * (https://github.com/una-dinosauria/local-search-quantization,
+ * https://github.com/una-dinosauria/Rayuela.jl)
+ *
+ * The trained codes are stored in `codebooks` which is called
+ * `centroids` in PQ and RQ.
+ */
+struct LocalSearchQuantizer : AdditiveQuantizer {
+ size_t K; ///< number of codes per codebook
+
+ size_t train_iters = 25; ///< number of iterations in training
+ size_t encode_ils_iters = 16; ///< iterations of local search in encoding
+ size_t train_ils_iters = 8; ///< iterations of local search in training
+ size_t icm_iters = 4; ///< number of iterations in icm
+
+ float p = 0.5f; ///< temperature factor
+ float lambd = 1e-2f; ///< regularization factor
+
+ size_t chunk_size = 10000; ///< nb of vectors to encode at a time
+
+ int random_seed = 0x12345; ///< seed for random generator
+ size_t nperts = 4; ///< number of perturbation in each code
+
+ ///< if non-NULL, use this encoder to encode (owned by the object)
+ lsq::IcmEncoderFactory* icm_encoder_factory = nullptr;
+
+ bool update_codebooks_with_double = true;
+
+ LocalSearchQuantizer(
+ size_t d, /* dimensionality of the input vectors */
+ size_t M, /* number of subquantizers */
+ size_t nbits, /* number of bit per subvector index */
+ Search_type_t search_type =
+ ST_decompress); /* determines the storage type */
+
+ LocalSearchQuantizer();
+
+ ~LocalSearchQuantizer() override;
+
+ // Train the local search quantizer
+ void train(size_t n, const float* x) override;
+
+ /** Encode a set of vectors
+ *
+ * @param x vectors to encode, size n * d
+ * @param codes output codes, size n * code_size
+ * @param n number of vectors
+ * @param centroids centroids to be added to x, size n * d
+ */
+ void compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes,
+ size_t n,
+ const float* centroids = nullptr) const override;
+
+ /** Update codebooks given encodings
+ *
+ * @param x training vectors, size n * d
+ * @param codes encoded training vectors, size n * M
+ * @param n number of vectors
+ */
+ void update_codebooks(const float* x, const int32_t* codes, size_t n);
+
+ /** Encode vectors given codebooks using iterative conditional mode (icm).
+ *
+ * @param codes output codes, size n * M
+ * @param x vectors to encode, size n * d
+ * @param n number of vectors
+ * @param ils_iters number of iterations of iterative local search
+ */
+ void icm_encode(
+ int32_t* codes,
+ const float* x,
+ size_t n,
+ size_t ils_iters,
+ std::mt19937& gen) const;
+
+ void icm_encode_impl(
+ int32_t* codes,
+ const float* x,
+ const float* unaries,
+ std::mt19937& gen,
+ size_t n,
+ size_t ils_iters,
+ bool verbose) const;
+
+ void icm_encode_step(
+ int32_t* codes,
+ const float* unaries,
+ const float* binaries,
+ size_t n,
+ size_t n_iters) const;
+
+ /** Add some perturbation to codes
+ *
+ * @param codes codes to be perturbed, size n * M
+ * @param n number of vectors
+ */
+ void perturb_codes(int32_t* codes, size_t n, std::mt19937& gen) const;
+
+ /** Add some perturbation to codebooks
+ *
+ * @param T temperature of simulated annealing
+ * @param stddev standard derivations of each dimension in training data
+ */
+ void perturb_codebooks(
+ float T,
+ const std::vector<float>& stddev,
+ std::mt19937& gen);
+
+ /** Compute binary terms
+ *
+ * @param binaries binary terms, size M * M * K * K
+ */
+ void compute_binary_terms(float* binaries) const;
+
+ /** Compute unary terms
+ *
+ * @param n number of vectors
+ * @param x vectors to encode, size n * d
+ * @param unaries unary terms, size n * M * K
+ */
+ void compute_unary_terms(const float* x, float* unaries, size_t n) const;
+
+ /** Helper function to compute reconstruction error
+ *
+ * @param codes encoded codes, size n * M
+ * @param x vectors to encode, size n * d
+ * @param n number of vectors
+ * @param objs if it is not null, store reconstruction
+ error of each vector into it, size n
+ */
+ float evaluate(
+ const int32_t* codes,
+ const float* x,
+ size_t n,
+ float* objs = nullptr) const;
+};
+
+namespace lsq {
+
+struct IcmEncoder {
+ std::vector<float> binaries;
+
+ bool verbose;
+
+ const LocalSearchQuantizer* lsq;
+
+ explicit IcmEncoder(const LocalSearchQuantizer* lsq);
+
+ virtual ~IcmEncoder() {}
+
+ ///< compute binary terms
+ virtual void set_binary_term();
+
+ /** Encode vectors given codebooks
+ *
+ * @param codes output codes, size n * M
+ * @param x vectors to encode, size n * d
+ * @param gen random generator
+ * @param n number of vectors
+ * @param ils_iters number of iterations of iterative local search
+ */
+ virtual void encode(
+ int32_t* codes,
+ const float* x,
+ std::mt19937& gen,
+ size_t n,
+ size_t ils_iters) const;
+};
+
+struct IcmEncoderFactory {
+ virtual IcmEncoder* get(const LocalSearchQuantizer* lsq) {
+ return new IcmEncoder(lsq);
+ }
+ virtual ~IcmEncoderFactory() {}
+};
+
+/** A helper struct to count consuming time during training.
+ * It is NOT thread-safe.
+ */
+struct LSQTimer {
+ std::unordered_map<std::string, double> t;
+
+ LSQTimer() {
+ reset();
+ }
+
+ double get(const std::string& name);
+
+ void add(const std::string& name, double delta);
+
+ void reset();
+};
+
+struct LSQTimerScope {
+ double t0;
+ LSQTimer* timer;
+ std::string name;
+ bool finished;
+
+ LSQTimerScope(LSQTimer* timer, std::string name);
+
+ void finish();
+
+ ~LSQTimerScope();
+};
+
+} // namespace lsq
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LookupTableScaler.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LookupTableScaler.h
new file mode 100644
index 0000000..015bcde
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/LookupTableScaler.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+
+#include <faiss/utils/simdlib.h>
+
+/*******************************************
+ * The Scaler objects are used to specialize the handling of the
+ * norm components in Additive quantizer fast-scan.
+ ********************************************/
+
+namespace faiss {
+
+/// no-op handler
+struct DummyScaler {
+ static constexpr int nscale = 0;
+
+ inline simd32uint8 lookup(const simd32uint8&, const simd32uint8&) const {
+ FAISS_THROW_MSG("DummyScaler::lookup should not be called.");
+ return simd32uint8(0);
+ }
+
+ inline simd16uint16 scale_lo(const simd32uint8&) const {
+ FAISS_THROW_MSG("DummyScaler::scale_lo should not be called.");
+ return simd16uint16(0);
+ }
+
+ inline simd16uint16 scale_hi(const simd32uint8&) const {
+ FAISS_THROW_MSG("DummyScaler::scale_hi should not be called.");
+ return simd16uint16(0);
+ }
+
+#ifdef __AVX512F__
+ inline simd64uint8 lookup(const simd64uint8&, const simd64uint8&) const {
+ FAISS_THROW_MSG("DummyScaler::lookup should not be called.");
+ return simd64uint8(0);
+ }
+
+ inline simd32uint16 scale_lo(const simd64uint8&) const {
+ FAISS_THROW_MSG("DummyScaler::scale_lo should not be called.");
+ return simd32uint16(0);
+ }
+
+ inline simd32uint16 scale_hi(const simd64uint8&) const {
+ FAISS_THROW_MSG("DummyScaler::scale_hi should not be called.");
+ return simd32uint16(0);
+ }
+#endif
+
+ template <class dist_t>
+ inline dist_t scale_one(const dist_t&) const {
+ FAISS_THROW_MSG("DummyScaler::scale_one should not be called.");
+ return 0;
+ }
+};
+
+/// consumes 2x4 bits to encode a norm as a scalar additive quantizer
+/// the norm is scaled because its range if larger than other components
+struct NormTableScaler {
+ static constexpr int nscale = 2;
+ int scale_int;
+ simd16uint16 scale_simd;
+
+ explicit NormTableScaler(int scale) : scale_int(scale), scale_simd(scale) {}
+
+ inline simd32uint8 lookup(const simd32uint8& lut, const simd32uint8& c)
+ const {
+ return lut.lookup_2_lanes(c);
+ }
+
+ inline simd16uint16 scale_lo(const simd32uint8& res) const {
+ return simd16uint16(res) * scale_simd;
+ }
+
+ inline simd16uint16 scale_hi(const simd32uint8& res) const {
+ return (simd16uint16(res) >> 8) * scale_simd;
+ }
+
+#ifdef __AVX512F__
+ inline simd64uint8 lookup(const simd64uint8& lut, const simd64uint8& c)
+ const {
+ return lut.lookup_4_lanes(c);
+ }
+
+ inline simd32uint16 scale_lo(const simd64uint8& res) const {
+ auto scale_simd_wide = simd32uint16(scale_simd, scale_simd);
+ return simd32uint16(res) * scale_simd_wide;
+ }
+
+ inline simd32uint16 scale_hi(const simd64uint8& res) const {
+ auto scale_simd_wide = simd32uint16(scale_simd, scale_simd);
+ return (simd32uint16(res) >> 8) * scale_simd_wide;
+ }
+#endif
+
+ // for non-SIMD implem 2, 3, 4
+ template <class dist_t>
+ inline dist_t scale_one(const dist_t& x) const {
+ return x * scale_int;
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NNDescent.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NNDescent.cpp
new file mode 100644
index 0000000..9a61651
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NNDescent.cpp
@@ -0,0 +1,499 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/NNDescent.h>
+
+#include <mutex>
+#include <string>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+
+namespace faiss {
+
+using LockGuard = std::lock_guard<std::mutex>;
+
+namespace nndescent {
+
+void gen_random(std::mt19937& rng, int* addr, const int size, const int N);
+
+Nhood::Nhood(int l, int s, std::mt19937& rng, int N) {
+ M = s;
+ nn_new.resize(s * 2);
+ gen_random(rng, nn_new.data(), (int)nn_new.size(), N);
+}
+
+/// Copy operator
+Nhood& Nhood::operator=(const Nhood& other) {
+ M = other.M;
+ std::copy(
+ other.nn_new.begin(),
+ other.nn_new.end(),
+ std::back_inserter(nn_new));
+ nn_new.reserve(other.nn_new.capacity());
+ pool.reserve(other.pool.capacity());
+ return *this;
+}
+
+/// Copy constructor
+Nhood::Nhood(const Nhood& other) {
+ M = other.M;
+ std::copy(
+ other.nn_new.begin(),
+ other.nn_new.end(),
+ std::back_inserter(nn_new));
+ nn_new.reserve(other.nn_new.capacity());
+ pool.reserve(other.pool.capacity());
+}
+
+/// Insert a point into the candidate pool
+void Nhood::insert(int id, float dist) {
+ LockGuard guard(lock);
+ if (dist > pool.front().distance)
+ return;
+ for (int i = 0; i < pool.size(); i++) {
+ if (id == pool[i].id)
+ return;
+ }
+ if (pool.size() < pool.capacity()) {
+ pool.push_back(Neighbor(id, dist, true));
+ std::push_heap(pool.begin(), pool.end());
+ } else {
+ std::pop_heap(pool.begin(), pool.end());
+ pool[pool.size() - 1] = Neighbor(id, dist, true);
+ std::push_heap(pool.begin(), pool.end());
+ }
+}
+
+/// In local join, two objects are compared only if at least
+/// one of them is new.
+template <typename C>
+void Nhood::join(C callback) const {
+ for (int const i : nn_new) {
+ for (int const j : nn_new) {
+ if (i < j) {
+ callback(i, j);
+ }
+ }
+ for (int j : nn_old) {
+ callback(i, j);
+ }
+ }
+}
+
+void gen_random(std::mt19937& rng, int* addr, const int size, const int N) {
+ for (int i = 0; i < size; ++i) {
+ addr[i] = rng() % (N - size);
+ }
+ std::sort(addr, addr + size);
+ for (int i = 1; i < size; ++i) {
+ if (addr[i] <= addr[i - 1]) {
+ addr[i] = addr[i - 1] + 1;
+ }
+ }
+ int off = rng() % N;
+ for (int i = 0; i < size; ++i) {
+ addr[i] = (addr[i] + off) % N;
+ }
+}
+
+// Insert a new point into the candidate pool in ascending order
+int insert_into_pool(Neighbor* addr, int size, Neighbor nn) {
+ // find the location to insert
+ int left = 0, right = size - 1;
+ if (addr[left].distance > nn.distance) {
+ memmove((char*)&addr[left + 1], &addr[left], size * sizeof(Neighbor));
+ addr[left] = nn;
+ return left;
+ }
+ if (addr[right].distance < nn.distance) {
+ addr[size] = nn;
+ return size;
+ }
+ while (left < right - 1) {
+ int mid = (left + right) / 2;
+ if (addr[mid].distance > nn.distance)
+ right = mid;
+ else
+ left = mid;
+ }
+ // check equal ID
+
+ while (left > 0) {
+ if (addr[left].distance < nn.distance)
+ break;
+ if (addr[left].id == nn.id)
+ return size + 1;
+ left--;
+ }
+ if (addr[left].id == nn.id || addr[right].id == nn.id)
+ return size + 1;
+ memmove((char*)&addr[right + 1],
+ &addr[right],
+ (size - right) * sizeof(Neighbor));
+ addr[right] = nn;
+ return right;
+}
+
+} // namespace nndescent
+
+using namespace nndescent;
+
+constexpr int NUM_EVAL_POINTS = 100;
+
+NNDescent::NNDescent(const int d, const int K) : K(K), d(d) {
+ L = K + 50;
+}
+
+NNDescent::~NNDescent() {}
+
+void NNDescent::join(DistanceComputer& qdis) {
+ idx_t check_period = InterruptCallback::get_period_hint(d * search_L);
+ for (idx_t i0 = 0; i0 < (idx_t)ntotal; i0 += check_period) {
+ idx_t i1 = std::min(i0 + check_period, (idx_t)ntotal);
+#pragma omp parallel for default(shared) schedule(dynamic, 100)
+ for (idx_t n = i0; n < i1; n++) {
+ graph[n].join([&](int i, int j) {
+ if (i != j) {
+ float dist = qdis.symmetric_dis(i, j);
+ graph[i].insert(j, dist);
+ graph[j].insert(i, dist);
+ }
+ });
+ }
+ InterruptCallback::check();
+ }
+}
+
+/// Sample neighbors for each node to peform local join later
+/// Store them in nn_new and nn_old
+void NNDescent::update() {
+ // Step 1.
+ // Clear all nn_new and nn_old
+#pragma omp parallel for
+ for (int i = 0; i < ntotal; i++) {
+ std::vector<int>().swap(graph[i].nn_new);
+ std::vector<int>().swap(graph[i].nn_old);
+ }
+
+ // Step 2.
+ // Compute the number of neighbors which is new i.e. flag is true
+ // in the candidate pool. This must not exceed the sample number S.
+ // That means We only select S new neighbors.
+#pragma omp parallel for
+ for (int n = 0; n < ntotal; ++n) {
+ auto& nn = graph[n];
+ std::sort(nn.pool.begin(), nn.pool.end());
+
+ if (nn.pool.size() > L)
+ nn.pool.resize(L);
+ nn.pool.reserve(L); // keep the pool size be L
+
+ int maxl = std::min(nn.M + S, (int)nn.pool.size());
+ int c = 0;
+ int l = 0;
+
+ while ((l < maxl) && (c < S)) {
+ if (nn.pool[l].flag) {
+ ++c;
+ }
+ ++l;
+ }
+ nn.M = l;
+ }
+
+ // Step 3.
+ // Find reverse links for each node
+ // Randomly choose R reverse links.
+#pragma omp parallel
+ {
+ std::mt19937 rng(random_seed * 5081 + omp_get_thread_num());
+#pragma omp for
+ for (int n = 0; n < ntotal; ++n) {
+ auto& node = graph[n];
+ auto& nn_new = node.nn_new;
+ auto& nn_old = node.nn_old;
+
+ for (int l = 0; l < node.M; ++l) {
+ auto& nn = node.pool[l];
+ auto& other = graph[nn.id]; // the other side of the edge
+
+ if (nn.flag) { // the node is inserted newly
+ // push the neighbor into nn_new
+ nn_new.push_back(nn.id);
+ // push itself into other.rnn_new if it is not in
+ // the candidate pool of the other side
+ if (nn.distance > other.pool.back().distance) {
+ LockGuard guard(other.lock);
+ if (other.rnn_new.size() < R) {
+ other.rnn_new.push_back(n);
+ } else {
+ int pos = rng() % R;
+ other.rnn_new[pos] = n;
+ }
+ }
+ nn.flag = false;
+
+ } else { // the node is old
+ // push the neighbor into nn_old
+ nn_old.push_back(nn.id);
+ // push itself into other.rnn_old if it is not in
+ // the candidate pool of the other side
+ if (nn.distance > other.pool.back().distance) {
+ LockGuard guard(other.lock);
+ if (other.rnn_old.size() < R) {
+ other.rnn_old.push_back(n);
+ } else {
+ int pos = rng() % R;
+ other.rnn_old[pos] = n;
+ }
+ }
+ }
+ }
+ // make heap to join later (in join() function)
+ std::make_heap(node.pool.begin(), node.pool.end());
+ }
+ }
+
+ // Step 4.
+ // Combine the forward and the reverse links
+ // R = 0 means no reverse links are used.
+#pragma omp parallel for
+ for (int i = 0; i < ntotal; ++i) {
+ auto& nn_new = graph[i].nn_new;
+ auto& nn_old = graph[i].nn_old;
+ auto& rnn_new = graph[i].rnn_new;
+ auto& rnn_old = graph[i].rnn_old;
+
+ nn_new.insert(nn_new.end(), rnn_new.begin(), rnn_new.end());
+ nn_old.insert(nn_old.end(), rnn_old.begin(), rnn_old.end());
+ if (nn_old.size() > R * 2) {
+ nn_old.resize(R * 2);
+ nn_old.reserve(R * 2);
+ }
+
+ std::vector<int>().swap(graph[i].rnn_new);
+ std::vector<int>().swap(graph[i].rnn_old);
+ }
+}
+
+void NNDescent::nndescent(DistanceComputer& qdis, bool verbose) {
+ int num_eval_points = std::min(NUM_EVAL_POINTS, ntotal);
+ std::vector<int> eval_points(num_eval_points);
+ std::vector<std::vector<int>> acc_eval_set(num_eval_points);
+ std::mt19937 rng(random_seed * 6577 + omp_get_thread_num());
+ gen_random(rng, eval_points.data(), eval_points.size(), ntotal);
+ generate_eval_set(qdis, eval_points, acc_eval_set, ntotal);
+ for (int it = 0; it < iter; it++) {
+ join(qdis);
+ update();
+
+ if (verbose) {
+ float recall = eval_recall(eval_points, acc_eval_set);
+ printf("Iter: %d, recall@%ld: %lf\n", it, K, recall);
+ }
+ }
+ printf("Final graph: %ld\n", final_graph.size());
+}
+
+/// Sample a small number of points to evaluate the quality of KNNG built
+void NNDescent::generate_eval_set(
+ DistanceComputer& qdis,
+ std::vector<int>& c,
+ std::vector<std::vector<int>>& v,
+ int N) {
+#pragma omp parallel for
+ for (int i = 0; i < c.size(); i++) {
+ std::vector<Neighbor> tmp;
+ for (int j = 0; j < N; j++) {
+ if (c[i] == j) {
+ continue; // skip itself
+ }
+ float dist = qdis.symmetric_dis(c[i], j);
+ tmp.push_back(Neighbor(j, dist, true));
+ }
+
+ std::partial_sort(tmp.begin(), tmp.begin() + K, tmp.end());
+ for (int j = 0; j < K; j++) {
+ v[i].push_back(tmp[j].id);
+ }
+ }
+}
+
+/// Evaluate the quality of KNNG built
+float NNDescent::eval_recall(
+ std::vector<int>& eval_points,
+ std::vector<std::vector<int>>& acc_eval_set) {
+ float mean_acc = 0.0f;
+ for (size_t i = 0; i < eval_points.size(); i++) {
+ float acc = 0;
+ std::vector<Neighbor>& g = graph[eval_points[i]].pool;
+ std::vector<int>& v = acc_eval_set[i];
+ for (size_t j = 0; j < g.size(); j++) {
+ for (size_t k = 0; k < v.size(); k++) {
+ if (g[j].id == v[k]) {
+ acc++;
+ break;
+ }
+ }
+ }
+ mean_acc += acc / v.size();
+ }
+ return mean_acc / eval_points.size();
+}
+
+/// Initialize the KNN graph randomly
+void NNDescent::init_graph(DistanceComputer& qdis) {
+ graph.reserve(ntotal);
+ {
+ std::mt19937 rng(random_seed * 6007);
+ for (int i = 0; i < ntotal; i++) {
+ graph.push_back(Nhood(L, S, rng, (int)ntotal));
+ }
+ }
+#pragma omp parallel
+ {
+ std::mt19937 rng(random_seed * 7741 + omp_get_thread_num());
+#pragma omp for
+ for (int i = 0; i < ntotal; i++) {
+ std::vector<int> tmp(S);
+
+ gen_random(rng, tmp.data(), S, ntotal);
+
+ for (int j = 0; j < S; j++) {
+ int id = tmp[j];
+ if (id == i) {
+ continue;
+ }
+ float dist = qdis.symmetric_dis(i, id);
+
+ graph[i].pool.push_back(Neighbor(id, dist, true));
+ }
+ std::make_heap(graph[i].pool.begin(), graph[i].pool.end());
+ graph[i].pool.reserve(L);
+ }
+ }
+}
+
+void NNDescent::build(DistanceComputer& qdis, const int n, bool verbose) {
+ FAISS_THROW_IF_NOT_MSG(L >= K, "L should be >= K in NNDescent.build");
+ FAISS_THROW_IF_NOT_FMT(
+ n > NUM_EVAL_POINTS,
+ "NNDescent.build cannot build a graph smaller than %d",
+ int(NUM_EVAL_POINTS));
+
+ if (verbose) {
+ printf("Parameters: K=%ld, S=%d, R=%d, L=%d, iter=%d\n",
+ K,
+ S,
+ R,
+ L,
+ iter);
+ }
+
+ ntotal = n;
+ init_graph(qdis);
+ final_graph.resize(uint64_t(ntotal) * K);
+ nndescent(qdis, verbose);
+
+ // Store the neighbor link structure into final_graph
+ // Clear the old graph
+ for (idx_t i = 0; i < ntotal; i++) {
+ std::sort(graph[i].pool.begin(), graph[i].pool.end());
+ for (int j = 0; j < K; j++) {
+ FAISS_ASSERT(graph[i].pool[j].id < ntotal);
+ final_graph[i * K + j] = graph[i].pool[j].id;
+ }
+ }
+ printf("swapping graph\n");
+ std::vector<Nhood>().swap(graph);
+ printf("swapped graph\n");
+ has_built = true;
+
+ if (verbose) {
+ printf("Added %d points into the index\n", ntotal);
+ }
+}
+
+void NNDescent::search(
+ DistanceComputer& qdis,
+ const int topk,
+ idx_t* indices,
+ float* dists,
+ VisitedTable& vt) const {
+ FAISS_THROW_IF_NOT_MSG(has_built, "The index is not build yet.");
+ int L_2 = std::max(search_L, topk);
+
+ // candidate pool, the K best items is the result.
+ std::vector<Neighbor> retset(L_2 + 1);
+
+ // Randomly choose L_2 points to initialize the candidate pool
+ std::vector<int> init_ids(L_2);
+ std::mt19937 rng(random_seed);
+
+ gen_random(rng, init_ids.data(), L_2, ntotal);
+ for (int i = 0; i < L_2; i++) {
+ int id = init_ids[i];
+ float dist = qdis(id);
+ retset[i] = Neighbor(id, dist, true);
+ }
+
+ // Maintain the candidate pool in ascending order
+ std::sort(retset.begin(), retset.begin() + L_2);
+
+ int k = 0;
+
+ // Stop until the smallest position updated is >= L_2
+ while (k < L_2) {
+ int nk = L_2;
+
+ if (retset[k].flag) {
+ retset[k].flag = false;
+ int n = retset[k].id;
+
+ for (int m = 0; m < K; ++m) {
+ int id = final_graph[n * K + m];
+ if (vt.get(id)) {
+ continue;
+ }
+
+ vt.set(id);
+ float dist = qdis(id);
+ if (dist >= retset[L_2 - 1].distance) {
+ continue;
+ }
+
+ Neighbor nn(id, dist, true);
+ int r = insert_into_pool(retset.data(), L_2, nn);
+
+ if (r < nk)
+ nk = r;
+ }
+ }
+ if (nk <= k) {
+ k = nk;
+ } else {
+ ++k;
+ }
+ }
+ for (size_t i = 0; i < topk; i++) {
+ indices[i] = retset[i].id;
+ dists[i] = retset[i].distance;
+ }
+
+ vt.advance();
+}
+
+void NNDescent::reset() {
+ has_built = false;
+ ntotal = 0;
+ final_graph.resize(0);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NNDescent.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NNDescent.h
new file mode 100644
index 0000000..e4b93da
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NNDescent.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <algorithm>
+#include <mutex>
+#include <queue>
+#include <random>
+#include <unordered_set>
+#include <vector>
+
+#include <omp.h>
+
+#include <faiss/Index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/random.h>
+
+namespace faiss {
+
+/** Implementation of NNDescent which is one of the most popular
+ * KNN graph building algorithms
+ *
+ * Efficient K-Nearest Neighbor Graph Construction for Generic
+ * Similarity Measures
+ *
+ * Dong, Wei, Charikar Moses, and Kai Li, WWW 2011
+ *
+ * This implmentation is heavily influenced by the efanna
+ * implementation by Cong Fu and the KGraph library by Wei Dong
+ * (https://github.com/ZJULearning/efanna_graph)
+ * (https://github.com/aaalgo/kgraph)
+ *
+ * The NNDescent object stores only the neighbor link structure,
+ * see IndexNNDescent.h for the full index object.
+ */
+
+struct VisitedTable;
+struct DistanceComputer;
+
+namespace nndescent {
+
+struct Neighbor {
+ int id;
+ float distance;
+ bool flag;
+
+ Neighbor() = default;
+ Neighbor(int id, float distance, bool f)
+ : id(id), distance(distance), flag(f) {}
+
+ inline bool operator<(const Neighbor& other) const {
+ return distance < other.distance;
+ }
+};
+
+struct Nhood {
+ std::mutex lock;
+ std::vector<Neighbor> pool; // candidate pool (a max heap)
+ int M; // number of new neighbors to be operated
+
+ std::vector<int> nn_old; // old neighbors
+ std::vector<int> nn_new; // new neighbors
+ std::vector<int> rnn_old; // reverse old neighbors
+ std::vector<int> rnn_new; // reverse new neighbors
+
+ Nhood() = default;
+
+ Nhood(int l, int s, std::mt19937& rng, int N);
+
+ Nhood& operator=(const Nhood& other);
+
+ Nhood(const Nhood& other);
+
+ void insert(int id, float dist);
+
+ template <typename C>
+ void join(C callback) const;
+};
+
+} // namespace nndescent
+
+struct NNDescent {
+ using storage_idx_t = int;
+
+ using KNNGraph = std::vector<nndescent::Nhood>;
+
+ explicit NNDescent(const int d, const int K);
+
+ ~NNDescent();
+
+ void build(DistanceComputer& qdis, const int n, bool verbose);
+
+ void search(
+ DistanceComputer& qdis,
+ const int topk,
+ idx_t* indices,
+ float* dists,
+ VisitedTable& vt) const;
+
+ void reset();
+
+ /// Initialize the KNN graph randomly
+ void init_graph(DistanceComputer& qdis);
+
+ /// Perform NNDescent algorithm
+ void nndescent(DistanceComputer& qdis, bool verbose);
+
+ /// Perform local join on each node
+ void join(DistanceComputer& qdis);
+
+ /// Sample new neighbors for each node to peform local join later
+ void update();
+
+ /// Sample a small number of points to evaluate the quality of KNNG built
+ void generate_eval_set(
+ DistanceComputer& qdis,
+ std::vector<int>& c,
+ std::vector<std::vector<int>>& v,
+ int N);
+
+ /// Evaluate the quality of KNNG built
+ float eval_recall(
+ std::vector<int>& ctrl_points,
+ std::vector<std::vector<int>>& acc_eval_set);
+
+ bool has_built = false;
+
+ int S = 10; // number of sample neighbors to be updated for each node
+ int R = 100; // size of reverse links, 0 means the reverse links will not be
+ // used
+ int iter = 10; // number of iterations to iterate over
+ int search_L = 0; // size of candidate pool in searching
+ int random_seed = 2021; // random seed for generators
+
+ idx_t K; // K in KNN graph
+ int d; // dimensions
+ int L; // size of the candidate pool in building
+
+ int ntotal = 0;
+
+ KNNGraph graph;
+ std::vector<int> final_graph;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NSG.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NSG.cpp
new file mode 100644
index 0000000..8a09193
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NSG.cpp
@@ -0,0 +1,775 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/NSG.h>
+
+#include <algorithm>
+#include <memory>
+#include <mutex>
+#include <stack>
+#include <unordered_set>
+
+#include <faiss/impl/DistanceComputer.h>
+
+namespace faiss {
+
+NSGStats nsg_stats;
+
+namespace {
+
+using LockGuard = std::lock_guard<std::mutex>;
+
+// It needs to be smaller than 0
+constexpr int EMPTY_ID = -1;
+
+} // anonymous namespace
+
+namespace nsg {
+
+DistanceComputer* storage_distance_computer(const Index* storage) {
+ if (is_similarity_metric(storage->metric_type)) {
+ return new NegativeDistanceComputer(storage->get_distance_computer());
+ } else {
+ return storage->get_distance_computer();
+ }
+}
+
+struct Neighbor {
+ int32_t id;
+ float distance;
+ bool flag;
+
+ Neighbor() = default;
+ Neighbor(int id, float distance, bool f)
+ : id(id), distance(distance), flag(f) {}
+
+ inline bool operator<(const Neighbor& other) const {
+ return distance < other.distance;
+ }
+};
+
+struct Node {
+ int32_t id;
+ float distance;
+
+ Node() = default;
+ Node(int id, float distance) : id(id), distance(distance) {}
+
+ inline bool operator<(const Node& other) const {
+ return distance < other.distance;
+ }
+
+ // to keep the compiler happy
+ inline bool operator<(int other) const {
+ return id < other;
+ }
+};
+
+inline int insert_into_pool(Neighbor* addr, int K, Neighbor nn) {
+ // find the location to insert
+ int left = 0, right = K - 1;
+ if (addr[left].distance > nn.distance) {
+ memmove(&addr[left + 1], &addr[left], K * sizeof(Neighbor));
+ addr[left] = nn;
+ return left;
+ }
+ if (addr[right].distance < nn.distance) {
+ addr[K] = nn;
+ return K;
+ }
+ while (left < right - 1) {
+ int mid = (left + right) / 2;
+ if (addr[mid].distance > nn.distance) {
+ right = mid;
+ } else {
+ left = mid;
+ }
+ }
+ // check equal ID
+
+ while (left > 0) {
+ if (addr[left].distance < nn.distance) {
+ break;
+ }
+ if (addr[left].id == nn.id) {
+ return K + 1;
+ }
+ left--;
+ }
+ if (addr[left].id == nn.id || addr[right].id == nn.id) {
+ return K + 1;
+ }
+ memmove(&addr[right + 1], &addr[right], (K - right) * sizeof(Neighbor));
+ addr[right] = nn;
+ return right;
+}
+
+} // namespace nsg
+
+using namespace nsg;
+
+NSG::NSG(int R) : R(R), rng(0x0903) {
+ L = R + 32;
+ C = R + 100;
+ srand(0x1998);
+}
+
+NSGStats NSG::search(
+ DistanceComputer& dis,
+ int k,
+ idx_t* I,
+ float* D,
+ VisitedTable& vt) const {
+ FAISS_THROW_IF_NOT(is_built);
+ FAISS_THROW_IF_NOT(final_graph);
+
+ int pool_size = std::max(search_L, k);
+ std::vector<Neighbor> retset;
+ std::vector<Node> tmp;
+ NSGStats stats = search_on_graph<false>(
+ *final_graph, dis, vt, enterpoint, pool_size, retset, tmp);
+
+ for (size_t i = 0; i < k; i++) {
+ I[i] = retset[i].id;
+ D[i] = retset[i].distance;
+ }
+
+ return stats;
+}
+
+void NSG::build(
+ Index* storage,
+ idx_t n,
+ const nsg::Graph<idx_t>& knn_graph,
+ bool verbose) {
+ FAISS_THROW_IF_NOT(!is_built && ntotal == 0);
+
+ if (verbose) {
+ printf("NSG::build R=%d, L=%d, C=%d\n", R, L, C);
+ }
+
+ ntotal = n;
+ init_graph(storage, knn_graph);
+
+ printf("graph init done\n");
+
+ std::vector<int> degrees(n, 0);
+ {
+ nsg::Graph<Node> tmp_graph(n, R);
+
+ link(storage, knn_graph, tmp_graph, verbose);
+
+ final_graph = std::make_shared<nsg::Graph<int>>(n, R);
+ std::fill_n(final_graph->data, n * R, EMPTY_ID);
+
+#pragma omp parallel for
+ for (int i = 0; i < n; i++) {
+ int cnt = 0;
+ for (int j = 0; j < R; j++) {
+ int id = tmp_graph.at(i, j).id;
+ if (id != EMPTY_ID) {
+ final_graph->at(i, cnt) = id;
+ cnt += 1;
+ }
+ degrees[i] = cnt;
+ }
+ }
+ }
+
+ int num_attached = tree_grow(storage, degrees);
+ check_graph();
+ is_built = true;
+
+ if (verbose) {
+ int max = 0, min = 1e6;
+ double avg = 0;
+
+ for (int i = 0; i < n; i++) {
+ int size = 0;
+ while (size < R && final_graph->at(i, size) != EMPTY_ID) {
+ size += 1;
+ }
+ max = std::max(size, max);
+ min = std::min(size, min);
+ avg += size;
+ }
+
+ avg = avg / n;
+ printf("Degree Statistics: Max = %d, Min = %d, Avg = %lf\n",
+ max,
+ min,
+ avg);
+ printf("Attached nodes: %d\n", num_attached);
+ }
+}
+
+void NSG::reset() {
+ final_graph.reset();
+ ntotal = 0;
+ is_built = false;
+}
+
+void NSG::init_graph(Index* storage, const nsg::Graph<idx_t>& knn_graph) {
+ int d = storage->d;
+ int n = storage->ntotal;
+
+ std::unique_ptr<float[]> center(new float[d]);
+ std::unique_ptr<float[]> tmp(new float[d]);
+ std::fill_n(center.get(), d, 0.0f);
+
+ for (int i = 0; i < n; i++) {
+ storage->reconstruct(i, tmp.get());
+ for (int j = 0; j < d; j++) {
+ center[j] += tmp[j];
+ }
+ }
+
+ for (int i = 0; i < d; i++) {
+ center[i] /= n;
+ }
+
+ std::vector<Neighbor> retset;
+ std::vector<Node> tmpset;
+
+ // random initialize navigating point
+ int ep = rng.rand_int(n);
+ std::unique_ptr<DistanceComputer> dis(storage_distance_computer(storage));
+
+ dis->set_query(center.get());
+ VisitedTable vt(ntotal);
+
+ // Do not collect the visited nodes
+ search_on_graph<false>(knn_graph, *dis, vt, ep, L, retset, tmpset);
+
+ // set enterpoint
+ enterpoint = retset[0].id;
+}
+
+template <bool collect_fullset, class index_t>
+NSGStats NSG::search_on_graph(
+ const nsg::Graph<index_t>& graph,
+ DistanceComputer& dis,
+ VisitedTable& vt,
+ int ep,
+ int pool_size,
+ std::vector<Neighbor>& retset,
+ std::vector<Node>& fullset) const {
+ RandomGenerator gen(0x1234);
+ retset.resize(pool_size + 1);
+ std::vector<int> init_ids(pool_size);
+
+ NSGStats stats;
+
+ int num_ids = 0;
+ std::vector<index_t> neighbors(graph.K);
+ size_t nneigh = graph.get_neighbors(ep, neighbors.data());
+ for (int i = 0; i < init_ids.size() && i < nneigh; i++) {
+ int id = (int)neighbors[i];
+ if (id >= ntotal) {
+ continue;
+ }
+
+ init_ids[i] = id;
+ vt.set(id);
+ num_ids += 1;
+ }
+
+ while (num_ids < pool_size) {
+ int id = gen.rand_int(ntotal);
+ if (vt.get(id)) {
+ continue;
+ }
+
+ init_ids[num_ids] = id;
+ num_ids++;
+ vt.set(id);
+ }
+
+ for (int i = 0; i < init_ids.size(); i++) {
+ int id = init_ids[i];
+
+ float dist = dis(id);
+ stats.ndis += 1;
+ retset[i] = Neighbor(id, dist, true);
+
+ if (collect_fullset) {
+ fullset.emplace_back(retset[i].id, retset[i].distance);
+ }
+ }
+
+ std::sort(retset.begin(), retset.begin() + pool_size);
+
+ int k = 0;
+ while (k < pool_size) {
+ int updated_pos = pool_size;
+
+ if (retset[k].flag) {
+ retset[k].flag = false;
+ int n = retset[k].id;
+
+ size_t nneigh_for_n = graph.get_neighbors(n, neighbors.data());
+ for (int m = 0; m < nneigh_for_n; m++) {
+ int id = neighbors[m];
+ if (id > ntotal || vt.get(id)) {
+ continue;
+ }
+ vt.set(id);
+
+ float dist = dis(id);
+ stats.ndis += 1;
+ Neighbor nn(id, dist, true);
+ if (collect_fullset) {
+ fullset.emplace_back(id, dist);
+ }
+
+ if (dist >= retset[pool_size - 1].distance) {
+ continue;
+ }
+
+ int r = insert_into_pool(retset.data(), pool_size, nn);
+
+ updated_pos = std::min(updated_pos, r);
+ }
+ }
+
+ k = (updated_pos <= k) ? updated_pos : (k + 1);
+ }
+
+ return stats;
+}
+
+void NSG::link(
+ Index* storage,
+ const nsg::Graph<idx_t>& knn_graph,
+ nsg::Graph<Node>& graph,
+ bool /* verbose */) {
+#pragma omp parallel
+ {
+ std::unique_ptr<float[]> vec(new float[storage->d]);
+
+ std::vector<Node> pool;
+ std::vector<Neighbor> tmp;
+
+ VisitedTable vt(ntotal);
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+#pragma omp for schedule(dynamic, 100)
+ for (int i = 0; i < ntotal; i++) {
+ storage->reconstruct(i, vec.get());
+ dis->set_query(vec.get());
+
+ // Collect the visited nodes into pool
+ search_on_graph<true>(
+ knn_graph, *dis, vt, enterpoint, L, tmp, pool);
+
+ sync_prune(i, pool, *dis, vt, knn_graph, graph);
+
+ pool.clear();
+ tmp.clear();
+ vt.advance();
+ }
+ } // omp parallel
+
+ std::vector<std::mutex> locks(ntotal);
+#pragma omp parallel
+ {
+ std::unique_ptr<DistanceComputer> dis(
+ storage_distance_computer(storage));
+
+#pragma omp for schedule(dynamic, 100)
+ for (int i = 0; i < ntotal; ++i) {
+ add_reverse_links(i, locks, *dis, graph);
+ }
+ } // omp parallel
+}
+
+void NSG::sync_prune(
+ int q,
+ std::vector<Node>& pool,
+ DistanceComputer& dis,
+ VisitedTable& vt,
+ const nsg::Graph<idx_t>& knn_graph,
+ nsg::Graph<Node>& graph) {
+ for (int i = 0; i < knn_graph.K; i++) {
+ int id = knn_graph.at(q, i);
+ if (id < 0 || id >= ntotal || vt.get(id)) {
+ continue;
+ }
+
+ float dist = dis.symmetric_dis(q, id);
+ pool.emplace_back(id, dist);
+ }
+
+ std::sort(pool.begin(), pool.end());
+
+ std::vector<Node> result;
+
+ int start = 0;
+ if (pool[start].id == q) {
+ start++;
+ }
+ result.push_back(pool[start]);
+
+ while (result.size() < R && (++start) < pool.size() && start < C) {
+ auto& p = pool[start];
+ bool occlude = false;
+ for (int t = 0; t < result.size(); t++) {
+ if (p.id == result[t].id) {
+ occlude = true;
+ break;
+ }
+ float djk = dis.symmetric_dis(result[t].id, p.id);
+ if (djk < p.distance /* dik */) {
+ occlude = true;
+ break;
+ }
+ }
+ if (!occlude) {
+ result.push_back(p);
+ }
+ }
+
+ for (size_t i = 0; i < R; i++) {
+ if (i < result.size()) {
+ graph.at(q, i).id = result[i].id;
+ graph.at(q, i).distance = result[i].distance;
+ } else {
+ graph.at(q, i).id = EMPTY_ID;
+ }
+ }
+}
+
+void NSG::add_reverse_links(
+ int q,
+ std::vector<std::mutex>& locks,
+ DistanceComputer& dis,
+ nsg::Graph<Node>& graph) {
+ for (size_t i = 0; i < R; i++) {
+ if (graph.at(q, i).id == EMPTY_ID) {
+ break;
+ }
+
+ Node sn(q, graph.at(q, i).distance);
+ int des = graph.at(q, i).id;
+
+ std::vector<Node> tmp_pool;
+ int dup = 0;
+ {
+ LockGuard guard(locks[des]);
+ for (int j = 0; j < R; j++) {
+ if (graph.at(des, j).id == EMPTY_ID) {
+ break;
+ }
+ if (q == graph.at(des, j).id) {
+ dup = 1;
+ break;
+ }
+ tmp_pool.push_back(graph.at(des, j));
+ }
+ }
+
+ if (dup) {
+ continue;
+ }
+
+ tmp_pool.push_back(sn);
+ if (tmp_pool.size() > R) {
+ std::vector<Node> result;
+ int start = 0;
+ std::sort(tmp_pool.begin(), tmp_pool.end());
+ result.push_back(tmp_pool[start]);
+
+ while (result.size() < R && (++start) < tmp_pool.size()) {
+ auto& p = tmp_pool[start];
+ bool occlude = false;
+
+ for (int t = 0; t < result.size(); t++) {
+ if (p.id == result[t].id) {
+ occlude = true;
+ break;
+ }
+ float djk = dis.symmetric_dis(result[t].id, p.id);
+ if (djk < p.distance /* dik */) {
+ occlude = true;
+ break;
+ }
+ }
+
+ if (!occlude) {
+ result.push_back(p);
+ }
+ }
+
+ {
+ LockGuard guard(locks[des]);
+ for (int t = 0; t < result.size(); t++) {
+ graph.at(des, t) = result[t];
+ }
+ }
+
+ } else {
+ LockGuard guard(locks[des]);
+ for (int t = 0; t < R; t++) {
+ if (graph.at(des, t).id == EMPTY_ID) {
+ graph.at(des, t) = sn;
+ break;
+ }
+ }
+ }
+ }
+}
+
+int NSG::tree_grow(Index* storage, std::vector<int>& degrees) {
+ int root = enterpoint;
+ VisitedTable vt(ntotal);
+ VisitedTable vt2(ntotal);
+
+ int num_attached = 0;
+ int cnt = 0;
+ while (true) {
+ cnt = dfs(vt, root, cnt);
+ if (cnt >= ntotal) {
+ break;
+ }
+
+ root = attach_unlinked(storage, vt, vt2, degrees);
+ vt2.advance();
+ num_attached += 1;
+ }
+
+ return num_attached;
+}
+
+int NSG::dfs(VisitedTable& vt, int root, int cnt) const {
+ int node = root;
+ std::stack<int> stack;
+ stack.push(root);
+
+ if (!vt.get(root)) {
+ cnt++;
+ }
+ vt.set(root);
+
+ while (!stack.empty()) {
+ int next = EMPTY_ID;
+ for (int i = 0; i < R; i++) {
+ int id = final_graph->at(node, i);
+ if (id != EMPTY_ID && !vt.get(id)) {
+ next = id;
+ break;
+ }
+ }
+
+ if (next == EMPTY_ID) {
+ stack.pop();
+ if (stack.empty()) {
+ break;
+ }
+ node = stack.top();
+ continue;
+ }
+ node = next;
+ vt.set(node);
+ stack.push(node);
+ cnt++;
+ }
+
+ return cnt;
+}
+
+int NSG::attach_unlinked(
+ Index* storage,
+ VisitedTable& vt,
+ VisitedTable& vt2,
+ std::vector<int>& degrees) {
+ /* NOTE: This implementation is slightly different from the original paper.
+ *
+ * Instead of connecting the unlinked node to the nearest point in the
+ * spanning tree which will increase the maximum degree of the graph and
+ * also make the graph hard to maintain, this implementation links the
+ * unlinked node to the nearest node of which the degree is smaller than R.
+ * It will keep the degree of all nodes to be no more than `R`.
+ */
+
+ // find one unlinked node
+ int id = EMPTY_ID;
+ for (int i = 0; i < ntotal; i++) {
+ if (!vt.get(i)) {
+ id = i;
+ break;
+ }
+ }
+
+ if (id == EMPTY_ID) {
+ return EMPTY_ID; // No Unlinked Node
+ }
+
+ std::vector<Neighbor> tmp;
+ std::vector<Node> pool;
+
+ std::unique_ptr<DistanceComputer> dis(storage_distance_computer(storage));
+ std::unique_ptr<float[]> vec(new float[storage->d]);
+
+ storage->reconstruct(id, vec.get());
+ dis->set_query(vec.get());
+
+ // Collect the visited nodes into pool
+ search_on_graph<true>(
+ *final_graph, *dis, vt2, enterpoint, search_L, tmp, pool);
+
+ std::sort(pool.begin(), pool.end());
+
+ int node;
+ bool found = false;
+ for (int i = 0; i < pool.size(); i++) {
+ node = pool[i].id;
+ if (degrees[node] < R && node != id) {
+ found = true;
+ break;
+ }
+ }
+
+ // randomly choice annother node
+ if (!found) {
+ do {
+ node = rng.rand_int(ntotal);
+ if (vt.get(node) && degrees[node] < R && node != id) {
+ found = true;
+ }
+ } while (!found);
+ }
+
+ int pos = degrees[node];
+ final_graph->at(node, pos) = id; // replace
+ degrees[node] += 1;
+
+ return node;
+}
+
+void NSG::check_graph() const {
+#pragma omp parallel for
+ for (int i = 0; i < ntotal; i++) {
+ for (int j = 0; j < R; j++) {
+ int id = final_graph->at(i, j);
+ FAISS_THROW_IF_NOT(id < ntotal && (id >= 0 || id == EMPTY_ID));
+ }
+ }
+}
+
+void NSG::print_neighbor_stats(int level) const {
+ FAISS_THROW_IF_NOT(is_built);
+ FAISS_THROW_IF_NOT(final_graph);
+ FAISS_THROW_IF_NOT(level == 0); // NSG only has one level
+
+ printf("stats on NSG graph, max %d neighbors per vertex:\n", R);
+ size_t tot_neigh = 0, tot_common = 0, tot_reciprocal = 0, n_node = 0;
+ size_t n_self_connections = 0;
+#pragma omp parallel for reduction(+ : tot_neigh) reduction(+ : tot_common) \
+ reduction(+ : tot_reciprocal) reduction(+ : n_node) \
+ reduction(+ : n_self_connections)
+ for (int i = 0; i < ntotal; i++) {
+ n_node++;
+ std::unordered_set<int> neighset;
+ for (int j = 0; j < R; j++) {
+ int neigh = final_graph->at(i, j);
+ if (neigh < 0)
+ break;
+ if (neigh == i) {
+ n_self_connections++;
+ continue; // Skip self-connections
+ }
+ neighset.insert(neigh);
+ }
+ int n_neigh = neighset.size();
+ int n_common = 0;
+ int n_reciprocal = 0;
+ for (int j = 0; j < R; j++) {
+ int i2 = final_graph->at(i, j);
+ if (i2 < 0)
+ break;
+ if (i2 == i)
+ continue; // Skip self-connections
+
+ for (int j2 = 0; j2 < R; j2++) {
+ int i3 = final_graph->at(i2, j2);
+ if (i3 < 0)
+ break;
+ if (i3 == i) {
+ n_reciprocal++;
+ continue;
+ }
+ if (neighset.count(i3)) {
+ neighset.erase(i3);
+ n_common++;
+ }
+ }
+ }
+ tot_neigh += n_neigh;
+ tot_common += n_common;
+ tot_reciprocal += n_reciprocal;
+ }
+ float normalizer = n_node;
+ printf(" nb of nodes in the graph: %zd\n", n_node);
+ printf(" neighbors per node: %.2f (%zd)\n",
+ tot_neigh / normalizer,
+ tot_neigh);
+ printf(" nb of reciprocal neighbors: %.2f\n",
+ tot_reciprocal / normalizer);
+ printf(" nb of neighbors that are also neighbor-of-neighbors: %.2f (%zd)\n",
+ tot_common / normalizer,
+ tot_common);
+ if (n_self_connections > 0) {
+ printf(" WARNING: Found %zd self-connections in the graph\n",
+ n_self_connections);
+ }
+}
+
+void NSG::save_degree_distribution(const char* filename) const {
+ FAISS_THROW_IF_NOT(is_built);
+ FAISS_THROW_IF_NOT(final_graph);
+
+ // Open file for writing
+ FILE* f = fopen(filename, "w");
+ if (!f) {
+ fprintf(stderr, "Could not open %s for writing\n", filename);
+ return;
+ }
+
+ // For each node, count actual unique neighbors (not -1 and not self)
+ printf("Computing degree distribution for NSG graph\n");
+
+ int nodes_in_graph = 0;
+ for (int i = 0; i < ntotal; i++) {
+ nodes_in_graph++;
+
+ // Count actual unique neighbors (not -1 and not self)
+ std::unordered_set<int> neighset;
+ for (int j = 0; j < R; j++) {
+ int neigh = final_graph->at(i, j);
+ if (neigh < 0)
+ break;
+ if (neigh == i)
+ continue; // Skip self-connections
+ neighset.insert(neigh);
+ }
+
+ // Write the unique degree to the file
+ fprintf(f, "%d\n", (int)neighset.size());
+ }
+
+ fclose(f);
+ printf("Saved degree distribution for %d nodes to %s\n",
+ nodes_in_graph,
+ filename);
+
+ // Print command to generate the plot
+ printf("To visualize the distribution, run:\n");
+ printf("python -m faiss.contrib.plot_degree_distribution %s\n", filename);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NSG.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NSG.h
new file mode 100644
index 0000000..305ec37
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/NSG.h
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include <omp.h>
+
+#include <faiss/Index.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/random.h>
+
+namespace faiss {
+
+/** Implementation of the Navigating Spreading-out Graph (NSG)
+ * datastructure.
+ *
+ * Fast Approximate Nearest Neighbor Search With The
+ * Navigating Spreading-out Graph
+ *
+ * Cong Fu, Chao Xiang, Changxu Wang, Deng Cai, VLDB 2019
+ *
+ * This implementation is heavily influenced by the NSG
+ * implementation by ZJULearning Group
+ * (https://github.com/zjulearning/nsg)
+ *
+ * The NSG object stores only the neighbor link structure, see
+ * IndexNSG.h for the full index object.
+ */
+
+struct DistanceComputer; // from AuxIndexStructures
+
+namespace nsg {
+
+struct Neighbor;
+struct Node;
+
+/***********************************************************
+ * Graph structure to store a graph.
+ *
+ * It is represented by an adjacency matrix `data`, where
+ * data[i, j] is the j-th neighbor of node i.
+ ***********************************************************/
+
+template <class node_t>
+struct Graph {
+ node_t* data; ///< the flattened adjacency matrix, size N-by-K
+ uint64_t K; ///< nb of neighbors per node
+ int N; ///< total nb of nodes
+ bool own_fields; ///< the underlying data owned by itself or not
+
+ // construct from a known graph
+ Graph(node_t* data, int N, uint64_t K)
+ : data(data), K(K), N(N), own_fields(false) {}
+
+ // construct an empty graph
+ // NOTE: the newly allocated data needs to be destroyed at destruction time
+ Graph(int N, uint64_t K) : K(K), N(N), own_fields(true) {
+ data = new node_t[N * K];
+ }
+
+ // copy constructor
+ Graph(const Graph& g) : Graph(g.N, g.K) {
+ memcpy(data, g.data, N * K * sizeof(node_t));
+ }
+
+ // release the allocated memory if needed
+ virtual ~Graph() {
+ if (own_fields) {
+ delete[] data;
+ }
+ }
+
+ // access the j-th neighbor of node i
+ inline node_t at(int i, int j) const {
+ return data[i * K + j];
+ }
+
+ // access the j-th neighbor of node i by reference
+ inline node_t& at(int i, int j) {
+ return data[i * K + j];
+ }
+
+ // get all neighbors of node i (used during search only)
+ virtual size_t get_neighbors(int i, node_t* neighbors) const {
+ for (int j = 0; j < K; j++) {
+ if (data[i * K + j] < 0) {
+ return j;
+ }
+ neighbors[j] = data[i * K + j];
+ }
+ return K;
+ }
+};
+
+DistanceComputer* storage_distance_computer(const Index* storage);
+
+} // namespace nsg
+
+struct NSGStats {
+ int ndis = 0;
+};
+
+FAISS_API extern NSGStats nsg_stats;
+
+struct NSG {
+ /// internal storage of vectors (32 bits: this is expensive)
+ using storage_idx_t = int32_t;
+ using Node = nsg::Node;
+ using Neighbor = nsg::Neighbor;
+
+ int ntotal = 0; ///< nb of nodes
+
+ // construction-time parameters
+ int R; ///< nb of neighbors per node
+ int L; ///< length of the search path at construction time
+ int C; ///< candidate pool size at construction time
+
+ // search-time parameters
+ int search_L = 16; ///< length of the search path
+
+ int enterpoint; ///< enterpoint
+
+ std::shared_ptr<nsg::Graph<int32_t>> final_graph; ///< NSG graph structure
+
+ bool is_built = false; ///< NSG is built or not
+
+ RandomGenerator rng; ///< random generator
+
+ explicit NSG(int R = 32);
+
+ // build NSG from a KNN graph
+ void build(
+ Index* storage,
+ idx_t n,
+ const nsg::Graph<idx_t>& knn_graph,
+ bool verbose);
+
+ // reset the graph
+ void reset();
+
+ // search interface
+ NSGStats search(
+ DistanceComputer& dis,
+ int k,
+ idx_t* I,
+ float* D,
+ VisitedTable& vt) const;
+
+ // Compute the center point
+ void init_graph(Index* storage, const nsg::Graph<idx_t>& knn_graph);
+
+ // Search on a built graph.
+ // If collect_fullset is true, the visited nodes will be
+ // collected in `fullset`.
+ template <bool collect_fullset, class index_t>
+ NSGStats search_on_graph(
+ const nsg::Graph<index_t>& graph,
+ DistanceComputer& dis,
+ VisitedTable& vt,
+ int ep,
+ int pool_size,
+ std::vector<Neighbor>& retset,
+ std::vector<Node>& fullset) const;
+
+ // Add reverse links
+ void add_reverse_links(
+ int q,
+ std::vector<std::mutex>& locks,
+ DistanceComputer& dis,
+ nsg::Graph<Node>& graph);
+
+ void sync_prune(
+ int q,
+ std::vector<Node>& pool,
+ DistanceComputer& dis,
+ VisitedTable& vt,
+ const nsg::Graph<idx_t>& knn_graph,
+ nsg::Graph<Node>& graph);
+
+ void link(
+ Index* storage,
+ const nsg::Graph<idx_t>& knn_graph,
+ nsg::Graph<Node>& graph,
+ bool verbose);
+
+ // make NSG be fully connected
+ int tree_grow(Index* storage, std::vector<int>& degrees);
+
+ // count the size of the connected component
+ // using depth first search start by root
+ int dfs(VisitedTable& vt, int root, int cnt) const;
+
+ // attach one unlinked node
+ int attach_unlinked(
+ Index* storage,
+ VisitedTable& vt,
+ VisitedTable& vt2,
+ std::vector<int>& degrees);
+
+ // check the integrity of the NSG built
+ void check_graph() const;
+
+ /// Print statistics about the graph connectivity at a given level
+ void print_neighbor_stats(int level = 0) const;
+
+ /// Save the degree distribution of the graph to a file
+ void save_degree_distribution(const char* filename) const;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/PolysemousTraining.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/PolysemousTraining.cpp
new file mode 100644
index 0000000..000a918
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/PolysemousTraining.cpp
@@ -0,0 +1,971 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/PolysemousTraining.h>
+
+#include <omp.h>
+#include <stdint.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/impl/FaissAssert.h>
+
+/*****************************************
+ * Mixed PQ / Hamming
+ ******************************************/
+
+namespace faiss {
+
+/****************************************************
+ * Optimization code
+ ****************************************************/
+
+// what would the cost update be if iw and jw were swapped?
+// default implementation just computes both and computes the difference
+double PermutationObjective::cost_update(const int* perm, int iw, int jw)
+ const {
+ double orig_cost = compute_cost(perm);
+
+ std::vector<int> perm2(n);
+ for (int i = 0; i < n; i++)
+ perm2[i] = perm[i];
+ perm2[iw] = perm[jw];
+ perm2[jw] = perm[iw];
+
+ double new_cost = compute_cost(perm2.data());
+ return new_cost - orig_cost;
+}
+
+SimulatedAnnealingOptimizer::SimulatedAnnealingOptimizer(
+ PermutationObjective* obj,
+ const SimulatedAnnealingParameters& p)
+ : SimulatedAnnealingParameters(p),
+ obj(obj),
+ n(obj->n),
+ logfile(nullptr) {
+ rnd = new RandomGenerator(p.seed);
+ FAISS_THROW_IF_NOT(n < 100000 && n >= 0);
+}
+
+SimulatedAnnealingOptimizer::~SimulatedAnnealingOptimizer() {
+ delete rnd;
+}
+
+// run the optimization and return the best result in best_perm
+double SimulatedAnnealingOptimizer::run_optimization(int* best_perm) {
+ double min_cost = 1e30;
+
+ // just do a few runs of the annealing and keep the lowest output cost
+ for (int it = 0; it < n_redo; it++) {
+ std::vector<int> perm(n);
+ for (int i = 0; i < n; i++)
+ perm[i] = i;
+ if (init_random) {
+ for (int i = 0; i < n; i++) {
+ int j = i + rnd->rand_int(n - i);
+ std::swap(perm[i], perm[j]);
+ }
+ }
+ float cost = optimize(perm.data());
+ if (logfile)
+ fprintf(logfile, "\n");
+ if (verbose > 1) {
+ printf(" optimization run %d: cost=%g %s\n",
+ it,
+ cost,
+ cost < min_cost ? "keep" : "");
+ }
+ if (cost < min_cost) {
+ memcpy(best_perm, perm.data(), sizeof(perm[0]) * n);
+ min_cost = cost;
+ }
+ }
+ return min_cost;
+}
+
+// perform the optimization loop, starting from and modifying
+// permutation in-place
+double SimulatedAnnealingOptimizer::optimize(int* perm) {
+ double cost = init_cost = obj->compute_cost(perm);
+ int log2n = 0;
+ while (!(n <= (1 << log2n)))
+ log2n++;
+ double temperature = init_temperature;
+ int n_swap = 0, n_hot = 0;
+ for (int it = 0; it < n_iter; it++) {
+ temperature = temperature * temperature_decay;
+ int iw, jw;
+ if (only_bit_flips) {
+ iw = rnd->rand_int(n);
+ jw = iw ^ (1 << rnd->rand_int(log2n));
+ } else {
+ iw = rnd->rand_int(n);
+ jw = rnd->rand_int(n - 1);
+ if (jw == iw)
+ jw++;
+ }
+ double delta_cost = obj->cost_update(perm, iw, jw);
+ if (delta_cost < 0 || rnd->rand_float() < temperature) {
+ std::swap(perm[iw], perm[jw]);
+ cost += delta_cost;
+ n_swap++;
+ if (delta_cost >= 0)
+ n_hot++;
+ }
+ if (verbose > 2 || (verbose > 1 && it % 10000 == 0)) {
+ printf(" iteration %d cost %g temp %g n_swap %d "
+ "(%d hot) \r",
+ it,
+ cost,
+ temperature,
+ n_swap,
+ n_hot);
+ fflush(stdout);
+ }
+ if (logfile) {
+ fprintf(logfile,
+ "%d %g %g %d %d\n",
+ it,
+ cost,
+ temperature,
+ n_swap,
+ n_hot);
+ }
+ }
+ if (verbose > 1)
+ printf("\n");
+ return cost;
+}
+
+/****************************************************
+ * Cost functions: ReproduceDistanceTable
+ ****************************************************/
+
+static inline int hamming_dis(uint64_t a, uint64_t b) {
+ return __builtin_popcountl(a ^ b);
+}
+
+namespace {
+
+/// optimize permutation to reproduce a distance table with Hamming distances
+struct ReproduceWithHammingObjective : PermutationObjective {
+ int nbits;
+ double dis_weight_factor;
+
+ static double sqr(double x) {
+ return x * x;
+ }
+
+ // weihgting of distances: it is more important to reproduce small
+ // distances well
+ double dis_weight(double x) const {
+ return exp(-dis_weight_factor * x);
+ }
+
+ std::vector<double> target_dis; // wanted distances (size n^2)
+ std::vector<double> weights; // weights for each distance (size n^2)
+
+ // cost = quadratic difference between actual distance and Hamming distance
+ double compute_cost(const int* perm) const override {
+ double cost = 0;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < n; j++) {
+ double wanted = target_dis[i * n + j];
+ double w = weights[i * n + j];
+ double actual = hamming_dis(perm[i], perm[j]);
+ cost += w * sqr(wanted - actual);
+ }
+ }
+ return cost;
+ }
+
+ // what would the cost update be if iw and jw were swapped?
+ // computed in O(n) instead of O(n^2) for the full re-computation
+ double cost_update(const int* perm, int iw, int jw) const override {
+ double delta_cost = 0;
+
+ for (int i = 0; i < n; i++) {
+ if (i == iw) {
+ for (int j = 0; j < n; j++) {
+ double wanted = target_dis[i * n + j],
+ w = weights[i * n + j];
+ double actual = hamming_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = hamming_dis(
+ perm[jw],
+ perm[j == iw ? jw
+ : j == jw ? iw
+ : j]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ } else if (i == jw) {
+ for (int j = 0; j < n; j++) {
+ double wanted = target_dis[i * n + j],
+ w = weights[i * n + j];
+ double actual = hamming_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = hamming_dis(
+ perm[iw],
+ perm[j == iw ? jw
+ : j == jw ? iw
+ : j]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ } else {
+ int j = iw;
+ {
+ double wanted = target_dis[i * n + j],
+ w = weights[i * n + j];
+ double actual = hamming_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = hamming_dis(perm[i], perm[jw]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ j = jw;
+ {
+ double wanted = target_dis[i * n + j],
+ w = weights[i * n + j];
+ double actual = hamming_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = hamming_dis(perm[i], perm[iw]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ }
+ }
+
+ return delta_cost;
+ }
+
+ ReproduceWithHammingObjective(
+ int nbits,
+ const std::vector<double>& dis_table,
+ double dis_weight_factor)
+ : nbits(nbits), dis_weight_factor(dis_weight_factor) {
+ n = 1 << nbits;
+ FAISS_THROW_IF_NOT(dis_table.size() == n * n);
+ set_affine_target_dis(dis_table);
+ }
+
+ void set_affine_target_dis(const std::vector<double>& dis_table) {
+ double sum = 0, sum2 = 0;
+ int n2 = n * n;
+ for (int i = 0; i < n2; i++) {
+ sum += dis_table[i];
+ sum2 += dis_table[i] * dis_table[i];
+ }
+ double mean = sum / n2;
+ double stddev = sqrt(sum2 / n2 - (sum / n2) * (sum / n2));
+
+ target_dis.resize(n2);
+
+ for (int i = 0; i < n2; i++) {
+ // the mapping function
+ double td = (dis_table[i] - mean) / stddev * sqrt(nbits / 4) +
+ nbits / 2;
+ target_dis[i] = td;
+ // compute a weight
+ weights.push_back(dis_weight(td));
+ }
+ }
+
+ ~ReproduceWithHammingObjective() override {}
+};
+
+} // anonymous namespace
+
+// weihgting of distances: it is more important to reproduce small
+// distances well
+double ReproduceDistancesObjective::dis_weight(double x) const {
+ return exp(-dis_weight_factor * x);
+}
+
+double ReproduceDistancesObjective::get_source_dis(int i, int j) const {
+ return source_dis[i * n + j];
+}
+
+// cost = quadratic difference between actual distance and Hamming distance
+double ReproduceDistancesObjective::compute_cost(const int* perm) const {
+ double cost = 0;
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < n; j++) {
+ double wanted = target_dis[i * n + j];
+ double w = weights[i * n + j];
+ double actual = get_source_dis(perm[i], perm[j]);
+ cost += w * sqr(wanted - actual);
+ }
+ }
+ return cost;
+}
+
+// what would the cost update be if iw and jw were swapped?
+// computed in O(n) instead of O(n^2) for the full re-computation
+double ReproduceDistancesObjective::cost_update(const int* perm, int iw, int jw)
+ const {
+ double delta_cost = 0;
+ for (int i = 0; i < n; i++) {
+ if (i == iw) {
+ for (int j = 0; j < n; j++) {
+ double wanted = target_dis[i * n + j], w = weights[i * n + j];
+ double actual = get_source_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = get_source_dis(
+ perm[jw],
+ perm[j == iw ? jw
+ : j == jw ? iw
+ : j]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ } else if (i == jw) {
+ for (int j = 0; j < n; j++) {
+ double wanted = target_dis[i * n + j], w = weights[i * n + j];
+ double actual = get_source_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = get_source_dis(
+ perm[iw],
+ perm[j == iw ? jw
+ : j == jw ? iw
+ : j]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ } else {
+ int j = iw;
+ {
+ double wanted = target_dis[i * n + j], w = weights[i * n + j];
+ double actual = get_source_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = get_source_dis(perm[i], perm[jw]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ j = jw;
+ {
+ double wanted = target_dis[i * n + j], w = weights[i * n + j];
+ double actual = get_source_dis(perm[i], perm[j]);
+ delta_cost -= w * sqr(wanted - actual);
+ double new_actual = get_source_dis(perm[i], perm[iw]);
+ delta_cost += w * sqr(wanted - new_actual);
+ }
+ }
+ }
+ return delta_cost;
+}
+
+ReproduceDistancesObjective::ReproduceDistancesObjective(
+ int n,
+ const double* source_dis_in,
+ const double* target_dis_in,
+ double dis_weight_factor)
+ : dis_weight_factor(dis_weight_factor), target_dis(target_dis_in) {
+ this->n = n;
+ set_affine_target_dis(source_dis_in);
+}
+
+void ReproduceDistancesObjective::compute_mean_stdev(
+ const double* tab,
+ size_t n2,
+ double* mean_out,
+ double* stddev_out) {
+ double sum = 0, sum2 = 0;
+ for (int i = 0; i < n2; i++) {
+ sum += tab[i];
+ sum2 += tab[i] * tab[i];
+ }
+ double mean = sum / n2;
+ double stddev = sqrt(sum2 / n2 - (sum / n2) * (sum / n2));
+ *mean_out = mean;
+ *stddev_out = stddev;
+}
+
+void ReproduceDistancesObjective::set_affine_target_dis(
+ const double* source_dis_in) {
+ int n2 = n * n;
+
+ double mean_src, stddev_src;
+ compute_mean_stdev(source_dis_in, n2, &mean_src, &stddev_src);
+
+ double mean_target, stddev_target;
+ compute_mean_stdev(target_dis, n2, &mean_target, &stddev_target);
+
+ printf("map mean %g std %g -> mean %g std %g\n",
+ mean_src,
+ stddev_src,
+ mean_target,
+ stddev_target);
+
+ source_dis.resize(n2);
+ weights.resize(n2);
+
+ for (int i = 0; i < n2; i++) {
+ // the mapping function
+ source_dis[i] =
+ (source_dis_in[i] - mean_src) / stddev_src * stddev_target +
+ mean_target;
+
+ // compute a weight
+ weights[i] = dis_weight(target_dis[i]);
+ }
+}
+
+/****************************************************
+ * Cost functions: RankingScore
+ ****************************************************/
+
+/// Maintains a 3D table of elementary costs.
+/// Accumulates elements based on Hamming distance comparisons
+template <typename Ttab, typename Taccu>
+struct Score3Computer : PermutationObjective {
+ int nc;
+
+ // cost matrix of size nc * nc *nc
+ // n_gt (i,j,k) = count of d_gt(x, y-) < d_gt(x, y+)
+ // where x has PQ code i, y- PQ code j and y+ PQ code k
+ std::vector<Ttab> n_gt;
+
+ /// the cost is a triple loop on the nc * nc * nc matrix of entries.
+ ///
+ Taccu compute(const int* perm) const {
+ Taccu accu = 0;
+ const Ttab* p = n_gt.data();
+ for (int i = 0; i < nc; i++) {
+ int ip = perm[i];
+ for (int j = 0; j < nc; j++) {
+ int jp = perm[j];
+ for (int k = 0; k < nc; k++) {
+ int kp = perm[k];
+ if (hamming_dis(ip, jp) < hamming_dis(ip, kp)) {
+ accu += *p; // n_gt [ ( i * nc + j) * nc + k];
+ }
+ p++;
+ }
+ }
+ }
+ return accu;
+ }
+
+ /** cost update if entries iw and jw of the permutation would be
+ * swapped.
+ *
+ * The computation is optimized by avoiding elements in the
+ * nc*nc*nc cube that are known not to change. For nc=256, this
+ * reduces the nb of cells to visit to about 6/256 th of the
+ * cells. Practical speedup is about 8x, and the code is quite
+ * complex :-/
+ */
+ Taccu compute_update(const int* perm, int iw, int jw) const {
+ assert(iw != jw);
+ if (iw > jw)
+ std::swap(iw, jw);
+
+ Taccu accu = 0;
+ const Ttab* n_gt_i = n_gt.data();
+ for (int i = 0; i < nc; i++) {
+ int ip0 = perm[i];
+ int ip = perm[i == iw ? jw : i == jw ? iw : i];
+
+ // accu += update_i (perm, iw, jw, ip0, ip, n_gt_i);
+
+ accu += update_i_cross(perm, iw, jw, ip0, ip, n_gt_i);
+
+ if (ip != ip0)
+ accu += update_i_plane(perm, iw, jw, ip0, ip, n_gt_i);
+
+ n_gt_i += nc * nc;
+ }
+
+ return accu;
+ }
+
+ Taccu update_i(
+ const int* perm,
+ int iw,
+ int jw,
+ int ip0,
+ int ip,
+ const Ttab* n_gt_i) const {
+ Taccu accu = 0;
+ const Ttab* n_gt_ij = n_gt_i;
+ for (int j = 0; j < nc; j++) {
+ int jp0 = perm[j];
+ int jp = perm[j == iw ? jw : j == jw ? iw : j];
+ for (int k = 0; k < nc; k++) {
+ int kp0 = perm[k];
+ int kp = perm[k == iw ? jw : k == jw ? iw : k];
+ int ng = n_gt_ij[k];
+ if (hamming_dis(ip, jp) < hamming_dis(ip, kp)) {
+ accu += ng;
+ }
+ if (hamming_dis(ip0, jp0) < hamming_dis(ip0, kp0)) {
+ accu -= ng;
+ }
+ }
+ n_gt_ij += nc;
+ }
+ return accu;
+ }
+
+ // 2 inner loops for the case ip0 != ip
+ Taccu update_i_plane(
+ const int* perm,
+ int iw,
+ int jw,
+ int ip0,
+ int ip,
+ const Ttab* n_gt_i) const {
+ Taccu accu = 0;
+ const Ttab* n_gt_ij = n_gt_i;
+
+ for (int j = 0; j < nc; j++) {
+ if (j != iw && j != jw) {
+ int jp = perm[j];
+ for (int k = 0; k < nc; k++) {
+ if (k != iw && k != jw) {
+ int kp = perm[k];
+ Ttab ng = n_gt_ij[k];
+ if (hamming_dis(ip, jp) < hamming_dis(ip, kp)) {
+ accu += ng;
+ }
+ if (hamming_dis(ip0, jp) < hamming_dis(ip0, kp)) {
+ accu -= ng;
+ }
+ }
+ }
+ }
+ n_gt_ij += nc;
+ }
+ return accu;
+ }
+
+ /// used for the 8 cells were the 3 indices are swapped
+ inline Taccu update_k(
+ const int* perm,
+ int iw,
+ int jw,
+ int ip0,
+ int ip,
+ int jp0,
+ int jp,
+ int k,
+ const Ttab* n_gt_ij) const {
+ Taccu accu = 0;
+ int kp0 = perm[k];
+ int kp = perm[k == iw ? jw : k == jw ? iw : k];
+ Ttab ng = n_gt_ij[k];
+ if (hamming_dis(ip, jp) < hamming_dis(ip, kp)) {
+ accu += ng;
+ }
+ if (hamming_dis(ip0, jp0) < hamming_dis(ip0, kp0)) {
+ accu -= ng;
+ }
+ return accu;
+ }
+
+ /// compute update on a line of k's, where i and j are swapped
+ Taccu update_j_line(
+ const int* perm,
+ int iw,
+ int jw,
+ int ip0,
+ int ip,
+ int jp0,
+ int jp,
+ const Ttab* n_gt_ij) const {
+ Taccu accu = 0;
+ for (int k = 0; k < nc; k++) {
+ if (k == iw || k == jw)
+ continue;
+ int kp = perm[k];
+ Ttab ng = n_gt_ij[k];
+ if (hamming_dis(ip, jp) < hamming_dis(ip, kp)) {
+ accu += ng;
+ }
+ if (hamming_dis(ip0, jp0) < hamming_dis(ip0, kp)) {
+ accu -= ng;
+ }
+ }
+ return accu;
+ }
+
+ /// considers the 2 pairs of crossing lines j=iw or jw and k = iw or kw
+ Taccu update_i_cross(
+ const int* perm,
+ int iw,
+ int jw,
+ int ip0,
+ int ip,
+ const Ttab* n_gt_i) const {
+ Taccu accu = 0;
+ const Ttab* n_gt_ij = n_gt_i;
+
+ for (int j = 0; j < nc; j++) {
+ int jp0 = perm[j];
+ int jp = perm[j == iw ? jw : j == jw ? iw : j];
+
+ accu += update_k(perm, iw, jw, ip0, ip, jp0, jp, iw, n_gt_ij);
+ accu += update_k(perm, iw, jw, ip0, ip, jp0, jp, jw, n_gt_ij);
+
+ if (jp != jp0)
+ accu += update_j_line(perm, iw, jw, ip0, ip, jp0, jp, n_gt_ij);
+
+ n_gt_ij += nc;
+ }
+ return accu;
+ }
+
+ /// PermutationObjective implementeation (just negates the scores
+ /// for minimization)
+
+ double compute_cost(const int* perm) const override {
+ return -compute(perm);
+ }
+
+ double cost_update(const int* perm, int iw, int jw) const override {
+ double ret = -compute_update(perm, iw, jw);
+ return ret;
+ }
+
+ ~Score3Computer() override {}
+};
+
+struct IndirectSort {
+ const float* tab;
+ bool operator()(int a, int b) {
+ return tab[a] < tab[b];
+ }
+};
+
+struct RankingScore2 : Score3Computer<float, double> {
+ int nbits;
+ int nq, nb;
+ const uint32_t *qcodes, *bcodes;
+ const float* gt_distances;
+
+ RankingScore2(
+ int nbits,
+ int nq,
+ int nb,
+ const uint32_t* qcodes,
+ const uint32_t* bcodes,
+ const float* gt_distances)
+ : nbits(nbits),
+ nq(nq),
+ nb(nb),
+ qcodes(qcodes),
+ bcodes(bcodes),
+ gt_distances(gt_distances) {
+ n = nc = 1 << nbits;
+ n_gt.resize(nc * nc * nc);
+ init_n_gt();
+ }
+
+ double rank_weight(int r) {
+ return 1.0 / (r + 1);
+ }
+
+ /// count nb of i, j in a x b st. i < j
+ /// a and b should be sorted on input
+ /// they are the ranks of j and k respectively.
+ /// specific version for diff-of-rank weighting, cannot optimized
+ /// with a cumulative table
+ double accum_gt_weight_diff(
+ const std::vector<int>& a,
+ const std::vector<int>& b) {
+ const auto nb_2 = b.size();
+ const auto na = a.size();
+
+ double accu = 0;
+ size_t j = 0;
+ for (size_t i = 0; i < na; i++) {
+ const auto ai = a[i];
+ while (j < nb_2 && ai >= b[j]) {
+ j++;
+ }
+
+ double accu_i = 0;
+ for (auto k = j; k < b.size(); k++) {
+ accu_i += rank_weight(b[k] - ai);
+ }
+
+ accu += rank_weight(ai) * accu_i;
+ }
+ return accu;
+ }
+
+ void init_n_gt() {
+ for (int q = 0; q < nq; q++) {
+ const float* gtd = gt_distances + q * nb;
+ const uint32_t* cb = bcodes; // all same codes
+ float* n_gt_q = &n_gt[qcodes[q] * nc * nc];
+
+ printf("init gt for q=%d/%d \r", q, nq);
+ fflush(stdout);
+
+ std::vector<int> rankv(nb);
+ int* ranks = rankv.data();
+
+ // elements in each code bin, ordered by rank within each bin
+ std::vector<std::vector<int>> tab(nc);
+
+ { // build rank table
+ IndirectSort s = {gtd};
+ for (int j = 0; j < nb; j++)
+ ranks[j] = j;
+ std::sort(ranks, ranks + nb, s);
+ }
+
+ for (int rank = 0; rank < nb; rank++) {
+ int i = ranks[rank];
+ tab[cb[i]].push_back(rank);
+ }
+
+ // this is very expensive. Any suggestion for improvement
+ // welcome.
+ for (int i = 0; i < nc; i++) {
+ std::vector<int>& di = tab[i];
+ for (int j = 0; j < nc; j++) {
+ std::vector<int>& dj = tab[j];
+ n_gt_q[i * nc + j] += accum_gt_weight_diff(di, dj);
+ }
+ }
+ }
+ }
+};
+
+/*****************************************
+ * PolysemousTraining
+ ******************************************/
+
+PolysemousTraining::PolysemousTraining() {
+ optimization_type = OT_ReproduceDistances_affine;
+ ntrain_permutation = 0;
+ dis_weight_factor = log(2);
+ // max 20 G RAM
+ max_memory = (size_t)(20) * 1024 * 1024 * 1024;
+}
+
+void PolysemousTraining::optimize_reproduce_distances(
+ ProductQuantizer& pq) const {
+ int dsub = pq.dsub;
+
+ int n = pq.ksub;
+ int nbits = pq.nbits;
+
+ size_t mem1 = memory_usage_per_thread(pq);
+ int nt = std::min(omp_get_max_threads(), int(pq.M));
+ FAISS_THROW_IF_NOT_FMT(
+ mem1 < max_memory,
+ "Polysemous training will use %zd bytes per thread, while the max is set to %zd",
+ mem1,
+ max_memory);
+
+ if (mem1 * nt > max_memory) {
+ nt = max_memory / mem1;
+ fprintf(stderr,
+ "Polysemous training: WARN, reducing number of threads to %d to save memory",
+ nt);
+ }
+
+#pragma omp parallel for num_threads(nt)
+ for (int m = 0; m < pq.M; m++) {
+ std::vector<double> dis_table;
+
+ // printf ("Optimizing quantizer %d\n", m);
+
+ float* centroids = pq.get_centroids(m, 0);
+
+ for (int i = 0; i < n; i++) {
+ for (int j = 0; j < n; j++) {
+ dis_table.push_back(fvec_L2sqr(
+ centroids + i * dsub, centroids + j * dsub, dsub));
+ }
+ }
+
+ std::vector<int> perm(n);
+ ReproduceWithHammingObjective obj(nbits, dis_table, dis_weight_factor);
+
+ SimulatedAnnealingOptimizer optim(&obj, *this);
+
+ if (log_pattern.size()) {
+ char fname[256];
+ snprintf(fname, 256, log_pattern.c_str(), m);
+ printf("opening log file %s\n", fname);
+ optim.logfile = fopen(fname, "w");
+ FAISS_THROW_IF_NOT_MSG(optim.logfile, "could not open logfile");
+ }
+ double final_cost = optim.run_optimization(perm.data());
+
+ if (verbose > 0) {
+ printf("SimulatedAnnealingOptimizer for m=%d: %g -> %g\n",
+ m,
+ optim.init_cost,
+ final_cost);
+ }
+
+ if (log_pattern.size())
+ fclose(optim.logfile);
+
+ std::vector<float> centroids_copy;
+ for (int i = 0; i < dsub * n; i++)
+ centroids_copy.push_back(centroids[i]);
+
+ for (int i = 0; i < n; i++)
+ memcpy(centroids + perm[i] * dsub,
+ centroids_copy.data() + i * dsub,
+ dsub * sizeof(centroids[0]));
+ }
+}
+
+void PolysemousTraining::optimize_ranking(
+ ProductQuantizer& pq,
+ size_t n,
+ const float* x) const {
+ int dsub = pq.dsub;
+ int nbits = pq.nbits;
+
+ std::vector<uint8_t> all_codes(pq.code_size * n);
+
+ pq.compute_codes(x, all_codes.data(), n);
+
+ FAISS_THROW_IF_NOT(pq.nbits == 8);
+
+ if (n == 0) {
+ pq.compute_sdc_table();
+ }
+
+#pragma omp parallel for
+ for (int m = 0; m < pq.M; m++) {
+ size_t nq, nb;
+ std::vector<uint32_t> codes; // query codes, then db codes
+ std::vector<float> gt_distances; // nq * nb matrix of distances
+
+ if (n > 0) {
+ std::vector<float> xtrain(n * dsub);
+ for (int i = 0; i < n; i++)
+ memcpy(xtrain.data() + i * dsub,
+ x + i * pq.d + m * dsub,
+ sizeof(float) * dsub);
+
+ codes.resize(n);
+ for (int i = 0; i < n; i++)
+ codes[i] = all_codes[i * pq.code_size + m];
+
+ nq = n / 4;
+ nb = n - nq;
+ const float* xq = xtrain.data();
+ const float* xb = xq + nq * dsub;
+
+ gt_distances.resize(nq * nb);
+
+ pairwise_L2sqr(dsub, nq, xq, nb, xb, gt_distances.data());
+ } else {
+ nq = nb = pq.ksub;
+ codes.resize(2 * nq);
+ for (int i = 0; i < nq; i++)
+ codes[i] = codes[i + nq] = i;
+
+ gt_distances.resize(nq * nb);
+
+ memcpy(gt_distances.data(),
+ pq.sdc_table.data() + m * nq * nb,
+ sizeof(float) * nq * nb);
+ }
+
+ double t0 = getmillisecs();
+
+ std::unique_ptr<PermutationObjective> obj(new RankingScore2(
+ nbits,
+ nq,
+ nb,
+ codes.data(),
+ codes.data() + nq,
+ gt_distances.data()));
+
+ if (verbose > 0) {
+ printf(" m=%d, nq=%zd, nb=%zd, initialize RankingScore "
+ "in %.3f ms\n",
+ m,
+ nq,
+ nb,
+ getmillisecs() - t0);
+ }
+
+ SimulatedAnnealingOptimizer optim(obj.get(), *this);
+
+ if (log_pattern.size()) {
+ char fname[256];
+ snprintf(fname, 256, log_pattern.c_str(), m);
+ printf("opening log file %s\n", fname);
+ optim.logfile = fopen(fname, "w");
+ FAISS_THROW_IF_NOT_FMT(
+ optim.logfile, "could not open logfile %s", fname);
+ }
+
+ std::vector<int> perm(pq.ksub);
+
+ double final_cost = optim.run_optimization(perm.data());
+ printf("SimulatedAnnealingOptimizer for m=%d: %g -> %g\n",
+ m,
+ optim.init_cost,
+ final_cost);
+
+ if (log_pattern.size())
+ fclose(optim.logfile);
+
+ float* centroids = pq.get_centroids(m, 0);
+
+ std::vector<float> centroids_copy;
+ for (int i = 0; i < dsub * pq.ksub; i++)
+ centroids_copy.push_back(centroids[i]);
+
+ for (int i = 0; i < pq.ksub; i++)
+ memcpy(centroids + perm[i] * dsub,
+ centroids_copy.data() + i * dsub,
+ dsub * sizeof(centroids[0]));
+ }
+}
+
+void PolysemousTraining::optimize_pq_for_hamming(
+ ProductQuantizer& pq,
+ size_t n,
+ const float* x) const {
+ if (optimization_type == OT_None) {
+ } else if (optimization_type == OT_ReproduceDistances_affine) {
+ optimize_reproduce_distances(pq);
+ } else {
+ optimize_ranking(pq, n, x);
+ }
+
+ pq.compute_sdc_table();
+}
+
+size_t PolysemousTraining::memory_usage_per_thread(
+ const ProductQuantizer& pq) const {
+ size_t n = pq.ksub;
+
+ switch (optimization_type) {
+ case OT_None:
+ return 0;
+ case OT_ReproduceDistances_affine:
+ return n * n * sizeof(double) * 3;
+ case OT_Ranking_weighted_diff:
+ return n * n * n * sizeof(float);
+ }
+
+ FAISS_THROW_MSG("Invalid optmization type");
+ return 0;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/PolysemousTraining.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/PolysemousTraining.h
new file mode 100644
index 0000000..cc9b76b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/PolysemousTraining.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_POLYSEMOUS_TRAINING_INCLUDED
+#define FAISS_POLYSEMOUS_TRAINING_INCLUDED
+
+#include <faiss/impl/ProductQuantizer.h>
+
+namespace faiss {
+
+/// parameters used for the simulated annealing method
+struct SimulatedAnnealingParameters {
+ // optimization parameters
+ double init_temperature = 0.7; // init probability of accepting a bad swap
+ // at each iteration the temp is multiplied by this
+ double temperature_decay = 0.9997893011688015; // = 0.9^(1/500)
+ int n_iter = 500000; // nb of iterations
+ int n_redo = 2; // nb of runs of the simulation
+ int seed = 123; // random seed
+ int verbose = 0;
+ bool only_bit_flips = false; // restrict permutation changes to bit flips
+ bool init_random =
+ false; // initialize with a random permutation (not identity)
+
+ // set reasonable defaults
+ SimulatedAnnealingParameters() {}
+};
+
+/// abstract class for the loss function
+struct PermutationObjective {
+ int n;
+
+ virtual double compute_cost(const int* perm) const = 0;
+
+ // what would the cost update be if iw and jw were swapped?
+ // default implementation just computes both and computes the difference
+ virtual double cost_update(const int* perm, int iw, int jw) const;
+
+ virtual ~PermutationObjective() {}
+};
+
+struct ReproduceDistancesObjective : PermutationObjective {
+ double dis_weight_factor;
+
+ static double sqr(double x) {
+ return x * x;
+ }
+
+ // weighting of distances: it is more important to reproduce small
+ // distances well
+ double dis_weight(double x) const;
+
+ std::vector<double> source_dis; ///< "real" corrected distances (size n^2)
+ const double* target_dis; ///< wanted distances (size n^2)
+ std::vector<double> weights; ///< weights for each distance (size n^2)
+
+ double get_source_dis(int i, int j) const;
+
+ // cost = quadratic difference between actual distance and Hamming distance
+ double compute_cost(const int* perm) const override;
+
+ // what would the cost update be if iw and jw were swapped?
+ // computed in O(n) instead of O(n^2) for the full re-computation
+ double cost_update(const int* perm, int iw, int jw) const override;
+
+ ReproduceDistancesObjective(
+ int n,
+ const double* source_dis_in,
+ const double* target_dis_in,
+ double dis_weight_factor);
+
+ static void compute_mean_stdev(
+ const double* tab,
+ size_t n2,
+ double* mean_out,
+ double* stddev_out);
+
+ void set_affine_target_dis(const double* source_dis_in);
+
+ ~ReproduceDistancesObjective() override {}
+};
+
+struct RandomGenerator;
+
+/// Simulated annealing optimization algorithm for permutations.
+struct SimulatedAnnealingOptimizer : SimulatedAnnealingParameters {
+ PermutationObjective* obj;
+ int n; ///< size of the permutation
+ FILE* logfile; /// logs values of the cost function
+
+ SimulatedAnnealingOptimizer(
+ PermutationObjective* obj,
+ const SimulatedAnnealingParameters& p);
+ RandomGenerator* rnd;
+
+ /// remember initial cost of optimization
+ double init_cost;
+
+ // main entry point. Perform the optimization loop, starting from
+ // and modifying permutation in-place
+ double optimize(int* perm);
+
+ // run the optimization and return the best result in best_perm
+ double run_optimization(int* best_perm);
+
+ virtual ~SimulatedAnnealingOptimizer();
+};
+
+/// optimizes the order of indices in a ProductQuantizer
+struct PolysemousTraining : SimulatedAnnealingParameters {
+ enum Optimization_type_t {
+ OT_None,
+ OT_ReproduceDistances_affine, ///< default
+ OT_Ranking_weighted_diff ///< same as _2, but use rank of y+ - rank of
+ ///< y-
+ };
+ Optimization_type_t optimization_type;
+
+ /** use 1/4 of the training points for the optimization, with
+ * max. ntrain_permutation. If ntrain_permutation == 0: train on
+ * centroids */
+ int ntrain_permutation;
+ double dis_weight_factor; ///< decay of exp that weights distance loss
+
+ /// refuse to train if it would require more than that amount of RAM
+ size_t max_memory;
+
+ // filename pattern for the logging of iterations
+ std::string log_pattern;
+
+ // sets default values
+ PolysemousTraining();
+
+ /// reorder the centroids so that the Hamming distance becomes a
+ /// good approximation of the SDC distance (called by train)
+ void optimize_pq_for_hamming(ProductQuantizer& pq, size_t n, const float* x)
+ const;
+
+ /// called by optimize_pq_for_hamming
+ void optimize_ranking(ProductQuantizer& pq, size_t n, const float* x) const;
+ /// called by optimize_pq_for_hamming
+ void optimize_reproduce_distances(ProductQuantizer& pq) const;
+
+ /// make sure we don't blow up the memory
+ size_t memory_usage_per_thread(const ProductQuantizer& pq) const;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductAdditiveQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductAdditiveQuantizer.cpp
new file mode 100644
index 0000000..1764b3c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductAdditiveQuantizer.cpp
@@ -0,0 +1,374 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/ProductAdditiveQuantizer.h>
+
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+
+#include <algorithm>
+
+#include <faiss/clone_index.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+
+extern "C" {
+
+// general matrix multiplication
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+ProductAdditiveQuantizer::ProductAdditiveQuantizer(
+ size_t d,
+ const std::vector<AdditiveQuantizer*>& aqs,
+ Search_type_t search_type) {
+ init(d, aqs, search_type);
+}
+
+ProductAdditiveQuantizer::ProductAdditiveQuantizer()
+ : ProductAdditiveQuantizer(0, {}) {}
+
+void ProductAdditiveQuantizer::init(
+ size_t d,
+ const std::vector<AdditiveQuantizer*>& aqs,
+ Search_type_t search_type) {
+ // AdditiveQuantizer constructor
+ this->d = d;
+ this->search_type = search_type;
+ M = 0;
+ for (const auto& q : aqs) {
+ M += q->M;
+ nbits.insert(nbits.end(), q->nbits.begin(), q->nbits.end());
+ }
+ set_derived_values();
+
+ // ProductAdditiveQuantizer
+ nsplits = aqs.size();
+
+ FAISS_THROW_IF_NOT(quantizers.empty());
+ for (const auto& q : aqs) {
+ auto aq = dynamic_cast<AdditiveQuantizer*>(clone_Quantizer(q));
+ quantizers.push_back(aq);
+ }
+}
+
+ProductAdditiveQuantizer::~ProductAdditiveQuantizer() {
+ for (auto& q : quantizers) {
+ delete q;
+ }
+}
+
+AdditiveQuantizer* ProductAdditiveQuantizer::subquantizer(size_t s) const {
+ return quantizers[s];
+}
+
+void ProductAdditiveQuantizer::train(size_t n, const float* x) {
+ if (is_trained) {
+ return;
+ }
+
+ // copy the subvectors into contiguous memory
+ size_t offset_d = 0;
+ std::vector<float> xt;
+ for (size_t s = 0; s < nsplits; s++) {
+ auto q = quantizers[s];
+ xt.resize(q->d * n);
+
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ memcpy(xt.data() + i * q->d,
+ x + i * d + offset_d,
+ q->d * sizeof(*x));
+ }
+
+ q->train(n, xt.data());
+ offset_d += q->d;
+ }
+
+ // compute codebook size
+ size_t codebook_size = 0;
+ for (const auto& q : quantizers) {
+ codebook_size += q->total_codebook_size * q->d;
+ }
+
+ // copy codebook from sub-quantizers
+ codebooks.resize(codebook_size); // size (M * ksub, dsub)
+ float* cb = codebooks.data();
+ for (size_t s = 0; s < nsplits; s++) {
+ auto q = quantizers[s];
+ size_t sub_codebook_size = q->total_codebook_size * q->d;
+ memcpy(cb, q->codebooks.data(), sub_codebook_size * sizeof(float));
+ cb += sub_codebook_size;
+ }
+
+ is_trained = true;
+
+ // train norm
+ std::vector<int32_t> codes(n * M);
+ compute_unpacked_codes(x, codes.data(), n);
+ std::vector<float> x_recons(n * d);
+ std::vector<float> norms(n);
+ decode_unpacked(codes.data(), x_recons.data(), n);
+ fvec_norms_L2sqr(norms.data(), x_recons.data(), d, n);
+ train_norm(n, norms.data());
+}
+
+void ProductAdditiveQuantizer::compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids) const {
+ // size (n, M)
+ std::vector<int32_t> unpacked_codes(n * M);
+ compute_unpacked_codes(x, unpacked_codes.data(), n, centroids);
+
+ // pack
+ pack_codes(n, unpacked_codes.data(), codes_out, -1, nullptr, centroids);
+}
+
+void ProductAdditiveQuantizer::compute_unpacked_codes(
+ const float* x,
+ int32_t* unpacked_codes,
+ size_t n,
+ const float* centroids) const {
+ /// TODO: actuallly we do not need to unpack and pack
+ size_t offset_d = 0, offset_m = 0;
+ std::vector<float> xsub;
+ std::vector<uint8_t> codes;
+
+ for (size_t s = 0; s < nsplits; s++) {
+ const auto q = quantizers[s];
+ xsub.resize(n * q->d);
+ codes.resize(n * q->code_size);
+
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ memcpy(xsub.data() + i * q->d,
+ x + i * d + offset_d,
+ q->d * sizeof(float));
+ }
+
+ q->compute_codes(xsub.data(), codes.data(), n);
+
+ // unpack
+#pragma omp parallel for if (n > 1000)
+ for (idx_t i = 0; i < n; i++) {
+ uint8_t* code = codes.data() + i * q->code_size;
+ BitstringReader bsr(code, q->code_size);
+
+ // unpacked_codes[i][s][m] = codes[i][m]
+ for (size_t m = 0; m < q->M; m++) {
+ unpacked_codes[i * M + offset_m + m] = bsr.read(q->nbits[m]);
+ }
+ }
+
+ offset_d += q->d;
+ offset_m += q->M;
+ }
+}
+
+void ProductAdditiveQuantizer::decode_unpacked(
+ const int32_t* codes,
+ float* x,
+ size_t n,
+ int64_t ld_codes) const {
+ FAISS_THROW_IF_NOT_MSG(
+ is_trained, "The product additive quantizer is not trained yet.");
+
+ if (ld_codes == -1) {
+ ld_codes = M;
+ }
+
+ // product additive quantizer decoding
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const int32_t* codesi = codes + i * ld_codes;
+
+ size_t offset_m = 0, offset_d = 0;
+ for (size_t s = 0; s < nsplits; s++) {
+ const auto q = quantizers[s];
+ float* xi = x + i * d + offset_d;
+
+ for (int m = 0; m < q->M; m++) {
+ int idx = codesi[offset_m + m];
+ const float* c = codebooks.data() +
+ q->d * (codebook_offsets[offset_m + m] + idx);
+ if (m == 0) {
+ memcpy(xi, c, sizeof(*x) * q->d);
+ } else {
+ fvec_add(q->d, xi, c, xi);
+ }
+ }
+
+ offset_m += q->M;
+ offset_d += q->d;
+ }
+ }
+}
+
+void ProductAdditiveQuantizer::decode(const uint8_t* codes, float* x, size_t n)
+ const {
+ FAISS_THROW_IF_NOT_MSG(
+ is_trained, "The product additive quantizer is not trained yet.");
+
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ BitstringReader bsr(codes + i * code_size, code_size);
+
+ size_t offset_m = 0, offset_d = 0;
+ for (size_t s = 0; s < nsplits; s++) {
+ const auto q = quantizers[s];
+ float* xi = x + i * d + offset_d;
+
+ for (int m = 0; m < q->M; m++) {
+ int idx = bsr.read(q->nbits[m]);
+ const float* c = codebooks.data() +
+ q->d * (codebook_offsets[offset_m + m] + idx);
+ if (m == 0) {
+ memcpy(xi, c, sizeof(*x) * q->d);
+ } else {
+ fvec_add(q->d, xi, c, xi);
+ }
+ }
+
+ offset_m += q->M;
+ offset_d += q->d;
+ }
+ }
+}
+
+void ProductAdditiveQuantizer::compute_LUT(
+ size_t n,
+ const float* xq,
+ float* LUT,
+ float alpha,
+ long ld_lut) const {
+ // codebooks: size (M * ksub, dsub)
+ // xq: size (n, d)
+ // output LUT: size (n, M * ksub)
+
+ FINTEGER nqi = n;
+ // leading dimension of 'LUT' and 'xq'
+ FINTEGER ld_LUT = ld_lut > 0 ? ld_lut : total_codebook_size;
+ FINTEGER ld_xq = d;
+
+ float zero = 0;
+ size_t offset_d = 0;
+ size_t offset_cb = 0;
+ size_t offset_lut = 0;
+
+ for (size_t s = 0; s < nsplits; s++) {
+ const auto q = quantizers[s];
+
+ FINTEGER ncenti = q->total_codebook_size;
+ FINTEGER ld_cb = q->d; // leading dimension of 'codebooks'
+
+ auto codebooksi = codebooks.data() + offset_cb;
+ auto xqi = xq + offset_d;
+ auto LUTi = LUT + offset_lut;
+
+ sgemm_("Transposed",
+ "Not transposed",
+ &ncenti,
+ &nqi,
+ &ld_cb,
+ &alpha,
+ codebooksi,
+ &ld_cb,
+ xqi,
+ &ld_xq,
+ &zero,
+ LUTi,
+ &ld_LUT);
+
+ offset_d += q->d;
+ offset_cb += q->total_codebook_size * q->d;
+ offset_lut += q->total_codebook_size;
+ }
+}
+
+/*************************************
+ * Product Local Search Quantizer
+ ************************************/
+
+ProductLocalSearchQuantizer::ProductLocalSearchQuantizer(
+ size_t d,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ Search_type_t search_type) {
+ std::vector<AdditiveQuantizer*> aqs;
+
+ if (nsplits > 0) {
+ FAISS_THROW_IF_NOT(d % nsplits == 0);
+ size_t dsub = d / nsplits;
+
+ for (size_t i = 0; i < nsplits; i++) {
+ auto lsq =
+ new LocalSearchQuantizer(dsub, Msub, nbits, ST_decompress);
+ aqs.push_back(lsq);
+ }
+ }
+ init(d, aqs, search_type);
+ for (auto& q : aqs) {
+ delete q;
+ }
+}
+
+ProductLocalSearchQuantizer::ProductLocalSearchQuantizer()
+ : ProductLocalSearchQuantizer(0, 0, 0, 0) {}
+
+/*************************************
+ * Product Residual Quantizer
+ ************************************/
+
+ProductResidualQuantizer::ProductResidualQuantizer(
+ size_t d,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ Search_type_t search_type) {
+ std::vector<AdditiveQuantizer*> aqs;
+
+ if (nsplits > 0) {
+ FAISS_THROW_IF_NOT(d % nsplits == 0);
+ size_t dsub = d / nsplits;
+
+ for (size_t i = 0; i < nsplits; i++) {
+ auto rq = new ResidualQuantizer(dsub, Msub, nbits, ST_decompress);
+ aqs.push_back(rq);
+ }
+ }
+ init(d, aqs, search_type);
+ for (auto& q : aqs) {
+ delete q;
+ }
+}
+
+ProductResidualQuantizer::ProductResidualQuantizer()
+ : ProductResidualQuantizer(0, 0, 0, 0) {}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductAdditiveQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductAdditiveQuantizer.h
new file mode 100644
index 0000000..dc33684
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductAdditiveQuantizer.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/impl/AdditiveQuantizer.h>
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/ResidualQuantizer.h>
+
+namespace faiss {
+
+/** Product Additive Quantizers
+ *
+ * The product additive quantizer is a variant of AQ and PQ.
+ * It first splits the vector space into multiple orthogonal sub-spaces
+ * just like PQ does. And then it quantizes each sub-space by an independent
+ * additive quantizer.
+ *
+ */
+struct ProductAdditiveQuantizer : AdditiveQuantizer {
+ size_t nsplits; ///< number of sub-vectors we split a vector into
+
+ std::vector<AdditiveQuantizer*> quantizers;
+
+ /** Construct a product additive quantizer.
+ *
+ * The additive quantizers passed in will be cloned into the
+ * ProductAdditiveQuantizer object.
+ *
+ * @param d dimensionality of the input vectors
+ * @param aqs sub-additive quantizers
+ * @param search_type AQ search type
+ */
+ ProductAdditiveQuantizer(
+ size_t d,
+ const std::vector<AdditiveQuantizer*>& aqs,
+ Search_type_t search_type = ST_decompress);
+
+ ProductAdditiveQuantizer();
+
+ virtual ~ProductAdditiveQuantizer();
+
+ void init(
+ size_t d,
+ const std::vector<AdditiveQuantizer*>& aqs,
+ Search_type_t search_type);
+
+ AdditiveQuantizer* subquantizer(size_t m) const;
+
+ ///< Train the product additive quantizer
+ void train(size_t n, const float* x) override;
+
+ /** Encode a set of vectors
+ *
+ * @param x vectors to encode, size n * d
+ * @param codes output codes, size n * code_size
+ * @param centroids centroids to be added to x, size n * d
+ */
+ void compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes,
+ size_t n,
+ const float* centroids = nullptr) const override;
+
+ void compute_unpacked_codes(
+ const float* x,
+ int32_t* codes,
+ size_t n,
+ const float* centroids = nullptr) const;
+
+ /** Decode a set of vectors in non-packed format
+ *
+ * @param codes codes to decode, size n * ld_codes
+ * @param x output vectors, size n * d
+ */
+ void decode_unpacked(
+ const int32_t* codes,
+ float* x,
+ size_t n,
+ int64_t ld_codes = -1) const override;
+
+ /** Decode a set of vectors
+ *
+ * @param codes codes to decode, size n * code_size
+ * @param x output vectors, size n * d
+ */
+ void decode(const uint8_t* codes, float* x, size_t n) const override;
+
+ /** Compute inner-product look-up tables. Used in the search functions.
+ *
+ * @param xq query vector, size (n, d)
+ * @param LUT look-up table, size (n, total_codebook_size)
+ * @param alpha compute alpha * inner-product
+ * @param ld_lut leading dimension of LUT
+ */
+ void compute_LUT(
+ size_t n,
+ const float* xq,
+ float* LUT,
+ float alpha = 1.0f,
+ long ld_lut = -1) const override;
+};
+
+/** Product Local Search Quantizer
+ */
+struct ProductLocalSearchQuantizer : ProductAdditiveQuantizer {
+ /** Construct a product LSQ object.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of sub-vectors we split a vector into
+ * @param Msub number of codebooks of each LSQ
+ * @param nbits bits for each step
+ * @param search_type AQ search type
+ */
+ ProductLocalSearchQuantizer(
+ size_t d,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ Search_type_t search_type = ST_decompress);
+
+ ProductLocalSearchQuantizer();
+};
+
+/** Product Residual Quantizer
+ */
+struct ProductResidualQuantizer : ProductAdditiveQuantizer {
+ /** Construct a product RQ object.
+ *
+ * @param d dimensionality of the input vectors
+ * @param nsplits number of sub-vectors we split a vector into
+ * @param Msub number of codebooks of each RQ
+ * @param nbits bits for each step
+ * @param search_type AQ search type
+ */
+ ProductResidualQuantizer(
+ size_t d,
+ size_t nsplits,
+ size_t Msub,
+ size_t nbits,
+ Search_type_t search_type = ST_decompress);
+
+ ProductResidualQuantizer();
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer-inl.h
new file mode 100644
index 0000000..a76ab25
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer-inl.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+namespace faiss {
+
+inline PQEncoderGeneric::PQEncoderGeneric(
+ uint8_t* code,
+ int nbits,
+ uint8_t offset)
+ : code(code), offset(offset), nbits(nbits), reg(0) {
+ assert(nbits <= 64);
+ if (offset > 0) {
+ reg = (*code & ((1 << offset) - 1));
+ }
+}
+
+inline void PQEncoderGeneric::encode(uint64_t x) {
+ reg |= (uint8_t)(x << offset);
+ x >>= (8 - offset);
+ if (offset + nbits >= 8) {
+ *code++ = reg;
+
+ for (int i = 0; i < (nbits - (8 - offset)) / 8; ++i) {
+ *code++ = (uint8_t)x;
+ x >>= 8;
+ }
+
+ offset += nbits;
+ offset &= 7;
+ reg = (uint8_t)x;
+ } else {
+ offset += nbits;
+ }
+}
+
+inline PQEncoderGeneric::~PQEncoderGeneric() {
+ if (offset > 0) {
+ *code = reg;
+ }
+}
+
+inline PQEncoder8::PQEncoder8(uint8_t* code, int nbits) : code(code) {
+ assert(8 == nbits);
+}
+
+inline void PQEncoder8::encode(uint64_t x) {
+ *code++ = (uint8_t)x;
+}
+
+inline PQEncoder16::PQEncoder16(uint8_t* code, int nbits)
+ : code((uint16_t*)code) {
+ assert(16 == nbits);
+}
+
+inline void PQEncoder16::encode(uint64_t x) {
+ *code++ = (uint16_t)x;
+}
+
+inline PQDecoderGeneric::PQDecoderGeneric(const uint8_t* code, int nbits)
+ : code(code),
+ offset(0),
+ nbits(nbits),
+ mask((1ull << nbits) - 1),
+ reg(0) {
+ assert(nbits <= 64);
+}
+
+inline uint64_t PQDecoderGeneric::decode() {
+ if (offset == 0) {
+ reg = *code;
+ }
+ uint64_t c = (reg >> offset);
+
+ if (offset + nbits >= 8) {
+ uint64_t e = 8 - offset;
+ ++code;
+ for (int i = 0; i < (nbits - (8 - offset)) / 8; ++i) {
+ c |= ((uint64_t)(*code++) << e);
+ e += 8;
+ }
+
+ offset += nbits;
+ offset &= 7;
+ if (offset > 0) {
+ reg = *code;
+ c |= ((uint64_t)reg << e);
+ }
+ } else {
+ offset += nbits;
+ }
+
+ return c & mask;
+}
+
+inline PQDecoder8::PQDecoder8(const uint8_t* code, int nbits_in) : code(code) {
+ assert(8 == nbits_in);
+}
+
+inline uint64_t PQDecoder8::decode() {
+ return (uint64_t)(*code++);
+}
+
+inline PQDecoder16::PQDecoder16(const uint8_t* code, int nbits_in)
+ : code((uint16_t*)code) {
+ assert(16 == nbits_in);
+}
+
+inline uint64_t PQDecoder16::decode() {
+ return (uint64_t)(*code++);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer.cpp
new file mode 100644
index 0000000..3fbedb8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer.cpp
@@ -0,0 +1,880 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/ProductQuantizer.h>
+
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+
+#include <algorithm>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/VectorTransform.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+
+extern "C" {
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+/*********************************************
+ * PQ implementation
+ *********************************************/
+
+ProductQuantizer::ProductQuantizer(size_t d, size_t M, size_t nbits)
+ : Quantizer(d, 0), M(M), nbits(nbits), assign_index(nullptr) {
+ set_derived_values();
+}
+
+ProductQuantizer::ProductQuantizer() : ProductQuantizer(0, 1, 0) {}
+
+void ProductQuantizer::set_derived_values() {
+ // quite a few derived values
+ FAISS_THROW_IF_NOT_MSG(
+ d % M == 0,
+ "The dimension of the vector (d) should be a multiple of the number of subquantizers (M)");
+ dsub = d / M;
+ code_size = (nbits * M + 7) / 8;
+ FAISS_THROW_IF_MSG(nbits > 24, "nbits larger than 24 is not practical.");
+ ksub = 1 << nbits;
+ centroids.resize(d * ksub);
+ verbose = false;
+ train_type = Train_default;
+}
+
+void ProductQuantizer::set_params(const float* centroids_, int m) {
+ memcpy(get_centroids(m, 0),
+ centroids_,
+ ksub * dsub * sizeof(centroids_[0]));
+}
+
+static void init_hypercube(
+ int d,
+ int nbits,
+ int n,
+ const float* x,
+ float* centroids) {
+ std::vector<float> mean(d);
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < d; j++)
+ mean[j] += x[i * d + j];
+
+ float maxm = 0;
+ for (int j = 0; j < d; j++) {
+ mean[j] /= n;
+ if (fabs(mean[j]) > maxm)
+ maxm = fabs(mean[j]);
+ }
+
+ for (int i = 0; i < (1 << nbits); i++) {
+ float* cent = centroids + i * d;
+ for (int j = 0; j < nbits; j++)
+ cent[j] = mean[j] + (((i >> j) & 1) ? 1 : -1) * maxm;
+ for (int j = nbits; j < d; j++)
+ cent[j] = mean[j];
+ }
+}
+
+static void init_hypercube_pca(
+ int d,
+ int nbits,
+ int n,
+ const float* x,
+ float* centroids) {
+ PCAMatrix pca(d, nbits);
+ pca.train(n, x);
+
+ for (int i = 0; i < (1 << nbits); i++) {
+ float* cent = centroids + i * d;
+ for (int j = 0; j < d; j++) {
+ cent[j] = pca.mean[j];
+ float f = 1.0;
+ for (int k = 0; k < nbits; k++)
+ cent[j] += f * sqrt(pca.eigenvalues[k]) *
+ (((i >> k) & 1) ? 1 : -1) * pca.PCAMat[j + k * d];
+ }
+ }
+}
+
+void ProductQuantizer::train(size_t n, const float* x) {
+ if (train_type != Train_shared) {
+ train_type_t final_train_type;
+ final_train_type = train_type;
+ if (train_type == Train_hypercube ||
+ train_type == Train_hypercube_pca) {
+ if (dsub < nbits) {
+ final_train_type = Train_default;
+ printf("cannot train hypercube: nbits=%zd > log2(d=%zd)\n",
+ nbits,
+ dsub);
+ }
+ }
+
+ std::unique_ptr<float[]> xslice(new float[n * dsub]);
+ for (int m = 0; m < M; m++) {
+ for (int j = 0; j < n; j++)
+ memcpy(xslice.get() + j * dsub,
+ x + j * d + m * dsub,
+ dsub * sizeof(float));
+
+ Clustering clus(dsub, ksub, cp);
+
+ // we have some initialization for the centroids
+ if (final_train_type != Train_default) {
+ clus.centroids.resize(dsub * ksub);
+ }
+
+ switch (final_train_type) {
+ case Train_hypercube:
+ init_hypercube(
+ dsub,
+ nbits,
+ n,
+ xslice.get(),
+ clus.centroids.data());
+ break;
+ case Train_hypercube_pca:
+ init_hypercube_pca(
+ dsub,
+ nbits,
+ n,
+ xslice.get(),
+ clus.centroids.data());
+ break;
+ case Train_hot_start:
+ memcpy(clus.centroids.data(),
+ get_centroids(m, 0),
+ dsub * ksub * sizeof(float));
+ break;
+ default:;
+ }
+
+ if (verbose) {
+ clus.verbose = true;
+ printf("Training PQ slice %d/%zd\n", m, M);
+ }
+ IndexFlatL2 index(dsub);
+ clus.train(n, xslice.get(), assign_index ? *assign_index : index);
+ set_params(clus.centroids.data(), m);
+ }
+
+ } else {
+ Clustering clus(dsub, ksub, cp);
+
+ if (verbose) {
+ clus.verbose = true;
+ printf("Training all PQ slices at once\n");
+ }
+
+ IndexFlatL2 index(dsub);
+
+ clus.train(n * M, x, assign_index ? *assign_index : index);
+ for (int m = 0; m < M; m++) {
+ set_params(clus.centroids.data(), m);
+ }
+ }
+}
+
+template <class PQEncoder>
+void compute_code(const ProductQuantizer& pq, const float* x, uint8_t* code) {
+ std::vector<float> distances(pq.ksub);
+
+ // It seems to be meaningless to allocate std::vector<float> distances.
+ // But it is done in order to cope the ineffectiveness of the way
+ // the compiler generates the code. Basically, doing something like
+ //
+ // size_t min_distance = HUGE_VALF;
+ // size_t idxm = 0;
+ // for (size_t i = 0; i < N; i++) {
+ // const float distance = compute_distance(x, y + i * d, d);
+ // if (distance < min_distance) {
+ // min_distance = distance;
+ // idxm = i;
+ // }
+ // }
+ //
+ // generates significantly more CPU instructions than the baseline
+ //
+ // std::vector<float> distances_cached(N);
+ // for (size_t i = 0; i < N; i++) {
+ // distances_cached[i] = compute_distance(x, y + i * d, d);
+ // }
+ // size_t min_distance = HUGE_VALF;
+ // size_t idxm = 0;
+ // for (size_t i = 0; i < N; i++) {
+ // const float distance = distances_cached[i];
+ // if (distance < min_distance) {
+ // min_distance = distance;
+ // idxm = i;
+ // }
+ // }
+ //
+ // So, the baseline is faster. This is because of the vectorization.
+ // I suppose that the branch predictor might affect the performance as well.
+ // So, the buffer is allocated, but it might be unused in
+ // manually optimized code. Let's hope that the compiler is smart enough to
+ // get rid of std::vector allocation in such a case.
+
+ PQEncoder encoder(code, pq.nbits);
+ for (size_t m = 0; m < pq.M; m++) {
+ const float* xsub = x + m * pq.dsub;
+
+ uint64_t idxm = 0;
+ if (pq.transposed_centroids.empty()) {
+ // the regular version
+ idxm = fvec_L2sqr_ny_nearest(
+ distances.data(),
+ xsub,
+ pq.get_centroids(m, 0),
+ pq.dsub,
+ pq.ksub);
+ } else {
+ // transposed centroids are available, use'em
+ idxm = fvec_L2sqr_ny_nearest_y_transposed(
+ distances.data(),
+ xsub,
+ pq.transposed_centroids.data() + m * pq.ksub,
+ pq.centroids_sq_lengths.data() + m * pq.ksub,
+ pq.dsub,
+ pq.M * pq.ksub,
+ pq.ksub);
+ }
+
+ encoder.encode(idxm);
+ }
+}
+
+void ProductQuantizer::compute_code(const float* x, uint8_t* code) const {
+ switch (nbits) {
+ case 8:
+ faiss::compute_code<PQEncoder8>(*this, x, code);
+ break;
+
+ case 16:
+ faiss::compute_code<PQEncoder16>(*this, x, code);
+ break;
+
+ default:
+ faiss::compute_code<PQEncoderGeneric>(*this, x, code);
+ break;
+ }
+}
+
+template <class PQDecoder>
+void decode(const ProductQuantizer& pq, const uint8_t* code, float* x) {
+ PQDecoder decoder(code, pq.nbits);
+ for (size_t m = 0; m < pq.M; m++) {
+ uint64_t c = decoder.decode();
+ memcpy(x + m * pq.dsub,
+ pq.get_centroids(m, c),
+ sizeof(float) * pq.dsub);
+ }
+}
+
+void ProductQuantizer::decode(const uint8_t* code, float* x) const {
+ switch (nbits) {
+ case 8:
+ faiss::decode<PQDecoder8>(*this, code, x);
+ break;
+
+ case 16:
+ faiss::decode<PQDecoder16>(*this, code, x);
+ break;
+
+ default:
+ faiss::decode<PQDecoderGeneric>(*this, code, x);
+ break;
+ }
+}
+
+void ProductQuantizer::decode(const uint8_t* code, float* x, size_t n) const {
+#pragma omp parallel for if (n > 100)
+ for (int64_t i = 0; i < n; i++) {
+ this->decode(code + code_size * i, x + d * i);
+ }
+}
+
+void ProductQuantizer::compute_code_from_distance_table(
+ const float* tab,
+ uint8_t* code) const {
+ PQEncoderGeneric encoder(code, nbits);
+ for (size_t m = 0; m < M; m++) {
+ float mindis = 1e20;
+ uint64_t idxm = 0;
+
+ /* Find best centroid */
+ for (size_t j = 0; j < ksub; j++) {
+ float dis = *tab++;
+ if (dis < mindis) {
+ mindis = dis;
+ idxm = j;
+ }
+ }
+
+ encoder.encode(idxm);
+ }
+}
+
+void ProductQuantizer::compute_codes_with_assign_index(
+ const float* x,
+ uint8_t* codes,
+ size_t n) {
+ FAISS_THROW_IF_NOT(assign_index && assign_index->d == dsub);
+
+ for (size_t m = 0; m < M; m++) {
+ assign_index->reset();
+ assign_index->add(ksub, get_centroids(m, 0));
+ size_t bs = 65536;
+
+ std::unique_ptr<float[]> xslice(new float[bs * dsub]);
+ std::unique_ptr<idx_t[]> assign(new idx_t[bs]);
+
+ for (size_t i0 = 0; i0 < n; i0 += bs) {
+ size_t i1 = std::min(i0 + bs, n);
+
+ for (size_t i = i0; i < i1; i++) {
+ memcpy(xslice.get() + (i - i0) * dsub,
+ x + i * d + m * dsub,
+ dsub * sizeof(float));
+ }
+
+ assign_index->assign(i1 - i0, xslice.get(), assign.get());
+
+ if (nbits == 8) {
+ uint8_t* c = codes + code_size * i0 + m;
+ for (size_t i = i0; i < i1; i++) {
+ *c = assign[i - i0];
+ c += M;
+ }
+ } else if (nbits == 16) {
+ uint16_t* c = (uint16_t*)(codes + code_size * i0 + m * 2);
+ for (size_t i = i0; i < i1; i++) {
+ *c = assign[i - i0];
+ c += M;
+ }
+ } else {
+ for (size_t i = i0; i < i1; ++i) {
+ uint8_t* c = codes + code_size * i + ((m * nbits) / 8);
+ uint8_t offset = (m * nbits) % 8;
+ uint64_t ass = assign[i - i0];
+
+ PQEncoderGeneric encoder(c, nbits, offset);
+ encoder.encode(ass);
+ }
+ }
+ }
+ }
+}
+
+// block size used in ProductQuantizer::compute_codes
+int product_quantizer_compute_codes_bs = 256 * 1024;
+
+void ProductQuantizer::compute_codes(const float* x, uint8_t* codes, size_t n)
+ const {
+ // process by blocks to avoid using too much RAM
+ size_t bs = product_quantizer_compute_codes_bs;
+ if (n > bs) {
+ for (size_t i0 = 0; i0 < n; i0 += bs) {
+ size_t i1 = std::min(i0 + bs, n);
+ compute_codes(x + d * i0, codes + code_size * i0, i1 - i0);
+ }
+ return;
+ }
+
+ if (dsub < 16) { // simple direct computation
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++)
+ compute_code(x + i * d, codes + i * code_size);
+
+ } else { // worthwhile to use BLAS
+ std::unique_ptr<float[]> dis_tables(new float[n * ksub * M]);
+ compute_distance_tables(n, x, dis_tables.get());
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++) {
+ uint8_t* code = codes + i * code_size;
+ const float* tab = dis_tables.get() + i * ksub * M;
+ compute_code_from_distance_table(tab, code);
+ }
+ }
+}
+
+void ProductQuantizer::compute_distance_table(const float* x, float* dis_table)
+ const {
+ if (transposed_centroids.empty()) {
+ // use regular version
+ for (size_t m = 0; m < M; m++) {
+ fvec_L2sqr_ny(
+ dis_table + m * ksub,
+ x + m * dsub,
+ get_centroids(m, 0),
+ dsub,
+ ksub);
+ }
+ } else {
+ // transposed centroids are available, use'em
+ for (size_t m = 0; m < M; m++) {
+ fvec_L2sqr_ny_transposed(
+ dis_table + m * ksub,
+ x + m * dsub,
+ transposed_centroids.data() + m * ksub,
+ centroids_sq_lengths.data() + m * ksub,
+ dsub,
+ M * ksub,
+ ksub);
+ }
+ }
+}
+
+void ProductQuantizer::compute_inner_prod_table(
+ const float* x,
+ float* dis_table) const {
+ size_t m;
+
+ for (m = 0; m < M; m++) {
+ fvec_inner_products_ny(
+ dis_table + m * ksub,
+ x + m * dsub,
+ get_centroids(m, 0),
+ dsub,
+ ksub);
+ }
+}
+
+void ProductQuantizer::compute_distance_tables(
+ size_t nx,
+ const float* x,
+ float* dis_tables) const {
+#if defined(__AVX2__) || defined(__aarch64__)
+ if (dsub == 2 && nbits < 8) { // interesting for a narrow range of settings
+ compute_PQ_dis_tables_dsub2(
+ d, ksub, centroids.data(), nx, x, false, dis_tables);
+ } else
+#endif
+ if (dsub < 16) {
+
+#pragma omp parallel for if (nx > 1)
+ for (int64_t i = 0; i < nx; i++) {
+ compute_distance_table(x + i * d, dis_tables + i * ksub * M);
+ }
+
+ } else { // use BLAS
+
+ for (int m = 0; m < M; m++) {
+ pairwise_L2sqr(
+ dsub,
+ nx,
+ x + dsub * m,
+ ksub,
+ centroids.data() + m * dsub * ksub,
+ dis_tables + ksub * m,
+ d,
+ dsub,
+ ksub * M);
+ }
+ }
+}
+
+void ProductQuantizer::compute_inner_prod_tables(
+ size_t nx,
+ const float* x,
+ float* dis_tables) const {
+#if defined(__AVX2__) || defined(__aarch64__)
+ if (dsub == 2 && nbits < 8) {
+ compute_PQ_dis_tables_dsub2(
+ d, ksub, centroids.data(), nx, x, true, dis_tables);
+ } else
+#endif
+ if (dsub < 16) {
+
+#pragma omp parallel for if (nx > 1)
+ for (int64_t i = 0; i < nx; i++) {
+ compute_inner_prod_table(x + i * d, dis_tables + i * ksub * M);
+ }
+
+ } else { // use BLAS
+
+ // compute distance tables
+ for (int m = 0; m < M; m++) {
+ FINTEGER ldc = ksub * M, nxi = nx, ksubi = ksub, dsubi = dsub,
+ di = d;
+ float one = 1.0, zero = 0;
+
+ sgemm_("Transposed",
+ "Not transposed",
+ &ksubi,
+ &nxi,
+ &dsubi,
+ &one,
+ &centroids[m * dsub * ksub],
+ &dsubi,
+ x + dsub * m,
+ &di,
+ &zero,
+ dis_tables + ksub * m,
+ &ldc);
+ }
+ }
+}
+
+/**********************************************
+ * Templatized search functions
+ * The template class C indicates whether to keep the highest or smallest values
+ **********************************************/
+
+namespace {
+
+/* compute an estimator using look-up tables for typical values of M */
+template <typename CT, class C>
+void pq_estimators_from_tables_Mmul4(
+ int M,
+ const CT* codes,
+ size_t ncodes,
+ const float* __restrict dis_table,
+ size_t ksub,
+ size_t k,
+ float* heap_dis,
+ int64_t* heap_ids) {
+ for (size_t j = 0; j < ncodes; j++) {
+ float dis = 0;
+ const float* dt = dis_table;
+
+ for (size_t m = 0; m < M; m += 4) {
+ float dism = 0;
+ dism = dt[*codes++];
+ dt += ksub;
+ dism += dt[*codes++];
+ dt += ksub;
+ dism += dt[*codes++];
+ dt += ksub;
+ dism += dt[*codes++];
+ dt += ksub;
+ dis += dism;
+ }
+
+ if (C::cmp(heap_dis[0], dis)) {
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis, j);
+ }
+ }
+}
+
+template <typename CT, class C>
+void pq_estimators_from_tables_M4(
+ const CT* codes,
+ size_t ncodes,
+ const float* __restrict dis_table,
+ size_t ksub,
+ size_t k,
+ float* heap_dis,
+ int64_t* heap_ids) {
+ for (size_t j = 0; j < ncodes; j++) {
+ float dis = 0;
+ const float* dt = dis_table;
+ dis = dt[*codes++];
+ dt += ksub;
+ dis += dt[*codes++];
+ dt += ksub;
+ dis += dt[*codes++];
+ dt += ksub;
+ dis += dt[*codes++];
+
+ if (C::cmp(heap_dis[0], dis)) {
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis, j);
+ }
+ }
+}
+
+template <typename CT, class C>
+void pq_estimators_from_tables(
+ const ProductQuantizer& pq,
+ const CT* codes,
+ size_t ncodes,
+ const float* dis_table,
+ size_t k,
+ float* heap_dis,
+ int64_t* heap_ids) {
+ if (pq.M == 4) {
+ pq_estimators_from_tables_M4<CT, C>(
+ codes, ncodes, dis_table, pq.ksub, k, heap_dis, heap_ids);
+ return;
+ }
+
+ if (pq.M % 4 == 0) {
+ pq_estimators_from_tables_Mmul4<CT, C>(
+ pq.M, codes, ncodes, dis_table, pq.ksub, k, heap_dis, heap_ids);
+ return;
+ }
+
+ /* Default is relatively slow */
+ const size_t M = pq.M;
+ const size_t ksub = pq.ksub;
+ for (size_t j = 0; j < ncodes; j++) {
+ float dis = 0;
+ const float* __restrict dt = dis_table;
+ for (int m = 0; m < M; m++) {
+ dis += dt[*codes++];
+ dt += ksub;
+ }
+ if (C::cmp(heap_dis[0], dis)) {
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis, j);
+ }
+ }
+}
+
+template <class C>
+void pq_estimators_from_tables_generic(
+ const ProductQuantizer& pq,
+ size_t nbits,
+ const uint8_t* codes,
+ size_t ncodes,
+ const float* dis_table,
+ size_t k,
+ float* heap_dis,
+ int64_t* heap_ids) {
+ const size_t M = pq.M;
+ const size_t ksub = pq.ksub;
+ for (size_t j = 0; j < ncodes; ++j) {
+ PQDecoderGeneric decoder(codes + j * pq.code_size, nbits);
+ float dis = 0;
+ const float* __restrict dt = dis_table;
+ for (size_t m = 0; m < M; m++) {
+ uint64_t c = decoder.decode();
+ dis += dt[c];
+ dt += ksub;
+ }
+
+ if (C::cmp(heap_dis[0], dis)) {
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis, j);
+ }
+ }
+}
+
+template <class C>
+void pq_knn_search_with_tables(
+ const ProductQuantizer& pq,
+ size_t nbits,
+ const float* dis_tables,
+ const uint8_t* codes,
+ const size_t ncodes,
+ HeapArray<C>* res,
+ bool init_finalize_heap) {
+ size_t k = res->k, nx = res->nh;
+ size_t ksub = pq.ksub, M = pq.M;
+
+#pragma omp parallel for if (nx > 1)
+ for (int64_t i = 0; i < nx; i++) {
+ /* query preparation for asymmetric search: compute look-up tables */
+ const float* dis_table = dis_tables + i * ksub * M;
+
+ /* Compute distances and keep smallest values */
+ int64_t* __restrict heap_ids = res->ids + i * k;
+ float* __restrict heap_dis = res->val + i * k;
+
+ if (init_finalize_heap) {
+ heap_heapify<C>(k, heap_dis, heap_ids);
+ }
+
+ switch (nbits) {
+ case 8:
+ pq_estimators_from_tables<uint8_t, C>(
+ pq, codes, ncodes, dis_table, k, heap_dis, heap_ids);
+ break;
+
+ case 16:
+ pq_estimators_from_tables<uint16_t, C>(
+ pq,
+ (uint16_t*)codes,
+ ncodes,
+ dis_table,
+ k,
+ heap_dis,
+ heap_ids);
+ break;
+
+ default:
+ pq_estimators_from_tables_generic<C>(
+ pq,
+ nbits,
+ codes,
+ ncodes,
+ dis_table,
+ k,
+ heap_dis,
+ heap_ids);
+ break;
+ }
+
+ if (init_finalize_heap) {
+ heap_reorder<C>(k, heap_dis, heap_ids);
+ }
+ }
+}
+
+} // anonymous namespace
+
+void ProductQuantizer::search(
+ const float* __restrict x,
+ size_t nx,
+ const uint8_t* codes,
+ const size_t ncodes,
+ float_maxheap_array_t* res,
+ bool init_finalize_heap) const {
+ FAISS_THROW_IF_NOT(nx == res->nh);
+ std::unique_ptr<float[]> dis_tables(new float[nx * ksub * M]);
+ compute_distance_tables(nx, x, dis_tables.get());
+
+ pq_knn_search_with_tables<CMax<float, int64_t>>(
+ *this,
+ nbits,
+ dis_tables.get(),
+ codes,
+ ncodes,
+ res,
+ init_finalize_heap);
+}
+
+void ProductQuantizer::search_ip(
+ const float* __restrict x,
+ size_t nx,
+ const uint8_t* codes,
+ const size_t ncodes,
+ float_minheap_array_t* res,
+ bool init_finalize_heap) const {
+ FAISS_THROW_IF_NOT(nx == res->nh);
+ std::unique_ptr<float[]> dis_tables(new float[nx * ksub * M]);
+ compute_inner_prod_tables(nx, x, dis_tables.get());
+
+ pq_knn_search_with_tables<CMin<float, int64_t>>(
+ *this,
+ nbits,
+ dis_tables.get(),
+ codes,
+ ncodes,
+ res,
+ init_finalize_heap);
+}
+
+void ProductQuantizer::compute_sdc_table() {
+ sdc_table.resize(M * ksub * ksub);
+
+ if (dsub < 4) {
+#pragma omp parallel for
+ for (int mk = 0; mk < M * ksub; mk++) {
+ // allow omp to schedule in a more fine-grained way
+ // `collapse` is not supported in OpenMP 2.x
+ int m = mk / ksub;
+ int k = mk % ksub;
+ const float* cents = centroids.data() + m * ksub * dsub;
+ const float* centi = cents + k * dsub;
+ float* dis_tab = sdc_table.data() + m * ksub * ksub;
+ fvec_L2sqr_ny(dis_tab + k * ksub, centi, cents, dsub, ksub);
+ }
+ } else {
+ // NOTE: it would disable the omp loop in pairwise_L2sqr
+ // but still accelerate especially when M >= 4
+#pragma omp parallel for
+ for (int m = 0; m < M; m++) {
+ const float* cents = centroids.data() + m * ksub * dsub;
+ float* dis_tab = sdc_table.data() + m * ksub * ksub;
+ pairwise_L2sqr(
+ dsub, ksub, cents, ksub, cents, dis_tab, dsub, dsub, ksub);
+ }
+ }
+}
+
+void ProductQuantizer::search_sdc(
+ const uint8_t* qcodes,
+ size_t nq,
+ const uint8_t* bcodes,
+ const size_t nb,
+ float_maxheap_array_t* res,
+ bool init_finalize_heap) const {
+ FAISS_THROW_IF_NOT(sdc_table.size() == M * ksub * ksub);
+ FAISS_THROW_IF_NOT(nbits == 8);
+ size_t k = res->k;
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < nq; i++) {
+ /* Compute distances and keep smallest values */
+ idx_t* heap_ids = res->ids + i * k;
+ float* heap_dis = res->val + i * k;
+ const uint8_t* qcode = qcodes + i * code_size;
+
+ if (init_finalize_heap)
+ maxheap_heapify(k, heap_dis, heap_ids);
+
+ const uint8_t* bcode = bcodes;
+ for (size_t j = 0; j < nb; j++) {
+ float dis = 0;
+ const float* tab = sdc_table.data();
+ for (int m = 0; m < M; m++) {
+ dis += tab[bcode[m] + qcode[m] * ksub];
+ tab += ksub * ksub;
+ }
+ if (dis < heap_dis[0]) {
+ maxheap_replace_top(k, heap_dis, heap_ids, dis, j);
+ }
+ bcode += code_size;
+ }
+
+ if (init_finalize_heap)
+ maxheap_reorder(k, heap_dis, heap_ids);
+ }
+}
+
+void ProductQuantizer::sync_transposed_centroids() {
+ transposed_centroids.resize(d * ksub);
+ centroids_sq_lengths.resize(ksub * M);
+
+ for (size_t mi = 0; mi < M; mi++) {
+ for (size_t ki = 0; ki < ksub; ki++) {
+ float sqlen = 0;
+
+ for (size_t di = 0; di < dsub; di++) {
+ const float q = centroids[(mi * ksub + ki) * dsub + di];
+
+ transposed_centroids[(di * M + mi) * ksub + ki] = q;
+ sqlen += q * q;
+ }
+
+ centroids_sq_lengths[mi * ksub + ki] = sqlen;
+ }
+ }
+}
+
+void ProductQuantizer::clear_transposed_centroids() {
+ transposed_centroids.clear();
+ transposed_centroids.shrink_to_fit();
+
+ centroids_sq_lengths.clear();
+ centroids_sq_lengths.shrink_to_fit();
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer.h
new file mode 100644
index 0000000..57c005c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ProductQuantizer.h
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_PRODUCT_QUANTIZER_H
+#define FAISS_PRODUCT_QUANTIZER_H
+
+#include <stdint.h>
+
+#include <vector>
+
+#include <faiss/Clustering.h>
+#include <faiss/impl/Quantizer.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+/** Product Quantizer.
+ * PQ is trained using k-means, minimizing the L2 distance to centroids.
+ * PQ supports L2 and Inner Product search, however the quantization error is
+ * biased towards L2 distance.
+ */
+struct ProductQuantizer : Quantizer {
+ size_t M; ///< number of subquantizers
+ size_t nbits; ///< number of bits per quantization index
+
+ // values derived from the above
+ size_t dsub; ///< dimensionality of each subvector
+ size_t ksub; ///< number of centroids for each subquantizer
+ bool verbose; ///< verbose during training?
+
+ /// initialization
+ enum train_type_t {
+ Train_default,
+ Train_hot_start, ///< the centroids are already initialized
+ Train_shared, ///< share dictionary across PQ segments
+ Train_hypercube, ///< initialize centroids with nbits-D hypercube
+ Train_hypercube_pca, ///< initialize centroids with nbits-D hypercube
+ };
+ train_type_t train_type;
+
+ ClusteringParameters cp; ///< parameters used during clustering
+
+ /// if non-NULL, use this index for assignment (should be of size
+ /// d / M)
+ Index* assign_index;
+
+ /// Centroid table, size M * ksub * dsub.
+ /// Layout: (M, ksub, dsub)
+ std::vector<float> centroids;
+
+ /// Transposed centroid table, size M * ksub * dsub.
+ /// Layout: (dsub, M, ksub)
+ std::vector<float> transposed_centroids;
+
+ /// Squared lengths of centroids, size M * ksub
+ /// Layout: (M, ksub)
+ std::vector<float> centroids_sq_lengths;
+
+ /// return the centroids associated with subvector m
+ float* get_centroids(size_t m, size_t i) {
+ return &centroids[(m * ksub + i) * dsub];
+ }
+ const float* get_centroids(size_t m, size_t i) const {
+ return &centroids[(m * ksub + i) * dsub];
+ }
+
+ // Train the product quantizer on a set of points. A clustering
+ // can be set on input to define non-default clustering parameters
+ void train(size_t n, const float* x) override;
+
+ ProductQuantizer(
+ size_t d, /* dimensionality of the input vectors */
+ size_t M, /* number of subquantizers */
+ size_t nbits); /* number of bit per subvector index */
+
+ ProductQuantizer();
+
+ /// compute derived values when d, M and nbits have been set
+ void set_derived_values();
+
+ /// Define the centroids for subquantizer m
+ void set_params(const float* centroids, int m);
+
+ /// Quantize one vector with the product quantizer
+ void compute_code(const float* x, uint8_t* code) const;
+
+ /// same as compute_code for several vectors
+ void compute_codes(const float* x, uint8_t* codes, size_t n) const override;
+
+ /// speed up code assignment using assign_index
+ /// (non-const because the index is changed)
+ void compute_codes_with_assign_index(
+ const float* x,
+ uint8_t* codes,
+ size_t n);
+
+ /// decode a vector from a given code (or n vectors if third argument)
+ void decode(const uint8_t* code, float* x) const;
+ void decode(const uint8_t* code, float* x, size_t n) const override;
+
+ /// If we happen to have the distance tables precomputed, this is
+ /// more efficient to compute the codes.
+ void compute_code_from_distance_table(const float* tab, uint8_t* code)
+ const;
+
+ /** Compute distance table for one vector.
+ *
+ * The distance table for x = [x_0 x_1 .. x_(M-1)] is a M * ksub
+ * matrix that contains
+ *
+ * dis_table (m, j) = || x_m - c_(m, j)||^2
+ * for m = 0..M-1 and j = 0 .. ksub - 1
+ *
+ * where c_(m, j) is the centroid no j of sub-quantizer m.
+ *
+ * @param x input vector size d
+ * @param dis_table output table, size M * ksub
+ */
+ void compute_distance_table(const float* x, float* dis_table) const;
+
+ void compute_inner_prod_table(const float* x, float* dis_table) const;
+
+ /** compute distance table for several vectors
+ * @param nx nb of input vectors
+ * @param x input vector size nx * d
+ * @param dis_table output table, size nx * M * ksub
+ */
+ void compute_distance_tables(size_t nx, const float* x, float* dis_tables)
+ const;
+
+ void compute_inner_prod_tables(size_t nx, const float* x, float* dis_tables)
+ const;
+
+ /** perform a search (L2 distance)
+ * @param x query vectors, size nx * d
+ * @param nx nb of queries
+ * @param codes database codes, size ncodes * code_size
+ * @param ncodes nb of nb vectors
+ * @param res heap array to store results (nh == nx)
+ * @param init_finalize_heap initialize heap (input) and sort (output)?
+ */
+ void search(
+ const float* x,
+ size_t nx,
+ const uint8_t* codes,
+ const size_t ncodes,
+ float_maxheap_array_t* res,
+ bool init_finalize_heap = true) const;
+
+ /** same as search, but with inner product similarity */
+ void search_ip(
+ const float* x,
+ size_t nx,
+ const uint8_t* codes,
+ const size_t ncodes,
+ float_minheap_array_t* res,
+ bool init_finalize_heap = true) const;
+
+ /// Symmetric Distance Table
+ std::vector<float> sdc_table;
+
+ // intitialize the SDC table from the centroids
+ void compute_sdc_table();
+
+ void search_sdc(
+ const uint8_t* qcodes,
+ size_t nq,
+ const uint8_t* bcodes,
+ const size_t ncodes,
+ float_maxheap_array_t* res,
+ bool init_finalize_heap = true) const;
+
+ /// Sync transposed centroids with regular centroids. This call
+ /// is needed if centroids were edited directly.
+ void sync_transposed_centroids();
+
+ /// Clear transposed centroids table so ones are no longer used.
+ void clear_transposed_centroids();
+};
+
+// block size used in ProductQuantizer::compute_codes
+FAISS_API extern int product_quantizer_compute_codes_bs;
+
+/*************************************************
+ * Objects to encode / decode strings of bits
+ *************************************************/
+
+struct PQEncoderGeneric {
+ uint8_t* code; ///< code for this vector
+ uint8_t offset;
+ const int nbits; ///< number of bits per subquantizer index
+
+ uint8_t reg;
+
+ PQEncoderGeneric(uint8_t* code, int nbits, uint8_t offset = 0);
+
+ void encode(uint64_t x);
+
+ ~PQEncoderGeneric();
+};
+
+struct PQEncoder8 {
+ uint8_t* code;
+ PQEncoder8(uint8_t* code, int nbits);
+ void encode(uint64_t x);
+};
+
+struct PQEncoder16 {
+ uint16_t* code;
+ PQEncoder16(uint8_t* code, int nbits);
+ void encode(uint64_t x);
+};
+
+struct PQDecoderGeneric {
+ const uint8_t* code;
+ uint8_t offset;
+ const int nbits;
+ const uint64_t mask;
+ uint8_t reg;
+ PQDecoderGeneric(const uint8_t* code, int nbits);
+ uint64_t decode();
+};
+
+struct PQDecoder8 {
+ static const int nbits = 8;
+ const uint8_t* code;
+ PQDecoder8(const uint8_t* code, int nbits);
+ uint64_t decode();
+};
+
+struct PQDecoder16 {
+ static const int nbits = 16;
+ const uint16_t* code;
+ PQDecoder16(const uint8_t* code, int nbits);
+ uint64_t decode();
+};
+
+} // namespace faiss
+
+#include <faiss/impl/ProductQuantizer-inl.h>
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/Quantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/Quantizer.h
new file mode 100644
index 0000000..f35b686
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/Quantizer.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+namespace faiss {
+
+/** General interface for quantizer objects */
+struct Quantizer {
+ size_t d; ///< size of the input vectors
+ size_t code_size; ///< bytes per indexed vector
+
+ explicit Quantizer(size_t d = 0, size_t code_size = 0)
+ : d(d), code_size(code_size) {}
+
+ /** Train the quantizer
+ *
+ * @param x training vectors, size n * d
+ */
+ virtual void train(size_t n, const float* x) = 0;
+
+ /** Quantize a set of vectors
+ *
+ * @param x input vectors, size n * d
+ * @param codes output codes, size n * code_size
+ */
+ virtual void compute_codes(const float* x, uint8_t* codes, size_t n)
+ const = 0;
+
+ /** Decode a set of vectors
+ *
+ * @param codes input codes, size n * code_size
+ * @param x output vectors, size n * d
+ */
+ virtual void decode(const uint8_t* code, float* x, size_t n) const = 0;
+
+ virtual ~Quantizer() {}
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/RaBitQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/RaBitQuantizer.cpp
new file mode 100644
index 0000000..8261a9a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/RaBitQuantizer.cpp
@@ -0,0 +1,519 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/RaBitQuantizer.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <limits>
+#include <memory>
+#include <vector>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+
+namespace faiss {
+
+struct FactorsData {
+ // ||or - c||^2 - ((metric==IP) ? ||or||^2 : 0)
+ float or_minus_c_l2sqr = 0;
+ float dp_multiplier = 0;
+};
+
+struct QueryFactorsData {
+ float c1 = 0;
+ float c2 = 0;
+ float c34 = 0;
+
+ float qr_to_c_L2sqr = 0;
+ float qr_norm_L2sqr = 0;
+};
+
+static size_t get_code_size(const size_t d) {
+ return (d + 7) / 8 + sizeof(FactorsData);
+}
+
+RaBitQuantizer::RaBitQuantizer(size_t d, MetricType metric)
+ : Quantizer(d, get_code_size(d)), metric_type{metric} {}
+
+void RaBitQuantizer::train(size_t n, const float* x) {
+ // does nothing
+}
+
+void RaBitQuantizer::compute_codes(const float* x, uint8_t* codes, size_t n)
+ const {
+ compute_codes_core(x, codes, n, centroid);
+}
+
+void RaBitQuantizer::compute_codes_core(
+ const float* x,
+ uint8_t* codes,
+ size_t n,
+ const float* centroid_in) const {
+ FAISS_ASSERT(codes != nullptr);
+ FAISS_ASSERT(x != nullptr);
+ FAISS_ASSERT(
+ (metric_type == MetricType::METRIC_L2 ||
+ metric_type == MetricType::METRIC_INNER_PRODUCT));
+
+ if (n == 0) {
+ return;
+ }
+
+ // compute some helper constants
+ const float inv_d_sqrt = (d == 0) ? 1.0f : (1.0f / std::sqrt((float)d));
+
+ // compute codes
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ // ||or - c||^2
+ float norm_L2sqr = 0;
+ // ||or||^2, which is equal to ||P(or)||^2 and ||P^(-1)(or)||^2
+ float or_L2sqr = 0;
+ // dot product
+ float dp_oO = 0;
+
+ // the code
+ uint8_t* code = codes + i * code_size;
+ FactorsData* fac = reinterpret_cast<FactorsData*>(code + (d + 7) / 8);
+
+ // cleanup it
+ if (code != nullptr) {
+ memset(code, 0, code_size);
+ }
+
+ for (size_t j = 0; j < d; j++) {
+ const float or_minus_c = x[i * d + j] -
+ ((centroid_in == nullptr) ? 0 : centroid_in[j]);
+ norm_L2sqr += or_minus_c * or_minus_c;
+ or_L2sqr += x[i * d + j] * x[i * d + j];
+
+ const bool xb = (or_minus_c > 0);
+
+ dp_oO += xb ? or_minus_c : (-or_minus_c);
+
+ // store the output data
+ if (code != nullptr) {
+ if (xb) {
+ // enable a particular bit
+ code[j / 8] |= (1 << (j % 8));
+ }
+ }
+ }
+
+ // compute factors
+
+ // compute the inverse norm
+ const float inv_norm_L2 =
+ (std::abs(norm_L2sqr) < std::numeric_limits<float>::epsilon())
+ ? 1.0f
+ : (1.0f / std::sqrt(norm_L2sqr));
+ dp_oO *= inv_norm_L2;
+ dp_oO *= inv_d_sqrt;
+
+ const float inv_dp_oO =
+ (std::abs(dp_oO) < std::numeric_limits<float>::epsilon())
+ ? 1.0f
+ : (1.0f / dp_oO);
+
+ fac->or_minus_c_l2sqr = norm_L2sqr;
+ if (metric_type == MetricType::METRIC_INNER_PRODUCT) {
+ fac->or_minus_c_l2sqr -= or_L2sqr;
+ }
+
+ fac->dp_multiplier = inv_dp_oO * std::sqrt(norm_L2sqr);
+ }
+}
+
+void RaBitQuantizer::decode(const uint8_t* codes, float* x, size_t n) const {
+ decode_core(codes, x, n, centroid);
+}
+
+void RaBitQuantizer::decode_core(
+ const uint8_t* codes,
+ float* x,
+ size_t n,
+ const float* centroid_in) const {
+ FAISS_ASSERT(codes != nullptr);
+ FAISS_ASSERT(x != nullptr);
+
+ const float inv_d_sqrt = (d == 0) ? 1.0f : (1.0f / std::sqrt((float)d));
+
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const uint8_t* code = codes + i * code_size;
+
+ // split the code into parts
+ const uint8_t* binary_data = code;
+ const FactorsData* fac =
+ reinterpret_cast<const FactorsData*>(code + (d + 7) / 8);
+
+ //
+ for (size_t j = 0; j < d; j++) {
+ // extract i-th bit
+ const uint8_t masker = (1 << (j % 8));
+ const float bit = ((binary_data[j / 8] & masker) == masker) ? 1 : 0;
+
+ // compute the output code
+ x[i * d + j] = (bit - 0.5f) * fac->dp_multiplier * 2 * inv_d_sqrt +
+ ((centroid_in == nullptr) ? 0 : centroid_in[j]);
+ }
+ }
+}
+
+struct RaBitDistanceComputer : FlatCodesDistanceComputer {
+ // dimensionality
+ size_t d = 0;
+ // a centroid to use
+ const float* centroid = nullptr;
+
+ // the metric
+ MetricType metric_type = MetricType::METRIC_L2;
+
+ RaBitDistanceComputer();
+
+ float symmetric_dis(idx_t i, idx_t j) override;
+};
+
+RaBitDistanceComputer::RaBitDistanceComputer() = default;
+
+float RaBitDistanceComputer::symmetric_dis(idx_t i, idx_t j) {
+ FAISS_THROW_MSG("Not implemented");
+}
+
+struct RaBitDistanceComputerNotQ : RaBitDistanceComputer {
+ // the rotated query (qr - c)
+ std::vector<float> rotated_q;
+ // some additional numbers for the query
+ QueryFactorsData query_fac;
+
+ RaBitDistanceComputerNotQ();
+
+ float distance_to_code(const uint8_t* code) override;
+
+ void set_query(const float* x) override;
+};
+
+RaBitDistanceComputerNotQ::RaBitDistanceComputerNotQ() = default;
+
+float RaBitDistanceComputerNotQ::distance_to_code(const uint8_t* code) {
+ FAISS_ASSERT(code != nullptr);
+ FAISS_ASSERT(
+ (metric_type == MetricType::METRIC_L2 ||
+ metric_type == MetricType::METRIC_INNER_PRODUCT));
+
+ // split the code into parts
+ const uint8_t* binary_data = code;
+ const FactorsData* fac =
+ reinterpret_cast<const FactorsData*>(code + (d + 7) / 8);
+
+ // this is the baseline code
+ //
+ // compute <q,o> using floats
+ float dot_qo = 0;
+ // It was a willful decision (after the discussion) to not to pre-cache
+ // the sum of all bits, just in order to reduce the overhead per vector.
+ uint64_t sum_q = 0;
+ for (size_t i = 0; i < d; i++) {
+ // extract i-th bit
+ const uint8_t masker = (1 << (i % 8));
+ const bool b_bit = ((binary_data[i / 8] & masker) == masker);
+
+ // accumulate dp
+ dot_qo += (b_bit) ? rotated_q[i] : 0;
+ // accumulate sum-of-bits
+ sum_q += (b_bit) ? 1 : 0;
+ }
+
+ float final_dot = 0;
+ // dot-product itself
+ final_dot += query_fac.c1 * dot_qo;
+ // normalizer coefficients
+ final_dot += query_fac.c2 * sum_q;
+ // normalizer coefficients
+ final_dot -= query_fac.c34;
+
+ // this is ||or - c||^2 - (IP ? ||or||^2 : 0)
+ const float or_c_l2sqr = fac->or_minus_c_l2sqr;
+
+ // pre_dist = ||or - c||^2 + ||qr - c||^2 -
+ // 2 * ||or - c|| * ||qr - c|| * <q,o> - (IP ? ||or||^2 : 0)
+ const float pre_dist = or_c_l2sqr + query_fac.qr_to_c_L2sqr -
+ 2 * fac->dp_multiplier * final_dot;
+
+ if (metric_type == MetricType::METRIC_L2) {
+ // ||or - q||^ 2
+ return pre_dist;
+ } else {
+ // metric == MetricType::METRIC_INNER_PRODUCT
+
+ // this is ||q||^2
+ const float query_norm_sqr = query_fac.qr_norm_L2sqr;
+
+ // 2 * (or, q) = (||or - q||^2 - ||q||^2 - ||or||^2)
+ return -0.5f * (pre_dist - query_norm_sqr);
+ }
+}
+
+void RaBitDistanceComputerNotQ::set_query(const float* x) {
+ FAISS_ASSERT(x != nullptr);
+ FAISS_ASSERT(
+ (metric_type == MetricType::METRIC_L2 ||
+ metric_type == MetricType::METRIC_INNER_PRODUCT));
+
+ // compute the distance from the query to the centroid
+ if (centroid != nullptr) {
+ query_fac.qr_to_c_L2sqr = fvec_L2sqr(x, centroid, d);
+ } else {
+ query_fac.qr_to_c_L2sqr = fvec_norm_L2sqr(x, d);
+ }
+
+ // subtract c, obtain P^(-1)(qr - c)
+ rotated_q.resize(d);
+ for (size_t i = 0; i < d; i++) {
+ rotated_q[i] = x[i] - ((centroid == nullptr) ? 0 : centroid[i]);
+ }
+
+ // compute some numbers
+ const float inv_d = (d == 0) ? 1.0f : (1.0f / std::sqrt((float)d));
+
+ // do not quantize the query
+ float sum_q = 0;
+ for (size_t i = 0; i < d; i++) {
+ sum_q += rotated_q[i];
+ }
+
+ query_fac.c1 = 2 * inv_d;
+ query_fac.c2 = 0;
+ query_fac.c34 = sum_q * inv_d;
+
+ if (metric_type == MetricType::METRIC_INNER_PRODUCT) {
+ // precompute if needed
+ query_fac.qr_norm_L2sqr = fvec_norm_L2sqr(x, d);
+ }
+}
+
+//
+struct RaBitDistanceComputerQ : RaBitDistanceComputer {
+ // the rotated and quantized query (qr - c)
+ std::vector<uint8_t> rotated_qq;
+ // we're using the proposed relayout-ed scheme from 3.3 that allows
+ // using popcounts for computing the distance.
+ std::vector<uint8_t> rearranged_rotated_qq;
+ // some additional numbers for the query
+ QueryFactorsData query_fac;
+
+ // the number of bits for SQ quantization of the query (qb > 0)
+ uint8_t qb = 8;
+ // the smallest value divisible by 8 that is not smaller than dim
+ size_t popcount_aligned_dim = 0;
+
+ RaBitDistanceComputerQ();
+
+ float distance_to_code(const uint8_t* code) override;
+
+ void set_query(const float* x) override;
+};
+
+RaBitDistanceComputerQ::RaBitDistanceComputerQ() = default;
+
+float RaBitDistanceComputerQ::distance_to_code(const uint8_t* code) {
+ FAISS_ASSERT(code != nullptr);
+ FAISS_ASSERT(
+ (metric_type == MetricType::METRIC_L2 ||
+ metric_type == MetricType::METRIC_INNER_PRODUCT));
+
+ // split the code into parts
+ const uint8_t* binary_data = code;
+ const FactorsData* fac =
+ reinterpret_cast<const FactorsData*>(code + (d + 7) / 8);
+
+ // // this is the baseline code
+ // //
+ // // compute <q,o> using integers
+ // size_t dot_qo = 0;
+ // for (size_t i = 0; i < d; i++) {
+ // // extract i-th bit
+ // const uint8_t masker = (1 << (i % 8));
+ // const uint8_t bit = ((binary_data[i / 8] & masker) == masker) ? 1 :
+ // 0;
+ //
+ // // accumulate dp
+ // dot_qo += bit * rotated_qq[i];
+ // }
+
+ // this is the scheme for popcount
+ const size_t di_8b = (d + 7) / 8;
+ const size_t di_64b = (di_8b / 8) * 8;
+
+ uint64_t dot_qo = 0;
+ for (size_t j = 0; j < qb; j++) {
+ const uint8_t* query_j = rearranged_rotated_qq.data() + j * di_8b;
+
+ // process 64-bit popcounts
+ uint64_t count_dot = 0;
+ for (size_t i = 0; i < di_64b; i += 8) {
+ const auto qv = *(const uint64_t*)(query_j + i);
+ const auto yv = *(const uint64_t*)(binary_data + i);
+ count_dot += __builtin_popcountll(qv & yv);
+ }
+
+ // process leftovers
+ for (size_t i = di_64b; i < di_8b; i++) {
+ const auto qv = *(query_j + i);
+ const auto yv = *(binary_data + i);
+ count_dot += __builtin_popcount(qv & yv);
+ }
+
+ dot_qo += (count_dot << j);
+ }
+
+ // It was a willful decision (after the discussion) to not to pre-cache
+ // the sum of all bits, just in order to reduce the overhead per vector.
+ uint64_t sum_q = 0;
+ {
+ // process 64-bit popcounts
+ for (size_t i = 0; i < di_64b; i += 8) {
+ const auto yv = *(const uint64_t*)(binary_data + i);
+ sum_q += __builtin_popcountll(yv);
+ }
+
+ // process leftovers
+ for (size_t i = di_64b; i < di_8b; i++) {
+ const auto yv = *(binary_data + i);
+ sum_q += __builtin_popcount(yv);
+ }
+ }
+
+ float final_dot = 0;
+ // dot-product itself
+ final_dot += query_fac.c1 * dot_qo;
+ // normalizer coefficients
+ final_dot += query_fac.c2 * sum_q;
+ // normalizer coefficients
+ final_dot -= query_fac.c34;
+
+ // this is ||or - c||^2 - (IP ? ||or||^2 : 0)
+ const float or_c_l2sqr = fac->or_minus_c_l2sqr;
+
+ // pre_dist = ||or - c||^2 + ||qr - c||^2 -
+ // 2 * ||or - c|| * ||qr - c|| * <q,o> - (IP ? ||or||^2 : 0)
+ const float pre_dist = or_c_l2sqr + query_fac.qr_to_c_L2sqr -
+ 2 * fac->dp_multiplier * final_dot;
+
+ if (metric_type == MetricType::METRIC_L2) {
+ // ||or - q||^ 2
+ return pre_dist;
+ } else {
+ // metric == MetricType::METRIC_INNER_PRODUCT
+
+ // this is ||q||^2
+ const float query_norm_sqr = query_fac.qr_norm_L2sqr;
+
+ // 2 * (or, q) = (||or - q||^2 - ||q||^2 - ||or||^2)
+ return -0.5f * (pre_dist - query_norm_sqr);
+ }
+}
+
+void RaBitDistanceComputerQ::set_query(const float* x) {
+ FAISS_ASSERT(x != nullptr);
+ FAISS_ASSERT(
+ (metric_type == MetricType::METRIC_L2 ||
+ metric_type == MetricType::METRIC_INNER_PRODUCT));
+
+ // compute the distance from the query to the centroid
+ if (centroid != nullptr) {
+ query_fac.qr_to_c_L2sqr = fvec_L2sqr(x, centroid, d);
+ } else {
+ query_fac.qr_to_c_L2sqr = fvec_norm_L2sqr(x, d);
+ }
+
+ // allocate space
+ rotated_qq.resize(d);
+
+ // rotate the query
+ std::vector<float> rotated_q(d);
+ for (size_t i = 0; i < d; i++) {
+ rotated_q[i] = x[i] - ((centroid == nullptr) ? 0 : centroid[i]);
+ }
+
+ // compute some numbers
+ const float inv_d = (d == 0) ? 1.0f : (1.0f / std::sqrt((float)d));
+
+ // quantize the query. compute min and max
+ float v_min = std::numeric_limits<float>::max();
+ float v_max = std::numeric_limits<float>::lowest();
+ for (size_t i = 0; i < d; i++) {
+ const float v_q = rotated_q[i];
+ v_min = std::min(v_min, v_q);
+ v_max = std::max(v_max, v_q);
+ }
+
+ const float pow_2_qb = 1 << qb;
+
+ const float delta = (v_max - v_min) / (pow_2_qb - 1);
+ const float inv_delta = 1.0f / delta;
+
+ size_t sum_qq = 0;
+ for (int32_t i = 0; i < d; i++) {
+ const float v_q = rotated_q[i];
+
+ // a default non-randomized SQ
+ const int v_qq = std::round((v_q - v_min) * inv_delta);
+
+ rotated_qq[i] = std::min(255, std::max(0, v_qq));
+ sum_qq += v_qq;
+ }
+
+ // rearrange the query vector
+ popcount_aligned_dim = ((d + 7) / 8) * 8;
+ size_t offset = (d + 7) / 8;
+
+ rearranged_rotated_qq.resize(offset * qb);
+ std::fill(rearranged_rotated_qq.begin(), rearranged_rotated_qq.end(), 0);
+
+ for (size_t idim = 0; idim < d; idim++) {
+ for (size_t iv = 0; iv < qb; iv++) {
+ const bool bit = ((rotated_qq[idim] & (1 << iv)) != 0);
+ rearranged_rotated_qq[iv * offset + idim / 8] |=
+ bit ? (1 << (idim % 8)) : 0;
+ }
+ }
+
+ query_fac.c1 = 2 * delta * inv_d;
+ query_fac.c2 = 2 * v_min * inv_d;
+ query_fac.c34 = inv_d * (delta * sum_qq + d * v_min);
+
+ if (metric_type == MetricType::METRIC_INNER_PRODUCT) {
+ // precompute if needed
+ query_fac.qr_norm_L2sqr = fvec_norm_L2sqr(x, d);
+ }
+}
+
+FlatCodesDistanceComputer* RaBitQuantizer::get_distance_computer(
+ uint8_t qb,
+ const float* centroid_in) const {
+ if (qb == 0) {
+ auto dc = std::make_unique<RaBitDistanceComputerNotQ>();
+ dc->metric_type = metric_type;
+ dc->d = d;
+ dc->centroid = centroid_in;
+
+ return dc.release();
+ } else {
+ auto dc = std::make_unique<RaBitDistanceComputerQ>();
+ dc->metric_type = metric_type;
+ dc->d = d;
+ dc->centroid = centroid_in;
+ dc->qb = qb;
+
+ return dc.release();
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/RaBitQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/RaBitQuantizer.h
new file mode 100644
index 0000000..0111583
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/RaBitQuantizer.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/MetricType.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/Quantizer.h>
+
+namespace faiss {
+
+// the reference implementation of the https://arxiv.org/pdf/2405.12497
+// Jianyang Gao, Cheng Long, "RaBitQ: Quantizing High-Dimensional Vectors
+// with a Theoretical Error Bound for Approximate Nearest Neighbor Search".
+//
+// It is assumed that the Random Matrix Rotation is performed externally.
+struct RaBitQuantizer : Quantizer {
+ // all RaBitQ operations are provided against a centroid, which needs
+ // to be provided Externally (!). Nullptr value implies that the centroid
+ // consists of zero values.
+ // This is the default value that can be customized using XYZ_core() calls.
+ // Such a customization is needed for IVF calls.
+ //
+ // This particular pointer will NOT be serialized.
+ float* centroid = nullptr;
+
+ // RaBitQ codes computations are independent from a metric. But it is needed
+ // to store some additional fp32 constants together with a quantized code.
+ // A decision was made to make this quantizer as space efficient as
+ // possible. Thus, a quantizer has to introduce a metric.
+ MetricType metric_type = MetricType::METRIC_L2;
+
+ RaBitQuantizer(size_t d = 0, MetricType metric = MetricType::METRIC_L2);
+
+ void train(size_t n, const float* x) override;
+
+ // every vector is expected to take (d + 7) / 8 + sizeof(FactorsData) bytes,
+ void compute_codes(const float* x, uint8_t* codes, size_t n) const override;
+
+ void compute_codes_core(
+ const float* x,
+ uint8_t* codes,
+ size_t n,
+ const float* centroid_in) const;
+
+ // The decode output is Heavily geared towards maintaining the IP, not L2.
+ // This means that the reconstructed codes maybe less accurate than one may
+ // expect, if one computes an L2 distance between a reconstructed code and
+ // the corresponding original vector.
+ // But value of the dot product between a query and the original vector
+ // might be very close to the value of the dot product between a query and
+ // the reconstructed code.
+ // Basically, it seems to be related to the distributions of values, not
+ // values.
+ void decode(const uint8_t* codes, float* x, size_t n) const override;
+
+ void decode_core(
+ const uint8_t* codes,
+ float* x,
+ size_t n,
+ const float* centroid_in) const;
+
+ // returns the distance computer.
+ // specify qb = 0 to get an DC that does not quantize a query
+ // specify qb > 0 to have SQ qb-bits query
+ FlatCodesDistanceComputer* get_distance_computer(
+ uint8_t qb,
+ const float* centroid_in = nullptr) const;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResidualQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResidualQuantizer.cpp
new file mode 100644
index 0000000..96eb2c3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResidualQuantizer.cpp
@@ -0,0 +1,514 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/ResidualQuantizer.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+#include <memory>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/VectorTransform.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/residual_quantizer_encode_steps.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/utils.h>
+
+extern "C" {
+
+// general matrix multiplication
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+
+// http://www.netlib.org/clapack/old/single/sgels.c
+// solve least squares
+
+int sgelsd_(
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* nrhs,
+ float* a,
+ FINTEGER* lda,
+ float* b,
+ FINTEGER* ldb,
+ float* s,
+ float* rcond,
+ FINTEGER* rank,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* iwork,
+ FINTEGER* info);
+}
+
+namespace faiss {
+
+ResidualQuantizer::ResidualQuantizer() {
+ d = 0;
+ M = 0;
+ verbose = false;
+}
+
+ResidualQuantizer::ResidualQuantizer(
+ size_t d,
+ const std::vector<size_t>& nbits,
+ Search_type_t search_type)
+ : ResidualQuantizer() {
+ this->search_type = search_type;
+ this->d = d;
+ M = nbits.size();
+ this->nbits = nbits;
+ set_derived_values();
+}
+
+ResidualQuantizer::ResidualQuantizer(
+ size_t d,
+ size_t M,
+ size_t nbits,
+ Search_type_t search_type)
+ : ResidualQuantizer(d, std::vector<size_t>(M, nbits), search_type) {}
+
+void ResidualQuantizer::initialize_from(
+ const ResidualQuantizer& other,
+ int skip_M) {
+ FAISS_THROW_IF_NOT(M + skip_M <= other.M);
+ FAISS_THROW_IF_NOT(skip_M >= 0);
+
+ Search_type_t this_search_type = search_type;
+ int this_M = M;
+
+ // a first good approximation: override everything
+ *this = other;
+
+ // adjust derived values
+ M = this_M;
+ search_type = this_search_type;
+ nbits.resize(M);
+ memcpy(nbits.data(),
+ other.nbits.data() + skip_M,
+ nbits.size() * sizeof(nbits[0]));
+
+ set_derived_values();
+
+ // resize codebooks if trained
+ if (codebooks.size() > 0) {
+ FAISS_THROW_IF_NOT(codebooks.size() == other.total_codebook_size * d);
+ codebooks.resize(total_codebook_size * d);
+ memcpy(codebooks.data(),
+ other.codebooks.data() + other.codebook_offsets[skip_M] * d,
+ codebooks.size() * sizeof(codebooks[0]));
+ // TODO: norm_tabs?
+ }
+}
+
+/****************************************************************
+ * Training
+ ****************************************************************/
+
+void ResidualQuantizer::train(size_t n, const float* x) {
+ codebooks.resize(d * codebook_offsets.back());
+
+ if (verbose) {
+ printf("Training ResidualQuantizer, with %zd steps on %zd %zdD vectors\n",
+ M,
+ n,
+ size_t(d));
+ }
+
+ int cur_beam_size = 1;
+ std::vector<float> residuals(x, x + n * d);
+ std::vector<int32_t> codes;
+ std::vector<float> distances;
+ double t0 = getmillisecs();
+ double clustering_time = 0;
+
+ for (int m = 0; m < M; m++) {
+ int K = 1 << nbits[m];
+
+ // on which residuals to train
+ std::vector<float>& train_residuals = residuals;
+ std::vector<float> residuals1;
+ if (train_type & Train_top_beam) {
+ residuals1.resize(n * d);
+ for (size_t j = 0; j < n; j++) {
+ memcpy(residuals1.data() + j * d,
+ residuals.data() + j * d * cur_beam_size,
+ sizeof(residuals[0]) * d);
+ }
+ train_residuals = residuals1;
+ }
+ std::vector<float> codebooks;
+ float obj = 0;
+
+ std::unique_ptr<Index> assign_index;
+ if (assign_index_factory) {
+ assign_index.reset((*assign_index_factory)(d));
+ } else {
+ assign_index.reset(new IndexFlatL2(d));
+ }
+
+ double t1 = getmillisecs();
+
+ if (!(train_type & Train_progressive_dim)) { // regular kmeans
+ Clustering clus(d, K, cp);
+ clus.train(
+ train_residuals.size() / d,
+ train_residuals.data(),
+ *assign_index.get());
+ codebooks.swap(clus.centroids);
+ assign_index->reset();
+ obj = clus.iteration_stats.back().obj;
+ } else { // progressive dim clustering
+ ProgressiveDimClustering clus(d, K, cp);
+ ProgressiveDimIndexFactory default_fac;
+ clus.train(
+ train_residuals.size() / d,
+ train_residuals.data(),
+ assign_index_factory ? *assign_index_factory : default_fac);
+ codebooks.swap(clus.centroids);
+ obj = clus.iteration_stats.back().obj;
+ }
+ clustering_time += (getmillisecs() - t1) / 1000;
+
+ memcpy(this->codebooks.data() + codebook_offsets[m] * d,
+ codebooks.data(),
+ codebooks.size() * sizeof(codebooks[0]));
+
+ // quantize using the new codebooks
+
+ int new_beam_size = std::min(cur_beam_size * K, max_beam_size);
+ std::vector<int32_t> new_codes(n * new_beam_size * (m + 1));
+ std::vector<float> new_residuals(n * new_beam_size * d);
+ std::vector<float> new_distances(n * new_beam_size);
+
+ size_t bs;
+ { // determine batch size
+ size_t mem = memory_per_point();
+ if (n > 1 && mem * n > max_mem_distances) {
+ // then split queries to reduce temp memory
+ bs = std::max(max_mem_distances / mem, size_t(1));
+ } else {
+ bs = n;
+ }
+ }
+
+ for (size_t i0 = 0; i0 < n; i0 += bs) {
+ size_t i1 = std::min(i0 + bs, n);
+
+ /* printf("i0: %ld i1: %ld K %d ntotal assign index %ld\n",
+ i0, i1, K, assign_index->ntotal); */
+
+ beam_search_encode_step(
+ d,
+ K,
+ codebooks.data(),
+ i1 - i0,
+ cur_beam_size,
+ residuals.data() + i0 * cur_beam_size * d,
+ m,
+ codes.data() + i0 * cur_beam_size * m,
+ new_beam_size,
+ new_codes.data() + i0 * new_beam_size * (m + 1),
+ new_residuals.data() + i0 * new_beam_size * d,
+ new_distances.data() + i0 * new_beam_size,
+ assign_index.get(),
+ approx_topk_mode);
+ }
+ codes.swap(new_codes);
+ residuals.swap(new_residuals);
+ distances.swap(new_distances);
+
+ float sum_distances = 0;
+ for (int j = 0; j < distances.size(); j++) {
+ sum_distances += distances[j];
+ }
+
+ if (verbose) {
+ printf("[%.3f s, %.3f s clustering] train stage %d, %d bits, kmeans objective %g, "
+ "total distance %g, beam_size %d->%d (batch size %zd)\n",
+ (getmillisecs() - t0) / 1000,
+ clustering_time,
+ m,
+ int(nbits[m]),
+ obj,
+ sum_distances,
+ cur_beam_size,
+ new_beam_size,
+ bs);
+ }
+ cur_beam_size = new_beam_size;
+ }
+
+ is_trained = true;
+
+ if (train_type & Train_refine_codebook) {
+ for (int iter = 0; iter < niter_codebook_refine; iter++) {
+ if (verbose) {
+ printf("re-estimating the codebooks to minimize "
+ "quantization errors (iter %d).\n",
+ iter);
+ }
+ retrain_AQ_codebook(n, x);
+ }
+ }
+
+ // find min and max norms
+ std::vector<float> norms(n);
+
+ for (size_t i = 0; i < n; i++) {
+ norms[i] = fvec_L2sqr(
+ x + i * d, residuals.data() + i * cur_beam_size * d, d);
+ }
+
+ // fvec_norms_L2sqr(norms.data(), x, d, n);
+ train_norm(n, norms.data());
+
+ if (!(train_type & Skip_codebook_tables)) {
+ compute_codebook_tables();
+ }
+}
+
+float ResidualQuantizer::retrain_AQ_codebook(size_t n, const float* x) {
+ FAISS_THROW_IF_NOT_MSG(n >= total_codebook_size, "too few training points");
+
+ if (verbose) {
+ printf(" encoding %zd training vectors\n", n);
+ }
+ std::vector<uint8_t> codes(n * code_size);
+ compute_codes(x, codes.data(), n);
+
+ // compute reconstruction error
+ float input_recons_error;
+ {
+ std::vector<float> x_recons(n * d);
+ decode(codes.data(), x_recons.data(), n);
+ input_recons_error = fvec_L2sqr(x, x_recons.data(), n * d);
+ if (verbose) {
+ printf(" input quantization error %g\n", input_recons_error);
+ }
+ }
+
+ // build matrix of the linear system
+ std::vector<float> C(n * total_codebook_size);
+ for (size_t i = 0; i < n; i++) {
+ BitstringReader bsr(codes.data() + i * code_size, code_size);
+ for (int m = 0; m < M; m++) {
+ int idx = bsr.read(nbits[m]);
+ C[i + (codebook_offsets[m] + idx) * n] = 1;
+ }
+ }
+
+ // transpose training vectors
+ std::vector<float> xt(n * d);
+
+ for (size_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < d; j++) {
+ xt[j * n + i] = x[i * d + j];
+ }
+ }
+
+ { // solve least squares
+ FINTEGER lwork = -1;
+ FINTEGER di = d, ni = n, tcsi = total_codebook_size;
+ FINTEGER info = -1, rank = -1;
+
+ float rcond = 1e-4; // this is an important parameter because the code
+ // matrix can be rank deficient for small problems,
+ // the default rcond=-1 does not work
+ float worksize;
+ std::vector<float> sing_vals(total_codebook_size);
+ FINTEGER nlvl = 1000; // formula is a bit convoluted so let's take an
+ // upper bound
+ std::vector<FINTEGER> iwork(
+ 3 * total_codebook_size * nlvl + 11 * total_codebook_size);
+
+ // worksize query
+ sgelsd_(&ni,
+ &tcsi,
+ &di,
+ C.data(),
+ &ni,
+ xt.data(),
+ &ni,
+ sing_vals.data(),
+ &rcond,
+ &rank,
+ &worksize,
+ &lwork,
+ iwork.data(),
+ &info);
+ FAISS_THROW_IF_NOT(info == 0);
+
+ lwork = worksize;
+ std::vector<float> work(lwork);
+ // actual call
+ sgelsd_(&ni,
+ &tcsi,
+ &di,
+ C.data(),
+ &ni,
+ xt.data(),
+ &ni,
+ sing_vals.data(),
+ &rcond,
+ &rank,
+ work.data(),
+ &lwork,
+ iwork.data(),
+ &info);
+ FAISS_THROW_IF_NOT_FMT(info == 0, "SGELS returned info=%d", int(info));
+ if (verbose) {
+ printf(" sgelsd rank=%d/%d\n",
+ int(rank),
+ int(total_codebook_size));
+ }
+ }
+
+ // result is in xt, re-transpose to codebook
+
+ for (size_t i = 0; i < total_codebook_size; i++) {
+ for (size_t j = 0; j < d; j++) {
+ codebooks[i * d + j] = xt[j * n + i];
+ FAISS_THROW_IF_NOT(std::isfinite(codebooks[i * d + j]));
+ }
+ }
+
+ float output_recons_error = 0;
+ for (size_t j = 0; j < d; j++) {
+ output_recons_error += fvec_norm_L2sqr(
+ xt.data() + total_codebook_size + n * j,
+ n - total_codebook_size);
+ }
+ if (verbose) {
+ printf(" output quantization error %g\n", output_recons_error);
+ }
+ return output_recons_error;
+}
+
+size_t ResidualQuantizer::memory_per_point(int beam_size) const {
+ if (beam_size < 0) {
+ beam_size = max_beam_size;
+ }
+ size_t mem;
+ mem = beam_size * d * 2 * sizeof(float); // size for 2 beams at a time
+ mem += beam_size * beam_size *
+ (sizeof(float) + sizeof(idx_t)); // size for 1 beam search result
+ return mem;
+}
+
+/****************************************************************
+ * Encoding
+ ****************************************************************/
+
+using namespace rq_encode_steps;
+
+void ResidualQuantizer::compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids) const {
+ FAISS_THROW_IF_NOT_MSG(is_trained, "RQ is not trained yet.");
+
+ //
+ size_t mem = memory_per_point();
+
+ size_t bs = max_mem_distances / mem;
+ if (bs == 0) {
+ bs = 1; // otherwise we can't do much
+ }
+
+ // prepare memory pools
+ ComputeCodesAddCentroidsLUT0MemoryPool pool0;
+ ComputeCodesAddCentroidsLUT1MemoryPool pool1;
+
+ for (size_t i0 = 0; i0 < n; i0 += bs) {
+ size_t i1 = std::min(n, i0 + bs);
+ const float* cent = nullptr;
+ if (centroids != nullptr) {
+ cent = centroids + i0 * d;
+ }
+
+ if (use_beam_LUT == 0) {
+ compute_codes_add_centroids_mp_lut0(
+ *this,
+ x + i0 * d,
+ codes_out + i0 * code_size,
+ i1 - i0,
+ cent,
+ pool0);
+ } else if (use_beam_LUT == 1) {
+ compute_codes_add_centroids_mp_lut1(
+ *this,
+ x + i0 * d,
+ codes_out + i0 * code_size,
+ i1 - i0,
+ cent,
+ pool1);
+ }
+ }
+}
+
+void ResidualQuantizer::refine_beam(
+ size_t n,
+ size_t beam_size,
+ const float* x,
+ int out_beam_size,
+ int32_t* out_codes,
+ float* out_residuals,
+ float* out_distances) const {
+ RefineBeamMemoryPool pool;
+ refine_beam_mp(
+ *this,
+ n,
+ beam_size,
+ x,
+ out_beam_size,
+ out_codes,
+ out_residuals,
+ out_distances,
+ pool);
+}
+
+/*******************************************************************
+ * Functions using the dot products between codebook entries
+ *******************************************************************/
+
+void ResidualQuantizer::refine_beam_LUT(
+ size_t n,
+ const float* query_norms, // size n
+ const float* query_cp, //
+ int out_beam_size,
+ int32_t* out_codes,
+ float* out_distances) const {
+ RefineBeamLUTMemoryPool pool;
+ refine_beam_LUT_mp(
+ *this,
+ n,
+ query_norms,
+ query_cp,
+ out_beam_size,
+ out_codes,
+ out_distances,
+ pool);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResidualQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResidualQuantizer.h
new file mode 100644
index 0000000..572232f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResidualQuantizer.h
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <vector>
+
+#include <faiss/Clustering.h>
+#include <faiss/impl/AdditiveQuantizer.h>
+
+#include <faiss/utils/approx_topk/mode.h>
+
+namespace faiss {
+
+/** Residual quantizer with variable number of bits per sub-quantizer
+ *
+ * The residual centroids are stored in a big cumulative centroid table.
+ * The codes are represented either as a non-compact table of size (n, M) or
+ * as the compact output (n, code_size).
+ */
+
+struct ResidualQuantizer : AdditiveQuantizer {
+ /// initialization
+
+ // Was enum but that does not work so well with bitmasks
+ using train_type_t = int;
+
+ /// Binary or of the Train_* flags below
+ train_type_t train_type = Train_progressive_dim;
+
+ /// regular k-means (minimal amount of computation)
+ static const int Train_default = 0;
+
+ /// progressive dim clustering (set by default)
+ static const int Train_progressive_dim = 1;
+
+ /// do a few iterations of codebook refinement after first level estimation
+ static const int Train_refine_codebook = 2;
+
+ /// number of iterations for codebook refinement.
+ int niter_codebook_refine = 5;
+
+ /** set this bit on train_type if beam is to be trained only on the
+ * first element of the beam (faster but less accurate) */
+ static const int Train_top_beam = 1024;
+
+ /** set this bit to *not* autmatically compute the codebook tables
+ * after training */
+ static const int Skip_codebook_tables = 2048;
+
+ /// beam size used for training and for encoding
+ int max_beam_size = 5;
+
+ /// use LUT for beam search
+ int use_beam_LUT = 0;
+
+ /// Currently used mode of approximate min-k computations.
+ /// Default value is EXACT_TOPK.
+ ApproxTopK_mode_t approx_topk_mode = ApproxTopK_mode_t::EXACT_TOPK;
+
+ /// clustering parameters
+ ProgressiveDimClusteringParameters cp;
+
+ /// if non-NULL, use this index for assignment
+ ProgressiveDimIndexFactory* assign_index_factory = nullptr;
+
+ ResidualQuantizer(
+ size_t d,
+ const std::vector<size_t>& nbits,
+ Search_type_t search_type = ST_decompress);
+
+ ResidualQuantizer(
+ size_t d, /* dimensionality of the input vectors */
+ size_t M, /* number of subquantizers */
+ size_t nbits, /* number of bit per subvector index */
+ Search_type_t search_type = ST_decompress);
+
+ ResidualQuantizer();
+
+ /// Train the residual quantizer
+ void train(size_t n, const float* x) override;
+
+ /// Copy the M codebook levels from other, starting from skip_M
+ void initialize_from(const ResidualQuantizer& other, int skip_M = 0);
+
+ /** Encode the vectors and compute codebook that minimizes the quantization
+ * error on these codes
+ *
+ * @param x training vectors, size n * d
+ * @param n nb of training vectors, n >= total_codebook_size
+ * @return returns quantization error for the new codebook with old
+ * codes
+ */
+ float retrain_AQ_codebook(size_t n, const float* x);
+
+ /** Encode a set of vectors
+ *
+ * @param x vectors to encode, size n * d
+ * @param codes output codes, size n * code_size
+ * @param centroids centroids to be added to x, size n * d
+ */
+ void compute_codes_add_centroids(
+ const float* x,
+ uint8_t* codes,
+ size_t n,
+ const float* centroids = nullptr) const override;
+
+ /** lower-level encode function
+ *
+ * @param n number of vectors to handle
+ * @param residuals vectors to encode, size (n, beam_size, d)
+ * @param beam_size input beam size
+ * @param new_beam_size output beam size (should be <= K * beam_size)
+ * @param new_codes output codes, size (n, new_beam_size, m + 1)
+ * @param new_residuals output residuals, size (n, new_beam_size, d)
+ * @param new_distances output distances, size (n, new_beam_size)
+ */
+ void refine_beam(
+ size_t n,
+ size_t beam_size,
+ const float* residuals,
+ int new_beam_size,
+ int32_t* new_codes,
+ float* new_residuals = nullptr,
+ float* new_distances = nullptr) const;
+
+ void refine_beam_LUT(
+ size_t n,
+ const float* query_norms,
+ const float* query_cp,
+ int new_beam_size,
+ int32_t* new_codes,
+ float* new_distances = nullptr) const;
+
+ /** Beam search can consume a lot of memory. This function estimates the
+ * amount of mem used by refine_beam to adjust the batch size
+ *
+ * @param beam_size if != -1, override the beam size
+ */
+ size_t memory_per_point(int beam_size = -1) const;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResultHandler.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResultHandler.h
new file mode 100644
index 0000000..ce15c63
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ResultHandler.h
@@ -0,0 +1,687 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/*
+ * Structures that collect search results from distance computations
+ */
+
+#pragma once
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissException.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/partitioning.h>
+
+#include <algorithm>
+#include <iostream>
+
+namespace faiss {
+
+/*****************************************************************
+ * The classes below are intended to be used as template arguments
+ * they handle results for batches of queries (size nq).
+ * They can be called in two ways:
+ * - by instanciating a SingleResultHandler that tracks results for a single
+ * query
+ * - with begin_multiple/add_results/end_multiple calls where a whole block of
+ * results is submitted
+ * All classes are templated on C which to define wheter the min or the max of
+ * results is to be kept, and on sel, so that the codepaths for with / without
+ * selector can be separated at compile time.
+ *****************************************************************/
+
+template <class C, bool use_sel = false>
+struct BlockResultHandler {
+ size_t nq; // number of queries for which we search
+ const IDSelector* sel;
+
+ explicit BlockResultHandler(size_t nq, const IDSelector* sel = nullptr)
+ : nq(nq), sel(sel) {
+ assert(!use_sel || sel);
+ }
+
+ // currently handled query range
+ size_t i0 = 0, i1 = 0;
+
+ // start collecting results for queries [i0, i1)
+ virtual void begin_multiple(size_t i0_2, size_t i1_2) {
+ this->i0 = i0_2;
+ this->i1 = i1_2;
+ }
+
+ // add results for queries [i0, i1) and database [j0, j1)
+ virtual void add_results(size_t, size_t, const typename C::T*) {}
+
+ // series of results for queries i0..i1 is done
+ virtual void end_multiple() {}
+
+ virtual ~BlockResultHandler() {}
+
+ bool is_in_selection(idx_t i) const {
+ return !use_sel || sel->is_member(i);
+ }
+};
+
+// handler for a single query
+template <class C>
+struct ResultHandler {
+ // if not better than threshold, then not necessary to call add_result
+ typename C::T threshold = C::neutral();
+
+ // return whether threshold was updated
+ virtual bool add_result(typename C::T dis, typename C::TI idx) = 0;
+
+ virtual ~ResultHandler() {}
+};
+
+/*****************************************************************
+ * Single best result handler.
+ * Tracks the only best result, thus avoiding storing
+ * some temporary data in memory.
+ *****************************************************************/
+
+template <class C, bool use_sel = false>
+struct Top1BlockResultHandler : BlockResultHandler<C, use_sel> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using BlockResultHandler<C, use_sel>::i0;
+ using BlockResultHandler<C, use_sel>::i1;
+
+ // contains exactly nq elements
+ T* dis_tab;
+ // contains exactly nq elements
+ TI* ids_tab;
+
+ Top1BlockResultHandler(
+ size_t nq,
+ T* dis_tab,
+ TI* ids_tab,
+ const IDSelector* sel = nullptr)
+ : BlockResultHandler<C, use_sel>(nq, sel),
+ dis_tab(dis_tab),
+ ids_tab(ids_tab) {}
+
+ struct SingleResultHandler : ResultHandler<C> {
+ Top1BlockResultHandler& hr;
+ using ResultHandler<C>::threshold;
+
+ TI min_idx;
+ size_t current_idx = 0;
+
+ explicit SingleResultHandler(Top1BlockResultHandler& hr) : hr(hr) {}
+
+ /// begin results for query # i
+ void begin(const size_t current_idx_2) {
+ this->current_idx = current_idx_2;
+ threshold = C::neutral();
+ min_idx = -1;
+ }
+
+ /// add one result for query i
+ bool add_result(T dis, TI idx) final {
+ if (C::cmp(this->threshold, dis)) {
+ threshold = dis;
+ min_idx = idx;
+ return true;
+ }
+ return false;
+ }
+
+ /// series of results for query i is done
+ void end() {
+ hr.dis_tab[current_idx] = threshold;
+ hr.ids_tab[current_idx] = min_idx;
+ }
+ };
+
+ /// begin
+ void begin_multiple(size_t i0, size_t i1) final {
+ this->i0 = i0;
+ this->i1 = i1;
+
+ for (size_t i = i0; i < i1; i++) {
+ this->dis_tab[i] = C::neutral();
+ }
+ }
+
+ /// add results for query i0..i1 and j0..j1
+ void add_results(size_t j0, size_t j1, const T* dis_tab_2) final {
+ for (int64_t i = i0; i < i1; i++) {
+ const T* dis_tab_i = dis_tab_2 + (j1 - j0) * (i - i0) - j0;
+
+ auto& min_distance = this->dis_tab[i];
+ auto& min_index = this->ids_tab[i];
+
+ for (size_t j = j0; j < j1; j++) {
+ const T distance = dis_tab_i[j];
+
+ if (C::cmp(min_distance, distance)) {
+ min_distance = distance;
+ min_index = j;
+ }
+ }
+ }
+ }
+
+ void add_result(const size_t i, const T dis, const TI idx) {
+ auto& min_distance = this->dis_tab[i];
+ auto& min_index = this->ids_tab[i];
+
+ if (C::cmp(min_distance, dis)) {
+ min_distance = dis;
+ min_index = idx;
+ }
+ }
+};
+
+/*****************************************************************
+ * Heap based result handler
+ *****************************************************************/
+
+template <class C, bool use_sel = false>
+struct HeapBlockResultHandler : BlockResultHandler<C, use_sel> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using BlockResultHandler<C, use_sel>::i0;
+ using BlockResultHandler<C, use_sel>::i1;
+
+ T* heap_dis_tab;
+ TI* heap_ids_tab;
+
+ int64_t k; // number of results to keep
+
+ HeapBlockResultHandler(
+ size_t nq,
+ T* heap_dis_tab,
+ TI* heap_ids_tab,
+ size_t k,
+ const IDSelector* sel = nullptr)
+ : BlockResultHandler<C, use_sel>(nq, sel),
+ heap_dis_tab(heap_dis_tab),
+ heap_ids_tab(heap_ids_tab),
+ k(k) {}
+
+ /******************************************************
+ * API for 1 result at a time (each SingleResultHandler is
+ * called from 1 thread)
+ */
+
+ struct SingleResultHandler : ResultHandler<C> {
+ HeapBlockResultHandler& hr;
+ using ResultHandler<C>::threshold;
+ size_t k;
+
+ T* heap_dis;
+ TI* heap_ids;
+
+ explicit SingleResultHandler(HeapBlockResultHandler& hr)
+ : hr(hr), k(hr.k) {}
+
+ /// begin results for query # i
+ void begin(size_t i) {
+ heap_dis = hr.heap_dis_tab + i * k;
+ heap_ids = hr.heap_ids_tab + i * k;
+ heap_heapify<C>(k, heap_dis, heap_ids);
+ threshold = heap_dis[0];
+ }
+
+ /// add one result for query i
+ bool add_result(T dis, TI idx) final {
+ if (C::cmp(threshold, dis)) {
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis, idx);
+ threshold = heap_dis[0];
+ return true;
+ }
+ return false;
+ }
+
+ /// series of results for query i is done
+ void end() {
+ heap_reorder<C>(k, heap_dis, heap_ids);
+ }
+ };
+
+ /******************************************************
+ * API for multiple results (called from 1 thread)
+ */
+
+ /// begin
+ void begin_multiple(size_t i0_2, size_t i1_2) final {
+ this->i0 = i0_2;
+ this->i1 = i1_2;
+ for (size_t i = i0; i < i1; i++) {
+ heap_heapify<C>(k, heap_dis_tab + i * k, heap_ids_tab + i * k);
+ }
+ }
+
+ /// add results for query i0..i1 and j0..j1
+ void add_results(size_t j0, size_t j1, const T* dis_tab) final {
+#pragma omp parallel for
+ for (int64_t i = i0; i < i1; i++) {
+ T* heap_dis = heap_dis_tab + i * k;
+ TI* heap_ids = heap_ids_tab + i * k;
+ const T* dis_tab_i = dis_tab + (j1 - j0) * (i - i0) - j0;
+ T thresh = heap_dis[0];
+ for (size_t j = j0; j < j1; j++) {
+ T dis = dis_tab_i[j];
+ if (C::cmp(thresh, dis)) {
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis, j);
+ thresh = heap_dis[0];
+ }
+ }
+ }
+ }
+
+ /// series of results for queries i0..i1 is done
+ void end_multiple() final {
+ // maybe parallel for
+ for (size_t i = i0; i < i1; i++) {
+ heap_reorder<C>(k, heap_dis_tab + i * k, heap_ids_tab + i * k);
+ }
+ }
+};
+
+/*****************************************************************
+ * Reservoir result handler
+ *
+ * A reservoir is a result array of size capacity > n (number of requested
+ * results) all results below a threshold are stored in an arbitrary order. When
+ * the capacity is reached, a new threshold is chosen by partitionning the
+ * distance array.
+ *****************************************************************/
+
+/// Reservoir for a single query
+template <class C>
+struct ReservoirTopN : ResultHandler<C> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using ResultHandler<C>::threshold;
+
+ T* vals;
+ TI* ids;
+
+ size_t i; // number of stored elements
+ size_t n; // number of requested elements
+ size_t capacity; // size of storage
+
+ ReservoirTopN() {}
+
+ ReservoirTopN(size_t n, size_t capacity, T* vals, TI* ids)
+ : vals(vals), ids(ids), i(0), n(n), capacity(capacity) {
+ assert(n < capacity);
+ threshold = C::neutral();
+ }
+
+ bool add_result(T val, TI id) final {
+ bool updated_threshold = false;
+ if (C::cmp(threshold, val)) {
+ if (i == capacity) {
+ shrink_fuzzy();
+ updated_threshold = true;
+ }
+ vals[i] = val;
+ ids[i] = id;
+ i++;
+ }
+ return updated_threshold;
+ }
+
+ void add(T val, TI id) {
+ add_result(val, id);
+ }
+
+ // reduce storage from capacity to anything
+ // between n and (capacity + n) / 2
+ void shrink_fuzzy() {
+ assert(i == capacity);
+
+ threshold = partition_fuzzy<C>(
+ vals, ids, capacity, n, (capacity + n) / 2, &i);
+ }
+
+ void shrink() {
+ threshold = partition<C>(vals, ids, i, n);
+ i = n;
+ }
+
+ void to_result(T* heap_dis, TI* heap_ids) const {
+ for (int j = 0; j < std::min(i, n); j++) {
+ heap_push<C>(j + 1, heap_dis, heap_ids, vals[j], ids[j]);
+ }
+
+ if (i < n) {
+ heap_reorder<C>(i, heap_dis, heap_ids);
+ // add empty results
+ heap_heapify<C>(n - i, heap_dis + i, heap_ids + i);
+ } else {
+ // add remaining elements
+ heap_addn<C>(n, heap_dis, heap_ids, vals + n, ids + n, i - n);
+ heap_reorder<C>(n, heap_dis, heap_ids);
+ }
+ }
+};
+
+template <class C, bool use_sel = false>
+struct ReservoirBlockResultHandler : BlockResultHandler<C, use_sel> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using BlockResultHandler<C, use_sel>::i0;
+ using BlockResultHandler<C, use_sel>::i1;
+
+ T* heap_dis_tab;
+ TI* heap_ids_tab;
+
+ int64_t k; // number of results to keep
+ size_t capacity; // capacity of the reservoirs
+
+ ReservoirBlockResultHandler(
+ size_t nq,
+ T* heap_dis_tab,
+ TI* heap_ids_tab,
+ size_t k,
+ const IDSelector* sel = nullptr)
+ : BlockResultHandler<C, use_sel>(nq, sel),
+ heap_dis_tab(heap_dis_tab),
+ heap_ids_tab(heap_ids_tab),
+ k(k) {
+ // double then round up to multiple of 16 (for SIMD alignment)
+ capacity = (2 * k + 15) & ~15;
+ }
+
+ /******************************************************
+ * API for 1 result at a time (each SingleResultHandler is
+ * called from 1 thread)
+ */
+
+ struct SingleResultHandler : ReservoirTopN<C> {
+ ReservoirBlockResultHandler& hr;
+
+ std::vector<T> reservoir_dis;
+ std::vector<TI> reservoir_ids;
+
+ explicit SingleResultHandler(ReservoirBlockResultHandler& hr)
+ : ReservoirTopN<C>(hr.k, hr.capacity, nullptr, nullptr),
+ hr(hr) {}
+
+ size_t qno;
+
+ /// begin results for query # i
+ void begin(size_t qno_2) {
+ reservoir_dis.resize(hr.capacity);
+ reservoir_ids.resize(hr.capacity);
+ this->vals = reservoir_dis.data();
+ this->ids = reservoir_ids.data();
+ this->i = 0; // size of reservoir
+ this->threshold = C::neutral();
+ this->qno = qno_2;
+ }
+
+ /// series of results for query qno is done
+ void end() {
+ T* heap_dis = hr.heap_dis_tab + qno * hr.k;
+ TI* heap_ids = hr.heap_ids_tab + qno * hr.k;
+ this->to_result(heap_dis, heap_ids);
+ }
+ };
+
+ /******************************************************
+ * API for multiple results (called from 1 thread)
+ */
+
+ std::vector<T> reservoir_dis;
+ std::vector<TI> reservoir_ids;
+ std::vector<ReservoirTopN<C>> reservoirs;
+
+ /// begin
+ void begin_multiple(size_t i0_2, size_t i1_2) {
+ this->i0 = i0_2;
+ this->i1 = i1_2;
+ reservoir_dis.resize((i1 - i0) * capacity);
+ reservoir_ids.resize((i1 - i0) * capacity);
+ reservoirs.clear();
+ for (size_t i = i0_2; i < i1_2; i++) {
+ reservoirs.emplace_back(
+ k,
+ capacity,
+ reservoir_dis.data() + (i - i0_2) * capacity,
+ reservoir_ids.data() + (i - i0_2) * capacity);
+ }
+ }
+
+ /// add results for query i0..i1 and j0..j1
+ void add_results(size_t j0, size_t j1, const T* dis_tab) {
+#pragma omp parallel for
+ for (int64_t i = i0; i < i1; i++) {
+ ReservoirTopN<C>& reservoir = reservoirs[i - i0];
+ const T* dis_tab_i = dis_tab + (j1 - j0) * (i - i0) - j0;
+ for (size_t j = j0; j < j1; j++) {
+ T dis = dis_tab_i[j];
+ reservoir.add_result(dis, j);
+ }
+ }
+ }
+
+ /// series of results for queries i0..i1 is done
+ void end_multiple() final {
+ // maybe parallel for
+ for (size_t i = i0; i < i1; i++) {
+ reservoirs[i - i0].to_result(
+ heap_dis_tab + i * k, heap_ids_tab + i * k);
+ }
+ }
+};
+
+/*****************************************************************
+ * Result handler for range searches
+ *****************************************************************/
+
+template <class C, bool use_sel = false>
+struct RangeSearchBlockResultHandler : BlockResultHandler<C, use_sel> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using BlockResultHandler<C, use_sel>::i0;
+ using BlockResultHandler<C, use_sel>::i1;
+
+ RangeSearchResult* res;
+ T radius;
+
+ RangeSearchBlockResultHandler(
+ RangeSearchResult* res,
+ float radius,
+ const IDSelector* sel = nullptr)
+ : BlockResultHandler<C, use_sel>(res->nq, sel),
+ res(res),
+ radius(radius) {}
+
+ /******************************************************
+ * API for 1 result at a time (each SingleResultHandler is
+ * called from 1 thread)
+ ******************************************************/
+
+ struct SingleResultHandler : ResultHandler<C> {
+ // almost the same interface as RangeSearchResultHandler
+ using ResultHandler<C>::threshold;
+ RangeSearchPartialResult pres;
+ RangeQueryResult* qr = nullptr;
+
+ explicit SingleResultHandler(RangeSearchBlockResultHandler& rh)
+ : pres(rh.res) {
+ threshold = rh.radius;
+ }
+
+ /// begin results for query # i
+ void begin(size_t i) {
+ qr = &pres.new_result(i);
+ }
+
+ /// add one result for query i
+ bool add_result(T dis, TI idx) final {
+ if (C::cmp(threshold, dis)) {
+ qr->add(dis, idx);
+ }
+ return false;
+ }
+
+ /// series of results for query i is done
+ void end() {}
+
+ ~SingleResultHandler() {
+ try {
+ // finalize the partial result
+ pres.finalize();
+ } catch ([[maybe_unused]] const faiss::FaissException& e) {
+ // Do nothing if allocation fails in finalizing partial results.
+#ifndef NDEBUG
+ std::cerr << e.what() << std::endl;
+#endif
+ }
+ }
+ };
+
+ /******************************************************
+ * API for multiple results (called from 1 thread)
+ ******************************************************/
+
+ std::vector<RangeSearchPartialResult*> partial_results;
+ std::vector<size_t> j0s;
+ int pr = 0;
+
+ /// begin
+ void begin_multiple(size_t i0_2, size_t i1_2) {
+ this->i0 = i0_2;
+ this->i1 = i1_2;
+ }
+
+ /// add results for query i0..i1 and j0..j1
+
+ void add_results(size_t j0, size_t j1, const T* dis_tab) {
+ RangeSearchPartialResult* pres;
+ // there is one RangeSearchPartialResult structure per j0
+ // (= block of columns of the large distance matrix)
+ // it is a bit tricky to find the poper PartialResult structure
+ // because the inner loop is on db not on queries.
+
+ if (pr < j0s.size() && j0 == j0s[pr]) {
+ pres = partial_results[pr];
+ pr++;
+ } else if (j0 == 0 && j0s.size() > 0) {
+ pr = 0;
+ pres = partial_results[pr];
+ pr++;
+ } else { // did not find this j0
+ pres = new RangeSearchPartialResult(res);
+ partial_results.push_back(pres);
+ j0s.push_back(j0);
+ pr = partial_results.size();
+ }
+
+ for (size_t i = i0; i < i1; i++) {
+ const float* ip_line = dis_tab + (i - i0) * (j1 - j0);
+ RangeQueryResult& qres = pres->new_result(i);
+
+ for (size_t j = j0; j < j1; j++) {
+ float dis = *ip_line++;
+ if (C::cmp(radius, dis)) {
+ qres.add(dis, j);
+ }
+ }
+ }
+ }
+
+ ~RangeSearchBlockResultHandler() {
+ try {
+ if (partial_results.size() > 0) {
+ RangeSearchPartialResult::merge(partial_results);
+ }
+ } catch ([[maybe_unused]] const faiss::FaissException& e) {
+ // Do nothing if allocation fails in merge.
+#ifndef NDEBUG
+ std::cerr << e.what() << std::endl;
+#endif
+ }
+ }
+};
+
+/*****************************************************************
+ * Dispatcher function to choose the right knn result handler depending on k
+ *****************************************************************/
+
+// declared in distances.cpp
+FAISS_API extern int distance_compute_min_k_reservoir;
+
+template <class Consumer, class... Types>
+typename Consumer::T dispatch_knn_ResultHandler(
+ size_t nx,
+ float* vals,
+ int64_t* ids,
+ size_t k,
+ MetricType metric,
+ const IDSelector* sel,
+ Consumer& consumer,
+ Types... args) {
+#define DISPATCH_C_SEL(C, use_sel) \
+ if (k == 1) { \
+ Top1BlockResultHandler<C, use_sel> res(nx, vals, ids, sel); \
+ return consumer.template f<>(res, args...); \
+ } else if (k < distance_compute_min_k_reservoir) { \
+ HeapBlockResultHandler<C, use_sel> res(nx, vals, ids, k, sel); \
+ return consumer.template f<>(res, args...); \
+ } else { \
+ ReservoirBlockResultHandler<C, use_sel> res(nx, vals, ids, k, sel); \
+ return consumer.template f<>(res, args...); \
+ }
+
+ if (is_similarity_metric(metric)) {
+ using C = CMin<float, int64_t>;
+ if (sel) {
+ DISPATCH_C_SEL(C, true);
+ } else {
+ DISPATCH_C_SEL(C, false);
+ }
+ } else {
+ using C = CMax<float, int64_t>;
+ if (sel) {
+ DISPATCH_C_SEL(C, true);
+ } else {
+ DISPATCH_C_SEL(C, false);
+ }
+ }
+#undef DISPATCH_C_SEL
+}
+
+template <class Consumer, class... Types>
+typename Consumer::T dispatch_range_ResultHandler(
+ RangeSearchResult* res,
+ float radius,
+ MetricType metric,
+ const IDSelector* sel,
+ Consumer& consumer,
+ Types... args) {
+#define DISPATCH_C_SEL(C, use_sel) \
+ RangeSearchBlockResultHandler<C, use_sel> resb(res, radius, sel); \
+ return consumer.template f<>(resb, args...);
+
+ if (is_similarity_metric(metric)) {
+ using C = CMin<float, int64_t>;
+ if (sel) {
+ DISPATCH_C_SEL(C, true);
+ } else {
+ DISPATCH_C_SEL(C, false);
+ }
+ } else {
+ using C = CMax<float, int64_t>;
+ if (sel) {
+ DISPATCH_C_SEL(C, true);
+ } else {
+ DISPATCH_C_SEL(C, false);
+ }
+ }
+#undef DISPATCH_C_SEL
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ScalarQuantizer.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ScalarQuantizer.cpp
new file mode 100644
index 0000000..e05f3a1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ScalarQuantizer.cpp
@@ -0,0 +1,2481 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/ScalarQuantizer.h>
+
+#include <algorithm>
+#include <cstdio>
+
+#include <faiss/impl/platform_macros.h>
+#include <omp.h>
+
+#ifdef __SSE__
+#include <immintrin.h>
+#endif
+
+#include <faiss/IndexIVF.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/utils/bf16.h>
+#include <faiss/utils/fp16.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/*******************************************************************
+ * ScalarQuantizer implementation
+ *
+ * The main source of complexity is to support combinations of 4
+ * variants without incurring runtime tests or virtual function calls:
+ *
+ * - 4 / 8 bits per code component
+ * - uniform / non-uniform
+ * - IP / L2 distance search
+ * - scalar / AVX distance computation
+ *
+ * The appropriate Quantizer object is returned via select_quantizer
+ * that hides the template mess.
+ ********************************************************************/
+
+#if defined(__AVX512F__) && defined(__F16C__)
+#define USE_AVX512_F16C
+#elif defined(__AVX2__)
+#ifdef __F16C__
+#define USE_F16C
+#else
+#warning \
+ "Cannot enable AVX optimizations in scalar quantizer if -mf16c is not set as well"
+#endif
+#endif
+
+#if defined(__aarch64__)
+#if defined(__GNUC__) && __GNUC__ < 8
+#warning \
+ "Cannot enable NEON optimizations in scalar quantizer if the compiler is GCC<8"
+#else
+#define USE_NEON
+#endif
+#endif
+
+namespace {
+
+typedef ScalarQuantizer::QuantizerType QuantizerType;
+typedef ScalarQuantizer::RangeStat RangeStat;
+using SQDistanceComputer = ScalarQuantizer::SQDistanceComputer;
+
+/*******************************************************************
+ * Codec: converts between values in [0, 1] and an index in a code
+ * array. The "i" parameter is the vector component index (not byte
+ * index).
+ */
+
+struct Codec8bit {
+ static FAISS_ALWAYS_INLINE void encode_component(
+ float x,
+ uint8_t* code,
+ int i) {
+ code[i] = (int)(255 * x);
+ }
+
+ static FAISS_ALWAYS_INLINE float decode_component(
+ const uint8_t* code,
+ int i) {
+ return (code[i] + 0.5f) / 255.0f;
+ }
+
+#if defined(__AVX512F__)
+ static FAISS_ALWAYS_INLINE __m512
+ decode_16_components(const uint8_t* code, int i) {
+ const __m128i c16 = _mm_loadu_si128((__m128i*)(code + i));
+ const __m512i i32 = _mm512_cvtepu8_epi32(c16);
+ const __m512 f16 = _mm512_cvtepi32_ps(i32);
+ const __m512 half_one_255 = _mm512_set1_ps(0.5f / 255.f);
+ const __m512 one_255 = _mm512_set1_ps(1.f / 255.f);
+ return _mm512_fmadd_ps(f16, one_255, half_one_255);
+ }
+#elif defined(__AVX2__)
+ static FAISS_ALWAYS_INLINE __m256
+ decode_8_components(const uint8_t* code, int i) {
+ const uint64_t c8 = *(uint64_t*)(code + i);
+
+ const __m128i i8 = _mm_set1_epi64x(c8);
+ const __m256i i32 = _mm256_cvtepu8_epi32(i8);
+ const __m256 f8 = _mm256_cvtepi32_ps(i32);
+ const __m256 half_one_255 = _mm256_set1_ps(0.5f / 255.f);
+ const __m256 one_255 = _mm256_set1_ps(1.f / 255.f);
+ return _mm256_fmadd_ps(f8, one_255, half_one_255);
+ }
+#endif
+
+#ifdef USE_NEON
+ static FAISS_ALWAYS_INLINE float32x4x2_t
+ decode_8_components(const uint8_t* code, int i) {
+ float32_t result[8] = {};
+ for (size_t j = 0; j < 8; j++) {
+ result[j] = decode_component(code, i + j);
+ }
+ float32x4_t res1 = vld1q_f32(result);
+ float32x4_t res2 = vld1q_f32(result + 4);
+ return {res1, res2};
+ }
+#endif
+};
+
+struct Codec4bit {
+ static FAISS_ALWAYS_INLINE void encode_component(
+ float x,
+ uint8_t* code,
+ int i) {
+ code[i / 2] |= (int)(x * 15.0) << ((i & 1) << 2);
+ }
+
+ static FAISS_ALWAYS_INLINE float decode_component(
+ const uint8_t* code,
+ int i) {
+ return (((code[i / 2] >> ((i & 1) << 2)) & 0xf) + 0.5f) / 15.0f;
+ }
+
+#if defined(__AVX512F__)
+ static FAISS_ALWAYS_INLINE __m512
+ decode_16_components(const uint8_t* code, int i) {
+ uint64_t c8 = *(uint64_t*)(code + (i >> 1));
+ uint64_t mask = 0x0f0f0f0f0f0f0f0f;
+ uint64_t c8ev = c8 & mask;
+ uint64_t c8od = (c8 >> 4) & mask;
+
+ __m128i c16 =
+ _mm_unpacklo_epi8(_mm_set1_epi64x(c8ev), _mm_set1_epi64x(c8od));
+ __m256i c8lo = _mm256_cvtepu8_epi32(c16);
+ __m256i c8hi = _mm256_cvtepu8_epi32(_mm_srli_si128(c16, 8));
+ __m512i i16 = _mm512_castsi256_si512(c8lo);
+ i16 = _mm512_inserti32x8(i16, c8hi, 1);
+ __m512 f16 = _mm512_cvtepi32_ps(i16);
+ const __m512 half_one_255 = _mm512_set1_ps(0.5f / 15.f);
+ const __m512 one_255 = _mm512_set1_ps(1.f / 15.f);
+ return _mm512_fmadd_ps(f16, one_255, half_one_255);
+ }
+#elif defined(__AVX2__)
+ static FAISS_ALWAYS_INLINE __m256
+ decode_8_components(const uint8_t* code, int i) {
+ uint32_t c4 = *(uint32_t*)(code + (i >> 1));
+ uint32_t mask = 0x0f0f0f0f;
+ uint32_t c4ev = c4 & mask;
+ uint32_t c4od = (c4 >> 4) & mask;
+
+ // the 8 lower bytes of c8 contain the values
+ __m128i c8 =
+ _mm_unpacklo_epi8(_mm_set1_epi32(c4ev), _mm_set1_epi32(c4od));
+ __m128i c4lo = _mm_cvtepu8_epi32(c8);
+ __m128i c4hi = _mm_cvtepu8_epi32(_mm_srli_si128(c8, 4));
+ __m256i i8 = _mm256_castsi128_si256(c4lo);
+ i8 = _mm256_insertf128_si256(i8, c4hi, 1);
+ __m256 f8 = _mm256_cvtepi32_ps(i8);
+ __m256 half = _mm256_set1_ps(0.5f);
+ f8 = _mm256_add_ps(f8, half);
+ __m256 one_255 = _mm256_set1_ps(1.f / 15.f);
+ return _mm256_mul_ps(f8, one_255);
+ }
+#endif
+
+#ifdef USE_NEON
+ static FAISS_ALWAYS_INLINE float32x4x2_t
+ decode_8_components(const uint8_t* code, int i) {
+ float32_t result[8] = {};
+ for (size_t j = 0; j < 8; j++) {
+ result[j] = decode_component(code, i + j);
+ }
+ float32x4_t res1 = vld1q_f32(result);
+ float32x4_t res2 = vld1q_f32(result + 4);
+ return {res1, res2};
+ }
+#endif
+};
+
+struct Codec6bit {
+ static FAISS_ALWAYS_INLINE void encode_component(
+ float x,
+ uint8_t* code,
+ int i) {
+ int bits = (int)(x * 63.0);
+ code += (i >> 2) * 3;
+ switch (i & 3) {
+ case 0:
+ code[0] |= bits;
+ break;
+ case 1:
+ code[0] |= bits << 6;
+ code[1] |= bits >> 2;
+ break;
+ case 2:
+ code[1] |= bits << 4;
+ code[2] |= bits >> 4;
+ break;
+ case 3:
+ code[2] |= bits << 2;
+ break;
+ }
+ }
+
+ static FAISS_ALWAYS_INLINE float decode_component(
+ const uint8_t* code,
+ int i) {
+ uint8_t bits;
+ code += (i >> 2) * 3;
+ switch (i & 3) {
+ case 0:
+ bits = code[0] & 0x3f;
+ break;
+ case 1:
+ bits = code[0] >> 6;
+ bits |= (code[1] & 0xf) << 2;
+ break;
+ case 2:
+ bits = code[1] >> 4;
+ bits |= (code[2] & 3) << 4;
+ break;
+ case 3:
+ bits = code[2] >> 2;
+ break;
+ }
+ return (bits + 0.5f) / 63.0f;
+ }
+
+#if defined(__AVX512F__)
+
+ static FAISS_ALWAYS_INLINE __m512
+ decode_16_components(const uint8_t* code, int i) {
+ // pure AVX512 implementation (not necessarily the fastest).
+ // see:
+ // https://github.com/zilliztech/knowhere/blob/main/thirdparty/faiss/faiss/impl/ScalarQuantizerCodec_avx512.h
+
+ // clang-format off
+
+ // 16 components, 16x6 bit=12 bytes
+ const __m128i bit_6v =
+ _mm_maskz_loadu_epi8(0b0000111111111111, code + (i >> 2) * 3);
+ const __m256i bit_6v_256 = _mm256_broadcast_i32x4(bit_6v);
+
+ // 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
+ // 00 01 02 03
+ const __m256i shuffle_mask = _mm256_setr_epi16(
+ 0xFF00, 0x0100, 0x0201, 0xFF02,
+ 0xFF03, 0x0403, 0x0504, 0xFF05,
+ 0xFF06, 0x0706, 0x0807, 0xFF08,
+ 0xFF09, 0x0A09, 0x0B0A, 0xFF0B);
+ const __m256i shuffled = _mm256_shuffle_epi8(bit_6v_256, shuffle_mask);
+
+ // 0: xxxxxxxx xx543210
+ // 1: xxxx5432 10xxxxxx
+ // 2: xxxxxx54 3210xxxx
+ // 3: xxxxxxxx 543210xx
+ const __m256i shift_right_v = _mm256_setr_epi16(
+ 0x0U, 0x6U, 0x4U, 0x2U,
+ 0x0U, 0x6U, 0x4U, 0x2U,
+ 0x0U, 0x6U, 0x4U, 0x2U,
+ 0x0U, 0x6U, 0x4U, 0x2U);
+ __m256i shuffled_shifted = _mm256_srlv_epi16(shuffled, shift_right_v);
+
+ // remove unneeded bits
+ shuffled_shifted =
+ _mm256_and_si256(shuffled_shifted, _mm256_set1_epi16(0x003F));
+
+ // scale
+ const __m512 f8 =
+ _mm512_cvtepi32_ps(_mm512_cvtepi16_epi32(shuffled_shifted));
+ const __m512 half_one_255 = _mm512_set1_ps(0.5f / 63.f);
+ const __m512 one_255 = _mm512_set1_ps(1.f / 63.f);
+ return _mm512_fmadd_ps(f8, one_255, half_one_255);
+
+ // clang-format on
+ }
+
+#elif defined(__AVX2__)
+
+ /* Load 6 bytes that represent 8 6-bit values, return them as a
+ * 8*32 bit vector register */
+ static FAISS_ALWAYS_INLINE __m256i load6(const uint16_t* code16) {
+ const __m128i perm = _mm_set_epi8(
+ -1, 5, 5, 4, 4, 3, -1, 3, -1, 2, 2, 1, 1, 0, -1, 0);
+ const __m256i shifts = _mm256_set_epi32(2, 4, 6, 0, 2, 4, 6, 0);
+
+ // load 6 bytes
+ __m128i c1 =
+ _mm_set_epi16(0, 0, 0, 0, 0, code16[2], code16[1], code16[0]);
+
+ // put in 8 * 32 bits
+ __m128i c2 = _mm_shuffle_epi8(c1, perm);
+ __m256i c3 = _mm256_cvtepi16_epi32(c2);
+
+ // shift and mask out useless bits
+ __m256i c4 = _mm256_srlv_epi32(c3, shifts);
+ __m256i c5 = _mm256_and_si256(_mm256_set1_epi32(63), c4);
+ return c5;
+ }
+
+ static FAISS_ALWAYS_INLINE __m256
+ decode_8_components(const uint8_t* code, int i) {
+ // // Faster code for Intel CPUs or AMD Zen3+, just keeping it here
+ // // for the reference, maybe, it becomes used oned day.
+ // const uint16_t* data16 = (const uint16_t*)(code + (i >> 2) * 3);
+ // const uint32_t* data32 = (const uint32_t*)data16;
+ // const uint64_t val = *data32 + ((uint64_t)data16[2] << 32);
+ // const uint64_t vext = _pdep_u64(val, 0x3F3F3F3F3F3F3F3FULL);
+ // const __m128i i8 = _mm_set1_epi64x(vext);
+ // const __m256i i32 = _mm256_cvtepi8_epi32(i8);
+ // const __m256 f8 = _mm256_cvtepi32_ps(i32);
+ // const __m256 half_one_255 = _mm256_set1_ps(0.5f / 63.f);
+ // const __m256 one_255 = _mm256_set1_ps(1.f / 63.f);
+ // return _mm256_fmadd_ps(f8, one_255, half_one_255);
+
+ __m256i i8 = load6((const uint16_t*)(code + (i >> 2) * 3));
+ __m256 f8 = _mm256_cvtepi32_ps(i8);
+ // this could also be done with bit manipulations but it is
+ // not obviously faster
+ const __m256 half_one_255 = _mm256_set1_ps(0.5f / 63.f);
+ const __m256 one_255 = _mm256_set1_ps(1.f / 63.f);
+ return _mm256_fmadd_ps(f8, one_255, half_one_255);
+ }
+
+#endif
+
+#ifdef USE_NEON
+ static FAISS_ALWAYS_INLINE float32x4x2_t
+ decode_8_components(const uint8_t* code, int i) {
+ float32_t result[8] = {};
+ for (size_t j = 0; j < 8; j++) {
+ result[j] = decode_component(code, i + j);
+ }
+ float32x4_t res1 = vld1q_f32(result);
+ float32x4_t res2 = vld1q_f32(result + 4);
+ return {res1, res2};
+ }
+#endif
+};
+
+/*******************************************************************
+ * Quantizer: normalizes scalar vector components, then passes them
+ * through a codec
+ *******************************************************************/
+
+enum class QuantizerTemplateScaling { UNIFORM = 0, NON_UNIFORM = 1 };
+
+template <class Codec, QuantizerTemplateScaling SCALING, int SIMD>
+struct QuantizerTemplate {};
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1>
+ : ScalarQuantizer::SQuantizer {
+ const size_t d;
+ const float vmin, vdiff;
+
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : d(d), vmin(trained[0]), vdiff(trained[1]) {}
+
+ void encode_vector(const float* x, uint8_t* code) const final {
+ for (size_t i = 0; i < d; i++) {
+ float xi = 0;
+ if (vdiff != 0) {
+ xi = (x[i] - vmin) / vdiff;
+ if (xi < 0) {
+ xi = 0;
+ }
+ if (xi > 1.0) {
+ xi = 1.0;
+ }
+ }
+ Codec::encode_component(xi, code, i);
+ }
+ }
+
+ void decode_vector(const uint8_t* code, float* x) const final {
+ for (size_t i = 0; i < d; i++) {
+ float xi = Codec::decode_component(code, i);
+ x[i] = vmin + xi * vdiff;
+ }
+ }
+
+ FAISS_ALWAYS_INLINE float reconstruct_component(const uint8_t* code, int i)
+ const {
+ float xi = Codec::decode_component(code, i);
+ return vmin + xi * vdiff;
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 16>
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1> {
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1>(
+ d,
+ trained) {}
+
+ FAISS_ALWAYS_INLINE __m512
+ reconstruct_16_components(const uint8_t* code, int i) const {
+ __m512 xi = Codec::decode_16_components(code, i);
+ return _mm512_fmadd_ps(
+ xi, _mm512_set1_ps(this->vdiff), _mm512_set1_ps(this->vmin));
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 8>
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1> {
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1>(
+ d,
+ trained) {}
+
+ FAISS_ALWAYS_INLINE __m256
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ __m256 xi = Codec::decode_8_components(code, i);
+ return _mm256_fmadd_ps(
+ xi, _mm256_set1_ps(this->vdiff), _mm256_set1_ps(this->vmin));
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 8>
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1> {
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::UNIFORM, 1>(
+ d,
+ trained) {}
+
+ FAISS_ALWAYS_INLINE float32x4x2_t
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ float32x4x2_t xi = Codec::decode_8_components(code, i);
+ return {vfmaq_f32(
+ vdupq_n_f32(this->vmin),
+ xi.val[0],
+ vdupq_n_f32(this->vdiff)),
+ vfmaq_f32(
+ vdupq_n_f32(this->vmin),
+ xi.val[1],
+ vdupq_n_f32(this->vdiff))};
+ }
+};
+
+#endif
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 1>
+ : ScalarQuantizer::SQuantizer {
+ const size_t d;
+ const float *vmin, *vdiff;
+
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : d(d), vmin(trained.data()), vdiff(trained.data() + d) {}
+
+ void encode_vector(const float* x, uint8_t* code) const final {
+ for (size_t i = 0; i < d; i++) {
+ float xi = 0;
+ if (vdiff[i] != 0) {
+ xi = (x[i] - vmin[i]) / vdiff[i];
+ if (xi < 0) {
+ xi = 0;
+ }
+ if (xi > 1.0) {
+ xi = 1.0;
+ }
+ }
+ Codec::encode_component(xi, code, i);
+ }
+ }
+
+ void decode_vector(const uint8_t* code, float* x) const final {
+ for (size_t i = 0; i < d; i++) {
+ float xi = Codec::decode_component(code, i);
+ x[i] = vmin[i] + xi * vdiff[i];
+ }
+ }
+
+ FAISS_ALWAYS_INLINE float reconstruct_component(const uint8_t* code, int i)
+ const {
+ float xi = Codec::decode_component(code, i);
+ return vmin[i] + xi * vdiff[i];
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 16>
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 1> {
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : QuantizerTemplate<
+ Codec,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ 1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m512
+ reconstruct_16_components(const uint8_t* code, int i) const {
+ __m512 xi = Codec::decode_16_components(code, i);
+ return _mm512_fmadd_ps(
+ xi,
+ _mm512_loadu_ps(this->vdiff + i),
+ _mm512_loadu_ps(this->vmin + i));
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 8>
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 1> {
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : QuantizerTemplate<
+ Codec,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ 1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m256
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ __m256 xi = Codec::decode_8_components(code, i);
+ return _mm256_fmadd_ps(
+ xi,
+ _mm256_loadu_ps(this->vdiff + i),
+ _mm256_loadu_ps(this->vmin + i));
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <class Codec>
+struct QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 8>
+ : QuantizerTemplate<Codec, QuantizerTemplateScaling::NON_UNIFORM, 1> {
+ QuantizerTemplate(size_t d, const std::vector<float>& trained)
+ : QuantizerTemplate<
+ Codec,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ 1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE float32x4x2_t
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ float32x4x2_t xi = Codec::decode_8_components(code, i);
+
+ float32x4x2_t vmin_8 = vld1q_f32_x2(this->vmin + i);
+ float32x4x2_t vdiff_8 = vld1q_f32_x2(this->vdiff + i);
+
+ return {vfmaq_f32(vmin_8.val[0], xi.val[0], vdiff_8.val[0]),
+ vfmaq_f32(vmin_8.val[1], xi.val[1], vdiff_8.val[1])};
+ }
+};
+
+#endif
+
+/*******************************************************************
+ * FP16 quantizer
+ *******************************************************************/
+
+template <int SIMDWIDTH>
+struct QuantizerFP16 {};
+
+template <>
+struct QuantizerFP16<1> : ScalarQuantizer::SQuantizer {
+ const size_t d;
+
+ QuantizerFP16(size_t d, const std::vector<float>& /* unused */) : d(d) {}
+
+ void encode_vector(const float* x, uint8_t* code) const final {
+ for (size_t i = 0; i < d; i++) {
+ ((uint16_t*)code)[i] = encode_fp16(x[i]);
+ }
+ }
+
+ void decode_vector(const uint8_t* code, float* x) const final {
+ for (size_t i = 0; i < d; i++) {
+ x[i] = decode_fp16(((uint16_t*)code)[i]);
+ }
+ }
+
+ FAISS_ALWAYS_INLINE float reconstruct_component(const uint8_t* code, int i)
+ const {
+ return decode_fp16(((uint16_t*)code)[i]);
+ }
+};
+
+#if defined(USE_AVX512_F16C)
+
+template <>
+struct QuantizerFP16<16> : QuantizerFP16<1> {
+ QuantizerFP16(size_t d, const std::vector<float>& trained)
+ : QuantizerFP16<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m512
+ reconstruct_16_components(const uint8_t* code, int i) const {
+ __m256i codei = _mm256_loadu_si256((const __m256i*)(code + 2 * i));
+ return _mm512_cvtph_ps(codei);
+ }
+};
+
+#endif
+
+#if defined(USE_F16C)
+
+template <>
+struct QuantizerFP16<8> : QuantizerFP16<1> {
+ QuantizerFP16(size_t d, const std::vector<float>& trained)
+ : QuantizerFP16<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m256
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ __m128i codei = _mm_loadu_si128((const __m128i*)(code + 2 * i));
+ return _mm256_cvtph_ps(codei);
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <>
+struct QuantizerFP16<8> : QuantizerFP16<1> {
+ QuantizerFP16(size_t d, const std::vector<float>& trained)
+ : QuantizerFP16<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE float32x4x2_t
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ uint16x4x2_t codei = vld1_u16_x2((const uint16_t*)(code + 2 * i));
+ return {vcvt_f32_f16(vreinterpret_f16_u16(codei.val[0])),
+ vcvt_f32_f16(vreinterpret_f16_u16(codei.val[1]))};
+ }
+};
+#endif
+
+/*******************************************************************
+ * BF16 quantizer
+ *******************************************************************/
+
+template <int SIMDWIDTH>
+struct QuantizerBF16 {};
+
+template <>
+struct QuantizerBF16<1> : ScalarQuantizer::SQuantizer {
+ const size_t d;
+
+ QuantizerBF16(size_t d, const std::vector<float>& /* unused */) : d(d) {}
+
+ void encode_vector(const float* x, uint8_t* code) const final {
+ for (size_t i = 0; i < d; i++) {
+ ((uint16_t*)code)[i] = encode_bf16(x[i]);
+ }
+ }
+
+ void decode_vector(const uint8_t* code, float* x) const final {
+ for (size_t i = 0; i < d; i++) {
+ x[i] = decode_bf16(((uint16_t*)code)[i]);
+ }
+ }
+
+ FAISS_ALWAYS_INLINE float reconstruct_component(const uint8_t* code, int i)
+ const {
+ return decode_bf16(((uint16_t*)code)[i]);
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <>
+struct QuantizerBF16<16> : QuantizerBF16<1> {
+ QuantizerBF16(size_t d, const std::vector<float>& trained)
+ : QuantizerBF16<1>(d, trained) {}
+ FAISS_ALWAYS_INLINE __m512
+ reconstruct_16_components(const uint8_t* code, int i) const {
+ __m256i code_256i = _mm256_loadu_si256((const __m256i*)(code + 2 * i));
+ __m512i code_512i = _mm512_cvtepu16_epi32(code_256i);
+ code_512i = _mm512_slli_epi32(code_512i, 16);
+ return _mm512_castsi512_ps(code_512i);
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <>
+struct QuantizerBF16<8> : QuantizerBF16<1> {
+ QuantizerBF16(size_t d, const std::vector<float>& trained)
+ : QuantizerBF16<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m256
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ __m128i code_128i = _mm_loadu_si128((const __m128i*)(code + 2 * i));
+ __m256i code_256i = _mm256_cvtepu16_epi32(code_128i);
+ code_256i = _mm256_slli_epi32(code_256i, 16);
+ return _mm256_castsi256_ps(code_256i);
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <>
+struct QuantizerBF16<8> : QuantizerBF16<1> {
+ QuantizerBF16(size_t d, const std::vector<float>& trained)
+ : QuantizerBF16<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE float32x4x2_t
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ uint16x4x2_t codei = vld1_u16_x2((const uint16_t*)(code + 2 * i));
+ return {vreinterpretq_f32_u32(vshlq_n_u32(vmovl_u16(codei.val[0]), 16)),
+ vreinterpretq_f32_u32(
+ vshlq_n_u32(vmovl_u16(codei.val[1]), 16))};
+ }
+};
+#endif
+
+/*******************************************************************
+ * 8bit_direct quantizer
+ *******************************************************************/
+
+template <int SIMDWIDTH>
+struct Quantizer8bitDirect {};
+
+template <>
+struct Quantizer8bitDirect<1> : ScalarQuantizer::SQuantizer {
+ const size_t d;
+
+ Quantizer8bitDirect(size_t d, const std::vector<float>& /* unused */)
+ : d(d) {}
+
+ void encode_vector(const float* x, uint8_t* code) const final {
+ for (size_t i = 0; i < d; i++) {
+ code[i] = (uint8_t)x[i];
+ }
+ }
+
+ void decode_vector(const uint8_t* code, float* x) const final {
+ for (size_t i = 0; i < d; i++) {
+ x[i] = code[i];
+ }
+ }
+
+ FAISS_ALWAYS_INLINE float reconstruct_component(const uint8_t* code, int i)
+ const {
+ return code[i];
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <>
+struct Quantizer8bitDirect<16> : Quantizer8bitDirect<1> {
+ Quantizer8bitDirect(size_t d, const std::vector<float>& trained)
+ : Quantizer8bitDirect<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m512
+ reconstruct_16_components(const uint8_t* code, int i) const {
+ __m128i x16 = _mm_loadu_si128((__m128i*)(code + i)); // 16 * int8
+ __m512i y16 = _mm512_cvtepu8_epi32(x16); // 16 * int32
+ return _mm512_cvtepi32_ps(y16); // 16 * float32
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <>
+struct Quantizer8bitDirect<8> : Quantizer8bitDirect<1> {
+ Quantizer8bitDirect(size_t d, const std::vector<float>& trained)
+ : Quantizer8bitDirect<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m256
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ __m128i x8 = _mm_loadl_epi64((__m128i*)(code + i)); // 8 * int8
+ __m256i y8 = _mm256_cvtepu8_epi32(x8); // 8 * int32
+ return _mm256_cvtepi32_ps(y8); // 8 * float32
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <>
+struct Quantizer8bitDirect<8> : Quantizer8bitDirect<1> {
+ Quantizer8bitDirect(size_t d, const std::vector<float>& trained)
+ : Quantizer8bitDirect<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE float32x4x2_t
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ uint8x8_t x8 = vld1_u8((const uint8_t*)(code + i));
+ uint16x8_t y8 = vmovl_u8(x8);
+ uint16x4_t y8_0 = vget_low_u16(y8);
+ uint16x4_t y8_1 = vget_high_u16(y8);
+
+ // convert uint16 -> uint32 -> fp32
+ return {vcvtq_f32_u32(vmovl_u16(y8_0)), vcvtq_f32_u32(vmovl_u16(y8_1))};
+ }
+};
+
+#endif
+
+/*******************************************************************
+ * 8bit_direct_signed quantizer
+ *******************************************************************/
+
+template <int SIMDWIDTH>
+struct Quantizer8bitDirectSigned {};
+
+template <>
+struct Quantizer8bitDirectSigned<1> : ScalarQuantizer::SQuantizer {
+ const size_t d;
+
+ Quantizer8bitDirectSigned(size_t d, const std::vector<float>& /* unused */)
+ : d(d) {}
+
+ void encode_vector(const float* x, uint8_t* code) const final {
+ for (size_t i = 0; i < d; i++) {
+ code[i] = (uint8_t)(x[i] + 128);
+ }
+ }
+
+ void decode_vector(const uint8_t* code, float* x) const final {
+ for (size_t i = 0; i < d; i++) {
+ x[i] = code[i] - 128;
+ }
+ }
+
+ FAISS_ALWAYS_INLINE float reconstruct_component(const uint8_t* code, int i)
+ const {
+ return code[i] - 128;
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <>
+struct Quantizer8bitDirectSigned<16> : Quantizer8bitDirectSigned<1> {
+ Quantizer8bitDirectSigned(size_t d, const std::vector<float>& trained)
+ : Quantizer8bitDirectSigned<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m512
+ reconstruct_16_components(const uint8_t* code, int i) const {
+ __m128i x16 = _mm_loadu_si128((__m128i*)(code + i)); // 16 * int8
+ __m512i y16 = _mm512_cvtepu8_epi32(x16); // 16 * int32
+ __m512i c16 = _mm512_set1_epi32(128);
+ __m512i z16 = _mm512_sub_epi32(y16, c16); // subtract 128 from all lanes
+ return _mm512_cvtepi32_ps(z16); // 16 * float32
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <>
+struct Quantizer8bitDirectSigned<8> : Quantizer8bitDirectSigned<1> {
+ Quantizer8bitDirectSigned(size_t d, const std::vector<float>& trained)
+ : Quantizer8bitDirectSigned<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE __m256
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ __m128i x8 = _mm_loadl_epi64((__m128i*)(code + i)); // 8 * int8
+ __m256i y8 = _mm256_cvtepu8_epi32(x8); // 8 * int32
+ __m256i c8 = _mm256_set1_epi32(128);
+ __m256i z8 = _mm256_sub_epi32(y8, c8); // subtract 128 from all lanes
+ return _mm256_cvtepi32_ps(z8); // 8 * float32
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <>
+struct Quantizer8bitDirectSigned<8> : Quantizer8bitDirectSigned<1> {
+ Quantizer8bitDirectSigned(size_t d, const std::vector<float>& trained)
+ : Quantizer8bitDirectSigned<1>(d, trained) {}
+
+ FAISS_ALWAYS_INLINE float32x4x2_t
+ reconstruct_8_components(const uint8_t* code, int i) const {
+ uint8x8_t x8 = vld1_u8((const uint8_t*)(code + i));
+ uint16x8_t y8 = vmovl_u8(x8); // convert uint8 -> uint16
+ uint16x4_t y8_0 = vget_low_u16(y8);
+ uint16x4_t y8_1 = vget_high_u16(y8);
+
+ float32x4_t z8_0 = vcvtq_f32_u32(
+ vmovl_u16(y8_0)); // convert uint16 -> uint32 -> fp32
+ float32x4_t z8_1 = vcvtq_f32_u32(vmovl_u16(y8_1));
+
+ // subtract 128 to convert into signed numbers
+ return {vsubq_f32(z8_0, vmovq_n_f32(128.0)),
+ vsubq_f32(z8_1, vmovq_n_f32(128.0))};
+ }
+};
+
+#endif
+
+template <int SIMDWIDTH>
+ScalarQuantizer::SQuantizer* select_quantizer_1(
+ QuantizerType qtype,
+ size_t d,
+ const std::vector<float>& trained) {
+ switch (qtype) {
+ case ScalarQuantizer::QT_8bit:
+ return new QuantizerTemplate<
+ Codec8bit,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_6bit:
+ return new QuantizerTemplate<
+ Codec6bit,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_4bit:
+ return new QuantizerTemplate<
+ Codec4bit,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_8bit_uniform:
+ return new QuantizerTemplate<
+ Codec8bit,
+ QuantizerTemplateScaling::UNIFORM,
+ SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_4bit_uniform:
+ return new QuantizerTemplate<
+ Codec4bit,
+ QuantizerTemplateScaling::UNIFORM,
+ SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_fp16:
+ return new QuantizerFP16<SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_bf16:
+ return new QuantizerBF16<SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_8bit_direct:
+ return new Quantizer8bitDirect<SIMDWIDTH>(d, trained);
+ case ScalarQuantizer::QT_8bit_direct_signed:
+ return new Quantizer8bitDirectSigned<SIMDWIDTH>(d, trained);
+ }
+ FAISS_THROW_MSG("unknown qtype");
+}
+
+/*******************************************************************
+ * Quantizer range training
+ */
+
+static float sqr(float x) {
+ return x * x;
+}
+
+void train_Uniform(
+ RangeStat rs,
+ float rs_arg,
+ idx_t n,
+ int k,
+ const float* x,
+ std::vector<float>& trained) {
+ trained.resize(2);
+ float& vmin = trained[0];
+ float& vmax = trained[1];
+
+ if (rs == ScalarQuantizer::RS_minmax) {
+ vmin = HUGE_VAL;
+ vmax = -HUGE_VAL;
+ for (size_t i = 0; i < n; i++) {
+ if (x[i] < vmin)
+ vmin = x[i];
+ if (x[i] > vmax)
+ vmax = x[i];
+ }
+ float vexp = (vmax - vmin) * rs_arg;
+ vmin -= vexp;
+ vmax += vexp;
+ } else if (rs == ScalarQuantizer::RS_meanstd) {
+ double sum = 0, sum2 = 0;
+ for (size_t i = 0; i < n; i++) {
+ sum += x[i];
+ sum2 += x[i] * x[i];
+ }
+ float mean = sum / n;
+ float var = sum2 / n - mean * mean;
+ float std = var <= 0 ? 1.0 : sqrt(var);
+
+ vmin = mean - std * rs_arg;
+ vmax = mean + std * rs_arg;
+ } else if (rs == ScalarQuantizer::RS_quantiles) {
+ std::vector<float> x_copy(n);
+ memcpy(x_copy.data(), x, n * sizeof(*x));
+ // TODO just do a quickselect
+ std::sort(x_copy.begin(), x_copy.end());
+ int o = int(rs_arg * n);
+ if (o < 0)
+ o = 0;
+ if (o > n - o)
+ o = n / 2;
+ vmin = x_copy[o];
+ vmax = x_copy[n - 1 - o];
+
+ } else if (rs == ScalarQuantizer::RS_optim) {
+ float a, b;
+ float sx = 0;
+ {
+ vmin = HUGE_VAL, vmax = -HUGE_VAL;
+ for (size_t i = 0; i < n; i++) {
+ if (x[i] < vmin)
+ vmin = x[i];
+ if (x[i] > vmax)
+ vmax = x[i];
+ sx += x[i];
+ }
+ b = vmin;
+ a = (vmax - vmin) / (k - 1);
+ }
+ int verbose = false;
+ int niter = 2000;
+ float last_err = -1;
+ int iter_last_err = 0;
+ for (int it = 0; it < niter; it++) {
+ float sn = 0, sn2 = 0, sxn = 0, err1 = 0;
+
+ for (idx_t i = 0; i < n; i++) {
+ float xi = x[i];
+ float ni = floor((xi - b) / a + 0.5);
+ if (ni < 0)
+ ni = 0;
+ if (ni >= k)
+ ni = k - 1;
+ err1 += sqr(xi - (ni * a + b));
+ sn += ni;
+ sn2 += ni * ni;
+ sxn += ni * xi;
+ }
+
+ if (err1 == last_err) {
+ iter_last_err++;
+ if (iter_last_err == 16)
+ break;
+ } else {
+ last_err = err1;
+ iter_last_err = 0;
+ }
+
+ float det = sqr(sn) - sn2 * n;
+
+ b = (sn * sxn - sn2 * sx) / det;
+ a = (sn * sx - n * sxn) / det;
+ if (verbose) {
+ printf("it %d, err1=%g \r", it, err1);
+ fflush(stdout);
+ }
+ }
+ if (verbose)
+ printf("\n");
+
+ vmin = b;
+ vmax = b + a * (k - 1);
+
+ } else {
+ FAISS_THROW_MSG("Invalid qtype");
+ }
+ vmax -= vmin;
+}
+
+void train_NonUniform(
+ RangeStat rs,
+ float rs_arg,
+ idx_t n,
+ int d,
+ int k,
+ const float* x,
+ std::vector<float>& trained) {
+ trained.resize(2 * d);
+ float* vmin = trained.data();
+ float* vmax = trained.data() + d;
+ if (rs == ScalarQuantizer::RS_minmax) {
+ memcpy(vmin, x, sizeof(*x) * d);
+ memcpy(vmax, x, sizeof(*x) * d);
+ for (size_t i = 1; i < n; i++) {
+ const float* xi = x + i * d;
+ for (size_t j = 0; j < d; j++) {
+ if (xi[j] < vmin[j])
+ vmin[j] = xi[j];
+ if (xi[j] > vmax[j])
+ vmax[j] = xi[j];
+ }
+ }
+ float* vdiff = vmax;
+ for (size_t j = 0; j < d; j++) {
+ float vexp = (vmax[j] - vmin[j]) * rs_arg;
+ vmin[j] -= vexp;
+ vmax[j] += vexp;
+ vdiff[j] = vmax[j] - vmin[j];
+ }
+ } else {
+ // transpose
+ std::vector<float> xt(n * d);
+ for (size_t i = 1; i < n; i++) {
+ const float* xi = x + i * d;
+ for (size_t j = 0; j < d; j++) {
+ xt[j * n + i] = xi[j];
+ }
+ }
+ std::vector<float> trained_d(2);
+#pragma omp parallel for
+ for (int j = 0; j < d; j++) {
+ train_Uniform(rs, rs_arg, n, k, xt.data() + j * n, trained_d);
+ vmin[j] = trained_d[0];
+ vmax[j] = trained_d[1];
+ }
+ }
+}
+
+/*******************************************************************
+ * Similarity: gets vector components and computes a similarity wrt. a
+ * query vector stored in the object. The data fields just encapsulate
+ * an accumulator.
+ */
+
+template <int SIMDWIDTH>
+struct SimilarityL2 {};
+
+template <>
+struct SimilarityL2<1> {
+ static constexpr int simdwidth = 1;
+ static constexpr MetricType metric_type = METRIC_L2;
+
+ const float *y, *yi;
+
+ explicit SimilarityL2(const float* y) : y(y) {}
+
+ /******* scalar accumulator *******/
+
+ float accu;
+
+ FAISS_ALWAYS_INLINE void begin() {
+ accu = 0;
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_component(float x) {
+ float tmp = *yi++ - x;
+ accu += tmp * tmp;
+ }
+
+ FAISS_ALWAYS_INLINE void add_component_2(float x1, float x2) {
+ float tmp = x1 - x2;
+ accu += tmp * tmp;
+ }
+
+ FAISS_ALWAYS_INLINE float result() {
+ return accu;
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <>
+struct SimilarityL2<16> {
+ static constexpr int simdwidth = 16;
+ static constexpr MetricType metric_type = METRIC_L2;
+
+ const float *y, *yi;
+
+ explicit SimilarityL2(const float* y) : y(y) {}
+ __m512 accu16;
+
+ FAISS_ALWAYS_INLINE void begin_16() {
+ accu16 = _mm512_setzero_ps();
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_16_components(__m512 x) {
+ __m512 yiv = _mm512_loadu_ps(yi);
+ yi += 16;
+ __m512 tmp = _mm512_sub_ps(yiv, x);
+ accu16 = _mm512_fmadd_ps(tmp, tmp, accu16);
+ }
+
+ FAISS_ALWAYS_INLINE void add_16_components_2(__m512 x, __m512 y_2) {
+ __m512 tmp = _mm512_sub_ps(y_2, x);
+ accu16 = _mm512_fmadd_ps(tmp, tmp, accu16);
+ }
+
+ FAISS_ALWAYS_INLINE float result_16() {
+ // performs better than dividing into _mm256 and adding
+ return _mm512_reduce_add_ps(accu16);
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <>
+struct SimilarityL2<8> {
+ static constexpr int simdwidth = 8;
+ static constexpr MetricType metric_type = METRIC_L2;
+
+ const float *y, *yi;
+
+ explicit SimilarityL2(const float* y) : y(y) {}
+ __m256 accu8;
+
+ FAISS_ALWAYS_INLINE void begin_8() {
+ accu8 = _mm256_setzero_ps();
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components(__m256 x) {
+ __m256 yiv = _mm256_loadu_ps(yi);
+ yi += 8;
+ __m256 tmp = _mm256_sub_ps(yiv, x);
+ accu8 = _mm256_fmadd_ps(tmp, tmp, accu8);
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components_2(__m256 x, __m256 y_2) {
+ __m256 tmp = _mm256_sub_ps(y_2, x);
+ accu8 = _mm256_fmadd_ps(tmp, tmp, accu8);
+ }
+
+ FAISS_ALWAYS_INLINE float result_8() {
+ const __m128 sum = _mm_add_ps(
+ _mm256_castps256_ps128(accu8), _mm256_extractf128_ps(accu8, 1));
+ const __m128 v0 = _mm_shuffle_ps(sum, sum, _MM_SHUFFLE(0, 0, 3, 2));
+ const __m128 v1 = _mm_add_ps(sum, v0);
+ __m128 v2 = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(0, 0, 0, 1));
+ const __m128 v3 = _mm_add_ps(v1, v2);
+ return _mm_cvtss_f32(v3);
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+template <>
+struct SimilarityL2<8> {
+ static constexpr int simdwidth = 8;
+ static constexpr MetricType metric_type = METRIC_L2;
+
+ const float *y, *yi;
+ explicit SimilarityL2(const float* y) : y(y) {}
+ float32x4x2_t accu8;
+
+ FAISS_ALWAYS_INLINE void begin_8() {
+ accu8 = {vdupq_n_f32(0.0f), vdupq_n_f32(0.0f)};
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components(float32x4x2_t x) {
+ float32x4x2_t yiv = vld1q_f32_x2(yi);
+ yi += 8;
+
+ float32x4_t sub0 = vsubq_f32(yiv.val[0], x.val[0]);
+ float32x4_t sub1 = vsubq_f32(yiv.val[1], x.val[1]);
+
+ float32x4_t accu8_0 = vfmaq_f32(accu8.val[0], sub0, sub0);
+ float32x4_t accu8_1 = vfmaq_f32(accu8.val[1], sub1, sub1);
+
+ accu8 = {accu8_0, accu8_1};
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components_2(
+ float32x4x2_t x,
+ float32x4x2_t y) {
+ float32x4_t sub0 = vsubq_f32(y.val[0], x.val[0]);
+ float32x4_t sub1 = vsubq_f32(y.val[1], x.val[1]);
+
+ float32x4_t accu8_0 = vfmaq_f32(accu8.val[0], sub0, sub0);
+ float32x4_t accu8_1 = vfmaq_f32(accu8.val[1], sub1, sub1);
+
+ accu8 = {accu8_0, accu8_1};
+ }
+
+ FAISS_ALWAYS_INLINE float result_8() {
+ float32x4_t sum_0 = vpaddq_f32(accu8.val[0], accu8.val[0]);
+ float32x4_t sum_1 = vpaddq_f32(accu8.val[1], accu8.val[1]);
+
+ float32x4_t sum2_0 = vpaddq_f32(sum_0, sum_0);
+ float32x4_t sum2_1 = vpaddq_f32(sum_1, sum_1);
+ return vgetq_lane_f32(sum2_0, 0) + vgetq_lane_f32(sum2_1, 0);
+ }
+};
+#endif
+
+template <int SIMDWIDTH>
+struct SimilarityIP {};
+
+template <>
+struct SimilarityIP<1> {
+ static constexpr int simdwidth = 1;
+ static constexpr MetricType metric_type = METRIC_INNER_PRODUCT;
+ const float *y, *yi;
+
+ float accu;
+
+ explicit SimilarityIP(const float* y) : y(y) {}
+
+ FAISS_ALWAYS_INLINE void begin() {
+ accu = 0;
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_component(float x) {
+ accu += *yi++ * x;
+ }
+
+ FAISS_ALWAYS_INLINE void add_component_2(float x1, float x2) {
+ accu += x1 * x2;
+ }
+
+ FAISS_ALWAYS_INLINE float result() {
+ return accu;
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <>
+struct SimilarityIP<16> {
+ static constexpr int simdwidth = 16;
+ static constexpr MetricType metric_type = METRIC_INNER_PRODUCT;
+
+ const float *y, *yi;
+
+ float accu;
+
+ explicit SimilarityIP(const float* y) : y(y) {}
+
+ __m512 accu16;
+
+ FAISS_ALWAYS_INLINE void begin_16() {
+ accu16 = _mm512_setzero_ps();
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_16_components(__m512 x) {
+ __m512 yiv = _mm512_loadu_ps(yi);
+ yi += 16;
+ accu16 = _mm512_fmadd_ps(yiv, x, accu16);
+ }
+
+ FAISS_ALWAYS_INLINE void add_16_components_2(__m512 x1, __m512 x2) {
+ accu16 = _mm512_fmadd_ps(x1, x2, accu16);
+ }
+
+ FAISS_ALWAYS_INLINE float result_16() {
+ // performs better than dividing into _mm256 and adding
+ return _mm512_reduce_add_ps(accu16);
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <>
+struct SimilarityIP<8> {
+ static constexpr int simdwidth = 8;
+ static constexpr MetricType metric_type = METRIC_INNER_PRODUCT;
+
+ const float *y, *yi;
+
+ float accu;
+
+ explicit SimilarityIP(const float* y) : y(y) {}
+
+ __m256 accu8;
+
+ FAISS_ALWAYS_INLINE void begin_8() {
+ accu8 = _mm256_setzero_ps();
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components(__m256 x) {
+ __m256 yiv = _mm256_loadu_ps(yi);
+ yi += 8;
+ accu8 = _mm256_fmadd_ps(yiv, x, accu8);
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components_2(__m256 x1, __m256 x2) {
+ accu8 = _mm256_fmadd_ps(x1, x2, accu8);
+ }
+
+ FAISS_ALWAYS_INLINE float result_8() {
+ const __m128 sum = _mm_add_ps(
+ _mm256_castps256_ps128(accu8), _mm256_extractf128_ps(accu8, 1));
+ const __m128 v0 = _mm_shuffle_ps(sum, sum, _MM_SHUFFLE(0, 0, 3, 2));
+ const __m128 v1 = _mm_add_ps(sum, v0);
+ __m128 v2 = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(0, 0, 0, 1));
+ const __m128 v3 = _mm_add_ps(v1, v2);
+ return _mm_cvtss_f32(v3);
+ }
+};
+#endif
+
+#ifdef USE_NEON
+
+template <>
+struct SimilarityIP<8> {
+ static constexpr int simdwidth = 8;
+ static constexpr MetricType metric_type = METRIC_INNER_PRODUCT;
+
+ const float *y, *yi;
+
+ explicit SimilarityIP(const float* y) : y(y) {}
+ float32x4x2_t accu8;
+
+ FAISS_ALWAYS_INLINE void begin_8() {
+ accu8 = {vdupq_n_f32(0.0f), vdupq_n_f32(0.0f)};
+ yi = y;
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components(float32x4x2_t x) {
+ float32x4x2_t yiv = vld1q_f32_x2(yi);
+ yi += 8;
+
+ float32x4_t accu8_0 = vfmaq_f32(accu8.val[0], yiv.val[0], x.val[0]);
+ float32x4_t accu8_1 = vfmaq_f32(accu8.val[1], yiv.val[1], x.val[1]);
+ accu8 = {accu8_0, accu8_1};
+ }
+
+ FAISS_ALWAYS_INLINE void add_8_components_2(
+ float32x4x2_t x1,
+ float32x4x2_t x2) {
+ float32x4_t accu8_0 = vfmaq_f32(accu8.val[0], x1.val[0], x2.val[0]);
+ float32x4_t accu8_1 = vfmaq_f32(accu8.val[1], x1.val[1], x2.val[1]);
+ accu8 = {accu8_0, accu8_1};
+ }
+
+ FAISS_ALWAYS_INLINE float result_8() {
+ float32x4x2_t sum = {
+ vpaddq_f32(accu8.val[0], accu8.val[0]),
+ vpaddq_f32(accu8.val[1], accu8.val[1])};
+
+ float32x4x2_t sum2 = {
+ vpaddq_f32(sum.val[0], sum.val[0]),
+ vpaddq_f32(sum.val[1], sum.val[1])};
+ return vgetq_lane_f32(sum2.val[0], 0) + vgetq_lane_f32(sum2.val[1], 0);
+ }
+};
+#endif
+
+/*******************************************************************
+ * DistanceComputer: combines a similarity and a quantizer to do
+ * code-to-vector or code-to-code comparisons
+ *******************************************************************/
+
+template <class Quantizer, class Similarity, int SIMDWIDTH>
+struct DCTemplate : SQDistanceComputer {};
+
+template <class Quantizer, class Similarity>
+struct DCTemplate<Quantizer, Similarity, 1> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ Quantizer quant;
+
+ DCTemplate(size_t d, const std::vector<float>& trained)
+ : quant(d, trained) {}
+
+ float compute_distance(const float* x, const uint8_t* code) const {
+ Similarity sim(x);
+ sim.begin();
+ for (size_t i = 0; i < quant.d; i++) {
+ float xi = quant.reconstruct_component(code, i);
+ sim.add_component(xi);
+ }
+ return sim.result();
+ }
+
+ float compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ Similarity sim(nullptr);
+ sim.begin();
+ for (size_t i = 0; i < quant.d; i++) {
+ float x1 = quant.reconstruct_component(code1, i);
+ float x2 = quant.reconstruct_component(code2, i);
+ sim.add_component_2(x1, x2);
+ }
+ return sim.result();
+ }
+
+ void set_query(const float* x) final {
+ q = x;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_distance(q, code);
+ }
+};
+
+#if defined(USE_AVX512_F16C)
+
+template <class Quantizer, class Similarity>
+struct DCTemplate<Quantizer, Similarity, 16>
+ : SQDistanceComputer { // Update to handle 16 lanes
+ using Sim = Similarity;
+
+ Quantizer quant;
+
+ DCTemplate(size_t d, const std::vector<float>& trained)
+ : quant(d, trained) {}
+
+ float compute_distance(const float* x, const uint8_t* code) const {
+ Similarity sim(x);
+ sim.begin_16();
+ for (size_t i = 0; i < quant.d; i += 16) {
+ __m512 xi = quant.reconstruct_16_components(code, i);
+ sim.add_16_components(xi);
+ }
+ return sim.result_16();
+ }
+
+ float compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ Similarity sim(nullptr);
+ sim.begin_16();
+ for (size_t i = 0; i < quant.d; i += 16) {
+ __m512 x1 = quant.reconstruct_16_components(code1, i);
+ __m512 x2 = quant.reconstruct_16_components(code2, i);
+ sim.add_16_components_2(x1, x2);
+ }
+ return sim.result_16();
+ }
+
+ void set_query(const float* x) final {
+ q = x;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_distance(q, code);
+ }
+};
+
+#elif defined(USE_F16C)
+
+template <class Quantizer, class Similarity>
+struct DCTemplate<Quantizer, Similarity, 8> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ Quantizer quant;
+
+ DCTemplate(size_t d, const std::vector<float>& trained)
+ : quant(d, trained) {}
+
+ float compute_distance(const float* x, const uint8_t* code) const {
+ Similarity sim(x);
+ sim.begin_8();
+ for (size_t i = 0; i < quant.d; i += 8) {
+ __m256 xi = quant.reconstruct_8_components(code, i);
+ sim.add_8_components(xi);
+ }
+ return sim.result_8();
+ }
+
+ float compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ Similarity sim(nullptr);
+ sim.begin_8();
+ for (size_t i = 0; i < quant.d; i += 8) {
+ __m256 x1 = quant.reconstruct_8_components(code1, i);
+ __m256 x2 = quant.reconstruct_8_components(code2, i);
+ sim.add_8_components_2(x1, x2);
+ }
+ return sim.result_8();
+ }
+
+ void set_query(const float* x) final {
+ q = x;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_distance(q, code);
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <class Quantizer, class Similarity>
+struct DCTemplate<Quantizer, Similarity, 8> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ Quantizer quant;
+
+ DCTemplate(size_t d, const std::vector<float>& trained)
+ : quant(d, trained) {}
+ float compute_distance(const float* x, const uint8_t* code) const {
+ Similarity sim(x);
+ sim.begin_8();
+ for (size_t i = 0; i < quant.d; i += 8) {
+ float32x4x2_t xi = quant.reconstruct_8_components(code, i);
+ sim.add_8_components(xi);
+ }
+ return sim.result_8();
+ }
+
+ float compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ Similarity sim(nullptr);
+ sim.begin_8();
+ for (size_t i = 0; i < quant.d; i += 8) {
+ float32x4x2_t x1 = quant.reconstruct_8_components(code1, i);
+ float32x4x2_t x2 = quant.reconstruct_8_components(code2, i);
+ sim.add_8_components_2(x1, x2);
+ }
+ return sim.result_8();
+ }
+
+ void set_query(const float* x) final {
+ q = x;
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_distance(q, code);
+ }
+};
+#endif
+
+/*******************************************************************
+ * DistanceComputerByte: computes distances in the integer domain
+ *******************************************************************/
+
+template <class Similarity, int SIMDWIDTH>
+struct DistanceComputerByte : SQDistanceComputer {};
+
+template <class Similarity>
+struct DistanceComputerByte<Similarity, 1> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ int d;
+ std::vector<uint8_t> tmp;
+
+ DistanceComputerByte(int d, const std::vector<float>&) : d(d), tmp(d) {}
+
+ int compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ int accu = 0;
+ for (int i = 0; i < d; i++) {
+ if (Sim::metric_type == METRIC_INNER_PRODUCT) {
+ accu += int(code1[i]) * code2[i];
+ } else {
+ int diff = int(code1[i]) - code2[i];
+ accu += diff * diff;
+ }
+ }
+ return accu;
+ }
+
+ void set_query(const float* x) final {
+ for (int i = 0; i < d; i++) {
+ tmp[i] = int(x[i]);
+ }
+ }
+
+ int compute_distance(const float* x, const uint8_t* code) {
+ set_query(x);
+ return compute_code_distance(tmp.data(), code);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_code_distance(tmp.data(), code);
+ }
+};
+
+#if defined(__AVX512F__)
+
+template <class Similarity>
+struct DistanceComputerByte<Similarity, 16> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ int d;
+ std::vector<uint8_t> tmp;
+
+ DistanceComputerByte(int d, const std::vector<float>&) : d(d), tmp(d) {}
+
+ int compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ __m512i accu = _mm512_setzero_si512();
+ for (int i = 0; i < d; i += 32) { // Process 32 bytes at a time
+ __m512i c1 = _mm512_cvtepu8_epi16(
+ _mm256_loadu_si256((__m256i*)(code1 + i)));
+ __m512i c2 = _mm512_cvtepu8_epi16(
+ _mm256_loadu_si256((__m256i*)(code2 + i)));
+ __m512i prod32;
+ if (Sim::metric_type == METRIC_INNER_PRODUCT) {
+ prod32 = _mm512_madd_epi16(c1, c2);
+ } else {
+ __m512i diff = _mm512_sub_epi16(c1, c2);
+ prod32 = _mm512_madd_epi16(diff, diff);
+ }
+ accu = _mm512_add_epi32(accu, prod32);
+ }
+ // Horizontally add elements of accu
+ return _mm512_reduce_add_epi32(accu);
+ }
+
+ void set_query(const float* x) final {
+ for (int i = 0; i < d; i++) {
+ tmp[i] = int(x[i]);
+ }
+ }
+
+ int compute_distance(const float* x, const uint8_t* code) {
+ set_query(x);
+ return compute_code_distance(tmp.data(), code);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_code_distance(tmp.data(), code);
+ }
+};
+
+#elif defined(__AVX2__)
+
+template <class Similarity>
+struct DistanceComputerByte<Similarity, 8> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ int d;
+ std::vector<uint8_t> tmp;
+
+ DistanceComputerByte(int d, const std::vector<float>&) : d(d), tmp(d) {}
+
+ int compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ // __m256i accu = _mm256_setzero_ps ();
+ __m256i accu = _mm256_setzero_si256();
+ for (int i = 0; i < d; i += 16) {
+ // load 16 bytes, convert to 16 uint16_t
+ __m256i c1 = _mm256_cvtepu8_epi16(
+ _mm_loadu_si128((__m128i*)(code1 + i)));
+ __m256i c2 = _mm256_cvtepu8_epi16(
+ _mm_loadu_si128((__m128i*)(code2 + i)));
+ __m256i prod32;
+ if (Sim::metric_type == METRIC_INNER_PRODUCT) {
+ prod32 = _mm256_madd_epi16(c1, c2);
+ } else {
+ __m256i diff = _mm256_sub_epi16(c1, c2);
+ prod32 = _mm256_madd_epi16(diff, diff);
+ }
+ accu = _mm256_add_epi32(accu, prod32);
+ }
+ __m128i sum = _mm256_extractf128_si256(accu, 0);
+ sum = _mm_add_epi32(sum, _mm256_extractf128_si256(accu, 1));
+ sum = _mm_hadd_epi32(sum, sum);
+ sum = _mm_hadd_epi32(sum, sum);
+ return _mm_cvtsi128_si32(sum);
+ }
+
+ void set_query(const float* x) final {
+ /*
+ for (int i = 0; i < d; i += 8) {
+ __m256 xi = _mm256_loadu_ps (x + i);
+ __m256i ci = _mm256_cvtps_epi32(xi);
+ */
+ for (int i = 0; i < d; i++) {
+ tmp[i] = int(x[i]);
+ }
+ }
+
+ int compute_distance(const float* x, const uint8_t* code) {
+ set_query(x);
+ return compute_code_distance(tmp.data(), code);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_code_distance(tmp.data(), code);
+ }
+};
+
+#endif
+
+#ifdef USE_NEON
+
+template <class Similarity>
+struct DistanceComputerByte<Similarity, 8> : SQDistanceComputer {
+ using Sim = Similarity;
+
+ int d;
+ std::vector<uint8_t> tmp;
+
+ DistanceComputerByte(int d, const std::vector<float>&) : d(d), tmp(d) {}
+
+ int compute_code_distance(const uint8_t* code1, const uint8_t* code2)
+ const {
+ int accu = 0;
+ for (int i = 0; i < d; i++) {
+ if (Sim::metric_type == METRIC_INNER_PRODUCT) {
+ accu += int(code1[i]) * code2[i];
+ } else {
+ int diff = int(code1[i]) - code2[i];
+ accu += diff * diff;
+ }
+ }
+ return accu;
+ }
+
+ void set_query(const float* x) final {
+ for (int i = 0; i < d; i++) {
+ tmp[i] = int(x[i]);
+ }
+ }
+
+ int compute_distance(const float* x, const uint8_t* code) {
+ set_query(x);
+ return compute_code_distance(tmp.data(), code);
+ }
+
+ float symmetric_dis(idx_t i, idx_t j) override {
+ return compute_code_distance(
+ codes + i * code_size, codes + j * code_size);
+ }
+
+ float query_to_code(const uint8_t* code) const final {
+ return compute_code_distance(tmp.data(), code);
+ }
+};
+
+#endif
+
+/*******************************************************************
+ * select_distance_computer: runtime selection of template
+ * specialization
+ *******************************************************************/
+
+template <class Sim>
+SQDistanceComputer* select_distance_computer(
+ QuantizerType qtype,
+ size_t d,
+ const std::vector<float>& trained) {
+ constexpr int SIMDWIDTH = Sim::simdwidth;
+ switch (qtype) {
+ case ScalarQuantizer::QT_8bit_uniform:
+ return new DCTemplate<
+ QuantizerTemplate<
+ Codec8bit,
+ QuantizerTemplateScaling::UNIFORM,
+ SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+
+ case ScalarQuantizer::QT_4bit_uniform:
+ return new DCTemplate<
+ QuantizerTemplate<
+ Codec4bit,
+ QuantizerTemplateScaling::UNIFORM,
+ SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+
+ case ScalarQuantizer::QT_8bit:
+ return new DCTemplate<
+ QuantizerTemplate<
+ Codec8bit,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+
+ case ScalarQuantizer::QT_6bit:
+ return new DCTemplate<
+ QuantizerTemplate<
+ Codec6bit,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+
+ case ScalarQuantizer::QT_4bit:
+ return new DCTemplate<
+ QuantizerTemplate<
+ Codec4bit,
+ QuantizerTemplateScaling::NON_UNIFORM,
+ SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+
+ case ScalarQuantizer::QT_fp16:
+ return new DCTemplate<QuantizerFP16<SIMDWIDTH>, Sim, SIMDWIDTH>(
+ d, trained);
+
+ case ScalarQuantizer::QT_bf16:
+ return new DCTemplate<QuantizerBF16<SIMDWIDTH>, Sim, SIMDWIDTH>(
+ d, trained);
+
+ case ScalarQuantizer::QT_8bit_direct:
+#if defined(__AVX512F__)
+ if (d % 32 == 0) {
+ return new DistanceComputerByte<Sim, SIMDWIDTH>(d, trained);
+ } else
+#elif defined(__AVX2__)
+ if (d % 16 == 0) {
+ return new DistanceComputerByte<Sim, SIMDWIDTH>(d, trained);
+ } else
+#endif
+ {
+ return new DCTemplate<
+ Quantizer8bitDirect<SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+ }
+ case ScalarQuantizer::QT_8bit_direct_signed:
+ return new DCTemplate<
+ Quantizer8bitDirectSigned<SIMDWIDTH>,
+ Sim,
+ SIMDWIDTH>(d, trained);
+ }
+ FAISS_THROW_MSG("unknown qtype");
+ return nullptr;
+}
+
+} // anonymous namespace
+
+/*******************************************************************
+ * ScalarQuantizer implementation
+ ********************************************************************/
+
+ScalarQuantizer::ScalarQuantizer(size_t d, QuantizerType qtype)
+ : Quantizer(d), qtype(qtype) {
+ set_derived_sizes();
+}
+
+ScalarQuantizer::ScalarQuantizer() {}
+
+void ScalarQuantizer::set_derived_sizes() {
+ switch (qtype) {
+ case QT_8bit:
+ case QT_8bit_uniform:
+ case QT_8bit_direct:
+ case QT_8bit_direct_signed:
+ code_size = d;
+ bits = 8;
+ break;
+ case QT_4bit:
+ case QT_4bit_uniform:
+ code_size = (d + 1) / 2;
+ bits = 4;
+ break;
+ case QT_6bit:
+ code_size = (d * 6 + 7) / 8;
+ bits = 6;
+ break;
+ case QT_fp16:
+ code_size = d * 2;
+ bits = 16;
+ break;
+ case QT_bf16:
+ code_size = d * 2;
+ bits = 16;
+ break;
+ }
+}
+
+void ScalarQuantizer::train(size_t n, const float* x) {
+ int bit_per_dim = qtype == QT_4bit_uniform ? 4
+ : qtype == QT_4bit ? 4
+ : qtype == QT_6bit ? 6
+ : qtype == QT_8bit_uniform ? 8
+ : qtype == QT_8bit ? 8
+ : -1;
+
+ switch (qtype) {
+ case QT_4bit_uniform:
+ case QT_8bit_uniform:
+ train_Uniform(
+ rangestat,
+ rangestat_arg,
+ n * d,
+ 1 << bit_per_dim,
+ x,
+ trained);
+ break;
+ case QT_4bit:
+ case QT_8bit:
+ case QT_6bit:
+ train_NonUniform(
+ rangestat,
+ rangestat_arg,
+ n,
+ d,
+ 1 << bit_per_dim,
+ x,
+ trained);
+ break;
+ case QT_fp16:
+ case QT_8bit_direct:
+ case QT_bf16:
+ case QT_8bit_direct_signed:
+ // no training necessary
+ break;
+ }
+}
+
+ScalarQuantizer::SQuantizer* ScalarQuantizer::select_quantizer() const {
+#if defined(USE_AVX512_F16C)
+ if (d % 16 == 0) {
+ return select_quantizer_1<16>(qtype, d, trained);
+ } else
+#elif defined(USE_F16C) || defined(USE_NEON)
+ if (d % 8 == 0) {
+ return select_quantizer_1<8>(qtype, d, trained);
+ } else
+#endif
+ {
+ return select_quantizer_1<1>(qtype, d, trained);
+ }
+}
+
+void ScalarQuantizer::compute_codes(const float* x, uint8_t* codes, size_t n)
+ const {
+ std::unique_ptr<SQuantizer> squant(select_quantizer());
+
+ memset(codes, 0, code_size * n);
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++)
+ squant->encode_vector(x + i * d, codes + i * code_size);
+}
+
+void ScalarQuantizer::decode(const uint8_t* codes, float* x, size_t n) const {
+ std::unique_ptr<SQuantizer> squant(select_quantizer());
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++)
+ squant->decode_vector(codes + i * code_size, x + i * d);
+}
+
+SQDistanceComputer* ScalarQuantizer::get_distance_computer(
+ MetricType metric) const {
+ FAISS_THROW_IF_NOT(metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT);
+#if defined(USE_AVX512_F16C)
+ if (d % 16 == 0) {
+ if (metric == METRIC_L2) {
+ return select_distance_computer<SimilarityL2<16>>(
+ qtype, d, trained);
+ } else {
+ return select_distance_computer<SimilarityIP<16>>(
+ qtype, d, trained);
+ }
+ } else
+#elif defined(USE_F16C) || defined(USE_NEON)
+ if (d % 8 == 0) {
+ if (metric == METRIC_L2) {
+ return select_distance_computer<SimilarityL2<8>>(qtype, d, trained);
+ } else {
+ return select_distance_computer<SimilarityIP<8>>(qtype, d, trained);
+ }
+ } else
+#endif
+ {
+ if (metric == METRIC_L2) {
+ return select_distance_computer<SimilarityL2<1>>(qtype, d, trained);
+ } else {
+ return select_distance_computer<SimilarityIP<1>>(qtype, d, trained);
+ }
+ }
+}
+
+/*******************************************************************
+ * IndexScalarQuantizer/IndexIVFScalarQuantizer scanner object
+ *
+ * It is an InvertedListScanner, but is designed to work with
+ * IndexScalarQuantizer as well.
+ ********************************************************************/
+
+namespace {
+
+template <class DCClass, int use_sel>
+struct IVFSQScannerIP : InvertedListScanner {
+ DCClass dc;
+ bool by_residual;
+
+ float accu0; /// added to all distances
+
+ IVFSQScannerIP(
+ int d,
+ const std::vector<float>& trained,
+ size_t code_size,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool by_residual)
+ : dc(d, trained), by_residual(by_residual), accu0(0) {
+ this->store_pairs = store_pairs;
+ this->sel = sel;
+ this->code_size = code_size;
+ this->keep_max = true;
+ }
+
+ void set_query(const float* query) override {
+ dc.set_query(query);
+ }
+
+ void set_list(idx_t list_no, float coarse_dis) override {
+ this->list_no = list_no;
+ accu0 = by_residual ? coarse_dis : 0;
+ }
+
+ float distance_to_code(const uint8_t* code) const final {
+ return accu0 + dc.query_to_code(code);
+ }
+
+ size_t scan_codes(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* simi,
+ idx_t* idxi,
+ size_t k) const override {
+ size_t nup = 0;
+
+ for (size_t j = 0; j < list_size; j++, codes += code_size) {
+ if (use_sel && !sel->is_member(use_sel == 1 ? ids[j] : j)) {
+ continue;
+ }
+
+ float accu = accu0 + dc.query_to_code(codes);
+
+ if (accu > simi[0]) {
+ int64_t id = store_pairs ? (list_no << 32 | j) : ids[j];
+ minheap_replace_top(k, simi, idxi, accu, id);
+ nup++;
+ }
+ }
+ return nup;
+ }
+
+ void scan_codes_range(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& res) const override {
+ for (size_t j = 0; j < list_size; j++, codes += code_size) {
+ if (use_sel && !sel->is_member(use_sel == 1 ? ids[j] : j)) {
+ continue;
+ }
+
+ float accu = accu0 + dc.query_to_code(codes);
+ if (accu > radius) {
+ int64_t id = store_pairs ? (list_no << 32 | j) : ids[j];
+ res.add(accu, id);
+ }
+ }
+ }
+};
+
+/* use_sel = 0: don't check selector
+ * = 1: check on ids[j]
+ * = 2: check in j directly (normally ids is nullptr and store_pairs)
+ */
+template <class DCClass, int use_sel>
+struct IVFSQScannerL2 : InvertedListScanner {
+ DCClass dc;
+
+ bool by_residual;
+ const Index* quantizer;
+ const float* x; /// current query
+
+ std::vector<float> tmp;
+
+ IVFSQScannerL2(
+ int d,
+ const std::vector<float>& trained,
+ size_t code_size,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool by_residual)
+ : dc(d, trained),
+ by_residual(by_residual),
+ quantizer(quantizer),
+ x(nullptr),
+ tmp(d) {
+ this->store_pairs = store_pairs;
+ this->sel = sel;
+ this->code_size = code_size;
+ }
+
+ void set_query(const float* query) override {
+ x = query;
+ if (!quantizer) {
+ dc.set_query(query);
+ }
+ }
+
+ void set_list(idx_t list_no, float /*coarse_dis*/) override {
+ this->list_no = list_no;
+ if (by_residual) {
+ // shift of x_in wrt centroid
+ quantizer->compute_residual(x, tmp.data(), list_no);
+ dc.set_query(tmp.data());
+ } else {
+ dc.set_query(x);
+ }
+ }
+
+ float distance_to_code(const uint8_t* code) const final {
+ return dc.query_to_code(code);
+ }
+
+ size_t scan_codes(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float* simi,
+ idx_t* idxi,
+ size_t k) const override {
+ size_t nup = 0;
+ for (size_t j = 0; j < list_size; j++, codes += code_size) {
+ if (use_sel && !sel->is_member(use_sel == 1 ? ids[j] : j)) {
+ continue;
+ }
+
+ float dis = dc.query_to_code(codes);
+
+ if (dis < simi[0]) {
+ int64_t id = store_pairs ? (list_no << 32 | j) : ids[j];
+ maxheap_replace_top(k, simi, idxi, dis, id);
+ nup++;
+ }
+ }
+ return nup;
+ }
+
+ void scan_codes_range(
+ size_t list_size,
+ const uint8_t* codes,
+ const idx_t* ids,
+ float radius,
+ RangeQueryResult& res) const override {
+ for (size_t j = 0; j < list_size; j++, codes += code_size) {
+ if (use_sel && !sel->is_member(use_sel == 1 ? ids[j] : j)) {
+ continue;
+ }
+
+ float dis = dc.query_to_code(codes);
+ if (dis < radius) {
+ int64_t id = store_pairs ? (list_no << 32 | j) : ids[j];
+ res.add(dis, id);
+ }
+ }
+ }
+};
+
+template <class DCClass, int use_sel>
+InvertedListScanner* sel3_InvertedListScanner(
+ const ScalarQuantizer* sq,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool r) {
+ if (DCClass::Sim::metric_type == METRIC_L2) {
+ return new IVFSQScannerL2<DCClass, use_sel>(
+ sq->d,
+ sq->trained,
+ sq->code_size,
+ quantizer,
+ store_pairs,
+ sel,
+ r);
+ } else if (DCClass::Sim::metric_type == METRIC_INNER_PRODUCT) {
+ return new IVFSQScannerIP<DCClass, use_sel>(
+ sq->d, sq->trained, sq->code_size, store_pairs, sel, r);
+ } else {
+ FAISS_THROW_MSG("unsupported metric type");
+ }
+}
+
+template <class DCClass>
+InvertedListScanner* sel2_InvertedListScanner(
+ const ScalarQuantizer* sq,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool r) {
+ if (sel) {
+ if (store_pairs) {
+ return sel3_InvertedListScanner<DCClass, 2>(
+ sq, quantizer, store_pairs, sel, r);
+ } else {
+ return sel3_InvertedListScanner<DCClass, 1>(
+ sq, quantizer, store_pairs, sel, r);
+ }
+ } else {
+ return sel3_InvertedListScanner<DCClass, 0>(
+ sq, quantizer, store_pairs, sel, r);
+ }
+}
+
+template <class Similarity, class Codec, QuantizerTemplateScaling SCALING>
+InvertedListScanner* sel12_InvertedListScanner(
+ const ScalarQuantizer* sq,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool r) {
+ constexpr int SIMDWIDTH = Similarity::simdwidth;
+ using QuantizerClass = QuantizerTemplate<Codec, SCALING, SIMDWIDTH>;
+ using DCClass = DCTemplate<QuantizerClass, Similarity, SIMDWIDTH>;
+ return sel2_InvertedListScanner<DCClass>(
+ sq, quantizer, store_pairs, sel, r);
+}
+
+template <class Similarity>
+InvertedListScanner* sel1_InvertedListScanner(
+ const ScalarQuantizer* sq,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool r) {
+ constexpr int SIMDWIDTH = Similarity::simdwidth;
+ switch (sq->qtype) {
+ case ScalarQuantizer::QT_8bit_uniform:
+ return sel12_InvertedListScanner<
+ Similarity,
+ Codec8bit,
+ QuantizerTemplateScaling::UNIFORM>(
+ sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_4bit_uniform:
+ return sel12_InvertedListScanner<
+ Similarity,
+ Codec4bit,
+ QuantizerTemplateScaling::UNIFORM>(
+ sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_8bit:
+ return sel12_InvertedListScanner<
+ Similarity,
+ Codec8bit,
+ QuantizerTemplateScaling::NON_UNIFORM>(
+ sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_4bit:
+ return sel12_InvertedListScanner<
+ Similarity,
+ Codec4bit,
+ QuantizerTemplateScaling::NON_UNIFORM>(
+ sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_6bit:
+ return sel12_InvertedListScanner<
+ Similarity,
+ Codec6bit,
+ QuantizerTemplateScaling::NON_UNIFORM>(
+ sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_fp16:
+ return sel2_InvertedListScanner<DCTemplate<
+ QuantizerFP16<SIMDWIDTH>,
+ Similarity,
+ SIMDWIDTH>>(sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_bf16:
+ return sel2_InvertedListScanner<DCTemplate<
+ QuantizerBF16<SIMDWIDTH>,
+ Similarity,
+ SIMDWIDTH>>(sq, quantizer, store_pairs, sel, r);
+ case ScalarQuantizer::QT_8bit_direct:
+#if defined(__AVX512F__)
+ if (sq->d % 32 == 0) {
+ return sel2_InvertedListScanner<
+ DistanceComputerByte<Similarity, SIMDWIDTH>>(
+ sq, quantizer, store_pairs, sel, r);
+ } else
+#elif defined(__AVX2__)
+ if (sq->d % 16 == 0) {
+ return sel2_InvertedListScanner<
+ DistanceComputerByte<Similarity, SIMDWIDTH>>(
+ sq, quantizer, store_pairs, sel, r);
+ } else
+#endif
+ {
+ return sel2_InvertedListScanner<DCTemplate<
+ Quantizer8bitDirect<SIMDWIDTH>,
+ Similarity,
+ SIMDWIDTH>>(sq, quantizer, store_pairs, sel, r);
+ }
+ case ScalarQuantizer::QT_8bit_direct_signed:
+ return sel2_InvertedListScanner<DCTemplate<
+ Quantizer8bitDirectSigned<SIMDWIDTH>,
+ Similarity,
+ SIMDWIDTH>>(sq, quantizer, store_pairs, sel, r);
+ }
+
+ FAISS_THROW_MSG("unknown qtype");
+ return nullptr;
+}
+
+template <int SIMDWIDTH>
+InvertedListScanner* sel0_InvertedListScanner(
+ MetricType mt,
+ const ScalarQuantizer* sq,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool by_residual) {
+ if (mt == METRIC_L2) {
+ return sel1_InvertedListScanner<SimilarityL2<SIMDWIDTH>>(
+ sq, quantizer, store_pairs, sel, by_residual);
+ } else if (mt == METRIC_INNER_PRODUCT) {
+ return sel1_InvertedListScanner<SimilarityIP<SIMDWIDTH>>(
+ sq, quantizer, store_pairs, sel, by_residual);
+ } else {
+ FAISS_THROW_MSG("unsupported metric type");
+ }
+}
+
+} // anonymous namespace
+
+InvertedListScanner* ScalarQuantizer::select_InvertedListScanner(
+ MetricType mt,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool by_residual) const {
+#if defined(USE_AVX512_F16C)
+ if (d % 16 == 0) {
+ return sel0_InvertedListScanner<16>(
+ mt, this, quantizer, store_pairs, sel, by_residual);
+ } else
+#elif defined(USE_F16C) || defined(USE_NEON)
+ if (d % 8 == 0) {
+ return sel0_InvertedListScanner<8>(
+ mt, this, quantizer, store_pairs, sel, by_residual);
+ } else
+#endif
+ {
+ return sel0_InvertedListScanner<1>(
+ mt, this, quantizer, store_pairs, sel, by_residual);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ScalarQuantizer.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ScalarQuantizer.h
new file mode 100644
index 0000000..c1f4f98
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ScalarQuantizer.h
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#pragma once
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/Quantizer.h>
+
+namespace faiss {
+
+struct InvertedListScanner;
+
+/**
+ * The uniform quantizer has a range [vmin, vmax]. The range can be
+ * the same for all dimensions (uniform) or specific per dimension
+ * (default).
+ */
+
+struct ScalarQuantizer : Quantizer {
+ enum QuantizerType {
+ QT_8bit, ///< 8 bits per component
+ QT_4bit, ///< 4 bits per component
+ QT_8bit_uniform, ///< same, shared range for all dimensions
+ QT_4bit_uniform,
+ QT_fp16,
+ QT_8bit_direct, ///< fast indexing of uint8s
+ QT_6bit, ///< 6 bits per component
+ QT_bf16,
+ QT_8bit_direct_signed, ///< fast indexing of signed int8s ranging from
+ ///< [-128 to 127]
+ };
+
+ QuantizerType qtype = QT_8bit;
+
+ /** The uniform encoder can estimate the range of representable
+ * values of the unform encoder using different statistics. Here
+ * rs = rangestat_arg */
+
+ // rangestat_arg.
+ enum RangeStat {
+ RS_minmax, ///< [min - rs*(max-min), max + rs*(max-min)]
+ RS_meanstd, ///< [mean - std * rs, mean + std * rs]
+ RS_quantiles, ///< [Q(rs), Q(1-rs)]
+ RS_optim, ///< alternate optimization of reconstruction error
+ };
+
+ RangeStat rangestat = RS_minmax;
+ float rangestat_arg = 0;
+
+ /// bits per scalar code
+ size_t bits = 0;
+
+ /// trained values (including the range)
+ std::vector<float> trained;
+
+ ScalarQuantizer(size_t d, QuantizerType qtype);
+ ScalarQuantizer();
+
+ /// updates internal values based on qtype and d
+ void set_derived_sizes();
+
+ void train(size_t n, const float* x) override;
+
+ /** Encode a set of vectors
+ *
+ * @param x vectors to encode, size n * d
+ * @param codes output codes, size n * code_size
+ */
+ void compute_codes(const float* x, uint8_t* codes, size_t n) const override;
+
+ /** Decode a set of vectors
+ *
+ * @param codes codes to decode, size n * code_size
+ * @param x output vectors, size n * d
+ */
+ void decode(const uint8_t* code, float* x, size_t n) const override;
+
+ /*****************************************************
+ * Objects that provide methods for encoding/decoding, distance
+ * computation and inverted list scanning
+ *****************************************************/
+
+ struct SQuantizer {
+ // encodes one vector. Assumes code is filled with 0s on input!
+ virtual void encode_vector(const float* x, uint8_t* code) const = 0;
+ virtual void decode_vector(const uint8_t* code, float* x) const = 0;
+
+ virtual ~SQuantizer() {}
+ };
+
+ SQuantizer* select_quantizer() const;
+
+ struct SQDistanceComputer : FlatCodesDistanceComputer {
+ const float* q;
+
+ SQDistanceComputer() : q(nullptr) {}
+
+ virtual float query_to_code(const uint8_t* code) const = 0;
+
+ float distance_to_code(const uint8_t* code) final {
+ return query_to_code(code);
+ }
+ };
+
+ SQDistanceComputer* get_distance_computer(
+ MetricType metric = METRIC_L2) const;
+
+ InvertedListScanner* select_InvertedListScanner(
+ MetricType mt,
+ const Index* quantizer,
+ bool store_pairs,
+ const IDSelector* sel,
+ bool by_residual = false) const;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ThreadedIndex-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ThreadedIndex-inl.h
new file mode 100644
index 0000000..38a4ff3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ThreadedIndex-inl.h
@@ -0,0 +1,190 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <exception>
+#include <iostream>
+
+namespace faiss {
+
+template <typename IndexT>
+ThreadedIndex<IndexT>::ThreadedIndex(bool threaded)
+ // 0 is default dimension
+ : ThreadedIndex(0, threaded) {}
+
+template <typename IndexT>
+ThreadedIndex<IndexT>::ThreadedIndex(int d, bool threaded)
+ : IndexT(d), isThreaded_(threaded) {}
+
+template <typename IndexT>
+ThreadedIndex<IndexT>::~ThreadedIndex() {
+ for (auto& p : indices_) {
+ if (isThreaded_) {
+ // should have worker thread
+ FAISS_ASSERT((bool)p.second);
+
+ // This will also flush all pending work
+ p.second->stop();
+ p.second->waitForThreadExit();
+ } else {
+ // should not have worker thread
+ FAISS_ASSERT(!(bool)p.second);
+ }
+
+ if (own_indices) {
+ delete p.first;
+ }
+ }
+}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::addIndex(IndexT* index) {
+ // We inherit the dimension from the first index added to us if we don't
+ // have a set dimension
+ if (indices_.empty() && this->d == 0) {
+ this->d = index->d;
+ }
+
+ // The new index must match our set dimension
+ FAISS_THROW_IF_NOT_FMT(
+ this->d == index->d,
+ "addIndex: dimension mismatch for "
+ "newly added index; expecting dim %d, "
+ "new index has dim %d",
+ this->d,
+ index->d);
+
+ if (!indices_.empty()) {
+ auto& existing = indices_.front().first;
+
+ FAISS_THROW_IF_NOT_MSG(
+ index->metric_type == existing->metric_type,
+ "addIndex: newly added index is "
+ "of different metric type than old index");
+
+ // Make sure this index is not duplicated
+ for (auto& p : indices_) {
+ FAISS_THROW_IF_NOT_MSG(
+ p.first != index,
+ "addIndex: attempting to add index "
+ "that is already in the collection");
+ }
+ }
+
+ indices_.emplace_back(std::make_pair(
+ index,
+ std::unique_ptr<WorkerThread>(
+ isThreaded_ ? new WorkerThread : nullptr)));
+
+ onAfterAddIndex(index);
+}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::removeIndex(IndexT* index) {
+ for (auto it = indices_.begin(); it != indices_.end(); ++it) {
+ if (it->first == index) {
+ // This is our index; stop the worker thread before removing it,
+ // to ensure that it has finished before function exit
+ if (isThreaded_) {
+ // should have worker thread
+ FAISS_ASSERT((bool)it->second);
+ it->second->stop();
+ it->second->waitForThreadExit();
+ } else {
+ // should not have worker thread
+ FAISS_ASSERT(!(bool)it->second);
+ }
+
+ indices_.erase(it);
+ onAfterRemoveIndex(index);
+
+ if (own_indices) {
+ delete index;
+ }
+
+ return;
+ }
+ }
+
+ // could not find our index
+ FAISS_THROW_MSG("IndexReplicas::removeIndex: index not found");
+}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::runOnIndex(std::function<void(int, IndexT*)> f) {
+ if (isThreaded_) {
+ std::vector<std::future<bool>> v;
+
+ for (int i = 0; i < this->indices_.size(); ++i) {
+ auto& p = this->indices_[i];
+ auto indexPtr = p.first;
+ v.emplace_back(
+ p.second->add([f, i, indexPtr]() { f(i, indexPtr); }));
+ }
+
+ waitAndHandleFutures(v);
+ } else {
+ // Multiple exceptions may be thrown; gather them as we encounter them,
+ // while letting everything else run to completion
+ std::vector<std::pair<int, std::exception_ptr>> exceptions;
+
+ for (int i = 0; i < this->indices_.size(); ++i) {
+ auto& p = this->indices_[i];
+ try {
+ f(i, p.first);
+ } catch (...) {
+ exceptions.emplace_back(
+ std::make_pair(i, std::current_exception()));
+ }
+ }
+
+ handleExceptions(exceptions);
+ }
+}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::runOnIndex(
+ std::function<void(int, const IndexT*)> f) const {
+ const_cast<ThreadedIndex<IndexT>*>(this)->runOnIndex(
+ [f](int i, IndexT* idx) { f(i, idx); });
+}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::reset() {
+ runOnIndex([](int, IndexT* index) { index->reset(); });
+ this->ntotal = 0;
+ this->is_trained = false;
+}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::onAfterAddIndex(IndexT* index) {}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::onAfterRemoveIndex(IndexT* index) {}
+
+template <typename IndexT>
+void ThreadedIndex<IndexT>::waitAndHandleFutures(
+ std::vector<std::future<bool>>& v) {
+ // Blocking wait for completion for all of the indices, capturing any
+ // exceptions that are generated
+ std::vector<std::pair<int, std::exception_ptr>> exceptions;
+
+ for (int i = 0; i < v.size(); ++i) {
+ auto& fut = v[i];
+
+ try {
+ fut.get();
+ } catch (...) {
+ exceptions.emplace_back(
+ std::make_pair(i, std::current_exception()));
+ }
+ }
+
+ handleExceptions(exceptions);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ThreadedIndex.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ThreadedIndex.h
new file mode 100644
index 0000000..2d6e8e1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/ThreadedIndex.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+#include <faiss/utils/WorkerThread.h>
+#include <memory>
+#include <vector>
+
+namespace faiss {
+
+/// A holder of indices in a collection of threads
+/// The interface to this class itself is not thread safe
+template <typename IndexT>
+class ThreadedIndex : public IndexT {
+ public:
+ explicit ThreadedIndex(bool threaded);
+ explicit ThreadedIndex(int d, bool threaded);
+
+ ~ThreadedIndex() override;
+
+ /// override an index that is managed by ourselves.
+ /// WARNING: once an index is added, it becomes unsafe to touch it from any
+ /// other thread than that on which is managing it, until we are shut
+ /// down. Use runOnIndex to perform work on it instead.
+ virtual void addIndex(IndexT* index);
+
+ /// Remove an index that is managed by ourselves.
+ /// This will flush all pending work on that index, and then shut
+ /// down its managing thread, and will remove the index.
+ void removeIndex(IndexT* index);
+
+ /// Run a function on all indices, in the thread that the index is
+ /// managed in.
+ /// Function arguments are (index in collection, index pointer)
+ void runOnIndex(std::function<void(int, IndexT*)> f);
+ void runOnIndex(std::function<void(int, const IndexT*)> f) const;
+
+ /// faiss::Index API
+ /// All indices receive the same call
+ void reset() override;
+
+ /// Returns the number of sub-indices
+ int count() const {
+ return indices_.size();
+ }
+
+ /// Returns the i-th sub-index
+ IndexT* at(size_t i) {
+ return indices_[i].first;
+ }
+
+ /// Returns the i-th sub-index (const version)
+ const IndexT* at(size_t i) const {
+ return indices_[i].first;
+ }
+
+ /// Whether or not we are responsible for deleting our contained indices
+ bool own_indices = false;
+
+ protected:
+ /// Called just after an index is added
+ virtual void onAfterAddIndex(IndexT* index);
+
+ /// Called just after an index is removed
+ virtual void onAfterRemoveIndex(IndexT* index);
+
+ protected:
+ static void waitAndHandleFutures(std::vector<std::future<bool>>& v);
+
+ /// Collection of Index instances, with their managing worker thread if any
+ std::vector<std::pair<IndexT*, std::unique_ptr<WorkerThread>>> indices_;
+
+ /// Is this index multi-threaded?
+ bool isThreaded_;
+};
+
+} // namespace faiss
+
+#include <faiss/impl/ThreadedIndex-inl.h>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-avx2.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-avx2.h
new file mode 100644
index 0000000..53380b6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-avx2.h
@@ -0,0 +1,534 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#ifdef __AVX2__
+
+#include <immintrin.h>
+
+#include <type_traits>
+
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/code_distance/code_distance-generic.h>
+
+// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78782
+#if defined(__GNUC__) && __GNUC__ < 9
+#define _mm_loadu_si64(x) (_mm_loadl_epi64((__m128i_u*)x))
+#endif
+
+namespace {
+
+inline float horizontal_sum(const __m128 v) {
+ const __m128 v0 = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0, 0, 3, 2));
+ const __m128 v1 = _mm_add_ps(v, v0);
+ __m128 v2 = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(0, 0, 0, 1));
+ const __m128 v3 = _mm_add_ps(v1, v2);
+ return _mm_cvtss_f32(v3);
+}
+
+// Computes a horizontal sum over an __m256 register
+inline float horizontal_sum(const __m256 v) {
+ const __m128 v0 =
+ _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
+ return horizontal_sum(v0);
+}
+
+// processes a single code for M=4, ksub=256, nbits=8
+float inline distance_single_code_avx2_pqdecoder8_m4(
+ // precomputed distances, layout (4, 256)
+ const float* sim_table,
+ const uint8_t* code) {
+ float result = 0;
+
+ const float* tab = sim_table;
+ constexpr size_t ksub = 1 << 8;
+
+ const __m128i vksub = _mm_set1_epi32(ksub);
+ __m128i offsets_0 = _mm_setr_epi32(0, 1, 2, 3);
+ offsets_0 = _mm_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m128 partialSum;
+
+ // load 4 uint8 values
+ const __m128i mm1 = _mm_cvtsi32_si128(*((const int32_t*)code));
+ {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m128i idx1 = _mm_cvtepu8_epi32(mm1);
+
+ // add offsets
+ const __m128i indices_to_read_from = _mm_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m128 collected =
+ _mm_i32gather_ps(tab, indices_to_read_from, sizeof(float));
+
+ // collect partial sums
+ partialSum = collected;
+ }
+
+ // horizontal sum for partialSum
+ result = horizontal_sum(partialSum);
+ return result;
+}
+
+// processes a single code for M=8, ksub=256, nbits=8
+float inline distance_single_code_avx2_pqdecoder8_m8(
+ // precomputed distances, layout (8, 256)
+ const float* sim_table,
+ const uint8_t* code) {
+ float result = 0;
+
+ const float* tab = sim_table;
+ constexpr size_t ksub = 1 << 8;
+
+ const __m256i vksub = _mm256_set1_epi32(ksub);
+ __m256i offsets_0 = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ offsets_0 = _mm256_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m256 partialSum;
+
+ // load 8 uint8 values
+ const __m128i mm1 = _mm_loadu_si64((const __m128i_u*)code);
+ {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m256i idx1 = _mm256_cvtepu8_epi32(mm1);
+
+ // add offsets
+ const __m256i indices_to_read_from = _mm256_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m256 collected =
+ _mm256_i32gather_ps(tab, indices_to_read_from, sizeof(float));
+
+ // collect partial sums
+ partialSum = collected;
+ }
+
+ // horizontal sum for partialSum
+ result = horizontal_sum(partialSum);
+ return result;
+}
+
+// processes four codes for M=4, ksub=256, nbits=8
+inline void distance_four_codes_avx2_pqdecoder8_m4(
+ // precomputed distances, layout (4, 256)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ constexpr intptr_t N = 4;
+
+ const float* tab = sim_table;
+ constexpr size_t ksub = 1 << 8;
+
+ // process 8 values
+ const __m128i vksub = _mm_set1_epi32(ksub);
+ __m128i offsets_0 = _mm_setr_epi32(0, 1, 2, 3);
+ offsets_0 = _mm_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m128 partialSums[N];
+
+ // load 4 uint8 values
+ __m128i mm1[N];
+ mm1[0] = _mm_cvtsi32_si128(*((const int32_t*)code0));
+ mm1[1] = _mm_cvtsi32_si128(*((const int32_t*)code1));
+ mm1[2] = _mm_cvtsi32_si128(*((const int32_t*)code2));
+ mm1[3] = _mm_cvtsi32_si128(*((const int32_t*)code3));
+
+ for (intptr_t j = 0; j < N; j++) {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m128i idx1 = _mm_cvtepu8_epi32(mm1[j]);
+
+ // add offsets
+ const __m128i indices_to_read_from = _mm_add_epi32(idx1, offsets_0);
+
+ // gather 4 values, similar to 4 operations of tab[idx]
+ __m128 collected =
+ _mm_i32gather_ps(tab, indices_to_read_from, sizeof(float));
+
+ // collect partial sums
+ partialSums[j] = collected;
+ }
+
+ // horizontal sum for partialSum
+ result0 = horizontal_sum(partialSums[0]);
+ result1 = horizontal_sum(partialSums[1]);
+ result2 = horizontal_sum(partialSums[2]);
+ result3 = horizontal_sum(partialSums[3]);
+}
+
+// processes four codes for M=8, ksub=256, nbits=8
+inline void distance_four_codes_avx2_pqdecoder8_m8(
+ // precomputed distances, layout (8, 256)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ constexpr intptr_t N = 4;
+
+ const float* tab = sim_table;
+ constexpr size_t ksub = 1 << 8;
+
+ // process 8 values
+ const __m256i vksub = _mm256_set1_epi32(ksub);
+ __m256i offsets_0 = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ offsets_0 = _mm256_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m256 partialSums[N];
+
+ // load 8 uint8 values
+ __m128i mm1[N];
+ mm1[0] = _mm_loadu_si64((const __m128i_u*)code0);
+ mm1[1] = _mm_loadu_si64((const __m128i_u*)code1);
+ mm1[2] = _mm_loadu_si64((const __m128i_u*)code2);
+ mm1[3] = _mm_loadu_si64((const __m128i_u*)code3);
+
+ for (intptr_t j = 0; j < N; j++) {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m256i idx1 = _mm256_cvtepu8_epi32(mm1[j]);
+
+ // add offsets
+ const __m256i indices_to_read_from = _mm256_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m256 collected =
+ _mm256_i32gather_ps(tab, indices_to_read_from, sizeof(float));
+
+ // collect partial sums
+ partialSums[j] = collected;
+ }
+
+ // horizontal sum for partialSum
+ result0 = horizontal_sum(partialSums[0]);
+ result1 = horizontal_sum(partialSums[1]);
+ result2 = horizontal_sum(partialSums[2]);
+ result3 = horizontal_sum(partialSums[3]);
+}
+
+} // namespace
+
+namespace faiss {
+
+template <typename PQDecoderT>
+typename std::enable_if<!std::is_same<PQDecoderT, PQDecoder8>::value, float>::
+ type inline distance_single_code_avx2(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ const uint8_t* code) {
+ // default implementation
+ return distance_single_code_generic<PQDecoderT>(M, nbits, sim_table, code);
+}
+
+template <typename PQDecoderT>
+typename std::enable_if<std::is_same<PQDecoderT, PQDecoder8>::value, float>::
+ type inline distance_single_code_avx2(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ const uint8_t* code) {
+ if (M == 4) {
+ return distance_single_code_avx2_pqdecoder8_m4(sim_table, code);
+ }
+ if (M == 8) {
+ return distance_single_code_avx2_pqdecoder8_m8(sim_table, code);
+ }
+
+ float result = 0;
+ constexpr size_t ksub = 1 << 8;
+
+ size_t m = 0;
+ const size_t pqM16 = M / 16;
+
+ const float* tab = sim_table;
+
+ if (pqM16 > 0) {
+ // process 16 values per loop
+
+ const __m256i vksub = _mm256_set1_epi32(ksub);
+ __m256i offsets_0 = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ offsets_0 = _mm256_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m256 partialSum = _mm256_setzero_ps();
+
+ // loop
+ for (m = 0; m < pqM16 * 16; m += 16) {
+ // load 16 uint8 values
+ const __m128i mm1 = _mm_loadu_si128((const __m128i_u*)(code + m));
+ {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m256i idx1 = _mm256_cvtepu8_epi32(mm1);
+
+ // add offsets
+ const __m256i indices_to_read_from =
+ _mm256_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m256 collected = _mm256_i32gather_ps(
+ tab, indices_to_read_from, sizeof(float));
+ tab += ksub * 8;
+
+ // collect partial sums
+ partialSum = _mm256_add_ps(partialSum, collected);
+ }
+
+ // move high 8 uint8 to low ones
+ const __m128i mm2 = _mm_unpackhi_epi64(mm1, _mm_setzero_si128());
+ {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m256i idx1 = _mm256_cvtepu8_epi32(mm2);
+
+ // add offsets
+ const __m256i indices_to_read_from =
+ _mm256_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m256 collected = _mm256_i32gather_ps(
+ tab, indices_to_read_from, sizeof(float));
+ tab += ksub * 8;
+
+ // collect partial sums
+ partialSum = _mm256_add_ps(partialSum, collected);
+ }
+ }
+
+ // horizontal sum for partialSum
+ result += horizontal_sum(partialSum);
+ }
+
+ //
+ if (m < M) {
+ // process leftovers
+ PQDecoder8 decoder(code + m, nbits);
+
+ for (; m < M; m++) {
+ result += tab[decoder.decode()];
+ tab += ksub;
+ }
+ }
+
+ return result;
+}
+
+template <typename PQDecoderT>
+typename std::enable_if<!std::is_same<PQDecoderT, PQDecoder8>::value, void>::
+ type
+ distance_four_codes_avx2(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ distance_four_codes_generic<PQDecoderT>(
+ M,
+ nbits,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+}
+
+// Combines 4 operations of distance_single_code()
+template <typename PQDecoderT>
+typename std::enable_if<std::is_same<PQDecoderT, PQDecoder8>::value, void>::type
+distance_four_codes_avx2(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ if (M == 4) {
+ distance_four_codes_avx2_pqdecoder8_m4(
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+ return;
+ }
+ if (M == 8) {
+ distance_four_codes_avx2_pqdecoder8_m8(
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+ return;
+ }
+
+ result0 = 0;
+ result1 = 0;
+ result2 = 0;
+ result3 = 0;
+ constexpr size_t ksub = 1 << 8;
+
+ size_t m = 0;
+ const size_t pqM16 = M / 16;
+
+ constexpr intptr_t N = 4;
+
+ const float* tab = sim_table;
+
+ if (pqM16 > 0) {
+ // process 16 values per loop
+ const __m256i vksub = _mm256_set1_epi32(ksub);
+ __m256i offsets_0 = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ offsets_0 = _mm256_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m256 partialSums[N];
+ for (intptr_t j = 0; j < N; j++) {
+ partialSums[j] = _mm256_setzero_ps();
+ }
+
+ // loop
+ for (m = 0; m < pqM16 * 16; m += 16) {
+ // load 16 uint8 values
+ __m128i mm1[N];
+ mm1[0] = _mm_loadu_si128((const __m128i_u*)(code0 + m));
+ mm1[1] = _mm_loadu_si128((const __m128i_u*)(code1 + m));
+ mm1[2] = _mm_loadu_si128((const __m128i_u*)(code2 + m));
+ mm1[3] = _mm_loadu_si128((const __m128i_u*)(code3 + m));
+
+ // process first 8 codes
+ for (intptr_t j = 0; j < N; j++) {
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m256i idx1 = _mm256_cvtepu8_epi32(mm1[j]);
+
+ // add offsets
+ const __m256i indices_to_read_from =
+ _mm256_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m256 collected = _mm256_i32gather_ps(
+ tab, indices_to_read_from, sizeof(float));
+
+ // collect partial sums
+ partialSums[j] = _mm256_add_ps(partialSums[j], collected);
+ }
+ tab += ksub * 8;
+
+ // process next 8 codes
+ for (intptr_t j = 0; j < N; j++) {
+ // move high 8 uint8 to low ones
+ const __m128i mm2 =
+ _mm_unpackhi_epi64(mm1[j], _mm_setzero_si128());
+
+ // convert uint8 values (low part of __m128i) to int32
+ // values
+ const __m256i idx1 = _mm256_cvtepu8_epi32(mm2);
+
+ // add offsets
+ const __m256i indices_to_read_from =
+ _mm256_add_epi32(idx1, offsets_0);
+
+ // gather 8 values, similar to 8 operations of tab[idx]
+ __m256 collected = _mm256_i32gather_ps(
+ tab, indices_to_read_from, sizeof(float));
+
+ // collect partial sums
+ partialSums[j] = _mm256_add_ps(partialSums[j], collected);
+ }
+
+ tab += ksub * 8;
+ }
+
+ // horizontal sum for partialSum
+ result0 += horizontal_sum(partialSums[0]);
+ result1 += horizontal_sum(partialSums[1]);
+ result2 += horizontal_sum(partialSums[2]);
+ result3 += horizontal_sum(partialSums[3]);
+ }
+
+ //
+ if (m < M) {
+ // process leftovers
+ PQDecoder8 decoder0(code0 + m, nbits);
+ PQDecoder8 decoder1(code1 + m, nbits);
+ PQDecoder8 decoder2(code2 + m, nbits);
+ PQDecoder8 decoder3(code3 + m, nbits);
+ for (; m < M; m++) {
+ result0 += tab[decoder0.decode()];
+ result1 += tab[decoder1.decode()];
+ result2 += tab[decoder2.decode()];
+ result3 += tab[decoder3.decode()];
+ tab += ksub;
+ }
+ }
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-avx512.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-avx512.h
new file mode 100644
index 0000000..d05c41c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-avx512.h
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#ifdef __AVX512F__
+
+#include <immintrin.h>
+
+#include <type_traits>
+
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/code_distance/code_distance-generic.h>
+
+namespace faiss {
+
+// According to experiments, the AVX-512 version may be SLOWER than
+// the AVX2 version, which is somewhat unexpected.
+// This version is not used for now, but it may be used later.
+//
+// TODO: test for AMD CPUs.
+
+template <typename PQDecoderT>
+typename std::enable_if<!std::is_same<PQDecoderT, PQDecoder8>::value, float>::
+ type inline distance_single_code_avx512(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ const uint8_t* code) {
+ // default implementation
+ return distance_single_code_generic<PQDecoderT>(M, nbits, sim_table, code);
+}
+
+template <typename PQDecoderT>
+typename std::enable_if<std::is_same<PQDecoderT, PQDecoder8>::value, float>::
+ type inline distance_single_code_avx512(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ const uint8_t* code0) {
+ float result0 = 0;
+ constexpr size_t ksub = 1 << 8;
+
+ size_t m = 0;
+ const size_t pqM16 = M / 16;
+
+ constexpr intptr_t N = 1;
+
+ const float* tab = sim_table;
+
+ if (pqM16 > 0) {
+ // process 16 values per loop
+ const __m512i vksub = _mm512_set1_epi32(ksub);
+ __m512i offsets_0 = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ offsets_0 = _mm512_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m512 partialSums[N];
+ for (intptr_t j = 0; j < N; j++) {
+ partialSums[j] = _mm512_setzero_ps();
+ }
+
+ // loop
+ for (m = 0; m < pqM16 * 16; m += 16) {
+ // load 16 uint8 values
+ __m128i mm1[N];
+ mm1[0] = _mm_loadu_si128((const __m128i_u*)(code0 + m));
+
+ // process first 8 codes
+ for (intptr_t j = 0; j < N; j++) {
+ const __m512i idx1 = _mm512_cvtepu8_epi32(mm1[j]);
+
+ // add offsets
+ const __m512i indices_to_read_from =
+ _mm512_add_epi32(idx1, offsets_0);
+
+ // gather 16 values, similar to 16 operations of tab[idx]
+ __m512 collected = _mm512_i32gather_ps(
+ indices_to_read_from, tab, sizeof(float));
+
+ // collect partial sums
+ partialSums[j] = _mm512_add_ps(partialSums[j], collected);
+ }
+ tab += ksub * 16;
+ }
+
+ // horizontal sum for partialSum
+ result0 += _mm512_reduce_add_ps(partialSums[0]);
+ }
+
+ //
+ if (m < M) {
+ // process leftovers
+ PQDecoder8 decoder0(code0 + m, nbits);
+ for (; m < M; m++) {
+ result0 += tab[decoder0.decode()];
+ tab += ksub;
+ }
+ }
+
+ return result0;
+}
+
+template <typename PQDecoderT>
+typename std::enable_if<!std::is_same<PQDecoderT, PQDecoder8>::value, void>::
+ type
+ distance_four_codes_avx512(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ distance_four_codes_generic<PQDecoderT>(
+ M,
+ nbits,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+}
+
+// Combines 4 operations of distance_single_code()
+template <typename PQDecoderT>
+typename std::enable_if<std::is_same<PQDecoderT, PQDecoder8>::value, void>::type
+distance_four_codes_avx512(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ result0 = 0;
+ result1 = 0;
+ result2 = 0;
+ result3 = 0;
+ constexpr size_t ksub = 1 << 8;
+
+ size_t m = 0;
+ const size_t pqM16 = M / 16;
+
+ constexpr intptr_t N = 4;
+
+ const float* tab = sim_table;
+
+ if (pqM16 > 0) {
+ // process 16 values per loop
+ const __m512i vksub = _mm512_set1_epi32(ksub);
+ __m512i offsets_0 = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ offsets_0 = _mm512_mullo_epi32(offsets_0, vksub);
+
+ // accumulators of partial sums
+ __m512 partialSums[N];
+ for (intptr_t j = 0; j < N; j++) {
+ partialSums[j] = _mm512_setzero_ps();
+ }
+
+ // loop
+ for (m = 0; m < pqM16 * 16; m += 16) {
+ // load 16 uint8 values
+ __m128i mm1[N];
+ mm1[0] = _mm_loadu_si128((const __m128i_u*)(code0 + m));
+ mm1[1] = _mm_loadu_si128((const __m128i_u*)(code1 + m));
+ mm1[2] = _mm_loadu_si128((const __m128i_u*)(code2 + m));
+ mm1[3] = _mm_loadu_si128((const __m128i_u*)(code3 + m));
+
+ // process first 8 codes
+ for (intptr_t j = 0; j < N; j++) {
+ const __m512i idx1 = _mm512_cvtepu8_epi32(mm1[j]);
+
+ // add offsets
+ const __m512i indices_to_read_from =
+ _mm512_add_epi32(idx1, offsets_0);
+
+ // gather 16 values, similar to 16 operations of tab[idx]
+ __m512 collected = _mm512_i32gather_ps(
+ indices_to_read_from, tab, sizeof(float));
+
+ // collect partial sums
+ partialSums[j] = _mm512_add_ps(partialSums[j], collected);
+ }
+ tab += ksub * 16;
+ }
+
+ // horizontal sum for partialSum
+ result0 += _mm512_reduce_add_ps(partialSums[0]);
+ result1 += _mm512_reduce_add_ps(partialSums[1]);
+ result2 += _mm512_reduce_add_ps(partialSums[2]);
+ result3 += _mm512_reduce_add_ps(partialSums[3]);
+ }
+
+ //
+ if (m < M) {
+ // process leftovers
+ PQDecoder8 decoder0(code0 + m, nbits);
+ PQDecoder8 decoder1(code1 + m, nbits);
+ PQDecoder8 decoder2(code2 + m, nbits);
+ PQDecoder8 decoder3(code3 + m, nbits);
+ for (; m < M; m++) {
+ result0 += tab[decoder0.decode()];
+ result1 += tab[decoder1.decode()];
+ result2 += tab[decoder2.decode()];
+ result3 += tab[decoder3.decode()];
+ tab += ksub;
+ }
+ }
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-generic.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-generic.h
new file mode 100644
index 0000000..c02551c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-generic.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace faiss {
+
+/// Returns the distance to a single code.
+template <typename PQDecoderT>
+inline float distance_single_code_generic(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // the code
+ const uint8_t* code) {
+ PQDecoderT decoder(code, nbits);
+ const size_t ksub = 1 << nbits;
+
+ const float* tab = sim_table;
+ float result = 0;
+
+ for (size_t m = 0; m < M; m++) {
+ result += tab[decoder.decode()];
+ tab += ksub;
+ }
+
+ return result;
+}
+
+/// Combines 4 operations of distance_single_code()
+/// General-purpose version.
+template <typename PQDecoderT>
+inline void distance_four_codes_generic(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ PQDecoderT decoder0(code0, nbits);
+ PQDecoderT decoder1(code1, nbits);
+ PQDecoderT decoder2(code2, nbits);
+ PQDecoderT decoder3(code3, nbits);
+ const size_t ksub = 1 << nbits;
+
+ const float* tab = sim_table;
+ result0 = 0;
+ result1 = 0;
+ result2 = 0;
+ result3 = 0;
+
+ for (size_t m = 0; m < M; m++) {
+ result0 += tab[decoder0.decode()];
+ result1 += tab[decoder1.decode()];
+ result2 += tab[decoder2.decode()];
+ result3 += tab[decoder3.decode()];
+ tab += ksub;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-sve.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-sve.h
new file mode 100644
index 0000000..82f7746
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance-sve.h
@@ -0,0 +1,439 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#ifdef __ARM_FEATURE_SVE
+
+#include <arm_sve.h>
+
+#include <tuple>
+#include <type_traits>
+
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/code_distance/code_distance-generic.h>
+
+namespace faiss {
+
+template <typename PQDecoderT>
+std::enable_if_t<!std::is_same_v<PQDecoderT, PQDecoder8>, float> inline distance_single_code_sve(
+ // the product quantizer
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ const uint8_t* code) {
+ // default implementation
+ return distance_single_code_generic<PQDecoderT>(M, nbits, sim_table, code);
+}
+
+static inline void distance_codes_kernel(
+ svbool_t pg,
+ svuint32_t idx1,
+ svuint32_t offsets_0,
+ const float* tab,
+ svfloat32_t& partialSum) {
+ // add offset
+ const auto indices_to_read_from = svadd_u32_x(pg, idx1, offsets_0);
+
+ // gather values, similar to some operations of tab[index]
+ const auto collected =
+ svld1_gather_u32index_f32(pg, tab, indices_to_read_from);
+
+ // collect partial sum
+ partialSum = svadd_f32_m(pg, partialSum, collected);
+}
+
+static inline float distance_single_code_sve_for_small_m(
+ // the product quantizer
+ const size_t M,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code) {
+ constexpr size_t nbits = 8u;
+
+ const size_t ksub = 1 << nbits;
+
+ const auto offsets_0 = svindex_u32(0, static_cast<uint32_t>(ksub));
+
+ // loop
+ const auto pg = svwhilelt_b32_u64(0, M);
+
+ auto mm1 = svld1ub_u32(pg, code);
+ mm1 = svadd_u32_x(pg, mm1, offsets_0);
+ const auto collected0 = svld1_gather_u32index_f32(pg, sim_table, mm1);
+ return svaddv_f32(pg, collected0);
+}
+
+template <typename PQDecoderT>
+std::enable_if_t<std::is_same_v<PQDecoderT, PQDecoder8>, float> inline distance_single_code_sve(
+ // the product quantizer
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ const uint8_t* code) {
+ if (M <= svcntw())
+ return distance_single_code_sve_for_small_m(M, sim_table, code);
+
+ const float* tab = sim_table;
+
+ const size_t ksub = 1 << nbits;
+
+ const auto offsets_0 = svindex_u32(0, static_cast<uint32_t>(ksub));
+
+ // accumulators of partial sums
+ auto partialSum = svdup_n_f32(0.f);
+
+ const auto lanes = svcntb();
+ const auto quad_lanes = lanes / 4;
+
+ // loop
+ for (std::size_t m = 0; m < M;) {
+ const auto pg = svwhilelt_b8_u64(m, M);
+
+ const auto mm1 = svld1_u8(pg, code + m);
+ {
+ const auto mm1lo = svunpklo_u16(mm1);
+ const auto pglo = svunpklo_b(pg);
+
+ {
+ // convert uint8 values to uint32 values
+ const auto idx1 = svunpklo_u32(mm1lo);
+ const auto pglolo = svunpklo_b(pglo);
+
+ distance_codes_kernel(pglolo, idx1, offsets_0, tab, partialSum);
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ if (m >= M)
+ break;
+
+ {
+ // convert uint8 values to uint32 values
+ const auto idx1 = svunpkhi_u32(mm1lo);
+ const auto pglohi = svunpkhi_b(pglo);
+
+ distance_codes_kernel(pglohi, idx1, offsets_0, tab, partialSum);
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ if (m >= M)
+ break;
+ }
+
+ {
+ const auto mm1hi = svunpkhi_u16(mm1);
+ const auto pghi = svunpkhi_b(pg);
+
+ {
+ // convert uint8 values to uint32 values
+ const auto idx1 = svunpklo_u32(mm1hi);
+ const auto pghilo = svunpklo_b(pghi);
+
+ distance_codes_kernel(pghilo, idx1, offsets_0, tab, partialSum);
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ if (m >= M)
+ break;
+
+ {
+ // convert uint8 values to uint32 values
+ const auto idx1 = svunpkhi_u32(mm1hi);
+ const auto pghihi = svunpkhi_b(pghi);
+
+ distance_codes_kernel(pghihi, idx1, offsets_0, tab, partialSum);
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ }
+ }
+
+ return svaddv_f32(svptrue_b32(), partialSum);
+}
+
+template <typename PQDecoderT>
+std::enable_if_t<!std::is_same_v<PQDecoderT, PQDecoder8>, void>
+distance_four_codes_sve(
+ // the product quantizer
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ distance_four_codes_generic<PQDecoderT>(
+ M,
+ nbits,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+}
+
+static inline void distance_four_codes_sve_for_small_m(
+ // the product quantizer
+ const size_t M,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ constexpr size_t nbits = 8u;
+
+ const size_t ksub = 1 << nbits;
+
+ const auto offsets_0 = svindex_u32(0, static_cast<uint32_t>(ksub));
+
+ // loop
+ const auto pg = svwhilelt_b32_u64(0, M);
+
+ auto mm10 = svld1ub_u32(pg, code0);
+ auto mm11 = svld1ub_u32(pg, code1);
+ auto mm12 = svld1ub_u32(pg, code2);
+ auto mm13 = svld1ub_u32(pg, code3);
+ mm10 = svadd_u32_x(pg, mm10, offsets_0);
+ mm11 = svadd_u32_x(pg, mm11, offsets_0);
+ mm12 = svadd_u32_x(pg, mm12, offsets_0);
+ mm13 = svadd_u32_x(pg, mm13, offsets_0);
+ const auto collected0 = svld1_gather_u32index_f32(pg, sim_table, mm10);
+ const auto collected1 = svld1_gather_u32index_f32(pg, sim_table, mm11);
+ const auto collected2 = svld1_gather_u32index_f32(pg, sim_table, mm12);
+ const auto collected3 = svld1_gather_u32index_f32(pg, sim_table, mm13);
+ result0 = svaddv_f32(pg, collected0);
+ result1 = svaddv_f32(pg, collected1);
+ result2 = svaddv_f32(pg, collected2);
+ result3 = svaddv_f32(pg, collected3);
+}
+
+// Combines 4 operations of distance_single_code()
+template <typename PQDecoderT>
+std::enable_if_t<std::is_same_v<PQDecoderT, PQDecoder8>, void>
+distance_four_codes_sve(
+ // the product quantizer
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ if (M <= svcntw()) {
+ distance_four_codes_sve_for_small_m(
+ M,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+ return;
+ }
+
+ const float* tab = sim_table;
+
+ const size_t ksub = 1 << nbits;
+
+ const auto offsets_0 = svindex_u32(0, static_cast<uint32_t>(ksub));
+
+ // accumulators of partial sums
+ auto partialSum0 = svdup_n_f32(0.f);
+ auto partialSum1 = svdup_n_f32(0.f);
+ auto partialSum2 = svdup_n_f32(0.f);
+ auto partialSum3 = svdup_n_f32(0.f);
+
+ const auto lanes = svcntb();
+ const auto quad_lanes = lanes / 4;
+
+ // loop
+ for (std::size_t m = 0; m < M;) {
+ const auto pg = svwhilelt_b8_u64(m, M);
+
+ const auto mm10 = svld1_u8(pg, code0 + m);
+ const auto mm11 = svld1_u8(pg, code1 + m);
+ const auto mm12 = svld1_u8(pg, code2 + m);
+ const auto mm13 = svld1_u8(pg, code3 + m);
+ {
+ const auto mm10lo = svunpklo_u16(mm10);
+ const auto mm11lo = svunpklo_u16(mm11);
+ const auto mm12lo = svunpklo_u16(mm12);
+ const auto mm13lo = svunpklo_u16(mm13);
+ const auto pglo = svunpklo_b(pg);
+
+ {
+ const auto pglolo = svunpklo_b(pglo);
+ {
+ const auto idx1 = svunpklo_u32(mm10lo);
+ distance_codes_kernel(
+ pglolo, idx1, offsets_0, tab, partialSum0);
+ }
+ {
+ const auto idx1 = svunpklo_u32(mm11lo);
+ distance_codes_kernel(
+ pglolo, idx1, offsets_0, tab, partialSum1);
+ }
+ {
+ const auto idx1 = svunpklo_u32(mm12lo);
+ distance_codes_kernel(
+ pglolo, idx1, offsets_0, tab, partialSum2);
+ }
+ {
+ const auto idx1 = svunpklo_u32(mm13lo);
+ distance_codes_kernel(
+ pglolo, idx1, offsets_0, tab, partialSum3);
+ }
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ if (m >= M)
+ break;
+
+ {
+ const auto pglohi = svunpkhi_b(pglo);
+ {
+ const auto idx1 = svunpkhi_u32(mm10lo);
+ distance_codes_kernel(
+ pglohi, idx1, offsets_0, tab, partialSum0);
+ }
+ {
+ const auto idx1 = svunpkhi_u32(mm11lo);
+ distance_codes_kernel(
+ pglohi, idx1, offsets_0, tab, partialSum1);
+ }
+ {
+ const auto idx1 = svunpkhi_u32(mm12lo);
+ distance_codes_kernel(
+ pglohi, idx1, offsets_0, tab, partialSum2);
+ }
+ {
+ const auto idx1 = svunpkhi_u32(mm13lo);
+ distance_codes_kernel(
+ pglohi, idx1, offsets_0, tab, partialSum3);
+ }
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ if (m >= M)
+ break;
+ }
+
+ {
+ const auto mm10hi = svunpkhi_u16(mm10);
+ const auto mm11hi = svunpkhi_u16(mm11);
+ const auto mm12hi = svunpkhi_u16(mm12);
+ const auto mm13hi = svunpkhi_u16(mm13);
+ const auto pghi = svunpkhi_b(pg);
+
+ {
+ const auto pghilo = svunpklo_b(pghi);
+ {
+ const auto idx1 = svunpklo_u32(mm10hi);
+ distance_codes_kernel(
+ pghilo, idx1, offsets_0, tab, partialSum0);
+ }
+ {
+ const auto idx1 = svunpklo_u32(mm11hi);
+ distance_codes_kernel(
+ pghilo, idx1, offsets_0, tab, partialSum1);
+ }
+ {
+ const auto idx1 = svunpklo_u32(mm12hi);
+ distance_codes_kernel(
+ pghilo, idx1, offsets_0, tab, partialSum2);
+ }
+ {
+ const auto idx1 = svunpklo_u32(mm13hi);
+ distance_codes_kernel(
+ pghilo, idx1, offsets_0, tab, partialSum3);
+ }
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ if (m >= M)
+ break;
+
+ {
+ const auto pghihi = svunpkhi_b(pghi);
+ {
+ const auto idx1 = svunpkhi_u32(mm10hi);
+ distance_codes_kernel(
+ pghihi, idx1, offsets_0, tab, partialSum0);
+ }
+ {
+ const auto idx1 = svunpkhi_u32(mm11hi);
+ distance_codes_kernel(
+ pghihi, idx1, offsets_0, tab, partialSum1);
+ }
+ {
+ const auto idx1 = svunpkhi_u32(mm12hi);
+ distance_codes_kernel(
+ pghihi, idx1, offsets_0, tab, partialSum2);
+ }
+ {
+ const auto idx1 = svunpkhi_u32(mm13hi);
+ distance_codes_kernel(
+ pghihi, idx1, offsets_0, tab, partialSum3);
+ }
+ tab += ksub * quad_lanes;
+ }
+
+ m += quad_lanes;
+ }
+ }
+
+ result0 = svaddv_f32(svptrue_b32(), partialSum0);
+ result1 = svaddv_f32(svptrue_b32(), partialSum1);
+ result2 = svaddv_f32(svptrue_b32(), partialSum2);
+ result3 = svaddv_f32(svptrue_b32(), partialSum3);
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance.h
new file mode 100644
index 0000000..8f29abd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/code_distance/code_distance.h
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/platform_macros.h>
+
+// This directory contains functions to compute a distance
+// from a given PQ code to a query vector, given that the
+// distances to a query vector for pq.M codebooks are precomputed.
+//
+// The code was originally the part of IndexIVFPQ.cpp.
+// The baseline implementation can be found in
+// code_distance-generic.h, distance_single_code_generic().
+
+// The reason for this somewhat unusual structure is that
+// custom implementations may need to fall off to generic
+// implementation in certain cases. So, say, avx2 header file
+// needs to reference the generic header file. This is
+// why the names of the functions for custom implementations
+// have this _generic or _avx2 suffix.
+
+#ifdef __AVX2__
+
+#include <faiss/impl/code_distance/code_distance-avx2.h>
+
+namespace faiss {
+
+template <typename PQDecoderT>
+inline float distance_single_code(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // the code
+ const uint8_t* code) {
+ return distance_single_code_avx2<PQDecoderT>(M, nbits, sim_table, code);
+}
+
+template <typename PQDecoderT>
+inline void distance_four_codes(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ distance_four_codes_avx2<PQDecoderT>(
+ M,
+ nbits,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+}
+
+} // namespace faiss
+
+#elif defined(__ARM_FEATURE_SVE)
+
+#include <faiss/impl/code_distance/code_distance-sve.h>
+
+namespace faiss {
+
+template <typename PQDecoderT>
+inline float distance_single_code(
+ // the product quantizer
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // the code
+ const uint8_t* code) {
+ return distance_single_code_sve<PQDecoderT>(M, nbits, sim_table, code);
+}
+
+template <typename PQDecoderT>
+inline void distance_four_codes(
+ // the product quantizer
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ distance_four_codes_sve<PQDecoderT>(
+ M,
+ nbits,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+}
+
+} // namespace faiss
+
+#else
+
+#include <faiss/impl/code_distance/code_distance-generic.h>
+
+namespace faiss {
+
+template <typename PQDecoderT>
+inline float distance_single_code(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // the code
+ const uint8_t* code) {
+ return distance_single_code_generic<PQDecoderT>(M, nbits, sim_table, code);
+}
+
+template <typename PQDecoderT>
+inline void distance_four_codes(
+ // number of subquantizers
+ const size_t M,
+ // number of bits per quantization index
+ const size_t nbits,
+ // precomputed distances, layout (M, ksub)
+ const float* sim_table,
+ // codes
+ const uint8_t* __restrict code0,
+ const uint8_t* __restrict code1,
+ const uint8_t* __restrict code2,
+ const uint8_t* __restrict code3,
+ // computed distances
+ float& result0,
+ float& result1,
+ float& result2,
+ float& result3) {
+ distance_four_codes_generic<PQDecoderT>(
+ M,
+ nbits,
+ sim_table,
+ code0,
+ code1,
+ code2,
+ code3,
+ result0,
+ result1,
+ result2,
+ result3);
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_read.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_read.cpp
new file mode 100644
index 0000000..c06f75f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_read.cpp
@@ -0,0 +1,1820 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/index_read_utils.h>
+#include <faiss/index_io.h>
+
+#include <faiss/impl/io_macros.h>
+
+#include <cstdio> // For ftell, fseek
+#include <cstdlib>
+#include <optional>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/io.h>
+#include <faiss/impl/io_macros.h>
+#include <faiss/utils/hamming.h>
+
+#include <faiss/invlists/InvertedListsIOHook.h>
+
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexAdditiveQuantizerFastScan.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFIndependentQuantizer.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/IndexIVFPQR.h>
+#include <faiss/IndexIVFRaBitQ.h>
+#include <faiss/IndexIVFSpectralHash.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexLattice.h>
+#include <faiss/IndexNNDescent.h>
+#include <faiss/IndexNSG.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRaBitQ.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/IndexRowwiseMinMax.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/VectorTransform.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryFromFloat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryHash.h>
+#include <faiss/IndexBinaryIVF.h>
+
+// mmap-ing and viewing facilities
+#include <faiss/impl/maybe_owned_vector.h>
+
+#include <faiss/impl/mapped_io.h>
+#include <faiss/impl/zerocopy_io.h>
+#include <cinttypes>
+
+#include <faiss/impl/HNSW_zmq.h>
+namespace faiss {
+
+/*************************************************************
+ * Mmap-ing and viewing facilities
+ **************************************************************/
+
+// This is a baseline functionality for reading mmapped and zerocopied vector.
+// * if `beforeknown_size` is defined, then a size of the vector won't be read.
+// * if `size_multiplier` is defined, then a size will be multiplied by it.
+// * returns true is the case was handled; ownerwise, false
+template <typename VectorT>
+bool read_vector_base(
+ VectorT& target,
+ IOReader* f,
+ const std::optional<size_t> beforeknown_size,
+ const std::optional<size_t> size_multiplier) {
+ // check if the use case is right
+ if constexpr (is_maybe_owned_vector_v<VectorT>) {
+ // is it a mmap-enabled reader?
+ MappedFileIOReader* mf = dynamic_cast<MappedFileIOReader*>(f);
+ if (mf != nullptr) {
+ // read the size or use a known one
+ size_t size = 0;
+ if (beforeknown_size.has_value()) {
+ size = beforeknown_size.value();
+ } else {
+ READANDCHECK(&size, 1);
+ }
+
+ // perform the size multiplication
+ size *= size_multiplier.value_or(1);
+
+ // ok, mmap and check
+ char* address = nullptr;
+ const size_t nread = mf->mmap(
+ (void**)&address,
+ sizeof(typename VectorT::value_type),
+ size);
+
+ FAISS_THROW_IF_NOT_FMT(
+ nread == (size),
+ "read error in %s: %zd != %zd (%s)",
+ f->name.c_str(),
+ nread,
+ size,
+ strerror(errno));
+
+ VectorT mmapped_view =
+ VectorT::create_view(address, nread, mf->mmap_owner);
+ target = std::move(mmapped_view);
+
+ return true;
+ }
+
+ // is it a zero-copy reader?
+ ZeroCopyIOReader* zr = dynamic_cast<ZeroCopyIOReader*>(f);
+ if (zr != nullptr) {
+ // read the size or use a known one
+ size_t size = 0;
+ if (beforeknown_size.has_value()) {
+ size = beforeknown_size.value();
+ } else {
+ READANDCHECK(&size, 1);
+ }
+
+ // perform the size multiplication
+ size *= size_multiplier.value_or(1);
+
+ // create a view
+ char* address = nullptr;
+ size_t nread = zr->get_data_view(
+ (void**)&address,
+ sizeof(typename VectorT::value_type),
+ size);
+
+ FAISS_THROW_IF_NOT_FMT(
+ nread == (size),
+ "read error in %s: %zd != %zd (%s)",
+ f->name.c_str(),
+ nread,
+ size_t(size),
+ strerror(errno));
+
+ VectorT view = VectorT::create_view(address, nread, nullptr);
+ target = std::move(view);
+
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// a replacement for READANDCHECK for reading data into std::vector
+template <typename VectorT>
+void read_vector_with_known_size(VectorT& target, IOReader* f, size_t size) {
+ // size is known beforehand, no size multiplication
+ if (read_vector_base<VectorT>(target, f, size, std::nullopt)) {
+ return;
+ }
+
+ // the default case
+ READANDCHECK(target.data(), size);
+}
+
+// a replacement for READVECTOR
+template <typename VectorT>
+void read_vector(VectorT& target, IOReader* f) {
+ // size is not known beforehand, no size multiplication
+ if (read_vector_base<VectorT>(target, f, std::nullopt, std::nullopt)) {
+ return;
+ }
+
+ // the default case
+ READVECTOR(target);
+}
+
+// a replacement for READXBVECTOR
+template <typename VectorT>
+void read_xb_vector(VectorT& target, IOReader* f) {
+ // size is not known beforehand, nultiply the size 4x
+ if (read_vector_base<VectorT>(target, f, std::nullopt, 4)) {
+ return;
+ }
+
+ // the default case
+ READXBVECTOR(target);
+}
+
+/*************************************************************
+ * Read
+ **************************************************************/
+
+void read_index_header(Index* idx, IOReader* f) {
+ READ1(idx->d);
+ READ1(idx->ntotal);
+ idx_t dummy;
+ READ1(dummy);
+ READ1(dummy);
+ READ1(idx->is_trained);
+ READ1(idx->metric_type);
+ if (idx->metric_type > 1) {
+ READ1(idx->metric_arg);
+ }
+ idx->verbose = false;
+}
+
+VectorTransform* read_VectorTransform(IOReader* f) {
+ uint32_t h;
+ READ1(h);
+ VectorTransform* vt = nullptr;
+
+ if (h == fourcc("rrot") || h == fourcc("PCAm") || h == fourcc("LTra") ||
+ h == fourcc("PcAm") || h == fourcc("Viqm") || h == fourcc("Pcam")) {
+ LinearTransform* lt = nullptr;
+ if (h == fourcc("rrot")) {
+ lt = new RandomRotationMatrix();
+ } else if (
+ h == fourcc("PCAm") || h == fourcc("PcAm") ||
+ h == fourcc("Pcam")) {
+ PCAMatrix* pca = new PCAMatrix();
+ READ1(pca->eigen_power);
+ if (h == fourcc("Pcam")) {
+ READ1(pca->epsilon);
+ }
+ READ1(pca->random_rotation);
+ if (h != fourcc("PCAm")) {
+ READ1(pca->balanced_bins);
+ }
+ READVECTOR(pca->mean);
+ READVECTOR(pca->eigenvalues);
+ READVECTOR(pca->PCAMat);
+ lt = pca;
+ } else if (h == fourcc("Viqm")) {
+ ITQMatrix* itqm = new ITQMatrix();
+ READ1(itqm->max_iter);
+ READ1(itqm->seed);
+ lt = itqm;
+ } else if (h == fourcc("LTra")) {
+ lt = new LinearTransform();
+ }
+ READ1(lt->have_bias);
+ READVECTOR(lt->A);
+ READVECTOR(lt->b);
+ FAISS_THROW_IF_NOT(lt->A.size() >= lt->d_in * lt->d_out);
+ FAISS_THROW_IF_NOT(!lt->have_bias || lt->b.size() >= lt->d_out);
+ lt->set_is_orthonormal();
+ vt = lt;
+ } else if (h == fourcc("RmDT")) {
+ RemapDimensionsTransform* rdt = new RemapDimensionsTransform();
+ READVECTOR(rdt->map);
+ vt = rdt;
+ } else if (h == fourcc("VNrm")) {
+ NormalizationTransform* nt = new NormalizationTransform();
+ READ1(nt->norm);
+ vt = nt;
+ } else if (h == fourcc("VCnt")) {
+ CenteringTransform* ct = new CenteringTransform();
+ READVECTOR(ct->mean);
+ vt = ct;
+ } else if (h == fourcc("Viqt")) {
+ ITQTransform* itqt = new ITQTransform();
+
+ READVECTOR(itqt->mean);
+ READ1(itqt->do_pca);
+ {
+ ITQMatrix* itqm = dynamic_cast<ITQMatrix*>(read_VectorTransform(f));
+ FAISS_THROW_IF_NOT(itqm);
+ itqt->itq = *itqm;
+ delete itqm;
+ }
+ {
+ LinearTransform* pi =
+ dynamic_cast<LinearTransform*>(read_VectorTransform(f));
+ FAISS_THROW_IF_NOT(pi);
+ itqt->pca_then_itq = *pi;
+ delete pi;
+ }
+ vt = itqt;
+ } else {
+ FAISS_THROW_FMT(
+ "fourcc %ud (\"%s\") not recognized in %s",
+ h,
+ fourcc_inv_printable(h).c_str(),
+ f->name.c_str());
+ }
+ READ1(vt->d_in);
+ READ1(vt->d_out);
+ READ1(vt->is_trained);
+ return vt;
+}
+
+static void read_ArrayInvertedLists_sizes(
+ IOReader* f,
+ std::vector<size_t>& sizes) {
+ uint32_t list_type;
+ READ1(list_type);
+ if (list_type == fourcc("full")) {
+ size_t os = sizes.size();
+ READVECTOR(sizes);
+ FAISS_THROW_IF_NOT(os == sizes.size());
+ } else if (list_type == fourcc("sprs")) {
+ std::vector<size_t> idsizes;
+ READVECTOR(idsizes);
+ for (size_t j = 0; j < idsizes.size(); j += 2) {
+ FAISS_THROW_IF_NOT(idsizes[j] < sizes.size());
+ sizes[idsizes[j]] = idsizes[j + 1];
+ }
+ } else {
+ FAISS_THROW_FMT(
+ "list_type %ud (\"%s\") not recognized",
+ list_type,
+ fourcc_inv_printable(list_type).c_str());
+ }
+}
+
+InvertedLists* read_InvertedLists(IOReader* f, int io_flags) {
+ uint32_t h;
+ READ1(h);
+ if (h == fourcc("il00")) {
+ fprintf(stderr,
+ "read_InvertedLists:"
+ " WARN! inverted lists not stored with IVF object\n");
+ return nullptr;
+ } else if (h == fourcc("ilar") && !(io_flags & IO_FLAG_SKIP_IVF_DATA)) {
+ auto ails = new ArrayInvertedLists(0, 0);
+ READ1(ails->nlist);
+ READ1(ails->code_size);
+ ails->ids.resize(ails->nlist);
+ ails->codes.resize(ails->nlist);
+ std::vector<size_t> sizes(ails->nlist);
+ read_ArrayInvertedLists_sizes(f, sizes);
+ for (size_t i = 0; i < ails->nlist; i++) {
+ ails->ids[i].resize(sizes[i]);
+ ails->codes[i].resize(sizes[i] * ails->code_size);
+ }
+ for (size_t i = 0; i < ails->nlist; i++) {
+ size_t n = ails->ids[i].size();
+ if (n > 0) {
+ read_vector_with_known_size(
+ ails->codes[i], f, n * ails->code_size);
+ read_vector_with_known_size(ails->ids[i], f, n);
+ }
+ }
+ return ails;
+
+ } else if (h == fourcc("ilar") && (io_flags & IO_FLAG_SKIP_IVF_DATA)) {
+ // code is always ilxx where xx is specific to the type of invlists we
+ // want so we get the 16 high bits from the io_flag and the 16 low bits
+ // as "il"
+ int h2 = (io_flags & 0xffff0000) | (fourcc("il__") & 0x0000ffff);
+ size_t nlist, code_size;
+ READ1(nlist);
+ READ1(code_size);
+ std::vector<size_t> sizes(nlist);
+ read_ArrayInvertedLists_sizes(f, sizes);
+ return InvertedListsIOHook::lookup(h2)->read_ArrayInvertedLists(
+ f, io_flags, nlist, code_size, sizes);
+ } else {
+ return InvertedListsIOHook::lookup(h)->read(f, io_flags);
+ }
+}
+
+void read_InvertedLists(IndexIVF* ivf, IOReader* f, int io_flags) {
+ InvertedLists* ils = read_InvertedLists(f, io_flags);
+ if (ils) {
+ FAISS_THROW_IF_NOT(ils->nlist == ivf->nlist);
+ FAISS_THROW_IF_NOT(
+ ils->code_size == InvertedLists::INVALID_CODE_SIZE ||
+ ils->code_size == ivf->code_size);
+ }
+ ivf->invlists = ils;
+ ivf->own_invlists = true;
+}
+
+void read_ProductQuantizer(ProductQuantizer* pq, IOReader* f) {
+ READ1(pq->d);
+ READ1(pq->M);
+ READ1(pq->nbits);
+ pq->set_derived_values();
+ READVECTOR(pq->centroids);
+}
+
+static void read_ResidualQuantizer_old(ResidualQuantizer* rq, IOReader* f) {
+ READ1(rq->d);
+ READ1(rq->M);
+ READVECTOR(rq->nbits);
+ READ1(rq->is_trained);
+ READ1(rq->train_type);
+ READ1(rq->max_beam_size);
+ READVECTOR(rq->codebooks);
+ READ1(rq->search_type);
+ READ1(rq->norm_min);
+ READ1(rq->norm_max);
+ rq->set_derived_values();
+}
+
+static void read_AdditiveQuantizer(AdditiveQuantizer* aq, IOReader* f) {
+ READ1(aq->d);
+ READ1(aq->M);
+ READVECTOR(aq->nbits);
+ READ1(aq->is_trained);
+ READVECTOR(aq->codebooks);
+ READ1(aq->search_type);
+ READ1(aq->norm_min);
+ READ1(aq->norm_max);
+ if (aq->search_type == AdditiveQuantizer::ST_norm_cqint8 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_cqint4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_lsq2x4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_rq2x4) {
+ read_xb_vector(aq->qnorm.codes, f);
+ aq->qnorm.ntotal = aq->qnorm.codes.size() / 4;
+ aq->qnorm.update_permutation();
+ }
+
+ if (aq->search_type == AdditiveQuantizer::ST_norm_lsq2x4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_rq2x4) {
+ READVECTOR(aq->norm_tabs);
+ }
+
+ aq->set_derived_values();
+}
+
+static void read_ResidualQuantizer(
+ ResidualQuantizer* rq,
+ IOReader* f,
+ int io_flags) {
+ read_AdditiveQuantizer(rq, f);
+ READ1(rq->train_type);
+ READ1(rq->max_beam_size);
+ if ((rq->train_type & ResidualQuantizer::Skip_codebook_tables) ||
+ (io_flags & IO_FLAG_SKIP_PRECOMPUTE_TABLE)) {
+ // don't precompute the tables
+ } else {
+ rq->compute_codebook_tables();
+ }
+}
+
+static void read_LocalSearchQuantizer(LocalSearchQuantizer* lsq, IOReader* f) {
+ read_AdditiveQuantizer(lsq, f);
+ READ1(lsq->K);
+ READ1(lsq->train_iters);
+ READ1(lsq->encode_ils_iters);
+ READ1(lsq->train_ils_iters);
+ READ1(lsq->icm_iters);
+ READ1(lsq->p);
+ READ1(lsq->lambd);
+ READ1(lsq->chunk_size);
+ READ1(lsq->random_seed);
+ READ1(lsq->nperts);
+ READ1(lsq->update_codebooks_with_double);
+}
+
+static void read_ProductAdditiveQuantizer(
+ ProductAdditiveQuantizer* paq,
+ IOReader* f) {
+ read_AdditiveQuantizer(paq, f);
+ READ1(paq->nsplits);
+}
+
+static void read_ProductResidualQuantizer(
+ ProductResidualQuantizer* prq,
+ IOReader* f,
+ int io_flags) {
+ read_ProductAdditiveQuantizer(prq, f);
+
+ for (size_t i = 0; i < prq->nsplits; i++) {
+ auto rq = new ResidualQuantizer();
+ read_ResidualQuantizer(rq, f, io_flags);
+ prq->quantizers.push_back(rq);
+ }
+}
+
+static void read_ProductLocalSearchQuantizer(
+ ProductLocalSearchQuantizer* plsq,
+ IOReader* f) {
+ read_ProductAdditiveQuantizer(plsq, f);
+
+ for (size_t i = 0; i < plsq->nsplits; i++) {
+ auto lsq = new LocalSearchQuantizer();
+ read_LocalSearchQuantizer(lsq, f);
+ plsq->quantizers.push_back(lsq);
+ }
+}
+
+void read_ScalarQuantizer(ScalarQuantizer* ivsc, IOReader* f) {
+ READ1(ivsc->qtype);
+ READ1(ivsc->rangestat);
+ READ1(ivsc->rangestat_arg);
+ READ1(ivsc->d);
+ READ1(ivsc->code_size);
+ READVECTOR(ivsc->trained);
+ ivsc->set_derived_sizes();
+}
+
+// Modified version of READ1
+#define READ1_AND_COUNT(var, count_var, reader_f) \
+ do { \
+ READANDCHECK(&(var), 1); \
+ (count_var) += sizeof(var); \
+ } while (0)
+
+// Modified version of READVECTOR
+#define READVECTOR_AND_COUNT(vec, count_var, reader_f) \
+ do { \
+ size_t size; \
+ READANDCHECK(&size, 1); \
+ (count_var) += sizeof(size_t); \
+ FAISS_THROW_IF_NOT(size >= 0 && size < (uint64_t{1} << 40)); \
+ (vec).resize(size); \
+ size_t bytes_to_read = \
+ size * sizeof(typename decltype(vec)::value_type); \
+ READANDCHECK((vec).data(), size); \
+ (count_var) += bytes_to_read; \
+ } while (0)
+
+static void read_HNSW(
+ HNSW* hnsw,
+ IOReader* f,
+ const HNSWIndexConfig& config = HNSWIndexConfig()) {
+ if (!config.is_compact && config.is_skip_neighbors) {
+ throw std::invalid_argument(
+ "Skipping neighbors data is not allowed for non-compact HNSW indices.");
+ }
+ printf("[read_HNSW - CSR NL v4] Reading metadata & CSR indices (manual offset)...\n");
+ uint64_t calculated_offset = 0;
+
+ READVECTOR_AND_COUNT(hnsw->assign_probas, calculated_offset, f);
+ READVECTOR_AND_COUNT(hnsw->cum_nneighbor_per_level, calculated_offset, f);
+ READVECTOR_AND_COUNT(hnsw->levels, calculated_offset, f);
+
+ printf("[read_HNSW NL v4] Read levels vector, size: %zd\n",
+ hnsw->levels.size());
+
+ if (config.is_compact) {
+ bool compact_flag_read;
+ READ1_AND_COUNT(compact_flag_read, calculated_offset, f);
+ FAISS_THROW_IF_NOT_MSG(
+ compact_flag_read == true, "Expected CSR format flag in file.");
+ hnsw->storage_is_compact = compact_flag_read;
+
+ printf("[read_HNSW NL v4] Reading Compact Storage format indices...\n");
+
+ READVECTOR_AND_COUNT(hnsw->compact_level_ptr, calculated_offset, f);
+ printf("[read_HNSW NL v4] Read compact_level_ptr, size: %zd\n",
+ hnsw->compact_level_ptr.size());
+ READVECTOR_AND_COUNT(hnsw->compact_node_offsets, calculated_offset, f);
+ printf("[read_HNSW NL v4] Read compact_node_offsets, size: %zd\n",
+ hnsw->compact_node_offsets.size());
+ FAISS_THROW_IF_NOT(
+ hnsw->compact_node_offsets.size() == hnsw->levels.size() + 1);
+ } else {
+ printf("[READ_HNSW] Reading Original Storage format...\n");
+
+ // --- BEGIN INSERTED CODE for handling potential extra byte ---
+ printf("[READ_HNSW] Probing for potential extra byte before non-compact offsets...\n");
+
+ // Get reader type for potential rewind
+ FileIOReader* file_reader_nc = dynamic_cast<FileIOReader*>(f);
+ MappedFileIOReader* mmap_reader_nc =
+ dynamic_cast<MappedFileIOReader*>(f);
+
+ off_t pos_before_probe = -1;
+ if (file_reader_nc) {
+ pos_before_probe = ftell(file_reader_nc->f);
+ if (pos_before_probe == -1) {
+ int RTERRNO = errno;
+ FAISS_THROW_FMT(
+ "ftell failed before extra byte probe: %s",
+ strerror(RTERRNO));
+ }
+ } else if (mmap_reader_nc) {
+ pos_before_probe = (off_t)mmap_reader_nc->pos;
+ }
+ // else: maybe print warning or throw for unknown reader if rewind is
+ // needed
+
+ uint8_t suspected_flag;
+ size_t read_count =
+ (*f)(&suspected_flag, 1, 1); // Tentatively read 1 byte
+
+ bool is_back_to_original_position = true;
+ if (read_count == 1) {
+ // Successfully read one byte
+ if (suspected_flag == 0x00) {
+ // It's exactly 0x00. Assume it's the unexpected 'false' flag.
+ // Consume it.
+ printf("[READ_HNSW] Found and consumed an unexpected 0x00 byte.\n");
+ is_back_to_original_position = false;
+ } else if (suspected_flag == 0x01) {
+ printf("is_compact is false, but we read 0x01\n");
+ assert(false);
+ }
+ } else {
+ // Failed to read (e.g., EOF). Cannot consume or rewind.
+ printf("[READ_HNSW] Warning: Failed to probe for extra byte (read_count=%zu).\n",
+ read_count);
+ // Proceed assuming no extra byte, rewind is not needed/possible.
+ }
+
+ // If the byte read was not the specific 0x00 we decided to consume,
+ // rewind.
+ if (read_count == 1 && is_back_to_original_position) {
+ FAISS_ASSERT_MSG(
+ pos_before_probe != -1,
+ "Cannot rewind reader, initial position unknown for rewind.");
+ if (file_reader_nc) {
+ if (fseek(file_reader_nc->f, pos_before_probe, SEEK_SET) != 0) {
+ int RTERRNO = errno;
+ FAISS_THROW_FMT(
+ "fseek failed to rewind to original position. errno=%d (%s)",
+ RTERRNO,
+ strerror(RTERRNO));
+ }
+ printf("[READ_HNSW] Rewound to original position for FileIOReader.\n");
+ } else if (mmap_reader_nc) {
+ mmap_reader_nc->pos = pos_before_probe;
+ printf("[READ_HNSW] Reset MappedFileIOReader pos to original position.\n");
+ } else {
+ FAISS_THROW_MSG("Cannot rewind unknown reader type.");
+ }
+ }
+ // --- END INSERTED CODE ---
+
+ // --- Read Original Storage data ---
+ READVECTOR(hnsw->offsets);
+ // Use the specific read_vector function for MaybeOwnedVector
+ read_vector(hnsw->neighbors, f);
+ printf("[READ_HNSW] Original Storage sizes: offsets=%zd, neighbors=%zd\n",
+ hnsw->offsets.size(),
+ hnsw->neighbors.size());
+ }
+
+ READ1_AND_COUNT(hnsw->entry_point, calculated_offset, f);
+ READ1_AND_COUNT(hnsw->max_level, calculated_offset, f);
+ READ1_AND_COUNT(hnsw->efConstruction, calculated_offset, f);
+ READ1_AND_COUNT(hnsw->efSearch, calculated_offset, f);
+
+ // hnsw->max_level = 0;
+
+ READ1_DUMMY(int)
+ calculated_offset += sizeof(int);
+
+ printf("[read_HNSW NL v4] Read entry_point: %ld, max_level: %d\n",
+ (long)hnsw->entry_point,
+ hnsw->max_level);
+
+ if (config.is_compact) {
+ uint32_t storage_fourcc;
+ READ1_AND_COUNT(storage_fourcc, calculated_offset, f);
+ printf("[read_HNSW NL v4] Read storage fourcc: 0x%x\n", storage_fourcc);
+
+ // Attempt to determine the reader type
+ FileIOReader* file_reader = dynamic_cast<FileIOReader*>(f);
+ MappedFileIOReader* mmap_reader = dynamic_cast<MappedFileIOReader*>(f);
+
+ // Initialize offset before obtaining it
+ hnsw->neighbors_start_offset = -1; // Default to invalid
+
+ // Get the current position *after* reading storage_fourcc.
+ // This position points to the start of the 8-byte size field for the
+ // neighbors vector.
+ if (file_reader != nullptr) {
+ long current_pos = ftell(file_reader->f);
+ if (current_pos == -1) {
+ int RTERRNO = errno;
+ FAISS_THROW_FMT(
+ "ftell failed after reading storage_fourcc: %s",
+ strerror(RTERRNO));
+ }
+ hnsw->neighbors_start_offset = (off_t)current_pos;
+ printf("[read_HNSW NL v4 FIX] Detected FileIOReader. Neighbors size field offset: %ld\n",
+ (long)hnsw->neighbors_start_offset);
+ } else if (mmap_reader != nullptr) {
+ // For MappedFileIOReader, 'pos' is the relevant offset within the
+ // map
+ hnsw->neighbors_start_offset =
+ (off_t)mmap_reader->pos; // pos is size_t, cast to off_t
+ printf("[read_HNSW NL v4 FIX] Detected MappedFileIOReader. Neighbors size field relative offset: %zu\n",
+ mmap_reader->pos);
+ } else {
+ // Handle unexpected reader types if necessary, or assume only these
+ // two
+ printf("[read_HNSW NL v4 FIX] Warning: Unknown IOReader type. Cannot reliably determine neighbor offset.\n");
+ // Optionally: FAISS_THROW_MSG("Unsupported IOReader for HNSW
+ // neighbor offset detection");
+ }
+
+ // Ensure the offset was successfully obtained if using file reader
+ if (file_reader != nullptr) {
+ FAISS_THROW_IF_NOT_FMT(
+ hnsw->neighbors_start_offset >= 0,
+ "Failed to obtain valid file offset (ftell result: %ld)",
+ (long)hnsw->neighbors_start_offset);
+ }
+
+ if (config.is_skip_neighbors) {
+ printf("[read_HNSW NL v4] Skipping neighbors data.\n");
+
+ // Determine the type of reader and handle accordingly
+ FileIOReader* file_reader = dynamic_cast<FileIOReader*>(f);
+ MappedFileIOReader* mmap_reader =
+ dynamic_cast<MappedFileIOReader*>(f);
+
+ // Set flag that neighbors should be read on-demand
+ hnsw->neighbors_on_disk = true;
+
+ if (file_reader) {
+ // --- FileIOReader case: use file offset + pread ---
+ printf("[read_HNSW NL v4] Using FileIOReader, will read on demand with pread.\n");
+
+ // Set flag that we're using pread (not mmap)
+ hnsw->neighbors_use_mmap = false;
+
+ // Read the size field (8 bytes) to skip past it
+ size_t neighbors_size_field;
+ if ((*f)(&neighbors_size_field, sizeof(size_t), 1) != 1) {
+ FAISS_THROW_MSG(
+ "Failed to read neighbors size field while skipping");
+ }
+
+ // Calculate bytes to skip
+ size_t neighbors_bytes =
+ neighbors_size_field * sizeof(HNSW::storage_idx_t);
+
+ // Skip past the neighbor data
+ if (fseek(file_reader->f, neighbors_bytes, SEEK_CUR) != 0) {
+ int RTERRNO = errno;
+ FAISS_THROW_FMT(
+ "fseek failed to skip %zu bytes of neighbor data: %s",
+ neighbors_bytes,
+ strerror(RTERRNO));
+ }
+
+ printf("[read_HNSW NL v4] Skipped %zu bytes of neighbor data.\n",
+ neighbors_bytes);
+
+ } else if (mmap_reader) {
+ // --- MappedFileIOReader case: use memory pointer ---
+ printf("[read_HNSW NL v4] Using MappedFileIOReader, will access via memory pointer.\n");
+
+ // Set flag that we're using mmap
+ hnsw->neighbors_use_mmap = true;
+
+ // Record current position (pointing to size field) for
+ // debugging
+ hnsw->neighbors_start_offset = mmap_reader->pos;
+
+ // Read the size field (8 bytes) to skip past it
+ size_t neighbors_size_field;
+ if ((*f)(&neighbors_size_field, sizeof(size_t), 1) != 1) {
+ FAISS_THROW_MSG(
+ "Failed to read neighbors size field while skipping (mmap)");
+ }
+
+ // Store the memory pointer where neighbors data starts (right
+ // after size field) At this point, pos is positioned at the
+ // start of actual data
+ hnsw->neighbors_mmap_ptr =
+ (HNSW::storage_idx_t*)((char*)mmap_reader->mmap_owner
+ ->data() +
+ mmap_reader->pos);
+
+ printf("[read_HNSW NL v4] Neighbor data starts at mmap offset (relative): %zu, pointer: %p\n",
+ mmap_reader->pos,
+ (void*)hnsw->neighbors_mmap_ptr);
+
+ // Calculate bytes to skip and the end position
+ size_t neighbors_bytes =
+ neighbors_size_field * sizeof(HNSW::storage_idx_t);
+ size_t end_pos = mmap_reader->pos + neighbors_bytes;
+
+ // Check boundary
+ FAISS_THROW_IF_NOT_FMT(
+ end_pos <= mmap_reader->mmap_owner->size(),
+ "Attempt to skip past mmap region (current pos %zu, skip %zu, total size %zu)",
+ mmap_reader->pos,
+ neighbors_bytes,
+ mmap_reader->mmap_owner->size());
+
+ // Advance mmap reader's position to skip data
+ mmap_reader->pos = end_pos;
+
+ printf("[read_HNSW NL v4] Advanced mmap reader pos by %zu bytes to %zu.\n",
+ neighbors_bytes,
+ mmap_reader->pos);
+
+ } else {
+ // Unsupported reader type
+ FAISS_THROW_MSG(
+ "Skipping neighbors requires FileIOReader or MappedFileIOReader");
+ }
+
+ } else {
+ printf("[read_HNSW NL v4] Reading neighbors data into memory.\n");
+
+ // Read neighbors into memory as before
+ hnsw->neighbors_on_disk = false;
+ hnsw->neighbors_use_mmap = false;
+ READVECTOR_AND_COUNT(
+ hnsw->compact_neighbors_data, calculated_offset, f);
+ printf("[read_HNSW NL v4] Read neighbors data, size: %zd\n",
+ hnsw->compact_neighbors_data.size());
+ }
+ }
+ printf("[read_HNSW NL v4] Finished reading metadata and CSR indices.\n");
+}
+
+static void read_NSG(NSG* nsg, IOReader* f) {
+ READ1(nsg->ntotal);
+ READ1(nsg->R);
+ READ1(nsg->L);
+ READ1(nsg->C);
+ READ1(nsg->search_L);
+ READ1(nsg->enterpoint);
+ READ1(nsg->is_built);
+
+ if (!nsg->is_built) {
+ return;
+ }
+
+ constexpr int EMPTY_ID = -1;
+ int N = nsg->ntotal;
+ int R = nsg->R;
+ auto& graph = nsg->final_graph;
+ graph = std::make_shared<nsg::Graph<int>>(N, R);
+ std::fill_n(graph->data, N * R, EMPTY_ID);
+
+ for (int i = 0; i < N; i++) {
+ for (int j = 0; j < R + 1; j++) {
+ int id;
+ READ1(id);
+ if (id != EMPTY_ID) {
+ graph->at(i, j) = id;
+ } else {
+ break;
+ }
+ }
+ }
+}
+
+static void read_NNDescent(NNDescent* nnd, IOReader* f) {
+ READ1(nnd->ntotal);
+ READ1(nnd->d);
+ READ1(nnd->K);
+ READ1(nnd->S);
+ READ1(nnd->R);
+ READ1(nnd->L);
+ READ1(nnd->iter);
+ READ1(nnd->search_L);
+ READ1(nnd->random_seed);
+ READ1(nnd->has_built);
+
+ READVECTOR(nnd->final_graph);
+}
+
+ProductQuantizer* read_ProductQuantizer(const char* fname) {
+ FileIOReader reader(fname);
+ return read_ProductQuantizer(&reader);
+}
+
+ProductQuantizer* read_ProductQuantizer(IOReader* reader) {
+ ProductQuantizer* pq = new ProductQuantizer();
+ std::unique_ptr<ProductQuantizer> del(pq);
+
+ read_ProductQuantizer(pq, reader);
+ del.release();
+ return pq;
+}
+
+static void read_RaBitQuantizer(RaBitQuantizer* rabitq, IOReader* f) {
+ // don't care about rabitq->centroid
+ READ1(rabitq->d);
+ READ1(rabitq->code_size);
+}
+
+void read_direct_map(DirectMap* dm, IOReader* f) {
+ char maintain_direct_map;
+ READ1(maintain_direct_map);
+ dm->type = (DirectMap::Type)maintain_direct_map;
+ READVECTOR(dm->array);
+ if (dm->type == DirectMap::Hashtable) {
+ std::vector<std::pair<idx_t, idx_t>> v;
+ READVECTOR(v);
+ std::unordered_map<idx_t, idx_t>& map = dm->hashtable;
+ map.reserve(v.size());
+ for (auto it : v) {
+ map[it.first] = it.second;
+ }
+ }
+}
+
+void read_ivf_header(
+ IndexIVF* ivf,
+ IOReader* f,
+ std::vector<std::vector<idx_t>>* ids) {
+ read_index_header(ivf, f);
+ READ1(ivf->nlist);
+ READ1(ivf->nprobe);
+ ivf->quantizer = read_index(f);
+ ivf->own_fields = true;
+ if (ids) { // used in legacy "Iv" formats
+ ids->resize(ivf->nlist);
+ for (size_t i = 0; i < ivf->nlist; i++)
+ READVECTOR((*ids)[i]);
+ }
+ read_direct_map(&ivf->direct_map, f);
+}
+
+// used for legacy formats
+ArrayInvertedLists* set_array_invlist(
+ IndexIVF* ivf,
+ std::vector<std::vector<idx_t>>& ids) {
+ ArrayInvertedLists* ail =
+ new ArrayInvertedLists(ivf->nlist, ivf->code_size);
+
+ ail->ids.resize(ids.size());
+ for (size_t i = 0; i < ids.size(); i++) {
+ ail->ids[i] = MaybeOwnedVector<idx_t>(std::move(ids[i]));
+ }
+
+ ivf->invlists = ail;
+ ivf->own_invlists = true;
+ return ail;
+}
+
+static IndexIVFPQ* read_ivfpq(IOReader* f, uint32_t h, int io_flags) {
+ bool legacy = h == fourcc("IvQR") || h == fourcc("IvPQ");
+
+ IndexIVFPQR* ivfpqr = h == fourcc("IvQR") || h == fourcc("IwQR")
+ ? new IndexIVFPQR()
+ : nullptr;
+ IndexIVFPQ* ivpq = ivfpqr ? ivfpqr : new IndexIVFPQ();
+
+ std::vector<std::vector<idx_t>> ids;
+ read_ivf_header(ivpq, f, legacy ? &ids : nullptr);
+ READ1(ivpq->by_residual);
+ READ1(ivpq->code_size);
+ read_ProductQuantizer(&ivpq->pq, f);
+
+ if (legacy) {
+ ArrayInvertedLists* ail = set_array_invlist(ivpq, ids);
+ for (size_t i = 0; i < ail->nlist; i++)
+ READVECTOR(ail->codes[i]);
+ } else {
+ read_InvertedLists(ivpq, f, io_flags);
+ }
+
+ if (ivpq->is_trained) {
+ // precomputed table not stored. It is cheaper to recompute it.
+ // precompute_table() may be disabled with a flag.
+ ivpq->use_precomputed_table = 0;
+ if (ivpq->by_residual) {
+ if ((io_flags & IO_FLAG_SKIP_PRECOMPUTE_TABLE) == 0) {
+ ivpq->precompute_table();
+ }
+ }
+ if (ivfpqr) {
+ read_ProductQuantizer(&ivfpqr->refine_pq, f);
+ READVECTOR(ivfpqr->refine_codes);
+ READ1(ivfpqr->k_factor);
+ }
+ }
+ return ivpq;
+}
+
+int read_old_fmt_hack = 0;
+
+Index* read_index(
+ IOReader* f,
+ int io_flags,
+ const HNSWIndexConfig& hnsw_config) {
+ Index* idx = nullptr;
+ uint32_t h;
+ READ1(h);
+ if (h == fourcc("null")) {
+ // denotes a missing index, useful for some cases
+ return nullptr;
+ } else if (
+ h == fourcc("IxFI") || h == fourcc("IxF2") || h == fourcc("IxFl")) {
+ IndexFlat* idxf;
+ if (h == fourcc("IxFI")) {
+ idxf = new IndexFlatIP();
+ } else if (h == fourcc("IxF2")) {
+ idxf = new IndexFlatL2();
+ } else {
+ idxf = new IndexFlat();
+ }
+ read_index_header(idxf, f);
+ idxf->code_size = idxf->d * sizeof(float);
+ read_xb_vector(idxf->codes, f);
+ FAISS_THROW_IF_NOT(
+ idxf->codes.size() == idxf->ntotal * idxf->code_size);
+ // leak!
+ idx = idxf;
+ } else if (h == fourcc("IxHE") || h == fourcc("IxHe")) {
+ IndexLSH* idxl = new IndexLSH();
+ read_index_header(idxl, f);
+ READ1(idxl->nbits);
+ READ1(idxl->rotate_data);
+ READ1(idxl->train_thresholds);
+ READVECTOR(idxl->thresholds);
+ int code_size_i;
+ READ1(code_size_i);
+ idxl->code_size = code_size_i;
+ if (h == fourcc("IxHE")) {
+ FAISS_THROW_IF_NOT_FMT(
+ idxl->nbits % 64 == 0,
+ "can only read old format IndexLSH with "
+ "nbits multiple of 64 (got %d)",
+ (int)idxl->nbits);
+ // leak
+ idxl->code_size *= 8;
+ }
+ {
+ RandomRotationMatrix* rrot = dynamic_cast<RandomRotationMatrix*>(
+ read_VectorTransform(f));
+ FAISS_THROW_IF_NOT_MSG(rrot, "expected a random rotation");
+ idxl->rrot = *rrot;
+ delete rrot;
+ }
+ read_vector(idxl->codes, f);
+ FAISS_THROW_IF_NOT(
+ idxl->rrot.d_in == idxl->d && idxl->rrot.d_out == idxl->nbits);
+ FAISS_THROW_IF_NOT(
+ idxl->codes.size() == idxl->ntotal * idxl->code_size);
+ idx = idxl;
+ } else if (
+ h == fourcc("IxPQ") || h == fourcc("IxPo") || h == fourcc("IxPq")) {
+ // IxPQ and IxPo were merged into the same IndexPQ object
+ IndexPQ* idxp = new IndexPQ();
+ read_index_header(idxp, f);
+ read_ProductQuantizer(&idxp->pq, f);
+ idxp->code_size = idxp->pq.code_size;
+ read_vector(idxp->codes, f);
+ if (h == fourcc("IxPo") || h == fourcc("IxPq")) {
+ READ1(idxp->search_type);
+ READ1(idxp->encode_signs);
+ READ1(idxp->polysemous_ht);
+ }
+ // Old versions of PQ all had metric_type set to INNER_PRODUCT
+ // when they were in fact using L2. Therefore, we force metric type
+ // to L2 when the old format is detected
+ if (h == fourcc("IxPQ") || h == fourcc("IxPo")) {
+ idxp->metric_type = METRIC_L2;
+ }
+ idx = idxp;
+ } else if (h == fourcc("IxRQ") || h == fourcc("IxRq")) {
+ IndexResidualQuantizer* idxr = new IndexResidualQuantizer();
+ read_index_header(idxr, f);
+ if (h == fourcc("IxRQ")) {
+ read_ResidualQuantizer_old(&idxr->rq, f);
+ } else {
+ read_ResidualQuantizer(&idxr->rq, f, io_flags);
+ }
+ READ1(idxr->code_size);
+ read_vector(idxr->codes, f);
+ idx = idxr;
+ } else if (h == fourcc("IxLS")) {
+ auto idxr = new IndexLocalSearchQuantizer();
+ read_index_header(idxr, f);
+ read_LocalSearchQuantizer(&idxr->lsq, f);
+ READ1(idxr->code_size);
+ read_vector(idxr->codes, f);
+ idx = idxr;
+ } else if (h == fourcc("IxPR")) {
+ auto idxpr = new IndexProductResidualQuantizer();
+ read_index_header(idxpr, f);
+ read_ProductResidualQuantizer(&idxpr->prq, f, io_flags);
+ READ1(idxpr->code_size);
+ read_vector(idxpr->codes, f);
+ idx = idxpr;
+ } else if (h == fourcc("IxPL")) {
+ auto idxpl = new IndexProductLocalSearchQuantizer();
+ read_index_header(idxpl, f);
+ read_ProductLocalSearchQuantizer(&idxpl->plsq, f);
+ READ1(idxpl->code_size);
+ read_vector(idxpl->codes, f);
+ idx = idxpl;
+ } else if (h == fourcc("ImRQ")) {
+ ResidualCoarseQuantizer* idxr = new ResidualCoarseQuantizer();
+ read_index_header(idxr, f);
+ read_ResidualQuantizer(&idxr->rq, f, io_flags);
+ READ1(idxr->beam_factor);
+ if (io_flags & IO_FLAG_SKIP_PRECOMPUTE_TABLE) {
+ // then we force the beam factor to -1
+ // which skips the table precomputation.
+ idxr->beam_factor = -1;
+ }
+ idxr->set_beam_factor(idxr->beam_factor);
+ idx = idxr;
+ } else if (
+ h == fourcc("ILfs") || h == fourcc("IRfs") || h == fourcc("IPRf") ||
+ h == fourcc("IPLf")) {
+ bool is_LSQ = h == fourcc("ILfs");
+ bool is_RQ = h == fourcc("IRfs");
+ bool is_PLSQ = h == fourcc("IPLf");
+
+ IndexAdditiveQuantizerFastScan* idxaqfs;
+ if (is_LSQ) {
+ idxaqfs = new IndexLocalSearchQuantizerFastScan();
+ } else if (is_RQ) {
+ idxaqfs = new IndexResidualQuantizerFastScan();
+ } else if (is_PLSQ) {
+ idxaqfs = new IndexProductLocalSearchQuantizerFastScan();
+ } else {
+ idxaqfs = new IndexProductResidualQuantizerFastScan();
+ }
+ read_index_header(idxaqfs, f);
+
+ if (is_LSQ) {
+ read_LocalSearchQuantizer((LocalSearchQuantizer*)idxaqfs->aq, f);
+ } else if (is_RQ) {
+ read_ResidualQuantizer(
+ (ResidualQuantizer*)idxaqfs->aq, f, io_flags);
+ } else if (is_PLSQ) {
+ read_ProductLocalSearchQuantizer(
+ (ProductLocalSearchQuantizer*)idxaqfs->aq, f);
+ } else {
+ read_ProductResidualQuantizer(
+ (ProductResidualQuantizer*)idxaqfs->aq, f, io_flags);
+ }
+
+ READ1(idxaqfs->implem);
+ READ1(idxaqfs->bbs);
+ READ1(idxaqfs->qbs);
+
+ READ1(idxaqfs->M);
+ READ1(idxaqfs->nbits);
+ READ1(idxaqfs->ksub);
+ READ1(idxaqfs->code_size);
+ READ1(idxaqfs->ntotal2);
+ READ1(idxaqfs->M2);
+
+ READ1(idxaqfs->rescale_norm);
+ READ1(idxaqfs->norm_scale);
+ READ1(idxaqfs->max_train_points);
+
+ READVECTOR(idxaqfs->codes);
+ idx = idxaqfs;
+ } else if (
+ h == fourcc("IVLf") || h == fourcc("IVRf") || h == fourcc("NPLf") ||
+ h == fourcc("NPRf")) {
+ bool is_LSQ = h == fourcc("IVLf");
+ bool is_RQ = h == fourcc("IVRf");
+ bool is_PLSQ = h == fourcc("NPLf");
+
+ IndexIVFAdditiveQuantizerFastScan* ivaqfs;
+ if (is_LSQ) {
+ ivaqfs = new IndexIVFLocalSearchQuantizerFastScan();
+ } else if (is_RQ) {
+ ivaqfs = new IndexIVFResidualQuantizerFastScan();
+ } else if (is_PLSQ) {
+ ivaqfs = new IndexIVFProductLocalSearchQuantizerFastScan();
+ } else {
+ ivaqfs = new IndexIVFProductResidualQuantizerFastScan();
+ }
+ read_ivf_header(ivaqfs, f);
+
+ if (is_LSQ) {
+ read_LocalSearchQuantizer((LocalSearchQuantizer*)ivaqfs->aq, f);
+ } else if (is_RQ) {
+ read_ResidualQuantizer((ResidualQuantizer*)ivaqfs->aq, f, io_flags);
+ } else if (is_PLSQ) {
+ read_ProductLocalSearchQuantizer(
+ (ProductLocalSearchQuantizer*)ivaqfs->aq, f);
+ } else {
+ read_ProductResidualQuantizer(
+ (ProductResidualQuantizer*)ivaqfs->aq, f, io_flags);
+ }
+
+ READ1(ivaqfs->by_residual);
+ READ1(ivaqfs->implem);
+ READ1(ivaqfs->bbs);
+ READ1(ivaqfs->qbs);
+
+ READ1(ivaqfs->M);
+ READ1(ivaqfs->nbits);
+ READ1(ivaqfs->ksub);
+ READ1(ivaqfs->code_size);
+ READ1(ivaqfs->qbs2);
+ READ1(ivaqfs->M2);
+
+ READ1(ivaqfs->rescale_norm);
+ READ1(ivaqfs->norm_scale);
+ READ1(ivaqfs->max_train_points);
+
+ read_InvertedLists(ivaqfs, f, io_flags);
+ ivaqfs->init_code_packer();
+ idx = ivaqfs;
+ } else if (h == fourcc("IvFl") || h == fourcc("IvFL")) { // legacy
+ IndexIVFFlat* ivfl = new IndexIVFFlat();
+ std::vector<std::vector<idx_t>> ids;
+ read_ivf_header(ivfl, f, &ids);
+ ivfl->code_size = ivfl->d * sizeof(float);
+ ArrayInvertedLists* ail = set_array_invlist(ivfl, ids);
+
+ if (h == fourcc("IvFL")) {
+ for (size_t i = 0; i < ivfl->nlist; i++) {
+ READVECTOR(ail->codes[i]);
+ }
+ } else { // old format
+ for (size_t i = 0; i < ivfl->nlist; i++) {
+ std::vector<float> vec;
+ READVECTOR(vec);
+ ail->codes[i].resize(vec.size() * sizeof(float));
+ memcpy(ail->codes[i].data(), vec.data(), ail->codes[i].size());
+ }
+ }
+ idx = ivfl;
+ } else if (h == fourcc("IwFd")) {
+ IndexIVFFlatDedup* ivfl = new IndexIVFFlatDedup();
+ read_ivf_header(ivfl, f);
+ ivfl->code_size = ivfl->d * sizeof(float);
+ {
+ std::vector<idx_t> tab;
+ READVECTOR(tab);
+ for (long i = 0; i < tab.size(); i += 2) {
+ std::pair<idx_t, idx_t> pair(tab[i], tab[i + 1]);
+ ivfl->instances.insert(pair);
+ }
+ }
+ read_InvertedLists(ivfl, f, io_flags);
+ idx = ivfl;
+ } else if (h == fourcc("IwFl")) {
+ IndexIVFFlat* ivfl = new IndexIVFFlat();
+ read_ivf_header(ivfl, f);
+ ivfl->code_size = ivfl->d * sizeof(float);
+ read_InvertedLists(ivfl, f, io_flags);
+ idx = ivfl;
+ } else if (h == fourcc("IxSQ")) {
+ IndexScalarQuantizer* idxs = new IndexScalarQuantizer();
+ read_index_header(idxs, f);
+ read_ScalarQuantizer(&idxs->sq, f);
+ read_vector(idxs->codes, f);
+ idxs->code_size = idxs->sq.code_size;
+ idx = idxs;
+ } else if (h == fourcc("IxLa")) {
+ int d, nsq, scale_nbit, r2;
+ READ1(d);
+ READ1(nsq);
+ READ1(scale_nbit);
+ READ1(r2);
+ IndexLattice* idxl = new IndexLattice(d, nsq, scale_nbit, r2);
+ read_index_header(idxl, f);
+ READVECTOR(idxl->trained);
+ idx = idxl;
+ } else if (h == fourcc("IvSQ")) { // legacy
+ IndexIVFScalarQuantizer* ivsc = new IndexIVFScalarQuantizer();
+ std::vector<std::vector<idx_t>> ids;
+ read_ivf_header(ivsc, f, &ids);
+ read_ScalarQuantizer(&ivsc->sq, f);
+ READ1(ivsc->code_size);
+ ArrayInvertedLists* ail = set_array_invlist(ivsc, ids);
+ for (int i = 0; i < ivsc->nlist; i++)
+ READVECTOR(ail->codes[i]);
+ idx = ivsc;
+ } else if (h == fourcc("IwSQ") || h == fourcc("IwSq")) {
+ IndexIVFScalarQuantizer* ivsc = new IndexIVFScalarQuantizer();
+ read_ivf_header(ivsc, f);
+ read_ScalarQuantizer(&ivsc->sq, f);
+ READ1(ivsc->code_size);
+ if (h == fourcc("IwSQ")) {
+ ivsc->by_residual = true;
+ } else {
+ READ1(ivsc->by_residual);
+ }
+ read_InvertedLists(ivsc, f, io_flags);
+ idx = ivsc;
+ } else if (
+ h == fourcc("IwLS") || h == fourcc("IwRQ") || h == fourcc("IwPL") ||
+ h == fourcc("IwPR")) {
+ bool is_LSQ = h == fourcc("IwLS");
+ bool is_RQ = h == fourcc("IwRQ");
+ bool is_PLSQ = h == fourcc("IwPL");
+ IndexIVFAdditiveQuantizer* iva;
+ if (is_LSQ) {
+ iva = new IndexIVFLocalSearchQuantizer();
+ } else if (is_RQ) {
+ iva = new IndexIVFResidualQuantizer();
+ } else if (is_PLSQ) {
+ iva = new IndexIVFProductLocalSearchQuantizer();
+ } else {
+ iva = new IndexIVFProductResidualQuantizer();
+ }
+ read_ivf_header(iva, f);
+ READ1(iva->code_size);
+ if (is_LSQ) {
+ read_LocalSearchQuantizer((LocalSearchQuantizer*)iva->aq, f);
+ } else if (is_RQ) {
+ read_ResidualQuantizer((ResidualQuantizer*)iva->aq, f, io_flags);
+ } else if (is_PLSQ) {
+ read_ProductLocalSearchQuantizer(
+ (ProductLocalSearchQuantizer*)iva->aq, f);
+ } else {
+ read_ProductResidualQuantizer(
+ (ProductResidualQuantizer*)iva->aq, f, io_flags);
+ }
+ READ1(iva->by_residual);
+ READ1(iva->use_precomputed_table);
+ read_InvertedLists(iva, f, io_flags);
+ idx = iva;
+ } else if (h == fourcc("IwSh")) {
+ IndexIVFSpectralHash* ivsp = new IndexIVFSpectralHash();
+ read_ivf_header(ivsp, f);
+ ivsp->vt = read_VectorTransform(f);
+ ivsp->own_fields = true;
+ READ1(ivsp->nbit);
+ // not stored by write_ivf_header
+ ivsp->code_size = (ivsp->nbit + 7) / 8;
+ READ1(ivsp->period);
+ READ1(ivsp->threshold_type);
+ READVECTOR(ivsp->trained);
+ read_InvertedLists(ivsp, f, io_flags);
+ idx = ivsp;
+ } else if (
+ h == fourcc("IvPQ") || h == fourcc("IvQR") || h == fourcc("IwPQ") ||
+ h == fourcc("IwQR")) {
+ idx = read_ivfpq(f, h, io_flags);
+ } else if (h == fourcc("IwIQ")) {
+ auto* indep = new IndexIVFIndependentQuantizer();
+ indep->own_fields = true;
+ read_index_header(indep, f);
+ indep->quantizer = read_index(f, io_flags);
+ bool has_vt;
+ READ1(has_vt);
+ if (has_vt) {
+ indep->vt = read_VectorTransform(f);
+ }
+ indep->index_ivf = dynamic_cast<IndexIVF*>(read_index(f, io_flags));
+ FAISS_THROW_IF_NOT(indep->index_ivf);
+ if (auto index_ivfpq = dynamic_cast<IndexIVFPQ*>(indep->index_ivf)) {
+ READ1(index_ivfpq->use_precomputed_table);
+ }
+ idx = indep;
+ } else if (h == fourcc("IxPT")) {
+ IndexPreTransform* ixpt = new IndexPreTransform();
+ ixpt->own_fields = true;
+ read_index_header(ixpt, f);
+ int nt;
+ if (read_old_fmt_hack == 2) {
+ nt = 1;
+ } else {
+ READ1(nt);
+ }
+ for (int i = 0; i < nt; i++) {
+ ixpt->chain.push_back(read_VectorTransform(f));
+ }
+ ixpt->index = read_index(f, io_flags);
+ idx = ixpt;
+ } else if (h == fourcc("Imiq")) {
+ MultiIndexQuantizer* imiq = new MultiIndexQuantizer();
+ read_index_header(imiq, f);
+ read_ProductQuantizer(&imiq->pq, f);
+ idx = imiq;
+ } else if (h == fourcc("IxRF")) {
+ IndexRefine* idxrf = new IndexRefine();
+ read_index_header(idxrf, f);
+ idxrf->base_index = read_index(f, io_flags);
+ idxrf->refine_index = read_index(f, io_flags);
+ READ1(idxrf->k_factor);
+ if (dynamic_cast<IndexFlat*>(idxrf->refine_index)) {
+ // then make a RefineFlat with it
+ IndexRefine* idxrf_old = idxrf;
+ idxrf = new IndexRefineFlat();
+ *idxrf = *idxrf_old;
+ delete idxrf_old;
+ }
+ idxrf->own_fields = true;
+ idxrf->own_refine_index = true;
+ idx = idxrf;
+ } else if (h == fourcc("IxMp") || h == fourcc("IxM2")) {
+ bool is_map2 = h == fourcc("IxM2");
+ IndexIDMap* idxmap = is_map2 ? new IndexIDMap2() : new IndexIDMap();
+ read_index_header(idxmap, f);
+ idxmap->index = read_index(f, io_flags);
+ idxmap->own_fields = true;
+ READVECTOR(idxmap->id_map);
+ if (is_map2) {
+ static_cast<IndexIDMap2*>(idxmap)->construct_rev_map();
+ }
+ idx = idxmap;
+ } else if (h == fourcc("Ix2L")) {
+ Index2Layer* idxp = new Index2Layer();
+ read_index_header(idxp, f);
+ idxp->q1.quantizer = read_index(f, io_flags);
+ READ1(idxp->q1.nlist);
+ READ1(idxp->q1.quantizer_trains_alone);
+ read_ProductQuantizer(&idxp->pq, f);
+ READ1(idxp->code_size_1);
+ READ1(idxp->code_size_2);
+ READ1(idxp->code_size);
+ read_vector(idxp->codes, f);
+ idx = idxp;
+ } else if (
+ h == fourcc("IHNf") || h == fourcc("IHNp") || h == fourcc("IHNs") ||
+ h == fourcc("IHN2") || h == fourcc("IHNc")) {
+ IndexHNSW* idxhnsw = nullptr;
+ if (h == fourcc("IHNf"))
+ idxhnsw = new IndexHNSWFlat();
+ if (h == fourcc("IHNp"))
+ idxhnsw = new IndexHNSWPQ();
+ if (h == fourcc("IHNs"))
+ idxhnsw = new IndexHNSWSQ();
+ if (h == fourcc("IHN2"))
+ idxhnsw = new IndexHNSW2Level();
+ if (h == fourcc("IHNc"))
+ idxhnsw = new IndexHNSWCagra();
+ read_index_header(idxhnsw, f);
+ if (h == fourcc("IHNc")) {
+ READ1(idxhnsw->keep_max_size_level0);
+ auto idx_hnsw_cagra = dynamic_cast<IndexHNSWCagra*>(idxhnsw);
+ READ1(idx_hnsw_cagra->base_level_only);
+ READ1(idx_hnsw_cagra->num_base_level_search_entrypoints);
+ }
+ read_HNSW(&idxhnsw->hnsw, f, hnsw_config);
+
+ if (hnsw_config.is_recompute) {
+ printf("INFO: Skipping external storage loading, since is_recompute is true.\n");
+ idxhnsw->is_recompute = true;
+
+ // even if is_recompute is true, when disk cache is on, we need to
+ // set the offset to the external storage path
+ if (hnsw_config.disk_cache_ratio > 0) {
+ setup_experimental_top_degree_disk_read(
+ "/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/degree_distribution.txt",
+ hnsw_config.disk_cache_ratio,
+ hnsw_config.external_storage_path,
+ 45,
+ idxhnsw->ntotal);
+ }
+ } else if (hnsw_config.external_storage_path != nullptr) {
+ // Load storage from the external file
+ printf("INFO: Loading external storage from: %s\n",
+ hnsw_config.external_storage_path);
+ // Decide reader type based on io_flags if desired (e.g.,
+ // mmap)
+ std::unique_ptr<IOReader> storage_reader;
+ if ((io_flags & IO_FLAG_MMAP_IFC) == IO_FLAG_MMAP_IFC) {
+ auto owner = std::make_shared<MmappedFileMappingOwner>(
+ hnsw_config.external_storage_path);
+ storage_reader = std::make_unique<MappedFileIOReader>(owner);
+ printf("INFO: Using MappedFileIOReader for external storage.\n");
+ } else {
+ storage_reader = std::make_unique<FileIOReader>(
+ hnsw_config.external_storage_path);
+ printf("INFO: Using FileIOReader for external storage.\n");
+ }
+
+ // Recursively call read_index for the storage part, passing
+ // flags Pass nullptr for external_storage_path in recursive
+ // call
+ idxhnsw->storage = read_index(storage_reader.get(), io_flags);
+
+ if (!idxhnsw->storage) {
+ FAISS_THROW_FMT(
+ "Failed to read external storage index from %s",
+ hnsw_config.external_storage_path);
+ }
+ printf("INFO: Successfully loaded external storage.\n");
+ // IMPORTANT: We DO NOT read storage from the primary reader 'f'
+ // anymore. 'f' remains positioned after the HNSW graph data.
+
+ } else if (io_flags & IO_FLAG_SKIP_STORAGE) {
+ // Original logic for skipping storage from primary reader
+ uint32_t null_check;
+ READ1(null_check);
+ FAISS_THROW_IF_NOT_MSG(
+ null_check == fourcc("null"),
+ "IO_FLAG_SKIP_STORAGE set, but storage field was not null");
+ idxhnsw->storage = nullptr; // Explicitly set to null
+ } else {
+ // Original logic: Read storage sequentially from primary reader 'f'
+ // Pass nullptr for external_storage_path in recursive call
+ idxhnsw->storage = read_index(f, io_flags);
+ }
+
+ idxhnsw->own_fields = idxhnsw->storage != nullptr;
+ if (h == fourcc("IHNp") && !(io_flags & IO_FLAG_PQ_SKIP_SDC_TABLE)) {
+ dynamic_cast<IndexPQ*>(idxhnsw->storage)->pq.compute_sdc_table();
+ }
+ idx = idxhnsw;
+ } else if (
+ h == fourcc("INSf") || h == fourcc("INSp") || h == fourcc("INSs")) {
+ IndexNSG* idxnsg;
+ if (h == fourcc("INSf"))
+ idxnsg = new IndexNSGFlat();
+ if (h == fourcc("INSp"))
+ idxnsg = new IndexNSGPQ();
+ if (h == fourcc("INSs"))
+ idxnsg = new IndexNSGSQ();
+ read_index_header(idxnsg, f);
+ READ1(idxnsg->GK);
+ READ1(idxnsg->build_type);
+ READ1(idxnsg->nndescent_S);
+ READ1(idxnsg->nndescent_R);
+ READ1(idxnsg->nndescent_L);
+ READ1(idxnsg->nndescent_iter);
+ read_NSG(&idxnsg->nsg, f);
+ idxnsg->storage = read_index(f, io_flags);
+ idxnsg->own_fields = true;
+ idx = idxnsg;
+ } else if (h == fourcc("INNf")) {
+ IndexNNDescent* idxnnd = new IndexNNDescentFlat();
+ read_index_header(idxnnd, f);
+ read_NNDescent(&idxnnd->nndescent, f);
+ idxnnd->storage = read_index(f, io_flags);
+ idxnnd->own_fields = true;
+ idx = idxnnd;
+ } else if (h == fourcc("IPfs")) {
+ IndexPQFastScan* idxpqfs = new IndexPQFastScan();
+ read_index_header(idxpqfs, f);
+ read_ProductQuantizer(&idxpqfs->pq, f);
+ READ1(idxpqfs->implem);
+ READ1(idxpqfs->bbs);
+ READ1(idxpqfs->qbs);
+ READ1(idxpqfs->ntotal2);
+ READ1(idxpqfs->M2);
+ READVECTOR(idxpqfs->codes);
+
+ const auto& pq = idxpqfs->pq;
+ idxpqfs->M = pq.M;
+ idxpqfs->nbits = pq.nbits;
+ idxpqfs->ksub = (1 << pq.nbits);
+ idxpqfs->code_size = pq.code_size;
+
+ idx = idxpqfs;
+
+ } else if (h == fourcc("IwPf")) {
+ IndexIVFPQFastScan* ivpq = new IndexIVFPQFastScan();
+ read_ivf_header(ivpq, f);
+ READ1(ivpq->by_residual);
+ READ1(ivpq->code_size);
+ READ1(ivpq->bbs);
+ READ1(ivpq->M2);
+ READ1(ivpq->implem);
+ READ1(ivpq->qbs2);
+ read_ProductQuantizer(&ivpq->pq, f);
+ read_InvertedLists(ivpq, f, io_flags);
+ ivpq->precompute_table();
+
+ const auto& pq = ivpq->pq;
+ ivpq->M = pq.M;
+ ivpq->nbits = pq.nbits;
+ ivpq->ksub = (1 << pq.nbits);
+ ivpq->code_size = pq.code_size;
+ ivpq->init_code_packer();
+
+ idx = ivpq;
+ } else if (h == fourcc("IRMf")) {
+ IndexRowwiseMinMax* imm = new IndexRowwiseMinMax();
+ read_index_header(imm, f);
+
+ imm->index = read_index(f, io_flags);
+ imm->own_fields = true;
+
+ idx = imm;
+ } else if (h == fourcc("IRMh")) {
+ IndexRowwiseMinMaxFP16* imm = new IndexRowwiseMinMaxFP16();
+ read_index_header(imm, f);
+
+ imm->index = read_index(f, io_flags);
+ imm->own_fields = true;
+
+ idx = imm;
+ } else if (h == fourcc("Ixrq")) {
+ IndexRaBitQ* idxq = new IndexRaBitQ();
+ read_index_header(idxq, f);
+ read_RaBitQuantizer(&idxq->rabitq, f);
+ READVECTOR(idxq->codes);
+ READVECTOR(idxq->center);
+ READ1(idxq->qb);
+ idxq->code_size = idxq->rabitq.code_size;
+ idx = idxq;
+ } else if (h == fourcc("Iwrq")) {
+ IndexIVFRaBitQ* ivrq = new IndexIVFRaBitQ();
+ read_ivf_header(ivrq, f);
+ read_RaBitQuantizer(&ivrq->rabitq, f);
+ READ1(ivrq->code_size);
+ READ1(ivrq->by_residual);
+ READ1(ivrq->qb);
+ read_InvertedLists(ivrq, f, io_flags);
+ idx = ivrq;
+ } else {
+ FAISS_THROW_FMT(
+ "Index type 0x%08x (\"%s\") not recognized",
+ h,
+ fourcc_inv_printable(h).c_str());
+ idx = nullptr;
+ }
+ return idx;
+}
+
+Index* read_index(FILE* f, int io_flags, const HNSWIndexConfig& hnsw_config) {
+ if ((io_flags & IO_FLAG_MMAP_IFC) == IO_FLAG_MMAP_IFC) {
+ // enable mmap-supporting IOReader
+ auto owner = std::make_shared<MmappedFileMappingOwner>(f);
+ MappedFileIOReader reader(owner);
+ return read_index(&reader, io_flags, hnsw_config);
+ } else {
+ FileIOReader reader(f);
+ return read_index(&reader, io_flags, hnsw_config);
+ }
+}
+
+Index* read_index(
+ const char* fname,
+ int io_flags,
+ const HNSWIndexConfig& hnsw_config) {
+ if ((io_flags & IO_FLAG_MMAP_IFC) == IO_FLAG_MMAP_IFC) {
+ // enable mmap-supporting IOReader
+ auto owner = std::make_shared<MmappedFileMappingOwner>(fname);
+ MappedFileIOReader reader(owner);
+ return read_index(&reader, io_flags, hnsw_config);
+ } else {
+ FileIOReader reader(fname);
+ Index* idx = read_index(&reader, io_flags, hnsw_config);
+ return idx;
+ }
+}
+
+VectorTransform* read_VectorTransform(const char* fname) {
+ FileIOReader reader(fname);
+ VectorTransform* vt = read_VectorTransform(&reader);
+ return vt;
+}
+
+/*************************************************************
+ * Read binary indexes
+ **************************************************************/
+
+static void read_InvertedLists(IndexBinaryIVF* ivf, IOReader* f, int io_flags) {
+ InvertedLists* ils = read_InvertedLists(f, io_flags);
+ FAISS_THROW_IF_NOT(
+ !ils ||
+ (ils->nlist == ivf->nlist && ils->code_size == ivf->code_size));
+ ivf->invlists = ils;
+ ivf->own_invlists = true;
+}
+
+static void read_index_binary_header(IndexBinary* idx, IOReader* f) {
+ READ1(idx->d);
+ READ1(idx->code_size);
+ READ1(idx->ntotal);
+ READ1(idx->is_trained);
+ READ1(idx->metric_type);
+ idx->verbose = false;
+}
+
+static void read_binary_ivf_header(
+ IndexBinaryIVF* ivf,
+ IOReader* f,
+ std::vector<std::vector<idx_t>>* ids = nullptr) {
+ read_index_binary_header(ivf, f);
+ READ1(ivf->nlist);
+ READ1(ivf->nprobe);
+ ivf->quantizer = read_index_binary(f);
+ ivf->own_fields = true;
+ if (ids) { // used in legacy "Iv" formats
+ ids->resize(ivf->nlist);
+ for (size_t i = 0; i < ivf->nlist; i++)
+ READVECTOR((*ids)[i]);
+ }
+ read_direct_map(&ivf->direct_map, f);
+}
+
+static void read_binary_hash_invlists(
+ IndexBinaryHash::InvertedListMap& invlists,
+ int b,
+ IOReader* f) {
+ size_t sz;
+ READ1(sz);
+ int il_nbit = 0;
+ READ1(il_nbit);
+ // buffer for bitstrings
+ std::vector<uint8_t> buf((b + il_nbit) * sz);
+ READVECTOR(buf);
+ BitstringReader rd(buf.data(), buf.size());
+ invlists.reserve(sz);
+ for (size_t i = 0; i < sz; i++) {
+ uint64_t hash = rd.read(b);
+ uint64_t ilsz = rd.read(il_nbit);
+ auto& il = invlists[hash];
+ READVECTOR(il.ids);
+ FAISS_THROW_IF_NOT(il.ids.size() == ilsz);
+ READVECTOR(il.vecs);
+ }
+}
+
+static void read_binary_multi_hash_map(
+ IndexBinaryMultiHash::Map& map,
+ int b,
+ size_t ntotal,
+ IOReader* f) {
+ int id_bits;
+ size_t sz;
+ READ1(id_bits);
+ READ1(sz);
+ std::vector<uint8_t> buf;
+ READVECTOR(buf);
+ size_t nbit = (b + id_bits) * sz + ntotal * id_bits;
+ FAISS_THROW_IF_NOT(buf.size() == (nbit + 7) / 8);
+ BitstringReader rd(buf.data(), buf.size());
+ map.reserve(sz);
+ for (size_t i = 0; i < sz; i++) {
+ uint64_t hash = rd.read(b);
+ uint64_t ilsz = rd.read(id_bits);
+ auto& il = map[hash];
+ for (size_t j = 0; j < ilsz; j++) {
+ il.push_back(rd.read(id_bits));
+ }
+ }
+}
+
+IndexBinary* read_index_binary(IOReader* f, int io_flags) {
+ IndexBinary* idx = nullptr;
+ uint32_t h;
+ READ1(h);
+ if (h == fourcc("IBxF")) {
+ IndexBinaryFlat* idxf = new IndexBinaryFlat();
+ read_index_binary_header(idxf, f);
+ read_vector(idxf->xb, f);
+ FAISS_THROW_IF_NOT(idxf->xb.size() == idxf->ntotal * idxf->code_size);
+ // leak!
+ idx = idxf;
+ } else if (h == fourcc("IBwF")) {
+ IndexBinaryIVF* ivf = new IndexBinaryIVF();
+ read_binary_ivf_header(ivf, f);
+ read_InvertedLists(ivf, f, io_flags);
+ idx = ivf;
+ } else if (h == fourcc("IBFf")) {
+ IndexBinaryFromFloat* idxff = new IndexBinaryFromFloat();
+ read_index_binary_header(idxff, f);
+ idxff->own_fields = true;
+ idxff->index = read_index(f, io_flags);
+ idx = idxff;
+ } else if (h == fourcc("IBHf")) {
+ IndexBinaryHNSW* idxhnsw = new IndexBinaryHNSW();
+ read_index_binary_header(idxhnsw, f);
+ read_HNSW(&idxhnsw->hnsw, f);
+ idxhnsw->storage = read_index_binary(f, io_flags);
+ idxhnsw->own_fields = true;
+ idx = idxhnsw;
+ } else if (h == fourcc("IBMp") || h == fourcc("IBM2")) {
+ bool is_map2 = h == fourcc("IBM2");
+ IndexBinaryIDMap* idxmap =
+ is_map2 ? new IndexBinaryIDMap2() : new IndexBinaryIDMap();
+ read_index_binary_header(idxmap, f);
+ idxmap->index = read_index_binary(f, io_flags);
+ idxmap->own_fields = true;
+ READVECTOR(idxmap->id_map);
+ if (is_map2) {
+ static_cast<IndexBinaryIDMap2*>(idxmap)->construct_rev_map();
+ }
+ idx = idxmap;
+ } else if (h == fourcc("IBHh")) {
+ IndexBinaryHash* idxh = new IndexBinaryHash();
+ read_index_binary_header(idxh, f);
+ READ1(idxh->b);
+ READ1(idxh->nflip);
+ read_binary_hash_invlists(idxh->invlists, idxh->b, f);
+ idx = idxh;
+ } else if (h == fourcc("IBHm")) {
+ IndexBinaryMultiHash* idxmh = new IndexBinaryMultiHash();
+ read_index_binary_header(idxmh, f);
+ idxmh->storage = dynamic_cast<IndexBinaryFlat*>(read_index_binary(f));
+ FAISS_THROW_IF_NOT(
+ idxmh->storage && idxmh->storage->ntotal == idxmh->ntotal);
+ idxmh->own_fields = true;
+ READ1(idxmh->b);
+ READ1(idxmh->nhash);
+ READ1(idxmh->nflip);
+ idxmh->maps.resize(idxmh->nhash);
+ for (int i = 0; i < idxmh->nhash; i++) {
+ read_binary_multi_hash_map(
+ idxmh->maps[i], idxmh->b, idxmh->ntotal, f);
+ }
+ idx = idxmh;
+ } else {
+ FAISS_THROW_FMT(
+ "Index type %08x (\"%s\") not recognized",
+ h,
+ fourcc_inv_printable(h).c_str());
+ idx = nullptr;
+ }
+ return idx;
+}
+
+IndexBinary* read_index_binary(FILE* f, int io_flags) {
+ if ((io_flags & IO_FLAG_MMAP_IFC) == IO_FLAG_MMAP_IFC) {
+ // enable mmap-supporting IOReader
+ auto owner = std::make_shared<MmappedFileMappingOwner>(f);
+ MappedFileIOReader reader(owner);
+ return read_index_binary(&reader, io_flags);
+ } else {
+ FileIOReader reader(f);
+ return read_index_binary(&reader, io_flags);
+ }
+}
+
+IndexBinary* read_index_binary(const char* fname, int io_flags) {
+ if ((io_flags & IO_FLAG_MMAP_IFC) == IO_FLAG_MMAP_IFC) {
+ // enable mmap-supporting IOReader
+ auto owner = std::make_shared<MmappedFileMappingOwner>(fname);
+ MappedFileIOReader reader(owner);
+ return read_index_binary(&reader, io_flags);
+ } else {
+ FileIOReader reader(fname);
+ IndexBinary* idx = read_index_binary(&reader, io_flags);
+ return idx;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_read_utils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_read_utils.h
new file mode 100644
index 0000000..543f481
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_read_utils.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// Utils for index_read
+
+#ifndef FAISS_INDEX_READ_UTILS_H
+#define FAISS_INDEX_READ_UTILS_H
+
+#include <faiss/IndexIVF.h>
+#include <faiss/impl/io.h>
+
+#pragma once
+
+namespace faiss {
+struct ProductQuantizer;
+struct ScalarQuantizer;
+
+void read_index_header(Index* idx, IOReader* f);
+void read_direct_map(DirectMap* dm, IOReader* f);
+void read_ivf_header(
+ IndexIVF* ivf,
+ IOReader* f,
+ std::vector<std::vector<idx_t>>* ids = nullptr);
+void read_InvertedLists(IndexIVF* ivf, IOReader* f, int io_flags);
+ArrayInvertedLists* set_array_invlist(
+ IndexIVF* ivf,
+ std::vector<std::vector<idx_t>>& ids);
+void read_ProductQuantizer(ProductQuantizer* pq, IOReader* f);
+void read_ScalarQuantizer(ScalarQuantizer* ivsc, IOReader* f);
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_write.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_write.cpp
new file mode 100644
index 0000000..3f23b6a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/index_write.cpp
@@ -0,0 +1,1075 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/index_io.h>
+
+#include <faiss/impl/io.h>
+#include <faiss/impl/io_macros.h>
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <faiss/invlists/InvertedListsIOHook.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/io_macros.h>
+#include <faiss/utils/hamming.h>
+
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexAdditiveQuantizerFastScan.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFIndependentQuantizer.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/IndexIVFPQR.h>
+#include <faiss/IndexIVFRaBitQ.h>
+#include <faiss/IndexIVFSpectralHash.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexLattice.h>
+#include <faiss/IndexNNDescent.h>
+#include <faiss/IndexNSG.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRaBitQ.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/IndexRowwiseMinMax.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/VectorTransform.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryFromFloat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryHash.h>
+#include <faiss/IndexBinaryIVF.h>
+
+/*************************************************************
+ * The I/O format is the content of the class. For objects that are
+ * inherited, like Index, a 4-character-code (fourcc) indicates which
+ * child class this is an instance of.
+ *
+ * In this case, the fields of the parent class are written first,
+ * then the ones for the child classes. Note that this requires
+ * classes to be serialized to have a constructor without parameters,
+ * so that the fields can be filled in later. The default constructor
+ * should set reasonable defaults for all fields.
+ *
+ * The fourccs are assigned arbitrarily. When the class changed (added
+ * or deprecated fields), the fourcc can be replaced. New code should
+ * be able to read the old fourcc and fill in new classes.
+ *
+ * TODO: in this file, the read functions that encouter errors may
+ * leak memory.
+ **************************************************************/
+
+namespace faiss {
+
+/*************************************************************
+ * Write
+ **************************************************************/
+static void write_index_header(const Index* idx, IOWriter* f) {
+ WRITE1(idx->d);
+ WRITE1(idx->ntotal);
+ idx_t dummy = 1 << 20;
+ WRITE1(dummy);
+ WRITE1(dummy);
+ WRITE1(idx->is_trained);
+ WRITE1(idx->metric_type);
+ if (idx->metric_type > 1) {
+ WRITE1(idx->metric_arg);
+ }
+}
+
+void write_VectorTransform(const VectorTransform* vt, IOWriter* f) {
+ if (const LinearTransform* lt = dynamic_cast<const LinearTransform*>(vt)) {
+ if (dynamic_cast<const RandomRotationMatrix*>(lt)) {
+ uint32_t h = fourcc("rrot");
+ WRITE1(h);
+ } else if (const PCAMatrix* pca = dynamic_cast<const PCAMatrix*>(lt)) {
+ uint32_t h = fourcc("Pcam");
+ WRITE1(h);
+ WRITE1(pca->eigen_power);
+ WRITE1(pca->epsilon);
+ WRITE1(pca->random_rotation);
+ WRITE1(pca->balanced_bins);
+ WRITEVECTOR(pca->mean);
+ WRITEVECTOR(pca->eigenvalues);
+ WRITEVECTOR(pca->PCAMat);
+ } else if (const ITQMatrix* itqm = dynamic_cast<const ITQMatrix*>(lt)) {
+ uint32_t h = fourcc("Viqm");
+ WRITE1(h);
+ WRITE1(itqm->max_iter);
+ WRITE1(itqm->seed);
+ } else {
+ // generic LinearTransform (includes OPQ)
+ uint32_t h = fourcc("LTra");
+ WRITE1(h);
+ }
+ WRITE1(lt->have_bias);
+ WRITEVECTOR(lt->A);
+ WRITEVECTOR(lt->b);
+ } else if (
+ const RemapDimensionsTransform* rdt =
+ dynamic_cast<const RemapDimensionsTransform*>(vt)) {
+ uint32_t h = fourcc("RmDT");
+ WRITE1(h);
+ WRITEVECTOR(rdt->map);
+ } else if (
+ const NormalizationTransform* nt =
+ dynamic_cast<const NormalizationTransform*>(vt)) {
+ uint32_t h = fourcc("VNrm");
+ WRITE1(h);
+ WRITE1(nt->norm);
+ } else if (
+ const CenteringTransform* ct =
+ dynamic_cast<const CenteringTransform*>(vt)) {
+ uint32_t h = fourcc("VCnt");
+ WRITE1(h);
+ WRITEVECTOR(ct->mean);
+ } else if (
+ const ITQTransform* itqt = dynamic_cast<const ITQTransform*>(vt)) {
+ uint32_t h = fourcc("Viqt");
+ WRITE1(h);
+ WRITEVECTOR(itqt->mean);
+ WRITE1(itqt->do_pca);
+ write_VectorTransform(&itqt->itq, f);
+ write_VectorTransform(&itqt->pca_then_itq, f);
+ } else {
+ FAISS_THROW_MSG("cannot serialize this");
+ }
+ // common fields
+ WRITE1(vt->d_in);
+ WRITE1(vt->d_out);
+ WRITE1(vt->is_trained);
+}
+
+void write_ProductQuantizer(const ProductQuantizer* pq, IOWriter* f) {
+ WRITE1(pq->d);
+ WRITE1(pq->M);
+ WRITE1(pq->nbits);
+ WRITEVECTOR(pq->centroids);
+}
+
+static void write_AdditiveQuantizer(const AdditiveQuantizer* aq, IOWriter* f) {
+ WRITE1(aq->d);
+ WRITE1(aq->M);
+ WRITEVECTOR(aq->nbits);
+ WRITE1(aq->is_trained);
+ WRITEVECTOR(aq->codebooks);
+ WRITE1(aq->search_type);
+ WRITE1(aq->norm_min);
+ WRITE1(aq->norm_max);
+ if (aq->search_type == AdditiveQuantizer::ST_norm_cqint8 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_cqint4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_lsq2x4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_rq2x4) {
+ WRITEXBVECTOR(aq->qnorm.codes);
+ }
+
+ if (aq->search_type == AdditiveQuantizer::ST_norm_lsq2x4 ||
+ aq->search_type == AdditiveQuantizer::ST_norm_rq2x4) {
+ WRITEVECTOR(aq->norm_tabs);
+ }
+}
+
+static void write_ResidualQuantizer(const ResidualQuantizer* rq, IOWriter* f) {
+ write_AdditiveQuantizer(rq, f);
+ WRITE1(rq->train_type);
+ WRITE1(rq->max_beam_size);
+}
+
+static void write_LocalSearchQuantizer(
+ const LocalSearchQuantizer* lsq,
+ IOWriter* f) {
+ write_AdditiveQuantizer(lsq, f);
+ WRITE1(lsq->K);
+ WRITE1(lsq->train_iters);
+ WRITE1(lsq->encode_ils_iters);
+ WRITE1(lsq->train_ils_iters);
+ WRITE1(lsq->icm_iters);
+ WRITE1(lsq->p);
+ WRITE1(lsq->lambd);
+ WRITE1(lsq->chunk_size);
+ WRITE1(lsq->random_seed);
+ WRITE1(lsq->nperts);
+ WRITE1(lsq->update_codebooks_with_double);
+}
+
+static void write_ProductAdditiveQuantizer(
+ const ProductAdditiveQuantizer* paq,
+ IOWriter* f) {
+ write_AdditiveQuantizer(paq, f);
+ WRITE1(paq->nsplits);
+}
+
+static void write_ProductResidualQuantizer(
+ const ProductResidualQuantizer* prq,
+ IOWriter* f) {
+ write_ProductAdditiveQuantizer(prq, f);
+ for (const auto aq : prq->quantizers) {
+ auto rq = dynamic_cast<const ResidualQuantizer*>(aq);
+ write_ResidualQuantizer(rq, f);
+ }
+}
+
+static void write_ProductLocalSearchQuantizer(
+ const ProductLocalSearchQuantizer* plsq,
+ IOWriter* f) {
+ write_ProductAdditiveQuantizer(plsq, f);
+ for (const auto aq : plsq->quantizers) {
+ auto lsq = dynamic_cast<const LocalSearchQuantizer*>(aq);
+ write_LocalSearchQuantizer(lsq, f);
+ }
+}
+
+static void write_ScalarQuantizer(const ScalarQuantizer* ivsc, IOWriter* f) {
+ WRITE1(ivsc->qtype);
+ WRITE1(ivsc->rangestat);
+ WRITE1(ivsc->rangestat_arg);
+ WRITE1(ivsc->d);
+ WRITE1(ivsc->code_size);
+ WRITEVECTOR(ivsc->trained);
+}
+
+void write_InvertedLists(const InvertedLists* ils, IOWriter* f) {
+ if (ils == nullptr) {
+ uint32_t h = fourcc("il00");
+ WRITE1(h);
+ } else if (
+ const auto& ails = dynamic_cast<const ArrayInvertedLists*>(ils)) {
+ uint32_t h = fourcc("ilar");
+ WRITE1(h);
+ WRITE1(ails->nlist);
+ WRITE1(ails->code_size);
+ // here we store either as a full or a sparse data buffer
+ size_t n_non0 = 0;
+ for (size_t i = 0; i < ails->nlist; i++) {
+ if (ails->ids[i].size() > 0)
+ n_non0++;
+ }
+ if (n_non0 > ails->nlist / 2) {
+ uint32_t list_type = fourcc("full");
+ WRITE1(list_type);
+ std::vector<size_t> sizes;
+ for (size_t i = 0; i < ails->nlist; i++) {
+ sizes.push_back(ails->ids[i].size());
+ }
+ WRITEVECTOR(sizes);
+ } else {
+ int list_type = fourcc("sprs"); // sparse
+ WRITE1(list_type);
+ std::vector<size_t> sizes;
+ for (size_t i = 0; i < ails->nlist; i++) {
+ size_t n = ails->ids[i].size();
+ if (n > 0) {
+ sizes.push_back(i);
+ sizes.push_back(n);
+ }
+ }
+ WRITEVECTOR(sizes);
+ }
+ // make a single contiguous data buffer (useful for mmapping)
+ for (size_t i = 0; i < ails->nlist; i++) {
+ size_t n = ails->ids[i].size();
+ if (n > 0) {
+ WRITEANDCHECK(ails->codes[i].data(), n * ails->code_size);
+ WRITEANDCHECK(ails->ids[i].data(), n);
+ }
+ }
+
+ } else {
+ InvertedListsIOHook::lookup_classname(typeid(*ils).name())
+ ->write(ils, f);
+ }
+}
+
+void write_ProductQuantizer(const ProductQuantizer* pq, const char* fname) {
+ FileIOWriter writer(fname);
+ write_ProductQuantizer(pq, &writer);
+}
+// faiss/index_io.cpp
+static void write_HNSW(const HNSW* hnsw, IOWriter* f) {
+ WRITEVECTOR(hnsw->assign_probas);
+ WRITEVECTOR(hnsw->cum_nneighbor_per_level);
+ WRITEVECTOR(hnsw->levels);
+
+ // --- NEW: Write storage format flag ---
+ WRITE1(hnsw->storage_is_compact);
+
+ if (hnsw->storage_is_compact) {
+ // --- Write Compact Storage ---
+ WRITEVECTOR(hnsw->compact_neighbors_data);
+ WRITEVECTOR(hnsw->compact_level_ptr);
+ WRITEVECTOR(hnsw->compact_node_offsets);
+ // Write empty original storage vectors for compatibility if needed?
+ // Let's assume reader knows based on flag, don't write empty ones.
+ } else {
+ // --- Write Original Storage ---
+ WRITEVECTOR(hnsw->offsets);
+ WRITEVECTOR(hnsw->neighbors); // Assuming WRITEVECTOR works for
+ // MaybeOwnedVector
+ }
+
+ WRITE1(hnsw->entry_point);
+ WRITE1(hnsw->max_level);
+ WRITE1(hnsw->efConstruction);
+ WRITE1(hnsw->efSearch);
+
+ // // deprecated field
+ // WRITE1(hnsw->upper_beam);
+ constexpr int tmp_upper_beam = 1;
+ WRITE1(tmp_upper_beam);
+}
+
+static void write_NSG(const NSG* nsg, IOWriter* f) {
+ WRITE1(nsg->ntotal);
+ WRITE1(nsg->R);
+ WRITE1(nsg->L);
+ WRITE1(nsg->C);
+ WRITE1(nsg->search_L);
+ WRITE1(nsg->enterpoint);
+ WRITE1(nsg->is_built);
+
+ if (!nsg->is_built) {
+ return;
+ }
+
+ constexpr int EMPTY_ID = -1;
+ auto& graph = nsg->final_graph;
+ int K = graph->K;
+ int N = graph->N;
+ FAISS_THROW_IF_NOT(N == nsg->ntotal);
+ FAISS_THROW_IF_NOT(K == nsg->R);
+ FAISS_THROW_IF_NOT(true == graph->own_fields);
+
+ for (int i = 0; i < N; i++) {
+ for (int j = 0; j < K; j++) {
+ int id = graph->at(i, j);
+ if (id != EMPTY_ID) {
+ WRITE1(id);
+ } else {
+ break;
+ }
+ }
+ WRITE1(EMPTY_ID);
+ }
+}
+
+static void write_NNDescent(const NNDescent* nnd, IOWriter* f) {
+ WRITE1(nnd->ntotal);
+ WRITE1(nnd->d);
+ WRITE1(nnd->K);
+ WRITE1(nnd->S);
+ WRITE1(nnd->R);
+ WRITE1(nnd->L);
+ WRITE1(nnd->iter);
+ WRITE1(nnd->search_L);
+ WRITE1(nnd->random_seed);
+ WRITE1(nnd->has_built);
+
+ WRITEVECTOR(nnd->final_graph);
+}
+
+static void write_RaBitQuantizer(const RaBitQuantizer* rabitq, IOWriter* f) {
+ // don't care about rabitq->centroid
+ WRITE1(rabitq->d);
+ WRITE1(rabitq->code_size);
+}
+
+static void write_direct_map(const DirectMap* dm, IOWriter* f) {
+ char maintain_direct_map =
+ (char)dm->type; // for backwards compatibility with bool
+ WRITE1(maintain_direct_map);
+ WRITEVECTOR(dm->array);
+ if (dm->type == DirectMap::Hashtable) {
+ std::vector<std::pair<idx_t, idx_t>> v;
+ const std::unordered_map<idx_t, idx_t>& map = dm->hashtable;
+ v.resize(map.size());
+ std::copy(map.begin(), map.end(), v.begin());
+ WRITEVECTOR(v);
+ }
+}
+
+static void write_ivf_header(const IndexIVF* ivf, IOWriter* f) {
+ write_index_header(ivf, f);
+ WRITE1(ivf->nlist);
+ WRITE1(ivf->nprobe);
+ // subclasses write by_residual (some of them support only one setting of
+ // by_residual).
+ write_index(ivf->quantizer, f);
+ write_direct_map(&ivf->direct_map, f);
+}
+
+void write_index(const Index* idx, IOWriter* f, int io_flags) {
+ if (idx == nullptr) {
+ // eg. for a storage component of HNSW that is set to nullptr
+ uint32_t h = fourcc("null");
+ WRITE1(h);
+ } else if (const IndexFlat* idxf = dynamic_cast<const IndexFlat*>(idx)) {
+ uint32_t h =
+ fourcc(idxf->metric_type == METRIC_INNER_PRODUCT ? "IxFI"
+ : idxf->metric_type == METRIC_L2 ? "IxF2"
+ : "IxFl");
+ WRITE1(h);
+ write_index_header(idx, f);
+ WRITEXBVECTOR(idxf->codes);
+ } else if (const IndexLSH* idxl = dynamic_cast<const IndexLSH*>(idx)) {
+ uint32_t h = fourcc("IxHe");
+ WRITE1(h);
+ write_index_header(idx, f);
+ WRITE1(idxl->nbits);
+ WRITE1(idxl->rotate_data);
+ WRITE1(idxl->train_thresholds);
+ WRITEVECTOR(idxl->thresholds);
+ int code_size_i = idxl->code_size;
+ WRITE1(code_size_i);
+ write_VectorTransform(&idxl->rrot, f);
+ WRITEVECTOR(idxl->codes);
+ } else if (const IndexPQ* idxp = dynamic_cast<const IndexPQ*>(idx)) {
+ uint32_t h = fourcc("IxPq");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_ProductQuantizer(&idxp->pq, f);
+ WRITEVECTOR(idxp->codes);
+ // search params -- maybe not useful to store?
+ WRITE1(idxp->search_type);
+ WRITE1(idxp->encode_signs);
+ WRITE1(idxp->polysemous_ht);
+ } else if (
+ const IndexResidualQuantizer* idxr =
+ dynamic_cast<const IndexResidualQuantizer*>(idx)) {
+ uint32_t h = fourcc("IxRq");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_ResidualQuantizer(&idxr->rq, f);
+ WRITE1(idxr->code_size);
+ WRITEVECTOR(idxr->codes);
+ } else if (
+ auto* idxr_2 =
+ dynamic_cast<const IndexLocalSearchQuantizer*>(idx)) {
+ uint32_t h = fourcc("IxLS");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_LocalSearchQuantizer(&idxr_2->lsq, f);
+ WRITE1(idxr_2->code_size);
+ WRITEVECTOR(idxr_2->codes);
+ } else if (
+ const IndexProductResidualQuantizer* idxpr =
+ dynamic_cast<const IndexProductResidualQuantizer*>(idx)) {
+ uint32_t h = fourcc("IxPR");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_ProductResidualQuantizer(&idxpr->prq, f);
+ WRITE1(idxpr->code_size);
+ WRITEVECTOR(idxpr->codes);
+ } else if (
+ const IndexProductLocalSearchQuantizer* idxpl =
+ dynamic_cast<const IndexProductLocalSearchQuantizer*>(
+ idx)) {
+ uint32_t h = fourcc("IxPL");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_ProductLocalSearchQuantizer(&idxpl->plsq, f);
+ WRITE1(idxpl->code_size);
+ WRITEVECTOR(idxpl->codes);
+ } else if (
+ auto* idxaqfs =
+ dynamic_cast<const IndexAdditiveQuantizerFastScan*>(idx)) {
+ auto idxlsqfs =
+ dynamic_cast<const IndexLocalSearchQuantizerFastScan*>(idx);
+ auto idxrqfs = dynamic_cast<const IndexResidualQuantizerFastScan*>(idx);
+ auto idxplsqfs =
+ dynamic_cast<const IndexProductLocalSearchQuantizerFastScan*>(
+ idx);
+ auto idxprqfs =
+ dynamic_cast<const IndexProductResidualQuantizerFastScan*>(idx);
+ FAISS_THROW_IF_NOT(idxlsqfs || idxrqfs || idxplsqfs || idxprqfs);
+
+ if (idxlsqfs) {
+ uint32_t h = fourcc("ILfs");
+ WRITE1(h);
+ } else if (idxrqfs) {
+ uint32_t h = fourcc("IRfs");
+ WRITE1(h);
+ } else if (idxplsqfs) {
+ uint32_t h = fourcc("IPLf");
+ WRITE1(h);
+ } else if (idxprqfs) {
+ uint32_t h = fourcc("IPRf");
+ WRITE1(h);
+ }
+
+ write_index_header(idxaqfs, f);
+
+ if (idxlsqfs) {
+ write_LocalSearchQuantizer(&idxlsqfs->lsq, f);
+ } else if (idxrqfs) {
+ write_ResidualQuantizer(&idxrqfs->rq, f);
+ } else if (idxplsqfs) {
+ write_ProductLocalSearchQuantizer(&idxplsqfs->plsq, f);
+ } else if (idxprqfs) {
+ write_ProductResidualQuantizer(&idxprqfs->prq, f);
+ }
+ WRITE1(idxaqfs->implem);
+ WRITE1(idxaqfs->bbs);
+ WRITE1(idxaqfs->qbs);
+
+ WRITE1(idxaqfs->M);
+ WRITE1(idxaqfs->nbits);
+ WRITE1(idxaqfs->ksub);
+ WRITE1(idxaqfs->code_size);
+ WRITE1(idxaqfs->ntotal2);
+ WRITE1(idxaqfs->M2);
+
+ WRITE1(idxaqfs->rescale_norm);
+ WRITE1(idxaqfs->norm_scale);
+ WRITE1(idxaqfs->max_train_points);
+
+ WRITEVECTOR(idxaqfs->codes);
+ } else if (
+ auto* ivaqfs =
+ dynamic_cast<const IndexIVFAdditiveQuantizerFastScan*>(
+ idx)) {
+ auto ivlsqfs =
+ dynamic_cast<const IndexIVFLocalSearchQuantizerFastScan*>(idx);
+ auto ivrqfs =
+ dynamic_cast<const IndexIVFResidualQuantizerFastScan*>(idx);
+ auto ivplsqfs = dynamic_cast<
+ const IndexIVFProductLocalSearchQuantizerFastScan*>(idx);
+ auto ivprqfs =
+ dynamic_cast<const IndexIVFProductResidualQuantizerFastScan*>(
+ idx);
+ FAISS_THROW_IF_NOT(ivlsqfs || ivrqfs || ivplsqfs || ivprqfs);
+
+ if (ivlsqfs) {
+ uint32_t h = fourcc("IVLf");
+ WRITE1(h);
+ } else if (ivrqfs) {
+ uint32_t h = fourcc("IVRf");
+ WRITE1(h);
+ } else if (ivplsqfs) {
+ uint32_t h = fourcc("NPLf"); // N means IV ...
+ WRITE1(h);
+ } else {
+ uint32_t h = fourcc("NPRf");
+ WRITE1(h);
+ }
+
+ write_ivf_header(ivaqfs, f);
+
+ if (ivlsqfs) {
+ write_LocalSearchQuantizer(&ivlsqfs->lsq, f);
+ } else if (ivrqfs) {
+ write_ResidualQuantizer(&ivrqfs->rq, f);
+ } else if (ivplsqfs) {
+ write_ProductLocalSearchQuantizer(&ivplsqfs->plsq, f);
+ } else {
+ write_ProductResidualQuantizer(&ivprqfs->prq, f);
+ }
+
+ WRITE1(ivaqfs->by_residual);
+ WRITE1(ivaqfs->implem);
+ WRITE1(ivaqfs->bbs);
+ WRITE1(ivaqfs->qbs);
+
+ WRITE1(ivaqfs->M);
+ WRITE1(ivaqfs->nbits);
+ WRITE1(ivaqfs->ksub);
+ WRITE1(ivaqfs->code_size);
+ WRITE1(ivaqfs->qbs2);
+ WRITE1(ivaqfs->M2);
+
+ WRITE1(ivaqfs->rescale_norm);
+ WRITE1(ivaqfs->norm_scale);
+ WRITE1(ivaqfs->max_train_points);
+
+ write_InvertedLists(ivaqfs->invlists, f);
+ } else if (
+ const ResidualCoarseQuantizer* idxr_2 =
+ dynamic_cast<const ResidualCoarseQuantizer*>(idx)) {
+ uint32_t h = fourcc("ImRQ");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_ResidualQuantizer(&idxr_2->rq, f);
+ WRITE1(idxr_2->beam_factor);
+ } else if (
+ const Index2Layer* idxp_2 = dynamic_cast<const Index2Layer*>(idx)) {
+ uint32_t h = fourcc("Ix2L");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_index(idxp_2->q1.quantizer, f);
+ WRITE1(idxp_2->q1.nlist);
+ WRITE1(idxp_2->q1.quantizer_trains_alone);
+ write_ProductQuantizer(&idxp_2->pq, f);
+ WRITE1(idxp_2->code_size_1);
+ WRITE1(idxp_2->code_size_2);
+ WRITE1(idxp_2->code_size);
+ WRITEVECTOR(idxp_2->codes);
+ } else if (
+ const IndexScalarQuantizer* idxs =
+ dynamic_cast<const IndexScalarQuantizer*>(idx)) {
+ uint32_t h = fourcc("IxSQ");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_ScalarQuantizer(&idxs->sq, f);
+ WRITEVECTOR(idxs->codes);
+ } else if (
+ const IndexLattice* idxl_2 =
+ dynamic_cast<const IndexLattice*>(idx)) {
+ uint32_t h = fourcc("IxLa");
+ WRITE1(h);
+ WRITE1(idxl_2->d);
+ WRITE1(idxl_2->nsq);
+ WRITE1(idxl_2->scale_nbit);
+ WRITE1(idxl_2->zn_sphere_codec.r2);
+ write_index_header(idx, f);
+ WRITEVECTOR(idxl_2->trained);
+ } else if (
+ const IndexIVFFlatDedup* ivfl =
+ dynamic_cast<const IndexIVFFlatDedup*>(idx)) {
+ uint32_t h = fourcc("IwFd");
+ WRITE1(h);
+ write_ivf_header(ivfl, f);
+ {
+ std::vector<idx_t> tab(2 * ivfl->instances.size());
+ long i = 0;
+ for (auto it = ivfl->instances.begin(); it != ivfl->instances.end();
+ ++it) {
+ tab[i++] = it->first;
+ tab[i++] = it->second;
+ }
+ WRITEVECTOR(tab);
+ }
+ write_InvertedLists(ivfl->invlists, f);
+ } else if (
+ const IndexIVFFlat* ivfl_2 =
+ dynamic_cast<const IndexIVFFlat*>(idx)) {
+ uint32_t h = fourcc("IwFl");
+ WRITE1(h);
+ write_ivf_header(ivfl_2, f);
+ write_InvertedLists(ivfl_2->invlists, f);
+ } else if (
+ const IndexIVFScalarQuantizer* ivsc =
+ dynamic_cast<const IndexIVFScalarQuantizer*>(idx)) {
+ uint32_t h = fourcc("IwSq");
+ WRITE1(h);
+ write_ivf_header(ivsc, f);
+ write_ScalarQuantizer(&ivsc->sq, f);
+ WRITE1(ivsc->code_size);
+ WRITE1(ivsc->by_residual);
+ write_InvertedLists(ivsc->invlists, f);
+ } else if (auto iva = dynamic_cast<const IndexIVFAdditiveQuantizer*>(idx)) {
+ bool is_LSQ = dynamic_cast<const IndexIVFLocalSearchQuantizer*>(iva);
+ bool is_RQ = dynamic_cast<const IndexIVFResidualQuantizer*>(iva);
+ bool is_PLSQ =
+ dynamic_cast<const IndexIVFProductLocalSearchQuantizer*>(iva);
+ uint32_t h;
+ if (is_LSQ) {
+ h = fourcc("IwLS");
+ } else if (is_RQ) {
+ h = fourcc("IwRQ");
+ } else if (is_PLSQ) {
+ h = fourcc("IwPL");
+ } else {
+ h = fourcc("IwPR");
+ }
+
+ WRITE1(h);
+ write_ivf_header(iva, f);
+ WRITE1(iva->code_size);
+ if (is_LSQ) {
+ write_LocalSearchQuantizer((LocalSearchQuantizer*)iva->aq, f);
+ } else if (is_RQ) {
+ write_ResidualQuantizer((ResidualQuantizer*)iva->aq, f);
+ } else if (is_PLSQ) {
+ write_ProductLocalSearchQuantizer(
+ (ProductLocalSearchQuantizer*)iva->aq, f);
+ } else {
+ write_ProductResidualQuantizer(
+ (ProductResidualQuantizer*)iva->aq, f);
+ }
+ WRITE1(iva->by_residual);
+ WRITE1(iva->use_precomputed_table);
+ write_InvertedLists(iva->invlists, f);
+ } else if (
+ const IndexIVFSpectralHash* ivsp =
+ dynamic_cast<const IndexIVFSpectralHash*>(idx)) {
+ uint32_t h = fourcc("IwSh");
+ WRITE1(h);
+ write_ivf_header(ivsp, f);
+ write_VectorTransform(ivsp->vt, f);
+ WRITE1(ivsp->nbit);
+ WRITE1(ivsp->period);
+ WRITE1(ivsp->threshold_type);
+ WRITEVECTOR(ivsp->trained);
+ write_InvertedLists(ivsp->invlists, f);
+ } else if (const IndexIVFPQ* ivpq = dynamic_cast<const IndexIVFPQ*>(idx)) {
+ const IndexIVFPQR* ivfpqr = dynamic_cast<const IndexIVFPQR*>(idx);
+
+ uint32_t h = fourcc(ivfpqr ? "IwQR" : "IwPQ");
+ WRITE1(h);
+ write_ivf_header(ivpq, f);
+ WRITE1(ivpq->by_residual);
+ WRITE1(ivpq->code_size);
+ write_ProductQuantizer(&ivpq->pq, f);
+ write_InvertedLists(ivpq->invlists, f);
+ if (ivfpqr) {
+ write_ProductQuantizer(&ivfpqr->refine_pq, f);
+ WRITEVECTOR(ivfpqr->refine_codes);
+ WRITE1(ivfpqr->k_factor);
+ }
+ } else if (
+ auto* indep =
+ dynamic_cast<const IndexIVFIndependentQuantizer*>(idx)) {
+ uint32_t h = fourcc("IwIQ");
+ WRITE1(h);
+ write_index_header(indep, f);
+ write_index(indep->quantizer, f);
+ bool has_vt = indep->vt != nullptr;
+ WRITE1(has_vt);
+ if (has_vt) {
+ write_VectorTransform(indep->vt, f);
+ }
+ write_index(indep->index_ivf, f);
+ if (auto index_ivfpq = dynamic_cast<IndexIVFPQ*>(indep->index_ivf)) {
+ WRITE1(index_ivfpq->use_precomputed_table);
+ }
+ } else if (
+ const IndexPreTransform* ixpt =
+ dynamic_cast<const IndexPreTransform*>(idx)) {
+ uint32_t h = fourcc("IxPT");
+ WRITE1(h);
+ write_index_header(ixpt, f);
+ int nt = ixpt->chain.size();
+ WRITE1(nt);
+ for (int i = 0; i < nt; i++)
+ write_VectorTransform(ixpt->chain[i], f);
+ write_index(ixpt->index, f);
+ } else if (
+ const MultiIndexQuantizer* imiq =
+ dynamic_cast<const MultiIndexQuantizer*>(idx)) {
+ uint32_t h = fourcc("Imiq");
+ WRITE1(h);
+ write_index_header(imiq, f);
+ write_ProductQuantizer(&imiq->pq, f);
+ } else if (
+ const IndexRefine* idxrf = dynamic_cast<const IndexRefine*>(idx)) {
+ uint32_t h = fourcc("IxRF");
+ WRITE1(h);
+ write_index_header(idxrf, f);
+ write_index(idxrf->base_index, f);
+ write_index(idxrf->refine_index, f);
+ WRITE1(idxrf->k_factor);
+ } else if (
+ const IndexIDMap* idxmap = dynamic_cast<const IndexIDMap*>(idx)) {
+ uint32_t h = dynamic_cast<const IndexIDMap2*>(idx) ? fourcc("IxM2")
+ : fourcc("IxMp");
+ // no need to store additional info for IndexIDMap2
+ WRITE1(h);
+ write_index_header(idxmap, f);
+ write_index(idxmap->index, f);
+ WRITEVECTOR(idxmap->id_map);
+ } else if (const IndexHNSW* idxhnsw = dynamic_cast<const IndexHNSW*>(idx)) {
+ uint32_t h = dynamic_cast<const IndexHNSWFlat*>(idx) ? fourcc("IHNf")
+ : dynamic_cast<const IndexHNSWPQ*>(idx) ? fourcc("IHNp")
+ : dynamic_cast<const IndexHNSWSQ*>(idx) ? fourcc("IHNs")
+ : dynamic_cast<const IndexHNSW2Level*>(idx) ? fourcc("IHN2")
+ : dynamic_cast<const IndexHNSWCagra*>(idx) ? fourcc("IHNc")
+ : 0;
+ FAISS_THROW_IF_NOT(h != 0);
+ WRITE1(h);
+ write_index_header(idxhnsw, f);
+ if (h == fourcc("IHNc")) {
+ WRITE1(idxhnsw->keep_max_size_level0);
+ auto idx_hnsw_cagra = dynamic_cast<const IndexHNSWCagra*>(idxhnsw);
+ WRITE1(idx_hnsw_cagra->base_level_only);
+ WRITE1(idx_hnsw_cagra->num_base_level_search_entrypoints);
+ }
+ write_HNSW(&idxhnsw->hnsw, f);
+ if (io_flags & IO_FLAG_SKIP_STORAGE) {
+ uint32_t n4 = fourcc("null");
+ WRITE1(n4);
+ } else {
+ write_index(idxhnsw->storage, f);
+ }
+ } else if (const IndexNSG* idxnsg = dynamic_cast<const IndexNSG*>(idx)) {
+ uint32_t h = dynamic_cast<const IndexNSGFlat*>(idx) ? fourcc("INSf")
+ : dynamic_cast<const IndexNSGPQ*>(idx) ? fourcc("INSp")
+ : dynamic_cast<const IndexNSGSQ*>(idx) ? fourcc("INSs")
+ : 0;
+ FAISS_THROW_IF_NOT(h != 0);
+ WRITE1(h);
+ write_index_header(idxnsg, f);
+ WRITE1(idxnsg->GK);
+ WRITE1(idxnsg->build_type);
+ WRITE1(idxnsg->nndescent_S);
+ WRITE1(idxnsg->nndescent_R);
+ WRITE1(idxnsg->nndescent_L);
+ WRITE1(idxnsg->nndescent_iter);
+ write_NSG(&idxnsg->nsg, f);
+ write_index(idxnsg->storage, f);
+ } else if (
+ const IndexNNDescent* idxnnd =
+ dynamic_cast<const IndexNNDescent*>(idx)) {
+ auto idxnndflat = dynamic_cast<const IndexNNDescentFlat*>(idx);
+ FAISS_THROW_IF_NOT(idxnndflat != nullptr);
+ uint32_t h = fourcc("INNf");
+ FAISS_THROW_IF_NOT(h != 0);
+ WRITE1(h);
+ write_index_header(idxnnd, f);
+ write_NNDescent(&idxnnd->nndescent, f);
+ write_index(idxnnd->storage, f);
+ } else if (
+ const IndexPQFastScan* idxpqfs =
+ dynamic_cast<const IndexPQFastScan*>(idx)) {
+ uint32_t h = fourcc("IPfs");
+ WRITE1(h);
+ write_index_header(idxpqfs, f);
+ write_ProductQuantizer(&idxpqfs->pq, f);
+ WRITE1(idxpqfs->implem);
+ WRITE1(idxpqfs->bbs);
+ WRITE1(idxpqfs->qbs);
+ WRITE1(idxpqfs->ntotal2);
+ WRITE1(idxpqfs->M2);
+ WRITEVECTOR(idxpqfs->codes);
+ } else if (
+ const IndexIVFPQFastScan* ivpq_2 =
+ dynamic_cast<const IndexIVFPQFastScan*>(idx)) {
+ uint32_t h = fourcc("IwPf");
+ WRITE1(h);
+ write_ivf_header(ivpq_2, f);
+ WRITE1(ivpq_2->by_residual);
+ WRITE1(ivpq_2->code_size);
+ WRITE1(ivpq_2->bbs);
+ WRITE1(ivpq_2->M2);
+ WRITE1(ivpq_2->implem);
+ WRITE1(ivpq_2->qbs2);
+ write_ProductQuantizer(&ivpq_2->pq, f);
+ write_InvertedLists(ivpq_2->invlists, f);
+ } else if (
+ const IndexRowwiseMinMax* imm =
+ dynamic_cast<const IndexRowwiseMinMax*>(idx)) {
+ // IndexRowwiseMinmaxFloat
+ uint32_t h = fourcc("IRMf");
+ WRITE1(h);
+ write_index_header(imm, f);
+ write_index(imm->index, f);
+ } else if (
+ const IndexRowwiseMinMaxFP16* imm_2 =
+ dynamic_cast<const IndexRowwiseMinMaxFP16*>(idx)) {
+ // IndexRowwiseMinmaxHalf
+ uint32_t h = fourcc("IRMh");
+ WRITE1(h);
+ write_index_header(imm_2, f);
+ write_index(imm_2->index, f);
+ } else if (
+ const IndexRaBitQ* idxq = dynamic_cast<const IndexRaBitQ*>(idx)) {
+ uint32_t h = fourcc("Ixrq");
+ WRITE1(h);
+ write_index_header(idx, f);
+ write_RaBitQuantizer(&idxq->rabitq, f);
+ WRITEVECTOR(idxq->codes);
+ WRITEVECTOR(idxq->center);
+ WRITE1(idxq->qb);
+ } else if (
+ const IndexIVFRaBitQ* ivrq =
+ dynamic_cast<const IndexIVFRaBitQ*>(idx)) {
+ uint32_t h = fourcc("Iwrq");
+ WRITE1(h);
+ write_ivf_header(ivrq, f);
+ write_RaBitQuantizer(&ivrq->rabitq, f);
+ WRITE1(ivrq->code_size);
+ WRITE1(ivrq->by_residual);
+ WRITE1(ivrq->qb);
+ write_InvertedLists(ivrq->invlists, f);
+ } else {
+ FAISS_THROW_MSG("don't know how to serialize this type of index");
+ }
+}
+
+void write_index(const Index* idx, FILE* f, int io_flags) {
+ FileIOWriter writer(f);
+ write_index(idx, &writer, io_flags);
+}
+
+void write_index(const Index* idx, const char* fname, int io_flags) {
+ FileIOWriter writer(fname);
+ write_index(idx, &writer, io_flags);
+}
+
+void write_VectorTransform(const VectorTransform* vt, const char* fname) {
+ FileIOWriter writer(fname);
+ write_VectorTransform(vt, &writer);
+}
+
+/*************************************************************
+ * Write binary indexes
+ **************************************************************/
+
+static void write_index_binary_header(const IndexBinary* idx, IOWriter* f) {
+ WRITE1(idx->d);
+ WRITE1(idx->code_size);
+ WRITE1(idx->ntotal);
+ WRITE1(idx->is_trained);
+ WRITE1(idx->metric_type);
+}
+
+static void write_binary_ivf_header(const IndexBinaryIVF* ivf, IOWriter* f) {
+ write_index_binary_header(ivf, f);
+ WRITE1(ivf->nlist);
+ WRITE1(ivf->nprobe);
+ write_index_binary(ivf->quantizer, f);
+ write_direct_map(&ivf->direct_map, f);
+}
+
+static void write_binary_hash_invlists(
+ const IndexBinaryHash::InvertedListMap& invlists,
+ int b,
+ IOWriter* f) {
+ size_t sz = invlists.size();
+ WRITE1(sz);
+ size_t maxil = 0;
+ for (auto it = invlists.begin(); it != invlists.end(); ++it) {
+ if (it->second.ids.size() > maxil) {
+ maxil = it->second.ids.size();
+ }
+ }
+ int il_nbit = 0;
+ while (maxil >= ((uint64_t)1 << il_nbit)) {
+ il_nbit++;
+ }
+ WRITE1(il_nbit);
+
+ // first write sizes then data, may be useful if we want to
+ // memmap it at some point
+
+ // buffer for bitstrings
+ std::vector<uint8_t> buf(((b + il_nbit) * sz + 7) / 8);
+ BitstringWriter wr(buf.data(), buf.size());
+ for (auto it = invlists.begin(); it != invlists.end(); ++it) {
+ wr.write(it->first, b);
+ wr.write(it->second.ids.size(), il_nbit);
+ }
+ WRITEVECTOR(buf);
+
+ for (auto it = invlists.begin(); it != invlists.end(); ++it) {
+ WRITEVECTOR(it->second.ids);
+ WRITEVECTOR(it->second.vecs);
+ }
+}
+
+static void write_binary_multi_hash_map(
+ const IndexBinaryMultiHash::Map& map,
+ int b,
+ size_t ntotal,
+ IOWriter* f) {
+ int id_bits = 0;
+ while ((ntotal > ((idx_t)1 << id_bits))) {
+ id_bits++;
+ }
+ WRITE1(id_bits);
+ size_t sz = map.size();
+ WRITE1(sz);
+ size_t nbit = (b + id_bits) * sz + ntotal * id_bits;
+ std::vector<uint8_t> buf((nbit + 7) / 8);
+ BitstringWriter wr(buf.data(), buf.size());
+ for (auto it = map.begin(); it != map.end(); ++it) {
+ wr.write(it->first, b);
+ wr.write(it->second.size(), id_bits);
+ for (auto id : it->second) {
+ wr.write(id, id_bits);
+ }
+ }
+ WRITEVECTOR(buf);
+}
+
+void write_index_binary(const IndexBinary* idx, IOWriter* f) {
+ if (const IndexBinaryFlat* idxf =
+ dynamic_cast<const IndexBinaryFlat*>(idx)) {
+ uint32_t h = fourcc("IBxF");
+ WRITE1(h);
+ write_index_binary_header(idx, f);
+ WRITEVECTOR(idxf->xb);
+ } else if (
+ const IndexBinaryIVF* ivf =
+ dynamic_cast<const IndexBinaryIVF*>(idx)) {
+ uint32_t h = fourcc("IBwF");
+ WRITE1(h);
+ write_binary_ivf_header(ivf, f);
+ write_InvertedLists(ivf->invlists, f);
+ } else if (
+ const IndexBinaryFromFloat* idxff =
+ dynamic_cast<const IndexBinaryFromFloat*>(idx)) {
+ uint32_t h = fourcc("IBFf");
+ WRITE1(h);
+ write_index_binary_header(idxff, f);
+ write_index(idxff->index, f);
+ } else if (
+ const IndexBinaryHNSW* idxhnsw =
+ dynamic_cast<const IndexBinaryHNSW*>(idx)) {
+ uint32_t h = fourcc("IBHf");
+ WRITE1(h);
+ write_index_binary_header(idxhnsw, f);
+ write_HNSW(&idxhnsw->hnsw, f);
+ write_index_binary(idxhnsw->storage, f);
+ } else if (
+ const IndexBinaryIDMap* idxmap =
+ dynamic_cast<const IndexBinaryIDMap*>(idx)) {
+ uint32_t h = dynamic_cast<const IndexBinaryIDMap2*>(idx)
+ ? fourcc("IBM2")
+ : fourcc("IBMp");
+ // no need to store additional info for IndexIDMap2
+ WRITE1(h);
+ write_index_binary_header(idxmap, f);
+ write_index_binary(idxmap->index, f);
+ WRITEVECTOR(idxmap->id_map);
+ } else if (
+ const IndexBinaryHash* idxh =
+ dynamic_cast<const IndexBinaryHash*>(idx)) {
+ uint32_t h = fourcc("IBHh");
+ WRITE1(h);
+ write_index_binary_header(idxh, f);
+ WRITE1(idxh->b);
+ WRITE1(idxh->nflip);
+ write_binary_hash_invlists(idxh->invlists, idxh->b, f);
+ } else if (
+ const IndexBinaryMultiHash* idxmh =
+ dynamic_cast<const IndexBinaryMultiHash*>(idx)) {
+ uint32_t h = fourcc("IBHm");
+ WRITE1(h);
+ write_index_binary_header(idxmh, f);
+ write_index_binary(idxmh->storage, f);
+ WRITE1(idxmh->b);
+ WRITE1(idxmh->nhash);
+ WRITE1(idxmh->nflip);
+ for (int i = 0; i < idxmh->nhash; i++) {
+ write_binary_multi_hash_map(
+ idxmh->maps[i], idxmh->b, idxmh->ntotal, f);
+ }
+ } else {
+ FAISS_THROW_MSG("don't know how to serialize this type of index");
+ }
+}
+
+void write_index_binary(const IndexBinary* idx, FILE* f) {
+ FileIOWriter writer(f);
+ write_index_binary(idx, &writer);
+}
+
+void write_index_binary(const IndexBinary* idx, const char* fname) {
+ FileIOWriter writer(fname);
+ write_index_binary(idx, &writer);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io.cpp
new file mode 100644
index 0000000..af453bd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io.cpp
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <algorithm>
+#include <cassert>
+#include <cstring>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/io.h>
+
+namespace faiss {
+
+/***********************************************************************
+ * IO functions
+ ***********************************************************************/
+
+int IOReader::filedescriptor() {
+ FAISS_THROW_MSG("IOReader does not support memory mapping");
+}
+
+int IOWriter::filedescriptor() {
+ FAISS_THROW_MSG("IOWriter does not support memory mapping");
+}
+
+/***********************************************************************
+ * IO Vector
+ ***********************************************************************/
+
+size_t VectorIOWriter::operator()(const void* ptr, size_t size, size_t nitems) {
+ size_t bytes = size * nitems;
+ if (bytes > 0) {
+ size_t o = data.size();
+ data.resize(o + bytes);
+ memcpy(&data[o], ptr, size * nitems);
+ }
+ return nitems;
+}
+
+size_t VectorIOReader::operator()(void* ptr, size_t size, size_t nitems) {
+ if (rp >= data.size())
+ return 0;
+ size_t nremain = (data.size() - rp) / size;
+ if (nremain < nitems)
+ nitems = nremain;
+ if (size * nitems > 0) {
+ memcpy(ptr, &data[rp], size * nitems);
+ rp += size * nitems;
+ }
+ return nitems;
+}
+
+/***********************************************************************
+ * IO File
+ ***********************************************************************/
+
+FileIOReader::FileIOReader(FILE* rf) : f(rf) {}
+
+FileIOReader::FileIOReader(const char* fname) {
+ name = fname;
+ f = fopen(fname, "rb");
+ FAISS_THROW_IF_NOT_FMT(
+ f, "could not open %s for reading: %s", fname, strerror(errno));
+ need_close = true;
+}
+
+FileIOReader::~FileIOReader() {
+ if (need_close) {
+ int ret = fclose(f);
+ if (ret != 0) { // we cannot raise and exception in the destructor
+ fprintf(stderr,
+ "file %s close error: %s",
+ name.c_str(),
+ strerror(errno));
+ }
+ }
+}
+
+size_t FileIOReader::operator()(void* ptr, size_t size, size_t nitems) {
+ return fread(ptr, size, nitems, f);
+}
+
+int FileIOReader::filedescriptor() {
+#ifdef _AIX
+ return fileno(f);
+#else
+ return ::fileno(f);
+#endif
+}
+
+FileIOWriter::FileIOWriter(FILE* wf) : f(wf) {}
+
+FileIOWriter::FileIOWriter(const char* fname) {
+ name = fname;
+ f = fopen(fname, "wb");
+ FAISS_THROW_IF_NOT_FMT(
+ f, "could not open %s for writing: %s", fname, strerror(errno));
+ need_close = true;
+}
+
+FileIOWriter::~FileIOWriter() {
+ if (need_close) {
+ int ret = fclose(f);
+ if (ret != 0) {
+ // we cannot raise and exception in the destructor
+ fprintf(stderr,
+ "file %s close error: %s",
+ name.c_str(),
+ strerror(errno));
+ }
+ }
+}
+
+size_t FileIOWriter::operator()(const void* ptr, size_t size, size_t nitems) {
+ return fwrite(ptr, size, nitems, f);
+}
+
+int FileIOWriter::filedescriptor() {
+#ifdef _AIX
+ return fileno(f);
+#else
+ return ::fileno(f);
+#endif
+}
+
+/***********************************************************************
+ * IO buffer
+ ***********************************************************************/
+
+BufferedIOReader::BufferedIOReader(IOReader* reader, size_t bsz)
+ : reader(reader),
+ bsz(bsz),
+ ofs(0),
+ ofs2(0),
+ b0(0),
+ b1(0),
+ buffer(bsz) {}
+
+size_t BufferedIOReader::operator()(void* ptr, size_t unitsize, size_t nitems) {
+ size_t size = unitsize * nitems;
+ if (size == 0)
+ return 0;
+ char* dst = (char*)ptr;
+ size_t nb;
+
+ { // first copy available bytes
+ nb = std::min(b1 - b0, size);
+ memcpy(dst, buffer.data() + b0, nb);
+ b0 += nb;
+ dst += nb;
+ size -= nb;
+ }
+
+ // while we would like to have more data
+ while (size > 0) {
+ assert(b0 == b1); // buffer empty on input
+ // try to read from main reader
+ b0 = 0;
+ b1 = (*reader)(buffer.data(), 1, bsz);
+
+ if (b1 == 0) {
+ // no more bytes available
+ break;
+ }
+ ofs += b1;
+
+ // copy remaining bytes
+ size_t nb2 = std::min(b1, size);
+ memcpy(dst, buffer.data(), nb2);
+ b0 = nb2;
+ nb += nb2;
+ dst += nb2;
+ size -= nb2;
+ }
+ ofs2 += nb;
+ return nb / unitsize;
+}
+
+BufferedIOWriter::BufferedIOWriter(IOWriter* writer, size_t bsz)
+ : writer(writer), bsz(bsz), ofs2(0), b0(0), buffer(bsz) {}
+
+size_t BufferedIOWriter::operator()(
+ const void* ptr,
+ size_t unitsize,
+ size_t nitems) {
+ size_t size = unitsize * nitems;
+ if (size == 0)
+ return 0;
+ const char* src = (const char*)ptr;
+ size_t nb;
+
+ { // copy as many bytes as possible to buffer
+ nb = std::min(bsz - b0, size);
+ memcpy(buffer.data() + b0, src, nb);
+ b0 += nb;
+ src += nb;
+ size -= nb;
+ }
+ while (size > 0) {
+ assert(b0 == bsz);
+ // now we need to flush to add more bytes
+ size_t ofs_2 = 0;
+ do {
+ assert(ofs_2 < 10000000);
+ size_t written = (*writer)(buffer.data() + ofs_2, 1, bsz - ofs_2);
+ FAISS_THROW_IF_NOT(written > 0);
+ ofs_2 += written;
+ } while (ofs_2 != bsz);
+
+ // copy src to buffer
+ size_t nb1 = std::min(bsz, size);
+ memcpy(buffer.data(), src, nb1);
+ b0 = nb1;
+ nb += nb1;
+ src += nb1;
+ size -= nb1;
+ }
+ ofs2 += nb;
+ return nb / unitsize;
+}
+
+BufferedIOWriter::~BufferedIOWriter() {
+ size_t ofs_2 = 0;
+ while (ofs_2 != b0) {
+ // printf("Destructor write %zd \n", b0 - ofs_2);
+ size_t written = (*writer)(buffer.data() + ofs_2, 1, b0 - ofs_2);
+ FAISS_THROW_IF_NOT(written > 0);
+ ofs_2 += written;
+ }
+}
+
+uint32_t fourcc(const char sx[4]) {
+ FAISS_THROW_IF_NOT(4 == strlen(sx));
+ const unsigned char* x = (unsigned char*)sx;
+ return x[0] | x[1] << 8 | x[2] << 16 | x[3] << 24;
+}
+
+uint32_t fourcc(const std::string& sx) {
+ FAISS_THROW_IF_NOT(sx.length() == 4);
+ const unsigned char* x = (unsigned char*)sx.c_str();
+ return x[0] | x[1] << 8 | x[2] << 16 | x[3] << 24;
+}
+
+void fourcc_inv(uint32_t x, char str[5]) {
+ *(uint32_t*)str = x;
+ str[4] = 0;
+}
+
+std::string fourcc_inv(uint32_t x) {
+ char str[5];
+ fourcc_inv(x, str);
+ return std::string(str);
+}
+
+std::string fourcc_inv_printable(uint32_t x) {
+ char cstr[5];
+ fourcc_inv(x, cstr);
+ std::string str = "";
+ for (int i = 0; i < 4; i++) {
+ uint8_t c = cstr[i];
+ if (32 <= c && c < 127) {
+ str += c;
+ } else {
+ char buf[10];
+ snprintf(buf, sizeof(buf), "\\x%02x", c);
+ str += buf;
+ }
+ }
+ return str;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io.h
new file mode 100644
index 0000000..ebd640f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io.h
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/***********************************************************
+ * Abstract I/O objects
+ *
+ * I/O is always sequential, seek does not need to be supported
+ * (indexes could be read or written to a pipe).
+ ***********************************************************/
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <string>
+#include <vector>
+
+namespace faiss {
+
+struct IOReader {
+ // name that can be used in error messages
+ std::string name;
+
+ // fread. Returns number of items read or 0 in case of EOF.
+ virtual size_t operator()(void* ptr, size_t size, size_t nitems) = 0;
+
+ // return a file number that can be memory-mapped
+ virtual int filedescriptor();
+
+ virtual ~IOReader() {}
+};
+
+struct IOWriter {
+ // name that can be used in error messages
+ std::string name;
+
+ // fwrite. Return number of items written
+ virtual size_t operator()(const void* ptr, size_t size, size_t nitems) = 0;
+
+ // return a file number that can be memory-mapped
+ virtual int filedescriptor();
+
+ virtual ~IOWriter() noexcept(false) {}
+};
+
+struct VectorIOReader : IOReader {
+ std::vector<uint8_t> data;
+ size_t rp = 0;
+ size_t operator()(void* ptr, size_t size, size_t nitems) override;
+};
+
+struct VectorIOWriter : IOWriter {
+ std::vector<uint8_t> data;
+ size_t operator()(const void* ptr, size_t size, size_t nitems) override;
+};
+
+struct FileIOReader : IOReader {
+ FILE* f = nullptr;
+ bool need_close = false;
+
+ FileIOReader(FILE* rf);
+
+ FileIOReader(const char* fname);
+
+ ~FileIOReader() override;
+
+ size_t operator()(void* ptr, size_t size, size_t nitems) override;
+
+ int filedescriptor() override;
+};
+
+struct FileIOWriter : IOWriter {
+ FILE* f = nullptr;
+ bool need_close = false;
+
+ FileIOWriter(FILE* wf);
+
+ FileIOWriter(const char* fname);
+
+ ~FileIOWriter() override;
+
+ size_t operator()(const void* ptr, size_t size, size_t nitems) override;
+
+ int filedescriptor() override;
+};
+
+/*******************************************************
+ * Buffered reader + writer
+ *
+ * They attempt to read and write only buffers of size bsz to the
+ * underlying reader or writer. This is done by splitting or merging
+ * the read/write functions.
+ *******************************************************/
+
+/** wraps an ioreader to make buffered reads to avoid too small reads */
+struct BufferedIOReader : IOReader {
+ IOReader* reader;
+ size_t bsz;
+ size_t ofs; ///< offset in input stream
+ size_t ofs2; ///< number of bytes returned to caller
+ size_t b0, b1; ///< range of available bytes in the buffer
+ std::vector<char> buffer;
+
+ /**
+ * @param bsz buffer size (bytes). Reads will be done by batched of
+ * this size
+ */
+ explicit BufferedIOReader(IOReader* reader, size_t bsz = 1024 * 1024);
+
+ size_t operator()(void* ptr, size_t size, size_t nitems) override;
+};
+
+struct BufferedIOWriter : IOWriter {
+ IOWriter* writer;
+ size_t bsz;
+ size_t ofs;
+ size_t ofs2; ///< number of bytes received from caller
+ size_t b0; ///< amount of data in buffer
+ std::vector<char> buffer;
+
+ explicit BufferedIOWriter(IOWriter* writer, size_t bsz = 1024 * 1024);
+
+ size_t operator()(const void* ptr, size_t size, size_t nitems) override;
+
+ // flushes
+ ~BufferedIOWriter() override;
+};
+
+/// cast a 4-character string to a uint32_t that can be written and read easily
+uint32_t fourcc(const char sx[4]);
+uint32_t fourcc(const std::string& sx);
+
+// decoding of fourcc (int32 -> string)
+void fourcc_inv(uint32_t x, char str[5]);
+std::string fourcc_inv(uint32_t x);
+std::string fourcc_inv_printable(uint32_t x);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io_macros.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io_macros.h
new file mode 100644
index 0000000..5449ba1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/io_macros.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/maybe_owned_vector.h>
+
+/*************************************************************
+ * I/O macros
+ *
+ * we use macros so that we have a line number to report in abort
+ * (). This makes debugging a lot easier. The IOReader or IOWriter is
+ * always called f and thus is not passed in as a macro parameter.
+ **************************************************************/
+
+#define READANDCHECK(ptr, n) \
+ { \
+ size_t ret = (*f)(ptr, sizeof(*(ptr)), n); \
+ FAISS_THROW_IF_NOT_FMT( \
+ ret == (n), \
+ "read error in %s: %zd != %zd (%s)", \
+ f->name.c_str(), \
+ ret, \
+ size_t(n), \
+ strerror(errno)); \
+ }
+
+#define READ1(x) READANDCHECK(&(x), 1)
+
+#define READ1_DUMMY(x_type) \
+ { \
+ x_type x = {}; \
+ READ1(x); \
+ }
+
+// will fail if we write 256G of data at once...
+#define READVECTOR(vec) \
+ { \
+ size_t size; \
+ READANDCHECK(&size, 1); \
+ FAISS_THROW_IF_NOT(size >= 0 && size < (uint64_t{1} << 40)); \
+ (vec).resize(size); \
+ READANDCHECK((vec).data(), size); \
+ }
+
+#define WRITEANDCHECK(ptr, n) \
+ { \
+ size_t ret = (*f)(ptr, sizeof(*(ptr)), n); \
+ FAISS_THROW_IF_NOT_FMT( \
+ ret == (n), \
+ "write error in %s: %zd != %zd (%s)", \
+ f->name.c_str(), \
+ ret, \
+ size_t(n), \
+ strerror(errno)); \
+ }
+
+#define WRITE1(x) WRITEANDCHECK(&(x), 1)
+
+#define WRITEVECTOR(vec) \
+ { \
+ size_t size = (vec).size(); \
+ WRITEANDCHECK(&size, 1); \
+ WRITEANDCHECK((vec).data(), size); \
+ }
+
+// read/write xb vector for backwards compatibility of IndexFlat
+
+#define WRITEXBVECTOR(vec) \
+ { \
+ FAISS_THROW_IF_NOT((vec).size() % 4 == 0); \
+ size_t size = (vec).size() / 4; \
+ WRITEANDCHECK(&size, 1); \
+ WRITEANDCHECK((vec).data(), size * 4); \
+ }
+
+#define READXBVECTOR(vec) \
+ { \
+ size_t size; \
+ READANDCHECK(&size, 1); \
+ FAISS_THROW_IF_NOT(size >= 0 && size < (uint64_t{1} << 40)); \
+ size *= 4; \
+ (vec).resize(size); \
+ READANDCHECK((vec).data(), size); \
+ }
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/kmeans1d.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/kmeans1d.cpp
new file mode 100644
index 0000000..0f607fd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/kmeans1d.cpp
@@ -0,0 +1,301 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <algorithm>
+#include <cstring>
+#include <functional>
+#include <numeric>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/kmeans1d.h>
+
+namespace faiss {
+
+using LookUpFunc = std::function<float(idx_t, idx_t)>;
+
+void reduce(
+ const std::vector<idx_t>& rows,
+ const std::vector<idx_t>& input_cols,
+ const LookUpFunc& lookup,
+ std::vector<idx_t>& output_cols) {
+ for (idx_t col : input_cols) {
+ while (!output_cols.empty()) {
+ idx_t row = rows[output_cols.size() - 1];
+ float a = lookup(row, col);
+ float b = lookup(row, output_cols.back());
+ if (a >= b) { // defeated
+ break;
+ }
+ output_cols.pop_back();
+ }
+ if (output_cols.size() < rows.size()) {
+ output_cols.push_back(col);
+ }
+ }
+}
+
+void interpolate(
+ const std::vector<idx_t>& rows,
+ const std::vector<idx_t>& cols,
+ const LookUpFunc& lookup,
+ idx_t* argmins) {
+ std::unordered_map<idx_t, idx_t> idx_to_col;
+ for (idx_t idx = 0; idx < cols.size(); ++idx) {
+ idx_to_col[cols[idx]] = idx;
+ }
+
+ idx_t start = 0;
+ for (idx_t r = 0; r < rows.size(); r += 2) {
+ idx_t row = rows[r];
+ idx_t end = cols.size() - 1;
+ if (r < rows.size() - 1) {
+ idx_t idx = argmins[rows[r + 1]];
+ end = idx_to_col[idx];
+ }
+ idx_t argmin = cols[start];
+ float min = lookup(row, argmin);
+ for (idx_t c = start + 1; c <= end; c++) {
+ float value = lookup(row, cols[c]);
+ if (value < min) {
+ argmin = cols[c];
+ min = value;
+ }
+ }
+ argmins[row] = argmin;
+ start = end;
+ }
+}
+
+/** SMAWK algo. Find the row minima of a monotone matrix.
+ *
+ * References:
+ * 1. http://web.cs.unlv.edu/larmore/Courses/CSC477/monge.pdf
+ * 2. https://gist.github.com/dstein64/8e94a6a25efc1335657e910ff525f405
+ * 3. https://github.com/dstein64/kmeans1d
+ */
+void smawk_impl(
+ const std::vector<idx_t>& rows,
+ const std::vector<idx_t>& input_cols,
+ const LookUpFunc& lookup,
+ idx_t* argmins) {
+ if (rows.size() == 0) {
+ return;
+ }
+
+ /**********************************
+ * REDUCE
+ **********************************/
+ auto ptr = &input_cols;
+ std::vector<idx_t> survived_cols; // survived columns
+ if (rows.size() < input_cols.size()) {
+ reduce(rows, input_cols, lookup, survived_cols);
+ ptr = &survived_cols;
+ }
+ auto& cols = *ptr; // avoid memory copy
+
+ /**********************************
+ * INTERPOLATE
+ **********************************/
+
+ // call recursively on odd-indexed rows
+ std::vector<idx_t> odd_rows;
+ for (idx_t i = 1; i < rows.size(); i += 2) {
+ odd_rows.push_back(rows[i]);
+ }
+ smawk_impl(odd_rows, cols, lookup, argmins);
+
+ // interpolate the even-indexed rows
+ interpolate(rows, cols, lookup, argmins);
+}
+
+void smawk(
+ const idx_t nrows,
+ const idx_t ncols,
+ const LookUpFunc& lookup,
+ idx_t* argmins) {
+ std::vector<idx_t> rows(nrows);
+ std::vector<idx_t> cols(ncols);
+ std::iota(std::begin(rows), std::end(rows), 0);
+ std::iota(std::begin(cols), std::end(cols), 0);
+
+ smawk_impl(rows, cols, lookup, argmins);
+}
+
+void smawk(
+ const idx_t nrows,
+ const idx_t ncols,
+ const float* x,
+ idx_t* argmins) {
+ auto lookup = [&x, &ncols](idx_t i, idx_t j) { return x[i * ncols + j]; };
+ smawk(nrows, ncols, lookup, argmins);
+}
+
+namespace {
+
+class CostCalculator {
+ // The reuslt would be inaccurate if we use float
+ std::vector<double> cumsum;
+ std::vector<double> cumsum2;
+
+ public:
+ CostCalculator(const std::vector<float>& vec, idx_t n) {
+ cumsum.push_back(0.0);
+ cumsum2.push_back(0.0);
+ for (idx_t i = 0; i < n; ++i) {
+ float x = vec[i];
+ cumsum.push_back(x + cumsum[i]);
+ cumsum2.push_back(x * x + cumsum2[i]);
+ }
+ }
+
+ float operator()(idx_t i, idx_t j) {
+ if (j < i) {
+ return 0.0f;
+ }
+ auto mu = (cumsum[j + 1] - cumsum[i]) / (j - i + 1);
+ auto result = cumsum2[j + 1] - cumsum2[i];
+ result += (j - i + 1) * (mu * mu);
+ result -= (2 * mu) * (cumsum[j + 1] - cumsum[i]);
+ return float(result);
+ }
+};
+
+template <class T>
+class Matrix {
+ std::vector<T> data;
+ idx_t nrows;
+ idx_t ncols;
+
+ public:
+ Matrix(idx_t nrows, idx_t ncols) {
+ this->nrows = nrows;
+ this->ncols = ncols;
+ data.resize(nrows * ncols);
+ }
+
+ inline T& at(idx_t i, idx_t j) {
+ return data[i * ncols + j];
+ }
+};
+
+} // anonymous namespace
+
+double kmeans1d(const float* x, size_t n, size_t nclusters, float* centroids) {
+ FAISS_THROW_IF_NOT(n >= nclusters);
+
+ // corner case
+ if (n == nclusters) {
+ memcpy(centroids, x, n * sizeof(*x));
+ return 0.0f;
+ }
+
+ /***************************************************
+ * sort in ascending order, O(NlogN) in time
+ ***************************************************/
+ std::vector<float> arr(x, x + n);
+ std::sort(arr.begin(), arr.end());
+
+ /***************************************************
+ dynamic programming algorithm
+
+ Reference: https://arxiv.org/abs/1701.07204
+ -------------------------------
+
+ Assume x is already sorted in ascending order.
+
+ N: number of points
+ K: number of clusters
+
+ CC(i, j): the cost of grouping xi,...,xj into one cluster
+ D[k][m]: the cost of optimally clustering x1,...,xm into k clusters
+ T[k][m]: the start index of the k-th cluster
+
+ The DP process is as follow:
+ D[k][m] = min_i D[k − 1][i − 1] + CC(i, m)
+ T[k][m] = argmin_i D[k − 1][i − 1] + CC(i, m)
+
+ This could be solved in O(KN^2) time and O(KN) space.
+
+ To further reduce the time complexity, we use SMAWK algo to
+ solve the argmin problem as follow:
+
+ For each k:
+ C[m][i] = D[k − 1][i − 1] + CC(i, m)
+
+ Here C is a n x n totally monotone matrix.
+ We could find the row minima by SMAWK in O(N) time.
+
+ Now the time complexity is reduced from O(kN^2) to O(KN).
+ ****************************************************/
+
+ CostCalculator CC(arr, n);
+ Matrix<float> D(nclusters, n);
+ Matrix<idx_t> T(nclusters, n);
+
+ for (idx_t m = 0; m < n; m++) {
+ D.at(0, m) = CC(0, m);
+ T.at(0, m) = 0;
+ }
+
+ std::vector<idx_t> indices(nclusters, 0);
+
+ for (idx_t k = 1; k < nclusters; ++k) {
+ // we define C here
+ auto C = [&D, &CC, &k](idx_t m, idx_t i) {
+ if (i == 0) {
+ return CC(i, m);
+ }
+ idx_t col = std::min(m, i - 1);
+ return D.at(k - 1, col) + CC(i, m);
+ };
+
+ std::vector<idx_t> argmins(n); // argmin of each row
+ smawk(n, n, C, argmins.data());
+ for (idx_t m = 0; m < argmins.size(); m++) {
+ idx_t idx = argmins[m];
+ D.at(k, m) = C(m, idx);
+ T.at(k, m) = idx;
+ }
+ }
+
+ /***************************************************
+ compute centroids by backtracking
+
+ T[K - 1][T[K][N] - 1] T[K][N] N
+ --------------|------------------------|-----------|
+ | cluster K - 1 | cluster K |
+
+ ****************************************************/
+
+ // for imbalance factor
+ double tot = 0.0;
+ double uf = 0.0;
+
+ idx_t end = n;
+ for (idx_t k = nclusters - 1; k >= 0; k--) {
+ const idx_t start = T.at(k, end - 1);
+ const float sum =
+ std::accumulate(arr.data() + start, arr.data() + end, 0.0f);
+ const idx_t size = end - start;
+ FAISS_THROW_IF_NOT_FMT(
+ size > 0, "Cluster %d: size %d", int(k), int(size));
+ centroids[k] = sum / size;
+ end = start;
+
+ tot += size;
+ uf += size * double(size);
+ }
+
+ uf = uf * nclusters / (tot * tot);
+ return uf;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/kmeans1d.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/kmeans1d.h
new file mode 100644
index 0000000..c823ae5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/kmeans1d.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <functional>
+
+namespace faiss {
+
+/** SMAWK algorithm. Find the row minima of a monotone matrix.
+ *
+ * Expose this for testing.
+ *
+ * @param nrows number of rows
+ * @param ncols number of columns
+ * @param x input matrix, size (nrows, ncols)
+ * @param argmins argmin of each row
+ */
+void smawk(
+ const idx_t nrows,
+ const idx_t ncols,
+ const float* x,
+ idx_t* argmins);
+
+/** Exact 1D K-Means by dynamic programming
+ *
+ * From "Fast Exact k-Means, k-Medians and Bregman Divergence Clustering in 1D"
+ * Allan Grønlund, Kasper Green Larsen, Alexander Mathiasen, Jesper Sindahl
+ * Nielsen, Stefan Schneider, Mingzhou Song, ArXiV'17
+ *
+ * Section 2.2
+ *
+ * https://arxiv.org/abs/1701.07204
+ *
+ * @param x input 1D array
+ * @param n input array length
+ * @param nclusters number of clusters
+ * @param centroids output centroids, size nclusters
+ * @return imbalancce factor
+ */
+double kmeans1d(const float* x, size_t n, size_t nclusters, float* centroids);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/lattice_Zn.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/lattice_Zn.cpp
new file mode 100644
index 0000000..6ffd3c1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/lattice_Zn.cpp
@@ -0,0 +1,664 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/impl/lattice_Zn.h>
+
+#include <cassert>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+
+#include <algorithm>
+#include <queue>
+#include <unordered_set>
+
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/distances.h>
+
+namespace faiss {
+
+/********************************************
+ * small utility functions
+ ********************************************/
+
+namespace {
+
+inline float sqr(float x) {
+ return x * x;
+}
+
+typedef std::vector<float> point_list_t;
+
+struct Comb {
+ std::vector<uint64_t> tab; // Pascal's triangle
+ int nmax;
+
+ explicit Comb(int nmax) : nmax(nmax) {
+ tab.resize(nmax * nmax, 0);
+ tab[0] = 1;
+ for (int i = 1; i < nmax; i++) {
+ tab[i * nmax] = 1;
+ for (int j = 1; j <= i; j++) {
+ tab[i * nmax + j] =
+ tab[(i - 1) * nmax + j] + tab[(i - 1) * nmax + (j - 1)];
+ }
+ }
+ }
+
+ uint64_t operator()(int n, int p) const {
+ assert(n < nmax && p < nmax);
+ if (p > n)
+ return 0;
+ return tab[n * nmax + p];
+ }
+};
+
+Comb comb(100);
+
+// compute combinations of n integer values <= v that sum up to total (squared)
+point_list_t sum_of_sq(float total, int v, int n, float add = 0) {
+ if (total < 0) {
+ return point_list_t();
+ } else if (n == 1) {
+ while (sqr(v + add) > total)
+ v--;
+ if (sqr(v + add) == total) {
+ return point_list_t(1, v + add);
+ } else {
+ return point_list_t();
+ }
+ } else {
+ point_list_t res;
+ while (v >= 0) {
+ point_list_t sub_points =
+ sum_of_sq(total - sqr(v + add), v, n - 1, add);
+ for (size_t i = 0; i < sub_points.size(); i += n - 1) {
+ res.push_back(v + add);
+ for (int j = 0; j < n - 1; j++) {
+ res.push_back(sub_points[i + j]);
+ }
+ }
+ v--;
+ }
+ return res;
+ }
+}
+
+int decode_comb_1(uint64_t* n, int k1, int r) {
+ while (comb(r, k1) > *n) {
+ r--;
+ }
+ *n -= comb(r, k1);
+ return r;
+}
+
+// optimized version for < 64 bits
+uint64_t repeats_encode_64(
+ const std::vector<Repeat>& repeats,
+ int dim,
+ const float* c) {
+ uint64_t coded = 0;
+ int nfree = dim;
+ uint64_t code = 0, shift = 1;
+ for (auto r = repeats.begin(); r != repeats.end(); ++r) {
+ int rank = 0, occ = 0;
+ uint64_t code_comb = 0;
+ uint64_t tosee = ~coded;
+ for (;;) {
+ // directly jump to next available slot.
+ int i = __builtin_ctzll(tosee);
+ tosee &= ~(uint64_t{1} << i);
+ if (c[i] == r->val) {
+ code_comb += comb(rank, occ + 1);
+ occ++;
+ coded |= uint64_t{1} << i;
+ if (occ == r->n)
+ break;
+ }
+ rank++;
+ }
+ uint64_t max_comb = comb(nfree, r->n);
+ code += shift * code_comb;
+ shift *= max_comb;
+ nfree -= r->n;
+ }
+ return code;
+}
+
+void repeats_decode_64(
+ const std::vector<Repeat>& repeats,
+ int dim,
+ uint64_t code,
+ float* c) {
+ uint64_t decoded = 0;
+ int nfree = dim;
+ for (auto r = repeats.begin(); r != repeats.end(); ++r) {
+ uint64_t max_comb = comb(nfree, r->n);
+ uint64_t code_comb = code % max_comb;
+ code /= max_comb;
+
+ int occ = 0;
+ int rank = nfree;
+ int next_rank = decode_comb_1(&code_comb, r->n, rank);
+ uint64_t tosee = ((uint64_t{1} << dim) - 1) ^ decoded;
+ for (;;) {
+ int i = 63 - __builtin_clzll(tosee);
+ tosee &= ~(uint64_t{1} << i);
+ rank--;
+ if (rank == next_rank) {
+ decoded |= uint64_t{1} << i;
+ c[i] = r->val;
+ occ++;
+ if (occ == r->n)
+ break;
+ next_rank = decode_comb_1(&code_comb, r->n - occ, next_rank);
+ }
+ }
+ nfree -= r->n;
+ }
+}
+
+} // anonymous namespace
+
+Repeats::Repeats(int dim, const float* c) : dim(dim) {
+ for (int i = 0; i < dim; i++) {
+ int j = 0;
+ for (;;) {
+ if (j == repeats.size()) {
+ repeats.push_back(Repeat{c[i], 1});
+ break;
+ }
+ if (repeats[j].val == c[i]) {
+ repeats[j].n++;
+ break;
+ }
+ j++;
+ }
+ }
+}
+
+uint64_t Repeats::count() const {
+ uint64_t accu = 1;
+ int remain = dim;
+ for (int i = 0; i < repeats.size(); i++) {
+ accu *= comb(remain, repeats[i].n);
+ remain -= repeats[i].n;
+ }
+ return accu;
+}
+
+// version with a bool vector that works for > 64 dim
+uint64_t Repeats::encode(const float* c) const {
+ if (dim < 64) {
+ return repeats_encode_64(repeats, dim, c);
+ }
+ std::vector<bool> coded(dim, false);
+ int nfree = dim;
+ uint64_t code = 0, shift = 1;
+ for (auto r = repeats.begin(); r != repeats.end(); ++r) {
+ int rank = 0, occ = 0;
+ uint64_t code_comb = 0;
+ for (int i = 0; i < dim; i++) {
+ if (!coded[i]) {
+ if (c[i] == r->val) {
+ code_comb += comb(rank, occ + 1);
+ occ++;
+ coded[i] = true;
+ if (occ == r->n)
+ break;
+ }
+ rank++;
+ }
+ }
+ uint64_t max_comb = comb(nfree, r->n);
+ code += shift * code_comb;
+ shift *= max_comb;
+ nfree -= r->n;
+ }
+ return code;
+}
+
+void Repeats::decode(uint64_t code, float* c) const {
+ if (dim < 64) {
+ repeats_decode_64(repeats, dim, code, c);
+ return;
+ }
+
+ std::vector<bool> decoded(dim, false);
+ int nfree = dim;
+ for (auto r = repeats.begin(); r != repeats.end(); ++r) {
+ uint64_t max_comb = comb(nfree, r->n);
+ uint64_t code_comb = code % max_comb;
+ code /= max_comb;
+
+ int occ = 0;
+ int rank = nfree;
+ int next_rank = decode_comb_1(&code_comb, r->n, rank);
+ for (int i = dim - 1; i >= 0; i--) {
+ if (!decoded[i]) {
+ rank--;
+ if (rank == next_rank) {
+ decoded[i] = true;
+ c[i] = r->val;
+ occ++;
+ if (occ == r->n)
+ break;
+ next_rank =
+ decode_comb_1(&code_comb, r->n - occ, next_rank);
+ }
+ }
+ }
+ nfree -= r->n;
+ }
+}
+
+/********************************************
+ * EnumeratedVectors functions
+ ********************************************/
+
+void EnumeratedVectors::encode_multi(size_t n, const float* c, uint64_t* codes)
+ const {
+#pragma omp parallel if (n > 1000)
+ {
+#pragma omp for
+ for (int i = 0; i < n; i++) {
+ codes[i] = encode(c + i * dim);
+ }
+ }
+}
+
+void EnumeratedVectors::decode_multi(size_t n, const uint64_t* codes, float* c)
+ const {
+#pragma omp parallel if (n > 1000)
+ {
+#pragma omp for
+ for (int i = 0; i < n; i++) {
+ decode(codes[i], c + i * dim);
+ }
+ }
+}
+
+void EnumeratedVectors::find_nn(
+ size_t nc,
+ const uint64_t* codes,
+ size_t nq,
+ const float* xq,
+ int64_t* labels,
+ float* distances) {
+ for (size_t i = 0; i < nq; i++) {
+ distances[i] = -1e20;
+ labels[i] = -1;
+ }
+
+ std::vector<float> c(dim);
+ for (size_t i = 0; i < nc; i++) {
+ uint64_t code = codes[nc];
+ decode(code, c.data());
+ for (size_t j = 0; j < nq; j++) {
+ const float* x = xq + j * dim;
+ float dis = fvec_inner_product(x, c.data(), dim);
+ if (dis > distances[j]) {
+ distances[j] = dis;
+ labels[j] = i;
+ }
+ }
+ }
+}
+
+/**********************************************************
+ * ZnSphereSearch
+ **********************************************************/
+
+ZnSphereSearch::ZnSphereSearch(int dim, int r2) : dimS(dim), r2(r2) {
+ voc = sum_of_sq(r2, int(ceil(sqrt(r2)) + 1), dim);
+ natom = voc.size() / dim;
+}
+
+float ZnSphereSearch::search(const float* x, float* c) const {
+ std::vector<float> tmp(dimS * 2);
+ std::vector<int> tmp_int(dimS);
+ return search(x, c, tmp.data(), tmp_int.data());
+}
+
+float ZnSphereSearch::search(
+ const float* x,
+ float* c,
+ float* tmp, // size 2 *dim
+ int* tmp_int, // size dim
+ int* ibest_out) const {
+ int dim = dimS;
+ assert(natom > 0);
+ int* o = tmp_int;
+ float* xabs = tmp;
+ float* xperm = tmp + dim;
+
+ // argsort
+ for (int i = 0; i < dim; i++) {
+ o[i] = i;
+ xabs[i] = fabsf(x[i]);
+ }
+ std::sort(o, o + dim, [xabs](int a, int b) { return xabs[a] > xabs[b]; });
+ for (int i = 0; i < dim; i++) {
+ xperm[i] = xabs[o[i]];
+ }
+ // find best
+ int ibest = -1;
+ float dpbest = -100;
+ for (int i = 0; i < natom; i++) {
+ float dp = fvec_inner_product(voc.data() + i * dim, xperm, dim);
+ if (dp > dpbest) {
+ dpbest = dp;
+ ibest = i;
+ }
+ }
+ // revert sort
+ const float* cin = voc.data() + ibest * dim;
+ for (int i = 0; i < dim; i++) {
+ c[o[i]] = copysignf(cin[i], x[o[i]]);
+ }
+ if (ibest_out) {
+ *ibest_out = ibest;
+ }
+ return dpbest;
+}
+
+void ZnSphereSearch::search_multi(
+ int n,
+ const float* x,
+ float* c_out,
+ float* dp_out) {
+#pragma omp parallel if (n > 1000)
+ {
+#pragma omp for
+ for (int i = 0; i < n; i++) {
+ dp_out[i] = search(x + i * dimS, c_out + i * dimS);
+ }
+ }
+}
+
+/**********************************************************
+ * ZnSphereCodec
+ **********************************************************/
+
+ZnSphereCodec::ZnSphereCodec(int dim, int r2)
+ : ZnSphereSearch(dim, r2), EnumeratedVectors(dim) {
+ nv = 0;
+ for (int i = 0; i < natom; i++) {
+ Repeats repeats(dim, &voc[i * dim]);
+ CodeSegment cs(repeats);
+ cs.c0 = nv;
+ Repeat& br = repeats.repeats.back();
+ cs.signbits = br.val == 0 ? dim - br.n : dim;
+ code_segments.push_back(cs);
+ nv += repeats.count() << cs.signbits;
+ }
+
+ uint64_t nvx = nv;
+ code_size = 0;
+ while (nvx > 0) {
+ nvx >>= 8;
+ code_size++;
+ }
+}
+
+uint64_t ZnSphereCodec::search_and_encode(const float* x) const {
+ std::vector<float> tmp(dim * 2);
+ std::vector<int> tmp_int(dim);
+ int ano; // atom number
+ std::vector<float> c(dim);
+ search(x, c.data(), tmp.data(), tmp_int.data(), &ano);
+ uint64_t signs = 0;
+ std::vector<float> cabs(dim);
+ int nnz = 0;
+ for (int i = 0; i < dim; i++) {
+ cabs[i] = fabs(c[i]);
+ if (c[i] != 0) {
+ if (c[i] < 0) {
+ signs |= uint64_t{1} << nnz;
+ }
+ nnz++;
+ }
+ }
+ const CodeSegment& cs = code_segments[ano];
+ assert(nnz == cs.signbits);
+ uint64_t code = cs.c0 + signs;
+ code += cs.encode(cabs.data()) << cs.signbits;
+ return code;
+}
+
+uint64_t ZnSphereCodec::encode(const float* x) const {
+ return search_and_encode(x);
+}
+
+void ZnSphereCodec::decode(uint64_t code, float* c) const {
+ int i0 = 0, i1 = natom;
+ while (i0 + 1 < i1) {
+ int imed = (i0 + i1) / 2;
+ if (code_segments[imed].c0 <= code)
+ i0 = imed;
+ else
+ i1 = imed;
+ }
+ const CodeSegment& cs = code_segments[i0];
+ code -= cs.c0;
+ uint64_t signs = code;
+ code >>= cs.signbits;
+ cs.decode(code, c);
+
+ int nnz = 0;
+ for (int i = 0; i < dim; i++) {
+ if (c[i] != 0) {
+ if (signs & (uint64_t(1) << nnz)) {
+ c[i] = -c[i];
+ }
+ nnz++;
+ }
+ }
+}
+
+/**************************************************************
+ * ZnSphereCodecRec
+ **************************************************************/
+
+uint64_t ZnSphereCodecRec::get_nv(int ld, int r2a) const {
+ return all_nv[ld * (r2 + 1) + r2a];
+}
+
+uint64_t ZnSphereCodecRec::get_nv_cum(int ld, int r2t, int r2a) const {
+ return all_nv_cum[(ld * (r2 + 1) + r2t) * (r2 + 1) + r2a];
+}
+
+void ZnSphereCodecRec::set_nv_cum(int ld, int r2t, int r2a, uint64_t cum) {
+ all_nv_cum[(ld * (r2 + 1) + r2t) * (r2 + 1) + r2a] = cum;
+}
+
+ZnSphereCodecRec::ZnSphereCodecRec(int dim, int r2)
+ : EnumeratedVectors(dim), r2(r2) {
+ log2_dim = 0;
+ while (dim > (1 << log2_dim)) {
+ log2_dim++;
+ }
+ assert(dim == (1 << log2_dim) || !"dimension must be a power of 2");
+
+ all_nv.resize((log2_dim + 1) * (r2 + 1));
+ all_nv_cum.resize((log2_dim + 1) * (r2 + 1) * (r2 + 1));
+
+ for (int r2a = 0; r2a <= r2; r2a++) {
+ int r = int(sqrt(r2a));
+ if (r * r == r2a) {
+ all_nv[r2a] = r == 0 ? 1 : 2;
+ } else {
+ all_nv[r2a] = 0;
+ }
+ }
+
+ for (int ld = 1; ld <= log2_dim; ld++) {
+ for (int r2sub = 0; r2sub <= r2; r2sub++) {
+ uint64_t nv = 0;
+ for (int r2a = 0; r2a <= r2sub; r2a++) {
+ int r2b = r2sub - r2a;
+ set_nv_cum(ld, r2sub, r2a, nv);
+ nv += get_nv(ld - 1, r2a) * get_nv(ld - 1, r2b);
+ }
+ all_nv[ld * (r2 + 1) + r2sub] = nv;
+ }
+ }
+ nv = get_nv(log2_dim, r2);
+
+ uint64_t nvx = nv;
+ code_size = 0;
+ while (nvx > 0) {
+ nvx >>= 8;
+ code_size++;
+ }
+
+ int cache_level = std::min(3, log2_dim - 1);
+ decode_cache_ld = 0;
+ assert(cache_level <= log2_dim);
+ decode_cache.resize((r2 + 1));
+
+ for (int r2sub = 0; r2sub <= r2; r2sub++) {
+ int ld = cache_level;
+ uint64_t nvi = get_nv(ld, r2sub);
+ std::vector<float>& cache = decode_cache[r2sub];
+ int dimsub = (1 << cache_level);
+ cache.resize(nvi * dimsub);
+ std::vector<float> c(dim);
+ uint64_t code0 = get_nv_cum(cache_level + 1, r2, r2 - r2sub);
+ for (int i = 0; i < nvi; i++) {
+ decode(i + code0, c.data());
+ memcpy(&cache[i * dimsub],
+ c.data() + dim - dimsub,
+ dimsub * sizeof(*c.data()));
+ }
+ }
+ decode_cache_ld = cache_level;
+}
+
+uint64_t ZnSphereCodecRec::encode(const float* c) const {
+ return encode_centroid(c);
+}
+
+uint64_t ZnSphereCodecRec::encode_centroid(const float* c) const {
+ std::vector<uint64_t> codes(dim);
+ std::vector<int> norm2s(dim);
+ for (int i = 0; i < dim; i++) {
+ if (c[i] == 0) {
+ codes[i] = 0;
+ norm2s[i] = 0;
+ } else {
+ int r2i = int(c[i] * c[i]);
+ norm2s[i] = r2i;
+ codes[i] = c[i] >= 0 ? 0 : 1;
+ }
+ }
+ int dim2 = dim / 2;
+ for (int ld = 1; ld <= log2_dim; ld++) {
+ for (int i = 0; i < dim2; i++) {
+ int r2a = norm2s[2 * i];
+ int r2b = norm2s[2 * i + 1];
+
+ uint64_t code_a = codes[2 * i];
+ uint64_t code_b = codes[2 * i + 1];
+
+ codes[i] = get_nv_cum(ld, r2a + r2b, r2a) +
+ code_a * get_nv(ld - 1, r2b) + code_b;
+ norm2s[i] = r2a + r2b;
+ }
+ dim2 /= 2;
+ }
+ return codes[0];
+}
+
+void ZnSphereCodecRec::decode(uint64_t code, float* c) const {
+ std::vector<uint64_t> codes(dim);
+ std::vector<int> norm2s(dim);
+ codes[0] = code;
+ norm2s[0] = r2;
+
+ int dim2 = 1;
+ for (int ld = log2_dim; ld > decode_cache_ld; ld--) {
+ for (int i = dim2 - 1; i >= 0; i--) {
+ int r2sub = norm2s[i];
+ int i0 = 0, i1 = r2sub + 1;
+ uint64_t codei = codes[i];
+ const uint64_t* cum =
+ &all_nv_cum[(ld * (r2 + 1) + r2sub) * (r2 + 1)];
+ while (i1 > i0 + 1) {
+ int imed = (i0 + i1) / 2;
+ if (cum[imed] <= codei)
+ i0 = imed;
+ else
+ i1 = imed;
+ }
+ int r2a = i0, r2b = r2sub - i0;
+ codei -= cum[r2a];
+ norm2s[2 * i] = r2a;
+ norm2s[2 * i + 1] = r2b;
+
+ uint64_t code_a = codei / get_nv(ld - 1, r2b);
+ uint64_t code_b = codei % get_nv(ld - 1, r2b);
+
+ codes[2 * i] = code_a;
+ codes[2 * i + 1] = code_b;
+ }
+ dim2 *= 2;
+ }
+
+ if (decode_cache_ld == 0) {
+ for (int i = 0; i < dim; i++) {
+ if (norm2s[i] == 0) {
+ c[i] = 0;
+ } else {
+ float r = sqrt(norm2s[i]);
+ assert(r * r == norm2s[i]);
+ c[i] = codes[i] == 0 ? r : -r;
+ }
+ }
+ } else {
+ int subdim = 1 << decode_cache_ld;
+ assert((dim2 * subdim) == dim);
+
+ for (int i = 0; i < dim2; i++) {
+ const std::vector<float>& cache = decode_cache[norm2s[i]];
+ assert(codes[i] < cache.size());
+ memcpy(c + i * subdim,
+ &cache[codes[i] * subdim],
+ sizeof(*c) * subdim);
+ }
+ }
+}
+
+// if not use_rec, instantiate an arbitrary harmless znc_rec
+ZnSphereCodecAlt::ZnSphereCodecAlt(int dim, int r2)
+ : ZnSphereCodec(dim, r2),
+ use_rec((dim & (dim - 1)) == 0),
+ znc_rec(use_rec ? dim : 8, use_rec ? r2 : 14) {}
+
+uint64_t ZnSphereCodecAlt::encode(const float* x) const {
+ if (!use_rec) {
+ // it's ok if the vector is not normalized
+ return ZnSphereCodec::encode(x);
+ } else {
+ // find nearest centroid
+ std::vector<float> centroid(dim);
+ search(x, centroid.data());
+ return znc_rec.encode(centroid.data());
+ }
+}
+
+void ZnSphereCodecAlt::decode(uint64_t code, float* c) const {
+ if (!use_rec) {
+ ZnSphereCodec::decode(code, c);
+ } else {
+ znc_rec.decode(code, c);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/lattice_Zn.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/lattice_Zn.h
new file mode 100644
index 0000000..e6da2af
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/lattice_Zn.h
@@ -0,0 +1,188 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+#ifndef FAISS_LATTICE_ZN_H
+#define FAISS_LATTICE_ZN_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include <vector>
+
+namespace faiss {
+
+/** returns the nearest vertex in the sphere to a query. Returns only
+ * the coordinates, not an id.
+ *
+ * Algorithm: all points are derived from a one atom vector up to a
+ * permutation and sign changes. The search function finds the most
+ * appropriate atom and transformation.
+ */
+struct ZnSphereSearch {
+ int dimS, r2;
+ int natom;
+
+ /// size dim * ntatom
+ std::vector<float> voc;
+
+ ZnSphereSearch(int dim, int r2);
+
+ /// find nearest centroid. x does not need to be normalized
+ float search(const float* x, float* c) const;
+
+ /// full call. Requires externally-allocated temp space
+ float search(
+ const float* x,
+ float* c,
+ float* tmp, // size 2 *dim
+ int* tmp_int, // size dim
+ int* ibest_out = nullptr) const;
+
+ // multi-threaded
+ void search_multi(int n, const float* x, float* c_out, float* dp_out);
+};
+
+/***************************************************************************
+ * Support ids as well.
+ *
+ * Limitations: ids are limited to 64 bit
+ ***************************************************************************/
+
+struct EnumeratedVectors {
+ /// size of the collection
+ uint64_t nv;
+ int dim;
+
+ explicit EnumeratedVectors(int dim) : nv(0), dim(dim) {}
+
+ /// encode a vector from a collection
+ virtual uint64_t encode(const float* x) const = 0;
+
+ /// decode it
+ virtual void decode(uint64_t code, float* c) const = 0;
+
+ // call encode on nc vectors
+ void encode_multi(size_t nc, const float* c, uint64_t* codes) const;
+
+ // call decode on nc codes
+ void decode_multi(size_t nc, const uint64_t* codes, float* c) const;
+
+ // find the nearest neighbor of each xq
+ // (decodes and computes distances)
+ void find_nn(
+ size_t n,
+ const uint64_t* codes,
+ size_t nq,
+ const float* xq,
+ int64_t* idx,
+ float* dis);
+
+ virtual ~EnumeratedVectors() {}
+};
+
+struct Repeat {
+ float val;
+ int n;
+};
+
+/** Repeats: used to encode a vector that has n occurrences of
+ * val. Encodes the signs and permutation of the vector. Useful for
+ * atoms.
+ */
+struct Repeats {
+ int dim;
+ std::vector<Repeat> repeats;
+
+ // initialize from a template of the atom.
+ Repeats(int dim = 0, const float* c = nullptr);
+
+ // count number of possible codes for this atom
+ uint64_t count() const;
+
+ uint64_t encode(const float* c) const;
+
+ void decode(uint64_t code, float* c) const;
+};
+
+/** codec that can return ids for the encoded vectors
+ *
+ * uses the ZnSphereSearch to encode the vector by encoding the
+ * permutation and signs. Depends on ZnSphereSearch because it uses
+ * the atom numbers */
+struct ZnSphereCodec : ZnSphereSearch, EnumeratedVectors {
+ struct CodeSegment : Repeats {
+ explicit CodeSegment(const Repeats& r) : Repeats(r) {}
+ uint64_t c0; // first code assigned to segment
+ int signbits;
+ };
+
+ std::vector<CodeSegment> code_segments;
+ uint64_t nv;
+ size_t code_size;
+
+ ZnSphereCodec(int dim, int r2);
+
+ uint64_t search_and_encode(const float* x) const;
+
+ void decode(uint64_t code, float* c) const override;
+
+ /// takes vectors that do not need to be centroids
+ uint64_t encode(const float* x) const override;
+};
+
+/** recursive sphere codec
+ *
+ * Uses a recursive decomposition on the dimensions to encode
+ * centroids found by the ZnSphereSearch. The codes are *not*
+ * compatible with the ones of ZnSpehreCodec
+ */
+struct ZnSphereCodecRec : EnumeratedVectors {
+ int r2;
+
+ int log2_dim;
+ int code_size;
+
+ ZnSphereCodecRec(int dim, int r2);
+
+ uint64_t encode_centroid(const float* c) const;
+
+ void decode(uint64_t code, float* c) const override;
+
+ /// vectors need to be centroids (does not work on arbitrary
+ /// vectors)
+ uint64_t encode(const float* x) const override;
+
+ std::vector<uint64_t> all_nv;
+ std::vector<uint64_t> all_nv_cum;
+
+ int decode_cache_ld;
+ std::vector<std::vector<float>> decode_cache;
+
+ // nb of vectors in the sphere in dim 2^ld with r2 radius
+ uint64_t get_nv(int ld, int r2a) const;
+
+ // cumulative version
+ uint64_t get_nv_cum(int ld, int r2t, int r2a) const;
+ void set_nv_cum(int ld, int r2t, int r2a, uint64_t v);
+};
+
+/** Codec that uses the recursive codec if dim is a power of 2 and
+ * the regular one otherwise */
+struct ZnSphereCodecAlt : ZnSphereCodec {
+ bool use_rec;
+ ZnSphereCodecRec znc_rec;
+
+ ZnSphereCodecAlt(int dim, int r2);
+
+ uint64_t encode(const float* x) const override;
+
+ void decode(uint64_t code, float* c) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/mapped_io.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/mapped_io.cpp
new file mode 100644
index 0000000..7c12544
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/mapped_io.cpp
@@ -0,0 +1,378 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <memory>
+
+#ifdef __linux__
+
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#elif defined(_WIN32)
+
+#include <Windows.h> // @manual
+#include <io.h> // @manual
+
+#elif defined(__APPLE__) || defined(__MACH__)
+
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#endif
+
+#include <cstring>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/mapped_io.h>
+
+namespace faiss {
+
+#ifdef __linux__
+
+struct MmappedFileMappingOwner::PImpl {
+ void* ptr = nullptr;
+ size_t ptr_size = 0;
+
+ PImpl(const std::string& filename) {
+ auto f = std::unique_ptr<FILE, decltype(&fclose)>(
+ fopen(filename.c_str(), "r"), &fclose);
+ FAISS_THROW_IF_NOT_FMT(
+ f.get(),
+ "could not open %s for reading: %s",
+ filename.c_str(),
+ strerror(errno));
+
+ // get the size
+ struct stat s;
+ int status = fstat(fileno(f.get()), &s);
+ FAISS_THROW_IF_NOT_FMT(
+ status >= 0, "fstat() failed: %s", strerror(errno));
+
+ const size_t filesize = s.st_size;
+
+ void* address = mmap(
+ nullptr, filesize, PROT_READ, MAP_SHARED, fileno(f.get()), 0);
+ FAISS_THROW_IF_NOT_FMT(
+ address != nullptr, "could not mmap(): %s", strerror(errno));
+
+ // btw, fd can be closed here
+
+ madvise(address, filesize, MADV_RANDOM);
+
+ // save it
+ ptr = address;
+ ptr_size = filesize;
+ }
+
+ PImpl(FILE* f) {
+ // get the size
+ struct stat s;
+ int status = fstat(fileno(f), &s);
+ FAISS_THROW_IF_NOT_FMT(
+ status >= 0, "fstat() failed: %s", strerror(errno));
+
+ const size_t filesize = s.st_size;
+
+ void* address =
+ mmap(nullptr, filesize, PROT_READ, MAP_SHARED, fileno(f), 0);
+ FAISS_THROW_IF_NOT_FMT(
+ address != nullptr, "could not mmap(): %s", strerror(errno));
+
+ // btw, fd can be closed here
+
+ madvise(address, filesize, MADV_RANDOM);
+
+ // save it
+ ptr = address;
+ ptr_size = filesize;
+ }
+
+ ~PImpl() {
+ // todo: check for an error
+ munmap(ptr, ptr_size);
+ }
+};
+
+#elif defined(_WIN32)
+
+struct MmappedFileMappingOwner::PImpl {
+ void* ptr = nullptr;
+ size_t ptr_size = 0;
+ HANDLE mapping_handle = INVALID_HANDLE_VALUE;
+
+ PImpl(const std::string& filename) {
+ HANDLE file_handle = CreateFile(
+ filename.c_str(),
+ GENERIC_READ,
+ FILE_SHARE_READ,
+ nullptr,
+ OPEN_EXISTING,
+ 0,
+ nullptr);
+ if (file_handle == INVALID_HANDLE_VALUE) {
+ const auto error = GetLastError();
+ FAISS_THROW_FMT(
+ "could not open the file, %s (error %d)",
+ filename.c_str(),
+ error);
+ }
+
+ // get the size of the file
+ LARGE_INTEGER len_li;
+ if (GetFileSizeEx(file_handle, &len_li) == 0) {
+ const auto error = GetLastError();
+
+ CloseHandle(file_handle);
+
+ FAISS_THROW_FMT(
+ "could not get the file size, %s (error %d)",
+ filename.c_str(),
+ error);
+ }
+
+ // create a mapping
+ mapping_handle = CreateFileMapping(
+ file_handle, nullptr, PAGE_READONLY, 0, 0, nullptr);
+ if (mapping_handle == 0) {
+ const auto error = GetLastError();
+
+ CloseHandle(file_handle);
+
+ FAISS_THROW_FMT(
+ "could not create a file mapping, %s (error %d)",
+ filename.c_str(),
+ error);
+ }
+ CloseHandle(file_handle);
+
+ char* data =
+ (char*)MapViewOfFile(mapping_handle, FILE_MAP_READ, 0, 0, 0);
+ if (data == nullptr) {
+ const auto error = GetLastError();
+
+ CloseHandle(mapping_handle);
+ mapping_handle = INVALID_HANDLE_VALUE;
+
+ FAISS_THROW_FMT(
+ "could not get map the file, %s (error %d)",
+ filename.c_str(),
+ error);
+ }
+
+ ptr = data;
+ ptr_size = len_li.QuadPart;
+ }
+
+ PImpl(FILE* f) {
+ // obtain a HANDLE from a FILE
+ const int fd = _fileno(f);
+ if (fd == -1) {
+ // no good
+ FAISS_THROW_FMT("could not get a HANDLE");
+ }
+
+ HANDLE file_handle = (HANDLE)_get_osfhandle(fd);
+ if (file_handle == INVALID_HANDLE_VALUE) {
+ FAISS_THROW_FMT("could not get an OS HANDLE");
+ }
+
+ // get the size of the file
+ LARGE_INTEGER len_li;
+ if (GetFileSizeEx(file_handle, &len_li) == 0) {
+ const auto error = GetLastError();
+ FAISS_THROW_FMT("could not get the file size (error %d)", error);
+ }
+
+ // create a mapping
+ mapping_handle = CreateFileMapping(
+ file_handle, nullptr, PAGE_READONLY, 0, 0, nullptr);
+ if (mapping_handle == 0) {
+ const auto error = GetLastError();
+ FAISS_THROW_FMT(
+ "could not create a file mapping, (error %d)", error);
+ }
+
+ // the handle is provided externally, so this is not our business
+ // to close file_handle.
+
+ char* data =
+ (char*)MapViewOfFile(mapping_handle, FILE_MAP_READ, 0, 0, 0);
+ if (data == nullptr) {
+ const auto error = GetLastError();
+
+ CloseHandle(mapping_handle);
+ mapping_handle = INVALID_HANDLE_VALUE;
+
+ FAISS_THROW_FMT("could not get map the file, (error %d)", error);
+ }
+
+ ptr = data;
+ ptr_size = len_li.QuadPart;
+ }
+
+ ~PImpl() {
+ if (mapping_handle != INVALID_HANDLE_VALUE) {
+ UnmapViewOfFile(ptr);
+ CloseHandle(mapping_handle);
+
+ mapping_handle = INVALID_HANDLE_VALUE;
+ ptr = nullptr;
+ }
+ }
+};
+
+#elif defined(__APPLE__) || defined(__MACH__)
+
+struct MmappedFileMappingOwner::PImpl {
+ void* ptr = nullptr;
+ size_t ptr_size = 0;
+
+ PImpl(const std::string& filename) {
+ auto f = std::unique_ptr<FILE, decltype(&fclose)>(
+ fopen(filename.c_str(), "r"), &fclose);
+ FAISS_THROW_IF_NOT_FMT(
+ f.get(),
+ "could not open %s for reading: %s",
+ filename.c_str(),
+ strerror(errno));
+
+ // get the size
+ struct stat s;
+ int status = fstat(fileno(f.get()), &s);
+ FAISS_THROW_IF_NOT_FMT(
+ status >= 0, "fstat() failed: %s", strerror(errno));
+
+ const size_t filesize = s.st_size;
+
+ void* address = mmap(
+ nullptr, filesize, PROT_READ, MAP_SHARED, fileno(f.get()), 0);
+ FAISS_THROW_IF_NOT_FMT(
+ address != MAP_FAILED, "could not mmap(): %s", strerror(errno));
+
+ // btw, fd can be closed here
+
+ // save it
+ ptr = address;
+ ptr_size = filesize;
+ }
+
+ PImpl(FILE* f) {
+ // get the size
+ struct stat s;
+ int status = fstat(fileno(f), &s);
+ FAISS_THROW_IF_NOT_FMT(
+ status >= 0, "fstat() failed: %s", strerror(errno));
+
+ const size_t filesize = s.st_size;
+
+ void* address =
+ mmap(nullptr, filesize, PROT_READ, MAP_SHARED, fileno(f), 0);
+ FAISS_THROW_IF_NOT_FMT(
+ address != MAP_FAILED, "could not mmap(): %s", strerror(errno));
+
+ // save it
+ ptr = address;
+ ptr_size = filesize;
+ }
+
+ ~PImpl() {
+ munmap(ptr, ptr_size);
+ }
+};
+
+#else
+
+struct MmappedFileMappingOwner::PImpl {
+ PImpl(FILE* f) {
+ FAISS_THROW_MSG("Not implemented");
+ }
+
+ ~PImpl() {
+ FAISS_THROW_MSG("Not implemented");
+ }
+};
+
+#endif
+
+MmappedFileMappingOwner::MmappedFileMappingOwner(const std::string& filename) {
+ p_impl = std::make_unique<MmappedFileMappingOwner::PImpl>(filename);
+}
+
+MmappedFileMappingOwner::MmappedFileMappingOwner(FILE* f) {
+ p_impl = std::make_unique<MmappedFileMappingOwner::PImpl>(f);
+}
+
+MmappedFileMappingOwner::~MmappedFileMappingOwner() = default;
+
+//
+void* MmappedFileMappingOwner::data() const {
+ return p_impl->ptr;
+}
+
+size_t MmappedFileMappingOwner::size() const {
+ return p_impl->ptr_size;
+}
+
+MappedFileIOReader::MappedFileIOReader(
+ const std::shared_ptr<MmappedFileMappingOwner>& owner)
+ : mmap_owner(owner) {}
+
+// this operation performs a copy
+size_t MappedFileIOReader::operator()(void* ptr, size_t size, size_t nitems) {
+ if (size * nitems == 0) {
+ return 0;
+ }
+
+ char* ptr_c = nullptr;
+
+ const size_t actual_nitems = this->mmap((void**)&ptr_c, size, nitems);
+ if (actual_nitems > 0) {
+ memcpy(ptr, ptr_c, size * actual_nitems);
+ }
+
+ return actual_nitems;
+}
+
+// this operation returns a mmapped address, owned by mmap_owner
+size_t MappedFileIOReader::mmap(void** ptr, size_t size, size_t nitems) {
+ if (size == 0) {
+ return nitems;
+ }
+
+ size_t actual_size = size * nitems;
+ if (pos + size * nitems > mmap_owner->size()) {
+ actual_size = mmap_owner->size() - pos;
+ }
+
+ size_t actual_nitems = (actual_size + size - 1) / size;
+ if (actual_nitems == 0) {
+ return 0;
+ }
+
+ // get an address
+ *ptr = (void*)(reinterpret_cast<const char*>(mmap_owner->data()) + pos);
+
+ // alter pos
+ pos += size * actual_nitems;
+
+ return actual_nitems;
+}
+
+int MappedFileIOReader::filedescriptor() {
+ // todo
+ return -1;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/mapped_io.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/mapped_io.h
new file mode 100644
index 0000000..0e32df2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/mapped_io.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+
+#include <faiss/impl/io.h>
+#include <faiss/impl/maybe_owned_vector.h>
+
+namespace faiss {
+
+// holds a memory-mapped region over a file
+struct MmappedFileMappingOwner : public MaybeOwnedVectorOwner {
+ MmappedFileMappingOwner(const std::string& filename);
+ MmappedFileMappingOwner(FILE* f);
+ ~MmappedFileMappingOwner();
+
+ void* data() const;
+ size_t size() const;
+
+ struct PImpl;
+ std::unique_ptr<PImpl> p_impl;
+};
+
+// A deserializer that supports memory-mapped files.
+// All de-allocations should happen as soon as the index gets destroyed,
+// after all underlying the MaybeOwnerVector objects are destroyed.
+struct MappedFileIOReader : IOReader {
+ std::shared_ptr<MmappedFileMappingOwner> mmap_owner;
+
+ size_t pos = 0;
+
+ MappedFileIOReader(const std::shared_ptr<MmappedFileMappingOwner>& owner);
+
+ // perform a copy
+ size_t operator()(void* ptr, size_t size, size_t nitems) override;
+ // perform a quasi-read that returns a mmapped address, owned by mmap_owner,
+ // and updates the position
+ size_t mmap(void** ptr, size_t size, size_t nitems);
+
+ int filedescriptor() override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/maybe_owned_vector.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/maybe_owned_vector.h
new file mode 100644
index 0000000..4b6770d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/maybe_owned_vector.h
@@ -0,0 +1,316 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <memory>
+#include <vector>
+
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+// An interface for an owner of a MaybeOwnedVector.
+struct MaybeOwnedVectorOwner {
+ virtual ~MaybeOwnedVectorOwner() = default;
+};
+
+// a container that either works as std::vector<T> that owns its own memory,
+// or as a view of a memory buffer, with a known size
+template <typename T>
+struct MaybeOwnedVector {
+ using value_type = T;
+ using self_type = MaybeOwnedVector<T>;
+ using iterator = typename std::vector<T>::iterator;
+ using const_iterator = typename std::vector<T>::const_iterator;
+ using size_type = typename std::vector<T>::size_type;
+
+ bool is_owned = true;
+
+ // this one is used if is_owned == true
+ std::vector<T> owned_data;
+
+ // these three are used if is_owned == false
+ T* view_data = nullptr;
+ // the number of T elements
+ size_t view_size = 0;
+ // who owns the data.
+ // This field can be nullptr, and it is present ONLY in order
+ // to avoid possible tricky memory / resource leaks.
+ std::shared_ptr<MaybeOwnedVectorOwner> owner;
+
+ // points either to view_data, or to owned.data()
+ T* c_ptr = nullptr;
+ // uses either view_size, or owned.size();
+ size_t c_size = 0;
+
+ MaybeOwnedVector() = default;
+ MaybeOwnedVector(const size_t initial_size) {
+ is_owned = true;
+
+ owned_data.resize(initial_size);
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ }
+
+ explicit MaybeOwnedVector(const std::vector<T>& vec)
+ : faiss::MaybeOwnedVector<T>(vec.size()) {
+ if (vec.size() > 0) {
+ memcpy(owned_data.data(), vec.data(), sizeof(T) * vec.size());
+ }
+ }
+
+ MaybeOwnedVector(const MaybeOwnedVector& other) {
+ is_owned = other.is_owned;
+ owned_data = other.owned_data;
+
+ view_data = other.view_data;
+ view_size = other.view_size;
+ owner = other.owner;
+
+ if (is_owned) {
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ } else {
+ c_ptr = view_data;
+ c_size = view_size;
+ }
+ }
+
+ MaybeOwnedVector(MaybeOwnedVector&& other) {
+ is_owned = other.is_owned;
+ owned_data = std::move(other.owned_data);
+
+ view_data = other.view_data;
+ view_size = other.view_size;
+ owner = std::move(other.owner);
+ other.owner = nullptr;
+
+ if (is_owned) {
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ } else {
+ c_ptr = view_data;
+ c_size = view_size;
+ }
+ }
+
+ MaybeOwnedVector& operator=(const MaybeOwnedVector& other) {
+ if (this == &other) {
+ return *this;
+ }
+
+ // create a copy
+ MaybeOwnedVector cloned(other);
+ // swap
+ swap(*this, cloned);
+
+ return *this;
+ }
+
+ MaybeOwnedVector& operator=(MaybeOwnedVector&& other) {
+ if (this == &other) {
+ return *this;
+ }
+
+ // moved
+ MaybeOwnedVector moved(std::move(other));
+ // swap
+ swap(*this, moved);
+
+ return *this;
+ }
+
+ MaybeOwnedVector(std::vector<T>&& other) {
+ is_owned = true;
+
+ owned_data = std::move(other);
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ }
+
+ static MaybeOwnedVector create_view(
+ void* address,
+ const size_t n_elements,
+ const std::shared_ptr<MaybeOwnedVectorOwner>& owner) {
+ MaybeOwnedVector vec;
+ vec.is_owned = false;
+ vec.view_data = reinterpret_cast<T*>(address);
+ vec.view_size = n_elements;
+ vec.owner = owner;
+
+ vec.c_ptr = vec.view_data;
+ vec.c_size = vec.view_size;
+
+ return vec;
+ }
+
+ const T* data() const {
+ return c_ptr;
+ }
+
+ T* data() {
+ return c_ptr;
+ }
+
+ size_t size() const {
+ return c_size;
+ }
+
+ size_t byte_size() const {
+ return c_size * sizeof(T);
+ }
+
+ T& operator[](const size_t idx) {
+ return c_ptr[idx];
+ }
+
+ const T& operator[](const size_t idx) const {
+ return c_ptr[idx];
+ }
+
+ T& at(size_type pos) {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ return owned_data.at(pos);
+ }
+
+ const T& at(size_type pos) const {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ return owned_data.at(pos);
+ }
+
+ iterator begin() {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ return owned_data.begin();
+ }
+
+ const_iterator begin() const {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ return owned_data.begin();
+ }
+
+ iterator end() {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ return owned_data.end();
+ }
+
+ const_iterator end() const {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ return owned_data.end();
+ }
+
+ iterator erase(const_iterator begin, const_iterator end) {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ auto result = owned_data.erase(begin, end);
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+
+ return result;
+ }
+
+ template <class InputIt>
+ iterator insert(const_iterator pos, InputIt first, InputIt last) {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ auto result = owned_data.insert(pos, first, last);
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+
+ return result;
+ }
+
+ void clear() {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ owned_data.clear();
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ }
+
+ void resize(const size_t new_size) {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ owned_data.resize(new_size);
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ }
+
+ void resize(const size_t new_size, const value_type v) {
+ FAISS_ASSERT_MSG(
+ is_owned,
+ "This operation cannot be performed on a viewed vector");
+
+ owned_data.resize(new_size, v);
+ c_ptr = owned_data.data();
+ c_size = owned_data.size();
+ }
+
+ friend void swap(self_type& a, self_type& b) {
+ std::swap(a.is_owned, b.is_owned);
+ std::swap(a.owned_data, b.owned_data);
+ std::swap(a.view_data, b.view_data);
+ std::swap(a.view_size, b.view_size);
+ std::swap(a.owner, b.owner);
+ std::swap(a.c_ptr, b.c_ptr);
+ std::swap(a.c_size, b.c_size);
+ }
+};
+
+template <typename T>
+struct is_maybe_owned_vector : std::false_type {};
+
+template <typename T>
+struct is_maybe_owned_vector<MaybeOwnedVector<T>> : std::true_type {};
+
+template <typename T>
+inline constexpr bool is_maybe_owned_vector_v = is_maybe_owned_vector<T>::value;
+
+template <typename T>
+bool operator==(
+ const MaybeOwnedVector<T>& lhs,
+ const MaybeOwnedVector<T>& rhs) {
+ return lhs.size() == rhs.size() &&
+ !memcmp(lhs.data(), rhs.data(), lhs.byte_size());
+}
+
+template <typename T>
+bool operator!=(
+ const MaybeOwnedVector<T>& lhs,
+ const MaybeOwnedVector<T>& rhs) {
+ return !(lhs == rhs);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/platform_macros.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/platform_macros.h
new file mode 100644
index 0000000..81b1542
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/platform_macros.h
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// basic int types and size_t
+#include <cstdint>
+#include <cstdio>
+
+#ifdef _WIN32
+
+/*******************************************************
+ * Windows specific macros
+ *******************************************************/
+
+#ifdef FAISS_MAIN_LIB
+#define FAISS_API __declspec(dllexport)
+#else // _FAISS_MAIN_LIB
+#define FAISS_API __declspec(dllimport)
+#endif // FAISS_MAIN_LIB
+
+#define strtok_r strtok_s
+
+#ifdef _MSC_VER
+#define __PRETTY_FUNCTION__ __FUNCSIG__
+#endif // _MSC_VER
+
+#define posix_memalign(p, a, s) \
+ (((*(p)) = _aligned_malloc((s), (a))), *(p) ? 0 : errno)
+#define posix_memalign_free _aligned_free
+
+// aligned should be in front of the declaration
+#define ALIGNED(x) __declspec(align(x))
+
+// redefine the GCC intrinsics with Windows equivalents
+#ifdef _MSC_VER
+
+#include <intrin.h>
+#include <limits.h>
+
+#ifndef __clang__
+inline int __builtin_ctzll(uint64_t x) {
+ unsigned long ret;
+ _BitScanForward64(&ret, x);
+ return (int)ret;
+}
+#endif
+
+// cudatoolkit provides __builtin_ctz for NVCC >= 11.0
+#if !defined(__CUDACC__) || __CUDACC_VER_MAJOR__ < 11
+inline int __builtin_ctz(unsigned long x) {
+ unsigned long ret;
+ _BitScanForward(&ret, x);
+ return (int)ret;
+}
+#endif
+
+#ifndef __clang__
+inline int __builtin_clzll(uint64_t x) {
+#if defined(_M_X64) || defined(__x86_64__)
+ return (int)__lzcnt64(x);
+#elif defined(_M_ARM64)
+ unsigned long index;
+ int count = sizeof(uint64_t) * CHAR_BIT;
+ if (_BitScanReverse64(&index, x)) {
+ count = count - 1 - index;
+ }
+ return count;
+#endif
+}
+#endif
+
+#define __builtin_popcount __popcnt
+#define __builtin_popcountl __popcnt64
+#define __builtin_popcountll __popcnt64
+
+#ifndef __clang__
+#define __m128i_u __m128i
+#define __m256i_u __m256i
+#endif
+
+// MSVC does not define __SSEx__, and _M_IX86_FP is only defined on 32-bit
+// processors cf.
+// https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros
+#ifdef __AVX__
+#define __SSE__ 1
+#define __SSE2__ 1
+#define __SSE3__ 1
+#define __SSE4_1__ 1
+#define __SSE4_2__ 1
+#endif
+
+// MSVC sets FMA and F16C automatically when using AVX2
+// Ref. FMA (under /arch:AVX2):
+// https://docs.microsoft.com/en-us/cpp/build/reference/arch-x64 Ref. F16C (2nd
+// paragraph): https://walbourn.github.io/directxmath-avx2/
+#ifdef __AVX2__
+#define __FMA__ 1
+#define __F16C__ 1
+#endif
+
+#endif // _MSC_VER
+
+#define FAISS_ALWAYS_INLINE __forceinline
+
+#else
+/*******************************************************
+ * Linux and OSX
+ *******************************************************/
+
+#define FAISS_API
+#define posix_memalign_free free
+
+// aligned should be *in front* of the declaration, for compatibility with
+// windows
+#ifdef SWIG
+#define ALIGNED(x)
+#else
+#define ALIGNED(x) __attribute__((aligned(x)))
+#endif
+
+#define FAISS_ALWAYS_INLINE __attribute__((always_inline)) inline
+
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+#define FAISS_DEPRECATED(msg) __attribute__((deprecated(msg)))
+#else
+#define FAISS_DEPRECATED(msg)
+#endif // GCC or Clang
+
+// Localized enablement of imprecise floating point operations
+// You need to use all 3 macros to cover all compilers.
+#if defined(_MSC_VER)
+#define FAISS_PRAGMA_IMPRECISE_LOOP
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN \
+ __pragma(float_control(precise, off, push))
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_END __pragma(float_control(pop))
+#elif defined(__clang__)
+#if defined(__PPC__)
+#define FAISS_PRAGMA_IMPRECISE_LOOP \
+ _Pragma("clang loop vectorize_width(4) interleave_count(8)")
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN \
+ _Pragma("float_control(precise, off, push)")
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_END _Pragma("float_control(pop)")
+#else
+#define FAISS_PRAGMA_IMPRECISE_LOOP \
+ _Pragma("clang loop vectorize(enable) interleave(enable)")
+
+// clang-format off
+
+// the following ifdef is needed, because old versions of clang (prior to 14)
+// do not generate FMAs on x86 unless this pragma is used. On the other hand,
+// ARM does not support the following pragma flag.
+// TODO: find out how to enable FMAs on clang 10 and earlier.
+#if defined(__x86_64__) && (defined(__clang_major__) && (__clang_major__ > 10))
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN \
+ _Pragma("float_control(precise, off, push)")
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_END _Pragma("float_control(pop)")
+#else
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+#endif
+#endif
+#elif defined(__GNUC__)
+// Unfortunately, GCC does not provide a pragma for detecting it.
+// So, we have to stick to GNUC, which is defined by MANY compilers.
+// This is why clang/icc needs to be checked first.
+
+// todo: add __INTEL_COMPILER check for the classic ICC
+// todo: add __INTEL_LLVM_COMPILER for ICX
+
+#define FAISS_PRAGMA_IMPRECISE_LOOP
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN \
+ _Pragma("GCC push_options") \
+ _Pragma("GCC optimize (\"unroll-loops,associative-math,no-signed-zeros\")")
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_END \
+ _Pragma("GCC pop_options")
+#else
+#define FAISS_PRAGMA_IMPRECISE_LOOP
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+#define FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+#endif
+
+// clang-format on
+
+/*******************************************************
+ * BIGENDIAN specific macros
+ *******************************************************/
+#if !defined(_MSC_VER) && \
+ (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
+#define FAISS_BIG_ENDIAN
+#endif
+
+#define Swap2Bytes(val) ((((val) >> 8) & 0x00FF) | (((val) << 8) & 0xFF00))
+
+#define Swap4Bytes(val) \
+ ((((val) >> 24) & 0x000000FF) | (((val) >> 8) & 0x0000FF00) | \
+ (((val) << 8) & 0x00FF0000) | (((val) << 24) & 0xFF000000))
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq.cpp
new file mode 100644
index 0000000..dbe875b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq.cpp
@@ -0,0 +1,225 @@
+#include "pq.h"
+#ifdef __linux__
+#include <xmmintrin.h> // For _mm_prefetch
+#endif
+#include <cmath>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <stdexcept>
+#include <vector>
+#include "faiss/impl/FaissAssert.h"
+
+namespace faiss {
+
+PQPrunerDataLoader::PQPrunerDataLoader()
+ : tables_tr(nullptr),
+ centroid(nullptr),
+ chunk_offsets(nullptr),
+ ndims(0),
+ n_chunks(0),
+ initialized(false) {}
+
+PQPrunerDataLoader::~PQPrunerDataLoader() {
+ delete[] tables_tr;
+ delete[] centroid;
+ delete[] chunk_offsets;
+}
+
+size_t PQPrunerDataLoader::get_num_chunks() const {
+ return n_chunks;
+}
+size_t PQPrunerDataLoader::get_dims() const {
+ return ndims;
+}
+bool PQPrunerDataLoader::is_initialized() const {
+ return initialized;
+}
+
+bool PQPrunerDataLoader::load_pq_pivots(const std::string& pq_pivots_path) {
+ initialized = false;
+ delete[] tables_tr;
+ tables_tr = nullptr;
+ delete[] centroid;
+ centroid = nullptr;
+ delete[] chunk_offsets;
+ chunk_offsets = nullptr;
+
+ std::ifstream reader(pq_pivots_path, std::ios::binary);
+
+ int32_t offset_nr_i32, offset_nc_i32;
+ reader.read(reinterpret_cast<char*>(&offset_nr_i32), sizeof(int32_t));
+ reader.read(reinterpret_cast<char*>(&offset_nc_i32), sizeof(int32_t));
+
+ size_t offset_rows = (size_t)offset_nr_i32;
+ size_t offset_cols = (size_t)offset_nc_i32;
+ // FAISS_ASSERT(offset_cols == 1 && (offset_rows == 4 || offset_rows == 5));
+
+ size_t num_offsets = offset_rows * offset_cols;
+ std::unique_ptr<size_t[]> file_offsets(new size_t[num_offsets]);
+ reader.read(
+ reinterpret_cast<char*>(file_offsets.get()),
+ num_offsets * sizeof(size_t));
+
+ bool use_old_filetype = (offset_rows == 5);
+
+ constexpr size_t NUM_PQ_CENTROIDS = 256;
+ float* tables_original = nullptr;
+ size_t pivot_rows = 0, pivot_cols = 0;
+ {
+ reader.seekg(file_offsets[0], std::ios::beg);
+ int32_t r_i32, c_i32;
+ reader.read(reinterpret_cast<char*>(&r_i32), sizeof(int32_t));
+ reader.read(reinterpret_cast<char*>(&c_i32), sizeof(int32_t));
+ pivot_rows = (size_t)r_i32;
+ pivot_cols = (size_t)c_i32;
+ // FAISS_ASSERT(pivot_rows == NUM_PQ_CENTROIDS && pivot_cols > 0); //
+ ndims = pivot_cols;
+ tables_original = new float[pivot_rows * pivot_cols];
+ reader.read(
+ reinterpret_cast<char*>(tables_original),
+ pivot_rows * pivot_cols * sizeof(float));
+ }
+ std::unique_ptr<float[]> tables_original_ptr(tables_original);
+
+ float* centroid_raw = nullptr;
+ size_t centroid_rows = 0, centroid_cols = 0;
+ {
+ reader.seekg(file_offsets[1], std::ios::beg);
+ int32_t r_i32, c_i32;
+ reader.read(reinterpret_cast<char*>(&r_i32), sizeof(int32_t));
+ reader.read(reinterpret_cast<char*>(&c_i32), sizeof(int32_t));
+ centroid_rows = (size_t)r_i32;
+ centroid_cols = (size_t)c_i32;
+ // FAISS_ASSERT(centroid_rows == ndims && centroid_cols == 1); //
+ centroid_raw = new float[centroid_rows * centroid_cols]; // 直接 new
+ reader.read(
+ reinterpret_cast<char*>(centroid_raw),
+ centroid_rows * centroid_cols * sizeof(float));
+ }
+ this->centroid = centroid_raw;
+
+ int chunk_offsets_file_idx = use_old_filetype ? 3 : 2;
+ uint32_t* chunk_offsets_raw = nullptr;
+ size_t chunk_rows = 0, chunk_cols = 0;
+ {
+ reader.seekg(file_offsets[chunk_offsets_file_idx], std::ios::beg);
+ int32_t r_i32, c_i32;
+ reader.read(reinterpret_cast<char*>(&r_i32), sizeof(int32_t));
+ reader.read(reinterpret_cast<char*>(&c_i32), sizeof(int32_t));
+ chunk_rows = (size_t)r_i32;
+ chunk_cols = (size_t)c_i32;
+ // FAISS_ASSERT(chunk_cols == 1 && chunk_rows >= 2);
+ n_chunks = chunk_rows - 1;
+ chunk_offsets_raw = new uint32_t[chunk_rows * chunk_cols];
+ reader.read(
+ reinterpret_cast<char*>(chunk_offsets_raw),
+ chunk_rows * chunk_cols * sizeof(uint32_t));
+ }
+ this->chunk_offsets = chunk_offsets_raw;
+
+ tables_tr = new float[ndims * NUM_PQ_CENTROIDS];
+ for (size_t i = 0; i < NUM_PQ_CENTROIDS; i++) {
+ for (size_t j = 0; j < ndims; j++) {
+ tables_tr[j * NUM_PQ_CENTROIDS + i] =
+ tables_original[i * ndims + j];
+ }
+ }
+
+ initialized = true;
+ std::cout << "PQPrunerDataLoader initialized from .cpp. Dims: " << ndims
+ << ", Chunks: " << n_chunks << std::endl;
+ return true;
+}
+
+void PQPrunerDataLoader::preprocess_query(
+ const float* query,
+ float* query_preprocessed) const {
+ if (!initialized)
+ return;
+
+ // Calculate L2 norm of the original query vector
+ double norm_sq = 0.0;
+ for (size_t d = 0; d < ndims; d++) {
+ norm_sq += (double)query[d] * query[d];
+ }
+ double norm = std::sqrt(norm_sq);
+
+ // Handle zero norm case (avoid division by zero)
+ if (norm <= 0.0) {
+ norm = 1.0;
+ }
+
+ // First normalize the query vector, then subtract the centroid
+ // This adapts L2-based PQ distance for IP/Cosine search approximation,
+ // assuming the loaded PQ codebook is compatible with this approach
+ for (size_t d = 0; d < ndims; d++) {
+ float normalized_query_d = query[d] / (float)norm;
+ query_preprocessed[d] = normalized_query_d - centroid[d];
+ }
+}
+
+void PQPrunerDataLoader::populate_chunk_distances(
+ const float* query_preprocessed,
+ float* pq_dists_lookup_table) const {
+ if (!initialized || !tables_tr || !chunk_offsets)
+ return;
+ constexpr size_t NUM_PQ_CENTROIDS = 256;
+ memset(pq_dists_lookup_table,
+ 0,
+ NUM_PQ_CENTROIDS * n_chunks * sizeof(float));
+ for (size_t chunk = 0; chunk < n_chunks; chunk++) {
+ float* chunk_dists = pq_dists_lookup_table + (NUM_PQ_CENTROIDS * chunk);
+ uint32_t start_dim = chunk_offsets[chunk];
+ uint32_t end_dim = chunk_offsets[chunk + 1];
+ for (size_t j = start_dim; j < end_dim; j++) {
+ const float* centers_dim_vec = tables_tr + (NUM_PQ_CENTROIDS * j);
+ float query_val_dim_j = query_preprocessed[j];
+ for (size_t idx = 0; idx < NUM_PQ_CENTROIDS; idx++) {
+ double diff =
+ (double)centers_dim_vec[idx] - (double)query_val_dim_j;
+ chunk_dists[idx] += (float)(diff * diff);
+ }
+ }
+ }
+}
+
+size_t aggregate_pq_codes(
+ const idx_t* ids,
+ size_t num_ids,
+ const uint8_t* all_pq_codes,
+ size_t total_codes_count,
+ size_t code_size,
+ uint8_t* out_aggregated_codes) {
+ size_t count = 0;
+ for (size_t i = 0; i < num_ids; i++) {
+ idx_t id = ids[i];
+ const uint8_t* code_ptr = all_pq_codes + (size_t)id * code_size;
+ memcpy(out_aggregated_codes + count * code_size, code_ptr, code_size);
+ count++;
+ }
+ return count;
+}
+
+void pq_distance_lookup(
+ const uint8_t* aggregated_codes,
+ size_t n_pts,
+ size_t n_chunks,
+ const float* pq_dists_lookup_table,
+ float* dists_out) {
+ memset(dists_out, 0, n_pts * sizeof(float));
+ for (size_t chunk = 0; chunk < n_chunks; chunk++) {
+ const float* chunk_dists = pq_dists_lookup_table + 256 * chunk;
+#ifdef __linux__
+ if (chunk < n_chunks - 1) {
+ _mm_prefetch((const char*)(chunk_dists + 256), _MM_HINT_T0);
+ }
+#endif
+ for (size_t idx = 0; idx < n_pts; idx++) {
+ uint8_t pq_centerid = aggregated_codes[idx * n_chunks + chunk];
+ dists_out[idx] += chunk_dists[pq_centerid];
+ }
+ }
+}
+} // namespace faiss
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq.h
new file mode 100644
index 0000000..5539ee8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq.h
@@ -0,0 +1,92 @@
+#pragma once
+
+#include <cstdint>
+#include <fstream>
+#include <string>
+#include <vector>
+
+#include "faiss/Index.h"
+#include "faiss/impl/FaissAssert.h"
+namespace faiss {
+
+class PQPrunerDataLoader {
+ public:
+ float* tables_tr = nullptr; // transposed codebook (ndims * 256)
+ float* centroid = nullptr; // centered vector (ndims)
+ uint32_t* chunk_offsets = nullptr; // chunk offsets (n_chunks + 1)
+ size_t ndims = 0; // original dimension
+ size_t n_chunks = 0; // number of PQ chunks
+ bool initialized = false;
+
+ PQPrunerDataLoader();
+ ~PQPrunerDataLoader();
+
+ PQPrunerDataLoader(const PQPrunerDataLoader&) = delete;
+ PQPrunerDataLoader& operator=(const PQPrunerDataLoader&) = delete;
+ PQPrunerDataLoader(PQPrunerDataLoader&&) = default;
+ PQPrunerDataLoader& operator=(PQPrunerDataLoader&&) = default;
+
+ bool load_pq_pivots(const std::string& pq_pivots_path);
+
+ // Preprocess the query (only centering)
+ void preprocess_query(const float* query, float* query_preprocessed) const;
+
+ // Calculate the distance lookup table from the query vector to all codebook
+ // centroids (L2 distance)
+ void populate_chunk_distances(
+ const float* query_preprocessed,
+ float* pq_dists_lookup_table) const;
+
+ size_t get_num_chunks() const;
+ size_t get_dims() const;
+ bool is_initialized() const;
+};
+
+size_t aggregate_pq_codes(
+ const idx_t* ids,
+ size_t num_ids,
+ const uint8_t* all_pq_codes,
+ size_t total_codes_count,
+ size_t code_size,
+ uint8_t* out_aggregated_codes);
+
+void pq_distance_lookup(
+ const uint8_t* aggregated_codes,
+ size_t n_pts,
+ size_t n_chunks,
+ const float* pq_dists_lookup_table,
+ float* dists_out);
+
+template <typename T>
+bool load_simple_bin(
+ const std::string& filename,
+ T*& data,
+ size_t& n_rows,
+ size_t& n_cols) {
+ data = nullptr;
+ n_rows = 0;
+ n_cols = 0;
+ std::ifstream reader(filename, std::ios::binary);
+
+ uint32_t r, c;
+ reader.read(reinterpret_cast<char*>(&r), sizeof(uint32_t));
+ reader.read(reinterpret_cast<char*>(&c), sizeof(uint32_t));
+ FAISS_ASSERT(reader);
+
+ n_rows = r;
+ n_cols = c;
+
+ size_t num_elements = n_rows * n_cols;
+ FAISS_ASSERT(num_elements > 0);
+
+ data = new T[num_elements];
+
+ size_t bytes_to_read = num_elements * sizeof(T);
+ reader.read(reinterpret_cast<char*>(data), bytes_to_read);
+
+ FAISS_ASSERT(reader);
+ FAISS_ASSERT((size_t)reader.gcount() == bytes_to_read);
+ return true;
+}
+
+} // namespace faiss
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan.cpp
new file mode 100644
index 0000000..5d7e2a4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan.cpp
@@ -0,0 +1,323 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/impl/pq4_fast_scan.h>
+#include <faiss/impl/simd_result_handlers.h>
+
+#include <array>
+
+namespace faiss {
+
+using namespace simd_result_handlers;
+
+/***************************************************************
+ * Packing functions for codes
+ ***************************************************************/
+
+namespace {
+
+/* extract the column starting at (i, j)
+ * from packed matrix src of size (m, n)*/
+template <typename T, class TA>
+void get_matrix_column(
+ T* src,
+ size_t m,
+ size_t n,
+ int64_t i,
+ int64_t j,
+ TA& dest) {
+ for (int64_t k = 0; k < dest.size(); k++) {
+ if (k + i >= 0 && k + i < m) {
+ dest[k] = src[(k + i) * n + j];
+ } else {
+ dest[k] = 0;
+ }
+ }
+}
+
+} // anonymous namespace
+
+void pq4_pack_codes(
+ const uint8_t* codes,
+ size_t ntotal,
+ size_t M,
+ size_t nb,
+ size_t bbs,
+ size_t nsq,
+ uint8_t* blocks) {
+ FAISS_THROW_IF_NOT(bbs % 32 == 0);
+ FAISS_THROW_IF_NOT(nb % bbs == 0);
+ FAISS_THROW_IF_NOT(nsq % 2 == 0);
+
+ if (nb == 0) {
+ return;
+ }
+ memset(blocks, 0, nb * nsq / 2);
+#ifdef FAISS_BIG_ENDIAN
+ const uint8_t perm0[16] = {
+ 8, 0, 9, 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7};
+#else
+ const uint8_t perm0[16] = {
+ 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15};
+#endif
+
+ uint8_t* codes2 = blocks;
+ for (size_t i0 = 0; i0 < nb; i0 += bbs) {
+ for (int sq = 0; sq < nsq; sq += 2) {
+ for (size_t i = 0; i < bbs; i += 32) {
+ std::array<uint8_t, 32> c, c0, c1;
+ get_matrix_column(
+ codes, ntotal, (M + 1) / 2, i0 + i, sq / 2, c);
+ for (int j = 0; j < 32; j++) {
+ c0[j] = c[j] & 15;
+ c1[j] = c[j] >> 4;
+ }
+ for (int j = 0; j < 16; j++) {
+ uint8_t d0, d1;
+ d0 = c0[perm0[j]] | (c0[perm0[j] + 16] << 4);
+ d1 = c1[perm0[j]] | (c1[perm0[j] + 16] << 4);
+ codes2[j] = d0;
+ codes2[j + 16] = d1;
+ }
+ codes2 += 32;
+ }
+ }
+ }
+}
+
+void pq4_pack_codes_range(
+ const uint8_t* codes,
+ size_t M,
+ size_t i0,
+ size_t i1,
+ size_t bbs,
+ size_t nsq,
+ uint8_t* blocks) {
+#ifdef FAISS_BIG_ENDIAN
+ const uint8_t perm0[16] = {
+ 8, 0, 9, 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7};
+#else
+ const uint8_t perm0[16] = {
+ 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15};
+#endif
+
+ // range of affected blocks
+ size_t block0 = i0 / bbs;
+ size_t block1 = ((i1 - 1) / bbs) + 1;
+
+ for (size_t b = block0; b < block1; b++) {
+ uint8_t* codes2 = blocks + b * bbs * nsq / 2;
+ int64_t i_base = b * bbs - i0;
+ for (int sq = 0; sq < nsq; sq += 2) {
+ for (size_t i = 0; i < bbs; i += 32) {
+ std::array<uint8_t, 32> c, c0, c1;
+ get_matrix_column(
+ codes, i1 - i0, (M + 1) / 2, i_base + i, sq / 2, c);
+ for (int j = 0; j < 32; j++) {
+ c0[j] = c[j] & 15;
+ c1[j] = c[j] >> 4;
+ }
+ for (int j = 0; j < 16; j++) {
+ uint8_t d0, d1;
+ d0 = c0[perm0[j]] | (c0[perm0[j] + 16] << 4);
+ d1 = c1[perm0[j]] | (c1[perm0[j] + 16] << 4);
+ codes2[j] |= d0;
+ codes2[j + 16] |= d1;
+ }
+ codes2 += 32;
+ }
+ }
+ }
+}
+
+namespace {
+
+// get the specific address of the vector inside a block
+// shift is used for determine the if the saved in bits 0..3 (false) or
+// bits 4..7 (true)
+size_t get_vector_specific_address(
+ size_t bbs,
+ size_t vector_id,
+ size_t sq,
+ bool& shift) {
+ // get the vector_id inside the block
+ vector_id = vector_id % bbs;
+ shift = vector_id > 15;
+ vector_id = vector_id & 15;
+
+ // get the address of the vector in sq
+ size_t address;
+ if (vector_id < 8) {
+ address = vector_id << 1;
+ } else {
+ address = ((vector_id - 8) << 1) + 1;
+ }
+ if (sq & 1) {
+ address += 16;
+ }
+ return (sq >> 1) * bbs + address;
+}
+
+} // anonymous namespace
+
+uint8_t pq4_get_packed_element(
+ const uint8_t* data,
+ size_t bbs,
+ size_t nsq,
+ size_t vector_id,
+ size_t sq) {
+ // move to correct bbs-sized block
+ // number of blocks * block size
+ data += (vector_id / bbs) * (((nsq + 1) / 2) * bbs);
+ bool shift;
+ size_t address = get_vector_specific_address(bbs, vector_id, sq, shift);
+ if (shift) {
+ return data[address] >> 4;
+ } else {
+ return data[address] & 15;
+ }
+}
+
+void pq4_set_packed_element(
+ uint8_t* data,
+ uint8_t code,
+ size_t bbs,
+ size_t nsq,
+ size_t vector_id,
+ size_t sq) {
+ // move to correct bbs-sized block
+ // number of blocks * block size
+ data += (vector_id / bbs) * (((nsq + 1) / 2) * bbs);
+ bool shift;
+ size_t address = get_vector_specific_address(bbs, vector_id, sq, shift);
+ if (shift) {
+ data[address] = (code << 4) | (data[address] & 15);
+ } else {
+ data[address] = code | (data[address] & ~15);
+ }
+}
+
+/***************************************************************
+ * CodePackerPQ4 implementation
+ ***************************************************************/
+
+CodePackerPQ4::CodePackerPQ4(size_t nsq, size_t bbs) {
+ this->nsq = nsq;
+ nvec = bbs;
+ code_size = (nsq * 4 + 7) / 8;
+ block_size = ((nsq + 1) / 2) * bbs;
+}
+
+void CodePackerPQ4::pack_1(
+ const uint8_t* flat_code,
+ size_t offset,
+ uint8_t* block) const {
+ size_t bbs = nvec;
+ if (offset >= nvec) {
+ block += (offset / nvec) * block_size;
+ offset = offset % nvec;
+ }
+ for (size_t i = 0; i < code_size; i++) {
+ uint8_t code = flat_code[i];
+ pq4_set_packed_element(block, code & 15, bbs, nsq, offset, 2 * i);
+ pq4_set_packed_element(block, code >> 4, bbs, nsq, offset, 2 * i + 1);
+ }
+}
+
+void CodePackerPQ4::unpack_1(
+ const uint8_t* block,
+ size_t offset,
+ uint8_t* flat_code) const {
+ size_t bbs = nvec;
+ if (offset >= nvec) {
+ block += (offset / nvec) * block_size;
+ offset = offset % nvec;
+ }
+ for (size_t i = 0; i < code_size; i++) {
+ uint8_t code0, code1;
+ code0 = pq4_get_packed_element(block, bbs, nsq, offset, 2 * i);
+ code1 = pq4_get_packed_element(block, bbs, nsq, offset, 2 * i + 1);
+ flat_code[i] = code0 | (code1 << 4);
+ }
+}
+
+/***************************************************************
+ * Packing functions for Look-Up Tables (LUT)
+ ***************************************************************/
+
+void pq4_pack_LUT(int nq, int nsq, const uint8_t* src, uint8_t* dest) {
+ for (int q = 0; q < nq; q++) {
+ for (int sq = 0; sq < nsq; sq += 2) {
+ memcpy(dest + (sq / 2 * nq + q) * 32,
+ src + (q * nsq + sq) * 16,
+ 16);
+ memcpy(dest + (sq / 2 * nq + q) * 32 + 16,
+ src + (q * nsq + sq + 1) * 16,
+ 16);
+ }
+ }
+}
+
+int pq4_pack_LUT_qbs(int qbs, int nsq, const uint8_t* src, uint8_t* dest) {
+ FAISS_THROW_IF_NOT(nsq % 2 == 0);
+ size_t dim12 = 16 * nsq;
+ int i0 = 0;
+ int qi = qbs;
+ while (qi) {
+ int nq = qi & 15;
+ qi >>= 4;
+ pq4_pack_LUT(nq, nsq, src + i0 * dim12, dest + i0 * dim12);
+ i0 += nq;
+ }
+ return i0;
+}
+
+namespace {
+
+void pack_LUT_1_q_map(
+ int nq,
+ const int* q_map,
+ int nsq,
+ const uint8_t* src,
+ uint8_t* dest) {
+ for (int qi = 0; qi < nq; qi++) {
+ int q = q_map[qi];
+ for (int sq = 0; sq < nsq; sq += 2) {
+ memcpy(dest + (sq / 2 * nq + qi) * 32,
+ src + (q * nsq + sq) * 16,
+ 16);
+ memcpy(dest + (sq / 2 * nq + qi) * 32 + 16,
+ src + (q * nsq + sq + 1) * 16,
+ 16);
+ }
+ }
+}
+
+} // anonymous namespace
+
+int pq4_pack_LUT_qbs_q_map(
+ int qbs,
+ int nsq,
+ const uint8_t* src,
+ const int* q_map,
+ uint8_t* dest) {
+ FAISS_THROW_IF_NOT(nsq % 2 == 0);
+ size_t dim12 = 16 * nsq;
+ int i0 = 0;
+ int qi = qbs;
+ while (qi) {
+ int nq = qi & 15;
+ qi >>= 4;
+ pack_LUT_1_q_map(nq, q_map + i0, nsq, src, dest + i0 * dim12);
+ i0 += nq;
+ }
+ return i0;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan.h
new file mode 100644
index 0000000..ccb084e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan.h
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+
+#include <faiss/impl/CodePacker.h>
+
+/** PQ4 SIMD packing and accumulation functions
+ *
+ * The basic kernel accumulates nq query vectors with bbs = nb * 2 * 16 vectors
+ * and produces an output matrix for that. It is interesting for nq * nb <= 4,
+ * otherwise register spilling becomes too large.
+ *
+ * The implementation of these functions is spread over 3 cpp files to reduce
+ * parallel compile times. Templates are instantiated explicitly.
+ */
+
+namespace faiss {
+
+struct NormTableScaler;
+struct SIMDResultHandler;
+
+/** Pack codes for consumption by the SIMD kernels.
+ * The unused bytes are set to 0.
+ *
+ * @param codes input codes, size (ntotal, ceil(M / 2))
+ * @param ntotal number of input codes
+ * @param nb output number of codes (ntotal rounded up to a multiple of
+ * bbs)
+ * @param nsq number of sub-quantizers (=M rounded up to a muliple of 2)
+ * @param bbs size of database blocks (multiple of 32)
+ * @param blocks output array, size nb * nsq / 2.
+ */
+void pq4_pack_codes(
+ const uint8_t* codes,
+ size_t ntotal,
+ size_t M,
+ size_t nb,
+ size_t bbs,
+ size_t nsq,
+ uint8_t* blocks);
+
+/** Same as pack_codes but write in a given range of the output,
+ * leaving the rest untouched. Assumes allocated entries are 0 on input.
+ *
+ * @param codes input codes, size (i1 - i0, ceil(M / 2))
+ * @param i0 first output code to write
+ * @param i1 last output code to write
+ * @param blocks output array, size at least ceil(i1 / bbs) * bbs * nsq / 2
+ */
+void pq4_pack_codes_range(
+ const uint8_t* codes,
+ size_t M,
+ size_t i0,
+ size_t i1,
+ size_t bbs,
+ size_t nsq,
+ uint8_t* blocks);
+
+/** get a single element from a packed codes table
+ *
+ * @param vector_id vector id
+ * @param sq subquantizer (< nsq)
+ */
+uint8_t pq4_get_packed_element(
+ const uint8_t* data,
+ size_t bbs,
+ size_t nsq,
+ size_t vector_id,
+ size_t sq);
+
+/** set a single element "code" into a packed codes table
+ *
+ * @param vector_id vector id
+ * @param sq subquantizer (< nsq)
+ */
+void pq4_set_packed_element(
+ uint8_t* data,
+ uint8_t code,
+ size_t bbs,
+ size_t nsq,
+ size_t vector_id,
+ size_t sq);
+
+/** CodePacker API for the PQ4 fast-scan */
+struct CodePackerPQ4 : CodePacker {
+ size_t nsq;
+
+ CodePackerPQ4(size_t nsq, size_t bbs);
+
+ void pack_1(const uint8_t* flat_code, size_t offset, uint8_t* block)
+ const final;
+ void unpack_1(const uint8_t* block, size_t offset, uint8_t* flat_code)
+ const final;
+};
+
+/** Pack Look-up table for consumption by the kernel.
+ *
+ * @param nq number of queries
+ * @param nsq number of sub-quantizers (muliple of 2)
+ * @param src input array, size (nq, 16)
+ * @param dest output array, size (nq, 16)
+ */
+void pq4_pack_LUT(int nq, int nsq, const uint8_t* src, uint8_t* dest);
+
+/** Loop over database elements and accumulate results into result handler
+ *
+ * @param nq number of queries
+ * @param nb number of database elements
+ * @param bbs size of database blocks (multiple of 32)
+ * @param nsq number of sub-quantizers (muliple of 2)
+ * @param codes packed codes array
+ * @param LUT packed look-up table
+ * @param scaler scaler to scale the encoded norm
+ */
+void pq4_accumulate_loop(
+ int nq,
+ size_t nb,
+ int bbs,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ SIMDResultHandler& res,
+ const NormTableScaler* scaler);
+
+/* qbs versions, supported only for bbs=32.
+ *
+ * The kernel function runs the kernel for *several* query blocks
+ * and bbs database vectors. The sizes of the blocks are encoded in qbs as
+ * base-16 digits.
+ *
+ * For example, qbs = 0x1223 means that the kernel will be run 4 times, the
+ * first time with 3 query vectors, second time with 2 query vectors, then 2
+ * vectors again and finally with 1 query vector. The output block will thus be
+ * nq = 3 + 2 + 2 + 1 = 6 queries. For a given total block size, the optimal
+ * decomposition into sub-blocks (measured empirically) is given by
+ * preferred_qbs().
+ */
+
+/* compute the number of queries from a base-16 decomposition */
+int pq4_qbs_to_nq(int qbs);
+
+/** return the preferred decomposition in blocks for a nb of queries. */
+int pq4_preferred_qbs(int nq);
+
+/** Pack Look-up table for consumption by the kernel.
+ *
+ * @param qbs 4-bit encoded number of query blocks, the total number of
+ * queries handled (nq) is deduced from it
+ * @param nsq number of sub-quantizers (muliple of 2)
+ * @param src input array, size (nq, 16)
+ * @param dest output array, size (nq, 16)
+ * @return nq
+ */
+int pq4_pack_LUT_qbs(int fqbs, int nsq, const uint8_t* src, uint8_t* dest);
+
+/** Same as pq4_pack_LUT_qbs, except the source vectors are remapped with q_map
+ */
+int pq4_pack_LUT_qbs_q_map(
+ int qbs,
+ int nsq,
+ const uint8_t* src,
+ const int* q_map,
+ uint8_t* dest);
+
+/** Run accumulation loop.
+ *
+ * @param qbs 4-bit encoded number of queries
+ * @param nb number of database codes (mutliple of bbs)
+ * @param nsq number of sub-quantizers
+ * @param codes encoded database vectors (packed)
+ * @param LUT look-up table (packed)
+ * @param res call-back for the resutls
+ * @param scaler scaler to scale the encoded norm
+ */
+void pq4_accumulate_loop_qbs(
+ int qbs,
+ size_t nb,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ SIMDResultHandler& res,
+ const NormTableScaler* scaler = nullptr);
+
+/** Wrapper of pq4_accumulate_loop_qbs using simple StoreResultHandler
+ * and DummyScaler
+ *
+ * @param nq number of queries
+ * @param ntotal2 number of database elements (multiple of 32)
+ * @param nsq number of sub-quantizers (muliple of 2)
+ * @param codes packed codes array
+ * @param LUT packed look-up table
+ * @param accu array to store the results
+ */
+void accumulate_to_mem(
+ int nq,
+ size_t ntotal2,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ uint16_t* accu);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan_search_1.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan_search_1.cpp
new file mode 100644
index 0000000..5c7d797
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan_search_1.cpp
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/pq4_fast_scan.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/LookupTableScaler.h>
+#include <faiss/impl/simd_result_handlers.h>
+
+namespace faiss {
+
+using namespace simd_result_handlers;
+
+/***************************************************************
+ * accumulation functions
+ ***************************************************************/
+
+namespace {
+
+/*
+ * The computation kernel
+ * It accumulates results for NQ queries and BB * 32 database elements
+ * writes results in a ResultHandler
+ */
+
+template <int NQ, int BB, class ResultHandler, class Scaler>
+void kernel_accumulate_block(
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ // distance accumulators
+ simd16uint16 accu[NQ][BB][4];
+
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < BB; b++) {
+ accu[q][b][0].clear();
+ accu[q][b][1].clear();
+ accu[q][b][2].clear();
+ accu[q][b][3].clear();
+ }
+ }
+
+ for (int sq = 0; sq < nsq - scaler.nscale; sq += 2) {
+ simd32uint8 lut_cache[NQ];
+ for (int q = 0; q < NQ; q++) {
+ lut_cache[q] = simd32uint8(LUT);
+ LUT += 32;
+ }
+
+ for (int b = 0; b < BB; b++) {
+ simd32uint8 c = simd32uint8(codes);
+ codes += 32;
+ simd32uint8 mask(15);
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ simd32uint8 lut = lut_cache[q];
+ simd32uint8 res0 = lut.lookup_2_lanes(clo);
+ simd32uint8 res1 = lut.lookup_2_lanes(chi);
+
+ accu[q][b][0] += simd16uint16(res0);
+ accu[q][b][1] += simd16uint16(res0) >> 8;
+
+ accu[q][b][2] += simd16uint16(res1);
+ accu[q][b][3] += simd16uint16(res1) >> 8;
+ }
+ }
+ }
+
+ for (int sq = 0; sq < scaler.nscale; sq += 2) {
+ simd32uint8 lut_cache[NQ];
+ for (int q = 0; q < NQ; q++) {
+ lut_cache[q] = simd32uint8(LUT);
+ LUT += 32;
+ }
+
+ for (int b = 0; b < BB; b++) {
+ simd32uint8 c = simd32uint8(codes);
+ codes += 32;
+ simd32uint8 mask(15);
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ simd32uint8 lut = lut_cache[q];
+
+ simd32uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][b][0] += scaler.scale_lo(res0); // handle vectors 0..7
+ accu[q][b][1] += scaler.scale_hi(res0); // handle vectors 8..15
+
+ simd32uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][b][2] += scaler.scale_lo(res1); // handle vectors 16..23
+ accu[q][b][3] +=
+ scaler.scale_hi(res1); // handle vectors 24..31
+ }
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < BB; b++) {
+ accu[q][b][0] -= accu[q][b][1] << 8;
+ simd16uint16 dis0 = combine2x2(accu[q][b][0], accu[q][b][1]);
+
+ accu[q][b][2] -= accu[q][b][3] << 8;
+ simd16uint16 dis1 = combine2x2(accu[q][b][2], accu[q][b][3]);
+
+ res.handle(q, b, dis0, dis1);
+ }
+ }
+}
+
+template <int NQ, int BB, class ResultHandler, class Scaler>
+void accumulate_fixed_blocks(
+ size_t nb,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ constexpr int bbs = 32 * BB;
+ for (size_t j0 = 0; j0 < nb; j0 += bbs) {
+ FixedStorageHandler<NQ, 2 * BB> res2;
+ kernel_accumulate_block<NQ, BB>(nsq, codes, LUT, res2, scaler);
+ res.set_block_origin(0, j0);
+ res2.to_other_handler(res);
+ codes += bbs * nsq / 2;
+ }
+}
+
+template <class ResultHandler, class Scaler>
+void pq4_accumulate_loop_fixed_scaler(
+ int nq,
+ size_t nb,
+ int bbs,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ FAISS_THROW_IF_NOT(is_aligned_pointer(codes));
+ FAISS_THROW_IF_NOT(is_aligned_pointer(LUT));
+ FAISS_THROW_IF_NOT(bbs % 32 == 0);
+ FAISS_THROW_IF_NOT(nb % bbs == 0);
+
+#define DISPATCH(NQ, BB) \
+ case NQ * 1000 + BB: \
+ accumulate_fixed_blocks<NQ, BB>(nb, nsq, codes, LUT, res, scaler); \
+ break
+
+ switch (nq * 1000 + bbs / 32) {
+ DISPATCH(1, 1);
+ DISPATCH(1, 2);
+ DISPATCH(1, 3);
+ DISPATCH(1, 4);
+ DISPATCH(1, 5);
+ DISPATCH(2, 1);
+ DISPATCH(2, 2);
+ DISPATCH(3, 1);
+ DISPATCH(4, 1);
+ default:
+ FAISS_THROW_FMT("nq=%d bbs=%d not instantiated", nq, bbs);
+ }
+#undef DISPATCH
+}
+
+template <class ResultHandler>
+void pq4_accumulate_loop_fixed_handler(
+ int nq,
+ size_t nb,
+ int bbs,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const NormTableScaler* scaler) {
+ if (scaler) {
+ pq4_accumulate_loop_fixed_scaler(
+ nq, nb, bbs, nsq, codes, LUT, res, *scaler);
+ } else {
+ DummyScaler dscaler;
+ pq4_accumulate_loop_fixed_scaler(
+ nq, nb, bbs, nsq, codes, LUT, res, dscaler);
+ }
+}
+
+struct Run_pq4_accumulate_loop {
+ template <class ResultHandler>
+ void f(ResultHandler& res,
+ int nq,
+ size_t nb,
+ int bbs,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ const NormTableScaler* scaler) {
+ pq4_accumulate_loop_fixed_handler(
+ nq, nb, bbs, nsq, codes, LUT, res, scaler);
+ }
+};
+
+} // anonymous namespace
+
+void pq4_accumulate_loop(
+ int nq,
+ size_t nb,
+ int bbs,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ SIMDResultHandler& res,
+ const NormTableScaler* scaler) {
+ Run_pq4_accumulate_loop consumer;
+ dispatch_SIMDResultHandler(
+ res, consumer, nq, nb, bbs, nsq, codes, LUT, scaler);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan_search_qbs.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan_search_qbs.cpp
new file mode 100644
index 0000000..a9efe13
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/pq4_fast_scan_search_qbs.cpp
@@ -0,0 +1,803 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/pq4_fast_scan.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/LookupTableScaler.h>
+#include <faiss/impl/simd_result_handlers.h>
+#include <faiss/utils/simdlib.h>
+
+namespace faiss {
+
+// declared in simd_result_handlers.h
+bool simd_result_handlers_accept_virtual = true;
+
+using namespace simd_result_handlers;
+
+/************************************************************
+ * Accumulation functions
+ ************************************************************/
+
+namespace {
+
+/*
+ * The computation kernel
+ * It accumulates results for NQ queries and 2 * 16 database elements
+ * writes results in a ResultHandler
+ */
+
+#ifndef __AVX512F__
+
+template <int NQ, class ResultHandler, class Scaler>
+void kernel_accumulate_block(
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ // dummy alloc to keep the windows compiler happy
+ constexpr int NQA = NQ > 0 ? NQ : 1;
+ // distance accumulators
+ // layout: accu[q][b]: distance accumulator for vectors 8*b..8*b+7
+ simd16uint16 accu[NQA][4];
+
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < 4; b++) {
+ accu[q][b].clear();
+ }
+ }
+
+ // _mm_prefetch(codes + 768, 0);
+ for (int sq = 0; sq < nsq - scaler.nscale; sq += 2) {
+ // prefetch
+ simd32uint8 c(codes);
+ codes += 32;
+
+ simd32uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 2 quantizers
+ simd32uint8 lut(LUT);
+ LUT += 32;
+
+ simd32uint8 res0 = lut.lookup_2_lanes(clo);
+ simd32uint8 res1 = lut.lookup_2_lanes(chi);
+
+ accu[q][0] += simd16uint16(res0);
+ accu[q][1] += simd16uint16(res0) >> 8;
+
+ accu[q][2] += simd16uint16(res1);
+ accu[q][3] += simd16uint16(res1) >> 8;
+ }
+ }
+
+ for (int sq = 0; sq < scaler.nscale; sq += 2) {
+ // prefetch
+ simd32uint8 c(codes);
+ codes += 32;
+
+ simd32uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 2 quantizers
+ simd32uint8 lut(LUT);
+ LUT += 32;
+
+ simd32uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][0] += scaler.scale_lo(res0); // handle vectors 0..7
+ accu[q][1] += scaler.scale_hi(res0); // handle vectors 8..15
+
+ simd32uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][2] += scaler.scale_lo(res1); // handle vectors 16..23
+ accu[q][3] += scaler.scale_hi(res1); // handle vectors 24..31
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ accu[q][0] -= accu[q][1] << 8;
+ simd16uint16 dis0 = combine2x2(accu[q][0], accu[q][1]);
+ accu[q][2] -= accu[q][3] << 8;
+ simd16uint16 dis1 = combine2x2(accu[q][2], accu[q][3]);
+ res.handle(q, 0, dis0, dis1);
+ }
+}
+
+#else
+
+// a special version for NQ=1.
+// Despite the function being large in the text form, it compiles to a very
+// compact assembler code.
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+template <class ResultHandler, class Scaler>
+void kernel_accumulate_block_avx512_nq1(
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ // NQ is kept in order to match the similarity to baseline function
+ constexpr int NQ = 1;
+ // distance accumulators. We can accept more for NQ=1
+ // layout: accu[q][b]: distance accumulator for vectors 32*b..32*b+15
+ simd32uint16 accu[NQ][4];
+ // layout: accu[q][b]: distance accumulator for vectors 32*b+16..32*b+31
+ simd32uint16 accu1[NQ][4];
+
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < 4; b++) {
+ accu[q][b].clear();
+ accu1[q][b].clear();
+ }
+ }
+
+ // process "nsq - scaler.nscale" part
+ const int nsq_minus_nscale = nsq - scaler.nscale;
+ const int nsq_minus_nscale_8 = (nsq_minus_nscale / 8) * 8;
+ const int nsq_minus_nscale_4 = (nsq_minus_nscale / 4) * 4;
+
+ // process in chunks of 8
+ for (int sq = 0; sq < nsq_minus_nscale_8; sq += 8) {
+ // prefetch
+ simd64uint8 c(codes);
+ codes += 64;
+
+ simd64uint8 c1(codes);
+ codes += 64;
+
+ simd64uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd64uint8 chi = simd64uint8(simd32uint16(c) >> 4) & mask;
+ simd64uint8 clo = c & mask;
+
+ simd64uint8 c1hi = simd64uint8(simd32uint16(c1) >> 4) & mask;
+ simd64uint8 c1lo = c1 & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd64uint8 lut(LUT);
+ LUT += 64;
+
+ {
+ simd64uint8 res0 = lut.lookup_4_lanes(clo);
+ simd64uint8 res1 = lut.lookup_4_lanes(chi);
+
+ accu[q][0] += simd32uint16(res0);
+ accu[q][1] += simd32uint16(res0) >> 8;
+
+ accu[q][2] += simd32uint16(res1);
+ accu[q][3] += simd32uint16(res1) >> 8;
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd64uint8 lut(LUT);
+ LUT += 64;
+
+ {
+ simd64uint8 res0 = lut.lookup_4_lanes(c1lo);
+ simd64uint8 res1 = lut.lookup_4_lanes(c1hi);
+
+ accu1[q][0] += simd32uint16(res0);
+ accu1[q][1] += simd32uint16(res0) >> 8;
+
+ accu1[q][2] += simd32uint16(res1);
+ accu1[q][3] += simd32uint16(res1) >> 8;
+ }
+ }
+ }
+
+ // process leftovers: a single chunk of size 4
+ if (nsq_minus_nscale_8 != nsq_minus_nscale_4) {
+ // prefetch
+ simd64uint8 c(codes);
+ codes += 64;
+
+ simd64uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd64uint8 chi = simd64uint8(simd32uint16(c) >> 4) & mask;
+ simd64uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd64uint8 lut(LUT);
+ LUT += 64;
+
+ simd64uint8 res0 = lut.lookup_4_lanes(clo);
+ simd64uint8 res1 = lut.lookup_4_lanes(chi);
+
+ accu[q][0] += simd32uint16(res0);
+ accu[q][1] += simd32uint16(res0) >> 8;
+
+ accu[q][2] += simd32uint16(res1);
+ accu[q][3] += simd32uint16(res1) >> 8;
+ }
+ }
+
+ // process leftovers: a single chunk of size 2
+ if (nsq_minus_nscale_4 != nsq_minus_nscale) {
+ // prefetch
+ simd32uint8 c(codes);
+ codes += 32;
+
+ simd32uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 2 quantizers
+ simd32uint8 lut(LUT);
+ LUT += 32;
+
+ simd32uint8 res0 = lut.lookup_2_lanes(clo);
+ simd32uint8 res1 = lut.lookup_2_lanes(chi);
+
+ accu[q][0] += simd32uint16(simd16uint16(res0));
+ accu[q][1] += simd32uint16(simd16uint16(res0) >> 8);
+
+ accu[q][2] += simd32uint16(simd16uint16(res1));
+ accu[q][3] += simd32uint16(simd16uint16(res1) >> 8);
+ }
+ }
+
+ // process "sq" part
+ const int nscale = scaler.nscale;
+ const int nscale_8 = (nscale / 8) * 8;
+ const int nscale_4 = (nscale / 4) * 4;
+
+ // process in chunks of 8
+ for (int sq = 0; sq < nscale_8; sq += 8) {
+ // prefetch
+ simd64uint8 c(codes);
+ codes += 64;
+
+ simd64uint8 c1(codes);
+ codes += 64;
+
+ simd64uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd64uint8 chi = simd64uint8(simd32uint16(c) >> 4) & mask;
+ simd64uint8 clo = c & mask;
+
+ simd64uint8 c1hi = simd64uint8(simd32uint16(c1) >> 4) & mask;
+ simd64uint8 c1lo = c1 & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd64uint8 lut(LUT);
+ LUT += 64;
+
+ {
+ simd64uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][0] += scaler.scale_lo(res0); // handle vectors 0..15
+ accu[q][1] += scaler.scale_hi(res0); // handle vectors 16..31
+
+ simd64uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][2] += scaler.scale_lo(res1); // handle vectors 32..47
+ accu[q][3] += scaler.scale_hi(res1); // handle vectors 48..63
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd64uint8 lut(LUT);
+ LUT += 64;
+
+ {
+ simd64uint8 res0 = scaler.lookup(lut, c1lo);
+ accu1[q][0] += scaler.scale_lo(res0); // handle vectors 0..7
+ accu1[q][1] += scaler.scale_hi(res0); // handle vectors 8..15
+
+ simd64uint8 res1 = scaler.lookup(lut, c1hi);
+ accu1[q][2] += scaler.scale_lo(res1); // handle vectors 16..23
+ accu1[q][3] += scaler.scale_hi(res1); // handle vectors 24..31
+ }
+ }
+ }
+
+ // process leftovers: a single chunk of size 4
+ if (nscale_8 != nscale_4) {
+ // prefetch
+ simd64uint8 c(codes);
+ codes += 64;
+
+ simd64uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd64uint8 chi = simd64uint8(simd32uint16(c) >> 4) & mask;
+ simd64uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd64uint8 lut(LUT);
+ LUT += 64;
+
+ simd64uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][0] += scaler.scale_lo(res0); // handle vectors 0..15
+ accu[q][1] += scaler.scale_hi(res0); // handle vectors 16..31
+
+ simd64uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][2] += scaler.scale_lo(res1); // handle vectors 32..47
+ accu[q][3] += scaler.scale_hi(res1); // handle vectors 48..63
+ }
+ }
+
+ // process leftovers: a single chunk of size 2
+ if (nscale_4 != nscale) {
+ // prefetch
+ simd32uint8 c(codes);
+ codes += 32;
+
+ simd32uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 2 quantizers
+ simd32uint8 lut(LUT);
+ LUT += 32;
+
+ simd32uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][0] +=
+ simd32uint16(scaler.scale_lo(res0)); // handle vectors 0..7
+ accu[q][1] +=
+ simd32uint16(scaler.scale_hi(res0)); // handle vectors 8..15
+
+ simd32uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][2] += simd32uint16(
+ scaler.scale_lo(res1)); // handle vectors 16..23
+ accu[q][3] += simd32uint16(
+ scaler.scale_hi(res1)); // handle vectors 24..31
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < 4; b++) {
+ accu[q][b] += accu1[q][b];
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ accu[q][0] -= accu[q][1] << 8;
+ simd16uint16 dis0 = combine4x2(accu[q][0], accu[q][1]);
+ accu[q][2] -= accu[q][3] << 8;
+ simd16uint16 dis1 = combine4x2(accu[q][2], accu[q][3]);
+ res.handle(q, 0, dis0, dis1);
+ }
+}
+
+// general-purpose case
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+template <int NQ, class ResultHandler, class Scaler>
+void kernel_accumulate_block_avx512_nqx(
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ // dummy alloc to keep the windows compiler happy
+ constexpr int NQA = NQ > 0 ? NQ : 1;
+ // distance accumulators
+ // layout: accu[q][b]: distance accumulator for vectors 8*b..8*b+7
+ simd32uint16 accu[NQA][4];
+
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < 4; b++) {
+ accu[q][b].clear();
+ }
+ }
+
+ // process "nsq - scaler.nscale" part
+ const int nsq_minus_nscale = nsq - scaler.nscale;
+ const int nsq_minus_nscale_4 = (nsq_minus_nscale / 4) * 4;
+
+ // process in chunks of 8
+ for (int sq = 0; sq < nsq_minus_nscale_4; sq += 4) {
+ // prefetch
+ simd64uint8 c(codes);
+ codes += 64;
+
+ simd64uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd64uint8 chi = simd64uint8(simd32uint16(c) >> 4) & mask;
+ simd64uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd32uint8 lut_a(LUT);
+ simd32uint8 lut_b(LUT + NQ * 32);
+
+ simd64uint8 lut(lut_a, lut_b);
+ LUT += 32;
+
+ {
+ simd64uint8 res0 = lut.lookup_4_lanes(clo);
+ simd64uint8 res1 = lut.lookup_4_lanes(chi);
+
+ accu[q][0] += simd32uint16(res0);
+ accu[q][1] += simd32uint16(res0) >> 8;
+
+ accu[q][2] += simd32uint16(res1);
+ accu[q][3] += simd32uint16(res1) >> 8;
+ }
+ }
+
+ LUT += NQ * 32;
+ }
+
+ // process leftovers: a single chunk of size 2
+ if (nsq_minus_nscale_4 != nsq_minus_nscale) {
+ // prefetch
+ simd32uint8 c(codes);
+ codes += 32;
+
+ simd32uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 2 quantizers
+ simd32uint8 lut(LUT);
+ LUT += 32;
+
+ simd32uint8 res0 = lut.lookup_2_lanes(clo);
+ simd32uint8 res1 = lut.lookup_2_lanes(chi);
+
+ accu[q][0] += simd32uint16(simd16uint16(res0));
+ accu[q][1] += simd32uint16(simd16uint16(res0) >> 8);
+
+ accu[q][2] += simd32uint16(simd16uint16(res1));
+ accu[q][3] += simd32uint16(simd16uint16(res1) >> 8);
+ }
+ }
+
+ // process "sq" part
+ const int nscale = scaler.nscale;
+ const int nscale_4 = (nscale / 4) * 4;
+
+ // process in chunks of 4
+ for (int sq = 0; sq < nscale_4; sq += 4) {
+ // prefetch
+ simd64uint8 c(codes);
+ codes += 64;
+
+ simd64uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd64uint8 chi = simd64uint8(simd32uint16(c) >> 4) & mask;
+ simd64uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 4 quantizers
+ simd32uint8 lut_a(LUT);
+ simd32uint8 lut_b(LUT + NQ * 32);
+
+ simd64uint8 lut(lut_a, lut_b);
+ LUT += 32;
+
+ {
+ simd64uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][0] += scaler.scale_lo(res0); // handle vectors 0..7
+ accu[q][1] += scaler.scale_hi(res0); // handle vectors 8..15
+
+ simd64uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][2] += scaler.scale_lo(res1); // handle vectors 16..23
+ accu[q][3] += scaler.scale_hi(res1); // handle vectors 24..31
+ }
+ }
+
+ LUT += NQ * 32;
+ }
+
+ // process leftovers: a single chunk of size 2
+ if (nscale_4 != nscale) {
+ // prefetch
+ simd32uint8 c(codes);
+ codes += 32;
+
+ simd32uint8 mask(0xf);
+ // shift op does not exist for int8...
+ simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask;
+ simd32uint8 clo = c & mask;
+
+ for (int q = 0; q < NQ; q++) {
+ // load LUTs for 2 quantizers
+ simd32uint8 lut(LUT);
+ LUT += 32;
+
+ simd32uint8 res0 = scaler.lookup(lut, clo);
+ accu[q][0] +=
+ simd32uint16(scaler.scale_lo(res0)); // handle vectors 0..7
+ accu[q][1] +=
+ simd32uint16(scaler.scale_hi(res0)); // handle vectors 8..15
+
+ simd32uint8 res1 = scaler.lookup(lut, chi);
+ accu[q][2] += simd32uint16(
+ scaler.scale_lo(res1)); // handle vectors 16..23
+ accu[q][3] += simd32uint16(
+ scaler.scale_hi(res1)); // handle vectors 24..31
+ }
+ }
+
+ for (int q = 0; q < NQ; q++) {
+ accu[q][0] -= accu[q][1] << 8;
+ simd16uint16 dis0 = combine4x2(accu[q][0], accu[q][1]);
+ accu[q][2] -= accu[q][3] << 8;
+ simd16uint16 dis1 = combine4x2(accu[q][2], accu[q][3]);
+ res.handle(q, 0, dis0, dis1);
+ }
+}
+
+template <int NQ, class ResultHandler, class Scaler>
+void kernel_accumulate_block(
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ if constexpr (NQ == 1) {
+ kernel_accumulate_block_avx512_nq1<ResultHandler, Scaler>(
+ nsq, codes, LUT, res, scaler);
+ } else {
+ kernel_accumulate_block_avx512_nqx<NQ, ResultHandler, Scaler>(
+ nsq, codes, LUT, res, scaler);
+ }
+}
+
+#endif
+
+// handle at most 4 blocks of queries
+template <int QBS, class ResultHandler, class Scaler>
+void accumulate_q_4step(
+ size_t ntotal2,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT0,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ constexpr int Q1 = QBS & 15;
+ constexpr int Q2 = (QBS >> 4) & 15;
+ constexpr int Q3 = (QBS >> 8) & 15;
+ constexpr int Q4 = (QBS >> 12) & 15;
+ constexpr int SQ = Q1 + Q2 + Q3 + Q4;
+
+ for (size_t j0 = 0; j0 < ntotal2; j0 += 32) {
+ FixedStorageHandler<SQ, 2> res2;
+ const uint8_t* LUT = LUT0;
+ kernel_accumulate_block<Q1>(nsq, codes, LUT, res2, scaler);
+ LUT += Q1 * nsq * 16;
+ if (Q2 > 0) {
+ res2.set_block_origin(Q1, 0);
+ kernel_accumulate_block<Q2>(nsq, codes, LUT, res2, scaler);
+ LUT += Q2 * nsq * 16;
+ }
+ if (Q3 > 0) {
+ res2.set_block_origin(Q1 + Q2, 0);
+ kernel_accumulate_block<Q3>(nsq, codes, LUT, res2, scaler);
+ LUT += Q3 * nsq * 16;
+ }
+ if (Q4 > 0) {
+ res2.set_block_origin(Q1 + Q2 + Q3, 0);
+ kernel_accumulate_block<Q4>(nsq, codes, LUT, res2, scaler);
+ }
+ res.set_block_origin(0, j0);
+ res2.to_other_handler(res);
+ codes += 32 * nsq / 2;
+ }
+}
+
+template <int NQ, class ResultHandler, class Scaler>
+void kernel_accumulate_block_loop(
+ size_t ntotal2,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ for (size_t j0 = 0; j0 < ntotal2; j0 += 32) {
+ res.set_block_origin(0, j0);
+ kernel_accumulate_block<NQ, ResultHandler>(
+ nsq, codes + j0 * nsq / 2, LUT, res, scaler);
+ }
+}
+
+// non-template version of accumulate kernel -- dispatches dynamically
+template <class ResultHandler, class Scaler>
+void accumulate(
+ int nq,
+ size_t ntotal2,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ assert(nsq % 2 == 0);
+ assert(is_aligned_pointer(codes));
+ assert(is_aligned_pointer(LUT));
+
+#define DISPATCH(NQ) \
+ case NQ: \
+ kernel_accumulate_block_loop<NQ, ResultHandler>( \
+ ntotal2, nsq, codes, LUT, res, scaler); \
+ return
+
+ switch (nq) {
+ DISPATCH(1);
+ DISPATCH(2);
+ DISPATCH(3);
+ DISPATCH(4);
+ }
+ FAISS_THROW_FMT("accumulate nq=%d not instantiated", nq);
+
+#undef DISPATCH
+}
+
+template <class ResultHandler, class Scaler>
+void pq4_accumulate_loop_qbs_fixed_scaler(
+ int qbs,
+ size_t ntotal2,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT0,
+ ResultHandler& res,
+ const Scaler& scaler) {
+ assert(nsq % 2 == 0);
+ assert(is_aligned_pointer(codes));
+ assert(is_aligned_pointer(LUT0));
+
+ // try out optimized versions
+ switch (qbs) {
+#define DISPATCH(QBS) \
+ case QBS: \
+ accumulate_q_4step<QBS>(ntotal2, nsq, codes, LUT0, res, scaler); \
+ return;
+ DISPATCH(0x3333); // 12
+ DISPATCH(0x2333); // 11
+ DISPATCH(0x2233); // 10
+ DISPATCH(0x333); // 9
+ DISPATCH(0x2223); // 9
+ DISPATCH(0x233); // 8
+ DISPATCH(0x1223); // 8
+ DISPATCH(0x223); // 7
+ DISPATCH(0x34); // 7
+ DISPATCH(0x133); // 7
+ DISPATCH(0x6); // 6
+ DISPATCH(0x33); // 6
+ DISPATCH(0x123); // 6
+ DISPATCH(0x222); // 6
+ DISPATCH(0x23); // 5
+ DISPATCH(0x5); // 5
+ DISPATCH(0x13); // 4
+ DISPATCH(0x22); // 4
+ DISPATCH(0x4); // 4
+ DISPATCH(0x3); // 3
+ DISPATCH(0x21); // 3
+ DISPATCH(0x2); // 2
+ DISPATCH(0x1); // 1
+#undef DISPATCH
+ }
+
+ // default implementation where qbs is not known at compile time
+
+ for (size_t j0 = 0; j0 < ntotal2; j0 += 32) {
+ const uint8_t* LUT = LUT0;
+ int qi = qbs;
+ int i0 = 0;
+ while (qi) {
+ int nq = qi & 15;
+ qi >>= 4;
+ res.set_block_origin(i0, j0);
+#define DISPATCH(NQ) \
+ case NQ: \
+ kernel_accumulate_block<NQ, ResultHandler>( \
+ nsq, codes, LUT, res, scaler); \
+ break
+ switch (nq) {
+ DISPATCH(1);
+ DISPATCH(2);
+ DISPATCH(3);
+ DISPATCH(4);
+#undef DISPATCH
+ default:
+ FAISS_THROW_FMT("accumulate nq=%d not instantiated", nq);
+ }
+ i0 += nq;
+ LUT += nq * nsq * 16;
+ }
+ codes += 32 * nsq / 2;
+ }
+}
+
+struct Run_pq4_accumulate_loop_qbs {
+ template <class ResultHandler>
+ void f(ResultHandler& res,
+ int qbs,
+ size_t nb,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ const NormTableScaler* scaler) {
+ if (scaler) {
+ pq4_accumulate_loop_qbs_fixed_scaler(
+ qbs, nb, nsq, codes, LUT, res, *scaler);
+ } else {
+ DummyScaler dummy;
+ pq4_accumulate_loop_qbs_fixed_scaler(
+ qbs, nb, nsq, codes, LUT, res, dummy);
+ }
+ }
+};
+
+} // namespace
+
+void pq4_accumulate_loop_qbs(
+ int qbs,
+ size_t nb,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ SIMDResultHandler& res,
+ const NormTableScaler* scaler) {
+ Run_pq4_accumulate_loop_qbs consumer;
+ dispatch_SIMDResultHandler(res, consumer, qbs, nb, nsq, codes, LUT, scaler);
+}
+
+/***************************************************************
+ * Packing functions
+ ***************************************************************/
+
+int pq4_qbs_to_nq(int qbs) {
+ int i0 = 0;
+ int qi = qbs;
+ while (qi) {
+ int nq = qi & 15;
+ qi >>= 4;
+ i0 += nq;
+ }
+ return i0;
+}
+
+void accumulate_to_mem(
+ int nq,
+ size_t ntotal2,
+ int nsq,
+ const uint8_t* codes,
+ const uint8_t* LUT,
+ uint16_t* accu) {
+ FAISS_THROW_IF_NOT(ntotal2 % 32 == 0);
+ StoreResultHandler handler(accu, ntotal2);
+ DummyScaler scaler;
+ accumulate(nq, ntotal2, nsq, codes, LUT, handler, scaler);
+}
+
+int pq4_preferred_qbs(int n) {
+ // from timmings in P141901742, P141902828
+ static int map[12] = {
+ 0, 1, 2, 3, 0x13, 0x23, 0x33, 0x223, 0x233, 0x333, 0x2233, 0x2333};
+ if (n <= 11) {
+ return map[n];
+ } else if (n <= 24) {
+ // override qbs: all first stages with 3 steps
+ // then 1 stage with the rest
+ int nbit = 4 * (n / 3); // nbits with only 3s
+ int qbs = 0x33333333 & ((1 << nbit) - 1);
+ qbs |= (n % 3) << nbit;
+ return qbs;
+ } else {
+ FAISS_THROW_FMT("number of queries %d too large", n);
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/residual_quantizer_encode_steps.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/residual_quantizer_encode_steps.cpp
new file mode 100644
index 0000000..e4c74b1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/residual_quantizer_encode_steps.cpp
@@ -0,0 +1,960 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/residual_quantizer_encode_steps.h>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/simdlib.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/utils/approx_topk/approx_topk.h>
+
+extern "C" {
+
+// general matrix multiplication
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+/********************************************************************
+ * Basic routines
+ ********************************************************************/
+
+namespace {
+
+template <size_t M, size_t NK>
+void accum_and_store_tab(
+ const size_t m_offset,
+ const float* const __restrict codebook_cross_norms,
+ const uint64_t* const __restrict codebook_offsets,
+ const int32_t* const __restrict codes_i,
+ const size_t b,
+ const size_t ldc,
+ const size_t K,
+ float* const __restrict output) {
+ // load pointers into registers
+ const float* cbs[M];
+ for (size_t ij = 0; ij < M; ij++) {
+ const size_t code = static_cast<size_t>(codes_i[b * m_offset + ij]);
+ cbs[ij] = &codebook_cross_norms[(codebook_offsets[ij] + code) * ldc];
+ }
+
+ // do accumulation in registers using SIMD.
+ // It is possible that compiler may be smart enough so that
+ // this manual SIMD unrolling might be unneeded.
+#if defined(__AVX2__) || defined(__aarch64__)
+ const size_t K8 = (K / (8 * NK)) * (8 * NK);
+
+ // process in chunks of size (8 * NK) floats
+ for (size_t kk = 0; kk < K8; kk += 8 * NK) {
+ simd8float32 regs[NK];
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik].loadu(cbs[0] + kk + ik * 8);
+ }
+
+ for (size_t ij = 1; ij < M; ij++) {
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik] += simd8float32(cbs[ij] + kk + ik * 8);
+ }
+ }
+
+ // write the result
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik].storeu(output + kk + ik * 8);
+ }
+ }
+#else
+ const size_t K8 = 0;
+#endif
+
+ // process leftovers
+ for (size_t kk = K8; kk < K; kk++) {
+ float reg = cbs[0][kk];
+ for (size_t ij = 1; ij < M; ij++) {
+ reg += cbs[ij][kk];
+ }
+ output[kk] = reg;
+ }
+}
+
+template <size_t M, size_t NK>
+void accum_and_add_tab(
+ const size_t m_offset,
+ const float* const __restrict codebook_cross_norms,
+ const uint64_t* const __restrict codebook_offsets,
+ const int32_t* const __restrict codes_i,
+ const size_t b,
+ const size_t ldc,
+ const size_t K,
+ float* const __restrict output) {
+ // load pointers into registers
+ const float* cbs[M];
+ for (size_t ij = 0; ij < M; ij++) {
+ const size_t code = static_cast<size_t>(codes_i[b * m_offset + ij]);
+ cbs[ij] = &codebook_cross_norms[(codebook_offsets[ij] + code) * ldc];
+ }
+
+ // do accumulation in registers using SIMD.
+ // It is possible that compiler may be smart enough so that
+ // this manual SIMD unrolling might be unneeded.
+#if defined(__AVX2__) || defined(__aarch64__)
+ const size_t K8 = (K / (8 * NK)) * (8 * NK);
+
+ // process in chunks of size (8 * NK) floats
+ for (size_t kk = 0; kk < K8; kk += 8 * NK) {
+ simd8float32 regs[NK];
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik].loadu(cbs[0] + kk + ik * 8);
+ }
+
+ for (size_t ij = 1; ij < M; ij++) {
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik] += simd8float32(cbs[ij] + kk + ik * 8);
+ }
+ }
+
+ // write the result
+ for (size_t ik = 0; ik < NK; ik++) {
+ simd8float32 existing(output + kk + ik * 8);
+ existing += regs[ik];
+ existing.storeu(output + kk + ik * 8);
+ }
+ }
+#else
+ const size_t K8 = 0;
+#endif
+
+ // process leftovers
+ for (size_t kk = K8; kk < K; kk++) {
+ float reg = cbs[0][kk];
+ for (size_t ij = 1; ij < M; ij++) {
+ reg += cbs[ij][kk];
+ }
+ output[kk] += reg;
+ }
+}
+
+template <size_t M, size_t NK>
+void accum_and_finalize_tab(
+ const float* const __restrict codebook_cross_norms,
+ const uint64_t* const __restrict codebook_offsets,
+ const int32_t* const __restrict codes_i,
+ const size_t b,
+ const size_t ldc,
+ const size_t K,
+ const float* const __restrict distances_i,
+ const float* const __restrict cd_common,
+ float* const __restrict output) {
+ // load pointers into registers
+ const float* cbs[M];
+ for (size_t ij = 0; ij < M; ij++) {
+ const size_t code = static_cast<size_t>(codes_i[b * M + ij]);
+ cbs[ij] = &codebook_cross_norms[(codebook_offsets[ij] + code) * ldc];
+ }
+
+ // do accumulation in registers using SIMD.
+ // It is possible that compiler may be smart enough so that
+ // this manual SIMD unrolling might be unneeded.
+#if defined(__AVX2__) || defined(__aarch64__)
+ const size_t K8 = (K / (8 * NK)) * (8 * NK);
+
+ // process in chunks of size (8 * NK) floats
+ for (size_t kk = 0; kk < K8; kk += 8 * NK) {
+ simd8float32 regs[NK];
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik].loadu(cbs[0] + kk + ik * 8);
+ }
+
+ for (size_t ij = 1; ij < M; ij++) {
+ for (size_t ik = 0; ik < NK; ik++) {
+ regs[ik] += simd8float32(cbs[ij] + kk + ik * 8);
+ }
+ }
+
+ simd8float32 two(2.0f);
+ for (size_t ik = 0; ik < NK; ik++) {
+ // cent_distances[b * K + k] = distances_i[b] + cd_common[k]
+ // + 2 * dp[k];
+
+ simd8float32 common_v(cd_common + kk + ik * 8);
+ common_v = fmadd(two, regs[ik], common_v);
+
+ common_v += simd8float32(distances_i[b]);
+ common_v.storeu(output + b * K + kk + ik * 8);
+ }
+ }
+#else
+ const size_t K8 = 0;
+#endif
+
+ // process leftovers
+ for (size_t kk = K8; kk < K; kk++) {
+ float reg = cbs[0][kk];
+ for (size_t ij = 1; ij < M; ij++) {
+ reg += cbs[ij][kk];
+ }
+
+ output[b * K + kk] = distances_i[b] + cd_common[kk] + 2 * reg;
+ }
+}
+
+} // anonymous namespace
+
+/********************************************************************
+ * Single encoding step
+ ********************************************************************/
+
+void beam_search_encode_step(
+ size_t d,
+ size_t K,
+ const float* cent, /// size (K, d)
+ size_t n,
+ size_t beam_size,
+ const float* residuals, /// size (n, beam_size, d)
+ size_t m,
+ const int32_t* codes, /// size (n, beam_size, m)
+ size_t new_beam_size,
+ int32_t* new_codes, /// size (n, new_beam_size, m + 1)
+ float* new_residuals, /// size (n, new_beam_size, d)
+ float* new_distances, /// size (n, new_beam_size)
+ Index* assign_index,
+ ApproxTopK_mode_t approx_topk_mode) {
+ // we have to fill in the whole output matrix
+ FAISS_THROW_IF_NOT(new_beam_size <= beam_size * K);
+
+ std::vector<float> cent_distances;
+ std::vector<idx_t> cent_ids;
+
+ if (assign_index) {
+ // search beam_size distances per query
+ FAISS_THROW_IF_NOT(assign_index->d == d);
+ cent_distances.resize(n * beam_size * new_beam_size);
+ cent_ids.resize(n * beam_size * new_beam_size);
+ if (assign_index->ntotal != 0) {
+ // then we assume the codebooks are already added to the index
+ FAISS_THROW_IF_NOT(assign_index->ntotal == K);
+ } else {
+ assign_index->add(K, cent);
+ }
+
+ // printf("beam_search_encode_step -- mem usage %zd\n",
+ // get_mem_usage_kb());
+ assign_index->search(
+ n * beam_size,
+ residuals,
+ new_beam_size,
+ cent_distances.data(),
+ cent_ids.data());
+ } else {
+ // do one big distance computation
+ cent_distances.resize(n * beam_size * K);
+ pairwise_L2sqr(
+ d, n * beam_size, residuals, K, cent, cent_distances.data());
+ }
+ InterruptCallback::check();
+
+#pragma omp parallel for if (n > 100)
+ for (int64_t i = 0; i < n; i++) {
+ const int32_t* codes_i = codes + i * m * beam_size;
+ int32_t* new_codes_i = new_codes + i * (m + 1) * new_beam_size;
+ const float* residuals_i = residuals + i * d * beam_size;
+ float* new_residuals_i = new_residuals + i * d * new_beam_size;
+
+ float* new_distances_i = new_distances + i * new_beam_size;
+ using C = CMax<float, int>;
+
+ if (assign_index) {
+ const float* cent_distances_i =
+ cent_distances.data() + i * beam_size * new_beam_size;
+ const idx_t* cent_ids_i =
+ cent_ids.data() + i * beam_size * new_beam_size;
+
+ // here we could be a tad more efficient by merging sorted arrays
+ for (int i_2 = 0; i_2 < new_beam_size; i_2++) {
+ new_distances_i[i_2] = C::neutral();
+ }
+ std::vector<int> perm(new_beam_size, -1);
+ heap_addn<C>(
+ new_beam_size,
+ new_distances_i,
+ perm.data(),
+ cent_distances_i,
+ nullptr,
+ beam_size * new_beam_size);
+ heap_reorder<C>(new_beam_size, new_distances_i, perm.data());
+
+ for (int j = 0; j < new_beam_size; j++) {
+ int js = perm[j] / new_beam_size;
+ int ls = cent_ids_i[perm[j]];
+ if (m > 0) {
+ memcpy(new_codes_i, codes_i + js * m, sizeof(*codes) * m);
+ }
+ new_codes_i[m] = ls;
+ new_codes_i += m + 1;
+ fvec_sub(
+ d,
+ residuals_i + js * d,
+ cent + ls * d,
+ new_residuals_i);
+ new_residuals_i += d;
+ }
+
+ } else {
+ const float* cent_distances_i =
+ cent_distances.data() + i * beam_size * K;
+ // then we have to select the best results
+ for (int i_2 = 0; i_2 < new_beam_size; i_2++) {
+ new_distances_i[i_2] = C::neutral();
+ }
+ std::vector<int> perm(new_beam_size, -1);
+
+#define HANDLE_APPROX(NB, BD) \
+ case ApproxTopK_mode_t::APPROX_TOPK_BUCKETS_B##NB##_D##BD: \
+ HeapWithBuckets<C, NB, BD>::bs_addn( \
+ beam_size, \
+ K, \
+ cent_distances_i, \
+ new_beam_size, \
+ new_distances_i, \
+ perm.data()); \
+ break;
+
+ switch (approx_topk_mode) {
+ HANDLE_APPROX(8, 3)
+ HANDLE_APPROX(8, 2)
+ HANDLE_APPROX(16, 2)
+ HANDLE_APPROX(32, 2)
+ default:
+ heap_addn<C>(
+ new_beam_size,
+ new_distances_i,
+ perm.data(),
+ cent_distances_i,
+ nullptr,
+ beam_size * K);
+ }
+ heap_reorder<C>(new_beam_size, new_distances_i, perm.data());
+
+#undef HANDLE_APPROX
+
+ for (int j = 0; j < new_beam_size; j++) {
+ int js = perm[j] / K;
+ int ls = perm[j] % K;
+ if (m > 0) {
+ memcpy(new_codes_i, codes_i + js * m, sizeof(*codes) * m);
+ }
+ new_codes_i[m] = ls;
+ new_codes_i += m + 1;
+ fvec_sub(
+ d,
+ residuals_i + js * d,
+ cent + ls * d,
+ new_residuals_i);
+ new_residuals_i += d;
+ }
+ }
+ }
+}
+
+// exposed in the faiss namespace
+void beam_search_encode_step_tab(
+ size_t K,
+ size_t n,
+ size_t beam_size, // input sizes
+ const float* codebook_cross_norms, // size K * ldc
+ size_t ldc,
+ const uint64_t* codebook_offsets, // m
+ const float* query_cp, // size n * ldqc
+ size_t ldqc, // >= K
+ const float* cent_norms_i, // size K
+ size_t m,
+ const int32_t* codes, // n * beam_size * m
+ const float* distances, // n * beam_size
+ size_t new_beam_size,
+ int32_t* new_codes, // n * new_beam_size * (m + 1)
+ float* new_distances, // n * new_beam_size
+ ApproxTopK_mode_t approx_topk_mode) //
+{
+ FAISS_THROW_IF_NOT(ldc >= K);
+
+#pragma omp parallel for if (n > 100) schedule(dynamic)
+ for (int64_t i = 0; i < n; i++) {
+ std::vector<float> cent_distances(beam_size * K);
+ std::vector<float> cd_common(K);
+
+ const int32_t* codes_i = codes + i * m * beam_size;
+ const float* query_cp_i = query_cp + i * ldqc;
+ const float* distances_i = distances + i * beam_size;
+
+ for (size_t k = 0; k < K; k++) {
+ cd_common[k] = cent_norms_i[k] - 2 * query_cp_i[k];
+ }
+
+ bool use_baseline_implementation = false;
+
+ // This is the baseline implementation. Its primary flaw
+ // that it writes way too many info to the temporary buffer
+ // called dp.
+ //
+ // This baseline code is kept intentionally because it is easy to
+ // understand what an optimized version optimizes exactly.
+ //
+ if (use_baseline_implementation) {
+ for (size_t b = 0; b < beam_size; b++) {
+ std::vector<float> dp(K);
+
+ for (size_t m1 = 0; m1 < m; m1++) {
+ size_t c = codes_i[b * m + m1];
+ const float* cb =
+ &codebook_cross_norms
+ [(codebook_offsets[m1] + c) * ldc];
+ fvec_add(K, cb, dp.data(), dp.data());
+ }
+
+ for (size_t k = 0; k < K; k++) {
+ cent_distances[b * K + k] =
+ distances_i[b] + cd_common[k] + 2 * dp[k];
+ }
+ }
+
+ } else {
+ // An optimized implementation that avoids using a temporary buffer
+ // and does the accumulation in registers.
+
+ // Compute a sum of NK AQ codes.
+#define ACCUM_AND_FINALIZE_TAB(NK) \
+ case NK: \
+ for (size_t b = 0; b < beam_size; b++) { \
+ accum_and_finalize_tab<NK, 4>( \
+ codebook_cross_norms, \
+ codebook_offsets, \
+ codes_i, \
+ b, \
+ ldc, \
+ K, \
+ distances_i, \
+ cd_common.data(), \
+ cent_distances.data()); \
+ } \
+ break;
+
+ // this version contains many switch-case scenarios, but
+ // they won't affect branch predictor.
+ switch (m) {
+ case 0:
+ // trivial case
+ for (size_t b = 0; b < beam_size; b++) {
+ for (size_t k = 0; k < K; k++) {
+ cent_distances[b * K + k] =
+ distances_i[b] + cd_common[k];
+ }
+ }
+ break;
+
+ ACCUM_AND_FINALIZE_TAB(1)
+ ACCUM_AND_FINALIZE_TAB(2)
+ ACCUM_AND_FINALIZE_TAB(3)
+ ACCUM_AND_FINALIZE_TAB(4)
+ ACCUM_AND_FINALIZE_TAB(5)
+ ACCUM_AND_FINALIZE_TAB(6)
+ ACCUM_AND_FINALIZE_TAB(7)
+
+ default: {
+ // m >= 8 case.
+
+ // A temporary buffer has to be used due to the lack of
+ // registers. But we'll try to accumulate up to 8 AQ codes
+ // in registers and issue a single write operation to the
+ // buffer, while the baseline does no accumulation. So, the
+ // number of write operations to the temporary buffer is
+ // reduced 8x.
+
+ // allocate a temporary buffer
+ std::vector<float> dp(K);
+
+ for (size_t b = 0; b < beam_size; b++) {
+ // Initialize it. Compute a sum of first 8 AQ codes
+ // because m >= 8 .
+ accum_and_store_tab<8, 4>(
+ m,
+ codebook_cross_norms,
+ codebook_offsets,
+ codes_i,
+ b,
+ ldc,
+ K,
+ dp.data());
+
+#define ACCUM_AND_ADD_TAB(NK) \
+ case NK: \
+ accum_and_add_tab<NK, 4>( \
+ m, \
+ codebook_cross_norms, \
+ codebook_offsets + im, \
+ codes_i + im, \
+ b, \
+ ldc, \
+ K, \
+ dp.data()); \
+ break;
+
+ // accumulate up to 8 additional AQ codes into
+ // a temporary buffer
+ for (size_t im = 8; im < ((m + 7) / 8) * 8; im += 8) {
+ size_t m_left = m - im;
+ if (m_left > 8) {
+ m_left = 8;
+ }
+
+ switch (m_left) {
+ ACCUM_AND_ADD_TAB(1)
+ ACCUM_AND_ADD_TAB(2)
+ ACCUM_AND_ADD_TAB(3)
+ ACCUM_AND_ADD_TAB(4)
+ ACCUM_AND_ADD_TAB(5)
+ ACCUM_AND_ADD_TAB(6)
+ ACCUM_AND_ADD_TAB(7)
+ ACCUM_AND_ADD_TAB(8)
+ }
+ }
+
+ // done. finalize the result
+ for (size_t k = 0; k < K; k++) {
+ cent_distances[b * K + k] =
+ distances_i[b] + cd_common[k] + 2 * dp[k];
+ }
+ }
+ }
+ }
+
+ // the optimized implementation ends here
+ }
+ using C = CMax<float, int>;
+ int32_t* new_codes_i = new_codes + i * (m + 1) * new_beam_size;
+ float* new_distances_i = new_distances + i * new_beam_size;
+
+ const float* cent_distances_i = cent_distances.data();
+
+ // then we have to select the best results
+ for (int i_2 = 0; i_2 < new_beam_size; i_2++) {
+ new_distances_i[i_2] = C::neutral();
+ }
+ std::vector<int> perm(new_beam_size, -1);
+
+#define HANDLE_APPROX(NB, BD) \
+ case ApproxTopK_mode_t::APPROX_TOPK_BUCKETS_B##NB##_D##BD: \
+ HeapWithBuckets<C, NB, BD>::bs_addn( \
+ beam_size, \
+ K, \
+ cent_distances_i, \
+ new_beam_size, \
+ new_distances_i, \
+ perm.data()); \
+ break;
+
+ switch (approx_topk_mode) {
+ HANDLE_APPROX(8, 3)
+ HANDLE_APPROX(8, 2)
+ HANDLE_APPROX(16, 2)
+ HANDLE_APPROX(32, 2)
+ default:
+ heap_addn<C>(
+ new_beam_size,
+ new_distances_i,
+ perm.data(),
+ cent_distances_i,
+ nullptr,
+ beam_size * K);
+ break;
+ }
+
+ heap_reorder<C>(new_beam_size, new_distances_i, perm.data());
+
+#undef HANDLE_APPROX
+
+ for (int j = 0; j < new_beam_size; j++) {
+ int js = perm[j] / K;
+ int ls = perm[j] % K;
+ if (m > 0) {
+ memcpy(new_codes_i, codes_i + js * m, sizeof(*codes) * m);
+ }
+ new_codes_i[m] = ls;
+ new_codes_i += m + 1;
+ }
+ }
+}
+
+/********************************************************************
+ * Multiple encoding steps
+ ********************************************************************/
+
+namespace rq_encode_steps {
+
+void refine_beam_mp(
+ const ResidualQuantizer& rq,
+ size_t n,
+ size_t beam_size,
+ const float* x,
+ int out_beam_size,
+ int32_t* out_codes,
+ float* out_residuals,
+ float* out_distances,
+ RefineBeamMemoryPool& pool) {
+ int cur_beam_size = beam_size;
+
+ double t0 = getmillisecs();
+
+ // find the max_beam_size
+ int max_beam_size = 0;
+ {
+ int tmp_beam_size = cur_beam_size;
+ for (int m = 0; m < rq.M; m++) {
+ int K = 1 << rq.nbits[m];
+ int new_beam_size = std::min(tmp_beam_size * K, out_beam_size);
+ tmp_beam_size = new_beam_size;
+
+ if (max_beam_size < new_beam_size) {
+ max_beam_size = new_beam_size;
+ }
+ }
+ }
+
+ // preallocate buffers
+ pool.new_codes.resize(n * max_beam_size * (rq.M + 1));
+ pool.new_residuals.resize(n * max_beam_size * rq.d);
+
+ pool.codes.resize(n * max_beam_size * (rq.M + 1));
+ pool.distances.resize(n * max_beam_size);
+ pool.residuals.resize(n * rq.d * max_beam_size);
+
+ for (size_t i = 0; i < n * rq.d * beam_size; i++) {
+ pool.residuals[i] = x[i];
+ }
+
+ // set up pointers to buffers
+ int32_t* __restrict codes_ptr = pool.codes.data();
+ float* __restrict residuals_ptr = pool.residuals.data();
+
+ int32_t* __restrict new_codes_ptr = pool.new_codes.data();
+ float* __restrict new_residuals_ptr = pool.new_residuals.data();
+
+ // index
+ std::unique_ptr<Index> assign_index;
+ if (rq.assign_index_factory) {
+ assign_index.reset((*rq.assign_index_factory)(rq.d));
+ }
+
+ // main loop
+ size_t codes_size = 0;
+ size_t distances_size = 0;
+ size_t residuals_size = 0;
+
+ for (int m = 0; m < rq.M; m++) {
+ int K = 1 << rq.nbits[m];
+
+ const float* __restrict codebooks_m =
+ rq.codebooks.data() + rq.codebook_offsets[m] * rq.d;
+
+ const int new_beam_size = std::min(cur_beam_size * K, out_beam_size);
+
+ codes_size = n * new_beam_size * (m + 1);
+ residuals_size = n * new_beam_size * rq.d;
+ distances_size = n * new_beam_size;
+
+ beam_search_encode_step(
+ rq.d,
+ K,
+ codebooks_m,
+ n,
+ cur_beam_size,
+ residuals_ptr,
+ m,
+ codes_ptr,
+ new_beam_size,
+ new_codes_ptr,
+ new_residuals_ptr,
+ pool.distances.data(),
+ assign_index.get(),
+ rq.approx_topk_mode);
+
+ if (assign_index != nullptr) {
+ assign_index->reset();
+ }
+
+ std::swap(codes_ptr, new_codes_ptr);
+ std::swap(residuals_ptr, new_residuals_ptr);
+
+ cur_beam_size = new_beam_size;
+
+ if (rq.verbose) {
+ float sum_distances = 0;
+ for (int j = 0; j < distances_size; j++) {
+ sum_distances += pool.distances[j];
+ }
+
+ printf("[%.3f s] encode stage %d, %d bits, "
+ "total error %g, beam_size %d\n",
+ (getmillisecs() - t0) / 1000,
+ m,
+ int(rq.nbits[m]),
+ sum_distances,
+ cur_beam_size);
+ }
+ }
+
+ if (out_codes) {
+ memcpy(out_codes, codes_ptr, codes_size * sizeof(*codes_ptr));
+ }
+ if (out_residuals) {
+ memcpy(out_residuals,
+ residuals_ptr,
+ residuals_size * sizeof(*residuals_ptr));
+ }
+ if (out_distances) {
+ memcpy(out_distances,
+ pool.distances.data(),
+ distances_size * sizeof(pool.distances[0]));
+ }
+}
+
+void refine_beam_LUT_mp(
+ const ResidualQuantizer& rq,
+ size_t n,
+ const float* query_norms, // size n
+ const float* query_cp, //
+ int out_beam_size,
+ int32_t* out_codes,
+ float* out_distances,
+ RefineBeamLUTMemoryPool& pool) {
+ int beam_size = 1;
+
+ double t0 = getmillisecs();
+
+ // find the max_beam_size
+ int max_beam_size = 0;
+ {
+ int tmp_beam_size = beam_size;
+ for (int m = 0; m < rq.M; m++) {
+ int K = 1 << rq.nbits[m];
+ int new_beam_size = std::min(tmp_beam_size * K, out_beam_size);
+ tmp_beam_size = new_beam_size;
+
+ if (max_beam_size < new_beam_size) {
+ max_beam_size = new_beam_size;
+ }
+ }
+ }
+
+ // preallocate buffers
+ pool.new_codes.resize(n * max_beam_size * (rq.M + 1));
+ pool.new_distances.resize(n * max_beam_size);
+
+ pool.codes.resize(n * max_beam_size * (rq.M + 1));
+ pool.distances.resize(n * max_beam_size);
+
+ for (size_t i = 0; i < n; i++) {
+ pool.distances[i] = query_norms[i];
+ }
+
+ // set up pointers to buffers
+ int32_t* __restrict new_codes_ptr = pool.new_codes.data();
+ float* __restrict new_distances_ptr = pool.new_distances.data();
+
+ int32_t* __restrict codes_ptr = pool.codes.data();
+ float* __restrict distances_ptr = pool.distances.data();
+
+ // main loop
+ size_t codes_size = 0;
+ size_t distances_size = 0;
+ size_t cross_ofs = 0;
+ for (int m = 0; m < rq.M; m++) {
+ int K = 1 << rq.nbits[m];
+
+ // it is guaranteed that (new_beam_size <= max_beam_size)
+ int new_beam_size = std::min(beam_size * K, out_beam_size);
+
+ codes_size = n * new_beam_size * (m + 1);
+ distances_size = n * new_beam_size;
+ FAISS_THROW_IF_NOT(
+ cross_ofs + rq.codebook_offsets[m] * K <=
+ rq.codebook_cross_products.size());
+ beam_search_encode_step_tab(
+ K,
+ n,
+ beam_size,
+ rq.codebook_cross_products.data() + cross_ofs,
+ K,
+ rq.codebook_offsets.data(),
+ query_cp + rq.codebook_offsets[m],
+ rq.total_codebook_size,
+ rq.centroid_norms.data() + rq.codebook_offsets[m],
+ m,
+ codes_ptr,
+ distances_ptr,
+ new_beam_size,
+ new_codes_ptr,
+ new_distances_ptr,
+ rq.approx_topk_mode);
+ cross_ofs += rq.codebook_offsets[m] * K;
+ std::swap(codes_ptr, new_codes_ptr);
+ std::swap(distances_ptr, new_distances_ptr);
+
+ beam_size = new_beam_size;
+
+ if (rq.verbose) {
+ float sum_distances = 0;
+ for (int j = 0; j < distances_size; j++) {
+ sum_distances += distances_ptr[j];
+ }
+ printf("[%.3f s] encode stage %d, %d bits, "
+ "total error %g, beam_size %d\n",
+ (getmillisecs() - t0) / 1000,
+ m,
+ int(rq.nbits[m]),
+ sum_distances,
+ beam_size);
+ }
+ }
+ if (out_codes) {
+ memcpy(out_codes, codes_ptr, codes_size * sizeof(*codes_ptr));
+ }
+ if (out_distances) {
+ memcpy(out_distances,
+ distances_ptr,
+ distances_size * sizeof(*distances_ptr));
+ }
+}
+
+// this is for use_beam_LUT == 0
+void compute_codes_add_centroids_mp_lut0(
+ const ResidualQuantizer& rq,
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids,
+ ComputeCodesAddCentroidsLUT0MemoryPool& pool) {
+ pool.codes.resize(rq.max_beam_size * rq.M * n);
+ pool.distances.resize(rq.max_beam_size * n);
+
+ pool.residuals.resize(rq.max_beam_size * n * rq.d);
+
+ refine_beam_mp(
+ rq,
+ n,
+ 1,
+ x,
+ rq.max_beam_size,
+ pool.codes.data(),
+ pool.residuals.data(),
+ pool.distances.data(),
+ pool.refine_beam_pool);
+
+ if (rq.search_type == ResidualQuantizer::ST_norm_float ||
+ rq.search_type == ResidualQuantizer::ST_norm_qint8 ||
+ rq.search_type == ResidualQuantizer::ST_norm_qint4) {
+ pool.norms.resize(n);
+ // recover the norms of reconstruction as
+ // || original_vector - residual ||^2
+ for (size_t i = 0; i < n; i++) {
+ pool.norms[i] = fvec_L2sqr(
+ x + i * rq.d,
+ pool.residuals.data() + i * rq.max_beam_size * rq.d,
+ rq.d);
+ }
+ }
+
+ // pack only the first code of the beam
+ // (hence the ld_codes=M * max_beam_size)
+ rq.pack_codes(
+ n,
+ pool.codes.data(),
+ codes_out,
+ rq.M * rq.max_beam_size,
+ (pool.norms.size() > 0) ? pool.norms.data() : nullptr,
+ centroids);
+}
+
+// use_beam_LUT == 1
+void compute_codes_add_centroids_mp_lut1(
+ const ResidualQuantizer& rq,
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids,
+ ComputeCodesAddCentroidsLUT1MemoryPool& pool) {
+ //
+ pool.codes.resize(rq.max_beam_size * rq.M * n);
+ pool.distances.resize(rq.max_beam_size * n);
+
+ FAISS_THROW_IF_NOT_MSG(
+ rq.M == 1 || rq.codebook_cross_products.size() > 0,
+ "call compute_codebook_tables first");
+
+ pool.query_norms.resize(n);
+ fvec_norms_L2sqr(pool.query_norms.data(), x, rq.d, n);
+
+ pool.query_cp.resize(n * rq.total_codebook_size);
+ {
+ FINTEGER ti = rq.total_codebook_size, di = rq.d, ni = n;
+ float zero = 0, one = 1;
+ sgemm_("Transposed",
+ "Not transposed",
+ &ti,
+ &ni,
+ &di,
+ &one,
+ rq.codebooks.data(),
+ &di,
+ x,
+ &di,
+ &zero,
+ pool.query_cp.data(),
+ &ti);
+ }
+
+ refine_beam_LUT_mp(
+ rq,
+ n,
+ pool.query_norms.data(),
+ pool.query_cp.data(),
+ rq.max_beam_size,
+ pool.codes.data(),
+ pool.distances.data(),
+ pool.refine_beam_lut_pool);
+
+ // pack only the first code of the beam
+ // (hence the ld_codes=M * max_beam_size)
+ rq.pack_codes(
+ n,
+ pool.codes.data(),
+ codes_out,
+ rq.M * rq.max_beam_size,
+ nullptr,
+ centroids);
+}
+
+} // namespace rq_encode_steps
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/residual_quantizer_encode_steps.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/residual_quantizer_encode_steps.h
new file mode 100644
index 0000000..3d17efd
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/residual_quantizer_encode_steps.h
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/utils/approx_topk/mode.h>
+
+namespace faiss {
+
+/********************************************************************
+ * Single step of encoding
+ ********************************************************************/
+
+/** Encode a residual by sampling from a centroid table.
+ *
+ * This is a single encoding step the residual quantizer.
+ * It allows low-level access to the encoding function, exposed mainly for unit
+ * tests.
+ *
+ * @param n number of vectors to handle
+ * @param residuals vectors to encode, size (n, beam_size, d)
+ * @param cent centroids, size (K, d)
+ * @param beam_size input beam size
+ * @param m size of the codes for the previous encoding steps
+ * @param codes code array for the previous steps of the beam (n,
+ * beam_size, m)
+ * @param new_beam_size output beam size (should be <= K * beam_size)
+ * @param new_codes output codes, size (n, new_beam_size, m + 1)
+ * @param new_residuals output residuals, size (n, new_beam_size, d)
+ * @param new_distances output distances, size (n, new_beam_size)
+ * @param assign_index if non-NULL, will be used to perform assignment
+ */
+void beam_search_encode_step(
+ size_t d,
+ size_t K,
+ const float* cent,
+ size_t n,
+ size_t beam_size,
+ const float* residuals,
+ size_t m,
+ const int32_t* codes,
+ size_t new_beam_size,
+ int32_t* new_codes,
+ float* new_residuals,
+ float* new_distances,
+ Index* assign_index = nullptr,
+ ApproxTopK_mode_t approx_topk = ApproxTopK_mode_t::EXACT_TOPK);
+
+/** Encode a set of vectors using their dot products with the codebooks
+ *
+ * @param K number of vectors in the codebook
+ * @param n nb of vectors to encode
+ * @param beam_size input beam size
+ * @param codebook_cross_norms inner product of this codebook with the m
+ * previously encoded codebooks
+ * @param codebook_offsets offsets into codebook_cross_norms for each
+ * previous codebook
+ * @param query_cp dot products of query vectors with ???
+ * @param cent_norms_i norms of centroids
+ */
+void beam_search_encode_step_tab(
+ size_t K,
+ size_t n,
+ size_t beam_size, // input sizes
+ const float* codebook_cross_norms, // size K * ldc
+ size_t ldc, // >= K
+ const uint64_t* codebook_offsets, // m
+ const float* query_cp, // size n * ldqc
+ size_t ldqc, // >= K
+ const float* cent_norms_i, // size K
+ size_t m,
+ const int32_t* codes, // n * beam_size * m
+ const float* distances, // n * beam_size
+ size_t new_beam_size,
+ int32_t* new_codes, // n * new_beam_size * (m + 1)
+ float* new_distances, // n * new_beam_size
+ ApproxTopK_mode_t approx_topk = ApproxTopK_mode_t::EXACT_TOPK);
+
+/********************************************************************
+ * Multiple encoding steps
+ *
+ * The following functions take buffer objects that they use as temp
+ * memory (allocated within the functions). The buffers are intended
+ * to be re-used over batches of points to encode.
+ ********************************************************************/
+
+struct ResidualQuantizer;
+
+namespace rq_encode_steps {
+
+// Preallocated memory chunk for refine_beam_mp() call
+struct RefineBeamMemoryPool {
+ std::vector<int32_t> new_codes;
+ std::vector<float> new_residuals;
+
+ std::vector<float> residuals;
+ std::vector<int32_t> codes;
+ std::vector<float> distances;
+};
+
+void refine_beam_mp(
+ const ResidualQuantizer& rq,
+ size_t n,
+ size_t beam_size,
+ const float* x,
+ int out_beam_size,
+ int32_t* out_codes,
+ float* out_residuals,
+ float* out_distances,
+ RefineBeamMemoryPool& pool);
+
+// Preallocated memory chunk for refine_beam_LUT_mp() call
+struct RefineBeamLUTMemoryPool {
+ std::vector<int32_t> new_codes;
+ std::vector<float> new_distances;
+
+ std::vector<int32_t> codes;
+ std::vector<float> distances;
+};
+
+void refine_beam_LUT_mp(
+ const ResidualQuantizer& rq,
+ size_t n,
+ const float* query_norms, // size n
+ const float* query_cp, //
+ int out_beam_size,
+ int32_t* out_codes,
+ float* out_distances,
+ RefineBeamLUTMemoryPool& pool);
+
+// this is for use_beam_LUT == 0 in compute_codes_add_centroids_mp_lut0() call
+struct ComputeCodesAddCentroidsLUT0MemoryPool {
+ std::vector<int32_t> codes;
+ std::vector<float> norms;
+ std::vector<float> distances;
+ std::vector<float> residuals;
+ RefineBeamMemoryPool refine_beam_pool;
+};
+
+void compute_codes_add_centroids_mp_lut0(
+ const ResidualQuantizer& rq,
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids,
+ ComputeCodesAddCentroidsLUT0MemoryPool& pool);
+
+// this is for use_beam_LUT == 1 in compute_codes_add_centroids_mp_lut1() call
+struct ComputeCodesAddCentroidsLUT1MemoryPool {
+ std::vector<int32_t> codes;
+ std::vector<float> distances;
+ std::vector<float> query_norms;
+ std::vector<float> query_cp;
+ std::vector<float> residuals;
+ RefineBeamLUTMemoryPool refine_beam_lut_pool;
+};
+
+void compute_codes_add_centroids_mp_lut1(
+ const ResidualQuantizer& rq,
+ const float* x,
+ uint8_t* codes_out,
+ size_t n,
+ const float* centroids,
+ ComputeCodesAddCentroidsLUT1MemoryPool& pool);
+
+} // namespace rq_encode_steps
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/simd_result_handlers.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/simd_result_handlers.h
new file mode 100644
index 0000000..baa640d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/simd_result_handlers.h
@@ -0,0 +1,787 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <type_traits>
+#include <vector>
+
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/simdlib.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/AlignedTable.h>
+#include <faiss/utils/partitioning.h>
+
+/** This file contains callbacks for kernels that compute distances.
+ */
+
+namespace faiss {
+
+struct SIMDResultHandler {
+ // used to dispatch templates
+ bool is_CMax = false;
+ uint8_t sizeof_ids = 0;
+ bool with_fields = false;
+
+ /** called when 32 distances are computed and provided in two
+ * simd16uint16. (q, b) indicate which entry it is in the block. */
+ virtual void handle(
+ size_t q,
+ size_t b,
+ simd16uint16 d0,
+ simd16uint16 d1) = 0;
+
+ /// set the sub-matrix that is being computed
+ virtual void set_block_origin(size_t i0, size_t j0) = 0;
+
+ virtual ~SIMDResultHandler() {}
+};
+
+/* Result handler that will return float resutls eventually */
+struct SIMDResultHandlerToFloat : SIMDResultHandler {
+ size_t nq; // number of queries
+ size_t ntotal; // ignore excess elements after ntotal
+
+ /// these fields are used mainly for the IVF variants (with_id_map=true)
+ const idx_t* id_map = nullptr; // map offset in invlist to vector id
+ const int* q_map = nullptr; // map q to global query
+ const uint16_t* dbias =
+ nullptr; // table of biases to add to each query (for IVF L2 search)
+ const float* normalizers = nullptr; // size 2 * nq, to convert
+
+ SIMDResultHandlerToFloat(size_t nq, size_t ntotal)
+ : nq(nq), ntotal(ntotal) {}
+
+ virtual void begin(const float* norms) {
+ normalizers = norms;
+ }
+
+ // called at end of search to convert int16 distances to float, before
+ // normalizers are deallocated
+ virtual void end() {
+ normalizers = nullptr;
+ }
+};
+
+FAISS_API extern bool simd_result_handlers_accept_virtual;
+
+namespace simd_result_handlers {
+
+/** Dummy structure that just computes a chqecksum on results
+ * (to avoid the computation to be optimized away) */
+struct DummyResultHandler : SIMDResultHandler {
+ size_t cs = 0;
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ cs += q * 123 + b * 789 + d0.get_scalar_0() + d1.get_scalar_0();
+ }
+
+ void set_block_origin(size_t, size_t) final {}
+
+ ~DummyResultHandler() {}
+};
+
+/** memorize results in a nq-by-nb matrix.
+ *
+ * j0 is the current upper-left block of the matrix
+ */
+struct StoreResultHandler : SIMDResultHandler {
+ uint16_t* data;
+ size_t ld; // total number of columns
+ size_t i0 = 0;
+ size_t j0 = 0;
+
+ StoreResultHandler(uint16_t* data, size_t ld) : data(data), ld(ld) {}
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ size_t ofs = (q + i0) * ld + j0 + b * 32;
+ d0.store(data + ofs);
+ d1.store(data + ofs + 16);
+ }
+
+ void set_block_origin(size_t i0_in, size_t j0_in) final {
+ this->i0 = i0_in;
+ this->j0 = j0_in;
+ }
+};
+
+/** stores results in fixed-size matrix. */
+template <int NQ, int BB>
+struct FixedStorageHandler : SIMDResultHandler {
+ simd16uint16 dis[NQ][BB];
+ int i0 = 0;
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ dis[q + i0][2 * b] = d0;
+ dis[q + i0][2 * b + 1] = d1;
+ }
+
+ void set_block_origin(size_t i0_in, size_t j0_in) final {
+ this->i0 = i0_in;
+ assert(j0_in == 0);
+ }
+
+ template <class OtherResultHandler>
+ void to_other_handler(OtherResultHandler& other) const {
+ for (int q = 0; q < NQ; q++) {
+ for (int b = 0; b < BB; b += 2) {
+ other.handle(q, b / 2, dis[q][b], dis[q][b + 1]);
+ }
+ }
+ }
+
+ virtual ~FixedStorageHandler() {}
+};
+
+/** Result handler that compares distances to check if they need to be kept */
+template <class C, bool with_id_map>
+struct ResultHandlerCompare : SIMDResultHandlerToFloat {
+ using TI = typename C::TI;
+
+ bool disable = false;
+
+ int64_t i0 = 0; // query origin
+ int64_t j0 = 0; // db origin
+
+ const IDSelector* sel;
+
+ ResultHandlerCompare(size_t nq, size_t ntotal, const IDSelector* sel_in)
+ : SIMDResultHandlerToFloat(nq, ntotal), sel{sel_in} {
+ this->is_CMax = C::is_max;
+ this->sizeof_ids = sizeof(typename C::TI);
+ this->with_fields = with_id_map;
+ }
+
+ void set_block_origin(size_t i0_in, size_t j0_in) final {
+ this->i0 = i0_in;
+ this->j0 = j0_in;
+ }
+
+ // adjust handler data for IVF.
+ void adjust_with_origin(size_t& q, simd16uint16& d0, simd16uint16& d1) {
+ q += i0;
+
+ if (dbias) {
+ simd16uint16 dbias16(dbias[q]);
+ d0 += dbias16;
+ d1 += dbias16;
+ }
+
+ if (with_id_map) { // FIXME test on q_map instead
+ q = q_map[q];
+ }
+ }
+
+ // compute and adjust idx
+ int64_t adjust_id(size_t b, size_t j) {
+ int64_t idx = j0 + 32 * b + j;
+ if (with_id_map) {
+ idx = id_map[idx];
+ }
+ return idx;
+ }
+
+ /// return binary mask of elements below thr in (d0, d1)
+ /// inverse_test returns elements above
+ uint32_t get_lt_mask(
+ uint16_t thr,
+ size_t b,
+ simd16uint16 d0,
+ simd16uint16 d1) {
+ simd16uint16 thr16(thr);
+ uint32_t lt_mask;
+
+ constexpr bool keep_min = C::is_max;
+ if (keep_min) {
+ lt_mask = ~cmp_ge32(d0, d1, thr16);
+ } else {
+ lt_mask = ~cmp_le32(d0, d1, thr16);
+ }
+
+ if (lt_mask == 0) {
+ return 0;
+ }
+ uint64_t idx = j0 + b * 32;
+ if (idx + 32 > ntotal) {
+ if (idx >= ntotal) {
+ return 0;
+ }
+ int nbit = (ntotal - idx);
+ lt_mask &= (uint32_t(1) << nbit) - 1;
+ }
+ return lt_mask;
+ }
+
+ virtual ~ResultHandlerCompare() {}
+};
+
+/** Special version for k=1 */
+template <class C, bool with_id_map = false>
+struct SingleResultHandler : ResultHandlerCompare<C, with_id_map> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using RHC = ResultHandlerCompare<C, with_id_map>;
+ using RHC::normalizers;
+
+ std::vector<int16_t> idis;
+ float* dis;
+ int64_t* ids;
+
+ SingleResultHandler(
+ size_t nq,
+ size_t ntotal,
+ float* dis,
+ int64_t* ids,
+ const IDSelector* sel_in)
+ : RHC(nq, ntotal, sel_in), idis(nq), dis(dis), ids(ids) {
+ for (size_t i = 0; i < nq; i++) {
+ ids[i] = -1;
+ idis[i] = C::neutral();
+ }
+ }
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ if (this->disable) {
+ return;
+ }
+
+ this->adjust_with_origin(q, d0, d1);
+
+ uint32_t lt_mask = this->get_lt_mask(idis[q], b, d0, d1);
+ if (!lt_mask) {
+ return;
+ }
+
+ ALIGNED(32) uint16_t d32tab[32];
+ d0.store(d32tab);
+ d1.store(d32tab + 16);
+
+ if (this->sel != nullptr) {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ auto real_idx = this->adjust_id(b, j);
+ lt_mask -= 1 << j;
+ if (this->sel->is_member(real_idx)) {
+ T d = d32tab[j];
+ if (C::cmp(idis[q], d)) {
+ idis[q] = d;
+ ids[q] = real_idx;
+ }
+ }
+ }
+ } else {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ lt_mask -= 1 << j;
+ T d = d32tab[j];
+ if (C::cmp(idis[q], d)) {
+ idis[q] = d;
+ ids[q] = this->adjust_id(b, j);
+ }
+ }
+ }
+ }
+
+ void end() {
+ for (size_t q = 0; q < this->nq; q++) {
+ if (!normalizers) {
+ dis[q] = idis[q];
+ } else {
+ float one_a = 1 / normalizers[2 * q];
+ float b = normalizers[2 * q + 1];
+ dis[q] = b + idis[q] * one_a;
+ }
+ }
+ }
+};
+
+/** Structure that collects results in a min- or max-heap */
+template <class C, bool with_id_map = false>
+struct HeapHandler : ResultHandlerCompare<C, with_id_map> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using RHC = ResultHandlerCompare<C, with_id_map>;
+ using RHC::normalizers;
+
+ std::vector<uint16_t> idis;
+ std::vector<TI> iids;
+ float* dis;
+ int64_t* ids;
+
+ int64_t k; // number of results to keep
+
+ HeapHandler(
+ size_t nq,
+ size_t ntotal,
+ int64_t k,
+ float* dis,
+ int64_t* ids,
+ const IDSelector* sel_in)
+ : RHC(nq, ntotal, sel_in),
+ idis(nq * k),
+ iids(nq * k),
+ dis(dis),
+ ids(ids),
+ k(k) {
+ heap_heapify<C>(k * nq, idis.data(), iids.data());
+ }
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ if (this->disable) {
+ return;
+ }
+
+ this->adjust_with_origin(q, d0, d1);
+
+ T* heap_dis = idis.data() + q * k;
+ TI* heap_ids = iids.data() + q * k;
+
+ uint16_t cur_thresh =
+ heap_dis[0] < 65536 ? (uint16_t)(heap_dis[0]) : 0xffff;
+
+ // here we handle the reverse comparison case as well
+ uint32_t lt_mask = this->get_lt_mask(cur_thresh, b, d0, d1);
+
+ if (!lt_mask) {
+ return;
+ }
+
+ ALIGNED(32) uint16_t d32tab[32];
+ d0.store(d32tab);
+ d1.store(d32tab + 16);
+
+ if (this->sel != nullptr) {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ auto real_idx = this->adjust_id(b, j);
+ lt_mask -= 1 << j;
+ if (this->sel->is_member(real_idx)) {
+ T dis_2 = d32tab[j];
+ if (C::cmp(heap_dis[0], dis_2)) {
+ heap_replace_top<C>(
+ k, heap_dis, heap_ids, dis_2, real_idx);
+ }
+ }
+ }
+ } else {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ lt_mask -= 1 << j;
+ T dis_2 = d32tab[j];
+ if (C::cmp(heap_dis[0], dis_2)) {
+ int64_t idx = this->adjust_id(b, j);
+ heap_replace_top<C>(k, heap_dis, heap_ids, dis_2, idx);
+ }
+ }
+ }
+ }
+
+ void end() override {
+ for (size_t q = 0; q < this->nq; q++) {
+ T* heap_dis_in = idis.data() + q * k;
+ TI* heap_ids_in = iids.data() + q * k;
+ heap_reorder<C>(k, heap_dis_in, heap_ids_in);
+ float* heap_dis = dis + q * k;
+ int64_t* heap_ids = ids + q * k;
+
+ float one_a = 1.0, b = 0.0;
+ if (normalizers) {
+ one_a = 1 / normalizers[2 * q];
+ b = normalizers[2 * q + 1];
+ }
+ for (int j = 0; j < k; j++) {
+ heap_dis[j] = heap_dis_in[j] * one_a + b;
+ heap_ids[j] = heap_ids_in[j];
+ }
+ }
+ }
+};
+
+/** Simple top-N implementation using a reservoir.
+ *
+ * Results are stored when they are below the threshold until the capacity is
+ * reached. Then a partition sort is used to update the threshold. */
+
+/** Handler built from several ReservoirTopN (one per query) */
+template <class C, bool with_id_map = false>
+struct ReservoirHandler : ResultHandlerCompare<C, with_id_map> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using RHC = ResultHandlerCompare<C, with_id_map>;
+ using RHC::normalizers;
+
+ size_t capacity; // rounded up to multiple of 16
+
+ // where the final results will be written
+ float* dis;
+ int64_t* ids;
+
+ std::vector<TI> all_ids;
+ AlignedTable<T> all_vals;
+ std::vector<ReservoirTopN<C>> reservoirs;
+
+ ReservoirHandler(
+ size_t nq,
+ size_t ntotal,
+ size_t k,
+ size_t cap,
+ float* dis,
+ int64_t* ids,
+ const IDSelector* sel_in)
+ : RHC(nq, ntotal, sel_in),
+ capacity((cap + 15) & ~15),
+ dis(dis),
+ ids(ids) {
+ assert(capacity % 16 == 0);
+ all_ids.resize(nq * capacity);
+ all_vals.resize(nq * capacity);
+ for (size_t q = 0; q < nq; q++) {
+ reservoirs.emplace_back(
+ k,
+ capacity,
+ all_vals.get() + q * capacity,
+ all_ids.data() + q * capacity);
+ }
+ }
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ if (this->disable) {
+ return;
+ }
+ this->adjust_with_origin(q, d0, d1);
+
+ ReservoirTopN<C>& res = reservoirs[q];
+ uint32_t lt_mask = this->get_lt_mask(res.threshold, b, d0, d1);
+
+ if (!lt_mask) {
+ return;
+ }
+ ALIGNED(32) uint16_t d32tab[32];
+ d0.store(d32tab);
+ d1.store(d32tab + 16);
+
+ if (this->sel != nullptr) {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ auto real_idx = this->adjust_id(b, j);
+ lt_mask -= 1 << j;
+ if (this->sel->is_member(real_idx)) {
+ T dis_2 = d32tab[j];
+ res.add(dis_2, real_idx);
+ }
+ }
+ } else {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ lt_mask -= 1 << j;
+ T dis_2 = d32tab[j];
+ res.add(dis_2, this->adjust_id(b, j));
+ }
+ }
+ }
+
+ void end() override {
+ using Cf = typename std::conditional<
+ C::is_max,
+ CMax<float, int64_t>,
+ CMin<float, int64_t>>::type;
+
+ std::vector<int> perm(reservoirs[0].n);
+ for (size_t q = 0; q < reservoirs.size(); q++) {
+ ReservoirTopN<C>& res = reservoirs[q];
+ size_t n = res.n;
+
+ if (res.i > res.n) {
+ res.shrink();
+ }
+ int64_t* heap_ids = ids + q * n;
+ float* heap_dis = dis + q * n;
+
+ float one_a = 1.0, b = 0.0;
+ if (normalizers) {
+ one_a = 1 / normalizers[2 * q];
+ b = normalizers[2 * q + 1];
+ }
+ for (size_t i = 0; i < res.i; i++) {
+ perm[i] = i;
+ }
+ // indirect sort of result arrays
+ std::sort(perm.begin(), perm.begin() + res.i, [&res](int i, int j) {
+ return C::cmp(res.vals[j], res.vals[i]);
+ });
+ for (size_t i = 0; i < res.i; i++) {
+ heap_dis[i] = res.vals[perm[i]] * one_a + b;
+ heap_ids[i] = res.ids[perm[i]];
+ }
+
+ // possibly add empty results
+ heap_heapify<Cf>(n - res.i, heap_dis + res.i, heap_ids + res.i);
+ }
+ }
+};
+
+/** Result handler for range search. The difficulty is that the range distances
+ * have to be scaled using the scaler.
+ */
+
+template <class C, bool with_id_map = false>
+struct RangeHandler : ResultHandlerCompare<C, with_id_map> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using RHC = ResultHandlerCompare<C, with_id_map>;
+ using RHC::normalizers;
+ using RHC::nq;
+
+ RangeSearchResult& rres;
+ float radius;
+ std::vector<uint16_t> thresholds;
+ std::vector<size_t> n_per_query;
+ size_t q0 = 0;
+
+ // we cannot use the RangeSearchPartialResult interface because queries can
+ // be performed by batches
+ struct Triplet {
+ idx_t q;
+ idx_t b;
+ uint16_t dis;
+ };
+ std::vector<Triplet> triplets;
+
+ RangeHandler(
+ RangeSearchResult& rres,
+ float radius,
+ size_t ntotal,
+ const IDSelector* sel_in)
+ : RHC(rres.nq, ntotal, sel_in), rres(rres), radius(radius) {
+ thresholds.resize(nq);
+ n_per_query.resize(nq + 1);
+ }
+
+ virtual void begin(const float* norms) override {
+ normalizers = norms;
+ for (int q = 0; q < nq; ++q) {
+ thresholds[q] =
+ int(normalizers[2 * q] * (radius - normalizers[2 * q + 1]));
+ }
+ }
+
+ void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final {
+ if (this->disable) {
+ return;
+ }
+ this->adjust_with_origin(q, d0, d1);
+
+ uint32_t lt_mask = this->get_lt_mask(thresholds[q], b, d0, d1);
+
+ if (!lt_mask) {
+ return;
+ }
+ ALIGNED(32) uint16_t d32tab[32];
+ d0.store(d32tab);
+ d1.store(d32tab + 16);
+
+ if (this->sel != nullptr) {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ lt_mask -= 1 << j;
+
+ auto real_idx = this->adjust_id(b, j);
+ if (this->sel->is_member(real_idx)) {
+ T dis = d32tab[j];
+ n_per_query[q]++;
+ triplets.push_back({idx_t(q + q0), real_idx, dis});
+ }
+ }
+ } else {
+ while (lt_mask) {
+ // find first non-zero
+ int j = __builtin_ctz(lt_mask);
+ lt_mask -= 1 << j;
+ T dis = d32tab[j];
+ n_per_query[q]++;
+ triplets.push_back({idx_t(q + q0), this->adjust_id(b, j), dis});
+ }
+ }
+ }
+
+ void end() override {
+ memcpy(rres.lims, n_per_query.data(), sizeof(n_per_query[0]) * nq);
+ rres.do_allocation();
+ for (auto it = triplets.begin(); it != triplets.end(); ++it) {
+ size_t& l = rres.lims[it->q];
+ rres.distances[l] = it->dis;
+ rres.labels[l] = it->b;
+ l++;
+ }
+ memmove(rres.lims + 1, rres.lims, sizeof(*rres.lims) * rres.nq);
+ rres.lims[0] = 0;
+
+ for (int q = 0; q < nq; q++) {
+ float one_a = 1 / normalizers[2 * q];
+ float b = normalizers[2 * q + 1];
+ for (size_t i = rres.lims[q]; i < rres.lims[q + 1]; i++) {
+ rres.distances[i] = rres.distances[i] * one_a + b;
+ }
+ }
+ }
+};
+
+#ifndef SWIG
+
+// handler for a subset of queries
+template <class C, bool with_id_map = false>
+struct PartialRangeHandler : RangeHandler<C, with_id_map> {
+ using T = typename C::T;
+ using TI = typename C::TI;
+ using RHC = RangeHandler<C, with_id_map>;
+ using RHC::normalizers;
+ using RHC::nq, RHC::q0, RHC::triplets, RHC::n_per_query;
+
+ RangeSearchPartialResult& pres;
+
+ PartialRangeHandler(
+ RangeSearchPartialResult& pres,
+ float radius,
+ size_t ntotal,
+ size_t q0,
+ size_t q1,
+ const IDSelector* sel_in)
+ : RangeHandler<C, with_id_map>(*pres.res, radius, ntotal, sel_in),
+ pres(pres) {
+ nq = q1 - q0;
+ this->q0 = q0;
+ }
+
+ // shift left n_per_query
+ void shift_n_per_query() {
+ memmove(n_per_query.data() + 1,
+ n_per_query.data(),
+ nq * sizeof(n_per_query[0]));
+ n_per_query[0] = 0;
+ }
+
+ // commit to partial result instead of full RangeResult
+ void end() override {
+ std::vector<typename RHC::Triplet> sorted_triplets(triplets.size());
+ for (int q = 0; q < nq; q++) {
+ n_per_query[q + 1] += n_per_query[q];
+ }
+ shift_n_per_query();
+
+ for (size_t i = 0; i < triplets.size(); i++) {
+ sorted_triplets[n_per_query[triplets[i].q - q0]++] = triplets[i];
+ }
+ shift_n_per_query();
+
+ size_t* lims = n_per_query.data();
+
+ for (int q = 0; q < nq; q++) {
+ float one_a = 1 / normalizers[2 * q];
+ float b = normalizers[2 * q + 1];
+ RangeQueryResult& qres = pres.new_result(q + q0);
+ for (size_t i = lims[q]; i < lims[q + 1]; i++) {
+ qres.add(
+ sorted_triplets[i].dis * one_a + b,
+ sorted_triplets[i].b);
+ }
+ }
+ }
+};
+
+#endif
+
+/********************************************************************************
+ * Dynamic dispatching function. The consumer should have a templatized method f
+ * that will be replaced with the actual SIMDResultHandler that is determined
+ * dynamically.
+ */
+
+template <class C, bool W, class Consumer, class... Types>
+void dispatch_SIMDResultHandler_fixedCW(
+ SIMDResultHandler& res,
+ Consumer& consumer,
+ Types... args) {
+ if (auto resh = dynamic_cast<SingleResultHandler<C, W>*>(&res)) {
+ consumer.template f<SingleResultHandler<C, W>>(*resh, args...);
+ } else if (auto resh_2 = dynamic_cast<HeapHandler<C, W>*>(&res)) {
+ consumer.template f<HeapHandler<C, W>>(*resh_2, args...);
+ } else if (auto resh_2 = dynamic_cast<ReservoirHandler<C, W>*>(&res)) {
+ consumer.template f<ReservoirHandler<C, W>>(*resh_2, args...);
+ } else { // generic handler -- will not be inlined
+ FAISS_THROW_IF_NOT_FMT(
+ simd_result_handlers_accept_virtual,
+ "Running vitrual handler for %s",
+ typeid(res).name());
+ consumer.template f<SIMDResultHandler>(res, args...);
+ }
+}
+
+template <class C, class Consumer, class... Types>
+void dispatch_SIMDResultHandler_fixedC(
+ SIMDResultHandler& res,
+ Consumer& consumer,
+ Types... args) {
+ if (res.with_fields) {
+ dispatch_SIMDResultHandler_fixedCW<C, true>(res, consumer, args...);
+ } else {
+ dispatch_SIMDResultHandler_fixedCW<C, false>(res, consumer, args...);
+ }
+}
+
+template <class Consumer, class... Types>
+void dispatch_SIMDResultHandler(
+ SIMDResultHandler& res,
+ Consumer& consumer,
+ Types... args) {
+ if (res.sizeof_ids == 0) {
+ if (auto resh = dynamic_cast<StoreResultHandler*>(&res)) {
+ consumer.template f<StoreResultHandler>(*resh, args...);
+ } else if (auto resh_2 = dynamic_cast<DummyResultHandler*>(&res)) {
+ consumer.template f<DummyResultHandler>(*resh_2, args...);
+ } else { // generic path
+ FAISS_THROW_IF_NOT_FMT(
+ simd_result_handlers_accept_virtual,
+ "Running vitrual handler for %s",
+ typeid(res).name());
+ consumer.template f<SIMDResultHandler>(res, args...);
+ }
+ } else if (res.sizeof_ids == sizeof(int)) {
+ if (res.is_CMax) {
+ dispatch_SIMDResultHandler_fixedC<CMax<uint16_t, int>>(
+ res, consumer, args...);
+ } else {
+ dispatch_SIMDResultHandler_fixedC<CMin<uint16_t, int>>(
+ res, consumer, args...);
+ }
+ } else if (res.sizeof_ids == sizeof(int64_t)) {
+ if (res.is_CMax) {
+ dispatch_SIMDResultHandler_fixedC<CMax<uint16_t, int64_t>>(
+ res, consumer, args...);
+ } else {
+ dispatch_SIMDResultHandler_fixedC<CMin<uint16_t, int64_t>>(
+ res, consumer, args...);
+ }
+ } else {
+ FAISS_THROW_FMT("Unknown id size %d", res.sizeof_ids);
+ }
+}
+
+} // namespace simd_result_handlers
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/zerocopy_io.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/zerocopy_io.cpp
new file mode 100644
index 0000000..2d37f6a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/zerocopy_io.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/zerocopy_io.h>
+#include <cstring>
+
+namespace faiss {
+
+ZeroCopyIOReader::ZeroCopyIOReader(uint8_t* data, size_t size)
+ : data_(data), rp_(0), total_(size) {}
+
+ZeroCopyIOReader::~ZeroCopyIOReader() {}
+
+size_t ZeroCopyIOReader::get_data_view(void** ptr, size_t size, size_t nitems) {
+ if (size == 0) {
+ return nitems;
+ }
+
+ size_t actual_size = size * nitems;
+ if (rp_ + size * nitems > total_) {
+ actual_size = total_ - rp_;
+ }
+
+ size_t actual_nitems = (actual_size + size - 1) / size;
+ if (actual_nitems == 0) {
+ return 0;
+ }
+
+ // get an address
+ *ptr = (void*)(reinterpret_cast<const char*>(data_ + rp_));
+
+ // alter pos
+ rp_ += size * actual_nitems;
+
+ return actual_nitems;
+}
+
+void ZeroCopyIOReader::reset() {
+ rp_ = 0;
+}
+
+size_t ZeroCopyIOReader::operator()(void* ptr, size_t size, size_t nitems) {
+ if (size * nitems == 0) {
+ return 0;
+ }
+
+ if (rp_ >= total_) {
+ return 0;
+ }
+ size_t nremain = (total_ - rp_) / size;
+ if (nremain < nitems) {
+ nitems = nremain;
+ }
+ memcpy(ptr, (data_ + rp_), size * nitems);
+ rp_ += size * nitems;
+ return nitems;
+}
+
+int ZeroCopyIOReader::filedescriptor() {
+ return -1; // Indicating no file descriptor available for memory buffer
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/zerocopy_io.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/zerocopy_io.h
new file mode 100644
index 0000000..488b5d1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/impl/zerocopy_io.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+
+#include <faiss/impl/io.h>
+
+namespace faiss {
+
+// ZeroCopyIOReader just maps the data from a given pointer.
+struct ZeroCopyIOReader : public faiss::IOReader {
+ uint8_t* data_;
+ size_t rp_ = 0;
+ size_t total_ = 0;
+
+ ZeroCopyIOReader(uint8_t* data, size_t size);
+ ~ZeroCopyIOReader();
+
+ void reset();
+ size_t get_data_view(void** ptr, size_t size, size_t nitems);
+ size_t operator()(void* ptr, size_t size, size_t nitems) override;
+
+ int filedescriptor() override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/index_factory.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/index_factory.cpp
new file mode 100644
index 0000000..3020439
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/index_factory.cpp
@@ -0,0 +1,956 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/*
+ * implementation of the index_factory function. Lots of regex parsing code.
+ */
+
+#include <faiss/index_factory.h>
+
+#include <map>
+
+#include <regex>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/random.h>
+
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexAdditiveQuantizerFastScan.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexHNSW.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/IndexIVFPQR.h>
+#include <faiss/IndexIVFRaBitQ.h>
+#include <faiss/IndexIVFSpectralHash.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexLattice.h>
+#include <faiss/IndexNSG.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexRaBitQ.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/IndexRowwiseMinMax.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/VectorTransform.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryHash.h>
+#include <faiss/IndexBinaryIVF.h>
+#include <string>
+
+namespace faiss {
+
+/***************************************************************
+ * index_factory
+ ***************************************************************/
+
+int index_factory_verbose = 0;
+
+namespace {
+
+/***************************************************************
+ * Small functions
+ */
+
+bool re_match(const std::string& s, const std::string& pat, std::smatch& sm) {
+ return std::regex_match(s, sm, std::regex(pat)); // NO-LINT : regex_match
+}
+
+// find first pair of matching parentheses
+void find_matching_parentheses(
+ const std::string& s,
+ int& i0,
+ int& i1,
+ int begin = 0) {
+ int st = 0;
+ i0 = i1 = 0;
+ for (int i = begin; i < s.length(); i++) {
+ if (s[i] == '(') {
+ if (st == 0) {
+ i0 = i;
+ }
+ st++;
+ }
+
+ if (s[i] == ')') {
+ st--;
+ if (st == 0) {
+ i1 = i;
+ return;
+ }
+ if (st < 0) {
+ FAISS_THROW_FMT(
+ "factory string %s: unbalanced parentheses", s.c_str());
+ }
+ }
+ }
+ FAISS_THROW_FMT(
+ "factory string %s: unbalanced parentheses st=%d", s.c_str(), st);
+}
+
+/// what kind of training does this coarse quantizer require?
+char get_trains_alone(const Index* coarse_quantizer) {
+ if (dynamic_cast<const IndexFlat*>(coarse_quantizer)) {
+ return 0;
+ }
+ // multi index just needs to be quantized
+ if (dynamic_cast<const MultiIndexQuantizer*>(coarse_quantizer) ||
+ dynamic_cast<const ResidualCoarseQuantizer*>(coarse_quantizer)) {
+ return 1;
+ }
+ if (dynamic_cast<const IndexHNSWFlat*>(coarse_quantizer)) {
+ return 2;
+ }
+ return 2; // for complicated indexes, we assume they can't be used as a
+ // kmeans index
+}
+
+// set the fields for factory-constructed IVF structures
+IndexIVF* fix_ivf_fields(IndexIVF* index_ivf) {
+ index_ivf->quantizer_trains_alone = get_trains_alone(index_ivf->quantizer);
+ index_ivf->cp.spherical = index_ivf->metric_type == METRIC_INNER_PRODUCT;
+ index_ivf->own_fields = true;
+ return index_ivf;
+}
+
+int mres_to_int(const std::ssub_match& mr, int deflt = -1, int begin = 0) {
+ if (mr.length() == 0) {
+ return deflt;
+ }
+ return std::stoi(mr.str().substr(begin));
+}
+
+std::map<std::string, ScalarQuantizer::QuantizerType> sq_types = {
+ {"SQ8", ScalarQuantizer::QT_8bit},
+ {"SQ4", ScalarQuantizer::QT_4bit},
+ {"SQ6", ScalarQuantizer::QT_6bit},
+ {"SQfp16", ScalarQuantizer::QT_fp16},
+ {"SQbf16", ScalarQuantizer::QT_bf16},
+ {"SQ8_direct_signed", ScalarQuantizer::QT_8bit_direct_signed},
+ {"SQ8_direct", ScalarQuantizer::QT_8bit_direct},
+};
+const std::string sq_pattern =
+ "(SQ4|SQ8|SQ6|SQfp16|SQbf16|SQ8_direct_signed|SQ8_direct)";
+
+std::map<std::string, AdditiveQuantizer::Search_type_t> aq_search_type = {
+ {"_Nfloat", AdditiveQuantizer::ST_norm_float},
+ {"_Nnone", AdditiveQuantizer::ST_LUT_nonorm},
+ {"_Nqint8", AdditiveQuantizer::ST_norm_qint8},
+ {"_Nqint4", AdditiveQuantizer::ST_norm_qint4},
+ {"_Ncqint8", AdditiveQuantizer::ST_norm_cqint8},
+ {"_Ncqint4", AdditiveQuantizer::ST_norm_cqint4},
+ {"_Nlsq2x4", AdditiveQuantizer::ST_norm_lsq2x4},
+ {"_Nrq2x4", AdditiveQuantizer::ST_norm_rq2x4},
+};
+
+const std::string aq_def_pattern = "[0-9]+x[0-9]+(_[0-9]+x[0-9]+)*";
+const std::string aq_norm_pattern =
+ "(|_Nnone|_Nfloat|_Nqint8|_Nqint4|_Ncqint8|_Ncqint4|_Nlsq2x4|_Nrq2x4)";
+
+const std::string paq_def_pattern = "([0-9]+)x([0-9]+)x([0-9]+)";
+
+AdditiveQuantizer::Search_type_t aq_parse_search_type(
+ const std::string& stok,
+ MetricType metric) {
+ if (stok == "") {
+ return metric == METRIC_L2 ? AdditiveQuantizer::ST_decompress
+ : AdditiveQuantizer::ST_LUT_nonorm;
+ }
+ int pos = stok.rfind("_");
+ return aq_search_type[stok.substr(pos)];
+}
+
+std::vector<size_t> aq_parse_nbits(std::string stok) {
+ std::vector<size_t> nbits;
+ std::smatch sm;
+ while (std::regex_search(
+ stok, sm, std::regex("[^q]([0-9]+)x([0-9]+)"))) { // NO-LINT
+ int M = std::stoi(sm[1].str());
+ int nbit = std::stoi(sm[2].str());
+ nbits.resize(nbits.size() + M, nbit);
+ stok = sm.suffix();
+ }
+ return nbits;
+}
+
+const std::string rabitq_pattern = "(RaBitQ)";
+
+/***************************************************************
+ * Parse VectorTransform
+ */
+
+VectorTransform* parse_VectorTransform(const std::string& description, int d) {
+ std::smatch sm;
+ auto match = [&sm, description](std::string pattern) {
+ return re_match(description, pattern, sm);
+ };
+ if (match("PCA(W?)(R?)([0-9]+)")) {
+ bool white = sm[1].length() > 0;
+ bool rot = sm[2].length() > 0;
+ return new PCAMatrix(d, std::stoi(sm[3].str()), white ? -0.5 : 0, rot);
+ }
+ if (match("L2[nN]orm")) {
+ return new NormalizationTransform(d, 2.0);
+ }
+ if (match("RR([0-9]+)?")) {
+ return new RandomRotationMatrix(d, mres_to_int(sm[1], d));
+ }
+ if (match("ITQ([0-9]+)?")) {
+ return new ITQTransform(d, mres_to_int(sm[1], d), sm[1].length() > 0);
+ }
+ if (match("OPQ([0-9]+)(_[0-9]+)?")) {
+ int M = std::stoi(sm[1].str());
+ int d_out = mres_to_int(sm[2], d, 1);
+ return new OPQMatrix(d, M, d_out);
+ }
+ if (match("Pad([0-9]+)")) {
+ int d_out = std::stoi(sm[1].str());
+ return new RemapDimensionsTransform(d, std::max(d_out, d), false);
+ }
+ return nullptr;
+}
+
+/***************************************************************
+ * Parse IndexIVF
+ */
+
+size_t parse_nlist(std::string s) {
+ size_t multiplier = 1;
+ if (s.back() == 'k') {
+ s.pop_back();
+ multiplier = 1024;
+ }
+ if (s.back() == 'M') {
+ s.pop_back();
+ multiplier = 1024 * 1024;
+ }
+ return std::stoi(s) * multiplier;
+}
+
+// parsing guard + function
+Index* parse_coarse_quantizer(
+ const std::string& description,
+ int d,
+ MetricType mt,
+ std::vector<std::unique_ptr<Index>>& parenthesis_indexes,
+ size_t& nlist,
+ bool& use_2layer) {
+ std::smatch sm;
+ auto match = [&sm, description](std::string pattern) {
+ return re_match(description, pattern, sm);
+ };
+ use_2layer = false;
+
+ if (match("IVF([0-9]+[kM]?)")) {
+ nlist = parse_nlist(sm[1].str());
+ return new IndexFlat(d, mt);
+ }
+ if (match("IMI2x([0-9]+)")) {
+ int nbit = std::stoi(sm[1].str());
+ FAISS_THROW_IF_NOT_MSG(
+ mt == METRIC_L2,
+ "MultiIndex not implemented for inner prod search");
+ nlist = (size_t)1 << (2 * nbit);
+ return new MultiIndexQuantizer(d, 2, nbit);
+ }
+ if (match("IVF([0-9]+[kM]?)_HNSW([0-9]*)")) {
+ nlist = parse_nlist(sm[1].str());
+ int hnsw_M = sm[2].length() > 0 ? std::stoi(sm[2]) : 32;
+ return new IndexHNSWFlat(d, hnsw_M, mt);
+ }
+ if (match("IVF([0-9]+[kM]?)_NSG([0-9]+)")) {
+ nlist = parse_nlist(sm[1].str());
+ int R = std::stoi(sm[2]);
+ return new IndexNSGFlat(d, R, mt);
+ }
+ if (match("IVF([0-9]+[kM]?)\\(Index([0-9])\\)")) {
+ nlist = parse_nlist(sm[1].str());
+ int no = std::stoi(sm[2].str());
+ FAISS_ASSERT(no >= 0 && no < parenthesis_indexes.size());
+ return parenthesis_indexes[no].release();
+ }
+
+ // these two generate Index2Layer's not IndexIVF's
+ if (match("Residual([0-9]+)x([0-9]+)")) {
+ FAISS_THROW_IF_NOT_MSG(
+ mt == METRIC_L2,
+ "MultiIndex not implemented for inner prod search");
+ int M = mres_to_int(sm[1]), nbit = mres_to_int(sm[2]);
+ nlist = (size_t)1 << (M * nbit);
+ use_2layer = true;
+ return new MultiIndexQuantizer(d, M, nbit);
+ }
+ if (match("Residual([0-9]+)")) {
+ FAISS_THROW_IF_NOT_MSG(
+ mt == METRIC_L2,
+ "Residual not implemented for inner prod search");
+ use_2layer = true;
+ nlist = mres_to_int(sm[1]);
+ return new IndexFlatL2(d);
+ }
+ return nullptr;
+}
+
+// parse the code description part of the IVF description
+
+IndexIVF* parse_IndexIVF(
+ const std::string& code_string,
+ std::unique_ptr<Index>& quantizer,
+ size_t nlist,
+ MetricType mt) {
+ std::smatch sm;
+ auto match = [&sm, &code_string](const std::string pattern) {
+ return re_match(code_string, pattern, sm);
+ };
+ auto get_q = [&quantizer] { return quantizer.release(); };
+ int d = quantizer->d;
+
+ if (match("Flat")) {
+ return new IndexIVFFlat(get_q(), d, nlist, mt);
+ }
+ if (match("FlatDedup")) {
+ return new IndexIVFFlatDedup(get_q(), d, nlist, mt);
+ }
+ if (match(sq_pattern)) {
+ return new IndexIVFScalarQuantizer(
+ get_q(), d, nlist, sq_types[sm[1].str()], mt);
+ }
+ if (match("PQ([0-9]+)(x[0-9]+)?(np)?")) {
+ int M = mres_to_int(sm[1]), nbit = mres_to_int(sm[2], 8, 1);
+ IndexIVFPQ* index_ivf = new IndexIVFPQ(get_q(), d, nlist, M, nbit, mt);
+ index_ivf->do_polysemous_training = sm[3].str() != "np";
+ return index_ivf;
+ }
+ if (match("PQ([0-9]+)\\+([0-9]+)")) {
+ FAISS_THROW_IF_NOT_MSG(
+ mt == METRIC_L2,
+ "IVFPQR not implemented for inner product search");
+ int M1 = mres_to_int(sm[1]), M2 = mres_to_int(sm[2]);
+ return new IndexIVFPQR(get_q(), d, nlist, M1, 8, M2, 8);
+ }
+ if (match("PQ([0-9]+)x4fs(r?)(_[0-9]+)?")) {
+ int M = mres_to_int(sm[1]);
+ int bbs = mres_to_int(sm[3], 32, 1);
+ IndexIVFPQFastScan* index_ivf =
+ new IndexIVFPQFastScan(get_q(), d, nlist, M, 4, mt, bbs);
+ index_ivf->by_residual = sm[2].str() == "r";
+ return index_ivf;
+ }
+ if (match("(RQ|LSQ)" + aq_def_pattern + aq_norm_pattern)) {
+ std::vector<size_t> nbits = aq_parse_nbits(sm.str());
+ AdditiveQuantizer::Search_type_t st =
+ aq_parse_search_type(sm[sm.size() - 1].str(), mt);
+ IndexIVF* index_ivf;
+ if (sm[1].str() == "RQ") {
+ index_ivf = new IndexIVFResidualQuantizer(
+ get_q(), d, nlist, nbits, mt, st);
+ } else {
+ FAISS_THROW_IF_NOT(nbits.size() > 0);
+ index_ivf = new IndexIVFLocalSearchQuantizer(
+ get_q(), d, nlist, nbits.size(), nbits[0], mt, st);
+ }
+ return index_ivf;
+ }
+ if (match("(PRQ|PLSQ)" + paq_def_pattern + aq_norm_pattern)) {
+ int nsplits = mres_to_int(sm[2]);
+ int Msub = mres_to_int(sm[3]);
+ int nbit = mres_to_int(sm[4]);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), mt);
+ IndexIVF* index_ivf;
+ if (sm[1].str() == "PRQ") {
+ index_ivf = new IndexIVFProductResidualQuantizer(
+ get_q(), d, nlist, nsplits, Msub, nbit, mt, st);
+ } else {
+ index_ivf = new IndexIVFProductLocalSearchQuantizer(
+ get_q(), d, nlist, nsplits, Msub, nbit, mt, st);
+ }
+ return index_ivf;
+ }
+ if (match("(RQ|LSQ)([0-9]+)x4fs(r?)(_[0-9]+)?" + aq_norm_pattern)) {
+ int M = std::stoi(sm[2].str());
+ int bbs = mres_to_int(sm[4], 32, 1);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), mt);
+ IndexIVFAdditiveQuantizerFastScan* index_ivf;
+ if (sm[1].str() == "RQ") {
+ index_ivf = new IndexIVFResidualQuantizerFastScan(
+ get_q(), d, nlist, M, 4, mt, st, bbs);
+ } else {
+ index_ivf = new IndexIVFLocalSearchQuantizerFastScan(
+ get_q(), d, nlist, M, 4, mt, st, bbs);
+ }
+ index_ivf->by_residual = (sm[3].str() == "r");
+ return index_ivf;
+ }
+ if (match("(PRQ|PLSQ)([0-9]+)x([0-9]+)x4fs(r?)(_[0-9]+)?" +
+ aq_norm_pattern)) {
+ int nsplits = std::stoi(sm[2].str());
+ int Msub = std::stoi(sm[3].str());
+ int bbs = mres_to_int(sm[5], 32, 1);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), mt);
+ IndexIVFAdditiveQuantizerFastScan* index_ivf;
+ if (sm[1].str() == "PRQ") {
+ index_ivf = new IndexIVFProductResidualQuantizerFastScan(
+ get_q(), d, nlist, nsplits, Msub, 4, mt, st, bbs);
+ } else {
+ index_ivf = new IndexIVFProductLocalSearchQuantizerFastScan(
+ get_q(), d, nlist, nsplits, Msub, 4, mt, st, bbs);
+ }
+ index_ivf->by_residual = (sm[4].str() == "r");
+ return index_ivf;
+ }
+ if (match("(ITQ|PCA|PCAR)([0-9]+)?,SH([-0-9.e]+)?([gcm])?")) {
+ int outdim = mres_to_int(sm[2], d); // is also the number of bits
+ std::unique_ptr<VectorTransform> vt;
+ if (sm[1] == "ITQ") {
+ vt.reset(new ITQTransform(d, outdim, d != outdim));
+ } else if (sm[1] == "PCA") {
+ vt.reset(new PCAMatrix(d, outdim));
+ } else if (sm[1] == "PCAR") {
+ vt.reset(new PCAMatrix(d, outdim, 0, true));
+ }
+ // the rationale for -1e10 is that this corresponds to simple
+ // thresholding
+ float period = sm[3].length() > 0 ? std::stof(sm[3]) : -1e10;
+ IndexIVFSpectralHash* index_ivf =
+ new IndexIVFSpectralHash(get_q(), d, nlist, outdim, period);
+ index_ivf->replace_vt(vt.release(), true);
+ if (sm[4].length()) {
+ std::string s = sm[4].str();
+ index_ivf->threshold_type = s == "g"
+ ? IndexIVFSpectralHash::Thresh_global
+ : s == "c"
+ ? IndexIVFSpectralHash::Thresh_centroid
+ :
+ /* s == "m" ? */ IndexIVFSpectralHash::Thresh_median;
+ }
+ return index_ivf;
+ }
+ if (match(rabitq_pattern)) {
+ return new IndexIVFRaBitQ(get_q(), d, nlist, mt);
+ }
+ return nullptr;
+}
+
+/***************************************************************
+ * Parse IndexHNSW
+ */
+
+IndexHNSW* parse_IndexHNSW(
+ const std::string code_string,
+ int d,
+ MetricType mt,
+ int hnsw_M) {
+ std::smatch sm;
+ auto match = [&sm, &code_string](const std::string& pattern) {
+ return re_match(code_string, pattern, sm);
+ };
+
+ if (match("Flat|")) {
+ return new IndexHNSWFlat(d, hnsw_M, mt);
+ }
+
+ if (match("PQ([0-9]+)(x[0-9]+)?(np)?")) {
+ int M = std::stoi(sm[1].str());
+ int nbit = mres_to_int(sm[2], 8, 1);
+ IndexHNSWPQ* ipq = new IndexHNSWPQ(d, M, hnsw_M, nbit);
+ dynamic_cast<IndexPQ*>(ipq->storage)->do_polysemous_training =
+ sm[3].str() != "np";
+ return ipq;
+ }
+ if (match(sq_pattern)) {
+ return new IndexHNSWSQ(d, sq_types[sm[1].str()], hnsw_M, mt);
+ }
+ if (match("([0-9]+)\\+PQ([0-9]+)?")) {
+ int ncent = mres_to_int(sm[1]);
+ int pq_m = mres_to_int(sm[2]);
+ IndexHNSW2Level* hidx2l =
+ new IndexHNSW2Level(new IndexFlatL2(d), ncent, pq_m, hnsw_M);
+ dynamic_cast<Index2Layer*>(hidx2l->storage)->q1.own_fields = true;
+ return hidx2l;
+ }
+ if (match("2x([0-9]+)\\+PQ([0-9]+)?")) {
+ int nbit = mres_to_int(sm[1]);
+ int pq_m = mres_to_int(sm[2]);
+ Index* quant = new MultiIndexQuantizer(d, 2, nbit);
+ IndexHNSW2Level* hidx2l = new IndexHNSW2Level(
+ quant, (size_t)1 << (2 * nbit), pq_m, hnsw_M);
+ Index2Layer* idx2l = dynamic_cast<Index2Layer*>(hidx2l->storage);
+ idx2l->q1.own_fields = true;
+ idx2l->q1.quantizer_trains_alone = 1;
+ return hidx2l;
+ }
+
+ return nullptr;
+}
+
+/***************************************************************
+ * Parse IndexNSG
+ */
+
+IndexNSG* parse_IndexNSG(
+ const std::string code_string,
+ int d,
+ MetricType mt,
+ int nsg_R) {
+ std::smatch sm;
+ auto match = [&sm, &code_string](const std::string& pattern) {
+ return re_match(code_string, pattern, sm);
+ };
+
+ if (match("Flat|")) {
+ return new IndexNSGFlat(d, nsg_R, mt);
+ }
+ if (match("PQ([0-9]+)(x[0-9]+)?(np)?")) {
+ int M = std::stoi(sm[1].str());
+ int nbit = mres_to_int(sm[2], 8, 1);
+ IndexNSGPQ* ipq = new IndexNSGPQ(d, M, nsg_R, nbit);
+ dynamic_cast<IndexPQ*>(ipq->storage)->do_polysemous_training =
+ sm[3].str() != "np";
+ return ipq;
+ }
+ if (match(sq_pattern)) {
+ return new IndexNSGSQ(d, sq_types[sm[1].str()], nsg_R, mt);
+ }
+
+ return nullptr;
+}
+
+/***************************************************************
+ * Parse basic indexes
+ */
+
+Index* parse_other_indexes(
+ const std::string& description,
+ int d,
+ MetricType metric) {
+ std::smatch sm;
+ auto match = [&sm, description](const std::string& pattern) {
+ return re_match(description, pattern, sm);
+ };
+
+ // IndexFlat
+ if (description == "Flat") {
+ return new IndexFlat(d, metric);
+ }
+
+ // IndexLSH
+ if (match("LSH([0-9]*)(r?)(t?)")) {
+ int nbits = sm[1].length() > 0 ? std::stoi(sm[1].str()) : d;
+ bool rotate_data = sm[2].length() > 0;
+ bool train_thresholds = sm[3].length() > 0;
+ FAISS_THROW_IF_NOT(metric == METRIC_L2);
+ return new IndexLSH(d, nbits, rotate_data, train_thresholds);
+ }
+
+ // IndexLattice
+ if (match("ZnLattice([0-9]+)x([0-9]+)_([0-9]+)")) {
+ int M = std::stoi(sm[1].str()), r2 = std::stoi(sm[2].str());
+ int nbit = std::stoi(sm[3].str());
+ return new IndexLattice(d, M, nbit, r2);
+ }
+
+ // IndexScalarQuantizer
+ if (match(sq_pattern)) {
+ return new IndexScalarQuantizer(d, sq_types[description], metric);
+ }
+
+ // IndexPQ
+ if (match("PQ([0-9]+)(x[0-9]+)?(np)?")) {
+ int M = std::stoi(sm[1].str());
+ int nbit = mres_to_int(sm[2], 8, 1);
+ IndexPQ* index_pq = new IndexPQ(d, M, nbit, metric);
+ index_pq->do_polysemous_training = sm[3].str() != "np";
+ return index_pq;
+ }
+
+ // IndexPQFastScan
+ if (match("PQ([0-9]+)x4fs(_[0-9]+)?")) {
+ int M = std::stoi(sm[1].str());
+ int bbs = mres_to_int(sm[2], 32, 1);
+ return new IndexPQFastScan(d, M, 4, metric, bbs);
+ }
+
+ // IndexResidualCoarseQuantizer and IndexResidualQuantizer
+ std::string pattern = "(RQ|RCQ)" + aq_def_pattern + aq_norm_pattern;
+ if (match(pattern)) {
+ std::vector<size_t> nbits = aq_parse_nbits(description);
+ if (sm[1].str() == "RCQ") {
+ return new ResidualCoarseQuantizer(d, nbits, metric);
+ }
+ AdditiveQuantizer::Search_type_t st =
+ aq_parse_search_type(sm[sm.size() - 1].str(), metric);
+ return new IndexResidualQuantizer(d, nbits, metric, st);
+ }
+
+ // LocalSearchCoarseQuantizer and IndexLocalSearchQuantizer
+ if (match("(LSQ|LSCQ)([0-9]+)x([0-9]+)" + aq_norm_pattern)) {
+ std::vector<size_t> nbits = aq_parse_nbits(description);
+ int M = mres_to_int(sm[2]);
+ int nbit = mres_to_int(sm[3]);
+ if (sm[1].str() == "LSCQ") {
+ return new LocalSearchCoarseQuantizer(d, M, nbit, metric);
+ }
+ AdditiveQuantizer::Search_type_t st =
+ aq_parse_search_type(sm[sm.size() - 1].str(), metric);
+ return new IndexLocalSearchQuantizer(d, M, nbit, metric, st);
+ }
+
+ // IndexProductResidualQuantizer
+ if (match("PRQ" + paq_def_pattern + aq_norm_pattern)) {
+ int nsplits = mres_to_int(sm[1]);
+ int Msub = mres_to_int(sm[2]);
+ int nbit = mres_to_int(sm[3]);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), metric);
+ return new IndexProductResidualQuantizer(
+ d, nsplits, Msub, nbit, metric, st);
+ }
+
+ // IndexProductLocalSearchQuantizer
+ if (match("PLSQ" + paq_def_pattern + aq_norm_pattern)) {
+ int nsplits = mres_to_int(sm[1]);
+ int Msub = mres_to_int(sm[2]);
+ int nbit = mres_to_int(sm[3]);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), metric);
+ return new IndexProductLocalSearchQuantizer(
+ d, nsplits, Msub, nbit, metric, st);
+ }
+
+ // IndexAdditiveQuantizerFastScan
+ // RQ{M}x4fs_{bbs}_{search_type}
+ pattern = "(LSQ|RQ)([0-9]+)x4fs(_[0-9]+)?" + aq_norm_pattern;
+ if (match(pattern)) {
+ int M = std::stoi(sm[2].str());
+ int bbs = mres_to_int(sm[3], 32, 1);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), metric);
+
+ if (sm[1].str() == "RQ") {
+ return new IndexResidualQuantizerFastScan(d, M, 4, metric, st, bbs);
+ } else if (sm[1].str() == "LSQ") {
+ return new IndexLocalSearchQuantizerFastScan(
+ d, M, 4, metric, st, bbs);
+ }
+ }
+
+ // IndexProductAdditiveQuantizerFastScan
+ // PRQ{nsplits}x{Msub}x4fs_{bbs}_{search_type}
+ pattern = "(PLSQ|PRQ)([0-9]+)x([0-9]+)x4fs(_[0-9]+)?" + aq_norm_pattern;
+ if (match(pattern)) {
+ int nsplits = std::stoi(sm[2].str());
+ int Msub = std::stoi(sm[3].str());
+ int bbs = mres_to_int(sm[4], 32, 1);
+ auto st = aq_parse_search_type(sm[sm.size() - 1].str(), metric);
+
+ if (sm[1].str() == "PRQ") {
+ return new IndexProductResidualQuantizerFastScan(
+ d, nsplits, Msub, 4, metric, st, bbs);
+ } else if (sm[1].str() == "PLSQ") {
+ return new IndexProductLocalSearchQuantizerFastScan(
+ d, nsplits, Msub, 4, metric, st, bbs);
+ }
+ }
+
+ // IndexRaBitQ
+ if (match(rabitq_pattern)) {
+ return new IndexRaBitQ(d, metric);
+ }
+
+ return nullptr;
+}
+
+/***************************************************************
+ * Driver function
+ */
+std::unique_ptr<Index> index_factory_sub(
+ int d,
+ std::string description,
+ MetricType metric) {
+ // handle composite indexes
+
+ bool verbose = index_factory_verbose;
+
+ if (verbose) {
+ printf("begin parse VectorTransforms: %s \n", description.c_str());
+ }
+
+ // for the current match
+ std::smatch sm;
+
+ // IndexIDMap -- it turns out is was used both as a prefix and a suffix, so
+ // support both
+ if (re_match(description, "(.+),IDMap2", sm) ||
+ re_match(description, "IDMap2,(.+)", sm)) {
+ IndexIDMap2* idmap2 = new IndexIDMap2(
+ index_factory_sub(d, sm[1].str(), metric).release());
+ idmap2->own_fields = true;
+ return std::unique_ptr<Index>(idmap2);
+ }
+
+ if (re_match(description, "(.+),IDMap", sm) ||
+ re_match(description, "IDMap,(.+)", sm)) {
+ IndexIDMap* idmap = new IndexIDMap(
+ index_factory_sub(d, sm[1].str(), metric).release());
+ idmap->own_fields = true;
+ return std::unique_ptr<Index>(idmap);
+ }
+
+ // handle refines
+ if (re_match(description, "(.+),RFlat", sm) ||
+ re_match(description, "(.+),Refine\\((.+)\\)", sm)) {
+ std::unique_ptr<Index> filter_index =
+ index_factory_sub(d, sm[1].str(), metric);
+
+ IndexRefine* index_rf = nullptr;
+ if (sm.size() == 3) { // Refine
+ std::unique_ptr<Index> refine_index =
+ index_factory_sub(d, sm[2].str(), metric);
+ index_rf = new IndexRefine(
+ filter_index.release(), refine_index.release());
+ index_rf->own_refine_index = true;
+ } else { // RFlat
+ index_rf = new IndexRefineFlat(filter_index.release(), nullptr);
+ }
+ FAISS_ASSERT(index_rf != nullptr);
+ index_rf->own_fields = true;
+ return std::unique_ptr<Index>(index_rf);
+ }
+
+ // IndexPreTransform
+ // should handle this first (even before parentheses) because it changes d
+ std::vector<std::unique_ptr<VectorTransform>> vts;
+ VectorTransform* vt = nullptr;
+ while (re_match(description, "([^,]+),(.*)", sm) &&
+ (vt = parse_VectorTransform(sm[1], d))) {
+ // reset loop
+ description = sm[sm.size() - 1];
+ vts.emplace_back(vt);
+ d = vts.back()->d_out;
+ }
+
+ if (vts.size() > 0) {
+ std::unique_ptr<Index> sub_index =
+ index_factory_sub(d, description, metric);
+ IndexPreTransform* index_pt = new IndexPreTransform(sub_index.get());
+ std::unique_ptr<Index> ret(index_pt);
+ index_pt->own_fields = true;
+ sub_index.release();
+ while (vts.size() > 0) {
+ if (verbose) {
+ printf("prepend trans %d -> %d\n",
+ vts.back()->d_in,
+ vts.back()->d_out);
+ }
+ index_pt->prepend_transform(vts.back().release());
+ vts.pop_back();
+ }
+ return ret;
+ }
+
+ // what we got from the parentheses
+ std::vector<std::unique_ptr<Index>> parenthesis_indexes;
+
+ int begin = 0;
+ while (description.find('(', begin) != std::string::npos) {
+ // replace indexes in () with Index0, Index1, etc.
+ int i0, i1;
+ find_matching_parentheses(description, i0, i1, begin);
+ std::string sub_description = description.substr(i0 + 1, i1 - i0 - 1);
+ int no = parenthesis_indexes.size();
+ parenthesis_indexes.push_back(
+ index_factory_sub(d, sub_description, metric));
+ description = description.substr(0, i0 + 1) + "Index" +
+ std::to_string(no) + description.substr(i1);
+ begin = i1 + 1;
+ }
+
+ if (verbose) {
+ printf("after () normalization: %s %zd parenthesis indexes d=%d\n",
+ description.c_str(),
+ parenthesis_indexes.size(),
+ d);
+ }
+
+ { // handle basic index types
+ Index* index = parse_other_indexes(description, d, metric);
+ if (index) {
+ return std::unique_ptr<Index>(index);
+ }
+ }
+
+ // HNSW variants (it was unclear in the old version that the separator was a
+ // "," so we support both "_" and ",")
+ if (re_match(description, "HNSW([0-9]*)([,_].*)?", sm)) {
+ int hnsw_M = mres_to_int(sm[1], 32);
+ // We also accept empty code string (synonym of Flat)
+ std::string code_string =
+ sm[2].length() > 0 ? sm[2].str().substr(1) : "";
+ if (verbose) {
+ printf("parsing HNSW string %s code_string=%s hnsw_M=%d\n",
+ description.c_str(),
+ code_string.c_str(),
+ hnsw_M);
+ }
+
+ IndexHNSW* index = parse_IndexHNSW(code_string, d, metric, hnsw_M);
+ FAISS_THROW_IF_NOT_FMT(
+ index,
+ "could not parse HNSW code description %s in %s",
+ code_string.c_str(),
+ description.c_str());
+ return std::unique_ptr<Index>(index);
+ }
+
+ // NSG variants (it was unclear in the old version that the separator was a
+ // "," so we support both "_" and ",")
+ if (re_match(description, "NSG([0-9]*)([,_].*)?", sm)) {
+ int nsg_R = mres_to_int(sm[1], 32);
+ // We also accept empty code string (synonym of Flat)
+ std::string code_string =
+ sm[2].length() > 0 ? sm[2].str().substr(1) : "";
+ if (verbose) {
+ printf("parsing NSG string %s code_string=%s nsg_R=%d\n",
+ description.c_str(),
+ code_string.c_str(),
+ nsg_R);
+ }
+
+ IndexNSG* index = parse_IndexNSG(code_string, d, metric, nsg_R);
+ FAISS_THROW_IF_NOT_FMT(
+ index,
+ "could not parse NSG code description %s in %s",
+ code_string.c_str(),
+ description.c_str());
+ return std::unique_ptr<Index>(index);
+ }
+
+ // IndexRowwiseMinMax, fp32 version
+ if (description.compare(0, 7, "MinMax,") == 0) {
+ size_t comma = description.find(",");
+ std::string sub_index_string = description.substr(comma + 1);
+ auto sub_index = index_factory_sub(d, sub_index_string, metric);
+
+ auto index = new IndexRowwiseMinMax(sub_index.release());
+ index->own_fields = true;
+
+ return std::unique_ptr<Index>(index);
+ }
+
+ // IndexRowwiseMinMax, fp16 version
+ if (description.compare(0, 11, "MinMaxFP16,") == 0) {
+ size_t comma = description.find(",");
+ std::string sub_index_string = description.substr(comma + 1);
+ auto sub_index = index_factory_sub(d, sub_index_string, metric);
+
+ auto index = new IndexRowwiseMinMaxFP16(sub_index.release());
+ index->own_fields = true;
+
+ return std::unique_ptr<Index>(index);
+ }
+
+ // IndexIVF
+ {
+ size_t nlist;
+ bool use_2layer;
+ size_t comma = description.find(",");
+ std::string coarse_string = description.substr(0, comma);
+ // Match coarse quantizer part first
+ std::unique_ptr<Index> quantizer(parse_coarse_quantizer(
+ description.substr(0, comma),
+ d,
+ metric,
+ parenthesis_indexes,
+ nlist,
+ use_2layer));
+
+ if (comma != std::string::npos && quantizer.get()) {
+ std::string code_description = description.substr(comma + 1);
+ if (use_2layer) {
+ bool ok =
+ re_match(code_description, "PQ([0-9]+)(x[0-9]+)?", sm);
+ FAISS_THROW_IF_NOT_FMT(
+ ok,
+ "could not parse 2 layer code description %s in %s",
+ code_description.c_str(),
+ description.c_str());
+ int M = std::stoi(sm[1].str()), nbit = mres_to_int(sm[2], 8, 1);
+ Index2Layer* index_2l =
+ new Index2Layer(quantizer.release(), nlist, M, nbit);
+ index_2l->q1.own_fields = true;
+ index_2l->q1.quantizer_trains_alone =
+ get_trains_alone(index_2l->q1.quantizer);
+ return std::unique_ptr<Index>(index_2l);
+ }
+
+ IndexIVF* index_ivf =
+ parse_IndexIVF(code_description, quantizer, nlist, metric);
+
+ FAISS_THROW_IF_NOT_FMT(
+ index_ivf,
+ "could not parse code description %s in %s",
+ code_description.c_str(),
+ description.c_str());
+ return std::unique_ptr<Index>(fix_ivf_fields(index_ivf));
+ }
+ }
+ FAISS_THROW_FMT("could not parse index string %s", description.c_str());
+ return nullptr;
+}
+
+} // anonymous namespace
+
+Index* index_factory(int d, const char* description, MetricType metric) {
+ return index_factory_sub(d, description, metric).release();
+}
+
+IndexBinary* index_binary_factory(int d, const char* description) {
+ IndexBinary* index = nullptr;
+
+ int ncentroids = -1;
+ int M, nhash, b;
+
+ if (sscanf(description, "BIVF%d_HNSW%d", &ncentroids, &M) == 2) {
+ IndexBinaryIVF* index_ivf =
+ new IndexBinaryIVF(new IndexBinaryHNSW(d, M), d, ncentroids);
+ index_ivf->own_fields = true;
+ index = index_ivf;
+
+ } else if (sscanf(description, "BIVF%d", &ncentroids) == 1) {
+ IndexBinaryIVF* index_ivf =
+ new IndexBinaryIVF(new IndexBinaryFlat(d), d, ncentroids);
+ index_ivf->own_fields = true;
+ index = index_ivf;
+
+ } else if (sscanf(description, "BHNSW%d", &M) == 1) {
+ IndexBinaryHNSW* index_hnsw = new IndexBinaryHNSW(d, M);
+ index = index_hnsw;
+
+ } else if (sscanf(description, "BHash%dx%d", &nhash, &b) == 2) {
+ index = new IndexBinaryMultiHash(d, nhash, b);
+
+ } else if (sscanf(description, "BHash%d", &b) == 1) {
+ index = new IndexBinaryHash(d, b);
+
+ } else if (std::string(description) == "BFlat") {
+ index = new IndexBinaryFlat(d);
+
+ } else {
+ FAISS_THROW_IF_NOT_FMT(
+ index, "description %s did not generate an index", description);
+ }
+
+ return index;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/index_factory.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/index_factory.h
new file mode 100644
index 0000000..5f92f13
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/index_factory.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/Index.h>
+#include <faiss/IndexBinary.h>
+
+namespace faiss {
+
+/** Build and index with the sequence of processing steps described in
+ * the string. */
+Index* index_factory(
+ int d,
+ const char* description,
+ MetricType metric = METRIC_L2);
+
+/// set to > 0 to get more logs from index_factory
+FAISS_API extern int index_factory_verbose;
+
+IndexBinary* index_binary_factory(int d, const char* description);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/index_io.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/index_io.h
new file mode 100644
index 0000000..be33cbb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/index_io.h
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// I/O code for indexes
+
+#ifndef FAISS_INDEX_IO_H
+#define FAISS_INDEX_IO_H
+
+#include <cstdio>
+#include <string>
+#include <typeinfo>
+#include <vector>
+
+/** I/O functions can read/write to a filename, a file handle or to an
+ * object that abstracts the medium.
+ *
+ * The read functions return objects that should be deallocated with
+ * delete. All references within these objectes are owned by the
+ * object.
+ */
+
+namespace faiss {
+
+struct Index;
+struct IndexBinary;
+struct VectorTransform;
+struct ProductQuantizer;
+struct IOReader;
+struct IOWriter;
+struct InvertedLists;
+
+/// skip the storage for graph-based indexes
+const int IO_FLAG_SKIP_STORAGE = 1;
+
+void write_index(const Index* idx, const char* fname, int io_flags = 0);
+void write_index(const Index* idx, FILE* f, int io_flags = 0);
+void write_index(const Index* idx, IOWriter* writer, int io_flags = 0);
+
+void write_index_binary(const IndexBinary* idx, const char* fname);
+void write_index_binary(const IndexBinary* idx, FILE* f);
+void write_index_binary(const IndexBinary* idx, IOWriter* writer);
+
+// The read_index flags are implemented only for a subset of index types.
+const int IO_FLAG_READ_ONLY = 2;
+// strip directory component from ondisk filename, and assume it's in
+// the same directory as the index file
+const int IO_FLAG_ONDISK_SAME_DIR = 4;
+// don't load IVF data to RAM, only list sizes
+const int IO_FLAG_SKIP_IVF_DATA = 8;
+// don't initialize precomputed table after loading
+const int IO_FLAG_SKIP_PRECOMPUTE_TABLE = 16;
+// don't compute the sdc table for PQ-based indices
+// this will prevent distances from being computed
+// between elements in the index. For indices like HNSWPQ,
+// this will prevent graph building because sdc
+// computations are required to construct the graph
+const int IO_FLAG_PQ_SKIP_SDC_TABLE = 32;
+// try to memmap data (useful to load an ArrayInvertedLists as an
+// OnDiskInvertedLists)
+const int IO_FLAG_MMAP = IO_FLAG_SKIP_IVF_DATA | 0x646f0000;
+// mmap that handles codes for IndexFlatCodes-derived indices and HNSW.
+// this is a temporary solution, it is expected to be merged with IO_FLAG_MMAP
+// after OnDiskInvertedLists get properly updated.
+const int IO_FLAG_MMAP_IFC = 1 << 9;
+
+struct HNSWIndexConfig {
+ bool is_compact;
+ bool is_skip_neighbors;
+ bool is_recompute;
+ float disk_cache_ratio = 0;
+ const char* external_storage_path;
+
+ HNSWIndexConfig(
+ bool is_compact,
+ bool is_skip_neighbors,
+ bool is_recompute,
+ float disk_cache_ratio,
+ const char* external_storage_path)
+ : is_compact(is_compact),
+ is_skip_neighbors(is_skip_neighbors),
+ is_recompute(is_recompute),
+ disk_cache_ratio(disk_cache_ratio),
+ external_storage_path(external_storage_path) {}
+
+ HNSWIndexConfig() = default;
+};
+
+Index* read_index(
+ const char* fname,
+ int io_flags = 0,
+ const HNSWIndexConfig& hnsw_config = HNSWIndexConfig());
+Index* read_index(
+ FILE* f,
+ int io_flags = 0,
+ const HNSWIndexConfig& hnsw_config = HNSWIndexConfig());
+Index* read_index(
+ IOReader* reader,
+ int io_flags = 0,
+ const HNSWIndexConfig& hnsw_config = HNSWIndexConfig());
+
+IndexBinary* read_index_binary(const char* fname, int io_flags = 0);
+IndexBinary* read_index_binary(FILE* f, int io_flags = 0);
+IndexBinary* read_index_binary(IOReader* reader, int io_flags = 0);
+
+void write_VectorTransform(const VectorTransform* vt, const char* fname);
+void write_VectorTransform(const VectorTransform* vt, IOWriter* f);
+
+VectorTransform* read_VectorTransform(const char* fname);
+VectorTransform* read_VectorTransform(IOReader* f);
+
+ProductQuantizer* read_ProductQuantizer(const char* fname);
+ProductQuantizer* read_ProductQuantizer(IOReader* reader);
+
+void write_ProductQuantizer(const ProductQuantizer* pq, const char* fname);
+void write_ProductQuantizer(const ProductQuantizer* pq, IOWriter* f);
+
+void write_InvertedLists(const InvertedLists* ils, IOWriter* f);
+InvertedLists* read_InvertedLists(IOReader* reader, int io_flags = 0);
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/BlockInvertedLists.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/BlockInvertedLists.cpp
new file mode 100644
index 0000000..4d100e2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/BlockInvertedLists.cpp
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/invlists/BlockInvertedLists.h>
+
+#include <faiss/impl/CodePacker.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+
+#include <faiss/impl/io.h>
+#include <faiss/impl/io_macros.h>
+
+namespace faiss {
+
+BlockInvertedLists::BlockInvertedLists(
+ size_t nlist,
+ size_t n_per_block,
+ size_t block_size)
+ : InvertedLists(nlist, InvertedLists::INVALID_CODE_SIZE),
+ n_per_block(n_per_block),
+ block_size(block_size) {
+ ids.resize(nlist);
+ codes.resize(nlist);
+}
+
+BlockInvertedLists::BlockInvertedLists(size_t nlist, const CodePacker* packer)
+ : InvertedLists(nlist, InvertedLists::INVALID_CODE_SIZE),
+ n_per_block(packer->nvec),
+ block_size(packer->block_size),
+ packer(packer) {
+ ids.resize(nlist);
+ codes.resize(nlist);
+}
+
+BlockInvertedLists::BlockInvertedLists()
+ : InvertedLists(0, InvertedLists::INVALID_CODE_SIZE) {}
+
+size_t BlockInvertedLists::add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids_in,
+ const uint8_t* code) {
+ if (n_entry == 0) {
+ return 0;
+ }
+ FAISS_THROW_IF_NOT(list_no < nlist);
+ size_t o = ids[list_no].size();
+ ids[list_no].resize(o + n_entry);
+ memcpy(&ids[list_no][o], ids_in, sizeof(ids_in[0]) * n_entry);
+ size_t n_block = (o + n_entry + n_per_block - 1) / n_per_block;
+ codes[list_no].resize(n_block * block_size);
+ if (o % block_size == 0) {
+ // copy whole blocks
+ memcpy(&codes[list_no][o * packer->code_size],
+ code,
+ n_block * block_size);
+ } else {
+ FAISS_THROW_IF_NOT_MSG(packer, "missing code packer");
+ std::vector<uint8_t> buffer(packer->code_size);
+ for (size_t i = 0; i < n_entry; i++) {
+ packer->unpack_1(code, i, buffer.data());
+ packer->pack_1(buffer.data(), i + o, codes[list_no].data());
+ }
+ }
+ return o;
+}
+
+size_t BlockInvertedLists::list_size(size_t list_no) const {
+ assert(list_no < nlist);
+ return ids[list_no].size();
+}
+
+const uint8_t* BlockInvertedLists::get_codes(size_t list_no) const {
+ assert(list_no < nlist);
+ return codes[list_no].get();
+}
+
+size_t BlockInvertedLists::remove_ids(const IDSelector& sel) {
+ idx_t nremove = 0;
+#pragma omp parallel for
+ for (idx_t i = 0; i < nlist; i++) {
+ std::vector<uint8_t> buffer(packer->code_size);
+ idx_t l = ids[i].size(), j = 0;
+ while (j < l) {
+ if (sel.is_member(ids[i][j])) {
+ l--;
+ ids[i][j] = ids[i][l];
+ packer->unpack_1(codes[i].data(), l, buffer.data());
+ packer->pack_1(buffer.data(), j, codes[i].data());
+ } else {
+ j++;
+ }
+ }
+ resize(i, l);
+ nremove += ids[i].size() - l;
+ }
+
+ return nremove;
+}
+
+const idx_t* BlockInvertedLists::get_ids(size_t list_no) const {
+ assert(list_no < nlist);
+ return ids[list_no].data();
+}
+
+void BlockInvertedLists::resize(size_t list_no, size_t new_size) {
+ ids[list_no].resize(new_size);
+ size_t prev_nbytes = codes[list_no].size();
+ size_t n_block = (new_size + n_per_block - 1) / n_per_block;
+ size_t new_nbytes = n_block * block_size;
+ codes[list_no].resize(new_nbytes);
+ if (prev_nbytes < new_nbytes) {
+ // set new elements to 0
+ memset(codes[list_no].data() + prev_nbytes,
+ 0,
+ new_nbytes - prev_nbytes);
+ }
+}
+
+void BlockInvertedLists::update_entries(
+ size_t,
+ size_t,
+ size_t,
+ const idx_t*,
+ const uint8_t*) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+BlockInvertedLists::~BlockInvertedLists() {
+ delete packer;
+}
+
+/**************************************************
+ * IO hook implementation
+ **************************************************/
+
+BlockInvertedListsIOHook::BlockInvertedListsIOHook()
+ : InvertedListsIOHook("ilbl", typeid(BlockInvertedLists).name()) {}
+
+void BlockInvertedListsIOHook::write(const InvertedLists* ils_in, IOWriter* f)
+ const {
+ uint32_t h = fourcc("ilbl");
+ WRITE1(h);
+ const BlockInvertedLists* il =
+ dynamic_cast<const BlockInvertedLists*>(ils_in);
+ WRITE1(il->nlist);
+ WRITE1(il->code_size);
+ WRITE1(il->n_per_block);
+ WRITE1(il->block_size);
+
+ for (size_t i = 0; i < il->nlist; i++) {
+ WRITEVECTOR(il->ids[i]);
+ WRITEVECTOR(il->codes[i]);
+ }
+}
+
+InvertedLists* BlockInvertedListsIOHook::read(IOReader* f, int /* io_flags */)
+ const {
+ BlockInvertedLists* il = new BlockInvertedLists();
+ READ1(il->nlist);
+ READ1(il->code_size);
+ READ1(il->n_per_block);
+ READ1(il->block_size);
+
+ il->ids.resize(il->nlist);
+ il->codes.resize(il->nlist);
+
+ for (size_t i = 0; i < il->nlist; i++) {
+ READVECTOR(il->ids[i]);
+ READVECTOR(il->codes[i]);
+ }
+
+ return il;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/BlockInvertedLists.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/BlockInvertedLists.h
new file mode 100644
index 0000000..7f608a8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/BlockInvertedLists.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/index_io.h>
+#include <faiss/invlists/InvertedLists.h>
+#include <faiss/invlists/InvertedListsIOHook.h>
+#include <faiss/utils/AlignedTable.h>
+
+namespace faiss {
+
+struct CodePacker;
+struct IDSelector;
+
+/** Inverted Lists that are organized by blocks.
+ *
+ * Different from the regular inverted lists, the codes are organized by blocks
+ * of size block_size bytes that reprsent a set of n_per_block. Therefore, code
+ * allocations are always rounded up to block_size bytes. The codes are also
+ * aligned on 32-byte boundaries for use with SIMD.
+ *
+ * To avoid misinterpretations, the code_size is set to (size_t)(-1), even if
+ * arguably the amount of memory consumed by code is block_size / n_per_block.
+ *
+ * The writing functions add_entries and update_entries operate on block-aligned
+ * data.
+ */
+struct BlockInvertedLists : InvertedLists {
+ size_t n_per_block = 0; // nb of vectors stored per block
+ size_t block_size = 0; // nb bytes per block
+
+ // required to interpret the content of the blocks (owned by this)
+ const CodePacker* packer = nullptr;
+
+ std::vector<AlignedTable<uint8_t>> codes;
+ std::vector<std::vector<idx_t>> ids;
+
+ BlockInvertedLists(size_t nlist, size_t vec_per_block, size_t block_size);
+ BlockInvertedLists(size_t nlist, const CodePacker* packer);
+
+ BlockInvertedLists();
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+ /// remove ids from the InvertedLists
+ size_t remove_ids(const IDSelector& sel);
+
+ // works only on empty BlockInvertedLists
+ // the codes should be of size ceil(n_entry / n_per_block) * block_size
+ // and padded with 0s
+ size_t add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ /// not implemented
+ void update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ // also pads new data with 0s
+ void resize(size_t list_no, size_t new_size) override;
+
+ ~BlockInvertedLists() override;
+};
+
+struct BlockInvertedListsIOHook : InvertedListsIOHook {
+ BlockInvertedListsIOHook();
+ void write(const InvertedLists* ils, IOWriter* f) const override;
+ InvertedLists* read(IOReader* f, int io_flags) const override;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/DirectMap.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/DirectMap.cpp
new file mode 100644
index 0000000..cc0fe30
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/DirectMap.cpp
@@ -0,0 +1,260 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/invlists/DirectMap.h>
+
+#include <cassert>
+#include <cstdio>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/invlists/BlockInvertedLists.h>
+
+namespace faiss {
+
+DirectMap::DirectMap() : type(NoMap) {}
+
+void DirectMap::set_type(
+ Type new_type,
+ const InvertedLists* invlists,
+ size_t ntotal) {
+ FAISS_THROW_IF_NOT(
+ new_type == NoMap || new_type == Array || new_type == Hashtable);
+
+ if (new_type == type) {
+ // nothing to do
+ return;
+ }
+
+ array.clear();
+ hashtable.clear();
+ type = new_type;
+
+ if (new_type == NoMap) {
+ return;
+ } else if (new_type == Array) {
+ array.resize(ntotal, -1);
+ } else if (new_type == Hashtable) {
+ hashtable.reserve(ntotal);
+ }
+
+ for (size_t key = 0; key < invlists->nlist; key++) {
+ size_t list_size = invlists->list_size(key);
+ InvertedLists::ScopedIds idlist(invlists, key);
+
+ if (new_type == Array) {
+ for (long ofs = 0; ofs < list_size; ofs++) {
+ FAISS_THROW_IF_NOT_MSG(
+ 0 <= idlist[ofs] && idlist[ofs] < ntotal,
+ "direct map supported only for seuquential ids");
+ array[idlist[ofs]] = lo_build(key, ofs);
+ }
+ } else if (new_type == Hashtable) {
+ for (long ofs = 0; ofs < list_size; ofs++) {
+ hashtable[idlist[ofs]] = lo_build(key, ofs);
+ }
+ }
+ }
+}
+
+void DirectMap::clear() {
+ array.clear();
+ hashtable.clear();
+}
+
+idx_t DirectMap::get(idx_t key) const {
+ if (type == Array) {
+ FAISS_THROW_IF_NOT_MSG(key >= 0 && key < array.size(), "invalid key");
+ idx_t lo = array[key];
+ FAISS_THROW_IF_NOT_MSG(lo >= 0, "-1 entry in direct_map");
+ return lo;
+ } else if (type == Hashtable) {
+ auto res = hashtable.find(key);
+ FAISS_THROW_IF_NOT_MSG(res != hashtable.end(), "key not found");
+ return res->second;
+ } else {
+ FAISS_THROW_MSG("direct map not initialized");
+ }
+}
+
+void DirectMap::add_single_id(idx_t id, idx_t list_no, size_t offset) {
+ if (type == NoMap)
+ return;
+
+ if (type == Array) {
+ assert(id == array.size());
+ if (list_no >= 0) {
+ array.push_back(lo_build(list_no, offset));
+ } else {
+ array.push_back(-1);
+ }
+ } else if (type == Hashtable) {
+ if (list_no >= 0) {
+ hashtable[id] = lo_build(list_no, offset);
+ }
+ }
+}
+
+void DirectMap::check_can_add(const idx_t* ids) {
+ if (type == Array && ids) {
+ FAISS_THROW_MSG("cannot have array direct map and add with ids");
+ }
+}
+
+/********************* DirectMapAdd implementation */
+
+DirectMapAdd::DirectMapAdd(DirectMap& direct_map, size_t n, const idx_t* xids)
+ : direct_map(direct_map), type(direct_map.type), n(n), xids(xids) {
+ if (type == DirectMap::Array) {
+ FAISS_THROW_IF_NOT(xids == nullptr);
+ ntotal = direct_map.array.size();
+ direct_map.array.resize(ntotal + n, -1);
+ } else if (type == DirectMap::Hashtable) {
+ // can't parallel update hashtable so use temp array
+ all_ofs.resize(n, -1);
+ }
+}
+
+void DirectMapAdd::add(size_t i, idx_t list_no, size_t ofs) {
+ if (type == DirectMap::Array) {
+ direct_map.array[ntotal + i] = lo_build(list_no, ofs);
+ } else if (type == DirectMap::Hashtable) {
+ all_ofs[i] = lo_build(list_no, ofs);
+ }
+}
+
+DirectMapAdd::~DirectMapAdd() {
+ if (type == DirectMap::Hashtable) {
+ for (int i = 0; i < n; i++) {
+ idx_t id = xids ? xids[i] : ntotal + i;
+ direct_map.hashtable[id] = all_ofs[i];
+ }
+ }
+}
+
+/********************************************************/
+
+using ScopedCodes = InvertedLists::ScopedCodes;
+using ScopedIds = InvertedLists::ScopedIds;
+
+size_t DirectMap::remove_ids(const IDSelector& sel, InvertedLists* invlists) {
+ size_t nlist = invlists->nlist;
+ std::vector<idx_t> toremove(nlist);
+
+ size_t nremove = 0;
+ BlockInvertedLists* block_invlists =
+ dynamic_cast<BlockInvertedLists*>(invlists);
+ if (type == NoMap) {
+ if (block_invlists != nullptr) {
+ return block_invlists->remove_ids(sel);
+ }
+ // exhaustive scan of IVF
+#pragma omp parallel for
+ for (idx_t i = 0; i < nlist; i++) {
+ idx_t l0 = invlists->list_size(i), l = l0, j = 0;
+ ScopedIds idsi(invlists, i);
+ while (j < l) {
+ if (sel.is_member(idsi[j])) {
+ l--;
+ invlists->update_entry(
+ i,
+ j,
+ invlists->get_single_id(i, l),
+ ScopedCodes(invlists, i, l).get());
+ } else {
+ j++;
+ }
+ }
+ toremove[i] = l0 - l;
+ }
+ // this will not run well in parallel on ondisk because of
+ // possible shrinks
+ for (idx_t i = 0; i < nlist; i++) {
+ if (toremove[i] > 0) {
+ nremove += toremove[i];
+ invlists->resize(i, invlists->list_size(i) - toremove[i]);
+ }
+ }
+ } else if (type == Hashtable) {
+ FAISS_THROW_IF_MSG(
+ block_invlists,
+ "remove with hashtable is not supported with BlockInvertedLists");
+ const IDSelectorArray* sela =
+ dynamic_cast<const IDSelectorArray*>(&sel);
+ FAISS_THROW_IF_NOT_MSG(
+ sela, "remove with hashtable works only with IDSelectorArray");
+
+ for (idx_t i = 0; i < sela->n; i++) {
+ idx_t id = sela->ids[i];
+ auto res = hashtable.find(id);
+ if (res != hashtable.end()) {
+ size_t list_no = lo_listno(res->second);
+ size_t offset = lo_offset(res->second);
+ idx_t last = invlists->list_size(list_no) - 1;
+ hashtable.erase(res);
+ if (offset < last) {
+ idx_t last_id = invlists->get_single_id(list_no, last);
+ invlists->update_entry(
+ list_no,
+ offset,
+ last_id,
+ ScopedCodes(invlists, list_no, last).get());
+ // update hash entry for last element
+ hashtable[last_id] = lo_build(list_no, offset);
+ }
+ invlists->resize(list_no, last);
+ nremove++;
+ }
+ }
+
+ } else {
+ FAISS_THROW_MSG("remove not supported with this direct_map format");
+ }
+ return nremove;
+}
+
+void DirectMap::update_codes(
+ InvertedLists* invlists,
+ int n,
+ const idx_t* ids,
+ const idx_t* assign,
+ const uint8_t* codes) {
+ FAISS_THROW_IF_NOT(type == Array);
+
+ size_t code_size = invlists->code_size;
+
+ for (size_t i = 0; i < n; i++) {
+ idx_t id = ids[i];
+ FAISS_THROW_IF_NOT_MSG(
+ 0 <= id && id < array.size(), "id to update out of range");
+ { // remove old one
+ idx_t dm = array[id];
+ int64_t ofs = lo_offset(dm);
+ int64_t il = lo_listno(dm);
+ size_t l = invlists->list_size(il);
+ if (ofs != l - 1) { // move l - 1 to ofs
+ int64_t id2 = invlists->get_single_id(il, l - 1);
+ array[id2] = lo_build(il, ofs);
+ invlists->update_entry(
+ il, ofs, id2, invlists->get_single_code(il, l - 1));
+ }
+ invlists->resize(il, l - 1);
+ }
+ { // insert new one
+ int64_t il = assign[i];
+ size_t l = invlists->list_size(il);
+ idx_t dm = lo_build(il, l);
+ array[id] = dm;
+ invlists->add_entry(il, id, codes + i * code_size);
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/DirectMap.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/DirectMap.h
new file mode 100644
index 0000000..08fc018
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/DirectMap.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_DIRECT_MAP_H
+#define FAISS_DIRECT_MAP_H
+
+#include <faiss/invlists/InvertedLists.h>
+#include <unordered_map>
+
+namespace faiss {
+
+struct IDSelector;
+
+// When offsets list id + offset are encoded in an uint64
+// we call this LO = list-offset
+
+inline uint64_t lo_build(uint64_t list_id, uint64_t offset) {
+ return list_id << 32 | offset;
+}
+
+inline uint64_t lo_listno(uint64_t lo) {
+ return lo >> 32;
+}
+
+inline uint64_t lo_offset(uint64_t lo) {
+ return lo & 0xffffffff;
+}
+
+/**
+ * Direct map: a way to map back from ids to inverted lists
+ */
+struct DirectMap {
+ enum Type {
+ NoMap = 0, // default
+ Array = 1, // sequential ids (only for add, no add_with_ids)
+ Hashtable = 2 // arbitrary ids
+ };
+ Type type;
+
+ /// map for direct access to the elements. Map ids to LO-encoded entries.
+ std::vector<idx_t> array;
+ std::unordered_map<idx_t, idx_t> hashtable;
+
+ DirectMap();
+
+ /// set type and initialize
+ void set_type(Type new_type, const InvertedLists* invlists, size_t ntotal);
+
+ /// get an entry
+ idx_t get(idx_t id) const;
+
+ /// for quick checks
+ bool no() const {
+ return type == NoMap;
+ }
+
+ /**
+ * update the direct_map
+ */
+
+ /// throw if Array and ids is not NULL
+ void check_can_add(const idx_t* ids);
+
+ /// non thread-safe version
+ void add_single_id(idx_t id, idx_t list_no, size_t offset);
+
+ /// remove all entries
+ void clear();
+
+ /**
+ * operations on inverted lists that require translation with a DirectMap
+ */
+
+ /// remove ids from the InvertedLists, possibly using the direct map
+ size_t remove_ids(const IDSelector& sel, InvertedLists* invlists);
+
+ /// update entries, using the direct map
+ void update_codes(
+ InvertedLists* invlists,
+ int n,
+ const idx_t* ids,
+ const idx_t* list_nos,
+ const uint8_t* codes);
+};
+
+/// Thread-safe way of updating the direct_map
+struct DirectMapAdd {
+ using Type = DirectMap::Type;
+
+ DirectMap& direct_map;
+ DirectMap::Type type;
+ size_t ntotal;
+ size_t n;
+ const idx_t* xids;
+
+ std::vector<idx_t> all_ofs;
+
+ DirectMapAdd(DirectMap& direct_map, size_t n, const idx_t* xids);
+
+ /// add vector i (with id xids[i]) at list_no and offset
+ void add(size_t i, idx_t list_no, size_t offset);
+
+ ~DirectMapAdd();
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedLists.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedLists.cpp
new file mode 100644
index 0000000..46b3c51
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedLists.cpp
@@ -0,0 +1,794 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/invlists/InvertedLists.h>
+
+#include <cstdio>
+#include <memory>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+InvertedListsIterator::~InvertedListsIterator() {}
+
+/*****************************************
+ * InvertedLists implementation
+ ******************************************/
+
+InvertedLists::InvertedLists(size_t nlist, size_t code_size)
+ : nlist(nlist), code_size(code_size) {}
+
+InvertedLists::~InvertedLists() {}
+
+idx_t InvertedLists::get_single_id(size_t list_no, size_t offset) const {
+ assert(offset < list_size(list_no));
+ const idx_t* ids = get_ids(list_no);
+ idx_t id = ids[offset];
+ release_ids(list_no, ids);
+ return id;
+}
+
+void InvertedLists::release_codes(size_t, const uint8_t*) const {}
+
+void InvertedLists::release_ids(size_t, const idx_t*) const {}
+
+void InvertedLists::prefetch_lists(const idx_t*, int) const {}
+
+const uint8_t* InvertedLists::get_single_code(size_t list_no, size_t offset)
+ const {
+ assert(offset < list_size(list_no));
+ return get_codes(list_no) + offset * code_size;
+}
+
+size_t InvertedLists::add_entry(
+ size_t list_no,
+ idx_t theid,
+ const uint8_t* code,
+ void* /*inverted_list_context*/) {
+ return add_entries(list_no, 1, &theid, code);
+}
+
+void InvertedLists::update_entry(
+ size_t list_no,
+ size_t offset,
+ idx_t id,
+ const uint8_t* code) {
+ update_entries(list_no, offset, 1, &id, code);
+}
+
+void InvertedLists::reset() {
+ for (size_t i = 0; i < nlist; i++) {
+ resize(i, 0);
+ }
+}
+
+void InvertedLists::merge_from(InvertedLists* oivf, size_t add_id) {
+#pragma omp parallel for
+ for (idx_t i = 0; i < nlist; i++) {
+ size_t list_size = oivf->list_size(i);
+ ScopedIds ids(oivf, i);
+ if (add_id == 0) {
+ add_entries(i, list_size, ids.get(), ScopedCodes(oivf, i).get());
+ } else {
+ std::vector<idx_t> new_ids(list_size);
+
+ for (size_t j = 0; j < list_size; j++) {
+ new_ids[j] = ids[j] + add_id;
+ }
+ add_entries(
+ i, list_size, new_ids.data(), ScopedCodes(oivf, i).get());
+ }
+ oivf->resize(i, 0);
+ }
+}
+
+size_t InvertedLists::copy_subset_to(
+ InvertedLists& oivf,
+ subset_type_t subset_type,
+ idx_t a1,
+ idx_t a2) const {
+ FAISS_THROW_IF_NOT(nlist == oivf.nlist);
+ FAISS_THROW_IF_NOT(code_size == oivf.code_size);
+ FAISS_THROW_IF_NOT_FMT(
+ subset_type >= 0 && subset_type <= 4,
+ "subset type %d not implemented",
+ subset_type);
+ size_t accu_n = 0;
+ size_t accu_a1 = 0;
+ size_t accu_a2 = 0;
+ size_t n_added = 0;
+
+ size_t ntotal = 0;
+ if (subset_type == 2) {
+ ntotal = compute_ntotal();
+ }
+
+ for (idx_t list_no = 0; list_no < nlist; list_no++) {
+ size_t n = list_size(list_no);
+ ScopedIds ids_in(this, list_no);
+
+ if (subset_type == SUBSET_TYPE_ID_RANGE) {
+ for (idx_t i = 0; i < n; i++) {
+ idx_t id = ids_in[i];
+ if (a1 <= id && id < a2) {
+ oivf.add_entry(
+ list_no,
+ get_single_id(list_no, i),
+ ScopedCodes(this, list_no, i).get());
+ n_added++;
+ }
+ }
+ } else if (subset_type == SUBSET_TYPE_ID_MOD) {
+ for (idx_t i = 0; i < n; i++) {
+ idx_t id = ids_in[i];
+ if (id % a1 == a2) {
+ oivf.add_entry(
+ list_no,
+ get_single_id(list_no, i),
+ ScopedCodes(this, list_no, i).get());
+ n_added++;
+ }
+ }
+ } else if (subset_type == SUBSET_TYPE_ELEMENT_RANGE) {
+ // see what is allocated to a1 and to a2
+ size_t next_accu_n = accu_n + n;
+ size_t next_accu_a1 = next_accu_n * a1 / ntotal;
+ size_t i1 = next_accu_a1 - accu_a1;
+ size_t next_accu_a2 = next_accu_n * a2 / ntotal;
+ size_t i2 = next_accu_a2 - accu_a2;
+
+ for (idx_t i = i1; i < i2; i++) {
+ oivf.add_entry(
+ list_no,
+ get_single_id(list_no, i),
+ ScopedCodes(this, list_no, i).get());
+ }
+
+ n_added += i2 - i1;
+ accu_a1 = next_accu_a1;
+ accu_a2 = next_accu_a2;
+ } else if (subset_type == SUBSET_TYPE_INVLIST_FRACTION) {
+ size_t i1 = n * a2 / a1;
+ size_t i2 = n * (a2 + 1) / a1;
+
+ for (idx_t i = i1; i < i2; i++) {
+ oivf.add_entry(
+ list_no,
+ get_single_id(list_no, i),
+ ScopedCodes(this, list_no, i).get());
+ }
+
+ n_added += i2 - i1;
+ } else if (subset_type == SUBSET_TYPE_INVLIST) {
+ if (list_no >= a1 && list_no < a2) {
+ oivf.add_entries(
+ list_no,
+ n,
+ ScopedIds(this, list_no).get(),
+ ScopedCodes(this, list_no).get());
+ n_added += n;
+ }
+ }
+ accu_n += n;
+ }
+ return n_added;
+}
+
+double InvertedLists::imbalance_factor() const {
+ std::vector<int64_t> hist(nlist);
+
+ for (size_t i = 0; i < nlist; i++) {
+ hist[i] = list_size(i);
+ }
+
+ return faiss::imbalance_factor(nlist, hist.data());
+}
+
+void InvertedLists::print_stats() const {
+ std::vector<int> sizes(40);
+ for (size_t i = 0; i < nlist; i++) {
+ for (size_t j = 0; j < sizes.size(); j++) {
+ if ((list_size(i) >> j) == 0) {
+ sizes[j]++;
+ break;
+ }
+ }
+ }
+ for (size_t i = 0; i < sizes.size(); i++) {
+ if (sizes[i]) {
+ printf("list size in < %zu: %d instances\n",
+ static_cast<size_t>(1) << i,
+ sizes[i]);
+ }
+ }
+}
+
+size_t InvertedLists::compute_ntotal() const {
+ size_t tot = 0;
+ for (size_t i = 0; i < nlist; i++) {
+ tot += list_size(i);
+ }
+ return tot;
+}
+
+bool InvertedLists::is_empty(size_t list_no, void* inverted_list_context)
+ const {
+ if (use_iterator) {
+ return !std::unique_ptr<InvertedListsIterator>(
+ get_iterator(list_no, inverted_list_context))
+ ->is_available();
+ } else {
+ FAISS_THROW_IF_NOT(inverted_list_context == nullptr);
+ return list_size(list_no) == 0;
+ }
+}
+
+// implemnent iterator on top of get_codes / get_ids
+namespace {
+
+struct CodeArrayIterator : InvertedListsIterator {
+ size_t list_size;
+ size_t code_size;
+ InvertedLists::ScopedCodes codes;
+ InvertedLists::ScopedIds ids;
+ size_t idx = 0;
+
+ CodeArrayIterator(const InvertedLists* il, size_t list_no)
+ : list_size(il->list_size(list_no)),
+ code_size(il->code_size),
+ codes(il, list_no),
+ ids(il, list_no) {}
+
+ bool is_available() const override {
+ return idx < list_size;
+ }
+ void next() override {
+ idx++;
+ }
+ std::pair<idx_t, const uint8_t*> get_id_and_codes() override {
+ return {ids[idx], codes.get() + code_size * idx};
+ }
+};
+
+} // namespace
+
+InvertedListsIterator* InvertedLists::get_iterator(
+ size_t list_no,
+ void* inverted_list_context) const {
+ FAISS_THROW_IF_NOT(inverted_list_context == nullptr);
+ return new CodeArrayIterator(this, list_no);
+}
+
+/*****************************************
+ * ArrayInvertedLists implementation
+ ******************************************/
+
+ArrayInvertedLists::ArrayInvertedLists(size_t nlist, size_t code_size)
+ : InvertedLists(nlist, code_size) {
+ ids.resize(nlist);
+ codes.resize(nlist);
+}
+
+size_t ArrayInvertedLists::add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids_in,
+ const uint8_t* code) {
+ if (n_entry == 0)
+ return 0;
+ assert(list_no < nlist);
+ size_t o = ids[list_no].size();
+ ids[list_no].resize(o + n_entry);
+ memcpy(&ids[list_no][o], ids_in, sizeof(ids_in[0]) * n_entry);
+ codes[list_no].resize((o + n_entry) * code_size);
+ memcpy(&codes[list_no][o * code_size], code, code_size * n_entry);
+ return o;
+}
+
+size_t ArrayInvertedLists::list_size(size_t list_no) const {
+ assert(list_no < nlist);
+ return ids[list_no].size();
+}
+
+bool ArrayInvertedLists::is_empty(size_t list_no, void* inverted_list_context)
+ const {
+ FAISS_THROW_IF_NOT(inverted_list_context == nullptr);
+ return ids[list_no].size() == 0;
+}
+
+const uint8_t* ArrayInvertedLists::get_codes(size_t list_no) const {
+ assert(list_no < nlist);
+ return codes[list_no].data();
+}
+
+const idx_t* ArrayInvertedLists::get_ids(size_t list_no) const {
+ assert(list_no < nlist);
+ return ids[list_no].data();
+}
+
+void ArrayInvertedLists::resize(size_t list_no, size_t new_size) {
+ ids[list_no].resize(new_size);
+ codes[list_no].resize(new_size * code_size);
+}
+
+void ArrayInvertedLists::update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids_in,
+ const uint8_t* codes_in) {
+ assert(list_no < nlist);
+ assert(n_entry + offset <= ids[list_no].size());
+ memcpy(&ids[list_no][offset], ids_in, sizeof(ids_in[0]) * n_entry);
+ memcpy(&codes[list_no][offset * code_size], codes_in, code_size * n_entry);
+}
+
+void ArrayInvertedLists::permute_invlists(const idx_t* map) {
+ std::vector<MaybeOwnedVector<uint8_t>> new_codes(nlist);
+ std::vector<MaybeOwnedVector<idx_t>> new_ids(nlist);
+
+ for (size_t i = 0; i < nlist; i++) {
+ size_t o = map[i];
+ FAISS_THROW_IF_NOT(o < nlist);
+ std::swap(new_codes[i], codes[o]);
+ std::swap(new_ids[i], ids[o]);
+ }
+ std::swap(codes, new_codes);
+ std::swap(ids, new_ids);
+}
+
+ArrayInvertedLists::~ArrayInvertedLists() {}
+
+/*****************************************************************
+ * Meta-inverted list implementations
+ *****************************************************************/
+
+size_t ReadOnlyInvertedLists::add_entries(
+ size_t,
+ size_t,
+ const idx_t*,
+ const uint8_t*) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void ReadOnlyInvertedLists::update_entries(
+ size_t,
+ size_t,
+ size_t,
+ const idx_t*,
+ const uint8_t*) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+void ReadOnlyInvertedLists::resize(size_t, size_t) {
+ FAISS_THROW_MSG("not implemented");
+}
+
+/*****************************************
+ * HStackInvertedLists implementation
+ ******************************************/
+
+HStackInvertedLists::HStackInvertedLists(int nil, const InvertedLists** ils_in)
+ : ReadOnlyInvertedLists(
+ nil > 0 ? ils_in[0]->nlist : 0,
+ nil > 0 ? ils_in[0]->code_size : 0) {
+ FAISS_THROW_IF_NOT(nil > 0);
+ for (int i = 0; i < nil; i++) {
+ ils.push_back(ils_in[i]);
+ FAISS_THROW_IF_NOT(
+ ils_in[i]->code_size == code_size && ils_in[i]->nlist == nlist);
+ }
+}
+
+size_t HStackInvertedLists::list_size(size_t list_no) const {
+ size_t sz = 0;
+ for (int i = 0; i < ils.size(); i++) {
+ const InvertedLists* il = ils[i];
+ sz += il->list_size(list_no);
+ }
+ return sz;
+}
+
+const uint8_t* HStackInvertedLists::get_codes(size_t list_no) const {
+ uint8_t *codes = new uint8_t[code_size * list_size(list_no)], *c = codes;
+
+ for (int i = 0; i < ils.size(); i++) {
+ const InvertedLists* il = ils[i];
+ size_t sz = il->list_size(list_no) * code_size;
+ if (sz > 0) {
+ memcpy(c, ScopedCodes(il, list_no).get(), sz);
+ c += sz;
+ }
+ }
+ return codes;
+}
+
+const uint8_t* HStackInvertedLists::get_single_code(
+ size_t list_no,
+ size_t offset) const {
+ for (int i = 0; i < ils.size(); i++) {
+ const InvertedLists* il = ils[i];
+ size_t sz = il->list_size(list_no);
+ if (offset < sz) {
+ // here we have to copy the code, otherwise it will crash at dealloc
+ uint8_t* code = new uint8_t[code_size];
+ memcpy(code, ScopedCodes(il, list_no, offset).get(), code_size);
+ return code;
+ }
+ offset -= sz;
+ }
+ FAISS_THROW_FMT("offset %zd unknown", offset);
+}
+
+void HStackInvertedLists::release_codes(size_t, const uint8_t* codes) const {
+ delete[] codes;
+}
+
+const idx_t* HStackInvertedLists::get_ids(size_t list_no) const {
+ idx_t *ids = new idx_t[list_size(list_no)], *c = ids;
+
+ for (int i = 0; i < ils.size(); i++) {
+ const InvertedLists* il = ils[i];
+ size_t sz = il->list_size(list_no);
+ if (sz > 0) {
+ memcpy(c, ScopedIds(il, list_no).get(), sz * sizeof(idx_t));
+ c += sz;
+ }
+ }
+ return ids;
+}
+
+idx_t HStackInvertedLists::get_single_id(size_t list_no, size_t offset) const {
+ for (int i = 0; i < ils.size(); i++) {
+ const InvertedLists* il = ils[i];
+ size_t sz = il->list_size(list_no);
+ if (offset < sz) {
+ return il->get_single_id(list_no, offset);
+ }
+ offset -= sz;
+ }
+ FAISS_THROW_FMT("offset %zd unknown", offset);
+}
+
+void HStackInvertedLists::release_ids(size_t, const idx_t* ids) const {
+ delete[] ids;
+}
+
+void HStackInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist)
+ const {
+ for (int i = 0; i < ils.size(); i++) {
+ const InvertedLists* il = ils[i];
+ il->prefetch_lists(list_nos, nlist);
+ }
+}
+
+/*****************************************
+ * SliceInvertedLists implementation
+ ******************************************/
+
+namespace {
+
+idx_t translate_list_no(const SliceInvertedLists* sil, idx_t list_no) {
+ FAISS_THROW_IF_NOT(list_no >= 0 && list_no < sil->nlist);
+ return list_no + sil->i0;
+}
+
+} // namespace
+
+SliceInvertedLists::SliceInvertedLists(
+ const InvertedLists* il,
+ idx_t i0,
+ idx_t i1)
+ : ReadOnlyInvertedLists(i1 - i0, il->code_size),
+ il(il),
+ i0(i0),
+ i1(i1) {}
+
+size_t SliceInvertedLists::list_size(size_t list_no) const {
+ return il->list_size(translate_list_no(this, list_no));
+}
+
+const uint8_t* SliceInvertedLists::get_codes(size_t list_no) const {
+ return il->get_codes(translate_list_no(this, list_no));
+}
+
+const uint8_t* SliceInvertedLists::get_single_code(
+ size_t list_no,
+ size_t offset) const {
+ return il->get_single_code(translate_list_no(this, list_no), offset);
+}
+
+void SliceInvertedLists::release_codes(size_t list_no, const uint8_t* codes)
+ const {
+ return il->release_codes(translate_list_no(this, list_no), codes);
+}
+
+const idx_t* SliceInvertedLists::get_ids(size_t list_no) const {
+ return il->get_ids(translate_list_no(this, list_no));
+}
+
+idx_t SliceInvertedLists::get_single_id(size_t list_no, size_t offset) const {
+ return il->get_single_id(translate_list_no(this, list_no), offset);
+}
+
+void SliceInvertedLists::release_ids(size_t list_no, const idx_t* ids) const {
+ return il->release_ids(translate_list_no(this, list_no), ids);
+}
+
+void SliceInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist)
+ const {
+ std::vector<idx_t> translated_list_nos;
+ for (int j = 0; j < nlist; j++) {
+ idx_t list_no = list_nos[j];
+ if (list_no < 0)
+ continue;
+ translated_list_nos.push_back(translate_list_no(this, list_no));
+ }
+ il->prefetch_lists(translated_list_nos.data(), translated_list_nos.size());
+}
+
+/*****************************************
+ * VStackInvertedLists implementation
+ ******************************************/
+
+namespace {
+
+// find the invlist this number belongs to
+int translate_list_no(const VStackInvertedLists* vil, idx_t list_no) {
+ FAISS_THROW_IF_NOT(list_no >= 0 && list_no < vil->nlist);
+ int i0 = 0, i1 = vil->ils.size();
+ const idx_t* cumsz = vil->cumsz.data();
+ while (i0 + 1 < i1) {
+ int imed = (i0 + i1) / 2;
+ if (list_no >= cumsz[imed]) {
+ i0 = imed;
+ } else {
+ i1 = imed;
+ }
+ }
+ assert(list_no >= cumsz[i0] && list_no < cumsz[i0 + 1]);
+ return i0;
+}
+
+idx_t sum_il_sizes(int nil, const InvertedLists** ils_in) {
+ idx_t tot = 0;
+ for (int i = 0; i < nil; i++) {
+ tot += ils_in[i]->nlist;
+ }
+ return tot;
+}
+
+} // namespace
+
+VStackInvertedLists::VStackInvertedLists(int nil, const InvertedLists** ils_in)
+ : ReadOnlyInvertedLists(
+ sum_il_sizes(nil, ils_in),
+ nil > 0 ? ils_in[0]->code_size : 0) {
+ FAISS_THROW_IF_NOT(nil > 0);
+ cumsz.resize(nil + 1);
+ for (int i = 0; i < nil; i++) {
+ ils.push_back(ils_in[i]);
+ FAISS_THROW_IF_NOT(ils_in[i]->code_size == code_size);
+ cumsz[i + 1] = cumsz[i] + ils_in[i]->nlist;
+ }
+}
+
+size_t VStackInvertedLists::list_size(size_t list_no) const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->list_size(list_no);
+}
+
+const uint8_t* VStackInvertedLists::get_codes(size_t list_no) const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->get_codes(list_no);
+}
+
+const uint8_t* VStackInvertedLists::get_single_code(
+ size_t list_no,
+ size_t offset) const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->get_single_code(list_no, offset);
+}
+
+void VStackInvertedLists::release_codes(size_t list_no, const uint8_t* codes)
+ const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->release_codes(list_no, codes);
+}
+
+const idx_t* VStackInvertedLists::get_ids(size_t list_no) const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->get_ids(list_no);
+}
+
+idx_t VStackInvertedLists::get_single_id(size_t list_no, size_t offset) const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->get_single_id(list_no, offset);
+}
+
+void VStackInvertedLists::release_ids(size_t list_no, const idx_t* ids) const {
+ int i = translate_list_no(this, list_no);
+ list_no -= cumsz[i];
+ return ils[i]->release_ids(list_no, ids);
+}
+
+void VStackInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist)
+ const {
+ std::vector<int> ilno(nlist, -1);
+ std::vector<int> n_per_il(ils.size(), 0);
+ for (int j = 0; j < nlist; j++) {
+ idx_t list_no = list_nos[j];
+ if (list_no < 0)
+ continue;
+ int i = ilno[j] = translate_list_no(this, list_no);
+ n_per_il[i]++;
+ }
+ std::vector<int> cum_n_per_il(ils.size() + 1, 0);
+ for (int j = 0; j < ils.size(); j++) {
+ cum_n_per_il[j + 1] = cum_n_per_il[j] + n_per_il[j];
+ }
+ std::vector<idx_t> sorted_list_nos(cum_n_per_il.back());
+ for (int j = 0; j < nlist; j++) {
+ idx_t list_no = list_nos[j];
+ if (list_no < 0)
+ continue;
+ int i = ilno[j];
+ list_no -= cumsz[i];
+ sorted_list_nos[cum_n_per_il[i]++] = list_no;
+ }
+
+ int i0 = 0;
+ for (int j = 0; j < ils.size(); j++) {
+ int i1 = i0 + n_per_il[j];
+ if (i1 > i0) {
+ ils[j]->prefetch_lists(sorted_list_nos.data() + i0, i1 - i0);
+ }
+ i0 = i1;
+ }
+}
+
+/*****************************************
+ * MaskedInvertedLists implementation
+ ******************************************/
+
+MaskedInvertedLists::MaskedInvertedLists(
+ const InvertedLists* il0,
+ const InvertedLists* il1)
+ : ReadOnlyInvertedLists(il0->nlist, il0->code_size),
+ il0(il0),
+ il1(il1) {
+ FAISS_THROW_IF_NOT(il1->nlist == nlist);
+ FAISS_THROW_IF_NOT(il1->code_size == code_size);
+}
+
+size_t MaskedInvertedLists::list_size(size_t list_no) const {
+ size_t sz = il0->list_size(list_no);
+ return sz ? sz : il1->list_size(list_no);
+}
+
+const uint8_t* MaskedInvertedLists::get_codes(size_t list_no) const {
+ size_t sz = il0->list_size(list_no);
+ return (sz ? il0 : il1)->get_codes(list_no);
+}
+
+const idx_t* MaskedInvertedLists::get_ids(size_t list_no) const {
+ size_t sz = il0->list_size(list_no);
+ return (sz ? il0 : il1)->get_ids(list_no);
+}
+
+void MaskedInvertedLists::release_codes(size_t list_no, const uint8_t* codes)
+ const {
+ size_t sz = il0->list_size(list_no);
+ (sz ? il0 : il1)->release_codes(list_no, codes);
+}
+
+void MaskedInvertedLists::release_ids(size_t list_no, const idx_t* ids) const {
+ size_t sz = il0->list_size(list_no);
+ (sz ? il0 : il1)->release_ids(list_no, ids);
+}
+
+idx_t MaskedInvertedLists::get_single_id(size_t list_no, size_t offset) const {
+ size_t sz = il0->list_size(list_no);
+ return (sz ? il0 : il1)->get_single_id(list_no, offset);
+}
+
+const uint8_t* MaskedInvertedLists::get_single_code(
+ size_t list_no,
+ size_t offset) const {
+ size_t sz = il0->list_size(list_no);
+ return (sz ? il0 : il1)->get_single_code(list_no, offset);
+}
+
+void MaskedInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist)
+ const {
+ std::vector<idx_t> list0, list1;
+ for (int i = 0; i < nlist; i++) {
+ idx_t list_no = list_nos[i];
+ if (list_no < 0)
+ continue;
+ size_t sz = il0->list_size(list_no);
+ (sz ? list0 : list1).push_back(list_no);
+ }
+ il0->prefetch_lists(list0.data(), list0.size());
+ il1->prefetch_lists(list1.data(), list1.size());
+}
+
+/*****************************************
+ * MaskedInvertedLists implementation
+ ******************************************/
+
+StopWordsInvertedLists::StopWordsInvertedLists(
+ const InvertedLists* il0,
+ size_t maxsize)
+ : ReadOnlyInvertedLists(il0->nlist, il0->code_size),
+ il0(il0),
+ maxsize(maxsize) {}
+
+size_t StopWordsInvertedLists::list_size(size_t list_no) const {
+ size_t sz = il0->list_size(list_no);
+ return sz < maxsize ? sz : 0;
+}
+
+const uint8_t* StopWordsInvertedLists::get_codes(size_t list_no) const {
+ return il0->list_size(list_no) < maxsize ? il0->get_codes(list_no)
+ : nullptr;
+}
+
+const idx_t* StopWordsInvertedLists::get_ids(size_t list_no) const {
+ return il0->list_size(list_no) < maxsize ? il0->get_ids(list_no) : nullptr;
+}
+
+void StopWordsInvertedLists::release_codes(size_t list_no, const uint8_t* codes)
+ const {
+ if (il0->list_size(list_no) < maxsize) {
+ il0->release_codes(list_no, codes);
+ }
+}
+
+void StopWordsInvertedLists::release_ids(size_t list_no, const idx_t* ids)
+ const {
+ if (il0->list_size(list_no) < maxsize) {
+ il0->release_ids(list_no, ids);
+ }
+}
+
+idx_t StopWordsInvertedLists::get_single_id(size_t list_no, size_t offset)
+ const {
+ FAISS_THROW_IF_NOT(il0->list_size(list_no) < maxsize);
+ return il0->get_single_id(list_no, offset);
+}
+
+const uint8_t* StopWordsInvertedLists::get_single_code(
+ size_t list_no,
+ size_t offset) const {
+ FAISS_THROW_IF_NOT(il0->list_size(list_no) < maxsize);
+ return il0->get_single_code(list_no, offset);
+}
+
+void StopWordsInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist)
+ const {
+ std::vector<idx_t> list0;
+ for (int i = 0; i < nlist; i++) {
+ idx_t list_no = list_nos[i];
+ if (list_no < 0)
+ continue;
+ if (il0->list_size(list_no) < maxsize) {
+ list0.push_back(list_no);
+ }
+ }
+ il0->prefetch_lists(list0.data(), list0.size());
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedLists.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedLists.h
new file mode 100644
index 0000000..78799a2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedLists.h
@@ -0,0 +1,426 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_INVERTEDLISTS_IVF_H
+#define FAISS_INVERTEDLISTS_IVF_H
+
+/**
+ * Definition of inverted lists + a few common classes that implement
+ * the interface.
+ */
+
+#include <vector>
+
+#include <faiss/MetricType.h>
+#include <faiss/impl/maybe_owned_vector.h>
+
+namespace faiss {
+
+struct InvertedListsIterator {
+ virtual ~InvertedListsIterator();
+ virtual bool is_available() const = 0;
+ virtual void next() = 0;
+ virtual std::pair<idx_t, const uint8_t*> get_id_and_codes() = 0;
+};
+
+/** Table of inverted lists
+ * multithreading rules:
+ * - concurrent read accesses are allowed
+ * - concurrent update accesses are allowed
+ * - for resize and add_entries, only concurrent access to different lists
+ * are allowed
+ */
+struct InvertedLists {
+ size_t nlist; ///< number of possible key values
+ size_t code_size; ///< code size per vector in bytes
+
+ /// request to use iterator rather than get_codes / get_ids
+ bool use_iterator = false;
+
+ InvertedLists(size_t nlist, size_t code_size);
+
+ virtual ~InvertedLists();
+
+ /// used for BlockInvertedLists, where the codes are packed into groups
+ /// and the individual code size is meaningless
+ static const size_t INVALID_CODE_SIZE = static_cast<size_t>(-1);
+
+ /*************************
+ * Read only functions */
+
+ /// get the size of a list
+ virtual size_t list_size(size_t list_no) const = 0;
+
+ /** get the codes for an inverted list
+ * must be released by release_codes
+ *
+ * @return codes size list_size * code_size
+ */
+ virtual const uint8_t* get_codes(size_t list_no) const = 0;
+
+ /** get the ids for an inverted list
+ * must be released by release_ids
+ *
+ * @return ids size list_size
+ */
+ virtual const idx_t* get_ids(size_t list_no) const = 0;
+
+ /// release codes returned by get_codes (default implementation is nop
+ virtual void release_codes(size_t list_no, const uint8_t* codes) const;
+
+ /// release ids returned by get_ids
+ virtual void release_ids(size_t list_no, const idx_t* ids) const;
+
+ /// @return a single id in an inverted list
+ virtual idx_t get_single_id(size_t list_no, size_t offset) const;
+
+ /// @return a single code in an inverted list
+ /// (should be deallocated with release_codes)
+ virtual const uint8_t* get_single_code(size_t list_no, size_t offset) const;
+
+ /// prepare the following lists (default does nothing)
+ /// a list can be -1 hence the signed long
+ virtual void prefetch_lists(const idx_t* list_nos, int nlist) const;
+
+ /*****************************************
+ * Iterator interface (with context) */
+
+ /// check if the list is empty
+ virtual bool is_empty(size_t list_no, void* inverted_list_context = nullptr)
+ const;
+
+ /// get iterable for lists that use_iterator
+ virtual InvertedListsIterator* get_iterator(
+ size_t list_no,
+ void* inverted_list_context = nullptr) const;
+
+ /*************************
+ * writing functions */
+
+ /// add one entry to an inverted list
+ virtual size_t add_entry(
+ size_t list_no,
+ idx_t theid,
+ const uint8_t* code,
+ void* inverted_list_context = nullptr);
+
+ virtual size_t add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) = 0;
+
+ virtual void update_entry(
+ size_t list_no,
+ size_t offset,
+ idx_t id,
+ const uint8_t* code);
+
+ virtual void update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) = 0;
+
+ virtual void resize(size_t list_no, size_t new_size) = 0;
+
+ virtual void reset();
+
+ /*************************
+ * high level functions */
+
+ /// move all entries from oivf (empty on output)
+ void merge_from(InvertedLists* oivf, size_t add_id);
+
+ // how to copy a subset of elements from the inverted lists
+ // This depends on two integers, a1 and a2.
+ enum subset_type_t : int {
+ // depends on IDs
+ SUBSET_TYPE_ID_RANGE = 0, // copies ids in [a1, a2)
+ SUBSET_TYPE_ID_MOD = 1, // copies ids if id % a1 == a2
+ // depends on order within invlists
+ SUBSET_TYPE_ELEMENT_RANGE =
+ 2, // copies fractions of invlists so that a1 elements are left
+ // before and a2 after
+ SUBSET_TYPE_INVLIST_FRACTION =
+ 3, // take fraction a2 out of a1 from each invlist, 0 <= a2 < a1
+ // copy only inverted lists a1:a2
+ SUBSET_TYPE_INVLIST = 4
+ };
+
+ /** copy a subset of the entries index to the other index
+ * @return number of entries copied
+ */
+ size_t copy_subset_to(
+ InvertedLists& other,
+ subset_type_t subset_type,
+ idx_t a1,
+ idx_t a2) const;
+
+ /*************************
+ * statistics */
+
+ /// 1= perfectly balanced, >1: imbalanced
+ double imbalance_factor() const;
+
+ /// display some stats about the inverted lists
+ void print_stats() const;
+
+ /// sum up list sizes
+ size_t compute_ntotal() const;
+
+ /**************************************
+ * Scoped inverted lists (for automatic deallocation)
+ *
+ * instead of writing:
+ *
+ * uint8_t * codes = invlists->get_codes (10);
+ * ... use codes
+ * invlists->release_codes(10, codes)
+ *
+ * write:
+ *
+ * ScopedCodes codes (invlists, 10);
+ * ... use codes.get()
+ * // release called automatically when codes goes out of scope
+ *
+ * the following function call also works:
+ *
+ * foo (123, ScopedCodes (invlists, 10).get(), 456);
+ *
+ */
+
+ struct ScopedIds {
+ const InvertedLists* il;
+ const idx_t* ids;
+ size_t list_no;
+
+ ScopedIds(const InvertedLists* il, size_t list_no)
+ : il(il), ids(il->get_ids(list_no)), list_no(list_no) {}
+
+ const idx_t* get() {
+ return ids;
+ }
+
+ idx_t operator[](size_t i) const {
+ return ids[i];
+ }
+
+ ~ScopedIds() {
+ il->release_ids(list_no, ids);
+ }
+ };
+
+ struct ScopedCodes {
+ const InvertedLists* il;
+ const uint8_t* codes;
+ size_t list_no;
+
+ ScopedCodes(const InvertedLists* il, size_t list_no)
+ : il(il), codes(il->get_codes(list_no)), list_no(list_no) {}
+
+ ScopedCodes(const InvertedLists* il, size_t list_no, size_t offset)
+ : il(il),
+ codes(il->get_single_code(list_no, offset)),
+ list_no(list_no) {}
+
+ const uint8_t* get() {
+ return codes;
+ }
+
+ ~ScopedCodes() {
+ il->release_codes(list_no, codes);
+ }
+ };
+};
+
+/// simple (default) implementation as an array of inverted lists
+struct ArrayInvertedLists : InvertedLists {
+ std::vector<MaybeOwnedVector<uint8_t>> codes; // binary codes, size nlist
+ std::vector<MaybeOwnedVector<idx_t>> ids; ///< Inverted lists for indexes
+
+ ArrayInvertedLists(size_t nlist, size_t code_size);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ size_t add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ void update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ void resize(size_t list_no, size_t new_size) override;
+
+ /// permute the inverted lists, map maps new_id to old_id
+ void permute_invlists(const idx_t* map);
+
+ bool is_empty(size_t list_no, void* inverted_list_context = nullptr)
+ const override;
+
+ ~ArrayInvertedLists() override;
+};
+
+/*****************************************************************
+ * Meta-inverted lists
+ *
+ * About terminology: the inverted lists are seen as a sparse matrix,
+ * that can be stacked horizontally, vertically and sliced.
+ *****************************************************************/
+
+/// invlists that fail for all write functions
+struct ReadOnlyInvertedLists : InvertedLists {
+ ReadOnlyInvertedLists(size_t nlist, size_t code_size)
+ : InvertedLists(nlist, code_size) {}
+
+ size_t add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ void update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ void resize(size_t list_no, size_t new_size) override;
+};
+
+/// Horizontal stack of inverted lists
+struct HStackInvertedLists : ReadOnlyInvertedLists {
+ std::vector<const InvertedLists*> ils;
+
+ /// build InvertedLists by concatenating nil of them
+ HStackInvertedLists(int nil, const InvertedLists** ils);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ void prefetch_lists(const idx_t* list_nos, int nlist) const override;
+
+ void release_codes(size_t list_no, const uint8_t* codes) const override;
+ void release_ids(size_t list_no, const idx_t* ids) const override;
+
+ idx_t get_single_id(size_t list_no, size_t offset) const override;
+
+ const uint8_t* get_single_code(size_t list_no, size_t offset)
+ const override;
+};
+
+using ConcatenatedInvertedLists = HStackInvertedLists;
+
+/// vertical slice of indexes in another InvertedLists
+struct SliceInvertedLists : ReadOnlyInvertedLists {
+ const InvertedLists* il;
+ idx_t i0, i1;
+
+ SliceInvertedLists(const InvertedLists* il, idx_t i0, idx_t i1);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ void release_codes(size_t list_no, const uint8_t* codes) const override;
+ void release_ids(size_t list_no, const idx_t* ids) const override;
+
+ idx_t get_single_id(size_t list_no, size_t offset) const override;
+
+ const uint8_t* get_single_code(size_t list_no, size_t offset)
+ const override;
+
+ void prefetch_lists(const idx_t* list_nos, int nlist) const override;
+};
+
+struct VStackInvertedLists : ReadOnlyInvertedLists {
+ std::vector<const InvertedLists*> ils;
+ std::vector<idx_t> cumsz;
+
+ /// build InvertedLists by concatenating nil of them
+ VStackInvertedLists(int nil, const InvertedLists** ils);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ void release_codes(size_t list_no, const uint8_t* codes) const override;
+ void release_ids(size_t list_no, const idx_t* ids) const override;
+
+ idx_t get_single_id(size_t list_no, size_t offset) const override;
+
+ const uint8_t* get_single_code(size_t list_no, size_t offset)
+ const override;
+
+ void prefetch_lists(const idx_t* list_nos, int nlist) const override;
+};
+
+/** use the first inverted lists if they are non-empty otherwise use the second
+ *
+ * This is useful if il1 has a few inverted lists that are too long,
+ * and that il0 has replacement lists for those, with empty lists for
+ * the others. */
+struct MaskedInvertedLists : ReadOnlyInvertedLists {
+ const InvertedLists* il0;
+ const InvertedLists* il1;
+
+ MaskedInvertedLists(const InvertedLists* il0, const InvertedLists* il1);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ void release_codes(size_t list_no, const uint8_t* codes) const override;
+ void release_ids(size_t list_no, const idx_t* ids) const override;
+
+ idx_t get_single_id(size_t list_no, size_t offset) const override;
+
+ const uint8_t* get_single_code(size_t list_no, size_t offset)
+ const override;
+
+ void prefetch_lists(const idx_t* list_nos, int nlist) const override;
+};
+
+/** if the inverted list in il is smaller than maxsize then return it,
+ * otherwise return an empty invlist */
+struct StopWordsInvertedLists : ReadOnlyInvertedLists {
+ const InvertedLists* il0;
+ size_t maxsize;
+
+ StopWordsInvertedLists(const InvertedLists* il, size_t maxsize);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ void release_codes(size_t list_no, const uint8_t* codes) const override;
+ void release_ids(size_t list_no, const idx_t* ids) const override;
+
+ idx_t get_single_id(size_t list_no, size_t offset) const override;
+
+ const uint8_t* get_single_code(size_t list_no, size_t offset)
+ const override;
+
+ void prefetch_lists(const idx_t* list_nos, int nlist) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedListsIOHook.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedListsIOHook.cpp
new file mode 100644
index 0000000..13d8490
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedListsIOHook.cpp
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/invlists/InvertedListsIOHook.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/io.h>
+#include <faiss/impl/io_macros.h>
+
+#include <faiss/invlists/BlockInvertedLists.h>
+
+#ifndef _WIN32
+#include <faiss/invlists/OnDiskInvertedLists.h>
+#endif // !_WIN32
+
+namespace faiss {
+
+/**********************************************************
+ * InvertedListIOHook's
+ **********************************************************/
+
+InvertedListsIOHook::InvertedListsIOHook(
+ const std::string& key,
+ const std::string& classname)
+ : key(key), classname(classname) {}
+
+namespace {
+
+/// std::vector that deletes its contents
+struct IOHookTable : std::vector<InvertedListsIOHook*> {
+ IOHookTable() {
+#ifndef _WIN32
+ push_back(new OnDiskInvertedListsIOHook());
+#endif
+ push_back(new BlockInvertedListsIOHook());
+ }
+
+ ~IOHookTable() {
+ for (auto x : *this) {
+ delete x;
+ }
+ }
+};
+
+static IOHookTable InvertedListsIOHook_table;
+
+} // namespace
+
+InvertedListsIOHook* InvertedListsIOHook::lookup(int h) {
+ for (const auto& callback : InvertedListsIOHook_table) {
+ if (h == fourcc(callback->key)) {
+ return callback;
+ }
+ }
+ FAISS_THROW_FMT(
+ "read_InvertedLists: could not load ArrayInvertedLists as "
+ "%08x (\"%s\")",
+ h,
+ fourcc_inv_printable(h).c_str());
+}
+
+InvertedListsIOHook* InvertedListsIOHook::lookup_classname(
+ const std::string& classname) {
+ for (const auto& callback : InvertedListsIOHook_table) {
+ if (callback->classname == classname) {
+ return callback;
+ }
+ }
+ FAISS_THROW_FMT(
+ "read_InvertedLists: could not find classname %s",
+ classname.c_str());
+}
+
+void InvertedListsIOHook::add_callback(InvertedListsIOHook* cb) {
+ InvertedListsIOHook_table.push_back(cb);
+}
+
+void InvertedListsIOHook::print_callbacks() {
+ printf("registered %zd InvertedListsIOHooks:\n",
+ InvertedListsIOHook_table.size());
+ for (const auto& cb : InvertedListsIOHook_table) {
+ printf("%08x %s %s\n",
+ fourcc(cb->key.c_str()),
+ cb->key.c_str(),
+ cb->classname.c_str());
+ }
+}
+
+InvertedLists* InvertedListsIOHook::read_ArrayInvertedLists(
+ IOReader*,
+ int,
+ size_t,
+ size_t,
+ const std::vector<size_t>&) const {
+ FAISS_THROW_FMT("read to array not implemented for %s", classname.c_str());
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedListsIOHook.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedListsIOHook.h
new file mode 100644
index 0000000..cfeeac8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/InvertedListsIOHook.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/io.h>
+#include <faiss/invlists/InvertedLists.h>
+#include <string>
+
+namespace faiss {
+
+/** Callbacks to handle other types of InvertedList objects.
+ *
+ * The callbacks should be registered with add_callback before calling
+ * read_index or read_InvertedLists. The callbacks for
+ * OnDiskInvertedLists are registrered by default. The invlist type is
+ * identified by:
+ *
+ * - the key (a fourcc) at read time
+ * - the class name (as given by typeid.name) at write time
+ */
+struct InvertedListsIOHook {
+ const std::string key; ///< string version of the fourcc
+ const std::string classname; ///< typeid.name
+
+ InvertedListsIOHook(const std::string& key, const std::string& classname);
+
+ /// write the index to the IOWriter (including the fourcc)
+ virtual void write(const InvertedLists* ils, IOWriter* f) const = 0;
+
+ /// called when the fourcc matches this class's fourcc
+ virtual InvertedLists* read(IOReader* f, int io_flags) const = 0;
+
+ /** read from a ArrayInvertedLists into this invertedlist type.
+ * For this to work, the callback has to be enabled and the io_flag has to
+ * be set to IO_FLAG_SKIP_IVF_DATA | (16 upper bits of the fourcc)
+ *
+ * (default implementation fails)
+ */
+ virtual InvertedLists* read_ArrayInvertedLists(
+ IOReader* f,
+ int io_flags,
+ size_t nlist,
+ size_t code_size,
+ const std::vector<size_t>& sizes) const;
+
+ virtual ~InvertedListsIOHook() {}
+
+ /**************************** Manage the set of callbacks ******/
+
+ // transfers ownership
+ static void add_callback(InvertedListsIOHook*);
+ static void print_callbacks();
+ static InvertedListsIOHook* lookup(int h);
+ static InvertedListsIOHook* lookup_classname(const std::string& classname);
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/OnDiskInvertedLists.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/OnDiskInvertedLists.cpp
new file mode 100644
index 0000000..eb0a219
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/OnDiskInvertedLists.cpp
@@ -0,0 +1,806 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/invlists/OnDiskInvertedLists.h>
+
+#include <pthread.h>
+
+#include <unordered_set>
+
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/impl/io.h>
+#include <faiss/impl/io_macros.h>
+
+namespace faiss {
+
+/**********************************************
+ * LockLevels
+ **********************************************/
+
+struct LockLevels {
+ /* There n times lock1(n), one lock2 and one lock3
+ * Invariants:
+ * a single thread can hold one lock1(n) for some n
+ * a single thread can hold lock2, if it holds lock1(n) for some n
+ * a single thread can hold lock3, if it holds lock1(n) for some n
+ * AND lock2 AND no other thread holds lock1(m) for m != n
+ */
+ pthread_mutex_t mutex1;
+ pthread_cond_t level1_cv;
+ pthread_cond_t level2_cv;
+ pthread_cond_t level3_cv;
+
+ std::unordered_set<int> level1_holders; // which level1 locks are held
+ int n_level2; // nb threads that wait on level2
+ bool level3_in_use; // a threads waits on level3
+ bool level2_in_use;
+
+ LockLevels() {
+ pthread_mutex_init(&mutex1, nullptr);
+ pthread_cond_init(&level1_cv, nullptr);
+ pthread_cond_init(&level2_cv, nullptr);
+ pthread_cond_init(&level3_cv, nullptr);
+ n_level2 = 0;
+ level2_in_use = false;
+ level3_in_use = false;
+ }
+
+ ~LockLevels() {
+ pthread_cond_destroy(&level1_cv);
+ pthread_cond_destroy(&level2_cv);
+ pthread_cond_destroy(&level3_cv);
+ pthread_mutex_destroy(&mutex1);
+ }
+
+ void lock_1(int no) {
+ pthread_mutex_lock(&mutex1);
+ while (level3_in_use || level1_holders.count(no) > 0) {
+ pthread_cond_wait(&level1_cv, &mutex1);
+ }
+ level1_holders.insert(no);
+ pthread_mutex_unlock(&mutex1);
+ }
+
+ void unlock_1(int no) {
+ pthread_mutex_lock(&mutex1);
+ assert(level1_holders.count(no) == 1);
+ level1_holders.erase(no);
+ if (level3_in_use) { // a writer is waiting
+ pthread_cond_signal(&level3_cv);
+ } else {
+ pthread_cond_broadcast(&level1_cv);
+ }
+ pthread_mutex_unlock(&mutex1);
+ }
+
+ void lock_2() {
+ pthread_mutex_lock(&mutex1);
+ n_level2++;
+ if (level3_in_use) { // tell waiting level3 that we are blocked
+ pthread_cond_signal(&level3_cv);
+ }
+ while (level2_in_use) {
+ pthread_cond_wait(&level2_cv, &mutex1);
+ }
+ level2_in_use = true;
+ pthread_mutex_unlock(&mutex1);
+ }
+
+ void unlock_2() {
+ pthread_mutex_lock(&mutex1);
+ level2_in_use = false;
+ n_level2--;
+ pthread_cond_signal(&level2_cv);
+ pthread_mutex_unlock(&mutex1);
+ }
+
+ void lock_3() {
+ pthread_mutex_lock(&mutex1);
+ level3_in_use = true;
+ // wait until there are no level1 holders anymore except the
+ // ones that are waiting on level2 (we are holding lock2)
+ while (level1_holders.size() > n_level2) {
+ pthread_cond_wait(&level3_cv, &mutex1);
+ }
+ // don't release the lock!
+ }
+
+ void unlock_3() {
+ level3_in_use = false;
+ // wake up all level1_holders
+ pthread_cond_broadcast(&level1_cv);
+ pthread_mutex_unlock(&mutex1);
+ }
+
+ void print() {
+ pthread_mutex_lock(&mutex1);
+ printf("State: level3_in_use=%d n_level2=%d level1_holders: [",
+ int(level3_in_use),
+ n_level2);
+ for (int k : level1_holders) {
+ printf("%d ", k);
+ }
+ printf("]\n");
+ pthread_mutex_unlock(&mutex1);
+ }
+};
+
+/**********************************************
+ * OngoingPrefetch
+ **********************************************/
+
+struct OnDiskInvertedLists::OngoingPrefetch {
+ struct Thread {
+ pthread_t pth;
+ OngoingPrefetch* pf;
+
+ bool one_list() {
+ idx_t list_no = pf->get_next_list();
+ if (list_no == -1)
+ return false;
+ const OnDiskInvertedLists* od = pf->od;
+ od->locks->lock_1(list_no);
+ size_t n = od->list_size(list_no);
+ const idx_t* idx = od->get_ids(list_no);
+ const uint8_t* codes = od->get_codes(list_no);
+ int cs = 0;
+ for (size_t i = 0; i < n; i++) {
+ cs += idx[i];
+ }
+ const idx_t* codes8 = (const idx_t*)codes;
+ idx_t n8 = n * od->code_size / 8;
+
+ for (size_t i = 0; i < n8; i++) {
+ cs += codes8[i];
+ }
+ od->locks->unlock_1(list_no);
+
+ global_cs += cs & 1;
+ return true;
+ }
+ };
+
+ std::vector<Thread> threads;
+
+ pthread_mutex_t list_ids_mutex;
+ std::vector<idx_t> list_ids;
+ int cur_list;
+
+ // mutex for the list of tasks
+ pthread_mutex_t mutex;
+
+ // pretext to avoid code below to be optimized out
+ static int global_cs;
+
+ const OnDiskInvertedLists* od;
+
+ explicit OngoingPrefetch(const OnDiskInvertedLists* od) : od(od) {
+ pthread_mutex_init(&mutex, nullptr);
+ pthread_mutex_init(&list_ids_mutex, nullptr);
+ cur_list = 0;
+ }
+
+ static void* prefetch_list(void* arg) {
+ Thread* th = static_cast<Thread*>(arg);
+
+ while (th->one_list())
+ ;
+
+ return nullptr;
+ }
+
+ idx_t get_next_list() {
+ idx_t list_no = -1;
+ pthread_mutex_lock(&list_ids_mutex);
+ if (cur_list >= 0 && cur_list < list_ids.size()) {
+ list_no = list_ids[cur_list++];
+ }
+ pthread_mutex_unlock(&list_ids_mutex);
+ return list_no;
+ }
+
+ void prefetch_lists(const idx_t* list_nos, int n) {
+ pthread_mutex_lock(&mutex);
+ pthread_mutex_lock(&list_ids_mutex);
+ list_ids.clear();
+ pthread_mutex_unlock(&list_ids_mutex);
+ for (auto& th : threads) {
+ pthread_join(th.pth, nullptr);
+ }
+
+ threads.resize(0);
+ cur_list = 0;
+ int nt = std::min(n, od->prefetch_nthread);
+
+ if (nt > 0) {
+ // prepare tasks
+ for (int i = 0; i < n; i++) {
+ idx_t list_no = list_nos[i];
+ if (list_no >= 0 && od->list_size(list_no) > 0) {
+ list_ids.push_back(list_no);
+ }
+ }
+ // prepare threads
+ threads.resize(nt);
+ for (Thread& th : threads) {
+ th.pf = this;
+ pthread_create(&th.pth, nullptr, prefetch_list, &th);
+ }
+ }
+ pthread_mutex_unlock(&mutex);
+ }
+
+ ~OngoingPrefetch() {
+ pthread_mutex_lock(&mutex);
+ for (auto& th : threads) {
+ pthread_join(th.pth, nullptr);
+ }
+ pthread_mutex_unlock(&mutex);
+ pthread_mutex_destroy(&mutex);
+ pthread_mutex_destroy(&list_ids_mutex);
+ }
+};
+
+int OnDiskInvertedLists::OngoingPrefetch::global_cs = 0;
+
+void OnDiskInvertedLists::prefetch_lists(const idx_t* list_nos, int n) const {
+ pf->prefetch_lists(list_nos, n);
+}
+
+/**********************************************
+ * OnDiskInvertedLists: mmapping
+ **********************************************/
+
+void OnDiskInvertedLists::do_mmap() {
+ const char* rw_flags = read_only ? "r" : "r+";
+ int prot = read_only ? PROT_READ : PROT_WRITE | PROT_READ;
+ FILE* f = fopen(filename.c_str(), rw_flags);
+ FAISS_THROW_IF_NOT_FMT(
+ f,
+ "could not open %s in mode %s: %s",
+ filename.c_str(),
+ rw_flags,
+ strerror(errno));
+
+ uint8_t* ptro =
+ (uint8_t*)mmap(nullptr, totsize, prot, MAP_SHARED, fileno(f), 0);
+
+ fclose(f);
+
+ FAISS_THROW_IF_NOT_FMT(
+ ptro != MAP_FAILED,
+ "could not mmap %s: %s",
+ filename.c_str(),
+ strerror(errno));
+ ptr = ptro;
+}
+
+void OnDiskInvertedLists::update_totsize(size_t new_size) {
+ // unmap file
+ if (ptr != nullptr) {
+ int err = munmap(ptr, totsize);
+ FAISS_THROW_IF_NOT_FMT(err == 0, "munmap error: %s", strerror(errno));
+ }
+ if (totsize == 0) {
+ // must create file before truncating it
+ FILE* f = fopen(filename.c_str(), "w");
+ FAISS_THROW_IF_NOT_FMT(
+ f,
+ "could not open %s in mode W: %s",
+ filename.c_str(),
+ strerror(errno));
+ fclose(f);
+ }
+
+ if (new_size > totsize) {
+ if (!slots.empty() &&
+ slots.back().offset + slots.back().capacity == totsize) {
+ slots.back().capacity += new_size - totsize;
+ } else {
+ slots.push_back(Slot(totsize, new_size - totsize));
+ }
+ } else {
+ assert(!"not implemented");
+ }
+
+ totsize = new_size;
+
+ // create file
+ printf("resizing %s to %zd bytes\n", filename.c_str(), totsize);
+
+ int err = truncate(filename.c_str(), totsize);
+
+ FAISS_THROW_IF_NOT_FMT(
+ err == 0,
+ "truncate %s to %ld: %s",
+ filename.c_str(),
+ totsize,
+ strerror(errno));
+ do_mmap();
+}
+
+/**********************************************
+ * OnDiskInvertedLists
+ **********************************************/
+
+#define INVALID_OFFSET (size_t)(-1)
+
+OnDiskOneList::OnDiskOneList() : size(0), capacity(0), offset(INVALID_OFFSET) {}
+
+OnDiskInvertedLists::Slot::Slot(size_t offset, size_t capacity)
+ : offset(offset), capacity(capacity) {}
+
+OnDiskInvertedLists::Slot::Slot() : offset(0), capacity(0) {}
+
+OnDiskInvertedLists::OnDiskInvertedLists(
+ size_t nlist,
+ size_t code_size,
+ const char* filename)
+ : InvertedLists(nlist, code_size),
+ filename(filename),
+ totsize(0),
+ ptr(nullptr),
+ read_only(false),
+ locks(new LockLevels()),
+ pf(new OngoingPrefetch(this)),
+ prefetch_nthread(32) {
+ lists.resize(nlist);
+
+ // slots starts empty
+}
+
+OnDiskInvertedLists::OnDiskInvertedLists() : OnDiskInvertedLists(0, 0, "") {}
+
+OnDiskInvertedLists::~OnDiskInvertedLists() {
+ delete pf;
+
+ // unmap all lists
+ if (ptr != nullptr) {
+ int err = munmap(ptr, totsize);
+ if (err != 0) {
+ fprintf(stderr, "mumap error: %s", strerror(errno));
+ }
+ }
+ delete locks;
+}
+
+size_t OnDiskInvertedLists::list_size(size_t list_no) const {
+ return lists[list_no].size;
+}
+
+const uint8_t* OnDiskInvertedLists::get_codes(size_t list_no) const {
+ if (lists[list_no].offset == INVALID_OFFSET) {
+ return nullptr;
+ }
+
+ return ptr + lists[list_no].offset;
+}
+
+const idx_t* OnDiskInvertedLists::get_ids(size_t list_no) const {
+ if (lists[list_no].offset == INVALID_OFFSET) {
+ return nullptr;
+ }
+
+ return (const idx_t*)(ptr + lists[list_no].offset +
+ code_size * lists[list_no].capacity);
+}
+
+void OnDiskInvertedLists::update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids_in,
+ const uint8_t* codes_in) {
+ FAISS_THROW_IF_NOT(!read_only);
+ if (n_entry == 0)
+ return;
+ [[maybe_unused]] const List& l = lists[list_no];
+ assert(n_entry + offset <= l.size);
+ idx_t* ids = const_cast<idx_t*>(get_ids(list_no));
+ memcpy(ids + offset, ids_in, sizeof(ids_in[0]) * n_entry);
+ uint8_t* codes = const_cast<uint8_t*>(get_codes(list_no));
+ memcpy(codes + offset * code_size, codes_in, code_size * n_entry);
+}
+
+size_t OnDiskInvertedLists::add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) {
+ FAISS_THROW_IF_NOT(!read_only);
+ locks->lock_1(list_no);
+ size_t o = list_size(list_no);
+ resize_locked(list_no, n_entry + o);
+ update_entries(list_no, o, n_entry, ids, code);
+ locks->unlock_1(list_no);
+ return o;
+}
+
+void OnDiskInvertedLists::resize(size_t list_no, size_t new_size) {
+ FAISS_THROW_IF_NOT(!read_only);
+ locks->lock_1(list_no);
+ resize_locked(list_no, new_size);
+ locks->unlock_1(list_no);
+}
+
+void OnDiskInvertedLists::resize_locked(size_t list_no, size_t new_size) {
+ List& l = lists[list_no];
+
+ if (new_size <= l.capacity && new_size > l.capacity / 2) {
+ l.size = new_size;
+ return;
+ }
+
+ // otherwise we release the current slot, and find a new one
+
+ locks->lock_2();
+ free_slot(l.offset, l.capacity);
+
+ List new_l;
+
+ if (new_size == 0) {
+ new_l = List();
+ } else {
+ new_l.size = new_size;
+ new_l.capacity = 1;
+ while (new_l.capacity < new_size) {
+ new_l.capacity *= 2;
+ }
+ new_l.offset =
+ allocate_slot(new_l.capacity * (sizeof(idx_t) + code_size));
+ }
+
+ // copy common data
+ if (l.offset != new_l.offset) {
+ size_t n = std::min(new_size, l.size);
+ if (n > 0) {
+ memcpy(ptr + new_l.offset, get_codes(list_no), n * code_size);
+ memcpy(ptr + new_l.offset + new_l.capacity * code_size,
+ get_ids(list_no),
+ n * sizeof(idx_t));
+ }
+ }
+
+ lists[list_no] = new_l;
+ locks->unlock_2();
+}
+
+size_t OnDiskInvertedLists::allocate_slot(size_t capacity) {
+ // should hold lock2
+
+ auto it = slots.begin();
+ while (it != slots.end() && it->capacity < capacity) {
+ it++;
+ }
+
+ if (it == slots.end()) {
+ // not enough capacity
+ size_t new_size = totsize == 0 ? 32 : totsize * 2;
+ while (new_size - totsize < capacity) {
+ new_size *= 2;
+ }
+ locks->lock_3();
+ update_totsize(new_size);
+ locks->unlock_3();
+ it = slots.begin();
+ while (it != slots.end() && it->capacity < capacity) {
+ it++;
+ }
+ assert(it != slots.end());
+ }
+
+ size_t o = it->offset;
+ if (it->capacity == capacity) {
+ slots.erase(it);
+ } else {
+ // take from beginning of slot
+ it->capacity -= capacity;
+ it->offset += capacity;
+ }
+
+ return o;
+}
+
+void OnDiskInvertedLists::free_slot(size_t offset, size_t capacity) {
+ // should hold lock2
+ if (capacity == 0)
+ return;
+
+ auto it = slots.begin();
+ while (it != slots.end() && it->offset <= offset) {
+ it++;
+ }
+
+ size_t inf = ((size_t)1) << 60;
+
+ size_t end_prev = inf;
+ if (it != slots.begin()) {
+ auto prev = it;
+ prev--;
+ end_prev = prev->offset + prev->capacity;
+ }
+
+ size_t begin_next = ((size_t)1) << 60;
+ if (it != slots.end()) {
+ begin_next = it->offset;
+ }
+
+ assert(end_prev == inf || offset >= end_prev);
+ assert(offset + capacity <= begin_next);
+
+ if (offset == end_prev) {
+ auto prev = it;
+ prev--;
+ if (offset + capacity == begin_next) {
+ prev->capacity += capacity + it->capacity;
+ slots.erase(it);
+ } else {
+ prev->capacity += capacity;
+ }
+ } else {
+ if (offset + capacity == begin_next) {
+ it->offset -= capacity;
+ it->capacity += capacity;
+ } else {
+ slots.insert(it, Slot(offset, capacity));
+ }
+ }
+
+ // TODO shrink global storage if needed
+}
+
+/*****************************************
+ * Compact form
+ *****************************************/
+size_t OnDiskInvertedLists::merge_from_multiple(
+ const InvertedLists** ils,
+ int n_il,
+ bool shift_ids,
+ bool verbose) {
+ FAISS_THROW_IF_NOT_MSG(
+ totsize == 0, "works only on an empty InvertedLists");
+
+ std::vector<size_t> sizes(nlist);
+ std::vector<size_t> shift_id_offsets(n_il);
+ for (int i = 0; i < n_il; i++) {
+ const InvertedLists* il = ils[i];
+ FAISS_THROW_IF_NOT(il->nlist == nlist && il->code_size == code_size);
+
+ for (size_t j = 0; j < nlist; j++) {
+ sizes[j] += il->list_size(j);
+ }
+
+ size_t il_totsize = il->compute_ntotal();
+ shift_id_offsets[i] =
+ (shift_ids && i > 0) ? shift_id_offsets[i - 1] + il_totsize : 0;
+ }
+
+ size_t cums = 0;
+ size_t ntotal = 0;
+ for (size_t j = 0; j < nlist; j++) {
+ ntotal += sizes[j];
+ lists[j].size = 0;
+ lists[j].capacity = sizes[j];
+ lists[j].offset = cums;
+ cums += lists[j].capacity * (sizeof(idx_t) + code_size);
+ }
+
+ update_totsize(cums);
+
+ size_t nmerged = 0;
+ double t0 = getmillisecs(), last_t = t0;
+
+#pragma omp parallel for
+ for (size_t j = 0; j < nlist; j++) {
+ List& l = lists[j];
+ for (int i = 0; i < n_il; i++) {
+ const InvertedLists* il = ils[i];
+ size_t n_entry = il->list_size(j);
+ l.size += n_entry;
+ ScopedIds scope_ids(il, j);
+ const idx_t* scope_ids_data = scope_ids.get();
+ std::vector<idx_t> new_ids;
+ if (shift_ids) {
+ new_ids.resize(n_entry);
+ for (size_t k = 0; k < n_entry; k++) {
+ new_ids[k] = scope_ids[k] + shift_id_offsets[i];
+ }
+ scope_ids_data = new_ids.data();
+ }
+ update_entries(
+ j,
+ l.size - n_entry,
+ n_entry,
+ scope_ids_data,
+ ScopedCodes(il, j).get());
+ }
+ assert(l.size == l.capacity);
+ if (verbose) {
+#pragma omp critical
+ {
+ nmerged++;
+ double t1 = getmillisecs();
+ if (t1 - last_t > 500) {
+ printf("merged %zd lists in %.3f s\r",
+ nmerged,
+ (t1 - t0) / 1000.0);
+ fflush(stdout);
+ last_t = t1;
+ }
+ }
+ }
+ }
+ if (verbose) {
+ printf("\n");
+ }
+
+ return ntotal;
+}
+
+size_t OnDiskInvertedLists::merge_from_1(
+ const InvertedLists* ils,
+ bool verbose) {
+ return merge_from_multiple(&ils, 1, verbose);
+}
+
+void OnDiskInvertedLists::crop_invlists(size_t l0, size_t l1) {
+ FAISS_THROW_IF_NOT(0 <= l0 && l0 <= l1 && l1 <= nlist);
+
+ std::vector<List> new_lists(l1 - l0);
+ memcpy(new_lists.data(), &lists[l0], (l1 - l0) * sizeof(List));
+
+ lists.swap(new_lists);
+
+ nlist = l1 - l0;
+}
+
+void OnDiskInvertedLists::set_all_lists_sizes(const size_t* sizes) {
+ size_t ofs = 0;
+ for (size_t i = 0; i < nlist; i++) {
+ lists[i].offset = ofs;
+ lists[i].capacity = lists[i].size = sizes[i];
+ ofs += sizes[i] * (sizeof(idx_t) + code_size);
+ }
+}
+
+/*******************************************************
+ * I/O support via callbacks
+ *******************************************************/
+
+OnDiskInvertedListsIOHook::OnDiskInvertedListsIOHook()
+ : InvertedListsIOHook("ilod", typeid(OnDiskInvertedLists).name()) {}
+
+void OnDiskInvertedListsIOHook::write(const InvertedLists* ils, IOWriter* f)
+ const {
+ uint32_t h = fourcc("ilod");
+ WRITE1(h);
+ WRITE1(ils->nlist);
+ WRITE1(ils->code_size);
+ const OnDiskInvertedLists* od =
+ dynamic_cast<const OnDiskInvertedLists*>(ils);
+ // this is a POD object
+ WRITEVECTOR(od->lists);
+
+ {
+ std::vector<OnDiskInvertedLists::Slot> v(
+ od->slots.begin(), od->slots.end());
+ WRITEVECTOR(v);
+ }
+ {
+ std::vector<char> x(od->filename.begin(), od->filename.end());
+ WRITEVECTOR(x);
+ }
+ WRITE1(od->totsize);
+}
+
+InvertedLists* OnDiskInvertedListsIOHook::read(IOReader* f, int io_flags)
+ const {
+ OnDiskInvertedLists* od = new OnDiskInvertedLists();
+ od->read_only = io_flags & IO_FLAG_READ_ONLY;
+ READ1(od->nlist);
+ READ1(od->code_size);
+ // this is a POD object
+ READVECTOR(od->lists);
+ {
+ std::vector<OnDiskInvertedLists::Slot> v;
+ READVECTOR(v);
+ od->slots.assign(v.begin(), v.end());
+ }
+ {
+ std::vector<char> x;
+ READVECTOR(x);
+ od->filename.assign(x.begin(), x.end());
+
+ if (io_flags & IO_FLAG_ONDISK_SAME_DIR) {
+ FileIOReader* reader = dynamic_cast<FileIOReader*>(f);
+ FAISS_THROW_IF_NOT_MSG(
+ reader,
+ "IO_FLAG_ONDISK_SAME_DIR only supported "
+ "when reading from file");
+ std::string indexname = reader->name;
+ std::string dirname = "./";
+ size_t slash = indexname.find_last_of('/');
+ if (slash != std::string::npos) {
+ dirname = indexname.substr(0, slash + 1);
+ }
+ std::string filename = od->filename;
+ slash = filename.find_last_of('/');
+ if (slash != std::string::npos) {
+ filename = filename.substr(slash + 1);
+ }
+ filename = dirname + filename;
+ printf("IO_FLAG_ONDISK_SAME_DIR: "
+ "updating ondisk filename from %s to %s\n",
+ od->filename.c_str(),
+ filename.c_str());
+ od->filename = filename;
+ }
+ }
+ READ1(od->totsize);
+ if (!(io_flags & IO_FLAG_SKIP_IVF_DATA)) {
+ od->do_mmap();
+ }
+ return od;
+}
+
+/** read from a ArrayInvertedLists into this invertedlist type */
+InvertedLists* OnDiskInvertedListsIOHook::read_ArrayInvertedLists(
+ IOReader* f,
+ int /* io_flags */,
+ size_t nlist,
+ size_t code_size,
+ const std::vector<size_t>& sizes) const {
+ auto ails = new OnDiskInvertedLists();
+ ails->nlist = nlist;
+ ails->code_size = code_size;
+ ails->read_only = true;
+ ails->lists.resize(nlist);
+
+ FileIOReader* reader = dynamic_cast<FileIOReader*>(f);
+ FAISS_THROW_IF_NOT_MSG(reader, "mmap only supported for File objects");
+ FILE* fdesc = reader->f;
+ size_t o0 = ftell(fdesc);
+ size_t o = o0;
+ { // do the mmap
+ struct stat buf;
+ int ret = fstat(fileno(fdesc), &buf);
+ FAISS_THROW_IF_NOT_FMT(ret == 0, "fstat failed: %s", strerror(errno));
+ ails->totsize = buf.st_size;
+ ails->ptr = (uint8_t*)mmap(
+ nullptr,
+ ails->totsize,
+ PROT_READ,
+ MAP_SHARED,
+ fileno(fdesc),
+ 0);
+ FAISS_THROW_IF_NOT_FMT(
+ ails->ptr != MAP_FAILED, "could not mmap: %s", strerror(errno));
+ }
+
+ FAISS_THROW_IF_NOT(o <= ails->totsize);
+
+ for (size_t i = 0; i < ails->nlist; i++) {
+ OnDiskInvertedLists::List& l = ails->lists[i];
+ l.size = l.capacity = sizes[i];
+ l.offset = o;
+ o += l.size * (sizeof(idx_t) + ails->code_size);
+ }
+ // resume normal reading of file
+ fseek(fdesc, o, SEEK_SET);
+
+ return ails;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/OnDiskInvertedLists.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/OnDiskInvertedLists.h
new file mode 100644
index 0000000..52953f9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/invlists/OnDiskInvertedLists.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#ifndef FAISS_ON_DISK_INVERTED_LISTS_H
+#define FAISS_ON_DISK_INVERTED_LISTS_H
+
+#include <list>
+#include <typeinfo>
+#include <vector>
+
+#include <faiss/IndexIVF.h>
+#include <faiss/index_io.h>
+#include <faiss/invlists/InvertedListsIOHook.h>
+
+namespace faiss {
+
+struct LockLevels;
+
+struct OnDiskOneList {
+ size_t size; // size of inverted list (entries)
+ size_t capacity; // allocated size (entries)
+ size_t offset; // offset in buffer (bytes)
+ OnDiskOneList();
+};
+
+/** On-disk storage of inverted lists.
+ *
+ * The data is stored in a mmapped chunk of memory (base pointer ptr,
+ * size totsize). Each list is a range of memory that contains (object
+ * List) that contains:
+ *
+ * - uint8_t codes[capacity * code_size]
+ * - followed by idx_t ids[capacity]
+ *
+ * in each of the arrays, the size <= capacity first elements are
+ * used, the rest is not initialized.
+ *
+ * Addition and resize are supported by:
+ * - roundind up the capacity of the lists to a power of two
+ * - maintaining a list of empty slots, sorted by size.
+ * - resizing the mmapped block is adjusted as needed.
+ *
+ * An OnDiskInvertedLists is compact if the size == capacity for all
+ * lists and there are no available slots.
+ *
+ * Addition to the invlists is slow. For incremental add it is better
+ * to use a default ArrayInvertedLists object and convert it to an
+ * OnDisk with merge_from.
+ *
+ * When it is known that a set of lists will be accessed, it is useful
+ * to call prefetch_lists, that launches a set of threads to read the
+ * lists in parallel.
+ */
+struct OnDiskInvertedLists : InvertedLists {
+ using List = OnDiskOneList;
+
+ // size nlist
+ std::vector<List> lists;
+
+ struct Slot {
+ size_t offset; // bytes
+ size_t capacity; // bytes
+ Slot(size_t offset, size_t capacity);
+ Slot();
+ };
+
+ // size whatever space remains
+ std::list<Slot> slots;
+
+ std::string filename;
+ size_t totsize;
+ uint8_t* ptr; // mmap base pointer
+ bool read_only; /// are inverted lists mapped read-only
+
+ OnDiskInvertedLists(size_t nlist, size_t code_size, const char* filename);
+
+ size_t list_size(size_t list_no) const override;
+ const uint8_t* get_codes(size_t list_no) const override;
+ const idx_t* get_ids(size_t list_no) const override;
+
+ size_t add_entries(
+ size_t list_no,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ void update_entries(
+ size_t list_no,
+ size_t offset,
+ size_t n_entry,
+ const idx_t* ids,
+ const uint8_t* code) override;
+
+ void resize(size_t list_no, size_t new_size) override;
+
+ // copy all inverted lists into *this, in compact form (without
+ // allocating slots)
+ size_t merge_from_multiple(
+ const InvertedLists** ils,
+ int n_il,
+ bool shift_ids = false,
+ bool verbose = false);
+
+ /// same as merge_from for a single invlist
+ size_t merge_from_1(const InvertedLists* il, bool verbose = false);
+
+ /// restrict the inverted lists to l0:l1 without touching the mmapped region
+ void crop_invlists(size_t l0, size_t l1);
+
+ void prefetch_lists(const idx_t* list_nos, int nlist) const override;
+
+ ~OnDiskInvertedLists() override;
+
+ // private
+
+ LockLevels* locks;
+
+ // encapsulates the threads that are busy prefeteching
+ struct OngoingPrefetch;
+ OngoingPrefetch* pf;
+ int prefetch_nthread;
+
+ void do_mmap();
+ void update_totsize(size_t new_totsize);
+ void resize_locked(size_t list_no, size_t new_size);
+ size_t allocate_slot(size_t capacity);
+ void free_slot(size_t offset, size_t capacity);
+
+ /// override all list sizes and make a packed storage
+ void set_all_lists_sizes(const size_t* sizes);
+
+ // empty constructor for the I/O functions
+ OnDiskInvertedLists();
+};
+
+struct OnDiskInvertedListsIOHook : InvertedListsIOHook {
+ OnDiskInvertedListsIOHook();
+ void write(const InvertedLists* ils, IOWriter* f) const override;
+ InvertedLists* read(IOReader* f, int io_flags) const override;
+ InvertedLists* read_ArrayInvertedLists(
+ IOReader* f,
+ int io_flags,
+ size_t nlist,
+ size_t code_size,
+ const std::vector<size_t>& sizes) const override;
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/CMakeLists.txt
new file mode 100644
index 0000000..0816dae
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/CMakeLists.txt
@@ -0,0 +1,348 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+cmake_minimum_required(VERSION 3.17 FATAL_ERROR)
+
+project(pyfaiss
+ DESCRIPTION "Python bindings for faiss."
+ HOMEPAGE_URL "https://github.com/facebookresearch/faiss"
+ LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+
+find_package(SWIG REQUIRED COMPONENTS python)
+include(${SWIG_USE_FILE})
+
+set(UseSWIG_TARGET_NAME_PREFERENCE STANDARD)
+set(SWIG_SOURCE_FILE_EXTENSIONS swig)
+
+macro(configure_swigfaiss source)
+ set_source_files_properties(${source} PROPERTIES
+ CPLUSPLUS ON
+ USE_TARGET_INCLUDE_DIRECTORIES TRUE
+ )
+ if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND NOT WIN32)
+ set_source_files_properties(${source} PROPERTIES
+ SWIG_FLAGS -DSWIGWORDSIZE64
+ )
+ endif()
+ if(WIN32)
+ set_source_files_properties(${source} PROPERTIES
+ SWIG_FLAGS -DSWIGWIN
+ )
+ endif()
+ if(FAISS_ENABLE_GPU)
+ set_source_files_properties(${source} PROPERTIES
+ COMPILE_DEFINITIONS GPU_WRAPPER
+ )
+ if (FAISS_ENABLE_ROCM)
+ set_property(SOURCE ${source} APPEND PROPERTY
+ COMPILE_DEFINITIONS FAISS_ENABLE_ROCM
+ )
+ endif()
+ if (FAISS_ENABLE_CUVS)
+ set_property(SOURCE ${source} APPEND PROPERTY
+ COMPILE_DEFINITIONS FAISS_ENABLE_CUVS
+ )
+ endif()
+ endif()
+endmacro()
+
+# CMake's SWIG wrappers only allow tweaking certain settings at source level, so
+# we duplicate the source in order to override the module name.
+configure_file(swigfaiss.swig ${CMAKE_CURRENT_SOURCE_DIR}/swigfaiss_avx2.swig COPYONLY)
+configure_file(swigfaiss.swig ${CMAKE_CURRENT_SOURCE_DIR}/swigfaiss_avx512.swig COPYONLY)
+configure_file(swigfaiss.swig ${CMAKE_CURRENT_SOURCE_DIR}/swigfaiss_avx512_spr.swig COPYONLY)
+configure_file(swigfaiss.swig ${CMAKE_CURRENT_SOURCE_DIR}/swigfaiss_sve.swig COPYONLY)
+
+configure_swigfaiss(swigfaiss.swig)
+configure_swigfaiss(swigfaiss_avx2.swig)
+configure_swigfaiss(swigfaiss_avx512.swig)
+configure_swigfaiss(swigfaiss_avx512_spr.swig)
+configure_swigfaiss(swigfaiss_sve.swig)
+configure_swigfaiss(faiss_example_external_module.swig)
+
+if(TARGET faiss)
+ # Manually add headers as extra dependencies of swigfaiss.
+ set(SWIG_MODULE_swigfaiss_EXTRA_DEPS)
+ foreach(h ${FAISS_HEADERS})
+ list(APPEND SWIG_MODULE_swigfaiss_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx2_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx512_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx512_spr_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_sve_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/${h}")
+ list(APPEND SWIG_MODULE_faiss_example_external_module_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/${h}")
+ endforeach()
+ if(FAISS_ENABLE_ROCM)
+ foreach(h ${FAISS_GPU_HEADERS})
+ list(APPEND SWIG_MODULE_swigfaiss_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu-rocm/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx2_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu-rocm/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx512_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu-rocm/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx512_spr_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu-rocm/${h}")
+ list(APPEND SWIG_MODULE_faiss_example_external_module_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu-rocm/${h}")
+ endforeach()
+ else()
+ foreach(h ${FAISS_GPU_HEADERS})
+ list(APPEND SWIG_MODULE_swigfaiss_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx2_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx512_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_avx512_spr_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu/${h}")
+ list(APPEND SWIG_MODULE_swigfaiss_sve_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu/${h}")
+ list(APPEND SWIG_MODULE_faiss_example_external_module_EXTRA_DEPS
+ "${faiss_SOURCE_DIR}/faiss/gpu/${h}")
+ endforeach()
+ endif()
+else()
+ find_package(faiss REQUIRED)
+endif()
+
+if (${CMAKE_SYSTEM_NAME} MATCHES "AIX")
+swig_add_library(swigfaiss
+ TYPE MODULE
+ LANGUAGE python
+ SOURCES swigfaiss.swig
+)
+else ()
+swig_add_library(swigfaiss
+ TYPE SHARED
+ LANGUAGE python
+ SOURCES swigfaiss.swig
+)
+endif()
+
+set_property(TARGET swigfaiss PROPERTY SWIG_COMPILE_OPTIONS -doxygen)
+
+set_property(SOURCE swigfaiss_avx2.swig
+ PROPERTY SWIG_MODULE_NAME swigfaiss_avx2)
+swig_add_library(swigfaiss_avx2
+ TYPE SHARED
+ LANGUAGE python
+ SOURCES swigfaiss_avx2.swig
+)
+set_property(TARGET swigfaiss_avx2 PROPERTY SWIG_COMPILE_OPTIONS -doxygen)
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx2")
+ set_target_properties(swigfaiss_avx2 PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+
+set_property(SOURCE swigfaiss_avx512.swig
+ PROPERTY SWIG_MODULE_NAME swigfaiss_avx512)
+swig_add_library(swigfaiss_avx512
+ TYPE SHARED
+ LANGUAGE python
+ SOURCES swigfaiss_avx512.swig
+)
+set_property(TARGET swigfaiss_avx512 PROPERTY SWIG_COMPILE_OPTIONS -doxygen)
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx512")
+ set_target_properties(swigfaiss_avx512 PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+
+set_property(SOURCE swigfaiss_avx512_spr.swig
+ PROPERTY SWIG_MODULE_NAME swigfaiss_avx512_spr)
+swig_add_library(swigfaiss_avx512_spr
+ TYPE SHARED
+ LANGUAGE python
+ SOURCES swigfaiss_avx512_spr.swig
+)
+set_property(TARGET swigfaiss_avx512_spr PROPERTY SWIG_COMPILE_OPTIONS -doxygen)
+if(NOT FAISS_OPT_LEVEL STREQUAL "avx512_spr")
+ set_target_properties(swigfaiss_avx512_spr PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+
+set_property(SOURCE swigfaiss_sve.swig
+ PROPERTY SWIG_MODULE_NAME swigfaiss_sve)
+swig_add_library(swigfaiss_sve
+ TYPE SHARED
+ LANGUAGE python
+ SOURCES swigfaiss_sve.swig
+)
+set_property(TARGET swigfaiss_sve PROPERTY SWIG_COMPILE_OPTIONS -doxygen)
+if(NOT FAISS_OPT_LEVEL STREQUAL "sve")
+ set_target_properties(swigfaiss_sve PROPERTIES EXCLUDE_FROM_ALL TRUE)
+endif()
+
+set_property(SOURCE faiss_example_external_module.swig
+ PROPERTY SWIG_MODULE_NAME faiss_example_external_module)
+swig_add_library(faiss_example_external_module
+ TYPE SHARED
+ LANGUAGE python
+ SOURCES faiss_example_external_module.swig
+)
+set_property(TARGET faiss_example_external_module PROPERTY SWIG_COMPILE_OPTIONS -doxygen)
+
+if(NOT WIN32)
+ # NOTE: Python does not recognize the dylib extension.
+ set_target_properties(swigfaiss PROPERTIES SUFFIX .so)
+ set_target_properties(swigfaiss_avx2 PROPERTIES SUFFIX .so)
+ set_target_properties(swigfaiss_avx512 PROPERTIES SUFFIX .so)
+ set_target_properties(swigfaiss_avx512_spr PROPERTIES SUFFIX .so)
+ set_target_properties(swigfaiss_sve PROPERTIES SUFFIX .so)
+ set_target_properties(faiss_example_external_module PROPERTIES SUFFIX .so)
+else()
+ # we need bigobj for the swig wrapper
+ target_compile_options(swigfaiss PRIVATE /bigobj)
+ target_compile_options(swigfaiss_avx2 PRIVATE /bigobj)
+ target_compile_options(swigfaiss_avx512 PRIVATE /bigobj)
+ target_compile_options(swigfaiss_avx512_spr PRIVATE /bigobj)
+ target_compile_options(swigfaiss_sve PRIVATE /bigobj)
+ target_compile_options(faiss_example_external_module PRIVATE /bigobj)
+endif()
+
+if(FAISS_ENABLE_GPU)
+ if(FAISS_ENABLE_ROCM)
+ target_link_libraries(swigfaiss PRIVATE hip::host)
+ target_link_libraries(swigfaiss_avx2 PRIVATE hip::host)
+ target_link_libraries(swigfaiss_avx512 PRIVATE hip::host)
+ target_link_libraries(swigfaiss_avx512_spr PRIVATE hip::host)
+ target_link_libraries(faiss_example_external_module PRIVATE hip::host)
+ else()
+ find_package(CUDAToolkit REQUIRED)
+ if(FAISS_ENABLE_CUVS)
+ find_package(cuvs)
+ endif()
+ target_link_libraries(swigfaiss PRIVATE CUDA::cudart $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(swigfaiss_avx2 PRIVATE CUDA::cudart $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(swigfaiss_avx512 PRIVATE CUDA::cudart $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(swigfaiss_avx512_spr PRIVATE CUDA::cudart $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ target_link_libraries(swigfaiss_sve PRIVATE CUDA::cudart $<$<BOOL:${FAISS_ENABLE_CUVS}>:cuvs::cuvs>)
+ endif()
+endif()
+
+find_package(OpenMP REQUIRED)
+
+target_link_libraries(swigfaiss PRIVATE
+ faiss
+ Python::Module
+ Python::NumPy
+ OpenMP::OpenMP_CXX
+)
+
+target_link_libraries(swigfaiss_avx2 PRIVATE
+ faiss_avx2
+ Python::Module
+ Python::NumPy
+ OpenMP::OpenMP_CXX
+)
+
+target_link_libraries(swigfaiss_avx512 PRIVATE
+ faiss_avx512
+ Python::Module
+ Python::NumPy
+ OpenMP::OpenMP_CXX
+)
+
+target_link_libraries(swigfaiss_avx512_spr PRIVATE
+ faiss_avx512_spr
+ Python::Module
+ Python::NumPy
+ OpenMP::OpenMP_CXX
+)
+
+target_link_libraries(swigfaiss_sve PRIVATE
+ faiss_sve
+ Python::Module
+ Python::NumPy
+ OpenMP::OpenMP_CXX
+)
+
+target_link_libraries(faiss_example_external_module PRIVATE
+ Python::Module
+ Python::NumPy
+ OpenMP::OpenMP_CXX
+ swigfaiss
+ faiss
+)
+
+# Hack so that python_callbacks.h can be included as
+# `#include <faiss/python/python_callbacks.h>`.
+target_include_directories(swigfaiss PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+target_include_directories(swigfaiss_avx2 PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+target_include_directories(swigfaiss_avx512 PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+target_include_directories(swigfaiss_avx512_spr PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+target_include_directories(swigfaiss_sve PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+target_include_directories(faiss_example_external_module PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+
+find_package(Python REQUIRED
+ COMPONENTS Development NumPy
+)
+
+add_library(faiss_python_callbacks EXCLUDE_FROM_ALL
+ python_callbacks.cpp
+)
+set_property(TARGET faiss_python_callbacks
+ PROPERTY POSITION_INDEPENDENT_CODE ON
+)
+
+if (${CMAKE_SYSTEM_NAME} MATCHES "AIX")
+target_link_libraries(faiss_python_callbacks PRIVATE faiss)
+endif()
+
+# Hack so that python_callbacks.h can be included as
+# `#include <faiss/python/python_callbacks.h>`.
+target_include_directories(faiss_python_callbacks PRIVATE ${PROJECT_SOURCE_DIR}/../..)
+target_include_directories(faiss_python_callbacks PRIVATE ${Python_INCLUDE_DIRS})
+
+target_link_libraries(swigfaiss PRIVATE faiss_python_callbacks)
+target_link_libraries(swigfaiss_avx2 PRIVATE faiss_python_callbacks)
+target_link_libraries(swigfaiss_avx512 PRIVATE faiss_python_callbacks)
+target_link_libraries(swigfaiss_avx512_spr PRIVATE faiss_python_callbacks)
+target_link_libraries(swigfaiss_sve PRIVATE faiss_python_callbacks)
+target_link_libraries(faiss_example_external_module PRIVATE faiss_python_callbacks)
+
+configure_file(setup.py setup.py COPYONLY)
+configure_file(__init__.py __init__.py COPYONLY)
+configure_file(loader.py loader.py COPYONLY)
+configure_file(class_wrappers.py class_wrappers.py COPYONLY)
+configure_file(gpu_wrappers.py gpu_wrappers.py COPYONLY)
+configure_file(extra_wrappers.py extra_wrappers.py COPYONLY)
+configure_file(array_conversions.py array_conversions.py COPYONLY)
+
+# file(GLOB files "${PROJECT_SOURCE_DIR}/../../contrib/*.py")
+file(COPY ${PROJECT_SOURCE_DIR}/../../contrib DESTINATION .)
+
+# ====================================================================
+# ========= BEGIN LEANN PROJECT PATCH =========
+# ====================================================================
+# 模仿 diskann 方案,将所有 Python 组件作为“兄弟模块”安装到主包目录中
+
+# 1. 安装 C++ 扩展,目标是主包根目录 leann_backend_hnsw
+install(TARGETS swigfaiss
+ DESTINATION leann_backend_hnsw
+)
+
+# 2. 安装 SWIG 包装器,并重命名为 faiss.py,目标是主包根目录
+install(FILES ${CMAKE_CURRENT_BINARY_DIR}/swigfaiss.py
+ DESTINATION leann_backend_hnsw
+ RENAME faiss.py
+)
+
+# 3. 安装所有静态辅助 .py 文件,目标是主包根目录
+# 注意:我们不再需要 faiss 自己的 __init__.py 文件了
+install(FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/loader.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/class_wrappers.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/gpu_wrappers.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/extra_wrappers.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/array_conversions.py
+ DESTINATION leann_backend_hnsw
+)
+# ====================================================================
+# ========= END LEANN PROJECT PATCH =========
+# ====================================================================
\ No newline at end of file
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/__init__.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/__init__.py
new file mode 100644
index 0000000..a212ef4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/__init__.py
@@ -0,0 +1,350 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# @nolint
+
+# not linting this file because it imports * from swigfaiss, which
+# causes a ton of useless warnings.
+
+import numpy as np
+import logging
+import sys
+import inspect
+
+# We import * so that the symbol foo can be accessed as faiss.foo.
+from .loader import *
+
+# additional wrappers
+from .faiss import class_wrappers
+from .faiss.gpu_wrappers import *
+from .faiss.array_conversions import *
+from .faiss.extra_wrappers import kmin, kmax, pairwise_distances, rand, randint, \
+ lrand, randn, rand_smooth_vectors, eval_intersection, normalize_L2, \
+ ResultHeap, knn, Kmeans, checksum, matrix_bucket_sort_inplace, bucket_sort, \
+ merge_knn_results, MapInt64ToInt64, knn_hamming, \
+ pack_bitstrings, unpack_bitstrings
+
+
+__version__ = "%d.%d.%d" % (FAISS_VERSION_MAJOR,
+ FAISS_VERSION_MINOR,
+ FAISS_VERSION_PATCH)
+
+logger = logging.getLogger(__name__)
+
+class_wrappers.handle_Clustering(Clustering)
+class_wrappers.handle_Clustering1D(Clustering1D)
+class_wrappers.handle_MatrixStats(MatrixStats)
+class_wrappers.handle_IOWriter(IOWriter)
+class_wrappers.handle_IOReader(IOReader)
+class_wrappers.handle_AutoTuneCriterion(AutoTuneCriterion)
+class_wrappers.handle_ParameterSpace(ParameterSpace)
+class_wrappers.handle_NSG(IndexNSG)
+class_wrappers.handle_MapLong2Long(MapLong2Long)
+class_wrappers.handle_IDSelectorSubset(IDSelectorBatch, class_owns=True)
+class_wrappers.handle_IDSelectorSubset(IDSelectorArray, class_owns=False)
+class_wrappers.handle_IDSelectorSubset(IDSelectorBitmap, class_owns=False, force_int64=False)
+class_wrappers.handle_CodeSet(CodeSet)
+
+class_wrappers.handle_Tensor2D(Tensor2D)
+class_wrappers.handle_Tensor2D(Int32Tensor2D)
+class_wrappers.handle_Embedding(Embedding)
+class_wrappers.handle_Linear(Linear)
+class_wrappers.handle_QINCo(QINCo)
+class_wrappers.handle_QINCoStep(QINCoStep)
+shard_ivf_index_centroids = class_wrappers.handle_shard_ivf_index_centroids(shard_ivf_index_centroids)
+
+
+this_module = sys.modules[__name__]
+
+# handle sub-classes
+for symbol in dir(this_module):
+ obj = getattr(this_module, symbol)
+ # print symbol, isinstance(obj, (type, types.ClassType))
+ if inspect.isclass(obj):
+ the_class = obj
+ if issubclass(the_class, Index):
+ class_wrappers.handle_Index(the_class)
+
+ if issubclass(the_class, IndexBinary):
+ class_wrappers.handle_IndexBinary(the_class)
+
+ if issubclass(the_class, VectorTransform):
+ class_wrappers.handle_VectorTransform(the_class)
+
+ if issubclass(the_class, Quantizer):
+ class_wrappers.handle_Quantizer(the_class)
+
+ if issubclass(the_class, IndexRowwiseMinMax) or \
+ issubclass(the_class, IndexRowwiseMinMaxFP16):
+ class_wrappers.handle_IndexRowwiseMinMax(the_class)
+
+ if issubclass(the_class, SearchParameters):
+ class_wrappers.handle_SearchParameters(the_class)
+
+ if issubclass(the_class, CodePacker):
+ class_wrappers.handle_CodePacker(the_class)
+
+##############################################################################
+# For some classes (IndexIVF, IDSelector), the object holds a reference to
+# a C++ object (eg. the quantizer object of IndexIVF). We don't transfer the
+# ownership to the C++ object (ie. set own_quantizer=true), but instead we add
+# a reference in the Python class wrapper instead. This is done via an
+# additional referenced_objects field.
+#
+# Since the semantics of ownership in the C++ classes are sometimes irregular,
+# these references are added manually using the functions below.
+##############################################################################
+
+
+def add_ref_in_constructor(the_class, parameter_no):
+ # adds a reference to parameter parameter_no in self
+ # so that that parameter does not get deallocated before self
+ original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ original_init(self, *args)
+ self.referenced_objects = [args[parameter_no]]
+
+ def replacement_init_multiple(self, *args):
+ original_init(self, *args)
+ pset = parameter_no[len(args)]
+ self.referenced_objects = [args[no] for no in pset]
+
+ if type(parameter_no) == dict:
+ # a list of parameters to keep, depending on the number of arguments
+ the_class.__init__ = replacement_init_multiple
+ else:
+ the_class.__init__ = replacement_init
+
+def add_to_referenced_objects(self, ref):
+ if not hasattr(self, 'referenced_objects'):
+ self.referenced_objects = [ref]
+ else:
+ self.referenced_objects.append(ref)
+
+
+def add_ref_in_method(the_class, method_name, parameter_no):
+ original_method = getattr(the_class, method_name)
+
+ def replacement_method(self, *args):
+ ref = args[parameter_no]
+ add_to_referenced_objects(self, ref)
+ return original_method(self, *args)
+ setattr(the_class, method_name, replacement_method)
+
+
+def add_ref_in_method_explicit_own(the_class, method_name):
+ # for methods of format set_XXX(object, own)
+ original_method = getattr(the_class, method_name)
+
+ def replacement_method(self, ref, own=False):
+ if not own:
+ if not hasattr(self, 'referenced_objects'):
+ self.referenced_objects = [ref]
+ else:
+ self.referenced_objects.append(ref)
+ else:
+ # transfer ownership to C++ class
+ ref.this.disown()
+ return original_method(self, ref, own)
+ setattr(the_class, method_name, replacement_method)
+
+
+def add_ref_in_function(function_name, parameter_no):
+ # assumes the function returns an object
+ original_function = getattr(this_module, function_name)
+
+ def replacement_function(*args):
+ result = original_function(*args)
+ ref = args[parameter_no]
+ result.referenced_objects = [ref]
+ return result
+ setattr(this_module, function_name, replacement_function)
+
+
+try:
+ add_ref_in_constructor(GpuIndexIVFFlat, 1)
+ add_ref_in_constructor(GpuIndexBinaryFlat, 1)
+ add_ref_in_constructor(GpuIndexFlat, 1)
+ add_ref_in_constructor(GpuIndexIVFPQ, 1)
+ add_ref_in_constructor(GpuIndexIVFScalarQuantizer, 1)
+except NameError as e:
+ logger.info("Failed to load GPU Faiss: %s. Will not load constructor refs for GPU indexes. This is only an error if you're trying to use GPU Faiss." % e.args[0])
+
+add_ref_in_constructor(IndexIVFFlat, 0)
+add_ref_in_constructor(IndexIVFFlatDedup, 0)
+add_ref_in_constructor(IndexPreTransform, {2: [0, 1], 1: [0]})
+add_ref_in_method(IndexPreTransform, 'prepend_transform', 0)
+add_ref_in_constructor(IndexIVFPQ, 0)
+add_ref_in_constructor(IndexIVFPQR, 0)
+add_ref_in_constructor(IndexIVFPQFastScan, 0)
+add_ref_in_constructor(IndexIVFResidualQuantizer, 0)
+add_ref_in_constructor(IndexIVFLocalSearchQuantizer, 0)
+add_ref_in_constructor(IndexIVFResidualQuantizerFastScan, 0)
+add_ref_in_constructor(IndexIVFLocalSearchQuantizerFastScan, 0)
+add_ref_in_constructor(IndexIVFSpectralHash, 0)
+add_ref_in_method_explicit_own(IndexIVFSpectralHash, "replace_vt")
+
+add_ref_in_constructor(Index2Layer, 0)
+add_ref_in_constructor(Level1Quantizer, 0)
+add_ref_in_constructor(IndexIVFScalarQuantizer, 0)
+add_ref_in_constructor(IndexRowwiseMinMax, 0)
+add_ref_in_constructor(IndexRowwiseMinMaxFP16, 0)
+add_ref_in_constructor(IndexIDMap, 0)
+add_ref_in_constructor(IndexIDMap2, 0)
+add_ref_in_constructor(IndexHNSW, 0)
+add_ref_in_method(IndexShards, 'add_shard', 0)
+add_ref_in_method(IndexBinaryShards, 'add_shard', 0)
+add_ref_in_constructor(IndexRefineFlat, {2: [0], 1: [0]})
+add_ref_in_constructor(IndexRefine, {2: [0, 1]})
+
+add_ref_in_constructor(IndexBinaryIVF, 0)
+add_ref_in_constructor(IndexBinaryFromFloat, 0)
+add_ref_in_constructor(IndexBinaryIDMap, 0)
+add_ref_in_constructor(IndexBinaryIDMap2, 0)
+
+add_ref_in_method(IndexReplicas, 'addIndex', 0)
+add_ref_in_method(IndexBinaryReplicas, 'addIndex', 0)
+
+add_ref_in_constructor(BufferedIOWriter, 0)
+add_ref_in_constructor(BufferedIOReader, 0)
+
+add_ref_in_constructor(IDSelectorNot, 0)
+add_ref_in_constructor(IDSelectorAnd, slice(2))
+add_ref_in_constructor(IDSelectorOr, slice(2))
+add_ref_in_constructor(IDSelectorXOr, slice(2))
+add_ref_in_constructor(IDSelectorTranslated, slice(2))
+
+add_ref_in_constructor(IDSelectorXOr, slice(2))
+add_ref_in_constructor(IndexIVFIndependentQuantizer, slice(3))
+
+# seems really marginal...
+# remove_ref_from_method(IndexReplicas, 'removeIndex', 0)
+
+
+######################################################
+# search_with_parameters interface
+######################################################
+
+search_with_parameters_c = search_with_parameters
+
+
+def search_with_parameters(index, x, k, params=None, output_stats=False):
+ x = np.ascontiguousarray(x, dtype='float32')
+ n, d = x.shape
+ assert d == index.d
+ if not params:
+ # if not provided use the ones set in the IVF object
+ params = IVFSearchParameters()
+ index_ivf = extract_index_ivf(index)
+ params.nprobe = index_ivf.nprobe
+ params.max_codes = index_ivf.max_codes
+ nb_dis = np.empty(1, 'uint64')
+ ms_per_stage = np.empty(3, 'float64')
+ distances = np.empty((n, k), dtype=np.float32)
+ labels = np.empty((n, k), dtype=np.int64)
+ search_with_parameters_c(
+ index, n, swig_ptr(x),
+ k, swig_ptr(distances),
+ swig_ptr(labels),
+ params, swig_ptr(nb_dis), swig_ptr(ms_per_stage)
+ )
+ if not output_stats:
+ return distances, labels
+ else:
+ stats = {
+ 'ndis': nb_dis[0],
+ 'pre_transform_ms': ms_per_stage[0],
+ 'coarse_quantizer_ms': ms_per_stage[1],
+ 'invlist_scan_ms': ms_per_stage[2],
+ }
+ return distances, labels, stats
+
+
+range_search_with_parameters_c = range_search_with_parameters
+
+
+def range_search_with_parameters(index, x, radius, params=None, output_stats=False):
+ x = np.ascontiguousarray(x, dtype='float32')
+ n, d = x.shape
+ assert d == index.d
+ if not params:
+ # if not provided use the ones set in the IVF object
+ params = IVFSearchParameters()
+ index_ivf = extract_index_ivf(index)
+ params.nprobe = index_ivf.nprobe
+ params.max_codes = index_ivf.max_codes
+ nb_dis = np.empty(1, 'uint64')
+ ms_per_stage = np.empty(3, 'float64')
+ res = RangeSearchResult(n)
+ range_search_with_parameters_c(
+ index, n, swig_ptr(x),
+ radius, res,
+ params, swig_ptr(nb_dis), swig_ptr(ms_per_stage)
+ )
+ lims = rev_swig_ptr(res.lims, n + 1).copy()
+ nd = int(lims[-1])
+ Dout = rev_swig_ptr(res.distances, nd).copy()
+ Iout = rev_swig_ptr(res.labels, nd).copy()
+ if not output_stats:
+ return lims, Dout, Iout
+ else:
+ stats = {
+ 'ndis': nb_dis[0],
+ 'pre_transform_ms': ms_per_stage[0],
+ 'coarse_quantizer_ms': ms_per_stage[1],
+ 'invlist_scan_ms': ms_per_stage[2],
+ }
+ return lims, Dout, Iout, stats
+
+
+# IndexProxy was renamed to IndexReplicas, remap the old name for any old code
+# people may have
+IndexProxy = IndexReplicas
+ConcatenatedInvertedLists = HStackInvertedLists
+IndexResidual = IndexResidualQuantizer
+
+IVFSearchParameters = SearchParametersIVF
+
+###########################################
+# serialization of indexes to byte arrays
+###########################################
+
+
+def serialize_index(index, io_flags=0):
+ """ convert an index to a numpy uint8 array """
+ writer = VectorIOWriter()
+ write_index(index, writer, io_flags)
+ return vector_to_array(writer.data)
+
+
+def deserialize_index(data, io_flags=0):
+ reader = VectorIOReader()
+ copy_array_to_vector(data, reader.data)
+ return read_index(reader, io_flags)
+
+
+def serialize_index_binary(index):
+ """ convert an index to a numpy uint8 array """
+ writer = VectorIOWriter()
+ write_index_binary(index, writer)
+ return vector_to_array(writer.data)
+
+
+def deserialize_index_binary(data):
+ reader = VectorIOReader()
+ copy_array_to_vector(data, reader.data)
+ return read_index_binary(reader)
+
+
+class TimeoutGuard:
+ def __init__(self, timeout_in_seconds: float):
+ self.timeout = timeout_in_seconds
+
+ def __enter__(self):
+ TimeoutCallback.reset(self.timeout)
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ PythonInterruptCallback.reset()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/array_conversions.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/array_conversions.py
new file mode 100644
index 0000000..b62c59e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/array_conversions.py
@@ -0,0 +1,183 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# @nolint
+
+# not linting this file because it imports * from swigfaiss, which
+# causes a ton of useless warnings.
+
+import numpy as np
+import array
+import warnings
+
+from faiss.loader import *
+
+###########################################
+# Utility to add a deprecation warning to
+# classes from the SWIG interface
+###########################################
+
+def _make_deprecated_swig_class(deprecated_name, base_name):
+ """
+ Dynamically construct deprecated classes as wrappers around renamed ones
+
+ The deprecation warning added in their __new__-method will trigger upon
+ construction of an instance of the class, but only once per session.
+
+ We do this here (in __init__.py) because the base classes are defined in
+ the SWIG interface, making it cumbersome to add the deprecation there.
+
+ Parameters
+ ----------
+ deprecated_name : string
+ Name of the class to be deprecated; _not_ present in SWIG interface.
+ base_name : string
+ Name of the class that is replacing deprecated_name; must already be
+ imported into the current namespace.
+
+ Returns
+ -------
+ None
+ However, the deprecated class gets added to the faiss namespace
+ """
+ base_class = globals()[base_name]
+
+ def new_meth(cls, *args, **kwargs):
+ msg = f"The class faiss.{deprecated_name} is deprecated in favour of faiss.{base_name}!"
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
+ instance = super(base_class, cls).__new__(cls, *args, **kwargs)
+ return instance
+
+ # three-argument version of "type" uses (name, tuple-of-bases, dict-of-attributes)
+ klazz = type(deprecated_name, (base_class,), {"__new__": new_meth})
+
+ # this ends up adding the class to the "faiss" namespace, in a way that it
+ # is available both through "import faiss" and "from faiss import *"
+ globals()[deprecated_name] = klazz
+
+
+###########################################
+# numpy array / std::vector conversions
+###########################################
+
+sizeof_long = array.array('l').itemsize
+deprecated_name_map = {
+ # deprecated: replacement
+ 'Float': 'Float32',
+ 'Double': 'Float64',
+ 'Char': 'Int8',
+ 'Int': 'Int32',
+ 'Long': 'Int32' if sizeof_long == 4 else 'Int64',
+ 'LongLong': 'Int64',
+ 'Byte': 'UInt8',
+ # previously misspelled variant
+ 'Uint64': 'UInt64',
+}
+
+for depr_prefix, base_prefix in deprecated_name_map.items():
+ _make_deprecated_swig_class(depr_prefix + "Vector", base_prefix + "Vector")
+
+ # same for the three legacy *VectorVector classes
+ if depr_prefix in ['Float', 'Long', 'Byte']:
+ _make_deprecated_swig_class(depr_prefix + "VectorVector",
+ base_prefix + "VectorVector")
+
+# mapping from vector names in swigfaiss.swig and the numpy dtype names
+# TODO: once deprecated classes are removed, remove the dict and just use .lower() below
+vector_name_map = {
+ 'Float32': 'float32',
+ 'Float64': 'float64',
+ 'Int8': 'int8',
+ 'Int16': 'int16',
+ 'Int32': 'int32',
+ 'Int64': 'int64',
+ 'UInt8': 'uint8',
+ 'UInt16': 'uint16',
+ 'UInt32': 'uint32',
+ 'UInt64': 'uint64',
+ **{k: v.lower() for k, v in deprecated_name_map.items()}
+}
+
+
+def vector_to_array(v):
+ """ convert a C++ vector to a numpy array """
+ classname = v.__class__.__name__
+ if classname.startswith('AlignedTable'):
+ return AlignedTable_to_array(v)
+ if classname.startswith('MaybeOwnedVector'):
+ dtype = np.dtype(vector_name_map[classname[16:]])
+ a = np.empty(v.size(), dtype=dtype)
+ if v.size() > 0:
+ memcpy(swig_ptr(a), v.data(), a.nbytes)
+ return a
+
+ assert classname.endswith('Vector')
+ dtype = np.dtype(vector_name_map[classname[:-6]])
+ a = np.empty(v.size(), dtype=dtype)
+ if v.size() > 0:
+ memcpy(swig_ptr(a), v.data(), a.nbytes)
+ return a
+
+
+def vector_float_to_array(v):
+ return vector_to_array(v)
+
+
+def copy_array_to_vector(a, v):
+ """ copy a numpy array to a vector """
+ n, = a.shape
+ classname = v.__class__.__name__
+ if classname.startswith('MaybeOwnedVector'):
+ assert v.is_owned, 'cannot copy to an non-owned MaybeOwnedVector'
+ dtype = np.dtype(vector_name_map[classname[16:]])
+ assert dtype == a.dtype, (
+ 'cannot copy a %s array to a %s (should be %s)' % (
+ a.dtype, classname, dtype))
+ v.resize(n)
+ if n > 0:
+ memcpy(v.data(), swig_ptr(a), a.nbytes)
+ return
+
+ assert classname.endswith('Vector')
+ dtype = np.dtype(vector_name_map[classname[:-6]])
+ assert dtype == a.dtype, (
+ 'cannot copy a %s array to a %s (should be %s)' % (
+ a.dtype, classname, dtype))
+ v.resize(n)
+ if n > 0:
+ memcpy(v.data(), swig_ptr(a), a.nbytes)
+
+# same for AlignedTable
+
+
+def copy_array_to_AlignedTable(a, v):
+ n, = a.shape
+ # TODO check class name
+ assert v.itemsize() == a.itemsize
+ v.resize(n)
+ if n > 0:
+ memcpy(v.get(), swig_ptr(a), a.nbytes)
+
+
+def array_to_AlignedTable(a):
+ if a.dtype == 'uint16':
+ v = AlignedTableUint16(a.size)
+ elif a.dtype == 'uint8':
+ v = AlignedTableUint8(a.size)
+ else:
+ assert False
+ copy_array_to_AlignedTable(a, v)
+ return v
+
+
+def AlignedTable_to_array(v):
+ """ convert an AlignedTable to a numpy array """
+ classname = v.__class__.__name__
+ assert classname.startswith('AlignedTable')
+ dtype = classname[12:].lower()
+ a = np.empty(v.size(), dtype=dtype)
+ if a.size > 0:
+ memcpy(swig_ptr(a), v.data(), a.nbytes)
+ return a
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/class_wrappers.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/class_wrappers.py
new file mode 100644
index 0000000..71756f5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/class_wrappers.py
@@ -0,0 +1,1407 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import inspect
+
+import faiss
+import numpy as np
+
+from faiss.loader import (
+ DirectMap,
+ IDSelector,
+ IDSelectorArray,
+ IDSelectorBatch,
+ OperatingPoints,
+ RangeSearchResult,
+ rev_swig_ptr,
+ swig_ptr,
+ try_extract_index_ivf,
+)
+
+##################################################################
+# The functions below add or replace some methods for classes
+# this is to be able to pass in numpy arrays directly
+# The C++ version of the classnames will be suffixed with _c
+#
+# The docstrings in the wrappers are intended to be similar to numpy
+# comments, they will appear with help(Class.method) or ?Class.method
+# For methods that are not replaced, the C++ documentation will be used if
+# swig 4.x is run with -doxygen.
+##################################################################
+
+# For most arrays we force the convesion to the target type with
+# np.ascontiguousarray, but for uint8 codes, we raise a type error
+# because it is unclear how the conversion should occur: with a view
+# (= cast) or conversion?
+
+def _check_dtype_uint8(codes):
+ if codes.dtype != 'uint8':
+ raise TypeError("Input argument %s must be ndarray of dtype "
+ " uint8, but found %s" % ("codes", codes.dtype))
+ return np.ascontiguousarray(codes)
+
+
+def replace_method(the_class, name, replacement, ignore_missing=False):
+ """ Replaces a method in a class with another version. The old method
+ is renamed to method_name_c (because presumably it was implemented in C) """
+ try:
+ orig_method = getattr(the_class, name)
+ except AttributeError:
+ if ignore_missing:
+ return
+ raise
+ if orig_method.__name__ == 'replacement_' + name:
+ # replacement was done in parent class
+ return
+ setattr(the_class, name + '_c', orig_method)
+ setattr(the_class, name, replacement)
+
+
+def handle_Clustering(the_class):
+
+ def replacement_train(self, x, index, weights=None):
+ """Perform clustering on a set of vectors. The index is used for assignment.
+
+ Parameters
+ ----------
+ x : array_like
+ Training vectors, shape (n, self.d). `dtype` must be float32.
+ index : faiss.Index
+ Index used for assignment. The dimension of the index should be `self.d`.
+ weights : array_like, optional
+ Per training sample weight (size n) used when computing the weighted
+ average to obtain the centroid (default is 1 for all training vectors).
+ """
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d
+ if weights is not None:
+ weights = np.ascontiguousarray(weights, dtype='float32')
+ assert weights.shape == (n, )
+ self.train_c(n, swig_ptr(x), index, swig_ptr(weights))
+ else:
+ self.train_c(n, swig_ptr(x), index)
+
+ def replacement_train_encoded(self, x, codec, index, weights=None):
+ """ Perform clustering on a set of compressed vectors. The index is used for assignment.
+ The decompression is performed on-the-fly.
+
+ Parameters
+ ----------
+ x : array_like
+ Training vectors, shape (n, codec.code_size()). `dtype` must be `uint8`.
+ codec : faiss.Index
+ Index used to decode the vectors. Should have dimension `self.d`.
+ index : faiss.Index
+ Index used for assignment. The dimension of the index should be `self.d`.
+ weights : array_like, optional
+ Per training sample weight (size n) used when computing the weighted
+ average to obtain the centroid (default is 1 for all training vectors).
+ """
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == codec.sa_code_size()
+ assert codec.d == index.d
+ if weights is not None:
+ weights = np.ascontiguousarray(weights, dtype='float32')
+ assert weights.shape == (n, )
+ self.train_encoded_c(n, swig_ptr(x), codec,
+ index, swig_ptr(weights))
+ else:
+ self.train_encoded_c(n, swig_ptr(x), codec, index)
+
+ replace_method(the_class, 'train', replacement_train)
+ replace_method(the_class, 'train_encoded', replacement_train_encoded)
+
+
+def handle_Clustering1D(the_class):
+
+ def replacement_train_exact(self, x):
+ """Perform clustering on a set of 1D vectors.
+
+ Parameters
+ ----------
+ x : array_like
+ Training vectors, shape (n, 1). `dtype` must be float32.
+ """
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d
+ self.train_exact_c(n, swig_ptr(x))
+
+ replace_method(the_class, 'train_exact', replacement_train_exact)
+
+
+def handle_Quantizer(the_class):
+
+ def replacement_train(self, x):
+ """ Train the quantizer on a set of training vectors.
+
+ Parameters
+ ----------
+ x : array_like
+ Training vectors, shape (n, self.d). `dtype` must be float32.
+ """
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d
+ self.train_c(n, swig_ptr(x))
+
+ def replacement_compute_codes(self, x):
+ """ Compute the codes corresponding to a set of vectors.
+
+ Parameters
+ ----------
+ x : array_like
+ Vectors to encode, shape (n, self.d). `dtype` must be float32.
+
+ Returns
+ -------
+ codes : array_like
+ Corresponding code for each vector, shape (n, self.code_size)
+ and `dtype` uint8.
+ """
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d
+ codes = np.empty((n, self.code_size), dtype='uint8')
+ self.compute_codes_c(swig_ptr(x), swig_ptr(codes), n)
+ return codes
+
+ def replacement_decode(self, codes):
+ """Reconstruct an approximation of vectors given their codes.
+
+ Parameters
+ ----------
+ codes : array_like
+ Codes to decode, shape (n, self.code_size). `dtype` must be uint8.
+
+ Returns
+ -------
+ Reconstructed vectors for each code, shape `(n, d)` and `dtype` float32.
+ """
+ n, cs = codes.shape
+ codes = _check_dtype_uint8(codes)
+ assert cs == self.code_size
+ x = np.empty((n, self.d), dtype='float32')
+ self.decode_c(swig_ptr(codes), swig_ptr(x), n)
+ return x
+
+ replace_method(the_class, 'train', replacement_train)
+ replace_method(the_class, 'compute_codes', replacement_compute_codes)
+ replace_method(the_class, 'decode', replacement_decode)
+
+
+def handle_NSG(the_class):
+
+ def replacement_build(self, x, graph):
+ n, d = x.shape
+ assert d == self.d
+ assert graph.ndim == 2
+ assert graph.shape[0] == n
+ K = graph.shape[1]
+ x = np.ascontiguousarray(x, dtype='float32')
+ graph = np.ascontiguousarray(graph, dtype='int64')
+ self.build_c(n, swig_ptr(x), swig_ptr(graph), K)
+
+ replace_method(the_class, 'build', replacement_build)
+
+
+def handle_Index(the_class):
+
+ def replacement_add(self, x):
+ """Adds vectors to the index.
+ The index must be trained before vectors can be added to it.
+ The vectors are implicitly numbered in sequence. When `n` vectors are
+ added to the index, they are given ids `ntotal`, `ntotal + 1`, ..., `ntotal + n - 1`.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ """
+
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+ self.add_c(n, swig_ptr(x))
+
+ def replacement_add_with_ids(self, x, ids):
+ """Adds vectors with arbitrary ids to the index (not all indexes support this).
+ The index must be trained before vectors can be added to it.
+ Vector `i` is stored in `x[i]` and has id `ids[i]`.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ ids : array_like
+ Array if ids of size n. The ids must be of type `int64`. Note that `-1` is reserved
+ in result lists to mean "not found" so it's better to not use it as an id.
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+ ids = np.ascontiguousarray(ids, dtype='int64')
+ assert ids.shape == (n, ), 'not same nb of vectors as ids'
+ self.add_with_ids_c(n, swig_ptr(x), swig_ptr(ids))
+
+ def replacement_assign(self, x, k, labels=None):
+ """Find the k nearest neighbors of the set of vectors x in the index.
+ This is the same as the `search` method, but discards the distances.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ labels : array_like, optional
+ Labels array to store the results.
+
+ Returns
+ -------
+ labels: array_like
+ Labels of the nearest neighbors, shape (n, k).
+ When not enough results are found, the label is set to -1
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+
+ if labels is None:
+ labels = np.empty((n, k), dtype=np.int64)
+ else:
+ assert labels.shape == (n, k)
+
+ self.assign_c(n, swig_ptr(x), swig_ptr(labels), k)
+ return labels
+
+ def replacement_train(self, x):
+ """Trains the index on a representative set of vectors.
+ The index must be trained before vectors can be added to it.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+ self.train_c(n, swig_ptr(x))
+
+ def replacement_search(self, x, k, *, params=None, D=None, I=None):
+ """Find the k nearest neighbors of the set of vectors x in the index.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ params : SearchParameters
+ Search parameters of the current search (overrides the class-level params)
+ D : array_like, optional
+ Distance array to store the result.
+ I : array_like, optional
+ Labels array to store the results.
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (n, k). When not enough results are found
+ the label is set to +Inf or -Inf.
+ I : array_like
+ Labels of the nearest neighbors, shape (n, k).
+ When not enough results are found, the label is set to -1
+ """
+
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d
+
+ assert k > 0
+
+ if D is None:
+ D = np.empty((n, k), dtype=np.float32)
+ else:
+ assert D.shape == (n, k)
+
+ if I is None:
+ I = np.empty((n, k), dtype=np.int64)
+ else:
+ assert I.shape == (n, k)
+
+ self.search_c(n, swig_ptr(x), k, swig_ptr(D), swig_ptr(I), params)
+ return D, I
+
+ def replacement_search_and_reconstruct(self, x, k, *, params=None, D=None, I=None, R=None):
+ """Find the k nearest neighbors of the set of vectors x in the index,
+ and return an approximation of these vectors.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ params : SearchParameters
+ Search parameters of the current search (overrides the class-level params)
+ D : array_like, optional
+ Distance array to store the result.
+ I : array_like, optional
+ Labels array to store the result.
+ R : array_like, optional
+ reconstruction array to store
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (n, k). When not enough results are found
+ the label is set to +Inf or -Inf.
+ I : array_like
+ Labels of the nearest neighbors, shape (n, k). When not enough results are found,
+ the label is set to -1
+ R : array_like
+ Approximate (reconstructed) nearest neighbor vectors, shape (n, k, d).
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+
+ assert k > 0
+
+ if D is None:
+ D = np.empty((n, k), dtype=np.float32)
+ else:
+ assert D.shape == (n, k)
+
+ if I is None:
+ I = np.empty((n, k), dtype=np.int64)
+ else:
+ assert I.shape == (n, k)
+
+ if R is None:
+ R = np.empty((n, k, d), dtype=np.float32)
+ else:
+ assert R.shape == (n, k, d)
+
+ self.search_and_reconstruct_c(
+ n, swig_ptr(x),
+ k, swig_ptr(D),
+ swig_ptr(I), swig_ptr(R), params
+ )
+ return D, I, R
+
+ def replacement_search_and_return_codes(
+ self, x, k, *,
+ include_listnos=False, params=None, D=None, I=None, codes=None):
+ """Find the k nearest neighbors of the set of vectors x in the index,
+ and return the codes stored for these vectors
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ params : SearchParameters
+ Search parameters of the current search (overrides the class-level params)
+ include_listnos : bool, optional
+ whether to include the list ids in the first bytes of each code
+ D : array_like, optional
+ Distance array to store the result.
+ I : array_like, optional
+ Labels array to store the result.
+ codes : array_like, optional
+ codes array to store
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (n, k). When not enough results are found
+ the label is set to +Inf or -Inf.
+ I : array_like
+ Labels of the nearest neighbors, shape (n, k). When not enough results are found,
+ the label is set to -1
+ R : array_like
+ Approximate (reconstructed) nearest neighbor vectors, shape (n, k, d).
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+
+ assert k > 0
+
+ if D is None:
+ D = np.empty((n, k), dtype=np.float32)
+ else:
+ assert D.shape == (n, k)
+
+ if I is None:
+ I = np.empty((n, k), dtype=np.int64)
+ else:
+ assert I.shape == (n, k)
+
+ code_size_1 = self.code_size
+ if include_listnos:
+ code_size_1 += self.coarse_code_size()
+
+ if codes is None:
+ codes = np.empty((n, k, code_size_1), dtype=np.uint8)
+ else:
+ assert codes.shape == (n, k, code_size_1)
+
+ self.search_and_return_codes_c(
+ n, swig_ptr(x),
+ k, swig_ptr(D),
+ swig_ptr(I), swig_ptr(codes), include_listnos,
+ params
+ )
+ return D, I, codes
+
+ def replacement_remove_ids(self, x):
+ """Remove some ids from the index.
+ This is a O(ntotal) operation by default, so could be expensive.
+
+ Parameters
+ ----------
+ x : array_like or faiss.IDSelector
+ Either an IDSelector that returns True for vectors to remove, or a
+ list of ids to reomove (1D array of int64). When `x` is a list,
+ it is wrapped into an IDSelector.
+
+ Returns
+ -------
+ n_remove: int
+ number of vectors that were removed
+ """
+ if isinstance(x, IDSelector):
+ sel = x
+ else:
+ assert x.ndim == 1
+ index_ivf = try_extract_index_ivf(self)
+ x = np.ascontiguousarray(x, dtype='int64')
+ if index_ivf and index_ivf.direct_map.type == DirectMap.Hashtable:
+ sel = IDSelectorArray(x.size, swig_ptr(x))
+ else:
+ sel = IDSelectorBatch(x.size, swig_ptr(x))
+ return self.remove_ids_c(sel)
+
+ def replacement_reconstruct(self, key, x=None):
+ """Approximate reconstruction of one vector from the index.
+
+ Parameters
+ ----------
+ key : int
+ Id of the vector to reconstruct
+ x : array_like, optional
+ pre-allocated array to store the results
+
+ Returns
+ -------
+ x : array_like reconstructed vector, size `self.d`, `dtype`=float32
+ """
+ if x is None:
+ x = np.empty(self.d, dtype=np.float32)
+ else:
+ assert x.shape == (self.d, )
+
+ self.reconstruct_c(key, swig_ptr(x))
+ return x
+
+ def replacement_reconstruct_batch(self, key, x=None):
+ """Approximate reconstruction of several vectors from the index.
+
+ Parameters
+ ----------
+ key : array of ints
+ Ids of the vectors to reconstruct
+ x : array_like, optional
+ pre-allocated array to store the results
+
+ Returns
+ -------
+ x : array_like
+ reconstrcuted vectors, size `len(key), self.d`
+ """
+ key = np.ascontiguousarray(key, dtype='int64')
+ n, = key.shape
+ if x is None:
+ x = np.empty((n, self.d), dtype=np.float32)
+ else:
+ assert x.shape == (n, self.d)
+ self.reconstruct_batch_c(n, swig_ptr(key), swig_ptr(x))
+ return x
+
+ def replacement_reconstruct_n(self, n0=0, ni=-1, x=None):
+ """Approximate reconstruction of vectors `n0` ... `n0 + ni - 1` from the index.
+ Missing vectors trigger an exception.
+
+ Parameters
+ ----------
+ n0 : int
+ Id of the first vector to reconstruct (default 0)
+ ni : int
+ Number of vectors to reconstruct (-1 = default = ntotal)
+ x : array_like, optional
+ pre-allocated array to store the results
+
+ Returns
+ -------
+ x : array_like
+ Reconstructed vectors, size (`ni`, `self.d`), `dtype`=float32
+ """
+ if ni == -1:
+ ni = self.ntotal - n0
+ if x is None:
+ x = np.empty((ni, self.d), dtype=np.float32)
+ else:
+ assert x.shape == (ni, self.d)
+
+ self.reconstruct_n_c(n0, ni, swig_ptr(x))
+ return x
+
+ def replacement_update_vectors(self, keys, x):
+ n = keys.size
+ assert keys.shape == (n, )
+ assert x.shape == (n, self.d)
+ x = np.ascontiguousarray(x, dtype='float32')
+ keys = np.ascontiguousarray(keys, dtype='int64')
+ self.update_vectors_c(n, swig_ptr(keys), swig_ptr(x))
+
+ # No support passed-in for output buffers
+ def replacement_range_search(self, x, thresh, *, params=None):
+ """Search vectors that are within a distance of the query vectors.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ thresh : float
+ Threshold to select neighbors. All elements within this radius are returned,
+ except for maximum inner product indexes, where the elements above the
+ threshold are returned
+ params : SearchParameters
+ Search parameters of the current search (overrides the class-level params)
+
+
+ Returns
+ -------
+ lims: array_like
+ Starting index of the results for each query vector, size n+1.
+ D : array_like
+ Distances of the nearest neighbors, shape `lims[n]`. The distances for
+ query i are in `D[lims[i]:lims[i+1]]`.
+ I : array_like
+ Labels of nearest neighbors, shape `lims[n]`. The labels for query i
+ are in `I[lims[i]:lims[i+1]]`.
+
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+ thresh = float(thresh)
+
+ res = RangeSearchResult(n)
+ self.range_search_c(n, swig_ptr(x), thresh, res, params)
+ # get pointers and copy them
+ lims = rev_swig_ptr(res.lims, n + 1).copy()
+ nd = int(lims[-1])
+ D = rev_swig_ptr(res.distances, nd).copy()
+ I = rev_swig_ptr(res.labels, nd).copy()
+ return lims, D, I
+
+ def replacement_search_preassigned(self, x, k, Iq, Dq, *, params=None, D=None, I=None):
+ """Find the k nearest neighbors of the set of vectors x in an IVF index,
+ with precalculated coarse quantization assignment.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ Dq : array_like, optional
+ Distance array to the centroids, size (n, nprobe)
+ Iq : array_like, optional
+ Nearest centroids, size (n, nprobe)
+
+ params : SearchParameters
+ Search parameters of the current search (overrides the class-level params)
+ D : array_like, optional
+ Distance array to store the result.
+ I : array_like, optional
+ Labels array to store the results.
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (n, k). When not enough results are found
+ the label is set to +Inf or -Inf.
+ I : array_like
+ Labels of the nearest neighbors, shape (n, k).
+ When not enough results are found, the label is set to -1
+ """
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d
+ assert k > 0
+
+ if D is None:
+ D = np.empty((n, k), dtype=np.float32)
+ else:
+ assert D.shape == (n, k)
+
+ if I is None:
+ I = np.empty((n, k), dtype=np.int64)
+ else:
+ assert I.shape == (n, k)
+
+ Iq = np.ascontiguousarray(Iq, dtype='int64')
+ assert params is None, "params not supported"
+ assert Iq.shape == (n, self.nprobe)
+
+ if Dq is not None:
+ Dq = np.ascontiguousarray(Dq, dtype='float32')
+ assert Dq.shape == Iq.shape
+
+ self.search_preassigned_c(
+ n, swig_ptr(x),
+ k,
+ swig_ptr(Iq), swig_ptr(Dq),
+ swig_ptr(D), swig_ptr(I),
+ False
+ )
+ return D, I
+
+ def replacement_range_search_preassigned(self, x, thresh, Iq, Dq, *, params=None):
+ """Search vectors that are within a distance of the query vectors.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ thresh : float
+ Threshold to select neighbors. All elements within this radius are returned,
+ except for maximum inner product indexes, where the elements above the
+ threshold are returned
+ Iq : array_like, optional
+ Nearest centroids, size (n, nprobe)
+ Dq : array_like, optional
+ Distance array to the centroids, size (n, nprobe)
+ params : SearchParameters
+ Search parameters of the current search (overrides the class-level params)
+
+
+ Returns
+ -------
+ lims: array_like
+ Starting index of the results for each query vector, size n+1.
+ D : array_like
+ Distances of the nearest neighbors, shape `lims[n]`. The distances for
+ query i are in `D[lims[i]:lims[i+1]]`.
+ I : array_like
+ Labels of nearest neighbors, shape `lims[n]`. The labels for query i
+ are in `I[lims[i]:lims[i+1]]`.
+
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+
+ Iq = np.ascontiguousarray(Iq, dtype='int64')
+ assert params is None, "params not supported"
+ assert Iq.shape == (n, self.nprobe)
+
+ if Dq is not None:
+ Dq = np.ascontiguousarray(Dq, dtype='float32')
+ assert Dq.shape == Iq.shape
+
+ thresh = float(thresh)
+ res = RangeSearchResult(n)
+ self.range_search_preassigned_c(
+ n, swig_ptr(x), thresh,
+ swig_ptr(Iq), swig_ptr(Dq),
+ res
+ )
+ # get pointers and copy them
+ lims = rev_swig_ptr(res.lims, n + 1).copy()
+ nd = int(lims[-1])
+ D = rev_swig_ptr(res.distances, nd).copy()
+ I = rev_swig_ptr(res.labels, nd).copy()
+ return lims, D, I
+
+ def replacement_sa_encode(self, x, codes=None):
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+
+ if codes is None:
+ codes = np.empty((n, self.sa_code_size()), dtype=np.uint8)
+ else:
+ assert codes.shape == (n, self.sa_code_size())
+
+ self.sa_encode_c(n, swig_ptr(x), swig_ptr(codes))
+ return codes
+
+ def replacement_sa_decode(self, codes, x=None):
+ n, cs = codes.shape
+ assert cs == self.sa_code_size()
+ codes = _check_dtype_uint8(codes)
+
+ if x is None:
+ x = np.empty((n, self.d), dtype=np.float32)
+ else:
+ assert x.shape == (n, self.d)
+
+ self.sa_decode_c(n, swig_ptr(codes), swig_ptr(x))
+ return x
+
+ def replacement_add_sa_codes(self, codes, ids=None):
+ n, cs = codes.shape
+ assert cs == self.sa_code_size()
+ codes = _check_dtype_uint8(codes)
+
+ if ids is not None:
+ assert ids.shape == (n,)
+ ids = swig_ptr(ids)
+ self.add_sa_codes_c(n, swig_ptr(codes), ids)
+
+ def replacement_permute_entries(self, perm):
+ n, = perm.shape
+ assert n == self.ntotal
+ perm = np.ascontiguousarray(perm, dtype='int64')
+ self.permute_entries_c(faiss.swig_ptr(perm))
+
+ replace_method(the_class, 'add', replacement_add)
+ replace_method(the_class, 'add_with_ids', replacement_add_with_ids)
+ replace_method(the_class, 'assign', replacement_assign)
+ replace_method(the_class, 'train', replacement_train)
+ replace_method(the_class, 'search', replacement_search)
+ replace_method(the_class, 'remove_ids', replacement_remove_ids)
+ replace_method(the_class, 'reconstruct', replacement_reconstruct)
+ replace_method(the_class, 'reconstruct_batch',
+ replacement_reconstruct_batch)
+ replace_method(the_class, 'reconstruct_n', replacement_reconstruct_n)
+ replace_method(the_class, 'range_search', replacement_range_search)
+ replace_method(the_class, 'update_vectors', replacement_update_vectors,
+ ignore_missing=True)
+ replace_method(the_class, 'search_and_reconstruct',
+ replacement_search_and_reconstruct, ignore_missing=True)
+ replace_method(the_class, 'search_and_return_codes',
+ replacement_search_and_return_codes, ignore_missing=True)
+
+ # these ones are IVF-specific
+ replace_method(the_class, 'search_preassigned',
+ replacement_search_preassigned, ignore_missing=True)
+ replace_method(the_class, 'range_search_preassigned',
+ replacement_range_search_preassigned, ignore_missing=True)
+ replace_method(the_class, 'sa_encode', replacement_sa_encode)
+ replace_method(the_class, 'sa_decode', replacement_sa_decode)
+ replace_method(the_class, 'add_sa_codes', replacement_add_sa_codes)
+ replace_method(the_class, 'permute_entries', replacement_permute_entries,
+ ignore_missing=True)
+
+ # get/set state for pickle
+ # the data is serialized to std::vector -> numpy array -> python bytes
+ # so not very efficient for now.
+
+ def index_getstate(self):
+ return {"this": faiss.serialize_index(self).tobytes()}
+
+ def index_setstate(self, st):
+ index2 = faiss.deserialize_index(np.frombuffer(st["this"], dtype="uint8"))
+ self.this = index2.this
+
+ the_class.__getstate__ = index_getstate
+ the_class.__setstate__ = index_setstate
+
+
+def handle_IndexBinary(the_class):
+
+ def replacement_add(self, x):
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == self.code_size
+ self.add_c(n, swig_ptr(x))
+
+ def replacement_add_with_ids(self, x, ids):
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ ids = np.ascontiguousarray(ids, dtype='int64')
+ assert d == self.code_size
+ assert ids.shape == (n, ), 'not same nb of vectors as ids'
+ self.add_with_ids_c(n, swig_ptr(x), swig_ptr(ids))
+
+ def replacement_train(self, x):
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == self.code_size
+ self.train_c(n, swig_ptr(x))
+
+ def replacement_reconstruct(self, key):
+ x = np.empty(self.code_size, dtype=np.uint8)
+ self.reconstruct_c(key, swig_ptr(x))
+ return x
+
+ def replacement_reconstruct_n(self, n0=0, ni=-1, x=None):
+ if ni == -1:
+ ni = self.ntotal - n0
+ if x is None:
+ x = np.empty((ni, self.code_size), dtype=np.uint8)
+ else:
+ assert x.shape == (ni, self.code_size)
+
+ self.reconstruct_n_c(n0, ni, swig_ptr(x))
+ return x
+
+ def replacement_search(self, x, k, *, params=None):
+ x = _check_dtype_uint8(x)
+ n, d = x.shape
+ assert d == self.code_size
+ assert k > 0
+ distances = np.empty((n, k), dtype=np.int32)
+ labels = np.empty((n, k), dtype=np.int64)
+ self.search_c(n, swig_ptr(x),
+ k, swig_ptr(distances),
+ swig_ptr(labels),
+ params=params)
+ return distances, labels
+
+ def replacement_search_preassigned(self, x, k, Iq, Dq):
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == self.code_size
+ assert k > 0
+
+ D = np.empty((n, k), dtype=np.int32)
+ I = np.empty((n, k), dtype=np.int64)
+
+ Iq = np.ascontiguousarray(Iq, dtype='int64')
+ assert Iq.shape == (n, self.nprobe)
+
+ if Dq is not None:
+ Dq = np.ascontiguousarray(Dq, dtype='int32')
+ assert Dq.shape == Iq.shape
+
+ self.search_preassigned_c(
+ n, swig_ptr(x),
+ k,
+ swig_ptr(Iq), swig_ptr(Dq),
+ swig_ptr(D), swig_ptr(I),
+ False
+ )
+ return D, I
+
+ def replacement_range_search(self, x, thresh, *, params=None):
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == self.code_size
+ res = RangeSearchResult(n)
+ self.range_search_c(n, swig_ptr(x), thresh, res, params=params)
+ # get pointers and copy them
+ lims = rev_swig_ptr(res.lims, n + 1).copy()
+ nd = int(lims[-1])
+ D = rev_swig_ptr(res.distances, nd).copy()
+ I = rev_swig_ptr(res.labels, nd).copy()
+ return lims, D, I
+
+ def replacement_range_search_preassigned(self, x, thresh, Iq, Dq, *, params=None):
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == self.code_size
+
+ Iq = np.ascontiguousarray(Iq, dtype='int64')
+ assert params is None, "params not supported"
+ assert Iq.shape == (n, self.nprobe)
+
+ if Dq is not None:
+ Dq = np.ascontiguousarray(Dq, dtype='int32')
+ assert Dq.shape == Iq.shape
+
+ thresh = int(thresh)
+ res = RangeSearchResult(n)
+ self.range_search_preassigned_c(
+ n, swig_ptr(x), thresh,
+ swig_ptr(Iq), swig_ptr(Dq),
+ res
+ )
+ # get pointers and copy them
+ lims = rev_swig_ptr(res.lims, n + 1).copy()
+ nd = int(lims[-1])
+ D = rev_swig_ptr(res.distances, nd).copy()
+ I = rev_swig_ptr(res.labels, nd).copy()
+ return lims, D, I
+
+ def replacement_remove_ids(self, x):
+ if isinstance(x, IDSelector):
+ sel = x
+ else:
+ assert x.ndim == 1
+ x = np.ascontiguousarray(x, dtype='int64')
+ sel = IDSelectorBatch(x.size, swig_ptr(x))
+ return self.remove_ids_c(sel)
+
+ def replacement_assign(self, x, k, labels=None):
+ """Find the k nearest neighbors of the set of vectors x in the index.
+ This is the same as the `search` method, but discards the distances.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be uint8.
+ k : int
+ Number of nearest neighbors.
+ labels : array_like, optional
+ Labels array to store the results.
+
+ Returns
+ -------
+ labels: array_like
+ Labels of the nearest neighbors, shape (n, k).
+ When not enough results are found, the label is set to -1
+ """
+ n, d = x.shape
+ x = _check_dtype_uint8(x)
+ assert d == self.code_size
+ assert k > 0
+
+ if labels is None:
+ labels = np.empty((n, k), dtype=np.int64)
+ else:
+ assert labels.shape == (n, k)
+
+ self.assign_c(n, swig_ptr(x), swig_ptr(labels), k)
+ return labels
+
+ replace_method(the_class, 'add', replacement_add)
+ replace_method(the_class, 'add_with_ids', replacement_add_with_ids)
+ replace_method(the_class, 'train', replacement_train)
+ replace_method(the_class, 'search', replacement_search)
+ replace_method(the_class, 'assign', replacement_assign)
+ replace_method(the_class, 'range_search', replacement_range_search)
+ replace_method(the_class, 'reconstruct', replacement_reconstruct)
+ replace_method(the_class, 'reconstruct_n', replacement_reconstruct_n)
+ replace_method(the_class, 'remove_ids', replacement_remove_ids)
+ replace_method(the_class, 'search_preassigned',
+ replacement_search_preassigned, ignore_missing=True)
+ replace_method(the_class, 'range_search_preassigned',
+ replacement_range_search_preassigned, ignore_missing=True)
+
+
+def handle_VectorTransform(the_class):
+
+ def apply_method(self, x):
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d_in
+ y = np.empty((n, self.d_out), dtype=np.float32)
+ self.apply_noalloc(n, swig_ptr(x), swig_ptr(y))
+ return y
+
+ def replacement_reverse_transform(self, x):
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d_out
+ y = np.empty((n, self.d_in), dtype=np.float32)
+ self.reverse_transform_c(n, swig_ptr(x), swig_ptr(y))
+ return y
+
+ def replacement_vt_train(self, x):
+ n, d = x.shape
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert d == self.d_in
+ self.train_c(n, swig_ptr(x))
+
+ replace_method(the_class, 'train', replacement_vt_train)
+ # apply is reserved in Pyton...
+ the_class.apply_py = apply_method
+ the_class.apply = apply_method
+ replace_method(the_class, 'reverse_transform',
+ replacement_reverse_transform)
+
+
+def handle_AutoTuneCriterion(the_class):
+ def replacement_set_groundtruth(self, D, I):
+ if D:
+ assert I.shape == D.shape
+ self.nq, self.gt_nnn = I.shape
+ self.set_groundtruth_c(
+ self.gt_nnn, swig_ptr(D) if D else None, swig_ptr(I))
+
+ def replacement_evaluate(self, D, I):
+ assert I.shape == D.shape
+ assert I.shape == (self.nq, self.nnn)
+ return self.evaluate_c(swig_ptr(D), swig_ptr(I))
+
+ replace_method(the_class, 'set_groundtruth', replacement_set_groundtruth)
+ replace_method(the_class, 'evaluate', replacement_evaluate)
+
+
+def handle_ParameterSpace(the_class):
+ def replacement_explore(self, index, xq, crit):
+ assert xq.shape == (crit.nq, index.d)
+ xq = np.ascontiguousarray(xq, dtype='float32')
+ ops = OperatingPoints()
+ self.explore_c(index, crit.nq, swig_ptr(xq),
+ crit, ops)
+ return ops
+ replace_method(the_class, 'explore', replacement_explore)
+
+
+def handle_MatrixStats(the_class):
+ original_init = the_class.__init__
+
+ def replacement_init(self, m):
+ assert len(m.shape) == 2
+ m = np.ascontiguousarray(m, dtype='float32')
+ original_init(self, m.shape[0], m.shape[1], swig_ptr(m))
+
+ the_class.__init__ = replacement_init
+
+
+def handle_IOWriter(the_class):
+ """ add a write_bytes method """
+ def write_bytes(self, b):
+ return self(swig_ptr(b), 1, len(b))
+
+ the_class.write_bytes = write_bytes
+
+
+def handle_IOReader(the_class):
+ """ add a read_bytes method """
+
+ def read_bytes(self, totsz):
+ buf = bytearray(totsz)
+ was_read = self(swig_ptr(buf), 1, len(buf))
+ return bytes(buf[:was_read])
+
+ the_class.read_bytes = read_bytes
+
+
+def handle_IndexRowwiseMinMax(the_class):
+ def replacement_train_inplace(self, x):
+ """Trains the index on a representative set of vectors inplace.
+ The index must be trained before vectors can be added to it.
+
+ This call WILL change the values in the input array, because
+ of two scaling proceduces being performed inplace.
+
+ Parameters
+ ----------
+ x : array_like
+ Query vectors, shape (n, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ """
+ n, d = x.shape
+ assert d == self.d
+ x = np.ascontiguousarray(x, dtype='float32')
+ self.train_inplace_c(n, swig_ptr(x))
+
+ replace_method(the_class, 'train_inplace', replacement_train_inplace)
+
+
+def handle_CodePacker(the_class):
+
+ def replacement_pack_1(self, x, offset, block):
+ assert x.shape == (self.code_size,)
+ nblock, block_size = block.shape
+ assert block_size == self.block_size
+ assert 0 <= offset < block_size * self.nvec
+ self.pack_1_c(swig_ptr(x), offset, faiss.swig_ptr(block))
+
+ def replacement_unpack_1(self, block, offset):
+ nblock, block_size = block.shape
+ assert block_size == self.block_size
+ assert 0 <= offset < block_size * self.nvec
+ x = np.zeros(self.code_size, dtype='uint8')
+ self.unpack_1_c(faiss.swig_ptr(block), offset, swig_ptr(x))
+ return x
+
+ replace_method(the_class, 'pack_1', replacement_pack_1)
+ replace_method(the_class, 'unpack_1', replacement_unpack_1)
+
+######################################################
+# MapLong2Long interface
+######################################################
+
+
+def handle_MapLong2Long(the_class):
+
+ def replacement_map_add(self, keys, vals):
+ n, = keys.shape
+ assert (n,) == vals.shape
+ self.add_c(n, swig_ptr(keys), swig_ptr(vals))
+
+ def replacement_map_search_multiple(self, keys):
+ n, = keys.shape
+ vals = np.empty(n, dtype='int64')
+ self.search_multiple_c(n, swig_ptr(keys), swig_ptr(vals))
+ return vals
+
+ replace_method(the_class, 'add', replacement_map_add)
+ replace_method(the_class, 'search_multiple',
+ replacement_map_search_multiple)
+
+
+######################################################
+# SearchParameters and related interface
+######################################################
+
+
+def add_to_referenced_objects(self, ref):
+ if not hasattr(self, 'referenced_objects'):
+ self.referenced_objects = [ref]
+ else:
+ self.referenced_objects.append(ref)
+
+class RememberSwigOwnership:
+ """
+ SWIG's seattr transfers ownership of SWIG wrapped objects to the class
+ (btw this seems to contradict https://www.swig.org/Doc1.3/Python.html#Python_nn22
+ 31.4.2)
+ This interferes with how we manage ownership: with the referenced_objects
+ table. Therefore, we reset the thisown field in this context manager.
+ """
+
+ def __init__(self, obj):
+ self.obj = obj
+
+ def __enter__(self):
+ if hasattr(self.obj, "thisown"):
+ self.old_thisown = self.obj.thisown
+ else:
+ self.old_thisown = None
+
+ def __exit__(self, *ignored):
+ if self.old_thisown is not None:
+ self.obj.thisown = self.old_thisown
+
+
+def handle_SearchParameters(the_class):
+ """ this wrapper is to enable initializations of the form
+ SearchParametersXX(a=3, b=SearchParamsYY)
+ This also requires the enclosing class to keep a reference on the
+ sub-object, since the C++ code assumes the object ownwership is
+ handled externally.
+ """
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, **args):
+ self.original_init()
+ for k, v in args.items():
+ assert hasattr(self, k)
+ with RememberSwigOwnership(v):
+ setattr(self, k, v)
+ if type(v) not in (int, float, bool, str):
+ add_to_referenced_objects(self, v)
+
+ the_class.__init__ = replacement_init
+
+
+def handle_IDSelectorSubset(the_class, class_owns, force_int64=True):
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ if len(args) == 1:
+ # assume it's an array
+ subset, = args
+ if force_int64:
+ subset = np.ascontiguousarray(subset, dtype='int64')
+ args = (len(subset), faiss.swig_ptr(subset))
+ if not class_owns:
+ add_to_referenced_objects(self, subset)
+ self.original_init(*args)
+
+ the_class.__init__ = replacement_init
+
+
+def handle_CodeSet(the_class):
+
+ def replacement_insert(self, codes, inserted=None):
+ n, d = codes.shape
+ assert d == self.d
+ codes = np.ascontiguousarray(codes, dtype=np.uint8)
+
+ if inserted is None:
+ inserted = np.empty(n, dtype=bool)
+ else:
+ assert inserted.shape == (n, )
+
+ self.insert_c(n, swig_ptr(codes), swig_ptr(inserted))
+ return inserted
+
+ replace_method(the_class, 'insert', replacement_insert)
+
+######################################################
+# Syntatic sugar for NeuralNet classes
+######################################################
+
+
+def handle_Tensor2D(the_class):
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ if len(args) == 1:
+ array, = args
+ n, d = array.shape
+ self.original_init(n, d)
+ faiss.copy_array_to_vector(
+ np.ascontiguousarray(array).ravel(), self.v)
+ else:
+ self.original_init(*args)
+
+ def numpy(self):
+ shape = np.zeros(2, dtype=np.int64)
+ faiss.memcpy(faiss.swig_ptr(shape), self.shape, shape.nbytes)
+ return faiss.vector_to_array(self.v).reshape(shape[0], shape[1])
+
+ the_class.__init__ = replacement_init
+ the_class.numpy = numpy
+
+
+def handle_Embedding(the_class):
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ if len(args) != 1 or args[0].__class__ == the_class:
+ self.original_init(*args)
+ return
+ # assume it's a torch.Embedding
+ emb = args[0]
+ self.original_init(emb.num_embeddings, emb.embedding_dim)
+ self.from_torch(emb)
+
+ def from_torch(self, emb):
+ """ copy weights from torch.Embedding """
+ assert emb.weight.shape == (self.num_embeddings, self.embedding_dim)
+ faiss.copy_array_to_vector(
+ np.ascontiguousarray(emb.weight.data).ravel(), self.weight)
+
+ def from_array(self, array):
+ """ copy weights from numpy array """
+ assert array.shape == (self.num_embeddings, self.embedding_dim)
+ faiss.copy_array_to_vector(
+ np.ascontiguousarray(array).ravel(), self.weight)
+
+ the_class.from_array = from_array
+ the_class.from_torch = from_torch
+ the_class.__init__ = replacement_init
+
+
+def handle_Linear(the_class):
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ if len(args) != 1 or args[0].__class__ == the_class:
+ self.original_init(*args)
+ return
+ # assume it's a torch.Linear
+ linear = args[0]
+ bias = linear.bias is not None
+ self.original_init(linear.in_features, linear.out_features, bias)
+ self.from_torch(linear)
+
+ def from_torch(self, linear):
+ """ copy weights from torch.Linear """
+ assert linear.weight.shape == (self.out_features, self.in_features)
+ faiss.copy_array_to_vector(
+ linear.weight.data.numpy().ravel(), self.weight)
+ if linear.bias is not None:
+ assert linear.bias.shape == (self.out_features,)
+ faiss.copy_array_to_vector(linear.bias.data.numpy(), self.bias)
+
+ def from_array(self, array, bias=None):
+ """ copy weights from numpy array """
+ assert array.shape == (self.out_features, self.in_features)
+ faiss.copy_array_to_vector(
+ np.ascontiguousarray(array).ravel(), self.weight)
+ if bias is not None:
+ assert bias.shape == (self.out_features,)
+ faiss.copy_array_to_vector(bias, self.bias)
+
+ the_class.__init__ = replacement_init
+ the_class.from_array = from_array
+ the_class.from_torch = from_torch
+
+######################################################
+# Syntatic sugar for QINCo and QINCoStep
+######################################################
+
+def handle_QINCoStep(the_class):
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ if len(args) != 1 or args[0].__class__ == the_class:
+ self.original_init(*args)
+ return
+ step = args[0]
+ # assume it's a Torch QINCoStep
+ self.original_init(step.d, step.K, step.L, step.h)
+ self.from_torch(step)
+
+ def from_torch(self, step):
+ """ copy weights from torch.QINCoStep """
+ assert (step.d, step.K, step.L, step.h) == (self.d, self.K, self.L, self.h)
+ self.codebook.from_torch(step.codebook)
+ self.MLPconcat.from_torch(step.MLPconcat)
+
+ for l in range(step.L):
+ src = step.residual_blocks[l]
+ dest = self.get_residual_block(l)
+ dest.linear1.from_torch(src[0])
+ dest.linear2.from_torch(src[2])
+
+ the_class.__init__ = replacement_init
+ the_class.from_torch = from_torch
+
+
+def handle_QINCo(the_class):
+ the_class.original_init = the_class.__init__
+
+ def replacement_init(self, *args):
+ if len(args) != 1 or args[0].__class__ == the_class:
+ self.original_init(*args)
+ return
+
+ # assume it's a Torch QINCo
+ qinco = args[0]
+ self.original_init(qinco.d, qinco.K, qinco.L, qinco.M, qinco.h)
+ self.from_torch(qinco)
+
+ def from_torch(self, qinco):
+ """ copy weights from torch.QINCo """
+ assert (
+ (qinco.d, qinco.K, qinco.L, qinco.M, qinco.h) ==
+ (self.d, self.K, self.L, self.M, self.h)
+ )
+ self.codebook0.from_torch(qinco.codebook0)
+ for m in range(qinco.M - 1):
+ self.get_step(m).from_torch(qinco.steps[m])
+
+ the_class.__init__ = replacement_init
+ the_class.from_torch = from_torch
+
+
+def handle_shard_ivf_index_centroids(func):
+ def wrapper(*args, **kwargs):
+ args = list(args)
+ if len(args) > 3 and args[3] is not None:
+ args[3] = faiss.PyCallbackShardingFunction(args[3])
+ return func(*args, **kwargs)
+ return wrapper
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/extra_wrappers.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/extra_wrappers.py
new file mode 100644
index 0000000..0b3deec
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/extra_wrappers.py
@@ -0,0 +1,659 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# @nolint
+
+# not linting this file because it imports * from swigfaiss, which
+# causes a ton of useless warnings.
+
+import numpy as np
+
+from faiss.loader import *
+
+import faiss
+
+import collections.abc
+
+
+###########################################
+# Wrapper for a few functions
+###########################################
+
+
+def kmin(array, k):
+ """return k smallest values (and their indices) of the lines of a
+ float32 array"""
+ array = np.ascontiguousarray(array, dtype='float32')
+ m, n = array.shape
+ I = np.zeros((m, k), dtype='int64')
+ D = np.zeros((m, k), dtype='float32')
+ ha = faiss.float_maxheap_array_t()
+ ha.ids = swig_ptr(I)
+ ha.val = swig_ptr(D)
+ ha.nh = m
+ ha.k = k
+ ha.heapify()
+ ha.addn(n, swig_ptr(array))
+ ha.reorder()
+ return D, I
+
+
+def kmax(array, k):
+ """return k largest values (and their indices) of the lines of a
+ float32 array"""
+ array = np.ascontiguousarray(array, dtype='float32')
+ m, n = array.shape
+ I = np.zeros((m, k), dtype='int64')
+ D = np.zeros((m, k), dtype='float32')
+ ha = faiss.float_minheap_array_t()
+ ha.ids = swig_ptr(I)
+ ha.val = swig_ptr(D)
+ ha.nh = m
+ ha.k = k
+ ha.heapify()
+ ha.addn(n, swig_ptr(array))
+ ha.reorder()
+ return D, I
+
+
+def pairwise_distances(xq, xb, metric=METRIC_L2, metric_arg=0):
+ """compute the whole pairwise distance matrix between two sets of
+ vectors"""
+ xq = np.ascontiguousarray(xq, dtype='float32')
+ xb = np.ascontiguousarray(xb, dtype='float32')
+ nq, d = xq.shape
+ nb, d2 = xb.shape
+ assert d == d2
+ dis = np.empty((nq, nb), dtype='float32')
+ if metric == METRIC_L2:
+ pairwise_L2sqr(
+ d, nq, swig_ptr(xq),
+ nb, swig_ptr(xb),
+ swig_ptr(dis))
+ elif metric == METRIC_INNER_PRODUCT:
+ dis[:] = xq @ xb.T
+ else:
+ pairwise_extra_distances(
+ d, nq, swig_ptr(xq),
+ nb, swig_ptr(xb),
+ metric, metric_arg,
+ swig_ptr(dis))
+ return dis
+
+
+def rand(n, seed=12345):
+ res = np.empty(n, dtype='float32')
+ float_rand(swig_ptr(res), res.size, seed)
+ return res
+
+
+def randint(n, seed=12345, vmax=None):
+ res = np.empty(n, dtype='int64')
+ if vmax is None:
+ int64_rand(swig_ptr(res), res.size, seed)
+ else:
+ int64_rand_max(swig_ptr(res), res.size, vmax, seed)
+ return res
+
+
+lrand = randint
+
+
+def randn(n, seed=12345):
+ res = np.empty(n, dtype='float32')
+ float_randn(swig_ptr(res), res.size, seed)
+ return res
+
+
+def checksum(a):
+ """ compute a checksum for quick-and-dirty comparisons of arrays """
+ a = a.view('uint8')
+ if a.ndim == 1:
+ return bvec_checksum(a.size, swig_ptr(a))
+ n, d = a.shape
+ cs = np.zeros(n, dtype='uint64')
+ bvecs_checksum(n, d, swig_ptr(a), swig_ptr(cs))
+ return cs
+
+rand_smooth_vectors_c = rand_smooth_vectors
+
+def rand_smooth_vectors(n, d, seed=1234):
+ res = np.empty((n, d), dtype='float32')
+ rand_smooth_vectors_c(n, d, swig_ptr(res), seed)
+ return res
+
+
+def eval_intersection(I1, I2):
+ """ size of intersection between each line of two result tables"""
+ I1 = np.ascontiguousarray(I1, dtype='int64')
+ I2 = np.ascontiguousarray(I2, dtype='int64')
+ n = I1.shape[0]
+ assert I2.shape[0] == n
+ k1, k2 = I1.shape[1], I2.shape[1]
+ ninter = 0
+ for i in range(n):
+ ninter += ranklist_intersection_size(
+ k1, swig_ptr(I1[i]), k2, swig_ptr(I2[i]))
+ return ninter
+
+
+def normalize_L2(x):
+ fvec_renorm_L2(x.shape[1], x.shape[0], swig_ptr(x))
+
+bucket_sort_c = bucket_sort
+
+def bucket_sort(tab, nbucket=None, nt=0):
+ """Perform a bucket sort on a table of integers.
+
+ Parameters
+ ----------
+ tab : array_like
+ elements to sort, max value nbucket - 1
+ nbucket : integer
+ number of buckets, None if unknown
+ nt : integer
+ number of threads to use (0 = use unthreaded codepath)
+
+ Returns
+ -------
+ lims : array_like
+ cumulative sum of bucket sizes (size vmax + 1)
+ perm : array_like
+ perm[lims[i] : lims[i + 1]] contains the indices of bucket #i (size tab.size)
+ """
+ tab = np.ascontiguousarray(tab, dtype="int64")
+ if nbucket is None:
+ nbucket = int(tab.max() + 1)
+ lims = np.empty(nbucket + 1, dtype='int64')
+ perm = np.empty(tab.size, dtype='int64')
+ bucket_sort_c(
+ tab.size, faiss.swig_ptr(tab.view('uint64')),
+ nbucket, faiss.swig_ptr(lims), faiss.swig_ptr(perm),
+ nt
+ )
+ return lims, perm
+
+matrix_bucket_sort_inplace_c = matrix_bucket_sort_inplace
+
+def matrix_bucket_sort_inplace(tab, nbucket=None, nt=0):
+ """Perform a bucket sort on a matrix, recording the original
+ row of each element.
+
+ Parameters
+ ----------
+ tab : array_like
+ array of size (N, ncol) that contains the bucket ids, maximum
+ value nbucket - 1.
+ On output, it the elements are shuffled such that the flat array
+ tab.ravel()[lims[i] : lims[i + 1]] contains the row numbers
+ of each bucket entry.
+ nbucket : integer
+ number of buckets (the maximum value in tab should be nbucket - 1)
+ nt : integer
+ number of threads to use (0 = use unthreaded codepath)
+
+ Returns
+ -------
+ lims : array_like
+ cumulative sum of bucket sizes (size vmax + 1)
+ """
+ assert tab.dtype == 'int32' or tab.dtype == 'int64'
+ nrow, ncol = tab.shape
+ if nbucket is None:
+ nbucket = int(tab.max() + 1)
+ lims = np.empty(nbucket + 1, dtype='int64')
+ matrix_bucket_sort_inplace_c(
+ nrow, ncol, faiss.swig_ptr(tab),
+ nbucket, faiss.swig_ptr(lims),
+ nt
+ )
+ return lims
+
+
+###########################################
+# ResultHeap
+###########################################
+
+class ResultHeap:
+ """Accumulate query results from a sliced dataset. The final result will
+ be in self.D, self.I."""
+
+ def __init__(self, nq, k, keep_max=False):
+ """
+ nq: number of query vectors,
+ k: number of results per query
+ keep_max: keep the top-k maximum values instead of the minima
+ """
+ self.I = np.zeros((nq, k), dtype='int64')
+ self.D = np.zeros((nq, k), dtype='float32')
+ self.nq, self.k = nq, k
+ if keep_max:
+ heaps = float_minheap_array_t()
+ else:
+ heaps = float_maxheap_array_t()
+ heaps.k = k
+ heaps.nh = nq
+ heaps.val = swig_ptr(self.D)
+ heaps.ids = swig_ptr(self.I)
+ heaps.heapify()
+ self.heaps = heaps
+
+ def add_result(self, D, I):
+ """
+ Add results for all heaps
+ D, I should be of size (nh, nres)
+ D, I do not need to be in a particular order (heap or sorted)
+ """
+ nq, kd = D.shape
+ D = np.ascontiguousarray(D, dtype='float32')
+ I = np.ascontiguousarray(I, dtype='int64')
+ assert I.shape == (nq, kd)
+ assert nq == self.nq
+ self.heaps.addn_with_ids(
+ kd, swig_ptr(D),
+ swig_ptr(I), kd)
+
+ def add_result_subset(self, subset, D, I):
+ """
+ Add results for a subset of heaps.
+ D, I should hold resutls for all the subset
+ as a special case, if I is 1D, then all ids are assumed to be the same
+ """
+ nsubset, kd = D.shape
+ assert nsubset == len(subset)
+ assert (
+ I.ndim == 2 and D.shape == I.shape or
+ I.ndim == 1 and I.shape == (kd, )
+ )
+ D = np.ascontiguousarray(D, dtype='float32')
+ I = np.ascontiguousarray(I, dtype='int64')
+ subset = np.ascontiguousarray(subset, dtype='int64')
+ id_stride = 0 if I.ndim == 1 else kd
+ self.heaps.addn_query_subset_with_ids(
+ nsubset, swig_ptr(subset),
+ kd, swig_ptr(D), swig_ptr(I), id_stride
+ )
+
+ def finalize(self):
+ self.heaps.reorder()
+
+
+def merge_knn_results(Dall, Iall, keep_max=False):
+ """
+ Merge a set of sorted knn-results obtained from different shards in a dataset
+ Dall and Iall are of size (nshard, nq, k) each D[i, j] should be sorted
+ returns D, I of size (nq, k) as the merged result set
+ """
+ assert Iall.shape == Dall.shape
+ nshard, n, k = Dall.shape
+ Dnew = np.empty((n, k), dtype=Dall.dtype)
+ Inew = np.empty((n, k), dtype=Iall.dtype)
+ func = merge_knn_results_CMax if keep_max else merge_knn_results_CMin
+ func(
+ n, k, nshard,
+ swig_ptr(Dall), swig_ptr(Iall),
+ swig_ptr(Dnew), swig_ptr(Inew)
+ )
+ return Dnew, Inew
+
+######################################################
+# Efficient ID to ID map
+######################################################
+
+class MapInt64ToInt64:
+
+ def __init__(self, capacity):
+ self.log2_capacity = int(np.log2(capacity))
+ assert capacity == 2 ** self.log2_capacity, "need power of 2 capacity"
+ self.capacity = capacity
+ self.tab = np.empty((capacity, 2), dtype='int64')
+ faiss.hashtable_int64_to_int64_init(self.log2_capacity, swig_ptr(self.tab))
+
+ def add(self, keys, vals):
+ n, = keys.shape
+ assert vals.shape == (n,)
+ faiss.hashtable_int64_to_int64_add(
+ self.log2_capacity, swig_ptr(self.tab),
+ n, swig_ptr(keys), swig_ptr(vals))
+
+ def lookup(self, keys):
+ n, = keys.shape
+ vals = np.empty((n,), dtype='int64')
+ faiss.hashtable_int64_to_int64_lookup(
+ self.log2_capacity, swig_ptr(self.tab),
+ n, swig_ptr(keys), swig_ptr(vals))
+ return vals
+
+######################################################
+# KNN function
+######################################################
+
+def knn(xq, xb, k, metric=METRIC_L2, metric_arg=0.0):
+ """
+ Compute the k nearest neighbors of a vector without constructing an index
+
+
+ Parameters
+ ----------
+ xq : array_like
+ Query vectors, shape (nq, d) where the dimension d is that same as xb
+ `dtype` must be float32.
+ xb : array_like
+ Database vectors, shape (nb, d) where dimension d is the same as xq
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ metric : MetricType, optional
+ distance measure to use (either METRIC_L2 or METRIC_INNER_PRODUCT)
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (nq, k)
+ I : array_like
+ Labels of the nearest neighbors, shape (nq, k)
+ """
+ xq = np.ascontiguousarray(xq, dtype='float32')
+ xb = np.ascontiguousarray(xb, dtype='float32')
+ nq, d = xq.shape
+ nb, d2 = xb.shape
+ assert d == d2
+
+ I = np.empty((nq, k), dtype='int64')
+ D = np.empty((nq, k), dtype='float32')
+
+ if metric == METRIC_L2:
+ knn_L2sqr(
+ swig_ptr(xq), swig_ptr(xb),
+ d, nq, nb, k, swig_ptr(D), swig_ptr(I)
+ )
+ elif metric == METRIC_INNER_PRODUCT:
+ knn_inner_product(
+ swig_ptr(xq), swig_ptr(xb),
+ d, nq, nb, k, swig_ptr(D), swig_ptr(I)
+ )
+ else:
+ knn_extra_metrics(
+ swig_ptr(xq), swig_ptr(xb),
+ d, nq, nb, metric, metric_arg, k,
+ swig_ptr(D), swig_ptr(I)
+ )
+
+ return D, I
+
+
+def knn_hamming(xq, xb, k, variant="hc"):
+ """
+ Compute the k nearest neighbors of a set of vectors without constructing an index.
+
+ Parameters
+ ----------
+ xq : array_like
+ Query vectors, shape (nq, d) where d is the number of bits / 8
+ `dtype` must be uint8.
+ xb : array_like
+ Database vectors, shape (nb, d) where d is the number of bits / 8
+ `dtype` must be uint8.
+ k : int
+ Number of nearest neighbors.
+ variant : string
+ Function variant to use, either "mc" (counter) or "hc" (heap)
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (nq, k)
+ I : array_like
+ Labels of the nearest neighbors, shape (nq, k)
+ """
+ # other variant is "mc"
+ nq, d = xq.shape
+ nb, d2 = xb.shape
+ assert d == d2
+ D = np.empty((nq, k), dtype='int32')
+ I = np.empty((nq, k), dtype='int64')
+
+ if variant == "hc":
+ heap = faiss.int_maxheap_array_t()
+ heap.k = k
+ heap.nh = nq
+ heap.ids = faiss.swig_ptr(I)
+ heap.val = faiss.swig_ptr(D)
+ faiss.hammings_knn_hc(
+ heap, faiss.swig_ptr(xq), faiss.swig_ptr(xb), nb,
+ d, 1
+ )
+ elif variant == "mc":
+ faiss.hammings_knn_mc(
+ faiss.swig_ptr(xq), faiss.swig_ptr(xb), nq, nb, k, d,
+ faiss.swig_ptr(D), faiss.swig_ptr(I)
+ )
+ else:
+ raise NotImplementedError
+ return D, I
+
+
+###########################################
+# Kmeans object
+###########################################
+
+
+class Kmeans:
+ """Object that performs k-means clustering and manages the centroids.
+ The `Kmeans` class is essentially a wrapper around the C++ `Clustering` object.
+
+ Parameters
+ ----------
+ d : int
+ dimension of the vectors to cluster
+ k : int
+ number of clusters
+ gpu: bool or int, optional
+ False: don't use GPU
+ True: use all GPUs
+ number: use this many GPUs
+ progressive_dim_steps:
+ use a progressive dimension clustering (with that number of steps)
+
+ Subsequent parameters are fields of the Clustring object. The most important are:
+
+ niter: int, optional
+ clustering iterations
+ nredo: int, optional
+ redo clustering this many times and keep best
+ verbose: bool, optional
+ spherical: bool, optional
+ do we want normalized centroids?
+ int_centroids: bool, optional
+ round centroids coordinates to integer
+ seed: int, optional
+ seed for the random number generator
+
+ """
+
+ def __init__(self, d, k, **kwargs):
+ """d: input dimension, k: nb of centroids. Additional
+ parameters are passed on the ClusteringParameters object,
+ including niter=25, verbose=False, spherical = False
+ """
+ self.d = d
+ self.reset(k)
+ self.gpu = False
+ if "progressive_dim_steps" in kwargs:
+ self.cp = ProgressiveDimClusteringParameters()
+ else:
+ self.cp = ClusteringParameters()
+ for k, v in kwargs.items():
+ if k == 'gpu':
+ if v == True or v == -1:
+ v = get_num_gpus()
+ self.gpu = v
+ else:
+ # if this raises an exception, it means that it is a non-existent field
+ getattr(self.cp, k)
+ setattr(self.cp, k, v)
+ self.set_index()
+
+ def set_index(self):
+ d = self.d
+ if self.cp.__class__ == ClusteringParameters:
+ if self.cp.spherical:
+ self.index = IndexFlatIP(d)
+ else:
+ self.index = IndexFlatL2(d)
+ if self.gpu:
+ self.index = faiss.index_cpu_to_all_gpus(self.index, ngpu=self.gpu)
+ else:
+ if self.gpu:
+ fac = GpuProgressiveDimIndexFactory(ngpu=self.gpu)
+ else:
+ fac = ProgressiveDimIndexFactory()
+ self.fac = fac
+
+ def reset(self, k=None):
+ """ prepare k-means object to perform a new clustering, possibly
+ with another number of centroids """
+ if k is not None:
+ self.k = int(k)
+ self.centroids = None
+ self.obj = None
+ self.iteration_stats = None
+
+ def train(self, x, weights=None, init_centroids=None):
+ """ Perform k-means clustering.
+ On output of the function call:
+
+ - the centroids are in the centroids field of size (`k`, `d`).
+
+ - the objective value at each iteration is in the array obj (size `niter`)
+
+ - detailed optimization statistics are in the array iteration_stats.
+
+ Parameters
+ ----------
+ x : array_like
+ Training vectors, shape (n, d), `dtype` must be float32 and n should
+ be larger than the number of clusters `k`.
+ weights : array_like
+ weight associated to each vector, shape `n`
+ init_centroids : array_like
+ initial set of centroids, shape (n, d)
+
+ Returns
+ -------
+ final_obj: float
+ final optimization objective
+
+ """
+ x = np.ascontiguousarray(x, dtype='float32')
+ n, d = x.shape
+ assert d == self.d
+
+ if self.cp.__class__ == ClusteringParameters:
+ # regular clustering
+ clus = Clustering(d, self.k, self.cp)
+ if init_centroids is not None:
+ nc, d2 = init_centroids.shape
+ assert d2 == d
+ faiss.copy_array_to_vector(init_centroids.ravel(), clus.centroids)
+ clus.train(x, self.index, weights)
+ else:
+ # not supported for progressive dim
+ assert weights is None
+ assert init_centroids is None
+ assert not self.cp.spherical
+ clus = ProgressiveDimClustering(d, self.k, self.cp)
+ clus.train(n, swig_ptr(x), self.fac)
+
+ centroids = faiss.vector_float_to_array(clus.centroids)
+
+ self.centroids = centroids.reshape(self.k, d)
+ stats = clus.iteration_stats
+ stats = [stats.at(i) for i in range(stats.size())]
+ self.obj = np.array([st.obj for st in stats])
+ # copy all the iteration_stats objects to a python array
+ stat_fields = 'obj time time_search imbalance_factor nsplit'.split()
+ self.iteration_stats = [
+ {field: getattr(st, field) for field in stat_fields}
+ for st in stats
+ ]
+ return self.obj[-1] if self.obj.size > 0 else 0.0
+
+ def assign(self, x):
+ x = np.ascontiguousarray(x, dtype='float32')
+ assert self.centroids is not None, "should train before assigning"
+ self.index.reset()
+ self.index.add(self.centroids)
+ D, I = self.index.search(x, 1)
+ return D.ravel(), I.ravel()
+
+
+###########################################
+# Packing and unpacking bistrings
+###########################################
+
+def is_sequence(x):
+ return isinstance(x, collections.abc.Sequence)
+
+pack_bitstrings_c = pack_bitstrings
+
+def pack_bitstrings(a, nbit):
+ """
+ Pack a set integers (i, j) where i=0:n and j=0:M into
+ n bitstrings.
+ Output is an uint8 array of size (n, code_size), where code_size is
+ such that at most 7 bits per code are wasted.
+
+ If nbit is an integer: all entries takes nbit bits.
+ If nbit is an array: entry (i, j) takes nbit[j] bits.
+ """
+ n, M = a.shape
+ a = np.ascontiguousarray(a, dtype='int32')
+ if is_sequence(nbit):
+ nbit = np.ascontiguousarray(nbit, dtype='int32')
+ assert nbit.shape == (M,)
+ code_size = int((nbit.sum() + 7) // 8)
+ b = np.empty((n, code_size), dtype='uint8')
+ pack_bitstrings_c(
+ n, M, swig_ptr(nbit), swig_ptr(a), swig_ptr(b), code_size)
+ else:
+ code_size = (M * nbit + 7) // 8
+ b = np.empty((n, code_size), dtype='uint8')
+ pack_bitstrings_c(n, M, nbit, swig_ptr(a), swig_ptr(b), code_size)
+ return b
+
+unpack_bitstrings_c = unpack_bitstrings
+
+def unpack_bitstrings(b, M_or_nbits, nbit=None):
+ """
+ Unpack a set integers (i, j) where i=0:n and j=0:M from
+ n bitstrings (encoded as uint8s).
+ Input is an uint8 array of size (n, code_size), where code_size is
+ such that at most 7 bits per code are wasted.
+
+ Two forms:
+ - when called with (array, M, nbit): there are M entries of size
+ nbit per row
+ - when called with (array, nbits): element (i, j) is encoded in
+ nbits[j] bits
+ """
+ n, code_size = b.shape
+ if nbit is None:
+ nbit = np.ascontiguousarray(M_or_nbits, dtype='int32')
+ M = len(nbit)
+ min_code_size = int((nbit.sum() + 7) // 8)
+ assert code_size >= min_code_size
+ a = np.empty((n, M), dtype='int32')
+ unpack_bitstrings_c(
+ n, M, swig_ptr(nbit),
+ swig_ptr(b), code_size, swig_ptr(a))
+ else:
+ M = M_or_nbits
+ min_code_size = (M * nbit + 7) // 8
+ assert code_size >= min_code_size
+ a = np.empty((n, M), dtype='int32')
+ unpack_bitstrings_c(
+ n, M, nbit, swig_ptr(b), code_size, swig_ptr(a))
+ return a
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/faiss_example_external_module.swig b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/faiss_example_external_module.swig
new file mode 100644
index 0000000..6a1c9fe
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/faiss_example_external_module.swig
@@ -0,0 +1,141 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// This is an example of how an external module can be added via SWIG.
+
+%module faiss_example_external_module;
+
+
+// Put C++ includes here
+%{
+
+#include <faiss/impl/FaissException.h>
+#include <faiss/impl/IDSelector.h>
+
+%}
+
+#pragma SWIG nowarn=322
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+
+typedef signed char int8_t;
+typedef short int16_t;
+typedef int int32_t;
+
+#ifdef SWIGWORDSIZE64
+typedef unsigned long uint64_t;
+typedef long int64_t;
+#else
+typedef unsigned long long uint64_t;
+typedef long long int64_t;
+#endif
+
+typedef uint64_t size_t;
+
+// This means: assume what's declared in these .h files is provided
+// by the Faiss module.
+%import(module="faiss") "faiss/MetricType.h"
+%import(module="faiss") "faiss/impl/IDSelector.h"
+
+// functions to be parsed here
+
+// This is important to release GIL and do Faiss exception handing
+%exception {
+ Py_BEGIN_ALLOW_THREADS
+ try {
+ $action
+ } catch(faiss::FaissException & e) {
+ PyEval_RestoreThread(_save);
+
+ if (PyErr_Occurred()) {
+ // some previous code already set the error type.
+ } else {
+ PyErr_SetString(PyExc_RuntimeError, e.what());
+ }
+ SWIG_fail;
+ } catch(std::bad_alloc & ba) {
+ PyEval_RestoreThread(_save);
+ PyErr_SetString(PyExc_MemoryError, "std::bad_alloc");
+ SWIG_fail;
+ }
+ Py_END_ALLOW_THREADS
+}
+
+
+// any class or function declared below will be made available
+// in the module.
+%inline %{
+
+struct IDSelectorModulo : faiss::IDSelector {
+ int mod;
+
+ IDSelectorModulo(int mod): mod(mod) {}
+
+ bool is_member(faiss::idx_t id) const {
+ return id % mod == 0;
+ }
+
+ ~IDSelectorModulo() override {}
+};
+
+faiss::idx_t sum_of_idx(size_t n, const faiss::idx_t *tab) {
+ faiss::idx_t sum = 0;
+ for(size_t i = 0; i < n; i++) {
+ sum += tab[i];
+ }
+ return sum;
+}
+
+float sum_of_float32(size_t n, const float *tab) {
+ float sum = 0;
+ for(size_t i = 0; i < n; i++) {
+ sum += tab[i];
+ }
+ return sum;
+}
+
+double sum_of_float64(size_t n, const double *tab) {
+ double sum = 0;
+ for(size_t i = 0; i < n; i++) {
+ sum += tab[i];
+ }
+ return sum;
+}
+
+%}
+
+/**********************************************
+ * To test if passing a swig_ptr on all array types works
+ **********************************************/
+
+%define SUM_OF_TYPE(ty)
+
+%inline %{
+
+ty##_t sum_of_##ty (size_t n, const ty##_t * tab) {
+ ty##_t sum = 0;
+ for(size_t i = 0; i < n; i++) {
+ sum += tab[i];
+ }
+ return sum;
+}
+
+%}
+
+%enddef
+
+SUM_OF_TYPE(uint8);
+SUM_OF_TYPE(uint16);
+SUM_OF_TYPE(uint32);
+SUM_OF_TYPE(uint64);
+
+SUM_OF_TYPE(int8);
+SUM_OF_TYPE(int16);
+SUM_OF_TYPE(int32);
+SUM_OF_TYPE(int64);
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/gpu_wrappers.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/gpu_wrappers.py
new file mode 100644
index 0000000..4945722
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/gpu_wrappers.py
@@ -0,0 +1,293 @@
+# Copyright (c) Facebook, Inc. and its affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# @nolint
+
+# not linting this file because it imports * from swigfaiss, which
+# causes a ton of useless warnings.
+
+import numpy as np
+
+from faiss.loader import *
+
+
+###########################################
+# GPU functions
+###########################################
+
+
+def index_cpu_to_gpu_multiple_py(resources, index, co=None, gpus=None):
+ """ builds the C++ vectors for the GPU indices and the
+ resources. Handles the case where the resources are assigned to
+ the list of GPUs """
+ if gpus is None:
+ gpus = range(len(resources))
+ vres = GpuResourcesVector()
+ vdev = Int32Vector()
+ for i, res in zip(gpus, resources):
+ vdev.push_back(i)
+ vres.push_back(res)
+ if isinstance(index, IndexBinary):
+ return index_binary_cpu_to_gpu_multiple(vres, vdev, index, co)
+ else:
+ return index_cpu_to_gpu_multiple(vres, vdev, index, co)
+
+
+def index_cpu_to_all_gpus(index, co=None, ngpu=-1):
+ index_gpu = index_cpu_to_gpus_list(index, co=co, gpus=None, ngpu=ngpu)
+ return index_gpu
+
+
+def index_cpu_to_gpus_list(index, co=None, gpus=None, ngpu=-1):
+ """ Here we can pass list of GPU ids as a parameter or ngpu to
+ use first n GPU's. gpus mut be a list or None.
+ co is a GpuMultipleClonerOptions
+ """
+ if (gpus is None) and (ngpu == -1): # All blank
+ gpus = range(get_num_gpus())
+ elif (gpus is None) and (ngpu != -1): # Get number of GPU's only
+ gpus = range(ngpu)
+ res = [StandardGpuResources() for _ in gpus]
+ index_gpu = index_cpu_to_gpu_multiple_py(res, index, co, gpus)
+ return index_gpu
+
+# allows numpy ndarray usage with bfKnn
+
+
+def knn_gpu(res, xq, xb, k, D=None, I=None, metric=METRIC_L2, device=-1, use_cuvs=False, vectorsMemoryLimit=0, queriesMemoryLimit=0):
+ """
+ Compute the k nearest neighbors of a vector on one GPU without constructing an index
+
+ Parameters
+ ----------
+ res : StandardGpuResources
+ GPU resources to use during computation
+ xq : array_like
+ Query vectors, shape (nq, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ xb : array_like
+ Database vectors, shape (nb, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ k : int
+ Number of nearest neighbors.
+ D : array_like, optional
+ Output array for distances of the nearest neighbors, shape (nq, k)
+ I : array_like, optional
+ Output array for the nearest neighbors, shape (nq, k)
+ metric : MetricType, optional
+ Distance measure to use (either METRIC_L2 or METRIC_INNER_PRODUCT)
+ device: int, optional
+ Which CUDA device in the system to run the search on. -1 indicates that
+ the current thread-local device state (via cudaGetDevice) should be used
+ (can also be set via torch.cuda.set_device in PyTorch)
+ Otherwise, an integer 0 <= device < numDevices indicates the GPU on which
+ the computation should be run
+ vectorsMemoryLimit: int, optional
+ queriesMemoryLimit: int, optional
+ Memory limits for vectors and queries.
+ If not 0, the GPU will use at most this amount of memory
+ for vectors and queries respectively.
+ Vectors are broken up into chunks of size vectorsMemoryLimit,
+ and queries are broken up into chunks of size queriesMemoryLimit,
+ including the memory required for the results.
+
+ Returns
+ -------
+ D : array_like
+ Distances of the nearest neighbors, shape (nq, k)
+ I : array_like
+ Labels of the nearest neighbors, shape (nq, k)
+ """
+ nq, d = xq.shape
+ if xq.flags.c_contiguous:
+ xq_row_major = True
+ elif xq.flags.f_contiguous:
+ xq = xq.T
+ xq_row_major = False
+ else:
+ xq = np.ascontiguousarray(xq, dtype='float32')
+ xq_row_major = True
+
+ xq_ptr = swig_ptr(xq)
+
+ if xq.dtype == np.float32:
+ xq_type = DistanceDataType_F32
+ elif xq.dtype == np.float16:
+ xq_type = DistanceDataType_F16
+ else:
+ raise TypeError('xq must be f32 or f16')
+
+ nb, d2 = xb.shape
+ assert d2 == d
+ if xb.flags.c_contiguous:
+ xb_row_major = True
+ elif xb.flags.f_contiguous:
+ xb = xb.T
+ xb_row_major = False
+ else:
+ xb = np.ascontiguousarray(xb, dtype='float32')
+ xb_row_major = True
+
+ xb_ptr = swig_ptr(xb)
+
+ if xb.dtype == np.float32:
+ xb_type = DistanceDataType_F32
+ elif xb.dtype == np.float16:
+ xb_type = DistanceDataType_F16
+ else:
+ raise TypeError('xb must be float32 or float16')
+
+ if D is None:
+ D = np.empty((nq, k), dtype=np.float32)
+ else:
+ assert D.shape == (nq, k)
+ # interface takes void*, we need to check this
+ assert D.dtype == np.float32
+
+ D_ptr = swig_ptr(D)
+
+ if I is None:
+ I = np.empty((nq, k), dtype=np.int64)
+ else:
+ assert I.shape == (nq, k)
+
+ I_ptr = swig_ptr(I)
+
+ if I.dtype == np.int64:
+ I_type = IndicesDataType_I64
+ elif I.dtype == I.dtype == np.int32:
+ I_type = IndicesDataType_I32
+ else:
+ raise TypeError('I must be i64 or i32')
+
+ args = GpuDistanceParams()
+ args.metric = metric
+ args.k = k
+ args.dims = d
+ args.vectors = xb_ptr
+ args.vectorsRowMajor = xb_row_major
+ args.vectorType = xb_type
+ args.numVectors = nb
+ args.queries = xq_ptr
+ args.queriesRowMajor = xq_row_major
+ args.queryType = xq_type
+ args.numQueries = nq
+ args.outDistances = D_ptr
+ args.outIndices = I_ptr
+ args.outIndicesType = I_type
+ args.device = device
+ args.use_cuvs = use_cuvs
+
+ # no stream synchronization needed, inputs and outputs are guaranteed to
+ # be on the CPU (numpy arrays)
+ if vectorsMemoryLimit > 0 or queriesMemoryLimit > 0:
+ bfKnn_tiling(res, args, vectorsMemoryLimit, queriesMemoryLimit)
+ else:
+ bfKnn(res, args)
+
+ return D, I
+
+# allows numpy ndarray usage with bfKnn for all pairwise distances
+
+
+def pairwise_distance_gpu(res, xq, xb, D=None, metric=METRIC_L2, device=-1):
+ """
+ Compute all pairwise distances between xq and xb on one GPU without constructing an index
+
+ Parameters
+ ----------
+ res : StandardGpuResources
+ GPU resources to use during computation
+ xq : array_like
+ Query vectors, shape (nq, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ xb : array_like
+ Database vectors, shape (nb, d) where d is appropriate for the index.
+ `dtype` must be float32.
+ D : array_like, optional
+ Output array for all pairwise distances, shape (nq, nb)
+ metric : MetricType, optional
+ Distance measure to use (either METRIC_L2 or METRIC_INNER_PRODUCT)
+ device: int, optional
+ Which CUDA device in the system to run the search on. -1 indicates that
+ the current thread-local device state (via cudaGetDevice) should be used
+ (can also be set via torch.cuda.set_device in PyTorch)
+ Otherwise, an integer 0 <= device < numDevices indicates the GPU on which
+ the computation should be run
+
+ Returns
+ -------
+ D : array_like
+ All pairwise distances, shape (nq, nb)
+ """
+ nq, d = xq.shape
+ if xq.flags.c_contiguous:
+ xq_row_major = True
+ elif xq.flags.f_contiguous:
+ xq = xq.T
+ xq_row_major = False
+ else:
+ raise TypeError(
+ 'xq matrix should be row (C) or column-major (Fortran)')
+
+ xq_ptr = swig_ptr(xq)
+
+ if xq.dtype == np.float32:
+ xq_type = DistanceDataType_F32
+ elif xq.dtype == np.float16:
+ xq_type = DistanceDataType_F16
+ else:
+ xq = np.ascontiguousarray(xb, dtype='float32')
+ xq_row_major = True
+
+ nb, d2 = xb.shape
+ assert d2 == d
+ if xb.flags.c_contiguous:
+ xb_row_major = True
+ elif xb.flags.f_contiguous:
+ xb = xb.T
+ xb_row_major = False
+ else:
+ xb = np.ascontiguousarray(xb, dtype='float32')
+ xb_row_major = True
+
+ xb_ptr = swig_ptr(xb)
+
+ if xb.dtype == np.float32:
+ xb_type = DistanceDataType_F32
+ elif xb.dtype == np.float16:
+ xb_type = DistanceDataType_F16
+ else:
+ raise TypeError('xb must be float32 or float16')
+
+ if D is None:
+ D = np.empty((nq, nb), dtype=np.float32)
+ else:
+ assert D.shape == (nq, nb)
+ # interface takes void*, we need to check this
+ assert D.dtype == np.float32
+
+ D_ptr = swig_ptr(D)
+
+ args = GpuDistanceParams()
+ args.metric = metric
+ args.k = -1 # selects all pairwise distances
+ args.dims = d
+ args.vectors = xb_ptr
+ args.vectorsRowMajor = xb_row_major
+ args.vectorType = xb_type
+ args.numVectors = nb
+ args.queries = xq_ptr
+ args.queriesRowMajor = xq_row_major
+ args.queryType = xq_type
+ args.numQueries = nq
+ args.outDistances = D_ptr
+ args.device = device
+
+ # no stream synchronization needed, inputs and outputs are guaranteed to
+ # be on the CPU (numpy arrays)
+ bfKnn(res, args)
+
+ return D
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/loader.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/loader.py
new file mode 100644
index 0000000..c3b7b00
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/loader.py
@@ -0,0 +1,150 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import platform
+import subprocess
+import logging
+import os
+
+
+def Version(v):
+ return [int(x) for x in v.split('.')]
+
+def supported_instruction_sets():
+ """
+ Returns the set of supported CPU features, see
+ https://github.com/numpy/numpy/blob/master/numpy/core/src/common/npy_cpu_features.h
+ for the list of features that this set may contain per architecture.
+
+ Example:
+ >>> supported_instruction_sets() # for x86
+ {"SSE2", "AVX2", "AVX512", ...}
+ >>> supported_instruction_sets() # for PPC
+ {"VSX", "VSX2", ...}
+ >>> supported_instruction_sets() # for ARM
+ {"NEON", "ASIMD", ...}
+ """
+
+ # Old numpy.core._multiarray_umath.__cpu_features__ doesn't support Arm SVE,
+ # so let's read Features in numpy.distutils.cpuinfo and search 'sve' entry
+ def is_sve_supported():
+ if platform.machine() != "aarch64":
+ return False
+ # Currently SVE is only supported on Linux
+ if platform.system() != "Linux":
+ return False
+ # Numpy 2.0 supports SVE detection by __cpu_features__, so just skip
+ import numpy
+ if Version(numpy.__version__) >= Version("2.0"):
+ return False
+ # platform-dependent legacy fallback using numpy.distutils.cpuinfo
+ import numpy.distutils.cpuinfo
+ return "sve" in numpy.distutils.cpuinfo.cpu.info[0].get('Features', "").split()
+
+ import numpy
+ if Version(numpy.__version__) >= Version("1.19"):
+ # use private API as next-best thing until numpy/numpy#18058 is solved
+ from numpy.core._multiarray_umath import __cpu_features__
+ # __cpu_features__ is a dictionary with CPU features
+ # as keys, and True / False as values
+ supported = {k for k, v in __cpu_features__.items() if v}
+ if is_sve_supported():
+ supported.add("SVE")
+ for f in os.getenv("FAISS_DISABLE_CPU_FEATURES", "").split(", \t\n\r"):
+ supported.discard(f)
+ return supported
+
+ # platform-dependent legacy fallback before numpy 1.19, no windows
+ if platform.system() == "Darwin":
+ if subprocess.check_output(["/usr/sbin/sysctl", "hw.optional.avx2_0"])[-1] == '1':
+ return {"AVX2"}
+ elif platform.system() == "Linux":
+ import numpy.distutils.cpuinfo
+ result = set()
+ if "avx2" in numpy.distutils.cpuinfo.cpu.info[0].get('flags', ""):
+ result.add("AVX2")
+ if "avx512" in numpy.distutils.cpuinfo.cpu.info[0].get('flags', ""):
+ result.add("AVX512")
+ if "avx512_fp16" in numpy.distutils.cpuinfo.cpu.info[0].get('flags', ""):
+ # avx512_fp16 is supported starting SPR
+ result.add("AVX512_SPR")
+ if is_sve_supported():
+ result.add("SVE")
+ for f in os.getenv("FAISS_DISABLE_CPU_FEATURES", "").split(", \t\n\r"):
+ result.discard(f)
+ return result
+ return set()
+
+logger = logging.getLogger(__name__)
+
+instruction_sets = None
+
+# try to load optimization level from env variable
+opt_env_variable_name = "FAISS_OPT_LEVEL"
+opt_level = os.environ.get(opt_env_variable_name, None)
+
+if opt_level is None:
+ logger.debug(f"Environment variable {opt_env_variable_name} is not set, " \
+ "so let's pick the instruction set according to the current CPU")
+ instruction_sets = supported_instruction_sets()
+else:
+ logger.debug(f"Using {opt_level} as an instruction set.")
+ instruction_sets = set()
+ instruction_sets.add(opt_level)
+
+loaded = False
+has_AVX512_SPR = any("AVX512_SPR" in x.upper() for x in instruction_sets)
+if has_AVX512_SPR:
+ try:
+ logger.info("Loading faiss with AVX512-SPR support.")
+ from .swigfaiss_avx512_spr import *
+ logger.info("Successfully loaded faiss with AVX512-SPR support.")
+ loaded = True
+ except ImportError as e:
+ logger.info(f"Could not load library with AVX512-SPR support due to:\n{e!r}")
+ # reset so that we load without AVX512 below
+ loaded = False
+
+has_AVX512 = any("AVX512" in x.upper() for x in instruction_sets)
+if has_AVX512 and not loaded:
+ try:
+ logger.info("Loading faiss with AVX512 support.")
+ from .swigfaiss_avx512 import *
+ logger.info("Successfully loaded faiss with AVX512 support.")
+ loaded = True
+ except ImportError as e:
+ logger.info(f"Could not load library with AVX512 support due to:\n{e!r}")
+ # reset so that we load without AVX512 below
+ loaded = False
+
+has_AVX2 = "AVX2" in instruction_sets
+if has_AVX2 and not loaded:
+ try:
+ logger.info("Loading faiss with AVX2 support.")
+ from .swigfaiss_avx2 import *
+ logger.info("Successfully loaded faiss with AVX2 support.")
+ loaded = True
+ except ImportError as e:
+ logger.info(f"Could not load library with AVX2 support due to:\n{e!r}")
+ # reset so that we load without AVX2 below
+ loaded = False
+
+has_SVE = "SVE" in instruction_sets
+if has_SVE and not loaded:
+ try:
+ logger.info("Loading faiss with SVE support.")
+ from .swigfaiss_sve import *
+ logger.info("Successfully loaded faiss with SVE support.")
+ loaded = True
+ except ImportError as e:
+ logger.info(f"Could not load library with SVE support due to:\n{e!r}")
+ # reset so that we load without SVE below
+ loaded = False
+
+if not loaded:
+ # we import * so that the symbol X can be accessed as faiss.X
+ logger.info("Loading faiss.")
+ from .swigfaiss import *
+ logger.info("Successfully loaded faiss.")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/python_callbacks.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/python_callbacks.cpp
new file mode 100644
index 0000000..8b78bf1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/python_callbacks.cpp
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/python/python_callbacks.h>
+
+namespace {
+
+struct PyThreadLock {
+ PyGILState_STATE gstate;
+
+ PyThreadLock() {
+ gstate = PyGILState_Ensure();
+ }
+
+ ~PyThreadLock() {
+ PyGILState_Release(gstate);
+ }
+};
+
+} // namespace
+
+/***********************************************************
+ * Callbacks for IO reader and writer
+ ***********************************************************/
+
+PyCallbackIOWriter::PyCallbackIOWriter(PyObject* callback, size_t bs)
+ : callback(callback), bs(bs) {
+ PyThreadLock gil;
+ Py_INCREF(callback);
+ name = "PyCallbackIOWriter";
+}
+
+size_t PyCallbackIOWriter::operator()(
+ const void* ptrv,
+ size_t size,
+ size_t nitems) {
+ size_t ws = size * nitems;
+ const char* ptr = (const char*)ptrv;
+ PyThreadLock gil;
+ while (ws > 0) {
+ size_t wi = ws > bs ? bs : ws;
+ PyObject* result = PyObject_CallFunction(
+ callback, "(N)", PyBytes_FromStringAndSize(ptr, wi));
+ if (result == nullptr) {
+ FAISS_THROW_MSG("py err");
+ }
+ // TODO check nb of bytes written
+ ptr += wi;
+ ws -= wi;
+ Py_DECREF(result);
+ }
+ return nitems;
+}
+
+PyCallbackIOWriter::~PyCallbackIOWriter() {
+ PyThreadLock gil;
+ Py_DECREF(callback);
+}
+
+PyCallbackIOReader::PyCallbackIOReader(PyObject* callback, size_t bs)
+ : callback(callback), bs(bs) {
+ PyThreadLock gil;
+ Py_INCREF(callback);
+ name = "PyCallbackIOReader";
+}
+
+size_t PyCallbackIOReader::operator()(void* ptrv, size_t size, size_t nitems) {
+ size_t rs = size * nitems;
+ size_t nb = 0;
+ char* ptr = (char*)ptrv;
+ PyThreadLock gil;
+ while (rs > 0) {
+ size_t ri = rs > bs ? bs : rs;
+ PyObject* result = PyObject_CallFunction(callback, "(n)", ri);
+ if (result == nullptr) {
+ FAISS_THROW_MSG("propagate py error");
+ }
+ if (!PyBytes_Check(result)) {
+ Py_DECREF(result);
+ FAISS_THROW_MSG("read callback did not return a bytes object");
+ }
+ size_t sz = PyBytes_Size(result);
+ if (sz == 0) {
+ Py_DECREF(result);
+ break;
+ }
+ nb += sz;
+ if (sz > rs) {
+ Py_DECREF(result);
+ FAISS_THROW_FMT(
+ "read callback returned %zd bytes (asked %zd)", sz, rs);
+ }
+ memcpy(ptr, PyBytes_AsString(result), sz);
+ Py_DECREF(result);
+ ptr += sz;
+ rs -= sz;
+ }
+ return nb / size;
+}
+
+PyCallbackIOReader::~PyCallbackIOReader() {
+ PyThreadLock gil;
+ Py_DECREF(callback);
+}
+
+/***********************************************************
+ * Callbacks for IDSelector
+ ***********************************************************/
+
+PyCallbackIDSelector::PyCallbackIDSelector(PyObject* callback)
+ : callback(callback) {
+ PyThreadLock gil;
+ Py_INCREF(callback);
+}
+
+bool PyCallbackIDSelector::is_member(faiss::idx_t id) const {
+ FAISS_THROW_IF_NOT((id >> 32) == 0);
+ PyThreadLock gil;
+ PyObject* result = PyObject_CallFunction(callback, "(n)", int(id));
+ if (result == nullptr) {
+ FAISS_THROW_MSG("propagate py error");
+ }
+ bool b = PyObject_IsTrue(result);
+ Py_DECREF(result);
+ return b;
+}
+
+PyCallbackIDSelector::~PyCallbackIDSelector() {
+ PyThreadLock gil;
+ Py_DECREF(callback);
+}
+
+/***********************************************************
+ * Callbacks for IVF index sharding
+ ***********************************************************/
+
+PyCallbackShardingFunction::PyCallbackShardingFunction(PyObject* callback)
+ : callback(callback) {
+ PyThreadLock gil;
+ Py_INCREF(callback);
+}
+
+int64_t PyCallbackShardingFunction::operator()(int64_t i, int64_t shard_count) {
+ PyThreadLock gil;
+ PyObject* shard_id = PyObject_CallFunction(callback, "LL", i, shard_count);
+ if (shard_id == nullptr) {
+ FAISS_THROW_MSG("propagate py error");
+ }
+ return PyLong_AsLongLong(shard_id);
+}
+
+PyCallbackShardingFunction::~PyCallbackShardingFunction() {
+ PyThreadLock gil;
+ Py_DECREF(callback);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/python_callbacks.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/python_callbacks.h
new file mode 100644
index 0000000..072e69f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/python_callbacks.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/IVFlib.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/io.h>
+#include <faiss/invlists/InvertedLists.h>
+#include "Python.h"
+
+// all callbacks have to acquire the GIL on input
+
+/***********************************************************
+ * Callbacks for IO reader and writer
+ ***********************************************************/
+
+struct PyCallbackIOWriter : faiss::IOWriter {
+ PyObject* callback;
+ size_t bs; // maximum write size
+
+ /** Callback: Python function that takes a bytes object and
+ * returns the number of bytes successfully written.
+ */
+ explicit PyCallbackIOWriter(PyObject* callback, size_t bs = 1024 * 1024);
+
+ size_t operator()(const void* ptrv, size_t size, size_t nitems) override;
+
+ ~PyCallbackIOWriter() override;
+};
+
+struct PyCallbackIOReader : faiss::IOReader {
+ PyObject* callback;
+ size_t bs; // maximum buffer size
+
+ /** Callback: Python function that takes a size and returns a
+ * bytes object with the resulting read */
+ explicit PyCallbackIOReader(PyObject* callback, size_t bs = 1024 * 1024);
+
+ size_t operator()(void* ptrv, size_t size, size_t nitems) override;
+
+ ~PyCallbackIOReader() override;
+};
+
+/***********************************************************
+ * Callbacks for IDSelector
+ ***********************************************************/
+
+struct PyCallbackIDSelector : faiss::IDSelector {
+ PyObject* callback;
+
+ explicit PyCallbackIDSelector(PyObject* callback);
+
+ bool is_member(faiss::idx_t id) const override;
+
+ ~PyCallbackIDSelector() override;
+};
+
+/***********************************************************
+ * Callbacks for IVF index sharding
+ ***********************************************************/
+
+struct PyCallbackShardingFunction : faiss::ivflib::ShardingFunction {
+ PyObject* callback;
+
+ explicit PyCallbackShardingFunction(PyObject* callback);
+
+ int64_t operator()(int64_t i, int64_t shard_count) override;
+
+ ~PyCallbackShardingFunction() override;
+
+ PyCallbackShardingFunction(const PyCallbackShardingFunction&) = delete;
+ PyCallbackShardingFunction(PyCallbackShardingFunction&&) noexcept = default;
+ PyCallbackShardingFunction& operator=(const PyCallbackShardingFunction&) =
+ default;
+ PyCallbackShardingFunction& operator=(PyCallbackShardingFunction&&) =
+ default;
+};
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/setup.py b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/setup.py
new file mode 100644
index 0000000..23611cb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/setup.py
@@ -0,0 +1,122 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+from __future__ import print_function
+
+import os
+import platform
+import shutil
+
+from setuptools import find_packages, setup
+
+# make the faiss python package dir
+shutil.rmtree("faiss", ignore_errors=True)
+os.mkdir("faiss")
+shutil.copytree("contrib", "faiss/contrib")
+shutil.copyfile("__init__.py", "faiss/__init__.py")
+shutil.copyfile("loader.py", "faiss/loader.py")
+shutil.copyfile("class_wrappers.py", "faiss/class_wrappers.py")
+shutil.copyfile("gpu_wrappers.py", "faiss/gpu_wrappers.py")
+shutil.copyfile("extra_wrappers.py", "faiss/extra_wrappers.py")
+shutil.copyfile("array_conversions.py", "faiss/array_conversions.py")
+
+ext = ".pyd" if platform.system() == "Windows" else ".so"
+prefix = "Release/" * (platform.system() == "Windows")
+
+swigfaiss_generic_lib = f"{prefix}_swigfaiss{ext}"
+swigfaiss_avx2_lib = f"{prefix}_swigfaiss_avx2{ext}"
+swigfaiss_avx512_lib = f"{prefix}_swigfaiss_avx512{ext}"
+swigfaiss_avx512_spr_lib = f"{prefix}_swigfaiss_avx512_spr{ext}"
+callbacks_lib = f"{prefix}libfaiss_python_callbacks{ext}"
+swigfaiss_sve_lib = f"{prefix}_swigfaiss_sve{ext}"
+faiss_example_external_module_lib = f"_faiss_example_external_module{ext}"
+
+found_swigfaiss_generic = os.path.exists(swigfaiss_generic_lib)
+found_swigfaiss_avx2 = os.path.exists(swigfaiss_avx2_lib)
+found_swigfaiss_avx512 = os.path.exists(swigfaiss_avx512_lib)
+found_swigfaiss_avx512_spr = os.path.exists(swigfaiss_avx512_spr_lib)
+found_callbacks = os.path.exists(callbacks_lib)
+found_swigfaiss_sve = os.path.exists(swigfaiss_sve_lib)
+found_faiss_example_external_module_lib = os.path.exists(
+ faiss_example_external_module_lib
+)
+
+assert (
+ found_swigfaiss_generic
+ or found_swigfaiss_avx2
+ or found_swigfaiss_avx512
+ or found_swigfaiss_avx512_spr
+ or found_swigfaiss_sve
+ or found_faiss_example_external_module_lib
+), (
+ f"Could not find {swigfaiss_generic_lib} or "
+ f"{swigfaiss_avx2_lib} or {swigfaiss_avx512_lib} or {swigfaiss_avx512_spr_lib} or {swigfaiss_sve_lib} or {faiss_example_external_module_lib}. "
+ f"Faiss may not be compiled yet."
+)
+
+if found_swigfaiss_generic:
+ print(f"Copying {swigfaiss_generic_lib}")
+ shutil.copyfile("swigfaiss.py", "faiss/swigfaiss.py")
+ shutil.copyfile(swigfaiss_generic_lib, f"faiss/_swigfaiss{ext}")
+
+if found_swigfaiss_avx2:
+ print(f"Copying {swigfaiss_avx2_lib}")
+ shutil.copyfile("swigfaiss_avx2.py", "faiss/swigfaiss_avx2.py")
+ shutil.copyfile(swigfaiss_avx2_lib, f"faiss/_swigfaiss_avx2{ext}")
+
+if found_swigfaiss_avx512:
+ print(f"Copying {swigfaiss_avx512_lib}")
+ shutil.copyfile("swigfaiss_avx512.py", "faiss/swigfaiss_avx512.py")
+ shutil.copyfile(swigfaiss_avx512_lib, f"faiss/_swigfaiss_avx512{ext}")
+
+if found_swigfaiss_avx512_spr:
+ print(f"Copying {swigfaiss_avx512_spr_lib}")
+ shutil.copyfile("swigfaiss_avx512_spr.py", "faiss/swigfaiss_avx512_spr.py")
+ shutil.copyfile(swigfaiss_avx512_spr_lib, f"faiss/_swigfaiss_avx512_spr{ext}")
+
+if found_callbacks:
+ print(f"Copying {callbacks_lib}")
+ shutil.copyfile(callbacks_lib, f"faiss/{callbacks_lib}")
+
+if found_swigfaiss_sve:
+ print(f"Copying {swigfaiss_sve_lib}")
+ shutil.copyfile("swigfaiss_sve.py", "faiss/swigfaiss_sve.py")
+ shutil.copyfile(swigfaiss_sve_lib, f"faiss/_swigfaiss_sve{ext}")
+
+if found_faiss_example_external_module_lib:
+ print(f"Copying {faiss_example_external_module_lib}")
+ shutil.copyfile(
+ "faiss_example_external_module.py", "faiss/faiss_example_external_module.py"
+ )
+ shutil.copyfile(
+ faiss_example_external_module_lib,
+ f"faiss/_faiss_example_external_module{ext}",
+ )
+
+long_description = """
+Faiss is a library for efficient similarity search and clustering of dense
+vectors. It contains algorithms that search in sets of vectors of any size,
+ up to ones that possibly do not fit in RAM. It also contains supporting
+code for evaluation and parameter tuning. Faiss is written in C++ with
+complete wrappers for Python/numpy. Some of the most useful algorithms
+are implemented on the GPU. It is developed by Facebook AI Research.
+"""
+setup(
+ name="faiss",
+ version="1.10.0",
+ description="A library for efficient similarity search and clustering of dense vectors",
+ long_description=long_description,
+ url="https://github.com/facebookresearch/faiss",
+ author="Matthijs Douze, Jeff Johnson, Herve Jegou, Lucas Hosseini",
+ author_email="[email protected]",
+ license="MIT",
+ keywords="search nearest neighbors",
+ install_requires=["numpy", "packaging"],
+ packages=["faiss", "faiss.contrib", "faiss.contrib.torch"],
+ package_data={
+ "faiss": ["*.so", "*.pyd"],
+ },
+ zip_safe=False,
+)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/python/swigfaiss.swig b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/swigfaiss.swig
new file mode 100644
index 0000000..4312027
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/python/swigfaiss.swig
@@ -0,0 +1,1322 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- C++ -*-
+
+// This file describes the C++-scripting language bridge for Python (and formerly Lua).
+// It contains mainly includes and a few macros. There are
+// 2 preprocessor macros of interest:
+
+// SWIGPYTHON: Python-specific code
+// GPU_WRAPPER: also compile interfaces for GPU.
+
+%module swigfaiss;
+
+%ignore faiss::ZmqDistanceComputer::setup_experimental_top_degree_disk_read;
+
+
+%ignore faiss::HNSW::pq_data_loader;
+%ignore faiss::HNSW::pq_pruning_ratio;
+%ignore faiss::HNSW::pq_codes;
+%ignore faiss::HNSW::code_size;
+
+// NOTE: While parsing the headers to generate the interface, SWIG does not know
+// about `_MSC_VER`.
+// TODO: Remove the need for this hack.
+#ifdef SWIGWIN
+#define _MSC_VER
+%include <windows.i>
+#endif // SWIGWIN
+
+// fbode SWIG fails on warnings, so make them non fatal
+#pragma SWIG nowarn=321
+#pragma SWIG nowarn=403
+#pragma SWIG nowarn=325
+#pragma SWIG nowarn=389
+#pragma SWIG nowarn=341
+#pragma SWIG nowarn=512
+#pragma SWIG nowarn=362
+#pragma SWIG nowarn=509
+
+// we need explict control of these typedefs...
+// %include <stdint.i>
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+
+// char != unsigned char AND char != signed char so be explicit
+typedef signed char int8_t;
+typedef short int16_t;
+typedef int int32_t;
+
+#ifdef SWIGWORDSIZE64
+typedef unsigned long uint64_t;
+typedef long int64_t;
+#else
+typedef unsigned long long uint64_t;
+typedef long long int64_t;
+#endif
+
+typedef uint64_t size_t;
+
+
+#define __restrict
+
+
+/*******************************************************************
+ * Copied verbatim to wrapper. Contains the C++-visible includes, and
+ * the language includes for their respective matrix libraries.
+ *******************************************************************/
+
+%{
+
+
+#include <stdint.h>
+#include <omp.h>
+
+
+
+#ifdef SWIGPYTHON
+
+#undef popcount64
+
+#define SWIG_FILE_WITH_INIT
+#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+#include <numpy/arrayobject.h>
+
+#endif
+
+#include <faiss/impl/io.h>
+
+#include <faiss/impl/maybe_owned_vector.h>
+#include <faiss/impl/mapped_io.h>
+#include <faiss/impl/zerocopy_io.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/VectorTransform.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/IndexLSH.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexIVFPQR.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexIVFIndependentQuantizer.h>
+
+#include <faiss/IndexFastScan.h>
+#include <faiss/IndexAdditiveQuantizerFastScan.h>
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/utils/simdlib.h>
+#include <faiss/impl/simd_result_handlers.h>
+
+#include <faiss/IndexIVFFastScan.h>
+#include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/utils/quantize_lut.h>
+
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/IndexIVFAdditiveQuantizer.h>
+#include <faiss/IndexIVFSpectralHash.h>
+#include <faiss/impl/ThreadedIndex.h>
+#include <faiss/IndexShards.h>
+#include <faiss/IndexShardsIVF.h>
+#include <faiss/IndexReplicas.h>
+#include <faiss/impl/HNSW.h>
+#include <faiss/IndexHNSW.h>
+
+#include <faiss/impl/kmeans1d.h>
+
+#include <faiss/impl/NNDescent.h>
+#include <faiss/IndexNNDescent.h>
+
+#include <faiss/impl/NSG.h>
+#include <faiss/IndexNSG.h>
+
+#include <faiss/MetaIndexes.h>
+#include <faiss/IndexIDMap.h>
+#include <faiss/IndexRefine.h>
+
+#include <faiss/IndexRowwiseMinMax.h>
+
+#include <faiss/impl/FaissAssert.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexBinaryIVF.h>
+#include <faiss/IndexBinaryFromFloat.h>
+#include <faiss/IndexBinaryHNSW.h>
+#include <faiss/IndexBinaryHash.h>
+
+#include <faiss/impl/io.h>
+#include <faiss/index_io.h>
+#include <faiss/clone_index.h>
+
+#include <faiss/IVFlib.h>
+#include <faiss/utils/utils.h>
+
+#include <faiss/utils/sorting.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/extra_distances.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/AlignedTable.h>
+#include <faiss/utils/partitioning.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/impl/AdditiveQuantizer.h>
+#include <faiss/impl/ResidualQuantizer.h>
+#include <faiss/impl/residual_quantizer_encode_steps.h>
+
+#include <faiss/impl/LocalSearchQuantizer.h>
+#include <faiss/impl/ProductAdditiveQuantizer.h>
+#include <faiss/impl/CodePacker.h>
+#include <faiss/utils/NeuralNet.h>
+
+#include <faiss/invlists/BlockInvertedLists.h>
+
+#ifndef _MSC_VER
+#include <faiss/invlists/OnDiskInvertedLists.h>
+#endif // !_MSC_VER
+
+#include <faiss/Clustering.h>
+
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/hamming_distance/common.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/MatrixStats.h>
+#include <faiss/index_factory.h>
+
+#include <faiss/impl/lattice_Zn.h>
+#include <faiss/IndexLattice.h>
+
+#include <faiss/IndexNeuralNetCodec.h>
+
+#include <faiss/impl/RaBitQuantizer.h>
+#include <faiss/IndexRaBitQ.h>
+#include <faiss/IndexIVFRaBitQ.h>
+
+%}
+
+/********************************************************
+ * GIL manipulation and exception handling
+ ********************************************************/
+
+#ifdef SWIGPYTHON
+// %catches(faiss::FaissException);
+
+
+// Python-specific: release GIL by default for all functions
+%exception {
+ Py_BEGIN_ALLOW_THREADS
+ try {
+ $action
+ } catch(faiss::FaissException & e) {
+ PyEval_RestoreThread(_save);
+
+ if (PyErr_Occurred()) {
+ // some previous code already set the error type.
+ } else {
+ PyErr_SetString(PyExc_RuntimeError, e.what());
+ }
+ SWIG_fail;
+ } catch(std::bad_alloc & ba) {
+ PyEval_RestoreThread(_save);
+ PyErr_SetString(PyExc_MemoryError, "std::bad_alloc");
+ SWIG_fail;
+ } catch(const std::exception& ex) {
+ PyEval_RestoreThread(_save);
+ std::string what = std::string("C++ exception ") + ex.what();
+ PyErr_SetString(PyExc_RuntimeError, what.c_str());
+ SWIG_fail;
+ }
+ Py_END_ALLOW_THREADS
+}
+
+#endif
+
+
+/*******************************************************************
+ * Types of vectors we want to manipulate at the scripting language
+ * level.
+ *******************************************************************/
+
+// simplified interface for vector
+namespace std {
+
+ template<class T>
+ class vector {
+ public:
+ vector();
+ void push_back(T);
+ void clear();
+ T * data();
+ size_t size();
+ T at (size_t n) const;
+ T & operator [] (size_t n);
+ void resize (size_t n);
+
+ void swap (vector<T> & other);
+ };
+};
+
+%include <std_string.i>
+%include <std_pair.i>
+%include <std_map.i>
+%include <std_shared_ptr.i>
+
+// primitive array types
+%template(Float32Vector) std::vector<float>;
+%template(Float64Vector) std::vector<double>;
+
+// weird interaction within C++ between char and signed char
+%ignore Int8Vector::swap;
+
+%template(Int8Vector) std::vector<int8_t>;
+%template(Int16Vector) std::vector<int16_t>;
+%template(Int32Vector) std::vector<int32_t>;
+%template(Int64Vector) std::vector<int64_t>;
+
+%template(UInt8Vector) std::vector<uint8_t>;
+%template(UInt16Vector) std::vector<uint16_t>;
+%template(UInt32Vector) std::vector<uint32_t>;
+%template(UInt64Vector) std::vector<uint64_t>;
+
+%template(Float32VectorVector) std::vector<std::vector<float> >;
+%template(UInt8VectorVector) std::vector<std::vector<uint8_t> >;
+%template(Int32VectorVector) std::vector<std::vector<int32_t> >;
+%template(Int64VectorVector) std::vector<std::vector<int64_t> >;
+%template(VectorTransformVector) std::vector<faiss::VectorTransform*>;
+%template(OperatingPointVector) std::vector<faiss::OperatingPoint>;
+%template(InvertedListsPtrVector) std::vector<faiss::InvertedLists*>;
+%template(RepeatVector) std::vector<faiss::Repeat>;
+%template(ClusteringIterationStatsVector) std::vector<faiss::ClusteringIterationStats>;
+%template(ParameterRangeVector) std::vector<faiss::ParameterRange>;
+%template(MaybeOwnedVectorUInt8Vector) std::vector<faiss::MaybeOwnedVector<uint8_t> >;
+%template(MaybeOwnedVectorInt32Vector) std::vector<faiss::MaybeOwnedVector<int32_t> >;
+%template(MaybeOwnedVectorFloat32Vector) std::vector<faiss::MaybeOwnedVector<float> >;
+
+#ifndef SWIGWIN
+%template(OnDiskOneListVector) std::vector<faiss::OnDiskOneList>;
+#endif // !SWIGWIN
+
+#ifdef GPU_WRAPPER
+%template(GpuResourcesVector) std::vector<faiss::gpu::GpuResourcesProvider*>;
+#endif
+
+// produces an error on the Mac
+%ignore faiss::hamming;
+
+/*******************************************************************
+ * Parse headers
+ *******************************************************************/
+
+%include <faiss/impl/platform_macros.h>
+
+%ignore *::cmp;
+
+%include <faiss/utils/ordered_key_value.h>
+%include <faiss/utils/Heap.h>
+
+// this ignore seems to be ignored, so disable W362 above
+%ignore faiss::AlignedTable::operator=;
+
+%include <faiss/utils/AlignedTable.h>
+%include <faiss/utils/partitioning.h>
+%include <faiss/utils/hamming.h>
+%include <faiss/utils/hamming_distance/common.h>
+
+int get_num_gpus();
+void gpu_profiler_start();
+void gpu_profiler_stop();
+void gpu_sync_all_devices();
+
+#ifdef GPU_WRAPPER
+#ifdef FAISS_ENABLE_ROCM
+
+%shared_ptr(faiss::gpu::GpuResources);
+%shared_ptr(faiss::gpu::StandardGpuResourcesImpl);
+
+%{
+
+#include <faiss/gpu-rocm/StandardGpuResources.h>
+#include <faiss/gpu-rocm/GpuIndicesOptions.h>
+#include <faiss/gpu-rocm/GpuClonerOptions.h>
+#include <faiss/gpu-rocm/GpuIndex.h>
+#include <faiss/gpu-rocm/GpuIndexFlat.h>
+#include <faiss/gpu-rocm/GpuIndexIVF.h>
+#include <faiss/gpu-rocm/GpuIndexIVFPQ.h>
+#include <faiss/gpu-rocm/GpuIndexIVFFlat.h>
+#include <faiss/gpu-rocm/GpuIndexIVFScalarQuantizer.h>
+#include <faiss/gpu-rocm/GpuIndexBinaryFlat.h>
+#include <faiss/gpu-rocm/GpuAutoTune.h>
+#include <faiss/gpu-rocm/GpuCloner.h>
+#include <faiss/gpu-rocm/GpuDistance.h>
+#include <faiss/gpu-rocm/GpuIcmEncoder.h>
+
+int get_num_gpus()
+{
+ return faiss::gpu::getNumDevices();
+}
+
+void gpu_profiler_start()
+{
+ return faiss::gpu::profilerStart();
+}
+
+void gpu_profiler_stop()
+{
+ return faiss::gpu::profilerStop();
+}
+
+void gpu_sync_all_devices()
+{
+ return faiss::gpu::synchronizeAllDevices();
+}
+
+%}
+
+%template() std::pair<int, uint64_t>;
+%template() std::map<std::string, std::pair<int, uint64_t> >;
+%template() std::map<int, std::map<std::string, std::pair<int, uint64_t> > >;
+
+// causes weird wrapper bug
+%ignore *::allocMemoryHandle;
+%ignore faiss::gpu::GpuMemoryReservation;
+%ignore faiss::gpu::GpuMemoryReservation::operator=(GpuMemoryReservation&&);
+%ignore faiss::gpu::AllocType;
+
+%include <faiss/gpu-rocm/GpuResources.h>
+%include <faiss/gpu-rocm/StandardGpuResources.h>
+
+typedef ihipStream_t* hipStream_t;
+
+%inline %{
+
+// interop between pytorch exposed hipStream_t and faiss
+hipStream_t cast_integer_to_cudastream_t(int64_t x) {
+ return (hipStream_t) x;
+}
+
+int64_t cast_cudastream_t_to_integer(hipStream_t x) {
+ return (int64_t) x;
+}
+
+%}
+
+#else // FAISS_ENABLE_ROCM
+
+%shared_ptr(faiss::gpu::GpuResources);
+%shared_ptr(faiss::gpu::StandardGpuResourcesImpl);
+
+%{
+
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/GpuIndicesOptions.h>
+#include <faiss/gpu/GpuClonerOptions.h>
+#include <faiss/gpu/GpuIndex.h>
+#include <faiss/gpu/GpuIndexCagra.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVF.h>
+#include <faiss/gpu/GpuIndexIVFPQ.h>
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/GpuIndexIVFScalarQuantizer.h>
+#include <faiss/gpu/GpuIndexBinaryFlat.h>
+#include <faiss/gpu/GpuAutoTune.h>
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/gpu/GpuDistance.h>
+#include <faiss/gpu/GpuIcmEncoder.h>
+
+int get_num_gpus()
+{
+ return faiss::gpu::getNumDevices();
+}
+
+void gpu_profiler_start()
+{
+ return faiss::gpu::profilerStart();
+}
+
+void gpu_profiler_stop()
+{
+ return faiss::gpu::profilerStop();
+}
+
+void gpu_sync_all_devices()
+{
+ return faiss::gpu::synchronizeAllDevices();
+}
+
+%}
+
+%template() std::pair<int, uint64_t>;
+%template() std::map<std::string, std::pair<int, uint64_t> >;
+%template() std::map<int, std::map<std::string, std::pair<int, uint64_t> > >;
+
+// causes weird wrapper bug
+%ignore *::allocMemoryHandle;
+%ignore faiss::gpu::GpuMemoryReservation;
+%ignore faiss::gpu::GpuMemoryReservation::operator=(GpuMemoryReservation&&);
+%ignore faiss::gpu::AllocType;
+
+%include <faiss/gpu/GpuResources.h>
+%include <faiss/gpu/StandardGpuResources.h>
+
+typedef CUstream_st* cudaStream_t;
+
+%inline %{
+
+// interop between pytorch exposed cudaStream_t and faiss
+cudaStream_t cast_integer_to_cudastream_t(int64_t x) {
+ return (cudaStream_t) x;
+}
+
+int64_t cast_cudastream_t_to_integer(cudaStream_t x) {
+ return (int64_t) x;
+}
+
+%}
+
+#endif // FAISS_ENABLE_ROCM
+#else // GPU_WRAPPER
+
+%{
+int get_num_gpus()
+{
+ return 0;
+}
+
+void gpu_profiler_start()
+{
+}
+
+void gpu_profiler_stop()
+{
+}
+
+void gpu_sync_all_devices()
+{
+}
+%}
+
+
+#endif // GPU_WRAPPER
+
+// order matters because includes are not recursive
+
+%include <faiss/utils/utils.h>
+%template(CombinerRangeKNNfloat) faiss::CombinerRangeKNN<float>;
+%template(CombinerRangeKNNint16) faiss::CombinerRangeKNN<int16_t>;
+
+%include <faiss/utils/distances.h>
+%include <faiss/utils/random.h>
+%include <faiss/utils/sorting.h>
+
+%include <faiss/MetricType.h>
+
+%newobject *::get_distance_computer() const;
+%newobject *::get_CodePacker() const;
+
+%include <faiss/Index.h>
+
+%include <faiss/impl/DistanceComputer.h>
+
+%include <faiss/impl/io.h>
+
+%ignore faiss::MmappedFileMappingOwner::p_impl;
+
+%include <faiss/impl/maybe_owned_vector.h>
+%include <faiss/impl/mapped_io.h>
+%include <faiss/impl/zerocopy_io.h>
+
+%newobject *::get_FlatCodesDistanceComputer() const;
+%include <faiss/IndexFlatCodes.h>
+%include <faiss/IndexFlat.h>
+%include <faiss/Clustering.h>
+
+%include <faiss/utils/extra_distances.h>
+
+%ignore faiss::ProductQuantizer::get_centroids(size_t,size_t) const;
+
+%include <faiss/impl/Quantizer.h>
+%include <faiss/impl/ProductQuantizer.h>
+%include <faiss/impl/AdditiveQuantizer.h>
+%include <faiss/impl/residual_quantizer_encode_steps.h>
+%include <faiss/impl/ResidualQuantizer.h>
+%include <faiss/impl/LocalSearchQuantizer.h>
+%include <faiss/impl/ProductAdditiveQuantizer.h>
+%include <faiss/impl/CodePacker.h>
+
+%include <faiss/VectorTransform.h>
+%include <faiss/IndexPreTransform.h>
+%include <faiss/IndexRefine.h>
+%include <faiss/IndexLSH.h>
+%include <faiss/impl/PolysemousTraining.h>
+%include <faiss/IndexPQ.h>
+%include <faiss/IndexAdditiveQuantizer.h>
+%include <faiss/impl/io.h>
+
+%include <faiss/invlists/InvertedLists.h>
+%include <faiss/invlists/InvertedListsIOHook.h>
+%ignore BlockInvertedListsIOHook;
+%include <faiss/invlists/BlockInvertedLists.h>
+%include <faiss/invlists/DirectMap.h>
+%include <faiss/IndexIVF.h>
+// NOTE(hoss): SWIG (wrongly) believes the overloaded const version shadows the
+// non-const one.
+%warnfilter(509) extract_index_ivf;
+%warnfilter(509) try_extract_index_ivf;
+%include <faiss/IVFlib.h>
+%include <faiss/impl/ScalarQuantizer.h>
+%include <faiss/IndexScalarQuantizer.h>
+%include <faiss/IndexIVFSpectralHash.h>
+%include <faiss/IndexIVFAdditiveQuantizer.h>
+%include <faiss/impl/HNSW.h>
+%include <faiss/IndexHNSW.h>
+
+%include <faiss/impl/kmeans1d.h>
+
+%ignore faiss::nndescent::Nhood::lock;
+%include <faiss/impl/NNDescent.h>
+%include <faiss/IndexNNDescent.h>
+
+%include <faiss/IndexIVFFlat.h>
+
+%warnfilter(509) faiss::nsg::Graph< int >::at(int,int);
+
+%include <faiss/impl/NSG.h>
+
+%template(NSG_Graph_int) faiss::nsg::Graph<int>;
+
+// not using %shared_ptr to avoid mem leaks
+%extend faiss::NSG {
+ faiss::nsg::Graph<int>* get_final_graph() {
+ return $self->final_graph.get();
+ }
+}
+
+%include <faiss/IndexNSG.h>
+
+#ifndef SWIGWIN
+%warnfilter(401) faiss::OnDiskInvertedListsIOHook;
+%ignore OnDiskInvertedListsIOHook;
+%include <faiss/invlists/OnDiskInvertedLists.h>
+#endif // !SWIGWIN
+
+%include <faiss/impl/lattice_Zn.h>
+%include <faiss/IndexLattice.h>
+
+%ignore faiss::IndexIVFPQ::alloc_type;
+%include <faiss/IndexIVFPQ.h>
+%include <faiss/IndexIVFPQR.h>
+%include <faiss/Index2Layer.h>
+
+%include <faiss/IndexFastScan.h>
+%include <faiss/IndexAdditiveQuantizerFastScan.h>
+%include <faiss/IndexPQFastScan.h>
+
+// NOTE(matthijs) let's not go into wrapping simdlib
+struct faiss::simd16uint16 {};
+
+%include <faiss/impl/simd_result_handlers.h>
+%include <faiss/IndexIVFFastScan.h>
+%include <faiss/IndexIVFAdditiveQuantizerFastScan.h>
+%include <faiss/IndexIVFIndependentQuantizer.h>
+
+%include <faiss/IndexIVFPQFastScan.h>
+%include <faiss/utils/quantize_lut.h>
+
+%include <faiss/IndexBinary.h>
+%include <faiss/IndexBinaryFlat.h>
+%include <faiss/IndexBinaryIVF.h>
+%include <faiss/IndexBinaryFromFloat.h>
+%include <faiss/IndexBinaryHNSW.h>
+%include <faiss/IndexBinaryHash.h>
+
+%include <faiss/impl/ThreadedIndex.h>
+%template(ThreadedIndexBase) faiss::ThreadedIndex<faiss::Index>;
+%template(ThreadedIndexBaseBinary) faiss::ThreadedIndex<faiss::IndexBinary>;
+
+%include <faiss/IndexShards.h>
+%template(IndexShards) faiss::IndexShardsTemplate<faiss::Index>;
+%template(IndexBinaryShards) faiss::IndexShardsTemplate<faiss::IndexBinary>;
+%include <faiss/IndexShardsIVF.h>
+
+%include <faiss/IndexReplicas.h>
+%template(IndexReplicas) faiss::IndexReplicasTemplate<faiss::Index>;
+%template(IndexBinaryReplicas) faiss::IndexReplicasTemplate<faiss::IndexBinary>;
+
+%include <faiss/MetaIndexes.h>
+
+%include <faiss/IndexRowwiseMinMax.h>
+
+%include <faiss/utils/NeuralNet.h>
+%template(Tensor2D) faiss::nn::Tensor2DTemplate<float>;
+%template(Int32Tensor2D) faiss::nn::Tensor2DTemplate<int32_t>;
+
+%include <faiss/IndexNeuralNetCodec.h>
+
+%include <faiss/impl/RaBitQuantizer.h>
+%include <faiss/IndexRaBitQ.h>
+%include <faiss/IndexIVFRaBitQ.h>
+
+%ignore faiss::BufferList::Buffer;
+%ignore faiss::RangeSearchPartialResult::QueryResult;
+%ignore faiss::IDSelectorBatch::set;
+%ignore faiss::IDSelectorBatch::bloom;
+%ignore faiss::InterruptCallback::instance;
+%ignore faiss::InterruptCallback::lock;
+
+%include <faiss/impl/AuxIndexStructures.h>
+%include <faiss/impl/IDSelector.h>
+
+%include <faiss/IndexIDMap.h>
+%template(IndexIDMap) faiss::IndexIDMapTemplate<faiss::Index>;
+%template(IndexBinaryIDMap) faiss::IndexIDMapTemplate<faiss::IndexBinary>;
+%template(IndexIDMap2) faiss::IndexIDMap2Template<faiss::Index>;
+%template(IndexBinaryIDMap2) faiss::IndexIDMap2Template<faiss::IndexBinary>;
+
+
+%include <faiss/utils/approx_topk/mode.h>
+
+#ifdef GPU_WRAPPER
+
+#ifdef FAISS_ENABLE_ROCM
+
+// quiet SWIG warnings
+%ignore faiss::gpu::GpuIndexIVF::GpuIndexIVF;
+
+%include <faiss/gpu-rocm/GpuIndicesOptions.h>
+%include <faiss/gpu-rocm/GpuClonerOptions.h>
+%include <faiss/gpu-rocm/GpuIndex.h>
+%include <faiss/gpu-rocm/GpuIndexFlat.h>
+%include <faiss/gpu-rocm/GpuIndexIVF.h>
+%include <faiss/gpu-rocm/GpuIndexIVFPQ.h>
+%include <faiss/gpu-rocm/GpuIndexIVFFlat.h>
+%include <faiss/gpu-rocm/GpuIndexIVFScalarQuantizer.h>
+%include <faiss/gpu-rocm/GpuIndexBinaryFlat.h>
+%include <faiss/gpu-rocm/GpuDistance.h>
+%include <faiss/gpu-rocm/GpuIcmEncoder.h>
+
+#else // FAISS_ENABLE_ROCM
+
+// quiet SWIG warnings
+%ignore faiss::gpu::GpuIndexIVF::GpuIndexIVF;
+
+%include <faiss/gpu/GpuIndicesOptions.h>
+%include <faiss/gpu/GpuClonerOptions.h>
+%include <faiss/gpu/GpuIndex.h>
+#ifdef FAISS_ENABLE_CUVS
+%include <faiss/gpu/GpuIndexCagra.h>
+#endif
+%include <faiss/gpu/GpuIndexFlat.h>
+%include <faiss/gpu/GpuIndexIVF.h>
+%include <faiss/gpu/GpuIndexIVFPQ.h>
+%include <faiss/gpu/GpuIndexIVFFlat.h>
+%include <faiss/gpu/GpuIndexIVFScalarQuantizer.h>
+%include <faiss/gpu/GpuIndexBinaryFlat.h>
+%include <faiss/gpu/GpuDistance.h>
+%include <faiss/gpu/GpuIcmEncoder.h>
+
+#endif // FAISS_ENABLE_ROCM
+#endif
+
+
+
+
+
+
+/*******************************************************************
+ * downcast return of some functions so that the sub-class is used
+ * instead of the generic upper-class.
+ *******************************************************************/
+
+
+#ifdef SWIGPYTHON
+
+%define DOWNCAST(subclass)
+ if (dynamic_cast<faiss::subclass *> ($1)) {
+ $result = SWIG_NewPointerObj($1,SWIGTYPE_p_faiss__ ## subclass,$owner);
+ } else
+%enddef
+
+%define DOWNCAST2(subclass, longname)
+ if (dynamic_cast<faiss::subclass *> ($1)) {
+ $result = SWIG_NewPointerObj($1,SWIGTYPE_p_faiss__ ## longname,$owner);
+ } else
+%enddef
+
+%define DOWNCAST_GPU(subclass)
+ if (dynamic_cast<faiss::gpu::subclass *> ($1)) {
+ $result = SWIG_NewPointerObj($1,SWIGTYPE_p_faiss__gpu__ ## subclass,$owner);
+ } else
+%enddef
+
+#endif
+
+%newobject read_index;
+%newobject read_index_binary;
+%newobject read_VectorTransform;
+%newobject read_ProductQuantizer;
+%newobject clone_index;
+%newobject clone_binary_index;
+%newobject clone_Quantizer;
+%newobject clone_VectorTransform;
+
+// Subclasses should appear before their parent
+%typemap(out) faiss::Index * {
+ DOWNCAST2 ( IndexIDMap2, IndexIDMap2TemplateT_faiss__Index_t )
+ DOWNCAST2 ( IndexIDMap, IndexIDMapTemplateT_faiss__Index_t )
+ DOWNCAST ( IndexShardsIVF )
+ DOWNCAST2 ( IndexShards, IndexShardsTemplateT_faiss__Index_t )
+ DOWNCAST2 ( IndexReplicas, IndexReplicasTemplateT_faiss__Index_t )
+ DOWNCAST ( IndexIVFIndependentQuantizer)
+ DOWNCAST ( IndexIVFPQR )
+ DOWNCAST ( IndexIVFPQ )
+ DOWNCAST ( IndexIVFPQFastScan )
+ DOWNCAST ( IndexIVFSpectralHash )
+ DOWNCAST ( IndexIVFScalarQuantizer )
+ DOWNCAST ( IndexIVFResidualQuantizer )
+ DOWNCAST ( IndexIVFLocalSearchQuantizer )
+ DOWNCAST ( IndexIVFProductResidualQuantizer )
+ DOWNCAST ( IndexIVFProductLocalSearchQuantizer )
+ DOWNCAST ( IndexIVFResidualQuantizerFastScan )
+ DOWNCAST ( IndexIVFLocalSearchQuantizerFastScan )
+ DOWNCAST ( IndexIVFProductResidualQuantizerFastScan )
+ DOWNCAST ( IndexIVFProductLocalSearchQuantizerFastScan )
+ DOWNCAST ( IndexIVFFlatDedup )
+ DOWNCAST ( IndexIVFFlat )
+ DOWNCAST ( IndexIVF )
+ DOWNCAST ( IndexFlatIP )
+ DOWNCAST ( IndexFlatL2 )
+ DOWNCAST ( IndexFlat )
+ DOWNCAST ( IndexRefineFlat )
+ DOWNCAST ( IndexRefine )
+ DOWNCAST ( IndexPQFastScan )
+ DOWNCAST ( IndexPQ )
+ DOWNCAST ( IndexResidualQuantizer )
+ DOWNCAST ( IndexLocalSearchQuantizer )
+ DOWNCAST ( IndexResidualQuantizerFastScan )
+ DOWNCAST ( IndexLocalSearchQuantizerFastScan )
+ DOWNCAST ( IndexProductResidualQuantizerFastScan )
+ DOWNCAST ( IndexProductLocalSearchQuantizerFastScan )
+ DOWNCAST ( ResidualCoarseQuantizer )
+ DOWNCAST ( LocalSearchCoarseQuantizer )
+ DOWNCAST ( IndexProductResidualQuantizer )
+ DOWNCAST ( IndexProductLocalSearchQuantizer )
+ DOWNCAST ( IndexScalarQuantizer )
+ DOWNCAST ( IndexLSH )
+ DOWNCAST ( IndexLattice )
+ DOWNCAST ( IndexPreTransform )
+ DOWNCAST ( MultiIndexQuantizer )
+ DOWNCAST ( IndexHNSWFlat )
+ DOWNCAST ( IndexHNSWPQ )
+ DOWNCAST ( IndexHNSWSQ )
+ DOWNCAST ( IndexHNSW )
+ DOWNCAST ( IndexHNSW2Level )
+ DOWNCAST ( IndexNNDescentFlat )
+ DOWNCAST ( IndexNSGFlat )
+ DOWNCAST ( IndexNSGPQ )
+ DOWNCAST ( IndexNSGSQ )
+ DOWNCAST ( Index2Layer )
+ DOWNCAST ( IndexRandom )
+ DOWNCAST ( IndexRowwiseMinMax )
+ DOWNCAST ( IndexRowwiseMinMaxFP16 )
+#ifdef GPU_WRAPPER
+#ifdef FAISS_ENABLE_CUVS
+ DOWNCAST_GPU ( GpuIndexCagra )
+#endif
+ DOWNCAST_GPU ( GpuIndexIVFPQ )
+ DOWNCAST_GPU ( GpuIndexIVFFlat )
+ DOWNCAST_GPU ( GpuIndexIVFScalarQuantizer )
+ DOWNCAST_GPU ( GpuIndexFlat )
+#endif
+ // default for non-recognized classes
+ DOWNCAST ( Index )
+ if ($1 == NULL)
+ {
+#ifdef SWIGPYTHON
+ $result = SWIG_Py_Void();
+#endif
+ } else {
+ assert(false);
+ }
+}
+
+
+%typemap(out) faiss::IndexBinary * {
+ DOWNCAST2 ( IndexBinaryReplicas, IndexReplicasTemplateT_faiss__IndexBinary_t )
+ DOWNCAST2 ( IndexBinaryIDMap2, IndexIDMap2TemplateT_faiss__IndexBinary_t )
+ DOWNCAST2 ( IndexBinaryIDMap, IndexIDMapTemplateT_faiss__IndexBinary_t )
+ DOWNCAST ( IndexBinaryIVF )
+ DOWNCAST ( IndexBinaryFlat )
+ DOWNCAST ( IndexBinaryFromFloat )
+ DOWNCAST ( IndexBinaryHNSW )
+ DOWNCAST ( IndexBinaryHash )
+ DOWNCAST ( IndexBinaryMultiHash )
+#ifdef GPU_WRAPPER
+ DOWNCAST_GPU ( GpuIndexBinaryFlat )
+#endif
+ // default for non-recognized classes
+ DOWNCAST ( IndexBinary )
+ if ($1 == NULL)
+ {
+#ifdef SWIGPYTHON
+ $result = SWIG_Py_Void();
+#endif
+ } else {
+ assert(false);
+ }
+}
+
+%typemap(out) faiss::VectorTransform * {
+ DOWNCAST (RemapDimensionsTransform)
+ DOWNCAST (OPQMatrix)
+ DOWNCAST (PCAMatrix)
+ DOWNCAST (ITQMatrix)
+ DOWNCAST (RandomRotationMatrix)
+ DOWNCAST (LinearTransform)
+ DOWNCAST (NormalizationTransform)
+ DOWNCAST (CenteringTransform)
+ DOWNCAST (ITQTransform)
+ DOWNCAST (VectorTransform)
+ {
+ assert(false);
+ }
+}
+
+%typemap(out) faiss::InvertedLists * {
+ DOWNCAST (ArrayInvertedLists)
+ DOWNCAST (BlockInvertedLists)
+#ifndef SWIGWIN
+ DOWNCAST (OnDiskInvertedLists)
+#endif // !SWIGWIN
+ DOWNCAST (VStackInvertedLists)
+ DOWNCAST (HStackInvertedLists)
+ DOWNCAST (MaskedInvertedLists)
+ DOWNCAST (InvertedLists)
+ {
+ assert(false);
+ }
+}
+
+%typemap(out) faiss::Quantizer * {
+ DOWNCAST (ScalarQuantizer)
+ DOWNCAST (ProductQuantizer)
+ DOWNCAST (LocalSearchQuantizer)
+ DOWNCAST (ResidualQuantizer)
+ DOWNCAST (ProductLocalSearchQuantizer)
+ DOWNCAST (ProductResidualQuantizer)
+ {
+ assert(false);
+ }
+}
+
+// just to downcast pointers that come from elsewhere (eg. direct
+// access to object fields)
+%inline %{
+faiss::Index * downcast_index (faiss::Index *index)
+{
+ return index;
+}
+faiss::VectorTransform * downcast_VectorTransform (faiss::VectorTransform *vt)
+{
+ return vt;
+}
+faiss::IndexBinary * downcast_IndexBinary (faiss::IndexBinary *index)
+{
+ return index;
+}
+faiss::InvertedLists * downcast_InvertedLists (faiss::InvertedLists *il)
+{
+ return il;
+}
+// backwards compatibility
+faiss::Quantizer * downcast_AdditiveQuantizer (faiss::AdditiveQuantizer *aq)
+{
+ return aq;
+}
+faiss::Quantizer * downcast_Quantizer (faiss::Quantizer *aq)
+{
+ return aq;
+}
+%}
+
+%include <faiss/index_io.h>
+%include <faiss/clone_index.h>
+%newobject index_factory;
+%newobject index_binary_factory;
+
+%include <faiss/AutoTune.h>
+%include <faiss/index_factory.h>
+%include <faiss/MatrixStats.h>
+
+
+#ifdef GPU_WRAPPER
+
+#ifdef FAISS_ENABLE_ROCM
+%include <faiss/gpu-rocm/GpuAutoTune.h>
+
+%newobject index_gpu_to_cpu;
+%newobject index_cpu_to_gpu;
+%newobject index_cpu_to_gpu_multiple;
+
+%include <faiss/gpu-rocm/GpuCloner.h>
+
+#else // FAISS_ENABLE_ROCM
+%include <faiss/gpu/GpuAutoTune.h>
+
+%newobject index_gpu_to_cpu;
+%newobject index_cpu_to_gpu;
+%newobject index_cpu_to_gpu_multiple;
+
+%include <faiss/gpu/GpuCloner.h>
+
+#endif // FAISS_ENABLE_ROCM
+#endif
+
+
+
+/*******************************************************************
+ * Support I/O to arbitrary functions
+ *******************************************************************/
+
+
+#ifdef SWIGPYTHON
+%include <faiss/python/python_callbacks.h>
+
+
+%{
+#include <faiss/python/python_callbacks.h>
+%}
+
+#endif
+
+
+/*******************************************************************
+ * How should the template objects appear in the scripting language?
+ *******************************************************************/
+
+// answer: the same as the C++ typedefs, but we still have to redefine them
+
+%template() faiss::CMin<float, int64_t>;
+%template() faiss::CMin<int, int64_t>;
+%template() faiss::CMax<float, int64_t>;
+%template() faiss::CMax<int, int64_t>;
+
+%template(float_minheap_array_t) faiss::HeapArray<faiss::CMin<float, int64_t> >;
+%template(int_minheap_array_t) faiss::HeapArray<faiss::CMin<int, int64_t> >;
+%template(float_maxheap_array_t) faiss::HeapArray<faiss::CMax<float, int64_t> >;
+%template(int_maxheap_array_t) faiss::HeapArray<faiss::CMax<int, int64_t> >;
+
+%template(CMin_float_partition_fuzzy)
+ faiss::partition_fuzzy<faiss::CMin<float, int64_t> >;
+%template(CMax_float_partition_fuzzy)
+ faiss::partition_fuzzy<faiss::CMax<float, int64_t> >;
+
+%template(AlignedTableUint8) faiss::AlignedTable<uint8_t>;
+%template(AlignedTableUint16) faiss::AlignedTable<uint16_t>;
+%template(AlignedTableFloat32) faiss::AlignedTable<float>;
+
+%template(MaybeOwnedVectorUInt8) faiss::MaybeOwnedVector<uint8_t>;
+%template(MaybeOwnedVectorInt32) faiss::MaybeOwnedVector<int32_t>;
+%template(MaybeOwnedVectorFloat32) faiss::MaybeOwnedVector<float>;
+
+
+// SWIG seems to have some trouble resolving function template types here, so
+// declare explicitly
+
+%define INSTANTIATE_uint16_partition_fuzzy(C, id_t)
+
+%inline %{
+
+uint16_t C ## _uint16_partition_fuzzy(
+ uint16_t *vals, id_t *ids, size_t n,
+ size_t q_min, size_t q_max, size_t * q_out)
+{
+ return faiss::partition_fuzzy<faiss::C<unsigned short, id_t> >(
+ vals, ids, n, q_min, q_max, q_out);
+}
+
+%}
+
+%enddef
+
+INSTANTIATE_uint16_partition_fuzzy(CMin, int64_t)
+INSTANTIATE_uint16_partition_fuzzy(CMax, int64_t)
+INSTANTIATE_uint16_partition_fuzzy(CMin, int)
+INSTANTIATE_uint16_partition_fuzzy(CMax, int)
+
+// Same for merge_knn_results
+
+// same define as explicit instanciation in Heap.cpp
+%define INSTANTIATE_merge_knn_results(C, distance_t)
+
+%inline %{
+void merge_knn_results_ ## C(
+ size_t n, size_t k, int nshard,
+ const distance_t *all_distances, const faiss::idx_t *all_labels,
+ distance_t *distances, faiss::idx_t *labels)
+{
+ faiss::merge_knn_results<faiss::idx_t, faiss::C<distance_t, int>>(
+ n, k, nshard, all_distances, all_labels, distances, labels);
+}
+%}
+
+%enddef
+
+INSTANTIATE_merge_knn_results(CMin, float);
+INSTANTIATE_merge_knn_results(CMax, float);
+INSTANTIATE_merge_knn_results(CMin, int32_t);
+INSTANTIATE_merge_knn_results(CMax, int32_t);
+
+
+
+%inline %{
+
+/*******************************************************************
+ * numpy misses a hash table implementation, hence this class. It
+ * represents not found values as -1 like in the Index implementation
+ *******************************************************************/
+
+
+struct MapLong2Long {
+ std::unordered_map<int64_t, int64_t> map;
+
+ void add(size_t n, const int64_t *keys, const int64_t *vals) {
+ map.reserve(map.size() + n);
+ for (size_t i = 0; i < n; i++) {
+ map[keys[i]] = vals[i];
+ }
+ }
+
+ int64_t search(int64_t key) const {
+ auto ptr = map.find(key);
+ if (ptr == map.end()) {
+ return -1;
+ } else {
+ return ptr->second;
+ }
+ }
+
+ void search_multiple(size_t n, int64_t *keys, int64_t * vals) {
+ for (size_t i = 0; i < n; i++) {
+ vals[i] = search(keys[i]);
+ }
+ }
+};
+
+%}
+
+
+/*******************************************************************
+ * Expose a few basic functions
+ *******************************************************************/
+
+
+void omp_set_num_threads (int num_threads);
+int omp_get_max_threads ();
+void *memcpy(void *dest, const void *src, size_t n);
+
+
+
+
+/*******************************************************************
+ * Python-specific: do not release GIL any more, as functions below
+ * use the Python/C API
+ *******************************************************************/
+
+#ifdef SWIGPYTHON
+%exception;
+#endif
+
+
+
+/*******************************************************************
+ * Python specific: numpy array <-> C++ pointer interface
+ *******************************************************************/
+
+#ifdef SWIGPYTHON
+
+// transfer SWIG flag to C++
+#ifdef SWIGWORDSIZE64
+%{
+#define SWIGWORDSIZE64_CPP
+%}
+#endif
+
+%{
+PyObject *swig_ptr (PyObject *a)
+{
+
+ if (PyBytes_Check(a)) {
+ return SWIG_NewPointerObj(PyBytes_AsString(a), SWIGTYPE_p_char, 0);
+ }
+ if (PyByteArray_Check(a)) {
+ return SWIG_NewPointerObj(PyByteArray_AsString(a), SWIGTYPE_p_char, 0);
+ }
+ if(!PyArray_Check(a)) {
+ PyErr_SetString(PyExc_ValueError, "input not a numpy array");
+ return NULL;
+ }
+ PyArrayObject *ao = (PyArrayObject *)a;
+
+ if(!PyArray_ISCONTIGUOUS(ao)) {
+ PyErr_SetString(PyExc_ValueError, "array is not C-contiguous");
+ return NULL;
+ }
+ void * data = PyArray_DATA(ao);
+ if(PyArray_TYPE(ao) == NPY_FLOAT32) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_float, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_FLOAT64) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_double, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_FLOAT16) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_unsigned_short, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_UINT8) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_unsigned_char, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_INT8) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_signed_char, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_UINT16) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_unsigned_short, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_INT16) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_short, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_UINT32) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_unsigned_int, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_INT32) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_int, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_BOOL) {
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_bool, 0);
+ }
+ if(PyArray_TYPE(ao) == NPY_UINT64) {
+ // Convert npy64 either long or long long and it depends on how compiler define int64_t.
+ // In the 64bit machine, typically the int64_t should be long but it is not hold for Apple osx.
+ // In this case, we want to convert npy64 to long_Long in osx
+#ifdef SWIGWORDSIZE64_CPP
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_unsigned_long, 0);
+#else
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_unsigned_long_long, 0);
+#endif
+ }
+ if(PyArray_TYPE(ao) == NPY_INT64) {
+#ifdef SWIGWORDSIZE64_CPP
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_long, 0);
+#else
+ return SWIG_NewPointerObj(data, SWIGTYPE_p_long_long, 0);
+#endif
+ }
+ PyErr_SetString(PyExc_ValueError, "did not recognize array type");
+ return NULL;
+}
+%}
+
+%inline %{
+
+struct PythonInterruptCallback: faiss::InterruptCallback {
+
+ bool want_interrupt () override {
+ int err;
+ {
+ PyGILState_STATE gstate;
+ gstate = PyGILState_Ensure();
+ err = PyErr_CheckSignals();
+ PyGILState_Release(gstate);
+ }
+ return err == -1;
+ }
+
+ static void reset() {
+ faiss::InterruptCallback::instance.reset(new PythonInterruptCallback());
+ }
+};
+
+%}
+
+%init %{
+ /* needed, else crash at runtime */
+ import_array();
+
+ PythonInterruptCallback::reset();
+%}
+
+// return a pointer usable as input for functions that expect pointers
+PyObject *swig_ptr (PyObject *a);
+
+%define REV_SWIG_PTR(ctype, numpytype)
+
+%{
+PyObject * rev_swig_ptr(ctype *src, npy_intp size) {
+ return PyArray_SimpleNewFromData(1, &size, numpytype, src);
+}
+%}
+
+PyObject * rev_swig_ptr(ctype *src, size_t size);
+
+%enddef
+
+REV_SWIG_PTR(float, NPY_FLOAT32);
+REV_SWIG_PTR(double, NPY_FLOAT64);
+REV_SWIG_PTR(uint8_t, NPY_UINT8);
+REV_SWIG_PTR(int8_t, NPY_INT8);
+REV_SWIG_PTR(unsigned short, NPY_UINT16);
+REV_SWIG_PTR(short, NPY_INT16);
+REV_SWIG_PTR(int, NPY_INT32);
+REV_SWIG_PTR(unsigned int, NPY_UINT32);
+REV_SWIG_PTR(int64_t, NPY_INT64);
+REV_SWIG_PTR(uint64_t, NPY_UINT64);
+
+#endif
+
+
+
+/*******************************************************************
+ * For Faiss/Pytorch interop via pointers encoded as longs
+ *******************************************************************/
+
+%inline %{
+uint8_t * cast_integer_to_uint8_ptr (int64_t x) {
+ return (uint8_t*)x;
+}
+
+float * cast_integer_to_float_ptr (int64_t x) {
+ return (float*)x;
+}
+
+faiss::idx_t* cast_integer_to_idx_t_ptr (int64_t x) {
+ return (faiss::idx_t*)x;
+}
+
+int * cast_integer_to_int_ptr (int64_t x) {
+ return (int*)x;
+}
+
+void * cast_integer_to_void_ptr (int64_t x) {
+ return (void*)x;
+}
+%}
+
+%inline %{
+
+// the SWIG version is a 6-digit hex string, eg. version 3.2.1 is encoded as
+// 0x030201
+uint64_t swig_version() {
+ return SWIG_VERSION;
+}
+
+%}
+
+// End of file...
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/AlignedTable.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/AlignedTable.h
new file mode 100644
index 0000000..216dae0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/AlignedTable.h
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cassert>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+
+#include <algorithm>
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+template <int A = 32>
+inline bool is_aligned_pointer(const void* x) {
+ size_t xi = (size_t)x;
+ return xi % A == 0;
+}
+
+// class that manages suitably aligned arrays for SIMD
+// T should be a POV type. The default alignment is 32 for AVX
+template <class T, int A = 32>
+struct AlignedTableTightAlloc {
+ T* ptr;
+ size_t numel;
+
+ AlignedTableTightAlloc() : ptr(nullptr), numel(0) {}
+
+ explicit AlignedTableTightAlloc(size_t n) : ptr(nullptr), numel(0) {
+ resize(n);
+ }
+
+ size_t itemsize() const {
+ return sizeof(T);
+ }
+
+ void resize(size_t n) {
+ if (numel == n) {
+ return;
+ }
+ T* new_ptr;
+ if (n > 0) {
+ int ret = posix_memalign((void**)&new_ptr, A, n * sizeof(T));
+ if (ret != 0) {
+ throw std::bad_alloc();
+ }
+ if (numel > 0) {
+ memcpy(new_ptr, ptr, sizeof(T) * std::min(numel, n));
+ }
+ } else {
+ new_ptr = nullptr;
+ }
+ numel = n;
+ posix_memalign_free(ptr);
+ ptr = new_ptr;
+ }
+
+ void clear() {
+ if (numel > 0) {
+ memset(ptr, 0, nbytes());
+ }
+ }
+ size_t size() const {
+ return numel;
+ }
+ size_t nbytes() const {
+ return numel * sizeof(T);
+ }
+
+ T* get() {
+ return ptr;
+ }
+ const T* get() const {
+ return ptr;
+ }
+ T* data() {
+ return ptr;
+ }
+ const T* data() const {
+ return ptr;
+ }
+ T& operator[](size_t i) {
+ return ptr[i];
+ }
+ T operator[](size_t i) const {
+ return ptr[i];
+ }
+
+ ~AlignedTableTightAlloc() {
+ posix_memalign_free(ptr);
+ }
+
+ AlignedTableTightAlloc<T, A>& operator=(
+ const AlignedTableTightAlloc<T, A>& other) {
+ resize(other.numel);
+ if (numel > 0) {
+ memcpy(ptr, other.ptr, sizeof(T) * numel);
+ }
+ return *this;
+ }
+
+ AlignedTableTightAlloc(const AlignedTableTightAlloc<T, A>& other)
+ : ptr(nullptr), numel(0) {
+ *this = other;
+ }
+};
+
+// same as AlignedTableTightAlloc, but with geometric re-allocation
+template <class T, int A = 32>
+struct AlignedTable {
+ AlignedTableTightAlloc<T, A> tab;
+ size_t numel = 0;
+
+ static size_t round_capacity(size_t n) {
+ if (n == 0) {
+ return 0;
+ }
+ if (n < 8 * A) {
+ return 8 * A;
+ }
+ size_t capacity = 8 * A;
+ while (capacity < n) {
+ capacity *= 2;
+ }
+ return capacity;
+ }
+
+ AlignedTable() {}
+
+ explicit AlignedTable(size_t n) : tab(round_capacity(n)), numel(n) {}
+
+ size_t itemsize() const {
+ return sizeof(T);
+ }
+
+ void resize(size_t n) {
+ tab.resize(round_capacity(n));
+ numel = n;
+ }
+
+ void clear() {
+ tab.clear();
+ }
+ size_t size() const {
+ return numel;
+ }
+ size_t nbytes() const {
+ return numel * sizeof(T);
+ }
+
+ T* get() {
+ return tab.get();
+ }
+ const T* get() const {
+ return tab.get();
+ }
+ T* data() {
+ return tab.get();
+ }
+ const T* data() const {
+ return tab.get();
+ }
+ T& operator[](size_t i) {
+ return tab.ptr[i];
+ }
+ T operator[](size_t i) const {
+ return tab.ptr[i];
+ }
+
+ // assign and copy constructor should work as expected
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/Heap.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/Heap.cpp
new file mode 100644
index 0000000..e68c3b8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/Heap.cpp
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/* Function for soft heap */
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+template <typename C>
+void HeapArray<C>::heapify() {
+#pragma omp parallel for
+ for (int64_t j = 0; j < nh; j++)
+ heap_heapify<C>(k, val + j * k, ids + j * k);
+}
+
+template <typename C>
+void HeapArray<C>::reorder() {
+#pragma omp parallel for
+ for (int64_t j = 0; j < nh; j++)
+ heap_reorder<C>(k, val + j * k, ids + j * k);
+}
+
+template <typename C>
+void HeapArray<C>::addn(size_t nj, const T* vin, TI j0, size_t i0, int64_t ni) {
+ if (ni == -1)
+ ni = nh;
+ assert(i0 >= 0 && i0 + ni <= nh);
+#pragma omp parallel for if (ni * nj > 100000)
+ for (int64_t i = i0; i < i0 + ni; i++) {
+ T* __restrict simi = get_val(i);
+ TI* __restrict idxi = get_ids(i);
+ const T* ip_line = vin + (i - i0) * nj;
+
+ for (size_t j = 0; j < nj; j++) {
+ T ip = ip_line[j];
+ if (C::cmp(simi[0], ip)) {
+ heap_replace_top<C>(k, simi, idxi, ip, j + j0);
+ }
+ }
+ }
+}
+
+template <typename C>
+void HeapArray<C>::addn_with_ids(
+ size_t nj,
+ const T* vin,
+ const TI* id_in,
+ int64_t id_stride,
+ size_t i0,
+ int64_t ni) {
+ if (id_in == nullptr) {
+ addn(nj, vin, 0, i0, ni);
+ return;
+ }
+ if (ni == -1)
+ ni = nh;
+ assert(i0 >= 0 && i0 + ni <= nh);
+#pragma omp parallel for if (ni * nj > 100000)
+ for (int64_t i = i0; i < i0 + ni; i++) {
+ T* __restrict simi = get_val(i);
+ TI* __restrict idxi = get_ids(i);
+ const T* ip_line = vin + (i - i0) * nj;
+ const TI* id_line = id_in + (i - i0) * id_stride;
+
+ for (size_t j = 0; j < nj; j++) {
+ T ip = ip_line[j];
+ if (C::cmp(simi[0], ip)) {
+ heap_replace_top<C>(k, simi, idxi, ip, id_line[j]);
+ }
+ }
+ }
+}
+
+template <typename C>
+void HeapArray<C>::addn_query_subset_with_ids(
+ size_t nsubset,
+ const TI* subset,
+ size_t nj,
+ const T* vin,
+ const TI* id_in,
+ int64_t id_stride) {
+ FAISS_THROW_IF_NOT_MSG(id_in, "anonymous ids not supported");
+ if (id_stride < 0) {
+ id_stride = nj;
+ }
+#pragma omp parallel for if (nsubset * nj > 100000)
+ for (int64_t si = 0; si < nsubset; si++) {
+ TI i = subset[si];
+ T* __restrict simi = get_val(i);
+ TI* __restrict idxi = get_ids(i);
+ const T* ip_line = vin + si * nj;
+ const TI* id_line = id_in + si * id_stride;
+
+ for (size_t j = 0; j < nj; j++) {
+ T ip = ip_line[j];
+ if (C::cmp(simi[0], ip)) {
+ heap_replace_top<C>(k, simi, idxi, ip, id_line[j]);
+ }
+ }
+ }
+}
+
+template <typename C>
+void HeapArray<C>::per_line_extrema(T* out_val, TI* out_ids) const {
+#pragma omp parallel for if (nh * k > 100000)
+ for (int64_t j = 0; j < nh; j++) {
+ int64_t imin = -1;
+ typename C::T xval = C::Crev::neutral();
+ const typename C::T* x_ = val + j * k;
+ for (size_t i = 0; i < k; i++)
+ if (C::cmp(x_[i], xval)) {
+ xval = x_[i];
+ imin = i;
+ }
+ if (out_val)
+ out_val[j] = xval;
+
+ if (out_ids) {
+ if (ids && imin != -1)
+ out_ids[j] = ids[j * k + imin];
+ else
+ out_ids[j] = imin;
+ }
+ }
+}
+
+// explicit instanciations
+
+template struct HeapArray<CMin<float, int64_t>>;
+template struct HeapArray<CMax<float, int64_t>>;
+template struct HeapArray<CMin<float, int32_t>>;
+template struct HeapArray<CMax<float, int32_t>>;
+template struct HeapArray<CMin<int, int64_t>>;
+template struct HeapArray<CMax<int, int64_t>>;
+
+/**********************************************************
+ * merge knn search results
+ **********************************************************/
+
+/** Merge result tables from several shards. The per-shard results are assumed
+ * to be sorted. Note that the C comparator is reversed w.r.t. the usual top-k
+ * element heap because we want the best (ie. lowest for L2) result to be on
+ * top, not the worst.
+ *
+ * @param all_distances size (nshard, n, k)
+ * @param all_labels size (nshard, n, k)
+ * @param distances output distances, size (n, k)
+ * @param labels output labels, size (n, k)
+ */
+template <class idx_t, class C>
+void merge_knn_results(
+ size_t n,
+ size_t k,
+ typename C::TI nshard,
+ const typename C::T* all_distances,
+ const idx_t* all_labels,
+ typename C::T* distances,
+ idx_t* labels) {
+ using distance_t = typename C::T;
+ if (k == 0) {
+ return;
+ }
+ long stride = n * k;
+#pragma omp parallel if (n * nshard * k > 100000)
+ {
+ std::vector<int> buf(2 * nshard);
+ // index in each shard's result list
+ int* pointer = buf.data();
+ // (shard_ids, heap_vals): heap that indexes
+ // shard -> current distance for this shard
+ int* shard_ids = pointer + nshard;
+ std::vector<distance_t> buf2(nshard);
+ distance_t* heap_vals = buf2.data();
+#pragma omp for
+ for (long i = 0; i < n; i++) {
+ // the heap maps values to the shard where they are
+ // produced.
+ const distance_t* D_in = all_distances + i * k;
+ const idx_t* I_in = all_labels + i * k;
+ int heap_size = 0;
+
+ // push the first element of each shard (if not -1)
+ for (long s = 0; s < nshard; s++) {
+ pointer[s] = 0;
+ if (I_in[stride * s] >= 0) {
+ heap_push<C>(
+ ++heap_size,
+ heap_vals,
+ shard_ids,
+ D_in[stride * s],
+ s);
+ }
+ }
+
+ distance_t* D = distances + i * k;
+ idx_t* I = labels + i * k;
+
+ int j;
+ for (j = 0; j < k && heap_size > 0; j++) {
+ // pop element from best shard
+ int s = shard_ids[0]; // top of heap
+ int& p = pointer[s];
+ D[j] = heap_vals[0];
+ I[j] = I_in[stride * s + p];
+
+ // pop from shard, advance pointer for this shard
+ heap_pop<C>(heap_size--, heap_vals, shard_ids);
+ p++;
+ if (p < k && I_in[stride * s + p] >= 0) {
+ heap_push<C>(
+ ++heap_size,
+ heap_vals,
+ shard_ids,
+ D_in[stride * s + p],
+ s);
+ }
+ }
+ for (; j < k; j++) {
+ I[j] = -1;
+ D[j] = C::Crev::neutral();
+ }
+ }
+ }
+}
+
+// explicit instanciations
+#define INSTANTIATE(C, distance_t) \
+ template void merge_knn_results<int64_t, C<distance_t, int>>( \
+ size_t, \
+ size_t, \
+ int, \
+ const distance_t*, \
+ const int64_t*, \
+ distance_t*, \
+ int64_t*);
+
+INSTANTIATE(CMin, float);
+INSTANTIATE(CMax, float);
+INSTANTIATE(CMin, int32_t);
+INSTANTIATE(CMax, int32_t);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/Heap.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/Heap.h
new file mode 100644
index 0000000..4653751
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/Heap.h
@@ -0,0 +1,636 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/*
+ * C++ support for heaps. The set of functions is tailored for efficient
+ * similarity search.
+ *
+ * There is no specific object for a heap, and the functions that operate on a
+ * single heap are inlined, because heaps are often small. More complex
+ * functions are implemented in Heaps.cpp
+ *
+ * All heap functions rely on a C template class that define the type of the
+ * keys and values and their ordering (increasing with CMax and decreasing with
+ * Cmin). The C types are defined in ordered_key_value.h
+ */
+
+#ifndef FAISS_Heap_h
+#define FAISS_Heap_h
+
+#include <climits>
+#include <cmath>
+#include <cstring>
+
+#include <stdint.h>
+#include <cassert>
+#include <cstdio>
+
+#include <limits>
+#include <utility>
+
+#include <faiss/utils/ordered_key_value.h>
+
+namespace faiss {
+
+/*******************************************************************
+ * Basic heap ops: push and pop
+ *******************************************************************/
+
+/** Pops the top element from the heap defined by bh_val[0..k-1] and
+ * bh_ids[0..k-1]. on output the element at k-1 is undefined.
+ */
+template <class C>
+inline void heap_pop(size_t k, typename C::T* bh_val, typename C::TI* bh_ids) {
+ bh_val--; /* Use 1-based indexing for easier node->child translation */
+ bh_ids--;
+ typename C::T val = bh_val[k];
+ typename C::TI id = bh_ids[k];
+ size_t i = 1, i1, i2;
+ while (1) {
+ i1 = i << 1;
+ i2 = i1 + 1;
+ if (i1 > k)
+ break;
+ if ((i2 == k + 1) ||
+ C::cmp2(bh_val[i1], bh_val[i2], bh_ids[i1], bh_ids[i2])) {
+ if (C::cmp2(val, bh_val[i1], id, bh_ids[i1])) {
+ break;
+ }
+ bh_val[i] = bh_val[i1];
+ bh_ids[i] = bh_ids[i1];
+ i = i1;
+ } else {
+ if (C::cmp2(val, bh_val[i2], id, bh_ids[i2])) {
+ break;
+ }
+ bh_val[i] = bh_val[i2];
+ bh_ids[i] = bh_ids[i2];
+ i = i2;
+ }
+ }
+ bh_val[i] = bh_val[k];
+ bh_ids[i] = bh_ids[k];
+}
+
+/** Pushes the element (val, ids) into the heap bh_val[0..k-2] and
+ * bh_ids[0..k-2]. on output the element at k-1 is defined.
+ */
+template <class C>
+inline void heap_push(
+ size_t k,
+ typename C::T* bh_val,
+ typename C::TI* bh_ids,
+ typename C::T val,
+ typename C::TI id) {
+ bh_val--; /* Use 1-based indexing for easier node->child translation */
+ bh_ids--;
+ size_t i = k, i_father;
+ while (i > 1) {
+ i_father = i >> 1;
+ if (!C::cmp2(val, bh_val[i_father], id, bh_ids[i_father])) {
+ /* the heap structure is ok */
+ break;
+ }
+ bh_val[i] = bh_val[i_father];
+ bh_ids[i] = bh_ids[i_father];
+ i = i_father;
+ }
+ bh_val[i] = val;
+ bh_ids[i] = id;
+}
+
+/**
+ * Replaces the top element from the heap defined by bh_val[0..k-1] and
+ * bh_ids[0..k-1], and for identical bh_val[] values also sorts by bh_ids[]
+ * values.
+ */
+template <class C>
+inline void heap_replace_top(
+ size_t k,
+ typename C::T* bh_val,
+ typename C::TI* bh_ids,
+ typename C::T val,
+ typename C::TI id) {
+ bh_val--; /* Use 1-based indexing for easier node->child translation */
+ bh_ids--;
+ size_t i = 1, i1, i2;
+ while (1) {
+ i1 = i << 1;
+ i2 = i1 + 1;
+ if (i1 > k) {
+ break;
+ }
+
+ // Note that C::cmp2() is a bool function answering
+ // `(a1 > b1) || ((a1 == b1) && (a2 > b2))` for max
+ // heap and same with the `<` sign for min heap.
+ if ((i2 == k + 1) ||
+ C::cmp2(bh_val[i1], bh_val[i2], bh_ids[i1], bh_ids[i2])) {
+ if (C::cmp2(val, bh_val[i1], id, bh_ids[i1])) {
+ break;
+ }
+ bh_val[i] = bh_val[i1];
+ bh_ids[i] = bh_ids[i1];
+ i = i1;
+ } else {
+ if (C::cmp2(val, bh_val[i2], id, bh_ids[i2])) {
+ break;
+ }
+ bh_val[i] = bh_val[i2];
+ bh_ids[i] = bh_ids[i2];
+ i = i2;
+ }
+ }
+ bh_val[i] = val;
+ bh_ids[i] = id;
+}
+
+/* Partial instanciation for heaps with TI = int64_t */
+
+template <typename T>
+inline void minheap_pop(size_t k, T* bh_val, int64_t* bh_ids) {
+ heap_pop<CMin<T, int64_t>>(k, bh_val, bh_ids);
+}
+
+template <typename T>
+inline void minheap_push(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ T val,
+ int64_t ids) {
+ heap_push<CMin<T, int64_t>>(k, bh_val, bh_ids, val, ids);
+}
+
+template <typename T>
+inline void minheap_replace_top(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ T val,
+ int64_t ids) {
+ heap_replace_top<CMin<T, int64_t>>(k, bh_val, bh_ids, val, ids);
+}
+
+template <typename T>
+inline void maxheap_pop(size_t k, T* bh_val, int64_t* bh_ids) {
+ heap_pop<CMax<T, int64_t>>(k, bh_val, bh_ids);
+}
+
+template <typename T>
+inline void maxheap_push(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ T val,
+ int64_t ids) {
+ heap_push<CMax<T, int64_t>>(k, bh_val, bh_ids, val, ids);
+}
+
+template <typename T>
+inline void maxheap_replace_top(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ T val,
+ int64_t ids) {
+ heap_replace_top<CMax<T, int64_t>>(k, bh_val, bh_ids, val, ids);
+}
+
+/*******************************************************************
+ * Basic heap<std:pair<>> ops: push and pop
+ *******************************************************************/
+
+// This section contains a heap implementation that works with
+// std::pair<Priority, Value> elements.
+
+/** Pops the top element from the heap defined by bh_val[0..k-1] and
+ * bh_ids[0..k-1]. on output the element at k-1 is undefined.
+ */
+template <class C>
+inline void heap_pop(size_t k, std::pair<typename C::T, typename C::TI>* bh) {
+ bh--; /* Use 1-based indexing for easier node->child translation */
+ typename C::T val = bh[k].first;
+ typename C::TI id = bh[k].second;
+ size_t i = 1, i1, i2;
+ while (1) {
+ i1 = i << 1;
+ i2 = i1 + 1;
+ if (i1 > k)
+ break;
+ if ((i2 == k + 1) ||
+ C::cmp2(bh[i1].first, bh[i2].first, bh[i1].second, bh[i2].second)) {
+ if (C::cmp2(val, bh[i1].first, id, bh[i1].second)) {
+ break;
+ }
+ bh[i] = bh[i1];
+ i = i1;
+ } else {
+ if (C::cmp2(val, bh[i2].first, id, bh[i2].second)) {
+ break;
+ }
+ bh[i] = bh[i2];
+ i = i2;
+ }
+ }
+ bh[i] = bh[k];
+}
+
+/** Pushes the element (val, ids) into the heap bh_val[0..k-2] and
+ * bh_ids[0..k-2]. on output the element at k-1 is defined.
+ */
+template <class C>
+inline void heap_push(
+ size_t k,
+ std::pair<typename C::T, typename C::TI>* bh,
+ typename C::T val,
+ typename C::TI id) {
+ bh--; /* Use 1-based indexing for easier node->child translation */
+ size_t i = k, i_father;
+ while (i > 1) {
+ i_father = i >> 1;
+ auto bh_v = bh[i_father];
+ if (!C::cmp2(val, bh_v.first, id, bh_v.second)) {
+ /* the heap structure is ok */
+ break;
+ }
+ bh[i] = bh_v;
+ i = i_father;
+ }
+ bh[i] = std::make_pair(val, id);
+}
+
+/**
+ * Replaces the top element from the heap defined by bh_val[0..k-1] and
+ * bh_ids[0..k-1], and for identical bh_val[] values also sorts by bh_ids[]
+ * values.
+ */
+template <class C>
+inline void heap_replace_top(
+ size_t k,
+ std::pair<typename C::T, typename C::TI>* bh,
+ typename C::T val,
+ typename C::TI id) {
+ bh--; /* Use 1-based indexing for easier node->child translation */
+ size_t i = 1, i1, i2;
+ while (1) {
+ i1 = i << 1;
+ i2 = i1 + 1;
+ if (i1 > k) {
+ break;
+ }
+
+ // Note that C::cmp2() is a bool function answering
+ // `(a1 > b1) || ((a1 == b1) && (a2 > b2))` for max
+ // heap and same with the `<` sign for min heap.
+ if ((i2 == k + 1) ||
+ C::cmp2(bh[i1].first, bh[i2].first, bh[i1].second, bh[i2].second)) {
+ if (C::cmp2(val, bh[i1].first, id, bh[i1].second)) {
+ break;
+ }
+ bh[i] = bh[i1];
+ i = i1;
+ } else {
+ if (C::cmp2(val, bh[i2].first, id, bh[i2].second)) {
+ break;
+ }
+ bh[i] = bh[i2];
+ i = i2;
+ }
+ }
+ bh[i] = std::make_pair(val, id);
+}
+
+/*******************************************************************
+ * Heap initialization
+ *******************************************************************/
+
+/* Initialization phase for the heap (with unconditionnal pushes).
+ * Store k0 elements in a heap containing up to k values. Note that
+ * (bh_val, bh_ids) can be the same as (x, ids) */
+template <class C>
+inline void heap_heapify(
+ size_t k,
+ typename C::T* bh_val,
+ typename C::TI* bh_ids,
+ const typename C::T* x = nullptr,
+ const typename C::TI* ids = nullptr,
+ size_t k0 = 0) {
+ if (k0 > 0)
+ assert(x);
+
+ if (ids) {
+ for (size_t i = 0; i < k0; i++)
+ heap_push<C>(i + 1, bh_val, bh_ids, x[i], ids[i]);
+ } else {
+ for (size_t i = 0; i < k0; i++)
+ heap_push<C>(i + 1, bh_val, bh_ids, x[i], i);
+ }
+
+ for (size_t i = k0; i < k; i++) {
+ bh_val[i] = C::neutral();
+ bh_ids[i] = -1;
+ }
+}
+
+template <typename T>
+inline void minheap_heapify(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ const T* x = nullptr,
+ const int64_t* ids = nullptr,
+ size_t k0 = 0) {
+ heap_heapify<CMin<T, int64_t>>(k, bh_val, bh_ids, x, ids, k0);
+}
+
+template <typename T>
+inline void maxheap_heapify(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ const T* x = nullptr,
+ const int64_t* ids = nullptr,
+ size_t k0 = 0) {
+ heap_heapify<CMax<T, int64_t>>(k, bh_val, bh_ids, x, ids, k0);
+}
+
+/*******************************************************************
+ * Add n elements to the heap
+ *******************************************************************/
+
+/* Add some elements to the heap */
+template <class C>
+inline void heap_addn(
+ size_t k,
+ typename C::T* bh_val,
+ typename C::TI* bh_ids,
+ const typename C::T* x,
+ const typename C::TI* ids,
+ size_t n) {
+ size_t i;
+ if (ids)
+ for (i = 0; i < n; i++) {
+ if (C::cmp(bh_val[0], x[i])) {
+ heap_replace_top<C>(k, bh_val, bh_ids, x[i], ids[i]);
+ }
+ }
+ else
+ for (i = 0; i < n; i++) {
+ if (C::cmp(bh_val[0], x[i])) {
+ heap_replace_top<C>(k, bh_val, bh_ids, x[i], i);
+ }
+ }
+}
+
+/* Partial instanciation for heaps with TI = int64_t */
+
+template <typename T>
+inline void minheap_addn(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ const T* x,
+ const int64_t* ids,
+ size_t n) {
+ heap_addn<CMin<T, int64_t>>(k, bh_val, bh_ids, x, ids, n);
+}
+
+template <typename T>
+inline void maxheap_addn(
+ size_t k,
+ T* bh_val,
+ int64_t* bh_ids,
+ const T* x,
+ const int64_t* ids,
+ size_t n) {
+ heap_addn<CMax<T, int64_t>>(k, bh_val, bh_ids, x, ids, n);
+}
+
+/*******************************************************************
+ * Heap finalization (reorder elements)
+ *******************************************************************/
+
+/* This function maps a binary heap into a sorted structure.
+ It returns the number */
+template <typename C>
+inline size_t heap_reorder(
+ size_t k,
+ typename C::T* bh_val,
+ typename C::TI* bh_ids) {
+ size_t i, ii;
+
+ for (i = 0, ii = 0; i < k; i++) {
+ /* top element should be put at the end of the list */
+ typename C::T val = bh_val[0];
+ typename C::TI id = bh_ids[0];
+
+ /* boundary case: we will over-ride this value if not a true element */
+ heap_pop<C>(k - i, bh_val, bh_ids);
+ bh_val[k - ii - 1] = val;
+ bh_ids[k - ii - 1] = id;
+ if (id != -1)
+ ii++;
+ }
+ /* Count the number of elements which are effectively returned */
+ size_t nel = ii;
+
+ memmove(bh_val, bh_val + k - ii, ii * sizeof(*bh_val));
+ memmove(bh_ids, bh_ids + k - ii, ii * sizeof(*bh_ids));
+
+ for (; ii < k; ii++) {
+ bh_val[ii] = C::neutral();
+ bh_ids[ii] = -1;
+ }
+ return nel;
+}
+
+template <typename T>
+inline size_t minheap_reorder(size_t k, T* bh_val, int64_t* bh_ids) {
+ return heap_reorder<CMin<T, int64_t>>(k, bh_val, bh_ids);
+}
+
+template <typename T>
+inline size_t maxheap_reorder(size_t k, T* bh_val, int64_t* bh_ids) {
+ return heap_reorder<CMax<T, int64_t>>(k, bh_val, bh_ids);
+}
+
+/*******************************************************************
+ * Operations on heap arrays
+ *******************************************************************/
+
+/** a template structure for a set of [min|max]-heaps it is tailored
+ * so that the actual data of the heaps can just live in compact
+ * arrays.
+ */
+template <typename C>
+struct HeapArray {
+ typedef typename C::TI TI;
+ typedef typename C::T T;
+
+ size_t nh; ///< number of heaps
+ size_t k; ///< allocated size per heap
+ TI* ids; ///< identifiers (size nh * k)
+ T* val; ///< values (distances or similarities), size nh * k
+
+ /// Return the list of values for a heap
+ T* get_val(size_t key) {
+ return val + key * k;
+ }
+
+ /// Correspponding identifiers
+ TI* get_ids(size_t key) {
+ return ids + key * k;
+ }
+
+ /// prepare all the heaps before adding
+ void heapify();
+
+ /** add nj elements to heaps i0:i0+ni, with sequential ids
+ *
+ * @param nj nb of elements to add to each heap
+ * @param vin elements to add, size ni * nj
+ * @param j0 add this to the ids that are added
+ * @param i0 first heap to update
+ * @param ni nb of elements to update (-1 = use nh)
+ */
+ void addn(
+ size_t nj,
+ const T* vin,
+ TI j0 = 0,
+ size_t i0 = 0,
+ int64_t ni = -1);
+
+ /** same as addn
+ *
+ * @param id_in ids of the elements to add, size ni * nj
+ * @param id_stride stride for id_in
+ */
+ void addn_with_ids(
+ size_t nj,
+ const T* vin,
+ const TI* id_in = nullptr,
+ int64_t id_stride = 0,
+ size_t i0 = 0,
+ int64_t ni = -1);
+
+ /** same as addn_with_ids, but for just a subset of queries
+ *
+ * @param nsubset number of query entries to update
+ * @param subset indexes of queries to update, in 0..nh-1, size nsubset
+ */
+ void addn_query_subset_with_ids(
+ size_t nsubset,
+ const TI* subset,
+ size_t nj,
+ const T* vin,
+ const TI* id_in = nullptr,
+ int64_t id_stride = 0);
+
+ /// reorder all the heaps
+ void reorder();
+
+ /** this is not really a heap function. It just finds the per-line
+ * extrema of each line of array D
+ * @param vals_out extreme value of each line (size nh, or NULL)
+ * @param idx_out index of extreme value (size nh or NULL)
+ */
+ void per_line_extrema(T* vals_out, TI* idx_out) const;
+};
+
+/* Define useful heaps */
+typedef HeapArray<CMin<float, int64_t>> float_minheap_array_t;
+typedef HeapArray<CMin<int, int64_t>> int_minheap_array_t;
+
+typedef HeapArray<CMax<float, int64_t>> float_maxheap_array_t;
+typedef HeapArray<CMax<int, int64_t>> int_maxheap_array_t;
+
+// The heap templates are instantiated explicitly in Heap.cpp
+
+/*********************************************************************
+ * Indirect heaps: instead of having
+ *
+ * node i = (bh_ids[i], bh_val[i]),
+ *
+ * in indirect heaps,
+ *
+ * node i = (bh_ids[i], bh_val[bh_ids[i]]),
+ *
+ *********************************************************************/
+
+template <class C>
+inline void indirect_heap_pop(
+ size_t k,
+ const typename C::T* bh_val,
+ typename C::TI* bh_ids) {
+ bh_ids--; /* Use 1-based indexing for easier node->child translation */
+ typename C::T val = bh_val[bh_ids[k]];
+ size_t i = 1;
+ while (1) {
+ size_t i1 = i << 1;
+ size_t i2 = i1 + 1;
+ if (i1 > k)
+ break;
+ typename C::TI id1 = bh_ids[i1], id2 = bh_ids[i2];
+ if (i2 == k + 1 || C::cmp(bh_val[id1], bh_val[id2])) {
+ if (C::cmp(val, bh_val[id1]))
+ break;
+ bh_ids[i] = id1;
+ i = i1;
+ } else {
+ if (C::cmp(val, bh_val[id2]))
+ break;
+ bh_ids[i] = id2;
+ i = i2;
+ }
+ }
+ bh_ids[i] = bh_ids[k];
+}
+
+template <class C>
+inline void indirect_heap_push(
+ size_t k,
+ const typename C::T* bh_val,
+ typename C::TI* bh_ids,
+ typename C::TI id) {
+ bh_ids--; /* Use 1-based indexing for easier node->child translation */
+ typename C::T val = bh_val[id];
+ size_t i = k;
+ while (i > 1) {
+ size_t i_father = i >> 1;
+ if (!C::cmp(val, bh_val[bh_ids[i_father]]))
+ break;
+ bh_ids[i] = bh_ids[i_father];
+ i = i_father;
+ }
+ bh_ids[i] = id;
+}
+
+/** Merge result tables from several shards. The per-shard results are assumed
+ * to be sorted. Note that the C comparator is reversed w.r.t. the usual top-k
+ * element heap because we want the best (ie. lowest for L2) result to be on
+ * top, not the worst. Also, it needs to hold an index of a shard id (ie.
+ * usually int32 is more than enough).
+ *
+ * @param all_distances size (nshard, n, k)
+ * @param all_labels size (nshard, n, k)
+ * @param distances output distances, size (n, k)
+ * @param labels output labels, size (n, k)
+ */
+template <class idx_t, class C>
+void merge_knn_results(
+ size_t n,
+ size_t k,
+ typename C::TI nshard,
+ const typename C::T* all_distances,
+ const idx_t* all_labels,
+ typename C::T* distances,
+ idx_t* labels);
+
+} // namespace faiss
+
+#endif /* FAISS_Heap_h */
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/NeuralNet.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/NeuralNet.cpp
new file mode 100644
index 0000000..90d06c1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/NeuralNet.cpp
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/utils/NeuralNet.h>
+
+#include <algorithm>
+#include <cstddef>
+#include <cstring>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+extern "C" {
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+namespace nn {
+
+/*************************************************************
+ * Tensor2D implementation
+ *************************************************************/
+
+template <typename T>
+Tensor2DTemplate<T>::Tensor2DTemplate(size_t n0, size_t n1, const T* data_in)
+ : shape{n0, n1}, v(n0 * n1) {
+ if (data_in) {
+ memcpy(data(), data_in, n0 * n1 * sizeof(T));
+ }
+}
+
+template <typename T>
+Tensor2DTemplate<T>& Tensor2DTemplate<T>::operator+=(
+ const Tensor2DTemplate<T>& other) {
+ FAISS_THROW_IF_NOT(shape[0] == other.shape[0]);
+ FAISS_THROW_IF_NOT(shape[1] == other.shape[1]);
+ for (size_t i = 0; i < numel(); i++) {
+ v[i] += other.v[i];
+ }
+ return *this;
+}
+
+template <typename T>
+Tensor2DTemplate<T> Tensor2DTemplate<T>::column(size_t j) const {
+ size_t n = shape[0], d = shape[1];
+ Tensor2DTemplate<T> out(n, 1);
+ for (size_t i = 0; i < n; i++) {
+ out.v[i] = v[i * d + j];
+ }
+ return out;
+}
+
+// explicit template instanciation
+template struct Tensor2DTemplate<float>;
+template struct Tensor2DTemplate<int32_t>;
+
+/*************************************************************
+ * Layers implementation
+ *************************************************************/
+
+Linear::Linear(size_t in_features, size_t out_features, bool bias)
+ : in_features(in_features),
+ out_features(out_features),
+ weight(in_features * out_features) {
+ if (bias) {
+ this->bias.resize(out_features);
+ }
+}
+
+Tensor2D Linear::operator()(const Tensor2D& x) const {
+ FAISS_THROW_IF_NOT(x.shape[1] == in_features);
+ size_t n = x.shape[0];
+ Tensor2D output(n, out_features);
+
+ float one = 1, zero = 0;
+ FINTEGER nbiti = out_features, ni = n, di = in_features;
+
+ sgemm_("Transposed",
+ "Not transposed",
+ &nbiti,
+ &ni,
+ &di,
+ &one,
+ weight.data(),
+ &di,
+ x.data(),
+ &di,
+ &zero,
+ output.data(),
+ &nbiti);
+
+ if (bias.size() > 0) {
+ FAISS_THROW_IF_NOT(bias.size() == out_features);
+ for (size_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < out_features; j++) {
+ output.v[i * out_features + j] += bias[j];
+ }
+ }
+ }
+
+ return output;
+}
+
+Embedding::Embedding(size_t num_embeddings, size_t embedding_dim)
+ : num_embeddings(num_embeddings), embedding_dim(embedding_dim) {
+ weight.resize(num_embeddings * embedding_dim);
+}
+
+Tensor2D Embedding::operator()(const Int32Tensor2D& code) const {
+ FAISS_THROW_IF_NOT(code.shape[1] == 1);
+ size_t n = code.shape[0];
+ Tensor2D output(n, embedding_dim);
+ for (size_t i = 0; i < n; ++i) {
+ size_t ci = code.v[i];
+ FAISS_THROW_IF_NOT(ci < num_embeddings);
+ memcpy(output.data() + i * embedding_dim,
+ weight.data() + ci * embedding_dim,
+ sizeof(float) * embedding_dim);
+ }
+ return output; // TODO figure out how std::move works
+}
+
+namespace {
+
+void inplace_relu(Tensor2D& x) {
+ for (size_t i = 0; i < x.numel(); i++) {
+ x.v[i] = std::max(0.0f, x.v[i]);
+ }
+}
+
+Tensor2D concatenate_rows(const Tensor2D& x, const Tensor2D& y) {
+ size_t n = x.shape[0], d1 = x.shape[1], d2 = y.shape[1];
+ FAISS_THROW_IF_NOT(n == y.shape[0]);
+ Tensor2D out(n, d1 + d2);
+ for (size_t i = 0; i < n; i++) {
+ memcpy(out.data() + i * (d1 + d2),
+ x.data() + i * d1,
+ sizeof(float) * d1);
+ memcpy(out.data() + i * (d1 + d2) + d1,
+ y.data() + i * d2,
+ sizeof(float) * d2);
+ }
+ return out;
+}
+
+} // anonymous namespace
+
+Tensor2D FFN::operator()(const Tensor2D& x_in) const {
+ Tensor2D x = linear1(x_in);
+ inplace_relu(x);
+ return linear2(x);
+}
+
+} // namespace nn
+
+/*************************************************************
+ * QINCoStep implementation
+ *************************************************************/
+
+using namespace nn;
+
+QINCoStep::QINCoStep(int d, int K, int L, int h)
+ : d(d), K(K), L(L), h(h), codebook(K, d), MLPconcat(2 * d, d) {
+ for (int i = 0; i < L; i++) {
+ residual_blocks.emplace_back(d, h);
+ }
+}
+
+nn::Tensor2D QINCoStep::decode(
+ const nn::Tensor2D& xhat,
+ const nn::Int32Tensor2D& codes) const {
+ size_t n = xhat.shape[0];
+ FAISS_THROW_IF_NOT(n == codes.shape[0]);
+ Tensor2D zqs = codebook(codes);
+ Tensor2D cc = concatenate_rows(zqs, xhat);
+ zqs += MLPconcat(cc);
+ for (int i = 0; i < L; i++) {
+ zqs += residual_blocks[i](zqs);
+ }
+ return zqs;
+}
+
+nn::Int32Tensor2D QINCoStep::encode(
+ const nn::Tensor2D& xhat,
+ const nn::Tensor2D& x,
+ nn::Tensor2D* residuals) const {
+ size_t n = xhat.shape[0];
+ FAISS_THROW_IF_NOT(
+ n == x.shape[0] && xhat.shape[1] == d && x.shape[1] == d);
+
+ // repeated codebook
+ Tensor2D zqs_r(n * K, d); // size n, K, d
+ Tensor2D cc(n * K, d * 2); // size n, K, d * 2
+
+ size_t local_d = this->d;
+
+ auto copy_row =
+ [local_d](Tensor2D& t, size_t i, size_t j, const float* data) {
+ assert(i <= t.shape[0] && j <= t.shape[1]);
+ memcpy(t.data() + i * t.shape[1] + j,
+ data,
+ sizeof(float) * local_d);
+ };
+
+ // manual broadcasting
+ for (size_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < K; j++) {
+ copy_row(zqs_r, i * K + j, 0, codebook.data() + j * d);
+ copy_row(cc, i * K + j, 0, codebook.data() + j * d);
+ copy_row(cc, i * K + j, d, xhat.data() + i * d);
+ }
+ }
+
+ zqs_r += MLPconcat(cc);
+
+ // residual blocks
+ for (int i = 0; i < L; i++) {
+ zqs_r += residual_blocks[i](zqs_r);
+ }
+
+ // add the xhat
+ for (size_t i = 0; i < n; i++) {
+ float* zqs_r_row = zqs_r.data() + i * K * d;
+ const float* xhat_row = xhat.data() + i * d;
+ for (size_t l = 0; l < K; l++) {
+ for (size_t j = 0; j < d; j++) {
+ zqs_r_row[j] += xhat_row[j];
+ }
+ zqs_r_row += d;
+ }
+ }
+
+ // perform assignment, finding the nearest
+ nn::Int32Tensor2D codes(n, 1);
+ float* res = nullptr;
+ if (residuals) {
+ FAISS_THROW_IF_NOT(
+ residuals->shape[0] == n && residuals->shape[1] == d);
+ res = residuals->data();
+ }
+
+ for (size_t i = 0; i < n; i++) {
+ const float* q = x.data() + i * d;
+ const float* db = zqs_r.data() + i * K * d;
+ float dis_min = HUGE_VALF;
+ int64_t idx = -1;
+ for (size_t j = 0; j < K; j++) {
+ float dis = fvec_L2sqr(q, db, d);
+ if (dis < dis_min) {
+ dis_min = dis;
+ idx = j;
+ }
+ db += d;
+ }
+ codes.v[i] = idx;
+ if (res) {
+ const float* xhat_row = xhat.data() + i * d;
+ const float* xhat_next_row = zqs_r.data() + (i * K + idx) * d;
+ for (size_t j = 0; j < d; j++) {
+ res[j] = xhat_next_row[j] - xhat_row[j];
+ }
+ res += d;
+ }
+ }
+ return codes;
+}
+
+/*************************************************************
+ * QINCo implementation
+ *************************************************************/
+
+QINCo::QINCo(int d, int K, int L, int M, int h)
+ : NeuralNetCodec(d, M), K(K), L(L), h(h), codebook0(K, d) {
+ for (int i = 1; i < M; i++) {
+ steps.emplace_back(d, K, L, h);
+ }
+}
+
+nn::Tensor2D QINCo::decode(const nn::Int32Tensor2D& codes) const {
+ FAISS_THROW_IF_NOT(codes.shape[1] == M);
+ Tensor2D xhat = codebook0(codes.column(0));
+ for (int i = 1; i < M; i++) {
+ xhat += steps[i - 1].decode(xhat, codes.column(i));
+ }
+ return xhat;
+}
+
+nn::Int32Tensor2D QINCo::encode(const nn::Tensor2D& x) const {
+ FAISS_THROW_IF_NOT(x.shape[1] == d);
+ size_t n = x.shape[0];
+ Int32Tensor2D codes(n, M);
+ Tensor2D xhat(n, d);
+ {
+ // assign to first codebook as a batch
+ std::vector<float> dis(n);
+ std::vector<int64_t> codes64(n);
+ knn_L2sqr(
+ x.data(),
+ codebook0.data(),
+ d,
+ n,
+ K,
+ 1,
+ dis.data(),
+ codes64.data());
+ for (size_t i = 0; i < n; i++) {
+ codes.v[i * M] = codes64[i];
+ memcpy(xhat.data() + i * d,
+ codebook0.data() + codes64[i] * d,
+ sizeof(float) * d);
+ }
+ }
+
+ Tensor2D toadd(n, d);
+ for (int i = 1; i < M; i++) {
+ Int32Tensor2D ci = steps[i - 1].encode(xhat, x, &toadd);
+ for (size_t j = 0; j < n; j++) {
+ codes.v[j * M + i] = ci.v[j];
+ }
+ xhat += toadd;
+ }
+ return codes;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/NeuralNet.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/NeuralNet.h
new file mode 100644
index 0000000..0d97b67
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/NeuralNet.h
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/** Implements a few neural net layers, mainly to support QINCo */
+
+#pragma once
+
+#include <cstdint>
+#include <cstdio>
+#include <vector>
+
+namespace faiss {
+
+// the names are based on the Pytorch names (more or less)
+namespace nn {
+
+// container for intermediate steps of the neural net
+template <typename T>
+struct Tensor2DTemplate {
+ size_t shape[2];
+ std::vector<T> v;
+
+ Tensor2DTemplate(size_t n0, size_t n1, const T* data = nullptr);
+
+ Tensor2DTemplate& operator+=(const Tensor2DTemplate&);
+
+ /// get column #j as a 1-column Tensor2D
+ Tensor2DTemplate column(size_t j) const;
+
+ size_t numel() const {
+ return shape[0] * shape[1];
+ }
+ T* data() {
+ return v.data();
+ }
+ const T* data() const {
+ return v.data();
+ }
+};
+
+using Tensor2D = Tensor2DTemplate<float>;
+using Int32Tensor2D = Tensor2DTemplate<int32_t>;
+
+/// minimal translation of nn.Linear
+struct Linear {
+ size_t in_features, out_features;
+ std::vector<float> weight;
+ std::vector<float> bias;
+
+ Linear(size_t in_features, size_t out_features, bool bias = true);
+
+ Tensor2D operator()(const Tensor2D& x) const;
+};
+
+/// minimal translation of nn.Embedding
+struct Embedding {
+ size_t num_embeddings, embedding_dim;
+ std::vector<float> weight;
+
+ Embedding(size_t num_embeddings, size_t embedding_dim);
+
+ Tensor2D operator()(const Int32Tensor2D&) const;
+
+ float* data() {
+ return weight.data();
+ }
+
+ const float* data() const {
+ return weight.data();
+ }
+};
+
+/// Feed forward layer that expands to a hidden dimension, applies a ReLU non
+/// linearity and maps back to the orignal dimension
+struct FFN {
+ Linear linear1, linear2;
+
+ FFN(int d, int h) : linear1(d, h, false), linear2(h, d, false) {}
+
+ Tensor2D operator()(const Tensor2D& x) const;
+};
+
+} // namespace nn
+
+// Translation of the QINCo implementation from
+// https://github.com/facebookresearch/Qinco/blob/main/model_qinco.py
+
+struct QINCoStep {
+ /// d: input dim, K: codebook size, L: # of residual blocks, h: hidden dim
+ int d, K, L, h;
+
+ QINCoStep(int d, int K, int L, int h);
+
+ nn::Embedding codebook;
+ nn::Linear MLPconcat;
+ std::vector<nn::FFN> residual_blocks;
+
+ nn::FFN& get_residual_block(int i) {
+ return residual_blocks[i];
+ }
+
+ /** encode a set of vectors x with intial estimate xhat. Optionally return
+ * the delta to be added to xhat to form the new xhat */
+ nn::Int32Tensor2D encode(
+ const nn::Tensor2D& xhat,
+ const nn::Tensor2D& x,
+ nn::Tensor2D* residuals = nullptr) const;
+
+ nn::Tensor2D decode(
+ const nn::Tensor2D& xhat,
+ const nn::Int32Tensor2D& codes) const;
+};
+
+struct NeuralNetCodec {
+ int d, M;
+
+ NeuralNetCodec(int d, int M) : d(d), M(M) {}
+
+ virtual nn::Tensor2D decode(const nn::Int32Tensor2D& codes) const = 0;
+ virtual nn::Int32Tensor2D encode(const nn::Tensor2D& x) const = 0;
+
+ virtual ~NeuralNetCodec() {}
+};
+
+struct QINCo : NeuralNetCodec {
+ int K, L, h;
+ nn::Embedding codebook0;
+ std::vector<QINCoStep> steps;
+
+ QINCo(int d, int K, int L, int M, int h);
+
+ QINCoStep& get_step(int i) {
+ return steps[i];
+ }
+
+ nn::Tensor2D decode(const nn::Int32Tensor2D& codes) const override;
+
+ nn::Int32Tensor2D encode(const nn::Tensor2D& x) const override;
+
+ virtual ~QINCo() {}
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/WorkerThread.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/WorkerThread.cpp
new file mode 100644
index 0000000..f734b52
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/WorkerThread.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/WorkerThread.h>
+#include <exception>
+
+namespace faiss {
+
+namespace {
+
+// Captures any exceptions thrown by the lambda and returns them via the promise
+void runCallback(std::function<void()>& fn, std::promise<bool>& promise) {
+ try {
+ fn();
+ promise.set_value(true);
+ } catch (...) {
+ promise.set_exception(std::current_exception());
+ }
+}
+
+} // namespace
+
+WorkerThread::WorkerThread() : wantStop_(false) {
+ startThread();
+
+ // Make sure that the thread has started before continuing
+ add([]() {}).get();
+}
+
+WorkerThread::~WorkerThread() {
+ stop();
+ waitForThreadExit();
+}
+
+void WorkerThread::startThread() {
+ thread_ = std::thread([this]() { threadMain(); });
+}
+
+void WorkerThread::stop() {
+ std::lock_guard<std::mutex> guard(mutex_);
+
+ wantStop_ = true;
+ monitor_.notify_one();
+}
+
+std::future<bool> WorkerThread::add(std::function<void()> f) {
+ std::lock_guard<std::mutex> guard(mutex_);
+
+ if (wantStop_) {
+ // The timer thread has been stopped, or we want to stop; we can't
+ // schedule anything else
+ std::promise<bool> p;
+ auto fut = p.get_future();
+
+ // did not execute
+ p.set_value(false);
+ return fut;
+ }
+
+ auto pr = std::promise<bool>();
+ auto fut = pr.get_future();
+
+ queue_.emplace_back(std::make_pair(std::move(f), std::move(pr)));
+
+ // Wake up our thread
+ monitor_.notify_one();
+ return fut;
+}
+
+void WorkerThread::threadMain() {
+ threadLoop();
+
+ // Call all pending tasks
+ FAISS_ASSERT(wantStop_);
+
+ // flush all pending operations
+ for (auto& f : queue_) {
+ runCallback(f.first, f.second);
+ }
+}
+
+void WorkerThread::threadLoop() {
+ while (true) {
+ std::pair<std::function<void()>, std::promise<bool>> data;
+
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+
+ while (!wantStop_ && queue_.empty()) {
+ monitor_.wait(lock);
+ }
+
+ if (wantStop_) {
+ return;
+ }
+
+ data = std::move(queue_.front());
+ queue_.pop_front();
+ }
+
+ runCallback(data.first, data.second);
+ }
+}
+
+void WorkerThread::waitForThreadExit() {
+ try {
+ thread_.join();
+ } catch (...) {
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/WorkerThread.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/WorkerThread.h
new file mode 100644
index 0000000..78d7505
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/WorkerThread.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <condition_variable>
+#include <deque>
+#include <functional>
+#include <future>
+#include <thread>
+
+namespace faiss {
+
+class WorkerThread {
+ public:
+ WorkerThread();
+
+ /// Stops and waits for the worker thread to exit, flushing all
+ /// pending lambdas
+ ~WorkerThread();
+
+ /// Request that the worker thread stop itself
+ void stop();
+
+ /// Blocking waits in the current thread for the worker thread to
+ /// stop
+ void waitForThreadExit();
+
+ /// Adds a lambda to run on the worker thread; returns a future that
+ /// can be used to block on its completion.
+ /// Future status is `true` if the lambda was run in the worker
+ /// thread; `false` if it was not run, because the worker thread is
+ /// exiting or has exited.
+ std::future<bool> add(std::function<void()> f);
+
+ private:
+ void startThread();
+ void threadMain();
+ void threadLoop();
+
+ /// Thread that all queued lambdas are run on
+ std::thread thread_;
+
+ /// Mutex for the queue and exit status
+ std::mutex mutex_;
+
+ /// Monitor for the exit status and the queue
+ std::condition_variable monitor_;
+
+ /// Whether or not we want the thread to exit
+ bool wantStop_;
+
+ /// Queue of pending lambdas to call
+ std::deque<std::pair<std::function<void()>, std::promise<bool>>> queue_;
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/approx_topk.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/approx_topk.h
new file mode 100644
index 0000000..234dce8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/approx_topk.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// This file contains an implementation of approximate top-k search
+// using heap. It was initially created for a beam search.
+//
+// The core idea is the following.
+// Say we need to find beam_size indices with the minimal distance
+// values. It is done via heap (priority_queue) using the following
+// pseudocode:
+//
+// def baseline():
+// distances = np.empty([beam_size * n], dtype=float)
+// indices = np.empty([beam_size * n], dtype=int)
+//
+// heap = Heap(max_heap_size=beam_size)
+//
+// for i in range(0, beam_size * n):
+// heap.push(distances[i], indices[i])
+//
+// Basically, this is what heap_addn() function from utils/Heap.h does.
+//
+// The following scheme can be used for approximate beam search.
+// Say, we need to find elements with min distance.
+// Basically, we split n elements of every beam into NBUCKETS buckets
+// and track the index with the minimal distance for every bucket.
+// This can be effectively SIMD-ed and significantly lowers the number
+// of operations, but yields approximate results for beam_size >= 2.
+//
+// def approximate_v1():
+// distances = np.empty([beam_size * n], dtype=float)
+// indices = np.empty([beam_size * n], dtype=int)
+//
+// heap = Heap(max_heap_size=beam_size)
+//
+// for beam in range(0, beam_size):
+// # The value of 32 is just an example.
+// # The value may be varied: the larger the value is,
+// # the slower and the more precise vs baseline beam search is
+// NBUCKETS = 32
+//
+// local_min_distances = [HUGE_VALF] * NBUCKETS
+// local_min_indices = [0] * NBUCKETS
+//
+// for i in range(0, n / NBUCKETS):
+// for j in range(0, NBUCKETS):
+// idx = beam * n + i * NBUCKETS + j
+// if distances[idx] < local_min_distances[j]:
+// local_min_distances[i] = distances[idx]
+// local_min_indices[i] = indices[idx]
+//
+// for j in range(0, NBUCKETS):
+// heap.push(local_min_distances[j], local_min_indices[j])
+//
+// The accuracy can be improved by tracking min-2 elements for every
+// bucket. Such a min-2 implementation with NBUCKETS buckets provides
+// better accuracy than top-1 implementation with 2 * NBUCKETS buckets.
+// Min-3 is also doable. One can use min-N approach, but I'm not sure
+// whether min-4 and above are practical, because of the lack of SIMD
+// registers (unless AVX-512 version is used).
+//
+// C++ template for top-N implementation is provided. The code
+// assumes that indices[idx] == idx. One can write a code that lifts
+// such an assumption easily.
+//
+// Currently, the code that tracks elements with min distances is implemented
+// (Max Heap). Min Heap option can be added easily.
+
+#pragma once
+
+#include <faiss/impl/platform_macros.h>
+
+// the list of available modes is in the following file
+#include <faiss/utils/approx_topk/mode.h>
+
+#ifdef __AVX2__
+#include <faiss/utils/approx_topk/avx2-inl.h>
+#else
+#include <faiss/utils/approx_topk/generic.h>
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/avx2-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/avx2-inl.h
new file mode 100644
index 0000000..4949982
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/avx2-inl.h
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <immintrin.h>
+
+#include <limits>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+template <typename C, uint32_t NBUCKETS, uint32_t N>
+struct HeapWithBuckets {
+ // this case was not implemented yet.
+};
+
+template <uint32_t NBUCKETS, uint32_t N>
+struct HeapWithBuckets<CMax<float, int>, NBUCKETS, N> {
+ static constexpr uint32_t NBUCKETS_8 = NBUCKETS / 8;
+ static_assert(
+ (NBUCKETS) > 0 && ((NBUCKETS % 8) == 0),
+ "Number of buckets needs to be 8, 16, 24, ...");
+
+ static void addn(
+ // number of elements
+ const uint32_t n,
+ // distances. It is assumed to have n elements.
+ const float* const __restrict distances,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ float* const __restrict bh_val,
+ // output indices, each being within [0, n) range
+ int32_t* const __restrict bh_ids) {
+ // forward a call to bs_addn with 1 beam
+ bs_addn(1, n, distances, k, bh_val, bh_ids);
+ }
+
+ static void bs_addn(
+ // beam_size parameter of Beam Search algorithm
+ const uint32_t beam_size,
+ // number of elements per beam
+ const uint32_t n_per_beam,
+ // distances. It is assumed to have (n_per_beam * beam_size)
+ // elements.
+ const float* const __restrict distances,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ float* const __restrict bh_val,
+ // output indices, each being within [0, n_per_beam * beam_size)
+ // range
+ int32_t* const __restrict bh_ids) {
+ // // Basically, the function runs beam_size iterations.
+ // // Every iteration NBUCKETS * N elements are added to a regular heap.
+ // // So, maximum number of added elements is beam_size * NBUCKETS * N.
+ // // This number is expected to be less or equal than k.
+ // FAISS_THROW_IF_NOT_FMT(
+ // beam_size * NBUCKETS * N >= k,
+ // "Cannot pick %d elements, only %d. "
+ // "Check the function and template arguments values.",
+ // k,
+ // beam_size * NBUCKETS * N);
+
+ using C = CMax<float, int>;
+
+ // main loop
+ for (uint32_t beam_index = 0; beam_index < beam_size; beam_index++) {
+ __m256 min_distances_i[NBUCKETS_8][N];
+ __m256i min_indices_i[NBUCKETS_8][N];
+
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ for (uint32_t p = 0; p < N; p++) {
+ min_distances_i[j][p] =
+ _mm256_set1_ps(std::numeric_limits<float>::max());
+ min_indices_i[j][p] =
+ _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ }
+ }
+
+ __m256i current_indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ __m256i indices_delta = _mm256_set1_epi32(NBUCKETS);
+
+ const uint32_t nb = (n_per_beam / NBUCKETS) * NBUCKETS;
+
+ // put the data into buckets
+ for (uint32_t ip = 0; ip < nb; ip += NBUCKETS) {
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ const __m256 distances_reg = _mm256_loadu_ps(
+ distances + j * 8 + ip + n_per_beam * beam_index);
+
+ // loop. Compiler should get rid of unneeded ops
+ __m256 distance_candidate = distances_reg;
+ __m256i indices_candidate = current_indices;
+
+ for (uint32_t p = 0; p < N; p++) {
+ const __m256 comparison = _mm256_cmp_ps(
+ min_distances_i[j][p],
+ distance_candidate,
+ _CMP_LE_OS);
+
+ // // blend seems to be slower that min
+ // const __m256 min_distances_new = _mm256_blendv_ps(
+ // distance_candidate,
+ // min_distances_i[j][p],
+ // comparison);
+ const __m256 min_distances_new = _mm256_min_ps(
+ distance_candidate, min_distances_i[j][p]);
+ const __m256i min_indices_new =
+ _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(indices_candidate),
+ _mm256_castsi256_ps(
+ min_indices_i[j][p]),
+ comparison));
+
+ // // blend seems to be slower that min
+ // const __m256 max_distances_new = _mm256_blendv_ps(
+ // min_distances_i[j][p],
+ // distance_candidate,
+ // comparison);
+ const __m256 max_distances_new = _mm256_max_ps(
+ min_distances_i[j][p], distances_reg);
+ const __m256i max_indices_new =
+ _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(
+ min_indices_i[j][p]),
+ _mm256_castsi256_ps(indices_candidate),
+ comparison));
+
+ distance_candidate = max_distances_new;
+ indices_candidate = max_indices_new;
+
+ min_distances_i[j][p] = min_distances_new;
+ min_indices_i[j][p] = min_indices_new;
+ }
+ }
+
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_delta);
+ }
+
+ // fix the indices
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ const __m256i offset =
+ _mm256_set1_epi32(n_per_beam * beam_index + j * 8);
+ for (uint32_t p = 0; p < N; p++) {
+ min_indices_i[j][p] =
+ _mm256_add_epi32(min_indices_i[j][p], offset);
+ }
+ }
+
+ // merge every bucket into the regular heap
+ for (uint32_t p = 0; p < N; p++) {
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ int32_t min_indices_scalar[8];
+ float min_distances_scalar[8];
+
+ _mm256_storeu_si256(
+ (__m256i*)min_indices_scalar, min_indices_i[j][p]);
+ _mm256_storeu_ps(
+ min_distances_scalar, min_distances_i[j][p]);
+
+ // this exact way is needed to maintain the order as if the
+ // input elements were pushed to the heap sequentially
+ for (size_t j8 = 0; j8 < 8; j8++) {
+ const auto value = min_distances_scalar[j8];
+ const auto index = min_indices_scalar[j8];
+ if (C::cmp2(bh_val[0], value, bh_ids[0], index)) {
+ heap_replace_top<C>(
+ k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+
+ // process leftovers
+ for (uint32_t ip = nb; ip < n_per_beam; ip++) {
+ const int32_t index = ip + n_per_beam * beam_index;
+ const float value = distances[index];
+
+ if (C::cmp(bh_val[0], value)) {
+ heap_replace_top<C>(k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/generic.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/generic.h
new file mode 100644
index 0000000..5bc813d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/generic.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <limits>
+#include <utility>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+// This is the implementation of the idea and it is very slow,
+// because a compiler is unable to vectorize it properly.
+
+template <typename C, uint32_t NBUCKETS, uint32_t N>
+struct HeapWithBuckets {
+ // this case was not implemented yet.
+};
+
+template <uint32_t NBUCKETS, uint32_t N>
+struct HeapWithBuckets<CMax<float, int>, NBUCKETS, N> {
+ static void addn(
+ // number of elements
+ const uint32_t n,
+ // distances. It is assumed to have n elements.
+ const float* const __restrict distances,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ float* const __restrict bh_val,
+ // output indices, each being within [0, n) range
+ int32_t* const __restrict bh_ids) {
+ // forward a call to bs_addn with 1 beam
+ bs_addn(1, n, distances, k, bh_val, bh_ids);
+ }
+
+ static void bs_addn(
+ // beam_size parameter of Beam Search algorithm
+ const uint32_t beam_size,
+ // number of elements per beam
+ const uint32_t n_per_beam,
+ // distances. It is assumed to have (n_per_beam * beam_size)
+ // elements.
+ const float* const __restrict distances,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ float* const __restrict bh_val,
+ // output indices, each being within [0, n_per_beam * beam_size)
+ // range
+ int32_t* const __restrict bh_ids) {
+ // // Basically, the function runs beam_size iterations.
+ // // Every iteration NBUCKETS * N elements are added to a regular heap.
+ // // So, maximum number of added elements is beam_size * NBUCKETS * N.
+ // // This number is expected to be less or equal than k.
+ // FAISS_THROW_IF_NOT_FMT(
+ // beam_size * NBUCKETS * N >= k,
+ // "Cannot pick %d elements, only %d. "
+ // "Check the function and template arguments values.",
+ // k,
+ // beam_size * NBUCKETS * N);
+
+ using C = CMax<float, int>;
+
+ // main loop
+ for (uint32_t beam_index = 0; beam_index < beam_size; beam_index++) {
+ float min_distances_i[N][NBUCKETS];
+ int min_indices_i[N][NBUCKETS];
+
+ for (uint32_t p = 0; p < N; p++) {
+ for (uint32_t j = 0; j < NBUCKETS; j++) {
+ min_distances_i[p][j] = std::numeric_limits<float>::max();
+ min_indices_i[p][j] = 0;
+ }
+ }
+
+ const uint32_t nb = (n_per_beam / NBUCKETS) * NBUCKETS;
+
+ // put the data into buckets
+ for (uint32_t ip = 0; ip < nb; ip += NBUCKETS) {
+ for (uint32_t j = 0; j < NBUCKETS; j++) {
+ const int index = j + ip + n_per_beam * beam_index;
+ const float distance = distances[index];
+
+ int index_candidate = index;
+ float distance_candidate = distance;
+
+ for (uint32_t p = 0; p < N; p++) {
+ if (distance_candidate < min_distances_i[p][j]) {
+ std::swap(
+ distance_candidate, min_distances_i[p][j]);
+ std::swap(index_candidate, min_indices_i[p][j]);
+ }
+ }
+ }
+ }
+
+ // merge every bucket into the regular heap
+ for (uint32_t p = 0; p < N; p++) {
+ for (uint32_t j = 0; j < NBUCKETS; j++) {
+ // this exact way is needed to maintain the order as if the
+ // input elements were pushed to the heap sequentially
+
+ if (C::cmp2(bh_val[0],
+ min_distances_i[p][j],
+ bh_ids[0],
+ min_indices_i[p][j])) {
+ heap_replace_top<C>(
+ k,
+ bh_val,
+ bh_ids,
+ min_distances_i[p][j],
+ min_indices_i[p][j]);
+ }
+ }
+ }
+
+ // process leftovers
+ for (uint32_t ip = nb; ip < n_per_beam; ip++) {
+ const int32_t index = ip + n_per_beam * beam_index;
+ const float value = distances[index];
+
+ if (C::cmp(bh_val[0], value)) {
+ heap_replace_top<C>(k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/mode.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/mode.h
new file mode 100644
index 0000000..f4294e2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk/mode.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+/// Represents the mode of use of approximate top-k computations
+/// that allows to trade accuracy vs speed. So, every options
+/// besides EXACT_TOPK increases the speed.
+///
+/// B represents the number of buckets.
+/// D is the number of min-k elements to track within every bucket.
+///
+/// Default option is EXACT_TOPK.
+/// APPROX_TOPK_BUCKETS_B16_D2 is worth starting from, if you'd like
+/// to experiment a bit.
+///
+/// It seems that only the limited number of combinations are
+/// meaningful, because of the limited supply of SIMD registers.
+/// Also, certain combinations, such as B32_D1 and B16_D1, were concluded
+/// to be not very precise in benchmarks, so ones were not introduced.
+///
+/// TODO: Consider d-ary SIMD heap.
+
+enum ApproxTopK_mode_t : int {
+ EXACT_TOPK = 0,
+ APPROX_TOPK_BUCKETS_B32_D2 = 1,
+ APPROX_TOPK_BUCKETS_B8_D3 = 2,
+ APPROX_TOPK_BUCKETS_B16_D2 = 3,
+ APPROX_TOPK_BUCKETS_B8_D2 = 4,
+};
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h
new file mode 100644
index 0000000..9f8d211
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h
@@ -0,0 +1,385 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <limits>
+#include <utility>
+
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/simdlib.h>
+
+namespace faiss {
+
+// HeapWithBucketsForHamming32 uses simd8uint32 under the hood.
+
+template <typename C, uint32_t NBUCKETS, uint32_t N, typename HammingComputerT>
+struct HeapWithBucketsForHamming32 {
+ // this case was not implemented yet.
+};
+
+template <uint32_t NBUCKETS, uint32_t N, typename HammingComputerT>
+struct HeapWithBucketsForHamming32<
+ CMax<int, int64_t>,
+ NBUCKETS,
+ N,
+ HammingComputerT> {
+ static constexpr uint32_t NBUCKETS_8 = NBUCKETS / 8;
+ static_assert(
+ (NBUCKETS) > 0 && ((NBUCKETS % 8) == 0),
+ "Number of buckets needs to be 8, 16, 24, ...");
+
+ static void addn(
+ // number of elements
+ const uint32_t n,
+ // Hamming computer
+ const HammingComputerT& hc,
+ // n elements that can be used with hc
+ const uint8_t* const __restrict binaryVectors,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ int* const __restrict bh_val,
+ // output indices, each being within [0, n) range
+ int64_t* const __restrict bh_ids,
+ // optional id selector for filtering
+ const IDSelector* sel = nullptr) {
+ // forward a call to bs_addn with 1 beam
+ bs_addn(1, n, hc, binaryVectors, k, bh_val, bh_ids, sel);
+ }
+
+ static void bs_addn(
+ // beam_size parameter of Beam Search algorithm
+ const uint32_t beam_size,
+ // number of elements per beam
+ const uint32_t n_per_beam,
+ // Hamming computer
+ const HammingComputerT& hc,
+ // n elements that can be used against hc
+ const uint8_t* const __restrict binary_vectors,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ int* const __restrict bh_val,
+ // output indices, each being within [0, n_per_beam * beam_size)
+ // range
+ int64_t* const __restrict bh_ids,
+ // optional id selector for filtering
+ const IDSelector* sel = nullptr) {
+ //
+ using C = CMax<int, int64_t>;
+
+ // Hamming code size
+ const size_t code_size = hc.get_code_size();
+
+ // main loop
+ for (uint32_t beam_index = 0; beam_index < beam_size; beam_index++) {
+ simd8uint32 min_distances_i[NBUCKETS_8][N];
+ simd8uint32 min_indices_i[NBUCKETS_8][N];
+
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ for (uint32_t p = 0; p < N; p++) {
+ min_distances_i[j][p] =
+ simd8uint32(std::numeric_limits<int32_t>::max());
+ min_indices_i[j][p] = simd8uint32(0, 1, 2, 3, 4, 5, 6, 7);
+ }
+ }
+
+ simd8uint32 current_indices(0, 1, 2, 3, 4, 5, 6, 7);
+ const simd8uint32 indices_delta(NBUCKETS);
+
+ const uint32_t nb = (n_per_beam / NBUCKETS) * NBUCKETS;
+
+ // put the data into buckets
+ for (uint32_t ip = 0; ip < nb; ip += NBUCKETS) {
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ uint32_t hamming_distances[8];
+ uint8_t valid_counter = 0;
+ for (size_t j8 = 0; j8 < 8; j8++) {
+ const uint32_t idx =
+ j8 + j * 8 + ip + n_per_beam * beam_index;
+ if (!sel || sel->is_member(idx)) {
+ hamming_distances[j8] = hc.hamming(
+ binary_vectors + idx * code_size);
+ valid_counter++;
+ } else {
+ hamming_distances[j8] =
+ std::numeric_limits<int32_t>::max();
+ }
+ }
+
+ if (valid_counter == 8) {
+ continue; // Skip if all vectors are filtered out
+ }
+
+ // loop. Compiler should get rid of unneeded ops
+ simd8uint32 distance_candidate;
+ distance_candidate.loadu(hamming_distances);
+ simd8uint32 indices_candidate = current_indices;
+
+ for (uint32_t p = 0; p < N; p++) {
+ simd8uint32 min_distances_new;
+ simd8uint32 min_indices_new;
+ simd8uint32 max_distances_new;
+ simd8uint32 max_indices_new;
+
+ faiss::cmplt_min_max_fast(
+ distance_candidate,
+ indices_candidate,
+ min_distances_i[j][p],
+ min_indices_i[j][p],
+ min_distances_new,
+ min_indices_new,
+ max_distances_new,
+ max_indices_new);
+
+ distance_candidate = max_distances_new;
+ indices_candidate = max_indices_new;
+
+ min_distances_i[j][p] = min_distances_new;
+ min_indices_i[j][p] = min_indices_new;
+ }
+ }
+
+ current_indices += indices_delta;
+ }
+
+ // fix the indices
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ const simd8uint32 offset(n_per_beam * beam_index + j * 8);
+ for (uint32_t p = 0; p < N; p++) {
+ min_indices_i[j][p] += offset;
+ }
+ }
+
+ // merge every bucket into the regular heap
+ for (uint32_t p = 0; p < N; p++) {
+ for (uint32_t j = 0; j < NBUCKETS_8; j++) {
+ uint32_t min_indices_scalar[8];
+ uint32_t min_distances_scalar[8];
+
+ min_indices_i[j][p].storeu(min_indices_scalar);
+ min_distances_i[j][p].storeu(min_distances_scalar);
+
+ // this exact way is needed to maintain the order as if the
+ // input elements were pushed to the heap sequentially
+ for (size_t j8 = 0; j8 < 8; j8++) {
+ const auto value = min_distances_scalar[j8];
+ const auto index = min_indices_scalar[j8];
+
+ if (value < std::numeric_limits<int32_t>::max() &&
+ C::cmp2(bh_val[0], value, bh_ids[0], index)) {
+ heap_replace_top<C>(
+ k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+
+ // process leftovers
+ for (uint32_t ip = nb; ip < n_per_beam; ip++) {
+ const auto index = ip + n_per_beam * beam_index;
+ if (!sel || sel->is_member(index)) {
+ const auto value =
+ hc.hamming(binary_vectors + (index)*code_size);
+
+ if (C::cmp(bh_val[0], value)) {
+ heap_replace_top<C>(k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+ }
+};
+
+// HeapWithBucketsForHamming16 uses simd16uint16 under the hood.
+// Less registers needed in total, so higher values of NBUCKETS/N can be used,
+// but somewhat slower.
+// No more than 32K elements currently, but it can be reorganized a bit
+// to be limited to 32K elements per beam.
+
+template <typename C, uint32_t NBUCKETS, uint32_t N, typename HammingComputerT>
+struct HeapWithBucketsForHamming16 {
+ // this case was not implemented yet.
+};
+
+template <uint32_t NBUCKETS, uint32_t N, typename HammingComputerT>
+struct HeapWithBucketsForHamming16<
+ CMax<int, int64_t>,
+ NBUCKETS,
+ N,
+ HammingComputerT> {
+ static constexpr uint32_t NBUCKETS_16 = NBUCKETS / 16;
+ static_assert(
+ (NBUCKETS) > 0 && ((NBUCKETS % 16) == 0),
+ "Number of buckets needs to be 16, 32, 48...");
+
+ static void addn(
+ // number of elements
+ const uint32_t n,
+ // Hamming computer
+ const HammingComputerT& hc,
+ // n elements that can be used with hc
+ const uint8_t* const __restrict binaryVectors,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ int* const __restrict bh_val,
+ // output indices, each being within [0, n) range
+ int64_t* const __restrict bh_ids) {
+ // forward a call to bs_addn with 1 beam
+ bs_addn(1, n, hc, binaryVectors, k, bh_val, bh_ids);
+ }
+
+ static void bs_addn(
+ // beam_size parameter of Beam Search algorithm
+ const uint32_t beam_size,
+ // number of elements per beam
+ const uint32_t n_per_beam,
+ // Hamming computer
+ const HammingComputerT& hc,
+ // n elements that can be used against hc
+ const uint8_t* const __restrict binary_vectors,
+ // number of best elements to keep
+ const uint32_t k,
+ // output distances
+ int* const __restrict bh_val,
+ // output indices, each being within [0, n_per_beam * beam_size)
+ // range
+ int64_t* const __restrict bh_ids) {
+ //
+ using C = CMax<int, int64_t>;
+
+ // Hamming code size
+ const size_t code_size = hc.get_code_size();
+
+ // main loop
+ for (uint32_t beam_index = 0; beam_index < beam_size; beam_index++) {
+ simd16uint16 min_distances_i[NBUCKETS_16][N];
+ simd16uint16 min_indices_i[NBUCKETS_16][N];
+
+ for (uint32_t j = 0; j < NBUCKETS_16; j++) {
+ for (uint32_t p = 0; p < N; p++) {
+ min_distances_i[j][p] =
+ simd16uint16(std::numeric_limits<int16_t>::max());
+ min_indices_i[j][p] = simd16uint16(
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15);
+ }
+ }
+
+ simd16uint16 current_indices(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ const simd16uint16 indices_delta((uint16_t)NBUCKETS);
+
+ const uint32_t nb = (n_per_beam / NBUCKETS) * NBUCKETS;
+
+ // put the data into buckets
+ for (uint32_t ip = 0; ip < nb; ip += NBUCKETS) {
+ for (uint32_t j = 0; j < NBUCKETS_16; j++) {
+ uint16_t hamming_distances[16];
+ for (size_t j16 = 0; j16 < 16; j16++) {
+ hamming_distances[j16] = hc.hamming(
+ binary_vectors +
+ (j16 + j * 16 + ip + n_per_beam * beam_index) *
+ code_size);
+ }
+
+ // loop. Compiler should get rid of unneeded ops
+ simd16uint16 distance_candidate;
+ distance_candidate.loadu(hamming_distances);
+ simd16uint16 indices_candidate = current_indices;
+
+ for (uint32_t p = 0; p < N; p++) {
+ simd16uint16 min_distances_new;
+ simd16uint16 min_indices_new;
+ simd16uint16 max_distances_new;
+ simd16uint16 max_indices_new;
+
+ faiss::cmplt_min_max_fast(
+ distance_candidate,
+ indices_candidate,
+ min_distances_i[j][p],
+ min_indices_i[j][p],
+ min_distances_new,
+ min_indices_new,
+ max_distances_new,
+ max_indices_new);
+
+ distance_candidate = max_distances_new;
+ indices_candidate = max_indices_new;
+
+ min_distances_i[j][p] = min_distances_new;
+ min_indices_i[j][p] = min_indices_new;
+ }
+ }
+
+ current_indices += indices_delta;
+ }
+
+ // fix the indices
+ for (uint32_t j = 0; j < NBUCKETS_16; j++) {
+ const simd16uint16 offset(
+ (uint16_t)(n_per_beam * beam_index + j * 16));
+ for (uint32_t p = 0; p < N; p++) {
+ min_indices_i[j][p] += offset;
+ }
+ }
+
+ // merge every bucket into the regular heap
+ for (uint32_t p = 0; p < N; p++) {
+ for (uint32_t j = 0; j < NBUCKETS_16; j++) {
+ uint16_t min_indices_scalar[16];
+ uint16_t min_distances_scalar[16];
+
+ min_indices_i[j][p].storeu(min_indices_scalar);
+ min_distances_i[j][p].storeu(min_distances_scalar);
+
+ // this exact way is needed to maintain the order as if the
+ // input elements were pushed to the heap sequentially
+ for (size_t j16 = 0; j16 < 16; j16++) {
+ const auto value = min_distances_scalar[j16];
+ const auto index = min_indices_scalar[j16];
+
+ if (C::cmp2(bh_val[0], value, bh_ids[0], index)) {
+ heap_replace_top<C>(
+ k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+
+ // process leftovers
+ for (uint32_t ip = nb; ip < n_per_beam; ip++) {
+ const auto index = ip + n_per_beam * beam_index;
+ const auto value =
+ hc.hamming(binary_vectors + (index)*code_size);
+
+ if (C::cmp(bh_val[0], value)) {
+ heap_replace_top<C>(k, bh_val, bh_ids, value, index);
+ }
+ }
+ }
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/bf16.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/bf16.h
new file mode 100644
index 0000000..7d29e35
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/bf16.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+
+namespace faiss {
+
+namespace {
+
+union fp32_bits {
+ uint32_t as_u32;
+ float as_f32;
+};
+
+} // namespace
+
+inline uint16_t encode_bf16(const float f) {
+ // Round off
+ fp32_bits fp;
+ fp.as_f32 = f;
+ return static_cast<uint16_t>((fp.as_u32 + 0x8000) >> 16);
+}
+
+inline float decode_bf16(const uint16_t v) {
+ fp32_bits fp;
+ fp.as_u32 = (uint32_t(v) << 16);
+ return fp.as_f32;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances.cpp
new file mode 100644
index 0000000..4241f2f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances.cpp
@@ -0,0 +1,1208 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/utils/distances.h>
+
+#include <algorithm>
+#include <cassert>
+#include <cmath>
+#include <cstddef>
+#include <cstdio>
+#include <cstring>
+
+#include <omp.h>
+
+#ifdef __AVX2__
+#include <immintrin.h>
+#elif defined(__ARM_FEATURE_SVE)
+#include <arm_sve.h>
+#endif
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/ResultHandler.h>
+
+#include <faiss/utils/distances_fused/distances_fused.h>
+
+#ifndef FINTEGER
+#define FINTEGER long
+#endif
+
+extern "C" {
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+/***************************************************************************
+ * Matrix/vector ops
+ ***************************************************************************/
+
+/* Compute the L2 norm of a set of nx vectors */
+void fvec_norms_L2(
+ float* __restrict nr,
+ const float* __restrict x,
+ size_t d,
+ size_t nx) {
+#pragma omp parallel for if (nx > 10000)
+ for (int64_t i = 0; i < nx; i++) {
+ nr[i] = sqrtf(fvec_norm_L2sqr(x + i * d, d));
+ }
+}
+
+void fvec_norms_L2sqr(
+ float* __restrict nr,
+ const float* __restrict x,
+ size_t d,
+ size_t nx) {
+#pragma omp parallel for if (nx > 10000)
+ for (int64_t i = 0; i < nx; i++)
+ nr[i] = fvec_norm_L2sqr(x + i * d, d);
+}
+
+// The following is a workaround to a problem
+// in OpenMP in fbcode. The crash occurs
+// inside OMP when IndexIVFSpectralHash::set_query()
+// calls fvec_renorm_L2. set_query() is always
+// calling this function with nx == 1, so even
+// the omp version should run single threaded,
+// as per the if condition of the omp pragma.
+// Instead, the omp version crashes inside OMP.
+// The workaround below is explicitly branching
+// off to a codepath without omp.
+
+#define FVEC_RENORM_L2_IMPL \
+ float* __restrict xi = x + i * d; \
+ \
+ float nr = fvec_norm_L2sqr(xi, d); \
+ \
+ if (nr > 0) { \
+ size_t j; \
+ const float inv_nr = 1.0 / sqrtf(nr); \
+ for (j = 0; j < d; j++) \
+ xi[j] *= inv_nr; \
+ }
+
+void fvec_renorm_L2_noomp(size_t d, size_t nx, float* __restrict x) {
+ for (int64_t i = 0; i < nx; i++) {
+ FVEC_RENORM_L2_IMPL
+ }
+}
+
+void fvec_renorm_L2_omp(size_t d, size_t nx, float* __restrict x) {
+#pragma omp parallel for if (nx > 10000)
+ for (int64_t i = 0; i < nx; i++) {
+ FVEC_RENORM_L2_IMPL
+ }
+}
+
+void fvec_renorm_L2(size_t d, size_t nx, float* __restrict x) {
+ if (nx <= 10000) {
+ fvec_renorm_L2_noomp(d, nx, x);
+ } else {
+ fvec_renorm_L2_omp(d, nx, x);
+ }
+}
+
+/***************************************************************************
+ * KNN functions
+ ***************************************************************************/
+
+namespace {
+
+/* Find the nearest neighbors for nx queries in a set of ny vectors */
+template <class BlockResultHandler>
+void exhaustive_inner_product_seq(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ BlockResultHandler& res) {
+ using SingleResultHandler =
+ typename BlockResultHandler::SingleResultHandler;
+ [[maybe_unused]] int nt = std::min(int(nx), omp_get_max_threads());
+
+#pragma omp parallel num_threads(nt)
+ {
+ SingleResultHandler resi(res);
+#pragma omp for
+ for (int64_t i = 0; i < nx; i++) {
+ const float* x_i = x + i * d;
+ const float* y_j = y;
+
+ resi.begin(i);
+
+ for (size_t j = 0; j < ny; j++, y_j += d) {
+ if (!res.is_in_selection(j)) {
+ continue;
+ }
+ float ip = fvec_inner_product(x_i, y_j, d);
+ resi.add_result(ip, j);
+ }
+ resi.end();
+ }
+ }
+}
+
+template <class BlockResultHandler>
+void exhaustive_L2sqr_seq(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ BlockResultHandler& res) {
+ using SingleResultHandler =
+ typename BlockResultHandler::SingleResultHandler;
+ [[maybe_unused]] int nt = std::min(int(nx), omp_get_max_threads());
+
+#pragma omp parallel num_threads(nt)
+ {
+ SingleResultHandler resi(res);
+#pragma omp for
+ for (int64_t i = 0; i < nx; i++) {
+ const float* x_i = x + i * d;
+ const float* y_j = y;
+ resi.begin(i);
+ for (size_t j = 0; j < ny; j++, y_j += d) {
+ if (!res.is_in_selection(j)) {
+ continue;
+ }
+ float disij = fvec_L2sqr(x_i, y_j, d);
+ resi.add_result(disij, j);
+ }
+ resi.end();
+ }
+ }
+}
+
+/** Find the nearest neighbors for nx queries in a set of ny vectors */
+template <class BlockResultHandler>
+void exhaustive_inner_product_blas(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ BlockResultHandler& res) {
+ // BLAS does not like empty matrices
+ if (nx == 0 || ny == 0)
+ return;
+
+ /* block sizes */
+ const size_t bs_x = distance_compute_blas_query_bs;
+ const size_t bs_y = distance_compute_blas_database_bs;
+ std::unique_ptr<float[]> ip_block(new float[bs_x * bs_y]);
+
+ for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
+ size_t i1 = i0 + bs_x;
+ if (i1 > nx)
+ i1 = nx;
+
+ res.begin_multiple(i0, i1);
+
+ for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
+ size_t j1 = j0 + bs_y;
+ if (j1 > ny)
+ j1 = ny;
+ /* compute the actual dot products */
+ {
+ float one = 1, zero = 0;
+ FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
+ sgemm_("Transpose",
+ "Not transpose",
+ &nyi,
+ &nxi,
+ &di,
+ &one,
+ y + j0 * d,
+ &di,
+ x + i0 * d,
+ &di,
+ &zero,
+ ip_block.get(),
+ &nyi);
+ }
+
+ res.add_results(j0, j1, ip_block.get());
+ }
+ res.end_multiple();
+ InterruptCallback::check();
+ }
+}
+
+// distance correction is an operator that can be applied to transform
+// the distances
+template <class BlockResultHandler>
+void exhaustive_L2sqr_blas_default_impl(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ BlockResultHandler& res,
+ const float* y_norms = nullptr) {
+ // BLAS does not like empty matrices
+ if (nx == 0 || ny == 0)
+ return;
+
+ /* block sizes */
+ const size_t bs_x = distance_compute_blas_query_bs;
+ const size_t bs_y = distance_compute_blas_database_bs;
+ // const size_t bs_x = 16, bs_y = 16;
+ std::unique_ptr<float[]> ip_block(new float[bs_x * bs_y]);
+ std::unique_ptr<float[]> x_norms(new float[nx]);
+ std::unique_ptr<float[]> del2;
+
+ fvec_norms_L2sqr(x_norms.get(), x, d, nx);
+
+ if (!y_norms) {
+ float* y_norms2 = new float[ny];
+ del2.reset(y_norms2);
+ fvec_norms_L2sqr(y_norms2, y, d, ny);
+ y_norms = y_norms2;
+ }
+
+ for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
+ size_t i1 = i0 + bs_x;
+ if (i1 > nx)
+ i1 = nx;
+
+ res.begin_multiple(i0, i1);
+
+ for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
+ size_t j1 = j0 + bs_y;
+ if (j1 > ny)
+ j1 = ny;
+ /* compute the actual dot products */
+ {
+ float one = 1, zero = 0;
+ FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
+ sgemm_("Transpose",
+ "Not transpose",
+ &nyi,
+ &nxi,
+ &di,
+ &one,
+ y + j0 * d,
+ &di,
+ x + i0 * d,
+ &di,
+ &zero,
+ ip_block.get(),
+ &nyi);
+ }
+#pragma omp parallel for
+ for (int64_t i = i0; i < i1; i++) {
+ float* ip_line = ip_block.get() + (i - i0) * (j1 - j0);
+
+ for (size_t j = j0; j < j1; j++) {
+ float ip = *ip_line;
+ float dis = x_norms[i] + y_norms[j] - 2 * ip;
+
+ if (!res.is_in_selection(j)) {
+ dis = HUGE_VALF;
+ }
+ // negative values can occur for identical vectors
+ // due to roundoff errors
+ if (dis < 0)
+ dis = 0;
+
+ *ip_line = dis;
+ ip_line++;
+ }
+ }
+ res.add_results(j0, j1, ip_block.get());
+ }
+ res.end_multiple();
+ InterruptCallback::check();
+ }
+}
+
+template <class BlockResultHandler>
+void exhaustive_L2sqr_blas(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ BlockResultHandler& res,
+ const float* y_norms = nullptr) {
+ exhaustive_L2sqr_blas_default_impl(x, y, d, nx, ny, res);
+}
+
+#ifdef __AVX2__
+void exhaustive_L2sqr_blas_cmax_avx2(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms) {
+ // BLAS does not like empty matrices
+ if (nx == 0 || ny == 0)
+ return;
+
+ /* block sizes */
+ const size_t bs_x = distance_compute_blas_query_bs;
+ const size_t bs_y = distance_compute_blas_database_bs;
+ // const size_t bs_x = 16, bs_y = 16;
+ std::unique_ptr<float[]> ip_block(new float[bs_x * bs_y]);
+ std::unique_ptr<float[]> x_norms(new float[nx]);
+ std::unique_ptr<float[]> del2;
+
+ fvec_norms_L2sqr(x_norms.get(), x, d, nx);
+
+ if (!y_norms) {
+ float* y_norms2 = new float[ny];
+ del2.reset(y_norms2);
+ fvec_norms_L2sqr(y_norms2, y, d, ny);
+ y_norms = y_norms2;
+ }
+
+ for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
+ size_t i1 = i0 + bs_x;
+ if (i1 > nx)
+ i1 = nx;
+
+ res.begin_multiple(i0, i1);
+
+ for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
+ size_t j1 = j0 + bs_y;
+ if (j1 > ny)
+ j1 = ny;
+ /* compute the actual dot products */
+ {
+ float one = 1, zero = 0;
+ FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
+ sgemm_("Transpose",
+ "Not transpose",
+ &nyi,
+ &nxi,
+ &di,
+ &one,
+ y + j0 * d,
+ &di,
+ x + i0 * d,
+ &di,
+ &zero,
+ ip_block.get(),
+ &nyi);
+ }
+#pragma omp parallel for
+ for (int64_t i = i0; i < i1; i++) {
+ float* ip_line = ip_block.get() + (i - i0) * (j1 - j0);
+
+ _mm_prefetch((const char*)ip_line, _MM_HINT_NTA);
+ _mm_prefetch((const char*)(ip_line + 16), _MM_HINT_NTA);
+
+ // constant
+ const __m256 mul_minus2 = _mm256_set1_ps(-2);
+
+ // Track 8 min distances + 8 min indices.
+ // All the distances tracked do not take x_norms[i]
+ // into account in order to get rid of extra
+ // _mm256_add_ps(x_norms[i], ...) instructions
+ // is distance computations.
+ __m256 min_distances =
+ _mm256_set1_ps(res.dis_tab[i] - x_norms[i]);
+
+ // these indices are local and are relative to j0.
+ // so, value 0 means j0.
+ __m256i min_indices = _mm256_set1_epi32(0);
+
+ __m256i current_indices =
+ _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ const __m256i indices_delta = _mm256_set1_epi32(8);
+
+ // current j index
+ size_t idx_j = 0;
+ size_t count = j1 - j0;
+
+ // process 16 elements per loop
+ for (; idx_j < (count / 16) * 16; idx_j += 16, ip_line += 16) {
+ _mm_prefetch((const char*)(ip_line + 32), _MM_HINT_NTA);
+ _mm_prefetch((const char*)(ip_line + 48), _MM_HINT_NTA);
+
+ // load values for norms
+ const __m256 y_norm_0 =
+ _mm256_loadu_ps(y_norms + idx_j + j0 + 0);
+ const __m256 y_norm_1 =
+ _mm256_loadu_ps(y_norms + idx_j + j0 + 8);
+
+ // load values for dot products
+ const __m256 ip_0 = _mm256_loadu_ps(ip_line + 0);
+ const __m256 ip_1 = _mm256_loadu_ps(ip_line + 8);
+
+ // compute dis = y_norm[j] - 2 * dot(x_norm[i], y_norm[j]).
+ // x_norm[i] was dropped off because it is a constant for a
+ // given i. We'll deal with it later.
+ __m256 distances_0 =
+ _mm256_fmadd_ps(ip_0, mul_minus2, y_norm_0);
+ __m256 distances_1 =
+ _mm256_fmadd_ps(ip_1, mul_minus2, y_norm_1);
+
+ // compare the new distances to the min distances
+ // for each of the first group of 8 AVX2 components.
+ const __m256 comparison_0 = _mm256_cmp_ps(
+ min_distances, distances_0, _CMP_LE_OS);
+
+ // update min distances and indices with closest vectors if
+ // needed.
+ min_distances = _mm256_blendv_ps(
+ distances_0, min_distances, comparison_0);
+ min_indices = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ comparison_0));
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_delta);
+
+ // compare the new distances to the min distances
+ // for each of the second group of 8 AVX2 components.
+ const __m256 comparison_1 = _mm256_cmp_ps(
+ min_distances, distances_1, _CMP_LE_OS);
+
+ // update min distances and indices with closest vectors if
+ // needed.
+ min_distances = _mm256_blendv_ps(
+ distances_1, min_distances, comparison_1);
+ min_indices = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ comparison_1));
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_delta);
+ }
+
+ // dump values and find the minimum distance / minimum index
+ float min_distances_scalar[8];
+ uint32_t min_indices_scalar[8];
+ _mm256_storeu_ps(min_distances_scalar, min_distances);
+ _mm256_storeu_si256(
+ (__m256i*)(min_indices_scalar), min_indices);
+
+ float current_min_distance = res.dis_tab[i];
+ uint32_t current_min_index = res.ids_tab[i];
+
+ // This unusual comparison is needed to maintain the behavior
+ // of the original implementation: if two indices are
+ // represented with equal distance values, then
+ // the index with the min value is returned.
+ for (size_t jv = 0; jv < 8; jv++) {
+ // add missing x_norms[i]
+ float distance_candidate =
+ min_distances_scalar[jv] + x_norms[i];
+
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ if (distance_candidate < 0)
+ distance_candidate = 0;
+
+ int64_t index_candidate = min_indices_scalar[jv] + j0;
+
+ if (current_min_distance > distance_candidate) {
+ current_min_distance = distance_candidate;
+ current_min_index = index_candidate;
+ } else if (
+ current_min_distance == distance_candidate &&
+ current_min_index > index_candidate) {
+ current_min_index = index_candidate;
+ }
+ }
+
+ // process leftovers
+ for (; idx_j < count; idx_j++, ip_line++) {
+ float ip = *ip_line;
+ float dis = x_norms[i] + y_norms[idx_j + j0] - 2 * ip;
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ if (dis < 0)
+ dis = 0;
+
+ if (current_min_distance > dis) {
+ current_min_distance = dis;
+ current_min_index = idx_j + j0;
+ }
+ }
+
+ //
+ res.add_result(i, current_min_distance, current_min_index);
+ }
+ }
+ // Does nothing for SingleBestResultHandler, but
+ // keeping the call for the consistency.
+ res.end_multiple();
+ InterruptCallback::check();
+ }
+}
+#elif defined(__ARM_FEATURE_SVE)
+void exhaustive_L2sqr_blas_cmax_sve(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms) {
+ // BLAS does not like empty matrices
+ if (nx == 0 || ny == 0)
+ return;
+
+ /* block sizes */
+ const size_t bs_x = distance_compute_blas_query_bs;
+ const size_t bs_y = distance_compute_blas_database_bs;
+ // const size_t bs_x = 16, bs_y = 16;
+ std::unique_ptr<float[]> ip_block(new float[bs_x * bs_y]);
+ std::unique_ptr<float[]> x_norms(new float[nx]);
+ std::unique_ptr<float[]> del2;
+
+ fvec_norms_L2sqr(x_norms.get(), x, d, nx);
+
+ const size_t lanes = svcntw();
+
+ if (!y_norms) {
+ float* y_norms2 = new float[ny];
+ del2.reset(y_norms2);
+ fvec_norms_L2sqr(y_norms2, y, d, ny);
+ y_norms = y_norms2;
+ }
+
+ for (size_t i0 = 0; i0 < nx; i0 += bs_x) {
+ size_t i1 = i0 + bs_x;
+ if (i1 > nx)
+ i1 = nx;
+
+ res.begin_multiple(i0, i1);
+
+ for (size_t j0 = 0; j0 < ny; j0 += bs_y) {
+ size_t j1 = j0 + bs_y;
+ if (j1 > ny)
+ j1 = ny;
+ /* compute the actual dot products */
+ {
+ float one = 1, zero = 0;
+ FINTEGER nyi = j1 - j0, nxi = i1 - i0, di = d;
+ sgemm_("Transpose",
+ "Not transpose",
+ &nyi,
+ &nxi,
+ &di,
+ &one,
+ y + j0 * d,
+ &di,
+ x + i0 * d,
+ &di,
+ &zero,
+ ip_block.get(),
+ &nyi);
+ }
+#pragma omp parallel for
+ for (int64_t i = i0; i < i1; i++) {
+ const size_t count = j1 - j0;
+ float* ip_line = ip_block.get() + (i - i0) * count;
+
+ svprfw(svwhilelt_b32_u64(0, count), ip_line, SV_PLDL1KEEP);
+ svprfw(svwhilelt_b32_u64(lanes, count),
+ ip_line + lanes,
+ SV_PLDL1KEEP);
+
+ // Track lanes min distances + lanes min indices.
+ // All the distances tracked do not take x_norms[i]
+ // into account in order to get rid of extra
+ // vaddq_f32(x_norms[i], ...) instructions
+ // is distance computations.
+ auto min_distances = svdup_n_f32(res.dis_tab[i] - x_norms[i]);
+
+ // these indices are local and are relative to j0.
+ // so, value 0 means j0.
+ auto min_indices = svdup_n_u32(0u);
+
+ auto current_indices = svindex_u32(0u, 1u);
+
+ // process lanes * 2 elements per loop
+ for (size_t idx_j = 0; idx_j < count;
+ idx_j += lanes * 2, ip_line += lanes * 2) {
+ svprfw(svwhilelt_b32_u64(idx_j + lanes * 2, count),
+ ip_line + lanes * 2,
+ SV_PLDL1KEEP);
+ svprfw(svwhilelt_b32_u64(idx_j + lanes * 3, count),
+ ip_line + lanes * 3,
+ SV_PLDL1KEEP);
+
+ // mask
+ const auto mask_0 = svwhilelt_b32_u64(idx_j, count);
+ const auto mask_1 = svwhilelt_b32_u64(idx_j + lanes, count);
+
+ // load values for norms
+ const auto y_norm_0 =
+ svld1_f32(mask_0, y_norms + idx_j + j0 + 0);
+ const auto y_norm_1 =
+ svld1_f32(mask_1, y_norms + idx_j + j0 + lanes);
+
+ // load values for dot products
+ const auto ip_0 = svld1_f32(mask_0, ip_line + 0);
+ const auto ip_1 = svld1_f32(mask_1, ip_line + lanes);
+
+ // compute dis = y_norm[j] - 2 * dot(x_norm[i], y_norm[j]).
+ // x_norm[i] was dropped off because it is a constant for a
+ // given i. We'll deal with it later.
+ const auto distances_0 =
+ svmla_n_f32_z(mask_0, y_norm_0, ip_0, -2.f);
+ const auto distances_1 =
+ svmla_n_f32_z(mask_1, y_norm_1, ip_1, -2.f);
+
+ // compare the new distances to the min distances
+ // for each of the first group of 4 ARM SIMD components.
+ auto comparison =
+ svcmpgt_f32(mask_0, min_distances, distances_0);
+
+ // update min distances and indices with closest vectors if
+ // needed.
+ min_distances =
+ svsel_f32(comparison, distances_0, min_distances);
+ min_indices =
+ svsel_u32(comparison, current_indices, min_indices);
+ current_indices = svadd_n_u32_x(
+ mask_0,
+ current_indices,
+ static_cast<uint32_t>(lanes));
+
+ // compare the new distances to the min distances
+ // for each of the second group of 4 ARM SIMD components.
+ comparison =
+ svcmpgt_f32(mask_1, min_distances, distances_1);
+
+ // update min distances and indices with closest vectors if
+ // needed.
+ min_distances =
+ svsel_f32(comparison, distances_1, min_distances);
+ min_indices =
+ svsel_u32(comparison, current_indices, min_indices);
+ current_indices = svadd_n_u32_x(
+ mask_1,
+ current_indices,
+ static_cast<uint32_t>(lanes));
+ }
+
+ // add missing x_norms[i]
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ auto mask = svwhilelt_b32_u64(0, count);
+ min_distances = svadd_n_f32_z(
+ svcmpge_n_f32(mask, min_distances, -x_norms[i]),
+ min_distances,
+ x_norms[i]);
+ min_indices = svadd_n_u32_x(
+ mask, min_indices, static_cast<uint32_t>(j0));
+ mask = svcmple_n_f32(mask, min_distances, res.dis_tab[i]);
+ if (svcntp_b32(svptrue_b32(), mask) == 0)
+ res.add_result(i, res.dis_tab[i], res.ids_tab[i]);
+ else {
+ const auto min_distance = svminv_f32(mask, min_distances);
+ const auto min_index = svminv_u32(
+ svcmpeq_n_f32(mask, min_distances, min_distance),
+ min_indices);
+ res.add_result(i, min_distance, min_index);
+ }
+ }
+ }
+ // Does nothing for SingleBestResultHandler, but
+ // keeping the call for the consistency.
+ res.end_multiple();
+ InterruptCallback::check();
+ }
+}
+#endif
+
+// an override if only a single closest point is needed
+template <>
+void exhaustive_L2sqr_blas<Top1BlockResultHandler<CMax<float, int64_t>>>(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms) {
+#if defined(__AVX2__)
+ // use a faster fused kernel if available
+ if (exhaustive_L2sqr_fused_cmax(x, y, d, nx, ny, res, y_norms)) {
+ // the kernel is available and it is complete, we're done.
+ return;
+ }
+
+ // run the specialized AVX2 implementation
+ exhaustive_L2sqr_blas_cmax_avx2(x, y, d, nx, ny, res, y_norms);
+
+#elif defined(__ARM_FEATURE_SVE)
+ // use a faster fused kernel if available
+ if (exhaustive_L2sqr_fused_cmax(x, y, d, nx, ny, res, y_norms)) {
+ // the kernel is available and it is complete, we're done.
+ return;
+ }
+
+ // run the specialized SVE implementation
+ exhaustive_L2sqr_blas_cmax_sve(x, y, d, nx, ny, res, y_norms);
+
+#elif defined(__aarch64__)
+ // use a faster fused kernel if available
+ if (exhaustive_L2sqr_fused_cmax(x, y, d, nx, ny, res, y_norms)) {
+ // the kernel is available and it is complete, we're done.
+ return;
+ }
+
+ // run the default implementation
+ exhaustive_L2sqr_blas_default_impl<
+ Top1BlockResultHandler<CMax<float, int64_t>>>(
+ x, y, d, nx, ny, res, y_norms);
+#else
+ // run the default implementation
+ exhaustive_L2sqr_blas_default_impl<
+ Top1BlockResultHandler<CMax<float, int64_t>>>(
+ x, y, d, nx, ny, res, y_norms);
+#endif
+}
+
+struct Run_search_inner_product {
+ using T = void;
+ template <class BlockResultHandler>
+ void f(BlockResultHandler& res,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny) {
+ if (res.sel || nx < distance_compute_blas_threshold) {
+ exhaustive_inner_product_seq(x, y, d, nx, ny, res);
+ } else {
+ exhaustive_inner_product_blas(x, y, d, nx, ny, res);
+ }
+ }
+};
+
+struct Run_search_L2sqr {
+ using T = void;
+ template <class BlockResultHandler>
+ void f(BlockResultHandler& res,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ const float* y_norm2) {
+ if (res.sel || nx < distance_compute_blas_threshold) {
+ exhaustive_L2sqr_seq(x, y, d, nx, ny, res);
+ } else {
+ exhaustive_L2sqr_blas(x, y, d, nx, ny, res, y_norm2);
+ }
+ }
+};
+
+} // anonymous namespace
+
+/*******************************************************
+ * KNN driver functions
+ *******************************************************/
+
+int distance_compute_blas_threshold = 20;
+int distance_compute_blas_query_bs = 4096;
+int distance_compute_blas_database_bs = 1024;
+int distance_compute_min_k_reservoir = 100;
+
+void knn_inner_product(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t k,
+ float* vals,
+ int64_t* ids,
+ const IDSelector* sel) {
+ int64_t imin = 0;
+ if (auto selr = dynamic_cast<const IDSelectorRange*>(sel)) {
+ imin = std::max(selr->imin, int64_t(0));
+ int64_t imax = std::min(selr->imax, int64_t(ny));
+ ny = imax - imin;
+ y += d * imin;
+ sel = nullptr;
+ }
+ if (auto sela = dynamic_cast<const IDSelectorArray*>(sel)) {
+ knn_inner_products_by_idx(
+ x, y, sela->ids, d, nx, ny, sela->n, k, vals, ids, 0);
+ return;
+ }
+
+ Run_search_inner_product r;
+ dispatch_knn_ResultHandler(
+ nx, vals, ids, k, METRIC_INNER_PRODUCT, sel, r, x, y, d, nx, ny);
+
+ if (imin != 0) {
+ for (size_t i = 0; i < nx * k; i++) {
+ if (ids[i] >= 0) {
+ ids[i] += imin;
+ }
+ }
+ }
+}
+
+void knn_inner_product(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float_minheap_array_t* res,
+ const IDSelector* sel) {
+ FAISS_THROW_IF_NOT(nx == res->nh);
+ knn_inner_product(x, y, d, nx, ny, res->k, res->val, res->ids, sel);
+}
+
+void knn_L2sqr(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t k,
+ float* vals,
+ int64_t* ids,
+ const float* y_norm2,
+ const IDSelector* sel) {
+ int64_t imin = 0;
+ if (auto selr = dynamic_cast<const IDSelectorRange*>(sel)) {
+ imin = std::max(selr->imin, int64_t(0));
+ int64_t imax = std::min(selr->imax, int64_t(ny));
+ ny = imax - imin;
+ y += d * imin;
+ sel = nullptr;
+ }
+ if (auto sela = dynamic_cast<const IDSelectorArray*>(sel)) {
+ knn_L2sqr_by_idx(x, y, sela->ids, d, nx, ny, sela->n, k, vals, ids, 0);
+ return;
+ }
+
+ Run_search_L2sqr r;
+ dispatch_knn_ResultHandler(
+ nx, vals, ids, k, METRIC_L2, sel, r, x, y, d, nx, ny, y_norm2);
+
+ if (imin != 0) {
+ for (size_t i = 0; i < nx * k; i++) {
+ if (ids[i] >= 0) {
+ ids[i] += imin;
+ }
+ }
+ }
+}
+
+void knn_L2sqr(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float_maxheap_array_t* res,
+ const float* y_norm2,
+ const IDSelector* sel) {
+ FAISS_THROW_IF_NOT(res->nh == nx);
+ knn_L2sqr(x, y, d, nx, ny, res->k, res->val, res->ids, y_norm2, sel);
+}
+
+/***************************************************************************
+ * Range search
+ ***************************************************************************/
+
+// TODO accept a y_norm2 as well
+void range_search_L2sqr(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float radius,
+ RangeSearchResult* res,
+ const IDSelector* sel) {
+ Run_search_L2sqr r;
+ dispatch_range_ResultHandler(
+ res, radius, METRIC_L2, sel, r, x, y, d, nx, ny, nullptr);
+}
+
+void range_search_inner_product(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float radius,
+ RangeSearchResult* res,
+ const IDSelector* sel) {
+ Run_search_inner_product r;
+ dispatch_range_ResultHandler(
+ res, radius, METRIC_INNER_PRODUCT, sel, r, x, y, d, nx, ny);
+}
+
+/***************************************************************************
+ * compute a subset of distances
+ ***************************************************************************/
+
+/* compute the inner product between x and a subset y of ny vectors,
+ whose indices are given by idy. */
+void fvec_inner_products_by_idx(
+ float* __restrict ip,
+ const float* x,
+ const float* y,
+ const int64_t* __restrict ids, /* for y vecs */
+ size_t d,
+ size_t nx,
+ size_t ny) {
+#pragma omp parallel for
+ for (int64_t j = 0; j < nx; j++) {
+ const int64_t* __restrict idsj = ids + j * ny;
+ const float* xj = x + j * d;
+ float* __restrict ipj = ip + j * ny;
+ for (size_t i = 0; i < ny; i++) {
+ if (idsj[i] < 0) {
+ ipj[i] = -INFINITY;
+ } else {
+ ipj[i] = fvec_inner_product(xj, y + d * idsj[i], d);
+ }
+ }
+ }
+}
+
+/* compute the inner product between x and a subset y of ny vectors,
+ whose indices are given by idy. */
+void fvec_L2sqr_by_idx(
+ float* __restrict dis,
+ const float* x,
+ const float* y,
+ const int64_t* __restrict ids, /* ids of y vecs */
+ size_t d,
+ size_t nx,
+ size_t ny) {
+#pragma omp parallel for
+ for (int64_t j = 0; j < nx; j++) {
+ const int64_t* __restrict idsj = ids + j * ny;
+ const float* xj = x + j * d;
+ float* __restrict disj = dis + j * ny;
+ for (size_t i = 0; i < ny; i++) {
+ if (idsj[i] < 0) {
+ disj[i] = INFINITY;
+ } else {
+ disj[i] = fvec_L2sqr(xj, y + d * idsj[i], d);
+ }
+ }
+ }
+}
+
+void pairwise_indexed_L2sqr(
+ size_t d,
+ size_t n,
+ const float* x,
+ const int64_t* ix,
+ const float* y,
+ const int64_t* iy,
+ float* dis) {
+#pragma omp parallel for if (n > 1)
+ for (int64_t j = 0; j < n; j++) {
+ if (ix[j] >= 0 && iy[j] >= 0) {
+ dis[j] = fvec_L2sqr(x + d * ix[j], y + d * iy[j], d);
+ } else {
+ dis[j] = INFINITY;
+ }
+ }
+}
+
+void pairwise_indexed_inner_product(
+ size_t d,
+ size_t n,
+ const float* x,
+ const int64_t* ix,
+ const float* y,
+ const int64_t* iy,
+ float* dis) {
+#pragma omp parallel for if (n > 1)
+ for (int64_t j = 0; j < n; j++) {
+ if (ix[j] >= 0 && iy[j] >= 0) {
+ dis[j] = fvec_inner_product(x + d * ix[j], y + d * iy[j], d);
+ } else {
+ dis[j] = -INFINITY;
+ }
+ }
+}
+
+/* Find the nearest neighbors for nx queries in a set of ny vectors
+ indexed by ids. May be useful for re-ranking a pre-selected vector list */
+void knn_inner_products_by_idx(
+ const float* x,
+ const float* y,
+ const int64_t* ids,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t nsubset,
+ size_t k,
+ float* res_vals,
+ int64_t* res_ids,
+ int64_t ld_ids) {
+ if (ld_ids < 0) {
+ ld_ids = ny;
+ }
+
+#pragma omp parallel for if (nx > 100)
+ for (int64_t i = 0; i < nx; i++) {
+ const float* x_ = x + i * d;
+ const int64_t* idsi = ids + i * ld_ids;
+ size_t j;
+ float* __restrict simi = res_vals + i * k;
+ int64_t* __restrict idxi = res_ids + i * k;
+ minheap_heapify(k, simi, idxi);
+
+ for (j = 0; j < nsubset; j++) {
+ if (idsi[j] < 0 || idsi[j] >= ny) {
+ break;
+ }
+ float ip = fvec_inner_product(x_, y + d * idsi[j], d);
+
+ if (ip > simi[0]) {
+ minheap_replace_top(k, simi, idxi, ip, idsi[j]);
+ }
+ }
+ minheap_reorder(k, simi, idxi);
+ }
+}
+
+void knn_L2sqr_by_idx(
+ const float* x,
+ const float* y,
+ const int64_t* __restrict ids,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t nsubset,
+ size_t k,
+ float* res_vals,
+ int64_t* res_ids,
+ int64_t ld_ids) {
+ if (ld_ids < 0) {
+ ld_ids = ny;
+ }
+#pragma omp parallel for if (nx > 100)
+ for (int64_t i = 0; i < nx; i++) {
+ const float* x_ = x + i * d;
+ const int64_t* __restrict idsi = ids + i * ld_ids;
+ float* __restrict simi = res_vals + i * k;
+ int64_t* __restrict idxi = res_ids + i * k;
+ maxheap_heapify(k, simi, idxi);
+ for (size_t j = 0; j < nsubset; j++) {
+ if (idsi[j] < 0 || idsi[j] >= ny) {
+ break;
+ }
+ float disij = fvec_L2sqr(x_, y + d * idsi[j], d);
+
+ if (disij < simi[0]) {
+ maxheap_replace_top(k, simi, idxi, disij, idsi[j]);
+ }
+ }
+ maxheap_reorder(k, simi, idxi);
+ }
+}
+
+void pairwise_L2sqr(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis,
+ int64_t ldq,
+ int64_t ldb,
+ int64_t ldd) {
+ if (nq == 0 || nb == 0)
+ return;
+ if (ldq == -1)
+ ldq = d;
+ if (ldb == -1)
+ ldb = d;
+ if (ldd == -1)
+ ldd = nb;
+
+ // store in beginning of distance matrix to avoid malloc
+ float* b_norms = dis;
+
+#pragma omp parallel for if (nb > 1)
+ for (int64_t i = 0; i < nb; i++)
+ b_norms[i] = fvec_norm_L2sqr(xb + i * ldb, d);
+
+#pragma omp parallel for
+ for (int64_t i = 1; i < nq; i++) {
+ float q_norm = fvec_norm_L2sqr(xq + i * ldq, d);
+ for (int64_t j = 0; j < nb; j++)
+ dis[i * ldd + j] = q_norm + b_norms[j];
+ }
+
+ {
+ float q_norm = fvec_norm_L2sqr(xq, d);
+ for (int64_t j = 0; j < nb; j++)
+ dis[j] += q_norm;
+ }
+
+ {
+ FINTEGER nbi = nb, nqi = nq, di = d, ldqi = ldq, ldbi = ldb, lddi = ldd;
+ float one = 1.0, minus_2 = -2.0;
+
+ sgemm_("Transposed",
+ "Not transposed",
+ &nbi,
+ &nqi,
+ &di,
+ &minus_2,
+ xb,
+ &ldbi,
+ xq,
+ &ldqi,
+ &one,
+ dis,
+ &lddi);
+ }
+}
+
+void inner_product_to_L2sqr(
+ float* __restrict dis,
+ const float* nr1,
+ const float* nr2,
+ size_t n1,
+ size_t n2) {
+#pragma omp parallel for
+ for (int64_t j = 0; j < n1; j++) {
+ float* disj = dis + j * n2;
+ for (size_t i = 0; i < n2; i++)
+ disj[i] = nr1[j] + nr2[i] - 2 * disj[i];
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances.h
new file mode 100644
index 0000000..80d2cfc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances.h
@@ -0,0 +1,486 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/* All distance functions for L2 and IP distances.
+ * The actual functions are implemented in distances.cpp and distances_simd.cpp
+ */
+
+#pragma once
+
+#include <stdint.h>
+
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+struct IDSelector;
+
+/*********************************************************
+ * Optimized distance/norm/inner prod computations
+ *********************************************************/
+
+/// Squared L2 distance between two vectors
+float fvec_L2sqr(const float* x, const float* y, size_t d);
+
+/// inner product
+float fvec_inner_product(const float* x, const float* y, size_t d);
+
+/// L1 distance
+float fvec_L1(const float* x, const float* y, size_t d);
+
+/// infinity distance
+float fvec_Linf(const float* x, const float* y, size_t d);
+
+/// Special version of inner product that computes 4 distances
+/// between x and yi, which is performance oriented.
+void fvec_inner_product_batch_4(
+ const float* x,
+ const float* y0,
+ const float* y1,
+ const float* y2,
+ const float* y3,
+ const size_t d,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3);
+
+/// Special version of L2sqr that computes 4 distances
+/// between x and yi, which is performance oriented.
+void fvec_L2sqr_batch_4(
+ const float* x,
+ const float* y0,
+ const float* y1,
+ const float* y2,
+ const float* y3,
+ const size_t d,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3);
+
+/** Compute pairwise distances between sets of vectors
+ *
+ * @param d dimension of the vectors
+ * @param nq nb of query vectors
+ * @param nb nb of database vectors
+ * @param xq query vectors (size nq * d)
+ * @param xb database vectors (size nb * d)
+ * @param dis output distances (size nq * nb)
+ * @param ldq,ldb, ldd strides for the matrices
+ */
+void pairwise_L2sqr(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis,
+ int64_t ldq = -1,
+ int64_t ldb = -1,
+ int64_t ldd = -1);
+
+/* compute the inner product between nx vectors x and one y */
+void fvec_inner_products_ny(
+ float* ip, /* output inner product */
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny);
+
+/* compute ny square L2 distance between x and a set of contiguous y vectors */
+void fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny);
+
+/* compute ny square L2 distance between x and a set of transposed contiguous
+ y vectors. squared lengths of y should be provided as well */
+void fvec_L2sqr_ny_transposed(
+ float* dis,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny);
+
+/* compute ny square L2 distance between x and a set of contiguous y vectors
+ and return the index of the nearest vector.
+ return 0 if ny == 0. */
+size_t fvec_L2sqr_ny_nearest(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny);
+
+/* compute ny square L2 distance between x and a set of transposed contiguous
+ y vectors and return the index of the nearest vector.
+ squared lengths of y should be provided as well
+ return 0 if ny == 0. */
+size_t fvec_L2sqr_ny_nearest_y_transposed(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny);
+
+/** squared norm of a vector */
+float fvec_norm_L2sqr(const float* x, size_t d);
+
+/** compute the L2 norms for a set of vectors
+ *
+ * @param norms output norms, size nx
+ * @param x set of vectors, size nx * d
+ */
+void fvec_norms_L2(float* norms, const float* x, size_t d, size_t nx);
+
+/// same as fvec_norms_L2, but computes squared norms
+void fvec_norms_L2sqr(float* norms, const float* x, size_t d, size_t nx);
+
+/* L2-renormalize a set of vector. Nothing done if the vector is 0-normed */
+void fvec_renorm_L2(size_t d, size_t nx, float* x);
+
+/* This function exists because the Torch counterpart is extremely slow
+ (not multi-threaded + unexpected overhead even in single thread).
+ It is here to implement the usual property |x-y|^2=|x|^2+|y|^2-2<x|y> */
+void inner_product_to_L2sqr(
+ float* dis,
+ const float* nr1,
+ const float* nr2,
+ size_t n1,
+ size_t n2);
+
+/*********************************************************
+ * Vector to vector functions
+ *********************************************************/
+
+/** compute c := a + b for vectors
+ *
+ * c and a can overlap, c and b can overlap
+ *
+ * @param a size d
+ * @param b size d
+ * @param c size d
+ */
+void fvec_add(size_t d, const float* a, const float* b, float* c);
+
+/** compute c := a + b for a, c vectors and b a scalar
+ *
+ * c and a can overlap
+ *
+ * @param a size d
+ * @param c size d
+ */
+void fvec_add(size_t d, const float* a, float b, float* c);
+
+/** compute c := a - b for vectors
+ *
+ * c and a can overlap, c and b can overlap
+ *
+ * @param a size d
+ * @param b size d
+ * @param c size d
+ */
+void fvec_sub(size_t d, const float* a, const float* b, float* c);
+
+/***************************************************************************
+ * Compute a subset of distances
+ ***************************************************************************/
+
+/** compute the inner product between x and a subset y of ny vectors defined by
+ * ids
+ *
+ * ip(i, j) = inner_product(x(i, :), y(ids(i, j), :))
+ *
+ * @param ip output array, size nx * ny
+ * @param x first-term vector, size nx * d
+ * @param y second-term vector, size (max(ids) + 1) * d
+ * @param ids ids to sample from y, size nx * ny
+ */
+void fvec_inner_products_by_idx(
+ float* ip,
+ const float* x,
+ const float* y,
+ const int64_t* ids,
+ size_t d,
+ size_t nx,
+ size_t ny);
+
+/** compute the squared L2 distances between x and a subset y of ny vectors
+ * defined by ids
+ *
+ * dis(i, j) = inner_product(x(i, :), y(ids(i, j), :))
+ *
+ * @param dis output array, size nx * ny
+ * @param x first-term vector, size nx * d
+ * @param y second-term vector, size (max(ids) + 1) * d
+ * @param ids ids to sample from y, size nx * ny
+ */
+void fvec_L2sqr_by_idx(
+ float* dis,
+ const float* x,
+ const float* y,
+ const int64_t* ids, /* ids of y vecs */
+ size_t d,
+ size_t nx,
+ size_t ny);
+
+/** compute dis[j] = L2sqr(x[ix[j]], y[iy[j]]) forall j=0..n-1
+ *
+ * @param x size (max(ix) + 1, d)
+ * @param y size (max(iy) + 1, d)
+ * @param ix size n
+ * @param iy size n
+ * @param dis size n
+ */
+void pairwise_indexed_L2sqr(
+ size_t d,
+ size_t n,
+ const float* x,
+ const int64_t* ix,
+ const float* y,
+ const int64_t* iy,
+ float* dis);
+
+/** compute dis[j] = inner_product(x[ix[j]], y[iy[j]]) forall j=0..n-1
+ *
+ * @param x size (max(ix) + 1, d)
+ * @param y size (max(iy) + 1, d)
+ * @param ix size n
+ * @param iy size n
+ * @param dis size n
+ */
+void pairwise_indexed_inner_product(
+ size_t d,
+ size_t n,
+ const float* x,
+ const int64_t* ix,
+ const float* y,
+ const int64_t* iy,
+ float* dis);
+
+/***************************************************************************
+ * KNN functions
+ ***************************************************************************/
+
+// threshold on nx above which we switch to BLAS to compute distances
+FAISS_API extern int distance_compute_blas_threshold;
+
+// block sizes for BLAS distance computations
+FAISS_API extern int distance_compute_blas_query_bs;
+FAISS_API extern int distance_compute_blas_database_bs;
+
+// above this number of results we switch to a reservoir to collect results
+// rather than a heap
+FAISS_API extern int distance_compute_min_k_reservoir;
+
+/** Return the k nearest neighbors of each of the nx vectors x among the ny
+ * vector y, w.r.t to max inner product.
+ *
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size ny * d
+ * @param res result heap structure, which also provides k. Sorted on output
+ */
+void knn_inner_product(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float_minheap_array_t* res,
+ const IDSelector* sel = nullptr);
+
+/** Return the k nearest neighbors of each of the nx vectors x among the ny
+ * vector y, for the inner product metric.
+ *
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size ny * d
+ * @param distances output distances, size nq * k
+ * @param indexes output vector ids, size nq * k
+ */
+void knn_inner_product(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t k,
+ float* distances,
+ int64_t* indexes,
+ const IDSelector* sel = nullptr);
+
+/** Return the k nearest neighbors of each of the nx vectors x among the ny
+ * vector y, for the L2 distance
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size ny * d
+ * @param res result heap strcture, which also provides k. Sorted on output
+ * @param y_norm2 (optional) norms for the y vectors (nullptr or size ny)
+ * @param sel search in this subset of vectors
+ */
+void knn_L2sqr(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float_maxheap_array_t* res,
+ const float* y_norm2 = nullptr,
+ const IDSelector* sel = nullptr);
+
+/** Return the k nearest neighbors of each of the nx vectors x among the ny
+ * vector y, for the L2 distance
+ *
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size ny * d
+ * @param distances output distances, size nq * k
+ * @param indexes output vector ids, size nq * k
+ * @param y_norm2 (optional) norms for the y vectors (nullptr or size ny)
+ * @param sel search in this subset of vectors
+ */
+void knn_L2sqr(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t k,
+ float* distances,
+ int64_t* indexes,
+ const float* y_norm2 = nullptr,
+ const IDSelector* sel = nullptr);
+
+/** Find the max inner product neighbors for nx queries in a set of ny vectors
+ * indexed by ids. May be useful for re-ranking a pre-selected vector list
+ *
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size (max(ids) + 1) * d
+ * @param ids subset of database vectors to consider, size (nx, nsubset)
+ * @param res result structure
+ * @param ld_ids stride for the ids array. -1: use nsubset, 0: all queries
+ * process the same subset
+ */
+void knn_inner_products_by_idx(
+ const float* x,
+ const float* y,
+ const int64_t* subset,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t nsubset,
+ size_t k,
+ float* vals,
+ int64_t* ids,
+ int64_t ld_ids = -1);
+
+/** Find the nearest neighbors for nx queries in a set of ny vectors
+ * indexed by ids. May be useful for re-ranking a pre-selected vector list
+ *
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size (max(ids) + 1) * d
+ * @param subset subset of database vectors to consider, size (nx, nsubset)
+ * @param res rIDesult structure
+ * @param ld_subset stride for the subset array. -1: use nsubset, 0: all queries
+ * process the same subset
+ */
+void knn_L2sqr_by_idx(
+ const float* x,
+ const float* y,
+ const int64_t* subset,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ size_t nsubset,
+ size_t k,
+ float* vals,
+ int64_t* ids,
+ int64_t ld_subset = -1);
+
+/***************************************************************************
+ * Range search
+ ***************************************************************************/
+
+/// Forward declaration, see AuxIndexStructures.h
+struct RangeSearchResult;
+
+/** Return the k nearest neighbors of each of the nx vectors x among the ny
+ * vector y, w.r.t to max inner product
+ *
+ * @param x query vectors, size nx * d
+ * @param y database vectors, size ny * d
+ * @param radius search radius around the x vectors
+ * @param result result structure
+ */
+void range_search_L2sqr(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float radius,
+ RangeSearchResult* result,
+ const IDSelector* sel = nullptr);
+
+/// same as range_search_L2sqr for the inner product similarity
+void range_search_inner_product(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ float radius,
+ RangeSearchResult* result,
+ const IDSelector* sel = nullptr);
+
+/***************************************************************************
+ * PQ tables computations
+ ***************************************************************************/
+
+/// specialized function for PQ2
+void compute_PQ_dis_tables_dsub2(
+ size_t d,
+ size_t ksub,
+ const float* centroids,
+ size_t nx,
+ const float* x,
+ bool is_inner_product,
+ float* dis_tables);
+
+/***************************************************************************
+ * Templatized versions of distance functions
+ ***************************************************************************/
+
+/***************************************************************************
+ * Misc matrix and vector manipulation functions
+ ***************************************************************************/
+
+/** compute c := a + bf * b for a, b and c tables
+ *
+ * @param n size of the tables
+ * @param a size n
+ * @param b size n
+ * @param c result table, size n
+ */
+void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c);
+
+/** same as fvec_madd, also return index of the min of the result table
+ * @return index of the min of table c
+ */
+int fvec_madd_and_argmin(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/avx512.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/avx512.cpp
new file mode 100644
index 0000000..be792b9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/avx512.cpp
@@ -0,0 +1,346 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/utils/distances_fused/avx512.h>
+
+#ifdef __AVX512F__
+
+#include <immintrin.h>
+
+namespace faiss {
+
+namespace {
+
+// It makes sense to like to overload certain cases because the further
+// kernels are in need of AVX512 registers. So, let's tell compiler
+// not to waste registers on a bit faster code, if needed.
+template <size_t DIM>
+float l2_sqr(const float* const x) {
+ // compiler should be smart enough to handle that
+ float output = x[0] * x[0];
+ for (size_t i = 1; i < DIM; i++) {
+ output += x[i] * x[i];
+ }
+
+ return output;
+}
+
+template <>
+float l2_sqr<4>(const float* const x) {
+ __m128 v = _mm_loadu_ps(x);
+ __m128 v2 = _mm_mul_ps(v, v);
+ v2 = _mm_hadd_ps(v2, v2);
+ v2 = _mm_hadd_ps(v2, v2);
+
+ return _mm_cvtss_f32(v2);
+}
+
+template <size_t DIM>
+float dot_product(
+ const float* const __restrict x,
+ const float* const __restrict y) {
+ // compiler should be smart enough to handle that
+ float output = x[0] * y[0];
+ for (size_t i = 1; i < DIM; i++) {
+ output += x[i] * y[i];
+ }
+
+ return output;
+}
+
+// The kernel for low dimensionality vectors.
+// Finds the closest one from y for every given NX_POINTS_PER_LOOP points from x
+//
+// DIM is the dimensionality of the data
+// NX_POINTS_PER_LOOP is the number of x points that get processed
+// simultaneously.
+// NY_POINTS_PER_LOOP is the number of y points that get processed
+// simultaneously.
+template <size_t DIM, size_t NX_POINTS_PER_LOOP, size_t NY_POINTS_PER_LOOP>
+void kernel(
+ const float* const __restrict x,
+ const float* const __restrict y,
+ const float* const __restrict y_transposed,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* __restrict y_norms,
+ size_t i) {
+ const size_t ny_p =
+ (ny / (16 * NY_POINTS_PER_LOOP)) * (16 * NY_POINTS_PER_LOOP);
+
+ // compute
+ const float* const __restrict xd_0 = x + i * DIM;
+
+ // prefetch the next point
+ _mm_prefetch(xd_0 + DIM * sizeof(float), _MM_HINT_NTA);
+
+ // load a single point from x
+ // load -2 * value
+ __m512 x_i[NX_POINTS_PER_LOOP][DIM];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ for (size_t dd = 0; dd < DIM; dd++) {
+ x_i[nx_k][dd] = _mm512_set1_ps(-2 * *(xd_0 + nx_k * DIM + dd));
+ }
+ }
+
+ // compute x_norm
+ float x_norm_i[NX_POINTS_PER_LOOP];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ x_norm_i[nx_k] = l2_sqr<DIM>(xd_0 + nx_k * DIM);
+ }
+
+ // distances and indices
+ __m512 min_distances_i[NX_POINTS_PER_LOOP];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ min_distances_i[nx_k] =
+ _mm512_set1_ps(res.dis_tab[i + nx_k] - x_norm_i[nx_k]);
+ }
+
+ __m512i min_indices_i[NX_POINTS_PER_LOOP];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ min_indices_i[nx_k] = _mm512_set1_epi32(0);
+ }
+
+ //
+ __m512i current_indices = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ const __m512i indices_delta = _mm512_set1_epi32(16);
+
+ // main loop
+ size_t j = 0;
+ for (; j < ny_p; j += NY_POINTS_PER_LOOP * 16) {
+ // compute dot products for NX_POINTS from x and NY_POINTS from y
+ // technically, we're multiplying -2x and y
+ __m512 dp_i[NX_POINTS_PER_LOOP][NY_POINTS_PER_LOOP];
+
+ // DIM 0 that uses MUL
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ __m512 y_i = _mm512_loadu_ps(y_transposed + j + ny_k * 16 + ny * 0);
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ dp_i[nx_k][ny_k] = _mm512_mul_ps(x_i[nx_k][0], y_i);
+ }
+ }
+
+ // other DIMs that use FMA
+ for (size_t dd = 1; dd < DIM; dd++) {
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ __m512 y_i =
+ _mm512_loadu_ps(y_transposed + j + ny_k * 16 + ny * dd);
+
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ dp_i[nx_k][ny_k] = _mm512_fmadd_ps(
+ x_i[nx_k][dd], y_i, dp_i[nx_k][ny_k]);
+ }
+ }
+ }
+
+ // compute y^2 - 2 * (x,y)
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ __m512 y_l2_sqr = _mm512_loadu_ps(y_norms + j + ny_k * 16);
+
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ dp_i[nx_k][ny_k] = _mm512_add_ps(dp_i[nx_k][ny_k], y_l2_sqr);
+ }
+ }
+
+ // do the comparisons and alter the min indices
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ const __mmask16 comparison = _mm512_cmp_ps_mask(
+ dp_i[nx_k][ny_k], min_distances_i[nx_k], _CMP_LT_OS);
+ min_distances_i[nx_k] = _mm512_mask_blend_ps(
+ comparison, min_distances_i[nx_k], dp_i[nx_k][ny_k]);
+ min_indices_i[nx_k] = _mm512_castps_si512(_mm512_mask_blend_ps(
+ comparison,
+ _mm512_castsi512_ps(min_indices_i[nx_k]),
+ _mm512_castsi512_ps(current_indices)));
+ }
+
+ current_indices = _mm512_add_epi32(current_indices, indices_delta);
+ }
+ }
+
+ // dump values and find the minimum distance / minimum index
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ float min_distances_scalar[16];
+ uint32_t min_indices_scalar[16];
+ _mm512_storeu_ps(min_distances_scalar, min_distances_i[nx_k]);
+ _mm512_storeu_si512(
+ (__m512i*)(min_indices_scalar), min_indices_i[nx_k]);
+
+ float current_min_distance = res.dis_tab[i + nx_k];
+ uint32_t current_min_index = res.ids_tab[i + nx_k];
+
+ // This unusual comparison is needed to maintain the behavior
+ // of the original implementation: if two indices are
+ // represented with equal distance values, then
+ // the index with the min value is returned.
+ for (size_t jv = 0; jv < 16; jv++) {
+ // add missing x_norms[i]
+ float distance_candidate =
+ min_distances_scalar[jv] + x_norm_i[nx_k];
+
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ if (distance_candidate < 0)
+ distance_candidate = 0;
+
+ const int64_t index_candidate = min_indices_scalar[jv];
+
+ if (current_min_distance > distance_candidate) {
+ current_min_distance = distance_candidate;
+ current_min_index = index_candidate;
+ } else if (
+ current_min_distance == distance_candidate &&
+ current_min_index > index_candidate) {
+ current_min_index = index_candidate;
+ }
+ }
+
+ // process leftovers
+ for (size_t j0 = j; j0 < ny; j0++) {
+ const float dp =
+ dot_product<DIM>(x + (i + nx_k) * DIM, y + j0 * DIM);
+ float dis = x_norm_i[nx_k] + y_norms[j0] - 2 * dp;
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ if (dis < 0) {
+ dis = 0;
+ }
+
+ if (current_min_distance > dis) {
+ current_min_distance = dis;
+ current_min_index = j0;
+ }
+ }
+
+ // done
+ res.add_result(i + nx_k, current_min_distance, current_min_index);
+ }
+}
+
+template <size_t DIM, size_t NX_POINTS_PER_LOOP, size_t NY_POINTS_PER_LOOP>
+void exhaustive_L2sqr_fused_cmax(
+ const float* const __restrict x,
+ const float* const __restrict y,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* __restrict y_norms) {
+ // BLAS does not like empty matrices
+ if (nx == 0 || ny == 0) {
+ return;
+ }
+
+ // compute norms for y
+ std::unique_ptr<float[]> del2;
+ if (!y_norms) {
+ float* y_norms2 = new float[ny];
+ del2.reset(y_norms2);
+
+ for (size_t i = 0; i < ny; i++) {
+ y_norms2[i] = l2_sqr<DIM>(y + i * DIM);
+ }
+
+ y_norms = y_norms2;
+ }
+
+ // initialize res
+ res.begin_multiple(0, nx);
+
+ // transpose y
+ std::vector<float> y_transposed(DIM * ny);
+ for (size_t j = 0; j < DIM; j++) {
+ for (size_t i = 0; i < ny; i++) {
+ y_transposed[j * ny + i] = y[j + i * DIM];
+ }
+ }
+
+ const size_t nx_p = (nx / NX_POINTS_PER_LOOP) * NX_POINTS_PER_LOOP;
+ // the main loop.
+#pragma omp parallel for schedule(dynamic)
+ for (size_t i = 0; i < nx_p; i += NX_POINTS_PER_LOOP) {
+ kernel<DIM, NX_POINTS_PER_LOOP, NY_POINTS_PER_LOOP>(
+ x, y, y_transposed.data(), ny, res, y_norms, i);
+ }
+
+ for (size_t i = nx_p; i < nx; i++) {
+ kernel<DIM, 1, NY_POINTS_PER_LOOP>(
+ x, y, y_transposed.data(), ny, res, y_norms, i);
+ }
+
+ // Does nothing for Top1BlockResultHandler, but
+ // keeping the call for the consistency.
+ res.end_multiple();
+ InterruptCallback::check();
+}
+
+} // namespace
+
+bool exhaustive_L2sqr_fused_cmax_AVX512(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms) {
+ // process only cases with certain dimensionalities
+
+#define DISPATCH(DIM, NX_POINTS_PER_LOOP, NY_POINTS_PER_LOOP) \
+ case DIM: { \
+ exhaustive_L2sqr_fused_cmax< \
+ DIM, \
+ NX_POINTS_PER_LOOP, \
+ NY_POINTS_PER_LOOP>(x, y, nx, ny, res, y_norms); \
+ return true; \
+ }
+
+ switch (d) {
+ DISPATCH(1, 8, 1)
+ DISPATCH(2, 8, 1)
+ DISPATCH(3, 8, 1)
+ DISPATCH(4, 8, 1)
+ DISPATCH(5, 8, 1)
+ DISPATCH(6, 8, 1)
+ DISPATCH(7, 8, 1)
+ DISPATCH(8, 8, 1)
+ DISPATCH(9, 8, 1)
+ DISPATCH(10, 8, 1)
+ DISPATCH(11, 8, 1)
+ DISPATCH(12, 8, 1)
+ DISPATCH(13, 8, 1)
+ DISPATCH(14, 8, 1)
+ DISPATCH(15, 8, 1)
+ DISPATCH(16, 8, 1)
+ DISPATCH(17, 8, 1)
+ DISPATCH(18, 8, 1)
+ DISPATCH(19, 8, 1)
+ DISPATCH(20, 8, 1)
+ DISPATCH(21, 8, 1)
+ DISPATCH(22, 8, 1)
+ DISPATCH(23, 8, 1)
+ DISPATCH(24, 8, 1)
+ DISPATCH(25, 8, 1)
+ DISPATCH(26, 8, 1)
+ DISPATCH(27, 8, 1)
+ DISPATCH(28, 8, 1)
+ DISPATCH(29, 8, 1)
+ DISPATCH(30, 8, 1)
+ DISPATCH(31, 8, 1)
+ DISPATCH(32, 8, 1)
+ }
+
+ return false;
+#undef DISPATCH
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/avx512.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/avx512.h
new file mode 100644
index 0000000..92d42c1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/avx512.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// AVX512 might be not used, but this version provides ~2x speedup
+// over AVX2 kernel, say, for training PQx10 or PQx12, and speeds up
+// additional cases with larger dimensionalities.
+
+#pragma once
+
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/impl/platform_macros.h>
+
+#include <faiss/utils/Heap.h>
+
+#ifdef __AVX512F__
+
+namespace faiss {
+
+// Returns true if the fused kernel is available and the data was processed.
+// Returns false if the fused kernel is not available.
+bool exhaustive_L2sqr_fused_cmax_AVX512(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms);
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/distances_fused.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/distances_fused.cpp
new file mode 100644
index 0000000..96d4690
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/distances_fused.cpp
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/utils/distances_fused/distances_fused.h>
+
+#include <faiss/impl/platform_macros.h>
+
+#include <faiss/utils/distances_fused/avx512.h>
+#include <faiss/utils/distances_fused/simdlib_based.h>
+
+namespace faiss {
+
+bool exhaustive_L2sqr_fused_cmax(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms) {
+ if (nx == 0 || ny == 0) {
+ // nothing to do
+ return true;
+ }
+
+#ifdef __AVX512F__
+ // avx512 kernel
+ return exhaustive_L2sqr_fused_cmax_AVX512(x, y, d, nx, ny, res, y_norms);
+#elif defined(__AVX2__) || defined(__aarch64__)
+ // avx2 or arm neon kernel
+ return exhaustive_L2sqr_fused_cmax_simdlib(x, y, d, nx, ny, res, y_norms);
+#else
+ // not supported, please use a general-purpose kernel
+ return false;
+#endif
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/distances_fused.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/distances_fused.h
new file mode 100644
index 0000000..dcfdbfa
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/distances_fused.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// This file contains a fused kernel that combines distance computation
+// and the search for the CLOSEST point. Currently, this is done for small
+// dimensionality vectors when it is beneficial to avoid storing temporary
+// dot product information in RAM. This is particularly effective
+// when training PQx10 or PQx12 with the default parameters.
+//
+// InterruptCallback::check() is not used, because it is assumed that the
+// kernel takes a little time because of a tiny dimensionality.
+//
+// Later on, similar optimization can be implemented for large size vectors,
+// but a different kernel is needed.
+//
+
+#pragma once
+
+#include <faiss/impl/ResultHandler.h>
+
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+// Returns true if the fused kernel is available and the data was processed.
+// Returns false if the fused kernel is not available.
+bool exhaustive_L2sqr_fused_cmax(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/simdlib_based.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/simdlib_based.cpp
new file mode 100644
index 0000000..146dfe8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/simdlib_based.cpp
@@ -0,0 +1,352 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/utils/distances_fused/simdlib_based.h>
+
+#if defined(__AVX2__) || defined(__aarch64__)
+
+#include <faiss/utils/simdlib.h>
+
+#if defined(__AVX2__)
+#include <immintrin.h>
+#endif
+
+namespace faiss {
+
+namespace {
+
+// It makes sense to like to overload certain cases because the further
+// kernels are in need of registers. So, let's tell compiler
+// not to waste registers on a bit faster code, if needed.
+template <size_t DIM>
+float l2_sqr(const float* const x) {
+ // compiler should be smart enough to handle that
+ float output = x[0] * x[0];
+ for (size_t i = 1; i < DIM; i++) {
+ output += x[i] * x[i];
+ }
+
+ return output;
+}
+
+template <size_t DIM>
+float dot_product(
+ const float* const __restrict x,
+ const float* const __restrict y) {
+ // compiler should be smart enough to handle that
+ float output = x[0] * y[0];
+ for (size_t i = 1; i < DIM; i++) {
+ output += x[i] * y[i];
+ }
+
+ return output;
+}
+
+// The kernel for low dimensionality vectors.
+// Finds the closest one from y for every given NX_POINTS_PER_LOOP points from x
+//
+// DIM is the dimensionality of the data
+// NX_POINTS_PER_LOOP is the number of x points that get processed
+// simultaneously.
+// NY_POINTS_PER_LOOP is the number of y points that get processed
+// simultaneously.
+template <size_t DIM, size_t NX_POINTS_PER_LOOP, size_t NY_POINTS_PER_LOOP>
+void kernel(
+ const float* const __restrict x,
+ const float* const __restrict y,
+ const float* const __restrict y_transposed,
+ const size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* __restrict y_norms,
+ const size_t i) {
+ const size_t ny_p =
+ (ny / (8 * NY_POINTS_PER_LOOP)) * (8 * NY_POINTS_PER_LOOP);
+
+ // compute
+ const float* const __restrict xd_0 = x + i * DIM;
+
+ // prefetch the next point
+#if defined(__AVX2__)
+ _mm_prefetch((const char*)(xd_0 + DIM * sizeof(float)), _MM_HINT_NTA);
+#endif
+
+ // load a single point from x
+ // load -2 * value
+ simd8float32 x_i[NX_POINTS_PER_LOOP][DIM];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ for (size_t dd = 0; dd < DIM; dd++) {
+ x_i[nx_k][dd] = simd8float32(-2 * *(xd_0 + nx_k * DIM + dd));
+ }
+ }
+
+ // compute x_norm
+ float x_norm_i[NX_POINTS_PER_LOOP];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ x_norm_i[nx_k] = l2_sqr<DIM>(xd_0 + nx_k * DIM);
+ }
+
+ // distances and indices
+ simd8float32 min_distances_i[NX_POINTS_PER_LOOP];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ min_distances_i[nx_k] =
+ simd8float32(res.dis_tab[i + nx_k] - x_norm_i[nx_k]);
+ }
+
+ simd8uint32 min_indices_i[NX_POINTS_PER_LOOP];
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ min_indices_i[nx_k] = simd8uint32((uint32_t)0);
+ }
+
+ //
+ simd8uint32 current_indices = simd8uint32(0, 1, 2, 3, 4, 5, 6, 7);
+ const simd8uint32 indices_delta = simd8uint32(8);
+
+ // main loop
+ size_t j = 0;
+ for (; j < ny_p; j += NY_POINTS_PER_LOOP * 8) {
+ // compute dot products for NX_POINTS from x and NY_POINTS from y
+ // technically, we're multiplying -2x and y
+ simd8float32 dp_i[NX_POINTS_PER_LOOP][NY_POINTS_PER_LOOP];
+
+ // DIM 0 that uses MUL
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ simd8float32 y_i =
+ simd8float32(y_transposed + j + ny_k * 8 + ny * 0);
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ dp_i[nx_k][ny_k] = x_i[nx_k][0] * y_i;
+ }
+ }
+
+ // other DIMs that use FMA
+ for (size_t dd = 1; dd < DIM; dd++) {
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ simd8float32 y_i =
+ simd8float32(y_transposed + j + ny_k * 8 + ny * dd);
+
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ dp_i[nx_k][ny_k] =
+ fmadd(x_i[nx_k][dd], y_i, dp_i[nx_k][ny_k]);
+ }
+ }
+ }
+
+ // compute y^2 + (-2x,y)
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ simd8float32 y_l2_sqr = simd8float32(y_norms + j + ny_k * 8);
+
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ dp_i[nx_k][ny_k] = dp_i[nx_k][ny_k] + y_l2_sqr;
+ }
+ }
+
+ // do the comparisons and alter the min indices
+ for (size_t ny_k = 0; ny_k < NY_POINTS_PER_LOOP; ny_k++) {
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ // cmpps
+ cmplt_and_blend_inplace(
+ dp_i[nx_k][ny_k],
+ current_indices,
+ min_distances_i[nx_k],
+ min_indices_i[nx_k]);
+ }
+
+ current_indices = current_indices + indices_delta;
+ }
+ }
+
+ // dump values and find the minimum distance / minimum index
+ for (size_t nx_k = 0; nx_k < NX_POINTS_PER_LOOP; nx_k++) {
+ float min_distances_scalar[8];
+ uint32_t min_indices_scalar[8];
+
+ min_distances_i[nx_k].storeu(min_distances_scalar);
+ min_indices_i[nx_k].storeu(min_indices_scalar);
+
+ float current_min_distance = res.dis_tab[i + nx_k];
+ uint32_t current_min_index = res.ids_tab[i + nx_k];
+
+ // This unusual comparison is needed to maintain the behavior
+ // of the original implementation: if two indices are
+ // represented with equal distance values, then
+ // the index with the min value is returned.
+ for (size_t jv = 0; jv < 8; jv++) {
+ // add missing x_norms[i]
+ float distance_candidate =
+ min_distances_scalar[jv] + x_norm_i[nx_k];
+
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ if (distance_candidate < 0) {
+ distance_candidate = 0;
+ }
+
+ const int64_t index_candidate = min_indices_scalar[jv];
+
+ if (current_min_distance > distance_candidate) {
+ current_min_distance = distance_candidate;
+ current_min_index = index_candidate;
+ } else if (
+ current_min_distance == distance_candidate &&
+ current_min_index > index_candidate) {
+ current_min_index = index_candidate;
+ }
+ }
+
+ // process leftovers
+ for (size_t j0 = j; j0 < ny; j0++) {
+ const float dp =
+ dot_product<DIM>(x + (i + nx_k) * DIM, y + j0 * DIM);
+ float dis = x_norm_i[nx_k] + y_norms[j0] - 2 * dp;
+ // negative values can occur for identical vectors
+ // due to roundoff errors.
+ if (dis < 0) {
+ dis = 0;
+ }
+
+ if (current_min_distance > dis) {
+ current_min_distance = dis;
+ current_min_index = j0;
+ }
+ }
+
+ // done
+ res.add_result(i + nx_k, current_min_distance, current_min_index);
+ }
+}
+
+template <size_t DIM, size_t NX_POINTS_PER_LOOP, size_t NY_POINTS_PER_LOOP>
+void exhaustive_L2sqr_fused_cmax(
+ const float* const __restrict x,
+ const float* const __restrict y,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* __restrict y_norms) {
+ // BLAS does not like empty matrices
+ if (nx == 0 || ny == 0) {
+ return;
+ }
+
+ // compute norms for y
+ std::unique_ptr<float[]> del2;
+ if (!y_norms) {
+ float* y_norms2 = new float[ny];
+ del2.reset(y_norms2);
+
+ for (size_t i = 0; i < ny; i++) {
+ y_norms2[i] = l2_sqr<DIM>(y + i * DIM);
+ }
+
+ y_norms = y_norms2;
+ }
+
+ // initialize res
+ res.begin_multiple(0, nx);
+
+ // transpose y
+ std::vector<float> y_transposed(DIM * ny);
+ for (size_t j = 0; j < DIM; j++) {
+ for (size_t i = 0; i < ny; i++) {
+ y_transposed[j * ny + i] = y[j + i * DIM];
+ }
+ }
+
+ const size_t nx_p = (nx / NX_POINTS_PER_LOOP) * NX_POINTS_PER_LOOP;
+ // the main loop.
+#pragma omp parallel for schedule(dynamic)
+ for (size_t i = 0; i < nx_p; i += NX_POINTS_PER_LOOP) {
+ kernel<DIM, NX_POINTS_PER_LOOP, NY_POINTS_PER_LOOP>(
+ x, y, y_transposed.data(), ny, res, y_norms, i);
+ }
+
+ for (size_t i = nx_p; i < nx; i++) {
+ kernel<DIM, 1, NY_POINTS_PER_LOOP>(
+ x, y, y_transposed.data(), ny, res, y_norms, i);
+ }
+
+ // Does nothing for Top1BlockResultHandler, but
+ // keeping the call for the consistency.
+ res.end_multiple();
+ InterruptCallback::check();
+}
+
+} // namespace
+
+bool exhaustive_L2sqr_fused_cmax_simdlib(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms) {
+ // Process only cases with certain dimensionalities.
+ // An acceptable dimensionality value is limited by the number of
+ // available registers.
+
+#define DISPATCH(DIM, NX_POINTS_PER_LOOP, NY_POINTS_PER_LOOP) \
+ case DIM: { \
+ exhaustive_L2sqr_fused_cmax< \
+ DIM, \
+ NX_POINTS_PER_LOOP, \
+ NY_POINTS_PER_LOOP>(x, y, nx, ny, res, y_norms); \
+ return true; \
+ }
+
+ // faiss/benchs/bench_quantizer.py was used for benchmarking
+ // and tuning 2nd and 3rd parameters values.
+ // Basically, the larger the values for 2nd and 3rd parameters are,
+ // the faster the execution is, but the more SIMD registers are needed.
+ // This can be compensated with L1 cache, this is why this
+ // code might operate with more registers than available
+ // because of concurrent ports operations for ALU and LOAD/STORE.
+
+#if defined(__AVX2__)
+ // It was possible to tweak these parameters on x64 machine.
+ switch (d) {
+ DISPATCH(1, 6, 1)
+ DISPATCH(2, 6, 1)
+ DISPATCH(3, 6, 1)
+ DISPATCH(4, 8, 1)
+ DISPATCH(5, 8, 1)
+ DISPATCH(6, 8, 1)
+ DISPATCH(7, 8, 1)
+ DISPATCH(8, 8, 1)
+ DISPATCH(9, 8, 1)
+ DISPATCH(10, 8, 1)
+ DISPATCH(11, 8, 1)
+ DISPATCH(12, 8, 1)
+ DISPATCH(13, 6, 1)
+ DISPATCH(14, 6, 1)
+ DISPATCH(15, 6, 1)
+ DISPATCH(16, 6, 1)
+ }
+#else
+ // Please feel free to alter 2nd and 3rd parameters if you have access
+ // to ARM-based machine so that you are able to benchmark this code.
+ // Or to enable other dimensions.
+ switch (d) {
+ DISPATCH(1, 4, 2)
+ DISPATCH(2, 2, 2)
+ DISPATCH(3, 2, 2)
+ DISPATCH(4, 2, 1)
+ DISPATCH(5, 1, 1)
+ DISPATCH(6, 1, 1)
+ DISPATCH(7, 1, 1)
+ DISPATCH(8, 1, 1)
+ }
+#endif
+
+ return false;
+#undef DISPATCH
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/simdlib_based.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/simdlib_based.h
new file mode 100644
index 0000000..dac5163
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_fused/simdlib_based.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/impl/platform_macros.h>
+
+#include <faiss/utils/Heap.h>
+
+#if defined(__AVX2__) || defined(__aarch64__)
+
+namespace faiss {
+
+// Returns true if the fused kernel is available and the data was processed.
+// Returns false if the fused kernel is not available.
+bool exhaustive_L2sqr_fused_cmax_simdlib(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ Top1BlockResultHandler<CMax<float, int64_t>>& res,
+ const float* y_norms);
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_simd.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_simd.cpp
new file mode 100644
index 0000000..1990e46
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/distances_simd.cpp
@@ -0,0 +1,3779 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/utils/distances.h>
+
+#include <algorithm>
+#include <cassert>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/simdlib.h>
+
+#ifdef __SSE3__
+#include <immintrin.h>
+#endif
+
+#if defined(__AVX512F__)
+#include <faiss/utils/transpose/transpose-avx512-inl.h>
+#elif defined(__AVX2__)
+#include <faiss/utils/transpose/transpose-avx2-inl.h>
+#endif
+
+#ifdef __ARM_FEATURE_SVE
+#include <arm_sve.h>
+#endif
+
+#ifdef __aarch64__
+#include <arm_neon.h>
+#endif
+
+namespace faiss {
+
+#ifdef __AVX__
+#define USE_AVX
+#endif
+
+/*********************************************************
+ * Optimized distance computations
+ *********************************************************/
+
+/* Functions to compute:
+ - L2 distance between 2 vectors
+ - inner product between 2 vectors
+ - L2 norm of a vector
+
+ The functions should probably not be invoked when a large number of
+ vectors are be processed in batch (in which case Matrix multiply
+ is faster), but may be useful for comparing vectors isolated in
+ memory.
+
+ Works with any vectors of any dimension, even unaligned (in which
+ case they are slower).
+
+*/
+
+/*********************************************************
+ * Reference implementations
+ */
+
+float fvec_L1_ref(const float* x, const float* y, size_t d) {
+ size_t i;
+ float res = 0;
+ for (i = 0; i < d; i++) {
+ const float tmp = x[i] - y[i];
+ res += fabs(tmp);
+ }
+ return res;
+}
+
+float fvec_Linf_ref(const float* x, const float* y, size_t d) {
+ size_t i;
+ float res = 0;
+ for (i = 0; i < d; i++) {
+ res = fmax(res, fabs(x[i] - y[i]));
+ }
+ return res;
+}
+
+void fvec_L2sqr_ny_ref(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ for (size_t i = 0; i < ny; i++) {
+ dis[i] = fvec_L2sqr(x, y, d);
+ y += d;
+ }
+}
+
+void fvec_L2sqr_ny_y_transposed_ref(
+ float* dis,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ float x_sqlen = 0;
+ for (size_t j = 0; j < d; j++) {
+ x_sqlen += x[j] * x[j];
+ }
+
+ for (size_t i = 0; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < d; j++) {
+ dp += x[j] * y[i + j * d_offset];
+ }
+
+ dis[i] = x_sqlen + y_sqlen[i] - 2 * dp;
+ }
+}
+
+size_t fvec_L2sqr_ny_nearest_ref(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ fvec_L2sqr_ny(distances_tmp_buffer, x, y, d, ny);
+
+ size_t nearest_idx = 0;
+ float min_dis = HUGE_VALF;
+
+ for (size_t i = 0; i < ny; i++) {
+ if (distances_tmp_buffer[i] < min_dis) {
+ min_dis = distances_tmp_buffer[i];
+ nearest_idx = i;
+ }
+ }
+
+ return nearest_idx;
+}
+
+size_t fvec_L2sqr_ny_nearest_y_transposed_ref(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ fvec_L2sqr_ny_y_transposed_ref(
+ distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny);
+
+ size_t nearest_idx = 0;
+ float min_dis = HUGE_VALF;
+
+ for (size_t i = 0; i < ny; i++) {
+ if (distances_tmp_buffer[i] < min_dis) {
+ min_dis = distances_tmp_buffer[i];
+ nearest_idx = i;
+ }
+ }
+
+ return nearest_idx;
+}
+
+void fvec_inner_products_ny_ref(
+ float* ip,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ // BLAS slower for the use cases here
+#if 0
+ {
+ FINTEGER di = d;
+ FINTEGER nyi = ny;
+ float one = 1.0, zero = 0.0;
+ FINTEGER onei = 1;
+ sgemv_ ("T", &di, &nyi, &one, y, &di, x, &onei, &zero, ip, &onei);
+ }
+#endif
+ for (size_t i = 0; i < ny; i++) {
+ ip[i] = fvec_inner_product(x, y, d);
+ y += d;
+ }
+}
+
+/*********************************************************
+ * Autovectorized implementations
+ */
+
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+float fvec_inner_product(const float* x, const float* y, size_t d) {
+ float res = 0.F;
+ FAISS_PRAGMA_IMPRECISE_LOOP
+ for (size_t i = 0; i != d; ++i) {
+ res += x[i] * y[i];
+ }
+ return res;
+}
+FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+float fvec_norm_L2sqr(const float* x, size_t d) {
+ // the double in the _ref is suspected to be a typo. Some of the manual
+ // implementations this replaces used float.
+ float res = 0;
+ FAISS_PRAGMA_IMPRECISE_LOOP
+ for (size_t i = 0; i != d; ++i) {
+ res += x[i] * x[i];
+ }
+
+ return res;
+}
+FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+float fvec_L2sqr(const float* x, const float* y, size_t d) {
+ size_t i;
+ float res = 0;
+ FAISS_PRAGMA_IMPRECISE_LOOP
+ for (i = 0; i < d; i++) {
+ const float tmp = x[i] - y[i];
+ res += tmp * tmp;
+ }
+ return res;
+}
+FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+
+/// Special version of inner product that computes 4 distances
+/// between x and yi
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+void fvec_inner_product_batch_4(
+ const float* __restrict x,
+ const float* __restrict y0,
+ const float* __restrict y1,
+ const float* __restrict y2,
+ const float* __restrict y3,
+ const size_t d,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) {
+ float d0 = 0;
+ float d1 = 0;
+ float d2 = 0;
+ float d3 = 0;
+ FAISS_PRAGMA_IMPRECISE_LOOP
+ for (size_t i = 0; i < d; ++i) {
+ d0 += x[i] * y0[i];
+ d1 += x[i] * y1[i];
+ d2 += x[i] * y2[i];
+ d3 += x[i] * y3[i];
+ }
+
+ dis0 = d0;
+ dis1 = d1;
+ dis2 = d2;
+ dis3 = d3;
+}
+FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+
+/// Special version of L2sqr that computes 4 distances
+/// between x and yi, which is performance oriented.
+FAISS_PRAGMA_IMPRECISE_FUNCTION_BEGIN
+void fvec_L2sqr_batch_4(
+ const float* x,
+ const float* y0,
+ const float* y1,
+ const float* y2,
+ const float* y3,
+ const size_t d,
+ float& dis0,
+ float& dis1,
+ float& dis2,
+ float& dis3) {
+ float d0 = 0;
+ float d1 = 0;
+ float d2 = 0;
+ float d3 = 0;
+ FAISS_PRAGMA_IMPRECISE_LOOP
+ for (size_t i = 0; i < d; ++i) {
+ const float q0 = x[i] - y0[i];
+ const float q1 = x[i] - y1[i];
+ const float q2 = x[i] - y2[i];
+ const float q3 = x[i] - y3[i];
+ d0 += q0 * q0;
+ d1 += q1 * q1;
+ d2 += q2 * q2;
+ d3 += q3 * q3;
+ }
+
+ dis0 = d0;
+ dis1 = d1;
+ dis2 = d2;
+ dis3 = d3;
+}
+FAISS_PRAGMA_IMPRECISE_FUNCTION_END
+
+/*********************************************************
+ * SSE and AVX implementations
+ */
+
+#ifdef __SSE3__
+
+// reads 0 <= d < 4 floats as __m128
+static inline __m128 masked_read(int d, const float* x) {
+ assert(0 <= d && d < 4);
+ ALIGNED(16) float buf[4] = {0, 0, 0, 0};
+ switch (d) {
+ case 3:
+ buf[2] = x[2];
+ [[fallthrough]];
+ case 2:
+ buf[1] = x[1];
+ [[fallthrough]];
+ case 1:
+ buf[0] = x[0];
+ }
+ return _mm_load_ps(buf);
+ // cannot use AVX2 _mm_mask_set1_epi32
+}
+
+namespace {
+
+/// helper function
+inline float horizontal_sum(const __m128 v) {
+ // say, v is [x0, x1, x2, x3]
+
+ // v0 is [x2, x3, ..., ...]
+ const __m128 v0 = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0, 0, 3, 2));
+ // v1 is [x0 + x2, x1 + x3, ..., ...]
+ const __m128 v1 = _mm_add_ps(v, v0);
+ // v2 is [x1 + x3, ..., .... ,...]
+ __m128 v2 = _mm_shuffle_ps(v1, v1, _MM_SHUFFLE(0, 0, 0, 1));
+ // v3 is [x0 + x1 + x2 + x3, ..., ..., ...]
+ const __m128 v3 = _mm_add_ps(v1, v2);
+ // return v3[0]
+ return _mm_cvtss_f32(v3);
+}
+
+#ifdef __AVX2__
+/// helper function for AVX2
+inline float horizontal_sum(const __m256 v) {
+ // add high and low parts
+ const __m128 v0 =
+ _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
+ // perform horizontal sum on v0
+ return horizontal_sum(v0);
+}
+#endif
+
+#ifdef __AVX512F__
+/// helper function for AVX512
+inline float horizontal_sum(const __m512 v) {
+ // performs better than adding the high and low parts
+ return _mm512_reduce_add_ps(v);
+}
+#endif
+
+/// Function that does a component-wise operation between x and y
+/// to compute L2 distances. ElementOp can then be used in the fvec_op_ny
+/// functions below
+struct ElementOpL2 {
+ static float op(float x, float y) {
+ float tmp = x - y;
+ return tmp * tmp;
+ }
+
+ static __m128 op(__m128 x, __m128 y) {
+ __m128 tmp = _mm_sub_ps(x, y);
+ return _mm_mul_ps(tmp, tmp);
+ }
+
+#ifdef __AVX2__
+ static __m256 op(__m256 x, __m256 y) {
+ __m256 tmp = _mm256_sub_ps(x, y);
+ return _mm256_mul_ps(tmp, tmp);
+ }
+#endif
+
+#ifdef __AVX512F__
+ static __m512 op(__m512 x, __m512 y) {
+ __m512 tmp = _mm512_sub_ps(x, y);
+ return _mm512_mul_ps(tmp, tmp);
+ }
+#endif
+};
+
+/// Function that does a component-wise operation between x and y
+/// to compute inner products
+struct ElementOpIP {
+ static float op(float x, float y) {
+ return x * y;
+ }
+
+ static __m128 op(__m128 x, __m128 y) {
+ return _mm_mul_ps(x, y);
+ }
+
+#ifdef __AVX2__
+ static __m256 op(__m256 x, __m256 y) {
+ return _mm256_mul_ps(x, y);
+ }
+#endif
+
+#ifdef __AVX512F__
+ static __m512 op(__m512 x, __m512 y) {
+ return _mm512_mul_ps(x, y);
+ }
+#endif
+};
+
+template <class ElementOp>
+void fvec_op_ny_D1(float* dis, const float* x, const float* y, size_t ny) {
+ float x0s = x[0];
+ __m128 x0 = _mm_set_ps(x0s, x0s, x0s, x0s);
+
+ size_t i;
+ for (i = 0; i + 3 < ny; i += 4) {
+ __m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ dis[i] = _mm_cvtss_f32(accu);
+ __m128 tmp = _mm_shuffle_ps(accu, accu, 1);
+ dis[i + 1] = _mm_cvtss_f32(tmp);
+ tmp = _mm_shuffle_ps(accu, accu, 2);
+ dis[i + 2] = _mm_cvtss_f32(tmp);
+ tmp = _mm_shuffle_ps(accu, accu, 3);
+ dis[i + 3] = _mm_cvtss_f32(tmp);
+ }
+ while (i < ny) { // handle non-multiple-of-4 case
+ dis[i++] = ElementOp::op(x0s, *y++);
+ }
+}
+
+template <class ElementOp>
+void fvec_op_ny_D2(float* dis, const float* x, const float* y, size_t ny) {
+ __m128 x0 = _mm_set_ps(x[1], x[0], x[1], x[0]);
+
+ size_t i;
+ for (i = 0; i + 1 < ny; i += 2) {
+ __m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ accu = _mm_hadd_ps(accu, accu);
+ dis[i] = _mm_cvtss_f32(accu);
+ accu = _mm_shuffle_ps(accu, accu, 3);
+ dis[i + 1] = _mm_cvtss_f32(accu);
+ }
+ if (i < ny) { // handle odd case
+ dis[i] = ElementOp::op(x[0], y[0]) + ElementOp::op(x[1], y[1]);
+ }
+}
+
+#if defined(__AVX512F__)
+
+template <>
+void fvec_op_ny_D2<ElementOpIP>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny16 = ny / 16;
+ size_t i = 0;
+
+ if (ny16 > 0) {
+ // process 16 D2-vectors per loop.
+ _mm_prefetch((const char*)y, _MM_HINT_T0);
+ _mm_prefetch((const char*)(y + 32), _MM_HINT_T0);
+
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+
+ for (i = 0; i < ny16 * 16; i += 16) {
+ _mm_prefetch((const char*)(y + 64), _MM_HINT_T0);
+
+ // load 16x2 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m512 v0;
+ __m512 v1;
+
+ transpose_16x2(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ v0,
+ v1);
+
+ // compute distances (dot product)
+ __m512 distances = _mm512_mul_ps(m0, v0);
+ distances = _mm512_fmadd_ps(m1, v1, distances);
+
+ // store
+ _mm512_storeu_ps(dis + i, distances);
+
+ y += 32; // move to the next set of 16x2 elements
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ float x0 = x[0];
+ float x1 = x[1];
+
+ for (; i < ny; i++) {
+ float distance = x0 * y[0] + x1 * y[1];
+ y += 2;
+ dis[i] = distance;
+ }
+ }
+}
+
+template <>
+void fvec_op_ny_D2<ElementOpL2>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny16 = ny / 16;
+ size_t i = 0;
+
+ if (ny16 > 0) {
+ // process 16 D2-vectors per loop.
+ _mm_prefetch((const char*)y, _MM_HINT_T0);
+ _mm_prefetch((const char*)(y + 32), _MM_HINT_T0);
+
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+
+ for (i = 0; i < ny16 * 16; i += 16) {
+ _mm_prefetch((const char*)(y + 64), _MM_HINT_T0);
+
+ // load 16x2 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m512 v0;
+ __m512 v1;
+
+ transpose_16x2(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ v0,
+ v1);
+
+ // compute differences
+ const __m512 d0 = _mm512_sub_ps(m0, v0);
+ const __m512 d1 = _mm512_sub_ps(m1, v1);
+
+ // compute squares of differences
+ __m512 distances = _mm512_mul_ps(d0, d0);
+ distances = _mm512_fmadd_ps(d1, d1, distances);
+
+ // store
+ _mm512_storeu_ps(dis + i, distances);
+
+ y += 32; // move to the next set of 16x2 elements
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ float x0 = x[0];
+ float x1 = x[1];
+
+ for (; i < ny; i++) {
+ float sub0 = x0 - y[0];
+ float sub1 = x1 - y[1];
+ float distance = sub0 * sub0 + sub1 * sub1;
+
+ y += 2;
+ dis[i] = distance;
+ }
+ }
+}
+
+#elif defined(__AVX2__)
+
+template <>
+void fvec_op_ny_D2<ElementOpIP>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny8 = ny / 8;
+ size_t i = 0;
+
+ if (ny8 > 0) {
+ // process 8 D2-vectors per loop.
+ _mm_prefetch((const char*)y, _MM_HINT_T0);
+ _mm_prefetch((const char*)(y + 16), _MM_HINT_T0);
+
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+
+ for (i = 0; i < ny8 * 8; i += 8) {
+ _mm_prefetch((const char*)(y + 32), _MM_HINT_T0);
+
+ // load 8x2 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m256 v0;
+ __m256 v1;
+
+ transpose_8x2(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ v0,
+ v1);
+
+ // compute distances
+ __m256 distances = _mm256_mul_ps(m0, v0);
+ distances = _mm256_fmadd_ps(m1, v1, distances);
+
+ // store
+ _mm256_storeu_ps(dis + i, distances);
+
+ y += 16;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ float x0 = x[0];
+ float x1 = x[1];
+
+ for (; i < ny; i++) {
+ float distance = x0 * y[0] + x1 * y[1];
+ y += 2;
+ dis[i] = distance;
+ }
+ }
+}
+
+template <>
+void fvec_op_ny_D2<ElementOpL2>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny8 = ny / 8;
+ size_t i = 0;
+
+ if (ny8 > 0) {
+ // process 8 D2-vectors per loop.
+ _mm_prefetch((const char*)y, _MM_HINT_T0);
+ _mm_prefetch((const char*)(y + 16), _MM_HINT_T0);
+
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+
+ for (i = 0; i < ny8 * 8; i += 8) {
+ _mm_prefetch((const char*)(y + 32), _MM_HINT_T0);
+
+ // load 8x2 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m256 v0;
+ __m256 v1;
+
+ transpose_8x2(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ v0,
+ v1);
+
+ // compute differences
+ const __m256 d0 = _mm256_sub_ps(m0, v0);
+ const __m256 d1 = _mm256_sub_ps(m1, v1);
+
+ // compute squares of differences
+ __m256 distances = _mm256_mul_ps(d0, d0);
+ distances = _mm256_fmadd_ps(d1, d1, distances);
+
+ // store
+ _mm256_storeu_ps(dis + i, distances);
+
+ y += 16;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ float x0 = x[0];
+ float x1 = x[1];
+
+ for (; i < ny; i++) {
+ float sub0 = x0 - y[0];
+ float sub1 = x1 - y[1];
+ float distance = sub0 * sub0 + sub1 * sub1;
+
+ y += 2;
+ dis[i] = distance;
+ }
+ }
+}
+
+#endif
+
+template <class ElementOp>
+void fvec_op_ny_D4(float* dis, const float* x, const float* y, size_t ny) {
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (size_t i = 0; i < ny; i++) {
+ __m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ dis[i] = horizontal_sum(accu);
+ }
+}
+
+#if defined(__AVX512F__)
+
+template <>
+void fvec_op_ny_D4<ElementOpIP>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny16 = ny / 16;
+ size_t i = 0;
+
+ if (ny16 > 0) {
+ // process 16 D4-vectors per loop.
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+ const __m512 m2 = _mm512_set1_ps(x[2]);
+ const __m512 m3 = _mm512_set1_ps(x[3]);
+
+ for (i = 0; i < ny16 * 16; i += 16) {
+ // load 16x4 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m512 v0;
+ __m512 v1;
+ __m512 v2;
+ __m512 v3;
+
+ transpose_16x4(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ _mm512_loadu_ps(y + 2 * 16),
+ _mm512_loadu_ps(y + 3 * 16),
+ v0,
+ v1,
+ v2,
+ v3);
+
+ // compute distances
+ __m512 distances = _mm512_mul_ps(m0, v0);
+ distances = _mm512_fmadd_ps(m1, v1, distances);
+ distances = _mm512_fmadd_ps(m2, v2, distances);
+ distances = _mm512_fmadd_ps(m3, v3, distances);
+
+ // store
+ _mm512_storeu_ps(dis + i, distances);
+
+ y += 64; // move to the next set of 16x4 elements
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m128 accu = ElementOpIP::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+template <>
+void fvec_op_ny_D4<ElementOpL2>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny16 = ny / 16;
+ size_t i = 0;
+
+ if (ny16 > 0) {
+ // process 16 D4-vectors per loop.
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+ const __m512 m2 = _mm512_set1_ps(x[2]);
+ const __m512 m3 = _mm512_set1_ps(x[3]);
+
+ for (i = 0; i < ny16 * 16; i += 16) {
+ // load 16x4 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m512 v0;
+ __m512 v1;
+ __m512 v2;
+ __m512 v3;
+
+ transpose_16x4(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ _mm512_loadu_ps(y + 2 * 16),
+ _mm512_loadu_ps(y + 3 * 16),
+ v0,
+ v1,
+ v2,
+ v3);
+
+ // compute differences
+ const __m512 d0 = _mm512_sub_ps(m0, v0);
+ const __m512 d1 = _mm512_sub_ps(m1, v1);
+ const __m512 d2 = _mm512_sub_ps(m2, v2);
+ const __m512 d3 = _mm512_sub_ps(m3, v3);
+
+ // compute squares of differences
+ __m512 distances = _mm512_mul_ps(d0, d0);
+ distances = _mm512_fmadd_ps(d1, d1, distances);
+ distances = _mm512_fmadd_ps(d2, d2, distances);
+ distances = _mm512_fmadd_ps(d3, d3, distances);
+
+ // store
+ _mm512_storeu_ps(dis + i, distances);
+
+ y += 64; // move to the next set of 16x4 elements
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m128 accu = ElementOpL2::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+#elif defined(__AVX2__)
+
+template <>
+void fvec_op_ny_D4<ElementOpIP>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny8 = ny / 8;
+ size_t i = 0;
+
+ if (ny8 > 0) {
+ // process 8 D4-vectors per loop.
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+ const __m256 m2 = _mm256_set1_ps(x[2]);
+ const __m256 m3 = _mm256_set1_ps(x[3]);
+
+ for (i = 0; i < ny8 * 8; i += 8) {
+ // load 8x4 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m256 v0;
+ __m256 v1;
+ __m256 v2;
+ __m256 v3;
+
+ transpose_8x4(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ _mm256_loadu_ps(y + 2 * 8),
+ _mm256_loadu_ps(y + 3 * 8),
+ v0,
+ v1,
+ v2,
+ v3);
+
+ // compute distances
+ __m256 distances = _mm256_mul_ps(m0, v0);
+ distances = _mm256_fmadd_ps(m1, v1, distances);
+ distances = _mm256_fmadd_ps(m2, v2, distances);
+ distances = _mm256_fmadd_ps(m3, v3, distances);
+
+ // store
+ _mm256_storeu_ps(dis + i, distances);
+
+ y += 32;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m128 accu = ElementOpIP::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+template <>
+void fvec_op_ny_D4<ElementOpL2>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny8 = ny / 8;
+ size_t i = 0;
+
+ if (ny8 > 0) {
+ // process 8 D4-vectors per loop.
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+ const __m256 m2 = _mm256_set1_ps(x[2]);
+ const __m256 m3 = _mm256_set1_ps(x[3]);
+
+ for (i = 0; i < ny8 * 8; i += 8) {
+ // load 8x4 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m256 v0;
+ __m256 v1;
+ __m256 v2;
+ __m256 v3;
+
+ transpose_8x4(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ _mm256_loadu_ps(y + 2 * 8),
+ _mm256_loadu_ps(y + 3 * 8),
+ v0,
+ v1,
+ v2,
+ v3);
+
+ // compute differences
+ const __m256 d0 = _mm256_sub_ps(m0, v0);
+ const __m256 d1 = _mm256_sub_ps(m1, v1);
+ const __m256 d2 = _mm256_sub_ps(m2, v2);
+ const __m256 d3 = _mm256_sub_ps(m3, v3);
+
+ // compute squares of differences
+ __m256 distances = _mm256_mul_ps(d0, d0);
+ distances = _mm256_fmadd_ps(d1, d1, distances);
+ distances = _mm256_fmadd_ps(d2, d2, distances);
+ distances = _mm256_fmadd_ps(d3, d3, distances);
+
+ // store
+ _mm256_storeu_ps(dis + i, distances);
+
+ y += 32;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m128 accu = ElementOpL2::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+#endif
+
+template <class ElementOp>
+void fvec_op_ny_D8(float* dis, const float* x, const float* y, size_t ny) {
+ __m128 x0 = _mm_loadu_ps(x);
+ __m128 x1 = _mm_loadu_ps(x + 4);
+
+ for (size_t i = 0; i < ny; i++) {
+ __m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ accu = _mm_add_ps(accu, ElementOp::op(x1, _mm_loadu_ps(y)));
+ y += 4;
+ accu = _mm_hadd_ps(accu, accu);
+ accu = _mm_hadd_ps(accu, accu);
+ dis[i] = _mm_cvtss_f32(accu);
+ }
+}
+
+#if defined(__AVX512F__)
+
+template <>
+void fvec_op_ny_D8<ElementOpIP>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny16 = ny / 16;
+ size_t i = 0;
+
+ if (ny16 > 0) {
+ // process 16 D16-vectors per loop.
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+ const __m512 m2 = _mm512_set1_ps(x[2]);
+ const __m512 m3 = _mm512_set1_ps(x[3]);
+ const __m512 m4 = _mm512_set1_ps(x[4]);
+ const __m512 m5 = _mm512_set1_ps(x[5]);
+ const __m512 m6 = _mm512_set1_ps(x[6]);
+ const __m512 m7 = _mm512_set1_ps(x[7]);
+
+ for (i = 0; i < ny16 * 16; i += 16) {
+ // load 16x8 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m512 v0;
+ __m512 v1;
+ __m512 v2;
+ __m512 v3;
+ __m512 v4;
+ __m512 v5;
+ __m512 v6;
+ __m512 v7;
+
+ transpose_16x8(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ _mm512_loadu_ps(y + 2 * 16),
+ _mm512_loadu_ps(y + 3 * 16),
+ _mm512_loadu_ps(y + 4 * 16),
+ _mm512_loadu_ps(y + 5 * 16),
+ _mm512_loadu_ps(y + 6 * 16),
+ _mm512_loadu_ps(y + 7 * 16),
+ v0,
+ v1,
+ v2,
+ v3,
+ v4,
+ v5,
+ v6,
+ v7);
+
+ // compute distances
+ __m512 distances = _mm512_mul_ps(m0, v0);
+ distances = _mm512_fmadd_ps(m1, v1, distances);
+ distances = _mm512_fmadd_ps(m2, v2, distances);
+ distances = _mm512_fmadd_ps(m3, v3, distances);
+ distances = _mm512_fmadd_ps(m4, v4, distances);
+ distances = _mm512_fmadd_ps(m5, v5, distances);
+ distances = _mm512_fmadd_ps(m6, v6, distances);
+ distances = _mm512_fmadd_ps(m7, v7, distances);
+
+ // store
+ _mm512_storeu_ps(dis + i, distances);
+
+ y += 128; // 16 floats * 8 rows
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m256 x0 = _mm256_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m256 accu = ElementOpIP::op(x0, _mm256_loadu_ps(y));
+ y += 8;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+template <>
+void fvec_op_ny_D8<ElementOpL2>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny16 = ny / 16;
+ size_t i = 0;
+
+ if (ny16 > 0) {
+ // process 16 D16-vectors per loop.
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+ const __m512 m2 = _mm512_set1_ps(x[2]);
+ const __m512 m3 = _mm512_set1_ps(x[3]);
+ const __m512 m4 = _mm512_set1_ps(x[4]);
+ const __m512 m5 = _mm512_set1_ps(x[5]);
+ const __m512 m6 = _mm512_set1_ps(x[6]);
+ const __m512 m7 = _mm512_set1_ps(x[7]);
+
+ for (i = 0; i < ny16 * 16; i += 16) {
+ // load 16x8 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m512 v0;
+ __m512 v1;
+ __m512 v2;
+ __m512 v3;
+ __m512 v4;
+ __m512 v5;
+ __m512 v6;
+ __m512 v7;
+
+ transpose_16x8(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ _mm512_loadu_ps(y + 2 * 16),
+ _mm512_loadu_ps(y + 3 * 16),
+ _mm512_loadu_ps(y + 4 * 16),
+ _mm512_loadu_ps(y + 5 * 16),
+ _mm512_loadu_ps(y + 6 * 16),
+ _mm512_loadu_ps(y + 7 * 16),
+ v0,
+ v1,
+ v2,
+ v3,
+ v4,
+ v5,
+ v6,
+ v7);
+
+ // compute differences
+ const __m512 d0 = _mm512_sub_ps(m0, v0);
+ const __m512 d1 = _mm512_sub_ps(m1, v1);
+ const __m512 d2 = _mm512_sub_ps(m2, v2);
+ const __m512 d3 = _mm512_sub_ps(m3, v3);
+ const __m512 d4 = _mm512_sub_ps(m4, v4);
+ const __m512 d5 = _mm512_sub_ps(m5, v5);
+ const __m512 d6 = _mm512_sub_ps(m6, v6);
+ const __m512 d7 = _mm512_sub_ps(m7, v7);
+
+ // compute squares of differences
+ __m512 distances = _mm512_mul_ps(d0, d0);
+ distances = _mm512_fmadd_ps(d1, d1, distances);
+ distances = _mm512_fmadd_ps(d2, d2, distances);
+ distances = _mm512_fmadd_ps(d3, d3, distances);
+ distances = _mm512_fmadd_ps(d4, d4, distances);
+ distances = _mm512_fmadd_ps(d5, d5, distances);
+ distances = _mm512_fmadd_ps(d6, d6, distances);
+ distances = _mm512_fmadd_ps(d7, d7, distances);
+
+ // store
+ _mm512_storeu_ps(dis + i, distances);
+
+ y += 128; // 16 floats * 8 rows
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m256 x0 = _mm256_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m256 accu = ElementOpL2::op(x0, _mm256_loadu_ps(y));
+ y += 8;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+#elif defined(__AVX2__)
+
+template <>
+void fvec_op_ny_D8<ElementOpIP>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny8 = ny / 8;
+ size_t i = 0;
+
+ if (ny8 > 0) {
+ // process 8 D8-vectors per loop.
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+ const __m256 m2 = _mm256_set1_ps(x[2]);
+ const __m256 m3 = _mm256_set1_ps(x[3]);
+ const __m256 m4 = _mm256_set1_ps(x[4]);
+ const __m256 m5 = _mm256_set1_ps(x[5]);
+ const __m256 m6 = _mm256_set1_ps(x[6]);
+ const __m256 m7 = _mm256_set1_ps(x[7]);
+
+ for (i = 0; i < ny8 * 8; i += 8) {
+ // load 8x8 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m256 v0;
+ __m256 v1;
+ __m256 v2;
+ __m256 v3;
+ __m256 v4;
+ __m256 v5;
+ __m256 v6;
+ __m256 v7;
+
+ transpose_8x8(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ _mm256_loadu_ps(y + 2 * 8),
+ _mm256_loadu_ps(y + 3 * 8),
+ _mm256_loadu_ps(y + 4 * 8),
+ _mm256_loadu_ps(y + 5 * 8),
+ _mm256_loadu_ps(y + 6 * 8),
+ _mm256_loadu_ps(y + 7 * 8),
+ v0,
+ v1,
+ v2,
+ v3,
+ v4,
+ v5,
+ v6,
+ v7);
+
+ // compute distances
+ __m256 distances = _mm256_mul_ps(m0, v0);
+ distances = _mm256_fmadd_ps(m1, v1, distances);
+ distances = _mm256_fmadd_ps(m2, v2, distances);
+ distances = _mm256_fmadd_ps(m3, v3, distances);
+ distances = _mm256_fmadd_ps(m4, v4, distances);
+ distances = _mm256_fmadd_ps(m5, v5, distances);
+ distances = _mm256_fmadd_ps(m6, v6, distances);
+ distances = _mm256_fmadd_ps(m7, v7, distances);
+
+ // store
+ _mm256_storeu_ps(dis + i, distances);
+
+ y += 64;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m256 x0 = _mm256_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m256 accu = ElementOpIP::op(x0, _mm256_loadu_ps(y));
+ y += 8;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+template <>
+void fvec_op_ny_D8<ElementOpL2>(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t ny8 = ny / 8;
+ size_t i = 0;
+
+ if (ny8 > 0) {
+ // process 8 D8-vectors per loop.
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+ const __m256 m2 = _mm256_set1_ps(x[2]);
+ const __m256 m3 = _mm256_set1_ps(x[3]);
+ const __m256 m4 = _mm256_set1_ps(x[4]);
+ const __m256 m5 = _mm256_set1_ps(x[5]);
+ const __m256 m6 = _mm256_set1_ps(x[6]);
+ const __m256 m7 = _mm256_set1_ps(x[7]);
+
+ for (i = 0; i < ny8 * 8; i += 8) {
+ // load 8x8 matrix and transpose it in registers.
+ // the typical bottleneck is memory access, so
+ // let's trade instructions for the bandwidth.
+
+ __m256 v0;
+ __m256 v1;
+ __m256 v2;
+ __m256 v3;
+ __m256 v4;
+ __m256 v5;
+ __m256 v6;
+ __m256 v7;
+
+ transpose_8x8(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ _mm256_loadu_ps(y + 2 * 8),
+ _mm256_loadu_ps(y + 3 * 8),
+ _mm256_loadu_ps(y + 4 * 8),
+ _mm256_loadu_ps(y + 5 * 8),
+ _mm256_loadu_ps(y + 6 * 8),
+ _mm256_loadu_ps(y + 7 * 8),
+ v0,
+ v1,
+ v2,
+ v3,
+ v4,
+ v5,
+ v6,
+ v7);
+
+ // compute differences
+ const __m256 d0 = _mm256_sub_ps(m0, v0);
+ const __m256 d1 = _mm256_sub_ps(m1, v1);
+ const __m256 d2 = _mm256_sub_ps(m2, v2);
+ const __m256 d3 = _mm256_sub_ps(m3, v3);
+ const __m256 d4 = _mm256_sub_ps(m4, v4);
+ const __m256 d5 = _mm256_sub_ps(m5, v5);
+ const __m256 d6 = _mm256_sub_ps(m6, v6);
+ const __m256 d7 = _mm256_sub_ps(m7, v7);
+
+ // compute squares of differences
+ __m256 distances = _mm256_mul_ps(d0, d0);
+ distances = _mm256_fmadd_ps(d1, d1, distances);
+ distances = _mm256_fmadd_ps(d2, d2, distances);
+ distances = _mm256_fmadd_ps(d3, d3, distances);
+ distances = _mm256_fmadd_ps(d4, d4, distances);
+ distances = _mm256_fmadd_ps(d5, d5, distances);
+ distances = _mm256_fmadd_ps(d6, d6, distances);
+ distances = _mm256_fmadd_ps(d7, d7, distances);
+
+ // store
+ _mm256_storeu_ps(dis + i, distances);
+
+ y += 64;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m256 x0 = _mm256_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m256 accu = ElementOpL2::op(x0, _mm256_loadu_ps(y));
+ y += 8;
+ dis[i] = horizontal_sum(accu);
+ }
+ }
+}
+
+#endif
+
+template <class ElementOp>
+void fvec_op_ny_D12(float* dis, const float* x, const float* y, size_t ny) {
+ __m128 x0 = _mm_loadu_ps(x);
+ __m128 x1 = _mm_loadu_ps(x + 4);
+ __m128 x2 = _mm_loadu_ps(x + 8);
+
+ for (size_t i = 0; i < ny; i++) {
+ __m128 accu = ElementOp::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ accu = _mm_add_ps(accu, ElementOp::op(x1, _mm_loadu_ps(y)));
+ y += 4;
+ accu = _mm_add_ps(accu, ElementOp::op(x2, _mm_loadu_ps(y)));
+ y += 4;
+ dis[i] = horizontal_sum(accu);
+ }
+}
+
+} // anonymous namespace
+
+void fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ // optimized for a few special cases
+
+#define DISPATCH(dval) \
+ case dval: \
+ fvec_op_ny_D##dval<ElementOpL2>(dis, x, y, ny); \
+ return;
+
+ switch (d) {
+ DISPATCH(1)
+ DISPATCH(2)
+ DISPATCH(4)
+ DISPATCH(8)
+ DISPATCH(12)
+ default:
+ fvec_L2sqr_ny_ref(dis, x, y, d, ny);
+ return;
+ }
+#undef DISPATCH
+}
+
+void fvec_inner_products_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+#define DISPATCH(dval) \
+ case dval: \
+ fvec_op_ny_D##dval<ElementOpIP>(dis, x, y, ny); \
+ return;
+
+ switch (d) {
+ DISPATCH(1)
+ DISPATCH(2)
+ DISPATCH(4)
+ DISPATCH(8)
+ DISPATCH(12)
+ default:
+ fvec_inner_products_ny_ref(dis, x, y, d, ny);
+ return;
+ }
+#undef DISPATCH
+}
+
+#if defined(__AVX512F__)
+
+template <size_t DIM>
+void fvec_L2sqr_ny_y_transposed_D(
+ float* distances,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ const size_t d_offset,
+ size_t ny) {
+ // current index being processed
+ size_t i = 0;
+
+ // squared length of x
+ float x_sqlen = 0;
+ for (size_t j = 0; j < DIM; j++) {
+ x_sqlen += x[j] * x[j];
+ }
+
+ // process 16 vectors per loop
+ const size_t ny16 = ny / 16;
+
+ if (ny16 > 0) {
+ // m[i] = (2 * x[i], ... 2 * x[i])
+ __m512 m[DIM];
+ for (size_t j = 0; j < DIM; j++) {
+ m[j] = _mm512_set1_ps(x[j]);
+ m[j] = _mm512_add_ps(m[j], m[j]); // m[j] = 2 * x[j]
+ }
+
+ __m512 x_sqlen_ymm = _mm512_set1_ps(x_sqlen);
+
+ for (; i < ny16 * 16; i += 16) {
+ // Load vectors for 16 dimensions
+ __m512 v[DIM];
+ for (size_t j = 0; j < DIM; j++) {
+ v[j] = _mm512_loadu_ps(y + j * d_offset);
+ }
+
+ // Compute dot products
+ __m512 dp = _mm512_fnmadd_ps(m[0], v[0], x_sqlen_ymm);
+ for (size_t j = 1; j < DIM; j++) {
+ dp = _mm512_fnmadd_ps(m[j], v[j], dp);
+ }
+
+ // Compute y^2 - (2 * x, y) + x^2
+ __m512 distances_v = _mm512_add_ps(_mm512_loadu_ps(y_sqlen), dp);
+
+ _mm512_storeu_ps(distances + i, distances_v);
+
+ // Scroll y and y_sqlen forward
+ y += 16;
+ y_sqlen += 16;
+ }
+ }
+
+ if (i < ny) {
+ // Process leftovers
+ for (; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < DIM; j++) {
+ dp += x[j] * y[j * d_offset];
+ }
+
+ // Compute y^2 - 2 * (x, y), which is sufficient for looking for the
+ // lowest distance.
+ const float distance = y_sqlen[0] - 2 * dp + x_sqlen;
+ distances[i] = distance;
+
+ y += 1;
+ y_sqlen += 1;
+ }
+ }
+}
+
+#elif defined(__AVX2__)
+
+template <size_t DIM>
+void fvec_L2sqr_ny_y_transposed_D(
+ float* distances,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ const size_t d_offset,
+ size_t ny) {
+ // current index being processed
+ size_t i = 0;
+
+ // squared length of x
+ float x_sqlen = 0;
+ for (size_t j = 0; j < DIM; j++) {
+ x_sqlen += x[j] * x[j];
+ }
+
+ // process 8 vectors per loop.
+ const size_t ny8 = ny / 8;
+
+ if (ny8 > 0) {
+ // m[i] = (2 * x[i], ... 2 * x[i])
+ __m256 m[DIM];
+ for (size_t j = 0; j < DIM; j++) {
+ m[j] = _mm256_set1_ps(x[j]);
+ m[j] = _mm256_add_ps(m[j], m[j]);
+ }
+
+ __m256 x_sqlen_ymm = _mm256_set1_ps(x_sqlen);
+
+ for (; i < ny8 * 8; i += 8) {
+ // collect dim 0 for 8 D4-vectors.
+ const __m256 v0 = _mm256_loadu_ps(y + 0 * d_offset);
+
+ // compute dot products
+ // this is x^2 - 2x[0]*y[0]
+ __m256 dp = _mm256_fnmadd_ps(m[0], v0, x_sqlen_ymm);
+
+ for (size_t j = 1; j < DIM; j++) {
+ // collect dim j for 8 D4-vectors.
+ const __m256 vj = _mm256_loadu_ps(y + j * d_offset);
+ dp = _mm256_fnmadd_ps(m[j], vj, dp);
+ }
+
+ // we've got x^2 - (2x, y) at this point
+
+ // y^2 - (2x, y) + x^2
+ __m256 distances_v = _mm256_add_ps(_mm256_loadu_ps(y_sqlen), dp);
+
+ _mm256_storeu_ps(distances + i, distances_v);
+
+ // scroll y and y_sqlen forward.
+ y += 8;
+ y_sqlen += 8;
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ for (; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < DIM; j++) {
+ dp += x[j] * y[j * d_offset];
+ }
+
+ // compute y^2 - 2 * (x, y), which is sufficient for looking for the
+ // lowest distance.
+ const float distance = y_sqlen[0] - 2 * dp + x_sqlen;
+ distances[i] = distance;
+
+ y += 1;
+ y_sqlen += 1;
+ }
+ }
+}
+
+#endif
+
+void fvec_L2sqr_ny_transposed(
+ float* dis,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ // optimized for a few special cases
+
+#ifdef __AVX2__
+#define DISPATCH(dval) \
+ case dval: \
+ return fvec_L2sqr_ny_y_transposed_D<dval>( \
+ dis, x, y, y_sqlen, d_offset, ny);
+
+ switch (d) {
+ DISPATCH(1)
+ DISPATCH(2)
+ DISPATCH(4)
+ DISPATCH(8)
+ default:
+ return fvec_L2sqr_ny_y_transposed_ref(
+ dis, x, y, y_sqlen, d, d_offset, ny);
+ }
+#undef DISPATCH
+#else
+ // non-AVX2 case
+ return fvec_L2sqr_ny_y_transposed_ref(dis, x, y, y_sqlen, d, d_offset, ny);
+#endif
+}
+
+#if defined(__AVX512F__)
+
+size_t fvec_L2sqr_ny_nearest_D2(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ size_t i = 0;
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ const size_t ny16 = ny / 16;
+ if (ny16 > 0) {
+ _mm_prefetch((const char*)y, _MM_HINT_T0);
+ _mm_prefetch((const char*)(y + 32), _MM_HINT_T0);
+
+ __m512 min_distances = _mm512_set1_ps(HUGE_VALF);
+ __m512i min_indices = _mm512_set1_epi32(0);
+
+ __m512i current_indices = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ const __m512i indices_increment = _mm512_set1_epi32(16);
+
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+
+ for (; i < ny16 * 16; i += 16) {
+ _mm_prefetch((const char*)(y + 64), _MM_HINT_T0);
+
+ __m512 v0;
+ __m512 v1;
+
+ transpose_16x2(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ v0,
+ v1);
+
+ const __m512 d0 = _mm512_sub_ps(m0, v0);
+ const __m512 d1 = _mm512_sub_ps(m1, v1);
+
+ __m512 distances = _mm512_mul_ps(d0, d0);
+ distances = _mm512_fmadd_ps(d1, d1, distances);
+
+ __mmask16 comparison =
+ _mm512_cmp_ps_mask(distances, min_distances, _CMP_LT_OS);
+
+ min_distances = _mm512_min_ps(distances, min_distances);
+ min_indices = _mm512_mask_blend_epi32(
+ comparison, min_indices, current_indices);
+
+ current_indices =
+ _mm512_add_epi32(current_indices, indices_increment);
+
+ y += 32;
+ }
+
+ alignas(64) float min_distances_scalar[16];
+ alignas(64) uint32_t min_indices_scalar[16];
+ _mm512_store_ps(min_distances_scalar, min_distances);
+ _mm512_store_epi32(min_indices_scalar, min_indices);
+
+ for (size_t j = 0; j < 16; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ float x0 = x[0];
+ float x1 = x[1];
+
+ for (; i < ny; i++) {
+ float sub0 = x0 - y[0];
+ float sub1 = x1 - y[1];
+ float distance = sub0 * sub0 + sub1 * sub1;
+
+ y += 2;
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+ }
+ }
+
+ return current_min_index;
+}
+
+size_t fvec_L2sqr_ny_nearest_D4(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ size_t i = 0;
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ const size_t ny16 = ny / 16;
+
+ if (ny16 > 0) {
+ __m512 min_distances = _mm512_set1_ps(HUGE_VALF);
+ __m512i min_indices = _mm512_set1_epi32(0);
+
+ __m512i current_indices = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ const __m512i indices_increment = _mm512_set1_epi32(16);
+
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+ const __m512 m2 = _mm512_set1_ps(x[2]);
+ const __m512 m3 = _mm512_set1_ps(x[3]);
+
+ for (; i < ny16 * 16; i += 16) {
+ __m512 v0;
+ __m512 v1;
+ __m512 v2;
+ __m512 v3;
+
+ transpose_16x4(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ _mm512_loadu_ps(y + 2 * 16),
+ _mm512_loadu_ps(y + 3 * 16),
+ v0,
+ v1,
+ v2,
+ v3);
+
+ const __m512 d0 = _mm512_sub_ps(m0, v0);
+ const __m512 d1 = _mm512_sub_ps(m1, v1);
+ const __m512 d2 = _mm512_sub_ps(m2, v2);
+ const __m512 d3 = _mm512_sub_ps(m3, v3);
+
+ __m512 distances = _mm512_mul_ps(d0, d0);
+ distances = _mm512_fmadd_ps(d1, d1, distances);
+ distances = _mm512_fmadd_ps(d2, d2, distances);
+ distances = _mm512_fmadd_ps(d3, d3, distances);
+
+ __mmask16 comparison =
+ _mm512_cmp_ps_mask(distances, min_distances, _CMP_LT_OS);
+
+ min_distances = _mm512_min_ps(distances, min_distances);
+ min_indices = _mm512_mask_blend_epi32(
+ comparison, min_indices, current_indices);
+
+ current_indices =
+ _mm512_add_epi32(current_indices, indices_increment);
+
+ y += 64;
+ }
+
+ alignas(64) float min_distances_scalar[16];
+ alignas(64) uint32_t min_indices_scalar[16];
+ _mm512_store_ps(min_distances_scalar, min_distances);
+ _mm512_store_epi32(min_indices_scalar, min_indices);
+
+ for (size_t j = 0; j < 16; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m128 accu = ElementOpL2::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ const float distance = horizontal_sum(accu);
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+ }
+ }
+
+ return current_min_index;
+}
+
+size_t fvec_L2sqr_ny_nearest_D8(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ size_t i = 0;
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ const size_t ny16 = ny / 16;
+ if (ny16 > 0) {
+ __m512 min_distances = _mm512_set1_ps(HUGE_VALF);
+ __m512i min_indices = _mm512_set1_epi32(0);
+
+ __m512i current_indices = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ const __m512i indices_increment = _mm512_set1_epi32(16);
+
+ const __m512 m0 = _mm512_set1_ps(x[0]);
+ const __m512 m1 = _mm512_set1_ps(x[1]);
+ const __m512 m2 = _mm512_set1_ps(x[2]);
+ const __m512 m3 = _mm512_set1_ps(x[3]);
+
+ const __m512 m4 = _mm512_set1_ps(x[4]);
+ const __m512 m5 = _mm512_set1_ps(x[5]);
+ const __m512 m6 = _mm512_set1_ps(x[6]);
+ const __m512 m7 = _mm512_set1_ps(x[7]);
+
+ for (; i < ny16 * 16; i += 16) {
+ __m512 v0;
+ __m512 v1;
+ __m512 v2;
+ __m512 v3;
+ __m512 v4;
+ __m512 v5;
+ __m512 v6;
+ __m512 v7;
+
+ transpose_16x8(
+ _mm512_loadu_ps(y + 0 * 16),
+ _mm512_loadu_ps(y + 1 * 16),
+ _mm512_loadu_ps(y + 2 * 16),
+ _mm512_loadu_ps(y + 3 * 16),
+ _mm512_loadu_ps(y + 4 * 16),
+ _mm512_loadu_ps(y + 5 * 16),
+ _mm512_loadu_ps(y + 6 * 16),
+ _mm512_loadu_ps(y + 7 * 16),
+ v0,
+ v1,
+ v2,
+ v3,
+ v4,
+ v5,
+ v6,
+ v7);
+
+ const __m512 d0 = _mm512_sub_ps(m0, v0);
+ const __m512 d1 = _mm512_sub_ps(m1, v1);
+ const __m512 d2 = _mm512_sub_ps(m2, v2);
+ const __m512 d3 = _mm512_sub_ps(m3, v3);
+ const __m512 d4 = _mm512_sub_ps(m4, v4);
+ const __m512 d5 = _mm512_sub_ps(m5, v5);
+ const __m512 d6 = _mm512_sub_ps(m6, v6);
+ const __m512 d7 = _mm512_sub_ps(m7, v7);
+
+ __m512 distances = _mm512_mul_ps(d0, d0);
+ distances = _mm512_fmadd_ps(d1, d1, distances);
+ distances = _mm512_fmadd_ps(d2, d2, distances);
+ distances = _mm512_fmadd_ps(d3, d3, distances);
+ distances = _mm512_fmadd_ps(d4, d4, distances);
+ distances = _mm512_fmadd_ps(d5, d5, distances);
+ distances = _mm512_fmadd_ps(d6, d6, distances);
+ distances = _mm512_fmadd_ps(d7, d7, distances);
+
+ __mmask16 comparison =
+ _mm512_cmp_ps_mask(distances, min_distances, _CMP_LT_OS);
+
+ min_distances = _mm512_min_ps(distances, min_distances);
+ min_indices = _mm512_mask_blend_epi32(
+ comparison, min_indices, current_indices);
+
+ current_indices =
+ _mm512_add_epi32(current_indices, indices_increment);
+
+ y += 128;
+ }
+
+ alignas(64) float min_distances_scalar[16];
+ alignas(64) uint32_t min_indices_scalar[16];
+ _mm512_store_ps(min_distances_scalar, min_distances);
+ _mm512_store_epi32(min_indices_scalar, min_indices);
+
+ for (size_t j = 0; j < 16; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ __m256 x0 = _mm256_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m256 accu = ElementOpL2::op(x0, _mm256_loadu_ps(y));
+ y += 8;
+ const float distance = horizontal_sum(accu);
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+ }
+ }
+
+ return current_min_index;
+}
+
+#elif defined(__AVX2__)
+
+size_t fvec_L2sqr_ny_nearest_D2(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ // current index being processed
+ size_t i = 0;
+
+ // min distance and the index of the closest vector so far
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ // process 8 D2-vectors per loop.
+ const size_t ny8 = ny / 8;
+ if (ny8 > 0) {
+ _mm_prefetch((const char*)y, _MM_HINT_T0);
+ _mm_prefetch((const char*)(y + 16), _MM_HINT_T0);
+
+ // track min distance and the closest vector independently
+ // for each of 8 AVX2 components.
+ __m256 min_distances = _mm256_set1_ps(HUGE_VALF);
+ __m256i min_indices = _mm256_set1_epi32(0);
+
+ __m256i current_indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ const __m256i indices_increment = _mm256_set1_epi32(8);
+
+ // 1 value per register
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+
+ for (; i < ny8 * 8; i += 8) {
+ _mm_prefetch((const char*)(y + 32), _MM_HINT_T0);
+
+ __m256 v0;
+ __m256 v1;
+
+ transpose_8x2(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ v0,
+ v1);
+
+ // compute differences
+ const __m256 d0 = _mm256_sub_ps(m0, v0);
+ const __m256 d1 = _mm256_sub_ps(m1, v1);
+
+ // compute squares of differences
+ __m256 distances = _mm256_mul_ps(d0, d0);
+ distances = _mm256_fmadd_ps(d1, d1, distances);
+
+ // compare the new distances to the min distances
+ // for each of 8 AVX2 components.
+ __m256 comparison =
+ _mm256_cmp_ps(min_distances, distances, _CMP_LT_OS);
+
+ // update min distances and indices with closest vectors if needed.
+ min_distances = _mm256_min_ps(distances, min_distances);
+ min_indices = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ comparison));
+
+ // update current indices values. Basically, +8 to each of the
+ // 8 AVX2 components.
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_increment);
+
+ // scroll y forward (8 vectors 2 DIM each).
+ y += 16;
+ }
+
+ // dump values and find the minimum distance / minimum index
+ float min_distances_scalar[8];
+ uint32_t min_indices_scalar[8];
+ _mm256_storeu_ps(min_distances_scalar, min_distances);
+ _mm256_storeu_si256((__m256i*)(min_indices_scalar), min_indices);
+
+ for (size_t j = 0; j < 8; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers.
+ // the following code is not optimal, but it is rarely invoked.
+ float x0 = x[0];
+ float x1 = x[1];
+
+ for (; i < ny; i++) {
+ float sub0 = x0 - y[0];
+ float sub1 = x1 - y[1];
+ float distance = sub0 * sub0 + sub1 * sub1;
+
+ y += 2;
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+ }
+ }
+
+ return current_min_index;
+}
+
+size_t fvec_L2sqr_ny_nearest_D4(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ // current index being processed
+ size_t i = 0;
+
+ // min distance and the index of the closest vector so far
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ // process 8 D4-vectors per loop.
+ const size_t ny8 = ny / 8;
+
+ if (ny8 > 0) {
+ // track min distance and the closest vector independently
+ // for each of 8 AVX2 components.
+ __m256 min_distances = _mm256_set1_ps(HUGE_VALF);
+ __m256i min_indices = _mm256_set1_epi32(0);
+
+ __m256i current_indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ const __m256i indices_increment = _mm256_set1_epi32(8);
+
+ // 1 value per register
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+ const __m256 m2 = _mm256_set1_ps(x[2]);
+ const __m256 m3 = _mm256_set1_ps(x[3]);
+
+ for (; i < ny8 * 8; i += 8) {
+ __m256 v0;
+ __m256 v1;
+ __m256 v2;
+ __m256 v3;
+
+ transpose_8x4(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ _mm256_loadu_ps(y + 2 * 8),
+ _mm256_loadu_ps(y + 3 * 8),
+ v0,
+ v1,
+ v2,
+ v3);
+
+ // compute differences
+ const __m256 d0 = _mm256_sub_ps(m0, v0);
+ const __m256 d1 = _mm256_sub_ps(m1, v1);
+ const __m256 d2 = _mm256_sub_ps(m2, v2);
+ const __m256 d3 = _mm256_sub_ps(m3, v3);
+
+ // compute squares of differences
+ __m256 distances = _mm256_mul_ps(d0, d0);
+ distances = _mm256_fmadd_ps(d1, d1, distances);
+ distances = _mm256_fmadd_ps(d2, d2, distances);
+ distances = _mm256_fmadd_ps(d3, d3, distances);
+
+ // compare the new distances to the min distances
+ // for each of 8 AVX2 components.
+ __m256 comparison =
+ _mm256_cmp_ps(min_distances, distances, _CMP_LT_OS);
+
+ // update min distances and indices with closest vectors if needed.
+ min_distances = _mm256_min_ps(distances, min_distances);
+ min_indices = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ comparison));
+
+ // update current indices values. Basically, +8 to each of the
+ // 8 AVX2 components.
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_increment);
+
+ // scroll y forward (8 vectors 4 DIM each).
+ y += 32;
+ }
+
+ // dump values and find the minimum distance / minimum index
+ float min_distances_scalar[8];
+ uint32_t min_indices_scalar[8];
+ _mm256_storeu_ps(min_distances_scalar, min_distances);
+ _mm256_storeu_si256((__m256i*)(min_indices_scalar), min_indices);
+
+ for (size_t j = 0; j < 8; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m128 x0 = _mm_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m128 accu = ElementOpL2::op(x0, _mm_loadu_ps(y));
+ y += 4;
+ const float distance = horizontal_sum(accu);
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+ }
+ }
+
+ return current_min_index;
+}
+
+size_t fvec_L2sqr_ny_nearest_D8(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ // current index being processed
+ size_t i = 0;
+
+ // min distance and the index of the closest vector so far
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ // process 8 D8-vectors per loop.
+ const size_t ny8 = ny / 8;
+ if (ny8 > 0) {
+ // track min distance and the closest vector independently
+ // for each of 8 AVX2 components.
+ __m256 min_distances = _mm256_set1_ps(HUGE_VALF);
+ __m256i min_indices = _mm256_set1_epi32(0);
+
+ __m256i current_indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ const __m256i indices_increment = _mm256_set1_epi32(8);
+
+ // 1 value per register
+ const __m256 m0 = _mm256_set1_ps(x[0]);
+ const __m256 m1 = _mm256_set1_ps(x[1]);
+ const __m256 m2 = _mm256_set1_ps(x[2]);
+ const __m256 m3 = _mm256_set1_ps(x[3]);
+
+ const __m256 m4 = _mm256_set1_ps(x[4]);
+ const __m256 m5 = _mm256_set1_ps(x[5]);
+ const __m256 m6 = _mm256_set1_ps(x[6]);
+ const __m256 m7 = _mm256_set1_ps(x[7]);
+
+ for (; i < ny8 * 8; i += 8) {
+ __m256 v0;
+ __m256 v1;
+ __m256 v2;
+ __m256 v3;
+ __m256 v4;
+ __m256 v5;
+ __m256 v6;
+ __m256 v7;
+
+ transpose_8x8(
+ _mm256_loadu_ps(y + 0 * 8),
+ _mm256_loadu_ps(y + 1 * 8),
+ _mm256_loadu_ps(y + 2 * 8),
+ _mm256_loadu_ps(y + 3 * 8),
+ _mm256_loadu_ps(y + 4 * 8),
+ _mm256_loadu_ps(y + 5 * 8),
+ _mm256_loadu_ps(y + 6 * 8),
+ _mm256_loadu_ps(y + 7 * 8),
+ v0,
+ v1,
+ v2,
+ v3,
+ v4,
+ v5,
+ v6,
+ v7);
+
+ // compute differences
+ const __m256 d0 = _mm256_sub_ps(m0, v0);
+ const __m256 d1 = _mm256_sub_ps(m1, v1);
+ const __m256 d2 = _mm256_sub_ps(m2, v2);
+ const __m256 d3 = _mm256_sub_ps(m3, v3);
+ const __m256 d4 = _mm256_sub_ps(m4, v4);
+ const __m256 d5 = _mm256_sub_ps(m5, v5);
+ const __m256 d6 = _mm256_sub_ps(m6, v6);
+ const __m256 d7 = _mm256_sub_ps(m7, v7);
+
+ // compute squares of differences
+ __m256 distances = _mm256_mul_ps(d0, d0);
+ distances = _mm256_fmadd_ps(d1, d1, distances);
+ distances = _mm256_fmadd_ps(d2, d2, distances);
+ distances = _mm256_fmadd_ps(d3, d3, distances);
+ distances = _mm256_fmadd_ps(d4, d4, distances);
+ distances = _mm256_fmadd_ps(d5, d5, distances);
+ distances = _mm256_fmadd_ps(d6, d6, distances);
+ distances = _mm256_fmadd_ps(d7, d7, distances);
+
+ // compare the new distances to the min distances
+ // for each of 8 AVX2 components.
+ __m256 comparison =
+ _mm256_cmp_ps(min_distances, distances, _CMP_LT_OS);
+
+ // update min distances and indices with closest vectors if needed.
+ min_distances = _mm256_min_ps(distances, min_distances);
+ min_indices = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ comparison));
+
+ // update current indices values. Basically, +8 to each of the
+ // 8 AVX2 components.
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_increment);
+
+ // scroll y forward (8 vectors 8 DIM each).
+ y += 64;
+ }
+
+ // dump values and find the minimum distance / minimum index
+ float min_distances_scalar[8];
+ uint32_t min_indices_scalar[8];
+ _mm256_storeu_ps(min_distances_scalar, min_distances);
+ _mm256_storeu_si256((__m256i*)(min_indices_scalar), min_indices);
+
+ for (size_t j = 0; j < 8; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ __m256 x0 = _mm256_loadu_ps(x);
+
+ for (; i < ny; i++) {
+ __m256 accu = ElementOpL2::op(x0, _mm256_loadu_ps(y));
+ y += 8;
+ const float distance = horizontal_sum(accu);
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+ }
+ }
+
+ return current_min_index;
+}
+
+#else
+size_t fvec_L2sqr_ny_nearest_D2(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, 2, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest_D4(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, 4, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest_D8(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, 8, ny);
+}
+#endif
+
+size_t fvec_L2sqr_ny_nearest(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ // optimized for a few special cases
+#define DISPATCH(dval) \
+ case dval: \
+ return fvec_L2sqr_ny_nearest_D##dval(distances_tmp_buffer, x, y, ny);
+
+ switch (d) {
+ DISPATCH(2)
+ DISPATCH(4)
+ DISPATCH(8)
+ default:
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, d, ny);
+ }
+#undef DISPATCH
+}
+
+#if defined(__AVX512F__)
+
+template <size_t DIM>
+size_t fvec_L2sqr_ny_nearest_y_transposed_D(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ const size_t d_offset,
+ size_t ny) {
+ // This implementation does not use distances_tmp_buffer.
+
+ // Current index being processed
+ size_t i = 0;
+
+ // Min distance and the index of the closest vector so far
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ // Process 16 vectors per loop
+ const size_t ny16 = ny / 16;
+
+ if (ny16 > 0) {
+ // Track min distance and the closest vector independently
+ // for each of 16 AVX-512 components.
+ __m512 min_distances = _mm512_set1_ps(HUGE_VALF);
+ __m512i min_indices = _mm512_set1_epi32(0);
+
+ __m512i current_indices = _mm512_setr_epi32(
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
+ const __m512i indices_increment = _mm512_set1_epi32(16);
+
+ // m[i] = (2 * x[i], ... 2 * x[i])
+ __m512 m[DIM];
+ for (size_t j = 0; j < DIM; j++) {
+ m[j] = _mm512_set1_ps(x[j]);
+ m[j] = _mm512_add_ps(m[j], m[j]);
+ }
+
+ for (; i < ny16 * 16; i += 16) {
+ // Compute dot products
+ const __m512 v0 = _mm512_loadu_ps(y + 0 * d_offset);
+ __m512 dp = _mm512_mul_ps(m[0], v0);
+ for (size_t j = 1; j < DIM; j++) {
+ const __m512 vj = _mm512_loadu_ps(y + j * d_offset);
+ dp = _mm512_fmadd_ps(m[j], vj, dp);
+ }
+
+ // Compute y^2 - (2 * x, y), which is sufficient for looking for the
+ // lowest distance.
+ // x^2 is the constant that can be avoided.
+ const __m512 distances =
+ _mm512_sub_ps(_mm512_loadu_ps(y_sqlen), dp);
+
+ // Compare the new distances to the min distances
+ __mmask16 comparison =
+ _mm512_cmp_ps_mask(min_distances, distances, _CMP_LT_OS);
+
+ // Update min distances and indices with closest vectors if needed
+ min_distances =
+ _mm512_mask_blend_ps(comparison, distances, min_distances);
+ min_indices = _mm512_castps_si512(_mm512_mask_blend_ps(
+ comparison,
+ _mm512_castsi512_ps(current_indices),
+ _mm512_castsi512_ps(min_indices)));
+
+ // Update current indices values. Basically, +16 to each of the 16
+ // AVX-512 components.
+ current_indices =
+ _mm512_add_epi32(current_indices, indices_increment);
+
+ // Scroll y and y_sqlen forward.
+ y += 16;
+ y_sqlen += 16;
+ }
+
+ // Dump values and find the minimum distance / minimum index
+ float min_distances_scalar[16];
+ uint32_t min_indices_scalar[16];
+ _mm512_storeu_ps(min_distances_scalar, min_distances);
+ _mm512_storeu_si512((__m512i*)(min_indices_scalar), min_indices);
+
+ for (size_t j = 0; j < 16; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ // Process leftovers
+ for (; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < DIM; j++) {
+ dp += x[j] * y[j * d_offset];
+ }
+
+ // Compute y^2 - 2 * (x, y), which is sufficient for looking for the
+ // lowest distance.
+ const float distance = y_sqlen[0] - 2 * dp;
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+
+ y += 1;
+ y_sqlen += 1;
+ }
+ }
+
+ return current_min_index;
+}
+
+#elif defined(__AVX2__)
+
+template <size_t DIM>
+size_t fvec_L2sqr_ny_nearest_y_transposed_D(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ const size_t d_offset,
+ size_t ny) {
+ // this implementation does not use distances_tmp_buffer.
+
+ // current index being processed
+ size_t i = 0;
+
+ // min distance and the index of the closest vector so far
+ float current_min_distance = HUGE_VALF;
+ size_t current_min_index = 0;
+
+ // process 8 vectors per loop.
+ const size_t ny8 = ny / 8;
+
+ if (ny8 > 0) {
+ // track min distance and the closest vector independently
+ // for each of 8 AVX2 components.
+ __m256 min_distances = _mm256_set1_ps(HUGE_VALF);
+ __m256i min_indices = _mm256_set1_epi32(0);
+
+ __m256i current_indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
+ const __m256i indices_increment = _mm256_set1_epi32(8);
+
+ // m[i] = (2 * x[i], ... 2 * x[i])
+ __m256 m[DIM];
+ for (size_t j = 0; j < DIM; j++) {
+ m[j] = _mm256_set1_ps(x[j]);
+ m[j] = _mm256_add_ps(m[j], m[j]);
+ }
+
+ for (; i < ny8 * 8; i += 8) {
+ // collect dim 0 for 8 D4-vectors.
+ const __m256 v0 = _mm256_loadu_ps(y + 0 * d_offset);
+ // compute dot products
+ __m256 dp = _mm256_mul_ps(m[0], v0);
+
+ for (size_t j = 1; j < DIM; j++) {
+ // collect dim j for 8 D4-vectors.
+ const __m256 vj = _mm256_loadu_ps(y + j * d_offset);
+ dp = _mm256_fmadd_ps(m[j], vj, dp);
+ }
+
+ // compute y^2 - (2 * x, y), which is sufficient for looking for the
+ // lowest distance.
+ // x^2 is the constant that can be avoided.
+ const __m256 distances =
+ _mm256_sub_ps(_mm256_loadu_ps(y_sqlen), dp);
+
+ // compare the new distances to the min distances
+ // for each of 8 AVX2 components.
+ const __m256 comparison =
+ _mm256_cmp_ps(min_distances, distances, _CMP_LT_OS);
+
+ // update min distances and indices with closest vectors if needed.
+ min_distances =
+ _mm256_blendv_ps(distances, min_distances, comparison);
+ min_indices = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(current_indices),
+ _mm256_castsi256_ps(min_indices),
+ comparison));
+
+ // update current indices values. Basically, +8 to each of the
+ // 8 AVX2 components.
+ current_indices =
+ _mm256_add_epi32(current_indices, indices_increment);
+
+ // scroll y and y_sqlen forward.
+ y += 8;
+ y_sqlen += 8;
+ }
+
+ // dump values and find the minimum distance / minimum index
+ float min_distances_scalar[8];
+ uint32_t min_indices_scalar[8];
+ _mm256_storeu_ps(min_distances_scalar, min_distances);
+ _mm256_storeu_si256((__m256i*)(min_indices_scalar), min_indices);
+
+ for (size_t j = 0; j < 8; j++) {
+ if (current_min_distance > min_distances_scalar[j]) {
+ current_min_distance = min_distances_scalar[j];
+ current_min_index = min_indices_scalar[j];
+ }
+ }
+ }
+
+ if (i < ny) {
+ // process leftovers
+ for (; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < DIM; j++) {
+ dp += x[j] * y[j * d_offset];
+ }
+
+ // compute y^2 - 2 * (x, y), which is sufficient for looking for the
+ // lowest distance.
+ const float distance = y_sqlen[0] - 2 * dp;
+
+ if (current_min_distance > distance) {
+ current_min_distance = distance;
+ current_min_index = i;
+ }
+
+ y += 1;
+ y_sqlen += 1;
+ }
+ }
+
+ return current_min_index;
+}
+
+#endif
+
+size_t fvec_L2sqr_ny_nearest_y_transposed(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ // optimized for a few special cases
+#ifdef __AVX2__
+#define DISPATCH(dval) \
+ case dval: \
+ return fvec_L2sqr_ny_nearest_y_transposed_D<dval>( \
+ distances_tmp_buffer, x, y, y_sqlen, d_offset, ny);
+
+ switch (d) {
+ DISPATCH(1)
+ DISPATCH(2)
+ DISPATCH(4)
+ DISPATCH(8)
+ default:
+ return fvec_L2sqr_ny_nearest_y_transposed_ref(
+ distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny);
+ }
+#undef DISPATCH
+#else
+ // non-AVX2 case
+ return fvec_L2sqr_ny_nearest_y_transposed_ref(
+ distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny);
+#endif
+}
+
+#endif
+
+#ifdef USE_AVX
+
+float fvec_L1(const float* x, const float* y, size_t d) {
+ __m256 msum1 = _mm256_setzero_ps();
+ // signmask used for absolute value
+ __m256 signmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffffUL));
+
+ while (d >= 8) {
+ __m256 mx = _mm256_loadu_ps(x);
+ x += 8;
+ __m256 my = _mm256_loadu_ps(y);
+ y += 8;
+ // subtract
+ const __m256 a_m_b = _mm256_sub_ps(mx, my);
+ // find sum of absolute value of distances (manhattan distance)
+ msum1 = _mm256_add_ps(msum1, _mm256_and_ps(signmask, a_m_b));
+ d -= 8;
+ }
+
+ __m128 msum2 = _mm256_extractf128_ps(msum1, 1);
+ msum2 = _mm_add_ps(msum2, _mm256_extractf128_ps(msum1, 0));
+ __m128 signmask2 = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffUL));
+
+ if (d >= 4) {
+ __m128 mx = _mm_loadu_ps(x);
+ x += 4;
+ __m128 my = _mm_loadu_ps(y);
+ y += 4;
+ const __m128 a_m_b = _mm_sub_ps(mx, my);
+ msum2 = _mm_add_ps(msum2, _mm_and_ps(signmask2, a_m_b));
+ d -= 4;
+ }
+
+ if (d > 0) {
+ __m128 mx = masked_read(d, x);
+ __m128 my = masked_read(d, y);
+ __m128 a_m_b = _mm_sub_ps(mx, my);
+ msum2 = _mm_add_ps(msum2, _mm_and_ps(signmask2, a_m_b));
+ }
+
+ msum2 = _mm_hadd_ps(msum2, msum2);
+ msum2 = _mm_hadd_ps(msum2, msum2);
+ return _mm_cvtss_f32(msum2);
+}
+
+float fvec_Linf(const float* x, const float* y, size_t d) {
+ __m256 msum1 = _mm256_setzero_ps();
+ // signmask used for absolute value
+ __m256 signmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffffUL));
+
+ while (d >= 8) {
+ __m256 mx = _mm256_loadu_ps(x);
+ x += 8;
+ __m256 my = _mm256_loadu_ps(y);
+ y += 8;
+ // subtract
+ const __m256 a_m_b = _mm256_sub_ps(mx, my);
+ // find max of absolute value of distances (chebyshev distance)
+ msum1 = _mm256_max_ps(msum1, _mm256_and_ps(signmask, a_m_b));
+ d -= 8;
+ }
+
+ __m128 msum2 = _mm256_extractf128_ps(msum1, 1);
+ msum2 = _mm_max_ps(msum2, _mm256_extractf128_ps(msum1, 0));
+ __m128 signmask2 = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffUL));
+
+ if (d >= 4) {
+ __m128 mx = _mm_loadu_ps(x);
+ x += 4;
+ __m128 my = _mm_loadu_ps(y);
+ y += 4;
+ const __m128 a_m_b = _mm_sub_ps(mx, my);
+ msum2 = _mm_max_ps(msum2, _mm_and_ps(signmask2, a_m_b));
+ d -= 4;
+ }
+
+ if (d > 0) {
+ __m128 mx = masked_read(d, x);
+ __m128 my = masked_read(d, y);
+ __m128 a_m_b = _mm_sub_ps(mx, my);
+ msum2 = _mm_max_ps(msum2, _mm_and_ps(signmask2, a_m_b));
+ }
+
+ msum2 = _mm_max_ps(_mm_movehl_ps(msum2, msum2), msum2);
+ msum2 = _mm_max_ps(msum2, _mm_shuffle_ps(msum2, msum2, 1));
+ return _mm_cvtss_f32(msum2);
+}
+
+#elif defined(__SSE3__) // But not AVX
+
+float fvec_L1(const float* x, const float* y, size_t d) {
+ return fvec_L1_ref(x, y, d);
+}
+
+float fvec_Linf(const float* x, const float* y, size_t d) {
+ return fvec_Linf_ref(x, y, d);
+}
+
+#elif defined(__ARM_FEATURE_SVE)
+
+struct ElementOpIP {
+ static svfloat32_t op(svbool_t pg, svfloat32_t x, svfloat32_t y) {
+ return svmul_f32_x(pg, x, y);
+ }
+ static svfloat32_t merge(
+ svbool_t pg,
+ svfloat32_t z,
+ svfloat32_t x,
+ svfloat32_t y) {
+ return svmla_f32_x(pg, z, x, y);
+ }
+};
+
+template <typename ElementOp>
+void fvec_op_ny_sve_d1(float* dis, const float* x, const float* y, size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes3 = lanes * 3;
+ const size_t lanes4 = lanes * 4;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svdup_n_f32(x[0]);
+ size_t i = 0;
+ for (; i + lanes4 < ny; i += lanes4) {
+ svfloat32_t y0 = svld1_f32(pg, y);
+ svfloat32_t y1 = svld1_f32(pg, y + lanes);
+ svfloat32_t y2 = svld1_f32(pg, y + lanes2);
+ svfloat32_t y3 = svld1_f32(pg, y + lanes3);
+ y0 = ElementOp::op(pg, x0, y0);
+ y1 = ElementOp::op(pg, x0, y1);
+ y2 = ElementOp::op(pg, x0, y2);
+ y3 = ElementOp::op(pg, x0, y3);
+ svst1_f32(pg, dis, y0);
+ svst1_f32(pg, dis + lanes, y1);
+ svst1_f32(pg, dis + lanes2, y2);
+ svst1_f32(pg, dis + lanes3, y3);
+ y += lanes4;
+ dis += lanes4;
+ }
+ const svbool_t pg0 = svwhilelt_b32_u64(i, ny);
+ const svbool_t pg1 = svwhilelt_b32_u64(i + lanes, ny);
+ const svbool_t pg2 = svwhilelt_b32_u64(i + lanes2, ny);
+ const svbool_t pg3 = svwhilelt_b32_u64(i + lanes3, ny);
+ svfloat32_t y0 = svld1_f32(pg0, y);
+ svfloat32_t y1 = svld1_f32(pg1, y + lanes);
+ svfloat32_t y2 = svld1_f32(pg2, y + lanes2);
+ svfloat32_t y3 = svld1_f32(pg3, y + lanes3);
+ y0 = ElementOp::op(pg0, x0, y0);
+ y1 = ElementOp::op(pg1, x0, y1);
+ y2 = ElementOp::op(pg2, x0, y2);
+ y3 = ElementOp::op(pg3, x0, y3);
+ svst1_f32(pg0, dis, y0);
+ svst1_f32(pg1, dis + lanes, y1);
+ svst1_f32(pg2, dis + lanes2, y2);
+ svst1_f32(pg3, dis + lanes3, y3);
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_d2(float* dis, const float* x, const float* y, size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes4 = lanes * 4;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svdup_n_f32(x[0]);
+ const svfloat32_t x1 = svdup_n_f32(x[1]);
+ size_t i = 0;
+ for (; i + lanes2 < ny; i += lanes2) {
+ const svfloat32x2_t y0 = svld2_f32(pg, y);
+ const svfloat32x2_t y1 = svld2_f32(pg, y + lanes2);
+ svfloat32_t y00 = svget2_f32(y0, 0);
+ const svfloat32_t y01 = svget2_f32(y0, 1);
+ svfloat32_t y10 = svget2_f32(y1, 0);
+ const svfloat32_t y11 = svget2_f32(y1, 1);
+ y00 = ElementOp::op(pg, x0, y00);
+ y10 = ElementOp::op(pg, x0, y10);
+ y00 = ElementOp::merge(pg, y00, x1, y01);
+ y10 = ElementOp::merge(pg, y10, x1, y11);
+ svst1_f32(pg, dis, y00);
+ svst1_f32(pg, dis + lanes, y10);
+ y += lanes4;
+ dis += lanes2;
+ }
+ const svbool_t pg0 = svwhilelt_b32_u64(i, ny);
+ const svbool_t pg1 = svwhilelt_b32_u64(i + lanes, ny);
+ const svfloat32x2_t y0 = svld2_f32(pg0, y);
+ const svfloat32x2_t y1 = svld2_f32(pg1, y + lanes2);
+ svfloat32_t y00 = svget2_f32(y0, 0);
+ const svfloat32_t y01 = svget2_f32(y0, 1);
+ svfloat32_t y10 = svget2_f32(y1, 0);
+ const svfloat32_t y11 = svget2_f32(y1, 1);
+ y00 = ElementOp::op(pg0, x0, y00);
+ y10 = ElementOp::op(pg1, x0, y10);
+ y00 = ElementOp::merge(pg0, y00, x1, y01);
+ y10 = ElementOp::merge(pg1, y10, x1, y11);
+ svst1_f32(pg0, dis, y00);
+ svst1_f32(pg1, dis + lanes, y10);
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_d4(float* dis, const float* x, const float* y, size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes4 = lanes * 4;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svdup_n_f32(x[0]);
+ const svfloat32_t x1 = svdup_n_f32(x[1]);
+ const svfloat32_t x2 = svdup_n_f32(x[2]);
+ const svfloat32_t x3 = svdup_n_f32(x[3]);
+ size_t i = 0;
+ for (; i + lanes < ny; i += lanes) {
+ const svfloat32x4_t y0 = svld4_f32(pg, y);
+ svfloat32_t y00 = svget4_f32(y0, 0);
+ const svfloat32_t y01 = svget4_f32(y0, 1);
+ svfloat32_t y02 = svget4_f32(y0, 2);
+ const svfloat32_t y03 = svget4_f32(y0, 3);
+ y00 = ElementOp::op(pg, x0, y00);
+ y02 = ElementOp::op(pg, x2, y02);
+ y00 = ElementOp::merge(pg, y00, x1, y01);
+ y02 = ElementOp::merge(pg, y02, x3, y03);
+ y00 = svadd_f32_x(pg, y00, y02);
+ svst1_f32(pg, dis, y00);
+ y += lanes4;
+ dis += lanes;
+ }
+ const svbool_t pg0 = svwhilelt_b32_u64(i, ny);
+ const svfloat32x4_t y0 = svld4_f32(pg0, y);
+ svfloat32_t y00 = svget4_f32(y0, 0);
+ const svfloat32_t y01 = svget4_f32(y0, 1);
+ svfloat32_t y02 = svget4_f32(y0, 2);
+ const svfloat32_t y03 = svget4_f32(y0, 3);
+ y00 = ElementOp::op(pg0, x0, y00);
+ y02 = ElementOp::op(pg0, x2, y02);
+ y00 = ElementOp::merge(pg0, y00, x1, y01);
+ y02 = ElementOp::merge(pg0, y02, x3, y03);
+ y00 = svadd_f32_x(pg0, y00, y02);
+ svst1_f32(pg0, dis, y00);
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_d8(float* dis, const float* x, const float* y, size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes4 = lanes * 4;
+ const size_t lanes8 = lanes * 8;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svdup_n_f32(x[0]);
+ const svfloat32_t x1 = svdup_n_f32(x[1]);
+ const svfloat32_t x2 = svdup_n_f32(x[2]);
+ const svfloat32_t x3 = svdup_n_f32(x[3]);
+ const svfloat32_t x4 = svdup_n_f32(x[4]);
+ const svfloat32_t x5 = svdup_n_f32(x[5]);
+ const svfloat32_t x6 = svdup_n_f32(x[6]);
+ const svfloat32_t x7 = svdup_n_f32(x[7]);
+ size_t i = 0;
+ for (; i + lanes < ny; i += lanes) {
+ const svfloat32x4_t ya = svld4_f32(pg, y);
+ const svfloat32x4_t yb = svld4_f32(pg, y + lanes4);
+ const svfloat32_t ya0 = svget4_f32(ya, 0);
+ const svfloat32_t ya1 = svget4_f32(ya, 1);
+ const svfloat32_t ya2 = svget4_f32(ya, 2);
+ const svfloat32_t ya3 = svget4_f32(ya, 3);
+ const svfloat32_t yb0 = svget4_f32(yb, 0);
+ const svfloat32_t yb1 = svget4_f32(yb, 1);
+ const svfloat32_t yb2 = svget4_f32(yb, 2);
+ const svfloat32_t yb3 = svget4_f32(yb, 3);
+ svfloat32_t y0 = svuzp1(ya0, yb0);
+ const svfloat32_t y1 = svuzp1(ya1, yb1);
+ svfloat32_t y2 = svuzp1(ya2, yb2);
+ const svfloat32_t y3 = svuzp1(ya3, yb3);
+ svfloat32_t y4 = svuzp2(ya0, yb0);
+ const svfloat32_t y5 = svuzp2(ya1, yb1);
+ svfloat32_t y6 = svuzp2(ya2, yb2);
+ const svfloat32_t y7 = svuzp2(ya3, yb3);
+ y0 = ElementOp::op(pg, x0, y0);
+ y2 = ElementOp::op(pg, x2, y2);
+ y4 = ElementOp::op(pg, x4, y4);
+ y6 = ElementOp::op(pg, x6, y6);
+ y0 = ElementOp::merge(pg, y0, x1, y1);
+ y2 = ElementOp::merge(pg, y2, x3, y3);
+ y4 = ElementOp::merge(pg, y4, x5, y5);
+ y6 = ElementOp::merge(pg, y6, x7, y7);
+ y0 = svadd_f32_x(pg, y0, y2);
+ y4 = svadd_f32_x(pg, y4, y6);
+ y0 = svadd_f32_x(pg, y0, y4);
+ svst1_f32(pg, dis, y0);
+ y += lanes8;
+ dis += lanes;
+ }
+ const svbool_t pg0 = svwhilelt_b32_u64(i, ny);
+ const svbool_t pga = svwhilelt_b32_u64(i * 2, ny * 2);
+ const svbool_t pgb = svwhilelt_b32_u64(i * 2 + lanes, ny * 2);
+ const svfloat32x4_t ya = svld4_f32(pga, y);
+ const svfloat32x4_t yb = svld4_f32(pgb, y + lanes4);
+ const svfloat32_t ya0 = svget4_f32(ya, 0);
+ const svfloat32_t ya1 = svget4_f32(ya, 1);
+ const svfloat32_t ya2 = svget4_f32(ya, 2);
+ const svfloat32_t ya3 = svget4_f32(ya, 3);
+ const svfloat32_t yb0 = svget4_f32(yb, 0);
+ const svfloat32_t yb1 = svget4_f32(yb, 1);
+ const svfloat32_t yb2 = svget4_f32(yb, 2);
+ const svfloat32_t yb3 = svget4_f32(yb, 3);
+ svfloat32_t y0 = svuzp1(ya0, yb0);
+ const svfloat32_t y1 = svuzp1(ya1, yb1);
+ svfloat32_t y2 = svuzp1(ya2, yb2);
+ const svfloat32_t y3 = svuzp1(ya3, yb3);
+ svfloat32_t y4 = svuzp2(ya0, yb0);
+ const svfloat32_t y5 = svuzp2(ya1, yb1);
+ svfloat32_t y6 = svuzp2(ya2, yb2);
+ const svfloat32_t y7 = svuzp2(ya3, yb3);
+ y0 = ElementOp::op(pg0, x0, y0);
+ y2 = ElementOp::op(pg0, x2, y2);
+ y4 = ElementOp::op(pg0, x4, y4);
+ y6 = ElementOp::op(pg0, x6, y6);
+ y0 = ElementOp::merge(pg0, y0, x1, y1);
+ y2 = ElementOp::merge(pg0, y2, x3, y3);
+ y4 = ElementOp::merge(pg0, y4, x5, y5);
+ y6 = ElementOp::merge(pg0, y6, x7, y7);
+ y0 = svadd_f32_x(pg0, y0, y2);
+ y4 = svadd_f32_x(pg0, y4, y6);
+ y0 = svadd_f32_x(pg0, y0, y4);
+ svst1_f32(pg0, dis, y0);
+ y += lanes8;
+ dis += lanes;
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_lanes1(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes3 = lanes * 3;
+ const size_t lanes4 = lanes * 4;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svld1_f32(pg, x);
+ size_t i = 0;
+ for (; i + 3 < ny; i += 4) {
+ svfloat32_t y0 = svld1_f32(pg, y);
+ svfloat32_t y1 = svld1_f32(pg, y + lanes);
+ svfloat32_t y2 = svld1_f32(pg, y + lanes2);
+ svfloat32_t y3 = svld1_f32(pg, y + lanes3);
+ y += lanes4;
+ y0 = ElementOp::op(pg, x0, y0);
+ y1 = ElementOp::op(pg, x0, y1);
+ y2 = ElementOp::op(pg, x0, y2);
+ y3 = ElementOp::op(pg, x0, y3);
+ dis[i] = svaddv_f32(pg, y0);
+ dis[i + 1] = svaddv_f32(pg, y1);
+ dis[i + 2] = svaddv_f32(pg, y2);
+ dis[i + 3] = svaddv_f32(pg, y3);
+ }
+ for (; i < ny; ++i) {
+ svfloat32_t y0 = svld1_f32(pg, y);
+ y += lanes;
+ y0 = ElementOp::op(pg, x0, y0);
+ dis[i] = svaddv_f32(pg, y0);
+ }
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_lanes2(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes3 = lanes * 3;
+ const size_t lanes4 = lanes * 4;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svld1_f32(pg, x);
+ const svfloat32_t x1 = svld1_f32(pg, x + lanes);
+ size_t i = 0;
+ for (; i + 1 < ny; i += 2) {
+ svfloat32_t y00 = svld1_f32(pg, y);
+ const svfloat32_t y01 = svld1_f32(pg, y + lanes);
+ svfloat32_t y10 = svld1_f32(pg, y + lanes2);
+ const svfloat32_t y11 = svld1_f32(pg, y + lanes3);
+ y += lanes4;
+ y00 = ElementOp::op(pg, x0, y00);
+ y10 = ElementOp::op(pg, x0, y10);
+ y00 = ElementOp::merge(pg, y00, x1, y01);
+ y10 = ElementOp::merge(pg, y10, x1, y11);
+ dis[i] = svaddv_f32(pg, y00);
+ dis[i + 1] = svaddv_f32(pg, y10);
+ }
+ if (i < ny) {
+ svfloat32_t y0 = svld1_f32(pg, y);
+ const svfloat32_t y1 = svld1_f32(pg, y + lanes);
+ y0 = ElementOp::op(pg, x0, y0);
+ y0 = ElementOp::merge(pg, y0, x1, y1);
+ dis[i] = svaddv_f32(pg, y0);
+ }
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_lanes3(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes3 = lanes * 3;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svld1_f32(pg, x);
+ const svfloat32_t x1 = svld1_f32(pg, x + lanes);
+ const svfloat32_t x2 = svld1_f32(pg, x + lanes2);
+ for (size_t i = 0; i < ny; ++i) {
+ svfloat32_t y0 = svld1_f32(pg, y);
+ const svfloat32_t y1 = svld1_f32(pg, y + lanes);
+ svfloat32_t y2 = svld1_f32(pg, y + lanes2);
+ y += lanes3;
+ y0 = ElementOp::op(pg, x0, y0);
+ y0 = ElementOp::merge(pg, y0, x1, y1);
+ y0 = ElementOp::merge(pg, y0, x2, y2);
+ dis[i] = svaddv_f32(pg, y0);
+ }
+}
+
+template <typename ElementOp>
+void fvec_op_ny_sve_lanes4(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t ny) {
+ const size_t lanes = svcntw();
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes3 = lanes * 3;
+ const size_t lanes4 = lanes * 4;
+ const svbool_t pg = svptrue_b32();
+ const svfloat32_t x0 = svld1_f32(pg, x);
+ const svfloat32_t x1 = svld1_f32(pg, x + lanes);
+ const svfloat32_t x2 = svld1_f32(pg, x + lanes2);
+ const svfloat32_t x3 = svld1_f32(pg, x + lanes3);
+ for (size_t i = 0; i < ny; ++i) {
+ svfloat32_t y0 = svld1_f32(pg, y);
+ const svfloat32_t y1 = svld1_f32(pg, y + lanes);
+ svfloat32_t y2 = svld1_f32(pg, y + lanes2);
+ const svfloat32_t y3 = svld1_f32(pg, y + lanes3);
+ y += lanes4;
+ y0 = ElementOp::op(pg, x0, y0);
+ y2 = ElementOp::op(pg, x2, y2);
+ y0 = ElementOp::merge(pg, y0, x1, y1);
+ y2 = ElementOp::merge(pg, y2, x3, y3);
+ y0 = svadd_f32_x(pg, y0, y2);
+ dis[i] = svaddv_f32(pg, y0);
+ }
+}
+
+void fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ fvec_L2sqr_ny_ref(dis, x, y, d, ny);
+}
+
+void fvec_L2sqr_ny_transposed(
+ float* dis,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ return fvec_L2sqr_ny_y_transposed_ref(dis, x, y, y_sqlen, d, d_offset, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, d, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest_y_transposed(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_y_transposed_ref(
+ distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny);
+}
+
+float fvec_L1(const float* x, const float* y, size_t d) {
+ return fvec_L1_ref(x, y, d);
+}
+
+float fvec_Linf(const float* x, const float* y, size_t d) {
+ return fvec_Linf_ref(x, y, d);
+}
+
+void fvec_inner_products_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ const size_t lanes = svcntw();
+ switch (d) {
+ case 1:
+ fvec_op_ny_sve_d1<ElementOpIP>(dis, x, y, ny);
+ break;
+ case 2:
+ fvec_op_ny_sve_d2<ElementOpIP>(dis, x, y, ny);
+ break;
+ case 4:
+ fvec_op_ny_sve_d4<ElementOpIP>(dis, x, y, ny);
+ break;
+ case 8:
+ fvec_op_ny_sve_d8<ElementOpIP>(dis, x, y, ny);
+ break;
+ default:
+ if (d == lanes)
+ fvec_op_ny_sve_lanes1<ElementOpIP>(dis, x, y, ny);
+ else if (d == lanes * 2)
+ fvec_op_ny_sve_lanes2<ElementOpIP>(dis, x, y, ny);
+ else if (d == lanes * 3)
+ fvec_op_ny_sve_lanes3<ElementOpIP>(dis, x, y, ny);
+ else if (d == lanes * 4)
+ fvec_op_ny_sve_lanes4<ElementOpIP>(dis, x, y, ny);
+ else
+ fvec_inner_products_ny_ref(dis, x, y, d, ny);
+ break;
+ }
+}
+
+#elif defined(__aarch64__)
+
+// not optimized for ARM
+void fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ fvec_L2sqr_ny_ref(dis, x, y, d, ny);
+}
+
+void fvec_L2sqr_ny_transposed(
+ float* dis,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ return fvec_L2sqr_ny_y_transposed_ref(dis, x, y, y_sqlen, d, d_offset, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, d, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest_y_transposed(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_y_transposed_ref(
+ distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny);
+}
+
+float fvec_L1(const float* x, const float* y, size_t d) {
+ return fvec_L1_ref(x, y, d);
+}
+
+float fvec_Linf(const float* x, const float* y, size_t d) {
+ return fvec_Linf_ref(x, y, d);
+}
+
+void fvec_inner_products_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ fvec_inner_products_ny_ref(dis, x, y, d, ny);
+}
+
+#else
+// scalar implementation
+
+float fvec_L1(const float* x, const float* y, size_t d) {
+ return fvec_L1_ref(x, y, d);
+}
+
+float fvec_Linf(const float* x, const float* y, size_t d) {
+ return fvec_Linf_ref(x, y, d);
+}
+
+void fvec_L2sqr_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ fvec_L2sqr_ny_ref(dis, x, y, d, ny);
+}
+
+void fvec_L2sqr_ny_transposed(
+ float* dis,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ return fvec_L2sqr_ny_y_transposed_ref(dis, x, y, y_sqlen, d, d_offset, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_ref(distances_tmp_buffer, x, y, d, ny);
+}
+
+size_t fvec_L2sqr_ny_nearest_y_transposed(
+ float* distances_tmp_buffer,
+ const float* x,
+ const float* y,
+ const float* y_sqlen,
+ size_t d,
+ size_t d_offset,
+ size_t ny) {
+ return fvec_L2sqr_ny_nearest_y_transposed_ref(
+ distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny);
+}
+
+void fvec_inner_products_ny(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ fvec_inner_products_ny_ref(dis, x, y, d, ny);
+}
+
+#endif
+
+/***************************************************************************
+ * heavily optimized table computations
+ ***************************************************************************/
+
+[[maybe_unused]] static inline void fvec_madd_ref(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ for (size_t i = 0; i < n; i++)
+ c[i] = a[i] + bf * b[i];
+}
+
+#if defined(__AVX512F__)
+
+static inline void fvec_madd_avx512(
+ const size_t n,
+ const float* __restrict a,
+ const float bf,
+ const float* __restrict b,
+ float* __restrict c) {
+ const size_t n16 = n / 16;
+ const size_t n_for_masking = n % 16;
+
+ const __m512 bfmm = _mm512_set1_ps(bf);
+
+ size_t idx = 0;
+ for (idx = 0; idx < n16 * 16; idx += 16) {
+ const __m512 ax = _mm512_loadu_ps(a + idx);
+ const __m512 bx = _mm512_loadu_ps(b + idx);
+ const __m512 abmul = _mm512_fmadd_ps(bfmm, bx, ax);
+ _mm512_storeu_ps(c + idx, abmul);
+ }
+
+ if (n_for_masking > 0) {
+ const __mmask16 mask = (1 << n_for_masking) - 1;
+
+ const __m512 ax = _mm512_maskz_loadu_ps(mask, a + idx);
+ const __m512 bx = _mm512_maskz_loadu_ps(mask, b + idx);
+ const __m512 abmul = _mm512_fmadd_ps(bfmm, bx, ax);
+ _mm512_mask_storeu_ps(c + idx, mask, abmul);
+ }
+}
+
+#elif defined(__AVX2__)
+
+static inline void fvec_madd_avx2(
+ const size_t n,
+ const float* __restrict a,
+ const float bf,
+ const float* __restrict b,
+ float* __restrict c) {
+ //
+ const size_t n8 = n / 8;
+ const size_t n_for_masking = n % 8;
+
+ const __m256 bfmm = _mm256_set1_ps(bf);
+
+ size_t idx = 0;
+ for (idx = 0; idx < n8 * 8; idx += 8) {
+ const __m256 ax = _mm256_loadu_ps(a + idx);
+ const __m256 bx = _mm256_loadu_ps(b + idx);
+ const __m256 abmul = _mm256_fmadd_ps(bfmm, bx, ax);
+ _mm256_storeu_ps(c + idx, abmul);
+ }
+
+ if (n_for_masking > 0) {
+ __m256i mask;
+ switch (n_for_masking) {
+ case 1:
+ mask = _mm256_set_epi32(0, 0, 0, 0, 0, 0, 0, -1);
+ break;
+ case 2:
+ mask = _mm256_set_epi32(0, 0, 0, 0, 0, 0, -1, -1);
+ break;
+ case 3:
+ mask = _mm256_set_epi32(0, 0, 0, 0, 0, -1, -1, -1);
+ break;
+ case 4:
+ mask = _mm256_set_epi32(0, 0, 0, 0, -1, -1, -1, -1);
+ break;
+ case 5:
+ mask = _mm256_set_epi32(0, 0, 0, -1, -1, -1, -1, -1);
+ break;
+ case 6:
+ mask = _mm256_set_epi32(0, 0, -1, -1, -1, -1, -1, -1);
+ break;
+ case 7:
+ mask = _mm256_set_epi32(0, -1, -1, -1, -1, -1, -1, -1);
+ break;
+ }
+
+ const __m256 ax = _mm256_maskload_ps(a + idx, mask);
+ const __m256 bx = _mm256_maskload_ps(b + idx, mask);
+ const __m256 abmul = _mm256_fmadd_ps(bfmm, bx, ax);
+ _mm256_maskstore_ps(c + idx, mask, abmul);
+ }
+}
+
+#endif
+
+#ifdef __SSE3__
+
+[[maybe_unused]] static inline void fvec_madd_sse(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ n >>= 2;
+ __m128 bf4 = _mm_set_ps1(bf);
+ __m128* a4 = (__m128*)a;
+ __m128* b4 = (__m128*)b;
+ __m128* c4 = (__m128*)c;
+
+ while (n--) {
+ *c4 = _mm_add_ps(*a4, _mm_mul_ps(bf4, *b4));
+ b4++;
+ a4++;
+ c4++;
+ }
+}
+
+void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c) {
+#ifdef __AVX512F__
+ fvec_madd_avx512(n, a, bf, b, c);
+#elif __AVX2__
+ fvec_madd_avx2(n, a, bf, b, c);
+#else
+ if ((n & 3) == 0 && ((((long)a) | ((long)b) | ((long)c)) & 15) == 0)
+ fvec_madd_sse(n, a, bf, b, c);
+ else
+ fvec_madd_ref(n, a, bf, b, c);
+#endif
+}
+
+#elif defined(__ARM_FEATURE_SVE)
+
+void fvec_madd(
+ const size_t n,
+ const float* __restrict a,
+ const float bf,
+ const float* __restrict b,
+ float* __restrict c) {
+ const size_t lanes = static_cast<size_t>(svcntw());
+ const size_t lanes2 = lanes * 2;
+ const size_t lanes3 = lanes * 3;
+ const size_t lanes4 = lanes * 4;
+ size_t i = 0;
+ for (; i + lanes4 < n; i += lanes4) {
+ const auto mask = svptrue_b32();
+ const auto ai0 = svld1_f32(mask, a + i);
+ const auto ai1 = svld1_f32(mask, a + i + lanes);
+ const auto ai2 = svld1_f32(mask, a + i + lanes2);
+ const auto ai3 = svld1_f32(mask, a + i + lanes3);
+ const auto bi0 = svld1_f32(mask, b + i);
+ const auto bi1 = svld1_f32(mask, b + i + lanes);
+ const auto bi2 = svld1_f32(mask, b + i + lanes2);
+ const auto bi3 = svld1_f32(mask, b + i + lanes3);
+ const auto ci0 = svmla_n_f32_x(mask, ai0, bi0, bf);
+ const auto ci1 = svmla_n_f32_x(mask, ai1, bi1, bf);
+ const auto ci2 = svmla_n_f32_x(mask, ai2, bi2, bf);
+ const auto ci3 = svmla_n_f32_x(mask, ai3, bi3, bf);
+ svst1_f32(mask, c + i, ci0);
+ svst1_f32(mask, c + i + lanes, ci1);
+ svst1_f32(mask, c + i + lanes2, ci2);
+ svst1_f32(mask, c + i + lanes3, ci3);
+ }
+ const auto mask0 = svwhilelt_b32_u64(i, n);
+ const auto mask1 = svwhilelt_b32_u64(i + lanes, n);
+ const auto mask2 = svwhilelt_b32_u64(i + lanes2, n);
+ const auto mask3 = svwhilelt_b32_u64(i + lanes3, n);
+ const auto ai0 = svld1_f32(mask0, a + i);
+ const auto ai1 = svld1_f32(mask1, a + i + lanes);
+ const auto ai2 = svld1_f32(mask2, a + i + lanes2);
+ const auto ai3 = svld1_f32(mask3, a + i + lanes3);
+ const auto bi0 = svld1_f32(mask0, b + i);
+ const auto bi1 = svld1_f32(mask1, b + i + lanes);
+ const auto bi2 = svld1_f32(mask2, b + i + lanes2);
+ const auto bi3 = svld1_f32(mask3, b + i + lanes3);
+ const auto ci0 = svmla_n_f32_x(mask0, ai0, bi0, bf);
+ const auto ci1 = svmla_n_f32_x(mask1, ai1, bi1, bf);
+ const auto ci2 = svmla_n_f32_x(mask2, ai2, bi2, bf);
+ const auto ci3 = svmla_n_f32_x(mask3, ai3, bi3, bf);
+ svst1_f32(mask0, c + i, ci0);
+ svst1_f32(mask1, c + i + lanes, ci1);
+ svst1_f32(mask2, c + i + lanes2, ci2);
+ svst1_f32(mask3, c + i + lanes3, ci3);
+}
+
+#elif defined(__aarch64__)
+
+void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c) {
+ const size_t n_simd = n - (n & 3);
+ const float32x4_t bfv = vdupq_n_f32(bf);
+ size_t i;
+ for (i = 0; i < n_simd; i += 4) {
+ const float32x4_t ai = vld1q_f32(a + i);
+ const float32x4_t bi = vld1q_f32(b + i);
+ const float32x4_t ci = vfmaq_f32(ai, bfv, bi);
+ vst1q_f32(c + i, ci);
+ }
+ for (; i < n; ++i)
+ c[i] = a[i] + bf * b[i];
+}
+
+#else
+
+void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c) {
+ fvec_madd_ref(n, a, bf, b, c);
+}
+
+#endif
+
+static inline int fvec_madd_and_argmin_ref(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ float vmin = 1e20;
+ int imin = -1;
+
+ for (size_t i = 0; i < n; i++) {
+ c[i] = a[i] + bf * b[i];
+ if (c[i] < vmin) {
+ vmin = c[i];
+ imin = i;
+ }
+ }
+ return imin;
+}
+
+#ifdef __SSE3__
+
+static inline int fvec_madd_and_argmin_sse(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ n >>= 2;
+ __m128 bf4 = _mm_set_ps1(bf);
+ __m128 vmin4 = _mm_set_ps1(1e20);
+ __m128i imin4 = _mm_set1_epi32(-1);
+ __m128i idx4 = _mm_set_epi32(3, 2, 1, 0);
+ __m128i inc4 = _mm_set1_epi32(4);
+ __m128* a4 = (__m128*)a;
+ __m128* b4 = (__m128*)b;
+ __m128* c4 = (__m128*)c;
+
+ while (n--) {
+ __m128 vc4 = _mm_add_ps(*a4, _mm_mul_ps(bf4, *b4));
+ *c4 = vc4;
+ __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(vmin4, vc4));
+ // imin4 = _mm_blendv_epi8 (imin4, idx4, mask); // slower!
+
+ imin4 = _mm_or_si128(
+ _mm_and_si128(mask, idx4), _mm_andnot_si128(mask, imin4));
+ vmin4 = _mm_min_ps(vmin4, vc4);
+ b4++;
+ a4++;
+ c4++;
+ idx4 = _mm_add_epi32(idx4, inc4);
+ }
+
+ // 4 values -> 2
+ {
+ idx4 = _mm_shuffle_epi32(imin4, 3 << 2 | 2);
+ __m128 vc4 = _mm_shuffle_ps(vmin4, vmin4, 3 << 2 | 2);
+ __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(vmin4, vc4));
+ imin4 = _mm_or_si128(
+ _mm_and_si128(mask, idx4), _mm_andnot_si128(mask, imin4));
+ vmin4 = _mm_min_ps(vmin4, vc4);
+ }
+ // 2 values -> 1
+ {
+ idx4 = _mm_shuffle_epi32(imin4, 1);
+ __m128 vc4 = _mm_shuffle_ps(vmin4, vmin4, 1);
+ __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(vmin4, vc4));
+ imin4 = _mm_or_si128(
+ _mm_and_si128(mask, idx4), _mm_andnot_si128(mask, imin4));
+ // vmin4 = _mm_min_ps (vmin4, vc4);
+ }
+ return _mm_cvtsi128_si32(imin4);
+}
+
+int fvec_madd_and_argmin(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ if ((n & 3) == 0 && ((((long)a) | ((long)b) | ((long)c)) & 15) == 0)
+ return fvec_madd_and_argmin_sse(n, a, bf, b, c);
+ else
+ return fvec_madd_and_argmin_ref(n, a, bf, b, c);
+}
+
+#elif defined(__aarch64__)
+
+int fvec_madd_and_argmin(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ float32x4_t vminv = vdupq_n_f32(1e20);
+ uint32x4_t iminv = vdupq_n_u32(static_cast<uint32_t>(-1));
+ size_t i;
+ {
+ const size_t n_simd = n - (n & 3);
+ const uint32_t iota[] = {0, 1, 2, 3};
+ uint32x4_t iv = vld1q_u32(iota);
+ const uint32x4_t incv = vdupq_n_u32(4);
+ const float32x4_t bfv = vdupq_n_f32(bf);
+ for (i = 0; i < n_simd; i += 4) {
+ const float32x4_t ai = vld1q_f32(a + i);
+ const float32x4_t bi = vld1q_f32(b + i);
+ const float32x4_t ci = vfmaq_f32(ai, bfv, bi);
+ vst1q_f32(c + i, ci);
+ const uint32x4_t less_than = vcltq_f32(ci, vminv);
+ vminv = vminq_f32(ci, vminv);
+ iminv = vorrq_u32(
+ vandq_u32(less_than, iv),
+ vandq_u32(vmvnq_u32(less_than), iminv));
+ iv = vaddq_u32(iv, incv);
+ }
+ }
+ float vmin = vminvq_f32(vminv);
+ uint32_t imin;
+ {
+ const float32x4_t vminy = vdupq_n_f32(vmin);
+ const uint32x4_t equals = vceqq_f32(vminv, vminy);
+ imin = vminvq_u32(vorrq_u32(
+ vandq_u32(equals, iminv),
+ vandq_u32(
+ vmvnq_u32(equals),
+ vdupq_n_u32(std::numeric_limits<uint32_t>::max()))));
+ }
+ for (; i < n; ++i) {
+ c[i] = a[i] + bf * b[i];
+ if (c[i] < vmin) {
+ vmin = c[i];
+ imin = static_cast<uint32_t>(i);
+ }
+ }
+ return static_cast<int>(imin);
+}
+
+#else
+
+int fvec_madd_and_argmin(
+ size_t n,
+ const float* a,
+ float bf,
+ const float* b,
+ float* c) {
+ return fvec_madd_and_argmin_ref(n, a, bf, b, c);
+}
+
+#endif
+
+/***************************************************************************
+ * PQ tables computations
+ ***************************************************************************/
+
+namespace {
+
+/// compute the IP for dsub = 2 for 8 centroids and 4 sub-vectors at a time
+template <bool is_inner_product>
+void pq2_8cents_table(
+ const simd8float32 centroids[8],
+ const simd8float32 x,
+ float* out,
+ size_t ldo,
+ size_t nout = 4) {
+ simd8float32 ips[4];
+
+ for (int i = 0; i < 4; i++) {
+ simd8float32 p1, p2;
+ if (is_inner_product) {
+ p1 = x * centroids[2 * i];
+ p2 = x * centroids[2 * i + 1];
+ } else {
+ p1 = (x - centroids[2 * i]);
+ p1 = p1 * p1;
+ p2 = (x - centroids[2 * i + 1]);
+ p2 = p2 * p2;
+ }
+ ips[i] = hadd(p1, p2);
+ }
+
+ simd8float32 ip02a = geteven(ips[0], ips[1]);
+ simd8float32 ip02b = geteven(ips[2], ips[3]);
+ simd8float32 ip0 = getlow128(ip02a, ip02b);
+ simd8float32 ip2 = gethigh128(ip02a, ip02b);
+
+ simd8float32 ip13a = getodd(ips[0], ips[1]);
+ simd8float32 ip13b = getodd(ips[2], ips[3]);
+ simd8float32 ip1 = getlow128(ip13a, ip13b);
+ simd8float32 ip3 = gethigh128(ip13a, ip13b);
+
+ switch (nout) {
+ case 4:
+ ip3.storeu(out + 3 * ldo);
+ [[fallthrough]];
+ case 3:
+ ip2.storeu(out + 2 * ldo);
+ [[fallthrough]];
+ case 2:
+ ip1.storeu(out + 1 * ldo);
+ [[fallthrough]];
+ case 1:
+ ip0.storeu(out);
+ }
+}
+
+simd8float32 load_simd8float32_partial(const float* x, int n) {
+ ALIGNED(32) float tmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+ float* wp = tmp;
+ for (int i = 0; i < n; i++) {
+ *wp++ = *x++;
+ }
+ return simd8float32(tmp);
+}
+
+} // anonymous namespace
+
+void compute_PQ_dis_tables_dsub2(
+ size_t d,
+ size_t ksub,
+ const float* all_centroids,
+ size_t nx,
+ const float* x,
+ bool is_inner_product,
+ float* dis_tables) {
+ size_t M = d / 2;
+ FAISS_THROW_IF_NOT(ksub % 8 == 0);
+
+ for (size_t m0 = 0; m0 < M; m0 += 4) {
+ int m1 = std::min(M, m0 + 4);
+ for (int k0 = 0; k0 < ksub; k0 += 8) {
+ simd8float32 centroids[8];
+ for (int k = 0; k < 8; k++) {
+ ALIGNED(32) float centroid[8];
+ size_t wp = 0;
+ size_t rp = (m0 * ksub + k + k0) * 2;
+ for (int m = m0; m < m1; m++) {
+ centroid[wp++] = all_centroids[rp];
+ centroid[wp++] = all_centroids[rp + 1];
+ rp += 2 * ksub;
+ }
+ centroids[k] = simd8float32(centroid);
+ }
+ for (size_t i = 0; i < nx; i++) {
+ simd8float32 xi;
+ if (m1 == m0 + 4) {
+ xi.loadu(x + i * d + m0 * 2);
+ } else {
+ xi = load_simd8float32_partial(
+ x + i * d + m0 * 2, 2 * (m1 - m0));
+ }
+
+ if (is_inner_product) {
+ pq2_8cents_table<true>(
+ centroids,
+ xi,
+ dis_tables + (i * M + m0) * ksub + k0,
+ ksub,
+ m1 - m0);
+ } else {
+ pq2_8cents_table<false>(
+ centroids,
+ xi,
+ dis_tables + (i * M + m0) * ksub + k0,
+ ksub,
+ m1 - m0);
+ }
+ }
+ }
+ }
+}
+
+/*********************************************************
+ * Vector to vector functions
+ *********************************************************/
+
+void fvec_sub(size_t d, const float* a, const float* b, float* c) {
+ size_t i;
+ for (i = 0; i + 7 < d; i += 8) {
+ simd8float32 ci, ai, bi;
+ ai.loadu(a + i);
+ bi.loadu(b + i);
+ ci = ai - bi;
+ ci.storeu(c + i);
+ }
+ // finish non-multiple of 8 remainder
+ for (; i < d; i++) {
+ c[i] = a[i] - b[i];
+ }
+}
+
+void fvec_add(size_t d, const float* a, const float* b, float* c) {
+ size_t i;
+ for (i = 0; i + 7 < d; i += 8) {
+ simd8float32 ci, ai, bi;
+ ai.loadu(a + i);
+ bi.loadu(b + i);
+ ci = ai + bi;
+ ci.storeu(c + i);
+ }
+ // finish non-multiple of 8 remainder
+ for (; i < d; i++) {
+ c[i] = a[i] + b[i];
+ }
+}
+
+void fvec_add(size_t d, const float* a, float b, float* c) {
+ size_t i;
+ simd8float32 bv(b);
+ for (i = 0; i + 7 < d; i += 8) {
+ simd8float32 ci, ai;
+ ai.loadu(a + i);
+ ci = ai + bv;
+ ci.storeu(c + i);
+ }
+ // finish non-multiple of 8 remainder
+ for (; i < d; i++) {
+ c[i] = a[i] + b;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances-inl.h
new file mode 100644
index 0000000..da62930
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances-inl.h
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/** In this file are the implementations of extra metrics beyond L2
+ * and inner product */
+
+#include <faiss/MetricType.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/distances.h>
+#include <cmath>
+#include <type_traits>
+
+namespace faiss {
+
+template <MetricType mt>
+struct VectorDistance {
+ size_t d;
+ float metric_arg;
+ static constexpr bool is_similarity = is_similarity_metric(mt);
+
+ inline float operator()(const float* x, const float* y) const;
+
+ // heap template to use for this type of metric
+ using C = typename std::conditional<
+ is_similarity_metric(mt),
+ CMin<float, int64_t>,
+ CMax<float, int64_t>>::type;
+};
+
+template <>
+inline float VectorDistance<METRIC_L2>::operator()(
+ const float* x,
+ const float* y) const {
+ return fvec_L2sqr(x, y, d);
+}
+
+template <>
+inline float VectorDistance<METRIC_INNER_PRODUCT>::operator()(
+ const float* x,
+ const float* y) const {
+ return fvec_inner_product(x, y, d);
+}
+
+template <>
+inline float VectorDistance<METRIC_L1>::operator()(
+ const float* x,
+ const float* y) const {
+ return fvec_L1(x, y, d);
+}
+
+template <>
+inline float VectorDistance<METRIC_Linf>::operator()(
+ const float* x,
+ const float* y) const {
+ return fvec_Linf(x, y, d);
+ /*
+ float vmax = 0;
+ for (size_t i = 0; i < d; i++) {
+ float diff = fabs (x[i] - y[i]);
+ if (diff > vmax) vmax = diff;
+ }
+ return vmax;*/
+}
+
+template <>
+inline float VectorDistance<METRIC_Lp>::operator()(
+ const float* x,
+ const float* y) const {
+ float accu = 0;
+ for (size_t i = 0; i < d; i++) {
+ float diff = fabs(x[i] - y[i]);
+ accu += powf(diff, metric_arg);
+ }
+ return accu;
+}
+
+template <>
+inline float VectorDistance<METRIC_Canberra>::operator()(
+ const float* x,
+ const float* y) const {
+ float accu = 0;
+ for (size_t i = 0; i < d; i++) {
+ float xi = x[i], yi = y[i];
+ accu += fabs(xi - yi) / (fabs(xi) + fabs(yi));
+ }
+ return accu;
+}
+
+template <>
+inline float VectorDistance<METRIC_BrayCurtis>::operator()(
+ const float* x,
+ const float* y) const {
+ float accu_num = 0, accu_den = 0;
+ for (size_t i = 0; i < d; i++) {
+ float xi = x[i], yi = y[i];
+ accu_num += fabs(xi - yi);
+ accu_den += fabs(xi + yi);
+ }
+ return accu_num / accu_den;
+}
+
+template <>
+inline float VectorDistance<METRIC_JensenShannon>::operator()(
+ const float* x,
+ const float* y) const {
+ float accu = 0;
+ for (size_t i = 0; i < d; i++) {
+ float xi = x[i], yi = y[i];
+ float mi = 0.5 * (xi + yi);
+ float kl1 = -xi * log(mi / xi);
+ float kl2 = -yi * log(mi / yi);
+ accu += kl1 + kl2;
+ }
+ return 0.5 * accu;
+}
+
+template <>
+inline float VectorDistance<METRIC_Jaccard>::operator()(
+ const float* x,
+ const float* y) const {
+ // WARNING: this distance is defined only for positive input vectors.
+ // Providing vectors with negative values would lead to incorrect results.
+ float accu_num = 0, accu_den = 0;
+ for (size_t i = 0; i < d; i++) {
+ accu_num += fmin(x[i], y[i]);
+ accu_den += fmax(x[i], y[i]);
+ }
+ return accu_num / accu_den;
+}
+
+template <>
+inline float VectorDistance<METRIC_NaNEuclidean>::operator()(
+ const float* x,
+ const float* y) const {
+ // https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.nan_euclidean_distances.html
+ float accu = 0;
+ size_t present = 0;
+ for (size_t i = 0; i < d; i++) {
+ if (!std::isnan(x[i]) && !std::isnan(y[i])) {
+ float diff = x[i] - y[i];
+ accu += diff * diff;
+ present++;
+ }
+ }
+ if (present == 0) {
+ return NAN;
+ }
+ return float(d) / float(present) * accu;
+}
+
+template <>
+inline float VectorDistance<METRIC_ABS_INNER_PRODUCT>::operator()(
+ const float* x,
+ const float* y) const {
+ float accu = 0;
+ for (size_t i = 0; i < d; i++) {
+ accu += fabs(x[i] * y[i]);
+ }
+ return accu;
+}
+
+/***************************************************************************
+ * Dispatching function that takes a metric type and a consumer object
+ * the consumer object should contain a retun type T and a operation template
+ * function f() that is called to perform the operation. The first argument
+ * of the function is the VectorDistance object. The rest are passed in as is.
+ **************************************************************************/
+
+template <class Consumer, class... Types>
+typename Consumer::T dispatch_VectorDistance(
+ size_t d,
+ MetricType metric,
+ float metric_arg,
+ Consumer& consumer,
+ Types... args) {
+ switch (metric) {
+#define DISPATCH_VD(mt) \
+ case mt: { \
+ VectorDistance<mt> vd = {d, metric_arg}; \
+ return consumer.template f<VectorDistance<mt>>(vd, args...); \
+ }
+ DISPATCH_VD(METRIC_INNER_PRODUCT);
+ DISPATCH_VD(METRIC_L2);
+ DISPATCH_VD(METRIC_L1);
+ DISPATCH_VD(METRIC_Linf);
+ DISPATCH_VD(METRIC_Lp);
+ DISPATCH_VD(METRIC_Canberra);
+ DISPATCH_VD(METRIC_BrayCurtis);
+ DISPATCH_VD(METRIC_JensenShannon);
+ DISPATCH_VD(METRIC_Jaccard);
+ DISPATCH_VD(METRIC_NaNEuclidean);
+ DISPATCH_VD(METRIC_ABS_INNER_PRODUCT);
+ default:
+ FAISS_THROW_FMT("Invalid metric %d", metric);
+ }
+#undef DISPATCH_VD
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances.cpp
new file mode 100644
index 0000000..ee2cd51
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances.cpp
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/utils/extra_distances.h>
+
+#include <omp.h>
+#include <algorithm>
+#include <cmath>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/DistanceComputer.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/***************************************************************************
+ * Distance functions (other than L2 and IP)
+ ***************************************************************************/
+
+namespace {
+
+struct Run_pairwise_extra_distances {
+ using T = void;
+
+ template <class VD>
+ void f(VD vd,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ float* dis,
+ int64_t ldq,
+ int64_t ldb,
+ int64_t ldd) {
+#pragma omp parallel for if (nq > 10)
+ for (int64_t i = 0; i < nq; i++) {
+ const float* xqi = xq + i * ldq;
+ const float* xbj = xb;
+ float* disi = dis + ldd * i;
+
+ for (int64_t j = 0; j < nb; j++) {
+ disi[j] = vd(xqi, xbj);
+ xbj += ldb;
+ }
+ }
+ }
+};
+
+struct Run_knn_extra_metrics {
+ using T = void;
+ template <class VD>
+ void f(VD vd,
+ const float* x,
+ const float* y,
+ size_t nx,
+ size_t ny,
+ size_t k,
+ float* distances,
+ int64_t* labels) {
+ size_t d = vd.d;
+ using C = typename VD::C;
+ size_t check_period = InterruptCallback::get_period_hint(ny * d);
+ check_period *= omp_get_max_threads();
+
+ for (size_t i0 = 0; i0 < nx; i0 += check_period) {
+ size_t i1 = std::min(i0 + check_period, nx);
+
+#pragma omp parallel for
+ for (int64_t i = i0; i < i1; i++) {
+ const float* x_i = x + i * d;
+ const float* y_j = y;
+ size_t j;
+ float* simi = distances + k * i;
+ int64_t* idxi = labels + k * i;
+
+ // maxheap_heapify(k, simi, idxi);
+ heap_heapify<C>(k, simi, idxi);
+ for (j = 0; j < ny; j++) {
+ float disij = vd(x_i, y_j);
+
+ if (C::cmp(simi[0], disij)) {
+ heap_replace_top<C>(k, simi, idxi, disij, j);
+ }
+ y_j += d;
+ }
+ // maxheap_reorder(k, simi, idxi);
+ heap_reorder<C>(k, simi, idxi);
+ }
+ InterruptCallback::check();
+ }
+ }
+};
+
+template <class VD>
+struct ExtraDistanceComputer : FlatCodesDistanceComputer {
+ VD vd;
+ idx_t nb;
+ const float* q;
+ const float* b;
+
+ float symmetric_dis(idx_t i, idx_t j) final {
+ return vd(b + j * vd.d, b + i * vd.d);
+ }
+
+ float distance_to_code(const uint8_t* code) final {
+ return vd(q, (float*)code);
+ }
+
+ ExtraDistanceComputer(
+ const VD& vd,
+ const float* xb,
+ size_t nb,
+ const float* q = nullptr)
+ : FlatCodesDistanceComputer((uint8_t*)xb, vd.d * sizeof(float)),
+ vd(vd),
+ nb(nb),
+ q(q),
+ b(xb) {}
+
+ void set_query(const float* x) override {
+ q = x;
+ }
+};
+
+struct Run_get_distance_computer {
+ using T = FlatCodesDistanceComputer*;
+
+ template <class VD>
+ FlatCodesDistanceComputer* f(
+ VD vd,
+ const float* xb,
+ size_t nb,
+ const float* q = nullptr) {
+ return new ExtraDistanceComputer<VD>(vd, xb, nb, q);
+ }
+};
+
+} // anonymous namespace
+
+void pairwise_extra_distances(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ MetricType mt,
+ float metric_arg,
+ float* dis,
+ int64_t ldq,
+ int64_t ldb,
+ int64_t ldd) {
+ if (nq == 0 || nb == 0)
+ return;
+ if (ldq == -1)
+ ldq = d;
+ if (ldb == -1)
+ ldb = d;
+ if (ldd == -1)
+ ldd = nb;
+
+ Run_pairwise_extra_distances run;
+ dispatch_VectorDistance(
+ d, mt, metric_arg, run, nq, xq, nb, xb, dis, ldq, ldb, ldd);
+}
+
+void knn_extra_metrics(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ MetricType mt,
+ float metric_arg,
+ size_t k,
+ float* distances,
+ int64_t* indexes) {
+ Run_knn_extra_metrics run;
+ dispatch_VectorDistance(
+ d, mt, metric_arg, run, x, y, nx, ny, k, distances, indexes);
+}
+
+FlatCodesDistanceComputer* get_extra_distance_computer(
+ size_t d,
+ MetricType mt,
+ float metric_arg,
+ size_t nb,
+ const float* xb) {
+ Run_get_distance_computer run;
+ return dispatch_VectorDistance(d, mt, metric_arg, run, xb, nb);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances.h
new file mode 100644
index 0000000..ae3edf8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/extra_distances.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+/** In this file are the implementations of extra metrics beyond L2
+ * and inner product */
+
+#include <stdint.h>
+
+#include <faiss/Index.h>
+
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+struct FlatCodesDistanceComputer;
+
+void pairwise_extra_distances(
+ int64_t d,
+ int64_t nq,
+ const float* xq,
+ int64_t nb,
+ const float* xb,
+ MetricType mt,
+ float metric_arg,
+ float* dis,
+ int64_t ldq = -1,
+ int64_t ldb = -1,
+ int64_t ldd = -1);
+
+void knn_extra_metrics(
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t nx,
+ size_t ny,
+ MetricType mt,
+ float metric_arg,
+ size_t k,
+ float* distances,
+ int64_t* indexes);
+
+/** get a DistanceComputer that refers to this type of distance and
+ * indexes a flat array of size nb */
+FlatCodesDistanceComputer* get_extra_distance_computer(
+ size_t d,
+ MetricType mt,
+ float metric_arg,
+ size_t nb,
+ const float* xb);
+
+} // namespace faiss
+
+#include <faiss/utils/extra_distances-inl.h>
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-arm.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-arm.h
new file mode 100644
index 0000000..181d9a6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-arm.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <arm_neon.h>
+#include <cstdint>
+
+namespace faiss {
+
+inline uint16_t encode_fp16(float x) {
+ float32x4_t fx4 = vdupq_n_f32(x);
+ float16x4_t f16x4 = vcvt_f16_f32(fx4);
+ uint16x4_t ui16x4 = vreinterpret_u16_f16(f16x4);
+ return vduph_lane_u16(ui16x4, 3);
+}
+
+inline float decode_fp16(uint16_t x) {
+ uint16x4_t ui16x4 = vdup_n_u16(x);
+ float16x4_t f16x4 = vreinterpret_f16_u16(ui16x4);
+ float32x4_t fx4 = vcvt_f32_f16(f16x4);
+ return vdups_laneq_f32(fx4, 3);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-fp16c.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-fp16c.h
new file mode 100644
index 0000000..8bf7844
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-fp16c.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <immintrin.h>
+#include <cstdint>
+
+namespace faiss {
+
+inline uint16_t encode_fp16(float x) {
+ __m128 xf = _mm_set1_ps(x);
+ __m128i xi =
+ _mm_cvtps_ph(xf, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
+ return _mm_cvtsi128_si32(xi) & 0xffff;
+}
+
+inline float decode_fp16(uint16_t x) {
+ __m128i xi = _mm_set1_epi16(x);
+ __m128 xf = _mm_cvtph_ps(xi);
+ return _mm_cvtss_f32(xf);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-inl.h
new file mode 100644
index 0000000..6c376e0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16-inl.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <cstdint>
+
+namespace faiss {
+
+// non-intrinsic FP16 <-> FP32 code adapted from
+// https://github.com/ispc/ispc/blob/master/stdlib.ispc
+
+namespace {
+
+inline float floatbits(uint32_t x) {
+ void* xptr = &x;
+ return *(float*)xptr;
+}
+
+inline uint32_t intbits(float f) {
+ void* fptr = &f;
+ return *(uint32_t*)fptr;
+}
+
+} // namespace
+
+inline uint16_t encode_fp16(float f) {
+ // via Fabian "ryg" Giesen.
+ // https://gist.github.com/2156668
+ uint32_t sign_mask = 0x80000000u;
+ int32_t o;
+
+ uint32_t fint = intbits(f);
+ uint32_t sign = fint & sign_mask;
+ fint ^= sign;
+
+ // NOTE all the integer compares in this function can be safely
+ // compiled into signed compares since all operands are below
+ // 0x80000000. Important if you want fast straight SSE2 code (since
+ // there's no unsigned PCMPGTD).
+
+ // Inf or NaN (all exponent bits set)
+ // NaN->qNaN and Inf->Inf
+ // unconditional assignment here, will override with right value for
+ // the regular case below.
+ uint32_t f32infty = 255u << 23;
+ o = (fint > f32infty) ? 0x7e00u : 0x7c00u;
+
+ // (De)normalized number or zero
+ // update fint unconditionally to save the blending; we don't need it
+ // anymore for the Inf/NaN case anyway.
+
+ const uint32_t round_mask = ~0xfffu;
+ const uint32_t magic = 15u << 23;
+
+ // Shift exponent down, denormalize if necessary.
+ // NOTE This represents half-float denormals using single
+ // precision denormals. The main reason to do this is that
+ // there's no shift with per-lane variable shifts in SSE*, which
+ // we'd otherwise need. It has some funky side effects though:
+ // - This conversion will actually respect the FTZ (Flush To Zero)
+ // flag in MXCSR - if it's set, no half-float denormals will be
+ // generated. I'm honestly not sure whether this is good or
+ // bad. It's definitely interesting.
+ // - If the underlying HW doesn't support denormals (not an issue
+ // with Intel CPUs, but might be a problem on GPUs or PS3 SPUs),
+ // you will always get flush-to-zero behavior. This is bad,
+ // unless you're on a CPU where you don't care.
+ // - Denormals tend to be slow. FP32 denormals are rare in
+ // practice outside of things like recursive filters in DSP -
+ // not a typical half-float application. Whether FP16 denormals
+ // are rare in practice, I don't know. Whatever slow path your
+ // HW may or may not have for denormals, this may well hit it.
+ float fscale = floatbits(fint & round_mask) * floatbits(magic);
+ fscale = std::min(fscale, floatbits((31u << 23) - 0x1000u));
+ int32_t fint2 = intbits(fscale) - round_mask;
+
+ if (fint < f32infty)
+ o = fint2 >> 13; // Take the bits!
+
+ return (o | (sign >> 16));
+}
+
+inline float decode_fp16(uint16_t h) {
+ // https://gist.github.com/2144712
+ // Fabian "ryg" Giesen.
+
+ const uint32_t shifted_exp = 0x7c00u << 13; // exponent mask after shift
+
+ int32_t o = ((int32_t)(h & 0x7fffu)) << 13; // exponent/mantissa bits
+ int32_t exp = shifted_exp & o; // just the exponent
+ o += (int32_t)(127 - 15) << 23; // exponent adjust
+
+ int32_t infnan_val = o + ((int32_t)(128 - 16) << 23);
+ int32_t zerodenorm_val =
+ intbits(floatbits(o + (1u << 23)) - floatbits(113u << 23));
+ int32_t reg_val = (exp == 0) ? zerodenorm_val : o;
+
+ int32_t sign_bit = ((int32_t)(h & 0x8000u)) << 16;
+ return floatbits(((exp == shifted_exp) ? infnan_val : reg_val) | sign_bit);
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16.h
new file mode 100644
index 0000000..af97831
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/fp16.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+
+#include <faiss/impl/platform_macros.h>
+
+#if defined(__F16C__)
+#include <faiss/utils/fp16-fp16c.h>
+#elif defined(__aarch64__)
+#include <faiss/utils/fp16-arm.h>
+#else
+#include <faiss/utils/fp16-inl.h>
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming-inl.h
new file mode 100644
index 0000000..97d433d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming-inl.h
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+namespace faiss {
+
+// BitstringWriter and BitstringReader functions
+inline BitstringWriter::BitstringWriter(uint8_t* code, size_t code_size)
+ : code(code), code_size(code_size), i(0) {
+ memset(code, 0, code_size);
+}
+
+inline void BitstringWriter::write(uint64_t x, int nbit) {
+ assert(code_size * 8 >= nbit + i);
+ // nb of available bits in i / 8
+ int na = 8 - (i & 7);
+
+ if (nbit <= na) {
+ code[i >> 3] |= x << (i & 7);
+ i += nbit;
+ return;
+ } else {
+ size_t j = i >> 3;
+ code[j++] |= x << (i & 7);
+ i += nbit;
+ x >>= na;
+ while (x != 0) {
+ code[j++] |= x;
+ x >>= 8;
+ }
+ }
+}
+
+inline BitstringReader::BitstringReader(const uint8_t* code, size_t code_size)
+ : code(code), code_size(code_size), i(0) {}
+
+inline uint64_t BitstringReader::read(int nbit) {
+ assert(code_size * 8 >= nbit + i);
+ // nb of available bits in i / 8
+ int na = 8 - (i & 7);
+ // get available bits in current byte
+ uint64_t res = code[i >> 3] >> (i & 7);
+ if (nbit <= na) {
+ res &= (1 << nbit) - 1;
+ i += nbit;
+ return res;
+ } else {
+ int ofs = na;
+ size_t j = (i >> 3) + 1;
+ i += nbit;
+ nbit -= na;
+ while (nbit > 8) {
+ res |= ((uint64_t)code[j++]) << ofs;
+ ofs += 8;
+ nbit -= 8; // TODO remove nbit
+ }
+ uint64_t last_byte = code[j];
+ last_byte &= (1 << nbit) - 1;
+ res |= last_byte << ofs;
+ return res;
+ }
+}
+
+/** This class maintains a list of best distances seen so far.
+ *
+ * Since the distances are in a limited range (0 to nbit), the
+ * object maintains one list per possible distance, and fills
+ * in only the n-first lists, such that the sum of sizes of the
+ * n lists is below k.
+ */
+template <class HammingComputer>
+struct HCounterState {
+ int* counters;
+ int64_t* ids_per_dis;
+
+ HammingComputer hc;
+ int thres;
+ int count_lt;
+ int count_eq;
+ int k;
+
+ HCounterState(
+ int* counters,
+ int64_t* ids_per_dis,
+ const uint8_t* x,
+ int d,
+ int k)
+ : counters(counters),
+ ids_per_dis(ids_per_dis),
+ hc(x, d / 8),
+ thres(d + 1),
+ count_lt(0),
+ count_eq(0),
+ k(k) {}
+
+ void update_counter(const uint8_t* y, size_t j) {
+ int32_t dis = hc.hamming(y);
+
+ if (dis <= thres) {
+ if (dis < thres) {
+ ids_per_dis[dis * k + counters[dis]++] = j;
+ ++count_lt;
+ while (count_lt == k && thres > 0) {
+ --thres;
+ count_eq = counters[thres];
+ count_lt -= count_eq;
+ }
+ } else if (count_eq < k) {
+ ids_per_dis[dis * k + count_eq++] = j;
+ counters[dis] = count_eq;
+ }
+ }
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming.cpp
new file mode 100644
index 0000000..0641867
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming.cpp
@@ -0,0 +1,789 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+/*
+ * Implementation of Hamming related functions (distances, smallest distance
+ * selection with regular heap|radix and probabilistic heap|radix.
+ *
+ * IMPLEMENTATION NOTES
+ * Optimal speed is typically obtained for vector sizes of multiples of 64
+ * bits.
+ *
+ * hamdis_t is used for distances because at this time
+ * it is not clear how we will need to balance
+ * - flexibility in vector size (unclear more than 2^16 or even 2^8 bitvectors)
+ * - memory usage
+ * - cache-misses when dealing with large volumes of data (lower bits is better)
+ *
+ */
+
+#include <faiss/utils/hamming.h>
+
+#include <algorithm>
+#include <cstdio>
+#include <memory>
+#include <vector>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/utils/Heap.h>
+#include <faiss/utils/approx_topk_hamming/approx_topk_hamming.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+size_t hamming_batch_size = 65536;
+
+template <size_t nbits>
+void hammings(
+ const uint64_t* __restrict bs1,
+ const uint64_t* __restrict bs2,
+ size_t n1,
+ size_t n2,
+ hamdis_t* __restrict dis)
+
+{
+ size_t i, j;
+ const size_t nwords = nbits / 64;
+ for (i = 0; i < n1; i++) {
+ const uint64_t* __restrict bs1_ = bs1 + i * nwords;
+ hamdis_t* __restrict dis_ = dis + i * n2;
+ for (j = 0; j < n2; j++)
+ dis_[j] = hamming<nbits>(bs1_, bs2 + j * nwords);
+ }
+}
+
+void hammings(
+ const uint64_t* __restrict bs1,
+ const uint64_t* __restrict bs2,
+ size_t n1,
+ size_t n2,
+ size_t nbits,
+ hamdis_t* __restrict dis) {
+ size_t i, j;
+ const size_t nwords = nbits / 64;
+ for (i = 0; i < n1; i++) {
+ const uint64_t* __restrict bs1_ = bs1 + i * nwords;
+ hamdis_t* __restrict dis_ = dis + i * n2;
+ for (j = 0; j < n2; j++)
+ dis_[j] = hamming(bs1_, bs2 + j * nwords, nwords);
+ }
+}
+
+/* Count number of matches given a max threshold */
+template <size_t nbits>
+void hamming_count_thres(
+ const uint64_t* __restrict bs1,
+ const uint64_t* __restrict bs2,
+ size_t n1,
+ size_t n2,
+ hamdis_t ht,
+ size_t* __restrict nptr) {
+ const size_t nwords = nbits / 64;
+ size_t i, j, posm = 0;
+ const uint64_t* bs2_ = bs2;
+
+ for (i = 0; i < n1; i++) {
+ bs2 = bs2_;
+ for (j = 0; j < n2; j++) {
+ /* collect the match only if this satisfies the threshold */
+ if (hamming<nbits>(bs1, bs2) <= ht)
+ posm++;
+ bs2 += nwords;
+ }
+ bs1 += nwords; /* next signature */
+ }
+ *nptr = posm;
+}
+
+template <size_t nbits>
+void crosshamming_count_thres(
+ const uint64_t* __restrict dbs,
+ size_t n,
+ int ht,
+ size_t* __restrict nptr) {
+ const size_t nwords = nbits / 64;
+ size_t i, j, posm = 0;
+ const uint64_t* bs1 = dbs;
+ for (i = 0; i < n; i++) {
+ const uint64_t* bs2 = bs1 + 2;
+ for (j = i + 1; j < n; j++) {
+ /* collect the match only if this satisfies the threshold */
+ if (hamming<nbits>(bs1, bs2) <= ht)
+ posm++;
+ bs2 += nwords;
+ }
+ bs1 += nwords;
+ }
+ *nptr = posm;
+}
+
+template <size_t nbits>
+size_t match_hamming_thres(
+ const uint64_t* __restrict bs1,
+ const uint64_t* __restrict bs2,
+ size_t n1,
+ size_t n2,
+ int ht,
+ int64_t* __restrict idx,
+ hamdis_t* __restrict hams) {
+ const size_t nwords = nbits / 64;
+ size_t i, j, posm = 0;
+ hamdis_t h;
+ const uint64_t* bs2_ = bs2;
+ for (i = 0; i < n1; i++) {
+ bs2 = bs2_;
+ for (j = 0; j < n2; j++) {
+ /* Here perform the real work of computing the distance */
+ h = hamming<nbits>(bs1, bs2);
+
+ /* collect the match only if this satisfies the threshold */
+ if (h <= ht) {
+ /* Enough space to store another match ? */
+ *idx = i;
+ idx++;
+ *idx = j;
+ idx++;
+ *hams = h;
+ hams++;
+ posm++;
+ }
+ bs2 += nwords; /* next signature */
+ }
+ bs1 += nwords;
+ }
+ return posm;
+}
+
+namespace {
+
+/* Return closest neighbors w.r.t Hamming distance, using a heap. */
+template <class HammingComputer>
+void hammings_knn_hc(
+ int bytes_per_code,
+ int_maxheap_array_t* __restrict ha,
+ const uint8_t* __restrict bs1,
+ const uint8_t* __restrict bs2,
+ size_t n2,
+ bool order = true,
+ bool init_heap = true,
+ ApproxTopK_mode_t approx_topk_mode = ApproxTopK_mode_t::EXACT_TOPK,
+ const faiss::IDSelector* sel = nullptr) {
+ size_t k = ha->k;
+ if (init_heap)
+ ha->heapify();
+
+ const size_t block_size = hamming_batch_size;
+ for (size_t j0 = 0; j0 < n2; j0 += block_size) {
+ const size_t j1 = std::min(j0 + block_size, n2);
+#pragma omp parallel for
+ for (int64_t i = 0; i < ha->nh; i++) {
+ HammingComputer hc(bs1 + i * bytes_per_code, bytes_per_code);
+
+ const uint8_t* __restrict bs2_ = bs2 + j0 * bytes_per_code;
+ hamdis_t dis;
+ hamdis_t* __restrict bh_val_ = ha->val + i * k;
+ int64_t* __restrict bh_ids_ = ha->ids + i * k;
+
+ // if larger number of k is required, then ::bs_addn() needs to be
+ // used instead of ::addn()
+#define HANDLE_APPROX(NB, BD) \
+ case ApproxTopK_mode_t::APPROX_TOPK_BUCKETS_B##NB##_D##BD: \
+ FAISS_THROW_IF_NOT_FMT( \
+ k <= NB * BD, \
+ "The chosen mode (%d) of approximate top-k supports " \
+ "up to %d values, but %zd is requested.", \
+ (int)(ApproxTopK_mode_t::APPROX_TOPK_BUCKETS_B##NB##_D##BD), \
+ NB * BD, \
+ k); \
+ HeapWithBucketsForHamming32< \
+ CMax<hamdis_t, int64_t>, \
+ NB, \
+ BD, \
+ HammingComputer>:: \
+ addn(j1 - j0, hc, bs2_, k, bh_val_, bh_ids_, sel); \
+ break;
+
+ switch (approx_topk_mode) {
+ HANDLE_APPROX(8, 3)
+ HANDLE_APPROX(8, 2)
+ HANDLE_APPROX(16, 2)
+ HANDLE_APPROX(32, 2)
+ default: {
+ for (size_t j = j0; j < j1; j++, bs2_ += bytes_per_code) {
+ if (sel && !sel->is_member(j)) {
+ continue;
+ }
+ dis = hc.hamming(bs2_);
+ if (dis < bh_val_[0]) {
+ faiss::maxheap_replace_top<hamdis_t>(
+ k, bh_val_, bh_ids_, dis, j);
+ }
+ }
+ } break;
+ }
+ }
+ }
+ if (order)
+ ha->reorder();
+}
+
+/* Return closest neighbors w.r.t Hamming distance, using max count. */
+template <class HammingComputer>
+void hammings_knn_mc(
+ int bytes_per_code,
+ const uint8_t* __restrict a,
+ const uint8_t* __restrict b,
+ size_t na,
+ size_t nb,
+ size_t k,
+ int32_t* __restrict distances,
+ int64_t* __restrict labels,
+ const faiss::IDSelector* sel) {
+ const int nBuckets = bytes_per_code * 8 + 1;
+ std::vector<int> all_counters(na * nBuckets, 0);
+ std::unique_ptr<int64_t[]> all_ids_per_dis(new int64_t[na * nBuckets * k]);
+
+ std::vector<HCounterState<HammingComputer>> cs;
+ for (size_t i = 0; i < na; ++i) {
+ cs.push_back(HCounterState<HammingComputer>(
+ all_counters.data() + i * nBuckets,
+ all_ids_per_dis.get() + i * nBuckets * k,
+ a + i * bytes_per_code,
+ 8 * bytes_per_code,
+ k));
+ }
+
+ const size_t block_size = hamming_batch_size;
+ for (size_t j0 = 0; j0 < nb; j0 += block_size) {
+ const size_t j1 = std::min(j0 + block_size, nb);
+#pragma omp parallel for
+ for (int64_t i = 0; i < na; ++i) {
+ for (size_t j = j0; j < j1; ++j) {
+ if (!sel || sel->is_member(j)) {
+ cs[i].update_counter(b + j * bytes_per_code, j);
+ }
+ }
+ }
+ }
+
+ for (size_t i = 0; i < na; ++i) {
+ HCounterState<HammingComputer>& csi = cs[i];
+
+ int nres = 0;
+ for (int b_2 = 0; b_2 < nBuckets && nres < k; b_2++) {
+ for (int l = 0; l < csi.counters[b_2] && nres < k; l++) {
+ labels[i * k + nres] = csi.ids_per_dis[b_2 * k + l];
+ distances[i * k + nres] = b_2;
+ nres++;
+ }
+ }
+ while (nres < k) {
+ labels[i * k + nres] = -1;
+ distances[i * k + nres] = std::numeric_limits<int32_t>::max();
+ ++nres;
+ }
+ }
+}
+
+template <class HammingComputer>
+void hamming_range_search(
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t na,
+ size_t nb,
+ int radius,
+ size_t code_size,
+ RangeSearchResult* res,
+ const faiss::IDSelector* sel) {
+#pragma omp parallel
+ {
+ RangeSearchPartialResult pres(res);
+
+#pragma omp for
+ for (int64_t i = 0; i < na; i++) {
+ HammingComputer hc(a + i * code_size, code_size);
+ const uint8_t* yi = b;
+ RangeQueryResult& qres = pres.new_result(i);
+
+ for (size_t j = 0; j < nb; j++) {
+ if (!sel || sel->is_member(j)) {
+ int dis = hc.hamming(yi);
+ if (dis < radius) {
+ qres.add(dis, j);
+ }
+ }
+ yi += code_size;
+ }
+ }
+ pres.finalize();
+ }
+}
+
+struct Run_hammings_knn_hc {
+ using T = void;
+ template <class HammingComputer, class... Types>
+ void f(Types... args) {
+ hammings_knn_hc<HammingComputer>(args...);
+ }
+};
+
+struct Run_hammings_knn_mc {
+ using T = void;
+ template <class HammingComputer, class... Types>
+ void f(Types... args) {
+ hammings_knn_mc<HammingComputer>(args...);
+ }
+};
+
+struct Run_hamming_range_search {
+ using T = void;
+ template <class HammingComputer, class... Types>
+ void f(Types... args) {
+ hamming_range_search<HammingComputer>(args...);
+ }
+};
+
+} // namespace
+
+/* Functions to maps vectors to bits. Assume proper allocation done beforehand,
+ meaning that b should be be able to receive as many bits as x may produce. */
+
+/*
+ * dimension 0 corresponds to the least significant bit of b[0], or
+ * equivalently to the lsb of the first byte that is stored.
+ */
+void fvec2bitvec(const float* __restrict x, uint8_t* __restrict b, size_t d) {
+ for (int i = 0; i < d; i += 8) {
+ uint8_t w = 0;
+ uint8_t mask = 1;
+ int nj = i + 8 <= d ? 8 : d - i;
+ for (int j = 0; j < nj; j++) {
+ if (x[i + j] >= 0)
+ w |= mask;
+ mask <<= 1;
+ }
+ *b = w;
+ b++;
+ }
+}
+
+/* Same but for n vectors.
+ Ensure that the output b is byte-aligned (pad with 0s). */
+void fvecs2bitvecs(
+ const float* __restrict x,
+ uint8_t* __restrict b,
+ size_t d,
+ size_t n) {
+ const int64_t ncodes = ((d + 7) / 8);
+#pragma omp parallel for if (n > 100000)
+ for (int64_t i = 0; i < n; i++)
+ fvec2bitvec(x + i * d, b + i * ncodes, d);
+}
+
+void bitvecs2fvecs(
+ const uint8_t* __restrict b,
+ float* __restrict x,
+ size_t d,
+ size_t n) {
+ const int64_t ncodes = ((d + 7) / 8);
+#pragma omp parallel for if (n > 100000)
+ for (int64_t i = 0; i < n; i++) {
+ binary_to_real(d, b + i * ncodes, x + i * d);
+ }
+}
+
+/* Reverse bit (NOT a optimized function, only used for print purpose) */
+static uint64_t uint64_reverse_bits(uint64_t b) {
+ int i;
+ uint64_t revb = 0;
+ for (i = 0; i < 64; i++) {
+ revb <<= 1;
+ revb |= b & 1;
+ b >>= 1;
+ }
+ return revb;
+}
+
+/* print the bit vector */
+void bitvec_print(const uint8_t* b, size_t d) {
+ size_t i, j;
+ for (i = 0; i < d;) {
+ uint64_t brev = uint64_reverse_bits(*(uint64_t*)b);
+ for (j = 0; j < 64 && i < d; j++, i++) {
+ printf("%d", (int)(brev & 1));
+ brev >>= 1;
+ }
+ b += 8;
+ printf(" ");
+ }
+}
+
+void bitvec_shuffle(
+ size_t n,
+ size_t da,
+ size_t db,
+ const int* __restrict order,
+ const uint8_t* __restrict a,
+ uint8_t* __restrict b) {
+ for (size_t i = 0; i < db; i++) {
+ FAISS_THROW_IF_NOT(order[i] >= 0 && order[i] < da);
+ }
+ size_t lda = (da + 7) / 8;
+ size_t ldb = (db + 7) / 8;
+
+#pragma omp parallel for if (n > 10000)
+ for (int64_t i = 0; i < n; i++) {
+ const uint8_t* ai = a + i * lda;
+ uint8_t* bi = b + i * ldb;
+ memset(bi, 0, ldb);
+ for (size_t j = 0; j < db; j++) {
+ int o = order[j];
+ uint8_t the_bit = (ai[o >> 3] >> (o & 7)) & 1;
+ bi[j >> 3] |= the_bit << (j & 7);
+ }
+ }
+}
+
+/*----------------------------------------*/
+/* Hamming distance computation and k-nn */
+
+#define C64(x) ((uint64_t*)x)
+
+/* Compute a set of Hamming distances */
+void hammings(
+ const uint8_t* __restrict a,
+ const uint8_t* __restrict b,
+ size_t na,
+ size_t nb,
+ size_t ncodes,
+ hamdis_t* __restrict dis) {
+ FAISS_THROW_IF_NOT(ncodes % 8 == 0);
+ switch (ncodes) {
+ case 8:
+ faiss::hammings<64>(C64(a), C64(b), na, nb, dis);
+ return;
+ case 16:
+ faiss::hammings<128>(C64(a), C64(b), na, nb, dis);
+ return;
+ case 32:
+ faiss::hammings<256>(C64(a), C64(b), na, nb, dis);
+ return;
+ case 64:
+ faiss::hammings<512>(C64(a), C64(b), na, nb, dis);
+ return;
+ default:
+ faiss::hammings(C64(a), C64(b), na, nb, ncodes * 8, dis);
+ return;
+ }
+}
+
+void hammings_knn(
+ int_maxheap_array_t* __restrict ha,
+ const uint8_t* __restrict a,
+ const uint8_t* __restrict b,
+ size_t nb,
+ size_t ncodes,
+ int order) {
+ hammings_knn_hc(ha, a, b, nb, ncodes, order);
+}
+
+void hammings_knn_hc(
+ int_maxheap_array_t* __restrict ha,
+ const uint8_t* __restrict a,
+ const uint8_t* __restrict b,
+ size_t nb,
+ size_t ncodes,
+ int order,
+ ApproxTopK_mode_t approx_topk_mode,
+ const faiss::IDSelector* sel) {
+ Run_hammings_knn_hc r;
+ dispatch_HammingComputer(
+ ncodes,
+ r,
+ ncodes,
+ ha,
+ a,
+ b,
+ nb,
+ order,
+ true,
+ approx_topk_mode,
+ sel);
+}
+
+void hammings_knn_mc(
+ const uint8_t* __restrict a,
+ const uint8_t* __restrict b,
+ size_t na,
+ size_t nb,
+ size_t k,
+ size_t ncodes,
+ int32_t* __restrict distances,
+ int64_t* __restrict labels,
+ const faiss::IDSelector* sel) {
+ Run_hammings_knn_mc r;
+ dispatch_HammingComputer(
+ ncodes, r, ncodes, a, b, na, nb, k, distances, labels, sel);
+}
+
+void hamming_range_search(
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t na,
+ size_t nb,
+ int radius,
+ size_t code_size,
+ RangeSearchResult* result,
+ const faiss::IDSelector* sel) {
+ Run_hamming_range_search r;
+ dispatch_HammingComputer(
+ code_size, r, a, b, na, nb, radius, code_size, result, sel);
+}
+
+/* Count number of matches given a max threshold */
+void hamming_count_thres(
+ const uint8_t* bs1,
+ const uint8_t* bs2,
+ size_t n1,
+ size_t n2,
+ hamdis_t ht,
+ size_t ncodes,
+ size_t* nptr) {
+ switch (ncodes) {
+ case 8:
+ faiss::hamming_count_thres<64>(
+ C64(bs1), C64(bs2), n1, n2, ht, nptr);
+ return;
+ case 16:
+ faiss::hamming_count_thres<128>(
+ C64(bs1), C64(bs2), n1, n2, ht, nptr);
+ return;
+ case 32:
+ faiss::hamming_count_thres<256>(
+ C64(bs1), C64(bs2), n1, n2, ht, nptr);
+ return;
+ case 64:
+ faiss::hamming_count_thres<512>(
+ C64(bs1), C64(bs2), n1, n2, ht, nptr);
+ return;
+ default:
+ FAISS_THROW_FMT("not implemented for %zu bits", ncodes);
+ }
+}
+
+/* Count number of cross-matches given a threshold */
+void crosshamming_count_thres(
+ const uint8_t* dbs,
+ size_t n,
+ hamdis_t ht,
+ size_t ncodes,
+ size_t* nptr) {
+ switch (ncodes) {
+ case 8:
+ faiss::crosshamming_count_thres<64>(C64(dbs), n, ht, nptr);
+ return;
+ case 16:
+ faiss::crosshamming_count_thres<128>(C64(dbs), n, ht, nptr);
+ return;
+ case 32:
+ faiss::crosshamming_count_thres<256>(C64(dbs), n, ht, nptr);
+ return;
+ case 64:
+ faiss::crosshamming_count_thres<512>(C64(dbs), n, ht, nptr);
+ return;
+ default:
+ FAISS_THROW_FMT("not implemented for %zu bits", ncodes);
+ }
+}
+
+/* Returns all matches given a threshold */
+size_t match_hamming_thres(
+ const uint8_t* bs1,
+ const uint8_t* bs2,
+ size_t n1,
+ size_t n2,
+ hamdis_t ht,
+ size_t ncodes,
+ int64_t* idx,
+ hamdis_t* dis) {
+ switch (ncodes) {
+ case 8:
+ return faiss::match_hamming_thres<64>(
+ C64(bs1), C64(bs2), n1, n2, ht, idx, dis);
+ case 16:
+ return faiss::match_hamming_thres<128>(
+ C64(bs1), C64(bs2), n1, n2, ht, idx, dis);
+ case 32:
+ return faiss::match_hamming_thres<256>(
+ C64(bs1), C64(bs2), n1, n2, ht, idx, dis);
+ case 64:
+ return faiss::match_hamming_thres<512>(
+ C64(bs1), C64(bs2), n1, n2, ht, idx, dis);
+ default:
+ FAISS_THROW_FMT("not implemented for %zu bits", ncodes);
+ return 0;
+ }
+}
+
+#undef C64
+
+/*************************************
+ * generalized Hamming distances
+ ************************************/
+
+template <class HammingComputer>
+static void hamming_dis_inner_loop(
+ const uint8_t* __restrict ca,
+ const uint8_t* __restrict cb,
+ size_t nb,
+ size_t code_size,
+ int k,
+ hamdis_t* __restrict bh_val_,
+ int64_t* __restrict bh_ids_) {
+ HammingComputer hc(ca, code_size);
+
+ for (size_t j = 0; j < nb; j++) {
+ int ndiff = hc.hamming(cb);
+ cb += code_size;
+ if (ndiff < bh_val_[0]) {
+ maxheap_replace_top<hamdis_t>(k, bh_val_, bh_ids_, ndiff, j);
+ }
+ }
+}
+
+void generalized_hammings_knn_hc(
+ int_maxheap_array_t* __restrict ha,
+ const uint8_t* __restrict a,
+ const uint8_t* __restrict b,
+ size_t nb,
+ size_t code_size,
+ int ordered) {
+ int na = ha->nh;
+ int k = ha->k;
+
+ if (ordered)
+ ha->heapify();
+
+#pragma omp parallel for
+ for (int i = 0; i < na; i++) {
+ const uint8_t* __restrict ca = a + i * code_size;
+ const uint8_t* __restrict cb = b;
+
+ hamdis_t* __restrict bh_val_ = ha->val + i * k;
+ int64_t* __restrict bh_ids_ = ha->ids + i * k;
+
+ switch (code_size) {
+ case 8:
+ hamming_dis_inner_loop<GenHammingComputer8>(
+ ca, cb, nb, 8, k, bh_val_, bh_ids_);
+ break;
+ case 16:
+ hamming_dis_inner_loop<GenHammingComputer16>(
+ ca, cb, nb, 16, k, bh_val_, bh_ids_);
+ break;
+ case 32:
+ hamming_dis_inner_loop<GenHammingComputer32>(
+ ca, cb, nb, 32, k, bh_val_, bh_ids_);
+ break;
+ default:
+ hamming_dis_inner_loop<GenHammingComputerM8>(
+ ca, cb, nb, code_size, k, bh_val_, bh_ids_);
+ break;
+ }
+ }
+
+ if (ordered)
+ ha->reorder();
+}
+
+void pack_bitstrings(
+ size_t n,
+ size_t M,
+ int nbit,
+ const int32_t* unpacked,
+ uint8_t* packed,
+ size_t code_size) {
+ FAISS_THROW_IF_NOT(code_size >= (M * nbit + 7) / 8);
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const int32_t* in = unpacked + i * M;
+ uint8_t* out = packed + i * code_size;
+ BitstringWriter wr(out, code_size);
+ for (int j = 0; j < M; j++) {
+ wr.write(in[j], nbit);
+ }
+ }
+}
+
+void pack_bitstrings(
+ size_t n,
+ size_t M,
+ const int32_t* nbit,
+ const int32_t* unpacked,
+ uint8_t* packed,
+ size_t code_size) {
+ int totbit = 0;
+ for (int j = 0; j < M; j++) {
+ totbit += nbit[j];
+ }
+ FAISS_THROW_IF_NOT(code_size >= (totbit + 7) / 8);
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const int32_t* in = unpacked + i * M;
+ uint8_t* out = packed + i * code_size;
+ BitstringWriter wr(out, code_size);
+ for (int j = 0; j < M; j++) {
+ wr.write(in[j], nbit[j]);
+ }
+ }
+}
+
+void unpack_bitstrings(
+ size_t n,
+ size_t M,
+ int nbit,
+ const uint8_t* packed,
+ size_t code_size,
+ int32_t* unpacked) {
+ FAISS_THROW_IF_NOT(code_size >= (M * nbit + 7) / 8);
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const uint8_t* in = packed + i * code_size;
+ int32_t* out = unpacked + i * M;
+ BitstringReader rd(in, code_size);
+ for (int j = 0; j < M; j++) {
+ out[j] = rd.read(nbit);
+ }
+ }
+}
+
+void unpack_bitstrings(
+ size_t n,
+ size_t M,
+ const int32_t* nbit,
+ const uint8_t* packed,
+ size_t code_size,
+ int32_t* unpacked) {
+ int totbit = 0;
+ for (int j = 0; j < M; j++) {
+ totbit += nbit[j];
+ }
+ FAISS_THROW_IF_NOT(code_size >= (totbit + 7) / 8);
+#pragma omp parallel for if (n > 1000)
+ for (int64_t i = 0; i < n; i++) {
+ const uint8_t* in = packed + i * code_size;
+ int32_t* out = unpacked + i * M;
+ BitstringReader rd(in, code_size);
+ for (int j = 0; j < M; j++) {
+ out[j] = rd.read(nbit[j]);
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming.h
new file mode 100644
index 0000000..3f3f488
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming.h
@@ -0,0 +1,291 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/*
+ * Hamming distances. The binary vector dimensionality should be a
+ * multiple of 8, as the elementary operations operate on bytes. If
+ * you need other sizes, just pad with 0s (this is done by function
+ * fvecs2bitvecs).
+ *
+ * User-defined type hamdis_t is used for distances because at this time
+ * it is still uncler clear how we will need to balance
+ * - flexibility in vector size (may need 16- or even 8-bit vectors)
+ * - memory usage
+ * - cache-misses when dealing with large volumes of data (fewer bits is better)
+ *
+ * hamdis_t is defined in utils/hamming_distance/common.h
+ */
+
+#ifndef FAISS_hamming_h
+#define FAISS_hamming_h
+
+#include <stdint.h>
+
+#include <faiss/impl/IDSelector.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+
+// Low-level Hamming distance computations and hamdis_t.
+#include <faiss/utils/hamming_distance/hamdis-inl.h>
+
+#include <faiss/utils/approx_topk/mode.h>
+
+namespace faiss {
+
+/**************************************************
+ * General bit vector functions
+ **************************************************/
+
+struct RangeSearchResult;
+
+void bitvec_print(const uint8_t* b, size_t d);
+
+/* Functions for casting vectors of regular types to compact bits.
+ They assume proper allocation done beforehand, meaning that b
+ should be be able to receive as many bits as x may produce. */
+
+/* Makes an array of bits from the signs of a float array. The length
+ of the output array b is rounded up to byte size (allocate
+ accordingly) */
+void fvecs2bitvecs(const float* x, uint8_t* b, size_t d, size_t n);
+
+void bitvecs2fvecs(const uint8_t* b, float* x, size_t d, size_t n);
+
+void fvec2bitvec(const float* x, uint8_t* b, size_t d);
+
+/** Shuffle the bits from b(i, j) := a(i, order[j])
+ */
+void bitvec_shuffle(
+ size_t n,
+ size_t da,
+ size_t db,
+ const int* order,
+ const uint8_t* a,
+ uint8_t* b);
+
+/***********************************************
+ * Generic reader/writer for bit strings
+ ***********************************************/
+
+struct BitstringWriter {
+ uint8_t* code;
+ size_t code_size;
+ size_t i; // current bit offset
+
+ // code_size in bytes
+ BitstringWriter(uint8_t* code, size_t code_size);
+
+ // write the nbit low bits of x
+ void write(uint64_t x, int nbit);
+};
+
+struct BitstringReader {
+ const uint8_t* code;
+ size_t code_size;
+ size_t i;
+
+ // code_size in bytes
+ BitstringReader(const uint8_t* code, size_t code_size);
+
+ // read nbit bits from the code
+ uint64_t read(int nbit);
+};
+
+/**************************************************
+ * Hamming distance computation functions
+ **************************************************/
+
+FAISS_API extern size_t hamming_batch_size;
+
+/** Compute a set of Hamming distances between na and nb binary vectors
+ *
+ * @param a size na * nbytespercode
+ * @param b size nb * nbytespercode
+ * @param nbytespercode should be multiple of 8
+ * @param dis output distances, size na * nb
+ */
+void hammings(
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t na,
+ size_t nb,
+ size_t nbytespercode,
+ hamdis_t* dis);
+
+/** Return the k smallest Hamming distances for a set of binary query vectors,
+ * using a max heap.
+ * @param a queries, size ha->nh * ncodes
+ * @param b database, size nb * ncodes
+ * @param nb number of database vectors
+ * @param ncodes size of the binary codes (bytes)
+ * @param ordered if != 0: order the results by decreasing distance
+ * (may be bottleneck for k/n > 0.01)
+ * @param approx_topk_mode allows to use approximate top-k facilities
+ * to speedup heap
+ */
+void hammings_knn_hc(
+ int_maxheap_array_t* ha,
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t nb,
+ size_t ncodes,
+ int ordered,
+ ApproxTopK_mode_t approx_topk_mode = ApproxTopK_mode_t::EXACT_TOPK,
+ const faiss::IDSelector* sel = nullptr);
+
+/* Legacy alias to hammings_knn_hc. */
+void hammings_knn(
+ int_maxheap_array_t* ha,
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t nb,
+ size_t ncodes,
+ int ordered);
+
+/** Return the k smallest Hamming distances for a set of binary query vectors,
+ * using counting max.
+ * @param a queries, size na * ncodes
+ * @param b database, size nb * ncodes
+ * @param na number of query vectors
+ * @param nb number of database vectors
+ * @param k number of vectors/distances to return
+ * @param ncodes size of the binary codes (bytes)
+ * @param distances output distances from each query vector to its k nearest
+ * neighbors
+ * @param labels output ids of the k nearest neighbors to each query vector
+ */
+void hammings_knn_mc(
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t na,
+ size_t nb,
+ size_t k,
+ size_t ncodes,
+ int32_t* distances,
+ int64_t* labels,
+ const faiss::IDSelector* sel = nullptr);
+
+/** same as hammings_knn except we are doing a range search with radius */
+void hamming_range_search(
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t na,
+ size_t nb,
+ int radius,
+ size_t ncodes,
+ RangeSearchResult* result,
+ const faiss::IDSelector* sel = nullptr);
+
+/* Counting the number of matches or of cross-matches (without returning them)
+ For use with function that assume pre-allocated memory */
+void hamming_count_thres(
+ const uint8_t* bs1,
+ const uint8_t* bs2,
+ size_t n1,
+ size_t n2,
+ hamdis_t ht,
+ size_t ncodes,
+ size_t* nptr);
+
+/* Return all Hamming distances/index passing a thres. Pre-allocation of output
+ is required. Use hamming_count_thres to determine the proper size. */
+size_t match_hamming_thres(
+ const uint8_t* bs1,
+ const uint8_t* bs2,
+ size_t n1,
+ size_t n2,
+ hamdis_t ht,
+ size_t ncodes,
+ int64_t* idx,
+ hamdis_t* dis);
+
+/* Cross-matching in a set of vectors */
+void crosshamming_count_thres(
+ const uint8_t* dbs,
+ size_t n,
+ hamdis_t ht,
+ size_t ncodes,
+ size_t* nptr);
+
+/* compute the Hamming distances between two codewords of nwords*64 bits */
+hamdis_t hamming(const uint64_t* bs1, const uint64_t* bs2, size_t nwords);
+
+/** generalized Hamming distances (= count number of code bytes that
+ are the same) */
+void generalized_hammings_knn_hc(
+ int_maxheap_array_t* ha,
+ const uint8_t* a,
+ const uint8_t* b,
+ size_t nb,
+ size_t code_size,
+ int ordered = true);
+
+/** Pack a set of n codes of size M * nbit
+ *
+ * @param n number of codes to pack
+ * @param M number of elementary codes per code
+ * @param nbit number of bits per elementary code
+ * @param unpacked input unpacked codes, size (n, M)
+ * @param packed output packed codes, size (n, code_size)
+ * @param code_size should be >= ceil(M * nbit / 8)
+ */
+void pack_bitstrings(
+ size_t n,
+ size_t M,
+ int nbit,
+ const int32_t* unpacked,
+ uint8_t* packed,
+ size_t code_size);
+
+/** Pack a set of n codes of variable sizes
+ *
+ * @param nbit number of bits per entry (size M)
+ */
+void pack_bitstrings(
+ size_t n,
+ size_t M,
+ const int32_t* nbits,
+ const int32_t* unpacked,
+ uint8_t* packed,
+ size_t code_size);
+
+/** Unpack a set of n codes of size M * nbit
+ *
+ * @param n number of codes to pack
+ * @param M number of elementary codes per code
+ * @param nbit number of bits per elementary code
+ * @param unpacked input unpacked codes, size (n, M)
+ * @param packed output packed codes, size (n, code_size)
+ * @param code_size should be >= ceil(M * nbit / 8)
+ */
+void unpack_bitstrings(
+ size_t n,
+ size_t M,
+ int nbit,
+ const uint8_t* packed,
+ size_t code_size,
+ int32_t* unpacked);
+
+/** Unpack a set of n codes of variable sizes
+ *
+ * @param nbit number of bits per entry (size M)
+ */
+void unpack_bitstrings(
+ size_t n,
+ size_t M,
+ const int32_t* nbits,
+ const uint8_t* packed,
+ size_t code_size,
+ int32_t* unpacked);
+
+} // namespace faiss
+
+#include <faiss/utils/hamming-inl.h>
+
+#endif /* FAISS_hamming_h */
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/avx2-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/avx2-inl.h
new file mode 100644
index 0000000..20a613d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/avx2-inl.h
@@ -0,0 +1,462 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef HAMMING_AVX2_INL_H
+#define HAMMING_AVX2_INL_H
+
+// AVX2 version
+
+#include <cassert>
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/impl/platform_macros.h>
+
+#include <immintrin.h>
+
+namespace faiss {
+
+/* Elementary Hamming distance computation: unoptimized */
+template <size_t nbits, typename T>
+inline T hamming(const uint8_t* bs1, const uint8_t* bs2) {
+ const size_t nbytes = nbits / 8;
+ size_t i;
+ T h = 0;
+ for (i = 0; i < nbytes; i++) {
+ h += (T)hamdis_tab_ham_bytes[bs1[i] ^ bs2[i]];
+ }
+ return h;
+}
+
+/* Hamming distances for multiples of 64 bits */
+template <size_t nbits>
+inline hamdis_t hamming(const uint64_t* bs1, const uint64_t* bs2) {
+ const size_t nwords = nbits / 64;
+ size_t i;
+ hamdis_t h = 0;
+ for (i = 0; i < nwords; i++) {
+ h += popcount64(bs1[i] ^ bs2[i]);
+ }
+ return h;
+}
+
+/* specialized (optimized) functions */
+template <>
+inline hamdis_t hamming<64>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]);
+}
+
+template <>
+inline hamdis_t hamming<128>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]) + popcount64(pa[1] ^ pb[1]);
+}
+
+template <>
+inline hamdis_t hamming<256>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]) + popcount64(pa[1] ^ pb[1]) +
+ popcount64(pa[2] ^ pb[2]) + popcount64(pa[3] ^ pb[3]);
+}
+
+/* Hamming distances for multiple of 64 bits */
+inline hamdis_t hamming(
+ const uint64_t* bs1,
+ const uint64_t* bs2,
+ size_t nwords) {
+ hamdis_t h = 0;
+ for (size_t i = 0; i < nwords; i++) {
+ h += popcount64(bs1[i] ^ bs2[i]);
+ }
+ return h;
+}
+
+/******************************************************************
+ * The HammingComputer series of classes compares a single code of
+ * size 4 to 32 to incoming codes. They are intended for use as a
+ * template class where it would be inefficient to switch on the code
+ * size in the inner loop. Hopefully the compiler will inline the
+ * hamming() functions and put the a0, a1, ... in registers.
+ ******************************************************************/
+
+struct HammingComputer4 {
+ uint32_t a0;
+
+ HammingComputer4() {}
+
+ HammingComputer4(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 4);
+ a0 = *(uint32_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint32_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 4;
+ }
+};
+
+struct HammingComputer8 {
+ uint64_t a0;
+
+ HammingComputer8() {}
+
+ HammingComputer8(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+struct HammingComputer16 {
+ uint64_t a0, a1;
+
+ HammingComputer16() {}
+
+ HammingComputer16(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+// when applied to an array, 1/2 of the 64-bit accesses are unaligned.
+// This incurs a penalty of ~10% wrt. fully aligned accesses.
+struct HammingComputer20 {
+ uint64_t a0, a1;
+ uint32_t a2;
+
+ HammingComputer20() {}
+
+ HammingComputer20(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 20);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(*(uint32_t*)(b + 2) ^ a2);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 20;
+ }
+};
+
+struct HammingComputer32 {
+ uint64_t a0, a1, a2, a3;
+
+ HammingComputer32() {}
+
+ HammingComputer32(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(b[2] ^ a2) + popcount64(b[3] ^ a3);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+struct HammingComputer64 {
+ uint64_t a0, a1, a2, a3, a4, a5, a6, a7;
+
+ HammingComputer64() {}
+
+ HammingComputer64(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 64);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ a4 = a[4];
+ a5 = a[5];
+ a6 = a[6];
+ a7 = a[7];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(b[2] ^ a2) + popcount64(b[3] ^ a3) +
+ popcount64(b[4] ^ a4) + popcount64(b[5] ^ a5) +
+ popcount64(b[6] ^ a6) + popcount64(b[7] ^ a7);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 64;
+ }
+};
+
+struct HammingComputerDefault {
+ const uint8_t* a8;
+ int quotient8;
+ int remainder8;
+
+ HammingComputerDefault() {}
+
+ HammingComputerDefault(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8_2, int code_size) {
+ this->a8 = a8_2;
+ quotient8 = code_size / 8;
+ remainder8 = code_size % 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ int accu = 0;
+
+ const uint64_t* a64 = reinterpret_cast<const uint64_t*>(a8);
+ const uint64_t* b64 = reinterpret_cast<const uint64_t*>(b8);
+ int i = 0, len = quotient8;
+ switch (len & 7) {
+ default:
+ while (len > 7) {
+ len -= 8;
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 7:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 6:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 5:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 4:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 3:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 2:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 1:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ }
+ }
+ if (remainder8) {
+ const uint8_t* a = a8 + 8 * quotient8;
+ const uint8_t* b = b8 + 8 * quotient8;
+ switch (remainder8) {
+ case 7:
+ accu += hamdis_tab_ham_bytes[a[6] ^ b[6]];
+ [[fallthrough]];
+ case 6:
+ accu += hamdis_tab_ham_bytes[a[5] ^ b[5]];
+ [[fallthrough]];
+ case 5:
+ accu += hamdis_tab_ham_bytes[a[4] ^ b[4]];
+ [[fallthrough]];
+ case 4:
+ accu += hamdis_tab_ham_bytes[a[3] ^ b[3]];
+ [[fallthrough]];
+ case 3:
+ accu += hamdis_tab_ham_bytes[a[2] ^ b[2]];
+ [[fallthrough]];
+ case 2:
+ accu += hamdis_tab_ham_bytes[a[1] ^ b[1]];
+ [[fallthrough]];
+ case 1:
+ accu += hamdis_tab_ham_bytes[a[0] ^ b[0]];
+ [[fallthrough]];
+ default:
+ break;
+ }
+ }
+
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return quotient8 * 8 + remainder8;
+ }
+};
+
+/***************************************************************************
+ * generalized Hamming = number of bytes that are different between
+ * two codes.
+ ***************************************************************************/
+
+inline int generalized_hamming_64(uint64_t a) {
+ a |= a >> 1;
+ a |= a >> 2;
+ a |= a >> 4;
+ a &= 0x0101010101010101UL;
+ return popcount64(a);
+}
+
+struct GenHammingComputer8 {
+ uint64_t a0;
+
+ GenHammingComputer8(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return generalized_hamming_64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+// I'm not sure whether this version is faster of slower, tbh
+// todo: test on different CPUs
+struct GenHammingComputer16 {
+ __m128i a;
+
+ GenHammingComputer16(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ a = _mm_loadu_si128((const __m128i_u*)a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const __m128i b = _mm_loadu_si128((const __m128i_u*)b8);
+ const __m128i cmp = _mm_cmpeq_epi8(a, b);
+ const auto movemask = _mm_movemask_epi8(cmp);
+ return 16 - popcount32(movemask);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+struct GenHammingComputer32 {
+ __m256i a;
+
+ GenHammingComputer32(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ a = _mm256_loadu_si256((const __m256i_u*)a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const __m256i b = _mm256_loadu_si256((const __m256i_u*)b8);
+ const __m256i cmp = _mm256_cmpeq_epi8(a, b);
+ const uint32_t movemask = _mm256_movemask_epi8(cmp);
+ return 32 - popcount32(movemask);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+// A specialized version might be needed for the very long
+// GenHamming code_size. In such a case, one may accumulate
+// counts using _mm256_sub_epi8 and then compute a horizontal
+// sum (using _mm256_sad_epu8, maybe, in blocks of no larger
+// than 256 * 32 bytes).
+
+struct GenHammingComputerM8 {
+ const uint64_t* a;
+ int n;
+
+ GenHammingComputerM8(const uint8_t* a8, int code_size) {
+ assert(code_size % 8 == 0);
+ a = (uint64_t*)a8;
+ n = code_size / 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ int accu = 0;
+
+ int i = 0;
+ int n4 = (n / 4) * 4;
+ for (; i < n4; i += 4) {
+ const __m256i av = _mm256_loadu_si256((const __m256i_u*)(a + i));
+ const __m256i bv = _mm256_loadu_si256((const __m256i_u*)(b + i));
+ const __m256i cmp = _mm256_cmpeq_epi8(av, bv);
+ const uint32_t movemask = _mm256_movemask_epi8(cmp);
+ accu += 32 - popcount32(movemask);
+ }
+
+ for (; i < n; i++)
+ accu += generalized_hamming_64(a[i] ^ b[i]);
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return n * 8;
+ }
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/avx512-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/avx512-inl.h
new file mode 100644
index 0000000..dfd8f55
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/avx512-inl.h
@@ -0,0 +1,490 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef HAMMING_AVX512_INL_H
+#define HAMMING_AVX512_INL_H
+
+// AVX512 version
+// The _mm512_popcnt_epi64 intrinsic is used to accelerate Hamming distance
+// calculations in HammingComputerDefault and HammingComputer64. This intrinsic
+// is not available in the default Faiss avx512 build mode but is only
+// available in the avx512_spr build mode, which targets Intel(R) Sapphire
+// Rapids.
+
+#include <cassert>
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/impl/platform_macros.h>
+
+#include <immintrin.h>
+
+namespace faiss {
+
+/* Elementary Hamming distance computation: unoptimized */
+template <size_t nbits, typename T>
+inline T hamming(const uint8_t* bs1, const uint8_t* bs2) {
+ const size_t nbytes = nbits / 8;
+ size_t i;
+ T h = 0;
+ for (i = 0; i < nbytes; i++) {
+ h += (T)hamdis_tab_ham_bytes[bs1[i] ^ bs2[i]];
+ }
+ return h;
+}
+
+/* Hamming distances for multiples of 64 bits */
+template <size_t nbits>
+inline hamdis_t hamming(const uint64_t* bs1, const uint64_t* bs2) {
+ const size_t nwords = nbits / 64;
+ size_t i;
+ hamdis_t h = 0;
+ for (i = 0; i < nwords; i++) {
+ h += popcount64(bs1[i] ^ bs2[i]);
+ }
+ return h;
+}
+
+/* specialized (optimized) functions */
+template <>
+inline hamdis_t hamming<64>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]);
+}
+
+template <>
+inline hamdis_t hamming<128>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]) + popcount64(pa[1] ^ pb[1]);
+}
+
+template <>
+inline hamdis_t hamming<256>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]) + popcount64(pa[1] ^ pb[1]) +
+ popcount64(pa[2] ^ pb[2]) + popcount64(pa[3] ^ pb[3]);
+}
+
+/* Hamming distances for multiple of 64 bits */
+inline hamdis_t hamming(
+ const uint64_t* bs1,
+ const uint64_t* bs2,
+ size_t nwords) {
+ hamdis_t h = 0;
+ for (size_t i = 0; i < nwords; i++) {
+ h += popcount64(bs1[i] ^ bs2[i]);
+ }
+ return h;
+}
+
+/******************************************************************
+ * The HammingComputer series of classes compares a single code of
+ * size 4 to 32 to incoming codes. They are intended for use as a
+ * template class where it would be inefficient to switch on the code
+ * size in the inner loop. Hopefully the compiler will inline the
+ * hamming() functions and put the a0, a1, ... in registers.
+ ******************************************************************/
+
+struct HammingComputer4 {
+ uint32_t a0;
+
+ HammingComputer4() {}
+
+ HammingComputer4(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 4);
+ a0 = *(uint32_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint32_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 4;
+ }
+};
+
+struct HammingComputer8 {
+ uint64_t a0;
+
+ HammingComputer8() {}
+
+ HammingComputer8(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+struct HammingComputer16 {
+ uint64_t a0, a1;
+
+ HammingComputer16() {}
+
+ HammingComputer16(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+// when applied to an array, 1/2 of the 64-bit accesses are unaligned.
+// This incurs a penalty of ~10% wrt. fully aligned accesses.
+struct HammingComputer20 {
+ uint64_t a0, a1;
+ uint32_t a2;
+
+ HammingComputer20() {}
+
+ HammingComputer20(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 20);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(*(uint32_t*)(b + 2) ^ a2);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 20;
+ }
+};
+
+struct HammingComputer32 {
+ uint64_t a0, a1, a2, a3;
+
+ HammingComputer32() {}
+
+ HammingComputer32(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(b[2] ^ a2) + popcount64(b[3] ^ a3);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+struct HammingComputer64 {
+ uint64_t a0, a1, a2, a3, a4, a5, a6, a7;
+ const uint64_t* a;
+
+ HammingComputer64() {}
+
+ HammingComputer64(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 64);
+ a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ a4 = a[4];
+ a5 = a[5];
+ a6 = a[6];
+ a7 = a[7];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+#ifdef __AVX512VPOPCNTDQ__
+ __m512i vxor =
+ _mm512_xor_si512(_mm512_loadu_si512(a), _mm512_loadu_si512(b));
+ __m512i vpcnt = _mm512_popcnt_epi64(vxor);
+ // reduce performs better than adding the lower and higher parts
+ return _mm512_reduce_add_epi32(vpcnt);
+#else
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(b[2] ^ a2) + popcount64(b[3] ^ a3) +
+ popcount64(b[4] ^ a4) + popcount64(b[5] ^ a5) +
+ popcount64(b[6] ^ a6) + popcount64(b[7] ^ a7);
+#endif
+ }
+
+ inline static constexpr int get_code_size() {
+ return 64;
+ }
+};
+
+struct HammingComputerDefault {
+ const uint8_t* a8;
+ int quotient8;
+ int remainder8;
+
+ HammingComputerDefault() {}
+
+ HammingComputerDefault(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8_2, int code_size) {
+ this->a8 = a8_2;
+ quotient8 = code_size / 8;
+ remainder8 = code_size % 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ int accu = 0;
+
+ const uint64_t* a64 = reinterpret_cast<const uint64_t*>(a8);
+ const uint64_t* b64 = reinterpret_cast<const uint64_t*>(b8);
+
+ int i = 0;
+#ifdef __AVX512VPOPCNTDQ__
+ int quotient64 = quotient8 / 8;
+ for (; i < quotient64; ++i) {
+ __m512i vxor = _mm512_xor_si512(
+ _mm512_loadu_si512(&a64[i * 8]),
+ _mm512_loadu_si512(&b64[i * 8]));
+ __m512i vpcnt = _mm512_popcnt_epi64(vxor);
+ // reduce performs better than adding the lower and higher parts
+ accu += _mm512_reduce_add_epi32(vpcnt);
+ }
+ i *= 8;
+#endif
+ int len = quotient8 - i;
+ switch (len & 7) {
+ default:
+ while (len > 7) {
+ len -= 8;
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 7:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 6:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 5:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 4:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 3:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 2:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 1:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ }
+ }
+ if (remainder8) {
+ const uint8_t* a = a8 + 8 * quotient8;
+ const uint8_t* b = b8 + 8 * quotient8;
+ switch (remainder8) {
+ case 7:
+ accu += hamdis_tab_ham_bytes[a[6] ^ b[6]];
+ [[fallthrough]];
+ case 6:
+ accu += hamdis_tab_ham_bytes[a[5] ^ b[5]];
+ [[fallthrough]];
+ case 5:
+ accu += hamdis_tab_ham_bytes[a[4] ^ b[4]];
+ [[fallthrough]];
+ case 4:
+ accu += hamdis_tab_ham_bytes[a[3] ^ b[3]];
+ [[fallthrough]];
+ case 3:
+ accu += hamdis_tab_ham_bytes[a[2] ^ b[2]];
+ [[fallthrough]];
+ case 2:
+ accu += hamdis_tab_ham_bytes[a[1] ^ b[1]];
+ [[fallthrough]];
+ case 1:
+ accu += hamdis_tab_ham_bytes[a[0] ^ b[0]];
+ [[fallthrough]];
+ default:
+ break;
+ }
+ }
+
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return quotient8 * 8 + remainder8;
+ }
+};
+
+/***************************************************************************
+ * generalized Hamming = number of bytes that are different between
+ * two codes.
+ ***************************************************************************/
+
+inline int generalized_hamming_64(uint64_t a) {
+ a |= a >> 1;
+ a |= a >> 2;
+ a |= a >> 4;
+ a &= 0x0101010101010101UL;
+ return popcount64(a);
+}
+
+struct GenHammingComputer8 {
+ uint64_t a0;
+
+ GenHammingComputer8(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return generalized_hamming_64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+// I'm not sure whether this version is faster of slower, tbh
+// todo: test on different CPUs
+struct GenHammingComputer16 {
+ __m128i a;
+
+ GenHammingComputer16(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ a = _mm_loadu_si128((const __m128i_u*)a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const __m128i b = _mm_loadu_si128((const __m128i_u*)b8);
+ const __m128i cmp = _mm_cmpeq_epi8(a, b);
+ const auto movemask = _mm_movemask_epi8(cmp);
+ return 16 - popcount32(movemask);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+struct GenHammingComputer32 {
+ __m256i a;
+
+ GenHammingComputer32(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ a = _mm256_loadu_si256((const __m256i_u*)a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const __m256i b = _mm256_loadu_si256((const __m256i_u*)b8);
+ const __m256i cmp = _mm256_cmpeq_epi8(a, b);
+ const uint32_t movemask = _mm256_movemask_epi8(cmp);
+ return 32 - popcount32(movemask);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+// A specialized version might be needed for the very long
+// GenHamming code_size. In such a case, one may accumulate
+// counts using _mm256_sub_epi8 and then compute a horizontal
+// sum (using _mm256_sad_epu8, maybe, in blocks of no larger
+// than 256 * 32 bytes).
+
+struct GenHammingComputerM8 {
+ const uint64_t* a;
+ int n;
+
+ GenHammingComputerM8(const uint8_t* a8, int code_size) {
+ assert(code_size % 8 == 0);
+ a = (uint64_t*)a8;
+ n = code_size / 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ int accu = 0;
+
+ int i = 0;
+ int n4 = (n / 4) * 4;
+ for (; i < n4; i += 4) {
+ const __m256i av = _mm256_loadu_si256((const __m256i_u*)(a + i));
+ const __m256i bv = _mm256_loadu_si256((const __m256i_u*)(b + i));
+ const __m256i cmp = _mm256_cmpeq_epi8(av, bv);
+ const uint32_t movemask = _mm256_movemask_epi8(cmp);
+ accu += 32 - popcount32(movemask);
+ }
+
+ for (; i < n; i++)
+ accu += generalized_hamming_64(a[i] ^ b[i]);
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return n * 8;
+ }
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/common.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/common.h
new file mode 100644
index 0000000..664900e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/common.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_hamming_common_h
+#define FAISS_hamming_common_h
+
+#include <cstdint>
+
+#include <faiss/impl/platform_macros.h>
+
+/* The Hamming distance type */
+using hamdis_t = int32_t;
+
+namespace faiss {
+
+// trust the compiler to provide efficient popcount implementations
+inline int popcount32(uint32_t x) {
+ return __builtin_popcount(x);
+}
+
+// popcount
+inline int popcount64(uint64_t x) {
+ return __builtin_popcountl(x);
+}
+
+// This table was moved from .cpp to .h file, because
+// otherwise it was causing compilation errors while trying to
+// compile swig modules on Windows.
+// todo for C++17: switch to 'inline constexpr'
+static constexpr uint8_t hamdis_tab_ham_bytes[256] = {
+ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4,
+ 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4,
+ 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,
+ 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5,
+ 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
+ 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,
+ 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
+ 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/generic-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/generic-inl.h
new file mode 100644
index 0000000..b8e7b42
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/generic-inl.h
@@ -0,0 +1,450 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef HAMMING_GENERIC_INL_H
+#define HAMMING_GENERIC_INL_H
+
+// A general-purpose version of hamming distance computation.
+
+#include <cassert>
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/* Elementary Hamming distance computation: unoptimized */
+template <size_t nbits, typename T>
+inline T hamming(const uint8_t* bs1, const uint8_t* bs2) {
+ const size_t nbytes = nbits / 8;
+ size_t i;
+ T h = 0;
+ for (i = 0; i < nbytes; i++) {
+ h += (T)hamdis_tab_ham_bytes[bs1[i] ^ bs2[i]];
+ }
+ return h;
+}
+
+/* Hamming distances for multiples of 64 bits */
+template <size_t nbits>
+inline hamdis_t hamming(const uint64_t* bs1, const uint64_t* bs2) {
+ const size_t nwords = nbits / 64;
+ size_t i;
+ hamdis_t h = 0;
+ for (i = 0; i < nwords; i++) {
+ h += popcount64(bs1[i] ^ bs2[i]);
+ }
+ return h;
+}
+
+/* specialized (optimized) functions */
+template <>
+inline hamdis_t hamming<64>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]);
+}
+
+template <>
+inline hamdis_t hamming<128>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]) + popcount64(pa[1] ^ pb[1]);
+}
+
+template <>
+inline hamdis_t hamming<256>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]) + popcount64(pa[1] ^ pb[1]) +
+ popcount64(pa[2] ^ pb[2]) + popcount64(pa[3] ^ pb[3]);
+}
+
+/* Hamming distances for multiple of 64 bits */
+inline hamdis_t hamming(
+ const uint64_t* bs1,
+ const uint64_t* bs2,
+ size_t nwords) {
+ hamdis_t h = 0;
+ for (size_t i = 0; i < nwords; i++) {
+ h += popcount64(bs1[i] ^ bs2[i]);
+ }
+ return h;
+}
+
+/******************************************************************
+ * The HammingComputer series of classes compares a single code of
+ * size 4 to 32 to incoming codes. They are intended for use as a
+ * template class where it would be inefficient to switch on the code
+ * size in the inner loop. Hopefully the compiler will inline the
+ * hamming() functions and put the a0, a1, ... in registers.
+ ******************************************************************/
+
+struct HammingComputer4 {
+ uint32_t a0;
+
+ HammingComputer4() {}
+
+ HammingComputer4(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 4);
+ a0 = *(uint32_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint32_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 4;
+ }
+};
+
+struct HammingComputer8 {
+ uint64_t a0;
+
+ HammingComputer8() {}
+
+ HammingComputer8(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+struct HammingComputer16 {
+ uint64_t a0, a1;
+
+ HammingComputer16() {}
+
+ HammingComputer16(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+// when applied to an array, 1/2 of the 64-bit accesses are unaligned.
+// This incurs a penalty of ~10% wrt. fully aligned accesses.
+struct HammingComputer20 {
+ uint64_t a0, a1;
+ uint32_t a2;
+
+ HammingComputer20() {}
+
+ HammingComputer20(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 20);
+ const uint64_t* a = (uint64_t*)a8;
+ const uint32_t* b = (uint32_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ // can't read a[2] since it is uint64_t, not uint32_t
+ // results in AddressSanitizer failure reading past end of array
+ a2 = b[4];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(*(uint32_t*)(b + 2) ^ a2);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 20;
+ }
+};
+
+struct HammingComputer32 {
+ uint64_t a0, a1, a2, a3;
+
+ HammingComputer32() {}
+
+ HammingComputer32(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(b[2] ^ a2) + popcount64(b[3] ^ a3);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+struct HammingComputer64 {
+ uint64_t a0, a1, a2, a3, a4, a5, a6, a7;
+
+ HammingComputer64() {}
+
+ HammingComputer64(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 64);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ a4 = a[4];
+ a5 = a[5];
+ a6 = a[6];
+ a7 = a[7];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return popcount64(b[0] ^ a0) + popcount64(b[1] ^ a1) +
+ popcount64(b[2] ^ a2) + popcount64(b[3] ^ a3) +
+ popcount64(b[4] ^ a4) + popcount64(b[5] ^ a5) +
+ popcount64(b[6] ^ a6) + popcount64(b[7] ^ a7);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 64;
+ }
+};
+
+struct HammingComputerDefault {
+ const uint8_t* a8;
+ int quotient8;
+ int remainder8;
+
+ HammingComputerDefault() {}
+
+ HammingComputerDefault(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ this->a8 = a8;
+ quotient8 = code_size / 8;
+ remainder8 = code_size % 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ int accu = 0;
+
+ const uint64_t* a64 = reinterpret_cast<const uint64_t*>(a8);
+ const uint64_t* b64 = reinterpret_cast<const uint64_t*>(b8);
+ int i = 0, len = quotient8;
+ switch (len & 7) {
+ default:
+ while (len > 7) {
+ len -= 8;
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 7:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 6:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 5:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 4:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 3:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 2:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 1:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ }
+ }
+ if (remainder8) {
+ const uint8_t* a = a8 + 8 * quotient8;
+ const uint8_t* b = b8 + 8 * quotient8;
+ switch (remainder8) {
+ [[fallthrough]];
+ case 7:
+ accu += hamdis_tab_ham_bytes[a[6] ^ b[6]];
+ [[fallthrough]];
+ case 6:
+ accu += hamdis_tab_ham_bytes[a[5] ^ b[5]];
+ [[fallthrough]];
+ case 5:
+ accu += hamdis_tab_ham_bytes[a[4] ^ b[4]];
+ [[fallthrough]];
+ case 4:
+ accu += hamdis_tab_ham_bytes[a[3] ^ b[3]];
+ [[fallthrough]];
+ case 3:
+ accu += hamdis_tab_ham_bytes[a[2] ^ b[2]];
+ [[fallthrough]];
+ case 2:
+ accu += hamdis_tab_ham_bytes[a[1] ^ b[1]];
+ [[fallthrough]];
+ case 1:
+ accu += hamdis_tab_ham_bytes[a[0] ^ b[0]];
+ [[fallthrough]];
+ default:
+ break;
+ }
+ }
+
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return quotient8 * 8 + remainder8;
+ }
+};
+
+/***************************************************************************
+ * generalized Hamming = number of bytes that are different between
+ * two codes.
+ ***************************************************************************/
+
+inline int generalized_hamming_64(uint64_t a) {
+ a |= a >> 1;
+ a |= a >> 2;
+ a |= a >> 4;
+ a &= 0x0101010101010101UL;
+ return popcount64(a);
+}
+
+struct GenHammingComputer8 {
+ uint64_t a0;
+
+ GenHammingComputer8(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return generalized_hamming_64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+struct GenHammingComputer16 {
+ uint64_t a0, a1;
+ GenHammingComputer16(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return generalized_hamming_64(b[0] ^ a0) +
+ generalized_hamming_64(b[1] ^ a1);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+struct GenHammingComputer32 {
+ uint64_t a0, a1, a2, a3;
+
+ GenHammingComputer32(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ const uint64_t* a = (uint64_t*)a8;
+ a0 = a[0];
+ a1 = a[1];
+ a2 = a[2];
+ a3 = a[3];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ return generalized_hamming_64(b[0] ^ a0) +
+ generalized_hamming_64(b[1] ^ a1) +
+ generalized_hamming_64(b[2] ^ a2) +
+ generalized_hamming_64(b[3] ^ a3);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+struct GenHammingComputerM8 {
+ const uint64_t* a;
+ int n;
+
+ GenHammingComputerM8(const uint8_t* a8, int code_size) {
+ assert(code_size % 8 == 0);
+ a = (uint64_t*)a8;
+ n = code_size / 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ int accu = 0;
+ for (int i = 0; i < n; i++)
+ accu += generalized_hamming_64(a[i] ^ b[i]);
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return n * 8;
+ }
+};
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/hamdis-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/hamdis-inl.h
new file mode 100644
index 0000000..0c9ac1b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/hamdis-inl.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// This file contains low level inline facilities for computing
+// Hamming distances, such as HammingComputerXX and GenHammingComputerXX.
+
+#ifndef FAISS_hamming_inl_h
+#define FAISS_hamming_inl_h
+
+#include <faiss/utils/hamming_distance/common.h>
+
+#ifdef __aarch64__
+// ARM compilers may produce inoptimal code for Hamming distance somewhy.
+#include <faiss/utils/hamming_distance/neon-inl.h>
+#elif __AVX512F__
+// offers better performance where __AVX512VPOPCNTDQ__ is supported
+#include <faiss/utils/hamming_distance/avx512-inl.h>
+#elif __AVX2__
+// better versions for GenHammingComputer
+#include <faiss/utils/hamming_distance/avx2-inl.h>
+#else
+#include <faiss/utils/hamming_distance/generic-inl.h>
+#endif
+
+namespace faiss {
+
+/***************************************************************************
+ * Equivalence with a template class when code size is known at compile time
+ **************************************************************************/
+
+// default template
+template <int CODE_SIZE>
+struct HammingComputer : HammingComputerDefault {
+ HammingComputer(const uint8_t* a, int code_size)
+ : HammingComputerDefault(a, code_size) {}
+};
+
+#define SPECIALIZED_HC(CODE_SIZE) \
+ template <> \
+ struct HammingComputer<CODE_SIZE> : HammingComputer##CODE_SIZE { \
+ HammingComputer(const uint8_t* a) \
+ : HammingComputer##CODE_SIZE(a, CODE_SIZE) {} \
+ }
+
+SPECIALIZED_HC(4);
+SPECIALIZED_HC(8);
+SPECIALIZED_HC(16);
+SPECIALIZED_HC(20);
+SPECIALIZED_HC(32);
+SPECIALIZED_HC(64);
+
+#undef SPECIALIZED_HC
+
+/***************************************************************************
+ * Dispatching function that takes a code size and a consumer object
+ * the consumer object should contain a retun type t and a operation template
+ * function f() that must be called to perform the operation.
+ **************************************************************************/
+
+template <class Consumer, class... Types>
+typename Consumer::T dispatch_HammingComputer(
+ int code_size,
+ Consumer& consumer,
+ Types... args) {
+ switch (code_size) {
+#define DISPATCH_HC(CODE_SIZE) \
+ case CODE_SIZE: \
+ return consumer.template f<HammingComputer##CODE_SIZE>(args...);
+ DISPATCH_HC(4);
+ DISPATCH_HC(8);
+ DISPATCH_HC(16);
+ DISPATCH_HC(20);
+ DISPATCH_HC(32);
+ DISPATCH_HC(64);
+ default:
+ return consumer.template f<HammingComputerDefault>(args...);
+ }
+#undef DISPATCH_HC
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/neon-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/neon-inl.h
new file mode 100644
index 0000000..d00a402
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/hamming_distance/neon-inl.h
@@ -0,0 +1,524 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef HAMMING_NEON_INL_H
+#define HAMMING_NEON_INL_H
+
+// a specialized version of hamming is needed here, because both
+// gcc, clang and msvc seem to generate suboptimal code sometimes.
+
+#ifdef __aarch64__
+
+#include <arm_neon.h>
+
+#include <cassert>
+#include <cstddef>
+#include <cstdint>
+
+#include <faiss/impl/platform_macros.h>
+
+#include <faiss/utils/hamming_distance/common.h>
+
+namespace faiss {
+
+/* Elementary Hamming distance computation: unoptimized */
+template <size_t nbits, typename T>
+inline T hamming(const uint8_t* bs1, const uint8_t* bs2) {
+ const size_t nbytes = nbits / 8;
+ size_t i;
+ T h = 0;
+ for (i = 0; i < nbytes; i++) {
+ h += (T)hamdis_tab_ham_bytes[bs1[i] ^ bs2[i]];
+ }
+ return h;
+}
+
+/* Hamming distances for multiples of 64 bits */
+template <size_t nbits>
+inline hamdis_t hamming(const uint64_t* pa, const uint64_t* pb) {
+ constexpr size_t nwords256 = nbits / 256;
+ constexpr size_t nwords128 = (nbits - nwords256 * 256) / 128;
+ constexpr size_t nwords64 =
+ (nbits - nwords256 * 256 - nwords128 * 128) / 64;
+
+ hamdis_t h = 0;
+ if (nwords256 > 0) {
+ for (size_t i = 0; i < nwords256; i++) {
+ h += hamming<256>(pa, pb);
+ pa += 4;
+ pb += 4;
+ }
+ }
+
+ if (nwords128 > 0) {
+ h += hamming<128>(pa, pb);
+ pa += 2;
+ pb += 2;
+ }
+
+ if (nwords64 > 0) {
+ h += hamming<64>(pa, pb);
+ }
+
+ return h;
+}
+
+/* specialized (optimized) functions */
+template <>
+inline hamdis_t hamming<64>(const uint64_t* pa, const uint64_t* pb) {
+ return popcount64(pa[0] ^ pb[0]);
+}
+
+template <>
+inline hamdis_t hamming<128>(const uint64_t* pa, const uint64_t* pb) {
+ const uint8_t* pa8 = reinterpret_cast<const uint8_t*>(pa);
+ const uint8_t* pb8 = reinterpret_cast<const uint8_t*>(pb);
+ uint8x16_t or0 = veorq_u8(vld1q_u8(pa8), vld1q_u8(pb8));
+ uint8x16_t c0 = vcntq_u8(or0);
+ auto dis = vaddvq_u8(c0);
+ return dis;
+}
+
+template <>
+inline hamdis_t hamming<256>(const uint64_t* pa, const uint64_t* pb) {
+ const uint8_t* pa8 = reinterpret_cast<const uint8_t*>(pa);
+ const uint8_t* pb8 = reinterpret_cast<const uint8_t*>(pb);
+ uint8x16_t or0 = veorq_u8(vld1q_u8(pa8), vld1q_u8(pb8));
+ uint8x16_t or1 = veorq_u8(vld1q_u8(pa8 + 16), vld1q_u8(pb8 + 16));
+ uint8x16_t c0 = vcntq_u8(or0);
+ uint8x16_t c1 = vcntq_u8(or1);
+ uint8x16_t ca = vpaddq_u8(c0, c1);
+ auto dis = vaddvq_u8(ca);
+ return dis;
+}
+
+/* Hamming distances for multiple of 64 bits */
+inline hamdis_t hamming(const uint64_t* pa, const uint64_t* pb, size_t nwords) {
+ const size_t nwords256 = nwords / 4;
+ const size_t nwords128 = (nwords % 4) / 2;
+ const size_t nwords64 = nwords % 2;
+
+ hamdis_t h = 0;
+ if (nwords256 > 0) {
+ for (size_t i = 0; i < nwords256; i++) {
+ h += hamming<256>(pa, pb);
+ pa += 4;
+ pb += 4;
+ }
+ }
+
+ if (nwords128 > 0) {
+ h += hamming<128>(pa, pb);
+ pa += 2;
+ pb += 2;
+ }
+
+ if (nwords64 > 0) {
+ h += hamming<64>(pa, pb);
+ }
+
+ return h;
+}
+
+/******************************************************************
+ * The HammingComputer series of classes compares a single code of
+ * size 4 to 32 to incoming codes. They are intended for use as a
+ * template class where it would be inefficient to switch on the code
+ * size in the inner loop. Hopefully the compiler will inline the
+ * hamming() functions and put the a0, a1, ... in registers.
+ ******************************************************************/
+
+struct HammingComputer4 {
+ uint32_t a0;
+
+ HammingComputer4() {}
+
+ HammingComputer4(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 4);
+ a0 = *(uint32_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint32_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 4;
+ }
+};
+
+struct HammingComputer8 {
+ uint64_t a0;
+
+ HammingComputer8() {}
+
+ HammingComputer8(const uint8_t* a, int code_size) {
+ set(a, code_size);
+ }
+
+ void set(const uint8_t* a, int code_size) {
+ assert(code_size == 8);
+ a0 = *(uint64_t*)a;
+ }
+
+ inline int hamming(const uint8_t* b) const {
+ return popcount64(*(uint64_t*)b ^ a0);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+struct HammingComputer16 {
+ uint8x16_t a0;
+
+ HammingComputer16() {}
+
+ HammingComputer16(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ a0 = vld1q_u8(a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ uint8x16_t b0 = vld1q_u8(b8);
+
+ uint8x16_t or0 = veorq_u8(a0, b0);
+ uint8x16_t c0 = vcntq_u8(or0);
+ auto dis = vaddvq_u8(c0);
+ return dis;
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+// when applied to an array, 1/2 of the 64-bit accesses are unaligned.
+// This incurs a penalty of ~10% wrt. fully aligned accesses.
+struct HammingComputer20 {
+ uint8x16_t a0;
+ uint32_t a2;
+
+ HammingComputer20() {}
+
+ HammingComputer20(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 20);
+
+ a0 = vld1q_u8(a8);
+
+ const uint32_t* a = (uint32_t*)a8;
+ a2 = a[4];
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ uint8x16_t b0 = vld1q_u8(b8);
+
+ uint8x16_t or0 = veorq_u8(a0, b0);
+ uint8x16_t c0 = vcntq_u8(or0);
+ auto dis = vaddvq_u8(c0);
+
+ const uint32_t* b = (uint32_t*)b8;
+ return dis + popcount64(b[4] ^ a2);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 20;
+ }
+};
+
+struct HammingComputer32 {
+ uint8x16_t a0;
+ uint8x16_t a1;
+
+ HammingComputer32() {}
+
+ HammingComputer32(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 32);
+ a0 = vld1q_u8(a8);
+ a1 = vld1q_u8(a8 + 16);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ uint8x16_t b0 = vld1q_u8(b8);
+ uint8x16_t b1 = vld1q_u8(b8 + 16);
+
+ uint8x16_t or0 = veorq_u8(a0, b0);
+ uint8x16_t or1 = veorq_u8(a1, b1);
+ uint8x16_t c0 = vcntq_u8(or0);
+ uint8x16_t c1 = vcntq_u8(or1);
+ uint8x16_t ca = vpaddq_u8(c0, c1);
+ auto dis = vaddvq_u8(ca);
+ return dis;
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+struct HammingComputer64 {
+ HammingComputer32 hc0, hc1;
+
+ HammingComputer64() {}
+
+ HammingComputer64(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ assert(code_size == 64);
+ hc0.set(a8, 32);
+ hc1.set(a8 + 32, 32);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ return hc0.hamming(b8) + hc1.hamming(b8 + 32);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 64;
+ }
+};
+
+struct HammingComputerDefault {
+ const uint8_t* a8;
+ int quotient8;
+ int remainder8;
+
+ HammingComputerDefault() {}
+
+ HammingComputerDefault(const uint8_t* a8, int code_size) {
+ set(a8, code_size);
+ }
+
+ void set(const uint8_t* a8, int code_size) {
+ this->a8 = a8;
+ quotient8 = code_size / 8;
+ remainder8 = code_size % 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ int accu = 0;
+
+ const uint64_t* a64 = reinterpret_cast<const uint64_t*>(a8);
+ const uint64_t* b64 = reinterpret_cast<const uint64_t*>(b8);
+ int i = 0, len = quotient8;
+
+ int len256 = (quotient8 / 4) * 4;
+ for (; i < len256; i += 4) {
+ accu += ::faiss::hamming<256>(a64 + i, b64 + i);
+ len -= 4;
+ }
+
+ switch (len & 7) {
+ default:
+ while (len > 7) {
+ len -= 8;
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 7:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 6:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 5:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 4:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 3:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 2:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ [[fallthrough]];
+ case 1:
+ accu += popcount64(a64[i] ^ b64[i]);
+ i++;
+ }
+ }
+ if (remainder8) {
+ const uint8_t* a = a8 + 8 * quotient8;
+ const uint8_t* b = b8 + 8 * quotient8;
+ switch (remainder8) {
+ case 7:
+ accu += hamdis_tab_ham_bytes[a[6] ^ b[6]];
+ [[fallthrough]];
+ case 6:
+ accu += hamdis_tab_ham_bytes[a[5] ^ b[5]];
+ [[fallthrough]];
+ case 5:
+ accu += hamdis_tab_ham_bytes[a[4] ^ b[4]];
+ [[fallthrough]];
+ case 4:
+ accu += hamdis_tab_ham_bytes[a[3] ^ b[3]];
+ [[fallthrough]];
+ case 3:
+ accu += hamdis_tab_ham_bytes[a[2] ^ b[2]];
+ [[fallthrough]];
+ case 2:
+ accu += hamdis_tab_ham_bytes[a[1] ^ b[1]];
+ [[fallthrough]];
+ case 1:
+ accu += hamdis_tab_ham_bytes[a[0] ^ b[0]];
+ [[fallthrough]];
+ default:
+ break;
+ }
+ }
+
+ return accu;
+ }
+
+ inline int get_code_size() const {
+ return quotient8 * 8 + remainder8;
+ }
+};
+
+/***************************************************************************
+ * generalized Hamming = number of bytes that are different between
+ * two codes.
+ ***************************************************************************/
+
+inline int generalized_hamming_64(uint64_t a) {
+ a |= a >> 1;
+ a |= a >> 2;
+ a |= a >> 4;
+ a &= 0x0101010101010101UL;
+ return popcount64(a);
+}
+
+struct GenHammingComputer8 {
+ uint8x8_t a0;
+
+ GenHammingComputer8(const uint8_t* a8, int code_size) {
+ assert(code_size == 8);
+ a0 = vld1_u8(a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ uint8x8_t b0 = vld1_u8(b8);
+ uint8x8_t reg = vceq_u8(a0, b0);
+ uint8x8_t c0 = vcnt_u8(reg);
+ return 8 - vaddv_u8(c0) / 8;
+ }
+
+ inline static constexpr int get_code_size() {
+ return 8;
+ }
+};
+
+struct GenHammingComputer16 {
+ uint8x16_t a0;
+
+ GenHammingComputer16(const uint8_t* a8, int code_size) {
+ assert(code_size == 16);
+ a0 = vld1q_u8(a8);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ uint8x16_t b0 = vld1q_u8(b8);
+ uint8x16_t reg = vceqq_u8(a0, b0);
+ uint8x16_t c0 = vcntq_u8(reg);
+ return 16 - vaddvq_u8(c0) / 8;
+ }
+
+ inline static constexpr int get_code_size() {
+ return 16;
+ }
+};
+
+struct GenHammingComputer32 {
+ GenHammingComputer16 a0, a1;
+
+ GenHammingComputer32(const uint8_t* a8, int code_size)
+ : a0(a8, 16), a1(a8 + 16, 16) {
+ assert(code_size == 32);
+ }
+
+ inline int hamming(const uint8_t* b8) const {
+ return a0.hamming(b8) + a1.hamming(b8 + 16);
+ }
+
+ inline static constexpr int get_code_size() {
+ return 32;
+ }
+};
+
+struct GenHammingComputerM8 {
+ const uint64_t* a;
+ int n;
+
+ GenHammingComputerM8(const uint8_t* a8, int code_size) {
+ assert(code_size % 8 == 0);
+ a = (uint64_t*)a8;
+ n = code_size / 8;
+ }
+
+ int hamming(const uint8_t* b8) const {
+ const uint64_t* b = (uint64_t*)b8;
+ int accu = 0;
+
+ int n2 = (n / 2) * 2;
+ int i = 0;
+ for (; i < n2; i += 2) {
+ uint8x16_t a0 = vld1q_u8((const uint8_t*)(a + i));
+ uint8x16_t b0 = vld1q_u8((const uint8_t*)(b + i));
+ uint8x16_t reg = vceqq_u8(a0, b0);
+ uint8x16_t c0 = vcntq_u8(reg);
+ auto dis = 16 - vaddvq_u8(c0) / 8;
+ accu += dis;
+ }
+
+ for (; i < n; i++) {
+ uint8x8_t a0 = vld1_u8((const uint8_t*)(a + i));
+ uint8x8_t b0 = vld1_u8((const uint8_t*)(b + i));
+ uint8x8_t reg = vceq_u8(a0, b0);
+ uint8x8_t c0 = vcnt_u8(reg);
+ auto dis = 8 - vaddv_u8(c0) / 8;
+ accu += dis;
+ }
+
+ return accu;
+ }
+
+ inline int get_code_size() {
+ return n * 8;
+ }
+};
+
+} // namespace faiss
+
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/ordered_key_value.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/ordered_key_value.h
new file mode 100644
index 0000000..ec0a82e
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/ordered_key_value.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <climits>
+#include <cmath>
+
+#include <limits>
+
+namespace faiss {
+
+/*******************************************************************
+ * C object: uniform handling of min and max heap
+ *******************************************************************/
+
+/** The C object gives the type T of the values of a key-value storage, the type
+ * of the keys, TI and the comparison that is done: CMax for a decreasing
+ * series and CMin for increasing series. In other words, for a given threshold
+ * threshold, an incoming value x is kept if
+ *
+ * C::cmp(threshold, x)
+ *
+ * is true.
+ */
+
+template <typename T_, typename TI_>
+struct CMax;
+
+template <typename T>
+inline T cmin_nextafter(T x);
+template <typename T>
+inline T cmax_nextafter(T x);
+
+// traits of minheaps = heaps where the minimum value is stored on top
+// useful to find the *max* values of an array
+template <typename T_, typename TI_>
+struct CMin {
+ typedef T_ T;
+ typedef TI_ TI;
+ typedef CMax<T_, TI_> Crev; // reference to reverse comparison
+ inline static bool cmp(T a, T b) {
+ return a < b;
+ }
+ // Similar to cmp(), but also breaks ties
+ // by comparing the second pair of arguments.
+ inline static bool cmp2(T a1, T b1, TI a2, TI b2) {
+ return (a1 < b1) || ((a1 == b1) && (a2 < b2));
+ }
+ inline static T neutral() {
+ return std::numeric_limits<T>::lowest();
+ }
+ static const bool is_max = false;
+
+ inline static T nextafter(T x) {
+ return cmin_nextafter(x);
+ }
+};
+
+template <typename T_, typename TI_>
+struct CMax {
+ typedef T_ T;
+ typedef TI_ TI;
+ typedef CMin<T_, TI_> Crev;
+ inline static bool cmp(T a, T b) {
+ return a > b;
+ }
+ // Similar to cmp(), but also breaks ties
+ // by comparing the second pair of arguments.
+ inline static bool cmp2(T a1, T b1, TI a2, TI b2) {
+ return (a1 > b1) || ((a1 == b1) && (a2 > b2));
+ }
+ inline static T neutral() {
+ return std::numeric_limits<T>::max();
+ }
+ static const bool is_max = true;
+ inline static T nextafter(T x) {
+ return cmax_nextafter(x);
+ }
+};
+
+template <>
+inline float cmin_nextafter<float>(float x) {
+ return std::nextafterf(x, -HUGE_VALF);
+}
+
+template <>
+inline float cmax_nextafter<float>(float x) {
+ return std::nextafterf(x, HUGE_VALF);
+}
+
+template <>
+inline uint16_t cmin_nextafter<uint16_t>(uint16_t x) {
+ return x - 1;
+}
+
+template <>
+inline uint16_t cmax_nextafter<uint16_t>(uint16_t x) {
+ return x + 1;
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/partitioning.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/partitioning.cpp
new file mode 100644
index 0000000..8fa2787
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/partitioning.cpp
@@ -0,0 +1,1326 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/utils/partitioning.h>
+
+#include <cassert>
+#include <cmath>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/AlignedTable.h>
+#include <faiss/utils/ordered_key_value.h>
+#include <faiss/utils/simdlib.h>
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/******************************************************************
+ * Internal routines
+ ******************************************************************/
+
+namespace partitioning {
+
+template <typename T>
+T median3(T a, T b, T c) {
+ if (a > b) {
+ std::swap(a, b);
+ }
+ if (c > b) {
+ return b;
+ }
+ if (c > a) {
+ return c;
+ }
+ return a;
+}
+
+template <class C>
+typename C::T sample_threshold_median3(
+ const typename C::T* vals,
+ int n,
+ typename C::T thresh_inf,
+ typename C::T thresh_sup) {
+ using T = typename C::T;
+ size_t big_prime = 6700417;
+ T val3[3];
+ int vi = 0;
+
+ for (size_t i = 0; i < n; i++) {
+ T v = vals[(i * big_prime) % n];
+ // thresh_inf < v < thresh_sup (for CMax)
+ if (C::cmp(v, thresh_inf) && C::cmp(thresh_sup, v)) {
+ val3[vi++] = v;
+ if (vi == 3) {
+ break;
+ }
+ }
+ }
+
+ if (vi == 3) {
+ return median3(val3[0], val3[1], val3[2]);
+ } else if (vi != 0) {
+ return val3[0];
+ } else {
+ return thresh_inf;
+ // FAISS_THROW_MSG("too few values to compute a median");
+ }
+}
+
+template <class C>
+void count_lt_and_eq(
+ const typename C::T* vals,
+ size_t n,
+ typename C::T thresh,
+ size_t& n_lt,
+ size_t& n_eq) {
+ n_lt = n_eq = 0;
+
+ for (size_t i = 0; i < n; i++) {
+ typename C::T v = *vals++;
+ if (C::cmp(thresh, v)) {
+ n_lt++;
+ } else if (v == thresh) {
+ n_eq++;
+ }
+ }
+}
+
+template <class C>
+size_t compress_array(
+ typename C::T* vals,
+ typename C::TI* ids,
+ size_t n,
+ typename C::T thresh,
+ size_t n_eq) {
+ size_t wp = 0;
+ for (size_t i = 0; i < n; i++) {
+ if (C::cmp(thresh, vals[i])) {
+ vals[wp] = vals[i];
+ ids[wp] = ids[i];
+ wp++;
+ } else if (n_eq > 0 && vals[i] == thresh) {
+ vals[wp] = vals[i];
+ ids[wp] = ids[i];
+ wp++;
+ n_eq--;
+ }
+ }
+ assert(n_eq == 0);
+ return wp;
+}
+
+#define IFV if (false)
+
+template <class C>
+typename C::T partition_fuzzy_median3(
+ typename C::T* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out) {
+ if (q_min == 0) {
+ if (q_out) {
+ *q_out = C::Crev::neutral();
+ }
+ return 0;
+ }
+ if (q_max >= n) {
+ if (q_out) {
+ *q_out = q_max;
+ }
+ return C::neutral();
+ }
+
+ using T = typename C::T;
+
+ // here we use bissection with a median of 3 to find the threshold and
+ // compress the arrays afterwards. So it's a n*log(n) algoirithm rather than
+ // qselect's O(n) but it avoids shuffling around the array.
+
+ FAISS_THROW_IF_NOT(n >= 3);
+
+ T thresh_inf = C::Crev::neutral();
+ T thresh_sup = C::neutral();
+ T thresh = median3(vals[0], vals[n / 2], vals[n - 1]);
+
+ size_t n_eq = 0, n_lt = 0;
+ size_t q = 0;
+
+ for (int it = 0; it < 200; it++) {
+ count_lt_and_eq<C>(vals, n, thresh, n_lt, n_eq);
+
+ IFV printf(
+ " thresh=%g [%g %g] n_lt=%ld n_eq=%ld, q=%ld:%ld/%ld\n",
+ float(thresh),
+ float(thresh_inf),
+ float(thresh_sup),
+ long(n_lt),
+ long(n_eq),
+ long(q_min),
+ long(q_max),
+ long(n));
+
+ if (n_lt <= q_min) {
+ if (n_lt + n_eq >= q_min) {
+ q = q_min;
+ break;
+ } else {
+ thresh_inf = thresh;
+ }
+ } else if (n_lt <= q_max) {
+ q = n_lt;
+ break;
+ } else {
+ thresh_sup = thresh;
+ }
+
+ // FIXME avoid a second pass over the array to sample the threshold
+ IFV printf(
+ " sample thresh in [%g %g]\n",
+ float(thresh_inf),
+ float(thresh_sup));
+ T new_thresh =
+ sample_threshold_median3<C>(vals, n, thresh_inf, thresh_sup);
+ if (new_thresh == thresh_inf) {
+ // then there is nothing between thresh_inf and thresh_sup
+ break;
+ }
+ thresh = new_thresh;
+ }
+
+ int64_t n_eq_1 = q - n_lt;
+
+ IFV printf("shrink: thresh=%g n_eq_1=%ld\n", float(thresh), long(n_eq_1));
+
+ if (n_eq_1 < 0) { // happens when > q elements are at lower bound
+ q = q_min;
+ thresh = C::Crev::nextafter(thresh);
+ n_eq_1 = q;
+ } else {
+ assert(n_eq_1 <= n_eq);
+ }
+
+ [[maybe_unused]] const int wp =
+ compress_array<C>(vals, ids, n, thresh, n_eq_1);
+
+ assert(wp == q);
+ if (q_out) {
+ *q_out = q;
+ }
+
+ return thresh;
+}
+
+} // namespace partitioning
+
+/******************************************************************
+ * SIMD routines when vals is an aligned array of uint16_t
+ ******************************************************************/
+
+namespace simd_partitioning {
+
+void find_minimax(
+ const uint16_t* vals,
+ size_t n,
+ uint16_t& smin,
+ uint16_t& smax) {
+ simd16uint16 vmin(0xffff), vmax(0);
+ for (size_t i = 0; i + 15 < n; i += 16) {
+ simd16uint16 v(vals + i);
+ vmin.accu_min(v);
+ vmax.accu_max(v);
+ }
+
+ ALIGNED(32) uint16_t tab32[32];
+ vmin.store(tab32);
+ vmax.store(tab32 + 16);
+
+ smin = tab32[0], smax = tab32[16];
+
+ for (int i = 1; i < 16; i++) {
+ smin = std::min(smin, tab32[i]);
+ smax = std::max(smax, tab32[i + 16]);
+ }
+
+ // missing values
+ for (size_t i = (n & ~15); i < n; i++) {
+ smin = std::min(smin, vals[i]);
+ smax = std::max(smax, vals[i]);
+ }
+}
+
+// max func differentiates between CMin and CMax (keep lowest or largest)
+template <class C>
+simd16uint16 max_func(simd16uint16 v, simd16uint16 thr16) {
+ constexpr bool is_max = C::is_max;
+ if (is_max) {
+ return max(v, thr16);
+ } else {
+ return min(v, thr16);
+ }
+}
+
+template <class C>
+void count_lt_and_eq(
+ const uint16_t* vals,
+ int n,
+ uint16_t thresh,
+ size_t& n_lt,
+ size_t& n_eq) {
+ n_lt = n_eq = 0;
+ simd16uint16 thr16(thresh);
+
+ size_t n1 = n / 16;
+
+ for (size_t i = 0; i < n1; i++) {
+ simd16uint16 v(vals);
+ vals += 16;
+ simd16uint16 eqmask = (v == thr16);
+ simd16uint16 max2 = max_func<C>(v, thr16);
+ simd16uint16 gemask = (v == max2);
+ uint32_t bits = get_MSBs(uint16_to_uint8_saturate(eqmask, gemask));
+ int i_eq = __builtin_popcount(bits & 0x00ff00ff);
+ int i_ge = __builtin_popcount(bits) - i_eq;
+ n_eq += i_eq;
+ n_lt += 16 - i_ge;
+ }
+
+ for (size_t i = n1 * 16; i < n; i++) {
+ uint16_t v = *vals++;
+ if (C::cmp(thresh, v)) {
+ n_lt++;
+ } else if (v == thresh) {
+ n_eq++;
+ }
+ }
+}
+
+/* compress separated values and ids table, keeping all values < thresh and at
+ * most n_eq equal values */
+template <class C>
+int simd_compress_array(
+ uint16_t* vals,
+ typename C::TI* ids,
+ size_t n,
+ uint16_t thresh,
+ int n_eq) {
+ simd16uint16 thr16(thresh);
+ simd16uint16 mixmask(0xff00);
+
+ int wp = 0;
+ size_t i0;
+
+ // loop while there are eqs to collect
+ for (i0 = 0; i0 + 15 < n && n_eq > 0; i0 += 16) {
+ simd16uint16 v(vals + i0);
+ simd16uint16 max2 = max_func<C>(v, thr16);
+ simd16uint16 gemask = (v == max2);
+ simd16uint16 eqmask = (v == thr16);
+ uint32_t bits = get_MSBs(
+ blendv(simd32uint8(eqmask),
+ simd32uint8(gemask),
+ simd32uint8(mixmask)));
+ bits ^= 0xAAAAAAAA;
+ // bit 2*i : eq
+ // bit 2*i + 1 : lt
+
+ while (bits) {
+ int j = __builtin_ctz(bits) & (~1);
+ bool is_eq = (bits >> j) & 1;
+ bool is_lt = (bits >> j) & 2;
+ bits &= ~(3 << j);
+ j >>= 1;
+
+ if (is_lt) {
+ vals[wp] = vals[i0 + j];
+ ids[wp] = ids[i0 + j];
+ wp++;
+ } else if (is_eq && n_eq > 0) {
+ vals[wp] = vals[i0 + j];
+ ids[wp] = ids[i0 + j];
+ wp++;
+ n_eq--;
+ }
+ }
+ }
+
+ // handle remaining, only striclty lt ones.
+ for (; i0 + 15 < n; i0 += 16) {
+ simd16uint16 v(vals + i0);
+ simd16uint16 max2 = max_func<C>(v, thr16);
+ simd16uint16 gemask = (v == max2);
+ uint32_t bits = ~get_MSBs(simd32uint8(gemask));
+
+ while (bits) {
+ int j = __builtin_ctz(bits);
+ bits &= ~(3 << j);
+ j >>= 1;
+
+ vals[wp] = vals[i0 + j];
+ ids[wp] = ids[i0 + j];
+ wp++;
+ }
+ }
+
+ // end with scalar
+ for (int i = (n & ~15); i < n; i++) {
+ if (C::cmp(thresh, vals[i])) {
+ vals[wp] = vals[i];
+ ids[wp] = ids[i];
+ wp++;
+ } else if (vals[i] == thresh && n_eq > 0) {
+ vals[wp] = vals[i];
+ ids[wp] = ids[i];
+ wp++;
+ n_eq--;
+ }
+ }
+ assert(n_eq == 0);
+ return wp;
+}
+
+// #define MICRO_BENCHMARK
+
+static uint64_t get_cy() {
+#ifdef MICRO_BENCHMARK
+ uint32_t high, low;
+ asm volatile("rdtsc \n\t" : "=a"(low), "=d"(high));
+ return ((uint64_t)high << 32) | (low);
+#else
+ return 0;
+#endif
+}
+
+#define IFV if (false)
+
+template <class C>
+uint16_t simd_partition_fuzzy_with_bounds(
+ uint16_t* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out,
+ uint16_t s0i,
+ uint16_t s1i) {
+ if (q_min == 0) {
+ if (q_out) {
+ *q_out = 0;
+ }
+ return 0;
+ }
+ if (q_max >= n) {
+ if (q_out) {
+ *q_out = q_max;
+ }
+ return 0xffff;
+ }
+ if (s0i == s1i) {
+ if (q_out) {
+ *q_out = q_min;
+ }
+ return s0i;
+ }
+ uint64_t t0 = get_cy();
+
+ // lower bound inclusive, upper exclusive
+ size_t s0 = s0i, s1 = s1i + 1;
+
+ IFV printf("bounds: %ld %ld\n", s0, s1 - 1);
+
+ int thresh;
+ size_t n_eq = 0, n_lt = 0;
+ size_t q = 0;
+
+ for (int it = 0; it < 200; it++) {
+ // while(s0 + 1 < s1) {
+ thresh = (s0 + s1) / 2;
+ count_lt_and_eq<C>(vals, n, thresh, n_lt, n_eq);
+
+ IFV printf(
+ " [%ld %ld] thresh=%d n_lt=%ld n_eq=%ld, q=%ld:%ld/%ld\n",
+ s0,
+ s1,
+ thresh,
+ n_lt,
+ n_eq,
+ q_min,
+ q_max,
+ n);
+ if (n_lt <= q_min) {
+ if (n_lt + n_eq >= q_min) {
+ q = q_min;
+ break;
+ } else {
+ if (C::is_max) {
+ s0 = thresh;
+ } else {
+ s1 = thresh;
+ }
+ }
+ } else if (n_lt <= q_max) {
+ q = n_lt;
+ break;
+ } else {
+ if (C::is_max) {
+ s1 = thresh;
+ } else {
+ s0 = thresh;
+ }
+ }
+ }
+
+ uint64_t t1 = get_cy();
+
+ // number of equal values to keep
+ int64_t n_eq_1 = q - n_lt;
+
+ IFV printf("shrink: thresh=%d q=%ld n_eq_1=%ld\n", thresh, q, n_eq_1);
+ if (n_eq_1 < 0) { // happens when > q elements are at lower bound
+ assert(s0 + 1 == s1);
+ q = q_min;
+ if (C::is_max) {
+ thresh--;
+ } else {
+ thresh++;
+ }
+ n_eq_1 = q;
+ IFV printf(" override: thresh=%d n_eq_1=%ld\n", thresh, n_eq_1);
+ } else {
+ assert(n_eq_1 <= n_eq);
+ }
+
+ size_t wp = simd_compress_array<C>(vals, ids, n, thresh, n_eq_1);
+
+ IFV printf("wp=%ld\n", wp);
+ assert(wp == q);
+ if (q_out) {
+ *q_out = q;
+ }
+
+ uint64_t t2 = get_cy();
+
+ partition_stats.bissect_cycles += t1 - t0;
+ partition_stats.compress_cycles += t2 - t1;
+
+ return thresh;
+}
+
+template <class C>
+uint16_t simd_partition_fuzzy_with_bounds_histogram(
+ uint16_t* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out,
+ uint16_t s0i,
+ uint16_t s1i) {
+ if (q_min == 0) {
+ if (q_out) {
+ *q_out = 0;
+ }
+ return 0;
+ }
+ if (q_max >= n) {
+ if (q_out) {
+ *q_out = q_max;
+ }
+ return 0xffff;
+ }
+ if (s0i == s1i) {
+ if (q_out) {
+ *q_out = q_min;
+ }
+ return s0i;
+ }
+
+ IFV printf(
+ "partition fuzzy, q=%ld:%ld / %ld, bounds=%d %d\n",
+ q_min,
+ q_max,
+ n,
+ s0i,
+ s1i);
+
+ if (!C::is_max) {
+ IFV printf(
+ "revert due to CMin, q_min:q_max -> %ld:%ld\n", q_min, q_max);
+ q_min = n - q_min;
+ q_max = n - q_max;
+ }
+
+ // lower and upper bound of range, inclusive
+ int s0 = s0i, s1 = s1i;
+ // number of values < s0 and > s1
+ size_t n_lt = 0, n_gt = 0;
+
+ // output of loop:
+ int thresh; // final threshold
+ uint64_t tot_eq = 0; // total nb of equal values
+ uint64_t n_eq = 0; // nb of equal values to keep
+ size_t q; // final quantile
+
+ // buffer for the histograms
+ int hist[16];
+
+ for (int it = 0; it < 20; it++) {
+ // otherwise we would be done already
+
+ int shift = 0;
+
+ IFV printf(
+ " it %d bounds: %d %d n_lt=%ld n_gt=%ld\n",
+ it,
+ s0,
+ s1,
+ n_lt,
+ n_gt);
+
+ int maxval = s1 - s0;
+
+ while (maxval > 15) {
+ shift++;
+ maxval >>= 1;
+ }
+
+ IFV printf(
+ " histogram shift %d maxval %d ?= %d\n",
+ shift,
+ maxval,
+ int((s1 - s0) >> shift));
+
+ if (maxval > 7) {
+ simd_histogram_16(vals, n, s0, shift, hist);
+ } else {
+ simd_histogram_8(vals, n, s0, shift, hist);
+ }
+ IFV {
+ int sum = n_lt + n_gt;
+ printf(" n_lt=%ld hist=[", n_lt);
+ for (int i = 0; i <= maxval; i++) {
+ printf("%d ", hist[i]);
+ sum += hist[i];
+ }
+ printf("] n_gt=%ld sum=%d\n", n_gt, sum);
+ assert(sum == n);
+ }
+
+ size_t sum_below = n_lt;
+ int i;
+ for (i = 0; i <= maxval; i++) {
+ sum_below += hist[i];
+ if (sum_below >= q_min) {
+ break;
+ }
+ }
+ IFV printf(" i=%d sum_below=%ld\n", i, sum_below);
+ if (i <= maxval) {
+ s0 = s0 + (i << shift);
+ s1 = s0 + (1 << shift) - 1;
+ n_lt = sum_below - hist[i];
+ n_gt = n - sum_below;
+ } else {
+ assert(!"not implemented");
+ }
+
+ IFV printf(
+ " new bin: s0=%d s1=%d n_lt=%ld n_gt=%ld\n",
+ s0,
+ s1,
+ n_lt,
+ n_gt);
+
+ if (s1 > s0) {
+ if (n_lt >= q_min && q_max >= n_lt) {
+ IFV printf(" FOUND1\n");
+ thresh = s0;
+ q = n_lt;
+ break;
+ }
+
+ size_t n_lt_2 = n - n_gt;
+ if (n_lt_2 >= q_min && q_max >= n_lt_2) {
+ thresh = s1 + 1;
+ q = n_lt_2;
+ IFV printf(" FOUND2\n");
+ break;
+ }
+ } else {
+ thresh = s0;
+ q = q_min;
+ tot_eq = n - n_gt - n_lt;
+ n_eq = q_min - n_lt;
+ IFV printf(" FOUND3\n");
+ break;
+ }
+ }
+
+ IFV printf("end bissection: thresh=%d q=%ld n_eq=%ld\n", thresh, q, n_eq);
+
+ if (!C::is_max) {
+ if (n_eq == 0) {
+ thresh--;
+ } else {
+ // thresh unchanged
+ n_eq = tot_eq - n_eq;
+ }
+ q = n - q;
+ IFV printf("revert due to CMin, q->%ld n_eq->%ld\n", q, n_eq);
+ }
+
+ size_t wp = simd_compress_array<C>(vals, ids, n, thresh, n_eq);
+ IFV printf("wp=%ld ?= %ld\n", wp, q);
+ assert(wp == q);
+ if (q_out) {
+ *q_out = wp;
+ }
+
+ return thresh;
+}
+
+template <class C>
+uint16_t simd_partition_fuzzy(
+ uint16_t* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out) {
+ assert(is_aligned_pointer(vals));
+
+ uint16_t s0i, s1i;
+ find_minimax(vals, n, s0i, s1i);
+ // QSelect_stats.t0 += get_cy() - t0;
+
+ return simd_partition_fuzzy_with_bounds<C>(
+ vals, ids, n, q_min, q_max, q_out, s0i, s1i);
+}
+
+template <class C>
+uint16_t simd_partition(
+ uint16_t* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q) {
+ assert(is_aligned_pointer(vals));
+
+ if (q == 0) {
+ return 0;
+ }
+ if (q >= n) {
+ return 0xffff;
+ }
+
+ uint16_t s0i, s1i;
+ find_minimax(vals, n, s0i, s1i);
+
+ return simd_partition_fuzzy_with_bounds<C>(
+ vals, ids, n, q, q, nullptr, s0i, s1i);
+}
+
+template <class C>
+uint16_t simd_partition_with_bounds(
+ uint16_t* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q,
+ uint16_t s0i,
+ uint16_t s1i) {
+ return simd_partition_fuzzy_with_bounds<C>(
+ vals, ids, n, q, q, nullptr, s0i, s1i);
+}
+
+} // namespace simd_partitioning
+
+/******************************************************************
+ * Driver routine
+ ******************************************************************/
+
+template <class C>
+typename C::T partition_fuzzy(
+ typename C::T* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out) {
+#ifdef __AVX2__
+ constexpr bool is_uint16 = std::is_same<typename C::T, uint16_t>::value;
+ if (is_uint16 && is_aligned_pointer(vals)) {
+ return simd_partitioning::simd_partition_fuzzy<C>(
+ (uint16_t*)vals, ids, n, q_min, q_max, q_out);
+ }
+#endif
+ return partitioning::partition_fuzzy_median3<C>(
+ vals, ids, n, q_min, q_max, q_out);
+}
+
+// explicit template instanciations
+
+template float partition_fuzzy<CMin<float, int64_t>>(
+ float* vals,
+ int64_t* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+template float partition_fuzzy<CMax<float, int64_t>>(
+ float* vals,
+ int64_t* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+template uint16_t partition_fuzzy<CMin<uint16_t, int64_t>>(
+ uint16_t* vals,
+ int64_t* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+template uint16_t partition_fuzzy<CMax<uint16_t, int64_t>>(
+ uint16_t* vals,
+ int64_t* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+template uint16_t partition_fuzzy<CMin<uint16_t, int>>(
+ uint16_t* vals,
+ int* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+template uint16_t partition_fuzzy<CMax<uint16_t, int>>(
+ uint16_t* vals,
+ int* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+/******************************************************************
+ * Histogram subroutines
+ ******************************************************************/
+
+#if defined(__AVX2__) || defined(__aarch64__)
+/// FIXME when MSB of uint16 is set
+// this code does not compile properly with GCC 7.4.0
+
+namespace {
+
+/************************************************************
+ * 8 bins
+ ************************************************************/
+
+simd32uint8 accu4to8(simd16uint16 a4) {
+ simd16uint16 mask4(0x0f0f);
+
+ simd16uint16 a8_0 = a4 & mask4;
+ simd16uint16 a8_1 = (a4 >> 4) & mask4;
+
+ return simd32uint8(hadd(a8_0, a8_1));
+}
+
+simd16uint16 accu8to16(simd32uint8 a8) {
+ simd16uint16 mask8(0x00ff);
+
+ simd16uint16 a8_0 = simd16uint16(a8) & mask8;
+ simd16uint16 a8_1 = (simd16uint16(a8) >> 8) & mask8;
+
+ return hadd(a8_0, a8_1);
+}
+
+static const simd32uint8 shifts = simd32uint8::create<
+ 1,
+ 16,
+ 0,
+ 0,
+ 4,
+ 64,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 16,
+ 0,
+ 0,
+ 4,
+ 64,
+ 1,
+ 16,
+ 0,
+ 0,
+ 4,
+ 64,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 16,
+ 0,
+ 0,
+ 4,
+ 64>();
+
+// 2-bit accumulator: we can add only up to 3 elements
+// on output we return 2*4-bit results
+// preproc returns either an index in 0..7 or 0xffff
+// that yields a 0 when used in the table look-up
+template <int N, class Preproc>
+void compute_accu2(
+ const uint16_t*& data,
+ Preproc& pp,
+ simd16uint16& a4lo,
+ simd16uint16& a4hi) {
+ simd16uint16 mask2(0x3333);
+ simd16uint16 a2((uint16_t)0); // 2-bit accu
+ for (int j = 0; j < N; j++) {
+ simd16uint16 v(data);
+ data += 16;
+ v = pp(v);
+ // 0x800 -> force second half of table
+ simd16uint16 idx = v | (v << 8) | simd16uint16(0x800);
+ a2 += simd16uint16(shifts.lookup_2_lanes(simd32uint8(idx)));
+ }
+ a4lo += a2 & mask2;
+ a4hi += (a2 >> 2) & mask2;
+}
+
+template <class Preproc>
+simd16uint16 histogram_8(const uint16_t* data, Preproc pp, size_t n_in) {
+ assert(n_in % 16 == 0);
+ int n = n_in / 16;
+
+ simd32uint8 a8lo(0);
+ simd32uint8 a8hi(0);
+
+ for (int i0 = 0; i0 < n; i0 += 15) {
+ simd16uint16 a4lo(0); // 4-bit accus
+ simd16uint16 a4hi(0);
+
+ int i1 = std::min(i0 + 15, n);
+ int i;
+ for (i = i0; i + 2 < i1; i += 3) {
+ compute_accu2<3>(data, pp, a4lo, a4hi); // adds 3 max
+ }
+ switch (i1 - i) {
+ case 2:
+ compute_accu2<2>(data, pp, a4lo, a4hi);
+ break;
+ case 1:
+ compute_accu2<1>(data, pp, a4lo, a4hi);
+ break;
+ }
+
+ a8lo += accu4to8(a4lo);
+ a8hi += accu4to8(a4hi);
+ }
+
+ // move to 16-bit accu
+ simd16uint16 a16lo = accu8to16(a8lo);
+ simd16uint16 a16hi = accu8to16(a8hi);
+
+ simd16uint16 a16 = hadd(a16lo, a16hi);
+
+ // the 2 lanes must still be combined
+ return a16;
+}
+
+/************************************************************
+ * 16 bins
+ ************************************************************/
+
+static const simd32uint8 shifts2 = simd32uint8::create<
+ 1,
+ 2,
+ 4,
+ 8,
+ 16,
+ 32,
+ 64,
+ 128,
+ 1,
+ 2,
+ 4,
+ 8,
+ 16,
+ 32,
+ 64,
+ 128,
+ 1,
+ 2,
+ 4,
+ 8,
+ 16,
+ 32,
+ 64,
+ 128,
+ 1,
+ 2,
+ 4,
+ 8,
+ 16,
+ 32,
+ 64,
+ 128>();
+
+simd32uint8 shiftr_16(simd32uint8 x, int n) {
+ return simd32uint8(simd16uint16(x) >> n);
+}
+
+// 2-bit accumulator: we can add only up to 3 elements
+// on output we return 2*4-bit results
+template <int N, class Preproc>
+void compute_accu2_16(
+ const uint16_t*& data,
+ Preproc pp,
+ simd32uint8& a4_0,
+ simd32uint8& a4_1,
+ simd32uint8& a4_2,
+ simd32uint8& a4_3) {
+ simd32uint8 mask1(0x55);
+ simd32uint8 a2_0; // 2-bit accu
+ simd32uint8 a2_1; // 2-bit accu
+ a2_0.clear();
+ a2_1.clear();
+
+ for (int j = 0; j < N; j++) {
+ simd16uint16 v(data);
+ data += 16;
+ v = pp(v);
+
+ simd16uint16 idx = v | (v << 8);
+ simd32uint8 a1 = shifts2.lookup_2_lanes(simd32uint8(idx));
+ // contains 0s for out-of-bounds elements
+
+ simd16uint16 lt8 = (v >> 3) == simd16uint16(0);
+ lt8 = lt8 ^ simd16uint16(0xff00);
+
+ a1 = a1 & lt8;
+
+ a2_0 += a1 & mask1;
+ a2_1 += shiftr_16(a1, 1) & mask1;
+ }
+ simd32uint8 mask2(0x33);
+
+ a4_0 += a2_0 & mask2;
+ a4_1 += a2_1 & mask2;
+ a4_2 += shiftr_16(a2_0, 2) & mask2;
+ a4_3 += shiftr_16(a2_1, 2) & mask2;
+}
+
+simd32uint8 accu4to8_2(simd32uint8 a4_0, simd32uint8 a4_1) {
+ simd32uint8 mask4(0x0f);
+
+ simd16uint16 a8_0 = combine2x2(
+ (simd16uint16)(a4_0 & mask4),
+ (simd16uint16)(shiftr_16(a4_0, 4) & mask4));
+
+ simd16uint16 a8_1 = combine2x2(
+ (simd16uint16)(a4_1 & mask4),
+ (simd16uint16)(shiftr_16(a4_1, 4) & mask4));
+
+ return simd32uint8(hadd(a8_0, a8_1));
+}
+
+template <class Preproc>
+simd16uint16 histogram_16(const uint16_t* data, Preproc pp, size_t n_in) {
+ assert(n_in % 16 == 0);
+ int n = n_in / 16;
+
+ simd32uint8 a8lo((uint8_t)0);
+ simd32uint8 a8hi((uint8_t)0);
+
+ for (int i0 = 0; i0 < n; i0 += 7) {
+ simd32uint8 a4_0(0); // 0, 4, 8, 12
+ simd32uint8 a4_1(0); // 1, 5, 9, 13
+ simd32uint8 a4_2(0); // 2, 6, 10, 14
+ simd32uint8 a4_3(0); // 3, 7, 11, 15
+
+ int i1 = std::min(i0 + 7, n);
+ int i;
+ for (i = i0; i + 2 < i1; i += 3) {
+ compute_accu2_16<3>(data, pp, a4_0, a4_1, a4_2, a4_3);
+ }
+ switch (i1 - i) {
+ case 2:
+ compute_accu2_16<2>(data, pp, a4_0, a4_1, a4_2, a4_3);
+ break;
+ case 1:
+ compute_accu2_16<1>(data, pp, a4_0, a4_1, a4_2, a4_3);
+ break;
+ }
+
+ a8lo += accu4to8_2(a4_0, a4_1);
+ a8hi += accu4to8_2(a4_2, a4_3);
+ }
+
+ // move to 16-bit accu
+ simd16uint16 a16lo = accu8to16(a8lo);
+ simd16uint16 a16hi = accu8to16(a8hi);
+
+ simd16uint16 a16 = hadd(a16lo, a16hi);
+
+ a16 = simd16uint16{simd8uint32{a16}.unzip()};
+
+ return a16;
+}
+
+struct PreprocNOP {
+ simd16uint16 operator()(simd16uint16 x) {
+ return x;
+ }
+};
+
+template <int shift, int nbin>
+struct PreprocMinShift {
+ simd16uint16 min16;
+ simd16uint16 max16;
+
+ explicit PreprocMinShift(uint16_t min) {
+ min16.set1(min);
+ int vmax0 = std::min((nbin << shift) + min, 65536);
+ uint16_t vmax = uint16_t(vmax0 - 1 - min);
+ max16.set1(vmax); // vmax inclusive
+ }
+
+ simd16uint16 operator()(simd16uint16 x) {
+ x = x - min16;
+ simd16uint16 mask = (x == max(x, max16)) - (x == max16);
+ return (x >> shift) | mask;
+ }
+};
+
+/* unbounded versions of the functions */
+
+void simd_histogram_8_unbounded(const uint16_t* data, int n, int* hist) {
+ PreprocNOP pp;
+ simd16uint16 a16 = histogram_8(data, pp, (n & ~15));
+
+ ALIGNED(32) uint16_t a16_tab[16];
+ a16.store(a16_tab);
+
+ for (int i = 0; i < 8; i++) {
+ hist[i] = a16_tab[i] + a16_tab[i + 8];
+ }
+
+ for (int i = (n & ~15); i < n; i++) {
+ hist[data[i]]++;
+ }
+}
+
+void simd_histogram_16_unbounded(const uint16_t* data, int n, int* hist) {
+ simd16uint16 a16 = histogram_16(data, PreprocNOP(), (n & ~15));
+
+ ALIGNED(32) uint16_t a16_tab[16];
+ a16.store(a16_tab);
+
+ for (int i = 0; i < 16; i++) {
+ hist[i] = a16_tab[i];
+ }
+
+ for (int i = (n & ~15); i < n; i++) {
+ hist[data[i]]++;
+ }
+}
+
+} // anonymous namespace
+
+/************************************************************
+ * Driver routines
+ ************************************************************/
+
+void simd_histogram_8(
+ const uint16_t* data,
+ int n,
+ uint16_t min,
+ int shift,
+ int* hist) {
+ if (shift < 0) {
+ simd_histogram_8_unbounded(data, n, hist);
+ return;
+ }
+
+ simd16uint16 a16;
+
+#define DISPATCH(s) \
+ case s: \
+ a16 = histogram_8(data, PreprocMinShift<s, 8>(min), (n & ~15)); \
+ break
+
+ switch (shift) {
+ DISPATCH(0);
+ DISPATCH(1);
+ DISPATCH(2);
+ DISPATCH(3);
+ DISPATCH(4);
+ DISPATCH(5);
+ DISPATCH(6);
+ DISPATCH(7);
+ DISPATCH(8);
+ DISPATCH(9);
+ DISPATCH(10);
+ DISPATCH(11);
+ DISPATCH(12);
+ DISPATCH(13);
+ default:
+ FAISS_THROW_FMT("dispatch for shift=%d not instantiated", shift);
+ }
+#undef DISPATCH
+
+ ALIGNED(32) uint16_t a16_tab[16];
+ a16.store(a16_tab);
+
+ for (int i = 0; i < 8; i++) {
+ hist[i] = a16_tab[i] + a16_tab[i + 8];
+ }
+
+ // complete with remaining bins
+ for (int i = (n & ~15); i < n; i++) {
+ if (data[i] < min)
+ continue;
+ uint16_t v = data[i] - min;
+ v >>= shift;
+ if (v < 8)
+ hist[v]++;
+ }
+}
+
+void simd_histogram_16(
+ const uint16_t* data,
+ int n,
+ uint16_t min,
+ int shift,
+ int* hist) {
+ if (shift < 0) {
+ simd_histogram_16_unbounded(data, n, hist);
+ return;
+ }
+
+ simd16uint16 a16;
+
+#define DISPATCH(s) \
+ case s: \
+ a16 = histogram_16(data, PreprocMinShift<s, 16>(min), (n & ~15)); \
+ break
+
+ switch (shift) {
+ DISPATCH(0);
+ DISPATCH(1);
+ DISPATCH(2);
+ DISPATCH(3);
+ DISPATCH(4);
+ DISPATCH(5);
+ DISPATCH(6);
+ DISPATCH(7);
+ DISPATCH(8);
+ DISPATCH(9);
+ DISPATCH(10);
+ DISPATCH(11);
+ DISPATCH(12);
+ default:
+ FAISS_THROW_FMT("dispatch for shift=%d not instantiated", shift);
+ }
+#undef DISPATCH
+
+ ALIGNED(32) uint16_t a16_tab[16];
+ a16.store(a16_tab);
+
+ for (int i = 0; i < 16; i++) {
+ hist[i] = a16_tab[i];
+ }
+
+ for (int i = (n & ~15); i < n; i++) {
+ if (data[i] < min)
+ continue;
+ uint16_t v = data[i] - min;
+ v >>= shift;
+ if (v < 16)
+ hist[v]++;
+ }
+}
+
+// no AVX2
+#else
+
+void simd_histogram_16(
+ const uint16_t* data,
+ int n,
+ uint16_t min,
+ int shift,
+ int* hist) {
+ memset(hist, 0, sizeof(*hist) * 16);
+ if (shift < 0) {
+ for (size_t i = 0; i < n; i++) {
+ hist[data[i]]++;
+ }
+ } else {
+ int vmax0 = std::min((16 << shift) + min, 65536);
+ uint16_t vmax = uint16_t(vmax0 - 1 - min);
+
+ for (size_t i = 0; i < n; i++) {
+ uint16_t v = data[i];
+ v -= min;
+ if (!(v <= vmax))
+ continue;
+ v >>= shift;
+ hist[v]++;
+
+ /*
+ if (data[i] < min) continue;
+ uint16_t v = data[i] - min;
+ v >>= shift;
+ if (v < 16) hist[v]++;
+ */
+ }
+ }
+}
+
+void simd_histogram_8(
+ const uint16_t* data,
+ int n,
+ uint16_t min,
+ int shift,
+ int* hist) {
+ memset(hist, 0, sizeof(*hist) * 8);
+ if (shift < 0) {
+ for (size_t i = 0; i < n; i++) {
+ hist[data[i]]++;
+ }
+ } else {
+ for (size_t i = 0; i < n; i++) {
+ if (data[i] < min)
+ continue;
+ uint16_t v = data[i] - min;
+ v >>= shift;
+ if (v < 8)
+ hist[v]++;
+ }
+ }
+}
+
+#endif
+
+void PartitionStats::reset() {
+ memset(this, 0, sizeof(*this));
+}
+
+PartitionStats partition_stats;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/partitioning.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/partitioning.h
new file mode 100644
index 0000000..66f8780
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/partitioning.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <stdio.h>
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/** partitions the table into 0:q and q:n where all elements above q are >= all
+ * elements below q (for C = CMax, for CMin comparisons are reversed)
+ *
+ * Returns the partition threshold. The elements q:n are destroyed on output.
+ */
+template <class C>
+typename C::T partition_fuzzy(
+ typename C::T* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q_min,
+ size_t q_max,
+ size_t* q_out);
+
+/** simplified interface for when the parition is not fuzzy */
+template <class C>
+inline typename C::T partition(
+ typename C::T* vals,
+ typename C::TI* ids,
+ size_t n,
+ size_t q) {
+ return partition_fuzzy<C>(vals, ids, n, q, q, nullptr);
+}
+
+/** low level SIMD histogramming functions */
+
+/** 8-bin histogram of (x - min) >> shift
+ * values outside the range are ignored.
+ * the data table should be aligned on 32 bytes */
+void simd_histogram_8(
+ const uint16_t* data,
+ int n,
+ uint16_t min,
+ int shift,
+ int* hist);
+
+/** same for 16-bin histogram */
+void simd_histogram_16(
+ const uint16_t* data,
+ int n,
+ uint16_t min,
+ int shift,
+ int* hist);
+
+struct PartitionStats {
+ uint64_t bissect_cycles;
+ uint64_t compress_cycles;
+
+ PartitionStats() {
+ reset();
+ }
+ void reset();
+};
+
+// global var that collects them all
+FAISS_API extern PartitionStats partition_stats;
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/prefetch.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/prefetch.h
new file mode 100644
index 0000000..7afe58a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/prefetch.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// prefetches
+
+#ifdef __AVX__
+
+// AVX
+
+#include <xmmintrin.h>
+
+inline void prefetch_L1(const void* address) {
+ _mm_prefetch((const char*)address, _MM_HINT_T0);
+}
+inline void prefetch_L2(const void* address) {
+ _mm_prefetch((const char*)address, _MM_HINT_T1);
+}
+inline void prefetch_L3(const void* address) {
+ _mm_prefetch((const char*)address, _MM_HINT_T2);
+}
+
+#elif defined(__aarch64__)
+
+// ARM64
+
+#ifdef _MSC_VER
+
+// todo: arm on MSVC
+inline void prefetch_L1(const void* address) {}
+inline void prefetch_L2(const void* address) {}
+inline void prefetch_L3(const void* address) {}
+
+#else
+// arm on non-MSVC
+
+inline void prefetch_L1(const void* address) {
+ __builtin_prefetch(address, 0, 3);
+}
+inline void prefetch_L2(const void* address) {
+ __builtin_prefetch(address, 0, 2);
+}
+inline void prefetch_L3(const void* address) {
+ __builtin_prefetch(address, 0, 1);
+}
+#endif
+
+#else
+
+// a generic platform
+
+#ifdef _MSC_VER
+
+inline void prefetch_L1(const void* address) {}
+inline void prefetch_L2(const void* address) {}
+inline void prefetch_L3(const void* address) {}
+
+#else
+
+inline void prefetch_L1(const void* address) {
+ __builtin_prefetch(address, 0, 3);
+}
+inline void prefetch_L2(const void* address) {
+ __builtin_prefetch(address, 0, 2);
+}
+inline void prefetch_L3(const void* address) {
+ __builtin_prefetch(address, 0, 1);
+}
+
+#endif
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/quantize_lut.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/quantize_lut.cpp
new file mode 100644
index 0000000..9253d23
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/quantize_lut.cpp
@@ -0,0 +1,337 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/utils/quantize_lut.h>
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <vector>
+
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+namespace quantize_lut {
+
+/******************************************************
+ * Quantize look-up tables
+ ******************************************************/
+
+namespace {
+
+// there can be NaNs in tables, they should be ignored
+float tab_min(const float* tab, size_t n) {
+ float min = HUGE_VAL;
+ for (int i = 0; i < n; i++) {
+ if (tab[i] < min)
+ min = tab[i];
+ }
+ return min;
+}
+
+float tab_max(const float* tab, size_t n) {
+ float max = -HUGE_VAL;
+ for (int i = 0; i < n; i++) {
+ if (tab[i] > max)
+ max = tab[i];
+ }
+ return max;
+}
+
+void round_tab(float* tab, size_t n, float a, float bi) {
+ for (int i = 0; i < n; i++) {
+ tab[i] = floorf((tab[i] - bi) * a + 0.5);
+ }
+}
+
+template <typename T>
+void round_tab(const float* tab, size_t n, float a, float bi, T* tab_out) {
+ for (int i = 0; i < n; i++) {
+ tab_out[i] = (T)floorf((tab[i] - bi) * a + 0.5);
+ }
+}
+
+} // anonymous namespace
+
+void round_uint8_per_column(
+ float* tab,
+ size_t n,
+ size_t d,
+ float* a_out,
+ float* b_out) {
+ float max_span = 0;
+ std::vector<float> mins(n);
+ for (int i = 0; i < n; i++) {
+ mins[i] = tab_min(tab + i * d, d);
+ float span = tab_max(tab + i * d, d) - mins[i];
+ if (span > max_span) {
+ max_span = span;
+ }
+ }
+ float a = 255 / max_span;
+ float b = 0;
+ for (int i = 0; i < n; i++) {
+ b += mins[i];
+ round_tab(tab + i * d, d, a, mins[i]);
+ }
+ if (a_out)
+ *a_out = a;
+ if (b_out)
+ *b_out = b;
+}
+
+void round_uint8_per_column_multi(
+ float* tab,
+ size_t m,
+ size_t n,
+ size_t d,
+ float* a_out,
+ float* b_out) {
+ float max_span = 0;
+ std::vector<float> mins(n);
+ for (int i = 0; i < n; i++) {
+ float min_i = HUGE_VAL;
+ float max_i = -HUGE_VAL;
+ for (int j = 0; j < m; j++) {
+ min_i = std::min(min_i, tab_min(tab + (j * n + i) * d, d));
+ max_i = std::max(max_i, tab_max(tab + (j * n + i) * d, d));
+ }
+ mins[i] = min_i;
+ float span = max_i - min_i;
+ if (span > max_span) {
+ max_span = span;
+ }
+ }
+ float a = 255 / max_span;
+ float b = 0;
+ for (int i = 0; i < n; i++) {
+ b += mins[i];
+ for (int j = 0; j < m; j++) {
+ round_tab(tab + (j * n + i) * d, d, a, mins[i]);
+ }
+ }
+ if (a_out)
+ *a_out = a;
+ if (b_out)
+ *b_out = b;
+}
+
+// translation of
+// https://github.com/fairinternal/faiss_improvements/blob/7122c3cc6ddb0a371d8aa6f1309cd8bcf2335e61/LUT_quantization.ipynb
+void quantize_LUT_and_bias(
+ size_t nprobe,
+ size_t M,
+ size_t ksub,
+ bool lut_is_3d,
+ const float* LUT,
+ const float* bias,
+ uint8_t* LUTq,
+ size_t M2,
+ uint16_t* biasq,
+ float* a_out,
+ float* b_out) {
+ float a, b;
+ if (!bias) {
+ FAISS_THROW_IF_NOT(!lut_is_3d);
+ std::vector<float> mins(M);
+ float max_span_LUT = -HUGE_VAL, max_span_dis = 0;
+ b = 0;
+ for (int i = 0; i < M; i++) {
+ mins[i] = tab_min(LUT + i * ksub, ksub);
+ float span = tab_max(LUT + i * ksub, ksub) - mins[i];
+ max_span_LUT = std::max(max_span_LUT, span);
+ max_span_dis += span;
+ b += mins[i];
+ }
+ a = std::min(255 / max_span_LUT, 65535 / max_span_dis);
+
+ for (int i = 0; i < M; i++) {
+ round_tab(LUT + i * ksub, ksub, a, mins[i], LUTq + i * ksub);
+ }
+ memset(LUTq + M * ksub, 0, ksub * (M2 - M));
+ } else if (!lut_is_3d) {
+ std::vector<float> mins(M);
+ float max_span_LUT = -HUGE_VAL, max_span_dis;
+ float bias_min = tab_min(bias, nprobe);
+ float bias_max = tab_max(bias, nprobe);
+ max_span_dis = bias_max - bias_min;
+ b = 0;
+ for (int i = 0; i < M; i++) {
+ mins[i] = tab_min(LUT + i * ksub, ksub);
+ float span = tab_max(LUT + i * ksub, ksub) - mins[i];
+ max_span_LUT = std::max(max_span_LUT, span);
+ max_span_dis += span;
+ b += mins[i];
+ }
+ a = std::min(255 / max_span_LUT, 65535 / max_span_dis);
+ b += bias_min;
+
+ for (int i = 0; i < M; i++) {
+ round_tab(LUT + i * ksub, ksub, a, mins[i], LUTq + i * ksub);
+ }
+ memset(LUTq + M * ksub, 0, ksub * (M2 - M));
+ round_tab(bias, nprobe, a, bias_min, biasq);
+
+ } else if (biasq) {
+ // LUT is 3D
+ std::vector<float> mins(nprobe * M);
+ std::vector<float> bias2(nprobe);
+ float bias_min = tab_min(bias, nprobe);
+ float max_span_LUT = -HUGE_VAL, max_span_dis = -HUGE_VAL;
+
+ b = HUGE_VAL;
+ size_t ij = 0;
+ for (int j = 0; j < nprobe; j++) {
+ float max_span_dis_j = bias[j] - bias_min;
+ float b2j = bias[j];
+ for (int i = 0; i < M; i++) {
+ mins[ij] = tab_min(LUT + ij * ksub, ksub);
+ float span = tab_max(LUT + ij * ksub, ksub) - mins[ij];
+ max_span_LUT = std::max(max_span_LUT, span);
+ max_span_dis_j += span;
+ b2j += mins[ij];
+ ij++;
+ }
+ max_span_dis = std::max(max_span_dis, max_span_dis_j);
+ bias2[j] = b2j;
+ b = std::min(b, b2j);
+ }
+
+ a = std::min(255 / max_span_LUT, 65535 / max_span_dis);
+
+ ij = 0;
+ size_t ij_2 = 0;
+ for (int j = 0; j < nprobe; j++) {
+ for (int i = 0; i < M; i++) {
+ round_tab(
+ LUT + ij * ksub, ksub, a, mins[ij], LUTq + ij_2 * ksub);
+ ij++;
+ ij_2++;
+ }
+ memset(LUTq + ij_2 * ksub, 0, ksub * (M2 - M));
+ ij_2 += M2 - M;
+ }
+
+ round_tab(bias2.data(), nprobe, a, b, biasq);
+
+ } else { // !biasq
+ // then we integrate the bias into the LUTs
+ std::vector<float> LUT2_storage(nprobe * M * ksub);
+ float* LUT2 = LUT2_storage.data();
+ size_t ijc = 0;
+ for (int j = 0; j < nprobe; j++) {
+ float bias_j = bias[j] / M;
+ for (int i = 0; i < M; i++) {
+ for (int c = 0; c < ksub; c++) {
+ LUT2[ijc] = LUT[ijc] + bias_j;
+ ijc++;
+ }
+ }
+ }
+ std::vector<float> mins(M, HUGE_VAL), maxs(M, -HUGE_VAL);
+ size_t ij = 0;
+ for (int j = 0; j < nprobe; j++) {
+ for (int i = 0; i < M; i++) {
+ mins[i] = std::min(mins[i], tab_min(LUT2 + ij * ksub, ksub));
+ maxs[i] = std::max(maxs[i], tab_max(LUT2 + ij * ksub, ksub));
+ ij++;
+ }
+ }
+
+ float max_span = -HUGE_VAL;
+ b = 0;
+ for (int i = 0; i < M; i++) {
+ float span = maxs[i] - mins[i];
+ max_span = std::max(max_span, span);
+ b += mins[i];
+ }
+ a = 255 / max_span;
+ ij = 0;
+ size_t ij_2 = 0;
+ for (int j = 0; j < nprobe; j++) {
+ for (int i = 0; i < M; i++) {
+ round_tab(
+ LUT2 + ij * ksub, ksub, a, mins[i], LUTq + ij_2 * ksub);
+ ij++;
+ ij_2++;
+ }
+ memset(LUTq + ij_2 * ksub, 0, ksub * (M2 - M));
+ ij_2 += M2 - M;
+ }
+ }
+ if (a_out)
+ *a_out = a;
+ if (b_out)
+ *b_out = b;
+}
+
+void aq_quantize_LUT_and_bias(
+ size_t nprobe,
+ size_t M,
+ size_t ksub,
+ const float* LUT,
+ const float* bias,
+ size_t M_norm,
+ int norm_scale,
+ uint8_t* LUTq,
+ size_t M2,
+ uint16_t* biasq,
+ float* a_out,
+ float* b_out) {
+ float a, b;
+ std::vector<float> mins(M);
+ float max_span_LUT = -HUGE_VAL, max_span_dis;
+ float bias_min = tab_min(bias, nprobe);
+ float bias_max = tab_max(bias, nprobe);
+ max_span_dis = bias_max - bias_min;
+ b = 0;
+ for (int i = 0; i < M; i++) {
+ mins[i] = tab_min(LUT + i * ksub, ksub);
+ float span = tab_max(LUT + i * ksub, ksub) - mins[i];
+ max_span_LUT = std::max(max_span_LUT, span);
+ max_span_dis += (i >= M - M_norm ? span * norm_scale : span);
+ b += mins[i];
+ }
+ a = std::min(255 / max_span_LUT, 65535 / max_span_dis);
+ b += bias_min;
+
+ for (int i = 0; i < M; i++) {
+ round_tab(LUT + i * ksub, ksub, a, mins[i], LUTq + i * ksub);
+ }
+ memset(LUTq + M * ksub, 0, ksub * (M2 - M));
+ round_tab(bias, nprobe, a, bias_min, biasq);
+
+ *a_out = a;
+ *b_out = b;
+}
+
+float aq_estimate_norm_scale(
+ size_t M,
+ size_t ksub,
+ size_t M_norm,
+ const float* LUT) {
+ float max_span_LUT = -HUGE_VAL;
+ for (int i = 0; i < M - M_norm; i++) {
+ float min = tab_min(LUT + i * ksub, ksub);
+ float span = tab_max(LUT + i * ksub, ksub) - min;
+ max_span_LUT = std::max(max_span_LUT, span);
+ }
+
+ float max_span_LUT_norm = -HUGE_VAL;
+ for (int i = M - M_norm; i < M; i++) {
+ float min = tab_min(LUT + i * ksub, ksub);
+ float span = tab_max(LUT + i * ksub, ksub) - min;
+ max_span_LUT_norm = std::max(max_span_LUT_norm, span);
+ }
+
+ return max_span_LUT_norm / max_span_LUT;
+}
+
+} // namespace quantize_lut
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/quantize_lut.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/quantize_lut.h
new file mode 100644
index 0000000..fc9e2dc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/quantize_lut.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <cstdio>
+
+namespace faiss {
+
+/** Functions to quantize PQ floating-point Look Up Tables (LUT) to uint8, and
+ * biases to uint16. The accumulation is supposed to take place in uint16.
+ * The quantization coefficients are float (a, b) such that
+ *
+ * original_value = quantized_value * a / b
+ *
+ * The hardest part of the quantization is with multiple LUTs that need to be
+ * added up together. In that case, coefficient a has to be chosen so that
+ * the sum fits in a uint16 accumulator.
+ */
+
+namespace quantize_lut {
+
+/* affine quantizer, a and b are the affine coefficients, marginalize over d
+ *
+ * @param tab input/output, size (n, d)
+ */
+void round_uint8_per_column(
+ float* tab,
+ size_t n,
+ size_t d,
+ float* a_out = nullptr,
+ float* b_out = nullptr);
+
+/* affine quantizer, a and b are the affine coefficients
+ *
+ * @param tab input/output, size (m, n, d)
+ */
+void round_uint8_per_column_multi(
+ float* tab,
+ size_t m,
+ size_t n,
+ size_t d,
+ float* a_out = nullptr,
+ float* b_out = nullptr);
+
+/** LUT quantization to uint8 and bias to uint16.
+ *
+ * (nprobe, M, ksub, lut_is_3d) determine the size of the the LUT
+ *
+ * LUT input:
+ * - 2D size (M, ksub): single matrix per probe (lut_is_3d=false)
+ * - 3D size (nprobe, M, ksub): separate LUT per probe (lut_is_3d=true)
+ * bias input:
+ * - nullptr: bias is 0
+ * - size (nprobe): one bias per probe
+ * Output:
+ * - LUTq uint8 version of the LUT (M size is rounded up to M2)
+ * - biasq (or nullptr): uint16 version of the LUT
+ * - a, b: scalars to approximate the true distance
+ */
+
+void quantize_LUT_and_bias(
+ size_t nprobe,
+ size_t M,
+ size_t ksub,
+ bool lut_is_3d,
+ const float* LUT,
+ const float* bias,
+ uint8_t* LUTq,
+ size_t M2,
+ uint16_t* biasq,
+ float* a_out = nullptr,
+ float* b_out = nullptr);
+
+void aq_quantize_LUT_and_bias(
+ size_t nprobe,
+ size_t M,
+ size_t ksub,
+ const float* LUT,
+ const float* bias,
+ size_t M_norm,
+ int norm_scale,
+ uint8_t* LUTq,
+ size_t M2,
+ uint16_t* biasq,
+ float* a_out,
+ float* b_out);
+
+float aq_estimate_norm_scale(
+ size_t M,
+ size_t ksub,
+ size_t M_norm,
+ const float* LUT);
+
+} // namespace quantize_lut
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/random.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/random.cpp
new file mode 100644
index 0000000..6187e17
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/random.cpp
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/utils/random.h>
+
+extern "C" {
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+}
+
+namespace faiss {
+
+/**************************************************
+ * Random data generation functions
+ **************************************************/
+
+RandomGenerator::RandomGenerator(int64_t seed) : mt((unsigned int)seed) {}
+
+int RandomGenerator::rand_int() {
+ return mt() & 0x7fffffff;
+}
+
+int64_t RandomGenerator::rand_int64() {
+ return int64_t(rand_int()) | int64_t(rand_int()) << 31;
+}
+
+int RandomGenerator::rand_int(int max) {
+ return mt() % max;
+}
+
+float RandomGenerator::rand_float() {
+ return mt() / float(mt.max());
+}
+
+double RandomGenerator::rand_double() {
+ return mt() / double(mt.max());
+}
+
+SplitMix64RandomGenerator::SplitMix64RandomGenerator(int64_t seed)
+ : state{static_cast<uint64_t>(seed)} {}
+
+int SplitMix64RandomGenerator::rand_int() {
+ return next() & 0x7fffffff;
+}
+
+int64_t SplitMix64RandomGenerator::rand_int64() {
+ uint64_t value = next();
+ return static_cast<int64_t>(value & 0x7fffffffffffffffULL);
+}
+
+int SplitMix64RandomGenerator::rand_int(int max) {
+ return next() % max;
+}
+
+float SplitMix64RandomGenerator::rand_float() {
+ return next() / float(std::numeric_limits<uint64_t>::max());
+}
+
+double SplitMix64RandomGenerator::rand_double() {
+ return next() / double(std::numeric_limits<uint64_t>::max());
+}
+
+uint64_t SplitMix64RandomGenerator::next() {
+ uint64_t z = (state += 0x9e3779b97f4a7c15ULL);
+ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
+ z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
+ return z ^ (z >> 31);
+}
+
+/***********************************************************************
+ * Random functions in this C file only exist because Torch
+ * counterparts are slow and not multi-threaded. Typical use is for
+ * more than 1-100 billion values. */
+
+/* Generate a set of random floating point values such that x[i] in [0,1]
+ multi-threading. For this reason, we rely on re-entreant functions. */
+void float_rand(float* x, size_t n, int64_t seed) {
+ // only try to parallelize on large enough arrays
+ const size_t nblock = n < 1024 ? 1 : 1024;
+
+ RandomGenerator rng0(seed);
+ int a0 = rng0.rand_int(), b0 = rng0.rand_int();
+
+#pragma omp parallel for
+ for (int64_t j = 0; j < nblock; j++) {
+ RandomGenerator rng(a0 + j * b0);
+
+ const size_t istart = j * n / nblock;
+ const size_t iend = (j + 1) * n / nblock;
+
+ for (size_t i = istart; i < iend; i++)
+ x[i] = rng.rand_float();
+ }
+}
+
+void float_randn(float* x, size_t n, int64_t seed) {
+ // only try to parallelize on large enough arrays
+ const size_t nblock = n < 1024 ? 1 : 1024;
+
+ RandomGenerator rng0(seed);
+ int a0 = rng0.rand_int(), b0 = rng0.rand_int();
+
+#pragma omp parallel for
+ for (int64_t j = 0; j < nblock; j++) {
+ RandomGenerator rng(a0 + j * b0);
+
+ double a = 0, b = 0, s = 0;
+ int state = 0; /* generate two number per "do-while" loop */
+
+ const size_t istart = j * n / nblock;
+ const size_t iend = (j + 1) * n / nblock;
+
+ for (size_t i = istart; i < iend; i++) {
+ /* Marsaglia's method (see Knuth) */
+ if (state == 0) {
+ do {
+ a = 2.0 * rng.rand_double() - 1;
+ b = 2.0 * rng.rand_double() - 1;
+ s = a * a + b * b;
+ } while (s >= 1.0);
+ x[i] = a * sqrt(-2.0 * log(s) / s);
+ } else
+ x[i] = b * sqrt(-2.0 * log(s) / s);
+ state = 1 - state;
+ }
+ }
+}
+
+/* Integer versions */
+void int64_rand(int64_t* x, size_t n, int64_t seed) {
+ // only try to parallelize on large enough arrays
+ const size_t nblock = n < 1024 ? 1 : 1024;
+
+ RandomGenerator rng0(seed);
+ int a0 = rng0.rand_int(), b0 = rng0.rand_int();
+
+#pragma omp parallel for
+ for (int64_t j = 0; j < nblock; j++) {
+ RandomGenerator rng(a0 + j * b0);
+
+ const size_t istart = j * n / nblock;
+ const size_t iend = (j + 1) * n / nblock;
+ for (size_t i = istart; i < iend; i++)
+ x[i] = rng.rand_int64();
+ }
+}
+
+void int64_rand_max(int64_t* x, size_t n, uint64_t max, int64_t seed) {
+ // only try to parallelize on large enough arrays
+ const size_t nblock = n < 1024 ? 1 : 1024;
+
+ RandomGenerator rng0(seed);
+ int a0 = rng0.rand_int(), b0 = rng0.rand_int();
+
+#pragma omp parallel for
+ for (int64_t j = 0; j < nblock; j++) {
+ RandomGenerator rng(a0 + j * b0);
+
+ const size_t istart = j * n / nblock;
+ const size_t iend = (j + 1) * n / nblock;
+ for (size_t i = istart; i < iend; i++)
+ x[i] = rng.rand_int64() % max;
+ }
+}
+
+void rand_perm(int* perm, size_t n, int64_t seed) {
+ for (size_t i = 0; i < n; i++)
+ perm[i] = i;
+
+ RandomGenerator rng(seed);
+
+ for (size_t i = 0; i + 1 < n; i++) {
+ int i2 = i + rng.rand_int(n - i);
+ std::swap(perm[i], perm[i2]);
+ }
+}
+
+void rand_perm_splitmix64(int* perm, size_t n, int64_t seed) {
+ for (size_t i = 0; i < n; i++)
+ perm[i] = i;
+
+ SplitMix64RandomGenerator rng(seed);
+
+ for (size_t i = 0; i + 1 < n; i++) {
+ int i2 = i + rng.rand_int(n - i);
+ std::swap(perm[i], perm[i2]);
+ }
+}
+
+void byte_rand(uint8_t* x, size_t n, int64_t seed) {
+ // only try to parallelize on large enough arrays
+ const size_t nblock = n < 1024 ? 1 : 1024;
+
+ RandomGenerator rng0(seed);
+ int a0 = rng0.rand_int(), b0 = rng0.rand_int();
+
+#pragma omp parallel for
+ for (int64_t j = 0; j < nblock; j++) {
+ RandomGenerator rng(a0 + j * b0);
+
+ const size_t istart = j * n / nblock;
+ const size_t iend = (j + 1) * n / nblock;
+
+ size_t i;
+ for (i = istart; i < iend; i++)
+ x[i] = rng.rand_int64();
+ }
+}
+
+void rand_smooth_vectors(size_t n, size_t d, float* x, int64_t seed) {
+ size_t d1 = 10;
+ std::vector<float> x1(n * d1);
+ float_randn(x1.data(), x1.size(), seed);
+ std::vector<float> rot(d1 * d);
+ float_rand(rot.data(), rot.size(), seed + 1);
+
+ { //
+ FINTEGER di = d, d1i = d1, ni = n;
+ float one = 1.0, zero = 0.0;
+ sgemm_("Not transposed",
+ "Not transposed", // natural order
+ &di,
+ &ni,
+ &d1i,
+ &one,
+ rot.data(),
+ &di, // rotation matrix
+ x1.data(),
+ &d1i, // second term
+ &zero,
+ x,
+ &di);
+ }
+
+ std::vector<float> scales(d);
+ float_rand(scales.data(), d, seed + 2);
+
+#pragma omp parallel for if (n * d > 10000)
+ for (int64_t i = 0; i < n; i++) {
+ for (size_t j = 0; j < d; j++) {
+ x[i * d + j] = sinf(x[i * d + j] * (scales[j] * 4 + 0.1));
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/random.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/random.h
new file mode 100644
index 0000000..2e2f3e5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/random.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/* Random generators. Implemented here for speed and to make
+ * sequences reproducible.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <random>
+
+namespace faiss {
+
+/**************************************************
+ * Random data generation functions
+ **************************************************/
+
+/// random generator that can be used in multithreaded contexts
+struct RandomGenerator {
+ std::mt19937 mt;
+
+ /// random positive integer
+ int rand_int();
+
+ /// random int64_t
+ int64_t rand_int64();
+
+ /// generate random integer between 0 and max-1
+ int rand_int(int max);
+
+ /// between 0 and 1
+ float rand_float();
+
+ double rand_double();
+
+ explicit RandomGenerator(int64_t seed = 1234);
+};
+
+/// fast random generator that cannot be used in multithreaded contexts.
+/// based on https://prng.di.unimi.it/
+struct SplitMix64RandomGenerator {
+ uint64_t state;
+
+ /// random positive integer
+ int rand_int();
+
+ /// random int64_t
+ int64_t rand_int64();
+
+ /// generate random integer between 0 and max-1
+ int rand_int(int max);
+
+ /// between 0 and 1
+ float rand_float();
+
+ double rand_double();
+
+ explicit SplitMix64RandomGenerator(int64_t seed = 1234);
+
+ uint64_t next();
+};
+
+/* Generate an array of uniform random floats / multi-threaded implementation */
+void float_rand(float* x, size_t n, int64_t seed);
+void float_randn(float* x, size_t n, int64_t seed);
+void int64_rand(int64_t* x, size_t n, int64_t seed);
+void byte_rand(uint8_t* x, size_t n, int64_t seed);
+// max is actually the maximum value + 1
+void int64_rand_max(int64_t* x, size_t n, uint64_t max, int64_t seed);
+
+/* random permutation */
+void rand_perm(int* perm, size_t n, int64_t seed);
+void rand_perm_splitmix64(int* perm, size_t n, int64_t seed);
+
+/* Random set of vectors with intrinsic dimensionality 10 that is harder to
+ * index than a subspace of dim 10 but easier than uniform data in dimension d
+ * */
+void rand_smooth_vectors(size_t n, size_t d, float* x, int64_t seed);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib.h
new file mode 100644
index 0000000..eadfb78
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+/** Abstractions for 256-bit registers
+ *
+ * The objective is to separate the different interpretations of the same
+ * registers (as a vector of uint8, uint16 or uint32), to provide printing
+ * functions.
+ */
+
+#if defined(__AVX512F__)
+
+#include <faiss/utils/simdlib_avx2.h>
+#include <faiss/utils/simdlib_avx512.h>
+
+#elif defined(__AVX2__)
+
+#include <faiss/utils/simdlib_avx2.h>
+
+#elif defined(__aarch64__)
+
+#include <faiss/utils/simdlib_neon.h>
+
+#elif defined(__PPC64__)
+
+#include <faiss/utils/simdlib_ppc64.h>
+
+#else
+
+// emulated = all operations are implemented as scalars
+#include <faiss/utils/simdlib_emulated.h>
+
+// FIXME: make a SSE version
+// is this ever going to happen? We will probably rather implement AVX512
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_avx2.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_avx2.h
new file mode 100644
index 0000000..1a84d12
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_avx2.h
@@ -0,0 +1,803 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+#include <immintrin.h>
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/** Simple wrapper around the AVX 256-bit registers
+ *
+ * The objective is to separate the different interpretations of the same
+ * registers (as a vector of uint8, uint16 or uint32), to provide printing
+ * functions, and to give more readable names to the AVX intrinsics. It does not
+ * pretend to be exhausitve, functions are added as needed.
+ */
+
+/// 256-bit representation without interpretation as a vector
+struct simd256bit {
+ union {
+ __m256i i;
+ __m256 f;
+ };
+
+ simd256bit() {}
+
+ explicit simd256bit(__m256i i) : i(i) {}
+
+ explicit simd256bit(__m256 f) : f(f) {}
+
+ explicit simd256bit(const void* x)
+ : i(_mm256_load_si256((__m256i const*)x)) {}
+
+ void clear() {
+ i = _mm256_setzero_si256();
+ }
+
+ void storeu(void* ptr) const {
+ _mm256_storeu_si256((__m256i*)ptr, i);
+ }
+
+ void loadu(const void* ptr) {
+ i = _mm256_loadu_si256((__m256i*)ptr);
+ }
+
+ void store(void* ptr) const {
+ _mm256_store_si256((__m256i*)ptr, i);
+ }
+
+ void bin(char bits[257]) const {
+ char bytes[32];
+ storeu((void*)bytes);
+ for (int i = 0; i < 256; i++) {
+ bits[i] = '0' + ((bytes[i / 8] >> (i % 8)) & 1);
+ }
+ bits[256] = 0;
+ }
+
+ std::string bin() const {
+ char bits[257];
+ bin(bits);
+ return std::string(bits);
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ bool is_same_as(simd256bit other) const {
+ const __m256i pcmp = _mm256_cmpeq_epi32(i, other.i);
+ unsigned bitmask = _mm256_movemask_epi8(pcmp);
+ return (bitmask == 0xffffffffU);
+ }
+};
+
+/// vector of 16 elements in uint16
+struct simd16uint16 : simd256bit {
+ simd16uint16() {}
+
+ explicit simd16uint16(__m256i i) : simd256bit(i) {}
+
+ explicit simd16uint16(int x) : simd256bit(_mm256_set1_epi16(x)) {}
+
+ explicit simd16uint16(uint16_t x) : simd256bit(_mm256_set1_epi16(x)) {}
+
+ explicit simd16uint16(simd256bit x) : simd256bit(x) {}
+
+ explicit simd16uint16(const uint16_t* x) : simd256bit((const void*)x) {}
+
+ explicit simd16uint16(
+ uint16_t u0,
+ uint16_t u1,
+ uint16_t u2,
+ uint16_t u3,
+ uint16_t u4,
+ uint16_t u5,
+ uint16_t u6,
+ uint16_t u7,
+ uint16_t u8,
+ uint16_t u9,
+ uint16_t u10,
+ uint16_t u11,
+ uint16_t u12,
+ uint16_t u13,
+ uint16_t u14,
+ uint16_t u15)
+ : simd256bit(_mm256_setr_epi16(
+ u0,
+ u1,
+ u2,
+ u3,
+ u4,
+ u5,
+ u6,
+ u7,
+ u8,
+ u9,
+ u10,
+ u11,
+ u12,
+ u13,
+ u14,
+ u15)) {}
+
+ std::string elements_to_string(const char* fmt) const {
+ uint16_t bytes[16];
+ storeu((void*)bytes);
+ char res[1000];
+ char* ptr = res;
+ for (int i = 0; i < 16; i++) {
+ ptr += sprintf(ptr, fmt, bytes[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint16_t x) {
+ i = _mm256_set1_epi16((short)x);
+ }
+
+ simd16uint16 operator*(const simd16uint16& other) const {
+ return simd16uint16(_mm256_mullo_epi16(i, other.i));
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator>>(const int shift) const {
+ return simd16uint16(_mm256_srli_epi16(i, shift));
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator<<(const int shift) const {
+ return simd16uint16(_mm256_slli_epi16(i, shift));
+ }
+
+ simd16uint16 operator+=(simd16uint16 other) {
+ i = _mm256_add_epi16(i, other.i);
+ return *this;
+ }
+
+ simd16uint16 operator-=(simd16uint16 other) {
+ i = _mm256_sub_epi16(i, other.i);
+ return *this;
+ }
+
+ simd16uint16 operator+(simd16uint16 other) const {
+ return simd16uint16(_mm256_add_epi16(i, other.i));
+ }
+
+ simd16uint16 operator-(simd16uint16 other) const {
+ return simd16uint16(_mm256_sub_epi16(i, other.i));
+ }
+
+ simd16uint16 operator&(simd256bit other) const {
+ return simd16uint16(_mm256_and_si256(i, other.i));
+ }
+
+ simd16uint16 operator|(simd256bit other) const {
+ return simd16uint16(_mm256_or_si256(i, other.i));
+ }
+
+ simd16uint16 operator^(simd256bit other) const {
+ return simd16uint16(_mm256_xor_si256(i, other.i));
+ }
+
+ // returns binary masks
+ friend simd16uint16 operator==(const simd256bit lhs, const simd256bit rhs) {
+ return simd16uint16(_mm256_cmpeq_epi16(lhs.i, rhs.i));
+ }
+
+ simd16uint16 operator~() const {
+ return simd16uint16(_mm256_xor_si256(i, _mm256_set1_epi32(-1)));
+ }
+
+ // get scalar at index 0
+ uint16_t get_scalar_0() const {
+ return _mm256_extract_epi16(i, 0);
+ }
+
+ // mask of elements where this >= thresh
+ // 2 bit per component: 16 * 2 = 32 bit
+ uint32_t ge_mask(simd16uint16 thresh) const {
+ __m256i j = thresh.i;
+ __m256i max = _mm256_max_epu16(i, j);
+ __m256i ge = _mm256_cmpeq_epi16(i, max);
+ return _mm256_movemask_epi8(ge);
+ }
+
+ uint32_t le_mask(simd16uint16 thresh) const {
+ return thresh.ge_mask(*this);
+ }
+
+ uint32_t gt_mask(simd16uint16 thresh) const {
+ return ~le_mask(thresh);
+ }
+
+ bool all_gt(simd16uint16 thresh) const {
+ return le_mask(thresh) == 0;
+ }
+
+ // for debugging only
+ uint16_t operator[](int i) const {
+ ALIGNED(32) uint16_t tab[16];
+ store(tab);
+ return tab[i];
+ }
+
+ void accu_min(simd16uint16 incoming) {
+ i = _mm256_min_epu16(i, incoming.i);
+ }
+
+ void accu_max(simd16uint16 incoming) {
+ i = _mm256_max_epu16(i, incoming.i);
+ }
+};
+
+// not really a std::min because it returns an elementwise min
+inline simd16uint16 min(simd16uint16 a, simd16uint16 b) {
+ return simd16uint16(_mm256_min_epu16(a.i, b.i));
+}
+
+inline simd16uint16 max(simd16uint16 a, simd16uint16 b) {
+ return simd16uint16(_mm256_max_epu16(a.i, b.i));
+}
+
+// decompose in 128-lanes: a = (a0, a1), b = (b0, b1)
+// return (a0 + a1, b0 + b1)
+// TODO find a better name
+inline simd16uint16 combine2x2(simd16uint16 a, simd16uint16 b) {
+ __m256i a1b0 = _mm256_permute2f128_si256(a.i, b.i, 0x21);
+ __m256i a0b1 = _mm256_blend_epi32(a.i, b.i, 0xF0);
+
+ return simd16uint16(a1b0) + simd16uint16(a0b1);
+}
+
+// compare d0 and d1 to thr, return 32 bits corresponding to the concatenation
+// of d0 and d1 with thr
+inline uint32_t cmp_ge32(simd16uint16 d0, simd16uint16 d1, simd16uint16 thr) {
+ __m256i max0 = _mm256_max_epu16(d0.i, thr.i);
+ __m256i ge0 = _mm256_cmpeq_epi16(d0.i, max0);
+
+ __m256i max1 = _mm256_max_epu16(d1.i, thr.i);
+ __m256i ge1 = _mm256_cmpeq_epi16(d1.i, max1);
+
+ __m256i ge01 = _mm256_packs_epi16(ge0, ge1);
+
+ // easier than manipulating bit fields afterwards
+ ge01 = _mm256_permute4x64_epi64(ge01, 0 | (2 << 2) | (1 << 4) | (3 << 6));
+ uint32_t ge = _mm256_movemask_epi8(ge01);
+
+ return ge;
+}
+
+inline uint32_t cmp_le32(simd16uint16 d0, simd16uint16 d1, simd16uint16 thr) {
+ __m256i max0 = _mm256_min_epu16(d0.i, thr.i);
+ __m256i ge0 = _mm256_cmpeq_epi16(d0.i, max0);
+
+ __m256i max1 = _mm256_min_epu16(d1.i, thr.i);
+ __m256i ge1 = _mm256_cmpeq_epi16(d1.i, max1);
+
+ __m256i ge01 = _mm256_packs_epi16(ge0, ge1);
+
+ // easier than manipulating bit fields afterwards
+ ge01 = _mm256_permute4x64_epi64(ge01, 0 | (2 << 2) | (1 << 4) | (3 << 6));
+ uint32_t ge = _mm256_movemask_epi8(ge01);
+
+ return ge;
+}
+
+inline simd16uint16 hadd(const simd16uint16& a, const simd16uint16& b) {
+ return simd16uint16(_mm256_hadd_epi16(a.i, b.i));
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+//
+// Works in i16 mode in order to save instructions. One may
+// switch from i16 to u16.
+inline void cmplt_min_max_fast(
+ const simd16uint16 candidateValues,
+ const simd16uint16 candidateIndices,
+ const simd16uint16 currentValues,
+ const simd16uint16 currentIndices,
+ simd16uint16& minValues,
+ simd16uint16& minIndices,
+ simd16uint16& maxValues,
+ simd16uint16& maxIndices) {
+ // there's no lt instruction, so we'll need to emulate one
+ __m256i comparison = _mm256_cmpgt_epi16(currentValues.i, candidateValues.i);
+ comparison = _mm256_andnot_si256(comparison, _mm256_set1_epi16(-1));
+
+ minValues.i = _mm256_min_epi16(candidateValues.i, currentValues.i);
+ minIndices.i = _mm256_blendv_epi8(
+ candidateIndices.i, currentIndices.i, comparison);
+ maxValues.i = _mm256_max_epi16(candidateValues.i, currentValues.i);
+ maxIndices.i = _mm256_blendv_epi8(
+ currentIndices.i, candidateIndices.i, comparison);
+}
+
+// vector of 32 unsigned 8-bit integers
+struct simd32uint8 : simd256bit {
+ simd32uint8() {}
+
+ explicit simd32uint8(__m256i i) : simd256bit(i) {}
+
+ explicit simd32uint8(int x) : simd256bit(_mm256_set1_epi8(x)) {}
+
+ explicit simd32uint8(uint8_t x) : simd256bit(_mm256_set1_epi8(x)) {}
+
+ template <
+ uint8_t _0,
+ uint8_t _1,
+ uint8_t _2,
+ uint8_t _3,
+ uint8_t _4,
+ uint8_t _5,
+ uint8_t _6,
+ uint8_t _7,
+ uint8_t _8,
+ uint8_t _9,
+ uint8_t _10,
+ uint8_t _11,
+ uint8_t _12,
+ uint8_t _13,
+ uint8_t _14,
+ uint8_t _15,
+ uint8_t _16,
+ uint8_t _17,
+ uint8_t _18,
+ uint8_t _19,
+ uint8_t _20,
+ uint8_t _21,
+ uint8_t _22,
+ uint8_t _23,
+ uint8_t _24,
+ uint8_t _25,
+ uint8_t _26,
+ uint8_t _27,
+ uint8_t _28,
+ uint8_t _29,
+ uint8_t _30,
+ uint8_t _31>
+ static simd32uint8 create() {
+ return simd32uint8(_mm256_setr_epi8(
+ (char)_0,
+ (char)_1,
+ (char)_2,
+ (char)_3,
+ (char)_4,
+ (char)_5,
+ (char)_6,
+ (char)_7,
+ (char)_8,
+ (char)_9,
+ (char)_10,
+ (char)_11,
+ (char)_12,
+ (char)_13,
+ (char)_14,
+ (char)_15,
+ (char)_16,
+ (char)_17,
+ (char)_18,
+ (char)_19,
+ (char)_20,
+ (char)_21,
+ (char)_22,
+ (char)_23,
+ (char)_24,
+ (char)_25,
+ (char)_26,
+ (char)_27,
+ (char)_28,
+ (char)_29,
+ (char)_30,
+ (char)_31));
+ }
+
+ explicit simd32uint8(simd256bit x) : simd256bit(x) {}
+
+ explicit simd32uint8(const uint8_t* x) : simd256bit((const void*)x) {}
+
+ std::string elements_to_string(const char* fmt) const {
+ uint8_t bytes[32];
+ storeu((void*)bytes);
+ char res[1000];
+ char* ptr = res;
+ for (int i = 0; i < 32; i++) {
+ ptr += sprintf(ptr, fmt, bytes[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint8_t x) {
+ i = _mm256_set1_epi8((char)x);
+ }
+
+ simd32uint8 operator&(simd256bit other) const {
+ return simd32uint8(_mm256_and_si256(i, other.i));
+ }
+
+ simd32uint8 operator+(simd32uint8 other) const {
+ return simd32uint8(_mm256_add_epi8(i, other.i));
+ }
+
+ simd32uint8 lookup_2_lanes(simd32uint8 idx) const {
+ return simd32uint8(_mm256_shuffle_epi8(i, idx.i));
+ }
+
+ // extract + 0-extend lane
+ // this operation is slow (3 cycles)
+ simd16uint16 lane0_as_uint16() const {
+ __m128i x = _mm256_extracti128_si256(i, 0);
+ return simd16uint16(_mm256_cvtepu8_epi16(x));
+ }
+
+ simd16uint16 lane1_as_uint16() const {
+ __m128i x = _mm256_extracti128_si256(i, 1);
+ return simd16uint16(_mm256_cvtepu8_epi16(x));
+ }
+
+ simd32uint8 operator+=(simd32uint8 other) {
+ i = _mm256_add_epi8(i, other.i);
+ return *this;
+ }
+
+ // for debugging only
+ uint8_t operator[](int i) const {
+ ALIGNED(32) uint8_t tab[32];
+ store(tab);
+ return tab[i];
+ }
+};
+
+// convert with saturation
+// careful: this does not cross lanes, so the order is weird
+inline simd32uint8 uint16_to_uint8_saturate(simd16uint16 a, simd16uint16 b) {
+ return simd32uint8(_mm256_packs_epi16(a.i, b.i));
+}
+
+/// get most significant bit of each byte
+inline uint32_t get_MSBs(simd32uint8 a) {
+ return _mm256_movemask_epi8(a.i);
+}
+
+/// use MSB of each byte of mask to select a byte between a and b
+inline simd32uint8 blendv(simd32uint8 a, simd32uint8 b, simd32uint8 mask) {
+ return simd32uint8(_mm256_blendv_epi8(a.i, b.i, mask.i));
+}
+
+/// vector of 8 unsigned 32-bit integers
+struct simd8uint32 : simd256bit {
+ simd8uint32() {}
+
+ explicit simd8uint32(__m256i i) : simd256bit(i) {}
+
+ explicit simd8uint32(uint32_t x) : simd256bit(_mm256_set1_epi32(x)) {}
+
+ explicit simd8uint32(simd256bit x) : simd256bit(x) {}
+
+ explicit simd8uint32(const uint8_t* x) : simd256bit((const void*)x) {}
+
+ explicit simd8uint32(
+ uint32_t u0,
+ uint32_t u1,
+ uint32_t u2,
+ uint32_t u3,
+ uint32_t u4,
+ uint32_t u5,
+ uint32_t u6,
+ uint32_t u7)
+ : simd256bit(_mm256_setr_epi32(u0, u1, u2, u3, u4, u5, u6, u7)) {}
+
+ simd8uint32 operator+(simd8uint32 other) const {
+ return simd8uint32(_mm256_add_epi32(i, other.i));
+ }
+
+ simd8uint32 operator-(simd8uint32 other) const {
+ return simd8uint32(_mm256_sub_epi32(i, other.i));
+ }
+
+ simd8uint32& operator+=(const simd8uint32& other) {
+ i = _mm256_add_epi32(i, other.i);
+ return *this;
+ }
+
+ bool operator==(simd8uint32 other) const {
+ const __m256i pcmp = _mm256_cmpeq_epi32(i, other.i);
+ unsigned bitmask = _mm256_movemask_epi8(pcmp);
+ return (bitmask == 0xffffffffU);
+ }
+
+ bool operator!=(simd8uint32 other) const {
+ return !(*this == other);
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ uint32_t bytes[8];
+ storeu((void*)bytes);
+ char res[1000];
+ char* ptr = res;
+ for (int i = 0; i < 8; i++) {
+ ptr += sprintf(ptr, fmt, bytes[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%08x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%10d,");
+ }
+
+ void set1(uint32_t x) {
+ i = _mm256_set1_epi32((int)x);
+ }
+
+ simd8uint32 unzip() const {
+ return simd8uint32(_mm256_permutevar8x32_epi32(
+ i, _mm256_setr_epi32(0, 2, 4, 6, 1, 3, 5, 7)));
+ }
+};
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8uint32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8uint32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8uint32& minValues,
+ simd8uint32& minIndices,
+ simd8uint32& maxValues,
+ simd8uint32& maxIndices) {
+ // there's no lt instruction, so we'll need to emulate one
+ __m256i comparison = _mm256_cmpgt_epi32(currentValues.i, candidateValues.i);
+ comparison = _mm256_andnot_si256(comparison, _mm256_set1_epi32(-1));
+
+ minValues.i = _mm256_min_epi32(candidateValues.i, currentValues.i);
+ minIndices.i = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(candidateIndices.i),
+ _mm256_castsi256_ps(currentIndices.i),
+ _mm256_castsi256_ps(comparison)));
+ maxValues.i = _mm256_max_epi32(candidateValues.i, currentValues.i);
+ maxIndices.i = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(currentIndices.i),
+ _mm256_castsi256_ps(candidateIndices.i),
+ _mm256_castsi256_ps(comparison)));
+}
+
+struct simd8float32 : simd256bit {
+ simd8float32() {}
+
+ explicit simd8float32(simd256bit x) : simd256bit(x) {}
+
+ explicit simd8float32(__m256 x) : simd256bit(x) {}
+
+ explicit simd8float32(float x) : simd256bit(_mm256_set1_ps(x)) {}
+
+ explicit simd8float32(const float* x) : simd256bit(_mm256_loadu_ps(x)) {}
+
+ explicit simd8float32(
+ float f0,
+ float f1,
+ float f2,
+ float f3,
+ float f4,
+ float f5,
+ float f6,
+ float f7)
+ : simd256bit(_mm256_setr_ps(f0, f1, f2, f3, f4, f5, f6, f7)) {}
+
+ simd8float32 operator*(simd8float32 other) const {
+ return simd8float32(_mm256_mul_ps(f, other.f));
+ }
+
+ simd8float32 operator+(simd8float32 other) const {
+ return simd8float32(_mm256_add_ps(f, other.f));
+ }
+
+ simd8float32 operator-(simd8float32 other) const {
+ return simd8float32(_mm256_sub_ps(f, other.f));
+ }
+
+ simd8float32& operator+=(const simd8float32& other) {
+ f = _mm256_add_ps(f, other.f);
+ return *this;
+ }
+
+ bool operator==(simd8float32 other) const {
+ const __m256i pcmp =
+ _mm256_castps_si256(_mm256_cmp_ps(f, other.f, _CMP_EQ_OQ));
+ unsigned bitmask = _mm256_movemask_epi8(pcmp);
+ return (bitmask == 0xffffffffU);
+ }
+
+ bool operator!=(simd8float32 other) const {
+ return !(*this == other);
+ }
+
+ std::string tostring() const {
+ float tab[8];
+ storeu((void*)tab);
+ char res[1000];
+ char* ptr = res;
+ for (int i = 0; i < 8; i++) {
+ ptr += sprintf(ptr, "%g,", tab[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+};
+
+inline simd8float32 hadd(simd8float32 a, simd8float32 b) {
+ return simd8float32(_mm256_hadd_ps(a.f, b.f));
+}
+
+inline simd8float32 unpacklo(simd8float32 a, simd8float32 b) {
+ return simd8float32(_mm256_unpacklo_ps(a.f, b.f));
+}
+
+inline simd8float32 unpackhi(simd8float32 a, simd8float32 b) {
+ return simd8float32(_mm256_unpackhi_ps(a.f, b.f));
+}
+
+// compute a * b + c
+inline simd8float32 fmadd(simd8float32 a, simd8float32 b, simd8float32 c) {
+ return simd8float32(_mm256_fmadd_ps(a.f, b.f, c.f));
+}
+
+// The following primitive is a vectorized version of the following code
+// snippet:
+// float lowestValue = HUGE_VAL;
+// uint lowestIndex = 0;
+// for (size_t i = 0; i < n; i++) {
+// if (values[i] < lowestValue) {
+// lowestValue = values[i];
+// lowestIndex = i;
+// }
+// }
+// Vectorized version can be implemented via two operations: cmp and blend
+// with something like this:
+// lowestValues = [HUGE_VAL; 8];
+// lowestIndices = {0, 1, 2, 3, 4, 5, 6, 7};
+// for (size_t i = 0; i < n; i += 8) {
+// auto comparison = cmp(values + i, lowestValues);
+// lowestValues = blend(
+// comparison,
+// values + i,
+// lowestValues);
+// lowestIndices = blend(
+// comparison,
+// i + {0, 1, 2, 3, 4, 5, 6, 7},
+// lowestIndices);
+// lowestIndices += {8, 8, 8, 8, 8, 8, 8, 8};
+// }
+// The problem is that blend primitive needs very different instruction
+// order for AVX and ARM.
+// So, let's introduce a combination of these two in order to avoid
+// confusion for ppl who write in low-level SIMD instructions. Additionally,
+// these two ops (cmp and blend) are very often used together.
+inline void cmplt_and_blend_inplace(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ simd8float32& lowestValues,
+ simd8uint32& lowestIndices) {
+ const __m256 comparison =
+ _mm256_cmp_ps(lowestValues.f, candidateValues.f, _CMP_LE_OS);
+ lowestValues.f = _mm256_min_ps(candidateValues.f, lowestValues.f);
+ lowestIndices.i = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(candidateIndices.i),
+ _mm256_castsi256_ps(lowestIndices.i),
+ comparison));
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8float32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8float32& minValues,
+ simd8uint32& minIndices,
+ simd8float32& maxValues,
+ simd8uint32& maxIndices) {
+ const __m256 comparison =
+ _mm256_cmp_ps(currentValues.f, candidateValues.f, _CMP_LE_OS);
+ minValues.f = _mm256_min_ps(candidateValues.f, currentValues.f);
+ minIndices.i = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(candidateIndices.i),
+ _mm256_castsi256_ps(currentIndices.i),
+ comparison));
+ maxValues.f = _mm256_max_ps(candidateValues.f, currentValues.f);
+ maxIndices.i = _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(currentIndices.i),
+ _mm256_castsi256_ps(candidateIndices.i),
+ comparison));
+}
+
+namespace {
+
+// get even float32's of a and b, interleaved
+inline simd8float32 geteven(simd8float32 a, simd8float32 b) {
+ return simd8float32(
+ _mm256_shuffle_ps(a.f, b.f, 0 << 0 | 2 << 2 | 0 << 4 | 2 << 6));
+}
+
+// get odd float32's of a and b, interleaved
+inline simd8float32 getodd(simd8float32 a, simd8float32 b) {
+ return simd8float32(
+ _mm256_shuffle_ps(a.f, b.f, 1 << 0 | 3 << 2 | 1 << 4 | 3 << 6));
+}
+
+// 3 cycles
+// if the lanes are a = [a0 a1] and b = [b0 b1], return [a0 b0]
+inline simd8float32 getlow128(simd8float32 a, simd8float32 b) {
+ return simd8float32(_mm256_permute2f128_ps(a.f, b.f, 0 | 2 << 4));
+}
+
+inline simd8float32 gethigh128(simd8float32 a, simd8float32 b) {
+ return simd8float32(_mm256_permute2f128_ps(a.f, b.f, 1 | 3 << 4));
+}
+
+} // namespace
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_avx512.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_avx512.h
new file mode 100644
index 0000000..63b23f9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_avx512.h
@@ -0,0 +1,296 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+#include <immintrin.h>
+
+#include <faiss/impl/platform_macros.h>
+
+#include <faiss/utils/simdlib_avx2.h>
+
+namespace faiss {
+
+/** Simple wrapper around the AVX 512-bit registers
+ *
+ * The objective is to separate the different interpretations of the same
+ * registers (as a vector of uint8, uint16 or uint32), to provide printing
+ * functions, and to give more readable names to the AVX intrinsics. It does not
+ * pretend to be exhausitve, functions are added as needed.
+ */
+
+/// 512-bit representation without interpretation as a vector
+struct simd512bit {
+ union {
+ __m512i i;
+ __m512 f;
+ };
+
+ simd512bit() {}
+
+ explicit simd512bit(__m512i i) : i(i) {}
+
+ explicit simd512bit(__m512 f) : f(f) {}
+
+ explicit simd512bit(const void* x)
+ : i(_mm512_loadu_si512((__m512i const*)x)) {}
+
+ // sets up a lower half of the register while keeping upper one as zero
+ explicit simd512bit(simd256bit lo)
+ : simd512bit(_mm512_inserti32x8(
+ _mm512_castsi256_si512(lo.i),
+ _mm256_setzero_si256(),
+ 1)) {}
+
+ // constructs from lower and upper halves
+ explicit simd512bit(simd256bit lo, simd256bit hi)
+ : simd512bit(_mm512_inserti32x8(
+ _mm512_castsi256_si512(lo.i),
+ hi.i,
+ 1)) {}
+
+ void clear() {
+ i = _mm512_setzero_si512();
+ }
+
+ void storeu(void* ptr) const {
+ _mm512_storeu_si512((__m512i*)ptr, i);
+ }
+
+ void loadu(const void* ptr) {
+ i = _mm512_loadu_si512((__m512i*)ptr);
+ }
+
+ void store(void* ptr) const {
+ _mm512_storeu_si512((__m512i*)ptr, i);
+ }
+
+ void bin(char bits[513]) const {
+ char bytes[64];
+ storeu((void*)bytes);
+ for (int i = 0; i < 512; i++) {
+ bits[i] = '0' + ((bytes[i / 8] >> (i % 8)) & 1);
+ }
+ bits[512] = 0;
+ }
+
+ std::string bin() const {
+ char bits[257];
+ bin(bits);
+ return std::string(bits);
+ }
+};
+
+/// vector of 32 elements in uint16
+struct simd32uint16 : simd512bit {
+ simd32uint16() {}
+
+ explicit simd32uint16(__m512i i) : simd512bit(i) {}
+
+ explicit simd32uint16(int x) : simd512bit(_mm512_set1_epi16(x)) {}
+
+ explicit simd32uint16(uint16_t x) : simd512bit(_mm512_set1_epi16(x)) {}
+
+ explicit simd32uint16(simd512bit x) : simd512bit(x) {}
+
+ explicit simd32uint16(const uint16_t* x) : simd512bit((const void*)x) {}
+
+ // sets up a lower half of the register
+ explicit simd32uint16(simd256bit lo) : simd512bit(lo) {}
+
+ // constructs from lower and upper halves
+ explicit simd32uint16(simd256bit lo, simd256bit hi) : simd512bit(lo, hi) {}
+
+ std::string elements_to_string(const char* fmt) const {
+ uint16_t bytes[32];
+ storeu((void*)bytes);
+ char res[2000];
+ char* ptr = res;
+ for (int i = 0; i < 32; i++) {
+ ptr += sprintf(ptr, fmt, bytes[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint16_t x) {
+ i = _mm512_set1_epi16((short)x);
+ }
+
+ simd32uint16 operator*(const simd32uint16& other) const {
+ return simd32uint16(_mm512_mullo_epi16(i, other.i));
+ }
+
+ // shift must be known at compile time
+ simd32uint16 operator>>(const int shift) const {
+ return simd32uint16(_mm512_srli_epi16(i, shift));
+ }
+
+ // shift must be known at compile time
+ simd32uint16 operator<<(const int shift) const {
+ return simd32uint16(_mm512_slli_epi16(i, shift));
+ }
+
+ simd32uint16 operator+=(simd32uint16 other) {
+ i = _mm512_add_epi16(i, other.i);
+ return *this;
+ }
+
+ simd32uint16 operator-=(simd32uint16 other) {
+ i = _mm512_sub_epi16(i, other.i);
+ return *this;
+ }
+
+ simd32uint16 operator+(simd32uint16 other) const {
+ return simd32uint16(_mm512_add_epi16(i, other.i));
+ }
+
+ simd32uint16 operator-(simd32uint16 other) const {
+ return simd32uint16(_mm512_sub_epi16(i, other.i));
+ }
+
+ simd32uint16 operator&(simd512bit other) const {
+ return simd32uint16(_mm512_and_si512(i, other.i));
+ }
+
+ simd32uint16 operator|(simd512bit other) const {
+ return simd32uint16(_mm512_or_si512(i, other.i));
+ }
+
+ simd32uint16 operator^(simd512bit other) const {
+ return simd32uint16(_mm512_xor_si512(i, other.i));
+ }
+
+ simd32uint16 operator~() const {
+ return simd32uint16(_mm512_xor_si512(i, _mm512_set1_epi32(-1)));
+ }
+
+ simd16uint16 low() const {
+ return simd16uint16(_mm512_castsi512_si256(i));
+ }
+
+ simd16uint16 high() const {
+ return simd16uint16(_mm512_extracti32x8_epi32(i, 1));
+ }
+
+ // for debugging only
+ uint16_t operator[](int i) const {
+ ALIGNED(64) uint16_t tab[32];
+ store(tab);
+ return tab[i];
+ }
+
+ void accu_min(simd32uint16 incoming) {
+ i = _mm512_min_epu16(i, incoming.i);
+ }
+
+ void accu_max(simd32uint16 incoming) {
+ i = _mm512_max_epu16(i, incoming.i);
+ }
+};
+
+// decompose in 128-lanes: a = (a0, a1, a2, a3), b = (b0, b1, b2, b3)
+// return (a0 + a1 + a2 + a3, b0 + b1 + b2 + b3)
+inline simd16uint16 combine4x2(simd32uint16 a, simd32uint16 b) {
+ return combine2x2(a.low(), b.low()) + combine2x2(a.high(), b.high());
+}
+
+// vector of 32 unsigned 8-bit integers
+struct simd64uint8 : simd512bit {
+ simd64uint8() {}
+
+ explicit simd64uint8(__m512i i) : simd512bit(i) {}
+
+ explicit simd64uint8(int x) : simd512bit(_mm512_set1_epi8(x)) {}
+
+ explicit simd64uint8(uint8_t x) : simd512bit(_mm512_set1_epi8(x)) {}
+
+ // sets up a lower half of the register
+ explicit simd64uint8(simd256bit lo) : simd512bit(lo) {}
+
+ // constructs from lower and upper halves
+ explicit simd64uint8(simd256bit lo, simd256bit hi) : simd512bit(lo, hi) {}
+
+ explicit simd64uint8(simd512bit x) : simd512bit(x) {}
+
+ explicit simd64uint8(const uint8_t* x) : simd512bit((const void*)x) {}
+
+ std::string elements_to_string(const char* fmt) const {
+ uint8_t bytes[64];
+ storeu((void*)bytes);
+ char res[2000];
+ char* ptr = res;
+ for (int i = 0; i < 64; i++) {
+ ptr += sprintf(ptr, fmt, bytes[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint8_t x) {
+ i = _mm512_set1_epi8((char)x);
+ }
+
+ simd64uint8 operator&(simd512bit other) const {
+ return simd64uint8(_mm512_and_si512(i, other.i));
+ }
+
+ simd64uint8 operator+(simd64uint8 other) const {
+ return simd64uint8(_mm512_add_epi8(i, other.i));
+ }
+
+ simd64uint8 lookup_4_lanes(simd64uint8 idx) const {
+ return simd64uint8(_mm512_shuffle_epi8(i, idx.i));
+ }
+
+ // extract + 0-extend lane
+ // this operation is slow (3 cycles)
+ simd32uint16 lane0_as_uint16() const {
+ __m256i x = _mm512_extracti32x8_epi32(i, 0);
+ return simd32uint16(_mm512_cvtepu8_epi16(x));
+ }
+
+ simd32uint16 lane1_as_uint16() const {
+ __m256i x = _mm512_extracti32x8_epi32(i, 1);
+ return simd32uint16(_mm512_cvtepu8_epi16(x));
+ }
+
+ simd64uint8 operator+=(simd64uint8 other) {
+ i = _mm512_add_epi8(i, other.i);
+ return *this;
+ }
+
+ // for debugging only
+ uint8_t operator[](int i) const {
+ ALIGNED(64) uint8_t tab[64];
+ store(tab);
+ return tab[i];
+ }
+};
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_emulated.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_emulated.h
new file mode 100644
index 0000000..55e6534
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_emulated.h
@@ -0,0 +1,1045 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <cstdint>
+#include <cstring>
+#include <string>
+
+namespace faiss {
+
+struct simd256bit {
+ union {
+ uint8_t u8[32];
+ uint16_t u16[16];
+ uint32_t u32[8];
+ float f32[8];
+ };
+
+ simd256bit() {}
+
+ explicit simd256bit(const void* x) {
+ memcpy(u8, x, 32);
+ }
+
+ void clear() {
+ memset(u8, 0, 32);
+ }
+
+ void storeu(void* ptr) const {
+ memcpy(ptr, u8, 32);
+ }
+
+ void loadu(const void* ptr) {
+ memcpy(u8, ptr, 32);
+ }
+
+ void store(void* ptr) const {
+ storeu(ptr);
+ }
+
+ void bin(char bits[257]) const {
+ const char* bytes = (char*)this->u8;
+ for (int i = 0; i < 256; i++) {
+ bits[i] = '0' + ((bytes[i / 8] >> (i % 8)) & 1);
+ }
+ bits[256] = 0;
+ }
+
+ std::string bin() const {
+ char bits[257];
+ bin(bits);
+ return std::string(bits);
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ bool is_same_as(simd256bit other) const {
+ for (size_t i = 0; i < 8; i++) {
+ if (u32[i] != other.u32[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+};
+
+/// vector of 16 elements in uint16
+struct simd16uint16 : simd256bit {
+ simd16uint16() {}
+
+ explicit simd16uint16(int x) {
+ set1(x);
+ }
+
+ explicit simd16uint16(uint16_t x) {
+ set1(x);
+ }
+
+ explicit simd16uint16(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd16uint16(const uint16_t* x) : simd256bit((const void*)x) {}
+
+ explicit simd16uint16(
+ uint16_t u0,
+ uint16_t u1,
+ uint16_t u2,
+ uint16_t u3,
+ uint16_t u4,
+ uint16_t u5,
+ uint16_t u6,
+ uint16_t u7,
+ uint16_t u8,
+ uint16_t u9,
+ uint16_t u10,
+ uint16_t u11,
+ uint16_t u12,
+ uint16_t u13,
+ uint16_t u14,
+ uint16_t u15) {
+ this->u16[0] = u0;
+ this->u16[1] = u1;
+ this->u16[2] = u2;
+ this->u16[3] = u3;
+ this->u16[4] = u4;
+ this->u16[5] = u5;
+ this->u16[6] = u6;
+ this->u16[7] = u7;
+ this->u16[8] = u8;
+ this->u16[9] = u9;
+ this->u16[10] = u10;
+ this->u16[11] = u11;
+ this->u16[12] = u12;
+ this->u16[13] = u13;
+ this->u16[14] = u14;
+ this->u16[15] = u15;
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 16; i++) {
+ ptr += sprintf(ptr, fmt, u16[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ template <typename F>
+ static simd16uint16 unary_func(const simd16uint16& a, F&& f) {
+ simd16uint16 c;
+ for (int j = 0; j < 16; j++) {
+ c.u16[j] = f(a.u16[j]);
+ }
+ return c;
+ }
+
+ template <typename F>
+ static simd16uint16 binary_func(
+ const simd16uint16& a,
+ const simd16uint16& b,
+ F&& f) {
+ simd16uint16 c;
+ for (int j = 0; j < 16; j++) {
+ c.u16[j] = f(a.u16[j], b.u16[j]);
+ }
+ return c;
+ }
+
+ void set1(uint16_t x) {
+ for (int i = 0; i < 16; i++) {
+ u16[i] = x;
+ }
+ }
+
+ simd16uint16 operator*(const simd16uint16& other) const {
+ return binary_func(
+ *this, other, [](uint16_t a, uint16_t b) { return a * b; });
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator>>(const int shift) const {
+ return unary_func(*this, [shift](uint16_t a) { return a >> shift; });
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator<<(const int shift) const {
+ return unary_func(*this, [shift](uint16_t a) { return a << shift; });
+ }
+
+ simd16uint16 operator+=(const simd16uint16& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ simd16uint16 operator-=(const simd16uint16& other) {
+ *this = *this - other;
+ return *this;
+ }
+
+ simd16uint16 operator+(const simd16uint16& other) const {
+ return binary_func(
+ *this, other, [](uint16_t a, uint16_t b) { return a + b; });
+ }
+
+ simd16uint16 operator-(const simd16uint16& other) const {
+ return binary_func(
+ *this, other, [](uint16_t a, uint16_t b) { return a - b; });
+ }
+
+ simd16uint16 operator&(const simd256bit& other) const {
+ return binary_func(
+ *this, simd16uint16(other), [](uint16_t a, uint16_t b) {
+ return a & b;
+ });
+ }
+
+ simd16uint16 operator|(const simd256bit& other) const {
+ return binary_func(
+ *this, simd16uint16(other), [](uint16_t a, uint16_t b) {
+ return a | b;
+ });
+ }
+
+ simd16uint16 operator^(const simd256bit& other) const {
+ return binary_func(
+ *this, simd16uint16(other), [](uint16_t a, uint16_t b) {
+ return a ^ b;
+ });
+ }
+
+ // returns binary masks
+ simd16uint16 operator==(const simd16uint16& other) const {
+ return binary_func(*this, other, [](uint16_t a, uint16_t b) {
+ return a == b ? 0xffff : 0;
+ });
+ }
+
+ simd16uint16 operator~() const {
+ return unary_func(*this, [](uint16_t a) { return ~a; });
+ }
+
+ // get scalar at index 0
+ uint16_t get_scalar_0() const {
+ return u16[0];
+ }
+
+ // mask of elements where this >= thresh
+ // 2 bit per component: 16 * 2 = 32 bit
+ uint32_t ge_mask(const simd16uint16& thresh) const {
+ uint32_t gem = 0;
+ for (int j = 0; j < 16; j++) {
+ if (u16[j] >= thresh.u16[j]) {
+ gem |= 3 << (j * 2);
+ }
+ }
+ return gem;
+ }
+
+ uint32_t le_mask(const simd16uint16& thresh) const {
+ return thresh.ge_mask(*this);
+ }
+
+ uint32_t gt_mask(const simd16uint16& thresh) const {
+ return ~le_mask(thresh);
+ }
+
+ bool all_gt(const simd16uint16& thresh) const {
+ return le_mask(thresh) == 0;
+ }
+
+ // for debugging only
+ uint16_t operator[](int i) const {
+ return u16[i];
+ }
+
+ void accu_min(const simd16uint16& incoming) {
+ for (int j = 0; j < 16; j++) {
+ if (incoming.u16[j] < u16[j]) {
+ u16[j] = incoming.u16[j];
+ }
+ }
+ }
+
+ void accu_max(const simd16uint16& incoming) {
+ for (int j = 0; j < 16; j++) {
+ if (incoming.u16[j] > u16[j]) {
+ u16[j] = incoming.u16[j];
+ }
+ }
+ }
+};
+
+// not really a std::min because it returns an elementwise min
+inline simd16uint16 min(const simd16uint16& av, const simd16uint16& bv) {
+ return simd16uint16::binary_func(
+ av, bv, [](uint16_t a, uint16_t b) { return std::min(a, b); });
+}
+
+inline simd16uint16 max(const simd16uint16& av, const simd16uint16& bv) {
+ return simd16uint16::binary_func(
+ av, bv, [](uint16_t a, uint16_t b) { return std::max(a, b); });
+}
+
+// decompose in 128-lanes: a = (a0, a1), b = (b0, b1)
+// return (a0 + a1, b0 + b1)
+// TODO find a better name
+inline simd16uint16 combine2x2(const simd16uint16& a, const simd16uint16& b) {
+ simd16uint16 c;
+ for (int j = 0; j < 8; j++) {
+ c.u16[j] = a.u16[j] + a.u16[j + 8];
+ c.u16[j + 8] = b.u16[j] + b.u16[j + 8];
+ }
+ return c;
+}
+
+// compare d0 and d1 to thr, return 32 bits corresponding to the concatenation
+// of d0 and d1 with thr
+inline uint32_t cmp_ge32(
+ const simd16uint16& d0,
+ const simd16uint16& d1,
+ const simd16uint16& thr) {
+ uint32_t gem = 0;
+ for (int j = 0; j < 16; j++) {
+ if (d0.u16[j] >= thr.u16[j]) {
+ gem |= 1 << j;
+ }
+ if (d1.u16[j] >= thr.u16[j]) {
+ gem |= 1 << (j + 16);
+ }
+ }
+ return gem;
+}
+
+inline uint32_t cmp_le32(
+ const simd16uint16& d0,
+ const simd16uint16& d1,
+ const simd16uint16& thr) {
+ uint32_t gem = 0;
+ for (int j = 0; j < 16; j++) {
+ if (d0.u16[j] <= thr.u16[j]) {
+ gem |= 1 << j;
+ }
+ if (d1.u16[j] <= thr.u16[j]) {
+ gem |= 1 << (j + 16);
+ }
+ }
+ return gem;
+}
+
+// hadd does not cross lanes
+inline simd16uint16 hadd(const simd16uint16& a, const simd16uint16& b) {
+ simd16uint16 c;
+ c.u16[0] = a.u16[0] + a.u16[1];
+ c.u16[1] = a.u16[2] + a.u16[3];
+ c.u16[2] = a.u16[4] + a.u16[5];
+ c.u16[3] = a.u16[6] + a.u16[7];
+ c.u16[4] = b.u16[0] + b.u16[1];
+ c.u16[5] = b.u16[2] + b.u16[3];
+ c.u16[6] = b.u16[4] + b.u16[5];
+ c.u16[7] = b.u16[6] + b.u16[7];
+
+ c.u16[8] = a.u16[8] + a.u16[9];
+ c.u16[9] = a.u16[10] + a.u16[11];
+ c.u16[10] = a.u16[12] + a.u16[13];
+ c.u16[11] = a.u16[14] + a.u16[15];
+ c.u16[12] = b.u16[8] + b.u16[9];
+ c.u16[13] = b.u16[10] + b.u16[11];
+ c.u16[14] = b.u16[12] + b.u16[13];
+ c.u16[15] = b.u16[14] + b.u16[15];
+
+ return c;
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd16uint16 candidateValues,
+ const simd16uint16 candidateIndices,
+ const simd16uint16 currentValues,
+ const simd16uint16 currentIndices,
+ simd16uint16& minValues,
+ simd16uint16& minIndices,
+ simd16uint16& maxValues,
+ simd16uint16& maxIndices) {
+ for (size_t i = 0; i < 16; i++) {
+ bool flag = (candidateValues.u16[i] < currentValues.u16[i]);
+ minValues.u16[i] = flag ? candidateValues.u16[i] : currentValues.u16[i];
+ minIndices.u16[i] =
+ flag ? candidateIndices.u16[i] : currentIndices.u16[i];
+ maxValues.u16[i] =
+ !flag ? candidateValues.u16[i] : currentValues.u16[i];
+ maxIndices.u16[i] =
+ !flag ? candidateIndices.u16[i] : currentIndices.u16[i];
+ }
+}
+
+// vector of 32 unsigned 8-bit integers
+struct simd32uint8 : simd256bit {
+ simd32uint8() {}
+
+ explicit simd32uint8(int x) {
+ set1(x);
+ }
+
+ explicit simd32uint8(uint8_t x) {
+ set1(x);
+ }
+ template <
+ uint8_t _0,
+ uint8_t _1,
+ uint8_t _2,
+ uint8_t _3,
+ uint8_t _4,
+ uint8_t _5,
+ uint8_t _6,
+ uint8_t _7,
+ uint8_t _8,
+ uint8_t _9,
+ uint8_t _10,
+ uint8_t _11,
+ uint8_t _12,
+ uint8_t _13,
+ uint8_t _14,
+ uint8_t _15,
+ uint8_t _16,
+ uint8_t _17,
+ uint8_t _18,
+ uint8_t _19,
+ uint8_t _20,
+ uint8_t _21,
+ uint8_t _22,
+ uint8_t _23,
+ uint8_t _24,
+ uint8_t _25,
+ uint8_t _26,
+ uint8_t _27,
+ uint8_t _28,
+ uint8_t _29,
+ uint8_t _30,
+ uint8_t _31>
+ static simd32uint8 create() {
+ simd32uint8 ret;
+ ret.u8[0] = _0;
+ ret.u8[1] = _1;
+ ret.u8[2] = _2;
+ ret.u8[3] = _3;
+ ret.u8[4] = _4;
+ ret.u8[5] = _5;
+ ret.u8[6] = _6;
+ ret.u8[7] = _7;
+ ret.u8[8] = _8;
+ ret.u8[9] = _9;
+ ret.u8[10] = _10;
+ ret.u8[11] = _11;
+ ret.u8[12] = _12;
+ ret.u8[13] = _13;
+ ret.u8[14] = _14;
+ ret.u8[15] = _15;
+ ret.u8[16] = _16;
+ ret.u8[17] = _17;
+ ret.u8[18] = _18;
+ ret.u8[19] = _19;
+ ret.u8[20] = _20;
+ ret.u8[21] = _21;
+ ret.u8[22] = _22;
+ ret.u8[23] = _23;
+ ret.u8[24] = _24;
+ ret.u8[25] = _25;
+ ret.u8[26] = _26;
+ ret.u8[27] = _27;
+ ret.u8[28] = _28;
+ ret.u8[29] = _29;
+ ret.u8[30] = _30;
+ ret.u8[31] = _31;
+ return ret;
+ }
+
+ explicit simd32uint8(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd32uint8(const uint8_t* x) : simd256bit((const void*)x) {}
+
+ std::string elements_to_string(const char* fmt) const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 32; i++) {
+ ptr += sprintf(ptr, fmt, u8[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint8_t x) {
+ for (int j = 0; j < 32; j++) {
+ u8[j] = x;
+ }
+ }
+
+ template <typename F>
+ static simd32uint8 binary_func(
+ const simd32uint8& a,
+ const simd32uint8& b,
+ F&& f) {
+ simd32uint8 c;
+ for (int j = 0; j < 32; j++) {
+ c.u8[j] = f(a.u8[j], b.u8[j]);
+ }
+ return c;
+ }
+
+ simd32uint8 operator&(const simd256bit& other) const {
+ return binary_func(*this, simd32uint8(other), [](uint8_t a, uint8_t b) {
+ return a & b;
+ });
+ }
+
+ simd32uint8 operator+(const simd32uint8& other) const {
+ return binary_func(
+ *this, other, [](uint8_t a, uint8_t b) { return a + b; });
+ }
+
+ // The very important operation that everything relies on
+ simd32uint8 lookup_2_lanes(const simd32uint8& idx) const {
+ simd32uint8 c;
+ for (int j = 0; j < 32; j++) {
+ if (idx.u8[j] & 0x80) {
+ c.u8[j] = 0;
+ } else {
+ uint8_t i = idx.u8[j] & 15;
+ if (j < 16) {
+ c.u8[j] = u8[i];
+ } else {
+ c.u8[j] = u8[16 + i];
+ }
+ }
+ }
+ return c;
+ }
+
+ // extract + 0-extend lane
+ // this operation is slow (3 cycles)
+
+ simd32uint8 operator+=(const simd32uint8& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ // for debugging only
+ uint8_t operator[](int i) const {
+ return u8[i];
+ }
+};
+
+// convert with saturation
+// careful: this does not cross lanes, so the order is weird
+inline simd32uint8 uint16_to_uint8_saturate(
+ const simd16uint16& a,
+ const simd16uint16& b) {
+ simd32uint8 c;
+
+ auto saturate_16_to_8 = [](uint16_t x) { return x >= 256 ? 0xff : x; };
+
+ for (int i = 0; i < 8; i++) {
+ c.u8[i] = saturate_16_to_8(a.u16[i]);
+ c.u8[8 + i] = saturate_16_to_8(b.u16[i]);
+ c.u8[16 + i] = saturate_16_to_8(a.u16[8 + i]);
+ c.u8[24 + i] = saturate_16_to_8(b.u16[8 + i]);
+ }
+ return c;
+}
+
+/// get most significant bit of each byte
+inline uint32_t get_MSBs(const simd32uint8& a) {
+ uint32_t res = 0;
+ for (int i = 0; i < 32; i++) {
+ if (a.u8[i] & 0x80) {
+ res |= 1 << i;
+ }
+ }
+ return res;
+}
+
+/// use MSB of each byte of mask to select a byte between a and b
+inline simd32uint8 blendv(
+ const simd32uint8& a,
+ const simd32uint8& b,
+ const simd32uint8& mask) {
+ simd32uint8 c;
+ for (int i = 0; i < 32; i++) {
+ if (mask.u8[i] & 0x80) {
+ c.u8[i] = b.u8[i];
+ } else {
+ c.u8[i] = a.u8[i];
+ }
+ }
+ return c;
+}
+
+/// vector of 8 unsigned 32-bit integers
+struct simd8uint32 : simd256bit {
+ simd8uint32() {}
+
+ explicit simd8uint32(uint32_t x) {
+ set1(x);
+ }
+
+ explicit simd8uint32(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd8uint32(const uint32_t* x) : simd256bit((const void*)x) {}
+
+ explicit simd8uint32(
+ uint32_t u0,
+ uint32_t u1,
+ uint32_t u2,
+ uint32_t u3,
+ uint32_t u4,
+ uint32_t u5,
+ uint32_t u6,
+ uint32_t u7) {
+ u32[0] = u0;
+ u32[1] = u1;
+ u32[2] = u2;
+ u32[3] = u3;
+ u32[4] = u4;
+ u32[5] = u5;
+ u32[6] = u6;
+ u32[7] = u7;
+ }
+
+ simd8uint32 operator+(simd8uint32 other) const {
+ simd8uint32 result;
+ for (int i = 0; i < 8; i++) {
+ result.u32[i] = u32[i] + other.u32[i];
+ }
+ return result;
+ }
+
+ simd8uint32 operator-(simd8uint32 other) const {
+ simd8uint32 result;
+ for (int i = 0; i < 8; i++) {
+ result.u32[i] = u32[i] - other.u32[i];
+ }
+ return result;
+ }
+
+ simd8uint32& operator+=(const simd8uint32& other) {
+ for (int i = 0; i < 8; i++) {
+ u32[i] += other.u32[i];
+ }
+ return *this;
+ }
+
+ bool operator==(simd8uint32 other) const {
+ for (size_t i = 0; i < 8; i++) {
+ if (u32[i] != other.u32[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ bool operator!=(simd8uint32 other) const {
+ return !(*this == other);
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 8; i++) {
+ ptr += sprintf(ptr, fmt, u32[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%08x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%10d,");
+ }
+
+ void set1(uint32_t x) {
+ for (int i = 0; i < 8; i++) {
+ u32[i] = x;
+ }
+ }
+
+ simd8uint32 unzip() const {
+ const uint32_t ret[] = {
+ u32[0], u32[2], u32[4], u32[6], u32[1], u32[3], u32[5], u32[7]};
+ return simd8uint32{ret};
+ }
+};
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8uint32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8uint32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8uint32& minValues,
+ simd8uint32& minIndices,
+ simd8uint32& maxValues,
+ simd8uint32& maxIndices) {
+ for (size_t i = 0; i < 8; i++) {
+ bool flag = (candidateValues.u32[i] < currentValues.u32[i]);
+ minValues.u32[i] = flag ? candidateValues.u32[i] : currentValues.u32[i];
+ minIndices.u32[i] =
+ flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ maxValues.u32[i] =
+ !flag ? candidateValues.u32[i] : currentValues.u32[i];
+ maxIndices.u32[i] =
+ !flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ }
+}
+
+struct simd8float32 : simd256bit {
+ simd8float32() {}
+
+ explicit simd8float32(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd8float32(float x) {
+ set1(x);
+ }
+
+ explicit simd8float32(const float* x) {
+ loadu((void*)x);
+ }
+
+ void set1(float x) {
+ for (int i = 0; i < 8; i++) {
+ f32[i] = x;
+ }
+ }
+
+ explicit simd8float32(
+ float f0,
+ float f1,
+ float f2,
+ float f3,
+ float f4,
+ float f5,
+ float f6,
+ float f7) {
+ f32[0] = f0;
+ f32[1] = f1;
+ f32[2] = f2;
+ f32[3] = f3;
+ f32[4] = f4;
+ f32[5] = f5;
+ f32[6] = f6;
+ f32[7] = f7;
+ }
+
+ template <typename F>
+ static simd8float32 binary_func(
+ const simd8float32& a,
+ const simd8float32& b,
+ F&& f) {
+ simd8float32 c;
+ for (int j = 0; j < 8; j++) {
+ c.f32[j] = f(a.f32[j], b.f32[j]);
+ }
+ return c;
+ }
+
+ simd8float32 operator*(const simd8float32& other) const {
+ return binary_func(
+ *this, other, [](float a, float b) { return a * b; });
+ }
+
+ simd8float32 operator+(const simd8float32& other) const {
+ return binary_func(
+ *this, other, [](float a, float b) { return a + b; });
+ }
+
+ simd8float32 operator-(const simd8float32& other) const {
+ return binary_func(
+ *this, other, [](float a, float b) { return a - b; });
+ }
+
+ simd8float32& operator+=(const simd8float32& other) {
+ for (size_t i = 0; i < 8; i++) {
+ f32[i] += other.f32[i];
+ }
+
+ return *this;
+ }
+
+ bool operator==(simd8float32 other) const {
+ for (size_t i = 0; i < 8; i++) {
+ if (f32[i] != other.f32[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ bool operator!=(simd8float32 other) const {
+ return !(*this == other);
+ }
+
+ std::string tostring() const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 8; i++) {
+ ptr += sprintf(ptr, "%g,", f32[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+};
+
+// hadd does not cross lanes
+inline simd8float32 hadd(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+ c.f32[0] = a.f32[0] + a.f32[1];
+ c.f32[1] = a.f32[2] + a.f32[3];
+ c.f32[2] = b.f32[0] + b.f32[1];
+ c.f32[3] = b.f32[2] + b.f32[3];
+
+ c.f32[4] = a.f32[4] + a.f32[5];
+ c.f32[5] = a.f32[6] + a.f32[7];
+ c.f32[6] = b.f32[4] + b.f32[5];
+ c.f32[7] = b.f32[6] + b.f32[7];
+
+ return c;
+}
+
+inline simd8float32 unpacklo(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+ c.f32[0] = a.f32[0];
+ c.f32[1] = b.f32[0];
+ c.f32[2] = a.f32[1];
+ c.f32[3] = b.f32[1];
+
+ c.f32[4] = a.f32[4];
+ c.f32[5] = b.f32[4];
+ c.f32[6] = a.f32[5];
+ c.f32[7] = b.f32[5];
+
+ return c;
+}
+
+inline simd8float32 unpackhi(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+ c.f32[0] = a.f32[2];
+ c.f32[1] = b.f32[2];
+ c.f32[2] = a.f32[3];
+ c.f32[3] = b.f32[3];
+
+ c.f32[4] = a.f32[6];
+ c.f32[5] = b.f32[6];
+ c.f32[6] = a.f32[7];
+ c.f32[7] = b.f32[7];
+
+ return c;
+}
+
+// compute a * b + c
+inline simd8float32 fmadd(
+ const simd8float32& a,
+ const simd8float32& b,
+ const simd8float32& c) {
+ simd8float32 res;
+ for (int i = 0; i < 8; i++) {
+ res.f32[i] = a.f32[i] * b.f32[i] + c.f32[i];
+ }
+ return res;
+}
+
+namespace {
+
+// get even float32's of a and b, interleaved
+simd8float32 geteven(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[0];
+ c.f32[1] = a.f32[2];
+ c.f32[2] = b.f32[0];
+ c.f32[3] = b.f32[2];
+
+ c.f32[4] = a.f32[4];
+ c.f32[5] = a.f32[6];
+ c.f32[6] = b.f32[4];
+ c.f32[7] = b.f32[6];
+
+ return c;
+}
+
+// get odd float32's of a and b, interleaved
+simd8float32 getodd(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[1];
+ c.f32[1] = a.f32[3];
+ c.f32[2] = b.f32[1];
+ c.f32[3] = b.f32[3];
+
+ c.f32[4] = a.f32[5];
+ c.f32[5] = a.f32[7];
+ c.f32[6] = b.f32[5];
+ c.f32[7] = b.f32[7];
+
+ return c;
+}
+
+// 3 cycles
+// if the lanes are a = [a0 a1] and b = [b0 b1], return [a0 b0]
+simd8float32 getlow128(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[0];
+ c.f32[1] = a.f32[1];
+ c.f32[2] = a.f32[2];
+ c.f32[3] = a.f32[3];
+
+ c.f32[4] = b.f32[0];
+ c.f32[5] = b.f32[1];
+ c.f32[6] = b.f32[2];
+ c.f32[7] = b.f32[3];
+
+ return c;
+}
+
+simd8float32 gethigh128(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[4];
+ c.f32[1] = a.f32[5];
+ c.f32[2] = a.f32[6];
+ c.f32[3] = a.f32[7];
+
+ c.f32[4] = b.f32[4];
+ c.f32[5] = b.f32[5];
+ c.f32[6] = b.f32[6];
+ c.f32[7] = b.f32[7];
+
+ return c;
+}
+
+// The following primitive is a vectorized version of the following code
+// snippet:
+// float lowestValue = HUGE_VAL;
+// uint lowestIndex = 0;
+// for (size_t i = 0; i < n; i++) {
+// if (values[i] < lowestValue) {
+// lowestValue = values[i];
+// lowestIndex = i;
+// }
+// }
+// Vectorized version can be implemented via two operations: cmp and blend
+// with something like this:
+// lowestValues = [HUGE_VAL; 8];
+// lowestIndices = {0, 1, 2, 3, 4, 5, 6, 7};
+// for (size_t i = 0; i < n; i += 8) {
+// auto comparison = cmp(values + i, lowestValues);
+// lowestValues = blend(
+// comparison,
+// values + i,
+// lowestValues);
+// lowestIndices = blend(
+// comparison,
+// i + {0, 1, 2, 3, 4, 5, 6, 7},
+// lowestIndices);
+// lowestIndices += {8, 8, 8, 8, 8, 8, 8, 8};
+// }
+// The problem is that blend primitive needs very different instruction
+// order for AVX and ARM.
+// So, let's introduce a combination of these two in order to avoid
+// confusion for ppl who write in low-level SIMD instructions. Additionally,
+// these two ops (cmp and blend) are very often used together.
+inline void cmplt_and_blend_inplace(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ simd8float32& lowestValues,
+ simd8uint32& lowestIndices) {
+ for (size_t j = 0; j < 8; j++) {
+ bool comparison = (candidateValues.f32[j] < lowestValues.f32[j]);
+ if (comparison) {
+ lowestValues.f32[j] = candidateValues.f32[j];
+ lowestIndices.u32[j] = candidateIndices.u32[j];
+ }
+ }
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8float32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8float32& minValues,
+ simd8uint32& minIndices,
+ simd8float32& maxValues,
+ simd8uint32& maxIndices) {
+ for (size_t i = 0; i < 8; i++) {
+ bool flag = (candidateValues.f32[i] < currentValues.f32[i]);
+ minValues.f32[i] = flag ? candidateValues.f32[i] : currentValues.f32[i];
+ minIndices.u32[i] =
+ flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ maxValues.f32[i] =
+ !flag ? candidateValues.f32[i] : currentValues.f32[i];
+ maxIndices.u32[i] =
+ !flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ }
+}
+
+} // namespace
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_neon.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_neon.h
new file mode 100644
index 0000000..10adc22
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_neon.h
@@ -0,0 +1,1360 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// TODO: Support big endian (currently supporting only little endian)
+
+#include <algorithm>
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <string>
+#include <type_traits>
+
+#include <arm_neon.h>
+
+#include <faiss/impl/FaissAssert.h>
+
+namespace faiss {
+
+namespace detail {
+
+namespace simdlib {
+
+static inline uint8x16x2_t reinterpret_u8(const uint8x16x2_t& v) {
+ return v;
+}
+
+static inline uint8x16x2_t reinterpret_u8(const uint16x8x2_t& v) {
+ return {vreinterpretq_u8_u16(v.val[0]), vreinterpretq_u8_u16(v.val[1])};
+}
+
+static inline uint8x16x2_t reinterpret_u8(const uint32x4x2_t& v) {
+ return {vreinterpretq_u8_u32(v.val[0]), vreinterpretq_u8_u32(v.val[1])};
+}
+
+static inline uint8x16x2_t reinterpret_u8(const float32x4x2_t& v) {
+ return {vreinterpretq_u8_f32(v.val[0]), vreinterpretq_u8_f32(v.val[1])};
+}
+
+static inline uint16x8x2_t reinterpret_u16(const uint8x16x2_t& v) {
+ return {vreinterpretq_u16_u8(v.val[0]), vreinterpretq_u16_u8(v.val[1])};
+}
+
+static inline uint16x8x2_t reinterpret_u16(const uint16x8x2_t& v) {
+ return v;
+}
+
+static inline uint16x8x2_t reinterpret_u16(const uint32x4x2_t& v) {
+ return {vreinterpretq_u16_u32(v.val[0]), vreinterpretq_u16_u32(v.val[1])};
+}
+
+static inline uint16x8x2_t reinterpret_u16(const float32x4x2_t& v) {
+ return {vreinterpretq_u16_f32(v.val[0]), vreinterpretq_u16_f32(v.val[1])};
+}
+
+static inline uint32x4x2_t reinterpret_u32(const uint8x16x2_t& v) {
+ return {vreinterpretq_u32_u8(v.val[0]), vreinterpretq_u32_u8(v.val[1])};
+}
+
+static inline uint32x4x2_t reinterpret_u32(const uint16x8x2_t& v) {
+ return {vreinterpretq_u32_u16(v.val[0]), vreinterpretq_u32_u16(v.val[1])};
+}
+
+static inline uint32x4x2_t reinterpret_u32(const uint32x4x2_t& v) {
+ return v;
+}
+
+static inline uint32x4x2_t reinterpret_u32(const float32x4x2_t& v) {
+ return {vreinterpretq_u32_f32(v.val[0]), vreinterpretq_u32_f32(v.val[1])};
+}
+
+static inline float32x4x2_t reinterpret_f32(const uint8x16x2_t& v) {
+ return {vreinterpretq_f32_u8(v.val[0]), vreinterpretq_f32_u8(v.val[1])};
+}
+
+static inline float32x4x2_t reinterpret_f32(const uint16x8x2_t& v) {
+ return {vreinterpretq_f32_u16(v.val[0]), vreinterpretq_f32_u16(v.val[1])};
+}
+
+static inline float32x4x2_t reinterpret_f32(const uint32x4x2_t& v) {
+ return {vreinterpretq_f32_u32(v.val[0]), vreinterpretq_f32_u32(v.val[1])};
+}
+
+static inline float32x4x2_t reinterpret_f32(const float32x4x2_t& v) {
+ return v;
+}
+
+// Surprisingly, vdupq_n_u16 has the type of
+// uint16x8_t (std::uint32_t) , and vdupq_n_u8 also has
+// uint8x16_t (std::uint32_t) on **some environments**.
+// We want argument type as same as the type of element
+// of result vector type (std::uint16_t for uint16x8_t,
+// and std::uint8_t for uint8x16_t) instead of
+// std::uint32_t due to using set1 function templates,
+// so let's fix the argument type here and use these
+// overload below.
+static inline ::uint16x8_t vdupq_n_u16(std::uint16_t v) {
+ return ::vdupq_n_u16(v);
+}
+
+static inline ::uint8x16_t vdupq_n_u8(std::uint8_t v) {
+ return ::vdupq_n_u8(v);
+}
+
+template <
+ typename T,
+ typename U = decltype(reinterpret_u8(std::declval<T>().data))>
+struct is_simd256bit : std::is_same<U, uint8x16x2_t> {};
+
+static inline void bin(const char (&bytes)[32], char bits[257]) {
+ for (int i = 0; i < 256; ++i) {
+ bits[i] = '0' + ((bytes[i / 8] >> (i % 8)) & 1);
+ }
+ bits[256] = 0;
+}
+
+template <typename T, size_t N, typename S>
+static inline void bin(const S& simd, char bits[257]) {
+ static_assert(
+ std::is_same<void (S::*)(T*) const, decltype(&S::store)>::value,
+ "invalid T");
+ T ds[N];
+ simd.store(ds);
+ char bytes[32];
+ std::memcpy(bytes, ds, sizeof(char) * 32);
+ bin(bytes, bits);
+}
+
+template <typename S>
+static inline std::string bin(const S& simd) {
+ char bits[257];
+ simd.bin(bits);
+ return std::string(bits);
+}
+
+template <typename T>
+using remove_cv_ref_t =
+ typename std::remove_reference<typename std::remove_cv<T>::type>::type;
+
+template <typename D, typename T>
+struct set1_impl {
+ D& d;
+ T t;
+ template <remove_cv_ref_t<decltype(std::declval<D>().val[0])> (*F)(T)>
+ inline void call() {
+ const auto v = F(t);
+ d.val[0] = v;
+ d.val[1] = v;
+ }
+};
+
+template <typename D, typename T>
+static inline set1_impl<remove_cv_ref_t<D>, T> set1(D& d, T t) {
+ return {d, t};
+}
+
+template <typename T, size_t N, typename S>
+static inline std::string elements_to_string(const char* fmt, const S& simd) {
+ static_assert(
+ std::is_same<void (S::*)(T*) const, decltype(&S::store)>::value,
+ "invalid T");
+ T bytes[N];
+ simd.store(bytes);
+ char res[1000], *ptr = res;
+ for (size_t i = 0; i < N; ++i) {
+ int bytesWritten =
+ snprintf(ptr, sizeof(res) - (ptr - res), fmt, bytes[i]);
+ ptr += bytesWritten;
+ }
+ // The format usually contains a ',' separator so this is to remove the last
+ // separator.
+ ptr[-1] = 0;
+ return std::string(res);
+}
+
+template <typename T, typename U>
+struct unary_func_impl {
+ const U& a;
+ using Telem = remove_cv_ref_t<decltype(std::declval<T>().val[0])>;
+ using Uelem = remove_cv_ref_t<decltype(std::declval<U>().val[0])>;
+ template <Telem (*F)(Uelem)>
+ inline T call() {
+ T t;
+ t.val[0] = F(a.val[0]);
+ t.val[1] = F(a.val[1]);
+ return t;
+ }
+};
+
+template <typename T>
+static inline unary_func_impl<remove_cv_ref_t<T>, remove_cv_ref_t<T>> unary_func(
+ const T& a) {
+ return {a};
+}
+
+template <typename T, typename U>
+static inline unary_func_impl<remove_cv_ref_t<T>, remove_cv_ref_t<U>> unary_func(
+ const U& a) {
+ return {a};
+}
+
+template <typename T, typename U>
+struct binary_func_impl {
+ const U& a;
+ const U& b;
+ using Telem = remove_cv_ref_t<decltype(std::declval<T>().val[0])>;
+ using Uelem = remove_cv_ref_t<decltype(std::declval<U>().val[0])>;
+ template <Telem (*F)(Uelem, Uelem)>
+ inline T call() {
+ T t;
+ t.val[0] = F(a.val[0], b.val[0]);
+ t.val[1] = F(a.val[1], b.val[1]);
+ return t;
+ }
+};
+
+template <typename T>
+static inline binary_func_impl<remove_cv_ref_t<T>, remove_cv_ref_t<T>>
+binary_func(const T& a, const T& b) {
+ return {a, b};
+}
+
+template <typename T, typename U>
+static inline binary_func_impl<remove_cv_ref_t<T>, remove_cv_ref_t<U>>
+binary_func(const U& a, const U& b) {
+ return {a, b};
+}
+
+static inline uint16_t vmovmask_u8(const uint8x16_t& v) {
+ uint8_t d[16];
+ const auto v2 = vreinterpretq_u16_u8(vshrq_n_u8(v, 7));
+ const auto v3 = vreinterpretq_u32_u16(vsraq_n_u16(v2, v2, 7));
+ const auto v4 = vreinterpretq_u64_u32(vsraq_n_u32(v3, v3, 14));
+ vst1q_u8(d, vreinterpretq_u8_u64(vsraq_n_u64(v4, v4, 28)));
+ return d[0] | static_cast<uint16_t>(d[8]) << 8u;
+}
+
+template <uint16x8_t (*F)(uint16x8_t, uint16x8_t)>
+static inline uint32_t cmp_xe32(
+ const uint16x8x2_t& d0,
+ const uint16x8x2_t& d1,
+ const uint16x8x2_t& thr) {
+ const auto d0_thr = detail::simdlib::binary_func(d0, thr).call<F>();
+ const auto d1_thr = detail::simdlib::binary_func(d1, thr).call<F>();
+ const auto d0_mask = vmovmask_u8(
+ vmovn_high_u16(vmovn_u16(d0_thr.val[0]), d0_thr.val[1]));
+ const auto d1_mask = vmovmask_u8(
+ vmovn_high_u16(vmovn_u16(d1_thr.val[0]), d1_thr.val[1]));
+ return d0_mask | static_cast<uint32_t>(d1_mask) << 16;
+}
+
+template <std::uint8_t Shift>
+static inline uint16x8_t vshlq(uint16x8_t vec) {
+ return vshlq_n_u16(vec, Shift);
+}
+
+template <std::uint8_t Shift>
+static inline uint16x8_t vshrq(uint16x8_t vec) {
+ return vshrq_n_u16(vec, Shift);
+}
+
+} // namespace simdlib
+
+} // namespace detail
+
+/// vector of 16 elements in uint16
+struct simd16uint16 {
+ uint16x8x2_t data;
+
+ simd16uint16() = default;
+
+ explicit simd16uint16(int x) : data{vdupq_n_u16(x), vdupq_n_u16(x)} {}
+
+ explicit simd16uint16(uint16_t x) : data{vdupq_n_u16(x), vdupq_n_u16(x)} {}
+
+ explicit simd16uint16(const uint16x8x2_t& v) : data{v} {}
+
+ explicit simd16uint16(
+ uint16_t u0,
+ uint16_t u1,
+ uint16_t u2,
+ uint16_t u3,
+ uint16_t u4,
+ uint16_t u5,
+ uint16_t u6,
+ uint16_t u7,
+ uint16_t u8,
+ uint16_t u9,
+ uint16_t u10,
+ uint16_t u11,
+ uint16_t u12,
+ uint16_t u13,
+ uint16_t u14,
+ uint16_t u15) {
+ uint16_t temp[16] = {
+ u0,
+ u1,
+ u2,
+ u3,
+ u4,
+ u5,
+ u6,
+ u7,
+ u8,
+ u9,
+ u10,
+ u11,
+ u12,
+ u13,
+ u14,
+ u15};
+ data.val[0] = vld1q_u16(temp);
+ data.val[1] = vld1q_u16(temp + 8);
+ }
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ explicit simd16uint16(const T& x)
+ : data{detail::simdlib::reinterpret_u16(x.data)} {}
+
+ explicit simd16uint16(const uint16_t* x)
+ : data{vld1q_u16(x), vld1q_u16(x + 8)} {}
+
+ void clear() {
+ detail::simdlib::set1(data, static_cast<uint16_t>(0))
+ .call<&detail::simdlib::vdupq_n_u16>();
+ }
+
+ void storeu(uint16_t* ptr) const {
+ vst1q_u16(ptr, data.val[0]);
+ vst1q_u16(ptr + 8, data.val[1]);
+ }
+
+ void loadu(const uint16_t* ptr) {
+ data.val[0] = vld1q_u16(ptr);
+ data.val[1] = vld1q_u16(ptr + 8);
+ }
+
+ void store(uint16_t* ptr) const {
+ storeu(ptr);
+ }
+
+ void bin(char bits[257]) const {
+ detail::simdlib::bin<uint16_t, 16u>(*this, bits);
+ }
+
+ std::string bin() const {
+ return detail::simdlib::bin(*this);
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ return detail::simdlib::elements_to_string<uint16_t, 16u>(fmt, *this);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint16_t x) {
+ detail::simdlib::set1(data, x).call<&detail::simdlib::vdupq_n_u16>();
+ }
+
+ simd16uint16 operator*(const simd16uint16& other) const {
+ return simd16uint16{detail::simdlib::binary_func(data, other.data)
+ .call<&vmulq_u16>()};
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator>>(const int shift) const {
+ switch (shift) {
+ case 0:
+ return *this;
+ case 1:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<1>>()};
+ case 2:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<2>>()};
+ case 3:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<3>>()};
+ case 4:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<4>>()};
+ case 5:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<5>>()};
+ case 6:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<6>>()};
+ case 7:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<7>>()};
+ case 8:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<8>>()};
+ case 9:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<9>>()};
+ case 10:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<10>>()};
+ case 11:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<11>>()};
+ case 12:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<12>>()};
+ case 13:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<13>>()};
+ case 14:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<14>>()};
+ case 15:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshrq<15>>()};
+ default:
+ FAISS_THROW_FMT("Invalid shift %d", shift);
+ }
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator<<(const int shift) const {
+ switch (shift) {
+ case 0:
+ return *this;
+ case 1:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<1>>()};
+ case 2:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<2>>()};
+ case 3:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<3>>()};
+ case 4:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<4>>()};
+ case 5:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<5>>()};
+ case 6:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<6>>()};
+ case 7:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<7>>()};
+ case 8:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<8>>()};
+ case 9:
+ return simd16uint16{detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<9>>()};
+ case 10:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<10>>()};
+ case 11:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<11>>()};
+ case 12:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<12>>()};
+ case 13:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<13>>()};
+ case 14:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<14>>()};
+ case 15:
+ return simd16uint16{
+ detail::simdlib::unary_func(data)
+ .call<detail::simdlib::vshlq<15>>()};
+ default:
+ FAISS_THROW_FMT("Invalid shift %d", shift);
+ }
+ }
+
+ simd16uint16 operator+=(const simd16uint16& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ simd16uint16 operator-=(const simd16uint16& other) {
+ *this = *this - other;
+ return *this;
+ }
+
+ simd16uint16 operator+(const simd16uint16& other) const {
+ return simd16uint16{detail::simdlib::binary_func(data, other.data)
+ .call<&vaddq_u16>()};
+ }
+
+ simd16uint16 operator-(const simd16uint16& other) const {
+ return simd16uint16{detail::simdlib::binary_func(data, other.data)
+ .call<&vsubq_u16>()};
+ }
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ simd16uint16 operator&(const T& other) const {
+ return simd16uint16{
+ detail::simdlib::binary_func(
+ data, detail::simdlib::reinterpret_u16(other.data))
+ .template call<&vandq_u16>()};
+ }
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ simd16uint16 operator|(const T& other) const {
+ return simd16uint16{
+ detail::simdlib::binary_func(
+ data, detail::simdlib::reinterpret_u16(other.data))
+ .template call<&vorrq_u16>()};
+ }
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ simd16uint16 operator^(const T& other) const {
+ return simd16uint16{
+ detail::simdlib::binary_func(
+ data, detail::simdlib::reinterpret_u16(other.data))
+ .template call<&veorq_u16>()};
+ }
+
+ // returns binary masks
+ simd16uint16 operator==(const simd16uint16& other) const {
+ return simd16uint16{detail::simdlib::binary_func(data, other.data)
+ .call<&vceqq_u16>()};
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ template <typename T>
+ bool is_same_as(T other) const {
+ const auto o = detail::simdlib::reinterpret_u16(other.data);
+ const auto equals = detail::simdlib::binary_func(data, o)
+ .template call<&vceqq_u16>();
+ const auto equal = vandq_u16(equals.val[0], equals.val[1]);
+ return vminvq_u16(equal) == 0xffffu;
+ }
+
+ simd16uint16 operator~() const {
+ return simd16uint16{
+ detail::simdlib::unary_func(data).call<&vmvnq_u16>()};
+ }
+
+ // get scalar at index 0
+ uint16_t get_scalar_0() const {
+ return vgetq_lane_u16(data.val[0], 0);
+ }
+
+ // mask of elements where this >= thresh
+ // 2 bit per component: 16 * 2 = 32 bit
+ uint32_t ge_mask(const simd16uint16& thresh) const {
+ const auto input = detail::simdlib::binary_func(data, thresh.data)
+ .call<&vcgeq_u16>();
+ const auto vmovmask_u16 = [](uint16x8_t v) -> uint16_t {
+ uint16_t d[8];
+ const auto v2 = vreinterpretq_u32_u16(vshrq_n_u16(v, 14));
+ const auto v3 = vreinterpretq_u64_u32(vsraq_n_u32(v2, v2, 14));
+ vst1q_u16(d, vreinterpretq_u16_u64(vsraq_n_u64(v3, v3, 28)));
+ return d[0] | d[4] << 8u;
+ };
+ return static_cast<uint32_t>(vmovmask_u16(input.val[1])) << 16u |
+ vmovmask_u16(input.val[0]);
+ }
+
+ uint32_t le_mask(const simd16uint16& thresh) const {
+ return thresh.ge_mask(*this);
+ }
+
+ uint32_t gt_mask(const simd16uint16& thresh) const {
+ return ~le_mask(thresh);
+ }
+
+ bool all_gt(const simd16uint16& thresh) const {
+ return le_mask(thresh) == 0;
+ }
+
+ // for debugging only
+ uint16_t operator[](int i) const {
+ uint16_t tab[8];
+ const bool high = i >= 8;
+ vst1q_u16(tab, data.val[high]);
+ return tab[i - high * 8];
+ }
+
+ void accu_min(const simd16uint16& incoming) {
+ data = detail::simdlib::binary_func(incoming.data, data)
+ .call<&vminq_u16>();
+ }
+
+ void accu_max(const simd16uint16& incoming) {
+ data = detail::simdlib::binary_func(incoming.data, data)
+ .call<&vmaxq_u16>();
+ }
+};
+
+// not really a std::min because it returns an elementwise min
+inline simd16uint16 min(const simd16uint16& av, const simd16uint16& bv) {
+ return simd16uint16{
+ detail::simdlib::binary_func(av.data, bv.data).call<&vminq_u16>()};
+}
+
+inline simd16uint16 max(const simd16uint16& av, const simd16uint16& bv) {
+ return simd16uint16{
+ detail::simdlib::binary_func(av.data, bv.data).call<&vmaxq_u16>()};
+}
+
+// decompose in 128-lanes: a = (a0, a1), b = (b0, b1)
+// return (a0 + a1, b0 + b1)
+// TODO find a better name
+inline simd16uint16 combine2x2(const simd16uint16& a, const simd16uint16& b) {
+ return simd16uint16{uint16x8x2_t{
+ vaddq_u16(a.data.val[0], a.data.val[1]),
+ vaddq_u16(b.data.val[0], b.data.val[1])}};
+}
+
+// compare d0 and d1 to thr, return 32 bits corresponding to the concatenation
+// of d0 and d1 with thr
+inline uint32_t cmp_ge32(
+ const simd16uint16& d0,
+ const simd16uint16& d1,
+ const simd16uint16& thr) {
+ return detail::simdlib::cmp_xe32<&vcgeq_u16>(d0.data, d1.data, thr.data);
+}
+
+inline uint32_t cmp_le32(
+ const simd16uint16& d0,
+ const simd16uint16& d1,
+ const simd16uint16& thr) {
+ return detail::simdlib::cmp_xe32<&vcleq_u16>(d0.data, d1.data, thr.data);
+}
+
+// hadd does not cross lanes
+inline simd16uint16 hadd(const simd16uint16& a, const simd16uint16& b) {
+ return simd16uint16{
+ detail::simdlib::binary_func(a.data, b.data).call<&vpaddq_u16>()};
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd16uint16 candidateValues,
+ const simd16uint16 candidateIndices,
+ const simd16uint16 currentValues,
+ const simd16uint16 currentIndices,
+ simd16uint16& minValues,
+ simd16uint16& minIndices,
+ simd16uint16& maxValues,
+ simd16uint16& maxIndices) {
+ const uint16x8x2_t comparison =
+ detail::simdlib::binary_func(
+ candidateValues.data, currentValues.data)
+ .call<&vcltq_u16>();
+
+ minValues = min(candidateValues, currentValues);
+ minIndices.data = uint16x8x2_t{
+ vbslq_u16(
+ comparison.val[0],
+ candidateIndices.data.val[0],
+ currentIndices.data.val[0]),
+ vbslq_u16(
+ comparison.val[1],
+ candidateIndices.data.val[1],
+ currentIndices.data.val[1])};
+
+ maxValues = max(candidateValues, currentValues);
+ maxIndices.data = uint16x8x2_t{
+ vbslq_u16(
+ comparison.val[0],
+ currentIndices.data.val[0],
+ candidateIndices.data.val[0]),
+ vbslq_u16(
+ comparison.val[1],
+ currentIndices.data.val[1],
+ candidateIndices.data.val[1])};
+}
+
+// vector of 32 unsigned 8-bit integers
+struct simd32uint8 {
+ uint8x16x2_t data;
+
+ simd32uint8() = default;
+
+ explicit simd32uint8(int x) : data{vdupq_n_u8(x), vdupq_n_u8(x)} {}
+
+ explicit simd32uint8(uint8_t x) : data{vdupq_n_u8(x), vdupq_n_u8(x)} {}
+
+ explicit simd32uint8(const uint8x16x2_t& v) : data{v} {}
+
+ template <
+ uint8_t _0,
+ uint8_t _1,
+ uint8_t _2,
+ uint8_t _3,
+ uint8_t _4,
+ uint8_t _5,
+ uint8_t _6,
+ uint8_t _7,
+ uint8_t _8,
+ uint8_t _9,
+ uint8_t _10,
+ uint8_t _11,
+ uint8_t _12,
+ uint8_t _13,
+ uint8_t _14,
+ uint8_t _15,
+ uint8_t _16,
+ uint8_t _17,
+ uint8_t _18,
+ uint8_t _19,
+ uint8_t _20,
+ uint8_t _21,
+ uint8_t _22,
+ uint8_t _23,
+ uint8_t _24,
+ uint8_t _25,
+ uint8_t _26,
+ uint8_t _27,
+ uint8_t _28,
+ uint8_t _29,
+ uint8_t _30,
+ uint8_t _31>
+ static simd32uint8 create() {
+ constexpr uint8_t ds[32] = {_0, _1, _2, _3, _4, _5, _6, _7,
+ _8, _9, _10, _11, _12, _13, _14, _15,
+ _16, _17, _18, _19, _20, _21, _22, _23,
+ _24, _25, _26, _27, _28, _29, _30, _31};
+ return simd32uint8{ds};
+ }
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ explicit simd32uint8(const T& x)
+ : data{detail::simdlib::reinterpret_u8(x.data)} {}
+
+ explicit simd32uint8(const uint8_t* x)
+ : data{vld1q_u8(x), vld1q_u8(x + 16)} {}
+
+ void clear() {
+ detail::simdlib::set1(data, static_cast<uint8_t>(0))
+ .call<&detail::simdlib::vdupq_n_u8>();
+ }
+
+ void storeu(uint8_t* ptr) const {
+ vst1q_u8(ptr, data.val[0]);
+ vst1q_u8(ptr + 16, data.val[1]);
+ }
+
+ void loadu(const uint8_t* ptr) {
+ data.val[0] = vld1q_u8(ptr);
+ data.val[1] = vld1q_u8(ptr + 16);
+ }
+
+ void store(uint8_t* ptr) const {
+ storeu(ptr);
+ }
+
+ void bin(char bits[257]) const {
+ uint8_t bytes[32];
+ store(bytes);
+ detail::simdlib::bin(
+ const_cast<const char(&)[32]>(
+ reinterpret_cast<char(&)[32]>(bytes)),
+ bits);
+ }
+
+ std::string bin() const {
+ return detail::simdlib::bin(*this);
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ return detail::simdlib::elements_to_string<uint8_t, 32u>(fmt, *this);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint8_t x) {
+ detail::simdlib::set1(data, x).call<&detail::simdlib::vdupq_n_u8>();
+ }
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ simd32uint8 operator&(const T& other) const {
+ return simd32uint8{
+ detail::simdlib::binary_func(
+ data, detail::simdlib::reinterpret_u8(other.data))
+ .template call<&vandq_u8>()};
+ }
+
+ simd32uint8 operator+(const simd32uint8& other) const {
+ return simd32uint8{detail::simdlib::binary_func(data, other.data)
+ .call<&vaddq_u8>()};
+ }
+
+ // The very important operation that everything relies on
+ simd32uint8 lookup_2_lanes(const simd32uint8& idx) const {
+ return simd32uint8{detail::simdlib::binary_func(data, idx.data)
+ .call<&vqtbl1q_u8>()};
+ }
+
+ simd32uint8 operator+=(const simd32uint8& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ // for debugging only
+ uint8_t operator[](int i) const {
+ uint8_t tab[16];
+ const bool high = i >= 16;
+ vst1q_u8(tab, data.val[high]);
+ return tab[i - high * 16];
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ template <typename T>
+ bool is_same_as(T other) const {
+ const auto o = detail::simdlib::reinterpret_u8(other.data);
+ const auto equals = detail::simdlib::binary_func(data, o)
+ .template call<&vceqq_u8>();
+ const auto equal = vandq_u8(equals.val[0], equals.val[1]);
+ return vminvq_u8(equal) == 0xffu;
+ }
+};
+
+// convert with saturation
+// careful: this does not cross lanes, so the order is weird
+inline simd32uint8 uint16_to_uint8_saturate(
+ const simd16uint16& a,
+ const simd16uint16& b) {
+ return simd32uint8{uint8x16x2_t{
+ vqmovn_high_u16(vqmovn_u16(a.data.val[0]), b.data.val[0]),
+ vqmovn_high_u16(vqmovn_u16(a.data.val[1]), b.data.val[1])}};
+}
+
+/// get most significant bit of each byte
+inline uint32_t get_MSBs(const simd32uint8& a) {
+ using detail::simdlib::vmovmask_u8;
+ return vmovmask_u8(a.data.val[0]) |
+ static_cast<uint32_t>(vmovmask_u8(a.data.val[1])) << 16u;
+}
+
+/// use MSB of each byte of mask to select a byte between a and b
+inline simd32uint8 blendv(
+ const simd32uint8& a,
+ const simd32uint8& b,
+ const simd32uint8& mask) {
+ const auto msb = vdupq_n_u8(0x80);
+ const uint8x16x2_t msb_mask = {
+ vtstq_u8(mask.data.val[0], msb), vtstq_u8(mask.data.val[1], msb)};
+ const uint8x16x2_t selected = {
+ vbslq_u8(msb_mask.val[0], b.data.val[0], a.data.val[0]),
+ vbslq_u8(msb_mask.val[1], b.data.val[1], a.data.val[1])};
+ return simd32uint8{selected};
+}
+
+/// vector of 8 unsigned 32-bit integers
+struct simd8uint32 {
+ uint32x4x2_t data;
+
+ simd8uint32() = default;
+
+ explicit simd8uint32(uint32_t x) : data{vdupq_n_u32(x), vdupq_n_u32(x)} {}
+
+ explicit simd8uint32(const uint32x4x2_t& v) : data{v} {}
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ explicit simd8uint32(const T& x)
+ : data{detail::simdlib::reinterpret_u32(x.data)} {}
+
+ explicit simd8uint32(const uint8_t* x) : simd8uint32(simd32uint8(x)) {}
+
+ explicit simd8uint32(
+ uint32_t u0,
+ uint32_t u1,
+ uint32_t u2,
+ uint32_t u3,
+ uint32_t u4,
+ uint32_t u5,
+ uint32_t u6,
+ uint32_t u7) {
+ uint32_t temp[8] = {u0, u1, u2, u3, u4, u5, u6, u7};
+ data.val[0] = vld1q_u32(temp);
+ data.val[1] = vld1q_u32(temp + 4);
+ }
+
+ simd8uint32 operator+(simd8uint32 other) const {
+ return simd8uint32{detail::simdlib::binary_func(data, other.data)
+ .call<&vaddq_u32>()};
+ }
+
+ simd8uint32 operator-(simd8uint32 other) const {
+ return simd8uint32{detail::simdlib::binary_func(data, other.data)
+ .call<&vsubq_u32>()};
+ }
+
+ simd8uint32& operator+=(const simd8uint32& other) {
+ data.val[0] = vaddq_u32(data.val[0], other.data.val[0]);
+ data.val[1] = vaddq_u32(data.val[1], other.data.val[1]);
+ return *this;
+ }
+
+ simd8uint32 operator==(simd8uint32 other) const {
+ return simd8uint32{detail::simdlib::binary_func(data, other.data)
+ .call<&vceqq_u32>()};
+ }
+
+ simd8uint32 operator~() const {
+ return simd8uint32{
+ detail::simdlib::unary_func(data).call<&vmvnq_u32>()};
+ }
+
+ simd8uint32 operator!=(simd8uint32 other) const {
+ return ~(*this == other);
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ template <typename T>
+ bool is_same_as(T other) const {
+ const auto o = detail::simdlib::reinterpret_u32(other.data);
+ const auto equals = detail::simdlib::binary_func(data, o)
+ .template call<&vceqq_u32>();
+ const auto equal = vandq_u32(equals.val[0], equals.val[1]);
+ return vminvq_u32(equal) == 0xffffffffu;
+ }
+
+ void clear() {
+ detail::simdlib::set1(data, static_cast<uint32_t>(0))
+ .call<&vdupq_n_u32>();
+ }
+
+ void storeu(uint32_t* ptr) const {
+ vst1q_u32(ptr, data.val[0]);
+ vst1q_u32(ptr + 4, data.val[1]);
+ }
+
+ void loadu(const uint32_t* ptr) {
+ data.val[0] = vld1q_u32(ptr);
+ data.val[1] = vld1q_u32(ptr + 4);
+ }
+
+ void store(uint32_t* ptr) const {
+ storeu(ptr);
+ }
+
+ void bin(char bits[257]) const {
+ detail::simdlib::bin<uint32_t, 8u>(*this, bits);
+ }
+
+ std::string bin() const {
+ return detail::simdlib::bin(*this);
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ return detail::simdlib::elements_to_string<uint32_t, 8u>(fmt, *this);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%08x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%10d,");
+ }
+
+ void set1(uint32_t x) {
+ detail::simdlib::set1(data, x).call<&vdupq_n_u32>();
+ }
+
+ simd8uint32 unzip() const {
+ return simd8uint32{uint32x4x2_t{
+ vuzp1q_u32(data.val[0], data.val[1]),
+ vuzp2q_u32(data.val[0], data.val[1])}};
+ }
+};
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8uint32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8uint32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8uint32& minValues,
+ simd8uint32& minIndices,
+ simd8uint32& maxValues,
+ simd8uint32& maxIndices) {
+ const uint32x4x2_t comparison =
+ detail::simdlib::binary_func(
+ candidateValues.data, currentValues.data)
+ .call<&vcltq_u32>();
+
+ minValues.data = detail::simdlib::binary_func(
+ candidateValues.data, currentValues.data)
+ .call<&vminq_u32>();
+ minIndices.data = uint32x4x2_t{
+ vbslq_u32(
+ comparison.val[0],
+ candidateIndices.data.val[0],
+ currentIndices.data.val[0]),
+ vbslq_u32(
+ comparison.val[1],
+ candidateIndices.data.val[1],
+ currentIndices.data.val[1])};
+
+ maxValues.data = detail::simdlib::binary_func(
+ candidateValues.data, currentValues.data)
+ .call<&vmaxq_u32>();
+ maxIndices.data = uint32x4x2_t{
+ vbslq_u32(
+ comparison.val[0],
+ currentIndices.data.val[0],
+ candidateIndices.data.val[0]),
+ vbslq_u32(
+ comparison.val[1],
+ currentIndices.data.val[1],
+ candidateIndices.data.val[1])};
+}
+
+struct simd8float32 {
+ float32x4x2_t data;
+
+ simd8float32() = default;
+
+ explicit simd8float32(float x) : data{vdupq_n_f32(x), vdupq_n_f32(x)} {}
+
+ explicit simd8float32(const float32x4x2_t& v) : data{v} {}
+
+ template <
+ typename T,
+ typename std::enable_if<
+ detail::simdlib::is_simd256bit<T>::value,
+ std::nullptr_t>::type = nullptr>
+ explicit simd8float32(const T& x)
+ : data{detail::simdlib::reinterpret_f32(x.data)} {}
+
+ explicit simd8float32(const float* x)
+ : data{vld1q_f32(x), vld1q_f32(x + 4)} {}
+
+ explicit simd8float32(
+ float f0,
+ float f1,
+ float f2,
+ float f3,
+ float f4,
+ float f5,
+ float f6,
+ float f7) {
+ float temp[8] = {f0, f1, f2, f3, f4, f5, f6, f7};
+ data.val[0] = vld1q_f32(temp);
+ data.val[1] = vld1q_f32(temp + 4);
+ }
+
+ void clear() {
+ detail::simdlib::set1(data, 0.f).call<&vdupq_n_f32>();
+ }
+
+ void storeu(float* ptr) const {
+ vst1q_f32(ptr, data.val[0]);
+ vst1q_f32(ptr + 4, data.val[1]);
+ }
+
+ void loadu(const float* ptr) {
+ data.val[0] = vld1q_f32(ptr);
+ data.val[1] = vld1q_f32(ptr + 4);
+ }
+
+ void store(float* ptr) const {
+ storeu(ptr);
+ }
+
+ void bin(char bits[257]) const {
+ detail::simdlib::bin<float, 8u>(*this, bits);
+ }
+
+ std::string bin() const {
+ return detail::simdlib::bin(*this);
+ }
+
+ simd8float32 operator*(const simd8float32& other) const {
+ return simd8float32{detail::simdlib::binary_func(data, other.data)
+ .call<&vmulq_f32>()};
+ }
+
+ simd8float32 operator+(const simd8float32& other) const {
+ return simd8float32{detail::simdlib::binary_func(data, other.data)
+ .call<&vaddq_f32>()};
+ }
+
+ simd8float32 operator-(const simd8float32& other) const {
+ return simd8float32{detail::simdlib::binary_func(data, other.data)
+ .call<&vsubq_f32>()};
+ }
+
+ simd8float32& operator+=(const simd8float32& other) {
+ // In this context, it is more compiler friendly to write intrinsics
+ // directly instead of using binary_func
+ data.val[0] = vaddq_f32(data.val[0], other.data.val[0]);
+ data.val[1] = vaddq_f32(data.val[1], other.data.val[1]);
+ return *this;
+ }
+
+ simd8uint32 operator==(simd8float32 other) const {
+ return simd8uint32{
+ detail::simdlib::binary_func<::uint32x4x2_t>(data, other.data)
+ .call<&vceqq_f32>()};
+ }
+
+ simd8uint32 operator!=(simd8float32 other) const {
+ return ~(*this == other);
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ template <typename T>
+ bool is_same_as(T other) const {
+ const auto o = detail::simdlib::reinterpret_f32(other.data);
+ const auto equals =
+ detail::simdlib::binary_func<::uint32x4x2_t>(data, o)
+ .template call<&vceqq_f32>();
+ const auto equal = vandq_u32(equals.val[0], equals.val[1]);
+ return vminvq_u32(equal) == 0xffffffffu;
+ }
+
+ std::string tostring() const {
+ return detail::simdlib::elements_to_string<float, 8u>("%g,", *this);
+ }
+};
+
+// hadd does not cross lanes
+inline simd8float32 hadd(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{
+ detail::simdlib::binary_func(a.data, b.data).call<&vpaddq_f32>()};
+}
+
+inline simd8float32 unpacklo(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{
+ detail::simdlib::binary_func(a.data, b.data).call<&vzip1q_f32>()};
+}
+
+inline simd8float32 unpackhi(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{
+ detail::simdlib::binary_func(a.data, b.data).call<&vzip2q_f32>()};
+}
+
+// compute a * b + c
+inline simd8float32 fmadd(
+ const simd8float32& a,
+ const simd8float32& b,
+ const simd8float32& c) {
+ return simd8float32{float32x4x2_t{
+ vfmaq_f32(c.data.val[0], a.data.val[0], b.data.val[0]),
+ vfmaq_f32(c.data.val[1], a.data.val[1], b.data.val[1])}};
+}
+
+// The following primitive is a vectorized version of the following code
+// snippet:
+// float lowestValue = HUGE_VAL;
+// uint lowestIndex = 0;
+// for (size_t i = 0; i < n; i++) {
+// if (values[i] < lowestValue) {
+// lowestValue = values[i];
+// lowestIndex = i;
+// }
+// }
+// Vectorized version can be implemented via two operations: cmp and blend
+// with something like this:
+// lowestValues = [HUGE_VAL; 8];
+// lowestIndices = {0, 1, 2, 3, 4, 5, 6, 7};
+// for (size_t i = 0; i < n; i += 8) {
+// auto comparison = cmp(values + i, lowestValues);
+// lowestValues = blend(
+// comparison,
+// values + i,
+// lowestValues);
+// lowestIndices = blend(
+// comparison,
+// i + {0, 1, 2, 3, 4, 5, 6, 7},
+// lowestIndices);
+// lowestIndices += {8, 8, 8, 8, 8, 8, 8, 8};
+// }
+// The problem is that blend primitive needs very different instruction
+// order for AVX and ARM.
+// So, let's introduce a combination of these two in order to avoid
+// confusion for ppl who write in low-level SIMD instructions. Additionally,
+// these two ops (cmp and blend) are very often used together.
+inline void cmplt_and_blend_inplace(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ simd8float32& lowestValues,
+ simd8uint32& lowestIndices) {
+ const auto comparison = detail::simdlib::binary_func<::uint32x4x2_t>(
+ candidateValues.data, lowestValues.data)
+ .call<&vcltq_f32>();
+
+ lowestValues.data = float32x4x2_t{
+ vbslq_f32(
+ comparison.val[0],
+ candidateValues.data.val[0],
+ lowestValues.data.val[0]),
+ vbslq_f32(
+ comparison.val[1],
+ candidateValues.data.val[1],
+ lowestValues.data.val[1])};
+ lowestIndices.data = uint32x4x2_t{
+ vbslq_u32(
+ comparison.val[0],
+ candidateIndices.data.val[0],
+ lowestIndices.data.val[0]),
+ vbslq_u32(
+ comparison.val[1],
+ candidateIndices.data.val[1],
+ lowestIndices.data.val[1])};
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8float32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8float32& minValues,
+ simd8uint32& minIndices,
+ simd8float32& maxValues,
+ simd8uint32& maxIndices) {
+ const uint32x4x2_t comparison =
+ detail::simdlib::binary_func<::uint32x4x2_t>(
+ candidateValues.data, currentValues.data)
+ .call<&vcltq_f32>();
+
+ minValues.data = detail::simdlib::binary_func(
+ candidateValues.data, currentValues.data)
+ .call<&vminq_f32>();
+ minIndices.data = uint32x4x2_t{
+ vbslq_u32(
+ comparison.val[0],
+ candidateIndices.data.val[0],
+ currentIndices.data.val[0]),
+ vbslq_u32(
+ comparison.val[1],
+ candidateIndices.data.val[1],
+ currentIndices.data.val[1])};
+
+ maxValues.data = detail::simdlib::binary_func(
+ candidateValues.data, currentValues.data)
+ .call<&vmaxq_f32>();
+ maxIndices.data = uint32x4x2_t{
+ vbslq_u32(
+ comparison.val[0],
+ currentIndices.data.val[0],
+ candidateIndices.data.val[0]),
+ vbslq_u32(
+ comparison.val[1],
+ currentIndices.data.val[1],
+ candidateIndices.data.val[1])};
+}
+
+namespace {
+
+// get even float32's of a and b, interleaved
+simd8float32 geteven(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{
+ detail::simdlib::binary_func(a.data, b.data).call<&vuzp1q_f32>()};
+}
+
+// get odd float32's of a and b, interleaved
+simd8float32 getodd(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{
+ detail::simdlib::binary_func(a.data, b.data).call<&vuzp2q_f32>()};
+}
+
+// 3 cycles
+// if the lanes are a = [a0 a1] and b = [b0 b1], return [a0 b0]
+simd8float32 getlow128(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{float32x4x2_t{a.data.val[0], b.data.val[0]}};
+}
+
+simd8float32 gethigh128(const simd8float32& a, const simd8float32& b) {
+ return simd8float32{float32x4x2_t{a.data.val[1], b.data.val[1]}};
+}
+
+} // namespace
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_ppc64.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_ppc64.h
new file mode 100644
index 0000000..8fc1109
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/simdlib_ppc64.h
@@ -0,0 +1,1084 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <cstdint>
+#include <cstring>
+#include <string>
+
+namespace faiss {
+
+struct simd256bit {
+ union {
+ uint8_t u8[32];
+ uint16_t u16[16];
+ uint32_t u32[8];
+ float f32[8];
+ };
+
+ simd256bit() {}
+
+ explicit simd256bit(const void* x) {
+ memcpy(u8, x, 32);
+ }
+
+ void clear() {
+ memset(u8, 0, 32);
+ }
+
+ void storeu(void* ptr) const {
+ memcpy(ptr, u8, 32);
+ }
+
+ void loadu(const void* ptr) {
+ memcpy(u8, ptr, 32);
+ }
+
+ void store(void* ptr) const {
+ storeu(ptr);
+ }
+
+ void bin(char bits[257]) const {
+ const char* bytes = (char*)this->u8;
+ for (int i = 0; i < 256; i++) {
+ bits[i] = '0' + ((bytes[i / 8] >> (i % 8)) & 1);
+ }
+ bits[256] = 0;
+ }
+
+ std::string bin() const {
+ char bits[257];
+ bin(bits);
+ return std::string(bits);
+ }
+
+ // Checks whether the other holds exactly the same bytes.
+ bool is_same_as(simd256bit other) const {
+ for (size_t i = 0; i < 8; i++) {
+ if (u32[i] != other.u32[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+};
+
+/// vector of 16 elements in uint16
+struct simd16uint16 : simd256bit {
+ simd16uint16() {}
+
+ explicit simd16uint16(int x) {
+ set1(x);
+ }
+
+ explicit simd16uint16(uint16_t x) {
+ set1(x);
+ }
+
+ explicit simd16uint16(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd16uint16(const uint16_t* x) : simd256bit((const void*)x) {}
+
+ explicit simd16uint16(
+ uint16_t u0,
+ uint16_t u1,
+ uint16_t u2,
+ uint16_t u3,
+ uint16_t u4,
+ uint16_t u5,
+ uint16_t u6,
+ uint16_t u7,
+ uint16_t u8,
+ uint16_t u9,
+ uint16_t u10,
+ uint16_t u11,
+ uint16_t u12,
+ uint16_t u13,
+ uint16_t u14,
+ uint16_t u15) {
+ this->u16[0] = u0;
+ this->u16[1] = u1;
+ this->u16[2] = u2;
+ this->u16[3] = u3;
+ this->u16[4] = u4;
+ this->u16[5] = u5;
+ this->u16[6] = u6;
+ this->u16[7] = u7;
+ this->u16[8] = u8;
+ this->u16[9] = u9;
+ this->u16[10] = u10;
+ this->u16[11] = u11;
+ this->u16[12] = u12;
+ this->u16[13] = u13;
+ this->u16[14] = u14;
+ this->u16[15] = u15;
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 16; i++) {
+ ptr += sprintf(ptr, fmt, u16[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ template <typename F>
+ static simd16uint16 unary_func(const simd16uint16& a, F&& f) {
+ simd16uint16 c;
+ for (int j = 0; j < 16; j++) {
+ c.u16[j] = f(a.u16[j]);
+ }
+ return c;
+ }
+
+ template <typename F>
+ static simd16uint16 binary_func(
+ const simd16uint16& a,
+ const simd16uint16& b,
+ F&& f) {
+ simd16uint16 c;
+ for (int j = 0; j < 16; j++) {
+ c.u16[j] = f(a.u16[j], b.u16[j]);
+ }
+ return c;
+ }
+
+ void set1(uint16_t x) {
+ for (int i = 0; i < 16; i++) {
+ u16[i] = x;
+ }
+ }
+
+ simd16uint16 operator*(const simd16uint16& other) const {
+ return binary_func(
+ *this, other, [](uint16_t a, uint16_t b) { return a * b; });
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator>>(const int shift) const {
+ return unary_func(*this, [shift](uint16_t a) { return a >> shift; });
+ }
+
+ // shift must be known at compile time
+ simd16uint16 operator<<(const int shift) const {
+ return unary_func(*this, [shift](uint16_t a) { return a << shift; });
+ }
+
+ simd16uint16 operator+=(const simd16uint16& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ simd16uint16 operator-=(const simd16uint16& other) {
+ *this = *this - other;
+ return *this;
+ }
+
+ simd16uint16 operator+(const simd16uint16& other) const {
+ return binary_func(
+ *this, other, [](uint16_t a, uint16_t b) { return a + b; });
+ }
+
+ simd16uint16 operator-(const simd16uint16& other) const {
+ return binary_func(
+ *this, other, [](uint16_t a, uint16_t b) { return a - b; });
+ }
+
+ simd16uint16 operator&(const simd256bit& other) const {
+ return binary_func(
+ *this, simd16uint16(other), [](uint16_t a, uint16_t b) {
+ return a & b;
+ });
+ }
+
+ simd16uint16 operator|(const simd256bit& other) const {
+ return binary_func(
+ *this, simd16uint16(other), [](uint16_t a, uint16_t b) {
+ return a | b;
+ });
+ }
+
+ simd16uint16 operator^(const simd256bit& other) const {
+ return binary_func(
+ *this, simd16uint16(other), [](uint16_t a, uint16_t b) {
+ return a ^ b;
+ });
+ }
+
+ // returns binary masks
+ simd16uint16 operator==(const simd16uint16& other) const {
+ return binary_func(*this, other, [](uint16_t a, uint16_t b) {
+ return a == b ? 0xffff : 0;
+ });
+ }
+
+ simd16uint16 operator~() const {
+ return unary_func(*this, [](uint16_t a) { return ~a; });
+ }
+
+ // get scalar at index 0
+ uint16_t get_scalar_0() const {
+ return u16[0];
+ }
+
+ // mask of elements where this >= thresh
+ // 2 bit per component: 16 * 2 = 32 bit
+ uint32_t ge_mask(const simd16uint16& thresh) const {
+ uint32_t gem = 0;
+ for (int j = 0; j < 16; j++) {
+ if (u16[j] >= thresh.u16[j]) {
+ gem |= 3 << (j * 2);
+ }
+ }
+ return gem;
+ }
+
+ uint32_t le_mask(const simd16uint16& thresh) const {
+ return thresh.ge_mask(*this);
+ }
+
+ uint32_t gt_mask(const simd16uint16& thresh) const {
+ return ~le_mask(thresh);
+ }
+
+ bool all_gt(const simd16uint16& thresh) const {
+ return le_mask(thresh) == 0;
+ }
+
+ // for debugging only
+ uint16_t operator[](int i) const {
+ return u16[i];
+ }
+
+ void accu_min(const simd16uint16& incoming) {
+ for (int j = 0; j < 16; j++) {
+ if (incoming.u16[j] < u16[j]) {
+ u16[j] = incoming.u16[j];
+ }
+ }
+ }
+
+ void accu_max(const simd16uint16& incoming) {
+ for (int j = 0; j < 16; j++) {
+ if (incoming.u16[j] > u16[j]) {
+ u16[j] = incoming.u16[j];
+ }
+ }
+ }
+};
+
+// not really a std::min because it returns an elementwise min
+inline simd16uint16 min(const simd16uint16& av, const simd16uint16& bv) {
+ return simd16uint16::binary_func(
+ av, bv, [](uint16_t a, uint16_t b) { return std::min(a, b); });
+}
+
+inline simd16uint16 max(const simd16uint16& av, const simd16uint16& bv) {
+ return simd16uint16::binary_func(
+ av, bv, [](uint16_t a, uint16_t b) { return std::max(a, b); });
+}
+
+// decompose in 128-lanes: a = (a0, a1), b = (b0, b1)
+// return (a0 + a1, b0 + b1)
+// TODO find a better name
+inline simd16uint16 combine2x2(const simd16uint16& a, const simd16uint16& b) {
+ simd16uint16 c;
+ for (int j = 0; j < 8; j++) {
+ c.u16[j] = a.u16[j] + a.u16[j + 8];
+ c.u16[j + 8] = b.u16[j] + b.u16[j + 8];
+ }
+ return c;
+}
+
+// compare d0 and d1 to thr, return 32 bits corresponding to the concatenation
+// of d0 and d1 with thr
+inline uint32_t cmp_ge32(
+ const simd16uint16& d0,
+ const simd16uint16& d1,
+ const simd16uint16& thr) {
+ uint32_t gem = 0;
+ for (int j = 0; j < 16; j++) {
+ if (d0.u16[j] >= thr.u16[j]) {
+ gem |= 1 << j;
+ }
+ if (d1.u16[j] >= thr.u16[j]) {
+ gem |= 1 << (j + 16);
+ }
+ }
+ return gem;
+}
+
+inline uint32_t cmp_le32(
+ const simd16uint16& d0,
+ const simd16uint16& d1,
+ const simd16uint16& thr) {
+ uint32_t gem = 0;
+ for (int j = 0; j < 16; j++) {
+ if (d0.u16[j] <= thr.u16[j]) {
+ gem |= 1 << j;
+ }
+ if (d1.u16[j] <= thr.u16[j]) {
+ gem |= 1 << (j + 16);
+ }
+ }
+ return gem;
+}
+
+// hadd does not cross lanes
+inline simd16uint16 hadd(const simd16uint16& a, const simd16uint16& b) {
+ simd16uint16 c;
+ c.u16[0] = a.u16[0] + a.u16[1];
+ c.u16[1] = a.u16[2] + a.u16[3];
+ c.u16[2] = a.u16[4] + a.u16[5];
+ c.u16[3] = a.u16[6] + a.u16[7];
+ c.u16[4] = b.u16[0] + b.u16[1];
+ c.u16[5] = b.u16[2] + b.u16[3];
+ c.u16[6] = b.u16[4] + b.u16[5];
+ c.u16[7] = b.u16[6] + b.u16[7];
+
+ c.u16[8] = a.u16[8] + a.u16[9];
+ c.u16[9] = a.u16[10] + a.u16[11];
+ c.u16[10] = a.u16[12] + a.u16[13];
+ c.u16[11] = a.u16[14] + a.u16[15];
+ c.u16[12] = b.u16[8] + b.u16[9];
+ c.u16[13] = b.u16[10] + b.u16[11];
+ c.u16[14] = b.u16[12] + b.u16[13];
+ c.u16[15] = b.u16[14] + b.u16[15];
+
+ return c;
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd16uint16 candidateValues,
+ const simd16uint16 candidateIndices,
+ const simd16uint16 currentValues,
+ const simd16uint16 currentIndices,
+ simd16uint16& minValues,
+ simd16uint16& minIndices,
+ simd16uint16& maxValues,
+ simd16uint16& maxIndices) {
+ for (size_t i = 0; i < 16; i++) {
+ bool flag = (candidateValues.u16[i] < currentValues.u16[i]);
+ minValues.u16[i] = flag ? candidateValues.u16[i] : currentValues.u16[i];
+ minIndices.u16[i] =
+ flag ? candidateIndices.u16[i] : currentIndices.u16[i];
+ maxValues.u16[i] =
+ !flag ? candidateValues.u16[i] : currentValues.u16[i];
+ maxIndices.u16[i] =
+ !flag ? candidateIndices.u16[i] : currentIndices.u16[i];
+ }
+}
+
+// vector of 32 unsigned 8-bit integers
+struct simd32uint8 : simd256bit {
+ simd32uint8() {}
+
+ explicit simd32uint8(int x) {
+ set1(x);
+ }
+
+ explicit simd32uint8(uint8_t x) {
+ set1(x);
+ }
+ template <
+ uint8_t _0,
+ uint8_t _1,
+ uint8_t _2,
+ uint8_t _3,
+ uint8_t _4,
+ uint8_t _5,
+ uint8_t _6,
+ uint8_t _7,
+ uint8_t _8,
+ uint8_t _9,
+ uint8_t _10,
+ uint8_t _11,
+ uint8_t _12,
+ uint8_t _13,
+ uint8_t _14,
+ uint8_t _15,
+ uint8_t _16,
+ uint8_t _17,
+ uint8_t _18,
+ uint8_t _19,
+ uint8_t _20,
+ uint8_t _21,
+ uint8_t _22,
+ uint8_t _23,
+ uint8_t _24,
+ uint8_t _25,
+ uint8_t _26,
+ uint8_t _27,
+ uint8_t _28,
+ uint8_t _29,
+ uint8_t _30,
+ uint8_t _31>
+ static simd32uint8 create() {
+ simd32uint8 ret;
+ ret.u8[0] = _0;
+ ret.u8[1] = _1;
+ ret.u8[2] = _2;
+ ret.u8[3] = _3;
+ ret.u8[4] = _4;
+ ret.u8[5] = _5;
+ ret.u8[6] = _6;
+ ret.u8[7] = _7;
+ ret.u8[8] = _8;
+ ret.u8[9] = _9;
+ ret.u8[10] = _10;
+ ret.u8[11] = _11;
+ ret.u8[12] = _12;
+ ret.u8[13] = _13;
+ ret.u8[14] = _14;
+ ret.u8[15] = _15;
+ ret.u8[16] = _16;
+ ret.u8[17] = _17;
+ ret.u8[18] = _18;
+ ret.u8[19] = _19;
+ ret.u8[20] = _20;
+ ret.u8[21] = _21;
+ ret.u8[22] = _22;
+ ret.u8[23] = _23;
+ ret.u8[24] = _24;
+ ret.u8[25] = _25;
+ ret.u8[26] = _26;
+ ret.u8[27] = _27;
+ ret.u8[28] = _28;
+ ret.u8[29] = _29;
+ ret.u8[30] = _30;
+ ret.u8[31] = _31;
+ return ret;
+ }
+
+ explicit simd32uint8(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd32uint8(const uint8_t* x) : simd256bit((const void*)x) {}
+
+ std::string elements_to_string(const char* fmt) const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 32; i++) {
+ ptr += sprintf(ptr, fmt, u8[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%02x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%3d,");
+ }
+
+ void set1(uint8_t x) {
+ for (int j = 0; j < 32; j++) {
+ u8[j] = x;
+ }
+ }
+
+ template <typename F>
+ static simd32uint8 binary_func(
+ const simd32uint8& a,
+ const simd32uint8& b,
+ F&& f) {
+ simd32uint8 c;
+ for (int j = 0; j < 32; j++) {
+ c.u8[j] = f(a.u8[j], b.u8[j]);
+ }
+ return c;
+ }
+
+ simd32uint8 operator&(const simd256bit& other) const {
+ return binary_func(*this, simd32uint8(other), [](uint8_t a, uint8_t b) {
+ return a & b;
+ });
+ }
+
+ simd32uint8 operator+(const simd32uint8& other) const {
+ return binary_func(
+ *this, other, [](uint8_t a, uint8_t b) { return a + b; });
+ }
+
+ // The very important operation that everything relies on
+ simd32uint8 lookup_2_lanes(const simd32uint8& idx) const {
+ simd32uint8 c;
+ // The original for loop:
+ // for (int j = 0; j < 32; j++) {
+ // if (idx.u8[j] & 0x80) {
+ // c.u8[j] = 0;
+ // } else {
+ // uint8_t i = idx.u8[j] & 15;
+ // if (j < 16) {
+ // c.u8[j] = u8[i];
+ // } else {
+ // c.u8[j] = u8[16 + i];
+ // }
+ // }
+
+ // The following function was re-written for Power 10
+ // The loop was unrolled to remove the if (j < 16) statement by doing
+ // the j and j + 16 iterations in parallel. The additional unrolling
+ // for j + 1 and j + 17, reduces the execution time on Power 10 by
+ // about 50% as the instruction scheduling allows on average 2X more
+ // instructions to be issued per cycle.
+
+ for (int j = 0; j < 16; j = j + 2) {
+ // j < 16, unrolled to depth of 2
+ if (idx.u8[j] & 0x80) {
+ c.u8[j] = 0;
+ } else {
+ uint8_t i = idx.u8[j] & 15;
+ c.u8[j] = u8[i];
+ }
+
+ if (idx.u8[j + 1] & 0x80) {
+ c.u8[j + 1] = 0;
+ } else {
+ uint8_t i = idx.u8[j + 1] & 15;
+ c.u8[j + 1] = u8[i];
+ }
+
+ // j >= 16, unrolled to depth of 2
+ if (idx.u8[j + 16] & 0x80) {
+ c.u8[j + 16] = 0;
+ } else {
+ uint8_t i = idx.u8[j + 16] & 15;
+ c.u8[j + 16] = u8[i + 16];
+ }
+
+ if (idx.u8[j + 17] & 0x80) {
+ c.u8[j + 17] = 0;
+ } else {
+ uint8_t i = idx.u8[j + 17] & 15;
+ c.u8[j + 17] = u8[i + 16];
+ }
+ }
+ return c;
+ }
+
+ // extract + 0-extend lane
+ // this operation is slow (3 cycles)
+
+ simd32uint8 operator+=(const simd32uint8& other) {
+ *this = *this + other;
+ return *this;
+ }
+
+ // for debugging only
+ uint8_t operator[](int i) const {
+ return u8[i];
+ }
+};
+
+// convert with saturation
+// careful: this does not cross lanes, so the order is weird
+inline simd32uint8 uint16_to_uint8_saturate(
+ const simd16uint16& a,
+ const simd16uint16& b) {
+ simd32uint8 c;
+
+ auto saturate_16_to_8 = [](uint16_t x) { return x >= 256 ? 0xff : x; };
+
+ for (int i = 0; i < 8; i++) {
+ c.u8[i] = saturate_16_to_8(a.u16[i]);
+ c.u8[8 + i] = saturate_16_to_8(b.u16[i]);
+ c.u8[16 + i] = saturate_16_to_8(a.u16[8 + i]);
+ c.u8[24 + i] = saturate_16_to_8(b.u16[8 + i]);
+ }
+ return c;
+}
+
+/// get most significant bit of each byte
+inline uint32_t get_MSBs(const simd32uint8& a) {
+ uint32_t res = 0;
+ for (int i = 0; i < 32; i++) {
+ if (a.u8[i] & 0x80) {
+ res |= 1 << i;
+ }
+ }
+ return res;
+}
+
+/// use MSB of each byte of mask to select a byte between a and b
+inline simd32uint8 blendv(
+ const simd32uint8& a,
+ const simd32uint8& b,
+ const simd32uint8& mask) {
+ simd32uint8 c;
+ for (int i = 0; i < 32; i++) {
+ if (mask.u8[i] & 0x80) {
+ c.u8[i] = b.u8[i];
+ } else {
+ c.u8[i] = a.u8[i];
+ }
+ }
+ return c;
+}
+
+/// vector of 8 unsigned 32-bit integers
+struct simd8uint32 : simd256bit {
+ simd8uint32() {}
+
+ explicit simd8uint32(uint32_t x) {
+ set1(x);
+ }
+
+ explicit simd8uint32(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd8uint32(const uint32_t* x) : simd256bit((const void*)x) {}
+
+ explicit simd8uint32(
+ uint32_t u0,
+ uint32_t u1,
+ uint32_t u2,
+ uint32_t u3,
+ uint32_t u4,
+ uint32_t u5,
+ uint32_t u6,
+ uint32_t u7) {
+ u32[0] = u0;
+ u32[1] = u1;
+ u32[2] = u2;
+ u32[3] = u3;
+ u32[4] = u4;
+ u32[5] = u5;
+ u32[6] = u6;
+ u32[7] = u7;
+ }
+
+ simd8uint32 operator+(simd8uint32 other) const {
+ simd8uint32 result;
+ for (int i = 0; i < 8; i++) {
+ result.u32[i] = u32[i] + other.u32[i];
+ }
+ return result;
+ }
+
+ simd8uint32 operator-(simd8uint32 other) const {
+ simd8uint32 result;
+ for (int i = 0; i < 8; i++) {
+ result.u32[i] = u32[i] - other.u32[i];
+ }
+ return result;
+ }
+
+ simd8uint32& operator+=(const simd8uint32& other) {
+ for (int i = 0; i < 8; i++) {
+ u32[i] += other.u32[i];
+ }
+ return *this;
+ }
+
+ bool operator==(simd8uint32 other) const {
+ for (size_t i = 0; i < 8; i++) {
+ if (u32[i] != other.u32[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ bool operator!=(simd8uint32 other) const {
+ return !(*this == other);
+ }
+
+ std::string elements_to_string(const char* fmt) const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 8; i++) {
+ ptr += sprintf(ptr, fmt, u32[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+
+ std::string hex() const {
+ return elements_to_string("%08x,");
+ }
+
+ std::string dec() const {
+ return elements_to_string("%10d,");
+ }
+
+ void set1(uint32_t x) {
+ for (int i = 0; i < 8; i++) {
+ u32[i] = x;
+ }
+ }
+
+ simd8uint32 unzip() const {
+ const uint32_t ret[] = {
+ u32[0], u32[2], u32[4], u32[6], u32[1], u32[3], u32[5], u32[7]};
+ return simd8uint32{ret};
+ }
+};
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8uint32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8uint32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8uint32& minValues,
+ simd8uint32& minIndices,
+ simd8uint32& maxValues,
+ simd8uint32& maxIndices) {
+ for (size_t i = 0; i < 8; i++) {
+ bool flag = (candidateValues.u32[i] < currentValues.u32[i]);
+ minValues.u32[i] = flag ? candidateValues.u32[i] : currentValues.u32[i];
+ minIndices.u32[i] =
+ flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ maxValues.u32[i] =
+ !flag ? candidateValues.u32[i] : currentValues.u32[i];
+ maxIndices.u32[i] =
+ !flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ }
+}
+
+struct simd8float32 : simd256bit {
+ simd8float32() {}
+
+ explicit simd8float32(const simd256bit& x) : simd256bit(x) {}
+
+ explicit simd8float32(float x) {
+ set1(x);
+ }
+
+ explicit simd8float32(const float* x) {
+ loadu((void*)x);
+ }
+
+ void set1(float x) {
+ for (int i = 0; i < 8; i++) {
+ f32[i] = x;
+ }
+ }
+
+ explicit simd8float32(
+ float f0,
+ float f1,
+ float f2,
+ float f3,
+ float f4,
+ float f5,
+ float f6,
+ float f7) {
+ f32[0] = f0;
+ f32[1] = f1;
+ f32[2] = f2;
+ f32[3] = f3;
+ f32[4] = f4;
+ f32[5] = f5;
+ f32[6] = f6;
+ f32[7] = f7;
+ }
+
+ template <typename F>
+ static simd8float32 binary_func(
+ const simd8float32& a,
+ const simd8float32& b,
+ F&& f) {
+ simd8float32 c;
+ for (int j = 0; j < 8; j++) {
+ c.f32[j] = f(a.f32[j], b.f32[j]);
+ }
+ return c;
+ }
+
+ simd8float32 operator*(const simd8float32& other) const {
+ return binary_func(
+ *this, other, [](float a, float b) { return a * b; });
+ }
+
+ simd8float32 operator+(const simd8float32& other) const {
+ return binary_func(
+ *this, other, [](float a, float b) { return a + b; });
+ }
+
+ simd8float32 operator-(const simd8float32& other) const {
+ return binary_func(
+ *this, other, [](float a, float b) { return a - b; });
+ }
+
+ simd8float32& operator+=(const simd8float32& other) {
+ for (size_t i = 0; i < 8; i++) {
+ f32[i] += other.f32[i];
+ }
+
+ return *this;
+ }
+
+ bool operator==(simd8float32 other) const {
+ for (size_t i = 0; i < 8; i++) {
+ if (f32[i] != other.f32[i]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ bool operator!=(simd8float32 other) const {
+ return !(*this == other);
+ }
+
+ std::string tostring() const {
+ char res[1000], *ptr = res;
+ for (int i = 0; i < 8; i++) {
+ ptr += sprintf(ptr, "%g,", f32[i]);
+ }
+ // strip last ,
+ ptr[-1] = 0;
+ return std::string(res);
+ }
+};
+
+// hadd does not cross lanes
+inline simd8float32 hadd(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+ c.f32[0] = a.f32[0] + a.f32[1];
+ c.f32[1] = a.f32[2] + a.f32[3];
+ c.f32[2] = b.f32[0] + b.f32[1];
+ c.f32[3] = b.f32[2] + b.f32[3];
+
+ c.f32[4] = a.f32[4] + a.f32[5];
+ c.f32[5] = a.f32[6] + a.f32[7];
+ c.f32[6] = b.f32[4] + b.f32[5];
+ c.f32[7] = b.f32[6] + b.f32[7];
+
+ return c;
+}
+
+inline simd8float32 unpacklo(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+ c.f32[0] = a.f32[0];
+ c.f32[1] = b.f32[0];
+ c.f32[2] = a.f32[1];
+ c.f32[3] = b.f32[1];
+
+ c.f32[4] = a.f32[4];
+ c.f32[5] = b.f32[4];
+ c.f32[6] = a.f32[5];
+ c.f32[7] = b.f32[5];
+
+ return c;
+}
+
+inline simd8float32 unpackhi(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+ c.f32[0] = a.f32[2];
+ c.f32[1] = b.f32[2];
+ c.f32[2] = a.f32[3];
+ c.f32[3] = b.f32[3];
+
+ c.f32[4] = a.f32[6];
+ c.f32[5] = b.f32[6];
+ c.f32[6] = a.f32[7];
+ c.f32[7] = b.f32[7];
+
+ return c;
+}
+
+// compute a * b + c
+inline simd8float32 fmadd(
+ const simd8float32& a,
+ const simd8float32& b,
+ const simd8float32& c) {
+ simd8float32 res;
+ for (int i = 0; i < 8; i++) {
+ res.f32[i] = a.f32[i] * b.f32[i] + c.f32[i];
+ }
+ return res;
+}
+
+namespace {
+
+// get even float32's of a and b, interleaved
+simd8float32 geteven(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[0];
+ c.f32[1] = a.f32[2];
+ c.f32[2] = b.f32[0];
+ c.f32[3] = b.f32[2];
+
+ c.f32[4] = a.f32[4];
+ c.f32[5] = a.f32[6];
+ c.f32[6] = b.f32[4];
+ c.f32[7] = b.f32[6];
+
+ return c;
+}
+
+// get odd float32's of a and b, interleaved
+simd8float32 getodd(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[1];
+ c.f32[1] = a.f32[3];
+ c.f32[2] = b.f32[1];
+ c.f32[3] = b.f32[3];
+
+ c.f32[4] = a.f32[5];
+ c.f32[5] = a.f32[7];
+ c.f32[6] = b.f32[5];
+ c.f32[7] = b.f32[7];
+
+ return c;
+}
+
+// 3 cycles
+// if the lanes are a = [a0 a1] and b = [b0 b1], return [a0 b0]
+simd8float32 getlow128(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[0];
+ c.f32[1] = a.f32[1];
+ c.f32[2] = a.f32[2];
+ c.f32[3] = a.f32[3];
+
+ c.f32[4] = b.f32[0];
+ c.f32[5] = b.f32[1];
+ c.f32[6] = b.f32[2];
+ c.f32[7] = b.f32[3];
+
+ return c;
+}
+
+simd8float32 gethigh128(const simd8float32& a, const simd8float32& b) {
+ simd8float32 c;
+
+ c.f32[0] = a.f32[4];
+ c.f32[1] = a.f32[5];
+ c.f32[2] = a.f32[6];
+ c.f32[3] = a.f32[7];
+
+ c.f32[4] = b.f32[4];
+ c.f32[5] = b.f32[5];
+ c.f32[6] = b.f32[6];
+ c.f32[7] = b.f32[7];
+
+ return c;
+}
+
+// The following primitive is a vectorized version of the following code
+// snippet:
+// float lowestValue = HUGE_VAL;
+// uint lowestIndex = 0;
+// for (size_t i = 0; i < n; i++) {
+// if (values[i] < lowestValue) {
+// lowestValue = values[i];
+// lowestIndex = i;
+// }
+// }
+// Vectorized version can be implemented via two operations: cmp and blend
+// with something like this:
+// lowestValues = [HUGE_VAL; 8];
+// lowestIndices = {0, 1, 2, 3, 4, 5, 6, 7};
+// for (size_t i = 0; i < n; i += 8) {
+// auto comparison = cmp(values + i, lowestValues);
+// lowestValues = blend(
+// comparison,
+// values + i,
+// lowestValues);
+// lowestIndices = blend(
+// comparison,
+// i + {0, 1, 2, 3, 4, 5, 6, 7},
+// lowestIndices);
+// lowestIndices += {8, 8, 8, 8, 8, 8, 8, 8};
+// }
+// The problem is that blend primitive needs very different instruction
+// order for AVX and ARM.
+// So, let's introduce a combination of these two in order to avoid
+// confusion for ppl who write in low-level SIMD instructions. Additionally,
+// these two ops (cmp and blend) are very often used together.
+inline void cmplt_and_blend_inplace(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ simd8float32& lowestValues,
+ simd8uint32& lowestIndices) {
+ for (size_t j = 0; j < 8; j++) {
+ bool comparison = (candidateValues.f32[j] < lowestValues.f32[j]);
+ if (comparison) {
+ lowestValues.f32[j] = candidateValues.f32[j];
+ lowestIndices.u32[j] = candidateIndices.u32[j];
+ }
+ }
+}
+
+// Vectorized version of the following code:
+// for (size_t i = 0; i < n; i++) {
+// bool flag = (candidateValues[i] < currentValues[i]);
+// minValues[i] = flag ? candidateValues[i] : currentValues[i];
+// minIndices[i] = flag ? candidateIndices[i] : currentIndices[i];
+// maxValues[i] = !flag ? candidateValues[i] : currentValues[i];
+// maxIndices[i] = !flag ? candidateIndices[i] : currentIndices[i];
+// }
+// Max indices evaluation is inaccurate in case of equal values (the index of
+// the last equal value is saved instead of the first one), but this behavior
+// saves instructions.
+inline void cmplt_min_max_fast(
+ const simd8float32 candidateValues,
+ const simd8uint32 candidateIndices,
+ const simd8float32 currentValues,
+ const simd8uint32 currentIndices,
+ simd8float32& minValues,
+ simd8uint32& minIndices,
+ simd8float32& maxValues,
+ simd8uint32& maxIndices) {
+ for (size_t i = 0; i < 8; i++) {
+ bool flag = (candidateValues.f32[i] < currentValues.f32[i]);
+ minValues.f32[i] = flag ? candidateValues.f32[i] : currentValues.f32[i];
+ minIndices.u32[i] =
+ flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ maxValues.f32[i] =
+ !flag ? candidateValues.f32[i] : currentValues.f32[i];
+ maxIndices.u32[i] =
+ !flag ? candidateIndices.u32[i] : currentIndices.u32[i];
+ }
+}
+
+} // namespace
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/sorting.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/sorting.cpp
new file mode 100644
index 0000000..e3bf495
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/sorting.cpp
@@ -0,0 +1,827 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/utils/sorting.h>
+
+#include <omp.h>
+#include <algorithm>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/utils.h>
+
+namespace faiss {
+
+/*****************************************************************************
+ * Argsort
+ ****************************************************************************/
+
+namespace {
+struct ArgsortComparator {
+ const float* vals;
+ bool operator()(const size_t a, const size_t b) const {
+ return vals[a] < vals[b];
+ }
+};
+
+struct SegmentS {
+ size_t i0; // begin pointer in the permutation array
+ size_t i1; // end
+ size_t len() const {
+ return i1 - i0;
+ }
+};
+
+// see https://en.wikipedia.org/wiki/Merge_algorithm#Parallel_merge
+// extended to > 1 merge thread
+
+// merges 2 ranges that should be consecutive on the source into
+// the union of the two on the destination
+template <typename T>
+void parallel_merge(
+ const T* src,
+ T* dst,
+ SegmentS& s1,
+ SegmentS& s2,
+ int nt,
+ const ArgsortComparator& comp) {
+ if (s2.len() > s1.len()) { // make sure that s1 larger than s2
+ std::swap(s1, s2);
+ }
+
+ // compute sub-ranges for each thread
+ std::vector<SegmentS> s1s(nt), s2s(nt), sws(nt);
+ s2s[0].i0 = s2.i0;
+ s2s[nt - 1].i1 = s2.i1;
+
+ // not sure parallel actually helps here
+#pragma omp parallel for num_threads(nt)
+ for (int t = 0; t < nt; t++) {
+ s1s[t].i0 = s1.i0 + s1.len() * t / nt;
+ s1s[t].i1 = s1.i0 + s1.len() * (t + 1) / nt;
+
+ if (t + 1 < nt) {
+ T pivot = src[s1s[t].i1];
+ size_t i0 = s2.i0, i1 = s2.i1;
+ while (i0 + 1 < i1) {
+ size_t imed = (i1 + i0) / 2;
+ if (comp(pivot, src[imed])) {
+ i1 = imed;
+ } else {
+ i0 = imed;
+ }
+ }
+ s2s[t].i1 = s2s[t + 1].i0 = i1;
+ }
+ }
+ s1.i0 = std::min(s1.i0, s2.i0);
+ s1.i1 = std::max(s1.i1, s2.i1);
+ s2 = s1;
+ sws[0].i0 = s1.i0;
+ for (int t = 0; t < nt; t++) {
+ sws[t].i1 = sws[t].i0 + s1s[t].len() + s2s[t].len();
+ if (t + 1 < nt) {
+ sws[t + 1].i0 = sws[t].i1;
+ }
+ }
+ assert(sws[nt - 1].i1 == s1.i1);
+
+ // do the actual merging
+#pragma omp parallel for num_threads(nt)
+ for (int t = 0; t < nt; t++) {
+ SegmentS sw = sws[t];
+ SegmentS s1t = s1s[t];
+ SegmentS s2t = s2s[t];
+ if (s1t.i0 < s1t.i1 && s2t.i0 < s2t.i1) {
+ for (;;) {
+ // assert (sw.len() == s1t.len() + s2t.len());
+ if (comp(src[s1t.i0], src[s2t.i0])) {
+ dst[sw.i0++] = src[s1t.i0++];
+ if (s1t.i0 == s1t.i1) {
+ break;
+ }
+ } else {
+ dst[sw.i0++] = src[s2t.i0++];
+ if (s2t.i0 == s2t.i1) {
+ break;
+ }
+ }
+ }
+ }
+ if (s1t.len() > 0) {
+ assert(s1t.len() == sw.len());
+ memcpy(dst + sw.i0, src + s1t.i0, s1t.len() * sizeof(dst[0]));
+ } else if (s2t.len() > 0) {
+ assert(s2t.len() == sw.len());
+ memcpy(dst + sw.i0, src + s2t.i0, s2t.len() * sizeof(dst[0]));
+ }
+ }
+}
+
+} // namespace
+
+void fvec_argsort(size_t n, const float* vals, size_t* perm) {
+ for (size_t i = 0; i < n; i++) {
+ perm[i] = i;
+ }
+ ArgsortComparator comp = {vals};
+ std::sort(perm, perm + n, comp);
+}
+
+void fvec_argsort_parallel(size_t n, const float* vals, size_t* perm) {
+ size_t* perm2 = new size_t[n];
+ // 2 result tables, during merging, flip between them
+ size_t *permB = perm2, *permA = perm;
+
+ int nt = omp_get_max_threads();
+ { // prepare correct permutation so that the result ends in perm
+ // at final iteration
+ int nseg = nt;
+ while (nseg > 1) {
+ nseg = (nseg + 1) / 2;
+ std::swap(permA, permB);
+ }
+ }
+
+#pragma omp parallel
+ for (size_t i = 0; i < n; i++) {
+ permA[i] = i;
+ }
+
+ ArgsortComparator comp = {vals};
+
+ std::vector<SegmentS> segs(nt);
+
+ // independent sorts
+#pragma omp parallel for
+ for (int t = 0; t < nt; t++) {
+ size_t i0 = t * n / nt;
+ size_t i1 = (t + 1) * n / nt;
+ SegmentS seg = {i0, i1};
+ std::sort(permA + seg.i0, permA + seg.i1, comp);
+ segs[t] = seg;
+ }
+ int prev_nested = omp_get_nested();
+ omp_set_nested(1);
+
+ int nseg = nt;
+ while (nseg > 1) {
+ int nseg1 = (nseg + 1) / 2;
+ int sub_nt = nseg % 2 == 0 ? nt : nt - 1;
+ int sub_nseg1 = nseg / 2;
+
+#pragma omp parallel for num_threads(nseg1)
+ for (int s = 0; s < nseg; s += 2) {
+ if (s + 1 == nseg) { // otherwise isolated segment
+ memcpy(permB + segs[s].i0,
+ permA + segs[s].i0,
+ segs[s].len() * sizeof(size_t));
+ } else {
+ int t0 = s * sub_nt / sub_nseg1;
+ int t1 = (s + 1) * sub_nt / sub_nseg1;
+ printf("merge %d %d, %d threads\n", s, s + 1, t1 - t0);
+ parallel_merge(
+ permA, permB, segs[s], segs[s + 1], t1 - t0, comp);
+ }
+ }
+ for (int s = 0; s < nseg; s += 2) {
+ segs[s / 2] = segs[s];
+ }
+ nseg = nseg1;
+ std::swap(permA, permB);
+ }
+ assert(permA == perm);
+ omp_set_nested(prev_nested);
+ delete[] perm2;
+}
+
+/*****************************************************************************
+ * Bucket sort
+ ****************************************************************************/
+
+// extern symbol in the .h
+int bucket_sort_verbose = 0;
+
+namespace {
+
+void bucket_sort_ref(
+ size_t nval,
+ const uint64_t* vals,
+ uint64_t vmax,
+ int64_t* lims,
+ int64_t* perm) {
+ double t0 = getmillisecs();
+ memset(lims, 0, sizeof(*lims) * (vmax + 1));
+ for (size_t i = 0; i < nval; i++) {
+ FAISS_THROW_IF_NOT(vals[i] < vmax);
+ lims[vals[i] + 1]++;
+ }
+ double t1 = getmillisecs();
+ // compute cumulative sum
+ for (size_t i = 0; i < vmax; i++) {
+ lims[i + 1] += lims[i];
+ }
+ FAISS_THROW_IF_NOT(lims[vmax] == nval);
+ double t2 = getmillisecs();
+ // populate buckets
+ for (size_t i = 0; i < nval; i++) {
+ perm[lims[vals[i]]++] = i;
+ }
+ double t3 = getmillisecs();
+ // reset pointers
+ for (size_t i = vmax; i > 0; i--) {
+ lims[i] = lims[i - 1];
+ }
+ lims[0] = 0;
+ double t4 = getmillisecs();
+ if (bucket_sort_verbose) {
+ printf("times %.3f %.3f %.3f %.3f\n",
+ t1 - t0,
+ t2 - t1,
+ t3 - t2,
+ t4 - t3);
+ }
+}
+
+void bucket_sort_parallel(
+ size_t nval,
+ const uint64_t* vals,
+ uint64_t vmax,
+ int64_t* lims,
+ int64_t* perm,
+ int nt_in) {
+ memset(lims, 0, sizeof(*lims) * (vmax + 1));
+#pragma omp parallel num_threads(nt_in)
+ {
+ int nt = omp_get_num_threads(); // might be different from nt_in
+ int rank = omp_get_thread_num();
+ std::vector<int64_t> local_lims(vmax + 1);
+
+ // range of indices handled by this thread
+ size_t i0 = nval * rank / nt;
+ size_t i1 = nval * (rank + 1) / nt;
+
+ // build histogram in local lims
+ double t0 = getmillisecs();
+ for (size_t i = i0; i < i1; i++) {
+ local_lims[vals[i]]++;
+ }
+#pragma omp critical
+ { // accumulate histograms (not shifted indices to prepare cumsum)
+ for (size_t i = 0; i < vmax; i++) {
+ lims[i + 1] += local_lims[i];
+ }
+ }
+#pragma omp barrier
+
+ double t1 = getmillisecs();
+#pragma omp master
+ {
+ // compute cumulative sum
+ for (size_t i = 0; i < vmax; i++) {
+ lims[i + 1] += lims[i];
+ }
+ FAISS_THROW_IF_NOT(lims[vmax] == nval);
+ }
+#pragma omp barrier
+
+#pragma omp critical
+ { // current thread grabs a slot in the buckets
+ for (size_t i = 0; i < vmax; i++) {
+ size_t nv = local_lims[i];
+ local_lims[i] = lims[i]; // where we should start writing
+ lims[i] += nv;
+ }
+ }
+
+ double t2 = getmillisecs();
+#pragma omp barrier
+ { // populate buckets, this is the slowest operation
+ for (size_t i = i0; i < i1; i++) {
+ perm[local_lims[vals[i]]++] = i;
+ }
+ }
+#pragma omp barrier
+ double t3 = getmillisecs();
+
+#pragma omp master
+ { // shift back lims
+ for (size_t i = vmax; i > 0; i--) {
+ lims[i] = lims[i - 1];
+ }
+ lims[0] = 0;
+ double t4 = getmillisecs();
+ if (bucket_sort_verbose) {
+ printf("times %.3f %.3f %.3f %.3f\n",
+ t1 - t0,
+ t2 - t1,
+ t3 - t2,
+ t4 - t3);
+ }
+ }
+ }
+}
+
+/***********************************************
+ * in-place bucket sort
+ */
+
+template <class TI>
+void bucket_sort_inplace_ref(
+ size_t nrow,
+ size_t ncol,
+ TI* vals,
+ TI nbucket,
+ int64_t* lims) {
+ double t0 = getmillisecs();
+ size_t nval = nrow * ncol;
+ FAISS_THROW_IF_NOT(
+ nbucket < nval); // unclear what would happen in this case...
+
+ memset(lims, 0, sizeof(*lims) * (nbucket + 1));
+ for (size_t i = 0; i < nval; i++) {
+ FAISS_THROW_IF_NOT(vals[i] < nbucket);
+ lims[vals[i] + 1]++;
+ }
+ double t1 = getmillisecs();
+ // compute cumulative sum
+ for (size_t i = 0; i < nbucket; i++) {
+ lims[i + 1] += lims[i];
+ }
+ FAISS_THROW_IF_NOT(lims[nbucket] == nval);
+ double t2 = getmillisecs();
+
+ std::vector<size_t> ptrs(nbucket);
+ for (size_t i = 0; i < nbucket; i++) {
+ ptrs[i] = lims[i];
+ }
+
+ // find loops in the permutation and follow them
+ TI row = -1;
+ TI init_bucket_no = 0, bucket_no = 0;
+ for (;;) {
+ size_t idx = ptrs[bucket_no];
+ if (row >= 0) {
+ ptrs[bucket_no] += 1;
+ }
+ assert(idx < lims[bucket_no + 1]);
+ TI next_bucket_no = vals[idx];
+ vals[idx] = row;
+ if (next_bucket_no != -1) {
+ row = idx / ncol;
+ bucket_no = next_bucket_no;
+ } else {
+ // start new loop
+ for (; init_bucket_no < nbucket; init_bucket_no++) {
+ if (ptrs[init_bucket_no] < lims[init_bucket_no + 1]) {
+ break;
+ }
+ }
+ if (init_bucket_no == nbucket) { // we're done
+ break;
+ }
+ bucket_no = init_bucket_no;
+ row = -1;
+ }
+ }
+
+ for (size_t i = 0; i < nbucket; i++) {
+ assert(ptrs[i] == lims[i + 1]);
+ }
+ double t3 = getmillisecs();
+ if (bucket_sort_verbose) {
+ printf("times %.3f %.3f %.3f\n", t1 - t0, t2 - t1, t3 - t2);
+ }
+}
+
+// collects row numbers to write into buckets
+template <class TI>
+struct ToWrite {
+ TI nbucket;
+ std::vector<TI> buckets;
+ std::vector<TI> rows;
+ std::vector<size_t> lims;
+
+ explicit ToWrite(TI nbucket) : nbucket(nbucket) {
+ lims.resize(nbucket + 1);
+ }
+
+ /// add one element (row) to write in bucket b
+ void add(TI row, TI b) {
+ assert(b >= 0 && b < nbucket);
+ rows.push_back(row);
+ buckets.push_back(b);
+ }
+
+ void bucket_sort() {
+ FAISS_THROW_IF_NOT(buckets.size() == rows.size());
+ lims.resize(nbucket + 1);
+ memset(lims.data(), 0, sizeof(lims[0]) * (nbucket + 1));
+
+ for (size_t i = 0; i < buckets.size(); i++) {
+ assert(buckets[i] >= 0 && buckets[i] < nbucket);
+ lims[buckets[i] + 1]++;
+ }
+ // compute cumulative sum
+ for (size_t i = 0; i < nbucket; i++) {
+ lims[i + 1] += lims[i];
+ }
+ FAISS_THROW_IF_NOT(lims[nbucket] == buckets.size());
+
+ // could also do a circular perm...
+ std::vector<TI> new_rows(rows.size());
+ std::vector<size_t> ptrs = lims;
+ for (size_t i = 0; i < buckets.size(); i++) {
+ TI b = buckets[i];
+ assert(ptrs[b] < lims[b + 1]);
+ new_rows[ptrs[b]++] = rows[i];
+ }
+ buckets.resize(0);
+ std::swap(rows, new_rows);
+ }
+
+ void swap(ToWrite& other) {
+ assert(nbucket == other.nbucket);
+ buckets.swap(other.buckets);
+ rows.swap(other.rows);
+ lims.swap(other.lims);
+ }
+};
+
+template <class TI>
+void bucket_sort_inplace_parallel(
+ size_t nrow,
+ size_t ncol,
+ TI* vals,
+ TI nbucket,
+ int64_t* lims,
+ int nt_in) {
+ int verbose = bucket_sort_verbose;
+ memset(lims, 0, sizeof(*lims) * (nbucket + 1));
+ std::vector<ToWrite<TI>> all_to_write;
+ size_t nval = nrow * ncol;
+ FAISS_THROW_IF_NOT(
+ nbucket < nval); // unclear what would happen in this case...
+
+ // try to keep size of all_to_write < 5GiB
+ // but we need at least one element per bucket
+ size_t init_to_write = std::max(
+ size_t(nbucket),
+ std::min(nval / 10, ((size_t)5 << 30) / (sizeof(TI) * 3 * nt_in)));
+ if (verbose > 0) {
+ printf("init_to_write=%zd\n", init_to_write);
+ }
+
+ std::vector<size_t> ptrs(nbucket); // ptrs is shared across all threads
+ std::vector<char> did_wrap(
+ nbucket); // DON'T use std::vector<bool> that cannot be accessed
+ // safely from multiple threads!!!
+
+#pragma omp parallel num_threads(nt_in)
+ {
+ int nt = omp_get_num_threads(); // might be different from nt_in (?)
+ int rank = omp_get_thread_num();
+ std::vector<int64_t> local_lims(nbucket + 1);
+
+ // range of indices handled by this thread
+ size_t i0 = nval * rank / nt;
+ size_t i1 = nval * (rank + 1) / nt;
+
+ // build histogram in local lims
+ for (size_t i = i0; i < i1; i++) {
+ local_lims[vals[i]]++;
+ }
+#pragma omp critical
+ { // accumulate histograms (not shifted indices to prepare cumsum)
+ for (size_t i = 0; i < nbucket; i++) {
+ lims[i + 1] += local_lims[i];
+ }
+ all_to_write.push_back(ToWrite<TI>(nbucket));
+ }
+
+#pragma omp barrier
+ // this thread's things to write
+ ToWrite<TI>& to_write = all_to_write[rank];
+
+#pragma omp master
+ {
+ // compute cumulative sum
+ for (size_t i = 0; i < nbucket; i++) {
+ lims[i + 1] += lims[i];
+ }
+ FAISS_THROW_IF_NOT(lims[nbucket] == nval);
+ // at this point lims is final (read only!)
+
+ memcpy(ptrs.data(), lims, sizeof(lims[0]) * nbucket);
+
+ // initial values to write (we write -1s to get the process running)
+ // make sure at least one element per bucket
+ size_t written = 0;
+ for (TI b = 0; b < nbucket; b++) {
+ size_t l0 = lims[b], l1 = lims[b + 1];
+ size_t target_to_write = l1 * init_to_write / nval;
+ do {
+ if (l0 == l1) {
+ break;
+ }
+ to_write.add(-1, b);
+ l0++;
+ written++;
+ } while (written < target_to_write);
+ }
+
+ to_write.bucket_sort();
+ }
+
+ // this thread writes only buckets b0:b1
+ size_t b0 = (rank * nbucket + nt - 1) / nt;
+ size_t b1 = ((rank + 1) * nbucket + nt - 1) / nt;
+
+ // in this loop, we write elements collected in the previous round
+ // and collect the elements that are overwritten for the next round
+ int round = 0;
+ for (;;) {
+#pragma omp barrier
+
+ size_t n_to_write = 0;
+ for (const ToWrite<TI>& to_write_2 : all_to_write) {
+ n_to_write += to_write_2.lims.back();
+ }
+
+#pragma omp master
+ {
+ if (verbose >= 1) {
+ printf("ROUND %d n_to_write=%zd\n", round, n_to_write);
+ }
+ if (verbose > 2) {
+ for (size_t b = 0; b < nbucket; b++) {
+ printf(" b=%zd [", b);
+ for (size_t i = lims[b]; i < lims[b + 1]; i++) {
+ printf(" %s%d",
+ ptrs[b] == i ? ">" : "",
+ int(vals[i]));
+ }
+ printf(" %s] %s\n",
+ ptrs[b] == lims[b + 1] ? ">" : "",
+ did_wrap[b] ? "w" : "");
+ }
+ printf("To write\n");
+ for (size_t b = 0; b < nbucket; b++) {
+ printf(" b=%zd ", b);
+ const char* sep = "[";
+ for (const ToWrite<TI>& to_write_2 : all_to_write) {
+ printf("%s", sep);
+ sep = " |";
+ size_t l0 = to_write_2.lims[b];
+ size_t l1 = to_write_2.lims[b + 1];
+ for (size_t i = l0; i < l1; i++) {
+ printf(" %d", int(to_write_2.rows[i]));
+ }
+ }
+ printf(" ]\n");
+ }
+ }
+ }
+ if (n_to_write == 0) {
+ break;
+ }
+ round++;
+
+#pragma omp barrier
+
+ ToWrite<TI> next_to_write(nbucket);
+
+ for (size_t b = b0; b < b1; b++) {
+ for (const ToWrite<TI>& to_write_2 : all_to_write) {
+ size_t l0 = to_write_2.lims[b];
+ size_t l1 = to_write_2.lims[b + 1];
+ for (size_t i = l0; i < l1; i++) {
+ TI row = to_write_2.rows[i];
+ size_t idx = ptrs[b];
+ if (verbose > 2) {
+ printf(" bucket %d (rank %d) idx %zd\n",
+ int(row),
+ rank,
+ idx);
+ }
+ if (idx < lims[b + 1]) {
+ ptrs[b]++;
+ } else {
+ // wrapping around
+ assert(!did_wrap[b]);
+ did_wrap[b] = true;
+ idx = lims[b];
+ ptrs[b] = idx + 1;
+ }
+
+ // check if we need to remember the overwritten number
+ if (vals[idx] >= 0) {
+ TI new_row = idx / ncol;
+ next_to_write.add(new_row, vals[idx]);
+ if (verbose > 2) {
+ printf(" new_row=%d\n", int(new_row));
+ }
+ } else {
+ assert(did_wrap[b]);
+ }
+
+ vals[idx] = row;
+ }
+ }
+ }
+ next_to_write.bucket_sort();
+#pragma omp barrier
+ all_to_write[rank].swap(next_to_write);
+ }
+ }
+}
+
+} // anonymous namespace
+
+void bucket_sort(
+ size_t nval,
+ const uint64_t* vals,
+ uint64_t vmax,
+ int64_t* lims,
+ int64_t* perm,
+ int nt) {
+ if (nt == 0) {
+ bucket_sort_ref(nval, vals, vmax, lims, perm);
+ } else {
+ bucket_sort_parallel(nval, vals, vmax, lims, perm, nt);
+ }
+}
+
+void matrix_bucket_sort_inplace(
+ size_t nrow,
+ size_t ncol,
+ int32_t* vals,
+ int32_t vmax,
+ int64_t* lims,
+ int nt) {
+ if (nt == 0) {
+ bucket_sort_inplace_ref(nrow, ncol, vals, vmax, lims);
+ } else {
+ bucket_sort_inplace_parallel(nrow, ncol, vals, vmax, lims, nt);
+ }
+}
+
+void matrix_bucket_sort_inplace(
+ size_t nrow,
+ size_t ncol,
+ int64_t* vals,
+ int64_t vmax,
+ int64_t* lims,
+ int nt) {
+ if (nt == 0) {
+ bucket_sort_inplace_ref(nrow, ncol, vals, vmax, lims);
+ } else {
+ bucket_sort_inplace_parallel(nrow, ncol, vals, vmax, lims, nt);
+ }
+}
+
+/** Hashtable implementation for int64 -> int64 with external storage
+ * implemented for speed and parallel processing.
+ */
+
+namespace {
+
+int log2_capacity_to_log2_nbucket(int log2_capacity) {
+ return log2_capacity < 12 ? 0
+ : log2_capacity < 20 ? log2_capacity - 12
+ : 10;
+}
+
+// https://bigprimes.org/
+int64_t bigprime = 8955327411143;
+
+inline int64_t hash_function(int64_t x) {
+ return (x * 1000003) % bigprime;
+}
+
+} // anonymous namespace
+
+void hashtable_int64_to_int64_init(int log2_capacity, int64_t* tab) {
+ size_t capacity = (size_t)1 << log2_capacity;
+#pragma omp parallel for
+ for (int64_t i = 0; i < capacity; i++) {
+ tab[2 * i] = -1;
+ tab[2 * i + 1] = -1;
+ }
+}
+
+void hashtable_int64_to_int64_add(
+ int log2_capacity,
+ int64_t* tab,
+ size_t n,
+ const int64_t* keys,
+ const int64_t* vals) {
+ size_t capacity = (size_t)1 << log2_capacity;
+ std::vector<int64_t> hk(n);
+ std::vector<uint64_t> bucket_no(n);
+ int64_t mask = capacity - 1;
+ int log2_nbucket = log2_capacity_to_log2_nbucket(log2_capacity);
+ size_t nbucket = (size_t)1 << log2_nbucket;
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++) {
+ hk[i] = hash_function(keys[i]) & mask;
+ bucket_no[i] = hk[i] >> (log2_capacity - log2_nbucket);
+ }
+
+ std::vector<int64_t> lims(nbucket + 1);
+ std::vector<int64_t> perm(n);
+ bucket_sort(
+ n,
+ bucket_no.data(),
+ nbucket,
+ lims.data(),
+ perm.data(),
+ omp_get_max_threads());
+
+ int num_errors = 0;
+#pragma omp parallel for reduction(+ : num_errors)
+ for (int64_t bucket = 0; bucket < nbucket; bucket++) {
+ size_t k0 = bucket << (log2_capacity - log2_nbucket);
+ size_t k1 = (bucket + 1) << (log2_capacity - log2_nbucket);
+
+ for (size_t i = lims[bucket]; i < lims[bucket + 1]; i++) {
+ int64_t j = perm[i];
+ assert(bucket_no[j] == bucket);
+ assert(hk[j] >= k0 && hk[j] < k1);
+ size_t slot = hk[j];
+ for (;;) {
+ if (tab[slot * 2] == -1) { // found!
+ tab[slot * 2] = keys[j];
+ tab[slot * 2 + 1] = vals[j];
+ break;
+ } else if (tab[slot * 2] == keys[j]) { // overwrite!
+ tab[slot * 2 + 1] = vals[j];
+ break;
+ }
+ slot++;
+ if (slot == k1) {
+ slot = k0;
+ }
+ if (slot == hk[j]) { // no free slot left in bucket
+ num_errors++;
+ break;
+ }
+ }
+ if (num_errors > 0) {
+ break;
+ }
+ }
+ }
+ FAISS_THROW_IF_NOT_MSG(num_errors == 0, "hashtable capacity exhausted");
+}
+
+void hashtable_int64_to_int64_lookup(
+ int log2_capacity,
+ const int64_t* tab,
+ size_t n,
+ const int64_t* keys,
+ int64_t* vals) {
+ size_t capacity = (size_t)1 << log2_capacity;
+ std::vector<int64_t> hk(n), bucket_no(n);
+ int64_t mask = capacity - 1;
+ int log2_nbucket = log2_capacity_to_log2_nbucket(log2_capacity);
+
+#pragma omp parallel for
+ for (int64_t i = 0; i < n; i++) {
+ int64_t k = keys[i];
+ int64_t hk = hash_function(k) & mask;
+ size_t slot = hk;
+
+ if (tab[2 * slot] == -1) { // not in table
+ vals[i] = -1;
+ } else if (tab[2 * slot] == k) { // found!
+ vals[i] = tab[2 * slot + 1];
+ } else { // need to search in [k0, k1)
+ size_t bucket = hk >> (log2_capacity - log2_nbucket);
+ size_t k0 = bucket << (log2_capacity - log2_nbucket);
+ size_t k1 = (bucket + 1) << (log2_capacity - log2_nbucket);
+ for (;;) {
+ if (tab[slot * 2] == k) { // found!
+ vals[i] = tab[2 * slot + 1];
+ break;
+ }
+ slot++;
+ if (slot == k1) {
+ slot = k0;
+ }
+ if (slot == hk) { // bucket is full and not found
+ vals[i] = -1;
+ break;
+ }
+ }
+ }
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/sorting.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/sorting.h
new file mode 100644
index 0000000..abe113f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/sorting.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+#include <faiss/impl/platform_macros.h>
+
+namespace faiss {
+
+/** Indirect sort of a floating-point array
+ *
+ * @param n size of the array
+ * @param vals array to sort, size n
+ * @param perm output: permutation of [0..n-1], st.
+ * vals[perm[i + 1]] >= vals[perm[i]]
+ */
+void fvec_argsort(size_t n, const float* vals, size_t* perm);
+
+/** Same as fvec_argsort, parallelized */
+void fvec_argsort_parallel(size_t n, const float* vals, size_t* perm);
+
+/// increase verbosity of the bucket_sort functions
+FAISS_API extern int bucket_sort_verbose;
+
+/** Bucket sort of a list of values
+ *
+ * @param vals values to sort, size nval, max value nbucket - 1
+ * @param lims output limits of buckets, size nbucket + 1
+ * @param perm output buckets, the elements of bucket
+ * i are in perm[lims[i]:lims[i + 1]]
+ * @param nt number of threads (0 = pure sequential code)
+ */
+void bucket_sort(
+ size_t nval,
+ const uint64_t* vals,
+ uint64_t nbucket,
+ int64_t* lims,
+ int64_t* perm,
+ int nt = 0);
+
+/** in-place bucket sort (with attention to memory=>int32)
+ * on input the values are in a nrow * col matrix
+ * we want to store the row numbers in the output.
+ *
+ * @param vals positive values to sort, size nrow * ncol,
+ * max value nbucket - 1
+ * @param lims output limits of buckets, size nbucket + 1
+ * @param nt number of threads (0 = pure sequential code)
+ */
+void matrix_bucket_sort_inplace(
+ size_t nrow,
+ size_t ncol,
+ int32_t* vals,
+ int32_t nbucket,
+ int64_t* lims,
+ int nt = 0);
+
+/// same with int64 elements
+void matrix_bucket_sort_inplace(
+ size_t nrow,
+ size_t ncol,
+ int64_t* vals,
+ int64_t nbucket,
+ int64_t* lims,
+ int nt = 0);
+
+/** Hashtable implementation for int64 -> int64 with external storage
+ * implemented for fast batch add and lookup.
+ *
+ * tab is of size 2 * (1 << log2_capacity)
+ * n is the number of elements to add or search
+ *
+ * adding several values in a same batch: an arbitrary one gets added
+ * in different batches: the newer batch overwrites.
+ * raises an exception if capacity is exhausted.
+ */
+
+void hashtable_int64_to_int64_init(int log2_capacity, int64_t* tab);
+
+void hashtable_int64_to_int64_add(
+ int log2_capacity,
+ int64_t* tab,
+ size_t n,
+ const int64_t* keys,
+ const int64_t* vals);
+
+void hashtable_int64_to_int64_lookup(
+ int log2_capacity,
+ const int64_t* tab,
+ size_t n,
+ const int64_t* keys,
+ int64_t* vals);
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/transpose/transpose-avx2-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/transpose/transpose-avx2-inl.h
new file mode 100644
index 0000000..464f44c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/transpose/transpose-avx2-inl.h
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// This file contains transposing kernels for AVX2 for
+// tiny float/int32 matrices, such as 8x2.
+
+#ifdef __AVX2__
+
+#include <immintrin.h>
+
+namespace faiss {
+
+// 8x2 -> 2x8
+inline void transpose_8x2(
+ const __m256 i0,
+ const __m256 i1,
+ __m256& o0,
+ __m256& o1) {
+ // say, we have the following as in input:
+ // i0: 00 01 10 11 20 21 30 31
+ // i1: 40 41 50 51 60 61 70 71
+
+ // 00 01 10 11 40 41 50 51
+ const __m256 r0 = _mm256_permute2f128_ps(i0, i1, _MM_SHUFFLE(0, 2, 0, 0));
+ // 20 21 30 31 60 61 70 71
+ const __m256 r1 = _mm256_permute2f128_ps(i0, i1, _MM_SHUFFLE(0, 3, 0, 1));
+
+ // 00 10 20 30 40 50 60 70
+ o0 = _mm256_shuffle_ps(r0, r1, _MM_SHUFFLE(2, 0, 2, 0));
+ // 01 11 21 31 41 51 61 71
+ o1 = _mm256_shuffle_ps(r0, r1, _MM_SHUFFLE(3, 1, 3, 1));
+}
+
+// 8x4 -> 4x8
+inline void transpose_8x4(
+ const __m256 i0,
+ const __m256 i1,
+ const __m256 i2,
+ const __m256 i3,
+ __m256& o0,
+ __m256& o1,
+ __m256& o2,
+ __m256& o3) {
+ // say, we have the following as an input:
+ // i0: 00 01 02 03 10 11 12 13
+ // i1: 20 21 22 23 30 31 32 33
+ // i2: 40 41 42 43 50 51 52 53
+ // i3: 60 61 62 63 70 71 72 73
+
+ // 00 01 02 03 40 41 42 43
+ const __m256 r0 = _mm256_permute2f128_ps(i0, i2, _MM_SHUFFLE(0, 2, 0, 0));
+ // 20 21 22 23 60 61 62 63
+ const __m256 r1 = _mm256_permute2f128_ps(i1, i3, _MM_SHUFFLE(0, 2, 0, 0));
+ // 10 11 12 13 50 51 52 53
+ const __m256 r2 = _mm256_permute2f128_ps(i0, i2, _MM_SHUFFLE(0, 3, 0, 1));
+ // 30 31 32 33 70 71 72 73
+ const __m256 r3 = _mm256_permute2f128_ps(i1, i3, _MM_SHUFFLE(0, 3, 0, 1));
+
+ // 00 02 10 12 40 42 50 52
+ const __m256 t0 = _mm256_shuffle_ps(r0, r2, _MM_SHUFFLE(2, 0, 2, 0));
+ // 01 03 11 13 41 43 51 53
+ const __m256 t1 = _mm256_shuffle_ps(r0, r2, _MM_SHUFFLE(3, 1, 3, 1));
+ // 20 22 30 32 60 62 70 72
+ const __m256 t2 = _mm256_shuffle_ps(r1, r3, _MM_SHUFFLE(2, 0, 2, 0));
+ // 21 23 31 33 61 63 71 73
+ const __m256 t3 = _mm256_shuffle_ps(r1, r3, _MM_SHUFFLE(3, 1, 3, 1));
+
+ // 00 10 20 30 40 50 60 70
+ o0 = _mm256_shuffle_ps(t0, t2, _MM_SHUFFLE(2, 0, 2, 0));
+ // 01 11 21 31 41 51 61 71
+ o1 = _mm256_shuffle_ps(t1, t3, _MM_SHUFFLE(2, 0, 2, 0));
+ // 02 12 22 32 42 52 62 72
+ o2 = _mm256_shuffle_ps(t0, t2, _MM_SHUFFLE(3, 1, 3, 1));
+ // 03 13 23 33 43 53 63 73
+ o3 = _mm256_shuffle_ps(t1, t3, _MM_SHUFFLE(3, 1, 3, 1));
+}
+
+inline void transpose_8x8(
+ const __m256 i0,
+ const __m256 i1,
+ const __m256 i2,
+ const __m256 i3,
+ const __m256 i4,
+ const __m256 i5,
+ const __m256 i6,
+ const __m256 i7,
+ __m256& o0,
+ __m256& o1,
+ __m256& o2,
+ __m256& o3,
+ __m256& o4,
+ __m256& o5,
+ __m256& o6,
+ __m256& o7) {
+ // say, we have the following as an input:
+ // i0: 00 01 02 03 04 05 06 07
+ // i1: 10 11 12 13 14 15 16 17
+ // i2: 20 21 22 23 24 25 26 27
+ // i3: 30 31 32 33 34 35 36 37
+ // i4: 40 41 42 43 44 45 46 47
+ // i5: 50 51 52 53 54 55 56 57
+ // i6: 60 61 62 63 64 65 66 67
+ // i7: 70 71 72 73 74 75 76 77
+
+ // 00 10 01 11 04 14 05 15
+ const __m256 r0 = _mm256_unpacklo_ps(i0, i1);
+ // 02 12 03 13 06 16 07 17
+ const __m256 r1 = _mm256_unpackhi_ps(i0, i1);
+ // 20 30 21 31 24 34 25 35
+ const __m256 r2 = _mm256_unpacklo_ps(i2, i3);
+ // 22 32 23 33 26 36 27 37
+ const __m256 r3 = _mm256_unpackhi_ps(i2, i3);
+ // 40 50 41 51 44 54 45 55
+ const __m256 r4 = _mm256_unpacklo_ps(i4, i5);
+ // 42 52 43 53 46 56 47 57
+ const __m256 r5 = _mm256_unpackhi_ps(i4, i5);
+ // 60 70 61 71 64 74 65 75
+ const __m256 r6 = _mm256_unpacklo_ps(i6, i7);
+ // 62 72 63 73 66 76 67 77
+ const __m256 r7 = _mm256_unpackhi_ps(i6, i7);
+
+ // 00 10 20 30 04 14 24 34
+ const __m256 rr0 = _mm256_shuffle_ps(r0, r2, _MM_SHUFFLE(1, 0, 1, 0));
+ // 01 11 21 31 05 15 25 35
+ const __m256 rr1 = _mm256_shuffle_ps(r0, r2, _MM_SHUFFLE(3, 2, 3, 2));
+ // 02 12 22 32 06 16 26 36
+ const __m256 rr2 = _mm256_shuffle_ps(r1, r3, _MM_SHUFFLE(1, 0, 1, 0));
+ // 03 13 23 33 07 17 27 37
+ const __m256 rr3 = _mm256_shuffle_ps(r1, r3, _MM_SHUFFLE(3, 2, 3, 2));
+ // 40 50 60 70 44 54 64 74
+ const __m256 rr4 = _mm256_shuffle_ps(r4, r6, _MM_SHUFFLE(1, 0, 1, 0));
+ // 41 51 61 71 45 55 65 75
+ const __m256 rr5 = _mm256_shuffle_ps(r4, r6, _MM_SHUFFLE(3, 2, 3, 2));
+ // 42 52 62 72 46 56 66 76
+ const __m256 rr6 = _mm256_shuffle_ps(r5, r7, _MM_SHUFFLE(1, 0, 1, 0));
+ // 43 53 63 73 47 57 67 77
+ const __m256 rr7 = _mm256_shuffle_ps(r5, r7, _MM_SHUFFLE(3, 2, 3, 2));
+
+ // 00 10 20 30 40 50 60 70
+ o0 = _mm256_permute2f128_ps(rr0, rr4, 0x20);
+ // 01 11 21 31 41 51 61 71
+ o1 = _mm256_permute2f128_ps(rr1, rr5, 0x20);
+ // 02 12 22 32 42 52 62 72
+ o2 = _mm256_permute2f128_ps(rr2, rr6, 0x20);
+ // 03 13 23 33 43 53 63 73
+ o3 = _mm256_permute2f128_ps(rr3, rr7, 0x20);
+ // 04 14 24 34 44 54 64 74
+ o4 = _mm256_permute2f128_ps(rr0, rr4, 0x31);
+ // 05 15 25 35 45 55 65 75
+ o5 = _mm256_permute2f128_ps(rr1, rr5, 0x31);
+ // 06 16 26 36 46 56 66 76
+ o6 = _mm256_permute2f128_ps(rr2, rr6, 0x31);
+ // 07 17 27 37 47 57 67 77
+ o7 = _mm256_permute2f128_ps(rr3, rr7, 0x31);
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/transpose/transpose-avx512-inl.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/transpose/transpose-avx512-inl.h
new file mode 100644
index 0000000..52413e2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/transpose/transpose-avx512-inl.h
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+
+// This file contains transposing kernels for AVX512 for // tiny float/int32
+// matrices, such as 16x2.
+
+#ifdef __AVX512F__
+
+#include <immintrin.h>
+
+namespace faiss {
+
+// 16x2 -> 2x16
+inline void transpose_16x2(
+ const __m512 i0,
+ const __m512 i1,
+ __m512& o0,
+ __m512& o1) {
+ // assume we have the following input:
+ // i0: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+ // i1: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
+
+ // 0 1 2 3 8 9 10 11 16 17 18 19 24 25 26 27
+ const __m512 r0 = _mm512_shuffle_f32x4(i0, i1, _MM_SHUFFLE(2, 0, 2, 0));
+ // 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31
+ const __m512 r1 = _mm512_shuffle_f32x4(i0, i1, _MM_SHUFFLE(3, 1, 3, 1));
+
+ // 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
+ o0 = _mm512_shuffle_ps(r0, r1, _MM_SHUFFLE(2, 0, 2, 0));
+ // 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31
+ o1 = _mm512_shuffle_ps(r0, r1, _MM_SHUFFLE(3, 1, 3, 1));
+}
+
+// 16x4 -> 4x16
+inline void transpose_16x4(
+ const __m512 i0,
+ const __m512 i1,
+ const __m512 i2,
+ const __m512 i3,
+ __m512& o0,
+ __m512& o1,
+ __m512& o2,
+ __m512& o3) {
+ // assume that we have the following input:
+ // i0: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+ // i1: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
+ // i2: 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
+ // i3: 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
+
+ // 0 1 2 3 8 9 10 11 16 17 18 19 24 25 26 27
+ const __m512 r0 = _mm512_shuffle_f32x4(i0, i1, _MM_SHUFFLE(2, 0, 2, 0));
+ // 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31
+ const __m512 r1 = _mm512_shuffle_f32x4(i0, i1, _MM_SHUFFLE(3, 1, 3, 1));
+ // 32 33 34 35 40 41 42 43 48 49 50 51 56 57 58 59
+ const __m512 r2 = _mm512_shuffle_f32x4(i2, i3, _MM_SHUFFLE(2, 0, 2, 0));
+ // 52 53 54 55 60 61 62 63 52 53 54 55 60 61 62 63
+ const __m512 r3 = _mm512_shuffle_f32x4(i2, i3, _MM_SHUFFLE(3, 1, 3, 1));
+
+ // 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
+ const __m512 t0 = _mm512_shuffle_ps(r0, r1, _MM_SHUFFLE(2, 0, 2, 0));
+ // 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31
+ const __m512 t1 = _mm512_shuffle_ps(r0, r1, _MM_SHUFFLE(3, 1, 3, 1));
+ // 32 34 52 54 40 42 60 62 48 50 52 54 56 58 60 62
+ const __m512 t2 = _mm512_shuffle_ps(r2, r3, _MM_SHUFFLE(2, 0, 2, 0));
+ // 33 35 53 55 41 43 61 63 49 51 53 55 57 59 61 63
+ const __m512 t3 = _mm512_shuffle_ps(r2, r3, _MM_SHUFFLE(3, 1, 3, 1));
+
+ const __m512i idx0 = _mm512_set_epi32(
+ 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0);
+ const __m512i idx1 = _mm512_set_epi32(
+ 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1);
+
+ // 0 4 8 12 16 20 24 28 32 52 40 60 48 52 56 60
+ o0 = _mm512_permutex2var_ps(t0, idx0, t2);
+ // 1 5 9 13 17 21 25 29 33 53 41 61 49 53 57 61
+ o1 = _mm512_permutex2var_ps(t1, idx0, t3);
+ // 2 6 10 14 18 22 26 30 34 54 42 62 50 54 58 62
+ o2 = _mm512_permutex2var_ps(t0, idx1, t2);
+ // 3 7 11 15 19 23 27 31 35 55 43 63 51 55 59 63
+ o3 = _mm512_permutex2var_ps(t1, idx1, t3);
+}
+
+// 16x8 -> 8x16 transpose
+inline void transpose_16x8(
+ const __m512 i0,
+ const __m512 i1,
+ const __m512 i2,
+ const __m512 i3,
+ const __m512 i4,
+ const __m512 i5,
+ const __m512 i6,
+ const __m512 i7,
+ __m512& o0,
+ __m512& o1,
+ __m512& o2,
+ __m512& o3,
+ __m512& o4,
+ __m512& o5,
+ __m512& o6,
+ __m512& o7) {
+ // assume that we have the following input:
+ // i0: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+ // i1: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
+ // i2: 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
+ // i3: 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
+ // i4: 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
+ // i5: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
+ // i6: 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
+ // i7: 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
+
+ // 0 16 1 17 4 20 5 21 8 24 9 25 12 28 13 29
+ const __m512 r0 = _mm512_unpacklo_ps(i0, i1);
+ // 2 18 3 19 6 22 7 23 10 26 11 27 14 30 15 31
+ const __m512 r1 = _mm512_unpackhi_ps(i0, i1);
+ // 32 48 33 49 36 52 37 53 40 56 41 57 44 60 45 61
+ const __m512 r2 = _mm512_unpacklo_ps(i2, i3);
+ // 34 50 35 51 38 54 39 55 42 58 43 59 46 62 47 63
+ const __m512 r3 = _mm512_unpackhi_ps(i2, i3);
+ // 64 80 65 81 68 84 69 85 72 88 73 89 76 92 77 93
+ const __m512 r4 = _mm512_unpacklo_ps(i4, i5);
+ // 66 82 67 83 70 86 71 87 74 90 75 91 78 94 79 95
+ const __m512 r5 = _mm512_unpackhi_ps(i4, i5);
+ // 96 112 97 113 100 116 101 117 104 120 105 121 108 124 109 125
+ const __m512 r6 = _mm512_unpacklo_ps(i6, i7);
+ // 98 114 99 115 102 118 103 119 106 122 107 123 110 126 111 127
+ const __m512 r7 = _mm512_unpackhi_ps(i6, i7);
+
+ // 0 16 32 48 4 20 36 52 8 24 40 56 12 28 44 60
+ const __m512 t0 = _mm512_shuffle_ps(r0, r2, _MM_SHUFFLE(1, 0, 1, 0));
+ // 1 17 33 49 5 21 37 53 9 25 41 57 13 29 45 61
+ const __m512 t1 = _mm512_shuffle_ps(r0, r2, _MM_SHUFFLE(3, 2, 3, 2));
+ // 2 18 34 50 6 22 38 54 10 26 42 58 14 30 46 62
+ const __m512 t2 = _mm512_shuffle_ps(r1, r3, _MM_SHUFFLE(1, 0, 1, 0));
+ // 3 19 35 51 7 23 39 55 11 27 43 59 15 31 47 63
+ const __m512 t3 = _mm512_shuffle_ps(r1, r3, _MM_SHUFFLE(3, 2, 3, 2));
+ // 64 80 96 112 68 84 100 116 72 88 104 120 76 92 108 124
+ const __m512 t4 = _mm512_shuffle_ps(r4, r6, _MM_SHUFFLE(1, 0, 1, 0));
+ // 65 81 97 113 69 85 101 117 73 89 105 121 77 93 109 125
+ const __m512 t5 = _mm512_shuffle_ps(r4, r6, _MM_SHUFFLE(3, 2, 3, 2));
+ // 66 82 98 114 70 86 102 118 74 90 106 122 78 94 110 126
+ const __m512 t6 = _mm512_shuffle_ps(r5, r7, _MM_SHUFFLE(1, 0, 1, 0));
+ // 67 83 99 115 71 87 103 119 75 91 107 123 79 95 111 127
+ const __m512 t7 = _mm512_shuffle_ps(r5, r7, _MM_SHUFFLE(3, 2, 3, 2));
+
+ const __m512i idx0 = _mm512_set_epi32(
+ 27, 19, 26, 18, 25, 17, 24, 16, 11, 3, 10, 2, 9, 1, 8, 0);
+ const __m512i idx1 = _mm512_set_epi32(
+ 31, 23, 30, 22, 29, 21, 28, 20, 15, 7, 14, 6, 13, 5, 12, 4);
+
+ // 0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120
+ o0 = _mm512_permutex2var_ps(t0, idx0, t4);
+ // 1 9 17 25 33 41 49 57 65 73 81 89 97 105 113 121
+ o1 = _mm512_permutex2var_ps(t1, idx0, t5);
+ // 2 10 18 26 34 42 50 58 66 74 82 90 98 106 114 122
+ o2 = _mm512_permutex2var_ps(t2, idx0, t6);
+ // 3 11 19 27 35 43 51 59 67 75 83 91 99 107 115 123
+ o3 = _mm512_permutex2var_ps(t3, idx0, t7);
+ // 4 12 20 28 36 44 52 60 68 76 84 92 100 108 116 124
+ o4 = _mm512_permutex2var_ps(t0, idx1, t4);
+ // 5 13 21 29 37 45 53 61 69 77 85 93 101 109 117 125
+ o5 = _mm512_permutex2var_ps(t1, idx1, t5);
+ // 6 14 22 30 38 46 54 62 70 78 86 94 102 110 118 126
+ o6 = _mm512_permutex2var_ps(t2, idx1, t6);
+ // 7 15 23 31 39 47 55 63 71 79 87 95 103 111 119 127
+ o7 = _mm512_permutex2var_ps(t3, idx1, t7);
+}
+
+} // namespace faiss
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/utils.cpp b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/utils.cpp
new file mode 100644
index 0000000..0811cb9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/utils.cpp
@@ -0,0 +1,644 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+#include <faiss/Index.h>
+#include <faiss/utils/utils.h>
+
+#include <cassert>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+
+#include <sys/types.h>
+
+#ifdef _MSC_VER
+#define NOMINMAX
+#include <windows.h>
+#undef NOMINMAX
+#else
+#include <sys/time.h>
+#include <unistd.h>
+#endif // !_MSC_VER
+
+#include <omp.h>
+
+#include <algorithm>
+#include <set>
+#include <type_traits>
+#include <vector>
+
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/random.h>
+
+#ifndef FINTEGER
+#define FINTEGER long
+#endif
+
+extern "C" {
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+
+/* Lapack functions, see http://www.netlib.org/clapack/old/single/sgeqrf.c */
+
+int sgeqrf_(
+ FINTEGER* m,
+ FINTEGER* n,
+ float* a,
+ FINTEGER* lda,
+ float* tau,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+int sorgqr_(
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ float* a,
+ FINTEGER* lda,
+ float* tau,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+
+int sgemv_(
+ const char* trans,
+ FINTEGER* m,
+ FINTEGER* n,
+ float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* x,
+ FINTEGER* incx,
+ float* beta,
+ float* y,
+ FINTEGER* incy);
+}
+
+/**************************************************
+ * Get some stats about the system
+ **************************************************/
+
+namespace faiss {
+
+// this will be set at load time from GPU Faiss
+std::string gpu_compile_options;
+
+std::string get_compile_options() {
+ std::string options;
+
+ // this flag is set by GCC and Clang
+#ifdef __OPTIMIZE__
+ options += "OPTIMIZE ";
+#endif
+
+#ifdef __AVX512F__
+ options += "AVX512 ";
+#elif defined(__AVX2__)
+ options += "AVX2 ";
+#elif defined(__ARM_FEATURE_SVE)
+ options += "SVE NEON ";
+#elif defined(__aarch64__)
+ options += "NEON ";
+#else
+ options += "GENERIC ";
+#endif
+
+ options += gpu_compile_options;
+
+ return options;
+}
+
+std::string get_version() {
+ return VERSION_STRING;
+}
+
+#ifdef _MSC_VER
+double getmillisecs() {
+ LARGE_INTEGER ts;
+ LARGE_INTEGER freq;
+ QueryPerformanceFrequency(&freq);
+ QueryPerformanceCounter(&ts);
+
+ return (ts.QuadPart * 1e3) / freq.QuadPart;
+}
+#else // _MSC_VER
+double getmillisecs() {
+ struct timeval tv;
+ gettimeofday(&tv, nullptr);
+ return tv.tv_sec * 1e3 + tv.tv_usec * 1e-3;
+}
+#endif // _MSC_VER
+
+uint64_t get_cycles() {
+#ifdef __x86_64__
+ uint32_t high, low;
+ asm volatile("rdtsc \n\t" : "=a"(low), "=d"(high));
+ return ((uint64_t)high << 32) | (low);
+#else
+ return 0;
+#endif
+}
+
+#ifdef __linux__
+
+size_t get_mem_usage_kb() {
+ int pid = getpid();
+ char fname[256];
+ snprintf(fname, 256, "/proc/%d/status", pid);
+ FILE* f = fopen(fname, "r");
+ FAISS_THROW_IF_NOT_MSG(f, "cannot open proc status file");
+ size_t sz = 0;
+ for (;;) {
+ char buf[256];
+ if (!fgets(buf, 256, f))
+ break;
+ if (sscanf(buf, "VmRSS: %ld kB", &sz) == 1)
+ break;
+ }
+ fclose(f);
+ return sz;
+}
+
+#else
+
+size_t get_mem_usage_kb() {
+ fprintf(stderr,
+ "WARN: get_mem_usage_kb not implemented on current architecture\n");
+ return 0;
+}
+
+#endif
+
+void reflection(
+ const float* __restrict u,
+ float* __restrict x,
+ size_t n,
+ size_t d,
+ size_t nu) {
+ size_t i, j, l;
+ for (i = 0; i < n; i++) {
+ const float* up = u;
+ for (l = 0; l < nu; l++) {
+ float ip1 = 0, ip2 = 0;
+
+ for (j = 0; j < d; j += 2) {
+ ip1 += up[j] * x[j];
+ ip2 += up[j + 1] * x[j + 1];
+ }
+ float ip = 2 * (ip1 + ip2);
+
+ for (j = 0; j < d; j++)
+ x[j] -= ip * up[j];
+ up += d;
+ }
+ x += d;
+ }
+}
+
+/* Reference implementation (slower) */
+void reflection_ref(const float* u, float* x, size_t n, size_t d, size_t nu) {
+ size_t i, j, l;
+ for (i = 0; i < n; i++) {
+ const float* up = u;
+ for (l = 0; l < nu; l++) {
+ double ip = 0;
+
+ for (j = 0; j < d; j++)
+ ip += up[j] * x[j];
+ ip *= 2;
+
+ for (j = 0; j < d; j++)
+ x[j] -= ip * up[j];
+
+ up += d;
+ }
+ x += d;
+ }
+}
+
+/***************************************************************************
+ * Some matrix manipulation functions
+ ***************************************************************************/
+
+void matrix_qr(int m, int n, float* a) {
+ FAISS_THROW_IF_NOT(m >= n);
+ FINTEGER mi = m, ni = n, ki = mi < ni ? mi : ni;
+ std::vector<float> tau(ki);
+ FINTEGER lwork = -1, info;
+ float work_size;
+
+ sgeqrf_(&mi, &ni, a, &mi, tau.data(), &work_size, &lwork, &info);
+ lwork = size_t(work_size);
+ std::vector<float> work(lwork);
+
+ sgeqrf_(&mi, &ni, a, &mi, tau.data(), work.data(), &lwork, &info);
+
+ sorgqr_(&mi, &ni, &ki, a, &mi, tau.data(), work.data(), &lwork, &info);
+}
+
+/***************************************************************************
+ * Result list routines
+ ***************************************************************************/
+
+void ranklist_handle_ties(int k, int64_t* idx, const float* dis) {
+ float prev_dis = -1e38;
+ int prev_i = -1;
+ for (int i = 0; i < k; i++) {
+ if (dis[i] != prev_dis) {
+ if (i > prev_i + 1) {
+ // sort between prev_i and i - 1
+ std::sort(idx + prev_i, idx + i);
+ }
+ prev_i = i;
+ prev_dis = dis[i];
+ }
+ }
+}
+
+size_t merge_result_table_with(
+ size_t n,
+ size_t k,
+ int64_t* I0,
+ float* D0,
+ const int64_t* I1,
+ const float* D1,
+ bool keep_min,
+ int64_t translation) {
+ size_t n1 = 0;
+
+#pragma omp parallel reduction(+ : n1)
+ {
+ std::vector<int64_t> tmpI(k);
+ std::vector<float> tmpD(k);
+
+#pragma omp for
+ for (int64_t i = 0; i < n; i++) {
+ int64_t* lI0 = I0 + i * k;
+ float* lD0 = D0 + i * k;
+ const int64_t* lI1 = I1 + i * k;
+ const float* lD1 = D1 + i * k;
+ size_t r0 = 0;
+ size_t r1 = 0;
+
+ if (keep_min) {
+ for (size_t j = 0; j < k; j++) {
+ if (lI0[r0] >= 0 && lD0[r0] < lD1[r1]) {
+ tmpD[j] = lD0[r0];
+ tmpI[j] = lI0[r0];
+ r0++;
+ } else if (lD1[r1] >= 0) {
+ tmpD[j] = lD1[r1];
+ tmpI[j] = lI1[r1] + translation;
+ r1++;
+ } else { // both are NaNs
+ tmpD[j] = NAN;
+ tmpI[j] = -1;
+ }
+ }
+ } else {
+ for (size_t j = 0; j < k; j++) {
+ if (lI0[r0] >= 0 && lD0[r0] > lD1[r1]) {
+ tmpD[j] = lD0[r0];
+ tmpI[j] = lI0[r0];
+ r0++;
+ } else if (lD1[r1] >= 0) {
+ tmpD[j] = lD1[r1];
+ tmpI[j] = lI1[r1] + translation;
+ r1++;
+ } else { // both are NaNs
+ tmpD[j] = NAN;
+ tmpI[j] = -1;
+ }
+ }
+ }
+ n1 += r1;
+ memcpy(lD0, tmpD.data(), sizeof(lD0[0]) * k);
+ memcpy(lI0, tmpI.data(), sizeof(lI0[0]) * k);
+ }
+ }
+
+ return n1;
+}
+
+size_t ranklist_intersection_size(
+ size_t k1,
+ const int64_t* v1,
+ size_t k2,
+ const int64_t* v2_in) {
+ if (k2 > k1)
+ return ranklist_intersection_size(k2, v2_in, k1, v1);
+ int64_t* v2 = new int64_t[k2];
+ memcpy(v2, v2_in, sizeof(int64_t) * k2);
+ std::sort(v2, v2 + k2);
+ { // de-dup v2
+ int64_t prev = -1;
+ size_t wp = 0;
+ for (size_t i = 0; i < k2; i++) {
+ if (v2[i] != prev) {
+ v2[wp++] = prev = v2[i];
+ }
+ }
+ k2 = wp;
+ }
+ const int64_t seen_flag = int64_t{1} << 60;
+ size_t count = 0;
+ for (size_t i = 0; i < k1; i++) {
+ int64_t q = v1[i];
+ size_t i0 = 0, i1 = k2;
+ while (i0 + 1 < i1) {
+ size_t imed = (i1 + i0) / 2;
+ int64_t piv = v2[imed] & ~seen_flag;
+ if (piv <= q)
+ i0 = imed;
+ else
+ i1 = imed;
+ }
+ if (v2[i0] == q) {
+ count++;
+ v2[i0] |= seen_flag;
+ }
+ }
+ delete[] v2;
+
+ return count;
+}
+
+double imbalance_factor(int k, const int64_t* hist) {
+ double tot = 0, uf = 0;
+
+ for (int i = 0; i < k; i++) {
+ tot += hist[i];
+ uf += hist[i] * (double)hist[i];
+ }
+ uf = uf * k / (tot * tot);
+
+ return uf;
+}
+
+double imbalance_factor(int64_t n, int k, const int64_t* assign) {
+ std::vector<int64_t> hist(k, 0);
+ for (int64_t i = 0; i < n; i++) {
+ hist[assign[i]]++;
+ }
+
+ return imbalance_factor(k, hist.data());
+}
+
+int ivec_hist(size_t n, const int* v, int vmax, int* hist) {
+ memset(hist, 0, sizeof(hist[0]) * vmax);
+ int nout = 0;
+ while (n--) {
+ if (v[n] < 0 || v[n] >= vmax)
+ nout++;
+ else
+ hist[v[n]]++;
+ }
+ return nout;
+}
+
+void bincode_hist(size_t n, size_t nbits, const uint8_t* codes, int* hist) {
+ FAISS_THROW_IF_NOT(nbits % 8 == 0);
+ size_t d = nbits / 8;
+ std::vector<int> accu(d * 256);
+ const uint8_t* c = codes;
+ for (size_t i = 0; i < n; i++)
+ for (int j = 0; j < d; j++)
+ accu[j * 256 + *c++]++;
+ memset(hist, 0, sizeof(*hist) * nbits);
+ for (int i = 0; i < d; i++) {
+ const int* ai = accu.data() + i * 256;
+ int* hi = hist + i * 8;
+ for (int j = 0; j < 256; j++)
+ for (int k = 0; k < 8; k++)
+ if ((j >> k) & 1)
+ hi[k] += ai[j];
+ }
+}
+
+uint64_t ivec_checksum(size_t n, const int32_t* assigned) {
+ const uint32_t* a = reinterpret_cast<const uint32_t*>(assigned);
+ uint64_t cs = 112909;
+ while (n--) {
+ cs = cs * 65713 + a[n] * 1686049;
+ }
+ return cs;
+}
+
+uint64_t bvec_checksum(size_t n, const uint8_t* a) {
+ uint64_t cs = ivec_checksum(n / 4, (const int32_t*)a);
+ for (size_t i = n / 4 * 4; i < n; i++) {
+ cs = cs * 65713 + a[n] * 1686049;
+ }
+ return cs;
+}
+
+void bvecs_checksum(size_t n, size_t d, const uint8_t* a, uint64_t* cs) {
+ // MSVC can't accept unsigned index for #pragma omp parallel for
+ // so below codes only accept n <= std::numeric_limits<ssize_t>::max()
+ using ssize_t = std::make_signed<std::size_t>::type;
+ const ssize_t size = n;
+#pragma omp parallel for if (size > 1000)
+ for (ssize_t i_ = 0; i_ < size; i_++) {
+ const auto i = static_cast<std::size_t>(i_);
+ cs[i] = bvec_checksum(d, a + i * d);
+ }
+}
+
+const float* fvecs_maybe_subsample(
+ size_t d,
+ size_t* n,
+ size_t nmax,
+ const float* x,
+ bool verbose,
+ int64_t seed) {
+ if (*n <= nmax)
+ return x; // nothing to do
+
+ size_t n2 = nmax;
+ if (verbose) {
+ printf(" Input training set too big (max size is %zd), sampling "
+ "%zd / %zd vectors\n",
+ nmax,
+ n2,
+ *n);
+ }
+ std::vector<int> subset(*n);
+ rand_perm(subset.data(), *n, seed);
+ float* x_subset = new float[n2 * d];
+ for (int64_t i = 0; i < n2; i++)
+ memcpy(&x_subset[i * d], &x[subset[i] * size_t(d)], sizeof(x[0]) * d);
+ *n = n2;
+ return x_subset;
+}
+
+void binary_to_real(size_t d, const uint8_t* x_in, float* x_out) {
+ for (size_t i = 0; i < d; ++i) {
+ x_out[i] = 2 * ((x_in[i >> 3] >> (i & 7)) & 1) - 1;
+ }
+}
+
+void real_to_binary(size_t d, const float* x_in, uint8_t* x_out) {
+ for (size_t i = 0; i < d / 8; ++i) {
+ uint8_t b = 0;
+ for (int j = 0; j < 8; ++j) {
+ if (x_in[8 * i + j] > 0) {
+ b |= (1 << j);
+ }
+ }
+ x_out[i] = b;
+ }
+}
+
+// from Python's stringobject.c
+uint64_t hash_bytes(const uint8_t* bytes, int64_t n) {
+ const uint8_t* p = bytes;
+ uint64_t x = (uint64_t)(*p) << 7;
+ int64_t len = n;
+ while (--len >= 0) {
+ x = (1000003 * x) ^ *p++;
+ }
+ x ^= n;
+ return x;
+}
+
+bool check_openmp() {
+ omp_set_num_threads(10);
+
+ if (omp_get_max_threads() != 10) {
+ return false;
+ }
+
+ std::vector<int> nt_per_thread(10);
+ size_t sum = 0;
+ bool in_parallel = true;
+#pragma omp parallel reduction(+ : sum)
+ {
+ if (!omp_in_parallel()) {
+ in_parallel = false;
+ }
+
+ int nt = omp_get_num_threads();
+ int rank = omp_get_thread_num();
+
+ nt_per_thread[rank] = nt;
+#pragma omp for
+ for (int i = 0; i < 1000 * 1000 * 10; i++) {
+ sum += i;
+ }
+ }
+
+ if (!in_parallel) {
+ return false;
+ }
+ if (nt_per_thread[0] != 10) {
+ return false;
+ }
+ if (sum == 0) {
+ return false;
+ }
+
+ return true;
+}
+
+namespace {
+
+template <typename T>
+int64_t count_lt(int64_t n, const T* row, T threshold) {
+ for (int64_t i = 0; i < n; i++) {
+ if (!(row[i] < threshold)) {
+ return i;
+ }
+ }
+ return n;
+}
+
+template <typename T>
+int64_t count_gt(int64_t n, const T* row, T threshold) {
+ for (int64_t i = 0; i < n; i++) {
+ if (!(row[i] > threshold)) {
+ return i;
+ }
+ }
+ return n;
+}
+
+} // namespace
+
+template <typename T>
+void CombinerRangeKNN<T>::compute_sizes(int64_t* L_res_init) {
+ this->L_res = L_res_init;
+ L_res_init[0] = 0;
+ int64_t j = 0;
+ for (int64_t i = 0; i < nq; i++) {
+ int64_t n_in;
+ if (!mask || !mask[i]) {
+ const T* row = D + i * k;
+ n_in = keep_max ? count_gt(k, row, r2) : count_lt(k, row, r2);
+ } else {
+ n_in = lim_remain[j + 1] - lim_remain[j];
+ j++;
+ }
+ L_res_init[i + 1] = n_in; // L_res_init[i] + n_in;
+ }
+ // cumsum
+ for (int64_t i = 0; i < nq; i++) {
+ L_res_init[i + 1] += L_res_init[i];
+ }
+}
+
+template <typename T>
+void CombinerRangeKNN<T>::write_result(T* D_res, int64_t* I_res) {
+ FAISS_THROW_IF_NOT(L_res);
+ int64_t j = 0;
+ for (int64_t i = 0; i < nq; i++) {
+ int64_t n_in = L_res[i + 1] - L_res[i];
+ T* D_row = D_res + L_res[i];
+ int64_t* I_row = I_res + L_res[i];
+ if (!mask || !mask[i]) {
+ memcpy(D_row, D + i * k, n_in * sizeof(*D_row));
+ memcpy(I_row, I + i * k, n_in * sizeof(*I_row));
+ } else {
+ memcpy(D_row, D_remain + lim_remain[j], n_in * sizeof(*D_row));
+ memcpy(I_row, I_remain + lim_remain[j], n_in * sizeof(*I_row));
+ j++;
+ }
+ }
+}
+
+// explicit template instantiations
+template struct CombinerRangeKNN<float>;
+template struct CombinerRangeKNN<int16_t>;
+
+void CodeSet::insert(size_t n, const uint8_t* codes, bool* inserted) {
+ for (size_t i = 0; i < n; i++) {
+ auto res = s.insert(
+ std::vector<uint8_t>(codes + i * d, codes + i * d + d));
+ inserted[i] = res.second;
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/utils.h b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/utils.h
new file mode 100644
index 0000000..7d75b32
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/faiss/utils/utils.h
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// -*- c++ -*-
+
+/*
+ * A few utilitary functions for similarity search:
+ * - optimized exhaustive distance and knn search functions
+ * - some functions reimplemented from torch for speed
+ */
+
+#ifndef FAISS_utils_h
+#define FAISS_utils_h
+
+#include <stdint.h>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <faiss/impl/platform_macros.h>
+#include <faiss/utils/Heap.h>
+
+namespace faiss {
+
+/****************************************************************************
+ * Get compile specific variables
+ ***************************************************************************/
+
+/// get compile options
+std::string get_compile_options();
+
+/**************************************************
+ * Get some stats about the system
+ **************************************************/
+
+// Expose Faiss version as a string
+std::string get_version();
+
+/// ms elapsed since some arbitrary epoch
+double getmillisecs();
+
+/// get current RSS usage in kB
+size_t get_mem_usage_kb();
+
+uint64_t get_cycles();
+
+/***************************************************************************
+ * Misc matrix and vector manipulation functions
+ ***************************************************************************/
+
+/* perform a reflection (not an efficient implementation, just for test ) */
+void reflection(const float* u, float* x, size_t n, size_t d, size_t nu);
+
+/** compute the Q of the QR decomposition for m > n
+ * @param a size n * m: input matrix and output Q
+ */
+void matrix_qr(int m, int n, float* a);
+
+/** distances are supposed to be sorted. Sorts indices with same distance*/
+void ranklist_handle_ties(int k, int64_t* idx, const float* dis);
+
+/** count the number of common elements between v1 and v2
+ * algorithm = sorting + bissection to avoid double-counting duplicates
+ */
+size_t ranklist_intersection_size(
+ size_t k1,
+ const int64_t* v1,
+ size_t k2,
+ const int64_t* v2);
+
+/** merge a result table into another one
+ *
+ * @param I0, D0 first result table, size (n, k)
+ * @param I1, D1 second result table, size (n, k)
+ * @param keep_min if true, keep min values, otherwise keep max
+ * @param translation add this value to all I1's indexes
+ * @return nb of values that were taken from the second table
+ */
+size_t merge_result_table_with(
+ size_t n,
+ size_t k,
+ int64_t* I0,
+ float* D0,
+ const int64_t* I1,
+ const float* D1,
+ bool keep_min = true,
+ int64_t translation = 0);
+
+/// a balanced assignment has a IF of 1, a completely unbalanced assignment has
+/// an IF = k.
+double imbalance_factor(int64_t n, int k, const int64_t* assign);
+
+/// same, takes a histogram as input
+double imbalance_factor(int k, const int64_t* hist);
+
+/// compute histogram on v
+int ivec_hist(size_t n, const int* v, int vmax, int* hist);
+
+/** Compute histogram of bits on a code array
+ *
+ * @param codes size(n, nbits / 8)
+ * @param hist size(nbits): nb of 1s in the array of codes
+ */
+void bincode_hist(size_t n, size_t nbits, const uint8_t* codes, int* hist);
+
+/// compute a checksum on a table.
+uint64_t ivec_checksum(size_t n, const int32_t* a);
+
+/// compute a checksum on a table.
+uint64_t bvec_checksum(size_t n, const uint8_t* a);
+
+/** compute checksums for the rows of a matrix
+ *
+ * @param n number of rows
+ * @param d size per row
+ * @param a matrix to handle, size n * d
+ * @param cs output checksums, size n
+ */
+void bvecs_checksum(size_t n, size_t d, const uint8_t* a, uint64_t* cs);
+
+/** random subsamples a set of vectors if there are too many of them
+ *
+ * @param d dimension of the vectors
+ * @param n on input: nb of input vectors, output: nb of output vectors
+ * @param nmax max nb of vectors to keep
+ * @param x input array, size *n-by-d
+ * @param seed random seed to use for sampling
+ * @return x or an array allocated with new [] with *n vectors
+ */
+const float* fvecs_maybe_subsample(
+ size_t d,
+ size_t* n,
+ size_t nmax,
+ const float* x,
+ bool verbose = false,
+ int64_t seed = 1234);
+
+/** Convert binary vector to +1/-1 valued float vector.
+ *
+ * @param d dimension of the vector (multiple of 8)
+ * @param x_in input binary vector (uint8_t table of size d / 8)
+ * @param x_out output float vector (float table of size d)
+ */
+void binary_to_real(size_t d, const uint8_t* x_in, float* x_out);
+
+/** Convert float vector to binary vector. Components > 0 are converted to 1,
+ * others to 0.
+ *
+ * @param d dimension of the vector (multiple of 8)
+ * @param x_in input float vector (float table of size d)
+ * @param x_out output binary vector (uint8_t table of size d / 8)
+ */
+void real_to_binary(size_t d, const float* x_in, uint8_t* x_out);
+
+/** A reasonable hashing function */
+uint64_t hash_bytes(const uint8_t* bytes, int64_t n);
+
+/** Whether OpenMP annotations were respected. */
+bool check_openmp();
+
+/** This class is used to combine range and knn search results
+ * in contrib.exhaustive_search.range_search_gpu */
+
+template <typename T>
+struct CombinerRangeKNN {
+ int64_t nq; /// nb of queries
+ size_t k; /// number of neighbors for the knn search part
+ T r2; /// range search radius
+ bool keep_max; /// whether to keep max values instead of min.
+
+ CombinerRangeKNN(int64_t nq, size_t k, T r2, bool keep_max)
+ : nq(nq), k(k), r2(r2), keep_max(keep_max) {}
+
+ /// Knn search results
+ const int64_t* I = nullptr; /// size nq * k
+ const T* D = nullptr; /// size nq * k
+
+ /// optional: range search results (ignored if mask is NULL)
+ const bool* mask =
+ nullptr; /// mask for where knn results are valid, size nq
+ // range search results for remaining entries nrange = sum(mask)
+ const int64_t* lim_remain = nullptr; /// size nrange + 1
+ const T* D_remain = nullptr; /// size lim_remain[nrange]
+ const int64_t* I_remain = nullptr; /// size lim_remain[nrange]
+
+ const int64_t* L_res = nullptr; /// size nq + 1
+ // Phase 1: compute sizes into limits array (of size nq + 1)
+ void compute_sizes(int64_t* L_res);
+
+ /// Phase 2: caller allocates D_res and I_res (size L_res[nq])
+ /// Phase 3: fill in D_res and I_res
+ void write_result(T* D_res, int64_t* I_res);
+};
+
+struct CodeSet {
+ size_t d;
+ std::set<std::vector<uint8_t>> s;
+
+ explicit CodeSet(size_t d) : d(d) {}
+ void insert(size_t n, const uint8_t* codes, bool* inserted);
+};
+
+} // namespace faiss
+
+#endif /* FAISS_utils_h */
diff --git a/packages/leann-backend-hnsw/third_party/faiss/misc/test_blas.cpp b/packages/leann-backend-hnsw/third_party/faiss/misc/test_blas.cpp
new file mode 100644
index 0000000..567e0bc
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/misc/test_blas.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#undef FINTEGER
+#define FINTEGER long
+
+extern "C" {
+
+/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
+
+int sgemm_(
+ const char* transa,
+ const char* transb,
+ FINTEGER* m,
+ FINTEGER* n,
+ FINTEGER* k,
+ const float* alpha,
+ const float* a,
+ FINTEGER* lda,
+ const float* b,
+ FINTEGER* ldb,
+ float* beta,
+ float* c,
+ FINTEGER* ldc);
+
+/* Lapack functions, see http://www.netlib.org/clapack/old/single/sgeqrf.c */
+
+int sgeqrf_(
+ FINTEGER* m,
+ FINTEGER* n,
+ float* a,
+ FINTEGER* lda,
+ float* tau,
+ float* work,
+ FINTEGER* lwork,
+ FINTEGER* info);
+}
+
+float* new_random_vec(int size) {
+ float* x = new float[size];
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (int i = 0; i < size; i++)
+ x[i] = distrib(rng);
+ return x;
+}
+
+int main() {
+ FINTEGER m = 10, n = 20, k = 30;
+ float *a = new_random_vec(m * k), *b = new_random_vec(n * k),
+ *c = new float[n * m];
+ float one = 1.0, zero = 0.0;
+
+ printf("BLAS test\n");
+
+ sgemm_("Not transposed",
+ "Not transposed",
+ &m,
+ &n,
+ &k,
+ &one,
+ a,
+ &m,
+ b,
+ &k,
+ &zero,
+ c,
+ &m);
+
+ printf("errors=\n");
+
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < n; j++) {
+ float accu = 0;
+ for (int l = 0; l < k; l++)
+ accu += a[i + l * m] * b[l + j * k];
+ printf("%6.3f ", accu - c[i + j * m]);
+ }
+ printf("\n");
+ }
+
+ long info = 0x64bL << 32;
+ long mi = 0x64bL << 32 | m;
+ float* tau = new float[m];
+ FINTEGER lwork = -1;
+
+ float work1;
+
+ printf("Intentional Lapack error (appears only for 64-bit INTEGER):\n");
+ sgeqrf_(&mi, &n, c, &m, tau, &work1, &lwork, (FINTEGER*)&info);
+
+ // sgeqrf_ (&m, &n, c, &zeroi, tau, &work1, &lwork, (FINTEGER*)&info);
+ printf("info=%016lx\n", info);
+
+ if (info >> 32 == 0x64b) {
+ printf("Lapack uses 32-bit integers\n");
+ } else {
+ printf("Lapack uses 64-bit integers\n");
+ }
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/CMakeLists.txt
new file mode 100644
index 0000000..e89d115
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/CMakeLists.txt
@@ -0,0 +1,49 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# @lint-ignore-every LINEWRAP
+project(faiss_perf_tests)
+set(BENCHMARK_ENABLE_TESTING OFF)
+
+include(FetchContent)
+FetchContent_Declare(googlebenchmark
+ GIT_REPOSITORY https://github.com/google/benchmark.git
+ GIT_TAG main) # need main for benchmark::benchmark
+FetchContent_MakeAvailable(
+ googlebenchmark)
+
+
+find_package(Threads REQUIRED)
+find_package(OpenMP REQUIRED)
+find_package(gflags REQUIRED)
+
+add_library(faiss_perf_tests_utils
+ utils.cpp
+)
+# `#include <faiss/perf_tests/utils.h>` or any other headers
+target_include_directories(faiss_perf_tests_utils PRIVATE
+ ${PROJECT_SOURCE_DIR}/../..)
+
+include(../cmake/link_to_faiss_lib.cmake)
+
+link_to_faiss_lib(faiss_perf_tests_utils)
+
+set(FAISS_PERF_TEST_SRC
+ bench_no_multithreading_rcq_search.cpp
+ bench_scalar_quantizer_accuracy.cpp
+ bench_scalar_quantizer_decode.cpp
+ bench_scalar_quantizer_distance.cpp
+ bench_scalar_quantizer_encode.cpp
+)
+foreach(bench ${FAISS_PERF_TEST_SRC})
+ get_filename_component(bench_exec ${bench} NAME_WE)
+ add_executable(${bench_exec} ${bench})
+ link_to_faiss_lib(${bench_exec})
+ target_link_libraries(${bench_exec} PRIVATE faiss_perf_tests_utils OpenMP::OpenMP_CXX benchmark::benchmark gflags)
+ # `#include <faiss/perf_tests/utils.h>` or any other headers
+ target_include_directories(${bench_exec} PRIVATE
+ ${PROJECT_SOURCE_DIR}/../..)
+
+endforeach()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_hnsw.py b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_hnsw.py
new file mode 100644
index 0000000..d6ac59d
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_hnsw.py
@@ -0,0 +1,204 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import argparse
+import resource
+import time
+from contextlib import contextmanager
+from dataclasses import dataclass
+from typing import Dict, Generator, List, Optional
+
+import faiss # @manual=//faiss/python:pyfaiss
+import numpy as np
+from faiss.contrib.datasets import ( # @manual=//faiss/contrib:faiss_contrib
+ Dataset,
+ SyntheticDataset,
+)
+
+US_IN_S = 1_000_000
+
+
+@dataclass
+class PerfCounters:
+ wall_time_s: float = 0.0
+ user_time_s: float = 0.0
+ system_time_s: float = 0.0
+
+
+@contextmanager
+def timed_execution() -> Generator[PerfCounters, None, None]:
+ pcounters = PerfCounters()
+ wall_time_start = time.perf_counter()
+ rusage_start = resource.getrusage(resource.RUSAGE_SELF)
+ yield pcounters
+ wall_time_end = time.perf_counter()
+ rusage_end = resource.getrusage(resource.RUSAGE_SELF)
+ pcounters.wall_time_s = wall_time_end - wall_time_start
+ pcounters.user_time_s = rusage_end.ru_utime - rusage_start.ru_utime
+ pcounters.system_time_s = rusage_end.ru_stime - rusage_start.ru_stime
+
+
+def is_perf_counter(key: str) -> bool:
+ return key.endswith("_time_us")
+
+
+def accumulate_perf_counter(
+ phase: str,
+ t: PerfCounters,
+ counters: Dict[str, int]
+):
+ counters[f"{phase}_wall_time_us"] = int(t.wall_time_s * US_IN_S)
+ counters[f"{phase}_user_time_us"] = int(t.user_time_s * US_IN_S)
+
+
+def run_on_dataset(
+ ds: Dataset,
+ M: int,
+ num_threads: int,
+ num_add_iterations: int,
+ num_search_iterations: int,
+ efSearch: int = 16,
+ efConstruction: int = 40,
+ search_bounded_queue: bool = True,
+) -> Dict[str, int]:
+ xq = ds.get_queries()
+ xb = ds.get_database()
+
+ nb, d = xb.shape
+ nq, d = xq.shape
+
+ k = 10
+ # pyre-ignore[16]: Module `faiss` has no attribute `omp_set_num_threads`.
+ faiss.omp_set_num_threads(num_threads)
+ index = faiss.IndexHNSWFlat(d, M)
+ index.hnsw.efConstruction = efConstruction # default
+ with timed_execution() as t:
+ for _ in range(num_add_iterations):
+ index.add(xb)
+ counters = {}
+ accumulate_perf_counter("add", t, counters)
+ counters["nb"] = nb
+ counters["num_add_iterations"] = num_add_iterations
+
+ index.hnsw.efSearch = efSearch
+ index.hnsw.search_bounded_queue = search_bounded_queue
+ with timed_execution() as t:
+ for _ in range(num_search_iterations):
+ D, I = index.search(xq, k)
+ accumulate_perf_counter("search", t, counters)
+ counters["nq"] = nq
+ counters["efSearch"] = efSearch
+ counters["efConstruction"] = efConstruction
+ counters["M"] = M
+ counters["d"] = d
+ counters["num_search_iterations"] = num_search_iterations
+
+ return counters
+
+
+def run(
+ d: int,
+ nb: int,
+ nq: int,
+ M: int,
+ num_threads: int,
+ num_add_iterations: int = 1,
+ num_search_iterations: int = 1,
+ efSearch: int = 16,
+ efConstruction: int = 40,
+ search_bounded_queue: bool = True,
+) -> Dict[str, int]:
+ ds = SyntheticDataset(d=d, nb=nb, nt=0, nq=nq, metric="L2", seed=1338)
+ return run_on_dataset(
+ ds,
+ M=M,
+ num_add_iterations=num_add_iterations,
+ num_search_iterations=num_search_iterations,
+ num_threads=num_threads,
+ efSearch=efSearch,
+ efConstruction=efConstruction,
+ search_bounded_queue=search_bounded_queue,
+ )
+
+
+def _accumulate_counters(
+ element: Dict[str, int], accu: Optional[Dict[str, List[int]]] = None
+) -> Dict[str, List[int]]:
+ if accu is None:
+ accu = {key: [value] for key, value in element.items()}
+ return accu
+ else:
+ assert accu.keys() <= element.keys(), (
+ "Accu keys must be a subset of element keys: "
+ f"{accu.keys()} not a subset of {element.keys()}"
+ )
+ for key in accu.keys():
+ accu[key].append(element[key])
+ return accu
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Benchmark HNSW")
+ parser.add_argument("--M", type=int, default=32)
+ parser.add_argument("--num-threads", type=int, default=5)
+ parser.add_argument("--warm-up-iterations", type=int, default=0)
+ parser.add_argument("--num-search-iterations", type=int, default=1)
+ parser.add_argument("--num-add-iterations", type=int, default=1)
+ parser.add_argument("--num-repetitions", type=int, default=1)
+ parser.add_argument("--ef-search", type=int, default=16)
+ parser.add_argument("--ef-construction", type=int, default=40)
+ parser.add_argument("--search-bounded-queue", action="store_true")
+
+ parser.add_argument("--nb", type=int, default=5000)
+ parser.add_argument("--nq", type=int, default=500)
+ parser.add_argument("--d", type=int, default=128)
+ args = parser.parse_args()
+
+ if args.warm_up_iterations > 0:
+ print(f"Warming up for {args.warm_up_iterations} iterations...")
+ # warm-up
+ run(
+ num_search_iterations=args.warm_up_iterations,
+ num_add_iterations=args.warm_up_iterations,
+ d=args.d,
+ nb=args.nb,
+ nq=args.nq,
+ M=args.M,
+ num_threads=args.num_threads,
+ efSearch=args.ef_search,
+ efConstruction=args.ef_construction,
+ search_bounded_queue=args.search_bounded_queue,
+ )
+ print(
+ f"Running benchmark with dataset(nb={args.nb}, nq={args.nq}, "
+ f"d={args.d}), M={args.M}, num_threads={args.num_threads}, "
+ f"efSearch={args.ef_search}, efConstruction={args.ef_construction}"
+ )
+ result = None
+ for _ in range(args.num_repetitions):
+ counters = run(
+ num_search_iterations=args.num_search_iterations,
+ num_add_iterations=args.num_add_iterations,
+ d=args.d,
+ nb=args.nb,
+ nq=args.nq,
+ M=args.M,
+ num_threads=args.num_threads,
+ efSearch=args.ef_search,
+ efConstruction=args.ef_construction,
+ search_bounded_queue=args.search_bounded_queue,
+ )
+ result = _accumulate_counters(counters, result)
+ assert result is not None
+ for counter, values in result.items():
+ if is_perf_counter(counter):
+ print(
+ "%s t=%.3f us (± %.4f)" %
+ (counter, np.mean(values), np.std(values))
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_no_multithreading_rcq_search.cpp b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_no_multithreading_rcq_search.cpp
new file mode 100644
index 0000000..e684d6a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_no_multithreading_rcq_search.cpp
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gflags/gflags.h>
+
+#include <benchmark/benchmark.h>
+#include <faiss/IndexAdditiveQuantizer.h> // @manual=//faiss:faiss_no_multithreading
+#include <faiss/utils/random.h> // @manual=//faiss:faiss_no_multithreading
+
+using namespace faiss;
+DEFINE_uint32(iterations, 20, "iterations");
+DEFINE_uint32(nprobe, 1, "nprobe");
+DEFINE_uint32(batch_size, 1, "batch_size");
+DEFINE_double(beam_factor, 4.0, "beam factor");
+
+static void bench_search(
+ benchmark::State& state,
+ int batch_size,
+ int nprobe,
+ float beam_factor) {
+ int d = 512;
+ int nt = 2 << 15;
+ std::vector<float> xt(d * nt);
+
+ float_rand(xt.data(), d * nt, 12345);
+ ResidualCoarseQuantizer rq(d, {16, 8});
+ rq.verbose = false;
+ rq.train(nt, xt.data());
+
+ std::vector<float> xq(d * batch_size);
+ float_rand(xq.data(), d * batch_size, 12345);
+
+ std::vector<float> distances(nprobe * batch_size);
+ std::vector<int64_t> clusterIndices(nprobe * batch_size);
+ SearchParametersResidualCoarseQuantizer param;
+ param.beam_factor = beam_factor;
+ for (auto _ : state) {
+ rq.search(
+ batch_size,
+ xq.data(),
+ nprobe,
+ distances.data(),
+ clusterIndices.data(),
+ &param);
+ }
+}
+
+int main(int argc, char** argv) {
+ benchmark::Initialize(&argc, argv);
+ gflags::AllowCommandLineReparsing();
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+ int iterations = FLAGS_iterations;
+ int nprobe = FLAGS_nprobe;
+ float beam_factor = FLAGS_beam_factor;
+ int batch_size = FLAGS_batch_size;
+ benchmark::RegisterBenchmark(
+ "search", bench_search, batch_size, nprobe, beam_factor)
+ ->Iterations(iterations);
+ benchmark::RunSpecifiedBenchmarks();
+ benchmark::Shutdown();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_accuracy.cpp b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_accuracy.cpp
new file mode 100644
index 0000000..bde9939
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_accuracy.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/perf_tests/utils.h>
+#include <gflags/gflags.h>
+#include <cstdio>
+#include <map>
+
+#include <benchmark/benchmark.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+
+using namespace faiss;
+DEFINE_uint32(d, 128, "dimension");
+DEFINE_uint32(n, 2000, "dimension");
+DEFINE_uint32(iterations, 20, "iterations");
+
+static void bench_reconstruction_error(
+ benchmark::State& state,
+ ScalarQuantizer::QuantizerType type,
+ int d,
+ int n) {
+ std::vector<float> x(d * n);
+
+ float_rand(x.data(), d * n, 12345);
+
+ // make sure it's idempotent
+ ScalarQuantizer sq(d, type);
+
+ sq.train(n, x.data());
+
+ size_t code_size = sq.code_size;
+ state.counters["code_size"] = sq.code_size;
+
+ // encode
+ std::vector<uint8_t> codes(code_size * n);
+ sq.compute_codes(x.data(), codes.data(), n);
+
+ // decode
+ std::vector<float> x2(d * n);
+ sq.decode(codes.data(), x2.data(), n);
+
+ state.counters["sql2_recons_error"] =
+ fvec_L2sqr(x.data(), x2.data(), n * d) / n;
+
+ // encode again
+ std::vector<uint8_t> codes2(code_size * n);
+ sq.compute_codes(x2.data(), codes2.data(), n);
+
+ size_t ndiff = 0;
+ for (size_t i = 0; i < codes.size(); i++) {
+ if (codes[i] != codes2[i])
+ ndiff++;
+ }
+
+ state.counters["ndiff_for_idempotence"] = ndiff;
+
+ state.counters["code_size_two"] = codes.size();
+}
+
+int main(int argc, char** argv) {
+ benchmark::Initialize(&argc, argv);
+ gflags::AllowCommandLineReparsing();
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+ int iterations = FLAGS_iterations;
+ int d = FLAGS_d;
+ int n = FLAGS_n;
+ auto benchs = ::perf_tests::sq_types();
+
+ for (auto& [bench_name, quantizer_type] : benchs) {
+ benchmark::RegisterBenchmark(
+ bench_name.c_str(),
+ bench_reconstruction_error,
+ quantizer_type,
+ d,
+ n)
+ ->Iterations(iterations);
+ }
+
+ benchmark::RunSpecifiedBenchmarks();
+ benchmark::Shutdown();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_decode.cpp b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_decode.cpp
new file mode 100644
index 0000000..16d1502
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_decode.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/perf_tests/utils.h>
+#include <gflags/gflags.h>
+#include <omp.h>
+#include <cstdio>
+#include <map>
+
+#include <benchmark/benchmark.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/utils/random.h>
+
+using namespace faiss;
+DEFINE_uint32(d, 128, "dimension");
+DEFINE_uint32(n, 2000, "dimension");
+DEFINE_uint32(iterations, 20, "iterations");
+
+static void bench_decode(
+ benchmark::State& state,
+ ScalarQuantizer::QuantizerType type,
+ int d,
+ int n) {
+ std::vector<float> x(d * n);
+
+ float_rand(x.data(), d * n, 12345);
+
+ // make sure it's idempotent
+ ScalarQuantizer sq(d, type);
+
+ omp_set_num_threads(1);
+
+ sq.train(n, x.data());
+
+ size_t code_size = sq.code_size;
+ state.counters["code_size"] = sq.code_size;
+
+ // encode
+ std::vector<uint8_t> codes(code_size * n);
+ sq.compute_codes(x.data(), codes.data(), n);
+ std::vector<float> x2(d * n);
+
+ for (auto _ : state) {
+ // decode
+ sq.decode(codes.data(), x2.data(), n);
+ }
+}
+
+int main(int argc, char** argv) {
+ benchmark::Initialize(&argc, argv);
+ gflags::AllowCommandLineReparsing();
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+ int iterations = FLAGS_iterations;
+ int d = FLAGS_d;
+ int n = FLAGS_n;
+ auto benchs = ::perf_tests::sq_types();
+
+ for (auto& [bench_name, quantizer_type] : benchs) {
+ benchmark::RegisterBenchmark(
+ bench_name.c_str(), bench_decode, quantizer_type, d, n)
+ ->Iterations(iterations);
+ }
+
+ benchmark::RunSpecifiedBenchmarks();
+ benchmark::Shutdown();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_distance.cpp b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_distance.cpp
new file mode 100644
index 0000000..8a32d69
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_distance.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gflags/gflags.h>
+#include <omp.h>
+#include <cstdio>
+#include <map>
+
+#include <benchmark/benchmark.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/perf_tests/utils.h>
+#include <faiss/utils/random.h>
+
+using namespace faiss;
+DEFINE_uint32(d, 128, "dimension");
+DEFINE_uint32(n, 2000, "dimension");
+DEFINE_uint32(iterations, 20, "iterations");
+
+static void bench_distance(
+ benchmark::State& state,
+ ScalarQuantizer::QuantizerType type,
+ int d,
+ int n) {
+ std::vector<float> x(d * n);
+
+ float_rand(x.data(), d * n, 12345);
+
+ // make sure it's idempotent
+ ScalarQuantizer sq(d, type);
+
+ omp_set_num_threads(1);
+
+ sq.train(n, x.data());
+
+ size_t code_size = sq.code_size;
+ state.counters["code_size"] = sq.code_size;
+
+ // encode
+ std::vector<uint8_t> codes(code_size * n);
+ sq.compute_codes(x.data(), codes.data(), n);
+
+ std::unique_ptr<ScalarQuantizer::SQDistanceComputer> dc(
+ sq.get_distance_computer());
+ dc->codes = codes.data();
+ dc->code_size = sq.code_size;
+
+ for (auto _ : state) {
+ float sum_dis = 0;
+ for (int i = 0; i < n; i++) {
+ dc->set_query(&x[i * d]);
+ for (int j = 0; j < n; j++) {
+ benchmark::DoNotOptimize(sum_dis += (*dc)(j));
+ }
+ }
+ }
+}
+
+int main(int argc, char** argv) {
+ benchmark::Initialize(&argc, argv);
+ gflags::AllowCommandLineReparsing();
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+ int iterations = FLAGS_iterations;
+ int d = FLAGS_d;
+ int n = FLAGS_n;
+ auto benchs = ::perf_tests::sq_types();
+
+ for (auto& [bench_name, quantizer_type] : benchs) {
+ benchmark::RegisterBenchmark(
+ bench_name.c_str(), bench_distance, quantizer_type, d, n)
+ ->Iterations(iterations);
+ }
+ benchmark::RunSpecifiedBenchmarks();
+ benchmark::Shutdown();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_encode.cpp b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_encode.cpp
new file mode 100644
index 0000000..0e4909c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/bench_scalar_quantizer_encode.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gflags/gflags.h>
+#include <omp.h>
+#include <cstdio>
+#include <map>
+
+#include <benchmark/benchmark.h>
+#include <faiss/impl/ScalarQuantizer.h>
+#include <faiss/perf_tests/utils.h>
+#include <faiss/utils/distances.h>
+#include <faiss/utils/random.h>
+
+using namespace faiss;
+DEFINE_uint32(d, 128, "dimension");
+DEFINE_uint32(n, 2000, "dimension");
+DEFINE_uint32(iterations, 20, "iterations");
+
+static void bench_encode(
+ benchmark::State& state,
+ ScalarQuantizer::QuantizerType type,
+ int d,
+ int n) {
+ std::vector<float> x(d * n);
+
+ float_rand(x.data(), d * n, 12345);
+ ScalarQuantizer sq(d, type);
+
+ omp_set_num_threads(1);
+ size_t code_size = sq.code_size;
+
+ sq.train(n, x.data());
+ state.counters["code_size"] = sq.code_size;
+ std::vector<uint8_t> codes(code_size * n);
+
+ for (auto _ : state) {
+ // encode
+ sq.compute_codes(x.data(), codes.data(), n);
+ }
+}
+
+int main(int argc, char** argv) {
+ benchmark::Initialize(&argc, argv);
+ gflags::AllowCommandLineReparsing();
+ gflags::ParseCommandLineFlags(&argc, &argv, true);
+ int iterations = FLAGS_iterations;
+ int d = FLAGS_d;
+ int n = FLAGS_n;
+ auto benchs = ::perf_tests::sq_types();
+
+ for (auto& [bench_name, quantizer_type] : benchs) {
+ benchmark::RegisterBenchmark(
+ bench_name.c_str(), bench_encode, quantizer_type, d, n)
+ ->Iterations(iterations);
+ }
+
+ benchmark::RunSpecifiedBenchmarks();
+ benchmark::Shutdown();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/utils.cpp b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/utils.cpp
new file mode 100644
index 0000000..9f505a4
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/utils.cpp
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/perf_tests/utils.h>
+namespace faiss::perf_tests {
+std::map<std::string, faiss::ScalarQuantizer::QuantizerType> sq_types() {
+ static std::map<std::string, faiss::ScalarQuantizer::QuantizerType>
+ sq_types = {
+ {"QT_8bit", faiss::ScalarQuantizer::QT_8bit},
+ {"QT_4bit", faiss::ScalarQuantizer::QT_4bit},
+ {"QT_8bit_uniform",
+ faiss::ScalarQuantizer::QT_8bit_uniform},
+ {"QT_4bit_uniform",
+ faiss::ScalarQuantizer::QT_4bit_uniform},
+ {"QT_fp16", faiss::ScalarQuantizer::QT_fp16},
+ {"QT_8bit_direct", faiss::ScalarQuantizer::QT_8bit_direct},
+ {"QT_6bit", faiss::ScalarQuantizer::QT_6bit},
+ {"QT_bf16", faiss::ScalarQuantizer::QT_bf16},
+ {"QT_8bit_direct_signed",
+ faiss::ScalarQuantizer::QT_8bit_direct_signed}};
+ return sq_types;
+}
+} // namespace faiss::perf_tests
diff --git a/packages/leann-backend-hnsw/third_party/faiss/perf_tests/utils.h b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/utils.h
new file mode 100644
index 0000000..08cf5ac
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/perf_tests/utils.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#pragma once
+#include <faiss/impl/ScalarQuantizer.h>
+#include <map>
+
+namespace faiss::perf_tests {
+
+std::map<std::string, faiss::ScalarQuantizer::QuantizerType> sq_types();
+
+} // namespace faiss::perf_tests
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/tests/CMakeLists.txt
new file mode 100644
index 0000000..285b909
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/CMakeLists.txt
@@ -0,0 +1,92 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+set(FAISS_TEST_SRC
+ test_binary_flat.cpp
+ test_dealloc_invlists.cpp
+ test_ivfpq_codec.cpp
+ test_ivfpq_indexing.cpp
+ test_lowlevel_ivf.cpp
+ test_ivf_index.cpp
+ test_merge.cpp
+ test_omp_threads.cpp
+ test_ondisk_ivf.cpp
+ test_pairs_decoding.cpp
+ test_params_override.cpp
+ test_pq_encoding.cpp
+ test_sliding_ivf.cpp
+ test_threaded_index.cpp
+ test_transfer_invlists.cpp
+ test_mem_leak.cpp
+ test_cppcontrib_sa_decode.cpp
+ test_cppcontrib_uintreader.cpp
+ test_simdlib.cpp
+ test_approx_topk.cpp
+ test_RCQ_cropping.cpp
+ test_distances_simd.cpp
+ test_heap.cpp
+ test_code_distance.cpp
+ test_hnsw.cpp
+ test_partitioning.cpp
+ test_fastscan_perf.cpp
+ test_disable_pq_sdc_tables.cpp
+ test_common_ivf_empty_index.cpp
+ test_callback.cpp
+ test_utils.cpp
+ test_hamming.cpp
+ test_mmap.cpp
+ test_zerocopy.cpp
+)
+
+add_executable(faiss_test ${FAISS_TEST_SRC})
+
+include(../cmake/link_to_faiss_lib.cmake)
+
+link_to_faiss_lib(faiss_test)
+
+if (FAISS_ENABLE_PYTHON)
+ target_link_libraries(faiss_test PUBLIC faiss_example_external_module)
+endif()
+
+include(FetchContent)
+FetchContent_Declare(
+ googletest
+ GIT_REPOSITORY https://github.com/google/googletest.git
+ GIT_TAG 58d77fa8070e8cec2dc1ed015d66b454c8d78850 # release-1.12.1
+ OVERRIDE_FIND_PACKAGE)
+set(BUILD_GMOCK CACHE BOOL OFF)
+set(INSTALL_GTEST CACHE BOOL OFF)
+FetchContent_MakeAvailable(googletest)
+
+if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
+ AND NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
+ file(
+ WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
+ [=[
+include(CMakeFindDependencyMacro)
+find_dependency(googletest)
+if(NOT TARGET GTest::GTest)
+ add_library(GTest::GTest INTERFACE IMPORTED)
+ target_link_libraries(GTest::GTest INTERFACE GTest::gtest)
+endif()
+if(NOT TARGET GTest::Main)
+ add_library(GTest::Main INTERFACE IMPORTED)
+ target_link_libraries(GTest::Main INTERFACE GTest::gtest_main)
+endif()
+]=])
+endif()
+
+find_package(OpenMP REQUIRED)
+find_package(GTest CONFIG REQUIRED)
+
+target_link_libraries(faiss_test PRIVATE
+ OpenMP::OpenMP_CXX
+ GTest::gtest_main
+ $<$<BOOL:${FAISS_ENABLE_ROCM}>:hip::host>
+)
+
+# Defines `gtest_discover_tests()`.
+include(GoogleTest)
+gtest_discover_tests(faiss_test)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/common_faiss_tests.py b/packages/leann-backend-hnsw/third_party/faiss/tests/common_faiss_tests.py
new file mode 100644
index 0000000..b945055
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/common_faiss_tests.py
@@ -0,0 +1,127 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+# a few common functions for the tests
+
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+import numpy as np
+import faiss
+
+# reduce number of threads to avoid excessive nb of threads in opt
+# mode (recuces runtime from 100s to 4s!)
+faiss.omp_set_num_threads(4)
+
+
+def random_unitary(n, d, seed):
+ x = faiss.randn(n * d, seed).reshape(n, d)
+ faiss.normalize_L2(x)
+ return x
+
+
+class Randu10k:
+
+ def __init__(self):
+ self.nb = 10000
+ self.nq = 1000
+ self.nt = 10000
+ self.d = 128
+
+ self.xb = random_unitary(self.nb, self.d, 1)
+ self.xt = random_unitary(self.nt, self.d, 2)
+ self.xq = random_unitary(self.nq, self.d, 3)
+
+ dotprods = np.dot(self.xq, self.xb.T)
+ self.gt = dotprods.argmax(1)
+ self.k = 100
+
+ def launch(self, name, index):
+ if not index.is_trained:
+ index.train(self.xt)
+ index.add(self.xb)
+ return index.search(self.xq, self.k)
+
+ def evalres(self, DI):
+ D, I = DI
+ e = {}
+ for rank in 1, 10, 100:
+ e[rank] = ((I[:, :rank] == self.gt.reshape(-1, 1)).sum() /
+ float(self.nq))
+ return e
+
+
+class Randu10kUnbalanced(Randu10k):
+
+ def __init__(self):
+ Randu10k.__init__(self)
+
+ weights = 0.95 ** np.arange(self.d)
+ rs = np.random.RandomState(123)
+ weights = weights[rs.permutation(self.d)]
+ self.xb *= weights
+ self.xb /= np.linalg.norm(self.xb, axis=1)[:, np.newaxis]
+ self.xq *= weights
+ self.xq /= np.linalg.norm(self.xq, axis=1)[:, np.newaxis]
+ self.xt *= weights
+ self.xt /= np.linalg.norm(self.xt, axis=1)[:, np.newaxis]
+
+ dotprods = np.dot(self.xq, self.xb.T)
+ self.gt = dotprods.argmax(1)
+ self.k = 100
+
+
+def get_dataset(d, nb, nt, nq):
+ rs = np.random.RandomState(123)
+ xb = rs.rand(nb, d).astype('float32')
+ xt = rs.rand(nt, d).astype('float32')
+ xq = rs.rand(nq, d).astype('float32')
+
+ return (xt, xb, xq)
+
+
+def get_dataset_2(d, nt, nb, nq):
+ """A dataset that is not completely random but still challenging to
+ index
+ """
+ d1 = 10 # intrinsic dimension (more or less)
+ n = nb + nt + nq
+ rs = np.random.RandomState(1338)
+ x = rs.normal(size=(n, d1))
+ x = np.dot(x, rs.rand(d1, d))
+ # now we have a d1-dim ellipsoid in d-dimensional space
+ # higher factor (>4) -> higher frequency -> less linear
+ x = x * (rs.rand(d) * 4 + 0.1)
+ x = np.sin(x)
+ x = x.astype('float32')
+ return x[:nt], x[nt:nt + nb], x[nt + nb:]
+
+
+def make_binary_dataset(d, nt, nb, nq):
+ assert d % 8 == 0
+ rs = np.random.RandomState(123)
+ x = rs.randint(256, size=(nb + nq + nt, int(d / 8))).astype('uint8')
+ return x[:nt], x[nt:-nq], x[-nq:]
+
+
+def compare_binary_result_lists(D1, I1, D2, I2):
+ """comparing result lists is difficult because there are many
+ ties. Here we sort by (distance, index) pairs and ignore the largest
+ distance of each result. Compatible result lists should pass this."""
+ assert D1.shape == I1.shape == D2.shape == I2.shape
+ n, k = D1.shape
+ ndiff = (D1 != D2).sum()
+ assert ndiff == 0, '%d differences in distance matrix %s' % (
+ ndiff, D1.shape)
+
+ def normalize_DI(D, I):
+ norm = I.max() + 1.0
+ Dr = D.astype('float64') + I / norm
+ # ignore -1s and elements on last column
+ Dr[I1 == -1] = 1e20
+ Dr[D == D[:, -1:]] = 1e20
+ Dr.sort(axis=1)
+ return Dr
+ ndiff = (normalize_DI(D1, I1) != normalize_DI(D2, I2)).sum()
+ assert ndiff == 0, '%d differences in normalized D matrix' % ndiff
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/external_module_test.py b/packages/leann-backend-hnsw/third_party/faiss/tests/external_module_test.py
new file mode 100644
index 0000000..15f2809
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/external_module_test.py
@@ -0,0 +1,66 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import unittest
+
+import faiss
+
+import faiss.faiss_example_external_module as external_module
+
+import numpy as np
+
+
+class TestCustomIDSelector(unittest.TestCase):
+ """test if we can construct a custom IDSelector"""
+
+ def test_IDSelector(self):
+ ids = external_module.IDSelectorModulo(3)
+ self.assertFalse(ids.is_member(1))
+ self.assertTrue(ids.is_member(3))
+
+
+class TestArrayConversions(unittest.TestCase):
+
+ def test_idx_array(self):
+ tab = np.arange(10).astype("int64")
+ new_sum = external_module.sum_of_idx(len(tab), faiss.swig_ptr(tab))
+ self.assertEqual(new_sum, tab.sum())
+
+ def do_array_test(self, ty):
+ tab = np.arange(10).astype(ty)
+ func = getattr(external_module, "sum_of_" + ty)
+ print("perceived type", faiss.swig_ptr(tab))
+ new_sum = func(len(tab), faiss.swig_ptr(tab))
+ self.assertEqual(new_sum, tab.sum())
+
+ def test_sum_uint8(self):
+ self.do_array_test("uint8")
+
+ def test_sum_uint16(self):
+ self.do_array_test("uint16")
+
+ def test_sum_uint32(self):
+ self.do_array_test("uint32")
+
+ def test_sum_uint64(self):
+ self.do_array_test("uint64")
+
+ def test_sum_int8(self):
+ self.do_array_test("int8")
+
+ def test_sum_int16(self):
+ self.do_array_test("int16")
+
+ def test_sum_int32(self):
+ self.do_array_test("int32")
+
+ def test_sum_int64(self):
+ self.do_array_test("int64")
+
+ def test_sum_float32(self):
+ self.do_array_test("float32")
+
+ def test_sum_float64(self):
+ self.do_array_test("float64")
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_NSG_compressed_graph.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_NSG_compressed_graph.cpp
new file mode 100644
index 0000000..36b6f5c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_NSG_compressed_graph.cpp
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexNSG.h>
+#include <faiss/utils/hamming.h>
+#include <faiss/utils/random.h>
+#include <gtest/gtest.h>
+
+using namespace faiss;
+
+using FinalNSGGraph = nsg::Graph<int32_t>;
+
+struct CompressedNSGGraph : FinalNSGGraph {
+ int bits;
+ size_t stride;
+ std::vector<uint8_t> compressed_data;
+
+ CompressedNSGGraph(const FinalNSGGraph& graph, int bits)
+ : FinalNSGGraph(graph.data, graph.N, graph.K), bits(bits) {
+ FAISS_THROW_IF_NOT((1 << bits) >= K + 1);
+ stride = (K * bits + 7) / 8;
+ compressed_data.resize(N * stride);
+ for (size_t i = 0; i < N; i++) {
+ BitstringWriter writer(compressed_data.data() + i * stride, stride);
+ for (size_t j = 0; j < K; j++) {
+ int32_t v = graph.data[i * K + j];
+ if (v == -1) {
+ writer.write(K + 1, bits);
+ break;
+ } else {
+ writer.write(v, bits);
+ }
+ }
+ }
+ data = nullptr;
+ }
+
+ size_t get_neighbors(int i, int32_t* neighbors) const override {
+ BitstringReader reader(compressed_data.data() + i * stride, stride);
+ for (int j = 0; j < K; j++) {
+ int32_t v = reader.read(bits);
+ if (v == K + 1) {
+ return j;
+ }
+ neighbors[j] = v;
+ }
+ return K;
+ }
+};
+
+TEST(NSGCompressed, test_compressed) {
+ size_t nq = 10, nt = 0, nb = 5000, d = 32, k = 10;
+
+ using idx_t = faiss::idx_t;
+
+ std::vector<float> buf((nq + nb + nt) * d);
+ faiss::rand_smooth_vectors(nq + nb + nt, d, buf.data(), 1234);
+ const float* xt = buf.data();
+ const float* xb = xt + nt * d;
+ const float* xq = xb + nb * d;
+
+ faiss::IndexNSGFlat index(d, 32);
+
+ index.add(nb, xb);
+
+ std::vector<faiss::idx_t> Iref(nq * k);
+ std::vector<float> Dref(nq * k);
+ index.search(nq, xq, k, Dref.data(), Iref.data());
+
+ // replace the shared ptr
+ index.nsg.final_graph.reset(
+ new CompressedNSGGraph(*index.nsg.final_graph, 13));
+
+ std::vector<idx_t> I(nq * k);
+ std::vector<float> D(nq * k);
+ index.search(nq, xq, k, D.data(), I.data());
+
+ // make sure we find back the original results
+ EXPECT_EQ(Iref, I);
+ EXPECT_EQ(Dref, D);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_RCQ_cropping.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_RCQ_cropping.cpp
new file mode 100644
index 0000000..593fd2a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_RCQ_cropping.cpp
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexAdditiveQuantizer.h>
+#include <faiss/IndexScalarQuantizer.h>
+#include <faiss/utils/random.h>
+#include <gtest/gtest.h>
+
+/* This test creates a 3-level RCQ and performs a search on it.
+ * Then it crops the RCQ to just the 2 first levels and verifies that
+ * the 3-level vectors are in a subtree that was visited in the 2-level RCQ. */
+TEST(RCQCropping, test_cropping) {
+ size_t nq = 10, nt = 2000, nb = 1000, d = 32;
+
+ using idx_t = faiss::idx_t;
+
+ std::vector<float> buf((nq + nb + nt) * d);
+ faiss::rand_smooth_vectors(nq + nb + nt, d, buf.data(), 1234);
+ const float* xt = buf.data();
+ const float* xb = xt + nt * d;
+ const float* xq = xb + nb * d;
+
+ std::vector<size_t> nbits = {5, 4, 4};
+ faiss::ResidualCoarseQuantizer rcq(d, nbits);
+
+ rcq.train(nt, xt);
+
+ // the test below works only for beam size == nprobe
+ rcq.set_beam_factor(1.0);
+
+ // perform search
+ int nprobe = 15;
+ std::vector<faiss::idx_t> Iref(nq * nprobe);
+ std::vector<float> Dref(nq * nprobe);
+ rcq.search(nq, xq, nprobe, Dref.data(), Iref.data());
+
+ // crop to the first 2 quantization levels
+ int last_nbits = nbits.back();
+ nbits.pop_back();
+ faiss::ResidualCoarseQuantizer rcq_cropped(d, nbits);
+ rcq_cropped.initialize_from(rcq);
+
+ EXPECT_EQ(rcq_cropped.ntotal, rcq.ntotal >> last_nbits);
+
+ // perform search
+ std::vector<faiss::idx_t> Inew(nq * nprobe);
+ std::vector<float> Dnew(nq * nprobe);
+ rcq_cropped.search(nq, xq, nprobe, Dnew.data(), Inew.data());
+
+ // these bits are in common between the two RCQs
+ idx_t mask = ((idx_t)1 << rcq_cropped.rq.tot_bits) - 1;
+ for (int q = 0; q < nq; q++) {
+ for (int i = 0; i < nprobe; i++) {
+ idx_t fine = Iref[q * nprobe + i];
+ EXPECT_GE(fine, 0);
+ bool found = false;
+
+ // fine should be generated from a path that passes through coarse
+ for (int j = 0; j < nprobe; j++) {
+ idx_t coarse = Inew[q * nprobe + j];
+ if ((fine & mask) == coarse) {
+ found = true;
+ break;
+ }
+ }
+ EXPECT_TRUE(found);
+ }
+ }
+}
+
+TEST(RCQCropping, search_params) {
+ size_t nq = 10, nt = 2000, nb = 1000, d = 32;
+
+ using idx_t = faiss::idx_t;
+
+ std::vector<float> buf((nq + nb + nt) * d);
+ faiss::rand_smooth_vectors(nq + nb + nt, d, buf.data(), 1234);
+ const float* xt = buf.data();
+ const float* xb = xt + nt * d;
+ const float* xq = xb + nb * d;
+
+ std::vector<size_t> nbits = {3, 6, 3};
+ faiss::ResidualCoarseQuantizer quantizer(d, nbits);
+ size_t ntotal = (size_t)1 << quantizer.rq.tot_bits;
+ faiss::IndexIVFScalarQuantizer index(
+ &quantizer, d, ntotal, faiss::ScalarQuantizer::QT_8bit);
+ index.quantizer_trains_alone = true;
+
+ index.train(nt, xt);
+ index.add(nb, xb);
+
+ index.nprobe = 10;
+
+ int k = 4;
+ float beam_factor_1 = 8.0;
+ quantizer.set_beam_factor(beam_factor_1);
+ std::vector<idx_t> I1(nq * k);
+ std::vector<float> D1(nq * k);
+ index.search(nq, xq, k, D1.data(), I1.data());
+
+ // change from 8 to 1
+ quantizer.set_beam_factor(1.0f);
+ std::vector<idx_t> I2(nq * k);
+ std::vector<float> D2(nq * k);
+ index.search(nq, xq, k, D2.data(), I2.data());
+
+ // make sure it changes the result
+ EXPECT_NE(I1, I2);
+ EXPECT_NE(D1, D2);
+
+ // override the class level beam factor
+ faiss::SearchParametersResidualCoarseQuantizer params1;
+ params1.beam_factor = beam_factor_1;
+ faiss::SearchParametersIVF params;
+ params.nprobe = index.nprobe;
+ params.quantizer_params = &params1;
+
+ std::vector<idx_t> I3(nq * k);
+ std::vector<float> D3(nq * k);
+ index.search(nq, xq, k, D3.data(), I3.data(), &params);
+
+ // make sure we find back the original results
+ EXPECT_EQ(I1, I3);
+ EXPECT_EQ(D1, D3);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_approx_topk.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_approx_topk.cpp
new file mode 100644
index 0000000..ff4ee1f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_approx_topk.cpp
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <chrono>
+#include <cstdint>
+#include <random>
+#include <sstream>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+#include <faiss/utils/approx_topk/approx_topk.h>
+
+#include <faiss/impl/FaissException.h>
+#include <faiss/utils/Heap.h>
+
+//
+using namespace faiss;
+
+//
+template <uint32_t NBUCKETS, uint32_t N>
+void test_approx_topk(
+ const uint32_t beamSize,
+ const uint32_t nPerBeam,
+ const uint32_t k,
+ const uint32_t nDatasetsToTest,
+ const bool verbose) {
+ if (verbose) {
+ printf("-----------\n");
+ }
+
+ // generate random data
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // matches
+ size_t nMatches = 0;
+ // the element was completely missed in approx version.
+ size_t nMissed = 0;
+ // the element is available
+ size_t nAvailable = 0;
+ // the distance is the same, but the index is different.
+ size_t nSoftMismatches = 0;
+ // the distances are different
+ size_t nHardMismatches = 0;
+ // error of distances
+ double sqrError = 0.0;
+
+ //
+ double timeBaseline = 0.0;
+ double timeApprox = 0.0;
+
+ for (size_t iDataset = 0; iDataset < nDatasetsToTest; iDataset++) {
+ const size_t n = (size_t)(nPerBeam)*beamSize;
+ std::vector<float> distances(n, 0);
+ for (size_t i = 0; i < n; i++) {
+ distances[i] = u(rng);
+ }
+
+ //
+ using C = CMax<float, int>;
+
+ // do a regular beam search
+ std::vector<float> baselineDistances(k, C::neutral());
+ std::vector<int> baselineIndices(k, -1);
+
+ auto startBaseline = std::chrono::high_resolution_clock::now();
+ heap_addn<C>(
+ k,
+ baselineDistances.data(),
+ baselineIndices.data(),
+ distances.data(),
+ nullptr,
+ nPerBeam * beamSize);
+ auto endBaseline = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diffBaseline =
+ endBaseline - startBaseline;
+ timeBaseline += diffBaseline.count();
+
+ heap_reorder<C>(k, baselineDistances.data(), baselineIndices.data());
+
+ // do an approximate beam search
+ std::vector<float> approxDistances(k, C::neutral());
+ std::vector<int> approxIndices(k, -1);
+
+ auto startApprox = std::chrono::high_resolution_clock::now();
+ try {
+ HeapWithBuckets<C, NBUCKETS, N>::bs_addn(
+ beamSize,
+ nPerBeam,
+ distances.data(),
+ k,
+ approxDistances.data(),
+ approxIndices.data());
+ } catch (const faiss::FaissException&) {
+ //
+ if (verbose) {
+ printf("Skipping the case.\n");
+ }
+ return;
+ }
+
+ auto endApprox = std::chrono::high_resolution_clock::now();
+ std::chrono::duration<double> diffApprox = endApprox - startApprox;
+ timeApprox += diffApprox.count();
+
+ heap_reorder<C>(k, approxDistances.data(), approxIndices.data());
+
+ bool bGotMismatches = false;
+
+ // the error
+ for (uint32_t i = 0; i < k; i++) {
+ if (baselineDistances[i] != approxDistances[i]) {
+ nHardMismatches += 1;
+
+ double diff = baselineDistances[i] - approxDistances[i];
+ sqrError += diff * diff;
+
+ bGotMismatches = true;
+
+ if (verbose) {
+ printf("i=%d, bs.d=%f, bs.i=%d, app.d=%f, app.i=%d\n",
+ i,
+ baselineDistances[i],
+ baselineIndices[i],
+ approxDistances[i],
+ approxIndices[i]);
+ }
+ } else {
+ if (baselineIndices[i] != approxIndices[i]) {
+ nSoftMismatches += 1;
+ } else {
+ nMatches += 1;
+ }
+ }
+ }
+
+ if (bGotMismatches) {
+ if (verbose) {
+ printf("\n");
+ }
+ }
+
+ //
+ std::unordered_set<int> bsIndicesHS(
+ baselineIndices.cbegin(), baselineIndices.cend());
+ for (uint32_t i = 0; i < k; i++) {
+ auto itr = bsIndicesHS.find(approxIndices[i]);
+ if (itr != bsIndicesHS.cend()) {
+ nAvailable += 1;
+ } else {
+ nMissed += 1;
+ }
+ }
+ }
+
+ if (verbose) {
+ printf("%d, %d, %d, %d, %d, %d: %ld, %ld, %ld, %f, %ld, %ld, %f, %f\n",
+ NBUCKETS,
+ N,
+ beamSize,
+ nPerBeam,
+ k,
+ nDatasetsToTest,
+ nMatches,
+ nSoftMismatches,
+ nHardMismatches,
+ sqrError,
+ nAvailable,
+ nMissed,
+ timeBaseline,
+ timeApprox);
+ }
+
+ // just confirm that the error is not crazy
+ if (NBUCKETS * N * beamSize >= k) {
+ EXPECT_TRUE(nAvailable > nMissed);
+ } else {
+ // it is possible that the results are crazy here. Skip it.
+ }
+}
+
+//
+TEST(testApproxTopk, COMMON) {
+ constexpr bool verbose = false;
+
+ //
+ const uint32_t nDifferentDatasets = 8;
+
+ uint32_t kValues[] = {1, 2, 3, 5, 8, 13, 21, 34};
+
+ for (size_t codebookBitSize = 8; codebookBitSize <= 10; codebookBitSize++) {
+ const uint32_t codebookSize = 1 << codebookBitSize;
+ for (const auto k : kValues) {
+ test_approx_topk<1 * 8, 3>(
+ 1, codebookSize, k, nDifferentDatasets, verbose);
+ test_approx_topk<1 * 8, 3>(
+ k, codebookSize, k, nDifferentDatasets, verbose);
+
+ test_approx_topk<1 * 8, 2>(
+ 1, codebookSize, k, nDifferentDatasets, verbose);
+ test_approx_topk<1 * 8, 2>(
+ k, codebookSize, k, nDifferentDatasets, verbose);
+
+ test_approx_topk<2 * 8, 2>(
+ 1, codebookSize, k, nDifferentDatasets, verbose);
+ test_approx_topk<2 * 8, 2>(
+ k, codebookSize, k, nDifferentDatasets, verbose);
+
+ test_approx_topk<4 * 8, 2>(
+ 1, codebookSize, k, nDifferentDatasets, verbose);
+ test_approx_topk<4 * 8, 2>(
+ k, codebookSize, k, nDifferentDatasets, verbose);
+ }
+ }
+}
+
+//
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_binary_flat.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_binary_flat.cpp
new file mode 100644
index 0000000..a3a3380
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_binary_flat.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/utils/hamming.h>
+
+TEST(BinaryFlat, accuracy) {
+ // dimension of the vectors to index
+ int d = 64;
+
+ // size of the database we plan to index
+ size_t nb = 1000;
+
+ // make the index object and train it
+ faiss::IndexBinaryFlat index(d);
+
+ std::vector<uint8_t> database(nb * (d / 8));
+ for (size_t i = 0; i < nb * (d / 8); i++) {
+ database[i] = rand() % 0x100;
+ }
+
+ { // populating the database
+ index.add(nb, database.data());
+ }
+
+ size_t nq = 200;
+
+ { // searching the database
+
+ std::vector<uint8_t> queries(nq * (d / 8));
+ for (size_t i = 0; i < nq * (d / 8); i++) {
+ queries[i] = rand() % 0x100;
+ }
+
+ int k = 5;
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<int> dis(k * nq);
+
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+
+ for (size_t i = 0; i < nq; ++i) {
+ faiss::HammingComputer8 hc(queries.data() + i * (d / 8), d / 8);
+ hamdis_t dist_min = hc.hamming(database.data());
+ for (size_t j = 1; j < nb; ++j) {
+ hamdis_t dist = hc.hamming(database.data() + j * (d / 8));
+ if (dist < dist_min) {
+ dist_min = dist;
+ }
+ }
+ EXPECT_EQ(dist_min, dis[k * i]);
+ }
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_callback.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_callback.cpp
new file mode 100644
index 0000000..fb0fc03
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_callback.cpp
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <faiss/Clustering.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/FaissException.h>
+#include <faiss/utils/random.h>
+
+TEST(TestCallback, timeout) {
+ int n = 1000;
+ int k = 100;
+ int d = 128;
+ int niter = 1000000000;
+ int seed = 42;
+
+ std::vector<float> vecs(n * d);
+ faiss::float_rand(vecs.data(), vecs.size(), seed);
+
+ auto index(new faiss::IndexFlat(d));
+
+ faiss::ClusteringParameters cp;
+ cp.niter = niter;
+ cp.verbose = false;
+
+ faiss::Clustering kmeans(d, k, cp);
+
+ faiss::TimeoutCallback::reset(0.010);
+ EXPECT_THROW(kmeans.train(n, vecs.data(), *index), faiss::FaissException);
+ delete index;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_code_distance.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_code_distance.cpp
new file mode 100644
index 0000000..f1a3939
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_code_distance.cpp
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <omp.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <iostream>
+#include <memory>
+#include <random>
+#include <thread>
+#include <tuple>
+#include <vector>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/code_distance/code_distance.h>
+
+size_t nMismatches(
+ const std::vector<float>& ref,
+ const std::vector<float>& candidate) {
+ size_t count = 0;
+ for (size_t i = 0; i < count; i++) {
+ double abs = std::abs(ref[i] - candidate[i]);
+ if (abs >= 1e-5) {
+ count += 1;
+ }
+ }
+
+ return count;
+}
+
+void test(
+ // dimensionality of the data
+ const size_t dim,
+ // number of subquantizers
+ const size_t subq,
+ // bits per subquantizer
+ const size_t nbits,
+ // number of codes to process
+ const size_t n) {
+ FAISS_THROW_IF_NOT(nbits == 8);
+
+ // remove if benchmarking is needed
+ omp_set_num_threads(1);
+
+ // rng
+ std::minstd_rand rng(123);
+ std::uniform_int_distribution<uint8_t> u(0, 255);
+ std::uniform_real_distribution<float> uf(0, 1);
+
+ // initialize lookup
+ std::vector<float> lookup(256 * subq, 0);
+ for (size_t i = 0; i < lookup.size(); i++) {
+ lookup[i] = uf(rng);
+ }
+
+ // initialize codes
+ std::vector<uint8_t> codes(n * subq);
+#pragma omp parallel
+ {
+ std::minstd_rand rng0(123);
+ std::uniform_int_distribution<uint8_t> u1(0, 255);
+
+#pragma omp for schedule(guided)
+ for (size_t i = 0; i < codes.size(); i++) {
+ codes[i] = u1(rng0);
+ }
+ }
+
+ // warmup. compute reference results
+ std::vector<float> resultsRef(n, 0);
+ for (size_t k = 0; k < 10; k++) {
+#pragma omp parallel for schedule(guided)
+ for (size_t i = 0; i < n; i++) {
+ resultsRef[i] =
+ faiss::distance_single_code_generic<faiss::PQDecoder8>(
+ subq, 8, lookup.data(), codes.data() + subq * i);
+ }
+ }
+
+ // generic, 1 code per step
+ std::vector<float> resultsNewGeneric1x(n, 0);
+ double generic1xMsec = 0;
+ {
+ const auto startingTimepoint = std::chrono::steady_clock::now();
+ for (size_t k = 0; k < 1000; k++) {
+#pragma omp parallel for schedule(guided)
+ for (size_t i = 0; i < n; i++) {
+ resultsNewGeneric1x[i] =
+ faiss::distance_single_code_generic<faiss::PQDecoder8>(
+ subq,
+ 8,
+ lookup.data(),
+ codes.data() + subq * i);
+ }
+ }
+ const auto endingTimepoint = std::chrono::steady_clock::now();
+
+ std::chrono::duration<double> duration =
+ endingTimepoint - startingTimepoint;
+ generic1xMsec = (duration.count() * 1000.0);
+ }
+
+ // generic, 4 codes per step
+ std::vector<float> resultsNewGeneric4x(n, 0);
+ double generic4xMsec = 0;
+ {
+ const auto startingTimepoint = std::chrono::steady_clock::now();
+ for (size_t k = 0; k < 1000; k++) {
+#pragma omp parallel for schedule(guided)
+ for (size_t i = 0; i < n; i += 4) {
+ faiss::distance_four_codes_generic<faiss::PQDecoder8>(
+ subq,
+ 8,
+ lookup.data(),
+ codes.data() + subq * (i + 0),
+ codes.data() + subq * (i + 1),
+ codes.data() + subq * (i + 2),
+ codes.data() + subq * (i + 3),
+ resultsNewGeneric4x[i + 0],
+ resultsNewGeneric4x[i + 1],
+ resultsNewGeneric4x[i + 2],
+ resultsNewGeneric4x[i + 3]);
+ }
+ }
+
+ const auto endingTimepoint = std::chrono::steady_clock::now();
+
+ std::chrono::duration<double> duration =
+ endingTimepoint - startingTimepoint;
+ generic4xMsec = (duration.count() * 1000.0);
+ }
+
+ // generic, 1 code per step
+ std::vector<float> resultsNewCustom1x(n, 0);
+ double custom1xMsec = 0;
+ {
+ const auto startingTimepoint = std::chrono::steady_clock::now();
+ for (size_t k = 0; k < 1000; k++) {
+#pragma omp parallel for schedule(guided)
+ for (size_t i = 0; i < n; i++) {
+ resultsNewCustom1x[i] =
+ faiss::distance_single_code<faiss::PQDecoder8>(
+ subq,
+ 8,
+ lookup.data(),
+ codes.data() + subq * i);
+ }
+ }
+ const auto endingTimepoint = std::chrono::steady_clock::now();
+
+ std::chrono::duration<double> duration =
+ endingTimepoint - startingTimepoint;
+ custom1xMsec = (duration.count() * 1000.0);
+ }
+
+ // generic, 4 codes per step
+ std::vector<float> resultsNewCustom4x(n, 0);
+ double custom4xMsec = 0;
+ {
+ const auto startingTimepoint = std::chrono::steady_clock::now();
+ for (size_t k = 0; k < 1000; k++) {
+#pragma omp parallel for schedule(guided)
+ for (size_t i = 0; i < n; i += 4) {
+ faiss::distance_four_codes<faiss::PQDecoder8>(
+ subq,
+ 8,
+ lookup.data(),
+ codes.data() + subq * (i + 0),
+ codes.data() + subq * (i + 1),
+ codes.data() + subq * (i + 2),
+ codes.data() + subq * (i + 3),
+ resultsNewCustom4x[i + 0],
+ resultsNewCustom4x[i + 1],
+ resultsNewCustom4x[i + 2],
+ resultsNewCustom4x[i + 3]);
+ }
+ }
+
+ const auto endingTimepoint = std::chrono::steady_clock::now();
+
+ std::chrono::duration<double> duration =
+ endingTimepoint - startingTimepoint;
+ custom4xMsec = (duration.count() * 1000.0);
+ }
+
+ const size_t nMismatchesG1 = nMismatches(resultsRef, resultsNewGeneric1x);
+ const size_t nMismatchesG4 = nMismatches(resultsRef, resultsNewGeneric4x);
+ const size_t nMismatchesCustom1 =
+ nMismatches(resultsRef, resultsNewCustom1x);
+ const size_t nMismatchesCustom4 =
+ nMismatches(resultsRef, resultsNewCustom4x);
+
+ std::cout << "Dim = " << dim << ", subq = " << subq << ", nbits = " << nbits
+ << ", n = " << n << std::endl;
+ std::cout << "Generic 1x code: " << generic1xMsec << " msec, "
+ << nMismatchesG1 << " mismatches" << std::endl;
+ std::cout << "Generic 4x code: " << generic4xMsec << " msec, "
+ << nMismatchesG4 << " mismatches" << std::endl;
+ std::cout << "custom 1x code: " << custom1xMsec << " msec, "
+ << nMismatchesCustom1 << " mismatches" << std::endl;
+ std::cout << "custom 4x code: " << custom4xMsec << " msec, "
+ << nMismatchesCustom4 << " mismatches" << std::endl;
+ std::cout << std::endl;
+
+ ASSERT_EQ(nMismatchesG1, 0);
+ ASSERT_EQ(nMismatchesG4, 0);
+ ASSERT_EQ(nMismatchesCustom1, 0);
+ ASSERT_EQ(nMismatchesCustom4, 0);
+}
+
+// this test can be used as a benchmark.
+// 1. Increase the value of NELEMENTS
+// 2. Remove omp_set_num_threads()
+
+constexpr size_t NELEMENTS = 10000;
+
+TEST(TestCodeDistance, SUBQ4_NBITS8) {
+ test(256, 4, 8, NELEMENTS);
+}
+
+TEST(TestCodeDistance, SUBQ8_NBITS8) {
+ test(256, 8, 8, NELEMENTS);
+}
+
+TEST(TestCodeDistance, SUBQ16_NBITS8) {
+ test(256, 16, 8, NELEMENTS);
+}
+
+TEST(TestCodeDistance, SUBQ32_NBITS8) {
+ test(256, 32, 8, NELEMENTS);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_common_ivf_empty_index.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_common_ivf_empty_index.cpp
new file mode 100644
index 0000000..eeaa839
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_common_ivf_empty_index.cpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <memory>
+#include <vector>
+
+#include <faiss/IndexIVF.h>
+#include <faiss/clone_index.h>
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/index_factory.h>
+#include <faiss/invlists/InvertedLists.h>
+#include <faiss/utils/random.h>
+
+/* This demonstrates how to query several independent IVF indexes with a trained
+ *index in common. This avoids to duplicate the coarse quantizer and metadata
+ *in memory.
+ **/
+
+namespace {
+
+int d = 64;
+
+} // namespace
+
+std::vector<float> get_random_vectors(size_t n, int seed) {
+ std::vector<float> x(n * d);
+ faiss::rand_smooth_vectors(n, d, x.data(), seed);
+ seed++;
+ return x;
+}
+
+/** InvetedLists implementation that dispatches the search to an InvertedList
+ * object that is passed in at query time */
+
+struct DispatchingInvertedLists : faiss::ReadOnlyInvertedLists {
+ DispatchingInvertedLists(size_t nlist, size_t code_size)
+ : faiss::ReadOnlyInvertedLists(nlist, code_size) {
+ use_iterator = true;
+ }
+
+ faiss::InvertedListsIterator* get_iterator(
+ size_t list_no,
+ void* inverted_list_context = nullptr) const override {
+ assert(inverted_list_context);
+ auto il =
+ static_cast<const faiss::InvertedLists*>(inverted_list_context);
+ return il->get_iterator(list_no);
+ }
+
+ using idx_t = faiss::idx_t;
+
+ size_t list_size(size_t list_no) const override {
+ FAISS_THROW_MSG("use iterator interface");
+ }
+ const uint8_t* get_codes(size_t list_no) const override {
+ FAISS_THROW_MSG("use iterator interface");
+ }
+ const idx_t* get_ids(size_t list_no) const override {
+ FAISS_THROW_MSG("use iterator interface");
+ }
+};
+
+TEST(COMMON, test_common_trained_index) {
+ int N = 3; // number of independent indexes
+ int nt = 500; // training vectors
+ int nb = 200; // nb database vectors per index
+ int nq = 10; // nb queries performed on each index
+ int k = 4; // restults requested per query
+
+ // construct and build an "empty index": a trained index that does not
+ // itself hold any data
+ std::unique_ptr<faiss::IndexIVF> empty_index(dynamic_cast<faiss::IndexIVF*>(
+ faiss::index_factory(d, "IVF32,PQ8np")));
+ auto xt = get_random_vectors(nt, 123);
+ empty_index->train(nt, xt.data());
+ empty_index->nprobe = 4;
+
+ // reference run: build one index for each set of db / queries and record
+ // results
+ std::vector<std::vector<faiss::idx_t>> ref_I(N);
+
+ for (int i = 0; i < N; i++) {
+ // clone the empty index
+ std::unique_ptr<faiss::Index> index(
+ faiss::clone_index(empty_index.get()));
+ auto xb = get_random_vectors(nb, 1234 + i);
+ auto xq = get_random_vectors(nq, 12345 + i);
+ // add vectors and perform a search
+ index->add(nb, xb.data());
+ std::vector<float> D(k * nq);
+ std::vector<faiss::idx_t> I(k * nq);
+ index->search(nq, xq.data(), k, D.data(), I.data());
+ // record result as reference
+ ref_I[i] = I;
+ }
+
+ // build a set of inverted lists for each independent index
+ std::vector<faiss::ArrayInvertedLists> sub_invlists;
+
+ for (int i = 0; i < N; i++) {
+ // swap in other inverted lists
+ sub_invlists.emplace_back(empty_index->nlist, empty_index->code_size);
+ faiss::InvertedLists* invlists = &sub_invlists.back();
+
+ // replace_invlists swaps in a new InvertedLists for an existing index
+ empty_index->replace_invlists(invlists, false);
+ empty_index->reset(); // reset id counter to 0
+ // populate inverted lists
+ auto xb = get_random_vectors(nb, 1234 + i);
+ empty_index->add(nb, xb.data());
+ }
+
+ // perform search dispatching to the sub-invlists. At search time, we don't
+ // use replace_invlists because that would wreak havoc in a multithreaded
+ // context
+ DispatchingInvertedLists di(empty_index->nlist, empty_index->code_size);
+ empty_index->replace_invlists(&di, false);
+
+ std::vector<std::vector<faiss::idx_t>> new_I(N);
+
+ // run searches in the independent indexes but with a common empty_index
+#pragma omp parallel for
+ for (int i = 0; i < N; i++) {
+ auto xq = get_random_vectors(nq, 12345 + i);
+ std::vector<float> D(k * nq);
+ std::vector<faiss::idx_t> I(k * nq);
+
+ // here we set to what sub-index the queries should be directed
+ faiss::SearchParametersIVF params;
+ params.nprobe = empty_index->nprobe;
+ params.inverted_list_context = &sub_invlists[i];
+
+ empty_index->search(nq, xq.data(), k, D.data(), I.data(), &params);
+ new_I[i] = I;
+ }
+
+ // compare with reference reslt
+ for (int i = 0; i < N; i++) {
+ ASSERT_EQ(ref_I[i], new_I[i]);
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_cppcontrib_sa_decode.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_cppcontrib_sa_decode.cpp
new file mode 100644
index 0000000..f621279
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_cppcontrib_sa_decode.cpp
@@ -0,0 +1,1306 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <random>
+#include <tuple>
+#include <vector>
+
+#include <faiss/Index.h>
+#include <faiss/Index2Layer.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/IndexPQ.h>
+#include <faiss/impl/io.h>
+#include <faiss/index_factory.h>
+#include <faiss/index_io.h>
+
+#include <faiss/IndexRowwiseMinMax.h>
+#include <faiss/cppcontrib/SaDecodeKernels.h>
+
+using namespace ::testing;
+using ::testing::TestWithParam;
+using ::testing::Values;
+
+std::tuple<std::shared_ptr<faiss::Index>, std::vector<uint8_t>> trainDataset(
+ const std::vector<float>& input,
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description) {
+ // train an index
+ auto index = std::shared_ptr<faiss::Index>(
+ faiss::index_factory((int)d, description.c_str()));
+ index->train((int)n, input.data());
+
+ // encode
+ const size_t codeSize = index->sa_code_size();
+
+ std::vector<uint8_t> encodedData(n * codeSize);
+ index->sa_encode(n, input.data(), encodedData.data());
+
+ return std::make_tuple(std::move(index), std::move(encodedData));
+}
+
+bool testIfIVFPQ(
+ const faiss::Index* const index,
+ const float** pqCoarseCentroidsQ,
+ const float** pqFineCentroidsQ) {
+ if (pqFineCentroidsQ == nullptr || pqCoarseCentroidsQ == nullptr) {
+ return false;
+ }
+
+ const faiss::IndexIVFPQ* const indexQ =
+ dynamic_cast<const faiss::IndexIVFPQ*>(index);
+ if (indexQ == nullptr) {
+ return false;
+ }
+
+ const auto coarseIndexQ =
+ dynamic_cast<const faiss::IndexFlatCodes*>(indexQ->quantizer);
+ if (coarseIndexQ == nullptr) {
+ return false;
+ }
+
+ *pqFineCentroidsQ = indexQ->pq.centroids.data();
+ *pqCoarseCentroidsQ =
+ reinterpret_cast<const float*>(coarseIndexQ->codes.data());
+ return true;
+}
+
+bool testIfResidualPQ(
+ const faiss::Index* const index,
+ const float** pqCoarseCentroidsQ,
+ const float** pqFineCentroidsQ) {
+ if (pqFineCentroidsQ == nullptr || pqCoarseCentroidsQ == nullptr) {
+ return false;
+ }
+
+ const faiss::Index2Layer* const indexQ =
+ dynamic_cast<const faiss::Index2Layer*>(index);
+ if (indexQ == nullptr) {
+ return false;
+ }
+
+ const auto coarseIndexQ = dynamic_cast<const faiss::MultiIndexQuantizer*>(
+ indexQ->q1.quantizer);
+ if (coarseIndexQ == nullptr) {
+ return false;
+ }
+
+ *pqFineCentroidsQ = indexQ->pq.centroids.data();
+ *pqCoarseCentroidsQ = coarseIndexQ->pq.centroids.data();
+ return true;
+}
+
+template <typename T>
+void verifyIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData) {
+ //
+ const float* pqFineCentroidsQ = nullptr;
+ const float* pqCoarseCentroidsQ = nullptr;
+
+ //
+ testIfIVFPQ(index.get(), &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+ testIfResidualPQ(index.get(), &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ //
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // test general purpose version vs contrib::store
+ std::vector<float> outputFaiss(d, 0);
+ std::vector<float> tmpFaiss(d, 0);
+ std::vector<float> tmpContrib(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ // compute using faiss
+ index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data());
+
+ // compute using contrib
+ T::store(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ tmpContrib.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++)
+ ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]);
+
+ // save for the further comparison
+ const float weight = u(rng);
+ for (size_t j = 0; j < d; j++)
+ outputFaiss[j] += weight * tmpFaiss[j];
+ }
+
+ // test contrib::accum, 1 sample per iteration
+ rng.seed(123);
+
+ std::vector<float> outputContrib1s(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ const float weight0 = u(rng);
+
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data());
+ }
+
+ // verify
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(outputFaiss[j], outputContrib1s[j]);
+ }
+
+ // test contrib::accum, 2 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib2s(d, 0);
+ std::vector<float> outputContrib2sSame(d, 0);
+ for (size_t i = 0; i < n; i += 2) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib2s[j] = (j + 1) * (j + 1);
+ outputContrib2sSame[j] = (j + 1) * (j + 1);
+ }
+
+ // do a single step, 2 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2s.data());
+
+ // do a single step, 2 samples per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2sSame.data());
+
+ // do two steps, 1 sample per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data());
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2s[j]);
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2sSame[j]);
+ }
+ }
+
+ // test contrib::accum, 3 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib3s(d, 0);
+ std::vector<float> outputContrib3sSame(d, 0);
+ const size_t n3 = (n / 3) * 3;
+ for (size_t i = 0; i < n3; i += 3) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib3s[j] = (j + 1) * (j + 1);
+ outputContrib3sSame[j] = (j + 1) * (j + 1);
+ }
+
+ // do a single step, 3 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+ const float weight2 = u(rng);
+
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3s.data());
+
+ // do a single step, 3 samples per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3sSame.data());
+
+ // do three steps, 1 sample per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data());
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data());
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib1s.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3s[j]);
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3sSame[j]);
+ }
+ }
+}
+
+template <typename T>
+void verifyMinMaxIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData) {
+ //
+ const float* pqFineCentroidsQ = nullptr;
+ const float* pqCoarseCentroidsQ = nullptr;
+
+ // extract an index that is wrapped with IndexRowwiseMinMaxBase
+ const std::shared_ptr<faiss::IndexRowwiseMinMaxBase> indexMinMax =
+ std::dynamic_pointer_cast<faiss::IndexRowwiseMinMaxBase>(index);
+ ASSERT_NE(indexMinMax.get(), nullptr);
+
+ auto subIndex = indexMinMax->index;
+
+ //
+ testIfIVFPQ(subIndex, &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+ testIfResidualPQ(subIndex, &pqCoarseCentroidsQ, &pqFineCentroidsQ);
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ //
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // test general purpose version vs contrib::store
+ std::vector<float> outputFaiss(d, 0);
+ std::vector<float> tmpFaiss(d, 0);
+ std::vector<float> tmpContrib(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ // compute using faiss
+ index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data());
+
+ // compute using contrib
+ T::store(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ tmpContrib.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++)
+ ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]);
+
+ // save for the further comparison
+ const float weight = u(rng);
+ for (size_t j = 0; j < d; j++)
+ outputFaiss[j] += weight * tmpFaiss[j];
+ }
+
+ // test contrib::accum, 1 sample per iteration.
+ // This needs a way of handling that is different from just IVFPQ and PQ
+ // because of the scaling, but rather similar to how 2 samples per iteration
+ // is processed.
+ rng.seed(123);
+
+ std::vector<float> outputContrib1s(d, 0);
+ float outputMinv1s = 0;
+ for (size_t i = 0; i < n; i++) {
+ // compute using faiss
+ index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data());
+
+ // populate some initial data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ }
+ outputMinv1s = 0;
+
+ // generate a weight
+ const float weight0 = u(rng);
+
+ //
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data(),
+ outputMinv1s);
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ tmpFaiss[j] * weight0 + (j + 1) * (j + 1));
+ }
+ }
+
+ // test contrib::accum, 2 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib2s(d, 0);
+ std::vector<float> outputContrib2sSame(d, 0);
+ float outputMinv2s = 0;
+ float outputMinv2sSame = 0;
+ for (size_t i = 0; i < n; i += 2) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib2s[j] = (j + 1) * (j + 1);
+ outputContrib2sSame[j] = (j + 1) * (j + 1);
+ }
+ outputMinv1s = 0;
+ outputMinv2s = 0;
+ outputMinv2sSame = 0;
+
+ // do a single step, 2 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2s.data(),
+ outputMinv2s);
+
+ // do a single step, 2 samples per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2sSame.data(),
+ outputMinv2sSame);
+
+ // do two steps, 1 sample per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data(),
+ outputMinv1s);
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data(),
+ outputMinv1s);
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib2s[j] + outputMinv2s);
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib2sSame[j] + outputMinv2sSame);
+ }
+ }
+
+ // test contrib::accum, 3 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib3s(d, 0);
+ float outputMinv3s = 0;
+ std::vector<float> outputContrib3sSame(d, 0);
+ float outputMinv3sSame = 0;
+ const size_t n3 = (n / 3) * 3;
+ for (size_t i = 0; i < n3; i += 3) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib3s[j] = (j + 1) * (j + 1);
+ outputContrib3sSame[j] = (j + 1) * (j + 1);
+ }
+ outputMinv1s = 0;
+ outputMinv3s = 0;
+ outputMinv3sSame = 0;
+
+ // do a single step, 3 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+ const float weight2 = u(rng);
+
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3s.data(),
+ outputMinv3s);
+
+ // do a single step, 3 samples per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3sSame.data(),
+ outputMinv3sSame);
+
+ // do three steps, 1 sample per step
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data(),
+ outputMinv1s);
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data(),
+ outputMinv1s);
+ T::accum(
+ pqCoarseCentroidsQ,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib1s.data(),
+ outputMinv1s);
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib3s[j] + outputMinv3s);
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib3sSame[j] + outputMinv3sSame);
+ }
+ }
+}
+
+template <typename T>
+void verifyIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData) {
+ //
+ const faiss::IndexPQ* const indexQ =
+ dynamic_cast<const faiss::IndexPQ*>(index.get());
+ const float* const pqFineCentroidsQ = indexQ->pq.centroids.data();
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ //
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // test general purpose version vs contrib::store
+ std::vector<float> outputFaiss(d, 0);
+ std::vector<float> tmpFaiss(d, 0);
+ std::vector<float> tmpContrib(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ // compute using faiss
+ index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data());
+
+ // compute using contrib
+ T::store(
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ tmpContrib.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++)
+ ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]);
+
+ // save for the further comparison
+ const float weight = u(rng);
+ for (size_t j = 0; j < d; j++)
+ outputFaiss[j] += weight * tmpFaiss[j];
+ }
+
+ // test contrib::accum, 1 sample per iteration
+ rng.seed(123);
+
+ std::vector<float> outputContrib1s(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ const float weight0 = u(rng);
+
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data());
+ }
+
+ // verify
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(outputFaiss[j], outputContrib1s[j]);
+ }
+
+ // test contrib::accum, 2 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib2s(d, 0);
+ std::vector<float> outputContrib2sSame(d, 0);
+ for (size_t i = 0; i < n; i += 2) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib2s[j] = (j + 1) * (j + 1);
+ outputContrib2sSame[j] = (j + 1) * (j + 1);
+ }
+
+ // do a single step, 2 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2s.data());
+
+ // do a single step, 2 samples per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2sSame.data());
+
+ // do two steps, 1 sample per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data());
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2s[j]);
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2sSame[j]);
+ }
+ }
+
+ // test contrib::accum, 3 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib3s(d, 0);
+ std::vector<float> outputContrib3sSame(d, 0);
+ const size_t n3 = (n / 3) * 3;
+ for (size_t i = 0; i < n3; i += 3) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib3s[j] = (j + 1) * (j + 1);
+ outputContrib3sSame[j] = (j + 1) * (j + 1);
+ }
+
+ // do a single step, 3 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+ const float weight2 = u(rng);
+
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3s.data());
+
+ // do a single step, 3 samples per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3sSame.data());
+
+ // do three steps, 1 sample per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data());
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data());
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib1s.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3s[j]);
+ ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3sSame[j]);
+ }
+ }
+}
+
+template <typename T>
+void verifyMinMaxIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::shared_ptr<faiss::Index>& index,
+ const std::vector<uint8_t>& encodedData) {
+ // extract an index that is wrapped with IndexRowwiseMinMaxBase
+ const std::shared_ptr<faiss::IndexRowwiseMinMaxBase> indexMinMax =
+ std::dynamic_pointer_cast<faiss::IndexRowwiseMinMaxBase>(index);
+ ASSERT_NE(indexMinMax.get(), nullptr);
+
+ auto subIndex = indexMinMax->index;
+
+ //
+ const faiss::IndexPQ* const indexQ =
+ dynamic_cast<const faiss::IndexPQ*>(subIndex);
+ const float* const pqFineCentroidsQ = indexQ->pq.centroids.data();
+
+ //
+ const size_t codeSize = index->sa_code_size();
+
+ //
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 1);
+
+ // test general purpose version vs contrib::store
+ std::vector<float> outputFaiss(d, 0);
+ std::vector<float> tmpFaiss(d, 0);
+ std::vector<float> tmpContrib(d, 0);
+ for (size_t i = 0; i < n; i++) {
+ // compute using faiss
+ index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data());
+
+ // compute using contrib
+ T::store(
+ pqFineCentroidsQ,
+ encodedData.data() + i * codeSize,
+ tmpContrib.data());
+
+ // compare
+ for (size_t j = 0; j < d; j++)
+ ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]);
+
+ // save for the further comparison
+ const float weight = u(rng);
+ for (size_t j = 0; j < d; j++)
+ outputFaiss[j] += weight * tmpFaiss[j];
+ }
+
+ // test contrib::accum, 1 sample per iteration.
+ // This needs a way of handling that is different from just IVFPQ and PQ
+ // because of the scaling, but rather similar to how 2 samples per iteration
+ // is processed.
+ rng.seed(123);
+
+ std::vector<float> outputContrib1s(d, 0);
+ float outputMinv1s = 0;
+ for (size_t i = 0; i < n; i++) {
+ // compute using faiss
+ index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data());
+
+ // populate some initial data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ }
+ outputMinv1s = 0;
+
+ // generate a weight
+ const float weight0 = u(rng);
+
+ //
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data(),
+ outputMinv1s);
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ tmpFaiss[j] * weight0 + (j + 1) * (j + 1));
+ }
+ }
+
+ // test contrib::accum, 2 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib2s(d, 0);
+ float outputMinv2s = 0;
+ std::vector<float> outputContrib2sSame(d, 0);
+ float outputMinv2sSame = 0;
+ for (size_t i = 0; i < n; i += 2) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib2s[j] = (j + 1) * (j + 1);
+ outputContrib2sSame[j] = (j + 1) * (j + 1);
+ }
+ outputMinv1s = 0;
+ outputMinv2s = 0;
+ outputMinv2sSame = 0;
+
+ // do a single step, 2 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2s.data(),
+ outputMinv2s);
+
+ // do a single step, 2 samples per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib2sSame.data(),
+ outputMinv2sSame);
+
+ // do two steps, 1 sample per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data(),
+ outputMinv1s);
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data(),
+ outputMinv1s);
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib2s[j] + outputMinv2s);
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib2sSame[j] + outputMinv2sSame);
+ }
+ }
+
+ // test contrib::accum, 3 samples per iteration.
+ rng.seed(123);
+
+ std::vector<float> outputContrib3s(d, 0);
+ float outputMinv3s = 0;
+ std::vector<float> outputContrib3sSame(d, 0);
+ float outputMinv3sSame = 0;
+ const size_t n3 = (n / 3) * 3;
+ for (size_t i = 0; i < n3; i += 3) {
+ // populate outputContribs with some existing data
+ for (size_t j = 0; j < d; j++) {
+ outputContrib1s[j] = (j + 1) * (j + 1);
+ outputContrib3s[j] = (j + 1) * (j + 1);
+ outputContrib3sSame[j] = (j + 1) * (j + 1);
+ }
+ outputMinv1s = 0;
+ outputMinv3s = 0;
+ outputMinv3sSame = 0;
+
+ // do a single step, 3 samples per step
+ const float weight0 = u(rng);
+ const float weight1 = u(rng);
+ const float weight2 = u(rng);
+
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3s.data(),
+ outputMinv3s);
+
+ // do a single step, 3 samples per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib3sSame.data(),
+ outputMinv3sSame);
+
+ // do three steps, 1 sample per step
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 0) * codeSize,
+ weight0,
+ outputContrib1s.data(),
+ outputMinv1s);
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 1) * codeSize,
+ weight1,
+ outputContrib1s.data(),
+ outputMinv1s);
+ T::accum(
+ pqFineCentroidsQ,
+ encodedData.data() + (i + 2) * codeSize,
+ weight2,
+ outputContrib1s.data(),
+ outputMinv1s);
+
+ // compare
+ for (size_t j = 0; j < d; j++) {
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib3s[j] + outputMinv3s);
+ ASSERT_FLOAT_EQ(
+ outputContrib1s[j] + outputMinv1s,
+ outputContrib3sSame[j] + outputMinv3sSame);
+ }
+ }
+}
+
+std::vector<float> generate(const size_t n, const size_t d) {
+ std::vector<float> data(n * d);
+
+ std::minstd_rand rng(345);
+ std::uniform_real_distribution<float> ux(0, 1);
+
+ //
+ for (size_t k = 0; k < n; k++) {
+ for (size_t j = 0; j < d; j++) {
+ data[k * d + j] = ux(rng);
+ }
+ }
+
+ return data;
+}
+
+template <typename T>
+void testIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyIndex2LevelDecoder<T>(n, d, index, encodedData);
+}
+
+template <typename T>
+void testMinMaxIndex2LevelDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyMinMaxIndex2LevelDecoder<T>(n, d, index, encodedData);
+}
+
+template <typename T>
+void testIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyIndexPQDecoder<T>(n, d, index, encodedData);
+}
+
+template <typename T>
+void testMinMaxIndexPQDecoder(
+ const uint64_t n,
+ const uint64_t d,
+ const std::string& description) {
+ auto data = generate(n, d);
+ std::shared_ptr<faiss::Index> index;
+ std::vector<uint8_t> encodedData;
+ std::tie(index, encodedData) = trainDataset(data, n, d, description);
+
+ verifyMinMaxIndexPQDecoder<T>(n, d, index, encodedData);
+}
+
+constexpr size_t NSAMPLES = 256;
+
+//
+TEST(testCppcontribSaDecode, D256_IVF256_PQ16) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 256, "IVF256,PQ16np");
+}
+
+TEST(testCppcontribSaDecode, D256_IVF256_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 32>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 256, "IVF256,PQ8np");
+}
+
+//
+TEST(testCppcontribSaDecode, D192_IVF256_PQ24) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<192, 192, 8>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 192, "IVF256,PQ24np");
+}
+
+//
+TEST(testCppcontribSaDecode, D192_IVF256_PQ16) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<192, 192, 12>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 192, "IVF256,PQ16np");
+}
+
+//
+TEST(testCppcontribSaDecode, D192_IVF256_PQ12) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<192, 192, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 192, "IVF256,PQ12np");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_IVF256_PQ40) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 4>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "IVF256,PQ40np");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_IVF256_PQ20) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 8>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "IVF256,PQ20np");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_IVF256_PQ10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "IVF256,PQ10np");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_IVF256_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 20>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "IVF256,PQ8np");
+}
+
+//
+TEST(testCppcontribSaDecode, D128_IVF256_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 128, "IVF256,PQ8np");
+}
+
+TEST(testCppcontribSaDecode, D128_IVF256_PQ4) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 32>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 128, "IVF256,PQ4np");
+}
+
+//
+TEST(testCppcontribSaDecode, D64_IVF256_PQ16) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<64, 64, 8>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 64, "IVF256,PQ8np");
+}
+
+TEST(testCppcontribSaDecode, D64_IVF256_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<64, 64, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 64, "IVF256,PQ4np");
+}
+
+#if defined(__AVX2__)
+TEST(testCppcontribSaDecode, D40_IVF256_PQ20) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<40, 40, 2>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 40, "IVF256,PQ20np");
+}
+#endif
+
+//
+TEST(testCppcontribSaDecode, D256_Residual4x8_PQ16) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 256, "Residual4x8,PQ16");
+}
+
+TEST(testCppcontribSaDecode, D256_Residual4x8_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 32>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 256, "Residual4x8,PQ8");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_Residual4x8_PQ10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "Residual4x8,PQ10");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_Residual2x8_PQ10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 80, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "Residual2x8,PQ10");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_Residual1x8_PQ10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 160, "Residual1x8,PQ10");
+}
+
+//
+TEST(testCppcontribSaDecode, D128_Residual4x8_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 128, "Residual4x8,PQ8");
+}
+
+TEST(testCppcontribSaDecode, D128_Residual4x8_PQ4) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 32>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 128, "Residual4x8,PQ4");
+}
+
+//
+TEST(testCppcontribSaDecode, D64_Residual4x8_PQ8) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<64, 16, 8>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 64, "Residual4x8,PQ8");
+}
+
+TEST(testCppcontribSaDecode, D64_Residual4x8_PQ4) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<64, 16, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES, 64, "Residual4x8,PQ4");
+}
+
+//
+TEST(testCppcontribSaDecode, D256_IVF1024_PQ16) {
+ // It is acceptable to use COARSE_BITS=16 in this case,
+ // because there's only one coarse quantizer element.
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 4, 256, "IVF1024,PQ16np");
+}
+
+TEST(testCppcontribSaDecode, D64_Residual1x9_PQ8) {
+ // It is acceptable to use COARSE_BITS=16 in this case,
+ // because there's only one coarse quantizer element.
+ // It won't work for "Residual2x9,PQ8".
+ using T = faiss::cppcontrib::Index2LevelDecoder<64, 64, 8, 16>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 2, 64, "Residual1x9,PQ8");
+}
+
+//
+TEST(testCppcontribSaDecode, D256_PQ16) {
+ using T = faiss::cppcontrib::IndexPQDecoder<256, 16>;
+ testIndexPQDecoder<T>(NSAMPLES, 256, "PQ16np");
+}
+
+//
+TEST(testCppcontribSaDecode, D160_PQ20) {
+ using T = faiss::cppcontrib::IndexPQDecoder<160, 8>;
+ testIndexPQDecoder<T>(NSAMPLES, 160, "PQ20np");
+}
+
+#if defined(__AVX2__)
+TEST(testCppcontribSaDecode, D40_PQ20) {
+ using T = faiss::cppcontrib::IndexPQDecoder<40, 2>;
+ testIndexPQDecoder<T>(NSAMPLES, 40, "PQ20np");
+}
+#endif
+
+// test IndexRowwiseMinMaxFP16
+TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF256_PQ16) {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(NSAMPLES, 256, "MinMaxFP16,IVF256,PQ16np");
+}
+
+TEST(testCppcontribSaDecode, D256_MINMAXFP16_PQ16) {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(NSAMPLES, 256, "MinMaxFP16,PQ16np");
+}
+
+// test IndexRowwiseMinMax
+TEST(testCppcontribSaDecode, D256_MINMAX_IVF256_PQ16) {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;
+ using T = faiss::cppcontrib::IndexMinMaxDecoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(NSAMPLES, 256, "MinMax,IVF256,PQ16np");
+}
+
+TEST(testCppcontribSaDecode, D256_MINMAX_PQ16) {
+ using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;
+ using T = faiss::cppcontrib::IndexMinMaxDecoder<SubT>;
+ testMinMaxIndexPQDecoder<T>(NSAMPLES, 256, "MinMax,PQ16np");
+}
+
+// implemented for AVX2 and ARM so far
+#if defined(__AVX2__) || defined(__ARM_NEON)
+TEST(testCppcontribSaDecode, D256_PQ16x10) {
+ using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;
+ testIndexPQDecoder<T>(NSAMPLES * 4, 256, "PQ16x10np");
+}
+
+TEST(testCppcontribSaDecode, D256_PQ16x12) {
+ using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 12>;
+ testIndexPQDecoder<T>(NSAMPLES * 16, 256, "PQ16x12np");
+}
+
+TEST(testCppcontribSaDecode, D160_PQ20x10) {
+ using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;
+ testIndexPQDecoder<T>(NSAMPLES * 4, 160, "PQ20x10np");
+}
+
+TEST(testCppcontribSaDecode, D160_PQ20x12) {
+ using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 12>;
+ testIndexPQDecoder<T>(NSAMPLES * 16, 160, "PQ20x12np");
+}
+
+TEST(testCppcontribSaDecode, D256_IVF256_PQ16x10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 4, 256, "IVF256,PQ16x10np");
+}
+
+TEST(testCppcontribSaDecode, D256_IVF256_PQ16x12) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 12>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 16, 256, "IVF256,PQ16x12np");
+}
+
+TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF256_PQ16x10) {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ NSAMPLES * 4, 256, "MinMaxFP16,IVF256,PQ16x10np");
+}
+
+TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF1024_PQ16x10) {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ NSAMPLES * 4, 256, "MinMaxFP16,IVF1024,PQ16x10np");
+}
+
+TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {
+ using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;
+ using T = faiss::cppcontrib::IndexMinMaxFP16Decoder<SubT>;
+ testMinMaxIndex2LevelDecoder<T>(
+ NSAMPLES * 4, 256, "MinMaxFP16,IVF1024,PQ16x10np");
+}
+
+TEST(testCppcontribSaDecode, D160_Residual4x8_PQ8x10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 4, 160, "Residual4x8,PQ8x10");
+}
+
+TEST(testCppcontribSaDecode, D256_Residual1x9_PQ16x10) {
+ // It is acceptable to use COARSE_BITS=16 in this case,
+ // because there's only one coarse quantizer element.
+ // It won't work for "Residual2x9,PQ16x10".
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 4, 256, "Residual1x9,PQ16x10");
+}
+
+TEST(testCppcontribSaDecode, D256_Residual4x10_PQ16x10) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 4, 256, "Residual4x10,PQ16x10");
+}
+
+TEST(testCppcontribSaDecode, D256_Residual4x12_PQ16x12) {
+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 12, 12>;
+ testIndex2LevelDecoder<T>(NSAMPLES * 16, 256, "Residual4x12,PQ16x12");
+}
+
+#endif
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_cppcontrib_uintreader.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_cppcontrib_uintreader.cpp
new file mode 100644
index 0000000..aa17ad6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_cppcontrib_uintreader.cpp
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+// This test was designed to be run using valgrind or ASAN to test the
+// correctness of memory accesses.
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <random>
+
+#include <faiss/utils/hamming.h>
+
+#include <faiss/cppcontrib/detail/UintReader.h>
+
+template <intptr_t N_ELEMENTS, intptr_t CODE_BITS, intptr_t CPOS>
+struct TestLoop {
+ static void test(
+ const uint8_t* const container,
+ faiss::BitstringReader& br) {
+ // validate
+ const intptr_t uintreader_data = faiss::cppcontrib::detail::
+ UintReaderRaw<N_ELEMENTS, CODE_BITS, CPOS>::get(container);
+ const intptr_t bitstringreader_data = br.read(CODE_BITS);
+
+ ASSERT_EQ(uintreader_data, bitstringreader_data)
+ << "Mismatch between BitstringReader (" << bitstringreader_data
+ << ") and UintReader (" << uintreader_data
+ << ") for N_ELEMENTS=" << N_ELEMENTS
+ << ", CODE_BITS=" << CODE_BITS << ", CPOS=" << CPOS;
+
+ //
+ TestLoop<N_ELEMENTS, CODE_BITS, CPOS + 1>::test(container, br);
+ }
+};
+
+template <intptr_t N_ELEMENTS, intptr_t CODE_BITS>
+struct TestLoop<N_ELEMENTS, CODE_BITS, N_ELEMENTS> {
+ static void test(
+ const uint8_t* const container,
+ faiss::BitstringReader& br) {}
+};
+
+template <intptr_t N_ELEMENTS, intptr_t CODE_BITS>
+void TestUintReader() {
+ constexpr intptr_t CODE_BYTES = (CODE_BITS * N_ELEMENTS + 7) / 8;
+
+ std::default_random_engine rng;
+ std::uniform_int_distribution<uint64_t> u(0, 1 << CODE_BITS);
+
+ // do several attempts
+ for (size_t attempt = 0; attempt < 10; attempt++) {
+ // allocate a buffer. This way, not std::vector
+ std::unique_ptr<uint8_t[]> container(new uint8_t[CODE_BYTES]);
+ // make it empty
+ for (size_t i = 0; i < CODE_BYTES; i++) {
+ container.get()[i] = 0;
+ }
+
+ // populate it
+ faiss::BitstringWriter bw(container.get(), CODE_BYTES);
+ for (size_t i = 0; i < N_ELEMENTS; i++) {
+ bw.write(u(rng), CODE_BITS);
+ }
+
+ // read it back and verify against bitreader
+ faiss::BitstringReader br(container.get(), CODE_BYTES);
+
+ TestLoop<N_ELEMENTS, CODE_BITS, 0>::test(container.get(), br);
+ }
+}
+
+template <intptr_t CODE_BITS>
+void TestUintReaderBits() {
+ TestUintReader<1, CODE_BITS>();
+ TestUintReader<2, CODE_BITS>();
+ TestUintReader<3, CODE_BITS>();
+ TestUintReader<4, CODE_BITS>();
+ TestUintReader<5, CODE_BITS>();
+ TestUintReader<6, CODE_BITS>();
+ TestUintReader<7, CODE_BITS>();
+ TestUintReader<8, CODE_BITS>();
+ TestUintReader<9, CODE_BITS>();
+ TestUintReader<10, CODE_BITS>();
+ TestUintReader<11, CODE_BITS>();
+ TestUintReader<12, CODE_BITS>();
+ TestUintReader<13, CODE_BITS>();
+ TestUintReader<14, CODE_BITS>();
+ TestUintReader<15, CODE_BITS>();
+ TestUintReader<16, CODE_BITS>();
+ TestUintReader<17, CODE_BITS>();
+}
+
+TEST(testCppcontribUintreader, Test8bit) {
+ TestUintReaderBits<8>();
+}
+
+TEST(testCppcontribUintreader, Test10bit) {
+ TestUintReaderBits<10>();
+}
+
+TEST(testCppcontribUintreader, Test12bit) {
+ TestUintReaderBits<12>();
+}
+
+TEST(testCppcontribUintreader, Test16bit) {
+ TestUintReaderBits<16>();
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_dealloc_invlists.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_dealloc_invlists.cpp
new file mode 100644
index 0000000..8ad278c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_dealloc_invlists.cpp
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <memory>
+#include <random>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/IVFlib.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/index_factory.h>
+
+using namespace faiss;
+
+namespace {
+
+// dimension of the vectors to index
+int d = 32;
+
+// nb of training vectors
+size_t nt = 5000;
+
+// size of the database points per window step
+size_t nb = 1000;
+
+// nb of queries
+size_t nq = 200;
+
+std::mt19937 rng;
+
+std::vector<float> make_data(size_t n) {
+ std::vector<float> database(n * d);
+ std::uniform_real_distribution<> distrib;
+
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<Index> make_trained_index(const char* index_type) {
+ auto index = std::unique_ptr<Index>(index_factory(d, index_type));
+ auto xt = make_data(nt * d);
+ index->train(nt, xt.data());
+ ParameterSpace().set_index_parameter(index.get(), "nprobe", 4);
+ return index;
+}
+
+std::vector<idx_t> search_index(Index* index, const float* xq) {
+ int k = 10;
+ std::vector<idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+ index->search(nq, xq, k, D.data(), I.data());
+ return I;
+}
+
+/*************************************************************
+ * Test functions for a given index type
+ *************************************************************/
+
+struct EncapsulateInvertedLists : InvertedLists {
+ const InvertedLists* il;
+
+ EncapsulateInvertedLists(const InvertedLists* il)
+ : InvertedLists(il->nlist, il->code_size), il(il) {}
+
+ static void* memdup(const void* m, size_t size) {
+ if (size == 0)
+ return nullptr;
+ return memcpy(malloc(size), m, size);
+ }
+
+ size_t list_size(size_t list_no) const override {
+ return il->list_size(list_no);
+ }
+
+ const uint8_t* get_codes(size_t list_no) const override {
+ return (uint8_t*)memdup(
+ il->get_codes(list_no), list_size(list_no) * code_size);
+ }
+
+ const idx_t* get_ids(size_t list_no) const override {
+ return (idx_t*)memdup(
+ il->get_ids(list_no), list_size(list_no) * sizeof(idx_t));
+ }
+
+ void release_codes(size_t, const uint8_t* codes) const override {
+ free((void*)codes);
+ }
+
+ void release_ids(size_t, const idx_t* ids) const override {
+ free((void*)ids);
+ }
+
+ const uint8_t* get_single_code(size_t list_no, size_t offset)
+ const override {
+ return (uint8_t*)memdup(
+ il->get_single_code(list_no, offset), code_size);
+ }
+
+ size_t add_entries(size_t, size_t, const idx_t*, const uint8_t*) override {
+ assert(!"not implemented");
+ return 0;
+ }
+
+ void update_entries(size_t, size_t, size_t, const idx_t*, const uint8_t*)
+ override {
+ assert(!"not implemented");
+ }
+
+ void resize(size_t, size_t) override {
+ assert(!"not implemented");
+ }
+
+ ~EncapsulateInvertedLists() override {}
+};
+
+int test_dealloc_invlists(const char* index_key) {
+ std::unique_ptr<Index> index = make_trained_index(index_key);
+ IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get());
+
+ auto xb = make_data(nb * d);
+ index->add(nb, xb.data());
+
+ auto xq = make_data(nq * d);
+
+ auto ref_res = search_index(index.get(), xq.data());
+
+ EncapsulateInvertedLists eil(index_ivf->invlists);
+
+ index_ivf->own_invlists = false;
+ index_ivf->replace_invlists(&eil, false);
+
+ // TEST: this could crash or leak mem
+ auto new_res = search_index(index.get(), xq.data());
+
+ // delete explicitly
+ delete eil.il;
+
+ // just to make sure
+ EXPECT_EQ(ref_res, new_res);
+ return 0;
+}
+
+} // anonymous namespace
+
+/*************************************************************
+ * Test entry points
+ *************************************************************/
+
+TEST(TestIvlistDealloc, IVFFlat) {
+ test_dealloc_invlists("IVF32,Flat");
+}
+
+TEST(TestIvlistDealloc, IVFSQ) {
+ test_dealloc_invlists("IVF32,SQ8");
+}
+
+TEST(TestIvlistDealloc, IVFPQ) {
+ test_dealloc_invlists("IVF32,PQ4np");
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_disable_pq_sdc_tables.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_disable_pq_sdc_tables.cpp
new file mode 100644
index 0000000..f94aac8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_disable_pq_sdc_tables.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <random>
+
+#include "faiss/Index.h"
+#include "faiss/IndexHNSW.h"
+#include "faiss/index_factory.h"
+#include "faiss/index_io.h"
+#include "test_util.h"
+
+pthread_mutex_t temp_file_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+TEST(IO, TestReadHNSWPQ_whenSDCDisabledFlagPassed_thenDisableSDCTable) {
+ // Create a temp file name with a randomized component for stress runs
+ std::random_device rd;
+ std::mt19937 mt(rd());
+ std::uniform_real_distribution<float> dist(0, 9999999);
+ std::string temp_file_name =
+ "/tmp/faiss_TestReadHNSWPQ" + std::to_string(int(dist(mt)));
+ Tempfilename index_filename(&temp_file_mutex, temp_file_name);
+
+ // Create a HNSW index with PQ encoding
+ int d = 32, n = 256;
+ std::default_random_engine rng(123);
+ std::uniform_real_distribution<float> u(0, 100);
+ std::vector<float> vectors(n * d);
+ for (size_t i = 0; i < n * d; i++) {
+ vectors[i] = u(rng);
+ }
+
+ // Build the index and write it to the temp file
+ {
+ std::unique_ptr<faiss::Index> index_writer(
+ faiss::index_factory(d, "HNSW8,PQ4np", faiss::METRIC_L2));
+ index_writer->train(n, vectors.data());
+ index_writer->add(n, vectors.data());
+
+ faiss::write_index(index_writer.get(), index_filename.c_str());
+ }
+
+ // Load index from disk. Confirm that the sdc table is equal to 0 when
+ // disable sdc is set
+ {
+ std::unique_ptr<faiss::IndexHNSWPQ> index_reader_read_write(
+ dynamic_cast<faiss::IndexHNSWPQ*>(
+ faiss::read_index(index_filename.c_str())));
+ std::unique_ptr<faiss::IndexHNSWPQ> index_reader_sdc_disabled(
+ dynamic_cast<faiss::IndexHNSWPQ*>(faiss::read_index(
+ index_filename.c_str(),
+ faiss::IO_FLAG_PQ_SKIP_SDC_TABLE)));
+
+ ASSERT_NE(
+ dynamic_cast<faiss::IndexPQ*>(index_reader_read_write->storage)
+ ->pq.sdc_table.size(),
+ 0);
+ ASSERT_EQ(
+ dynamic_cast<faiss::IndexPQ*>(
+ index_reader_sdc_disabled->storage)
+ ->pq.sdc_table.size(),
+ 0);
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_distances_simd.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_distances_simd.cpp
new file mode 100644
index 0000000..539fe2a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_distances_simd.cpp
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <random>
+#include <vector>
+
+#include <faiss/utils/distances.h>
+
+// reference implementations
+void fvec_inner_products_ny_ref(
+ float* ip,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ for (size_t i = 0; i < ny; i++) {
+ ip[i] = faiss::fvec_inner_product(x, y, d);
+ y += d;
+ }
+}
+
+void fvec_L2sqr_ny_ref(
+ float* dis,
+ const float* x,
+ const float* y,
+ size_t d,
+ size_t ny) {
+ for (size_t i = 0; i < ny; i++) {
+ dis[i] = faiss::fvec_L2sqr(x, y, d);
+ y += d;
+ }
+}
+
+// test templated versions of fvec_L2sqr_ny
+TEST(TestFvecL2sqrNy, D2) {
+ // we're using int values in order to get 100% accurate
+ // results with floats.
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> u(0, 32);
+
+ for (const auto dim : {2, 4, 8, 12}) {
+ std::vector<float> x(dim, 0);
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = u(rng);
+ }
+
+ for (const auto nrows : {1, 2, 5, 10, 15, 20, 25}) {
+ std::vector<float> y(nrows * dim);
+ for (size_t i = 0; i < y.size(); i++) {
+ y[i] = u(rng);
+ }
+
+ std::vector<float> distances(nrows, 0);
+ faiss::fvec_L2sqr_ny(
+ distances.data(), x.data(), y.data(), dim, nrows);
+
+ std::vector<float> distances_ref(nrows, 0);
+ fvec_L2sqr_ny_ref(
+ distances_ref.data(), x.data(), y.data(), dim, nrows);
+
+ ASSERT_EQ(distances, distances_ref)
+ << "Mismatching results for dim = " << dim
+ << ", nrows = " << nrows;
+ }
+ }
+}
+
+// fvec_inner_products_ny
+TEST(TestFvecInnerProductsNy, D2) {
+ // we're using int values in order to get 100% accurate
+ // results with floats.
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> u(0, 32);
+
+ for (const auto dim : {2, 4, 8, 12}) {
+ std::vector<float> x(dim, 0);
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = u(rng);
+ }
+
+ for (const auto nrows : {1, 2, 5, 10, 15, 20, 25}) {
+ std::vector<float> y(nrows * dim);
+ for (size_t i = 0; i < y.size(); i++) {
+ y[i] = u(rng);
+ }
+
+ std::vector<float> distances(nrows, 0);
+ faiss::fvec_inner_products_ny(
+ distances.data(), x.data(), y.data(), dim, nrows);
+
+ std::vector<float> distances_ref(nrows, 0);
+ fvec_inner_products_ny_ref(
+ distances_ref.data(), x.data(), y.data(), dim, nrows);
+
+ ASSERT_EQ(distances, distances_ref)
+ << "Mismatching results for dim = " << dim
+ << ", nrows = " << nrows;
+ }
+ }
+}
+
+TEST(TestFvecL2sqr, distances_L2_squared_y_transposed) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ // modulo 8 results - 16 is to repeat the loop in the function
+ int ny = 11; // this value will hit all the codepaths
+ for (const auto d : {1, 2, 3, 4, 5, 6, 7, 8, 16}) {
+ // initialize inputs
+ std::vector<float> x(d);
+ float x_sqlen = 0;
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = uniform(rng);
+ x_sqlen += x[i] * x[i];
+ }
+ std::vector<float> y(d * ny);
+ std::vector<float> y_sqlens(ny, 0);
+ for (size_t i = 0; i < ny; i++) {
+ for (size_t j = 0; j < y.size(); j++) {
+ y[j] = uniform(rng);
+ y_sqlens[i] += y[j] * y[j];
+ }
+ }
+
+ // perform function
+ std::vector<float> true_distances(ny, 0);
+ for (size_t i = 0; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < d; j++) {
+ dp += x[j] * y[i + j * ny];
+ }
+ true_distances[i] = x_sqlen + y_sqlens[i] - 2 * dp;
+ }
+
+ std::vector<float> distances(ny);
+ faiss::fvec_L2sqr_ny_transposed(
+ distances.data(),
+ x.data(),
+ y.data(),
+ y_sqlens.data(),
+ d,
+ ny, // no need for special offset to test all lines of code
+ ny);
+
+ ASSERT_EQ(distances, true_distances)
+ << "Mismatching fvec_L2sqr_ny_transposed results for d = " << d;
+ }
+}
+
+TEST(TestFvecL2sqr, nearest_L2_squared_y_transposed) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ // modulo 8 results - 16 is to repeat the loop in the function
+ int ny = 11; // this value will hit all the codepaths
+ for (const auto d : {1, 2, 3, 4, 5, 6, 7, 8, 16}) {
+ // initialize inputs
+ std::vector<float> x(d);
+ float x_sqlen = 0;
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = uniform(rng);
+ x_sqlen += x[i] * x[i];
+ }
+ std::vector<float> y(d * ny);
+ std::vector<float> y_sqlens(ny, 0);
+ for (size_t i = 0; i < ny; i++) {
+ for (size_t j = 0; j < y.size(); j++) {
+ y[j] = uniform(rng);
+ y_sqlens[i] += y[j] * y[j];
+ }
+ }
+
+ // get distances
+ std::vector<float> distances(ny, 0);
+ for (size_t i = 0; i < ny; i++) {
+ float dp = 0;
+ for (size_t j = 0; j < d; j++) {
+ dp += x[j] * y[i + j * ny];
+ }
+ distances[i] = x_sqlen + y_sqlens[i] - 2 * dp;
+ }
+ // find nearest
+ size_t true_nearest_idx = 0;
+ float min_dis = HUGE_VALF;
+ for (size_t i = 0; i < ny; i++) {
+ if (distances[i] < min_dis) {
+ min_dis = distances[i];
+ true_nearest_idx = i;
+ }
+ }
+
+ std::vector<float> buffer(ny);
+ size_t nearest_idx = faiss::fvec_L2sqr_ny_nearest_y_transposed(
+ buffer.data(),
+ x.data(),
+ y.data(),
+ y_sqlens.data(),
+ d,
+ ny, // no need for special offset to test all lines of code
+ ny);
+
+ ASSERT_EQ(nearest_idx, true_nearest_idx)
+ << "Mismatching fvec_L2sqr_ny_nearest_y_transposed results for d = "
+ << d;
+ }
+}
+
+TEST(TestFvecL1, manhattan_distance) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ // modulo 8 results - 16 is to repeat the while loop in the function
+ for (const auto nrows : {8, 9, 10, 11, 12, 13, 14, 15, 16}) {
+ std::vector<float> x(nrows);
+ std::vector<float> y(nrows);
+ float true_distance = 0;
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = uniform(rng);
+ y[i] = uniform(rng);
+ true_distance += std::abs(x[i] - y[i]);
+ }
+
+ auto distance = faiss::fvec_L1(x.data(), y.data(), x.size());
+
+ ASSERT_EQ(distance, true_distance)
+ << "Mismatching fvec_Linf results for nrows = " << nrows;
+ }
+}
+
+TEST(TestFvecLinf, chebyshev_distance) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ // modulo 8 results - 16 is to repeat the while loop in the function
+ for (const auto nrows : {8, 9, 10, 11, 12, 13, 14, 15, 16}) {
+ std::vector<float> x(nrows);
+ std::vector<float> y(nrows);
+ float true_distance = 0;
+ for (size_t i = 0; i < x.size(); i++) {
+ x[i] = uniform(rng);
+ y[i] = uniform(rng);
+ true_distance = std::max(true_distance, std::abs(x[i] - y[i]));
+ }
+
+ auto distance = faiss::fvec_Linf(x.data(), y.data(), x.size());
+
+ ASSERT_EQ(distance, true_distance)
+ << "Mismatching fvec_Linf results for nrows = " << nrows;
+ }
+}
+
+TEST(TestFvecMadd, multiple_add) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ // modulo 8 results - 16 is to repeat the while loop in the function
+ for (const auto nrows : {8, 9, 10, 11, 12, 13, 14, 15, 16}) {
+ std::vector<float> a(nrows);
+ std::vector<float> b(nrows);
+ const float bf = uniform(rng);
+ std::vector<float> true_distances(nrows);
+ for (size_t i = 0; i < a.size(); i++) {
+ a[i] = uniform(rng);
+ b[i] = uniform(rng);
+ true_distances[i] = a[i] + bf * b[i];
+ }
+
+ std::vector<float> distances(nrows);
+ faiss::fvec_madd(a.size(), a.data(), bf, b.data(), distances.data());
+
+ ASSERT_EQ(distances, true_distances)
+ << "Mismatching fvec_madd results for nrows = " << nrows;
+ }
+}
+
+TEST(TestFvecAdd, add_array) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ for (const auto nrows : {1, 2, 5, 10, 15, 20, 25}) {
+ std::vector<float> a(nrows);
+ std::vector<float> b(nrows);
+ std::vector<float> true_distances(nrows);
+ for (size_t i = 0; i < a.size(); i++) {
+ a[i] = uniform(rng);
+ b[i] = uniform(rng);
+ true_distances[i] = a[i] + b[i];
+ }
+
+ std::vector<float> distances(nrows);
+ faiss::fvec_add(a.size(), a.data(), b.data(), distances.data());
+
+ ASSERT_EQ(distances, true_distances)
+ << "Mismatching array-array fvec_add results for nrows = "
+ << nrows;
+ }
+}
+
+TEST(TestFvecAdd, add_value) {
+ // ints instead of floats for 100% accuracy
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ for (const auto nrows : {1, 2, 5, 10, 15, 20, 25}) {
+ std::vector<float> a(nrows);
+ const float b = uniform(rng); // value to add
+ std::vector<float> true_distances(nrows);
+ for (size_t i = 0; i < a.size(); i++) {
+ a[i] = uniform(rng);
+ true_distances[i] = a[i] + b;
+ }
+
+ std::vector<float> distances(nrows);
+ faiss::fvec_add(a.size(), a.data(), b, distances.data());
+
+ ASSERT_EQ(distances, true_distances)
+ << "Mismatching array-value fvec_add results for nrows = "
+ << nrows;
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_factory_tools.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_factory_tools.cpp
new file mode 100644
index 0000000..f5dda2a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_factory_tools.cpp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/cppcontrib/factory_tools.h>
+#include <faiss/index_factory.h>
+#include <gtest/gtest.h>
+
+namespace faiss {
+
+TEST(TestFactoryTools, TestReverseIndexFactory) {
+ for (const char* factory : {
+ "Flat",
+ "IMI2x5,PQ8x8",
+ "IVF32_HNSW32,SQ8",
+ "IVF8,Flat",
+ "IVF8,SQ4",
+ "IVF8,PQ4x8",
+ "LSHrt",
+ "PQ4x8",
+ "HNSW32",
+ "SQ8",
+ "SQfp16",
+ "NSG24,Flat",
+ "NSG16,SQ8",
+ }) {
+ std::unique_ptr<Index> index{index_factory(64, factory)};
+ ASSERT_TRUE(index);
+ EXPECT_EQ(factory, reverse_index_factory(index.get()));
+ }
+ using Case = std::pair<const char*, const char*>;
+ for (auto [src, dst] : {
+ Case{"SQ8,RFlat", "SQ8,Refine(Flat)"},
+ Case{"NSG", "NSG32,Flat"},
+ Case{"NSG,PQ8", "NSG32,PQ8x8"},
+ }) {
+ std::unique_ptr<Index> index{index_factory(64, src)};
+ ASSERT_TRUE(index);
+ EXPECT_EQ(dst, reverse_index_factory(index.get()));
+ }
+}
+
+} // namespace faiss
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_fastscan_perf.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_fastscan_perf.cpp
new file mode 100644
index 0000000..a1e879b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_fastscan_perf.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <random>
+#include <vector>
+
+#include <omp.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQFastScan.h>
+#include <faiss/impl/AuxIndexStructures.h>
+
+TEST(TestFastScan, knnVSrange) {
+ // small vectors and database
+ int d = 64;
+ size_t nb = 4000;
+
+ // ivf centroids
+ size_t nlist = 4;
+
+ // more than 2 threads to surface
+ // problems related to multi-threading
+ omp_set_num_threads(8);
+
+ // random database, also used as queries
+ std::vector<float> database(nb * d);
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+
+ // build index
+ faiss::IndexFlatL2 coarse_quantizer(d);
+ faiss::IndexIVFPQFastScan index(
+ &coarse_quantizer, d, nlist, d / 2, 4, faiss::METRIC_L2, 32);
+ index.pq.cp.niter = 10; // speed up train
+ index.nprobe = nlist;
+ index.train(nb, database.data());
+ index.add(nb, database.data());
+
+ std::vector<float> distances(nb);
+ std::vector<faiss::idx_t> labels(nb);
+ auto t = std::chrono::high_resolution_clock::now();
+ index.search(nb, database.data(), 1, distances.data(), labels.data());
+ auto knn_time = std::chrono::high_resolution_clock::now() - t;
+
+ faiss::RangeSearchResult rsr(nb);
+ t = std::chrono::high_resolution_clock::now();
+ index.range_search(nb, database.data(), 1.0, &rsr);
+ auto range_time = std::chrono::high_resolution_clock::now() - t;
+
+ // we expect the perf of knn and range search
+ // to be similar, at least within a factor of 4
+ ASSERT_LE(range_time, knn_time * 4);
+ ASSERT_LE(knn_time, range_time * 4);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_hamming.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_hamming.cpp
new file mode 100644
index 0000000..cbce2c8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_hamming.cpp
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <faiss/impl/FaissAssert.h>
+#include <faiss/utils/hamming.h>
+#include <random>
+
+using namespace ::testing;
+
+template <typename T>
+std::string print_data(
+ std::shared_ptr<std::vector<T>> data,
+ const size_t divider) {
+ std::string ret = "";
+ for (int i = 0; i < data->size(); ++i) {
+ if (i % divider) {
+ ret += " ";
+ } else {
+ ret += "|";
+ }
+ ret += std::to_string((*data)[i]);
+ }
+ ret += "|";
+ return ret;
+}
+
+std::stringstream get_correct_hamming_example(
+ const size_t na, // number of queries
+ const size_t nb, // number of candidates
+ const size_t k,
+ const size_t code_size,
+ std::shared_ptr<std::vector<uint8_t>> a,
+ std::shared_ptr<std::vector<uint8_t>> b,
+ std::shared_ptr<std::vector<long>> true_ids,
+ // regular Hamming (bit-level distances)
+ std::shared_ptr<std::vector<int>> true_bit_distances,
+ // generalized Hamming (byte-level distances)
+ std::shared_ptr<std::vector<int>> true_byte_distances) {
+ assert(nb >= k);
+
+ // Initialization
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, nb - 1);
+
+ const size_t nresults = na * k;
+
+ a->clear();
+ a->resize(na * code_size, 1); // query vectors are all 1
+ b->clear();
+ b->resize(nb * code_size, 2); // database vectors are all 2
+ true_ids->clear();
+ true_ids->reserve(nresults);
+ true_bit_distances->clear();
+ true_bit_distances->reserve(nresults);
+ true_byte_distances->clear();
+ true_byte_distances->reserve(nresults);
+
+ // define correct ids (must be unique)
+ std::set<long> correct_ids;
+ do {
+ correct_ids.insert(uniform(rng));
+ } while (correct_ids.size() < k);
+
+ // replace database vector at id with vector more similar to query
+ // ordered, so earlier ids must be more similar
+ for (size_t nmatches = k; nmatches > 0; --nmatches) {
+ // get id and erase it
+ const size_t id = *correct_ids.begin();
+ *correct_ids.erase(correct_ids.begin());
+
+ // assemble true id and distance at locations
+ true_ids->push_back(id);
+ true_bit_distances->push_back(
+ (code_size > nmatches ? code_size - nmatches : 0) *
+ /* per-code distance between 1 and 2 (0b01 and 0b10) */
+ 2);
+ true_byte_distances->push_back(
+ (code_size > nmatches ? code_size - nmatches : 0));
+ for (size_t i = 0; i < nmatches; ++i) {
+ b->begin()[id * code_size + i] = 1; // query byte value
+ }
+ }
+
+ // true_ids, true_bit_distances, true_byte_distances only contain results
+ // for the first query.
+ // Query vectors are identical (all 1s), so copy the first sets of k
+ // distances na-1 times.
+ for (size_t i = 1; i < na; ++i) {
+ true_ids->insert(
+ true_ids->end(), true_ids->begin(), true_ids->begin() + k);
+ true_bit_distances->insert(
+ true_bit_distances->end(),
+ true_bit_distances->begin(),
+ true_bit_distances->begin() + k);
+ true_byte_distances->insert(
+ true_byte_distances->end(),
+ true_byte_distances->begin(),
+ true_byte_distances->begin() + k);
+ }
+
+ // assemble string for debugging
+ std::stringstream ret;
+ ret << "na: " << na << std::endl
+ << "nb: " << nb << std::endl
+ << "k: " << k << std::endl
+ << "code_size: " << code_size << std::endl
+ << "a: " << print_data(a, code_size) << std::endl
+ << "b: " << print_data(b, code_size) << std::endl
+ << "true_ids: " << print_data(true_ids, k) << std::endl
+ << "true_bit_distances: " << print_data(true_bit_distances, k)
+ << std::endl
+ << "true_byte_distances: " << print_data(true_byte_distances, k)
+ << std::endl;
+ return ret;
+}
+
+TEST(TestHamming, test_crosshamming_count_thres) {
+ // Initialize randomizer
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 255);
+
+ // Initialize inputs
+ const size_t n = 10; // number of codes
+ const hamdis_t hamming_threshold = 20;
+
+ // one for each case - 65 is default
+ for (auto ncodes : {8, 16, 32, 64, 65}) {
+ // initialize inputs
+ const int nbits = ncodes * 8;
+ const size_t nwords = nbits / 64;
+ // 8 to for later conversion to uint64_t, and 2 for buffer
+ std::vector<uint8_t> dbs(nwords * n * 8 * 2);
+ for (int i = 0; i < dbs.size(); ++i) {
+ dbs[i] = uniform(rng);
+ }
+
+ // get true distance
+ size_t true_count = 0;
+ uint64_t* bs1 = (uint64_t*)dbs.data();
+ for (int i = 0; i < n; ++i) {
+ uint64_t* bs2 = bs1 + 2;
+ for (int j = i + 1; j < n; ++j) {
+ if (faiss::hamming(bs1 + i * nwords, bs2 + j * nwords, nwords) <
+ hamming_threshold) {
+ ++true_count;
+ }
+ }
+ }
+
+ // run test and check correctness
+ size_t count;
+ if (ncodes == 65) {
+ ASSERT_THROW(
+ faiss::crosshamming_count_thres(
+ dbs.data(), n, hamming_threshold, ncodes, &count),
+ faiss::FaissException);
+ continue;
+ }
+ faiss::crosshamming_count_thres(
+ dbs.data(), n, hamming_threshold, ncodes, &count);
+
+ ASSERT_EQ(count, true_count) << "ncodes = " << ncodes;
+ }
+}
+TEST(TestHamming, test_hamming_thres) {
+ // Initialize randomizer
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 255);
+
+ // Initialize inputs
+ const size_t n1 = 10;
+ const size_t n2 = 15;
+ const hamdis_t hamming_threshold = 100;
+
+ // one for each case - 65 is default
+ for (auto ncodes : {8, 16, 32, 64, 65}) {
+ // initialize inputs
+ const int nbits = ncodes * 8;
+ const size_t nwords = nbits / 64;
+ std::vector<uint8_t> bs1(nwords * n1 * 8);
+ std::vector<uint8_t> bs2(nwords * n2 * 8);
+ for (int i = 0; i < bs1.size(); ++i) {
+ bs1[i] = uniform(rng);
+ }
+ for (int i = 0; i < bs2.size(); ++i) {
+ bs2[i] = uniform(rng);
+ }
+
+ // get true distance
+ size_t true_count = 0;
+ std::vector<int64_t> true_idx;
+ std::vector<hamdis_t> true_dis;
+
+ uint64_t* bs1_64 = (uint64_t*)bs1.data();
+ uint64_t* bs2_64 = (uint64_t*)bs2.data();
+ for (int i = 0; i < n1; ++i) {
+ for (int j = 0; j < n2; ++j) {
+ hamdis_t ham_dist = faiss::hamming(
+ bs1_64 + i * nwords, bs2_64 + j * nwords, nwords);
+ if (ham_dist < hamming_threshold) {
+ ++true_count;
+ true_idx.push_back(i);
+ true_idx.push_back(j);
+ true_dis.push_back(ham_dist);
+ }
+ }
+ }
+
+ // run test and check correctness for both
+ // match_hamming_thres and hamming_count_thres
+ std::vector<int64_t> idx(true_idx.size());
+ std::vector<hamdis_t> dis(true_dis.size());
+ if (ncodes == 65) {
+ ASSERT_THROW(
+ faiss::match_hamming_thres(
+ bs1.data(),
+ bs2.data(),
+ n1,
+ n2,
+ hamming_threshold,
+ ncodes,
+ idx.data(),
+ dis.data()),
+ faiss::FaissException);
+ ASSERT_THROW(
+ faiss::hamming_count_thres(
+ bs1.data(),
+ bs2.data(),
+ n1,
+ n2,
+ hamming_threshold,
+ ncodes,
+ nullptr),
+ faiss::FaissException);
+ continue;
+ }
+ size_t match_count = faiss::match_hamming_thres(
+ bs1.data(),
+ bs2.data(),
+ n1,
+ n2,
+ hamming_threshold,
+ ncodes,
+ idx.data(),
+ dis.data());
+ size_t count_count;
+ faiss::hamming_count_thres(
+ bs1.data(),
+ bs2.data(),
+ n1,
+ n2,
+ hamming_threshold,
+ ncodes,
+ &count_count);
+
+ ASSERT_EQ(match_count, true_count) << "ncodes = " << ncodes;
+ ASSERT_EQ(count_count, true_count) << "ncodes = " << ncodes;
+ ASSERT_EQ(idx, true_idx) << "ncodes = " << ncodes;
+ ASSERT_EQ(dis, true_dis) << "ncodes = " << ncodes;
+ }
+}
+
+TEST(TestHamming, test_hamming_knn) {
+ // Initialize randomizer
+ std::default_random_engine rng(123);
+ std::uniform_int_distribution<int32_t> uniform(0, 32);
+
+ // Initialize inputs
+ const size_t na = 4;
+ const size_t nb = 12; // number of candidates
+ const size_t k = 6;
+
+ auto a = std::make_shared<std::vector<uint8_t>>();
+ auto b = std::make_shared<std::vector<uint8_t>>();
+ auto true_ids = std::make_shared<std::vector<long>>();
+ auto true_bit_distances = std::make_shared<std::vector<int>>();
+ auto true_byte_distances = std::make_shared<std::vector<int>>();
+
+ // 8, 16, 32 are cases - 24 will hit default case
+ // all should be multiples of 8
+ for (auto code_size : {8, 16, 24, 32}) {
+ // get example
+ std::stringstream assert_str = get_correct_hamming_example(
+ na,
+ nb,
+ k,
+ code_size,
+ a,
+ b,
+ true_ids,
+ true_bit_distances,
+ true_byte_distances);
+
+ // run test on generalized_hammings_knn_hc
+ std::vector<long> ids_gen(na * k);
+ std::vector<int> dist_gen(na * k);
+ faiss::int_maxheap_array_t res = {
+ na, k, ids_gen.data(), dist_gen.data()};
+ faiss::generalized_hammings_knn_hc(
+ &res, a->data(), b->data(), nb, code_size, true);
+ ASSERT_EQ(ids_gen, *true_ids) << assert_str.str();
+ ASSERT_EQ(dist_gen, *true_byte_distances) << assert_str.str();
+
+ // run test on hammings_knn
+ std::vector<long> ids_ham_knn(na * k, 0);
+ std::vector<int> dist_ham_knn(na * k, 0);
+ res = {na, k, ids_ham_knn.data(), dist_ham_knn.data()};
+ faiss::hammings_knn(&res, a->data(), b->data(), nb, code_size, true);
+ ASSERT_EQ(ids_ham_knn, *true_ids) << assert_str.str();
+ ASSERT_EQ(dist_ham_knn, *true_bit_distances) << assert_str.str();
+ }
+
+ for (auto code_size : {8, 16, 24, 32}) {
+ std::stringstream assert_str = get_correct_hamming_example(
+ na,
+ nb,
+ /* k */ nb, // faiss::hammings computes all distances
+ code_size,
+ a,
+ b,
+ true_ids,
+ true_bit_distances,
+ true_byte_distances);
+ std::vector<hamdis_t> dist_gen(na * nb);
+ faiss::hammings(
+ a->data(), b->data(), na, nb, code_size, dist_gen.data());
+ EXPECT_EQ(dist_gen, *true_bit_distances) << assert_str.str();
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_heap.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_heap.cpp
new file mode 100644
index 0000000..b707ba8
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_heap.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/utils/Heap.h>
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <numeric>
+
+using namespace faiss;
+
+TEST(Heap, addn_with_ids) {
+ size_t n = 1000;
+ size_t k = 1;
+ std::vector<int64_t> heap_labels(n, -1);
+ std::vector<float> heap_distances(n, 0);
+ float_minheap_array_t heaps = {
+ n, k, heap_labels.data(), heap_distances.data()};
+ heaps.heapify();
+ std::vector<int64_t> labels(n, 1);
+ std::vector<float> distances(n, 0.0f);
+ std::vector<int64_t> subset(n);
+ std::iota(subset.begin(), subset.end(), 0);
+ heaps.addn_with_ids(1, distances.data(), labels.data(), 1);
+ heaps.reorder();
+ EXPECT_TRUE(
+ std::all_of(heap_labels.begin(), heap_labels.end(), [](int64_t i) {
+ return i == 1;
+ }));
+}
+
+TEST(Heap, addn_query_subset_with_ids) {
+ size_t n = 20000000; // more than 2^24
+ size_t k = 1;
+ std::vector<int64_t> heap_labels(n, -1);
+ std::vector<float> heap_distances(n, 0);
+ float_minheap_array_t heaps = {
+ n, k, heap_labels.data(), heap_distances.data()};
+ heaps.heapify();
+ std::vector<int64_t> labels(n, 1);
+ std::vector<float> distances(n, 0.0f);
+ std::vector<int64_t> subset(n);
+ std::iota(subset.begin(), subset.end(), 0);
+ heaps.addn_query_subset_with_ids(
+ n, subset.data(), 1, distances.data(), labels.data(), 1);
+ heaps.reorder();
+ EXPECT_TRUE(
+ std::all_of(heap_labels.begin(), heap_labels.end(), [](int64_t i) {
+ return i == 1;
+ }));
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_hnsw.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_hnsw.cpp
new file mode 100644
index 0000000..9c33c08
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_hnsw.cpp
@@ -0,0 +1,657 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <limits>
+#include <random>
+#include <unordered_set>
+#include <vector>
+
+#include <faiss/IndexHNSW.h>
+#include <faiss/impl/HNSW.h>
+#include <faiss/impl/ResultHandler.h>
+#include <faiss/utils/random.h>
+
+int reference_pop_min(faiss::HNSW::MinimaxHeap& heap, float* vmin_out) {
+ assert(heap.k > 0);
+ // returns min. This is an O(n) operation
+ int i = heap.k - 1;
+ while (i >= 0) {
+ if (heap.ids[i] != -1)
+ break;
+ i--;
+ }
+ if (i == -1)
+ return -1;
+ int imin = i;
+ float vmin = heap.dis[i];
+ i--;
+ while (i >= 0) {
+ if (heap.ids[i] != -1 && heap.dis[i] < vmin) {
+ vmin = heap.dis[i];
+ imin = i;
+ }
+ i--;
+ }
+ if (vmin_out)
+ *vmin_out = vmin;
+ int ret = heap.ids[imin];
+ heap.ids[imin] = -1;
+ --heap.nvalid;
+
+ return ret;
+}
+
+void test_popmin(int heap_size, int amount_to_put) {
+ // create a heap
+ faiss::HNSW::MinimaxHeap mm_heap(heap_size);
+
+ using storage_idx_t = faiss::HNSW::storage_idx_t;
+
+ std::default_random_engine rng(123 + heap_size * amount_to_put);
+ std::uniform_int_distribution<storage_idx_t> u(0, 65536);
+ std::uniform_real_distribution<float> uf(0, 1);
+
+ // generate random unique indices
+ std::unordered_set<storage_idx_t> indices;
+ while (indices.size() < amount_to_put) {
+ const storage_idx_t index = u(rng);
+ indices.insert(index);
+ }
+
+ // put ones into the heap
+ for (const auto index : indices) {
+ float distance = uf(rng);
+ if (distance >= 0.7f) {
+ // add infinity values from time to time
+ distance = std::numeric_limits<float>::infinity();
+ }
+ mm_heap.push(index, distance);
+ }
+
+ // clone the heap
+ faiss::HNSW::MinimaxHeap cloned_mm_heap = mm_heap;
+
+ // takes ones out one by one
+ while (mm_heap.size() > 0) {
+ // compare heaps
+ ASSERT_EQ(mm_heap.n, cloned_mm_heap.n);
+ ASSERT_EQ(mm_heap.k, cloned_mm_heap.k);
+ ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid);
+ ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids);
+ ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis);
+
+ // use the reference pop_min for the cloned heap
+ float cloned_vmin_dis = std::numeric_limits<float>::quiet_NaN();
+ storage_idx_t cloned_vmin_idx =
+ reference_pop_min(cloned_mm_heap, &cloned_vmin_dis);
+
+ float vmin_dis = std::numeric_limits<float>::quiet_NaN();
+ storage_idx_t vmin_idx = mm_heap.pop_min(&vmin_dis);
+
+ // compare returns
+ ASSERT_EQ(vmin_dis, cloned_vmin_dis);
+ ASSERT_EQ(vmin_idx, cloned_vmin_idx);
+ }
+
+ // compare heaps again
+ ASSERT_EQ(mm_heap.n, cloned_mm_heap.n);
+ ASSERT_EQ(mm_heap.k, cloned_mm_heap.k);
+ ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid);
+ ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids);
+ ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis);
+}
+
+void test_popmin_identical_distances(
+ int heap_size,
+ int amount_to_put,
+ const float distance) {
+ // create a heap
+ faiss::HNSW::MinimaxHeap mm_heap(heap_size);
+
+ using storage_idx_t = faiss::HNSW::storage_idx_t;
+
+ std::default_random_engine rng(123 + heap_size * amount_to_put);
+ std::uniform_int_distribution<storage_idx_t> u(0, 65536);
+
+ // generate random unique indices
+ std::unordered_set<storage_idx_t> indices;
+ while (indices.size() < amount_to_put) {
+ const storage_idx_t index = u(rng);
+ indices.insert(index);
+ }
+
+ // put ones into the heap
+ for (const auto index : indices) {
+ mm_heap.push(index, distance);
+ }
+
+ // clone the heap
+ faiss::HNSW::MinimaxHeap cloned_mm_heap = mm_heap;
+
+ // takes ones out one by one
+ while (mm_heap.size() > 0) {
+ // compare heaps
+ ASSERT_EQ(mm_heap.n, cloned_mm_heap.n);
+ ASSERT_EQ(mm_heap.k, cloned_mm_heap.k);
+ ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid);
+ ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids);
+ ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis);
+
+ // use the reference pop_min for the cloned heap
+ float cloned_vmin_dis = std::numeric_limits<float>::quiet_NaN();
+ storage_idx_t cloned_vmin_idx =
+ reference_pop_min(cloned_mm_heap, &cloned_vmin_dis);
+
+ float vmin_dis = std::numeric_limits<float>::quiet_NaN();
+ storage_idx_t vmin_idx = mm_heap.pop_min(&vmin_dis);
+
+ // compare returns
+ ASSERT_EQ(vmin_dis, cloned_vmin_dis);
+ ASSERT_EQ(vmin_idx, cloned_vmin_idx);
+ }
+
+ // compare heaps again
+ ASSERT_EQ(mm_heap.n, cloned_mm_heap.n);
+ ASSERT_EQ(mm_heap.k, cloned_mm_heap.k);
+ ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid);
+ ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids);
+ ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis);
+}
+
+TEST(HNSW, Test_popmin) {
+ std::vector<size_t> sizes = {1, 2, 3, 4, 5, 7, 9, 11, 16, 27, 32, 64, 128};
+ for (const size_t size : sizes) {
+ for (size_t amount = size; amount > 0; amount /= 2) {
+ test_popmin(size, amount);
+ }
+ }
+}
+
+TEST(HNSW, Test_popmin_identical_distances) {
+ std::vector<size_t> sizes = {1, 2, 3, 4, 5, 7, 9, 11, 16, 27, 32};
+ for (const size_t size : sizes) {
+ for (size_t amount = size; amount > 0; amount /= 2) {
+ test_popmin_identical_distances(size, amount, 1.0f);
+ }
+ }
+}
+
+TEST(HNSW, Test_popmin_infinite_distances) {
+ std::vector<size_t> sizes = {1, 2, 3, 4, 5, 7, 9, 11, 16, 27, 32};
+ for (const size_t size : sizes) {
+ for (size_t amount = size; amount > 0; amount /= 2) {
+ test_popmin_identical_distances(
+ size, amount, std::numeric_limits<float>::infinity());
+ }
+ }
+}
+
+TEST(HNSW, Test_IndexHNSW_METRIC_Lp) {
+ // Create an HNSW index with METRIC_Lp and metric_arg = 3
+ faiss::IndexFlat storage_index(1, faiss::METRIC_Lp);
+ storage_index.metric_arg = 3;
+ faiss::IndexHNSW index(&storage_index, 32);
+
+ // Add a single data point
+ float data[1] = {0.0};
+ index.add(1, data);
+
+ // Prepare a query
+ float query[1] = {2.0};
+ float distance;
+ faiss::idx_t label;
+
+ index.search(1, query, 1, &distance, &label);
+
+ EXPECT_NEAR(distance, 8.0, 1e-5); // Distance should be 8.0 (2^3)
+ EXPECT_EQ(label, 0); // Label should be 0
+}
+
+class HNSWTest : public testing::Test {
+ protected:
+ HNSWTest() {
+ xb = std::make_unique<std::vector<float>>(d * nb);
+ xb->reserve(d * nb);
+ faiss::float_rand(xb->data(), d * nb, 12345);
+ index = std::make_unique<faiss::IndexHNSWFlat>(d, M);
+ index->add(nb, xb->data());
+ xq = std::unique_ptr<std::vector<float>>(
+ new std::vector<float>(d * nq));
+ xq->reserve(d * nq);
+ faiss::float_rand(xq->data(), d * nq, 12345);
+ dis = std::unique_ptr<faiss::DistanceComputer>(
+ index->storage->get_distance_computer());
+ dis->set_query(xq->data() + 0 * index->d);
+ }
+
+ const int d = 64;
+ const int nb = 2000;
+ const int M = 4;
+ const int nq = 10;
+ const int k = 10;
+ std::unique_ptr<std::vector<float>> xb;
+ std::unique_ptr<std::vector<float>> xq;
+ std::unique_ptr<faiss::DistanceComputer> dis;
+ std::unique_ptr<faiss::IndexHNSWFlat> index;
+};
+
+/** Do a BFS on the candidates list */
+int reference_search_from_candidates(
+ const faiss::HNSW& hnsw,
+ faiss::DistanceComputer& qdis,
+ faiss::ResultHandler<faiss::HNSW::C>& res,
+ faiss::HNSW::MinimaxHeap& candidates,
+ faiss::VisitedTable& vt,
+ faiss::HNSWStats& stats,
+ int level,
+ int nres_in,
+ const faiss::SearchParametersHNSW* params) {
+ int nres = nres_in;
+ int ndis = 0;
+
+ // can be overridden by search params
+ bool do_dis_check = params ? params->check_relative_distance
+ : hnsw.check_relative_distance;
+ int efSearch = params ? params->efSearch : hnsw.efSearch;
+ const faiss::IDSelector* sel = params ? params->sel : nullptr;
+
+ faiss::HNSW::C::T threshold = res.threshold;
+ for (int i = 0; i < candidates.size(); i++) {
+ faiss::idx_t v1 = candidates.ids[i];
+ float d = candidates.dis[i];
+ FAISS_ASSERT(v1 >= 0);
+ if (!sel || sel->is_member(v1)) {
+ if (d < threshold) {
+ if (res.add_result(d, v1)) {
+ threshold = res.threshold;
+ }
+ }
+ }
+ vt.set(v1);
+ }
+
+ int nstep = 0;
+
+ while (candidates.size() > 0) {
+ float d0 = 0;
+ int v0 = candidates.pop_min(&d0);
+
+ if (do_dis_check) {
+ // tricky stopping condition: there are more that ef
+ // distances that are processed already that are smaller
+ // than d0
+
+ int n_dis_below = candidates.count_below(d0);
+ if (n_dis_below >= efSearch) {
+ break;
+ }
+ }
+
+ size_t begin, end;
+ hnsw.neighbor_range(v0, level, &begin, &end);
+
+ // a reference version
+ for (size_t j = begin; j < end; j++) {
+ int v1 = hnsw.neighbors[j];
+ if (v1 < 0)
+ break;
+ if (vt.get(v1)) {
+ continue;
+ }
+ vt.set(v1);
+ ndis++;
+ float d = qdis(v1);
+ if (!sel || sel->is_member(v1)) {
+ if (d < threshold) {
+ if (res.add_result(d, v1)) {
+ threshold = res.threshold;
+ nres += 1;
+ }
+ }
+ }
+
+ candidates.push(v1, d);
+ }
+
+ nstep++;
+ if (!do_dis_check && nstep > efSearch) {
+ break;
+ }
+ }
+
+ if (level == 0) {
+ stats.n1++;
+ if (candidates.size() == 0) {
+ stats.n2++;
+ }
+ stats.ndis += ndis;
+ stats.nhops += nstep;
+ }
+
+ return nres;
+}
+
+faiss::HNSWStats reference_greedy_update_nearest(
+ const faiss::HNSW& hnsw,
+ faiss::DistanceComputer& qdis,
+ int level,
+ faiss::HNSW::storage_idx_t& nearest,
+ float& d_nearest) {
+ faiss::HNSWStats stats;
+
+ for (;;) {
+ faiss::HNSW::storage_idx_t prev_nearest = nearest;
+
+ size_t begin, end;
+ hnsw.neighbor_range(nearest, level, &begin, &end);
+
+ size_t ndis = 0;
+
+ for (size_t i = begin; i < end; i++) {
+ faiss::HNSW::storage_idx_t v = hnsw.neighbors[i];
+ if (v < 0)
+ break;
+ ndis += 1;
+ float dis = qdis(v);
+ if (dis < d_nearest) {
+ nearest = v;
+ d_nearest = dis;
+ }
+ }
+ // update stats
+ stats.ndis += ndis;
+ stats.nhops += 1;
+
+ if (nearest == prev_nearest) {
+ return stats;
+ }
+ }
+}
+
+std::priority_queue<faiss::HNSW::Node> reference_search_from_candidate_unbounded(
+ const faiss::HNSW& hnsw,
+ const faiss::HNSW::Node& node,
+ faiss::DistanceComputer& qdis,
+ int ef,
+ faiss::VisitedTable* vt,
+ faiss::HNSWStats& stats) {
+ int ndis = 0;
+ std::priority_queue<faiss::HNSW::Node> top_candidates;
+ std::priority_queue<
+ faiss::HNSW::Node,
+ std::vector<faiss::HNSW::Node>,
+ std::greater<faiss::HNSW::Node>>
+ candidates;
+
+ top_candidates.push(node);
+ candidates.push(node);
+
+ vt->set(node.second);
+
+ while (!candidates.empty()) {
+ float d0;
+ faiss::HNSW::storage_idx_t v0;
+ std::tie(d0, v0) = candidates.top();
+
+ if (d0 > top_candidates.top().first) {
+ break;
+ }
+
+ candidates.pop();
+
+ size_t begin, end;
+ hnsw.neighbor_range(v0, 0, &begin, &end);
+
+ for (size_t j = begin; j < end; ++j) {
+ int v1 = hnsw.neighbors[j];
+
+ if (v1 < 0) {
+ break;
+ }
+ if (vt->get(v1)) {
+ continue;
+ }
+
+ vt->set(v1);
+
+ float d1 = qdis(v1);
+ ++ndis;
+
+ if (top_candidates.top().first > d1 || top_candidates.size() < ef) {
+ candidates.emplace(d1, v1);
+ top_candidates.emplace(d1, v1);
+
+ if (top_candidates.size() > ef) {
+ top_candidates.pop();
+ }
+ }
+ }
+
+ stats.nhops += 1;
+ }
+
+ ++stats.n1;
+ if (candidates.size() == 0) {
+ ++stats.n2;
+ }
+ stats.ndis += ndis;
+
+ return top_candidates;
+}
+
+TEST_F(HNSWTest, TEST_search_from_candidate_unbounded) {
+ omp_set_num_threads(1);
+ auto nearest = index->hnsw.entry_point;
+ float d_nearest = (*dis)(nearest);
+ auto node = faiss::HNSW::Node(d_nearest, nearest);
+ faiss::VisitedTable vt(index->ntotal);
+ faiss::HNSWStats stats;
+
+ // actual version
+ auto top_candidates = faiss::search_from_candidate_unbounded(
+ index->hnsw, node, *dis, k, &vt, stats);
+
+ auto reference_nearest = index->hnsw.entry_point;
+ float reference_d_nearest = (*dis)(nearest);
+ auto reference_node =
+ faiss::HNSW::Node(reference_d_nearest, reference_nearest);
+ faiss::VisitedTable reference_vt(index->ntotal);
+ faiss::HNSWStats reference_stats;
+
+ // reference version
+ auto reference_top_candidates = reference_search_from_candidate_unbounded(
+ index->hnsw,
+ reference_node,
+ *dis,
+ k,
+ &reference_vt,
+ reference_stats);
+ EXPECT_EQ(stats.ndis, reference_stats.ndis);
+ EXPECT_EQ(stats.nhops, reference_stats.nhops);
+ EXPECT_EQ(stats.n1, reference_stats.n1);
+ EXPECT_EQ(stats.n2, reference_stats.n2);
+ EXPECT_EQ(top_candidates.size(), reference_top_candidates.size());
+}
+
+TEST_F(HNSWTest, TEST_greedy_update_nearest) {
+ omp_set_num_threads(1);
+
+ auto nearest = index->hnsw.entry_point;
+ float d_nearest = (*dis)(nearest);
+ auto reference_nearest = index->hnsw.entry_point;
+ float reference_d_nearest = (*dis)(reference_nearest);
+
+ // actual version
+ auto stats = faiss::greedy_update_nearest(
+ index->hnsw, *dis, 0, nearest, d_nearest);
+
+ // reference version
+ auto reference_stats = reference_greedy_update_nearest(
+ index->hnsw, *dis, 0, reference_nearest, reference_d_nearest);
+ EXPECT_EQ(stats.ndis, reference_stats.ndis);
+ EXPECT_EQ(stats.nhops, reference_stats.nhops);
+ EXPECT_EQ(stats.n1, reference_stats.n1);
+ EXPECT_EQ(stats.n2, reference_stats.n2);
+ EXPECT_NEAR(d_nearest, reference_d_nearest, 0.01);
+ EXPECT_EQ(nearest, reference_nearest);
+}
+
+TEST_F(HNSWTest, TEST_search_from_candidates) {
+ omp_set_num_threads(1);
+
+ std::vector<faiss::idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+ std::vector<faiss::idx_t> reference_I(k * nq);
+ std::vector<float> reference_D(k * nq);
+ using RH = faiss::HeapBlockResultHandler<faiss::HNSW::C>;
+
+ faiss::VisitedTable vt(index->ntotal);
+ faiss::VisitedTable reference_vt(index->ntotal);
+ int num_candidates = 10;
+ faiss::HNSW::MinimaxHeap candidates(num_candidates);
+ faiss::HNSW::MinimaxHeap reference_candidates(num_candidates);
+
+ for (int i = 0; i < num_candidates; i++) {
+ vt.set(i);
+ reference_vt.set(i);
+ candidates.push(i, (*dis)(i));
+ reference_candidates.push(i, (*dis)(i));
+ }
+
+ faiss::HNSWStats stats;
+ RH bres(nq, D.data(), I.data(), k);
+ faiss::HeapBlockResultHandler<faiss::HNSW::C>::SingleResultHandler res(
+ bres);
+
+ res.begin(0);
+ faiss::search_from_candidates(
+ index->hnsw, *dis, res, candidates, vt, stats, 0, 0, nullptr);
+ res.end();
+
+ faiss::HNSWStats reference_stats;
+ RH reference_bres(nq, reference_D.data(), reference_I.data(), k);
+ faiss::HeapBlockResultHandler<faiss::HNSW::C>::SingleResultHandler
+ reference_res(reference_bres);
+ reference_res.begin(0);
+ reference_search_from_candidates(
+ index->hnsw,
+ *dis,
+ reference_res,
+ reference_candidates,
+ reference_vt,
+ reference_stats,
+ 0,
+ 0,
+ nullptr);
+ reference_res.end();
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < k; j++) {
+ EXPECT_NEAR(I[i * k + j], reference_I[i * k + j], 0.1);
+ EXPECT_NEAR(D[i * k + j], reference_D[i * k + j], 0.1);
+ }
+ }
+ EXPECT_EQ(reference_stats.ndis, stats.ndis);
+ EXPECT_EQ(reference_stats.nhops, stats.nhops);
+ EXPECT_EQ(reference_stats.n1, stats.n1);
+ EXPECT_EQ(reference_stats.n2, stats.n2);
+}
+
+TEST_F(HNSWTest, TEST_search_neighbors_to_add) {
+ omp_set_num_threads(1);
+
+ faiss::VisitedTable vt(index->ntotal);
+ faiss::VisitedTable reference_vt(index->ntotal);
+
+ std::priority_queue<faiss::HNSW::NodeDistCloser> link_targets;
+ std::priority_queue<faiss::HNSW::NodeDistCloser> reference_link_targets;
+
+ faiss::search_neighbors_to_add(
+ index->hnsw,
+ *dis,
+ link_targets,
+ index->hnsw.entry_point,
+ (*dis)(index->hnsw.entry_point),
+ index->hnsw.max_level,
+ vt,
+ false);
+
+ faiss::search_neighbors_to_add(
+ index->hnsw,
+ *dis,
+ reference_link_targets,
+ index->hnsw.entry_point,
+ (*dis)(index->hnsw.entry_point),
+ index->hnsw.max_level,
+ reference_vt,
+ true);
+
+ EXPECT_EQ(link_targets.size(), reference_link_targets.size());
+ while (!link_targets.empty()) {
+ auto val = link_targets.top();
+ auto reference_val = reference_link_targets.top();
+ EXPECT_EQ(val.d, reference_val.d);
+ EXPECT_EQ(val.id, reference_val.id);
+ link_targets.pop();
+ reference_link_targets.pop();
+ }
+}
+
+TEST_F(HNSWTest, TEST_nb_neighbors_bound) {
+ omp_set_num_threads(1);
+ EXPECT_EQ(index->hnsw.nb_neighbors(0), 8);
+ EXPECT_EQ(index->hnsw.nb_neighbors(1), 4);
+ EXPECT_EQ(index->hnsw.nb_neighbors(2), 4);
+ EXPECT_EQ(index->hnsw.nb_neighbors(3), 4);
+ // picking a large number to trigger an exception based on checking bounds
+ EXPECT_THROW(index->hnsw.nb_neighbors(100), faiss::FaissException);
+}
+
+TEST_F(HNSWTest, TEST_search_level_0) {
+ omp_set_num_threads(1);
+ std::vector<faiss::idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+
+ using RH = faiss::HeapBlockResultHandler<faiss::HNSW::C>;
+ RH bres1(nq, D.data(), I.data(), k);
+ faiss::HeapBlockResultHandler<faiss::HNSW::C>::SingleResultHandler res1(
+ bres1);
+ RH bres2(nq, D.data(), I.data(), k);
+ faiss::HeapBlockResultHandler<faiss::HNSW::C>::SingleResultHandler res2(
+ bres2);
+
+ faiss::HNSWStats stats1, stats2;
+ faiss::VisitedTable vt1(index->ntotal);
+ faiss::VisitedTable vt2(index->ntotal);
+ auto nprobe = 5;
+ const faiss::HNSW::storage_idx_t values[] = {1, 2, 3, 4, 5};
+ const faiss::HNSW::storage_idx_t* nearest_i = values;
+ const float distances[] = {0.1, 0.2, 0.3, 0.4, 0.5};
+ const float* nearest_d = distances;
+
+ // search_type == 1
+ res1.begin(0);
+ index->hnsw.search_level_0(
+ *dis, res1, nprobe, nearest_i, nearest_d, 1, stats1, vt1, nullptr);
+ res1.end();
+
+ // search_type == 2
+ res2.begin(0);
+ index->hnsw.search_level_0(
+ *dis, res2, nprobe, nearest_i, nearest_d, 2, stats2, vt2, nullptr);
+ res2.end();
+
+ // search_type 1 calls search_from_candidates in a loop nprobe times.
+ // search_type 2 pushes the candidates and just calls search_from_candidates
+ // once, so those stats will be much less.
+ EXPECT_GT(stats1.ndis, stats2.ndis);
+ EXPECT_GT(stats1.nhops, stats2.nhops);
+ EXPECT_GT(stats1.n1, stats2.n1);
+ EXPECT_GT(stats1.n2, stats2.n2);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivf_index.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivf_index.cpp
new file mode 100644
index 0000000..089c7a1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivf_index.cpp
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <omp.h>
+#include <algorithm>
+#include <cstddef>
+#include <map>
+#include <random>
+#include <set>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/impl/FaissAssert.h>
+
+namespace {
+
+// stores all ivf lists, used to verify the context
+// object is passed to the iterator
+class TestContext {
+ public:
+ TestContext() {}
+
+ void save_code(size_t list_no, const uint8_t* code, size_t code_size) {
+ list_nos.emplace(id, list_no);
+ codes.emplace(id, std::vector<uint8_t>(code_size));
+ for (size_t i = 0; i < code_size; i++) {
+ codes[id][i] = code[i];
+ }
+ id++;
+ }
+
+ // id to codes map
+ std::unordered_map<faiss::idx_t, std::vector<uint8_t>> codes;
+ // id to list_no map
+ std::unordered_map<faiss::idx_t, size_t> list_nos;
+ faiss::idx_t id = 0;
+ std::set<size_t> lists_probed;
+};
+
+// the iterator that iterates over the codes stored in context object
+class TestInvertedListIterator : public faiss::InvertedListsIterator {
+ public:
+ TestInvertedListIterator(size_t list_no, TestContext* context)
+ : list_no{list_no}, context{context} {
+ it = context->codes.cbegin();
+ seek_next();
+ }
+ ~TestInvertedListIterator() override {}
+
+ // move the cursor to the first valid entry
+ void seek_next() {
+ while (it != context->codes.cend() &&
+ context->list_nos[it->first] != list_no) {
+ it++;
+ }
+ }
+
+ virtual bool is_available() const override {
+ return it != context->codes.cend();
+ }
+
+ virtual void next() override {
+ it++;
+ seek_next();
+ }
+
+ virtual std::pair<faiss::idx_t, const uint8_t*> get_id_and_codes()
+ override {
+ if (it == context->codes.cend()) {
+ FAISS_THROW_MSG("invalid state");
+ }
+ return std::make_pair(it->first, it->second.data());
+ }
+
+ private:
+ size_t list_no;
+ TestContext* context;
+ decltype(context->codes.cbegin()) it;
+};
+
+class TestInvertedLists : public faiss::InvertedLists {
+ public:
+ TestInvertedLists(size_t nlist, size_t code_size)
+ : faiss::InvertedLists(nlist, code_size) {
+ use_iterator = true;
+ }
+
+ ~TestInvertedLists() override {}
+ size_t list_size(size_t /*list_no*/) const override {
+ FAISS_THROW_MSG("unexpected call");
+ }
+
+ faiss::InvertedListsIterator* get_iterator(size_t list_no, void* context)
+ const override {
+ auto testContext = (TestContext*)context;
+ testContext->lists_probed.insert(list_no);
+ return new TestInvertedListIterator(list_no, testContext);
+ }
+
+ const uint8_t* get_codes(size_t /* list_no */) const override {
+ FAISS_THROW_MSG("unexpected call");
+ }
+
+ const faiss::idx_t* get_ids(size_t /* list_no */) const override {
+ FAISS_THROW_MSG("unexpected call");
+ }
+
+ // store the codes in context object
+ size_t add_entry(
+ size_t list_no,
+ faiss::idx_t /*theid*/,
+ const uint8_t* code,
+ void* context) override {
+ auto testContext = (TestContext*)context;
+ testContext->save_code(list_no, code, code_size);
+ return 0;
+ }
+
+ size_t add_entries(
+ size_t /*list_no*/,
+ size_t /*n_entry*/,
+ const faiss::idx_t* /*ids*/,
+ const uint8_t* /*code*/) override {
+ FAISS_THROW_MSG("unexpected call");
+ }
+
+ void update_entries(
+ size_t /*list_no*/,
+ size_t /*offset*/,
+ size_t /*n_entry*/,
+ const faiss::idx_t* /*ids*/,
+ const uint8_t* /*code*/) override {
+ FAISS_THROW_MSG("unexpected call");
+ }
+
+ void resize(size_t /*list_no*/, size_t /*new_size*/) override {
+ FAISS_THROW_MSG("unexpected call");
+ }
+};
+} // namespace
+
+TEST(IVF, list_context) {
+ // this test verifies that the context object is passed
+ // to the InvertedListsIterator and InvertedLists::add_entry.
+ // the test InvertedLists and InvertedListsIterator reads/writes
+ // to the test context object.
+ // the test verifies the context object is modified as expected.
+
+ constexpr int d = 32; // dimension
+ constexpr int nb = 100000; // database size
+ constexpr int nlist = 100;
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ // disable parallism, or we need to make Context object
+ // thread-safe
+ omp_set_num_threads(1);
+
+ faiss::IndexFlatL2 quantizer(d); // the other index
+ faiss::IndexIVFFlat index(&quantizer, d, nlist);
+ TestInvertedLists inverted_lists(nlist, index.code_size);
+ index.replace_invlists(&inverted_lists);
+ {
+ // training
+ constexpr size_t nt = 1500; // nb of training vectors
+ std::vector<float> trainvecs(nt * d);
+ for (size_t i = 0; i < nt * d; i++) {
+ trainvecs[i] = distrib(rng);
+ }
+ index.verbose = true;
+ index.train(nt, trainvecs.data());
+ }
+ TestContext context;
+ std::vector<float> query_vector;
+ constexpr faiss::idx_t query_vector_id = 100;
+ {
+ // populating the database
+ std::vector<float> database(nb * d);
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ // populate the query vector
+ if (i >= query_vector_id * d && i < query_vector_id * d + d) {
+ query_vector.push_back(database[i]);
+ }
+ }
+ std::vector<faiss::idx_t> coarse_idx(nb);
+ index.quantizer->assign(nb, database.data(), coarse_idx.data());
+ // pass dummy ids, the acutal ids are assigned in TextContext object
+ std::vector<faiss::idx_t> xids(nb, 42);
+ index.add_core(
+ nb, database.data(), xids.data(), coarse_idx.data(), &context);
+
+ // check the context object get updated
+ EXPECT_EQ(nb, context.id) << "should have added all ids";
+ EXPECT_EQ(nb, context.codes.size())
+ << "should have correct number of codes";
+ EXPECT_EQ(nb, context.list_nos.size())
+ << "should have correct number of list numbers";
+ }
+ {
+ constexpr size_t num_vecs = 5; // number of vectors
+ std::vector<float> vecs(num_vecs * d);
+ for (size_t i = 0; i < num_vecs * d; i++) {
+ vecs[i] = distrib(rng);
+ }
+ const size_t codeSize = index.sa_code_size();
+ std::vector<uint8_t> encodedData(num_vecs * codeSize);
+ index.sa_encode(num_vecs, vecs.data(), encodedData.data());
+ std::vector<float> decodedVecs(num_vecs * d);
+ index.sa_decode(num_vecs, encodedData.data(), decodedVecs.data());
+ EXPECT_EQ(vecs, decodedVecs)
+ << "decoded vectors should be the same as the original vectors that were encoded";
+ }
+ {
+ constexpr faiss::idx_t k = 100;
+ constexpr size_t nprobe = 10;
+ std::vector<float> distances(k);
+ std::vector<faiss::idx_t> labels(k);
+ faiss::SearchParametersIVF params;
+ params.inverted_list_context = &context;
+ params.nprobe = nprobe;
+ index.search(
+ 1,
+ query_vector.data(),
+ k,
+ distances.data(),
+ labels.data(),
+ &params);
+ EXPECT_EQ(nprobe, context.lists_probed.size())
+ << "should probe nprobe lists";
+
+ // check the result contains the query vector, the probablity of
+ // this fail should be low
+ auto query_vector_listno = context.list_nos[query_vector_id];
+ auto& lists_probed = context.lists_probed;
+ EXPECT_TRUE(
+ std::find(
+ lists_probed.cbegin(),
+ lists_probed.cend(),
+ query_vector_listno) != lists_probed.cend())
+ << "should probe the list of the query vector";
+ EXPECT_TRUE(
+ std::find(labels.cbegin(), labels.cend(), query_vector_id) !=
+ labels.cend())
+ << "should return the query vector";
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivfpq_codec.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivfpq_codec.cpp
new file mode 100644
index 0000000..c9e9a03
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivfpq_codec.cpp
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <omp.h>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+#include <faiss/utils/distances.h>
+
+namespace {
+
+// dimension of the vectors to index
+int d = 64;
+
+// size of the database we plan to index
+size_t nb = 8000;
+
+double eval_codec_error(long ncentroids, long m, const std::vector<float>& v) {
+ faiss::IndexFlatL2 coarse_quantizer(d);
+ faiss::IndexIVFPQ index(&coarse_quantizer, d, ncentroids, m, 8);
+ index.pq.cp.niter = 10; // speed up train
+ index.train(nb, v.data());
+
+ // encode and decode to compute reconstruction error
+
+ std::vector<faiss::idx_t> keys(nb);
+ std::vector<uint8_t> codes(nb * m);
+ index.encode_multiple(nb, keys.data(), v.data(), codes.data(), true);
+
+ std::vector<float> v2(nb * d);
+ index.decode_multiple(nb, keys.data(), codes.data(), v2.data());
+
+ return faiss::fvec_L2sqr(v.data(), v2.data(), nb * d);
+}
+
+} // namespace
+
+bool runs_on_sandcastle() {
+ // see discussion here https://fburl.com/qc5kpdo2
+ const char* sandcastle = getenv("SANDCASTLE");
+ if (sandcastle && !strcmp(sandcastle, "1")) {
+ return true;
+ }
+ const char* tw_job_user = getenv("TW_JOB_USER");
+ if (tw_job_user && !strcmp(tw_job_user, "sandcastle")) {
+ return true;
+ }
+
+ return false;
+}
+
+TEST(IVFPQ, codec) {
+ std::vector<float> database(nb * d);
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+
+ // limit number of threads when running on heavily parallelized test
+ // environment
+ if (runs_on_sandcastle()) {
+ omp_set_num_threads(2);
+ }
+
+ double err0 = eval_codec_error(16, 8, database);
+
+ // should be more accurate as there are more coarse centroids
+ double err1 = eval_codec_error(128, 8, database);
+ EXPECT_GT(err0, err1);
+
+ // should be more accurate as there are more PQ codes
+ double err2 = eval_codec_error(16, 16, database);
+ EXPECT_GT(err0, err2);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivfpq_indexing.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivfpq_indexing.cpp
new file mode 100644
index 0000000..d277c6a
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ivfpq_indexing.cpp
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+
+TEST(IVFPQ, accuracy) {
+ // dimension of the vectors to index
+ int d = 64;
+
+ // size of the database we plan to index
+ size_t nb = 1000;
+
+ // make a set of nt training vectors in the unit cube
+ // (could be the database)
+ size_t nt = 1500;
+
+ // make the index object and train it
+ faiss::IndexFlatL2 coarse_quantizer(d);
+
+ // a reasonable number of cetroids to index nb vectors
+ int ncentroids = 25;
+
+ faiss::IndexIVFPQ index(&coarse_quantizer, d, ncentroids, 16, 8);
+
+ // index that gives the ground-truth
+ faiss::IndexFlatL2 index_gt(d);
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ { // training
+
+ std::vector<float> trainvecs(nt * d);
+ for (size_t i = 0; i < nt * d; i++) {
+ trainvecs[i] = distrib(rng);
+ }
+ index.verbose = true;
+ index.train(nt, trainvecs.data());
+ }
+
+ { // populating the database
+
+ std::vector<float> database(nb * d);
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+
+ index.add(nb, database.data());
+ index_gt.add(nb, database.data());
+ }
+
+ int nq = 200;
+ int n_ok;
+
+ { // searching the database
+
+ std::vector<float> queries(nq * d);
+ for (size_t i = 0; i < nq * d; i++) {
+ queries[i] = distrib(rng);
+ }
+
+ std::vector<faiss::idx_t> gt_nns(nq);
+ std::vector<float> gt_dis(nq);
+
+ index_gt.search(nq, queries.data(), 1, gt_dis.data(), gt_nns.data());
+
+ index.nprobe = 5;
+ int k = 5;
+ std::vector<faiss::idx_t> nns(k * nq);
+ std::vector<float> dis(k * nq);
+
+ index.search(nq, queries.data(), k, dis.data(), nns.data());
+
+ n_ok = 0;
+ for (int q = 0; q < nq; q++) {
+ for (int i = 0; i < k; i++)
+ if (nns[q * k + i] == gt_nns[q])
+ n_ok++;
+ }
+ EXPECT_GT(n_ok, nq * 0.4);
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_lowlevel_ivf.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_lowlevel_ivf.cpp
new file mode 100644
index 0000000..3d7dd43
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_lowlevel_ivf.cpp
@@ -0,0 +1,549 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cinttypes>
+#include <cstdio>
+#include <cstdlib>
+
+#include <memory>
+#include <random>
+#include <thread>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/IVFlib.h>
+#include <faiss/IndexBinaryIVF.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/index_factory.h>
+
+using namespace faiss;
+
+namespace {
+
+// dimension of the vectors to index
+int d = 32;
+
+// nb of training vectors
+size_t nt = 5000;
+
+// size of the database points per window step
+size_t nb = 1000;
+
+// nb of queries
+size_t nq = 200;
+
+int k = 10;
+
+std::mt19937 rng;
+
+std::vector<float> make_data(size_t n) {
+ std::vector<float> database(n * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<Index> make_trained_index(
+ const char* index_type,
+ MetricType metric_type) {
+ auto index =
+ std::unique_ptr<Index>(index_factory(d, index_type, metric_type));
+ auto xt = make_data(nt);
+ index->train(nt, xt.data());
+ ParameterSpace().set_index_parameter(index.get(), "nprobe", 4);
+ return index;
+}
+
+std::vector<idx_t> search_index(Index* index, const float* xq) {
+ std::vector<idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+ index->search(nq, xq, k, D.data(), I.data());
+ return I;
+}
+
+/*************************************************************
+ * Test functions for a given index type
+ *************************************************************/
+
+void test_lowlevel_access(const char* index_key, MetricType metric) {
+ std::unique_ptr<Index> index = make_trained_index(index_key, metric);
+
+ auto xb = make_data(nb);
+ index->add(nb, xb.data());
+
+ /** handle the case if we have a preprocessor */
+
+ const IndexPreTransform* index_pt =
+ dynamic_cast<const IndexPreTransform*>(index.get());
+
+ int dt = index->d;
+ const float* xbt = xb.data();
+ std::unique_ptr<float[]> del_xbt;
+
+ if (index_pt) {
+ dt = index_pt->index->d;
+ xbt = index_pt->apply_chain(nb, xb.data());
+ if (xbt != xb.data()) {
+ del_xbt.reset((float*)xbt);
+ }
+ }
+
+ IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get());
+
+ /** Test independent encoding
+ *
+ * Makes it possible to do additions on a custom inverted list
+ * implementation. From a set of vectors, computes the inverted
+ * list ids + the codes corresponding to each vector.
+ */
+
+ std::vector<idx_t> list_nos(nb);
+ std::vector<uint8_t> codes(index_ivf->code_size * nb);
+ index_ivf->quantizer->assign(nb, xbt, list_nos.data());
+ index_ivf->encode_vectors(nb, xbt, list_nos.data(), codes.data());
+
+ // compare with normal IVF addition
+
+ const InvertedLists* il = index_ivf->invlists;
+
+ for (int list_no = 0; list_no < index_ivf->nlist; list_no++) {
+ InvertedLists::ScopedCodes ivf_codes(il, list_no);
+ InvertedLists::ScopedIds ivf_ids(il, list_no);
+ size_t list_size = il->list_size(list_no);
+ for (int i = 0; i < list_size; i++) {
+ const uint8_t* ref_code = ivf_codes.get() + i * il->code_size;
+ const uint8_t* new_code = codes.data() + ivf_ids[i] * il->code_size;
+ EXPECT_EQ(memcmp(ref_code, new_code, il->code_size), 0);
+ }
+ }
+
+ /** Test independent search
+ *
+ * Manually scans through inverted lists, computing distances and
+ * ordering results organized in a heap.
+ */
+
+ // sample some example queries and get reference search results.
+ auto xq = make_data(nq);
+ auto ref_I = search_index(index.get(), xq.data());
+
+ // handle preprocessing
+ const float* xqt = xq.data();
+ std::unique_ptr<float[]> del_xqt;
+
+ if (index_pt) {
+ xqt = index_pt->apply_chain(nq, xq.data());
+ if (xqt != xq.data()) {
+ del_xqt.reset((float*)xqt);
+ }
+ }
+
+ // quantize the queries to get the inverted list ids to visit.
+ int nprobe = index_ivf->nprobe;
+
+ std::vector<idx_t> q_lists(nq * nprobe);
+ std::vector<float> q_dis(nq * nprobe);
+
+ index_ivf->quantizer->search(nq, xqt, nprobe, q_dis.data(), q_lists.data());
+
+ // object that does the scanning and distance computations.
+ std::unique_ptr<InvertedListScanner> scanner(
+ index_ivf->get_InvertedListScanner());
+
+ for (int i = 0; i < nq; i++) {
+ std::vector<idx_t> I(k, -1);
+ float default_dis = metric == METRIC_L2 ? HUGE_VAL : -HUGE_VAL;
+ std::vector<float> D(k, default_dis);
+
+ scanner->set_query(xqt + i * dt);
+
+ for (int j = 0; j < nprobe; j++) {
+ int list_no = q_lists[i * nprobe + j];
+ if (list_no < 0)
+ continue;
+ scanner->set_list(list_no, q_dis[i * nprobe + j]);
+
+ // here we get the inverted lists from the InvertedLists
+ // object but they could come from anywhere
+
+ scanner->scan_codes(
+ il->list_size(list_no),
+ InvertedLists::ScopedCodes(il, list_no).get(),
+ InvertedLists::ScopedIds(il, list_no).get(),
+ D.data(),
+ I.data(),
+ k);
+
+ if (j == 0) {
+ // all results so far come from list_no, so let's check if
+ // the distance function works
+ for (int jj = 0; jj < k; jj++) {
+ int vno = I[jj];
+ if (vno < 0)
+ break; // heap is not full yet
+
+ // we have the codes from the addition test
+ float computed_D = scanner->distance_to_code(
+ codes.data() + vno * il->code_size);
+
+ EXPECT_FLOAT_EQ(computed_D, D[jj]);
+ }
+ }
+ }
+
+ // re-order heap
+ if (metric == METRIC_L2) {
+ maxheap_reorder(k, D.data(), I.data());
+ } else {
+ minheap_reorder(k, D.data(), I.data());
+ }
+
+ // check that we have the same results as the reference search
+ for (int j = 0; j < k; j++) {
+ EXPECT_EQ(I[j], ref_I[i * k + j]);
+ }
+ }
+}
+
+} // anonymous namespace
+
+/*************************************************************
+ * Test entry points
+ *************************************************************/
+
+TEST(TestLowLevelIVF, IVFFlatL2) {
+ test_lowlevel_access("IVF32,Flat", METRIC_L2);
+}
+
+TEST(TestLowLevelIVF, PCAIVFFlatL2) {
+ test_lowlevel_access("PCAR16,IVF32,Flat", METRIC_L2);
+}
+
+TEST(TestLowLevelIVF, IVFFlatIP) {
+ test_lowlevel_access("IVF32,Flat", METRIC_INNER_PRODUCT);
+}
+
+TEST(TestLowLevelIVF, IVFSQL2) {
+ test_lowlevel_access("IVF32,SQ8", METRIC_L2);
+}
+
+TEST(TestLowLevelIVF, IVFSQIP) {
+ test_lowlevel_access("IVF32,SQ8", METRIC_INNER_PRODUCT);
+}
+
+TEST(TestLowLevelIVF, IVFPQL2) {
+ test_lowlevel_access("IVF32,PQ4np", METRIC_L2);
+}
+
+TEST(TestLowLevelIVF, IVFPQIP) {
+ test_lowlevel_access("IVF32,PQ4np", METRIC_INNER_PRODUCT);
+}
+
+/*************************************************************
+ * Same for binary (a bit simpler)
+ *************************************************************/
+
+namespace {
+
+int nbit = 256;
+
+// here d is used the number of ints -> d=32 means 128 bits
+
+std::vector<uint8_t> make_data_binary(size_t n) {
+ std::vector<uint8_t> database(n * nbit / 8);
+ std::uniform_int_distribution<> distrib;
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<IndexBinary> make_trained_index_binary(const char* index_type) {
+ auto index = std::unique_ptr<IndexBinary>(
+ index_binary_factory(nbit, index_type));
+ auto xt = make_data_binary(nt);
+ index->train(nt, xt.data());
+ return index;
+}
+
+void test_lowlevel_access_binary(const char* index_key) {
+ std::unique_ptr<IndexBinary> index = make_trained_index_binary(index_key);
+
+ IndexBinaryIVF* index_ivf = dynamic_cast<IndexBinaryIVF*>(index.get());
+ assert(index_ivf);
+
+ index_ivf->nprobe = 4;
+
+ auto xb = make_data_binary(nb);
+ index->add(nb, xb.data());
+
+ std::vector<idx_t> list_nos(nb);
+ index_ivf->quantizer->assign(nb, xb.data(), list_nos.data());
+
+ /* For binary there is no test for encoding because binary vectors
+ * are copied verbatim to the inverted lists */
+
+ const InvertedLists* il = index_ivf->invlists;
+
+ /** Test independent search
+ *
+ * Manually scans through inverted lists, computing distances and
+ * ordering results organized in a heap.
+ */
+
+ // sample some example queries and get reference search results.
+ auto xq = make_data_binary(nq);
+
+ std::vector<idx_t> I_ref(k * nq);
+ std::vector<int32_t> D_ref(k * nq);
+ index->search(nq, xq.data(), k, D_ref.data(), I_ref.data());
+
+ // quantize the queries to get the inverted list ids to visit.
+ int nprobe = index_ivf->nprobe;
+
+ std::vector<idx_t> q_lists(nq * nprobe);
+ std::vector<int32_t> q_dis(nq * nprobe);
+
+ // quantize queries
+ index_ivf->quantizer->search(
+ nq, xq.data(), nprobe, q_dis.data(), q_lists.data());
+
+ // object that does the scanning and distance computations.
+ std::unique_ptr<BinaryInvertedListScanner> scanner(
+ index_ivf->get_InvertedListScanner());
+
+ for (int i = 0; i < nq; i++) {
+ std::vector<idx_t> I(k, -1);
+ uint32_t default_dis = 1 << 30;
+ std::vector<int32_t> D(k, default_dis);
+
+ scanner->set_query(xq.data() + i * index_ivf->code_size);
+
+ for (int j = 0; j < nprobe; j++) {
+ int list_no = q_lists[i * nprobe + j];
+ if (list_no < 0)
+ continue;
+ scanner->set_list(list_no, q_dis[i * nprobe + j]);
+
+ // here we get the inverted lists from the InvertedLists
+ // object but they could come from anywhere
+
+ scanner->scan_codes(
+ il->list_size(list_no),
+ InvertedLists::ScopedCodes(il, list_no).get(),
+ InvertedLists::ScopedIds(il, list_no).get(),
+ D.data(),
+ I.data(),
+ k);
+
+ if (j == 0) {
+ // all results so far come from list_no, so let's check if
+ // the distance function works
+ for (int jj = 0; jj < k; jj++) {
+ int vno = I[jj];
+ if (vno < 0)
+ break; // heap is not full yet
+
+ // we have the codes from the addition test
+ float computed_D = scanner->distance_to_code(
+ xb.data() + vno * il->code_size);
+
+ EXPECT_EQ(computed_D, D[jj]);
+ }
+ }
+ }
+
+ // re-order heap
+ heap_reorder<CMax<int32_t, idx_t>>(k, D.data(), I.data());
+
+ // check that we have the same results as the reference search
+ for (int j = 0; j < k; j++) {
+ // here the order is not guaranteed to be the same
+ // so we scan through ref results
+ // EXPECT_EQ (I[j], I_ref[i * k + j]);
+ EXPECT_LE(D[j], D_ref[i * k + k - 1]);
+ if (D[j] < D_ref[i * k + k - 1]) {
+ int j2 = 0;
+ while (j2 < k) {
+ if (I[j] == I_ref[i * k + j2])
+ break;
+ j2++;
+ }
+ EXPECT_LT(j2, k); // it was found
+ if (j2 < k) {
+ EXPECT_EQ(D[j], D_ref[i * k + j2]);
+ }
+ }
+ }
+ }
+}
+
+} // anonymous namespace
+
+TEST(TestLowLevelIVF, IVFBinary) {
+ test_lowlevel_access_binary("BIVF32");
+}
+
+namespace {
+
+void test_threaded_search(const char* index_key, MetricType metric) {
+ std::unique_ptr<Index> index = make_trained_index(index_key, metric);
+
+ auto xb = make_data(nb);
+ index->add(nb, xb.data());
+
+ /** handle the case if we have a preprocessor */
+
+ const IndexPreTransform* index_pt =
+ dynamic_cast<const IndexPreTransform*>(index.get());
+
+ int dt = index->d;
+ const float* xbt = xb.data();
+ std::unique_ptr<float[]> del_xbt;
+
+ if (index_pt) {
+ dt = index_pt->index->d;
+ xbt = index_pt->apply_chain(nb, xb.data());
+ if (xbt != xb.data()) {
+ del_xbt.reset((float*)xbt);
+ }
+ }
+
+ IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get());
+
+ /** Test independent search
+ *
+ * Manually scans through inverted lists, computing distances and
+ * ordering results organized in a heap.
+ */
+
+ // sample some example queries and get reference search results.
+ auto xq = make_data(nq);
+ auto ref_I = search_index(index.get(), xq.data());
+
+ // handle preprocessing
+ const float* xqt = xq.data();
+ std::unique_ptr<float[]> del_xqt;
+
+ if (index_pt) {
+ xqt = index_pt->apply_chain(nq, xq.data());
+ if (xqt != xq.data()) {
+ del_xqt.reset((float*)xqt);
+ }
+ }
+
+ // quantize the queries to get the inverted list ids to visit.
+ int nprobe = index_ivf->nprobe;
+
+ std::vector<idx_t> q_lists(nq * nprobe);
+ std::vector<float> q_dis(nq * nprobe);
+
+ index_ivf->quantizer->search(nq, xqt, nprobe, q_dis.data(), q_lists.data());
+
+ // now run search in this many threads
+ int nproc = 3;
+
+ for (int i = 0; i < nq; i++) {
+ // one result table per thread
+ std::vector<idx_t> I(k * nproc, -1);
+ float default_dis = metric == METRIC_L2 ? HUGE_VAL : -HUGE_VAL;
+ std::vector<float> D(k * nproc, default_dis);
+
+ auto search_function = [index_ivf,
+ &I,
+ &D,
+ dt,
+ i,
+ nproc,
+ xqt,
+ nprobe,
+ &q_dis,
+ &q_lists](int rank) {
+ const InvertedLists* il = index_ivf->invlists;
+
+ // object that does the scanning and distance computations.
+ std::unique_ptr<InvertedListScanner> scanner(
+ index_ivf->get_InvertedListScanner());
+
+ idx_t* local_I = I.data() + rank * k;
+ float* local_D = D.data() + rank * k;
+
+ scanner->set_query(xqt + i * dt);
+
+ for (int j = rank; j < nprobe; j += nproc) {
+ int list_no = q_lists[i * nprobe + j];
+ if (list_no < 0)
+ continue;
+ scanner->set_list(list_no, q_dis[i * nprobe + j]);
+
+ scanner->scan_codes(
+ il->list_size(list_no),
+ InvertedLists::ScopedCodes(il, list_no).get(),
+ InvertedLists::ScopedIds(il, list_no).get(),
+ local_D,
+ local_I,
+ k);
+ }
+ };
+
+ // start the threads. Threads are numbered rank=0..nproc-1 (a la MPI)
+ // thread rank takes care of inverted lists
+ // rank, rank+nproc, rank+2*nproc,...
+ std::vector<std::thread> threads;
+ for (int rank = 0; rank < nproc; rank++) {
+ threads.emplace_back(search_function, rank);
+ }
+
+ // join threads, merge heaps
+ for (int rank = 0; rank < nproc; rank++) {
+ threads[rank].join();
+ if (rank == 0)
+ continue; // nothing to merge
+ // merge into first result
+ if (metric == METRIC_L2) {
+ maxheap_addn(
+ k,
+ D.data(),
+ I.data(),
+ D.data() + rank * k,
+ I.data() + rank * k,
+ k);
+ } else {
+ minheap_addn(
+ k,
+ D.data(),
+ I.data(),
+ D.data() + rank * k,
+ I.data() + rank * k,
+ k);
+ }
+ }
+
+ // re-order heap
+ if (metric == METRIC_L2) {
+ maxheap_reorder(k, D.data(), I.data());
+ } else {
+ minheap_reorder(k, D.data(), I.data());
+ }
+
+ // check that we have the same results as the reference search
+ for (int j = 0; j < k; j++) {
+ EXPECT_EQ(I[j], ref_I[i * k + j]);
+ }
+ }
+}
+
+} // namespace
+
+TEST(TestLowLevelIVF, ThreadedSearch) {
+ test_threaded_search("IVF32,Flat", METRIC_L2);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_mem_leak.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_mem_leak.cpp
new file mode 100644
index 0000000..bd6f7d7
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_mem_leak.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/utils/random.h>
+#include <faiss/utils/utils.h>
+
+#include <gtest/gtest.h>
+
+using namespace faiss;
+
+TEST(TestMemoryLeak, ivfflat) {
+ size_t num_tfidf_faiss_cells = 20;
+ size_t max_tfidf_features = 500;
+
+ IndexFlatIP quantizer(max_tfidf_features);
+ IndexIVFFlat tfidf_faiss_index(
+ &quantizer, max_tfidf_features, num_tfidf_faiss_cells);
+
+ std::vector<float> dense_matrix(5000 * max_tfidf_features);
+ float_rand(dense_matrix.data(), dense_matrix.size(), 123);
+
+ tfidf_faiss_index.train(5000, dense_matrix.data());
+ tfidf_faiss_index.add(5000, dense_matrix.data());
+
+ int N1 = 1000;
+ int N2 = 10000;
+
+ std::vector<float> ent_substr_tfidfs_list(N1 * max_tfidf_features);
+ float_rand(
+ ent_substr_tfidfs_list.data(), ent_substr_tfidfs_list.size(), 1234);
+
+ for (int bs : {1, 4, 16}) {
+ size_t m0 = get_mem_usage_kb();
+ double t0 = getmillisecs();
+
+ for (int i = 0; i < N2; i++) {
+ std::vector<idx_t> I(10 * bs);
+ std::vector<float> D(10 * bs);
+
+ tfidf_faiss_index.search(
+ bs,
+ ent_substr_tfidfs_list.data() +
+ (i % (N1 - bs + 1)) * max_tfidf_features,
+ 10,
+ D.data(),
+ I.data());
+ if (i % 100 == 0) {
+ printf("[%.2f s] BS %d %d: %ld kB %.2f bytes/it\r",
+ (getmillisecs() - t0) / 1000,
+ bs,
+ i,
+ get_mem_usage_kb(),
+ (get_mem_usage_kb() - m0) * 1024.0 / (i + 1));
+ fflush(stdout);
+ }
+ }
+ printf("\n");
+ EXPECT_GE(50 * bs, (get_mem_usage_kb() - m0) * 1024.0 / N2);
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_merge.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_merge.cpp
new file mode 100644
index 0000000..9bb4382
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_merge.cpp
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <random>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IVFlib.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/IndexPreTransform.h>
+#include <faiss/MetaIndexes.h>
+#include <faiss/invlists/OnDiskInvertedLists.h>
+
+#include "test_util.h"
+
+namespace {
+
+pthread_mutex_t temp_file_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+typedef faiss::idx_t idx_t;
+
+// parameters to use for the test
+int d = 64;
+size_t nb = 1000;
+size_t nq = 100;
+int nindex = 4;
+int k = 10;
+int nlist = 40;
+int shard_size = nb / nindex;
+
+struct CommonData {
+ std::vector<float> database;
+ std::vector<float> queries;
+ std::vector<idx_t> ids;
+ faiss::IndexFlatL2 quantizer;
+
+ CommonData() : database(nb * d), queries(nq * d), ids(nb), quantizer(d) {
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < nb * d; i++) {
+ database[i] = distrib(rng);
+ }
+ for (size_t i = 0; i < nq * d; i++) {
+ queries[i] = distrib(rng);
+ }
+ for (int i = 0; i < nb; i++) {
+ ids[i] = 123 + 456 * i;
+ }
+ { // just to train the quantizer
+ faiss::IndexIVFFlat iflat(&quantizer, d, nlist);
+ iflat.train(nb, database.data());
+ }
+ }
+};
+
+CommonData cd;
+std::string temp_filename_template = "/tmp/faiss_tmp_XXXXXX";
+/// perform a search on shards, then merge and search again and
+/// compare results.
+int compare_merged(
+ faiss::IndexShards* index_shards,
+ bool shift_ids,
+ bool standard_merge = true) {
+ std::vector<idx_t> refI(k * nq);
+ std::vector<float> refD(k * nq);
+
+ index_shards->search(nq, cd.queries.data(), k, refD.data(), refI.data());
+ Tempfilename filename(&temp_file_mutex, temp_filename_template);
+
+ std::vector<idx_t> newI(k * nq);
+ std::vector<float> newD(k * nq);
+
+ if (standard_merge) {
+ for (int i = 1; i < nindex; i++) {
+ faiss::ivflib::merge_into(
+ index_shards->at(0), index_shards->at(i), shift_ids);
+ }
+
+ index_shards->syncWithSubIndexes();
+ } else {
+ std::vector<const faiss::InvertedLists*> lists;
+ faiss::IndexIVF* index0 = nullptr;
+ size_t ntotal = 0;
+ for (int i = 0; i < nindex; i++) {
+ auto index_ivf =
+ dynamic_cast<faiss::IndexIVF*>(index_shards->at(i));
+ assert(index_ivf);
+ if (i == 0) {
+ index0 = index_ivf;
+ }
+ lists.push_back(index_ivf->invlists);
+ ntotal += index_ivf->ntotal;
+ }
+
+ auto il = new faiss::OnDiskInvertedLists(
+ index0->nlist, index0->code_size, filename.c_str());
+
+ il->merge_from_multiple(lists.data(), lists.size(), shift_ids);
+
+ index0->replace_invlists(il, true);
+ index0->ntotal = ntotal;
+ }
+ // search only on first index
+ index_shards->at(0)->search(
+ nq, cd.queries.data(), k, newD.data(), newI.data());
+
+ size_t ndiff = 0;
+ bool adjust_ids = shift_ids && !standard_merge;
+ for (size_t i = 0; i < k * nq; i++) {
+ idx_t new_id = adjust_ids ? refI[i] % shard_size : refI[i];
+ if (refI[i] != new_id) {
+ ndiff++;
+ }
+ }
+
+ return ndiff;
+}
+
+} // namespace
+
+// test on IVFFlat with implicit numbering
+TEST(MERGE, merge_flat_no_ids) {
+ faiss::IndexShards index_shards(d);
+ index_shards.own_indices = true;
+ for (int i = 0; i < nindex; i++) {
+ index_shards.add_shard(
+ new faiss::IndexIVFFlat(&cd.quantizer, d, nlist));
+ }
+ EXPECT_TRUE(index_shards.is_trained);
+ index_shards.add(nb, cd.database.data());
+ size_t prev_ntotal = index_shards.ntotal;
+ int ndiff = compare_merged(&index_shards, true);
+ EXPECT_EQ(prev_ntotal, index_shards.ntotal);
+ EXPECT_EQ(0, ndiff);
+}
+
+// test on IVFFlat, explicit ids
+TEST(MERGE, merge_flat) {
+ faiss::IndexShards index_shards(d, false, false);
+ index_shards.own_indices = true;
+
+ for (int i = 0; i < nindex; i++) {
+ index_shards.add_shard(
+ new faiss::IndexIVFFlat(&cd.quantizer, d, nlist));
+ }
+
+ EXPECT_TRUE(index_shards.is_trained);
+ index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data());
+ int ndiff = compare_merged(&index_shards, false);
+ EXPECT_GE(0, ndiff);
+}
+
+// test on IVFFlat and a VectorTransform
+TEST(MERGE, merge_flat_vt) {
+ faiss::IndexShards index_shards(d, false, false);
+ index_shards.own_indices = true;
+
+ // here we have to retrain because of the vectorTransform
+ faiss::RandomRotationMatrix rot(d, d);
+ rot.init(1234);
+ faiss::IndexFlatL2 quantizer(d);
+
+ { // just to train the quantizer
+ faiss::IndexIVFFlat iflat(&quantizer, d, nlist);
+ faiss::IndexPreTransform ipt(&rot, &iflat);
+ ipt.train(nb, cd.database.data());
+ }
+
+ for (int i = 0; i < nindex; i++) {
+ faiss::IndexPreTransform* ipt = new faiss::IndexPreTransform(
+ new faiss::RandomRotationMatrix(rot),
+ new faiss::IndexIVFFlat(&quantizer, d, nlist));
+ ipt->own_fields = true;
+ index_shards.add_shard(ipt);
+ }
+ EXPECT_TRUE(index_shards.is_trained);
+ index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data());
+ size_t prev_ntotal = index_shards.ntotal;
+ int ndiff = compare_merged(&index_shards, false);
+ EXPECT_EQ(prev_ntotal, index_shards.ntotal);
+ EXPECT_GE(0, ndiff);
+}
+
+// put the merged invfile on disk
+TEST(MERGE, merge_flat_ondisk) {
+ faiss::IndexShards index_shards(d, false, false);
+ index_shards.own_indices = true;
+ Tempfilename filename(&temp_file_mutex, temp_filename_template);
+
+ for (int i = 0; i < nindex; i++) {
+ auto ivf = new faiss::IndexIVFFlat(&cd.quantizer, d, nlist);
+ if (i == 0) {
+ auto il = new faiss::OnDiskInvertedLists(
+ ivf->nlist, ivf->code_size, filename.c_str());
+ ivf->replace_invlists(il, true);
+ }
+ index_shards.add_shard(ivf);
+ }
+
+ EXPECT_TRUE(index_shards.is_trained);
+ index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data());
+ int ndiff = compare_merged(&index_shards, false);
+
+ EXPECT_EQ(ndiff, 0);
+}
+
+// now use ondisk specific merge
+TEST(MERGE, merge_flat_ondisk_2) {
+ faiss::IndexShards index_shards(d, false, false);
+ index_shards.own_indices = true;
+
+ for (int i = 0; i < nindex; i++) {
+ index_shards.add_shard(
+ new faiss::IndexIVFFlat(&cd.quantizer, d, nlist));
+ }
+ EXPECT_TRUE(index_shards.is_trained);
+ index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data());
+ int ndiff = compare_merged(&index_shards, false, false);
+ EXPECT_GE(0, ndiff);
+}
+
+// now use ondisk specific merge and use shift ids
+TEST(MERGE, merge_flat_ondisk_3) {
+ faiss::IndexShards index_shards(d, false, false);
+ index_shards.own_indices = true;
+
+ std::vector<idx_t> ids;
+ for (int i = 0; i < nb; ++i) {
+ int id = i % shard_size;
+ ids.push_back(id);
+ }
+ for (int i = 0; i < nindex; i++) {
+ index_shards.add_shard(
+ new faiss::IndexIVFFlat(&cd.quantizer, d, nlist));
+ }
+ EXPECT_TRUE(index_shards.is_trained);
+ index_shards.add_with_ids(nb, cd.database.data(), ids.data());
+ int ndiff = compare_merged(&index_shards, true, false);
+ EXPECT_GE(0, ndiff);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_mmap.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_mmap.cpp
new file mode 100644
index 0000000..800ffc2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_mmap.cpp
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <cstdio>
+#include <fstream>
+#include <iostream>
+#include <random>
+#include <vector>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/io.h>
+#include <faiss/index_io.h>
+
+namespace {
+
+std::vector<float> make_data(const size_t n, const size_t d, size_t seed) {
+ std::vector<float> database(n * d);
+ std::mt19937 rng(seed);
+ std::uniform_real_distribution<float> distrib;
+
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::vector<uint8_t> make_binary_data(
+ const size_t n,
+ const size_t d,
+ size_t seed) {
+ std::vector<uint8_t> database(n * d);
+ std::mt19937 rng(seed);
+ std::uniform_int_distribution<uint8_t> distrib(0, 255);
+
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+} // namespace
+
+// the logic is the following:
+// 1. generate two flatcodes-based indices, Index1 and Index2
+// 2. serialize both indices into std::vector<> buffers, Buf1 and Buf2
+// 3. save Buf1 into a temporary file, File1
+// 4. deserialize Index1 using mmap feature on File1 into Index1MM
+// 5. ensure that Index1MM acts as Index2 if we write the data from Buf2
+// on top of the existing File1
+// 6. ensure that Index1MM acts as Index1 if we write the data from Buf1
+// on top of the existing File1 again
+
+TEST(TestMmap, mmap_flatcodes) {
+ // generate data
+ const size_t nt = 1000;
+ const size_t nq = 10;
+ const size_t d = 32;
+ const size_t k = 25;
+
+ std::vector<float> xt1 = make_data(nt, d, 123);
+ std::vector<float> xt2 = make_data(nt, d, 456);
+ std::vector<float> xq = make_data(nq, d, 789);
+
+ // ensure that the data is different
+ ASSERT_NE(xt1, xt2);
+
+ // make index1 and create reference results
+ faiss::IndexFlatL2 index1(d);
+ index1.train(nt, xt1.data());
+ index1.add(nt, xt1.data());
+
+ std::vector<float> ref_dis_1(k * nq);
+ std::vector<faiss::idx_t> ref_ids_1(k * nq);
+ index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data());
+
+ // make index2 and create reference results
+ faiss::IndexFlatL2 index2(d);
+ index2.train(nt, xt2.data());
+ index2.add(nt, xt2.data());
+
+ std::vector<float> ref_dis_2(k * nq);
+ std::vector<faiss::idx_t> ref_ids_2(k * nq);
+ index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data());
+
+ // ensure that the results are different
+ ASSERT_NE(ref_dis_1, ref_dis_2);
+ ASSERT_NE(ref_ids_1, ref_ids_2);
+
+ // serialize both in a form of vectors
+ faiss::VectorIOWriter wr1;
+ faiss::write_index(&index1, &wr1);
+
+ faiss::VectorIOWriter wr2;
+ faiss::write_index(&index2, &wr2);
+
+ // generate a temporary file and write index1 into it
+ std::string tmpname = std::tmpnam(nullptr);
+
+ {
+ std::ofstream ofs(tmpname);
+ ofs.write((const char*)wr1.data.data(), wr1.data.size());
+ }
+
+ // create a mmap index
+ std::unique_ptr<faiss::Index> index1mm(
+ faiss::read_index(tmpname.c_str(), faiss::IO_FLAG_MMAP_IFC));
+
+ ASSERT_NE(index1mm, nullptr);
+
+ // perform a search
+ std::vector<float> cand_dis_1(k * nq);
+ std::vector<faiss::idx_t> cand_ids_1(k * nq);
+ index1mm->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_1);
+ ASSERT_EQ(ref_dis_1, cand_dis_1);
+
+ // ok now, overwrite the internals of the file without recreating it
+ {
+ std::ofstream ofs(tmpname);
+ ofs.seekp(0, std::ios::beg);
+
+ ofs.write((const char*)wr2.data.data(), wr2.data.size());
+ }
+
+ // perform a search
+ std::vector<float> cand_dis_2(k * nq);
+ std::vector<faiss::idx_t> cand_ids_2(k * nq);
+ index1mm->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_2, cand_ids_2);
+ ASSERT_EQ(ref_dis_2, cand_dis_2);
+
+ // write back data1
+ {
+ std::ofstream ofs(tmpname);
+ ofs.seekp(0, std::ios::beg);
+
+ ofs.write((const char*)wr1.data.data(), wr1.data.size());
+ }
+
+ // perform a search
+ std::vector<float> cand_dis_3(k * nq);
+ std::vector<faiss::idx_t> cand_ids_3(k * nq);
+ index1mm->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_3);
+ ASSERT_EQ(ref_dis_1, cand_dis_3);
+}
+
+TEST(TestMmap, mmap_binary_flatcodes) {
+ // generate data
+ const size_t nt = 1000;
+ const size_t nq = 10;
+ // in bits
+ const size_t d = 64;
+ // in bytes
+ const size_t d8 = (d + 7) / 8;
+ const size_t k = 25;
+
+ std::vector<uint8_t> xt1 = make_binary_data(nt, d8, 123);
+ std::vector<uint8_t> xt2 = make_binary_data(nt, d8, 456);
+ std::vector<uint8_t> xq = make_binary_data(nq, d8, 789);
+
+ // ensure that the data is different
+ ASSERT_NE(xt1, xt2);
+
+ // make index1 and create reference results
+ faiss::IndexBinaryFlat index1(d);
+ index1.train(nt, xt1.data());
+ index1.add(nt, xt1.data());
+
+ std::vector<int32_t> ref_dis_1(k * nq);
+ std::vector<faiss::idx_t> ref_ids_1(k * nq);
+ index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data());
+
+ // make index2 and create reference results
+ faiss::IndexBinaryFlat index2(d);
+ index2.train(nt, xt2.data());
+ index2.add(nt, xt2.data());
+
+ std::vector<int32_t> ref_dis_2(k * nq);
+ std::vector<faiss::idx_t> ref_ids_2(k * nq);
+ index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data());
+
+ // ensure that the results are different
+ ASSERT_NE(ref_dis_1, ref_dis_2);
+ ASSERT_NE(ref_ids_1, ref_ids_2);
+
+ // serialize both in a form of vectors
+ faiss::VectorIOWriter wr1;
+ faiss::write_index_binary(&index1, &wr1);
+
+ faiss::VectorIOWriter wr2;
+ faiss::write_index_binary(&index2, &wr2);
+
+ // generate a temporary file and write index1 into it
+ std::string tmpname = std::tmpnam(nullptr);
+
+ {
+ std::ofstream ofs(tmpname);
+ ofs.write((const char*)wr1.data.data(), wr1.data.size());
+ }
+
+ // create a mmap index
+ std::unique_ptr<faiss::IndexBinary> index1mm(
+ faiss::read_index_binary(tmpname.c_str(), faiss::IO_FLAG_MMAP_IFC));
+
+ ASSERT_NE(index1mm, nullptr);
+
+ // perform a search
+ std::vector<int32_t> cand_dis_1(k * nq);
+ std::vector<faiss::idx_t> cand_ids_1(k * nq);
+ index1mm->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_1);
+ ASSERT_EQ(ref_dis_1, cand_dis_1);
+
+ // ok now, overwrite the internals of the file without recreating it
+ {
+ std::ofstream ofs(tmpname);
+ ofs.seekp(0, std::ios::beg);
+
+ ofs.write((const char*)wr2.data.data(), wr2.data.size());
+ }
+
+ // perform a search
+ std::vector<int32_t> cand_dis_2(k * nq);
+ std::vector<faiss::idx_t> cand_ids_2(k * nq);
+ index1mm->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_2, cand_ids_2);
+ ASSERT_EQ(ref_dis_2, cand_dis_2);
+
+ // write back data1
+ {
+ std::ofstream ofs(tmpname);
+ ofs.seekp(0, std::ios::beg);
+
+ ofs.write((const char*)wr1.data.data(), wr1.data.size());
+ }
+
+ // perform a search
+ std::vector<int32_t> cand_dis_3(k * nq);
+ std::vector<faiss::idx_t> cand_ids_3(k * nq);
+ index1mm->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_3);
+ ASSERT_EQ(ref_dis_1, cand_dis_3);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_omp_threads.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_omp_threads.cpp
new file mode 100644
index 0000000..1249b88
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_omp_threads.cpp
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <faiss/utils/utils.h>
+
+TEST(Threading, openmp) {
+ EXPECT_TRUE(faiss::check_openmp());
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_ondisk_ivf.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ondisk_ivf.cpp
new file mode 100644
index 0000000..4f3d3a3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_ondisk_ivf.cpp
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <unistd.h>
+
+#include <pthread.h>
+#include <unordered_map>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/index_io.h>
+#include <faiss/invlists/OnDiskInvertedLists.h>
+#include <faiss/utils/random.h>
+
+namespace {
+
+struct Tempfilename {
+ static pthread_mutex_t mutex;
+
+ std::string filename = "/tmp/faiss_tmp_XXXXXX";
+
+ Tempfilename() {
+ pthread_mutex_lock(&mutex);
+ int fd = mkstemp(&filename[0]);
+ close(fd);
+ pthread_mutex_unlock(&mutex);
+ }
+
+ ~Tempfilename() {
+ if (access(filename.c_str(), F_OK)) {
+ unlink(filename.c_str());
+ }
+ }
+
+ const char* c_str() {
+ return filename.c_str();
+ }
+};
+
+pthread_mutex_t Tempfilename::mutex = PTHREAD_MUTEX_INITIALIZER;
+
+} // namespace
+
+TEST(ONDISK, make_invlists) {
+ int nlist = 100;
+ int code_size = 32;
+ int nadd = 1000000;
+ std::unordered_map<int, int> listnos;
+
+ Tempfilename filename;
+
+ faiss::OnDiskInvertedLists ivf(nlist, code_size, filename.c_str());
+
+ {
+ std::vector<uint8_t> code(32);
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (int i = 0; i < nadd; i++) {
+ double d = distrib(rng);
+ int list_no = int(nlist * d * d); // skewed distribution
+ int* ar = (int*)code.data();
+ ar[0] = i;
+ ar[1] = list_no;
+ ivf.add_entry(list_no, i, code.data());
+ listnos[i] = list_no;
+ }
+ }
+
+ int ntot = 0;
+ for (int i = 0; i < nlist; i++) {
+ int size = ivf.list_size(i);
+ const faiss::idx_t* ids = ivf.get_ids(i);
+ const uint8_t* codes = ivf.get_codes(i);
+ for (int j = 0; j < size; j++) {
+ faiss::idx_t id = ids[j];
+ const int* ar = (const int*)&codes[code_size * j];
+ EXPECT_EQ(ar[0], id);
+ EXPECT_EQ(ar[1], i);
+ EXPECT_EQ(listnos[id], i);
+ ntot++;
+ }
+ }
+ EXPECT_EQ(ntot, nadd);
+}
+
+TEST(ONDISK, test_add) {
+ int d = 8;
+ int nlist = 30, nq = 200, nb = 1500, k = 10;
+ faiss::IndexFlatL2 quantizer(d);
+ {
+ std::vector<float> x(d * nlist);
+ faiss::float_rand(x.data(), d * nlist, 12345);
+ quantizer.add(nlist, x.data());
+ }
+ std::vector<float> xb(d * nb);
+ faiss::float_rand(xb.data(), d * nb, 23456);
+
+ faiss::IndexIVFFlat index(&quantizer, d, nlist);
+ index.add(nb, xb.data());
+
+ std::vector<float> xq(d * nb);
+ faiss::float_rand(xq.data(), d * nq, 34567);
+
+ std::vector<float> ref_D(nq * k);
+ std::vector<faiss::idx_t> ref_I(nq * k);
+
+ index.search(nq, xq.data(), k, ref_D.data(), ref_I.data());
+
+ Tempfilename filename, filename2;
+
+ // test add + search
+ {
+ faiss::IndexIVFFlat index2(&quantizer, d, nlist);
+
+ faiss::OnDiskInvertedLists ivf(
+ index.nlist, index.code_size, filename.c_str());
+
+ index2.replace_invlists(&ivf);
+
+ index2.add(nb, xb.data());
+
+ std::vector<float> new_D(nq * k);
+ std::vector<faiss::idx_t> new_I(nq * k);
+
+ index2.search(nq, xq.data(), k, new_D.data(), new_I.data());
+
+ EXPECT_EQ(ref_D, new_D);
+ EXPECT_EQ(ref_I, new_I);
+
+ write_index(&index2, filename2.c_str());
+ }
+
+ // test io
+ {
+ faiss::Index* index3 = faiss::read_index(filename2.c_str());
+
+ std::vector<float> new_D(nq * k);
+ std::vector<faiss::idx_t> new_I(nq * k);
+
+ index3->search(nq, xq.data(), k, new_D.data(), new_I.data());
+
+ EXPECT_EQ(ref_D, new_D);
+ EXPECT_EQ(ref_I, new_I);
+
+ delete index3;
+ }
+}
+
+// WARN this thest will run multithreaded only in opt mode
+TEST(ONDISK, make_invlists_threaded) {
+ int nlist = 100;
+ int code_size = 32;
+ int nadd = 1000000;
+
+ Tempfilename filename;
+
+ faiss::OnDiskInvertedLists ivf(nlist, code_size, filename.c_str());
+
+ std::vector<int> list_nos(nadd);
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (int i = 0; i < nadd; i++) {
+ double d = distrib(rng);
+ list_nos[i] = int(nlist * d * d); // skewed distribution
+ }
+
+#pragma omp parallel
+ {
+ std::vector<uint8_t> code(32);
+#pragma omp for
+ for (int i = 0; i < nadd; i++) {
+ int list_no = list_nos[i];
+ int* ar = (int*)code.data();
+ ar[0] = i;
+ ar[1] = list_no;
+ ivf.add_entry(list_no, i, code.data());
+ }
+ }
+
+ int ntot = 0;
+ for (int i = 0; i < nlist; i++) {
+ int size = ivf.list_size(i);
+ const faiss::idx_t* ids = ivf.get_ids(i);
+ const uint8_t* codes = ivf.get_codes(i);
+ for (int j = 0; j < size; j++) {
+ faiss::idx_t id = ids[j];
+ const int* ar = (const int*)&codes[code_size * j];
+ EXPECT_EQ(ar[0], id);
+ EXPECT_EQ(ar[1], i);
+ EXPECT_EQ(list_nos[id], i);
+ ntot++;
+ }
+ }
+ EXPECT_EQ(ntot, nadd);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_pairs_decoding.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_pairs_decoding.cpp
new file mode 100644
index 0000000..3b36d41
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_pairs_decoding.cpp
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <memory>
+#include <random>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IVFlib.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/VectorTransform.h>
+#include <faiss/index_factory.h>
+
+namespace {
+
+typedef faiss::idx_t idx_t;
+
+/*************************************************************
+ * Test utils
+ *************************************************************/
+
+// dimension of the vectors to index
+int d = 64;
+
+// size of the database we plan to index
+size_t nb = 8000;
+
+// nb of queries
+size_t nq = 200;
+
+std::mt19937 rng;
+
+std::vector<float> make_data(size_t n) {
+ std::vector<float> database(n * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<faiss::Index> make_index(
+ const char* index_type,
+ const std::vector<float>& x) {
+ auto index =
+ std::unique_ptr<faiss::Index>(faiss::index_factory(d, index_type));
+ index->train(nb, x.data());
+ index->add(nb, x.data());
+ return index;
+}
+
+/*************************************************************
+ * Test functions for a given index type
+ *************************************************************/
+
+bool test_search_centroid(const char* index_key) {
+ std::vector<float> xb = make_data(nb); // database vectors
+ auto index = make_index(index_key, xb);
+
+ /* First test: find the centroids associated to the database
+ vectors and make sure that each vector does indeed appear in
+ the inverted list corresponding to its centroid */
+
+ std::vector<idx_t> centroid_ids(nb);
+ faiss::ivflib::search_centroid(
+ index.get(), xb.data(), nb, centroid_ids.data());
+
+ const faiss::IndexIVF* ivf = faiss::ivflib::extract_index_ivf(index.get());
+
+ for (int i = 0; i < nb; i++) {
+ bool found = false;
+ int list_no = centroid_ids[i];
+ int list_size = ivf->invlists->list_size(list_no);
+ auto* list = ivf->invlists->get_ids(list_no);
+
+ for (int j = 0; j < list_size; j++) {
+ if (list[j] == i) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ return false;
+ }
+ return true;
+}
+
+int test_search_and_return_centroids(const char* index_key) {
+ std::vector<float> xb = make_data(nb); // database vectors
+ auto index = make_index(index_key, xb);
+
+ std::vector<idx_t> centroid_ids(nb);
+ faiss::ivflib::search_centroid(
+ index.get(), xb.data(), nb, centroid_ids.data());
+
+ faiss::IndexIVF* ivf = faiss::ivflib::extract_index_ivf(index.get());
+ ivf->nprobe = 4;
+
+ std::vector<float> xq = make_data(nq); // database vectors
+
+ int k = 5;
+
+ // compute a reference search result
+
+ std::vector<idx_t> refI(nq * k);
+ std::vector<float> refD(nq * k);
+ index->search(nq, xq.data(), k, refD.data(), refI.data());
+
+ // compute search result
+
+ std::vector<idx_t> newI(nq * k);
+ std::vector<float> newD(nq * k);
+
+ std::vector<idx_t> query_centroid_ids(nq);
+ std::vector<idx_t> result_centroid_ids(nq * k);
+
+ faiss::ivflib::search_and_return_centroids(
+ index.get(),
+ nq,
+ xq.data(),
+ k,
+ newD.data(),
+ newI.data(),
+ query_centroid_ids.data(),
+ result_centroid_ids.data());
+
+ // first verify that we have the same result as the standard search
+
+ if (newI != refI) {
+ return 1;
+ }
+
+ // then check if the result ids are indeed in the inverted list
+ // they are supposed to be in
+
+ for (int i = 0; i < nq * k; i++) {
+ int list_no = result_centroid_ids[i];
+ int result_no = newI[i];
+
+ if (result_no < 0)
+ continue;
+
+ bool found = false;
+
+ int list_size = ivf->invlists->list_size(list_no);
+ auto* list = ivf->invlists->get_ids(list_no);
+
+ for (int j = 0; j < list_size; j++) {
+ if (list[j] == result_no) {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ return 2;
+ }
+ return 0;
+}
+
+} // namespace
+
+/*************************************************************
+ * Test entry points
+ *************************************************************/
+
+TEST(testSearchCentroid, IVFFlat) {
+ bool ok = test_search_centroid("IVF32,Flat");
+ EXPECT_TRUE(ok);
+}
+
+TEST(testSearchCentroid, PCAIVFFlat) {
+ bool ok = test_search_centroid("PCA16,IVF32,Flat");
+ EXPECT_TRUE(ok);
+}
+
+TEST(testSearchAndReturnCentroids, IVFFlat) {
+ int err = test_search_and_return_centroids("IVF32,Flat");
+ EXPECT_NE(err, 1);
+ EXPECT_NE(err, 2);
+}
+
+TEST(testSearchAndReturnCentroids, PCAIVFFlat) {
+ int err = test_search_and_return_centroids("PCA16,IVF32,Flat");
+ EXPECT_NE(err, 1);
+ EXPECT_NE(err, 2);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_params_override.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_params_override.cpp
new file mode 100644
index 0000000..106bf27
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_params_override.cpp
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <memory>
+#include <random>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/IVFlib.h>
+#include <faiss/IndexBinaryIVF.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/clone_index.h>
+#include <faiss/impl/AuxIndexStructures.h>
+#include <faiss/impl/IDSelector.h>
+#include <faiss/index_factory.h>
+
+using namespace faiss;
+
+namespace {
+
+// dimension of the vectors to index
+int d = 32;
+
+// size of the database we plan to index
+size_t nb = 1000;
+
+// nb of queries
+size_t nq = 200;
+
+std::mt19937 rng;
+
+std::vector<float> make_data(size_t n) {
+ std::vector<float> database(n * d);
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<Index> make_index(
+ const char* index_type,
+ MetricType metric,
+ const std::vector<float>& x) {
+ assert(x.size() % d == 0);
+ idx_t nb = x.size() / d;
+ std::unique_ptr<Index> index(index_factory(d, index_type, metric));
+ index->train(nb, x.data());
+ index->add(nb, x.data());
+ return index;
+}
+
+std::vector<idx_t> search_index(Index* index, const float* xq) {
+ int k = 10;
+ std::vector<idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+ index->search(nq, xq, k, D.data(), I.data());
+ return I;
+}
+
+std::vector<idx_t> search_index_with_params(
+ Index* index,
+ const float* xq,
+ IVFSearchParameters* params) {
+ int k = 10;
+ std::vector<idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+ ivflib::search_with_parameters(
+ index, nq, xq, k, D.data(), I.data(), params);
+ return I;
+}
+
+/*************************************************************
+ * Test functions for a given index type
+ *************************************************************/
+
+int test_params_override(const char* index_key, MetricType metric) {
+ std::vector<float> xb = make_data(nb); // database vectors
+ auto index = make_index(index_key, metric, xb);
+ // index->train(nb, xb.data());
+ // index->add(nb, xb.data());
+ std::vector<float> xq = make_data(nq);
+ ParameterSpace ps;
+ ps.set_index_parameter(index.get(), "nprobe", 2);
+ auto res2ref = search_index(index.get(), xq.data());
+ ps.set_index_parameter(index.get(), "nprobe", 9);
+ auto res9ref = search_index(index.get(), xq.data());
+ ps.set_index_parameter(index.get(), "nprobe", 1);
+
+ IVFSearchParameters params;
+ params.max_codes = 0;
+ params.nprobe = 2;
+ auto res2new = search_index_with_params(index.get(), xq.data(), &params);
+ params.nprobe = 9;
+ auto res9new = search_index_with_params(index.get(), xq.data(), &params);
+
+ if (res2ref != res2new)
+ return 2;
+
+ if (res9ref != res9new)
+ return 9;
+
+ return 0;
+}
+
+/*************************************************************
+ * Test subsets
+ *************************************************************/
+
+int test_selector(const char* index_key) {
+ std::vector<float> xb = make_data(nb); // database vectors
+ std::vector<float> xq = make_data(nq);
+ ParameterSpace ps;
+
+ std::vector<float> sub_xb;
+ std::vector<idx_t> kept;
+ for (idx_t i = 0; i < nb; i++) {
+ if (i % 10 == 2) {
+ kept.push_back(i);
+ sub_xb.insert(
+ sub_xb.end(), xb.begin() + i * d, xb.begin() + (i + 1) * d);
+ }
+ }
+
+ // full index
+ auto index = make_index(index_key, METRIC_L2, xb);
+ ps.set_index_parameter(index.get(), "nprobe", 3);
+
+ // restricted index
+ std::unique_ptr<Index> sub_index(clone_index(index.get()));
+ sub_index->reset();
+ sub_index->add_with_ids(kept.size(), sub_xb.data(), kept.data());
+
+ auto ref_result = search_index(sub_index.get(), xq.data());
+
+ IVFSearchParameters params;
+ params.max_codes = 0;
+ params.nprobe = 3;
+ IDSelectorBatch sel(kept.size(), kept.data());
+ params.sel = &sel;
+ auto new_result = search_index_with_params(index.get(), xq.data(), &params);
+
+ if (ref_result != new_result) {
+ return 1;
+ }
+
+ return 0;
+}
+
+} // namespace
+
+/*************************************************************
+ * Test entry points
+ *************************************************************/
+
+TEST(TPO, IVFFlat) {
+ int err1 = test_params_override("IVF32,Flat", METRIC_L2);
+ EXPECT_EQ(err1, 0);
+ int err2 = test_params_override("IVF32,Flat", METRIC_INNER_PRODUCT);
+ EXPECT_EQ(err2, 0);
+}
+
+TEST(TPO, IVFPQ) {
+ int err1 = test_params_override("IVF32,PQ8np", METRIC_L2);
+ EXPECT_EQ(err1, 0);
+ int err2 = test_params_override("IVF32,PQ8np", METRIC_INNER_PRODUCT);
+ EXPECT_EQ(err2, 0);
+}
+
+TEST(TPO, IVFSQ) {
+ int err1 = test_params_override("IVF32,SQ8", METRIC_L2);
+ EXPECT_EQ(err1, 0);
+ int err2 = test_params_override("IVF32,SQ8", METRIC_INNER_PRODUCT);
+ EXPECT_EQ(err2, 0);
+}
+
+TEST(TPO, IVFFlatPP) {
+ int err1 = test_params_override("PCA16,IVF32,SQ8", METRIC_L2);
+ EXPECT_EQ(err1, 0);
+ int err2 = test_params_override("PCA16,IVF32,SQ8", METRIC_INNER_PRODUCT);
+ EXPECT_EQ(err2, 0);
+}
+
+TEST(TSEL, IVFFlat) {
+ int err = test_selector("PCA16,IVF32,Flat");
+ EXPECT_EQ(err, 0);
+}
+
+TEST(TSEL, IVFFPQ) {
+ int err = test_selector("PCA16,IVF32,PQ4x8np");
+ EXPECT_EQ(err, 0);
+}
+
+TEST(TSEL, IVFFSQ) {
+ int err = test_selector("PCA16,IVF32,SQ8");
+ EXPECT_EQ(err, 0);
+}
+
+/*************************************************************
+ * Same for binary indexes
+ *************************************************************/
+
+std::vector<uint8_t> make_data_binary(size_t n) {
+ std::vector<uint8_t> database(n * d / 8);
+ std::uniform_int_distribution<> distrib;
+ for (size_t i = 0; i < n * d / 8; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<IndexBinaryIVF> make_index(
+ const char* index_type,
+ const std::vector<uint8_t>& x) {
+ auto index = std::unique_ptr<IndexBinaryIVF>(
+ dynamic_cast<IndexBinaryIVF*>(index_binary_factory(d, index_type)));
+ index->train(nb, x.data());
+ index->add(nb, x.data());
+ return index;
+}
+
+std::vector<idx_t> search_index(IndexBinaryIVF* index, const uint8_t* xq) {
+ int k = 10;
+ std::vector<idx_t> I(k * nq);
+ std::vector<int32_t> D(k * nq);
+ index->search(nq, xq, k, D.data(), I.data());
+ return I;
+}
+
+std::vector<idx_t> search_index_with_params(
+ IndexBinaryIVF* index,
+ const uint8_t* xq,
+ IVFSearchParameters* params) {
+ int k = 10;
+ std::vector<idx_t> I(k * nq);
+ std::vector<int32_t> D(k * nq);
+
+ std::vector<idx_t> Iq(params->nprobe * nq);
+ std::vector<int32_t> Dq(params->nprobe * nq);
+
+ index->quantizer->search(nq, xq, params->nprobe, Dq.data(), Iq.data());
+ index->search_preassigned(
+ nq, xq, k, Iq.data(), Dq.data(), D.data(), I.data(), false, params);
+ return I;
+}
+
+int test_params_override_binary(const char* index_key) {
+ std::vector<uint8_t> xb = make_data_binary(nb); // database vectors
+ auto index = make_index(index_key, xb);
+ index->train(nb, xb.data());
+ index->add(nb, xb.data());
+ std::vector<uint8_t> xq = make_data_binary(nq);
+ index->nprobe = 2;
+ auto res2ref = search_index(index.get(), xq.data());
+ index->nprobe = 9;
+ auto res9ref = search_index(index.get(), xq.data());
+ index->nprobe = 1;
+
+ IVFSearchParameters params;
+ params.max_codes = 0;
+ params.nprobe = 2;
+ auto res2new = search_index_with_params(index.get(), xq.data(), &params);
+ params.nprobe = 9;
+ auto res9new = search_index_with_params(index.get(), xq.data(), &params);
+
+ if (res2ref != res2new)
+ return 2;
+
+ if (res9ref != res9new)
+ return 9;
+
+ return 0;
+}
+
+TEST(TPOB, IVF) {
+ int err1 = test_params_override_binary("BIVF32");
+ EXPECT_EQ(err1, 0);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_partitioning.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_partitioning.cpp
new file mode 100644
index 0000000..14b8927
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_partitioning.cpp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <faiss/utils/AlignedTable.h>
+#include <faiss/utils/partitioning.h>
+
+using namespace faiss;
+
+typedef AlignedTable<uint16_t> AlignedTableUint16;
+
+// TODO: This test fails when Faiss is compiled with
+// GCC 13.2 from conda-forge with AVX2 enabled. This may be
+// a GCC bug that needs to be investigated further.
+// As of 16-AUG-2023 the Faiss conda packages are built
+// with GCC 11.2, so the published binaries are not affected.
+TEST(TestPartitioning, TestPartitioningBigRange) {
+ auto n = 1024;
+ AlignedTableUint16 tab(n);
+ for (auto i = 0; i < n; i++) {
+ tab[i] = i * 64;
+ }
+ int32_t hist[16]{};
+ simd_histogram_16(tab.get(), n, 0, 12, hist);
+ for (auto i = 0; i < 16; i++) {
+ ASSERT_EQ(hist[i], 64);
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_pq_encoding.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_pq_encoding.cpp
new file mode 100644
index 0000000..ad5a089
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_pq_encoding.cpp
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <iostream>
+#include <memory>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/impl/ProductQuantizer.h>
+#include <faiss/impl/pq4_fast_scan.h>
+
+namespace {
+
+const std::vector<uint64_t> random_vector(size_t s) {
+ std::vector<uint64_t> v(s, 0);
+ for (size_t i = 0; i < s; ++i) {
+ v[i] = rand();
+ }
+
+ return v;
+}
+
+const std::vector<float> random_vector_float(size_t s) {
+ std::vector<float> v(s, 0);
+ for (size_t i = 0; i < s; ++i) {
+ v[i] = rand();
+ }
+
+ return v;
+}
+
+} // namespace
+
+TEST(PQEncoderGeneric, encode) {
+ const int nsubcodes = 97;
+ const int minbits = 1;
+ const int maxbits = 24;
+ const std::vector<uint64_t> values = random_vector(nsubcodes);
+
+ for (int nbits = minbits; nbits <= maxbits; ++nbits) {
+ std::cerr << "nbits = " << nbits << std::endl;
+
+ const uint64_t mask = (1ull << nbits) - 1;
+ std::unique_ptr<uint8_t[]> codes(
+ new uint8_t[(nsubcodes * maxbits + 7) / 8]);
+
+ // NOTE(hoss): Necessary scope to ensure trailing bits are flushed to
+ // mem.
+ {
+ faiss::PQEncoderGeneric encoder(codes.get(), nbits);
+ for (const auto& v : values) {
+ encoder.encode(v & mask);
+ }
+ }
+
+ faiss::PQDecoderGeneric decoder(codes.get(), nbits);
+ for (int i = 0; i < nsubcodes; ++i) {
+ uint64_t v = decoder.decode();
+ EXPECT_EQ(values[i] & mask, v);
+ }
+ }
+}
+
+TEST(PQEncoder8, encode) {
+ const int nsubcodes = 100;
+ const std::vector<uint64_t> values = random_vector(nsubcodes);
+ const uint64_t mask = 0xFF;
+ std::unique_ptr<uint8_t[]> codes(new uint8_t[nsubcodes]);
+
+ faiss::PQEncoder8 encoder(codes.get(), 8);
+ for (const auto& v : values) {
+ encoder.encode(v & mask);
+ }
+
+ faiss::PQDecoder8 decoder(codes.get(), 8);
+ for (int i = 0; i < nsubcodes; ++i) {
+ uint64_t v = decoder.decode();
+ EXPECT_EQ(values[i] & mask, v);
+ }
+}
+
+TEST(PQEncoder16, encode) {
+ const int nsubcodes = 100;
+ const std::vector<uint64_t> values = random_vector(nsubcodes);
+ const uint64_t mask = 0xFFFF;
+ std::unique_ptr<uint8_t[]> codes(new uint8_t[2 * nsubcodes]);
+
+ faiss::PQEncoder16 encoder(codes.get(), 16);
+ for (const auto& v : values) {
+ encoder.encode(v & mask);
+ }
+
+ faiss::PQDecoder16 decoder(codes.get(), 16);
+ for (int i = 0; i < nsubcodes; ++i) {
+ uint64_t v = decoder.decode();
+ EXPECT_EQ(values[i] & mask, v);
+ }
+}
+
+TEST(PQFastScan, set_packed_element) {
+ int d = 20, ntotal = 1000, M = 5, nbits = 4;
+ const std::vector<float> ds = random_vector_float(ntotal * d);
+ faiss::IndexPQFastScan index(d, M, nbits);
+ index.train(ntotal, ds.data());
+ index.add(ntotal, ds.data());
+
+ for (int j = 0; j < 10; j++) {
+ int vector_id = rand() % ntotal;
+ std::vector<uint8_t> old(ntotal * M);
+ std::vector<uint8_t> code(M);
+ for (int i = 0; i < ntotal; i++) {
+ for (int sq = 0; sq < M; sq++) {
+ old[i * M + sq] = faiss::pq4_get_packed_element(
+ index.codes.data(), index.bbs, M, i, sq);
+ }
+ }
+ for (int sq = 0; sq < M; sq++) {
+ faiss::pq4_set_packed_element(
+ index.codes.data(),
+ ((old[vector_id * M + sq] + 3) % 16),
+ index.bbs,
+ M,
+ vector_id,
+ sq);
+ }
+ for (int i = 0; i < ntotal; i++) {
+ for (int sq = 0; sq < M; sq++) {
+ uint8_t newcode = faiss::pq4_get_packed_element(
+ index.codes.data(), index.bbs, M, i, sq);
+ uint8_t oldcode = old[i * M + sq];
+ if (i == vector_id) {
+ EXPECT_EQ(newcode, (oldcode + 3) % 16);
+ } else {
+ EXPECT_EQ(newcode, oldcode);
+ }
+ }
+ }
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_simdlib.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_simdlib.cpp
new file mode 100644
index 0000000..7ecbbb9
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_simdlib.cpp
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <faiss/utils/simdlib.h>
+
+using namespace faiss;
+
+TEST(TestSIMDLib, TestCmpltAndBlendInplace) {
+ simd8float32 lowestValues(0, 1, 2, 3, 4, 5, 6, 7);
+ simd8uint32 lowestIndices(0, 1, 2, 3, 4, 5, 6, 7);
+
+ simd8float32 candidateValues0(5, 5, 5, 5, 5, 5, 5, 5);
+ simd8uint32 candidateIndices0(10, 11, 12, 13, 14, 15, 16, 17);
+ cmplt_and_blend_inplace(
+ candidateValues0, candidateIndices0, lowestValues, lowestIndices);
+
+ simd8float32 candidateValues1(6, 6, 6, 6, 6, 6, 6, 6);
+ simd8uint32 candidateIndices1(20, 21, 22, 23, 24, 25, 26, 27);
+ cmplt_and_blend_inplace(
+ candidateValues1, candidateIndices1, lowestValues, lowestIndices);
+
+ simd8float32 candidateValues2(0, 1, 2, 3, 4, 5, 5, 5);
+ simd8uint32 candidateIndices2(30, 31, 32, 33, 34, 35, 36, 37);
+ cmplt_and_blend_inplace(
+ candidateValues2, candidateIndices2, lowestValues, lowestIndices);
+
+ simd8float32 expectedValues(0, 1, 2, 3, 4, 5, 5, 5);
+ simd8uint32 expectedIndices(0, 1, 2, 3, 4, 5, 16, 17);
+ ASSERT_TRUE(lowestValues.is_same_as(expectedValues));
+ ASSERT_TRUE(lowestIndices.is_same_as(expectedIndices));
+}
+
+TEST(TestSIMDLib, TestCmpltMinMaxFloat) {
+ simd8float32 minValues(0, 0, 0, 0, 0, 0, 0, 0);
+ simd8uint32 minIndices(0, 0, 0, 0, 0, 0, 0, 0);
+ simd8float32 maxValues(0, 0, 0, 0, 0, 0, 0, 0);
+ simd8uint32 maxIndices(0, 0, 0, 0, 0, 0, 0, 0);
+
+ simd8float32 candidateValues0(5, 5, 5, 5, 5, 5, 5, 5);
+ simd8uint32 candidateIndices0(10, 11, 12, 13, 14, 15, 16, 17);
+ simd8float32 currentValues0(0, 1, 2, 3, 4, 5, 6, 7);
+ simd8uint32 currentIndices0(0, 1, 2, 3, 4, 5, 6, 7);
+
+ cmplt_min_max_fast(
+ candidateValues0,
+ candidateIndices0,
+ currentValues0,
+ currentIndices0,
+ minValues,
+ minIndices,
+ maxValues,
+ maxIndices);
+
+ simd8float32 expectedMinValues(0, 1, 2, 3, 4, 5, 5, 5);
+ simd8uint32 expectedMinIndices(0, 1, 2, 3, 4, 5, 16, 17);
+ ASSERT_TRUE(minValues.is_same_as(expectedMinValues));
+ ASSERT_TRUE(minIndices.is_same_as(expectedMinIndices));
+
+ simd8float32 expectedMaxValues(5, 5, 5, 5, 5, 5, 6, 7);
+ // the result is not 10,11,12,13,14,5,6,7 because it is _fast version
+ simd8uint32 expectedMaxIndices(10, 11, 12, 13, 14, 15, 6, 7);
+ ASSERT_TRUE(maxValues.is_same_as(expectedMaxValues));
+ ASSERT_TRUE(maxIndices.is_same_as(expectedMaxIndices));
+}
+
+TEST(TestSIMDLib, TestCmpltMinMaxInt) {
+ simd8uint32 minValues(0, 0, 0, 0, 0, 0, 0, 0);
+ simd8uint32 minIndices(0, 0, 0, 0, 0, 0, 0, 0);
+ simd8uint32 maxValues(0, 0, 0, 0, 0, 0, 0, 0);
+ simd8uint32 maxIndices(0, 0, 0, 0, 0, 0, 0, 0);
+
+ simd8uint32 candidateValues0(5, 5, 5, 5, 5, 5, 5, 5);
+ simd8uint32 candidateIndices0(10, 11, 12, 13, 14, 15, 16, 17);
+ simd8uint32 currentValues0(0, 1, 2, 3, 4, 5, 6, 7);
+ simd8uint32 currentIndices0(0, 1, 2, 3, 4, 5, 6, 7);
+
+ cmplt_min_max_fast(
+ candidateValues0,
+ candidateIndices0,
+ currentValues0,
+ currentIndices0,
+ minValues,
+ minIndices,
+ maxValues,
+ maxIndices);
+
+ simd8uint32 expectedMinValues(0, 1, 2, 3, 4, 5, 5, 5);
+ simd8uint32 expectedMinIndices(0, 1, 2, 3, 4, 5, 16, 17);
+ ASSERT_TRUE(minValues.is_same_as(expectedMinValues));
+ ASSERT_TRUE(minIndices.is_same_as(expectedMinIndices));
+
+ simd8uint32 expectedMaxValues(5, 5, 5, 5, 5, 5, 6, 7);
+ // the result is not 10,11,12,13,14,5,6,7 because it is _fast version
+ simd8uint32 expectedMaxIndices(10, 11, 12, 13, 14, 15, 6, 7);
+ ASSERT_TRUE(maxValues.is_same_as(expectedMaxValues));
+ ASSERT_TRUE(maxIndices.is_same_as(expectedMaxIndices));
+}
+
+TEST(TestSIMDLib, TestCmpltMinMaxInt16) {
+ simd16uint16 minValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ simd16uint16 minIndices(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ simd16uint16 maxValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ simd16uint16 maxIndices(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+
+ simd16uint16 candidateValues0(
+ 5,
+ 5,
+ 5,
+ 5,
+ 5,
+ 5,
+ 5,
+ 5,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1005);
+ simd16uint16 candidateIndices0(
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ 16,
+ 17,
+ 1010,
+ 1011,
+ 1012,
+ 1013,
+ 1014,
+ 1015,
+ 1016,
+ 1017);
+ simd16uint16 currentValues0(
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 1000,
+ 1001,
+ 1002,
+ 1003,
+ 1004,
+ 1005,
+ 1006,
+ 1007);
+ simd16uint16 currentIndices0(
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 1000,
+ 1001,
+ 1002,
+ 1003,
+ 1004,
+ 1005,
+ 1006,
+ 1007);
+
+ cmplt_min_max_fast(
+ candidateValues0,
+ candidateIndices0,
+ currentValues0,
+ currentIndices0,
+ minValues,
+ minIndices,
+ maxValues,
+ maxIndices);
+
+ simd16uint16 expectedMinValues(
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 5,
+ 5,
+ 1000,
+ 1001,
+ 1002,
+ 1003,
+ 1004,
+ 1005,
+ 1005,
+ 1005);
+ simd16uint16 expectedMinIndices(
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 16,
+ 17,
+ 1000,
+ 1001,
+ 1002,
+ 1003,
+ 1004,
+ 1005,
+ 1016,
+ 1017);
+ ASSERT_TRUE(minValues.is_same_as(expectedMinValues));
+ ASSERT_TRUE(minIndices.is_same_as(expectedMinIndices));
+
+ simd16uint16 expectedMaxValues(
+ 5,
+ 5,
+ 5,
+ 5,
+ 5,
+ 5,
+ 6,
+ 7,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1005,
+ 1006,
+ 1007);
+ // the result is not 10,11,12,13,14,5,6,7 because it is _fast version
+ simd16uint16 expectedMaxIndices(
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ 6,
+ 7,
+ 1010,
+ 1011,
+ 1012,
+ 1013,
+ 1014,
+ 1015,
+ 1006,
+ 1007);
+ ASSERT_TRUE(maxValues.is_same_as(expectedMaxValues));
+ ASSERT_TRUE(maxIndices.is_same_as(expectedMaxIndices));
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_sliding_ivf.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_sliding_ivf.cpp
new file mode 100644
index 0000000..0afe630
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_sliding_ivf.cpp
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+
+#include <memory>
+#include <random>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/IVFlib.h>
+#include <faiss/IndexIVF.h>
+#include <faiss/clone_index.h>
+#include <faiss/index_factory.h>
+
+using namespace faiss;
+
+// dimension of the vectors to index
+int d = 32;
+
+// nb of training vectors
+size_t nt = 5000;
+
+// size of the database points per window step
+size_t nb = 1000;
+
+// nb of queries
+size_t nq = 200;
+
+int total_size = 40;
+int window_size = 10;
+
+std::vector<float> make_data(size_t n) {
+ std::vector<float> database(n * d);
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::unique_ptr<Index> make_trained_index(const char* index_type) {
+ auto index = std::unique_ptr<Index>(index_factory(d, index_type));
+ auto xt = make_data(nt * d);
+ index->train(nt, xt.data());
+ ParameterSpace().set_index_parameter(index.get(), "nprobe", 4);
+ return index;
+}
+
+std::vector<idx_t> search_index(Index* index, const float* xq) {
+ int k = 10;
+ std::vector<idx_t> I(k * nq);
+ std::vector<float> D(k * nq);
+ index->search(nq, xq, k, D.data(), I.data());
+ return I;
+}
+
+/*************************************************************
+ * Test functions for a given index type
+ *************************************************************/
+
+// make a few slices of indexes that can be merged
+void make_index_slices(
+ const Index* trained_index,
+ std::vector<std::unique_ptr<Index>>& sub_indexes) {
+ for (int i = 0; i < total_size; i++) {
+ sub_indexes.emplace_back(clone_index(trained_index));
+
+ Index* index = sub_indexes.back().get();
+
+ auto xb = make_data(nb * d);
+ std::vector<faiss::idx_t> ids(nb);
+ std::mt19937 rng;
+ std::uniform_int_distribution<> distrib;
+ for (int j = 0; j < nb; j++) {
+ ids[j] = distrib(rng);
+ }
+ index->add_with_ids(nb, xb.data(), ids.data());
+ }
+}
+
+// build merged index explicitly at sliding window position i
+Index* make_merged_index(
+ const Index* trained_index,
+ const std::vector<std::unique_ptr<Index>>& sub_indexes,
+ int i) {
+ Index* merged_index = clone_index(trained_index);
+ for (int j = i - window_size + 1; j <= i; j++) {
+ if (j < 0 || j >= total_size)
+ continue;
+ std::unique_ptr<Index> sub_index(clone_index(sub_indexes[j].get()));
+ IndexIVF* ivf0 = ivflib::extract_index_ivf(merged_index);
+ IndexIVF* ivf1 = ivflib::extract_index_ivf(sub_index.get());
+ ivf0->merge_from(*ivf1, 0);
+ merged_index->ntotal = ivf0->ntotal;
+ }
+ return merged_index;
+}
+
+int test_sliding_window(const char* index_key) {
+ std::unique_ptr<Index> trained_index = make_trained_index(index_key);
+
+ // make the index slices
+ std::vector<std::unique_ptr<Index>> sub_indexes;
+
+ make_index_slices(trained_index.get(), sub_indexes);
+
+ // now slide over the windows
+ std::unique_ptr<Index> index(clone_index(trained_index.get()));
+ ivflib::SlidingIndexWindow window(index.get());
+
+ auto xq = make_data(nq * d);
+
+ for (int i = 0; i < total_size + window_size; i++) {
+ // update the index
+ window.step(
+ i < total_size ? sub_indexes[i].get() : nullptr,
+ i >= window_size);
+
+ auto new_res = search_index(index.get(), xq.data());
+
+ std::unique_ptr<Index> merged_index(
+ make_merged_index(trained_index.get(), sub_indexes, i));
+
+ auto ref_res = search_index(merged_index.get(), xq.data());
+
+ EXPECT_EQ(ref_res.size(), new_res.size());
+
+ EXPECT_EQ(ref_res, new_res);
+ }
+ return 0;
+}
+
+int test_sliding_invlists(const char* index_key) {
+ std::unique_ptr<Index> trained_index = make_trained_index(index_key);
+
+ // make the index slices
+ std::vector<std::unique_ptr<Index>> sub_indexes;
+
+ make_index_slices(trained_index.get(), sub_indexes);
+
+ // now slide over the windows
+ std::unique_ptr<Index> index(clone_index(trained_index.get()));
+ IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get());
+
+ auto xq = make_data(nq * d);
+
+ for (int i = 0; i < total_size + window_size; i++) {
+ // update the index
+ std::vector<const InvertedLists*> ils;
+ for (int j = i - window_size + 1; j <= i; j++) {
+ if (j < 0 || j >= total_size)
+ continue;
+ ils.push_back(
+ ivflib::extract_index_ivf(sub_indexes[j].get())->invlists);
+ }
+ if (ils.size() == 0)
+ continue;
+
+ ConcatenatedInvertedLists* ci =
+ new ConcatenatedInvertedLists(ils.size(), ils.data());
+
+ // will be deleted by the index
+ index_ivf->replace_invlists(ci, true);
+
+ auto new_res = search_index(index.get(), xq.data());
+
+ std::unique_ptr<Index> merged_index(
+ make_merged_index(trained_index.get(), sub_indexes, i));
+
+ auto ref_res = search_index(merged_index.get(), xq.data());
+
+ EXPECT_EQ(ref_res.size(), new_res.size());
+ EXPECT_EQ(ref_res, new_res);
+ }
+ return 0;
+}
+
+/*************************************************************
+ * Test entry points
+ *************************************************************/
+
+TEST(SlidingWindow, IVFFlat) {
+ test_sliding_window("IVF32,Flat");
+}
+
+TEST(SlidingWindow, PCAIVFFlat) {
+ test_sliding_window("PCA24,IVF32,Flat");
+}
+
+TEST(SlidingInvlists, IVFFlat) {
+ test_sliding_invlists("IVF32,Flat");
+}
+
+TEST(SlidingInvlists, PCAIVFFlat) {
+ test_sliding_invlists("PCA24,IVF32,Flat");
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_threaded_index.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_threaded_index.cpp
new file mode 100644
index 0000000..170b58f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_threaded_index.cpp
@@ -0,0 +1,260 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <faiss/IndexReplicas.h>
+#include <faiss/IndexShards.h>
+#include <faiss/impl/ThreadedIndex.h>
+
+#include <gtest/gtest.h>
+#include <chrono>
+#include <memory>
+#include <thread>
+#include <vector>
+
+namespace {
+
+struct TestException : public std::exception {};
+
+using idx_t = faiss::idx_t;
+
+struct MockIndex : public faiss::Index {
+ explicit MockIndex(idx_t d) : faiss::Index(d) {
+ resetMock();
+ }
+
+ void resetMock() {
+ flag = false;
+ nCalled = 0;
+ xCalled = nullptr;
+ kCalled = 0;
+ distancesCalled = nullptr;
+ labelsCalled = nullptr;
+ }
+
+ void add(idx_t n, const float* x) override {
+ nCalled = n;
+ xCalled = x;
+ }
+
+ void search(
+ idx_t n,
+ const float* x,
+ idx_t k,
+ float* distances,
+ idx_t* labels,
+ const faiss::SearchParameters* params) const override {
+ FAISS_THROW_IF_NOT(!params);
+ nCalled = n;
+ xCalled = x;
+ kCalled = k;
+ distancesCalled = distances;
+ labelsCalled = labels;
+ }
+
+ void reset() override {}
+
+ bool flag;
+
+ mutable idx_t nCalled;
+ mutable const float* xCalled;
+ mutable idx_t kCalled;
+ mutable float* distancesCalled;
+ mutable idx_t* labelsCalled;
+};
+
+template <typename IndexT>
+struct MockThreadedIndex : public faiss::ThreadedIndex<IndexT> {
+ using idx_t = faiss::idx_t;
+
+ explicit MockThreadedIndex(bool threaded)
+ : faiss::ThreadedIndex<IndexT>(threaded) {}
+
+ void add(idx_t, const float*) override {}
+ void search(
+ idx_t,
+ const float*,
+ idx_t,
+ float*,
+ idx_t*,
+ const faiss::SearchParameters*) const override {}
+ void reset() override {}
+};
+
+} // namespace
+
+TEST(ThreadedIndex, SingleException) {
+ std::vector<std::unique_ptr<MockIndex>> idxs;
+
+ for (int i = 0; i < 3; ++i) {
+ idxs.emplace_back(new MockIndex(1));
+ }
+
+ auto fn = [](int i, MockIndex* index) {
+ if (i == 1) {
+ throw TestException();
+ } else {
+ std::this_thread::sleep_for(std::chrono::milliseconds(i * 250));
+
+ index->flag = true;
+ }
+ };
+
+ // Try with threading and without
+ for (bool threaded : {true, false}) {
+ // clear flags
+ for (auto& idx : idxs) {
+ idx->resetMock();
+ }
+
+ MockThreadedIndex<MockIndex> ti(threaded);
+ for (auto& idx : idxs) {
+ ti.addIndex(idx.get());
+ }
+
+ // The second index should throw
+ EXPECT_THROW(ti.runOnIndex(fn), TestException);
+
+ // Index 0 and 2 should have processed
+ EXPECT_TRUE(idxs[0]->flag);
+ EXPECT_TRUE(idxs[2]->flag);
+ }
+}
+
+TEST(ThreadedIndex, MultipleException) {
+ std::vector<std::unique_ptr<MockIndex>> idxs;
+
+ for (int i = 0; i < 3; ++i) {
+ idxs.emplace_back(new MockIndex(1));
+ }
+
+ auto fn = [](int i, MockIndex* index) {
+ if (i < 2) {
+ throw TestException();
+ } else {
+ std::this_thread::sleep_for(std::chrono::milliseconds(i * 250));
+
+ index->flag = true;
+ }
+ };
+
+ // Try with threading and without
+ for (bool threaded : {true, false}) {
+ // clear flags
+ for (auto& idx : idxs) {
+ idx->resetMock();
+ }
+
+ MockThreadedIndex<MockIndex> ti(threaded);
+ for (auto& idx : idxs) {
+ ti.addIndex(idx.get());
+ }
+
+ // Multiple indices threw an exception that was aggregated into a
+ // FaissException
+ EXPECT_THROW(ti.runOnIndex(fn), faiss::FaissException);
+
+ // Index 2 should have processed
+ EXPECT_TRUE(idxs[2]->flag);
+ }
+}
+
+TEST(ThreadedIndex, TestReplica) {
+ int numReplicas = 5;
+ int n = 10 * numReplicas;
+ int d = 3;
+ int k = 6;
+
+ // Try with threading and without
+ for ([[maybe_unused]] const bool threaded : {true, false}) {
+ std::vector<std::unique_ptr<MockIndex>> idxs;
+ faiss::IndexReplicas replica(d);
+
+ for (int i = 0; i < numReplicas; ++i) {
+ idxs.emplace_back(new MockIndex(d));
+ replica.addIndex(idxs.back().get());
+ }
+
+ std::vector<float> x(n * d);
+ std::vector<float> distances(n * k);
+ std::vector<faiss::idx_t> labels(n * k);
+
+ replica.add(n, x.data());
+
+ for (int i = 0; i < idxs.size(); ++i) {
+ EXPECT_EQ(idxs[i]->nCalled, n);
+ EXPECT_EQ(idxs[i]->xCalled, x.data());
+ }
+
+ for (auto& idx : idxs) {
+ idx->resetMock();
+ }
+
+ replica.search(n, x.data(), k, distances.data(), labels.data());
+
+ for (int i = 0; i < idxs.size(); ++i) {
+ auto perReplica = n / idxs.size();
+
+ EXPECT_EQ(idxs[i]->nCalled, perReplica);
+ EXPECT_EQ(idxs[i]->xCalled, x.data() + i * perReplica * d);
+ EXPECT_EQ(idxs[i]->kCalled, k);
+ EXPECT_EQ(
+ idxs[i]->distancesCalled,
+ distances.data() + (i * perReplica) * k);
+ EXPECT_EQ(
+ idxs[i]->labelsCalled,
+ labels.data() + (i * perReplica) * k);
+ }
+ }
+}
+
+TEST(ThreadedIndex, TestShards) {
+ int numShards = 7;
+ int d = 3;
+ int n = 10 * numShards;
+ int k = 6;
+
+ // Try with threading and without
+ for (bool threaded : {true, false}) {
+ std::vector<std::unique_ptr<MockIndex>> idxs;
+ faiss::IndexShards shards(d, threaded);
+
+ for (int i = 0; i < numShards; ++i) {
+ idxs.emplace_back(new MockIndex(d));
+ shards.addIndex(idxs.back().get());
+ }
+
+ std::vector<float> x(n * d);
+ std::vector<float> distances(n * k);
+ std::vector<faiss::idx_t> labels(n * k);
+
+ shards.add(n, x.data());
+
+ for (int i = 0; i < idxs.size(); ++i) {
+ auto perShard = n / idxs.size();
+
+ EXPECT_EQ(idxs[i]->nCalled, perShard);
+ EXPECT_EQ(idxs[i]->xCalled, x.data() + i * perShard * d);
+ }
+
+ for (auto& idx : idxs) {
+ idx->resetMock();
+ }
+
+ shards.search(n, x.data(), k, distances.data(), labels.data());
+
+ for (int i = 0; i < idxs.size(); ++i) {
+ EXPECT_EQ(idxs[i]->nCalled, n);
+ EXPECT_EQ(idxs[i]->xCalled, x.data());
+ EXPECT_EQ(idxs[i]->kCalled, k);
+ // There is a temporary buffer used for shards
+ EXPECT_EQ(
+ idxs[i]->distancesCalled,
+ idxs[0]->distancesCalled + i * k * n);
+ EXPECT_EQ(idxs[i]->labelsCalled, idxs[0]->labelsCalled + i * k * n);
+ }
+ }
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_transfer_invlists.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_transfer_invlists.cpp
new file mode 100644
index 0000000..f275eb6
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_transfer_invlists.cpp
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <memory>
+
+#include <gtest/gtest.h>
+
+#include <faiss/AutoTune.h>
+#include <faiss/IVFlib.h>
+#include <faiss/IndexIVFFlat.h>
+#include <faiss/clone_index.h>
+#include <faiss/impl/io.h>
+#include <faiss/index_factory.h>
+#include <faiss/index_io.h>
+#include <faiss/utils/random.h>
+
+namespace {
+
+// parameters to use for the test
+int d = 64;
+size_t nb = 1000;
+size_t nq = 100;
+size_t nt = 500;
+int k = 10;
+int nlist = 40;
+
+using namespace faiss;
+
+typedef faiss::idx_t idx_t;
+
+std::vector<float> get_data(size_t nb, int seed) {
+ std::vector<float> x(nb * d);
+ float_randn(x.data(), nb * d, seed);
+ return x;
+}
+
+void test_index_type(const char* factory_string) {
+ // transfer inverted lists in nslice slices
+ int nslice = 3;
+
+ /****************************************************************
+ * trained reference index
+ ****************************************************************/
+
+ std::unique_ptr<Index> trained(index_factory(d, factory_string));
+
+ {
+ auto xt = get_data(nt, 123);
+ trained->train(nt, xt.data());
+ }
+
+ // sample nq query vectors to check if results are the same
+ auto xq = get_data(nq, 818);
+
+ /****************************************************************
+ * source index
+ ***************************************************************/
+ std::unique_ptr<Index> src_index(clone_index(trained.get()));
+
+ { // add some data to source index
+ auto xb = get_data(nb, 245);
+ src_index->add(nb, xb.data());
+ }
+
+ ParameterSpace().set_index_parameter(src_index.get(), "nprobe", 4);
+
+ // remember reference search result on source index
+ std::vector<idx_t> Iref(nq * k);
+ std::vector<float> Dref(nq * k);
+ src_index->search(nq, xq.data(), k, Dref.data(), Iref.data());
+
+ /****************************************************************
+ * destination index -- should be replaced by source index
+ ***************************************************************/
+
+ std::unique_ptr<Index> dst_index(clone_index(trained.get()));
+
+ { // initial state: filled in with some garbage
+ int nb2 = nb + 10;
+ auto xb = get_data(nb2, 366);
+ dst_index->add(nb2, xb.data());
+ }
+
+ std::vector<idx_t> Inew(nq * k);
+ std::vector<float> Dnew(nq * k);
+
+ ParameterSpace().set_index_parameter(dst_index.get(), "nprobe", 4);
+
+ // transfer from source to destination in nslice slices
+ for (int sl = 0; sl < nslice; sl++) {
+ // so far, the indexes are different
+ dst_index->search(nq, xq.data(), k, Dnew.data(), Inew.data());
+ EXPECT_TRUE(Iref != Inew);
+ EXPECT_TRUE(Dref != Dnew);
+
+ // range of inverted list indices to transfer
+ long i0 = sl * nlist / nslice;
+ long i1 = (sl + 1) * nlist / nslice;
+
+ std::vector<uint8_t> data_to_transfer;
+ {
+ std::unique_ptr<ArrayInvertedLists> il(
+ ivflib::get_invlist_range(src_index.get(), i0, i1));
+ // serialize inverted lists
+ VectorIOWriter wr;
+ write_InvertedLists(il.get(), &wr);
+ data_to_transfer.swap(wr.data);
+ }
+
+ // transfer data here from source machine to dest machine
+
+ {
+ VectorIOReader reader;
+ reader.data.swap(data_to_transfer);
+
+ // deserialize inverted lists
+ std::unique_ptr<ArrayInvertedLists> il(
+ dynamic_cast<ArrayInvertedLists*>(
+ read_InvertedLists(&reader)));
+
+ // swap inverted lists. Block searches here!
+ { ivflib::set_invlist_range(dst_index.get(), i0, i1, il.get()); }
+ }
+ }
+ EXPECT_EQ(dst_index->ntotal, src_index->ntotal);
+
+ // now, the indexes are the same
+ dst_index->search(nq, xq.data(), k, Dnew.data(), Inew.data());
+ EXPECT_TRUE(Iref == Inew);
+ EXPECT_TRUE(Dref == Dnew);
+}
+
+} // namespace
+
+TEST(TRANS, IVFFlat) {
+ test_index_type("IVF40,Flat");
+}
+
+TEST(TRANS, IVFFlatPreproc) {
+ test_index_type("PCAR32,IVF40,Flat");
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_util.h b/packages/leann-backend-hnsw/third_party/faiss/tests/test_util.h
new file mode 100644
index 0000000..75ff9af
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_util.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#ifndef FAISS_TEST_UTIL_H
+#define FAISS_TEST_UTIL_H
+
+#include <faiss/IndexIVFPQ.h>
+#include <unistd.h>
+
+struct Tempfilename {
+ pthread_mutex_t* mutex;
+ std::string filename;
+
+ Tempfilename(pthread_mutex_t* mutex, std::string filename_template) {
+ this->mutex = mutex;
+ this->filename = filename_template;
+ pthread_mutex_lock(mutex);
+ int fd = mkstemp(&this->filename[0]);
+ close(fd);
+ pthread_mutex_unlock(mutex);
+ }
+
+ ~Tempfilename() {
+ if (access(filename.c_str(), F_OK)) {
+ unlink(filename.c_str());
+ }
+ }
+
+ const char* c_str() {
+ return filename.c_str();
+ }
+};
+
+#endif // FAISS_TEST_UTIL_H
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_utils.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_utils.cpp
new file mode 100644
index 0000000..f297c79
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_utils.cpp
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <faiss/Index.h>
+#include <faiss/utils/utils.h>
+
+TEST(TestUtils, get_version) {
+ std::string version = std::to_string(FAISS_VERSION_MAJOR) + "." +
+ std::to_string(FAISS_VERSION_MINOR) + "." +
+ std::to_string(FAISS_VERSION_PATCH);
+
+ EXPECT_EQ(version, faiss::get_version());
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/test_zerocopy.cpp b/packages/leann-backend-hnsw/third_party/faiss/tests/test_zerocopy.cpp
new file mode 100644
index 0000000..9b8734b
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/test_zerocopy.cpp
@@ -0,0 +1,243 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <gtest/gtest.h>
+
+#include <cstddef>
+#include <cstdint>
+#include <random>
+#include <vector>
+
+#include <faiss/IndexBinaryFlat.h>
+#include <faiss/IndexFlat.h>
+#include <faiss/impl/io.h>
+#include <faiss/impl/zerocopy_io.h>
+#include <faiss/index_io.h>
+
+namespace {
+
+std::vector<float> make_data(const size_t n, const size_t d, size_t seed) {
+ std::vector<float> database(n * d);
+ std::mt19937 rng(seed);
+ std::uniform_real_distribution<float> distrib;
+
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+std::vector<uint8_t> make_binary_data(
+ const size_t n,
+ const size_t d,
+ size_t seed) {
+ std::vector<uint8_t> database(n * d);
+ std::mt19937 rng(seed);
+ std::uniform_int_distribution<uint8_t> distrib(0, 255);
+
+ for (size_t i = 0; i < n * d; i++) {
+ database[i] = distrib(rng);
+ }
+ return database;
+}
+
+} // namespace
+
+// the logic is the following:
+// 1. generate two flatcodes-based indices, Index1 and Index2
+// 2. serialize both indices into std::vector<> buffers, Buf1 and Buf2
+// 3. deserialize Index1 using zero-copy feature on Buf1 into Index1ZC
+// 4. ensure that Index1ZC acts as Index2 if we write the data from Buf2
+// on top of the existing Buf1
+
+TEST(TestZeroCopy, zerocopy_flatcodes) {
+ // generate data
+ const size_t nt = 1000;
+ const size_t nq = 10;
+ const size_t d = 32;
+ const size_t k = 25;
+
+ std::vector<float> xt1 = make_data(nt, d, 123);
+ std::vector<float> xt2 = make_data(nt, d, 456);
+ std::vector<float> xq = make_data(nq, d, 789);
+
+ // ensure that the data is different
+ ASSERT_NE(xt1, xt2);
+
+ // make index1 and create reference results
+ faiss::IndexFlatL2 index1(d);
+ index1.train(nt, xt1.data());
+ index1.add(nt, xt1.data());
+
+ std::vector<float> ref_dis_1(k * nq);
+ std::vector<faiss::idx_t> ref_ids_1(k * nq);
+ index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data());
+
+ // make index2 and create reference results
+ faiss::IndexFlatL2 index2(d);
+ index2.train(nt, xt2.data());
+ index2.add(nt, xt2.data());
+
+ std::vector<float> ref_dis_2(k * nq);
+ std::vector<faiss::idx_t> ref_ids_2(k * nq);
+ index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data());
+
+ // ensure that the results are different
+ ASSERT_NE(ref_dis_1, ref_dis_2);
+ ASSERT_NE(ref_ids_1, ref_ids_2);
+
+ // serialize both in a form of vectors
+ faiss::VectorIOWriter wr1;
+ faiss::write_index(&index1, &wr1);
+
+ faiss::VectorIOWriter wr2;
+ faiss::write_index(&index2, &wr2);
+
+ ASSERT_EQ(wr1.data.size(), wr2.data.size());
+
+ // clone a buffer
+ std::vector<uint8_t> buffer = wr1.data;
+
+ // create a zero-copy index
+ faiss::ZeroCopyIOReader reader(buffer.data(), buffer.size());
+ std::unique_ptr<faiss::Index> index1zc(faiss::read_index(&reader));
+
+ ASSERT_NE(index1zc, nullptr);
+
+ // perform a search
+ std::vector<float> cand_dis_1(k * nq);
+ std::vector<faiss::idx_t> cand_ids_1(k * nq);
+ index1zc->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_1);
+ ASSERT_EQ(ref_dis_1, cand_dis_1);
+
+ // overwrite buffer without moving it
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = wr2.data[i];
+ }
+
+ // perform a search
+ std::vector<float> cand_dis_2(k * nq);
+ std::vector<faiss::idx_t> cand_ids_2(k * nq);
+ index1zc->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data());
+
+ // match vs ref2
+ ASSERT_EQ(ref_ids_2, cand_ids_2);
+ ASSERT_EQ(ref_dis_2, cand_dis_2);
+
+ // overwrite again
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = wr1.data[i];
+ }
+
+ // perform a search
+ std::vector<float> cand_dis_3(k * nq);
+ std::vector<faiss::idx_t> cand_ids_3(k * nq);
+ index1zc->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_3);
+ ASSERT_EQ(ref_dis_1, cand_dis_3);
+}
+
+TEST(TestZeroCopy, zerocopy_binary_flatcodes) {
+ // generate data
+ const size_t nt = 1000;
+ const size_t nq = 10;
+ // in bits
+ const size_t d = 64;
+ // in bytes
+ const size_t d8 = (d + 7) / 8;
+ const size_t k = 25;
+
+ std::vector<uint8_t> xt1 = make_binary_data(nt, d8, 123);
+ std::vector<uint8_t> xt2 = make_binary_data(nt, d8, 456);
+ std::vector<uint8_t> xq = make_binary_data(nq, d8, 789);
+
+ // ensure that the data is different
+ ASSERT_NE(xt1, xt2);
+
+ // make index1 and create reference results
+ faiss::IndexBinaryFlat index1(d);
+ index1.train(nt, xt1.data());
+ index1.add(nt, xt1.data());
+
+ std::vector<int32_t> ref_dis_1(k * nq);
+ std::vector<faiss::idx_t> ref_ids_1(k * nq);
+ index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data());
+
+ // make index2 and create reference results
+ faiss::IndexBinaryFlat index2(d);
+ index2.train(nt, xt2.data());
+ index2.add(nt, xt2.data());
+
+ std::vector<int32_t> ref_dis_2(k * nq);
+ std::vector<faiss::idx_t> ref_ids_2(k * nq);
+ index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data());
+
+ // ensure that the results are different
+ ASSERT_NE(ref_dis_1, ref_dis_2);
+ ASSERT_NE(ref_ids_1, ref_ids_2);
+
+ // serialize both in a form of vectors
+ faiss::VectorIOWriter wr1;
+ faiss::write_index_binary(&index1, &wr1);
+
+ faiss::VectorIOWriter wr2;
+ faiss::write_index_binary(&index2, &wr2);
+
+ ASSERT_EQ(wr1.data.size(), wr2.data.size());
+
+ // clone a buffer
+ std::vector<uint8_t> buffer = wr1.data;
+
+ // create a zero-copy index
+ faiss::ZeroCopyIOReader reader(buffer.data(), buffer.size());
+ std::unique_ptr<faiss::IndexBinary> index1zc(
+ faiss::read_index_binary(&reader));
+
+ ASSERT_NE(index1zc, nullptr);
+
+ // perform a search
+ std::vector<int32_t> cand_dis_1(k * nq);
+ std::vector<faiss::idx_t> cand_ids_1(k * nq);
+ index1zc->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_1);
+ ASSERT_EQ(ref_dis_1, cand_dis_1);
+
+ // overwrite buffer without moving it
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = wr2.data[i];
+ }
+
+ // perform a search
+ std::vector<int32_t> cand_dis_2(k * nq);
+ std::vector<faiss::idx_t> cand_ids_2(k * nq);
+ index1zc->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data());
+
+ // match vs ref2
+ ASSERT_EQ(ref_ids_2, cand_ids_2);
+ ASSERT_EQ(ref_dis_2, cand_dis_2);
+
+ // overwrite again
+ for (size_t i = 0; i < buffer.size(); i++) {
+ buffer[i] = wr1.data[i];
+ }
+
+ // perform a search
+ std::vector<int32_t> cand_dis_3(k * nq);
+ std::vector<faiss::idx_t> cand_ids_3(k * nq);
+ index1zc->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data());
+
+ // match vs ref1
+ ASSERT_EQ(ref_ids_1, cand_ids_3);
+ ASSERT_EQ(ref_dis_1, cand_dis_3);
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/torch_test_contrib.py b/packages/leann-backend-hnsw/third_party/faiss/tests/torch_test_contrib.py
new file mode 100644
index 0000000..3eb6c6c
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/torch_test_contrib.py
@@ -0,0 +1,427 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch # usort: skip
+import unittest # usort: skip
+import numpy as np # usort: skip
+
+import faiss # usort: skip
+import faiss.contrib.torch_utils # usort: skip
+from faiss.contrib import datasets
+from faiss.contrib.torch import clustering, quantization
+
+
+
+
+class TestTorchUtilsCPU(unittest.TestCase):
+ # tests add, search
+ def test_lookup(self):
+ d = 128
+ index = faiss.IndexFlatL2(d)
+
+ # Add to CPU index with torch CPU
+ xb_torch = torch.rand(10000, d)
+ index.add(xb_torch)
+
+ # Test reconstruct
+ y_torch = index.reconstruct(10)
+ self.assertTrue(torch.equal(y_torch, xb_torch[10]))
+
+ # Add to CPU index with numpy CPU
+ xb_np = torch.rand(500, d).numpy()
+ index.add(xb_np)
+ self.assertEqual(index.ntotal, 10500)
+
+ y_np = np.zeros(d, dtype=np.float32)
+ index.reconstruct(10100, y_np)
+ self.assertTrue(np.array_equal(y_np, xb_np[100]))
+
+ # Search with np cpu
+ xq_torch = torch.rand(10, d, dtype=torch.float32)
+ d_np, I_np = index.search(xq_torch.numpy(), 5)
+
+ # Search with torch cpu
+ d_torch, I_torch = index.search(xq_torch, 5)
+
+ # The two should be equivalent
+ self.assertTrue(np.array_equal(d_np, d_torch.numpy()))
+ self.assertTrue(np.array_equal(I_np, I_torch.numpy()))
+
+ # Search with np cpu using pre-allocated arrays
+ d_np_input = np.zeros((10, 5), dtype=np.float32)
+ I_np_input = np.zeros((10, 5), dtype=np.int64)
+ index.search(xq_torch.numpy(), 5, d_np_input, I_np_input)
+
+ self.assertTrue(np.array_equal(d_np, d_np_input))
+ self.assertTrue(np.array_equal(I_np, I_np_input))
+
+ # Search with torch cpu using pre-allocated arrays
+ d_torch_input = torch.zeros(10, 5, dtype=torch.float32)
+ I_torch_input = torch.zeros(10, 5, dtype=torch.int64)
+ index.search(xq_torch, 5, d_torch_input, I_torch_input)
+
+ self.assertTrue(np.array_equal(d_torch_input.numpy(), d_np))
+ self.assertTrue(np.array_equal(I_torch_input.numpy(), I_np))
+
+ # tests train, add_with_ids
+ def test_train_add_with_ids(self):
+ d = 32
+ nlist = 5
+
+ quantizer = faiss.IndexFlatL2(d)
+ index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
+ xb = torch.rand(1000, d, dtype=torch.float32)
+ index.train(xb)
+
+ # Test add_with_ids with torch cpu
+ ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64)
+ index.add_with_ids(xb, ids)
+ _, I = index.search(xb[10:20], 1)
+ self.assertTrue(torch.equal(I.view(10), ids[10:20]))
+
+ # Test add_with_ids with numpy
+ index.reset()
+ index.train(xb.numpy())
+ index.add_with_ids(xb.numpy(), ids.numpy())
+ _, I = index.search(xb.numpy()[10:20], 1)
+ self.assertTrue(np.array_equal(I.reshape(10), ids.numpy()[10:20]))
+
+ # tests reconstruct, reconstruct_n
+ def test_reconstruct(self):
+ d = 32
+ index = faiss.IndexFlatL2(d)
+
+ xb = torch.rand(100, d, dtype=torch.float32)
+ index.add(xb)
+
+ # Test reconstruct with torch cpu (native return)
+ y = index.reconstruct(7)
+ self.assertTrue(torch.equal(xb[7], y))
+
+ # Test reconstruct with numpy output provided
+ y = np.empty(d, dtype=np.float32)
+ index.reconstruct(11, y)
+ self.assertTrue(np.array_equal(xb.numpy()[11], y))
+
+ # Test reconstruct with torch cpu output providesd
+ y = torch.empty(d, dtype=torch.float32)
+ index.reconstruct(12, y)
+ self.assertTrue(torch.equal(xb[12], y))
+
+ # Test reconstruct_n with torch cpu (native return)
+ y = index.reconstruct_n(10, 10)
+ self.assertTrue(torch.equal(xb[10:20], y))
+
+ # Test reconstruct with numpy output provided
+ y = np.empty((10, d), dtype=np.float32)
+ index.reconstruct_n(20, 10, y)
+ self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y))
+
+ # Test reconstruct_n with torch cpu output provided
+ y = torch.empty(10, d, dtype=torch.float32)
+ index.reconstruct_n(40, 10, y)
+ self.assertTrue(torch.equal(xb[40:50].cpu(), y))
+
+ # tests assign
+ def test_assign(self):
+ d = 32
+ index = faiss.IndexFlatL2(d)
+ xb = torch.rand(1000, d, dtype=torch.float32)
+ index.add(xb)
+
+ index_ref = faiss.IndexFlatL2(d)
+ index_ref.add(xb.numpy())
+
+ # Test assign with native cpu output
+ xq = torch.rand(10, d, dtype=torch.float32)
+ labels = index.assign(xq, 5)
+ labels_ref = index_ref.assign(xq.cpu(), 5)
+
+ self.assertTrue(torch.equal(labels, labels_ref))
+
+ # Test assign with np input
+ labels = index.assign(xq.numpy(), 5)
+ labels_ref = index_ref.assign(xq.numpy(), 5)
+ self.assertTrue(np.array_equal(labels, labels_ref))
+
+ # Test assign with numpy output provided
+ labels = np.empty((xq.shape[0], 5), dtype='int64')
+ index.assign(xq.numpy(), 5, labels)
+ self.assertTrue(np.array_equal(labels, labels_ref))
+
+ # Test assign with torch cpu output provided
+ labels = torch.empty(xq.shape[0], 5, dtype=torch.int64)
+ index.assign(xq, 5, labels)
+ labels_ref = index_ref.assign(xq, 5)
+ self.assertTrue(torch.equal(labels, labels_ref))
+
+ # tests remove_ids
+ def test_remove_ids(self):
+ # only implemented for cpu index + numpy at the moment
+ d = 32
+ quantizer = faiss.IndexFlatL2(d)
+ index = faiss.IndexIVFFlat(quantizer, d, 5)
+ index.make_direct_map()
+ index.set_direct_map_type(faiss.DirectMap.Hashtable)
+
+ xb = torch.rand(1000, d, dtype=torch.float32)
+ ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64)
+ index.train(xb)
+ index.add_with_ids(xb, ids)
+
+ ids_remove = np.array([1010], dtype=np.int64)
+ index.remove_ids(ids_remove)
+
+ # We should find this
+ y = index.reconstruct(1011)
+ self.assertTrue(np.array_equal(xb[11].numpy(), y))
+
+ # We should not find this
+ with self.assertRaises(RuntimeError):
+ y = index.reconstruct(1010)
+
+ # Torch not yet supported
+ ids_remove = torch.tensor([1012], dtype=torch.int64)
+ with self.assertRaises(AssertionError):
+ index.remove_ids(ids_remove)
+
+ # tests update_vectors
+ def test_update_vectors(self):
+ d = 32
+ quantizer_np = faiss.IndexFlatL2(d)
+ index_np = faiss.IndexIVFFlat(quantizer_np, d, 5)
+ index_np.make_direct_map()
+ index_np.set_direct_map_type(faiss.DirectMap.Hashtable)
+
+ quantizer_torch = faiss.IndexFlatL2(d)
+ index_torch = faiss.IndexIVFFlat(quantizer_torch, d, 5)
+ index_torch.make_direct_map()
+ index_torch.set_direct_map_type(faiss.DirectMap.Hashtable)
+
+ xb = torch.rand(1000, d, dtype=torch.float32)
+ ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64)
+
+ index_np.train(xb.numpy())
+ index_np.add_with_ids(xb.numpy(), ids.numpy())
+
+ index_torch.train(xb)
+ index_torch.add_with_ids(xb, ids)
+
+ xb_up = torch.rand(10, d, dtype=torch.float32)
+ ids_up = ids[0:10]
+
+ index_np.update_vectors(ids_up.numpy(), xb_up.numpy())
+ index_torch.update_vectors(ids_up, xb_up)
+
+ xq = torch.rand(10, d, dtype=torch.float32)
+
+ D_np, I_np = index_np.search(xq.numpy(), 5)
+ D_torch, I_torch = index_torch.search(xq, 5)
+
+ self.assertTrue(np.array_equal(D_np, D_torch.numpy()))
+ self.assertTrue(np.array_equal(I_np, I_torch.numpy()))
+
+ # tests range_search
+ def test_range_search(self):
+ torch.manual_seed(10)
+ d = 32
+ index = faiss.IndexFlatL2(d)
+ xb = torch.rand(100, d, dtype=torch.float32)
+ index.add(xb)
+
+ # torch cpu as ground truth
+ thresh = 2.9
+ xq = torch.rand(10, d, dtype=torch.float32)
+ lims, D, I = index.range_search(xq, thresh)
+
+ # compare against np
+ lims_np, D_np, I_np = index.range_search(xq.numpy(), thresh)
+
+ self.assertTrue(np.array_equal(lims.numpy(), lims_np))
+ self.assertTrue(np.array_equal(D.numpy(), D_np))
+ self.assertTrue(np.array_equal(I.numpy(), I_np))
+
+ # tests search_and_reconstruct
+ def test_search_and_reconstruct(self):
+ d = 32
+ nlist = 10
+ M = 4
+ k = 5
+ quantizer = faiss.IndexFlatL2(d)
+ index = faiss.IndexIVFPQ(quantizer, d, nlist, M, 4)
+
+ xb = torch.rand(1000, d, dtype=torch.float32)
+ index.train(xb)
+
+ # different set
+ xb = torch.rand(500, d, dtype=torch.float32)
+ index.add(xb)
+
+ # torch cpu as ground truth
+ xq = torch.rand(10, d, dtype=torch.float32)
+ D, I, R = index.search_and_reconstruct(xq, k)
+
+ # compare against numpy
+ D_np, I_np, R_np = index.search_and_reconstruct(xq.numpy(), k)
+
+ self.assertTrue(np.array_equal(D.numpy(), D_np))
+ self.assertTrue(np.array_equal(I.numpy(), I_np))
+ self.assertTrue(np.array_equal(R.numpy(), R_np))
+
+ # numpy input values
+ D_input = np.zeros((xq.shape[0], k), dtype=np.float32)
+ I_input = np.zeros((xq.shape[0], k), dtype=np.int64)
+ R_input = np.zeros((xq.shape[0], k, d), dtype=np.float32)
+
+ index.search_and_reconstruct(xq.numpy(), k, D_input, I_input, R_input)
+
+ self.assertTrue(np.array_equal(D.numpy(), D_input))
+ self.assertTrue(np.array_equal(I.numpy(), I_input))
+ self.assertTrue(np.array_equal(R.numpy(), R_input))
+
+ # torch input values
+ D_input = torch.zeros(xq.shape[0], k, dtype=torch.float32)
+ I_input = torch.zeros(xq.shape[0], k, dtype=torch.int64)
+ R_input = torch.zeros(xq.shape[0], k, d, dtype=torch.float32)
+
+ index.search_and_reconstruct(xq, k, D_input, I_input, R_input)
+
+ self.assertTrue(torch.equal(D, D_input))
+ self.assertTrue(torch.equal(I, I_input))
+ self.assertTrue(torch.equal(R, R_input))
+
+ def test_search_preassigned(self):
+ ds = datasets.SyntheticDataset(32, 1000, 100, 10)
+ index = faiss.index_factory(32, "IVF20,PQ4np")
+ index.train(ds.get_train())
+ index.add(ds.get_database())
+ index.nprobe = 4
+ Dref, Iref = index.search(ds.get_queries(), 10)
+ quantizer = faiss.clone_index(index.quantizer)
+
+ # mutilate the index' quantizer
+ index.quantizer.reset()
+ index.quantizer.add(np.zeros((20, 32), dtype='float32'))
+
+ # test numpy codepath
+ Dq, Iq = quantizer.search(ds.get_queries(), 4)
+ Dref2, Iref2 = index.search_preassigned(ds.get_queries(), 10, Iq, Dq)
+ np.testing.assert_array_equal(Iref, Iref2)
+ np.testing.assert_array_equal(Dref, Dref2)
+
+ # test torch codepath
+ xq = torch.from_numpy(ds.get_queries())
+ Dq, Iq = quantizer.search(xq, 4)
+ Dref2, Iref2 = index.search_preassigned(xq, 10, Iq, Dq)
+ np.testing.assert_array_equal(Iref, Iref2.numpy())
+ np.testing.assert_array_equal(Dref, Dref2.numpy())
+
+ # tests sa_encode, sa_decode
+ def test_sa_encode_decode(self):
+ d = 16
+ index = faiss.IndexScalarQuantizer(d, faiss.ScalarQuantizer.QT_8bit)
+
+ xb = torch.rand(1000, d, dtype=torch.float32)
+ index.train(xb)
+
+ # torch cpu as ground truth
+ nq = 10
+ xq = torch.rand(nq, d, dtype=torch.float32)
+ encoded_torch = index.sa_encode(xq)
+
+ # numpy cpu
+ encoded_np = index.sa_encode(xq.numpy())
+
+ self.assertTrue(np.array_equal(encoded_torch.numpy(), encoded_np))
+
+ decoded_torch = index.sa_decode(encoded_torch)
+ decoded_np = index.sa_decode(encoded_np)
+
+ self.assertTrue(torch.equal(decoded_torch, torch.from_numpy(decoded_np)))
+
+ # torch cpu as output parameter
+ encoded_torch_param = torch.zeros(nq, d, dtype=torch.uint8)
+ index.sa_encode(xq, encoded_torch_param)
+
+ self.assertTrue(torch.equal(encoded_torch, encoded_torch))
+
+ decoded_torch_param = torch.zeros(nq, d, dtype=torch.float32)
+ index.sa_decode(encoded_torch, decoded_torch_param)
+
+ self.assertTrue(torch.equal(decoded_torch, decoded_torch_param))
+
+ # np as output parameter
+ encoded_np_param = np.zeros((nq, d), dtype=np.uint8)
+ index.sa_encode(xq.numpy(), encoded_np_param)
+
+ self.assertTrue(np.array_equal(encoded_torch.numpy(), encoded_np_param))
+
+ decoded_np_param = np.zeros((nq, d), dtype=np.float32)
+ index.sa_decode(encoded_np_param, decoded_np_param)
+
+ self.assertTrue(np.array_equal(decoded_np, decoded_np_param))
+
+ def test_non_contiguous(self):
+ d = 128
+ index = faiss.IndexFlatL2(d)
+
+ xb = torch.rand(d, 100).transpose(0, 1)
+
+ with self.assertRaises(AssertionError):
+ index.add(xb)
+
+ # disabled since we now accept non-contiguous arrays
+ # with self.assertRaises(ValueError):
+ # index.add(xb.numpy())
+
+
+class TestClustering(unittest.TestCase):
+
+ def test_python_kmeans(self):
+ """ Test the python implementation of kmeans """
+ ds = datasets.SyntheticDataset(32, 10000, 0, 0)
+ x = ds.get_train()
+
+ # bad distribution to stress-test split code
+ xt = x[:10000].copy()
+ xt[:5000] = x[0]
+
+ km_ref = faiss.Kmeans(ds.d, 100, niter=10)
+ km_ref.train(xt)
+ err = faiss.knn(xt, km_ref.centroids, 1)[0].sum()
+
+ xt_torch = torch.from_numpy(xt)
+ data = clustering.DatasetAssign(xt_torch)
+ centroids = clustering.kmeans(100, data, 10)
+ centroids = centroids.numpy()
+ err2 = faiss.knn(xt, centroids, 1)[0].sum()
+
+ # 33498.332 33380.477
+ # print(err, err2) 1/0
+ self.assertLess(err2, err * 1.1)
+
+
+class TestQuantization(unittest.TestCase):
+ def test_python_product_quantization(self):
+ """ Test the python implementation of product quantization """
+ d = 64
+ n = 10000
+ cs = 4
+ nbits = 8
+ M = 4
+ x = np.random.random(size=(n, d)).astype('float32')
+ pq = faiss.ProductQuantizer(d, cs, nbits)
+ pq.train(x)
+ codes = pq.compute_codes(x)
+ x2 = pq.decode(codes)
+ diff = ((x - x2)**2).sum()
+ # vs pure pytorch impl
+ xt = torch.from_numpy(x)
+ my_pq = quantization.ProductQuantizer(d, M, nbits)
+ my_pq.train(xt)
+ my_codes = my_pq.encode(xt)
+ xt2 = my_pq.decode(my_codes)
+ my_diff = ((xt - xt2)**2).sum()
+ self.assertLess(abs(diff - my_diff), 100)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tests/torch_test_neural_net.py b/packages/leann-backend-hnsw/third_party/faiss/tests/torch_test_neural_net.py
new file mode 100644
index 0000000..0958b26
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tests/torch_test_neural_net.py
@@ -0,0 +1,374 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch # usort: skip
+from torch import nn # usort: skip
+import unittest # usort: skip
+import numpy as np # usort: skip
+
+import faiss # usort: skip
+
+from faiss.contrib import datasets # usort: skip
+from faiss.contrib.inspect_tools import get_additive_quantizer_codebooks # usort: skip
+
+
+class TestLayer(unittest.TestCase):
+
+ @torch.no_grad()
+ def test_Embedding(self):
+ """ verify that the Faiss Embedding works the same as in Pytorch """
+ torch.manual_seed(123)
+
+ emb = nn.Embedding(40, 50)
+ idx = torch.randint(40, (25, ))
+ ref_batch = emb(idx)
+
+ emb2 = faiss.Embedding(emb)
+ idx2 = faiss.Int32Tensor2D(idx[:, None].to(dtype=torch.int32))
+ new_batch = emb2(idx2)
+
+ new_batch = new_batch.numpy()
+ np.testing.assert_allclose(ref_batch.numpy(), new_batch, atol=2e-6)
+
+ @torch.no_grad()
+ def do_test_Linear(self, bias):
+ """ verify that the Faiss Linear works the same as in Pytorch """
+ torch.manual_seed(123)
+ linear = nn.Linear(50, 40, bias=bias)
+ x = torch.randn(25, 50)
+ ref_y = linear(x)
+
+ linear2 = faiss.Linear(linear)
+ x2 = faiss.Tensor2D(x)
+ y = linear2(x2)
+ np.testing.assert_allclose(ref_y.numpy(), y.numpy(), atol=2e-6)
+
+ def test_Linear(self):
+ self.do_test_Linear(True)
+
+ def test_Linear_nobias(self):
+ self.do_test_Linear(False)
+
+######################################################
+# QINCo Pytorch implementation copied from
+# https://github.com/facebookresearch/Qinco/blob/main/model_qinco.py
+#
+# The implementation is copied here to avoid introducting an additional
+# dependency.
+######################################################
+
+
+def pairwise_distances(a, b):
+ anorms = (a**2).sum(-1)
+ bnorms = (b**2).sum(-1)
+ return anorms[:, None] + bnorms - 2 * a @ b.T
+
+
+def compute_batch_distances(a, b):
+ anorms = (a**2).sum(-1)
+ bnorms = (b**2).sum(-1)
+ return (
+ anorms.unsqueeze(-1) + bnorms.unsqueeze(1) - 2 * torch.bmm(a, b.transpose(2, 1))
+ )
+
+
+def assign_batch_multiple(x, zqs):
+ bs, d = x.shape
+ bs, K, d = zqs.shape
+
+ L2distances = compute_batch_distances(x.unsqueeze(1), zqs).squeeze(1) # [bs x ksq]
+ idx = torch.argmin(L2distances, dim=1).unsqueeze(1) # [bsx1]
+ quantized = torch.gather(zqs, dim=1, index=idx.unsqueeze(-1).repeat(1, 1, d))
+ return idx.squeeze(1), quantized.squeeze(1)
+
+
+def assign_to_codebook(x, c, bs=16384):
+ nq, d = x.shape
+ nb, d2 = c.shape
+ assert d == d2
+ if nq * nb < bs * bs:
+ # small enough to represent the whole distance table
+ dis = pairwise_distances(x, c)
+ return dis.argmin(1)
+
+ # otherwise tile computation to avoid OOM
+ res = torch.empty((nq,), dtype=torch.int64, device=x.device)
+ cnorms = (c**2).sum(1)
+ for i in range(0, nq, bs):
+ xnorms = (x[i : i + bs] ** 2).sum(1, keepdim=True)
+ for j in range(0, nb, bs):
+ dis = xnorms + cnorms[j : j + bs] - 2 * x[i : i + bs] @ c[j : j + bs].T
+ dmini, imini = dis.min(1)
+ if j == 0:
+ dmin = dmini
+ imin = imini
+ else:
+ (mask,) = torch.where(dmini < dmin)
+ dmin[mask] = dmini[mask]
+ imin[mask] = imini[mask] + j
+ res[i : i + bs] = imin
+ return res
+
+
+class QINCoStep(nn.Module):
+ """
+ One quantization step for QINCo.
+ Contains the codebook, concatenation block, and residual blocks
+ """
+
+ def __init__(self, d, K, L, h):
+ nn.Module.__init__(self)
+
+ self.d, self.K, self.L, self.h = d, K, L, h
+
+ self.codebook = nn.Embedding(K, d)
+ self.MLPconcat = nn.Linear(2 * d, d)
+
+ self.residual_blocks = []
+ for l in range(L):
+ residual_block = nn.Sequential(
+ nn.Linear(d, h, bias=False), nn.ReLU(), nn.Linear(h, d, bias=False)
+ )
+ self.add_module(f"residual_block{l}", residual_block)
+ self.residual_blocks.append(residual_block)
+
+ def decode(self, xhat, codes):
+ zqs = self.codebook(codes)
+ cc = torch.concatenate((zqs, xhat), 1)
+ zqs = zqs + self.MLPconcat(cc)
+
+ for residual_block in self.residual_blocks:
+ zqs = zqs + residual_block(zqs)
+
+ return zqs
+
+ def encode(self, xhat, x):
+ # we are trying out the whole codebook
+ zqs = self.codebook.weight
+ K, d = zqs.shape
+ bs, d = xhat.shape
+
+ # repeat so that they are of size bs * K
+ zqs_r = zqs.repeat(bs, 1, 1).reshape(bs * K, d)
+ xhat_r = xhat.reshape(bs, 1, d).repeat(1, K, 1).reshape(bs * K, d)
+
+ # pass on batch of size bs * K
+ cc = torch.concatenate((zqs_r, xhat_r), 1)
+ zqs_r = zqs_r + self.MLPconcat(cc)
+
+ for residual_block in self.residual_blocks:
+ zqs_r = zqs_r + residual_block(zqs_r)
+
+ # possible next steps
+ zqs_r = zqs_r.reshape(bs, K, d) + xhat.reshape(bs, 1, d)
+ codes, xhat_next = assign_batch_multiple(x, zqs_r)
+
+ return codes, xhat_next - xhat
+
+
+class QINCo(nn.Module):
+ """
+ QINCo quantizer, built from a chain of residual quantization steps
+ """
+
+ def __init__(self, d, K, L, M, h):
+ nn.Module.__init__(self)
+
+ self.d, self.K, self.L, self.M, self.h = d, K, L, M, h
+
+ self.codebook0 = nn.Embedding(K, d)
+
+ self.steps = []
+ for m in range(1, M):
+ step = QINCoStep(d, K, L, h)
+ self.add_module(f"step{m}", step)
+ self.steps.append(step)
+
+ def decode(self, codes):
+ xhat = self.codebook0(codes[:, 0])
+ for i, step in enumerate(self.steps):
+ xhat = xhat + step.decode(xhat, codes[:, i + 1])
+ return xhat
+
+ def encode(self, x, code0=None):
+ """
+ Encode a batch of vectors x to codes of length M.
+ If this function is called from IVF-QINCo, codes are 1 index longer,
+ due to the first index being the IVF index, and codebook0 is the IVF codebook.
+ """
+ M = len(self.steps) + 1
+ bs, d = x.shape
+ codes = torch.zeros(bs, M, dtype=int, device=x.device)
+
+ if code0 is None:
+ # at IVF training time, the code0 is fixed (and precomputed)
+ code0 = assign_to_codebook(x, self.codebook0.weight)
+
+ codes[:, 0] = code0
+ xhat = self.codebook0.weight[code0]
+
+ for i, step in enumerate(self.steps):
+ codes[:, i + 1], toadd = step.encode(xhat, x)
+ xhat = xhat + toadd
+
+ return codes, xhat
+
+
+######################################################
+# QINCo tests
+######################################################
+
+def copy_QINCoStep(step):
+ step2 = faiss.QINCoStep(step.d, step.K, step.L, step.h)
+ step2.codebook.from_torch(step.codebook)
+ step2.MLPconcat.from_torch(step.MLPconcat)
+
+ for l in range(step.L):
+ src = step.residual_blocks[l]
+ dest = step2.get_residual_block(l)
+ dest.linear1.from_torch(src[0])
+ dest.linear2.from_torch(src[2])
+ return step2
+
+
+class TestQINCoStep(unittest.TestCase):
+ @torch.no_grad()
+ def test_decode(self):
+ torch.manual_seed(123)
+ step = QINCoStep(d=16, K=20, L=2, h=8)
+
+ codes = torch.randint(0, 20, (10, ))
+ xhat = torch.randn(10, 16)
+ ref_decode = step.decode(xhat, codes)
+
+ # step2 = copy_QINCoStep(step)
+ step2 = faiss.QINCoStep(step)
+ codes2 = faiss.Int32Tensor2D(codes[:, None].to(dtype=torch.int32))
+
+ np.testing.assert_array_equal(
+ step.codebook(codes).numpy(),
+ step2.codebook(codes2).numpy()
+ )
+
+ xhat2 = faiss.Tensor2D(xhat)
+ # xhat2 = faiss.Tensor2D(len(codes), step2.d)
+
+ new_decode = step2.decode(xhat2, codes2)
+
+ np.testing.assert_allclose(
+ ref_decode.numpy(),
+ new_decode.numpy(),
+ atol=2e-6
+ )
+
+ @torch.no_grad()
+ def test_encode(self):
+ torch.manual_seed(123)
+ step = QINCoStep(d=16, K=20, L=2, h=8)
+
+ # create plausible x for testing starting from actual codes
+ codes = torch.randint(0, 20, (10, ))
+ xhat = torch.zeros(10, 16)
+ x = step.decode(xhat, codes)
+ del codes
+ ref_codes, toadd = step.encode(xhat, x)
+
+ step2 = copy_QINCoStep(step)
+ xhat2 = faiss.Tensor2D(xhat)
+ x2 = faiss.Tensor2D(x)
+ toadd2 = faiss.Tensor2D(10, 16)
+
+ new_codes = step2.encode(xhat2, x2, toadd2)
+
+ np.testing.assert_allclose(
+ ref_codes.numpy(),
+ new_codes.numpy().ravel(),
+ atol=2e-6
+ )
+ np.testing.assert_allclose(toadd.numpy(), toadd2.numpy(), atol=2e-6)
+
+
+
+class TestQINCo(unittest.TestCase):
+
+ @torch.no_grad()
+ def test_decode(self):
+ torch.manual_seed(123)
+ qinco = QINCo(d=16, K=20, L=2, M=3, h=8)
+ codes = torch.randint(0, 20, (10, 3))
+ x_ref = qinco.decode(codes)
+
+ qinco2 = faiss.QINCo(qinco)
+ codes2 = faiss.Int32Tensor2D(codes.to(dtype=torch.int32))
+ x_new = qinco2.decode(codes2)
+
+ np.testing.assert_allclose(x_ref.numpy(), x_new.numpy(), atol=2e-6)
+
+ @torch.no_grad()
+ def test_encode(self):
+ torch.manual_seed(123)
+ qinco = QINCo(d=16, K=20, L=2, M=3, h=8)
+ codes = torch.randint(0, 20, (10, 3))
+ x = qinco.decode(codes)
+ del codes
+
+ ref_codes, _ = qinco.encode(x)
+
+ qinco2 = faiss.QINCo(qinco)
+ x2 = faiss.Tensor2D(x)
+
+ new_codes = qinco2.encode(x2)
+
+ np.testing.assert_allclose(ref_codes.numpy(), new_codes.numpy(), atol=2e-6)
+
+
+######################################################
+# Test index
+######################################################
+
+class TestIndexQINCo(unittest.TestCase):
+
+ def test_search(self):
+ """
+ We can't train qinco with just Faiss so we just train a RQ and use the
+ codebooks in QINCo with L = 0 residual blocks
+ """
+ ds = datasets.SyntheticDataset(32, 1000, 100, 0)
+
+ # prepare reference quantizer
+ M = 5
+ index_ref = faiss.index_factory(ds.d, "RQ5x4")
+ rq = index_ref.rq
+ # rq = faiss.ResidualQuantizer(ds.d, M, 4)
+ rq.train_type = faiss.ResidualQuantizer.Train_default
+ rq.max_beam_size = 1 # beam search not implemented for QINCo (yet)
+ index_ref.train(ds.get_train())
+ codebooks = get_additive_quantizer_codebooks(rq)
+
+ # convert to QINCo index
+ qinco_index = faiss.IndexQINCo(ds.d, M, 4, 0, ds.d)
+ qinco = qinco_index.qinco
+ qinco.codebook0.from_array(codebooks[0])
+ for i in range(1, qinco.M):
+ step = qinco.get_step(i - 1)
+ step.codebook.from_array(codebooks[i])
+ # MLPConcat left at zero -- it's added to the backbone
+ qinco_index.is_trained = True
+
+ # verify that the encoding gives the same results
+ ref_codes = rq.compute_codes(ds.get_database())
+ ref_decoded = rq.decode(ref_codes)
+ new_decoded = qinco_index.sa_decode(ref_codes)
+ np.testing.assert_allclose(ref_decoded, new_decoded, atol=2e-6)
+
+ new_codes = qinco_index.sa_encode(ds.get_database())
+ np.testing.assert_array_equal(ref_codes, new_codes)
+
+ # verify that search gives the same results
+ Dref, Iref = index_ref.search(ds.get_queries(), 5)
+ Dnew, Inew = qinco_index.search(ds.get_queries(), 5)
+
+ np.testing.assert_array_equal(Iref, Inew)
+ np.testing.assert_allclose(Dref, Dnew, atol=2e-6)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/1-Flat.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/1-Flat.cpp
new file mode 100644
index 0000000..8bdebe2
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/1-Flat.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexFlat.h>
+
+// 64-bit int
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[d * nb];
+ float* xq = new float[d * nq];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = distrib(rng);
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = distrib(rng);
+ xq[d * i] += i / 1000.;
+ }
+
+ faiss::IndexFlatL2 index(d); // call constructor
+ printf("is_trained = %s\n", index.is_trained ? "true" : "false");
+ index.add(nb, xb); // add vectors to the index
+ printf("ntotal = %zd\n", index.ntotal);
+
+ int k = 4;
+
+ { // sanity check: search 5 first vectors of xb
+ idx_t* I = new idx_t[k * 5];
+ float* D = new float[k * 5];
+
+ index.search(5, xb, k, D, I);
+
+ // print results
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5zd ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("D=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%7g ", D[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ { // search xq
+ idx_t* I = new idx_t[k * nq];
+ float* D = new float[k * nq];
+
+ index.search(nq, xq, k, D, I);
+
+ // print results
+ printf("I (5 first results)=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5zd ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("D (5 last results)=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5f ", D[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/2-IVFFlat.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/2-IVFFlat.cpp
new file mode 100644
index 0000000..1427f86
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/2-IVFFlat.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFFlat.h>
+
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[d * nb];
+ float* xq = new float[d * nq];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = distrib(rng);
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = distrib(rng);
+ xq[d * i] += i / 1000.;
+ }
+
+ int nlist = 100;
+ int k = 4;
+
+ faiss::IndexFlatL2 quantizer(d); // the other index
+ faiss::IndexIVFFlat index(&quantizer, d, nlist);
+ assert(!index.is_trained);
+ index.train(nb, xb);
+ assert(index.is_trained);
+ index.add(nb, xb);
+
+ { // search xq
+ idx_t* I = new idx_t[k * nq];
+ float* D = new float[k * nq];
+
+ index.search(nq, xq, k, D, I);
+
+ printf("I=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5zd ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("D=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5f ", D[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/3-IVFPQ.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/3-IVFPQ.cpp
new file mode 100644
index 0000000..0de05b0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/3-IVFPQ.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/IndexIVFPQ.h>
+
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[d * nb];
+ float* xq = new float[d * nq];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = distrib(rng);
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = distrib(rng);
+ xq[d * i] += i / 1000.;
+ }
+
+ int nlist = 100;
+ int k = 4;
+ int m = 8; // bytes per vector
+ faiss::IndexFlatL2 quantizer(d); // the other index
+ faiss::IndexIVFPQ index(&quantizer, d, nlist, m, 8);
+
+ index.train(nb, xb);
+ index.add(nb, xb);
+
+ { // sanity check
+ idx_t* I = new idx_t[k * 5];
+ float* D = new float[k * 5];
+
+ index.search(5, xb, k, D, I);
+
+ printf("I=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5zd ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("D=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%7g ", D[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ { // search xq
+ idx_t* I = new idx_t[k * nq];
+ float* D = new float[k * nq];
+
+ index.nprobe = 10;
+ index.search(nq, xq, k, D, I);
+
+ printf("I=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5zd ", I[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/4-GPU.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/4-GPU.cpp
new file mode 100644
index 0000000..fe623a0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/4-GPU.cpp
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/GpuIndexIVFFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[d * nb];
+ float* xq = new float[d * nq];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = distrib(rng);
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = distrib(rng);
+ xq[d * i] += i / 1000.;
+ }
+
+ faiss::gpu::StandardGpuResources res;
+
+ // Using a flat index
+
+ faiss::gpu::GpuIndexFlatL2 index_flat(&res, d);
+
+ printf("is_trained = %s\n", index_flat.is_trained ? "true" : "false");
+ index_flat.add(nb, xb); // add vectors to the index
+ printf("ntotal = %ld\n", index_flat.ntotal);
+
+ int k = 4;
+
+ { // search xq
+ long* I = new long[k * nq];
+ float* D = new float[k * nq];
+
+ index_flat.search(nq, xq, k, D, I);
+
+ // print results
+ printf("I (5 first results)=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("I (5 last results)=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld ", I[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ // Using an IVF index
+
+ int nlist = 100;
+ faiss::gpu::GpuIndexIVFFlat index_ivf(&res, d, nlist, faiss::METRIC_L2);
+
+ assert(!index_ivf.is_trained);
+ index_ivf.train(nb, xb);
+ assert(index_ivf.is_trained);
+ index_ivf.add(nb, xb); // add vectors to the index
+
+ printf("is_trained = %s\n", index_ivf.is_trained ? "true" : "false");
+ printf("ntotal = %ld\n", index_ivf.ntotal);
+
+ { // search xq
+ long* I = new long[k * nq];
+ float* D = new float[k * nq];
+
+ index_ivf.search(nq, xq, k, D, I);
+
+ // print results
+ printf("I (5 first results)=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("I (5 last results)=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld ", I[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/5-Multiple-GPUs.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/5-Multiple-GPUs.cpp
new file mode 100644
index 0000000..b381ec5
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/5-Multiple-GPUs.cpp
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexFlat.h>
+#include <faiss/gpu/GpuAutoTune.h>
+#include <faiss/gpu/GpuCloner.h>
+#include <faiss/gpu/GpuIndexFlat.h>
+#include <faiss/gpu/StandardGpuResources.h>
+#include <faiss/gpu/utils/DeviceUtils.h>
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[d * nb];
+ float* xq = new float[d * nq];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = distrib(rng);
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = distrib(rng);
+ xq[d * i] += i / 1000.;
+ }
+
+ int ngpus = faiss::gpu::getNumDevices();
+
+ printf("Number of GPUs: %d\n", ngpus);
+
+ std::vector<faiss::gpu::GpuResourcesProvider*> res;
+ std::vector<int> devs;
+ for (int i = 0; i < ngpus; i++) {
+ res.push_back(new faiss::gpu::StandardGpuResources);
+ devs.push_back(i);
+ }
+
+ faiss::IndexFlatL2 cpu_index(d);
+
+ faiss::Index* gpu_index =
+ faiss::gpu::index_cpu_to_gpu_multiple(res, devs, &cpu_index);
+
+ printf("is_trained = %s\n", gpu_index->is_trained ? "true" : "false");
+ gpu_index->add(nb, xb); // add vectors to the index
+ printf("ntotal = %ld\n", gpu_index->ntotal);
+
+ int k = 4;
+
+ { // search xq
+ long* I = new long[k * nq];
+ float* D = new float[k * nq];
+
+ gpu_index->search(nq, xq, k, D, I);
+
+ // print results
+ printf("I (5 first results)=\n");
+ for (int i = 0; i < 5; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("I (5 last results)=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5ld ", I[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete gpu_index;
+
+ for (int i = 0; i < ngpus; i++) {
+ delete res[i];
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/6-HNSW.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/6-HNSW.cpp
new file mode 100644
index 0000000..115fa53
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/6-HNSW.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexHNSW.h>
+
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[d * nb];
+ float* xq = new float[d * nq];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++)
+ xb[d * i + j] = distrib(rng);
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++)
+ xq[d * i + j] = distrib(rng);
+ xq[d * i] += i / 1000.;
+ }
+
+ int k = 4;
+
+ faiss::IndexHNSWFlat index(d, 32);
+ index.add(nb, xb);
+
+ { // search xq
+ idx_t* I = new idx_t[k * nq];
+ float* D = new float[k * nq];
+
+ index.search(nq, xq, k, D, I);
+
+ printf("I=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5zd ", I[i * k + j]);
+ printf("\n");
+ }
+
+ printf("D=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++)
+ printf("%5f ", D[i * k + j]);
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/7-PQFastScan.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/7-PQFastScan.cpp
new file mode 100644
index 0000000..3e08948
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/7-PQFastScan.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexPQFastScan.h>
+
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[(int)(d * nb)];
+ float* xq = new float[(int)(d * nq)];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++) {
+ xb[d * i + j] = distrib(rng);
+ }
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++) {
+ xq[d * i + j] = distrib(rng);
+ }
+ xq[d * i] += i / 1000.;
+ }
+
+ int m = 8;
+ int n_bit = 4;
+
+ faiss::IndexPQFastScan index(d, m, n_bit);
+ printf("Index is trained? %s\n", index.is_trained ? "true" : "false");
+ index.train(nb, xb);
+ printf("Index is trained? %s\n", index.is_trained ? "true" : "false");
+ index.add(nb, xb);
+
+ int k = 4;
+
+ { // search xq
+ idx_t* I = new idx_t[(int)(k * nq)];
+ float* D = new float[(int)(k * nq)];
+
+ index.search(nq, xq, k, D, I);
+
+ printf("I=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++) {
+ printf("%5zd ", I[i * k + j]);
+ }
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+} // namespace facebook::detail
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/8-PQFastScanRefine.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/8-PQFastScanRefine.cpp
new file mode 100644
index 0000000..b900361
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/8-PQFastScanRefine.cpp
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexRefine.h>
+
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[(int)(d * nb)];
+ float* xq = new float[(int)(d * nq)];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++) {
+ xb[d * i + j] = distrib(rng);
+ }
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++) {
+ xq[d * i + j] = distrib(rng);
+ }
+ xq[d * i] += i / 1000.;
+ }
+
+ int m = 8;
+ int n_bit = 4;
+
+ faiss::IndexPQFastScan index(d, m, n_bit);
+ faiss::IndexRefineFlat index_refine(&index);
+ // refine index after PQFastScan
+
+ printf("Index is trained? %s\n",
+ index_refine.is_trained ? "true" : "false");
+ index_refine.train(nb, xb);
+ printf("Index is trained? %s\n",
+ index_refine.is_trained ? "true" : "false");
+ index_refine.add(nb, xb);
+
+ int k = 4;
+ { // search xq
+ idx_t* I = new idx_t[(int)(k * nq)];
+ float* D = new float[(int)(k * nq)];
+ float k_factor = 3;
+ faiss::IndexRefineSearchParameters* params =
+ new faiss::IndexRefineSearchParameters();
+ params->k_factor = k_factor;
+ index_refine.search(nq, xq, k, D, I, params);
+
+ printf("I=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++) {
+ printf("%5zd ", I[i * k + j]);
+ }
+ printf("\n");
+ }
+
+ delete[] I;
+ delete[] D;
+ delete params;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/9-RefineComparison.cpp b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/9-RefineComparison.cpp
new file mode 100644
index 0000000..cf38b6f
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/9-RefineComparison.cpp
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+#include <cassert>
+#include <cstdio>
+#include <cstdlib>
+#include <random>
+
+#include <faiss/IndexPQFastScan.h>
+#include <faiss/IndexRefine.h>
+#include <faiss/index_factory.h>
+using idx_t = faiss::idx_t;
+
+int main() {
+ int d = 64; // dimension
+ int nb = 100000; // database size
+ int nq = 10000; // nb of queries
+
+ std::mt19937 rng;
+ std::uniform_real_distribution<> distrib;
+
+ float* xb = new float[(int)(d * nb)];
+ float* xq = new float[(int)(d * nq)];
+
+ for (int i = 0; i < nb; i++) {
+ for (int j = 0; j < d; j++) {
+ xb[d * i + j] = distrib(rng);
+ }
+ xb[d * i] += i / 1000.;
+ }
+
+ for (int i = 0; i < nq; i++) {
+ for (int j = 0; j < d; j++) {
+ xq[d * i + j] = distrib(rng);
+ }
+ xq[d * i] += i / 1000.;
+ }
+
+ // Constructing the refine PQ index with SQfp16 with index factory
+ faiss::Index* index_fp16;
+ index_fp16 = faiss::index_factory(
+ d, "PQ32x4fs,Refine(SQfp16)", faiss::METRIC_L2);
+ index_fp16->train(nb, xb);
+ index_fp16->add(nb, xb);
+
+ // Constructing the refine PQ index with SQ8
+ faiss::Index* index_sq8;
+ index_sq8 =
+ faiss::index_factory(d, "PQ32x4fs,Refine(SQ8)", faiss::METRIC_L2);
+ index_sq8->train(nb, xb);
+ index_sq8->add(nb, xb);
+
+ int k = 10;
+ { // search xq
+ idx_t* I_fp16 = new idx_t[(int)(k * nq)];
+ float* D_fp16 = new float[(int)(k * nq)];
+ idx_t* I_sq8 = new idx_t[(int)(k * nq)];
+ float* D_sq8 = new float[(int)(k * nq)];
+
+ // Parameterization on k factor while doing search for index refinement
+ float k_factor = 3;
+ faiss::IndexRefineSearchParameters* params =
+ new faiss::IndexRefineSearchParameters();
+ params->k_factor = k_factor;
+
+ // Perform index search using different index refinement
+ index_fp16->search(nq, xq, k, D_fp16, I_fp16, params);
+ index_sq8->search(nq, xq, k, D_sq8, I_sq8, params);
+
+ printf("I_fp16=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++) {
+ printf("%5zd ", I_fp16[i * k + j]);
+ }
+ printf("\n");
+ }
+
+ printf("I_sq8=\n");
+ for (int i = nq - 5; i < nq; i++) {
+ for (int j = 0; j < k; j++) {
+ printf("%5zd ", I_sq8[i * k + j]);
+ }
+ printf("\n");
+ }
+
+ delete[] I_fp16;
+ delete[] D_fp16;
+ delete[] I_sq8;
+ delete[] D_sq8;
+ delete params;
+
+ delete index_fp16;
+ delete index_sq8;
+ }
+
+ delete[] xb;
+ delete[] xq;
+
+ return 0;
+}
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/CMakeLists.txt b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/CMakeLists.txt
new file mode 100644
index 0000000..045c1bb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/cpp/CMakeLists.txt
@@ -0,0 +1,31 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+add_executable(1-Flat EXCLUDE_FROM_ALL 1-Flat.cpp)
+target_link_libraries(1-Flat PRIVATE faiss)
+
+add_executable(2-IVFFlat EXCLUDE_FROM_ALL 2-IVFFlat.cpp)
+target_link_libraries(2-IVFFlat PRIVATE faiss)
+
+add_executable(3-IVFPQ EXCLUDE_FROM_ALL 3-IVFPQ.cpp)
+target_link_libraries(3-IVFPQ PRIVATE faiss)
+
+add_executable(4-GPU EXCLUDE_FROM_ALL 4-GPU.cpp)
+target_link_libraries(4-GPU PRIVATE faiss)
+
+add_executable(5-Multiple-GPUs EXCLUDE_FROM_ALL 5-Multiple-GPUs.cpp)
+target_link_libraries(5-Multiple-GPUs PRIVATE faiss)
+
+add_executable(6-HNSW EXCLUDE_FROM_ALL 6-HNSW.cpp)
+target_link_libraries(6-HNSW PRIVATE faiss)
+
+add_executable(7-PQFastScan EXCLUDE_FROM_ALL 7-PQFastScan.cpp)
+target_link_libraries(7-PQFastScan PRIVATE faiss)
+
+add_executable(8-PQFastScanRefine EXCLUDE_FROM_ALL 8-PQFastScanRefine.cpp)
+target_link_libraries(8-PQFastScanRefine PRIVATE faiss)
+
+add_executable(9-RefineComparison EXCLUDE_FROM_ALL 9-RefineComparison.cpp)
+target_link_libraries(9-RefineComparison PRIVATE faiss)
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/1-Flat.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/1-Flat.py
new file mode 100644
index 0000000..e0caaf3
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/1-Flat.py
@@ -0,0 +1,29 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32')
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+import faiss # make faiss available
+index = faiss.IndexFlatL2(d) # build the index
+print(index.is_trained)
+index.add(xb) # add vectors to the index
+print(index.ntotal)
+
+k = 4 # we want to see 4 nearest neighbors
+D, I = index.search(xb[:5], k) # sanity check
+print(I)
+print(D)
+D, I = index.search(xq, k) # actual search
+print(I[:5]) # neighbors of the 5 first queries
+print(I[-5:]) # neighbors of the 5 last queries
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/2-IVFFlat.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/2-IVFFlat.py
new file mode 100644
index 0000000..394baef
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/2-IVFFlat.py
@@ -0,0 +1,34 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32')
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+import faiss
+
+nlist = 100
+k = 4
+quantizer = faiss.IndexFlatL2(d) # the other index
+index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
+# here we specify METRIC_L2, by default it performs inner-product search
+
+assert not index.is_trained
+index.train(xb)
+assert index.is_trained
+
+index.add(xb) # add may be a bit slower as well
+D, I = index.search(xq, k) # actual search
+print(I[-5:]) # neighbors of the 5 last queries
+index.nprobe = 10 # default nprobe is 1, try a few more
+D, I = index.search(xq, k)
+print(I[-5:]) # neighbors of the 5 last queries
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/3-IVFPQ.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/3-IVFPQ.py
new file mode 100644
index 0000000..b2d83b0
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/3-IVFPQ.py
@@ -0,0 +1,32 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32')
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+import faiss
+
+nlist = 100
+m = 8
+k = 4
+quantizer = faiss.IndexFlatL2(d) # this remains the same
+index = faiss.IndexIVFPQ(quantizer, d, nlist, m, 8)
+ # 8 specifies that each sub-vector is encoded as 8 bits
+index.train(xb)
+index.add(xb)
+D, I = index.search(xb[:5], k) # sanity check
+print(I)
+print(D)
+index.nprobe = 10 # make comparable with experiment above
+D, I = index.search(xq, k) # search
+print(I[-5:])
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/4-GPU.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/4-GPU.py
new file mode 100644
index 0000000..ebad5ab
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/4-GPU.py
@@ -0,0 +1,57 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32')
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+import faiss # make faiss available
+
+res = faiss.StandardGpuResources() # use a single GPU
+
+## Using a flat index
+
+index_flat = faiss.IndexFlatL2(d) # build a flat (CPU) index
+
+# make it a flat GPU index
+gpu_index_flat = faiss.index_cpu_to_gpu(res, 0, index_flat)
+
+gpu_index_flat.add(xb) # add vectors to the index
+print(gpu_index_flat.ntotal)
+
+k = 4 # we want to see 4 nearest neighbors
+D, I = gpu_index_flat.search(xq, k) # actual search
+print(I[:5]) # neighbors of the 5 first queries
+print(I[-5:]) # neighbors of the 5 last queries
+
+
+## Using an IVF index
+
+nlist = 100
+quantizer = faiss.IndexFlatL2(d) # the other index
+index_ivf = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
+# here we specify METRIC_L2, by default it performs inner-product search
+
+# make it an IVF GPU index
+gpu_index_ivf = faiss.index_cpu_to_gpu(res, 0, index_ivf)
+
+assert not gpu_index_ivf.is_trained
+gpu_index_ivf.train(xb) # add vectors to the index
+assert gpu_index_ivf.is_trained
+
+gpu_index_ivf.add(xb) # add vectors to the index
+print(gpu_index_ivf.ntotal)
+
+k = 4 # we want to see 4 nearest neighbors
+D, I = gpu_index_ivf.search(xq, k) # actual search
+print(I[:5]) # neighbors of the 5 first queries
+print(I[-5:]) # neighbors of the 5 last queries
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/5-Multiple-GPUs.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/5-Multiple-GPUs.py
new file mode 100644
index 0000000..d3ce033
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/5-Multiple-GPUs.py
@@ -0,0 +1,35 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32')
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+import faiss # make faiss available
+
+ngpus = faiss.get_num_gpus()
+
+print("number of GPUs:", ngpus)
+
+cpu_index = faiss.IndexFlatL2(d)
+
+gpu_index = faiss.index_cpu_to_all_gpus( # build the index
+ cpu_index
+)
+
+gpu_index.add(xb) # add vectors to the index
+print(gpu_index.ntotal)
+
+k = 4 # we want to see 4 nearest neighbors
+D, I = gpu_index.search(xq, k) # actual search
+print(I[:5]) # neighbors of the 5 first queries
+print(I[-5:]) # neighbors of the 5 last queries
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/7-PQFastScan.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/7-PQFastScan.py
new file mode 100644
index 0000000..c6e2fa1
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/7-PQFastScan.py
@@ -0,0 +1,35 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32') # 64-dim *nb queries
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+m = 8 # 8 specifies that the number of sub-vector is 8
+k = 4 # number of dimension in etracted vector
+n_bit = 4 # 4 specifies that each sub-vector is encoded as 4 bits
+bbs = 32 # build block size ( bbs % 32 == 0 ) for PQ
+index = faiss.IndexPQFastScan(d, m, n_bit, faiss.METRIC_L2, bbs)
+# construct FastScan Index
+
+assert not index.is_trained
+index.train(xb) # Train vectors data index within mockup database
+assert index.is_trained
+
+index.add(xb)
+D, I = index.search(xb[:5], k) # sanity check
+print(I)
+print(D)
+index.nprobe = 10 # make comparable with experiment above
+D, I = index.search(xq, k) # search
+print(I[-5:]) # neighbors of the 5 last queries
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/8-PQFastScanRefine.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/8-PQFastScanRefine.py
new file mode 100644
index 0000000..487c2eb
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/8-PQFastScanRefine.py
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+import numpy as np
+
+d = 64 # dimension
+nb = 100000 # database size
+nq = 10000 # nb of queries
+np.random.seed(1234) # make reproducible
+xb = np.random.random((nb, d)).astype('float32') # 64-dim *nb queries
+xb[:, 0] += np.arange(nb) / 1000.
+xq = np.random.random((nq, d)).astype('float32')
+xq[:, 0] += np.arange(nq) / 1000.
+
+m = 8 # 8 specifies that the number of sub-vector is 8
+k = 4 # number of dimension in etracted vector
+n_bit = 4 # 4 specifies that each sub-vector is encoded as 4 bits
+bbs = 32 # build block size ( bbs % 32 == 0 ) for PQ
+
+index = faiss.IndexPQFastScan(d, m, n_bit, faiss.METRIC_L2)
+index_refine = faiss.IndexRefineFlat(index)
+# construct FastScan and run index refinement
+
+assert not index_refine.is_trained
+index_refine.train(xb) # Train vectors data index within mockup database
+assert index_refine.is_trained
+
+index_refine.add(xb)
+params = faiss.IndexRefineSearchParameters(k_factor=3)
+D, I = index_refine.search(xq[:5], 10, params=params)
+print(I)
+print(D)
+index.nprobe = 10 # make comparable with experiment above
+D, I = index.search(xq[:5], k) # search
+print(I[-5:])
diff --git a/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/9-RefineComparison.py b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/9-RefineComparison.py
new file mode 100644
index 0000000..a1c5870
--- /dev/null
+++ b/packages/leann-backend-hnsw/third_party/faiss/tutorial/python/9-RefineComparison.py
@@ -0,0 +1,42 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# This source code is licensed under the MIT license found in the
+# LICENSE file in the root directory of this source tree.
+
+import faiss
+
+from faiss.contrib.evaluation import knn_intersection_measure
+from faiss.contrib import datasets
+
+# 64-dim vectors, 50000 vectors in the training, 100000 in database,
+# 10000 in queries, dtype ('float32')
+ds = datasets.SyntheticDataset(64, 50000, 100000, 10000)
+d = 64 # dimension
+
+# Constructing the refine PQ index with SQfp16 with index factory
+index_fp16 = faiss.index_factory(d, 'PQ32x4fs,Refine(SQfp16)')
+index_fp16.train(ds.get_train())
+index_fp16.add(ds.get_database())
+
+# Constructing the refine PQ index with SQ8
+index_sq8 = faiss.index_factory(d, 'PQ32x4fs,Refine(SQ8)')
+index_sq8.train(ds.get_train())
+index_sq8.add(ds.get_database())
+
+# Parameterization on k factor while doing search for index refinement
+k_factor = 3.0
+params = faiss.IndexRefineSearchParameters(k_factor=k_factor)
+
+# Perform index search using different index refinement
+D_fp16, I_fp16 = index_fp16.search(ds.get_queries(), 100, params=params)
+D_sq8, I_sq8 = index_sq8.search(ds.get_queries(), 100, params=params)
+
+# Calculating knn intersection measure for different index types on refinement
+KIM_fp16 = knn_intersection_measure(I_fp16, ds.get_groundtruth())
+KIM_sq8 = knn_intersection_measure(I_sq8, ds.get_groundtruth())
+
+# KNN intersection measure accuracy shows that choosing SQ8 impacts accuracy
+assert (KIM_fp16 > KIM_sq8)
+
+print(I_sq8[:5])
+print(I_fp16[:5])
diff --git a/packages/leann-core/pyproject.toml b/packages/leann-core/pyproject.toml
new file mode 100644
index 0000000..7936d53
--- /dev/null
+++ b/packages/leann-core/pyproject.toml
@@ -0,0 +1,18 @@
+[build-system]
+requires = ["setuptools>=61.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "leann-core"
+version = "0.1.0"
+description = "Core API and plugin system for Leann."
+readme = "README.md"
+requires-python = ">=3.9"
+license = { text = "MIT" }
+
+dependencies = [
+ "numpy>=1.20.0"
+]
+
+[tool.setuptools.packages.find]
+where = ["src"]
\ No newline at end of file
diff --git a/packages/leann-core/src/leann/api.py b/packages/leann-core/src/leann/api.py
new file mode 100644
index 0000000..e9955e9
--- /dev/null
+++ b/packages/leann-core/src/leann/api.py
@@ -0,0 +1,179 @@
+from .registry import BACKEND_REGISTRY
+from .interface import LeannBackendFactoryInterface
+from typing import List, Dict, Any, Optional
+import numpy as np
+import os
+import json
+from pathlib import Path
+import openai # Import openai library
+
+# 一个辅助函数,用于临时计算 embedding
+def _compute_embeddings(chunks: List[str], model_name: str) -> np.ndarray:
+ try:
+ from sentence_transformers import SentenceTransformer
+ model = SentenceTransformer(model_name)
+ print(f"INFO: Computing embeddings for {len(chunks)} chunks using '{model_name}'...")
+ embeddings = model.encode(chunks, show_progress_bar=True)
+ return np.asarray(embeddings, dtype=np.float32)
+ except ImportError:
+ print("WARNING: sentence-transformers not installed. Falling back to random embeddings.")
+ # 如果没有安装,则生成随机向量用于测试
+ # TODO: 应该从一个固定的地方获取维度信息
+ return np.random.rand(len(chunks), 768).astype(np.float32)
+
+
+class LeannBuilder:
+ """
+ 负责构建 Leann 索引的上层 API。
+ 它协调 embedding 计算和后端索引构建。
+ """
+ def __init__(self, backend_name: str, embedding_model: str = "sentence-transformers/all-mpnet-base-v2", **backend_kwargs):
+ self.backend_name = backend_name
+ self.backend_factory = BACKEND_REGISTRY.get(backend_name)
+ if self.backend_factory is None:
+ raise ValueError(f"Backend '{backend_name}' not found or not registered.")
+
+ self.embedding_model = embedding_model
+ self.backend_kwargs = backend_kwargs
+ self.chunks: List[Dict[str, Any]] = []
+ print(f"INFO: LeannBuilder initialized with '{backend_name}' backend.")
+
+ def add_text(self, text: str, metadata: Optional[Dict[str, Any]] = None):
+ # 简单的分块逻辑
+ self.chunks.append({"text": text, "metadata": metadata or {}})
+
+ def build_index(self, index_path: str):
+ if not self.chunks:
+ raise ValueError("No chunks added. Use add_text() first.")
+
+ # 1. 计算 embedding (这是 leann-core 的职责)
+ texts_to_embed = [c["text"] for c in self.chunks]
+ embeddings = _compute_embeddings(texts_to_embed, self.embedding_model)
+
+ # 2. 创建 builder 实例并构建索引
+ builder_instance = self.backend_factory.builder(**self.backend_kwargs)
+ builder_instance.build(embeddings, index_path, **self.backend_kwargs)
+
+ # 3. 保存 leann 特有的元数据(不包含向量)
+ index_dir = Path(index_path).parent
+ leann_meta_path = index_dir / f"{Path(index_path).name}.meta.json"
+
+ meta_data = {
+ "version": "0.1.0",
+ "backend_name": self.backend_name,
+ "embedding_model": self.embedding_model,
+ "num_chunks": len(self.chunks),
+ "chunks": self.chunks,
+ }
+ with open(leann_meta_path, 'w', encoding='utf-8') as f:
+ json.dump(meta_data, f, indent=2)
+ print(f"INFO: Leann metadata saved to {leann_meta_path}")
+
+
+class LeannSearcher:
+ """
+ 负责加载索引并执行检索的上层 API。
+ """
+ def __init__(self, index_path: str, **backend_kwargs):
+ leann_meta_path = Path(index_path).parent / f"{Path(index_path).name}.meta.json"
+ if not leann_meta_path.exists():
+ raise FileNotFoundError(f"Leann metadata file not found at {leann_meta_path}. Was the index built with LeannBuilder?")
+
+ with open(leann_meta_path, 'r', encoding='utf-8') as f:
+ self.meta_data = json.load(f)
+
+ backend_name = self.meta_data['backend_name']
+ self.embedding_model = self.meta_data['embedding_model']
+
+ backend_factory = BACKEND_REGISTRY.get(backend_name)
+ if backend_factory is None:
+ raise ValueError(f"Backend '{backend_name}' (from index file) not found or not registered.")
+
+ # 创建 searcher 实例
+ self.backend_impl = backend_factory.searcher(index_path, **backend_kwargs)
+ print(f"INFO: LeannSearcher initialized with '{backend_name}' backend using index '{index_path}'.")
+
+ def search(self, query: str, top_k: int = 5, **search_kwargs):
+ query_embedding = _compute_embeddings([query], self.embedding_model)
+
+ # 委托给后端的 search 方法
+ results = self.backend_impl.search(query_embedding, top_k, **search_kwargs)
+
+ # 丰富返回结果,加入原始文本和元数据
+ enriched_results = []
+ for label, dist in zip(results['labels'][0], results['distances'][0]):
+ if label < len(self.meta_data['chunks']):
+ chunk_info = self.meta_data['chunks'][label]
+ enriched_results.append({
+ "id": label,
+ "score": dist,
+ "text": chunk_info['text'],
+ "metadata": chunk_info['metadata']
+ })
+ return enriched_results
+
+
+class LeannChat:
+ """
+ 封装了 Searcher 和 LLM 的对话式 RAG 接口。
+ """
+ def __init__(self, index_path: str, backend_name: Optional[str] = None, llm_model: str = "gpt-4o", **kwargs):
+ # 如果用户没有指定后端,尝试从索引元数据中读取
+ if backend_name is None:
+ leann_meta_path = Path(index_path).parent / f"{Path(index_path).name}.meta.json"
+ if not leann_meta_path.exists():
+ raise FileNotFoundError(f"Leann metadata file not found at {leann_meta_path}.")
+ with open(leann_meta_path, 'r', encoding='utf-8') as f:
+ meta_data = json.load(f)
+ backend_name = meta_data['backend_name']
+
+ self.searcher = LeannSearcher(index_path, **kwargs)
+ self.llm_model = llm_model
+ self.openai_client = None # Lazy load
+
+ def _get_openai_client(self):
+ if self.openai_client is None:
+ api_key = os.getenv("OPENAI_API_KEY")
+ if not api_key:
+ raise ValueError("OPENAI_API_KEY environment variable not set.")
+ self.openai_client = openai.OpenAI(api_key=api_key)
+ return self.openai_client
+
+ def ask(self, question: str, **kwargs):
+ # 1. 检索
+ results = self.searcher.search(question, top_k=3, **kwargs)
+ context = "\n\n".join([r['text'] for r in results])
+
+ # 2. 构建 Prompt
+ prompt = f"Context:\n{context}\n\nQuestion: {question}\n\nAnswer:"
+
+ # 3. 调用 LLM
+ print(f"DEBUG: Calling LLM with prompt: {prompt[:200]}...")
+ try:
+ client = self._get_openai_client()
+ response = client.chat.completions.create(
+ model=self.llm_model,
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant that answers questions based on the provided context."},
+ {"role": "user", "content": prompt}
+ ]
+ )
+ return response.choices[0].message.content
+ except Exception as e:
+ print(f"ERROR: Failed to call OpenAI API: {e}")
+ return f"Error: Could not get a response from the LLM. {e}"
+
+ def start_interactive(self):
+ print("\nLeann Chat started (type 'quit' to exit)")
+ while True:
+ try:
+ user_input = input("You: ").strip()
+ if user_input.lower() in ['quit', 'exit']:
+ break
+ if not user_input:
+ continue
+ response = self.ask(user_input)
+ print(f"Leann: {response}")
+ except (KeyboardInterrupt, EOFError):
+ print("\nGoodbye!")
+ break
diff --git a/packages/leann-core/src/leann/interface.py b/packages/leann-core/src/leann/interface.py
new file mode 100644
index 0000000..2786b62
--- /dev/null
+++ b/packages/leann-core/src/leann/interface.py
@@ -0,0 +1,59 @@
+from abc import ABC, abstractmethod
+import numpy as np
+from typing import Dict, Any
+
+class LeannBackendBuilderInterface(ABC):
+ """用于构建索引的后端接口"""
+
+ @abstractmethod
+ def build(self, data: np.ndarray, index_path: str, **kwargs) -> None:
+ """构建索引
+
+ Args:
+ data: 向量数据 (N, D)
+ index_path: 索引保存路径
+ **kwargs: 后端特定的构建参数
+ """
+ pass
+
+class LeannBackendSearcherInterface(ABC):
+ """用于搜索的后端接口"""
+
+ @abstractmethod
+ def __init__(self, index_path: str, **kwargs):
+ """初始化搜索器
+
+ Args:
+ index_path: 索引文件路径
+ **kwargs: 后端特定的加载参数
+ """
+ pass
+
+ @abstractmethod
+ def search(self, query: np.ndarray, top_k: int, **kwargs) -> Dict[str, Any]:
+ """搜索最近邻
+
+ Args:
+ query: 查询向量 (1, D) 或 (B, D)
+ top_k: 返回的最近邻数量
+ **kwargs: 搜索参数
+
+ Returns:
+ {"labels": [...], "distances": [...]}
+ """
+ pass
+
+class LeannBackendFactoryInterface(ABC):
+ """后端工厂接口"""
+
+ @staticmethod
+ @abstractmethod
+ def builder(**kwargs) -> LeannBackendBuilderInterface:
+ """创建 Builder 实例"""
+ pass
+
+ @staticmethod
+ @abstractmethod
+ def searcher(index_path: str, **kwargs) -> LeannBackendSearcherInterface:
+ """创建 Searcher 实例"""
+ pass
\ No newline at end of file
diff --git a/packages/leann-core/src/leann/registry.py b/packages/leann-core/src/leann/registry.py
new file mode 100644
index 0000000..e9f54e0
--- /dev/null
+++ b/packages/leann-core/src/leann/registry.py
@@ -0,0 +1,12 @@
+# packages/leann-core/src/leann/registry.py
+
+# 全局的后端注册表字典
+BACKEND_REGISTRY = {}
+
+def register_backend(name: str):
+ """一个用于注册新后端类的装饰器。"""
+ def decorator(cls):
+ print(f"INFO: Registering backend '{name}'")
+ BACKEND_REGISTRY[name] = cls
+ return cls
+ return decorator
\ No newline at end of file
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..11ed2a6
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,49 @@
+[build-system]
+requires = ["setuptools>=61.0", "cmake>=3.24"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "leann-workspace"
+version = "0.1.0"
+requires-python = ">=3.9"
+
+dependencies = [
+ "leann-core",
+ "leann-backend-diskann",
+ "leann-backend-hnsw",
+ "numpy==1.25.0",
+ "torch",
+ "tqdm",
+ "flask",
+ "flask_compress",
+ "datasets>=2.15.0",
+ "evaluate",
+ "colorama",
+ "boto3",
+ "protobuf==4.25.3",
+ "sglang[all]",
+ "ollama",
+ "requests>=2.25.0",
+ "sentence-transformers>=2.2.0",
+ "openai>=1.0.0",
+ "PyPDF2>=3.0.0",
+ "llama-index>=0.12.44",
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest>=7.0",
+ "pytest-cov>=4.0",
+ "black>=23.0",
+ "ruff>=0.1.0",
+ "matplotlib",
+]
+
+[tool.setuptools]
+py-modules = []
+
+
+[tool.uv.sources]
+leann-core = { path = "packages/leann-core", editable = true }
+leann-backend-diskann = { path = "packages/leann-backend-diskann", editable = true }
+leann-backend-hnsw = { path = "packages/leann-backend-hnsw", editable = true }
diff --git a/research/micro/analyze_HNSW.py b/research/micro/analyze_HNSW.py
new file mode 100644
index 0000000..315cfcf
--- /dev/null
+++ b/research/micro/analyze_HNSW.py
@@ -0,0 +1,12 @@
+import faiss
+hnsw_index = faiss.read_index("/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/hnsw_IP_M30_efC128.index", faiss.IO_FLAG_ONDISK_SAME_DIR)
+
+# print total number of nodes
+print(hnsw_index.ntotal)
+
+# print stats of the graph
+print(hnsw_index.hnsw.print_neighbor_stats(0))
+
+
+# save_degree_distribution
+hnsw_index.hnsw.save_degree_distribution(0, "degree_distribution_HNSW_M30.txt")
\ No newline at end of file
diff --git a/research/micro/analyze_NSG.py b/research/micro/analyze_NSG.py
new file mode 100644
index 0000000..f14f020
--- /dev/null
+++ b/research/micro/analyze_NSG.py
@@ -0,0 +1,11 @@
+import faiss
+nsg_index = faiss.read_index("/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/nsg_R16.index", faiss.IO_FLAG_ONDISK_SAME_DIR)
+
+# print total number of nodes
+print(nsg_index.ntotal)
+
+# print stats of the graph
+print(nsg_index.nsg.print_neighbor_stats(0))
+
+# save degree distribution
+nsg_index.nsg.save_degree_distribution("degree_distribution_NSG_R60.txt")
\ No newline at end of file
diff --git a/research/micro/bnbtest.py b/research/micro/bnbtest.py
new file mode 100644
index 0000000..3738c20
--- /dev/null
+++ b/research/micro/bnbtest.py
@@ -0,0 +1,63 @@
+import torch
+import torch.nn as nn
+import time
+
+# import bitsandbytes as bnb
+from bitsandbytes.nn import Linear8bitLt
+
+# set default to half
+import torch
+torch.set_default_dtype(torch.float16)
+
+M = 2048
+N = 2048
+
+bsz = 2048
+import torch_int
+from torch_int.nn.linear import W8A8BFP32OFP32Linear, W8A8B8O8Linear, W8A8B8O8LinearReLU
+
+fp16_model = nn.Sequential(
+ nn.Linear(M, N),
+ # nn.Linear(2048, 2048)
+)
+
+int8_model = nn.Sequential(
+ Linear8bitLt(M, N, has_fp16_weights=False),
+ # Linear8bitLt(2048, 2048, has_fp16_weights=False)
+)
+
+int8_model.load_state_dict(fp16_model.state_dict())
+int8_model = int8_model.to(0) # Quantization happens here
+fp16_model = fp16_model.to(0) # Move fp16 model to GPU as well
+
+# Create random input tensor
+input_tensor = torch.randn(bsz, M, device=0) # Batch of 1000 vectors
+
+# Speed test function
+def speed_test(model, input_tensor, name, num_iterations=100):
+ # Warmup
+ for _ in range(10):
+ _ = model(input_tensor)
+
+ # Actual timing
+ torch.cuda.synchronize()
+ start_time = time.time()
+
+ for _ in range(num_iterations):
+ _ = model(input_tensor)
+
+ torch.cuda.synchronize()
+ end_time = time.time()
+
+ avg_time = (end_time - start_time) / num_iterations
+ print(f"{name} model: {avg_time:.6f} seconds per iteration")
+ return avg_time
+
+# Run speed tests
+with torch.no_grad(): # Disable gradient calculation for inference
+ fp16_time = speed_test(fp16_model, input_tensor, "FP16")
+ int8_time = speed_test(int8_model, input_tensor, "INT8")
+
+ # Calculate speedup
+ speedup = fp16_time / int8_time
+ print(f"INT8 is {speedup:.2f}x faster than FP16")
\ No newline at end of file
diff --git a/research/micro/data/transformer-batching-microbenchmarks.csv b/research/micro/data/transformer-batching-microbenchmarks.csv
new file mode 100644
index 0000000..8240586
--- /dev/null
+++ b/research/micro/data/transformer-batching-microbenchmarks.csv
@@ -0,0 +1,89 @@
+n,d,seqlen,bs,latency,h,flop,io,intensity,throughput,series
+3,256,256,2048,0.009623501679245285,768,618475290624,167.48502132816208,3692720015.912285,64267177503366.266,dense
+3,256,256,1024,0.004853848615384615,768,309237645312,166.15392854317415,1861151572.059558,63709783682138.234,dense
+3,256,256,512,0.0024687246971962615,768,154618822656,163.57953256539062,945221081.3366361,62631051097597.516,dense
+3,256,256,256,0.0012845360838052097,768,77309411328,157.64931990085577,490388486.1451936,60184694149645.54,dense
+3,256,256,128,0.0006901147179878049,768,38654705664,147.57393422494675,261934506.70684624,56012000116019.945,dense
+3,256,256,64,0.0003363830693015702,768,19327352832,153.1328437752606,126212981.84970059,57456378146882.51,dense
+3,256,256,32,0.00018671159748991485,768,9663676416,141.10249365427362,68486928.65540518,51757237075334.75,dense
+3,256,256,16,0.00012353640857142858,768,4831838208,111.40488993609125,43371868.24359184,39112665358133.98,dense
+3,256,256,8,9.774760007849294e-05,768,2415919104,76.43260800265766,31608487.09906635,24715891766754.14,dense
+3,256,256,4,6.672271167474822e-05,768,1207959552,64.82614227498455,18633833.660438772,18104173551704.773,dense
+3,256,256,2,4.9758770289855074e-05,768,603979776,55.317122669351576,10918495.880745342,12138157202874.861,dense
+3,256,1,2048,9.785507940251571e-05,768,2415919104,76.34865809334705,31643242.518371396,24688745017132.86,dense
+3,256,1,1024,6.692813470149253e-05,768,1207959552,64.62717090938949,18691202.70936228,18048606275785.867,dense
+3,256,1,512,4.9680950036205655e-05,768,603979776,55.40377142534654,10901419.893658841,12157170415618.898,dense
+3,256,1,256,4.2781118741058655e-05,768,301989888,45.95672244805227,6571179.83862661,7058952568020.829,dense
+3,256,1,128,5.0662328255350016e-05,768,150994944,31.046026784880404,4863583.512513602,2980418571348.519,dense
+3,256,1,64,4.475009253945481e-05,768,75497472,30.75426042497223,2454862.219307235,1687090857598.4766,dense
+3,256,1,32,4.51682671454219e-05,768,37748736,28.29313765537115,1334201.1218340008,835735758435.5786,dense
+3,256,1,16,5.03585186661834e-05,768,18874368,24.401035466223117,773506.846712577,374799904761.1871,dense
+3,256,1,8,5.023459565217391e-05,768,9437184,23.972005435021096,393675.19858030166,187862246674.45105,dense
+3,256,1,4,5.053219391083726e-05,768,4718592,23.58765586356967,200044.97383259286,93377936614.54384,dense
+3,256,1,2,4.4607398995335484e-05,768,2359296,26.58285456464288,88752.54515134107,52890239133.797226,dense
+12,256,256,2048,0.14480779847058822,3072,9895604649984,44.620009282941716,221775046868.20184,68336130750540.26,dense
+12,256,256,1024,0.07254347629166667,3072,4947802324992,44.664248332585096,110777691547.58836,68204648824643.82,dense
+12,256,256,512,0.036310761444444443,3072,2473901162496,44.876147984203506,55127306456.13385,68131349056975.164,dense
+12,256,256,256,0.01821551906896552,3072,1236950581248,45.24607467289738,27338295977.947884,67906414116709.98,dense
+12,256,256,128,0.009229417903030302,3072,618475290624,45.67217092440895,13541622351.335684,67011299859001.46,dense
+12,256,256,64,0.004754550595394737,3072,309237645312,46.31372736116993,6677019167.566916,65040352207320.695,dense
+12,256,256,32,0.002405752659340659,3072,154618822656,49.68826015254682,3111777755.5766335,64270456921525.82,dense
+12,256,256,16,0.0012287219045005488,3072,77309411328,56.323579604557374,1372594069.3184311,62918558743709.18,dense
+12,256,256,8,0.0006206816149425287,3072,38654705664,70.95456179103653,544781120.315271,62277832520589.78,dense
+12,256,256,4,0.0003875502697142857,3072,19327352832,81.16954743236613,238110885.71245712,49870569942445.75,dense
+12,256,256,2,0.00027502018627941914,3072,9663676416,91.50537035282076,105607751.53129694,35138062215483.168,dense
+12,256,1,2048,0.0006202853873290136,3072,38654705664,70.99988634205897,544433345.6784943,62317614526515.766,dense
+12,256,1,1024,0.00038721467732724153,3072,19327352832,81.2398957010995,237904697.74985722,49913791918755.53,dense
+12,256,1,512,0.000274364799,3072,9663676416,91.72395326121995,105356082.81599998,35221998052308.45,dense
+12,256,1,256,0.00012488918589482266,3072,4831838208,176.31707535146046,27404255.647778228,38689003962834.75,dense
+12,256,1,128,8.976711102514506e-05,3072,2415919104,227.78088507574267,10606329.425740216,26913187652026.21,dense
+12,256,1,64,8.715176287471176e-05,3072,1207959552,225.59268282689945,5354604.31102229,13860414432884.701,dense
+12,256,1,32,8.523013435114503e-05,3072,603979776,226.06539514085782,2671703.8033338524,7086458100741.991,dense
+12,256,1,16,7.901561645904116e-05,3072,301989888,241.35704882952732,1251216.3595988373,3821901309300.556,dense
+12,256,1,8,7.827949114210329e-05,3072,150994944,242.37091635608994,622991.1833900034,1928920867994.581,dense
+12,256,1,4,7.779445951035782e-05,3072,75497472,243.25022783249054,310369.58391664835,970473636235.5986,dense
+12,256,1,2,7.758845406626506e-05,3072,37748736,243.57933441822672,154975.11761480253,486525172518.07056,dense
+3,256,256,2048,0.00507974918466899,768,206158430208,475.59810852303485,433471930.42508715,40584371927298.98,qk_init
+3,256,256,1024,0.0025616677649325623,768,103079215104,471.5519977009198,218595649.27424532,40239103803811.82,qk_init
+3,256,256,512,0.0013029336670480549,768,51539607552,463.55374128015677,111183672.92143403,39556585922573.38,qk_init
+3,256,256,256,0.0006738189029345373,768,25769803776,448.1766342333362,57499213.050413854,38244406121244.69,qk_init
+3,256,256,128,0.000358254672959467,768,12884901888,421.47375986100144,30571065.425874516,35965760841472.125,qk_init
+3,256,256,64,0.0002007051105022831,768,6442450944,376.1611839930762,17126836.096194826,32099087700742.5,qk_init
+3,256,256,32,0.00012189697230142565,768,3221225472,309.6773881032524,10401874.969721656,26425803784810.87,qk_init
+3,256,256,16,8.453561698040722e-05,768,1610612736,223.2711923587723,7213705.982328083,19052475081281.902,qk_init
+3,256,256,8,6.407660705009276e-05,768,805306368,147.2797083750448,5467870.468274581,12567868448003.822,qk_init
+3,256,256,4,5.036328747284576e-05,768,402653184,93.69110391262903,4297667.197682838,7994974200544.344,qk_init
+3,256,256,2,4.5488761135057476e-05,768,201326592,51.865470527877875,3881707.616858238,4425853485045.578,qk_init
+12,256,256,2048,0.020202365999999996,3072,824633720832,478.3437947812648,1723935231.9999998,40818670488001.266,qk_init
+12,256,256,1024,0.010124155888157895,3072,412316860416,477.2583770318811,863927969.1228071,40726048173387.19,qk_init
+12,256,256,512,0.005085633937062937,3072,206158430208,475.04777848703077,433974095.9627039,40537410430893.29,qk_init
+12,256,256,256,0.0025654916853281853,3072,103079215104,470.84913933193053,218921957.14800516,40179126556324.74,qk_init
+12,256,256,128,0.0013045765704467354,3072,51539607552,462.9699702434292,111323867.34478809,39506770794105.96,qk_init
+12,256,256,64,0.0006742801519939804,3072,25769803776,447.87005387442576,57538572.970153,38218244597284.33,qk_init
+12,256,256,32,0.00035831976790671853,3072,12884901888,421.3971919051604,30576620.194706645,35959227042573.69,qk_init
+12,256,256,16,0.0002005369068918302,3072,6442450944,376.4766953382971,17112482.721436176,32126011335534.68,qk_init
+12,256,256,8,0.00012179187250509165,3072,3221225472,309.94462293386505,10392906.453767821,26448607823689.82,qk_init
+12,256,256,4,8.452507263643351e-05,3072,1610612736,223.2990450204527,7212806.198308992,19054851841745.297,qk_init
+12,256,256,2,6.412381767545489e-05,3072,805306368,147.17127491946468,5471899.108305484,12558615459794.32,qk_init
+3,256,256,2048,0.0016183739398395718,768,805306368,811597824.0,0.9922480620155039,1265467.7325087283,qk_ar
+3,256,256,1024,0.0008322699728813558,768,402653184,405798912.0,0.9922480620155039,1230369.9921491416,qk_ar
+3,256,256,512,0.00043886859397590365,768,201326592,202899456.0,0.9922480620155039,1166636.2255762408,qk_ar
+3,256,256,256,0.00024185948322147648,768,100663296,101449728.0,0.9922480620155039,1058465.8355760013,qk_ar
+3,256,256,128,0.00014308985100166944,768,50331648,50724864.0,0.9922480620155039,894542.82818777,qk_ar
+3,256,256,64,9.382939365815932e-05,768,25165824,25362432.0,0.9922480620155039,682089.028872613,qk_ar
+3,256,256,32,6.856070612244899e-05,768,12582912,12681216.0,0.9922480620155039,466739.6503012703,qk_ar
+3,256,256,16,5.452260553129549e-05,768,6291456,6340608.0,0.9922480620155039,293456.26174846216,qk_ar
+3,256,256,8,4.608557533261417e-05,768,3145728,3170304.0,0.9922480620155039,173590.1080166944,qk_ar
+3,256,256,4,4.386146957766642e-05,768,1572864,1585152.0,0.9922480620155039,91196.21477609445,qk_ar
+3,256,256,2,4.330941094420601e-05,768,786432,792576.0,0.9922480620155039,46179.33969539622,qk_ar
+12,256,256,2048,0.006347041645299144,3072,3221225472,3246391296.0,0.9922480620155039,322670.011392918,qk_ar
+12,256,256,1024,0.0031943104467592586,3072,1610612736,1623195648.0,0.9922480620155039,320569.96872013,qk_ar
+12,256,256,512,0.0016183416350267381,3072,805306368,811597824.0,0.9922480620155039,316373.2483416833,qk_ar
+12,256,256,256,0.0008325934893977947,3072,402653184,405798912.0,0.9922480620155039,307472.9784221131,qk_ar
+12,256,256,128,0.0004389725746987952,3072,201326592,202899456.0,0.9922480620155039,291589.9702568624,qk_ar
+12,256,256,64,0.00024191767449664432,3072,100663296,101449728.0,0.9922480620155039,264552.8076159138,qk_ar
+12,256,256,32,0.0001431546143572621,3072,50331648,50724864.0,0.9922480620155039,223534.53392804778,qk_ar
+12,256,256,16,9.404283597678917e-05,3072,25165824,25362432.0,0.9922480620155039,170135.23501087292,qk_ar
+12,256,256,8,6.855550037091989e-05,3072,12582912,12681216.0,0.9922480620155039,116693.773026467,qk_ar
+12,256,256,4,5.4802094978165945e-05,3072,6291456,6340608.0,0.9922480620155039,72989.91036006316,qk_ar
+12,256,256,2,4.608510707869206e-05,3072,3145728,3170304.0,0.9922480620155039,43397.96795057727,qk_ar
diff --git a/research/micro/degree_distribution_degree_distribution_HNSW_M30.txt.png b/research/micro/degree_distribution_degree_distribution_HNSW_M30.txt.png
new file mode 100644
index 0000000..47c942c
Binary files /dev/null and b/research/micro/degree_distribution_degree_distribution_HNSW_M30.txt.png differ
diff --git a/research/micro/embedd_micro.py b/research/micro/embedd_micro.py
new file mode 100755
index 0000000..de8c088
--- /dev/null
+++ b/research/micro/embedd_micro.py
@@ -0,0 +1,594 @@
+# python embedd_micro.py --use_int8 Fastest
+
+import argparse
+import time
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Tuple
+
+import numpy as np
+import torch
+from torch import nn
+from torchao import quantize_
+from transformers import AutoModel, BitsAndBytesConfig
+from tqdm import tqdm
+from contextlib import contextmanager
+
+@dataclass
+class BenchmarkConfig:
+ model_path: str
+ batch_sizes: List[int]
+ seq_length: int
+ num_runs: int
+ use_fp16: bool = True
+ use_int4: bool = False
+ use_int8: bool = False # Add this parameter
+ use_cuda_graphs: bool = False
+ use_flash_attention: bool = False
+ use_linear8bitlt: bool = False
+
+
+class CUDAGraphContainer:
+ """Container for managing CUDA graphs for different batch sizes."""
+
+ def __init__(self, model: nn.Module, seq_length: int):
+ self.model = model
+ self.seq_length = seq_length
+ self.graphs: Dict[int, CUDAGraphWrapper] = {}
+
+ def get_or_create(self, batch_size: int) -> 'CUDAGraphWrapper':
+ if batch_size not in self.graphs:
+ self.graphs[batch_size] = CUDAGraphWrapper(
+ self.model, batch_size, self.seq_length
+ )
+ return self.graphs[batch_size]
+
+
+class CUDAGraphWrapper:
+ """Wrapper for CUDA graph capture and replay."""
+
+ def __init__(self, model: nn.Module, batch_size: int, seq_length: int):
+ self.model = model
+ self.static_input = self._create_random_batch(batch_size, seq_length)
+ self.static_attention_mask = torch.ones_like(self.static_input)
+
+ # Warm up
+ self._warmup()
+
+ # Capture graph
+ self.graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(self.graph):
+ self.static_output = self.model(
+ input_ids=self.static_input,
+ attention_mask=self.static_attention_mask
+ )
+
+ def _create_random_batch(self, batch_size: int, seq_length: int) -> torch.Tensor:
+ return torch.randint(
+ 0, 1000, (batch_size, seq_length),
+ device="cuda",
+ dtype=torch.long
+ )
+
+ def _warmup(self, num_warmup: int = 3):
+ with torch.no_grad():
+ for _ in range(num_warmup):
+ self.model(
+ input_ids=self.static_input,
+ attention_mask=self.static_attention_mask
+ )
+
+ def __call__(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ self.static_input.copy_(input_ids)
+ self.static_attention_mask.copy_(attention_mask)
+ self.graph.replay()
+ return self.static_output
+
+
+class ModelOptimizer:
+ """Applies various optimizations to the model."""
+
+ @staticmethod
+ def optimize(model: nn.Module, config: BenchmarkConfig) -> nn.Module:
+ print("\nApplying model optimizations:")
+
+ if model is None:
+ raise ValueError("Cannot optimize None model")
+
+ # Move to GPU
+ model = model.cuda()
+ print("- Model moved to GPU")
+
+ # FP16
+ if config.use_fp16 and not config.use_int4:
+ model = model.half()
+ # use torch compile
+ model = torch.compile(model)
+ print("- Using FP16 precision")
+
+ # Check if using SDPA
+ if torch.version.cuda and float(torch.version.cuda[:3]) >= 11.6:
+ if hasattr(torch.nn.functional, 'scaled_dot_product_attention'):
+ print("- Using PyTorch SDPA (scaled_dot_product_attention)")
+ else:
+ print("- PyTorch SDPA not available")
+
+ # Flash Attention
+ if config.use_flash_attention:
+ try:
+ from flash_attn.flash_attention import FlashAttention
+ print("- Flash Attention 2 available")
+ if hasattr(model.config, "attention_mode"):
+ model.config.attention_mode = "flash_attention_2"
+ print(" - Enabled Flash Attention 2 mode")
+ except ImportError:
+ print("- Flash Attention not available")
+
+ # Memory efficient attention
+ try:
+ from xformers.ops import memory_efficient_attention
+ if hasattr(model, 'enable_xformers_memory_efficient_attention'):
+ model.enable_xformers_memory_efficient_attention()
+ print("- Enabled xformers memory efficient attention")
+ else:
+ print("- Model doesn't support xformers")
+ except (ImportError, AttributeError):
+ print("- Xformers not available")
+
+ model.eval()
+ print("- Model set to eval mode")
+
+ return model
+
+
+class Timer:
+ """Handles accurate GPU timing using CUDA events."""
+
+ def __init__(self):
+ self.start_event = torch.cuda.Event(enable_timing=True)
+ self.end_event = torch.cuda.Event(enable_timing=True)
+
+ @contextmanager
+ def timing(self):
+ self.start_event.record()
+ yield
+ self.end_event.record()
+ self.end_event.synchronize()
+
+ def elapsed_time(self) -> float:
+ return self.start_event.elapsed_time(self.end_event) / 1000 # ms to seconds
+
+
+class Benchmark:
+ """Main benchmark runner."""
+
+ def __init__(self, config: BenchmarkConfig):
+ self.config = config
+ try:
+ self.model = self._load_model()
+ if self.model is None:
+ raise ValueError("Model initialization failed - model is None")
+
+ self.cuda_graphs = (
+ CUDAGraphContainer(self.model, config.seq_length)
+ if config.use_cuda_graphs
+ else None
+ )
+ self.timer = Timer()
+ except Exception as e:
+ print(f"ERROR in benchmark initialization: {str(e)}")
+ raise
+
+ def _load_model(self) -> nn.Module:
+ print(f"Loading model from {self.config.model_path}...")
+
+ try:
+ # Int4 quantization using HuggingFace integration
+ if self.config.use_int4:
+ import bitsandbytes as bnb
+ print(f"- bitsandbytes version: {bnb.__version__}")
+
+ # 检查是否使用自定义的8bit量化
+ if hasattr(self.config, 'use_linear8bitlt') and self.config.use_linear8bitlt:
+ print("- Using custom Linear8bitLt replacement for all linear layers")
+
+ # 加载原始模型(不使用量化配置)
+ import bitsandbytes as bnb
+ import torch
+ # set default to half
+ torch.set_default_dtype(torch.float16)
+ compute_dtype = torch.float16 if self.config.use_fp16 else torch.float32
+ model = AutoModel.from_pretrained(
+ self.config.model_path,
+ torch_dtype=compute_dtype,
+ )
+
+ # 定义替换函数
+ def replace_linear_with_linear8bitlt(model):
+ """递归地将模型中的所有nn.Linear层替换为Linear8bitLt"""
+ for name, module in list(model.named_children()):
+ if isinstance(module, nn.Linear):
+ # 获取原始线性层的参数
+ in_features = module.in_features
+ out_features = module.out_features
+ bias = module.bias is not None
+
+ # 创建8bit线性层
+ # print size
+ print(f"in_features: {in_features}, out_features: {out_features}")
+ new_module = bnb.nn.Linear8bitLt(
+ in_features,
+ out_features,
+ bias=bias,
+ has_fp16_weights=False
+ )
+
+ # 复制权重和偏置
+ new_module.weight.data = module.weight.data
+ if bias:
+ new_module.bias.data = module.bias.data
+
+ # 替换模块
+ setattr(model, name, new_module)
+ else:
+ # 递归处理子模块
+ replace_linear_with_linear8bitlt(module)
+
+ return model
+
+ # 替换所有线性层
+ model = replace_linear_with_linear8bitlt(model)
+ # add torch compile
+ model = torch.compile(model)
+
+ # 将模型移到GPU(量化发生在这里)
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ model = model.to(device)
+
+ print("- All linear layers replaced with Linear8bitLt")
+
+ else:
+ # 使用原来的Int4量化方法
+ print("- Using bitsandbytes for Int4 quantization")
+
+ # Create quantization config
+
+ compute_dtype = torch.float16 if self.config.use_fp16 else torch.float32
+ quantization_config = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_compute_dtype=compute_dtype,
+ bnb_4bit_use_double_quant=True,
+ bnb_4bit_quant_type="nf4"
+ )
+
+ print("- Quantization config:", quantization_config)
+
+ # Load model directly with quantization config
+ model = AutoModel.from_pretrained(
+ self.config.model_path,
+ quantization_config=quantization_config,
+ torch_dtype=compute_dtype,
+ device_map="auto" # Let HF decide on device mapping
+ )
+
+ # Check if model loaded successfully
+ if model is None:
+ raise ValueError("Model loading returned None")
+
+ print(f"- Model type: {type(model)}")
+
+ # Apply optimizations directly here
+ print("\nApplying model optimizations:")
+
+ if hasattr(self.config, 'use_linear8bitlt') and self.config.use_linear8bitlt:
+ print("- Model moved to GPU with Linear8bitLt quantization")
+ else:
+ # Skip moving to GPU since device_map="auto" already did that
+ print("- Model already on GPU due to device_map='auto'")
+
+ # Skip FP16 conversion since we specified compute_dtype
+ print(f"- Using {compute_dtype} for compute dtype")
+
+ # Check CUDA and SDPA
+ if torch.version.cuda and float(torch.version.cuda[:3]) >= 11.6:
+ if hasattr(torch.nn.functional, 'scaled_dot_product_attention'):
+ print("- Using PyTorch SDPA (scaled_dot_product_attention)")
+ else:
+ print("- PyTorch SDPA not available")
+
+ # Try xformers if available
+ try:
+ from xformers.ops import memory_efficient_attention
+ if hasattr(model, 'enable_xformers_memory_efficient_attention'):
+ model.enable_xformers_memory_efficient_attention()
+ print("- Enabled xformers memory efficient attention")
+ else:
+ print("- Model doesn't support xformers")
+ except (ImportError, AttributeError):
+ print("- Xformers not available")
+
+ # Set to eval mode
+ model.eval()
+ print("- Model set to eval mode")
+ # Int8 quantization using HuggingFace integration
+ # Int8 quantization using TorchAO
+ elif self.config.use_int8:
+ print("- Using TorchAO for Int8 dynamic activation and Int8 weight quantization")
+
+ # Import the quantize_ function and the quantization config
+ from torchao.quantization import quantize_, int8_dynamic_activation_int8_weight
+ print("- Successfully imported TorchAO")
+
+ # Load model normally first
+ # set default to half
+ import torch
+ torch.set_default_dtype(torch.bfloat16)
+ model = AutoModel.from_pretrained(
+ self.config.model_path,
+ device_map="auto"
+ )
+
+ print("- Model loaded in full precision")
+ print(f"- Model type: {type(model)}")
+
+ # Apply quantization - call the function to get the config, then apply it
+ # quantize_(model, int8_dynamic_activation_int8_weight())
+ # from torchao.quantization import quantize_, Int8DynamicActivationInt8WeightConfig,int8_dynamic_activation_int8_semi_sparse_weight,int4_weight_only,Int8DynActInt4WeightGPTQQuantizer,int8_dynamic_activation_int4_weight,Int8DynamicActivationInt4WeightConfig,Int4DynamicActivationInt4WeightConfig
+ from torchao.quantization import quantize_, Int8DynamicActivationInt8WeightConfig
+ quantize_(model, Int8DynamicActivationInt8WeightConfig())
+ print("- Model successfully quantized with int8 weights and int8 activations")
+ # add torch compile
+ model = torch.compile(model)
+ # For older PyTorch versions that have issues with tensor subclasses
+ from torchao.utils import unwrap_tensor_subclass
+ import torch
+ if hasattr(torch, '_version') and not torch.version >= "2.5.0":
+ print("- Unwrapping tensor subclasses for compatibility with older PyTorch")
+ unwrap_tensor_subclass(model)
+
+ # Apply optimizations
+ if torch.version.cuda and float(torch.version.cuda[:3]) >= 11.6:
+ if hasattr(torch.nn.functional, 'scaled_dot_product_attention'):
+ print("- Using PyTorch SDPA (scaled_dot_product_attention)")
+ else:
+ print("- PyTorch SDPA not available")
+
+ # Set to eval mode
+ model.eval()
+ print("- Model set to eval mode")
+
+ # For better performance with int8 dynamic quantization
+ torch._inductor.config.force_fuse_int_mm_with_mul = True
+ print("- Enabled fusion of int matmul with mul operations")
+
+
+
+ else:
+ # Standard loading for FP16/FP32
+ model = AutoModel.from_pretrained(self.config.model_path)
+ print("- Model loaded in standard precision")
+ print(f"- Model type: {type(model)}")
+
+ # Apply standard optimizations
+ # set default to half
+ import torch
+ torch.set_default_dtype(torch.bfloat16)
+ model = ModelOptimizer.optimize(model, self.config)
+ model = model.half()
+ # add torch compile
+ model = torch.compile(model)
+
+ # Final check to ensure model is not None
+ if model is None:
+ raise ValueError("Model is None after optimization")
+
+ print(f"- Final model type: {type(model)}")
+ return model
+
+ except Exception as e:
+ print(f"ERROR loading model: {str(e)}")
+ import traceback
+ traceback.print_exc()
+ raise
+
+ def _create_random_batch(self, batch_size: int) -> torch.Tensor:
+ return torch.randint(
+ 0, 1000,
+ (batch_size, self.config.seq_length),
+ device="cuda",
+ dtype=torch.long
+ )
+
+ def _run_inference(
+ self,
+ input_ids: torch.Tensor,
+ cuda_graph_wrapper: Optional[CUDAGraphWrapper] = None
+ ) -> Tuple[float, torch.Tensor]:
+ attention_mask = torch.ones_like(input_ids)
+
+ with torch.no_grad(), self.timer.timing():
+ if cuda_graph_wrapper is not None:
+ output = cuda_graph_wrapper(input_ids, attention_mask)
+ else:
+ output = self.model(input_ids=input_ids, attention_mask=attention_mask)
+
+ return self.timer.elapsed_time(), output
+
+ def run(self) -> Dict[int, Dict[str, float]]:
+ results = {}
+
+ # Reset peak memory stats
+ torch.cuda.reset_peak_memory_stats()
+
+ for batch_size in self.config.batch_sizes:
+ print(f"\nTesting batch size: {batch_size}")
+ times = []
+
+ # Get or create CUDA graph for this batch size
+ cuda_graph_wrapper = (
+ self.cuda_graphs.get_or_create(batch_size)
+ if self.cuda_graphs is not None
+ else None
+ )
+
+ # Pre-allocate input tensor
+ input_ids = self._create_random_batch(batch_size)
+ print(f"Input shape: {input_ids.shape}")
+
+ # Run benchmark
+ for i in tqdm(range(self.config.num_runs), desc=f"Batch size {batch_size}"):
+ try:
+ elapsed_time, output = self._run_inference(input_ids, cuda_graph_wrapper)
+ if i == 0: # Only print on first run
+ print(f"Output shape: {output.last_hidden_state.shape}")
+ times.append(elapsed_time)
+ except Exception as e:
+ print(f"Error during inference: {e}")
+ break
+
+ if not times:
+ print(f"No successful runs for batch size {batch_size}, skipping")
+ continue
+
+ # Calculate statistics
+ avg_time = np.mean(times)
+ std_time = np.std(times)
+ throughput = batch_size / avg_time
+
+ results[batch_size] = {
+ "avg_time": avg_time,
+ "std_time": std_time,
+ "throughput": throughput,
+ }
+
+ print(f"Avg Time: {avg_time:.4f}s ± {std_time:.4f}s")
+ print(f"Throughput: {throughput:.2f} sequences/second")
+
+ # Log memory usage
+ peak_memory_gb = torch.cuda.max_memory_allocated() / (1024 ** 3)
+ print(f"\nPeak GPU memory usage: {peak_memory_gb:.2f} GB")
+
+ # Add memory info to results
+ for batch_size in results:
+ results[batch_size]["peak_memory_gb"] = peak_memory_gb
+
+ return results
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Model Inference Benchmark")
+ parser.add_argument(
+ "--model_path",
+ type=str,
+ default="facebook/contriever",
+ help="Path to the model",
+ )
+ parser.add_argument(
+ "--batch_sizes",
+ type=str,
+ default="1,2,4,8,10,16,20,32,40,64,128,256,512,1024,2048,4096,8192",
+ help="Comma-separated list of batch sizes",
+ )
+ parser.add_argument(
+ "--seq_length",
+ type=int,
+ default=256,
+ help="Sequence length for input",
+ )
+ parser.add_argument(
+ "--num_runs",
+ type=int,
+ default=5,
+ help="Number of runs for each batch size",
+ )
+ parser.add_argument(
+ "--use_fp16",
+ action="store_true",
+ help="Enable FP16 inference",
+ )
+ parser.add_argument(
+ "--use_int4",
+ action="store_true",
+ help="Enable INT4 quantization using bitsandbytes",
+ )
+ parser.add_argument(
+ "--use_int8",
+ action="store_true",
+ help="Enable INT8 quantization for both activations and weights using bitsandbytes",
+ )
+ parser.add_argument(
+ "--use_cuda_graphs",
+ action="store_true",
+ help="Enable CUDA Graphs optimization",
+ )
+ parser.add_argument(
+ "--use_flash_attention",
+ action="store_true",
+ help="Enable Flash Attention 2 if available",
+ )
+ parser.add_argument(
+ "--use_linear8bitlt",
+ action="store_true",
+ help="Enable Linear8bitLt quantization for all linear layers",
+ )
+
+ args = parser.parse_args()
+
+ # Print arguments for debugging
+ print("\nCommand line arguments:")
+ for arg, value in vars(args).items():
+ print(f"- {arg}: {value}")
+
+ config = BenchmarkConfig(
+ model_path=args.model_path,
+ batch_sizes=[int(bs) for bs in args.batch_sizes.split(",")],
+ seq_length=args.seq_length,
+ num_runs=args.num_runs,
+ use_fp16=args.use_fp16,
+ use_int4=args.use_int4,
+ use_int8=args.use_int8, # Add this line
+ use_cuda_graphs=args.use_cuda_graphs,
+ use_flash_attention=args.use_flash_attention,
+ use_linear8bitlt=args.use_linear8bitlt,
+ )
+
+ # Print configuration for debugging
+ print("\nBenchmark configuration:")
+ for field, value in vars(config).items():
+ print(f"- {field}: {value}")
+
+ try:
+ benchmark = Benchmark(config)
+ results = benchmark.run()
+
+ # Save results to file
+ import json
+ import os
+
+ # Create results directory if it doesn't exist
+ os.makedirs("results", exist_ok=True)
+
+ # Generate filename based on configuration
+ precision_type = "int4" if config.use_int4 else "fp16" if config.use_fp16 else "fp32"
+ model_name = os.path.basename(config.model_path)
+ output_file = f"results/benchmark_{model_name}_{precision_type}.json"
+
+ # Save results
+ with open(output_file, "w") as f:
+ json.dump(
+ {
+ "config": {k: str(v) if isinstance(v, list) else v for k, v in vars(config).items()},
+ "results": {str(k): v for k, v in results.items()}
+ },
+ f,
+ indent=2
+ )
+ print(f"Results saved to {output_file}")
+
+ except Exception as e:
+ print(f"Benchmark failed: {e}")
+ import traceback
+ traceback.print_exc()
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/research/micro/embedd_micro_seq.py b/research/micro/embedd_micro_seq.py
new file mode 100644
index 0000000..b5cd6ce
--- /dev/null
+++ b/research/micro/embedd_micro_seq.py
@@ -0,0 +1,376 @@
+import argparse
+import time
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Tuple
+
+import numpy as np
+import torch
+from torch import nn
+from transformers import AutoModel
+from tqdm import tqdm
+from contextlib import contextmanager
+import math
+
+@dataclass
+class BenchmarkConfig:
+ model_path: str
+ batch_sizes: List[int]
+ seq_length: int
+ num_runs: int
+ use_fp16: bool = True
+ use_cuda_graphs: bool = False
+ use_flash_attention: bool = False
+ max_batch_size: int = 256 # Maximum batch size before splitting
+
+
+class CUDAGraphContainer:
+ """Container for managing CUDA graphs for different batch sizes."""
+
+ def __init__(self, model: nn.Module, seq_length: int, max_batch_size: int):
+ self.model = model
+ self.seq_length = seq_length
+ self.max_batch_size = max_batch_size
+ self.graphs: Dict[int, CUDAGraphWrapper] = {}
+
+ def get_or_create(self, batch_size: int) -> 'CUDAGraphWrapper':
+ # For CUDA graphs, we always use the actual batch size or max_batch_size
+ effective_batch_size = min(batch_size, self.max_batch_size)
+
+ if effective_batch_size not in self.graphs:
+ self.graphs[effective_batch_size] = CUDAGraphWrapper(
+ self.model, effective_batch_size, self.seq_length
+ )
+ return self.graphs[effective_batch_size]
+
+
+class CUDAGraphWrapper:
+ """Wrapper for CUDA graph capture and replay."""
+
+ def __init__(self, model: nn.Module, batch_size: int, seq_length: int):
+ self.model = model
+ self.static_input = self._create_random_batch(batch_size, seq_length)
+ self.static_attention_mask = torch.ones_like(self.static_input)
+
+ # Warm up
+ self._warmup()
+
+ # Capture graph
+ self.graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(self.graph):
+ self.static_output = self.model(
+ input_ids=self.static_input,
+ attention_mask=self.static_attention_mask
+ )
+
+ def _create_random_batch(self, batch_size: int, seq_length: int) -> torch.Tensor:
+ return torch.randint(
+ 0, 1000, (batch_size, seq_length),
+ device="cuda",
+ dtype=torch.long
+ )
+
+ def _warmup(self, num_warmup: int = 3):
+ with torch.no_grad():
+ for _ in range(num_warmup):
+ self.model(
+ input_ids=self.static_input,
+ attention_mask=self.static_attention_mask
+ )
+
+ def __call__(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ self.static_input.copy_(input_ids)
+ self.static_attention_mask.copy_(attention_mask)
+ self.graph.replay()
+ return self.static_output
+
+
+class ModelOptimizer:
+ """Applies various optimizations to the model."""
+
+ @staticmethod
+ def optimize(model: nn.Module, config: BenchmarkConfig) -> nn.Module:
+ print("\nApplying model optimizations:")
+
+ # Move to GPU
+ model = model.cuda()
+ print("- Model moved to GPU")
+
+ # FP16
+ if config.use_fp16:
+ model = model.half()
+ print("- Using FP16 precision")
+
+ # Check if using SDPA
+ if torch.version.cuda and float(torch.version.cuda[:3]) >= 11.6:
+ if hasattr(torch.nn.functional, 'scaled_dot_product_attention'):
+ print("- Using PyTorch SDPA (scaled_dot_product_attention)")
+ # No need to do anything as it's automatically enabled
+ else:
+ print("- PyTorch SDPA not available")
+
+ # Flash Attention
+ if config.use_flash_attention:
+ try:
+ from flash_attn.flash_attention import FlashAttention
+ print("- Flash Attention 2 available")
+ if hasattr(model.config, "attention_mode"):
+ model.config.attention_mode = "flash_attention_2"
+ print(" - Enabled Flash Attention 2 mode")
+ except ImportError:
+ print("- Flash Attention not available")
+
+ # Optimize LayerNorm
+ try:
+ num_layernorms = 0
+ for module in model.modules():
+ if isinstance(module, torch.nn.LayerNorm):
+ module.forward = torch.jit.script(module.forward)
+ num_layernorms += 1
+ if num_layernorms > 0:
+ print(f"- Optimized {num_layernorms} LayerNorm modules with TorchScript")
+ except Exception as e:
+ print(f"- LayerNorm optimization failed: {e}")
+
+ # Memory efficient attention
+ try:
+ from xformers.ops import memory_efficient_attention
+ model.enable_xformers_memory_efficient_attention()
+ print("- Enabled xformers memory efficient attention")
+ except (ImportError, AttributeError):
+ print("- Xformers not available")
+
+ model.eval()
+ print("- Model set to eval mode")
+
+ return model
+
+
+class Timer:
+ """Handles accurate GPU timing using CUDA events."""
+
+ def __init__(self):
+ self.start_event = torch.cuda.Event(enable_timing=True)
+ self.end_event = torch.cuda.Event(enable_timing=True)
+
+ @contextmanager
+ def timing(self):
+ self.start_event.record()
+ yield
+ self.end_event.record()
+ self.end_event.synchronize()
+
+ def elapsed_time(self) -> float:
+ return self.start_event.elapsed_time(self.end_event) / 1000 # ms to seconds
+
+
+class Benchmark:
+ """Main benchmark runner."""
+
+ def __init__(self, config: BenchmarkConfig):
+ self.config = config
+ self.model = self._load_model()
+ self.cuda_graphs = (
+ CUDAGraphContainer(self.model, config.seq_length, config.max_batch_size)
+ if config.use_cuda_graphs
+ else None
+ )
+ self.timer = Timer()
+
+ def _load_model(self) -> nn.Module:
+ print(f"Loading model from {self.config.model_path}...")
+ model = AutoModel.from_pretrained(self.config.model_path)
+ return ModelOptimizer.optimize(model, self.config)
+
+ def _create_random_batch(self, batch_size: int) -> torch.Tensor:
+ return torch.randint(
+ 0, 1000,
+ (batch_size, self.config.seq_length),
+ device="cuda",
+ dtype=torch.long
+ )
+
+ def _run_inference(
+ self,
+ input_ids: torch.Tensor,
+ cuda_graph_wrapper: Optional[CUDAGraphWrapper] = None
+ ) -> Tuple[float, torch.Tensor]:
+ attention_mask = torch.ones_like(input_ids)
+ original_batch_size = input_ids.shape[0]
+ print(f"Original input_ids shape: {input_ids.shape}")
+
+ # Split large batches to avoid OOM
+ max_batch_size = self.config.max_batch_size
+ if original_batch_size > max_batch_size:
+ print(f"Splitting batch of size {original_batch_size} into chunks of {max_batch_size}")
+ total_time = 0
+ outputs = []
+
+ with torch.no_grad():
+ for i in range(0, original_batch_size, max_batch_size):
+ end_idx = min(i + max_batch_size, original_batch_size)
+ batch_slice = input_ids[i:end_idx]
+ mask_slice = attention_mask[i:end_idx]
+
+ print(f"Processing chunk {i//max_batch_size + 1}: shape {batch_slice.shape}")
+
+ # Use CUDA graph if available (with the smaller batch size)
+ chunk_cuda_graph = None
+ if cuda_graph_wrapper is not None:
+ chunk_cuda_graph = self.cuda_graphs.get_or_create(batch_slice.shape[0])
+
+ with self.timer.timing():
+ if chunk_cuda_graph is not None:
+ chunk_output = chunk_cuda_graph(batch_slice, mask_slice)
+ else:
+ chunk_output = self.model(input_ids=batch_slice, attention_mask=mask_slice)
+
+ total_time += self.timer.elapsed_time()
+ outputs.append(chunk_output.last_hidden_state)
+
+ # Combine outputs
+ combined_output = torch.cat(outputs, dim=0)
+ print(f"Combined output shape: {combined_output.shape}")
+
+ # Create a wrapper object similar to model output to maintain consistency
+ class DummyOutput:
+ def __init__(self, hidden_states):
+ self.last_hidden_state = hidden_states
+
+ output = DummyOutput(combined_output)
+ return total_time, output
+ else:
+ # Process normally for small batches
+ with torch.no_grad(), self.timer.timing():
+ if cuda_graph_wrapper is not None:
+ output = cuda_graph_wrapper(input_ids, attention_mask)
+ else:
+ output = self.model(input_ids=input_ids, attention_mask=attention_mask)
+
+ print(f"Output shape: {output.last_hidden_state.shape}")
+ return self.timer.elapsed_time(), output
+
+ def run(self) -> Dict[int, Dict[str, float]]:
+ results = {}
+
+ for batch_size in self.config.batch_sizes:
+ print(f"\nTesting batch size: {batch_size}")
+ times = []
+
+ # Get or create CUDA graph for this batch size
+ cuda_graph_wrapper = None
+ if self.cuda_graphs is not None:
+ if batch_size <= self.config.max_batch_size:
+ cuda_graph_wrapper = self.cuda_graphs.get_or_create(batch_size)
+ else:
+ # For large batches, we'll use the max_batch_size graph in chunks
+ cuda_graph_wrapper = True # Just a flag to indicate we want to use CUDA graphs
+
+ # Pre-allocate input tensor
+ input_ids = self._create_random_batch(batch_size)
+
+ # Run benchmark
+ for run_idx in tqdm(range(self.config.num_runs), desc=f"Batch size {batch_size}"):
+ elapsed_time, _ = self._run_inference(input_ids, cuda_graph_wrapper)
+ times.append(elapsed_time)
+ print(f"Run {run_idx+1}: {elapsed_time:.4f}s")
+
+ # Calculate statistics
+ avg_time = np.mean(times)
+ std_time = np.std(times)
+ throughput = batch_size / avg_time
+
+ results[batch_size] = {
+ "avg_time": avg_time,
+ "std_time": std_time,
+ "throughput": throughput,
+ }
+
+ print(f"Avg Time: {avg_time:.4f}s ± {std_time:.4f}s")
+ print(f"Throughput: {throughput:.2f} sequences/second")
+
+ return results
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Model Inference Benchmark")
+ parser.add_argument(
+ "--model_path",
+ type=str,
+ default="facebook/contriever",
+ help="Path to the model",
+ )
+ parser.add_argument(
+ "--batch_sizes",
+ type=str,
+ default="1,2,4,8,16,32,64,128,256,512,1024,2048,4096",
+ help="Comma-separated list of batch sizes",
+ )
+ parser.add_argument(
+ "--seq_length",
+ type=int,
+ default=256,
+ help="Sequence length for input",
+ )
+ parser.add_argument(
+ "--num_runs",
+ type=int,
+ default=5,
+ help="Number of runs for each batch size",
+ )
+ parser.add_argument(
+ "--no_fp16",
+ action="store_true",
+ help="Disable FP16 inference",
+ )
+ parser.add_argument(
+ "--use_cuda_graphs",
+ action="store_true",
+ help="Enable CUDA Graphs optimization",
+ )
+ parser.add_argument(
+ "--use_flash_attention",
+ action="store_true",
+ help="Enable Flash Attention 2 if available",
+ )
+ parser.add_argument(
+ "--max_batch_size",
+ type=int,
+ default=256,
+ help="Maximum batch size before splitting to prevent OOM",
+ )
+
+ args = parser.parse_args()
+
+ config = BenchmarkConfig(
+ model_path=args.model_path,
+ batch_sizes=[int(bs) for bs in args.batch_sizes.split(",")],
+ seq_length=args.seq_length,
+ num_runs=args.num_runs,
+ use_fp16=not args.no_fp16,
+ use_cuda_graphs=args.use_cuda_graphs,
+ use_flash_attention=args.use_flash_attention,
+ max_batch_size=args.max_batch_size,
+ )
+
+ benchmark = Benchmark(config)
+ results = benchmark.run()
+
+ # Print overall summary
+ print("\n===== BENCHMARK SUMMARY =====")
+ print(f"Model: {config.model_path}")
+ print(f"Sequence Length: {config.seq_length}")
+ print(f"FP16: {config.use_fp16}")
+ print(f"CUDA Graphs: {config.use_cuda_graphs}")
+ print(f"Flash Attention: {config.use_flash_attention}")
+ print(f"Max Batch Size: {config.max_batch_size}")
+ print("\nResults:")
+
+ print("\nBatch Size | Avg Time (s) | Throughput (seq/s)")
+ print("-" * 50)
+ for bs in sorted(results.keys()):
+ r = results[bs]
+ print(f"{bs:^10} | {r['avg_time']:^12.4f} | {r['throughput']:^17.2f}")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/research/micro/int4benchmark.py b/research/micro/int4benchmark.py
new file mode 100644
index 0000000..764362d
--- /dev/null
+++ b/research/micro/int4benchmark.py
@@ -0,0 +1,218 @@
+import torch
+import torch.nn as nn
+import time
+import torch.nn.functional as F
+
+# Import necessary functions from the quantize.py file
+def get_group_qparams(w, n_bit=4, groupsize=128):
+ # needed for GPTQ with padding
+ if groupsize > w.shape[-1]:
+ groupsize = w.shape[-1]
+ assert groupsize > 1
+ assert w.shape[-1] % groupsize == 0
+ assert w.dim() == 2
+
+ to_quant = w.reshape(-1, groupsize)
+ assert torch.isnan(to_quant).sum() == 0
+
+ max_val = to_quant.amax(dim=1, keepdim=True)
+ min_val = to_quant.amin(dim=1, keepdim=True)
+ max_int = 2**n_bit - 1
+ scales = (max_val - min_val).clamp(min=1e-6) / max_int
+ zeros = min_val + scales * (2 ** (n_bit - 1))
+ return scales.to(torch.bfloat16).reshape(w.shape[0], -1), zeros.to(
+ torch.bfloat16
+ ).reshape(w.shape[0], -1)
+
+def pack_scales_and_zeros(scales, zeros):
+ assert scales.shape == zeros.shape
+ assert scales.dtype == torch.bfloat16
+ assert zeros.dtype == torch.bfloat16
+ return (
+ torch.cat(
+ [
+ scales.reshape(scales.size(0), scales.size(1), 1),
+ zeros.reshape(zeros.size(0), zeros.size(1), 1),
+ ],
+ 2,
+ )
+ .transpose(0, 1)
+ .contiguous()
+ )
+
+def group_quantize_tensor(w, n_bit=4, groupsize=128):
+ scales, zeros = get_group_qparams(w, n_bit, groupsize)
+ w_int32 = group_quantize_tensor_from_qparams(w, scales, zeros, n_bit, groupsize)
+ scales_and_zeros = pack_scales_and_zeros(scales, zeros)
+ return w_int32, scales_and_zeros
+
+def group_quantize_tensor_from_qparams(w, scales, zeros, n_bit=4, groupsize=128):
+ assert groupsize > 1
+ # needed for GPTQ single column quantize
+ if groupsize > w.shape[-1] and scales.shape[-1] == 1:
+ groupsize = w.shape[-1]
+
+ assert w.shape[-1] % groupsize == 0
+ assert w.dim() == 2
+
+ to_quant = w.reshape(-1, groupsize)
+ assert torch.isnan(to_quant).sum() == 0
+
+ scales = scales.reshape(-1, 1)
+ zeros = zeros.reshape(-1, 1)
+ min_val = zeros - scales * (2 ** (n_bit - 1))
+ max_int = 2**n_bit - 1
+ min_int = 0
+ w_int32 = (
+ to_quant.sub(min_val)
+ .div(scales)
+ .round()
+ .clamp_(min_int, max_int)
+ .to(torch.int32)
+ .reshape_as(w)
+ )
+
+ return w_int32
+
+def prepare_int4_weight_and_scales_and_zeros(weight_bf16, groupsize, inner_k_tiles):
+ weight_int32, scales_and_zeros = group_quantize_tensor(
+ weight_bf16, n_bit=4, groupsize=groupsize
+ )
+ weight_int4pack = torch.ops.aten._convert_weight_to_int4pack(weight_int32, inner_k_tiles)
+ return weight_int4pack, scales_and_zeros
+
+def linear_forward_int4(x, weight_int4pack, scales_and_zeros, out_features, groupsize):
+ origin_x_size = x.size()
+ x = x.reshape(-1, origin_x_size[-1])
+ c = torch.ops.aten._weight_int4pack_mm(x, weight_int4pack, groupsize, scales_and_zeros)
+ new_shape = origin_x_size[:-1] + (out_features,)
+ c = c.reshape(new_shape)
+ return c
+
+class WeightOnlyInt4Linear(torch.nn.Module):
+ __constants__ = ['in_features', 'out_features']
+ in_features: int
+ out_features: int
+ weight: torch.Tensor
+
+ def __init__(
+ self, in_features: int, out_features: int,
+ bias=False, device=None, dtype=None, groupsize: int = 128, inner_k_tiles: int = 8
+ ) -> None:
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.groupsize = groupsize
+ self.inner_k_tiles = inner_k_tiles
+
+ assert out_features % 8 == 0, "require out_features % 8 == 0"
+ assert in_features % (inner_k_tiles * 16) == 0, "require in_features % (innerKTiles * 16) == 0"
+ self.register_buffer(
+ "weight",
+ torch.empty((out_features // 8, in_features // (inner_k_tiles * 16), 32, inner_k_tiles // 2), dtype=torch.int32)
+ )
+ self.register_buffer(
+ "scales_and_zeros",
+ torch.empty((in_features // groupsize, out_features, 2), dtype=torch.bfloat16)
+ )
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ input = input.to(torch.bfloat16)
+ return linear_forward_int4(
+ input,
+ self.weight, self.scales_and_zeros, self.out_features, self.groupsize
+ )
+
+# Define dimensions that satisfy the requirements for INT4 quantization
+# in_features must be divisible by inner_k_tiles * 16
+# out_features must be divisible by 8
+in_features = 1024 # Must be divisible by inner_k_tiles * 16
+out_features = 2048 # Must be divisible by 8
+groupsize = 128
+inner_k_tiles = 8
+
+# Create models
+fp16_model = nn.Sequential(
+ nn.Linear(in_features, out_features, bias=False)
+)
+
+# Create INT4 model
+int4_model = nn.Sequential(
+ WeightOnlyInt4Linear(in_features, out_features, bias=False,
+ groupsize=groupsize, inner_k_tiles=inner_k_tiles)
+)
+
+# Quantize the weights and set up the INT4 model
+with torch.no_grad():
+ # Convert FP16 weights to INT4
+ fp16_weight = fp16_model[0].weight.data.to(torch.bfloat16)
+ weight_int4pack, scales_and_zeros = prepare_int4_weight_and_scales_and_zeros(
+ fp16_weight, groupsize, inner_k_tiles
+ )
+
+ # Set the quantized weights in the INT4 model
+ int4_model[0].weight.copy_(weight_int4pack)
+ int4_model[0].scales_and_zeros.copy_(scales_and_zeros)
+
+# Move models to GPU
+device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+fp16_model = fp16_model.to(device)
+int4_model = int4_model.to(device)
+
+# Create random input tensor
+batch_size = 1024
+input_tensor = torch.randn(batch_size, in_features, device=device)
+input_tensor_bf16 = input_tensor.to(torch.bfloat16)
+
+# Speed test function
+def speed_test(model, input_tensor, name, num_iterations=100):
+ # Warmup
+ for _ in range(10):
+ _ = model(input_tensor)
+
+ # Actual timing
+ torch.cuda.synchronize()
+ start_time = time.time()
+
+ for _ in range(num_iterations):
+ _ = model(input_tensor)
+
+ torch.cuda.synchronize()
+ end_time = time.time()
+
+ avg_time = (end_time - start_time) / num_iterations
+ print(f"{name} model: {avg_time:.6f} seconds per iteration")
+ return avg_time
+
+# Run speed tests
+with torch.no_grad(): # Disable gradient calculation for inference
+ print(f"Running benchmark with batch_size={batch_size}, in_features={in_features}, out_features={out_features}")
+ print(f"INT4 parameters: groupsize={groupsize}, inner_k_tiles={inner_k_tiles}")
+
+ fp16_time = speed_test(fp16_model, input_tensor_bf16, "FP16")
+ int4_time = speed_test(int4_model, input_tensor, "INT4")
+
+ # Calculate speedup
+ speedup = fp16_time / int4_time
+ print(f"INT4 is {speedup:.2f}x faster than FP16")
+
+ # Calculate memory savings
+ fp16_memory = fp16_model[0].weight.nelement() * fp16_model[0].weight.element_size()
+ int4_memory = (int4_model[0].weight.nelement() * int4_model[0].weight.element_size() +
+ int4_model[0].scales_and_zeros.nelement() * int4_model[0].scales_and_zeros.element_size())
+
+ memory_reduction = fp16_memory / int4_memory
+ print(f"Memory reduction: {memory_reduction:.2f}x ({fp16_memory/1024/1024:.2f} MB vs {int4_memory/1024/1024:.2f} MB)")
+
+ # Check accuracy
+ with torch.no_grad():
+ fp16_output = fp16_model(input_tensor_bf16)
+ int4_output = int4_model(input_tensor)
+
+ # Calculate error metrics
+ abs_error = torch.abs(fp16_output - int4_output)
+ rel_error = abs_error / (torch.abs(fp16_output) + 1e-7)
+
+ print(f"Mean absolute error: {abs_error.mean().item():.6f}")
+ print(f"Max absolute error: {abs_error.max().item():.6f}")
+ print(f"Mean relative error: {rel_error.mean().item():.6f}")
\ No newline at end of file
diff --git a/research/micro/int8.py b/research/micro/int8.py
new file mode 100644
index 0000000..289ffd8
--- /dev/null
+++ b/research/micro/int8.py
@@ -0,0 +1,83 @@
+import torch
+import nvmath.bindings.cublas
+import ctypes
+
+# 创建 CUBLAS 句柄
+handle = nvmath.bindings.cublas.create()
+
+# 准备数据 - 使用 uint8 类型,并确保内存连续
+m, n, k = 64, 32, 48
+a = (torch.rand(m, k, device="cuda") * 255).to(torch.uint8).contiguous()
+b = (torch.rand(k, n, device="cuda") * 255).to(torch.uint8).contiguous()
+c = torch.zeros(m, n, device="cuda", dtype=torch.uint8).contiguous()
+
+# 确保张量在 CUDA 上
+assert a.is_cuda and b.is_cuda and c.is_cuda
+# 确保张量是连续的
+assert a.is_contiguous() and b.is_contiguous() and c.is_contiguous()
+
+# 获取指针
+a_ptr = a.data_ptr()
+b_ptr = b.data_ptr()
+c_ptr = c.data_ptr()
+
+# 设置参数
+transa = 0 # CUBLAS_OP_N (不转置)
+transb = 0 # CUBLAS_OP_N (不转置)
+transc = 0 # CUBLAS_OP_N (不转置)
+
+# 设置偏置值
+a_bias = 0
+b_bias = 0
+c_bias = 0
+
+# 设置正确的 leading dimensions
+lda = k # A 的 leading dimension
+ldb = n # B 的 leading dimension
+ldc = n # C 的 leading dimension
+
+c_mult = 1
+c_shift = 0
+
+# 打印调试信息
+print(f"a shape: {a.shape}, a_ptr: {a_ptr}")
+print(f"b shape: {b.shape}, b_ptr: {b_ptr}")
+print(f"c shape: {c.shape}, c_ptr: {c_ptr}")
+
+try:
+ # 调用 uint8gemm_bias
+ nvmath.bindings.cublas.uint8gemm_bias(
+ handle,
+ transa, transb, transc,
+ m, n, k,
+ a_ptr, a_bias, lda,
+ b_ptr, b_bias, ldb,
+ c_ptr, c_bias, ldc,
+ c_mult, c_shift
+ )
+except Exception as e:
+ print(f"Error: {e}")
+ # 尝试使用 ctypes 转换指针
+ a_ptr_c = ctypes.c_void_p(a_ptr).value
+ b_ptr_c = ctypes.c_void_p(b_ptr).value
+ c_ptr_c = ctypes.c_void_p(c_ptr).value
+
+ print(f"Using ctypes: a_ptr: {a_ptr_c}, b_ptr: {b_ptr_c}, c_ptr: {c_ptr_c}")
+
+ # 再次尝试调用
+ nvmath.bindings.cublas.uint8gemm_bias(
+ handle,
+ transa, transb, transc,
+ m, n, k,
+ a_ptr_c, a_bias, lda,
+ b_ptr_c, b_bias, ldb,
+ c_ptr_c, c_bias, ldc,
+ c_mult, c_shift
+ )
+
+# 销毁 CUBLAS 句柄
+nvmath.bindings.cublas.destroy(handle)
+
+# 打印结果
+print("Result:")
+print(c)
\ No newline at end of file
diff --git a/research/micro/llm_compress.py b/research/micro/llm_compress.py
new file mode 100644
index 0000000..f0c6cdb
--- /dev/null
+++ b/research/micro/llm_compress.py
@@ -0,0 +1,23 @@
+from llmcompressor.modifiers.smoothquant import SmoothQuantModifier
+from llmcompressor.modifiers.quantization import GPTQModifier
+from llmcompressor import oneshot
+
+# Select quantization algorithm. In this case, we:
+# * apply SmoothQuant to make the activations easier to quantize
+# * quantize the weights to int8 with GPTQ (static per channel)
+# * quantize the activations to int8 (dynamic per token)
+recipe = [
+ SmoothQuantModifier(smoothing_strength=0.8),
+ GPTQModifier(scheme="W8A8", targets="Linear", ignore=["lm_head"]),
+]
+
+# Apply quantization using the built in open_platypus dataset.
+# * See examples for demos showing how to pass a custom calibration set
+oneshot(
+ model="facebook/contriever",
+ dataset="open_platypus",
+ recipe=recipe,
+ output_dir="contriever-INT4",
+ max_seq_length=2048,
+ num_calibration_samples=512,
+)
\ No newline at end of file
diff --git a/research/micro/nvmath_test.py b/research/micro/nvmath_test.py
new file mode 100644
index 0000000..9761c6d
--- /dev/null
+++ b/research/micro/nvmath_test.py
@@ -0,0 +1,41 @@
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED.
+#
+# SPDX-License-Identifier: Apache-2.0
+
+"""
+This example demonstrates basic matrix multiplication of FP8 tensors.
+
+In narrow-precision operations, quantization scales must be provided for each tensor. These
+scales are used to dequantize input operands and quantize the result. Without proper
+scaling, the results of FP8 operations will likely exceed the type's range.
+
+FP8 is only supported with cuBLAS 12.8 or newer and on devices with compute
+capability 8.9 or higher.
+"""
+
+import torch
+
+import nvmath
+
+# Prepare sample input data. Note that N, M and K must be divisible by 16 for FP8.
+# cuBLAS requires B to be column-major, so we first create a row-major tensor and then
+# transpose it.
+m, n, k = 64, 32, 48
+a = (torch.rand(m, k, device="cuda") * 10).type(torch.float8_e4m3fn)
+b = (torch.rand(n, k, device="cuda") * 10).type(torch.float8_e4m3fn).T
+
+# Prepare quantization scales. The scales must allow the result to fit within the dynamic
+# range of the data type used. Scales can be provided either as a dictionary or as a
+# MatmulQuantizationScales object. Note that scales are only allowed for FP8 operands.
+scales = {"a": 1, "b": 1, "d": 0.1}
+
+# Perform the multiplication. The result of the multiplication will be:
+# (scales.a * A) @ (scales.b * B) * scales.d
+result = nvmath.linalg.advanced.matmul(a, b, quantization_scales=scales)
+
+# Check how scaling helped to fit into the dynamic range of float8_e4m3fn type.
+result_without_scaling = nvmath.linalg.advanced.matmul(a, b, quantization_scales={"a": 1, "b": 1, "d": 1})
+print("Without scaling, most of the elements were clamped to the maximum value of float8_e4m3fn type (448):")
+print(result_without_scaling)
+print(f"\nWith D scale set to {scales['d']}, they were scaled down to fit into the dynamic range of float8_e4m3fn:")
+print(result)
\ No newline at end of file
diff --git a/research/micro/result.md b/research/micro/result.md
new file mode 100644
index 0000000..e69de29
diff --git a/research/micro/save_small_model.py b/research/micro/save_small_model.py
new file mode 100644
index 0000000..553ce07
--- /dev/null
+++ b/research/micro/save_small_model.py
@@ -0,0 +1,58 @@
+import os
+import torch
+from transformers import AutoModelForCausalLM, AutoTokenizer
+from pathlib import Path
+
+def save_model_in_pth_format(model_name, output_dir):
+ """
+ Download a model from Hugging Face and save it in PTH format
+ for use with quantization benchmarks.
+
+ Args:
+ model_name: Name of the model on Hugging Face
+ output_dir: Directory to save the model
+ """
+ print(f"Loading model {model_name}...")
+
+ # Create output directory if it doesn't exist
+ os.makedirs(output_dir, exist_ok=True)
+
+ # Load tokenizer and model
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ model = AutoModelForCausalLM.from_pretrained(
+ model_name,
+ torch_dtype=torch.bfloat16,
+ low_cpu_mem_usage=True
+ )
+
+ # Save tokenizer
+ tokenizer.save_pretrained(output_dir)
+
+ # Extract and save the model weights in PTH format
+ model_state_dict = model.state_dict()
+
+ # Save the model weights
+ model_path = Path(output_dir) / "model.pth"
+ torch.save(model_state_dict, model_path)
+
+ print(f"Model saved to {model_path}")
+
+ # Print model size information
+ param_count = sum(p.numel() for p in model.parameters())
+ model_size_mb = sum(p.numel() * p.element_size() for p in model.parameters()) / (1024 * 1024)
+
+ print(f"Model parameters: {param_count:,}")
+ print(f"Model size: {model_size_mb:.2f} MB")
+
+ return model_path
+
+if __name__ == "__main__":
+ # Use a small model for testing
+ model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
+ output_dir = "./tinyllama-1.1b-chat"
+
+ model_path = save_model_in_pth_format(model_name, output_dir)
+
+ print("\nYou can now use this model with the INT4 benchmark script.")
+ print("Example command:")
+ print(f"python int4benchmark.py --model_path {model_path}")
\ No newline at end of file
diff --git a/research/micro/transformer-batching-benchmark.ipynb b/research/micro/transformer-batching-benchmark.ipynb
new file mode 100644
index 0000000..2b1a384
--- /dev/null
+++ b/research/micro/transformer-batching-benchmark.ipynb
@@ -0,0 +1,677 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "cab91cfc",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/home/ubuntu/Power-RAG/.venv/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
+ " from .autonotebook import tqdm as notebook_tqdm\n"
+ ]
+ }
+ ],
+ "source": [
+ "import copy\n",
+ "import dataclasses\n",
+ "import os\n",
+ "import time\n",
+ "import pathlib\n",
+ "import itertools\n",
+ "import multiprocessing\n",
+ "import scipy\n",
+ "import numpy as np\n",
+ "import pandas as pd\n",
+ "import pickle\n",
+ "import gzip\n",
+ "import threading\n",
+ "import queue\n",
+ "import pytz\n",
+ "import traceback\n",
+ "from datetime import datetime\n",
+ "from tqdm.auto import tqdm, trange\n",
+ "from typing import Any\n",
+ "\n",
+ "import matplotlib.pyplot as plt\n",
+ "import matplotlib.ticker as mtick\n",
+ "%matplotlib inline\n",
+ "%config InlineBackend.figure_format='retina'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "8d24fbd7",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Sat Apr 12 00:10:05 2025 \n",
+ "+-----------------------------------------------------------------------------------------+\n",
+ "| NVIDIA-SMI 550.120 Driver Version: 550.120 CUDA Version: 12.4 |\n",
+ "|-----------------------------------------+------------------------+----------------------+\n",
+ "| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n",
+ "| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n",
+ "| | | MIG M. |\n",
+ "|=========================================+========================+======================|\n",
+ "| 0 NVIDIA A10G Off | 00000000:00:1E.0 Off | 0 |\n",
+ "| 0% 27C P8 15W / 300W | 4MiB / 23028MiB | 0% Default |\n",
+ "| | | N/A |\n",
+ "+-----------------------------------------+------------------------+----------------------+\n",
+ " \n",
+ "+-----------------------------------------------------------------------------------------+\n",
+ "| Processes: |\n",
+ "| GPU GI CI PID Type Process name GPU Memory |\n",
+ "| ID ID Usage |\n",
+ "|=========================================================================================|\n",
+ "| No running processes found |\n",
+ "+-----------------------------------------------------------------------------------------+\n"
+ ]
+ }
+ ],
+ "source": [
+ "!nvidia-smi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "538b2c11",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def benchmark(f, *, f_setup=None, min_repeat: int, min_secs: float, tqdm_kwargs: dict | None=None) -> np.ndarray:\n",
+ " latency = []\n",
+ " \n",
+ " # First run, ignore min_secs\n",
+ " if f_setup is not None:\n",
+ " f_setup()\n",
+ " st = time.perf_counter_ns()\n",
+ " f()\n",
+ " ed = time.perf_counter_ns()\n",
+ " latency.append((ed-st)/1e9)\n",
+ " \n",
+ " # Subsequent runs, until reaching both min_repeat and min_secs\n",
+ " min_nanos = int(min_secs * 1e9)\n",
+ " start_nanos = time.perf_counter_ns()\n",
+ " while True:\n",
+ " now_nanos = time.perf_counter_ns()\n",
+ " if len(latency) > min_repeat and now_nanos - start_nanos > min_nanos:\n",
+ " break\n",
+ " if f_setup is not None:\n",
+ " f_setup()\n",
+ " st = time.perf_counter_ns()\n",
+ " f()\n",
+ " ed = time.perf_counter_ns()\n",
+ " latency.append((ed-st)/1e9)\n",
+ " return np.array(latency)\n",
+ "\n",
+ "def tail_mean(xs, skip=0.2):\n",
+ " return xs[int(len(xs) * skip):].mean()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "02c9c9b1",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "<torch.autograd.grad_mode.set_grad_enabled at 0x7c5afc12b850>"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "import torch\n",
+ "torch.set_grad_enabled(False)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "3405fdc7",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nd_list = list(itertools.chain(itertools.product([12, 3], [256])))\n",
+ "seqlen_list = [256]\n",
+ "bs_list = [2,4,8,16,32,64,128,256,512,1024,2048]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "10dc981a",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[(12, 256), (3, 256)]\n",
+ "[256]\n",
+ "[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(nd_list)\n",
+ "print(seqlen_list)\n",
+ "print(bs_list)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "7e0ee385",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def benchmark_dense(out, nd_list, seqlen_list, bs_list):\n",
+ " seqlen_list = [1] + seqlen_list\n",
+ " total = len(list(itertools.product(nd_list, seqlen_list, bs_list)))\n",
+ " pbar = tqdm(total=total)\n",
+ " for (n, d), seqlen in reversed(list(itertools.product(nd_list, seqlen_list))):\n",
+ " h = n * d\n",
+ " maxbs = max(bs_list)\n",
+ " print(maxbs, n, d, seqlen)\n",
+ " cache = torch.empty(int(256e6 // 4), dtype=torch.int, device=\"cuda:0\")\n",
+ " X = torch.rand((maxbs, seqlen, h), dtype=torch.bfloat16, device=\"cuda:0\")\n",
+ " W = torch.rand((h, h), dtype=torch.bfloat16, device=\"cuda:0\")\n",
+ " torch.cuda.synchronize()\n",
+ " for bs in reversed(bs_list):\n",
+ " pbar.set_postfix(n=n, h=h, d=d, seqlen=seqlen, bs=bs)\n",
+ " def run():\n",
+ " torch.matmul(X[:bs], W)\n",
+ " torch.cuda.synchronize()\n",
+ " def clear_cache():\n",
+ " cache.zero_()\n",
+ " torch.cuda.synchronize()\n",
+ " latency = benchmark(run, f_setup=clear_cache, min_repeat=20, min_secs=2)\n",
+ " l = tail_mean(latency)\n",
+ " out.append({\n",
+ " \"n\": n,\n",
+ " \"d\": d,\n",
+ " \"seqlen\": seqlen,\n",
+ " \"bs\": bs,\n",
+ " \"latency\": l\n",
+ " })\n",
+ " pbar.update()\n",
+ " del cache, X, W\n",
+ " torch.cuda.empty_cache()\n",
+ " pbar.close()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "c206a502",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def benchmark_qk_init(out, nd_list, seqlen_list, bs_list):\n",
+ " total = len(list(itertools.product(nd_list, seqlen_list, bs_list)))\n",
+ " pbar = tqdm(total=total)\n",
+ " for (n, d), seqlen in reversed(list(itertools.product(nd_list, seqlen_list))):\n",
+ " h = n * d\n",
+ " try:\n",
+ " maxbs = max(b for b in bs_list if b*n*seqlen*d*2*2+b*n*seqlen**2*2 < 80e9)\n",
+ " except ValueError:\n",
+ " pbar.update(len(bs_list))\n",
+ " continue\n",
+ " cache = torch.empty(int(256e6 // 4), dtype=torch.int, device=\"cuda:0\")\n",
+ " Qmax = torch.rand((maxbs, n, seqlen, d), dtype=torch.bfloat16, device=\"cuda:0\")\n",
+ " Kmax = torch.rand((maxbs, n, seqlen, d), dtype=torch.bfloat16, device=\"cuda:0\")\n",
+ " torch.cuda.synchronize()\n",
+ " for bs in reversed(bs_list):\n",
+ " pbar.set_postfix(n=n, h=h, d=d, seqlen=seqlen, bs=bs)\n",
+ " if bs > maxbs:\n",
+ " pbar.update()\n",
+ " continue\n",
+ " Q = Qmax[:bs]\n",
+ " K = Kmax[:bs]\n",
+ " def run():\n",
+ " torch.bmm(Q.view(bs * n, seqlen, d), K.view(bs * n, seqlen, d).transpose(1, 2))\n",
+ " torch.cuda.synchronize()\n",
+ " def clear_cache():\n",
+ " cache.zero_()\n",
+ " torch.cuda.synchronize()\n",
+ " latency = benchmark(run, f_setup=clear_cache, min_repeat=20, min_secs=2)\n",
+ " l = tail_mean(latency)\n",
+ " out.append({\n",
+ " \"n\": n,\n",
+ " \"d\": d,\n",
+ " \"seqlen\": seqlen,\n",
+ " \"bs\": bs,\n",
+ " \"latency\": l\n",
+ " })\n",
+ " pbar.update()\n",
+ " del cache, Q, K, Qmax, Kmax\n",
+ " torch.cuda.empty_cache()\n",
+ " pbar.close()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "a3a2103c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def benchmark_qk_ar(out, nd_list, seqlen_list, bs_list):\n",
+ " total = len(list(itertools.product(nd_list, seqlen_list, bs_list)))\n",
+ " pbar = tqdm(total=total)\n",
+ " for (n, d), seqlen in reversed(list(itertools.product(nd_list, seqlen_list))):\n",
+ " h = n * d\n",
+ " try:\n",
+ " maxbs = max(b for b in bs_list if b*n*(1+seqlen)*d*2+b*n*seqlen*2 < 80e9)\n",
+ " except ValueError:\n",
+ " pbar.update(len(bs_list))\n",
+ " continue\n",
+ " cache = torch.empty(int(256e6 // 4), dtype=torch.int, device=\"cuda:0\")\n",
+ " Qmax = torch.rand((maxbs, n, 1, d), dtype=torch.bfloat16, device=\"cuda:0\")\n",
+ " Kmax = torch.rand((maxbs, n, seqlen, d), dtype=torch.bfloat16, device=\"cuda:0\")\n",
+ " torch.cuda.synchronize()\n",
+ " for bs in reversed(bs_list):\n",
+ " pbar.set_postfix(n=n, h=h, d=d, seqlen=seqlen, bs=bs)\n",
+ " if bs > maxbs:\n",
+ " pbar.update()\n",
+ " continue\n",
+ " Q = Qmax[:bs]\n",
+ " K = Kmax[:bs]\n",
+ " def run():\n",
+ " torch.bmm(Q.view(bs * n, 1, d), K.view(bs * n, seqlen, d).transpose(1, 2))\n",
+ " torch.cuda.synchronize()\n",
+ " def clear_cache():\n",
+ " cache.zero_()\n",
+ " torch.cuda.synchronize()\n",
+ " latency = benchmark(run, f_setup=clear_cache, min_repeat=20, min_secs=2)\n",
+ " l = tail_mean(latency)\n",
+ " out.append({\n",
+ " \"n\": n,\n",
+ " \"d\": d,\n",
+ " \"seqlen\": seqlen,\n",
+ " \"bs\": bs,\n",
+ " \"latency\": l\n",
+ " })\n",
+ " pbar.update()\n",
+ " del cache, Q, K, Qmax, Kmax\n",
+ " torch.cuda.empty_cache()\n",
+ " pbar.close()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "3aaad98a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data = {}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "18137de3",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ " 0%| | 0/22 [00:00<?, ?it/s]"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "100%|██████████| 22/22 [00:44<00:00, 2.04s/it, bs=2, d=256, h=3072, n=12, seqlen=256] \n"
+ ]
+ }
+ ],
+ "source": [
+ "db = []\n",
+ "benchmark_qk_init(db, nd_list, seqlen_list, bs_list)\n",
+ "data[\"qk_init\"] = db"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "26c76e15",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "100%|██████████| 22/22 [00:44<00:00, 2.01s/it, bs=2, d=256, h=3072, n=12, seqlen=256] \n"
+ ]
+ }
+ ],
+ "source": [
+ "db = []\n",
+ "benchmark_qk_ar(db, nd_list, seqlen_list, bs_list)\n",
+ "data[\"qk_ar\"] = db"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "313e36eb",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ " 0%| | 0/44 [00:00<?, ?it/s, bs=2048, d=256, h=768, n=3, seqlen=256]"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2048 3 256 256\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ " 25%|██▌ | 11/44 [00:22<01:06, 2.00s/it, bs=2048, d=256, h=768, n=3, seqlen=1] "
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2048 3 256 1\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ " 50%|█████ | 22/44 [00:44<00:44, 2.00s/it, bs=2048, d=256, h=3072, n=12, seqlen=256]"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2048 12 256 256\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ " 75%|███████▌ | 33/44 [01:07<00:22, 2.02s/it, bs=2048, d=256, h=3072, n=12, seqlen=1] "
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2048 12 256 1\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "100%|██████████| 44/44 [01:29<00:00, 2.03s/it, bs=2, d=256, h=3072, n=12, seqlen=1] \n"
+ ]
+ }
+ ],
+ "source": [
+ "db = []\n",
+ "benchmark_dense(db, nd_list, seqlen_list, bs_list)\n",
+ "data[\"dense\"] = db"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "50c37959",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "with gzip.open(\"data/20230516-transformer-batching1.pkl.gz\", \"wb\") as f:\n",
+ " pickle.dump(data, f)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "828ddb54",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "df_dense = (\n",
+ " pd.DataFrame.from_dict(data[\"dense\"])\n",
+ " .assign(h=lambda x: x[\"n\"] * x[\"d\"])\n",
+ " .assign(flop=lambda x: (x[\"bs\"] * x[\"seqlen\"] * x[\"h\"]**2) * 2)\n",
+ " .assign(io=lambda x: (x[\"bs\"]*x[\"seqlen\"]*x[\"h\"]*2 + x[\"h\"]**2) * 2/x['latency']/1e9)\n",
+ " .assign(intensity=lambda x: x[\"flop\"] / x[\"io\"])\n",
+ " .assign(throughput=lambda x: x[\"flop\"] / x[\"latency\"])\n",
+ " .assign(series=\"dense\")\n",
+ ")\n",
+ "df_qk_init = (\n",
+ " pd.DataFrame.from_dict(data[\"qk_init\"])\n",
+ " .assign(h=lambda x: x[\"n\"] * x[\"d\"])\n",
+ " .assign(flop=lambda x: (x[\"bs\"]*x[\"n\"]*x[\"d\"]*x[\"seqlen\"]**2) * 2)\n",
+ " .assign(io=lambda x: (x[\"bs\"]*x[\"n\"]*(x[\"seqlen\"]*x[\"d\"]*2 + x[\"seqlen\"]**2)) * 2/x['latency']/1e9)\n",
+ " .assign(intensity=lambda x: x[\"flop\"] / x[\"io\"])\n",
+ " .assign(throughput=lambda x: x[\"flop\"] / x[\"latency\"])\n",
+ " .assign(series=\"qk_init\")\n",
+ ")\n",
+ "df_qk_ar = (\n",
+ " pd.DataFrame.from_dict(data[\"qk_ar\"])\n",
+ " .assign(h=lambda x: x[\"n\"] * x[\"d\"])\n",
+ " .assign(flop=lambda x: (x[\"bs\"]*x[\"n\"]*x[\"d\"]*x[\"seqlen\"]) * 2)\n",
+ " .assign(io=lambda x: (x[\"bs\"]*x[\"n\"]*(x[\"d\"] + x[\"seqlen\"]*x[\"d\"] + x[\"seqlen\"])) * 2)\n",
+ " .assign(intensity=lambda x: x[\"flop\"] / x[\"io\"])\n",
+ " .assign(throughput=lambda x: x[\"bs\"] / x[\"latency\"])\n",
+ " .assign(series=\"qk_ar\")\n",
+ ")\n",
+ "pd.concat([df_dense, df_qk_init, df_qk_ar]).to_csv(\"data/transformer-batching-microbenchmarks.csv\", index=False)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "id": "c296a395",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "<module 'pandas' from '/home/ubuntu/Power-RAG/.venv/lib/python3.10/site-packages/pandas/__init__.py'>"
+ ]
+ },
+ "execution_count": 39,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pd\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a25cdd5a",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "63b8a531",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import transformers"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "af90eff1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def _gen_opt_cfg(n_layers: int, d_model: int, n_heads: int, **kwargs) -> transformers.OPTConfig:\n",
+ " return transformers.OPTConfig(\n",
+ " num_hidden_layers=n_layers,\n",
+ " hidden_size=d_model,\n",
+ " ffn_dim=d_model*4,\n",
+ " num_attention_heads=n_heads,\n",
+ " **kwargs\n",
+ " )\n",
+ "optcfg = {\n",
+ " # https://arxiv.org/pdf/2205.01068.pdf Table 2.1\n",
+ " \"125m\": _gen_opt_cfg(12, 768, 12),\n",
+ " \"350m\": _gen_opt_cfg(24, 1024, 16),\n",
+ " \"760m\": _gen_opt_cfg(24, 1536, 16),\n",
+ " \"1.3b\": _gen_opt_cfg(24, 2048, 32),\n",
+ " \"2.7b\": _gen_opt_cfg(32, 2560, 32),\n",
+ " \"6.7b\": _gen_opt_cfg(32, 4096, 32),\n",
+ " \"13b\": _gen_opt_cfg(40, 5120, 40),\n",
+ " \"13b_1layer\": _gen_opt_cfg(1, 5120, 40),\n",
+ " \"30b\": _gen_opt_cfg(48, 7168, 56),\n",
+ " \"66b\": _gen_opt_cfg(64, 9216, 72),\n",
+ " \"175b\": _gen_opt_cfg(96, 12288, 96),\n",
+ " \"175b_1layer\": _gen_opt_cfg(1, 12288, 96),\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "5b9ebbec",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def greedy_sample_one(model, input_ids, attention_mask=None, past_key_values=None):\n",
+ " bs, tgt_len = input_ids.shape\n",
+ " if past_key_values is not None:\n",
+ " _bs, _num_heads, src_len, _head_dims = past_key_values[0][0].shape\n",
+ " assert bs == _bs\n",
+ " else:\n",
+ " src_len = 0\n",
+ " if attention_mask is None:\n",
+ " attention_mask = torch.ones((bs, src_len + tgt_len), device=model.device)\n",
+ " ret = model(\n",
+ " input_ids=input_ids,\n",
+ " attention_mask=attention_mask,\n",
+ " past_key_values=past_key_values,\n",
+ " use_cache=True, output_hidden_states=False, return_dict=True,\n",
+ " )\n",
+ " return ret\n",
+ "\n",
+ "def time_greedy_generate(model, input_ids, new_tokens):\n",
+ " ts = []\n",
+ " output = input_ids\n",
+ " past_key_values = None\n",
+ " cache = torch.empty(int(256e6 // 4), dtype=torch.int, device=model.device)\n",
+ " attention_mask = torch.ones(input_ids.shape, device=model.device) \n",
+ " for _ in range(new_tokens):\n",
+ " cache.zero_()\n",
+ " torch.cuda.synchronize()\n",
+ " st = time.perf_counter_ns()\n",
+ " \n",
+ " ret = greedy_sample_one(model, input_ids, attention_mask, past_key_values)\n",
+ " input_ids = torch.argmax(ret.logits[:, -1, :], axis=-1)[:, None]\n",
+ " output = torch.cat([output, input_ids], axis=1)\n",
+ " past_key_values = ret.past_key_values\n",
+ " attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1)\n",
+ " \n",
+ " torch.cuda.synchronize()\n",
+ " ed = time.perf_counter_ns()\n",
+ " ts.append((ed-st)/1e9)\n",
+ " return np.array(ts)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "fc92f940",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "opt_config = optcfg[\"6.7b\"]\n",
+ "\n",
+ "torch.set_default_dtype(torch.bfloat16)\n",
+ "with transformers.modeling_utils.no_init_weights():\n",
+ " model = transformers.models.opt.OPTForCausalLM(opt_config).to(\"cuda\")\n",
+ "torch.set_default_dtype(torch.float32)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c19fa396",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "db = {}\n",
+ "input_tokens = 200\n",
+ "new_tokens = 500\n",
+ "for bs in tqdm(list(itertools.chain(range(1, 8), range(8, 16, 2), [16]))):\n",
+ " x = torch.randint(1000, 10000, (bs, input_tokens), device=model.device)\n",
+ " stack = []\n",
+ " for _ in range(10):\n",
+ " l = time_greedy_generate(model, x, new_tokens=new_tokens)\n",
+ " stack.append(l)\n",
+ " db[bs] = np.median(np.stack(stack), axis=0)\n",
+ " del x\n",
+ " torch.cuda.empty_cache()\n",
+ "del model\n",
+ "torch.cuda.empty_cache()\n",
+ "\n",
+ "with gzip.open(\"data/20230516-e2e-text-generation-batch.pkl.gz\", \"wb\") as f:\n",
+ " pickle.dump(db, f)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": ".venv",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.12"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/research/paper_plot/acc_fig.py b/research/paper_plot/acc_fig.py
new file mode 100644
index 0000000..7afbb42
--- /dev/null
+++ b/research/paper_plot/acc_fig.py
@@ -0,0 +1,165 @@
+import matplotlib.pyplot as plt
+import numpy as np
+import pandas as pd
+
+# Set plot parameters
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 1.5
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True
+
+# Path settings
+FIGURE_PATH = "./paper_plot/figures"
+
+# Load accuracy data
+acc_data = pd.read_csv("./paper_plot/data/acc.csv")
+
+# Create figure with 4 subplots (one for each dataset)
+fig, axs = plt.subplots(1, 4)
+fig.set_size_inches(9, 2.5)
+
+# Reduce the spacing between subplots
+# plt.subplots_adjust(wspace=0.2) # Reduced from 0.3 to 0.1
+
+# Define datasets and their columns
+datasets = ["NQ", "TriviaQA", "GPQA", "HotpotQA"]
+metrics = ["Exact Match", "F1"]
+
+# Define bar settings - make bars thicker
+# total_width, n = 0.9, 3 # increased total width and n for three models
+# width = total_width / n
+# The 'width' variable below now defines the distance between the centers of adjacent bars within a group.
+# It's also used as the base for calculating the actual plotted bar width.
+# Original 2 bars had centers 1.0 apart. For 3 bars, we need a smaller distance.
+# A value of 0.64 for distance between centers, with a scaling factor of 0.8 for bar width,
+# results in an actual bar width of ~0.51, and a group span of ~1.79, similar to original's ~1.76.
+n = 3 # Number of models
+width = 0.64 # Distance between centers of adjacent bars in a group
+bar_width_plotting_factor = 0.8 # Bar takes 80% of the space defined by 'width'
+
+# Colors and hatches
+edgecolors = ["dimgrey", "#63B8B6", "tomato"] # Added color for PQ 5
+hatches = ["/////", "xxxxx", "\\\\\\\\\\"] # Added hatch for PQ 5
+labels = ["BM25", "PQ Compressed", "Ours"] # Added PQ 5
+
+# Create plots for each dataset
+for i, dataset in enumerate(datasets):
+ ax = axs[i]
+
+ # Get data for this dataset and convert to percentages
+ em_values = [
+ acc_data.loc[0, f"{dataset} Exact Match"] * 100,
+ acc_data.loc[1, f"{dataset} Exact Match"] * 100,
+ acc_data.loc[2, f"{dataset} Exact Match"] * 100 # Added PQ 5 EM data
+ ]
+ f1_values = [
+ acc_data.loc[0, f"{dataset} F1"] * 100,
+ acc_data.loc[1, f"{dataset} F1"] * 100,
+ acc_data.loc[2, f"{dataset} F1"] * 100 # Added PQ 5 F1 data
+ ]
+
+ # Define x positions for bars
+ # For EM: center - width, center, center + width
+ # For F1: center - width, center, center + width
+ group_centers = [1.0, 3.0] # Centers for EM and F1 groups
+ bar_offsets = [-width, 0, width]
+
+ # Plot all bars on the same axis
+ for metric_idx, metric_group_center in enumerate(group_centers):
+ values_to_plot = em_values if metric_idx == 0 else f1_values
+ for j, model_label in enumerate(labels):
+ x_pos = metric_group_center + bar_offsets[j]
+ bar_value = values_to_plot[j]
+
+ ax.bar(
+ x_pos,
+ bar_value,
+ width=width * bar_width_plotting_factor, # Use the new factor for bar width
+ color="white",
+ edgecolor=edgecolors[j],
+ hatch=hatches[j],
+ linewidth=1.5,
+ label=model_label if i == 0 and metric_idx == 0 else None # Label only once
+ )
+
+ # Add value on top of bar
+ ax.text(x_pos, bar_value + (0.1 if dataset == "GPQA" else 0.1),
+ f"{bar_value:.1f}", ha='center', va='bottom',
+ fontsize=9, fontweight='bold') # Reduced fontsize for text on bars
+
+ # Set x-ticks and labels
+ ax.set_xticks(group_centers) # Position ticks at the center of each group
+ xticklabels = ax.set_xticklabels(metrics, fontsize=12)
+
+ # Now, shift these labels slightly to the right
+ # Adjust this value to control the amount of shift (in data coordinates)
+ # Given your group_centers are 1.0 and 3.0, a small value like 0.05 to 0.15 might be appropriate.
+ # horizontal_shift = 0.7 # Try adjusting this value
+
+ # for label in xticklabels:
+ # # Get the current x position (which is the tick location)
+ # current_x_pos = label.get_position()[0]
+ # # Set the new x position by adding the shift
+ # label.set_position((current_x_pos + horizontal_shift, label.get_position()[1]))
+ # # Ensure the label remains horizontally centered on this new x position
+ # # (set_xticklabels defaults to 'center', so this re-affirms it if needed)
+ # label.set_horizontalalignment('center')
+
+ # Set title
+ ax.set_title(dataset, fontsize=14)
+
+ # Set y-label for all subplots
+ if i == 0:
+ ax.set_ylabel("Accuracy (\%)", fontsize=12, fontweight="bold")
+ else:
+ # Hide y-tick labels for non-first subplots to save space
+ ax.tick_params(axis='y', labelsize=10)
+
+ # Set y-limits based on data range
+ all_values = em_values + f1_values
+ max_val = max(all_values)
+ min_val = min(all_values)
+
+ # Special handling for GPQA which has very low values
+ if dataset == "GPQA":
+ ax.set_ylim(0, 10.0) # Set a fixed range for GPQA
+ else:
+ # Reduce the extra space above the bars
+ ax.set_ylim(min_val * 0.9, max_val * 1.1) # Adjusted upper limit for text
+
+ # Format y-ticks as percentages
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda y, _: ' {:.0f}'.format(y)))
+
+ # Set x-limits to properly space the bars with less blank space
+ # ax.set_xlim(group_centers[0] - total_width, group_centers[1] + total_width)
+ # Set xlim to be similar to original (0,4) for group_centers (1,3) => margin of 1.0
+ ax.set_xlim(group_centers[0] - 1.0, group_centers[1] + 1.0)
+
+ # Add a box around the subplot
+ # for spine in ax.spines.values():
+ # spine.set_visible(True)
+ # spine.set_linewidth(1.0)
+
+ # Add legend to first subplot
+ if i == 0:
+ ax.legend(
+ bbox_to_anchor=(2.21, 1.35), # Adjusted anchor if needed
+ ncol=3, # Changed to 3 columns for three labels
+ loc="upper center",
+ labelspacing=0.1,
+ edgecolor="black",
+ facecolor="white",
+ framealpha=1,
+ shadow=False,
+ fancybox=False,
+ handlelength=1.0,
+ handletextpad=0.6,
+ columnspacing=0.8,
+ prop={"weight": "bold", "size": 12},
+ )
+
+# Save figure with tight layout but no additional padding
+plt.savefig(FIGURE_PATH + "/accuracy_comparison.pdf", bbox_inches='tight', pad_inches=0.05)
+plt.show()
\ No newline at end of file
diff --git a/research/paper_plot/analyze_visits.py b/research/paper_plot/analyze_visits.py
new file mode 100644
index 0000000..940d1d8
--- /dev/null
+++ b/research/paper_plot/analyze_visits.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+# -*- coding:utf-8 -*-
+# Motto: Were It to Benefit My Country, I Would Lay Down My Life!
+# \file: /hnsw_degree_visit_plot_binned_academic.py
+# \brief: Generates a binned bar plot of HNSW node average per-query visit probability
+# per degree bin, styled for academic publications, with caching.
+# Author: raphael hao (Original script by user, styling and caching adapted by Gemini)
+
+# %%
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+import re
+from collections import Counter
+import os # For robust filepath manipulation
+import math # For calculating scaling factor
+import pickle # For caching data
+
+# %%
+# --- Matplotlib parameters for academic paper style (from reference) ---
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 1.5
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True # Use LaTeX for text rendering (if available)
+
+# --- Define styles from reference ---
+edgecolors_ref = ["dimgrey", "#63B8B6", "tomato", "silver", "slategray"]
+
+# %%
+# --- File Paths ---
+degree_file = '/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/degree_distribution.txt'
+visit_log_file = './re.log'
+output_image_file = './paper_plot/figures/hnsw_visit_count_per_degree_corrected.pdf'
+# --- CACHE FILE PATH: Keep this consistent ---
+CACHE_FILE_PATH = './binned_plot_data_cache.pkl'
+
+# --- Configuration ---
+# Set to True to bypass cache and force recomputation.
+# Otherwise, delete CACHE_FILE_PATH manually to force recomputation.
+FORCE_RECOMPUTE = False
+NUMBER_OF_QUERIES = 1000.0 # Number of queries the visit_counts are based on
+
+# Create directory for figures if it doesn't exist
+output_dir = os.path.dirname(output_image_file)
+if output_dir and not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+ print(f"Created directory: {output_dir}")
+
+# %%
+# --- Attempt to load data from cache or compute ---
+df_plot_data = None
+bin_size_for_plot = None # Will hold the bin_size associated with df_plot_data
+
+if not FORCE_RECOMPUTE and os.path.exists(CACHE_FILE_PATH):
+ try:
+ with open(CACHE_FILE_PATH, 'rb') as f:
+ cache_content = pickle.load(f)
+ df_plot_data = cache_content['data']
+ bin_size_for_plot = cache_content['bin_size']
+ # Basic validation of cached data
+ # Expecting 'average_visit_count_per_node_in_bin' (raw average over NUMBER_OF_QUERIES)
+ if not isinstance(df_plot_data, pd.DataFrame) or \
+ 'degree_bin_label' not in df_plot_data.columns or \
+ 'average_visit_count_per_node_in_bin' not in df_plot_data.columns or \
+ not isinstance(bin_size_for_plot, int):
+ print("Cached data is not in the expected format or missing 'average_visit_count_per_node_in_bin'. Recomputing.")
+ df_plot_data = None # Invalidate to trigger recomputation
+ else:
+ print(f"Successfully loaded binned data from cache: {CACHE_FILE_PATH}")
+
+ # --- Modify the label loaded from cache for display purpose ---
+ # This modification only happens when data is loaded from cache and meets specific conditions.
+ # Assumption: If the bin_size_for_plot in cache is 5,
+ # then the original label "0-4" actually represents nodes with degree 1-4 (because you guarantee no 0-degree nodes).
+ if df_plot_data is not None and 'degree_bin_label' in df_plot_data.columns and bin_size_for_plot == 5:
+ # Check if "0-4" label exists
+ if '0-4' in df_plot_data['degree_bin_label'].values:
+ # Use .loc to ensure the modification is on the original DataFrame
+ df_plot_data.loc[df_plot_data['degree_bin_label'] == '0-4', 'degree_bin_label'] = '1-4'
+ print("Modified degree_bin_label from '0-4' to '1-4' for display purpose.")
+ except Exception as e:
+ print(f"Error loading from cache: {e}. Recomputing.")
+ df_plot_data = None # Invalidate to trigger recomputation
+
+if df_plot_data is None:
+ print("Cache not found, invalid, or recompute forced. Computing data from scratch...")
+ # --- 1. Read Degree Distribution File ---
+ degrees_data = []
+ try:
+ with open(degree_file, 'r') as f:
+ for i, line in enumerate(f):
+ line_stripped = line.strip()
+ if line_stripped:
+ degrees_data.append({'node_id': i, 'degree': int(line_stripped)})
+ except FileNotFoundError:
+ print(f"Error: Degree file '{degree_file}' not found. Using dummy data for degrees.")
+ degrees_data = [{'node_id': i, 'degree': (i % 20) + 1 } for i in range(200)]
+ degrees_data.extend([{'node_id': 200+i, 'degree': i} for i in range(58, 67)]) # For 60-64 bin
+ degrees_data.extend([{'node_id': 300+i, 'degree': (i % 5)+1} for i in range(10)]) # Low degrees
+ degrees_data.extend([{'node_id': 400+i, 'degree': 80 + (i%5)} for i in range(10)]) # High degrees
+
+
+ if not degrees_data:
+ print(f"Critical Error: No data loaded or generated for degrees. Exiting.")
+ exit()
+ df_degrees = pd.DataFrame(degrees_data)
+ print(f"Successfully loaded/generated {len(df_degrees)} degree entries.")
+
+ # --- 2. Read Visit Log File and Count Frequencies ---
+ visit_counts = Counter()
+ node_id_pattern = re.compile(r"Vis(i)?ted node: (\d+)")
+ try:
+ with open(visit_log_file, 'r') as f_log:
+ for line_num, line in enumerate(f_log, 1):
+ match = node_id_pattern.search(line)
+ if match:
+ try:
+ node_id = int(match.group(2))
+ visit_counts[node_id] += 1 # Increment visit count for the node
+ except ValueError:
+ print(f"Warning: Non-integer node_id in log '{visit_log_file}' line {line_num}: {line.strip()}")
+ except FileNotFoundError:
+ print(f"Warning: Visit log file '{visit_log_file}' not found. Using dummy visit counts.")
+ if not df_degrees.empty:
+ for node_id_val in df_degrees['node_id'].sample(frac=0.9, random_state=1234): # Seed for reproducibility
+ degree_val = df_degrees[df_degrees['node_id'] == node_id_val]['degree'].iloc[0]
+ # Generate visit counts to test different probability magnitudes
+ if node_id_val % 23 == 0: # Very low probability
+ lambda_val = 0.0005 * (100 / (max(1,degree_val) + 1)) # avg visits over 1k queries
+ elif node_id_val % 11 == 0: # Low probability
+ lambda_val = 0.05 * (100 / (max(1,degree_val) + 1))
+ elif node_id_val % 5 == 0: # Moderate probability
+ lambda_val = 2.5 * (100 / (max(1,degree_val) + 1))
+ else: # Higher probability (but still < 1000 visits for a single node usually)
+ lambda_val = 50 * (100 / (max(1,degree_val) + 1))
+ visit_counts[node_id_val] = np.random.poisson(lambda_val)
+ if visit_counts[node_id_val] < 0: visit_counts[node_id_val] = 0
+
+ if not visit_counts:
+ print(f"Warning: No visit data parsed/generated. Plot may show zero visits.")
+ df_visits = pd.DataFrame(columns=['node_id', 'visit_count'])
+ else:
+ df_visits_list = [{'node_id': nid, 'visit_count': count} for nid, count in visit_counts.items()]
+ df_visits = pd.DataFrame(df_visits_list)
+ print(f"Parsed/generated {len(df_visits)} unique visited nodes, totaling {sum(visit_counts.values())} visits (simulated over {NUMBER_OF_QUERIES} queries).")
+
+ # --- 3. Merge Degree Data with Visit Data ---
+ df_merged = pd.merge(df_degrees, df_visits, on='node_id', how='left')
+ df_merged['visit_count'] = df_merged['visit_count'].fillna(0).astype(float) # visit_count is total over NUMBER_OF_QUERIES
+ print(f"Merged data contains {len(df_merged)} entries.")
+
+ # --- 5. Binning Degrees and Calculating Average Visit Count per Node in Bin (over NUMBER_OF_QUERIES) ---
+ current_bin_size = 5
+ bin_size_for_plot = current_bin_size
+
+ if not df_degrees.empty:
+ print(f"\nBinning degrees into groups of {current_bin_size} for average visit count calculation...")
+
+ df_merged_with_bins = df_merged.copy()
+ df_merged_with_bins['degree_bin_start'] = (df_merged_with_bins['degree'] // current_bin_size) * current_bin_size
+
+ df_binned_analysis = df_merged_with_bins.groupby('degree_bin_start').agg(
+ total_visit_count_in_bin=('visit_count', 'sum'),
+ node_count_in_bin=('node_id', 'nunique')
+ ).reset_index()
+
+ # This is the average number of times a node in this bin was visited over NUMBER_OF_QUERIES queries.
+ # This value is what gets cached.
+ df_binned_analysis['average_visit_count_per_node_in_bin'] = 0.0
+ df_binned_analysis.loc[df_binned_analysis['node_count_in_bin'] > 0, 'average_visit_count_per_node_in_bin'] = \
+ df_binned_analysis['total_visit_count_in_bin'] / df_binned_analysis['node_count_in_bin']
+
+ df_binned_analysis['degree_bin_label'] = df_binned_analysis['degree_bin_start'].astype(str) + '-' + \
+ (df_binned_analysis['degree_bin_start'] + current_bin_size - 1).astype(str)
+
+ bin_to_drop_label = '60-64'
+ original_length = len(df_binned_analysis)
+ df_plot_data_intermediate = df_binned_analysis[df_binned_analysis['degree_bin_label'] != bin_to_drop_label].copy()
+ if len(df_plot_data_intermediate) < original_length:
+ print(f"\nManually dropped the bin: '{bin_to_drop_label}'")
+ else:
+ print(f"\nNote: Bin '{bin_to_drop_label}' not found for dropping or already removed.")
+
+ df_plot_data = df_plot_data_intermediate
+
+ print(f"\nBinned data (average visit count per node in bin over {NUMBER_OF_QUERIES} queries) for plotting prepared:")
+ print(df_plot_data[['degree_bin_label', 'average_visit_count_per_node_in_bin']].head())
+
+ if df_plot_data is not None and not df_plot_data.empty:
+ try:
+ with open(CACHE_FILE_PATH, 'wb') as f:
+ pickle.dump({'data': df_plot_data, 'bin_size': bin_size_for_plot}, f)
+ print(f"Saved computed binned data to cache: {CACHE_FILE_PATH}")
+ except Exception as e:
+ print(f"Error saving data to cache: {e}")
+ elif df_plot_data is None or df_plot_data.empty:
+ print("Computed data for binned plot is empty, not saving to cache.")
+ else:
+ print("Degree data (df_degrees) is empty. Cannot perform binning.")
+ df_plot_data = pd.DataFrame()
+ bin_size_for_plot = current_bin_size
+
+# %%
+# --- 6. Plotting (Binned Bar Chart - Academic Style) ---
+
+if df_plot_data is not None and not df_plot_data.empty and 'average_visit_count_per_node_in_bin' in df_plot_data.columns:
+ base_name, ext = os.path.splitext(output_image_file)
+ # --- OUTPUT PDF FILE NAME: Keep this consistent ---
+ binned_output_image_file = base_name + ext
+
+ fig, ax = plt.subplots(figsize=(6, 2.5)) # Adjusted figure size
+
+ df_plot_data_plotting = df_plot_data.copy()
+ # Calculate per-query probability: (avg visits over N queries) / N
+ df_plot_data_plotting['per_query_visit_probability'] = \
+ df_plot_data_plotting['average_visit_count_per_node_in_bin'] / NUMBER_OF_QUERIES
+
+ max_probability = df_plot_data_plotting['per_query_visit_probability'].max()
+
+ y_axis_values_to_plot = df_plot_data_plotting['per_query_visit_probability']
+ y_axis_label = r"Per-Query Node Visit Probability in Bin" # Base label
+
+ apply_scaling_to_label_and_values = False # Initialize flag
+ exponent_for_label_display = 0 # Initialize exponent
+
+ if pd.notna(max_probability) and max_probability > 0:
+ potential_exponent = math.floor(math.log10(max_probability))
+
+ if potential_exponent <= -4 or potential_exponent >= 0:
+ apply_scaling_to_label_and_values = True
+ exponent_for_label_display = potential_exponent
+ # No specific adjustment for potential_exponent >=0 here, it's handled by the general logic.
+
+ if apply_scaling_to_label_and_values:
+ y_axis_label = rf"Visit Probability ($\times 10^{{{exponent_for_label_display}}}$)"
+ y_axis_values_to_plot = df_plot_data_plotting['per_query_visit_probability'] / (10**exponent_for_label_display)
+ print(f"Plotting with Max per-query probability: {max_probability:.2e}, Exponent for label: {exponent_for_label_display}. Y-axis values scaled for plot.")
+ else:
+ print(f"Plotting with Max per-query probability: {max_probability:.2e}. Plotting direct probabilities without label scaling (exponent {potential_exponent} is within no-scale range [-3, -1]).")
+
+ elif pd.notna(max_probability) and max_probability == 0:
+ print("Max per-query probability is 0. Plotting direct probabilities (all zeros).")
+ else:
+ print(f"Max per-query probability is NaN or invalid ({max_probability}). Plotting direct probabilities without scaling if possible.")
+
+ ax.bar(
+ df_plot_data_plotting['degree_bin_label'],
+ y_axis_values_to_plot,
+ color='white',
+ edgecolor=edgecolors_ref[0],
+ linewidth=1.5,
+ width=0.8
+ )
+
+ ax.set_xlabel('Node Degree', fontsize=10.5, labelpad=6)
+ # MODIFIED LINE: Added labelpad to move the y-axis label to the left
+ ax.set_ylabel(y_axis_label, fontsize=10.5, labelpad=10)
+
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: f"{x:.0f}%"))
+
+ num_bins = len(df_plot_data_plotting)
+ if num_bins > 12:
+ ax.set_xticks(ax.get_xticks())
+ ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right", fontsize=9)
+ elif num_bins > 8:
+ ax.tick_params(axis='x', labelsize=9)
+ else:
+ ax.tick_params(axis='x', labelsize=10)
+
+ ax.tick_params(axis='y', labelsize=10)
+
+ padding_factor = 0.05
+ current_max_y_on_axis = y_axis_values_to_plot.max()
+
+ upper_y_limit = 0.1 # Default small upper limit
+ if pd.notna(current_max_y_on_axis):
+ if current_max_y_on_axis > 0:
+ # Adjust minimum visible range based on whether scaling was applied and the exponent
+ min_meaningful_limit = 0.01
+ if apply_scaling_to_label_and_values and exponent_for_label_display >= 0 : # Numbers on axis are smaller due to positive exponent scaling
+ min_meaningful_limit = 0.1 # If original numbers were e.g. 2500 (2.5 x 10^3), scaled axis is 2.5, 0.1 is fine
+ elif not apply_scaling_to_label_and_values and pd.notna(max_probability) and max_probability >=1: # Direct large probabilities
+ min_meaningful_limit = 1 # If max prob is 2.5 (250%), axis value 2.5, needs larger base limit
+
+ upper_y_limit = max(min_meaningful_limit, current_max_y_on_axis * (1 + padding_factor))
+
+ else: # current_max_y_on_axis is 0
+ upper_y_limit = 0.1
+ ax.set_ylim(0, upper_y_limit)
+ else:
+ ax.set_ylim(0, 1.0) # Default for empty or NaN data
+
+ plt.tight_layout()
+ plt.savefig(binned_output_image_file, bbox_inches="tight", dpi=300)
+ print(f"Binned bar chart saved to {binned_output_image_file}")
+ plt.show()
+ plt.close(fig)
+else:
+ if df_plot_data is None:
+ print("Data for plotting (df_plot_data) is None. Skipping plot generation.")
+ elif df_plot_data.empty:
+ print("Data for plotting (df_plot_data) is empty. Skipping plot generation.")
+ elif 'average_visit_count_per_node_in_bin' not in df_plot_data.columns:
+ print("Essential column 'average_visit_count_per_node_in_bin' is missing in df_plot_data. Skipping plot generation.")
+
+# %%
+print("Script finished.")
\ No newline at end of file
diff --git a/research/paper_plot/b.md b/research/paper_plot/b.md
new file mode 100644
index 0000000..ef57bcd
--- /dev/null
+++ b/research/paper_plot/b.md
@@ -0,0 +1,7 @@
+In this paper, we present LiteANN, a storage-efficient approximate nearest neighbor (ANN) search index optimized for resource-constrained personal devices. LiteANN combines a compact graph-based structure with an efficient on-the-fly recomputation strategy to enable fast and accurate retrieval wih minimal storage overhead. Our evaluation shows that LiteANN reduces index size to under 5% of the original raw data – up to 50× smaller than standard indexes – while achieving 90% top-3 recall in under 2 seconds on real-world question-answering benchmarks.
+
+
+
+
+
+
diff --git a/research/paper_plot/cache_degree_data.py b/research/paper_plot/cache_degree_data.py
new file mode 100644
index 0000000..e4e5cd0
--- /dev/null
+++ b/research/paper_plot/cache_degree_data.py
@@ -0,0 +1,81 @@
+import numpy as np
+import os
+
+# --- Configuration for Data Paths and Labels (Mirrors plotting script for consistency) ---
+BIG_GRAPH_PATHS = [
+ "/opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/",
+ "/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/99_4_degree_based_hnsw_IP_M32_efC256/",
+ "/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/d9_hnsw_IP_M8_efC128/",
+ "/opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/half_edges_IP_M32_efC128/"
+]
+STATS_FILE_NAME = "degree_distribution.txt"
+BIG_GRAPH_LABELS = [ # These will be used as keys in the cached file
+ "HNSW-Base",
+ "DegreeGuide",
+ "HNSW-D9",
+ "RandCut",
+]
+# Average degrees are static and can be directly used in the plotting script or also cached.
+# For simplicity here, we'll focus on caching the dynamic degree arrays.
+# BIG_GRAPH_AVG_DEG = [18, 9, 9, 9]
+
+# --- Cache File Configuration ---
+DATA_CACHE_DIR = "./paper_plot/data/"
+CACHE_FILE_NAME = "big_graph_degree_data.npz" # Using .npz for multiple arrays
+
+def create_degree_data_cache():
+ """
+ Reads degree distribution data from specified text files and saves it
+ into a compressed NumPy (.npz) cache file.
+ """
+ os.makedirs(DATA_CACHE_DIR, exist_ok=True)
+ cache_file_path = os.path.join(DATA_CACHE_DIR, CACHE_FILE_NAME)
+
+ cached_data = {}
+ print(f"Starting data caching process for {len(BIG_GRAPH_PATHS)} graph types...")
+
+ for i, base_path in enumerate(BIG_GRAPH_PATHS):
+ method_label = BIG_GRAPH_LABELS[i]
+ degree_file_path = os.path.join(base_path, STATS_FILE_NAME)
+
+ print(f"Processing: {method_label} from {degree_file_path}")
+
+ try:
+ # Load degrees as integers
+ degrees = np.loadtxt(degree_file_path, dtype=int)
+
+ if degrees.size == 0:
+ print(f" [WARN] Degree file is empty: {degree_file_path}. Storing as empty array for {method_label}.")
+ # Store an empty array or handle as needed. For npz, an empty array is fine.
+ cached_data[method_label] = np.array([], dtype=int)
+ else:
+ # Store the loaded degrees array with the method label as the key
+ cached_data[method_label] = degrees
+ print(f" [INFO] Loaded {len(degrees)} degrees for {method_label}. Max degree: {np.max(degrees) if degrees.size > 0 else 'N/A'}")
+
+ except FileNotFoundError:
+ print(f" [ERROR] Degree file not found: {degree_file_path}. Skipping {method_label}.")
+ # Optionally store a placeholder or skip. For robustness, store None or an empty array.
+ # Storing None might require special handling when loading. Empty array is safer for np.load.
+ cached_data[method_label] = np.array([], dtype=int) # Store empty array if file not found
+ except Exception as e:
+ print(f" [ERROR] An error occurred loading {degree_file_path} for {method_label}: {e}")
+ cached_data[method_label] = np.array([], dtype=int) # Store empty array on other errors
+
+ if not cached_data:
+ print("[ERROR] No data was successfully processed or loaded. Cache file will not be created.")
+ return
+
+ try:
+ # Save all collected degree arrays into a single .npz file.
+ # Using savez_compressed for potentially smaller file size.
+ np.savez_compressed(cache_file_path, **cached_data)
+ print(f"\n[SUCCESS] Degree distribution data successfully cached to: {os.path.abspath(cache_file_path)}")
+ print("Cached arrays (keys):", list(cached_data.keys()))
+ except Exception as e:
+ print(f"\n[ERROR] Failed to save data to cache file {cache_file_path}: {e}")
+
+if __name__ == "__main__":
+ print("--- Degree Distribution Data Caching Script ---")
+ create_degree_data_cache()
+ print("--- Caching script finished. ---")
diff --git a/research/paper_plot/data/acc.csv b/research/paper_plot/data/acc.csv
new file mode 100644
index 0000000..fe7c786
--- /dev/null
+++ b/research/paper_plot/data/acc.csv
@@ -0,0 +1,4 @@
+Model,NQ Exact Match,NQ F1,TriviaQA Exact Match,TriviaQA F1,GPQA Exact Match,GPQA F1,HotpotQA Exact Match,HotpotQA F1
+BM25,0.192,0.277,0.406,0.474,0.020089,0.04524,0.162,0.239
+PQ 5,0.2075,0.291,0.422,0.495,0.0201,0.0445,0.148,0.219
+Ours,0.265,0.361,0.533,0.604,0.02008,0.0452,0.182,0.2729
\ No newline at end of file
diff --git a/research/paper_plot/data/big_graph_degree_data.npz b/research/paper_plot/data/big_graph_degree_data.npz
new file mode 100644
index 0000000..3fb30ab
--- /dev/null
+++ b/research/paper_plot/data/big_graph_degree_data.npz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1296720e79196bbdf38f051043c1b054667803726a24036c0b6a87cedb204ea5
+size 227482438
diff --git a/research/paper_plot/data/branches.csv b/research/paper_plot/data/branches.csv
new file mode 100644
index 0000000..1a21d3e
--- /dev/null
+++ b/research/paper_plot/data/branches.csv
@@ -0,0 +1,21 @@
+2,1,512,1024,0.541,0.326,1.659509202
+2,2,512,1024,0.979,0.621,1.576489533
+2,4,512,1024,1.846,0.977,1.889457523
+2,8,512,1024,3.575,1.943,1.83993824
+2,16,512,1024,7.035,3.733,1.884543263
+2,32,512,1024,15.655,8.517,1.838088529
+2,64,512,1024,32.772,17.43,1.88020654
+4,1,512,1024,2.675,1.38,1.938405797
+4,2,512,1024,5.397,2.339,2.307396323
+4,4,512,1024,10.672,4.944,2.158576052
+4,8,512,1024,21.061,9.266,2.272933305
+4,16,512,1024,46.332,18.334,2.527108105
+4,32,512,1024,99.607,36.156,2.754923111
+4,64,512,1024,186.348,72.356,2.575432583
+8,1,512,1024,7.325,4.087,1.792268167
+8,2,512,1024,14.109,7.491,1.883460152
+8,4,512,1024,28.499,14.013,2.033754371
+8,8,512,1024,65.222,27.453,2.375769497
+8,16,512,1024,146.294,52.55,2.783901047
+8,32,512,1024,277.099,103.61,2.674442621
+8,64,512,1024,512.979,208.36,2.461984066
\ No newline at end of file
diff --git a/research/paper_plot/data/latency_ablation.csv b/research/paper_plot/data/latency_ablation.csv
new file mode 100644
index 0000000..7ece976
--- /dev/null
+++ b/research/paper_plot/data/latency_ablation.csv
@@ -0,0 +1,9 @@
+Dataset,Metric,Original,original + batch,original + two_level,original + two_level + batch
+NQ,Latency,6.9,5.8,4.2,3.7
+NQ,SpeedUp,1,1.18965517,1.64285714,1.86486486
+TriviaQA,Latency,17.054,14.542,12.046,10.83
+TriviaQA,SpeedUp,1,1.17274103,1.41573967,1.57469990
+GPQA,Latency,9.164,7.639,6.798,5.77
+GPQA,SpeedUp,1,1.19963346,1.34804354,1.58821490
+HotpotQA,Latency,60.279,39.827,50.664,29.868
+HotpotQA,SpeedUp,1,1.51352098,1.18977972,2.01817999
diff --git a/research/paper_plot/data/main_latency.csv b/research/paper_plot/data/main_latency.csv
new file mode 100644
index 0000000..c97fb61
--- /dev/null
+++ b/research/paper_plot/data/main_latency.csv
@@ -0,0 +1,25 @@
+Dataset,Hardware,Recall_target,HNSW,IVF,DiskANN,IVF-Disk,IVF-Recompute,Our,BM25,LLM_Gen_Time_1B,LLM_Gen_Time_3B,LLM_Gen_Time_7B
+NQ,A10,85%,0.046,1.656,0.017,2.996,482.53,3.323,0.021,0.085,0.217,0.472
+NQ,A10,90%,0.051,2.552,0.028,3.437,769.04,4.616,0,0.085,0.217,0.472
+NQ,A10,95%,0.055,5.163,0.070,5.602,1436.26,19.494,0,0.085,0.217,0.472
+NQ,MAC,85%,0,0,0.152,2.199,1535.10,7.971,0.033,0.316,0.717,1.468
+NQ,MAC,90%,0,0,0.37,2.936,2446.60,13.843,0,0.316,0.717,1.468
+NQ,MAC,95%,0,0,1.207,4.191,4569.29,44.363,0,0.316,0.717,1.468
+TriviaQA,A10,85%,0.042,1.772,0.032,2.464,560.5,3.752,0.033,0.139,0.156,0.315
+TriviaQA,A10,90%,0.043,3.541,0.057,3.651,997.81,5.777,0,0.139,0.156,0.315
+TriviaQA,A10,95%,0.053,7.168,0.090,5.458,2005.33,20.944,0,0.139,0.156,0.315
+TriviaQA,MAC,85%,0,0,0.481,1.875,1783.14787,8.889,0.036,0.325,0.692,1.415
+TriviaQA,MAC,90%,0,0,0.984,2.639,3174.410301,17.145,0,0.325,0.692,1.415
+TriviaQA,MAC,95%,0,0,1.578,3.884,6379.712245,47.909,0,0.325,0.692,1.415
+GPQA,A10,85%,0.041,0.134,0.024,0.048,40.16,1.897,0.137,0.443,0.396,0.651
+GPQA,A10,90%,0.042,0.174,0.034,0.06,54.71,1.733,0,0.443,0.396,0.651
+GPQA,A10,95%,0.045,0.292,0.051,0.11,97.67,4.033,0,0.443,0.396,0.651
+GPQA,MAC,85%,0,0,0.144,0.087,127.7707505,4.762,0.100,0.37,0.813,1.676
+GPQA,MAC,90%,0,0,0.288,0.108,174.0647409,5.223,0,0.37,0.813,1.676
+GPQA,MAC,95%,0,0,0.497,0.132,310.7380142,9.715,0,0.37,0.813,1.676
+HotpotQA,A10,85%,0.044,2.519,0.054,4.048,724.26,10.358,0.70,0.144,0.196,0.420
+HotpotQA,A10,90%,0.049,3.867,0.109,5.045,1173.67,15.515,0,0.144,0.196,0.420
+HotpotQA,A10,95%,0.07,10.928,0.412,8.659,3079.57,61.757,0,0.144,0.196,0.420
+HotpotQA,MAC,85%,0,0,0.974,2.844,2304.125187,23.636,0.052,0.144,0.196,0.420
+HotpotQA,MAC,90%,0,0,1.913,3.542,3415.736201,44.803,0,0.144,0.196,0.420
+HotpotQA,MAC,95%,0,0,5.783,6.764,9797.244043,140.62,0,0.144,0.196,0.420
diff --git a/research/paper_plot/data/main_latency_small.csv b/research/paper_plot/data/main_latency_small.csv
new file mode 100644
index 0000000..525dc61
--- /dev/null
+++ b/research/paper_plot/data/main_latency_small.csv
@@ -0,0 +1,25 @@
+Dataset,Hardware,Recall_target,HNSW,IVF,DiskANN,IVF-Disk,IVF-Recompute,Our,
+NQ,A10,85%,0.046,1.656,0.017,2.996,482.53,4.243,
+NQ,A10,90%,0.051,2.552,0.028,3.437,769.04,8.136,
+NQ,A10,95%,0.055,5.163,0.070,5.602,1436.26,27.275,
+NQ,MAC,85%,0,0,0.152,2.199,1535.10,10.672,
+NQ,MAC,90%,0,0,0.37,2.936,2446.60,19.941,
+NQ,MAC,95%,0,0,1.207,4.191,4569.29,61.383,
+TriviaQA,A10,85%,0.042,1.772,0.032,2.464,560.5,5.612,
+TriviaQA,A10,90%,0.043,3.541,0.057,3.651,997.81,10.737,
+TriviaQA,A10,95%,0.053,7.168,0.090,5.458,2005.33,36.387,
+TriviaQA,MAC,85%,0,0,0.481,1.875,1783.14787,12.825,
+TriviaQA,MAC,90%,0,0,0.984,2.639,3174.410301,24.977,
+TriviaQA,MAC,95%,0,0,1.578,3.884,6379.712245,85.734,
+GPQA,A10,85%,0.041,0.134,0.024,0.048,40.16,2.269,
+GPQA,A10,90%,0.042,0.174,0.034,0.06,54.71,3.200,
+GPQA,A10,95%,0.045,0.292,0.051,0.11,97.67,7.445,
+GPQA,MAC,85%,0,0,0.144,0.087,127.7707505,6.123,
+GPQA,MAC,90%,0,0,0.288,0.108,174.0647409,8.507,
+GPQA,MAC,95%,0,0,0.497,0.132,310.7380142,19.577,
+HotpotQA,A10,85%,0.044,2.519,0.054,4.048,724.26,14.713,
+HotpotQA,A10,90%,0.049,3.867,0.109,5.045,1173.67,33.561,
+HotpotQA,A10,95%,0.07,10.928,0.412,8.659,3079.57,68.626,
+HotpotQA,MAC,85%,0,0,0.974,2.844,2304.125187,34.783,
+HotpotQA,MAC,90%,0,0,1.913,3.542,3415.736201,53.004,
+HotpotQA,MAC,95%,0,0,5.783,6.764,9797.244043,95.413,
diff --git a/research/paper_plot/data/ram_storage.csv b/research/paper_plot/data/ram_storage.csv
new file mode 100644
index 0000000..892de68
--- /dev/null
+++ b/research/paper_plot/data/ram_storage.csv
@@ -0,0 +1,3 @@
+Hardware,HNSW,IVF,DiskANN,IVF-Disk,IVF-Recompute,Our,BM25
+RAM,190,171,10,0,0,0,0
+Storage,185.4,171,240,171,0.5,5,59
\ No newline at end of file
diff --git a/research/paper_plot/data/swithc_e2e.csv b/research/paper_plot/data/swithc_e2e.csv
new file mode 100644
index 0000000..f690e03
--- /dev/null
+++ b/research/paper_plot/data/swithc_e2e.csv
@@ -0,0 +1,12 @@
+Torch,8,55.592
+Torch,16,75.439
+Torch,32,110.025
+Torch,64,186.496
+Tutel,8,56.718
+Tutel,16,82.121
+Tutel,32,125.070
+Tutel,64,216.191
+BRT,8,56.725
+BRT,16,79.291
+BRT,32,93.180
+BRT,64,118.923
diff --git a/research/paper_plot/data/vary_cache.csv b/research/paper_plot/data/vary_cache.csv
new file mode 100644
index 0000000..57c2f1e
--- /dev/null
+++ b/research/paper_plot/data/vary_cache.csv
@@ -0,0 +1,6 @@
+Disk cache size,0,2.5%(180G*2.5%),5%,8%,10%
+Latency,,,,,
+NQ,4.616,4.133,3.826,3.511,3.323
+TriviaQA,5.777,4.979,4.553,4.141,3.916
+GPQA,1.733,1.593,1.468,1.336,1.259
+Hotpot,15.515,13.479,12.383,11.216,10.606
\ No newline at end of file
diff --git a/research/paper_plot/disk_cache.py b/research/paper_plot/disk_cache.py
new file mode 100644
index 0000000..8437b0f
--- /dev/null
+++ b/research/paper_plot/disk_cache.py
@@ -0,0 +1,151 @@
+import matplotlib
+from matplotlib.axes import Axes
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.patches as mpatches
+from matplotlib.lines import Line2D
+
+# plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 1
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True
+plt.rcParams["font.family"] = "sans-serif" # Use generic sans-serif family
+plt.rcParams['text.latex.preamble'] = r"""
+\usepackage{helvet} % Use Helvetica font for text
+\usepackage{sfmath} % Use sans-serif font for math
+\renewcommand{\familydefault}{\sfdefault} % Set sans-serif as default text font
+\usepackage[T1]{fontenc} % Recommended for font encoding
+"""
+# plt.rcParams['mathtext.fontset'] = 'dejavusans'
+SAVE_PTH = "./paper_plot/figures"
+font_size = 16
+
+# New data in dictionary format
+datasets = ["NQ", "TriviaQA", "GPQA", "Hotpot"]
+
+cache_ratios = ["4.2G\n (0\%)", "8.7G\n (2.5\%)", "13.2G\n (5\%)", "18.6G\n (8\%)", "22.2G\n (10\%)"]
+latency_data = {
+ "NQ": [4.616, 4.133, 3.826, 3.511, 3.323],
+ "TriviaQA": [5.777, 4.979, 4.553, 4.141, 3.916],
+ "GPQA": [1.733, 1.593, 1.468, 1.336, 1.259],
+ "Hotpot": [15.515, 13.479, 12.383, 11.216, 10.606],
+}
+cache_hit_counts = {
+ "NQ": [0, 14.81, 23.36, 31.99, 36.73],
+ "TriviaQA": [0, 18.55, 27.99, 37.06, 41.86],
+ "GPQA": [0, 10.99, 20.31, 29.71, 35.01],
+ "Hotpot": [0, 17.47, 26.91, 36.2, 41.06]
+}
+
+# Create the figure with 4 subplots in a 2x2 grid
+fig, axes_grid = plt.subplots(2, 2, figsize=(7,6))
+axes = axes_grid.flatten() # Flatten the 2x2 grid to a 1D array
+
+# Bar style settings
+width = 0.7
+x = np.arange(len(cache_ratios))
+
+# Define hatch patterns for different cache ratios
+hatch_patterns = ['//', '//', '//', '//', '//']
+
+# Find max cache hit value across all datasets for unified y-axis
+all_hit_counts = []
+for dataset in datasets:
+ all_hit_counts.extend(cache_hit_counts[dataset])
+max_unified_hit = max(all_hit_counts) * 1.13
+
+for i, dataset in enumerate(datasets):
+ latencies = latency_data[dataset]
+ hit_counts = cache_hit_counts[dataset]
+
+ for j, val in enumerate(latencies):
+ container = axes[i].bar(
+ x[j],
+ val,
+ width=width,
+ color="white",
+ edgecolor="black",
+ linewidth=1.0,
+ zorder=10,
+ )
+ axes[i].bar_label(
+ container,
+ [f"{val:.2f}"],
+ fontsize=10,
+ zorder=200,
+ fontweight="bold",
+ )
+
+ axes[i].set_title(dataset, fontsize=font_size)
+ axes[i].set_xticks(x)
+ axes[i].set_xticklabels(cache_ratios, fontsize=12, rotation=0, ha='center', fontweight="bold")
+
+ max_val_ratios = [1.35, 1.65, 1.45, 1.75]
+ max_val = max(latencies) * max_val_ratios[i]
+ axes[i].set_ylim(0, max_val)
+ axes[i].tick_params(axis='y', labelsize=12)
+
+ if i % 2 == 0:
+ axes[i].set_ylabel("Latency (s)", fontsize=font_size)
+ axes[i].yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%.1f'))
+
+ ax2: Axes = axes[i].twinx()
+ ax2.plot(x, hit_counts,
+ linestyle='--',
+ marker='o',
+ markersize=6,
+ linewidth=1.5,
+ color='k',
+ markerfacecolor='none',
+ zorder=20)
+
+ ax2.set_ylim(0, max_unified_hit)
+ ax2.tick_params(axis='y', labelsize=12)
+ if i % 2 == 1:
+ ax2.set_ylabel(r"Cache Hit (\%)", fontsize=font_size)
+
+ for j, val in enumerate(hit_counts):
+ if val > 0:
+ ax2.annotate(f"{val:.1f}%",
+ (x[j], val),
+ textcoords="offset points",
+ xytext=(0, 5),
+ ha='center',
+ va='bottom',
+ fontsize=10,
+ fontweight='bold')
+
+# Create legend for both plots
+bar_patch = mpatches.Patch(facecolor='white', edgecolor='black', label='Latency')
+line_patch = Line2D([0], [0], color='black', linestyle='--', label='Cache Hit Rate')
+
+# --- MODIFICATION FOR LEGEND AT THE TOP ---
+fig.legend(handles=[bar_patch, line_patch],
+ loc='upper center', # Position the legend at the upper center
+ bbox_to_anchor=(0.5, 0.995), # Anchor point (0.5 means horizontal center of figure,
+ # 0.97 means 97% from the bottom, so near the top)
+ ncol=3,
+ fontsize=font_size-2)
+# --- END OF MODIFICATION ---
+
+# Set common x-axis label - you might want to add this back if needed
+# fig.text(0.5, 0.02, "Disk Cache Size", ha='center', fontsize=font_size, fontweight='bold') # Adjusted y for potential bottom label
+
+# --- MODIFICATION FOR TIGHT LAYOUT ---
+# Adjust rect to make space for the legend at the top.
+# (left, bottom, right, top_for_subplots)
+# We want subplots to occupy space from y=0 up to y=0.93 (or similar)
+# leaving the top portion (0.93 to 1.0) for the legend.
+plt.tight_layout(rect=(0, 0, 1, 0.93)) # Ensure subplots are below the legend
+# --- END OF MODIFICATION ---
+
+# Create directory if it doesn't exist (optional, good practice)
+import os
+if not os.path.exists(SAVE_PTH):
+ os.makedirs(SAVE_PTH)
+
+plt.savefig(f"{SAVE_PTH}/disk_cache_latency.pdf", dpi=300) # Changed filename slightly for testing
+print(f"Save to {SAVE_PTH}/disk_cache_latency.pdf")
+# plt.show() # Optional: to display the plot
\ No newline at end of file
diff --git a/research/paper_plot/figures/H_hnsw_performance_comparison.pdf b/research/paper_plot/figures/H_hnsw_performance_comparison.pdf
new file mode 100644
index 0000000..d258c62
Binary files /dev/null and b/research/paper_plot/figures/H_hnsw_performance_comparison.pdf differ
diff --git a/research/paper_plot/figures/H_hnsw_performance_comparison.png b/research/paper_plot/figures/H_hnsw_performance_comparison.png
new file mode 100644
index 0000000..67b4745
Binary files /dev/null and b/research/paper_plot/figures/H_hnsw_performance_comparison.png differ
diff --git a/research/paper_plot/figures/H_hnsw_recall_comparison.pdf b/research/paper_plot/figures/H_hnsw_recall_comparison.pdf
new file mode 100644
index 0000000..b31b78c
Binary files /dev/null and b/research/paper_plot/figures/H_hnsw_recall_comparison.pdf differ
diff --git a/research/paper_plot/figures/H_hnsw_recall_comparison.png b/research/paper_plot/figures/H_hnsw_recall_comparison.png
new file mode 100644
index 0000000..840f5d1
Binary files /dev/null and b/research/paper_plot/figures/H_hnsw_recall_comparison.png differ
diff --git a/research/paper_plot/figures/accuracy_comparison.pdf b/research/paper_plot/figures/accuracy_comparison.pdf
new file mode 100644
index 0000000..48ddfd2
Binary files /dev/null and b/research/paper_plot/figures/accuracy_comparison.pdf differ
diff --git a/research/paper_plot/figures/degree_distribution.pdf b/research/paper_plot/figures/degree_distribution.pdf
new file mode 100644
index 0000000..c559c8c
Binary files /dev/null and b/research/paper_plot/figures/degree_distribution.pdf differ
diff --git a/research/paper_plot/figures/degree_distribution_small.pdf b/research/paper_plot/figures/degree_distribution_small.pdf
new file mode 100644
index 0000000..9deec6e
Binary files /dev/null and b/research/paper_plot/figures/degree_distribution_small.pdf differ
diff --git a/research/paper_plot/figures/disk_cache_latency.pdf b/research/paper_plot/figures/disk_cache_latency.pdf
new file mode 100644
index 0000000..646d998
Binary files /dev/null and b/research/paper_plot/figures/disk_cache_latency.pdf differ
diff --git a/research/paper_plot/figures/figure15.pdf b/research/paper_plot/figures/figure15.pdf
new file mode 100644
index 0000000..eb12d8b
Binary files /dev/null and b/research/paper_plot/figures/figure15.pdf differ
diff --git a/research/paper_plot/figures/gpu_throughput_vs_batch_size.pdf b/research/paper_plot/figures/gpu_throughput_vs_batch_size.pdf
new file mode 100644
index 0000000..bb8820d
Binary files /dev/null and b/research/paper_plot/figures/gpu_throughput_vs_batch_size.pdf differ
diff --git a/research/paper_plot/figures/hnsw_visit_count_per_degree_corrected.pdf b/research/paper_plot/figures/hnsw_visit_count_per_degree_corrected.pdf
new file mode 100644
index 0000000..fce62e4
Binary files /dev/null and b/research/paper_plot/figures/hnsw_visit_count_per_degree_corrected.pdf differ
diff --git a/research/paper_plot/figures/hnsw_visit_count_per_degree_corrected.png b/research/paper_plot/figures/hnsw_visit_count_per_degree_corrected.png
new file mode 100644
index 0000000..c7aa03d
Binary files /dev/null and b/research/paper_plot/figures/hnsw_visit_count_per_degree_corrected.png differ
diff --git a/research/paper_plot/figures/latency_speedup.pdf b/research/paper_plot/figures/latency_speedup.pdf
new file mode 100644
index 0000000..1d55ef6
Binary files /dev/null and b/research/paper_plot/figures/latency_speedup.pdf differ
diff --git a/research/paper_plot/figures/main_exp_fig_1.pdf b/research/paper_plot/figures/main_exp_fig_1.pdf
new file mode 100644
index 0000000..105053e
Binary files /dev/null and b/research/paper_plot/figures/main_exp_fig_1.pdf differ
diff --git a/research/paper_plot/figures/main_exp_fig_2.pdf b/research/paper_plot/figures/main_exp_fig_2.pdf
new file mode 100644
index 0000000..d1730d7
Binary files /dev/null and b/research/paper_plot/figures/main_exp_fig_2.pdf differ
diff --git a/research/paper_plot/figures/plot1_em_f1.pdf b/research/paper_plot/figures/plot1_em_f1.pdf
new file mode 100644
index 0000000..d4b5dad
Binary files /dev/null and b/research/paper_plot/figures/plot1_em_f1.pdf differ
diff --git a/research/paper_plot/figures/plot2_latency.pdf b/research/paper_plot/figures/plot2_latency.pdf
new file mode 100644
index 0000000..8f1a39a
Binary files /dev/null and b/research/paper_plot/figures/plot2_latency.pdf differ
diff --git a/research/paper_plot/figures/ram_storage_double_column.pdf b/research/paper_plot/figures/ram_storage_double_column.pdf
new file mode 100644
index 0000000..efee2b0
Binary files /dev/null and b/research/paper_plot/figures/ram_storage_double_column.pdf differ
diff --git a/research/paper_plot/figures/sparse_a2a_branches.pdf b/research/paper_plot/figures/sparse_a2a_branches.pdf
new file mode 100644
index 0000000..3ef773b
Binary files /dev/null and b/research/paper_plot/figures/sparse_a2a_branches.pdf differ
diff --git a/research/paper_plot/figures/speed_A10_revised.pdf b/research/paper_plot/figures/speed_A10_revised.pdf
new file mode 100644
index 0000000..c5b8cf2
Binary files /dev/null and b/research/paper_plot/figures/speed_A10_revised.pdf differ
diff --git a/research/paper_plot/figures/speed_MAC_revised.pdf b/research/paper_plot/figures/speed_MAC_revised.pdf
new file mode 100644
index 0000000..71f75b6
Binary files /dev/null and b/research/paper_plot/figures/speed_MAC_revised.pdf differ
diff --git a/research/paper_plot/gpu_under.py b/research/paper_plot/gpu_under.py
new file mode 100644
index 0000000..f631872
--- /dev/null
+++ b/research/paper_plot/gpu_under.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+# -*- coding:utf-8 -*-
+# Motto: Were It to Benefit My Country, I Would Lay Down My Life!
+# \file: /gpu_utilization_plot.py
+# \brief: Plots GPU throughput vs. batch size to show utilization with equally spaced x-axis.
+# Author: AI Assistant
+
+import numpy as np
+import pandas as pd # Using pandas for data structuring, similar to example
+from matplotlib import pyplot as plt
+
+# Apply styling similar to the example script
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["xtick.direction"] = "in"
+# plt.rcParams["hatch.linewidth"] = 1.5 # Not used for line plots
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True # Enables LaTeX for text rendering
+
+# New Benchmark data (4th set)
+data = {
+ 'batch_size': [1, 4, 8, 10, 16, 20, 32, 40, 64, 128, 256,],
+ 'avg_time_s': [
+ 0.0031, 0.0057, 0.0100, 0.0114, 0.0186, 0.0234,
+ 0.0359, 0.0422, 0.0626, 0.1259, 0.2454,
+ ],
+ 'throughput_seq_s': [
+ 318.10, 696.77, 798.95, 874.70, 859.58, 855.19,
+ 890.80, 946.93, 1022.75, 1017.03, 1043.17,
+ ]
+}
+benchmark_df = pd.DataFrame(data)
+
+# Create the plot
+# Increased width slightly for more x-axis labels
+fig, ax = plt.subplots()
+fig.set_size_inches(8, 5)
+
+# Generate equally spaced x-coordinates (indices)
+x_indices = np.arange(len(benchmark_df))
+
+# Plotting throughput vs. batch size (using indices for x-axis)
+ax.plot(
+ x_indices, # Use equally spaced indices for plotting
+ benchmark_df['throughput_seq_s'],
+ marker='o', # Add markers to data points
+ linestyle='-',
+ color="#63B8B6", # A color inspired by the example's 'edgecolors'
+ linewidth=2,
+ markersize=6,
+ # label="Model Throughput" # Label for legend if needed, but not showing legend by default
+)
+
+# Setting labels for axes
+ax.set_xlabel("Batch Size", fontsize=14)
+ax.set_ylabel("Throughput (sequences/second)", fontsize=14)
+
+# Customizing Y-axis for the new data range:
+# Start Y from 0 to include the anomalous low point and show full scale.
+y_min_val = 200
+# Round up y_max_val to the nearest 100, as max throughput > 1000
+y_max_val = np.ceil(benchmark_df['throughput_seq_s'].max() / 100) * 100
+ax.set_ylim((y_min_val, y_max_val))
+# Set y-ticks every 100 units, ensuring the top tick is included.
+ax.set_yticks(np.arange(y_min_val, y_max_val + 1, 100))
+
+# Customizing X-axis for equally spaced ticks:
+# Set tick positions to the indices
+ax.set_xticks(x_indices)
+# Set tick labels to the actual batch_size values
+ax.set_xticklabels(benchmark_df['batch_size'])
+ax.tick_params(axis='x', rotation=45, labelsize=10) # Rotate X-axis labels, fontsize 10
+ax.tick_params(axis='y', labelsize=12)
+
+
+# Add a light grid for better readability, common in academic plots
+ax.grid(True, linestyle=':', linewidth=0.5, color='grey', alpha=0.7, zorder=0)
+
+# Remove title (as requested)
+# ax.set_title("GPU Throughput vs. Batch Size", fontsize=16) # Title would go here
+
+# Optional: Add a legend if you have multiple lines or want to label the single line
+# ax.legend(
+# loc="center right", # Location might need adjustment due to data shape
+# edgecolor="black",
+# facecolor="white",
+# framealpha=1.0,
+# shadow=False,
+# fancybox=False,
+# prop={"weight": "bold", "size": 10}
+# ).set_zorder(100)
+
+# Adjust layout to prevent labels from being cut off
+plt.tight_layout()
+
+# Save the figure
+output_filename = "./paper_plot/figures/gpu_throughput_vs_batch_size_equispaced.pdf"
+plt.savefig(output_filename, bbox_inches="tight", dpi=300)
+print(f"Plot saved to {output_filename}")
+
+# Display the plot (optional, depending on environment)
+plt.show()
+
+# %%
+# This is just to mimic the '%%' cell structure from the example.
+# No actual code needed here for this script.
\ No newline at end of file
diff --git a/research/paper_plot/graph_dist.py b/research/paper_plot/graph_dist.py
new file mode 100644
index 0000000..4286883
--- /dev/null
+++ b/research/paper_plot/graph_dist.py
@@ -0,0 +1,245 @@
+import argparse
+import matplotlib.pyplot as plt
+import numpy as np
+import os
+import matplotlib.ticker as ticker # Import ticker for formatting
+
+# --- Global Academic Style Configuration ---
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["axes.titleweight"] = "bold"
+
+plt.rcParams["ytick.direction"] = "out"
+plt.rcParams["xtick.direction"] = "out"
+
+plt.rcParams["axes.grid"] = False # Grid lines are off
+
+plt.rcParams["text.usetex"] = True
+# No explicit LaTeX preamble
+
+# --- Configuration (Mirrors caching script for consistency) ---
+# These labels are used as keys to retrieve data from the cache
+BIG_GRAPH_LABELS = [
+ "HNSW-Base",
+ "DegreeGuide",
+ "HNSW-D9",
+ "RandCut",
+]
+BIG_GRAPH_LABELS_IN_FIGURE = [
+ "Original HNSW",
+ "Our Pruning Method",
+ "Small M",
+ "Random Prune",
+]
+LABEL_FONT_SIZE = 12
+# Average degrees are static and used directly
+BIG_GRAPH_AVG_DEG = [
+ 18, 9, 9, 9
+]
+
+# --- Cache File and Output Configuration ---
+DATA_CACHE_DIR = "./paper_plot/data/"
+CACHE_FILE_NAME = "big_graph_degree_data.npz"
+OUTPUT_DIR = "./paper_plot/figures/"
+os.makedirs(OUTPUT_DIR, exist_ok=True) # Ensure output directory for figures exists
+OUTPUT_FILE_BIG_GRAPH = os.path.join(OUTPUT_DIR, "degree_distribution.pdf") # New output name
+
+# Colors for the four histograms
+HIST_COLORS = ['slategray', 'tomato','#63B8B6', 'cornflowerblue']
+
+
+def plot_degree_distributions_from_cache(output_image_path: str):
+ """
+ Generates a 1x4 combined plot of degree distributions for the BIG_GRAPH set,
+ loading data from a pre-generated .npz cache file.
+ """
+ cache_file_path = os.path.join(DATA_CACHE_DIR, CACHE_FILE_NAME)
+
+ if not os.path.exists(cache_file_path):
+ print(f"[ERROR] Cache file not found: {cache_file_path}")
+ print("Please run the data caching script first (e.g., cache_degree_data.py).")
+ return
+
+ try:
+ # Load the cached data
+ with np.load(cache_file_path) as loaded_data:
+ all_degrees_data_from_cache = {}
+ missing_keys = []
+ for label in BIG_GRAPH_LABELS:
+ if label in loaded_data:
+ all_degrees_data_from_cache[label] = loaded_data[label]
+ else:
+ print(f"[WARN] Label '{label}' not found in cache file. Plotting may be incomplete.")
+ all_degrees_data_from_cache[label] = np.array([], dtype=int) # Use empty array for missing data
+ missing_keys.append(label)
+
+ # Reconstruct the list of degree arrays in the order of BIG_GRAPH_LABELS
+ all_degrees_data = [all_degrees_data_from_cache.get(label, np.array([], dtype=int)) for label in BIG_GRAPH_LABELS]
+
+ print(f"[INFO] Successfully loaded data from cache: {cache_file_path}")
+
+ except Exception as e:
+ print(f"[ERROR] Failed to load or process data from cache file {cache_file_path}: {e}")
+ return
+
+ try:
+ fig, axes = plt.subplots(2, 2, figsize=(7, 4), sharex=True, sharey=True)
+ axes = axes.flatten() # Flatten the 2x2 axes array for easy iteration
+
+ active_degrees_data = all_degrees_data
+ for i, method in enumerate(BIG_GRAPH_LABELS):
+ if method == "DegreeGuide":
+ # Random span these 60 datas to 64
+ arr = active_degrees_data[i]
+ print(arr[:10])
+ # arr[arr > 54] -= 4
+ print(type(arr))
+ print(np.max(arr))
+ arr2 = arr * 60 / 64
+ # print(np.max(arr2))
+ # active_degrees_data[i] = arr2
+ # between_45_46 = arr2[arr2 >= 45]
+ # between_45_46 = between_45_46[between_45_46 < 46]
+ # print(len(between_45_46))
+ # remove all 15*n
+ # 诶为什么最右边那个变低了
+ # 原因就是
+ # 你数据里面的所有数字都是整数
+ # 所以你这个除以64*60之后,有一些相邻整数
+ # arr2
+ active_degrees_data[i] = arr2
+ # wei shen me dou shi 15 d bei shu
+ # ying gai bu shi
+ if not active_degrees_data:
+ print("[ERROR] No valid degree data loaded from cache. Cannot generate plot.")
+ if 'fig' in locals() and plt.fignum_exists(fig.number):
+ plt.close(fig)
+ return
+
+ overall_min_deg = min(np.min(d) for d in active_degrees_data)
+ overall_max_deg = max(np.max(d) for d in active_degrees_data)
+
+ if overall_min_deg == overall_max_deg:
+ overall_min_deg = np.floor(overall_min_deg - 0.5)
+ overall_max_deg = np.ceil(overall_max_deg + 0.5)
+ else:
+ overall_min_deg = np.floor(overall_min_deg - 0.5)
+ overall_max_deg = np.ceil(overall_max_deg + 0.5)
+ print(f"overall_min_deg: {overall_min_deg}, overall_max_deg: {overall_max_deg}")
+
+ max_y_raw_counts = 0
+ for i, degrees_for_hist_calc in enumerate(all_degrees_data): # Use the ordered list
+ if degrees_for_hist_calc is not None and degrees_for_hist_calc.size > 0:
+ min_deg_local = np.min(degrees_for_hist_calc)
+ max_deg_local = np.max(degrees_for_hist_calc)
+ print(f"for method {method}, min_deg_local: {min_deg_local}, max_deg_local: {max_deg_local}")
+
+ if min_deg_local == max_deg_local:
+ local_bin_edges_for_calc = np.array([np.floor(min_deg_local - 0.5), np.ceil(max_deg_local + 0.5)])
+ else:
+ num_local_bins_for_calc = int(np.ceil(max_deg_local + 0.5) - np.floor(min_deg_local - 0.5))
+ local_bin_edges_for_calc = np.linspace(np.floor(min_deg_local - 0.5),
+ np.ceil(max_deg_local + 0.5),
+ num_local_bins_for_calc + 1)
+ if i == 1:
+ unique_data = np.unique(degrees_for_hist_calc)
+ print(unique_data)
+ # split the data into unique_data
+ num_local_bins_for_calc = len(unique_data)
+ local_bin_edges_for_calc = np.concatenate([unique_data-0.1, [np.inf]])
+
+ counts, _ = np.histogram(degrees_for_hist_calc, bins=local_bin_edges_for_calc)
+ if counts.size > 0:
+ max_y_raw_counts = max(max_y_raw_counts, np.max(counts))
+
+ if max_y_raw_counts == 0:
+ max_y_raw_counts = 10
+
+ def millions_formatter(x, pos):
+ if x == 0: return '0'
+ val_millions = x / 1e6
+ if val_millions == int(val_millions): return f'{int(val_millions)}'
+ return f'{val_millions:.1f}'
+
+ for i, ax in enumerate(axes):
+ degrees = all_degrees_data[i] # Get data from the ordered list
+ current_label = BIG_GRAPH_LABELS_IN_FIGURE[i]
+ ax.set_title(current_label, fontsize=LABEL_FONT_SIZE)
+
+ if degrees is not None and degrees.size > 0:
+ min_deg_local_plot = np.min(degrees)
+ max_deg_local_plot = np.max(degrees)
+
+ if min_deg_local_plot == max_deg_local_plot:
+ plot_bin_edges = np.array([np.floor(min_deg_local_plot - 0.5), np.ceil(max_deg_local_plot + 0.5)])
+ else:
+ num_plot_bins = int(np.ceil(max_deg_local_plot + 0.5) - np.floor(min_deg_local_plot - 0.5))
+ plot_bin_edges = np.linspace(np.floor(min_deg_local_plot - 0.5),
+ np.ceil(max_deg_local_plot + 0.5),
+ num_plot_bins + 1)
+ if i == 1:
+ unique_data = np.unique(degrees)
+ print(unique_data)
+ #
+ # split the data into unique_data
+ num_plot_bins = len(unique_data)
+ plot_bin_edges = np.concatenate([unique_data-0.1, [unique_data[-1] + 0.8375]])
+
+ ax.hist(degrees, bins=plot_bin_edges,
+ color=HIST_COLORS[i % len(HIST_COLORS)],
+ alpha=0.85)
+
+ avg_deg_val = BIG_GRAPH_AVG_DEG[i]
+ ax.text(0.95, 0.88, f"Avg Degree: {avg_deg_val}",
+ transform=ax.transAxes, fontsize=15,
+ verticalalignment='top', horizontalalignment='right',
+ bbox=dict(facecolor='white', alpha=0.6, edgecolor='none', pad=0.3))
+ else:
+ ax.text(0.5, 0.5, 'Data unavailable', horizontalalignment='center',
+ verticalalignment='center', transform=ax.transAxes, fontsize=9)
+
+ ax.set_xlim(0, overall_max_deg)
+ ax.set_ylim(0, max_y_raw_counts * 1.12)
+ ax.set_yscale('log')
+
+ for spine_pos in ['top', 'right', 'bottom', 'left']:
+ ax.spines[spine_pos].set_edgecolor('black')
+ ax.spines[spine_pos].set_linewidth(1.0)
+
+ # ax.spines['top'].set_visible(False)
+ # ax.spines['right'].set_visible(False)
+
+ ax.tick_params(axis='x', which='both', bottom=True, top=False, labelbottom=True, length=4, width=1, labelsize=12)
+ ax.tick_params(axis='y', which='both', left=True, right=False, labelleft=(i%2==0), length=4, width=1, labelsize=12)
+
+ # ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: millions_formatter(x, pos)))
+
+ ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
+ ax.ticklabel_format(style='plain', axis='x', useOffset=False)
+
+ axes[0].set_ylabel(r"Number of Nodes", fontsize=12)
+ axes[2].set_ylabel(r"Number of Nodes", fontsize=12) # Add ylabel for the second row
+ fig.text(0.54, 0.02, "Node Degree", ha='center', va='bottom', fontsize=15)
+
+ plt.tight_layout(rect=(0.06, 0.05, 0.98, 0.88))
+
+ plt.savefig(output_image_path, dpi=300, bbox_inches='tight', pad_inches=0.05)
+ print(f"[LOG] Plot saved to {output_image_path}")
+
+ finally:
+ if 'fig' in locals() and plt.fignum_exists(fig.number):
+ plt.close(fig)
+
+
+if __name__ == "__main__":
+ if plt.rcParams["text.usetex"]:
+ print("INFO: LaTeX rendering is enabled via rcParams.")
+ else:
+ print("INFO: LaTeX rendering is disabled (text.usetex=False).")
+
+ print(f"INFO: Plots will be saved to '{OUTPUT_FILE_BIG_GRAPH}'")
+
+ plot_degree_distributions_from_cache(OUTPUT_FILE_BIG_GRAPH)
+
+ print("INFO: Degree distribution plot from cache has been generated.")
diff --git a/research/paper_plot/graph_pruning_ablation.py b/research/paper_plot/graph_pruning_ablation.py
new file mode 100644
index 0000000..19cf96b
--- /dev/null
+++ b/research/paper_plot/graph_pruning_ablation.py
@@ -0,0 +1,330 @@
+# python faiss/demo/plot_graph_struct.py faiss/demo/output.log
+# python faiss/demo/plot_graph_struct.py large_graph_recompute.log
+import argparse
+import re
+import matplotlib.pyplot as plt
+import numpy as np
+
+# Modified recall_levels and corresponding styles/widths from previous step
+recall_levels = [0.90, 0.92, 0.94, 0.96]
+line_styles = ['--', '-', '-', '-']
+line_widths = [1, 1.5, 1.5, 1.5]
+
+MAPPED_METHOD_NAMES = [
+ # 'HNSW-Base',
+ # 'DegreeGuide',
+ # 'HNSW-D9',
+ # 'RandCut',
+ "Original HNSW",
+ "Our Pruning Method",
+ "Small M",
+ "Random Prune",
+]
+
+PERFORMANCE_PLOT_PATH = './paper_plot/figures/H_hnsw_performance_comparison.pdf'
+SAVED_PATH = './paper_plot/figures/H_hnsw_recall_comparison.pdf'
+
+def extract_data_from_log(log_content):
+ """Extract method names, recall lists, and recompute lists from the log file."""
+
+ method_pattern = r"Building HNSW index with ([^\.]+)\.\.\.|Building HNSW index with ([^\n]+)..."
+ recall_list_pattern = r"recall_list: (\[[\d\., ]+\])"
+ recompute_list_pattern = r"recompute_list: (\[[\d\., ]+\])"
+ avg_neighbors_pattern = r"neighbors per node: ([\d\.]+)"
+
+ method_matches = re.findall(method_pattern, log_content)
+ # Temporary list for raw method identifiers from regex
+ _methods_raw_identifiers_regex = []
+ for match in method_matches:
+ method_ident = match[0] if match[0] else match[1]
+ _methods_raw_identifiers_regex.append(method_ident.strip().rstrip('.'))
+
+ recall_lists_str = re.findall(recall_list_pattern, log_content)
+ recompute_lists_str = re.findall(recompute_list_pattern, log_content)
+ avg_neighbors_str_list = re.findall(avg_neighbors_pattern, log_content) # Keep as string list for now
+
+ # Determine if regex approach was sufficient, similar to original logic
+ # This check helps decide if we use regex-extracted names or fallback to split-parsing
+ _min_len_for_regex_path = min(
+ len(_methods_raw_identifiers_regex) if _methods_raw_identifiers_regex else 0,
+ len(recall_lists_str) if recall_lists_str else 0,
+ len(recompute_lists_str) if recompute_lists_str else 0,
+ len(avg_neighbors_str_list) if avg_neighbors_str_list else 0
+ )
+
+ methods = [] # This will hold the final display names
+
+ if _min_len_for_regex_path < 4 : # Fallback path if regex didn't get enough (e.g., for 4 methods)
+ # print("Regex approach failed or yielded insufficient data, trying direct extraction...")
+ sections = log_content.split("Building HNSW index with ")[1:]
+ methods_temp = []
+ for section in sections:
+ method_name_raw = section.split("\n")[0].strip().rstrip('.')
+ # Apply new short names in fallback
+ if method_name_raw == 'hnsw_IP_M30_efC128': mapped_name = MAPPED_METHOD_NAMES[0]
+ elif method_name_raw.startswith('99_4_degree'): mapped_name = MAPPED_METHOD_NAMES[1]
+ elif method_name_raw.startswith('d9_hnsw'): mapped_name = MAPPED_METHOD_NAMES[2]
+ elif method_name_raw.startswith('half'): mapped_name = MAPPED_METHOD_NAMES[3]
+ else: mapped_name = method_name_raw # Fallback to raw if no rule
+ methods_temp.append(mapped_name)
+ methods = methods_temp
+ # If fallback provides fewer than 4 methods, reordering later might not apply or error
+ # print(f"Direct extraction found {len(methods)} methods: {methods}")
+ else: # Regex path considered sufficient
+ methods_temp = []
+ for raw_name in _methods_raw_identifiers_regex:
+ # Apply new short names for regex path too
+ if raw_name == 'hnsw_IP_M30_efC128': mapped_name = MAPPED_METHOD_NAMES[0]
+ elif raw_name.startswith('99_4_degree'): mapped_name = MAPPED_METHOD_NAMES[1]
+ elif raw_name.startswith('d9_hnsw'): mapped_name = MAPPED_METHOD_NAMES[2]
+ elif raw_name.startswith('half'): mapped_name = MAPPED_METHOD_NAMES[3] # Assumes 'half' is a good prefix
+ else: mapped_name = raw_name # Fallback to cleaned raw name
+ methods_temp.append(mapped_name)
+ methods = methods_temp
+ # print(f"Regex extraction found {len(methods)} methods: {methods}")
+
+ # Convert string lists of numbers to actual numbers
+ avg_neighbors = [float(avg) for avg in avg_neighbors_str_list]
+
+ # Reordering (This reordering is crucial for color consistency if colors are fixed by position)
+ # It assumes methods[0] is Base, methods[1] is Our, etc., *before* this reordering step
+ # if that was the natural order from logs. The reordering swaps 3rd and 4th items.
+ if len(methods) >= 4 and \
+ len(recall_lists_str) >= 4 and \
+ len(recompute_lists_str) >= 4 and \
+ len(avg_neighbors) >= 4:
+ # This reordering means:
+ # Original order assumed: HNSW-Base, DegreeGuide, HNSW-D9, RandCut
+ # After reorder: HNSW-Base, DegreeGuide, RandCut, HNSW-D9
+ methods = [methods[0], methods[1], methods[3], methods[2]]
+ recall_lists_str = [recall_lists_str[0], recall_lists_str[1], recall_lists_str[3], recall_lists_str[2]]
+ recompute_lists_str = [recompute_lists_str[0], recompute_lists_str[1], recompute_lists_str[3], recompute_lists_str[2]]
+ avg_neighbors = [avg_neighbors[0], avg_neighbors[1], avg_neighbors[3], avg_neighbors[2]]
+ # else:
+ # print("Warning: Not enough elements to perform standard reordering. Using data as found.")
+
+
+ if len(avg_neighbors) > 0 and avg_neighbors_str_list[0] == "17.35": # Note: avg_neighbors_str_list used for string comparison
+ target_avg_neighbors = [18, 9, 9, 9] # This seems to be a specific adjustment based on a known log state
+ current_len = len(avg_neighbors)
+ # Ensure this reordering matches the one applied to `methods` if avg_neighbors were reordered with them
+ # If avg_neighbors was reordered, this hardcoding might need adjustment or be applied pre-reorder.
+ # For now, assume it applies to the (potentially reordered) avg_neighbors list.
+ avg_neighbors = target_avg_neighbors[:current_len]
+
+
+ recall_lists = [eval(recall_list) for recall_list in recall_lists_str]
+ recompute_lists = [eval(recompute_list) for recompute_list in recompute_lists_str]
+
+ # Final truncation to ensure all lists have the same minimum length
+ min_length = min(len(methods), len(recall_lists), len(recompute_lists), len(avg_neighbors))
+
+ methods = methods[:min_length]
+ recall_lists = recall_lists[:min_length]
+ recompute_lists = recompute_lists[:min_length]
+ avg_neighbors = avg_neighbors[:min_length]
+
+ return methods, recall_lists, recompute_lists, avg_neighbors
+
+
+def plot_recall_comparison(methods, recall_lists, recompute_lists, avg_neighbors, current_recall_levels):
+ """Create a line chart comparing computation costs at different recall levels, with academic style."""
+ plt.rcParams["font.family"] = "Helvetica"
+ plt.rcParams["ytick.direction"] = "in"
+ # plt.rcParams["hatch.linewidth"] = 1.5 # From example, but not used in line plot
+ plt.rcParams["font.weight"] = "bold"
+ plt.rcParams["axes.labelweight"] = "bold"
+ plt.rcParams["text.usetex"] = True # Ensure LaTeX is available or set to False
+
+ computation_costs = []
+ for i, method_name in enumerate(methods): # methods now contains short names
+ method_costs = []
+ for level in current_recall_levels:
+ recall_idx = next((idx for idx, recall in enumerate(recall_lists[i]) if recall >= level), None)
+ if recall_idx is not None:
+ method_costs.append(recompute_lists[i][recall_idx])
+ else:
+ method_costs.append(None)
+ computation_costs.append(method_costs)
+
+ fig, ax = plt.subplots(figsize=(5,2.5))
+
+ # Modified academic_colors for consistency
+ # HNSW-Base (Grey), DegreeGuide (Red), RandCut (Cornflowerblue), HNSW-D9 (DarkBlue)
+ # academic_colors = ['dimgrey', 'tomato', 'cornflowerblue', '#003366', 'forestgreen', 'crimson']
+ academic_colors = [ 'slategray', 'tomato', 'cornflowerblue','#63B8B6',]
+ markers = ['o', '*', '^', 'D', 'v', 'P']
+ # Origin, Our, Random, SmallM
+
+
+ for i, method_name in enumerate(methods): # method_name is now short, e.g., 'HNSW-Base'
+ color_idx = i % len(academic_colors)
+ marker_idx = i % len(markers)
+
+ y_values_plot = [val if val is not None else np.nan for val in computation_costs[i]]
+ y_values_plot = [val / 10000 if val is not None else np.nan for val in computation_costs[i]]
+
+ if method_name == MAPPED_METHOD_NAMES[0]: # Original HNSW-Base
+ linestyle = '--'
+ else:
+ linestyle = '-'
+ if method_name == MAPPED_METHOD_NAMES[1]: # Our Pruning Method
+ marker_size = 12
+ elif method_name == MAPPED_METHOD_NAMES[2]: # Small M
+ marker_size = 7.5
+ else:
+ marker_size = 8
+ if method_name == MAPPED_METHOD_NAMES[1]: # Our Pruning Method
+ zorder = 10
+ else:
+ zorder = 1
+
+ # for random prune
+ if method_name == MAPPED_METHOD_NAMES[3]:
+ y_values_plot[0] += 0.12 # To prevent overlap with our method
+ elif method_name == MAPPED_METHOD_NAMES[1]:
+ y_values_plot[0] -= 0.06 # To prevent overlap with original hnsw
+
+ ax.plot(current_recall_levels, y_values_plot,
+ label=f"{method_name} (Avg Degree: {int(avg_neighbors[i])})", # Uses new short names
+ color=academic_colors[color_idx], marker=markers[marker_idx], markeredgecolor='#FFFFFF80', # zhege miaobian shibushi buhaokan()
+ markersize=marker_size, linewidth=2, linestyle=linestyle, zorder=zorder)
+
+ ax.set_xlabel('Recall Target', fontsize=9, fontweight="bold")
+ ax.set_ylabel('Nodes to Recompute', fontsize=9, fontweight="bold")
+ ax.set_xticks(current_recall_levels)
+ ax.set_xticklabels([f'{level*100:.0f}\%' for level in current_recall_levels], fontsize=10)
+ ax.tick_params(axis='y', labelsize=10)
+
+ ax.set_ylabel(r'Nodes to Recompute ($\mathbf{\times 10^4}$)', fontsize=9, fontweight="bold")
+
+ # Legend styling (already moved up from previous request)
+ ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1.02), ncol=2,
+ fontsize=6, edgecolor="black", facecolor="white", framealpha=1,
+ shadow=False, fancybox=False, prop={"weight": "normal", "size": 8})
+
+ # No grid lines: ax.grid(True, linestyle='--', alpha=0.7)
+
+ # Spines adjustment for academic look
+ ax.spines['top'].set_visible(False)
+ ax.spines['right'].set_visible(False)
+ ax.spines['left'].set_linewidth(1.0)
+ ax.spines['bottom'].set_linewidth(1.0)
+
+ annot_recall_level_92 = 0.92
+ if annot_recall_level_92 in current_recall_levels:
+ annot_recall_idx_92 = current_recall_levels.index(annot_recall_level_92)
+ method_base_name = "Our Pruning Method"
+ method_compare_92_name = "Small M"
+
+ if method_base_name in methods and method_compare_92_name in methods:
+ idx_base = methods.index(method_base_name)
+ idx_compare_92 = methods.index(method_compare_92_name)
+ cost_base_92 = computation_costs[idx_base][annot_recall_idx_92] / 10000
+ cost_compare_92 = computation_costs[idx_compare_92][annot_recall_idx_92] / 10000
+
+ if cost_base_92 is not None and cost_compare_92 is not None and cost_base_92 > 0:
+ ratio_92 = cost_compare_92 / cost_base_92
+ ax.annotate("", xy=(annot_recall_level_92, cost_compare_92),
+ xytext=(annot_recall_level_92, cost_base_92),
+ arrowprops=dict(arrowstyle="<->", color='#333333',
+ lw=1.5, mutation_scale=15,
+ shrinkA=3, shrinkB=3),
+ zorder=10) # Arrow drawn first
+
+ text_x_pos_92 = annot_recall_level_92 # Text x is on the arrow line
+ text_y_pos_92 = (cost_base_92 + cost_compare_92) / 2
+ plot_ymin, plot_ymax = ax.get_ylim() # Boundary checks
+ if text_y_pos_92 < plot_ymin + (plot_ymax-plot_ymin)*0.05: text_y_pos_92 = plot_ymin + (plot_ymax-plot_ymin)*0.05
+ if text_y_pos_92 > plot_ymax - (plot_ymax-plot_ymin)*0.05: text_y_pos_92 = plot_ymax - (plot_ymax-plot_ymin)*0.05
+
+ ax.text(text_x_pos_92, text_y_pos_92, f"{ratio_92:.2f}x",
+ fontsize=9, color='black',
+ va='center', ha='center', # Centered horizontally and vertically
+ bbox=dict(boxstyle='square,pad=0.25', # Creates space around text
+ fc='white', # Face color matches plot background
+ ec='white', # Edge color matches plot background
+ alpha=1.0), # Fully opaque
+ zorder=11) # Text on top of arrow
+
+ # --- Annotation for performance gap at 96% recall (0.96) ---
+ annot_recall_level_96 = 0.96
+ if annot_recall_level_96 in current_recall_levels:
+ annot_recall_idx_96 = current_recall_levels.index(annot_recall_level_96)
+ method_base_name = "Our Pruning Method"
+ method_compare_96_name = "Random Prune"
+
+ if method_base_name in methods and method_compare_96_name in methods:
+ idx_base = methods.index(method_base_name)
+ idx_compare_96 = methods.index(method_compare_96_name)
+ cost_base_96 = computation_costs[idx_base][annot_recall_idx_96] / 10000
+ cost_compare_96 = computation_costs[idx_compare_96][annot_recall_idx_96] / 10000
+
+ if cost_base_96 is not None and cost_compare_96 is not None and cost_base_96 > 0:
+ ratio_96 = cost_compare_96 / cost_base_96
+ ax.annotate("", xy=(annot_recall_level_96, cost_compare_96),
+ xytext=(annot_recall_level_96, cost_base_96),
+ arrowprops=dict(arrowstyle="<->", color='#333333',
+ lw=1.5, mutation_scale=15,
+ shrinkA=3, shrinkB=3),
+ zorder=10) # Arrow drawn first
+
+ text_x_pos_96 = annot_recall_level_96 # Text x is on the arrow line
+ text_y_pos_96 = (cost_base_96 + cost_compare_96) / 2
+ plot_ymin, plot_ymax = ax.get_ylim() # Boundary checks
+ if text_y_pos_96 < plot_ymin + (plot_ymax-plot_ymin)*0.05: text_y_pos_96 = plot_ymin + (plot_ymax-plot_ymin)*0.05
+ if text_y_pos_96 > plot_ymax - (plot_ymax-plot_ymin)*0.05: text_y_pos_96 = plot_ymax - (plot_ymax-plot_ymin)*0.05
+
+ ax.text(text_x_pos_96, text_y_pos_96, f"{ratio_96:.2f}x",
+ fontsize=9, color='black',
+ va='center', ha='center', # Centered horizontally and vertically
+ bbox=dict(boxstyle='square,pad=0.25', # Creates space around text
+ fc='white', # Face color matches plot background
+ ec='white', # Edge color matches plot background
+ alpha=1.0), # Fully opaque
+ zorder=11) # Text on top of arrow
+
+
+ plt.tight_layout(pad=0.5)
+ plt.savefig(SAVED_PATH, bbox_inches="tight", dpi=300)
+ plt.show()
+
+# --- Main script execution ---
+parser = argparse.ArgumentParser()
+parser.add_argument("log_file", type=str, default="./demo/output.log")
+args = parser.parse_args()
+
+try:
+ with open(args.log_file, 'r') as f:
+ log_content = f.read()
+except FileNotFoundError:
+ print(f"Error: Log file '{args.log_file}' not found.")
+ exit()
+
+methods, recall_lists, recompute_lists, avg_neighbors = extract_data_from_log(log_content)
+
+if methods:
+ # plot_performance(methods, recall_lists, recompute_lists, avg_neighbors)
+ # print(f"Performance plot saved to {PERFORMANCE_PLOT_PATH}")
+
+ plot_recall_comparison(methods, recall_lists, recompute_lists, avg_neighbors, recall_levels)
+ print(f"Recall comparison plot saved to {SAVED_PATH}")
+
+ print("\nMethod Summary:")
+ for i, method in enumerate(methods):
+ print(f"{method}:")
+ if i < len(avg_neighbors): # Check index bounds
+ print(f" - Average neighbors per node: {avg_neighbors[i]:.2f}")
+
+ for level in recall_levels:
+ if i < len(recall_lists) and i < len(recompute_lists): # Check index bounds
+ recall_idx = next((idx for idx, recall_val in enumerate(recall_lists[i]) if recall_val >= level), None)
+ if recall_idx is not None:
+ print(f" - Computations needed for {level*100:.0f}% recall: {recompute_lists[i][recall_idx]:.0f}")
+ else:
+ print(f" - Does not reach {level*100:.0f}% recall in the test")
+ else:
+ print(f" - Data missing for recall/recompute lists for method {method}")
+ print()
+else:
+ print("No data extracted from the log file. Cannot generate plots or summary.")
\ No newline at end of file
diff --git a/research/paper_plot/main_exp.py b/research/paper_plot/main_exp.py
new file mode 100644
index 0000000..bf8efed
--- /dev/null
+++ b/research/paper_plot/main_exp.py
@@ -0,0 +1,441 @@
+import matplotlib.pyplot as plt
+import seaborn as sns
+import matplotlib.lines as mlines
+import pandas as pd
+import numpy as np
+from matplotlib.patches import FancyArrowPatch
+
+sns.set_theme(style="ticks", font_scale=1.2)
+plt.rcParams['axes.grid'] = True
+plt.rcParams['axes.grid.which'] = 'major'
+plt.rcParams['grid.linestyle'] = '--'
+plt.rcParams['grid.color'] = 'gray'
+plt.rcParams['grid.alpha'] = 0.3
+plt.rcParams['xtick.minor.visible'] = False
+plt.rcParams['ytick.minor.visible'] = False
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["text.usetex"] = True
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+# Generation(LLama 1B) Generation(LLama 3B) Generation(LLama 7B)
+# 0.085s 0.217s 0.472s
+# llm_inference_time=[0.085, 0.217, 0.472, 0] # Will be replaced by CSV data
+# llm_inference_time_for_mac = [0.316, 0.717, 1.468, 0] # Will be replaced by CSV data
+
+def parse_latency_data(csv_path):
+ df = pd.read_csv(csv_path)
+ latency_data = {}
+ llm_gen_times = {} # To store LLM generation times: (dataset, hardware) -> time
+
+ for _, row in df.iterrows():
+ dataset = row['Dataset']
+ hardware = row['Hardware']
+ recall_target_str = row['Recall_target'].replace('%', '')
+ try:
+ recall_target = float(recall_target_str)
+ except ValueError:
+ print(f"Warning: Could not parse recall_target '{row['Recall_target']}'. Skipping row.")
+ continue
+
+ if (dataset, hardware) not in llm_gen_times: # Read once per (dataset, hardware)
+ llm_time_val = pd.to_numeric(row.get('LLM_Gen_Time_1B'), errors='coerce')
+ if not pd.isna(llm_time_val):
+ llm_gen_times[(dataset, hardware)] = llm_time_val
+ else:
+ llm_gen_times[(dataset, hardware)] = np.nan # Store NaN if unparsable/missing
+
+ cols_to_skip = ['Dataset', 'Hardware', 'Recall_target',
+ 'LLM_Gen_Time_1B', 'LLM_Gen_Time_3B', 'LLM_Gen_Time_7B']
+
+ for col in df.columns:
+ if col not in cols_to_skip:
+ method_name = col
+ key = (dataset, hardware, method_name)
+ if key not in latency_data:
+ latency_data[key] = []
+ try:
+ latency_value = float(row[method_name])
+ latency_data[key].append((recall_target, latency_value))
+ except ValueError:
+ # Handle cases where latency might be non-numeric (e.g., 'N/A' or empty)
+ print(f"Warning: Could not parse latency for {method_name} at {dataset}/{hardware}/Recall {recall_target} ('{row[method_name]}'). Skipping this point.")
+ latency_data[key].append((recall_target, np.nan)) # Or skip appending
+
+ # Sort by recall for consistent plotting
+ for key in latency_data:
+ latency_data[key].sort(key=lambda x: x[0])
+ return latency_data, llm_gen_times
+
+def parse_storage_data(csv_path):
+ df = pd.read_csv(csv_path)
+ storage_data = {}
+ # Assuming the first column is 'MetricType' (RAM/Storage) and subsequent columns are methods
+ # And the header row is like: MetricType, Method1, Method2, ...
+ # Transpose to make methods as rows for easier lookup might be an option,
+ # but let's try direct parsing.
+
+ # Find the row for RAM and Storage
+ ram_row = df[df.iloc[:, 0] == 'RAM'].iloc[0]
+ storage_row = df[df.iloc[:, 0] == 'Storage'].iloc[0]
+
+ methods = df.columns[1:] # First column is the metric type label
+ for method in methods:
+ storage_data[method] = {
+ 'RAM': pd.to_numeric(ram_row[method], errors='coerce'),
+ 'Storage': pd.to_numeric(storage_row[method], errors='coerce')
+ }
+ return storage_data
+
+# Load data
+latency_csv_path = 'paper_plot/data/main_latency.csv'
+storage_csv_path = 'paper_plot/data/ram_storage.csv'
+latency_data, llm_generation_times = parse_latency_data(latency_csv_path)
+storage_info = parse_storage_data(storage_csv_path)
+
+# --- Determine unique Datasets and Hardware combinations to plot for ---
+unique_dataset_hardware_configs = sorted(list(set((d, h) for d, h, m in latency_data.keys())))
+
+if not unique_dataset_hardware_configs:
+ print("Error: No (Dataset, Hardware) combinations found in latency data. Check CSV paths and content.")
+ exit()
+
+# --- Define constants for plotting ---
+all_method_names = sorted(list(set(m for d,h,m in latency_data.keys())))
+if not all_method_names:
+ # Fallback if latency_data is empty but storage_info might have method names
+ all_method_names = sorted(list(storage_info.keys()))
+
+if not all_method_names:
+ print("Error: No method names found in data. Cannot proceed with plotting.")
+ exit()
+
+method_markers = {
+ 'HNSW': 'o',
+ 'IVF': 'X',
+ 'DiskANN': 's',
+ 'IVF-Disk': 'P',
+ 'IVF-Recompute': '^',
+ 'Our': '*',
+ 'BM25': "v"
+ # Add more if necessary, or make it dynamic
+}
+method_display_names = {
+ 'IVF-Recompute': 'IVF-Recompute (EdgeRAG)',
+ # 其他方法保持原名
+}
+
+# Ensure all methods have a marker
+default_markers = ['^', 'v', '<', '>', 'H', 'h', '+', 'x', '|', '_']
+next_default_marker = 0
+for mn in all_method_names:
+ if mn not in method_markers:
+ print(f"mn: {mn}")
+ method_markers[mn] = default_markers[next_default_marker % len(default_markers)]
+ next_default_marker +=1
+
+recall_levels_present = sorted(list(set(r for key in latency_data for r, l in latency_data[key])))
+# Define colors for up to a few common recall levels, add more if needed
+base_recall_colors = {
+ 85.0: "#1f77b4", # Blue
+ 90.0: "#ff7f0e", # Orange
+ 95.0: "#2ca02c", # Green
+ # Add more if other recall % values exist
+}
+recall_colors = {}
+color_palette = sns.color_palette("viridis", n_colors=len(recall_levels_present))
+
+for idx, r_level in enumerate(recall_levels_present):
+ recall_colors[r_level] = base_recall_colors.get(r_level, color_palette[idx % len(color_palette)])
+
+
+# --- Determine global x (latency) and y (storage) limits for consistent axes ---
+all_latency_values = []
+all_storage_values = []
+raw_data_size = 76 # Raw data size in GB
+
+for ds_hw_key in unique_dataset_hardware_configs:
+ current_ds, current_hw = ds_hw_key
+ for method_name in all_method_names:
+ # Get storage for this method
+ disk_storage = storage_info.get(method_name, {}).get('Storage', np.nan)
+ if not np.isnan(disk_storage):
+ all_storage_values.append(disk_storage)
+
+ # Get latencies for this method under current_ds, current_hw
+ latency_key = (current_ds, current_hw, method_name)
+ if latency_key in latency_data:
+ for recall, latency in latency_data[latency_key]:
+ if not np.isnan(latency):
+ all_latency_values.append(latency)
+
+# Add padding to limits
+min_lat = min(all_latency_values) if all_latency_values else 0.001
+max_lat = max(all_latency_values) if all_latency_values else 1
+min_store = min(all_storage_values) if all_storage_values else 0
+max_store = max(all_storage_values) if all_storage_values else 1
+
+# Convert storage values to proportion of raw data
+min_store_proportion = min_store / raw_data_size if all_storage_values else 0
+max_store_proportion = max_store / raw_data_size if all_storage_values else 0.1
+
+# Padding for log scale latency - adjust minimum to be more reasonable
+lat_log_min = -1 # Changed from -2 to -1 to set minimum to 10^-1 (0.1s)
+lat_log_max = np.log10(max_lat) if max_lat > 0 else 3 # default to 1000 s
+lat_padding = (lat_log_max - lat_log_min) * 0.05
+global_xlim = [10**(lat_log_min - lat_padding), 10**(lat_log_max + lat_padding)]
+if global_xlim[0] <= 0: global_xlim[0] = 0.1 # Changed from 0.01 to 0.1
+
+# Padding for linear scale storage proportion
+store_padding = (max_store_proportion - min_store_proportion) * 0.05
+global_ylim = [max(0, min_store_proportion - store_padding), max_store_proportion + store_padding]
+if global_ylim[0] >= global_ylim[1]: # Avoid inverted or zero range
+ global_ylim[1] = global_ylim[0] + 0.1
+
+# After loading the data and before plotting, add this code to reorder the datasets
+# Find where you define all_datasets (around line 95)
+
+# Original code:
+all_datasets = sorted(list(set(ds for ds, _ in unique_dataset_hardware_configs)))
+
+# Replace with this to specify the exact order:
+all_datasets_unsorted = list(set(ds for ds, _ in unique_dataset_hardware_configs))
+desired_order = ['NQ', 'TriviaQA', 'GPQA','HotpotQA']
+all_datasets = [ds for ds in desired_order if ds in all_datasets_unsorted]
+# Add any datasets that might be in the data but not in our desired_order list
+all_datasets.extend([ds for ds in all_datasets_unsorted if ds not in desired_order])
+
+# Then the rest of your code remains the same:
+a10_configs = [(ds, 'A10') for ds in all_datasets if (ds, 'A10') in unique_dataset_hardware_configs]
+mac_configs = [(ds, 'MAC') for ds in all_datasets if (ds, 'MAC') in unique_dataset_hardware_configs]
+
+# Create two figures - one for A10 and one for MAC
+hardware_configs = [a10_configs, mac_configs]
+hardware_names = ['A10', 'MAC']
+
+for fig_idx, configs_for_this_figure in enumerate(hardware_configs):
+ if not configs_for_this_figure:
+ continue
+
+ num_cols_this_figure = len(configs_for_this_figure)
+ # 1 row, num_cols_this_figure columns
+ fig, axs = plt.subplots(1, num_cols_this_figure, figsize=(7 * num_cols_this_figure, 6), sharex=True, sharey=True, squeeze=False)
+
+ # fig.suptitle(f"Latency vs. Storage ({hardware_names[fig_idx]})", fontsize=18, y=0.98)
+
+ for subplot_idx, (current_ds, current_hw) in enumerate(configs_for_this_figure):
+ ax = axs[0, subplot_idx] # Accessing column in the first row
+ ax.set_title(f"{current_ds}", fontsize=25) # No need to show hardware in title since it's in suptitle
+
+ for method_name in all_method_names:
+ marker = method_markers.get(method_name, '+')
+ disk_storage = storage_info.get(method_name, {}).get('Storage', np.nan)
+
+ latency_points_key = (current_ds, current_hw, method_name)
+ if latency_points_key in latency_data:
+ points_for_method = latency_data[latency_points_key]
+ print(f"points_for_method: {points_for_method}")
+ for recall, latency in points_for_method:
+ # Only skip if latency is invalid (since we need log scale for x-axis)
+ # But allow zero storage since y-axis is now linear
+ if np.isnan(latency) or np.isnan(disk_storage) or latency <= 0:
+ continue
+
+ # Add LLM generation time from CSV
+ current_llm_add_time = llm_generation_times.get((current_ds, current_hw))
+ if current_llm_add_time is not None and not np.isnan(current_llm_add_time):
+ latency = latency + current_llm_add_time
+ else:
+ raise ValueError(f"No LLM generation time found for {current_ds} on {current_hw}")
+
+ # Special handling for BM25
+ if method_name == 'BM25':
+ # BM25 is only valid for 85% recall points (other points are 0)
+ if recall != 85.0:
+ continue
+ color = 'grey'
+ else:
+ # Use the color for target recall
+ color = recall_colors.get(recall, 'grey')
+
+ # Convert storage to proportion
+ disk_storage_proportion = disk_storage / raw_data_size
+ size = 80
+
+ x_offset = -50
+ if current_ds == 'GPQA':
+ x_offset = -32
+
+ # Apply a small vertical offset to IVF-Recompute points to make them more visible
+ if method_name == 'IVF-Recompute':
+ # Add a small vertical offset (adjust the 0.05 value as needed)
+ disk_storage_proportion += 0.07
+ size = 80
+ if method_name == 'DiskANN':
+ size = 50
+ if method_name == 'Our':
+ size = 140
+ disk_storage_proportion += 0.05
+ # Add "Pareto Frontier" label to Our method points
+
+ if recall == 95:
+ ax.annotate('Ours',
+ (latency, disk_storage_proportion),
+ xytext=(x_offset, 25), # Increased leftward offset from -65 to -120
+ textcoords='offset points',
+ fontsize=20,
+ color='red',
+ weight='bold',
+ bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="red", alpha=0.7))
+ # Increase size for BM25 points
+ if method_name == 'BM25':
+ size = 70
+ size*=5
+
+ ax.scatter(latency, disk_storage_proportion, marker=marker, color=color,
+ s=size, alpha=0.85, edgecolors='black', linewidths=0.7)
+
+
+
+
+ ax.set_xscale("log")
+ ax.set_yscale("linear") # CHANGED from log scale to linear scale for Y-axis
+
+ # Generate appropriate powers of 10 based on your data range
+ min_power = -1
+ max_power = 4
+ log_ticks = [10**i for i in range(min_power, max_power+1)]
+
+ # Set custom tick positions
+ ax.set_xticks(log_ticks)
+
+ # Create custom bold LaTeX labels with 10^n format
+ log_tick_labels = [fr'$\mathbf{{10^{{{i}}}}}$' for i in range(min_power, max_power+1)]
+ ax.set_xticklabels(log_tick_labels, fontsize=24)
+
+ # Apply global limits
+ if subplot_idx == 0:
+ ax.set_xlim(global_xlim)
+ ax.set_ylim(global_ylim)
+
+ ax.grid(True, which="major", linestyle="--", linewidth=0.6, alpha=0.7)
+ # Remove minor grid lines completely
+ ax.grid(False, which="minor")
+
+ # Remove ticks
+ # First set the shared parameters for both axes
+ ax.tick_params(axis='both', which='both', length=0, labelsize=24)
+
+ # Then set the padding only for the x-axis
+ ax.tick_params(axis='x', which='both', pad=10)
+
+ if subplot_idx == 0: # Y-label only for the leftmost subplot
+ ax.set_ylabel("Proportional Size", fontsize=24)
+
+ # X-label for all subplots in a 1xN layout can be okay, or just the middle/last one.
+ # Let's put it on all for now.
+ ax.set_xlabel("Latency (s)", fontsize=25)
+
+ # Display 100%, 200%, 300% for yaxis
+ ax.set_yticks([1, 2, 3])
+ ax.set_yticklabels(['100\%', '200\\%', '300\\%'])
+
+ # Create a custom arrow with "Better" text inside
+ # Create the arrow patch with a wider shaft
+ arrow = FancyArrowPatch(
+ (0.8, 0.8), # Start point (top-right)
+ (0.65, 0.6), # End point (toward bottom-left)
+ transform=ax.transAxes,
+ arrowstyle='simple,head_width=40,head_length=35,tail_width=20', # Increased arrow dimensions
+ facecolor='white',
+ edgecolor='black',
+ linewidth=3, # Thicker outline
+ zorder=5
+ )
+
+ # Add the arrow to the plot
+ ax.add_patch(arrow)
+
+ # Calculate the midpoint of the arrow for text placement
+ mid_x = (0.8 + 0.65) / 2 + 0.002 + 0.01
+ mid_y = (0.8 + 0.6) / 2 + 0.01
+
+ # Add the "Better" text at the midpoint of the arrow
+ ax.text(mid_x, mid_y, 'Better',
+ transform=ax.transAxes,
+ ha='center',
+ va='center',
+ fontsize=16, # Increased font size from 12 to 16
+ fontweight='bold',
+ rotation=40, # Rotate to match arrow direction
+ zorder=6) # Ensure text is on top of arrow
+
+ # Create legends (once per figure)
+ method_legend_handles = []
+ for method, marker_style in method_markers.items():
+ if method in all_method_names:
+ print(f"method: {method}")
+ # Use black color for BM25 in the legend
+ if method == 'BM25':
+ method_legend_handles.append(mlines.Line2D([], [], color='black', marker=marker_style, linestyle='None',
+ markersize=10, label=method))
+ else:
+ if method in method_display_names:
+ method = method_display_names[method]
+ method_legend_handles.append(mlines.Line2D([], [], color='black', marker=marker_style, linestyle='None',
+ markersize=10, label=method))
+
+ recall_legend_handles = []
+ sorted_recall_levels = sorted(recall_colors.keys())
+ for r_level in sorted_recall_levels:
+ recall_legend_handles.append(mlines.Line2D([], [], color=recall_colors[r_level], marker='o', linestyle='None',
+ markersize=20, label=f"Target Recall={r_level:.0f}\%"))
+
+ # 将图例分成两行:第一行是方法,第二行是召回率
+ if fig_idx == 0:
+ # 从方法列表中先排除'Our'
+ other_methods = [m for m in all_method_names if m != 'Our']
+ # 按照需要的顺序创建方法列表(将'Our'放在最后)
+ ordered_methods = other_methods + (['Our'] if 'Our' in all_method_names else [])
+
+ # 按照新顺序创建方法图例句柄
+ method_legend_handles = []
+ for method in ordered_methods:
+ if method in method_markers:
+ marker_style = method_markers[method]
+ # 使用显示名称映射
+ display_name = method_display_names.get(method, method)
+ color = 'black'
+ marker_size = 22
+ if method == 'Our':
+ marker_size = 27
+ elif 'IVF-Recompute' in method or 'EdgeRAG' in method:
+ marker_size = 17
+ elif 'DiskANN' in method:
+ marker_size = 19
+ elif 'BM25' in method:
+ marker_size = 20
+ method_legend_handles.append(mlines.Line2D([], [], color=color, marker=marker_style,
+ linestyle='None', markersize=marker_size, label=display_name))
+
+ # 创建召回率图例(第二行)- 注意位置调整,放在方法图例下方
+ recall_legend = fig.legend(handles=recall_legend_handles,
+ loc='upper center', bbox_to_anchor=(0.5, 1.05), # y坐标降低,放在第一行下方
+ ncol=len(recall_legend_handles), fontsize=28)
+
+
+ # 创建方法图例(第一行)
+ method_legend = fig.legend(handles=method_legend_handles,
+ loc='upper center', bbox_to_anchor=(0.5, 0.91),
+ ncol=len(method_legend_handles), fontsize=28)
+
+ # 添加图例到渲染器
+ fig.add_artist(method_legend)
+ fig.add_artist(recall_legend)
+
+ # 调整布局,为顶部的两行图例留出更多空间
+ plt.tight_layout(rect=(0, 0, 1.0, 0.74)) # 顶部空间从0.9调整到0.85,给两行图例留出更多空间
+
+ save_path = f'./paper_plot/figures/main_exp_fig_{fig_idx+1}.pdf'
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
+ print(f"Saved figure {fig_idx+1} to {save_path}")
+ plt.show()
\ No newline at end of file
diff --git a/research/paper_plot/main_latency.py b/research/paper_plot/main_latency.py
new file mode 100644
index 0000000..4a48dab
--- /dev/null
+++ b/research/paper_plot/main_latency.py
@@ -0,0 +1,163 @@
+import csv
+
+import numpy as np
+import matplotlib.pyplot as plt
+import csv
+
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 1
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True
+SAVE_PTH = "./paper_plot/figures"
+font_size = 16
+
+# Generation(LLama 1B) Generation(LLama 3B) Generation(LLama 7B)
+# 0.085s 0.217s 0.472s
+llm_inference_time=[0.085, 0.217, 0.472, 0]
+
+USE_LLM_INDEX = 3 # +0
+
+file_path = "./paper_plot/data/main_latency.csv"
+
+with open(file_path, mode="r", newline="") as file:
+ reader = csv.reader(file)
+ data = list(reader)
+
+# 打印原始数据
+for row in data:
+ print(",".join(row))
+
+
+
+
+models = ["A10", "MAC"]
+datasets = ["NQ", "TriviaQA", "GPQA", "HotpotQA"]
+data = [[float(cell) if cell.isdigit() else cell for cell in row] for row in data[1:]]
+for k, model in enumerate(models):
+
+ fig, axes = plt.subplots(1, 4)
+ fig.set_size_inches(20, 3)
+ plt.subplots_adjust(wspace=0, hspace=0)
+
+ total_width, n = 6, 6
+ group = 1
+ width = total_width * 0.9 / n
+ x = np.arange(group) * n
+ exit_idx_x = x + (total_width - width) / n
+ edgecolors = ["dimgrey", "#63B8B6", "tomato", "slategray", "mediumpurple", "green", "red", "blue", "yellow", "silver"]
+ # hatches = ["", "\\\\", "//", "||", "x", "--", "..", "", "\\\\", "//", "||", "x", "--", ".."]
+ hatches =["\\\\\\","\\\\"]
+
+ labels = [
+ "HNSW",
+ "IVF",
+ "DiskANN",
+ "IVF-Disk",
+ "IVF-Recompute",
+ "Our",
+ # "DGL-OnDisk",
+ ]
+ if k == 0:
+ x_labels = "GraphSAGE"
+ else:
+ x_labels = "GAT"
+
+ yticks = [0.01, 0.1, 1, 10, 100, 1000,10000] # Log scale ticks
+ val_limit = 15000 # Upper limit for the plot
+
+ for i in range(4):
+ axes[i].set_yscale('log') # Set y-axis to logarithmic scale
+ axes[i].set_yticks(yticks)
+ axes[i].set_ylim(0.01, val_limit) # Lower limit should be > 0 for log scale
+
+ axes[i].tick_params(axis="y", labelsize=10)
+
+ axes[i].set_xticks([])
+ # axes[i].set_xticklabels()
+ axes[i].set_xlabel(datasets[i], fontsize=font_size)
+ axes[i].grid(axis="y", linestyle="--")
+ axes[i].set_xlim(exit_idx_x[0] - 0.15 * width - 0.2, exit_idx_x[0] + (n-0.25)* width + 0.2)
+ for j in range(n):
+ ##TODO add label
+
+ # num = float(data[i * 2 + k][j + 3])
+ # plot_label = [num]
+ # if j == 6 and i == 3:
+ # plot_label = ["N/A"]
+ # num = 0
+ local_hatches=["////","\\\\","xxxx"]
+ # here add 3 bars rather than one bar TODO
+ print('exit_idx_x',exit_idx_x)
+
+ # Check if all three models for this algorithm are OOM (data = 0)
+ is_oom = True
+ for m in range(3):
+ if float(data[i * 6 + k*3 + m][j + 3]) != 0:
+ is_oom = False
+ break
+
+ if is_oom:
+ # Draw a cross for OOM instead of bars
+ pos = exit_idx_x + j * width + width * 0.3 # Center position for cross
+ marker_size = width * 150 # Size of the cross
+ axes[i].scatter(pos, 0.02, marker='x', color=edgecolors[j], s=marker_size,
+ linewidth=4, label=labels[j] if j < len(labels) else "", zorder=20)
+ else:
+ # Create three separate bar calls instead of trying to plot multiple bars at once
+ for m in range(3):
+ num = float(data[i * 6 + k*3 +m][j + 3]) +llm_inference_time[USE_LLM_INDEX]
+ plot_label = [num]
+ pos = exit_idx_x + j * width + width * 0.3 * m
+ print(f"j: {j}, m: {m}, pos: {pos}")
+ # For log scale, we need to ensure values are positive
+ plot_value = max(0.01, num) if num < val_limit else val_limit
+ container = axes[i].bar(
+ pos,
+ plot_value,
+ width=width * 0.3,
+ color="white",
+ edgecolor=edgecolors[j],
+ # edgecolor="k",
+ hatch=local_hatches[m], # Use different hatches for each of the 3 bars
+ linewidth=1.0,
+ label=labels[j] if m == 0 else "", # Only add label for the first bar
+ zorder=10,
+ )
+ # axes[i].bar_label(
+ # container,
+ # plot_label,
+ # fontsize=font_size - 2,
+ # zorder=200,
+ # fontweight="bold",
+ # )
+
+ if k == 0:
+ axes[0].legend(
+ bbox_to_anchor=(3.25, 1.02),
+ ncol=7,
+ loc="lower right",
+ # fontsize=font_size,
+ # markerscale=3,
+ labelspacing=0.2,
+ edgecolor="black",
+ facecolor="white",
+ framealpha=1,
+ shadow=False,
+ # fancybox=False,
+ handlelength=2,
+ handletextpad=0.5,
+ columnspacing=0.5,
+ prop={"weight": "bold", "size": font_size},
+ ).set_zorder(100)
+
+ axes[0].set_ylabel("Runtime (log scale)", fontsize=font_size, fontweight="bold")
+ axes[0].set_yticklabels([r"$10^{-2}$", r"$10^{-1}$", r"$10^{0}$", r"$10^{1}$", r"$10^{2}$", r"$10^{3}$",r"$10^{4}$"], fontsize=font_size)
+ axes[1].set_yticklabels([])
+ axes[2].set_yticklabels([])
+ axes[3].set_yticklabels([])
+
+ plt.savefig(f"{SAVE_PTH }/speed_{model}_revised.pdf", bbox_inches="tight", dpi=300)
+ ## print save
+ print(f"{SAVE_PTH }/speed_{model}_revised.pdf")
\ No newline at end of file
diff --git a/research/paper_plot/main_memory_storage.py b/research/paper_plot/main_memory_storage.py
new file mode 100644
index 0000000..889ccd6
--- /dev/null
+++ b/research/paper_plot/main_memory_storage.py
@@ -0,0 +1,85 @@
+from matplotlib import pyplot as plt
+from matplotlib.gridspec import GridSpec
+
+# Comment Test
+
+# om script.settings import DATA_PATH, FIGURE_PATH
+# DATA_PATH ="/home/ubuntu/Power-RAG/paper_plot/data"
+# FIGURE_PATH = "/home/ubuntu/Power-RAG/paper_plot/figures"
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 2
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True
+
+import numpy as np
+import pandas as pd
+
+# Load the RAM and Storage data directly from CSV
+data = pd.read_csv("./paper_plot/data/ram_storage.csv")
+
+# Explicitly reorder columns to ensure "Our" is at the end
+cols = list(data.columns)
+if "Our" in cols and cols[-1] != "Our":
+ cols.remove("Our")
+ cols.append("Our")
+ data = data[cols]
+
+# Set up the figure with two columns
+fig = plt.figure(figsize=(12, 3))
+gs = GridSpec(1, 2, figure=fig)
+ax1 = fig.add_subplot(gs[0, 0]) # Left panel for RAM
+ax2 = fig.add_subplot(gs[0, 1]) # Right panel for Storage
+
+# Define the visual style elements
+edgecolors = ["dimgrey", "#63B8B6", "tomato", "slategray", "silver", "navy"]
+hatches = ["/////", "\\\\\\\\\\"]
+
+# Calculate positions for the bars
+methods = data.columns[1:] # Skip the 'Hardware' column
+num_methods = len(methods)
+# Reverse the order of methods for display (to have "Our" at the bottom)
+methods = list(methods)[::-1]
+y_positions = np.arange(num_methods)
+bar_width = 0.6
+
+# Plot RAM data in left panel
+ram_bars = ax1.barh(
+ y_positions,
+ data.iloc[0, 1:].values[::-1], # Reverse the data to match reversed methods
+ height=bar_width,
+ color="white",
+ edgecolor=edgecolors[0],
+ hatch=hatches[0],
+ linewidth=1.0,
+ label="RAM",
+ zorder=10,
+)
+ax1.set_title("RAM Usage", fontsize=14, fontweight='bold')
+ax1.set_yticks(y_positions)
+ax1.set_yticklabels(methods, fontsize=14)
+ax1.set_xlabel("Size (\\textit{GB})", fontsize=14)
+ax1.xaxis.set_tick_params(labelsize=14)
+
+# Plot Storage data in right panel
+storage_bars = ax2.barh(
+ y_positions,
+ data.iloc[1, 1:].values[::-1], # Reverse the data to match reversed methods
+ height=bar_width,
+ color="white",
+ edgecolor=edgecolors[1],
+ hatch=hatches[1],
+ linewidth=1.0,
+ label="Storage",
+ zorder=10,
+)
+ax2.set_title("Storage Usage", fontsize=14, fontweight='bold')
+ax2.set_yticks(y_positions)
+ax2.set_yticklabels(methods, fontsize=14)
+ax2.set_xlabel("Size (\\textit{GB})", fontsize=14)
+ax2.xaxis.set_tick_params(labelsize=14)
+
+plt.tight_layout()
+plt.savefig("./paper_plot/figures/ram_storage_double_column.pdf", bbox_inches="tight", dpi=300)
+print("Saving the figure to ./paper_plot/figures/ram_storage_double_column.pdf")
\ No newline at end of file
diff --git a/research/paper_plot/recompute_bottle.py b/research/paper_plot/recompute_bottle.py
new file mode 100644
index 0000000..77b1f67
--- /dev/null
+++ b/research/paper_plot/recompute_bottle.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# -*- coding:utf-8 -*-
+# Motto: Were It to Benefit My Country, I Would Lay Down My Life!
+# \file: /bottleneck_breakdown.py
+# \brief: Illustrates the query time bottleneck on consumer devices (Final Version - Font & Legend Adjust).
+# Author: Gemini Assistant (adapted from user's style and feedback)
+
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib.ticker import FuncFormatter # Not strictly needed for just font, but imported if user wants to try
+
+# Set matplotlib styles similar to the example
+plt.rcParams["font.family"] = "Helvetica" # Primary font family
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["xtick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 1.0
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+
+plt.rcParams["text.usetex"] = True
+# Attempt to make LaTeX use Helvetica as the main font
+plt.rcParams['text.latex.preamble'] = r"""
+\usepackage{helvet} % helvetica font
+\usepackage{sansmath} % helvetica for math
+\sansmath % activate sansmath
+\renewcommand{\familydefault}{\sfdefault} % make sans-serif the default family
+"""
+
+
+# Final Data for the breakdown (3 Segments)
+labels_raw = [ # Raw labels before potential LaTeX escaping
+ 'IO: Text + PQ Lookup',
+ 'CPU: Tokenize + Distance Compute',
+ 'GPU: Embedding Recompute',
+]
+# Times in ms, ordered for stacking
+times_ms = np.array([
+ 8.009, # Quantization
+ 16.197, # Search
+ 76.512, # Embedding Recomputation
+])
+
+total_time_ms = times_ms.sum()
+percentages = (times_ms / total_time_ms) * 100
+
+# Prepare labels for legend, escaping for LaTeX if active
+labels_legend = []
+# st1 = r'&' # Not needed as current labels_raw don't have '&'
+for label, time, perc in zip(labels_raw, times_ms, percentages):
+ # Construct the percentage string carefully for LaTeX
+ perc_str = f"{perc:.1f}" + r"\%" # Correct way to form 'NN.N\%'
+ # label_tex = label.replace('&', st1) # Use if '&' is in labels_raw
+ label_tex = label # Current labels_raw are clean for LaTeX
+ labels_legend.append(
+ f"{label_tex}\n({time:.1f}ms, {perc_str})"
+ )
+
+# Styling based on user's script
+# Using first 3 from the provided lists
+edgecolors_list = ["dimgrey", "#63B8B6", "tomato", "silver", "slategray"]
+hatches_list = ["/////", "xxxxx", "\\\\\\\\\\"]
+
+edgecolors = edgecolors_list[:3]
+hatches = hatches_list[:3]
+fill_color = "white"
+
+# Create the figure and axes
+# Adjusted figure size to potentially accommodate legend on the right
+fig, ax = plt.subplots()
+fig.set_size_inches(7, 1.5) # Width increased slightly, height adjusted
+# Adjusted right margin for external legend, bottom for x-label
+plt.subplots_adjust(left=0.12, right=0.72, top=0.95, bottom=0.25)
+
+# Create the horizontal stacked bar
+bar_height = 0.2
+y_pos = 0
+
+left_offset = 0
+for i in range(len(times_ms)):
+ ax.barh(
+ y_pos,
+ times_ms[i],
+ height=bar_height,
+ left=left_offset,
+ color=fill_color,
+ edgecolor=edgecolors[i],
+ hatch=hatches[i],
+ linewidth=1.5,
+ label=labels_legend[i],
+ zorder=10
+ )
+ text_x_pos = left_offset + times_ms[i] / 2
+ if times_ms[i] > total_time_ms * 0.03: # Threshold for displaying text
+ ax.text(
+ text_x_pos,
+ y_pos,
+ f"{times_ms[i]:.1f}ms",
+ ha='center',
+ va='center',
+ fontsize=8,
+ fontweight='bold',
+ color='black',
+ zorder=20,
+ bbox=dict(facecolor='white', edgecolor='none', pad=0.5, alpha=0.8)
+ )
+ left_offset += times_ms[i]
+
+# Set plot limits and labels
+ax.set_xlim([0, total_time_ms * 1.02])
+ax.set_xlabel("Time (ms)", fontsize=14, fontweight='bold', x=0.75, )
+
+# Y-axis: Remove y-ticks and labels
+ax.set_yticks([])
+ax.set_yticklabels([])
+
+# Legend: Placed to the right of the plot
+ax.legend(
+ # (x, y) for anchor, (0,0) is bottom left, (1,1) is top right of AXES
+ # To place outside on the right, x should be > 1
+ bbox_to_anchor=(1.03, 0.5), # x > 1 means outside to the right, y=0.5 for vertical center
+ ncol=1, # Single column for a taller, narrower legend
+ loc="center left", # Anchor the legend's left-center to bbox_to_anchor point
+ labelspacing=0.5, # Adjust spacing
+ edgecolor="black",
+ facecolor="white",
+ framealpha=1,
+ shadow=False,
+ fancybox=False,
+ handlelength=1.5,
+ handletextpad=0.6,
+ columnspacing=1.5,
+ prop={"weight": "bold", "size": 9},
+).set_zorder(100)
+
+# Save the figure (using the original generic name as requested)
+output_filename = "./bottleneck_breakdown.pdf"
+# plt.tight_layout() # tight_layout might conflict with external legend; adjust subplots_adjust instead
+plt.savefig(output_filename, bbox_inches="tight", dpi=300)
+print(f"Saved plot to {output_filename}")
+
+# plt.show() # Uncomment to display plot interactively
\ No newline at end of file
diff --git a/research/paper_plot/small_emb.py b/research/paper_plot/small_emb.py
new file mode 100644
index 0000000..0d32091
--- /dev/null
+++ b/research/paper_plot/small_emb.py
@@ -0,0 +1,226 @@
+import matplotlib.pyplot as plt
+import numpy as np
+# import matplotlib.ticker as mticker # Not actively used
+import os
+
+FIGURE_PATH = "paper_plot/figures"
+
+try:
+ os.makedirs(FIGURE_PATH, exist_ok=True)
+ print(f"Images will be saved to: {os.path.abspath(FIGURE_PATH)}")
+except OSError as e:
+ print(f"Create {FIGURE_PATH} failed: {e}. Images will be saved in the current working directory.")
+ FIGURE_PATH = "."
+
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 2
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True
+
+method_labels = ["gte-small (33M)", "contriever-msmarco (110M)"]
+dataset_names = ["NQ", "TriviaQA"]
+metrics_plot1 = ["Exact Match", "F1"]
+
+small_nq_f1 = 0.2621040899
+small_tq_f1 = 0.4698198059
+small_nq_em_score = 0.1845
+small_tq_em_score = 0.4015
+small_nq_time = 1.137
+small_tq_time = 1.173
+
+large_nq_f1 = 0.2841386117
+large_tq_f1 = 0.4548340289
+large_nq_em_score = 0.206
+large_tq_em_score = 0.382
+large_nq_time = 2.632
+large_tq_time = 2.684
+
+data_scores_plot1 = {
+ "NQ": {"Exact Match": [small_nq_em_score, large_nq_em_score], "F1": [small_nq_f1, large_nq_f1]},
+ "TriviaQA": {"Exact Match": [small_tq_em_score, large_tq_em_score], "F1": [small_tq_f1, large_tq_f1]}
+}
+latency_data_plot2 = {
+ "NQ": [small_nq_time, large_nq_time],
+ "TriviaQA": [small_tq_time, large_tq_time]
+}
+
+edgecolors = ["dimgrey", "tomato"]
+hatches = ["/////", "\\\\\\\\\\"]
+
+# Changed: bar_center_separation_in_group increased for larger gap
+bar_center_separation_in_group = 0.42
+# Changed: bar_visual_width decreased for narrower bars
+bar_visual_width = 0.28
+
+figsize_plot1 = (4, 2.5)
+# Changed: figsize_plot2 width adjusted to match figsize_plot1 for legend/caption alignment
+figsize_plot2 = (2.5, 2.5)
+
+# Define plot1_xlim_per_subplot globally so it can be accessed by create_plot2_latency
+plot1_xlim_per_subplot = (0.0, 2.0) # Explicit xlim for plot 1 subplots
+
+common_subplots_adjust_params = dict(wspace=0.30, top=0.80, bottom=0.22, left=0.09, right=0.96)
+
+
+def create_plot1_em_f1():
+ fig, axs = plt.subplots(1, 2, figsize=figsize_plot1)
+ fig.subplots_adjust(**common_subplots_adjust_params)
+
+ num_methods = len(method_labels)
+ metric_group_centers = np.array([0.5, 1.5])
+ # plot1_xlim_per_subplot is now global
+
+ for i, dataset_name in enumerate(dataset_names):
+ ax = axs[i]
+ for metric_idx, metric_name in enumerate(metrics_plot1):
+ metric_center_pos = metric_group_centers[metric_idx]
+ current_scores_raw = data_scores_plot1[dataset_name][metric_name]
+ current_scores_percent = [val * 100 for val in current_scores_raw]
+
+ for j, method_label in enumerate(method_labels):
+ offset = (j - (num_methods - 1) / 2.0) * bar_center_separation_in_group
+ bar_center_pos = metric_center_pos + offset
+
+ ax.bar(
+ bar_center_pos, current_scores_percent[j], width=bar_visual_width, color="white",
+ edgecolor=edgecolors[j], hatch=hatches[j], linewidth=1.5,
+ label=method_label if i == 0 and metric_idx == 0 else None
+ )
+ ax.text(
+ bar_center_pos, current_scores_percent[j] + 0.8, f"{current_scores_percent[j]:.1f}",
+ ha='center', va='bottom', fontsize=8, fontweight='bold'
+ )
+
+ ax.set_xticks(metric_group_centers)
+ ax.set_xticklabels(metrics_plot1, fontsize=9, fontweight='bold')
+ ax.set_title(dataset_name, fontsize=12, fontweight='bold')
+ ax.set_xlim(plot1_xlim_per_subplot) # Apply consistent xlim
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda y, _: ' {:.0f}'.format(y)))
+
+ if i == 0:
+ ax.set_ylabel("Accuracy (\%)", fontsize=12, fontweight="bold")
+
+ all_subplot_scores_percent = []
+ for metric_name_iter in metrics_plot1:
+ all_subplot_scores_percent.extend([val * 100 for val in data_scores_plot1[dataset_name][metric_name_iter]])
+
+ max_val = max(all_subplot_scores_percent) if all_subplot_scores_percent else 0
+ ax.set_ylim(0, max_val * 1.22 if max_val > 0 else 10)
+ ax.tick_params(axis='y', labelsize=12)
+
+ for spine in ax.spines.values():
+ spine.set_visible(True)
+ spine.set_linewidth(1.0)
+ spine.set_edgecolor("black")
+
+ handles, labels = axs[0].get_legend_handles_labels()
+ fig.legend(
+ handles, labels, loc="upper center", bbox_to_anchor=(0.5, 0.97), ncol=len(method_labels),
+ edgecolor="black", facecolor="white", framealpha=1, shadow=False, fancybox=False,
+ handlelength=1.5, handletextpad=0.4, columnspacing=0.8,
+ prop={"weight": "bold", "size": 9}
+ )
+
+ # fig.text(0.5, 0.06, "(a) EM \& F1", ha='center', va='center', fontweight='bold', fontsize=11)
+
+
+ save_path = os.path.join(FIGURE_PATH, "plot1_em_f1.pdf")
+ # plt.tight_layout() # Adjusted call below
+ fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.88)) # Adjusted to make space for fig.text and fig.legend
+ plt.savefig(save_path, bbox_inches='tight', pad_inches=0.03)
+ plt.close(fig)
+ print(f"Figure 1 (Exact Match & F1) has been saved to: {save_path}")
+
+def create_plot2_latency():
+ fig, axs = plt.subplots(1, 2, figsize=figsize_plot2) # figsize_plot2 width is now 8.0
+ fig.subplots_adjust(**common_subplots_adjust_params)
+
+ num_methods = len(method_labels)
+ method_group_center_in_subplot = 0.5
+
+# Calculate bar extents to determine focused xlim
+ bar_positions_calc = []
+ for j_idx in range(num_methods):
+ offset_calc = (j_idx - (num_methods - 1) / 2.0) * bar_center_separation_in_group
+ bar_center_pos_calc = method_group_center_in_subplot + offset_calc
+ bar_positions_calc.append(bar_center_pos_calc)
+
+ min_bar_actual_edge = min(bar_positions_calc) - bar_visual_width / 2.0
+ max_bar_actual_edge = max(bar_positions_calc) + bar_visual_width / 2.0
+
+ # Define padding around the bars
+ # Option 1: Fixed padding (e.g., 0.15 as derived from plot 1 visual)
+ # padding_val = 0.15
+ # plot2_xlim_calculated = (min_bar_actual_edge - padding_val, max_bar_actual_edge + padding_val)
+ # This would be (0.15 - 0.15, 0.85 + 0.15) = (0.0, 1.0)
+
+ # Option 2: Center the group (0.5) in a span of 1.0
+ plot2_xlim_calculated = (method_group_center_in_subplot - 0.5, method_group_center_in_subplot + 0.5)
+ # This is (0.5 - 0.5, 0.5 + 0.5) = (0.0, 1.0)
+ # This is simpler and achieves the (0.0, 1.0) directly.
+
+ for i, dataset_name in enumerate(dataset_names):
+ ax = axs[i]
+ current_latencies = latency_data_plot2[dataset_name]
+
+ for j, method_label in enumerate(method_labels):
+ offset = (j - (num_methods - 1) / 2.0) * bar_center_separation_in_group
+ bar_center_pos = method_group_center_in_subplot + offset
+
+ ax.bar(
+ bar_center_pos, current_latencies[j], width=bar_visual_width, color="white",
+ edgecolor=edgecolors[j], hatch=hatches[j], linewidth=1.5,
+ label=method_label if i == 0 else None
+ )
+ ax.text(
+ bar_center_pos, current_latencies[j] + 0.05, f"{current_latencies[j]:.2f}",
+ ha='center', va='bottom', fontsize=10, fontweight='bold'
+ )
+ ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda y, _: ' {:.0f}'.format(y)))
+
+ ax.set_xticks([0.5])
+ ax.set_xticklabels(["Latency"], color="white", fontsize=12)
+ # set tick hatches
+ ax.tick_params(axis='x', colors="white")
+ ax.set_title(dataset_name, fontsize=13, fontweight='bold')
+ ax.set_xlim(plot2_xlim_calculated)
+
+ if i == 0:
+ ax.set_ylabel("Latency (s)", fontsize=12, fontweight="bold")
+
+ max_latency_in_subplot = max(current_latencies) if current_latencies else 0
+ ax.set_ylim(0, max_latency_in_subplot * 1.22 if max_latency_in_subplot > 0 else 1)
+ ax.tick_params(axis='y', labelsize=12)
+
+ for spine in ax.spines.values():
+ spine.set_visible(True)
+ spine.set_linewidth(1.0)
+ spine.set_edgecolor("black")
+
+ handles, labels = axs[0].get_legend_handles_labels()
+ fig.legend(
+ handles, labels, loc="upper center", bbox_to_anchor=(0.5, 0.97), ncol=num_methods,
+ edgecolor="black", facecolor="white", framealpha=1, shadow=False, fancybox=False,
+ handlelength=1.5, handletextpad=0.4, columnspacing=0.8,
+ prop={"weight": "bold", "size": 9}
+ )
+
+ # fig.text(0.5, 0.06, "(b) Latency", ha='center', va='center', fontweight='bold', fontsize=11)
+
+ save_path = os.path.join(FIGURE_PATH, "plot2_latency.pdf")
+ # plt.tight_layout() # Adjusted call below
+ fig.tight_layout(rect=(0.0, 0.0, 1.0, 0.88)) # Adjusted to make space for fig.text and fig.legend
+ plt.savefig(save_path, bbox_inches='tight', pad_inches=0.03)
+ plt.close(fig)
+ print(f"Figure 2 (Latency) has been saved to: {save_path}")
+
+if __name__ == "__main__":
+ print("Start generating figures...")
+ if plt.rcParams["text.usetex"]:
+ print("Info: LaTeX rendering is enabled. Ensure LaTeX is installed and configured if issues arise, or set plt.rcParams['text.usetex'] to False.")
+
+ create_plot1_em_f1()
+ create_plot2_latency()
+ print("All figures have been generated.")
diff --git a/research/paper_plot/speed_ablation.py b/research/paper_plot/speed_ablation.py
new file mode 100644
index 0000000..222cc6c
--- /dev/null
+++ b/research/paper_plot/speed_ablation.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+# -*- coding:utf-8 -*-
+# Motto: Were It to Benefit My Country, I Would Lay Down My Life!
+# \file: /speed_ablation.py
+# \brief:
+# Author: raphael hao
+
+# %%
+import numpy as np
+import pandas as pd
+
+# %%
+# from script.settings import DATA_PATH, FIGURE_PATH
+
+# Load the latency ablation data
+latency_data = pd.read_csv("./paper_plot/data/latency_ablation.csv")
+# Filter for SpeedUp metric only
+speedup_data = latency_data[latency_data['Metric'] == 'SpeedUp']
+
+# %%
+from matplotlib import pyplot as plt
+
+plt.rcParams["font.family"] = "Helvetica"
+plt.rcParams["ytick.direction"] = "in"
+plt.rcParams["hatch.linewidth"] = 1.5
+plt.rcParams["font.weight"] = "bold"
+plt.rcParams["axes.labelweight"] = "bold"
+plt.rcParams["text.usetex"] = True
+
+# %%
+
+fig, ax = plt.subplots()
+fig.set_size_inches(5, 1.5)
+plt.subplots_adjust(wspace=0, hspace=0)
+
+total_width, n = 3, 3
+group = len(speedup_data['Dataset'].unique())
+width = total_width * 0.9 / n
+x = np.arange(group) * n
+exit_idx_x = x + (total_width - width) / n
+edgecolors = ["dimgrey", "#63B8B6", "tomato", "silver", "slategray"]
+hatches = ["/////", "xxxxx", "\\\\\\\\\\"]
+labels = ["Base", "Base + Two-level", "Base + Two-level + Batch"]
+
+datasets = speedup_data['Dataset'].unique()
+
+for i, dataset in enumerate(datasets):
+ dataset_data = speedup_data[speedup_data['Dataset'] == dataset]
+
+ for j in range(n):
+ if j == 0:
+ value = dataset_data['Original'].values[0]
+ elif j == 1:
+ value = dataset_data['original + two_level'].values[0]
+ else:
+ value = dataset_data['original + two_level + batch'].values[0]
+
+ ax.text(
+ exit_idx_x[i] + j * width,
+ value + 0.05,
+ f"{value:.2f}",
+ ha='center',
+ va='bottom',
+ fontsize=10,
+ fontweight='bold',
+ rotation=0,
+ zorder=20,
+ )
+
+ ax.bar(
+ exit_idx_x[i] + j * width,
+ value,
+ width=width * 0.8,
+ color="white",
+ edgecolor=edgecolors[j],
+ hatch=hatches[j],
+ linewidth=1.5,
+ label=labels[j] if i == 0 else None,
+ zorder=10,
+ )
+
+
+
+ax.set_ylim([0.5, 2.3])
+ax.set_yticks(np.arange(0.5, 2.2, 0.5))
+ax.set_yticklabels(np.arange(0.5, 2.2, 0.5), fontsize=12)
+ax.set_xticks(exit_idx_x + width)
+ax.set_xticklabels(datasets, fontsize=10)
+# ax.set_xlabel("Different Datasets", fontsize=14)
+ax.legend(
+ bbox_to_anchor=(-0.03, 1.4),
+ ncol=3,
+ loc="upper left",
+ labelspacing=0.1,
+ edgecolor="black",
+ facecolor="white",
+ framealpha=1,
+ shadow=False,
+ fancybox=False,
+ handlelength=0.8,
+ handletextpad=0.6,
+ columnspacing=0.8,
+ prop={"weight": "bold", "size": 10},
+).set_zorder(100)
+ax.set_ylabel("Speedup", fontsize=11)
+
+plt.savefig("./paper_plot/figures/latency_speedup.pdf", bbox_inches="tight", dpi=300)
+
+# %%
+
+print(f"Save to ./paper_plot/figures/latency_speedup.pdf")
\ No newline at end of file
diff --git a/research/utils/.gitignore b/research/utils/.gitignore
new file mode 100644
index 0000000..30690f4
--- /dev/null
+++ b/research/utils/.gitignore
@@ -0,0 +1 @@
+analyze_diskann_graph
\ No newline at end of file
diff --git a/research/utils/analyze_diskann_graph.cpp b/research/utils/analyze_diskann_graph.cpp
new file mode 100644
index 0000000..459ee72
--- /dev/null
+++ b/research/utils/analyze_diskann_graph.cpp
@@ -0,0 +1,227 @@
+#include <cassert>
+#include <cstdint>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <limits>
+#include <string>
+#include <vector>
+
+static const size_t DISKANN_SECTOR_LEN = 4096; // Typical sector size
+
+// ! Use float as CoordT
+using CoordT = float;
+
+int main(int argc, char **argv) {
+ if (argc < 3) {
+ std::cerr << "Usage: " << argv[0]
+ << " <diskann_index_file> <output_degree_file>" << std::endl;
+ return -1;
+ }
+
+ std::string disk_index_path = argv[1];
+ std::string output_degree_path = argv[2];
+ std::ifstream in(disk_index_path, std::ios::binary);
+ if (!in.is_open()) {
+ std::cerr << "Failed to open file: " << disk_index_path << std::endl;
+ return -1;
+ }
+
+ // =========== 1) Read meta information (corresponds to
+ // save_bin<uint64_t>(...,...,...,1,0)) ============== Read bin header:
+ // (npts_i32, dim_i32)
+ int32_t meta_count_i32 = 0, meta_dim_i32 = 0;
+ in.read(reinterpret_cast<char *>(&meta_count_i32), sizeof(int32_t));
+ in.read(reinterpret_cast<char *>(&meta_dim_i32), sizeof(int32_t));
+ size_t meta_count = static_cast<size_t>(meta_count_i32);
+ size_t meta_dim = static_cast<size_t>(meta_dim_i32);
+
+ // According to the diskann::save_bin writing method, here meta_dim is usually
+ // 1
+ std::cout << "[LOG] meta_count=" << meta_count << ", meta_dim=" << meta_dim
+ << std::endl;
+ if (meta_dim != 1) {
+ std::cerr << "[ERROR] meta_dim != 1,不符合 create_disk_layout 的写盘约定。"
+ << std::endl;
+ return -1;
+ }
+
+ // Read meta array
+ std::vector<uint64_t> meta(meta_count);
+ in.read(reinterpret_cast<char *>(meta.data()), meta_count * sizeof(uint64_t));
+ if (!in.good()) {
+ std::cerr << "[ERROR] Failed to read meta array, file is incomplete."
+ << std::endl;
+ return -1;
+ }
+
+ // meta[0..] Metadata
+ // 0: npts_64, 1: ndims_64, 2: medoid, 3: max_node_len, 4: nnodes_per_sector,
+ // 5: vamana_frozen_num, 6: vamana_frozen_loc, 7: append_reorder_data, ...
+ const uint64_t npts_64 = meta[0];
+ const uint64_t ndims_64 = meta[1];
+ const uint64_t medoid = meta[2];
+ const uint64_t max_node_len = meta[3];
+ const uint64_t nnodes_per_sector = meta[4];
+ const uint64_t vamana_frozen_num = meta[5];
+ const uint64_t vamana_frozen_loc = meta[6];
+ const uint64_t append_reorder_data = meta[7];
+
+ std::cout << "[LOG] npts_64=" << npts_64 << " ndims_64=" << ndims_64
+ << " max_node_len=" << max_node_len
+ << " nnodes_per_sector=" << nnodes_per_sector << std::endl;
+ // If append_reorder_data==1, it means that reorder_data is appended at the
+ // end of the index, but it does not affect the degree statistics, we can
+ // ignore that part of the vector.
+
+ // =========== 2) Skip the first sector (all empty/placeholder information)
+ // ==============
+ in.seekg(DISKANN_SECTOR_LEN, std::ios::beg);
+ if (!in.good()) {
+ std::cerr << "[ERROR] Failed to seek to the first sector." << std::endl;
+ return -1;
+ }
+
+ // =========== 3) Calculate the total number of sectors ==============
+ // In create_disk_layout:
+ // If nnodes_per_sector > 0, then n_sectors = ceil(npts_64 /
+ // nnodes_per_sector) Otherwise nsectors_per_node = ceil(max_node_len /
+ // 4096), n_sectors = nsectors_per_node * npts_64
+ uint64_t n_sectors = 0;
+ if (nnodes_per_sector > 0) {
+ // Equivalent to Roundup(npts_64, nnodes_per_sector) / nnodes_per_sector
+ n_sectors = (npts_64 + nnodes_per_sector - 1) / nnodes_per_sector;
+ } else {
+ // multi-sector per node
+ uint64_t nsectors_per_node =
+ (max_node_len + DISKANN_SECTOR_LEN - 1) / DISKANN_SECTOR_LEN;
+ n_sectors = nsectors_per_node * npts_64;
+ }
+ std::cout << "[LOG] estimated #sectors storing adjacency = " << n_sectors
+ << std::endl;
+
+ // =========== 4) Read the degree of all nodes in order ==============
+ // The memory layout of adjacency_count in each node: offset = ndims_64 *
+ // sizeof(CoordT) This is followed by 4 bytes for the number of neighbors
+ // uint32_t If you want to read the complete neighbor list, it is
+ // adjacency_count * sizeof(uint32_t) But we only count the count
+ std::vector<uint32_t> degrees(npts_64, 0); // Store the degree of each node
+ size_t node_id = 0; // Current node number
+ // Buffer for reading one sector at a time
+ std::vector<char> sector_buf(DISKANN_SECTOR_LEN, 0);
+ // If nnodes_per_sector>0, it means that one sector holds multiple nodes
+ // Otherwise, one node occupies nsectors_per_node sectors
+ if (nnodes_per_sector > 0) {
+ // Read one sector at a time
+ for (uint64_t s = 0; s < n_sectors; s++) {
+ in.read((char *)sector_buf.data(), DISKANN_SECTOR_LEN);
+ if (!in.good()) {
+ if (node_id < npts_64) {
+ std::cerr << "[ERROR] Failed to read sector " << s
+ << ", nodes not finished, file error or incomplete."
+ << std::endl;
+ return -1;
+ }
+ break; // If all nodes are read, you can exit
+ }
+ // Parse each node in sector_buf
+ for (uint64_t i = 0; i < nnodes_per_sector; i++) {
+ if (node_id >= npts_64)
+ break; // All node degrees have been obtained
+ // The starting offset of the node in sector_buf
+ size_t node_offset = i * max_node_len;
+ // offset first skips ndims_64 * sizeof(CoordT)
+ size_t degree_offset = node_offset + ndims_64 * sizeof(CoordT);
+ // Ensure not out of bounds
+ if (degree_offset + sizeof(uint32_t) > sector_buf.size()) {
+ std::cerr << "[ERROR] 不应该发生: 读取degree越过了扇区边界."
+ << std::endl;
+ return -1;
+ }
+ uint32_t deg = 0;
+ memcpy(&deg, sector_buf.data() + degree_offset, sizeof(uint32_t));
+ degrees[node_id] = deg;
+ node_id++;
+ }
+ }
+ } else {
+ // Each node occupies nsectors_per_node sectors
+ uint64_t nsectors_per_node =
+ (max_node_len + DISKANN_SECTOR_LEN - 1) / DISKANN_SECTOR_LEN;
+ // Read each node
+ for (uint64_t n = 0; n < npts_64; n++) {
+ // Read multiple sectors into a multi-sector buffer
+ std::vector<char> node_buf(nsectors_per_node * DISKANN_SECTOR_LEN, 0);
+ in.read((char *)node_buf.data(), node_buf.size());
+ if (!in.good()) {
+ std::cerr << "[ERROR] Failed to read sector corresponding to node " << n
+ << ", file error or incomplete." << std::endl;
+ return -1;
+ }
+ // Parse the degree in node_buf
+ size_t degree_offset = ndims_64 * sizeof(CoordT);
+ if (degree_offset + sizeof(uint32_t) > node_buf.size()) {
+ std::cerr << "[ERROR] Should not happen: reading degree beyond node "
+ "region."
+ << std::endl;
+ return -1;
+ }
+ uint32_t deg = 0;
+ memcpy(&deg, node_buf.data() + degree_offset, sizeof(uint32_t));
+ degrees[n] = deg;
+ }
+ }
+
+ // We assert here: node_id should equal npts_64 (in multi-node mode)
+ if (nnodes_per_sector > 0) {
+ if (node_id != npts_64) {
+ std::cerr << "[ERROR] Actually read " << node_id
+ << " nodes, but meta npts_64=" << npts_64
+ << ", file may be incorrect or parsing method is wrong."
+ << std::endl;
+ return -1;
+ }
+ }
+
+ // =========== 5) Calculate min / max / average degree ==============
+ uint64_t sum_deg = 0;
+ uint32_t min_deg = std::numeric_limits<uint32_t>::max();
+ uint32_t max_deg = 0;
+
+ for (uint64_t n = 0; n < npts_64; n++) {
+ uint32_t d = degrees[n];
+ sum_deg += d;
+ if (d < min_deg)
+ min_deg = d;
+ if (d > max_deg)
+ max_deg = d;
+ }
+ double avg_deg = (npts_64 == 0) ? 0.0 : double(sum_deg) / double(npts_64);
+
+ // =========== 6) Output results ==============
+ std::cout << "DiskANN index file: " << disk_index_path << std::endl;
+ std::cout << "Total points: " << npts_64 << std::endl;
+ std::cout << "Min degree : " << min_deg << std::endl;
+ std::cout << "Max degree : " << max_deg << std::endl;
+ std::cout << "Avg degree : " << avg_deg << std::endl;
+
+ // =========== 7) Write degrees to output file ==============
+ std::ofstream out_deg(output_degree_path);
+ if (!out_deg.is_open()) {
+ std::cerr << "[ERROR] Failed to open output file: " << output_degree_path
+ << std::endl;
+ // Don't necessarily exit, maybe just warn? Depends on desired behavior.
+ // For now, we continue closing the input file.
+ } else {
+ std::cout << "[LOG] Writing degrees to " << output_degree_path << "..."
+ << std::endl;
+ for (uint64_t n = 0; n < npts_64; n++) {
+ out_deg << degrees[n] << std::endl;
+ }
+ out_deg.close();
+ std::cout << "[LOG] Finished writing degrees." << std::endl;
+ }
+
+ in.close();
+ return 0;
+}
diff --git a/research/utils/analyze_top3_positions.py b/research/utils/analyze_top3_positions.py
new file mode 100644
index 0000000..e62c7bd
--- /dev/null
+++ b/research/utils/analyze_top3_positions.py
@@ -0,0 +1,187 @@
+import pandas as pd
+import matplotlib.pyplot as plt
+import seaborn as sns
+import numpy as np
+import os
+import re
+
+# 设置风格
+plt.style.use('ggplot')
+sns.set(font_scale=1.2)
+
+# 读取数据 - 修改为自定义读取逻辑
+log_file = './top3_positions_log.txt'
+
+# 手动解析文件
+data = []
+header = None
+with open(log_file, 'r') as f:
+ lines = f.readlines()
+ header = lines[0].strip().split(',')
+
+ # 检查是否存在ThreadID列
+ has_thread_id = 'ThreadID' in header
+
+ for line in lines[1:]:
+ # 跳过非数据行,如"Search X results:"
+ if 'results:' in line or not ',' in line:
+ continue
+
+ # 分割并解析数据行
+ parts = line.strip().split(',')
+
+ # 检查数据是否符合格式
+ if len(parts) >= 7: # 至少需要7个字段
+ # 对于旧格式(无ThreadID)的数据
+ if not has_thread_id and len(parts) == 7:
+ data.append([parts[0], 0, parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]])
+ # 对于新格式(有ThreadID)的数据
+ elif has_thread_id and len(parts) == 8:
+ data.append(parts)
+ # 处理不一致的格式
+ elif not has_thread_id and len(parts) == 8:
+ # 假设第二列是ThreadID
+ data.append(parts)
+ if not has_thread_id:
+ has_thread_id = True
+ header.insert(1, 'ThreadID')
+
+# 确保header正确
+if not has_thread_id:
+ header.insert(1, 'ThreadID')
+
+# 创建DataFrame并确保列名正确
+if len(header) == 8: # 确保有8列
+ df = pd.DataFrame(data, columns=header)
+else:
+ # 如果header不正确,则使用默认列名
+ default_header = ['Search#', 'ThreadID', 'FullSetSize', 'Rank', 'ID', 'PQ_Rank', 'PQ_Distance', 'Exact_Distance']
+ df = pd.DataFrame(data, columns=default_header)
+
+# 转换数值列
+df['Search#'] = pd.to_numeric(df['Search#'], errors='coerce').fillna(0).astype(int)
+df['ThreadID'] = pd.to_numeric(df['ThreadID'], errors='coerce').fillna(0).astype(int)
+df['FullSetSize'] = pd.to_numeric(df['FullSetSize'], errors='coerce').fillna(0).astype(int)
+df['Rank'] = pd.to_numeric(df['Rank'], errors='coerce').fillna(0).astype(int)
+df['ID'] = pd.to_numeric(df['ID'], errors='coerce').fillna(0).astype(int)
+df['PQ_Rank'] = pd.to_numeric(df['PQ_Rank'], errors='coerce').fillna(0).astype(int)
+df['PQ_Distance'] = pd.to_numeric(df['PQ_Distance'], errors='coerce').fillna(0).astype(float)
+df['Exact_Distance'] = pd.to_numeric(df['Exact_Distance'], errors='coerce').fillna(0).astype(float)
+
+print(f"读取了 {len(df)} 行数据")
+print(f"搜索次数: {df['Search#'].nunique()}")
+print(f"线程数: {df['ThreadID'].nunique()}")
+
+# 提取前3名的结果
+top3_df = df[df['Rank'] <= 3].copy()
+
+# 分析PQ Rank的分布
+pq_positions = []
+for rank in [1, 2, 3]:
+ rank_df = top3_df[top3_df['Rank'] == rank]
+ pq_positions.append(rank_df['PQ_Rank'].values)
+
+# 创建结果目录
+result_dir = './analysis_results'
+os.makedirs(result_dir, exist_ok=True)
+
+# 1. 箱型图:展示top-3结果在PQ排序中的位置分布
+plt.figure(figsize=(10, 6))
+box_data = [top3_df[top3_df['Rank'] == i]['PQ_Rank'].values for i in [1, 2, 3]]
+sns.boxplot(data=box_data)
+plt.xticks([0, 1, 2], ['Top 1', 'Top 2', 'Top 3'])
+plt.ylabel('PQ Rank Position')
+plt.title('Distribution of PQ Ranks for Top-3 Exact Results')
+plt.savefig(os.path.join(result_dir, 'pq_rank_boxplot.png'), dpi=300)
+
+# 2. 直方图:每个排名在PQ结果中的位置分布
+fig, axs = plt.subplots(1, 3, figsize=(18, 6))
+for i, rank in enumerate([1, 2, 3]):
+ rank_df = top3_df[top3_df['Rank'] == rank]
+ sns.histplot(x=rank_df['PQ_Rank'].values, bins=20, ax=axs[i])
+ axs[i].set_title(f'Exact Rank {rank}')
+ axs[i].set_xlabel('PQ Rank')
+ axs[i].set_ylabel('Frequency')
+plt.tight_layout()
+plt.savefig(os.path.join(result_dir, 'pq_rank_histogram.png'), dpi=300)
+
+# 3. 热力图:PQ排名与精确排名的关系
+plt.figure(figsize=(10, 8))
+# 只关注Top 20的排名
+bins = list(range(0, 22))
+pq_rank_bins = pd.cut(top3_df['PQ_Rank'], bins=bins)
+heatmap_data = pd.crosstab(pq_rank_bins, top3_df['Rank'])
+sns.heatmap(heatmap_data, cmap='YlGnBu', annot=True, fmt='d')
+plt.title('Heatmap of Exact Rank vs PQ Rank (Top 20)')
+plt.xlabel('Exact Rank')
+plt.ylabel('PQ Rank Range')
+plt.savefig(os.path.join(result_dir, 'rank_heatmap.png'), dpi=300)
+
+# 4. 散点图:比较PQ距离和精确距离的关系
+plt.figure(figsize=(10, 8))
+sns.scatterplot(x=top3_df['Exact_Distance'], y=top3_df['PQ_Distance'], hue=top3_df['Rank'], palette='viridis')
+plt.title('PQ Distance vs Exact Distance')
+plt.xlabel('Exact Distance')
+plt.ylabel('PQ Distance')
+plt.legend(title='Exact Rank')
+# 添加对角线表示完美匹配
+min_val = min(top3_df['Exact_Distance'].min(), top3_df['PQ_Distance'].min())
+max_val = max(top3_df['Exact_Distance'].max(), top3_df['PQ_Distance'].max())
+plt.plot([min_val, max_val], [min_val, max_val], 'r--', alpha=0.5)
+plt.savefig(os.path.join(result_dir, 'distance_scatter.png'), dpi=300)
+
+# 5. 折线图:PQ Rank随结果集大小的变化
+plt.figure(figsize=(12, 6))
+size_grouped = top3_df.groupby(['FullSetSize', 'Rank'])['PQ_Rank'].mean().reset_index()
+for rank in [1, 2, 3]:
+ rank_data = size_grouped[size_grouped['Rank'] == rank]
+ plt.plot(rank_data['FullSetSize'], rank_data['PQ_Rank'], marker='o', label=f'Rank {rank}')
+plt.xlabel('Result Set Size')
+plt.ylabel('Average PQ Rank')
+plt.title('Average PQ Rank by Result Set Size')
+plt.legend()
+plt.grid(True)
+plt.savefig(os.path.join(result_dir, 'pq_rank_by_size.png'), dpi=300)
+
+# 6. 百分比热力图:在PQ排名前K的概率
+top_k_values = [1, 5, 10, 20, 50, 100, 200, 300, 500, 700, 800, 900]
+top_k_probs = []
+
+for rank in [1, 2, 3]:
+ rank_df = top3_df[top3_df['Rank'] == rank]
+ probs = []
+ for k in top_k_values:
+ prob = (rank_df['PQ_Rank'] <= k).mean() * 100
+ probs.append(prob)
+ top_k_probs.append(probs)
+
+plt.figure(figsize=(10, 6))
+sns.heatmap(top_k_probs, annot=True, fmt='.1f', cmap='YlGnBu',
+ xticklabels=[f'Top-{k}' for k in top_k_values],
+ yticklabels=['Rank 1', 'Rank 2', 'Rank 3'])
+plt.title('Probability (%) of Finding Exact Top-K Results in PQ Top-K')
+plt.xlabel('PQ Top-K')
+plt.ylabel('Exact Rank')
+plt.savefig(os.path.join(result_dir, 'topk_probability.png'), dpi=300)
+
+# 7. 生成统计摘要报告
+with open(os.path.join(result_dir, 'summary_report.txt'), 'w') as f:
+ f.write(f"数据分析摘要\n")
+ f.write(f"=================\n")
+ f.write(f"总搜索次数: {df['Search#'].nunique()}\n")
+ f.write(f"使用线程数: {df['ThreadID'].nunique()}\n\n")
+
+ f.write("精确排名前3的结果在PQ排序中的平均位置:\n")
+ for rank in [1, 2, 3]:
+ avg_pq_rank = top3_df[top3_df['Rank'] == rank]['PQ_Rank'].mean()
+ median_pq_rank = top3_df[top3_df['Rank'] == rank]['PQ_Rank'].median()
+ f.write(f" 排名 {rank}: 平均位置 = {avg_pq_rank:.2f}, 中位数位置 = {median_pq_rank:.1f}\n")
+
+ f.write("\n各排名结果在PQ排序前K的命中率:\n")
+ for rank in [1, 2, 3]:
+ f.write(f" 排名 {rank}:\n")
+ for k in top_k_values:
+ hit_rate = (top3_df[top3_df['Rank'] == rank]['PQ_Rank'] <= k).mean() * 100
+ f.write(f" 在PQ前 {k} 中的命中率: {hit_rate:.2f}%\n")
+
+print(f"分析完成! 结果已保存到 {result_dir} 目录")
\ No newline at end of file
diff --git a/research/utils/debug_embedd.py b/research/utils/debug_embedd.py
new file mode 100644
index 0000000..c4238b7
--- /dev/null
+++ b/research/utils/debug_embedd.py
@@ -0,0 +1,137 @@
+import os
+import torch
+import numpy as np
+import argparse
+from tqdm import tqdm
+import json
+from contriever.src.contriever import load_retriever
+
+os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
+os.environ["OMP_NUM_THREADS"] = "1"
+os.environ["KMP_BLOCKTIME"] = "0"
+
+torch.set_num_threads(1)
+device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+def embed_queries(queries, model, tokenizer, model_name_or_path, per_gpu_batch_size=64):
+ """Embed queries using the model with batching"""
+ model = model.half()
+ model.eval()
+ embeddings = []
+ batch_question = []
+
+ with torch.no_grad():
+ for k, query in tqdm(enumerate(queries), desc="Encoding queries"):
+ batch_question.append(query)
+
+ # Process when batch is full or at the end
+ if len(batch_question) == per_gpu_batch_size or k == len(queries) - 1:
+ encoded_batch = tokenizer.batch_encode_plus(
+ batch_question,
+ return_tensors="pt",
+ max_length=512,
+ padding=True,
+ truncation=True,
+ )
+
+ encoded_batch = {k: v.to(device) for k, v in encoded_batch.items()}
+ output = model(**encoded_batch)
+
+ # Contriever typically uses output.last_hidden_state pooling or something specialized
+ # if "contriever" not in model_name_or_path:
+ # output = output.last_hidden_state[:, 0, :]
+
+ embeddings.append(output.cpu())
+ batch_question = [] # Reset batch
+
+ embeddings = torch.cat(embeddings, dim=0).numpy()
+ print(f"Query embeddings shape: {embeddings.shape}")
+ return embeddings
+
+def main():
+ parser = argparse.ArgumentParser(description="Debug embedding tool")
+ parser.add_argument("--model", type=str, default="Alibaba-NLP/gte-Qwen2-1.5B-instruct",
+ help="Model name for embedding (default: facebook/contriever-msmarco)")
+ parser.add_argument("--batch-size", type=int, default=32,
+ help="Batch size for encoding (default: 32)")
+ parser.add_argument("--input-file", type=str,
+ help="Input file with queries (JSON lines format with 'query' field)")
+ parser.add_argument("--output-file", type=str, default="embeddings.npy",
+ help="Output file to save embeddings (default: embeddings.npy)")
+ parser.add_argument("--text", type=str, nargs="+",
+ help="Direct text input to embed (can provide multiple)")
+ parser.add_argument("--save-text", action="store_true",
+ help="Save the input text alongside embeddings")
+
+ args = parser.parse_args()
+
+ # Load model
+ print(f"Loading query encoder: {args.model}")
+ query_encoder, query_tokenizer, _ = load_retriever(args.model)
+ query_encoder = query_encoder.to(device)
+ query_encoder.eval()
+
+ # Get queries
+ queries = []
+
+ # From file if provided
+ if args.input_file:
+ print(f"Loading queries from: {args.input_file}")
+ with open(args.input_file, "r") as f:
+ for line in f:
+ data = json.loads(line)
+ queries.append(data["query"])
+
+ # From command line if provided
+ if args.text:
+ print(f"Using {len(args.text)} queries from command line")
+ queries.extend(args.text)
+
+ # If no queries, use some examples
+ if not queries:
+ print("No queries provided, using example queries")
+ queries = [
+ "Were there any variances detected for hour 6 on 3/9/01?"
+ ]
+
+ print(f"Embedding {len(queries)} queries")
+ for i, q in enumerate(queries[:5]): # Print first 5 queries
+ print(f"Query {i+1}: {q}")
+ if len(queries) > 5:
+ print(f"... and {len(queries)-5} more")
+
+ # Encode queries
+ embeddings = embed_queries(
+ queries, query_encoder, query_tokenizer, args.model, per_gpu_batch_size=args.batch_size
+ )
+
+
+ passages = [
+ "Start Date: 3/9/01; HourAhead hour: 6; No ancillary schedules awarded. Variances detected. Variances detected in Generation schedule. Variances detected in Energy Import/Export schedule. LOG MESSAGES: PARSING FILE -->> O:\\Portland\\WestDesk\\California Scheduling\\ISO Final Schedules\\2001030906.txt ---- Generation Schedule ---- $$$ Variance found in table tblGEN_SCHEDULE. Details: (Hour: 6 / Preferred: 20.00 / Final: 19.80) TRANS_TYPE: FINAL SC_ID: TOSCO MKT_TYPE: 2 TRANS_DATE: 3/9/01 UNIT_ID: UNCHEM_1_UNIT $$$ Variance found in table tblGEN_SCHEDULE. Details: (Hour: 6 / Preferred: 29.00 / Final: 28.20) TRANS_TYPE: FINAL SC_ID: ARCO MKT_TYPE: 2 TRANS_DATE: 3/9/01 UNIT_ID: CARBGN_6_UNIT 1 $$$ Variance found in table tblGEN_SCHEDULE. Details: (Hour: 6 / Preferred: 45.00 / Final: 43.80) TRANS_TYPE: FINAL SC_ID: DELANO MKT_TYPE: 2 TRANS_DATE: 3/9/01 UNIT_ID: PANDOL_6_UNIT $$$ Variance found in table tblGEN_SCHEDULE. Details: (Hour: 6 / Preferred: 13.00 / Final: 12.60) TRANS_TYPE: FINAL SC_ID: Wheelabrat MKT_TYPE: 2 TRANS_DATE: 3/9/01 UNIT_ID: MARTEL_2_AMFOR ---- Energy Import/Export Schedule ---- $$$ Variance found in table tblINTCHG_IMPEXP. Details: (Hour: 6 / Preferred: 62.00 / Final: 60.40) TRANS_TYPE: FINAL SC_ID: ECTstCA MKT_TYPE: 2 TRANS_DATE: 3/9/01 TIE_POINT: PVERDE_5_DEVERS INTERCHG_ID: EPMI_CISO_5001 ENGY_TYPE: FIRM $$$ Variance found in table tblINTCHG_IMPEXP. Details: (Hour: 6 / Preferred: 63.00 / Final: 61.23) TRANS_TYPE: FINAL SC_ID: ECTstSW MKT_TYPE: 2 TRANS_DATE: 3/9/01 TIE_POINT: PVERDE_5_DEVERS INTERCHG_ID: EPMI_CISO_5000 ENGY_TYPE: FIRM $$$ Variance found in table tblINTCHG_IMPEXP. Details: (Hour: 6 / Preferred: 17.00 / Final: 11.00) TRANS_TYPE: FINAL SC_ID: ECTRT MKT_TYPE: 2 TRANS_DATE: 3/9/01 TIE_POINT: SYLMAR_2_NOB INTERCHG_ID: EPMI_CISO_LUCKY ENGY_TYPE: NFRM",
+ "Start Date: 3/30/01; HourAhead hour: 15; No ancillary schedules awarded. Variances detected. Variances detected in Generation schedule. LOG MESSAGES: PARSING FILE -->> O:\\Portland\\WestDesk\\California Scheduling\\ISO Final Schedules\\2001033015.txt ---- Generation Schedule ---- $$$ Variance found in table tblGEN_SCHEDULE. Details: (Hour: 15 / Preferred: 0.00 / Final: 0.00) TRANS_TYPE: FINAL SC_ID: ARCO MKT_TYPE: 2 TRANS_DATE: 3/30/01 UNIT_ID: CARBGN_6_UNIT 1 $$$ Variance found in table tblGEN_SCHEDULE. Details: (Hour: 15 / Preferred: 45.00 / Final: 44.00) TRANS_TYPE: FINAL SC_ID: DELANO MKT_TYPE: 2 TRANS_DATE: 3/30/01 UNIT_ID: PANDOL_6_UNIT"
+ ]
+
+ # Embed passages
+ passage_embeddings = embed_queries(passages, query_encoder, query_tokenizer, args.model, per_gpu_batch_size=args.batch_size)
+
+
+ # distance with passages 0 and query
+ distance_0 = np.linalg.norm(embeddings[0] - passage_embeddings[0])
+ print(f"Distance between query 0 and passage 0: {distance_0}")
+
+ # distance with passages 1 and query
+ distance_1 = np.linalg.norm(embeddings[0] - passage_embeddings[1])
+ print(f"Distance between query 0 and passage 1: {distance_1}")
+
+ # print which one is closer
+ if distance_0 < distance_1:
+ print("Query 0 is closer to passage 0")
+ else:
+ print("Query 0 is closer to passage 1")
+
+
+
+ print("Done!")
+
+if __name__ == "__main__":
+ main()
diff --git a/research/utils/dedup_eval_data.py b/research/utils/dedup_eval_data.py
new file mode 100755
index 0000000..de45cd4
--- /dev/null
+++ b/research/utils/dedup_eval_data.py
@@ -0,0 +1,33 @@
+import json
+import os
+
+
+input_file = "/gscratch/zlab/rulins/data/lm-eval-data/raw_mmlu.jsonl"
+output_file = "/gscratch/zlab/rulins/data/lm-eval-data/mmlu.jsonl"
+
+
+raw_data = []
+
+with open(input_file, "r") as fin:
+ for line in fin:
+ raw_data.append(json.loads(line))
+
+
+def deduplicate_dicts(dict_list):
+ unique_dicts = set()
+ unique_items = []
+ for item in dict_list:
+ # Make a hashable version of the dictionary by sorting it
+ hashable_item = tuple(sorted(item.items()))
+ if hashable_item not in unique_dicts:
+ unique_dicts.add(hashable_item)
+ unique_items.append(item)
+ return unique_items
+
+
+unique_data = deduplicate_dicts(raw_data)
+print(len(unique_data))
+
+with open(output_file, "w") as fout:
+ for ex in unique_data:
+ fout.write(json.dumps(ex) + "\n")
diff --git a/research/utils/deduplication.py b/research/utils/deduplication.py
new file mode 100755
index 0000000..5b5a3c0
--- /dev/null
+++ b/research/utils/deduplication.py
@@ -0,0 +1,167 @@
+import time
+import multiprocessing
+from datasketch import MinHash, MinHashLSH
+
+
+def shingle_document(text, shingle_size=13):
+ """Generate word-based shingles from a document."""
+ # Split the text into words
+ words = text.split()
+ # Generate shingles that are sequences of 'shingle_size' consecutive words
+ shingles = set(
+ " ".join(words[i : i + shingle_size])
+ for i in range(len(words) - shingle_size + 1)
+ )
+ return shingles
+
+
+m = MinHash(num_perm=128)
+perm = m.permutations
+
+
+def create_minhash(shingles, num_perm=128):
+ """Create a MinHash object from the set of shingles."""
+ m = MinHash(permutations=perm)
+ m.update_batch(map(lambda x: x.encode("utf-8"), shingles))
+ # for shingle in shingles:
+ # m.update(shingle.encode('utf-8'))
+ return m
+
+
+def abstein_string_for_decon(string):
+ # Abstein the reading comprehension subject in MMLU where a paragraph from Wikipedia is given in the question
+ return "refers to the following information" in string
+
+
+def remove_duplicates_with_minhash(
+ documents, string_for_decontamination=None, threshold=0.8, num_perm=128
+):
+ # Apply 13-gram Jaccard similarity deduplication and removes ones with similarity > 80% compared to former docs.
+ # Remove chunks shorter than 13 words.
+
+ # Create an LSH index
+ lsh = MinHashLSH(threshold=threshold, num_perm=num_perm)
+
+ # Dictionary to store the MinHash of each document
+ minhashes = {}
+
+ # Hash string for decontamination first so contaminated samples will be removed
+ decon_offset = 0
+ if string_for_decontamination is not None and not abstein_string_for_decon(
+ string_for_decontamination
+ ):
+ shingles = shingle_document(string_for_decontamination)
+ m_decon = create_minhash(shingles, num_perm)
+ lsh.insert(f"doc_{decon_offset}", m_decon)
+ minhashes[decon_offset] = m_decon
+ decon_offset = 1
+
+ # Populate the LSH index
+ short_chunk_indices = []
+ for idx, ctx in enumerate(documents, start=decon_offset):
+ doc = ctx["retrieval text"]
+ shingles = shingle_document(doc)
+ if not shingles:
+ short_chunk_indices.append(idx - decon_offset)
+ m = create_minhash(shingles, num_perm)
+ lsh.insert(f"doc_{idx}", m)
+ minhashes[idx] = m
+
+ # List to keep track of non-duplicate document indices
+ non_duplicate_indices = []
+
+ # Check each document against the LSH index
+ for idx, m in minhashes.items():
+ if idx < decon_offset:
+ continue
+
+ # Query the LSH for near-duplicate candidates
+ result = lsh.query(m)
+
+ # print(result)
+ # print([minhashes[int(doc_id.split("_")[1])].jaccard(m) for doc_id in result])
+
+ # If the document is the only one in its bucket or it appears first in the list
+ if all(
+ minhashes[int(doc_id.split("_")[1])].jaccard(m) <= threshold
+ or int(doc_id.split("_")[1]) >= idx
+ for doc_id in result
+ ):
+ non_duplicate_indices.append(idx - decon_offset)
+
+ # Return non-duplicate documents
+ deduplicated_documents = [
+ documents[i] for i in non_duplicate_indices if i not in short_chunk_indices
+ ]
+ [doc.update({"quality score": 1}) for doc in deduplicated_documents]
+ removed_documents = [doc for doc in documents if doc not in deduplicated_documents]
+ [doc.update({"quality score": 0}) for doc in removed_documents]
+
+ print(f"Non-deduplication ctxs num: {len(deduplicated_documents)}")
+ # for c in deduplicated_documents:
+ # try:
+ # print(c['retrieval text'][:10])
+ # except:
+ # print(c)
+ # if len(deduplicated_documents[0]['retrieval text'].split(' ')) < 13:
+ # import pdb; pdb.set_trace()
+ return deduplicated_documents # + removed_documents
+
+
+def process_item(data_item):
+ time.sleep(0.0001)
+ id_, ex = data_item
+ ex["ctxs"] = remove_duplicates_with_minhash(
+ ex["ctxs"], string_for_decontamination=ex["raw_query"]
+ )
+ return id_, ex
+
+
+def multiprocess_deduplication(data):
+ items_to_process = list(enumerate(data))
+ pool = multiprocessing.Pool(processes=32)
+ for result in pool.imap(process_item, items_to_process):
+ id_, updated_ex = result
+ data[id_] = updated_ex
+ return data
+
+
+if __name__ == "__main__":
+ # Example usage:
+ question = (
+ "Answer these questions:\n\nQ: when did the eagles win last super bowl?\nA:"
+ )
+ docs = [
+ "Eagles won the Super Bowl.",
+ "Machine learning provides the ability to automatically learn and improve from experience without being explicitly programmed."
+ * 20,
+ "Machine learning provides the ability to automatically learn and improve from experience without being explicitly programmed."
+ * 20
+ + ".",
+ "An entirely different document looks nothing like the others and should not be considered a duplicate."
+ * 20,
+ "Short sentence." * 1,
+ "As someone who lived in Philly for about five years, I agree about the city\u2019s greatness \u2014 which makes the juxtaposition between its friendly day-to-day interactions and sometimes psychotic sports fandom even more jarring. The Eagles did win three NFL championships before the Super Bowl existed, most recently in 1960. But any fan who was following the team back then is now at least into their mid-60s, if not much older. It is, to say the least, a distant memory from another era. Granted, the Sixers went on their infamous tanking expedition during this span.",
+ ] * 1
+ import time
+
+ num_ex = 1
+
+ start = time.time()
+ data1 = []
+ for _ in range(num_ex):
+ cleaned_ex = remove_duplicates_with_minhash(
+ [{"retrieval text": doc} for doc in docs], question
+ )
+ data1.append(cleaned_ex)
+ time1 = time.time() - start
+
+ # ori_data = [{'raw_query': docs[0], 'ctxs': [{'retrieval text': doc} for doc in docs]}] * num_ex
+ # start = time.time()
+ # data2 = multiprocess_deduplication(ori_data)
+ # time2 = time.time()-start
+
+ # assert data2[0]['ctxs'] == data1[0]
+
+ # print(time1)
+ # print(time2)
diff --git a/research/utils/demo_reader.cpp b/research/utils/demo_reader.cpp
new file mode 100644
index 0000000..4d7af1c
--- /dev/null
+++ b/research/utils/demo_reader.cpp
@@ -0,0 +1,387 @@
+/*
+Run with
+g++ ./demo_reader.cpp -o ./demo_reader && ./demo_reader --stats \
+/powerrag/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/diskann/_partition.bin
+\
+/powerrag/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/diskann/_disk_graph.index
+*/
+
+#include <algorithm>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <iomanip>
+#include <iostream>
+#include <limits> // Include for std::numeric_limits
+#include <string> // Include for std::string comparison
+#include <vector>
+
+#define READ_U64(f, val) \
+ f.read(reinterpret_cast<char *>(&val), sizeof(uint64_t))
+#define READ_U32(f, val) \
+ f.read(reinterpret_cast<char *>(&val), sizeof(uint32_t))
+#define SECTOR_SIZE 4096
+
+// 辅助:获取文件大小
+static size_t get_file_size(const std::string &fname) {
+ std::ifstream ifs(fname, std::ios::binary | std::ios::ate);
+ if (ifs.fail() || !ifs.is_open()) {
+ return 0;
+ }
+ return static_cast<size_t>(ifs.tellg());
+}
+
+// 打印 sector 的前若干 hex,用于debug
+static void print_hex(const char *buf, size_t len, size_t max_len = 64) {
+ size_t show_len = (len < max_len) ? len : max_len;
+ for (size_t i = 0; i < show_len; i++) {
+ unsigned char c = (unsigned char)buf[i];
+ std::cout << std::hex << std::setw(2) << std::setfill('0') << (unsigned)c
+ << " ";
+ if ((i + 1) % 16 == 0)
+ std::cout << "\n ";
+ }
+ std::cout << std::dec << "\n";
+}
+
+/*
+ 修正后的 demo_reader:
+ 1) 从 partition.bin 读:
+ - C, partition_nums, nd
+ - graph_partitions[i]: 分区 i 的所有 nodeID
+ - id2partition[nodeID]: nodeID => partition i
+ 2) 从 _disk_graph.index 读:
+ a) sector0 里先有 2个 int: meta_n, meta_dim
+ b) 再有 meta_n个 uint64_t
+ 例如: [0]=nd, [1]=dim, [2]=??, [3]=max_node_len, [4]=C, [5]..??,
+ [8]=file_size... 具体位置要结合 relayout 的写法 c) graph_node_len =
+ max_node_len - dim_in_meta*sizeof(float) 3) 用户给定 target_node_id =>
+ partition_id= id2partition[node_id]
+ 在 graph_partitions[partition_id] 里找 node 的下标 j
+ offset = (partition_id+1)*4096 => sector
+ adjacency_offset= j*graph_node_len => neighbor_count => neighbors
+*/
+int main(int argc, char **argv) {
+ bool calculate_stats = false;
+ // int arg_offset = 0; // Offset for positional arguments
+ std::string partition_bin;
+ std::string graph_index;
+ uint64_t target_node_id = 0; // Initialize
+
+ if (argc != 4) {
+ std::cerr << "Usage:\n"
+ << " " << argv[0]
+ << " <partition.bin> <disk_graph.index> <target_node_id> (Reads "
+ "adjacency for a node)\n"
+ << " " << argv[0]
+ << " --stats <partition.bin> <disk_graph.index> "
+ "(Calculates degree statistics)\n";
+ return 1;
+ }
+
+ // Check if the first argument is the stats flag
+ if (std::string(argv[1]) == "--stats") {
+ calculate_stats = true;
+ partition_bin = argv[2];
+ graph_index = argv[3];
+ std::cout << "Mode: Calculating Degree Statistics\n";
+ } else {
+ // Assume default mode (single node lookup)
+ calculate_stats = false;
+ partition_bin = argv[1];
+ graph_index = argv[2];
+ try { // Add error handling for stoull
+ target_node_id = std::stoull(argv[3]);
+ } catch (const std::invalid_argument &ia) {
+ std::cerr << "Error: Invalid target_node_id: " << argv[3] << std::endl;
+ return 1;
+ } catch (const std::out_of_range &oor) {
+ std::cerr << "Error: target_node_id out of range: " << argv[3]
+ << std::endl;
+ return 1;
+ }
+ std::cout << "Mode: Single Node Lookup for Node ID " << target_node_id
+ << "\n";
+ }
+
+ // 1) 读取 partition.bin
+ std::ifstream pf(partition_bin, std::ios::binary);
+ if (!pf.is_open()) {
+ std::cerr << "Cannot open partition.bin: " << partition_bin << std::endl;
+ return 1;
+ }
+ uint64_t C, partition_nums, nd;
+ READ_U64(pf, C);
+ READ_U64(pf, partition_nums);
+ READ_U64(pf, nd);
+ std::cout << "[partition.bin header] C=" << C
+ << ", partition_nums=" << partition_nums << ", nd=" << nd
+ << std::endl;
+
+ // 读取分区节点列表
+ std::vector<std::vector<uint32_t>> graph_partitions(partition_nums);
+ for (uint64_t i = 0; i < partition_nums; i++) {
+ uint32_t psize;
+ READ_U32(pf, psize);
+ graph_partitions[i].resize(psize);
+ pf.read(reinterpret_cast<char *>(graph_partitions[i].data()),
+ psize * sizeof(uint32_t));
+ }
+ // 读取 _id2partition[node], 大小= nd
+ std::vector<uint32_t> id2partition(nd);
+ pf.read(reinterpret_cast<char *>(id2partition.data()), nd * sizeof(uint32_t));
+ pf.close();
+ std::cout << "Done loading partition info.\n";
+
+ if (target_node_id >= nd) {
+ std::cerr << "target_node_id=" << target_node_id
+ << " out of range nd=" << nd << std::endl;
+ return 1;
+ }
+
+ // 2) 解析 _disk_graph.index
+ std::ifstream gf(graph_index, std::ios::binary);
+ if (!gf.is_open()) {
+ std::cerr << "Cannot open disk_graph.index: " << graph_index << std::endl;
+ return 1;
+ }
+ // (a) sector0 => 先读 2个 int
+ int meta_n, meta_dim;
+ gf.read((char *)&meta_n, sizeof(int));
+ gf.read((char *)&meta_dim, sizeof(int));
+ std::cout << "[debug] meta_n=" << meta_n << ", meta_dim=" << meta_dim << "\n";
+
+ // (b) 读 meta_n个 uint64_t
+ std::vector<uint64_t> meta_info(meta_n);
+ gf.read(reinterpret_cast<char *>(meta_info.data()),
+ meta_n * sizeof(uint64_t));
+ // 打印
+ for (int i = 0; i < meta_n; i++) {
+ std::cout << " meta_info[" << i << "]= " << meta_info[i] << "\n";
+ }
+
+ size_t file_size = get_file_size(graph_index);
+ std::cout << "[disk_graph.index size] " << file_size << " bytes\n";
+
+ // **根据 relayout log** 你说: meta_info[0]=nd=60450220, meta_info[1]=dim=769,
+ // meta_info[2]=??(16495248?), meta_info[3]=max_node_len=3320,
+ // meta_info[4]=16 (C),
+ // meta_info[8]= 15475261440(文件大小)
+ // 我们这里先手动解析:
+ uint64_t nd_in_meta = meta_info[0];
+ uint64_t dim_in_meta = meta_info[1];
+ uint64_t max_node_len = meta_info[3];
+ uint64_t c_in_meta = meta_info[4];
+ uint64_t entire_file_sz = meta_info[8];
+
+ std::cout << "Based on meta_info:\n"
+ << " nd_in_meta= " << nd_in_meta
+ << ", dim_in_meta= " << dim_in_meta
+ << ", max_node_len= " << max_node_len
+ << ", c_in_meta= " << c_in_meta
+ << ", entire_file_size= " << entire_file_sz << "\n";
+
+ // 计算 graph_node_len
+ uint64_t dim_size = dim_in_meta * sizeof(float);
+ uint64_t graph_node_len = max_node_len - dim_size;
+ std::cout << " => graph_node_len= " << graph_node_len << "\n\n";
+
+ if (calculate_stats) {
+ // --- Degree Statistics Calculation Mode ---
+ std::cout << " Calculated graph_node_len = " << graph_node_len << "\n\n";
+
+ if (nd == 0) {
+ std::cerr << "Graph has 0 nodes (nd=0). Cannot calculate stats."
+ << std::endl;
+ gf.close();
+ return 1;
+ }
+
+ uint32_t min_degree = std::numeric_limits<uint32_t>::max();
+ uint32_t max_degree = 0;
+ uint64_t total_degree = 0;
+ uint64_t nodes_processed = 0;
+ std::vector<char> sectorBuf(SECTOR_SIZE);
+
+ std::cout << "Calculating degrees for " << nd << " nodes across "
+ << partition_nums << " partitions..." << std::endl;
+
+ for (uint32_t p = 0; p < partition_nums; ++p) {
+ uint64_t sector_offset = uint64_t(p + 1) * SECTOR_SIZE;
+ gf.seekg(sector_offset, std::ios::beg);
+ if (gf.fail()) {
+ std::cerr << "Error seeking to sector offset for partition " << p
+ << std::endl;
+ gf.close();
+ return 1;
+ }
+ gf.read(sectorBuf.data(), SECTOR_SIZE);
+ if (gf.fail() && !gf.eof()) {
+ std::cerr << "Error reading sector data for partition " << p
+ << std::endl;
+ gf.close();
+ return 1;
+ }
+ gf.clear(); // Reset fail bits
+
+ const auto &part_list = graph_partitions[p];
+ for (size_t j = 0; j < part_list.size(); ++j) {
+ uint64_t node_offset = j * graph_node_len;
+ if (node_offset + sizeof(uint32_t) > SECTOR_SIZE) {
+ std::cerr << "Error: Node offset out of sector bounds.\n"
+ << " Partition=" << p << ", node_subIndex=" << j
+ << ", node_offset=" << node_offset
+ << ", graph_node_len=" << graph_node_len << std::endl;
+ gf.close();
+ return 1;
+ }
+ char *adjacency_ptr = sectorBuf.data() + node_offset;
+ uint32_t neighbor_count = *reinterpret_cast<uint32_t *>(adjacency_ptr);
+ min_degree = std::min(min_degree, neighbor_count);
+ max_degree = std::max(max_degree, neighbor_count);
+ total_degree += neighbor_count;
+ nodes_processed++;
+ }
+ if (p % 10 == 0 || p == partition_nums - 1) {
+ std::cout << " Processed partition " << p + 1 << " / "
+ << partition_nums << "...\r" << std::flush;
+ }
+ }
+ std::cout << "\nFinished processing partitions." << std::endl;
+
+ if (nodes_processed != nd) {
+ std::cerr << "Warning: Processed " << nodes_processed
+ << " nodes, but expected " << nd << std::endl;
+ }
+
+ double avg_degree = (nd > 0) ? static_cast<double>(total_degree) / nd : 0.0;
+ std::cout << "\n--- Degree Statistics ---\n";
+ std::cout << "Min Degree: "
+ << (min_degree == std::numeric_limits<uint32_t>::max()
+ ? 0
+ : min_degree)
+ << std::endl; // Handle case of 0 nodes
+ std::cout << "Max Degree: " << max_degree << std::endl;
+ std::cout << "Avg Degree: " << std::fixed << std::setprecision(2)
+ << avg_degree << std::endl;
+ std::cout << "Total Degree (Sum): " << total_degree << std::endl;
+ std::cout << "Nodes Processed: " << nodes_processed << std::endl;
+
+ } else {
+ uint64_t nd_in_meta = meta_info[0];
+ uint64_t c_in_meta = meta_info[4];
+ uint64_t entire_file_sz = meta_info[8];
+ std::cout << "Based on meta_info:\n"
+ << " nd_in_meta= " << nd_in_meta
+ << ", dim_in_meta= " << dim_in_meta
+ << ", max_node_len= " << max_node_len
+ << ", c_in_meta= " << c_in_meta
+ << ", entire_file_size= " << entire_file_sz << "\n";
+ std::cout << " => graph_node_len= " << graph_node_len << "\n\n";
+
+ if (target_node_id >= nd) {
+ std::cerr << "target_node_id=" << target_node_id
+ << " out of range nd=" << nd << std::endl;
+ gf.close();
+ return 1;
+ }
+
+ // We need id2partition only for single-node lookup
+ std::vector<uint32_t> id2partition(nd);
+ { // Read id2partition again as it was skipped before
+ std::ifstream pf_again(partition_bin, std::ios::binary);
+ uint64_t header_offset =
+ 3 * sizeof(uint64_t); // Skip C, partition_nums, nd
+ uint64_t partition_list_offset = 0;
+ for (uint64_t i = 0; i < partition_nums; i++) {
+ partition_list_offset += sizeof(uint32_t); // Size field
+ partition_list_offset +=
+ graph_partitions[i].size() * sizeof(uint32_t); // Data
+ }
+ pf_again.seekg(header_offset + partition_list_offset, std::ios::beg);
+ pf_again.read(reinterpret_cast<char *>(id2partition.data()),
+ nd * sizeof(uint32_t));
+ // Error check pf_again if needed
+ }
+
+ // 3) 找 target_node_id => partition_id => subIndex
+ uint32_t partition_id = id2partition[target_node_id];
+ if (partition_id >= partition_nums) {
+ std::cerr << "Partition ID out-of-range for target node.\n";
+ gf.close();
+ return 1;
+ }
+ const auto &part_list = graph_partitions[partition_id]; // Use const ref
+ auto it =
+ std::find(part_list.begin(), part_list.end(), (uint32_t)target_node_id);
+ if (it == part_list.end()) {
+ std::cerr << "Cannot find node " << target_node_id << " in partition "
+ << partition_id << std::endl;
+ gf.close();
+ return 1;
+ }
+ size_t j = std::distance(part_list.begin(), it);
+
+ // 4) sector => (partition_id+1)* 4096
+ uint64_t sector_offset = uint64_t(partition_id + 1) * SECTOR_SIZE;
+ gf.seekg(sector_offset, std::ios::beg);
+ std::vector<char> sectorBuf(SECTOR_SIZE);
+ gf.read(sectorBuf.data(), SECTOR_SIZE);
+ if (gf.fail() && !gf.eof()) {
+ std::cerr << "Error reading sector data for partition " << partition_id
+ << std::endl;
+ gf.close();
+ return 1;
+ }
+ gf.clear(); // Reset fail bits
+
+ std::cout << "Partition #" << partition_id
+ << ", nodeCount= " << part_list.size()
+ << ", offset= " << sector_offset << "\n"
+ << " first64 hex:\n ";
+ print_hex(sectorBuf.data(), SECTOR_SIZE, 64);
+
+ // adjacency_offset= j* graph_node_len
+ uint64_t node_offset = j * graph_node_len;
+ if (node_offset + sizeof(uint32_t) >
+ SECTOR_SIZE) { // Check only for neighbor_count read first
+ std::cerr << "Out-of-range. j=" << j << ", node_offset=" << node_offset
+ << ", node_offset+4=" << (node_offset + sizeof(uint32_t))
+ << "> 4096\n";
+ gf.close();
+ return 1;
+ }
+
+ char *adjacency_ptr = sectorBuf.data() + node_offset;
+ uint32_t neighbor_count = *reinterpret_cast<uint32_t *>(adjacency_ptr);
+ std::cout << "[Node " << target_node_id << "] partition=" << partition_id
+ << ", subIndex=" << j << ", adjacency_offset=" << node_offset
+ << ", neighbor_count=" << neighbor_count << "\n";
+
+ size_t needed = neighbor_count * sizeof(uint32_t);
+ if (node_offset + sizeof(uint32_t) + needed > SECTOR_SIZE) {
+ std::cerr << "Neighbors partly out-of-range => neighbor_count="
+ << neighbor_count << "\n";
+ // Option: Can still print partial list if needed, but indicating it's
+ // truncated
+ gf.close();
+ return 1; // Or handle differently
+ }
+ std::vector<uint32_t> neighbors(neighbor_count);
+ memcpy(neighbors.data(), adjacency_ptr + sizeof(uint32_t), needed);
+
+ std::cout << " neighbors=[";
+ for (size_t kk = 0; kk < std::min<size_t>(10, neighbor_count); kk++) {
+ std::cout << neighbors[kk];
+ if (kk + 1 < std::min<size_t>(10, neighbor_count))
+ std::cout << ", ";
+ }
+ if (neighbor_count > 10)
+ std::cout << " ... (total " << neighbor_count << ")";
+ std::cout << "]\n";
+ } // End of else (single node lookup mode)
+
+ gf.close();
+ return 0;
+}
\ No newline at end of file
diff --git a/research/utils/diskann_degree_distribution.fish b/research/utils/diskann_degree_distribution.fish
new file mode 100755
index 0000000..a370a9b
--- /dev/null
+++ b/research/utils/diskann_degree_distribution.fish
@@ -0,0 +1,15 @@
+#! /bin/fish
+
+# get the dir of this script
+set -x SCRIPT_DIR (dirname (realpath $0))
+
+g++ $SCRIPT_DIR/analyze_diskann_graph.cpp -o $SCRIPT_DIR/analyze_diskann_graph
+
+# get args
+set -x INDEX_PATH $argv[1]
+
+./analyze_diskann_graph $INDEX_PATH $INDEX_PATH.degree_distribution.txt
+
+python plot_degree_distribution.py $INDEX_PATH.degree_distribution.txt
+
+rm $INDEX_PATH.degree_distribution.txt
\ No newline at end of file
diff --git a/research/utils/download_mac.fish b/research/utils/download_mac.fish
new file mode 100644
index 0000000..b3b1280
--- /dev/null
+++ b/research/utils/download_mac.fish
@@ -0,0 +1,30 @@
+#!/usr/bin/env fish
+
+set scaling_out_dir "/Users/ec2-user/scaling_out"
+
+# Define an array of paths to download
+set paths \
+ "examples/" \
+ "indices/rpj_wiki/facebook/contriever-msmarco/diskann/_disk_graph.index" \
+ "indices/rpj_wiki/facebook/contriever-msmarco/diskann/_partition.bin" \
+ "indices/rpj_wiki/facebook/contriever-msmarco/diskann/ann_disk.index_medoids.bin" \
+ "indices/rpj_wiki/facebook/contriever-msmarco/diskann/ann_disk.index_centroids.bin" \
+ "indices/rpj_wiki/facebook/contriever-msmarco/diskann/ann_disk.index_max_base_norm.bin" \
+ "embeddings/facebook/contriever-msmarco/rpj_wiki/compressed_10/" \
+ "passages/rpj_wiki/8-shards/" \
+ "indices/rpj_wiki/facebook/contriever-msmarco/flat_results_nq_k3.json"
+
+# Download each path using a for loop
+for path in $paths
+ echo "Downloading $path..."
+ # if ends with /, then create the directory
+ if string match -q "*/" $path
+ echo "Creating directory $scaling_out_dir/$path"
+ mkdir -p "$scaling_out_dir/$path"
+ aws s3 cp "s3://retrieval-scaling-out/$path" "$scaling_out_dir/$path" --recursive
+ else
+ aws s3 cp "s3://retrieval-scaling-out/$path" "$scaling_out_dir/$path"
+ end
+end
+
+echo "Download completed."
\ No newline at end of file
diff --git a/research/utils/embedding_comp.py b/research/utils/embedding_comp.py
new file mode 100644
index 0000000..a06af39
--- /dev/null
+++ b/research/utils/embedding_comp.py
@@ -0,0 +1,422 @@
+import torch
+import numpy as np
+from transformers import AutoTokenizer, AutoModel
+import pandas as pd
+import matplotlib.pyplot as plt
+import seaborn as sns
+from tqdm import tqdm
+from scipy.stats import kendalltau, spearmanr
+
+# 设置设备
+device = torch.device("cuda" if torch.cuda.is_available() else
+ ("mps" if torch.backends.mps.is_available() else "cpu"))
+print(f"使用设备: {device}")
+
+# 定义自定义比较函数(基于内积)
+def compare(a, b):
+ """
+ 计算两个向量的内积,并返回其负值作为距离度量
+ 数值越小表示越相似(与提供的代码一致)
+ """
+ result = np.dot(a, b)
+ return -result # 返回负值,与原代码一致
+
+# 批量计算相似度
+def compute_similarities(queries, corpus):
+ """计算查询向量与语料库向量之间的相似度矩阵"""
+ similarities = np.zeros((len(queries), len(corpus)))
+ for i, query in enumerate(queries):
+ for j, doc in enumerate(corpus):
+ similarities[i, j] = compare(query, doc)
+ return similarities
+
+# 加载两个模型
+model_names = [
+ "facebook/contriever-msmarco", # Contriever模型
+ "facebook/contriever-msmarco-int4" # Contriever模型 (int4)
+]
+
+# 扩展的样本文本 - 分为多个主题组
+texts = [
+ # 组1: 关于狐狸和动物 (0-9)
+ "The quick brown fox jumps over the lazy dog.",
+ "A rapid auburn fox leaps above the inactive canine.",
+ "The sly fox outsmarts the hunting hounds in the forest.",
+ "Foxes are known for their cunning behavior and bushy tails.",
+ "The red fox is the largest of the true foxes and the most common fox species.",
+ "Dogs have been companions to humans for thousands of years.",
+ "The lazy dog slept through the commotion of the playful fox.",
+ "Wolves and foxes belong to the same family, Canidae.",
+ "The arctic fox changes its coat color with the seasons.",
+ "Domestic dogs come in hundreds of breeds of various sizes and appearances.",
+
+ # 组2: 人工智能和机器学习 (10-19)
+ "Machine learning is a branch of artificial intelligence.",
+ "Deep learning is a subset of machine learning.",
+ "Neural networks are computing systems inspired by biological neural networks.",
+ "AI systems can now beat human champions at complex games like chess and Go.",
+ "Natural language processing allows computers to understand human language.",
+ "Reinforcement learning involves training agents to make sequences of decisions.",
+ "Computer vision enables machines to derive information from images and videos.",
+ "The Turing test measures a machine's ability to exhibit intelligent behavior.",
+ "Supervised learning uses labeled training data to learn the mapping function.",
+ "Unsupervised learning finds patterns in data without pre-existing labels.",
+
+ # 组3: 巴黎和法国地标 (20-29)
+ "The Eiffel Tower is located in Paris, France.",
+ "The Louvre Museum is in the city of Paris.",
+ "Notre-Dame Cathedral is a medieval Catholic cathedral on the Île de la Cité in Paris.",
+ "The Arc de Triomphe stands at the center of the Place Charles de Gaulle in Paris.",
+ "The Seine River flows through the heart of Paris.",
+ "Montmartre is a large hill in Paris's 18th arrondissement known for its artistic history.",
+ "The Palace of Versailles is located in the Île-de-France region of France.",
+ "The Champs-Élysées is an avenue in Paris famous for its theatres, cafés, and luxury shops.",
+ "The Sacré-Cœur Basilica offers one of the most beautiful panoramic views of Paris.",
+ "The Musée d'Orsay houses the largest collection of impressionist masterpieces in the world.",
+
+ # 组4: 可再生能源 (30-39)
+ "Solar panels convert sunlight into electricity.",
+ "Wind turbines generate power from moving air.",
+ "Hydroelectric power is generated from flowing water.",
+ "Geothermal energy harnesses heat from within the Earth.",
+ "Biomass energy comes from organic materials like plants and waste.",
+ "Tidal energy uses the natural rise and fall of coastal tidal waters.",
+ "Renewable energy sources can help reduce greenhouse gas emissions.",
+ "Solar farms can span hundreds of acres with thousands of panels.",
+ "Offshore wind farms are built in bodies of water to harvest wind energy.",
+ "Energy storage systems are crucial for balancing renewable energy supply and demand.",
+
+ # 组5: 编程语言 (40-49)
+ "Python is a popular programming language for data science.",
+ "JavaScript is commonly used for web development.",
+ "Java is known for its 'write once, run anywhere' capability.",
+ "C++ provides high-performance and close hardware control.",
+ "Ruby is praised for its simplicity and productivity.",
+ "PHP is a server-side scripting language designed for web development.",
+ "Swift is used to develop applications for Apple platforms.",
+ "Rust offers memory safety without using garbage collection.",
+ "Go was designed at Google to improve programming productivity.",
+ "Kotlin is fully interoperable with Java and provides more concise syntax.",
+]
+
+# 扩展的查询句子
+query_texts = [
+ # 动物相关查询
+ "A fox jumped over a dog.",
+ "Wild animals and their behaviors in forests.",
+ "Different species of foxes around the world.",
+
+ # AI相关查询
+ "Artificial intelligence and neural networks.",
+ "Machine learning algorithms and applications.",
+ "The future of deep learning technology.",
+
+ # 巴黎相关查询
+ "Famous landmarks in Paris, France.",
+ "Tourist attractions along the Seine River.",
+ "Historical buildings and museums in Paris.",
+
+ # 能源相关查询
+ "Renewable energy sources and sustainability.",
+ "Solar and wind power generation technologies.",
+ "Alternative clean energy solutions for the future.",
+
+ # 编程相关查询
+ "Computer programming languages comparison.",
+ "Best languages for web development.",
+ "Programming tools for data science applications."
+]
+
+# 函数:获取BGE模型的嵌入
+def get_bge_embeddings(model, tokenizer, texts, device):
+ # 处理大量文本时分批进行
+ batch_size = 16
+ all_embeddings = []
+
+ for i in range(0, len(texts), batch_size):
+ batch_texts = texts[i:i+batch_size]
+ encoded_input = tokenizer(batch_texts, padding=True, truncation=True,
+ max_length=512, return_tensors='pt').to(device)
+
+ with torch.no_grad():
+ model_output = model(**encoded_input)
+
+ # BGE使用[CLS]标记
+ embeddings = model_output.last_hidden_state[:, 0]
+ # 归一化嵌入
+ normalized_embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
+ all_embeddings.append(normalized_embeddings.cpu().numpy())
+
+ return np.vstack(all_embeddings)
+
+# 函数:获取Contriever模型的嵌入
+def get_contriever_embeddings(model, tokenizer, texts, device, use_int4=False):
+ # 处理大量文本时分批进行
+ batch_size = 16
+ all_embeddings = []
+
+ for i in range(0, len(texts), batch_size):
+ batch_texts = texts[i:i+batch_size]
+ encoded_input = tokenizer(batch_texts, padding=True, truncation=True,
+ max_length=512, return_tensors='pt').to(device)
+
+ with torch.no_grad():
+ model_output = model(**encoded_input)
+
+ # Contriever使用平均池化
+ attention_mask = encoded_input['attention_mask'].unsqueeze(-1)
+ embeddings = (model_output.last_hidden_state * attention_mask).sum(1) / attention_mask.sum(1)
+ # 归一化嵌入
+ normalized_embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
+ all_embeddings.append(normalized_embeddings.cpu().numpy())
+
+ return np.vstack(all_embeddings)
+
+# 主函数
+def compare_embeddings():
+ results = {}
+
+ for i, model_name in enumerate(model_names):
+ model_display_name = model_name
+ # 给第二个模型一个不同的显示名称,以便区分
+ if i == 1:
+ model_display_name = "facebook/contriever-msmarco-int4"
+
+ print(f"\n======= 加载模型 {i+1}: {model_display_name} =======")
+ tokenizer = AutoTokenizer.from_pretrained(model_names[0]) # 两个模型使用相同的tokenizer
+
+ # 如果是第二个模型(int4版本),进行量化
+ if i == 1:
+ print("应用int4量化...")
+ try:
+ from transformers import BitsAndBytesConfig
+ quantization_config = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_compute_dtype=torch.float16,
+ bnb_4bit_use_double_quant=True,
+ bnb_4bit_quant_type="nf4"
+ )
+ model = AutoModel.from_pretrained(
+ model_names[0], # 使用相同的基础模型
+ quantization_config=quantization_config,
+ device_map="auto"
+ )
+ print("成功加载int4模型")
+ except Exception as e:
+ print(f"int4加载失败: {e}")
+ print("回退到标准模型...")
+ model = AutoModel.from_pretrained(model_names[0]).to(device)
+ else:
+ model = AutoModel.from_pretrained(model_names[0]).to(device)
+
+ model.eval()
+
+ print(f"使用 {model_display_name} 生成嵌入...")
+ # 所有模型都使用contriever
+ use_int4 = i == 1
+ corpus_embeddings = get_contriever_embeddings(model, tokenizer, texts, device, use_int4)
+ query_embeddings = get_contriever_embeddings(model, tokenizer, query_texts, device, use_int4)
+
+ print(f"语料库嵌入形状: {corpus_embeddings.shape}")
+ print(f"查询嵌入形状: {query_embeddings.shape}")
+
+ # 使用自定义函数计算相似度
+ similarity_scores = compute_similarities(query_embeddings, corpus_embeddings)
+
+ # 对每个查询,按相似度排序文本索引(较小的值表示更相似)
+ ranked_indices = {}
+ for j, scores in enumerate(similarity_scores):
+ # 按相似度从低到高排序(因为我们返回的是负内积值)
+ sorted_indices = np.argsort(scores)
+ ranked_indices[f"query_{j+1}"] = sorted_indices
+
+ results[model_display_name] = {
+ 'corpus_embeddings': corpus_embeddings,
+ 'query_embeddings': query_embeddings,
+ 'similarity_scores': similarity_scores,
+ 'ranked_indices': ranked_indices
+ }
+
+ # 立即打印这个模型的一些结果作为验证
+ print(f"\n=== {model_display_name} 初步结果 ===")
+ # 显示第一个查询的前3个结果
+ query_idx = 0
+ ranked_idx = ranked_indices[f"query_{query_idx+1}"]
+ top_texts = [texts[idx] for idx in ranked_idx[:3]]
+ print(f"查询: '{query_texts[query_idx]}'")
+ print(f"排名前3位的文本:")
+ for j, text in enumerate(top_texts):
+ idx = ranked_idx[j]
+ score = similarity_scores[query_idx][idx]
+ print(f" {j+1}. [ID:{idx}] {text} (分数: {score:.4f})")
+
+ return results
+
+# 分析结果
+def analyze_results(results):
+ models = list(results.keys())
+
+ # 1. 比较相似度分数
+ print("\n=== 相似度分数比较 ===")
+ for model_name, result in results.items():
+ similarities = result['similarity_scores'].flatten()
+ print(f"{model_name} 相似度统计:")
+ print(f" 平均值: {similarities.mean():.4f}")
+ print(f" 最小值: {similarities.min():.4f}")
+ print(f" 最大值: {similarities.max():.4f}")
+ print(f" 标准差: {similarities.std():.4f}")
+
+ # 2. 比较排序结果(针对每个查询显示前5个结果)
+ print("\n=== 排序结果比较 ===")
+ for query_idx in range(len(query_texts)):
+ query_key = f"query_{query_idx+1}"
+ print(f"\n查询 {query_idx+1}: '{query_texts[query_idx]}'")
+
+ for model_name in models:
+ ranked_idx = results[model_name]['ranked_indices'][query_key]
+ top_texts = [texts[idx] for idx in ranked_idx[:5]]
+ print(f"{model_name} 排名前5位的文本:")
+ for i, text in enumerate(top_texts):
+ idx = ranked_idx[i]
+ score = results[model_name]['similarity_scores'][query_idx][idx]
+ print(f" {i+1}. [ID:{idx}] {text} (分数: {score:.4f})")
+
+ # 3. 排序一致性分析
+ print("\n=== 模型间排序一致性分析 ===")
+ kendall_tau_scores = []
+ spearman_scores = []
+
+ for query_idx in range(len(query_texts)):
+ query_key = f"query_{query_idx+1}"
+
+ # 获取各模型的排序结果(只比较前10个结果)
+ model1_top10 = results[models[0]]['ranked_indices'][query_key][:10]
+ model2_top10 = results[models[1]]['ranked_indices'][query_key][:10]
+
+ # 计算排序一致性
+ kt, _ = kendalltau(model1_top10, model2_top10)
+ sr, _ = spearmanr(model1_top10, model2_top10)
+
+ kendall_tau_scores.append(kt)
+ spearman_scores.append(sr)
+
+ # 计算前10个结果的重叠率
+ overlap = len(set(model1_top10) & set(model2_top10))
+ overlap_rate = overlap / 10.0
+
+ print(f"查询 {query_idx+1} '{query_texts[query_idx]}':")
+ print(f" Kendall's Tau = {kt:.4f}, Spearman's rank correlation = {sr:.4f}")
+ print(f" 前10结果重叠率: {overlap_rate:.2f} ({overlap}/10)")
+
+ print(f"\n平均 Kendall's Tau: {np.mean(kendall_tau_scores):.4f}")
+ print(f"平均 Spearman's rank correlation: {np.mean(spearman_scores):.4f}")
+
+ # 4. 可视化相似度分布差异
+ plt.figure(figsize=(12, 6))
+ for i, model_name in enumerate(models):
+ sns.histplot(results[model_name]['similarity_scores'].flatten(),
+ kde=True, label=model_name, alpha=0.6)
+
+ plt.title('不同模型的相似度分布')
+ plt.xlabel('相似度得分(越小越相似)')
+ plt.ylabel('频率')
+ plt.legend()
+ plt.savefig('similarity_distribution.png')
+ print("已保存相似度分布图表到 'similarity_distribution.png'")
+
+ # 5. 可视化主题相关性
+ plt.figure(figsize=(15, 10))
+
+ # 为每个主题组定义颜色
+ topic_colors = {
+ '动物': 'blue',
+ 'AI': 'red',
+ '巴黎': 'green',
+ '能源': 'purple',
+ '编程': 'orange'
+ }
+
+ # 定义主题组范围
+ topic_ranges = {
+ '动物': (0, 10),
+ 'AI': (10, 20),
+ '巴黎': (20, 30),
+ '能源': (30, 40),
+ '编程': (40, 50)
+ }
+
+ # 对每个查询显示前10个结果的主题分布
+ query_groups = [
+ [0, 1, 2], # 动物查询组
+ [3, 4, 5], # AI查询组
+ [6, 7, 8], # 巴黎查询组
+ [9, 10, 11], # 能源查询组
+ [12, 13, 14] # 编程查询组
+ ]
+
+ for group_idx, group in enumerate(query_groups):
+ plt.subplot(len(query_groups), 1, group_idx+1)
+
+ # 为每个模型计算主题分布
+ bar_width = 0.35
+ bar_positions = np.arange(len(topic_ranges))
+
+ for model_idx, model_name in enumerate(models):
+ # 统计每个主题在前10个结果中的出现次数
+ topic_counts = {topic: 0 for topic in topic_ranges.keys()}
+
+ for query_idx in group:
+ query_key = f"query_{query_idx+1}"
+ top10 = results[model_name]['ranked_indices'][query_key][:10]
+
+ for idx in top10:
+ for topic, (start, end) in topic_ranges.items():
+ if start <= idx < end:
+ topic_counts[topic] += 1
+
+ # 绘制主题分布柱状图
+ plt.bar(bar_positions + (model_idx * bar_width),
+ list(topic_counts.values()),
+ bar_width,
+ label=model_name)
+
+ plt.title(f"查询组 {group_idx+1}: {', '.join([query_texts[i] for i in group[:1]])}")
+ plt.xticks(bar_positions + bar_width/2, list(topic_ranges.keys()))
+ plt.ylabel('前10结果中的出现次数')
+ plt.legend()
+
+ plt.tight_layout()
+ plt.savefig('topic_distribution.png')
+ print("已保存主题分布图表到 'topic_distribution.png'")
+
+ # 6. 可视化查询与相关文档的相似度热图
+ plt.figure(figsize=(15, 12))
+
+ for i, model_name in enumerate(models):
+ plt.subplot(2, 1, i+1)
+
+ # 获取相似度矩阵(负数越小表示越相似)
+ sim_matrix = results[model_name]['similarity_scores']
+
+ # 将负值转换为正值以便可视化(越大表示越相似)
+ sim_matrix_viz = -sim_matrix
+
+ # 绘制热图
+ sns.heatmap(sim_matrix_viz, cmap='YlGnBu',
+ xticklabels=[f"Doc{i}" for i in range(len(texts))],
+ yticklabels=[f"Q{i+1}" for i in range(len(query_texts))],
+ cbar_kws={'label': '相似度(越高越相似)'})
+
+ plt.title(f"{model_name} 相似度热图")
+ plt.xlabel('文档ID')
+ plt.ylabel('查询ID')
+
+ plt.tight_layout()
+ plt.savefig('similarity_heatmap.png')
+ print("已保存相似度热图到 'similarity_heatmap.png'")
+
+if __name__ == "__main__":
+ print("开始比较嵌入模型...")
+ results = compare_embeddings()
+ analyze_results(results)
+ print("\n比较完成!")
\ No newline at end of file
diff --git a/research/utils/evaluate_results.py b/research/utils/evaluate_results.py
new file mode 100644
index 0000000..6074e75
--- /dev/null
+++ b/research/utils/evaluate_results.py
@@ -0,0 +1,444 @@
+# Filename: evaluate_results_xai_line_sync.py
+import openai
+import json
+import os
+import time
+from dotenv import load_dotenv
+from tqdm import tqdm
+from collections import defaultdict
+import concurrent.futures
+from typing import List, Dict, Any, Tuple
+
+# --- Configuration ---
+load_dotenv()
+OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
+if not OPENAI_API_KEY:
+ raise ValueError("Please set the OPENAI_API_KEY in your .env file")
+
+try:
+ client = openai.OpenAI(
+ api_key=OPENAI_API_KEY,
+ )
+except ImportError:
+ print("Please install the latest OpenAI library: pip install --upgrade openai")
+ exit()
+except openai.AuthenticationError:
+ print("OpenAI library reported an AuthenticationError. Ensure OPENAI_API_KEY is correct.")
+ exit()
+
+LLM_MODEL = "gpt-3.5-turbo" # Using OpenAI's standard model
+MAX_RETRIES = 5
+INITIAL_RETRY_DELAY_SECONDS = 5
+REQUEST_TIMEOUT_SECONDS = 90
+MAX_WORKERS = 10 # Number of parallel workers
+
+# --- File Paths (Adjust as needed) ---
+# User provided paths
+QUERIES_FILE_PATH = "/opt/dlami/nvme/scaling_out/examples/enron_eval_retrieval.jsonl"
+RAW_PASSAGES_FILE_PATH = "/opt/dlami/nvme/scaling_out/passages/enron_emails/1-shards/raw_passages-0-of-1.jsonl"
+RESULTS_FILE_PATH = "search_results_top10_bm25.jsonl" # This file's Nth line corresponds to QUERIES_FILE_PATH's Nth line
+OUTPUT_EVALUATION_FILE = "llm_containment_evaluations_xai_line_sync.jsonl"
+
+# --- LLM Prompt Definitions for Containment (Same as before) ---
+CONTAINMENT_SYSTEM_PROMPT = """You are an AI evaluator. Your task is to determine if the core information presented in the 'Retrieved Passage' is directly contained within *any* of the text snippets provided in the 'Ground Truth Email Snippets' list."""
+CONTAINMENT_USER_TEMPLATE = """Retrieved Passage:
+"{retrieved_passage_text}"
+
+---
+Ground Truth Email Snippets (Parts of the correct source email):
+{ground_truth_snippets_formatted_list}
+---
+
+Is the core information of the 'Retrieved Passage' directly present or fully contained within *any* of the 'Ground Truth Email Snippets' listed above?
+- Focus on whether the specific facts or statements in the 'Retrieved Passage' can be found within the ground truth snippets.
+- Ignore minor formatting differences. If the retrieved passage is a direct quote or a very close paraphrase of content within the ground truth snippets, answer YES.
+- Respond YES if the Retrieved Passage's content is clearly represented in one or more of the ground truth snippets.
+- Respond NO if the Retrieved Passage's content is not found, is contradictory, or introduces significant information not present in the ground truth snippets.
+
+Your response must be a single word: YES or NO.
+"""
+
+# --- Data Loading Functions ---
+
+def load_queries_as_list(file_path):
+ """
+ Loads queries from a jsonl file into a list, preserving order.
+ Each item in the list is a dict containing original_id, query_text, and ground_truth_message_ids.
+ """
+ queries_list = []
+ try:
+ with open(file_path, 'r', encoding='utf-8') as f:
+ for line_num, line in enumerate(f):
+ try:
+ data = json.loads(line)
+ required_keys = ["id", "query", "ground_truth_message_ids"]
+ if not all(key in data for key in required_keys):
+ print(f"Warning: Skipping line {line_num + 1} in query file due to missing keys: {line.strip()}")
+ continue
+ if not isinstance(data["ground_truth_message_ids"], list):
+ print(f"Warning: 'ground_truth_message_ids' is not a list in line {line_num + 1}. Skipping: {line.strip()}")
+ continue
+ queries_list.append({
+ "original_id": data["id"], # Store the original ID from the file
+ "query_text": data["query"],
+ "ground_truth_message_ids": data["ground_truth_message_ids"]
+ })
+ except json.JSONDecodeError:
+ print(f"Warning: Skipping malformed JSON line {line_num + 1} in query file: {line.strip()}")
+ except FileNotFoundError:
+ print(f"Error: Queries file not found at {file_path}")
+ exit()
+ print(f"Loaded {len(queries_list)} queries (as a list) from {file_path}")
+ return queries_list
+
+def load_all_passages_by_message_id(raw_passages_file_path):
+ """Loads all raw passages into memory, grouped by message_id. (Same as before)"""
+ passages_dict = defaultdict(list)
+ # ... (implementation from previous script, no changes needed here) ...
+ print(f"Loading all raw passages from {raw_passages_file_path} into memory...")
+ try:
+ with open(raw_passages_file_path, 'r', encoding='utf-8') as f:
+ for line_num, line in enumerate(f):
+ try:
+ data = json.loads(line)
+ if "message_id" in data and "text" in data:
+ passages_dict[data["message_id"]].append(data["text"])
+ else:
+ print(f"Warning: Skipping line {line_num+1} in raw passages file due to missing 'message_id' or 'text'.")
+ except json.JSONDecodeError:
+ print(f"Warning: Skipping malformed JSON line {line_num + 1} in raw passages file: {line.strip()}")
+ print(f"Finished loading raw passages. Found {len(passages_dict)} unique message IDs.")
+ except FileNotFoundError:
+ print(f"Error: Raw passages file not found at {raw_passages_file_path}")
+ exit()
+ except MemoryError:
+ print("Error: Ran out of memory loading all raw passages. Consider an indexed approach.")
+ exit()
+ return dict(passages_dict)
+
+def load_search_results_as_list(file_path):
+ """Loads search results from a jsonl file into a list, preserving order."""
+ results_list = []
+ # ... (implementation similar to load_queries_as_list, parsing each line as a dict) ...
+ try:
+ with open(file_path, 'r', encoding='utf-8') as f:
+ for line_num, line in enumerate(f):
+ try:
+ data = json.loads(line)
+ # We expect "query_id" (though not used for matching) and "passages"
+ if "passages" not in data: # query_id might be implicitly by order
+ print(f"Warning: Skipping line {line_num + 1} in search results file due to missing 'passages' key: {line.strip()}")
+ continue
+ results_list.append(data)
+ except json.JSONDecodeError:
+ print(f"Warning: Skipping malformed JSON line {line_num + 1} in search results file: {line.strip()}")
+ except FileNotFoundError:
+ print(f"Error: Search results file not found at {file_path}")
+ exit()
+ print(f"Loaded {len(results_list)} search result sets (as a list) from {file_path}")
+ return results_list
+
+
+def format_ground_truth_snippets(snippet_list):
+ """Formats the list of ground truth snippets for the prompt. (Same as before)"""
+ # ... (implementation from previous script) ...
+ if not snippet_list:
+ return " [No ground truth snippets found for the target message ID(s)]"
+ formatted = []
+ for i, snippet in enumerate(snippet_list):
+ display_snippet = (snippet[:500] + '...') if len(snippet) > 500 else snippet
+ formatted.append(f" {i+1}. {display_snippet}")
+ return "\n".join(formatted)
+
+# --- LLM API Call Function ---
+def get_llm_containment_evaluation(retrieved_passage_text: str, ground_truth_snippets_list: List[str], query_id_for_log: str, passage_identifier_info: str, query_text_for_context: str = "") -> str:
+ """Calls the OpenAI API with retry logic."""
+ formatted_gt_snippets = format_ground_truth_snippets(ground_truth_snippets_list)
+ # max_gt_chars_in_prompt = 5000 # Arbitrary limit, adjust as needed
+ # if len(formatted_gt_snippets) > max_gt_chars_in_prompt:
+ # print(f"Warning: Ground truth snippets for Q_log_id:{query_id_for_log} are too long ({len(formatted_gt_snippets)} chars), truncating for LLM prompt.")
+ # formatted_gt_snippets = formatted_gt_snippets[:max_gt_chars_in_prompt] + "\n [... Snippets Truncated ...]"
+
+ user_prompt = CONTAINMENT_USER_TEMPLATE.format(
+ retrieved_passage_text=retrieved_passage_text,
+ ground_truth_snippets_formatted_list=formatted_gt_snippets
+ )
+ messages = [
+ {"role": "system", "content": CONTAINMENT_SYSTEM_PROMPT},
+ {"role": "user", "content": user_prompt}
+ ]
+
+ current_retry_delay = INITIAL_RETRY_DELAY_SECONDS
+ for attempt in range(MAX_RETRIES):
+ try:
+ response = client.chat.completions.create(
+ model=LLM_MODEL,
+ messages=messages,
+ temperature=0.0,
+ max_tokens=10,
+ timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ answer = response.choices[0].message.content.strip().upper()
+ if answer in ["YES", "NO"]:
+ return answer
+ else:
+ print(f"Warning: Unexpected LLM response content '{answer[:100]}' for Q_log_id:{query_id_for_log} P:{passage_identifier_info}. Defaulting to NO.")
+ return "NO"
+ except openai.APIConnectionError as e:
+ error_message = f"API Connection Error (Attempt {attempt + 1}/{MAX_RETRIES}): {e}"
+ except openai.RateLimitError as e:
+ error_message = f"API Rate Limit Error (Attempt {attempt + 1}/{MAX_RETRIES}): {e}"
+ except openai.APIStatusError as e:
+ error_message = f"API Status Error (Attempt {attempt + 1}/{MAX_RETRIES}): {e.status_code} - {e.response}"
+ if e.status_code == 401:
+ return "ERROR_AUTH"
+ if e.status_code == 500:
+ pass
+ else:
+ return "ERROR_API_CLIENT"
+ except Exception as e:
+ error_message = f"Unexpected error with OpenAI lib (Attempt {attempt + 1}/{MAX_RETRIES}): {type(e).__name__} - {e}"
+
+ print(f"{error_message}. Query Log ID: {query_id_for_log}, Passage: {passage_identifier_info}")
+ if "ERROR_AUTH" in error_message or "ERROR_API_CLIENT" in error_message:
+ break
+
+ if attempt < MAX_RETRIES - 1:
+ print(f"Retrying in {current_retry_delay} seconds...")
+ time.sleep(current_retry_delay)
+ current_retry_delay = min(current_retry_delay * 2, 60)
+ else:
+ print(f"Max retries ({MAX_RETRIES}) reached for Q_log_id:{query_id_for_log} P:{passage_identifier_info}. Skipping.")
+ return "ERROR_MAX_RETRIES"
+ return "ERROR_MAX_RETRIES"
+
+def process_query_passage_pair(args: Tuple[Dict[str, Any], Dict[str, Any], Dict[str, List[str]], set]) -> List[Dict[str, Any]]:
+ """Process a single query-passage pair for parallel execution."""
+ query_info, result_item, passages_lookup, already_evaluated = args
+ evaluations = []
+
+ query_original_id = query_info["original_id"]
+ query_text = query_info["query_text"]
+ target_message_ids = query_info.get("ground_truth_message_ids", [])
+
+ if not target_message_ids:
+ return evaluations
+
+ ground_truth_snippets = []
+ for msg_id_in_query_file in target_message_ids:
+ msg_id_to_lookup = msg_id_in_query_file
+ if msg_id_in_query_file.startswith("<") and msg_id_in_query_file.endswith(">"):
+ msg_id_to_lookup = msg_id_in_query_file[1:-1]
+
+ snippets = passages_lookup.get(msg_id_to_lookup)
+ if snippets:
+ ground_truth_snippets.extend(snippets)
+
+ if not ground_truth_snippets:
+ return evaluations
+
+ retrieved_passages = result_item.get("passages", [])
+ if not retrieved_passages:
+ return evaluations
+
+ for passage_idx, passage_obj in enumerate(retrieved_passages):
+ if not isinstance(passage_obj, dict):
+ print(f"Warning: Invalid passage format for Q_original_id:{query_original_id}, passage index {passage_idx}. Skipping passage.")
+ continue
+
+ retrieved_passage_text = passage_obj.get("text", "").strip()
+ passage_identifier = passage_obj.get("passage_id", passage_obj.get("id", f"retrieved_idx_{passage_idx}"))
+
+ evaluation_key = (query_original_id, passage_identifier)
+ if evaluation_key in already_evaluated:
+ continue
+
+ passage_text_preview = (retrieved_passage_text[:75] + '...') if len(retrieved_passage_text) > 75 else retrieved_passage_text
+
+ if not retrieved_passage_text:
+ evaluation = "NO"
+ else:
+ evaluation = get_llm_containment_evaluation(
+ retrieved_passage_text,
+ ground_truth_snippets,
+ query_original_id,
+ passage_identifier,
+ query_text
+ )
+ if evaluation == "ERROR_AUTH":
+ print("Authentication error with OpenAI API. Stopping script.")
+ return evaluations
+
+ evaluation_record = {
+ "query_original_id": query_original_id,
+ "passage_identifier": passage_identifier,
+ "passage_text_preview": passage_text_preview,
+ "evaluation": evaluation,
+ "model_used": LLM_MODEL,
+ "ground_truth_message_ids_checked": target_message_ids
+ }
+ evaluations.append(evaluation_record)
+
+ return evaluations
+
+# --- Resume Logic ---
+def load_existing_evaluations(output_file):
+ """Loads already evaluated query-passage pairs using 'passage_identifier' and 'query_original_id'. (Same as before, but keying with original_id)"""
+ # ... (implementation from previous script, ensure it uses the correct ID for keys) ...
+ evaluated_pairs = set()
+ if os.path.exists(output_file):
+ print(f"Loading existing containment evaluations from {output_file}...")
+ with open(output_file, 'r', encoding='utf-8') as f:
+ for line_num, line in enumerate(f):
+ try:
+ data = json.loads(line)
+ # Key for resuming should be based on the logged original query ID
+ query_original_id = data.get('query_original_id')
+ passage_identifier = data.get('passage_identifier')
+ if query_original_id is not None and passage_identifier is not None:
+ evaluated_pairs.add((query_original_id, passage_identifier))
+ else:
+ print(f"Warning: Could not identify query_original_id/passage_identifier in existing file line {line_num + 1}.")
+ except json.JSONDecodeError:
+ print(f"Warning: Skipping malformed line {line_num + 1} in existing file: {line.strip()}")
+ except KeyError as e:
+ print(f"Warning: Skipping line {line_num + 1} with missing key '{e}' in existing file: {line.strip()}")
+ print(f"Loaded {len(evaluated_pairs)} existing evaluation records.")
+ else:
+ print(f"No existing evaluation file found at {output_file}. Starting fresh.")
+ return evaluated_pairs
+
+# --- Main Execution Logic ---
+
+def main():
+ """Main function to run the containment evaluation process using parallel processing."""
+ print(f"Starting containment evaluation using OpenAI model: {LLM_MODEL} via OpenAI library interface.")
+
+ # Load data as lists
+ queries_list = load_queries_as_list(QUERIES_FILE_PATH)
+ passages_lookup = load_all_passages_by_message_id(RAW_PASSAGES_FILE_PATH)
+ search_results_list = load_search_results_as_list(RESULTS_FILE_PATH)
+
+ if not queries_list or not search_results_list or not passages_lookup:
+ print("Error loading one or more input files or raw passages. Exiting.")
+ return
+
+ # Determine the number of items to process
+ num_items_to_process = min(len(queries_list), len(search_results_list))
+ print(f"Will process {num_items_to_process} query-result pairs.")
+
+ already_evaluated = load_existing_evaluations(OUTPUT_EVALUATION_FILE)
+
+ try:
+ with open(OUTPUT_EVALUATION_FILE, 'a', encoding='utf-8') as outfile:
+ # Prepare arguments for parallel processing
+ process_args = [
+ (queries_list[i], search_results_list[i], passages_lookup, already_evaluated)
+ for i in range(num_items_to_process)
+ ]
+
+ # Use ThreadPoolExecutor for parallel processing
+ with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
+ # Submit all tasks and get futures
+ futures = [executor.submit(process_query_passage_pair, args) for args in process_args]
+
+ # Process results as they complete
+ for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures), desc="Processing query-result pairs"):
+ try:
+ evaluations = future.result()
+ for evaluation in evaluations:
+ outfile.write(json.dumps(evaluation) + "\n")
+ outfile.flush()
+ # Update already_evaluated set
+ already_evaluated.add((evaluation["query_original_id"], evaluation["passage_identifier"]))
+ except Exception as e:
+ print(f"Error processing query-result pair: {e}")
+
+ except IOError as e:
+ print(f"Error writing to output file {OUTPUT_EVALUATION_FILE}: {e}")
+ return
+ except Exception as e:
+ print(f"An unexpected error occurred during the main processing loop: {e}")
+ return
+
+ print("\n--- Containment Evaluation Script Finished ---")
+
+ # --- Final Summary Calculation ---
+ print(f"Calculating final summary statistics from: {OUTPUT_EVALUATION_FILE}")
+ final_query_containment_found = {}
+ total_evaluated_pairs = 0
+ error_count = 0
+ evaluated_query_original_ids = set()
+
+ try:
+ with open(OUTPUT_EVALUATION_FILE, 'r', encoding='utf-8') as f:
+ for line_num, line in enumerate(f):
+ total_evaluated_pairs += 1
+ try:
+ data = json.loads(line)
+ q_original_id = data['query_original_id']
+ eval_result = data['evaluation']
+ evaluated_query_original_ids.add(q_original_id)
+
+ if eval_result == "YES":
+ final_query_containment_found[q_original_id] = True
+ elif q_original_id not in final_query_containment_found:
+ final_query_containment_found[q_original_id] = False
+ if eval_result not in ["YES", "NO"]:
+ error_count += 1
+ except (json.JSONDecodeError, KeyError) as e:
+ print(f"Error reading line {line_num + 1} during summary: {e} - Line: {line.strip()}")
+ error_count += 1
+
+ num_queries_with_any_contained = sum(1 for contained in final_query_containment_found.values() if contained)
+ total_unique_queries_evaluated = len(evaluated_query_original_ids)
+
+ if total_unique_queries_evaluated > 0:
+ containment_rate_at_10 = num_queries_with_any_contained / total_unique_queries_evaluated
+ print(f"\n--- Final Statistics (Containment Check) ---")
+ print(f"Total unique queries processed (based on output file entries): {total_unique_queries_evaluated}")
+ print(f"Number of queries with at least one contained passage (YES): {num_queries_with_any_contained}")
+ print(f"Containment Match Rate @ Top 10 (Any YES): {containment_rate_at_10:.4f}")
+ print(f"Total query-passage pairs processed (lines in output file): {total_evaluated_pairs}")
+ if error_count > 0:
+ print(f"Number of evaluation errors or non-YES/NO results: {error_count}")
+ else:
+ print("No evaluation results found to summarize.")
+ except FileNotFoundError:
+ print(f"Error: Output file {OUTPUT_EVALUATION_FILE} not found for summary.")
+ except Exception as e:
+ print(f"An unexpected error occurred during summary calculation: {e}")
+
+ print(f"\nDetailed containment evaluations saved to: {OUTPUT_EVALUATION_FILE}")
+
+
+if __name__ == "__main__":
+ # Dummy files for testing the line sync logic
+ if not os.path.exists(QUERIES_FILE_PATH):
+ print(f"Warning: {QUERIES_FILE_PATH} not found. Creating dummy file.")
+ with open(QUERIES_FILE_PATH, 'w', encoding='utf-8') as f:
+ json.dump({"id": "q_alpha", "query": "Query Alpha Text", "ground_truth_message_ids": ["<msg_A>"]}, f); f.write("\n") # Line 0
+ json.dump({"id": "q_beta", "query": "Query Beta Text", "ground_truth_message_ids": ["<msg_B>"]}, f); f.write("\n") # Line 1
+ json.dump({"id": "q_gamma", "query": "Query Gamma Text", "ground_truth_message_ids": ["<msg_C>"]}, f); f.write("\n")# Line 2
+
+ if not os.path.exists(RAW_PASSAGES_FILE_PATH):
+ print(f"Warning: {RAW_PASSAGES_FILE_PATH} not found. Creating dummy file.")
+ with open(RAW_PASSAGES_FILE_PATH, 'w', encoding='utf-8') as f:
+ json.dump({"text": "Content from message A snippet 1.", "id": 100, "message_id": "<msg_A>"}, f); f.write("\n")
+ json.dump({"text": "Content from message A snippet 2.", "id": 101, "message_id": "<msg_A>"}, f); f.write("\n")
+ json.dump({"text": "Content from message B.", "id": 200, "message_id": "<msg_B>"}, f); f.write("\n")
+ json.dump({"text": "Content from message D (unrelated).", "id": 300, "message_id": "<msg_D>"}, f); f.write("\n")
+
+ # RESULTS_FILE_PATH should have results corresponding line-by-line to QUERIES_FILE_PATH
+ if not os.path.exists(RESULTS_FILE_PATH):
+ print(f"Warning: {RESULTS_FILE_PATH} not found. Creating dummy file (2 entries).")
+ with open(RESULTS_FILE_PATH, 'w', encoding='utf-8') as f:
+ # Result for query "q_alpha" (line 0 in queries file)
+ json.dump({"query_id": "this_can_be_ignored_if_line_sync", "passages": [{"id": 101, "text": "Content from message A snippet 2."}, {"id": 300, "text": "Content from message D (unrelated)."}]}, f); f.write("\n")
+ # Result for query "q_beta" (line 1 in queries file)
+ json.dump({"query_id": "this_too", "passages": [{"id": 999, "text": "Some other text."}, {"id": 200, "text": "Content from message B."}]}, f); f.write("\n")
+ # Note: Only 2 result sets, but 3 queries in dummy QUERIES_FILE_PATH.
+ # The script will process min(len(queries_list), len(search_results_list)) if you uncomment that logic,
+ # or just len(search_results_list) as it's currently written for tqdm.
+
+ main()
\ No newline at end of file
diff --git a/research/utils/experiment.md b/research/utils/experiment.md
new file mode 100644
index 0000000..9fe9d96
--- /dev/null
+++ b/research/utils/experiment.md
@@ -0,0 +1,44 @@
+# Recompute Embeddings Saved
+
+```console
+python ./demo/main.py --mode serve --engine sglang --load-indices diskann --port 8082 --domain rpj_wiki --lazy --recompute --dedup --use-partition
+python ./demo/embedding_server.py --domain rpj_wiki
+python ./demo/test_serve.py --port 8082 --nprobe 80 --re --dedup
+```
+
+Result:
+```
+Evaluation Results for nprobe = 80:
+Final Recall Rate: 0.9333
+Average total latency: 2.427s
+Average search time: 2.414s
+```
+
+其中,use-partition也可以不加,也可以跑。不加的效果如下:
+```
+Results for nprobe = 80:
+Final Recall Rate: 0.9333
+Average total latency: 2.434s
+Average search time: 2.421s
+```
+
+# Recompute Embeddings + Loading from disk
+
+Remove `--dedup --use-partition`
+
+```console
+python ./demo/main.py --mode serve --engine sglang --load-indices diskann --port 8082 --domain rpj_wiki --lazy --recompute
+python ./demo/embedding_server.py --domain rpj_wiki
+python ./demo/test_serve.py --port 8082 --nprobe 80 --re
+```
+
+Result:
+```
+Evaluation Results for nprobe = 80:
+Evaluation Results for nprobe = 80:
+Average F1 Score: 0.5708
+Average Exact Match Score: 0.4500
+Average Recall Rate: 0.9333
+Average total latency: 3.709s
+Average search time: 3.696s
+```
diff --git a/research/utils/extract_results.py b/research/utils/extract_results.py
new file mode 100755
index 0000000..a8f23d2
--- /dev/null
+++ b/research/utils/extract_results.py
@@ -0,0 +1,599 @@
+import os
+import math
+import pandas as pd
+import numpy as np
+import re
+import matplotlib.pyplot as plt
+import matplotlib.ticker as ticker
+import json
+import pickle
+import pdb
+
+
+"""
+Automatic result extraction for BM25.
+"""
+
+
+def extract_data_to_table(directory_path):
+ # Regular expression pattern to match the data format in file content
+ content_pattern = (
+ r"# tokens: (\d+(\.\d+)?)\tLM PPL: (\d+(\.\d+)?)\tPPL: (\d+(\.\d+)?)"
+ )
+ # Regular expression pattern to extract info from file names
+ file_name_pattern_M = r"(.+)-(\d+)M-seed_(\d+).txt"
+ file_name_pattern = r"(.+)-(\d+)-seed_(\d+).txt"
+
+ # Data storage
+ data = []
+
+ # Iterating through each file in the directory
+ for file_name in os.listdir(directory_path):
+ # Checking if the file name matches the pattern
+ file_match_M = re.match(file_name_pattern_M, file_name)
+ file_match = re.match(file_name_pattern, file_name)
+ if file_match_M:
+ domain, num_samples, seed = file_match_M.groups()
+
+ # Reading the file and extracting data
+ file_path = os.path.join(directory_path, file_name)
+ with open(file_path, "r") as file:
+ for line in file:
+ # Searching for the pattern in each line
+ content_match = re.search(content_pattern, line)
+ if content_match:
+ # Extracting values
+ tokens, lm_ppl, ppl = (
+ content_match.groups()[0],
+ content_match.groups()[2],
+ content_match.groups()[4],
+ )
+ # Adding the extracted data and extra info to the list
+ data.append(
+ {
+ "Domain": domain,
+ "Samples": int(num_samples) * 1e6,
+ "Seed": int(seed),
+ "#eval_tokens": float(tokens),
+ "LM_PPL": float(lm_ppl),
+ "PPL": float(ppl),
+ }
+ )
+ elif file_match:
+ domain, num_samples, seed = file_match.groups()
+
+ # Reading the file and extracting data
+ file_path = os.path.join(directory_path, file_name)
+ with open(file_path, "r") as file:
+ for line in file:
+ # Searching for the pattern in each line
+ content_match = re.search(content_pattern, line)
+ if content_match:
+ # Extracting values
+ tokens, lm_ppl, ppl = (
+ content_match.groups()[0],
+ content_match.groups()[2],
+ content_match.groups()[4],
+ )
+ # Adding the extracted data and extra info to the list
+ data.append(
+ {
+ "Domain": domain,
+ "Samples": int(num_samples),
+ "Seed": int(seed),
+ "#eval_tokens": float(tokens),
+ "LM_PPL": float(lm_ppl),
+ "PPL": float(ppl),
+ }
+ )
+
+ df = pd.DataFrame(data)
+ grouped_df = df.groupby(["Domain", "Samples", "#eval_tokens"]).mean()
+
+ return df, grouped_df
+
+
+"""
+Automatic resutls extraction for dense retrieval. (new)
+"""
+
+
+def extract_dense_scaling_results(log_files, domain=None, plot=None):
+ # Regular expression pattern to match the key-value pairs in the input string
+ pattern = r"(\w[\w #]+) = ([\w.]+)"
+
+ data_list = []
+ for file in log_files:
+ with open(file, "r") as file:
+ for line in file:
+ # Use re.findall to extract all matches of the pattern
+ matches = re.findall(pattern, line)
+
+ if matches:
+ data_dict = {
+ key.replace(" ", "_").lower(): (
+ None
+ if value == "None"
+ else float(value)
+ if value.replace(".", "", 1).isdigit()
+ else value
+ )
+ for key, value in matches
+ }
+ data_list.append(data_dict)
+
+ df = pd.DataFrame(data_list)
+ if "total_shards" in df.columns:
+ df["subsample_ratio"] = df["sampled_shards"] / df["total_shards"]
+ else:
+ df["subsample_ratio"] = 1 / df["total_shards"]
+ df = df.sort_values(by="subsample_ratio")
+ print(df.head)
+
+ if plot:
+ # Setting the plot size for better visibility
+ plt.figure(figsize=(10, 6))
+
+ # Plotting
+ for concate_k in df["concate_k"].unique():
+ subset = df[df["concate_k"] == concate_k]
+ if concate_k == 0:
+ perplexity_when_concate_k_0 = subset["perplexity"].mean()
+ plt.axhline(
+ y=perplexity_when_concate_k_0,
+ color="r",
+ linestyle="-",
+ label="Closed-book",
+ )
+ else:
+ plt.plot(
+ subset["subsample_ratio"],
+ subset["perplexity"],
+ label=f"Concate_k = {concate_k}",
+ )
+
+ plt.title(f"Perplexity Change with Total Shards -- {domain}")
+ plt.xlabel("Subsample Ratio")
+ plt.ylabel("Perplexity")
+ plt.legend()
+ plt.grid(True)
+ plt.savefig(plot)
+ return df
+
+
+def plot_mmlu():
+ # C4 results
+ labels = [
+ "LM-only",
+ "top-1 w/ 1/32 C4 datastore",
+ "top-1 w/ 2/32 C4 datastore",
+ "top-1 w/ 3/32 C4 datastore",
+ "top-1 w/ 4/32 C4 datastore",
+ "top-1 w/ 5/32 C4 datastore",
+ "top-1 w/ 6/32 C4 datastore",
+ ]
+ x = [0, 1, 2, 3, 4, 5, 6]
+ few_shot_0_concat_1 = [30.69, 32.81, 32.05, 32.55, 32.57, 33.03, 32.88]
+ few_shot_1_concat_1 = [39.67, 41.03, 41.74, 42.1, 42.62, 41.55, 42.09]
+ few_shot_5_concat_1 = [42.47, 43.75, 44.37, 44.1, 44.84, 43.95, 44.49]
+
+ # Plotting the data
+ plt.figure(figsize=(14, 8))
+
+ # Plot for few_shot_0_concat_1
+ plt.plot(
+ x,
+ few_shot_0_concat_1,
+ marker="o",
+ linestyle="-",
+ color="blue",
+ label="Few-shot k=0, Concat k=1",
+ )
+
+ # Plot for few_shot_1_concat_1
+ plt.plot(
+ x,
+ few_shot_1_concat_1,
+ marker="s",
+ linestyle="-",
+ color="red",
+ label="Few-shot k=1, Concat k=1",
+ )
+
+ # Plot for few_shot_5_concat_1
+ plt.plot(
+ x,
+ few_shot_5_concat_1,
+ marker="^",
+ linestyle="-",
+ color="green",
+ label="Few-shot k=5, Concat k=1",
+ )
+
+ # Adding details
+ plt.title("MMLU Performance")
+ plt.xlabel("Retrieval-based LM Datastore Composition")
+ plt.ylabel("Accuracy")
+ plt.xticks(ticks=x, labels=labels, rotation=45, ha="right")
+ plt.legend()
+ plt.tight_layout()
+ plt.grid(True)
+ plt.savefig("mmlu_c4_scaling.png")
+
+
+def extract_lm_eval_results(
+ result_dir, task_name, model_name, n_shot_list, n_doc_list, datastore_name_filter=""
+):
+ markers = ["o", "s", "^", "D", "*", "p", "H", "x"]
+ colors = plt.cm.tab20.colors
+
+ all_data = []
+ for subdir, dirs, files in os.walk(result_dir):
+ num_ints = len(os.path.basename(subdir).split("-"))
+ for file in files:
+ if file.endswith(".jsonl"):
+ file_path = os.path.join(subdir, file)
+ with open(file_path, "r") as f:
+ for line in f:
+ data = json.loads(line)
+ data["SubdirLevel"] = num_ints
+ data["n-shot"], data["n-doc"] = (
+ int(data["n-shot"]),
+ int(data["n-doc"]),
+ )
+ data["Value"] = float(data["Value"])
+ all_data.append(data)
+
+ filtered_data = [
+ d
+ for d in all_data
+ if datastore_name_filter in result_dir
+ and d["n-shot"] in n_shot_list
+ and d["n-doc"] in n_doc_list
+ and d["SubdirLevel"] > 0
+ ]
+
+ plot_data = {}
+ for d in filtered_data:
+ key = (d["n-shot"], d["n-doc"])
+ plot_data.setdefault(key, []).append((d["SubdirLevel"], d["Value"]))
+
+ sorted_keys = sorted(plot_data.keys(), key=lambda x: (x[0], x[1]))
+
+ closed_book_values = {}
+ for i, key in enumerate(sorted_keys):
+ n_shot, n_doc = key
+ if n_doc == 0:
+ value = plot_data[key][-1][-1]
+ closed_book_values.update({n_shot: value})
+
+ plt.figure(figsize=(15, 10))
+ for i, key in enumerate(sorted_keys):
+ n_shot, n_doc = key
+ if n_doc == 0:
+ continue
+ values = plot_data[key]
+ values.append(
+ (0, closed_book_values[n_shot])
+ if n_shot in closed_book_values.keys()
+ else (0, None)
+ )
+ values.sort() # Ensure the values are sorted by SubdirLevel
+ x_values, y_values = zip(*values) # Unzip the tuple pairs to separate lists
+ marker = markers[n_shot] if n_doc else ""
+ color = colors[i % len(colors)] # Choose a color from the colormap
+ label = f"n-shot={n_shot}, n-doc={n_doc}"
+ plt.plot(
+ x_values, y_values, marker=marker, color=color, linestyle="-", label=label
+ )
+
+ # plt.gca().yaxis.set_major_locator(ticker.MaxNLocator(nbins='auto', steps=[1, 2, 5, 10]))
+
+ if subject_name == "mmlu":
+ plot_dir = os.path.join("plots", "mmlu")
+ else:
+ plot_dir = "plots"
+ os.makedirs(plot_dir, exist_ok=True)
+
+ plt.xlabel("Number of Index Shards")
+ plt.ylabel("Accuracy")
+ plt.title(f"{task_name} scaling performance with {model_name}")
+ plt.legend()
+ plt.grid(True)
+ plt.savefig(f"{plot_dir}/{task_name}_{model_name}.png")
+
+ return all_data
+
+
+def plot_mmlu_persub_figures(directory="plots"):
+ files = [
+ file
+ for file in os.listdir(directory)
+ if file.startswith("mmlu_") and file.endswith(".png")
+ ]
+ plots_per_figure = 16
+ for i in range(0, len(files), plots_per_figure):
+ # Create a new figure
+ fig, axs = plt.subplots(4, 4, figsize=(20, 20))
+
+ # Flatten the axis array for easy indexing
+ axs = axs.flatten()
+
+ # Iterate over each subplot in the current figure
+ for ax, file in zip(axs, files[i : i + plots_per_figure]):
+ # Read the image file
+ img = plt.imread(os.path.join(directory, file))
+
+ # Display the image in the subplot
+ ax.imshow(img)
+ ax.set_title(file)
+ ax.axis("off") # Hide axes
+
+ # Adjust layout and display the figure
+ plt.tight_layout()
+ plt.savefig(f"mmlu_persub_{i}.png")
+
+
+def plot_calibration_figures(domain, shard_id=8, show_ci=True, show_all_points=False):
+ if show_all_points:
+ show_ci = False
+
+ data_path = f"out_calibration/{shard_id}_shard_{domain}/calibration_results_decon_rpj_{domain}_None_samples.pkl"
+
+ with open(data_path, "rb") as file:
+ all_results = pickle.load(file)
+
+ all_lm_losses = [item[0] for item in all_results]
+ all_retrieval_scores = [item[1] for item in all_results]
+ print(f"Total {len(all_lm_losses)} examples.")
+
+ # Compute PPL of top-1 doc v.s. golden doc from top-100
+ losses_top1 = [losses[0] for losses in all_lm_losses]
+ avg_losses_top1 = sum(losses_top1) / len(losses_top1)
+ ppl_losses_top1 = math.exp(avg_losses_top1)
+
+ lossed_top100_gold = [min(losses) for losses in all_lm_losses]
+ avg_losses_top100_gold = sum(lossed_top100_gold) / len(lossed_top100_gold)
+ ppl_lossed_top100_gold = math.exp(avg_losses_top100_gold)
+
+ print(
+ f"Top-1 doc PPL: {ppl_losses_top1:.4f}\nGold doc from top-100 PPL: {ppl_lossed_top100_gold:.4f}"
+ )
+
+ # Calibration plot
+ lm_losses = np.array(all_lm_losses)
+ retrieval_scores = np.array(all_retrieval_scores)
+
+ from scipy.special import softmax
+ import scipy.stats as stats
+
+ softmax_lm_losses = softmax(lm_losses, axis=1)
+ softmax_retrieval_scores = softmax(retrieval_scores, axis=1)
+
+ if show_all_points:
+ lm_losses = lm_losses.flatten()
+ retrieval_scores = retrieval_scores.flatten()
+
+ plt.figure(figsize=(8, 6))
+ plt.plot(lm_losses, retrieval_scores, marker="o", linestyle="")
+ plt.title(f"Calibration Curve with {shard_id} Shards")
+ plt.xlabel("LM Losses")
+ plt.ylabel("Retrieval Scores")
+ plt.grid(True)
+ plt.savefig(f"out_calibration/calibration_all_{shard_id}_shard_{domain}.png")
+
+ elif show_ci:
+ lm_losses_mean = np.mean(lm_losses, axis=0)
+ retrieval_scores_mean = np.mean(retrieval_scores, axis=0)
+
+ lm_losses_sem = stats.sem(lm_losses, axis=0)
+ retrieval_scores_sem = stats.sem(retrieval_scores, axis=0)
+
+ # Assuming a 95% confidence interval, z-score is approximately 1.96 for a normal distribution
+ z_score = 1.96
+ losses_ci = lm_losses_sem * z_score
+ retrieval_ci = retrieval_scores_sem * z_score
+
+ plt.figure(figsize=(10, 6))
+ plt.errorbar(
+ lm_losses_mean,
+ retrieval_scores_mean,
+ xerr=losses_ci,
+ yerr=retrieval_ci,
+ fmt="o",
+ ecolor="lightgray",
+ alpha=0.5,
+ capsize=5,
+ )
+ plt.xlabel("LM Losses")
+ plt.ylabel("Retrieval Scores")
+ plt.title(
+ f"Calibration plot for {shard_id}-shard {domain} with Confidence Intervals"
+ )
+ plt.grid(True)
+ plt.savefig(f"out_calibration/calibration_ci_{shard_id}_shard_{domain}.png")
+
+ else:
+ lm_losses = np.mean(lm_losses, axis=0)
+ retrieval_scores = np.mean(retrieval_scores, axis=0)
+
+ plt.figure(figsize=(8, 6))
+ plt.plot(lm_losses, retrieval_scores, marker="o", linestyle="")
+ plt.title(f"Calibration Curve with {shard_id} Shards")
+ plt.xlabel("LM Losses")
+ plt.ylabel("Retrieval Scores")
+ plt.grid(True)
+ plt.savefig(f"out_calibration/calibration_{shard_id}_shard_{domain}.png")
+
+ return ppl_losses_top1, ppl_lossed_top100_gold, all_lm_losses, all_retrieval_scores
+
+
+def plot_top1_vs_best_doc(domain, total_shards=8):
+ lm_only_ppl = {
+ "books": 21.5250,
+ "stackexchange": 11.5948,
+ "wiki": 14.0729,
+ }
+
+ top1_losses, best_losses = [], []
+ for shard_id in range(1, total_shards + 1):
+ top1_loss, best_loss, _, _ = plot_calibration_figures(domain, shard_id)
+ top1_losses.append(top1_loss)
+ best_losses.append(best_loss)
+
+ x = [i for i in range(1, total_shards + 1)]
+ plt.figure(figsize=(10, 6))
+
+ # Plotting
+ if lm_only_ppl[domain]:
+ plt.axhline(
+ y=lm_only_ppl[domain], color="r", linestyle="-", label="Closed-book"
+ )
+
+ plt.plot(x, top1_losses, label=f"Top-1 Doc")
+ plt.plot(x, best_losses, label=f"Gold Doc")
+
+ plt.title(f"Perplexity Change with Total Shards")
+ plt.xlabel("Number of Shards")
+ plt.ylabel("Perplexity")
+ plt.legend()
+ plt.grid(True)
+ plt.savefig(f"best_plot_{domain}.png")
+
+
+def plot_top1_vs_best_doc_per_sample(domain, shard_id, show_top_k=10, special_mark_k=0):
+ _, _, all_lm_losses, all_retrieval_scores = plot_calibration_figures(
+ domain, shard_id
+ )
+ all_sorted_lm_losses, all_sorted_retrieval_scores = [], []
+ for lm_losses, retrieval_scores in zip(all_retrieval_scores, all_lm_losses):
+ sorted_scores, sorted_losses = zip(
+ *sorted(zip(retrieval_scores, lm_losses), reverse=True)
+ )
+ all_sorted_lm_losses.append(sorted_losses)
+ all_sorted_retrieval_scores.append(sorted_scores)
+
+ num_samples = len(all_lm_losses)
+ x = [i for i in range(num_samples)]
+ plt.figure(figsize=(25, 6))
+
+ # Plotting
+ for i in range(show_top_k - 1, -1, -1):
+ plt.plot(
+ x,
+ [losses[i] for losses in all_sorted_lm_losses],
+ label=f"Top-{i + 1}th Doc",
+ marker="x" if i == special_mark_k else "o",
+ linestyle="",
+ )
+
+ plt.title(f"Per-sample Loss of {domain} with 1 retrieved doc")
+ plt.xlabel("Index of the Evaluation Sample")
+ plt.ylabel("Loss")
+ plt.legend(loc="upper left", bbox_to_anchor=(1, 1))
+ plt.grid(True)
+ plt.savefig(f"per_sample_{domain}.png")
+
+
+def compute_variance_across_hards(path, n_shot=5, n_doc=3):
+ all_data = []
+ for subdir, dirs, files in os.walk(path):
+ num_ints = len(os.path.basename(subdir).split("-"))
+ for file in files:
+ if file.endswith(".jsonl"):
+ file_path = os.path.join(subdir, file)
+ with open(file_path, "r") as f:
+ for line in f:
+ data = json.loads(line)
+ data["SubdirLevel"] = num_ints
+ data["n-shot"], data["n-doc"] = (
+ int(data["n-shot"]),
+ int(data["n-doc"]),
+ )
+ data["Value"] = float(data["Value"])
+ all_data.append(data)
+
+ plot_data = {}
+ for d in all_data:
+ key = (d["n-shot"], d["n-doc"])
+ plot_data.setdefault(key, []).append((d["SubdirLevel"], d["Value"]))
+
+ files_end = [d.split("/")[-1] for d, _, _ in os.walk(path)]
+ shard_ids = [int(i) for i in files_end[1:]]
+ key = n_shot, n_doc
+ values = plot_data[key]
+ _, y_values = zip(*values)
+
+ plt.figure(figsize=(10, 6))
+ try:
+ plt.plot(shard_ids, y_values, marker="o", linestyle="")
+ except:
+ print(f"mismatched size for {key}: {len(shard_ids)}, {len(y_values)}")
+
+ print(y_values)
+ print(f"Saving to {f'per_sample_{files_end[0]}.png'}")
+
+ plt.xlabel("Single-shard Index ID")
+ plt.ylabel("PPL")
+ plt.grid(True)
+ plt.savefig(f"per_sample_{files_end[0]}.png")
+
+
+if __name__ == "__main__":
+ # # Replace with your directory path
+ # directory_path = "out/2023_dec_25_single_domain"
+
+ # # Extracting data to a table with additional information
+ # df, grouped_df = extract_data_to_table(directory_path)
+ # print(grouped_df)
+ # print(grouped_df.index.get_level_values("Samples (M)").to_numpy())
+
+ plot_info_list = [
+ # {'logfile': 'rpj_c4.log', 'domain': 'rpj-c4', 'plot': 'scaling_c4_single_index_plot.png'},
+ # {'logfile': 'rpj_arxiv.log', 'domain': 'rpj-arxiv', 'plot': 'scaling_arxiv_plot.png'},
+ # {'logfile': 'rpj_book_scaling.log', 'domain': 'rpj-book', 'plot': 'scaling_book_plot.png'},
+ # {'logfile': 'rpj_github_scaling.log', 'domain': 'rpj-github', 'plot': 'scaling_github_plot.png'},
+ # {'logfile': 'rpj_stackexchange_scaling.log', 'domain': 'rpj-stackexchange', 'plot': 'scaling_stackexchange_plot.png'},
+ # {'logfile': 'rpj_wiki.log', 'domain': 'rpj-wiki', 'plot': 'scaling_wiki_plot.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_wiki_contriever_ppl.log', 'domain': 'rpj-wiki-decon-contriever', 'plot': 'scaling_wiki_decon_plot_contriever.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_book_contriever_ppl.log', 'domain': 'rpj-book-decon-contriever', 'plot': 'scaling_book_decon_plot_contriever.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_arxiv_contriever_ppl.log', 'domain': 'rpj-arxiv-decon-contriever', 'plot': 'scaling_arxiv_decon_plot_contriever.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_stackexchange_contriever_ppl.log', 'domain': 'rpj-stackexchange-decon-contriever', 'plot': 'scaling_stackexchange_decon_plot_contriever.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_stackexchange_dragon_ppl.log', 'domain': 'rpj-stackexchange-decon-dragon', 'plot': 'scaling_stackexchange_decon_plot_dragon.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_wiki_dragon_ppl.log', 'domain': 'rpj-wiki-decon-dragon', 'plot': 'scaling_wiki_decon_plot_dragon.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_arxiv_dragon_ppl.log', 'domain': 'rpj-arxiv-decon-dragon', 'plot': 'scaling_arxiv_decon_plot_dragon.png'},
+ # {'logfile': 'out/2024_apr_decon/decon_rpj_book_dragon_ppl.log', 'domain': 'rpj-book-decon-dragon', 'plot': 'scaling_book_decon_plot_dragon.png'},
+ ]
+
+ # for plot_info in plot_info_list:
+ # extract_dense_scaling_results([plot_info['logfile']], plot_info['domain'], plot_info['plot'])
+
+ model_name = "lclm"
+ subject_name = "gsm8k"
+ datastore_name = "c4"
+ result_dir = f"/gscratch/zlab/rulins/Scaling/lm_eval_results/{model_name}"
+
+ all_subjects = [
+ file
+ for file in os.listdir(result_dir)
+ if subject_name in file and datastore_name in file
+ ]
+ for subject in all_subjects:
+ file_name = subject
+ print(file_name)
+ extract_lm_eval_results(
+ os.path.join(result_dir, file_name),
+ subject,
+ model_name,
+ [0, 5], # few-shot
+ [0, 3], # n-doc
+ file_name,
+ )
+
+ # plot_mmlu_persub_figures("plots/mmlu")
+
+ # compute_variance_across_hards(f'/gscratch/zlab/rulins/Scaling/lm_eval_results/llama2-7b/subsample/nq_open-rpj_c4-32_shards')
+ # compute_variance_across_hards(f'/gscratch/zlab/rulins/Scaling/lm_eval_results/llama2-7b/subsample/medqa_4options-rpj_c4-32_shards')
+
+ # plot_calibration_figures(domain='wiki', shard_id=1, show_all_points=True)
+ # plot_top1_vs_best_doc_per_sample(domain='stackexchange', shard_id=1, show_top_k=10, special_mark_k=0)
diff --git a/research/utils/faiss.md b/research/utils/faiss.md
new file mode 100644
index 0000000..67eb7a3
--- /dev/null
+++ b/research/utils/faiss.md
@@ -0,0 +1,20 @@
+sudo apt-get install libgflags-dev
+
+uv pip install swig
+
+sudo apt-get update && sudo apt-get install libzmq3-dev libmsgpack-dev pkg-config
+
+/home/ubuntu/Power-RAG/.venv/bin/cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DFAISS_ENABLE_PYTHON=ON -DFAISS_ENABLE_GPU=OFF -DCMAKE_BUILD_TYPE=Debug .
+
+make -C build -j faiss && make -C build -j swigfaiss && uv pip install -e build/faiss/python
+
+
+
+## Some outdated info (may not needeed)
+
+&& cp ./build/faiss/python/_swigfaiss.so /home/andy/Power-RAG/.venv/lib/python3.10/site-packages/faiss-1.10.0-py3.10.egg/faiss/
+
+
+export LD_PRELOAD="/lib/x86_64-linux-gnu/libiomp5.so /lib/x86_64-linux-gnu/libmkl_core.so /lib/x86_64-linux-gnu/libmkl_intel_lp64.so /lib/x86_64-linux-gnu/libmkl_intel_thread.so"
+
+set -x LD_PRELOAD "/lib/x86_64-linux-gnu/libiomp5.so /lib/x86_64-linux-gnu/libmkl_core.so /lib/x86_64-linux-gnu/libmkl_intel_lp64.so /lib/x86_64-linux-gnu/libmkl_intel_thread.so"
\ No newline at end of file
diff --git a/research/utils/find_probe.py b/research/utils/find_probe.py
new file mode 100644
index 0000000..189c872
--- /dev/null
+++ b/research/utils/find_probe.py
@@ -0,0 +1,739 @@
+#!/usr/bin/env python3
+import subprocess
+import json
+import re
+import numpy as np
+import matplotlib.pyplot as plt
+from typing import List, Dict, Any, Tuple, Optional
+import os
+import time
+import sys
+import argparse
+import concurrent.futures
+import signal
+import psutil
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--path-suffix", type=str, default="", help="Path suffix for the index")
+parser.add_argument("--pq-compressed", type=int, default=None)
+parser.add_argument("--beam-width", type=int, default=2, help="DiskANN beam width for search (controls number of IO requests per iteration)")
+parser.add_argument("--index-type", type=str, default="diskann", help="Index type to test (default: diskann)")
+parser.add_argument("--task", type=str, default="nq", help="Task to run (default: nq)")
+parser.add_argument("--max-workers", type=int, default=1, help="Maximum number of concurrent processes")
+parser.add_argument("--timeout", type=int, default=1800, help="Timeout for each process in seconds")
+parser.add_argument("--retry-count", type=int, default=2, help="Number of retries for failed runs")
+parser.add_argument(
+ "--target-recalls",
+ type=float,
+ nargs='+',
+ default=[0.85, 0.90, 0.95],
+ help="Target recalls to achieve (e.g., --target-recalls 0.85 0.90 0.95)"
+)
+args = parser.parse_args()
+path_suffix = args.path_suffix
+
+pq_compressed = args.pq_compressed
+beam_width = args.beam_width
+max_workers = args.max_workers
+timeout = args.timeout
+retry_count = args.retry_count
+
+TARGET_RECALLS = args.target_recalls
+
+task = args.task
+
+# Process management
+running_processes = {} # PID -> Process object
+
+# Based on previous data, search around these values
+if args.index_type == "diskann":
+ if task == "nq":
+ if pq_compressed is None:
+ NPROBE_RANGES = {
+ 0.85: range(10, 50),
+ 0.90: range(62, 67), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(190, 195) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif pq_compressed == 10:
+ NPROBE_RANGES = {
+ 0.85: range(10, 70),
+ 0.90: range(90, 127), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(200, 384) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif pq_compressed == 20:
+ NPROBE_RANGES = {
+ 0.85: range(10, 50),
+ 0.90: range(64, 128), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(188, 192) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif pq_compressed == 5:
+ NPROBE_RANGES = {
+ 0.85: range(10, 500),
+ 0.90: range(768, 2000), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(3000, 4096) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif task == "trivia":
+ if pq_compressed is None:
+ NPROBE_RANGES = {
+ 0.85: range(90, 150),
+ 0.90: range(150, 200), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(200, 300) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif task == "gpqa":
+ if pq_compressed is None:
+ NPROBE_RANGES = {
+ 0.85: range(1, 30),
+ 0.90: range(1, 30), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(1, 30) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif task == "hotpot":
+ if pq_compressed is None:
+ NPROBE_RANGES = {
+ 0.85: range(19, 160),
+ 0.90: range(120, 210), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(1000, 1200) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+elif args.index_type == "ivf_disk":
+ if task == "nq":
+ assert pq_compressed is None
+ NPROBE_RANGES = {
+ 0.85: range(13, 16),
+ 0.90: range(30,40),
+ 0.95: range(191, 194)
+ }
+ elif task == "trivia":
+ assert pq_compressed is None
+ NPROBE_RANGES = {
+ 0.85: range(13, 50),
+ 0.90: range(30, 100),
+ 0.95: range(100, 400)
+ }
+ elif task == "gpqa":
+ assert pq_compressed is None
+ NPROBE_RANGES = {
+ 0.85: range(1, 30),
+ 0.90: range(1, 30), # Narrow range around 64 (63, 64, 65, 66)
+ 0.95: range(1, 30) # Narrow range around 192 (190, 191, 192, 193, 194)
+ }
+ elif task == "hotpot":
+ NPROBE_RANGES = {
+ 0.85: range(13, 100),
+ 0.90: range(30, 200),
+ 0.95: range(191, 700)
+ }
+elif args.index_type == "hnsw":
+ if task == "nq":
+ NPROBE_RANGES = {
+ 0.85: range(130, 140),
+ 0.90: range(550, 666),
+ 0.95: range(499, 1199),
+ }
+ if task == "gpqa":
+ NPROBE_RANGES = {
+ 0.85: range(40, 70),
+ 0.90: range(60, 100),
+ 0.95: range(200, 500),
+ }
+ elif task == "hotpot":
+ NPROBE_RANGES = {
+ 0.85: range(450, 480),
+ 0.90: range(1000, 1300),
+ 0.95: range(2000, 4000),
+ }
+ elif task == "trivia":
+ NPROBE_RANGES = {
+ 0.85: range(100, 400),
+ 0.90: range(700, 1800),
+ 0.95: range(506, 1432)
+ }
+
+# Create a directory for logs if it doesn't exist
+os.makedirs("nprobe_logs", exist_ok=True)
+
+# Set up signal handling for clean termination
+def signal_handler(sig, frame):
+ print("Received termination signal. Cleaning up running processes...")
+ for pid, process in running_processes.items():
+ try:
+ if process.poll() is None: # Process is still running
+ print(f"Terminating process {pid}...")
+ process.terminate()
+ time.sleep(0.5)
+ if process.poll() is None: # If still running after terminate
+ print(f"Killing process {pid}...")
+ process.kill()
+
+ # Kill any child processes
+ try:
+ parent = psutil.Process(pid)
+ children = parent.children(recursive=True)
+ for child in children:
+ print(f"Killing child process {child.pid}...")
+ child.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+ except:
+ pass
+
+ print("All processes terminated. Exiting.")
+ sys.exit(1)
+
+# Register signal handlers
+signal.signal(signal.SIGINT, signal_handler)
+signal.signal(signal.SIGTERM, signal_handler)
+
+def run_batch_demo(nprobe: int, retry: int = 0) -> Optional[float]:
+ """Run main.py in batch mode with a specific nprobe value and extract the recall."""
+ command = f"python -u ./demo/main.py --search-only --load-indices {args.index_type} --domain rpj_wiki --lazy-load-passages --nprobe {nprobe} --task {task} --skip-passages"
+ if pq_compressed is not None:
+ command += f" --diskann-search-memory-maximum {pq_compressed}"
+ if beam_width is not None:
+ command += f" --diskann-beam-width {beam_width}"
+ if args.index_type == "hnsw":
+ command += f" --hnsw-old"
+ # command += " --embedder intfloat/multilingual-e5-small"
+
+ cmd = [
+ "fish", "-c",
+ # f"set -gx LD_PRELOAD \"/lib/x86_64-linux-gnu/libmkl_core.so /lib/x86_64-linux-gnu/libmkl_intel_lp64.so /lib/x86_64-linux-gnu/libmkl_intel_thread.so /lib/x86_64-linux-gnu/libiomp5.so\" && "
+ "source ./.venv/bin/activate.fish &&"
+ + command
+ ]
+
+ print(f"Running with nprobe={nprobe}, beam_width={beam_width}, retry={retry}/{retry_count}")
+ log_file = f"nprobe_logs/nprobe_{nprobe}_beam{beam_width}_{path_suffix}_retry{retry}.log"
+
+ try:
+ # Also save the command to the log file
+ with open(log_file, "w") as f:
+ f.write(f"Command: {cmd[1]}\n\n")
+ f.write(f"Start time: {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
+ f.write("=== OUTPUT BEGINS ===\n")
+
+ # Run the command and tee the output to both stdout and the log file
+ with open(log_file, "a") as f:
+ process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ bufsize=1 # Line buffered
+ )
+
+ # Register the process for cleanup
+ pid = process.pid
+ running_processes[pid] = process
+
+ # Process output line by line for real-time logging
+ if process.stdout: # Check if stdout is not None
+ # Set a timeout
+ start_time = time.time()
+ current_output = ""
+
+ while process.poll() is None:
+ # Check for timeout
+ if time.time() - start_time > timeout:
+ print(f"Process timeout for nprobe={nprobe}, killing...")
+ f.write("\n\nProcess timed out, killing...\n")
+ process.terminate()
+ time.sleep(0.5)
+ if process.poll() is None:
+ process.kill()
+
+ # Clean up child processes
+ try:
+ parent = psutil.Process(pid)
+ children = parent.children(recursive=True)
+ for child in children:
+ child.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ pass
+
+ if pid in running_processes:
+ del running_processes[pid]
+
+ # Retry if we have attempts left
+ if retry < retry_count:
+ print(f"Retrying nprobe={nprobe}...")
+ return run_batch_demo(nprobe, retry + 1)
+ return None
+
+ # Read output with a small timeout to allow for process checking
+ try:
+ line = process.stdout.readline()
+ if not line:
+ time.sleep(0.1) # Small pause to avoid busy waiting
+ continue
+
+ print(line, end='') # Print to console
+ f.write(line) # Write to log file
+ f.flush() # Make sure it's written immediately
+ except:
+ time.sleep(0.1)
+
+ exit_code = process.wait()
+
+ # Process complete, remove from running list
+ if pid in running_processes:
+ del running_processes[pid]
+
+ f.write(f"\nExit code: {exit_code}\n")
+ f.write(f"End time: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
+
+ # Re-read the log file to extract recall rate
+ with open(log_file, "r") as f:
+ log_content = f.read()
+
+ # Try multiple patterns to find recall rate
+ recall = None
+ patterns = [
+ fr"Avg recall rate for {args.index_type}: ([0-9.]+)",
+ r"recall: ([0-9.]+)",
+ fr"{args.index_type}.*?recall.*?([0-9.]+)",
+ fr"recall.*?{args.index_type}.*?([0-9.]+)"
+ ]
+
+ for pattern in patterns:
+ matches = re.findall(pattern, log_content, re.IGNORECASE)
+ if matches:
+ try:
+ recall = float(matches[-1]) # Take the last one if multiple matches
+ print(f"Found recall rate using pattern: {pattern}")
+ break
+ except ValueError:
+ continue
+
+ if recall is None:
+ print(f"Warning: Could not extract recall rate from output log {log_file}")
+ # Try to find any number that looks like a recall rate (between 0 and 1)
+ possible_recalls = re.findall(r"recall.*?([0-9]+\.[0-9]+)", log_content, re.IGNORECASE)
+ if possible_recalls:
+ try:
+ recall_candidates = [float(r) for r in possible_recalls if 0 <= float(r) <= 1]
+ if recall_candidates:
+ recall = recall_candidates[-1] # Take the last one
+ print(f"Guessed recall rate: {recall} (based on pattern matching)")
+ except ValueError:
+ pass
+
+ if recall is None:
+ # Log this failure with more context
+ with open("nprobe_logs/failed_recalls.log", "a") as f:
+ f.write(f"Failed to extract recall for nprobe={nprobe} at {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
+
+ # Retry if we have attempts left
+ if retry < retry_count:
+ print(f"Retrying nprobe={nprobe} due to failed recall extraction...")
+ return run_batch_demo(nprobe, retry + 1)
+
+ return None
+
+ print(f"nprobe={nprobe}, recall={recall:.4f}")
+ return recall
+
+ except subprocess.TimeoutExpired:
+ print(f"Command timed out for nprobe={nprobe}")
+ with open(log_file, "a") as f:
+ f.write("\n\nCommand timed out after 1800 seconds\n")
+
+ # Retry if we have attempts left
+ if retry < retry_count:
+ print(f"Retrying nprobe={nprobe}...")
+ return run_batch_demo(nprobe, retry + 1)
+
+ return None
+
+ except Exception as e:
+ print(f"Error running command for nprobe={nprobe}: {e}")
+ with open(log_file, "a") as f:
+ f.write(f"\n\nError: {e}\n")
+
+ # Retry if we have attempts left
+ if retry < retry_count:
+ print(f"Retrying nprobe={nprobe} due to error: {e}...")
+ return run_batch_demo(nprobe, retry + 1)
+
+ return None
+
+def batch_run_nprobe_values(nprobe_values):
+ """Run multiple nprobe values in parallel with a thread pool."""
+ results = {}
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
+ future_to_nprobe = {executor.submit(run_batch_demo, nprobe): nprobe for nprobe in nprobe_values}
+
+ for future in concurrent.futures.as_completed(future_to_nprobe):
+ nprobe = future_to_nprobe[future]
+ try:
+ recall = future.result()
+ if recall is not None:
+ results[nprobe] = recall
+ print(f"Completed nprobe={nprobe} with recall={recall:.4f}")
+ except Exception as e:
+ print(f"Error processing nprobe={nprobe}: {e}")
+
+ return results
+
+def adaptive_search_nprobe(target_recall: float, min_nprobe: int, max_nprobe: int, tolerance: float = 0.001) -> Dict:
+ """
+ Use an adaptive search strategy to find the optimal nprobe value for a target recall.
+ Combines binary search with exploration to handle non-linear relationships.
+
+ Args:
+ target_recall: The target recall to achieve
+ min_nprobe: Minimum nprobe value to start search
+ max_nprobe: Maximum nprobe value for search
+ tolerance: How close we need to get to the target_recall
+
+ Returns:
+ Dictionary with the best nprobe, achieved recall, and other metadata
+ """
+ print(f"\nAdaptive searching for nprobe that achieves {target_recall*100:.1f}% recall...")
+ print(f"Search range: {min_nprobe} - {max_nprobe}")
+
+ with open(f"nprobe_logs/summary_{path_suffix}.log", "a") as f:
+ f.write(f"\nAdaptive searching for nprobe that achieves {target_recall*100:.1f}% recall...\n")
+ f.write(f"Search range: {min_nprobe} - {max_nprobe}\n")
+
+ best_result = {"nprobe": None, "recall": None, "difference": float('inf')}
+ all_results = {"nprobe": [], "recall": []}
+
+ # Save initial file for this search
+ search_results_file = f"nprobe_logs/search_results_{path_suffix}_{target_recall:.2f}.json"
+ search_data = {
+ "target": target_recall,
+ "current_best": best_result,
+ "all_results": all_results,
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
+ "search_range": {"min": min_nprobe, "max": max_nprobe}
+ }
+
+ with open(search_results_file, "w") as f:
+ json.dump(search_data, f, indent=2)
+
+ # Start with a strategic sampling to understand the recall curve
+ # Choose more points if the range is large
+ range_size = max_nprobe - min_nprobe
+ if range_size > 500:
+ num_initial_samples = 5
+ elif range_size > 100:
+ num_initial_samples = 4
+ else:
+ num_initial_samples = 3
+
+ sample_points = [min_nprobe]
+ step = range_size // (num_initial_samples - 1)
+ for i in range(1, num_initial_samples - 1):
+ sample_points.append(min_nprobe + i * step)
+ sample_points.append(max_nprobe)
+
+ # Run initial sample points in parallel
+ initial_results = batch_run_nprobe_values(sample_points)
+
+ # Update all_results and best_result based on initial_results
+ for nprobe, recall in initial_results.items():
+ all_results["nprobe"].append(nprobe)
+ all_results["recall"].append(recall)
+
+ diff = abs(recall - target_recall)
+ if diff < best_result["difference"]:
+ best_result = {"nprobe": nprobe, "recall": recall, "difference": diff}
+
+ # Update search results file
+ search_data = {
+ "target": target_recall,
+ "current_best": best_result,
+ "all_results": all_results,
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
+ "search_range": {"min": min_nprobe, "max": max_nprobe}
+ }
+ with open(search_results_file, "w") as f:
+ json.dump(search_data, f, indent=2)
+
+ # Check if we've already reached target within tolerance
+ if best_result["difference"] <= tolerance:
+ print(f"Found good enough nprobe value: {best_result['nprobe']} with recall {best_result['recall']:.4f}")
+ return best_result
+
+ # Analyze initial results to decide on next strategy
+ # Sort results by nprobe
+ sorted_results = sorted([(n, r) for n, r in zip(all_results["nprobe"], all_results["recall"])])
+ nprobes, recalls = zip(*sorted_results)
+
+ # Check if the relationship is monotonic
+ is_monotonic = all(recalls[i] <= recalls[i+1] for i in range(len(recalls)-1)) or \
+ all(recalls[i] >= recalls[i+1] for i in range(len(recalls)-1))
+
+ if is_monotonic:
+ print("Relationship appears monotonic, proceeding with binary search.")
+ # Find the two closest points that bracket the target
+ bracket_low, bracket_high = None, None
+ for i in range(len(recalls)-1):
+ if (recalls[i] <= target_recall <= recalls[i+1]) or (recalls[i] >= target_recall >= recalls[i+1]):
+ bracket_low, bracket_high = nprobes[i], nprobes[i+1]
+ break
+
+ if bracket_low is None:
+ # Target is outside our current range, adjust range
+ if all(r < target_recall for r in recalls):
+ # All recalls are too low, need to increase nprobe
+ bracket_low = nprobes[-1]
+ bracket_high = min(max_nprobe, nprobes[-1] * 2)
+ else:
+ # All recalls are too high, need to decrease nprobe
+ bracket_low = max(min_nprobe, nprobes[0] // 2)
+ bracket_high = nprobes[0]
+
+ # Binary search between bracket_low and bracket_high
+ while abs(bracket_high - bracket_low) > 3:
+ mid_nprobe = (bracket_low + bracket_high) // 2
+ if mid_nprobe in initial_results:
+ mid_recall = initial_results[mid_nprobe]
+ else:
+ mid_recall = run_batch_demo(mid_nprobe)
+ if mid_recall is not None:
+ all_results["nprobe"].append(mid_nprobe)
+ all_results["recall"].append(mid_recall)
+
+ diff = abs(mid_recall - target_recall)
+ if diff < best_result["difference"]:
+ best_result = {"nprobe": mid_nprobe, "recall": mid_recall, "difference": diff}
+
+ # Update search results file
+ search_data["current_best"] = best_result
+ search_data["all_results"] = all_results
+ with open(search_results_file, "w") as f:
+ json.dump(search_data, f, indent=2)
+
+ # Check if we're close enough
+ if mid_recall is not None:
+ if abs(mid_recall - target_recall) <= tolerance:
+ break
+
+ # Adjust brackets
+ if mid_recall < target_recall:
+ bracket_low = mid_nprobe
+ else:
+ bracket_high = mid_nprobe
+ else:
+ # If we failed to get a result, try a different point
+ bracket_high = mid_nprobe - 1
+ else:
+ print("Relationship appears non-monotonic, using adaptive sampling.")
+ # For non-monotonic relationships, we'll use adaptive sampling
+ # First, find the best current point
+ best_idx = recalls.index(min(recalls, key=lambda r: abs(r - target_recall)))
+ best_nprobe = nprobes[best_idx]
+
+ # Try points around the best point with decreasing radius
+ radius = max(50, (max_nprobe - min_nprobe) // 10)
+ min_radius = 3
+
+ while radius >= min_radius:
+ # Try points at current radius around best_nprobe
+ test_points = []
+ lower_bound = max(min_nprobe, best_nprobe - radius)
+ upper_bound = min(max_nprobe, best_nprobe + radius)
+
+ if lower_bound not in initial_results and lower_bound != best_nprobe:
+ test_points.append(lower_bound)
+ if upper_bound not in initial_results and upper_bound != best_nprobe:
+ test_points.append(upper_bound)
+
+ # Add a point in the middle if range is large enough
+ if upper_bound - lower_bound > 2*radius/3 and len(test_points) < max_workers:
+ mid_point = (lower_bound + upper_bound) // 2
+ if mid_point not in initial_results and mid_point != best_nprobe:
+ test_points.append(mid_point)
+
+ # Run tests
+ if test_points:
+ new_results = batch_run_nprobe_values(test_points)
+ initial_results.update(new_results)
+
+ # Update all_results and best_result
+ for nprobe, recall in new_results.items():
+ all_results["nprobe"].append(nprobe)
+ all_results["recall"].append(recall)
+
+ diff = abs(recall - target_recall)
+ if diff < best_result["difference"]:
+ best_result = {"nprobe": nprobe, "recall": recall, "difference": diff}
+ best_nprobe = nprobe # Update the center for next iteration
+
+ # Update search results file
+ search_data["current_best"] = best_result
+ search_data["all_results"] = all_results
+ with open(search_results_file, "w") as f:
+ json.dump(search_data, f, indent=2)
+
+ # Check if we're close enough
+ if best_result["difference"] <= tolerance:
+ break
+
+ # Reduce radius for next iteration
+ radius = max(min_radius, radius // 2)
+
+ # After search, do a final fine-tuning around the best result
+ if best_result["nprobe"] is not None:
+ fine_tune_range = range(max(min_nprobe, best_result["nprobe"] - 2),
+ min(max_nprobe, best_result["nprobe"] + 3))
+
+ fine_tune_points = [n for n in fine_tune_range if n not in all_results["nprobe"]]
+ if fine_tune_points:
+ fine_tune_results = batch_run_nprobe_values(fine_tune_points)
+
+ for nprobe, recall in fine_tune_results.items():
+ all_results["nprobe"].append(nprobe)
+ all_results["recall"].append(recall)
+
+ diff = abs(recall - target_recall)
+ if diff < best_result["difference"]:
+ best_result = {"nprobe": nprobe, "recall": recall, "difference": diff}
+
+ # Final update to search results file
+ search_data["current_best"] = best_result
+ search_data["all_results"] = all_results
+ search_data["search_range"] = {"min": min_nprobe, "max": max_nprobe, "phase": "fine_tune"}
+ with open(search_results_file, "w") as f:
+ json.dump(search_data, f, indent=2)
+
+ return best_result
+
+def find_optimal_nprobe_values():
+ """Find the optimal nprobe values for target recall rates using adaptive search."""
+ # Dictionary to store results for each target recall
+ results = {}
+ # Dictionary to store all nprobe-recall pairs for plotting
+ all_data = {target: {"nprobe": [], "recall": []} for target in TARGET_RECALLS}
+
+ # Create a summary file for all runs
+ with open(f"nprobe_logs/summary_{path_suffix}.log", "w") as f:
+ f.write(f"Find optimal nprobe values - started at {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
+ f.write(f"Target recalls: {TARGET_RECALLS}\n")
+ f.write(f"nprobe ranges: {NPROBE_RANGES}\n\n")
+ f.write(f"Max workers: {max_workers}\n")
+ f.write(f"Timeout per process: {timeout}s\n")
+ f.write(f"Retry count: {retry_count}\n\n")
+
+ for target in TARGET_RECALLS:
+ # Use the existing NPROBE_RANGES to determine min and max values
+ min_nprobe = min(NPROBE_RANGES[target])
+ max_nprobe = max(NPROBE_RANGES[target])
+
+ print(f"\nUsing NPROBE_RANGES for target {target*100:.1f}%: {min_nprobe} to {max_nprobe}")
+
+ # Run adaptive search instead of binary search
+ best_result = adaptive_search_nprobe(
+ target_recall=target,
+ min_nprobe=min_nprobe,
+ max_nprobe=max_nprobe
+ )
+
+ results[target] = best_result
+
+ # Save all tested points to all_data for plotting
+ search_results_file = f"nprobe_logs/search_results_{path_suffix}_{target:.2f}.json"
+ try:
+ with open(search_results_file, "r") as f:
+ search_data = json.load(f)
+ if "all_results" in search_data:
+ all_data[target]["nprobe"] = search_data["all_results"]["nprobe"]
+ all_data[target]["recall"] = search_data["all_results"]["recall"]
+ except (FileNotFoundError, json.JSONDecodeError) as e:
+ print(f"Warning: Could not load search results for {target}: {e}")
+
+ print(f"For target recall {target*100:.1f}%:")
+ print(f" Best nprobe value: {best_result['nprobe']}")
+ print(f" Achieved recall: {best_result['recall']:.4f}")
+ print(f" Difference: {best_result['difference']:.4f}")
+
+ with open(f"nprobe_logs/summary_{path_suffix}.log", "a") as f:
+ f.write(f"For target recall {target*100:.1f}%:\n")
+ f.write(f" Best nprobe value: {best_result['nprobe']}\n")
+ f.write(f" Achieved recall: {best_result['recall']:.4f}\n")
+ f.write(f" Difference: {best_result['difference']:.4f}\n")
+
+ # Plot the results if we have data
+ if all_data and any(data["nprobe"] for data in all_data.values()):
+ plt.figure(figsize=(10, 6))
+
+ # Plot each target's data
+ for target in TARGET_RECALLS:
+ if not all_data[target]["nprobe"]:
+ continue
+
+ nprobe_values = all_data[target]["nprobe"]
+ recall_values = all_data[target]["recall"]
+
+ # Sort data points for better visualization
+ sorted_points = sorted(zip(nprobe_values, recall_values))
+ sorted_nprobe, sorted_recall = zip(*sorted_points) if sorted_points else ([], [])
+
+ plt.plot(sorted_nprobe, sorted_recall, 'o-',
+ label=f"Target {target*100:.1f}%, Best={results[target]['nprobe']}")
+
+ # Mark the optimal point
+ opt_nprobe = results[target]["nprobe"]
+ opt_recall = results[target]["recall"]
+ plt.plot(opt_nprobe, opt_recall, 'r*', markersize=15)
+
+ # Add a horizontal line at the target recall
+ plt.axhline(y=target, color='gray', linestyle='--', alpha=0.5)
+
+ plt.xlabel('nprobe value')
+ plt.ylabel('Recall rate')
+ plt.title(f'Recall Rate vs nprobe Value (Max Workers: {max_workers})')
+ plt.grid(True)
+ plt.legend()
+ plt.savefig(f'nprobe_logs/nprobe_vs_recall_{path_suffix}.png')
+ print(f"Plot saved to nprobe_logs/nprobe_vs_recall_{path_suffix}.png")
+ else:
+ print("No data to plot.")
+ with open(f"nprobe_logs/summary_{path_suffix}.log", "a") as f:
+ f.write("No data to plot.\n")
+
+ # Save final results
+ with open(f"nprobe_logs/optimal_nprobe_values_{path_suffix}.json", "w") as f:
+ json.dump(results, f, indent=2)
+
+ with open(f"nprobe_logs/summary_{path_suffix}.log", "a") as f:
+ f.write(f"\nFind optimal nprobe values - finished at {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
+ if results:
+ f.write("\nOptimal nprobe values for target recall rates:\n")
+ for target, data in results.items():
+ f.write(f"{target*100:.1f}% recall: nprobe={data['nprobe']} (actual recall: {data['recall']:.4f})\n")
+ else:
+ f.write("No optimal nprobe values found.\n")
+
+ return results
+
+if __name__ == "__main__":
+ try:
+ results = find_optimal_nprobe_values()
+
+ if not results:
+ print("No optimal nprobe values found.")
+ sys.exit(1)
+
+ print("\nOptimal nprobe values for target recall rates:")
+ for target, data in results.items():
+ print(f"{target*100:.1f}% recall: nprobe={data['nprobe']} (actual recall: {data['recall']:.4f})")
+
+ # Generate the command for running the latency test with the optimal nprobe values
+ optimal_values = [data["nprobe"] for target, data in sorted(results.items())]
+ test_cmd = f"source ./.venv/bin/activate.fish && cd ~ && python ./Power-RAG/demo/test_serve.py --nprobe_values {' '.join(map(str, optimal_values))}"
+
+ print("\nRun this command to test latency with the optimal nprobe values:")
+ print(test_cmd)
+
+ except KeyboardInterrupt:
+ print("\nScript interrupted by user. Cleaning up running processes...")
+ signal_handler(signal.SIGINT, None)
+ sys.exit(1)
+ except Exception as e:
+ # Clean up any running processes before re-raising
+ import traceback
+ traceback.print_exc()
+ signal_handler(signal.SIGINT, None)
+ raise e
\ No newline at end of file
diff --git a/research/utils/generate_dataset_cache.fish b/research/utils/generate_dataset_cache.fish
new file mode 100644
index 0000000..b63ee00
--- /dev/null
+++ b/research/utils/generate_dataset_cache.fish
@@ -0,0 +1,60 @@
+#!/usr/bin/env fish
+
+# Set default parameters
+set domain "rpj_wiki"
+set embedder "facebook/contriever-msmarco"
+set k 5
+set tasks "nq" "trivia" "hotpot" "gpqa"
+
+# Parse command line arguments
+for i in (seq 1 (count $argv))
+ switch $argv[$i]
+ case "--domain"
+ set domain $argv[(math $i + 1)]
+ case "--embedder"
+ set embedder $argv[(math $i + 1)]
+ case "--k"
+ set k $argv[(math $i + 1)]
+ case "--tasks"
+ set j (math $i + 1)
+ set tasks
+ while test $j -le (count $argv) && not string match -q -- "--*" $argv[$j]
+ set -a tasks $argv[$j]
+ set j (math $j + 1)
+ end
+ end
+end
+
+echo "Running with the following parameters:"
+echo "Domain: $domain"
+echo "Embedder: $embedder"
+echo "k: $k"
+echo "Datasets: $tasks"
+
+# Create directory for results
+set results_dir "retrieval_results"
+mkdir -p $results_dir
+
+# Process each dataset using retrieval_demo directly
+for task in $tasks
+ echo ""
+ echo "===== Processing dataset: $task ====="
+
+ # Step 1: Run retrieval_demo with flat index to generate cache and get results
+ echo "Running retrieval for $task..."
+ echo "python demo/main.py --domain $domain --task $task --search --load flat --lazy"
+ python demo/main.py --domain $domain --task $task --search --load flat --lazy
+
+ # Check if successful
+ if test $status -ne 0
+ echo "Retrieval for $task failed"
+ continue
+ end
+
+ echo "Completed processing for $task"
+ echo "--------------------------------"
+end
+
+echo "All operations completed successfully!"
+echo "The cache files have been created at the locations specified by get_flat_cache_path() in config.py"
+echo "You can now use test_all_datasets.py to view the results"
diff --git a/research/utils/mem_monitor.fish b/research/utils/mem_monitor.fish
new file mode 100644
index 0000000..b17702a
--- /dev/null
+++ b/research/utils/mem_monitor.fish
@@ -0,0 +1,61 @@
+#!/usr/bin/env fish
+
+# 用法: ./mem_monitor.fish <PID> [interval_seconds=5]
+# 比如: ./mem_monitor.fish 110303 5
+# 会在当前目录写一个 mem_usage_110303.log,每隔5秒记录一次RSS和VSZ(单位MB)。
+
+function usage
+ echo "用法: mem_monitor.fish <PID> [interval_seconds=5]"
+ exit 1
+end
+
+if test (count $argv) -lt 1
+ usage
+end
+
+set pid $argv[1]
+set interval 5
+if test (count $argv) -gt 1
+ set interval $argv[2]
+end
+
+# 输出到 mem_usage_<pid>.log
+set logfile mem_usage_$pid.log
+echo "写入日志: $logfile"
+echo "timestamp,rss_MB,vms_MB" > $logfile
+
+# 轮询检查
+while true
+ # 获取 RSS/VSZ (KB) 值
+ # 兼容 macOS 的 ps 命令,不使用 Linux 特有的选项
+ set proc_line (ps -p $pid -o rss,vsz | tail -n +2 2>/dev/null)
+
+ # 若取不到(进程已退出),则停止
+ if test -z "$proc_line"
+ echo "进程 $pid 已退出或不存在."
+ exit 0
+ end
+
+ # 将单行字符串通过空格拆分为数组,如 ("79673856" "95904664")
+ set arr (string split ' ' (string trim $proc_line))
+ if test (count $arr) -lt 2
+ echo "解析 ps 输出时出现意外: $proc_line"
+ exit 1
+ end
+
+ # 分别赋值
+ set rss_kb $arr[1]
+ set vsz_kb $arr[2]
+
+ # 时间戳
+ set t (date "+%Y-%m-%d %H:%M:%S")
+
+ # 转换成 MB
+ set rss_MB (math "$rss_kb / 1024.0")
+ set vsz_MB (math "$vsz_kb / 1024.0")
+
+ # 写日志
+ echo "$t,$rss_MB,$vsz_MB" >> $logfile
+
+ sleep $interval
+end
diff --git a/research/utils/modelfile.fish b/research/utils/modelfile.fish
new file mode 100644
index 0000000..ba734ab
--- /dev/null
+++ b/research/utils/modelfile.fish
@@ -0,0 +1,76 @@
+#!/usr/bin/env fish
+
+# 创建无chat template的纯llama模型,对齐sglang的generate行为
+# 支持llama3.2的1b和3b型号,以及llama3.1的8b型号
+
+function create_llama32_model
+ set model_size $argv[1]
+ set model_name "llama3.2:$model_size-pure"
+
+ echo "创建 $model_name 模型..."
+
+ # 创建临时Modelfile
+ echo "FROM llama3.2:$model_size
+TEMPLATE \"\"
+PARAMETER stop \"\"
+PARAMETER stop \"<|start_header_id|>\"
+PARAMETER stop \"<|end_header_id|>\"
+PARAMETER stop \"<|eot_id|>\"
+PARAMETER stop \"USER:\"
+PARAMETER stop \"ASSISTANT:\"
+PARAMETER temperature 1.0
+PARAMETER num_ctx 4096
+PARAMETER seed 1234
+PARAMETER num_predict 100" > Modelfile
+
+ # 创建模型
+ ollama create $model_name -f ./Modelfile
+
+ # 清理临时文件
+ rm Modelfile
+
+ echo "$model_name 创建完成"
+end
+
+function create_llama31_model
+ set model_size $argv[1]
+ set model_name "llama3.1:$model_size-pure"
+
+ echo "创建 $model_name 模型..."
+
+ # 创建临时Modelfile
+ echo "FROM llama3.1:$model_size
+TEMPLATE \"\"
+PARAMETER stop \"\"
+PARAMETER stop \"<|start_header_id|>\"
+PARAMETER stop \"<|end_header_id|>\"
+PARAMETER stop \"<|eot_id|>\"
+PARAMETER stop \"USER:\"
+PARAMETER stop \"ASSISTANT:\"
+PARAMETER temperature 1.0
+PARAMETER num_ctx 4096
+PARAMETER seed 1234
+PARAMETER num_predict 100" > Modelfile
+
+ # 创建模型
+ ollama create $model_name -f ./Modelfile
+
+ # 清理临时文件
+ rm Modelfile
+
+ echo "$model_name 创建完成"
+end
+
+# 创建Llama 3.2的1b和3b模型
+for size in 1b 3b
+ create_llama32_model $size
+end
+
+# 创建Llama 3.1的8b模型
+create_llama31_model 8b
+
+echo "完成! 所有纯文本llama模型已创建"
+echo "使用方法: "
+echo "- ollama run llama3.2:1b-pure \"你的提示\""
+echo "- ollama run llama3.2:3b-pure \"你的提示\""
+echo "- ollama run llama3.1:8b-pure \"你的提示\""
\ No newline at end of file
diff --git a/research/utils/parse_logs_draw_skip_reorder.py b/research/utils/parse_logs_draw_skip_reorder.py
new file mode 100644
index 0000000..522b5aa
--- /dev/null
+++ b/research/utils/parse_logs_draw_skip_reorder.py
@@ -0,0 +1,193 @@
+import argparse
+import re
+import matplotlib.pyplot as plt
+import os
+
+
+def parse_log(log_file_path):
+ """
+ Parses the log file to extract relevant data for accuracy-recall curve comparison.
+ Args:
+ log_file_path (str): Path to the log file to parse.
+ Returns:
+ dict: A dictionary containing extracted results.
+ """
+ data = {
+ "recalls_with_skip": [],
+ "f1_scores_with_skip": [],
+ "exact_match_scores_with_skip": [],
+ "recalls_without_skip": [],
+ "f1_scores_without_skip": [],
+ "exact_match_scores_without_skip": [],
+ "nprobe_values": [],
+ }
+
+ with open(log_file_path, "r") as file:
+ logs = file.readlines()
+
+ # Variables to track the state during parsing
+ is_skip_reorder_true = False
+ is_skip_reorder_false = False
+ current_nprobe = None
+
+ for line in logs:
+ # Debug: print the current line being processed
+ # print(f"Processing line: {line.strip()}")
+
+ # Check for skip_reorder flag
+ if "skip_search_reorder=True" in line:
+ is_skip_reorder_true = True
+ is_skip_reorder_false = False
+ elif "skip_search_reorder=False" in line:
+ is_skip_reorder_true = False
+ is_skip_reorder_false = True
+
+ # Extract nprobe values (assuming they are given before the experiment)
+ nprobe_match = re.search(r"nprobe=(\d+)", line)
+ if nprobe_match:
+ current_nprobe = int(nprobe_match.group(1))
+ if current_nprobe not in data["nprobe_values"]:
+ data["nprobe_values"].append(current_nprobe)
+ print(f"Found nprobe value: {current_nprobe}")
+
+ # Extract average recall rate
+ avg_recall_match = re.search(
+ r"Avg recall rate for (flat|diskann): ([0-9\.e\-]+)", line
+ )
+ if avg_recall_match:
+ recall_value = float(avg_recall_match.group(2))
+ print(
+ f"Found avg recall rate: {recall_value} for {avg_recall_match.group(1)} in line {line!r}"
+ )
+
+ if "flat" in avg_recall_match.group(1):
+ # data["recalls_without_skip"].append(recall_value)
+ pass
+ elif "diskann" in avg_recall_match.group(1):
+ if is_skip_reorder_true:
+ data["recalls_with_skip"].append(recall_value)
+ elif is_skip_reorder_false:
+ data["recalls_without_skip"].append(recall_value)
+
+ # Extract exact_match, f1, and recall scores from evaluation results
+ eval_match = re.search(
+ r"\{'exact_match': ([0-9\.]+), 'exact_match_stderr': [0-9\.]+, 'f1': ([0-9\.]+), 'f1_stderr': [0-9\.]+",
+ line,
+ )
+ if eval_match:
+ exact_match = float(eval_match.group(1))
+ f1 = float(eval_match.group(2))
+
+ print(f"Found evaluation results -> Exact Match: {exact_match}, F1: {f1}")
+
+ # Add to appropriate list based on skip_reorder flag
+ if is_skip_reorder_true:
+ data["exact_match_scores_with_skip"].append(exact_match)
+ data["f1_scores_with_skip"].append(f1)
+ elif is_skip_reorder_false:
+ data["exact_match_scores_without_skip"].append(exact_match)
+ data["f1_scores_without_skip"].append(f1)
+
+ return data
+
+
+def plot_skip_reorder_comparison(data, output_dir):
+ """
+ 绘制带有和不带 skip_reorder 参数的准确率-召回率曲线。
+
+ Args:
+ data: The parsed data including recalls, f1 scores, and exact match scores.
+ output_dir: Path where the plot will be saved.
+ """
+ recalls_with_skip = data["recalls_with_skip"]
+ f1_scores_with_skip = data["f1_scores_with_skip"]
+ exact_match_scores_with_skip = data["exact_match_scores_with_skip"]
+ recalls_without_skip = data["recalls_without_skip"]
+ f1_scores_without_skip = data["f1_scores_without_skip"]
+ exact_match_scores_without_skip = data["exact_match_scores_without_skip"]
+ nprobe_values = data["nprobe_values"]
+
+ plt.figure(figsize=(10, 6))
+
+ # Check if data lists are not empty and have the same length before plotting
+ if (
+ recalls_with_skip
+ and len(recalls_with_skip) == len(f1_scores_with_skip)
+ and len(recalls_with_skip) == len(exact_match_scores_with_skip)
+ ):
+ plt.plot(
+ recalls_with_skip,
+ f1_scores_with_skip,
+ "bo-",
+ label="F1 Score (with skip_reorder)",
+ markersize=8,
+ linewidth=2,
+ )
+ plt.plot(
+ recalls_with_skip,
+ exact_match_scores_with_skip,
+ "rs-",
+ label="Exact Match (with skip_reorder)",
+ markersize=8,
+ linewidth=2,
+ )
+
+ if (
+ recalls_without_skip
+ and len(recalls_without_skip) == len(f1_scores_without_skip)
+ and len(recalls_without_skip) == len(exact_match_scores_without_skip)
+ ):
+ plt.plot(
+ recalls_without_skip,
+ f1_scores_without_skip,
+ "go-",
+ label="F1 Score (without skip_reorder)",
+ markersize=8,
+ linewidth=2,
+ )
+ plt.plot(
+ recalls_without_skip,
+ exact_match_scores_without_skip,
+ "ms-",
+ label="Exact Match (without skip_reorder)",
+ markersize=8,
+ linewidth=2,
+ )
+
+ plt.xlabel("Recall")
+ plt.ylabel("Score")
+ plt.title("Recall vs Accuracy Comparison")
+ plt.legend()
+ plt.grid(True)
+ plt.xlim(0.0, 1.0)
+
+ # Save the plot only if data is present
+ if len(nprobe_values) > 0:
+ plot_path = os.path.join(
+ output_dir,
+ f"recall_vs_acc_comparison.png",
+ )
+ plt.savefig(plot_path, dpi=300, bbox_inches="tight")
+ print(f"Plot saved to {plot_path}")
+ else:
+ print("No valid data to plot.")
+
+ plt.close()
+
+
+parser = argparse.ArgumentParser(description="Parse log file and plot results")
+parser.add_argument(
+ "log_file_path", type=str, help="Path to the log file"
+)
+parser.add_argument(
+ "--output_dir", type=str, help="Path to the output directory", default="skip_reorder_comparison"
+)
+args = parser.parse_args()
+
+# Parse the log
+parsed_data = parse_log(args.log_file_path)
+
+print(parsed_data)
+
+# Plot the data
+plot_skip_reorder_comparison(parsed_data, args.output_dir)
diff --git a/research/utils/plot_degree_distribution.py b/research/utils/plot_degree_distribution.py
new file mode 100644
index 0000000..9343652
--- /dev/null
+++ b/research/utils/plot_degree_distribution.py
@@ -0,0 +1,114 @@
+import argparse
+import matplotlib.pyplot as plt
+import numpy as np
+import os
+
+def plot_degree_distribution(degree_file_path: str, output_image_path: str):
+ """
+ Reads a file containing node degrees (one per line) and plots the
+ degree distribution as a histogram.
+
+ Args:
+ degree_file_path: Path to the file containing degrees.
+ output_image_path: Path to save the output plot image.
+ """
+ try:
+ # Read degrees from the file
+ degrees = np.loadtxt(degree_file_path, dtype=int)
+ print(f"[LOG] Read {len(degrees)} degrees from {degree_file_path}")
+
+ if len(degrees) == 0:
+ print("[WARN] Degree file is empty. No plot generated.")
+ return
+
+ # Calculate basic statistics
+ min_deg = np.min(degrees)
+ max_deg = np.max(degrees)
+ avg_deg = np.mean(degrees)
+ median_deg = np.median(degrees)
+
+ print(f"[LOG] Degree Stats: Min={min_deg}, Max={max_deg}, Avg={avg_deg:.2f}, Median={median_deg}")
+
+ # Plotting the distribution
+ plt.figure(figsize=(10, 6))
+ # Determine appropriate number of bins, maybe max_deg+1 if not too large
+ # Or use automatic binning like 'auto' or Sturges' rule etc.
+ # Using max_deg - min_deg + 1 bins can be too many if the range is large
+ # Let's try 'auto' binning first
+ n_bins = 'auto'
+ # If max_deg is reasonably small, we can use exact bins
+ if max_deg <= 1000: # Heuristic threshold
+ n_bins = max_deg - min_deg + 1
+
+ counts, bin_edges, patches = plt.hist(degrees, bins=n_bins, edgecolor='black', alpha=0.7)
+ plt.xlabel("Node Degree")
+ plt.ylabel("Number of Nodes")
+ plt.title(f"Degree Distribution (from {os.path.basename(degree_file_path)})")
+ plt.grid(axis='y', linestyle='--', alpha=0.7)
+
+ # Add text for statistics on the plot
+ stats_text = (
+ f"Total Nodes: {len(degrees)}\n"
+ f"Min Degree: {min_deg}\n"
+ f"Max Degree: {max_deg}\n"
+ f"Avg Degree: {avg_deg:.2f}\n"
+ f"Median Degree: {median_deg}"
+ )
+ # Position the text box; adjust as needed
+ plt.text(0.95, 0.95, stats_text, transform=plt.gca().transAxes,
+ fontsize=9, verticalalignment='top', horizontalalignment='right',
+ bbox=dict(boxstyle='round,pad=0.5', fc='wheat', alpha=0.5))
+
+
+ plt.tight_layout()
+ plt.savefig(output_image_path)
+ print(f"[LOG] Degree distribution plot saved to {output_image_path}")
+ # plt.show() # Uncomment if you want to display the plot interactively
+
+ # Create weighted degree distribution plot
+ plt.figure(figsize=(10, 6))
+ # Calculate weighted distribution (degree * number of nodes)
+ unique_degrees, degree_counts = np.unique(degrees, return_counts=True)
+ weighted_counts = unique_degrees * degree_counts
+
+ plt.bar(unique_degrees, weighted_counts, edgecolor='black', alpha=0.7)
+ plt.xlabel("Node Degree")
+ plt.ylabel("Degree × Number of Nodes")
+ plt.title(f"Weighted Degree Distribution (from {os.path.basename(degree_file_path)})")
+ plt.grid(axis='y', linestyle='--', alpha=0.7)
+
+ # Add text for statistics on the plot
+ plt.text(0.95, 0.95, stats_text, transform=plt.gca().transAxes,
+ fontsize=9, verticalalignment='top', horizontalalignment='right',
+ bbox=dict(boxstyle='round,pad=0.5', fc='wheat', alpha=0.5))
+
+ # Generate weighted output filename based on the original output path
+ weighted_output_path = os.path.splitext(output_image_path)[0] + "_weighted" + os.path.splitext(output_image_path)[1]
+
+ plt.tight_layout()
+ plt.savefig(weighted_output_path)
+ print(f"[LOG] Weighted degree distribution plot saved to {weighted_output_path}")
+
+ except FileNotFoundError:
+ print(f"[ERROR] Degree file not found: {degree_file_path}")
+ except Exception as e:
+ print(f"[ERROR] An error occurred: {e}")
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(
+ description="Plot the degree distribution from a file containing node degrees."
+ )
+ parser.add_argument(
+ "degree_file",
+ type=str,
+ help="Path to the input file containing node degrees (one degree per line)."
+ )
+ parser.add_argument(
+ "-o", "--output",
+ type=str,
+ default="degree_distribution.png",
+ help="Path to save the output plot image (default: degree_distribution.png)."
+ )
+ args = parser.parse_args()
+
+ plot_degree_distribution(args.degree_file, args.output)
\ No newline at end of file
diff --git a/research/utils/prepare_query_files.py b/research/utils/prepare_query_files.py
new file mode 100644
index 0000000..d3166e3
--- /dev/null
+++ b/research/utils/prepare_query_files.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python3
+import os
+import json
+import argparse
+import sys
+from pathlib import Path
+from typing import Optional
+
+# Ensure project root is in path for imports
+project_root = Path(__file__).resolve().parent.parent
+sys.path.append(str(project_root))
+
+try:
+ from datasets import load_dataset, Dataset, IterableDataset
+ from tqdm import tqdm
+except ImportError:
+ print("Error: Required libraries 'datasets' or 'tqdm' not found.")
+ print("Please install them using: pip install datasets tqdm")
+ sys.exit(1)
+
+from demo.config import TASK_CONFIGS, get_example_path
+
+# Color constants for output
+RED = "\033[91m"
+GREEN = "\033[92m"
+YELLOW = "\033[93m"
+RESET = "\033[0m"
+
+# --- Dataset Specific Loading Configurations ---
+# You might need to adjust these based on the exact dataset structure on Hugging Face
+DATASET_LOAD_INFO = {
+ "nq": {
+ "hf_name": "nq_open",
+ "split": "validation", # NQ Open doesn't have a standard HF dataset, usually custom splits are used.
+ # This entry assumes a custom formatted source or might need manual creation.
+ # Let's mark it as needing manual setup for now.
+ "query_key": "question",
+ "needs_manual_setup": True,
+ "manual_setup_instructions": "nq_open requires a pre-formatted file. Please ensure it exists at the target path."
+ },
+ "trivia": {
+ "hf_name": "trivia_qa",
+ "subset": "rc.nocontext", # Use rc.nocontext as a valid config
+ "split": "validation",
+ "query_key": "question",
+ "needs_manual_setup": False
+ },
+ "hotpot": {
+ "hf_name": "hotpot_qa",
+ "subset": "distractor", # Explicitly choose the 'distractor' config
+ "split": "validation",
+ "query_key": "question",
+ "needs_manual_setup": False
+ },
+ "gpqa": {
+ "hf_name": "Idavidrein/gpqa", # Corrected HF identifier
+ "subset": "gpqa_main", # Use subset (name) for the configuration
+ "split": "train", # Align with evaluation_demo
+ "query_key": "Question", # CORRECTED: Use uppercase 'Q' as found in the dataset item
+ "needs_manual_setup": False # Assuming this config loads correctly now
+ },
+ "retrievalqa": {
+ "hf_name": "aialt/RetrievalQA",
+ "split": "train",
+ "query_key": "question",
+ "needs_manual_setup": False,
+ "custom_loading": True # Flag to use custom loading logic
+ }
+}
+# --- End Dataset Specific Loading Configurations ---
+
+def format_query(original_query: str) -> str:
+ # """Formats the query string according to the NQ example."""
+ # # Basic check to prevent double formatting if somehow the prefix is already there
+ # if original_query.startswith("Answer these questions:"):
+ # return original_query
+ # return f"Answer these questions:\n\nQ: {original_query}?\nA:"
+ return original_query
+
+def load_retrievalqa():
+ """Custom function to load the RetrievalQA dataset with its complex structure.
+ Downloads the JSONL file directly and processes it line by line to avoid schema issues.
+ """
+ import requests
+ import json
+ import tempfile
+
+ try:
+ print(f"{YELLOW}Attempting to directly download and parse RetrievalQA dataset...{RESET}")
+ url = "https://huggingface.co/datasets/aialt/RetrievalQA/resolve/main/retrievalqa.jsonl"
+
+ # Create a temp file to store the downloaded data
+ with tempfile.NamedTemporaryFile(mode='w+', delete=False) as tmp_file:
+ # Download the file
+ response = requests.get(url, stream=True)
+ response.raise_for_status() # Ensure we got a successful response
+
+ # Process the dataset line by line to avoid schema issues
+ data = []
+ line_count = 0
+
+ for line in response.iter_lines(decode_unicode=True):
+ if line: # Skip empty lines
+ try:
+ item = json.loads(line)
+ # Extract just what we need - the question
+ if "question" in item:
+ data.append({"question": item["question"]})
+ line_count += 1
+ if line_count % 500 == 0:
+ print(f"{YELLOW}Processed {line_count} lines...{RESET}")
+ except json.JSONDecodeError as e:
+ print(f"{RED}Error parsing JSON at line {line_count}: {e}{RESET}")
+ continue
+
+ print(f"{GREEN}Successfully parsed {len(data)} questions from RetrievalQA dataset.{RESET}")
+ return data
+ except Exception as e:
+ print(f"{RED}Custom loading for RetrievalQA failed: {e}{RESET}")
+ raise
+
+def prepare_file(task: str, force_overwrite: bool = False):
+ """Loads, formats, and saves the query file for a specific task."""
+ print(f"--- Processing task: {task} ---")
+
+ if task not in TASK_CONFIGS:
+ print(f"{RED}Error: Task '{task}' not found in TASK_CONFIGS in config.py.{RESET}")
+ return False
+
+ if task not in DATASET_LOAD_INFO:
+ print(f"{RED}Error: Loading configuration for task '{task}' not defined in DATASET_LOAD_INFO.{RESET}")
+ return False
+
+ config = TASK_CONFIGS[task]
+ load_info = DATASET_LOAD_INFO[task]
+ target_path = Path(config.query_path) # Use the path from config.py
+
+ if target_path.exists() and not force_overwrite:
+ print(f"{YELLOW}Target file already exists: {target_path}. Skipping.{RESET}")
+ print(f"Use --force to overwrite.")
+ return True
+
+ # Initialize query_key before the try block uses it in except
+ query_key: Optional[str] = None
+ try:
+ # Use custom loading for retrievalqa
+ if task == "retrievalqa" and load_info.get('custom_loading', False):
+ raw_dataset = load_retrievalqa()
+
+ # Custom handling for retrievalqa data format (list of dicts)
+ print(f"Formatting and saving queries to {target_path}...")
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+
+ count = 0
+ with open(target_path, "w", encoding="utf-8") as f_out:
+ for item in tqdm(raw_dataset, desc=f"Formatting {task}"):
+ if "question" in item:
+ formatted_query = format_query(item["question"])
+ f_out.write(json.dumps({"query": formatted_query}) + "\n")
+ count += 1
+
+ print(f"{GREEN}Successfully generated query file for {task} with {count} queries: {target_path}{RESET}")
+ return True
+ else:
+ print(f"Loading raw dataset: {load_info['hf_name']} (subset: {load_info.get('subset')}, split: {load_info['split']}) ...")
+ raw_dataset = load_dataset(
+ load_info['hf_name'],
+ name=load_info.get('subset'), # Pass the config name via 'name' (subset)
+ split=load_info['split']
+ )
+
+ query_key = load_info['query_key']
+ print(f"Formatting and saving queries to {target_path}...")
+ target_path.parent.mkdir(parents=True, exist_ok=True) # Ensure directory exists
+
+ count = 0
+ with open(target_path, "w", encoding="utf-8") as f_out:
+ for item in tqdm(raw_dataset, desc=f"Formatting {task}"):
+ if not isinstance(item, dict) or query_key not in item:
+ print(f"{YELLOW}Warning: Skipping item due to unexpected format or missing key '{query_key}'. Item: {item}{RESET}")
+ continue
+ original_query = item[query_key]
+ formatted_query = format_query(original_query)
+ f_out.write(json.dumps({"query": formatted_query}) + "\n")
+ count += 1
+
+ print(f"{GREEN}Successfully generated query file for {task} with {count} queries: {target_path}{RESET}")
+ return True
+
+ except Exception as e:
+ print(f"{RED}Error processing task '{task}': {e}{RESET}")
+ key_info = f"query key ('{query_key}')" if query_key else "query key (not assigned)"
+ print(f"Check dataset name ('{load_info['hf_name']}'), subset ('{load_info.get('subset')}'), split ('{load_info['split']}'), and {key_info}.")
+ print(f"Target path was: {target_path}")
+ # Attempt to clean up potentially incomplete file
+ if target_path.exists():
+ try:
+ target_path.unlink()
+ print(f"{YELLOW}Cleaned up potentially incomplete file: {target_path}{RESET}")
+ except OSError as unlink_e:
+ print(f"{RED}Error cleaning up file {target_path}: {unlink_e}{RESET}")
+ return False # Indicate failure
+
+def main():
+ parser = argparse.ArgumentParser(description="Prepare formatted query files for datasets.")
+ parser.add_argument(
+ "--tasks",
+ nargs="+",
+ default=["nq", "trivia", "hotpot", "gpqa", "retrievalqa"],
+ choices=list(TASK_CONFIGS.keys()),
+ help="Which tasks to prepare query files for."
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="Overwrite existing query files."
+ )
+ args = parser.parse_args()
+
+ print(f"Starting query file preparation for tasks: {', '.join(args.tasks)}")
+ if args.force:
+ print(f"{YELLOW}Force overwrite enabled.{RESET}")
+
+ success_count = 0
+ fail_count = 0
+ for task in args.tasks:
+ if prepare_file(task, args.force):
+ success_count += 1
+ else:
+ fail_count += 1
+
+ print("\n--- Preparation Summary ---")
+ print(f"Tasks processed: {len(args.tasks)}")
+ print(f"Successful: {success_count}")
+ print(f"Failed/Skipped due to errors or manual setup needed: {fail_count}")
+ if fail_count > 0:
+ print(f"{RED}Some tasks requires manual intervention or failed. Please check the logs above.{RESET}")
+ sys.exit(1)
+ else:
+ print(f"{GREEN}All specified tasks prepared successfully.{RESET}")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/research/utils/run_bm25.fish b/research/utils/run_bm25.fish
new file mode 100644
index 0000000..0b2d566
--- /dev/null
+++ b/research/utils/run_bm25.fish
@@ -0,0 +1,5 @@
+python demo/main.py --task nq --search --use-original --load bm25 --skip-pa
+
+python demo/main.py --task trivia --search --use-original --load bm25 --skip-pa
+python demo/main.py --task gpqa --search --use-original --load bm25 --skip-pa
+python demo/main.py --task hotpot --search --use-original --load bm25 --skip-pa
diff --git a/research/utils/run_recall_experiment.py b/research/utils/run_recall_experiment.py
new file mode 100644
index 0000000..6cad219
--- /dev/null
+++ b/research/utils/run_recall_experiment.py
@@ -0,0 +1,313 @@
+import subprocess
+import os
+import re
+import time
+from datetime import datetime
+import matplotlib.pyplot as plt
+import pandas as pd
+import argparse
+import numpy as np # Added for sorting unique nprobes
+
+# --- Configuration ---
+PYTHON_EXE = "python" # Or specify the full path if needed
+SCRIPT_TO_RUN = "run_server.py"
+LOG_DIR = "exp_logs" # Directory where run_server.py saves logs/summaries
+RESULTS_DIR = "experiment_results" # Directory to save plot and data
+os.makedirs(RESULTS_DIR, exist_ok=True)
+
+# --- Argument Parsing for Flexibility ---
+parser = argparse.ArgumentParser(description="Run recall experiments or plot results from existing CSV.")
+parser.add_argument('--nprobes', type=str, default="2,4,8,16,32,64", help='Comma-separated list of nprobe values (used when running experiments)')
+parser.add_argument('--degrees', type=str, default="None,30,240", help='Comma-separated list of degree values (use None for default, used when running experiments)')
+parser.add_argument('--task', type=str, default="nq", help='Task argument for run_server.py (used when running experiments, or inferred from --input-csv)')
+parser.add_argument('--input-csv', type=str, default=None, help='Path to an existing CSV file to plot directly, skipping experiments.') # New argument
+args = parser.parse_args()
+
+# --- Initialize Variables ---
+results_df = None
+task_name = args.task # Default task name
+NPROBE_VALUES = []
+DEGREE_VALUES = []
+
+# --- Mode Selection: Run Experiments or Plot from CSV ---
+
+if args.input_csv:
+ # --- Plot from CSV Mode ---
+ print(f"--- Plotting from existing CSV: {args.input_csv} ---")
+ try:
+ results_df = pd.read_csv(args.input_csv)
+ print(f"Loaded data with {len(results_df)} rows.")
+
+ # ---- NEW: Replace 'default' string with 60 if present ----
+ if 'degree' in results_df.columns and results_df['degree'].dtype == 'object': # Check if column exists and might contain strings
+ results_df['degree'] = results_df['degree'].replace('default', 60)
+ # Attempt to convert the column to numeric after replacement
+ results_df['degree'] = pd.to_numeric(results_df['degree'], errors='coerce')
+ print("Replaced 'default' degree values with 60 and converted column to numeric.")
+ # ---- END NEW ----
+
+ # Infer task name from filename if possible
+ match = re.search(r'results_([^_]+)_[\d_]+\.csv', os.path.basename(args.input_csv))
+ if match:
+ task_name = match.group(1)
+ print(f"Inferred task name: {task_name}")
+ else:
+ print(f"Could not infer task name from filename, using default: {task_name}")
+
+ # Get NPROBE_VALUES from loaded data for plotting ticks
+ if 'nprobe' in results_df.columns:
+ NPROBE_VALUES = sorted(results_df['nprobe'].unique())
+ print(f"Nprobe values from data: {NPROBE_VALUES}")
+ else:
+ print("Warning: 'nprobe' column not found in CSV. Plot ticks might be incorrect.")
+
+
+ except FileNotFoundError:
+ print(f"Error: Input CSV file not found: {args.input_csv}")
+ exit(1)
+ except Exception as e:
+ print(f"Error reading CSV file {args.input_csv}: {e}")
+ exit(1)
+
+else:
+ # --- Run Experiments Mode ---
+ print("--- Running New Experiments ---")
+ # Parse nprobe values
+ try:
+ NPROBE_VALUES = [int(p.strip()) for p in args.nprobes.split(',')]
+ except ValueError:
+ print("Error: Invalid nprobe values. Please provide comma-separated integers.")
+ exit(1)
+
+ # Parse degree values
+ DEGREE_VALUES = []
+ for d_str in args.degrees.split(','):
+ d_str = d_str.strip()
+ if d_str.lower() == 'none':
+ DEGREE_VALUES.append(None)
+ else:
+ try:
+ DEGREE_VALUES.append(int(d_str))
+ except ValueError:
+ print(f"Error: Invalid degree value '{d_str}'. Use 'None' or integers.")
+ exit(1)
+
+ print(f"Nprobe values to test: {NPROBE_VALUES}")
+ print(f"Degree values to test: {DEGREE_VALUES}")
+ print(f"Task: {task_name}") # Use task_name
+
+
+ # --- Helper Functions (Only needed for experiment mode) ---
+ def parse_recall_from_summary(summary_file_path):
+ """Parses the recall rate from the summary file."""
+ try:
+ with open(summary_file_path, 'r', encoding='utf-8') as f:
+ content = f.read()
+ # Regex to find the recall rate line
+ match = re.search(r"Average Recall Rate:\s*([\d.]+)", content)
+ if match:
+ return float(match.group(1))
+ else:
+ print(f"Warning: Could not find recall rate in {summary_file_path}")
+ return None
+ except FileNotFoundError:
+ print(f"Error: Summary file not found at {summary_file_path}")
+ return None
+ except Exception as e:
+ print(f"Error reading or parsing summary file {summary_file_path}: {e}")
+ return None
+
+ def find_summary_file(output_text):
+ """Finds the summary file path from the script's output."""
+ # Regex to find the summary file path line
+ match = re.search(r"Summary written to:\s*(.*\.txt)", output_text)
+ if match:
+ return match.group(1).strip()
+ else:
+ # Fallback: Search for any summary file pattern in the log directory if not found in stdout
+ print("Warning: Could not find summary file path in script output. Searching log directory...")
+ try:
+ # Look for the most recent summary file
+ log_files = [os.path.join(LOG_DIR, f) for f in os.listdir(LOG_DIR) if f.startswith("summary_") and f.endswith(".txt")]
+ if log_files:
+ latest_summary = max(log_files, key=os.path.getmtime)
+ print(f"Found potential summary file by search: {latest_summary}")
+ return latest_summary
+ except FileNotFoundError:
+ print(f"Warning: Log directory '{LOG_DIR}' not found during fallback search.")
+ except Exception as e:
+ print(f"Error during fallback summary file search: {e}")
+ print("Fallback search failed.")
+ return None
+
+
+ # --- Main Experiment Loop ---
+ results = []
+ start_experiment_time = time.time()
+
+ for degree in DEGREE_VALUES:
+ for nprobe in NPROBE_VALUES:
+ run_start_time = time.time()
+ degree_str = str(degree) if degree is not None else "Default"
+ print(f"\n--- Running Experiment: degree={degree_str}, nprobe={nprobe}, task={task_name} ---") # Use task_name
+
+ # Base command
+ cmd = [
+ PYTHON_EXE, "-u", SCRIPT_TO_RUN,
+ "--nprobe", str(nprobe),
+ "--task", task_name # Use task_name
+ ]
+ # Add degree if specified
+ if degree is not None:
+ cmd.extend(["--degree", str(degree)])
+
+ print(f"Executing command: {' '.join(cmd)}")
+
+ recall_rate = None
+ summary_file = None
+ process_returncode = -1 # Default to error
+
+ try:
+ # Run the script and capture output
+ process = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ check=False, # Check returncode manually
+ encoding='utf-8',
+ errors='replace'
+ )
+ process_returncode = process.returncode
+
+ print(f"Command finished with return code: {process.returncode}")
+ # Uncomment below to see full output for debugging
+ # print("--- stdout ---")
+ # print(process.stdout)
+ # print("--- stderr ---")
+ # print(process.stderr)
+ # print("--------------")
+
+ # Attempt to find summary file path from stdout
+ summary_file = find_summary_file(process.stdout)
+
+ if summary_file:
+ # Give the filesystem a moment before reading
+ time.sleep(1)
+ recall_rate = parse_recall_from_summary(summary_file)
+ else:
+ print("ERROR: Could not locate summary file for this run.")
+
+ if process.returncode != 0:
+ print(f"Warning: Script execution failed (return code {process.returncode}) for degree={degree_str}, nprobe={nprobe}.")
+ # Recall might still be None or potentially parsed if summary existed
+
+ except FileNotFoundError:
+ print(f"CRITICAL ERROR: Could not find script '{SCRIPT_TO_RUN}' or Python executable '{PYTHON_EXE}'.")
+ # No result to append for this specific run in this case
+ continue # Skip to next iteration
+ except Exception as e:
+ print(f"CRITICAL ERROR running experiment for degree={degree_str}, nprobe={nprobe}: {e}")
+ # Append error result
+ results.append({
+ "degree": 60 if degree is None else degree, # <-- MODIFIED: Use 60 for None
+ "nprobe": nprobe,
+ "recall": None,
+ "duration_s": time.time() - run_start_time,
+ "return_code": process_returncode, # Use captured or default error code
+ "summary_file": summary_file,
+ "error": str(e)
+ })
+ continue # Skip to next iteration
+
+ run_duration = time.time() - run_start_time
+ print(f"Result: degree={degree_str}, nprobe={nprobe}, recall={recall_rate}, duration={run_duration:.2f}s")
+ results.append({
+ "degree": 60 if degree is None else degree, # <-- MODIFIED: Use 60 for None
+ "nprobe": nprobe,
+ "recall": recall_rate,
+ "duration_s": run_duration,
+ "return_code": process_returncode,
+ "summary_file": summary_file,
+ "error": None if process_returncode == 0 and recall_rate is not None else "Run failed or recall not found"
+ })
+
+ # Optional: add a small delay between runs if needed
+ # time.sleep(5)
+
+ # --- Post-Experiment Processing ---
+ print("\n--- Experiment Complete. Processing Results ---")
+ total_duration = time.time() - start_experiment_time
+ print(f"Total experiment duration: {total_duration:.2f}s")
+
+ if not results:
+ print("No results collected. Exiting.")
+ exit()
+
+ # Convert to DataFrame
+ results_df = pd.DataFrame(results)
+
+ # Save results to CSV
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ results_csv_path = os.path.join(RESULTS_DIR, f"experiment_results_{task_name}_{timestamp}.csv") # Use task_name
+ try:
+ results_df.to_csv(results_csv_path, index=False)
+ print(f"Results saved to: {results_csv_path}")
+ except Exception as e:
+ print(f"Error saving results to CSV: {e}")
+
+
+# --- Data Processing and Plotting (Common to both modes) ---
+
+if results_df is None or results_df.empty:
+ print("No data available to plot. Exiting.")
+ exit()
+
+print("\n--- Generating Plot ---")
+
+# Filter out runs where recall could not be parsed or is missing
+plot_df = results_df.dropna(subset=['recall'])
+
+# Filter out rows where degree is 'default' as we need numeric degree for calculation
+# Also ensure nprobe is numeric
+plot_df_numeric = plot_df[pd.to_numeric(plot_df['degree'], errors='coerce').notna()].copy()
+plot_df_numeric['degree'] = pd.to_numeric(plot_df_numeric['degree'])
+plot_df_numeric['nprobe'] = pd.to_numeric(plot_df_numeric['nprobe']) # Ensure nprobe is numeric
+
+if plot_df_numeric.empty:
+ print("No successful runs with numeric degree and recall values found. Cannot generate plot.")
+else:
+ # Calculate the new x-axis value
+ plot_df_numeric['degree_times_nprobe'] = plot_df_numeric['degree'] * plot_df_numeric['nprobe']
+
+ # Convert 'degree' column back to string for legend grouping
+ plot_df_numeric['degree_label'] = plot_df_numeric['degree'].astype(int).astype(str)
+
+ # Plotting
+ plt.figure(figsize=(12, 7))
+
+ # Group by degree and plot recall vs degree * nprobe
+ # Sort group by the new x-axis value for correct line plotting
+ for degree_label, group in plot_df_numeric.groupby('degree_label'):
+ group = group.sort_values('degree_times_nprobe')
+ plt.plot(group['degree_times_nprobe'], group['recall'], marker='o', linestyle='-', label=f'Degree={degree_label}')
+
+ plt.xlabel("Degree * Nprobe") # Updated X-axis label
+ plt.ylabel("Average Recall Rate")
+ plt.title(f"Recall Rate vs. Degree * Nprobe (Task: {task_name})") # Updated title
+ plt.legend(title="Graph Degree")
+ plt.grid(True, which="both", linestyle='--', linewidth=0.5)
+ # plt.xscale('log', base=2) # Removed log scale, let matplotlib decide or adjust later if needed
+ # plt.xticks(...) # Removed custom ticks, let matplotlib decide
+
+ # Save plot
+ plot_timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # Use a new timestamp for the plot
+ # Updated filename
+ plot_path = os.path.join(RESULTS_DIR, f"recall_vs_degree_nprobe_{task_name}_{plot_timestamp}.png")
+ try:
+ plt.savefig(plot_path)
+ print(f"Plot saved to: {plot_path}")
+ except Exception as e:
+ print(f"Error saving plot: {e}")
+ # plt.show() # Uncomment to display the plot interactively
+
+print("\nDone.")
\ No newline at end of file
diff --git a/research/utils/s3.md b/research/utils/s3.md
new file mode 100644
index 0000000..69774be
--- /dev/null
+++ b/research/utils/s3.md
@@ -0,0 +1,89 @@
+# How to Download Needed Data from S3
+
+## Install AWS CLI v2
+
+Install AWS CLI v2 by following the instructions at https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html.
+
+
+curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
+unzip awscliv2.zip
+sudo ./aws/install
+
+## Configure SSO
+
+Run the following command:
+
+```console
+aws configure sso
+```
+
+Example output:
+```
+(retrieval_scaling) (base) ➜ retrieval_scaling git:(main) ✗ aws configure sso
+SSO session name (Recommended): yichuan
+SSO start URL [None]: https://ucberkeley.awsapps.com/start#/
+SSO region [None]: us-west-2
+SSO registration scopes [sso:account:access]:
+Attempting to automatically open the SSO authorization page in your default browser.
+If the browser does not open or you wish to use a different device to authorize this request, open the following URL:
+
+https://oidc.us-west-2.amazonaws.com/authorize?response_type=code&client_id=i3YtHZTRneXEIApSyvdgSHVzLXdlc3QtMg&redirect_uri=http%3A%2F%2F127.0.0.1%3A37899%2Foauth%2Fcallback&state=5f52320e-0929-4e44-83c7-f6bd9b492010&code_challenge_method=S256&scopes=sso%3Aaccount%3Aaccess&code_challenge=HYnZ4Pc-tqI8CdJb6qEAR0LjI1_UjN-zln26lqJKeL8
+The only AWS account available to you is: 976193267581
+Using the account ID 976193267581
+There are 2 roles available to you.
+Using the role name "UCB-FederatedAdmins"
+Default client Region [None]:
+CLI default output format (json if not specified) [None]:
+Profile name [UCB-FederatedAdmins-976193267581]:
+To use this profile, specify the profile name using --profile, as shown:
+
+aws sts get-caller-identity --profile UCB-FederatedAdmins-976193267581
+```
+
+After configuration, you must include `--profile UCB-FederatedAdmins-976193267581` with each AWS operation to use the SSO credentials.
+
+## Refresh the SSO
+
+If you encounter the error `Error when retrieving token from sso: Token has expired and refresh failed`, simply run the SSO configuration command again.
+
+## Download S3 Data
+
+All data is stored in `s3://retrieval-scaling-out`, which includes 4 directories:
+- embeddings/
+- examples/
+- indices/
+- passages/
+
+Download the data using AWS CLI:
+
+```console
+aws s3 cp s3://retrieval-scaling-out ~/scaling_out --profile UCB-FederatedAdmins-976193267581
+
+aws s3 cp s3://retrieval-scaling-out/examples/test_c4.jsonl ~/examples/scaling_out --profile UCB-FederatedAdmins-976193267581
+```
+
+### Faster Download Options
+
+To accelerate downloads, you can try the following methods:
+
+Use multipart downloads:
+```console
+aws s3 cp s3://retrieval-scaling-out ~/scaling_out --profile UCB-FederatedAdmins-976193267581 --recursive --multipart-threshold 128MB --multipart-chunksize 512MB
+```
+
+Configure higher concurrency:
+```console
+aws configure set default.s3.max_concurrent_requests 50
+aws configure set default.s3.max_queue_size 10000
+```
+
+Utilize S3 Transfer Acceleration:
+```console
+aws s3 cp s3://retrieval-scaling-out ~/scaling_out --profile UCB-FederatedAdmins-976193267581 --recursive --endpoint-url https://s3-accelerate.amazonaws.com
+```
+
+Or use alternative tools like `s5cmd`:
+```console
+pip install s5cmd
+s5cmd --profile UCB-FederatedAdmins-976193267581 cp s3://retrieval-scaling-out/* ~/scaling_out/
+```
\ No newline at end of file
diff --git a/research/utils/seperate_hnsw_flat.py b/research/utils/seperate_hnsw_flat.py
new file mode 100644
index 0000000..7c49eb3
--- /dev/null
+++ b/research/utils/seperate_hnsw_flat.py
@@ -0,0 +1,212 @@
+import struct
+import sys
+import numpy as np
+import os
+
+INDEX_FLAT_L2_FOURCC = int.from_bytes(b'IxF2', 'little')
+INDEX_FLAT_IP_FOURCC = int.from_bytes(b'IxFI', 'little')
+INDEX_HNSW_FLAT_FOURCC = int.from_bytes(b'IHNf', 'little')
+INDEX_HNSW_PQ_FOURCC = int.from_bytes(b'IHNp', 'little')
+INDEX_HNSW_SQ_FOURCC = int.from_bytes(b'IHNs', 'little')
+INDEX_HNSW_2L_FOURCC = int.from_bytes(b'IHN2', 'little')
+INDEX_HNSW_CAGRA_FOURCC = int.from_bytes(b'IHNc', 'little')
+NULL_INDEX_FOURCC = int.from_bytes(b'null', 'little')
+
+HNSW_FOURCCS = {
+ INDEX_HNSW_FLAT_FOURCC,
+ INDEX_HNSW_PQ_FOURCC,
+ INDEX_HNSW_SQ_FOURCC,
+ INDEX_HNSW_2L_FOURCC,
+ INDEX_HNSW_CAGRA_FOURCC,
+}
+FLAT_FOURCCS = {INDEX_FLAT_L2_FOURCC, INDEX_FLAT_IP_FOURCC}
+
+
+# --- Helper functions for reading binary data ---
+
+def read_struct(f, fmt):
+ """Reads data according to the struct format."""
+ size = struct.calcsize(fmt)
+ data = f.read(size)
+ if len(data) != size:
+ raise EOFError("File ended unexpectedly.")
+ return struct.unpack(fmt, data)[0]
+
+def read_vector(f, element_fmt):
+ """Reads a vector (size followed by data)."""
+ count = read_struct(f, '<Q') # size_t usually 64-bit unsigned
+ element_size = struct.calcsize(element_fmt)
+ data_bytes = f.read(count * element_size)
+ if len(data_bytes) != count * element_size:
+ raise EOFError("File ended unexpectedly when reading vector data.")
+ # Unpack the elements individually if needed, or return raw bytes
+ # For simplicity here, we'll return the raw bytes and size
+ return count, data_bytes
+
+def read_vector_data(f, element_fmt, count):
+ """Reads vector data when the count is known."""
+ element_size = struct.calcsize(element_fmt)
+ data_bytes = f.read(count * element_size)
+ if len(data_bytes) != count * element_size:
+ raise EOFError("File ended unexpectedly when reading vector data.")
+ return data_bytes
+
+# --- Main Separation Logic ---
+
+def separate_hnsw_flat(input_filename, graph_output_filename, storage_output_filename):
+ """
+ Separates an IndexHNSWFlat file into graph and storage components.
+ """
+ print(f"Processing: {input_filename}")
+ try:
+ with open(input_filename, 'rb') as f_in, \
+ open(graph_output_filename, 'wb') as f_graph_out, \
+ open(storage_output_filename, 'wb') as f_storage_out:
+
+ # 1. Read and write HNSW FourCC
+ hnsw_fourcc = read_struct(f_in, '<I')
+ if hnsw_fourcc != INDEX_HNSW_FLAT_FOURCC:
+ print(f"Error: Expected IndexHNSWFlat FourCC ({INDEX_HNSW_FLAT_FOURCC:08x}), "
+ f"but got {hnsw_fourcc:08x}. Is this an IndexHNSWFlat file?", file=sys.stderr)
+ return False
+ f_graph_out.write(struct.pack('<I', hnsw_fourcc))
+ print(f" Index type: HNSWFlat ({hnsw_fourcc:08x})")
+
+ # 2. Read and write Index Header
+ # d, ntotal, dummy1, dummy2, is_trained, metric_type, [metric_arg]
+ d = read_struct(f_in, '<i')
+ ntotal = read_struct(f_in, '<q') # idx_t is int64 in Faiss default
+ dummy1 = read_struct(f_in, '<q')
+ dummy2 = read_struct(f_in, '<q')
+ is_trained = read_struct(f_in, '?') # bool -> 1 byte
+ metric_type = read_struct(f_in, '<i')
+ metric_arg = 0.0
+ header_data = struct.pack('<iq?i', d, ntotal, # omit dummies here
+ is_trained, metric_type)
+ if metric_type > 1:
+ metric_arg = read_struct(f_in, '<f')
+ header_data += struct.pack('<f', metric_arg)
+
+ # Write header *without* dummies to graph file
+ # We'll reconstruct the full header later if needed, but for now
+ # just keep the essential parts. Alternatively, write the exact bytes read.
+ # Let's write exact bytes for simplicity of reassembly
+ f_graph_out.write(struct.pack('<i', d))
+ f_graph_out.write(struct.pack('<q', ntotal))
+ f_graph_out.write(struct.pack('<q', dummy1))
+ f_graph_out.write(struct.pack('<q', dummy2))
+ f_graph_out.write(struct.pack('?', is_trained))
+ f_graph_out.write(struct.pack('<i', metric_type))
+ if metric_type > 1:
+ f_graph_out.write(struct.pack('<f', metric_arg))
+
+ print(f" Dimensions (d): {d}")
+ print(f" Num vectors (ntotal): {ntotal}")
+ print(f" Is trained: {is_trained}")
+ print(f" Metric type: {metric_type}")
+ if metric_type > 1:
+ print(f" Metric arg: {metric_arg}")
+
+ # 3. Read and write HNSW struct data
+ print(" Reading HNSW graph data...")
+ # assign_probas (vector<double>)
+ count, data = read_vector(f_in, '<d')
+ f_graph_out.write(struct.pack('<Q', count))
+ f_graph_out.write(data)
+ print(f" assign_probas size: {count}")
+
+ # cum_nneighbor_per_level (vector<int>)
+ count, data = read_vector(f_in, '<i')
+ f_graph_out.write(struct.pack('<Q', count))
+ f_graph_out.write(data)
+ print(f" cum_nneighbor_per_level size: {count}")
+
+ # levels (vector<int>) - Store node levels
+ count, data = read_vector(f_in, '<i')
+ f_graph_out.write(struct.pack('<Q', count))
+ f_graph_out.write(data)
+ print(f" levels size: {count}")
+
+ # offsets (vector<size_t>) - Store offsets for neighbors
+ count, data = read_vector(f_in, '<Q')
+ f_graph_out.write(struct.pack('<Q', count))
+ f_graph_out.write(data)
+ print(f" offsets size: {count}")
+
+ # neighbors (vector<storage_idx_t> -> int32_t typically)
+ count, data = read_vector(f_in, '<i') # Assuming storage_idx_t is int32
+ f_graph_out.write(struct.pack('<Q', count))
+ f_graph_out.write(data)
+ print(f" neighbors size: {count}")
+
+ # entry_point, max_level, efConstruction, efSearch
+ entry_point = read_struct(f_in, '<i')
+ max_level = read_struct(f_in, '<i')
+ efConstruction = read_struct(f_in, '<i')
+ efSearch = read_struct(f_in, '<i')
+ # Read and discard the dummy upper_beam
+ _ = read_struct(f_in, '<i')
+
+ f_graph_out.write(struct.pack('<i', entry_point))
+ f_graph_out.write(struct.pack('<i', max_level))
+ f_graph_out.write(struct.pack('<i', efConstruction))
+ f_graph_out.write(struct.pack('<i', efSearch))
+ f_graph_out.write(struct.pack('<i', 1)) # Write dummy upper_beam back
+ print(f" entry_point: {entry_point}")
+ print(f" max_level: {max_level}")
+ print(f" efConstruction: {efConstruction}")
+ print(f" efSearch: {efSearch}")
+
+
+ # --- Storage Part ---
+ print(" Reading storage (IndexFlat) data...")
+ storage_start_pos = f_in.tell()
+
+ # 4. Check: Read the storage FourCC (should be IndexFlat)
+ storage_fourcc = read_struct(f_in, '<I')
+ if storage_fourcc not in FLAT_FOURCCS:
+ print(f"Error: Expected IndexFlat FourCC ({list(FLAT_FOURCCS)}), "
+ f"but got {storage_fourcc:08x} after HNSW data.", file=sys.stderr)
+ return False
+ print(f" Storage type: IndexFlat ({storage_fourcc:08x})")
+
+ # 5. Read the rest of the file as storage data
+ f_in.seek(storage_start_pos) # Go back to start of storage
+ storage_data = f_in.read() # Read everything remaining
+ f_storage_out.write(storage_data)
+ print(f" Wrote {len(storage_data)} bytes to storage file.")
+
+ # 6. Final Check: Did we reach the end of the input file?
+ if f_in.read(1):
+ print("Warning: Unexpected data found after storage part in input file.", file=sys.stderr)
+
+ print(f"Separation complete:")
+ print(f" Graph structure: {graph_output_filename}")
+ print(f" Vector storage: {storage_output_filename}")
+ return True
+
+ except EOFError as e:
+ print(f"Error: Reached end of file unexpectedly. The input file might be incomplete or corrupted. {e}", file=sys.stderr)
+ return False
+ except Exception as e:
+ print(f"An error occurred: {e}", file=sys.stderr)
+ return False
+
+# --- Example Usage ---
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("Usage: python separate_hnsw_flat.py <input_index_file>")
+ sys.exit(1)
+
+ input_file = sys.argv[1]
+ base_name = os.path.splitext(input_file)[0]
+ graph_file = base_name + ".hnsw_graph"
+ storage_file = base_name + ".flat_storage"
+
+ if not os.path.exists(input_file):
+ print(f"Error: Input file not found: {input_file}", file=sys.stderr)
+ sys.exit(1)
+
+ success = separate_hnsw_flat(input_file, graph_file, storage_file)
+ if not success:
+ sys.exit(1)
\ No newline at end of file
diff --git a/research/utils/simple_search.fish b/research/utils/simple_search.fish
new file mode 100644
index 0000000..3f8209b
--- /dev/null
+++ b/research/utils/simple_search.fish
@@ -0,0 +1,18 @@
+
+
+set -l BIG_GRAPH /opt/dlami/nvme/scaling_out/indices/rpj_wiki/facebook/contriever-msmarco/hnsw/hnsw_IP_M30_efC128.index \
+ /opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/99_4_degree_based_hnsw_IP_M32_efC256/index.faiss \
+ /opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/d9_hnsw_IP_M8_efC128/index.faiss \
+ /opt/dlami/nvme/scaling_out/embeddings/facebook/contriever-msmarco/rpj_wiki/1-shards/indices/half_edges_IP_M32_efC128/index.faiss
+
+set -l LABELS hnsw_IP_M30_efC128 \
+ 99_4_degree_based_hnsw_IP_M32_efC256 \
+ d9_hnsw_IP_M8_efC128 \
+ half_edges_IP_M32_efC128
+
+for i in (seq 1 4)
+ set graph (string join / $BIG_GRAPH[$i])
+ set label (string join / $LABELS[$i])
+ echo "Building HNSW index with $label..."
+ python ./faiss/demo/large_graph_simple_build.py --index-file $graph
+end
diff --git a/research/utils/subsample_data_new.py b/research/utils/subsample_data_new.py
new file mode 100755
index 0000000..df58391
--- /dev/null
+++ b/research/utils/subsample_data_new.py
@@ -0,0 +1,59 @@
+import os
+import time
+import json
+import numpy as np
+import multiprocessing
+
+
+def subsample_jsonl_random(input_file_path, output_file_path, ratio=0.1, seed=42):
+ """
+ Subsamples 10% of the data from a JSONL file efficiently.
+
+ Args:
+ input_file_path (str): Path to the input JSONL file.
+ output_file_path (str): Path to the output JSONL file where the subsample will be saved.
+ seed (int): Seed for the random number generator to ensure reproducibility.
+ """
+ start_time = time.time()
+
+ # First pass: count the number of lines in the file
+ line_count = 0
+ with open(input_file_path, "r", encoding="utf-8") as file:
+ for _ in file:
+ line_count += 1
+ print(f"Total lines: {line_count}")
+
+ # Calculate indices for 10% sample
+ np.random.seed(seed)
+ sample_size = int(line_count * ratio)
+ selected_indices = set(np.random.choice(line_count, sample_size, replace=False))
+
+ # Second pass: write the selected lines to the output file
+ print(f"Subsampling {sample_size} lines")
+ current_index = 0
+ with (
+ open(input_file_path, "r", encoding="utf-8") as input_file,
+ open(output_file_path, "w", encoding="utf-8") as output_file,
+ ):
+ for line in input_file:
+ if current_index in selected_indices:
+ output_file.write(line)
+ current_index += 1
+
+ end_time = time.time()
+ print(
+ f"Time: {(end_time - start_time) / 60:.2f} minutes\tRaw Size: {line_count}\t Sampled Size: {sample_size}"
+ )
+
+
+if __name__ == "__main__":
+ # input_dir = '/mnt/md-256k/redpajama_v1/common_crawl_2023_06'
+ # output_dir = '/mnt/md-256k/massive_ds_data/subsampled_0.1/rpj_common_crawl_2023_06'
+ input_dir = "/mnt/md-256k/massive_ds_data/full/dpr_wiki"
+ output_dir = "/mnt/md-256k/massive_ds_data/subsampled_0.1/dpr_wiki"
+ os.makedirs(output_dir, exist_ok=True)
+
+ for filename in os.listdir(input_dir):
+ input_path = os.path.join(input_dir, filename)
+ output_path = os.path.join(output_dir, filename)
+ subsample_jsonl_random(input_path, output_path)
diff --git a/research/utils/timing.py b/research/utils/timing.py
new file mode 100755
index 0000000..2f6149e
--- /dev/null
+++ b/research/utils/timing.py
@@ -0,0 +1,52 @@
+import os
+import time
+import functools
+
+
+class time_exec:
+ def __init__(self, func):
+ functools.update_wrapper(self, func)
+ self.func = func
+
+ def __call__(self, *args, **kwargs):
+ start_time = time.time()
+ result = self.func(*args, **kwargs)
+ end_time = time.time()
+ execution_time = end_time - start_time
+ timing_log = (
+ f"Function '{self.func.__name__}' executed in {execution_time:.2f} seconds"
+ )
+ print(timing_log)
+ return result, execution_time
+
+
+class Logger:
+ def __init__(self, args):
+ self.log_file = args.log_file
+ self.ds_domain = args.domain
+ self.seed = args.seed
+ self.datastore_size = args.sample_size
+ self.stride = args.stride
+ self.max_seq_length = args.max_seq_length
+ self.merge = args.merge
+ self.prefix = f"{self.ds_domain}\t{self.seed}\t{self.datastore_size}\t{self.stride}\t{self.max_seq_length}\t{self.merge}"
+
+ def log_results(
+ self,
+ time_sample=None,
+ time_chunk=None,
+ time_index=None,
+ time_eval=None,
+ num_eval=None,
+ perplexity=None,
+ ):
+ # Create the log entry
+ log_entry = f"{self.prefix}\t{time_sample}\t{time_chunk}\t{time_index}\t{time_eval}\t{num_eval}\t{perplexity}\n"
+
+ # Open the file in append mode. Creates the file if it doesn't exist.
+ with open(self.log_file, "a") as file:
+ file.write(log_entry)
+
+ def log_string(self, log_string):
+ with open(self.log_file, "a") as file:
+ file.write(log_string)
diff --git a/tests/sanity_checks/README.md b/tests/sanity_checks/README.md
new file mode 100644
index 0000000..d55498c
--- /dev/null
+++ b/tests/sanity_checks/README.md
@@ -0,0 +1,120 @@
+# 🧪 Leann Sanity Checks
+
+This directory contains comprehensive sanity checks for the Leann system, ensuring all components work correctly across different configurations.
+
+## 📁 Test Files
+
+### `test_distance_functions.py`
+Tests all supported distance functions across DiskANN backend:
+- ✅ **MIPS** (Maximum Inner Product Search)
+- ✅ **L2** (Euclidean Distance)
+- ✅ **Cosine** (Cosine Similarity)
+
+```bash
+uv run python tests/sanity_checks/test_distance_functions.py
+```
+
+### `test_l2_verification.py`
+Specifically verifies that L2 distance is correctly implemented by:
+- Building indices with L2 vs Cosine metrics
+- Comparing search results and score ranges
+- Validating that different metrics produce expected score patterns
+
+```bash
+uv run python tests/sanity_checks/test_l2_verification.py
+```
+
+### `test_sanity_check.py`
+Comprehensive end-to-end verification including:
+- Distance function testing
+- Embedding model compatibility
+- Search result correctness validation
+- Backend integration testing
+
+```bash
+uv run python tests/sanity_checks/test_sanity_check.py
+```
+
+## 🎯 What These Tests Verify
+
+### ✅ Distance Function Support
+- All three distance metrics (MIPS, L2, Cosine) work correctly
+- Score ranges are appropriate for each metric type
+- Different metrics can produce different rankings (as expected)
+
+### ✅ Backend Integration
+- DiskANN backend properly initializes and builds indices
+- Graph construction completes without errors
+- Search operations return valid results
+
+### ✅ Embedding Pipeline
+- Real-time embedding computation works
+- Multiple embedding models are supported
+- ZMQ server communication functions correctly
+
+### ✅ End-to-End Functionality
+- Index building → searching → result retrieval pipeline
+- Metadata preservation through the entire flow
+- Error handling and graceful degradation
+
+## 🔍 Expected Output
+
+When all tests pass, you should see:
+
+```
+📊 测试结果总结:
+ mips : ✅ 通过
+ l2 : ✅ 通过
+ cosine : ✅ 通过
+
+🎉 测试完成!
+```
+
+## 🐛 Troubleshooting
+
+### Common Issues
+
+**Import Errors**: Ensure you're running from the project root:
+```bash
+cd /path/to/leann
+uv run python tests/sanity_checks/test_distance_functions.py
+```
+
+**Memory Issues**: Reduce graph complexity for resource-constrained systems:
+```python
+builder = LeannBuilder(
+ backend_name="diskann",
+ graph_degree=8, # Reduced from 16
+ complexity=16 # Reduced from 32
+)
+```
+
+**ZMQ Port Conflicts**: The tests use different ports to avoid conflicts, but you may need to kill existing processes:
+```bash
+pkill -f "embedding_server"
+```
+
+## 📊 Performance Expectations
+
+### Typical Timing (3 documents, consumer hardware):
+- **Index Building**: 2-5 seconds per distance function
+- **Search Query**: 50-200ms
+- **Recompute Mode**: 5-15 seconds (higher accuracy)
+
+### Memory Usage:
+- **Index Storage**: ~1-2 MB per distance function
+- **Runtime Memory**: ~500MB (including model loading)
+
+## 🔗 Integration with CI/CD
+
+These tests are designed to be run in automated environments:
+
+```yaml
+# GitHub Actions example
+- name: Run Sanity Checks
+ run: |
+ uv run python tests/sanity_checks/test_distance_functions.py
+ uv run python tests/sanity_checks/test_l2_verification.py
+```
+
+The tests are deterministic and should produce consistent results across different platforms.
\ No newline at end of file
diff --git a/tests/sanity_checks/test_distance_functions.py b/tests/sanity_checks/test_distance_functions.py
new file mode 100644
index 0000000..004619e
--- /dev/null
+++ b/tests/sanity_checks/test_distance_functions.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""
+DiskANN 距离函数测试
+"""
+
+import os
+from pathlib import Path
+import shutil
+import time
+
+# 导入后端包以触发插件注册
+try:
+ import leann_backend_diskann
+ import leann_backend_hnsw
+ print("INFO: Backend packages imported successfully.")
+except ImportError as e:
+ print(f"WARNING: Could not import backend packages. Error: {e}")
+
+# 从 leann-core 导入上层 API
+from leann.api import LeannBuilder, LeannSearcher
+
+
+def load_sample_documents():
+ """创建用于演示的样本文档"""
+ docs = [
+ {"title": "Intro to Python", "content": "Python is a programming language for machine learning"},
+ {"title": "ML Basics", "content": "Machine learning algorithms build intelligent systems"},
+ {"title": "Data Structures", "content": "Data structures like arrays and graphs organize information"},
+ ]
+ return docs
+
+
+def test_distance_function(distance_func, test_name):
+ """测试特定距离函数"""
+ print(f"\n=== 测试 {test_name} ({distance_func}) ===")
+
+ INDEX_DIR = Path(f"./test_indices_{distance_func}")
+ INDEX_PATH = str(INDEX_DIR / "documents.diskann")
+
+ if INDEX_DIR.exists():
+ shutil.rmtree(INDEX_DIR)
+
+ # 构建索引
+ print(f"构建索引 (距离函数: {distance_func})...")
+ builder = LeannBuilder(
+ backend_name="diskann",
+ distance_metric=distance_func,
+ graph_degree=16,
+ complexity=32
+ )
+
+ documents = load_sample_documents()
+ for doc in documents:
+ builder.add_text(doc["content"], metadata=doc)
+
+ try:
+ builder.build_index(INDEX_PATH)
+ print(f"✅ 索引构建成功")
+
+ # 测试搜索
+ searcher = LeannSearcher(INDEX_PATH, distance_metric=distance_func)
+ results = searcher.search("machine learning programming", top_k=2)
+
+ print(f"搜索结果:")
+ for i, result in enumerate(results):
+ print(f" {i+1}. Score: {result['score']:.4f}")
+ print(f" Text: {result['text'][:50]}...")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ 测试失败: {e}")
+ return False
+
+
+def main():
+ print("🔍 DiskANN 距离函数测试")
+ print("=" * 50)
+
+ # 测试不同距离函数
+ distance_tests = [
+ ("mips", "Maximum Inner Product Search"),
+ ("l2", "L2 Euclidean Distance"),
+ ("cosine", "Cosine Similarity")
+ ]
+
+ results = {}
+ for distance_func, test_name in distance_tests:
+ try:
+ success = test_distance_function(distance_func, test_name)
+ results[distance_func] = success
+ except Exception as e:
+ print(f"❌ {distance_func} 测试异常: {e}")
+ results[distance_func] = False
+
+ # 总结
+ print("\n" + "=" * 50)
+ print("📊 测试结果总结:")
+ for distance_func, success in results.items():
+ status = "✅ 通过" if success else "❌ 失败"
+ print(f" {distance_func:10s}: {status}")
+
+ print("\n🎉 测试完成!")
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/tests/sanity_checks/test_l2_verification.py b/tests/sanity_checks/test_l2_verification.py
new file mode 100644
index 0000000..96c1b6c
--- /dev/null
+++ b/tests/sanity_checks/test_l2_verification.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""
+验证DiskANN L2距离是否真正工作
+"""
+
+import numpy as np
+from pathlib import Path
+import shutil
+
+# 导入后端包以触发插件注册
+try:
+ import leann_backend_diskann
+ print("INFO: Backend packages imported successfully.")
+except ImportError as e:
+ print(f"WARNING: Could not import backend packages. Error: {e}")
+
+from leann.api import LeannBuilder, LeannSearcher
+
+def test_l2_verification():
+ """验证L2距离是否真正被使用"""
+ print("=== 验证DiskANN L2距离实现 ===")
+
+ INDEX_DIR = Path("./test_l2_verification")
+ INDEX_PATH = str(INDEX_DIR / "documents.diskann")
+
+ if INDEX_DIR.exists():
+ shutil.rmtree(INDEX_DIR)
+
+ # 创建特殊的测试文档,使L2和cosine产生不同结果
+ documents = [
+ "machine learning artificial intelligence", # 文档0
+ "computer programming software development", # 文档1
+ "data science analytics statistics" # 文档2
+ ]
+
+ print("构建索引...")
+ builder = LeannBuilder(
+ backend_name="diskann",
+ distance_metric="l2", # 明确指定L2
+ graph_degree=16,
+ complexity=32
+ )
+
+ for i, doc in enumerate(documents):
+ builder.add_text(doc, metadata={"id": i, "text": doc})
+
+ builder.build_index(INDEX_PATH)
+ print("✅ 索引构建完成")
+
+ # 测试搜索
+ searcher = LeannSearcher(INDEX_PATH, distance_metric="l2")
+
+ # 用一个与文档0非常相似的查询
+ query = "machine learning AI technology"
+ results = searcher.search(query, top_k=3)
+
+ print(f"\n查询: '{query}'")
+ print("L2距离搜索结果:")
+ for i, result in enumerate(results):
+ print(f" {i+1}. ID:{result['id']}, Score:{result['score']:.6f}")
+ print(f" Text: {result['text']}")
+
+ # 现在用cosine重新测试同样的数据
+ print(f"\n--- 用Cosine距离对比测试 ---")
+
+ INDEX_DIR_COS = Path("./test_cosine_verification")
+ INDEX_PATH_COS = str(INDEX_DIR_COS / "documents.diskann")
+
+ if INDEX_DIR_COS.exists():
+ shutil.rmtree(INDEX_DIR_COS)
+
+ builder_cos = LeannBuilder(
+ backend_name="diskann",
+ distance_metric="cosine", # 使用cosine
+ graph_degree=16,
+ complexity=32
+ )
+
+ for i, doc in enumerate(documents):
+ builder_cos.add_text(doc, metadata={"id": i, "text": doc})
+
+ builder_cos.build_index(INDEX_PATH_COS)
+
+ searcher_cos = LeannSearcher(INDEX_PATH_COS, distance_metric="cosine")
+ results_cos = searcher_cos.search(query, top_k=3)
+
+ print("Cosine距离搜索结果:")
+ for i, result in enumerate(results_cos):
+ print(f" {i+1}. ID:{result['id']}, Score:{result['score']:.6f}")
+ print(f" Text: {result['text']}")
+
+ # 对比分析
+ print(f"\n--- 结果对比分析 ---")
+ print("L2距离的分数是欧几里得距离平方,越小越相似")
+ print("Cosine距离的分数是余弦相似度的负值,越小越相似")
+
+ l2_top = results[0]
+ cos_top = results_cos[0]
+
+ print(f"L2最佳匹配: ID{l2_top['id']}, Score={l2_top['score']:.6f}")
+ print(f"Cosine最佳匹配: ID{cos_top['id']}, Score={cos_top['score']:.6f}")
+
+ if l2_top['id'] == cos_top['id']:
+ print("✅ 两种距离函数返回相同的最佳匹配")
+ else:
+ print("⚠️ 两种距离函数返回不同的最佳匹配 - 这表明它们确实使用了不同的距离计算")
+
+ # 验证分数范围的合理性
+ l2_scores = [r['score'] for r in results]
+ cos_scores = [r['score'] for r in results_cos]
+
+ print(f"L2分数范围: {min(l2_scores):.6f} 到 {max(l2_scores):.6f}")
+ print(f"Cosine分数范围: {min(cos_scores):.6f} 到 {max(cos_scores):.6f}")
+
+ # L2分数应该是正数,cosine分数应该在-1到0之间(因为是负的相似度)
+ if all(score >= 0 for score in l2_scores):
+ print("✅ L2分数都是正数,符合预期")
+ else:
+ print("❌ L2分数有负数,可能有问题")
+
+ if all(-1 <= score <= 0 for score in cos_scores):
+ print("✅ Cosine分数在合理范围内")
+ else:
+ print(f"⚠️ Cosine分数超出预期范围: {cos_scores}")
+
+if __name__ == "__main__":
+ test_l2_verification()
\ No newline at end of file
diff --git a/tests/sanity_checks/test_sanity_check.py b/tests/sanity_checks/test_sanity_check.py
new file mode 100644
index 0000000..1c95b8c
--- /dev/null
+++ b/tests/sanity_checks/test_sanity_check.py
@@ -0,0 +1,190 @@
+#!/usr/bin/env python3
+"""
+Sanity check script for Leann DiskANN backend
+Tests different distance functions and embedding models
+"""
+
+import os
+import numpy as np
+from pathlib import Path
+import shutil
+import time
+
+# 导入后端包以触发插件注册
+import sys
+sys.path.append('packages/leann-core/src')
+sys.path.append('packages/leann-backend-diskann')
+sys.path.append('packages/leann-backend-hnsw')
+
+try:
+ import leann_backend_diskann
+ import leann_backend_hnsw
+ print("INFO: Backend packages imported successfully.")
+except ImportError as e:
+ print(f"WARNING: Could not import backend packages. Error: {e}")
+
+# 从 leann-core 导入上层 API
+from leann.api import LeannBuilder, LeannSearcher
+
+def test_distance_functions():
+ """测试不同的距离函数"""
+ print("\n=== 测试不同距离函数 ===")
+
+ # 测试数据
+ documents = [
+ "Machine learning is a powerful technology",
+ "Deep learning uses neural networks",
+ "Artificial intelligence transforms industries"
+ ]
+
+ distance_functions = ["mips", "l2", "cosine"]
+
+ for distance_func in distance_functions:
+ print(f"\n[测试 {distance_func} 距离函数]")
+ try:
+ index_path = f"test_indices/test_{distance_func}.diskann"
+ if Path(index_path).parent.exists():
+ shutil.rmtree(Path(index_path).parent)
+
+ # 构建索引
+ builder = LeannBuilder(
+ backend_name="diskann",
+ distance_metric=distance_func,
+ graph_degree=16,
+ complexity=32
+ )
+
+ for doc in documents:
+ builder.add_text(doc)
+
+ builder.build_index(index_path)
+
+ # 测试搜索
+ searcher = LeannSearcher(index_path, distance_metric=distance_func)
+ results = searcher.search("neural network technology", top_k=2)
+
+ print(f"✅ {distance_func} 距离函数工作正常")
+ for i, result in enumerate(results):
+ print(f" {i+1}. Score: {result['score']:.4f}, Text: {result['text'][:50]}...")
+
+ except Exception as e:
+ print(f"❌ {distance_func} 距离函数失败: {e}")
+
+def test_embedding_models():
+ """测试不同的embedding模型"""
+ print("\n=== 测试不同Embedding模型 ===")
+
+ documents = ["AI is transforming the world", "Technology advances rapidly"]
+
+ # 测试不同的embedding模型
+ models_to_test = [
+ "sentence-transformers/all-mpnet-base-v2",
+ "sentence-transformers/all-MiniLM-L6-v2",
+ # "sentence-transformers/distilbert-base-nli-mean-tokens", # 可能不存在
+ ]
+
+ for model_name in models_to_test:
+ print(f"\n[测试 {model_name}]")
+ try:
+ index_path = f"test_indices/test_model.diskann"
+ if Path(index_path).parent.exists():
+ shutil.rmtree(Path(index_path).parent)
+
+ # 构建索引
+ builder = LeannBuilder(
+ backend_name="diskann",
+ embedding_model=model_name,
+ distance_metric="cosine"
+ )
+
+ for doc in documents:
+ builder.add_text(doc)
+
+ builder.build_index(index_path)
+
+ # 测试搜索
+ searcher = LeannSearcher(index_path)
+ results = searcher.search("artificial intelligence", top_k=1)
+
+ print(f"✅ {model_name} 模型工作正常")
+ print(f" 结果: {results[0]['text'][:50]}...")
+
+ except Exception as e:
+ print(f"❌ {model_name} 模型失败: {e}")
+
+def test_search_correctness():
+ """验证搜索结果的正确性"""
+ print("\n=== 验证搜索结果正确性 ===")
+
+ # 创建有明确相关性的测试文档
+ documents = [
+ "Python is a programming language used for machine learning", # 与编程相关
+ "Dogs are loyal pets that love to play fetch", # 与动物相关
+ "Machine learning algorithms can predict future trends", # 与ML相关
+ "Cats are independent animals that sleep a lot", # 与动物相关
+ "Deep learning neural networks process complex data" # 与ML相关
+ ]
+
+ try:
+ index_path = "test_indices/correctness_test.diskann"
+ if Path(index_path).parent.exists():
+ shutil.rmtree(Path(index_path).parent)
+
+ # 构建索引
+ builder = LeannBuilder(
+ backend_name="diskann",
+ distance_metric="cosine"
+ )
+
+ for doc in documents:
+ builder.add_text(doc)
+
+ builder.build_index(index_path)
+
+ # 测试相关性查询
+ searcher = LeannSearcher(index_path)
+
+ test_queries = [
+ ("machine learning programming", [0, 2, 4]), # 应该返回ML相关文档
+ ("pet animals behavior", [1, 3]), # 应该返回动物相关文档
+ ]
+
+ for query, expected_topics in test_queries:
+ print(f"\n查询: '{query}'")
+ results = searcher.search(query, top_k=3)
+
+ print("搜索结果:")
+ for i, result in enumerate(results):
+ print(f" {i+1}. ID:{result['id']}, Score:{result['score']:.4f}")
+ print(f" Text: {result['text'][:60]}...")
+
+ # 简单验证:检查前两个结果是否在预期范围内
+ top_ids = [result['id'] for result in results[:2]]
+ relevant_found = any(id in expected_topics for id in top_ids)
+
+ if relevant_found:
+ print("✅ 搜索结果相关性正确")
+ else:
+ print("⚠️ 搜索结果相关性可能有问题")
+
+ except Exception as e:
+ print(f"❌ 正确性测试失败: {e}")
+
+def main():
+ print("🔍 Leann DiskANN Sanity Check")
+ print("=" * 50)
+
+ # 清理旧的测试数据
+ if Path("test_indices").exists():
+ shutil.rmtree("test_indices")
+
+ # 运行测试
+ test_distance_functions()
+ test_embedding_models()
+ test_search_correctness()
+
+ print("\n" + "=" * 50)
+ print("🎉 Sanity check 完成!")
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/uv.lock b/uv.lock
new file mode 100644
index 0000000..5f590e4
--- /dev/null
+++ b/uv.lock
@@ -0,0 +1,6241 @@
+version = 1
+revision = 1
+requires-python = ">=3.9"
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+
+[[package]]
+name = "aiohappyeyeballs"
+version = "2.6.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/26/30/f84a107a9c4331c14b2b586036f40965c128aa4fee4dda5d3d51cb14ad54/aiohappyeyeballs-2.6.1.tar.gz", hash = "sha256:c3f9d0113123803ccadfdf3f0faa505bc78e6a72d1cc4806cbd719826e943558", size = 22760 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0f/15/5bf3b99495fb160b63f95972b81750f18f7f4e02ad051373b669d17d44f2/aiohappyeyeballs-2.6.1-py3-none-any.whl", hash = "sha256:f349ba8f4b75cb25c99c5c2d84e997e485204d2902a9597802b0371f09331fb8", size = 15265 },
+]
+
+[[package]]
+name = "aiohttp"
+version = "3.12.13"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "aiohappyeyeballs" },
+ { name = "aiosignal" },
+ { name = "async-timeout", marker = "python_full_version < '3.11'" },
+ { name = "attrs" },
+ { name = "frozenlist" },
+ { name = "multidict" },
+ { name = "propcache" },
+ { name = "yarl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/42/6e/ab88e7cb2a4058bed2f7870276454f85a7c56cd6da79349eb314fc7bbcaa/aiohttp-3.12.13.tar.gz", hash = "sha256:47e2da578528264a12e4e3dd8dd72a7289e5f812758fe086473fab037a10fcce", size = 7819160 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8b/2d/27e4347660723738b01daa3f5769d56170f232bf4695dd4613340da135bb/aiohttp-3.12.13-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:5421af8f22a98f640261ee48aae3a37f0c41371e99412d55eaf2f8a46d5dad29", size = 702090 },
+ { url = "https://files.pythonhosted.org/packages/10/0b/4a8e0468ee8f2b9aff3c05f2c3a6be1dfc40b03f68a91b31041d798a9510/aiohttp-3.12.13-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0fcda86f6cb318ba36ed8f1396a6a4a3fd8f856f84d426584392083d10da4de0", size = 478440 },
+ { url = "https://files.pythonhosted.org/packages/b9/c8/2086df2f9a842b13feb92d071edf756be89250f404f10966b7bc28317f17/aiohttp-3.12.13-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:4cd71c9fb92aceb5a23c4c39d8ecc80389c178eba9feab77f19274843eb9412d", size = 466215 },
+ { url = "https://files.pythonhosted.org/packages/a7/3d/d23e5bd978bc8012a65853959b13bd3b55c6e5afc172d89c26ad6624c52b/aiohttp-3.12.13-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:34ebf1aca12845066c963016655dac897651e1544f22a34c9b461ac3b4b1d3aa", size = 1648271 },
+ { url = "https://files.pythonhosted.org/packages/31/31/e00122447bb137591c202786062f26dd383574c9f5157144127077d5733e/aiohttp-3.12.13-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:893a4639694c5b7edd4bdd8141be296042b6806e27cc1d794e585c43010cc294", size = 1622329 },
+ { url = "https://files.pythonhosted.org/packages/04/01/caef70be3ac38986969045f21f5fb802ce517b3f371f0615206bf8aa6423/aiohttp-3.12.13-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:663d8ee3ffb3494502ebcccb49078faddbb84c1d870f9c1dd5a29e85d1f747ce", size = 1694734 },
+ { url = "https://files.pythonhosted.org/packages/3f/15/328b71fedecf69a9fd2306549b11c8966e420648a3938d75d3ed5bcb47f6/aiohttp-3.12.13-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f0f8f6a85a0006ae2709aa4ce05749ba2cdcb4b43d6c21a16c8517c16593aabe", size = 1737049 },
+ { url = "https://files.pythonhosted.org/packages/e6/7a/d85866a642158e1147c7da5f93ad66b07e5452a84ec4258e5f06b9071e92/aiohttp-3.12.13-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1582745eb63df267c92d8b61ca655a0ce62105ef62542c00a74590f306be8cb5", size = 1641715 },
+ { url = "https://files.pythonhosted.org/packages/14/57/3588800d5d2f5f3e1cb6e7a72747d1abc1e67ba5048e8b845183259c2e9b/aiohttp-3.12.13-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d59227776ee2aa64226f7e086638baa645f4b044f2947dbf85c76ab11dcba073", size = 1581836 },
+ { url = "https://files.pythonhosted.org/packages/2f/55/c913332899a916d85781aa74572f60fd98127449b156ad9c19e23135b0e4/aiohttp-3.12.13-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:06b07c418bde1c8e737d8fa67741072bd3f5b0fb66cf8c0655172188c17e5fa6", size = 1625685 },
+ { url = "https://files.pythonhosted.org/packages/4c/34/26cded195f3bff128d6a6d58d7a0be2ae7d001ea029e0fe9008dcdc6a009/aiohttp-3.12.13-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:9445c1842680efac0f81d272fd8db7163acfcc2b1436e3f420f4c9a9c5a50795", size = 1636471 },
+ { url = "https://files.pythonhosted.org/packages/19/21/70629ca006820fccbcec07f3cd5966cbd966e2d853d6da55339af85555b9/aiohttp-3.12.13-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:09c4767af0b0b98c724f5d47f2bf33395c8986995b0a9dab0575ca81a554a8c0", size = 1611923 },
+ { url = "https://files.pythonhosted.org/packages/31/80/7fa3f3bebf533aa6ae6508b51ac0de9965e88f9654fa679cc1a29d335a79/aiohttp-3.12.13-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:f3854fbde7a465318ad8d3fc5bef8f059e6d0a87e71a0d3360bb56c0bf87b18a", size = 1691511 },
+ { url = "https://files.pythonhosted.org/packages/0f/7a/359974653a3cdd3e9cee8ca10072a662c3c0eb46a359c6a1f667b0296e2f/aiohttp-3.12.13-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:2332b4c361c05ecd381edb99e2a33733f3db906739a83a483974b3df70a51b40", size = 1714751 },
+ { url = "https://files.pythonhosted.org/packages/2d/24/0aa03d522171ce19064347afeefadb008be31ace0bbb7d44ceb055700a14/aiohttp-3.12.13-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1561db63fa1b658cd94325d303933553ea7d89ae09ff21cc3bcd41b8521fbbb6", size = 1643090 },
+ { url = "https://files.pythonhosted.org/packages/86/2e/7d4b0026a41e4b467e143221c51b279083b7044a4b104054f5c6464082ff/aiohttp-3.12.13-cp310-cp310-win32.whl", hash = "sha256:a0be857f0b35177ba09d7c472825d1b711d11c6d0e8a2052804e3b93166de1ad", size = 427526 },
+ { url = "https://files.pythonhosted.org/packages/17/de/34d998da1e7f0de86382160d039131e9b0af1962eebfe53dda2b61d250e7/aiohttp-3.12.13-cp310-cp310-win_amd64.whl", hash = "sha256:fcc30ad4fb5cb41a33953292d45f54ef4066746d625992aeac33b8c681173178", size = 450734 },
+ { url = "https://files.pythonhosted.org/packages/6a/65/5566b49553bf20ffed6041c665a5504fb047cefdef1b701407b8ce1a47c4/aiohttp-3.12.13-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7c229b1437aa2576b99384e4be668af1db84b31a45305d02f61f5497cfa6f60c", size = 709401 },
+ { url = "https://files.pythonhosted.org/packages/14/b5/48e4cc61b54850bdfafa8fe0b641ab35ad53d8e5a65ab22b310e0902fa42/aiohttp-3.12.13-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:04076d8c63471e51e3689c93940775dc3d12d855c0c80d18ac5a1c68f0904358", size = 481669 },
+ { url = "https://files.pythonhosted.org/packages/04/4f/e3f95c8b2a20a0437d51d41d5ccc4a02970d8ad59352efb43ea2841bd08e/aiohttp-3.12.13-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:55683615813ce3601640cfaa1041174dc956d28ba0511c8cbd75273eb0587014", size = 469933 },
+ { url = "https://files.pythonhosted.org/packages/41/c9/c5269f3b6453b1cfbd2cfbb6a777d718c5f086a3727f576c51a468b03ae2/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:921bc91e602d7506d37643e77819cb0b840d4ebb5f8d6408423af3d3bf79a7b7", size = 1740128 },
+ { url = "https://files.pythonhosted.org/packages/6f/49/a3f76caa62773d33d0cfaa842bdf5789a78749dbfe697df38ab1badff369/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e72d17fe0974ddeae8ed86db297e23dba39c7ac36d84acdbb53df2e18505a013", size = 1688796 },
+ { url = "https://files.pythonhosted.org/packages/ad/e4/556fccc4576dc22bf18554b64cc873b1a3e5429a5bdb7bbef7f5d0bc7664/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0653d15587909a52e024a261943cf1c5bdc69acb71f411b0dd5966d065a51a47", size = 1787589 },
+ { url = "https://files.pythonhosted.org/packages/b9/3d/d81b13ed48e1a46734f848e26d55a7391708421a80336e341d2aef3b6db2/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a77b48997c66722c65e157c06c74332cdf9c7ad00494b85ec43f324e5c5a9b9a", size = 1826635 },
+ { url = "https://files.pythonhosted.org/packages/75/a5/472e25f347da88459188cdaadd1f108f6292f8a25e62d226e63f860486d1/aiohttp-3.12.13-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d6946bae55fd36cfb8e4092c921075cde029c71c7cb571d72f1079d1e4e013bc", size = 1729095 },
+ { url = "https://files.pythonhosted.org/packages/b9/fe/322a78b9ac1725bfc59dfc301a5342e73d817592828e4445bd8f4ff83489/aiohttp-3.12.13-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4f95db8c8b219bcf294a53742c7bda49b80ceb9d577c8e7aa075612b7f39ffb7", size = 1666170 },
+ { url = "https://files.pythonhosted.org/packages/7a/77/ec80912270e231d5e3839dbd6c065472b9920a159ec8a1895cf868c2708e/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:03d5eb3cfb4949ab4c74822fb3326cd9655c2b9fe22e4257e2100d44215b2e2b", size = 1714444 },
+ { url = "https://files.pythonhosted.org/packages/21/b2/fb5aedbcb2b58d4180e58500e7c23ff8593258c27c089abfbcc7db65bd40/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:6383dd0ffa15515283c26cbf41ac8e6705aab54b4cbb77bdb8935a713a89bee9", size = 1709604 },
+ { url = "https://files.pythonhosted.org/packages/e3/15/a94c05f7c4dc8904f80b6001ad6e07e035c58a8ebfcc15e6b5d58500c858/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6548a411bc8219b45ba2577716493aa63b12803d1e5dc70508c539d0db8dbf5a", size = 1689786 },
+ { url = "https://files.pythonhosted.org/packages/1d/fd/0d2e618388f7a7a4441eed578b626bda9ec6b5361cd2954cfc5ab39aa170/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:81b0fcbfe59a4ca41dc8f635c2a4a71e63f75168cc91026c61be665945739e2d", size = 1783389 },
+ { url = "https://files.pythonhosted.org/packages/a6/6b/6986d0c75996ef7e64ff7619b9b7449b1d1cbbe05c6755e65d92f1784fe9/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:6a83797a0174e7995e5edce9dcecc517c642eb43bc3cba296d4512edf346eee2", size = 1803853 },
+ { url = "https://files.pythonhosted.org/packages/21/65/cd37b38f6655d95dd07d496b6d2f3924f579c43fd64b0e32b547b9c24df5/aiohttp-3.12.13-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a5734d8469a5633a4e9ffdf9983ff7cdb512524645c7a3d4bc8a3de45b935ac3", size = 1716909 },
+ { url = "https://files.pythonhosted.org/packages/fd/20/2de7012427dc116714c38ca564467f6143aec3d5eca3768848d62aa43e62/aiohttp-3.12.13-cp311-cp311-win32.whl", hash = "sha256:fef8d50dfa482925bb6b4c208b40d8e9fa54cecba923dc65b825a72eed9a5dbd", size = 427036 },
+ { url = "https://files.pythonhosted.org/packages/f8/b6/98518bcc615ef998a64bef371178b9afc98ee25895b4f476c428fade2220/aiohttp-3.12.13-cp311-cp311-win_amd64.whl", hash = "sha256:9a27da9c3b5ed9d04c36ad2df65b38a96a37e9cfba6f1381b842d05d98e6afe9", size = 451427 },
+ { url = "https://files.pythonhosted.org/packages/b4/6a/ce40e329788013cd190b1d62bbabb2b6a9673ecb6d836298635b939562ef/aiohttp-3.12.13-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0aa580cf80558557285b49452151b9c69f2fa3ad94c5c9e76e684719a8791b73", size = 700491 },
+ { url = "https://files.pythonhosted.org/packages/28/d9/7150d5cf9163e05081f1c5c64a0cdf3c32d2f56e2ac95db2a28fe90eca69/aiohttp-3.12.13-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b103a7e414b57e6939cc4dece8e282cfb22043efd0c7298044f6594cf83ab347", size = 475104 },
+ { url = "https://files.pythonhosted.org/packages/f8/91/d42ba4aed039ce6e449b3e2db694328756c152a79804e64e3da5bc19dffc/aiohttp-3.12.13-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78f64e748e9e741d2eccff9597d09fb3cd962210e5b5716047cbb646dc8fe06f", size = 467948 },
+ { url = "https://files.pythonhosted.org/packages/99/3b/06f0a632775946981d7c4e5a865cddb6e8dfdbaed2f56f9ade7bb4a1039b/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:29c955989bf4c696d2ededc6b0ccb85a73623ae6e112439398935362bacfaaf6", size = 1714742 },
+ { url = "https://files.pythonhosted.org/packages/92/a6/2552eebad9ec5e3581a89256276009e6a974dc0793632796af144df8b740/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d640191016763fab76072c87d8854a19e8e65d7a6fcfcbf017926bdbbb30a7e5", size = 1697393 },
+ { url = "https://files.pythonhosted.org/packages/d8/9f/bd08fdde114b3fec7a021381b537b21920cdd2aa29ad48c5dffd8ee314f1/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4dc507481266b410dede95dd9f26c8d6f5a14315372cc48a6e43eac652237d9b", size = 1752486 },
+ { url = "https://files.pythonhosted.org/packages/f7/e1/affdea8723aec5bd0959171b5490dccd9a91fcc505c8c26c9f1dca73474d/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8a94daa873465d518db073bd95d75f14302e0208a08e8c942b2f3f1c07288a75", size = 1798643 },
+ { url = "https://files.pythonhosted.org/packages/f3/9d/666d856cc3af3a62ae86393baa3074cc1d591a47d89dc3bf16f6eb2c8d32/aiohttp-3.12.13-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:177f52420cde4ce0bb9425a375d95577fe082cb5721ecb61da3049b55189e4e6", size = 1718082 },
+ { url = "https://files.pythonhosted.org/packages/f3/ce/3c185293843d17be063dada45efd2712bb6bf6370b37104b4eda908ffdbd/aiohttp-3.12.13-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f7df1f620ec40f1a7fbcb99ea17d7326ea6996715e78f71a1c9a021e31b96b8", size = 1633884 },
+ { url = "https://files.pythonhosted.org/packages/3a/5b/f3413f4b238113be35dfd6794e65029250d4b93caa0974ca572217745bdb/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3062d4ad53b36e17796dce1c0d6da0ad27a015c321e663657ba1cc7659cfc710", size = 1694943 },
+ { url = "https://files.pythonhosted.org/packages/82/c8/0e56e8bf12081faca85d14a6929ad5c1263c146149cd66caa7bc12255b6d/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:8605e22d2a86b8e51ffb5253d9045ea73683d92d47c0b1438e11a359bdb94462", size = 1716398 },
+ { url = "https://files.pythonhosted.org/packages/ea/f3/33192b4761f7f9b2f7f4281365d925d663629cfaea093a64b658b94fc8e1/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:54fbbe6beafc2820de71ece2198458a711e224e116efefa01b7969f3e2b3ddae", size = 1657051 },
+ { url = "https://files.pythonhosted.org/packages/5e/0b/26ddd91ca8f84c48452431cb4c5dd9523b13bc0c9766bda468e072ac9e29/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:050bd277dfc3768b606fd4eae79dd58ceda67d8b0b3c565656a89ae34525d15e", size = 1736611 },
+ { url = "https://files.pythonhosted.org/packages/c3/8d/e04569aae853302648e2c138a680a6a2f02e374c5b6711732b29f1e129cc/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:2637a60910b58f50f22379b6797466c3aa6ae28a6ab6404e09175ce4955b4e6a", size = 1764586 },
+ { url = "https://files.pythonhosted.org/packages/ac/98/c193c1d1198571d988454e4ed75adc21c55af247a9fda08236602921c8c8/aiohttp-3.12.13-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e986067357550d1aaa21cfe9897fa19e680110551518a5a7cf44e6c5638cb8b5", size = 1724197 },
+ { url = "https://files.pythonhosted.org/packages/e7/9e/07bb8aa11eec762c6b1ff61575eeeb2657df11ab3d3abfa528d95f3e9337/aiohttp-3.12.13-cp312-cp312-win32.whl", hash = "sha256:ac941a80aeea2aaae2875c9500861a3ba356f9ff17b9cb2dbfb5cbf91baaf5bf", size = 421771 },
+ { url = "https://files.pythonhosted.org/packages/52/66/3ce877e56ec0813069cdc9607cd979575859c597b6fb9b4182c6d5f31886/aiohttp-3.12.13-cp312-cp312-win_amd64.whl", hash = "sha256:671f41e6146a749b6c81cb7fd07f5a8356d46febdaaaf07b0e774ff04830461e", size = 447869 },
+ { url = "https://files.pythonhosted.org/packages/11/0f/db19abdf2d86aa1deec3c1e0e5ea46a587b97c07a16516b6438428b3a3f8/aiohttp-3.12.13-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:d4a18e61f271127465bdb0e8ff36e8f02ac4a32a80d8927aa52371e93cd87938", size = 694910 },
+ { url = "https://files.pythonhosted.org/packages/d5/81/0ab551e1b5d7f1339e2d6eb482456ccbe9025605b28eed2b1c0203aaaade/aiohttp-3.12.13-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:532542cb48691179455fab429cdb0d558b5e5290b033b87478f2aa6af5d20ace", size = 472566 },
+ { url = "https://files.pythonhosted.org/packages/34/3f/6b7d336663337672d29b1f82d1f252ec1a040fe2d548f709d3f90fa2218a/aiohttp-3.12.13-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d7eea18b52f23c050ae9db5d01f3d264ab08f09e7356d6f68e3f3ac2de9dfabb", size = 464856 },
+ { url = "https://files.pythonhosted.org/packages/26/7f/32ca0f170496aa2ab9b812630fac0c2372c531b797e1deb3deb4cea904bd/aiohttp-3.12.13-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ad7c8e5c25f2a26842a7c239de3f7b6bfb92304593ef997c04ac49fb703ff4d7", size = 1703683 },
+ { url = "https://files.pythonhosted.org/packages/ec/53/d5513624b33a811c0abea8461e30a732294112318276ce3dbf047dbd9d8b/aiohttp-3.12.13-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6af355b483e3fe9d7336d84539fef460120c2f6e50e06c658fe2907c69262d6b", size = 1684946 },
+ { url = "https://files.pythonhosted.org/packages/37/72/4c237dd127827b0247dc138d3ebd49c2ded6114c6991bbe969058575f25f/aiohttp-3.12.13-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a95cf9f097498f35c88e3609f55bb47b28a5ef67f6888f4390b3d73e2bac6177", size = 1737017 },
+ { url = "https://files.pythonhosted.org/packages/0d/67/8a7eb3afa01e9d0acc26e1ef847c1a9111f8b42b82955fcd9faeb84edeb4/aiohttp-3.12.13-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b8ed8c38a1c584fe99a475a8f60eefc0b682ea413a84c6ce769bb19a7ff1c5ef", size = 1786390 },
+ { url = "https://files.pythonhosted.org/packages/48/19/0377df97dd0176ad23cd8cad4fd4232cfeadcec6c1b7f036315305c98e3f/aiohttp-3.12.13-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7a0b9170d5d800126b5bc89d3053a2363406d6e327afb6afaeda2d19ee8bb103", size = 1708719 },
+ { url = "https://files.pythonhosted.org/packages/61/97/ade1982a5c642b45f3622255173e40c3eed289c169f89d00eeac29a89906/aiohttp-3.12.13-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:372feeace612ef8eb41f05ae014a92121a512bd5067db8f25101dd88a8db11da", size = 1622424 },
+ { url = "https://files.pythonhosted.org/packages/99/ab/00ad3eea004e1d07ccc406e44cfe2b8da5acb72f8c66aeeb11a096798868/aiohttp-3.12.13-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a946d3702f7965d81f7af7ea8fb03bb33fe53d311df48a46eeca17e9e0beed2d", size = 1675447 },
+ { url = "https://files.pythonhosted.org/packages/3f/fe/74e5ce8b2ccaba445fe0087abc201bfd7259431d92ae608f684fcac5d143/aiohttp-3.12.13-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:a0c4725fae86555bbb1d4082129e21de7264f4ab14baf735278c974785cd2041", size = 1707110 },
+ { url = "https://files.pythonhosted.org/packages/ef/c4/39af17807f694f7a267bd8ab1fbacf16ad66740862192a6c8abac2bff813/aiohttp-3.12.13-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:9b28ea2f708234f0a5c44eb6c7d9eb63a148ce3252ba0140d050b091b6e842d1", size = 1649706 },
+ { url = "https://files.pythonhosted.org/packages/38/e8/f5a0a5f44f19f171d8477059aa5f28a158d7d57fe1a46c553e231f698435/aiohttp-3.12.13-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d4f5becd2a5791829f79608c6f3dc745388162376f310eb9c142c985f9441cc1", size = 1725839 },
+ { url = "https://files.pythonhosted.org/packages/fd/ac/81acc594c7f529ef4419d3866913f628cd4fa9cab17f7bf410a5c3c04c53/aiohttp-3.12.13-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:60f2ce6b944e97649051d5f5cc0f439360690b73909230e107fd45a359d3e911", size = 1759311 },
+ { url = "https://files.pythonhosted.org/packages/38/0d/aabe636bd25c6ab7b18825e5a97d40024da75152bec39aa6ac8b7a677630/aiohttp-3.12.13-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:69fc1909857401b67bf599c793f2183fbc4804717388b0b888f27f9929aa41f3", size = 1708202 },
+ { url = "https://files.pythonhosted.org/packages/1f/ab/561ef2d8a223261683fb95a6283ad0d36cb66c87503f3a7dde7afe208bb2/aiohttp-3.12.13-cp313-cp313-win32.whl", hash = "sha256:7d7e68787a2046b0e44ba5587aa723ce05d711e3a3665b6b7545328ac8e3c0dd", size = 420794 },
+ { url = "https://files.pythonhosted.org/packages/9d/47/b11d0089875a23bff0abd3edb5516bcd454db3fefab8604f5e4b07bd6210/aiohttp-3.12.13-cp313-cp313-win_amd64.whl", hash = "sha256:5a178390ca90419bfd41419a809688c368e63c86bd725e1186dd97f6b89c2706", size = 446735 },
+ { url = "https://files.pythonhosted.org/packages/05/7e/0f6b2b4797ac364b6ecc9176bb2dd24d4a9aeaa77ecb093c7f87e44dfbd6/aiohttp-3.12.13-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:36f6c973e003dc9b0bb4e8492a643641ea8ef0e97ff7aaa5c0f53d68839357b4", size = 704988 },
+ { url = "https://files.pythonhosted.org/packages/52/38/d51ea984c777b203959030895c1c8b1f9aac754f8e919e4942edce05958e/aiohttp-3.12.13-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6cbfc73179bd67c229eb171e2e3745d2afd5c711ccd1e40a68b90427f282eab1", size = 479967 },
+ { url = "https://files.pythonhosted.org/packages/9d/0a/62f1c2914840eb2184939e773b65e1e5d6b651b78134798263467f0d2467/aiohttp-3.12.13-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1e8b27b2d414f7e3205aa23bb4a692e935ef877e3a71f40d1884f6e04fd7fa74", size = 467373 },
+ { url = "https://files.pythonhosted.org/packages/7b/4e/327a4b56bb940afb03ee45d5fd1ef7dae5ed6617889d61ed8abf0548310b/aiohttp-3.12.13-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eabded0c2b2ef56243289112c48556c395d70150ce4220d9008e6b4b3dd15690", size = 1642326 },
+ { url = "https://files.pythonhosted.org/packages/55/5d/f0277aad4d85a56cd6102335d5111c7c6d1f98cb760aa485e4fe11a24f52/aiohttp-3.12.13-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:003038e83f1a3ff97409999995ec02fe3008a1d675478949643281141f54751d", size = 1616820 },
+ { url = "https://files.pythonhosted.org/packages/f2/ff/909193459a6d32ee806d9f7ae2342c940ee97d2c1416140c5aec3bd6bfc0/aiohttp-3.12.13-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1b6f46613031dbc92bdcaad9c4c22c7209236ec501f9c0c5f5f0b6a689bf50f3", size = 1690448 },
+ { url = "https://files.pythonhosted.org/packages/45/e7/14d09183849e9bd69d8d5bf7df0ab7603996b83b00540e0890eeefa20e1e/aiohttp-3.12.13-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c332c6bb04650d59fb94ed96491f43812549a3ba6e7a16a218e612f99f04145e", size = 1729763 },
+ { url = "https://files.pythonhosted.org/packages/55/01/07b980d6226574cc2d157fa4978a3d77270a4e860193a579630a81b30e30/aiohttp-3.12.13-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3fea41a2c931fb582cb15dc86a3037329e7b941df52b487a9f8b5aa960153cbd", size = 1636002 },
+ { url = "https://files.pythonhosted.org/packages/73/cf/20a1f75ca3d8e48065412e80b79bb1c349e26a4fa51d660be186a9c0c1e3/aiohttp-3.12.13-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:846104f45d18fb390efd9b422b27d8f3cf8853f1218c537f36e71a385758c896", size = 1571003 },
+ { url = "https://files.pythonhosted.org/packages/e1/99/09520d83e5964d6267074be9c66698e2003dfe8c66465813f57b029dec8c/aiohttp-3.12.13-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:5d6c85ac7dd350f8da2520bac8205ce99df4435b399fa7f4dc4a70407073e390", size = 1618964 },
+ { url = "https://files.pythonhosted.org/packages/3a/01/c68f2c7632441fbbfc4a835e003e61eb1d63531857b0a2b73c9698846fa8/aiohttp-3.12.13-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:5a1ecce0ed281bec7da8550da052a6b89552db14d0a0a45554156f085a912f48", size = 1629103 },
+ { url = "https://files.pythonhosted.org/packages/fb/fe/f9540bf12fa443d8870ecab70260c02140ed8b4c37884a2e1050bdd689a2/aiohttp-3.12.13-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:5304d74867028cca8f64f1cc1215eb365388033c5a691ea7aa6b0dc47412f495", size = 1605745 },
+ { url = "https://files.pythonhosted.org/packages/91/d7/526f1d16ca01e0c995887097b31e39c2e350dc20c1071e9b2dcf63a86fcd/aiohttp-3.12.13-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:64d1f24ee95a2d1e094a4cd7a9b7d34d08db1bbcb8aa9fb717046b0a884ac294", size = 1693348 },
+ { url = "https://files.pythonhosted.org/packages/cd/0a/c103fdaab6fbde7c5f10450b5671dca32cea99800b1303ee8194a799bbb9/aiohttp-3.12.13-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:119c79922a7001ca6a9e253228eb39b793ea994fd2eccb79481c64b5f9d2a055", size = 1709023 },
+ { url = "https://files.pythonhosted.org/packages/2f/bc/b8d14e754b5e0bf9ecf6df4b930f2cbd6eaaafcdc1b2f9271968747fb6e3/aiohttp-3.12.13-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:bb18f00396d22e2f10cd8825d671d9f9a3ba968d708a559c02a627536b36d91c", size = 1638691 },
+ { url = "https://files.pythonhosted.org/packages/a4/7b/44b77bf4c48d95d81af5c57e79337d0d51350a85a84e9997a99a6205c441/aiohttp-3.12.13-cp39-cp39-win32.whl", hash = "sha256:0022de47ef63fd06b065d430ac79c6b0bd24cdae7feaf0e8c6bac23b805a23a8", size = 428365 },
+ { url = "https://files.pythonhosted.org/packages/e5/cb/aaa022eb993e7d51928dc22d743ed17addb40142250e829701c5e6679615/aiohttp-3.12.13-cp39-cp39-win_amd64.whl", hash = "sha256:29e08111ccf81b2734ae03f1ad1cb03b9615e7d8f616764f22f71209c094f122", size = 451652 },
+]
+
+[[package]]
+name = "aiosignal"
+version = "1.3.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "frozenlist" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ba/b5/6d55e80f6d8a08ce22b982eafa278d823b541c925f11ee774b0b9c43473d/aiosignal-1.3.2.tar.gz", hash = "sha256:a8c255c66fafb1e499c9351d0bf32ff2d8a0321595ebac3b93713656d2436f54", size = 19424 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ec/6a/bc7e17a3e87a2985d3e8f4da4cd0f481060eb78fb08596c42be62c90a4d9/aiosignal-1.3.2-py2.py3-none-any.whl", hash = "sha256:45cde58e409a301715980c2b01d0c28bdde3770d8290b5eb2173759d9acb31a5", size = 7597 },
+]
+
+[[package]]
+name = "aiosqlite"
+version = "0.21.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/13/7d/8bca2bf9a247c2c5dfeec1d7a5f40db6518f88d314b8bca9da29670d2671/aiosqlite-0.21.0.tar.gz", hash = "sha256:131bb8056daa3bc875608c631c678cda73922a2d4ba8aec373b19f18c17e7aa3", size = 13454 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f5/10/6c25ed6de94c49f88a91fa5018cb4c0f3625f31d5be9f771ebe5cc7cd506/aiosqlite-0.21.0-py3-none-any.whl", hash = "sha256:2549cf4057f95f53dcba16f2b64e8e2791d7e1adedb13197dd8ed77bb226d7d0", size = 15792 },
+]
+
+[[package]]
+name = "airportsdata"
+version = "20250523"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4f/0d/72a1dcdf3c70ece43a4d8ce1337b1b8683f8c47ca9f7b1ba8355baa550e0/airportsdata-20250523.tar.gz", hash = "sha256:78e0eb72efccd63bda2decf1c6ec0a8e1d3ae8312764a85baa56496607c8f3de", size = 903156 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/88/72/b78feb161ae6c82c6fb45d0eb6cb1881bc04c05207646e1ecd936a0d6c35/airportsdata-20250523-py3-none-any.whl", hash = "sha256:88ce8a928ee45d650b5214a3b16273f0bf1d04a4494c78a216aea067e42a0233", size = 912679 },
+]
+
+[[package]]
+name = "annotated-types"
+version = "0.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643 },
+]
+
+[[package]]
+name = "anthropic"
+version = "0.54.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "distro" },
+ { name = "httpx" },
+ { name = "jiter" },
+ { name = "pydantic" },
+ { name = "sniffio" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/89/28/80cb9bb6e7ce77d404145b51da4257455805c17f0a6be528ff3286e3882f/anthropic-0.54.0.tar.gz", hash = "sha256:5e6f997d97ce8e70eac603c3ec2e7f23addeff953fbbb76b19430562bb6ba815", size = 312376 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/b9/6ffb48e82c5e97b03cecee872d134a6b6666c2767b2d32ed709f3a60a8fe/anthropic-0.54.0-py3-none-any.whl", hash = "sha256:c1062a0a905daeec17ca9c06c401e4b3f24cb0495841d29d752568a1d4018d56", size = 288774 },
+]
+
+[[package]]
+name = "anyio"
+version = "4.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
+ { name = "idna" },
+ { name = "sniffio" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/95/7d/4c1bd541d4dffa1b52bd83fb8527089e097a106fc90b467a7313b105f840/anyio-4.9.0.tar.gz", hash = "sha256:673c0c244e15788651a4ff38710fea9675823028a6f08a5eda409e0c9840a028", size = 190949 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a1/ee/48ca1a7c89ffec8b6a0c5d02b89c305671d5ffd8d3c94acf8b8c408575bb/anyio-4.9.0-py3-none-any.whl", hash = "sha256:9f76d541cad6e36af7beb62e978876f3b41e3e04f2c1fbf0884604c0a9c4d93c", size = 100916 },
+]
+
+[[package]]
+name = "asttokens"
+version = "3.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4a/e7/82da0a03e7ba5141f05cce0d302e6eed121ae055e0456ca228bf693984bc/asttokens-3.0.0.tar.gz", hash = "sha256:0dcd8baa8d62b0c1d118b399b2ddba3c4aff271d0d7a9e0d4c1681c79035bbc7", size = 61978 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl", hash = "sha256:e3078351a059199dd5138cb1c706e6430c05eff2ff136af5eb4790f9d28932e2", size = 26918 },
+]
+
+[[package]]
+name = "async-timeout"
+version = "5.0.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a5/ae/136395dfbfe00dfc94da3f3e136d0b13f394cba8f4841120e34226265780/async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3", size = 9274 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fe/ba/e2081de779ca30d473f21f5b30e0e737c438205440784c7dfc81efc2b029/async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c", size = 6233 },
+]
+
+[[package]]
+name = "attrs"
+version = "25.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/5a/b0/1367933a8532ee6ff8d63537de4f1177af4bff9f3e829baf7331f595bb24/attrs-25.3.0.tar.gz", hash = "sha256:75d7cefc7fb576747b2c81b4442d4d4a1ce0900973527c011d1030fd3bf4af1b", size = 812032 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/77/06/bb80f5f86020c4551da315d78b3ab75e8228f89f0162f2c3a819e407941a/attrs-25.3.0-py3-none-any.whl", hash = "sha256:427318ce031701fea540783410126f03899a97ffc6f61596ad581ac2e40e3bc3", size = 63815 },
+]
+
+[[package]]
+name = "banks"
+version = "2.1.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "deprecated" },
+ { name = "eval-type-backport", marker = "python_full_version < '3.10'" },
+ { name = "griffe" },
+ { name = "jinja2" },
+ { name = "platformdirs" },
+ { name = "pydantic" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/21/5f/08a0c087581726044536e198c011742ccb9ced6061575f1ed00c034e6443/banks-2.1.3.tar.gz", hash = "sha256:c0dd2cb0c5487274a513a552827e6a8ddbd0ab1a1b967f177e71a6e4748a3ed2", size = 177311 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fe/27/a30c24a74cc4f3969f3e0d184da149fa6327620c7c72333ccc3a8e3e1095/banks-2.1.3-py3-none-any.whl", hash = "sha256:9e1217dc977e6dd1ce42c5ff48e9bcaf238d788c81b42deb6a555615ffcffbab", size = 28133 },
+]
+
+[[package]]
+name = "beautifulsoup4"
+version = "4.13.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "soupsieve" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d8/e4/0c4c39e18fd76d6a628d4dd8da40543d136ce2d1752bd6eeeab0791f4d6b/beautifulsoup4-4.13.4.tar.gz", hash = "sha256:dbb3c4e1ceae6aefebdaf2423247260cd062430a410e38c66f2baa50a8437195", size = 621067 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/50/cd/30110dc0ffcf3b131156077b90e9f60ed75711223f306da4db08eff8403b/beautifulsoup4-4.13.4-py3-none-any.whl", hash = "sha256:9bbbb14bfde9d79f38b8cd5f8c7c85f4b8f2523190ebed90e950a8dea4cb1c4b", size = 187285 },
+]
+
+[[package]]
+name = "black"
+version = "25.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "mypy-extensions" },
+ { name = "packaging" },
+ { name = "pathspec" },
+ { name = "platformdirs" },
+ { name = "tomli", marker = "python_full_version < '3.11'" },
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/94/49/26a7b0f3f35da4b5a65f081943b7bcd22d7002f5f0fb8098ec1ff21cb6ef/black-25.1.0.tar.gz", hash = "sha256:33496d5cd1222ad73391352b4ae8da15253c5de89b93a80b3e2c8d9a19ec2666", size = 649449 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4d/3b/4ba3f93ac8d90410423fdd31d7541ada9bcee1df32fb90d26de41ed40e1d/black-25.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:759e7ec1e050a15f89b770cefbf91ebee8917aac5c20483bc2d80a6c3a04df32", size = 1629419 },
+ { url = "https://files.pythonhosted.org/packages/b4/02/0bde0485146a8a5e694daed47561785e8b77a0466ccc1f3e485d5ef2925e/black-25.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0e519ecf93120f34243e6b0054db49c00a35f84f195d5bce7e9f5cfc578fc2da", size = 1461080 },
+ { url = "https://files.pythonhosted.org/packages/52/0e/abdf75183c830eaca7589144ff96d49bce73d7ec6ad12ef62185cc0f79a2/black-25.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:055e59b198df7ac0b7efca5ad7ff2516bca343276c466be72eb04a3bcc1f82d7", size = 1766886 },
+ { url = "https://files.pythonhosted.org/packages/dc/a6/97d8bb65b1d8a41f8a6736222ba0a334db7b7b77b8023ab4568288f23973/black-25.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:db8ea9917d6f8fc62abd90d944920d95e73c83a5ee3383493e35d271aca872e9", size = 1419404 },
+ { url = "https://files.pythonhosted.org/packages/7e/4f/87f596aca05c3ce5b94b8663dbfe242a12843caaa82dd3f85f1ffdc3f177/black-25.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a39337598244de4bae26475f77dda852ea00a93bd4c728e09eacd827ec929df0", size = 1614372 },
+ { url = "https://files.pythonhosted.org/packages/e7/d0/2c34c36190b741c59c901e56ab7f6e54dad8df05a6272a9747ecef7c6036/black-25.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:96c1c7cd856bba8e20094e36e0f948718dc688dba4a9d78c3adde52b9e6c2299", size = 1442865 },
+ { url = "https://files.pythonhosted.org/packages/21/d4/7518c72262468430ead45cf22bd86c883a6448b9eb43672765d69a8f1248/black-25.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bce2e264d59c91e52d8000d507eb20a9aca4a778731a08cfff7e5ac4a4bb7096", size = 1749699 },
+ { url = "https://files.pythonhosted.org/packages/58/db/4f5beb989b547f79096e035c4981ceb36ac2b552d0ac5f2620e941501c99/black-25.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:172b1dbff09f86ce6f4eb8edf9dede08b1fce58ba194c87d7a4f1a5aa2f5b3c2", size = 1428028 },
+ { url = "https://files.pythonhosted.org/packages/83/71/3fe4741df7adf015ad8dfa082dd36c94ca86bb21f25608eb247b4afb15b2/black-25.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4b60580e829091e6f9238c848ea6750efed72140b91b048770b64e74fe04908b", size = 1650988 },
+ { url = "https://files.pythonhosted.org/packages/13/f3/89aac8a83d73937ccd39bbe8fc6ac8860c11cfa0af5b1c96d081facac844/black-25.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e2978f6df243b155ef5fa7e558a43037c3079093ed5d10fd84c43900f2d8ecc", size = 1453985 },
+ { url = "https://files.pythonhosted.org/packages/6f/22/b99efca33f1f3a1d2552c714b1e1b5ae92efac6c43e790ad539a163d1754/black-25.1.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b48735872ec535027d979e8dcb20bf4f70b5ac75a8ea99f127c106a7d7aba9f", size = 1783816 },
+ { url = "https://files.pythonhosted.org/packages/18/7e/a27c3ad3822b6f2e0e00d63d58ff6299a99a5b3aee69fa77cd4b0076b261/black-25.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:ea0213189960bda9cf99be5b8c8ce66bb054af5e9e861249cd23471bd7b0b3ba", size = 1440860 },
+ { url = "https://files.pythonhosted.org/packages/98/87/0edf98916640efa5d0696e1abb0a8357b52e69e82322628f25bf14d263d1/black-25.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8f0b18a02996a836cc9c9c78e5babec10930862827b1b724ddfe98ccf2f2fe4f", size = 1650673 },
+ { url = "https://files.pythonhosted.org/packages/52/e5/f7bf17207cf87fa6e9b676576749c6b6ed0d70f179a3d812c997870291c3/black-25.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:afebb7098bfbc70037a053b91ae8437c3857482d3a690fefc03e9ff7aa9a5fd3", size = 1453190 },
+ { url = "https://files.pythonhosted.org/packages/e3/ee/adda3d46d4a9120772fae6de454c8495603c37c4c3b9c60f25b1ab6401fe/black-25.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:030b9759066a4ee5e5aca28c3c77f9c64789cdd4de8ac1df642c40b708be6171", size = 1782926 },
+ { url = "https://files.pythonhosted.org/packages/cc/64/94eb5f45dcb997d2082f097a3944cfc7fe87e071907f677e80788a2d7b7a/black-25.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:a22f402b410566e2d1c950708c77ebf5ebd5d0d88a6a2e87c86d9fb48afa0d18", size = 1442613 },
+ { url = "https://files.pythonhosted.org/packages/d3/b6/ae7507470a4830dbbfe875c701e84a4a5fb9183d1497834871a715716a92/black-25.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a1ee0a0c330f7b5130ce0caed9936a904793576ef4d2b98c40835d6a65afa6a0", size = 1628593 },
+ { url = "https://files.pythonhosted.org/packages/24/c1/ae36fa59a59f9363017ed397750a0cd79a470490860bc7713967d89cdd31/black-25.1.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f3df5f1bf91d36002b0a75389ca8663510cf0531cca8aa5c1ef695b46d98655f", size = 1460000 },
+ { url = "https://files.pythonhosted.org/packages/ac/b6/98f832e7a6c49aa3a464760c67c7856363aa644f2f3c74cf7d624168607e/black-25.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d9e6827d563a2c820772b32ce8a42828dc6790f095f441beef18f96aa6f8294e", size = 1765963 },
+ { url = "https://files.pythonhosted.org/packages/ce/e9/2cb0a017eb7024f70e0d2e9bdb8c5a5b078c5740c7f8816065d06f04c557/black-25.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:bacabb307dca5ebaf9c118d2d2f6903da0d62c9faa82bd21a33eecc319559355", size = 1419419 },
+ { url = "https://files.pythonhosted.org/packages/09/71/54e999902aed72baf26bca0d50781b01838251a462612966e9fc4891eadd/black-25.1.0-py3-none-any.whl", hash = "sha256:95e8176dae143ba9097f351d174fdaf0ccd29efb414b362ae3fd72bf0f710717", size = 207646 },
+]
+
+[[package]]
+name = "blinker"
+version = "1.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458 },
+]
+
+[[package]]
+name = "blobfile"
+version = "3.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "filelock" },
+ { name = "lxml" },
+ { name = "pycryptodomex" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9d/a9/a34e8153b0203d9060ff7aa5dfcd175e161117949697a83c4cc003b523ff/blobfile-3.0.0.tar.gz", hash = "sha256:32ec777414de7bb2a76ca812a838f0d33327ca28ae844a253503cde625cdf2f1", size = 77863 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ed/4d/1392562369b1139e741b30d624f09fe7091d17dd5579fae5732f044b12bb/blobfile-3.0.0-py3-none-any.whl", hash = "sha256:48ecc3307e622804bd8fe13bf6f40e6463c4439eba7a1f9ad49fd78aa63cc658", size = 75413 },
+]
+
+[[package]]
+name = "boto3"
+version = "1.7.84"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "botocore", version = "1.10.84", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "jmespath", version = "0.10.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "s3transfer", version = "0.1.13", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/2f/2b/7010a5189859eec725c36081b1d1c8e721000ebdf81a1682ec6b64e1c373/boto3-1.7.84.tar.gz", hash = "sha256:64496f2c814e454e26c024df86bd08fb4643770d0e2b7a8fd70055fc6683eb9d", size = 93151 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ac/6e/faf7c6c3ae59641c75023fb5dcc8a02c33752ac8ccadf9931e8d8364f2fe/boto3-1.7.84-py2.py3-none-any.whl", hash = "sha256:0ed4b107c3b4550547aaec3c9bb17df068ff92d1f6f4781205800e2cb8a66de5", size = 128502 },
+]
+
+[[package]]
+name = "boto3"
+version = "1.38.36"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "botocore", version = "1.38.36", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "jmespath", version = "1.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "s3transfer", version = "0.13.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c4/22/df130d30dcc73b726c3d254ed855806853b86b987052517337587085b6db/boto3-1.38.36.tar.gz", hash = "sha256:efe0aaa060f8fedd76e5c942055f051aee0432fc722d79d8830a9fd9db83593e", size = 111823 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/24/ce/f609adc7dfd53792a9b704aa1241f8e5f34c21a5364f64b114d7874f8327/boto3-1.38.36-py3-none-any.whl", hash = "sha256:34c27d7317cadb62c0e9856e5d5aa0271ef47202d340584831048bc7ac904136", size = 139938 },
+]
+
+[[package]]
+name = "botocore"
+version = "1.10.84"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "docutils", marker = "python_full_version < '3.10'" },
+ { name = "jmespath", version = "0.10.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "python-dateutil", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/67/01/43759329a6f7036aa739e86d446b908fa207222e224e537cd3d66fdb4c29/botocore-1.10.84.tar.gz", hash = "sha256:d3e4b5a2c903ea30d19d41ea2f65d0e51dce54f4f4c4dfd6ecd7b04f240844a8", size = 4612644 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/01/b7/cb08cd1af2bb0d0dfb393101a93b6ab6fb80f109ab7b37f2f34386c11351/botocore-1.10.84-py2.py3-none-any.whl", hash = "sha256:380852e1adb9ba4ba9ff096af61f88a6888197b86e580e1bd786f04ebe6f9c0c", size = 4478913 },
+]
+
+[[package]]
+name = "botocore"
+version = "1.38.36"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "jmespath", version = "1.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "python-dateutil", marker = "python_full_version >= '3.10'" },
+ { name = "urllib3", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/2e/15/d218917f2d568f6fa92ad3831b31ecc4ee514d775a142385aa87c672bc08/botocore-1.38.36.tar.gz", hash = "sha256:4a1ced1a4218bdff0ed5b46abb54570d473154ddefafa5d121a8d96e4b76ebc1", size = 13966245 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/75/2d/3ccc58837b3ed8322a15b9fd94114a326e6ab29d36a37508aadf9cf7808e/botocore-1.38.36-py3-none-any.whl", hash = "sha256:b6a50b853f6d23af9edfed89a59800c6bc1687a947cdd3492879f7d64e002d30", size = 13623866 },
+]
+
+[[package]]
+name = "brotli"
+version = "1.1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2f/c2/f9e977608bdf958650638c3f1e28f85a1b075f075ebbe77db8555463787b/Brotli-1.1.0.tar.gz", hash = "sha256:81de08ac11bcb85841e440c13611c00b67d3bf82698314928d0b676362546724", size = 7372270 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6d/3a/dbf4fb970c1019a57b5e492e1e0eae745d32e59ba4d6161ab5422b08eefe/Brotli-1.1.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e1140c64812cb9b06c922e77f1c26a75ec5e3f0fb2bf92cc8c58720dec276752", size = 873045 },
+ { url = "https://files.pythonhosted.org/packages/dd/11/afc14026ea7f44bd6eb9316d800d439d092c8d508752055ce8d03086079a/Brotli-1.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c8fd5270e906eef71d4a8d19b7c6a43760c6abcfcc10c9101d14eb2357418de9", size = 446218 },
+ { url = "https://files.pythonhosted.org/packages/36/83/7545a6e7729db43cb36c4287ae388d6885c85a86dd251768a47015dfde32/Brotli-1.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1ae56aca0402a0f9a3431cddda62ad71666ca9d4dc3a10a142b9dce2e3c0cda3", size = 2903872 },
+ { url = "https://files.pythonhosted.org/packages/32/23/35331c4d9391fcc0f29fd9bec2c76e4b4eeab769afbc4b11dd2e1098fb13/Brotli-1.1.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:43ce1b9935bfa1ede40028054d7f48b5469cd02733a365eec8a329ffd342915d", size = 2941254 },
+ { url = "https://files.pythonhosted.org/packages/3b/24/1671acb450c902edb64bd765d73603797c6c7280a9ada85a195f6b78c6e5/Brotli-1.1.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:7c4855522edb2e6ae7fdb58e07c3ba9111e7621a8956f481c68d5d979c93032e", size = 2857293 },
+ { url = "https://files.pythonhosted.org/packages/d5/00/40f760cc27007912b327fe15bf6bfd8eaecbe451687f72a8abc587d503b3/Brotli-1.1.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:38025d9f30cf4634f8309c6874ef871b841eb3c347e90b0851f63d1ded5212da", size = 3002385 },
+ { url = "https://files.pythonhosted.org/packages/b8/cb/8aaa83f7a4caa131757668c0fb0c4b6384b09ffa77f2fba9570d87ab587d/Brotli-1.1.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:e6a904cb26bfefc2f0a6f240bdf5233be78cd2488900a2f846f3c3ac8489ab80", size = 2911104 },
+ { url = "https://files.pythonhosted.org/packages/bc/c4/65456561d89d3c49f46b7fbeb8fe6e449f13bdc8ea7791832c5d476b2faf/Brotli-1.1.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:a37b8f0391212d29b3a91a799c8e4a2855e0576911cdfb2515487e30e322253d", size = 2809981 },
+ { url = "https://files.pythonhosted.org/packages/05/1b/cf49528437bae28abce5f6e059f0d0be6fecdcc1d3e33e7c54b3ca498425/Brotli-1.1.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:e84799f09591700a4154154cab9787452925578841a94321d5ee8fb9a9a328f0", size = 2935297 },
+ { url = "https://files.pythonhosted.org/packages/81/ff/190d4af610680bf0c5a09eb5d1eac6e99c7c8e216440f9c7cfd42b7adab5/Brotli-1.1.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:f66b5337fa213f1da0d9000bc8dc0cb5b896b726eefd9c6046f699b169c41b9e", size = 2930735 },
+ { url = "https://files.pythonhosted.org/packages/80/7d/f1abbc0c98f6e09abd3cad63ec34af17abc4c44f308a7a539010f79aae7a/Brotli-1.1.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5dab0844f2cf82be357a0eb11a9087f70c5430b2c241493fc122bb6f2bb0917c", size = 2933107 },
+ { url = "https://files.pythonhosted.org/packages/34/ce/5a5020ba48f2b5a4ad1c0522d095ad5847a0be508e7d7569c8630ce25062/Brotli-1.1.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e4fe605b917c70283db7dfe5ada75e04561479075761a0b3866c081d035b01c1", size = 2845400 },
+ { url = "https://files.pythonhosted.org/packages/44/89/fa2c4355ab1eecf3994e5a0a7f5492c6ff81dfcb5f9ba7859bd534bb5c1a/Brotli-1.1.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:1e9a65b5736232e7a7f91ff3d02277f11d339bf34099a56cdab6a8b3410a02b2", size = 3031985 },
+ { url = "https://files.pythonhosted.org/packages/af/a4/79196b4a1674143d19dca400866b1a4d1a089040df7b93b88ebae81f3447/Brotli-1.1.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:58d4b711689366d4a03ac7957ab8c28890415e267f9b6589969e74b6e42225ec", size = 2927099 },
+ { url = "https://files.pythonhosted.org/packages/e9/54/1c0278556a097f9651e657b873ab08f01b9a9ae4cac128ceb66427d7cd20/Brotli-1.1.0-cp310-cp310-win32.whl", hash = "sha256:be36e3d172dc816333f33520154d708a2657ea63762ec16b62ece02ab5e4daf2", size = 333172 },
+ { url = "https://files.pythonhosted.org/packages/f7/65/b785722e941193fd8b571afd9edbec2a9b838ddec4375d8af33a50b8dab9/Brotli-1.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:0c6244521dda65ea562d5a69b9a26120769b7a9fb3db2fe9545935ed6735b128", size = 357255 },
+ { url = "https://files.pythonhosted.org/packages/96/12/ad41e7fadd5db55459c4c401842b47f7fee51068f86dd2894dd0dcfc2d2a/Brotli-1.1.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a3daabb76a78f829cafc365531c972016e4aa8d5b4bf60660ad8ecee19df7ccc", size = 873068 },
+ { url = "https://files.pythonhosted.org/packages/95/4e/5afab7b2b4b61a84e9c75b17814198ce515343a44e2ed4488fac314cd0a9/Brotli-1.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c8146669223164fc87a7e3de9f81e9423c67a79d6b3447994dfb9c95da16e2d6", size = 446244 },
+ { url = "https://files.pythonhosted.org/packages/9d/e6/f305eb61fb9a8580c525478a4a34c5ae1a9bcb12c3aee619114940bc513d/Brotli-1.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:30924eb4c57903d5a7526b08ef4a584acc22ab1ffa085faceb521521d2de32dd", size = 2906500 },
+ { url = "https://files.pythonhosted.org/packages/3e/4f/af6846cfbc1550a3024e5d3775ede1e00474c40882c7bf5b37a43ca35e91/Brotli-1.1.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ceb64bbc6eac5a140ca649003756940f8d6a7c444a68af170b3187623b43bebf", size = 2943950 },
+ { url = "https://files.pythonhosted.org/packages/b3/e7/ca2993c7682d8629b62630ebf0d1f3bb3d579e667ce8e7ca03a0a0576a2d/Brotli-1.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a469274ad18dc0e4d316eefa616d1d0c2ff9da369af19fa6f3daa4f09671fd61", size = 2918527 },
+ { url = "https://files.pythonhosted.org/packages/b3/96/da98e7bedc4c51104d29cc61e5f449a502dd3dbc211944546a4cc65500d3/Brotli-1.1.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:524f35912131cc2cabb00edfd8d573b07f2d9f21fa824bd3fb19725a9cf06327", size = 2845489 },
+ { url = "https://files.pythonhosted.org/packages/e8/ef/ccbc16947d6ce943a7f57e1a40596c75859eeb6d279c6994eddd69615265/Brotli-1.1.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:5b3cc074004d968722f51e550b41a27be656ec48f8afaeeb45ebf65b561481dd", size = 2914080 },
+ { url = "https://files.pythonhosted.org/packages/80/d6/0bd38d758d1afa62a5524172f0b18626bb2392d717ff94806f741fcd5ee9/Brotli-1.1.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:19c116e796420b0cee3da1ccec3b764ed2952ccfcc298b55a10e5610ad7885f9", size = 2813051 },
+ { url = "https://files.pythonhosted.org/packages/14/56/48859dd5d129d7519e001f06dcfbb6e2cf6db92b2702c0c2ce7d97e086c1/Brotli-1.1.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:510b5b1bfbe20e1a7b3baf5fed9e9451873559a976c1a78eebaa3b86c57b4265", size = 2938172 },
+ { url = "https://files.pythonhosted.org/packages/3d/77/a236d5f8cd9e9f4348da5acc75ab032ab1ab2c03cc8f430d24eea2672888/Brotli-1.1.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:a1fd8a29719ccce974d523580987b7f8229aeace506952fa9ce1d53a033873c8", size = 2933023 },
+ { url = "https://files.pythonhosted.org/packages/f1/87/3b283efc0f5cb35f7f84c0c240b1e1a1003a5e47141a4881bf87c86d0ce2/Brotli-1.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c247dd99d39e0338a604f8c2b3bc7061d5c2e9e2ac7ba9cc1be5a69cb6cd832f", size = 2935871 },
+ { url = "https://files.pythonhosted.org/packages/f3/eb/2be4cc3e2141dc1a43ad4ca1875a72088229de38c68e842746b342667b2a/Brotli-1.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1b2c248cd517c222d89e74669a4adfa5577e06ab68771a529060cf5a156e9757", size = 2847784 },
+ { url = "https://files.pythonhosted.org/packages/66/13/b58ddebfd35edde572ccefe6890cf7c493f0c319aad2a5badee134b4d8ec/Brotli-1.1.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:2a24c50840d89ded6c9a8fdc7b6ed3692ed4e86f1c4a4a938e1e92def92933e0", size = 3034905 },
+ { url = "https://files.pythonhosted.org/packages/84/9c/bc96b6c7db824998a49ed3b38e441a2cae9234da6fa11f6ed17e8cf4f147/Brotli-1.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f31859074d57b4639318523d6ffdca586ace54271a73ad23ad021acd807eb14b", size = 2929467 },
+ { url = "https://files.pythonhosted.org/packages/e7/71/8f161dee223c7ff7fea9d44893fba953ce97cf2c3c33f78ba260a91bcff5/Brotli-1.1.0-cp311-cp311-win32.whl", hash = "sha256:39da8adedf6942d76dc3e46653e52df937a3c4d6d18fdc94a7c29d263b1f5b50", size = 333169 },
+ { url = "https://files.pythonhosted.org/packages/02/8a/fece0ee1057643cb2a5bbf59682de13f1725f8482b2c057d4e799d7ade75/Brotli-1.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:aac0411d20e345dc0920bdec5548e438e999ff68d77564d5e9463a7ca9d3e7b1", size = 357253 },
+ { url = "https://files.pythonhosted.org/packages/5c/d0/5373ae13b93fe00095a58efcbce837fd470ca39f703a235d2a999baadfbc/Brotli-1.1.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:32d95b80260d79926f5fab3c41701dbb818fde1c9da590e77e571eefd14abe28", size = 815693 },
+ { url = "https://files.pythonhosted.org/packages/8e/48/f6e1cdf86751300c288c1459724bfa6917a80e30dbfc326f92cea5d3683a/Brotli-1.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b760c65308ff1e462f65d69c12e4ae085cff3b332d894637f6273a12a482d09f", size = 422489 },
+ { url = "https://files.pythonhosted.org/packages/06/88/564958cedce636d0f1bed313381dfc4b4e3d3f6015a63dae6146e1b8c65c/Brotli-1.1.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:316cc9b17edf613ac76b1f1f305d2a748f1b976b033b049a6ecdfd5612c70409", size = 873081 },
+ { url = "https://files.pythonhosted.org/packages/58/79/b7026a8bb65da9a6bb7d14329fd2bd48d2b7f86d7329d5cc8ddc6a90526f/Brotli-1.1.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:caf9ee9a5775f3111642d33b86237b05808dafcd6268faa492250e9b78046eb2", size = 446244 },
+ { url = "https://files.pythonhosted.org/packages/e5/18/c18c32ecea41b6c0004e15606e274006366fe19436b6adccc1ae7b2e50c2/Brotli-1.1.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:70051525001750221daa10907c77830bc889cb6d865cc0b813d9db7fefc21451", size = 2906505 },
+ { url = "https://files.pythonhosted.org/packages/08/c8/69ec0496b1ada7569b62d85893d928e865df29b90736558d6c98c2031208/Brotli-1.1.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7f4bf76817c14aa98cc6697ac02f3972cb8c3da93e9ef16b9c66573a68014f91", size = 2944152 },
+ { url = "https://files.pythonhosted.org/packages/ab/fb/0517cea182219d6768113a38167ef6d4eb157a033178cc938033a552ed6d/Brotli-1.1.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d0c5516f0aed654134a2fc936325cc2e642f8a0e096d075209672eb321cff408", size = 2919252 },
+ { url = "https://files.pythonhosted.org/packages/c7/53/73a3431662e33ae61a5c80b1b9d2d18f58dfa910ae8dd696e57d39f1a2f5/Brotli-1.1.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6c3020404e0b5eefd7c9485ccf8393cfb75ec38ce75586e046573c9dc29967a0", size = 2845955 },
+ { url = "https://files.pythonhosted.org/packages/55/ac/bd280708d9c5ebdbf9de01459e625a3e3803cce0784f47d633562cf40e83/Brotli-1.1.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:4ed11165dd45ce798d99a136808a794a748d5dc38511303239d4e2363c0695dc", size = 2914304 },
+ { url = "https://files.pythonhosted.org/packages/76/58/5c391b41ecfc4527d2cc3350719b02e87cb424ef8ba2023fb662f9bf743c/Brotli-1.1.0-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:4093c631e96fdd49e0377a9c167bfd75b6d0bad2ace734c6eb20b348bc3ea180", size = 2814452 },
+ { url = "https://files.pythonhosted.org/packages/c7/4e/91b8256dfe99c407f174924b65a01f5305e303f486cc7a2e8a5d43c8bec3/Brotli-1.1.0-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:7e4c4629ddad63006efa0ef968c8e4751c5868ff0b1c5c40f76524e894c50248", size = 2938751 },
+ { url = "https://files.pythonhosted.org/packages/5a/a6/e2a39a5d3b412938362bbbeba5af904092bf3f95b867b4a3eb856104074e/Brotli-1.1.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:861bf317735688269936f755fa136a99d1ed526883859f86e41a5d43c61d8966", size = 2933757 },
+ { url = "https://files.pythonhosted.org/packages/13/f0/358354786280a509482e0e77c1a5459e439766597d280f28cb097642fc26/Brotli-1.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:87a3044c3a35055527ac75e419dfa9f4f3667a1e887ee80360589eb8c90aabb9", size = 2936146 },
+ { url = "https://files.pythonhosted.org/packages/80/f7/daf538c1060d3a88266b80ecc1d1c98b79553b3f117a485653f17070ea2a/Brotli-1.1.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c5529b34c1c9d937168297f2c1fde7ebe9ebdd5e121297ff9c043bdb2ae3d6fb", size = 2848055 },
+ { url = "https://files.pythonhosted.org/packages/ad/cf/0eaa0585c4077d3c2d1edf322d8e97aabf317941d3a72d7b3ad8bce004b0/Brotli-1.1.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ca63e1890ede90b2e4454f9a65135a4d387a4585ff8282bb72964fab893f2111", size = 3035102 },
+ { url = "https://files.pythonhosted.org/packages/d8/63/1c1585b2aa554fe6dbce30f0c18bdbc877fa9a1bf5ff17677d9cca0ac122/Brotli-1.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e79e6520141d792237c70bcd7a3b122d00f2613769ae0cb61c52e89fd3443839", size = 2930029 },
+ { url = "https://files.pythonhosted.org/packages/5f/3b/4e3fd1893eb3bbfef8e5a80d4508bec17a57bb92d586c85c12d28666bb13/Brotli-1.1.0-cp312-cp312-win32.whl", hash = "sha256:5f4d5ea15c9382135076d2fb28dde923352fe02951e66935a9efaac8f10e81b0", size = 333276 },
+ { url = "https://files.pythonhosted.org/packages/3d/d5/942051b45a9e883b5b6e98c041698b1eb2012d25e5948c58d6bf85b1bb43/Brotli-1.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:906bc3a79de8c4ae5b86d3d75a8b77e44404b0f4261714306e3ad248d8ab0951", size = 357255 },
+ { url = "https://files.pythonhosted.org/packages/0a/9f/fb37bb8ffc52a8da37b1c03c459a8cd55df7a57bdccd8831d500e994a0ca/Brotli-1.1.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8bf32b98b75c13ec7cf774164172683d6e7891088f6316e54425fde1efc276d5", size = 815681 },
+ { url = "https://files.pythonhosted.org/packages/06/b3/dbd332a988586fefb0aa49c779f59f47cae76855c2d00f450364bb574cac/Brotli-1.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7bc37c4d6b87fb1017ea28c9508b36bbcb0c3d18b4260fcdf08b200c74a6aee8", size = 422475 },
+ { url = "https://files.pythonhosted.org/packages/bb/80/6aaddc2f63dbcf2d93c2d204e49c11a9ec93a8c7c63261e2b4bd35198283/Brotli-1.1.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c0ef38c7a7014ffac184db9e04debe495d317cc9c6fb10071f7fefd93100a4f", size = 2906173 },
+ { url = "https://files.pythonhosted.org/packages/ea/1d/e6ca79c96ff5b641df6097d299347507d39a9604bde8915e76bf026d6c77/Brotli-1.1.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:91d7cc2a76b5567591d12c01f019dd7afce6ba8cba6571187e21e2fc418ae648", size = 2943803 },
+ { url = "https://files.pythonhosted.org/packages/ac/a3/d98d2472e0130b7dd3acdbb7f390d478123dbf62b7d32bda5c830a96116d/Brotli-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a93dde851926f4f2678e704fadeb39e16c35d8baebd5252c9fd94ce8ce68c4a0", size = 2918946 },
+ { url = "https://files.pythonhosted.org/packages/c4/a5/c69e6d272aee3e1423ed005d8915a7eaa0384c7de503da987f2d224d0721/Brotli-1.1.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f0db75f47be8b8abc8d9e31bc7aad0547ca26f24a54e6fd10231d623f183d089", size = 2845707 },
+ { url = "https://files.pythonhosted.org/packages/58/9f/4149d38b52725afa39067350696c09526de0125ebfbaab5acc5af28b42ea/Brotli-1.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6967ced6730aed543b8673008b5a391c3b1076d834ca438bbd70635c73775368", size = 2936231 },
+ { url = "https://files.pythonhosted.org/packages/5a/5a/145de884285611838a16bebfdb060c231c52b8f84dfbe52b852a15780386/Brotli-1.1.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:7eedaa5d036d9336c95915035fb57422054014ebdeb6f3b42eac809928e40d0c", size = 2848157 },
+ { url = "https://files.pythonhosted.org/packages/50/ae/408b6bfb8525dadebd3b3dd5b19d631da4f7d46420321db44cd99dcf2f2c/Brotli-1.1.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d487f5432bf35b60ed625d7e1b448e2dc855422e87469e3f450aa5552b0eb284", size = 3035122 },
+ { url = "https://files.pythonhosted.org/packages/af/85/a94e5cfaa0ca449d8f91c3d6f78313ebf919a0dbd55a100c711c6e9655bc/Brotli-1.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:832436e59afb93e1836081a20f324cb185836c617659b07b129141a8426973c7", size = 2930206 },
+ { url = "https://files.pythonhosted.org/packages/c2/f0/a61d9262cd01351df22e57ad7c34f66794709acab13f34be2675f45bf89d/Brotli-1.1.0-cp313-cp313-win32.whl", hash = "sha256:43395e90523f9c23a3d5bdf004733246fba087f2948f87ab28015f12359ca6a0", size = 333804 },
+ { url = "https://files.pythonhosted.org/packages/7e/c1/ec214e9c94000d1c1974ec67ced1c970c148aa6b8d8373066123fc3dbf06/Brotli-1.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:9011560a466d2eb3f5a6e4929cf4a09be405c64154e12df0dd72713f6500e32b", size = 358517 },
+ { url = "https://files.pythonhosted.org/packages/1b/aa/aa6e0c9848ee4375514af0b27abf470904992939b7363ae78fc8aca8a9a8/Brotli-1.1.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:5fb2ce4b8045c78ebbc7b8f3c15062e435d47e7393cc57c25115cfd49883747a", size = 873048 },
+ { url = "https://files.pythonhosted.org/packages/ae/32/38bba1a8bef9ecb1cda08439fd28d7e9c51aff13b4783a4f1610da90b6c2/Brotli-1.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:7905193081db9bfa73b1219140b3d315831cbff0d8941f22da695832f0dd188f", size = 446207 },
+ { url = "https://files.pythonhosted.org/packages/3c/6a/14cc20ddc53efc274601c8195791a27cfb7acc5e5134e0f8c493a8b8821a/Brotli-1.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a77def80806c421b4b0af06f45d65a136e7ac0bdca3c09d9e2ea4e515367c7e9", size = 2903803 },
+ { url = "https://files.pythonhosted.org/packages/9a/26/62b2d894d4e82d7a7f4e0bb9007a42bbc765697a5679b43186acd68d7a79/Brotli-1.1.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8dadd1314583ec0bf2d1379f7008ad627cd6336625d6679cf2f8e67081b83acf", size = 2941149 },
+ { url = "https://files.pythonhosted.org/packages/a9/ca/00d55bbdd8631236c61777742d8a8454cf6a87eb4125cad675912c68bec7/Brotli-1.1.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:901032ff242d479a0efa956d853d16875d42157f98951c0230f69e69f9c09bac", size = 2672253 },
+ { url = "https://files.pythonhosted.org/packages/e2/e6/4a730f6e5b5d538e92d09bc51bf69119914f29a222f9e1d65ae4abb27a4e/Brotli-1.1.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:22fc2a8549ffe699bfba2256ab2ed0421a7b8fadff114a3d201794e45a9ff578", size = 2757005 },
+ { url = "https://files.pythonhosted.org/packages/cb/6b/8cf297987fe3c1bf1c87f0c0b714af2ce47092b8d307b9f6ecbc65f98968/Brotli-1.1.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ae15b066e5ad21366600ebec29a7ccbc86812ed267e4b28e860b8ca16a2bc474", size = 2910658 },
+ { url = "https://files.pythonhosted.org/packages/2c/1f/be9443995821c933aad7159803f84ef4923c6f5b72c2affd001192b310fc/Brotli-1.1.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:949f3b7c29912693cee0afcf09acd6ebc04c57af949d9bf77d6101ebb61e388c", size = 2809728 },
+ { url = "https://files.pythonhosted.org/packages/76/2f/213bab6efa902658c80a1247142d42b138a27ccdd6bade49ca9cd74e714a/Brotli-1.1.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:89f4988c7203739d48c6f806f1e87a1d96e0806d44f0fba61dba81392c9e474d", size = 2935043 },
+ { url = "https://files.pythonhosted.org/packages/27/89/bbb14fa98e895d1e601491fba54a5feec167d262f0d3d537a3b0d4cd0029/Brotli-1.1.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:de6551e370ef19f8de1807d0a9aa2cdfdce2e85ce88b122fe9f6b2b076837e59", size = 2930639 },
+ { url = "https://files.pythonhosted.org/packages/14/87/03a6d6e1866eddf9f58cc57e35befbeb5514da87a416befe820150cae63f/Brotli-1.1.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:0737ddb3068957cf1b054899b0883830bb1fec522ec76b1098f9b6e0f02d9419", size = 2932834 },
+ { url = "https://files.pythonhosted.org/packages/a4/d5/e5f85e04f75144d1a89421ba432def6bdffc8f28b04f5b7d540bbd03362c/Brotli-1.1.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:4f3607b129417e111e30637af1b56f24f7a49e64763253bbc275c75fa887d4b2", size = 2845213 },
+ { url = "https://files.pythonhosted.org/packages/99/bf/25ef07add7afbb1aacd4460726a1a40370dfd60c0810b6f242a6d3871d7e/Brotli-1.1.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:6c6e0c425f22c1c719c42670d561ad682f7bfeeef918edea971a79ac5252437f", size = 3031573 },
+ { url = "https://files.pythonhosted.org/packages/55/22/948a97bda5c9dc9968d56b9ed722d9727778db43739cf12ef26ff69be94d/Brotli-1.1.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:494994f807ba0b92092a163a0a283961369a65f6cbe01e8891132b7a320e61eb", size = 2926885 },
+ { url = "https://files.pythonhosted.org/packages/31/ba/e53d107399b535ef89deb6977dd8eae468e2dde7b1b74c6cbe2c0e31fda2/Brotli-1.1.0-cp39-cp39-win32.whl", hash = "sha256:f0d8a7a6b5983c2496e364b969f0e526647a06b075d034f3297dc66f3b360c64", size = 333171 },
+ { url = "https://files.pythonhosted.org/packages/99/b3/f7b3af539f74b82e1c64d28685a5200c631cc14ae751d37d6ed819655627/Brotli-1.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:cdad5b9014d83ca68c25d2e9444e28e967ef16e80f6b436918c700c117a85467", size = 357258 },
+]
+
+[[package]]
+name = "brotlicffi"
+version = "1.1.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi", marker = "platform_python_implementation == 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/95/9d/70caa61192f570fcf0352766331b735afa931b4c6bc9a348a0925cc13288/brotlicffi-1.1.0.0.tar.gz", hash = "sha256:b77827a689905143f87915310b93b273ab17888fd43ef350d4832c4a71083c13", size = 465192 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/11/7b96009d3dcc2c931e828ce1e157f03824a69fb728d06bfd7b2fc6f93718/brotlicffi-1.1.0.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:9b7ae6bd1a3f0df532b6d67ff674099a96d22bc0948955cb338488c31bfb8851", size = 453786 },
+ { url = "https://files.pythonhosted.org/packages/d6/e6/a8f46f4a4ee7856fbd6ac0c6fb0dc65ed181ba46cd77875b8d9bbe494d9e/brotlicffi-1.1.0.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:19ffc919fa4fc6ace69286e0a23b3789b4219058313cf9b45625016bf7ff996b", size = 2911165 },
+ { url = "https://files.pythonhosted.org/packages/be/20/201559dff14e83ba345a5ec03335607e47467b6633c210607e693aefac40/brotlicffi-1.1.0.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9feb210d932ffe7798ee62e6145d3a757eb6233aa9a4e7db78dd3690d7755814", size = 2927895 },
+ { url = "https://files.pythonhosted.org/packages/cd/15/695b1409264143be3c933f708a3f81d53c4a1e1ebbc06f46331decbf6563/brotlicffi-1.1.0.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:84763dbdef5dd5c24b75597a77e1b30c66604725707565188ba54bab4f114820", size = 2851834 },
+ { url = "https://files.pythonhosted.org/packages/b4/40/b961a702463b6005baf952794c2e9e0099bde657d0d7e007f923883b907f/brotlicffi-1.1.0.0-cp37-abi3-win32.whl", hash = "sha256:1b12b50e07c3911e1efa3a8971543e7648100713d4e0971b13631cce22c587eb", size = 341731 },
+ { url = "https://files.pythonhosted.org/packages/1c/fa/5408a03c041114ceab628ce21766a4ea882aa6f6f0a800e04ee3a30ec6b9/brotlicffi-1.1.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:994a4f0681bb6c6c3b0925530a1926b7a189d878e6e5e38fae8efa47c5d9c613", size = 366783 },
+ { url = "https://files.pythonhosted.org/packages/e5/3b/bd4f3d2bcf2306ae66b0346f5b42af1962480b200096ffc7abc3bd130eca/brotlicffi-1.1.0.0-pp310-pypy310_pp73-macosx_10_9_x86_64.whl", hash = "sha256:2e4aeb0bd2540cb91b069dbdd54d458da8c4334ceaf2d25df2f4af576d6766ca", size = 397397 },
+ { url = "https://files.pythonhosted.org/packages/54/10/1fd57864449360852c535c2381ee7120ba8f390aa3869df967c44ca7eba1/brotlicffi-1.1.0.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4b7b0033b0d37bb33009fb2fef73310e432e76f688af76c156b3594389d81391", size = 379698 },
+ { url = "https://files.pythonhosted.org/packages/e5/95/15aa422aa6450e6556e54a5fd1650ff59f470aed77ac739aa90ab63dc611/brotlicffi-1.1.0.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:54a07bb2374a1eba8ebb52b6fafffa2afd3c4df85ddd38fcc0511f2bb387c2a8", size = 378635 },
+ { url = "https://files.pythonhosted.org/packages/6c/a7/f254e13b2cb43337d6d99a4ec10394c134e41bfda8a2eff15b75627f4a3d/brotlicffi-1.1.0.0-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7901a7dc4b88f1c1475de59ae9be59799db1007b7d059817948d8e4f12e24e35", size = 385719 },
+ { url = "https://files.pythonhosted.org/packages/72/a9/0971251c4427c14b2a827dba3d910d4d3330dabf23d4278bf6d06a978847/brotlicffi-1.1.0.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:ce01c7316aebc7fce59da734286148b1d1b9455f89cf2c8a4dfce7d41db55c2d", size = 361760 },
+ { url = "https://files.pythonhosted.org/packages/35/9b/e0b577351e1d9d5890e1a56900c4ceaaef783b807145cd229446a43cf437/brotlicffi-1.1.0.0-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:1a807d760763e398bbf2c6394ae9da5815901aa93ee0a37bca5efe78d4ee3171", size = 397392 },
+ { url = "https://files.pythonhosted.org/packages/4f/7f/a16534d28386f74781db8b4544a764cf955abae336379a76f50e745bb0ee/brotlicffi-1.1.0.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fa8ca0623b26c94fccc3a1fdd895be1743b838f3917300506d04aa3346fd2a14", size = 379695 },
+ { url = "https://files.pythonhosted.org/packages/50/2a/699388b5e489726991132441b55aff0691dd73c49105ef220408a5ab98d6/brotlicffi-1.1.0.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3de0cf28a53a3238b252aca9fed1593e9d36c1d116748013339f0949bfc84112", size = 378629 },
+ { url = "https://files.pythonhosted.org/packages/4a/3f/58254e7fbe6011bf043e4dcade0e16995a9f82b731734fad97220d201f42/brotlicffi-1.1.0.0-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6be5ec0e88a4925c91f3dea2bb0013b3a2accda6f77238f76a34a1ea532a1cb0", size = 385712 },
+ { url = "https://files.pythonhosted.org/packages/40/16/2a29a625a6f74d13726387f83484dfaaf6fcdaafaadfbe26a0412ae268cc/brotlicffi-1.1.0.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:d9eb71bb1085d996244439154387266fd23d6ad37161f6f52f1cd41dd95a3808", size = 361747 },
+]
+
+[[package]]
+name = "certifi"
+version = "2025.4.26"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e8/9e/c05b3920a3b7d20d3d3310465f50348e5b3694f4f88c6daf736eef3024c4/certifi-2025.4.26.tar.gz", hash = "sha256:0a816057ea3cdefcef70270d2c515e4506bbc954f417fa5ade2021213bb8f0c6", size = 160705 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4a/7e/3db2bd1b1f9e95f7cddca6d6e75e2f2bd9f51b1246e546d88addca0106bd/certifi-2025.4.26-py3-none-any.whl", hash = "sha256:30350364dfe371162649852c63336a15c70c6510c2ad5015b21c2345311805f3", size = 159618 },
+]
+
+[[package]]
+name = "cffi"
+version = "1.17.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pycparser" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fc/97/c783634659c2920c3fc70419e3af40972dbaf758daa229a7d6ea6135c90d/cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824", size = 516621 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/90/07/f44ca684db4e4f08a3fdc6eeb9a0d15dc6883efc7b8c90357fdbf74e186c/cffi-1.17.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:df8b1c11f177bc2313ec4b2d46baec87a5f3e71fc8b45dab2ee7cae86d9aba14", size = 182191 },
+ { url = "https://files.pythonhosted.org/packages/08/fd/cc2fedbd887223f9f5d170c96e57cbf655df9831a6546c1727ae13fa977a/cffi-1.17.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f2cdc858323644ab277e9bb925ad72ae0e67f69e804f4898c070998d50b1a67", size = 178592 },
+ { url = "https://files.pythonhosted.org/packages/de/cc/4635c320081c78d6ffc2cab0a76025b691a91204f4aa317d568ff9280a2d/cffi-1.17.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:edae79245293e15384b51f88b00613ba9f7198016a5948b5dddf4917d4d26382", size = 426024 },
+ { url = "https://files.pythonhosted.org/packages/b6/7b/3b2b250f3aab91abe5f8a51ada1b717935fdaec53f790ad4100fe2ec64d1/cffi-1.17.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:45398b671ac6d70e67da8e4224a065cec6a93541bb7aebe1b198a61b58c7b702", size = 448188 },
+ { url = "https://files.pythonhosted.org/packages/d3/48/1b9283ebbf0ec065148d8de05d647a986c5f22586b18120020452fff8f5d/cffi-1.17.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ad9413ccdeda48c5afdae7e4fa2192157e991ff761e7ab8fdd8926f40b160cc3", size = 455571 },
+ { url = "https://files.pythonhosted.org/packages/40/87/3b8452525437b40f39ca7ff70276679772ee7e8b394934ff60e63b7b090c/cffi-1.17.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5da5719280082ac6bd9aa7becb3938dc9f9cbd57fac7d2871717b1feb0902ab6", size = 436687 },
+ { url = "https://files.pythonhosted.org/packages/8d/fb/4da72871d177d63649ac449aec2e8a29efe0274035880c7af59101ca2232/cffi-1.17.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bb1a08b8008b281856e5971307cc386a8e9c5b625ac297e853d36da6efe9c17", size = 446211 },
+ { url = "https://files.pythonhosted.org/packages/ab/a0/62f00bcb411332106c02b663b26f3545a9ef136f80d5df746c05878f8c4b/cffi-1.17.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:045d61c734659cc045141be4bae381a41d89b741f795af1dd018bfb532fd0df8", size = 461325 },
+ { url = "https://files.pythonhosted.org/packages/36/83/76127035ed2e7e27b0787604d99da630ac3123bfb02d8e80c633f218a11d/cffi-1.17.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6883e737d7d9e4899a8a695e00ec36bd4e5e4f18fabe0aca0efe0a4b44cdb13e", size = 438784 },
+ { url = "https://files.pythonhosted.org/packages/21/81/a6cd025db2f08ac88b901b745c163d884641909641f9b826e8cb87645942/cffi-1.17.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:6b8b4a92e1c65048ff98cfe1f735ef8f1ceb72e3d5f0c25fdb12087a23da22be", size = 461564 },
+ { url = "https://files.pythonhosted.org/packages/f8/fe/4d41c2f200c4a457933dbd98d3cf4e911870877bd94d9656cc0fcb390681/cffi-1.17.1-cp310-cp310-win32.whl", hash = "sha256:c9c3d058ebabb74db66e431095118094d06abf53284d9c81f27300d0e0d8bc7c", size = 171804 },
+ { url = "https://files.pythonhosted.org/packages/d1/b6/0b0f5ab93b0df4acc49cae758c81fe4e5ef26c3ae2e10cc69249dfd8b3ab/cffi-1.17.1-cp310-cp310-win_amd64.whl", hash = "sha256:0f048dcf80db46f0098ccac01132761580d28e28bc0f78ae0d58048063317e15", size = 181299 },
+ { url = "https://files.pythonhosted.org/packages/6b/f4/927e3a8899e52a27fa57a48607ff7dc91a9ebe97399b357b85a0c7892e00/cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401", size = 182264 },
+ { url = "https://files.pythonhosted.org/packages/6c/f5/6c3a8efe5f503175aaddcbea6ad0d2c96dad6f5abb205750d1b3df44ef29/cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf", size = 178651 },
+ { url = "https://files.pythonhosted.org/packages/94/dd/a3f0118e688d1b1a57553da23b16bdade96d2f9bcda4d32e7d2838047ff7/cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4", size = 445259 },
+ { url = "https://files.pythonhosted.org/packages/2e/ea/70ce63780f096e16ce8588efe039d3c4f91deb1dc01e9c73a287939c79a6/cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41", size = 469200 },
+ { url = "https://files.pythonhosted.org/packages/1c/a0/a4fa9f4f781bda074c3ddd57a572b060fa0df7655d2a4247bbe277200146/cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1", size = 477235 },
+ { url = "https://files.pythonhosted.org/packages/62/12/ce8710b5b8affbcdd5c6e367217c242524ad17a02fe5beec3ee339f69f85/cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6", size = 459721 },
+ { url = "https://files.pythonhosted.org/packages/ff/6b/d45873c5e0242196f042d555526f92aa9e0c32355a1be1ff8c27f077fd37/cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d", size = 467242 },
+ { url = "https://files.pythonhosted.org/packages/1a/52/d9a0e523a572fbccf2955f5abe883cfa8bcc570d7faeee06336fbd50c9fc/cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6", size = 477999 },
+ { url = "https://files.pythonhosted.org/packages/44/74/f2a2460684a1a2d00ca799ad880d54652841a780c4c97b87754f660c7603/cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f", size = 454242 },
+ { url = "https://files.pythonhosted.org/packages/f8/4a/34599cac7dfcd888ff54e801afe06a19c17787dfd94495ab0c8d35fe99fb/cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b", size = 478604 },
+ { url = "https://files.pythonhosted.org/packages/34/33/e1b8a1ba29025adbdcda5fb3a36f94c03d771c1b7b12f726ff7fef2ebe36/cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655", size = 171727 },
+ { url = "https://files.pythonhosted.org/packages/3d/97/50228be003bb2802627d28ec0627837ac0bf35c90cf769812056f235b2d1/cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0", size = 181400 },
+ { url = "https://files.pythonhosted.org/packages/5a/84/e94227139ee5fb4d600a7a4927f322e1d4aea6fdc50bd3fca8493caba23f/cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4", size = 183178 },
+ { url = "https://files.pythonhosted.org/packages/da/ee/fb72c2b48656111c4ef27f0f91da355e130a923473bf5ee75c5643d00cca/cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c", size = 178840 },
+ { url = "https://files.pythonhosted.org/packages/cc/b6/db007700f67d151abadf508cbfd6a1884f57eab90b1bb985c4c8c02b0f28/cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36", size = 454803 },
+ { url = "https://files.pythonhosted.org/packages/1a/df/f8d151540d8c200eb1c6fba8cd0dfd40904f1b0682ea705c36e6c2e97ab3/cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5", size = 478850 },
+ { url = "https://files.pythonhosted.org/packages/28/c0/b31116332a547fd2677ae5b78a2ef662dfc8023d67f41b2a83f7c2aa78b1/cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff", size = 485729 },
+ { url = "https://files.pythonhosted.org/packages/91/2b/9a1ddfa5c7f13cab007a2c9cc295b70fbbda7cb10a286aa6810338e60ea1/cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99", size = 471256 },
+ { url = "https://files.pythonhosted.org/packages/b2/d5/da47df7004cb17e4955df6a43d14b3b4ae77737dff8bf7f8f333196717bf/cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93", size = 479424 },
+ { url = "https://files.pythonhosted.org/packages/0b/ac/2a28bcf513e93a219c8a4e8e125534f4f6db03e3179ba1c45e949b76212c/cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3", size = 484568 },
+ { url = "https://files.pythonhosted.org/packages/d4/38/ca8a4f639065f14ae0f1d9751e70447a261f1a30fa7547a828ae08142465/cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8", size = 488736 },
+ { url = "https://files.pythonhosted.org/packages/86/c5/28b2d6f799ec0bdecf44dced2ec5ed43e0eb63097b0f58c293583b406582/cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65", size = 172448 },
+ { url = "https://files.pythonhosted.org/packages/50/b9/db34c4755a7bd1cb2d1603ac3863f22bcecbd1ba29e5ee841a4bc510b294/cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903", size = 181976 },
+ { url = "https://files.pythonhosted.org/packages/8d/f8/dd6c246b148639254dad4d6803eb6a54e8c85c6e11ec9df2cffa87571dbe/cffi-1.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f3a2b4222ce6b60e2e8b337bb9596923045681d71e5a082783484d845390938e", size = 182989 },
+ { url = "https://files.pythonhosted.org/packages/8b/f1/672d303ddf17c24fc83afd712316fda78dc6fce1cd53011b839483e1ecc8/cffi-1.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0984a4925a435b1da406122d4d7968dd861c1385afe3b45ba82b750f229811e2", size = 178802 },
+ { url = "https://files.pythonhosted.org/packages/0e/2d/eab2e858a91fdff70533cab61dcff4a1f55ec60425832ddfdc9cd36bc8af/cffi-1.17.1-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d01b12eeeb4427d3110de311e1774046ad344f5b1a7403101878976ecd7a10f3", size = 454792 },
+ { url = "https://files.pythonhosted.org/packages/75/b2/fbaec7c4455c604e29388d55599b99ebcc250a60050610fadde58932b7ee/cffi-1.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:706510fe141c86a69c8ddc029c7910003a17353970cff3b904ff0686a5927683", size = 478893 },
+ { url = "https://files.pythonhosted.org/packages/4f/b7/6e4a2162178bf1935c336d4da8a9352cccab4d3a5d7914065490f08c0690/cffi-1.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de55b766c7aa2e2a3092c51e0483d700341182f08e67c63630d5b6f200bb28e5", size = 485810 },
+ { url = "https://files.pythonhosted.org/packages/c7/8a/1d0e4a9c26e54746dc08c2c6c037889124d4f59dffd853a659fa545f1b40/cffi-1.17.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c59d6e989d07460165cc5ad3c61f9fd8f1b4796eacbd81cee78957842b834af4", size = 471200 },
+ { url = "https://files.pythonhosted.org/packages/26/9f/1aab65a6c0db35f43c4d1b4f580e8df53914310afc10ae0397d29d697af4/cffi-1.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd398dbc6773384a17fe0d3e7eeb8d1a21c2200473ee6806bb5e6a8e62bb73dd", size = 479447 },
+ { url = "https://files.pythonhosted.org/packages/5f/e4/fb8b3dd8dc0e98edf1135ff067ae070bb32ef9d509d6cb0f538cd6f7483f/cffi-1.17.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3edc8d958eb099c634dace3c7e16560ae474aa3803a5df240542b305d14e14ed", size = 484358 },
+ { url = "https://files.pythonhosted.org/packages/f1/47/d7145bf2dc04684935d57d67dff9d6d795b2ba2796806bb109864be3a151/cffi-1.17.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:72e72408cad3d5419375fc87d289076ee319835bdfa2caad331e377589aebba9", size = 488469 },
+ { url = "https://files.pythonhosted.org/packages/bf/ee/f94057fa6426481d663b88637a9a10e859e492c73d0384514a17d78ee205/cffi-1.17.1-cp313-cp313-win32.whl", hash = "sha256:e03eab0a8677fa80d646b5ddece1cbeaf556c313dcfac435ba11f107ba117b5d", size = 172475 },
+ { url = "https://files.pythonhosted.org/packages/7c/fc/6a8cb64e5f0324877d503c854da15d76c1e50eb722e320b15345c4d0c6de/cffi-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6a16c31041f09ead72d69f583767292f750d24913dadacf5756b966aacb3f1a", size = 182009 },
+ { url = "https://files.pythonhosted.org/packages/b9/ea/8bb50596b8ffbc49ddd7a1ad305035daa770202a6b782fc164647c2673ad/cffi-1.17.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b2ab587605f4ba0bf81dc0cb08a41bd1c0a5906bd59243d56bad7668a6fc6c16", size = 182220 },
+ { url = "https://files.pythonhosted.org/packages/ae/11/e77c8cd24f58285a82c23af484cf5b124a376b32644e445960d1a4654c3a/cffi-1.17.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:28b16024becceed8c6dfbc75629e27788d8a3f9030691a1dbf9821a128b22c36", size = 178605 },
+ { url = "https://files.pythonhosted.org/packages/ed/65/25a8dc32c53bf5b7b6c2686b42ae2ad58743f7ff644844af7cdb29b49361/cffi-1.17.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1d599671f396c4723d016dbddb72fe8e0397082b0a77a4fab8028923bec050e8", size = 424910 },
+ { url = "https://files.pythonhosted.org/packages/42/7a/9d086fab7c66bd7c4d0f27c57a1b6b068ced810afc498cc8c49e0088661c/cffi-1.17.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca74b8dbe6e8e8263c0ffd60277de77dcee6c837a3d0881d8c1ead7268c9e576", size = 447200 },
+ { url = "https://files.pythonhosted.org/packages/da/63/1785ced118ce92a993b0ec9e0d0ac8dc3e5dbfbcaa81135be56c69cabbb6/cffi-1.17.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f7f5baafcc48261359e14bcd6d9bff6d4b28d9103847c9e136694cb0501aef87", size = 454565 },
+ { url = "https://files.pythonhosted.org/packages/74/06/90b8a44abf3556599cdec107f7290277ae8901a58f75e6fe8f970cd72418/cffi-1.17.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98e3969bcff97cae1b2def8ba499ea3d6f31ddfdb7635374834cf89a1a08ecf0", size = 435635 },
+ { url = "https://files.pythonhosted.org/packages/bd/62/a1f468e5708a70b1d86ead5bab5520861d9c7eacce4a885ded9faa7729c3/cffi-1.17.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdf5ce3acdfd1661132f2a9c19cac174758dc2352bfe37d98aa7512c6b7178b3", size = 445218 },
+ { url = "https://files.pythonhosted.org/packages/5b/95/b34462f3ccb09c2594aa782d90a90b045de4ff1f70148ee79c69d37a0a5a/cffi-1.17.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:9755e4345d1ec879e3849e62222a18c7174d65a6a92d5b346b1863912168b595", size = 460486 },
+ { url = "https://files.pythonhosted.org/packages/fc/fc/a1e4bebd8d680febd29cf6c8a40067182b64f00c7d105f8f26b5bc54317b/cffi-1.17.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f1e22e8c4419538cb197e4dd60acc919d7696e5ef98ee4da4e01d3f8cfa4cc5a", size = 437911 },
+ { url = "https://files.pythonhosted.org/packages/e6/c3/21cab7a6154b6a5ea330ae80de386e7665254835b9e98ecc1340b3a7de9a/cffi-1.17.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c03e868a0b3bc35839ba98e74211ed2b05d2119be4e8a0f224fba9384f1fe02e", size = 460632 },
+ { url = "https://files.pythonhosted.org/packages/cb/b5/fd9f8b5a84010ca169ee49f4e4ad6f8c05f4e3545b72ee041dbbcb159882/cffi-1.17.1-cp39-cp39-win32.whl", hash = "sha256:e31ae45bc2e29f6b2abd0de1cc3b9d5205aa847cafaecb8af1476a609a2f6eb7", size = 171820 },
+ { url = "https://files.pythonhosted.org/packages/8c/52/b08750ce0bce45c143e1b5d7357ee8c55341b52bdef4b0f081af1eb248c2/cffi-1.17.1-cp39-cp39-win_amd64.whl", hash = "sha256:d016c76bdd850f3c626af19b0542c9677ba156e4ee4fccfdd7848803533ef662", size = 181290 },
+]
+
+[[package]]
+name = "charset-normalizer"
+version = "3.4.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/95/28/9901804da60055b406e1a1c5ba7aac1276fb77f1dde635aabfc7fd84b8ab/charset_normalizer-3.4.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7c48ed483eb946e6c04ccbe02c6b4d1d48e51944b6db70f697e089c193404941", size = 201818 },
+ { url = "https://files.pythonhosted.org/packages/d9/9b/892a8c8af9110935e5adcbb06d9c6fe741b6bb02608c6513983048ba1a18/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2d318c11350e10662026ad0eb71bb51c7812fc8590825304ae0bdd4ac283acd", size = 144649 },
+ { url = "https://files.pythonhosted.org/packages/7b/a5/4179abd063ff6414223575e008593861d62abfc22455b5d1a44995b7c101/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9cbfacf36cb0ec2897ce0ebc5d08ca44213af24265bd56eca54bee7923c48fd6", size = 155045 },
+ { url = "https://files.pythonhosted.org/packages/3b/95/bc08c7dfeddd26b4be8c8287b9bb055716f31077c8b0ea1cd09553794665/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:18dd2e350387c87dabe711b86f83c9c78af772c748904d372ade190b5c7c9d4d", size = 147356 },
+ { url = "https://files.pythonhosted.org/packages/a8/2d/7a5b635aa65284bf3eab7653e8b4151ab420ecbae918d3e359d1947b4d61/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8075c35cd58273fee266c58c0c9b670947c19df5fb98e7b66710e04ad4e9ff86", size = 149471 },
+ { url = "https://files.pythonhosted.org/packages/ae/38/51fc6ac74251fd331a8cfdb7ec57beba8c23fd5493f1050f71c87ef77ed0/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5bf4545e3b962767e5c06fe1738f951f77d27967cb2caa64c28be7c4563e162c", size = 151317 },
+ { url = "https://files.pythonhosted.org/packages/b7/17/edee1e32215ee6e9e46c3e482645b46575a44a2d72c7dfd49e49f60ce6bf/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:7a6ab32f7210554a96cd9e33abe3ddd86732beeafc7a28e9955cdf22ffadbab0", size = 146368 },
+ { url = "https://files.pythonhosted.org/packages/26/2c/ea3e66f2b5f21fd00b2825c94cafb8c326ea6240cd80a91eb09e4a285830/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:b33de11b92e9f75a2b545d6e9b6f37e398d86c3e9e9653c4864eb7e89c5773ef", size = 154491 },
+ { url = "https://files.pythonhosted.org/packages/52/47/7be7fa972422ad062e909fd62460d45c3ef4c141805b7078dbab15904ff7/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8755483f3c00d6c9a77f490c17e6ab0c8729e39e6390328e42521ef175380ae6", size = 157695 },
+ { url = "https://files.pythonhosted.org/packages/2f/42/9f02c194da282b2b340f28e5fb60762de1151387a36842a92b533685c61e/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:68a328e5f55ec37c57f19ebb1fdc56a248db2e3e9ad769919a58672958e8f366", size = 154849 },
+ { url = "https://files.pythonhosted.org/packages/67/44/89cacd6628f31fb0b63201a618049be4be2a7435a31b55b5eb1c3674547a/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:21b2899062867b0e1fde9b724f8aecb1af14f2778d69aacd1a5a1853a597a5db", size = 150091 },
+ { url = "https://files.pythonhosted.org/packages/1f/79/4b8da9f712bc079c0f16b6d67b099b0b8d808c2292c937f267d816ec5ecc/charset_normalizer-3.4.2-cp310-cp310-win32.whl", hash = "sha256:e8082b26888e2f8b36a042a58307d5b917ef2b1cacab921ad3323ef91901c71a", size = 98445 },
+ { url = "https://files.pythonhosted.org/packages/7d/d7/96970afb4fb66497a40761cdf7bd4f6fca0fc7bafde3a84f836c1f57a926/charset_normalizer-3.4.2-cp310-cp310-win_amd64.whl", hash = "sha256:f69a27e45c43520f5487f27627059b64aaf160415589230992cec34c5e18a509", size = 105782 },
+ { url = "https://files.pythonhosted.org/packages/05/85/4c40d00dcc6284a1c1ad5de5e0996b06f39d8232f1031cd23c2f5c07ee86/charset_normalizer-3.4.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:be1e352acbe3c78727a16a455126d9ff83ea2dfdcbc83148d2982305a04714c2", size = 198794 },
+ { url = "https://files.pythonhosted.org/packages/41/d9/7a6c0b9db952598e97e93cbdfcb91bacd89b9b88c7c983250a77c008703c/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa88ca0b1932e93f2d961bf3addbb2db902198dca337d88c89e1559e066e7645", size = 142846 },
+ { url = "https://files.pythonhosted.org/packages/66/82/a37989cda2ace7e37f36c1a8ed16c58cf48965a79c2142713244bf945c89/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d524ba3f1581b35c03cb42beebab4a13e6cdad7b36246bd22541fa585a56cccd", size = 153350 },
+ { url = "https://files.pythonhosted.org/packages/df/68/a576b31b694d07b53807269d05ec3f6f1093e9545e8607121995ba7a8313/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28a1005facc94196e1fb3e82a3d442a9d9110b8434fc1ded7a24a2983c9888d8", size = 145657 },
+ { url = "https://files.pythonhosted.org/packages/92/9b/ad67f03d74554bed3aefd56fe836e1623a50780f7c998d00ca128924a499/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb20a30fe1175ecabed17cbf7812f7b804b8a315a25f24678bcdf120a90077f", size = 147260 },
+ { url = "https://files.pythonhosted.org/packages/a6/e6/8aebae25e328160b20e31a7e9929b1578bbdc7f42e66f46595a432f8539e/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f5d9ed7f254402c9e7d35d2f5972c9bbea9040e99cd2861bd77dc68263277c7", size = 149164 },
+ { url = "https://files.pythonhosted.org/packages/8b/f2/b3c2f07dbcc248805f10e67a0262c93308cfa149a4cd3d1fe01f593e5fd2/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd387a49825780ff861998cd959767800d54f8308936b21025326de4b5a42b9", size = 144571 },
+ { url = "https://files.pythonhosted.org/packages/60/5b/c3f3a94bc345bc211622ea59b4bed9ae63c00920e2e8f11824aa5708e8b7/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f0aa37f3c979cf2546b73e8222bbfa3dc07a641585340179d768068e3455e544", size = 151952 },
+ { url = "https://files.pythonhosted.org/packages/e2/4d/ff460c8b474122334c2fa394a3f99a04cf11c646da895f81402ae54f5c42/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e70e990b2137b29dc5564715de1e12701815dacc1d056308e2b17e9095372a82", size = 155959 },
+ { url = "https://files.pythonhosted.org/packages/a2/2b/b964c6a2fda88611a1fe3d4c400d39c66a42d6c169c924818c848f922415/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c8c57f84ccfc871a48a47321cfa49ae1df56cd1d965a09abe84066f6853b9c0", size = 153030 },
+ { url = "https://files.pythonhosted.org/packages/59/2e/d3b9811db26a5ebf444bc0fa4f4be5aa6d76fc6e1c0fd537b16c14e849b6/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6b66f92b17849b85cad91259efc341dce9c1af48e2173bf38a85c6329f1033e5", size = 148015 },
+ { url = "https://files.pythonhosted.org/packages/90/07/c5fd7c11eafd561bb51220d600a788f1c8d77c5eef37ee49454cc5c35575/charset_normalizer-3.4.2-cp311-cp311-win32.whl", hash = "sha256:daac4765328a919a805fa5e2720f3e94767abd632ae410a9062dff5412bae65a", size = 98106 },
+ { url = "https://files.pythonhosted.org/packages/a8/05/5e33dbef7e2f773d672b6d79f10ec633d4a71cd96db6673625838a4fd532/charset_normalizer-3.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53efc7c7cee4c1e70661e2e112ca46a575f90ed9ae3fef200f2a25e954f4b28", size = 105402 },
+ { url = "https://files.pythonhosted.org/packages/d7/a4/37f4d6035c89cac7930395a35cc0f1b872e652eaafb76a6075943754f095/charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0c29de6a1a95f24b9a1aa7aefd27d2487263f00dfd55a77719b530788f75cff7", size = 199936 },
+ { url = "https://files.pythonhosted.org/packages/ee/8a/1a5e33b73e0d9287274f899d967907cd0bf9c343e651755d9307e0dbf2b3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cddf7bd982eaa998934a91f69d182aec997c6c468898efe6679af88283b498d3", size = 143790 },
+ { url = "https://files.pythonhosted.org/packages/66/52/59521f1d8e6ab1482164fa21409c5ef44da3e9f653c13ba71becdd98dec3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fcbe676a55d7445b22c10967bceaaf0ee69407fbe0ece4d032b6eb8d4565982a", size = 153924 },
+ { url = "https://files.pythonhosted.org/packages/86/2d/fb55fdf41964ec782febbf33cb64be480a6b8f16ded2dbe8db27a405c09f/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d41c4d287cfc69060fa91cae9683eacffad989f1a10811995fa309df656ec214", size = 146626 },
+ { url = "https://files.pythonhosted.org/packages/8c/73/6ede2ec59bce19b3edf4209d70004253ec5f4e319f9a2e3f2f15601ed5f7/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e594135de17ab3866138f496755f302b72157d115086d100c3f19370839dd3a", size = 148567 },
+ { url = "https://files.pythonhosted.org/packages/09/14/957d03c6dc343c04904530b6bef4e5efae5ec7d7990a7cbb868e4595ee30/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf713fe9a71ef6fd5adf7a79670135081cd4431c2943864757f0fa3a65b1fafd", size = 150957 },
+ { url = "https://files.pythonhosted.org/packages/0d/c8/8174d0e5c10ccebdcb1b53cc959591c4c722a3ad92461a273e86b9f5a302/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a370b3e078e418187da8c3674eddb9d983ec09445c99a3a263c2011993522981", size = 145408 },
+ { url = "https://files.pythonhosted.org/packages/58/aa/8904b84bc8084ac19dc52feb4f5952c6df03ffb460a887b42615ee1382e8/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a955b438e62efdf7e0b7b52a64dc5c3396e2634baa62471768a64bc2adb73d5c", size = 153399 },
+ { url = "https://files.pythonhosted.org/packages/c2/26/89ee1f0e264d201cb65cf054aca6038c03b1a0c6b4ae998070392a3ce605/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7222ffd5e4de8e57e03ce2cef95a4c43c98fcb72ad86909abdfc2c17d227fc1b", size = 156815 },
+ { url = "https://files.pythonhosted.org/packages/fd/07/68e95b4b345bad3dbbd3a8681737b4338ff2c9df29856a6d6d23ac4c73cb/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bee093bf902e1d8fc0ac143c88902c3dfc8941f7ea1d6a8dd2bcb786d33db03d", size = 154537 },
+ { url = "https://files.pythonhosted.org/packages/77/1a/5eefc0ce04affb98af07bc05f3bac9094513c0e23b0562d64af46a06aae4/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb8adb91d11846ee08bec4c8236c8549ac721c245678282dcb06b221aab59f", size = 149565 },
+ { url = "https://files.pythonhosted.org/packages/37/a0/2410e5e6032a174c95e0806b1a6585eb21e12f445ebe239fac441995226a/charset_normalizer-3.4.2-cp312-cp312-win32.whl", hash = "sha256:db4c7bf0e07fc3b7d89ac2a5880a6a8062056801b83ff56d8464b70f65482b6c", size = 98357 },
+ { url = "https://files.pythonhosted.org/packages/6c/4f/c02d5c493967af3eda9c771ad4d2bbc8df6f99ddbeb37ceea6e8716a32bc/charset_normalizer-3.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:5a9979887252a82fefd3d3ed2a8e3b937a7a809f65dcb1e068b090e165bbe99e", size = 105776 },
+ { url = "https://files.pythonhosted.org/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622 },
+ { url = "https://files.pythonhosted.org/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435 },
+ { url = "https://files.pythonhosted.org/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653 },
+ { url = "https://files.pythonhosted.org/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231 },
+ { url = "https://files.pythonhosted.org/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243 },
+ { url = "https://files.pythonhosted.org/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442 },
+ { url = "https://files.pythonhosted.org/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147 },
+ { url = "https://files.pythonhosted.org/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057 },
+ { url = "https://files.pythonhosted.org/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454 },
+ { url = "https://files.pythonhosted.org/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174 },
+ { url = "https://files.pythonhosted.org/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166 },
+ { url = "https://files.pythonhosted.org/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064 },
+ { url = "https://files.pythonhosted.org/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641 },
+ { url = "https://files.pythonhosted.org/packages/28/f8/dfb01ff6cc9af38552c69c9027501ff5a5117c4cc18dcd27cb5259fa1888/charset_normalizer-3.4.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:005fa3432484527f9732ebd315da8da8001593e2cf46a3d817669f062c3d9ed4", size = 201671 },
+ { url = "https://files.pythonhosted.org/packages/32/fb/74e26ee556a9dbfe3bd264289b67be1e6d616329403036f6507bb9f3f29c/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e92fca20c46e9f5e1bb485887d074918b13543b1c2a1185e69bb8d17ab6236a7", size = 144744 },
+ { url = "https://files.pythonhosted.org/packages/ad/06/8499ee5aa7addc6f6d72e068691826ff093329fe59891e83b092ae4c851c/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:50bf98d5e563b83cc29471fa114366e6806bc06bc7a25fd59641e41445327836", size = 154993 },
+ { url = "https://files.pythonhosted.org/packages/f1/a2/5e4c187680728219254ef107a6949c60ee0e9a916a5dadb148c7ae82459c/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:721c76e84fe669be19c5791da68232ca2e05ba5185575086e384352e2c309597", size = 147382 },
+ { url = "https://files.pythonhosted.org/packages/4c/fe/56aca740dda674f0cc1ba1418c4d84534be51f639b5f98f538b332dc9a95/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:82d8fd25b7f4675d0c47cf95b594d4e7b158aca33b76aa63d07186e13c0e0ab7", size = 149536 },
+ { url = "https://files.pythonhosted.org/packages/53/13/db2e7779f892386b589173dd689c1b1e304621c5792046edd8a978cbf9e0/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b3daeac64d5b371dea99714f08ffc2c208522ec6b06fbc7866a450dd446f5c0f", size = 151349 },
+ { url = "https://files.pythonhosted.org/packages/69/35/e52ab9a276186f729bce7a0638585d2982f50402046e4b0faa5d2c3ef2da/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:dccab8d5fa1ef9bfba0590ecf4d46df048d18ffe3eec01eeb73a42e0d9e7a8ba", size = 146365 },
+ { url = "https://files.pythonhosted.org/packages/a6/d8/af7333f732fc2e7635867d56cb7c349c28c7094910c72267586947561b4b/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:aaf27faa992bfee0264dc1f03f4c75e9fcdda66a519db6b957a3f826e285cf12", size = 154499 },
+ { url = "https://files.pythonhosted.org/packages/7a/3d/a5b2e48acef264d71e036ff30bcc49e51bde80219bb628ba3e00cf59baac/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:eb30abc20df9ab0814b5a2524f23d75dcf83cde762c161917a2b4b7b55b1e518", size = 157735 },
+ { url = "https://files.pythonhosted.org/packages/85/d8/23e2c112532a29f3eef374375a8684a4f3b8e784f62b01da931186f43494/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:c72fbbe68c6f32f251bdc08b8611c7b3060612236e960ef848e0a517ddbe76c5", size = 154786 },
+ { url = "https://files.pythonhosted.org/packages/c7/57/93e0169f08ecc20fe82d12254a200dfaceddc1c12a4077bf454ecc597e33/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:982bb1e8b4ffda883b3d0a521e23abcd6fd17418f6d2c4118d257a10199c0ce3", size = 150203 },
+ { url = "https://files.pythonhosted.org/packages/2c/9d/9bf2b005138e7e060d7ebdec7503d0ef3240141587651f4b445bdf7286c2/charset_normalizer-3.4.2-cp39-cp39-win32.whl", hash = "sha256:43e0933a0eff183ee85833f341ec567c0980dae57c464d8a508e1b2ceb336471", size = 98436 },
+ { url = "https://files.pythonhosted.org/packages/6d/24/5849d46cf4311bbf21b424c443b09b459f5b436b1558c04e45dbb7cc478b/charset_normalizer-3.4.2-cp39-cp39-win_amd64.whl", hash = "sha256:d11b54acf878eef558599658b0ffca78138c8c3655cf4f3a4a673c437e67732e", size = 105772 },
+ { url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626 },
+]
+
+[[package]]
+name = "click"
+version = "8.1.8"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version < '3.10' and sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b9/2e/0090cbf739cee7d23781ad4b89a9894a41538e4fcf4c31dcdd705b78eb8b/click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a", size = 226593 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/d4/7ebdbd03970677812aac39c869717059dbb71a4cfc033ca6e5221787892c/click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2", size = 98188 },
+]
+
+[[package]]
+name = "click"
+version = "8.2.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version >= '3.10' and sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215 },
+]
+
+[[package]]
+name = "cloudpickle"
+version = "3.1.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/52/39/069100b84d7418bc358d81669d5748efb14b9cceacd2f9c75f550424132f/cloudpickle-3.1.1.tar.gz", hash = "sha256:b216fa8ae4019d5482a8ac3c95d8f6346115d8835911fd4aefd1a445e4242c64", size = 22113 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/e8/64c37fadfc2816a7701fa8a6ed8d87327c7d54eacfbfb6edab14a2f2be75/cloudpickle-3.1.1-py3-none-any.whl", hash = "sha256:c8c5a44295039331ee9dad40ba100a9c7297b6f988e50e87ccdf3765a668350e", size = 20992 },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },
+]
+
+[[package]]
+name = "compressed-tensors"
+version = "0.10.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pydantic" },
+ { name = "torch" },
+ { name = "transformers" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/40/eb/2229523a539e8074b238c225d168f734f6f056ab4ea2278eefe752f4a6f3/compressed_tensors-0.10.1.tar.gz", hash = "sha256:f99ce620ddcf8a657eaa7995daf5faa8e988d4b4cadc595bf2c4ff9346c2c19a", size = 126778 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5b/07/e70a0b9efc24a32740396c404e7213c62b8aeb4a577ed5a3f191f8d7806b/compressed_tensors-0.10.1-py3-none-any.whl", hash = "sha256:b8890735522c119900e8d4192cced0b0f70a98440ae070448cb699165c404659", size = 116998 },
+]
+
+[[package]]
+name = "contourpy"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "numpy", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f5/f6/31a8f28b4a2a4fa0e01085e542f3081ab0588eff8e589d39d775172c9792/contourpy-1.3.0.tar.gz", hash = "sha256:7ffa0db17717a8ffb127efd0c95a4362d996b892c2904db72428d5b52e1938a4", size = 13464370 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6c/e0/be8dcc796cfdd96708933e0e2da99ba4bb8f9b2caa9d560a50f3f09a65f3/contourpy-1.3.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:880ea32e5c774634f9fcd46504bf9f080a41ad855f4fef54f5380f5133d343c7", size = 265366 },
+ { url = "https://files.pythonhosted.org/packages/50/d6/c953b400219443535d412fcbbc42e7a5e823291236bc0bb88936e3cc9317/contourpy-1.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:76c905ef940a4474a6289c71d53122a4f77766eef23c03cd57016ce19d0f7b42", size = 249226 },
+ { url = "https://files.pythonhosted.org/packages/6f/b4/6fffdf213ffccc28483c524b9dad46bb78332851133b36ad354b856ddc7c/contourpy-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:92f8557cbb07415a4d6fa191f20fd9d2d9eb9c0b61d1b2f52a8926e43c6e9af7", size = 308460 },
+ { url = "https://files.pythonhosted.org/packages/cf/6c/118fc917b4050f0afe07179a6dcbe4f3f4ec69b94f36c9e128c4af480fb8/contourpy-1.3.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:36f965570cff02b874773c49bfe85562b47030805d7d8360748f3eca570f4cab", size = 347623 },
+ { url = "https://files.pythonhosted.org/packages/f9/a4/30ff110a81bfe3abf7b9673284d21ddce8cc1278f6f77393c91199da4c90/contourpy-1.3.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cacd81e2d4b6f89c9f8a5b69b86490152ff39afc58a95af002a398273e5ce589", size = 317761 },
+ { url = "https://files.pythonhosted.org/packages/99/e6/d11966962b1aa515f5586d3907ad019f4b812c04e4546cc19ebf62b5178e/contourpy-1.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:69375194457ad0fad3a839b9e29aa0b0ed53bb54db1bfb6c3ae43d111c31ce41", size = 322015 },
+ { url = "https://files.pythonhosted.org/packages/4d/e3/182383743751d22b7b59c3c753277b6aee3637049197624f333dac5b4c80/contourpy-1.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:7a52040312b1a858b5e31ef28c2e865376a386c60c0e248370bbea2d3f3b760d", size = 1262672 },
+ { url = "https://files.pythonhosted.org/packages/78/53/974400c815b2e605f252c8fb9297e2204347d1755a5374354ee77b1ea259/contourpy-1.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:3faeb2998e4fcb256542e8a926d08da08977f7f5e62cf733f3c211c2a5586223", size = 1321688 },
+ { url = "https://files.pythonhosted.org/packages/52/29/99f849faed5593b2926a68a31882af98afbeac39c7fdf7de491d9c85ec6a/contourpy-1.3.0-cp310-cp310-win32.whl", hash = "sha256:36e0cff201bcb17a0a8ecc7f454fe078437fa6bda730e695a92f2d9932bd507f", size = 171145 },
+ { url = "https://files.pythonhosted.org/packages/a9/97/3f89bba79ff6ff2b07a3cbc40aa693c360d5efa90d66e914f0ff03b95ec7/contourpy-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:87ddffef1dbe5e669b5c2440b643d3fdd8622a348fe1983fad7a0f0ccb1cd67b", size = 216019 },
+ { url = "https://files.pythonhosted.org/packages/b3/1f/9375917786cb39270b0ee6634536c0e22abf225825602688990d8f5c6c19/contourpy-1.3.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0fa4c02abe6c446ba70d96ece336e621efa4aecae43eaa9b030ae5fb92b309ad", size = 266356 },
+ { url = "https://files.pythonhosted.org/packages/05/46/9256dd162ea52790c127cb58cfc3b9e3413a6e3478917d1f811d420772ec/contourpy-1.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:834e0cfe17ba12f79963861e0f908556b2cedd52e1f75e6578801febcc6a9f49", size = 250915 },
+ { url = "https://files.pythonhosted.org/packages/e1/5d/3056c167fa4486900dfbd7e26a2fdc2338dc58eee36d490a0ed3ddda5ded/contourpy-1.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dbc4c3217eee163fa3984fd1567632b48d6dfd29216da3ded3d7b844a8014a66", size = 310443 },
+ { url = "https://files.pythonhosted.org/packages/ca/c2/1a612e475492e07f11c8e267ea5ec1ce0d89971be496c195e27afa97e14a/contourpy-1.3.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4865cd1d419e0c7a7bf6de1777b185eebdc51470800a9f42b9e9decf17762081", size = 348548 },
+ { url = "https://files.pythonhosted.org/packages/45/cf/2c2fc6bb5874158277b4faf136847f0689e1b1a1f640a36d76d52e78907c/contourpy-1.3.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:303c252947ab4b14c08afeb52375b26781ccd6a5ccd81abcdfc1fafd14cf93c1", size = 319118 },
+ { url = "https://files.pythonhosted.org/packages/03/33/003065374f38894cdf1040cef474ad0546368eea7e3a51d48b8a423961f8/contourpy-1.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:637f674226be46f6ba372fd29d9523dd977a291f66ab2a74fbeb5530bb3f445d", size = 323162 },
+ { url = "https://files.pythonhosted.org/packages/42/80/e637326e85e4105a802e42959f56cff2cd39a6b5ef68d5d9aee3ea5f0e4c/contourpy-1.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:76a896b2f195b57db25d6b44e7e03f221d32fe318d03ede41f8b4d9ba1bff53c", size = 1265396 },
+ { url = "https://files.pythonhosted.org/packages/7c/3b/8cbd6416ca1bbc0202b50f9c13b2e0b922b64be888f9d9ee88e6cfabfb51/contourpy-1.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e1fd23e9d01591bab45546c089ae89d926917a66dceb3abcf01f6105d927e2cb", size = 1324297 },
+ { url = "https://files.pythonhosted.org/packages/4d/2c/021a7afaa52fe891f25535506cc861c30c3c4e5a1c1ce94215e04b293e72/contourpy-1.3.0-cp311-cp311-win32.whl", hash = "sha256:d402880b84df3bec6eab53cd0cf802cae6a2ef9537e70cf75e91618a3801c20c", size = 171808 },
+ { url = "https://files.pythonhosted.org/packages/8d/2f/804f02ff30a7fae21f98198828d0857439ec4c91a96e20cf2d6c49372966/contourpy-1.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:6cb6cc968059db9c62cb35fbf70248f40994dfcd7aa10444bbf8b3faeb7c2d67", size = 217181 },
+ { url = "https://files.pythonhosted.org/packages/c9/92/8e0bbfe6b70c0e2d3d81272b58c98ac69ff1a4329f18c73bd64824d8b12e/contourpy-1.3.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:570ef7cf892f0afbe5b2ee410c507ce12e15a5fa91017a0009f79f7d93a1268f", size = 267838 },
+ { url = "https://files.pythonhosted.org/packages/e3/04/33351c5d5108460a8ce6d512307690b023f0cfcad5899499f5c83b9d63b1/contourpy-1.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:da84c537cb8b97d153e9fb208c221c45605f73147bd4cadd23bdae915042aad6", size = 251549 },
+ { url = "https://files.pythonhosted.org/packages/51/3d/aa0fe6ae67e3ef9f178389e4caaaa68daf2f9024092aa3c6032e3d174670/contourpy-1.3.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0be4d8425bfa755e0fd76ee1e019636ccc7c29f77a7c86b4328a9eb6a26d0639", size = 303177 },
+ { url = "https://files.pythonhosted.org/packages/56/c3/c85a7e3e0cab635575d3b657f9535443a6f5d20fac1a1911eaa4bbe1aceb/contourpy-1.3.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9c0da700bf58f6e0b65312d0a5e695179a71d0163957fa381bb3c1f72972537c", size = 341735 },
+ { url = "https://files.pythonhosted.org/packages/dd/8d/20f7a211a7be966a53f474bc90b1a8202e9844b3f1ef85f3ae45a77151ee/contourpy-1.3.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eb8b141bb00fa977d9122636b16aa67d37fd40a3d8b52dd837e536d64b9a4d06", size = 314679 },
+ { url = "https://files.pythonhosted.org/packages/6e/be/524e377567defac0e21a46e2a529652d165fed130a0d8a863219303cee18/contourpy-1.3.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3634b5385c6716c258d0419c46d05c8aa7dc8cb70326c9a4fb66b69ad2b52e09", size = 320549 },
+ { url = "https://files.pythonhosted.org/packages/0f/96/fdb2552a172942d888915f3a6663812e9bc3d359d53dafd4289a0fb462f0/contourpy-1.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0dce35502151b6bd35027ac39ba6e5a44be13a68f55735c3612c568cac3805fd", size = 1263068 },
+ { url = "https://files.pythonhosted.org/packages/2a/25/632eab595e3140adfa92f1322bf8915f68c932bac468e89eae9974cf1c00/contourpy-1.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:aea348f053c645100612b333adc5983d87be69acdc6d77d3169c090d3b01dc35", size = 1322833 },
+ { url = "https://files.pythonhosted.org/packages/73/e3/69738782e315a1d26d29d71a550dbbe3eb6c653b028b150f70c1a5f4f229/contourpy-1.3.0-cp312-cp312-win32.whl", hash = "sha256:90f73a5116ad1ba7174341ef3ea5c3150ddf20b024b98fb0c3b29034752c8aeb", size = 172681 },
+ { url = "https://files.pythonhosted.org/packages/0c/89/9830ba00d88e43d15e53d64931e66b8792b46eb25e2050a88fec4a0df3d5/contourpy-1.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:b11b39aea6be6764f84360fce6c82211a9db32a7c7de8fa6dd5397cf1d079c3b", size = 218283 },
+ { url = "https://files.pythonhosted.org/packages/53/a1/d20415febfb2267af2d7f06338e82171824d08614084714fb2c1dac9901f/contourpy-1.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:3e1c7fa44aaae40a2247e2e8e0627f4bea3dd257014764aa644f319a5f8600e3", size = 267879 },
+ { url = "https://files.pythonhosted.org/packages/aa/45/5a28a3570ff6218d8bdfc291a272a20d2648104815f01f0177d103d985e1/contourpy-1.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:364174c2a76057feef647c802652f00953b575723062560498dc7930fc9b1cb7", size = 251573 },
+ { url = "https://files.pythonhosted.org/packages/39/1c/d3f51540108e3affa84f095c8b04f0aa833bb797bc8baa218a952a98117d/contourpy-1.3.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:32b238b3b3b649e09ce9aaf51f0c261d38644bdfa35cbaf7b263457850957a84", size = 303184 },
+ { url = "https://files.pythonhosted.org/packages/00/56/1348a44fb6c3a558c1a3a0cd23d329d604c99d81bf5a4b58c6b71aab328f/contourpy-1.3.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d51fca85f9f7ad0b65b4b9fe800406d0d77017d7270d31ec3fb1cc07358fdea0", size = 340262 },
+ { url = "https://files.pythonhosted.org/packages/2b/23/00d665ba67e1bb666152131da07e0f24c95c3632d7722caa97fb61470eca/contourpy-1.3.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:732896af21716b29ab3e988d4ce14bc5133733b85956316fb0c56355f398099b", size = 313806 },
+ { url = "https://files.pythonhosted.org/packages/5a/42/3cf40f7040bb8362aea19af9a5fb7b32ce420f645dd1590edcee2c657cd5/contourpy-1.3.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d73f659398a0904e125280836ae6f88ba9b178b2fed6884f3b1f95b989d2c8da", size = 319710 },
+ { url = "https://files.pythonhosted.org/packages/05/32/f3bfa3fc083b25e1a7ae09197f897476ee68e7386e10404bdf9aac7391f0/contourpy-1.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c6c7c2408b7048082932cf4e641fa3b8ca848259212f51c8c59c45aa7ac18f14", size = 1264107 },
+ { url = "https://files.pythonhosted.org/packages/1c/1e/1019d34473a736664f2439542b890b2dc4c6245f5c0d8cdfc0ccc2cab80c/contourpy-1.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f317576606de89da6b7e0861cf6061f6146ead3528acabff9236458a6ba467f8", size = 1322458 },
+ { url = "https://files.pythonhosted.org/packages/22/85/4f8bfd83972cf8909a4d36d16b177f7b8bdd942178ea4bf877d4a380a91c/contourpy-1.3.0-cp313-cp313-win32.whl", hash = "sha256:31cd3a85dbdf1fc002280c65caa7e2b5f65e4a973fcdf70dd2fdcb9868069294", size = 172643 },
+ { url = "https://files.pythonhosted.org/packages/cc/4a/fb3c83c1baba64ba90443626c228ca14f19a87c51975d3b1de308dd2cf08/contourpy-1.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:4553c421929ec95fb07b3aaca0fae668b2eb5a5203d1217ca7c34c063c53d087", size = 218301 },
+ { url = "https://files.pythonhosted.org/packages/76/65/702f4064f397821fea0cb493f7d3bc95a5d703e20954dce7d6d39bacf378/contourpy-1.3.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:345af746d7766821d05d72cb8f3845dfd08dd137101a2cb9b24de277d716def8", size = 278972 },
+ { url = "https://files.pythonhosted.org/packages/80/85/21f5bba56dba75c10a45ec00ad3b8190dbac7fd9a8a8c46c6116c933e9cf/contourpy-1.3.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3bb3808858a9dc68f6f03d319acd5f1b8a337e6cdda197f02f4b8ff67ad2057b", size = 263375 },
+ { url = "https://files.pythonhosted.org/packages/0a/64/084c86ab71d43149f91ab3a4054ccf18565f0a8af36abfa92b1467813ed6/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:420d39daa61aab1221567b42eecb01112908b2cab7f1b4106a52caaec8d36973", size = 307188 },
+ { url = "https://files.pythonhosted.org/packages/3d/ff/d61a4c288dc42da0084b8d9dc2aa219a850767165d7d9a9c364ff530b509/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4d63ee447261e963af02642ffcb864e5a2ee4cbfd78080657a9880b8b1868e18", size = 345644 },
+ { url = "https://files.pythonhosted.org/packages/ca/aa/00d2313d35ec03f188e8f0786c2fc61f589306e02fdc158233697546fd58/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:167d6c890815e1dac9536dca00828b445d5d0df4d6a8c6adb4a7ec3166812fa8", size = 317141 },
+ { url = "https://files.pythonhosted.org/packages/8d/6a/b5242c8cb32d87f6abf4f5e3044ca397cb1a76712e3fa2424772e3ff495f/contourpy-1.3.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:710a26b3dc80c0e4febf04555de66f5fd17e9cf7170a7b08000601a10570bda6", size = 323469 },
+ { url = "https://files.pythonhosted.org/packages/6f/a6/73e929d43028a9079aca4bde107494864d54f0d72d9db508a51ff0878593/contourpy-1.3.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:75ee7cb1a14c617f34a51d11fa7524173e56551646828353c4af859c56b766e2", size = 1260894 },
+ { url = "https://files.pythonhosted.org/packages/2b/1e/1e726ba66eddf21c940821df8cf1a7d15cb165f0682d62161eaa5e93dae1/contourpy-1.3.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:33c92cdae89ec5135d036e7218e69b0bb2851206077251f04a6c4e0e21f03927", size = 1314829 },
+ { url = "https://files.pythonhosted.org/packages/b3/e3/b9f72758adb6ef7397327ceb8b9c39c75711affb220e4f53c745ea1d5a9a/contourpy-1.3.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a11077e395f67ffc2c44ec2418cfebed032cd6da3022a94fc227b6faf8e2acb8", size = 265518 },
+ { url = "https://files.pythonhosted.org/packages/ec/22/19f5b948367ab5260fb41d842c7a78dae645603881ea6bc39738bcfcabf6/contourpy-1.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e8134301d7e204c88ed7ab50028ba06c683000040ede1d617298611f9dc6240c", size = 249350 },
+ { url = "https://files.pythonhosted.org/packages/26/76/0c7d43263dd00ae21a91a24381b7e813d286a3294d95d179ef3a7b9fb1d7/contourpy-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e12968fdfd5bb45ffdf6192a590bd8ddd3ba9e58360b29683c6bb71a7b41edca", size = 309167 },
+ { url = "https://files.pythonhosted.org/packages/96/3b/cadff6773e89f2a5a492c1a8068e21d3fccaf1a1c1df7d65e7c8e3ef60ba/contourpy-1.3.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fd2a0fc506eccaaa7595b7e1418951f213cf8255be2600f1ea1b61e46a60c55f", size = 348279 },
+ { url = "https://files.pythonhosted.org/packages/e1/86/158cc43aa549d2081a955ab11c6bdccc7a22caacc2af93186d26f5f48746/contourpy-1.3.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4cfb5c62ce023dfc410d6059c936dcf96442ba40814aefbfa575425a3a7f19dc", size = 318519 },
+ { url = "https://files.pythonhosted.org/packages/05/11/57335544a3027e9b96a05948c32e566328e3a2f84b7b99a325b7a06d2b06/contourpy-1.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:68a32389b06b82c2fdd68276148d7b9275b5f5cf13e5417e4252f6d1a34f72a2", size = 321922 },
+ { url = "https://files.pythonhosted.org/packages/0b/e3/02114f96543f4a1b694333b92a6dcd4f8eebbefcc3a5f3bbb1316634178f/contourpy-1.3.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:94e848a6b83da10898cbf1311a815f770acc9b6a3f2d646f330d57eb4e87592e", size = 1258017 },
+ { url = "https://files.pythonhosted.org/packages/f3/3b/bfe4c81c6d5881c1c643dde6620be0b42bf8aab155976dd644595cfab95c/contourpy-1.3.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:d78ab28a03c854a873787a0a42254a0ccb3cb133c672f645c9f9c8f3ae9d0800", size = 1316773 },
+ { url = "https://files.pythonhosted.org/packages/f1/17/c52d2970784383cafb0bd918b6fb036d98d96bbf0bc1befb5d1e31a07a70/contourpy-1.3.0-cp39-cp39-win32.whl", hash = "sha256:81cb5ed4952aae6014bc9d0421dec7c5835c9c8c31cdf51910b708f548cf58e5", size = 171353 },
+ { url = "https://files.pythonhosted.org/packages/53/23/db9f69676308e094d3c45f20cc52e12d10d64f027541c995d89c11ad5c75/contourpy-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:14e262f67bd7e6eb6880bc564dcda30b15e351a594657e55b7eec94b6ef72843", size = 211817 },
+ { url = "https://files.pythonhosted.org/packages/d1/09/60e486dc2b64c94ed33e58dcfb6f808192c03dfc5574c016218b9b7680dc/contourpy-1.3.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:fe41b41505a5a33aeaed2a613dccaeaa74e0e3ead6dd6fd3a118fb471644fd6c", size = 261886 },
+ { url = "https://files.pythonhosted.org/packages/19/20/b57f9f7174fcd439a7789fb47d764974ab646fa34d1790551de386457a8e/contourpy-1.3.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eca7e17a65f72a5133bdbec9ecf22401c62bcf4821361ef7811faee695799779", size = 311008 },
+ { url = "https://files.pythonhosted.org/packages/74/fc/5040d42623a1845d4f17a418e590fd7a79ae8cb2bad2b2f83de63c3bdca4/contourpy-1.3.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:1ec4dc6bf570f5b22ed0d7efba0dfa9c5b9e0431aeea7581aa217542d9e809a4", size = 215690 },
+ { url = "https://files.pythonhosted.org/packages/2b/24/dc3dcd77ac7460ab7e9d2b01a618cb31406902e50e605a8d6091f0a8f7cc/contourpy-1.3.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:00ccd0dbaad6d804ab259820fa7cb0b8036bda0686ef844d24125d8287178ce0", size = 261894 },
+ { url = "https://files.pythonhosted.org/packages/b1/db/531642a01cfec39d1682e46b5457b07cf805e3c3c584ec27e2a6223f8f6c/contourpy-1.3.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8ca947601224119117f7c19c9cdf6b3ab54c5726ef1d906aa4a69dfb6dd58102", size = 311099 },
+ { url = "https://files.pythonhosted.org/packages/38/1e/94bda024d629f254143a134eead69e21c836429a2a6ce82209a00ddcb79a/contourpy-1.3.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:c6ec93afeb848a0845a18989da3beca3eec2c0f852322efe21af1931147d12cb", size = 215838 },
+]
+
+[[package]]
+name = "contourpy"
+version = "1.3.2"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "numpy", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/66/54/eb9bfc647b19f2009dd5c7f5ec51c4e6ca831725f1aea7a993034f483147/contourpy-1.3.2.tar.gz", hash = "sha256:b6945942715a034c671b7fc54f9588126b0b8bf23db2696e3ca8328f3ff0ab54", size = 13466130 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/a3/da4153ec8fe25d263aa48c1a4cbde7f49b59af86f0b6f7862788c60da737/contourpy-1.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ba38e3f9f330af820c4b27ceb4b9c7feee5fe0493ea53a8720f4792667465934", size = 268551 },
+ { url = "https://files.pythonhosted.org/packages/2f/6c/330de89ae1087eb622bfca0177d32a7ece50c3ef07b28002de4757d9d875/contourpy-1.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:dc41ba0714aa2968d1f8674ec97504a8f7e334f48eeacebcaa6256213acb0989", size = 253399 },
+ { url = "https://files.pythonhosted.org/packages/c1/bd/20c6726b1b7f81a8bee5271bed5c165f0a8e1f572578a9d27e2ccb763cb2/contourpy-1.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9be002b31c558d1ddf1b9b415b162c603405414bacd6932d031c5b5a8b757f0d", size = 312061 },
+ { url = "https://files.pythonhosted.org/packages/22/fc/a9665c88f8a2473f823cf1ec601de9e5375050f1958cbb356cdf06ef1ab6/contourpy-1.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8d2e74acbcba3bfdb6d9d8384cdc4f9260cae86ed9beee8bd5f54fee49a430b9", size = 351956 },
+ { url = "https://files.pythonhosted.org/packages/25/eb/9f0a0238f305ad8fb7ef42481020d6e20cf15e46be99a1fcf939546a177e/contourpy-1.3.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e259bced5549ac64410162adc973c5e2fb77f04df4a439d00b478e57a0e65512", size = 320872 },
+ { url = "https://files.pythonhosted.org/packages/32/5c/1ee32d1c7956923202f00cf8d2a14a62ed7517bdc0ee1e55301227fc273c/contourpy-1.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ad687a04bc802cbe8b9c399c07162a3c35e227e2daccf1668eb1f278cb698631", size = 325027 },
+ { url = "https://files.pythonhosted.org/packages/83/bf/9baed89785ba743ef329c2b07fd0611d12bfecbedbdd3eeecf929d8d3b52/contourpy-1.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:cdd22595308f53ef2f891040ab2b93d79192513ffccbd7fe19be7aa773a5e09f", size = 1306641 },
+ { url = "https://files.pythonhosted.org/packages/d4/cc/74e5e83d1e35de2d28bd97033426b450bc4fd96e092a1f7a63dc7369b55d/contourpy-1.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b4f54d6a2defe9f257327b0f243612dd051cc43825587520b1bf74a31e2f6ef2", size = 1374075 },
+ { url = "https://files.pythonhosted.org/packages/0c/42/17f3b798fd5e033b46a16f8d9fcb39f1aba051307f5ebf441bad1ecf78f8/contourpy-1.3.2-cp310-cp310-win32.whl", hash = "sha256:f939a054192ddc596e031e50bb13b657ce318cf13d264f095ce9db7dc6ae81c0", size = 177534 },
+ { url = "https://files.pythonhosted.org/packages/54/ec/5162b8582f2c994721018d0c9ece9dc6ff769d298a8ac6b6a652c307e7df/contourpy-1.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:c440093bbc8fc21c637c03bafcbef95ccd963bc6e0514ad887932c18ca2a759a", size = 221188 },
+ { url = "https://files.pythonhosted.org/packages/b3/b9/ede788a0b56fc5b071639d06c33cb893f68b1178938f3425debebe2dab78/contourpy-1.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6a37a2fb93d4df3fc4c0e363ea4d16f83195fc09c891bc8ce072b9d084853445", size = 269636 },
+ { url = "https://files.pythonhosted.org/packages/e6/75/3469f011d64b8bbfa04f709bfc23e1dd71be54d05b1b083be9f5b22750d1/contourpy-1.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b7cd50c38f500bbcc9b6a46643a40e0913673f869315d8e70de0438817cb7773", size = 254636 },
+ { url = "https://files.pythonhosted.org/packages/8d/2f/95adb8dae08ce0ebca4fd8e7ad653159565d9739128b2d5977806656fcd2/contourpy-1.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6658ccc7251a4433eebd89ed2672c2ed96fba367fd25ca9512aa92a4b46c4f1", size = 313053 },
+ { url = "https://files.pythonhosted.org/packages/c3/a6/8ccf97a50f31adfa36917707fe39c9a0cbc24b3bbb58185577f119736cc9/contourpy-1.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:70771a461aaeb335df14deb6c97439973d253ae70660ca085eec25241137ef43", size = 352985 },
+ { url = "https://files.pythonhosted.org/packages/1d/b6/7925ab9b77386143f39d9c3243fdd101621b4532eb126743201160ffa7e6/contourpy-1.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65a887a6e8c4cd0897507d814b14c54a8c2e2aa4ac9f7686292f9769fcf9a6ab", size = 323750 },
+ { url = "https://files.pythonhosted.org/packages/c2/f3/20c5d1ef4f4748e52d60771b8560cf00b69d5c6368b5c2e9311bcfa2a08b/contourpy-1.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3859783aefa2b8355697f16642695a5b9792e7a46ab86da1118a4a23a51a33d7", size = 326246 },
+ { url = "https://files.pythonhosted.org/packages/8c/e5/9dae809e7e0b2d9d70c52b3d24cba134dd3dad979eb3e5e71f5df22ed1f5/contourpy-1.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:eab0f6db315fa4d70f1d8ab514e527f0366ec021ff853d7ed6a2d33605cf4b83", size = 1308728 },
+ { url = "https://files.pythonhosted.org/packages/e2/4a/0058ba34aeea35c0b442ae61a4f4d4ca84d6df8f91309bc2d43bb8dd248f/contourpy-1.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d91a3ccc7fea94ca0acab82ceb77f396d50a1f67412efe4c526f5d20264e6ecd", size = 1375762 },
+ { url = "https://files.pythonhosted.org/packages/09/33/7174bdfc8b7767ef2c08ed81244762d93d5c579336fc0b51ca57b33d1b80/contourpy-1.3.2-cp311-cp311-win32.whl", hash = "sha256:1c48188778d4d2f3d48e4643fb15d8608b1d01e4b4d6b0548d9b336c28fc9b6f", size = 178196 },
+ { url = "https://files.pythonhosted.org/packages/5e/fe/4029038b4e1c4485cef18e480b0e2cd2d755448bb071eb9977caac80b77b/contourpy-1.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:5ebac872ba09cb8f2131c46b8739a7ff71de28a24c869bcad554477eb089a878", size = 222017 },
+ { url = "https://files.pythonhosted.org/packages/34/f7/44785876384eff370c251d58fd65f6ad7f39adce4a093c934d4a67a7c6b6/contourpy-1.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4caf2bcd2969402bf77edc4cb6034c7dd7c0803213b3523f111eb7460a51b8d2", size = 271580 },
+ { url = "https://files.pythonhosted.org/packages/93/3b/0004767622a9826ea3d95f0e9d98cd8729015768075d61f9fea8eeca42a8/contourpy-1.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:82199cb78276249796419fe36b7386bd8d2cc3f28b3bc19fe2454fe2e26c4c15", size = 255530 },
+ { url = "https://files.pythonhosted.org/packages/e7/bb/7bd49e1f4fa805772d9fd130e0d375554ebc771ed7172f48dfcd4ca61549/contourpy-1.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:106fab697af11456fcba3e352ad50effe493a90f893fca6c2ca5c033820cea92", size = 307688 },
+ { url = "https://files.pythonhosted.org/packages/fc/97/e1d5dbbfa170725ef78357a9a0edc996b09ae4af170927ba8ce977e60a5f/contourpy-1.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d14f12932a8d620e307f715857107b1d1845cc44fdb5da2bc8e850f5ceba9f87", size = 347331 },
+ { url = "https://files.pythonhosted.org/packages/6f/66/e69e6e904f5ecf6901be3dd16e7e54d41b6ec6ae3405a535286d4418ffb4/contourpy-1.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:532fd26e715560721bb0d5fc7610fce279b3699b018600ab999d1be895b09415", size = 318963 },
+ { url = "https://files.pythonhosted.org/packages/a8/32/b8a1c8965e4f72482ff2d1ac2cd670ce0b542f203c8e1d34e7c3e6925da7/contourpy-1.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f26b383144cf2d2c29f01a1e8170f50dacf0eac02d64139dcd709a8ac4eb3cfe", size = 323681 },
+ { url = "https://files.pythonhosted.org/packages/30/c6/12a7e6811d08757c7162a541ca4c5c6a34c0f4e98ef2b338791093518e40/contourpy-1.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c49f73e61f1f774650a55d221803b101d966ca0c5a2d6d5e4320ec3997489441", size = 1308674 },
+ { url = "https://files.pythonhosted.org/packages/2a/8a/bebe5a3f68b484d3a2b8ffaf84704b3e343ef1addea528132ef148e22b3b/contourpy-1.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3d80b2c0300583228ac98d0a927a1ba6a2ba6b8a742463c564f1d419ee5b211e", size = 1380480 },
+ { url = "https://files.pythonhosted.org/packages/34/db/fcd325f19b5978fb509a7d55e06d99f5f856294c1991097534360b307cf1/contourpy-1.3.2-cp312-cp312-win32.whl", hash = "sha256:90df94c89a91b7362e1142cbee7568f86514412ab8a2c0d0fca72d7e91b62912", size = 178489 },
+ { url = "https://files.pythonhosted.org/packages/01/c8/fadd0b92ffa7b5eb5949bf340a63a4a496a6930a6c37a7ba0f12acb076d6/contourpy-1.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:8c942a01d9163e2e5cfb05cb66110121b8d07ad438a17f9e766317bcb62abf73", size = 223042 },
+ { url = "https://files.pythonhosted.org/packages/2e/61/5673f7e364b31e4e7ef6f61a4b5121c5f170f941895912f773d95270f3a2/contourpy-1.3.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:de39db2604ae755316cb5967728f4bea92685884b1e767b7c24e983ef5f771cb", size = 271630 },
+ { url = "https://files.pythonhosted.org/packages/ff/66/a40badddd1223822c95798c55292844b7e871e50f6bfd9f158cb25e0bd39/contourpy-1.3.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3f9e896f447c5c8618f1edb2bafa9a4030f22a575ec418ad70611450720b5b08", size = 255670 },
+ { url = "https://files.pythonhosted.org/packages/1e/c7/cf9fdee8200805c9bc3b148f49cb9482a4e3ea2719e772602a425c9b09f8/contourpy-1.3.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71e2bd4a1c4188f5c2b8d274da78faab884b59df20df63c34f74aa1813c4427c", size = 306694 },
+ { url = "https://files.pythonhosted.org/packages/dd/e7/ccb9bec80e1ba121efbffad7f38021021cda5be87532ec16fd96533bb2e0/contourpy-1.3.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de425af81b6cea33101ae95ece1f696af39446db9682a0b56daaa48cfc29f38f", size = 345986 },
+ { url = "https://files.pythonhosted.org/packages/dc/49/ca13bb2da90391fa4219fdb23b078d6065ada886658ac7818e5441448b78/contourpy-1.3.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:977e98a0e0480d3fe292246417239d2d45435904afd6d7332d8455981c408b85", size = 318060 },
+ { url = "https://files.pythonhosted.org/packages/c8/65/5245ce8c548a8422236c13ffcdcdada6a2a812c361e9e0c70548bb40b661/contourpy-1.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:434f0adf84911c924519d2b08fc10491dd282b20bdd3fa8f60fd816ea0b48841", size = 322747 },
+ { url = "https://files.pythonhosted.org/packages/72/30/669b8eb48e0a01c660ead3752a25b44fdb2e5ebc13a55782f639170772f9/contourpy-1.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c66c4906cdbc50e9cba65978823e6e00b45682eb09adbb78c9775b74eb222422", size = 1308895 },
+ { url = "https://files.pythonhosted.org/packages/05/5a/b569f4250decee6e8d54498be7bdf29021a4c256e77fe8138c8319ef8eb3/contourpy-1.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8b7fc0cd78ba2f4695fd0a6ad81a19e7e3ab825c31b577f384aa9d7817dc3bef", size = 1379098 },
+ { url = "https://files.pythonhosted.org/packages/19/ba/b227c3886d120e60e41b28740ac3617b2f2b971b9f601c835661194579f1/contourpy-1.3.2-cp313-cp313-win32.whl", hash = "sha256:15ce6ab60957ca74cff444fe66d9045c1fd3e92c8936894ebd1f3eef2fff075f", size = 178535 },
+ { url = "https://files.pythonhosted.org/packages/12/6e/2fed56cd47ca739b43e892707ae9a13790a486a3173be063681ca67d2262/contourpy-1.3.2-cp313-cp313-win_amd64.whl", hash = "sha256:e1578f7eafce927b168752ed7e22646dad6cd9bca673c60bff55889fa236ebf9", size = 223096 },
+ { url = "https://files.pythonhosted.org/packages/54/4c/e76fe2a03014a7c767d79ea35c86a747e9325537a8b7627e0e5b3ba266b4/contourpy-1.3.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0475b1f6604896bc7c53bb070e355e9321e1bc0d381735421a2d2068ec56531f", size = 285090 },
+ { url = "https://files.pythonhosted.org/packages/7b/e2/5aba47debd55d668e00baf9651b721e7733975dc9fc27264a62b0dd26eb8/contourpy-1.3.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c85bb486e9be652314bb5b9e2e3b0d1b2e643d5eec4992c0fbe8ac71775da739", size = 268643 },
+ { url = "https://files.pythonhosted.org/packages/a1/37/cd45f1f051fe6230f751cc5cdd2728bb3a203f5619510ef11e732109593c/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:745b57db7758f3ffc05a10254edd3182a2a83402a89c00957a8e8a22f5582823", size = 310443 },
+ { url = "https://files.pythonhosted.org/packages/8b/a2/36ea6140c306c9ff6dd38e3bcec80b3b018474ef4d17eb68ceecd26675f4/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:970e9173dbd7eba9b4e01aab19215a48ee5dd3f43cef736eebde064a171f89a5", size = 349865 },
+ { url = "https://files.pythonhosted.org/packages/95/b7/2fc76bc539693180488f7b6cc518da7acbbb9e3b931fd9280504128bf956/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c6c4639a9c22230276b7bffb6a850dfc8258a2521305e1faefe804d006b2e532", size = 321162 },
+ { url = "https://files.pythonhosted.org/packages/f4/10/76d4f778458b0aa83f96e59d65ece72a060bacb20cfbee46cf6cd5ceba41/contourpy-1.3.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc829960f34ba36aad4302e78eabf3ef16a3a100863f0d4eeddf30e8a485a03b", size = 327355 },
+ { url = "https://files.pythonhosted.org/packages/43/a3/10cf483ea683f9f8ab096c24bad3cce20e0d1dd9a4baa0e2093c1c962d9d/contourpy-1.3.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:d32530b534e986374fc19eaa77fcb87e8a99e5431499949b828312bdcd20ac52", size = 1307935 },
+ { url = "https://files.pythonhosted.org/packages/78/73/69dd9a024444489e22d86108e7b913f3528f56cfc312b5c5727a44188471/contourpy-1.3.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e298e7e70cf4eb179cc1077be1c725b5fd131ebc81181bf0c03525c8abc297fd", size = 1372168 },
+ { url = "https://files.pythonhosted.org/packages/0f/1b/96d586ccf1b1a9d2004dd519b25fbf104a11589abfd05484ff12199cca21/contourpy-1.3.2-cp313-cp313t-win32.whl", hash = "sha256:d0e589ae0d55204991450bb5c23f571c64fe43adaa53f93fc902a84c96f52fe1", size = 189550 },
+ { url = "https://files.pythonhosted.org/packages/b0/e6/6000d0094e8a5e32ad62591c8609e269febb6e4db83a1c75ff8868b42731/contourpy-1.3.2-cp313-cp313t-win_amd64.whl", hash = "sha256:78e9253c3de756b3f6a5174d024c4835acd59eb3f8e2ca13e775dbffe1558f69", size = 238214 },
+ { url = "https://files.pythonhosted.org/packages/33/05/b26e3c6ecc05f349ee0013f0bb850a761016d89cec528a98193a48c34033/contourpy-1.3.2-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:fd93cc7f3139b6dd7aab2f26a90dde0aa9fc264dbf70f6740d498a70b860b82c", size = 265681 },
+ { url = "https://files.pythonhosted.org/packages/2b/25/ac07d6ad12affa7d1ffed11b77417d0a6308170f44ff20fa1d5aa6333f03/contourpy-1.3.2-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:107ba8a6a7eec58bb475329e6d3b95deba9440667c4d62b9b6063942b61d7f16", size = 315101 },
+ { url = "https://files.pythonhosted.org/packages/8f/4d/5bb3192bbe9d3f27e3061a6a8e7733c9120e203cb8515767d30973f71030/contourpy-1.3.2-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:ded1706ed0c1049224531b81128efbd5084598f18d8a2d9efae833edbd2b40ad", size = 220599 },
+ { url = "https://files.pythonhosted.org/packages/ff/c0/91f1215d0d9f9f343e4773ba6c9b89e8c0cc7a64a6263f21139da639d848/contourpy-1.3.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:5f5964cdad279256c084b69c3f412b7801e15356b16efa9d78aa974041903da0", size = 266807 },
+ { url = "https://files.pythonhosted.org/packages/d4/79/6be7e90c955c0487e7712660d6cead01fa17bff98e0ea275737cc2bc8e71/contourpy-1.3.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49b65a95d642d4efa8f64ba12558fcb83407e58a2dfba9d796d77b63ccfcaff5", size = 318729 },
+ { url = "https://files.pythonhosted.org/packages/87/68/7f46fb537958e87427d98a4074bcde4b67a70b04900cfc5ce29bc2f556c1/contourpy-1.3.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:8c5acb8dddb0752bf252e01a3035b21443158910ac16a3b0d20e7fed7d534ce5", size = 221791 },
+]
+
+[[package]]
+name = "coverage"
+version = "7.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/06/d1/7b18a2e0d2994e4e108dadf16580ec192e0a9c65f7456ccb82ced059f9bf/coverage-7.9.0.tar.gz", hash = "sha256:1a93b43de2233a7670a8bf2520fed8ebd5eea6a65b47417500a9d882b0533fa2", size = 813385 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/37/25/c83935ed228bd0ce277a9a92b505a4f67b0b15ba0344680974a77452c5dd/coverage-7.9.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:3d494fa4256e3cb161ca1df14a91d2d703c27d60452eb0d4a58bb05f52f676e4", size = 211940 },
+ { url = "https://files.pythonhosted.org/packages/36/42/c58ca1fec2a346ad12356fac955a9b6d848ab37f632a7cb1bc7476efcf90/coverage-7.9.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b613efceeabf242978d14e1a65626ec3be67c5261918a82a985f56c2a05475ee", size = 212329 },
+ { url = "https://files.pythonhosted.org/packages/64/0a/6b61e4348cf7b0a70f7995247cde5cc4b5ef0b61d9718109896c77d9ed0e/coverage-7.9.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:673a4d2cb7ec78e1f2f6f41039f6785f27bca0f6bc0e722b53a58286d12754e1", size = 241447 },
+ { url = "https://files.pythonhosted.org/packages/a9/1e/5f7060b909352cba70d34be0e34619659c0ddbef426665e036d5d3046b3c/coverage-7.9.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1edc2244932e9fed92ad14428b9480a97ecd37c970333688bd35048f6472f260", size = 239322 },
+ { url = "https://files.pythonhosted.org/packages/f5/78/f4ba669c9bf15b537136b663ccb846032cfb73e28b59458ef6899f18fe07/coverage-7.9.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ec8b92a7617faa2017bd44c94583830bab8be175722d420501680abc4f5bc794", size = 240467 },
+ { url = "https://files.pythonhosted.org/packages/79/38/3246ea3ac68dc6f85afac0cb0362d3703647378b9882d55796c71fe83a1a/coverage-7.9.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:d8f3ca1f128f11812d3baf0a482e7f36ffb856ac1ae14de3b5d1adcfb7af955d", size = 240376 },
+ { url = "https://files.pythonhosted.org/packages/c0/58/ef1f20afbaf9affe2941e7b077a8cf08075c6e3fe5e1dfc3160908b6a1de/coverage-7.9.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:c30eed34eb8206d9b8c2d0d9fa342fa98e10f34b1e9e1eb05f79ccbf4499c8ff", size = 239046 },
+ { url = "https://files.pythonhosted.org/packages/09/ba/d510b05b3ca0da8fe746acf8ac815b2d560d6c4d5c4e0f6eafb2ec27dc33/coverage-7.9.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:24e6f8e5f125cd8bff33593a484a079305c9f0be911f76c6432f580ade5c1a17", size = 239318 },
+ { url = "https://files.pythonhosted.org/packages/82/c7/328a412e3bd78c049180df3f4374bb13a332ed8731ff66f49578d5ebf98c/coverage-7.9.0-cp310-cp310-win32.whl", hash = "sha256:a1b0317b4a8ff4d3703cd7aa642b4f963a71255abe4e878659f768238fab6602", size = 214430 },
+ { url = "https://files.pythonhosted.org/packages/db/a5/0e788cc4796989d77bfb6b1c58819edc2c65522926f0c08cfe42d1529f2b/coverage-7.9.0-cp310-cp310-win_amd64.whl", hash = "sha256:512b1ea57a11dfa23b7f3d8fe8690fcf8cd983a70ae4c2c262cf5c972618fa15", size = 215350 },
+ { url = "https://files.pythonhosted.org/packages/9d/91/721a7df15263babfe89caf535a08bacbadebdef87338cf37d40f7400161b/coverage-7.9.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:55b7b9df45174956e0f719a56cf60c0cb4a7f155668881d00de6384e2a3402f4", size = 212055 },
+ { url = "https://files.pythonhosted.org/packages/8d/d6/1f4c1eae67e698a8535ede02a6958a7587d06869d33a9b134ecc0e17ee07/coverage-7.9.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:87bceebbc91a58c9264c43638729fcb45910805b9f86444f93654d988305b3a2", size = 212445 },
+ { url = "https://files.pythonhosted.org/packages/bd/48/c375a6e6a266efa2d5fbf9b04eac88c87430d1a337b4f383ea8beeeedd44/coverage-7.9.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81da3b6e289bf9fc7dc159ab6d5222f5330ac6e94a6d06f147ba46e53fa6ec82", size = 245010 },
+ { url = "https://files.pythonhosted.org/packages/7a/43/ec070ad02a1ee10837555a852b6fa256f8c71a953c209488e027673fc5b6/coverage-7.9.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b361684a91224d4362879c1b1802168d2435ff76666f1b7ba52fc300ad832dbc", size = 242725 },
+ { url = "https://files.pythonhosted.org/packages/fa/ff/8b8efbd058dd59b489d9c5e27ba5766e895c396dd3bd1b78bebef9808c5f/coverage-7.9.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f9a384ea4f77ac0a7e36c9a805ed95ef10f423bdb68b4e9487646cdf548a6a05", size = 244527 },
+ { url = "https://files.pythonhosted.org/packages/9d/e7/3863f458a3af009a4817656f5b56fa90c7e363d73fef338601b275e979c4/coverage-7.9.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:38a5642aa82ea6de0e4331e346f5ba188a9fdb7d727e00199f55031b85135d0a", size = 244174 },
+ { url = "https://files.pythonhosted.org/packages/4b/f0/2ff1fa06ccd3c3d653e352b10ddeec511b018890b28dbd3c29b6ea3f742e/coverage-7.9.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:8c5ff4ca4890c0b57d3e80850534609493280c0f9e6ea2bd314b10cb8cbd76e0", size = 242227 },
+ { url = "https://files.pythonhosted.org/packages/32/e2/bae13555436f1d0278e70cfe22a0980eab9809e89361e859c96ffa788cb9/coverage-7.9.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:cd052a0c4727ede06393da3c1df1ae6ef6c079e6bdfefb39079877404b3edc22", size = 242815 },
+ { url = "https://files.pythonhosted.org/packages/20/7c/e1b5b3313c1e3a5e8f8ced567fee67f18c8f18cebee8af0d69052f445a55/coverage-7.9.0-cp311-cp311-win32.whl", hash = "sha256:f73fd1128165e1d665cb7f863a91d00f073044a672c7dfa04ab400af4d1a9226", size = 214469 },
+ { url = "https://files.pythonhosted.org/packages/6a/c9/0034d3ccbb7b8f80b1ce8a927ea06e2ba265bd0ba4a9a95a83026ac78dfd/coverage-7.9.0-cp311-cp311-win_amd64.whl", hash = "sha256:dd62d62e782d3add529c8e7943f5600efd0d07dadf3819e5f9917edb4acf85d8", size = 215407 },
+ { url = "https://files.pythonhosted.org/packages/f1/e1/7473bf679a43638c5ccba6228f45f68d33c3b7414ffae757dbb0bb2f1127/coverage-7.9.0-cp311-cp311-win_arm64.whl", hash = "sha256:f75288785cc9a67aff3b04dafd8d0f0be67306018b224d319d23867a161578d6", size = 213778 },
+ { url = "https://files.pythonhosted.org/packages/dd/6b/7bdef79e79076c7e3303ce2453072528ed13988210fb7a8702bb3d98ea8c/coverage-7.9.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:969ed1ed0ab0325b50af3204f9024782180e64fb281f5a2952f479ec60a02aba", size = 212252 },
+ { url = "https://files.pythonhosted.org/packages/08/fe/7e08dd50c3c3cfdbe822ee11e24da9f418983faefb4f5e52fbffae5beeb2/coverage-7.9.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1abd41781c874e716aaeecb8b27db5f4f2bc568f2ed8d41228aa087d567674f0", size = 212491 },
+ { url = "https://files.pythonhosted.org/packages/d4/65/9793cf61b3e4c5647e70aabd5b9470958ffd341c42f90730beeb4d21af9c/coverage-7.9.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0eb6e99487dffd28c88a4fc2ea4286beaf0207a43388775900c93e56cc5a8ae3", size = 246294 },
+ { url = "https://files.pythonhosted.org/packages/2a/c9/fc61695132da06a34b27a49e853010a80d66a5534a1dfa770cb38aca71c0/coverage-7.9.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c425c85ddb62b32d44f83fb20044fe32edceceee1db1f978c062eec020a73ea5", size = 243311 },
+ { url = "https://files.pythonhosted.org/packages/62/0e/559a86887580d0de390e018bddfa632ae0762eeeb065bb5557f319071527/coverage-7.9.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d0a1f7676bc90ceba67caa66850d689947d586f204ccf6478400c2bf39da5790", size = 245503 },
+ { url = "https://files.pythonhosted.org/packages/45/09/344d012dc91e60b8c7afee11ffae18338780c703a5b5fb32d8d82987e7cb/coverage-7.9.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f17055c50768d710d6abc789c9469d0353574780935e1381b83e63edc49ff530", size = 245313 },
+ { url = "https://files.pythonhosted.org/packages/d2/2d/151b23e82aaea28aa7e3c0390d893bd1aef685866132aad36034f7d462b8/coverage-7.9.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:298d2917a6bfadbb272e08545ed026af3965e4d2fe71e3f38bf0a816818b226e", size = 243495 },
+ { url = "https://files.pythonhosted.org/packages/74/5c/0da7fd4ad44259b4b61bd429dc642c6511314a356ffa782b924bd1ea9e5c/coverage-7.9.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d9be5d26e5f817d478506e4d3c4ff7b92f17d980670b4791bf05baaa37ce2f88", size = 244727 },
+ { url = "https://files.pythonhosted.org/packages/de/08/6ccf2847c5c0d8fcc153bd8f4341d89ab50c85e01a15cabe4a546d3e943e/coverage-7.9.0-cp312-cp312-win32.whl", hash = "sha256:dc2784edd9ac9fe8692fc5505667deb0b05d895c016aaaf641031ed4a5f93d53", size = 214636 },
+ { url = "https://files.pythonhosted.org/packages/79/fa/ae2c14d49475215372772f7638c333deaaacda8f3c5717a75377d1992c82/coverage-7.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:18223198464a6d5549db1934cf77a15deb24bb88652c4f5f7cb21cd3ad853704", size = 215448 },
+ { url = "https://files.pythonhosted.org/packages/62/a9/45309219ba08b89cae84b2cb4ccfed8f941850aa7721c4914282fb3c1081/coverage-7.9.0-cp312-cp312-win_arm64.whl", hash = "sha256:3b00194ff3c84d4b821822ff6c041f245fc55d0d5c7833fc4311d082e97595e8", size = 213817 },
+ { url = "https://files.pythonhosted.org/packages/0b/59/449eb05f795d0050007b57a4efee79b540fa6fcccad813a191351964a001/coverage-7.9.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:122c60e92ab66c9c88e17565f67a91b3b3be5617cb50f73cfd34a4c60ed4aab0", size = 212271 },
+ { url = "https://files.pythonhosted.org/packages/e0/3b/26852a4fb719a6007b0169c1b52116ed14b61267f0bf3ba1e23db516f352/coverage-7.9.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:813c11b367a6b3cf37212ec36b230f8d086c22b69dbf62877b40939fb2c79e74", size = 212538 },
+ { url = "https://files.pythonhosted.org/packages/f6/80/99f82896119f36984a5b9189e71c7310fc036613276560b5884b5ee890d7/coverage-7.9.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3f05e0f5e87f23d43fefe49e86655c6209dd4f9f034786b983e6803cf4554183", size = 245705 },
+ { url = "https://files.pythonhosted.org/packages/a9/29/0b007deb096dd527c42e933129a8e4d5f9f1026f4953979c3a1e60e7ea9f/coverage-7.9.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:62f465886fa4f86d5515da525aead97c5dff13a5cf997fc4c5097a1a59e063b2", size = 242918 },
+ { url = "https://files.pythonhosted.org/packages/6f/eb/273855b57c7fb387dd9787f250b8b333ba8c1c100877c21e32eb1b24ff29/coverage-7.9.0-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:549ea4ca901595bbe3270e1afdef98bf5d4d5791596efbdc90b00449a2bb1f91", size = 244902 },
+ { url = "https://files.pythonhosted.org/packages/20/57/4e411b47dbfd831538ecf9e5f407e42888b0c56aedbfe0ea7b102a787559/coverage-7.9.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8cae1d4450945c74a6a65a09864ed3eaa917055cf70aa65f83ac1b9b0d8d5f9a", size = 245069 },
+ { url = "https://files.pythonhosted.org/packages/91/75/b24cf5703fb325fc4b1899d89984dac117b99e757b9fadd525cad7ecc020/coverage-7.9.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d7b263910234c0d5ec913ec79ca921152fe874b805a7bcaf67118ef71708e5d2", size = 243040 },
+ { url = "https://files.pythonhosted.org/packages/c7/e1/9495751d5315c3d76ee2c7b5dbc1935ab891d45ad585e1910a333dbdef43/coverage-7.9.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7d7b7425215963da8f5968096a20c5b5c9af4a86a950fcc25dcc2177ab33e9e5", size = 244424 },
+ { url = "https://files.pythonhosted.org/packages/94/2a/ee504188a586da2379939f37fdc69047d9c46d35c34d1196f2605974a17d/coverage-7.9.0-cp313-cp313-win32.whl", hash = "sha256:e7dcfa92867b0c53d2e22e985c66af946dc09e8bb13c556709e396e90a0adf5c", size = 214677 },
+ { url = "https://files.pythonhosted.org/packages/80/2b/5eab6518643c7560fe180ba5e0f35a0be3d4fc0a88aa6601120407b1fd03/coverage-7.9.0-cp313-cp313-win_amd64.whl", hash = "sha256:aa34ca040785a2b768da489df0c036364d47a6c1c00bdd8f662b98fd3277d3d4", size = 215482 },
+ { url = "https://files.pythonhosted.org/packages/fd/7f/9c9c8b736c4f40d7247bea8339afac40d8f6465491440608b3d73c10ffce/coverage-7.9.0-cp313-cp313-win_arm64.whl", hash = "sha256:9c5dcb5cd3c52d84c5f52045e1c87c16bf189c2fbfa57cc0d811a3b4059939df", size = 213852 },
+ { url = "https://files.pythonhosted.org/packages/e5/83/056464aec8b360dee6f4d7a517dc5ae5a9f462ff895ff536588b42f95b2d/coverage-7.9.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:b52d2fdc1940f90c4572bd48211475a7b102f75a7f9a5e6cfc6e3da7dc380c44", size = 212994 },
+ { url = "https://files.pythonhosted.org/packages/a3/87/f0291ecaa6baaaedbd428cf8b7e1d16b5dc010718fe7739cce955149ef83/coverage-7.9.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4cc555a3e6ceb8841df01a4634374f5f9635e661f5c307da00bce19819e8bcdf", size = 213212 },
+ { url = "https://files.pythonhosted.org/packages/16/a0/9eb39541774a5beb662dc4ae98fee23afb947414b6aa1443b53d2ad3ea05/coverage-7.9.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:244f613617876b7cd32a097788d49c952a8f1698afb25275b2a825a4e895854e", size = 256453 },
+ { url = "https://files.pythonhosted.org/packages/93/33/d0e99f4c809334dfed20f17234080a9003a713ddb80e33ad22697a8aa8e5/coverage-7.9.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5c335d77539e66bc6f83e8f1ef207d038129d9b9acd9dc9f0ca42fa9eedf564a", size = 252674 },
+ { url = "https://files.pythonhosted.org/packages/0b/3a/d2a64e7ee5eb783e44e6ca404f8fc2a45afef052ed6593afb4ce9663dae6/coverage-7.9.0-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6b335c7077c8da7bb8173d4f9ebd90ff1a97af6a6bec4fc4e6db4856ae80b31e", size = 254830 },
+ { url = "https://files.pythonhosted.org/packages/e2/6a/9de640f8e2b097d155532d1bc16eb9c5186fccc7c4b8148fe1dd2520875a/coverage-7.9.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:01cbc2c36895b7ab906514042c92b3fc9dd0526bf1c3251cb6aefd9c71ae6dda", size = 256060 },
+ { url = "https://files.pythonhosted.org/packages/07/72/928fa3583b9783fc32e3dfafb6cc0cf73bdd73d1dc41e3a973f203c6aeff/coverage-7.9.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:1ac62880a9dff0726a193ce77a1bcdd4e8491009cb3a0510d31381e8b2c46d7a", size = 254174 },
+ { url = "https://files.pythonhosted.org/packages/ad/01/2fd0785f8768693b748e36b442352bc26edf3391246eedcc80d480d06da1/coverage-7.9.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:95314eb306cf54af3d1147e27ba008cf78eed6f1309a1310772f4f05b12c9c65", size = 255011 },
+ { url = "https://files.pythonhosted.org/packages/b7/49/1d0120cfa24e001e0d38795388914183c48cd86fc8640ca3b01337831917/coverage-7.9.0-cp313-cp313t-win32.whl", hash = "sha256:c5cbf3ddfb68de8dc8ce33caa9321df27297a032aeaf2e99b278f183fb4ebc37", size = 215349 },
+ { url = "https://files.pythonhosted.org/packages/9f/48/7625c09621a206fff0b51fcbcf5d6c1162ab10a5ffa546fc132f01c9132b/coverage-7.9.0-cp313-cp313t-win_amd64.whl", hash = "sha256:e3ec9e1525eb7a0f89d31083539b398d921415d884e9f55400002a1e9fe0cf63", size = 216516 },
+ { url = "https://files.pythonhosted.org/packages/bb/50/048b55c34985c3aafcecb32cced3abc4291969bfd967dbcaed95cfc26b2a/coverage-7.9.0-cp313-cp313t-win_arm64.whl", hash = "sha256:a02efe6769f74245ce476e89db3d4e110db07b4c0c3d3f81728e2464bbbbcb8e", size = 214308 },
+ { url = "https://files.pythonhosted.org/packages/c3/4e/4c72909d117d593e388c82b8bc29f99ad0fe20fe84f6390ee14d5650b750/coverage-7.9.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:64dab59d812c1cbfc9cebadada377365874964acdf59b12e86487d25c2e0c29f", size = 211938 },
+ { url = "https://files.pythonhosted.org/packages/84/84/8e2e1ebe02a5c68c4ac54668392ee00fa5ea8e7989b339d847fff27220bd/coverage-7.9.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:46b9dc640c6309fb49625d3569d4ba7abe2afcba645eb1e52bad97510f60ac26", size = 212314 },
+ { url = "https://files.pythonhosted.org/packages/1c/61/931117485d6917f4719be2bf8cc25c79c7108c078b005b38882688e1f41b/coverage-7.9.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:89358f4025ed424861311b33815a2866f7c94856c932b0ffc98180f655e813e2", size = 241077 },
+ { url = "https://files.pythonhosted.org/packages/f9/58/431fbfb00a4dfc1d845b70d296b503d306be76d07a67a4046b15e42c8234/coverage-7.9.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:589e37ae75d81fd53cd1ca624e07af4466e9e4ce259e3bfe2b147896857c06ea", size = 238945 },
+ { url = "https://files.pythonhosted.org/packages/a5/e2/8b2cc9b761bee876472379db92d017d7042eeaddba35adf67f54e3ceff3d/coverage-7.9.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:29dea81eef5432076cee561329b3831bc988a4ce1bfaec90eee2078ff5311e6e", size = 240063 },
+ { url = "https://files.pythonhosted.org/packages/6c/39/e1b0ba8cac5ae66a13475cb08b184f06d89515b6ea6ed45cd678ae2fbcb1/coverage-7.9.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:7b3482588772b6b24601d1677aef299af28d6c212c70b0be27bdfc2e10fb00fe", size = 239789 },
+ { url = "https://files.pythonhosted.org/packages/6e/91/b6b926cd875cd03989abb696ccbbd5895e367e6394dcf7c264180f72d038/coverage-7.9.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:2debc0b9481b5fc76f771b3b31e89a0cd8791ad977654940a3523f3f2e5d98fe", size = 238041 },
+ { url = "https://files.pythonhosted.org/packages/43/ce/de736582c44906b5d6067b650ac851d5f249e246753b9d8f7369e7eea00a/coverage-7.9.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:304ded640bc2a60f14a2ff0fec98cce4c3f2e573c122f0548728c8dceba5abe7", size = 238977 },
+ { url = "https://files.pythonhosted.org/packages/27/d3/35317997155b16b140a2c62f09e001a12e244b2d410deb5b8cfa861173f4/coverage-7.9.0-cp39-cp39-win32.whl", hash = "sha256:8e0a3a3f9b968007e1f56418a3586f9a983c84ac4e84d28d1c4f8b76c4226282", size = 214442 },
+ { url = "https://files.pythonhosted.org/packages/0a/42/d4bcd2900c05bdb5773d47173395c68c147b4ca2564e791c8c9b0ed42c73/coverage-7.9.0-cp39-cp39-win_amd64.whl", hash = "sha256:cb3c07dd71d1ff52156d35ee6fa48458c3cec1add7fcce6a934f977fb80c48a5", size = 215351 },
+ { url = "https://files.pythonhosted.org/packages/e8/b6/d16966f9439ccc3007e1740960d241420d6ba81502642a4be1da1672a103/coverage-7.9.0-pp39.pp310.pp311-none-any.whl", hash = "sha256:ccf1540a0e82ff525844880f988f6caaa2d037005e57bfe203b71cac7626145d", size = 203927 },
+ { url = "https://files.pythonhosted.org/packages/70/0d/534c1e35cb7688b5c40de93fcca07e3ddc0287659ff85cd376b1dd3f770f/coverage-7.9.0-py3-none-any.whl", hash = "sha256:79ea9a26b27c963cdf541e1eb9ac05311b012bc367d0e31816f1833b06c81c02", size = 203917 },
+]
+
+[package.optional-dependencies]
+toml = [
+ { name = "tomli", marker = "python_full_version <= '3.11'" },
+]
+
+[[package]]
+name = "cuda-bindings"
+version = "12.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pywin32", marker = "sys_platform == 'win32'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/aa/1d/863af72fbfe7ffbdd0a58238682d625365649757906c64c0f88557236475/cuda_bindings-12.9.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2ec34fe4327d9dc9d935fa11c1d61fbec6adbfd271d9b794fb3a60044df49da", size = 12205459 },
+ { url = "https://files.pythonhosted.org/packages/03/30/f5f2da321f72c23af9bb9df947ef5f53a1efe536d8ec4ccdacdfac25174d/cuda_bindings-12.9.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:050e82a8d1ee4d8ac04fc56cf6f98cfea72225447f4a57e477fd455484b88818", size = 12583818 },
+ { url = "https://files.pythonhosted.org/packages/28/f8/fb2de39c185769442c4a7f4aa044b529cd8eb544eef771b97f71d25f1790/cuda_bindings-12.9.0-cp310-cp310-win_amd64.whl", hash = "sha256:03c9335369080309f94a20e458d912ce2b096ec67593b0babc293b9c49148fb9", size = 12077022 },
+ { url = "https://files.pythonhosted.org/packages/59/de/c40a497192f8a3c7f5962be11a3ec7d029b90e5dcc6b77bf2bb82a5efc3a/cuda_bindings-12.9.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8d77bf2a9c74477be39f7489f882a9a52f5205a4c832e90083458c4c0b59f6e5", size = 12159817 },
+ { url = "https://files.pythonhosted.org/packages/49/0d/82de160bd477c1a51195a49476dd7e3b538432c8717fd636bffc9c806076/cuda_bindings-12.9.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f543acf44f1d119c148c49937810451541a8618b054cc779fb1fa21ab46da64c", size = 12510735 },
+ { url = "https://files.pythonhosted.org/packages/c4/44/8479b2a051c28cfa9b4f440c1144e157a1b3fe8841c4d5d40455eb8913a4/cuda_bindings-12.9.0-cp311-cp311-win_amd64.whl", hash = "sha256:37e186e1f6e74c3d589a168839ed674eb3550e163dd4ae712a7289fd19a01e08", size = 12093223 },
+ { url = "https://files.pythonhosted.org/packages/5f/bf/23a583b8453f580bb1c7749c7abf57017176e0053197384ce81e73977ab3/cuda_bindings-12.9.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:34318c3a1b442854f072f5bb410aea6834172fd1ee7a5ecf49f1d125ea7498a0", size = 11820737 },
+ { url = "https://files.pythonhosted.org/packages/e3/03/40fc1488727a8d72ecc35f58f9df4939277892a837614339c3366d520426/cuda_bindings-12.9.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ff0e28d1e34758654b9c961e1f55e4786e49aee6a4dbceaf3cc24c46c672df7e", size = 12154006 },
+ { url = "https://files.pythonhosted.org/packages/2c/6a/2808871d0b519364db2b460dc1b17d4fff3e340d5875144a303254f996e5/cuda_bindings-12.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:57bdaa778116ee50fdcdd31810e0f345c23549ffb045452dc88d5c63601d35d4", size = 12223544 },
+ { url = "https://files.pythonhosted.org/packages/a0/29/7b9e64e3078e31516dad683d6a23f5e5a0d5c2b642c58fb23786ec4bfac6/cuda_bindings-12.9.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b9d039981412575c1713915a889934ec750b8c2ed3dbfaa739292e0478a3f6f", size = 11810588 },
+ { url = "https://files.pythonhosted.org/packages/01/fd/1c30778265488c6797c6c17a69c09ba5636df6dc6b0ebfc96d950be2f9e7/cuda_bindings-12.9.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6d7314b2e5db025bb88ddba4df6db2127cc39610ccf4f74c0e1ead05241da29", size = 12149149 },
+ { url = "https://files.pythonhosted.org/packages/d0/86/fdf309b334db8c6555f303c0f6a1538db53135103d13a78d8445b4981f15/cuda_bindings-12.9.0-cp313-cp313-win_amd64.whl", hash = "sha256:44eae9c854a55c7f464f08fa895a1fe0846e36097697d8c255051789d59bf55b", size = 12188603 },
+ { url = "https://files.pythonhosted.org/packages/c3/cb/68e58ec0b0352e8185944653eb8641997ea1a7889631cae1d93b4d411c9b/cuda_bindings-12.9.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c14ebaab52de662e0244df353dd11e477d94cca7bd3c956711d9cf1cba5a194d", size = 12211280 },
+ { url = "https://files.pythonhosted.org/packages/1a/47/9c16b088a9ed1d7f9b2c5a73866df41fe61eb460222bb75281a1159491fd/cuda_bindings-12.9.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98391b6c811dd6565a23b89dcd3d5a530c0d1557a37d3c915670931b6578052b", size = 12583971 },
+ { url = "https://files.pythonhosted.org/packages/37/f6/146d224abf666066cb231bf0def371be1a52539f9cfc1528e82cba719f22/cuda_bindings-12.9.0-cp39-cp39-win_amd64.whl", hash = "sha256:3d0bc07c587f609880bfad2709197bfebbb750636528a18c9789069b1490defb", size = 12065791 },
+]
+
+[[package]]
+name = "cuda-python"
+version = "12.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cuda-bindings" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/24/3c/4475aebeaab9651f2e61000fbe76f91a476d371dbfbf0a1cf46e689af253/cuda_python-12.9.0-py3-none-any.whl", hash = "sha256:926acba49b2c0a0374c61b7c98f337c085199cf51cdfe4d6423c4129c20547a7", size = 7532 },
+]
+
+[[package]]
+name = "cycler"
+version = "0.12.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321 },
+]
+
+[[package]]
+name = "dataclasses-json"
+version = "0.6.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "marshmallow" },
+ { name = "typing-inspect" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/64/a4/f71d9cf3a5ac257c993b5ca3f93df5f7fb395c725e7f1e6479d2514173c3/dataclasses_json-0.6.7.tar.gz", hash = "sha256:b6b3e528266ea45b9535223bc53ca645f5208833c29229e847b3f26a1cc55fc0", size = 32227 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c3/be/d0d44e092656fe7a06b55e6103cbce807cdbdee17884a5367c68c9860853/dataclasses_json-0.6.7-py3-none-any.whl", hash = "sha256:0dbf33f26c8d5305befd61b39d2b3414e8a407bedc2834dea9b8d642666fb40a", size = 28686 },
+]
+
+[[package]]
+name = "datasets"
+version = "3.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "dill" },
+ { name = "filelock" },
+ { name = "fsspec", extra = ["http"] },
+ { name = "huggingface-hub" },
+ { name = "multiprocess" },
+ { name = "numpy" },
+ { name = "packaging" },
+ { name = "pandas" },
+ { name = "pyarrow" },
+ { name = "pyyaml" },
+ { name = "requests" },
+ { name = "tqdm" },
+ { name = "xxhash" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/1a/89/d3d6fef58a488f8569c82fd293ab7cbd4250244d67f425dcae64c63800ea/datasets-3.6.0.tar.gz", hash = "sha256:1b2bf43b19776e2787e181cfd329cb0ca1a358ea014780c3581e0f276375e041", size = 569336 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/34/a08b0ee99715eaba118cbe19a71f7b5e2425c2718ef96007c325944a1152/datasets-3.6.0-py3-none-any.whl", hash = "sha256:25000c4a2c0873a710df127d08a202a06eab7bf42441a6bc278b499c2f72cd1b", size = 491546 },
+]
+
+[[package]]
+name = "decorator"
+version = "5.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/43/fa/6d96a0978d19e17b68d634497769987b16c8f4cd0a7a05048bec693caa6b/decorator-5.2.1.tar.gz", hash = "sha256:65f266143752f734b0a7cc83c46f4618af75b8c5911b00ccb61d0ac9b6da0360", size = 56711 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl", hash = "sha256:d316bb415a2d9e2d2b3abcc4084c6502fc09240e292cd76a76afc106a1c8e04a", size = 9190 },
+]
+
+[[package]]
+name = "decord"
+version = "0.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/11/79/936af42edf90a7bd4e41a6cac89c913d4b47fa48a26b042d5129a9242ee3/decord-0.6.0-py3-none-manylinux2010_x86_64.whl", hash = "sha256:51997f20be8958e23b7c4061ba45d0efcd86bffd5fe81c695d0befee0d442976", size = 13602299 },
+ { url = "https://files.pythonhosted.org/packages/6c/be/e15b5b866da452e62635a7b27513f31cb581fa2ea9cc9b768b535d62a955/decord-0.6.0-py3-none-win_amd64.whl", hash = "sha256:02665d7c4f1193a330205a791bc128f7e108eb6ae5b67144437a02f700943bad", size = 24733380 },
+]
+
+[[package]]
+name = "deprecated"
+version = "1.2.18"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/98/97/06afe62762c9a8a86af0cfb7bfdab22a43ad17138b07af5b1a58442690a2/deprecated-1.2.18.tar.gz", hash = "sha256:422b6f6d859da6f2ef57857761bfb392480502a64c3028ca9bbe86085d72115d", size = 2928744 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6e/c6/ac0b6c1e2d138f1002bcf799d330bd6d85084fece321e662a14223794041/Deprecated-1.2.18-py2.py3-none-any.whl", hash = "sha256:bd5011788200372a32418f888e326a09ff80d0214bd961147cfed01b5c018eec", size = 9998 },
+]
+
+[[package]]
+name = "dill"
+version = "0.3.8"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/17/4d/ac7ffa80c69ea1df30a8aa11b3578692a5118e7cd1aa157e3ef73b092d15/dill-0.3.8.tar.gz", hash = "sha256:3ebe3c479ad625c4553aca177444d89b486b1d84982eeacded644afc0cf797ca", size = 184847 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c9/7a/cef76fd8438a42f96db64ddaa85280485a9c395e7df3db8158cfec1eee34/dill-0.3.8-py3-none-any.whl", hash = "sha256:c36ca9ffb54365bdd2f8eb3eff7d2a21237f8452b57ace88b1ac615b7e815bd7", size = 116252 },
+]
+
+[[package]]
+name = "dirtyjson"
+version = "1.0.8"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/db/04/d24f6e645ad82ba0ef092fa17d9ef7a21953781663648a01c9371d9e8e98/dirtyjson-1.0.8.tar.gz", hash = "sha256:90ca4a18f3ff30ce849d100dcf4a003953c79d3a2348ef056f1d9c22231a25fd", size = 30782 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/68/69/1bcf70f81de1b4a9f21b3a62ec0c83bdff991c88d6cc2267d02408457e88/dirtyjson-1.0.8-py3-none-any.whl", hash = "sha256:125e27248435a58acace26d5c2c4c11a1c0de0a9c5124c5a94ba78e517d74f53", size = 25197 },
+]
+
+[[package]]
+name = "diskcache"
+version = "5.6.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/3f/21/1c1ffc1a039ddcc459db43cc108658f32c57d271d7289a2794e401d0fdb6/diskcache-5.6.3.tar.gz", hash = "sha256:2c3a3fa2743d8535d832ec61c2054a1641f41775aa7c556758a109941e33e4fc", size = 67916 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3f/27/4570e78fc0bf5ea0ca45eb1de3818a23787af9b390c0b0a0033a1b8236f9/diskcache-5.6.3-py3-none-any.whl", hash = "sha256:5e31b2d5fbad117cc363ebaf6b689474db18a1f6438bc82358b024abd4c2ca19", size = 45550 },
+]
+
+[[package]]
+name = "distro"
+version = "1.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277 },
+]
+
+[[package]]
+name = "docutils"
+version = "0.21.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ae/ed/aefcc8cd0ba62a0560c3c18c33925362d46c6075480bfa4df87b28e169a9/docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f", size = 2204444 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8f/d7/9322c609343d929e75e7e5e6255e614fcc67572cfd083959cdef3b7aad79/docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2", size = 587408 },
+]
+
+[[package]]
+name = "einops"
+version = "0.8.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359 },
+]
+
+[[package]]
+name = "eval-type-backport"
+version = "0.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/30/ea/8b0ac4469d4c347c6a385ff09dc3c048c2d021696664e26c7ee6791631b5/eval_type_backport-0.2.2.tar.gz", hash = "sha256:f0576b4cf01ebb5bd358d02314d31846af5e07678387486e2c798af0e7d849c1", size = 9079 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ce/31/55cd413eaccd39125368be33c46de24a1f639f2e12349b0361b4678f3915/eval_type_backport-0.2.2-py3-none-any.whl", hash = "sha256:cb6ad7c393517f476f96d456d0412ea80f0a8cf96f6892834cd9340149111b0a", size = 5830 },
+]
+
+[[package]]
+name = "evaluate"
+version = "0.4.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "datasets" },
+ { name = "dill" },
+ { name = "fsspec", extra = ["http"] },
+ { name = "huggingface-hub" },
+ { name = "multiprocess" },
+ { name = "numpy" },
+ { name = "packaging" },
+ { name = "pandas" },
+ { name = "requests" },
+ { name = "tqdm" },
+ { name = "xxhash" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5a/a0/10a56e0939ece94c54276e81459cb4101f46f0e9a6f54fc31a35f64e8854/evaluate-0.4.3.tar.gz", hash = "sha256:3a5700cf83aabee9549264e1e5666f116367c61dbd4d38352015e859a5e2098d", size = 65679 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/e7/cbca9e2d2590eb9b5aa8f7ebabe1beb1498f9462d2ecede5c9fd9735faaf/evaluate-0.4.3-py3-none-any.whl", hash = "sha256:47d8770bdea76e2c2ed0d40189273027d1a41ccea861bcc7ba12d30ec5d1e517", size = 84010 },
+]
+
+[[package]]
+name = "exceptiongroup"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674 },
+]
+
+[[package]]
+name = "executing"
+version = "2.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/91/50/a9d80c47ff289c611ff12e63f7c5d13942c65d68125160cefd768c73e6e4/executing-2.2.0.tar.gz", hash = "sha256:5d108c028108fe2551d1a7b2e8b713341e2cb4fc0aa7dcf966fa4327a5226755", size = 978693 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7b/8f/c4d9bafc34ad7ad5d8dc16dd1347ee0e507a52c3adb6bfa8887e1c6a26ba/executing-2.2.0-py2.py3-none-any.whl", hash = "sha256:11387150cad388d62750327a53d3339fad4888b39a6fe233c3afbb54ecffd3aa", size = 26702 },
+]
+
+[[package]]
+name = "fastapi"
+version = "0.115.12"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pydantic" },
+ { name = "starlette" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f4/55/ae499352d82338331ca1e28c7f4a63bfd09479b16395dce38cf50a39e2c2/fastapi-0.115.12.tar.gz", hash = "sha256:1e2c2a2646905f9e83d32f04a3f86aff4a286669c6c950ca95b5fd68c2602681", size = 295236 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/50/b3/b51f09c2ba432a576fe63758bddc81f78f0c6309d9e5c10d194313bf021e/fastapi-0.115.12-py3-none-any.whl", hash = "sha256:e94613d6c05e27be7ffebdd6ea5f388112e5e430c8f7d6494a9d1d88d43e814d", size = 95164 },
+]
+
+[[package]]
+name = "filelock"
+version = "3.18.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0a/10/c23352565a6544bdc5353e0b15fc1c563352101f30e24bf500207a54df9a/filelock-3.18.0.tar.gz", hash = "sha256:adbc88eabb99d2fec8c9c1b229b171f18afa655400173ddc653d5d01501fb9f2", size = 18075 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4d/36/2a115987e2d8c300a974597416d9de88f2444426de9571f4b59b2cca3acc/filelock-3.18.0-py3-none-any.whl", hash = "sha256:c401f4f8377c4464e6db25fff06205fd89bdd83b65eb0488ed1b160f780e21de", size = 16215 },
+]
+
+[[package]]
+name = "filetype"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bb/29/745f7d30d47fe0f251d3ad3dc2978a23141917661998763bebb6da007eb1/filetype-1.2.0.tar.gz", hash = "sha256:66b56cd6474bf41d8c54660347d37afcc3f7d1970648de365c102ef77548aadb", size = 998020 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/79/1b8fa1bb3568781e84c9200f951c735f3f157429f44be0495da55894d620/filetype-1.2.0-py2.py3-none-any.whl", hash = "sha256:7ce71b6880181241cf7ac8697a2f1eb6a8bd9b429f7ad6d27b8db9ba5f1c2d25", size = 19970 },
+]
+
+[[package]]
+name = "flashinfer-python"
+version = "0.2.6.post1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "ninja" },
+ { name = "numpy" },
+ { name = "requests" },
+ { name = "torch" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/34/26/3c6f12ffaefbfa0c453030d6e15941269b3a4ffcd267daec32d1a10dda96/flashinfer_python-0.2.6.post1.tar.gz", hash = "sha256:0cb5b346024b75deb08bd09a1cc6273ceb23f1f5f0d7e40dbe594abc6a67be69", size = 3137122 }
+
+[[package]]
+name = "flask"
+version = "3.1.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "blinker" },
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "importlib-metadata", marker = "python_full_version < '3.10'" },
+ { name = "itsdangerous" },
+ { name = "jinja2" },
+ { name = "markupsafe" },
+ { name = "werkzeug" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/de/e47735752347f4128bcf354e0da07ef311a78244eba9e3dc1d4a5ab21a98/flask-3.1.1.tar.gz", hash = "sha256:284c7b8f2f58cb737f0cf1c30fd7eaf0ccfcde196099d24ecede3fc2005aa59e", size = 753440 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3d/68/9d4508e893976286d2ead7f8f571314af6c2037af34853a30fd769c02e9d/flask-3.1.1-py3-none-any.whl", hash = "sha256:07aae2bb5eaf77993ef57e357491839f5fd9f4dc281593a81a9e4d79a24f295c", size = 103305 },
+]
+
+[[package]]
+name = "flask-compress"
+version = "1.17"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "brotli", marker = "platform_python_implementation != 'PyPy'" },
+ { name = "brotlicffi", marker = "platform_python_implementation == 'PyPy'" },
+ { name = "flask" },
+ { name = "zstandard" },
+ { name = "zstandard", extra = ["cffi"], marker = "platform_python_implementation == 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/cc/1f/260db5a4517d59bfde7b4a0d71052df68fb84983bda9231100e3b80f5989/flask_compress-1.17.tar.gz", hash = "sha256:1ebb112b129ea7c9e7d6ee6d5cc0d64f226cbc50c4daddf1a58b9bd02253fbd8", size = 15733 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f7/54/ff08f947d07c0a8a5d8f1c8e57b142c97748ca912b259db6467ab35983cd/Flask_Compress-1.17-py3-none-any.whl", hash = "sha256:415131f197c41109f08e8fdfc3a6628d83d81680fb5ecd0b3a97410e02397b20", size = 8723 },
+]
+
+[[package]]
+name = "fonttools"
+version = "4.58.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2e/5a/1124b2c8cb3a8015faf552e92714040bcdbc145dfa29928891b02d147a18/fonttools-4.58.4.tar.gz", hash = "sha256:928a8009b9884ed3aae17724b960987575155ca23c6f0b8146e400cc9e0d44ba", size = 3525026 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ed/86/d22c24caa574449b56e994ed1a96d23b23af85557fb62a92df96439d3f6c/fonttools-4.58.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:834542f13fee7625ad753b2db035edb674b07522fcbdd0ed9e9a9e2a1034467f", size = 2748349 },
+ { url = "https://files.pythonhosted.org/packages/f9/b8/384aca93856def00e7de30341f1e27f439694857d82c35d74a809c705ed0/fonttools-4.58.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2e6c61ce330142525296170cd65666e46121fc0d44383cbbcfa39cf8f58383df", size = 2318565 },
+ { url = "https://files.pythonhosted.org/packages/1a/f2/273edfdc8d9db89ecfbbf659bd894f7e07b6d53448b19837a4bdba148d17/fonttools-4.58.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9c75f8faa29579c0fbf29b56ae6a3660c6c025f3b671803cb6a9caa7e4e3a98", size = 4838855 },
+ { url = "https://files.pythonhosted.org/packages/13/fa/403703548c093c30b52ab37e109b369558afa221130e67f06bef7513f28a/fonttools-4.58.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:88dedcedbd5549e35b2ea3db3de02579c27e62e51af56779c021e7b33caadd0e", size = 4767637 },
+ { url = "https://files.pythonhosted.org/packages/6e/a8/3380e1e0bff6defb0f81c9abf274a5b4a0f30bc8cab4fd4e346c6f923b4c/fonttools-4.58.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ae80a895adab43586f4da1521d58fd4f4377cef322ee0cc205abcefa3a5effc3", size = 4819397 },
+ { url = "https://files.pythonhosted.org/packages/cd/1b/99e47eb17a8ca51d808622a4658584fa8f340857438a4e9d7ac326d4a041/fonttools-4.58.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:0d3acc7f0d151da116e87a182aefb569cf0a3c8e0fd4c9cd0a7c1e7d3e7adb26", size = 4926641 },
+ { url = "https://files.pythonhosted.org/packages/31/75/415254408f038e35b36c8525fc31feb8561f98445688dd2267c23eafd7a2/fonttools-4.58.4-cp310-cp310-win32.whl", hash = "sha256:1244f69686008e7e8d2581d9f37eef330a73fee3843f1107993eb82c9d306577", size = 2201917 },
+ { url = "https://files.pythonhosted.org/packages/c5/69/f019a15ed2946317c5318e1bcc8876f8a54a313848604ad1d4cfc4c07916/fonttools-4.58.4-cp310-cp310-win_amd64.whl", hash = "sha256:2a66c0af8a01eb2b78645af60f3b787de5fe5eb1fd8348163715b80bdbfbde1f", size = 2246327 },
+ { url = "https://files.pythonhosted.org/packages/17/7b/cc6e9bb41bab223bd2dc70ba0b21386b85f604e27f4c3206b4205085a2ab/fonttools-4.58.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a3841991c9ee2dc0562eb7f23d333d34ce81e8e27c903846f0487da21e0028eb", size = 2768901 },
+ { url = "https://files.pythonhosted.org/packages/3d/15/98d75df9f2b4e7605f3260359ad6e18e027c11fa549f74fce567270ac891/fonttools-4.58.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3c98f91b6a9604e7ffb5ece6ea346fa617f967c2c0944228801246ed56084664", size = 2328696 },
+ { url = "https://files.pythonhosted.org/packages/a8/c8/dc92b80f5452c9c40164e01b3f78f04b835a00e673bd9355ca257008ff61/fonttools-4.58.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ab9f891eb687ddf6a4e5f82901e00f992e18012ca97ab7acd15f13632acd14c1", size = 5018830 },
+ { url = "https://files.pythonhosted.org/packages/19/48/8322cf177680505d6b0b6062e204f01860cb573466a88077a9b795cb70e8/fonttools-4.58.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:891c5771e8f0094b7c0dc90eda8fc75e72930b32581418f2c285a9feedfd9a68", size = 4960922 },
+ { url = "https://files.pythonhosted.org/packages/14/e0/2aff149ed7eb0916de36da513d473c6fff574a7146891ce42de914899395/fonttools-4.58.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:43ba4d9646045c375d22e3473b7d82b18b31ee2ac715cd94220ffab7bc2d5c1d", size = 4997135 },
+ { url = "https://files.pythonhosted.org/packages/e6/6f/4d9829b29a64a2e63a121cb11ecb1b6a9524086eef3e35470949837a1692/fonttools-4.58.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33d19f16e6d2ffd6669bda574a6589941f6c99a8d5cfb9f464038244c71555de", size = 5108701 },
+ { url = "https://files.pythonhosted.org/packages/6f/1e/2d656ddd1b0cd0d222f44b2d008052c2689e66b702b9af1cd8903ddce319/fonttools-4.58.4-cp311-cp311-win32.whl", hash = "sha256:b59e5109b907da19dc9df1287454821a34a75f2632a491dd406e46ff432c2a24", size = 2200177 },
+ { url = "https://files.pythonhosted.org/packages/fb/83/ba71ad053fddf4157cb0697c8da8eff6718d059f2a22986fa5f312b49c92/fonttools-4.58.4-cp311-cp311-win_amd64.whl", hash = "sha256:3d471a5b567a0d1648f2e148c9a8bcf00d9ac76eb89e976d9976582044cc2509", size = 2247892 },
+ { url = "https://files.pythonhosted.org/packages/04/3c/1d1792bfe91ef46f22a3d23b4deb514c325e73c17d4f196b385b5e2faf1c/fonttools-4.58.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:462211c0f37a278494e74267a994f6be9a2023d0557aaa9ecbcbfce0f403b5a6", size = 2754082 },
+ { url = "https://files.pythonhosted.org/packages/2a/1f/2b261689c901a1c3bc57a6690b0b9fc21a9a93a8b0c83aae911d3149f34e/fonttools-4.58.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0c7a12fb6f769165547f00fcaa8d0df9517603ae7e04b625e5acb8639809b82d", size = 2321677 },
+ { url = "https://files.pythonhosted.org/packages/fe/6b/4607add1755a1e6581ae1fc0c9a640648e0d9cdd6591cc2d581c2e07b8c3/fonttools-4.58.4-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2d42c63020a922154add0a326388a60a55504629edc3274bc273cd3806b4659f", size = 4896354 },
+ { url = "https://files.pythonhosted.org/packages/cd/95/34b4f483643d0cb11a1f830b72c03fdd18dbd3792d77a2eb2e130a96fada/fonttools-4.58.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8f2b4e6fd45edc6805f5f2c355590b092ffc7e10a945bd6a569fc66c1d2ae7aa", size = 4941633 },
+ { url = "https://files.pythonhosted.org/packages/81/ac/9bafbdb7694059c960de523e643fa5a61dd2f698f3f72c0ca18ae99257c7/fonttools-4.58.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f155b927f6efb1213a79334e4cb9904d1e18973376ffc17a0d7cd43d31981f1e", size = 4886170 },
+ { url = "https://files.pythonhosted.org/packages/ae/44/a3a3b70d5709405f7525bb7cb497b4e46151e0c02e3c8a0e40e5e9fe030b/fonttools-4.58.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e38f687d5de97c7fb7da3e58169fb5ba349e464e141f83c3c2e2beb91d317816", size = 5037851 },
+ { url = "https://files.pythonhosted.org/packages/21/cb/e8923d197c78969454eb876a4a55a07b59c9c4c46598f02b02411dc3b45c/fonttools-4.58.4-cp312-cp312-win32.whl", hash = "sha256:636c073b4da9db053aa683db99580cac0f7c213a953b678f69acbca3443c12cc", size = 2187428 },
+ { url = "https://files.pythonhosted.org/packages/46/e6/fe50183b1a0e1018e7487ee740fa8bb127b9f5075a41e20d017201e8ab14/fonttools-4.58.4-cp312-cp312-win_amd64.whl", hash = "sha256:82e8470535743409b30913ba2822e20077acf9ea70acec40b10fcf5671dceb58", size = 2236649 },
+ { url = "https://files.pythonhosted.org/packages/d4/4f/c05cab5fc1a4293e6bc535c6cb272607155a0517700f5418a4165b7f9ec8/fonttools-4.58.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:5f4a64846495c543796fa59b90b7a7a9dff6839bd852741ab35a71994d685c6d", size = 2745197 },
+ { url = "https://files.pythonhosted.org/packages/3e/d3/49211b1f96ae49308f4f78ca7664742377a6867f00f704cdb31b57e4b432/fonttools-4.58.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e80661793a5d4d7ad132a2aa1eae2e160fbdbb50831a0edf37c7c63b2ed36574", size = 2317272 },
+ { url = "https://files.pythonhosted.org/packages/b2/11/c9972e46a6abd752a40a46960e431c795ad1f306775fc1f9e8c3081a1274/fonttools-4.58.4-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fe5807fc64e4ba5130f1974c045a6e8d795f3b7fb6debfa511d1773290dbb76b", size = 4877184 },
+ { url = "https://files.pythonhosted.org/packages/ea/24/5017c01c9ef8df572cc9eaf9f12be83ad8ed722ff6dc67991d3d752956e4/fonttools-4.58.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b610b9bef841cb8f4b50472494158b1e347d15cad56eac414c722eda695a6cfd", size = 4939445 },
+ { url = "https://files.pythonhosted.org/packages/79/b0/538cc4d0284b5a8826b4abed93a69db52e358525d4b55c47c8cef3669767/fonttools-4.58.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2daa7f0e213c38f05f054eb5e1730bd0424aebddbeac094489ea1585807dd187", size = 4878800 },
+ { url = "https://files.pythonhosted.org/packages/5a/9b/a891446b7a8250e65bffceb248508587958a94db467ffd33972723ab86c9/fonttools-4.58.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:66cccb6c0b944496b7f26450e9a66e997739c513ffaac728d24930df2fd9d35b", size = 5021259 },
+ { url = "https://files.pythonhosted.org/packages/17/b2/c4d2872cff3ace3ddd1388bf15b76a1d8d5313f0a61f234e9aed287e674d/fonttools-4.58.4-cp313-cp313-win32.whl", hash = "sha256:94d2aebb5ca59a5107825520fde596e344652c1f18170ef01dacbe48fa60c889", size = 2185824 },
+ { url = "https://files.pythonhosted.org/packages/98/57/cddf8bcc911d4f47dfca1956c1e3aeeb9f7c9b8e88b2a312fe8c22714e0b/fonttools-4.58.4-cp313-cp313-win_amd64.whl", hash = "sha256:b554bd6e80bba582fd326ddab296e563c20c64dca816d5e30489760e0c41529f", size = 2236382 },
+ { url = "https://files.pythonhosted.org/packages/45/20/787d70ba4cb831706fa587c56ee472a88ebc28752be660f4b58e598af6fc/fonttools-4.58.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:ca773fe7812e4e1197ee4e63b9691e89650ab55f679e12ac86052d2fe0d152cd", size = 2754537 },
+ { url = "https://files.pythonhosted.org/packages/4d/a5/ccb7ef1b8ab4bbf48f7753b6df512b61e73af82cd27aa486a03d6afb8635/fonttools-4.58.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:e31289101221910f44245472e02b1a2f7d671c6d06a45c07b354ecb25829ad92", size = 2321715 },
+ { url = "https://files.pythonhosted.org/packages/20/5c/b361a7eae95950afaadb7049f55b214b619cb5368086cb3253726fe0c478/fonttools-4.58.4-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90c9e3c01475bb9602cb617f69f02c4ba7ab7784d93f0b0d685e84286f4c1a10", size = 4819004 },
+ { url = "https://files.pythonhosted.org/packages/d5/2f/3006fbb1f57704cd60af82fb8127788cfb102f12d39c39fb5996af595cf3/fonttools-4.58.4-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e00a826f2bc745a010341ac102082fe5e3fb9f0861b90ed9ff32277598813711", size = 4749072 },
+ { url = "https://files.pythonhosted.org/packages/c2/42/ea79e2c3d5e4441e4508d6456b268a7de275452f3dba3a13fc9d73f3e03d/fonttools-4.58.4-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:bc75e72e9d2a4ad0935c59713bd38679d51c6fefab1eadde80e3ed4c2a11ea84", size = 4802023 },
+ { url = "https://files.pythonhosted.org/packages/d4/70/90a196f57faa2bcd1485710c6d08eedceca500cdf2166640b3478e72072c/fonttools-4.58.4-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:f57a795e540059ce3de68508acfaaf177899b39c36ef0a2833b2308db98c71f1", size = 4911103 },
+ { url = "https://files.pythonhosted.org/packages/cb/3f/a7d38e606e98701dbcb6198406c8b554a77ed06c5b21e425251813fd3775/fonttools-4.58.4-cp39-cp39-win32.whl", hash = "sha256:a7d04f64c88b48ede655abcf76f2b2952f04933567884d99be7c89e0a4495131", size = 1471393 },
+ { url = "https://files.pythonhosted.org/packages/37/6e/08158deaebeb5b0c7a0fb251ca6827defb5f5159958a23ba427e0b677e95/fonttools-4.58.4-cp39-cp39-win_amd64.whl", hash = "sha256:5a8bc5dfd425c89b1c38380bc138787b0a830f761b82b37139aa080915503b69", size = 1515901 },
+ { url = "https://files.pythonhosted.org/packages/0b/2f/c536b5b9bb3c071e91d536a4d11f969e911dbb6b227939f4c5b0bca090df/fonttools-4.58.4-py3-none-any.whl", hash = "sha256:a10ce13a13f26cbb9f37512a4346bb437ad7e002ff6fa966a7ce7ff5ac3528bd", size = 1114660 },
+]
+
+[[package]]
+name = "frozenlist"
+version = "1.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/79/b1/b64018016eeb087db503b038296fd782586432b9c077fc5c7839e9cb6ef6/frozenlist-1.7.0.tar.gz", hash = "sha256:2e310d81923c2437ea8670467121cc3e9b0f76d3043cc1d2331d56c7fb7a3a8f", size = 45078 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/af/36/0da0a49409f6b47cc2d060dc8c9040b897b5902a8a4e37d9bc1deb11f680/frozenlist-1.7.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:cc4df77d638aa2ed703b878dd093725b72a824c3c546c076e8fdf276f78ee84a", size = 81304 },
+ { url = "https://files.pythonhosted.org/packages/77/f0/77c11d13d39513b298e267b22eb6cb559c103d56f155aa9a49097221f0b6/frozenlist-1.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:716a9973a2cc963160394f701964fe25012600f3d311f60c790400b00e568b61", size = 47735 },
+ { url = "https://files.pythonhosted.org/packages/37/12/9d07fa18971a44150593de56b2f2947c46604819976784bcf6ea0d5db43b/frozenlist-1.7.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a0fd1bad056a3600047fb9462cff4c5322cebc59ebf5d0a3725e0ee78955001d", size = 46775 },
+ { url = "https://files.pythonhosted.org/packages/70/34/f73539227e06288fcd1f8a76853e755b2b48bca6747e99e283111c18bcd4/frozenlist-1.7.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3789ebc19cb811163e70fe2bd354cea097254ce6e707ae42e56f45e31e96cb8e", size = 224644 },
+ { url = "https://files.pythonhosted.org/packages/fb/68/c1d9c2f4a6e438e14613bad0f2973567586610cc22dcb1e1241da71de9d3/frozenlist-1.7.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:af369aa35ee34f132fcfad5be45fbfcde0e3a5f6a1ec0712857f286b7d20cca9", size = 222125 },
+ { url = "https://files.pythonhosted.org/packages/b9/d0/98e8f9a515228d708344d7c6986752be3e3192d1795f748c24bcf154ad99/frozenlist-1.7.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ac64b6478722eeb7a3313d494f8342ef3478dff539d17002f849101b212ef97c", size = 233455 },
+ { url = "https://files.pythonhosted.org/packages/79/df/8a11bcec5600557f40338407d3e5bea80376ed1c01a6c0910fcfdc4b8993/frozenlist-1.7.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f89f65d85774f1797239693cef07ad4c97fdd0639544bad9ac4b869782eb1981", size = 227339 },
+ { url = "https://files.pythonhosted.org/packages/50/82/41cb97d9c9a5ff94438c63cc343eb7980dac4187eb625a51bdfdb7707314/frozenlist-1.7.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1073557c941395fdfcfac13eb2456cb8aad89f9de27bae29fabca8e563b12615", size = 212969 },
+ { url = "https://files.pythonhosted.org/packages/13/47/f9179ee5ee4f55629e4f28c660b3fdf2775c8bfde8f9c53f2de2d93f52a9/frozenlist-1.7.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1ed8d2fa095aae4bdc7fdd80351009a48d286635edffee66bf865e37a9125c50", size = 222862 },
+ { url = "https://files.pythonhosted.org/packages/1a/52/df81e41ec6b953902c8b7e3a83bee48b195cb0e5ec2eabae5d8330c78038/frozenlist-1.7.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:24c34bea555fe42d9f928ba0a740c553088500377448febecaa82cc3e88aa1fa", size = 222492 },
+ { url = "https://files.pythonhosted.org/packages/84/17/30d6ea87fa95a9408245a948604b82c1a4b8b3e153cea596421a2aef2754/frozenlist-1.7.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:69cac419ac6a6baad202c85aaf467b65ac860ac2e7f2ac1686dc40dbb52f6577", size = 238250 },
+ { url = "https://files.pythonhosted.org/packages/8f/00/ecbeb51669e3c3df76cf2ddd66ae3e48345ec213a55e3887d216eb4fbab3/frozenlist-1.7.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:960d67d0611f4c87da7e2ae2eacf7ea81a5be967861e0c63cf205215afbfac59", size = 218720 },
+ { url = "https://files.pythonhosted.org/packages/1a/c0/c224ce0e0eb31cc57f67742071bb470ba8246623c1823a7530be0e76164c/frozenlist-1.7.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:41be2964bd4b15bf575e5daee5a5ce7ed3115320fb3c2b71fca05582ffa4dc9e", size = 232585 },
+ { url = "https://files.pythonhosted.org/packages/55/3c/34cb694abf532f31f365106deebdeac9e45c19304d83cf7d51ebbb4ca4d1/frozenlist-1.7.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:46d84d49e00c9429238a7ce02dc0be8f6d7cd0cd405abd1bebdc991bf27c15bd", size = 234248 },
+ { url = "https://files.pythonhosted.org/packages/98/c0/2052d8b6cecda2e70bd81299e3512fa332abb6dcd2969b9c80dfcdddbf75/frozenlist-1.7.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:15900082e886edb37480335d9d518cec978afc69ccbc30bd18610b7c1b22a718", size = 221621 },
+ { url = "https://files.pythonhosted.org/packages/c5/bf/7dcebae315436903b1d98ffb791a09d674c88480c158aa171958a3ac07f0/frozenlist-1.7.0-cp310-cp310-win32.whl", hash = "sha256:400ddd24ab4e55014bba442d917203c73b2846391dd42ca5e38ff52bb18c3c5e", size = 39578 },
+ { url = "https://files.pythonhosted.org/packages/8f/5f/f69818f017fa9a3d24d1ae39763e29b7f60a59e46d5f91b9c6b21622f4cd/frozenlist-1.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:6eb93efb8101ef39d32d50bce242c84bcbddb4f7e9febfa7b524532a239b4464", size = 43830 },
+ { url = "https://files.pythonhosted.org/packages/34/7e/803dde33760128acd393a27eb002f2020ddb8d99d30a44bfbaab31c5f08a/frozenlist-1.7.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:aa51e147a66b2d74de1e6e2cf5921890de6b0f4820b257465101d7f37b49fb5a", size = 82251 },
+ { url = "https://files.pythonhosted.org/packages/75/a9/9c2c5760b6ba45eae11334db454c189d43d34a4c0b489feb2175e5e64277/frozenlist-1.7.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9b35db7ce1cd71d36ba24f80f0c9e7cff73a28d7a74e91fe83e23d27c7828750", size = 48183 },
+ { url = "https://files.pythonhosted.org/packages/47/be/4038e2d869f8a2da165f35a6befb9158c259819be22eeaf9c9a8f6a87771/frozenlist-1.7.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:34a69a85e34ff37791e94542065c8416c1afbf820b68f720452f636d5fb990cd", size = 47107 },
+ { url = "https://files.pythonhosted.org/packages/79/26/85314b8a83187c76a37183ceed886381a5f992975786f883472fcb6dc5f2/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4a646531fa8d82c87fe4bb2e596f23173caec9185bfbca5d583b4ccfb95183e2", size = 237333 },
+ { url = "https://files.pythonhosted.org/packages/1f/fd/e5b64f7d2c92a41639ffb2ad44a6a82f347787abc0c7df5f49057cf11770/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:79b2ffbba483f4ed36a0f236ccb85fbb16e670c9238313709638167670ba235f", size = 231724 },
+ { url = "https://files.pythonhosted.org/packages/20/fb/03395c0a43a5976af4bf7534759d214405fbbb4c114683f434dfdd3128ef/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a26f205c9ca5829cbf82bb2a84b5c36f7184c4316617d7ef1b271a56720d6b30", size = 245842 },
+ { url = "https://files.pythonhosted.org/packages/d0/15/c01c8e1dffdac5d9803507d824f27aed2ba76b6ed0026fab4d9866e82f1f/frozenlist-1.7.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bcacfad3185a623fa11ea0e0634aac7b691aa925d50a440f39b458e41c561d98", size = 239767 },
+ { url = "https://files.pythonhosted.org/packages/14/99/3f4c6fe882c1f5514b6848aa0a69b20cb5e5d8e8f51a339d48c0e9305ed0/frozenlist-1.7.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:72c1b0fe8fe451b34f12dce46445ddf14bd2a5bcad7e324987194dc8e3a74c86", size = 224130 },
+ { url = "https://files.pythonhosted.org/packages/4d/83/220a374bd7b2aeba9d0725130665afe11de347d95c3620b9b82cc2fcab97/frozenlist-1.7.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:61d1a5baeaac6c0798ff6edfaeaa00e0e412d49946c53fae8d4b8e8b3566c4ae", size = 235301 },
+ { url = "https://files.pythonhosted.org/packages/03/3c/3e3390d75334a063181625343e8daab61b77e1b8214802cc4e8a1bb678fc/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7edf5c043c062462f09b6820de9854bf28cc6cc5b6714b383149745e287181a8", size = 234606 },
+ { url = "https://files.pythonhosted.org/packages/23/1e/58232c19608b7a549d72d9903005e2d82488f12554a32de2d5fb59b9b1ba/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:d50ac7627b3a1bd2dcef6f9da89a772694ec04d9a61b66cf87f7d9446b4a0c31", size = 248372 },
+ { url = "https://files.pythonhosted.org/packages/c0/a4/e4a567e01702a88a74ce8a324691e62a629bf47d4f8607f24bf1c7216e7f/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:ce48b2fece5aeb45265bb7a58259f45027db0abff478e3077e12b05b17fb9da7", size = 229860 },
+ { url = "https://files.pythonhosted.org/packages/73/a6/63b3374f7d22268b41a9db73d68a8233afa30ed164c46107b33c4d18ecdd/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:fe2365ae915a1fafd982c146754e1de6ab3478def8a59c86e1f7242d794f97d5", size = 245893 },
+ { url = "https://files.pythonhosted.org/packages/6d/eb/d18b3f6e64799a79673c4ba0b45e4cfbe49c240edfd03a68be20002eaeaa/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:45a6f2fdbd10e074e8814eb98b05292f27bad7d1883afbe009d96abdcf3bc898", size = 246323 },
+ { url = "https://files.pythonhosted.org/packages/5a/f5/720f3812e3d06cd89a1d5db9ff6450088b8f5c449dae8ffb2971a44da506/frozenlist-1.7.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:21884e23cffabb157a9dd7e353779077bf5b8f9a58e9b262c6caad2ef5f80a56", size = 233149 },
+ { url = "https://files.pythonhosted.org/packages/69/68/03efbf545e217d5db8446acfd4c447c15b7c8cf4dbd4a58403111df9322d/frozenlist-1.7.0-cp311-cp311-win32.whl", hash = "sha256:284d233a8953d7b24f9159b8a3496fc1ddc00f4db99c324bd5fb5f22d8698ea7", size = 39565 },
+ { url = "https://files.pythonhosted.org/packages/58/17/fe61124c5c333ae87f09bb67186d65038834a47d974fc10a5fadb4cc5ae1/frozenlist-1.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:387cbfdcde2f2353f19c2f66bbb52406d06ed77519ac7ee21be0232147c2592d", size = 44019 },
+ { url = "https://files.pythonhosted.org/packages/ef/a2/c8131383f1e66adad5f6ecfcce383d584ca94055a34d683bbb24ac5f2f1c/frozenlist-1.7.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3dbf9952c4bb0e90e98aec1bd992b3318685005702656bc6f67c1a32b76787f2", size = 81424 },
+ { url = "https://files.pythonhosted.org/packages/4c/9d/02754159955088cb52567337d1113f945b9e444c4960771ea90eb73de8db/frozenlist-1.7.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f5906d3359300b8a9bb194239491122e6cf1444c2efb88865426f170c262cdb", size = 47952 },
+ { url = "https://files.pythonhosted.org/packages/01/7a/0046ef1bd6699b40acd2067ed6d6670b4db2f425c56980fa21c982c2a9db/frozenlist-1.7.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3dabd5a8f84573c8d10d8859a50ea2dec01eea372031929871368c09fa103478", size = 46688 },
+ { url = "https://files.pythonhosted.org/packages/d6/a2/a910bafe29c86997363fb4c02069df4ff0b5bc39d33c5198b4e9dd42d8f8/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa57daa5917f1738064f302bf2626281a1cb01920c32f711fbc7bc36111058a8", size = 243084 },
+ { url = "https://files.pythonhosted.org/packages/64/3e/5036af9d5031374c64c387469bfcc3af537fc0f5b1187d83a1cf6fab1639/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c193dda2b6d49f4c4398962810fa7d7c78f032bf45572b3e04dd5249dff27e08", size = 233524 },
+ { url = "https://files.pythonhosted.org/packages/06/39/6a17b7c107a2887e781a48ecf20ad20f1c39d94b2a548c83615b5b879f28/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bfe2b675cf0aaa6d61bf8fbffd3c274b3c9b7b1623beb3809df8a81399a4a9c4", size = 248493 },
+ { url = "https://files.pythonhosted.org/packages/be/00/711d1337c7327d88c44d91dd0f556a1c47fb99afc060ae0ef66b4d24793d/frozenlist-1.7.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8fc5d5cda37f62b262405cf9652cf0856839c4be8ee41be0afe8858f17f4c94b", size = 244116 },
+ { url = "https://files.pythonhosted.org/packages/24/fe/74e6ec0639c115df13d5850e75722750adabdc7de24e37e05a40527ca539/frozenlist-1.7.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0d5ce521d1dd7d620198829b87ea002956e4319002ef0bc8d3e6d045cb4646e", size = 224557 },
+ { url = "https://files.pythonhosted.org/packages/8d/db/48421f62a6f77c553575201e89048e97198046b793f4a089c79a6e3268bd/frozenlist-1.7.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:488d0a7d6a0008ca0db273c542098a0fa9e7dfaa7e57f70acef43f32b3f69dca", size = 241820 },
+ { url = "https://files.pythonhosted.org/packages/1d/fa/cb4a76bea23047c8462976ea7b7a2bf53997a0ca171302deae9d6dd12096/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:15a7eaba63983d22c54d255b854e8108e7e5f3e89f647fc854bd77a237e767df", size = 236542 },
+ { url = "https://files.pythonhosted.org/packages/5d/32/476a4b5cfaa0ec94d3f808f193301debff2ea42288a099afe60757ef6282/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1eaa7e9c6d15df825bf255649e05bd8a74b04a4d2baa1ae46d9c2d00b2ca2cb5", size = 249350 },
+ { url = "https://files.pythonhosted.org/packages/8d/ba/9a28042f84a6bf8ea5dbc81cfff8eaef18d78b2a1ad9d51c7bc5b029ad16/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e4389e06714cfa9d47ab87f784a7c5be91d3934cd6e9a7b85beef808297cc025", size = 225093 },
+ { url = "https://files.pythonhosted.org/packages/bc/29/3a32959e68f9cf000b04e79ba574527c17e8842e38c91d68214a37455786/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:73bd45e1488c40b63fe5a7df892baf9e2a4d4bb6409a2b3b78ac1c6236178e01", size = 245482 },
+ { url = "https://files.pythonhosted.org/packages/80/e8/edf2f9e00da553f07f5fa165325cfc302dead715cab6ac8336a5f3d0adc2/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99886d98e1643269760e5fe0df31e5ae7050788dd288947f7f007209b8c33f08", size = 249590 },
+ { url = "https://files.pythonhosted.org/packages/1c/80/9a0eb48b944050f94cc51ee1c413eb14a39543cc4f760ed12657a5a3c45a/frozenlist-1.7.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:290a172aae5a4c278c6da8a96222e6337744cd9c77313efe33d5670b9f65fc43", size = 237785 },
+ { url = "https://files.pythonhosted.org/packages/f3/74/87601e0fb0369b7a2baf404ea921769c53b7ae00dee7dcfe5162c8c6dbf0/frozenlist-1.7.0-cp312-cp312-win32.whl", hash = "sha256:426c7bc70e07cfebc178bc4c2bf2d861d720c4fff172181eeb4a4c41d4ca2ad3", size = 39487 },
+ { url = "https://files.pythonhosted.org/packages/0b/15/c026e9a9fc17585a9d461f65d8593d281fedf55fbf7eb53f16c6df2392f9/frozenlist-1.7.0-cp312-cp312-win_amd64.whl", hash = "sha256:563b72efe5da92e02eb68c59cb37205457c977aa7a449ed1b37e6939e5c47c6a", size = 43874 },
+ { url = "https://files.pythonhosted.org/packages/24/90/6b2cebdabdbd50367273c20ff6b57a3dfa89bd0762de02c3a1eb42cb6462/frozenlist-1.7.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ee80eeda5e2a4e660651370ebffd1286542b67e268aa1ac8d6dbe973120ef7ee", size = 79791 },
+ { url = "https://files.pythonhosted.org/packages/83/2e/5b70b6a3325363293fe5fc3ae74cdcbc3e996c2a11dde2fd9f1fb0776d19/frozenlist-1.7.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d1a81c85417b914139e3a9b995d4a1c84559afc839a93cf2cb7f15e6e5f6ed2d", size = 47165 },
+ { url = "https://files.pythonhosted.org/packages/f4/25/a0895c99270ca6966110f4ad98e87e5662eab416a17e7fd53c364bf8b954/frozenlist-1.7.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cbb65198a9132ebc334f237d7b0df163e4de83fb4f2bdfe46c1e654bdb0c5d43", size = 45881 },
+ { url = "https://files.pythonhosted.org/packages/19/7c/71bb0bbe0832793c601fff68cd0cf6143753d0c667f9aec93d3c323f4b55/frozenlist-1.7.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dab46c723eeb2c255a64f9dc05b8dd601fde66d6b19cdb82b2e09cc6ff8d8b5d", size = 232409 },
+ { url = "https://files.pythonhosted.org/packages/c0/45/ed2798718910fe6eb3ba574082aaceff4528e6323f9a8570be0f7028d8e9/frozenlist-1.7.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6aeac207a759d0dedd2e40745575ae32ab30926ff4fa49b1635def65806fddee", size = 225132 },
+ { url = "https://files.pythonhosted.org/packages/ba/e2/8417ae0f8eacb1d071d4950f32f229aa6bf68ab69aab797b72a07ea68d4f/frozenlist-1.7.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bd8c4e58ad14b4fa7802b8be49d47993182fdd4023393899632c88fd8cd994eb", size = 237638 },
+ { url = "https://files.pythonhosted.org/packages/f8/b7/2ace5450ce85f2af05a871b8c8719b341294775a0a6c5585d5e6170f2ce7/frozenlist-1.7.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:04fb24d104f425da3540ed83cbfc31388a586a7696142004c577fa61c6298c3f", size = 233539 },
+ { url = "https://files.pythonhosted.org/packages/46/b9/6989292c5539553dba63f3c83dc4598186ab2888f67c0dc1d917e6887db6/frozenlist-1.7.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a5c505156368e4ea6b53b5ac23c92d7edc864537ff911d2fb24c140bb175e60", size = 215646 },
+ { url = "https://files.pythonhosted.org/packages/72/31/bc8c5c99c7818293458fe745dab4fd5730ff49697ccc82b554eb69f16a24/frozenlist-1.7.0-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8bd7eb96a675f18aa5c553eb7ddc24a43c8c18f22e1f9925528128c052cdbe00", size = 232233 },
+ { url = "https://files.pythonhosted.org/packages/59/52/460db4d7ba0811b9ccb85af996019f5d70831f2f5f255f7cc61f86199795/frozenlist-1.7.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:05579bf020096fe05a764f1f84cd104a12f78eaab68842d036772dc6d4870b4b", size = 227996 },
+ { url = "https://files.pythonhosted.org/packages/ba/c9/f4b39e904c03927b7ecf891804fd3b4df3db29b9e487c6418e37988d6e9d/frozenlist-1.7.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:376b6222d114e97eeec13d46c486facd41d4f43bab626b7c3f6a8b4e81a5192c", size = 242280 },
+ { url = "https://files.pythonhosted.org/packages/b8/33/3f8d6ced42f162d743e3517781566b8481322be321b486d9d262adf70bfb/frozenlist-1.7.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:0aa7e176ebe115379b5b1c95b4096fb1c17cce0847402e227e712c27bdb5a949", size = 217717 },
+ { url = "https://files.pythonhosted.org/packages/3e/e8/ad683e75da6ccef50d0ab0c2b2324b32f84fc88ceee778ed79b8e2d2fe2e/frozenlist-1.7.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3fbba20e662b9c2130dc771e332a99eff5da078b2b2648153a40669a6d0e36ca", size = 236644 },
+ { url = "https://files.pythonhosted.org/packages/b2/14/8d19ccdd3799310722195a72ac94ddc677541fb4bef4091d8e7775752360/frozenlist-1.7.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:f3f4410a0a601d349dd406b5713fec59b4cee7e71678d5b17edda7f4655a940b", size = 238879 },
+ { url = "https://files.pythonhosted.org/packages/ce/13/c12bf657494c2fd1079a48b2db49fa4196325909249a52d8f09bc9123fd7/frozenlist-1.7.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e2cdfaaec6a2f9327bf43c933c0319a7c429058e8537c508964a133dffee412e", size = 232502 },
+ { url = "https://files.pythonhosted.org/packages/d7/8b/e7f9dfde869825489382bc0d512c15e96d3964180c9499efcec72e85db7e/frozenlist-1.7.0-cp313-cp313-win32.whl", hash = "sha256:5fc4df05a6591c7768459caba1b342d9ec23fa16195e744939ba5914596ae3e1", size = 39169 },
+ { url = "https://files.pythonhosted.org/packages/35/89/a487a98d94205d85745080a37860ff5744b9820a2c9acbcdd9440bfddf98/frozenlist-1.7.0-cp313-cp313-win_amd64.whl", hash = "sha256:52109052b9791a3e6b5d1b65f4b909703984b770694d3eb64fad124c835d7cba", size = 43219 },
+ { url = "https://files.pythonhosted.org/packages/56/d5/5c4cf2319a49eddd9dd7145e66c4866bdc6f3dbc67ca3d59685149c11e0d/frozenlist-1.7.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:a6f86e4193bb0e235ef6ce3dde5cbabed887e0b11f516ce8a0f4d3b33078ec2d", size = 84345 },
+ { url = "https://files.pythonhosted.org/packages/a4/7d/ec2c1e1dc16b85bc9d526009961953df9cec8481b6886debb36ec9107799/frozenlist-1.7.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:82d664628865abeb32d90ae497fb93df398a69bb3434463d172b80fc25b0dd7d", size = 48880 },
+ { url = "https://files.pythonhosted.org/packages/69/86/f9596807b03de126e11e7d42ac91e3d0b19a6599c714a1989a4e85eeefc4/frozenlist-1.7.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:912a7e8375a1c9a68325a902f3953191b7b292aa3c3fb0d71a216221deca460b", size = 48498 },
+ { url = "https://files.pythonhosted.org/packages/5e/cb/df6de220f5036001005f2d726b789b2c0b65f2363b104bbc16f5be8084f8/frozenlist-1.7.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9537c2777167488d539bc5de2ad262efc44388230e5118868e172dd4a552b146", size = 292296 },
+ { url = "https://files.pythonhosted.org/packages/83/1f/de84c642f17c8f851a2905cee2dae401e5e0daca9b5ef121e120e19aa825/frozenlist-1.7.0-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:f34560fb1b4c3e30ba35fa9a13894ba39e5acfc5f60f57d8accde65f46cc5e74", size = 273103 },
+ { url = "https://files.pythonhosted.org/packages/88/3c/c840bfa474ba3fa13c772b93070893c6e9d5c0350885760376cbe3b6c1b3/frozenlist-1.7.0-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:acd03d224b0175f5a850edc104ac19040d35419eddad04e7cf2d5986d98427f1", size = 292869 },
+ { url = "https://files.pythonhosted.org/packages/a6/1c/3efa6e7d5a39a1d5ef0abeb51c48fb657765794a46cf124e5aca2c7a592c/frozenlist-1.7.0-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f2038310bc582f3d6a09b3816ab01737d60bf7b1ec70f5356b09e84fb7408ab1", size = 291467 },
+ { url = "https://files.pythonhosted.org/packages/4f/00/d5c5e09d4922c395e2f2f6b79b9a20dab4b67daaf78ab92e7729341f61f6/frozenlist-1.7.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b8c05e4c8e5f36e5e088caa1bf78a687528f83c043706640a92cb76cd6999384", size = 266028 },
+ { url = "https://files.pythonhosted.org/packages/4e/27/72765be905619dfde25a7f33813ac0341eb6b076abede17a2e3fbfade0cb/frozenlist-1.7.0-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:765bb588c86e47d0b68f23c1bee323d4b703218037765dcf3f25c838c6fecceb", size = 284294 },
+ { url = "https://files.pythonhosted.org/packages/88/67/c94103a23001b17808eb7dd1200c156bb69fb68e63fcf0693dde4cd6228c/frozenlist-1.7.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:32dc2e08c67d86d0969714dd484fd60ff08ff81d1a1e40a77dd34a387e6ebc0c", size = 281898 },
+ { url = "https://files.pythonhosted.org/packages/42/34/a3e2c00c00f9e2a9db5653bca3fec306349e71aff14ae45ecc6d0951dd24/frozenlist-1.7.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:c0303e597eb5a5321b4de9c68e9845ac8f290d2ab3f3e2c864437d3c5a30cd65", size = 290465 },
+ { url = "https://files.pythonhosted.org/packages/bb/73/f89b7fbce8b0b0c095d82b008afd0590f71ccb3dee6eee41791cf8cd25fd/frozenlist-1.7.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:a47f2abb4e29b3a8d0b530f7c3598badc6b134562b1a5caee867f7c62fee51e3", size = 266385 },
+ { url = "https://files.pythonhosted.org/packages/cd/45/e365fdb554159462ca12df54bc59bfa7a9a273ecc21e99e72e597564d1ae/frozenlist-1.7.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:3d688126c242a6fabbd92e02633414d40f50bb6002fa4cf995a1d18051525657", size = 288771 },
+ { url = "https://files.pythonhosted.org/packages/00/11/47b6117002a0e904f004d70ec5194fe9144f117c33c851e3d51c765962d0/frozenlist-1.7.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:4e7e9652b3d367c7bd449a727dc79d5043f48b88d0cbfd4f9f1060cf2b414104", size = 288206 },
+ { url = "https://files.pythonhosted.org/packages/40/37/5f9f3c3fd7f7746082ec67bcdc204db72dad081f4f83a503d33220a92973/frozenlist-1.7.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:1a85e345b4c43db8b842cab1feb41be5cc0b10a1830e6295b69d7310f99becaf", size = 282620 },
+ { url = "https://files.pythonhosted.org/packages/0b/31/8fbc5af2d183bff20f21aa743b4088eac4445d2bb1cdece449ae80e4e2d1/frozenlist-1.7.0-cp313-cp313t-win32.whl", hash = "sha256:3a14027124ddb70dfcee5148979998066897e79f89f64b13328595c4bdf77c81", size = 43059 },
+ { url = "https://files.pythonhosted.org/packages/bb/ed/41956f52105b8dbc26e457c5705340c67c8cc2b79f394b79bffc09d0e938/frozenlist-1.7.0-cp313-cp313t-win_amd64.whl", hash = "sha256:3bf8010d71d4507775f658e9823210b7427be36625b387221642725b515dcf3e", size = 47516 },
+ { url = "https://files.pythonhosted.org/packages/dd/b1/ee59496f51cd244039330015d60f13ce5a54a0f2bd8d79e4a4a375ab7469/frozenlist-1.7.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:cea3dbd15aea1341ea2de490574a4a37ca080b2ae24e4b4f4b51b9057b4c3630", size = 82434 },
+ { url = "https://files.pythonhosted.org/packages/75/e1/d518391ce36a6279b3fa5bc14327dde80bcb646bb50d059c6ca0756b8d05/frozenlist-1.7.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:7d536ee086b23fecc36c2073c371572374ff50ef4db515e4e503925361c24f71", size = 48232 },
+ { url = "https://files.pythonhosted.org/packages/b7/8d/a0d04f28b6e821a9685c22e67b5fb798a5a7b68752f104bfbc2dccf080c4/frozenlist-1.7.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:dfcebf56f703cb2e346315431699f00db126d158455e513bd14089d992101e44", size = 47186 },
+ { url = "https://files.pythonhosted.org/packages/93/3a/a5334c0535c8b7c78eeabda1579179e44fe3d644e07118e59a2276dedaf1/frozenlist-1.7.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:974c5336e61d6e7eb1ea5b929cb645e882aadab0095c5a6974a111e6479f8878", size = 226617 },
+ { url = "https://files.pythonhosted.org/packages/0a/67/8258d971f519dc3f278c55069a775096cda6610a267b53f6248152b72b2f/frozenlist-1.7.0-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c70db4a0ab5ab20878432c40563573229a7ed9241506181bba12f6b7d0dc41cb", size = 224179 },
+ { url = "https://files.pythonhosted.org/packages/fc/89/8225905bf889b97c6d935dd3aeb45668461e59d415cb019619383a8a7c3b/frozenlist-1.7.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1137b78384eebaf70560a36b7b229f752fb64d463d38d1304939984d5cb887b6", size = 235783 },
+ { url = "https://files.pythonhosted.org/packages/54/6e/ef52375aa93d4bc510d061df06205fa6dcfd94cd631dd22956b09128f0d4/frozenlist-1.7.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e793a9f01b3e8b5c0bc646fb59140ce0efcc580d22a3468d70766091beb81b35", size = 229210 },
+ { url = "https://files.pythonhosted.org/packages/ee/55/62c87d1a6547bfbcd645df10432c129100c5bd0fd92a384de6e3378b07c1/frozenlist-1.7.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:74739ba8e4e38221d2c5c03d90a7e542cb8ad681915f4ca8f68d04f810ee0a87", size = 215994 },
+ { url = "https://files.pythonhosted.org/packages/45/d2/263fea1f658b8ad648c7d94d18a87bca7e8c67bd6a1bbf5445b1bd5b158c/frozenlist-1.7.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1e63344c4e929b1a01e29bc184bbb5fd82954869033765bfe8d65d09e336a677", size = 225122 },
+ { url = "https://files.pythonhosted.org/packages/7b/22/7145e35d12fb368d92124f679bea87309495e2e9ddf14c6533990cb69218/frozenlist-1.7.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:2ea2a7369eb76de2217a842f22087913cdf75f63cf1307b9024ab82dfb525938", size = 224019 },
+ { url = "https://files.pythonhosted.org/packages/44/1e/7dae8c54301beb87bcafc6144b9a103bfd2c8f38078c7902984c9a0c4e5b/frozenlist-1.7.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:836b42f472a0e006e02499cef9352ce8097f33df43baaba3e0a28a964c26c7d2", size = 239925 },
+ { url = "https://files.pythonhosted.org/packages/4b/1e/99c93e54aa382e949a98976a73b9b20c3aae6d9d893f31bbe4991f64e3a8/frozenlist-1.7.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:e22b9a99741294b2571667c07d9f8cceec07cb92aae5ccda39ea1b6052ed4319", size = 220881 },
+ { url = "https://files.pythonhosted.org/packages/5e/9c/ca5105fa7fb5abdfa8837581be790447ae051da75d32f25c8f81082ffc45/frozenlist-1.7.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:9a19e85cc503d958abe5218953df722748d87172f71b73cf3c9257a91b999890", size = 234046 },
+ { url = "https://files.pythonhosted.org/packages/8d/4d/e99014756093b4ddbb67fb8f0df11fe7a415760d69ace98e2ac6d5d43402/frozenlist-1.7.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:f22dac33bb3ee8fe3e013aa7b91dc12f60d61d05b7fe32191ffa84c3aafe77bd", size = 235756 },
+ { url = "https://files.pythonhosted.org/packages/8b/72/a19a40bcdaa28a51add2aaa3a1a294ec357f36f27bd836a012e070c5e8a5/frozenlist-1.7.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:9ccec739a99e4ccf664ea0775149f2749b8a6418eb5b8384b4dc0a7d15d304cb", size = 222894 },
+ { url = "https://files.pythonhosted.org/packages/08/49/0042469993e023a758af81db68c76907cd29e847d772334d4d201cbe9a42/frozenlist-1.7.0-cp39-cp39-win32.whl", hash = "sha256:b3950f11058310008a87757f3eee16a8e1ca97979833239439586857bc25482e", size = 39848 },
+ { url = "https://files.pythonhosted.org/packages/5a/45/827d86ee475c877f5f766fbc23fb6acb6fada9e52f1c9720e2ba3eae32da/frozenlist-1.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:43a82fce6769c70f2f5a06248b614a7d268080a9d20f7457ef10ecee5af82b63", size = 44102 },
+ { url = "https://files.pythonhosted.org/packages/ee/45/b82e3c16be2182bff01179db177fe144d58b5dc787a7d4492c6ed8b9317f/frozenlist-1.7.0-py3-none-any.whl", hash = "sha256:9a5af342e34f7e97caf8c995864c7a396418ae2859cc6fdf1b1073020d516a7e", size = 13106 },
+]
+
+[[package]]
+name = "fsspec"
+version = "2025.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/34/f4/5721faf47b8c499e776bc34c6a8fc17efdf7fdef0b00f398128bc5dcb4ac/fsspec-2025.3.0.tar.gz", hash = "sha256:a935fd1ea872591f2b5148907d103488fc523295e6c64b835cfad8c3eca44972", size = 298491 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/56/53/eb690efa8513166adef3e0669afd31e95ffde69fb3c52ec2ac7223ed6018/fsspec-2025.3.0-py3-none-any.whl", hash = "sha256:efb87af3efa9103f94ca91a7f8cb7a4df91af9f74fc106c9c7ea0efd7277c1b3", size = 193615 },
+]
+
+[package.optional-dependencies]
+http = [
+ { name = "aiohttp" },
+]
+
+[[package]]
+name = "greenlet"
+version = "3.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/92/bb85bd6e80148a4d2e0c59f7c0c2891029f8fd510183afc7d8d2feeed9b6/greenlet-3.2.3.tar.gz", hash = "sha256:8b0dd8ae4c0d6f5e54ee55ba935eeb3d735a9b58a8a1e5b5cbab64e01a39f365", size = 185752 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/92/db/b4c12cff13ebac2786f4f217f06588bccd8b53d260453404ef22b121fc3a/greenlet-3.2.3-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:1afd685acd5597349ee6d7a88a8bec83ce13c106ac78c196ee9dde7c04fe87be", size = 268977 },
+ { url = "https://files.pythonhosted.org/packages/52/61/75b4abd8147f13f70986df2801bf93735c1bd87ea780d70e3b3ecda8c165/greenlet-3.2.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:761917cac215c61e9dc7324b2606107b3b292a8349bdebb31503ab4de3f559ac", size = 627351 },
+ { url = "https://files.pythonhosted.org/packages/35/aa/6894ae299d059d26254779a5088632874b80ee8cf89a88bca00b0709d22f/greenlet-3.2.3-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:a433dbc54e4a37e4fff90ef34f25a8c00aed99b06856f0119dcf09fbafa16392", size = 638599 },
+ { url = "https://files.pythonhosted.org/packages/30/64/e01a8261d13c47f3c082519a5e9dbf9e143cc0498ed20c911d04e54d526c/greenlet-3.2.3-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:72e77ed69312bab0434d7292316d5afd6896192ac4327d44f3d613ecb85b037c", size = 634482 },
+ { url = "https://files.pythonhosted.org/packages/47/48/ff9ca8ba9772d083a4f5221f7b4f0ebe8978131a9ae0909cf202f94cd879/greenlet-3.2.3-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:68671180e3849b963649254a882cd544a3c75bfcd2c527346ad8bb53494444db", size = 633284 },
+ { url = "https://files.pythonhosted.org/packages/e9/45/626e974948713bc15775b696adb3eb0bd708bec267d6d2d5c47bb47a6119/greenlet-3.2.3-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:49c8cfb18fb419b3d08e011228ef8a25882397f3a859b9fe1436946140b6756b", size = 582206 },
+ { url = "https://files.pythonhosted.org/packages/b1/8e/8b6f42c67d5df7db35b8c55c9a850ea045219741bb14416255616808c690/greenlet-3.2.3-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:efc6dc8a792243c31f2f5674b670b3a95d46fa1c6a912b8e310d6f542e7b0712", size = 1111412 },
+ { url = "https://files.pythonhosted.org/packages/05/46/ab58828217349500a7ebb81159d52ca357da747ff1797c29c6023d79d798/greenlet-3.2.3-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:731e154aba8e757aedd0781d4b240f1225b075b4409f1bb83b05ff410582cf00", size = 1135054 },
+ { url = "https://files.pythonhosted.org/packages/68/7f/d1b537be5080721c0f0089a8447d4ef72839039cdb743bdd8ffd23046e9a/greenlet-3.2.3-cp310-cp310-win_amd64.whl", hash = "sha256:96c20252c2f792defe9a115d3287e14811036d51e78b3aaddbee23b69b216302", size = 296573 },
+ { url = "https://files.pythonhosted.org/packages/fc/2e/d4fcb2978f826358b673f779f78fa8a32ee37df11920dc2bb5589cbeecef/greenlet-3.2.3-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:784ae58bba89fa1fa5733d170d42486580cab9decda3484779f4759345b29822", size = 270219 },
+ { url = "https://files.pythonhosted.org/packages/16/24/929f853e0202130e4fe163bc1d05a671ce8dcd604f790e14896adac43a52/greenlet-3.2.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0921ac4ea42a5315d3446120ad48f90c3a6b9bb93dd9b3cf4e4d84a66e42de83", size = 630383 },
+ { url = "https://files.pythonhosted.org/packages/d1/b2/0320715eb61ae70c25ceca2f1d5ae620477d246692d9cc284c13242ec31c/greenlet-3.2.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d2971d93bb99e05f8c2c0c2f4aa9484a18d98c4c3bd3c62b65b7e6ae33dfcfaf", size = 642422 },
+ { url = "https://files.pythonhosted.org/packages/bd/49/445fd1a210f4747fedf77615d941444349c6a3a4a1135bba9701337cd966/greenlet-3.2.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:c667c0bf9d406b77a15c924ef3285e1e05250948001220368e039b6aa5b5034b", size = 638375 },
+ { url = "https://files.pythonhosted.org/packages/7e/c8/ca19760cf6eae75fa8dc32b487e963d863b3ee04a7637da77b616703bc37/greenlet-3.2.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:592c12fb1165be74592f5de0d70f82bc5ba552ac44800d632214b76089945147", size = 637627 },
+ { url = "https://files.pythonhosted.org/packages/65/89/77acf9e3da38e9bcfca881e43b02ed467c1dedc387021fc4d9bd9928afb8/greenlet-3.2.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29e184536ba333003540790ba29829ac14bb645514fbd7e32af331e8202a62a5", size = 585502 },
+ { url = "https://files.pythonhosted.org/packages/97/c6/ae244d7c95b23b7130136e07a9cc5aadd60d59b5951180dc7dc7e8edaba7/greenlet-3.2.3-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:93c0bb79844a367782ec4f429d07589417052e621aa39a5ac1fb99c5aa308edc", size = 1114498 },
+ { url = "https://files.pythonhosted.org/packages/89/5f/b16dec0cbfd3070658e0d744487919740c6d45eb90946f6787689a7efbce/greenlet-3.2.3-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:751261fc5ad7b6705f5f76726567375bb2104a059454e0226e1eef6c756748ba", size = 1139977 },
+ { url = "https://files.pythonhosted.org/packages/66/77/d48fb441b5a71125bcac042fc5b1494c806ccb9a1432ecaa421e72157f77/greenlet-3.2.3-cp311-cp311-win_amd64.whl", hash = "sha256:83a8761c75312361aa2b5b903b79da97f13f556164a7dd2d5448655425bd4c34", size = 297017 },
+ { url = "https://files.pythonhosted.org/packages/f3/94/ad0d435f7c48debe960c53b8f60fb41c2026b1d0fa4a99a1cb17c3461e09/greenlet-3.2.3-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:25ad29caed5783d4bd7a85c9251c651696164622494c00802a139c00d639242d", size = 271992 },
+ { url = "https://files.pythonhosted.org/packages/93/5d/7c27cf4d003d6e77749d299c7c8f5fd50b4f251647b5c2e97e1f20da0ab5/greenlet-3.2.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88cd97bf37fe24a6710ec6a3a7799f3f81d9cd33317dcf565ff9950c83f55e0b", size = 638820 },
+ { url = "https://files.pythonhosted.org/packages/c6/7e/807e1e9be07a125bb4c169144937910bf59b9d2f6d931578e57f0bce0ae2/greenlet-3.2.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:baeedccca94880d2f5666b4fa16fc20ef50ba1ee353ee2d7092b383a243b0b0d", size = 653046 },
+ { url = "https://files.pythonhosted.org/packages/9d/ab/158c1a4ea1068bdbc78dba5a3de57e4c7aeb4e7fa034320ea94c688bfb61/greenlet-3.2.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:be52af4b6292baecfa0f397f3edb3c6092ce071b499dd6fe292c9ac9f2c8f264", size = 647701 },
+ { url = "https://files.pythonhosted.org/packages/cc/0d/93729068259b550d6a0288da4ff72b86ed05626eaf1eb7c0d3466a2571de/greenlet-3.2.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0cc73378150b8b78b0c9fe2ce56e166695e67478550769536a6742dca3651688", size = 649747 },
+ { url = "https://files.pythonhosted.org/packages/f6/f6/c82ac1851c60851302d8581680573245c8fc300253fc1ff741ae74a6c24d/greenlet-3.2.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:706d016a03e78df129f68c4c9b4c4f963f7d73534e48a24f5f5a7101ed13dbbb", size = 605461 },
+ { url = "https://files.pythonhosted.org/packages/98/82/d022cf25ca39cf1200650fc58c52af32c90f80479c25d1cbf57980ec3065/greenlet-3.2.3-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:419e60f80709510c343c57b4bb5a339d8767bf9aef9b8ce43f4f143240f88b7c", size = 1121190 },
+ { url = "https://files.pythonhosted.org/packages/f5/e1/25297f70717abe8104c20ecf7af0a5b82d2f5a980eb1ac79f65654799f9f/greenlet-3.2.3-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:93d48533fade144203816783373f27a97e4193177ebaaf0fc396db19e5d61163", size = 1149055 },
+ { url = "https://files.pythonhosted.org/packages/1f/8f/8f9e56c5e82eb2c26e8cde787962e66494312dc8cb261c460e1f3a9c88bc/greenlet-3.2.3-cp312-cp312-win_amd64.whl", hash = "sha256:7454d37c740bb27bdeddfc3f358f26956a07d5220818ceb467a483197d84f849", size = 297817 },
+ { url = "https://files.pythonhosted.org/packages/b1/cf/f5c0b23309070ae93de75c90d29300751a5aacefc0a3ed1b1d8edb28f08b/greenlet-3.2.3-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:500b8689aa9dd1ab26872a34084503aeddefcb438e2e7317b89b11eaea1901ad", size = 270732 },
+ { url = "https://files.pythonhosted.org/packages/48/ae/91a957ba60482d3fecf9be49bc3948f341d706b52ddb9d83a70d42abd498/greenlet-3.2.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a07d3472c2a93117af3b0136f246b2833fdc0b542d4a9799ae5f41c28323faef", size = 639033 },
+ { url = "https://files.pythonhosted.org/packages/6f/df/20ffa66dd5a7a7beffa6451bdb7400d66251374ab40b99981478c69a67a8/greenlet-3.2.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:8704b3768d2f51150626962f4b9a9e4a17d2e37c8a8d9867bbd9fa4eb938d3b3", size = 652999 },
+ { url = "https://files.pythonhosted.org/packages/51/b4/ebb2c8cb41e521f1d72bf0465f2f9a2fd803f674a88db228887e6847077e/greenlet-3.2.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:5035d77a27b7c62db6cf41cf786cfe2242644a7a337a0e155c80960598baab95", size = 647368 },
+ { url = "https://files.pythonhosted.org/packages/8e/6a/1e1b5aa10dced4ae876a322155705257748108b7fd2e4fae3f2a091fe81a/greenlet-3.2.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2d8aa5423cd4a396792f6d4580f88bdc6efcb9205891c9d40d20f6e670992efb", size = 650037 },
+ { url = "https://files.pythonhosted.org/packages/26/f2/ad51331a157c7015c675702e2d5230c243695c788f8f75feba1af32b3617/greenlet-3.2.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2c724620a101f8170065d7dded3f962a2aea7a7dae133a009cada42847e04a7b", size = 608402 },
+ { url = "https://files.pythonhosted.org/packages/26/bc/862bd2083e6b3aff23300900a956f4ea9a4059de337f5c8734346b9b34fc/greenlet-3.2.3-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:873abe55f134c48e1f2a6f53f7d1419192a3d1a4e873bace00499a4e45ea6af0", size = 1119577 },
+ { url = "https://files.pythonhosted.org/packages/86/94/1fc0cc068cfde885170e01de40a619b00eaa8f2916bf3541744730ffb4c3/greenlet-3.2.3-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:024571bbce5f2c1cfff08bf3fbaa43bbc7444f580ae13b0099e95d0e6e67ed36", size = 1147121 },
+ { url = "https://files.pythonhosted.org/packages/27/1a/199f9587e8cb08a0658f9c30f3799244307614148ffe8b1e3aa22f324dea/greenlet-3.2.3-cp313-cp313-win_amd64.whl", hash = "sha256:5195fb1e75e592dd04ce79881c8a22becdfa3e6f500e7feb059b1e6fdd54d3e3", size = 297603 },
+ { url = "https://files.pythonhosted.org/packages/d8/ca/accd7aa5280eb92b70ed9e8f7fd79dc50a2c21d8c73b9a0856f5b564e222/greenlet-3.2.3-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:3d04332dddb10b4a211b68111dabaee2e1a073663d117dc10247b5b1642bac86", size = 271479 },
+ { url = "https://files.pythonhosted.org/packages/55/71/01ed9895d9eb49223280ecc98a557585edfa56b3d0e965b9fa9f7f06b6d9/greenlet-3.2.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8186162dffde068a465deab08fc72c767196895c39db26ab1c17c0b77a6d8b97", size = 683952 },
+ { url = "https://files.pythonhosted.org/packages/ea/61/638c4bdf460c3c678a0a1ef4c200f347dff80719597e53b5edb2fb27ab54/greenlet-3.2.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f4bfbaa6096b1b7a200024784217defedf46a07c2eee1a498e94a1b5f8ec5728", size = 696917 },
+ { url = "https://files.pythonhosted.org/packages/22/cc/0bd1a7eb759d1f3e3cc2d1bc0f0b487ad3cc9f34d74da4b80f226fde4ec3/greenlet-3.2.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:ed6cfa9200484d234d8394c70f5492f144b20d4533f69262d530a1a082f6ee9a", size = 692443 },
+ { url = "https://files.pythonhosted.org/packages/67/10/b2a4b63d3f08362662e89c103f7fe28894a51ae0bc890fabf37d1d780e52/greenlet-3.2.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:02b0df6f63cd15012bed5401b47829cfd2e97052dc89da3cfaf2c779124eb892", size = 692995 },
+ { url = "https://files.pythonhosted.org/packages/5a/c6/ad82f148a4e3ce9564056453a71529732baf5448ad53fc323e37efe34f66/greenlet-3.2.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:86c2d68e87107c1792e2e8d5399acec2487a4e993ab76c792408e59394d52141", size = 655320 },
+ { url = "https://files.pythonhosted.org/packages/5c/4f/aab73ecaa6b3086a4c89863d94cf26fa84cbff63f52ce9bc4342b3087a06/greenlet-3.2.3-cp314-cp314-win_amd64.whl", hash = "sha256:8c47aae8fbbfcf82cc13327ae802ba13c9c36753b67e760023fd116bc124a62a", size = 301236 },
+ { url = "https://files.pythonhosted.org/packages/3d/d9/a3114df5fba2bf9823e0acc01e9e2abdcd8ea4c5487cf1c3dcd4cc0b48cf/greenlet-3.2.3-cp39-cp39-macosx_11_0_universal2.whl", hash = "sha256:42efc522c0bd75ffa11a71e09cd8a399d83fafe36db250a87cf1dacfaa15dc64", size = 267769 },
+ { url = "https://files.pythonhosted.org/packages/bc/da/47dfc50f6e5673116e66a737dc58d1eca651db9a9aa8797c1d27e940e211/greenlet-3.2.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d760f9bdfe79bff803bad32b4d8ffb2c1d2ce906313fc10a83976ffb73d64ca7", size = 625472 },
+ { url = "https://files.pythonhosted.org/packages/f5/74/f6ef9f85d981b2fcd665bbee3e69e3c0a10fb962eb4c6a5889ac3b6debfa/greenlet-3.2.3-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:8324319cbd7b35b97990090808fdc99c27fe5338f87db50514959f8059999805", size = 637253 },
+ { url = "https://files.pythonhosted.org/packages/66/69/4919bb1c9e43bfc16dc886e7a37fe1bc04bfa4101aba177936a10f313cad/greenlet-3.2.3-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:8c37ef5b3787567d322331d5250e44e42b58c8c713859b8a04c6065f27efbf72", size = 632611 },
+ { url = "https://files.pythonhosted.org/packages/6b/8d/97d988d019f40b6b360b0c71c99e5b4c877a3d92666fe48b081d0e1ea1cd/greenlet-3.2.3-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ce539fb52fb774d0802175d37fcff5c723e2c7d249c65916257f0a940cee8904", size = 631843 },
+ { url = "https://files.pythonhosted.org/packages/59/24/d5e1504ec00768755d4ccc2168b76d9f4524e96694a14ad45bd87796e9bb/greenlet-3.2.3-cp39-cp39-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:003c930e0e074db83559edc8705f3a2d066d4aa8c2f198aff1e454946efd0f26", size = 580781 },
+ { url = "https://files.pythonhosted.org/packages/9c/df/d009bcca566dbfd2283b306b4e424f4c0e59bf984868f8b789802fe9e607/greenlet-3.2.3-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:7e70ea4384b81ef9e84192e8a77fb87573138aa5d4feee541d8014e452b434da", size = 1109903 },
+ { url = "https://files.pythonhosted.org/packages/33/54/5036097197a78388aa6901a5b90b562f3a154a9fbee89c301a26f56f3942/greenlet-3.2.3-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:22eb5ba839c4b2156f18f76768233fe44b23a31decd9cc0d4cc8141c211fd1b4", size = 1133975 },
+ { url = "https://files.pythonhosted.org/packages/e2/15/b001456a430805fdd8b600a788d19a790664eee8863739523395f68df752/greenlet-3.2.3-cp39-cp39-win32.whl", hash = "sha256:4532f0d25df67f896d137431b13f4cdce89f7e3d4a96387a41290910df4d3a57", size = 279320 },
+ { url = "https://files.pythonhosted.org/packages/6c/4c/bf2100cbc1bd07f39bee3b09e7eef39beffe29f5453dc2477a2693737913/greenlet-3.2.3-cp39-cp39-win_amd64.whl", hash = "sha256:aaa7aae1e7f75eaa3ae400ad98f8644bb81e1dc6ba47ce8a93d3f17274e08322", size = 296444 },
+]
+
+[[package]]
+name = "griffe"
+version = "1.7.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a9/3e/5aa9a61f7c3c47b0b52a1d930302992229d191bf4bc76447b324b731510a/griffe-1.7.3.tar.gz", hash = "sha256:52ee893c6a3a968b639ace8015bec9d36594961e156e23315c8e8e51401fa50b", size = 395137 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/58/c6/5c20af38c2a57c15d87f7f38bee77d63c1d2a3689f74fefaf35915dd12b2/griffe-1.7.3-py3-none-any.whl", hash = "sha256:c6b3ee30c2f0f17f30bcdef5068d6ab7a2a4f1b8bf1a3e74b56fffd21e1c5f75", size = 129303 },
+]
+
+[[package]]
+name = "h11"
+version = "0.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515 },
+]
+
+[[package]]
+name = "hf-transfer"
+version = "0.1.9"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1a/eb/8fc64f40388c29ce8ce3b2b180a089d4d6b25b1d0d232d016704cb852104/hf_transfer-0.1.9.tar.gz", hash = "sha256:035572865dab29d17e783fbf1e84cf1cb24f3fcf8f1b17db1cfc7fdf139f02bf", size = 25201 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a4/78/0dce00208f585fae675f40033ef9a30dedfa83665d5ac79f16beb4a0a6c2/hf_transfer-0.1.9-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:6e94e8822da79573c9b6ae4d6b2f847c59a7a06c5327d7db20751b68538dc4f6", size = 1386084 },
+ { url = "https://files.pythonhosted.org/packages/ea/2e/3d60b1a9e9f29a2152aa66c823bf5e399ae7be3fef310ff0de86779c5d2d/hf_transfer-0.1.9-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:3ebc4ab9023414880c8b1d3c38174d1c9989eb5022d37e814fa91a3060123eb0", size = 1343558 },
+ { url = "https://files.pythonhosted.org/packages/fb/38/130a5ac3747f104033591bcac1c961cb1faadfdc91704f59b09c0b465ff2/hf_transfer-0.1.9-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8674026f21ed369aa2a0a4b46000aca850fc44cd2b54af33a172ce5325b4fc82", size = 3726676 },
+ { url = "https://files.pythonhosted.org/packages/15/a1/f4e27c5ad17aac616ae0849e2aede5aae31db8267a948c6b3eeb9fd96446/hf_transfer-0.1.9-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a736dfbb2c84f5a2c975478ad200c0c8bfcb58a25a35db402678fb87ce17fa4", size = 3062920 },
+ { url = "https://files.pythonhosted.org/packages/8d/0d/727abdfba39bc3f1132cfa4c970588c2c0bb0d82fe2d645cc10f4e2f8e0b/hf_transfer-0.1.9-cp313-cp313t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:504b8427fd785dd8546d53b9fafe6e436bd7a3adf76b9dce556507650a7b4567", size = 3578681 },
+ { url = "https://files.pythonhosted.org/packages/50/d0/2b213eb1ea8b1252ccaf1a6c804d0aba03fea38aae4124df6a3acb70511a/hf_transfer-0.1.9-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2c7fc1b85f4d0f76e452765d7648c9f4bfd0aedb9ced2ae1ebfece2d8cfaf8e2", size = 3398837 },
+ { url = "https://files.pythonhosted.org/packages/8c/8a/79dbce9006e0bd6b74516f97451a7b7c64dbbb426df15d901dd438cfeee3/hf_transfer-0.1.9-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0d991376f0eac70a60f0cbc95602aa708a6f7c8617f28b4945c1431d67b8e3c8", size = 3546986 },
+ { url = "https://files.pythonhosted.org/packages/a9/f7/9ac239b6ee6fe0bad130325d987a93ea58c4118e50479f0786f1733b37e8/hf_transfer-0.1.9-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e6ac4eddcd99575ed3735ed911ddf9d1697e2bd13aa3f0ad7e3904dd4863842e", size = 4071715 },
+ { url = "https://files.pythonhosted.org/packages/d8/a3/0ed697279f5eeb7a40f279bd783cf50e6d0b91f24120dcf66ef2cf8822b4/hf_transfer-0.1.9-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:57fd9880da1ee0f47250f735f791fab788f0aa1ee36afc49f761349869c8b4d9", size = 3388081 },
+ { url = "https://files.pythonhosted.org/packages/dc/eb/47e477bdf1d784f31c7540db6cc8c354b777e51a186897a7abda34517f36/hf_transfer-0.1.9-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:5d561f0520f493c66b016d99ceabe69c23289aa90be38dd802d2aef279f15751", size = 3658654 },
+ { url = "https://files.pythonhosted.org/packages/45/07/6661e43fbee09594a8a5e9bb778107d95fe38dac4c653982afe03d32bd4d/hf_transfer-0.1.9-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:a5b366d34cd449fe9b20ef25941e6eef0460a2f74e7389f02e673e1f88ebd538", size = 3690551 },
+ { url = "https://files.pythonhosted.org/packages/81/f5/461d2e5f307e5048289b1168d5c642ae3bb2504e88dff1a38b92ed990a21/hf_transfer-0.1.9-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e66acf91df4a8b72f60223059df3003062a5ae111757187ed1a06750a30e911b", size = 1393046 },
+ { url = "https://files.pythonhosted.org/packages/41/ba/8d9fd9f1083525edfcb389c93738c802f3559cb749324090d7109c8bf4c2/hf_transfer-0.1.9-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:8669dbcc7a3e2e8d61d42cd24da9c50d57770bd74b445c65123291ca842a7e7a", size = 1348126 },
+ { url = "https://files.pythonhosted.org/packages/8e/a2/cd7885bc9959421065a6fae0fe67b6c55becdeda4e69b873e52976f9a9f0/hf_transfer-0.1.9-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8fd0167c4407a3bc4cdd0307e65ada2294ec04f1813d8a69a5243e379b22e9d8", size = 3728604 },
+ { url = "https://files.pythonhosted.org/packages/f6/2e/a072cf196edfeda3310c9a5ade0a0fdd785e6154b3ce24fc738c818da2a7/hf_transfer-0.1.9-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ee8b10afedcb75f71091bcc197c526a6ebf5c58bbbadb34fdeee6160f55f619f", size = 3064995 },
+ { url = "https://files.pythonhosted.org/packages/c2/84/aec9ef4c0fab93c1ea2b1badff38c78b4b2f86f0555b26d2051dbc920cde/hf_transfer-0.1.9-cp38-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5828057e313de59300dd1abb489444bc452efe3f479d3c55b31a8f680936ba42", size = 3580908 },
+ { url = "https://files.pythonhosted.org/packages/29/63/b560d39651a56603d64f1a0212d0472a44cbd965db2fa62b99d99cb981bf/hf_transfer-0.1.9-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fc6bd19e1cc177c66bdef15ef8636ad3bde79d5a4f608c158021153b4573509d", size = 3400839 },
+ { url = "https://files.pythonhosted.org/packages/d6/d8/f87ea6f42456254b48915970ed98e993110521e9263472840174d32c880d/hf_transfer-0.1.9-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdca9bfb89e6f8f281890cc61a8aff2d3cecaff7e1a4d275574d96ca70098557", size = 3552664 },
+ { url = "https://files.pythonhosted.org/packages/d6/56/1267c39b65fc8f4e2113b36297320f102718bf5799b544a6cbe22013aa1d/hf_transfer-0.1.9-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:89a23f58b7b7effbc047b8ca286f131b17728c99a9f972723323003ffd1bb916", size = 4073732 },
+ { url = "https://files.pythonhosted.org/packages/82/1a/9c748befbe3decf7cb415e34f8a0c3789a0a9c55910dea73d581e48c0ce5/hf_transfer-0.1.9-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:dc7fff1345980d6c0ebb92c811d24afa4b98b3e07ed070c8e38cc91fd80478c5", size = 3390096 },
+ { url = "https://files.pythonhosted.org/packages/72/85/4c03da147b6b4b7cb12e074d3d44eee28604a387ed0eaf7eaaead5069c57/hf_transfer-0.1.9-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:1a6bd16c667ebe89a069ca163060127a794fa3a3525292c900b8c8cc47985b0d", size = 3664743 },
+ { url = "https://files.pythonhosted.org/packages/e7/6e/e597b04f753f1b09e6893075d53a82a30c13855cbaa791402695b01e369f/hf_transfer-0.1.9-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:d2fde99d502093ade3ab1b53f80da18480e9902aa960dab7f74fb1b9e5bc5746", size = 3695243 },
+ { url = "https://files.pythonhosted.org/packages/09/89/d4e234727a26b2546c8fb70a276cd924260d60135f2165bf8b9ed67bb9a4/hf_transfer-0.1.9-cp38-abi3-win32.whl", hash = "sha256:435cc3cdc8524ce57b074032b8fd76eed70a4224d2091232fa6a8cef8fd6803e", size = 1086605 },
+ { url = "https://files.pythonhosted.org/packages/a1/14/f1e15b851d1c2af5b0b1a82bf8eb10bda2da62d98180220ba6fd8879bb5b/hf_transfer-0.1.9-cp38-abi3-win_amd64.whl", hash = "sha256:16f208fc678911c37e11aa7b586bc66a37d02e636208f18b6bc53d29b5df40ad", size = 1160240 },
+]
+
+[[package]]
+name = "hf-xet"
+version = "1.1.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/75/dc/dc091aeeb671e71cbec30e84963f9c0202c17337b24b0a800e7d205543e8/hf_xet-1.1.3.tar.gz", hash = "sha256:a5f09b1dd24e6ff6bcedb4b0ddab2d81824098bb002cf8b4ffa780545fa348c3", size = 488127 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9b/1f/bc01a4c0894973adebbcd4aa338a06815c76333ebb3921d94dcbd40dae6a/hf_xet-1.1.3-cp37-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c3b508b5f583a75641aebf732853deb058953370ce8184f5dabc49f803b0819b", size = 2256929 },
+ { url = "https://files.pythonhosted.org/packages/78/07/6ef50851b5c6b45b77a6e018fa299c69a2db3b8bbd0d5af594c0238b1ceb/hf_xet-1.1.3-cp37-abi3-macosx_11_0_arm64.whl", hash = "sha256:b788a61977fbe6b5186e66239e2a329a3f0b7e7ff50dad38984c0c74f44aeca1", size = 2153719 },
+ { url = "https://files.pythonhosted.org/packages/52/48/e929e6e3db6e4758c2adf0f2ca2c59287f1b76229d8bdc1a4c9cfc05212e/hf_xet-1.1.3-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd2da210856444a34aad8ada2fc12f70dabed7cc20f37e90754d1d9b43bc0534", size = 4820519 },
+ { url = "https://files.pythonhosted.org/packages/28/2e/03f89c5014a5aafaa9b150655f811798a317036646623bdaace25f485ae8/hf_xet-1.1.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8203f52827e3df65981984936654a5b390566336956f65765a8aa58c362bb841", size = 4964121 },
+ { url = "https://files.pythonhosted.org/packages/47/8b/5cd399a92b47d98086f55fc72d69bc9ea5e5c6f27a9ed3e0cdd6be4e58a3/hf_xet-1.1.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:30c575a5306f8e6fda37edb866762140a435037365eba7a17ce7bd0bc0216a8b", size = 5283017 },
+ { url = "https://files.pythonhosted.org/packages/53/e3/2fcec58d2fcfd25ff07feb876f466cfa11f8dcf9d3b742c07fe9dd51ee0a/hf_xet-1.1.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7c1a6aa6abed1f696f8099aa9796ca04c9ee778a58728a115607de9cc4638ff1", size = 4970349 },
+ { url = "https://files.pythonhosted.org/packages/53/bf/10ca917e335861101017ff46044c90e517b574fbb37219347b83be1952f6/hf_xet-1.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:b578ae5ac9c056296bb0df9d018e597c8dc6390c5266f35b5c44696003cde9f3", size = 2310934 },
+]
+
+[[package]]
+name = "httpcore"
+version = "1.0.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "h11" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784 },
+]
+
+[[package]]
+name = "httpx"
+version = "0.28.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "certifi" },
+ { name = "httpcore" },
+ { name = "idna" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517 },
+]
+
+[[package]]
+name = "huggingface-hub"
+version = "0.33.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "filelock" },
+ { name = "fsspec" },
+ { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "requests" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/91/8a/1362d565fefabaa4185cf3ae842a98dbc5b35146f5694f7080f043a6952f/huggingface_hub-0.33.0.tar.gz", hash = "sha256:aa31f70d29439d00ff7a33837c03f1f9dd83971ce4e29ad664d63ffb17d3bb97", size = 426179 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/33/fb/53587a89fbc00799e4179796f51b3ad713c5de6bb680b2becb6d37c94649/huggingface_hub-0.33.0-py3-none-any.whl", hash = "sha256:e8668875b40c68f9929150d99727d39e5ebb8a05a98e4191b908dc7ded9074b3", size = 514799 },
+]
+
+[[package]]
+name = "idna"
+version = "3.10"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 },
+]
+
+[[package]]
+name = "importlib-metadata"
+version = "8.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "zipp" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/76/66/650a33bd90f786193e4de4b3ad86ea60b53c89b669a5c7be931fac31cdb0/importlib_metadata-8.7.0.tar.gz", hash = "sha256:d13b81ad223b890aa16c5471f2ac3056cf76c5f10f82d6f9292f0b415f389000", size = 56641 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/b0/36bd937216ec521246249be3bf9855081de4c5e06a0c9b4219dbeda50373/importlib_metadata-8.7.0-py3-none-any.whl", hash = "sha256:e5dd1551894c77868a30651cef00984d50e1002d06942a7101d34870c5f02afd", size = 27656 },
+]
+
+[[package]]
+name = "importlib-resources"
+version = "6.5.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "zipp", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/cf/8c/f834fbf984f691b4f7ff60f50b514cc3de5cc08abfc3295564dd89c5e2e7/importlib_resources-6.5.2.tar.gz", hash = "sha256:185f87adef5bcc288449d98fb4fba07cea78bc036455dd44c5fc4a2fe78fed2c", size = 44693 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a4/ed/1f1afb2e9e7f38a545d628f864d562a5ae64fe6f7a10e28ffb9b185b4e89/importlib_resources-6.5.2-py3-none-any.whl", hash = "sha256:789cfdc3ed28c78b67a06acb8126751ced69a3d5f79c095a98298cd8a760ccec", size = 37461 },
+]
+
+[[package]]
+name = "iniconfig"
+version = "2.1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050 },
+]
+
+[[package]]
+name = "interegular"
+version = "0.3.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/dc/9d/8b6dde58a028a3962ce17e84d5fe73758df61378e00ef8ac3d85da34b0ff/interegular-0.3.3.tar.gz", hash = "sha256:d9b697b21b34884711399ba0f0376914b81899ce670032486d0d048344a76600", size = 24705 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c4/01/72d6472f80651673716d1deda2a5bbb633e563ecf94f4479da5519d69d25/interegular-0.3.3-py37-none-any.whl", hash = "sha256:b0c07007d48c89d6d19f7204972d369b2a77222722e126b6aa63aa721dc3b19c", size = 23635 },
+]
+
+[[package]]
+name = "ipython"
+version = "8.18.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version < '3.10' and sys_platform == 'win32'" },
+ { name = "decorator", marker = "python_full_version < '3.10'" },
+ { name = "exceptiongroup", marker = "python_full_version < '3.10'" },
+ { name = "jedi", marker = "python_full_version < '3.10'" },
+ { name = "matplotlib-inline", marker = "python_full_version < '3.10'" },
+ { name = "pexpect", marker = "python_full_version < '3.10' and sys_platform != 'win32'" },
+ { name = "prompt-toolkit", marker = "python_full_version < '3.10'" },
+ { name = "pygments", marker = "python_full_version < '3.10'" },
+ { name = "stack-data", marker = "python_full_version < '3.10'" },
+ { name = "traitlets", marker = "python_full_version < '3.10'" },
+ { name = "typing-extensions", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b1/b9/3ba6c45a6df813c09a48bac313c22ff83efa26cbb55011218d925a46e2ad/ipython-8.18.1.tar.gz", hash = "sha256:ca6f079bb33457c66e233e4580ebfc4128855b4cf6370dddd73842a9563e8a27", size = 5486330 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/47/6b/d9fdcdef2eb6a23f391251fde8781c38d42acd82abe84d054cb74f7863b0/ipython-8.18.1-py3-none-any.whl", hash = "sha256:e8267419d72d81955ec1177f8a29aaa90ac80ad647499201119e2f05e99aa397", size = 808161 },
+]
+
+[[package]]
+name = "ipython"
+version = "8.37.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version == '3.10.*' and sys_platform == 'win32'" },
+ { name = "decorator", marker = "python_full_version == '3.10.*'" },
+ { name = "exceptiongroup", marker = "python_full_version == '3.10.*'" },
+ { name = "jedi", marker = "python_full_version == '3.10.*'" },
+ { name = "matplotlib-inline", marker = "python_full_version == '3.10.*'" },
+ { name = "pexpect", marker = "python_full_version == '3.10.*' and sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "prompt-toolkit", marker = "python_full_version == '3.10.*'" },
+ { name = "pygments", marker = "python_full_version == '3.10.*'" },
+ { name = "stack-data", marker = "python_full_version == '3.10.*'" },
+ { name = "traitlets", marker = "python_full_version == '3.10.*'" },
+ { name = "typing-extensions", marker = "python_full_version == '3.10.*'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/85/31/10ac88f3357fc276dc8a64e8880c82e80e7459326ae1d0a211b40abf6665/ipython-8.37.0.tar.gz", hash = "sha256:ca815841e1a41a1e6b73a0b08f3038af9b2252564d01fc405356d34033012216", size = 5606088 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/91/d0/274fbf7b0b12643cbbc001ce13e6a5b1607ac4929d1b11c72460152c9fc3/ipython-8.37.0-py3-none-any.whl", hash = "sha256:ed87326596b878932dbcb171e3e698845434d8c61b8d8cd474bf663041a9dcf2", size = 831864 },
+]
+
+[[package]]
+name = "ipython"
+version = "9.3.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version >= '3.11' and sys_platform == 'win32'" },
+ { name = "decorator", marker = "python_full_version >= '3.11'" },
+ { name = "ipython-pygments-lexers", marker = "python_full_version >= '3.11'" },
+ { name = "jedi", marker = "python_full_version >= '3.11'" },
+ { name = "matplotlib-inline", marker = "python_full_version >= '3.11'" },
+ { name = "pexpect", marker = "python_full_version >= '3.11' and sys_platform != 'emscripten' and sys_platform != 'win32'" },
+ { name = "prompt-toolkit", marker = "python_full_version >= '3.11'" },
+ { name = "pygments", marker = "python_full_version >= '3.11'" },
+ { name = "stack-data", marker = "python_full_version >= '3.11'" },
+ { name = "traitlets", marker = "python_full_version >= '3.11'" },
+ { name = "typing-extensions", marker = "python_full_version == '3.11.*'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/dc/09/4c7e06b96fbd203e06567b60fb41b06db606b6a82db6db7b2c85bb72a15c/ipython-9.3.0.tar.gz", hash = "sha256:79eb896f9f23f50ad16c3bc205f686f6e030ad246cc309c6279a242b14afe9d8", size = 4426460 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3c/99/9ed3d52d00f1846679e3aa12e2326ac7044b5e7f90dc822b60115fa533ca/ipython-9.3.0-py3-none-any.whl", hash = "sha256:1a0b6dd9221a1f5dddf725b57ac0cb6fddc7b5f470576231ae9162b9b3455a04", size = 605320 },
+]
+
+[[package]]
+name = "ipython-pygments-lexers"
+version = "1.1.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pygments", marker = "python_full_version >= '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ef/4c/5dd1d8af08107f88c7f741ead7a40854b8ac24ddf9ae850afbcf698aa552/ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81", size = 8393 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d9/33/1f075bf72b0b747cb3288d011319aaf64083cf2efef8354174e3ed4540e2/ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c", size = 8074 },
+]
+
+[[package]]
+name = "itsdangerous"
+version = "2.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234 },
+]
+
+[[package]]
+name = "jedi"
+version = "0.19.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "parso" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/72/3a/79a912fbd4d8dd6fbb02bf69afd3bb72cf0c729bb3063c6f4498603db17a/jedi-0.19.2.tar.gz", hash = "sha256:4770dc3de41bde3966b02eb84fbcf557fb33cce26ad23da12c742fb50ecb11f0", size = 1231287 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c0/5a/9cac0c82afec3d09ccd97c8b6502d48f165f9124db81b4bcb90b4af974ee/jedi-0.19.2-py2.py3-none-any.whl", hash = "sha256:a8ef22bde8490f57fe5c7681a3c83cb58874daf72b4784de3cce5b6ef6edb5b9", size = 1572278 },
+]
+
+[[package]]
+name = "jinja2"
+version = "3.1.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markupsafe" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899 },
+]
+
+[[package]]
+name = "jiter"
+version = "0.10.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ee/9d/ae7ddb4b8ab3fb1b51faf4deb36cb48a4fbbd7cb36bad6a5fca4741306f7/jiter-0.10.0.tar.gz", hash = "sha256:07a7142c38aacc85194391108dc91b5b57093c978a9932bd86a36862759d9500", size = 162759 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/be/7e/4011b5c77bec97cb2b572f566220364e3e21b51c48c5bd9c4a9c26b41b67/jiter-0.10.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:cd2fb72b02478f06a900a5782de2ef47e0396b3e1f7d5aba30daeb1fce66f303", size = 317215 },
+ { url = "https://files.pythonhosted.org/packages/8a/4f/144c1b57c39692efc7ea7d8e247acf28e47d0912800b34d0ad815f6b2824/jiter-0.10.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:32bb468e3af278f095d3fa5b90314728a6916d89ba3d0ffb726dd9bf7367285e", size = 322814 },
+ { url = "https://files.pythonhosted.org/packages/63/1f/db977336d332a9406c0b1f0b82be6f71f72526a806cbb2281baf201d38e3/jiter-0.10.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa8b3e0068c26ddedc7abc6fac37da2d0af16b921e288a5a613f4b86f050354f", size = 345237 },
+ { url = "https://files.pythonhosted.org/packages/d7/1c/aa30a4a775e8a672ad7f21532bdbfb269f0706b39c6ff14e1f86bdd9e5ff/jiter-0.10.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:286299b74cc49e25cd42eea19b72aa82c515d2f2ee12d11392c56d8701f52224", size = 370999 },
+ { url = "https://files.pythonhosted.org/packages/35/df/f8257abc4207830cb18880781b5f5b716bad5b2a22fb4330cfd357407c5b/jiter-0.10.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6ed5649ceeaeffc28d87fb012d25a4cd356dcd53eff5acff1f0466b831dda2a7", size = 491109 },
+ { url = "https://files.pythonhosted.org/packages/06/76/9e1516fd7b4278aa13a2cc7f159e56befbea9aa65c71586305e7afa8b0b3/jiter-0.10.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b2ab0051160cb758a70716448908ef14ad476c3774bd03ddce075f3c1f90a3d6", size = 388608 },
+ { url = "https://files.pythonhosted.org/packages/6d/64/67750672b4354ca20ca18d3d1ccf2c62a072e8a2d452ac3cf8ced73571ef/jiter-0.10.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03997d2f37f6b67d2f5c475da4412be584e1cec273c1cfc03d642c46db43f8cf", size = 352454 },
+ { url = "https://files.pythonhosted.org/packages/96/4d/5c4e36d48f169a54b53a305114be3efa2bbffd33b648cd1478a688f639c1/jiter-0.10.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c404a99352d839fed80d6afd6c1d66071f3bacaaa5c4268983fc10f769112e90", size = 391833 },
+ { url = "https://files.pythonhosted.org/packages/0b/de/ce4a6166a78810bd83763d2fa13f85f73cbd3743a325469a4a9289af6dae/jiter-0.10.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:66e989410b6666d3ddb27a74c7e50d0829704ede652fd4c858e91f8d64b403d0", size = 523646 },
+ { url = "https://files.pythonhosted.org/packages/a2/a6/3bc9acce53466972964cf4ad85efecb94f9244539ab6da1107f7aed82934/jiter-0.10.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b532d3af9ef4f6374609a3bcb5e05a1951d3bf6190dc6b176fdb277c9bbf15ee", size = 514735 },
+ { url = "https://files.pythonhosted.org/packages/b4/d8/243c2ab8426a2a4dea85ba2a2ba43df379ccece2145320dfd4799b9633c5/jiter-0.10.0-cp310-cp310-win32.whl", hash = "sha256:da9be20b333970e28b72edc4dff63d4fec3398e05770fb3205f7fb460eb48dd4", size = 210747 },
+ { url = "https://files.pythonhosted.org/packages/37/7a/8021bd615ef7788b98fc76ff533eaac846322c170e93cbffa01979197a45/jiter-0.10.0-cp310-cp310-win_amd64.whl", hash = "sha256:f59e533afed0c5b0ac3eba20d2548c4a550336d8282ee69eb07b37ea526ee4e5", size = 207484 },
+ { url = "https://files.pythonhosted.org/packages/1b/dd/6cefc6bd68b1c3c979cecfa7029ab582b57690a31cd2f346c4d0ce7951b6/jiter-0.10.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3bebe0c558e19902c96e99217e0b8e8b17d570906e72ed8a87170bc290b1e978", size = 317473 },
+ { url = "https://files.pythonhosted.org/packages/be/cf/fc33f5159ce132be1d8dd57251a1ec7a631c7df4bd11e1cd198308c6ae32/jiter-0.10.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:558cc7e44fd8e507a236bee6a02fa17199ba752874400a0ca6cd6e2196cdb7dc", size = 321971 },
+ { url = "https://files.pythonhosted.org/packages/68/a4/da3f150cf1d51f6c472616fb7650429c7ce053e0c962b41b68557fdf6379/jiter-0.10.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4d613e4b379a07d7c8453c5712ce7014e86c6ac93d990a0b8e7377e18505e98d", size = 345574 },
+ { url = "https://files.pythonhosted.org/packages/84/34/6e8d412e60ff06b186040e77da5f83bc158e9735759fcae65b37d681f28b/jiter-0.10.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f62cf8ba0618eda841b9bf61797f21c5ebd15a7a1e19daab76e4e4b498d515b2", size = 371028 },
+ { url = "https://files.pythonhosted.org/packages/fb/d9/9ee86173aae4576c35a2f50ae930d2ccb4c4c236f6cb9353267aa1d626b7/jiter-0.10.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:919d139cdfa8ae8945112398511cb7fca58a77382617d279556b344867a37e61", size = 491083 },
+ { url = "https://files.pythonhosted.org/packages/d9/2c/f955de55e74771493ac9e188b0f731524c6a995dffdcb8c255b89c6fb74b/jiter-0.10.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:13ddbc6ae311175a3b03bd8994881bc4635c923754932918e18da841632349db", size = 388821 },
+ { url = "https://files.pythonhosted.org/packages/81/5a/0e73541b6edd3f4aada586c24e50626c7815c561a7ba337d6a7eb0a915b4/jiter-0.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c440ea003ad10927a30521a9062ce10b5479592e8a70da27f21eeb457b4a9c5", size = 352174 },
+ { url = "https://files.pythonhosted.org/packages/1c/c0/61eeec33b8c75b31cae42be14d44f9e6fe3ac15a4e58010256ac3abf3638/jiter-0.10.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:dc347c87944983481e138dea467c0551080c86b9d21de6ea9306efb12ca8f606", size = 391869 },
+ { url = "https://files.pythonhosted.org/packages/41/22/5beb5ee4ad4ef7d86f5ea5b4509f680a20706c4a7659e74344777efb7739/jiter-0.10.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:13252b58c1f4d8c5b63ab103c03d909e8e1e7842d302473f482915d95fefd605", size = 523741 },
+ { url = "https://files.pythonhosted.org/packages/ea/10/768e8818538e5817c637b0df52e54366ec4cebc3346108a4457ea7a98f32/jiter-0.10.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7d1bbf3c465de4a24ab12fb7766a0003f6f9bce48b8b6a886158c4d569452dc5", size = 514527 },
+ { url = "https://files.pythonhosted.org/packages/73/6d/29b7c2dc76ce93cbedabfd842fc9096d01a0550c52692dfc33d3cc889815/jiter-0.10.0-cp311-cp311-win32.whl", hash = "sha256:db16e4848b7e826edca4ccdd5b145939758dadf0dc06e7007ad0e9cfb5928ae7", size = 210765 },
+ { url = "https://files.pythonhosted.org/packages/c2/c9/d394706deb4c660137caf13e33d05a031d734eb99c051142e039d8ceb794/jiter-0.10.0-cp311-cp311-win_amd64.whl", hash = "sha256:9c9c1d5f10e18909e993f9641f12fe1c77b3e9b533ee94ffa970acc14ded3812", size = 209234 },
+ { url = "https://files.pythonhosted.org/packages/6d/b5/348b3313c58f5fbfb2194eb4d07e46a35748ba6e5b3b3046143f3040bafa/jiter-0.10.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1e274728e4a5345a6dde2d343c8da018b9d4bd4350f5a472fa91f66fda44911b", size = 312262 },
+ { url = "https://files.pythonhosted.org/packages/9c/4a/6a2397096162b21645162825f058d1709a02965606e537e3304b02742e9b/jiter-0.10.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7202ae396446c988cb2a5feb33a543ab2165b786ac97f53b59aafb803fef0744", size = 320124 },
+ { url = "https://files.pythonhosted.org/packages/2a/85/1ce02cade7516b726dd88f59a4ee46914bf79d1676d1228ef2002ed2f1c9/jiter-0.10.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23ba7722d6748b6920ed02a8f1726fb4b33e0fd2f3f621816a8b486c66410ab2", size = 345330 },
+ { url = "https://files.pythonhosted.org/packages/75/d0/bb6b4f209a77190ce10ea8d7e50bf3725fc16d3372d0a9f11985a2b23eff/jiter-0.10.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:371eab43c0a288537d30e1f0b193bc4eca90439fc08a022dd83e5e07500ed026", size = 369670 },
+ { url = "https://files.pythonhosted.org/packages/a0/f5/a61787da9b8847a601e6827fbc42ecb12be2c925ced3252c8ffcb56afcaf/jiter-0.10.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c675736059020365cebc845a820214765162728b51ab1e03a1b7b3abb70f74c", size = 489057 },
+ { url = "https://files.pythonhosted.org/packages/12/e4/6f906272810a7b21406c760a53aadbe52e99ee070fc5c0cb191e316de30b/jiter-0.10.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0c5867d40ab716e4684858e4887489685968a47e3ba222e44cde6e4a2154f959", size = 389372 },
+ { url = "https://files.pythonhosted.org/packages/e2/ba/77013b0b8ba904bf3762f11e0129b8928bff7f978a81838dfcc958ad5728/jiter-0.10.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:395bb9a26111b60141757d874d27fdea01b17e8fac958b91c20128ba8f4acc8a", size = 352038 },
+ { url = "https://files.pythonhosted.org/packages/67/27/c62568e3ccb03368dbcc44a1ef3a423cb86778a4389e995125d3d1aaa0a4/jiter-0.10.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6842184aed5cdb07e0c7e20e5bdcfafe33515ee1741a6835353bb45fe5d1bd95", size = 391538 },
+ { url = "https://files.pythonhosted.org/packages/c0/72/0d6b7e31fc17a8fdce76164884edef0698ba556b8eb0af9546ae1a06b91d/jiter-0.10.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:62755d1bcea9876770d4df713d82606c8c1a3dca88ff39046b85a048566d56ea", size = 523557 },
+ { url = "https://files.pythonhosted.org/packages/2f/09/bc1661fbbcbeb6244bd2904ff3a06f340aa77a2b94e5a7373fd165960ea3/jiter-0.10.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:533efbce2cacec78d5ba73a41756beff8431dfa1694b6346ce7af3a12c42202b", size = 514202 },
+ { url = "https://files.pythonhosted.org/packages/1b/84/5a5d5400e9d4d54b8004c9673bbe4403928a00d28529ff35b19e9d176b19/jiter-0.10.0-cp312-cp312-win32.whl", hash = "sha256:8be921f0cadd245e981b964dfbcd6fd4bc4e254cdc069490416dd7a2632ecc01", size = 211781 },
+ { url = "https://files.pythonhosted.org/packages/9b/52/7ec47455e26f2d6e5f2ea4951a0652c06e5b995c291f723973ae9e724a65/jiter-0.10.0-cp312-cp312-win_amd64.whl", hash = "sha256:a7c7d785ae9dda68c2678532a5a1581347e9c15362ae9f6e68f3fdbfb64f2e49", size = 206176 },
+ { url = "https://files.pythonhosted.org/packages/2e/b0/279597e7a270e8d22623fea6c5d4eeac328e7d95c236ed51a2b884c54f70/jiter-0.10.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:e0588107ec8e11b6f5ef0e0d656fb2803ac6cf94a96b2b9fc675c0e3ab5e8644", size = 311617 },
+ { url = "https://files.pythonhosted.org/packages/91/e3/0916334936f356d605f54cc164af4060e3e7094364add445a3bc79335d46/jiter-0.10.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cafc4628b616dc32530c20ee53d71589816cf385dd9449633e910d596b1f5c8a", size = 318947 },
+ { url = "https://files.pythonhosted.org/packages/6a/8e/fd94e8c02d0e94539b7d669a7ebbd2776e51f329bb2c84d4385e8063a2ad/jiter-0.10.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:520ef6d981172693786a49ff5b09eda72a42e539f14788124a07530f785c3ad6", size = 344618 },
+ { url = "https://files.pythonhosted.org/packages/6f/b0/f9f0a2ec42c6e9c2e61c327824687f1e2415b767e1089c1d9135f43816bd/jiter-0.10.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:554dedfd05937f8fc45d17ebdf298fe7e0c77458232bcb73d9fbbf4c6455f5b3", size = 368829 },
+ { url = "https://files.pythonhosted.org/packages/e8/57/5bbcd5331910595ad53b9fd0c610392ac68692176f05ae48d6ce5c852967/jiter-0.10.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5bc299da7789deacf95f64052d97f75c16d4fc8c4c214a22bf8d859a4288a1c2", size = 491034 },
+ { url = "https://files.pythonhosted.org/packages/9b/be/c393df00e6e6e9e623a73551774449f2f23b6ec6a502a3297aeeece2c65a/jiter-0.10.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5161e201172de298a8a1baad95eb85db4fb90e902353b1f6a41d64ea64644e25", size = 388529 },
+ { url = "https://files.pythonhosted.org/packages/42/3e/df2235c54d365434c7f150b986a6e35f41ebdc2f95acea3036d99613025d/jiter-0.10.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2e2227db6ba93cb3e2bf67c87e594adde0609f146344e8207e8730364db27041", size = 350671 },
+ { url = "https://files.pythonhosted.org/packages/c6/77/71b0b24cbcc28f55ab4dbfe029f9a5b73aeadaba677843fc6dc9ed2b1d0a/jiter-0.10.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:15acb267ea5e2c64515574b06a8bf393fbfee6a50eb1673614aa45f4613c0cca", size = 390864 },
+ { url = "https://files.pythonhosted.org/packages/6a/d3/ef774b6969b9b6178e1d1e7a89a3bd37d241f3d3ec5f8deb37bbd203714a/jiter-0.10.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:901b92f2e2947dc6dfcb52fd624453862e16665ea909a08398dde19c0731b7f4", size = 522989 },
+ { url = "https://files.pythonhosted.org/packages/0c/41/9becdb1d8dd5d854142f45a9d71949ed7e87a8e312b0bede2de849388cb9/jiter-0.10.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:d0cb9a125d5a3ec971a094a845eadde2db0de85b33c9f13eb94a0c63d463879e", size = 513495 },
+ { url = "https://files.pythonhosted.org/packages/9c/36/3468e5a18238bdedae7c4d19461265b5e9b8e288d3f86cd89d00cbb48686/jiter-0.10.0-cp313-cp313-win32.whl", hash = "sha256:48a403277ad1ee208fb930bdf91745e4d2d6e47253eedc96e2559d1e6527006d", size = 211289 },
+ { url = "https://files.pythonhosted.org/packages/7e/07/1c96b623128bcb913706e294adb5f768fb7baf8db5e1338ce7b4ee8c78ef/jiter-0.10.0-cp313-cp313-win_amd64.whl", hash = "sha256:75f9eb72ecb640619c29bf714e78c9c46c9c4eaafd644bf78577ede459f330d4", size = 205074 },
+ { url = "https://files.pythonhosted.org/packages/54/46/caa2c1342655f57d8f0f2519774c6d67132205909c65e9aa8255e1d7b4f4/jiter-0.10.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:28ed2a4c05a1f32ef0e1d24c2611330219fed727dae01789f4a335617634b1ca", size = 318225 },
+ { url = "https://files.pythonhosted.org/packages/43/84/c7d44c75767e18946219ba2d703a5a32ab37b0bc21886a97bc6062e4da42/jiter-0.10.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:14a4c418b1ec86a195f1ca69da8b23e8926c752b685af665ce30777233dfe070", size = 350235 },
+ { url = "https://files.pythonhosted.org/packages/01/16/f5a0135ccd968b480daad0e6ab34b0c7c5ba3bc447e5088152696140dcb3/jiter-0.10.0-cp313-cp313t-win_amd64.whl", hash = "sha256:d7bfed2fe1fe0e4dda6ef682cee888ba444b21e7a6553e03252e4feb6cf0adca", size = 207278 },
+ { url = "https://files.pythonhosted.org/packages/1c/9b/1d646da42c3de6c2188fdaa15bce8ecb22b635904fc68be025e21249ba44/jiter-0.10.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:5e9251a5e83fab8d87799d3e1a46cb4b7f2919b895c6f4483629ed2446f66522", size = 310866 },
+ { url = "https://files.pythonhosted.org/packages/ad/0e/26538b158e8a7c7987e94e7aeb2999e2e82b1f9d2e1f6e9874ddf71ebda0/jiter-0.10.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:023aa0204126fe5b87ccbcd75c8a0d0261b9abdbbf46d55e7ae9f8e22424eeb8", size = 318772 },
+ { url = "https://files.pythonhosted.org/packages/7b/fb/d302893151caa1c2636d6574d213e4b34e31fd077af6050a9c5cbb42f6fb/jiter-0.10.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c189c4f1779c05f75fc17c0c1267594ed918996a231593a21a5ca5438445216", size = 344534 },
+ { url = "https://files.pythonhosted.org/packages/01/d8/5780b64a149d74e347c5128d82176eb1e3241b1391ac07935693466d6219/jiter-0.10.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:15720084d90d1098ca0229352607cd68256c76991f6b374af96f36920eae13c4", size = 369087 },
+ { url = "https://files.pythonhosted.org/packages/e8/5b/f235a1437445160e777544f3ade57544daf96ba7e96c1a5b24a6f7ac7004/jiter-0.10.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e4f2fb68e5f1cfee30e2b2a09549a00683e0fde4c6a2ab88c94072fc33cb7426", size = 490694 },
+ { url = "https://files.pythonhosted.org/packages/85/a9/9c3d4617caa2ff89cf61b41e83820c27ebb3f7b5fae8a72901e8cd6ff9be/jiter-0.10.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ce541693355fc6da424c08b7edf39a2895f58d6ea17d92cc2b168d20907dee12", size = 388992 },
+ { url = "https://files.pythonhosted.org/packages/68/b1/344fd14049ba5c94526540af7eb661871f9c54d5f5601ff41a959b9a0bbd/jiter-0.10.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31c50c40272e189d50006ad5c73883caabb73d4e9748a688b216e85a9a9ca3b9", size = 351723 },
+ { url = "https://files.pythonhosted.org/packages/41/89/4c0e345041186f82a31aee7b9d4219a910df672b9fef26f129f0cda07a29/jiter-0.10.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fa3402a2ff9815960e0372a47b75c76979d74402448509ccd49a275fa983ef8a", size = 392215 },
+ { url = "https://files.pythonhosted.org/packages/55/58/ee607863e18d3f895feb802154a2177d7e823a7103f000df182e0f718b38/jiter-0.10.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:1956f934dca32d7bb647ea21d06d93ca40868b505c228556d3373cbd255ce853", size = 522762 },
+ { url = "https://files.pythonhosted.org/packages/15/d0/9123fb41825490d16929e73c212de9a42913d68324a8ce3c8476cae7ac9d/jiter-0.10.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:fcedb049bdfc555e261d6f65a6abe1d5ad68825b7202ccb9692636c70fcced86", size = 513427 },
+ { url = "https://files.pythonhosted.org/packages/d8/b3/2bd02071c5a2430d0b70403a34411fc519c2f227da7b03da9ba6a956f931/jiter-0.10.0-cp314-cp314-win32.whl", hash = "sha256:ac509f7eccca54b2a29daeb516fb95b6f0bd0d0d8084efaf8ed5dfc7b9f0b357", size = 210127 },
+ { url = "https://files.pythonhosted.org/packages/03/0c/5fe86614ea050c3ecd728ab4035534387cd41e7c1855ef6c031f1ca93e3f/jiter-0.10.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5ed975b83a2b8639356151cef5c0d597c68376fc4922b45d0eb384ac058cfa00", size = 318527 },
+ { url = "https://files.pythonhosted.org/packages/b3/4a/4175a563579e884192ba6e81725fc0448b042024419be8d83aa8a80a3f44/jiter-0.10.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3aa96f2abba33dc77f79b4cf791840230375f9534e5fac927ccceb58c5e604a5", size = 354213 },
+ { url = "https://files.pythonhosted.org/packages/98/fd/aced428e2bd3c6c1132f67c5a708f9e7fd161d0ca8f8c5862b17b93cdf0a/jiter-0.10.0-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:bd6292a43c0fc09ce7c154ec0fa646a536b877d1e8f2f96c19707f65355b5a4d", size = 317665 },
+ { url = "https://files.pythonhosted.org/packages/b6/2e/47d42f15d53ed382aef8212a737101ae2720e3697a954f9b95af06d34e89/jiter-0.10.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:39de429dcaeb6808d75ffe9effefe96a4903c6a4b376b2f6d08d77c1aaee2f18", size = 312152 },
+ { url = "https://files.pythonhosted.org/packages/7b/02/aae834228ef4834fc18718724017995ace8da5f70aa1ec225b9bc2b2d7aa/jiter-0.10.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:52ce124f13a7a616fad3bb723f2bfb537d78239d1f7f219566dc52b6f2a9e48d", size = 346708 },
+ { url = "https://files.pythonhosted.org/packages/35/d4/6ff39dee2d0a9abd69d8a3832ce48a3aa644eed75e8515b5ff86c526ca9a/jiter-0.10.0-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:166f3606f11920f9a1746b2eea84fa2c0a5d50fd313c38bdea4edc072000b0af", size = 371360 },
+ { url = "https://files.pythonhosted.org/packages/a9/67/c749d962b4eb62445867ae4e64a543cbb5d63cc7d78ada274ac515500a7f/jiter-0.10.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:28dcecbb4ba402916034fc14eba7709f250c4d24b0c43fc94d187ee0580af181", size = 492105 },
+ { url = "https://files.pythonhosted.org/packages/f6/d3/8fe1b1bae5161f27b1891c256668f598fa4c30c0a7dacd668046a6215fca/jiter-0.10.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:86c5aa6910f9bebcc7bc4f8bc461aff68504388b43bfe5e5c0bd21efa33b52f4", size = 389577 },
+ { url = "https://files.pythonhosted.org/packages/ef/28/ecb19d789b4777898a4252bfaac35e3f8caf16c93becd58dcbaac0dc24ad/jiter-0.10.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ceeb52d242b315d7f1f74b441b6a167f78cea801ad7c11c36da77ff2d42e8a28", size = 353849 },
+ { url = "https://files.pythonhosted.org/packages/77/69/261f798f84790da6482ebd8c87ec976192b8c846e79444d0a2e0d33ebed8/jiter-0.10.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ff76d8887c8c8ee1e772274fcf8cc1071c2c58590d13e33bd12d02dc9a560397", size = 392029 },
+ { url = "https://files.pythonhosted.org/packages/cb/08/b8d15140d4d91f16faa2f5d416c1a71ab1bbe2b66c57197b692d04c0335f/jiter-0.10.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:a9be4d0fa2b79f7222a88aa488bd89e2ae0a0a5b189462a12def6ece2faa45f1", size = 524386 },
+ { url = "https://files.pythonhosted.org/packages/9b/1d/23c41765cc95c0e23ac492a88450d34bf0fd87a37218d1b97000bffe0f53/jiter-0.10.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9ab7fd8738094139b6c1ab1822d6f2000ebe41515c537235fd45dabe13ec9324", size = 515234 },
+ { url = "https://files.pythonhosted.org/packages/9f/14/381d8b151132e79790579819c3775be32820569f23806769658535fe467f/jiter-0.10.0-cp39-cp39-win32.whl", hash = "sha256:5f51e048540dd27f204ff4a87f5d79294ea0aa3aa552aca34934588cf27023cf", size = 211436 },
+ { url = "https://files.pythonhosted.org/packages/59/66/f23ae51dea8ee8ce429027b60008ca895d0fa0704f0c7fe5f09014a6cffb/jiter-0.10.0-cp39-cp39-win_amd64.whl", hash = "sha256:1b28302349dc65703a9e4ead16f163b1c339efffbe1049c30a44b001a2a4fff9", size = 208777 },
+]
+
+[[package]]
+name = "jmespath"
+version = "0.10.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz", hash = "sha256:b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9", size = 21607 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/07/cb/5f001272b6faeb23c1c9e0acc04d48eaaf5c862c17709d20e3469c6e0139/jmespath-0.10.0-py2.py3-none-any.whl", hash = "sha256:cdf6525904cc597730141d61b36f2e4b8ecc257c420fa2f4549bac2c2d0cb72f", size = 24489 },
+]
+
+[[package]]
+name = "jmespath"
+version = "1.0.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/00/2a/e867e8531cf3e36b41201936b7fa7ba7b5702dbef42922193f05c8976cd6/jmespath-1.0.1.tar.gz", hash = "sha256:90261b206d6defd58fdd5e85f478bf633a2901798906be2ad389150c5c60edbe", size = 25843 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/31/b4/b9b800c45527aadd64d5b442f9b932b00648617eb5d63d2c7a6587b7cafc/jmespath-1.0.1-py3-none-any.whl", hash = "sha256:02e2e4cc71b5bcab88332eebf907519190dd9e6e82107fa7f83b1003a6252980", size = 20256 },
+]
+
+[[package]]
+name = "joblib"
+version = "1.5.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/dc/fe/0f5a938c54105553436dbff7a61dc4fed4b1b2c98852f8833beaf4d5968f/joblib-1.5.1.tar.gz", hash = "sha256:f4f86e351f39fe3d0d32a9f2c3d8af1ee4cec285aafcb27003dda5205576b444", size = 330475 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7d/4f/1195bbac8e0c2acc5f740661631d8d750dc38d4a32b23ee5df3cde6f4e0d/joblib-1.5.1-py3-none-any.whl", hash = "sha256:4719a31f054c7d766948dcd83e9613686b27114f190f717cec7eaa2084f8a74a", size = 307746 },
+]
+
+[[package]]
+name = "jsonschema"
+version = "4.24.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "attrs" },
+ { name = "jsonschema-specifications" },
+ { name = "referencing" },
+ { name = "rpds-py" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/bf/d3/1cf5326b923a53515d8f3a2cd442e6d7e94fcc444716e879ea70a0ce3177/jsonschema-4.24.0.tar.gz", hash = "sha256:0b4e8069eb12aedfa881333004bccaec24ecef5a8a6a4b6df142b2cc9599d196", size = 353480 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/3d/023389198f69c722d039351050738d6755376c8fd343e91dc493ea485905/jsonschema-4.24.0-py3-none-any.whl", hash = "sha256:a462455f19f5faf404a7902952b6f0e3ce868f3ee09a359b05eca6673bd8412d", size = 88709 },
+]
+
+[[package]]
+name = "jsonschema-specifications"
+version = "2025.4.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "referencing" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/bf/ce/46fbd9c8119cfc3581ee5643ea49464d168028cfb5caff5fc0596d0cf914/jsonschema_specifications-2025.4.1.tar.gz", hash = "sha256:630159c9f4dbea161a6a2205c3011cc4f18ff381b189fff48bb39b9bf26ae608", size = 15513 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/01/0e/b27cdbaccf30b890c40ed1da9fd4a3593a5cf94dae54fb34f8a4b74fcd3f/jsonschema_specifications-2025.4.1-py3-none-any.whl", hash = "sha256:4653bffbd6584f7de83a67e0d620ef16900b390ddc7939d56684d6c81e33f1af", size = 18437 },
+]
+
+[[package]]
+name = "kiwisolver"
+version = "1.4.7"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/85/4d/2255e1c76304cbd60b48cee302b66d1dde4468dc5b1160e4b7cb43778f2a/kiwisolver-1.4.7.tar.gz", hash = "sha256:9893ff81bd7107f7b685d3017cc6583daadb4fc26e4a888350df530e41980a60", size = 97286 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/97/14/fc943dd65268a96347472b4fbe5dcc2f6f55034516f80576cd0dd3a8930f/kiwisolver-1.4.7-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:8a9c83f75223d5e48b0bc9cb1bf2776cf01563e00ade8775ffe13b0b6e1af3a6", size = 122440 },
+ { url = "https://files.pythonhosted.org/packages/1e/46/e68fed66236b69dd02fcdb506218c05ac0e39745d696d22709498896875d/kiwisolver-1.4.7-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:58370b1ffbd35407444d57057b57da5d6549d2d854fa30249771775c63b5fe17", size = 65758 },
+ { url = "https://files.pythonhosted.org/packages/ef/fa/65de49c85838681fc9cb05de2a68067a683717321e01ddafb5b8024286f0/kiwisolver-1.4.7-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:aa0abdf853e09aff551db11fce173e2177d00786c688203f52c87ad7fcd91ef9", size = 64311 },
+ { url = "https://files.pythonhosted.org/packages/42/9c/cc8d90f6ef550f65443bad5872ffa68f3dee36de4974768628bea7c14979/kiwisolver-1.4.7-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:8d53103597a252fb3ab8b5845af04c7a26d5e7ea8122303dd7a021176a87e8b9", size = 1637109 },
+ { url = "https://files.pythonhosted.org/packages/55/91/0a57ce324caf2ff5403edab71c508dd8f648094b18cfbb4c8cc0fde4a6ac/kiwisolver-1.4.7-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:88f17c5ffa8e9462fb79f62746428dd57b46eb931698e42e990ad63103f35e6c", size = 1617814 },
+ { url = "https://files.pythonhosted.org/packages/12/5d/c36140313f2510e20207708adf36ae4919416d697ee0236b0ddfb6fd1050/kiwisolver-1.4.7-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:88a9ca9c710d598fd75ee5de59d5bda2684d9db36a9f50b6125eaea3969c2599", size = 1400881 },
+ { url = "https://files.pythonhosted.org/packages/56/d0/786e524f9ed648324a466ca8df86298780ef2b29c25313d9a4f16992d3cf/kiwisolver-1.4.7-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f4d742cb7af1c28303a51b7a27aaee540e71bb8e24f68c736f6f2ffc82f2bf05", size = 1512972 },
+ { url = "https://files.pythonhosted.org/packages/67/5a/77851f2f201e6141d63c10a0708e996a1363efaf9e1609ad0441b343763b/kiwisolver-1.4.7-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e28c7fea2196bf4c2f8d46a0415c77a1c480cc0724722f23d7410ffe9842c407", size = 1444787 },
+ { url = "https://files.pythonhosted.org/packages/06/5f/1f5eaab84355885e224a6fc8d73089e8713dc7e91c121f00b9a1c58a2195/kiwisolver-1.4.7-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:e968b84db54f9d42046cf154e02911e39c0435c9801681e3fc9ce8a3c4130278", size = 2199212 },
+ { url = "https://files.pythonhosted.org/packages/b5/28/9152a3bfe976a0ae21d445415defc9d1cd8614b2910b7614b30b27a47270/kiwisolver-1.4.7-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:0c18ec74c0472de033e1bebb2911c3c310eef5649133dd0bedf2a169a1b269e5", size = 2346399 },
+ { url = "https://files.pythonhosted.org/packages/26/f6/453d1904c52ac3b400f4d5e240ac5fec25263716723e44be65f4d7149d13/kiwisolver-1.4.7-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8f0ea6da6d393d8b2e187e6a5e3fb81f5862010a40c3945e2c6d12ae45cfb2ad", size = 2308688 },
+ { url = "https://files.pythonhosted.org/packages/5a/9a/d4968499441b9ae187e81745e3277a8b4d7c60840a52dc9d535a7909fac3/kiwisolver-1.4.7-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:f106407dda69ae456dd1227966bf445b157ccc80ba0dff3802bb63f30b74e895", size = 2445493 },
+ { url = "https://files.pythonhosted.org/packages/07/c9/032267192e7828520dacb64dfdb1d74f292765f179e467c1cba97687f17d/kiwisolver-1.4.7-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:84ec80df401cfee1457063732d90022f93951944b5b58975d34ab56bb150dfb3", size = 2262191 },
+ { url = "https://files.pythonhosted.org/packages/6c/ad/db0aedb638a58b2951da46ddaeecf204be8b4f5454df020d850c7fa8dca8/kiwisolver-1.4.7-cp310-cp310-win32.whl", hash = "sha256:71bb308552200fb2c195e35ef05de12f0c878c07fc91c270eb3d6e41698c3bcc", size = 46644 },
+ { url = "https://files.pythonhosted.org/packages/12/ca/d0f7b7ffbb0be1e7c2258b53554efec1fd652921f10d7d85045aff93ab61/kiwisolver-1.4.7-cp310-cp310-win_amd64.whl", hash = "sha256:44756f9fd339de0fb6ee4f8c1696cfd19b2422e0d70b4cefc1cc7f1f64045a8c", size = 55877 },
+ { url = "https://files.pythonhosted.org/packages/97/6c/cfcc128672f47a3e3c0d918ecb67830600078b025bfc32d858f2e2d5c6a4/kiwisolver-1.4.7-cp310-cp310-win_arm64.whl", hash = "sha256:78a42513018c41c2ffd262eb676442315cbfe3c44eed82385c2ed043bc63210a", size = 48347 },
+ { url = "https://files.pythonhosted.org/packages/e9/44/77429fa0a58f941d6e1c58da9efe08597d2e86bf2b2cce6626834f49d07b/kiwisolver-1.4.7-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d2b0e12a42fb4e72d509fc994713d099cbb15ebf1103545e8a45f14da2dfca54", size = 122442 },
+ { url = "https://files.pythonhosted.org/packages/e5/20/8c75caed8f2462d63c7fd65e16c832b8f76cda331ac9e615e914ee80bac9/kiwisolver-1.4.7-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2a8781ac3edc42ea4b90bc23e7d37b665d89423818e26eb6df90698aa2287c95", size = 65762 },
+ { url = "https://files.pythonhosted.org/packages/f4/98/fe010f15dc7230f45bc4cf367b012d651367fd203caaa992fd1f5963560e/kiwisolver-1.4.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:46707a10836894b559e04b0fd143e343945c97fd170d69a2d26d640b4e297935", size = 64319 },
+ { url = "https://files.pythonhosted.org/packages/8b/1b/b5d618f4e58c0675654c1e5051bcf42c776703edb21c02b8c74135541f60/kiwisolver-1.4.7-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ef97b8df011141c9b0f6caf23b29379f87dd13183c978a30a3c546d2c47314cb", size = 1334260 },
+ { url = "https://files.pythonhosted.org/packages/b8/01/946852b13057a162a8c32c4c8d2e9ed79f0bb5d86569a40c0b5fb103e373/kiwisolver-1.4.7-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3ab58c12a2cd0fc769089e6d38466c46d7f76aced0a1f54c77652446733d2d02", size = 1426589 },
+ { url = "https://files.pythonhosted.org/packages/70/d1/c9f96df26b459e15cf8a965304e6e6f4eb291e0f7a9460b4ad97b047561e/kiwisolver-1.4.7-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:803b8e1459341c1bb56d1c5c010406d5edec8a0713a0945851290a7930679b51", size = 1541080 },
+ { url = "https://files.pythonhosted.org/packages/d3/73/2686990eb8b02d05f3de759d6a23a4ee7d491e659007dd4c075fede4b5d0/kiwisolver-1.4.7-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f9a9e8a507420fe35992ee9ecb302dab68550dedc0da9e2880dd88071c5fb052", size = 1470049 },
+ { url = "https://files.pythonhosted.org/packages/a7/4b/2db7af3ed3af7c35f388d5f53c28e155cd402a55432d800c543dc6deb731/kiwisolver-1.4.7-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:18077b53dc3bb490e330669a99920c5e6a496889ae8c63b58fbc57c3d7f33a18", size = 1426376 },
+ { url = "https://files.pythonhosted.org/packages/05/83/2857317d04ea46dc5d115f0df7e676997bbd968ced8e2bd6f7f19cfc8d7f/kiwisolver-1.4.7-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6af936f79086a89b3680a280c47ea90b4df7047b5bdf3aa5c524bbedddb9e545", size = 2222231 },
+ { url = "https://files.pythonhosted.org/packages/0d/b5/866f86f5897cd4ab6d25d22e403404766a123f138bd6a02ecb2cdde52c18/kiwisolver-1.4.7-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3abc5b19d24af4b77d1598a585b8a719beb8569a71568b66f4ebe1fb0449460b", size = 2368634 },
+ { url = "https://files.pythonhosted.org/packages/c1/ee/73de8385403faba55f782a41260210528fe3273d0cddcf6d51648202d6d0/kiwisolver-1.4.7-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:933d4de052939d90afbe6e9d5273ae05fb836cc86c15b686edd4b3560cc0ee36", size = 2329024 },
+ { url = "https://files.pythonhosted.org/packages/a1/e7/cd101d8cd2cdfaa42dc06c433df17c8303d31129c9fdd16c0ea37672af91/kiwisolver-1.4.7-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:65e720d2ab2b53f1f72fb5da5fb477455905ce2c88aaa671ff0a447c2c80e8e3", size = 2468484 },
+ { url = "https://files.pythonhosted.org/packages/e1/72/84f09d45a10bc57a40bb58b81b99d8f22b58b2040c912b7eb97ebf625bf2/kiwisolver-1.4.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3bf1ed55088f214ba6427484c59553123fdd9b218a42bbc8c6496d6754b1e523", size = 2284078 },
+ { url = "https://files.pythonhosted.org/packages/d2/d4/71828f32b956612dc36efd7be1788980cb1e66bfb3706e6dec9acad9b4f9/kiwisolver-1.4.7-cp311-cp311-win32.whl", hash = "sha256:4c00336b9dd5ad96d0a558fd18a8b6f711b7449acce4c157e7343ba92dd0cf3d", size = 46645 },
+ { url = "https://files.pythonhosted.org/packages/a1/65/d43e9a20aabcf2e798ad1aff6c143ae3a42cf506754bcb6a7ed8259c8425/kiwisolver-1.4.7-cp311-cp311-win_amd64.whl", hash = "sha256:929e294c1ac1e9f615c62a4e4313ca1823ba37326c164ec720a803287c4c499b", size = 56022 },
+ { url = "https://files.pythonhosted.org/packages/35/b3/9f75a2e06f1b4ca00b2b192bc2b739334127d27f1d0625627ff8479302ba/kiwisolver-1.4.7-cp311-cp311-win_arm64.whl", hash = "sha256:e33e8fbd440c917106b237ef1a2f1449dfbb9b6f6e1ce17c94cd6a1e0d438376", size = 48536 },
+ { url = "https://files.pythonhosted.org/packages/97/9c/0a11c714cf8b6ef91001c8212c4ef207f772dd84540104952c45c1f0a249/kiwisolver-1.4.7-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:5360cc32706dab3931f738d3079652d20982511f7c0ac5711483e6eab08efff2", size = 121808 },
+ { url = "https://files.pythonhosted.org/packages/f2/d8/0fe8c5f5d35878ddd135f44f2af0e4e1d379e1c7b0716f97cdcb88d4fd27/kiwisolver-1.4.7-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:942216596dc64ddb25adb215c3c783215b23626f8d84e8eff8d6d45c3f29f75a", size = 65531 },
+ { url = "https://files.pythonhosted.org/packages/80/c5/57fa58276dfdfa612241d640a64ca2f76adc6ffcebdbd135b4ef60095098/kiwisolver-1.4.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:48b571ecd8bae15702e4f22d3ff6a0f13e54d3d00cd25216d5e7f658242065ee", size = 63894 },
+ { url = "https://files.pythonhosted.org/packages/8b/e9/26d3edd4c4ad1c5b891d8747a4f81b1b0aba9fb9721de6600a4adc09773b/kiwisolver-1.4.7-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ad42ba922c67c5f219097b28fae965e10045ddf145d2928bfac2eb2e17673640", size = 1369296 },
+ { url = "https://files.pythonhosted.org/packages/b6/67/3f4850b5e6cffb75ec40577ddf54f7b82b15269cc5097ff2e968ee32ea7d/kiwisolver-1.4.7-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:612a10bdae23404a72941a0fc8fa2660c6ea1217c4ce0dbcab8a8f6543ea9e7f", size = 1461450 },
+ { url = "https://files.pythonhosted.org/packages/52/be/86cbb9c9a315e98a8dc6b1d23c43cffd91d97d49318854f9c37b0e41cd68/kiwisolver-1.4.7-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9e838bba3a3bac0fe06d849d29772eb1afb9745a59710762e4ba3f4cb8424483", size = 1579168 },
+ { url = "https://files.pythonhosted.org/packages/0f/00/65061acf64bd5fd34c1f4ae53f20b43b0a017a541f242a60b135b9d1e301/kiwisolver-1.4.7-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:22f499f6157236c19f4bbbd472fa55b063db77a16cd74d49afe28992dff8c258", size = 1507308 },
+ { url = "https://files.pythonhosted.org/packages/21/e4/c0b6746fd2eb62fe702118b3ca0cb384ce95e1261cfada58ff693aeec08a/kiwisolver-1.4.7-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:693902d433cf585133699972b6d7c42a8b9f8f826ebcaf0132ff55200afc599e", size = 1464186 },
+ { url = "https://files.pythonhosted.org/packages/0a/0f/529d0a9fffb4d514f2782c829b0b4b371f7f441d61aa55f1de1c614c4ef3/kiwisolver-1.4.7-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4e77f2126c3e0b0d055f44513ed349038ac180371ed9b52fe96a32aa071a5107", size = 2247877 },
+ { url = "https://files.pythonhosted.org/packages/d1/e1/66603ad779258843036d45adcbe1af0d1a889a07af4635f8b4ec7dccda35/kiwisolver-1.4.7-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:657a05857bda581c3656bfc3b20e353c232e9193eb167766ad2dc58b56504948", size = 2404204 },
+ { url = "https://files.pythonhosted.org/packages/8d/61/de5fb1ca7ad1f9ab7970e340a5b833d735df24689047de6ae71ab9d8d0e7/kiwisolver-1.4.7-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4bfa75a048c056a411f9705856abfc872558e33c055d80af6a380e3658766038", size = 2352461 },
+ { url = "https://files.pythonhosted.org/packages/ba/d2/0edc00a852e369827f7e05fd008275f550353f1f9bcd55db9363d779fc63/kiwisolver-1.4.7-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:34ea1de54beef1c104422d210c47c7d2a4999bdecf42c7b5718fbe59a4cac383", size = 2501358 },
+ { url = "https://files.pythonhosted.org/packages/84/15/adc15a483506aec6986c01fb7f237c3aec4d9ed4ac10b756e98a76835933/kiwisolver-1.4.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:90da3b5f694b85231cf93586dad5e90e2d71b9428f9aad96952c99055582f520", size = 2314119 },
+ { url = "https://files.pythonhosted.org/packages/36/08/3a5bb2c53c89660863a5aa1ee236912269f2af8762af04a2e11df851d7b2/kiwisolver-1.4.7-cp312-cp312-win32.whl", hash = "sha256:18e0cca3e008e17fe9b164b55735a325140a5a35faad8de92dd80265cd5eb80b", size = 46367 },
+ { url = "https://files.pythonhosted.org/packages/19/93/c05f0a6d825c643779fc3c70876bff1ac221f0e31e6f701f0e9578690d70/kiwisolver-1.4.7-cp312-cp312-win_amd64.whl", hash = "sha256:58cb20602b18f86f83a5c87d3ee1c766a79c0d452f8def86d925e6c60fbf7bfb", size = 55884 },
+ { url = "https://files.pythonhosted.org/packages/d2/f9/3828d8f21b6de4279f0667fb50a9f5215e6fe57d5ec0d61905914f5b6099/kiwisolver-1.4.7-cp312-cp312-win_arm64.whl", hash = "sha256:f5a8b53bdc0b3961f8b6125e198617c40aeed638b387913bf1ce78afb1b0be2a", size = 48528 },
+ { url = "https://files.pythonhosted.org/packages/c4/06/7da99b04259b0f18b557a4effd1b9c901a747f7fdd84cf834ccf520cb0b2/kiwisolver-1.4.7-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2e6039dcbe79a8e0f044f1c39db1986a1b8071051efba3ee4d74f5b365f5226e", size = 121913 },
+ { url = "https://files.pythonhosted.org/packages/97/f5/b8a370d1aa593c17882af0a6f6755aaecd643640c0ed72dcfd2eafc388b9/kiwisolver-1.4.7-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a1ecf0ac1c518487d9d23b1cd7139a6a65bc460cd101ab01f1be82ecf09794b6", size = 65627 },
+ { url = "https://files.pythonhosted.org/packages/2a/fc/6c0374f7503522539e2d4d1b497f5ebad3f8ed07ab51aed2af988dd0fb65/kiwisolver-1.4.7-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7ab9ccab2b5bd5702ab0803676a580fffa2aa178c2badc5557a84cc943fcf750", size = 63888 },
+ { url = "https://files.pythonhosted.org/packages/bf/3e/0b7172793d0f41cae5c923492da89a2ffcd1adf764c16159ca047463ebd3/kiwisolver-1.4.7-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f816dd2277f8d63d79f9c8473a79fe54047bc0467754962840782c575522224d", size = 1369145 },
+ { url = "https://files.pythonhosted.org/packages/77/92/47d050d6f6aced2d634258123f2688fbfef8ded3c5baf2c79d94d91f1f58/kiwisolver-1.4.7-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf8bcc23ceb5a1b624572a1623b9f79d2c3b337c8c455405ef231933a10da379", size = 1461448 },
+ { url = "https://files.pythonhosted.org/packages/9c/1b/8f80b18e20b3b294546a1adb41701e79ae21915f4175f311a90d042301cf/kiwisolver-1.4.7-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dea0bf229319828467d7fca8c7c189780aa9ff679c94539eed7532ebe33ed37c", size = 1578750 },
+ { url = "https://files.pythonhosted.org/packages/a4/fe/fe8e72f3be0a844f257cadd72689c0848c6d5c51bc1d60429e2d14ad776e/kiwisolver-1.4.7-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7c06a4c7cf15ec739ce0e5971b26c93638730090add60e183530d70848ebdd34", size = 1507175 },
+ { url = "https://files.pythonhosted.org/packages/39/fa/cdc0b6105d90eadc3bee525fecc9179e2b41e1ce0293caaf49cb631a6aaf/kiwisolver-1.4.7-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:913983ad2deb14e66d83c28b632fd35ba2b825031f2fa4ca29675e665dfecbe1", size = 1463963 },
+ { url = "https://files.pythonhosted.org/packages/6e/5c/0c03c4e542720c6177d4f408e56d1c8315899db72d46261a4e15b8b33a41/kiwisolver-1.4.7-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5337ec7809bcd0f424c6b705ecf97941c46279cf5ed92311782c7c9c2026f07f", size = 2248220 },
+ { url = "https://files.pythonhosted.org/packages/3d/ee/55ef86d5a574f4e767df7da3a3a7ff4954c996e12d4fbe9c408170cd7dcc/kiwisolver-1.4.7-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:4c26ed10c4f6fa6ddb329a5120ba3b6db349ca192ae211e882970bfc9d91420b", size = 2404463 },
+ { url = "https://files.pythonhosted.org/packages/0f/6d/73ad36170b4bff4825dc588acf4f3e6319cb97cd1fb3eb04d9faa6b6f212/kiwisolver-1.4.7-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c619b101e6de2222c1fcb0531e1b17bbffbe54294bfba43ea0d411d428618c27", size = 2352842 },
+ { url = "https://files.pythonhosted.org/packages/0b/16/fa531ff9199d3b6473bb4d0f47416cdb08d556c03b8bc1cccf04e756b56d/kiwisolver-1.4.7-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:073a36c8273647592ea332e816e75ef8da5c303236ec0167196793eb1e34657a", size = 2501635 },
+ { url = "https://files.pythonhosted.org/packages/78/7e/aa9422e78419db0cbe75fb86d8e72b433818f2e62e2e394992d23d23a583/kiwisolver-1.4.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3ce6b2b0231bda412463e152fc18335ba32faf4e8c23a754ad50ffa70e4091ee", size = 2314556 },
+ { url = "https://files.pythonhosted.org/packages/a8/b2/15f7f556df0a6e5b3772a1e076a9d9f6c538ce5f05bd590eca8106508e06/kiwisolver-1.4.7-cp313-cp313-win32.whl", hash = "sha256:f4c9aee212bc89d4e13f58be11a56cc8036cabad119259d12ace14b34476fd07", size = 46364 },
+ { url = "https://files.pythonhosted.org/packages/0b/db/32e897e43a330eee8e4770bfd2737a9584b23e33587a0812b8e20aac38f7/kiwisolver-1.4.7-cp313-cp313-win_amd64.whl", hash = "sha256:8a3ec5aa8e38fc4c8af308917ce12c536f1c88452ce554027e55b22cbbfbff76", size = 55887 },
+ { url = "https://files.pythonhosted.org/packages/c8/a4/df2bdca5270ca85fd25253049eb6708d4127be2ed0e5c2650217450b59e9/kiwisolver-1.4.7-cp313-cp313-win_arm64.whl", hash = "sha256:76c8094ac20ec259471ac53e774623eb62e6e1f56cd8690c67ce6ce4fcb05650", size = 48530 },
+ { url = "https://files.pythonhosted.org/packages/11/88/37ea0ea64512997b13d69772db8dcdc3bfca5442cda3a5e4bb943652ee3e/kiwisolver-1.4.7-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:3f9362ecfca44c863569d3d3c033dbe8ba452ff8eed6f6b5806382741a1334bd", size = 122449 },
+ { url = "https://files.pythonhosted.org/packages/4e/45/5a5c46078362cb3882dcacad687c503089263c017ca1241e0483857791eb/kiwisolver-1.4.7-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:e8df2eb9b2bac43ef8b082e06f750350fbbaf2887534a5be97f6cf07b19d9583", size = 65757 },
+ { url = "https://files.pythonhosted.org/packages/8a/be/a6ae58978772f685d48dd2e84460937761c53c4bbd84e42b0336473d9775/kiwisolver-1.4.7-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f32d6edbc638cde7652bd690c3e728b25332acbadd7cad670cc4a02558d9c417", size = 64312 },
+ { url = "https://files.pythonhosted.org/packages/f4/04/18ef6f452d311e1e1eb180c9bf5589187fa1f042db877e6fe443ef10099c/kiwisolver-1.4.7-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:e2e6c39bd7b9372b0be21456caab138e8e69cc0fc1190a9dfa92bd45a1e6e904", size = 1626966 },
+ { url = "https://files.pythonhosted.org/packages/21/b1/40655f6c3fa11ce740e8a964fa8e4c0479c87d6a7944b95af799c7a55dfe/kiwisolver-1.4.7-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:dda56c24d869b1193fcc763f1284b9126550eaf84b88bbc7256e15028f19188a", size = 1607044 },
+ { url = "https://files.pythonhosted.org/packages/fd/93/af67dbcfb9b3323bbd2c2db1385a7139d8f77630e4a37bb945b57188eb2d/kiwisolver-1.4.7-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79849239c39b5e1fd906556c474d9b0439ea6792b637511f3fe3a41158d89ca8", size = 1391879 },
+ { url = "https://files.pythonhosted.org/packages/40/6f/d60770ef98e77b365d96061d090c0cd9e23418121c55fff188fa4bdf0b54/kiwisolver-1.4.7-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5e3bc157fed2a4c02ec468de4ecd12a6e22818d4f09cde2c31ee3226ffbefab2", size = 1504751 },
+ { url = "https://files.pythonhosted.org/packages/fa/3a/5f38667d313e983c432f3fcd86932177519ed8790c724e07d77d1de0188a/kiwisolver-1.4.7-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3da53da805b71e41053dc670f9a820d1157aae77b6b944e08024d17bcd51ef88", size = 1436990 },
+ { url = "https://files.pythonhosted.org/packages/cb/3b/1520301a47326e6a6043b502647e42892be33b3f051e9791cc8bb43f1a32/kiwisolver-1.4.7-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:8705f17dfeb43139a692298cb6637ee2e59c0194538153e83e9ee0c75c2eddde", size = 2191122 },
+ { url = "https://files.pythonhosted.org/packages/cf/c4/eb52da300c166239a2233f1f9c4a1b767dfab98fae27681bfb7ea4873cb6/kiwisolver-1.4.7-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:82a5c2f4b87c26bb1a0ef3d16b5c4753434633b83d365cc0ddf2770c93829e3c", size = 2338126 },
+ { url = "https://files.pythonhosted.org/packages/1a/cb/42b92fd5eadd708dd9107c089e817945500685f3437ce1fd387efebc6d6e/kiwisolver-1.4.7-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:ce8be0466f4c0d585cdb6c1e2ed07232221df101a4c6f28821d2aa754ca2d9e2", size = 2298313 },
+ { url = "https://files.pythonhosted.org/packages/4f/eb/be25aa791fe5fc75a8b1e0c965e00f942496bc04635c9aae8035f6b76dcd/kiwisolver-1.4.7-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:409afdfe1e2e90e6ee7fc896f3df9a7fec8e793e58bfa0d052c8a82f99c37abb", size = 2437784 },
+ { url = "https://files.pythonhosted.org/packages/c5/22/30a66be7f3368d76ff95689e1c2e28d382383952964ab15330a15d8bfd03/kiwisolver-1.4.7-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:5b9c3f4ee0b9a439d2415012bd1b1cc2df59e4d6a9939f4d669241d30b414327", size = 2253988 },
+ { url = "https://files.pythonhosted.org/packages/35/d3/5f2ecb94b5211c8a04f218a76133cc8d6d153b0f9cd0b45fad79907f0689/kiwisolver-1.4.7-cp39-cp39-win32.whl", hash = "sha256:a79ae34384df2b615eefca647a2873842ac3b596418032bef9a7283675962644", size = 46980 },
+ { url = "https://files.pythonhosted.org/packages/ef/17/cd10d020578764ea91740204edc6b3236ed8106228a46f568d716b11feb2/kiwisolver-1.4.7-cp39-cp39-win_amd64.whl", hash = "sha256:cf0438b42121a66a3a667de17e779330fc0f20b0d97d59d2f2121e182b0505e4", size = 55847 },
+ { url = "https://files.pythonhosted.org/packages/91/84/32232502020bd78d1d12be7afde15811c64a95ed1f606c10456db4e4c3ac/kiwisolver-1.4.7-cp39-cp39-win_arm64.whl", hash = "sha256:764202cc7e70f767dab49e8df52c7455e8de0df5d858fa801a11aa0d882ccf3f", size = 48494 },
+ { url = "https://files.pythonhosted.org/packages/ac/59/741b79775d67ab67ced9bb38552da688c0305c16e7ee24bba7a2be253fb7/kiwisolver-1.4.7-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:94252291e3fe68001b1dd747b4c0b3be12582839b95ad4d1b641924d68fd4643", size = 59491 },
+ { url = "https://files.pythonhosted.org/packages/58/cc/fb239294c29a5656e99e3527f7369b174dd9cc7c3ef2dea7cb3c54a8737b/kiwisolver-1.4.7-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b7dfa3b546da08a9f622bb6becdb14b3e24aaa30adba66749d38f3cc7ea9706", size = 57648 },
+ { url = "https://files.pythonhosted.org/packages/3b/ef/2f009ac1f7aab9f81efb2d837301d255279d618d27b6015780115ac64bdd/kiwisolver-1.4.7-pp310-pypy310_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bd3de6481f4ed8b734da5df134cd5a6a64fe32124fe83dde1e5b5f29fe30b1e6", size = 84257 },
+ { url = "https://files.pythonhosted.org/packages/81/e1/c64f50987f85b68b1c52b464bb5bf73e71570c0f7782d626d1eb283ad620/kiwisolver-1.4.7-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a91b5f9f1205845d488c928e8570dcb62b893372f63b8b6e98b863ebd2368ff2", size = 80906 },
+ { url = "https://files.pythonhosted.org/packages/fd/71/1687c5c0a0be2cee39a5c9c389e546f9c6e215e46b691d00d9f646892083/kiwisolver-1.4.7-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40fa14dbd66b8b8f470d5fc79c089a66185619d31645f9b0773b88b19f7223c4", size = 79951 },
+ { url = "https://files.pythonhosted.org/packages/ea/8b/d7497df4a1cae9367adf21665dd1f896c2a7aeb8769ad77b662c5e2bcce7/kiwisolver-1.4.7-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:eb542fe7933aa09d8d8f9d9097ef37532a7df6497819d16efe4359890a2f417a", size = 55715 },
+ { url = "https://files.pythonhosted.org/packages/d5/df/ce37d9b26f07ab90880923c94d12a6ff4d27447096b4c849bfc4339ccfdf/kiwisolver-1.4.7-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:8b01aac285f91ca889c800042c35ad3b239e704b150cfd3382adfc9dcc780e39", size = 58666 },
+ { url = "https://files.pythonhosted.org/packages/b0/d3/e4b04f43bc629ac8e186b77b2b1a251cdfa5b7610fa189dc0db622672ce6/kiwisolver-1.4.7-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:48be928f59a1f5c8207154f935334d374e79f2b5d212826307d072595ad76a2e", size = 57088 },
+ { url = "https://files.pythonhosted.org/packages/30/1c/752df58e2d339e670a535514d2db4fe8c842ce459776b8080fbe08ebb98e/kiwisolver-1.4.7-pp39-pypy39_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f37cfe618a117e50d8c240555331160d73d0411422b59b5ee217843d7b693608", size = 84321 },
+ { url = "https://files.pythonhosted.org/packages/f0/f8/fe6484e847bc6e238ec9f9828089fb2c0bb53f2f5f3a79351fde5b565e4f/kiwisolver-1.4.7-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:599b5c873c63a1f6ed7eead644a8a380cfbdf5db91dcb6f85707aaab213b1674", size = 80776 },
+ { url = "https://files.pythonhosted.org/packages/9b/57/d7163c0379f250ef763aba85330a19feefb5ce6cb541ade853aaba881524/kiwisolver-1.4.7-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:801fa7802e5cfabe3ab0c81a34c323a319b097dfb5004be950482d882f3d7225", size = 79984 },
+ { url = "https://files.pythonhosted.org/packages/8c/95/4a103776c265d13b3d2cd24fb0494d4e04ea435a8ef97e1b2c026d43250b/kiwisolver-1.4.7-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:0c6c43471bc764fad4bc99c5c2d6d16a676b1abf844ca7c8702bdae92df01ee0", size = 55811 },
+]
+
+[[package]]
+name = "kiwisolver"
+version = "1.4.8"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/82/59/7c91426a8ac292e1cdd53a63b6d9439abd573c875c3f92c146767dd33faf/kiwisolver-1.4.8.tar.gz", hash = "sha256:23d5f023bdc8c7e54eb65f03ca5d5bb25b601eac4d7f1a042888a1f45237987e", size = 97538 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/47/5f/4d8e9e852d98ecd26cdf8eaf7ed8bc33174033bba5e07001b289f07308fd/kiwisolver-1.4.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:88c6f252f6816a73b1f8c904f7bbe02fd67c09a69f7cb8a0eecdbf5ce78e63db", size = 124623 },
+ { url = "https://files.pythonhosted.org/packages/1d/70/7f5af2a18a76fe92ea14675f8bd88ce53ee79e37900fa5f1a1d8e0b42998/kiwisolver-1.4.8-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c72941acb7b67138f35b879bbe85be0f6c6a70cab78fe3ef6db9c024d9223e5b", size = 66720 },
+ { url = "https://files.pythonhosted.org/packages/c6/13/e15f804a142353aefd089fadc8f1d985561a15358c97aca27b0979cb0785/kiwisolver-1.4.8-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ce2cf1e5688edcb727fdf7cd1bbd0b6416758996826a8be1d958f91880d0809d", size = 65413 },
+ { url = "https://files.pythonhosted.org/packages/ce/6d/67d36c4d2054e83fb875c6b59d0809d5c530de8148846b1370475eeeece9/kiwisolver-1.4.8-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:c8bf637892dc6e6aad2bc6d4d69d08764166e5e3f69d469e55427b6ac001b19d", size = 1650826 },
+ { url = "https://files.pythonhosted.org/packages/de/c6/7b9bb8044e150d4d1558423a1568e4f227193662a02231064e3824f37e0a/kiwisolver-1.4.8-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:034d2c891f76bd3edbdb3ea11140d8510dca675443da7304205a2eaa45d8334c", size = 1628231 },
+ { url = "https://files.pythonhosted.org/packages/b6/38/ad10d437563063eaaedbe2c3540a71101fc7fb07a7e71f855e93ea4de605/kiwisolver-1.4.8-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d47b28d1dfe0793d5e96bce90835e17edf9a499b53969b03c6c47ea5985844c3", size = 1408938 },
+ { url = "https://files.pythonhosted.org/packages/52/ce/c0106b3bd7f9e665c5f5bc1e07cc95b5dabd4e08e3dad42dbe2faad467e7/kiwisolver-1.4.8-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:eb158fe28ca0c29f2260cca8c43005329ad58452c36f0edf298204de32a9a3ed", size = 1422799 },
+ { url = "https://files.pythonhosted.org/packages/d0/87/efb704b1d75dc9758087ba374c0f23d3254505edaedd09cf9d247f7878b9/kiwisolver-1.4.8-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d5536185fce131780ebd809f8e623bf4030ce1b161353166c49a3c74c287897f", size = 1354362 },
+ { url = "https://files.pythonhosted.org/packages/eb/b3/fd760dc214ec9a8f208b99e42e8f0130ff4b384eca8b29dd0efc62052176/kiwisolver-1.4.8-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:369b75d40abedc1da2c1f4de13f3482cb99e3237b38726710f4a793432b1c5ff", size = 2222695 },
+ { url = "https://files.pythonhosted.org/packages/a2/09/a27fb36cca3fc01700687cc45dae7a6a5f8eeb5f657b9f710f788748e10d/kiwisolver-1.4.8-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:641f2ddf9358c80faa22e22eb4c9f54bd3f0e442e038728f500e3b978d00aa7d", size = 2370802 },
+ { url = "https://files.pythonhosted.org/packages/3d/c3/ba0a0346db35fe4dc1f2f2cf8b99362fbb922d7562e5f911f7ce7a7b60fa/kiwisolver-1.4.8-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:d561d2d8883e0819445cfe58d7ddd673e4015c3c57261d7bdcd3710d0d14005c", size = 2334646 },
+ { url = "https://files.pythonhosted.org/packages/41/52/942cf69e562f5ed253ac67d5c92a693745f0bed3c81f49fc0cbebe4d6b00/kiwisolver-1.4.8-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:1732e065704b47c9afca7ffa272f845300a4eb959276bf6970dc07265e73b605", size = 2467260 },
+ { url = "https://files.pythonhosted.org/packages/32/26/2d9668f30d8a494b0411d4d7d4ea1345ba12deb6a75274d58dd6ea01e951/kiwisolver-1.4.8-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:bcb1ebc3547619c3b58a39e2448af089ea2ef44b37988caf432447374941574e", size = 2288633 },
+ { url = "https://files.pythonhosted.org/packages/98/99/0dd05071654aa44fe5d5e350729961e7bb535372935a45ac89a8924316e6/kiwisolver-1.4.8-cp310-cp310-win_amd64.whl", hash = "sha256:89c107041f7b27844179ea9c85d6da275aa55ecf28413e87624d033cf1f6b751", size = 71885 },
+ { url = "https://files.pythonhosted.org/packages/6c/fc/822e532262a97442989335394d441cd1d0448c2e46d26d3e04efca84df22/kiwisolver-1.4.8-cp310-cp310-win_arm64.whl", hash = "sha256:b5773efa2be9eb9fcf5415ea3ab70fc785d598729fd6057bea38d539ead28271", size = 65175 },
+ { url = "https://files.pythonhosted.org/packages/da/ed/c913ee28936c371418cb167b128066ffb20bbf37771eecc2c97edf8a6e4c/kiwisolver-1.4.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a4d3601908c560bdf880f07d94f31d734afd1bb71e96585cace0e38ef44c6d84", size = 124635 },
+ { url = "https://files.pythonhosted.org/packages/4c/45/4a7f896f7467aaf5f56ef093d1f329346f3b594e77c6a3c327b2d415f521/kiwisolver-1.4.8-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:856b269c4d28a5c0d5e6c1955ec36ebfd1651ac00e1ce0afa3e28da95293b561", size = 66717 },
+ { url = "https://files.pythonhosted.org/packages/5f/b4/c12b3ac0852a3a68f94598d4c8d569f55361beef6159dce4e7b624160da2/kiwisolver-1.4.8-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c2b9a96e0f326205af81a15718a9073328df1173a2619a68553decb7097fd5d7", size = 65413 },
+ { url = "https://files.pythonhosted.org/packages/a9/98/1df4089b1ed23d83d410adfdc5947245c753bddfbe06541c4aae330e9e70/kiwisolver-1.4.8-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c5020c83e8553f770cb3b5fc13faac40f17e0b205bd237aebd21d53d733adb03", size = 1343994 },
+ { url = "https://files.pythonhosted.org/packages/8d/bf/b4b169b050c8421a7c53ea1ea74e4ef9c335ee9013216c558a047f162d20/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dace81d28c787956bfbfbbfd72fdcef014f37d9b48830829e488fdb32b49d954", size = 1434804 },
+ { url = "https://files.pythonhosted.org/packages/66/5a/e13bd341fbcf73325ea60fdc8af752addf75c5079867af2e04cc41f34434/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:11e1022b524bd48ae56c9b4f9296bce77e15a2e42a502cceba602f804b32bb79", size = 1450690 },
+ { url = "https://files.pythonhosted.org/packages/9b/4f/5955dcb376ba4a830384cc6fab7d7547bd6759fe75a09564910e9e3bb8ea/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3b9b4d2892fefc886f30301cdd80debd8bb01ecdf165a449eb6e78f79f0fabd6", size = 1376839 },
+ { url = "https://files.pythonhosted.org/packages/3a/97/5edbed69a9d0caa2e4aa616ae7df8127e10f6586940aa683a496c2c280b9/kiwisolver-1.4.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a96c0e790ee875d65e340ab383700e2b4891677b7fcd30a699146f9384a2bb0", size = 1435109 },
+ { url = "https://files.pythonhosted.org/packages/13/fc/e756382cb64e556af6c1809a1bbb22c141bbc2445049f2da06b420fe52bf/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:23454ff084b07ac54ca8be535f4174170c1094a4cff78fbae4f73a4bcc0d4dab", size = 2245269 },
+ { url = "https://files.pythonhosted.org/packages/76/15/e59e45829d7f41c776d138245cabae6515cb4eb44b418f6d4109c478b481/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:87b287251ad6488e95b4f0b4a79a6d04d3ea35fde6340eb38fbd1ca9cd35bbbc", size = 2393468 },
+ { url = "https://files.pythonhosted.org/packages/e9/39/483558c2a913ab8384d6e4b66a932406f87c95a6080112433da5ed668559/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:b21dbe165081142b1232a240fc6383fd32cdd877ca6cc89eab93e5f5883e1c25", size = 2355394 },
+ { url = "https://files.pythonhosted.org/packages/01/aa/efad1fbca6570a161d29224f14b082960c7e08268a133fe5dc0f6906820e/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:768cade2c2df13db52475bd28d3a3fac8c9eff04b0e9e2fda0f3760f20b3f7fc", size = 2490901 },
+ { url = "https://files.pythonhosted.org/packages/c9/4f/15988966ba46bcd5ab9d0c8296914436720dd67fca689ae1a75b4ec1c72f/kiwisolver-1.4.8-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d47cfb2650f0e103d4bf68b0b5804c68da97272c84bb12850d877a95c056bd67", size = 2312306 },
+ { url = "https://files.pythonhosted.org/packages/2d/27/bdf1c769c83f74d98cbc34483a972f221440703054894a37d174fba8aa68/kiwisolver-1.4.8-cp311-cp311-win_amd64.whl", hash = "sha256:ed33ca2002a779a2e20eeb06aea7721b6e47f2d4b8a8ece979d8ba9e2a167e34", size = 71966 },
+ { url = "https://files.pythonhosted.org/packages/4a/c9/9642ea855604aeb2968a8e145fc662edf61db7632ad2e4fb92424be6b6c0/kiwisolver-1.4.8-cp311-cp311-win_arm64.whl", hash = "sha256:16523b40aab60426ffdebe33ac374457cf62863e330a90a0383639ce14bf44b2", size = 65311 },
+ { url = "https://files.pythonhosted.org/packages/fc/aa/cea685c4ab647f349c3bc92d2daf7ae34c8e8cf405a6dcd3a497f58a2ac3/kiwisolver-1.4.8-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d6af5e8815fd02997cb6ad9bbed0ee1e60014438ee1a5c2444c96f87b8843502", size = 124152 },
+ { url = "https://files.pythonhosted.org/packages/c5/0b/8db6d2e2452d60d5ebc4ce4b204feeb16176a851fd42462f66ade6808084/kiwisolver-1.4.8-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:bade438f86e21d91e0cf5dd7c0ed00cda0f77c8c1616bd83f9fc157fa6760d31", size = 66555 },
+ { url = "https://files.pythonhosted.org/packages/60/26/d6a0db6785dd35d3ba5bf2b2df0aedc5af089962c6eb2cbf67a15b81369e/kiwisolver-1.4.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b83dc6769ddbc57613280118fb4ce3cd08899cc3369f7d0e0fab518a7cf37fdb", size = 65067 },
+ { url = "https://files.pythonhosted.org/packages/c9/ed/1d97f7e3561e09757a196231edccc1bcf59d55ddccefa2afc9c615abd8e0/kiwisolver-1.4.8-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:111793b232842991be367ed828076b03d96202c19221b5ebab421ce8bcad016f", size = 1378443 },
+ { url = "https://files.pythonhosted.org/packages/29/61/39d30b99954e6b46f760e6289c12fede2ab96a254c443639052d1b573fbc/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:257af1622860e51b1a9d0ce387bf5c2c4f36a90594cb9514f55b074bcc787cfc", size = 1472728 },
+ { url = "https://files.pythonhosted.org/packages/0c/3e/804163b932f7603ef256e4a715e5843a9600802bb23a68b4e08c8c0ff61d/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:69b5637c3f316cab1ec1c9a12b8c5f4750a4c4b71af9157645bf32830e39c03a", size = 1478388 },
+ { url = "https://files.pythonhosted.org/packages/8a/9e/60eaa75169a154700be74f875a4d9961b11ba048bef315fbe89cb6999056/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:782bb86f245ec18009890e7cb8d13a5ef54dcf2ebe18ed65f795e635a96a1c6a", size = 1413849 },
+ { url = "https://files.pythonhosted.org/packages/bc/b3/9458adb9472e61a998c8c4d95cfdfec91c73c53a375b30b1428310f923e4/kiwisolver-1.4.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc978a80a0db3a66d25767b03688f1147a69e6237175c0f4ffffaaedf744055a", size = 1475533 },
+ { url = "https://files.pythonhosted.org/packages/e4/7a/0a42d9571e35798de80aef4bb43a9b672aa7f8e58643d7bd1950398ffb0a/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:36dbbfd34838500a31f52c9786990d00150860e46cd5041386f217101350f0d3", size = 2268898 },
+ { url = "https://files.pythonhosted.org/packages/d9/07/1255dc8d80271400126ed8db35a1795b1a2c098ac3a72645075d06fe5c5d/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:eaa973f1e05131de5ff3569bbba7f5fd07ea0595d3870ed4a526d486fe57fa1b", size = 2425605 },
+ { url = "https://files.pythonhosted.org/packages/84/df/5a3b4cf13780ef6f6942df67b138b03b7e79e9f1f08f57c49957d5867f6e/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a66f60f8d0c87ab7f59b6fb80e642ebb29fec354a4dfad687ca4092ae69d04f4", size = 2375801 },
+ { url = "https://files.pythonhosted.org/packages/8f/10/2348d068e8b0f635c8c86892788dac7a6b5c0cb12356620ab575775aad89/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:858416b7fb777a53f0c59ca08190ce24e9abbd3cffa18886a5781b8e3e26f65d", size = 2520077 },
+ { url = "https://files.pythonhosted.org/packages/32/d8/014b89fee5d4dce157d814303b0fce4d31385a2af4c41fed194b173b81ac/kiwisolver-1.4.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:085940635c62697391baafaaeabdf3dd7a6c3643577dde337f4d66eba021b2b8", size = 2338410 },
+ { url = "https://files.pythonhosted.org/packages/bd/72/dfff0cc97f2a0776e1c9eb5bef1ddfd45f46246c6533b0191887a427bca5/kiwisolver-1.4.8-cp312-cp312-win_amd64.whl", hash = "sha256:01c3d31902c7db5fb6182832713d3b4122ad9317c2c5877d0539227d96bb2e50", size = 71853 },
+ { url = "https://files.pythonhosted.org/packages/dc/85/220d13d914485c0948a00f0b9eb419efaf6da81b7d72e88ce2391f7aed8d/kiwisolver-1.4.8-cp312-cp312-win_arm64.whl", hash = "sha256:a3c44cb68861de93f0c4a8175fbaa691f0aa22550c331fefef02b618a9dcb476", size = 65424 },
+ { url = "https://files.pythonhosted.org/packages/79/b3/e62464a652f4f8cd9006e13d07abad844a47df1e6537f73ddfbf1bc997ec/kiwisolver-1.4.8-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:1c8ceb754339793c24aee1c9fb2485b5b1f5bb1c2c214ff13368431e51fc9a09", size = 124156 },
+ { url = "https://files.pythonhosted.org/packages/8d/2d/f13d06998b546a2ad4f48607a146e045bbe48030774de29f90bdc573df15/kiwisolver-1.4.8-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:54a62808ac74b5e55a04a408cda6156f986cefbcf0ada13572696b507cc92fa1", size = 66555 },
+ { url = "https://files.pythonhosted.org/packages/59/e3/b8bd14b0a54998a9fd1e8da591c60998dc003618cb19a3f94cb233ec1511/kiwisolver-1.4.8-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:68269e60ee4929893aad82666821aaacbd455284124817af45c11e50a4b42e3c", size = 65071 },
+ { url = "https://files.pythonhosted.org/packages/f0/1c/6c86f6d85ffe4d0ce04228d976f00674f1df5dc893bf2dd4f1928748f187/kiwisolver-1.4.8-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:34d142fba9c464bc3bbfeff15c96eab0e7310343d6aefb62a79d51421fcc5f1b", size = 1378053 },
+ { url = "https://files.pythonhosted.org/packages/4e/b9/1c6e9f6dcb103ac5cf87cb695845f5fa71379021500153566d8a8a9fc291/kiwisolver-1.4.8-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3ddc373e0eef45b59197de815b1b28ef89ae3955e7722cc9710fb91cd77b7f47", size = 1472278 },
+ { url = "https://files.pythonhosted.org/packages/ee/81/aca1eb176de671f8bda479b11acdc42c132b61a2ac861c883907dde6debb/kiwisolver-1.4.8-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:77e6f57a20b9bd4e1e2cedda4d0b986ebd0216236f0106e55c28aea3d3d69b16", size = 1478139 },
+ { url = "https://files.pythonhosted.org/packages/49/f4/e081522473671c97b2687d380e9e4c26f748a86363ce5af48b4a28e48d06/kiwisolver-1.4.8-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:08e77738ed7538f036cd1170cbed942ef749137b1311fa2bbe2a7fda2f6bf3cc", size = 1413517 },
+ { url = "https://files.pythonhosted.org/packages/8f/e9/6a7d025d8da8c4931522922cd706105aa32b3291d1add8c5427cdcd66e63/kiwisolver-1.4.8-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5ce1e481a74b44dd5e92ff03ea0cb371ae7a0268318e202be06c8f04f4f1246", size = 1474952 },
+ { url = "https://files.pythonhosted.org/packages/82/13/13fa685ae167bee5d94b415991c4fc7bb0a1b6ebea6e753a87044b209678/kiwisolver-1.4.8-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:fc2ace710ba7c1dfd1a3b42530b62b9ceed115f19a1656adefce7b1782a37794", size = 2269132 },
+ { url = "https://files.pythonhosted.org/packages/ef/92/bb7c9395489b99a6cb41d502d3686bac692586db2045adc19e45ee64ed23/kiwisolver-1.4.8-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:3452046c37c7692bd52b0e752b87954ef86ee2224e624ef7ce6cb21e8c41cc1b", size = 2425997 },
+ { url = "https://files.pythonhosted.org/packages/ed/12/87f0e9271e2b63d35d0d8524954145837dd1a6c15b62a2d8c1ebe0f182b4/kiwisolver-1.4.8-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7e9a60b50fe8b2ec6f448fe8d81b07e40141bfced7f896309df271a0b92f80f3", size = 2376060 },
+ { url = "https://files.pythonhosted.org/packages/02/6e/c8af39288edbce8bf0fa35dee427b082758a4b71e9c91ef18fa667782138/kiwisolver-1.4.8-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:918139571133f366e8362fa4a297aeba86c7816b7ecf0bc79168080e2bd79957", size = 2520471 },
+ { url = "https://files.pythonhosted.org/packages/13/78/df381bc7b26e535c91469f77f16adcd073beb3e2dd25042efd064af82323/kiwisolver-1.4.8-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e063ef9f89885a1d68dd8b2e18f5ead48653176d10a0e324e3b0030e3a69adeb", size = 2338793 },
+ { url = "https://files.pythonhosted.org/packages/d0/dc/c1abe38c37c071d0fc71c9a474fd0b9ede05d42f5a458d584619cfd2371a/kiwisolver-1.4.8-cp313-cp313-win_amd64.whl", hash = "sha256:a17b7c4f5b2c51bb68ed379defd608a03954a1845dfed7cc0117f1cc8a9b7fd2", size = 71855 },
+ { url = "https://files.pythonhosted.org/packages/a0/b6/21529d595b126ac298fdd90b705d87d4c5693de60023e0efcb4f387ed99e/kiwisolver-1.4.8-cp313-cp313-win_arm64.whl", hash = "sha256:3cd3bc628b25f74aedc6d374d5babf0166a92ff1317f46267f12d2ed54bc1d30", size = 65430 },
+ { url = "https://files.pythonhosted.org/packages/34/bd/b89380b7298e3af9b39f49334e3e2a4af0e04819789f04b43d560516c0c8/kiwisolver-1.4.8-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:370fd2df41660ed4e26b8c9d6bbcad668fbe2560462cba151a721d49e5b6628c", size = 126294 },
+ { url = "https://files.pythonhosted.org/packages/83/41/5857dc72e5e4148eaac5aa76e0703e594e4465f8ab7ec0fc60e3a9bb8fea/kiwisolver-1.4.8-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:84a2f830d42707de1d191b9490ac186bf7997a9495d4e9072210a1296345f7dc", size = 67736 },
+ { url = "https://files.pythonhosted.org/packages/e1/d1/be059b8db56ac270489fb0b3297fd1e53d195ba76e9bbb30e5401fa6b759/kiwisolver-1.4.8-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:7a3ad337add5148cf51ce0b55642dc551c0b9d6248458a757f98796ca7348712", size = 66194 },
+ { url = "https://files.pythonhosted.org/packages/e1/83/4b73975f149819eb7dcf9299ed467eba068ecb16439a98990dcb12e63fdd/kiwisolver-1.4.8-cp313-cp313t-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7506488470f41169b86d8c9aeff587293f530a23a23a49d6bc64dab66bedc71e", size = 1465942 },
+ { url = "https://files.pythonhosted.org/packages/c7/2c/30a5cdde5102958e602c07466bce058b9d7cb48734aa7a4327261ac8e002/kiwisolver-1.4.8-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2f0121b07b356a22fb0414cec4666bbe36fd6d0d759db3d37228f496ed67c880", size = 1595341 },
+ { url = "https://files.pythonhosted.org/packages/ff/9b/1e71db1c000385aa069704f5990574b8244cce854ecd83119c19e83c9586/kiwisolver-1.4.8-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d6d6bd87df62c27d4185de7c511c6248040afae67028a8a22012b010bc7ad062", size = 1598455 },
+ { url = "https://files.pythonhosted.org/packages/85/92/c8fec52ddf06231b31cbb779af77e99b8253cd96bd135250b9498144c78b/kiwisolver-1.4.8-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:291331973c64bb9cce50bbe871fb2e675c4331dab4f31abe89f175ad7679a4d7", size = 1522138 },
+ { url = "https://files.pythonhosted.org/packages/0b/51/9eb7e2cd07a15d8bdd976f6190c0164f92ce1904e5c0c79198c4972926b7/kiwisolver-1.4.8-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:893f5525bb92d3d735878ec00f781b2de998333659507d29ea4466208df37bed", size = 1582857 },
+ { url = "https://files.pythonhosted.org/packages/0f/95/c5a00387a5405e68ba32cc64af65ce881a39b98d73cc394b24143bebc5b8/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:b47a465040146981dc9db8647981b8cb96366fbc8d452b031e4f8fdffec3f26d", size = 2293129 },
+ { url = "https://files.pythonhosted.org/packages/44/83/eeb7af7d706b8347548313fa3a3a15931f404533cc54fe01f39e830dd231/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:99cea8b9dd34ff80c521aef46a1dddb0dcc0283cf18bde6d756f1e6f31772165", size = 2421538 },
+ { url = "https://files.pythonhosted.org/packages/05/f9/27e94c1b3eb29e6933b6986ffc5fa1177d2cd1f0c8efc5f02c91c9ac61de/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:151dffc4865e5fe6dafce5480fab84f950d14566c480c08a53c663a0020504b6", size = 2390661 },
+ { url = "https://files.pythonhosted.org/packages/d9/d4/3c9735faa36ac591a4afcc2980d2691000506050b7a7e80bcfe44048daa7/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:577facaa411c10421314598b50413aa1ebcf5126f704f1e5d72d7e4e9f020d90", size = 2546710 },
+ { url = "https://files.pythonhosted.org/packages/4c/fa/be89a49c640930180657482a74970cdcf6f7072c8d2471e1babe17a222dc/kiwisolver-1.4.8-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:be4816dc51c8a471749d664161b434912eee82f2ea66bd7628bd14583a833e85", size = 2349213 },
+ { url = "https://files.pythonhosted.org/packages/1f/f9/ae81c47a43e33b93b0a9819cac6723257f5da2a5a60daf46aa5c7226ea85/kiwisolver-1.4.8-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:e7a019419b7b510f0f7c9dceff8c5eae2392037eae483a7f9162625233802b0a", size = 60403 },
+ { url = "https://files.pythonhosted.org/packages/58/ca/f92b5cb6f4ce0c1ebfcfe3e2e42b96917e16f7090e45b21102941924f18f/kiwisolver-1.4.8-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:286b18e86682fd2217a48fc6be6b0f20c1d0ed10958d8dc53453ad58d7be0bf8", size = 58657 },
+ { url = "https://files.pythonhosted.org/packages/80/28/ae0240f732f0484d3a4dc885d055653c47144bdf59b670aae0ec3c65a7c8/kiwisolver-1.4.8-pp310-pypy310_pp73-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4191ee8dfd0be1c3666ccbac178c5a05d5f8d689bbe3fc92f3c4abec817f8fe0", size = 84948 },
+ { url = "https://files.pythonhosted.org/packages/5d/eb/78d50346c51db22c7203c1611f9b513075f35c4e0e4877c5dde378d66043/kiwisolver-1.4.8-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7cd2785b9391f2873ad46088ed7599a6a71e762e1ea33e87514b1a441ed1da1c", size = 81186 },
+ { url = "https://files.pythonhosted.org/packages/43/f8/7259f18c77adca88d5f64f9a522792e178b2691f3748817a8750c2d216ef/kiwisolver-1.4.8-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c07b29089b7ba090b6f1a669f1411f27221c3662b3a1b7010e67b59bb5a6f10b", size = 80279 },
+ { url = "https://files.pythonhosted.org/packages/3a/1d/50ad811d1c5dae091e4cf046beba925bcae0a610e79ae4c538f996f63ed5/kiwisolver-1.4.8-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:65ea09a5a3faadd59c2ce96dc7bf0f364986a315949dc6374f04396b0d60e09b", size = 71762 },
+]
+
+[[package]]
+name = "lark"
+version = "1.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/af/60/bc7622aefb2aee1c0b4ba23c1446d3e30225c8770b38d7aedbfb65ca9d5a/lark-1.2.2.tar.gz", hash = "sha256:ca807d0162cd16cef15a8feecb862d7319e7a09bdb13aef927968e45040fed80", size = 252132 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2d/00/d90b10b962b4277f5e64a78b6609968859ff86889f5b898c1a778c06ec00/lark-1.2.2-py3-none-any.whl", hash = "sha256:c2276486b02f0f1b90be155f2c8ba4a8e194d42775786db622faccd652d8e80c", size = 111036 },
+]
+
+[[package]]
+name = "leann-backend-diskann"
+version = "0.1.0"
+source = { editable = "packages/leann-backend-diskann" }
+dependencies = [
+ { name = "leann-core" },
+ { name = "numpy" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "leann-core", specifier = "==0.1.0" },
+ { name = "numpy" },
+]
+
+[[package]]
+name = "leann-backend-hnsw"
+version = "0.1.0"
+source = { editable = "packages/leann-backend-hnsw" }
+dependencies = [
+ { name = "leann-core" },
+ { name = "numpy" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "leann-core", specifier = "==0.1.0" },
+ { name = "numpy" },
+]
+
+[[package]]
+name = "leann-core"
+version = "0.1.0"
+source = { editable = "packages/leann-core" }
+dependencies = [
+ { name = "numpy" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "numpy", specifier = ">=1.20.0" }]
+
+[[package]]
+name = "leann-workspace"
+version = "0.1.0"
+source = { editable = "." }
+dependencies = [
+ { name = "boto3", version = "1.7.84", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "boto3", version = "1.38.36", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "colorama" },
+ { name = "datasets" },
+ { name = "evaluate" },
+ { name = "flask" },
+ { name = "flask-compress" },
+ { name = "leann-backend-diskann" },
+ { name = "leann-backend-hnsw" },
+ { name = "leann-core" },
+ { name = "llama-index" },
+ { name = "numpy" },
+ { name = "ollama" },
+ { name = "openai" },
+ { name = "protobuf" },
+ { name = "pypdf2" },
+ { name = "requests" },
+ { name = "sentence-transformers" },
+ { name = "sglang", extra = ["all"] },
+ { name = "torch" },
+ { name = "tqdm" },
+]
+
+[package.optional-dependencies]
+dev = [
+ { name = "black" },
+ { name = "matplotlib", version = "3.9.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "matplotlib", version = "3.10.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "pytest" },
+ { name = "pytest-cov" },
+ { name = "ruff" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "black", marker = "extra == 'dev'", specifier = ">=23.0" },
+ { name = "boto3" },
+ { name = "colorama" },
+ { name = "datasets", specifier = ">=2.15.0" },
+ { name = "evaluate" },
+ { name = "flask" },
+ { name = "flask-compress" },
+ { name = "leann-backend-diskann", editable = "packages/leann-backend-diskann" },
+ { name = "leann-backend-hnsw", editable = "packages/leann-backend-hnsw" },
+ { name = "leann-core", editable = "packages/leann-core" },
+ { name = "llama-index", specifier = ">=0.12.44" },
+ { name = "matplotlib", marker = "extra == 'dev'" },
+ { name = "numpy", specifier = "==1.25.0" },
+ { name = "ollama" },
+ { name = "openai", specifier = ">=1.0.0" },
+ { name = "protobuf", specifier = "==4.25.3" },
+ { name = "pypdf2", specifier = ">=3.0.0" },
+ { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" },
+ { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" },
+ { name = "requests", specifier = ">=2.25.0" },
+ { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" },
+ { name = "sentence-transformers", specifier = ">=2.2.0" },
+ { name = "sglang", extras = ["all"] },
+ { name = "torch" },
+ { name = "tqdm" },
+]
+provides-extras = ["dev"]
+
+[[package]]
+name = "litellm"
+version = "1.72.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "httpx" },
+ { name = "importlib-metadata" },
+ { name = "jinja2" },
+ { name = "jsonschema" },
+ { name = "openai" },
+ { name = "pydantic" },
+ { name = "python-dotenv" },
+ { name = "tiktoken" },
+ { name = "tokenizers" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/83/80/d73c821a2f65ee5b97b41e61d9b18324ebb9d616e1e21844f4253ac38957/litellm-1.72.4.tar.gz", hash = "sha256:8855de30f78bcb1f37af244519b37a37faaaf579401b1414400b5b5e5b616d57", size = 8132997 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6f/0d/0f86db9724b9bd63d057b912aa6aa532a76e6e707f9bb75abbd3b0a0401a/litellm-1.72.4-py3-none-any.whl", hash = "sha256:f98ca994420ed649c466d423655a6e0f2aeecab4564ed372b3378a949e491dc2", size = 8036589 },
+]
+
+[[package]]
+name = "llama-cloud"
+version = "0.1.26"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "httpx" },
+ { name = "pydantic" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f1/02/c6428db51ec5dfcadc9a29e16fcb3829a10d82f6deebf71db0412fc80ef0/llama_cloud-0.1.26.tar.gz", hash = "sha256:b307f91b1ad97189b5278119ac4ad665931b65f240fb643b3e384d0a1fc81f56", size = 92788 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/2a/80864124d649ef06a3cbc93adb0b236dcc3d95348a36e65b852e3ccc9bb4/llama_cloud-0.1.26-py3-none-any.whl", hash = "sha256:2c0b2663e619b71c0645885ef622d6443725ab37bdc6ae5fb723e097f3af9459", size = 266775 },
+]
+
+[[package]]
+name = "llama-cloud-services"
+version = "0.6.34"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "eval-type-backport", marker = "python_full_version < '3.10'" },
+ { name = "llama-cloud" },
+ { name = "llama-index-core" },
+ { name = "platformdirs" },
+ { name = "pydantic" },
+ { name = "python-dotenv" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/4e/e4/b4e9d74a7c9f42a53f5450b3b57ea8ca819a3653c842e4c0a28503e90dcf/llama_cloud_services-0.6.34.tar.gz", hash = "sha256:b56884ee0cc2298fd625b6b6d9f161e09340cb962cdb04006770ecf097e925ae", size = 34450 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/df/36/088caee44cbafab71c9b329c056654dfd0a1fa9834e8aca3e658f61c17cb/llama_cloud_services-0.6.34-py3-none-any.whl", hash = "sha256:02df81b03ed0286422a1cce0c650a3fe0eba385c88b12ac690a23153aab55432", size = 39778 },
+]
+
+[[package]]
+name = "llama-index"
+version = "0.12.44"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-agent-openai" },
+ { name = "llama-index-cli" },
+ { name = "llama-index-core" },
+ { name = "llama-index-embeddings-openai" },
+ { name = "llama-index-indices-managed-llama-cloud" },
+ { name = "llama-index-llms-openai" },
+ { name = "llama-index-multi-modal-llms-openai" },
+ { name = "llama-index-program-openai" },
+ { name = "llama-index-question-gen-openai" },
+ { name = "llama-index-readers-file" },
+ { name = "llama-index-readers-llama-parse" },
+ { name = "nltk" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/77/98/f7a278e0c1a8d2896418a0c80eaf9412edaa2b7178da742f7a133fbf1015/llama_index-0.12.44.tar.gz", hash = "sha256:c0e2e61f61f39c4d72ae7e3ac88b88eeaa8f5ea30a79ff8eccd883f1c45759b5", size = 8087 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ee/0f/0455e13982c03684bfd0ee68aa14da31776a10277b909e0b71931f18a265/llama_index-0.12.44-py3-none-any.whl", hash = "sha256:693c1c19c46855014c40ee627c6312af10ac4f6ca9fd08e7d905b403f1fdefa6", size = 7085 },
+]
+
+[[package]]
+name = "llama-index-agent-openai"
+version = "0.4.12"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "llama-index-llms-openai" },
+ { name = "openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0e/94/69decc46d11e954c6a8c64999cc237af5932d116eeb7a06515856641a6d4/llama_index_agent_openai-0.4.12.tar.gz", hash = "sha256:d2fe53feb69cfe45752edb7328bf0d25f6a9071b3c056787e661b93e5b748a28", size = 12443 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/89/f5/857ea1c136f422234e298e868af74094a71bf98687be40a365ad6551a660/llama_index_agent_openai-0.4.12-py3-none-any.whl", hash = "sha256:6dbb6276b2e5330032a726b28d5eef5140825f36d72d472b231f08ad3af99665", size = 14704 },
+]
+
+[[package]]
+name = "llama-index-cli"
+version = "0.4.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "llama-index-embeddings-openai" },
+ { name = "llama-index-llms-openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f8/a3/1acdb3aa3f4a90a1d5275dcaa4acea295aa3d9102d7529c56734c0cde46c/llama_index_cli-0.4.3.tar.gz", hash = "sha256:dae8183a10551bbd89686b94ed294a6cf44633c3dd6285c4f991c85031b7a55f", size = 25274 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bc/e5/0e7f9515c88cf4e791bf243f83246e2634c01ec5cdbd7245307b28b48487/llama_index_cli-0.4.3-py3-none-any.whl", hash = "sha256:f0af55ce4b90e5a2466e394b88f4ac6085ea3e6286019bc3f49de6673ce2238d", size = 28564 },
+]
+
+[[package]]
+name = "llama-index-core"
+version = "0.12.44"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "aiosqlite" },
+ { name = "banks" },
+ { name = "dataclasses-json" },
+ { name = "deprecated" },
+ { name = "dirtyjson" },
+ { name = "eval-type-backport", marker = "python_full_version < '3.10'" },
+ { name = "filetype" },
+ { name = "fsspec" },
+ { name = "httpx" },
+ { name = "llama-index-workflows" },
+ { name = "nest-asyncio" },
+ { name = "networkx", version = "3.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.10.*'" },
+ { name = "networkx", version = "3.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
+ { name = "nltk" },
+ { name = "numpy" },
+ { name = "pillow" },
+ { name = "pydantic" },
+ { name = "pyyaml" },
+ { name = "requests" },
+ { name = "setuptools" },
+ { name = "sqlalchemy", extra = ["asyncio"] },
+ { name = "tenacity" },
+ { name = "tiktoken" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+ { name = "typing-inspect" },
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/26/03/d57a98f5b3d2e8ebb39bb4dd51a2472e42201d00e82429ae06e02e141158/llama_index_core-0.12.44.tar.gz", hash = "sha256:d2fdbbd2bcb0dd289f3df305874dbc0d7532f39c3d725ca6d937c6fa18a8d249", size = 7272062 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1d/3f/44fbaca608c2e2116cd9d624f7b836624a6c5dc4bf4608d25918a6cd065b/llama_index_core-0.12.44-py3-none-any.whl", hash = "sha256:12ac30adb1f46768bac4d07d363cf16ae0b032cfb9da861791f13415fc4f1f12", size = 7641712 },
+]
+
+[[package]]
+name = "llama-index-embeddings-openai"
+version = "0.3.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a1/02/a2604ef3a167131fdd701888f45f16c8efa6d523d02efe8c4e640238f4ea/llama_index_embeddings_openai-0.3.1.tar.gz", hash = "sha256:1368aad3ce24cbaed23d5ad251343cef1eb7b4a06d6563d6606d59cb347fef20", size = 5492 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bb/45/ca55b91c4ac1b6251d4099fa44121a6c012129822906cadcc27b8cfb33a4/llama_index_embeddings_openai-0.3.1-py3-none-any.whl", hash = "sha256:f15a3d13da9b6b21b8bd51d337197879a453d1605e625a1c6d45e741756c0290", size = 6177 },
+]
+
+[[package]]
+name = "llama-index-indices-managed-llama-cloud"
+version = "0.7.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-cloud" },
+ { name = "llama-index-core" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c6/1b/886a67f488de729195c7a25a12ed655cda9d35bf6196e9d147978e27e965/llama_index_indices_managed_llama_cloud-0.7.7.tar.gz", hash = "sha256:7fd730a2967dc20eb422ae2fa4028b4cf7023114a5cfadb5232355137754186f", size = 14774 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/23/38/9910dd096a6f014a9cb54dab5dcf4a92775f22497d38b12f0fc6913d2d0a/llama_index_indices_managed_llama_cloud-0.7.7-py3-none-any.whl", hash = "sha256:5a8a24de6a2f425a5616818582b57f603e4192179443045f636e865efc6692c4", size = 16469 },
+]
+
+[[package]]
+name = "llama-index-instrumentation"
+version = "0.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "deprecated" },
+ { name = "pydantic" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ef/03/6a34612ecc03ab05cd4818b989cbd7c6bf83e9ffa94c7275847a82ff4f9f/llama_index_instrumentation-0.2.0.tar.gz", hash = "sha256:ae8333522487e22a33732924a9a08dfb456f54993c5c97d8340db3c620b76f13", size = 44023 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/96/b5/24ad1cf25b8c35b2075cfdd8c12d0f8390b7cfd54122ed704097bd755a2f/llama_index_instrumentation-0.2.0-py3-none-any.whl", hash = "sha256:1055ae7a3d19666671a8f1a62d08c90472552d9fcec7e84e6919b2acc92af605", size = 14966 },
+]
+
+[[package]]
+name = "llama-index-llms-openai"
+version = "0.4.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d9/39/a7ce514fb500951e9edb713ed918a9ffe49f1a76fccfc531a4ec5c7fe15a/llama_index_llms_openai-0.4.7.tar.gz", hash = "sha256:564af8ab39fb3f3adfeae73a59c0dca46c099ab844a28e725eee0c551d4869f8", size = 24251 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/61/e9/391926dad180ced6bb37a62edddb8483fbecde411239bd5e726841bb77b4/llama_index_llms_openai-0.4.7-py3-none-any.whl", hash = "sha256:3b8d9d3c1bcadc2cff09724de70f074f43eafd5b7048a91247c9a41b7cd6216d", size = 25365 },
+]
+
+[[package]]
+name = "llama-index-multi-modal-llms-openai"
+version = "0.5.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "llama-index-llms-openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7b/77/0ece3c7887e9c7242fc7cc2a184374bbeb08a35783d71a8466e1dd18ccfc/llama_index_multi_modal_llms_openai-0.5.1.tar.gz", hash = "sha256:df3aff00c36023c5f8c49f972a325f71823ed0f4dd9cd479955d76afc146575f", size = 3708 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/17/a5/6181a385af1caef88e1d0d3919c399ba7e031190fc0be4fd5242875c5b0e/llama_index_multi_modal_llms_openai-0.5.1-py3-none-any.whl", hash = "sha256:69bb9c310c323ce51038f0d40719f546d0d4e0853835a4f5cfa21f07dbb0b91e", size = 3362 },
+]
+
+[[package]]
+name = "llama-index-program-openai"
+version = "0.3.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-agent-openai" },
+ { name = "llama-index-core" },
+ { name = "llama-index-llms-openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/83/81/9caa34e80adce1adb715ae083a54ad45c8fc0d9aef0f2d80d61c1b805ab6/llama_index_program_openai-0.3.2.tar.gz", hash = "sha256:04c959a2e616489894bd2eeebb99500d6f1c17d588c3da0ddc75ebd3eb7451ee", size = 6301 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/05/80/d6ac8afafdd38115d61214891c36876e64f429809abff873660fe30862fe/llama_index_program_openai-0.3.2-py3-none-any.whl", hash = "sha256:451829ae53e074e7b47dcc60a9dd155fcf9d1dcbc1754074bdadd6aab4ceb9aa", size = 6129 },
+]
+
+[[package]]
+name = "llama-index-question-gen-openai"
+version = "0.3.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "llama-index-llms-openai" },
+ { name = "llama-index-program-openai" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/52/6e/19c5051c81ef5fca597d13c6d41b863535521565b1414ab5ab0e5e8c1297/llama_index_question_gen_openai-0.3.1.tar.gz", hash = "sha256:5e9311b433cc2581ff8a531fa19fb3aa21815baff75aaacdef11760ac9522aa9", size = 4107 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/15/2a/652593d0bd24f901776db0d1778a42363ea2656530da18215f413ce4f981/llama_index_question_gen_openai-0.3.1-py3-none-any.whl", hash = "sha256:1ce266f6c8373fc8d884ff83a44dfbacecde2301785db7144872db51b8b99429", size = 3733 },
+]
+
+[[package]]
+name = "llama-index-readers-file"
+version = "0.4.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "beautifulsoup4" },
+ { name = "llama-index-core" },
+ { name = "pandas" },
+ { name = "pypdf" },
+ { name = "striprtf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6a/aa/517a79b9fa57ff42dc3d0ae801676b794c81bbceacc2350c948ebe9cfa7e/llama_index_readers_file-0.4.9.tar.gz", hash = "sha256:b705fd42a2875af03d343c66b28138471800cd13a67efcc48ae2983b39d816c7", size = 22710 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/65/65/ebc692d80f55501771eec0854cea90c9f7ecdbd688a74e89357ef8afa285/llama_index_readers_file-0.4.9-py3-none-any.whl", hash = "sha256:71f1d0d2ea22012bf233ed4afb9b9b6b2f098d26286e38ed82e3c4af685e07bd", size = 40976 },
+]
+
+[[package]]
+name = "llama-index-readers-llama-parse"
+version = "0.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-index-core" },
+ { name = "llama-parse" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/35/30/4611821286f82ba7b5842295607baa876262db86f88b87d83595eed172bf/llama_index_readers_llama_parse-0.4.0.tar.gz", hash = "sha256:e99ec56f4f8546d7fda1a7c1ae26162fb9acb7ebcac343b5abdb4234b4644e0f", size = 2472 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/68/4f/e30d4257fe9e4224f5612b77fe99aaceddae411b2e74ca30534491de3e6f/llama_index_readers_llama_parse-0.4.0-py3-none-any.whl", hash = "sha256:574e48386f28d2c86c3f961ca4a4906910312f3400dd0c53014465bfbc6b32bf", size = 2472 },
+]
+
+[[package]]
+name = "llama-index-workflows"
+version = "1.0.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "eval-type-backport", marker = "python_full_version < '3.10'" },
+ { name = "llama-index-instrumentation" },
+ { name = "pydantic" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/08/4f/64e0f6a2721240a9318926bfe691193f1ae7836e6ae145e0bbcd95b1d9f1/llama_index_workflows-1.0.1.tar.gz", hash = "sha256:07a68cf58040d469af8d05f56217418ae6404557f0254bff22a7481987818e3f", size = 85599 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/57/cf/2980bcdbb58c24afd5798ef0cc9403e092beae528c6002bfd4fc03a62674/llama_index_workflows-1.0.1-py3-none-any.whl", hash = "sha256:765844e143fac7fa1f25749be2479a9f75bf553d779a2fbec4f2caeeaa4ff1dd", size = 36943 },
+]
+
+[[package]]
+name = "llama-parse"
+version = "0.6.34"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "llama-cloud-services" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b4/4f/c1a0616799c02b214411851a10c7631287f8280b3c64884198d7fb11cc18/llama_parse-0.6.34.tar.gz", hash = "sha256:a228619806687ff7b3fb44f21210e98c337f7e05f19374f0fb52196158caae0d", size = 3538 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/50/24/af0d46874ec18d240fe200ce3902044f6d1d373067433c2b9ade5dc217d4/llama_parse-0.6.34-py3-none-any.whl", hash = "sha256:395174c3c4d22dc372ab310727de2b3fc4e268e36f11fe9959a95bfa9cf63d66", size = 4945 },
+]
+
+[[package]]
+name = "llguidance"
+version = "0.7.29"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fb/3b/c3ced46dd10cffa49fad941e84118a1e8279cd3261769b2238eafc4df3c1/llguidance-0.7.29.tar.gz", hash = "sha256:d1aa68a54f9496d36750018e7edad3bf624ee2fbcf671a7483883790d798c4fe", size = 1041807 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d9/6e/dc3d372828ec5e90dfd7d9cf17edebc9fd2722b4a42d224d6ca068749843/llguidance-0.7.29-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:94a5ccbd86a70ae5e0a967c5d0e1ee6b0edf2d42f1023fdef0eca87f07ea9da4", size = 3279134 },
+ { url = "https://files.pythonhosted.org/packages/63/de/f8945358d163f27d1370106e543d81cc94a197d94e4a613a5da42e264466/llguidance-0.7.29-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:47cedfba78f0e8e0f377439c4f2ff3734e0e09c87be3934fe93bb8996f21a6b9", size = 3173892 },
+ { url = "https://files.pythonhosted.org/packages/4e/f4/91342f63620ed1c75518f1cf807fb1d67a789d6357bce5fbdb75bb13a94a/llguidance-0.7.29-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d30a76b30b646ac7f9025d262665f62bdbf2d43698115eeb1119c6ee062a36f", size = 14986589 },
+ { url = "https://files.pythonhosted.org/packages/7d/62/269b43d56c89d2b2a82c2e5596b5e10250a699b9d6a94e9b70b09d1c3cdb/llguidance-0.7.29-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:234ff847e91c429e598897109bb61ca2fa9278ef409f7125fb68374166e06b5b", size = 15147555 },
+ { url = "https://files.pythonhosted.org/packages/9f/c8/59504a4e9ba60243261708f345c85af9d5b4c46220334b575f6f744c4622/llguidance-0.7.29-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17fd439957d6ca5f459d0dec755a2d040c2dc946ed7e3c332b469ef6861292f8", size = 15045686 },
+ { url = "https://files.pythonhosted.org/packages/be/1d/189af6a0a40138cab75523c229f486be8d82f00e28ca4e9d80b2e08fe114/llguidance-0.7.29-cp39-abi3-win32.whl", hash = "sha256:c97f16ddd6be28f4d176eaaa493102b981ba5470299253903de9a764e2501ef3", size = 2535564 },
+ { url = "https://files.pythonhosted.org/packages/9a/b6/aa9dd5ac6215efd1071ab2af9547e7b777743e3e8ed48a1074f458042769/llguidance-0.7.29-cp39-abi3-win_amd64.whl", hash = "sha256:83e175212effb655f7e19b4c642b8d013a42b8f17e0baaf869c607a2fc5438f9", size = 2746679 },
+]
+
+[[package]]
+name = "lxml"
+version = "5.4.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/76/3d/14e82fc7c8fb1b7761f7e748fd47e2ec8276d137b6acfe5a4bb73853e08f/lxml-5.4.0.tar.gz", hash = "sha256:d12832e1dbea4be280b22fd0ea7c9b87f0d8fc51ba06e92dc62d52f804f78ebd", size = 3679479 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f5/1f/a3b6b74a451ceb84b471caa75c934d2430a4d84395d38ef201d539f38cd1/lxml-5.4.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e7bc6df34d42322c5289e37e9971d6ed114e3776b45fa879f734bded9d1fea9c", size = 8076838 },
+ { url = "https://files.pythonhosted.org/packages/36/af/a567a55b3e47135b4d1f05a1118c24529104c003f95851374b3748139dc1/lxml-5.4.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6854f8bd8a1536f8a1d9a3655e6354faa6406621cf857dc27b681b69860645c7", size = 4381827 },
+ { url = "https://files.pythonhosted.org/packages/50/ba/4ee47d24c675932b3eb5b6de77d0f623c2db6dc466e7a1f199792c5e3e3a/lxml-5.4.0-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:696ea9e87442467819ac22394ca36cb3d01848dad1be6fac3fb612d3bd5a12cf", size = 5204098 },
+ { url = "https://files.pythonhosted.org/packages/f2/0f/b4db6dfebfefe3abafe360f42a3d471881687fd449a0b86b70f1f2683438/lxml-5.4.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ef80aeac414f33c24b3815ecd560cee272786c3adfa5f31316d8b349bfade28", size = 4930261 },
+ { url = "https://files.pythonhosted.org/packages/0b/1f/0bb1bae1ce056910f8db81c6aba80fec0e46c98d77c0f59298c70cd362a3/lxml-5.4.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3b9c2754cef6963f3408ab381ea55f47dabc6f78f4b8ebb0f0b25cf1ac1f7609", size = 5529621 },
+ { url = "https://files.pythonhosted.org/packages/21/f5/e7b66a533fc4a1e7fa63dd22a1ab2ec4d10319b909211181e1ab3e539295/lxml-5.4.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7a62cc23d754bb449d63ff35334acc9f5c02e6dae830d78dab4dd12b78a524f4", size = 4983231 },
+ { url = "https://files.pythonhosted.org/packages/11/39/a38244b669c2d95a6a101a84d3c85ba921fea827e9e5483e93168bf1ccb2/lxml-5.4.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f82125bc7203c5ae8633a7d5d20bcfdff0ba33e436e4ab0abc026a53a8960b7", size = 5084279 },
+ { url = "https://files.pythonhosted.org/packages/db/64/48cac242347a09a07740d6cee7b7fd4663d5c1abd65f2e3c60420e231b27/lxml-5.4.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:b67319b4aef1a6c56576ff544b67a2a6fbd7eaee485b241cabf53115e8908b8f", size = 4927405 },
+ { url = "https://files.pythonhosted.org/packages/98/89/97442835fbb01d80b72374f9594fe44f01817d203fa056e9906128a5d896/lxml-5.4.0-cp310-cp310-manylinux_2_28_ppc64le.whl", hash = "sha256:a8ef956fce64c8551221f395ba21d0724fed6b9b6242ca4f2f7beb4ce2f41997", size = 5550169 },
+ { url = "https://files.pythonhosted.org/packages/f1/97/164ca398ee654eb21f29c6b582685c6c6b9d62d5213abc9b8380278e9c0a/lxml-5.4.0-cp310-cp310-manylinux_2_28_s390x.whl", hash = "sha256:0a01ce7d8479dce84fc03324e3b0c9c90b1ece9a9bb6a1b6c9025e7e4520e78c", size = 5062691 },
+ { url = "https://files.pythonhosted.org/packages/d0/bc/712b96823d7feb53482d2e4f59c090fb18ec7b0d0b476f353b3085893cda/lxml-5.4.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:91505d3ddebf268bb1588eb0f63821f738d20e1e7f05d3c647a5ca900288760b", size = 5133503 },
+ { url = "https://files.pythonhosted.org/packages/d4/55/a62a39e8f9da2a8b6002603475e3c57c870cd9c95fd4b94d4d9ac9036055/lxml-5.4.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:a3bcdde35d82ff385f4ede021df801b5c4a5bcdfb61ea87caabcebfc4945dc1b", size = 4999346 },
+ { url = "https://files.pythonhosted.org/packages/ea/47/a393728ae001b92bb1a9e095e570bf71ec7f7fbae7688a4792222e56e5b9/lxml-5.4.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:aea7c06667b987787c7d1f5e1dfcd70419b711cdb47d6b4bb4ad4b76777a0563", size = 5627139 },
+ { url = "https://files.pythonhosted.org/packages/5e/5f/9dcaaad037c3e642a7ea64b479aa082968de46dd67a8293c541742b6c9db/lxml-5.4.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:a7fb111eef4d05909b82152721a59c1b14d0f365e2be4c742a473c5d7372f4f5", size = 5465609 },
+ { url = "https://files.pythonhosted.org/packages/a7/0a/ebcae89edf27e61c45023005171d0ba95cb414ee41c045ae4caf1b8487fd/lxml-5.4.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:43d549b876ce64aa18b2328faff70f5877f8c6dede415f80a2f799d31644d776", size = 5192285 },
+ { url = "https://files.pythonhosted.org/packages/42/ad/cc8140ca99add7d85c92db8b2354638ed6d5cc0e917b21d36039cb15a238/lxml-5.4.0-cp310-cp310-win32.whl", hash = "sha256:75133890e40d229d6c5837b0312abbe5bac1c342452cf0e12523477cd3aa21e7", size = 3477507 },
+ { url = "https://files.pythonhosted.org/packages/e9/39/597ce090da1097d2aabd2f9ef42187a6c9c8546d67c419ce61b88b336c85/lxml-5.4.0-cp310-cp310-win_amd64.whl", hash = "sha256:de5b4e1088523e2b6f730d0509a9a813355b7f5659d70eb4f319c76beea2e250", size = 3805104 },
+ { url = "https://files.pythonhosted.org/packages/81/2d/67693cc8a605a12e5975380d7ff83020dcc759351b5a066e1cced04f797b/lxml-5.4.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:98a3912194c079ef37e716ed228ae0dcb960992100461b704aea4e93af6b0bb9", size = 8083240 },
+ { url = "https://files.pythonhosted.org/packages/73/53/b5a05ab300a808b72e848efd152fe9c022c0181b0a70b8bca1199f1bed26/lxml-5.4.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0ea0252b51d296a75f6118ed0d8696888e7403408ad42345d7dfd0d1e93309a7", size = 4387685 },
+ { url = "https://files.pythonhosted.org/packages/d8/cb/1a3879c5f512bdcd32995c301886fe082b2edd83c87d41b6d42d89b4ea4d/lxml-5.4.0-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b92b69441d1bd39f4940f9eadfa417a25862242ca2c396b406f9272ef09cdcaa", size = 4991164 },
+ { url = "https://files.pythonhosted.org/packages/f9/94/bbc66e42559f9d04857071e3b3d0c9abd88579367fd2588a4042f641f57e/lxml-5.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:20e16c08254b9b6466526bc1828d9370ee6c0d60a4b64836bc3ac2917d1e16df", size = 4746206 },
+ { url = "https://files.pythonhosted.org/packages/66/95/34b0679bee435da2d7cae895731700e519a8dfcab499c21662ebe671603e/lxml-5.4.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7605c1c32c3d6e8c990dd28a0970a3cbbf1429d5b92279e37fda05fb0c92190e", size = 5342144 },
+ { url = "https://files.pythonhosted.org/packages/e0/5d/abfcc6ab2fa0be72b2ba938abdae1f7cad4c632f8d552683ea295d55adfb/lxml-5.4.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ecf4c4b83f1ab3d5a7ace10bafcb6f11df6156857a3c418244cef41ca9fa3e44", size = 4825124 },
+ { url = "https://files.pythonhosted.org/packages/5a/78/6bd33186c8863b36e084f294fc0a5e5eefe77af95f0663ef33809cc1c8aa/lxml-5.4.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0cef4feae82709eed352cd7e97ae062ef6ae9c7b5dbe3663f104cd2c0e8d94ba", size = 4876520 },
+ { url = "https://files.pythonhosted.org/packages/3b/74/4d7ad4839bd0fc64e3d12da74fc9a193febb0fae0ba6ebd5149d4c23176a/lxml-5.4.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:df53330a3bff250f10472ce96a9af28628ff1f4efc51ccba351a8820bca2a8ba", size = 4765016 },
+ { url = "https://files.pythonhosted.org/packages/24/0d/0a98ed1f2471911dadfc541003ac6dd6879fc87b15e1143743ca20f3e973/lxml-5.4.0-cp311-cp311-manylinux_2_28_ppc64le.whl", hash = "sha256:aefe1a7cb852fa61150fcb21a8c8fcea7b58c4cb11fbe59c97a0a4b31cae3c8c", size = 5362884 },
+ { url = "https://files.pythonhosted.org/packages/48/de/d4f7e4c39740a6610f0f6959052b547478107967362e8424e1163ec37ae8/lxml-5.4.0-cp311-cp311-manylinux_2_28_s390x.whl", hash = "sha256:ef5a7178fcc73b7d8c07229e89f8eb45b2908a9238eb90dcfc46571ccf0383b8", size = 4902690 },
+ { url = "https://files.pythonhosted.org/packages/07/8c/61763abd242af84f355ca4ef1ee096d3c1b7514819564cce70fd18c22e9a/lxml-5.4.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:d2ed1b3cb9ff1c10e6e8b00941bb2e5bb568b307bfc6b17dffbbe8be5eecba86", size = 4944418 },
+ { url = "https://files.pythonhosted.org/packages/f9/c5/6d7e3b63e7e282619193961a570c0a4c8a57fe820f07ca3fe2f6bd86608a/lxml-5.4.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:72ac9762a9f8ce74c9eed4a4e74306f2f18613a6b71fa065495a67ac227b3056", size = 4827092 },
+ { url = "https://files.pythonhosted.org/packages/71/4a/e60a306df54680b103348545706a98a7514a42c8b4fbfdcaa608567bb065/lxml-5.4.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f5cb182f6396706dc6cc1896dd02b1c889d644c081b0cdec38747573db88a7d7", size = 5418231 },
+ { url = "https://files.pythonhosted.org/packages/27/f2/9754aacd6016c930875854f08ac4b192a47fe19565f776a64004aa167521/lxml-5.4.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:3a3178b4873df8ef9457a4875703488eb1622632a9cee6d76464b60e90adbfcd", size = 5261798 },
+ { url = "https://files.pythonhosted.org/packages/38/a2/0c49ec6941428b1bd4f280650d7b11a0f91ace9db7de32eb7aa23bcb39ff/lxml-5.4.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e094ec83694b59d263802ed03a8384594fcce477ce484b0cbcd0008a211ca751", size = 4988195 },
+ { url = "https://files.pythonhosted.org/packages/7a/75/87a3963a08eafc46a86c1131c6e28a4de103ba30b5ae903114177352a3d7/lxml-5.4.0-cp311-cp311-win32.whl", hash = "sha256:4329422de653cdb2b72afa39b0aa04252fca9071550044904b2e7036d9d97fe4", size = 3474243 },
+ { url = "https://files.pythonhosted.org/packages/fa/f9/1f0964c4f6c2be861c50db380c554fb8befbea98c6404744ce243a3c87ef/lxml-5.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:fd3be6481ef54b8cfd0e1e953323b7aa9d9789b94842d0e5b142ef4bb7999539", size = 3815197 },
+ { url = "https://files.pythonhosted.org/packages/f8/4c/d101ace719ca6a4ec043eb516fcfcb1b396a9fccc4fcd9ef593df34ba0d5/lxml-5.4.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:b5aff6f3e818e6bdbbb38e5967520f174b18f539c2b9de867b1e7fde6f8d95a4", size = 8127392 },
+ { url = "https://files.pythonhosted.org/packages/11/84/beddae0cec4dd9ddf46abf156f0af451c13019a0fa25d7445b655ba5ccb7/lxml-5.4.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:942a5d73f739ad7c452bf739a62a0f83e2578afd6b8e5406308731f4ce78b16d", size = 4415103 },
+ { url = "https://files.pythonhosted.org/packages/d0/25/d0d93a4e763f0462cccd2b8a665bf1e4343dd788c76dcfefa289d46a38a9/lxml-5.4.0-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:460508a4b07364d6abf53acaa0a90b6d370fafde5693ef37602566613a9b0779", size = 5024224 },
+ { url = "https://files.pythonhosted.org/packages/31/ce/1df18fb8f7946e7f3388af378b1f34fcf253b94b9feedb2cec5969da8012/lxml-5.4.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:529024ab3a505fed78fe3cc5ddc079464e709f6c892733e3f5842007cec8ac6e", size = 4769913 },
+ { url = "https://files.pythonhosted.org/packages/4e/62/f4a6c60ae7c40d43657f552f3045df05118636be1165b906d3423790447f/lxml-5.4.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7ca56ebc2c474e8f3d5761debfd9283b8b18c76c4fc0967b74aeafba1f5647f9", size = 5290441 },
+ { url = "https://files.pythonhosted.org/packages/9e/aa/04f00009e1e3a77838c7fc948f161b5d2d5de1136b2b81c712a263829ea4/lxml-5.4.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a81e1196f0a5b4167a8dafe3a66aa67c4addac1b22dc47947abd5d5c7a3f24b5", size = 4820165 },
+ { url = "https://files.pythonhosted.org/packages/c9/1f/e0b2f61fa2404bf0f1fdf1898377e5bd1b74cc9b2cf2c6ba8509b8f27990/lxml-5.4.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:00b8686694423ddae324cf614e1b9659c2edb754de617703c3d29ff568448df5", size = 4932580 },
+ { url = "https://files.pythonhosted.org/packages/24/a2/8263f351b4ffe0ed3e32ea7b7830f845c795349034f912f490180d88a877/lxml-5.4.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:c5681160758d3f6ac5b4fea370495c48aac0989d6a0f01bb9a72ad8ef5ab75c4", size = 4759493 },
+ { url = "https://files.pythonhosted.org/packages/05/00/41db052f279995c0e35c79d0f0fc9f8122d5b5e9630139c592a0b58c71b4/lxml-5.4.0-cp312-cp312-manylinux_2_28_ppc64le.whl", hash = "sha256:2dc191e60425ad70e75a68c9fd90ab284df64d9cd410ba8d2b641c0c45bc006e", size = 5324679 },
+ { url = "https://files.pythonhosted.org/packages/1d/be/ee99e6314cdef4587617d3b3b745f9356d9b7dd12a9663c5f3b5734b64ba/lxml-5.4.0-cp312-cp312-manylinux_2_28_s390x.whl", hash = "sha256:67f779374c6b9753ae0a0195a892a1c234ce8416e4448fe1e9f34746482070a7", size = 4890691 },
+ { url = "https://files.pythonhosted.org/packages/ad/36/239820114bf1d71f38f12208b9c58dec033cbcf80101cde006b9bde5cffd/lxml-5.4.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:79d5bfa9c1b455336f52343130b2067164040604e41f6dc4d8313867ed540079", size = 4955075 },
+ { url = "https://files.pythonhosted.org/packages/d4/e1/1b795cc0b174efc9e13dbd078a9ff79a58728a033142bc6d70a1ee8fc34d/lxml-5.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3d3c30ba1c9b48c68489dc1829a6eede9873f52edca1dda900066542528d6b20", size = 4838680 },
+ { url = "https://files.pythonhosted.org/packages/72/48/3c198455ca108cec5ae3662ae8acd7fd99476812fd712bb17f1b39a0b589/lxml-5.4.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1af80c6316ae68aded77e91cd9d80648f7dd40406cef73df841aa3c36f6907c8", size = 5391253 },
+ { url = "https://files.pythonhosted.org/packages/d6/10/5bf51858971c51ec96cfc13e800a9951f3fd501686f4c18d7d84fe2d6352/lxml-5.4.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:4d885698f5019abe0de3d352caf9466d5de2baded00a06ef3f1216c1a58ae78f", size = 5261651 },
+ { url = "https://files.pythonhosted.org/packages/2b/11/06710dd809205377da380546f91d2ac94bad9ff735a72b64ec029f706c85/lxml-5.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:aea53d51859b6c64e7c51d522c03cc2c48b9b5d6172126854cc7f01aa11f52bc", size = 5024315 },
+ { url = "https://files.pythonhosted.org/packages/f5/b0/15b6217834b5e3a59ebf7f53125e08e318030e8cc0d7310355e6edac98ef/lxml-5.4.0-cp312-cp312-win32.whl", hash = "sha256:d90b729fd2732df28130c064aac9bb8aff14ba20baa4aee7bd0795ff1187545f", size = 3486149 },
+ { url = "https://files.pythonhosted.org/packages/91/1e/05ddcb57ad2f3069101611bd5f5084157d90861a2ef460bf42f45cced944/lxml-5.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:1dc4ca99e89c335a7ed47d38964abcb36c5910790f9bd106f2a8fa2ee0b909d2", size = 3817095 },
+ { url = "https://files.pythonhosted.org/packages/87/cb/2ba1e9dd953415f58548506fa5549a7f373ae55e80c61c9041b7fd09a38a/lxml-5.4.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:773e27b62920199c6197130632c18fb7ead3257fce1ffb7d286912e56ddb79e0", size = 8110086 },
+ { url = "https://files.pythonhosted.org/packages/b5/3e/6602a4dca3ae344e8609914d6ab22e52ce42e3e1638c10967568c5c1450d/lxml-5.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ce9c671845de9699904b1e9df95acfe8dfc183f2310f163cdaa91a3535af95de", size = 4404613 },
+ { url = "https://files.pythonhosted.org/packages/4c/72/bf00988477d3bb452bef9436e45aeea82bb40cdfb4684b83c967c53909c7/lxml-5.4.0-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9454b8d8200ec99a224df8854786262b1bd6461f4280064c807303c642c05e76", size = 5012008 },
+ { url = "https://files.pythonhosted.org/packages/92/1f/93e42d93e9e7a44b2d3354c462cd784dbaaf350f7976b5d7c3f85d68d1b1/lxml-5.4.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cccd007d5c95279e529c146d095f1d39ac05139de26c098166c4beb9374b0f4d", size = 4760915 },
+ { url = "https://files.pythonhosted.org/packages/45/0b/363009390d0b461cf9976a499e83b68f792e4c32ecef092f3f9ef9c4ba54/lxml-5.4.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0fce1294a0497edb034cb416ad3e77ecc89b313cff7adbee5334e4dc0d11f422", size = 5283890 },
+ { url = "https://files.pythonhosted.org/packages/19/dc/6056c332f9378ab476c88e301e6549a0454dbee8f0ae16847414f0eccb74/lxml-5.4.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:24974f774f3a78ac12b95e3a20ef0931795ff04dbb16db81a90c37f589819551", size = 4812644 },
+ { url = "https://files.pythonhosted.org/packages/ee/8a/f8c66bbb23ecb9048a46a5ef9b495fd23f7543df642dabeebcb2eeb66592/lxml-5.4.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:497cab4d8254c2a90bf988f162ace2ddbfdd806fce3bda3f581b9d24c852e03c", size = 4921817 },
+ { url = "https://files.pythonhosted.org/packages/04/57/2e537083c3f381f83d05d9b176f0d838a9e8961f7ed8ddce3f0217179ce3/lxml-5.4.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:e794f698ae4c5084414efea0f5cc9f4ac562ec02d66e1484ff822ef97c2cadff", size = 4753916 },
+ { url = "https://files.pythonhosted.org/packages/d8/80/ea8c4072109a350848f1157ce83ccd9439601274035cd045ac31f47f3417/lxml-5.4.0-cp313-cp313-manylinux_2_28_ppc64le.whl", hash = "sha256:2c62891b1ea3094bb12097822b3d44b93fc6c325f2043c4d2736a8ff09e65f60", size = 5289274 },
+ { url = "https://files.pythonhosted.org/packages/b3/47/c4be287c48cdc304483457878a3f22999098b9a95f455e3c4bda7ec7fc72/lxml-5.4.0-cp313-cp313-manylinux_2_28_s390x.whl", hash = "sha256:142accb3e4d1edae4b392bd165a9abdee8a3c432a2cca193df995bc3886249c8", size = 4874757 },
+ { url = "https://files.pythonhosted.org/packages/2f/04/6ef935dc74e729932e39478e44d8cfe6a83550552eaa072b7c05f6f22488/lxml-5.4.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:1a42b3a19346e5601d1b8296ff6ef3d76038058f311902edd574461e9c036982", size = 4947028 },
+ { url = "https://files.pythonhosted.org/packages/cb/f9/c33fc8daa373ef8a7daddb53175289024512b6619bc9de36d77dca3df44b/lxml-5.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4291d3c409a17febf817259cb37bc62cb7eb398bcc95c1356947e2871911ae61", size = 4834487 },
+ { url = "https://files.pythonhosted.org/packages/8d/30/fc92bb595bcb878311e01b418b57d13900f84c2b94f6eca9e5073ea756e6/lxml-5.4.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4f5322cf38fe0e21c2d73901abf68e6329dc02a4994e483adbcf92b568a09a54", size = 5381688 },
+ { url = "https://files.pythonhosted.org/packages/43/d1/3ba7bd978ce28bba8e3da2c2e9d5ae3f8f521ad3f0ca6ea4788d086ba00d/lxml-5.4.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:0be91891bdb06ebe65122aa6bf3fc94489960cf7e03033c6f83a90863b23c58b", size = 5242043 },
+ { url = "https://files.pythonhosted.org/packages/ee/cd/95fa2201041a610c4d08ddaf31d43b98ecc4b1d74b1e7245b1abdab443cb/lxml-5.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:15a665ad90054a3d4f397bc40f73948d48e36e4c09f9bcffc7d90c87410e478a", size = 5021569 },
+ { url = "https://files.pythonhosted.org/packages/2d/a6/31da006fead660b9512d08d23d31e93ad3477dd47cc42e3285f143443176/lxml-5.4.0-cp313-cp313-win32.whl", hash = "sha256:d5663bc1b471c79f5c833cffbc9b87d7bf13f87e055a5c86c363ccd2348d7e82", size = 3485270 },
+ { url = "https://files.pythonhosted.org/packages/fc/14/c115516c62a7d2499781d2d3d7215218c0731b2c940753bf9f9b7b73924d/lxml-5.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:bcb7a1096b4b6b24ce1ac24d4942ad98f983cd3810f9711bcd0293f43a9d8b9f", size = 3814606 },
+ { url = "https://files.pythonhosted.org/packages/1e/04/acd238222ea25683e43ac7113facc380b3aaf77c53e7d88c4f544cef02ca/lxml-5.4.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:bda3ea44c39eb74e2488297bb39d47186ed01342f0022c8ff407c250ac3f498e", size = 8082189 },
+ { url = "https://files.pythonhosted.org/packages/d6/4e/cc7fe9ccb9999cc648492ce970b63c657606aefc7d0fba46b17aa2ba93fb/lxml-5.4.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9ceaf423b50ecfc23ca00b7f50b64baba85fb3fb91c53e2c9d00bc86150c7e40", size = 4384950 },
+ { url = "https://files.pythonhosted.org/packages/56/bf/acd219c489346d0243a30769b9d446b71e5608581db49a18c8d91a669e19/lxml-5.4.0-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:664cdc733bc87449fe781dbb1f309090966c11cc0c0cd7b84af956a02a8a4729", size = 5209823 },
+ { url = "https://files.pythonhosted.org/packages/57/51/ec31cd33175c09aa7b93d101f56eed43d89e15504455d884d021df7166a7/lxml-5.4.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:67ed8a40665b84d161bae3181aa2763beea3747f748bca5874b4af4d75998f87", size = 4931808 },
+ { url = "https://files.pythonhosted.org/packages/e5/68/865d229f191514da1777125598d028dc88a5ea300d68c30e1f120bfd01bd/lxml-5.4.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9b4a3bd174cc9cdaa1afbc4620c049038b441d6ba07629d89a83b408e54c35cd", size = 5086067 },
+ { url = "https://files.pythonhosted.org/packages/82/01/4c958c5848b4e263cd9e83dff6b49f975a5a0854feb1070dfe0bdcdf70a0/lxml-5.4.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:b0989737a3ba6cf2a16efb857fb0dfa20bc5c542737fddb6d893fde48be45433", size = 4929026 },
+ { url = "https://files.pythonhosted.org/packages/55/31/5327d8af74d7f35e645b40ae6658761e1fee59ebecaa6a8d295e495c2ca9/lxml-5.4.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:dc0af80267edc68adf85f2a5d9be1cdf062f973db6790c1d065e45025fa26140", size = 5134245 },
+ { url = "https://files.pythonhosted.org/packages/6f/c9/204eba2400beb0016dacc2c5335ecb1e37f397796683ffdb7f471e86bddb/lxml-5.4.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:639978bccb04c42677db43c79bdaa23785dc7f9b83bfd87570da8207872f1ce5", size = 5001020 },
+ { url = "https://files.pythonhosted.org/packages/07/53/979165f50a853dab1cf3b9e53105032d55f85c5993f94afc4d9a61a22877/lxml-5.4.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:5a99d86351f9c15e4a901fc56404b485b1462039db59288b203f8c629260a142", size = 5192346 },
+ { url = "https://files.pythonhosted.org/packages/17/2b/f37b5ae28949143f863ba3066b30eede6107fc9a503bd0d01677d4e2a1e0/lxml-5.4.0-cp39-cp39-win32.whl", hash = "sha256:3e6d5557989cdc3ebb5302bbdc42b439733a841891762ded9514e74f60319ad6", size = 3478275 },
+ { url = "https://files.pythonhosted.org/packages/9a/d5/b795a183680126147665a8eeda8e802c180f2f7661aa9a550bba5bcdae63/lxml-5.4.0-cp39-cp39-win_amd64.whl", hash = "sha256:a8c9b7f16b63e65bbba889acb436a1034a82d34fa09752d754f88d708eca80e1", size = 3806275 },
+ { url = "https://files.pythonhosted.org/packages/c6/b0/e4d1cbb8c078bc4ae44de9c6a79fec4e2b4151b1b4d50af71d799e76b177/lxml-5.4.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:1b717b00a71b901b4667226bba282dd462c42ccf618ade12f9ba3674e1fabc55", size = 3892319 },
+ { url = "https://files.pythonhosted.org/packages/5b/aa/e2bdefba40d815059bcb60b371a36fbfcce970a935370e1b367ba1cc8f74/lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27a9ded0f0b52098ff89dd4c418325b987feed2ea5cc86e8860b0f844285d740", size = 4211614 },
+ { url = "https://files.pythonhosted.org/packages/3c/5f/91ff89d1e092e7cfdd8453a939436ac116db0a665e7f4be0cd8e65c7dc5a/lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b7ce10634113651d6f383aa712a194179dcd496bd8c41e191cec2099fa09de5", size = 4306273 },
+ { url = "https://files.pythonhosted.org/packages/be/7c/8c3f15df2ca534589717bfd19d1e3482167801caedfa4d90a575facf68a6/lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:53370c26500d22b45182f98847243efb518d268374a9570409d2e2276232fd37", size = 4208552 },
+ { url = "https://files.pythonhosted.org/packages/7d/d8/9567afb1665f64d73fc54eb904e418d1138d7f011ed00647121b4dd60b38/lxml-5.4.0-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:c6364038c519dffdbe07e3cf42e6a7f8b90c275d4d1617a69bb59734c1a2d571", size = 4331091 },
+ { url = "https://files.pythonhosted.org/packages/f1/ab/fdbbd91d8d82bf1a723ba88ec3e3d76c022b53c391b0c13cad441cdb8f9e/lxml-5.4.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:b12cb6527599808ada9eb2cd6e0e7d3d8f13fe7bbb01c6311255a15ded4c7ab4", size = 3487862 },
+ { url = "https://files.pythonhosted.org/packages/ad/fb/d19b67e4bb63adc20574ba3476cf763b3514df1a37551084b890254e4b15/lxml-5.4.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:9459e6892f59ecea2e2584ee1058f5d8f629446eab52ba2305ae13a32a059530", size = 3891034 },
+ { url = "https://files.pythonhosted.org/packages/c9/5d/6e1033ee0cdb2f9bc93164f9df14e42cb5bbf1bbed3bf67f687de2763104/lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:47fb24cc0f052f0576ea382872b3fc7e1f7e3028e53299ea751839418ade92a6", size = 4207420 },
+ { url = "https://files.pythonhosted.org/packages/f3/4b/23ac79efc32d913259d66672c5f93daac7750a3d97cdc1c1a9a5d1c1b46c/lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:50441c9de951a153c698b9b99992e806b71c1f36d14b154592580ff4a9d0d877", size = 4305106 },
+ { url = "https://files.pythonhosted.org/packages/a4/7a/fe558bee63a62f7a75a52111c0a94556c1c1bdcf558cd7d52861de558759/lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:ab339536aa798b1e17750733663d272038bf28069761d5be57cb4a9b0137b4f8", size = 4205587 },
+ { url = "https://files.pythonhosted.org/packages/ed/5b/3207e6bd8d67c952acfec6bac9d1fa0ee353202e7c40b335ebe00879ab7d/lxml-5.4.0-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:9776af1aad5a4b4a1317242ee2bea51da54b2a7b7b48674be736d463c999f37d", size = 4329077 },
+ { url = "https://files.pythonhosted.org/packages/a1/25/d381abcfd00102d3304aa191caab62f6e3bcbac93ee248771db6be153dfd/lxml-5.4.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:63e7968ff83da2eb6fdda967483a7a023aa497d85ad8f05c3ad9b1f2e8c84987", size = 3486416 },
+]
+
+[[package]]
+name = "markupsafe"
+version = "3.0.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b2/97/5d42485e71dfc078108a86d6de8fa46db44a1a9295e89c5d6d4a06e23a62/markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0", size = 20537 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/90/d08277ce111dd22f77149fd1a5d4653eeb3b3eaacbdfcbae5afb2600eebd/MarkupSafe-3.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7e94c425039cde14257288fd61dcfb01963e658efbc0ff54f5306b06054700f8", size = 14357 },
+ { url = "https://files.pythonhosted.org/packages/04/e1/6e2194baeae0bca1fae6629dc0cbbb968d4d941469cbab11a3872edff374/MarkupSafe-3.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e2d922824181480953426608b81967de705c3cef4d1af983af849d7bd619158", size = 12393 },
+ { url = "https://files.pythonhosted.org/packages/1d/69/35fa85a8ece0a437493dc61ce0bb6d459dcba482c34197e3efc829aa357f/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:38a9ef736c01fccdd6600705b09dc574584b89bea478200c5fbf112a6b0d5579", size = 21732 },
+ { url = "https://files.pythonhosted.org/packages/22/35/137da042dfb4720b638d2937c38a9c2df83fe32d20e8c8f3185dbfef05f7/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbcb445fa71794da8f178f0f6d66789a28d7319071af7a496d4d507ed566270d", size = 20866 },
+ { url = "https://files.pythonhosted.org/packages/29/28/6d029a903727a1b62edb51863232152fd335d602def598dade38996887f0/MarkupSafe-3.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:57cb5a3cf367aeb1d316576250f65edec5bb3be939e9247ae594b4bcbc317dfb", size = 20964 },
+ { url = "https://files.pythonhosted.org/packages/cc/cd/07438f95f83e8bc028279909d9c9bd39e24149b0d60053a97b2bc4f8aa51/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3809ede931876f5b2ec92eef964286840ed3540dadf803dd570c3b7e13141a3b", size = 21977 },
+ { url = "https://files.pythonhosted.org/packages/29/01/84b57395b4cc062f9c4c55ce0df7d3108ca32397299d9df00fedd9117d3d/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e07c3764494e3776c602c1e78e298937c3315ccc9043ead7e685b7f2b8d47b3c", size = 21366 },
+ { url = "https://files.pythonhosted.org/packages/bd/6e/61ebf08d8940553afff20d1fb1ba7294b6f8d279df9fd0c0db911b4bbcfd/MarkupSafe-3.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b424c77b206d63d500bcb69fa55ed8d0e6a3774056bdc4839fc9298a7edca171", size = 21091 },
+ { url = "https://files.pythonhosted.org/packages/11/23/ffbf53694e8c94ebd1e7e491de185124277964344733c45481f32ede2499/MarkupSafe-3.0.2-cp310-cp310-win32.whl", hash = "sha256:fcabf5ff6eea076f859677f5f0b6b5c1a51e70a376b0579e0eadef8db48c6b50", size = 15065 },
+ { url = "https://files.pythonhosted.org/packages/44/06/e7175d06dd6e9172d4a69a72592cb3f7a996a9c396eee29082826449bbc3/MarkupSafe-3.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:6af100e168aa82a50e186c82875a5893c5597a0c1ccdb0d8b40240b1f28b969a", size = 15514 },
+ { url = "https://files.pythonhosted.org/packages/6b/28/bbf83e3f76936960b850435576dd5e67034e200469571be53f69174a2dfd/MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d", size = 14353 },
+ { url = "https://files.pythonhosted.org/packages/6c/30/316d194b093cde57d448a4c3209f22e3046c5bb2fb0820b118292b334be7/MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93", size = 12392 },
+ { url = "https://files.pythonhosted.org/packages/f2/96/9cdafba8445d3a53cae530aaf83c38ec64c4d5427d975c974084af5bc5d2/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832", size = 23984 },
+ { url = "https://files.pythonhosted.org/packages/f1/a4/aefb044a2cd8d7334c8a47d3fb2c9f328ac48cb349468cc31c20b539305f/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84", size = 23120 },
+ { url = "https://files.pythonhosted.org/packages/8d/21/5e4851379f88f3fad1de30361db501300d4f07bcad047d3cb0449fc51f8c/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca", size = 23032 },
+ { url = "https://files.pythonhosted.org/packages/00/7b/e92c64e079b2d0d7ddf69899c98842f3f9a60a1ae72657c89ce2655c999d/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798", size = 24057 },
+ { url = "https://files.pythonhosted.org/packages/f9/ac/46f960ca323037caa0a10662ef97d0a4728e890334fc156b9f9e52bcc4ca/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e", size = 23359 },
+ { url = "https://files.pythonhosted.org/packages/69/84/83439e16197337b8b14b6a5b9c2105fff81d42c2a7c5b58ac7b62ee2c3b1/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4", size = 23306 },
+ { url = "https://files.pythonhosted.org/packages/9a/34/a15aa69f01e2181ed8d2b685c0d2f6655d5cca2c4db0ddea775e631918cd/MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d", size = 15094 },
+ { url = "https://files.pythonhosted.org/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b", size = 15521 },
+ { url = "https://files.pythonhosted.org/packages/22/09/d1f21434c97fc42f09d290cbb6350d44eb12f09cc62c9476effdb33a18aa/MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf", size = 14274 },
+ { url = "https://files.pythonhosted.org/packages/6b/b0/18f76bba336fa5aecf79d45dcd6c806c280ec44538b3c13671d49099fdd0/MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225", size = 12348 },
+ { url = "https://files.pythonhosted.org/packages/e0/25/dd5c0f6ac1311e9b40f4af06c78efde0f3b5cbf02502f8ef9501294c425b/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028", size = 24149 },
+ { url = "https://files.pythonhosted.org/packages/f3/f0/89e7aadfb3749d0f52234a0c8c7867877876e0a20b60e2188e9850794c17/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e17c96c14e19278594aa4841ec148115f9c7615a47382ecb6b82bd8fea3ab0c8", size = 23118 },
+ { url = "https://files.pythonhosted.org/packages/d5/da/f2eeb64c723f5e3777bc081da884b414671982008c47dcc1873d81f625b6/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:88416bd1e65dcea10bc7569faacb2c20ce071dd1f87539ca2ab364bf6231393c", size = 22993 },
+ { url = "https://files.pythonhosted.org/packages/da/0e/1f32af846df486dce7c227fe0f2398dc7e2e51d4a370508281f3c1c5cddc/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2181e67807fc2fa785d0592dc2d6206c019b9502410671cc905d132a92866557", size = 24178 },
+ { url = "https://files.pythonhosted.org/packages/c4/f6/bb3ca0532de8086cbff5f06d137064c8410d10779c4c127e0e47d17c0b71/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:52305740fe773d09cffb16f8ed0427942901f00adedac82ec8b67752f58a1b22", size = 23319 },
+ { url = "https://files.pythonhosted.org/packages/a2/82/8be4c96ffee03c5b4a034e60a31294daf481e12c7c43ab8e34a1453ee48b/MarkupSafe-3.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad10d3ded218f1039f11a75f8091880239651b52e9bb592ca27de44eed242a48", size = 23352 },
+ { url = "https://files.pythonhosted.org/packages/51/ae/97827349d3fcffee7e184bdf7f41cd6b88d9919c80f0263ba7acd1bbcb18/MarkupSafe-3.0.2-cp312-cp312-win32.whl", hash = "sha256:0f4ca02bea9a23221c0182836703cbf8930c5e9454bacce27e767509fa286a30", size = 15097 },
+ { url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601 },
+ { url = "https://files.pythonhosted.org/packages/83/0e/67eb10a7ecc77a0c2bbe2b0235765b98d164d81600746914bebada795e97/MarkupSafe-3.0.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ba9527cdd4c926ed0760bc301f6728ef34d841f405abf9d4f959c478421e4efd", size = 14274 },
+ { url = "https://files.pythonhosted.org/packages/2b/6d/9409f3684d3335375d04e5f05744dfe7e9f120062c9857df4ab490a1031a/MarkupSafe-3.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f8b3d067f2e40fe93e1ccdd6b2e1d16c43140e76f02fb1319a05cf2b79d99430", size = 12352 },
+ { url = "https://files.pythonhosted.org/packages/d2/f5/6eadfcd3885ea85fe2a7c128315cc1bb7241e1987443d78c8fe712d03091/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:569511d3b58c8791ab4c2e1285575265991e6d8f8700c7be0e88f86cb0672094", size = 24122 },
+ { url = "https://files.pythonhosted.org/packages/0c/91/96cf928db8236f1bfab6ce15ad070dfdd02ed88261c2afafd4b43575e9e9/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15ab75ef81add55874e7ab7055e9c397312385bd9ced94920f2802310c930396", size = 23085 },
+ { url = "https://files.pythonhosted.org/packages/c2/cf/c9d56af24d56ea04daae7ac0940232d31d5a8354f2b457c6d856b2057d69/MarkupSafe-3.0.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f3818cb119498c0678015754eba762e0d61e5b52d34c8b13d770f0719f7b1d79", size = 22978 },
+ { url = "https://files.pythonhosted.org/packages/2a/9f/8619835cd6a711d6272d62abb78c033bda638fdc54c4e7f4272cf1c0962b/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cdb82a876c47801bb54a690c5ae105a46b392ac6099881cdfb9f6e95e4014c6a", size = 24208 },
+ { url = "https://files.pythonhosted.org/packages/f9/bf/176950a1792b2cd2102b8ffeb5133e1ed984547b75db47c25a67d3359f77/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cabc348d87e913db6ab4aa100f01b08f481097838bdddf7c7a84b7575b7309ca", size = 23357 },
+ { url = "https://files.pythonhosted.org/packages/ce/4f/9a02c1d335caabe5c4efb90e1b6e8ee944aa245c1aaaab8e8a618987d816/MarkupSafe-3.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:444dcda765c8a838eaae23112db52f1efaf750daddb2d9ca300bcae1039adc5c", size = 23344 },
+ { url = "https://files.pythonhosted.org/packages/ee/55/c271b57db36f748f0e04a759ace9f8f759ccf22b4960c270c78a394f58be/MarkupSafe-3.0.2-cp313-cp313-win32.whl", hash = "sha256:bcf3e58998965654fdaff38e58584d8937aa3096ab5354d493c77d1fdd66d7a1", size = 15101 },
+ { url = "https://files.pythonhosted.org/packages/29/88/07df22d2dd4df40aba9f3e402e6dc1b8ee86297dddbad4872bd5e7b0094f/MarkupSafe-3.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:e6a2a455bd412959b57a172ce6328d2dd1f01cb2135efda2e4576e8a23fa3b0f", size = 15603 },
+ { url = "https://files.pythonhosted.org/packages/62/6a/8b89d24db2d32d433dffcd6a8779159da109842434f1dd2f6e71f32f738c/MarkupSafe-3.0.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b5a6b3ada725cea8a5e634536b1b01c30bcdcd7f9c6fff4151548d5bf6b3a36c", size = 14510 },
+ { url = "https://files.pythonhosted.org/packages/7a/06/a10f955f70a2e5a9bf78d11a161029d278eeacbd35ef806c3fd17b13060d/MarkupSafe-3.0.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:a904af0a6162c73e3edcb969eeeb53a63ceeb5d8cf642fade7d39e7963a22ddb", size = 12486 },
+ { url = "https://files.pythonhosted.org/packages/34/cf/65d4a571869a1a9078198ca28f39fba5fbb910f952f9dbc5220afff9f5e6/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4aa4e5faecf353ed117801a068ebab7b7e09ffb6e1d5e412dc852e0da018126c", size = 25480 },
+ { url = "https://files.pythonhosted.org/packages/0c/e3/90e9651924c430b885468b56b3d597cabf6d72be4b24a0acd1fa0e12af67/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0ef13eaeee5b615fb07c9a7dadb38eac06a0608b41570d8ade51c56539e509d", size = 23914 },
+ { url = "https://files.pythonhosted.org/packages/66/8c/6c7cf61f95d63bb866db39085150df1f2a5bd3335298f14a66b48e92659c/MarkupSafe-3.0.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d16a81a06776313e817c951135cf7340a3e91e8c1ff2fac444cfd75fffa04afe", size = 23796 },
+ { url = "https://files.pythonhosted.org/packages/bb/35/cbe9238ec3f47ac9a7c8b3df7a808e7cb50fe149dc7039f5f454b3fba218/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:6381026f158fdb7c72a168278597a5e3a5222e83ea18f543112b2662a9b699c5", size = 25473 },
+ { url = "https://files.pythonhosted.org/packages/e6/32/7621a4382488aa283cc05e8984a9c219abad3bca087be9ec77e89939ded9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:3d79d162e7be8f996986c064d1c7c817f6df3a77fe3d6859f6f9e7be4b8c213a", size = 24114 },
+ { url = "https://files.pythonhosted.org/packages/0d/80/0985960e4b89922cb5a0bac0ed39c5b96cbc1a536a99f30e8c220a996ed9/MarkupSafe-3.0.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:131a3c7689c85f5ad20f9f6fb1b866f402c445b220c19fe4308c0b147ccd2ad9", size = 24098 },
+ { url = "https://files.pythonhosted.org/packages/82/78/fedb03c7d5380df2427038ec8d973587e90561b2d90cd472ce9254cf348b/MarkupSafe-3.0.2-cp313-cp313t-win32.whl", hash = "sha256:ba8062ed2cf21c07a9e295d5b8a2a5ce678b913b45fdf68c32d95d6c1291e0b6", size = 15208 },
+ { url = "https://files.pythonhosted.org/packages/4f/65/6079a46068dfceaeabb5dcad6d674f5f5c61a6fa5673746f42a9f4c233b3/MarkupSafe-3.0.2-cp313-cp313t-win_amd64.whl", hash = "sha256:e444a31f8db13eb18ada366ab3cf45fd4b31e4db1236a4448f68778c1d1a5a2f", size = 15739 },
+ { url = "https://files.pythonhosted.org/packages/a7/ea/9b1530c3fdeeca613faeb0fb5cbcf2389d816072fab72a71b45749ef6062/MarkupSafe-3.0.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:eaa0a10b7f72326f1372a713e73c3f739b524b3af41feb43e4921cb529f5929a", size = 14344 },
+ { url = "https://files.pythonhosted.org/packages/4b/c2/fbdbfe48848e7112ab05e627e718e854d20192b674952d9042ebd8c9e5de/MarkupSafe-3.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:48032821bbdf20f5799ff537c7ac3d1fba0ba032cfc06194faffa8cda8b560ff", size = 12389 },
+ { url = "https://files.pythonhosted.org/packages/f0/25/7a7c6e4dbd4f867d95d94ca15449e91e52856f6ed1905d58ef1de5e211d0/MarkupSafe-3.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1a9d3f5f0901fdec14d8d2f66ef7d035f2157240a433441719ac9a3fba440b13", size = 21607 },
+ { url = "https://files.pythonhosted.org/packages/53/8f/f339c98a178f3c1e545622206b40986a4c3307fe39f70ccd3d9df9a9e425/MarkupSafe-3.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:88b49a3b9ff31e19998750c38e030fc7bb937398b1f78cfa599aaef92d693144", size = 20728 },
+ { url = "https://files.pythonhosted.org/packages/1a/03/8496a1a78308456dbd50b23a385c69b41f2e9661c67ea1329849a598a8f9/MarkupSafe-3.0.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cfad01eed2c2e0c01fd0ecd2ef42c492f7f93902e39a42fc9ee1692961443a29", size = 20826 },
+ { url = "https://files.pythonhosted.org/packages/e6/cf/0a490a4bd363048c3022f2f475c8c05582179bb179defcee4766fb3dcc18/MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:1225beacc926f536dc82e45f8a4d68502949dc67eea90eab715dea3a21c1b5f0", size = 21843 },
+ { url = "https://files.pythonhosted.org/packages/19/a3/34187a78613920dfd3cdf68ef6ce5e99c4f3417f035694074beb8848cd77/MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:3169b1eefae027567d1ce6ee7cae382c57fe26e82775f460f0b2778beaad66c0", size = 21219 },
+ { url = "https://files.pythonhosted.org/packages/17/d8/5811082f85bb88410ad7e452263af048d685669bbbfb7b595e8689152498/MarkupSafe-3.0.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:eb7972a85c54febfb25b5c4b4f3af4dcc731994c7da0d8a0b4a6eb0640e1d178", size = 20946 },
+ { url = "https://files.pythonhosted.org/packages/7c/31/bd635fb5989440d9365c5e3c47556cfea121c7803f5034ac843e8f37c2f2/MarkupSafe-3.0.2-cp39-cp39-win32.whl", hash = "sha256:8c4e8c3ce11e1f92f6536ff07154f9d49677ebaaafc32db9db4620bc11ed480f", size = 15063 },
+ { url = "https://files.pythonhosted.org/packages/b3/73/085399401383ce949f727afec55ec3abd76648d04b9f22e1c0e99cb4bec3/MarkupSafe-3.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:6e296a513ca3d94054c2c881cc913116e90fd030ad1c656b3869762b754f5f8a", size = 15506 },
+]
+
+[[package]]
+name = "marshmallow"
+version = "3.26.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "packaging" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ab/5e/5e53d26b42ab75491cda89b871dab9e97c840bf12c63ec58a1919710cd06/marshmallow-3.26.1.tar.gz", hash = "sha256:e6d8affb6cb61d39d26402096dc0aee12d5a26d490a121f118d2e81dc0719dc6", size = 221825 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/34/75/51952c7b2d3873b44a0028b1bd26a25078c18f92f256608e8d1dc61b39fd/marshmallow-3.26.1-py3-none-any.whl", hash = "sha256:3350409f20a70a7e4e11a27661187b77cdcaeb20abca41c1454fe33636bea09c", size = 50878 },
+]
+
+[[package]]
+name = "matplotlib"
+version = "3.9.4"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "contourpy", version = "1.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "cycler", marker = "python_full_version < '3.10'" },
+ { name = "fonttools", marker = "python_full_version < '3.10'" },
+ { name = "importlib-resources", marker = "python_full_version < '3.10'" },
+ { name = "kiwisolver", version = "1.4.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "numpy", marker = "python_full_version < '3.10'" },
+ { name = "packaging", marker = "python_full_version < '3.10'" },
+ { name = "pillow", marker = "python_full_version < '3.10'" },
+ { name = "pyparsing", marker = "python_full_version < '3.10'" },
+ { name = "python-dateutil", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/df/17/1747b4154034befd0ed33b52538f5eb7752d05bb51c5e2a31470c3bc7d52/matplotlib-3.9.4.tar.gz", hash = "sha256:1e00e8be7393cbdc6fedfa8a6fba02cf3e83814b285db1c60b906a023ba41bc3", size = 36106529 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/94/27d2e2c30d54b56c7b764acc1874a909e34d1965a427fc7092bb6a588b63/matplotlib-3.9.4-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:c5fdd7abfb706dfa8d307af64a87f1a862879ec3cd8d0ec8637458f0885b9c50", size = 7885089 },
+ { url = "https://files.pythonhosted.org/packages/c6/25/828273307e40a68eb8e9df832b6b2aaad075864fdc1de4b1b81e40b09e48/matplotlib-3.9.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d89bc4e85e40a71d1477780366c27fb7c6494d293e1617788986f74e2a03d7ff", size = 7770600 },
+ { url = "https://files.pythonhosted.org/packages/f2/65/f841a422ec994da5123368d76b126acf4fc02ea7459b6e37c4891b555b83/matplotlib-3.9.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ddf9f3c26aae695c5daafbf6b94e4c1a30d6cd617ba594bbbded3b33a1fcfa26", size = 8200138 },
+ { url = "https://files.pythonhosted.org/packages/07/06/272aca07a38804d93b6050813de41ca7ab0e29ba7a9dd098e12037c919a9/matplotlib-3.9.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:18ebcf248030173b59a868fda1fe42397253f6698995b55e81e1f57431d85e50", size = 8312711 },
+ { url = "https://files.pythonhosted.org/packages/98/37/f13e23b233c526b7e27ad61be0a771894a079e0f7494a10d8d81557e0e9a/matplotlib-3.9.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:974896ec43c672ec23f3f8c648981e8bc880ee163146e0312a9b8def2fac66f5", size = 9090622 },
+ { url = "https://files.pythonhosted.org/packages/4f/8c/b1f5bd2bd70e60f93b1b54c4d5ba7a992312021d0ddddf572f9a1a6d9348/matplotlib-3.9.4-cp310-cp310-win_amd64.whl", hash = "sha256:4598c394ae9711cec135639374e70871fa36b56afae17bdf032a345be552a88d", size = 7828211 },
+ { url = "https://files.pythonhosted.org/packages/74/4b/65be7959a8fa118a3929b49a842de5b78bb55475236fcf64f3e308ff74a0/matplotlib-3.9.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:d4dd29641d9fb8bc4492420c5480398dd40a09afd73aebe4eb9d0071a05fbe0c", size = 7894430 },
+ { url = "https://files.pythonhosted.org/packages/e9/18/80f70d91896e0a517b4a051c3fd540daa131630fd75e02e250365353b253/matplotlib-3.9.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30e5b22e8bcfb95442bf7d48b0d7f3bdf4a450cbf68986ea45fca3d11ae9d099", size = 7780045 },
+ { url = "https://files.pythonhosted.org/packages/a2/73/ccb381026e3238c5c25c3609ba4157b2d1a617ec98d65a8b4ee4e1e74d02/matplotlib-3.9.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2bb0030d1d447fd56dcc23b4c64a26e44e898f0416276cac1ebc25522e0ac249", size = 8209906 },
+ { url = "https://files.pythonhosted.org/packages/ab/33/1648da77b74741c89f5ea95cbf42a291b4b364f2660b316318811404ed97/matplotlib-3.9.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aca90ed222ac3565d2752b83dbb27627480d27662671e4d39da72e97f657a423", size = 8322873 },
+ { url = "https://files.pythonhosted.org/packages/57/d3/8447ba78bc6593c9044c372d1609f8ea10fb1e071e7a9e0747bea74fc16c/matplotlib-3.9.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a181b2aa2906c608fcae72f977a4a2d76e385578939891b91c2550c39ecf361e", size = 9099566 },
+ { url = "https://files.pythonhosted.org/packages/23/e1/4f0e237bf349c02ff9d1b6e7109f1a17f745263809b9714a8576dc17752b/matplotlib-3.9.4-cp311-cp311-win_amd64.whl", hash = "sha256:1f6882828231eca17f501c4dcd98a05abb3f03d157fbc0769c6911fe08b6cfd3", size = 7838065 },
+ { url = "https://files.pythonhosted.org/packages/1a/2b/c918bf6c19d6445d1cefe3d2e42cb740fb997e14ab19d4daeb6a7ab8a157/matplotlib-3.9.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:dfc48d67e6661378a21c2983200a654b72b5c5cdbd5d2cf6e5e1ece860f0cc70", size = 7891131 },
+ { url = "https://files.pythonhosted.org/packages/c1/e5/b4e8fc601ca302afeeabf45f30e706a445c7979a180e3a978b78b2b681a4/matplotlib-3.9.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:47aef0fab8332d02d68e786eba8113ffd6f862182ea2999379dec9e237b7e483", size = 7776365 },
+ { url = "https://files.pythonhosted.org/packages/99/06/b991886c506506476e5d83625c5970c656a491b9f80161458fed94597808/matplotlib-3.9.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fba1f52c6b7dc764097f52fd9ab627b90db452c9feb653a59945de16752e965f", size = 8200707 },
+ { url = "https://files.pythonhosted.org/packages/c3/e2/556b627498cb27e61026f2d1ba86a78ad1b836fef0996bef5440e8bc9559/matplotlib-3.9.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:173ac3748acaac21afcc3fa1633924609ba1b87749006bc25051c52c422a5d00", size = 8313761 },
+ { url = "https://files.pythonhosted.org/packages/58/ff/165af33ec766ff818306ea88e91f9f60d2a6ed543be1eb122a98acbf3b0d/matplotlib-3.9.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:320edea0cadc07007765e33f878b13b3738ffa9745c5f707705692df70ffe0e0", size = 9095284 },
+ { url = "https://files.pythonhosted.org/packages/9f/8b/3d0c7a002db3b1ed702731c2a9a06d78d035f1f2fb0fb936a8e43cc1e9f4/matplotlib-3.9.4-cp312-cp312-win_amd64.whl", hash = "sha256:a4a4cfc82330b27042a7169533da7991e8789d180dd5b3daeaee57d75cd5a03b", size = 7841160 },
+ { url = "https://files.pythonhosted.org/packages/49/b1/999f89a7556d101b23a2f0b54f1b6e140d73f56804da1398f2f0bc0924bc/matplotlib-3.9.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:37eeffeeca3c940985b80f5b9a7b95ea35671e0e7405001f249848d2b62351b6", size = 7891499 },
+ { url = "https://files.pythonhosted.org/packages/87/7b/06a32b13a684977653396a1bfcd34d4e7539c5d55c8cbfaa8ae04d47e4a9/matplotlib-3.9.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3e7465ac859ee4abcb0d836137cd8414e7bb7ad330d905abced457217d4f0f45", size = 7776802 },
+ { url = "https://files.pythonhosted.org/packages/65/87/ac498451aff739e515891bbb92e566f3c7ef31891aaa878402a71f9b0910/matplotlib-3.9.4-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f4c12302c34afa0cf061bea23b331e747e5e554b0fa595c96e01c7b75bc3b858", size = 8200802 },
+ { url = "https://files.pythonhosted.org/packages/f8/6b/9eb761c00e1cb838f6c92e5f25dcda3f56a87a52f6cb8fdfa561e6cf6a13/matplotlib-3.9.4-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2b8c97917f21b75e72108b97707ba3d48f171541a74aa2a56df7a40626bafc64", size = 8313880 },
+ { url = "https://files.pythonhosted.org/packages/d7/a2/c8eaa600e2085eec7e38cbbcc58a30fc78f8224939d31d3152bdafc01fd1/matplotlib-3.9.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:0229803bd7e19271b03cb09f27db76c918c467aa4ce2ae168171bc67c3f508df", size = 9094637 },
+ { url = "https://files.pythonhosted.org/packages/71/1f/c6e1daea55b7bfeb3d84c6cb1abc449f6a02b181e7e2a5e4db34c3afb793/matplotlib-3.9.4-cp313-cp313-win_amd64.whl", hash = "sha256:7c0d8ef442ebf56ff5e206f8083d08252ee738e04f3dc88ea882853a05488799", size = 7841311 },
+ { url = "https://files.pythonhosted.org/packages/c0/3a/2757d3f7d388b14dd48f5a83bea65b6d69f000e86b8f28f74d86e0d375bd/matplotlib-3.9.4-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:a04c3b00066a688834356d196136349cb32f5e1003c55ac419e91585168b88fb", size = 7919989 },
+ { url = "https://files.pythonhosted.org/packages/24/28/f5077c79a4f521589a37fe1062d6a6ea3534e068213f7357e7cfffc2e17a/matplotlib-3.9.4-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:04c519587f6c210626741a1e9a68eefc05966ede24205db8982841826af5871a", size = 7809417 },
+ { url = "https://files.pythonhosted.org/packages/36/c8/c523fd2963156692916a8eb7d4069084cf729359f7955cf09075deddfeaf/matplotlib-3.9.4-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:308afbf1a228b8b525fcd5cec17f246bbbb63b175a3ef6eb7b4d33287ca0cf0c", size = 8226258 },
+ { url = "https://files.pythonhosted.org/packages/f6/88/499bf4b8fa9349b6f5c0cf4cead0ebe5da9d67769129f1b5651e5ac51fbc/matplotlib-3.9.4-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ddb3b02246ddcffd3ce98e88fed5b238bc5faff10dbbaa42090ea13241d15764", size = 8335849 },
+ { url = "https://files.pythonhosted.org/packages/b8/9f/20a4156b9726188646a030774ee337d5ff695a965be45ce4dbcb9312c170/matplotlib-3.9.4-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8a75287e9cb9eee48cb79ec1d806f75b29c0fde978cb7223a1f4c5848d696041", size = 9102152 },
+ { url = "https://files.pythonhosted.org/packages/10/11/237f9c3a4e8d810b1759b67ff2da7c32c04f9c80aa475e7beb36ed43a8fb/matplotlib-3.9.4-cp313-cp313t-win_amd64.whl", hash = "sha256:488deb7af140f0ba86da003e66e10d55ff915e152c78b4b66d231638400b1965", size = 7896987 },
+ { url = "https://files.pythonhosted.org/packages/56/eb/501b465c9fef28f158e414ea3a417913dc2ac748564c7ed41535f23445b4/matplotlib-3.9.4-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:3c3724d89a387ddf78ff88d2a30ca78ac2b4c89cf37f2db4bd453c34799e933c", size = 7885919 },
+ { url = "https://files.pythonhosted.org/packages/da/36/236fbd868b6c91309a5206bd90c3f881f4f44b2d997cd1d6239ef652f878/matplotlib-3.9.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:d5f0a8430ffe23d7e32cfd86445864ccad141797f7d25b7c41759a5b5d17cfd7", size = 7771486 },
+ { url = "https://files.pythonhosted.org/packages/e0/4b/105caf2d54d5ed11d9f4335398f5103001a03515f2126c936a752ccf1461/matplotlib-3.9.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6bb0141a21aef3b64b633dc4d16cbd5fc538b727e4958be82a0e1c92a234160e", size = 8201838 },
+ { url = "https://files.pythonhosted.org/packages/5d/a7/bb01188fb4013d34d274caf44a2f8091255b0497438e8b6c0a7c1710c692/matplotlib-3.9.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:57aa235109e9eed52e2c2949db17da185383fa71083c00c6c143a60e07e0888c", size = 8314492 },
+ { url = "https://files.pythonhosted.org/packages/33/19/02e1a37f7141fc605b193e927d0a9cdf9dc124a20b9e68793f4ffea19695/matplotlib-3.9.4-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:b18c600061477ccfdd1e6fd050c33d8be82431700f3452b297a56d9ed7037abb", size = 9092500 },
+ { url = "https://files.pythonhosted.org/packages/57/68/c2feb4667adbf882ffa4b3e0ac9967f848980d9f8b5bebd86644aa67ce6a/matplotlib-3.9.4-cp39-cp39-win_amd64.whl", hash = "sha256:ef5f2d1b67d2d2145ff75e10f8c008bfbf71d45137c4b648c87193e7dd053eac", size = 7822962 },
+ { url = "https://files.pythonhosted.org/packages/0c/22/2ef6a364cd3f565442b0b055e0599744f1e4314ec7326cdaaa48a4d864d7/matplotlib-3.9.4-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:44e0ed786d769d85bc787b0606a53f2d8d2d1d3c8a2608237365e9121c1a338c", size = 7877995 },
+ { url = "https://files.pythonhosted.org/packages/87/b8/2737456e566e9f4d94ae76b8aa0d953d9acb847714f9a7ad80184474f5be/matplotlib-3.9.4-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:09debb9ce941eb23ecdbe7eab972b1c3e0276dcf01688073faff7b0f61d6c6ca", size = 7769300 },
+ { url = "https://files.pythonhosted.org/packages/b2/1f/e709c6ec7b5321e6568769baa288c7178e60a93a9da9e682b39450da0e29/matplotlib-3.9.4-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bcc53cf157a657bfd03afab14774d54ba73aa84d42cfe2480c91bd94873952db", size = 8313423 },
+ { url = "https://files.pythonhosted.org/packages/5e/b6/5a1f868782cd13f053a679984e222007ecff654a9bfbac6b27a65f4eeb05/matplotlib-3.9.4-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:ad45da51be7ad02387801fd154ef74d942f49fe3fcd26a64c94842ba7ec0d865", size = 7854624 },
+]
+
+[[package]]
+name = "matplotlib"
+version = "3.10.3"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "contourpy", version = "1.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "cycler", marker = "python_full_version >= '3.10'" },
+ { name = "fonttools", marker = "python_full_version >= '3.10'" },
+ { name = "kiwisolver", version = "1.4.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "numpy", marker = "python_full_version >= '3.10'" },
+ { name = "packaging", marker = "python_full_version >= '3.10'" },
+ { name = "pillow", marker = "python_full_version >= '3.10'" },
+ { name = "pyparsing", marker = "python_full_version >= '3.10'" },
+ { name = "python-dateutil", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/26/91/d49359a21893183ed2a5b6c76bec40e0b1dcbf8ca148f864d134897cfc75/matplotlib-3.10.3.tar.gz", hash = "sha256:2f82d2c5bb7ae93aaaa4cd42aca65d76ce6376f83304fa3a630b569aca274df0", size = 34799811 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d0/ea/2bba25d289d389c7451f331ecd593944b3705f06ddf593fa7be75037d308/matplotlib-3.10.3-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:213fadd6348d106ca7db99e113f1bea1e65e383c3ba76e8556ba4a3054b65ae7", size = 8167862 },
+ { url = "https://files.pythonhosted.org/packages/41/81/cc70b5138c926604e8c9ed810ed4c79e8116ba72e02230852f5c12c87ba2/matplotlib-3.10.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d3bec61cb8221f0ca6313889308326e7bb303d0d302c5cc9e523b2f2e6c73deb", size = 8042149 },
+ { url = "https://files.pythonhosted.org/packages/4a/9a/0ff45b6bfa42bb16de597e6058edf2361c298ad5ef93b327728145161bbf/matplotlib-3.10.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8c21ae75651c0231b3ba014b6d5e08fb969c40cdb5a011e33e99ed0c9ea86ecb", size = 8453719 },
+ { url = "https://files.pythonhosted.org/packages/85/c7/1866e972fed6d71ef136efbc980d4d1854ab7ef1ea8152bbd995ca231c81/matplotlib-3.10.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a49e39755580b08e30e3620efc659330eac5d6534ab7eae50fa5e31f53ee4e30", size = 8590801 },
+ { url = "https://files.pythonhosted.org/packages/5d/b9/748f6626d534ab7e255bdc39dc22634d337cf3ce200f261b5d65742044a1/matplotlib-3.10.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cf4636203e1190871d3a73664dea03d26fb019b66692cbfd642faafdad6208e8", size = 9402111 },
+ { url = "https://files.pythonhosted.org/packages/1f/78/8bf07bd8fb67ea5665a6af188e70b57fcb2ab67057daa06b85a08e59160a/matplotlib-3.10.3-cp310-cp310-win_amd64.whl", hash = "sha256:fd5641a9bb9d55f4dd2afe897a53b537c834b9012684c8444cc105895c8c16fd", size = 8057213 },
+ { url = "https://files.pythonhosted.org/packages/f5/bd/af9f655456f60fe1d575f54fb14704ee299b16e999704817a7645dfce6b0/matplotlib-3.10.3-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:0ef061f74cd488586f552d0c336b2f078d43bc00dc473d2c3e7bfee2272f3fa8", size = 8178873 },
+ { url = "https://files.pythonhosted.org/packages/c2/86/e1c86690610661cd716eda5f9d0b35eaf606ae6c9b6736687cfc8f2d0cd8/matplotlib-3.10.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d96985d14dc5f4a736bbea4b9de9afaa735f8a0fc2ca75be2fa9e96b2097369d", size = 8052205 },
+ { url = "https://files.pythonhosted.org/packages/54/51/a9f8e49af3883dacddb2da1af5fca1f7468677f1188936452dd9aaaeb9ed/matplotlib-3.10.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7c5f0283da91e9522bdba4d6583ed9d5521566f63729ffb68334f86d0bb98049", size = 8465823 },
+ { url = "https://files.pythonhosted.org/packages/e7/e3/c82963a3b86d6e6d5874cbeaa390166458a7f1961bab9feb14d3d1a10f02/matplotlib-3.10.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdfa07c0ec58035242bc8b2c8aae37037c9a886370eef6850703d7583e19964b", size = 8606464 },
+ { url = "https://files.pythonhosted.org/packages/0e/34/24da1027e7fcdd9e82da3194c470143c551852757a4b473a09a012f5b945/matplotlib-3.10.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c0b9849a17bce080a16ebcb80a7b714b5677d0ec32161a2cc0a8e5a6030ae220", size = 9413103 },
+ { url = "https://files.pythonhosted.org/packages/a6/da/948a017c3ea13fd4a97afad5fdebe2f5bbc4d28c0654510ce6fd6b06b7bd/matplotlib-3.10.3-cp311-cp311-win_amd64.whl", hash = "sha256:eef6ed6c03717083bc6d69c2d7ee8624205c29a8e6ea5a31cd3492ecdbaee1e1", size = 8065492 },
+ { url = "https://files.pythonhosted.org/packages/eb/43/6b80eb47d1071f234ef0c96ca370c2ca621f91c12045f1401b5c9b28a639/matplotlib-3.10.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ab1affc11d1f495ab9e6362b8174a25afc19c081ba5b0775ef00533a4236eea", size = 8179689 },
+ { url = "https://files.pythonhosted.org/packages/0f/70/d61a591958325c357204870b5e7b164f93f2a8cca1dc6ce940f563909a13/matplotlib-3.10.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2a818d8bdcafa7ed2eed74487fdb071c09c1ae24152d403952adad11fa3c65b4", size = 8050466 },
+ { url = "https://files.pythonhosted.org/packages/e7/75/70c9d2306203148cc7902a961240c5927dd8728afedf35e6a77e105a2985/matplotlib-3.10.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:748ebc3470c253e770b17d8b0557f0aa85cf8c63fd52f1a61af5b27ec0b7ffee", size = 8456252 },
+ { url = "https://files.pythonhosted.org/packages/c4/91/ba0ae1ff4b3f30972ad01cd4a8029e70a0ec3b8ea5be04764b128b66f763/matplotlib-3.10.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ed70453fd99733293ace1aec568255bc51c6361cb0da94fa5ebf0649fdb2150a", size = 8601321 },
+ { url = "https://files.pythonhosted.org/packages/d2/88/d636041eb54a84b889e11872d91f7cbf036b3b0e194a70fa064eb8b04f7a/matplotlib-3.10.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dbed9917b44070e55640bd13419de83b4c918e52d97561544814ba463811cbc7", size = 9406972 },
+ { url = "https://files.pythonhosted.org/packages/b1/79/0d1c165eac44405a86478082e225fce87874f7198300bbebc55faaf6d28d/matplotlib-3.10.3-cp312-cp312-win_amd64.whl", hash = "sha256:cf37d8c6ef1a48829443e8ba5227b44236d7fcaf7647caa3178a4ff9f7a5be05", size = 8067954 },
+ { url = "https://files.pythonhosted.org/packages/3b/c1/23cfb566a74c696a3b338d8955c549900d18fe2b898b6e94d682ca21e7c2/matplotlib-3.10.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:9f2efccc8dcf2b86fc4ee849eea5dcaecedd0773b30f47980dc0cbeabf26ec84", size = 8180318 },
+ { url = "https://files.pythonhosted.org/packages/6c/0c/02f1c3b66b30da9ee343c343acbb6251bef5b01d34fad732446eaadcd108/matplotlib-3.10.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3ddbba06a6c126e3301c3d272a99dcbe7f6c24c14024e80307ff03791a5f294e", size = 8051132 },
+ { url = "https://files.pythonhosted.org/packages/b4/ab/8db1a5ac9b3a7352fb914133001dae889f9fcecb3146541be46bed41339c/matplotlib-3.10.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:748302b33ae9326995b238f606e9ed840bf5886ebafcb233775d946aa8107a15", size = 8457633 },
+ { url = "https://files.pythonhosted.org/packages/f5/64/41c4367bcaecbc03ef0d2a3ecee58a7065d0a36ae1aa817fe573a2da66d4/matplotlib-3.10.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a80fcccbef63302c0efd78042ea3c2436104c5b1a4d3ae20f864593696364ac7", size = 8601031 },
+ { url = "https://files.pythonhosted.org/packages/12/6f/6cc79e9e5ab89d13ed64da28898e40fe5b105a9ab9c98f83abd24e46d7d7/matplotlib-3.10.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:55e46cbfe1f8586adb34f7587c3e4f7dedc59d5226719faf6cb54fc24f2fd52d", size = 9406988 },
+ { url = "https://files.pythonhosted.org/packages/b1/0f/eed564407bd4d935ffabf561ed31099ed609e19287409a27b6d336848653/matplotlib-3.10.3-cp313-cp313-win_amd64.whl", hash = "sha256:151d89cb8d33cb23345cd12490c76fd5d18a56581a16d950b48c6ff19bb2ab93", size = 8068034 },
+ { url = "https://files.pythonhosted.org/packages/3e/e5/2f14791ff69b12b09e9975e1d116d9578ac684460860ce542c2588cb7a1c/matplotlib-3.10.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:c26dd9834e74d164d06433dc7be5d75a1e9890b926b3e57e74fa446e1a62c3e2", size = 8218223 },
+ { url = "https://files.pythonhosted.org/packages/5c/08/30a94afd828b6e02d0a52cae4a29d6e9ccfcf4c8b56cc28b021d3588873e/matplotlib-3.10.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:24853dad5b8c84c8c2390fc31ce4858b6df504156893292ce8092d190ef8151d", size = 8094985 },
+ { url = "https://files.pythonhosted.org/packages/89/44/f3bc6b53066c889d7a1a3ea8094c13af6a667c5ca6220ec60ecceec2dabe/matplotlib-3.10.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68f7878214d369d7d4215e2a9075fef743be38fa401d32e6020bab2dfabaa566", size = 8483109 },
+ { url = "https://files.pythonhosted.org/packages/ba/c7/473bc559beec08ebee9f86ca77a844b65747e1a6c2691e8c92e40b9f42a8/matplotlib-3.10.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6929fc618cb6db9cb75086f73b3219bbb25920cb24cee2ea7a12b04971a4158", size = 8618082 },
+ { url = "https://files.pythonhosted.org/packages/d8/e9/6ce8edd264c8819e37bbed8172e0ccdc7107fe86999b76ab5752276357a4/matplotlib-3.10.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6c7818292a5cc372a2dc4c795e5c356942eb8350b98ef913f7fda51fe175ac5d", size = 9413699 },
+ { url = "https://files.pythonhosted.org/packages/1b/92/9a45c91089c3cf690b5badd4be81e392ff086ccca8a1d4e3a08463d8a966/matplotlib-3.10.3-cp313-cp313t-win_amd64.whl", hash = "sha256:4f23ffe95c5667ef8a2b56eea9b53db7f43910fa4a2d5472ae0f72b64deab4d5", size = 8139044 },
+ { url = "https://files.pythonhosted.org/packages/3d/d1/f54d43e95384b312ffa4a74a4326c722f3b8187aaaa12e9a84cdf3037131/matplotlib-3.10.3-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:86ab63d66bbc83fdb6733471d3bff40897c1e9921cba112accd748eee4bce5e4", size = 8162896 },
+ { url = "https://files.pythonhosted.org/packages/24/a4/fbfc00c2346177c95b353dcf9b5a004106abe8730a62cb6f27e79df0a698/matplotlib-3.10.3-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:a48f9c08bf7444b5d2391a83e75edb464ccda3c380384b36532a0962593a1751", size = 8039702 },
+ { url = "https://files.pythonhosted.org/packages/6a/b9/59e120d24a2ec5fc2d30646adb2efb4621aab3c6d83d66fb2a7a182db032/matplotlib-3.10.3-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cb73d8aa75a237457988f9765e4dfe1c0d2453c5ca4eabc897d4309672c8e014", size = 8594298 },
+]
+
+[[package]]
+name = "matplotlib-inline"
+version = "0.1.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "traitlets" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/99/5b/a36a337438a14116b16480db471ad061c36c3694df7c2084a0da7ba538b7/matplotlib_inline-0.1.7.tar.gz", hash = "sha256:8423b23ec666be3d16e16b60bdd8ac4e86e840ebd1dd11a30b9f117f2fa0ab90", size = 8159 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8f/8e/9ad090d3553c280a8060fbf6e24dc1c0c29704ee7d1c372f0c174aa59285/matplotlib_inline-0.1.7-py3-none-any.whl", hash = "sha256:df192d39a4ff8f21b1895d72e6a13f5fcc5099f00fa84384e0ea28c2cc0653ca", size = 9899 },
+]
+
+[[package]]
+name = "mlx"
+version = "0.26.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/91/9d/645600137d0b7d4689e081de1c62247dae448dfadd8ebdac0fea8c70da33/mlx-0.26.1-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:8f88900eaef76f8f23e957ef303f3664c273c73a504b4e57bb491e397d7a891e", size = 32399627 },
+ { url = "https://files.pythonhosted.org/packages/50/8c/132c081c62ff3352f62bd25c9fc4f654d959402ff94de7c269b53479978d/mlx-0.26.1-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:794b52f2ae52969aac8fa5c271f55a668c0f802cbacda70652033db9c11887c6", size = 31869876 },
+ { url = "https://files.pythonhosted.org/packages/1e/11/eba1bdbaa82b6178887ff22eeae5ab90ef6de73e5fdd518753b808bbbc21/mlx-0.26.1-cp310-cp310-macosx_15_0_arm64.whl", hash = "sha256:030b79376da1564d21af24ecfaa4e049bad823adfd7572376e1f81bd0f08af90", size = 31870531 },
+ { url = "https://files.pythonhosted.org/packages/63/93/97c0a149cba1ad3fbfb01be4c6b293b4cb9d11e41d4b54735048e3d671bd/mlx-0.26.1-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:1973b46817db50328fe8f74b2faa860e761eb08f4230461bb299057a411c070b", size = 32399548 },
+ { url = "https://files.pythonhosted.org/packages/1d/4f/3d3b52f0040462ab53d66d65eefd062f577feb0647ec3aa916faa7f0282b/mlx-0.26.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:478abbe1de49cb1409a38c263bafe45e70e3c5b6cbefd4fc3f5c5b7db90d2908", size = 31870277 },
+ { url = "https://files.pythonhosted.org/packages/80/75/ea19b3f1e9db337a8ef5ceded8f95ae0ed636c66ab40473c6d9eaad5ce01/mlx-0.26.1-cp311-cp311-macosx_15_0_arm64.whl", hash = "sha256:8d76d75d652f252f7887acebc6d1ef5d3aec16e72673332895584f1617c35151", size = 31871009 },
+ { url = "https://files.pythonhosted.org/packages/73/3e/a099ca333bd9cd313c7792a18ad4dfc47b051957ba24edd59f3bcda87d8c/mlx-0.26.1-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:ebcc19c01d90b16462c8ff4255b00837bf45ce149d207170d95770b6699cc5ce", size = 32396393 },
+ { url = "https://files.pythonhosted.org/packages/d1/e0/91707351c0becd33c477a1eba1a0fc124b3838cc65e3d2bd06dfa0a0533e/mlx-0.26.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:5eea5e025655a2b07c1573602e705013bd6d3ebdf432c39eb8eb29628c6df5a7", size = 31871294 },
+ { url = "https://files.pythonhosted.org/packages/8d/e6/d5759fb20faceac183cfd45ede5fa0484f972eecfa2a851f8dd24aa4ace2/mlx-0.26.1-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:3b93e1e2375222a7b0f65b4be3c4010855db2ee8c40cc39f8bf2820ff1652b06", size = 31871854 },
+ { url = "https://files.pythonhosted.org/packages/a2/a7/871c451fe81274d37022a62f825c1dcd22b30e1f8bd2241f91d9f508c9b9/mlx-0.26.1-cp313-cp313-macosx_13_0_arm64.whl", hash = "sha256:ccd8662abad0f1340326412d6051c116fcb5c923c4d2a25ba1277ae65ab140dd", size = 32396333 },
+ { url = "https://files.pythonhosted.org/packages/82/77/720bea5a67934b50372dfd5043864458f103743edcc7c30049e788ea3762/mlx-0.26.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:0c113dd7c7ac13af6e39f0132d33a8dc78928e858ba8d18f8c89f8bfa694a358", size = 31871172 },
+ { url = "https://files.pythonhosted.org/packages/15/4f/83f67bc4fe012dffffd2d96d2767b83fee9b2d7d185611d554ac659cfa4d/mlx-0.26.1-cp313-cp313-macosx_15_0_arm64.whl", hash = "sha256:2ec37131dbb06c0be78ce56b1731ddab6e56183012e7b83bea79b5329ef7d695", size = 31871791 },
+ { url = "https://files.pythonhosted.org/packages/ea/fe/5c181788223880a1bce84d83cfb8c34ffbad88f90260d2453f7b68d6d9dd/mlx-0.26.1-cp39-cp39-macosx_13_0_arm64.whl", hash = "sha256:8aa6a6778625407ef6a963461d6cdb914a2b0cb836020bca89b4114b13f323ee", size = 32399614 },
+ { url = "https://files.pythonhosted.org/packages/6f/82/00aab969d38b4721285a49001960af05d3c8210705c5e62f7f741a81f6e5/mlx-0.26.1-cp39-cp39-macosx_14_0_arm64.whl", hash = "sha256:ab695c473dabdda7a3d19f78665bc85551a36f2cff587fdb56bc2d59ce5d5a22", size = 31870447 },
+ { url = "https://files.pythonhosted.org/packages/a0/1f/0904c8a9a64dcafd7be768907a91ef6a3ee3f336e489999fec7611ff95c5/mlx-0.26.1-cp39-cp39-macosx_15_0_arm64.whl", hash = "sha256:51c2edffc69b6479aa29222dc623e15f7f56f6b67688902bf34cbdce520c06b1", size = 31871197 },
+]
+
+[[package]]
+name = "mlx-lm"
+version = "0.25.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "jinja2" },
+ { name = "mlx" },
+ { name = "numpy" },
+ { name = "protobuf" },
+ { name = "pyyaml" },
+ { name = "transformers", extra = ["sentencepiece"] },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/52/34/d2b551d4519a9bafdfd29f76987dbcaaee370b974cfa81acfba782d6063f/mlx_lm-0.25.2.tar.gz", hash = "sha256:7d01baa66916aabd5be7345786acbfaf01d4e3f646759d7232e14aebfd4420a8", size = 146815 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/5d/47bb6fb75e4488be07e7cc80072d09a9208be9e36c55d0195ac75cc3eec6/mlx_lm-0.25.2-py3-none-any.whl", hash = "sha256:eb2ddd0ae352a62adeb7cb9f09f7a7faa013406840bb98128aacd028c8bc2c9c", size = 196126 },
+]
+
+[[package]]
+name = "modelscope"
+version = "1.27.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "requests" },
+ { name = "setuptools" },
+ { name = "tqdm" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a4/50/86ecf64cc894b37285a95dfc5528d9f7121f2710e7a46e7f333bfcea5e45/modelscope-1.27.0.tar.gz", hash = "sha256:645e8b9cd346f3538ddce9f905b0ac7e57fb6f48710c6c256ae3e5bb37303df5", size = 4415867 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/50/1b/ca9e471925784a5a9e0334678cf57155e1badceca0f262f639ebc39c56cb/modelscope-1.27.0-py3-none-any.whl", hash = "sha256:95071d3f9a7bf944a485d1ae86e96a75e4148030e96969b8d1971672795a47d4", size = 5895685 },
+]
+
+[[package]]
+name = "mpmath"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198 },
+]
+
+[[package]]
+name = "msgspec"
+version = "0.19.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cf/9b/95d8ce458462b8b71b8a70fa94563b2498b89933689f3a7b8911edfae3d7/msgspec-0.19.0.tar.gz", hash = "sha256:604037e7cd475345848116e89c553aa9a233259733ab51986ac924ab1b976f8e", size = 216934 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/13/40/817282b42f58399762267b30deb8ac011d8db373f8da0c212c85fbe62b8f/msgspec-0.19.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d8dd848ee7ca7c8153462557655570156c2be94e79acec3561cf379581343259", size = 190019 },
+ { url = "https://files.pythonhosted.org/packages/92/99/bd7ed738c00f223a8119928661167a89124140792af18af513e6519b0d54/msgspec-0.19.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0553bbc77662e5708fe66aa75e7bd3e4b0f209709c48b299afd791d711a93c36", size = 183680 },
+ { url = "https://files.pythonhosted.org/packages/e5/27/322badde18eb234e36d4a14122b89edd4e2973cdbc3da61ca7edf40a1ccd/msgspec-0.19.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fe2c4bf29bf4e89790b3117470dea2c20b59932772483082c468b990d45fb947", size = 209334 },
+ { url = "https://files.pythonhosted.org/packages/c6/65/080509c5774a1592b2779d902a70b5fe008532759927e011f068145a16cb/msgspec-0.19.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:00e87ecfa9795ee5214861eab8326b0e75475c2e68a384002aa135ea2a27d909", size = 211551 },
+ { url = "https://files.pythonhosted.org/packages/6f/2e/1c23c6b4ca6f4285c30a39def1054e2bee281389e4b681b5e3711bd5a8c9/msgspec-0.19.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3c4ec642689da44618f68c90855a10edbc6ac3ff7c1d94395446c65a776e712a", size = 215099 },
+ { url = "https://files.pythonhosted.org/packages/83/fe/95f9654518879f3359d1e76bc41189113aa9102452170ab7c9a9a4ee52f6/msgspec-0.19.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:2719647625320b60e2d8af06b35f5b12d4f4d281db30a15a1df22adb2295f633", size = 218211 },
+ { url = "https://files.pythonhosted.org/packages/79/f6/71ca7e87a1fb34dfe5efea8156c9ef59dd55613aeda2ca562f122cd22012/msgspec-0.19.0-cp310-cp310-win_amd64.whl", hash = "sha256:695b832d0091edd86eeb535cd39e45f3919f48d997685f7ac31acb15e0a2ed90", size = 186174 },
+ { url = "https://files.pythonhosted.org/packages/24/d4/2ec2567ac30dab072cce3e91fb17803c52f0a37aab6b0c24375d2b20a581/msgspec-0.19.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:aa77046904db764b0462036bc63ef71f02b75b8f72e9c9dd4c447d6da1ed8f8e", size = 187939 },
+ { url = "https://files.pythonhosted.org/packages/2b/c0/18226e4328897f4f19875cb62bb9259fe47e901eade9d9376ab5f251a929/msgspec-0.19.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:047cfa8675eb3bad68722cfe95c60e7afabf84d1bd8938979dd2b92e9e4a9551", size = 182202 },
+ { url = "https://files.pythonhosted.org/packages/81/25/3a4b24d468203d8af90d1d351b77ea3cffb96b29492855cf83078f16bfe4/msgspec-0.19.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e78f46ff39a427e10b4a61614a2777ad69559cc8d603a7c05681f5a595ea98f7", size = 209029 },
+ { url = "https://files.pythonhosted.org/packages/85/2e/db7e189b57901955239f7689b5dcd6ae9458637a9c66747326726c650523/msgspec-0.19.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c7adf191e4bd3be0e9231c3b6dc20cf1199ada2af523885efc2ed218eafd011", size = 210682 },
+ { url = "https://files.pythonhosted.org/packages/03/97/7c8895c9074a97052d7e4a1cc1230b7b6e2ca2486714eb12c3f08bb9d284/msgspec-0.19.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f04cad4385e20be7c7176bb8ae3dca54a08e9756cfc97bcdb4f18560c3042063", size = 214003 },
+ { url = "https://files.pythonhosted.org/packages/61/61/e892997bcaa289559b4d5869f066a8021b79f4bf8e955f831b095f47a4cd/msgspec-0.19.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:45c8fb410670b3b7eb884d44a75589377c341ec1392b778311acdbfa55187716", size = 216833 },
+ { url = "https://files.pythonhosted.org/packages/ce/3d/71b2dffd3a1c743ffe13296ff701ee503feaebc3f04d0e75613b6563c374/msgspec-0.19.0-cp311-cp311-win_amd64.whl", hash = "sha256:70eaef4934b87193a27d802534dc466778ad8d536e296ae2f9334e182ac27b6c", size = 186184 },
+ { url = "https://files.pythonhosted.org/packages/b2/5f/a70c24f075e3e7af2fae5414c7048b0e11389685b7f717bb55ba282a34a7/msgspec-0.19.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f98bd8962ad549c27d63845b50af3f53ec468b6318400c9f1adfe8b092d7b62f", size = 190485 },
+ { url = "https://files.pythonhosted.org/packages/89/b0/1b9763938cfae12acf14b682fcf05c92855974d921a5a985ecc197d1c672/msgspec-0.19.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:43bbb237feab761b815ed9df43b266114203f53596f9b6e6f00ebd79d178cdf2", size = 183910 },
+ { url = "https://files.pythonhosted.org/packages/87/81/0c8c93f0b92c97e326b279795f9c5b956c5a97af28ca0fbb9fd86c83737a/msgspec-0.19.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4cfc033c02c3e0aec52b71710d7f84cb3ca5eb407ab2ad23d75631153fdb1f12", size = 210633 },
+ { url = "https://files.pythonhosted.org/packages/d0/ef/c5422ce8af73928d194a6606f8ae36e93a52fd5e8df5abd366903a5ca8da/msgspec-0.19.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d911c442571605e17658ca2b416fd8579c5050ac9adc5e00c2cb3126c97f73bc", size = 213594 },
+ { url = "https://files.pythonhosted.org/packages/19/2b/4137bc2ed45660444842d042be2cf5b18aa06efd2cda107cff18253b9653/msgspec-0.19.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:757b501fa57e24896cf40a831442b19a864f56d253679f34f260dcb002524a6c", size = 214053 },
+ { url = "https://files.pythonhosted.org/packages/9d/e6/8ad51bdc806aac1dc501e8fe43f759f9ed7284043d722b53323ea421c360/msgspec-0.19.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5f0f65f29b45e2816d8bded36e6b837a4bf5fb60ec4bc3c625fa2c6da4124537", size = 219081 },
+ { url = "https://files.pythonhosted.org/packages/b1/ef/27dd35a7049c9a4f4211c6cd6a8c9db0a50647546f003a5867827ec45391/msgspec-0.19.0-cp312-cp312-win_amd64.whl", hash = "sha256:067f0de1c33cfa0b6a8206562efdf6be5985b988b53dd244a8e06f993f27c8c0", size = 187467 },
+ { url = "https://files.pythonhosted.org/packages/3c/cb/2842c312bbe618d8fefc8b9cedce37f773cdc8fa453306546dba2c21fd98/msgspec-0.19.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f12d30dd6266557aaaf0aa0f9580a9a8fbeadfa83699c487713e355ec5f0bd86", size = 190498 },
+ { url = "https://files.pythonhosted.org/packages/58/95/c40b01b93465e1a5f3b6c7d91b10fb574818163740cc3acbe722d1e0e7e4/msgspec-0.19.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:82b2c42c1b9ebc89e822e7e13bbe9d17ede0c23c187469fdd9505afd5a481314", size = 183950 },
+ { url = "https://files.pythonhosted.org/packages/e8/f0/5b764e066ce9aba4b70d1db8b087ea66098c7c27d59b9dd8a3532774d48f/msgspec-0.19.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:19746b50be214a54239aab822964f2ac81e38b0055cca94808359d779338c10e", size = 210647 },
+ { url = "https://files.pythonhosted.org/packages/9d/87/bc14f49bc95c4cb0dd0a8c56028a67c014ee7e6818ccdce74a4862af259b/msgspec-0.19.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:60ef4bdb0ec8e4ad62e5a1f95230c08efb1f64f32e6e8dd2ced685bcc73858b5", size = 213563 },
+ { url = "https://files.pythonhosted.org/packages/53/2f/2b1c2b056894fbaa975f68f81e3014bb447516a8b010f1bed3fb0e016ed7/msgspec-0.19.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac7f7c377c122b649f7545810c6cd1b47586e3aa3059126ce3516ac7ccc6a6a9", size = 213996 },
+ { url = "https://files.pythonhosted.org/packages/aa/5a/4cd408d90d1417e8d2ce6a22b98a6853c1b4d7cb7669153e4424d60087f6/msgspec-0.19.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a5bc1472223a643f5ffb5bf46ccdede7f9795078194f14edd69e3aab7020d327", size = 219087 },
+ { url = "https://files.pythonhosted.org/packages/23/d8/f15b40611c2d5753d1abb0ca0da0c75348daf1252220e5dda2867bd81062/msgspec-0.19.0-cp313-cp313-win_amd64.whl", hash = "sha256:317050bc0f7739cb30d257ff09152ca309bf5a369854bbf1e57dffc310c1f20f", size = 187432 },
+ { url = "https://files.pythonhosted.org/packages/ea/d0/323f867eaec1f2236ba30adf613777b1c97a7e8698e2e881656b21871fa4/msgspec-0.19.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:15c1e86fff77184c20a2932cd9742bf33fe23125fa3fcf332df9ad2f7d483044", size = 189926 },
+ { url = "https://files.pythonhosted.org/packages/a8/37/c3e1b39bdae90a7258d77959f5f5e36ad44b40e2be91cff83eea33c54d43/msgspec-0.19.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3b5541b2b3294e5ffabe31a09d604e23a88533ace36ac288fa32a420aa38d229", size = 183873 },
+ { url = "https://files.pythonhosted.org/packages/cb/a2/48f2c15c7644668e51f4dce99d5f709bd55314e47acb02e90682f5880f35/msgspec-0.19.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0f5c043ace7962ef188746e83b99faaa9e3e699ab857ca3f367b309c8e2c6b12", size = 209272 },
+ { url = "https://files.pythonhosted.org/packages/25/3c/aa339cf08b990c3f07e67b229a3a8aa31bf129ed974b35e5daa0df7d9d56/msgspec-0.19.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca06aa08e39bf57e39a258e1996474f84d0dd8130d486c00bec26d797b8c5446", size = 211396 },
+ { url = "https://files.pythonhosted.org/packages/c7/00/c7fb9d524327c558b2803973cc3f988c5100a1708879970a9e377bdf6f4f/msgspec-0.19.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:e695dad6897896e9384cf5e2687d9ae9feaef50e802f93602d35458e20d1fb19", size = 215002 },
+ { url = "https://files.pythonhosted.org/packages/3f/bf/d9f9fff026c1248cde84a5ce62b3742e8a63a3c4e811f99f00c8babf7615/msgspec-0.19.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:3be5c02e1fee57b54130316a08fe40cca53af92999a302a6054cd451700ea7db", size = 218132 },
+ { url = "https://files.pythonhosted.org/packages/00/03/b92011210f79794958167a3a3ea64a71135d9a2034cfb7597b545a42606d/msgspec-0.19.0-cp39-cp39-win_amd64.whl", hash = "sha256:0684573a821be3c749912acf5848cce78af4298345cb2d7a8b8948a0a5a27cfe", size = 186301 },
+]
+
+[[package]]
+name = "multidict"
+version = "6.4.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/91/2f/a3470242707058fe856fe59241eee5635d79087100b7042a867368863a27/multidict-6.4.4.tar.gz", hash = "sha256:69ee9e6ba214b5245031b76233dd95408a0fd57fdb019ddcc1ead4790932a8e8", size = 90183 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1f/92/0926a5baafa164b5d0ade3cd7932be39310375d7e25c9d7ceca05cb26a45/multidict-6.4.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:8adee3ac041145ffe4488ea73fa0a622b464cc25340d98be76924d0cda8545ff", size = 66052 },
+ { url = "https://files.pythonhosted.org/packages/b2/54/8a857ae4f8f643ec444d91f419fdd49cc7a90a2ca0e42d86482b604b63bd/multidict-6.4.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b61e98c3e2a861035aaccd207da585bdcacef65fe01d7a0d07478efac005e028", size = 38867 },
+ { url = "https://files.pythonhosted.org/packages/9e/5f/63add9069f945c19bc8b217ea6b0f8a1ad9382eab374bb44fae4354b3baf/multidict-6.4.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:75493f28dbadecdbb59130e74fe935288813301a8554dc32f0c631b6bdcdf8b0", size = 38138 },
+ { url = "https://files.pythonhosted.org/packages/97/8b/fbd9c0fc13966efdb4a47f5bcffff67a4f2a3189fbeead5766eaa4250b20/multidict-6.4.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4ffc3c6a37e048b5395ee235e4a2a0d639c2349dffa32d9367a42fc20d399772", size = 220433 },
+ { url = "https://files.pythonhosted.org/packages/a9/c4/5132b2d75b3ea2daedb14d10f91028f09f74f5b4d373b242c1b8eec47571/multidict-6.4.4-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:87cb72263946b301570b0f63855569a24ee8758aaae2cd182aae7d95fbc92ca7", size = 218059 },
+ { url = "https://files.pythonhosted.org/packages/1a/70/f1e818c7a29b908e2d7b4fafb1d7939a41c64868e79de2982eea0a13193f/multidict-6.4.4-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9bbf7bd39822fd07e3609b6b4467af4c404dd2b88ee314837ad1830a7f4a8299", size = 231120 },
+ { url = "https://files.pythonhosted.org/packages/b4/7e/95a194d85f27d5ef9cbe48dff9ded722fc6d12fedf641ec6e1e680890be7/multidict-6.4.4-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d1f7cbd4f1f44ddf5fd86a8675b7679176eae770f2fc88115d6dddb6cefb59bc", size = 227457 },
+ { url = "https://files.pythonhosted.org/packages/25/2b/590ad220968d1babb42f265debe7be5c5c616df6c5688c995a06d8a9b025/multidict-6.4.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb5ac9e5bfce0e6282e7f59ff7b7b9a74aa8e5c60d38186a4637f5aa764046ad", size = 219111 },
+ { url = "https://files.pythonhosted.org/packages/e0/f0/b07682b995d3fb5313f339b59d7de02db19ba0c02d1f77c27bdf8212d17c/multidict-6.4.4-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4efc31dfef8c4eeb95b6b17d799eedad88c4902daba39ce637e23a17ea078915", size = 213012 },
+ { url = "https://files.pythonhosted.org/packages/24/56/c77b5f36feef2ec92f1119756e468ac9c3eebc35aa8a4c9e51df664cbbc9/multidict-6.4.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:9fcad2945b1b91c29ef2b4050f590bfcb68d8ac8e0995a74e659aa57e8d78e01", size = 225408 },
+ { url = "https://files.pythonhosted.org/packages/cc/b3/e8189b82af9b198b47bc637766208fc917189eea91d674bad417e657bbdf/multidict-6.4.4-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:d877447e7368c7320832acb7159557e49b21ea10ffeb135c1077dbbc0816b598", size = 214396 },
+ { url = "https://files.pythonhosted.org/packages/20/e0/200d14c84e35ae13ee99fd65dc106e1a1acb87a301f15e906fc7d5b30c17/multidict-6.4.4-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:33a12ebac9f380714c298cbfd3e5b9c0c4e89c75fe612ae496512ee51028915f", size = 222237 },
+ { url = "https://files.pythonhosted.org/packages/13/f3/bb3df40045ca8262694a3245298732ff431dc781414a89a6a364ebac6840/multidict-6.4.4-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:0f14ea68d29b43a9bf37953881b1e3eb75b2739e896ba4a6aa4ad4c5b9ffa145", size = 231425 },
+ { url = "https://files.pythonhosted.org/packages/85/3b/538563dc18514384dac169bcba938753ad9ab4d4c8d49b55d6ae49fb2579/multidict-6.4.4-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:0327ad2c747a6600e4797d115d3c38a220fdb28e54983abe8964fd17e95ae83c", size = 226251 },
+ { url = "https://files.pythonhosted.org/packages/56/79/77e1a65513f09142358f1beb1d4cbc06898590b34a7de2e47023e3c5a3a2/multidict-6.4.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:d1a20707492db9719a05fc62ee215fd2c29b22b47c1b1ba347f9abc831e26683", size = 220363 },
+ { url = "https://files.pythonhosted.org/packages/16/57/67b0516c3e348f8daaa79c369b3de4359a19918320ab82e2e586a1c624ef/multidict-6.4.4-cp310-cp310-win32.whl", hash = "sha256:d83f18315b9fca5db2452d1881ef20f79593c4aa824095b62cb280019ef7aa3d", size = 35175 },
+ { url = "https://files.pythonhosted.org/packages/86/5a/4ed8fec642d113fa653777cda30ef67aa5c8a38303c091e24c521278a6c6/multidict-6.4.4-cp310-cp310-win_amd64.whl", hash = "sha256:9c17341ee04545fd962ae07330cb5a39977294c883485c8d74634669b1f7fe04", size = 38678 },
+ { url = "https://files.pythonhosted.org/packages/19/1b/4c6e638195851524a63972c5773c7737bea7e47b1ba402186a37773acee2/multidict-6.4.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4f5f29794ac0e73d2a06ac03fd18870adc0135a9d384f4a306a951188ed02f95", size = 65515 },
+ { url = "https://files.pythonhosted.org/packages/25/d5/10e6bca9a44b8af3c7f920743e5fc0c2bcf8c11bf7a295d4cfe00b08fb46/multidict-6.4.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c04157266344158ebd57b7120d9b0b35812285d26d0e78193e17ef57bfe2979a", size = 38609 },
+ { url = "https://files.pythonhosted.org/packages/26/b4/91fead447ccff56247edc7f0535fbf140733ae25187a33621771ee598a18/multidict-6.4.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bb61ffd3ab8310d93427e460f565322c44ef12769f51f77277b4abad7b6f7223", size = 37871 },
+ { url = "https://files.pythonhosted.org/packages/3b/37/cbc977cae59277e99d15bbda84cc53b5e0c4929ffd91d958347200a42ad0/multidict-6.4.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5e0ba18a9afd495f17c351d08ebbc4284e9c9f7971d715f196b79636a4d0de44", size = 226661 },
+ { url = "https://files.pythonhosted.org/packages/15/cd/7e0b57fbd4dc2fc105169c4ecce5be1a63970f23bb4ec8c721b67e11953d/multidict-6.4.4-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:9faf1b1dcaadf9f900d23a0e6d6c8eadd6a95795a0e57fcca73acce0eb912065", size = 223422 },
+ { url = "https://files.pythonhosted.org/packages/f1/01/1de268da121bac9f93242e30cd3286f6a819e5f0b8896511162d6ed4bf8d/multidict-6.4.4-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a4d1cb1327c6082c4fce4e2a438483390964c02213bc6b8d782cf782c9b1471f", size = 235447 },
+ { url = "https://files.pythonhosted.org/packages/d2/8c/8b9a5e4aaaf4f2de14e86181a3a3d7b105077f668b6a06f043ec794f684c/multidict-6.4.4-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:941f1bec2f5dbd51feeb40aea654c2747f811ab01bdd3422a48a4e4576b7d76a", size = 231455 },
+ { url = "https://files.pythonhosted.org/packages/35/db/e1817dcbaa10b319c412769cf999b1016890849245d38905b73e9c286862/multidict-6.4.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5f8a146184da7ea12910a4cec51ef85e44f6268467fb489c3caf0cd512f29c2", size = 223666 },
+ { url = "https://files.pythonhosted.org/packages/4a/e1/66e8579290ade8a00e0126b3d9a93029033ffd84f0e697d457ed1814d0fc/multidict-6.4.4-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:232b7237e57ec3c09be97206bfb83a0aa1c5d7d377faa019c68a210fa35831f1", size = 217392 },
+ { url = "https://files.pythonhosted.org/packages/7b/6f/f8639326069c24a48c7747c2a5485d37847e142a3f741ff3340c88060a9a/multidict-6.4.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:55ae0721c1513e5e3210bca4fc98456b980b0c2c016679d3d723119b6b202c42", size = 228969 },
+ { url = "https://files.pythonhosted.org/packages/d2/c3/3d58182f76b960eeade51c89fcdce450f93379340457a328e132e2f8f9ed/multidict-6.4.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:51d662c072579f63137919d7bb8fc250655ce79f00c82ecf11cab678f335062e", size = 217433 },
+ { url = "https://files.pythonhosted.org/packages/e1/4b/f31a562906f3bd375f3d0e83ce314e4a660c01b16c2923e8229b53fba5d7/multidict-6.4.4-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:0e05c39962baa0bb19a6b210e9b1422c35c093b651d64246b6c2e1a7e242d9fd", size = 225418 },
+ { url = "https://files.pythonhosted.org/packages/99/89/78bb95c89c496d64b5798434a3deee21996114d4d2c28dd65850bf3a691e/multidict-6.4.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d5b1cc3ab8c31d9ebf0faa6e3540fb91257590da330ffe6d2393d4208e638925", size = 235042 },
+ { url = "https://files.pythonhosted.org/packages/74/91/8780a6e5885a8770442a8f80db86a0887c4becca0e5a2282ba2cae702bc4/multidict-6.4.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:93ec84488a384cd7b8a29c2c7f467137d8a73f6fe38bb810ecf29d1ade011a7c", size = 230280 },
+ { url = "https://files.pythonhosted.org/packages/68/c1/fcf69cabd542eb6f4b892469e033567ee6991d361d77abdc55e3a0f48349/multidict-6.4.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b308402608493638763abc95f9dc0030bbd6ac6aff784512e8ac3da73a88af08", size = 223322 },
+ { url = "https://files.pythonhosted.org/packages/b8/85/5b80bf4b83d8141bd763e1d99142a9cdfd0db83f0739b4797172a4508014/multidict-6.4.4-cp311-cp311-win32.whl", hash = "sha256:343892a27d1a04d6ae455ecece12904d242d299ada01633d94c4f431d68a8c49", size = 35070 },
+ { url = "https://files.pythonhosted.org/packages/09/66/0bed198ffd590ab86e001f7fa46b740d58cf8ff98c2f254e4a36bf8861ad/multidict-6.4.4-cp311-cp311-win_amd64.whl", hash = "sha256:73484a94f55359780c0f458bbd3c39cb9cf9c182552177d2136e828269dee529", size = 38667 },
+ { url = "https://files.pythonhosted.org/packages/d2/b5/5675377da23d60875fe7dae6be841787755878e315e2f517235f22f59e18/multidict-6.4.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:dc388f75a1c00000824bf28b7633e40854f4127ede80512b44c3cfeeea1839a2", size = 64293 },
+ { url = "https://files.pythonhosted.org/packages/34/a7/be384a482754bb8c95d2bbe91717bf7ccce6dc38c18569997a11f95aa554/multidict-6.4.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:98af87593a666f739d9dba5d0ae86e01b0e1a9cfcd2e30d2d361fbbbd1a9162d", size = 38096 },
+ { url = "https://files.pythonhosted.org/packages/66/6d/d59854bb4352306145bdfd1704d210731c1bb2c890bfee31fb7bbc1c4c7f/multidict-6.4.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:aff4cafea2d120327d55eadd6b7f1136a8e5a0ecf6fb3b6863e8aca32cd8e50a", size = 37214 },
+ { url = "https://files.pythonhosted.org/packages/99/e0/c29d9d462d7cfc5fc8f9bf24f9c6843b40e953c0b55e04eba2ad2cf54fba/multidict-6.4.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:169c4ba7858176b797fe551d6e99040c531c775d2d57b31bcf4de6d7a669847f", size = 224686 },
+ { url = "https://files.pythonhosted.org/packages/dc/4a/da99398d7fd8210d9de068f9a1b5f96dfaf67d51e3f2521f17cba4ee1012/multidict-6.4.4-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b9eb4c59c54421a32b3273d4239865cb14ead53a606db066d7130ac80cc8ec93", size = 231061 },
+ { url = "https://files.pythonhosted.org/packages/21/f5/ac11add39a0f447ac89353e6ca46666847051103649831c08a2800a14455/multidict-6.4.4-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7cf3bd54c56aa16fdb40028d545eaa8d051402b61533c21e84046e05513d5780", size = 232412 },
+ { url = "https://files.pythonhosted.org/packages/d9/11/4b551e2110cded705a3c13a1d4b6a11f73891eb5a1c449f1b2b6259e58a6/multidict-6.4.4-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f682c42003c7264134bfe886376299db4cc0c6cd06a3295b41b347044bcb5482", size = 231563 },
+ { url = "https://files.pythonhosted.org/packages/4c/02/751530c19e78fe73b24c3da66618eda0aa0d7f6e7aa512e46483de6be210/multidict-6.4.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a920f9cf2abdf6e493c519492d892c362007f113c94da4c239ae88429835bad1", size = 223811 },
+ { url = "https://files.pythonhosted.org/packages/c7/cb/2be8a214643056289e51ca356026c7b2ce7225373e7a1f8c8715efee8988/multidict-6.4.4-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:530d86827a2df6504526106b4c104ba19044594f8722d3e87714e847c74a0275", size = 216524 },
+ { url = "https://files.pythonhosted.org/packages/19/f3/6d5011ec375c09081f5250af58de85f172bfcaafebff286d8089243c4bd4/multidict-6.4.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ecde56ea2439b96ed8a8d826b50c57364612ddac0438c39e473fafad7ae1c23b", size = 229012 },
+ { url = "https://files.pythonhosted.org/packages/67/9c/ca510785df5cf0eaf5b2a8132d7d04c1ce058dcf2c16233e596ce37a7f8e/multidict-6.4.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:dc8c9736d8574b560634775ac0def6bdc1661fc63fa27ffdfc7264c565bcb4f2", size = 226765 },
+ { url = "https://files.pythonhosted.org/packages/36/c8/ca86019994e92a0f11e642bda31265854e6ea7b235642f0477e8c2e25c1f/multidict-6.4.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:7f3d3b3c34867579ea47cbd6c1f2ce23fbfd20a273b6f9e3177e256584f1eacc", size = 222888 },
+ { url = "https://files.pythonhosted.org/packages/c6/67/bc25a8e8bd522935379066950ec4e2277f9b236162a73548a2576d4b9587/multidict-6.4.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:87a728af265e08f96b6318ebe3c0f68b9335131f461efab2fc64cc84a44aa6ed", size = 234041 },
+ { url = "https://files.pythonhosted.org/packages/f1/a0/70c4c2d12857fccbe607b334b7ee28b6b5326c322ca8f73ee54e70d76484/multidict-6.4.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9f193eeda1857f8e8d3079a4abd258f42ef4a4bc87388452ed1e1c4d2b0c8740", size = 231046 },
+ { url = "https://files.pythonhosted.org/packages/c1/0f/52954601d02d39742aab01d6b92f53c1dd38b2392248154c50797b4df7f1/multidict-6.4.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:be06e73c06415199200e9a2324a11252a3d62030319919cde5e6950ffeccf72e", size = 227106 },
+ { url = "https://files.pythonhosted.org/packages/af/24/679d83ec4379402d28721790dce818e5d6b9f94ce1323a556fb17fa9996c/multidict-6.4.4-cp312-cp312-win32.whl", hash = "sha256:622f26ea6a7e19b7c48dd9228071f571b2fbbd57a8cd71c061e848f281550e6b", size = 35351 },
+ { url = "https://files.pythonhosted.org/packages/52/ef/40d98bc5f986f61565f9b345f102409534e29da86a6454eb6b7c00225a13/multidict-6.4.4-cp312-cp312-win_amd64.whl", hash = "sha256:5e2bcda30d5009996ff439e02a9f2b5c3d64a20151d34898c000a6281faa3781", size = 38791 },
+ { url = "https://files.pythonhosted.org/packages/df/2a/e166d2ffbf4b10131b2d5b0e458f7cee7d986661caceae0de8753042d4b2/multidict-6.4.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:82ffabefc8d84c2742ad19c37f02cde5ec2a1ee172d19944d380f920a340e4b9", size = 64123 },
+ { url = "https://files.pythonhosted.org/packages/8c/96/e200e379ae5b6f95cbae472e0199ea98913f03d8c9a709f42612a432932c/multidict-6.4.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:6a2f58a66fe2c22615ad26156354005391e26a2f3721c3621504cd87c1ea87bf", size = 38049 },
+ { url = "https://files.pythonhosted.org/packages/75/fb/47afd17b83f6a8c7fa863c6d23ac5ba6a0e6145ed8a6bcc8da20b2b2c1d2/multidict-6.4.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5883d6ee0fd9d8a48e9174df47540b7545909841ac82354c7ae4cbe9952603bd", size = 37078 },
+ { url = "https://files.pythonhosted.org/packages/fa/70/1af3143000eddfb19fd5ca5e78393985ed988ac493bb859800fe0914041f/multidict-6.4.4-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9abcf56a9511653fa1d052bfc55fbe53dbee8f34e68bd6a5a038731b0ca42d15", size = 224097 },
+ { url = "https://files.pythonhosted.org/packages/b1/39/d570c62b53d4fba844e0378ffbcd02ac25ca423d3235047013ba2f6f60f8/multidict-6.4.4-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6ed5ae5605d4ad5a049fad2a28bb7193400700ce2f4ae484ab702d1e3749c3f9", size = 230768 },
+ { url = "https://files.pythonhosted.org/packages/fd/f8/ed88f2c4d06f752b015933055eb291d9bc184936903752c66f68fb3c95a7/multidict-6.4.4-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bbfcb60396f9bcfa63e017a180c3105b8c123a63e9d1428a36544e7d37ca9e20", size = 231331 },
+ { url = "https://files.pythonhosted.org/packages/9c/6f/8e07cffa32f483ab887b0d56bbd8747ac2c1acd00dc0af6fcf265f4a121e/multidict-6.4.4-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b0f1987787f5f1e2076b59692352ab29a955b09ccc433c1f6b8e8e18666f608b", size = 230169 },
+ { url = "https://files.pythonhosted.org/packages/e6/2b/5dcf173be15e42f330110875a2668ddfc208afc4229097312212dc9c1236/multidict-6.4.4-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d0121ccce8c812047d8d43d691a1ad7641f72c4f730474878a5aeae1b8ead8c", size = 222947 },
+ { url = "https://files.pythonhosted.org/packages/39/75/4ddcbcebe5ebcd6faa770b629260d15840a5fc07ce8ad295a32e14993726/multidict-6.4.4-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:83ec4967114295b8afd120a8eec579920c882831a3e4c3331d591a8e5bfbbc0f", size = 215761 },
+ { url = "https://files.pythonhosted.org/packages/6a/c9/55e998ae45ff15c5608e384206aa71a11e1b7f48b64d166db400b14a3433/multidict-6.4.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:995f985e2e268deaf17867801b859a282e0448633f1310e3704b30616d269d69", size = 227605 },
+ { url = "https://files.pythonhosted.org/packages/04/49/c2404eac74497503c77071bd2e6f88c7e94092b8a07601536b8dbe99be50/multidict-6.4.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:d832c608f94b9f92a0ec8b7e949be7792a642b6e535fcf32f3e28fab69eeb046", size = 226144 },
+ { url = "https://files.pythonhosted.org/packages/62/c5/0cd0c3c6f18864c40846aa2252cd69d308699cb163e1c0d989ca301684da/multidict-6.4.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d21c1212171cf7da703c5b0b7a0e85be23b720818aef502ad187d627316d5645", size = 221100 },
+ { url = "https://files.pythonhosted.org/packages/71/7b/f2f3887bea71739a046d601ef10e689528d4f911d84da873b6be9194ffea/multidict-6.4.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:cbebaa076aaecad3d4bb4c008ecc73b09274c952cf6a1b78ccfd689e51f5a5b0", size = 232731 },
+ { url = "https://files.pythonhosted.org/packages/e5/b3/d9de808349df97fa75ec1372758701b5800ebad3c46ae377ad63058fbcc6/multidict-6.4.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:c93a6fb06cc8e5d3628b2b5fda215a5db01e8f08fc15fadd65662d9b857acbe4", size = 229637 },
+ { url = "https://files.pythonhosted.org/packages/5e/57/13207c16b615eb4f1745b44806a96026ef8e1b694008a58226c2d8f5f0a5/multidict-6.4.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8cd8f81f1310182362fb0c7898145ea9c9b08a71081c5963b40ee3e3cac589b1", size = 225594 },
+ { url = "https://files.pythonhosted.org/packages/3a/e4/d23bec2f70221604f5565000632c305fc8f25ba953e8ce2d8a18842b9841/multidict-6.4.4-cp313-cp313-win32.whl", hash = "sha256:3e9f1cd61a0ab857154205fb0b1f3d3ace88d27ebd1409ab7af5096e409614cd", size = 35359 },
+ { url = "https://files.pythonhosted.org/packages/a7/7a/cfe1a47632be861b627f46f642c1d031704cc1c0f5c0efbde2ad44aa34bd/multidict-6.4.4-cp313-cp313-win_amd64.whl", hash = "sha256:8ffb40b74400e4455785c2fa37eba434269149ec525fc8329858c862e4b35373", size = 38903 },
+ { url = "https://files.pythonhosted.org/packages/68/7b/15c259b0ab49938a0a1c8f3188572802704a779ddb294edc1b2a72252e7c/multidict-6.4.4-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:6a602151dbf177be2450ef38966f4be3467d41a86c6a845070d12e17c858a156", size = 68895 },
+ { url = "https://files.pythonhosted.org/packages/f1/7d/168b5b822bccd88142e0a3ce985858fea612404edd228698f5af691020c9/multidict-6.4.4-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0d2b9712211b860d123815a80b859075d86a4d54787e247d7fbee9db6832cf1c", size = 40183 },
+ { url = "https://files.pythonhosted.org/packages/e0/b7/d4b8d98eb850ef28a4922ba508c31d90715fd9b9da3801a30cea2967130b/multidict-6.4.4-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:d2fa86af59f8fc1972e121ade052145f6da22758f6996a197d69bb52f8204e7e", size = 39592 },
+ { url = "https://files.pythonhosted.org/packages/18/28/a554678898a19583548e742080cf55d169733baf57efc48c2f0273a08583/multidict-6.4.4-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50855d03e9e4d66eab6947ba688ffb714616f985838077bc4b490e769e48da51", size = 226071 },
+ { url = "https://files.pythonhosted.org/packages/ee/dc/7ba6c789d05c310e294f85329efac1bf5b450338d2542498db1491a264df/multidict-6.4.4-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5bce06b83be23225be1905dcdb6b789064fae92499fbc458f59a8c0e68718601", size = 222597 },
+ { url = "https://files.pythonhosted.org/packages/24/4f/34eadbbf401b03768dba439be0fb94b0d187facae9142821a3d5599ccb3b/multidict-6.4.4-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:66ed0731f8e5dfd8369a883b6e564aca085fb9289aacabd9decd70568b9a30de", size = 228253 },
+ { url = "https://files.pythonhosted.org/packages/c0/e6/493225a3cdb0d8d80d43a94503fc313536a07dae54a3f030d279e629a2bc/multidict-6.4.4-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:329ae97fc2f56f44d91bc47fe0972b1f52d21c4b7a2ac97040da02577e2daca2", size = 226146 },
+ { url = "https://files.pythonhosted.org/packages/2f/70/e411a7254dc3bff6f7e6e004303b1b0591358e9f0b7c08639941e0de8bd6/multidict-6.4.4-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c27e5dcf520923d6474d98b96749e6805f7677e93aaaf62656005b8643f907ab", size = 220585 },
+ { url = "https://files.pythonhosted.org/packages/08/8f/beb3ae7406a619100d2b1fb0022c3bb55a8225ab53c5663648ba50dfcd56/multidict-6.4.4-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:058cc59b9e9b143cc56715e59e22941a5d868c322242278d28123a5d09cdf6b0", size = 212080 },
+ { url = "https://files.pythonhosted.org/packages/9c/ec/355124e9d3d01cf8edb072fd14947220f357e1c5bc79c88dff89297e9342/multidict-6.4.4-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:69133376bc9a03f8c47343d33f91f74a99c339e8b58cea90433d8e24bb298031", size = 226558 },
+ { url = "https://files.pythonhosted.org/packages/fd/22/d2b95cbebbc2ada3be3812ea9287dcc9712d7f1a012fad041770afddb2ad/multidict-6.4.4-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:d6b15c55721b1b115c5ba178c77104123745b1417527ad9641a4c5e2047450f0", size = 212168 },
+ { url = "https://files.pythonhosted.org/packages/4d/c5/62bfc0b2f9ce88326dbe7179f9824a939c6c7775b23b95de777267b9725c/multidict-6.4.4-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:a887b77f51d3d41e6e1a63cf3bc7ddf24de5939d9ff69441387dfefa58ac2e26", size = 217970 },
+ { url = "https://files.pythonhosted.org/packages/79/74/977cea1aadc43ff1c75d23bd5bc4768a8fac98c14e5878d6ee8d6bab743c/multidict-6.4.4-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:632a3bf8f1787f7ef7d3c2f68a7bde5be2f702906f8b5842ad6da9d974d0aab3", size = 226980 },
+ { url = "https://files.pythonhosted.org/packages/48/fc/cc4a1a2049df2eb84006607dc428ff237af38e0fcecfdb8a29ca47b1566c/multidict-6.4.4-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:a145c550900deb7540973c5cdb183b0d24bed6b80bf7bddf33ed8f569082535e", size = 220641 },
+ { url = "https://files.pythonhosted.org/packages/3b/6a/a7444d113ab918701988d4abdde373dbdfd2def7bd647207e2bf645c7eac/multidict-6.4.4-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:cc5d83c6619ca5c9672cb78b39ed8542f1975a803dee2cda114ff73cbb076edd", size = 221728 },
+ { url = "https://files.pythonhosted.org/packages/2b/b0/fdf4c73ad1c55e0f4dbbf2aa59dd37037334091f9a4961646d2b7ac91a86/multidict-6.4.4-cp313-cp313t-win32.whl", hash = "sha256:3312f63261b9df49be9d57aaa6abf53a6ad96d93b24f9cc16cf979956355ce6e", size = 41913 },
+ { url = "https://files.pythonhosted.org/packages/8e/92/27989ecca97e542c0d01d05a98a5ae12198a243a9ee12563a0313291511f/multidict-6.4.4-cp313-cp313t-win_amd64.whl", hash = "sha256:ba852168d814b2c73333073e1c7116d9395bea69575a01b0b3c89d2d5a87c8fb", size = 46112 },
+ { url = "https://files.pythonhosted.org/packages/18/5c/92607a79e7fd0361c90b3c5d79bbd186e3968e8a4832dbefcd7808f1c823/multidict-6.4.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:603f39bd1cf85705c6c1ba59644b480dfe495e6ee2b877908de93322705ad7cf", size = 66007 },
+ { url = "https://files.pythonhosted.org/packages/32/1e/212a154926a9290d8ae432e761d1c98ed95fccce84b1b938eaf1bf17378e/multidict-6.4.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:fc60f91c02e11dfbe3ff4e1219c085695c339af72d1641800fe6075b91850c8f", size = 38824 },
+ { url = "https://files.pythonhosted.org/packages/8b/64/5ca6fb5dbc7d5aa352cd2d013c86ae44133c3f4f6b83a80dacd42ee5c568/multidict-6.4.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:496bcf01c76a70a31c3d746fd39383aad8d685ce6331e4c709e9af4ced5fa221", size = 38117 },
+ { url = "https://files.pythonhosted.org/packages/aa/20/3aee7910260e7b6f0045b6f48b97ebf041de0cab513c12f87cf6e4e514d3/multidict-6.4.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4219390fb5bf8e548e77b428bb36a21d9382960db5321b74d9d9987148074d6b", size = 218106 },
+ { url = "https://files.pythonhosted.org/packages/a9/79/15f5a65b8de8ae8f3c5da1591a322620675e4fec8d39995b04101d2b2e2c/multidict-6.4.4-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef4e9096ff86dfdcbd4a78253090ba13b1d183daa11b973e842465d94ae1772", size = 213817 },
+ { url = "https://files.pythonhosted.org/packages/ab/a7/90de36db90ce2936fbb1639ca51508965861a8ad5dc2947531d18f3363b9/multidict-6.4.4-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:49a29d7133b1fc214e818bbe025a77cc6025ed9a4f407d2850373ddde07fd04a", size = 228133 },
+ { url = "https://files.pythonhosted.org/packages/df/25/5fcd66fda3c8b7d6d6f658a871017791c46824e965dfa20a4c46d4167ad4/multidict-6.4.4-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e32053d6d3a8b0dfe49fde05b496731a0e6099a4df92154641c00aa76786aef5", size = 224271 },
+ { url = "https://files.pythonhosted.org/packages/fd/9a/1011812091fd99b2dddd9d2dbde4b7d69bbf8070e0291fe49c3bb40c2d55/multidict-6.4.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8cc403092a49509e8ef2d2fd636a8ecefc4698cc57bbe894606b14579bc2a955", size = 216448 },
+ { url = "https://files.pythonhosted.org/packages/cf/cc/916e066b7e2686999f95dde87f588be26fa1c2f05e70d9fd472fe2289c0b/multidict-6.4.4-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5363f9b2a7f3910e5c87d8b1855c478c05a2dc559ac57308117424dfaad6805c", size = 210080 },
+ { url = "https://files.pythonhosted.org/packages/f8/ff/15034b18f2e4179cd559aa13bc3b376a95c22e1fd7c3b88884e078ad5466/multidict-6.4.4-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:2e543a40e4946cf70a88a3be87837a3ae0aebd9058ba49e91cacb0b2cd631e2b", size = 221926 },
+ { url = "https://files.pythonhosted.org/packages/17/43/4243298a6b0b869a83b6331f3fcc12a2a0544c0995292ee96badf0fec6aa/multidict-6.4.4-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:60d849912350da557fe7de20aa8cf394aada6980d0052cc829eeda4a0db1c1db", size = 211318 },
+ { url = "https://files.pythonhosted.org/packages/fe/80/bc43c87d60138e401c7d1818a47e5a0f748904c9f3be99012cdab5e31446/multidict-6.4.4-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:19d08b4f22eae45bb018b9f06e2838c1e4b853c67628ef8ae126d99de0da6395", size = 217611 },
+ { url = "https://files.pythonhosted.org/packages/1e/5d/2ec94209254e48910911ac2404d71b37f06fd97ec83948a92d0c87a11d3c/multidict-6.4.4-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:d693307856d1ef08041e8b6ff01d5b4618715007d288490ce2c7e29013c12b9a", size = 227893 },
+ { url = "https://files.pythonhosted.org/packages/71/83/89344adc0cf08fd89d82d43de1a17a2635b03a57dfa680f6cdf2a24d481f/multidict-6.4.4-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:fad6daaed41021934917f4fb03ca2db8d8a4d79bf89b17ebe77228eb6710c003", size = 221956 },
+ { url = "https://files.pythonhosted.org/packages/f0/ea/81382bb59cd3a1047d1c2ea9339d2107fc918a63491bbb9399eb1aceda91/multidict-6.4.4-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:c10d17371bff801af0daf8b073c30b6cf14215784dc08cd5c43ab5b7b8029bbc", size = 216850 },
+ { url = "https://files.pythonhosted.org/packages/0f/90/c848d62de66c2958932ce155adae418cbf79d96cfaf992e5255819f8f1d9/multidict-6.4.4-cp39-cp39-win32.whl", hash = "sha256:7e23f2f841fcb3ebd4724a40032d32e0892fbba4143e43d2a9e7695c5e50e6bd", size = 35235 },
+ { url = "https://files.pythonhosted.org/packages/d4/19/dd625207c92889c1ae7b89fcbde760d99853265cfe7ffb0826393151acd1/multidict-6.4.4-cp39-cp39-win_amd64.whl", hash = "sha256:4d7b50b673ffb4ff4366e7ab43cf1f0aef4bd3608735c5fbdf0bdb6f690da411", size = 38821 },
+ { url = "https://files.pythonhosted.org/packages/84/5d/e17845bb0fa76334477d5de38654d27946d5b5d3695443987a094a71b440/multidict-6.4.4-py3-none-any.whl", hash = "sha256:bd4557071b561a8b3b6075c3ce93cf9bfb6182cb241805c3d66ced3b75eff4ac", size = 10481 },
+]
+
+[[package]]
+name = "multiprocess"
+version = "0.70.16"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "dill" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b5/ae/04f39c5d0d0def03247c2893d6f2b83c136bf3320a2154d7b8858f2ba72d/multiprocess-0.70.16.tar.gz", hash = "sha256:161af703d4652a0e1410be6abccecde4a7ddffd19341be0a7011b94aeb171ac1", size = 1772603 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ef/76/6e712a2623d146d314f17598df5de7224c85c0060ef63fd95cc15a25b3fa/multiprocess-0.70.16-pp310-pypy310_pp73-macosx_10_13_x86_64.whl", hash = "sha256:476887be10e2f59ff183c006af746cb6f1fd0eadcfd4ef49e605cbe2659920ee", size = 134980 },
+ { url = "https://files.pythonhosted.org/packages/0f/ab/1e6e8009e380e22254ff539ebe117861e5bdb3bff1fc977920972237c6c7/multiprocess-0.70.16-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:d951bed82c8f73929ac82c61f01a7b5ce8f3e5ef40f5b52553b4f547ce2b08ec", size = 134982 },
+ { url = "https://files.pythonhosted.org/packages/d8/94/8638a89f93c80df329116e6781a060506c7e91e1f4370dc831e9d17a041d/multiprocess-0.70.16-pp39-pypy39_pp73-macosx_10_13_x86_64.whl", hash = "sha256:0dfd078c306e08d46d7a8d06fb120313d87aa43af60d66da43ffff40b44d2f41", size = 133497 },
+ { url = "https://files.pythonhosted.org/packages/89/21/222066f6bb8d8af287923ae3bd26cf4699a9ce020228ac273caca1de8250/multiprocess-0.70.16-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:e7b9d0f307cd9bd50851afaac0dba2cb6c44449efff697df7c7645f7d3f2be3a", size = 133498 },
+ { url = "https://files.pythonhosted.org/packages/bc/f7/7ec7fddc92e50714ea3745631f79bd9c96424cb2702632521028e57d3a36/multiprocess-0.70.16-py310-none-any.whl", hash = "sha256:c4a9944c67bd49f823687463660a2d6daae94c289adff97e0f9d696ba6371d02", size = 134824 },
+ { url = "https://files.pythonhosted.org/packages/50/15/b56e50e8debaf439f44befec5b2af11db85f6e0f344c3113ae0be0593a91/multiprocess-0.70.16-py311-none-any.whl", hash = "sha256:af4cabb0dac72abfb1e794fa7855c325fd2b55a10a44628a3c1ad3311c04127a", size = 143519 },
+ { url = "https://files.pythonhosted.org/packages/0a/7d/a988f258104dcd2ccf1ed40fdc97e26c4ac351eeaf81d76e266c52d84e2f/multiprocess-0.70.16-py312-none-any.whl", hash = "sha256:fc0544c531920dde3b00c29863377f87e1632601092ea2daca74e4beb40faa2e", size = 146741 },
+ { url = "https://files.pythonhosted.org/packages/ea/89/38df130f2c799090c978b366cfdf5b96d08de5b29a4a293df7f7429fa50b/multiprocess-0.70.16-py38-none-any.whl", hash = "sha256:a71d82033454891091a226dfc319d0cfa8019a4e888ef9ca910372a446de4435", size = 132628 },
+ { url = "https://files.pythonhosted.org/packages/da/d9/f7f9379981e39b8c2511c9e0326d212accacb82f12fbfdc1aa2ce2a7b2b6/multiprocess-0.70.16-py39-none-any.whl", hash = "sha256:a0bafd3ae1b732eac64be2e72038231c1ba97724b60b09400d68f229fcc2fbf3", size = 133351 },
+]
+
+[[package]]
+name = "mypy-extensions"
+version = "1.1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963 },
+]
+
+[[package]]
+name = "nest-asyncio"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195 },
+]
+
+[[package]]
+name = "networkx"
+version = "3.2.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c4/80/a84676339aaae2f1cfdf9f418701dd634aef9cc76f708ef55c36ff39c3ca/networkx-3.2.1.tar.gz", hash = "sha256:9f1bb5cf3409bf324e0a722c20bdb4c20ee39bf1c30ce8ae499c8502b0b5e0c6", size = 2073928 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d5/f0/8fbc882ca80cf077f1b246c0e3c3465f7f415439bdea6b899f6b19f61f70/networkx-3.2.1-py3-none-any.whl", hash = "sha256:f18c69adc97877c42332c170849c96cefa91881c99a7cb3e95b7c659ebdc1ec2", size = 1647772 },
+]
+
+[[package]]
+name = "networkx"
+version = "3.4.2"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fd/1d/06475e1cd5264c0b870ea2cc6fdb3e37177c1e565c43f56ff17a10e3937f/networkx-3.4.2.tar.gz", hash = "sha256:307c3669428c5362aab27c8a1260aa8f47c4e91d3891f48be0141738d8d053e1", size = 2151368 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b9/54/dd730b32ea14ea797530a4479b2ed46a6fb250f682a9cfb997e968bf0261/networkx-3.4.2-py3-none-any.whl", hash = "sha256:df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", size = 1723263 },
+]
+
+[[package]]
+name = "networkx"
+version = "3.5"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6c/4f/ccdb8ad3a38e583f214547fd2f7ff1fc160c43a75af88e6aec213404b96a/networkx-3.5.tar.gz", hash = "sha256:d4c6f9cf81f52d69230866796b82afbccdec3db7ae4fbd1b65ea750feed50037", size = 2471065 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl", hash = "sha256:0030d386a9a06dee3565298b4a734b68589749a544acbb6c412dc9e2489ec6ec", size = 2034406 },
+]
+
+[[package]]
+name = "ninja"
+version = "1.11.1.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/95/d4/6b0324541018561c5e73e617bd16f20a4fc17d1179bb3b3520b6ca8beb7b/ninja-1.11.1.4.tar.gz", hash = "sha256:6aa39f6e894e0452e5b297327db00019383ae55d5d9c57c73b04f13bf79d438a", size = 201256 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4f/b1/3a61b348936b62a386465b1937cd778fa3a5748582e26d832dbab844ff27/ninja-1.11.1.4-py3-none-macosx_10_9_universal2.whl", hash = "sha256:b33923c8da88e8da20b6053e38deb433f53656441614207e01d283ad02c5e8e7", size = 279071 },
+ { url = "https://files.pythonhosted.org/packages/12/42/4c94fdad51fcf1f039a156e97de9e4d564c2a8cc0303782d36f9bd893a4b/ninja-1.11.1.4-py3-none-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:cede0af00b58e27b31f2482ba83292a8e9171cdb9acc2c867a3b6e40b3353e43", size = 472026 },
+ { url = "https://files.pythonhosted.org/packages/eb/7a/455d2877fe6cf99886849c7f9755d897df32eaf3a0fba47b56e615f880f7/ninja-1.11.1.4-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:096487995473320de7f65d622c3f1d16c3ad174797602218ca8c967f51ec38a0", size = 422814 },
+ { url = "https://files.pythonhosted.org/packages/e3/ad/fb6cca942528e25e8e0ab0f0cf98fe007319bf05cf69d726c564b815c4af/ninja-1.11.1.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3090d4488fadf6047d0d7a1db0c9643a8d391f0d94729554dbb89b5bdc769d7", size = 156965 },
+ { url = "https://files.pythonhosted.org/packages/a8/e7/d94a1b60031b115dd88526834b3da69eaacdc3c1a6769773ca8e2b1386b5/ninja-1.11.1.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ecce44a00325a93631792974659cf253a815cc6da4ec96f89742925dfc295a0d", size = 179937 },
+ { url = "https://files.pythonhosted.org/packages/08/cc/e9316a28235409e9363794fc3d0b3083e48dd80d441006de66421e55f364/ninja-1.11.1.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9c29bb66d2aa46a2409ab369ea804c730faec7652e8c22c1e428cc09216543e5", size = 157020 },
+ { url = "https://files.pythonhosted.org/packages/e3/30/389b22300541aa5f2e9dad322c4de2f84be4e32aa4e8babd9160d620b5f1/ninja-1.11.1.4-py3-none-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:055f386fb550c2c9d6157e45e20a84d29c47968876b9c5794ae2aec46f952306", size = 130389 },
+ { url = "https://files.pythonhosted.org/packages/a9/10/e27f35cb92813aabbb7ae771b1685b45be1cc8a0798ce7d4bfd08d142b93/ninja-1.11.1.4-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:f6186d7607bb090c3be1e10c8a56b690be238f953616626f5032238c66e56867", size = 372435 },
+ { url = "https://files.pythonhosted.org/packages/c2/26/e3559619756739aae124c6abf7fe41f7e546ab1209cfbffb13137bff2d2e/ninja-1.11.1.4-py3-none-musllinux_1_1_i686.whl", hash = "sha256:cf4453679d15babc04ba023d68d091bb613091b67101c88f85d2171c6621c6eb", size = 419300 },
+ { url = "https://files.pythonhosted.org/packages/35/46/809e4e9572570991b8e6f88f3583807d017371ab4cb09171cbc72a7eb3e4/ninja-1.11.1.4-py3-none-musllinux_1_1_ppc64le.whl", hash = "sha256:d4a6f159b08b0ac4aca5ee1572e3e402f969139e71d85d37c0e2872129098749", size = 420239 },
+ { url = "https://files.pythonhosted.org/packages/e6/64/5cb5710d15f844edf02ada577f8eddfdcd116f47eec15850f3371a3a4b33/ninja-1.11.1.4-py3-none-musllinux_1_1_s390x.whl", hash = "sha256:c3b96bd875f3ef1db782470e9e41d7508905a0986571f219d20ffed238befa15", size = 415986 },
+ { url = "https://files.pythonhosted.org/packages/95/b2/0e9ab1d926f423b12b09925f78afcc5e48b3c22e7121be3ddf6c35bf06a3/ninja-1.11.1.4-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:cf554e73f72c04deb04d0cf51f5fdb1903d9c9ca3d2344249c8ce3bd616ebc02", size = 379657 },
+ { url = "https://files.pythonhosted.org/packages/c8/3e/fd6d330d0434168e7fe070d414b57dd99c4c133faa69c05b42a3cbdc6c13/ninja-1.11.1.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:cfdd09776436a1ff3c4a2558d3fc50a689fb9d7f1bdbc3e6f7b8c2991341ddb3", size = 454466 },
+ { url = "https://files.pythonhosted.org/packages/e6/df/a25f3ad0b1c59d1b90564096e4fd89a6ca30d562b1e942f23880c3000b89/ninja-1.11.1.4-py3-none-win32.whl", hash = "sha256:2ab67a41c90bea5ec4b795bab084bc0b3b3bb69d3cd21ca0294fc0fc15a111eb", size = 255931 },
+ { url = "https://files.pythonhosted.org/packages/5b/10/9b8fe9ac004847490cc7b54896124c01ce2d87d95dc60aabd0b8591addff/ninja-1.11.1.4-py3-none-win_amd64.whl", hash = "sha256:4617b3c12ff64b611a7d93fd9e378275512bb36eff8babff7c83f5116b4f8d66", size = 296461 },
+ { url = "https://files.pythonhosted.org/packages/b9/58/612a17593c2d117f96c7f6b7f1e6570246bddc4b1e808519403a1417f217/ninja-1.11.1.4-py3-none-win_arm64.whl", hash = "sha256:5713cf50c5be50084a8693308a63ecf9e55c3132a78a41ab1363a28b6caaaee1", size = 271441 },
+]
+
+[[package]]
+name = "nltk"
+version = "3.9.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "joblib" },
+ { name = "regex" },
+ { name = "tqdm" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3c/87/db8be88ad32c2d042420b6fd9ffd4a149f9a0d7f0e86b3f543be2eeeedd2/nltk-3.9.1.tar.gz", hash = "sha256:87d127bd3de4bd89a4f81265e5fa59cb1b199b27440175370f7417d2bc7ae868", size = 2904691 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4d/66/7d9e26593edda06e8cb531874633f7c2372279c3b0f46235539fe546df8b/nltk-3.9.1-py3-none-any.whl", hash = "sha256:4fa26829c5b00715afe3061398a8989dc643b92ce7dd93fb4585a70930d168a1", size = 1505442 },
+]
+
+[[package]]
+name = "numpy"
+version = "1.25.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d0/b2/fe774844d1857804cc884bba67bec38f649c99d0dc1ee7cbbf1da601357c/numpy-1.25.0.tar.gz", hash = "sha256:f1accae9a28dc3cda46a91de86acf69de0d1b5f4edd44a9b0c3ceb8036dfff19", size = 10426700 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a7/71/8cadc39a58fc18a91ad135c3a33b6a6a7c0ccf00adb4263d6f2aebf8124d/numpy-1.25.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:8aa130c3042052d656751df5e81f6d61edff3e289b5994edcf77f54118a8d9f4", size = 20055608 },
+ { url = "https://files.pythonhosted.org/packages/c8/7c/87cf5dc663803120901302db2494e625d762e19060b390d925e3e8666b18/numpy-1.25.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9e3f2b96e3b63c978bc29daaa3700c028fe3f049ea3031b58aa33fe2a5809d24", size = 13963319 },
+ { url = "https://files.pythonhosted.org/packages/ed/f6/1ce8d0bdcf926a5d94ae2a793eee4364c76ba2d1a5b73ee9de9aebc3a0e0/numpy-1.25.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d6b267f349a99d3908b56645eebf340cb58f01bd1e773b4eea1a905b3f0e4208", size = 14132512 },
+ { url = "https://files.pythonhosted.org/packages/77/03/79b0bfc6e9dcd5eabbb17a714a2480ad3f932063eb8b39f6116ac207d5e3/numpy-1.25.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4aedd08f15d3045a4e9c648f1e04daca2ab1044256959f1f95aafeeb3d794c16", size = 17612667 },
+ { url = "https://files.pythonhosted.org/packages/a8/a5/dded2b52d4a460f265973f2aaedc5ea82814d471241e5d17599506c4ee0e/numpy-1.25.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:6d183b5c58513f74225c376643234c369468e02947b47942eacbb23c1671f25d", size = 17449973 },
+ { url = "https://files.pythonhosted.org/packages/a5/c7/586bc658351595f252dd6fa31a14ca28ca7de7d93171f933b1c193e7e32c/numpy-1.25.0-cp310-cp310-win32.whl", hash = "sha256:d76a84998c51b8b68b40448ddd02bd1081bb33abcdc28beee6cd284fe11036c6", size = 12607709 },
+ { url = "https://files.pythonhosted.org/packages/13/a0/bd219e125915e1d5706a5d00b87cd93932d6a204d976aea09fa0f36af5a1/numpy-1.25.0-cp310-cp310-win_amd64.whl", hash = "sha256:c0dc071017bc00abb7d7201bac06fa80333c6314477b3d10b52b58fa6a6e38f6", size = 15034656 },
+ { url = "https://files.pythonhosted.org/packages/bb/b9/0f7a1d48d5c65c7a2cc8d5de119318a254351a0146e696855ade26615455/numpy-1.25.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c69fe5f05eea336b7a740e114dec995e2f927003c30702d896892403df6dbf0", size = 20041989 },
+ { url = "https://files.pythonhosted.org/packages/e8/bd/937ffc7345985456c963089418c4c7efdb2ca3af36624c5ea60a07d99bcf/numpy-1.25.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9c7211d7920b97aeca7b3773a6783492b5b93baba39e7c36054f6e749fc7490c", size = 13973163 },
+ { url = "https://files.pythonhosted.org/packages/8c/00/a65518f58b9bbba597cd757a765d7a34fea3d8fd089a8ecc7f6eb4e4f42d/numpy-1.25.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ecc68f11404930e9c7ecfc937aa423e1e50158317bf67ca91736a9864eae0232", size = 14123400 },
+ { url = "https://files.pythonhosted.org/packages/f6/ae/546c18cad7525242d87def9ee1cba2e407028044f79c023ea8b2a11397d2/numpy-1.25.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e559c6afbca484072a98a51b6fa466aae785cfe89b69e8b856c3191bc8872a82", size = 17602714 },
+ { url = "https://files.pythonhosted.org/packages/fa/9f/9023a2135a86a80369c942670ef23c2c838aee3408f982e3b9bcaf9ffe61/numpy-1.25.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:6c284907e37f5e04d2412950960894b143a648dea3f79290757eb878b91acbd1", size = 17453872 },
+ { url = "https://files.pythonhosted.org/packages/ef/29/a2503fed1bb38902e789f3e73259d760911fb7b51420896716502c727aa1/numpy-1.25.0-cp311-cp311-win32.whl", hash = "sha256:95367ccd88c07af21b379be1725b5322362bb83679d36691f124a16357390153", size = 12600664 },
+ { url = "https://files.pythonhosted.org/packages/de/8b/b2d73b913be92056b1f77b0b9d184d93f368353540adf91e699a10a2effb/numpy-1.25.0-cp311-cp311-win_amd64.whl", hash = "sha256:b76aa836a952059d70a2788a2d98cb2a533ccd46222558b6970348939e55fc24", size = 15026783 },
+ { url = "https://files.pythonhosted.org/packages/f4/73/08500367cf69634970c87d11bcc82dc0daf4d9554a3e5d4a3750f26c25b7/numpy-1.25.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b792164e539d99d93e4e5e09ae10f8cbe5466de7d759fc155e075237e0c274e4", size = 20087986 },
+ { url = "https://files.pythonhosted.org/packages/d0/62/7c85c27e4277b142a91023bfb69ba27f1783777d31f5e920b314e1a92f69/numpy-1.25.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:7cd981ccc0afe49b9883f14761bb57c964df71124dcd155b0cba2b591f0d64b9", size = 13990971 },
+ { url = "https://files.pythonhosted.org/packages/d2/b0/ce6c0056f057e681b0b9f78900e122715389f865047c25fc2f37bfe2f8fe/numpy-1.25.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5aa48bebfb41f93043a796128854b84407d4df730d3fb6e5dc36402f5cd594c0", size = 14171380 },
+ { url = "https://files.pythonhosted.org/packages/68/44/1ff079e62f44fc6d17aea45ec6a7008c033c9a59972644c320c4fda95a49/numpy-1.25.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5177310ac2e63d6603f659fadc1e7bab33dd5a8db4e0596df34214eeab0fee3b", size = 17657037 },
+ { url = "https://files.pythonhosted.org/packages/8e/de/a6cddb5b3b2ffd03bc0061dcb7c0edeaff2d10460eed8e0e9a57341ce455/numpy-1.25.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:0ac6edfb35d2a99aaf102b509c8e9319c499ebd4978df4971b94419a116d0790", size = 17482524 },
+ { url = "https://files.pythonhosted.org/packages/52/68/ce0a665654fbc26a00ba9dfbd98a6f749246576bbc826710676ca9f67a1c/numpy-1.25.0-cp39-cp39-win32.whl", hash = "sha256:7412125b4f18aeddca2ecd7219ea2d2708f697943e6f624be41aa5f8a9852cc4", size = 12636181 },
+ { url = "https://files.pythonhosted.org/packages/50/4b/2246882e9c89e8da081296bef4539ab1d44bf97f757931ddaf5f7d0a3b58/numpy-1.25.0-cp39-cp39-win_amd64.whl", hash = "sha256:26815c6c8498dc49d81faa76d61078c4f9f0859ce7817919021b9eba72b425e3", size = 15061375 },
+ { url = "https://files.pythonhosted.org/packages/e3/51/524ba2b98e083b59dc287011adc6829778c496998aa329715a6a13ae4735/numpy-1.25.0-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:5b1b90860bf7d8a8c313b372d4f27343a54f415b20fb69dd601b7efe1029c91e", size = 19409896 },
+ { url = "https://files.pythonhosted.org/packages/75/74/7eec4db7eea3796fe6f47bc358c24447fc66a080ac2fd35cbe4a3cd8d17b/numpy-1.25.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:85cdae87d8c136fd4da4dad1e48064d700f63e923d5af6c8c782ac0df8044542", size = 17011428 },
+ { url = "https://files.pythonhosted.org/packages/76/72/d9e66a7bef82261aff26c71b8ac8b13fa2ffa965e046be958f949ca3388f/numpy-1.25.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:cc3fda2b36482891db1060f00f881c77f9423eead4c3579629940a3e12095fe8", size = 14922176 },
+]
+
+[[package]]
+name = "nvidia-cublas-cu12"
+version = "12.6.4.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/af/eb/ff4b8c503fa1f1796679dce648854d58751982426e4e4b37d6fce49d259c/nvidia_cublas_cu12-12.6.4.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08ed2686e9875d01b58e3cb379c6896df8e76c75e0d4a7f7dace3d7b6d9ef8eb", size = 393138322 },
+]
+
+[[package]]
+name = "nvidia-cuda-cupti-cu12"
+version = "12.6.80"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/60/7b6497946d74bcf1de852a21824d63baad12cd417db4195fc1bfe59db953/nvidia_cuda_cupti_cu12-12.6.80-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6768bad6cab4f19e8292125e5f1ac8aa7d1718704012a0e3272a6f61c4bce132", size = 8917980 },
+ { url = "https://files.pythonhosted.org/packages/a5/24/120ee57b218d9952c379d1e026c4479c9ece9997a4fb46303611ee48f038/nvidia_cuda_cupti_cu12-12.6.80-py3-none-manylinux2014_x86_64.whl", hash = "sha256:a3eff6cdfcc6a4c35db968a06fcadb061cbc7d6dde548609a941ff8701b98b73", size = 8917972 },
+]
+
+[[package]]
+name = "nvidia-cuda-nvrtc-cu12"
+version = "12.6.77"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/75/2e/46030320b5a80661e88039f59060d1790298b4718944a65a7f2aeda3d9e9/nvidia_cuda_nvrtc_cu12-12.6.77-py3-none-manylinux2014_x86_64.whl", hash = "sha256:35b0cc6ee3a9636d5409133e79273ce1f3fd087abb0532d2d2e8fff1fe9efc53", size = 23650380 },
+]
+
+[[package]]
+name = "nvidia-cuda-runtime-cu12"
+version = "12.6.77"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/23/e717c5ac26d26cf39a27fbc076240fad2e3b817e5889d671b67f4f9f49c5/nvidia_cuda_runtime_cu12-12.6.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ba3b56a4f896141e25e19ab287cd71e52a6a0f4b29d0d31609f60e3b4d5219b7", size = 897690 },
+ { url = "https://files.pythonhosted.org/packages/f0/62/65c05e161eeddbafeca24dc461f47de550d9fa8a7e04eb213e32b55cfd99/nvidia_cuda_runtime_cu12-12.6.77-py3-none-manylinux2014_x86_64.whl", hash = "sha256:a84d15d5e1da416dd4774cb42edf5e954a3e60cc945698dc1d5be02321c44dc8", size = 897678 },
+]
+
+[[package]]
+name = "nvidia-cudnn-cu12"
+version = "9.5.1.17"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cublas-cu12" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/78/4535c9c7f859a64781e43c969a3a7e84c54634e319a996d43ef32ce46f83/nvidia_cudnn_cu12-9.5.1.17-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:30ac3869f6db17d170e0e556dd6cc5eee02647abc31ca856634d5a40f82c15b2", size = 570988386 },
+]
+
+[[package]]
+name = "nvidia-cufft-cu12"
+version = "11.3.0.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-nvjitlink-cu12" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8f/16/73727675941ab8e6ffd86ca3a4b7b47065edcca7a997920b831f8147c99d/nvidia_cufft_cu12-11.3.0.4-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ccba62eb9cef5559abd5e0d54ceed2d9934030f51163df018532142a8ec533e5", size = 200221632 },
+ { url = "https://files.pythonhosted.org/packages/60/de/99ec247a07ea40c969d904fc14f3a356b3e2a704121675b75c366b694ee1/nvidia_cufft_cu12-11.3.0.4-py3-none-manylinux2014_x86_64.whl", hash = "sha256:768160ac89f6f7b459bee747e8d175dbf53619cfe74b2a5636264163138013ca", size = 200221622 },
+]
+
+[[package]]
+name = "nvidia-cufile-cu12"
+version = "1.11.1.6"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b2/66/cc9876340ac68ae71b15c743ddb13f8b30d5244af344ec8322b449e35426/nvidia_cufile_cu12-1.11.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cc23469d1c7e52ce6c1d55253273d32c565dd22068647f3aa59b3c6b005bf159", size = 1142103 },
+]
+
+[[package]]
+name = "nvidia-curand-cu12"
+version = "10.3.7.77"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/73/1b/44a01c4e70933637c93e6e1a8063d1e998b50213a6b65ac5a9169c47e98e/nvidia_curand_cu12-10.3.7.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a42cd1344297f70b9e39a1e4f467a4e1c10f1da54ff7a85c12197f6c652c8bdf", size = 56279010 },
+ { url = "https://files.pythonhosted.org/packages/4a/aa/2c7ff0b5ee02eaef890c0ce7d4f74bc30901871c5e45dee1ae6d0083cd80/nvidia_curand_cu12-10.3.7.77-py3-none-manylinux2014_x86_64.whl", hash = "sha256:99f1a32f1ac2bd134897fc7a203f779303261268a65762a623bf30cc9fe79117", size = 56279000 },
+]
+
+[[package]]
+name = "nvidia-cusolver-cu12"
+version = "11.7.1.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cublas-cu12" },
+ { name = "nvidia-cusparse-cu12" },
+ { name = "nvidia-nvjitlink-cu12" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f0/6e/c2cf12c9ff8b872e92b4a5740701e51ff17689c4d726fca91875b07f655d/nvidia_cusolver_cu12-11.7.1.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e9e49843a7707e42022babb9bcfa33c29857a93b88020c4e4434656a655b698c", size = 158229790 },
+ { url = "https://files.pythonhosted.org/packages/9f/81/baba53585da791d043c10084cf9553e074548408e04ae884cfe9193bd484/nvidia_cusolver_cu12-11.7.1.2-py3-none-manylinux2014_x86_64.whl", hash = "sha256:6cf28f17f64107a0c4d7802be5ff5537b2130bfc112f25d5a30df227058ca0e6", size = 158229780 },
+]
+
+[[package]]
+name = "nvidia-cusparse-cu12"
+version = "12.5.4.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-nvjitlink-cu12" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/06/1e/b8b7c2f4099a37b96af5c9bb158632ea9e5d9d27d7391d7eb8fc45236674/nvidia_cusparse_cu12-12.5.4.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7556d9eca156e18184b94947ade0fba5bb47d69cec46bf8660fd2c71a4b48b73", size = 216561367 },
+ { url = "https://files.pythonhosted.org/packages/43/ac/64c4316ba163e8217a99680c7605f779accffc6a4bcd0c778c12948d3707/nvidia_cusparse_cu12-12.5.4.2-py3-none-manylinux2014_x86_64.whl", hash = "sha256:23749a6571191a215cb74d1cdbff4a86e7b19f1200c071b3fcf844a5bea23a2f", size = 216561357 },
+]
+
+[[package]]
+name = "nvidia-cusparselt-cu12"
+version = "0.6.3"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3b/9a/72ef35b399b0e183bc2e8f6f558036922d453c4d8237dab26c666a04244b/nvidia_cusparselt_cu12-0.6.3-py3-none-manylinux2014_x86_64.whl", hash = "sha256:e5c8a26c36445dd2e6812f1177978a24e2d37cacce7e090f297a688d1ec44f46", size = 156785796 },
+]
+
+[[package]]
+name = "nvidia-ml-py"
+version = "12.575.51"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d2/4d/6f017814ed5ac28e08e1b8a62e3a258957da27582c89b7f8f8b15ac3d2e7/nvidia_ml_py-12.575.51.tar.gz", hash = "sha256:6490e93fea99eb4e966327ae18c6eec6256194c921f23459c8767aee28c54581", size = 46597 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/db/24/552ebea28f0570b9e65e62b50287a273804c9f997cc1c2dcd4e2d64b9e7d/nvidia_ml_py-12.575.51-py3-none-any.whl", hash = "sha256:eb8641800d98ce40a22f479873f34b482e214a7e80349c63be51c3919845446e", size = 47547 },
+]
+
+[[package]]
+name = "nvidia-nccl-cu12"
+version = "2.26.2"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/67/ca/f42388aed0fddd64ade7493dbba36e1f534d4e6fdbdd355c6a90030ae028/nvidia_nccl_cu12-2.26.2-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:694cf3879a206553cc9d7dbda76b13efaf610fdb70a50cba303de1b0d1530ac6", size = 201319755 },
+]
+
+[[package]]
+name = "nvidia-nvjitlink-cu12"
+version = "12.6.85"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9d/d7/c5383e47c7e9bf1c99d5bd2a8c935af2b6d705ad831a7ec5c97db4d82f4f/nvidia_nvjitlink_cu12-12.6.85-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:eedc36df9e88b682efe4309aa16b5b4e78c2407eac59e8c10a6a47535164369a", size = 19744971 },
+]
+
+[[package]]
+name = "nvidia-nvtx-cu12"
+version = "12.6.77"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/56/9a/fff8376f8e3d084cd1530e1ef7b879bb7d6d265620c95c1b322725c694f4/nvidia_nvtx_cu12-12.6.77-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b90bed3df379fa79afbd21be8e04a0314336b8ae16768b58f2d34cb1d04cd7d2", size = 89276 },
+ { url = "https://files.pythonhosted.org/packages/9e/4e/0d0c945463719429b7bd21dece907ad0bde437a2ff12b9b12fee94722ab0/nvidia_nvtx_cu12-12.6.77-py3-none-manylinux2014_x86_64.whl", hash = "sha256:6574241a3ec5fdc9334353ab8c479fe75841dbe8f4532a8fc97ce63503330ba1", size = 89265 },
+]
+
+[[package]]
+name = "ollama"
+version = "0.5.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "httpx" },
+ { name = "pydantic" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/8d/96/c7fe0d2d1b3053be614822a7b722c7465161b3672ce90df71515137580a0/ollama-0.5.1.tar.gz", hash = "sha256:5a799e4dc4e7af638b11e3ae588ab17623ee019e496caaf4323efbaa8feeff93", size = 41112 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d6/76/3f96c8cdbf3955d7a73ee94ce3e0db0755d6de1e0098a70275940d1aff2f/ollama-0.5.1-py3-none-any.whl", hash = "sha256:4c8839f35bc173c7057b1eb2cbe7f498c1a7e134eafc9192824c8aecb3617506", size = 13369 },
+]
+
+[[package]]
+name = "openai"
+version = "1.86.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "distro" },
+ { name = "httpx" },
+ { name = "jiter" },
+ { name = "pydantic" },
+ { name = "sniffio" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ec/7a/9ad4a61f1502f0e59d8c27fb629e28a63259a44d8d31cd2314e1534a2d9f/openai-1.86.0.tar.gz", hash = "sha256:c64d5b788359a8fdf69bd605ae804ce41c1ce2e78b8dd93e2542e0ee267f1e4b", size = 468272 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/58/c1/dfb16b3432810fc9758564f9d1a4dbce6b93b7fb763ba57530c7fc48316d/openai-1.86.0-py3-none-any.whl", hash = "sha256:c8889c39410621fe955c230cc4c21bfe36ec887f4e60a957de05f507d7e1f349", size = 730296 },
+]
+
+[[package]]
+name = "orjson"
+version = "3.10.18"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/81/0b/fea456a3ffe74e70ba30e01ec183a9b26bec4d497f61dcfce1b601059c60/orjson-3.10.18.tar.gz", hash = "sha256:e8da3947d92123eda795b68228cafe2724815621fe35e8e320a9e9593a4bcd53", size = 5422810 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/27/16/2ceb9fb7bc2b11b1e4a3ea27794256e93dee2309ebe297fd131a778cd150/orjson-3.10.18-cp310-cp310-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:a45e5d68066b408e4bc383b6e4ef05e717c65219a9e1390abc6155a520cac402", size = 248927 },
+ { url = "https://files.pythonhosted.org/packages/3d/e1/d3c0a2bba5b9906badd121da449295062b289236c39c3a7801f92c4682b0/orjson-3.10.18-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be3b9b143e8b9db05368b13b04c84d37544ec85bb97237b3a923f076265ec89c", size = 136995 },
+ { url = "https://files.pythonhosted.org/packages/d7/51/698dd65e94f153ee5ecb2586c89702c9e9d12f165a63e74eb9ea1299f4e1/orjson-3.10.18-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:9b0aa09745e2c9b3bf779b096fa71d1cc2d801a604ef6dd79c8b1bfef52b2f92", size = 132893 },
+ { url = "https://files.pythonhosted.org/packages/b3/e5/155ce5a2c43a85e790fcf8b985400138ce5369f24ee6770378ee6b691036/orjson-3.10.18-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:53a245c104d2792e65c8d225158f2b8262749ffe64bc7755b00024757d957a13", size = 137017 },
+ { url = "https://files.pythonhosted.org/packages/46/bb/6141ec3beac3125c0b07375aee01b5124989907d61c72c7636136e4bd03e/orjson-3.10.18-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f9495ab2611b7f8a0a8a505bcb0f0cbdb5469caafe17b0e404c3c746f9900469", size = 138290 },
+ { url = "https://files.pythonhosted.org/packages/77/36/6961eca0b66b7809d33c4ca58c6bd4c23a1b914fb23aba2fa2883f791434/orjson-3.10.18-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:73be1cbcebadeabdbc468f82b087df435843c809cd079a565fb16f0f3b23238f", size = 142828 },
+ { url = "https://files.pythonhosted.org/packages/8b/2f/0c646d5fd689d3be94f4d83fa9435a6c4322c9b8533edbb3cd4bc8c5f69a/orjson-3.10.18-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fe8936ee2679e38903df158037a2f1c108129dee218975122e37847fb1d4ac68", size = 132806 },
+ { url = "https://files.pythonhosted.org/packages/ea/af/65907b40c74ef4c3674ef2bcfa311c695eb934710459841b3c2da212215c/orjson-3.10.18-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:7115fcbc8525c74e4c2b608129bef740198e9a120ae46184dac7683191042056", size = 135005 },
+ { url = "https://files.pythonhosted.org/packages/c7/d1/68bd20ac6a32cd1f1b10d23e7cc58ee1e730e80624e3031d77067d7150fc/orjson-3.10.18-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:771474ad34c66bc4d1c01f645f150048030694ea5b2709b87d3bda273ffe505d", size = 413418 },
+ { url = "https://files.pythonhosted.org/packages/31/31/c701ec0bcc3e80e5cb6e319c628ef7b768aaa24b0f3b4c599df2eaacfa24/orjson-3.10.18-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:7c14047dbbea52886dd87169f21939af5d55143dad22d10db6a7514f058156a8", size = 153288 },
+ { url = "https://files.pythonhosted.org/packages/d9/31/5e1aa99a10893a43cfc58009f9da840990cc8a9ebb75aa452210ba18587e/orjson-3.10.18-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:641481b73baec8db14fdf58f8967e52dc8bda1f2aba3aa5f5c1b07ed6df50b7f", size = 137181 },
+ { url = "https://files.pythonhosted.org/packages/bf/8c/daba0ac1b8690011d9242a0f37235f7d17df6d0ad941021048523b76674e/orjson-3.10.18-cp310-cp310-win32.whl", hash = "sha256:607eb3ae0909d47280c1fc657c4284c34b785bae371d007595633f4b1a2bbe06", size = 142694 },
+ { url = "https://files.pythonhosted.org/packages/16/62/8b687724143286b63e1d0fab3ad4214d54566d80b0ba9d67c26aaf28a2f8/orjson-3.10.18-cp310-cp310-win_amd64.whl", hash = "sha256:8770432524ce0eca50b7efc2a9a5f486ee0113a5fbb4231526d414e6254eba92", size = 134600 },
+ { url = "https://files.pythonhosted.org/packages/97/c7/c54a948ce9a4278794f669a353551ce7db4ffb656c69a6e1f2264d563e50/orjson-3.10.18-cp311-cp311-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:e0a183ac3b8e40471e8d843105da6fbe7c070faab023be3b08188ee3f85719b8", size = 248929 },
+ { url = "https://files.pythonhosted.org/packages/9e/60/a9c674ef1dd8ab22b5b10f9300e7e70444d4e3cda4b8258d6c2488c32143/orjson-3.10.18-cp311-cp311-macosx_15_0_arm64.whl", hash = "sha256:5ef7c164d9174362f85238d0cd4afdeeb89d9e523e4651add6a5d458d6f7d42d", size = 133364 },
+ { url = "https://files.pythonhosted.org/packages/c1/4e/f7d1bdd983082216e414e6d7ef897b0c2957f99c545826c06f371d52337e/orjson-3.10.18-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd14c5d99cdc7bf93f22b12ec3b294931518aa019e2a147e8aa2f31fd3240f7", size = 136995 },
+ { url = "https://files.pythonhosted.org/packages/17/89/46b9181ba0ea251c9243b0c8ce29ff7c9796fa943806a9c8b02592fce8ea/orjson-3.10.18-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7b672502323b6cd133c4af6b79e3bea36bad2d16bca6c1f645903fce83909a7a", size = 132894 },
+ { url = "https://files.pythonhosted.org/packages/ca/dd/7bce6fcc5b8c21aef59ba3c67f2166f0a1a9b0317dcca4a9d5bd7934ecfd/orjson-3.10.18-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:51f8c63be6e070ec894c629186b1c0fe798662b8687f3d9fdfa5e401c6bd7679", size = 137016 },
+ { url = "https://files.pythonhosted.org/packages/1c/4a/b8aea1c83af805dcd31c1f03c95aabb3e19a016b2a4645dd822c5686e94d/orjson-3.10.18-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3f9478ade5313d724e0495d167083c6f3be0dd2f1c9c8a38db9a9e912cdaf947", size = 138290 },
+ { url = "https://files.pythonhosted.org/packages/36/d6/7eb05c85d987b688707f45dcf83c91abc2251e0dd9fb4f7be96514f838b1/orjson-3.10.18-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:187aefa562300a9d382b4b4eb9694806e5848b0cedf52037bb5c228c61bb66d4", size = 142829 },
+ { url = "https://files.pythonhosted.org/packages/d2/78/ddd3ee7873f2b5f90f016bc04062713d567435c53ecc8783aab3a4d34915/orjson-3.10.18-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9da552683bc9da222379c7a01779bddd0ad39dd699dd6300abaf43eadee38334", size = 132805 },
+ { url = "https://files.pythonhosted.org/packages/8c/09/c8e047f73d2c5d21ead9c180203e111cddeffc0848d5f0f974e346e21c8e/orjson-3.10.18-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e450885f7b47a0231979d9c49b567ed1c4e9f69240804621be87c40bc9d3cf17", size = 135008 },
+ { url = "https://files.pythonhosted.org/packages/0c/4b/dccbf5055ef8fb6eda542ab271955fc1f9bf0b941a058490293f8811122b/orjson-3.10.18-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:5e3c9cc2ba324187cd06287ca24f65528f16dfc80add48dc99fa6c836bb3137e", size = 413419 },
+ { url = "https://files.pythonhosted.org/packages/8a/f3/1eac0c5e2d6d6790bd2025ebfbefcbd37f0d097103d76f9b3f9302af5a17/orjson-3.10.18-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:50ce016233ac4bfd843ac5471e232b865271d7d9d44cf9d33773bcd883ce442b", size = 153292 },
+ { url = "https://files.pythonhosted.org/packages/1f/b4/ef0abf64c8f1fabf98791819ab502c2c8c1dc48b786646533a93637d8999/orjson-3.10.18-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b3ceff74a8f7ffde0b2785ca749fc4e80e4315c0fd887561144059fb1c138aa7", size = 137182 },
+ { url = "https://files.pythonhosted.org/packages/a9/a3/6ea878e7b4a0dc5c888d0370d7752dcb23f402747d10e2257478d69b5e63/orjson-3.10.18-cp311-cp311-win32.whl", hash = "sha256:fdba703c722bd868c04702cac4cb8c6b8ff137af2623bc0ddb3b3e6a2c8996c1", size = 142695 },
+ { url = "https://files.pythonhosted.org/packages/79/2a/4048700a3233d562f0e90d5572a849baa18ae4e5ce4c3ba6247e4ece57b0/orjson-3.10.18-cp311-cp311-win_amd64.whl", hash = "sha256:c28082933c71ff4bc6ccc82a454a2bffcef6e1d7379756ca567c772e4fb3278a", size = 134603 },
+ { url = "https://files.pythonhosted.org/packages/03/45/10d934535a4993d27e1c84f1810e79ccf8b1b7418cef12151a22fe9bb1e1/orjson-3.10.18-cp311-cp311-win_arm64.whl", hash = "sha256:a6c7c391beaedd3fa63206e5c2b7b554196f14debf1ec9deb54b5d279b1b46f5", size = 131400 },
+ { url = "https://files.pythonhosted.org/packages/21/1a/67236da0916c1a192d5f4ccbe10ec495367a726996ceb7614eaa687112f2/orjson-3.10.18-cp312-cp312-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:50c15557afb7f6d63bc6d6348e0337a880a04eaa9cd7c9d569bcb4e760a24753", size = 249184 },
+ { url = "https://files.pythonhosted.org/packages/b3/bc/c7f1db3b1d094dc0c6c83ed16b161a16c214aaa77f311118a93f647b32dc/orjson-3.10.18-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:356b076f1662c9813d5fa56db7d63ccceef4c271b1fb3dd522aca291375fcf17", size = 133279 },
+ { url = "https://files.pythonhosted.org/packages/af/84/664657cd14cc11f0d81e80e64766c7ba5c9b7fc1ec304117878cc1b4659c/orjson-3.10.18-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:559eb40a70a7494cd5beab2d73657262a74a2c59aff2068fdba8f0424ec5b39d", size = 136799 },
+ { url = "https://files.pythonhosted.org/packages/9a/bb/f50039c5bb05a7ab024ed43ba25d0319e8722a0ac3babb0807e543349978/orjson-3.10.18-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f3c29eb9a81e2fbc6fd7ddcfba3e101ba92eaff455b8d602bf7511088bbc0eae", size = 132791 },
+ { url = "https://files.pythonhosted.org/packages/93/8c/ee74709fc072c3ee219784173ddfe46f699598a1723d9d49cbc78d66df65/orjson-3.10.18-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6612787e5b0756a171c7d81ba245ef63a3533a637c335aa7fcb8e665f4a0966f", size = 137059 },
+ { url = "https://files.pythonhosted.org/packages/6a/37/e6d3109ee004296c80426b5a62b47bcadd96a3deab7443e56507823588c5/orjson-3.10.18-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7ac6bd7be0dcab5b702c9d43d25e70eb456dfd2e119d512447468f6405b4a69c", size = 138359 },
+ { url = "https://files.pythonhosted.org/packages/4f/5d/387dafae0e4691857c62bd02839a3bf3fa648eebd26185adfac58d09f207/orjson-3.10.18-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9f72f100cee8dde70100406d5c1abba515a7df926d4ed81e20a9730c062fe9ad", size = 142853 },
+ { url = "https://files.pythonhosted.org/packages/27/6f/875e8e282105350b9a5341c0222a13419758545ae32ad6e0fcf5f64d76aa/orjson-3.10.18-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9dca85398d6d093dd41dc0983cbf54ab8e6afd1c547b6b8a311643917fbf4e0c", size = 133131 },
+ { url = "https://files.pythonhosted.org/packages/48/b2/73a1f0b4790dcb1e5a45f058f4f5dcadc8a85d90137b50d6bbc6afd0ae50/orjson-3.10.18-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:22748de2a07fcc8781a70edb887abf801bb6142e6236123ff93d12d92db3d406", size = 134834 },
+ { url = "https://files.pythonhosted.org/packages/56/f5/7ed133a5525add9c14dbdf17d011dd82206ca6840811d32ac52a35935d19/orjson-3.10.18-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:3a83c9954a4107b9acd10291b7f12a6b29e35e8d43a414799906ea10e75438e6", size = 413368 },
+ { url = "https://files.pythonhosted.org/packages/11/7c/439654221ed9c3324bbac7bdf94cf06a971206b7b62327f11a52544e4982/orjson-3.10.18-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:303565c67a6c7b1f194c94632a4a39918e067bd6176a48bec697393865ce4f06", size = 153359 },
+ { url = "https://files.pythonhosted.org/packages/48/e7/d58074fa0cc9dd29a8fa2a6c8d5deebdfd82c6cfef72b0e4277c4017563a/orjson-3.10.18-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:86314fdb5053a2f5a5d881f03fca0219bfdf832912aa88d18676a5175c6916b5", size = 137466 },
+ { url = "https://files.pythonhosted.org/packages/57/4d/fe17581cf81fb70dfcef44e966aa4003360e4194d15a3f38cbffe873333a/orjson-3.10.18-cp312-cp312-win32.whl", hash = "sha256:187ec33bbec58c76dbd4066340067d9ece6e10067bb0cc074a21ae3300caa84e", size = 142683 },
+ { url = "https://files.pythonhosted.org/packages/e6/22/469f62d25ab5f0f3aee256ea732e72dc3aab6d73bac777bd6277955bceef/orjson-3.10.18-cp312-cp312-win_amd64.whl", hash = "sha256:f9f94cf6d3f9cd720d641f8399e390e7411487e493962213390d1ae45c7814fc", size = 134754 },
+ { url = "https://files.pythonhosted.org/packages/10/b0/1040c447fac5b91bc1e9c004b69ee50abb0c1ffd0d24406e1350c58a7fcb/orjson-3.10.18-cp312-cp312-win_arm64.whl", hash = "sha256:3d600be83fe4514944500fa8c2a0a77099025ec6482e8087d7659e891f23058a", size = 131218 },
+ { url = "https://files.pythonhosted.org/packages/04/f0/8aedb6574b68096f3be8f74c0b56d36fd94bcf47e6c7ed47a7bd1474aaa8/orjson-3.10.18-cp313-cp313-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:69c34b9441b863175cc6a01f2935de994025e773f814412030f269da4f7be147", size = 249087 },
+ { url = "https://files.pythonhosted.org/packages/bc/f7/7118f965541aeac6844fcb18d6988e111ac0d349c9b80cda53583e758908/orjson-3.10.18-cp313-cp313-macosx_15_0_arm64.whl", hash = "sha256:1ebeda919725f9dbdb269f59bc94f861afbe2a27dce5608cdba2d92772364d1c", size = 133273 },
+ { url = "https://files.pythonhosted.org/packages/fb/d9/839637cc06eaf528dd8127b36004247bf56e064501f68df9ee6fd56a88ee/orjson-3.10.18-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5adf5f4eed520a4959d29ea80192fa626ab9a20b2ea13f8f6dc58644f6927103", size = 136779 },
+ { url = "https://files.pythonhosted.org/packages/2b/6d/f226ecfef31a1f0e7d6bf9a31a0bbaf384c7cbe3fce49cc9c2acc51f902a/orjson-3.10.18-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7592bb48a214e18cd670974f289520f12b7aed1fa0b2e2616b8ed9e069e08595", size = 132811 },
+ { url = "https://files.pythonhosted.org/packages/73/2d/371513d04143c85b681cf8f3bce743656eb5b640cb1f461dad750ac4b4d4/orjson-3.10.18-cp313-cp313-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f872bef9f042734110642b7a11937440797ace8c87527de25e0c53558b579ccc", size = 137018 },
+ { url = "https://files.pythonhosted.org/packages/69/cb/a4d37a30507b7a59bdc484e4a3253c8141bf756d4e13fcc1da760a0b00cb/orjson-3.10.18-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0315317601149c244cb3ecef246ef5861a64824ccbcb8018d32c66a60a84ffbc", size = 138368 },
+ { url = "https://files.pythonhosted.org/packages/1e/ae/cd10883c48d912d216d541eb3db8b2433415fde67f620afe6f311f5cd2ca/orjson-3.10.18-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e0da26957e77e9e55a6c2ce2e7182a36a6f6b180ab7189315cb0995ec362e049", size = 142840 },
+ { url = "https://files.pythonhosted.org/packages/6d/4c/2bda09855c6b5f2c055034c9eda1529967b042ff8d81a05005115c4e6772/orjson-3.10.18-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb70d489bc79b7519e5803e2cc4c72343c9dc1154258adf2f8925d0b60da7c58", size = 133135 },
+ { url = "https://files.pythonhosted.org/packages/13/4a/35971fd809a8896731930a80dfff0b8ff48eeb5d8b57bb4d0d525160017f/orjson-3.10.18-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e9e86a6af31b92299b00736c89caf63816f70a4001e750bda179e15564d7a034", size = 134810 },
+ { url = "https://files.pythonhosted.org/packages/99/70/0fa9e6310cda98365629182486ff37a1c6578e34c33992df271a476ea1cd/orjson-3.10.18-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:c382a5c0b5931a5fc5405053d36c1ce3fd561694738626c77ae0b1dfc0242ca1", size = 413491 },
+ { url = "https://files.pythonhosted.org/packages/32/cb/990a0e88498babddb74fb97855ae4fbd22a82960e9b06eab5775cac435da/orjson-3.10.18-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:8e4b2ae732431127171b875cb2668f883e1234711d3c147ffd69fe5be51a8012", size = 153277 },
+ { url = "https://files.pythonhosted.org/packages/92/44/473248c3305bf782a384ed50dd8bc2d3cde1543d107138fd99b707480ca1/orjson-3.10.18-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2d808e34ddb24fc29a4d4041dcfafbae13e129c93509b847b14432717d94b44f", size = 137367 },
+ { url = "https://files.pythonhosted.org/packages/ad/fd/7f1d3edd4ffcd944a6a40e9f88af2197b619c931ac4d3cfba4798d4d3815/orjson-3.10.18-cp313-cp313-win32.whl", hash = "sha256:ad8eacbb5d904d5591f27dee4031e2c1db43d559edb8f91778efd642d70e6bea", size = 142687 },
+ { url = "https://files.pythonhosted.org/packages/4b/03/c75c6ad46be41c16f4cfe0352a2d1450546f3c09ad2c9d341110cd87b025/orjson-3.10.18-cp313-cp313-win_amd64.whl", hash = "sha256:aed411bcb68bf62e85588f2a7e03a6082cc42e5a2796e06e72a962d7c6310b52", size = 134794 },
+ { url = "https://files.pythonhosted.org/packages/c2/28/f53038a5a72cc4fd0b56c1eafb4ef64aec9685460d5ac34de98ca78b6e29/orjson-3.10.18-cp313-cp313-win_arm64.whl", hash = "sha256:f54c1385a0e6aba2f15a40d703b858bedad36ded0491e55d35d905b2c34a4cc3", size = 131186 },
+ { url = "https://files.pythonhosted.org/packages/df/db/69488acaa2316788b7e171f024912c6fe8193aa2e24e9cfc7bc41c3669ba/orjson-3.10.18-cp39-cp39-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:c95fae14225edfd699454e84f61c3dd938df6629a00c6ce15e704f57b58433bb", size = 249301 },
+ { url = "https://files.pythonhosted.org/packages/23/21/d816c44ec5d1482c654e1d23517d935bb2716e1453ff9380e861dc6efdd3/orjson-3.10.18-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5232d85f177f98e0cefabb48b5e7f60cff6f3f0365f9c60631fecd73849b2a82", size = 136786 },
+ { url = "https://files.pythonhosted.org/packages/a5/9f/f68d8a9985b717e39ba7bf95b57ba173fcd86aeca843229ec60d38f1faa7/orjson-3.10.18-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2783e121cafedf0d85c148c248a20470018b4ffd34494a68e125e7d5857655d1", size = 132711 },
+ { url = "https://files.pythonhosted.org/packages/b5/63/447f5955439bf7b99bdd67c38a3f689d140d998ac58e3b7d57340520343c/orjson-3.10.18-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e54ee3722caf3db09c91f442441e78f916046aa58d16b93af8a91500b7bbf273", size = 136841 },
+ { url = "https://files.pythonhosted.org/packages/68/9e/4855972f2be74097242e4681ab6766d36638a079e09d66f3d6a5d1188ce7/orjson-3.10.18-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2daf7e5379b61380808c24f6fc182b7719301739e4271c3ec88f2984a2d61f89", size = 138082 },
+ { url = "https://files.pythonhosted.org/packages/08/0f/e68431e53a39698d2355faf1f018c60a3019b4b54b4ea6be9dc6b8208a3d/orjson-3.10.18-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7f39b371af3add20b25338f4b29a8d6e79a8c7ed0e9dd49e008228a065d07781", size = 142618 },
+ { url = "https://files.pythonhosted.org/packages/32/da/bdcfff239ddba1b6ef465efe49d7e43cc8c30041522feba9fd4241d47c32/orjson-3.10.18-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2b819ed34c01d88c6bec290e6842966f8e9ff84b7694632e88341363440d4cc0", size = 132627 },
+ { url = "https://files.pythonhosted.org/packages/0c/28/bc634da09bbe972328f615b0961f1e7d91acb3cc68bddbca9e8dd64e8e24/orjson-3.10.18-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:2f6c57debaef0b1aa13092822cbd3698a1fb0209a9ea013a969f4efa36bdea57", size = 134832 },
+ { url = "https://files.pythonhosted.org/packages/1d/d2/e8ac0c2d0ec782ed8925b4eb33f040cee1f1fbd1d8b268aeb84b94153e49/orjson-3.10.18-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:755b6d61ffdb1ffa1e768330190132e21343757c9aa2308c67257cc81a1a6f5a", size = 413161 },
+ { url = "https://files.pythonhosted.org/packages/28/f0/397e98c352a27594566e865999dc6b88d6f37d5bbb87b23c982af24114c4/orjson-3.10.18-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:ce8d0a875a85b4c8579eab5ac535fb4b2a50937267482be402627ca7e7570ee3", size = 153012 },
+ { url = "https://files.pythonhosted.org/packages/93/bf/2c7334caeb48bdaa4cae0bde17ea417297ee136598653b1da7ae1f98c785/orjson-3.10.18-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:57b5d0673cbd26781bebc2bf86f99dd19bd5a9cb55f71cc4f66419f6b50f3d77", size = 136999 },
+ { url = "https://files.pythonhosted.org/packages/35/72/4827b1c0c31621c2aa1e661a899cdd2cfac0565c6cd7131890daa4ef7535/orjson-3.10.18-cp39-cp39-win32.whl", hash = "sha256:951775d8b49d1d16ca8818b1f20c4965cae9157e7b562a2ae34d3967b8f21c8e", size = 142560 },
+ { url = "https://files.pythonhosted.org/packages/72/91/ef8e76868e7eed478887c82f60607a8abf58dadd24e95817229a4b2e2639/orjson-3.10.18-cp39-cp39-win_amd64.whl", hash = "sha256:fdd9d68f83f0bc4406610b1ac68bdcded8c5ee58605cc69e643a06f4d075f429", size = 134455 },
+]
+
+[[package]]
+name = "outlines"
+version = "0.1.11"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "airportsdata" },
+ { name = "cloudpickle" },
+ { name = "diskcache" },
+ { name = "interegular" },
+ { name = "jinja2" },
+ { name = "jsonschema" },
+ { name = "lark" },
+ { name = "nest-asyncio" },
+ { name = "numpy" },
+ { name = "outlines-core" },
+ { name = "pycountry" },
+ { name = "pydantic" },
+ { name = "referencing" },
+ { name = "requests" },
+ { name = "torch" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ac/d0/d59ae830bf7026425942899e3d48e77b58a713cff946a695e5405808da1b/outlines-0.1.11.tar.gz", hash = "sha256:0997bd9da1cc050e430bd08995dc7d4bd855918bafa4531e49d3f37110a23aba", size = 2488858 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/13/b4/99ea4a122bef60e3fd6402d19665aff1f928e0daf8fac3044d0b73f72003/outlines-0.1.11-py3-none-any.whl", hash = "sha256:f5a5f2242ed9802d3aab7a92789bf4008d734c576be9258cc0a297f690124727", size = 87623 },
+]
+
+[[package]]
+name = "outlines-core"
+version = "0.1.26"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "interegular" },
+ { name = "jsonschema" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d3/f3/274d07f4702728b43581235a77e545ec602b25f9b0098b288a0f3052521d/outlines_core-0.1.26.tar.gz", hash = "sha256:481c4301341e77cc8f1832d616784adb4d461b4fec65878e7c0d2cba7163a189", size = 75139 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e2/df/e9ff00f1dcf671cb8c4c20abcfd53406328b344cafa689a2832e8059c0b4/outlines_core-0.1.26-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:6a962a7452e7ac170fa04d405342cadae2d28fafa5b1830cef7aa610257ed32f", size = 322602 },
+ { url = "https://files.pythonhosted.org/packages/3c/f1/e9064f18c462a61f4abbe73b24f25e36d8abef19c593416fa69dce6a83c0/outlines_core-0.1.26-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:15a3684fa29564da2db03934cf0097bef3e871f70d3af0ef2b52fdb886da2e09", size = 301929 },
+ { url = "https://files.pythonhosted.org/packages/76/c3/6bc82db40b4818421e573237f43d4026c40a3305fa2558eb0aa1a7aa08f7/outlines_core-0.1.26-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:64e01c0cfa9ba371634d7c3f6ea1862397cef98e4509fe98e3f57faa721a72d6", size = 321355 },
+ { url = "https://files.pythonhosted.org/packages/c9/c2/1d85bfeaee3a83327e0d162bee4bdc7d7889bea5998e44fcc66c924dc1fd/outlines_core-0.1.26-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a3c4196148e47f455f1ace78e329d5b97e531cbc406456d681592952adae7e17", size = 343552 },
+ { url = "https://files.pythonhosted.org/packages/45/da/1e61d3d997ba1858fb8e71c3127f24a95c30575559da012ea5b45b147ad3/outlines_core-0.1.26-cp310-cp310-win32.whl", hash = "sha256:f38d290a7f6e5e12cbfcaee03269dfc0dbda49b360024b4279d1aba251fdc346", size = 234750 },
+ { url = "https://files.pythonhosted.org/packages/1c/04/6d7968019a81df235ad6bc7405eefe32be8da4c4153792655e7490d06c8d/outlines_core-0.1.26-cp310-cp310-win_amd64.whl", hash = "sha256:11ff56af56cb54c563b7f25d86cd9ee77f3fed825f1d4dccd9449bb1e4e89538", size = 243713 },
+ { url = "https://files.pythonhosted.org/packages/17/94/19d5c50c303ba71f3465c81620ca9b5af4db07fd8922dfe59ae5a9ae61d1/outlines_core-0.1.26-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:b6787b07b7c673fc3087d2b537719ecac8e03b10a47d032dd1926985c32885b0", size = 322344 },
+ { url = "https://files.pythonhosted.org/packages/f2/ea/f44beea7f610f2737ebb908c8dfa37d8324e92ca529468a56b00a77af199/outlines_core-0.1.26-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e0ea28a76da31d25b6f53242bf13e1b59a0241badf82353c88f55e1cf81b128", size = 301670 },
+ { url = "https://files.pythonhosted.org/packages/6a/a6/ceac3760e1feb898b4047aeb54e0a3de975b59e87a17d6ba0a04dec5eaed/outlines_core-0.1.26-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a8932044a3d9329be53a226118850638f85b4d7842f9b863d0a123f23de220cd", size = 321067 },
+ { url = "https://files.pythonhosted.org/packages/92/f0/ad0074d6726fed86bb0bba1b9307cbbd67a2af5debd3540d66c69298a001/outlines_core-0.1.26-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a84b7cd2fb6268bf990dd3d479ffb4fa0bace6f571cb85b15b6cdb44b84f5b69", size = 343264 },
+ { url = "https://files.pythonhosted.org/packages/e6/bd/198c9a73d5f36e2ecad558a26359af3f0dbe4f5ba11c4629e46fccdfe2d6/outlines_core-0.1.26-cp311-cp311-win32.whl", hash = "sha256:f19765c151abfc970996368080aeea6d2a19e927817fe4e2af6726e639be3de4", size = 234529 },
+ { url = "https://files.pythonhosted.org/packages/b9/27/354b484045e6368c92f688d954124064ec2ce961681e56711852904e1ec2/outlines_core-0.1.26-cp311-cp311-win_amd64.whl", hash = "sha256:3f59aeccea21ed6ff3cf52102fd163f26d279821c20e5127ddd18d4ea4d0c8d2", size = 243457 },
+ { url = "https://files.pythonhosted.org/packages/c6/86/0fb40746e579db38d89f127122a3900d9e0350f76aae8cb61adeaff44cc2/outlines_core-0.1.26-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f54633bca50055d42ea4d94ae06dcbe52d3d76a9b621b75723b1177d0d952953", size = 321874 },
+ { url = "https://files.pythonhosted.org/packages/ab/0c/b91f7bc03843796c1d643ee030b6cd8fd5a8ba2cd4856c855f140c878976/outlines_core-0.1.26-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9525321b48700dcaaabf60bcdc951e45f9357ba3fb3e1bfc81b662d7d4170e7c", size = 301995 },
+ { url = "https://files.pythonhosted.org/packages/ad/db/fa91a2d54288b900de82d86eda3adb2417b3b5b2db6256854a5e8bc85c32/outlines_core-0.1.26-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:00f409f72c11f6ffadb57066950dd384d5388015028c1a1a615c9a64988dae3e", size = 321050 },
+ { url = "https://files.pythonhosted.org/packages/e2/1d/a36292b6198986bd9c3ff8c24355deb82ed5475403379ee40b5b5473e2e3/outlines_core-0.1.26-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e86a1bb46adc5cbf6dfd7a7fe4105e0e2a4c6e041732a053126b41c521a1f223", size = 343201 },
+ { url = "https://files.pythonhosted.org/packages/08/63/5dd2b5a364412f674b6edcb59b0c21513bdb07cdcc7613b064c1a0660d01/outlines_core-0.1.26-cp312-cp312-win32.whl", hash = "sha256:19f462f6b00935708677ad27cb4df55e0e17f6ffe713ab750f5f2683b090f95d", size = 233970 },
+ { url = "https://files.pythonhosted.org/packages/a5/56/8adf0b7446d1e975c2314454813c59eb7b195889908a2932ed34148c113c/outlines_core-0.1.26-cp312-cp312-win_amd64.whl", hash = "sha256:9b36bff12779e58883747116893a17b3551bbd10865878b951b03a44d112229a", size = 243578 },
+ { url = "https://files.pythonhosted.org/packages/5b/b8/d38f13e417f2af82f6cd588df5a26ff8ffeb9a3a15b8a1a883d5922048ac/outlines_core-0.1.26-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:7b7849cf40028319ebb9d8ba0fe4c590ef5888eebe524a81b3af30aaa06ea21c", size = 323047 },
+ { url = "https://files.pythonhosted.org/packages/3b/59/43f5c7b8ad0e98a663db8f24cbff0421a58e946934e3f3751a17a06ae84d/outlines_core-0.1.26-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:2f8641aab4a6bd84516907492ce82099503129da01b3c29c1dc9ad50320bae77", size = 302547 },
+ { url = "https://files.pythonhosted.org/packages/23/30/d9eb8202cbc994536a1fefa60e87c582a714ad1b46367c43af299f3889ba/outlines_core-0.1.26-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bba56604efdbc5932c7a8a88c2b8b0d0c740ab883b0012fb5464a9736796802b", size = 321817 },
+ { url = "https://files.pythonhosted.org/packages/80/c7/bd718f6329f5c65b936edff532e40614b66032b153ab9ac89e6cb6d2fcff/outlines_core-0.1.26-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8cc8c87d89bd267356f8149c9066cbb98970425ec162997fbf195c3f1feb7009", size = 344102 },
+ { url = "https://files.pythonhosted.org/packages/cb/3e/69ca7394fc89c98c763f2d475c08206fa56f2ffeec210833c1db0195ba51/outlines_core-0.1.26-cp39-cp39-win32.whl", hash = "sha256:9d792a43ed9d8a4e1b38f4d83fe99db442d57aad4404c2edf98b710892eda47e", size = 235081 },
+ { url = "https://files.pythonhosted.org/packages/56/7f/38decd8d63f6b2d513c372186c68337455efba3fb45d0ff722ac268f05d2/outlines_core-0.1.26-cp39-cp39-win_amd64.whl", hash = "sha256:ad8564ecd7b64bcb840596c5049ff1c1a96346de494302ffcc0f2b188c15675e", size = 244007 },
+]
+
+[[package]]
+name = "packaging"
+version = "25.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469 },
+]
+
+[[package]]
+name = "pandas"
+version = "2.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "python-dateutil" },
+ { name = "pytz" },
+ { name = "tzdata" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6f/31/a4a8e7367856d9584d0332793edfe631182a9cca885f12dbe2dd77c10c4a/pandas-2.1.0.tar.gz", hash = "sha256:62c24c7fc59e42b775ce0679cfa7b14a5f9bfb7643cfbe708c960699e05fb918", size = 4263970 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cf/ba/be69b6fa37c74699d333dbcbf0fc799eb31c35ce465651cdc4baf6a2e30d/pandas-2.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:40dd20439ff94f1b2ed55b393ecee9cb6f3b08104c2c40b0cb7186a2f0046242", size = 12118394 },
+ { url = "https://files.pythonhosted.org/packages/8d/08/1cf87814dcd87604807971abc743b12e635de36d820be7b50e2b6aa9e1b5/pandas-2.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d4f38e4fedeba580285eaac7ede4f686c6701a9e618d8a857b138a126d067f2f", size = 11306908 },
+ { url = "https://files.pythonhosted.org/packages/f3/21/8ea83d6990457c5253d9e6c40a3d2c8a3d383dfabb937b0a36a71ae43bde/pandas-2.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e6a0fe052cf27ceb29be9429428b4918f3740e37ff185658f40d8702f0b3e09", size = 15167237 },
+ { url = "https://files.pythonhosted.org/packages/fb/4f/4a4372b2e24439f559b73318683486831d75e59544ae02bf8dec8dd6f48b/pandas-2.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d81e1813191070440d4c7a413cb673052b3b4a984ffd86b8dd468c45742d3cc", size = 12662125 },
+ { url = "https://files.pythonhosted.org/packages/4c/a8/8ac4fa3970e64d7f62ebdcd47e507c2443d49090a3f402fa01f0e6e30b13/pandas-2.1.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:eb20252720b1cc1b7d0b2879ffc7e0542dd568f24d7c4b2347cb035206936421", size = 13465263 },
+ { url = "https://files.pythonhosted.org/packages/c5/89/ce1c7dc497f9a20644f6a7d2dd5bce6378a48321955178197fa3b55d6fe3/pandas-2.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:38f74ef7ebc0ffb43b3d633e23d74882bce7e27bfa09607f3c5d3e03ffd9a4a5", size = 11097660 },
+ { url = "https://files.pythonhosted.org/packages/c3/05/c5c73d54ceb7d5e4b8c046d39a1bb7f38ee76ea556a002cf3317514f0196/pandas-2.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cda72cc8c4761c8f1d97b169661f23a86b16fdb240bdc341173aee17e4d6cedd", size = 12015015 },
+ { url = "https://files.pythonhosted.org/packages/e5/cd/c941b51e95992968e3e8abc7180f33b952478abd6943062051517a808db7/pandas-2.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d97daeac0db8c993420b10da4f5f5b39b01fc9ca689a17844e07c0a35ac96b4b", size = 11173830 },
+ { url = "https://files.pythonhosted.org/packages/e2/25/bfb5c7573e2b884b18e5ea993ee7aeb5a6915ea687174349fdc5f979ceec/pandas-2.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8c58b1113892e0c8078f006a167cc210a92bdae23322bb4614f2f0b7a4b510f", size = 15176284 },
+ { url = "https://files.pythonhosted.org/packages/d9/26/895a49ebddb4211f2d777150f38ef9e538deff6df7e179a3624c663efc98/pandas-2.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:629124923bcf798965b054a540f9ccdfd60f71361255c81fa1ecd94a904b9dd3", size = 12630840 },
+ { url = "https://files.pythonhosted.org/packages/bc/ad/d1f0a867064f62ffde917876cc09cfd53352af2b1f147c140fd1943a0c7a/pandas-2.1.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:70cf866af3ab346a10debba8ea78077cf3a8cd14bd5e4bed3d41555a3280041c", size = 13463414 },
+ { url = "https://files.pythonhosted.org/packages/b7/f8/32d6b5aa4c4bc045fa2c4c58f88c325facc54721956c6313f0afea8ea853/pandas-2.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:d53c8c1001f6a192ff1de1efe03b31a423d0eee2e9e855e69d004308e046e694", size = 11043589 },
+ { url = "https://files.pythonhosted.org/packages/fa/c4/e09a705190d0930c8460257fcb6f2df83be78c82cb2cacd3b9be343d7205/pandas-2.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:86f100b3876b8c6d1a2c66207288ead435dc71041ee4aea789e55ef0e06408cb", size = 12186100 },
+ { url = "https://files.pythonhosted.org/packages/ee/70/bad32e3c05d95bc53ed2c596fc8edb333cdd9049d248b6702d92d6be2389/pandas-2.1.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:28f330845ad21c11db51e02d8d69acc9035edfd1116926ff7245c7215db57957", size = 11347706 },
+ { url = "https://files.pythonhosted.org/packages/af/f4/e5e3283c04f0459e523828084a29a367484e3fe0e9b95c2c012f2d9d0c2e/pandas-2.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9a6ccf0963db88f9b12df6720e55f337447aea217f426a22d71f4213a3099a6", size = 15305826 },
+ { url = "https://files.pythonhosted.org/packages/83/f0/2765daac3c58165460b127df5c0ef7b3a039f3bfe7ea7a51f3d20b01371b/pandas-2.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d99e678180bc59b0c9443314297bddce4ad35727a1a2656dbe585fd78710b3b9", size = 12735384 },
+ { url = "https://files.pythonhosted.org/packages/ba/80/8bd10d9215dc3ce1036aec0152f86d55981f4dde36843a079c6bafbc19c1/pandas-2.1.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b31da36d376d50a1a492efb18097b9101bdbd8b3fbb3f49006e02d4495d4c644", size = 13612616 },
+ { url = "https://files.pythonhosted.org/packages/b9/42/78b0e183e545de3cc8d04fdb7a40d39d456a45823fae66d2ec9f4ccc190d/pandas-2.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:0164b85937707ec7f70b34a6c3a578dbf0f50787f910f21ca3b26a7fd3363437", size = 11192623 },
+]
+
+[[package]]
+name = "parso"
+version = "0.8.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/66/94/68e2e17afaa9169cf6412ab0f28623903be73d1b32e208d9e8e541bb086d/parso-0.8.4.tar.gz", hash = "sha256:eb3a7b58240fb99099a345571deecc0f9540ea5f4dd2fe14c2a99d6b281ab92d", size = 400609 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c6/ac/dac4a63f978e4dcb3c6d3a78c4d8e0192a113d288502a1216950c41b1027/parso-0.8.4-py2.py3-none-any.whl", hash = "sha256:a418670a20291dacd2dddc80c377c5c3791378ee1e8d12bffc35420643d43f18", size = 103650 },
+]
+
+[[package]]
+name = "partial-json-parser"
+version = "0.2.1.1.post5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/27/9c/9c366aed65acb40a97842ce1375a87b27ea37d735fc9717f7729bae3cc00/partial_json_parser-0.2.1.1.post5.tar.gz", hash = "sha256:992710ac67e90b367921d52727698928040f7713ba7ecb33b96371ea7aec82ca", size = 10313 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8c/ee/a9476f01f27c74420601be208c6c2c0dd3486681d515e9d765931b89851c/partial_json_parser-0.2.1.1.post5-py3-none-any.whl", hash = "sha256:627715aaa3cb3fb60a65b0d62223243acaa6c70846520a90326fef3a2f0b61ca", size = 10885 },
+]
+
+[[package]]
+name = "pathspec"
+version = "0.12.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191 },
+]
+
+[[package]]
+name = "pexpect"
+version = "4.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "ptyprocess" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772 },
+]
+
+[[package]]
+name = "pillow"
+version = "11.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/af/cb/bb5c01fcd2a69335b86c22142b2bccfc3464087efb7fd382eee5ffc7fdf7/pillow-11.2.1.tar.gz", hash = "sha256:a64dd61998416367b7ef979b73d3a85853ba9bec4c2925f74e588879a58716b6", size = 47026707 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0d/8b/b158ad57ed44d3cc54db8d68ad7c0a58b8fc0e4c7a3f995f9d62d5b464a1/pillow-11.2.1-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:d57a75d53922fc20c165016a20d9c44f73305e67c351bbc60d1adaf662e74047", size = 3198442 },
+ { url = "https://files.pythonhosted.org/packages/b1/f8/bb5d956142f86c2d6cc36704943fa761f2d2e4c48b7436fd0a85c20f1713/pillow-11.2.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:127bf6ac4a5b58b3d32fc8289656f77f80567d65660bc46f72c0d77e6600cc95", size = 3030553 },
+ { url = "https://files.pythonhosted.org/packages/22/7f/0e413bb3e2aa797b9ca2c5c38cb2e2e45d88654e5b12da91ad446964cfae/pillow-11.2.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b4ba4be812c7a40280629e55ae0b14a0aafa150dd6451297562e1764808bbe61", size = 4405503 },
+ { url = "https://files.pythonhosted.org/packages/f3/b4/cc647f4d13f3eb837d3065824aa58b9bcf10821f029dc79955ee43f793bd/pillow-11.2.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c8bd62331e5032bc396a93609982a9ab6b411c05078a52f5fe3cc59234a3abd1", size = 4490648 },
+ { url = "https://files.pythonhosted.org/packages/c2/6f/240b772a3b35cdd7384166461567aa6713799b4e78d180c555bd284844ea/pillow-11.2.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:562d11134c97a62fe3af29581f083033179f7ff435f78392565a1ad2d1c2c45c", size = 4508937 },
+ { url = "https://files.pythonhosted.org/packages/f3/5e/7ca9c815ade5fdca18853db86d812f2f188212792780208bdb37a0a6aef4/pillow-11.2.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:c97209e85b5be259994eb5b69ff50c5d20cca0f458ef9abd835e262d9d88b39d", size = 4599802 },
+ { url = "https://files.pythonhosted.org/packages/02/81/c3d9d38ce0c4878a77245d4cf2c46d45a4ad0f93000227910a46caff52f3/pillow-11.2.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0c3e6d0f59171dfa2e25d7116217543310908dfa2770aa64b8f87605f8cacc97", size = 4576717 },
+ { url = "https://files.pythonhosted.org/packages/42/49/52b719b89ac7da3185b8d29c94d0e6aec8140059e3d8adcaa46da3751180/pillow-11.2.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cc1c3bc53befb6096b84165956e886b1729634a799e9d6329a0c512ab651e579", size = 4654874 },
+ { url = "https://files.pythonhosted.org/packages/5b/0b/ede75063ba6023798267023dc0d0401f13695d228194d2242d5a7ba2f964/pillow-11.2.1-cp310-cp310-win32.whl", hash = "sha256:312c77b7f07ab2139924d2639860e084ec2a13e72af54d4f08ac843a5fc9c79d", size = 2331717 },
+ { url = "https://files.pythonhosted.org/packages/ed/3c/9831da3edea527c2ed9a09f31a2c04e77cd705847f13b69ca60269eec370/pillow-11.2.1-cp310-cp310-win_amd64.whl", hash = "sha256:9bc7ae48b8057a611e5fe9f853baa88093b9a76303937449397899385da06fad", size = 2676204 },
+ { url = "https://files.pythonhosted.org/packages/01/97/1f66ff8a1503d8cbfc5bae4dc99d54c6ec1e22ad2b946241365320caabc2/pillow-11.2.1-cp310-cp310-win_arm64.whl", hash = "sha256:2728567e249cdd939f6cc3d1f049595c66e4187f3c34078cbc0a7d21c47482d2", size = 2414767 },
+ { url = "https://files.pythonhosted.org/packages/68/08/3fbf4b98924c73037a8e8b4c2c774784805e0fb4ebca6c5bb60795c40125/pillow-11.2.1-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:35ca289f712ccfc699508c4658a1d14652e8033e9b69839edf83cbdd0ba39e70", size = 3198450 },
+ { url = "https://files.pythonhosted.org/packages/84/92/6505b1af3d2849d5e714fc75ba9e69b7255c05ee42383a35a4d58f576b16/pillow-11.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e0409af9f829f87a2dfb7e259f78f317a5351f2045158be321fd135973fff7bf", size = 3030550 },
+ { url = "https://files.pythonhosted.org/packages/3c/8c/ac2f99d2a70ff966bc7eb13dacacfaab57c0549b2ffb351b6537c7840b12/pillow-11.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d4e5c5edee874dce4f653dbe59db7c73a600119fbea8d31f53423586ee2aafd7", size = 4415018 },
+ { url = "https://files.pythonhosted.org/packages/1f/e3/0a58b5d838687f40891fff9cbaf8669f90c96b64dc8f91f87894413856c6/pillow-11.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b93a07e76d13bff9444f1a029e0af2964e654bfc2e2c2d46bfd080df5ad5f3d8", size = 4498006 },
+ { url = "https://files.pythonhosted.org/packages/21/f5/6ba14718135f08fbfa33308efe027dd02b781d3f1d5c471444a395933aac/pillow-11.2.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:e6def7eed9e7fa90fde255afaf08060dc4b343bbe524a8f69bdd2a2f0018f600", size = 4517773 },
+ { url = "https://files.pythonhosted.org/packages/20/f2/805ad600fc59ebe4f1ba6129cd3a75fb0da126975c8579b8f57abeb61e80/pillow-11.2.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:8f4f3724c068be008c08257207210c138d5f3731af6c155a81c2b09a9eb3a788", size = 4607069 },
+ { url = "https://files.pythonhosted.org/packages/71/6b/4ef8a288b4bb2e0180cba13ca0a519fa27aa982875882392b65131401099/pillow-11.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a0a6709b47019dff32e678bc12c63008311b82b9327613f534e496dacaefb71e", size = 4583460 },
+ { url = "https://files.pythonhosted.org/packages/62/ae/f29c705a09cbc9e2a456590816e5c234382ae5d32584f451c3eb41a62062/pillow-11.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f6b0c664ccb879109ee3ca702a9272d877f4fcd21e5eb63c26422fd6e415365e", size = 4661304 },
+ { url = "https://files.pythonhosted.org/packages/6e/1a/c8217b6f2f73794a5e219fbad087701f412337ae6dbb956db37d69a9bc43/pillow-11.2.1-cp311-cp311-win32.whl", hash = "sha256:cc5d875d56e49f112b6def6813c4e3d3036d269c008bf8aef72cd08d20ca6df6", size = 2331809 },
+ { url = "https://files.pythonhosted.org/packages/e2/72/25a8f40170dc262e86e90f37cb72cb3de5e307f75bf4b02535a61afcd519/pillow-11.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:0f5c7eda47bf8e3c8a283762cab94e496ba977a420868cb819159980b6709193", size = 2676338 },
+ { url = "https://files.pythonhosted.org/packages/06/9e/76825e39efee61efea258b479391ca77d64dbd9e5804e4ad0fa453b4ba55/pillow-11.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:4d375eb838755f2528ac8cbc926c3e31cc49ca4ad0cf79cff48b20e30634a4a7", size = 2414918 },
+ { url = "https://files.pythonhosted.org/packages/c7/40/052610b15a1b8961f52537cc8326ca6a881408bc2bdad0d852edeb6ed33b/pillow-11.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:78afba22027b4accef10dbd5eed84425930ba41b3ea0a86fa8d20baaf19d807f", size = 3190185 },
+ { url = "https://files.pythonhosted.org/packages/e5/7e/b86dbd35a5f938632093dc40d1682874c33dcfe832558fc80ca56bfcb774/pillow-11.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78092232a4ab376a35d68c4e6d5e00dfd73454bd12b230420025fbe178ee3b0b", size = 3030306 },
+ { url = "https://files.pythonhosted.org/packages/a4/5c/467a161f9ed53e5eab51a42923c33051bf8d1a2af4626ac04f5166e58e0c/pillow-11.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25a5f306095c6780c52e6bbb6109624b95c5b18e40aab1c3041da3e9e0cd3e2d", size = 4416121 },
+ { url = "https://files.pythonhosted.org/packages/62/73/972b7742e38ae0e2ac76ab137ca6005dcf877480da0d9d61d93b613065b4/pillow-11.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0c7b29dbd4281923a2bfe562acb734cee96bbb129e96e6972d315ed9f232bef4", size = 4501707 },
+ { url = "https://files.pythonhosted.org/packages/e4/3a/427e4cb0b9e177efbc1a84798ed20498c4f233abde003c06d2650a6d60cb/pillow-11.2.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:3e645b020f3209a0181a418bffe7b4a93171eef6c4ef6cc20980b30bebf17b7d", size = 4522921 },
+ { url = "https://files.pythonhosted.org/packages/fe/7c/d8b1330458e4d2f3f45d9508796d7caf0c0d3764c00c823d10f6f1a3b76d/pillow-11.2.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:b2dbea1012ccb784a65349f57bbc93730b96e85b42e9bf7b01ef40443db720b4", size = 4612523 },
+ { url = "https://files.pythonhosted.org/packages/b3/2f/65738384e0b1acf451de5a573d8153fe84103772d139e1e0bdf1596be2ea/pillow-11.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:da3104c57bbd72948d75f6a9389e6727d2ab6333c3617f0a89d72d4940aa0443", size = 4587836 },
+ { url = "https://files.pythonhosted.org/packages/6a/c5/e795c9f2ddf3debb2dedd0df889f2fe4b053308bb59a3cc02a0cd144d641/pillow-11.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:598174aef4589af795f66f9caab87ba4ff860ce08cd5bb447c6fc553ffee603c", size = 4669390 },
+ { url = "https://files.pythonhosted.org/packages/96/ae/ca0099a3995976a9fce2f423166f7bff9b12244afdc7520f6ed38911539a/pillow-11.2.1-cp312-cp312-win32.whl", hash = "sha256:1d535df14716e7f8776b9e7fee118576d65572b4aad3ed639be9e4fa88a1cad3", size = 2332309 },
+ { url = "https://files.pythonhosted.org/packages/7c/18/24bff2ad716257fc03da964c5e8f05d9790a779a8895d6566e493ccf0189/pillow-11.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:14e33b28bf17c7a38eede290f77db7c664e4eb01f7869e37fa98a5aa95978941", size = 2676768 },
+ { url = "https://files.pythonhosted.org/packages/da/bb/e8d656c9543276517ee40184aaa39dcb41e683bca121022f9323ae11b39d/pillow-11.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:21e1470ac9e5739ff880c211fc3af01e3ae505859392bf65458c224d0bf283eb", size = 2415087 },
+ { url = "https://files.pythonhosted.org/packages/36/9c/447528ee3776e7ab8897fe33697a7ff3f0475bb490c5ac1456a03dc57956/pillow-11.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:fdec757fea0b793056419bca3e9932eb2b0ceec90ef4813ea4c1e072c389eb28", size = 3190098 },
+ { url = "https://files.pythonhosted.org/packages/b5/09/29d5cd052f7566a63e5b506fac9c60526e9ecc553825551333e1e18a4858/pillow-11.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:b0e130705d568e2f43a17bcbe74d90958e8a16263868a12c3e0d9c8162690830", size = 3030166 },
+ { url = "https://files.pythonhosted.org/packages/71/5d/446ee132ad35e7600652133f9c2840b4799bbd8e4adba881284860da0a36/pillow-11.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7bdb5e09068332578214cadd9c05e3d64d99e0e87591be22a324bdbc18925be0", size = 4408674 },
+ { url = "https://files.pythonhosted.org/packages/69/5f/cbe509c0ddf91cc3a03bbacf40e5c2339c4912d16458fcb797bb47bcb269/pillow-11.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d189ba1bebfbc0c0e529159631ec72bb9e9bc041f01ec6d3233d6d82eb823bc1", size = 4496005 },
+ { url = "https://files.pythonhosted.org/packages/f9/b3/dd4338d8fb8a5f312021f2977fb8198a1184893f9b00b02b75d565c33b51/pillow-11.2.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:191955c55d8a712fab8934a42bfefbf99dd0b5875078240943f913bb66d46d9f", size = 4518707 },
+ { url = "https://files.pythonhosted.org/packages/13/eb/2552ecebc0b887f539111c2cd241f538b8ff5891b8903dfe672e997529be/pillow-11.2.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:ad275964d52e2243430472fc5d2c2334b4fc3ff9c16cb0a19254e25efa03a155", size = 4610008 },
+ { url = "https://files.pythonhosted.org/packages/72/d1/924ce51bea494cb6e7959522d69d7b1c7e74f6821d84c63c3dc430cbbf3b/pillow-11.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:750f96efe0597382660d8b53e90dd1dd44568a8edb51cb7f9d5d918b80d4de14", size = 4585420 },
+ { url = "https://files.pythonhosted.org/packages/43/ab/8f81312d255d713b99ca37479a4cb4b0f48195e530cdc1611990eb8fd04b/pillow-11.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fe15238d3798788d00716637b3d4e7bb6bde18b26e5d08335a96e88564a36b6b", size = 4667655 },
+ { url = "https://files.pythonhosted.org/packages/94/86/8f2e9d2dc3d308dfd137a07fe1cc478df0a23d42a6c4093b087e738e4827/pillow-11.2.1-cp313-cp313-win32.whl", hash = "sha256:3fe735ced9a607fee4f481423a9c36701a39719252a9bb251679635f99d0f7d2", size = 2332329 },
+ { url = "https://files.pythonhosted.org/packages/6d/ec/1179083b8d6067a613e4d595359b5fdea65d0a3b7ad623fee906e1b3c4d2/pillow-11.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:74ee3d7ecb3f3c05459ba95eed5efa28d6092d751ce9bf20e3e253a4e497e691", size = 2676388 },
+ { url = "https://files.pythonhosted.org/packages/23/f1/2fc1e1e294de897df39fa8622d829b8828ddad938b0eaea256d65b84dd72/pillow-11.2.1-cp313-cp313-win_arm64.whl", hash = "sha256:5119225c622403afb4b44bad4c1ca6c1f98eed79db8d3bc6e4e160fc6339d66c", size = 2414950 },
+ { url = "https://files.pythonhosted.org/packages/c4/3e/c328c48b3f0ead7bab765a84b4977acb29f101d10e4ef57a5e3400447c03/pillow-11.2.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:8ce2e8411c7aaef53e6bb29fe98f28cd4fbd9a1d9be2eeea434331aac0536b22", size = 3192759 },
+ { url = "https://files.pythonhosted.org/packages/18/0e/1c68532d833fc8b9f404d3a642991441d9058eccd5606eab31617f29b6d4/pillow-11.2.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:9ee66787e095127116d91dea2143db65c7bb1e232f617aa5957c0d9d2a3f23a7", size = 3033284 },
+ { url = "https://files.pythonhosted.org/packages/b7/cb/6faf3fb1e7705fd2db74e070f3bf6f88693601b0ed8e81049a8266de4754/pillow-11.2.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9622e3b6c1d8b551b6e6f21873bdcc55762b4b2126633014cea1803368a9aa16", size = 4445826 },
+ { url = "https://files.pythonhosted.org/packages/07/94/8be03d50b70ca47fb434a358919d6a8d6580f282bbb7af7e4aa40103461d/pillow-11.2.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63b5dff3a68f371ea06025a1a6966c9a1e1ee452fc8020c2cd0ea41b83e9037b", size = 4527329 },
+ { url = "https://files.pythonhosted.org/packages/fd/a4/bfe78777076dc405e3bd2080bc32da5ab3945b5a25dc5d8acaa9de64a162/pillow-11.2.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:31df6e2d3d8fc99f993fd253e97fae451a8db2e7207acf97859732273e108406", size = 4549049 },
+ { url = "https://files.pythonhosted.org/packages/65/4d/eaf9068dc687c24979e977ce5677e253624bd8b616b286f543f0c1b91662/pillow-11.2.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:062b7a42d672c45a70fa1f8b43d1d38ff76b63421cbbe7f88146b39e8a558d91", size = 4635408 },
+ { url = "https://files.pythonhosted.org/packages/1d/26/0fd443365d9c63bc79feb219f97d935cd4b93af28353cba78d8e77b61719/pillow-11.2.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:4eb92eca2711ef8be42fd3f67533765d9fd043b8c80db204f16c8ea62ee1a751", size = 4614863 },
+ { url = "https://files.pythonhosted.org/packages/49/65/dca4d2506be482c2c6641cacdba5c602bc76d8ceb618fd37de855653a419/pillow-11.2.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:f91ebf30830a48c825590aede79376cb40f110b387c17ee9bd59932c961044f9", size = 4692938 },
+ { url = "https://files.pythonhosted.org/packages/b3/92/1ca0c3f09233bd7decf8f7105a1c4e3162fb9142128c74adad0fb361b7eb/pillow-11.2.1-cp313-cp313t-win32.whl", hash = "sha256:e0b55f27f584ed623221cfe995c912c61606be8513bfa0e07d2c674b4516d9dd", size = 2335774 },
+ { url = "https://files.pythonhosted.org/packages/a5/ac/77525347cb43b83ae905ffe257bbe2cc6fd23acb9796639a1f56aa59d191/pillow-11.2.1-cp313-cp313t-win_amd64.whl", hash = "sha256:36d6b82164c39ce5482f649b437382c0fb2395eabc1e2b1702a6deb8ad647d6e", size = 2681895 },
+ { url = "https://files.pythonhosted.org/packages/67/32/32dc030cfa91ca0fc52baebbba2e009bb001122a1daa8b6a79ad830b38d3/pillow-11.2.1-cp313-cp313t-win_arm64.whl", hash = "sha256:225c832a13326e34f212d2072982bb1adb210e0cc0b153e688743018c94a2681", size = 2417234 },
+ { url = "https://files.pythonhosted.org/packages/21/3a/c1835d1c7cf83559e95b4f4ed07ab0bb7acc689712adfce406b3f456e9fd/pillow-11.2.1-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:7491cf8a79b8eb867d419648fff2f83cb0b3891c8b36da92cc7f1931d46108c8", size = 3198391 },
+ { url = "https://files.pythonhosted.org/packages/b6/4d/dcb7a9af3fc1e8653267c38ed622605d9d1793349274b3ef7af06457e257/pillow-11.2.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8b02d8f9cb83c52578a0b4beadba92e37d83a4ef11570a8688bbf43f4ca50909", size = 3030573 },
+ { url = "https://files.pythonhosted.org/packages/9d/29/530ca098c1a1eb31d4e163d317d0e24e6d2ead907991c69ca5b663de1bc5/pillow-11.2.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:014ca0050c85003620526b0ac1ac53f56fc93af128f7546623cc8e31875ab928", size = 4398677 },
+ { url = "https://files.pythonhosted.org/packages/8b/ee/0e5e51db34de1690264e5f30dcd25328c540aa11d50a3bc0b540e2a445b6/pillow-11.2.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3692b68c87096ac6308296d96354eddd25f98740c9d2ab54e1549d6c8aea9d79", size = 4484986 },
+ { url = "https://files.pythonhosted.org/packages/93/7d/bc723b41ce3d2c28532c47678ec988974f731b5c6fadd5b3a4fba9015e4f/pillow-11.2.1-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:f781dcb0bc9929adc77bad571b8621ecb1e4cdef86e940fe2e5b5ee24fd33b35", size = 4501897 },
+ { url = "https://files.pythonhosted.org/packages/be/0b/532e31abc7389617ddff12551af625a9b03cd61d2989fa595e43c470ec67/pillow-11.2.1-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:2b490402c96f907a166615e9a5afacf2519e28295f157ec3a2bb9bd57de638cb", size = 4592618 },
+ { url = "https://files.pythonhosted.org/packages/4c/f0/21ed6499a6216fef753e2e2254a19d08bff3747108ba042422383f3e9faa/pillow-11.2.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:dd6b20b93b3ccc9c1b597999209e4bc5cf2853f9ee66e3fc9a400a78733ffc9a", size = 4570493 },
+ { url = "https://files.pythonhosted.org/packages/68/de/17004ddb8ab855573fe1127ab0168d11378cdfe4a7ee2a792a70ff2e9ba7/pillow-11.2.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:4b835d89c08a6c2ee7781b8dd0a30209a8012b5f09c0a665b65b0eb3560b6f36", size = 4647748 },
+ { url = "https://files.pythonhosted.org/packages/c7/23/82ecb486384bb3578115c509d4a00bb52f463ee700a5ca1be53da3c88c19/pillow-11.2.1-cp39-cp39-win32.whl", hash = "sha256:b10428b3416d4f9c61f94b494681280be7686bda15898a3a9e08eb66a6d92d67", size = 2331731 },
+ { url = "https://files.pythonhosted.org/packages/58/bb/87efd58b3689537a623d44dbb2550ef0bb5ff6a62769707a0fe8b1a7bdeb/pillow-11.2.1-cp39-cp39-win_amd64.whl", hash = "sha256:6ebce70c3f486acf7591a3d73431fa504a4e18a9b97ff27f5f47b7368e4b9dd1", size = 2676346 },
+ { url = "https://files.pythonhosted.org/packages/80/08/dc268475b22887b816e5dcfae31bce897f524b4646bab130c2142c9b2400/pillow-11.2.1-cp39-cp39-win_arm64.whl", hash = "sha256:c27476257b2fdcd7872d54cfd119b3a9ce4610fb85c8e32b70b42e3680a29a1e", size = 2414623 },
+ { url = "https://files.pythonhosted.org/packages/33/49/c8c21e4255b4f4a2c0c68ac18125d7f5460b109acc6dfdef1a24f9b960ef/pillow-11.2.1-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:9b7b0d4fd2635f54ad82785d56bc0d94f147096493a79985d0ab57aedd563156", size = 3181727 },
+ { url = "https://files.pythonhosted.org/packages/6d/f1/f7255c0838f8c1ef6d55b625cfb286835c17e8136ce4351c5577d02c443b/pillow-11.2.1-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:aa442755e31c64037aa7c1cb186e0b369f8416c567381852c63444dd666fb772", size = 2999833 },
+ { url = "https://files.pythonhosted.org/packages/e2/57/9968114457bd131063da98d87790d080366218f64fa2943b65ac6739abb3/pillow-11.2.1-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0d3348c95b766f54b76116d53d4cb171b52992a1027e7ca50c81b43b9d9e363", size = 3437472 },
+ { url = "https://files.pythonhosted.org/packages/b2/1b/e35d8a158e21372ecc48aac9c453518cfe23907bb82f950d6e1c72811eb0/pillow-11.2.1-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:85d27ea4c889342f7e35f6d56e7e1cb345632ad592e8c51b693d7b7556043ce0", size = 3459976 },
+ { url = "https://files.pythonhosted.org/packages/26/da/2c11d03b765efff0ccc473f1c4186dc2770110464f2177efaed9cf6fae01/pillow-11.2.1-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:bf2c33d6791c598142f00c9c4c7d47f6476731c31081331664eb26d6ab583e01", size = 3527133 },
+ { url = "https://files.pythonhosted.org/packages/79/1a/4e85bd7cadf78412c2a3069249a09c32ef3323650fd3005c97cca7aa21df/pillow-11.2.1-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:e616e7154c37669fc1dfc14584f11e284e05d1c650e1c0f972f281c4ccc53193", size = 3571555 },
+ { url = "https://files.pythonhosted.org/packages/69/03/239939915216de1e95e0ce2334bf17a7870ae185eb390fab6d706aadbfc0/pillow-11.2.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:39ad2e0f424394e3aebc40168845fee52df1394a4673a6ee512d840d14ab3013", size = 2674713 },
+ { url = "https://files.pythonhosted.org/packages/a4/ad/2613c04633c7257d9481ab21d6b5364b59fc5d75faafd7cb8693523945a3/pillow-11.2.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:80f1df8dbe9572b4b7abdfa17eb5d78dd620b1d55d9e25f834efdbee872d3aed", size = 3181734 },
+ { url = "https://files.pythonhosted.org/packages/a4/fd/dcdda4471ed667de57bb5405bb42d751e6cfdd4011a12c248b455c778e03/pillow-11.2.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:ea926cfbc3957090becbcbbb65ad177161a2ff2ad578b5a6ec9bb1e1cd78753c", size = 2999841 },
+ { url = "https://files.pythonhosted.org/packages/ac/89/8a2536e95e77432833f0db6fd72a8d310c8e4272a04461fb833eb021bf94/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:738db0e0941ca0376804d4de6a782c005245264edaa253ffce24e5a15cbdc7bd", size = 3437470 },
+ { url = "https://files.pythonhosted.org/packages/9d/8f/abd47b73c60712f88e9eda32baced7bfc3e9bd6a7619bb64b93acff28c3e/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db98ab6565c69082ec9b0d4e40dd9f6181dab0dd236d26f7a50b8b9bfbd5076", size = 3460013 },
+ { url = "https://files.pythonhosted.org/packages/f6/20/5c0a0aa83b213b7a07ec01e71a3d6ea2cf4ad1d2c686cc0168173b6089e7/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:036e53f4170e270ddb8797d4c590e6dd14d28e15c7da375c18978045f7e6c37b", size = 3527165 },
+ { url = "https://files.pythonhosted.org/packages/58/0e/2abab98a72202d91146abc839e10c14f7cf36166f12838ea0c4db3ca6ecb/pillow-11.2.1-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:14f73f7c291279bd65fda51ee87affd7c1e097709f7fdd0188957a16c264601f", size = 3571586 },
+ { url = "https://files.pythonhosted.org/packages/21/2c/5e05f58658cf49b6667762cca03d6e7d85cededde2caf2ab37b81f80e574/pillow-11.2.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:208653868d5c9ecc2b327f9b9ef34e0e42a4cdd172c2988fd81d62d2bc9bc044", size = 2674751 },
+]
+
+[[package]]
+name = "platformdirs"
+version = "4.3.8"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567 },
+]
+
+[[package]]
+name = "pluggy"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538 },
+]
+
+[[package]]
+name = "prometheus-client"
+version = "0.22.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/5e/cf/40dde0a2be27cc1eb41e333d1a674a74ce8b8b0457269cc640fd42b07cf7/prometheus_client-0.22.1.tar.gz", hash = "sha256:190f1331e783cf21eb60bca559354e0a4d4378facecf78f5428c39b675d20d28", size = 69746 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/32/ae/ec06af4fe3ee72d16973474f122541746196aaa16cea6f66d18b963c6177/prometheus_client-0.22.1-py3-none-any.whl", hash = "sha256:cca895342e308174341b2cbf99a56bef291fbc0ef7b9e5412a0f26d653ba7094", size = 58694 },
+]
+
+[[package]]
+name = "prompt-toolkit"
+version = "3.0.51"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "wcwidth" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/bb/6e/9d084c929dfe9e3bfe0c6a47e31f78a25c54627d64a66e884a8bf5474f1c/prompt_toolkit-3.0.51.tar.gz", hash = "sha256:931a162e3b27fc90c86f1b48bb1fb2c528c2761475e57c9c06de13311c7b54ed", size = 428940 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ce/4f/5249960887b1fbe561d9ff265496d170b55a735b76724f10ef19f9e40716/prompt_toolkit-3.0.51-py3-none-any.whl", hash = "sha256:52742911fde84e2d423e2f9a4cf1de7d7ac4e51958f648d9540e0fb8db077b07", size = 387810 },
+]
+
+[[package]]
+name = "propcache"
+version = "0.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a6/16/43264e4a779dd8588c21a70f0709665ee8f611211bdd2c87d952cfa7c776/propcache-0.3.2.tar.gz", hash = "sha256:20d7d62e4e7ef05f221e0db2856b979540686342e7dd9973b815599c7057e168", size = 44139 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ab/14/510deed325e262afeb8b360043c5d7c960da7d3ecd6d6f9496c9c56dc7f4/propcache-0.3.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:22d9962a358aedbb7a2e36187ff273adeaab9743373a272976d2e348d08c7770", size = 73178 },
+ { url = "https://files.pythonhosted.org/packages/cd/4e/ad52a7925ff01c1325653a730c7ec3175a23f948f08626a534133427dcff/propcache-0.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0d0fda578d1dc3f77b6b5a5dce3b9ad69a8250a891760a548df850a5e8da87f3", size = 43133 },
+ { url = "https://files.pythonhosted.org/packages/63/7c/e9399ba5da7780871db4eac178e9c2e204c23dd3e7d32df202092a1ed400/propcache-0.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:3def3da3ac3ce41562d85db655d18ebac740cb3fa4367f11a52b3da9d03a5cc3", size = 43039 },
+ { url = "https://files.pythonhosted.org/packages/22/e1/58da211eb8fdc6fc854002387d38f415a6ca5f5c67c1315b204a5d3e9d7a/propcache-0.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9bec58347a5a6cebf239daba9bda37dffec5b8d2ce004d9fe4edef3d2815137e", size = 201903 },
+ { url = "https://files.pythonhosted.org/packages/c4/0a/550ea0f52aac455cb90111c8bab995208443e46d925e51e2f6ebdf869525/propcache-0.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55ffda449a507e9fbd4aca1a7d9aa6753b07d6166140e5a18d2ac9bc49eac220", size = 213362 },
+ { url = "https://files.pythonhosted.org/packages/5a/af/9893b7d878deda9bb69fcf54600b247fba7317761b7db11fede6e0f28bd0/propcache-0.3.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:64a67fb39229a8a8491dd42f864e5e263155e729c2e7ff723d6e25f596b1e8cb", size = 210525 },
+ { url = "https://files.pythonhosted.org/packages/7c/bb/38fd08b278ca85cde36d848091ad2b45954bc5f15cce494bb300b9285831/propcache-0.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9da1cf97b92b51253d5b68cf5a2b9e0dafca095e36b7f2da335e27dc6172a614", size = 198283 },
+ { url = "https://files.pythonhosted.org/packages/78/8c/9fe55bd01d362bafb413dfe508c48753111a1e269737fa143ba85693592c/propcache-0.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5f559e127134b07425134b4065be45b166183fdcb433cb6c24c8e4149056ad50", size = 191872 },
+ { url = "https://files.pythonhosted.org/packages/54/14/4701c33852937a22584e08abb531d654c8bcf7948a8f87ad0a4822394147/propcache-0.3.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:aff2e4e06435d61f11a428360a932138d0ec288b0a31dd9bd78d200bd4a2b339", size = 199452 },
+ { url = "https://files.pythonhosted.org/packages/16/44/447f2253d859602095356007657ee535e0093215ea0b3d1d6a41d16e5201/propcache-0.3.2-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:4927842833830942a5d0a56e6f4839bc484785b8e1ce8d287359794818633ba0", size = 191567 },
+ { url = "https://files.pythonhosted.org/packages/f2/b3/e4756258749bb2d3b46defcff606a2f47410bab82be5824a67e84015b267/propcache-0.3.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:6107ddd08b02654a30fb8ad7a132021759d750a82578b94cd55ee2772b6ebea2", size = 193015 },
+ { url = "https://files.pythonhosted.org/packages/1e/df/e6d3c7574233164b6330b9fd697beeac402afd367280e6dc377bb99b43d9/propcache-0.3.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:70bd8b9cd6b519e12859c99f3fc9a93f375ebd22a50296c3a295028bea73b9e7", size = 204660 },
+ { url = "https://files.pythonhosted.org/packages/b2/53/e4d31dd5170b4a0e2e6b730f2385a96410633b4833dc25fe5dffd1f73294/propcache-0.3.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:2183111651d710d3097338dd1893fcf09c9f54e27ff1a8795495a16a469cc90b", size = 206105 },
+ { url = "https://files.pythonhosted.org/packages/7f/fe/74d54cf9fbe2a20ff786e5f7afcfde446588f0cf15fb2daacfbc267b866c/propcache-0.3.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:fb075ad271405dcad8e2a7ffc9a750a3bf70e533bd86e89f0603e607b93aa64c", size = 196980 },
+ { url = "https://files.pythonhosted.org/packages/22/ec/c469c9d59dada8a7679625e0440b544fe72e99311a4679c279562051f6fc/propcache-0.3.2-cp310-cp310-win32.whl", hash = "sha256:404d70768080d3d3bdb41d0771037da19d8340d50b08e104ca0e7f9ce55fce70", size = 37679 },
+ { url = "https://files.pythonhosted.org/packages/38/35/07a471371ac89d418f8d0b699c75ea6dca2041fbda360823de21f6a9ce0a/propcache-0.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:7435d766f978b4ede777002e6b3b6641dd229cd1da8d3d3106a45770365f9ad9", size = 41459 },
+ { url = "https://files.pythonhosted.org/packages/80/8d/e8b436717ab9c2cfc23b116d2c297305aa4cd8339172a456d61ebf5669b8/propcache-0.3.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0b8d2f607bd8f80ddc04088bc2a037fdd17884a6fcadc47a96e334d72f3717be", size = 74207 },
+ { url = "https://files.pythonhosted.org/packages/d6/29/1e34000e9766d112171764b9fa3226fa0153ab565d0c242c70e9945318a7/propcache-0.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:06766d8f34733416e2e34f46fea488ad5d60726bb9481d3cddf89a6fa2d9603f", size = 43648 },
+ { url = "https://files.pythonhosted.org/packages/46/92/1ad5af0df781e76988897da39b5f086c2bf0f028b7f9bd1f409bb05b6874/propcache-0.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2dc1f4a1df4fecf4e6f68013575ff4af84ef6f478fe5344317a65d38a8e6dc9", size = 43496 },
+ { url = "https://files.pythonhosted.org/packages/b3/ce/e96392460f9fb68461fabab3e095cb00c8ddf901205be4eae5ce246e5b7e/propcache-0.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be29c4f4810c5789cf10ddf6af80b041c724e629fa51e308a7a0fb19ed1ef7bf", size = 217288 },
+ { url = "https://files.pythonhosted.org/packages/c5/2a/866726ea345299f7ceefc861a5e782b045545ae6940851930a6adaf1fca6/propcache-0.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:59d61f6970ecbd8ff2e9360304d5c8876a6abd4530cb752c06586849ac8a9dc9", size = 227456 },
+ { url = "https://files.pythonhosted.org/packages/de/03/07d992ccb6d930398689187e1b3c718339a1c06b8b145a8d9650e4726166/propcache-0.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:62180e0b8dbb6b004baec00a7983e4cc52f5ada9cd11f48c3528d8cfa7b96a66", size = 225429 },
+ { url = "https://files.pythonhosted.org/packages/5d/e6/116ba39448753b1330f48ab8ba927dcd6cf0baea8a0ccbc512dfb49ba670/propcache-0.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c144ca294a204c470f18cf4c9d78887810d04a3e2fbb30eea903575a779159df", size = 213472 },
+ { url = "https://files.pythonhosted.org/packages/a6/85/f01f5d97e54e428885a5497ccf7f54404cbb4f906688a1690cd51bf597dc/propcache-0.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c5c2a784234c28854878d68978265617aa6dc0780e53d44b4d67f3651a17a9a2", size = 204480 },
+ { url = "https://files.pythonhosted.org/packages/e3/79/7bf5ab9033b8b8194cc3f7cf1aaa0e9c3256320726f64a3e1f113a812dce/propcache-0.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5745bc7acdafa978ca1642891b82c19238eadc78ba2aaa293c6863b304e552d7", size = 214530 },
+ { url = "https://files.pythonhosted.org/packages/31/0b/bd3e0c00509b609317df4a18e6b05a450ef2d9a963e1d8bc9c9415d86f30/propcache-0.3.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:c0075bf773d66fa8c9d41f66cc132ecc75e5bb9dd7cce3cfd14adc5ca184cb95", size = 205230 },
+ { url = "https://files.pythonhosted.org/packages/7a/23/fae0ff9b54b0de4e819bbe559508da132d5683c32d84d0dc2ccce3563ed4/propcache-0.3.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5f57aa0847730daceff0497f417c9de353c575d8da3579162cc74ac294c5369e", size = 206754 },
+ { url = "https://files.pythonhosted.org/packages/b7/7f/ad6a3c22630aaa5f618b4dc3c3598974a72abb4c18e45a50b3cdd091eb2f/propcache-0.3.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:eef914c014bf72d18efb55619447e0aecd5fb7c2e3fa7441e2e5d6099bddff7e", size = 218430 },
+ { url = "https://files.pythonhosted.org/packages/5b/2c/ba4f1c0e8a4b4c75910742f0d333759d441f65a1c7f34683b4a74c0ee015/propcache-0.3.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:2a4092e8549031e82facf3decdbc0883755d5bbcc62d3aea9d9e185549936dcf", size = 223884 },
+ { url = "https://files.pythonhosted.org/packages/88/e4/ebe30fc399e98572019eee82ad0caf512401661985cbd3da5e3140ffa1b0/propcache-0.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:85871b050f174bc0bfb437efbdb68aaf860611953ed12418e4361bc9c392749e", size = 211480 },
+ { url = "https://files.pythonhosted.org/packages/96/0a/7d5260b914e01d1d0906f7f38af101f8d8ed0dc47426219eeaf05e8ea7c2/propcache-0.3.2-cp311-cp311-win32.whl", hash = "sha256:36c8d9b673ec57900c3554264e630d45980fd302458e4ac801802a7fd2ef7897", size = 37757 },
+ { url = "https://files.pythonhosted.org/packages/e1/2d/89fe4489a884bc0da0c3278c552bd4ffe06a1ace559db5ef02ef24ab446b/propcache-0.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53af8cb6a781b02d2ea079b5b853ba9430fcbe18a8e3ce647d5982a3ff69f39", size = 41500 },
+ { url = "https://files.pythonhosted.org/packages/a8/42/9ca01b0a6f48e81615dca4765a8f1dd2c057e0540f6116a27dc5ee01dfb6/propcache-0.3.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8de106b6c84506b31c27168582cd3cb3000a6412c16df14a8628e5871ff83c10", size = 73674 },
+ { url = "https://files.pythonhosted.org/packages/af/6e/21293133beb550f9c901bbece755d582bfaf2176bee4774000bd4dd41884/propcache-0.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:28710b0d3975117239c76600ea351934ac7b5ff56e60953474342608dbbb6154", size = 43570 },
+ { url = "https://files.pythonhosted.org/packages/0c/c8/0393a0a3a2b8760eb3bde3c147f62b20044f0ddac81e9d6ed7318ec0d852/propcache-0.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce26862344bdf836650ed2487c3d724b00fbfec4233a1013f597b78c1cb73615", size = 43094 },
+ { url = "https://files.pythonhosted.org/packages/37/2c/489afe311a690399d04a3e03b069225670c1d489eb7b044a566511c1c498/propcache-0.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bca54bd347a253af2cf4544bbec232ab982f4868de0dd684246b67a51bc6b1db", size = 226958 },
+ { url = "https://files.pythonhosted.org/packages/9d/ca/63b520d2f3d418c968bf596839ae26cf7f87bead026b6192d4da6a08c467/propcache-0.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55780d5e9a2ddc59711d727226bb1ba83a22dd32f64ee15594b9392b1f544eb1", size = 234894 },
+ { url = "https://files.pythonhosted.org/packages/11/60/1d0ed6fff455a028d678df30cc28dcee7af77fa2b0e6962ce1df95c9a2a9/propcache-0.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:035e631be25d6975ed87ab23153db6a73426a48db688070d925aa27e996fe93c", size = 233672 },
+ { url = "https://files.pythonhosted.org/packages/37/7c/54fd5301ef38505ab235d98827207176a5c9b2aa61939b10a460ca53e123/propcache-0.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ee6f22b6eaa39297c751d0e80c0d3a454f112f5c6481214fcf4c092074cecd67", size = 224395 },
+ { url = "https://files.pythonhosted.org/packages/ee/1a/89a40e0846f5de05fdc6779883bf46ba980e6df4d2ff8fb02643de126592/propcache-0.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7ca3aee1aa955438c4dba34fc20a9f390e4c79967257d830f137bd5a8a32ed3b", size = 212510 },
+ { url = "https://files.pythonhosted.org/packages/5e/33/ca98368586c9566a6b8d5ef66e30484f8da84c0aac3f2d9aec6d31a11bd5/propcache-0.3.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7a4f30862869fa2b68380d677cc1c5fcf1e0f2b9ea0cf665812895c75d0ca3b8", size = 222949 },
+ { url = "https://files.pythonhosted.org/packages/ba/11/ace870d0aafe443b33b2f0b7efdb872b7c3abd505bfb4890716ad7865e9d/propcache-0.3.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b77ec3c257d7816d9f3700013639db7491a434644c906a2578a11daf13176251", size = 217258 },
+ { url = "https://files.pythonhosted.org/packages/5b/d2/86fd6f7adffcfc74b42c10a6b7db721d1d9ca1055c45d39a1a8f2a740a21/propcache-0.3.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:cab90ac9d3f14b2d5050928483d3d3b8fb6b4018893fc75710e6aa361ecb2474", size = 213036 },
+ { url = "https://files.pythonhosted.org/packages/07/94/2d7d1e328f45ff34a0a284cf5a2847013701e24c2a53117e7c280a4316b3/propcache-0.3.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:0b504d29f3c47cf6b9e936c1852246c83d450e8e063d50562115a6be6d3a2535", size = 227684 },
+ { url = "https://files.pythonhosted.org/packages/b7/05/37ae63a0087677e90b1d14710e532ff104d44bc1efa3b3970fff99b891dc/propcache-0.3.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:ce2ac2675a6aa41ddb2a0c9cbff53780a617ac3d43e620f8fd77ba1c84dcfc06", size = 234562 },
+ { url = "https://files.pythonhosted.org/packages/a4/7c/3f539fcae630408d0bd8bf3208b9a647ccad10976eda62402a80adf8fc34/propcache-0.3.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:62b4239611205294cc433845b914131b2a1f03500ff3c1ed093ed216b82621e1", size = 222142 },
+ { url = "https://files.pythonhosted.org/packages/7c/d2/34b9eac8c35f79f8a962546b3e97e9d4b990c420ee66ac8255d5d9611648/propcache-0.3.2-cp312-cp312-win32.whl", hash = "sha256:df4a81b9b53449ebc90cc4deefb052c1dd934ba85012aa912c7ea7b7e38b60c1", size = 37711 },
+ { url = "https://files.pythonhosted.org/packages/19/61/d582be5d226cf79071681d1b46b848d6cb03d7b70af7063e33a2787eaa03/propcache-0.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:7046e79b989d7fe457bb755844019e10f693752d169076138abf17f31380800c", size = 41479 },
+ { url = "https://files.pythonhosted.org/packages/dc/d1/8c747fafa558c603c4ca19d8e20b288aa0c7cda74e9402f50f31eb65267e/propcache-0.3.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ca592ed634a73ca002967458187109265e980422116c0a107cf93d81f95af945", size = 71286 },
+ { url = "https://files.pythonhosted.org/packages/61/99/d606cb7986b60d89c36de8a85d58764323b3a5ff07770a99d8e993b3fa73/propcache-0.3.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:9ecb0aad4020e275652ba3975740f241bd12a61f1a784df044cf7477a02bc252", size = 42425 },
+ { url = "https://files.pythonhosted.org/packages/8c/96/ef98f91bbb42b79e9bb82bdd348b255eb9d65f14dbbe3b1594644c4073f7/propcache-0.3.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7f08f1cc28bd2eade7a8a3d2954ccc673bb02062e3e7da09bc75d843386b342f", size = 41846 },
+ { url = "https://files.pythonhosted.org/packages/5b/ad/3f0f9a705fb630d175146cd7b1d2bf5555c9beaed54e94132b21aac098a6/propcache-0.3.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d1a342c834734edb4be5ecb1e9fb48cb64b1e2320fccbd8c54bf8da8f2a84c33", size = 208871 },
+ { url = "https://files.pythonhosted.org/packages/3a/38/2085cda93d2c8b6ec3e92af2c89489a36a5886b712a34ab25de9fbca7992/propcache-0.3.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8a544caaae1ac73f1fecfae70ded3e93728831affebd017d53449e3ac052ac1e", size = 215720 },
+ { url = "https://files.pythonhosted.org/packages/61/c1/d72ea2dc83ac7f2c8e182786ab0fc2c7bd123a1ff9b7975bee671866fe5f/propcache-0.3.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:310d11aa44635298397db47a3ebce7db99a4cc4b9bbdfcf6c98a60c8d5261cf1", size = 215203 },
+ { url = "https://files.pythonhosted.org/packages/af/81/b324c44ae60c56ef12007105f1460d5c304b0626ab0cc6b07c8f2a9aa0b8/propcache-0.3.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c1396592321ac83157ac03a2023aa6cc4a3cc3cfdecb71090054c09e5a7cce3", size = 206365 },
+ { url = "https://files.pythonhosted.org/packages/09/73/88549128bb89e66d2aff242488f62869014ae092db63ccea53c1cc75a81d/propcache-0.3.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8cabf5b5902272565e78197edb682017d21cf3b550ba0460ee473753f28d23c1", size = 196016 },
+ { url = "https://files.pythonhosted.org/packages/b9/3f/3bdd14e737d145114a5eb83cb172903afba7242f67c5877f9909a20d948d/propcache-0.3.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0a2f2235ac46a7aa25bdeb03a9e7060f6ecbd213b1f9101c43b3090ffb971ef6", size = 205596 },
+ { url = "https://files.pythonhosted.org/packages/0f/ca/2f4aa819c357d3107c3763d7ef42c03980f9ed5c48c82e01e25945d437c1/propcache-0.3.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:92b69e12e34869a6970fd2f3da91669899994b47c98f5d430b781c26f1d9f387", size = 200977 },
+ { url = "https://files.pythonhosted.org/packages/cd/4a/e65276c7477533c59085251ae88505caf6831c0e85ff8b2e31ebcbb949b1/propcache-0.3.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:54e02207c79968ebbdffc169591009f4474dde3b4679e16634d34c9363ff56b4", size = 197220 },
+ { url = "https://files.pythonhosted.org/packages/7c/54/fc7152e517cf5578278b242396ce4d4b36795423988ef39bb8cd5bf274c8/propcache-0.3.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:4adfb44cb588001f68c5466579d3f1157ca07f7504fc91ec87862e2b8e556b88", size = 210642 },
+ { url = "https://files.pythonhosted.org/packages/b9/80/abeb4a896d2767bf5f1ea7b92eb7be6a5330645bd7fb844049c0e4045d9d/propcache-0.3.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:fd3e6019dc1261cd0291ee8919dd91fbab7b169bb76aeef6c716833a3f65d206", size = 212789 },
+ { url = "https://files.pythonhosted.org/packages/b3/db/ea12a49aa7b2b6d68a5da8293dcf50068d48d088100ac016ad92a6a780e6/propcache-0.3.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4c181cad81158d71c41a2bce88edce078458e2dd5ffee7eddd6b05da85079f43", size = 205880 },
+ { url = "https://files.pythonhosted.org/packages/d1/e5/9076a0bbbfb65d1198007059c65639dfd56266cf8e477a9707e4b1999ff4/propcache-0.3.2-cp313-cp313-win32.whl", hash = "sha256:8a08154613f2249519e549de2330cf8e2071c2887309a7b07fb56098f5170a02", size = 37220 },
+ { url = "https://files.pythonhosted.org/packages/d3/f5/b369e026b09a26cd77aa88d8fffd69141d2ae00a2abaaf5380d2603f4b7f/propcache-0.3.2-cp313-cp313-win_amd64.whl", hash = "sha256:e41671f1594fc4ab0a6dec1351864713cb3a279910ae8b58f884a88a0a632c05", size = 40678 },
+ { url = "https://files.pythonhosted.org/packages/a4/3a/6ece377b55544941a08d03581c7bc400a3c8cd3c2865900a68d5de79e21f/propcache-0.3.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:9a3cf035bbaf035f109987d9d55dc90e4b0e36e04bbbb95af3055ef17194057b", size = 76560 },
+ { url = "https://files.pythonhosted.org/packages/0c/da/64a2bb16418740fa634b0e9c3d29edff1db07f56d3546ca2d86ddf0305e1/propcache-0.3.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:156c03d07dc1323d8dacaa221fbe028c5c70d16709cdd63502778e6c3ccca1b0", size = 44676 },
+ { url = "https://files.pythonhosted.org/packages/36/7b/f025e06ea51cb72c52fb87e9b395cced02786610b60a3ed51da8af017170/propcache-0.3.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74413c0ba02ba86f55cf60d18daab219f7e531620c15f1e23d95563f505efe7e", size = 44701 },
+ { url = "https://files.pythonhosted.org/packages/a4/00/faa1b1b7c3b74fc277f8642f32a4c72ba1d7b2de36d7cdfb676db7f4303e/propcache-0.3.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f066b437bb3fa39c58ff97ab2ca351db465157d68ed0440abecb21715eb24b28", size = 276934 },
+ { url = "https://files.pythonhosted.org/packages/74/ab/935beb6f1756e0476a4d5938ff44bf0d13a055fed880caf93859b4f1baf4/propcache-0.3.2-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f1304b085c83067914721e7e9d9917d41ad87696bf70f0bc7dee450e9c71ad0a", size = 278316 },
+ { url = "https://files.pythonhosted.org/packages/f8/9d/994a5c1ce4389610838d1caec74bdf0e98b306c70314d46dbe4fcf21a3e2/propcache-0.3.2-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ab50cef01b372763a13333b4e54021bdcb291fc9a8e2ccb9c2df98be51bcde6c", size = 282619 },
+ { url = "https://files.pythonhosted.org/packages/2b/00/a10afce3d1ed0287cef2e09506d3be9822513f2c1e96457ee369adb9a6cd/propcache-0.3.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fad3b2a085ec259ad2c2842666b2a0a49dea8463579c606426128925af1ed725", size = 265896 },
+ { url = "https://files.pythonhosted.org/packages/2e/a8/2aa6716ffa566ca57c749edb909ad27884680887d68517e4be41b02299f3/propcache-0.3.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:261fa020c1c14deafd54c76b014956e2f86991af198c51139faf41c4d5e83892", size = 252111 },
+ { url = "https://files.pythonhosted.org/packages/36/4f/345ca9183b85ac29c8694b0941f7484bf419c7f0fea2d1e386b4f7893eed/propcache-0.3.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:46d7f8aa79c927e5f987ee3a80205c987717d3659f035c85cf0c3680526bdb44", size = 268334 },
+ { url = "https://files.pythonhosted.org/packages/3e/ca/fcd54f78b59e3f97b3b9715501e3147f5340167733d27db423aa321e7148/propcache-0.3.2-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:6d8f3f0eebf73e3c0ff0e7853f68be638b4043c65a70517bb575eff54edd8dbe", size = 255026 },
+ { url = "https://files.pythonhosted.org/packages/8b/95/8e6a6bbbd78ac89c30c225210a5c687790e532ba4088afb8c0445b77ef37/propcache-0.3.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:03c89c1b14a5452cf15403e291c0ccd7751d5b9736ecb2c5bab977ad6c5bcd81", size = 250724 },
+ { url = "https://files.pythonhosted.org/packages/ee/b0/0dd03616142baba28e8b2d14ce5df6631b4673850a3d4f9c0f9dd714a404/propcache-0.3.2-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:0cc17efde71e12bbaad086d679ce575268d70bc123a5a71ea7ad76f70ba30bba", size = 268868 },
+ { url = "https://files.pythonhosted.org/packages/c5/98/2c12407a7e4fbacd94ddd32f3b1e3d5231e77c30ef7162b12a60e2dd5ce3/propcache-0.3.2-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:acdf05d00696bc0447e278bb53cb04ca72354e562cf88ea6f9107df8e7fd9770", size = 271322 },
+ { url = "https://files.pythonhosted.org/packages/35/91/9cb56efbb428b006bb85db28591e40b7736847b8331d43fe335acf95f6c8/propcache-0.3.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4445542398bd0b5d32df908031cb1b30d43ac848e20470a878b770ec2dcc6330", size = 265778 },
+ { url = "https://files.pythonhosted.org/packages/9a/4c/b0fe775a2bdd01e176b14b574be679d84fc83958335790f7c9a686c1f468/propcache-0.3.2-cp313-cp313t-win32.whl", hash = "sha256:f86e5d7cd03afb3a1db8e9f9f6eff15794e79e791350ac48a8c924e6f439f394", size = 41175 },
+ { url = "https://files.pythonhosted.org/packages/a4/ff/47f08595e3d9b5e149c150f88d9714574f1a7cbd89fe2817158a952674bf/propcache-0.3.2-cp313-cp313t-win_amd64.whl", hash = "sha256:9704bedf6e7cbe3c65eca4379a9b53ee6a83749f047808cbb5044d40d7d72198", size = 44857 },
+ { url = "https://files.pythonhosted.org/packages/6c/39/8ea9bcfaaff16fd0b0fc901ee522e24c9ec44b4ca0229cfffb8066a06959/propcache-0.3.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:a7fad897f14d92086d6b03fdd2eb844777b0c4d7ec5e3bac0fbae2ab0602bbe5", size = 74678 },
+ { url = "https://files.pythonhosted.org/packages/d3/85/cab84c86966e1d354cf90cdc4ba52f32f99a5bca92a1529d666d957d7686/propcache-0.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:1f43837d4ca000243fd7fd6301947d7cb93360d03cd08369969450cc6b2ce3b4", size = 43829 },
+ { url = "https://files.pythonhosted.org/packages/23/f7/9cb719749152d8b26d63801b3220ce2d3931312b2744d2b3a088b0ee9947/propcache-0.3.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:261df2e9474a5949c46e962065d88eb9b96ce0f2bd30e9d3136bcde84befd8f2", size = 43729 },
+ { url = "https://files.pythonhosted.org/packages/a2/a2/0b2b5a210ff311260002a315f6f9531b65a36064dfb804655432b2f7d3e3/propcache-0.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e514326b79e51f0a177daab1052bc164d9d9e54133797a3a58d24c9c87a3fe6d", size = 204483 },
+ { url = "https://files.pythonhosted.org/packages/3f/e0/7aff5de0c535f783b0c8be5bdb750c305c1961d69fbb136939926e155d98/propcache-0.3.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d4a996adb6904f85894570301939afeee65f072b4fd265ed7e569e8d9058e4ec", size = 217425 },
+ { url = "https://files.pythonhosted.org/packages/92/1d/65fa889eb3b2a7d6e4ed3c2b568a9cb8817547a1450b572de7bf24872800/propcache-0.3.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:76cace5d6b2a54e55b137669b30f31aa15977eeed390c7cbfb1dafa8dfe9a701", size = 214723 },
+ { url = "https://files.pythonhosted.org/packages/9a/e2/eecf6989870988dfd731de408a6fa366e853d361a06c2133b5878ce821ad/propcache-0.3.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31248e44b81d59d6addbb182c4720f90b44e1efdc19f58112a3c3a1615fb47ef", size = 200166 },
+ { url = "https://files.pythonhosted.org/packages/12/06/c32be4950967f18f77489268488c7cdc78cbfc65a8ba8101b15e526b83dc/propcache-0.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:abb7fa19dbf88d3857363e0493b999b8011eea856b846305d8c0512dfdf8fbb1", size = 194004 },
+ { url = "https://files.pythonhosted.org/packages/46/6c/17b521a6b3b7cbe277a4064ff0aa9129dd8c89f425a5a9b6b4dd51cc3ff4/propcache-0.3.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:d81ac3ae39d38588ad0549e321e6f773a4e7cc68e7751524a22885d5bbadf886", size = 203075 },
+ { url = "https://files.pythonhosted.org/packages/62/cb/3bdba2b736b3e45bc0e40f4370f745b3e711d439ffbffe3ae416393eece9/propcache-0.3.2-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:cc2782eb0f7a16462285b6f8394bbbd0e1ee5f928034e941ffc444012224171b", size = 195407 },
+ { url = "https://files.pythonhosted.org/packages/29/bd/760c5c6a60a4a2c55a421bc34a25ba3919d49dee411ddb9d1493bb51d46e/propcache-0.3.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:db429c19a6c7e8a1c320e6a13c99799450f411b02251fb1b75e6217cf4a14fcb", size = 196045 },
+ { url = "https://files.pythonhosted.org/packages/76/58/ced2757a46f55b8c84358d6ab8de4faf57cba831c51e823654da7144b13a/propcache-0.3.2-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:21d8759141a9e00a681d35a1f160892a36fb6caa715ba0b832f7747da48fb6ea", size = 208432 },
+ { url = "https://files.pythonhosted.org/packages/bb/ec/d98ea8d5a4d8fe0e372033f5254eddf3254344c0c5dc6c49ab84349e4733/propcache-0.3.2-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:2ca6d378f09adb13837614ad2754fa8afaee330254f404299611bce41a8438cb", size = 210100 },
+ { url = "https://files.pythonhosted.org/packages/56/84/b6d8a7ecf3f62d7dd09d9d10bbf89fad6837970ef868b35b5ffa0d24d9de/propcache-0.3.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:34a624af06c048946709f4278b4176470073deda88d91342665d95f7c6270fbe", size = 200712 },
+ { url = "https://files.pythonhosted.org/packages/bf/32/889f4903ddfe4a9dc61da71ee58b763758cf2d608fe1decede06e6467f8d/propcache-0.3.2-cp39-cp39-win32.whl", hash = "sha256:4ba3fef1c30f306b1c274ce0b8baaa2c3cdd91f645c48f06394068f37d3837a1", size = 38187 },
+ { url = "https://files.pythonhosted.org/packages/67/74/d666795fb9ba1dc139d30de64f3b6fd1ff9c9d3d96ccfdb992cd715ce5d2/propcache-0.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:7a2368eed65fc69a7a7a40b27f22e85e7627b74216f0846b04ba5c116e191ec9", size = 42025 },
+ { url = "https://files.pythonhosted.org/packages/cc/35/cc0aaecf278bb4575b8555f2b137de5ab821595ddae9da9d3cd1da4072c7/propcache-0.3.2-py3-none-any.whl", hash = "sha256:98f1ec44fb675f5052cccc8e609c46ed23a35a1cfd18545ad4e29002d858a43f", size = 12663 },
+]
+
+[[package]]
+name = "protobuf"
+version = "4.25.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/5e/d8/65adb47d921ce828ba319d6587aa8758da022de509c3862a70177a958844/protobuf-4.25.3.tar.gz", hash = "sha256:25b5d0b42fd000320bd7830b349e3b696435f3b329810427a6bcce6a5492cc5c", size = 380274 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ce/c7/0d3bf9f6700b8ce36968899aaca4fa82d8dc6ee981f248565bec8cf3719f/protobuf-4.25.3-cp310-abi3-win32.whl", hash = "sha256:d4198877797a83cbfe9bffa3803602bbe1625dc30d8a097365dbc762e5790faa", size = 392414 },
+ { url = "https://files.pythonhosted.org/packages/ad/6e/1bed3b7c904cc178cb8ee8dbaf72934964452b3de95b7a63412591edb93c/protobuf-4.25.3-cp310-abi3-win_amd64.whl", hash = "sha256:209ba4cc916bab46f64e56b85b090607a676f66b473e6b762e6f1d9d591eb2e8", size = 413401 },
+ { url = "https://files.pythonhosted.org/packages/f3/bf/26deba06a4c910a85f78245cac7698f67cedd7efe00d04f6b3e1b3506a59/protobuf-4.25.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:f1279ab38ecbfae7e456a108c5c0681e4956d5b1090027c1de0f934dfdb4b35c", size = 394162 },
+ { url = "https://files.pythonhosted.org/packages/d8/82/aefe901174b5a618daee511ddd00342193c1b545e3cd6a2cd6df9ba452b5/protobuf-4.25.3-cp37-abi3-manylinux2014_aarch64.whl", hash = "sha256:e7cb0ae90dd83727f0c0718634ed56837bfeeee29a5f82a7514c03ee1364c019", size = 293701 },
+ { url = "https://files.pythonhosted.org/packages/15/db/7f731524fe0e56c6b2eb57d05b55d3badd80ef7d1f1ed59db191b2fdd8ab/protobuf-4.25.3-cp37-abi3-manylinux2014_x86_64.whl", hash = "sha256:7c8daa26095f82482307bc717364e7c13f4f1c99659be82890dcfc215194554d", size = 294613 },
+ { url = "https://files.pythonhosted.org/packages/67/ff/62939c3861f6385ab6a535fa1aeb2efdf9526dbd89f80409c9c2f6f46213/protobuf-4.25.3-cp39-cp39-win32.whl", hash = "sha256:19b270aeaa0099f16d3ca02628546b8baefe2955bbe23224aaf856134eccf1e4", size = 392491 },
+ { url = "https://files.pythonhosted.org/packages/d8/b8/ca033cb753f84a4d780c92a6e5a625c6d25eafc60353d0e258f20d5789f0/protobuf-4.25.3-cp39-cp39-win_amd64.whl", hash = "sha256:e3c97a1555fd6388f857770ff8b9703083de6bf1f9274a002a332d65fbb56c8c", size = 413358 },
+ { url = "https://files.pythonhosted.org/packages/f4/d5/db585a5e8d64af6b384c7b3a63da13df2ff86933e486ba78431736c67c25/protobuf-4.25.3-py3-none-any.whl", hash = "sha256:f0700d54bcf45424477e46a9f0944155b46fb0639d69728739c0e47bab83f2b9", size = 156466 },
+]
+
+[[package]]
+name = "psutil"
+version = "7.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/2a/80/336820c1ad9286a4ded7e845b2eccfcb27851ab8ac6abece774a6ff4d3de/psutil-7.0.0.tar.gz", hash = "sha256:7be9c3eba38beccb6495ea33afd982a44074b78f28c434a1f51cc07fd315c456", size = 497003 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ed/e6/2d26234410f8b8abdbf891c9da62bee396583f713fb9f3325a4760875d22/psutil-7.0.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25", size = 238051 },
+ { url = "https://files.pythonhosted.org/packages/04/8b/30f930733afe425e3cbfc0e1468a30a18942350c1a8816acfade80c005c4/psutil-7.0.0-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:39db632f6bb862eeccf56660871433e111b6ea58f2caea825571951d4b6aa3da", size = 239535 },
+ { url = "https://files.pythonhosted.org/packages/2a/ed/d362e84620dd22876b55389248e522338ed1bf134a5edd3b8231d7207f6d/psutil-7.0.0-cp36-abi3-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fcee592b4c6f146991ca55919ea3d1f8926497a713ed7faaf8225e174581e91", size = 275004 },
+ { url = "https://files.pythonhosted.org/packages/bf/b9/b0eb3f3cbcb734d930fdf839431606844a825b23eaf9a6ab371edac8162c/psutil-7.0.0-cp36-abi3-manylinux_2_12_x86_64.manylinux2010_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b1388a4f6875d7e2aff5c4ca1cc16c545ed41dd8bb596cefea80111db353a34", size = 277986 },
+ { url = "https://files.pythonhosted.org/packages/eb/a2/709e0fe2f093556c17fbafda93ac032257242cabcc7ff3369e2cb76a97aa/psutil-7.0.0-cp36-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5f098451abc2828f7dc6b58d44b532b22f2088f4999a937557b603ce72b1993", size = 279544 },
+ { url = "https://files.pythonhosted.org/packages/50/e6/eecf58810b9d12e6427369784efe814a1eec0f492084ce8eb8f4d89d6d61/psutil-7.0.0-cp37-abi3-win32.whl", hash = "sha256:ba3fcef7523064a6c9da440fc4d6bd07da93ac726b5733c29027d7dc95b39d99", size = 241053 },
+ { url = "https://files.pythonhosted.org/packages/50/1b/6921afe68c74868b4c9fa424dad3be35b095e16687989ebbb50ce4fceb7c/psutil-7.0.0-cp37-abi3-win_amd64.whl", hash = "sha256:4cf3d4eb1aa9b348dec30105c55cd9b7d4629285735a102beb4441e38db90553", size = 244885 },
+]
+
+[[package]]
+name = "ptyprocess"
+version = "0.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993 },
+]
+
+[[package]]
+name = "pure-eval"
+version = "0.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cd/05/0a34433a064256a578f1783a10da6df098ceaa4a57bbeaa96a6c0352786b/pure_eval-0.2.3.tar.gz", hash = "sha256:5f4e983f40564c576c7c8635ae88db5956bb2229d7e9237d03b3c0b0190eaf42", size = 19752 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8e/37/efad0257dc6e593a18957422533ff0f87ede7c9c6ea010a2177d738fb82f/pure_eval-0.2.3-py3-none-any.whl", hash = "sha256:1db8e35b67b3d218d818ae653e27f06c3aa420901fa7b081ca98cbedc874e0d0", size = 11842 },
+]
+
+[[package]]
+name = "pyarrow"
+version = "20.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/ee/a7810cb9f3d6e9238e61d312076a9859bf3668fd21c69744de9532383912/pyarrow-20.0.0.tar.gz", hash = "sha256:febc4a913592573c8d5805091a6c2b5064c8bd6e002131f01061797d91c783c1", size = 1125187 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5b/23/77094eb8ee0dbe88441689cb6afc40ac312a1e15d3a7acc0586999518222/pyarrow-20.0.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:c7dd06fd7d7b410ca5dc839cc9d485d2bc4ae5240851bcd45d85105cc90a47d7", size = 30832591 },
+ { url = "https://files.pythonhosted.org/packages/c3/d5/48cc573aff00d62913701d9fac478518f693b30c25f2c157550b0b2565cb/pyarrow-20.0.0-cp310-cp310-macosx_12_0_x86_64.whl", hash = "sha256:d5382de8dc34c943249b01c19110783d0d64b207167c728461add1ecc2db88e4", size = 32273686 },
+ { url = "https://files.pythonhosted.org/packages/37/df/4099b69a432b5cb412dd18adc2629975544d656df3d7fda6d73c5dba935d/pyarrow-20.0.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6415a0d0174487456ddc9beaead703d0ded5966129fa4fd3114d76b5d1c5ceae", size = 41337051 },
+ { url = "https://files.pythonhosted.org/packages/4c/27/99922a9ac1c9226f346e3a1e15e63dee6f623ed757ff2893f9d6994a69d3/pyarrow-20.0.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15aa1b3b2587e74328a730457068dc6c89e6dcbf438d4369f572af9d320a25ee", size = 42404659 },
+ { url = "https://files.pythonhosted.org/packages/21/d1/71d91b2791b829c9e98f1e0d85be66ed93aff399f80abb99678511847eaa/pyarrow-20.0.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:5605919fbe67a7948c1f03b9f3727d82846c053cd2ce9303ace791855923fd20", size = 40695446 },
+ { url = "https://files.pythonhosted.org/packages/f1/ca/ae10fba419a6e94329707487835ec721f5a95f3ac9168500bcf7aa3813c7/pyarrow-20.0.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:a5704f29a74b81673d266e5ec1fe376f060627c2e42c5c7651288ed4b0db29e9", size = 42278528 },
+ { url = "https://files.pythonhosted.org/packages/7a/a6/aba40a2bf01b5d00cf9cd16d427a5da1fad0fb69b514ce8c8292ab80e968/pyarrow-20.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:00138f79ee1b5aca81e2bdedb91e3739b987245e11fa3c826f9e57c5d102fb75", size = 42918162 },
+ { url = "https://files.pythonhosted.org/packages/93/6b/98b39650cd64f32bf2ec6d627a9bd24fcb3e4e6ea1873c5e1ea8a83b1a18/pyarrow-20.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:f2d67ac28f57a362f1a2c1e6fa98bfe2f03230f7e15927aecd067433b1e70ce8", size = 44550319 },
+ { url = "https://files.pythonhosted.org/packages/ab/32/340238be1eb5037e7b5de7e640ee22334417239bc347eadefaf8c373936d/pyarrow-20.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:4a8b029a07956b8d7bd742ffca25374dd3f634b35e46cc7a7c3fa4c75b297191", size = 25770759 },
+ { url = "https://files.pythonhosted.org/packages/47/a2/b7930824181ceadd0c63c1042d01fa4ef63eee233934826a7a2a9af6e463/pyarrow-20.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:24ca380585444cb2a31324c546a9a56abbe87e26069189e14bdba19c86c049f0", size = 30856035 },
+ { url = "https://files.pythonhosted.org/packages/9b/18/c765770227d7f5bdfa8a69f64b49194352325c66a5c3bb5e332dfd5867d9/pyarrow-20.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:95b330059ddfdc591a3225f2d272123be26c8fa76e8c9ee1a77aad507361cfdb", size = 32309552 },
+ { url = "https://files.pythonhosted.org/packages/44/fb/dfb2dfdd3e488bb14f822d7335653092dde150cffc2da97de6e7500681f9/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f0fb1041267e9968c6d0d2ce3ff92e3928b243e2b6d11eeb84d9ac547308232", size = 41334704 },
+ { url = "https://files.pythonhosted.org/packages/58/0d/08a95878d38808051a953e887332d4a76bc06c6ee04351918ee1155407eb/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8ff87cc837601532cc8242d2f7e09b4e02404de1b797aee747dd4ba4bd6313f", size = 42399836 },
+ { url = "https://files.pythonhosted.org/packages/f3/cd/efa271234dfe38f0271561086eedcad7bc0f2ddd1efba423916ff0883684/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7a3a5dcf54286e6141d5114522cf31dd67a9e7c9133d150799f30ee302a7a1ab", size = 40711789 },
+ { url = "https://files.pythonhosted.org/packages/46/1f/7f02009bc7fc8955c391defee5348f510e589a020e4b40ca05edcb847854/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a6ad3e7758ecf559900261a4df985662df54fb7fdb55e8e3b3aa99b23d526b62", size = 42301124 },
+ { url = "https://files.pythonhosted.org/packages/4f/92/692c562be4504c262089e86757a9048739fe1acb4024f92d39615e7bab3f/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6bb830757103a6cb300a04610e08d9636f0cd223d32f388418ea893a3e655f1c", size = 42916060 },
+ { url = "https://files.pythonhosted.org/packages/a4/ec/9f5c7e7c828d8e0a3c7ef50ee62eca38a7de2fa6eb1b8fa43685c9414fef/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96e37f0766ecb4514a899d9a3554fadda770fb57ddf42b63d80f14bc20aa7db3", size = 44547640 },
+ { url = "https://files.pythonhosted.org/packages/54/96/46613131b4727f10fd2ffa6d0d6f02efcc09a0e7374eff3b5771548aa95b/pyarrow-20.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:3346babb516f4b6fd790da99b98bed9708e3f02e734c84971faccb20736848dc", size = 25781491 },
+ { url = "https://files.pythonhosted.org/packages/a1/d6/0c10e0d54f6c13eb464ee9b67a68b8c71bcf2f67760ef5b6fbcddd2ab05f/pyarrow-20.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:75a51a5b0eef32727a247707d4755322cb970be7e935172b6a3a9f9ae98404ba", size = 30815067 },
+ { url = "https://files.pythonhosted.org/packages/7e/e2/04e9874abe4094a06fd8b0cbb0f1312d8dd7d707f144c2ec1e5e8f452ffa/pyarrow-20.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:211d5e84cecc640c7a3ab900f930aaff5cd2702177e0d562d426fb7c4f737781", size = 32297128 },
+ { url = "https://files.pythonhosted.org/packages/31/fd/c565e5dcc906a3b471a83273039cb75cb79aad4a2d4a12f76cc5ae90a4b8/pyarrow-20.0.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4ba3cf4182828be7a896cbd232aa8dd6a31bd1f9e32776cc3796c012855e1199", size = 41334890 },
+ { url = "https://files.pythonhosted.org/packages/af/a9/3bdd799e2c9b20c1ea6dc6fa8e83f29480a97711cf806e823f808c2316ac/pyarrow-20.0.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c3a01f313ffe27ac4126f4c2e5ea0f36a5fc6ab51f8726cf41fee4b256680bd", size = 42421775 },
+ { url = "https://files.pythonhosted.org/packages/10/f7/da98ccd86354c332f593218101ae56568d5dcedb460e342000bd89c49cc1/pyarrow-20.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:a2791f69ad72addd33510fec7bb14ee06c2a448e06b649e264c094c5b5f7ce28", size = 40687231 },
+ { url = "https://files.pythonhosted.org/packages/bb/1b/2168d6050e52ff1e6cefc61d600723870bf569cbf41d13db939c8cf97a16/pyarrow-20.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:4250e28a22302ce8692d3a0e8ec9d9dde54ec00d237cff4dfa9c1fbf79e472a8", size = 42295639 },
+ { url = "https://files.pythonhosted.org/packages/b2/66/2d976c0c7158fd25591c8ca55aee026e6d5745a021915a1835578707feb3/pyarrow-20.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:89e030dc58fc760e4010148e6ff164d2f44441490280ef1e97a542375e41058e", size = 42908549 },
+ { url = "https://files.pythonhosted.org/packages/31/a9/dfb999c2fc6911201dcbf348247f9cc382a8990f9ab45c12eabfd7243a38/pyarrow-20.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6102b4864d77102dbbb72965618e204e550135a940c2534711d5ffa787df2a5a", size = 44557216 },
+ { url = "https://files.pythonhosted.org/packages/a0/8e/9adee63dfa3911be2382fb4d92e4b2e7d82610f9d9f668493bebaa2af50f/pyarrow-20.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:96d6a0a37d9c98be08f5ed6a10831d88d52cac7b13f5287f1e0f625a0de8062b", size = 25660496 },
+ { url = "https://files.pythonhosted.org/packages/9b/aa/daa413b81446d20d4dad2944110dcf4cf4f4179ef7f685dd5a6d7570dc8e/pyarrow-20.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:a15532e77b94c61efadde86d10957950392999503b3616b2ffcef7621a002893", size = 30798501 },
+ { url = "https://files.pythonhosted.org/packages/ff/75/2303d1caa410925de902d32ac215dc80a7ce7dd8dfe95358c165f2adf107/pyarrow-20.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dd43f58037443af715f34f1322c782ec463a3c8a94a85fdb2d987ceb5658e061", size = 32277895 },
+ { url = "https://files.pythonhosted.org/packages/92/41/fe18c7c0b38b20811b73d1bdd54b1fccba0dab0e51d2048878042d84afa8/pyarrow-20.0.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa0d288143a8585806e3cc7c39566407aab646fb9ece164609dac1cfff45f6ae", size = 41327322 },
+ { url = "https://files.pythonhosted.org/packages/da/ab/7dbf3d11db67c72dbf36ae63dcbc9f30b866c153b3a22ef728523943eee6/pyarrow-20.0.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b6953f0114f8d6f3d905d98e987d0924dabce59c3cda380bdfaa25a6201563b4", size = 42411441 },
+ { url = "https://files.pythonhosted.org/packages/90/c3/0c7da7b6dac863af75b64e2f827e4742161128c350bfe7955b426484e226/pyarrow-20.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:991f85b48a8a5e839b2128590ce07611fae48a904cae6cab1f089c5955b57eb5", size = 40677027 },
+ { url = "https://files.pythonhosted.org/packages/be/27/43a47fa0ff9053ab5203bb3faeec435d43c0d8bfa40179bfd076cdbd4e1c/pyarrow-20.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:97c8dc984ed09cb07d618d57d8d4b67a5100a30c3818c2fb0b04599f0da2de7b", size = 42281473 },
+ { url = "https://files.pythonhosted.org/packages/bc/0b/d56c63b078876da81bbb9ba695a596eabee9b085555ed12bf6eb3b7cab0e/pyarrow-20.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9b71daf534f4745818f96c214dbc1e6124d7daf059167330b610fc69b6f3d3e3", size = 42893897 },
+ { url = "https://files.pythonhosted.org/packages/92/ac/7d4bd020ba9145f354012838692d48300c1b8fe5634bfda886abcada67ed/pyarrow-20.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e8b88758f9303fa5a83d6c90e176714b2fd3852e776fc2d7e42a22dd6c2fb368", size = 44543847 },
+ { url = "https://files.pythonhosted.org/packages/9d/07/290f4abf9ca702c5df7b47739c1b2c83588641ddfa2cc75e34a301d42e55/pyarrow-20.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:30b3051b7975801c1e1d387e17c588d8ab05ced9b1e14eec57915f79869b5031", size = 25653219 },
+ { url = "https://files.pythonhosted.org/packages/95/df/720bb17704b10bd69dde086e1400b8eefb8f58df3f8ac9cff6c425bf57f1/pyarrow-20.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:ca151afa4f9b7bc45bcc791eb9a89e90a9eb2772767d0b1e5389609c7d03db63", size = 30853957 },
+ { url = "https://files.pythonhosted.org/packages/d9/72/0d5f875efc31baef742ba55a00a25213a19ea64d7176e0fe001c5d8b6e9a/pyarrow-20.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:4680f01ecd86e0dd63e39eb5cd59ef9ff24a9d166db328679e36c108dc993d4c", size = 32247972 },
+ { url = "https://files.pythonhosted.org/packages/d5/bc/e48b4fa544d2eea72f7844180eb77f83f2030b84c8dad860f199f94307ed/pyarrow-20.0.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f4c8534e2ff059765647aa69b75d6543f9fef59e2cd4c6d18015192565d2b70", size = 41256434 },
+ { url = "https://files.pythonhosted.org/packages/c3/01/974043a29874aa2cf4f87fb07fd108828fc7362300265a2a64a94965e35b/pyarrow-20.0.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3e1f8a47f4b4ae4c69c4d702cfbdfe4d41e18e5c7ef6f1bb1c50918c1e81c57b", size = 42353648 },
+ { url = "https://files.pythonhosted.org/packages/68/95/cc0d3634cde9ca69b0e51cbe830d8915ea32dda2157560dda27ff3b3337b/pyarrow-20.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:a1f60dc14658efaa927f8214734f6a01a806d7690be4b3232ba526836d216122", size = 40619853 },
+ { url = "https://files.pythonhosted.org/packages/29/c2/3ad40e07e96a3e74e7ed7cc8285aadfa84eb848a798c98ec0ad009eb6bcc/pyarrow-20.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:204a846dca751428991346976b914d6d2a82ae5b8316a6ed99789ebf976551e6", size = 42241743 },
+ { url = "https://files.pythonhosted.org/packages/eb/cb/65fa110b483339add6a9bc7b6373614166b14e20375d4daa73483755f830/pyarrow-20.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:f3b117b922af5e4c6b9a9115825726cac7d8b1421c37c2b5e24fbacc8930612c", size = 42839441 },
+ { url = "https://files.pythonhosted.org/packages/98/7b/f30b1954589243207d7a0fbc9997401044bf9a033eec78f6cb50da3f304a/pyarrow-20.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e724a3fd23ae5b9c010e7be857f4405ed5e679db5c93e66204db1a69f733936a", size = 44503279 },
+ { url = "https://files.pythonhosted.org/packages/37/40/ad395740cd641869a13bcf60851296c89624662575621968dcfafabaa7f6/pyarrow-20.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:82f1ee5133bd8f49d31be1299dc07f585136679666b502540db854968576faf9", size = 25944982 },
+ { url = "https://files.pythonhosted.org/packages/10/53/421820fa125138c868729b930d4bc487af2c4b01b1c6104818aab7e98f13/pyarrow-20.0.0-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:1bcbe471ef3349be7714261dea28fe280db574f9d0f77eeccc195a2d161fd861", size = 30844702 },
+ { url = "https://files.pythonhosted.org/packages/2e/70/fd75e03312b715e90d928fb91ed8d45c9b0520346e5231b1c69293afd4c7/pyarrow-20.0.0-cp39-cp39-macosx_12_0_x86_64.whl", hash = "sha256:a18a14baef7d7ae49247e75641fd8bcbb39f44ed49a9fc4ec2f65d5031aa3b96", size = 32287180 },
+ { url = "https://files.pythonhosted.org/packages/c4/e3/21e5758e46219fdedf5e6c800574dd9d17e962e80014cfe08d6d475be863/pyarrow-20.0.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cb497649e505dc36542d0e68eca1a3c94ecbe9799cb67b578b55f2441a247fbc", size = 41351968 },
+ { url = "https://files.pythonhosted.org/packages/ac/f5/ed6a4c4b11f9215092a35097a985485bb7d879cb79d93d203494e8604f4e/pyarrow-20.0.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11529a2283cb1f6271d7c23e4a8f9f8b7fd173f7360776b668e509d712a02eec", size = 42415208 },
+ { url = "https://files.pythonhosted.org/packages/44/e5/466a63668ba25788ee8d38d55f853a60469ae7ad1cda343db9f3f45e0b0a/pyarrow-20.0.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:6fc1499ed3b4b57ee4e090e1cea6eb3584793fe3d1b4297bbf53f09b434991a5", size = 40708556 },
+ { url = "https://files.pythonhosted.org/packages/e8/d7/4c4d4e4cf6e53e16a519366dfe9223ee4a7a38e6e28c1c0d372b38ba3fe7/pyarrow-20.0.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:db53390eaf8a4dab4dbd6d93c85c5cf002db24902dbff0ca7d988beb5c9dd15b", size = 42291754 },
+ { url = "https://files.pythonhosted.org/packages/07/d5/79effb32585b7c18897d3047a2163034f3f9c944d12f7b2fd8df6a2edc70/pyarrow-20.0.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:851c6a8260ad387caf82d2bbf54759130534723e37083111d4ed481cb253cc0d", size = 42936483 },
+ { url = "https://files.pythonhosted.org/packages/09/5c/f707603552c058b2e9129732de99a67befb1f13f008cc58856304a62c38b/pyarrow-20.0.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:e22f80b97a271f0a7d9cd07394a7d348f80d3ac63ed7cc38b6d1b696ab3b2619", size = 44558895 },
+ { url = "https://files.pythonhosted.org/packages/26/cc/1eb6a01c1bbc787f596c270c46bcd2273e35154a84afcb1d0cb4cc72457e/pyarrow-20.0.0-cp39-cp39-win_amd64.whl", hash = "sha256:9965a050048ab02409fb7cbbefeedba04d3d67f2cc899eff505cc084345959ca", size = 25785667 },
+]
+
+[[package]]
+name = "pycountry"
+version = "24.6.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/76/57/c389fa68c50590881a75b7883eeb3dc15e9e73a0fdc001cdd45c13290c92/pycountry-24.6.1.tar.gz", hash = "sha256:b61b3faccea67f87d10c1f2b0fc0be714409e8fcdcc1315613174f6466c10221", size = 6043910 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b1/ec/1fb891d8a2660716aadb2143235481d15ed1cbfe3ad669194690b0604492/pycountry-24.6.1-py3-none-any.whl", hash = "sha256:f1a4fb391cd7214f8eefd39556d740adcc233c778a27f8942c8dca351d6ce06f", size = 6335189 },
+]
+
+[[package]]
+name = "pycparser"
+version = "2.22"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1d/b2/31537cf4b1ca988837256c910a668b553fceb8f069bedc4b1c826024b52c/pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6", size = 172736 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", size = 117552 },
+]
+
+[[package]]
+name = "pycryptodomex"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/85/e24bf90972a30b0fcd16c73009add1d7d7cd9140c2498a68252028899e41/pycryptodomex-3.23.0.tar.gz", hash = "sha256:71909758f010c82bc99b0abf4ea12012c98962fbf0583c2164f8b84533c2e4da", size = 4922157 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/00/10edb04777069a42490a38c137099d4b17ba6e36a4e6e28bdc7470e9e853/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:7b37e08e3871efe2187bc1fd9320cc81d87caf19816c648f24443483005ff886", size = 2498764 },
+ { url = "https://files.pythonhosted.org/packages/6b/3f/2872a9c2d3a27eac094f9ceaa5a8a483b774ae69018040ea3240d5b11154/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:91979028227543010d7b2ba2471cf1d1e398b3f183cb105ac584df0c36dac28d", size = 1643012 },
+ { url = "https://files.pythonhosted.org/packages/70/af/774c2e2b4f6570fbf6a4972161adbb183aeeaa1863bde31e8706f123bf92/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b8962204c47464d5c1c4038abeadd4514a133b28748bcd9fa5b6d62e3cec6fa", size = 2187643 },
+ { url = "https://files.pythonhosted.org/packages/de/a3/71065b24cb889d537954cedc3ae5466af00a2cabcff8e29b73be047e9a19/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a33986a0066860f7fcf7c7bd2bc804fa90e434183645595ae7b33d01f3c91ed8", size = 2273762 },
+ { url = "https://files.pythonhosted.org/packages/c9/0b/ff6f43b7fbef4d302c8b981fe58467b8871902cdc3eb28896b52421422cc/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7947ab8d589e3178da3d7cdeabe14f841b391e17046954f2fbcd941705762b5", size = 2313012 },
+ { url = "https://files.pythonhosted.org/packages/02/de/9d4772c0506ab6da10b41159493657105d3f8bb5c53615d19452afc6b315/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c25e30a20e1b426e1f0fa00131c516f16e474204eee1139d1603e132acffc314", size = 2186856 },
+ { url = "https://files.pythonhosted.org/packages/28/ad/8b30efcd6341707a234e5eba5493700a17852ca1ac7a75daa7945fcf6427/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:da4fa650cef02db88c2b98acc5434461e027dce0ae8c22dd5a69013eaf510006", size = 2347523 },
+ { url = "https://files.pythonhosted.org/packages/0f/02/16868e9f655b7670dbb0ac4f2844145cbc42251f916fc35c414ad2359849/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:58b851b9effd0d072d4ca2e4542bf2a4abcf13c82a29fd2c93ce27ee2a2e9462", size = 2272825 },
+ { url = "https://files.pythonhosted.org/packages/ca/18/4ca89ac737230b52ac8ffaca42f9c6f1fd07c81a6cd821e91af79db60632/pycryptodomex-3.23.0-cp313-cp313t-win32.whl", hash = "sha256:a9d446e844f08299236780f2efa9898c818fe7e02f17263866b8550c7d5fb328", size = 1772078 },
+ { url = "https://files.pythonhosted.org/packages/73/34/13e01c322db027682e00986873eca803f11c56ade9ba5bbf3225841ea2d4/pycryptodomex-3.23.0-cp313-cp313t-win_amd64.whl", hash = "sha256:bc65bdd9fc8de7a35a74cab1c898cab391a4add33a8fe740bda00f5976ca4708", size = 1803656 },
+ { url = "https://files.pythonhosted.org/packages/54/68/9504c8796b1805d58f4425002bcca20f12880e6fa4dc2fc9a668705c7a08/pycryptodomex-3.23.0-cp313-cp313t-win_arm64.whl", hash = "sha256:c885da45e70139464f082018ac527fdaad26f1657a99ee13eecdce0f0ca24ab4", size = 1707172 },
+ { url = "https://files.pythonhosted.org/packages/dd/9c/1a8f35daa39784ed8adf93a694e7e5dc15c23c741bbda06e1d45f8979e9e/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:06698f957fe1ab229a99ba2defeeae1c09af185baa909a31a5d1f9d42b1aaed6", size = 2499240 },
+ { url = "https://files.pythonhosted.org/packages/7a/62/f5221a191a97157d240cf6643747558759126c76ee92f29a3f4aee3197a5/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b2c2537863eccef2d41061e82a881dcabb04944c5c06c5aa7110b577cc487545", size = 1644042 },
+ { url = "https://files.pythonhosted.org/packages/8c/fd/5a054543c8988d4ed7b612721d7e78a4b9bf36bc3c5ad45ef45c22d0060e/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:43c446e2ba8df8889e0e16f02211c25b4934898384c1ec1ec04d7889c0333587", size = 2186227 },
+ { url = "https://files.pythonhosted.org/packages/c8/a9/8862616a85cf450d2822dbd4fff1fcaba90877907a6ff5bc2672cafe42f8/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f489c4765093fb60e2edafdf223397bc716491b2b69fe74367b70d6999257a5c", size = 2272578 },
+ { url = "https://files.pythonhosted.org/packages/46/9f/bda9c49a7c1842820de674ab36c79f4fbeeee03f8ff0e4f3546c3889076b/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bdc69d0d3d989a1029df0eed67cc5e8e5d968f3724f4519bd03e0ec68df7543c", size = 2312166 },
+ { url = "https://files.pythonhosted.org/packages/03/cc/870b9bf8ca92866ca0186534801cf8d20554ad2a76ca959538041b7a7cf4/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6bbcb1dd0f646484939e142462d9e532482bc74475cecf9c4903d4e1cd21f003", size = 2185467 },
+ { url = "https://files.pythonhosted.org/packages/96/e3/ce9348236d8e669fea5dd82a90e86be48b9c341210f44e25443162aba187/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_i686.whl", hash = "sha256:8a4fcd42ccb04c31268d1efeecfccfd1249612b4de6374205376b8f280321744", size = 2346104 },
+ { url = "https://files.pythonhosted.org/packages/a5/e9/e869bcee87beb89040263c416a8a50204f7f7a83ac11897646c9e71e0daf/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:55ccbe27f049743a4caf4f4221b166560d3438d0b1e5ab929e07ae1702a4d6fd", size = 2271038 },
+ { url = "https://files.pythonhosted.org/packages/8d/67/09ee8500dd22614af5fbaa51a4aee6e342b5fa8aecf0a6cb9cbf52fa6d45/pycryptodomex-3.23.0-cp37-abi3-win32.whl", hash = "sha256:189afbc87f0b9f158386bf051f720e20fa6145975f1e76369303d0f31d1a8d7c", size = 1771969 },
+ { url = "https://files.pythonhosted.org/packages/69/96/11f36f71a865dd6df03716d33bd07a67e9d20f6b8d39820470b766af323c/pycryptodomex-3.23.0-cp37-abi3-win_amd64.whl", hash = "sha256:52e5ca58c3a0b0bd5e100a9fbc8015059b05cffc6c66ce9d98b4b45e023443b9", size = 1803124 },
+ { url = "https://files.pythonhosted.org/packages/f9/93/45c1cdcbeb182ccd2e144c693eaa097763b08b38cded279f0053ed53c553/pycryptodomex-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:02d87b80778c171445d67e23d1caef279bf4b25c3597050ccd2e13970b57fd51", size = 1707161 },
+ { url = "https://files.pythonhosted.org/packages/f3/b8/3e76d948c3c4ac71335bbe75dac53e154b40b0f8f1f022dfa295257a0c96/pycryptodomex-3.23.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:ebfff755c360d674306e5891c564a274a47953562b42fb74a5c25b8fc1fb1cb5", size = 1627695 },
+ { url = "https://files.pythonhosted.org/packages/6a/cf/80f4297a4820dfdfd1c88cf6c4666a200f204b3488103d027b5edd9176ec/pycryptodomex-3.23.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eca54f4bb349d45afc17e3011ed4264ef1cc9e266699874cdd1349c504e64798", size = 1675772 },
+ { url = "https://files.pythonhosted.org/packages/d1/42/1e969ee0ad19fe3134b0e1b856c39bd0b70d47a4d0e81c2a8b05727394c9/pycryptodomex-3.23.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f2596e643d4365e14d0879dc5aafe6355616c61c2176009270f3048f6d9a61f", size = 1668083 },
+ { url = "https://files.pythonhosted.org/packages/6e/c3/1de4f7631fea8a992a44ba632aa40e0008764c0fb9bf2854b0acf78c2cf2/pycryptodomex-3.23.0-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fdfac7cda115bca3a5abb2f9e43bc2fb66c2b65ab074913643803ca7083a79ea", size = 1706056 },
+ { url = "https://files.pythonhosted.org/packages/f2/5f/af7da8e6f1e42b52f44a24d08b8e4c726207434e2593732d39e7af5e7256/pycryptodomex-3.23.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:14c37aaece158d0ace436f76a7bb19093db3b4deade9797abfc39ec6cd6cc2fe", size = 1806478 },
+ { url = "https://files.pythonhosted.org/packages/e2/eb/022ae689a90f4101847d3f43c2319b3f7f5ed53ba6a49b2c7af7d72c2523/pycryptodomex-3.23.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:7de1e40a41a5d7f1ac42b6569b10bcdded34339950945948529067d8426d2785", size = 1627595 },
+ { url = "https://files.pythonhosted.org/packages/2c/5f/566de54abb78a0a7f4ca7730e8a1fd372509e257d15d9f0f076aa30e73a5/pycryptodomex-3.23.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bffc92138d75664b6d543984db7893a628559b9e78658563b0395e2a5fb47ed9", size = 1675678 },
+ { url = "https://files.pythonhosted.org/packages/9b/e4/8240294e46b1ceb027b432be861b641752486691f675b9f0a4b0495c1cb5/pycryptodomex-3.23.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df027262368334552db2c0ce39706b3fb32022d1dce34673d0f9422df004b96a", size = 1667977 },
+ { url = "https://files.pythonhosted.org/packages/0e/ac/2b8eee86b73811e3d814e429f3aeebf84ca07a5c1912a0a33246bfc4675f/pycryptodomex-3.23.0-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4e79f1aaff5a3a374e92eb462fa9e598585452135012e2945f96874ca6eeb1ff", size = 1705980 },
+ { url = "https://files.pythonhosted.org/packages/37/be/2e75f36f368068d87656a04e07f998fd345a5ba7a3a56fa8c3f80484a506/pycryptodomex-3.23.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:27e13c80ac9a0a1d050ef0a7e0a18cc04c8850101ec891815b6c5a0375e8a245", size = 1806361 },
+]
+
+[[package]]
+name = "pydantic"
+version = "2.11.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "annotated-types" },
+ { name = "pydantic-core" },
+ { name = "typing-extensions" },
+ { name = "typing-inspection" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f0/86/8ce9040065e8f924d642c58e4a344e33163a07f6b57f836d0d734e0ad3fb/pydantic-2.11.5.tar.gz", hash = "sha256:7f853db3d0ce78ce8bbb148c401c2cdd6431b3473c0cdff2755c7690952a7b7a", size = 787102 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b5/69/831ed22b38ff9b4b64b66569f0e5b7b97cf3638346eb95a2147fdb49ad5f/pydantic-2.11.5-py3-none-any.whl", hash = "sha256:f9c26ba06f9747749ca1e5c94d6a85cb84254577553c8785576fd38fa64dc0f7", size = 444229 },
+]
+
+[[package]]
+name = "pydantic-core"
+version = "2.33.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ad/88/5f2260bdfae97aabf98f1778d43f69574390ad787afb646292a638c923d4/pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc", size = 435195 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e5/92/b31726561b5dae176c2d2c2dc43a9c5bfba5d32f96f8b4c0a600dd492447/pydantic_core-2.33.2-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:2b3d326aaef0c0399d9afffeb6367d5e26ddc24d351dbc9c636840ac355dc5d8", size = 2028817 },
+ { url = "https://files.pythonhosted.org/packages/a3/44/3f0b95fafdaca04a483c4e685fe437c6891001bf3ce8b2fded82b9ea3aa1/pydantic_core-2.33.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0e5b2671f05ba48b94cb90ce55d8bdcaaedb8ba00cc5359f6810fc918713983d", size = 1861357 },
+ { url = "https://files.pythonhosted.org/packages/30/97/e8f13b55766234caae05372826e8e4b3b96e7b248be3157f53237682e43c/pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0069c9acc3f3981b9ff4cdfaf088e98d83440a4c7ea1bc07460af3d4dc22e72d", size = 1898011 },
+ { url = "https://files.pythonhosted.org/packages/9b/a3/99c48cf7bafc991cc3ee66fd544c0aae8dc907b752f1dad2d79b1b5a471f/pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d53b22f2032c42eaaf025f7c40c2e3b94568ae077a606f006d206a463bc69572", size = 1982730 },
+ { url = "https://files.pythonhosted.org/packages/de/8e/a5b882ec4307010a840fb8b58bd9bf65d1840c92eae7534c7441709bf54b/pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0405262705a123b7ce9f0b92f123334d67b70fd1f20a9372b907ce1080c7ba02", size = 2136178 },
+ { url = "https://files.pythonhosted.org/packages/e4/bb/71e35fc3ed05af6834e890edb75968e2802fe98778971ab5cba20a162315/pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4b25d91e288e2c4e0662b8038a28c6a07eaac3e196cfc4ff69de4ea3db992a1b", size = 2736462 },
+ { url = "https://files.pythonhosted.org/packages/31/0d/c8f7593e6bc7066289bbc366f2235701dcbebcd1ff0ef8e64f6f239fb47d/pydantic_core-2.33.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6bdfe4b3789761f3bcb4b1ddf33355a71079858958e3a552f16d5af19768fef2", size = 2005652 },
+ { url = "https://files.pythonhosted.org/packages/d2/7a/996d8bd75f3eda405e3dd219ff5ff0a283cd8e34add39d8ef9157e722867/pydantic_core-2.33.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:efec8db3266b76ef9607c2c4c419bdb06bf335ae433b80816089ea7585816f6a", size = 2113306 },
+ { url = "https://files.pythonhosted.org/packages/ff/84/daf2a6fb2db40ffda6578a7e8c5a6e9c8affb251a05c233ae37098118788/pydantic_core-2.33.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:031c57d67ca86902726e0fae2214ce6770bbe2f710dc33063187a68744a5ecac", size = 2073720 },
+ { url = "https://files.pythonhosted.org/packages/77/fb/2258da019f4825128445ae79456a5499c032b55849dbd5bed78c95ccf163/pydantic_core-2.33.2-cp310-cp310-musllinux_1_1_armv7l.whl", hash = "sha256:f8de619080e944347f5f20de29a975c2d815d9ddd8be9b9b7268e2e3ef68605a", size = 2244915 },
+ { url = "https://files.pythonhosted.org/packages/d8/7a/925ff73756031289468326e355b6fa8316960d0d65f8b5d6b3a3e7866de7/pydantic_core-2.33.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:73662edf539e72a9440129f231ed3757faab89630d291b784ca99237fb94db2b", size = 2241884 },
+ { url = "https://files.pythonhosted.org/packages/0b/b0/249ee6d2646f1cdadcb813805fe76265745c4010cf20a8eba7b0e639d9b2/pydantic_core-2.33.2-cp310-cp310-win32.whl", hash = "sha256:0a39979dcbb70998b0e505fb1556a1d550a0781463ce84ebf915ba293ccb7e22", size = 1910496 },
+ { url = "https://files.pythonhosted.org/packages/66/ff/172ba8f12a42d4b552917aa65d1f2328990d3ccfc01d5b7c943ec084299f/pydantic_core-2.33.2-cp310-cp310-win_amd64.whl", hash = "sha256:b0379a2b24882fef529ec3b4987cb5d003b9cda32256024e6fe1586ac45fc640", size = 1955019 },
+ { url = "https://files.pythonhosted.org/packages/3f/8d/71db63483d518cbbf290261a1fc2839d17ff89fce7089e08cad07ccfce67/pydantic_core-2.33.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:4c5b0a576fb381edd6d27f0a85915c6daf2f8138dc5c267a57c08a62900758c7", size = 2028584 },
+ { url = "https://files.pythonhosted.org/packages/24/2f/3cfa7244ae292dd850989f328722d2aef313f74ffc471184dc509e1e4e5a/pydantic_core-2.33.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e799c050df38a639db758c617ec771fd8fb7a5f8eaaa4b27b101f266b216a246", size = 1855071 },
+ { url = "https://files.pythonhosted.org/packages/b3/d3/4ae42d33f5e3f50dd467761304be2fa0a9417fbf09735bc2cce003480f2a/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dc46a01bf8d62f227d5ecee74178ffc448ff4e5197c756331f71efcc66dc980f", size = 1897823 },
+ { url = "https://files.pythonhosted.org/packages/f4/f3/aa5976e8352b7695ff808599794b1fba2a9ae2ee954a3426855935799488/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a144d4f717285c6d9234a66778059f33a89096dfb9b39117663fd8413d582dcc", size = 1983792 },
+ { url = "https://files.pythonhosted.org/packages/d5/7a/cda9b5a23c552037717f2b2a5257e9b2bfe45e687386df9591eff7b46d28/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73cf6373c21bc80b2e0dc88444f41ae60b2f070ed02095754eb5a01df12256de", size = 2136338 },
+ { url = "https://files.pythonhosted.org/packages/2b/9f/b8f9ec8dd1417eb9da784e91e1667d58a2a4a7b7b34cf4af765ef663a7e5/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3dc625f4aa79713512d1976fe9f0bc99f706a9dee21dfd1810b4bbbf228d0e8a", size = 2730998 },
+ { url = "https://files.pythonhosted.org/packages/47/bc/cd720e078576bdb8255d5032c5d63ee5c0bf4b7173dd955185a1d658c456/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:881b21b5549499972441da4758d662aeea93f1923f953e9cbaff14b8b9565aef", size = 2003200 },
+ { url = "https://files.pythonhosted.org/packages/ca/22/3602b895ee2cd29d11a2b349372446ae9727c32e78a94b3d588a40fdf187/pydantic_core-2.33.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bdc25f3681f7b78572699569514036afe3c243bc3059d3942624e936ec93450e", size = 2113890 },
+ { url = "https://files.pythonhosted.org/packages/ff/e6/e3c5908c03cf00d629eb38393a98fccc38ee0ce8ecce32f69fc7d7b558a7/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:fe5b32187cbc0c862ee201ad66c30cf218e5ed468ec8dc1cf49dec66e160cc4d", size = 2073359 },
+ { url = "https://files.pythonhosted.org/packages/12/e7/6a36a07c59ebefc8777d1ffdaf5ae71b06b21952582e4b07eba88a421c79/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:bc7aee6f634a6f4a95676fcb5d6559a2c2a390330098dba5e5a5f28a2e4ada30", size = 2245883 },
+ { url = "https://files.pythonhosted.org/packages/16/3f/59b3187aaa6cc0c1e6616e8045b284de2b6a87b027cce2ffcea073adf1d2/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:235f45e5dbcccf6bd99f9f472858849f73d11120d76ea8707115415f8e5ebebf", size = 2241074 },
+ { url = "https://files.pythonhosted.org/packages/e0/ed/55532bb88f674d5d8f67ab121a2a13c385df382de2a1677f30ad385f7438/pydantic_core-2.33.2-cp311-cp311-win32.whl", hash = "sha256:6368900c2d3ef09b69cb0b913f9f8263b03786e5b2a387706c5afb66800efd51", size = 1910538 },
+ { url = "https://files.pythonhosted.org/packages/fe/1b/25b7cccd4519c0b23c2dd636ad39d381abf113085ce4f7bec2b0dc755eb1/pydantic_core-2.33.2-cp311-cp311-win_amd64.whl", hash = "sha256:1e063337ef9e9820c77acc768546325ebe04ee38b08703244c1309cccc4f1bab", size = 1952909 },
+ { url = "https://files.pythonhosted.org/packages/49/a9/d809358e49126438055884c4366a1f6227f0f84f635a9014e2deb9b9de54/pydantic_core-2.33.2-cp311-cp311-win_arm64.whl", hash = "sha256:6b99022f1d19bc32a4c2a0d544fc9a76e3be90f0b3f4af413f87d38749300e65", size = 1897786 },
+ { url = "https://files.pythonhosted.org/packages/18/8a/2b41c97f554ec8c71f2a8a5f85cb56a8b0956addfe8b0efb5b3d77e8bdc3/pydantic_core-2.33.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a7ec89dc587667f22b6a0b6579c249fca9026ce7c333fc142ba42411fa243cdc", size = 2009000 },
+ { url = "https://files.pythonhosted.org/packages/a1/02/6224312aacb3c8ecbaa959897af57181fb6cf3a3d7917fd44d0f2917e6f2/pydantic_core-2.33.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3c6db6e52c6d70aa0d00d45cdb9b40f0433b96380071ea80b09277dba021ddf7", size = 1847996 },
+ { url = "https://files.pythonhosted.org/packages/d6/46/6dcdf084a523dbe0a0be59d054734b86a981726f221f4562aed313dbcb49/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e61206137cbc65e6d5256e1166f88331d3b6238e082d9f74613b9b765fb9025", size = 1880957 },
+ { url = "https://files.pythonhosted.org/packages/ec/6b/1ec2c03837ac00886ba8160ce041ce4e325b41d06a034adbef11339ae422/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb8c529b2819c37140eb51b914153063d27ed88e3bdc31b71198a198e921e011", size = 1964199 },
+ { url = "https://files.pythonhosted.org/packages/2d/1d/6bf34d6adb9debd9136bd197ca72642203ce9aaaa85cfcbfcf20f9696e83/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c52b02ad8b4e2cf14ca7b3d918f3eb0ee91e63b3167c32591e57c4317e134f8f", size = 2120296 },
+ { url = "https://files.pythonhosted.org/packages/e0/94/2bd0aaf5a591e974b32a9f7123f16637776c304471a0ab33cf263cf5591a/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96081f1605125ba0855dfda83f6f3df5ec90c61195421ba72223de35ccfb2f88", size = 2676109 },
+ { url = "https://files.pythonhosted.org/packages/f9/41/4b043778cf9c4285d59742281a769eac371b9e47e35f98ad321349cc5d61/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f57a69461af2a5fa6e6bbd7a5f60d3b7e6cebb687f55106933188e79ad155c1", size = 2002028 },
+ { url = "https://files.pythonhosted.org/packages/cb/d5/7bb781bf2748ce3d03af04d5c969fa1308880e1dca35a9bd94e1a96a922e/pydantic_core-2.33.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:572c7e6c8bb4774d2ac88929e3d1f12bc45714ae5ee6d9a788a9fb35e60bb04b", size = 2100044 },
+ { url = "https://files.pythonhosted.org/packages/fe/36/def5e53e1eb0ad896785702a5bbfd25eed546cdcf4087ad285021a90ed53/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:db4b41f9bd95fbe5acd76d89920336ba96f03e149097365afe1cb092fceb89a1", size = 2058881 },
+ { url = "https://files.pythonhosted.org/packages/01/6c/57f8d70b2ee57fc3dc8b9610315949837fa8c11d86927b9bb044f8705419/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:fa854f5cf7e33842a892e5c73f45327760bc7bc516339fda888c75ae60edaeb6", size = 2227034 },
+ { url = "https://files.pythonhosted.org/packages/27/b9/9c17f0396a82b3d5cbea4c24d742083422639e7bb1d5bf600e12cb176a13/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:5f483cfb75ff703095c59e365360cb73e00185e01aaea067cd19acffd2ab20ea", size = 2234187 },
+ { url = "https://files.pythonhosted.org/packages/b0/6a/adf5734ffd52bf86d865093ad70b2ce543415e0e356f6cacabbc0d9ad910/pydantic_core-2.33.2-cp312-cp312-win32.whl", hash = "sha256:9cb1da0f5a471435a7bc7e439b8a728e8b61e59784b2af70d7c169f8dd8ae290", size = 1892628 },
+ { url = "https://files.pythonhosted.org/packages/43/e4/5479fecb3606c1368d496a825d8411e126133c41224c1e7238be58b87d7e/pydantic_core-2.33.2-cp312-cp312-win_amd64.whl", hash = "sha256:f941635f2a3d96b2973e867144fde513665c87f13fe0e193c158ac51bfaaa7b2", size = 1955866 },
+ { url = "https://files.pythonhosted.org/packages/0d/24/8b11e8b3e2be9dd82df4b11408a67c61bb4dc4f8e11b5b0fc888b38118b5/pydantic_core-2.33.2-cp312-cp312-win_arm64.whl", hash = "sha256:cca3868ddfaccfbc4bfb1d608e2ccaaebe0ae628e1416aeb9c4d88c001bb45ab", size = 1888894 },
+ { url = "https://files.pythonhosted.org/packages/46/8c/99040727b41f56616573a28771b1bfa08a3d3fe74d3d513f01251f79f172/pydantic_core-2.33.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1082dd3e2d7109ad8b7da48e1d4710c8d06c253cbc4a27c1cff4fbcaa97a9e3f", size = 2015688 },
+ { url = "https://files.pythonhosted.org/packages/3a/cc/5999d1eb705a6cefc31f0b4a90e9f7fc400539b1a1030529700cc1b51838/pydantic_core-2.33.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f517ca031dfc037a9c07e748cefd8d96235088b83b4f4ba8939105d20fa1dcd6", size = 1844808 },
+ { url = "https://files.pythonhosted.org/packages/6f/5e/a0a7b8885c98889a18b6e376f344da1ef323d270b44edf8174d6bce4d622/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a9f2c9dd19656823cb8250b0724ee9c60a82f3cdf68a080979d13092a3b0fef", size = 1885580 },
+ { url = "https://files.pythonhosted.org/packages/3b/2a/953581f343c7d11a304581156618c3f592435523dd9d79865903272c256a/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2b0a451c263b01acebe51895bfb0e1cc842a5c666efe06cdf13846c7418caa9a", size = 1973859 },
+ { url = "https://files.pythonhosted.org/packages/e6/55/f1a813904771c03a3f97f676c62cca0c0a4138654107c1b61f19c644868b/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ea40a64d23faa25e62a70ad163571c0b342b8bf66d5fa612ac0dec4f069d916", size = 2120810 },
+ { url = "https://files.pythonhosted.org/packages/aa/c3/053389835a996e18853ba107a63caae0b9deb4a276c6b472931ea9ae6e48/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0fb2d542b4d66f9470e8065c5469ec676978d625a8b7a363f07d9a501a9cb36a", size = 2676498 },
+ { url = "https://files.pythonhosted.org/packages/eb/3c/f4abd740877a35abade05e437245b192f9d0ffb48bbbbd708df33d3cda37/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fdac5d6ffa1b5a83bca06ffe7583f5576555e6c8b3a91fbd25ea7780f825f7d", size = 2000611 },
+ { url = "https://files.pythonhosted.org/packages/59/a7/63ef2fed1837d1121a894d0ce88439fe3e3b3e48c7543b2a4479eb99c2bd/pydantic_core-2.33.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:04a1a413977ab517154eebb2d326da71638271477d6ad87a769102f7c2488c56", size = 2107924 },
+ { url = "https://files.pythonhosted.org/packages/04/8f/2551964ef045669801675f1cfc3b0d74147f4901c3ffa42be2ddb1f0efc4/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c8e7af2f4e0194c22b5b37205bfb293d166a7344a5b0d0eaccebc376546d77d5", size = 2063196 },
+ { url = "https://files.pythonhosted.org/packages/26/bd/d9602777e77fc6dbb0c7db9ad356e9a985825547dce5ad1d30ee04903918/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:5c92edd15cd58b3c2d34873597a1e20f13094f59cf88068adb18947df5455b4e", size = 2236389 },
+ { url = "https://files.pythonhosted.org/packages/42/db/0e950daa7e2230423ab342ae918a794964b053bec24ba8af013fc7c94846/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:65132b7b4a1c0beded5e057324b7e16e10910c106d43675d9bd87d4f38dde162", size = 2239223 },
+ { url = "https://files.pythonhosted.org/packages/58/4d/4f937099c545a8a17eb52cb67fe0447fd9a373b348ccfa9a87f141eeb00f/pydantic_core-2.33.2-cp313-cp313-win32.whl", hash = "sha256:52fb90784e0a242bb96ec53f42196a17278855b0f31ac7c3cc6f5c1ec4811849", size = 1900473 },
+ { url = "https://files.pythonhosted.org/packages/a0/75/4a0a9bac998d78d889def5e4ef2b065acba8cae8c93696906c3a91f310ca/pydantic_core-2.33.2-cp313-cp313-win_amd64.whl", hash = "sha256:c083a3bdd5a93dfe480f1125926afcdbf2917ae714bdb80b36d34318b2bec5d9", size = 1955269 },
+ { url = "https://files.pythonhosted.org/packages/f9/86/1beda0576969592f1497b4ce8e7bc8cbdf614c352426271b1b10d5f0aa64/pydantic_core-2.33.2-cp313-cp313-win_arm64.whl", hash = "sha256:e80b087132752f6b3d714f041ccf74403799d3b23a72722ea2e6ba2e892555b9", size = 1893921 },
+ { url = "https://files.pythonhosted.org/packages/a4/7d/e09391c2eebeab681df2b74bfe6c43422fffede8dc74187b2b0bf6fd7571/pydantic_core-2.33.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:61c18fba8e5e9db3ab908620af374db0ac1baa69f0f32df4f61ae23f15e586ac", size = 1806162 },
+ { url = "https://files.pythonhosted.org/packages/f1/3d/847b6b1fed9f8ed3bb95a9ad04fbd0b212e832d4f0f50ff4d9ee5a9f15cf/pydantic_core-2.33.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95237e53bb015f67b63c91af7518a62a8660376a6a0db19b89acc77a4d6199f5", size = 1981560 },
+ { url = "https://files.pythonhosted.org/packages/6f/9a/e73262f6c6656262b5fdd723ad90f518f579b7bc8622e43a942eec53c938/pydantic_core-2.33.2-cp313-cp313t-win_amd64.whl", hash = "sha256:c2fc0a768ef76c15ab9238afa6da7f69895bb5d1ee83aeea2e3509af4472d0b9", size = 1935777 },
+ { url = "https://files.pythonhosted.org/packages/53/ea/bbe9095cdd771987d13c82d104a9c8559ae9aec1e29f139e286fd2e9256e/pydantic_core-2.33.2-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:a2b911a5b90e0374d03813674bf0a5fbbb7741570dcd4b4e85a2e48d17def29d", size = 2028677 },
+ { url = "https://files.pythonhosted.org/packages/49/1d/4ac5ed228078737d457a609013e8f7edc64adc37b91d619ea965758369e5/pydantic_core-2.33.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:6fa6dfc3e4d1f734a34710f391ae822e0a8eb8559a85c6979e14e65ee6ba2954", size = 1864735 },
+ { url = "https://files.pythonhosted.org/packages/23/9a/2e70d6388d7cda488ae38f57bc2f7b03ee442fbcf0d75d848304ac7e405b/pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c54c939ee22dc8e2d545da79fc5381f1c020d6d3141d3bd747eab59164dc89fb", size = 1898467 },
+ { url = "https://files.pythonhosted.org/packages/ff/2e/1568934feb43370c1ffb78a77f0baaa5a8b6897513e7a91051af707ffdc4/pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:53a57d2ed685940a504248187d5685e49eb5eef0f696853647bf37c418c538f7", size = 1983041 },
+ { url = "https://files.pythonhosted.org/packages/01/1a/1a1118f38ab64eac2f6269eb8c120ab915be30e387bb561e3af904b12499/pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:09fb9dd6571aacd023fe6aaca316bd01cf60ab27240d7eb39ebd66a3a15293b4", size = 2136503 },
+ { url = "https://files.pythonhosted.org/packages/5c/da/44754d1d7ae0f22d6d3ce6c6b1486fc07ac2c524ed8f6eca636e2e1ee49b/pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0e6116757f7959a712db11f3e9c0a99ade00a5bbedae83cb801985aa154f071b", size = 2736079 },
+ { url = "https://files.pythonhosted.org/packages/4d/98/f43cd89172220ec5aa86654967b22d862146bc4d736b1350b4c41e7c9c03/pydantic_core-2.33.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8d55ab81c57b8ff8548c3e4947f119551253f4e3787a7bbc0b6b3ca47498a9d3", size = 2006508 },
+ { url = "https://files.pythonhosted.org/packages/2b/cc/f77e8e242171d2158309f830f7d5d07e0531b756106f36bc18712dc439df/pydantic_core-2.33.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c20c462aa4434b33a2661701b861604913f912254e441ab8d78d30485736115a", size = 2113693 },
+ { url = "https://files.pythonhosted.org/packages/54/7a/7be6a7bd43e0a47c147ba7fbf124fe8aaf1200bc587da925509641113b2d/pydantic_core-2.33.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:44857c3227d3fb5e753d5fe4a3420d6376fa594b07b621e220cd93703fe21782", size = 2074224 },
+ { url = "https://files.pythonhosted.org/packages/2a/07/31cf8fadffbb03be1cb520850e00a8490c0927ec456e8293cafda0726184/pydantic_core-2.33.2-cp39-cp39-musllinux_1_1_armv7l.whl", hash = "sha256:eb9b459ca4df0e5c87deb59d37377461a538852765293f9e6ee834f0435a93b9", size = 2245403 },
+ { url = "https://files.pythonhosted.org/packages/b6/8d/bbaf4c6721b668d44f01861f297eb01c9b35f612f6b8e14173cb204e6240/pydantic_core-2.33.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9fcd347d2cc5c23b06de6d3b7b8275be558a0c90549495c699e379a80bf8379e", size = 2242331 },
+ { url = "https://files.pythonhosted.org/packages/bb/93/3cc157026bca8f5006250e74515119fcaa6d6858aceee8f67ab6dc548c16/pydantic_core-2.33.2-cp39-cp39-win32.whl", hash = "sha256:83aa99b1285bc8f038941ddf598501a86f1536789740991d7d8756e34f1e74d9", size = 1910571 },
+ { url = "https://files.pythonhosted.org/packages/5b/90/7edc3b2a0d9f0dda8806c04e511a67b0b7a41d2187e2003673a996fb4310/pydantic_core-2.33.2-cp39-cp39-win_amd64.whl", hash = "sha256:f481959862f57f29601ccced557cc2e817bce7533ab8e01a797a48b49c9692b3", size = 1956504 },
+ { url = "https://files.pythonhosted.org/packages/30/68/373d55e58b7e83ce371691f6eaa7175e3a24b956c44628eb25d7da007917/pydantic_core-2.33.2-pp310-pypy310_pp73-macosx_10_12_x86_64.whl", hash = "sha256:5c4aa4e82353f65e548c476b37e64189783aa5384903bfea4f41580f255fddfa", size = 2023982 },
+ { url = "https://files.pythonhosted.org/packages/a4/16/145f54ac08c96a63d8ed6442f9dec17b2773d19920b627b18d4f10a061ea/pydantic_core-2.33.2-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:d946c8bf0d5c24bf4fe333af284c59a19358aa3ec18cb3dc4370080da1e8ad29", size = 1858412 },
+ { url = "https://files.pythonhosted.org/packages/41/b1/c6dc6c3e2de4516c0bb2c46f6a373b91b5660312342a0cf5826e38ad82fa/pydantic_core-2.33.2-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:87b31b6846e361ef83fedb187bb5b4372d0da3f7e28d85415efa92d6125d6e6d", size = 1892749 },
+ { url = "https://files.pythonhosted.org/packages/12/73/8cd57e20afba760b21b742106f9dbdfa6697f1570b189c7457a1af4cd8a0/pydantic_core-2.33.2-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa9d91b338f2df0508606f7009fde642391425189bba6d8c653afd80fd6bb64e", size = 2067527 },
+ { url = "https://files.pythonhosted.org/packages/e3/d5/0bb5d988cc019b3cba4a78f2d4b3854427fc47ee8ec8e9eaabf787da239c/pydantic_core-2.33.2-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2058a32994f1fde4ca0480ab9d1e75a0e8c87c22b53a3ae66554f9af78f2fe8c", size = 2108225 },
+ { url = "https://files.pythonhosted.org/packages/f1/c5/00c02d1571913d496aabf146106ad8239dc132485ee22efe08085084ff7c/pydantic_core-2.33.2-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:0e03262ab796d986f978f79c943fc5f620381be7287148b8010b4097f79a39ec", size = 2069490 },
+ { url = "https://files.pythonhosted.org/packages/22/a8/dccc38768274d3ed3a59b5d06f59ccb845778687652daa71df0cab4040d7/pydantic_core-2.33.2-pp310-pypy310_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:1a8695a8d00c73e50bff9dfda4d540b7dee29ff9b8053e38380426a85ef10052", size = 2237525 },
+ { url = "https://files.pythonhosted.org/packages/d4/e7/4f98c0b125dda7cf7ccd14ba936218397b44f50a56dd8c16a3091df116c3/pydantic_core-2.33.2-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:fa754d1850735a0b0e03bcffd9d4b4343eb417e47196e4485d9cca326073a42c", size = 2238446 },
+ { url = "https://files.pythonhosted.org/packages/ce/91/2ec36480fdb0b783cd9ef6795753c1dea13882f2e68e73bce76ae8c21e6a/pydantic_core-2.33.2-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:a11c8d26a50bfab49002947d3d237abe4d9e4b5bdc8846a63537b6488e197808", size = 2066678 },
+ { url = "https://files.pythonhosted.org/packages/7b/27/d4ae6487d73948d6f20dddcd94be4ea43e74349b56eba82e9bdee2d7494c/pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:dd14041875d09cc0f9308e37a6f8b65f5585cf2598a53aa0123df8b129d481f8", size = 2025200 },
+ { url = "https://files.pythonhosted.org/packages/f1/b8/b3cb95375f05d33801024079b9392a5ab45267a63400bf1866e7ce0f0de4/pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d87c561733f66531dced0da6e864f44ebf89a8fba55f31407b00c2f7f9449593", size = 1859123 },
+ { url = "https://files.pythonhosted.org/packages/05/bc/0d0b5adeda59a261cd30a1235a445bf55c7e46ae44aea28f7bd6ed46e091/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2f82865531efd18d6e07a04a17331af02cb7a651583c418df8266f17a63c6612", size = 1892852 },
+ { url = "https://files.pythonhosted.org/packages/3e/11/d37bdebbda2e449cb3f519f6ce950927b56d62f0b84fd9cb9e372a26a3d5/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bfb5112df54209d820d7bf9317c7a6c9025ea52e49f46b6a2060104bba37de7", size = 2067484 },
+ { url = "https://files.pythonhosted.org/packages/8c/55/1f95f0a05ce72ecb02a8a8a1c3be0579bbc29b1d5ab68f1378b7bebc5057/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:64632ff9d614e5eecfb495796ad51b0ed98c453e447a76bcbeeb69615079fc7e", size = 2108896 },
+ { url = "https://files.pythonhosted.org/packages/53/89/2b2de6c81fa131f423246a9109d7b2a375e83968ad0800d6e57d0574629b/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:f889f7a40498cc077332c7ab6b4608d296d852182211787d4f3ee377aaae66e8", size = 2069475 },
+ { url = "https://files.pythonhosted.org/packages/b8/e9/1f7efbe20d0b2b10f6718944b5d8ece9152390904f29a78e68d4e7961159/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:de4b83bb311557e439b9e186f733f6c645b9417c84e2eb8203f3f820a4b988bf", size = 2239013 },
+ { url = "https://files.pythonhosted.org/packages/3c/b2/5309c905a93811524a49b4e031e9851a6b00ff0fb668794472ea7746b448/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:82f68293f055f51b51ea42fafc74b6aad03e70e191799430b90c13d643059ebb", size = 2238715 },
+ { url = "https://files.pythonhosted.org/packages/32/56/8a7ca5d2cd2cda1d245d34b1c9a942920a718082ae8e54e5f3e5a58b7add/pydantic_core-2.33.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:329467cecfb529c925cf2bbd4d60d2c509bc2fb52a20c1045bf09bb70971a9c1", size = 2066757 },
+ { url = "https://files.pythonhosted.org/packages/08/98/dbf3fdfabaf81cda5622154fda78ea9965ac467e3239078e0dcd6df159e7/pydantic_core-2.33.2-pp39-pypy39_pp73-macosx_10_12_x86_64.whl", hash = "sha256:87acbfcf8e90ca885206e98359d7dca4bcbb35abdc0ff66672a293e1d7a19101", size = 2024034 },
+ { url = "https://files.pythonhosted.org/packages/8d/99/7810aa9256e7f2ccd492590f86b79d370df1e9292f1f80b000b6a75bd2fb/pydantic_core-2.33.2-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:7f92c15cd1e97d4b12acd1cc9004fa092578acfa57b67ad5e43a197175d01a64", size = 1858578 },
+ { url = "https://files.pythonhosted.org/packages/d8/60/bc06fa9027c7006cc6dd21e48dbf39076dc39d9abbaf718a1604973a9670/pydantic_core-2.33.2-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3f26877a748dc4251cfcfda9dfb5f13fcb034f5308388066bcfe9031b63ae7d", size = 1892858 },
+ { url = "https://files.pythonhosted.org/packages/f2/40/9d03997d9518816c68b4dfccb88969756b9146031b61cd37f781c74c9b6a/pydantic_core-2.33.2-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dac89aea9af8cd672fa7b510e7b8c33b0bba9a43186680550ccf23020f32d535", size = 2068498 },
+ { url = "https://files.pythonhosted.org/packages/d8/62/d490198d05d2d86672dc269f52579cad7261ced64c2df213d5c16e0aecb1/pydantic_core-2.33.2-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:970919794d126ba8645f3837ab6046fb4e72bbc057b3709144066204c19a455d", size = 2108428 },
+ { url = "https://files.pythonhosted.org/packages/9a/ec/4cd215534fd10b8549015f12ea650a1a973da20ce46430b68fc3185573e8/pydantic_core-2.33.2-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:3eb3fe62804e8f859c49ed20a8451342de53ed764150cb14ca71357c765dc2a6", size = 2069854 },
+ { url = "https://files.pythonhosted.org/packages/1a/1a/abbd63d47e1d9b0d632fee6bb15785d0889c8a6e0a6c3b5a8e28ac1ec5d2/pydantic_core-2.33.2-pp39-pypy39_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:3abcd9392a36025e3bd55f9bd38d908bd17962cc49bc6da8e7e96285336e2bca", size = 2237859 },
+ { url = "https://files.pythonhosted.org/packages/80/1c/fa883643429908b1c90598fd2642af8839efd1d835b65af1f75fba4d94fe/pydantic_core-2.33.2-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:3a1c81334778f9e3af2f8aeb7a960736e5cab1dfebfb26aabca09afd2906c039", size = 2239059 },
+ { url = "https://files.pythonhosted.org/packages/d4/29/3cade8a924a61f60ccfa10842f75eb12787e1440e2b8660ceffeb26685e7/pydantic_core-2.33.2-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:2807668ba86cb38c6817ad9bc66215ab8584d1d304030ce4f0887336f28a5e27", size = 2066661 },
+]
+
+[[package]]
+name = "pygments"
+version = "2.19.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7c/2d/c3338d48ea6cc0feb8446d8e6937e1408088a72a39937982cc6111d17f84/pygments-2.19.1.tar.gz", hash = "sha256:61c16d2a8576dc0649d9f39e089b5f02bcd27fba10d8fb4dcc28173f7a45151f", size = 4968581 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8a/0b/9fcc47d19c48b59121088dd6da2488a49d5f72dacf8262e2790a1d2c7d15/pygments-2.19.1-py3-none-any.whl", hash = "sha256:9ea1544ad55cecf4b8242fab6dd35a93bbce657034b0611ee383099054ab6d8c", size = 1225293 },
+]
+
+[[package]]
+name = "pynvml"
+version = "12.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-ml-py" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/26/6f/6b5880ed0239e85b9a39aed103b65b2ef81425beef9f45e5c035bf008330/pynvml-12.0.0.tar.gz", hash = "sha256:299ce2451a6a17e6822d6faee750103e25b415f06f59abb8db65d30f794166f5", size = 33636 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ed/df/f7cf07a65a96dd11d71f346f9c2863accdd4784da83af7181b067d556cbc/pynvml-12.0.0-py3-none-any.whl", hash = "sha256:fdff84b62a27dbe98e08e1a647eb77342bef1aebe0878bcd15e99a83fcbecb9e", size = 26560 },
+]
+
+[[package]]
+name = "pyparsing"
+version = "3.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bb/22/f1129e69d94ffff626bdb5c835506b3a5b4f3d070f17ea295e12c2c6f60f/pyparsing-3.2.3.tar.gz", hash = "sha256:b9c13f1ab8b3b542f72e28f634bad4de758ab3ce4546e4301970ad6fa77c38be", size = 1088608 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/05/e7/df2285f3d08fee213f2d041540fa4fc9ca6c2d44cf36d3a035bf2a8d2bcc/pyparsing-3.2.3-py3-none-any.whl", hash = "sha256:a749938e02d6fd0b59b356ca504a24982314bb090c383e3cf201c95ef7e2bfcf", size = 111120 },
+]
+
+[[package]]
+name = "pypdf"
+version = "5.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7b/42/fbc37af367b20fa6c53da81b1780025f6046a0fac8cbf0663a17e743b033/pypdf-5.7.0.tar.gz", hash = "sha256:68c92f2e1aae878bab1150e74447f31ab3848b1c0a6f8becae9f0b1904460b6f", size = 5026120 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/73/9f/78d096ef795a813fa0e1cb9b33fa574b205f2b563d9c1e9366c854cf0364/pypdf-5.7.0-py3-none-any.whl", hash = "sha256:203379453439f5b68b7a1cd43cdf4c5f7a02b84810cefa7f93a47b350aaaba48", size = 305524 },
+]
+
+[[package]]
+name = "pypdf2"
+version = "3.0.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9f/bb/18dc3062d37db6c491392007dfd1a7f524bb95886eb956569ac38a23a784/PyPDF2-3.0.1.tar.gz", hash = "sha256:a74408f69ba6271f71b9352ef4ed03dc53a31aa404d29b5d31f53bfecfee1440", size = 227419 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8e/5e/c86a5643653825d3c913719e788e41386bee415c2b87b4f955432f2de6b2/pypdf2-3.0.1-py3-none-any.whl", hash = "sha256:d16e4205cfee272fbdc0568b68d82be796540b1537508cef59388f839c191928", size = 232572 },
+]
+
+[[package]]
+name = "pytest"
+version = "8.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
+ { name = "iniconfig" },
+ { name = "packaging" },
+ { name = "pluggy" },
+ { name = "pygments" },
+ { name = "tomli", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fb/aa/405082ce2749be5398045152251ac69c0f3578c7077efc53431303af97ce/pytest-8.4.0.tar.gz", hash = "sha256:14d920b48472ea0dbf68e45b96cd1ffda4705f33307dcc86c676c1b5104838a6", size = 1515232 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2f/de/afa024cbe022b1b318a3d224125aa24939e99b4ff6f22e0ba639a2eaee47/pytest-8.4.0-py3-none-any.whl", hash = "sha256:f40f825768ad76c0977cbacdf1fd37c6f7a468e460ea6a0636078f8972d4517e", size = 363797 },
+]
+
+[[package]]
+name = "pytest-cov"
+version = "6.2.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "coverage", extra = ["toml"] },
+ { name = "pluggy" },
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/18/99/668cade231f434aaa59bbfbf49469068d2ddd945000621d3d165d2e7dd7b/pytest_cov-6.2.1.tar.gz", hash = "sha256:25cc6cc0a5358204b8108ecedc51a9b57b34cc6b8c967cc2c01a4e00d8a67da2", size = 69432 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bc/16/4ea354101abb1287856baa4af2732be351c7bee728065aed451b678153fd/pytest_cov-6.2.1-py3-none-any.whl", hash = "sha256:f5bc4c23f42f1cdd23c70b1dab1bbaef4fc505ba950d53e0081d0730dd7e86d5", size = 24644 },
+]
+
+[[package]]
+name = "python-dateutil"
+version = "2.9.0.post0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892 },
+]
+
+[[package]]
+name = "python-dotenv"
+version = "1.1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/88/2c/7bb1416c5620485aa793f2de31d3df393d3686aa8a8506d11e10e13c5baf/python_dotenv-1.1.0.tar.gz", hash = "sha256:41f90bc6f5f177fb41f53e87666db362025010eb28f60a01c9143bfa33a2b2d5", size = 39920 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1e/18/98a99ad95133c6a6e2005fe89faedf294a748bd5dc803008059409ac9b1e/python_dotenv-1.1.0-py3-none-any.whl", hash = "sha256:d7c01d9e2293916c18baf562d95698754b0dbbb5e74d457c45d4f6561fb9d55d", size = 20256 },
+]
+
+[[package]]
+name = "python-multipart"
+version = "0.0.20"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f3/87/f44d7c9f274c7ee665a29b885ec97089ec5dc034c7f3fafa03da9e39a09e/python_multipart-0.0.20.tar.gz", hash = "sha256:8dd0cab45b8e23064ae09147625994d090fa46f5b0d1e13af944c331a7fa9d13", size = 37158 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/45/58/38b5afbc1a800eeea951b9285d3912613f2603bdf897a4ab0f4bd7f405fc/python_multipart-0.0.20-py3-none-any.whl", hash = "sha256:8a62d3a8335e06589fe01f2a3e178cdcc632f3fbe0d492ad9ee0ec35aab1f104", size = 24546 },
+]
+
+[[package]]
+name = "pytz"
+version = "2025.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f8/bf/abbd3cdfb8fbc7fb3d4d38d320f2441b1e7cbe29be4f23797b4a2b5d8aac/pytz-2025.2.tar.gz", hash = "sha256:360b9e3dbb49a209c21ad61809c7fb453643e048b38924c765813546746e81c3", size = 320884 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/81/c4/34e93fe5f5429d7570ec1fa436f1986fb1f00c3e0f43a589fe2bbcd22c3f/pytz-2025.2-py2.py3-none-any.whl", hash = "sha256:5ddf76296dd8c44c26eb8f4b6f35488f3ccbf6fbbd7adee0b7262d43f0ec2f00", size = 509225 },
+]
+
+[[package]]
+name = "pywin32"
+version = "310"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/95/da/a5f38fffbba2fb99aa4aa905480ac4b8e83ca486659ac8c95bce47fb5276/pywin32-310-cp310-cp310-win32.whl", hash = "sha256:6dd97011efc8bf51d6793a82292419eba2c71cf8e7250cfac03bba284454abc1", size = 8848240 },
+ { url = "https://files.pythonhosted.org/packages/aa/fe/d873a773324fa565619ba555a82c9dabd677301720f3660a731a5d07e49a/pywin32-310-cp310-cp310-win_amd64.whl", hash = "sha256:c3e78706e4229b915a0821941a84e7ef420bf2b77e08c9dae3c76fd03fd2ae3d", size = 9601854 },
+ { url = "https://files.pythonhosted.org/packages/3c/84/1a8e3d7a15490d28a5d816efa229ecb4999cdc51a7c30dd8914f669093b8/pywin32-310-cp310-cp310-win_arm64.whl", hash = "sha256:33babed0cf0c92a6f94cc6cc13546ab24ee13e3e800e61ed87609ab91e4c8213", size = 8522963 },
+ { url = "https://files.pythonhosted.org/packages/f7/b1/68aa2986129fb1011dabbe95f0136f44509afaf072b12b8f815905a39f33/pywin32-310-cp311-cp311-win32.whl", hash = "sha256:1e765f9564e83011a63321bb9d27ec456a0ed90d3732c4b2e312b855365ed8bd", size = 8784284 },
+ { url = "https://files.pythonhosted.org/packages/b3/bd/d1592635992dd8db5bb8ace0551bc3a769de1ac8850200cfa517e72739fb/pywin32-310-cp311-cp311-win_amd64.whl", hash = "sha256:126298077a9d7c95c53823934f000599f66ec9296b09167810eb24875f32689c", size = 9520748 },
+ { url = "https://files.pythonhosted.org/packages/90/b1/ac8b1ffce6603849eb45a91cf126c0fa5431f186c2e768bf56889c46f51c/pywin32-310-cp311-cp311-win_arm64.whl", hash = "sha256:19ec5fc9b1d51c4350be7bb00760ffce46e6c95eaf2f0b2f1150657b1a43c582", size = 8455941 },
+ { url = "https://files.pythonhosted.org/packages/6b/ec/4fdbe47932f671d6e348474ea35ed94227fb5df56a7c30cbbb42cd396ed0/pywin32-310-cp312-cp312-win32.whl", hash = "sha256:8a75a5cc3893e83a108c05d82198880704c44bbaee4d06e442e471d3c9ea4f3d", size = 8796239 },
+ { url = "https://files.pythonhosted.org/packages/e3/e5/b0627f8bb84e06991bea89ad8153a9e50ace40b2e1195d68e9dff6b03d0f/pywin32-310-cp312-cp312-win_amd64.whl", hash = "sha256:bf5c397c9a9a19a6f62f3fb821fbf36cac08f03770056711f765ec1503972060", size = 9503839 },
+ { url = "https://files.pythonhosted.org/packages/1f/32/9ccf53748df72301a89713936645a664ec001abd35ecc8578beda593d37d/pywin32-310-cp312-cp312-win_arm64.whl", hash = "sha256:2349cc906eae872d0663d4d6290d13b90621eaf78964bb1578632ff20e152966", size = 8459470 },
+ { url = "https://files.pythonhosted.org/packages/1c/09/9c1b978ffc4ae53999e89c19c77ba882d9fce476729f23ef55211ea1c034/pywin32-310-cp313-cp313-win32.whl", hash = "sha256:5d241a659c496ada3253cd01cfaa779b048e90ce4b2b38cd44168ad555ce74ab", size = 8794384 },
+ { url = "https://files.pythonhosted.org/packages/45/3c/b4640f740ffebadd5d34df35fecba0e1cfef8fde9f3e594df91c28ad9b50/pywin32-310-cp313-cp313-win_amd64.whl", hash = "sha256:667827eb3a90208ddbdcc9e860c81bde63a135710e21e4cb3348968e4bd5249e", size = 9503039 },
+ { url = "https://files.pythonhosted.org/packages/b4/f4/f785020090fb050e7fb6d34b780f2231f302609dc964672f72bfaeb59a28/pywin32-310-cp313-cp313-win_arm64.whl", hash = "sha256:e308f831de771482b7cf692a1f308f8fca701b2d8f9dde6cc440c7da17e47b33", size = 8458152 },
+ { url = "https://files.pythonhosted.org/packages/a2/cd/d09d434630edb6a0c44ad5079611279a67530296cfe0451e003de7f449ff/pywin32-310-cp39-cp39-win32.whl", hash = "sha256:851c8d927af0d879221e616ae1f66145253537bbdd321a77e8ef701b443a9a1a", size = 8848099 },
+ { url = "https://files.pythonhosted.org/packages/93/ff/2a8c10315ffbdee7b3883ac0d1667e267ca8b3f6f640d81d43b87a82c0c7/pywin32-310-cp39-cp39-win_amd64.whl", hash = "sha256:96867217335559ac619f00ad70e513c0fcf84b8a3af9fc2bba3b59b97da70475", size = 9602031 },
+]
+
+[[package]]
+name = "pyyaml"
+version = "6.0.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9b/95/a3fac87cb7158e231b5a6012e438c647e1a87f09f8e0d123acec8ab8bf71/PyYAML-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086", size = 184199 },
+ { url = "https://files.pythonhosted.org/packages/c7/7a/68bd47624dab8fd4afbfd3c48e3b79efe09098ae941de5b58abcbadff5cb/PyYAML-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf", size = 171758 },
+ { url = "https://files.pythonhosted.org/packages/49/ee/14c54df452143b9ee9f0f29074d7ca5516a36edb0b4cc40c3f280131656f/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8824b5a04a04a047e72eea5cec3bc266db09e35de6bdfe34c9436ac5ee27d237", size = 718463 },
+ { url = "https://files.pythonhosted.org/packages/4d/61/de363a97476e766574650d742205be468921a7b532aa2499fcd886b62530/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7c36280e6fb8385e520936c3cb3b8042851904eba0e58d277dca80a5cfed590b", size = 719280 },
+ { url = "https://files.pythonhosted.org/packages/6b/4e/1523cb902fd98355e2e9ea5e5eb237cbc5f3ad5f3075fa65087aa0ecb669/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ec031d5d2feb36d1d1a24380e4db6d43695f3748343d99434e6f5f9156aaa2ed", size = 751239 },
+ { url = "https://files.pythonhosted.org/packages/b7/33/5504b3a9a4464893c32f118a9cc045190a91637b119a9c881da1cf6b7a72/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:936d68689298c36b53b29f23c6dbb74de12b4ac12ca6cfe0e047bedceea56180", size = 695802 },
+ { url = "https://files.pythonhosted.org/packages/5c/20/8347dcabd41ef3a3cdc4f7b7a2aff3d06598c8779faa189cdbf878b626a4/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:23502f431948090f597378482b4812b0caae32c22213aecf3b55325e049a6c68", size = 720527 },
+ { url = "https://files.pythonhosted.org/packages/be/aa/5afe99233fb360d0ff37377145a949ae258aaab831bde4792b32650a4378/PyYAML-6.0.2-cp310-cp310-win32.whl", hash = "sha256:2e99c6826ffa974fe6e27cdb5ed0021786b03fc98e5ee3c5bfe1fd5015f42b99", size = 144052 },
+ { url = "https://files.pythonhosted.org/packages/b5/84/0fa4b06f6d6c958d207620fc60005e241ecedceee58931bb20138e1e5776/PyYAML-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:a4d3091415f010369ae4ed1fc6b79def9416358877534caf6a0fdd2146c87a3e", size = 161774 },
+ { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612 },
+ { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040 },
+ { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829 },
+ { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167 },
+ { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952 },
+ { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301 },
+ { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638 },
+ { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850 },
+ { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980 },
+ { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873 },
+ { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302 },
+ { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154 },
+ { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223 },
+ { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542 },
+ { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164 },
+ { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611 },
+ { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591 },
+ { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338 },
+ { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309 },
+ { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679 },
+ { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428 },
+ { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361 },
+ { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523 },
+ { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660 },
+ { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597 },
+ { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527 },
+ { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446 },
+ { url = "https://files.pythonhosted.org/packages/65/d8/b7a1db13636d7fb7d4ff431593c510c8b8fca920ade06ca8ef20015493c5/PyYAML-6.0.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:688ba32a1cffef67fd2e9398a2efebaea461578b0923624778664cc1c914db5d", size = 184777 },
+ { url = "https://files.pythonhosted.org/packages/0a/02/6ec546cd45143fdf9840b2c6be8d875116a64076218b61d68e12548e5839/PyYAML-6.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a8786accb172bd8afb8be14490a16625cbc387036876ab6ba70912730faf8e1f", size = 172318 },
+ { url = "https://files.pythonhosted.org/packages/0e/9a/8cc68be846c972bda34f6c2a93abb644fb2476f4dcc924d52175786932c9/PyYAML-6.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8e03406cac8513435335dbab54c0d385e4a49e4945d2909a581c83647ca0290", size = 720891 },
+ { url = "https://files.pythonhosted.org/packages/e9/6c/6e1b7f40181bc4805e2e07f4abc10a88ce4648e7e95ff1abe4ae4014a9b2/PyYAML-6.0.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f753120cb8181e736c57ef7636e83f31b9c0d1722c516f7e86cf15b7aa57ff12", size = 722614 },
+ { url = "https://files.pythonhosted.org/packages/3d/32/e7bd8535d22ea2874cef6a81021ba019474ace0d13a4819c2a4bce79bd6a/PyYAML-6.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3b1fdb9dc17f5a7677423d508ab4f243a726dea51fa5e70992e59a7411c89d19", size = 737360 },
+ { url = "https://files.pythonhosted.org/packages/d7/12/7322c1e30b9be969670b672573d45479edef72c9a0deac3bb2868f5d7469/PyYAML-6.0.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0b69e4ce7a131fe56b7e4d770c67429700908fc0752af059838b1cfb41960e4e", size = 699006 },
+ { url = "https://files.pythonhosted.org/packages/82/72/04fcad41ca56491995076630c3ec1e834be241664c0c09a64c9a2589b507/PyYAML-6.0.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a9f8c2e67970f13b16084e04f134610fd1d374bf477b17ec1599185cf611d725", size = 723577 },
+ { url = "https://files.pythonhosted.org/packages/ed/5e/46168b1f2757f1fcd442bc3029cd8767d88a98c9c05770d8b420948743bb/PyYAML-6.0.2-cp39-cp39-win32.whl", hash = "sha256:6395c297d42274772abc367baaa79683958044e5d3835486c16da75d2a694631", size = 144593 },
+ { url = "https://files.pythonhosted.org/packages/19/87/5124b1c1f2412bb95c59ec481eaf936cd32f0fe2a7b16b97b81c4c017a6a/PyYAML-6.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:39693e1f8320ae4f43943590b49779ffb98acb81f788220ea932a6b6c51004d8", size = 162312 },
+]
+
+[[package]]
+name = "pyzmq"
+version = "27.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi", marker = "implementation_name == 'pypy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f1/06/50a4e9648b3e8b992bef8eb632e457307553a89d294103213cfd47b3da69/pyzmq-27.0.0.tar.gz", hash = "sha256:b1f08eeb9ce1510e6939b6e5dcd46a17765e2333daae78ecf4606808442e52cf", size = 280478 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9c/09/1681d4b047626d352c083770618ac29655ab1f5c20eee31dc94c000b9b7b/pyzmq-27.0.0-cp310-cp310-macosx_10_15_universal2.whl", hash = "sha256:b973ee650e8f442ce482c1d99ca7ab537c69098d53a3d046676a484fd710c87a", size = 1329291 },
+ { url = "https://files.pythonhosted.org/packages/9d/b2/9c9385225fdd54db9506ed8accbb9ea63ca813ba59d43d7f282a6a16a30b/pyzmq-27.0.0-cp310-cp310-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:661942bc7cd0223d569d808f2e5696d9cc120acc73bf3e88a1f1be7ab648a7e4", size = 905952 },
+ { url = "https://files.pythonhosted.org/packages/41/73/333c72c7ec182cdffe25649e3da1c3b9f3cf1cede63cfdc23d1384d4a601/pyzmq-27.0.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:50360fb2a056ffd16e5f4177eee67f1dd1017332ea53fb095fe7b5bf29c70246", size = 666165 },
+ { url = "https://files.pythonhosted.org/packages/a5/fe/fc7b9c1a50981928e25635a926653cb755364316db59ccd6e79cfb9a0b4f/pyzmq-27.0.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf209a6dc4b420ed32a7093642843cbf8703ed0a7d86c16c0b98af46762ebefb", size = 853755 },
+ { url = "https://files.pythonhosted.org/packages/8c/4c/740ed4b6e8fa160cd19dc5abec8db68f440564b2d5b79c1d697d9862a2f7/pyzmq-27.0.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:c2dace4a7041cca2fba5357a2d7c97c5effdf52f63a1ef252cfa496875a3762d", size = 1654868 },
+ { url = "https://files.pythonhosted.org/packages/97/00/875b2ecfcfc78ab962a59bd384995186818524ea957dc8ad3144611fae12/pyzmq-27.0.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:63af72b2955fc77caf0a77444baa2431fcabb4370219da38e1a9f8d12aaebe28", size = 2033443 },
+ { url = "https://files.pythonhosted.org/packages/60/55/6dd9c470c42d713297c5f2a56f7903dc1ebdb4ab2edda996445c21651900/pyzmq-27.0.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:e8c4adce8e37e75c4215297d7745551b8dcfa5f728f23ce09bf4e678a9399413", size = 1891288 },
+ { url = "https://files.pythonhosted.org/packages/28/5d/54b0ef50d40d7c65a627f4a4b4127024ba9820f2af8acd933a4d30ae192e/pyzmq-27.0.0-cp310-cp310-win32.whl", hash = "sha256:5d5ef4718ecab24f785794e0e7536436698b459bfbc19a1650ef55280119d93b", size = 567936 },
+ { url = "https://files.pythonhosted.org/packages/18/ea/dedca4321de748ca48d3bcdb72274d4d54e8d84ea49088d3de174bd45d88/pyzmq-27.0.0-cp310-cp310-win_amd64.whl", hash = "sha256:e40609380480b3d12c30f841323f42451c755b8fece84235236f5fe5ffca8c1c", size = 628686 },
+ { url = "https://files.pythonhosted.org/packages/d4/a7/fcdeedc306e71e94ac262cba2d02337d885f5cdb7e8efced8e5ffe327808/pyzmq-27.0.0-cp310-cp310-win_arm64.whl", hash = "sha256:6b0397b0be277b46762956f576e04dc06ced265759e8c2ff41a0ee1aa0064198", size = 559039 },
+ { url = "https://files.pythonhosted.org/packages/44/df/84c630654106d9bd9339cdb564aa941ed41b023a0264251d6743766bb50e/pyzmq-27.0.0-cp311-cp311-macosx_10_15_universal2.whl", hash = "sha256:21457825249b2a53834fa969c69713f8b5a79583689387a5e7aed880963ac564", size = 1332718 },
+ { url = "https://files.pythonhosted.org/packages/c1/8e/f6a5461a07654d9840d256476434ae0ff08340bba562a455f231969772cb/pyzmq-27.0.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:1958947983fef513e6e98eff9cb487b60bf14f588dc0e6bf35fa13751d2c8251", size = 908248 },
+ { url = "https://files.pythonhosted.org/packages/7c/93/82863e8d695a9a3ae424b63662733ae204a295a2627d52af2f62c2cd8af9/pyzmq-27.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c0dc628b5493f9a8cd9844b8bee9732ef587ab00002157c9329e4fc0ef4d3afa", size = 668647 },
+ { url = "https://files.pythonhosted.org/packages/f3/85/15278769b348121eacdbfcbd8c4d40f1102f32fa6af5be1ffc032ed684be/pyzmq-27.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f7bbe9e1ed2c8d3da736a15694d87c12493e54cc9dc9790796f0321794bbc91f", size = 856600 },
+ { url = "https://files.pythonhosted.org/packages/d4/af/1c469b3d479bd095edb28e27f12eee10b8f00b356acbefa6aeb14dd295d1/pyzmq-27.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dc1091f59143b471d19eb64f54bae4f54bcf2a466ffb66fe45d94d8d734eb495", size = 1657748 },
+ { url = "https://files.pythonhosted.org/packages/8c/f4/17f965d0ee6380b1d6326da842a50e4b8b9699745161207945f3745e8cb5/pyzmq-27.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7011ade88c8e535cf140f8d1a59428676fbbce7c6e54fefce58bf117aefb6667", size = 2034311 },
+ { url = "https://files.pythonhosted.org/packages/e0/6e/7c391d81fa3149fd759de45d298003de6cfab343fb03e92c099821c448db/pyzmq-27.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2c386339d7e3f064213aede5d03d054b237937fbca6dd2197ac8cf3b25a6b14e", size = 1893630 },
+ { url = "https://files.pythonhosted.org/packages/0e/e0/eaffe7a86f60e556399e224229e7769b717f72fec0706b70ab2c03aa04cb/pyzmq-27.0.0-cp311-cp311-win32.whl", hash = "sha256:0546a720c1f407b2172cb04b6b094a78773491497e3644863cf5c96c42df8cff", size = 567706 },
+ { url = "https://files.pythonhosted.org/packages/c9/05/89354a8cffdcce6e547d48adaaf7be17007fc75572123ff4ca90a4ca04fc/pyzmq-27.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:15f39d50bd6c9091c67315ceb878a4f531957b121d2a05ebd077eb35ddc5efed", size = 630322 },
+ { url = "https://files.pythonhosted.org/packages/fa/07/4ab976d5e1e63976719389cc4f3bfd248a7f5f2bb2ebe727542363c61b5f/pyzmq-27.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c5817641eebb391a2268c27fecd4162448e03538387093cdbd8bf3510c316b38", size = 558435 },
+ { url = "https://files.pythonhosted.org/packages/93/a7/9ad68f55b8834ede477842214feba6a4c786d936c022a67625497aacf61d/pyzmq-27.0.0-cp312-abi3-macosx_10_15_universal2.whl", hash = "sha256:cbabc59dcfaac66655c040dfcb8118f133fb5dde185e5fc152628354c1598e52", size = 1305438 },
+ { url = "https://files.pythonhosted.org/packages/ba/ee/26aa0f98665a22bc90ebe12dced1de5f3eaca05363b717f6fb229b3421b3/pyzmq-27.0.0-cp312-abi3-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:cb0ac5179cba4b2f94f1aa208fbb77b62c4c9bf24dd446278b8b602cf85fcda3", size = 895095 },
+ { url = "https://files.pythonhosted.org/packages/cf/85/c57e7ab216ecd8aa4cc7e3b83b06cc4e9cf45c87b0afc095f10cd5ce87c1/pyzmq-27.0.0-cp312-abi3-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53a48f0228eab6cbf69fde3aa3c03cbe04e50e623ef92ae395fce47ef8a76152", size = 651826 },
+ { url = "https://files.pythonhosted.org/packages/69/9a/9ea7e230feda9400fb0ae0d61d7d6ddda635e718d941c44eeab22a179d34/pyzmq-27.0.0-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:111db5f395e09f7e775f759d598f43cb815fc58e0147623c4816486e1a39dc22", size = 839750 },
+ { url = "https://files.pythonhosted.org/packages/08/66/4cebfbe71f3dfbd417011daca267539f62ed0fbc68105357b68bbb1a25b7/pyzmq-27.0.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c8878011653dcdc27cc2c57e04ff96f0471e797f5c19ac3d7813a245bcb24371", size = 1641357 },
+ { url = "https://files.pythonhosted.org/packages/ac/f6/b0f62578c08d2471c791287149cb8c2aaea414ae98c6e995c7dbe008adfb/pyzmq-27.0.0-cp312-abi3-musllinux_1_2_i686.whl", hash = "sha256:c0ed2c1f335ba55b5fdc964622254917d6b782311c50e138863eda409fbb3b6d", size = 2020281 },
+ { url = "https://files.pythonhosted.org/packages/37/b9/4f670b15c7498495da9159edc374ec09c88a86d9cd5a47d892f69df23450/pyzmq-27.0.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e918d70862d4cfd4b1c187310015646a14e1f5917922ab45b29f28f345eeb6be", size = 1877110 },
+ { url = "https://files.pythonhosted.org/packages/66/31/9dee25c226295b740609f0d46db2fe972b23b6f5cf786360980524a3ba92/pyzmq-27.0.0-cp312-abi3-win32.whl", hash = "sha256:88b4e43cab04c3c0f0d55df3b1eef62df2b629a1a369b5289a58f6fa8b07c4f4", size = 559297 },
+ { url = "https://files.pythonhosted.org/packages/9b/12/52da5509800f7ff2d287b2f2b4e636e7ea0f001181cba6964ff6c1537778/pyzmq-27.0.0-cp312-abi3-win_amd64.whl", hash = "sha256:dce4199bf5f648a902ce37e7b3afa286f305cd2ef7a8b6ec907470ccb6c8b371", size = 619203 },
+ { url = "https://files.pythonhosted.org/packages/93/6d/7f2e53b19d1edb1eb4f09ec7c3a1f945ca0aac272099eab757d15699202b/pyzmq-27.0.0-cp312-abi3-win_arm64.whl", hash = "sha256:56e46bbb85d52c1072b3f809cc1ce77251d560bc036d3a312b96db1afe76db2e", size = 551927 },
+ { url = "https://files.pythonhosted.org/packages/19/62/876b27c4ff777db4ceba1c69ea90d3c825bb4f8d5e7cd987ce5802e33c55/pyzmq-27.0.0-cp313-cp313t-macosx_10_15_universal2.whl", hash = "sha256:c36ad534c0c29b4afa088dc53543c525b23c0797e01b69fef59b1a9c0e38b688", size = 1340826 },
+ { url = "https://files.pythonhosted.org/packages/43/69/58ef8f4f59d3bcd505260c73bee87b008850f45edca40ddaba54273c35f4/pyzmq-27.0.0-cp313-cp313t-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:67855c14173aec36395d7777aaba3cc527b393821f30143fd20b98e1ff31fd38", size = 897283 },
+ { url = "https://files.pythonhosted.org/packages/43/15/93a0d0396700a60475ad3c5d42c5f1c308d3570bc94626b86c71ef9953e0/pyzmq-27.0.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8617c7d43cd8ccdb62aebe984bfed77ca8f036e6c3e46dd3dddda64b10f0ab7a", size = 660567 },
+ { url = "https://files.pythonhosted.org/packages/0e/b3/fe055513e498ca32f64509abae19b9c9eb4d7c829e02bd8997dd51b029eb/pyzmq-27.0.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:67bfbcbd0a04c575e8103a6061d03e393d9f80ffdb9beb3189261e9e9bc5d5e9", size = 847681 },
+ { url = "https://files.pythonhosted.org/packages/b6/4f/ff15300b00b5b602191f3df06bbc8dd4164e805fdd65bb77ffbb9c5facdc/pyzmq-27.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5cd11d46d7b7e5958121b3eaf4cd8638eff3a720ec527692132f05a57f14341d", size = 1650148 },
+ { url = "https://files.pythonhosted.org/packages/c4/6f/84bdfff2a224a6f26a24249a342e5906993c50b0761e311e81b39aef52a7/pyzmq-27.0.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:b801c2e40c5aa6072c2f4876de8dccd100af6d9918d4d0d7aa54a1d982fd4f44", size = 2023768 },
+ { url = "https://files.pythonhosted.org/packages/64/39/dc2db178c26a42228c5ac94a9cc595030458aa64c8d796a7727947afbf55/pyzmq-27.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:20d5cb29e8c5f76a127c75b6e7a77e846bc4b655c373baa098c26a61b7ecd0ef", size = 1885199 },
+ { url = "https://files.pythonhosted.org/packages/c7/21/dae7b06a1f8cdee5d8e7a63d99c5d129c401acc40410bef2cbf42025e26f/pyzmq-27.0.0-cp313-cp313t-win32.whl", hash = "sha256:a20528da85c7ac7a19b7384e8c3f8fa707841fd85afc4ed56eda59d93e3d98ad", size = 575439 },
+ { url = "https://files.pythonhosted.org/packages/eb/bc/1709dc55f0970cf4cb8259e435e6773f9946f41a045c2cb90e870b7072da/pyzmq-27.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:d8229f2efece6a660ee211d74d91dbc2a76b95544d46c74c615e491900dc107f", size = 639933 },
+ { url = "https://files.pythonhosted.org/packages/19/dc/95210fe17e5d7dba89bd663e1d88f50a8003f296284731b09f1d95309a42/pyzmq-27.0.0-cp39-cp39-macosx_10_15_universal2.whl", hash = "sha256:100f6e5052ba42b2533011d34a018a5ace34f8cac67cb03cfa37c8bdae0ca617", size = 1330656 },
+ { url = "https://files.pythonhosted.org/packages/d3/7e/63f742b578316258e03ecb393d35c0964348d80834bdec8a100ed7bb9c91/pyzmq-27.0.0-cp39-cp39-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:bf6c6b061efd00404b9750e2cfbd9507492c8d4b3721ded76cb03786131be2ed", size = 906522 },
+ { url = "https://files.pythonhosted.org/packages/1f/bf/f0b2b67f5a9bfe0fbd0e978a2becd901f802306aa8e29161cb0963094352/pyzmq-27.0.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee05728c0b0b2484a9fc20466fa776fffb65d95f7317a3419985b8c908563861", size = 863545 },
+ { url = "https://files.pythonhosted.org/packages/87/0e/7d90ccd2ef577c8bae7f926acd2011a6d960eea8a068c5fd52b419206960/pyzmq-27.0.0-cp39-cp39-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7cdf07fe0a557b131366f80727ec8ccc4b70d89f1e3f920d94a594d598d754f0", size = 666796 },
+ { url = "https://files.pythonhosted.org/packages/4f/6d/ca8007a313baa73361778773aef210f4902e68f468d1f93b6c8b908fabbd/pyzmq-27.0.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:90252fa2ff3a104219db1f5ced7032a7b5fc82d7c8d2fec2b9a3e6fd4e25576b", size = 1655599 },
+ { url = "https://files.pythonhosted.org/packages/46/de/5cb4f99d6c0dd8f33d729c9ebd49af279586e5ab127e93aa6ef0ecd08c4c/pyzmq-27.0.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:ea6d441c513bf18c578c73c323acf7b4184507fc244762193aa3a871333c9045", size = 2034119 },
+ { url = "https://files.pythonhosted.org/packages/d0/8d/57cc90c8b5f30a97a7e86ec91a3b9822ec7859d477e9c30f531fb78f4a97/pyzmq-27.0.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:ae2b34bcfaae20c064948a4113bf8709eee89fd08317eb293ae4ebd69b4d9740", size = 1891955 },
+ { url = "https://files.pythonhosted.org/packages/24/f5/a7012022573188903802ab75b5314b00e5c629228f3a36fadb421a42ebff/pyzmq-27.0.0-cp39-cp39-win32.whl", hash = "sha256:5b10bd6f008937705cf6e7bf8b6ece5ca055991e3eb130bca8023e20b86aa9a3", size = 568497 },
+ { url = "https://files.pythonhosted.org/packages/9b/f3/2a4b2798275a574801221d94d599ed3e26d19f6378a7364cdfa3bee53944/pyzmq-27.0.0-cp39-cp39-win_amd64.whl", hash = "sha256:00387d12a8af4b24883895f7e6b9495dc20a66027b696536edac35cb988c38f3", size = 629315 },
+ { url = "https://files.pythonhosted.org/packages/da/eb/386a70314f305816142d6e8537f5557e5fd9614c03698d6c88cbd6c41190/pyzmq-27.0.0-cp39-cp39-win_arm64.whl", hash = "sha256:4c19d39c04c29a6619adfeb19e3735c421b3bfee082f320662f52e59c47202ba", size = 559596 },
+ { url = "https://files.pythonhosted.org/packages/09/6f/be6523a7f3821c0b5370912ef02822c028611360e0d206dd945bdbf9eaef/pyzmq-27.0.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:656c1866505a5735d0660b7da6d7147174bbf59d4975fc2b7f09f43c9bc25745", size = 835950 },
+ { url = "https://files.pythonhosted.org/packages/c6/1e/a50fdd5c15018de07ab82a61bc460841be967ee7bbe7abee3b714d66f7ac/pyzmq-27.0.0-pp310-pypy310_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:74175b9e12779382432dd1d1f5960ebe7465d36649b98a06c6b26be24d173fab", size = 799876 },
+ { url = "https://files.pythonhosted.org/packages/88/a1/89eb5b71f5a504f8f887aceb8e1eb3626e00c00aa8085381cdff475440dc/pyzmq-27.0.0-pp310-pypy310_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d8c6de908465697a8708e4d6843a1e884f567962fc61eb1706856545141d0cbb", size = 567400 },
+ { url = "https://files.pythonhosted.org/packages/56/aa/4571dbcff56cfb034bac73fde8294e123c975ce3eea89aff31bf6dc6382b/pyzmq-27.0.0-pp310-pypy310_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c644aaacc01d0df5c7072826df45e67301f191c55f68d7b2916d83a9ddc1b551", size = 747031 },
+ { url = "https://files.pythonhosted.org/packages/46/e0/d25f30fe0991293c5b2f5ef3b070d35fa6d57c0c7428898c3ab4913d0297/pyzmq-27.0.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:10f70c1d9a446a85013a36871a296007f6fe4232b530aa254baf9da3f8328bc0", size = 544726 },
+ { url = "https://files.pythonhosted.org/packages/98/a6/92394373b8dbc1edc9d53c951e8d3989d518185174ee54492ec27711779d/pyzmq-27.0.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd1dc59763effd1576f8368047c9c31468fce0af89d76b5067641137506792ae", size = 835948 },
+ { url = "https://files.pythonhosted.org/packages/56/f3/4dc38d75d9995bfc18773df3e41f2a2ca9b740b06f1a15dbf404077e7588/pyzmq-27.0.0-pp311-pypy311_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:60e8cc82d968174650c1860d7b716366caab9973787a1c060cf8043130f7d0f7", size = 799874 },
+ { url = "https://files.pythonhosted.org/packages/ab/ba/64af397e0f421453dc68e31d5e0784d554bf39013a2de0872056e96e58af/pyzmq-27.0.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:14fe7aaac86e4e93ea779a821967360c781d7ac5115b3f1a171ced77065a0174", size = 567400 },
+ { url = "https://files.pythonhosted.org/packages/63/87/ec956cbe98809270b59a22891d5758edae147a258e658bf3024a8254c855/pyzmq-27.0.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6ad0562d4e6abb785be3e4dd68599c41be821b521da38c402bc9ab2a8e7ebc7e", size = 747031 },
+ { url = "https://files.pythonhosted.org/packages/be/8a/4a3764a68abc02e2fbb0668d225b6fda5cd39586dd099cee8b2ed6ab0452/pyzmq-27.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:9df43a2459cd3a3563404c1456b2c4c69564daa7dbaf15724c09821a3329ce46", size = 544726 },
+ { url = "https://files.pythonhosted.org/packages/03/f6/11b2a6c8cd13275c31cddc3f89981a1b799a3c41dec55289fa18dede96b5/pyzmq-27.0.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:39ddd3ba0a641f01d8f13a3cfd4c4924eb58e660d8afe87e9061d6e8ca6f7ac3", size = 835944 },
+ { url = "https://files.pythonhosted.org/packages/73/34/aa39076f4e07ae1912fa4b966fe24e831e01d736d4c1c7e8a3aa28a555b5/pyzmq-27.0.0-pp39-pypy39_pp73-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:8ca7e6a0388dd9e1180b14728051068f4efe83e0d2de058b5ff92c63f399a73f", size = 799869 },
+ { url = "https://files.pythonhosted.org/packages/65/f3/81ed6b3dd242408ee79c0d8a88734644acf208baee8666ecd7e52664cf55/pyzmq-27.0.0-pp39-pypy39_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2524c40891be6a3106885a3935d58452dd83eb7a5742a33cc780a1ad4c49dec0", size = 758371 },
+ { url = "https://files.pythonhosted.org/packages/e1/04/dac4ca674764281caf744e8adefd88f7e325e1605aba0f9a322094b903fa/pyzmq-27.0.0-pp39-pypy39_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6a56e3e5bd2d62a01744fd2f1ce21d760c7c65f030e9522738d75932a14ab62a", size = 567393 },
+ { url = "https://files.pythonhosted.org/packages/51/8b/619a9ee2fa4d3c724fbadde946427735ade64da03894b071bbdc3b789d83/pyzmq-27.0.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:096af9e133fec3a72108ddefba1e42985cb3639e9de52cfd336b6fc23aa083e9", size = 544715 },
+]
+
+[[package]]
+name = "referencing"
+version = "0.36.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "attrs" },
+ { name = "rpds-py" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/2f/db/98b5c277be99dd18bfd91dd04e1b759cad18d1a338188c936e92f921c7e2/referencing-0.36.2.tar.gz", hash = "sha256:df2e89862cd09deabbdba16944cc3f10feb6b3e6f18e902f7cc25609a34775aa", size = 74744 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c1/b1/3baf80dc6d2b7bc27a95a67752d0208e410351e3feb4eb78de5f77454d8d/referencing-0.36.2-py3-none-any.whl", hash = "sha256:e8699adbbf8b5c7de96d8ffa0eb5c158b3beafce084968e2ea8bb08c6794dcd0", size = 26775 },
+]
+
+[[package]]
+name = "regex"
+version = "2024.11.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8e/5f/bd69653fbfb76cf8604468d3b4ec4c403197144c7bfe0e6a5fc9e02a07cb/regex-2024.11.6.tar.gz", hash = "sha256:7ab159b063c52a0333c884e4679f8d7a85112ee3078fe3d9004b2dd875585519", size = 399494 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/95/3c/4651f6b130c6842a8f3df82461a8950f923925db8b6961063e82744bddcc/regex-2024.11.6-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ff590880083d60acc0433f9c3f713c51f7ac6ebb9adf889c79a261ecf541aa91", size = 482674 },
+ { url = "https://files.pythonhosted.org/packages/15/51/9f35d12da8434b489c7b7bffc205c474a0a9432a889457026e9bc06a297a/regex-2024.11.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:658f90550f38270639e83ce492f27d2c8d2cd63805c65a13a14d36ca126753f0", size = 287684 },
+ { url = "https://files.pythonhosted.org/packages/bd/18/b731f5510d1b8fb63c6b6d3484bfa9a59b84cc578ac8b5172970e05ae07c/regex-2024.11.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:164d8b7b3b4bcb2068b97428060b2a53be050085ef94eca7f240e7947f1b080e", size = 284589 },
+ { url = "https://files.pythonhosted.org/packages/78/a2/6dd36e16341ab95e4c6073426561b9bfdeb1a9c9b63ab1b579c2e96cb105/regex-2024.11.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3660c82f209655a06b587d55e723f0b813d3a7db2e32e5e7dc64ac2a9e86fde", size = 782511 },
+ { url = "https://files.pythonhosted.org/packages/1b/2b/323e72d5d2fd8de0d9baa443e1ed70363ed7e7b2fb526f5950c5cb99c364/regex-2024.11.6-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d22326fcdef5e08c154280b71163ced384b428343ae16a5ab2b3354aed12436e", size = 821149 },
+ { url = "https://files.pythonhosted.org/packages/90/30/63373b9ea468fbef8a907fd273e5c329b8c9535fee36fc8dba5fecac475d/regex-2024.11.6-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f1ac758ef6aebfc8943560194e9fd0fa18bcb34d89fd8bd2af18183afd8da3a2", size = 809707 },
+ { url = "https://files.pythonhosted.org/packages/f2/98/26d3830875b53071f1f0ae6d547f1d98e964dd29ad35cbf94439120bb67a/regex-2024.11.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:997d6a487ff00807ba810e0f8332c18b4eb8d29463cfb7c820dc4b6e7562d0cf", size = 781702 },
+ { url = "https://files.pythonhosted.org/packages/87/55/eb2a068334274db86208ab9d5599ffa63631b9f0f67ed70ea7c82a69bbc8/regex-2024.11.6-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:02a02d2bb04fec86ad61f3ea7f49c015a0681bf76abb9857f945d26159d2968c", size = 771976 },
+ { url = "https://files.pythonhosted.org/packages/74/c0/be707bcfe98254d8f9d2cff55d216e946f4ea48ad2fd8cf1428f8c5332ba/regex-2024.11.6-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f02f93b92358ee3f78660e43b4b0091229260c5d5c408d17d60bf26b6c900e86", size = 697397 },
+ { url = "https://files.pythonhosted.org/packages/49/dc/bb45572ceb49e0f6509f7596e4ba7031f6819ecb26bc7610979af5a77f45/regex-2024.11.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:06eb1be98df10e81ebaded73fcd51989dcf534e3c753466e4b60c4697a003b67", size = 768726 },
+ { url = "https://files.pythonhosted.org/packages/5a/db/f43fd75dc4c0c2d96d0881967897926942e935d700863666f3c844a72ce6/regex-2024.11.6-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:040df6fe1a5504eb0f04f048e6d09cd7c7110fef851d7c567a6b6e09942feb7d", size = 775098 },
+ { url = "https://files.pythonhosted.org/packages/99/d7/f94154db29ab5a89d69ff893159b19ada89e76b915c1293e98603d39838c/regex-2024.11.6-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:fdabbfc59f2c6edba2a6622c647b716e34e8e3867e0ab975412c5c2f79b82da2", size = 839325 },
+ { url = "https://files.pythonhosted.org/packages/f7/17/3cbfab1f23356fbbf07708220ab438a7efa1e0f34195bf857433f79f1788/regex-2024.11.6-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:8447d2d39b5abe381419319f942de20b7ecd60ce86f16a23b0698f22e1b70008", size = 843277 },
+ { url = "https://files.pythonhosted.org/packages/7e/f2/48b393b51900456155de3ad001900f94298965e1cad1c772b87f9cfea011/regex-2024.11.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:da8f5fc57d1933de22a9e23eec290a0d8a5927a5370d24bda9a6abe50683fe62", size = 773197 },
+ { url = "https://files.pythonhosted.org/packages/45/3f/ef9589aba93e084cd3f8471fded352826dcae8489b650d0b9b27bc5bba8a/regex-2024.11.6-cp310-cp310-win32.whl", hash = "sha256:b489578720afb782f6ccf2840920f3a32e31ba28a4b162e13900c3e6bd3f930e", size = 261714 },
+ { url = "https://files.pythonhosted.org/packages/42/7e/5f1b92c8468290c465fd50c5318da64319133231415a8aa6ea5ab995a815/regex-2024.11.6-cp310-cp310-win_amd64.whl", hash = "sha256:5071b2093e793357c9d8b2929dfc13ac5f0a6c650559503bb81189d0a3814519", size = 274042 },
+ { url = "https://files.pythonhosted.org/packages/58/58/7e4d9493a66c88a7da6d205768119f51af0f684fe7be7bac8328e217a52c/regex-2024.11.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:5478c6962ad548b54a591778e93cd7c456a7a29f8eca9c49e4f9a806dcc5d638", size = 482669 },
+ { url = "https://files.pythonhosted.org/packages/34/4c/8f8e631fcdc2ff978609eaeef1d6994bf2f028b59d9ac67640ed051f1218/regex-2024.11.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2c89a8cc122b25ce6945f0423dc1352cb9593c68abd19223eebbd4e56612c5b7", size = 287684 },
+ { url = "https://files.pythonhosted.org/packages/c5/1b/f0e4d13e6adf866ce9b069e191f303a30ab1277e037037a365c3aad5cc9c/regex-2024.11.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:94d87b689cdd831934fa3ce16cc15cd65748e6d689f5d2b8f4f4df2065c9fa20", size = 284589 },
+ { url = "https://files.pythonhosted.org/packages/25/4d/ab21047f446693887f25510887e6820b93f791992994f6498b0318904d4a/regex-2024.11.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1062b39a0a2b75a9c694f7a08e7183a80c63c0d62b301418ffd9c35f55aaa114", size = 792121 },
+ { url = "https://files.pythonhosted.org/packages/45/ee/c867e15cd894985cb32b731d89576c41a4642a57850c162490ea34b78c3b/regex-2024.11.6-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:167ed4852351d8a750da48712c3930b031f6efdaa0f22fa1933716bfcd6bf4a3", size = 831275 },
+ { url = "https://files.pythonhosted.org/packages/b3/12/b0f480726cf1c60f6536fa5e1c95275a77624f3ac8fdccf79e6727499e28/regex-2024.11.6-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2d548dafee61f06ebdb584080621f3e0c23fff312f0de1afc776e2a2ba99a74f", size = 818257 },
+ { url = "https://files.pythonhosted.org/packages/bf/ce/0d0e61429f603bac433910d99ef1a02ce45a8967ffbe3cbee48599e62d88/regex-2024.11.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2a19f302cd1ce5dd01a9099aaa19cae6173306d1302a43b627f62e21cf18ac0", size = 792727 },
+ { url = "https://files.pythonhosted.org/packages/e4/c1/243c83c53d4a419c1556f43777ccb552bccdf79d08fda3980e4e77dd9137/regex-2024.11.6-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bec9931dfb61ddd8ef2ebc05646293812cb6b16b60cf7c9511a832b6f1854b55", size = 780667 },
+ { url = "https://files.pythonhosted.org/packages/c5/f4/75eb0dd4ce4b37f04928987f1d22547ddaf6c4bae697623c1b05da67a8aa/regex-2024.11.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:9714398225f299aa85267fd222f7142fcb5c769e73d7733344efc46f2ef5cf89", size = 776963 },
+ { url = "https://files.pythonhosted.org/packages/16/5d/95c568574e630e141a69ff8a254c2f188b4398e813c40d49228c9bbd9875/regex-2024.11.6-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:202eb32e89f60fc147a41e55cb086db2a3f8cb82f9a9a88440dcfc5d37faae8d", size = 784700 },
+ { url = "https://files.pythonhosted.org/packages/8e/b5/f8495c7917f15cc6fee1e7f395e324ec3e00ab3c665a7dc9d27562fd5290/regex-2024.11.6-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:4181b814e56078e9b00427ca358ec44333765f5ca1b45597ec7446d3a1ef6e34", size = 848592 },
+ { url = "https://files.pythonhosted.org/packages/1c/80/6dd7118e8cb212c3c60b191b932dc57db93fb2e36fb9e0e92f72a5909af9/regex-2024.11.6-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:068376da5a7e4da51968ce4c122a7cd31afaaec4fccc7856c92f63876e57b51d", size = 852929 },
+ { url = "https://files.pythonhosted.org/packages/11/9b/5a05d2040297d2d254baf95eeeb6df83554e5e1df03bc1a6687fc4ba1f66/regex-2024.11.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ac10f2c4184420d881a3475fb2c6f4d95d53a8d50209a2500723d831036f7c45", size = 781213 },
+ { url = "https://files.pythonhosted.org/packages/26/b7/b14e2440156ab39e0177506c08c18accaf2b8932e39fb092074de733d868/regex-2024.11.6-cp311-cp311-win32.whl", hash = "sha256:c36f9b6f5f8649bb251a5f3f66564438977b7ef8386a52460ae77e6070d309d9", size = 261734 },
+ { url = "https://files.pythonhosted.org/packages/80/32/763a6cc01d21fb3819227a1cc3f60fd251c13c37c27a73b8ff4315433a8e/regex-2024.11.6-cp311-cp311-win_amd64.whl", hash = "sha256:02e28184be537f0e75c1f9b2f8847dc51e08e6e171c6bde130b2687e0c33cf60", size = 274052 },
+ { url = "https://files.pythonhosted.org/packages/ba/30/9a87ce8336b172cc232a0db89a3af97929d06c11ceaa19d97d84fa90a8f8/regex-2024.11.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:52fb28f528778f184f870b7cf8f225f5eef0a8f6e3778529bdd40c7b3920796a", size = 483781 },
+ { url = "https://files.pythonhosted.org/packages/01/e8/00008ad4ff4be8b1844786ba6636035f7ef926db5686e4c0f98093612add/regex-2024.11.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fdd6028445d2460f33136c55eeb1f601ab06d74cb3347132e1c24250187500d9", size = 288455 },
+ { url = "https://files.pythonhosted.org/packages/60/85/cebcc0aff603ea0a201667b203f13ba75d9fc8668fab917ac5b2de3967bc/regex-2024.11.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:805e6b60c54bf766b251e94526ebad60b7de0c70f70a4e6210ee2891acb70bf2", size = 284759 },
+ { url = "https://files.pythonhosted.org/packages/94/2b/701a4b0585cb05472a4da28ee28fdfe155f3638f5e1ec92306d924e5faf0/regex-2024.11.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b85c2530be953a890eaffde05485238f07029600e8f098cdf1848d414a8b45e4", size = 794976 },
+ { url = "https://files.pythonhosted.org/packages/4b/bf/fa87e563bf5fee75db8915f7352e1887b1249126a1be4813837f5dbec965/regex-2024.11.6-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bb26437975da7dc36b7efad18aa9dd4ea569d2357ae6b783bf1118dabd9ea577", size = 833077 },
+ { url = "https://files.pythonhosted.org/packages/a1/56/7295e6bad94b047f4d0834e4779491b81216583c00c288252ef625c01d23/regex-2024.11.6-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:abfa5080c374a76a251ba60683242bc17eeb2c9818d0d30117b4486be10c59d3", size = 823160 },
+ { url = "https://files.pythonhosted.org/packages/fb/13/e3b075031a738c9598c51cfbc4c7879e26729c53aa9cca59211c44235314/regex-2024.11.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b7fa6606c2881c1db9479b0eaa11ed5dfa11c8d60a474ff0e095099f39d98e", size = 796896 },
+ { url = "https://files.pythonhosted.org/packages/24/56/0b3f1b66d592be6efec23a795b37732682520b47c53da5a32c33ed7d84e3/regex-2024.11.6-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0c32f75920cf99fe6b6c539c399a4a128452eaf1af27f39bce8909c9a3fd8cbe", size = 783997 },
+ { url = "https://files.pythonhosted.org/packages/f9/a1/eb378dada8b91c0e4c5f08ffb56f25fcae47bf52ad18f9b2f33b83e6d498/regex-2024.11.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:982e6d21414e78e1f51cf595d7f321dcd14de1f2881c5dc6a6e23bbbbd68435e", size = 781725 },
+ { url = "https://files.pythonhosted.org/packages/83/f2/033e7dec0cfd6dda93390089864732a3409246ffe8b042e9554afa9bff4e/regex-2024.11.6-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a7c2155f790e2fb448faed6dd241386719802296ec588a8b9051c1f5c481bc29", size = 789481 },
+ { url = "https://files.pythonhosted.org/packages/83/23/15d4552ea28990a74e7696780c438aadd73a20318c47e527b47a4a5a596d/regex-2024.11.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:149f5008d286636e48cd0b1dd65018548944e495b0265b45e1bffecce1ef7f39", size = 852896 },
+ { url = "https://files.pythonhosted.org/packages/e3/39/ed4416bc90deedbfdada2568b2cb0bc1fdb98efe11f5378d9892b2a88f8f/regex-2024.11.6-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:e5364a4502efca094731680e80009632ad6624084aff9a23ce8c8c6820de3e51", size = 860138 },
+ { url = "https://files.pythonhosted.org/packages/93/2d/dd56bb76bd8e95bbce684326302f287455b56242a4f9c61f1bc76e28360e/regex-2024.11.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0a86e7eeca091c09e021db8eb72d54751e527fa47b8d5787caf96d9831bd02ad", size = 787692 },
+ { url = "https://files.pythonhosted.org/packages/0b/55/31877a249ab7a5156758246b9c59539abbeba22461b7d8adc9e8475ff73e/regex-2024.11.6-cp312-cp312-win32.whl", hash = "sha256:32f9a4c643baad4efa81d549c2aadefaeba12249b2adc5af541759237eee1c54", size = 262135 },
+ { url = "https://files.pythonhosted.org/packages/38/ec/ad2d7de49a600cdb8dd78434a1aeffe28b9d6fc42eb36afab4a27ad23384/regex-2024.11.6-cp312-cp312-win_amd64.whl", hash = "sha256:a93c194e2df18f7d264092dc8539b8ffb86b45b899ab976aa15d48214138e81b", size = 273567 },
+ { url = "https://files.pythonhosted.org/packages/90/73/bcb0e36614601016552fa9344544a3a2ae1809dc1401b100eab02e772e1f/regex-2024.11.6-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a6ba92c0bcdf96cbf43a12c717eae4bc98325ca3730f6b130ffa2e3c3c723d84", size = 483525 },
+ { url = "https://files.pythonhosted.org/packages/0f/3f/f1a082a46b31e25291d830b369b6b0c5576a6f7fb89d3053a354c24b8a83/regex-2024.11.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:525eab0b789891ac3be914d36893bdf972d483fe66551f79d3e27146191a37d4", size = 288324 },
+ { url = "https://files.pythonhosted.org/packages/09/c9/4e68181a4a652fb3ef5099e077faf4fd2a694ea6e0f806a7737aff9e758a/regex-2024.11.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:086a27a0b4ca227941700e0b31425e7a28ef1ae8e5e05a33826e17e47fbfdba0", size = 284617 },
+ { url = "https://files.pythonhosted.org/packages/fc/fd/37868b75eaf63843165f1d2122ca6cb94bfc0271e4428cf58c0616786dce/regex-2024.11.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bde01f35767c4a7899b7eb6e823b125a64de314a8ee9791367c9a34d56af18d0", size = 795023 },
+ { url = "https://files.pythonhosted.org/packages/c4/7c/d4cd9c528502a3dedb5c13c146e7a7a539a3853dc20209c8e75d9ba9d1b2/regex-2024.11.6-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b583904576650166b3d920d2bcce13971f6f9e9a396c673187f49811b2769dc7", size = 833072 },
+ { url = "https://files.pythonhosted.org/packages/4f/db/46f563a08f969159c5a0f0e722260568425363bea43bb7ae370becb66a67/regex-2024.11.6-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1c4de13f06a0d54fa0d5ab1b7138bfa0d883220965a29616e3ea61b35d5f5fc7", size = 823130 },
+ { url = "https://files.pythonhosted.org/packages/db/60/1eeca2074f5b87df394fccaa432ae3fc06c9c9bfa97c5051aed70e6e00c2/regex-2024.11.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3cde6e9f2580eb1665965ce9bf17ff4952f34f5b126beb509fee8f4e994f143c", size = 796857 },
+ { url = "https://files.pythonhosted.org/packages/10/db/ac718a08fcee981554d2f7bb8402f1faa7e868c1345c16ab1ebec54b0d7b/regex-2024.11.6-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0d7f453dca13f40a02b79636a339c5b62b670141e63efd511d3f8f73fba162b3", size = 784006 },
+ { url = "https://files.pythonhosted.org/packages/c2/41/7da3fe70216cea93144bf12da2b87367590bcf07db97604edeea55dac9ad/regex-2024.11.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:59dfe1ed21aea057a65c6b586afd2a945de04fc7db3de0a6e3ed5397ad491b07", size = 781650 },
+ { url = "https://files.pythonhosted.org/packages/a7/d5/880921ee4eec393a4752e6ab9f0fe28009435417c3102fc413f3fe81c4e5/regex-2024.11.6-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b97c1e0bd37c5cd7902e65f410779d39eeda155800b65fc4d04cc432efa9bc6e", size = 789545 },
+ { url = "https://files.pythonhosted.org/packages/dc/96/53770115e507081122beca8899ab7f5ae28ae790bfcc82b5e38976df6a77/regex-2024.11.6-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:f9d1e379028e0fc2ae3654bac3cbbef81bf3fd571272a42d56c24007979bafb6", size = 853045 },
+ { url = "https://files.pythonhosted.org/packages/31/d3/1372add5251cc2d44b451bd94f43b2ec78e15a6e82bff6a290ef9fd8f00a/regex-2024.11.6-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:13291b39131e2d002a7940fb176e120bec5145f3aeb7621be6534e46251912c4", size = 860182 },
+ { url = "https://files.pythonhosted.org/packages/ed/e3/c446a64984ea9f69982ba1a69d4658d5014bc7a0ea468a07e1a1265db6e2/regex-2024.11.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4f51f88c126370dcec4908576c5a627220da6c09d0bff31cfa89f2523843316d", size = 787733 },
+ { url = "https://files.pythonhosted.org/packages/2b/f1/e40c8373e3480e4f29f2692bd21b3e05f296d3afebc7e5dcf21b9756ca1c/regex-2024.11.6-cp313-cp313-win32.whl", hash = "sha256:63b13cfd72e9601125027202cad74995ab26921d8cd935c25f09c630436348ff", size = 262122 },
+ { url = "https://files.pythonhosted.org/packages/45/94/bc295babb3062a731f52621cdc992d123111282e291abaf23faa413443ea/regex-2024.11.6-cp313-cp313-win_amd64.whl", hash = "sha256:2b3361af3198667e99927da8b84c1b010752fa4b1115ee30beaa332cabc3ef1a", size = 273545 },
+ { url = "https://files.pythonhosted.org/packages/89/23/c4a86df398e57e26f93b13ae63acce58771e04bdde86092502496fa57f9c/regex-2024.11.6-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:5704e174f8ccab2026bd2f1ab6c510345ae8eac818b613d7d73e785f1310f839", size = 482682 },
+ { url = "https://files.pythonhosted.org/packages/3c/8b/45c24ab7a51a1658441b961b86209c43e6bb9d39caf1e63f46ce6ea03bc7/regex-2024.11.6-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:220902c3c5cc6af55d4fe19ead504de80eb91f786dc102fbd74894b1551f095e", size = 287679 },
+ { url = "https://files.pythonhosted.org/packages/7a/d1/598de10b17fdafc452d11f7dada11c3be4e379a8671393e4e3da3c4070df/regex-2024.11.6-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:5e7e351589da0850c125f1600a4c4ba3c722efefe16b297de54300f08d734fbf", size = 284578 },
+ { url = "https://files.pythonhosted.org/packages/49/70/c7eaa219efa67a215846766fde18d92d54cb590b6a04ffe43cef30057622/regex-2024.11.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5056b185ca113c88e18223183aa1a50e66507769c9640a6ff75859619d73957b", size = 782012 },
+ { url = "https://files.pythonhosted.org/packages/89/e5/ef52c7eb117dd20ff1697968219971d052138965a4d3d9b95e92e549f505/regex-2024.11.6-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2e34b51b650b23ed3354b5a07aab37034d9f923db2a40519139af34f485f77d0", size = 820580 },
+ { url = "https://files.pythonhosted.org/packages/5f/3f/9f5da81aff1d4167ac52711acf789df13e789fe6ac9545552e49138e3282/regex-2024.11.6-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5670bce7b200273eee1840ef307bfa07cda90b38ae56e9a6ebcc9f50da9c469b", size = 809110 },
+ { url = "https://files.pythonhosted.org/packages/86/44/2101cc0890c3621b90365c9ee8d7291a597c0722ad66eccd6ffa7f1bcc09/regex-2024.11.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:08986dce1339bc932923e7d1232ce9881499a0e02925f7402fb7c982515419ef", size = 780919 },
+ { url = "https://files.pythonhosted.org/packages/ce/2e/3e0668d8d1c7c3c0d397bf54d92fc182575b3a26939aed5000d3cc78760f/regex-2024.11.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:93c0b12d3d3bc25af4ebbf38f9ee780a487e8bf6954c115b9f015822d3bb8e48", size = 771515 },
+ { url = "https://files.pythonhosted.org/packages/a6/49/1bc4584254355e3dba930a3a2fd7ad26ccba3ebbab7d9100db0aff2eedb0/regex-2024.11.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:764e71f22ab3b305e7f4c21f1a97e1526a25ebdd22513e251cf376760213da13", size = 696957 },
+ { url = "https://files.pythonhosted.org/packages/c8/dd/42879c1fc8a37a887cd08e358af3d3ba9e23038cd77c7fe044a86d9450ba/regex-2024.11.6-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:f056bf21105c2515c32372bbc057f43eb02aae2fda61052e2f7622c801f0b4e2", size = 768088 },
+ { url = "https://files.pythonhosted.org/packages/89/96/c05a0fe173cd2acd29d5e13c1adad8b706bcaa71b169e1ee57dcf2e74584/regex-2024.11.6-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:69ab78f848845569401469da20df3e081e6b5a11cb086de3eed1d48f5ed57c95", size = 774752 },
+ { url = "https://files.pythonhosted.org/packages/b5/f3/a757748066255f97f14506483436c5f6aded7af9e37bca04ec30c90ca683/regex-2024.11.6-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:86fddba590aad9208e2fa8b43b4c098bb0ec74f15718bb6a704e3c63e2cef3e9", size = 838862 },
+ { url = "https://files.pythonhosted.org/packages/5c/93/c6d2092fd479dcaeea40fc8fa673822829181ded77d294a7f950f1dda6e2/regex-2024.11.6-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:684d7a212682996d21ca12ef3c17353c021fe9de6049e19ac8481ec35574a70f", size = 842622 },
+ { url = "https://files.pythonhosted.org/packages/ff/9c/daa99532c72f25051a90ef90e1413a8d54413a9e64614d9095b0c1c154d0/regex-2024.11.6-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:a03e02f48cd1abbd9f3b7e3586d97c8f7a9721c436f51a5245b3b9483044480b", size = 772713 },
+ { url = "https://files.pythonhosted.org/packages/13/5d/61a533ccb8c231b474ac8e3a7d70155b00dfc61af6cafdccd1947df6d735/regex-2024.11.6-cp39-cp39-win32.whl", hash = "sha256:41758407fc32d5c3c5de163888068cfee69cb4c2be844e7ac517a52770f9af57", size = 261756 },
+ { url = "https://files.pythonhosted.org/packages/dc/7b/e59b7f7c91ae110d154370c24133f947262525b5d6406df65f23422acc17/regex-2024.11.6-cp39-cp39-win_amd64.whl", hash = "sha256:b2837718570f95dd41675328e111345f9b7095d821bac435aac173ac80b19983", size = 274110 },
+]
+
+[[package]]
+name = "requests"
+version = "2.32.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "charset-normalizer" },
+ { name = "idna" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e1/0a/929373653770d8a0d7ea76c37de6e41f11eb07559b103b1c02cafb3f7cf8/requests-2.32.4.tar.gz", hash = "sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422", size = 135258 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/e4/56027c4a6b4ae70ca9de302488c5ca95ad4a39e190093d6c1a8ace08341b/requests-2.32.4-py3-none-any.whl", hash = "sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c", size = 64847 },
+]
+
+[[package]]
+name = "rpds-py"
+version = "0.25.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8c/a6/60184b7fc00dd3ca80ac635dd5b8577d444c57e8e8742cecabfacb829921/rpds_py-0.25.1.tar.gz", hash = "sha256:8960b6dac09b62dac26e75d7e2c4a22efb835d827a7278c34f72b2b84fa160e3", size = 27304 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cb/09/e1158988e50905b7f8306487a576b52d32aa9a87f79f7ab24ee8db8b6c05/rpds_py-0.25.1-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:f4ad628b5174d5315761b67f212774a32f5bad5e61396d38108bd801c0a8f5d9", size = 373140 },
+ { url = "https://files.pythonhosted.org/packages/e0/4b/a284321fb3c45c02fc74187171504702b2934bfe16abab89713eedfe672e/rpds_py-0.25.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8c742af695f7525e559c16f1562cf2323db0e3f0fbdcabdf6865b095256b2d40", size = 358860 },
+ { url = "https://files.pythonhosted.org/packages/4e/46/8ac9811150c75edeae9fc6fa0e70376c19bc80f8e1f7716981433905912b/rpds_py-0.25.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:605ffe7769e24b1800b4d024d24034405d9404f0bc2f55b6db3362cd34145a6f", size = 386179 },
+ { url = "https://files.pythonhosted.org/packages/f3/ec/87eb42d83e859bce91dcf763eb9f2ab117142a49c9c3d17285440edb5b69/rpds_py-0.25.1-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ccc6f3ddef93243538be76f8e47045b4aad7a66a212cd3a0f23e34469473d36b", size = 400282 },
+ { url = "https://files.pythonhosted.org/packages/68/c8/2a38e0707d7919c8c78e1d582ab15cf1255b380bcb086ca265b73ed6db23/rpds_py-0.25.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f70316f760174ca04492b5ab01be631a8ae30cadab1d1081035136ba12738cfa", size = 521824 },
+ { url = "https://files.pythonhosted.org/packages/5e/2c/6a92790243569784dde84d144bfd12bd45102f4a1c897d76375076d730ab/rpds_py-0.25.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e1dafef8df605fdb46edcc0bf1573dea0d6d7b01ba87f85cd04dc855b2b4479e", size = 411644 },
+ { url = "https://files.pythonhosted.org/packages/eb/76/66b523ffc84cf47db56efe13ae7cf368dee2bacdec9d89b9baca5e2e6301/rpds_py-0.25.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0701942049095741a8aeb298a31b203e735d1c61f4423511d2b1a41dcd8a16da", size = 386955 },
+ { url = "https://files.pythonhosted.org/packages/b6/b9/a362d7522feaa24dc2b79847c6175daa1c642817f4a19dcd5c91d3e2c316/rpds_py-0.25.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e87798852ae0b37c88babb7f7bbbb3e3fecc562a1c340195b44c7e24d403e380", size = 421039 },
+ { url = "https://files.pythonhosted.org/packages/0f/c4/b5b6f70b4d719b6584716889fd3413102acf9729540ee76708d56a76fa97/rpds_py-0.25.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3bcce0edc1488906c2d4c75c94c70a0417e83920dd4c88fec1078c94843a6ce9", size = 563290 },
+ { url = "https://files.pythonhosted.org/packages/87/a3/2e6e816615c12a8f8662c9d8583a12eb54c52557521ef218cbe3095a8afa/rpds_py-0.25.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:e2f6a2347d3440ae789505693a02836383426249d5293541cd712e07e7aecf54", size = 592089 },
+ { url = "https://files.pythonhosted.org/packages/c0/08/9b8e1050e36ce266135994e2c7ec06e1841f1c64da739daeb8afe9cb77a4/rpds_py-0.25.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:4fd52d3455a0aa997734f3835cbc4c9f32571345143960e7d7ebfe7b5fbfa3b2", size = 558400 },
+ { url = "https://files.pythonhosted.org/packages/f2/df/b40b8215560b8584baccd839ff5c1056f3c57120d79ac41bd26df196da7e/rpds_py-0.25.1-cp310-cp310-win32.whl", hash = "sha256:3f0b1798cae2bbbc9b9db44ee068c556d4737911ad53a4e5093d09d04b3bbc24", size = 219741 },
+ { url = "https://files.pythonhosted.org/packages/10/99/e4c58be18cf5d8b40b8acb4122bc895486230b08f978831b16a3916bd24d/rpds_py-0.25.1-cp310-cp310-win_amd64.whl", hash = "sha256:3ebd879ab996537fc510a2be58c59915b5dd63bccb06d1ef514fee787e05984a", size = 231553 },
+ { url = "https://files.pythonhosted.org/packages/95/e1/df13fe3ddbbea43567e07437f097863b20c99318ae1f58a0fe389f763738/rpds_py-0.25.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:5f048bbf18b1f9120685c6d6bb70cc1a52c8cc11bdd04e643d28d3be0baf666d", size = 373341 },
+ { url = "https://files.pythonhosted.org/packages/7a/58/deef4d30fcbcbfef3b6d82d17c64490d5c94585a2310544ce8e2d3024f83/rpds_py-0.25.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4fbb0dbba559959fcb5d0735a0f87cdbca9e95dac87982e9b95c0f8f7ad10255", size = 359111 },
+ { url = "https://files.pythonhosted.org/packages/bb/7e/39f1f4431b03e96ebaf159e29a0f82a77259d8f38b2dd474721eb3a8ac9b/rpds_py-0.25.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d4ca54b9cf9d80b4016a67a0193ebe0bcf29f6b0a96f09db942087e294d3d4c2", size = 386112 },
+ { url = "https://files.pythonhosted.org/packages/db/e7/847068a48d63aec2ae695a1646089620b3b03f8ccf9f02c122ebaf778f3c/rpds_py-0.25.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1ee3e26eb83d39b886d2cb6e06ea701bba82ef30a0de044d34626ede51ec98b0", size = 400362 },
+ { url = "https://files.pythonhosted.org/packages/3b/3d/9441d5db4343d0cee759a7ab4d67420a476cebb032081763de934719727b/rpds_py-0.25.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:89706d0683c73a26f76a5315d893c051324d771196ae8b13e6ffa1ffaf5e574f", size = 522214 },
+ { url = "https://files.pythonhosted.org/packages/a2/ec/2cc5b30d95f9f1a432c79c7a2f65d85e52812a8f6cbf8768724571710786/rpds_py-0.25.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c2013ee878c76269c7b557a9a9c042335d732e89d482606990b70a839635feb7", size = 411491 },
+ { url = "https://files.pythonhosted.org/packages/dc/6c/44695c1f035077a017dd472b6a3253553780837af2fac9b6ac25f6a5cb4d/rpds_py-0.25.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:45e484db65e5380804afbec784522de84fa95e6bb92ef1bd3325d33d13efaebd", size = 386978 },
+ { url = "https://files.pythonhosted.org/packages/b1/74/b4357090bb1096db5392157b4e7ed8bb2417dc7799200fcbaee633a032c9/rpds_py-0.25.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:48d64155d02127c249695abb87d39f0faf410733428d499867606be138161d65", size = 420662 },
+ { url = "https://files.pythonhosted.org/packages/26/dd/8cadbebf47b96e59dfe8b35868e5c38a42272699324e95ed522da09d3a40/rpds_py-0.25.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:048893e902132fd6548a2e661fb38bf4896a89eea95ac5816cf443524a85556f", size = 563385 },
+ { url = "https://files.pythonhosted.org/packages/c3/ea/92960bb7f0e7a57a5ab233662f12152085c7dc0d5468534c65991a3d48c9/rpds_py-0.25.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:0317177b1e8691ab5879f4f33f4b6dc55ad3b344399e23df2e499de7b10a548d", size = 592047 },
+ { url = "https://files.pythonhosted.org/packages/61/ad/71aabc93df0d05dabcb4b0c749277881f8e74548582d96aa1bf24379493a/rpds_py-0.25.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bffcf57826d77a4151962bf1701374e0fc87f536e56ec46f1abdd6a903354042", size = 557863 },
+ { url = "https://files.pythonhosted.org/packages/93/0f/89df0067c41f122b90b76f3660028a466eb287cbe38efec3ea70e637ca78/rpds_py-0.25.1-cp311-cp311-win32.whl", hash = "sha256:cda776f1967cb304816173b30994faaf2fd5bcb37e73118a47964a02c348e1bc", size = 219627 },
+ { url = "https://files.pythonhosted.org/packages/7c/8d/93b1a4c1baa903d0229374d9e7aa3466d751f1d65e268c52e6039c6e338e/rpds_py-0.25.1-cp311-cp311-win_amd64.whl", hash = "sha256:dc3c1ff0abc91444cd20ec643d0f805df9a3661fcacf9c95000329f3ddf268a4", size = 231603 },
+ { url = "https://files.pythonhosted.org/packages/cb/11/392605e5247bead2f23e6888e77229fbd714ac241ebbebb39a1e822c8815/rpds_py-0.25.1-cp311-cp311-win_arm64.whl", hash = "sha256:5a3ddb74b0985c4387719fc536faced33cadf2172769540c62e2a94b7b9be1c4", size = 223967 },
+ { url = "https://files.pythonhosted.org/packages/7f/81/28ab0408391b1dc57393653b6a0cf2014cc282cc2909e4615e63e58262be/rpds_py-0.25.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:b5ffe453cde61f73fea9430223c81d29e2fbf412a6073951102146c84e19e34c", size = 364647 },
+ { url = "https://files.pythonhosted.org/packages/2c/9a/7797f04cad0d5e56310e1238434f71fc6939d0bc517192a18bb99a72a95f/rpds_py-0.25.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:115874ae5e2fdcfc16b2aedc95b5eef4aebe91b28e7e21951eda8a5dc0d3461b", size = 350454 },
+ { url = "https://files.pythonhosted.org/packages/69/3c/93d2ef941b04898011e5d6eaa56a1acf46a3b4c9f4b3ad1bbcbafa0bee1f/rpds_py-0.25.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a714bf6e5e81b0e570d01f56e0c89c6375101b8463999ead3a93a5d2a4af91fa", size = 389665 },
+ { url = "https://files.pythonhosted.org/packages/c1/57/ad0e31e928751dde8903a11102559628d24173428a0f85e25e187defb2c1/rpds_py-0.25.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:35634369325906bcd01577da4c19e3b9541a15e99f31e91a02d010816b49bfda", size = 403873 },
+ { url = "https://files.pythonhosted.org/packages/16/ad/c0c652fa9bba778b4f54980a02962748479dc09632e1fd34e5282cf2556c/rpds_py-0.25.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d4cb2b3ddc16710548801c6fcc0cfcdeeff9dafbc983f77265877793f2660309", size = 525866 },
+ { url = "https://files.pythonhosted.org/packages/2a/39/3e1839bc527e6fcf48d5fec4770070f872cdee6c6fbc9b259932f4e88a38/rpds_py-0.25.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9ceca1cf097ed77e1a51f1dbc8d174d10cb5931c188a4505ff9f3e119dfe519b", size = 416886 },
+ { url = "https://files.pythonhosted.org/packages/7a/95/dd6b91cd4560da41df9d7030a038298a67d24f8ca38e150562644c829c48/rpds_py-0.25.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c2cd1a4b0c2b8c5e31ffff50d09f39906fe351389ba143c195566056c13a7ea", size = 390666 },
+ { url = "https://files.pythonhosted.org/packages/64/48/1be88a820e7494ce0a15c2d390ccb7c52212370badabf128e6a7bb4cb802/rpds_py-0.25.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1de336a4b164c9188cb23f3703adb74a7623ab32d20090d0e9bf499a2203ad65", size = 425109 },
+ { url = "https://files.pythonhosted.org/packages/cf/07/3e2a17927ef6d7720b9949ec1b37d1e963b829ad0387f7af18d923d5cfa5/rpds_py-0.25.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9fca84a15333e925dd59ce01da0ffe2ffe0d6e5d29a9eeba2148916d1824948c", size = 567244 },
+ { url = "https://files.pythonhosted.org/packages/d2/e5/76cf010998deccc4f95305d827847e2eae9c568099c06b405cf96384762b/rpds_py-0.25.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:88ec04afe0c59fa64e2f6ea0dd9657e04fc83e38de90f6de201954b4d4eb59bd", size = 596023 },
+ { url = "https://files.pythonhosted.org/packages/52/9a/df55efd84403736ba37a5a6377b70aad0fd1cb469a9109ee8a1e21299a1c/rpds_py-0.25.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a8bd2f19e312ce3e1d2c635618e8a8d8132892bb746a7cf74780a489f0f6cdcb", size = 561634 },
+ { url = "https://files.pythonhosted.org/packages/ab/aa/dc3620dd8db84454aaf9374bd318f1aa02578bba5e567f5bf6b79492aca4/rpds_py-0.25.1-cp312-cp312-win32.whl", hash = "sha256:e5e2f7280d8d0d3ef06f3ec1b4fd598d386cc6f0721e54f09109a8132182fbfe", size = 222713 },
+ { url = "https://files.pythonhosted.org/packages/a3/7f/7cef485269a50ed5b4e9bae145f512d2a111ca638ae70cc101f661b4defd/rpds_py-0.25.1-cp312-cp312-win_amd64.whl", hash = "sha256:db58483f71c5db67d643857404da360dce3573031586034b7d59f245144cc192", size = 235280 },
+ { url = "https://files.pythonhosted.org/packages/99/f2/c2d64f6564f32af913bf5f3f7ae41c7c263c5ae4c4e8f1a17af8af66cd46/rpds_py-0.25.1-cp312-cp312-win_arm64.whl", hash = "sha256:6d50841c425d16faf3206ddbba44c21aa3310a0cebc3c1cdfc3e3f4f9f6f5728", size = 225399 },
+ { url = "https://files.pythonhosted.org/packages/2b/da/323848a2b62abe6a0fec16ebe199dc6889c5d0a332458da8985b2980dffe/rpds_py-0.25.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:659d87430a8c8c704d52d094f5ba6fa72ef13b4d385b7e542a08fc240cb4a559", size = 364498 },
+ { url = "https://files.pythonhosted.org/packages/1f/b4/4d3820f731c80fd0cd823b3e95b9963fec681ae45ba35b5281a42382c67d/rpds_py-0.25.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:68f6f060f0bbdfb0245267da014d3a6da9be127fe3e8cc4a68c6f833f8a23bb1", size = 350083 },
+ { url = "https://files.pythonhosted.org/packages/d5/b1/3a8ee1c9d480e8493619a437dec685d005f706b69253286f50f498cbdbcf/rpds_py-0.25.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:083a9513a33e0b92cf6e7a6366036c6bb43ea595332c1ab5c8ae329e4bcc0a9c", size = 389023 },
+ { url = "https://files.pythonhosted.org/packages/3b/31/17293edcfc934dc62c3bf74a0cb449ecd549531f956b72287203e6880b87/rpds_py-0.25.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:816568614ecb22b18a010c7a12559c19f6fe993526af88e95a76d5a60b8b75fb", size = 403283 },
+ { url = "https://files.pythonhosted.org/packages/d1/ca/e0f0bc1a75a8925024f343258c8ecbd8828f8997ea2ac71e02f67b6f5299/rpds_py-0.25.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c6564c0947a7f52e4792983f8e6cf9bac140438ebf81f527a21d944f2fd0a40", size = 524634 },
+ { url = "https://files.pythonhosted.org/packages/3e/03/5d0be919037178fff33a6672ffc0afa04ea1cfcb61afd4119d1b5280ff0f/rpds_py-0.25.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5c4a128527fe415d73cf1f70a9a688d06130d5810be69f3b553bf7b45e8acf79", size = 416233 },
+ { url = "https://files.pythonhosted.org/packages/05/7c/8abb70f9017a231c6c961a8941403ed6557664c0913e1bf413cbdc039e75/rpds_py-0.25.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a49e1d7a4978ed554f095430b89ecc23f42014a50ac385eb0c4d163ce213c325", size = 390375 },
+ { url = "https://files.pythonhosted.org/packages/7a/ac/a87f339f0e066b9535074a9f403b9313fd3892d4a164d5d5f5875ac9f29f/rpds_py-0.25.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d74ec9bc0e2feb81d3f16946b005748119c0f52a153f6db6a29e8cd68636f295", size = 424537 },
+ { url = "https://files.pythonhosted.org/packages/1f/8f/8d5c1567eaf8c8afe98a838dd24de5013ce6e8f53a01bd47fe8bb06b5533/rpds_py-0.25.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3af5b4cc10fa41e5bc64e5c198a1b2d2864337f8fcbb9a67e747e34002ce812b", size = 566425 },
+ { url = "https://files.pythonhosted.org/packages/95/33/03016a6be5663b389c8ab0bbbcca68d9e96af14faeff0a04affcb587e776/rpds_py-0.25.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:79dc317a5f1c51fd9c6a0c4f48209c6b8526d0524a6904fc1076476e79b00f98", size = 595197 },
+ { url = "https://files.pythonhosted.org/packages/33/8d/da9f4d3e208c82fda311bff0cf0a19579afceb77cf456e46c559a1c075ba/rpds_py-0.25.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1521031351865e0181bc585147624d66b3b00a84109b57fcb7a779c3ec3772cd", size = 561244 },
+ { url = "https://files.pythonhosted.org/packages/e2/b3/39d5dcf7c5f742ecd6dbc88f6f84ae54184b92f5f387a4053be2107b17f1/rpds_py-0.25.1-cp313-cp313-win32.whl", hash = "sha256:5d473be2b13600b93a5675d78f59e63b51b1ba2d0476893415dfbb5477e65b31", size = 222254 },
+ { url = "https://files.pythonhosted.org/packages/5f/19/2d6772c8eeb8302c5f834e6d0dfd83935a884e7c5ce16340c7eaf89ce925/rpds_py-0.25.1-cp313-cp313-win_amd64.whl", hash = "sha256:a7b74e92a3b212390bdce1d93da9f6488c3878c1d434c5e751cbc202c5e09500", size = 234741 },
+ { url = "https://files.pythonhosted.org/packages/5b/5a/145ada26cfaf86018d0eb304fe55eafdd4f0b6b84530246bb4a7c4fb5c4b/rpds_py-0.25.1-cp313-cp313-win_arm64.whl", hash = "sha256:dd326a81afe332ede08eb39ab75b301d5676802cdffd3a8f287a5f0b694dc3f5", size = 224830 },
+ { url = "https://files.pythonhosted.org/packages/4b/ca/d435844829c384fd2c22754ff65889c5c556a675d2ed9eb0e148435c6690/rpds_py-0.25.1-cp313-cp313t-macosx_10_12_x86_64.whl", hash = "sha256:a58d1ed49a94d4183483a3ce0af22f20318d4a1434acee255d683ad90bf78129", size = 359668 },
+ { url = "https://files.pythonhosted.org/packages/1f/01/b056f21db3a09f89410d493d2f6614d87bb162499f98b649d1dbd2a81988/rpds_py-0.25.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:f251bf23deb8332823aef1da169d5d89fa84c89f67bdfb566c49dea1fccfd50d", size = 345649 },
+ { url = "https://files.pythonhosted.org/packages/e0/0f/e0d00dc991e3d40e03ca36383b44995126c36b3eafa0ccbbd19664709c88/rpds_py-0.25.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8dbd586bfa270c1103ece2109314dd423df1fa3d9719928b5d09e4840cec0d72", size = 384776 },
+ { url = "https://files.pythonhosted.org/packages/9f/a2/59374837f105f2ca79bde3c3cd1065b2f8c01678900924949f6392eab66d/rpds_py-0.25.1-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6d273f136e912aa101a9274c3145dcbddbe4bac560e77e6d5b3c9f6e0ed06d34", size = 395131 },
+ { url = "https://files.pythonhosted.org/packages/9c/dc/48e8d84887627a0fe0bac53f0b4631e90976fd5d35fff8be66b8e4f3916b/rpds_py-0.25.1-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:666fa7b1bd0a3810a7f18f6d3a25ccd8866291fbbc3c9b912b917a6715874bb9", size = 520942 },
+ { url = "https://files.pythonhosted.org/packages/7c/f5/ee056966aeae401913d37befeeab57a4a43a4f00099e0a20297f17b8f00c/rpds_py-0.25.1-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:921954d7fbf3fccc7de8f717799304b14b6d9a45bbeec5a8d7408ccbf531faf5", size = 411330 },
+ { url = "https://files.pythonhosted.org/packages/ab/74/b2cffb46a097cefe5d17f94ede7a174184b9d158a0aeb195f39f2c0361e8/rpds_py-0.25.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f3d86373ff19ca0441ebeb696ef64cb58b8b5cbacffcda5a0ec2f3911732a194", size = 387339 },
+ { url = "https://files.pythonhosted.org/packages/7f/9a/0ff0b375dcb5161c2b7054e7d0b7575f1680127505945f5cabaac890bc07/rpds_py-0.25.1-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c8980cde3bb8575e7c956a530f2c217c1d6aac453474bf3ea0f9c89868b531b6", size = 418077 },
+ { url = "https://files.pythonhosted.org/packages/0d/a1/fda629bf20d6b698ae84c7c840cfb0e9e4200f664fc96e1f456f00e4ad6e/rpds_py-0.25.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:8eb8c84ecea987a2523e057c0d950bcb3f789696c0499290b8d7b3107a719d78", size = 562441 },
+ { url = "https://files.pythonhosted.org/packages/20/15/ce4b5257f654132f326f4acd87268e1006cc071e2c59794c5bdf4bebbb51/rpds_py-0.25.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:e43a005671a9ed5a650f3bc39e4dbccd6d4326b24fb5ea8be5f3a43a6f576c72", size = 590750 },
+ { url = "https://files.pythonhosted.org/packages/fb/ab/e04bf58a8d375aeedb5268edcc835c6a660ebf79d4384d8e0889439448b0/rpds_py-0.25.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:58f77c60956501a4a627749a6dcb78dac522f249dd96b5c9f1c6af29bfacfb66", size = 558891 },
+ { url = "https://files.pythonhosted.org/packages/90/82/cb8c6028a6ef6cd2b7991e2e4ced01c854b6236ecf51e81b64b569c43d73/rpds_py-0.25.1-cp313-cp313t-win32.whl", hash = "sha256:2cb9e5b5e26fc02c8a4345048cd9998c2aca7c2712bd1b36da0c72ee969a3523", size = 218718 },
+ { url = "https://files.pythonhosted.org/packages/b6/97/5a4b59697111c89477d20ba8a44df9ca16b41e737fa569d5ae8bff99e650/rpds_py-0.25.1-cp313-cp313t-win_amd64.whl", hash = "sha256:401ca1c4a20cc0510d3435d89c069fe0a9ae2ee6495135ac46bdd49ec0495763", size = 232218 },
+ { url = "https://files.pythonhosted.org/packages/89/74/716d42058ef501e2c08f27aa3ff455f6fc1bbbd19a6ab8dea07e6322d217/rpds_py-0.25.1-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:ce4c8e485a3c59593f1a6f683cf0ea5ab1c1dc94d11eea5619e4fb5228b40fbd", size = 373475 },
+ { url = "https://files.pythonhosted.org/packages/e1/21/3faa9c523e2496a2505d7440b6f24c9166f37cb7ac027cac6cfbda9b4b5f/rpds_py-0.25.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:d8222acdb51a22929c3b2ddb236b69c59c72af4019d2cba961e2f9add9b6e634", size = 359349 },
+ { url = "https://files.pythonhosted.org/packages/6a/1c/c747fe568d21b1d679079b52b926ebc4d1497457510a1773dc5fd4b7b4e2/rpds_py-0.25.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4593c4eae9b27d22df41cde518b4b9e4464d139e4322e2127daa9b5b981b76be", size = 386526 },
+ { url = "https://files.pythonhosted.org/packages/0b/cc/4a41703de4fb291f13660fa3d882cbd39db5d60497c6e7fa7f5142e5e69f/rpds_py-0.25.1-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bd035756830c712b64725a76327ce80e82ed12ebab361d3a1cdc0f51ea21acb0", size = 400526 },
+ { url = "https://files.pythonhosted.org/packages/f1/78/60c980bedcad8418b614f0b4d6d420ecf11225b579cec0cb4e84d168b4da/rpds_py-0.25.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:114a07e85f32b125404f28f2ed0ba431685151c037a26032b213c882f26eb908", size = 525726 },
+ { url = "https://files.pythonhosted.org/packages/3f/37/f2f36b7f1314b3c3200d663decf2f8e29480492a39ab22447112aead4693/rpds_py-0.25.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dec21e02e6cc932538b5203d3a8bd6aa1480c98c4914cb88eea064ecdbc6396a", size = 412045 },
+ { url = "https://files.pythonhosted.org/packages/df/96/e03783e87a775b1242477ccbc35895f8e9b2bbdb60e199034a6da03c2687/rpds_py-0.25.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:09eab132f41bf792c7a0ea1578e55df3f3e7f61888e340779b06050a9a3f16e9", size = 386953 },
+ { url = "https://files.pythonhosted.org/packages/7c/7d/1418f4b69bfb4b40481a3d84782113ad7d4cca0b38ae70b982dd5b20102a/rpds_py-0.25.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c98f126c4fc697b84c423e387337d5b07e4a61e9feac494362a59fd7a2d9ed80", size = 421144 },
+ { url = "https://files.pythonhosted.org/packages/b3/0e/61469912c6493ee3808012e60f4930344b974fcb6b35c4348e70b6be7bc7/rpds_py-0.25.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:0e6a327af8ebf6baba1c10fadd04964c1965d375d318f4435d5f3f9651550f4a", size = 563730 },
+ { url = "https://files.pythonhosted.org/packages/f6/86/6d0a5cc56481ac61977b7c839677ed5c63d38cf0fcb3e2280843a8a6f476/rpds_py-0.25.1-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:bc120d1132cff853ff617754196d0ac0ae63befe7c8498bd67731ba368abe451", size = 592321 },
+ { url = "https://files.pythonhosted.org/packages/5d/87/d1e2453fe336f71e6aa296452a8c85c2118b587b1d25ce98014f75838a60/rpds_py-0.25.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:140f61d9bed7839446bdd44852e30195c8e520f81329b4201ceead4d64eb3a9f", size = 558162 },
+ { url = "https://files.pythonhosted.org/packages/ad/92/349f04b1644c5cef3e2e6c53b7168a28531945f9e6fca7425f6d20ddbc3c/rpds_py-0.25.1-cp39-cp39-win32.whl", hash = "sha256:9c006f3aadeda131b438c3092124bd196b66312f0caa5823ef09585a669cf449", size = 219920 },
+ { url = "https://files.pythonhosted.org/packages/f2/84/3969bef883a3f37ff2213795257cb7b7e93a115829670befb8de0e003031/rpds_py-0.25.1-cp39-cp39-win_amd64.whl", hash = "sha256:a61d0b2c7c9a0ae45732a77844917b427ff16ad5464b4d4f5e4adb955f582890", size = 231452 },
+ { url = "https://files.pythonhosted.org/packages/78/ff/566ce53529b12b4f10c0a348d316bd766970b7060b4fd50f888be3b3b281/rpds_py-0.25.1-pp310-pypy310_pp73-macosx_10_12_x86_64.whl", hash = "sha256:b24bf3cd93d5b6ecfbedec73b15f143596c88ee249fa98cefa9a9dc9d92c6f28", size = 373931 },
+ { url = "https://files.pythonhosted.org/packages/83/5d/deba18503f7c7878e26aa696e97f051175788e19d5336b3b0e76d3ef9256/rpds_py-0.25.1-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:0eb90e94f43e5085623932b68840b6f379f26db7b5c2e6bcef3179bd83c9330f", size = 359074 },
+ { url = "https://files.pythonhosted.org/packages/0d/74/313415c5627644eb114df49c56a27edba4d40cfd7c92bd90212b3604ca84/rpds_py-0.25.1-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d50e4864498a9ab639d6d8854b25e80642bd362ff104312d9770b05d66e5fb13", size = 387255 },
+ { url = "https://files.pythonhosted.org/packages/8c/c8/c723298ed6338963d94e05c0f12793acc9b91d04ed7c4ba7508e534b7385/rpds_py-0.25.1-pp310-pypy310_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7c9409b47ba0650544b0bb3c188243b83654dfe55dcc173a86832314e1a6a35d", size = 400714 },
+ { url = "https://files.pythonhosted.org/packages/33/8a/51f1f6aa653c2e110ed482ef2ae94140d56c910378752a1b483af11019ee/rpds_py-0.25.1-pp310-pypy310_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:796ad874c89127c91970652a4ee8b00d56368b7e00d3477f4415fe78164c8000", size = 523105 },
+ { url = "https://files.pythonhosted.org/packages/c7/a4/7873d15c088ad3bff36910b29ceb0f178e4b3232c2adbe9198de68a41e63/rpds_py-0.25.1-pp310-pypy310_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:85608eb70a659bf4c1142b2781083d4b7c0c4e2c90eff11856a9754e965b2540", size = 411499 },
+ { url = "https://files.pythonhosted.org/packages/90/f3/0ce1437befe1410766d11d08239333ac1b2d940f8a64234ce48a7714669c/rpds_py-0.25.1-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c4feb9211d15d9160bc85fa72fed46432cdc143eb9cf6d5ca377335a921ac37b", size = 387918 },
+ { url = "https://files.pythonhosted.org/packages/94/d4/5551247988b2a3566afb8a9dba3f1d4a3eea47793fd83000276c1a6c726e/rpds_py-0.25.1-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ccfa689b9246c48947d31dd9d8b16d89a0ecc8e0e26ea5253068efb6c542b76e", size = 421705 },
+ { url = "https://files.pythonhosted.org/packages/b0/25/5960f28f847bf736cc7ee3c545a7e1d2f3b5edaf82c96fb616c2f5ed52d0/rpds_py-0.25.1-pp310-pypy310_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:3c5b317ecbd8226887994852e85de562f7177add602514d4ac40f87de3ae45a8", size = 564489 },
+ { url = "https://files.pythonhosted.org/packages/02/66/1c99884a0d44e8c2904d3c4ec302f995292d5dde892c3bf7685ac1930146/rpds_py-0.25.1-pp310-pypy310_pp73-musllinux_1_2_i686.whl", hash = "sha256:454601988aab2c6e8fd49e7634c65476b2b919647626208e376afcd22019eeb8", size = 592557 },
+ { url = "https://files.pythonhosted.org/packages/55/ae/4aeac84ebeffeac14abb05b3bb1d2f728d00adb55d3fb7b51c9fa772e760/rpds_py-0.25.1-pp310-pypy310_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:1c0c434a53714358532d13539272db75a5ed9df75a4a090a753ac7173ec14e11", size = 558691 },
+ { url = "https://files.pythonhosted.org/packages/41/b3/728a08ff6f5e06fe3bb9af2e770e9d5fd20141af45cff8dfc62da4b2d0b3/rpds_py-0.25.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:f73ce1512e04fbe2bc97836e89830d6b4314c171587a99688082d090f934d20a", size = 231651 },
+ { url = "https://files.pythonhosted.org/packages/49/74/48f3df0715a585cbf5d34919c9c757a4c92c1a9eba059f2d334e72471f70/rpds_py-0.25.1-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:ee86d81551ec68a5c25373c5643d343150cc54672b5e9a0cafc93c1870a53954", size = 374208 },
+ { url = "https://files.pythonhosted.org/packages/55/b0/9b01bb11ce01ec03d05e627249cc2c06039d6aa24ea5a22a39c312167c10/rpds_py-0.25.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:89c24300cd4a8e4a51e55c31a8ff3918e6651b241ee8876a42cc2b2a078533ba", size = 359262 },
+ { url = "https://files.pythonhosted.org/packages/a9/eb/5395621618f723ebd5116c53282052943a726dba111b49cd2071f785b665/rpds_py-0.25.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:771c16060ff4e79584dc48902a91ba79fd93eade3aa3a12d6d2a4aadaf7d542b", size = 387366 },
+ { url = "https://files.pythonhosted.org/packages/68/73/3d51442bdb246db619d75039a50ea1cf8b5b4ee250c3e5cd5c3af5981cd4/rpds_py-0.25.1-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:785ffacd0ee61c3e60bdfde93baa6d7c10d86f15655bd706c89da08068dc5038", size = 400759 },
+ { url = "https://files.pythonhosted.org/packages/b7/4c/3a32d5955d7e6cb117314597bc0f2224efc798428318b13073efe306512a/rpds_py-0.25.1-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2a40046a529cc15cef88ac5ab589f83f739e2d332cb4d7399072242400ed68c9", size = 523128 },
+ { url = "https://files.pythonhosted.org/packages/be/95/1ffccd3b0bb901ae60b1dd4b1be2ab98bb4eb834cd9b15199888f5702f7b/rpds_py-0.25.1-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:85fc223d9c76cabe5d0bff82214459189720dc135db45f9f66aa7cffbf9ff6c1", size = 411597 },
+ { url = "https://files.pythonhosted.org/packages/ef/6d/6e6cd310180689db8b0d2de7f7d1eabf3fb013f239e156ae0d5a1a85c27f/rpds_py-0.25.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b0be9965f93c222fb9b4cc254235b3b2b215796c03ef5ee64f995b1b69af0762", size = 388053 },
+ { url = "https://files.pythonhosted.org/packages/4a/87/ec4186b1fe6365ced6fa470960e68fc7804bafbe7c0cf5a36237aa240efa/rpds_py-0.25.1-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8378fa4a940f3fb509c081e06cb7f7f2adae8cf46ef258b0e0ed7519facd573e", size = 421821 },
+ { url = "https://files.pythonhosted.org/packages/7a/60/84f821f6bf4e0e710acc5039d91f8f594fae0d93fc368704920d8971680d/rpds_py-0.25.1-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:33358883a4490287e67a2c391dfaea4d9359860281db3292b6886bf0be3d8692", size = 564534 },
+ { url = "https://files.pythonhosted.org/packages/41/3a/bc654eb15d3b38f9330fe0f545016ba154d89cdabc6177b0295910cd0ebe/rpds_py-0.25.1-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:1d1fadd539298e70cac2f2cb36f5b8a65f742b9b9f1014dd4ea1f7785e2470bf", size = 592674 },
+ { url = "https://files.pythonhosted.org/packages/2e/ba/31239736f29e4dfc7a58a45955c5db852864c306131fd6320aea214d5437/rpds_py-0.25.1-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:9a46c2fb2545e21181445515960006e85d22025bd2fe6db23e76daec6eb689fe", size = 558781 },
+ { url = "https://files.pythonhosted.org/packages/78/b2/198266f070c6760e0e8cd00f9f2b9c86133ceebbe7c6d114bdcfea200180/rpds_py-0.25.1-pp39-pypy39_pp73-macosx_10_12_x86_64.whl", hash = "sha256:50f2c501a89c9a5f4e454b126193c5495b9fb441a75b298c60591d8a2eb92e1b", size = 373973 },
+ { url = "https://files.pythonhosted.org/packages/13/79/1265eae618f88aa5d5e7122bd32dd41700bafe5a8bcea404e998848cd844/rpds_py-0.25.1-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:7d779b325cc8238227c47fbc53964c8cc9a941d5dbae87aa007a1f08f2f77b23", size = 359326 },
+ { url = "https://files.pythonhosted.org/packages/30/ab/6913b96f3ac072e87e76e45fe938263b0ab0d78b6b2cef3f2e56067befc0/rpds_py-0.25.1-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:036ded36bedb727beeabc16dc1dad7cb154b3fa444e936a03b67a86dc6a5066e", size = 387544 },
+ { url = "https://files.pythonhosted.org/packages/b0/23/129ed12d25229acc6deb8cbe90baadd8762e563c267c9594eb2fcc15be0c/rpds_py-0.25.1-pp39-pypy39_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:245550f5a1ac98504147cba96ffec8fabc22b610742e9150138e5d60774686d7", size = 400240 },
+ { url = "https://files.pythonhosted.org/packages/b5/e0/6811a38a5efa46b7ee6ed2103c95cb9abb16991544c3b69007aa679b6944/rpds_py-0.25.1-pp39-pypy39_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ff7c23ba0a88cb7b104281a99476cccadf29de2a0ef5ce864959a52675b1ca83", size = 525599 },
+ { url = "https://files.pythonhosted.org/packages/6c/10/2dc88bcaa0d86bdb59e017a330b1972ffeeb7f5061bb5a180c9a2bb73bbf/rpds_py-0.25.1-pp39-pypy39_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e37caa8cdb3b7cf24786451a0bdb853f6347b8b92005eeb64225ae1db54d1c2b", size = 411154 },
+ { url = "https://files.pythonhosted.org/packages/cf/d1/a72d522eb7d934fb33e9c501e6ecae00e2035af924d4ff37d964e9a3959b/rpds_py-0.25.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9f2f48ab00181600ee266a095fe815134eb456163f7d6699f525dee471f312cf", size = 388297 },
+ { url = "https://files.pythonhosted.org/packages/55/90/0dd7169ec74f042405b6b73512200d637a3088c156f64e1c07c18aa2fe59/rpds_py-0.25.1-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:9e5fc7484fa7dce57e25063b0ec9638ff02a908304f861d81ea49273e43838c1", size = 421894 },
+ { url = "https://files.pythonhosted.org/packages/37/e9/45170894add451783ed839c5c4a495e050aa8baa06d720364d9dff394dac/rpds_py-0.25.1-pp39-pypy39_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:d3c10228d6cf6fe2b63d2e7985e94f6916fa46940df46b70449e9ff9297bd3d1", size = 564409 },
+ { url = "https://files.pythonhosted.org/packages/59/d0/31cece9090e76fbdb50c758c165d40da604b03b37c3ba53f010bbfeb130a/rpds_py-0.25.1-pp39-pypy39_pp73-musllinux_1_2_i686.whl", hash = "sha256:5d9e40f32745db28c1ef7aad23f6fc458dc1e29945bd6781060f0d15628b8ddf", size = 592681 },
+ { url = "https://files.pythonhosted.org/packages/f1/4c/22ef535efb2beec614ba7be83e62b439eb83b0b0d7b1775e22d35af3f9b5/rpds_py-0.25.1-pp39-pypy39_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:35a8d1a24b5936b35c5003313bc177403d8bdef0f8b24f28b1c4a255f94ea992", size = 558744 },
+ { url = "https://files.pythonhosted.org/packages/79/ff/f2150efc8daf0581d4dfaf0a2a30b08088b6df900230ee5ae4f7c8cd5163/rpds_py-0.25.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:6099263f526efff9cf3883dfef505518730f7a7a93049b1d90d42e50a22b4793", size = 231305 },
+]
+
+[[package]]
+name = "ruff"
+version = "0.11.13"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ed/da/9c6f995903b4d9474b39da91d2d626659af3ff1eeb43e9ae7c119349dba6/ruff-0.11.13.tar.gz", hash = "sha256:26fa247dc68d1d4e72c179e08889a25ac0c7ba4d78aecfc835d49cbfd60bf514", size = 4282054 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7d/ce/a11d381192966e0b4290842cc8d4fac7dc9214ddf627c11c1afff87da29b/ruff-0.11.13-py3-none-linux_armv6l.whl", hash = "sha256:4bdfbf1240533f40042ec00c9e09a3aade6f8c10b6414cf11b519488d2635d46", size = 10292516 },
+ { url = "https://files.pythonhosted.org/packages/78/db/87c3b59b0d4e753e40b6a3b4a2642dfd1dcaefbff121ddc64d6c8b47ba00/ruff-0.11.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:aef9c9ed1b5ca28bb15c7eac83b8670cf3b20b478195bd49c8d756ba0a36cf48", size = 11106083 },
+ { url = "https://files.pythonhosted.org/packages/77/79/d8cec175856ff810a19825d09ce700265f905c643c69f45d2b737e4a470a/ruff-0.11.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:53b15a9dfdce029c842e9a5aebc3855e9ab7771395979ff85b7c1dedb53ddc2b", size = 10436024 },
+ { url = "https://files.pythonhosted.org/packages/8b/5b/f6d94f2980fa1ee854b41568368a2e1252681b9238ab2895e133d303538f/ruff-0.11.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab153241400789138d13f362c43f7edecc0edfffce2afa6a68434000ecd8f69a", size = 10646324 },
+ { url = "https://files.pythonhosted.org/packages/6c/9c/b4c2acf24ea4426016d511dfdc787f4ce1ceb835f3c5fbdbcb32b1c63bda/ruff-0.11.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c51f93029d54a910d3d24f7dd0bb909e31b6cd989a5e4ac513f4eb41629f0dc", size = 10174416 },
+ { url = "https://files.pythonhosted.org/packages/f3/10/e2e62f77c65ede8cd032c2ca39c41f48feabedb6e282bfd6073d81bb671d/ruff-0.11.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1808b3ed53e1a777c2ef733aca9051dc9bf7c99b26ece15cb59a0320fbdbd629", size = 11724197 },
+ { url = "https://files.pythonhosted.org/packages/bb/f0/466fe8469b85c561e081d798c45f8a1d21e0b4a5ef795a1d7f1a9a9ec182/ruff-0.11.13-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:d28ce58b5ecf0f43c1b71edffabe6ed7f245d5336b17805803312ec9bc665933", size = 12511615 },
+ { url = "https://files.pythonhosted.org/packages/17/0e/cefe778b46dbd0cbcb03a839946c8f80a06f7968eb298aa4d1a4293f3448/ruff-0.11.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55e4bc3a77842da33c16d55b32c6cac1ec5fb0fbec9c8c513bdce76c4f922165", size = 12117080 },
+ { url = "https://files.pythonhosted.org/packages/5d/2c/caaeda564cbe103bed145ea557cb86795b18651b0f6b3ff6a10e84e5a33f/ruff-0.11.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:633bf2c6f35678c56ec73189ba6fa19ff1c5e4807a78bf60ef487b9dd272cc71", size = 11326315 },
+ { url = "https://files.pythonhosted.org/packages/75/f0/782e7d681d660eda8c536962920c41309e6dd4ebcea9a2714ed5127d44bd/ruff-0.11.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ffbc82d70424b275b089166310448051afdc6e914fdab90e08df66c43bb5ca9", size = 11555640 },
+ { url = "https://files.pythonhosted.org/packages/5d/d4/3d580c616316c7f07fb3c99dbecfe01fbaea7b6fd9a82b801e72e5de742a/ruff-0.11.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4a9ddd3ec62a9a89578c85842b836e4ac832d4a2e0bfaad3b02243f930ceafcc", size = 10507364 },
+ { url = "https://files.pythonhosted.org/packages/5a/dc/195e6f17d7b3ea6b12dc4f3e9de575db7983db187c378d44606e5d503319/ruff-0.11.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d237a496e0778d719efb05058c64d28b757c77824e04ffe8796c7436e26712b7", size = 10141462 },
+ { url = "https://files.pythonhosted.org/packages/f4/8e/39a094af6967faa57ecdeacb91bedfb232474ff8c3d20f16a5514e6b3534/ruff-0.11.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:26816a218ca6ef02142343fd24c70f7cd8c5aa6c203bca284407adf675984432", size = 11121028 },
+ { url = "https://files.pythonhosted.org/packages/5a/c0/b0b508193b0e8a1654ec683ebab18d309861f8bd64e3a2f9648b80d392cb/ruff-0.11.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:51c3f95abd9331dc5b87c47ac7f376db5616041173826dfd556cfe3d4977f492", size = 11602992 },
+ { url = "https://files.pythonhosted.org/packages/7c/91/263e33ab93ab09ca06ce4f8f8547a858cc198072f873ebc9be7466790bae/ruff-0.11.13-py3-none-win32.whl", hash = "sha256:96c27935418e4e8e77a26bb05962817f28b8ef3843a6c6cc49d8783b5507f250", size = 10474944 },
+ { url = "https://files.pythonhosted.org/packages/46/f4/7c27734ac2073aae8efb0119cae6931b6fb48017adf048fdf85c19337afc/ruff-0.11.13-py3-none-win_amd64.whl", hash = "sha256:29c3189895a8a6a657b7af4e97d330c8a3afd2c9c8f46c81e2fc5a31866517e3", size = 11548669 },
+ { url = "https://files.pythonhosted.org/packages/ec/bf/b273dd11673fed8a6bd46032c0ea2a04b2ac9bfa9c628756a5856ba113b0/ruff-0.11.13-py3-none-win_arm64.whl", hash = "sha256:b4385285e9179d608ff1d2fb9922062663c658605819a6876d8beef0c30b7f3b", size = 10683928 },
+]
+
+[[package]]
+name = "s3transfer"
+version = "0.1.13"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "botocore", version = "1.10.84", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9a/66/c6a5ae4dbbaf253bd662921b805e4972451a6d214d0dc9fb3300cb642320/s3transfer-0.1.13.tar.gz", hash = "sha256:90dc18e028989c609146e241ea153250be451e05ecc0c2832565231dacdf59c1", size = 103335 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d7/14/2a0004d487464d120c9fb85313a75cd3d71a7506955be458eebfe19a6b1d/s3transfer-0.1.13-py2.py3-none-any.whl", hash = "sha256:c7a9ec356982d5e9ab2d4b46391a7d6a950e2b04c472419f5fdec70cc0ada72f", size = 59642 },
+]
+
+[[package]]
+name = "s3transfer"
+version = "0.13.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "botocore", version = "1.38.36", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ed/5d/9dcc100abc6711e8247af5aa561fc07c4a046f72f659c3adea9a449e191a/s3transfer-0.13.0.tar.gz", hash = "sha256:f5e6db74eb7776a37208001113ea7aa97695368242b364d73e91c981ac522177", size = 150232 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/17/22bf8155aa0ea2305eefa3a6402e040df7ebe512d1310165eda1e233c3f8/s3transfer-0.13.0-py3-none-any.whl", hash = "sha256:0148ef34d6dd964d0d8cf4311b2b21c474693e57c2e069ec708ce043d2b527be", size = 85152 },
+]
+
+[[package]]
+name = "safetensors"
+version = "0.5.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/71/7e/2d5d6ee7b40c0682315367ec7475693d110f512922d582fef1bd4a63adc3/safetensors-0.5.3.tar.gz", hash = "sha256:b6b0d6ecacec39a4fdd99cc19f4576f5219ce858e6fd8dbe7609df0b8dc56965", size = 67210 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/ae/88f6c49dbd0cc4da0e08610019a3c78a7d390879a919411a410a1876d03a/safetensors-0.5.3-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:bd20eb133db8ed15b40110b7c00c6df51655a2998132193de2f75f72d99c7073", size = 436917 },
+ { url = "https://files.pythonhosted.org/packages/b8/3b/11f1b4a2f5d2ab7da34ecc062b0bc301f2be024d110a6466726bec8c055c/safetensors-0.5.3-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:21d01c14ff6c415c485616b8b0bf961c46b3b343ca59110d38d744e577f9cce7", size = 418419 },
+ { url = "https://files.pythonhosted.org/packages/5d/9a/add3e6fef267658075c5a41573c26d42d80c935cdc992384dfae435feaef/safetensors-0.5.3-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11bce6164887cd491ca75c2326a113ba934be596e22b28b1742ce27b1d076467", size = 459493 },
+ { url = "https://files.pythonhosted.org/packages/df/5c/bf2cae92222513cc23b3ff85c4a1bb2811a2c3583ac0f8e8d502751de934/safetensors-0.5.3-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4a243be3590bc3301c821da7a18d87224ef35cbd3e5f5727e4e0728b8172411e", size = 472400 },
+ { url = "https://files.pythonhosted.org/packages/58/11/7456afb740bd45782d0f4c8e8e1bb9e572f1bf82899fb6ace58af47b4282/safetensors-0.5.3-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8bd84b12b1670a6f8e50f01e28156422a2bc07fb16fc4e98bded13039d688a0d", size = 522891 },
+ { url = "https://files.pythonhosted.org/packages/57/3d/fe73a9d2ace487e7285f6e157afee2383bd1ddb911b7cb44a55cf812eae3/safetensors-0.5.3-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:391ac8cab7c829452175f871fcaf414aa1e292b5448bd02620f675a7f3e7abb9", size = 537694 },
+ { url = "https://files.pythonhosted.org/packages/a6/f8/dae3421624fcc87a89d42e1898a798bc7ff72c61f38973a65d60df8f124c/safetensors-0.5.3-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cead1fa41fc54b1e61089fa57452e8834f798cb1dc7a09ba3524f1eb08e0317a", size = 471642 },
+ { url = "https://files.pythonhosted.org/packages/ce/20/1fbe16f9b815f6c5a672f5b760951e20e17e43f67f231428f871909a37f6/safetensors-0.5.3-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1077f3e94182d72618357b04b5ced540ceb71c8a813d3319f1aba448e68a770d", size = 502241 },
+ { url = "https://files.pythonhosted.org/packages/5f/18/8e108846b506487aa4629fe4116b27db65c3dde922de2c8e0cc1133f3f29/safetensors-0.5.3-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:799021e78287bac619c7b3f3606730a22da4cda27759ddf55d37c8db7511c74b", size = 638001 },
+ { url = "https://files.pythonhosted.org/packages/82/5a/c116111d8291af6c8c8a8b40628fe833b9db97d8141c2a82359d14d9e078/safetensors-0.5.3-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:df26da01aaac504334644e1b7642fa000bfec820e7cef83aeac4e355e03195ff", size = 734013 },
+ { url = "https://files.pythonhosted.org/packages/7d/ff/41fcc4d3b7de837963622e8610d998710705bbde9a8a17221d85e5d0baad/safetensors-0.5.3-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:32c3ef2d7af8b9f52ff685ed0bc43913cdcde135089ae322ee576de93eae5135", size = 670687 },
+ { url = "https://files.pythonhosted.org/packages/40/ad/2b113098e69c985a3d8fbda4b902778eae4a35b7d5188859b4a63d30c161/safetensors-0.5.3-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:37f1521be045e56fc2b54c606d4455573e717b2d887c579ee1dbba5f868ece04", size = 643147 },
+ { url = "https://files.pythonhosted.org/packages/0a/0c/95aeb51d4246bd9a3242d3d8349c1112b4ee7611a4b40f0c5c93b05f001d/safetensors-0.5.3-cp38-abi3-win32.whl", hash = "sha256:cfc0ec0846dcf6763b0ed3d1846ff36008c6e7290683b61616c4b040f6a54ace", size = 296677 },
+ { url = "https://files.pythonhosted.org/packages/69/e2/b011c38e5394c4c18fb5500778a55ec43ad6106126e74723ffaee246f56e/safetensors-0.5.3-cp38-abi3-win_amd64.whl", hash = "sha256:836cbbc320b47e80acd40e44c8682db0e8ad7123209f69b093def21ec7cafd11", size = 308878 },
+]
+
+[[package]]
+name = "scikit-learn"
+version = "1.6.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "joblib", marker = "python_full_version < '3.10'" },
+ { name = "numpy", marker = "python_full_version < '3.10'" },
+ { name = "scipy", version = "1.13.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "threadpoolctl", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9e/a5/4ae3b3a0755f7b35a280ac90b28817d1f380318973cff14075ab41ef50d9/scikit_learn-1.6.1.tar.gz", hash = "sha256:b4fc2525eca2c69a59260f583c56a7557c6ccdf8deafdba6e060f94c1c59738e", size = 7068312 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/3a/f4597eb41049110b21ebcbb0bcb43e4035017545daa5eedcfeb45c08b9c5/scikit_learn-1.6.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d056391530ccd1e501056160e3c9673b4da4805eb67eb2bdf4e983e1f9c9204e", size = 12067702 },
+ { url = "https://files.pythonhosted.org/packages/37/19/0423e5e1fd1c6ec5be2352ba05a537a473c1677f8188b9306097d684b327/scikit_learn-1.6.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:0c8d036eb937dbb568c6242fa598d551d88fb4399c0344d95c001980ec1c7d36", size = 11112765 },
+ { url = "https://files.pythonhosted.org/packages/70/95/d5cb2297a835b0f5fc9a77042b0a2d029866379091ab8b3f52cc62277808/scikit_learn-1.6.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8634c4bd21a2a813e0a7e3900464e6d593162a29dd35d25bdf0103b3fce60ed5", size = 12643991 },
+ { url = "https://files.pythonhosted.org/packages/b7/91/ab3c697188f224d658969f678be86b0968ccc52774c8ab4a86a07be13c25/scikit_learn-1.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:775da975a471c4f6f467725dff0ced5c7ac7bda5e9316b260225b48475279a1b", size = 13497182 },
+ { url = "https://files.pythonhosted.org/packages/17/04/d5d556b6c88886c092cc989433b2bab62488e0f0dafe616a1d5c9cb0efb1/scikit_learn-1.6.1-cp310-cp310-win_amd64.whl", hash = "sha256:8a600c31592bd7dab31e1c61b9bbd6dea1b3433e67d264d17ce1017dbdce8002", size = 11125517 },
+ { url = "https://files.pythonhosted.org/packages/6c/2a/e291c29670795406a824567d1dfc91db7b699799a002fdaa452bceea8f6e/scikit_learn-1.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:72abc587c75234935e97d09aa4913a82f7b03ee0b74111dcc2881cba3c5a7b33", size = 12102620 },
+ { url = "https://files.pythonhosted.org/packages/25/92/ee1d7a00bb6b8c55755d4984fd82608603a3cc59959245068ce32e7fb808/scikit_learn-1.6.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:b3b00cdc8f1317b5f33191df1386c0befd16625f49d979fe77a8d44cae82410d", size = 11116234 },
+ { url = "https://files.pythonhosted.org/packages/30/cd/ed4399485ef364bb25f388ab438e3724e60dc218c547a407b6e90ccccaef/scikit_learn-1.6.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dc4765af3386811c3ca21638f63b9cf5ecf66261cc4815c1db3f1e7dc7b79db2", size = 12592155 },
+ { url = "https://files.pythonhosted.org/packages/a8/f3/62fc9a5a659bb58a03cdd7e258956a5824bdc9b4bb3c5d932f55880be569/scikit_learn-1.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:25fc636bdaf1cc2f4a124a116312d837148b5e10872147bdaf4887926b8c03d8", size = 13497069 },
+ { url = "https://files.pythonhosted.org/packages/a1/a6/c5b78606743a1f28eae8f11973de6613a5ee87366796583fb74c67d54939/scikit_learn-1.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:fa909b1a36e000a03c382aade0bd2063fd5680ff8b8e501660c0f59f021a6415", size = 11139809 },
+ { url = "https://files.pythonhosted.org/packages/0a/18/c797c9b8c10380d05616db3bfb48e2a3358c767affd0857d56c2eb501caa/scikit_learn-1.6.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:926f207c804104677af4857b2c609940b743d04c4c35ce0ddc8ff4f053cddc1b", size = 12104516 },
+ { url = "https://files.pythonhosted.org/packages/c4/b7/2e35f8e289ab70108f8cbb2e7a2208f0575dc704749721286519dcf35f6f/scikit_learn-1.6.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:2c2cae262064e6a9b77eee1c8e768fc46aa0b8338c6a8297b9b6759720ec0ff2", size = 11167837 },
+ { url = "https://files.pythonhosted.org/packages/a4/f6/ff7beaeb644bcad72bcfd5a03ff36d32ee4e53a8b29a639f11bcb65d06cd/scikit_learn-1.6.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1061b7c028a8663fb9a1a1baf9317b64a257fcb036dae5c8752b2abef31d136f", size = 12253728 },
+ { url = "https://files.pythonhosted.org/packages/29/7a/8bce8968883e9465de20be15542f4c7e221952441727c4dad24d534c6d99/scikit_learn-1.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2e69fab4ebfc9c9b580a7a80111b43d214ab06250f8a7ef590a4edf72464dd86", size = 13147700 },
+ { url = "https://files.pythonhosted.org/packages/62/27/585859e72e117fe861c2079bcba35591a84f801e21bc1ab85bce6ce60305/scikit_learn-1.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:70b1d7e85b1c96383f872a519b3375f92f14731e279a7b4c6cfd650cf5dffc52", size = 11110613 },
+ { url = "https://files.pythonhosted.org/packages/2e/59/8eb1872ca87009bdcdb7f3cdc679ad557b992c12f4b61f9250659e592c63/scikit_learn-1.6.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2ffa1e9e25b3d93990e74a4be2c2fc61ee5af85811562f1288d5d055880c4322", size = 12010001 },
+ { url = "https://files.pythonhosted.org/packages/9d/05/f2fc4effc5b32e525408524c982c468c29d22f828834f0625c5ef3d601be/scikit_learn-1.6.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:dc5cf3d68c5a20ad6d571584c0750ec641cc46aeef1c1507be51300e6003a7e1", size = 11096360 },
+ { url = "https://files.pythonhosted.org/packages/c8/e4/4195d52cf4f113573fb8ebc44ed5a81bd511a92c0228889125fac2f4c3d1/scikit_learn-1.6.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c06beb2e839ecc641366000ca84f3cf6fa9faa1777e29cf0c04be6e4d096a348", size = 12209004 },
+ { url = "https://files.pythonhosted.org/packages/94/be/47e16cdd1e7fcf97d95b3cb08bde1abb13e627861af427a3651fcb80b517/scikit_learn-1.6.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e8ca8cb270fee8f1f76fa9bfd5c3507d60c6438bbee5687f81042e2bb98e5a97", size = 13171776 },
+ { url = "https://files.pythonhosted.org/packages/34/b0/ca92b90859070a1487827dbc672f998da95ce83edce1270fc23f96f1f61a/scikit_learn-1.6.1-cp313-cp313-win_amd64.whl", hash = "sha256:7a1c43c8ec9fde528d664d947dc4c0789be4077a3647f232869f41d9bf50e0fb", size = 11071865 },
+ { url = "https://files.pythonhosted.org/packages/12/ae/993b0fb24a356e71e9a894e42b8a9eec528d4c70217353a1cd7a48bc25d4/scikit_learn-1.6.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:a17c1dea1d56dcda2fac315712f3651a1fea86565b64b48fa1bc090249cbf236", size = 11955804 },
+ { url = "https://files.pythonhosted.org/packages/d6/54/32fa2ee591af44507eac86406fa6bba968d1eb22831494470d0a2e4a1eb1/scikit_learn-1.6.1-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6a7aa5f9908f0f28f4edaa6963c0a6183f1911e63a69aa03782f0d924c830a35", size = 11100530 },
+ { url = "https://files.pythonhosted.org/packages/3f/58/55856da1adec655bdce77b502e94a267bf40a8c0b89f8622837f89503b5a/scikit_learn-1.6.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0650e730afb87402baa88afbf31c07b84c98272622aaba002559b614600ca691", size = 12433852 },
+ { url = "https://files.pythonhosted.org/packages/ff/4f/c83853af13901a574f8f13b645467285a48940f185b690936bb700a50863/scikit_learn-1.6.1-cp313-cp313t-win_amd64.whl", hash = "sha256:3f59fe08dc03ea158605170eb52b22a105f238a5d512c4470ddeca71feae8e5f", size = 11337256 },
+ { url = "https://files.pythonhosted.org/packages/d2/37/b305b759cc65829fe1b8853ff3e308b12cdd9d8884aa27840835560f2b42/scikit_learn-1.6.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6849dd3234e87f55dce1db34c89a810b489ead832aaf4d4550b7ea85628be6c1", size = 12101868 },
+ { url = "https://files.pythonhosted.org/packages/83/74/f64379a4ed5879d9db744fe37cfe1978c07c66684d2439c3060d19a536d8/scikit_learn-1.6.1-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:e7be3fa5d2eb9be7d77c3734ff1d599151bb523674be9b834e8da6abe132f44e", size = 11144062 },
+ { url = "https://files.pythonhosted.org/packages/fd/dc/d5457e03dc9c971ce2b0d750e33148dd060fefb8b7dc71acd6054e4bb51b/scikit_learn-1.6.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:44a17798172df1d3c1065e8fcf9019183f06c87609b49a124ebdf57ae6cb0107", size = 12693173 },
+ { url = "https://files.pythonhosted.org/packages/79/35/b1d2188967c3204c78fa79c9263668cf1b98060e8e58d1a730fe5b2317bb/scikit_learn-1.6.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8b7a3b86e411e4bce21186e1c180d792f3d99223dcfa3b4f597ecc92fa1a422", size = 13518605 },
+ { url = "https://files.pythonhosted.org/packages/fb/d8/8d603bdd26601f4b07e2363032b8565ab82eb857f93d86d0f7956fcf4523/scikit_learn-1.6.1-cp39-cp39-win_amd64.whl", hash = "sha256:7a73d457070e3318e32bdb3aa79a8d990474f19035464dfd8bede2883ab5dc3b", size = 11155078 },
+]
+
+[[package]]
+name = "scikit-learn"
+version = "1.7.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "joblib", marker = "python_full_version >= '3.10'" },
+ { name = "numpy", marker = "python_full_version >= '3.10'" },
+ { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "threadpoolctl", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/df/3b/29fa87e76b1d7b3b77cc1fcbe82e6e6b8cd704410705b008822de530277c/scikit_learn-1.7.0.tar.gz", hash = "sha256:c01e869b15aec88e2cdb73d27f15bdbe03bce8e2fb43afbe77c45d399e73a5a3", size = 7178217 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a4/70/e725b1da11e7e833f558eb4d3ea8b7ed7100edda26101df074f1ae778235/scikit_learn-1.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9fe7f51435f49d97bd41d724bb3e11eeb939882af9c29c931a8002c357e8cdd5", size = 11728006 },
+ { url = "https://files.pythonhosted.org/packages/32/aa/43874d372e9dc51eb361f5c2f0a4462915c9454563b3abb0d9457c66b7e9/scikit_learn-1.7.0-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:d0c93294e1e1acbee2d029b1f2a064f26bd928b284938d51d412c22e0c977eb3", size = 10726255 },
+ { url = "https://files.pythonhosted.org/packages/f5/1a/da73cc18e00f0b9ae89f7e4463a02fb6e0569778120aeab138d9554ecef0/scikit_learn-1.7.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bf3755f25f145186ad8c403312f74fb90df82a4dfa1af19dc96ef35f57237a94", size = 12205657 },
+ { url = "https://files.pythonhosted.org/packages/fb/f6/800cb3243dd0137ca6d98df8c9d539eb567ba0a0a39ecd245c33fab93510/scikit_learn-1.7.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2726c8787933add436fb66fb63ad18e8ef342dfb39bbbd19dc1e83e8f828a85a", size = 12877290 },
+ { url = "https://files.pythonhosted.org/packages/4c/bd/99c3ccb49946bd06318fe194a1c54fb7d57ac4fe1c2f4660d86b3a2adf64/scikit_learn-1.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:e2539bb58886a531b6e86a510c0348afaadd25005604ad35966a85c2ec378800", size = 10713211 },
+ { url = "https://files.pythonhosted.org/packages/5a/42/c6b41711c2bee01c4800ad8da2862c0b6d2956a399d23ce4d77f2ca7f0c7/scikit_learn-1.7.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8ef09b1615e1ad04dc0d0054ad50634514818a8eb3ee3dee99af3bffc0ef5007", size = 11719657 },
+ { url = "https://files.pythonhosted.org/packages/a3/24/44acca76449e391b6b2522e67a63c0454b7c1f060531bdc6d0118fb40851/scikit_learn-1.7.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:7d7240c7b19edf6ed93403f43b0fcb0fe95b53bc0b17821f8fb88edab97085ef", size = 10712636 },
+ { url = "https://files.pythonhosted.org/packages/9f/1b/fcad1ccb29bdc9b96bcaa2ed8345d56afb77b16c0c47bafe392cc5d1d213/scikit_learn-1.7.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:80bd3bd4e95381efc47073a720d4cbab485fc483966f1709f1fd559afac57ab8", size = 12242817 },
+ { url = "https://files.pythonhosted.org/packages/c6/38/48b75c3d8d268a3f19837cb8a89155ead6e97c6892bb64837183ea41db2b/scikit_learn-1.7.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9dbe48d69aa38ecfc5a6cda6c5df5abef0c0ebdb2468e92437e2053f84abb8bc", size = 12873961 },
+ { url = "https://files.pythonhosted.org/packages/f4/5a/ba91b8c57aa37dbd80d5ff958576a9a8c14317b04b671ae7f0d09b00993a/scikit_learn-1.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:8fa979313b2ffdfa049ed07252dc94038def3ecd49ea2a814db5401c07f1ecfa", size = 10717277 },
+ { url = "https://files.pythonhosted.org/packages/70/3a/bffab14e974a665a3ee2d79766e7389572ffcaad941a246931c824afcdb2/scikit_learn-1.7.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c2c7243d34aaede0efca7a5a96d67fddaebb4ad7e14a70991b9abee9dc5c0379", size = 11646758 },
+ { url = "https://files.pythonhosted.org/packages/58/d8/f3249232fa79a70cb40595282813e61453c1e76da3e1a44b77a63dd8d0cb/scikit_learn-1.7.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:9f39f6a811bf3f15177b66c82cbe0d7b1ebad9f190737dcdef77cfca1ea3c19c", size = 10673971 },
+ { url = "https://files.pythonhosted.org/packages/67/93/eb14c50533bea2f77758abe7d60a10057e5f2e2cdcf0a75a14c6bc19c734/scikit_learn-1.7.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:63017a5f9a74963d24aac7590287149a8d0f1a0799bbe7173c0d8ba1523293c0", size = 11818428 },
+ { url = "https://files.pythonhosted.org/packages/08/17/804cc13b22a8663564bb0b55fb89e661a577e4e88a61a39740d58b909efe/scikit_learn-1.7.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b2f8a0b1e73e9a08b7cc498bb2aeab36cdc1f571f8ab2b35c6e5d1c7115d97d", size = 12505887 },
+ { url = "https://files.pythonhosted.org/packages/68/c7/4e956281a077f4835458c3f9656c666300282d5199039f26d9de1dabd9be/scikit_learn-1.7.0-cp312-cp312-win_amd64.whl", hash = "sha256:34cc8d9d010d29fb2b7cbcd5ccc24ffdd80515f65fe9f1e4894ace36b267ce19", size = 10668129 },
+ { url = "https://files.pythonhosted.org/packages/9a/c3/a85dcccdaf1e807e6f067fa95788a6485b0491d9ea44fd4c812050d04f45/scikit_learn-1.7.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5b7974f1f32bc586c90145df51130e02267e4b7e77cab76165c76cf43faca0d9", size = 11559841 },
+ { url = "https://files.pythonhosted.org/packages/d8/57/eea0de1562cc52d3196eae51a68c5736a31949a465f0b6bb3579b2d80282/scikit_learn-1.7.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:014e07a23fe02e65f9392898143c542a50b6001dbe89cb867e19688e468d049b", size = 10616463 },
+ { url = "https://files.pythonhosted.org/packages/10/a4/39717ca669296dfc3a62928393168da88ac9d8cbec88b6321ffa62c6776f/scikit_learn-1.7.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e7e7ced20582d3a5516fb6f405fd1d254e1f5ce712bfef2589f51326af6346e8", size = 11766512 },
+ { url = "https://files.pythonhosted.org/packages/d5/cd/a19722241d5f7b51e08351e1e82453e0057aeb7621b17805f31fcb57bb6c/scikit_learn-1.7.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1babf2511e6ffd695da7a983b4e4d6de45dce39577b26b721610711081850906", size = 12461075 },
+ { url = "https://files.pythonhosted.org/packages/f3/bc/282514272815c827a9acacbe5b99f4f1a4bc5961053719d319480aee0812/scikit_learn-1.7.0-cp313-cp313-win_amd64.whl", hash = "sha256:5abd2acff939d5bd4701283f009b01496832d50ddafa83c90125a4e41c33e314", size = 10652517 },
+ { url = "https://files.pythonhosted.org/packages/ea/78/7357d12b2e4c6674175f9a09a3ba10498cde8340e622715bcc71e532981d/scikit_learn-1.7.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:e39d95a929b112047c25b775035c8c234c5ca67e681ce60d12413afb501129f7", size = 12111822 },
+ { url = "https://files.pythonhosted.org/packages/d0/0c/9c3715393343f04232f9d81fe540eb3831d0b4ec351135a145855295110f/scikit_learn-1.7.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:0521cb460426c56fee7e07f9365b0f45ec8ca7b2d696534ac98bfb85e7ae4775", size = 11325286 },
+ { url = "https://files.pythonhosted.org/packages/64/e0/42282ad3dd70b7c1a5f65c412ac3841f6543502a8d6263cae7b466612dc9/scikit_learn-1.7.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:317ca9f83acbde2883bd6bb27116a741bfcb371369706b4f9973cf30e9a03b0d", size = 12380865 },
+ { url = "https://files.pythonhosted.org/packages/4e/d0/3ef4ab2c6be4aa910445cd09c5ef0b44512e3de2cfb2112a88bb647d2cf7/scikit_learn-1.7.0-cp313-cp313t-win_amd64.whl", hash = "sha256:126c09740a6f016e815ab985b21e3a0656835414521c81fc1a8da78b679bdb75", size = 11549609 },
+]
+
+[[package]]
+name = "scipy"
+version = "1.13.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10' and platform_python_implementation != 'PyPy'",
+ "python_full_version < '3.10' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "numpy", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ae/00/48c2f661e2816ccf2ecd77982f6605b2950afe60f60a52b4cbbc2504aa8f/scipy-1.13.1.tar.gz", hash = "sha256:095a87a0312b08dfd6a6155cbbd310a8c51800fc931b8c0b84003014b874ed3c", size = 57210720 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/33/59/41b2529908c002ade869623b87eecff3e11e3ce62e996d0bdcb536984187/scipy-1.13.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:20335853b85e9a49ff7572ab453794298bcf0354d8068c5f6775a0eabf350aca", size = 39328076 },
+ { url = "https://files.pythonhosted.org/packages/d5/33/f1307601f492f764062ce7dd471a14750f3360e33cd0f8c614dae208492c/scipy-1.13.1-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:d605e9c23906d1994f55ace80e0125c587f96c020037ea6aa98d01b4bd2e222f", size = 30306232 },
+ { url = "https://files.pythonhosted.org/packages/c0/66/9cd4f501dd5ea03e4a4572ecd874936d0da296bd04d1c45ae1a4a75d9c3a/scipy-1.13.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cfa31f1def5c819b19ecc3a8b52d28ffdcc7ed52bb20c9a7589669dd3c250989", size = 33743202 },
+ { url = "https://files.pythonhosted.org/packages/a3/ba/7255e5dc82a65adbe83771c72f384d99c43063648456796436c9a5585ec3/scipy-1.13.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f26264b282b9da0952a024ae34710c2aff7d27480ee91a2e82b7b7073c24722f", size = 38577335 },
+ { url = "https://files.pythonhosted.org/packages/49/a5/bb9ded8326e9f0cdfdc412eeda1054b914dfea952bda2097d174f8832cc0/scipy-1.13.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:eccfa1906eacc02de42d70ef4aecea45415f5be17e72b61bafcfd329bdc52e94", size = 38820728 },
+ { url = "https://files.pythonhosted.org/packages/12/30/df7a8fcc08f9b4a83f5f27cfaaa7d43f9a2d2ad0b6562cced433e5b04e31/scipy-1.13.1-cp310-cp310-win_amd64.whl", hash = "sha256:2831f0dc9c5ea9edd6e51e6e769b655f08ec6db6e2e10f86ef39bd32eb11da54", size = 46210588 },
+ { url = "https://files.pythonhosted.org/packages/b4/15/4a4bb1b15bbd2cd2786c4f46e76b871b28799b67891f23f455323a0cdcfb/scipy-1.13.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:27e52b09c0d3a1d5b63e1105f24177e544a222b43611aaf5bc44d4a0979e32f9", size = 39333805 },
+ { url = "https://files.pythonhosted.org/packages/ba/92/42476de1af309c27710004f5cdebc27bec62c204db42e05b23a302cb0c9a/scipy-1.13.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:54f430b00f0133e2224c3ba42b805bfd0086fe488835effa33fa291561932326", size = 30317687 },
+ { url = "https://files.pythonhosted.org/packages/80/ba/8be64fe225360a4beb6840f3cbee494c107c0887f33350d0a47d55400b01/scipy-1.13.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e89369d27f9e7b0884ae559a3a956e77c02114cc60a6058b4e5011572eea9299", size = 33694638 },
+ { url = "https://files.pythonhosted.org/packages/36/07/035d22ff9795129c5a847c64cb43c1fa9188826b59344fee28a3ab02e283/scipy-1.13.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a78b4b3345f1b6f68a763c6e25c0c9a23a9fd0f39f5f3d200efe8feda560a5fa", size = 38569931 },
+ { url = "https://files.pythonhosted.org/packages/d9/10/f9b43de37e5ed91facc0cfff31d45ed0104f359e4f9a68416cbf4e790241/scipy-1.13.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:45484bee6d65633752c490404513b9ef02475b4284c4cfab0ef946def50b3f59", size = 38838145 },
+ { url = "https://files.pythonhosted.org/packages/4a/48/4513a1a5623a23e95f94abd675ed91cfb19989c58e9f6f7d03990f6caf3d/scipy-1.13.1-cp311-cp311-win_amd64.whl", hash = "sha256:5713f62f781eebd8d597eb3f88b8bf9274e79eeabf63afb4a737abc6c84ad37b", size = 46196227 },
+ { url = "https://files.pythonhosted.org/packages/f2/7b/fb6b46fbee30fc7051913068758414f2721003a89dd9a707ad49174e3843/scipy-1.13.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:5d72782f39716b2b3509cd7c33cdc08c96f2f4d2b06d51e52fb45a19ca0c86a1", size = 39357301 },
+ { url = "https://files.pythonhosted.org/packages/dc/5a/2043a3bde1443d94014aaa41e0b50c39d046dda8360abd3b2a1d3f79907d/scipy-1.13.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:017367484ce5498445aade74b1d5ab377acdc65e27095155e448c88497755a5d", size = 30363348 },
+ { url = "https://files.pythonhosted.org/packages/e7/cb/26e4a47364bbfdb3b7fb3363be6d8a1c543bcd70a7753ab397350f5f189a/scipy-1.13.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:949ae67db5fa78a86e8fa644b9a6b07252f449dcf74247108c50e1d20d2b4627", size = 33406062 },
+ { url = "https://files.pythonhosted.org/packages/88/ab/6ecdc526d509d33814835447bbbeedbebdec7cca46ef495a61b00a35b4bf/scipy-1.13.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:de3ade0e53bc1f21358aa74ff4830235d716211d7d077e340c7349bc3542e884", size = 38218311 },
+ { url = "https://files.pythonhosted.org/packages/0b/00/9f54554f0f8318100a71515122d8f4f503b1a2c4b4cfab3b4b68c0eb08fa/scipy-1.13.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:2ac65fb503dad64218c228e2dc2d0a0193f7904747db43014645ae139c8fad16", size = 38442493 },
+ { url = "https://files.pythonhosted.org/packages/3e/df/963384e90733e08eac978cd103c34df181d1fec424de383cdc443f418dd4/scipy-1.13.1-cp312-cp312-win_amd64.whl", hash = "sha256:cdd7dacfb95fea358916410ec61bbc20440f7860333aee6d882bb8046264e949", size = 45910955 },
+ { url = "https://files.pythonhosted.org/packages/7f/29/c2ea58c9731b9ecb30b6738113a95d147e83922986b34c685b8f6eefde21/scipy-1.13.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:436bbb42a94a8aeef855d755ce5a465479c721e9d684de76bf61a62e7c2b81d5", size = 39352927 },
+ { url = "https://files.pythonhosted.org/packages/5c/c0/e71b94b20ccf9effb38d7147c0064c08c622309fd487b1b677771a97d18c/scipy-1.13.1-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:8335549ebbca860c52bf3d02f80784e91a004b71b059e3eea9678ba994796a24", size = 30324538 },
+ { url = "https://files.pythonhosted.org/packages/6d/0f/aaa55b06d474817cea311e7b10aab2ea1fd5d43bc6a2861ccc9caec9f418/scipy-1.13.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d533654b7d221a6a97304ab63c41c96473ff04459e404b83275b60aa8f4b7004", size = 33732190 },
+ { url = "https://files.pythonhosted.org/packages/35/f5/d0ad1a96f80962ba65e2ce1de6a1e59edecd1f0a7b55990ed208848012e0/scipy-1.13.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:637e98dcf185ba7f8e663e122ebf908c4702420477ae52a04f9908707456ba4d", size = 38612244 },
+ { url = "https://files.pythonhosted.org/packages/8d/02/1165905f14962174e6569076bcc3315809ae1291ed14de6448cc151eedfd/scipy-1.13.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a014c2b3697bde71724244f63de2476925596c24285c7a637364761f8710891c", size = 38845637 },
+ { url = "https://files.pythonhosted.org/packages/3e/77/dab54fe647a08ee4253963bcd8f9cf17509c8ca64d6335141422fe2e2114/scipy-1.13.1-cp39-cp39-win_amd64.whl", hash = "sha256:392e4ec766654852c25ebad4f64e4e584cf19820b980bc04960bca0b0cd6eaa2", size = 46227440 },
+]
+
+[[package]]
+name = "scipy"
+version = "1.15.3"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.12' and platform_python_implementation != 'PyPy'",
+ "python_full_version >= '3.12' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.11.*' and platform_python_implementation == 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation != 'PyPy'",
+ "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
+]
+dependencies = [
+ { name = "numpy", marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/78/2f/4966032c5f8cc7e6a60f1b2e0ad686293b9474b65246b0c642e3ef3badd0/scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c", size = 38702770 },
+ { url = "https://files.pythonhosted.org/packages/a0/6e/0c3bf90fae0e910c274db43304ebe25a6b391327f3f10b5dcc638c090795/scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253", size = 30094511 },
+ { url = "https://files.pythonhosted.org/packages/ea/b1/4deb37252311c1acff7f101f6453f0440794f51b6eacb1aad4459a134081/scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f", size = 22368151 },
+ { url = "https://files.pythonhosted.org/packages/38/7d/f457626e3cd3c29b3a49ca115a304cebb8cc6f31b04678f03b216899d3c6/scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92", size = 25121732 },
+ { url = "https://files.pythonhosted.org/packages/db/0a/92b1de4a7adc7a15dcf5bddc6e191f6f29ee663b30511ce20467ef9b82e4/scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82", size = 35547617 },
+ { url = "https://files.pythonhosted.org/packages/8e/6d/41991e503e51fc1134502694c5fa7a1671501a17ffa12716a4a9151af3df/scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40", size = 37662964 },
+ { url = "https://files.pythonhosted.org/packages/25/e1/3df8f83cb15f3500478c889be8fb18700813b95e9e087328230b98d547ff/scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e", size = 37238749 },
+ { url = "https://files.pythonhosted.org/packages/93/3e/b3257cf446f2a3533ed7809757039016b74cd6f38271de91682aa844cfc5/scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c", size = 40022383 },
+ { url = "https://files.pythonhosted.org/packages/d1/84/55bc4881973d3f79b479a5a2e2df61c8c9a04fcb986a213ac9c02cfb659b/scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13", size = 41259201 },
+ { url = "https://files.pythonhosted.org/packages/96/ab/5cc9f80f28f6a7dff646c5756e559823614a42b1939d86dd0ed550470210/scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b", size = 38714255 },
+ { url = "https://files.pythonhosted.org/packages/4a/4a/66ba30abe5ad1a3ad15bfb0b59d22174012e8056ff448cb1644deccbfed2/scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba", size = 30111035 },
+ { url = "https://files.pythonhosted.org/packages/4b/fa/a7e5b95afd80d24313307f03624acc65801846fa75599034f8ceb9e2cbf6/scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65", size = 22384499 },
+ { url = "https://files.pythonhosted.org/packages/17/99/f3aaddccf3588bb4aea70ba35328c204cadd89517a1612ecfda5b2dd9d7a/scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1", size = 25152602 },
+ { url = "https://files.pythonhosted.org/packages/56/c5/1032cdb565f146109212153339f9cb8b993701e9fe56b1c97699eee12586/scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889", size = 35503415 },
+ { url = "https://files.pythonhosted.org/packages/bd/37/89f19c8c05505d0601ed5650156e50eb881ae3918786c8fd7262b4ee66d3/scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982", size = 37652622 },
+ { url = "https://files.pythonhosted.org/packages/7e/31/be59513aa9695519b18e1851bb9e487de66f2d31f835201f1b42f5d4d475/scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9", size = 37244796 },
+ { url = "https://files.pythonhosted.org/packages/10/c0/4f5f3eeccc235632aab79b27a74a9130c6c35df358129f7ac8b29f562ac7/scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594", size = 40047684 },
+ { url = "https://files.pythonhosted.org/packages/ab/a7/0ddaf514ce8a8714f6ed243a2b391b41dbb65251affe21ee3077ec45ea9a/scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb", size = 41246504 },
+ { url = "https://files.pythonhosted.org/packages/37/4b/683aa044c4162e10ed7a7ea30527f2cbd92e6999c10a8ed8edb253836e9c/scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019", size = 38766735 },
+ { url = "https://files.pythonhosted.org/packages/7b/7e/f30be3d03de07f25dc0ec926d1681fed5c732d759ac8f51079708c79e680/scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6", size = 30173284 },
+ { url = "https://files.pythonhosted.org/packages/07/9c/0ddb0d0abdabe0d181c1793db51f02cd59e4901da6f9f7848e1f96759f0d/scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477", size = 22446958 },
+ { url = "https://files.pythonhosted.org/packages/af/43/0bce905a965f36c58ff80d8bea33f1f9351b05fad4beaad4eae34699b7a1/scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c", size = 25242454 },
+ { url = "https://files.pythonhosted.org/packages/56/30/a6f08f84ee5b7b28b4c597aca4cbe545535c39fe911845a96414700b64ba/scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45", size = 35210199 },
+ { url = "https://files.pythonhosted.org/packages/0b/1f/03f52c282437a168ee2c7c14a1a0d0781a9a4a8962d84ac05c06b4c5b555/scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49", size = 37309455 },
+ { url = "https://files.pythonhosted.org/packages/89/b1/fbb53137f42c4bf630b1ffdfc2151a62d1d1b903b249f030d2b1c0280af8/scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e", size = 36885140 },
+ { url = "https://files.pythonhosted.org/packages/2e/2e/025e39e339f5090df1ff266d021892694dbb7e63568edcfe43f892fa381d/scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539", size = 39710549 },
+ { url = "https://files.pythonhosted.org/packages/e6/eb/3bf6ea8ab7f1503dca3a10df2e4b9c3f6b3316df07f6c0ded94b281c7101/scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed", size = 40966184 },
+ { url = "https://files.pythonhosted.org/packages/73/18/ec27848c9baae6e0d6573eda6e01a602e5649ee72c27c3a8aad673ebecfd/scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759", size = 38728256 },
+ { url = "https://files.pythonhosted.org/packages/74/cd/1aef2184948728b4b6e21267d53b3339762c285a46a274ebb7863c9e4742/scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62", size = 30109540 },
+ { url = "https://files.pythonhosted.org/packages/5b/d8/59e452c0a255ec352bd0a833537a3bc1bfb679944c4938ab375b0a6b3a3e/scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb", size = 22383115 },
+ { url = "https://files.pythonhosted.org/packages/08/f5/456f56bbbfccf696263b47095291040655e3cbaf05d063bdc7c7517f32ac/scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730", size = 25163884 },
+ { url = "https://files.pythonhosted.org/packages/a2/66/a9618b6a435a0f0c0b8a6d0a2efb32d4ec5a85f023c2b79d39512040355b/scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825", size = 35174018 },
+ { url = "https://files.pythonhosted.org/packages/b5/09/c5b6734a50ad4882432b6bb7c02baf757f5b2f256041da5df242e2d7e6b6/scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7", size = 37269716 },
+ { url = "https://files.pythonhosted.org/packages/77/0a/eac00ff741f23bcabd352731ed9b8995a0a60ef57f5fd788d611d43d69a1/scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11", size = 36872342 },
+ { url = "https://files.pythonhosted.org/packages/fe/54/4379be86dd74b6ad81551689107360d9a3e18f24d20767a2d5b9253a3f0a/scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126", size = 39670869 },
+ { url = "https://files.pythonhosted.org/packages/87/2e/892ad2862ba54f084ffe8cc4a22667eaf9c2bcec6d2bff1d15713c6c0703/scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163", size = 40988851 },
+ { url = "https://files.pythonhosted.org/packages/1b/e9/7a879c137f7e55b30d75d90ce3eb468197646bc7b443ac036ae3fe109055/scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8", size = 38863011 },
+ { url = "https://files.pythonhosted.org/packages/51/d1/226a806bbd69f62ce5ef5f3ffadc35286e9fbc802f606a07eb83bf2359de/scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5", size = 30266407 },
+ { url = "https://files.pythonhosted.org/packages/e5/9b/f32d1d6093ab9eeabbd839b0f7619c62e46cc4b7b6dbf05b6e615bbd4400/scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e", size = 22540030 },
+ { url = "https://files.pythonhosted.org/packages/e7/29/c278f699b095c1a884f29fda126340fcc201461ee8bfea5c8bdb1c7c958b/scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb", size = 25218709 },
+ { url = "https://files.pythonhosted.org/packages/24/18/9e5374b617aba742a990581373cd6b68a2945d65cc588482749ef2e64467/scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723", size = 34809045 },
+ { url = "https://files.pythonhosted.org/packages/e1/fe/9c4361e7ba2927074360856db6135ef4904d505e9b3afbbcb073c4008328/scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb", size = 36703062 },
+ { url = "https://files.pythonhosted.org/packages/b7/8e/038ccfe29d272b30086b25a4960f757f97122cb2ec42e62b460d02fe98e9/scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4", size = 36393132 },
+ { url = "https://files.pythonhosted.org/packages/10/7e/5c12285452970be5bdbe8352c619250b97ebf7917d7a9a9e96b8a8140f17/scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5", size = 38979503 },
+ { url = "https://files.pythonhosted.org/packages/81/06/0a5e5349474e1cbc5757975b21bd4fad0e72ebf138c5592f191646154e06/scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca", size = 40308097 },
+]
+
+[[package]]
+name = "sentence-transformers"
+version = "4.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "huggingface-hub" },
+ { name = "pillow" },
+ { name = "scikit-learn", version = "1.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "scikit-learn", version = "1.7.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "scipy", version = "1.13.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "torch" },
+ { name = "tqdm" },
+ { name = "transformers" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/73/84/b30d1b29ff58cfdff423e36a50efd622c8e31d7039b1a0d5e72066620da1/sentence_transformers-4.1.0.tar.gz", hash = "sha256:f125ffd1c727533e0eca5d4567de72f84728de8f7482834de442fd90c2c3d50b", size = 272420 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/45/2d/1151b371f28caae565ad384fdc38198f1165571870217aedda230b9d7497/sentence_transformers-4.1.0-py3-none-any.whl", hash = "sha256:382a7f6be1244a100ce40495fb7523dbe8d71b3c10b299f81e6b735092b3b8ca", size = 345695 },
+]
+
+[[package]]
+name = "sentencepiece"
+version = "0.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/d2/b9c7ca067c26d8ff085d252c89b5f69609ca93fb85a00ede95f4857865d4/sentencepiece-0.2.0.tar.gz", hash = "sha256:a52c19171daaf2e697dc6cbe67684e0fa341b1248966f6aebb541de654d15843", size = 2632106 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f6/71/98648c3b64b23edb5403f74bcc906ad21766872a6e1ada26ea3f1eb941ab/sentencepiece-0.2.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:188779e1298a1c8b8253c7d3ad729cb0a9891e5cef5e5d07ce4592c54869e227", size = 2408979 },
+ { url = "https://files.pythonhosted.org/packages/77/9f/7efbaa6d4c0c718a9affbecc536b03ca62f99f421bdffb531c16030e2d2b/sentencepiece-0.2.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bed9cf85b296fa2b76fc2547b9cbb691a523864cebaee86304c43a7b4cb1b452", size = 1238845 },
+ { url = "https://files.pythonhosted.org/packages/1c/e4/c2541027a43ec6962ba9b601805d17ba3f86b38bdeae0e8ac65a2981e248/sentencepiece-0.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d7b67e724bead13f18db6e1d10b6bbdc454af574d70efbb36f27d90387be1ca3", size = 1181472 },
+ { url = "https://files.pythonhosted.org/packages/fd/46/316c1ba6c52b97de76aff7b9da678f7afbb52136afb2987c474d95630e65/sentencepiece-0.2.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2fde4b08cfe237be4484c6c7c2e2c75fb862cfeab6bd5449ce4caeafd97b767a", size = 1259151 },
+ { url = "https://files.pythonhosted.org/packages/aa/5a/3c48738a0835d76dd06c62b6ac48d39c923cde78dd0f587353bdcbb99851/sentencepiece-0.2.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4c378492056202d1c48a4979650981635fd97875a00eabb1f00c6a236b013b5e", size = 1355931 },
+ { url = "https://files.pythonhosted.org/packages/a6/27/33019685023221ca8ed98e8ceb7ae5e166032686fa3662c68f1f1edf334e/sentencepiece-0.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1380ce6540a368de2ef6d7e6ba14ba8f3258df650d39ba7d833b79ee68a52040", size = 1301537 },
+ { url = "https://files.pythonhosted.org/packages/ca/e4/55f97cef14293171fef5f96e96999919ab5b4d1ce95b53547ad653d7e3bf/sentencepiece-0.2.0-cp310-cp310-win32.whl", hash = "sha256:a1151d6a6dd4b43e552394aed0edfe9292820272f0194bd56c7c1660a0c06c3d", size = 936747 },
+ { url = "https://files.pythonhosted.org/packages/85/f4/4ef1a6e0e9dbd8a60780a91df8b7452ada14cfaa0e17b3b8dfa42cecae18/sentencepiece-0.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:d490142b0521ef22bc1085f061d922a2a6666175bb6b42e588ff95c0db6819b2", size = 991525 },
+ { url = "https://files.pythonhosted.org/packages/32/43/8f8885168a47a02eba1455bd3f4f169f50ad5b8cebd2402d0f5e20854d04/sentencepiece-0.2.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:17982700c4f6dbb55fa3594f3d7e5dd1c8659a274af3738e33c987d2a27c9d5c", size = 2409036 },
+ { url = "https://files.pythonhosted.org/packages/0f/35/e63ba28062af0a3d688a9f128e407a1a2608544b2f480cb49bf7f4b1cbb9/sentencepiece-0.2.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7c867012c0e8bcd5bdad0f791609101cb5c66acb303ab3270218d6debc68a65e", size = 1238921 },
+ { url = "https://files.pythonhosted.org/packages/de/42/ae30952c4a0bd773e90c9bf2579f5533037c886dfc8ec68133d5694f4dd2/sentencepiece-0.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7fd6071249c74f779c5b27183295b9202f8dedb68034e716784364443879eaa6", size = 1181477 },
+ { url = "https://files.pythonhosted.org/packages/e3/ac/2f2ab1d60bb2d795d054eebe5e3f24b164bc21b5a9b75fba7968b3b91b5a/sentencepiece-0.2.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27f90c55a65013cbb8f4d7aab0599bf925cde4adc67ae43a0d323677b5a1c6cb", size = 1259182 },
+ { url = "https://files.pythonhosted.org/packages/45/fb/14633c6ecf262c468759ffcdb55c3a7ee38fe4eda6a70d75ee7c7d63c58b/sentencepiece-0.2.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b293734059ef656dcd65be62ff771507bea8fed0a711b6733976e1ed3add4553", size = 1355537 },
+ { url = "https://files.pythonhosted.org/packages/fb/12/2f5c8d4764b00033cf1c935b702d3bb878d10be9f0b87f0253495832d85f/sentencepiece-0.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e58b47f933aca74c6a60a79dcb21d5b9e47416256c795c2d58d55cec27f9551d", size = 1301464 },
+ { url = "https://files.pythonhosted.org/packages/4e/b1/67afc0bde24f6dcb3acdea0dd8dcdf4b8b0db240f6bacd39378bd32d09f8/sentencepiece-0.2.0-cp311-cp311-win32.whl", hash = "sha256:c581258cf346b327c62c4f1cebd32691826306f6a41d8c4bec43b010dee08e75", size = 936749 },
+ { url = "https://files.pythonhosted.org/packages/a2/f6/587c62fd21fc988555b85351f50bbde43a51524caafd63bc69240ded14fd/sentencepiece-0.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:0993dbc665f4113017892f1b87c3904a44d0640eda510abcacdfb07f74286d36", size = 991520 },
+ { url = "https://files.pythonhosted.org/packages/27/5a/141b227ed54293360a9ffbb7bf8252b4e5efc0400cdeac5809340e5d2b21/sentencepiece-0.2.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ea5f536e32ea8ec96086ee00d7a4a131ce583a1b18d130711707c10e69601cb2", size = 2409370 },
+ { url = "https://files.pythonhosted.org/packages/2e/08/a4c135ad6fc2ce26798d14ab72790d66e813efc9589fd30a5316a88ca8d5/sentencepiece-0.2.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:d0cb51f53b6aae3c36bafe41e86167c71af8370a039f542c43b0cce5ef24a68c", size = 1239288 },
+ { url = "https://files.pythonhosted.org/packages/49/0a/2fe387f825ac5aad5a0bfe221904882106cac58e1b693ba7818785a882b6/sentencepiece-0.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3212121805afc58d8b00ab4e7dd1f8f76c203ddb9dc94aa4079618a31cf5da0f", size = 1181597 },
+ { url = "https://files.pythonhosted.org/packages/cc/38/e4698ee2293fe4835dc033c49796a39b3eebd8752098f6bd0aa53a14af1f/sentencepiece-0.2.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a3149e3066c2a75e0d68a43eb632d7ae728c7925b517f4c05c40f6f7280ce08", size = 1259220 },
+ { url = "https://files.pythonhosted.org/packages/12/24/fd7ef967c9dad2f6e6e5386d0cadaf65cda8b7be6e3861a9ab3121035139/sentencepiece-0.2.0-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:632f3594d3e7ac8b367bca204cb3fd05a01d5b21455acd097ea4c0e30e2f63d7", size = 1355962 },
+ { url = "https://files.pythonhosted.org/packages/4f/d2/18246f43ca730bb81918f87b7e886531eda32d835811ad9f4657c54eee35/sentencepiece-0.2.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f295105c6bdbb05bd5e1b0cafbd78ff95036f5d3641e7949455a3f4e5e7c3109", size = 1301706 },
+ { url = "https://files.pythonhosted.org/packages/8a/47/ca237b562f420044ab56ddb4c278672f7e8c866e183730a20e413b38a989/sentencepiece-0.2.0-cp312-cp312-win32.whl", hash = "sha256:fb89f811e5efd18bab141afc3fea3de141c3f69f3fe9e898f710ae7fe3aab251", size = 936941 },
+ { url = "https://files.pythonhosted.org/packages/c6/97/d159c32642306ee2b70732077632895438867b3b6df282354bd550cf2a67/sentencepiece-0.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7a673a72aab81fef5ebe755c6e0cc60087d1f3a4700835d40537183c1703a45f", size = 991994 },
+ { url = "https://files.pythonhosted.org/packages/e9/18/eb620d94d63f62ca69cecccf4459529864ac3fbb35ec123190bd58dadb46/sentencepiece-0.2.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:1e0f9c4d0a6b0af59b613175f019916e28ade076e21242fd5be24340d8a2f64a", size = 2409003 },
+ { url = "https://files.pythonhosted.org/packages/6e/a6/df28bc0b6a2a86416232c0a5f0d69a9cb7244bb95cb5dcdfcbf01cced8a6/sentencepiece-0.2.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:298f21cc1366eb60311aedba3169d30f885c363ddbf44214b0a587d2908141ad", size = 1238898 },
+ { url = "https://files.pythonhosted.org/packages/79/91/b54a528e0789cd7986341ed3909bec56365c3b672daef8b10aa4098238f0/sentencepiece-0.2.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3f1ec95aa1e5dab11f37ac7eff190493fd87770f7a8b81ebc9dd768d1a3c8704", size = 1181534 },
+ { url = "https://files.pythonhosted.org/packages/a3/69/e96ef68261fa5b82379fdedb325ceaf1d353c6e839ec346d8244e0da5f2f/sentencepiece-0.2.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7b06b70af54daa4b4904cbb90b4eb6d35c9f3252fdc86c9c32d5afd4d30118d8", size = 1259161 },
+ { url = "https://files.pythonhosted.org/packages/45/de/461d15856c29ba1ce778cf76e0462572661f647abc8a5373690c52e98a00/sentencepiece-0.2.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22e37bac44dd6603388cb598c64ff7a76e41ca774646f21c23aadfbf5a2228ab", size = 1355945 },
+ { url = "https://files.pythonhosted.org/packages/5f/01/c95e42eb86282b2c79305d3e0b0ca5a743f85a61262bb7130999c70b9374/sentencepiece-0.2.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0461324897735512a32d222e3d886e24ad6a499761952b6bda2a9ee6e4313ea5", size = 1301596 },
+ { url = "https://files.pythonhosted.org/packages/be/47/e16f368fe6327e873e8029aa539115025e9f61a4e8ca8f0f8eaf8e6a4c1c/sentencepiece-0.2.0-cp39-cp39-win32.whl", hash = "sha256:38aed822fb76435fa1f12185f10465a94ab9e51d5e8a9159e9a540ce926f0ffd", size = 936757 },
+ { url = "https://files.pythonhosted.org/packages/4b/36/497e6407700efd6b97f81bc160913a70d33b9b09227429f68fc86f387bbe/sentencepiece-0.2.0-cp39-cp39-win_amd64.whl", hash = "sha256:d8cf876516548b5a1d6ac4745d8b554f5c07891d55da557925e5c13ff0b4e6ad", size = 991541 },
+]
+
+[[package]]
+name = "setproctitle"
+version = "1.3.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/9e/af/56efe21c53ac81ac87e000b15e60b3d8104224b4313b6eacac3597bd183d/setproctitle-1.3.6.tar.gz", hash = "sha256:c9f32b96c700bb384f33f7cf07954bb609d35dd82752cef57fb2ee0968409169", size = 26889 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7d/db/8214810cae49e2e474ea741aaa7d6111486f27377e864f0eb6d297c9be56/setproctitle-1.3.6-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ebcf34b69df4ca0eabaaaf4a3d890f637f355fed00ba806f7ebdd2d040658c26", size = 17412 },
+ { url = "https://files.pythonhosted.org/packages/a4/45/909b0dcd68b16d2e58de0e861c0c0b67748ccc87ff9b59136e9710b528b1/setproctitle-1.3.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1aa1935aa2195b76f377e5cb018290376b7bf085f0b53f5a95c0c21011b74367", size = 11966 },
+ { url = "https://files.pythonhosted.org/packages/8a/f4/f1cd54fedae1cdacf1d1db833dc096bfb1f029451f60e68563e4c26ed2f7/setproctitle-1.3.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:13624d9925bb481bc0ccfbc7f533da38bfbfe6e80652314f789abc78c2e513bd", size = 31350 },
+ { url = "https://files.pythonhosted.org/packages/5a/5f/f159b22d286a349633d4090090b8e6632fb84575a64f189b68e70a613c65/setproctitle-1.3.6-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:97a138fa875c6f281df7720dac742259e85518135cd0e3551aba1c628103d853", size = 32704 },
+ { url = "https://files.pythonhosted.org/packages/9c/25/e5ea2673d951dafc04b6544d7b33dd9283733d715c8f40e93d39ae35d6a0/setproctitle-1.3.6-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c86e9e82bfab579327dbe9b82c71475165fbc8b2134d24f9a3b2edaf200a5c3d", size = 29833 },
+ { url = "https://files.pythonhosted.org/packages/67/2b/c3cbd4a4462c1143465d8c151f1d51bbfb418e60a96a754329d28d416575/setproctitle-1.3.6-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6af330ddc2ec05a99c3933ab3cba9365357c0b8470a7f2fa054ee4b0984f57d1", size = 30884 },
+ { url = "https://files.pythonhosted.org/packages/27/04/b43a622a9fbf0f216a50b523067d3b07739ede2106a7226223e33abf6659/setproctitle-1.3.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:109fc07b1cd6cef9c245b2028e3e98e038283342b220def311d0239179810dbe", size = 30798 },
+ { url = "https://files.pythonhosted.org/packages/41/60/8eb197b56b0a3110eef2a1d2ddb61b3f5809dbab9d975aa40c86e5d4b312/setproctitle-1.3.6-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:7df5fcc48588f82b6cc8073db069609ddd48a49b1e9734a20d0efb32464753c4", size = 29758 },
+ { url = "https://files.pythonhosted.org/packages/db/1d/c394322a5425c12f4ada0696eb6d194768752d4e3acaca0c9d593025feb4/setproctitle-1.3.6-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:2407955dc359d735a20ac6e797ad160feb33d529a2ac50695c11a1ec680eafab", size = 32157 },
+ { url = "https://files.pythonhosted.org/packages/e7/24/ce080682b144f057814efbe95daac09149e90f7689e2515897817a941686/setproctitle-1.3.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:38ca045626af693da042ac35d7332e7b9dbd52e6351d6973b310612e3acee6d6", size = 30291 },
+ { url = "https://files.pythonhosted.org/packages/a7/4f/4db265493567865428dcec376f8142a9c65d27c10c3ac915d173b4053afb/setproctitle-1.3.6-cp310-cp310-win32.whl", hash = "sha256:9483aa336687463f5497dd37a070094f3dff55e2c888994f8440fcf426a1a844", size = 11492 },
+ { url = "https://files.pythonhosted.org/packages/38/b0/64c3948f7957db44b4c5edfe9c197de493144dc915ddf95cf36aeca0dc52/setproctitle-1.3.6-cp310-cp310-win_amd64.whl", hash = "sha256:4efc91b437f6ff2578e89e3f17d010c0a0ff01736606473d082913ecaf7859ba", size = 12204 },
+ { url = "https://files.pythonhosted.org/packages/27/3b/8288d0cd969a63500dd62fc2c99ce6980f9909ccef0770ab1f86c361e0bf/setproctitle-1.3.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:a1d856b0f4e4a33e31cdab5f50d0a14998f3a2d726a3fd5cb7c4d45a57b28d1b", size = 17412 },
+ { url = "https://files.pythonhosted.org/packages/39/37/43a5a3e25ca1048dbbf4db0d88d346226f5f1acd131bb8e660f4bfe2799f/setproctitle-1.3.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:50706b9c0eda55f7de18695bfeead5f28b58aa42fd5219b3b1692d554ecbc9ec", size = 11963 },
+ { url = "https://files.pythonhosted.org/packages/5b/47/f103c40e133154783c91a10ab08ac9fc410ed835aa85bcf7107cb882f505/setproctitle-1.3.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:af188f3305f0a65c3217c30c6d4c06891e79144076a91e8b454f14256acc7279", size = 31718 },
+ { url = "https://files.pythonhosted.org/packages/1f/13/7325dd1c008dd6c0ebd370ddb7505977054a87e406f142318e395031a792/setproctitle-1.3.6-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cce0ed8b3f64c71c140f0ec244e5fdf8ecf78ddf8d2e591d4a8b6aa1c1214235", size = 33027 },
+ { url = "https://files.pythonhosted.org/packages/0c/0a/6075bfea05a71379d77af98a9ac61163e8b6e5ef1ae58cd2b05871b2079c/setproctitle-1.3.6-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70100e2087fe05359f249a0b5f393127b3a1819bf34dec3a3e0d4941138650c9", size = 30223 },
+ { url = "https://files.pythonhosted.org/packages/cc/41/fbf57ec52f4f0776193bd94334a841f0bc9d17e745f89c7790f336420c65/setproctitle-1.3.6-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1065ed36bd03a3fd4186d6c6de5f19846650b015789f72e2dea2d77be99bdca1", size = 31204 },
+ { url = "https://files.pythonhosted.org/packages/97/b5/f799fb7a00de29fb0ac1dfd015528dea425b9e31a8f1068a0b3df52d317f/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4adf6a0013fe4e0844e3ba7583ec203ca518b9394c6cc0d3354df2bf31d1c034", size = 31181 },
+ { url = "https://files.pythonhosted.org/packages/b5/b7/81f101b612014ec61723436022c31146178813d6ca6b947f7b9c84e9daf4/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:eb7452849f6615871eabed6560ffedfe56bc8af31a823b6be4ce1e6ff0ab72c5", size = 30101 },
+ { url = "https://files.pythonhosted.org/packages/67/23/681232eed7640eab96719daa8647cc99b639e3daff5c287bd270ef179a73/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a094b7ce455ca341b59a0f6ce6be2e11411ba6e2860b9aa3dbb37468f23338f4", size = 32438 },
+ { url = "https://files.pythonhosted.org/packages/19/f8/4d075a7bdc3609ac71535b849775812455e4c40aedfbf0778a6f123b1774/setproctitle-1.3.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ad1c2c2baaba62823a7f348f469a967ece0062140ca39e7a48e4bbb1f20d54c4", size = 30625 },
+ { url = "https://files.pythonhosted.org/packages/5f/73/a2a8259ebee166aee1ca53eead75de0e190b3ddca4f716e5c7470ebb7ef6/setproctitle-1.3.6-cp311-cp311-win32.whl", hash = "sha256:8050c01331135f77ec99d99307bfbc6519ea24d2f92964b06f3222a804a3ff1f", size = 11488 },
+ { url = "https://files.pythonhosted.org/packages/c9/15/52cf5e1ff0727d53704cfdde2858eaf237ce523b0b04db65faa84ff83e13/setproctitle-1.3.6-cp311-cp311-win_amd64.whl", hash = "sha256:9b73cf0fe28009a04a35bb2522e4c5b5176cc148919431dcb73fdbdfaab15781", size = 12201 },
+ { url = "https://files.pythonhosted.org/packages/8f/fb/99456fd94d4207c5f6c40746a048a33a52b4239cd7d9c8d4889e2210ec82/setproctitle-1.3.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:af44bb7a1af163806bbb679eb8432fa7b4fb6d83a5d403b541b675dcd3798638", size = 17399 },
+ { url = "https://files.pythonhosted.org/packages/d5/48/9699191fe6062827683c43bfa9caac33a2c89f8781dd8c7253fa3dba85fd/setproctitle-1.3.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3cca16fd055316a48f0debfcbfb6af7cea715429fc31515ab3fcac05abd527d8", size = 11966 },
+ { url = "https://files.pythonhosted.org/packages/33/03/b085d192b9ecb9c7ce6ad6ef30ecf4110b7f39430b58a56245569827fcf4/setproctitle-1.3.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ea002088d5554fd75e619742cefc78b84a212ba21632e59931b3501f0cfc8f67", size = 32017 },
+ { url = "https://files.pythonhosted.org/packages/ae/68/c53162e645816f97212002111420d1b2f75bf6d02632e37e961dc2cd6d8b/setproctitle-1.3.6-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bb465dd5825356c1191a038a86ee1b8166e3562d6e8add95eec04ab484cfb8a2", size = 33419 },
+ { url = "https://files.pythonhosted.org/packages/ac/0d/119a45d15a816a6cf5ccc61b19729f82620095b27a47e0a6838216a95fae/setproctitle-1.3.6-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d2c8e20487b3b73c1fa72c56f5c89430617296cd380373e7af3a538a82d4cd6d", size = 30711 },
+ { url = "https://files.pythonhosted.org/packages/e3/fb/5e9b5068df9e9f31a722a775a5e8322a29a638eaaa3eac5ea7f0b35e6314/setproctitle-1.3.6-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a0d6252098e98129a1decb59b46920d4eca17b0395f3d71b0d327d086fefe77d", size = 31742 },
+ { url = "https://files.pythonhosted.org/packages/35/88/54de1e73e8fce87d587889c7eedb48fc4ee2bbe4e4ca6331690d03024f86/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cf355fbf0d4275d86f9f57be705d8e5eaa7f8ddb12b24ced2ea6cbd68fdb14dc", size = 31925 },
+ { url = "https://files.pythonhosted.org/packages/f3/01/65948d7badd66e63e3db247b923143da142790fa293830fdecf832712c2d/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e288f8a162d663916060beb5e8165a8551312b08efee9cf68302687471a6545d", size = 30981 },
+ { url = "https://files.pythonhosted.org/packages/22/20/c495e61786f1d38d5dc340b9d9077fee9be3dfc7e89f515afe12e1526dbc/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b2e54f4a2dc6edf0f5ea5b1d0a608d2af3dcb5aa8c8eeab9c8841b23e1b054fe", size = 33209 },
+ { url = "https://files.pythonhosted.org/packages/98/3f/a457b8550fbd34d5b482fe20b8376b529e76bf1fbf9a474a6d9a641ab4ad/setproctitle-1.3.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b6f4abde9a2946f57e8daaf1160b2351bcf64274ef539e6675c1d945dbd75e2a", size = 31587 },
+ { url = "https://files.pythonhosted.org/packages/44/fe/743517340e5a635e3f1c4310baea20c16c66202f96a6f4cead222ffd6d84/setproctitle-1.3.6-cp312-cp312-win32.whl", hash = "sha256:db608db98ccc21248370d30044a60843b3f0f3d34781ceeea67067c508cd5a28", size = 11487 },
+ { url = "https://files.pythonhosted.org/packages/60/9a/d88f1c1f0f4efff1bd29d9233583ee341114dda7d9613941453984849674/setproctitle-1.3.6-cp312-cp312-win_amd64.whl", hash = "sha256:082413db8a96b1f021088e8ec23f0a61fec352e649aba20881895815388b66d3", size = 12208 },
+ { url = "https://files.pythonhosted.org/packages/89/76/f1a2fdbf9b9602945a7489ba5c52e9863de37381ef1a85a2b9ed0ff8bc79/setproctitle-1.3.6-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:e2a9e62647dc040a76d55563580bf3bb8fe1f5b6ead08447c2ed0d7786e5e794", size = 17392 },
+ { url = "https://files.pythonhosted.org/packages/5c/5b/4e0db8b10b4543afcb3dbc0827793d46e43ec1de6b377e313af3703d08e0/setproctitle-1.3.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:751ba352ed922e0af60458e961167fa7b732ac31c0ddd1476a2dfd30ab5958c5", size = 11951 },
+ { url = "https://files.pythonhosted.org/packages/dc/fe/d5d00aaa700fe1f6160b6e95c225b29c01f4d9292176d48fd968815163ea/setproctitle-1.3.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7890e291bf4708e3b61db9069ea39b3ab0651e42923a5e1f4d78a7b9e4b18301", size = 32087 },
+ { url = "https://files.pythonhosted.org/packages/9f/b3/894b827b93ef813c082479bebf88185860f01ac243df737823dd705e7fff/setproctitle-1.3.6-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b2b17855ed7f994f3f259cf2dfbfad78814538536fa1a91b50253d84d87fd88d", size = 33502 },
+ { url = "https://files.pythonhosted.org/packages/b2/cd/5330734cca1a4cfcb721432c22cb7899ff15a4101ba868b2ef452ffafea1/setproctitle-1.3.6-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2e51ec673513465663008ce402171192a053564865c2fc6dc840620871a9bd7c", size = 30713 },
+ { url = "https://files.pythonhosted.org/packages/fa/d3/c2590c5daa2e9a008d3f2b16c0f4a351826193be55f147cb32af49c6d814/setproctitle-1.3.6-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63cc10352dc6cf35a33951656aa660d99f25f574eb78132ce41a85001a638aa7", size = 31792 },
+ { url = "https://files.pythonhosted.org/packages/e6/b1/c553ed5af8cfcecd5ae7737e63af58a17a03d26f3d61868c7eb20bf7e3cf/setproctitle-1.3.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0dba8faee2e4a96e934797c9f0f2d093f8239bf210406a99060b3eabe549628e", size = 31927 },
+ { url = "https://files.pythonhosted.org/packages/70/78/2d5385206540127a3dca0ff83225b1ac66873f5cc89d4a6d3806c92f5ae2/setproctitle-1.3.6-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:e3e44d08b61de0dd6f205528498f834a51a5c06689f8fb182fe26f3a3ce7dca9", size = 30981 },
+ { url = "https://files.pythonhosted.org/packages/31/62/e3e4a4e006d0e549748e53cded4ff3b667be0602860fc61b7de8b412b667/setproctitle-1.3.6-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:de004939fc3fd0c1200d26ea9264350bfe501ffbf46c8cf5dc7f345f2d87a7f1", size = 33244 },
+ { url = "https://files.pythonhosted.org/packages/aa/05/4b223fd4ef94e105dc7aff27fa502fb7200cf52be2bb0c064bd2406b5611/setproctitle-1.3.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3f8194b4d631b003a1176a75d1acd545e04b1f54b821638e098a93e6e62830ef", size = 31630 },
+ { url = "https://files.pythonhosted.org/packages/1b/ba/5f68eb969f7336f54b54a599fd3ffbd7662f9733b080bc8598705971b3dd/setproctitle-1.3.6-cp313-cp313-win32.whl", hash = "sha256:d714e002dd3638170fe7376dc1b686dbac9cb712cde3f7224440af722cc9866a", size = 11480 },
+ { url = "https://files.pythonhosted.org/packages/ba/f5/7f47f0ca35c9c357f16187cee9229f3eda0237bc6fdd3061441336f361c0/setproctitle-1.3.6-cp313-cp313-win_amd64.whl", hash = "sha256:b70c07409d465f3a8b34d52f863871fb8a00755370791d2bd1d4f82b3cdaf3d5", size = 12198 },
+ { url = "https://files.pythonhosted.org/packages/39/ad/c3941b8fc6b32a976c9e2d9615a90ae793b69cd010ca8c3575dbc822104f/setproctitle-1.3.6-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:23a57d3b8f1549515c2dbe4a2880ebc1f27780dc126c5e064167563e015817f5", size = 17401 },
+ { url = "https://files.pythonhosted.org/packages/04/38/a184f857b988d3a9c401e470a4e38182a5c99ee77bf90432d7665e9d35a3/setproctitle-1.3.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:81c443310831e29fabbd07b75ebbfa29d0740b56f5907c6af218482d51260431", size = 11959 },
+ { url = "https://files.pythonhosted.org/packages/b7/b9/4878ef9d8483adfd1edf6bf95151362aaec0d05aac306a97ff0383f491b5/setproctitle-1.3.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d88c63bd395c787b0aa81d8bbc22c1809f311032ce3e823a6517b711129818e4", size = 33463 },
+ { url = "https://files.pythonhosted.org/packages/cc/60/3ef49d1931aff2a36a7324a49cca10d77ef03e0278452fd468c33a52d7e3/setproctitle-1.3.6-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d73f14b86d0e2858ece6bf5807c9889670e392c001d414b4293d0d9b291942c3", size = 34959 },
+ { url = "https://files.pythonhosted.org/packages/81/c6/dee0a973acecefb0db6c9c2e0ea7f18b7e4db773a72e534741ebdee8bbb8/setproctitle-1.3.6-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3393859eb8f19f5804049a685bf286cb08d447e28ba5c6d8543c7bf5500d5970", size = 32055 },
+ { url = "https://files.pythonhosted.org/packages/ea/a5/5dd5c4192cf18d16349a32a07f728a9a48a2a05178e16966cabd6645903e/setproctitle-1.3.6-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:785cd210c0311d9be28a70e281a914486d62bfd44ac926fcd70cf0b4d65dff1c", size = 32986 },
+ { url = "https://files.pythonhosted.org/packages/df/a6/1508d37eb8008670d33f13fcdb91cbd8ef54697276469abbfdd3d4428c59/setproctitle-1.3.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c051f46ed1e13ba8214b334cbf21902102807582fbfaf0fef341b9e52f0fafbf", size = 32736 },
+ { url = "https://files.pythonhosted.org/packages/1a/73/c84ec8880d543766a12fcd6b65dbd013770974a40577889f357409b0441e/setproctitle-1.3.6-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:49498ebf68ca3e75321ffe634fcea5cc720502bfaa79bd6b03ded92ce0dc3c24", size = 31945 },
+ { url = "https://files.pythonhosted.org/packages/95/0a/126b9ff7a406a69a62825fe5bd6d1ba8671919a7018c4f9e2c63f49bfcb6/setproctitle-1.3.6-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:4431629c178193f23c538cb1de3da285a99ccc86b20ee91d81eb5f1a80e0d2ba", size = 34333 },
+ { url = "https://files.pythonhosted.org/packages/9a/fd/5474b04f1c013ff460129d2bc774557dd6e186da4667865efef9a83bf378/setproctitle-1.3.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:d136fbf8ad4321716e44d6d6b3d8dffb4872626010884e07a1db54b7450836cf", size = 32508 },
+ { url = "https://files.pythonhosted.org/packages/32/21/2503e38520cb076a7ecaef6a35d6a6fa89cf02af3541c84c811fd7500d20/setproctitle-1.3.6-cp313-cp313t-win32.whl", hash = "sha256:d483cc23cc56ab32911ea0baa0d2d9ea7aa065987f47de847a0a93a58bf57905", size = 11482 },
+ { url = "https://files.pythonhosted.org/packages/65/23/7833d75a27fba25ddc5cd3b54cd03c4bf8e18b8e2dbec622eb6326278ce8/setproctitle-1.3.6-cp313-cp313t-win_amd64.whl", hash = "sha256:74973aebea3543ad033b9103db30579ec2b950a466e09f9c2180089e8346e0ec", size = 12209 },
+ { url = "https://files.pythonhosted.org/packages/c6/c2/444f0a21bc8eaa82e166a1147ee8a972275b0d54347525cd2030cecafdb9/setproctitle-1.3.6-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:391bb6a29c4fe7ccc9c30812e3744060802d89b39264cfa77f3d280d7f387ea5", size = 17396 },
+ { url = "https://files.pythonhosted.org/packages/31/86/1e5af105ccf0fe4232be77742ee4278887df28331000da5ad85e7e2dd584/setproctitle-1.3.6-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:156795b3db976611d09252fc80761fcdb65bb7c9b9581148da900851af25ecf4", size = 11962 },
+ { url = "https://files.pythonhosted.org/packages/22/f4/73ab265b6ffbd6ae5bbbb287d5b0533f4004ab77716ed22d9e8fe147d05d/setproctitle-1.3.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cdd7315314b0744a7dd506f3bd0f2cf90734181529cdcf75542ee35ad885cab7", size = 31115 },
+ { url = "https://files.pythonhosted.org/packages/fb/e9/1cd69bec906bb31320fa83a470d8df007dd1cb70309487d61cf2430f9709/setproctitle-1.3.6-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6d50bfcc1d1692dc55165b3dd2f0b9f8fb5b1f7b571a93e08d660ad54b9ca1a5", size = 32474 },
+ { url = "https://files.pythonhosted.org/packages/85/bf/6928c7cd5927c37b90eb094fb98c8cf1da1cf1462f6a8904020303179058/setproctitle-1.3.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:163dba68f979c61e4e2e779c4d643e968973bdae7c33c3ec4d1869f7a9ba8390", size = 29589 },
+ { url = "https://files.pythonhosted.org/packages/dc/4f/027ac688b4fcd4d6f04344e3dbca69cee4154454a9a578a5aa1edc62f75b/setproctitle-1.3.6-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d5a369eb7ec5b2fdfa9927530b5259dd21893fa75d4e04a223332f61b84b586", size = 30606 },
+ { url = "https://files.pythonhosted.org/packages/50/0d/f695386ca855618c78f43803a71f52ba5201a1fba5e5b10eed9eb21847cc/setproctitle-1.3.6-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:18d0667bafaaae4c1dee831e2e59841c411ff399b9b4766822ba2685d419c3be", size = 30518 },
+ { url = "https://files.pythonhosted.org/packages/b2/b8/9a44c3f3f5ffcff778f4b662795e7644ab3f616a1d4c42aae00f48d448e7/setproctitle-1.3.6-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:f33fbf96b52d51c23b6cff61f57816539c1c147db270cfc1cc3bc012f4a560a9", size = 29464 },
+ { url = "https://files.pythonhosted.org/packages/57/77/9d63a1139ac33a721a58023334ea2776c94fa4c909d1bf945594abd3eb91/setproctitle-1.3.6-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:543f59601a4e32daf44741b52f9a23e0ee374f9f13b39c41d917302d98fdd7b0", size = 31879 },
+ { url = "https://files.pythonhosted.org/packages/00/c7/39d73db7698f2498b7a340499103b87a09810b65e45a2dca63b918ecf4d5/setproctitle-1.3.6-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:2156d55308431ac3b3ec4e5e05b1726d11a5215352d6a22bb933171dee292f8c", size = 30023 },
+ { url = "https://files.pythonhosted.org/packages/00/d0/0a36027fab8e47dbfea42d4e17c78206ba3faeab72b65e872a9c82f577f9/setproctitle-1.3.6-cp39-cp39-win32.whl", hash = "sha256:17d7c833ed6545ada5ac4bb606b86a28f13a04431953d4beac29d3773aa00b1d", size = 11496 },
+ { url = "https://files.pythonhosted.org/packages/e2/3c/f11db7a9168b82e87e84816eabdca2b624520838200cfa123c9aba0c79ea/setproctitle-1.3.6-cp39-cp39-win_amd64.whl", hash = "sha256:2940cf13f4fc11ce69ad2ed37a9f22386bfed314b98d8aebfd4f55459aa59108", size = 12189 },
+ { url = "https://files.pythonhosted.org/packages/d0/2b/f19977b646b64c1440dade2c385c89c39f74ce5254defa102dfd9c163e0b/setproctitle-1.3.6-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:3cde5b83ec4915cd5e6ae271937fd60d14113c8f7769b4a20d51769fe70d8717", size = 11471 },
+ { url = "https://files.pythonhosted.org/packages/78/46/db58cf700f1408cf0f63d3f939f7b077bd450da8e037310f70e74c41262f/setproctitle-1.3.6-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:797f2846b546a8741413c57d9fb930ad5aa939d925c9c0fa6186d77580035af7", size = 13520 },
+ { url = "https://files.pythonhosted.org/packages/5c/46/0b89e7ebe77543e721c67077ad93fc8c7c3c31a8db3b12e00d02950f6adc/setproctitle-1.3.6-pp310-pypy310_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ac3eb04bcf0119aadc6235a2c162bae5ed5f740e3d42273a7228b915722de20", size = 13094 },
+ { url = "https://files.pythonhosted.org/packages/f7/78/03f2e42eb83bce6f853d7751ae95f8a3ae7408145a0b6cdd717be01497d7/setproctitle-1.3.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:0e6b5633c94c5111f7137f875e8f1ff48f53b991d5d5b90932f27dc8c1fa9ae4", size = 12241 },
+ { url = "https://files.pythonhosted.org/packages/df/11/fa611d7ed77ca28da4f870e280bae23e93ed790ea15ff2f3a19e81fd085a/setproctitle-1.3.6-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:9b50700785eccac0819bea794d968ed8f6055c88f29364776b7ea076ac105c5d", size = 11464 },
+ { url = "https://files.pythonhosted.org/packages/2e/b3/fc91b9ba8547e3a8c3732b64c8d3fefcd51f902bba8be351aa0e461a7fea/setproctitle-1.3.6-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:92df0e70b884f5da35f2e01489dca3c06a79962fb75636985f1e3a17aec66833", size = 13518 },
+ { url = "https://files.pythonhosted.org/packages/0c/82/b208480e68ff75ae475aa649fe8b04fbc5509fa8e43268775fb8ace81364/setproctitle-1.3.6-pp39-pypy39_pp73-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8834ab7be6539f1bfadec7c8d12249bbbe6c2413b1d40ffc0ec408692232a0c6", size = 13088 },
+ { url = "https://files.pythonhosted.org/packages/8d/8f/e108c7ef434afbed823013356b6401ced8aa1aef03b118b3c2d6d6fed9db/setproctitle-1.3.6-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:a5963b663da69ad25fa1559ee064584935570def665917918938c1f1289f5ebc", size = 12225 },
+]
+
+[[package]]
+name = "setuptools"
+version = "80.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486 },
+]
+
+[[package]]
+name = "sgl-kernel"
+version = "0.1.7"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8c/24/c57c1f2a6af02f4db7bd4d0d872373fb9ceb76e775b3336030d9d6490084/sgl_kernel-0.1.7-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:a40e0db73ceff1efde7970174630310c8467039e2eba7918307b0d7ef4822a20", size = 248723461 },
+]
+
+[[package]]
+name = "sglang"
+version = "0.4.7"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "aiohttp" },
+ { name = "ipython", version = "8.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "ipython", version = "8.37.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.10.*'" },
+ { name = "ipython", version = "9.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
+ { name = "numpy" },
+ { name = "requests" },
+ { name = "setproctitle" },
+ { name = "tqdm" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/bf/16/14add0e9b8e1eddca82a50f8d0b1a4148018400a73099bb40c8e7ace67a4/sglang-0.4.7.tar.gz", hash = "sha256:39326110c7ba9121084b752513f429e866f7af72cc073f7fddad72df35e4adb4", size = 1062495 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/d4/2ed4309c246ccff1f4f3fe014f979a15743f923c6adf9869316d9ad631da/sglang-0.4.7-py3-none-any.whl", hash = "sha256:c897284d8ca4fe7f2906a89775ad9609666d369ed70aded908722630ece34a54", size = 1479355 },
+]
+
+[package.optional-dependencies]
+all = [
+ { name = "anthropic" },
+ { name = "blobfile" },
+ { name = "compressed-tensors" },
+ { name = "cuda-python" },
+ { name = "datasets" },
+ { name = "decord" },
+ { name = "einops" },
+ { name = "fastapi" },
+ { name = "flashinfer-python" },
+ { name = "hf-transfer" },
+ { name = "huggingface-hub" },
+ { name = "interegular" },
+ { name = "litellm" },
+ { name = "llguidance" },
+ { name = "modelscope" },
+ { name = "msgspec" },
+ { name = "ninja" },
+ { name = "openai" },
+ { name = "orjson" },
+ { name = "outlines" },
+ { name = "packaging" },
+ { name = "partial-json-parser" },
+ { name = "pillow" },
+ { name = "prometheus-client" },
+ { name = "psutil" },
+ { name = "pydantic" },
+ { name = "pynvml" },
+ { name = "python-multipart" },
+ { name = "pyzmq" },
+ { name = "scipy", version = "1.13.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "sgl-kernel" },
+ { name = "soundfile" },
+ { name = "tiktoken" },
+ { name = "torch" },
+ { name = "torch-memory-saver" },
+ { name = "torchao" },
+ { name = "torchaudio" },
+ { name = "torchvision" },
+ { name = "transformers" },
+ { name = "uvicorn" },
+ { name = "uvloop" },
+ { name = "xgrammar" },
+]
+
+[[package]]
+name = "six"
+version = "1.17.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050 },
+]
+
+[[package]]
+name = "sniffio"
+version = "1.3.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235 },
+]
+
+[[package]]
+name = "soundfile"
+version = "0.13.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi" },
+ { name = "numpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e1/41/9b873a8c055582859b239be17902a85339bec6a30ad162f98c9b0288a2cc/soundfile-0.13.1.tar.gz", hash = "sha256:b2c68dab1e30297317080a5b43df57e302584c49e2942defdde0acccc53f0e5b", size = 46156 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/64/28/e2a36573ccbcf3d57c00626a21fe51989380636e821b341d36ccca0c1c3a/soundfile-0.13.1-py2.py3-none-any.whl", hash = "sha256:a23c717560da2cf4c7b5ae1142514e0fd82d6bbd9dfc93a50423447142f2c445", size = 25751 },
+ { url = "https://files.pythonhosted.org/packages/ea/ab/73e97a5b3cc46bba7ff8650a1504348fa1863a6f9d57d7001c6b67c5f20e/soundfile-0.13.1-py2.py3-none-macosx_10_9_x86_64.whl", hash = "sha256:82dc664d19831933fe59adad199bf3945ad06d84bc111a5b4c0d3089a5b9ec33", size = 1142250 },
+ { url = "https://files.pythonhosted.org/packages/a0/e5/58fd1a8d7b26fc113af244f966ee3aecf03cb9293cb935daaddc1e455e18/soundfile-0.13.1-py2.py3-none-macosx_11_0_arm64.whl", hash = "sha256:743f12c12c4054921e15736c6be09ac26b3b3d603aef6fd69f9dde68748f2593", size = 1101406 },
+ { url = "https://files.pythonhosted.org/packages/58/ae/c0e4a53d77cf6e9a04179535766b3321b0b9ced5f70522e4caf9329f0046/soundfile-0.13.1-py2.py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:9c9e855f5a4d06ce4213f31918653ab7de0c5a8d8107cd2427e44b42df547deb", size = 1235729 },
+ { url = "https://files.pythonhosted.org/packages/57/5e/70bdd9579b35003a489fc850b5047beeda26328053ebadc1fb60f320f7db/soundfile-0.13.1-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:03267c4e493315294834a0870f31dbb3b28a95561b80b134f0bd3cf2d5f0e618", size = 1313646 },
+ { url = "https://files.pythonhosted.org/packages/fe/df/8c11dc4dfceda14e3003bb81a0d0edcaaf0796dd7b4f826ea3e532146bba/soundfile-0.13.1-py2.py3-none-win32.whl", hash = "sha256:c734564fab7c5ddf8e9be5bf70bab68042cd17e9c214c06e365e20d64f9a69d5", size = 899881 },
+ { url = "https://files.pythonhosted.org/packages/14/e9/6b761de83277f2f02ded7e7ea6f07828ec78e4b229b80e4ca55dd205b9dc/soundfile-0.13.1-py2.py3-none-win_amd64.whl", hash = "sha256:1e70a05a0626524a69e9f0f4dd2ec174b4e9567f4d8b6c11d38b5c289be36ee9", size = 1019162 },
+]
+
+[[package]]
+name = "soupsieve"
+version = "2.7"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/3f/f4/4a80cd6ef364b2e8b65b15816a843c0980f7a5a2b4dc701fc574952aa19f/soupsieve-2.7.tar.gz", hash = "sha256:ad282f9b6926286d2ead4750552c8a6142bc4c783fd66b0293547c8fe6ae126a", size = 103418 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/9c/0e6afc12c269578be5c0c1c9f4b49a8d32770a080260c333ac04cc1c832d/soupsieve-2.7-py3-none-any.whl", hash = "sha256:6e60cc5c1ffaf1cebcc12e8188320b72071e922c2e897f737cadce79ad5d30c4", size = 36677 },
+]
+
+[[package]]
+name = "sqlalchemy"
+version = "2.0.41"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "greenlet", marker = "(python_full_version < '3.14' and platform_machine == 'AMD64') or (python_full_version < '3.14' and platform_machine == 'WIN32') or (python_full_version < '3.14' and platform_machine == 'aarch64') or (python_full_version < '3.14' and platform_machine == 'amd64') or (python_full_version < '3.14' and platform_machine == 'ppc64le') or (python_full_version < '3.14' and platform_machine == 'win32') or (python_full_version < '3.14' and platform_machine == 'x86_64')" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/63/66/45b165c595ec89aa7dcc2c1cd222ab269bc753f1fc7a1e68f8481bd957bf/sqlalchemy-2.0.41.tar.gz", hash = "sha256:edba70118c4be3c2b1f90754d308d0b79c6fe2c0fdc52d8ddf603916f83f4db9", size = 9689424 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e9/12/d7c445b1940276a828efce7331cb0cb09d6e5f049651db22f4ebb0922b77/sqlalchemy-2.0.41-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b1f09b6821406ea1f94053f346f28f8215e293344209129a9c0fcc3578598d7b", size = 2117967 },
+ { url = "https://files.pythonhosted.org/packages/6f/b8/cb90f23157e28946b27eb01ef401af80a1fab7553762e87df51507eaed61/sqlalchemy-2.0.41-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1936af879e3db023601196a1684d28e12f19ccf93af01bf3280a3262c4b6b4e5", size = 2107583 },
+ { url = "https://files.pythonhosted.org/packages/9e/c2/eef84283a1c8164a207d898e063edf193d36a24fb6a5bb3ce0634b92a1e8/sqlalchemy-2.0.41-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2ac41acfc8d965fb0c464eb8f44995770239668956dc4cdf502d1b1ffe0d747", size = 3186025 },
+ { url = "https://files.pythonhosted.org/packages/bd/72/49d52bd3c5e63a1d458fd6d289a1523a8015adedbddf2c07408ff556e772/sqlalchemy-2.0.41-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:81c24e0c0fde47a9723c81d5806569cddef103aebbf79dbc9fcbb617153dea30", size = 3186259 },
+ { url = "https://files.pythonhosted.org/packages/4f/9e/e3ffc37d29a3679a50b6bbbba94b115f90e565a2b4545abb17924b94c52d/sqlalchemy-2.0.41-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:23a8825495d8b195c4aa9ff1c430c28f2c821e8c5e2d98089228af887e5d7e29", size = 3126803 },
+ { url = "https://files.pythonhosted.org/packages/8a/76/56b21e363f6039978ae0b72690237b38383e4657281285a09456f313dd77/sqlalchemy-2.0.41-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:60c578c45c949f909a4026b7807044e7e564adf793537fc762b2489d522f3d11", size = 3148566 },
+ { url = "https://files.pythonhosted.org/packages/3b/92/11b8e1b69bf191bc69e300a99badbbb5f2f1102f2b08b39d9eee2e21f565/sqlalchemy-2.0.41-cp310-cp310-win32.whl", hash = "sha256:118c16cd3f1b00c76d69343e38602006c9cfb9998fa4f798606d28d63f23beda", size = 2086696 },
+ { url = "https://files.pythonhosted.org/packages/5c/88/2d706c9cc4502654860f4576cd54f7db70487b66c3b619ba98e0be1a4642/sqlalchemy-2.0.41-cp310-cp310-win_amd64.whl", hash = "sha256:7492967c3386df69f80cf67efd665c0f667cee67032090fe01d7d74b0e19bb08", size = 2110200 },
+ { url = "https://files.pythonhosted.org/packages/37/4e/b00e3ffae32b74b5180e15d2ab4040531ee1bef4c19755fe7926622dc958/sqlalchemy-2.0.41-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6375cd674fe82d7aa9816d1cb96ec592bac1726c11e0cafbf40eeee9a4516b5f", size = 2121232 },
+ { url = "https://files.pythonhosted.org/packages/ef/30/6547ebb10875302074a37e1970a5dce7985240665778cfdee2323709f749/sqlalchemy-2.0.41-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9f8c9fdd15a55d9465e590a402f42082705d66b05afc3ffd2d2eb3c6ba919560", size = 2110897 },
+ { url = "https://files.pythonhosted.org/packages/9e/21/59df2b41b0f6c62da55cd64798232d7349a9378befa7f1bb18cf1dfd510a/sqlalchemy-2.0.41-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:32f9dc8c44acdee06c8fc6440db9eae8b4af8b01e4b1aee7bdd7241c22edff4f", size = 3273313 },
+ { url = "https://files.pythonhosted.org/packages/62/e4/b9a7a0e5c6f79d49bcd6efb6e90d7536dc604dab64582a9dec220dab54b6/sqlalchemy-2.0.41-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:90c11ceb9a1f482c752a71f203a81858625d8df5746d787a4786bca4ffdf71c6", size = 3273807 },
+ { url = "https://files.pythonhosted.org/packages/39/d8/79f2427251b44ddee18676c04eab038d043cff0e764d2d8bb08261d6135d/sqlalchemy-2.0.41-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:911cc493ebd60de5f285bcae0491a60b4f2a9f0f5c270edd1c4dbaef7a38fc04", size = 3209632 },
+ { url = "https://files.pythonhosted.org/packages/d4/16/730a82dda30765f63e0454918c982fb7193f6b398b31d63c7c3bd3652ae5/sqlalchemy-2.0.41-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:03968a349db483936c249f4d9cd14ff2c296adfa1290b660ba6516f973139582", size = 3233642 },
+ { url = "https://files.pythonhosted.org/packages/04/61/c0d4607f7799efa8b8ea3c49b4621e861c8f5c41fd4b5b636c534fcb7d73/sqlalchemy-2.0.41-cp311-cp311-win32.whl", hash = "sha256:293cd444d82b18da48c9f71cd7005844dbbd06ca19be1ccf6779154439eec0b8", size = 2086475 },
+ { url = "https://files.pythonhosted.org/packages/9d/8e/8344f8ae1cb6a479d0741c02cd4f666925b2bf02e2468ddaf5ce44111f30/sqlalchemy-2.0.41-cp311-cp311-win_amd64.whl", hash = "sha256:3d3549fc3e40667ec7199033a4e40a2f669898a00a7b18a931d3efb4c7900504", size = 2110903 },
+ { url = "https://files.pythonhosted.org/packages/3e/2a/f1f4e068b371154740dd10fb81afb5240d5af4aa0087b88d8b308b5429c2/sqlalchemy-2.0.41-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:81f413674d85cfd0dfcd6512e10e0f33c19c21860342a4890c3a2b59479929f9", size = 2119645 },
+ { url = "https://files.pythonhosted.org/packages/9b/e8/c664a7e73d36fbfc4730f8cf2bf930444ea87270f2825efbe17bf808b998/sqlalchemy-2.0.41-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:598d9ebc1e796431bbd068e41e4de4dc34312b7aa3292571bb3674a0cb415dd1", size = 2107399 },
+ { url = "https://files.pythonhosted.org/packages/5c/78/8a9cf6c5e7135540cb682128d091d6afa1b9e48bd049b0d691bf54114f70/sqlalchemy-2.0.41-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a104c5694dfd2d864a6f91b0956eb5d5883234119cb40010115fd45a16da5e70", size = 3293269 },
+ { url = "https://files.pythonhosted.org/packages/3c/35/f74add3978c20de6323fb11cb5162702670cc7a9420033befb43d8d5b7a4/sqlalchemy-2.0.41-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6145afea51ff0af7f2564a05fa95eb46f542919e6523729663a5d285ecb3cf5e", size = 3303364 },
+ { url = "https://files.pythonhosted.org/packages/6a/d4/c990f37f52c3f7748ebe98883e2a0f7d038108c2c5a82468d1ff3eec50b7/sqlalchemy-2.0.41-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b46fa6eae1cd1c20e6e6f44e19984d438b6b2d8616d21d783d150df714f44078", size = 3229072 },
+ { url = "https://files.pythonhosted.org/packages/15/69/cab11fecc7eb64bc561011be2bd03d065b762d87add52a4ca0aca2e12904/sqlalchemy-2.0.41-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41836fe661cc98abfae476e14ba1906220f92c4e528771a8a3ae6a151242d2ae", size = 3268074 },
+ { url = "https://files.pythonhosted.org/packages/5c/ca/0c19ec16858585d37767b167fc9602593f98998a68a798450558239fb04a/sqlalchemy-2.0.41-cp312-cp312-win32.whl", hash = "sha256:a8808d5cf866c781150d36a3c8eb3adccfa41a8105d031bf27e92c251e3969d6", size = 2084514 },
+ { url = "https://files.pythonhosted.org/packages/7f/23/4c2833d78ff3010a4e17f984c734f52b531a8c9060a50429c9d4b0211be6/sqlalchemy-2.0.41-cp312-cp312-win_amd64.whl", hash = "sha256:5b14e97886199c1f52c14629c11d90c11fbb09e9334fa7bb5f6d068d9ced0ce0", size = 2111557 },
+ { url = "https://files.pythonhosted.org/packages/d3/ad/2e1c6d4f235a97eeef52d0200d8ddda16f6c4dd70ae5ad88c46963440480/sqlalchemy-2.0.41-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:4eeb195cdedaf17aab6b247894ff2734dcead6c08f748e617bfe05bd5a218443", size = 2115491 },
+ { url = "https://files.pythonhosted.org/packages/cf/8d/be490e5db8400dacc89056f78a52d44b04fbf75e8439569d5b879623a53b/sqlalchemy-2.0.41-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d4ae769b9c1c7757e4ccce94b0641bc203bbdf43ba7a2413ab2523d8d047d8dc", size = 2102827 },
+ { url = "https://files.pythonhosted.org/packages/a0/72/c97ad430f0b0e78efaf2791342e13ffeafcbb3c06242f01a3bb8fe44f65d/sqlalchemy-2.0.41-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a62448526dd9ed3e3beedc93df9bb6b55a436ed1474db31a2af13b313a70a7e1", size = 3225224 },
+ { url = "https://files.pythonhosted.org/packages/5e/51/5ba9ea3246ea068630acf35a6ba0d181e99f1af1afd17e159eac7e8bc2b8/sqlalchemy-2.0.41-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc56c9788617b8964ad02e8fcfeed4001c1f8ba91a9e1f31483c0dffb207002a", size = 3230045 },
+ { url = "https://files.pythonhosted.org/packages/78/2f/8c14443b2acea700c62f9b4a8bad9e49fc1b65cfb260edead71fd38e9f19/sqlalchemy-2.0.41-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c153265408d18de4cc5ded1941dcd8315894572cddd3c58df5d5b5705b3fa28d", size = 3159357 },
+ { url = "https://files.pythonhosted.org/packages/fc/b2/43eacbf6ccc5276d76cea18cb7c3d73e294d6fb21f9ff8b4eef9b42bbfd5/sqlalchemy-2.0.41-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4f67766965996e63bb46cfbf2ce5355fc32d9dd3b8ad7e536a920ff9ee422e23", size = 3197511 },
+ { url = "https://files.pythonhosted.org/packages/fa/2e/677c17c5d6a004c3c45334ab1dbe7b7deb834430b282b8a0f75ae220c8eb/sqlalchemy-2.0.41-cp313-cp313-win32.whl", hash = "sha256:bfc9064f6658a3d1cadeaa0ba07570b83ce6801a1314985bf98ec9b95d74e15f", size = 2082420 },
+ { url = "https://files.pythonhosted.org/packages/e9/61/e8c1b9b6307c57157d328dd8b8348ddc4c47ffdf1279365a13b2b98b8049/sqlalchemy-2.0.41-cp313-cp313-win_amd64.whl", hash = "sha256:82ca366a844eb551daff9d2e6e7a9e5e76d2612c8564f58db6c19a726869c1df", size = 2108329 },
+ { url = "https://files.pythonhosted.org/packages/dd/1c/3d2a893c020fcc18463794e0a687de58044d1c8a9892d23548ca7e71274a/sqlalchemy-2.0.41-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9a420a91913092d1e20c86a2f5f1fc85c1a8924dbcaf5e0586df8aceb09c9cc2", size = 2121327 },
+ { url = "https://files.pythonhosted.org/packages/3e/84/389c8f7c7b465682c4e5ba97f6e7825149a6625c629e09b5e872ec3b378f/sqlalchemy-2.0.41-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:906e6b0d7d452e9a98e5ab8507c0da791856b2380fdee61b765632bb8698026f", size = 2110739 },
+ { url = "https://files.pythonhosted.org/packages/b2/3d/036e84ecb46d6687fa57dc25ab366dff50773a19364def210b8770fd1516/sqlalchemy-2.0.41-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a373a400f3e9bac95ba2a06372c4fd1412a7cee53c37fc6c05f829bf672b8769", size = 3198018 },
+ { url = "https://files.pythonhosted.org/packages/8d/de/112e2142bf730a16a6cb43efc87e36dd62426e155727490c041130c6e852/sqlalchemy-2.0.41-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:087b6b52de812741c27231b5a3586384d60c353fbd0e2f81405a814b5591dc8b", size = 3197074 },
+ { url = "https://files.pythonhosted.org/packages/d4/be/a766c78ec3050cb5b734c3087cd20bafd7370b0ab0c8636a87652631af1f/sqlalchemy-2.0.41-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:34ea30ab3ec98355235972dadc497bb659cc75f8292b760394824fab9cf39826", size = 3138698 },
+ { url = "https://files.pythonhosted.org/packages/e5/c3/245e39ec45e1a8c86ff1ac3a88b13d0457307ac728eaeb217834a3ac6813/sqlalchemy-2.0.41-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:8280856dd7c6a68ab3a164b4a4b1c51f7691f6d04af4d4ca23d6ecf2261b7923", size = 3160877 },
+ { url = "https://files.pythonhosted.org/packages/d7/0c/cda8631405f6417208e160070b513bb752da0885e462fce42ac200c8262f/sqlalchemy-2.0.41-cp39-cp39-win32.whl", hash = "sha256:b50eab9994d64f4a823ff99a0ed28a6903224ddbe7fef56a6dd865eec9243440", size = 2089270 },
+ { url = "https://files.pythonhosted.org/packages/b0/1f/f68c58970d80ea5a1868ca5dc965d154a3b711f9ab06376ad9840d1475b8/sqlalchemy-2.0.41-cp39-cp39-win_amd64.whl", hash = "sha256:5e22575d169529ac3e0a120cf050ec9daa94b6a9597993d1702884f6954a7d71", size = 2113134 },
+ { url = "https://files.pythonhosted.org/packages/1c/fc/9ba22f01b5cdacc8f5ed0d22304718d2c758fce3fd49a5372b886a86f37c/sqlalchemy-2.0.41-py3-none-any.whl", hash = "sha256:57df5dc6fdb5ed1a88a1ed2195fd31927e705cad62dedd86b46972752a80f576", size = 1911224 },
+]
+
+[package.optional-dependencies]
+asyncio = [
+ { name = "greenlet" },
+]
+
+[[package]]
+name = "stack-data"
+version = "0.6.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "asttokens" },
+ { name = "executing" },
+ { name = "pure-eval" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/28/e3/55dcc2cfbc3ca9c29519eb6884dd1415ecb53b0e934862d3559ddcb7e20b/stack_data-0.6.3.tar.gz", hash = "sha256:836a778de4fec4dcd1dcd89ed8abff8a221f58308462e1c4aa2a3cf30148f0b9", size = 44707 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f1/7b/ce1eafaf1a76852e2ec9b22edecf1daa58175c090266e9f6c64afcd81d91/stack_data-0.6.3-py3-none-any.whl", hash = "sha256:d5558e0c25a4cb0853cddad3d77da9891a08cb85dd9f9f91b9f8cd66e511e695", size = 24521 },
+]
+
+[[package]]
+name = "starlette"
+version = "0.46.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "typing-extensions", marker = "python_full_version < '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ce/20/08dfcd9c983f6a6f4a1000d934b9e6d626cff8d2eeb77a89a68eef20a2b7/starlette-0.46.2.tar.gz", hash = "sha256:7f7361f34eed179294600af672f565727419830b54b7b084efe44bb82d2fccd5", size = 2580846 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8b/0c/9d30a4ebeb6db2b25a841afbb80f6ef9a854fc3b41be131d249a977b4959/starlette-0.46.2-py3-none-any.whl", hash = "sha256:595633ce89f8ffa71a015caed34a5b2dc1c0cdb3f0f1fbd1e69339cf2abeec35", size = 72037 },
+]
+
+[[package]]
+name = "striprtf"
+version = "0.0.26"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/25/20/3d419008265346452d09e5dadfd5d045b64b40d8fc31af40588e6c76997a/striprtf-0.0.26.tar.gz", hash = "sha256:fdb2bba7ac440072d1c41eab50d8d74ae88f60a8b6575c6e2c7805dc462093aa", size = 6258 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a3/cf/0fea4f4ba3fc2772ac2419278aa9f6964124d4302117d61bc055758e000c/striprtf-0.0.26-py3-none-any.whl", hash = "sha256:8c8f9d32083cdc2e8bfb149455aa1cc5a4e0a035893bedc75db8b73becb3a1bb", size = 6914 },
+]
+
+[[package]]
+name = "sympy"
+version = "1.14.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mpmath" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353 },
+]
+
+[[package]]
+name = "tenacity"
+version = "9.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0a/d4/2b0cd0fe285e14b36db076e78c93766ff1d529d70408bd1d2a5a84f1d929/tenacity-9.1.2.tar.gz", hash = "sha256:1169d376c297e7de388d18b4481760d478b0e99a777cad3a9c86e556f4b697cb", size = 48036 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e5/30/643397144bfbfec6f6ef821f36f33e57d35946c44a2352d3c9f0ae847619/tenacity-9.1.2-py3-none-any.whl", hash = "sha256:f77bf36710d8b73a50b2dd155c97b870017ad21afe6ab300326b0371b3b05138", size = 28248 },
+]
+
+[[package]]
+name = "threadpoolctl"
+version = "3.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b7/4d/08c89e34946fce2aec4fbb45c9016efd5f4d7f24af8e5d93296e935631d8/threadpoolctl-3.6.0.tar.gz", hash = "sha256:8ab8b4aa3491d812b623328249fab5302a68d2d71745c8a4c719a2fcaba9f44e", size = 21274 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638 },
+]
+
+[[package]]
+name = "tiktoken"
+version = "0.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "regex" },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ea/cf/756fedf6981e82897f2d570dd25fa597eb3f4459068ae0572d7e888cfd6f/tiktoken-0.9.0.tar.gz", hash = "sha256:d02a5ca6a938e0490e1ff957bc48c8b078c88cb83977be1625b1fd8aac792c5d", size = 35991 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/64/f3/50ec5709fad61641e4411eb1b9ac55b99801d71f1993c29853f256c726c9/tiktoken-0.9.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:586c16358138b96ea804c034b8acf3f5d3f0258bd2bc3b0227af4af5d622e382", size = 1065770 },
+ { url = "https://files.pythonhosted.org/packages/d6/f8/5a9560a422cf1755b6e0a9a436e14090eeb878d8ec0f80e0cd3d45b78bf4/tiktoken-0.9.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d9c59ccc528c6c5dd51820b3474402f69d9a9e1d656226848ad68a8d5b2e5108", size = 1009314 },
+ { url = "https://files.pythonhosted.org/packages/bc/20/3ed4cfff8f809cb902900ae686069e029db74567ee10d017cb254df1d598/tiktoken-0.9.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0968d5beeafbca2a72c595e8385a1a1f8af58feaebb02b227229b69ca5357fd", size = 1143140 },
+ { url = "https://files.pythonhosted.org/packages/f1/95/cc2c6d79df8f113bdc6c99cdec985a878768120d87d839a34da4bd3ff90a/tiktoken-0.9.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:92a5fb085a6a3b7350b8fc838baf493317ca0e17bd95e8642f95fc69ecfed1de", size = 1197860 },
+ { url = "https://files.pythonhosted.org/packages/c7/6c/9c1a4cc51573e8867c9381db1814223c09ebb4716779c7f845d48688b9c8/tiktoken-0.9.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:15a2752dea63d93b0332fb0ddb05dd909371ededa145fe6a3242f46724fa7990", size = 1259661 },
+ { url = "https://files.pythonhosted.org/packages/cd/4c/22eb8e9856a2b1808d0a002d171e534eac03f96dbe1161978d7389a59498/tiktoken-0.9.0-cp310-cp310-win_amd64.whl", hash = "sha256:26113fec3bd7a352e4b33dbaf1bd8948de2507e30bd95a44e2b1156647bc01b4", size = 894026 },
+ { url = "https://files.pythonhosted.org/packages/4d/ae/4613a59a2a48e761c5161237fc850eb470b4bb93696db89da51b79a871f1/tiktoken-0.9.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:f32cc56168eac4851109e9b5d327637f15fd662aa30dd79f964b7c39fbadd26e", size = 1065987 },
+ { url = "https://files.pythonhosted.org/packages/3f/86/55d9d1f5b5a7e1164d0f1538a85529b5fcba2b105f92db3622e5d7de6522/tiktoken-0.9.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:45556bc41241e5294063508caf901bf92ba52d8ef9222023f83d2483a3055348", size = 1009155 },
+ { url = "https://files.pythonhosted.org/packages/03/58/01fb6240df083b7c1916d1dcb024e2b761213c95d576e9f780dfb5625a76/tiktoken-0.9.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:03935988a91d6d3216e2ec7c645afbb3d870b37bcb67ada1943ec48678e7ee33", size = 1142898 },
+ { url = "https://files.pythonhosted.org/packages/b1/73/41591c525680cd460a6becf56c9b17468d3711b1df242c53d2c7b2183d16/tiktoken-0.9.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b3d80aad8d2c6b9238fc1a5524542087c52b860b10cbf952429ffb714bc1136", size = 1197535 },
+ { url = "https://files.pythonhosted.org/packages/7d/7c/1069f25521c8f01a1a182f362e5c8e0337907fae91b368b7da9c3e39b810/tiktoken-0.9.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b2a21133be05dc116b1d0372af051cd2c6aa1d2188250c9b553f9fa49301b336", size = 1259548 },
+ { url = "https://files.pythonhosted.org/packages/6f/07/c67ad1724b8e14e2b4c8cca04b15da158733ac60136879131db05dda7c30/tiktoken-0.9.0-cp311-cp311-win_amd64.whl", hash = "sha256:11a20e67fdf58b0e2dea7b8654a288e481bb4fc0289d3ad21291f8d0849915fb", size = 893895 },
+ { url = "https://files.pythonhosted.org/packages/cf/e5/21ff33ecfa2101c1bb0f9b6df750553bd873b7fb532ce2cb276ff40b197f/tiktoken-0.9.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:e88f121c1c22b726649ce67c089b90ddda8b9662545a8aeb03cfef15967ddd03", size = 1065073 },
+ { url = "https://files.pythonhosted.org/packages/8e/03/a95e7b4863ee9ceec1c55983e4cc9558bcfd8f4f80e19c4f8a99642f697d/tiktoken-0.9.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a6600660f2f72369acb13a57fb3e212434ed38b045fd8cc6cdd74947b4b5d210", size = 1008075 },
+ { url = "https://files.pythonhosted.org/packages/40/10/1305bb02a561595088235a513ec73e50b32e74364fef4de519da69bc8010/tiktoken-0.9.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:95e811743b5dfa74f4b227927ed86cbc57cad4df859cb3b643be797914e41794", size = 1140754 },
+ { url = "https://files.pythonhosted.org/packages/1b/40/da42522018ca496432ffd02793c3a72a739ac04c3794a4914570c9bb2925/tiktoken-0.9.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:99376e1370d59bcf6935c933cb9ba64adc29033b7e73f5f7569f3aad86552b22", size = 1196678 },
+ { url = "https://files.pythonhosted.org/packages/5c/41/1e59dddaae270ba20187ceb8aa52c75b24ffc09f547233991d5fd822838b/tiktoken-0.9.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:badb947c32739fb6ddde173e14885fb3de4d32ab9d8c591cbd013c22b4c31dd2", size = 1259283 },
+ { url = "https://files.pythonhosted.org/packages/5b/64/b16003419a1d7728d0d8c0d56a4c24325e7b10a21a9dd1fc0f7115c02f0a/tiktoken-0.9.0-cp312-cp312-win_amd64.whl", hash = "sha256:5a62d7a25225bafed786a524c1b9f0910a1128f4232615bf3f8257a73aaa3b16", size = 894897 },
+ { url = "https://files.pythonhosted.org/packages/7a/11/09d936d37f49f4f494ffe660af44acd2d99eb2429d60a57c71318af214e0/tiktoken-0.9.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2b0e8e05a26eda1249e824156d537015480af7ae222ccb798e5234ae0285dbdb", size = 1064919 },
+ { url = "https://files.pythonhosted.org/packages/80/0e/f38ba35713edb8d4197ae602e80837d574244ced7fb1b6070b31c29816e0/tiktoken-0.9.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:27d457f096f87685195eea0165a1807fae87b97b2161fe8c9b1df5bd74ca6f63", size = 1007877 },
+ { url = "https://files.pythonhosted.org/packages/fe/82/9197f77421e2a01373e27a79dd36efdd99e6b4115746ecc553318ecafbf0/tiktoken-0.9.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cf8ded49cddf825390e36dd1ad35cd49589e8161fdcb52aa25f0583e90a3e01", size = 1140095 },
+ { url = "https://files.pythonhosted.org/packages/f2/bb/4513da71cac187383541facd0291c4572b03ec23c561de5811781bbd988f/tiktoken-0.9.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc156cb314119a8bb9748257a2eaebd5cc0753b6cb491d26694ed42fc7cb3139", size = 1195649 },
+ { url = "https://files.pythonhosted.org/packages/fa/5c/74e4c137530dd8504e97e3a41729b1103a4ac29036cbfd3250b11fd29451/tiktoken-0.9.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:cd69372e8c9dd761f0ab873112aba55a0e3e506332dd9f7522ca466e817b1b7a", size = 1258465 },
+ { url = "https://files.pythonhosted.org/packages/de/a8/8f499c179ec900783ffe133e9aab10044481679bb9aad78436d239eee716/tiktoken-0.9.0-cp313-cp313-win_amd64.whl", hash = "sha256:5ea0edb6f83dc56d794723286215918c1cde03712cbbafa0348b33448faf5b95", size = 894669 },
+ { url = "https://files.pythonhosted.org/packages/c4/92/4d681b5c066d417b98f22a0176358d9e606e183c6b61c337d61fb54accb4/tiktoken-0.9.0-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:c6386ca815e7d96ef5b4ac61e0048cd32ca5a92d5781255e13b31381d28667dc", size = 1066217 },
+ { url = "https://files.pythonhosted.org/packages/12/dd/af27bbe186df481666de48cf0f2f4e0643ba9c78b472e7bf70144c663b22/tiktoken-0.9.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:75f6d5db5bc2c6274b674ceab1615c1778e6416b14705827d19b40e6355f03e0", size = 1009441 },
+ { url = "https://files.pythonhosted.org/packages/33/35/2792b7dcb8b150d2767322637513c73a3e80833c19212efea80b31087894/tiktoken-0.9.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e15b16f61e6f4625a57a36496d28dd182a8a60ec20a534c5343ba3cafa156ac7", size = 1144423 },
+ { url = "https://files.pythonhosted.org/packages/65/ae/4d1682510172ce3500bbed3b206ebc4efefe280f0bf1179cfb043f88cc16/tiktoken-0.9.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ebcec91babf21297022882344c3f7d9eed855931466c3311b1ad6b64befb3df", size = 1199002 },
+ { url = "https://files.pythonhosted.org/packages/1c/2e/df2dc31dd161190f315829775a9652ea01d60f307af8f98e35bdd14a6a93/tiktoken-0.9.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:e5fd49e7799579240f03913447c0cdfa1129625ebd5ac440787afc4345990427", size = 1260610 },
+ { url = "https://files.pythonhosted.org/packages/70/22/e8fc1bf9cdecc439b7ddc28a45b976a8c699a38874c070749d855696368a/tiktoken-0.9.0-cp39-cp39-win_amd64.whl", hash = "sha256:26242ca9dc8b58e875ff4ca078b9a94d2f0813e6a535dcd2205df5d49d927cc7", size = 894215 },
+]
+
+[[package]]
+name = "tokenizers"
+version = "0.21.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "huggingface-hub" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/92/76/5ac0c97f1117b91b7eb7323dcd61af80d72f790b4df71249a7850c195f30/tokenizers-0.21.1.tar.gz", hash = "sha256:a1bb04dc5b448985f86ecd4b05407f5a8d97cb2c0532199b2a302a604a0165ab", size = 343256 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a5/1f/328aee25f9115bf04262e8b4e5a2050b7b7cf44b59c74e982db7270c7f30/tokenizers-0.21.1-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e78e413e9e668ad790a29456e677d9d3aa50a9ad311a40905d6861ba7692cf41", size = 2780767 },
+ { url = "https://files.pythonhosted.org/packages/ae/1a/4526797f3719b0287853f12c5ad563a9be09d446c44ac784cdd7c50f76ab/tokenizers-0.21.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:cd51cd0a91ecc801633829fcd1fda9cf8682ed3477c6243b9a095539de4aecf3", size = 2650555 },
+ { url = "https://files.pythonhosted.org/packages/4d/7a/a209b29f971a9fdc1da86f917fe4524564924db50d13f0724feed37b2a4d/tokenizers-0.21.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:28da6b72d4fb14ee200a1bd386ff74ade8992d7f725f2bde2c495a9a98cf4d9f", size = 2937541 },
+ { url = "https://files.pythonhosted.org/packages/3c/1e/b788b50ffc6191e0b1fc2b0d49df8cff16fe415302e5ceb89f619d12c5bc/tokenizers-0.21.1-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:34d8cfde551c9916cb92014e040806122295a6800914bab5865deb85623931cf", size = 2819058 },
+ { url = "https://files.pythonhosted.org/packages/36/aa/3626dfa09a0ecc5b57a8c58eeaeb7dd7ca9a37ad9dd681edab5acd55764c/tokenizers-0.21.1-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aaa852d23e125b73d283c98f007e06d4595732104b65402f46e8ef24b588d9f8", size = 3133278 },
+ { url = "https://files.pythonhosted.org/packages/a4/4d/8fbc203838b3d26269f944a89459d94c858f5b3f9a9b6ee9728cdcf69161/tokenizers-0.21.1-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a21a15d5c8e603331b8a59548bbe113564136dc0f5ad8306dd5033459a226da0", size = 3144253 },
+ { url = "https://files.pythonhosted.org/packages/d8/1b/2bd062adeb7c7511b847b32e356024980c0ffcf35f28947792c2d8ad2288/tokenizers-0.21.1-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2fdbd4c067c60a0ac7eca14b6bd18a5bebace54eb757c706b47ea93204f7a37c", size = 3398225 },
+ { url = "https://files.pythonhosted.org/packages/8a/63/38be071b0c8e06840bc6046991636bcb30c27f6bb1e670f4f4bc87cf49cc/tokenizers-0.21.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2dd9a0061e403546f7377df940e866c3e678d7d4e9643d0461ea442b4f89e61a", size = 3038874 },
+ { url = "https://files.pythonhosted.org/packages/ec/83/afa94193c09246417c23a3c75a8a0a96bf44ab5630a3015538d0c316dd4b/tokenizers-0.21.1-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:db9484aeb2e200c43b915a1a0150ea885e35f357a5a8fabf7373af333dcc8dbf", size = 9014448 },
+ { url = "https://files.pythonhosted.org/packages/ae/b3/0e1a37d4f84c0f014d43701c11eb8072704f6efe8d8fc2dcdb79c47d76de/tokenizers-0.21.1-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:ed248ab5279e601a30a4d67bdb897ecbe955a50f1e7bb62bd99f07dd11c2f5b6", size = 8937877 },
+ { url = "https://files.pythonhosted.org/packages/ac/33/ff08f50e6d615eb180a4a328c65907feb6ded0b8f990ec923969759dc379/tokenizers-0.21.1-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:9ac78b12e541d4ce67b4dfd970e44c060a2147b9b2a21f509566d556a509c67d", size = 9186645 },
+ { url = "https://files.pythonhosted.org/packages/5f/aa/8ae85f69a9f6012c6f8011c6f4aa1c96154c816e9eea2e1b758601157833/tokenizers-0.21.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e5a69c1a4496b81a5ee5d2c1f3f7fbdf95e90a0196101b0ee89ed9956b8a168f", size = 9384380 },
+ { url = "https://files.pythonhosted.org/packages/e8/5b/a5d98c89f747455e8b7a9504910c865d5e51da55e825a7ae641fb5ff0a58/tokenizers-0.21.1-cp39-abi3-win32.whl", hash = "sha256:1039a3a5734944e09de1d48761ade94e00d0fa760c0e0551151d4dd851ba63e3", size = 2239506 },
+ { url = "https://files.pythonhosted.org/packages/e6/b6/072a8e053ae600dcc2ac0da81a23548e3b523301a442a6ca900e92ac35be/tokenizers-0.21.1-cp39-abi3-win_amd64.whl", hash = "sha256:0f0dcbcc9f6e13e675a66d7a5f2f225a736745ce484c1a4e07476a89ccdad382", size = 2435481 },
+]
+
+[[package]]
+name = "tomli"
+version = "2.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077 },
+ { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429 },
+ { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067 },
+ { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030 },
+ { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898 },
+ { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894 },
+ { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319 },
+ { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273 },
+ { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310 },
+ { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309 },
+ { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762 },
+ { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453 },
+ { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486 },
+ { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349 },
+ { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159 },
+ { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243 },
+ { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645 },
+ { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584 },
+ { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875 },
+ { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418 },
+ { url = "https://files.pythonhosted.org/packages/04/90/2ee5f2e0362cb8a0b6499dc44f4d7d48f8fff06d28ba46e6f1eaa61a1388/tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7", size = 132708 },
+ { url = "https://files.pythonhosted.org/packages/c0/ec/46b4108816de6b385141f082ba99e315501ccd0a2ea23db4a100dd3990ea/tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c", size = 123582 },
+ { url = "https://files.pythonhosted.org/packages/a0/bd/b470466d0137b37b68d24556c38a0cc819e8febe392d5b199dcd7f578365/tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13", size = 232543 },
+ { url = "https://files.pythonhosted.org/packages/d9/e5/82e80ff3b751373f7cead2815bcbe2d51c895b3c990686741a8e56ec42ab/tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281", size = 241691 },
+ { url = "https://files.pythonhosted.org/packages/05/7e/2a110bc2713557d6a1bfb06af23dd01e7dde52b6ee7dadc589868f9abfac/tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272", size = 251170 },
+ { url = "https://files.pythonhosted.org/packages/64/7b/22d713946efe00e0adbcdfd6d1aa119ae03fd0b60ebed51ebb3fa9f5a2e5/tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140", size = 236530 },
+ { url = "https://files.pythonhosted.org/packages/38/31/3a76f67da4b0cf37b742ca76beaf819dca0ebef26d78fc794a576e08accf/tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2", size = 258666 },
+ { url = "https://files.pythonhosted.org/packages/07/10/5af1293da642aded87e8a988753945d0cf7e00a9452d3911dd3bb354c9e2/tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744", size = 243954 },
+ { url = "https://files.pythonhosted.org/packages/5b/b9/1ed31d167be802da0fc95020d04cd27b7d7065cc6fbefdd2f9186f60d7bd/tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec", size = 98724 },
+ { url = "https://files.pythonhosted.org/packages/c7/32/b0963458706accd9afcfeb867c0f9175a741bf7b19cd424230714d722198/tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69", size = 109383 },
+ { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257 },
+]
+
+[[package]]
+name = "torch"
+version = "2.7.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "filelock" },
+ { name = "fsspec" },
+ { name = "jinja2" },
+ { name = "networkx", version = "3.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "networkx", version = "3.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.10.*'" },
+ { name = "networkx", version = "3.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
+ { name = "nvidia-cublas-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cuda-cupti-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cuda-nvrtc-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cuda-runtime-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cudnn-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cufft-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cufile-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-curand-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cusolver-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cusparse-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-cusparselt-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-nccl-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-nvjitlink-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "nvidia-nvtx-cu12", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "setuptools", marker = "python_full_version >= '3.12'" },
+ { name = "sympy" },
+ { name = "triton", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+ { name = "typing-extensions" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6a/27/2e06cb52adf89fe6e020963529d17ed51532fc73c1e6d1b18420ef03338c/torch-2.7.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:a103b5d782af5bd119b81dbcc7ffc6fa09904c423ff8db397a1e6ea8fd71508f", size = 99089441 },
+ { url = "https://files.pythonhosted.org/packages/0a/7c/0a5b3aee977596459ec45be2220370fde8e017f651fecc40522fd478cb1e/torch-2.7.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:fe955951bdf32d182ee8ead6c3186ad54781492bf03d547d31771a01b3d6fb7d", size = 821154516 },
+ { url = "https://files.pythonhosted.org/packages/f9/91/3d709cfc5e15995fb3fe7a6b564ce42280d3a55676dad672205e94f34ac9/torch-2.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:885453d6fba67d9991132143bf7fa06b79b24352f4506fd4d10b309f53454162", size = 216093147 },
+ { url = "https://files.pythonhosted.org/packages/92/f6/5da3918414e07da9866ecb9330fe6ffdebe15cb9a4c5ada7d4b6e0a6654d/torch-2.7.1-cp310-none-macosx_11_0_arm64.whl", hash = "sha256:d72acfdb86cee2a32c0ce0101606f3758f0d8bb5f8f31e7920dc2809e963aa7c", size = 68630914 },
+ { url = "https://files.pythonhosted.org/packages/11/56/2eae3494e3d375533034a8e8cf0ba163363e996d85f0629441fa9d9843fe/torch-2.7.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:236f501f2e383f1cb861337bdf057712182f910f10aeaf509065d54d339e49b2", size = 99093039 },
+ { url = "https://files.pythonhosted.org/packages/e5/94/34b80bd172d0072c9979708ccd279c2da2f55c3ef318eceec276ab9544a4/torch-2.7.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:06eea61f859436622e78dd0cdd51dbc8f8c6d76917a9cf0555a333f9eac31ec1", size = 821174704 },
+ { url = "https://files.pythonhosted.org/packages/50/9e/acf04ff375b0b49a45511c55d188bcea5c942da2aaf293096676110086d1/torch-2.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:8273145a2e0a3c6f9fd2ac36762d6ee89c26d430e612b95a99885df083b04e52", size = 216095937 },
+ { url = "https://files.pythonhosted.org/packages/5b/2b/d36d57c66ff031f93b4fa432e86802f84991477e522adcdffd314454326b/torch-2.7.1-cp311-none-macosx_11_0_arm64.whl", hash = "sha256:aea4fc1bf433d12843eb2c6b2204861f43d8364597697074c8d38ae2507f8730", size = 68640034 },
+ { url = "https://files.pythonhosted.org/packages/87/93/fb505a5022a2e908d81fe9a5e0aa84c86c0d5f408173be71c6018836f34e/torch-2.7.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:27ea1e518df4c9de73af7e8a720770f3628e7f667280bce2be7a16292697e3fa", size = 98948276 },
+ { url = "https://files.pythonhosted.org/packages/56/7e/67c3fe2b8c33f40af06326a3d6ae7776b3e3a01daa8f71d125d78594d874/torch-2.7.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c33360cfc2edd976c2633b3b66c769bdcbbf0e0b6550606d188431c81e7dd1fc", size = 821025792 },
+ { url = "https://files.pythonhosted.org/packages/a1/37/a37495502bc7a23bf34f89584fa5a78e25bae7b8da513bc1b8f97afb7009/torch-2.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:d8bf6e1856ddd1807e79dc57e54d3335f2b62e6f316ed13ed3ecfe1fc1df3d8b", size = 216050349 },
+ { url = "https://files.pythonhosted.org/packages/3a/60/04b77281c730bb13460628e518c52721257814ac6c298acd25757f6a175c/torch-2.7.1-cp312-none-macosx_11_0_arm64.whl", hash = "sha256:787687087412c4bd68d315e39bc1223f08aae1d16a9e9771d95eabbb04ae98fb", size = 68645146 },
+ { url = "https://files.pythonhosted.org/packages/66/81/e48c9edb655ee8eb8c2a6026abdb6f8d2146abd1f150979ede807bb75dcb/torch-2.7.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:03563603d931e70722dce0e11999d53aa80a375a3d78e6b39b9f6805ea0a8d28", size = 98946649 },
+ { url = "https://files.pythonhosted.org/packages/3a/24/efe2f520d75274fc06b695c616415a1e8a1021d87a13c68ff9dce733d088/torch-2.7.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:d632f5417b6980f61404a125b999ca6ebd0b8b4bbdbb5fbbba44374ab619a412", size = 821033192 },
+ { url = "https://files.pythonhosted.org/packages/dd/d9/9c24d230333ff4e9b6807274f6f8d52a864210b52ec794c5def7925f4495/torch-2.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:23660443e13995ee93e3d844786701ea4ca69f337027b05182f5ba053ce43b38", size = 216055668 },
+ { url = "https://files.pythonhosted.org/packages/95/bf/e086ee36ddcef9299f6e708d3b6c8487c1651787bb9ee2939eb2a7f74911/torch-2.7.1-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:0da4f4dba9f65d0d203794e619fe7ca3247a55ffdcbd17ae8fb83c8b2dc9b585", size = 68925988 },
+ { url = "https://files.pythonhosted.org/packages/69/6a/67090dcfe1cf9048448b31555af6efb149f7afa0a310a366adbdada32105/torch-2.7.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:e08d7e6f21a617fe38eeb46dd2213ded43f27c072e9165dc27300c9ef9570934", size = 99028857 },
+ { url = "https://files.pythonhosted.org/packages/90/1c/48b988870823d1cc381f15ec4e70ed3d65e043f43f919329b0045ae83529/torch-2.7.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:30207f672328a42df4f2174b8f426f354b2baa0b7cca3a0adb3d6ab5daf00dc8", size = 821098066 },
+ { url = "https://files.pythonhosted.org/packages/7b/eb/10050d61c9d5140c5dc04a89ed3257ef1a6b93e49dd91b95363d757071e0/torch-2.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:79042feca1c634aaf6603fe6feea8c6b30dfa140a6bbc0b973e2260c7e79a22e", size = 216336310 },
+ { url = "https://files.pythonhosted.org/packages/b1/29/beb45cdf5c4fc3ebe282bf5eafc8dfd925ead7299b3c97491900fe5ed844/torch-2.7.1-cp313-none-macosx_11_0_arm64.whl", hash = "sha256:988b0cbc4333618a1056d2ebad9eb10089637b659eb645434d0809d8d937b946", size = 68645708 },
+ { url = "https://files.pythonhosted.org/packages/71/8a/7db5ed2696e9d67dbc7f8df02d0bc1680b68a0552a3c07ea2d1795fb3f19/torch-2.7.1-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:e0d81e9a12764b6f3879a866607c8ae93113cbcad57ce01ebde63eb48a576369", size = 99140587 },
+ { url = "https://files.pythonhosted.org/packages/95/7b/62bedf718e6100c6d1d53fbdb7e56cb7ad80912a57f2bc7f4f1f289988f1/torch-2.7.1-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:8394833c44484547ed4a47162318337b88c97acdb3273d85ea06e03ffff44998", size = 821146689 },
+ { url = "https://files.pythonhosted.org/packages/ed/e3/80230d0eec3a4dd1b5d2b423e663026452ac8ffb64aeac1619febc1b4ac7/torch-2.7.1-cp39-cp39-win_amd64.whl", hash = "sha256:df41989d9300e6e3c19ec9f56f856187a6ef060c3662fe54f4b6baf1fc90bd19", size = 215987480 },
+ { url = "https://files.pythonhosted.org/packages/62/77/6391214d084a85aeb099d520420d39f405928b6a5f27a3f1a453c27c5173/torch-2.7.1-cp39-none-macosx_11_0_arm64.whl", hash = "sha256:a737b5edd1c44a5c1ece2e9f3d00df9d1b3fb9541138bee56d83d38293fb6c9d", size = 68630146 },
+]
+
+[[package]]
+name = "torch-memory-saver"
+version = "0.0.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b1/c4/8e05c4a2b625c7831f26ead7710c428bac5e651ea2d1ec35a6a875f0de2c/torch_memory_saver-0.0.6.tar.gz", hash = "sha256:df012df2fdda20a45c7f5d95e2488080c15fbcc88e1f98f703eea3c2ba026d4a", size = 5486 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/68/75/081a1fdc3dc23b412383c9c006465ec591762b01a6d8001892fdc8c939e7/torch_memory_saver-0.0.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:8a5fb45b5e1f5bea9ce68b1fa184badc5c699d133f4f90af5eeb36d908d7ef4a", size = 94867 },
+]
+
+[[package]]
+name = "torchao"
+version = "0.9.0"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7d/fe/a24225d30775192a4c5d9cea3ecb95e6adc69d0a8b5ed98eb8e58d362344/torchao-0.9.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bc708910301a9f98344d43f3fe2aa6d5e1fab706d772b6df47ff05087d664145", size = 5652091 },
+ { url = "https://files.pythonhosted.org/packages/db/72/01f755514fb61eadc80b974eb4bd4f22f3009b35457773523e3bd497c511/torchao-0.9.0-py3-none-any.whl", hash = "sha256:ea5603c32762f1a9ade1a4dc7b00f5246623b24a28e49e666f614c79a408712a", size = 712541 },
+]
+
+[[package]]
+name = "torchaudio"
+version = "2.7.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "torch" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/da/71/bfc6d2b28ede6c4c5446901cfa4d98fa25b2606eb12e641baccec16fcde0/torchaudio-2.7.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:4739af57d0eb94347d1c6a1b5668be78a7383afe826dde18a04883b9f9f263b1", size = 1842457 },
+ { url = "https://files.pythonhosted.org/packages/e6/8c/35eea5138ccd4abf38b163743d5ab4a8b25349bafa8bdf3d629e7f3036b9/torchaudio-2.7.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:c089dbfc14c5f47091b7bf3f6bf2bbac93b86619299d04d9c102f4ad53758990", size = 1680682 },
+ { url = "https://files.pythonhosted.org/packages/7d/dc/7569889c1fc95ebf18b0295bc4fdebafbbb89ba9e0018c7e9b0844bae011/torchaudio-2.7.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:6bb1e6db22fa2aad6b89b2a455ec5c6dc31df2635dbfafa213394f8b07b09516", size = 3498891 },
+ { url = "https://files.pythonhosted.org/packages/b3/e0/ff0ac4234798a0b6b1398fa878a2e7d22f1d06d4327feb312d9e77e079bd/torchaudio-2.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:2ba4df6e3ad35cb1e5bd162cf86b492526138f6476f5a06b10725b8880c618eb", size = 2483343 },
+ { url = "https://files.pythonhosted.org/packages/85/a2/52e6760d352584ae1ab139d97647bdc51d1eb7d480b688fe69c72616c956/torchaudio-2.7.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d5a62f88c629035913f506df03f710c48fc8bb9637191933f27c67088d5ca136", size = 1849254 },
+ { url = "https://files.pythonhosted.org/packages/df/e6/0f3835895f9d0b8900ca4a7196932b13b74156ad9ffb76e7aacfc5bb4157/torchaudio-2.7.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:53bc4ba12e7468be34a7ca2ee837ee5c8bd5755b25c12f665af9339cae37e265", size = 1686156 },
+ { url = "https://files.pythonhosted.org/packages/0d/c5/8ba8869ac5607bbd83ea864bda2c628f8b7b55a9200f8147687995e95a49/torchaudio-2.7.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:f8bd69354a397753b9dea9699d9e1251f8496fbbdf3028c7086a57a615bf33c3", size = 3508053 },
+ { url = "https://files.pythonhosted.org/packages/78/cc/11709b2cbf841eda124918523088d9aaa1509ae4400f346192037e6de6c6/torchaudio-2.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:0ae0678ad27355eebea5a9fdd9ae9bfec444f8405f9b6c60026905ba3665c43a", size = 2488974 },
+ { url = "https://files.pythonhosted.org/packages/0b/d1/eb8bc3b3502dddb1b789567b7b19668b1d32817266887b9f381494cfe463/torchaudio-2.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9306dcfc4586cebd7647a93fe9a448e791c4f83934da616b9433b75597a1f978", size = 1846897 },
+ { url = "https://files.pythonhosted.org/packages/62/7d/6c15f15d3edc5271abc808f70713644b50f0f7bfb85a09dba8b5735fbad3/torchaudio-2.7.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:d66bd76b226fdd4135c97650e1b7eb63fb7659b4ed0e3a778898e41dbba21b61", size = 1686680 },
+ { url = "https://files.pythonhosted.org/packages/48/65/0f46ba74cdc67ea9a8c37c8acfb5194d81639e481e85903c076bcd97188c/torchaudio-2.7.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:9cbcdaab77ad9a73711acffee58f4eebc8a0685289a938a3fa6f660af9489aee", size = 3506966 },
+ { url = "https://files.pythonhosted.org/packages/52/29/06f887baf22cbba85ae331b71b110b115bf11b3968f5914a50c17dde5ab7/torchaudio-2.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:9cfb8f6ace8e01e2b89de74eb893ba5ce936b88b415383605b0a4d974009dec7", size = 2484265 },
+ { url = "https://files.pythonhosted.org/packages/b6/ee/6e308868b9467e1b51da9d781cb73dd5aadca7c8b6256f88ce5d18a7fb77/torchaudio-2.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e5f0599a507f4683546878ed9667e1b32d7ca3c8a957e4c15c6b302378ef4dee", size = 1847208 },
+ { url = "https://files.pythonhosted.org/packages/3a/f9/ca0e0960526e6deaa476d168b877480a3fbae5d44668a54de963a9800097/torchaudio-2.7.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:271f717844e5c7f9e05c8328de817bf90f46d83281c791e94f54d4edea2f5817", size = 1686311 },
+ { url = "https://files.pythonhosted.org/packages/bb/ab/83f282ca5475ae34c58520a4a97b6d69438bc699d70d16432deb19791cda/torchaudio-2.7.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:1862b063d8d4e55cb4862bcbd63568545f549825a3c5605bd312224c3ebb1919", size = 3507174 },
+ { url = "https://files.pythonhosted.org/packages/12/91/dbd17a6eda4b0504d9b4f1f721a1654456e39f7178b8462344f942100865/torchaudio-2.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:edb4deaa6f95acd5522912ed643303d0b86d79a6f15914362f5a5d49baaf5d13", size = 2484503 },
+ { url = "https://files.pythonhosted.org/packages/73/5e/da52d2fa9f7cc89512b63dd8a88fb3e097a89815f440cc16159b216ec611/torchaudio-2.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:18560955b8beb2a8d39a6bfae20a442337afcefb3dfd4ee007ce82233a796799", size = 1929983 },
+ { url = "https://files.pythonhosted.org/packages/f7/16/9d03dc62613f276f9666eb0609164287df23986b67d20b53e78d21a3d8d8/torchaudio-2.7.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:1850475ef9101ea0b3593fe93ff6ee4e7a20598f6da6510761220b9fe56eb7fa", size = 1700436 },
+ { url = "https://files.pythonhosted.org/packages/83/45/57a437fe41b302fc79b4eb78fdb3e480ff42c66270e7505eedf0b000969c/torchaudio-2.7.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:98257fc14dd493ba5a3258fb6d61d27cd64a48ee79537c3964c4da26b9bf295f", size = 3521631 },
+ { url = "https://files.pythonhosted.org/packages/91/5e/9262a7e41e47bc87eb245c4fc485eb26ff41a05886b241c003440c9e0107/torchaudio-2.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:c802e0dcbf38669007327bb52f065573cc5cac106eaca987f6e1a32e6282263a", size = 2534956 },
+ { url = "https://files.pythonhosted.org/packages/3b/67/82ee183a867d5138b594a5c07be403d8efd0e010b3ea8a7e135058e965cd/torchaudio-2.7.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a07100fe2cf7af4fa69d8cb046a2b74046612621a1a548afa5af1c69e02eaf81", size = 1843193 },
+ { url = "https://files.pythonhosted.org/packages/a5/57/6f7c8b9c00970248498152549f004587db0a83e6caad0025c9723994ffc9/torchaudio-2.7.1-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:e8b2da11a7f7782b00b823c99e812eb00ee8b3455ad474f8fd42a0da0bc4f46a", size = 1681224 },
+ { url = "https://files.pythonhosted.org/packages/37/7b/0bf5da00d883b241bd4986e2d26dc1aabd16cc860c4c5d4bc9237e6350c3/torchaudio-2.7.1-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:9ce8aed225d5ce65705d30f6ef8e457d329fe6ea0b8729ad953ba99e87da264e", size = 3502377 },
+ { url = "https://files.pythonhosted.org/packages/26/99/00764e98c82d0b48a1e1fd059a0f10cf1bec741013a7e9c05077bd1fd481/torchaudio-2.7.1-cp39-cp39-win_amd64.whl", hash = "sha256:30e21f043f5cc50f703c2cf0de75633e2c720227f9bf848ffc9b8b987871b3fc", size = 2477692 },
+]
+
+[[package]]
+name = "torchvision"
+version = "0.22.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "pillow" },
+ { name = "torch" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/15/2c/7b67117b14c6cc84ae3126ca6981abfa3af2ac54eb5252b80d9475fb40df/torchvision-0.22.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:3b47d8369ee568c067795c0da0b4078f39a9dfea6f3bc1f3ac87530dfda1dd56", size = 1947825 },
+ { url = "https://files.pythonhosted.org/packages/6c/9f/c4dcf1d232b75e28bc37e21209ab2458d6d60235e16163544ed693de54cb/torchvision-0.22.1-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:990de4d657a41ed71680cd8be2e98ebcab55371f30993dc9bd2e676441f7180e", size = 2512611 },
+ { url = "https://files.pythonhosted.org/packages/e2/99/db71d62d12628111d59147095527a0ab492bdfecfba718d174c04ae6c505/torchvision-0.22.1-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:3347f690c2eed6d02aa0edfb9b01d321e7f7cf1051992d96d8d196c39b881d49", size = 7485668 },
+ { url = "https://files.pythonhosted.org/packages/32/ff/4a93a4623c3e5f97e8552af0f9f81d289dcf7f2ac71f1493f1c93a6b973d/torchvision-0.22.1-cp310-cp310-win_amd64.whl", hash = "sha256:86ad938f5a6ca645f0d5fb19484b1762492c2188c0ffb05c602e9e9945b7b371", size = 1707961 },
+ { url = "https://files.pythonhosted.org/packages/f6/00/bdab236ef19da050290abc2b5203ff9945c84a1f2c7aab73e8e9c8c85669/torchvision-0.22.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4addf626e2b57fc22fd6d329cf1346d474497672e6af8383b7b5b636fba94a53", size = 1947827 },
+ { url = "https://files.pythonhosted.org/packages/ac/d0/18f951b2be3cfe48c0027b349dcc6fde950e3dc95dd83e037e86f284f6fd/torchvision-0.22.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:8b4a53a6067d63adba0c52f2b8dd2290db649d642021674ee43c0c922f0c6a69", size = 2514021 },
+ { url = "https://files.pythonhosted.org/packages/c3/1a/63eb241598b36d37a0221e10af357da34bd33402ccf5c0765e389642218a/torchvision-0.22.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:b7866a3b326413e67724ac46f1ee594996735e10521ba9e6cdbe0fa3cd98c2f2", size = 7487300 },
+ { url = "https://files.pythonhosted.org/packages/e5/73/1b009b42fe4a7774ba19c23c26bb0f020d68525c417a348b166f1c56044f/torchvision-0.22.1-cp311-cp311-win_amd64.whl", hash = "sha256:bb3f6df6f8fd415ce38ec4fd338376ad40c62e86052d7fc706a0dd51efac1718", size = 1707989 },
+ { url = "https://files.pythonhosted.org/packages/02/90/f4e99a5112dc221cf68a485e853cc3d9f3f1787cb950b895f3ea26d1ea98/torchvision-0.22.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:153f1790e505bd6da123e21eee6e83e2e155df05c0fe7d56347303067d8543c5", size = 1947827 },
+ { url = "https://files.pythonhosted.org/packages/25/f6/53e65384cdbbe732cc2106bb04f7fb908487e4fb02ae4a1613ce6904a122/torchvision-0.22.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:964414eef19459d55a10e886e2fca50677550e243586d1678f65e3f6f6bac47a", size = 2514576 },
+ { url = "https://files.pythonhosted.org/packages/17/8b/155f99042f9319bd7759536779b2a5b67cbd4f89c380854670850f89a2f4/torchvision-0.22.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:699c2d70d33951187f6ed910ea05720b9b4aaac1dcc1135f53162ce7d42481d3", size = 7485962 },
+ { url = "https://files.pythonhosted.org/packages/05/17/e45d5cd3627efdb47587a0634179a3533593436219de3f20c743672d2a79/torchvision-0.22.1-cp312-cp312-win_amd64.whl", hash = "sha256:75e0897da7a8e43d78632f66f2bdc4f6e26da8d3f021a7c0fa83746073c2597b", size = 1707992 },
+ { url = "https://files.pythonhosted.org/packages/7a/30/fecdd09fb973e963da68207fe9f3d03ec6f39a935516dc2a98397bf495c6/torchvision-0.22.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9c3ae3319624c43cc8127020f46c14aa878406781f0899bb6283ae474afeafbf", size = 1947818 },
+ { url = "https://files.pythonhosted.org/packages/55/f4/b45f6cd92fa0acfac5e31b8e9258232f25bcdb0709a604e8b8a39d76e411/torchvision-0.22.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:4a614a6a408d2ed74208d0ea6c28a2fbb68290e9a7df206c5fef3f0b6865d307", size = 2471597 },
+ { url = "https://files.pythonhosted.org/packages/8d/b0/3cffd6a285b5ffee3fe4a31caff49e350c98c5963854474d1c4f7a51dea5/torchvision-0.22.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:7ee682be589bb1a002b7704f06b8ec0b89e4b9068f48e79307d2c6e937a9fdf4", size = 7485894 },
+ { url = "https://files.pythonhosted.org/packages/fd/1d/0ede596fedc2080d18108149921278b59f220fbb398f29619495337b0f86/torchvision-0.22.1-cp313-cp313-win_amd64.whl", hash = "sha256:2566cafcfa47ecfdbeed04bab8cef1307c8d4ef75046f7624b9e55f384880dfe", size = 1708020 },
+ { url = "https://files.pythonhosted.org/packages/0f/ca/e9a06bd61ee8e04fb4962a3fb524fe6ee4051662db07840b702a9f339b24/torchvision-0.22.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:043d9e35ed69c2e586aff6eb9e2887382e7863707115668ac9d140da58f42cba", size = 2137623 },
+ { url = "https://files.pythonhosted.org/packages/ab/c8/2ebe90f18e7ffa2120f5c3eab62aa86923185f78d2d051a455ea91461608/torchvision-0.22.1-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:27142bcc8a984227a6dcf560985e83f52b82a7d3f5fe9051af586a2ccc46ef26", size = 2476561 },
+ { url = "https://files.pythonhosted.org/packages/94/8b/04c6b15f8c29b39f0679589753091cec8b192ab296d4fdaf9055544c4ec9/torchvision-0.22.1-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:ef46e065502f7300ad6abc98554131c35dc4c837b978d91306658f1a65c00baa", size = 7658543 },
+ { url = "https://files.pythonhosted.org/packages/ab/c0/131628e6d42682b0502c63fd7f647b8b5ca4bd94088f6c85ca7225db8ac4/torchvision-0.22.1-cp313-cp313t-win_amd64.whl", hash = "sha256:7414eeacfb941fa21acddcd725f1617da5630ec822e498660a4b864d7d998075", size = 1629892 },
+ { url = "https://files.pythonhosted.org/packages/1f/91/cfd4dfab7893acebb7cea9b60cf9624a0a107681249c68b1b41fb10b2286/torchvision-0.22.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8be941b4d35c0aba819be70fdbbbed8ceb60401ce6996b8cfaaba1300ce62263", size = 1947875 },
+ { url = "https://files.pythonhosted.org/packages/bd/e9/2c13d5aba26be09bcbb799e54955b5526eb75f630957bc2c24133e9e350e/torchvision-0.22.1-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:154a2bdc37a16122c2024f2f77e65f5986020b40c013515c694b5d357fac99a1", size = 2512672 },
+ { url = "https://files.pythonhosted.org/packages/be/b0/ac3158206bff9e3ceadace60a753e4e21ce499daf0e6716184e9265a2855/torchvision-0.22.1-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:ef7dee376f42900c0e7b0e34624f391d9ece70ab90ee74b42de0c1fffe371284", size = 7487053 },
+ { url = "https://files.pythonhosted.org/packages/2e/ba/aa10c0771588420a81fa1ea3666801856d1fb57abc186f16d64a7c86c105/torchvision-0.22.1-cp39-cp39-win_amd64.whl", hash = "sha256:e01631046fda25a1eca2f58d5fdc9a152b93740eb82435cdb27c5151b8d20c02", size = 1707934 },
+]
+
+[[package]]
+name = "tqdm"
+version = "4.67.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a8/4b/29b4ef32e036bb34e4ab51796dd745cdba7ed47ad142a9f4a1eb8e0c744d/tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2", size = 169737 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540 },
+]
+
+[[package]]
+name = "traitlets"
+version = "5.14.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/eb/79/72064e6a701c2183016abbbfedaba506d81e30e232a68c9f0d6f6fcd1574/traitlets-5.14.3.tar.gz", hash = "sha256:9ed0579d3502c94b4b3732ac120375cda96f923114522847de4b3bb98b96b6b7", size = 161621 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/00/c0/8f5d070730d7836adc9c9b6408dec68c6ced86b304a9b26a14df072a6e8c/traitlets-5.14.3-py3-none-any.whl", hash = "sha256:b74e89e397b1ed28cc831db7aea759ba6640cb3de13090ca145426688ff1ac4f", size = 85359 },
+]
+
+[[package]]
+name = "transformers"
+version = "4.52.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "filelock" },
+ { name = "huggingface-hub" },
+ { name = "numpy" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "regex" },
+ { name = "requests" },
+ { name = "safetensors" },
+ { name = "tokenizers" },
+ { name = "tqdm" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/07/42/271bcf364788337ac24e7f200005ac7142aaf022206bd6119d2daca22c04/transformers-4.52.3.tar.gz", hash = "sha256:2e1de29374f27920aaf6d589d4e6339f33def2fb08809e1a1d792e040e9fbce7", size = 8951324 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/36/f8/1f086942bc6a044e4e68dacf6de761a45367795efd5f57ad356765691c79/transformers-4.52.3-py3-none-any.whl", hash = "sha256:cd04059da50e7cf2a617ce3143ba8beffbf119f8c25a0717c3454fd9d0f19609", size = 10460322 },
+]
+
+[package.optional-dependencies]
+sentencepiece = [
+ { name = "protobuf" },
+ { name = "sentencepiece" },
+]
+
+[[package]]
+name = "triton"
+version = "3.3.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "setuptools" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8d/a9/549e51e9b1b2c9b854fd761a1d23df0ba2fbc60bd0c13b489ffa518cfcb7/triton-3.3.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b74db445b1c562844d3cfad6e9679c72e93fdfb1a90a24052b03bb5c49d1242e", size = 155600257 },
+ { url = "https://files.pythonhosted.org/packages/21/2f/3e56ea7b58f80ff68899b1dbe810ff257c9d177d288c6b0f55bf2fe4eb50/triton-3.3.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b31e3aa26f8cb3cc5bf4e187bf737cbacf17311e1112b781d4a059353dfd731b", size = 155689937 },
+ { url = "https://files.pythonhosted.org/packages/24/5f/950fb373bf9c01ad4eb5a8cd5eaf32cdf9e238c02f9293557a2129b9c4ac/triton-3.3.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9999e83aba21e1a78c1f36f21bce621b77bcaa530277a50484a7cb4a822f6e43", size = 155669138 },
+ { url = "https://files.pythonhosted.org/packages/74/1f/dfb531f90a2d367d914adfee771babbd3f1a5b26c3f5fbc458dee21daa78/triton-3.3.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b89d846b5a4198317fec27a5d3a609ea96b6d557ff44b56c23176546023c4240", size = 155673035 },
+ { url = "https://files.pythonhosted.org/packages/28/71/bd20ffcb7a64c753dc2463489a61bf69d531f308e390ad06390268c4ea04/triton-3.3.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a3198adb9d78b77818a5388bff89fa72ff36f9da0bc689db2f0a651a67ce6a42", size = 155735832 },
+ { url = "https://files.pythonhosted.org/packages/6d/81/ac4d50af22f594c4cb7c84fd2ad5ba1e0c03e2a83fe3483ddd79edcd7ec7/triton-3.3.1-cp39-cp39-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f6139aeb04a146b0b8e0fbbd89ad1e65861c57cfed881f21d62d3cb94a36bab7", size = 155596799 },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.14.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d1/bc/51647cd02527e87d05cb083ccc402f93e441606ff1f01739a62c8ad09ba5/typing_extensions-4.14.0.tar.gz", hash = "sha256:8676b788e32f02ab42d9e7c61324048ae4c6d844a399eebace3d4979d75ceef4", size = 107423 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/69/e0/552843e0d356fbb5256d21449fa957fa4eff3bbc135a74a691ee70c7c5da/typing_extensions-4.14.0-py3-none-any.whl", hash = "sha256:a1514509136dd0b477638fc68d6a91497af5076466ad0fa6c338e44e359944af", size = 43839 },
+]
+
+[[package]]
+name = "typing-inspect"
+version = "0.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mypy-extensions" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/dc/74/1789779d91f1961fa9438e9a8710cdae6bd138c80d7303996933d117264a/typing_inspect-0.9.0.tar.gz", hash = "sha256:b23fc42ff6f6ef6954e4852c1fb512cdd18dbea03134f91f856a95ccc9461f78", size = 13825 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/65/f3/107a22063bf27bdccf2024833d3445f4eea42b2e598abfbd46f6a63b6cb0/typing_inspect-0.9.0-py3-none-any.whl", hash = "sha256:9ee6fc59062311ef8547596ab6b955e1b8aa46242d854bfc78f4f6b0eff35f9f", size = 8827 },
+]
+
+[[package]]
+name = "typing-inspection"
+version = "0.4.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f8/b1/0c11f5058406b3af7609f121aaa6b609744687f1d158b3c3a5bf4cc94238/typing_inspection-0.4.1.tar.gz", hash = "sha256:6ae134cc0203c33377d43188d4064e9b357dba58cff3185f22924610e70a9d28", size = 75726 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/17/69/cd203477f944c353c31bade965f880aa1061fd6bf05ded0726ca845b6ff7/typing_inspection-0.4.1-py3-none-any.whl", hash = "sha256:389055682238f53b04f7badcb49b989835495a96700ced5dab2d8feae4b26f51", size = 14552 },
+]
+
+[[package]]
+name = "tzdata"
+version = "2025.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/95/32/1a225d6164441be760d75c2c42e2780dc0873fe382da3e98a2e1e48361e5/tzdata-2025.2.tar.gz", hash = "sha256:b60a638fcc0daffadf82fe0f57e53d06bdec2f36c4df66280ae79bce6bd6f2b9", size = 196380 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5c/23/c7abc0ca0a1526a0774eca151daeb8de62ec457e77262b66b359c3c7679e/tzdata-2025.2-py2.py3-none-any.whl", hash = "sha256:1a403fada01ff9221ca8044d701868fa132215d84beb92242d9acd2147f667a8", size = 347839 },
+]
+
+[[package]]
+name = "urllib3"
+version = "2.4.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8a/78/16493d9c386d8e60e442a35feac5e00f0913c0f4b7c217c11e8ec2ff53e0/urllib3-2.4.0.tar.gz", hash = "sha256:414bc6535b787febd7567804cc015fee39daab8ad86268f1310a9250697de466", size = 390672 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6b/11/cc635220681e93a0183390e26485430ca2c7b5f9d33b15c74c2861cb8091/urllib3-2.4.0-py3-none-any.whl", hash = "sha256:4e16665048960a0900c702d4a66415956a584919c03361cac9f1df5c5dd7e813", size = 128680 },
+]
+
+[[package]]
+name = "uvicorn"
+version = "0.34.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "h11" },
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/de/ad/713be230bcda622eaa35c28f0d328c3675c371238470abdea52417f17a8e/uvicorn-0.34.3.tar.gz", hash = "sha256:35919a9a979d7a59334b6b10e05d77c1d0d574c50e0fc98b8b1a0f165708b55a", size = 76631 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6d/0d/8adfeaa62945f90d19ddc461c55f4a50c258af7662d34b6a3d5d1f8646f6/uvicorn-0.34.3-py3-none-any.whl", hash = "sha256:16246631db62bdfbf069b0645177d6e8a77ba950cfedbfd093acef9444e4d885", size = 62431 },
+]
+
+[[package]]
+name = "uvloop"
+version = "0.21.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/af/c0/854216d09d33c543f12a44b393c402e89a920b1a0a7dc634c42de91b9cf6/uvloop-0.21.0.tar.gz", hash = "sha256:3bf12b0fda68447806a7ad847bfa591613177275d35b6724b1ee573faa3704e3", size = 2492741 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3d/76/44a55515e8c9505aa1420aebacf4dd82552e5e15691654894e90d0bd051a/uvloop-0.21.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ec7e6b09a6fdded42403182ab6b832b71f4edaf7f37a9a0e371a01db5f0cb45f", size = 1442019 },
+ { url = "https://files.pythonhosted.org/packages/35/5a/62d5800358a78cc25c8a6c72ef8b10851bdb8cca22e14d9c74167b7f86da/uvloop-0.21.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:196274f2adb9689a289ad7d65700d37df0c0930fd8e4e743fa4834e850d7719d", size = 801898 },
+ { url = "https://files.pythonhosted.org/packages/f3/96/63695e0ebd7da6c741ccd4489b5947394435e198a1382349c17b1146bb97/uvloop-0.21.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f38b2e090258d051d68a5b14d1da7203a3c3677321cf32a95a6f4db4dd8b6f26", size = 3827735 },
+ { url = "https://files.pythonhosted.org/packages/61/e0/f0f8ec84979068ffae132c58c79af1de9cceeb664076beea86d941af1a30/uvloop-0.21.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:87c43e0f13022b998eb9b973b5e97200c8b90823454d4bc06ab33829e09fb9bb", size = 3825126 },
+ { url = "https://files.pythonhosted.org/packages/bf/fe/5e94a977d058a54a19df95f12f7161ab6e323ad49f4dabc28822eb2df7ea/uvloop-0.21.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:10d66943def5fcb6e7b37310eb6b5639fd2ccbc38df1177262b0640c3ca68c1f", size = 3705789 },
+ { url = "https://files.pythonhosted.org/packages/26/dd/c7179618e46092a77e036650c1f056041a028a35c4d76945089fcfc38af8/uvloop-0.21.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:67dd654b8ca23aed0a8e99010b4c34aca62f4b7fce88f39d452ed7622c94845c", size = 3800523 },
+ { url = "https://files.pythonhosted.org/packages/57/a7/4cf0334105c1160dd6819f3297f8700fda7fc30ab4f61fbf3e725acbc7cc/uvloop-0.21.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:c0f3fa6200b3108919f8bdabb9a7f87f20e7097ea3c543754cabc7d717d95cf8", size = 1447410 },
+ { url = "https://files.pythonhosted.org/packages/8c/7c/1517b0bbc2dbe784b563d6ab54f2ef88c890fdad77232c98ed490aa07132/uvloop-0.21.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0878c2640cf341b269b7e128b1a5fed890adc4455513ca710d77d5e93aa6d6a0", size = 805476 },
+ { url = "https://files.pythonhosted.org/packages/ee/ea/0bfae1aceb82a503f358d8d2fa126ca9dbdb2ba9c7866974faec1cb5875c/uvloop-0.21.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9fb766bb57b7388745d8bcc53a359b116b8a04c83a2288069809d2b3466c37e", size = 3960855 },
+ { url = "https://files.pythonhosted.org/packages/8a/ca/0864176a649838b838f36d44bf31c451597ab363b60dc9e09c9630619d41/uvloop-0.21.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a375441696e2eda1c43c44ccb66e04d61ceeffcd76e4929e527b7fa401b90fb", size = 3973185 },
+ { url = "https://files.pythonhosted.org/packages/30/bf/08ad29979a936d63787ba47a540de2132169f140d54aa25bc8c3df3e67f4/uvloop-0.21.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:baa0e6291d91649c6ba4ed4b2f982f9fa165b5bbd50a9e203c416a2797bab3c6", size = 3820256 },
+ { url = "https://files.pythonhosted.org/packages/da/e2/5cf6ef37e3daf2f06e651aae5ea108ad30df3cb269102678b61ebf1fdf42/uvloop-0.21.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4509360fcc4c3bd2c70d87573ad472de40c13387f5fda8cb58350a1d7475e58d", size = 3937323 },
+ { url = "https://files.pythonhosted.org/packages/8c/4c/03f93178830dc7ce8b4cdee1d36770d2f5ebb6f3d37d354e061eefc73545/uvloop-0.21.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:359ec2c888397b9e592a889c4d72ba3d6befba8b2bb01743f72fffbde663b59c", size = 1471284 },
+ { url = "https://files.pythonhosted.org/packages/43/3e/92c03f4d05e50f09251bd8b2b2b584a2a7f8fe600008bcc4523337abe676/uvloop-0.21.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f7089d2dc73179ce5ac255bdf37c236a9f914b264825fdaacaded6990a7fb4c2", size = 821349 },
+ { url = "https://files.pythonhosted.org/packages/a6/ef/a02ec5da49909dbbfb1fd205a9a1ac4e88ea92dcae885e7c961847cd51e2/uvloop-0.21.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:baa4dcdbd9ae0a372f2167a207cd98c9f9a1ea1188a8a526431eef2f8116cc8d", size = 4580089 },
+ { url = "https://files.pythonhosted.org/packages/06/a7/b4e6a19925c900be9f98bec0a75e6e8f79bb53bdeb891916609ab3958967/uvloop-0.21.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:86975dca1c773a2c9864f4c52c5a55631038e387b47eaf56210f873887b6c8dc", size = 4693770 },
+ { url = "https://files.pythonhosted.org/packages/ce/0c/f07435a18a4b94ce6bd0677d8319cd3de61f3a9eeb1e5f8ab4e8b5edfcb3/uvloop-0.21.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:461d9ae6660fbbafedd07559c6a2e57cd553b34b0065b6550685f6653a98c1cb", size = 4451321 },
+ { url = "https://files.pythonhosted.org/packages/8f/eb/f7032be105877bcf924709c97b1bf3b90255b4ec251f9340cef912559f28/uvloop-0.21.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:183aef7c8730e54c9a3ee3227464daed66e37ba13040bb3f350bc2ddc040f22f", size = 4659022 },
+ { url = "https://files.pythonhosted.org/packages/3f/8d/2cbef610ca21539f0f36e2b34da49302029e7c9f09acef0b1c3b5839412b/uvloop-0.21.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:bfd55dfcc2a512316e65f16e503e9e450cab148ef11df4e4e679b5e8253a5281", size = 1468123 },
+ { url = "https://files.pythonhosted.org/packages/93/0d/b0038d5a469f94ed8f2b2fce2434a18396d8fbfb5da85a0a9781ebbdec14/uvloop-0.21.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:787ae31ad8a2856fc4e7c095341cccc7209bd657d0e71ad0dc2ea83c4a6fa8af", size = 819325 },
+ { url = "https://files.pythonhosted.org/packages/50/94/0a687f39e78c4c1e02e3272c6b2ccdb4e0085fda3b8352fecd0410ccf915/uvloop-0.21.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ee4d4ef48036ff6e5cfffb09dd192c7a5027153948d85b8da7ff705065bacc6", size = 4582806 },
+ { url = "https://files.pythonhosted.org/packages/d2/19/f5b78616566ea68edd42aacaf645adbf71fbd83fc52281fba555dc27e3f1/uvloop-0.21.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f3df876acd7ec037a3d005b3ab85a7e4110422e4d9c1571d4fc89b0fc41b6816", size = 4701068 },
+ { url = "https://files.pythonhosted.org/packages/47/57/66f061ee118f413cd22a656de622925097170b9380b30091b78ea0c6ea75/uvloop-0.21.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:bd53ecc9a0f3d87ab847503c2e1552b690362e005ab54e8a48ba97da3924c0dc", size = 4454428 },
+ { url = "https://files.pythonhosted.org/packages/63/9a/0962b05b308494e3202d3f794a6e85abe471fe3cafdbcf95c2e8c713aabd/uvloop-0.21.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a5c39f217ab3c663dc699c04cbd50c13813e31d917642d459fdcec07555cc553", size = 4660018 },
+ { url = "https://files.pythonhosted.org/packages/3c/a4/646a9d0edff7cde25fc1734695d3dfcee0501140dd0e723e4df3f0a50acb/uvloop-0.21.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c097078b8031190c934ed0ebfee8cc5f9ba9642e6eb88322b9958b649750f72b", size = 1439646 },
+ { url = "https://files.pythonhosted.org/packages/01/2e/e128c66106af9728f86ebfeeb52af27ecd3cb09336f3e2f3e06053707a15/uvloop-0.21.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:46923b0b5ee7fc0020bef24afe7836cb068f5050ca04caf6b487c513dc1a20b2", size = 800931 },
+ { url = "https://files.pythonhosted.org/packages/2d/1a/9fbc2b1543d0df11f7aed1632f64bdf5ecc4053cf98cdc9edb91a65494f9/uvloop-0.21.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:53e420a3afe22cdcf2a0f4846e377d16e718bc70103d7088a4f7623567ba5fb0", size = 3829660 },
+ { url = "https://files.pythonhosted.org/packages/b8/c0/392e235e4100ae3b95b5c6dac77f82b529d2760942b1e7e0981e5d8e895d/uvloop-0.21.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:88cb67cdbc0e483da00af0b2c3cdad4b7c61ceb1ee0f33fe00e09c81e3a6cb75", size = 3827185 },
+ { url = "https://files.pythonhosted.org/packages/e1/24/a5da6aba58f99aed5255eca87d58d1760853e8302d390820cc29058408e3/uvloop-0.21.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:221f4f2a1f46032b403bf3be628011caf75428ee3cc204a22addf96f586b19fd", size = 3705833 },
+ { url = "https://files.pythonhosted.org/packages/1a/5c/6ba221bb60f1e6474474102e17e38612ec7a06dc320e22b687ab563d877f/uvloop-0.21.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:2d1f581393673ce119355d56da84fe1dd9d2bb8b3d13ce792524e1607139feff", size = 3804696 },
+]
+
+[[package]]
+name = "wcwidth"
+version = "0.2.13"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6c/63/53559446a878410fc5a5974feb13d31d78d752eb18aeba59c7fef1af7598/wcwidth-0.2.13.tar.gz", hash = "sha256:72ea0c06399eb286d978fdedb6923a9eb47e1c486ce63e9b4e64fc18303972b5", size = 101301 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/84/fd2ba7aafacbad3c4201d395674fc6348826569da3c0937e75505ead3528/wcwidth-0.2.13-py2.py3-none-any.whl", hash = "sha256:3da69048e4540d84af32131829ff948f1e022c1c6bdb8d6102117aac784f6859", size = 34166 },
+]
+
+[[package]]
+name = "werkzeug"
+version = "3.1.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markupsafe" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9f/69/83029f1f6300c5fb2471d621ab06f6ec6b3324685a2ce0f9777fd4a8b71e/werkzeug-3.1.3.tar.gz", hash = "sha256:60723ce945c19328679790e3282cc758aa4a6040e4bb330f53d30fa546d44746", size = 806925 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/52/24/ab44c871b0f07f491e5d2ad12c9bd7358e527510618cb1b803a88e986db1/werkzeug-3.1.3-py3-none-any.whl", hash = "sha256:54b78bf3716d19a65be4fceccc0d1d7b89e608834989dfae50ea87564639213e", size = 224498 },
+]
+
+[[package]]
+name = "wrapt"
+version = "1.17.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c3/fc/e91cc220803d7bc4db93fb02facd8461c37364151b8494762cc88b0fbcef/wrapt-1.17.2.tar.gz", hash = "sha256:41388e9d4d1522446fe79d3213196bd9e3b301a336965b9e27ca2788ebd122f3", size = 55531 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5a/d1/1daec934997e8b160040c78d7b31789f19b122110a75eca3d4e8da0049e1/wrapt-1.17.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:3d57c572081fed831ad2d26fd430d565b76aa277ed1d30ff4d40670b1c0dd984", size = 53307 },
+ { url = "https://files.pythonhosted.org/packages/1b/7b/13369d42651b809389c1a7153baa01d9700430576c81a2f5c5e460df0ed9/wrapt-1.17.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b5e251054542ae57ac7f3fba5d10bfff615b6c2fb09abeb37d2f1463f841ae22", size = 38486 },
+ { url = "https://files.pythonhosted.org/packages/62/bf/e0105016f907c30b4bd9e377867c48c34dc9c6c0c104556c9c9126bd89ed/wrapt-1.17.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:80dd7db6a7cb57ffbc279c4394246414ec99537ae81ffd702443335a61dbf3a7", size = 38777 },
+ { url = "https://files.pythonhosted.org/packages/27/70/0f6e0679845cbf8b165e027d43402a55494779295c4b08414097b258ac87/wrapt-1.17.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a6e821770cf99cc586d33833b2ff32faebdbe886bd6322395606cf55153246c", size = 83314 },
+ { url = "https://files.pythonhosted.org/packages/0f/77/0576d841bf84af8579124a93d216f55d6f74374e4445264cb378a6ed33eb/wrapt-1.17.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b60fb58b90c6d63779cb0c0c54eeb38941bae3ecf7a73c764c52c88c2dcb9d72", size = 74947 },
+ { url = "https://files.pythonhosted.org/packages/90/ec/00759565518f268ed707dcc40f7eeec38637d46b098a1f5143bff488fe97/wrapt-1.17.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b870b5df5b71d8c3359d21be8f0d6c485fa0ebdb6477dda51a1ea54a9b558061", size = 82778 },
+ { url = "https://files.pythonhosted.org/packages/f8/5a/7cffd26b1c607b0b0c8a9ca9d75757ad7620c9c0a9b4a25d3f8a1480fafc/wrapt-1.17.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4011d137b9955791f9084749cba9a367c68d50ab8d11d64c50ba1688c9b457f2", size = 81716 },
+ { url = "https://files.pythonhosted.org/packages/7e/09/dccf68fa98e862df7e6a60a61d43d644b7d095a5fc36dbb591bbd4a1c7b2/wrapt-1.17.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:1473400e5b2733e58b396a04eb7f35f541e1fb976d0c0724d0223dd607e0f74c", size = 74548 },
+ { url = "https://files.pythonhosted.org/packages/b7/8e/067021fa3c8814952c5e228d916963c1115b983e21393289de15128e867e/wrapt-1.17.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:3cedbfa9c940fdad3e6e941db7138e26ce8aad38ab5fe9dcfadfed9db7a54e62", size = 81334 },
+ { url = "https://files.pythonhosted.org/packages/4b/0d/9d4b5219ae4393f718699ca1c05f5ebc0c40d076f7e65fd48f5f693294fb/wrapt-1.17.2-cp310-cp310-win32.whl", hash = "sha256:582530701bff1dec6779efa00c516496968edd851fba224fbd86e46cc6b73563", size = 36427 },
+ { url = "https://files.pythonhosted.org/packages/72/6a/c5a83e8f61aec1e1aeef939807602fb880e5872371e95df2137142f5c58e/wrapt-1.17.2-cp310-cp310-win_amd64.whl", hash = "sha256:58705da316756681ad3c9c73fd15499aa4d8c69f9fd38dc8a35e06c12468582f", size = 38774 },
+ { url = "https://files.pythonhosted.org/packages/cd/f7/a2aab2cbc7a665efab072344a8949a71081eed1d2f451f7f7d2b966594a2/wrapt-1.17.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ff04ef6eec3eee8a5efef2401495967a916feaa353643defcc03fc74fe213b58", size = 53308 },
+ { url = "https://files.pythonhosted.org/packages/50/ff/149aba8365fdacef52b31a258c4dc1c57c79759c335eff0b3316a2664a64/wrapt-1.17.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4db983e7bca53819efdbd64590ee96c9213894272c776966ca6306b73e4affda", size = 38488 },
+ { url = "https://files.pythonhosted.org/packages/65/46/5a917ce85b5c3b490d35c02bf71aedaa9f2f63f2d15d9949cc4ba56e8ba9/wrapt-1.17.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9abc77a4ce4c6f2a3168ff34b1da9b0f311a8f1cfd694ec96b0603dff1c79438", size = 38776 },
+ { url = "https://files.pythonhosted.org/packages/ca/74/336c918d2915a4943501c77566db41d1bd6e9f4dbc317f356b9a244dfe83/wrapt-1.17.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0b929ac182f5ace000d459c59c2c9c33047e20e935f8e39371fa6e3b85d56f4a", size = 83776 },
+ { url = "https://files.pythonhosted.org/packages/09/99/c0c844a5ccde0fe5761d4305485297f91d67cf2a1a824c5f282e661ec7ff/wrapt-1.17.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f09b286faeff3c750a879d336fb6d8713206fc97af3adc14def0cdd349df6000", size = 75420 },
+ { url = "https://files.pythonhosted.org/packages/b4/b0/9fc566b0fe08b282c850063591a756057c3247b2362b9286429ec5bf1721/wrapt-1.17.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1a7ed2d9d039bd41e889f6fb9364554052ca21ce823580f6a07c4ec245c1f5d6", size = 83199 },
+ { url = "https://files.pythonhosted.org/packages/9d/4b/71996e62d543b0a0bd95dda485219856def3347e3e9380cc0d6cf10cfb2f/wrapt-1.17.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:129a150f5c445165ff941fc02ee27df65940fcb8a22a61828b1853c98763a64b", size = 82307 },
+ { url = "https://files.pythonhosted.org/packages/39/35/0282c0d8789c0dc9bcc738911776c762a701f95cfe113fb8f0b40e45c2b9/wrapt-1.17.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1fb5699e4464afe5c7e65fa51d4f99e0b2eadcc176e4aa33600a3df7801d6662", size = 75025 },
+ { url = "https://files.pythonhosted.org/packages/4f/6d/90c9fd2c3c6fee181feecb620d95105370198b6b98a0770cba090441a828/wrapt-1.17.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9a2bce789a5ea90e51a02dfcc39e31b7f1e662bc3317979aa7e5538e3a034f72", size = 81879 },
+ { url = "https://files.pythonhosted.org/packages/8f/fa/9fb6e594f2ce03ef03eddbdb5f4f90acb1452221a5351116c7c4708ac865/wrapt-1.17.2-cp311-cp311-win32.whl", hash = "sha256:4afd5814270fdf6380616b321fd31435a462019d834f83c8611a0ce7484c7317", size = 36419 },
+ { url = "https://files.pythonhosted.org/packages/47/f8/fb1773491a253cbc123c5d5dc15c86041f746ed30416535f2a8df1f4a392/wrapt-1.17.2-cp311-cp311-win_amd64.whl", hash = "sha256:acc130bc0375999da18e3d19e5a86403667ac0c4042a094fefb7eec8ebac7cf3", size = 38773 },
+ { url = "https://files.pythonhosted.org/packages/a1/bd/ab55f849fd1f9a58ed7ea47f5559ff09741b25f00c191231f9f059c83949/wrapt-1.17.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d5e2439eecc762cd85e7bd37161d4714aa03a33c5ba884e26c81559817ca0925", size = 53799 },
+ { url = "https://files.pythonhosted.org/packages/53/18/75ddc64c3f63988f5a1d7e10fb204ffe5762bc663f8023f18ecaf31a332e/wrapt-1.17.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fc7cb4c1c744f8c05cd5f9438a3caa6ab94ce8344e952d7c45a8ed59dd88392", size = 38821 },
+ { url = "https://files.pythonhosted.org/packages/48/2a/97928387d6ed1c1ebbfd4efc4133a0633546bec8481a2dd5ec961313a1c7/wrapt-1.17.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8fdbdb757d5390f7c675e558fd3186d590973244fab0c5fe63d373ade3e99d40", size = 38919 },
+ { url = "https://files.pythonhosted.org/packages/73/54/3bfe5a1febbbccb7a2f77de47b989c0b85ed3a6a41614b104204a788c20e/wrapt-1.17.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5bb1d0dbf99411f3d871deb6faa9aabb9d4e744d67dcaaa05399af89d847a91d", size = 88721 },
+ { url = "https://files.pythonhosted.org/packages/25/cb/7262bc1b0300b4b64af50c2720ef958c2c1917525238d661c3e9a2b71b7b/wrapt-1.17.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d18a4865f46b8579d44e4fe1e2bcbc6472ad83d98e22a26c963d46e4c125ef0b", size = 80899 },
+ { url = "https://files.pythonhosted.org/packages/2a/5a/04cde32b07a7431d4ed0553a76fdb7a61270e78c5fd5a603e190ac389f14/wrapt-1.17.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc570b5f14a79734437cb7b0500376b6b791153314986074486e0b0fa8d71d98", size = 89222 },
+ { url = "https://files.pythonhosted.org/packages/09/28/2e45a4f4771fcfb109e244d5dbe54259e970362a311b67a965555ba65026/wrapt-1.17.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6d9187b01bebc3875bac9b087948a2bccefe464a7d8f627cf6e48b1bbae30f82", size = 86707 },
+ { url = "https://files.pythonhosted.org/packages/c6/d2/dcb56bf5f32fcd4bd9aacc77b50a539abdd5b6536872413fd3f428b21bed/wrapt-1.17.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9e8659775f1adf02eb1e6f109751268e493c73716ca5761f8acb695e52a756ae", size = 79685 },
+ { url = "https://files.pythonhosted.org/packages/80/4e/eb8b353e36711347893f502ce91c770b0b0929f8f0bed2670a6856e667a9/wrapt-1.17.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e8b2816ebef96d83657b56306152a93909a83f23994f4b30ad4573b00bd11bb9", size = 87567 },
+ { url = "https://files.pythonhosted.org/packages/17/27/4fe749a54e7fae6e7146f1c7d914d28ef599dacd4416566c055564080fe2/wrapt-1.17.2-cp312-cp312-win32.whl", hash = "sha256:468090021f391fe0056ad3e807e3d9034e0fd01adcd3bdfba977b6fdf4213ea9", size = 36672 },
+ { url = "https://files.pythonhosted.org/packages/15/06/1dbf478ea45c03e78a6a8c4be4fdc3c3bddea5c8de8a93bc971415e47f0f/wrapt-1.17.2-cp312-cp312-win_amd64.whl", hash = "sha256:ec89ed91f2fa8e3f52ae53cd3cf640d6feff92ba90d62236a81e4e563ac0e991", size = 38865 },
+ { url = "https://files.pythonhosted.org/packages/ce/b9/0ffd557a92f3b11d4c5d5e0c5e4ad057bd9eb8586615cdaf901409920b14/wrapt-1.17.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6ed6ffac43aecfe6d86ec5b74b06a5be33d5bb9243d055141e8cabb12aa08125", size = 53800 },
+ { url = "https://files.pythonhosted.org/packages/c0/ef/8be90a0b7e73c32e550c73cfb2fa09db62234227ece47b0e80a05073b375/wrapt-1.17.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:35621ae4c00e056adb0009f8e86e28eb4a41a4bfa8f9bfa9fca7d343fe94f998", size = 38824 },
+ { url = "https://files.pythonhosted.org/packages/36/89/0aae34c10fe524cce30fe5fc433210376bce94cf74d05b0d68344c8ba46e/wrapt-1.17.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a604bf7a053f8362d27eb9fefd2097f82600b856d5abe996d623babd067b1ab5", size = 38920 },
+ { url = "https://files.pythonhosted.org/packages/3b/24/11c4510de906d77e0cfb5197f1b1445d4fec42c9a39ea853d482698ac681/wrapt-1.17.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5cbabee4f083b6b4cd282f5b817a867cf0b1028c54d445b7ec7cfe6505057cf8", size = 88690 },
+ { url = "https://files.pythonhosted.org/packages/71/d7/cfcf842291267bf455b3e266c0c29dcb675b5540ee8b50ba1699abf3af45/wrapt-1.17.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:49703ce2ddc220df165bd2962f8e03b84c89fee2d65e1c24a7defff6f988f4d6", size = 80861 },
+ { url = "https://files.pythonhosted.org/packages/d5/66/5d973e9f3e7370fd686fb47a9af3319418ed925c27d72ce16b791231576d/wrapt-1.17.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8112e52c5822fc4253f3901b676c55ddf288614dc7011634e2719718eaa187dc", size = 89174 },
+ { url = "https://files.pythonhosted.org/packages/a7/d3/8e17bb70f6ae25dabc1aaf990f86824e4fd98ee9cadf197054e068500d27/wrapt-1.17.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9fee687dce376205d9a494e9c121e27183b2a3df18037f89d69bd7b35bcf59e2", size = 86721 },
+ { url = "https://files.pythonhosted.org/packages/6f/54/f170dfb278fe1c30d0ff864513cff526d624ab8de3254b20abb9cffedc24/wrapt-1.17.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:18983c537e04d11cf027fbb60a1e8dfd5190e2b60cc27bc0808e653e7b218d1b", size = 79763 },
+ { url = "https://files.pythonhosted.org/packages/4a/98/de07243751f1c4a9b15c76019250210dd3486ce098c3d80d5f729cba029c/wrapt-1.17.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:703919b1633412ab54bcf920ab388735832fdcb9f9a00ae49387f0fe67dad504", size = 87585 },
+ { url = "https://files.pythonhosted.org/packages/f9/f0/13925f4bd6548013038cdeb11ee2cbd4e37c30f8bfd5db9e5a2a370d6e20/wrapt-1.17.2-cp313-cp313-win32.whl", hash = "sha256:abbb9e76177c35d4e8568e58650aa6926040d6a9f6f03435b7a522bf1c487f9a", size = 36676 },
+ { url = "https://files.pythonhosted.org/packages/bf/ae/743f16ef8c2e3628df3ddfd652b7d4c555d12c84b53f3d8218498f4ade9b/wrapt-1.17.2-cp313-cp313-win_amd64.whl", hash = "sha256:69606d7bb691b50a4240ce6b22ebb319c1cfb164e5f6569835058196e0f3a845", size = 38871 },
+ { url = "https://files.pythonhosted.org/packages/3d/bc/30f903f891a82d402ffb5fda27ec1d621cc97cb74c16fea0b6141f1d4e87/wrapt-1.17.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:4a721d3c943dae44f8e243b380cb645a709ba5bd35d3ad27bc2ed947e9c68192", size = 56312 },
+ { url = "https://files.pythonhosted.org/packages/8a/04/c97273eb491b5f1c918857cd26f314b74fc9b29224521f5b83f872253725/wrapt-1.17.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:766d8bbefcb9e00c3ac3b000d9acc51f1b399513f44d77dfe0eb026ad7c9a19b", size = 40062 },
+ { url = "https://files.pythonhosted.org/packages/4e/ca/3b7afa1eae3a9e7fefe499db9b96813f41828b9fdb016ee836c4c379dadb/wrapt-1.17.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e496a8ce2c256da1eb98bd15803a79bee00fc351f5dfb9ea82594a3f058309e0", size = 40155 },
+ { url = "https://files.pythonhosted.org/packages/89/be/7c1baed43290775cb9030c774bc53c860db140397047cc49aedaf0a15477/wrapt-1.17.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40d615e4fe22f4ad3528448c193b218e077656ca9ccb22ce2cb20db730f8d306", size = 113471 },
+ { url = "https://files.pythonhosted.org/packages/32/98/4ed894cf012b6d6aae5f5cc974006bdeb92f0241775addad3f8cd6ab71c8/wrapt-1.17.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a5aaeff38654462bc4b09023918b7f21790efb807f54c000a39d41d69cf552cb", size = 101208 },
+ { url = "https://files.pythonhosted.org/packages/ea/fd/0c30f2301ca94e655e5e057012e83284ce8c545df7661a78d8bfca2fac7a/wrapt-1.17.2-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9a7d15bbd2bc99e92e39f49a04653062ee6085c0e18b3b7512a4f2fe91f2d681", size = 109339 },
+ { url = "https://files.pythonhosted.org/packages/75/56/05d000de894c4cfcb84bcd6b1df6214297b8089a7bd324c21a4765e49b14/wrapt-1.17.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e3890b508a23299083e065f435a492b5435eba6e304a7114d2f919d400888cc6", size = 110232 },
+ { url = "https://files.pythonhosted.org/packages/53/f8/c3f6b2cf9b9277fb0813418e1503e68414cd036b3b099c823379c9575e6d/wrapt-1.17.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:8c8b293cd65ad716d13d8dd3624e42e5a19cc2a2f1acc74b30c2c13f15cb61a6", size = 100476 },
+ { url = "https://files.pythonhosted.org/packages/a7/b1/0bb11e29aa5139d90b770ebbfa167267b1fc548d2302c30c8f7572851738/wrapt-1.17.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c82b8785d98cdd9fed4cac84d765d234ed3251bd6afe34cb7ac523cb93e8b4f", size = 106377 },
+ { url = "https://files.pythonhosted.org/packages/6a/e1/0122853035b40b3f333bbb25f1939fc1045e21dd518f7f0922b60c156f7c/wrapt-1.17.2-cp313-cp313t-win32.whl", hash = "sha256:13e6afb7fe71fe7485a4550a8844cc9ffbe263c0f1a1eea569bc7091d4898555", size = 37986 },
+ { url = "https://files.pythonhosted.org/packages/09/5e/1655cf481e079c1f22d0cabdd4e51733679932718dc23bf2db175f329b76/wrapt-1.17.2-cp313-cp313t-win_amd64.whl", hash = "sha256:eaf675418ed6b3b31c7a989fd007fa7c3be66ce14e5c3b27336383604c9da85c", size = 40750 },
+ { url = "https://files.pythonhosted.org/packages/8a/f4/6ed2b8f6f1c832933283974839b88ec7c983fd12905e01e97889dadf7559/wrapt-1.17.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99039fa9e6306880572915728d7f6c24a86ec57b0a83f6b2491e1d8ab0235b9a", size = 53308 },
+ { url = "https://files.pythonhosted.org/packages/a2/a9/712a53f8f4f4545768ac532619f6e56d5d0364a87b2212531685e89aeef8/wrapt-1.17.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2696993ee1eebd20b8e4ee4356483c4cb696066ddc24bd70bcbb80fa56ff9061", size = 38489 },
+ { url = "https://files.pythonhosted.org/packages/fa/9b/e172c8f28a489a2888df18f953e2f6cb8d33b1a2e78c9dfc52d8bf6a5ead/wrapt-1.17.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:612dff5db80beef9e649c6d803a8d50c409082f1fedc9dbcdfde2983b2025b82", size = 38776 },
+ { url = "https://files.pythonhosted.org/packages/cf/cb/7a07b51762dcd59bdbe07aa97f87b3169766cadf240f48d1cbe70a1be9db/wrapt-1.17.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62c2caa1585c82b3f7a7ab56afef7b3602021d6da34fbc1cf234ff139fed3cd9", size = 83050 },
+ { url = "https://files.pythonhosted.org/packages/a5/51/a42757dd41032afd6d8037617aa3bc6803ba971850733b24dfb7d5c627c4/wrapt-1.17.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c958bcfd59bacc2d0249dcfe575e71da54f9dcf4a8bdf89c4cb9a68a1170d73f", size = 74718 },
+ { url = "https://files.pythonhosted.org/packages/bf/bb/d552bfe47db02fcfc950fc563073a33500f8108efa5f7b41db2f83a59028/wrapt-1.17.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc78a84e2dfbc27afe4b2bd7c80c8db9bca75cc5b85df52bfe634596a1da846b", size = 82590 },
+ { url = "https://files.pythonhosted.org/packages/77/99/77b06b3c3c410dbae411105bf22496facf03a5496bfaca8fbcf9da381889/wrapt-1.17.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:ba0f0eb61ef00ea10e00eb53a9129501f52385c44853dbd6c4ad3f403603083f", size = 81462 },
+ { url = "https://files.pythonhosted.org/packages/2d/21/cf0bd85ae66f92600829ea1de8e1da778e5e9f6e574ccbe74b66db0d95db/wrapt-1.17.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:1e1fe0e6ab7775fd842bc39e86f6dcfc4507ab0ffe206093e76d61cde37225c8", size = 74309 },
+ { url = "https://files.pythonhosted.org/packages/6d/16/112d25e9092398a0dd6fec50ab7ac1b775a0c19b428f049785096067ada9/wrapt-1.17.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:c86563182421896d73858e08e1db93afdd2b947a70064b813d515d66549e15f9", size = 81081 },
+ { url = "https://files.pythonhosted.org/packages/2b/49/364a615a0cc0872685646c495c7172e4fc7bf1959e3b12a1807a03014e05/wrapt-1.17.2-cp39-cp39-win32.whl", hash = "sha256:f393cda562f79828f38a819f4788641ac7c4085f30f1ce1a68672baa686482bb", size = 36423 },
+ { url = "https://files.pythonhosted.org/packages/00/ad/5d2c1b34ba3202cd833d9221833e74d6500ce66730974993a8dc9a94fb8c/wrapt-1.17.2-cp39-cp39-win_amd64.whl", hash = "sha256:36ccae62f64235cf8ddb682073a60519426fdd4725524ae38874adf72b5f2aeb", size = 38772 },
+ { url = "https://files.pythonhosted.org/packages/2d/82/f56956041adef78f849db6b289b282e72b55ab8045a75abad81898c28d19/wrapt-1.17.2-py3-none-any.whl", hash = "sha256:b18f2d1533a71f069c7f82d524a52599053d4c7166e9dd374ae2136b7f40f7c8", size = 23594 },
+]
+
+[[package]]
+name = "xgrammar"
+version = "0.1.19"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mlx-lm", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" },
+ { name = "ninja" },
+ { name = "pydantic" },
+ { name = "sentencepiece" },
+ { name = "tiktoken" },
+ { name = "torch" },
+ { name = "transformers" },
+ { name = "triton", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b5/55/73e1e4f918ade656c4fa7f3a5fcfb3d521a429fe305d2cb8ca58bfb201d4/xgrammar-0.1.19.tar.gz", hash = "sha256:75bf3e814283b1cbaee9252234c5d4081f0058d29b26d8984f1cdf031c99b775", size = 1714056 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/36/b4/aa9fd3ff607fcaafa11a70c8486f59cedd2e011432f4a72364a4a149059e/xgrammar-0.1.19-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:b9e770afe040969d4d2be1b4a8086927c12c89f3145e3601433467bb940d3ef3", size = 505167 },
+ { url = "https://files.pythonhosted.org/packages/5f/0c/058d0f98049a43ad0de2376e7d4226af3eb4022bb819c6716df2a5beb245/xgrammar-0.1.19-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a393827a63bb85e2e53ad5994db7e93359041ca5a46fa7e71e7a90312029969f", size = 458955 },
+ { url = "https://files.pythonhosted.org/packages/5a/cb/38cd04149742349a46bce5839c4f794751ad8b1aa9522c8dd8173c6a14d9/xgrammar-0.1.19-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7c071a28e00409a4b098b80fca5a6459fddefd3911fabd8e590564ce7c4b45ec", size = 5716766 },
+ { url = "https://files.pythonhosted.org/packages/1e/b2/ff4ab2473d060a1b407e97409dd6d3d8fd1346d1d314c1621968ca64d847/xgrammar-0.1.19-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f493cb36275fefd66c7aac799d7c2aaf629b9c8968c29db5aa895fcfde4e092d", size = 5833332 },
+ { url = "https://files.pythonhosted.org/packages/1b/68/8b63fc009b1eb67d70fc777c498adf011746eb902c1391a332dc145481bf/xgrammar-0.1.19-cp310-cp310-win_amd64.whl", hash = "sha256:d15680fed6b7a776e1323bc06d493e6c2730092187b6c4d9d3c22fbb220226bb", size = 528402 },
+ { url = "https://files.pythonhosted.org/packages/d1/d9/aa9b3db8ed8dd51c3a45f94d94afcc8b7f89c0de8e72aab975bd787da91e/xgrammar-0.1.19-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:fcfeac78f12b75348cce8b8c1ae75cf522cf45f38eb710697aa4512de659b93c", size = 505028 },
+ { url = "https://files.pythonhosted.org/packages/c5/53/c4ce8585699d334a3f8c78249b1369177fd13556e780e65ed732d60da088/xgrammar-0.1.19-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c151c7e73ac0550cb0bec6ee4cb4be9553bd547d246fe35c0e4fd8a6a9e9b813", size = 458745 },
+ { url = "https://files.pythonhosted.org/packages/82/7c/4989f3e73cc7080978f9882ebd68660a7d92dc2f40122f0d374dfdf70081/xgrammar-0.1.19-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:53c3b94cf1489121064e2b89bf143325e7b30410c1f8e36f83a69132bb80c451", size = 5716484 },
+ { url = "https://files.pythonhosted.org/packages/9d/47/77a6b826ff810094d059fc056393e61503beb0dfa6c53a0b27649df80ff1/xgrammar-0.1.19-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:78f02e241a2e6ec568b29da7ce049f350e2e95d2c51c5423c016b02f92941c63", size = 5831522 },
+ { url = "https://files.pythonhosted.org/packages/97/cf/b83cb7e2114cf0730d1300aa5f99957f0ff8417cfe399d2c1a64f58683f2/xgrammar-0.1.19-cp311-cp311-win_amd64.whl", hash = "sha256:9a69abe4d7a6ded512407e69b1772391f5af7db4c69220651a6bd816b68f90c9", size = 528059 },
+ { url = "https://files.pythonhosted.org/packages/3a/a8/886975ef77106ba8fad8f7c253d8aead02e1d285a831857f4a67365a7c6e/xgrammar-0.1.19-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:70f1bb54e9bdb92830424713629e37ffcd4f8e4ebbbf03a72860503e25d349bf", size = 504554 },
+ { url = "https://files.pythonhosted.org/packages/cc/9d/e27686ad71be897cda26289d7f899250f41a3fd8a12b472f1ba3ea8fc5ae/xgrammar-0.1.19-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:70ee7d359386e816eb85f9f763d68a0f2dfedb3da8601ed38e6e8e8391aa9b98", size = 457619 },
+ { url = "https://files.pythonhosted.org/packages/bc/64/e64c7a06fbbe8d610dd520cb00045c109ad4f56457198220d63830efd426/xgrammar-0.1.19-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:16439a86378f7e07d2db91f8a9645d1ff9959b018f1fae6768a057b4b3926dc7", size = 5717888 },
+ { url = "https://files.pythonhosted.org/packages/c6/68/df91740b23287d06c9d67fadd5d0dc096bb1beaf6079ab083f143545f520/xgrammar-0.1.19-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9beb2cb2b55c9524f24b3cbf8181c47e435586976aa0c37e220661f786c601f", size = 5834560 },
+ { url = "https://files.pythonhosted.org/packages/df/42/d0248e8af1c69a92c409ee06e6f07fb047567c366e4d08676b6a3bc356f6/xgrammar-0.1.19-cp312-cp312-win_amd64.whl", hash = "sha256:4a430dbf229c04539f0929069df245f5f652298e37dc3f04ce0a6aa8639546ef", size = 527418 },
+ { url = "https://files.pythonhosted.org/packages/75/80/988ba82581b74ec7638b61897fdb6725d9998ce52c26ea93b98cc0259148/xgrammar-0.1.19-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:057a883ac2f37afe15e045eaad5dad8458bdaa1b69d62f554ff7ac6ca3f4b4a7", size = 457657 },
+ { url = "https://files.pythonhosted.org/packages/de/1d/46ac48834d0166057612c5eec1bc2e9e69ff16f8de676fb379b8b53dadbd/xgrammar-0.1.19-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6f26bbcf8d4f7698c64f4304b99b45dffe4633012d0c91f1c3f687dd08696ef7", size = 5834052 },
+ { url = "https://files.pythonhosted.org/packages/e2/f5/c6eeba50fd93b03f0c9256e48d0b9f6195d30bb7ce31f5324fc1da8a90d3/xgrammar-0.1.19-cp313-cp313-win_amd64.whl", hash = "sha256:6b4bfd84df561b978e4158796adbfa23c80db96e19754483508d4f9003f2f88f", size = 527495 },
+ { url = "https://files.pythonhosted.org/packages/88/86/6b6872146223fa7259cb029690a1f115db37a40c219a8e07ef653f602e80/xgrammar-0.1.19-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:defb7cfc6b0ec114211280cf2e67bd8cbcbc6d58319a13c26be2854ed61c4dd1", size = 505471 },
+ { url = "https://files.pythonhosted.org/packages/2c/89/6c36394171a85cc59a4aaa620e0ec9bef7e174314873e2f878063357ff29/xgrammar-0.1.19-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:72da54b585cc16ef1d5222fc843f3d4227028ef2c7158050cddab0de820458af", size = 459113 },
+ { url = "https://files.pythonhosted.org/packages/78/30/b5048439431b15541fee86e7bb86b49ee2f6c54af1d7b65252ff8f00c5d4/xgrammar-0.1.19-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e198c4cfc498157fe120dfe09c4f84358d7ede48530541b8f419c7bc64b7ec2", size = 5715371 },
+ { url = "https://files.pythonhosted.org/packages/74/35/b6c378c9a259a8cf33531afa47bef4d8ff639b879f03d1ab62804b33130c/xgrammar-0.1.19-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1994a8f29fb3f7084bd48a49d7cca1bb01fcd3cd5f2e093bd02fd1278f0ed5a4", size = 5831411 },
+ { url = "https://files.pythonhosted.org/packages/05/ed/9840bb8a2e860b5858c9a0756a2d1be558c54e5c769c4d5193c538af75f7/xgrammar-0.1.19-cp39-cp39-win_amd64.whl", hash = "sha256:430400fc5ec5534229d27245c33b4c18d3428f732a80a14d3fcd2ef5b2477725", size = 528742 },
+]
+
+[[package]]
+name = "xxhash"
+version = "3.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/00/5e/d6e5258d69df8b4ed8c83b6664f2b47d30d2dec551a29ad72a6c69eafd31/xxhash-3.5.0.tar.gz", hash = "sha256:84f2caddf951c9cbf8dc2e22a89d4ccf5d86391ac6418fe81e3c67d0cf60b45f", size = 84241 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bb/8a/0e9feca390d512d293afd844d31670e25608c4a901e10202aa98785eab09/xxhash-3.5.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ece616532c499ee9afbb83078b1b952beffef121d989841f7f4b3dc5ac0fd212", size = 31970 },
+ { url = "https://files.pythonhosted.org/packages/16/e6/be5aa49580cd064a18200ab78e29b88b1127e1a8c7955eb8ecf81f2626eb/xxhash-3.5.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:3171f693dbc2cef6477054a665dc255d996646b4023fe56cb4db80e26f4cc520", size = 30801 },
+ { url = "https://files.pythonhosted.org/packages/20/ee/b8a99ebbc6d1113b3a3f09e747fa318c3cde5b04bd9c197688fadf0eeae8/xxhash-3.5.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7c5d3e570ef46adaf93fc81b44aca6002b5a4d8ca11bd0580c07eac537f36680", size = 220927 },
+ { url = "https://files.pythonhosted.org/packages/58/62/15d10582ef159283a5c2b47f6d799fc3303fe3911d5bb0bcc820e1ef7ff4/xxhash-3.5.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7cb29a034301e2982df8b1fe6328a84f4b676106a13e9135a0d7e0c3e9f806da", size = 200360 },
+ { url = "https://files.pythonhosted.org/packages/23/41/61202663ea9b1bd8e53673b8ec9e2619989353dba8cfb68e59a9cbd9ffe3/xxhash-3.5.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5d0d307d27099bb0cbeea7260eb39ed4fdb99c5542e21e94bb6fd29e49c57a23", size = 428528 },
+ { url = "https://files.pythonhosted.org/packages/f2/07/d9a3059f702dec5b3b703737afb6dda32f304f6e9da181a229dafd052c29/xxhash-3.5.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0342aafd421795d740e514bc9858ebddfc705a75a8c5046ac56d85fe97bf196", size = 194149 },
+ { url = "https://files.pythonhosted.org/packages/eb/58/27caadf78226ecf1d62dbd0c01d152ed381c14c1ee4ad01f0d460fc40eac/xxhash-3.5.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3dbbd9892c5ebffeca1ed620cf0ade13eb55a0d8c84e0751a6653adc6ac40d0c", size = 207703 },
+ { url = "https://files.pythonhosted.org/packages/b1/08/32d558ce23e1e068453c39aed7b3c1cdc690c177873ec0ca3a90d5808765/xxhash-3.5.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4cc2d67fdb4d057730c75a64c5923abfa17775ae234a71b0200346bfb0a7f482", size = 216255 },
+ { url = "https://files.pythonhosted.org/packages/3f/d4/2b971e2d2b0a61045f842b622ef11e94096cf1f12cd448b6fd426e80e0e2/xxhash-3.5.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:ec28adb204b759306a3d64358a5e5c07d7b1dd0ccbce04aa76cb9377b7b70296", size = 202744 },
+ { url = "https://files.pythonhosted.org/packages/19/ae/6a6438864a8c4c39915d7b65effd85392ebe22710412902487e51769146d/xxhash-3.5.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:1328f6d8cca2b86acb14104e381225a3d7b42c92c4b86ceae814e5c400dbb415", size = 210115 },
+ { url = "https://files.pythonhosted.org/packages/48/7d/b3c27c27d1fc868094d02fe4498ccce8cec9fcc591825c01d6bcb0b4fc49/xxhash-3.5.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:8d47ebd9f5d9607fd039c1fbf4994e3b071ea23eff42f4ecef246ab2b7334198", size = 414247 },
+ { url = "https://files.pythonhosted.org/packages/a1/05/918f9e7d2fbbd334b829997045d341d6239b563c44e683b9a7ef8fe50f5d/xxhash-3.5.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:b96d559e0fcddd3343c510a0fe2b127fbff16bf346dd76280b82292567523442", size = 191419 },
+ { url = "https://files.pythonhosted.org/packages/08/29/dfe393805b2f86bfc47c290b275f0b7c189dc2f4e136fd4754f32eb18a8d/xxhash-3.5.0-cp310-cp310-win32.whl", hash = "sha256:61c722ed8d49ac9bc26c7071eeaa1f6ff24053d553146d5df031802deffd03da", size = 30114 },
+ { url = "https://files.pythonhosted.org/packages/7b/d7/aa0b22c4ebb7c3ccb993d4c565132abc641cd11164f8952d89eb6a501909/xxhash-3.5.0-cp310-cp310-win_amd64.whl", hash = "sha256:9bed5144c6923cc902cd14bb8963f2d5e034def4486ab0bbe1f58f03f042f9a9", size = 30003 },
+ { url = "https://files.pythonhosted.org/packages/69/12/f969b81541ee91b55f1ce469d7ab55079593c80d04fd01691b550e535000/xxhash-3.5.0-cp310-cp310-win_arm64.whl", hash = "sha256:893074d651cf25c1cc14e3bea4fceefd67f2921b1bb8e40fcfeba56820de80c6", size = 26773 },
+ { url = "https://files.pythonhosted.org/packages/b8/c7/afed0f131fbda960ff15eee7f304fa0eeb2d58770fade99897984852ef23/xxhash-3.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:02c2e816896dc6f85922ced60097bcf6f008dedfc5073dcba32f9c8dd786f3c1", size = 31969 },
+ { url = "https://files.pythonhosted.org/packages/8c/0c/7c3bc6d87e5235672fcc2fb42fd5ad79fe1033925f71bf549ee068c7d1ca/xxhash-3.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6027dcd885e21581e46d3c7f682cfb2b870942feeed58a21c29583512c3f09f8", size = 30800 },
+ { url = "https://files.pythonhosted.org/packages/04/9e/01067981d98069eec1c20201f8c145367698e9056f8bc295346e4ea32dd1/xxhash-3.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1308fa542bbdbf2fa85e9e66b1077eea3a88bef38ee8a06270b4298a7a62a166", size = 221566 },
+ { url = "https://files.pythonhosted.org/packages/d4/09/d4996de4059c3ce5342b6e1e6a77c9d6c91acce31f6ed979891872dd162b/xxhash-3.5.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c28b2fdcee797e1c1961cd3bcd3d545cab22ad202c846235197935e1df2f8ef7", size = 201214 },
+ { url = "https://files.pythonhosted.org/packages/62/f5/6d2dc9f8d55a7ce0f5e7bfef916e67536f01b85d32a9fbf137d4cadbee38/xxhash-3.5.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:924361811732ddad75ff23e90efd9ccfda4f664132feecb90895bade6a1b4623", size = 429433 },
+ { url = "https://files.pythonhosted.org/packages/d9/72/9256303f10e41ab004799a4aa74b80b3c5977d6383ae4550548b24bd1971/xxhash-3.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:89997aa1c4b6a5b1e5b588979d1da048a3c6f15e55c11d117a56b75c84531f5a", size = 194822 },
+ { url = "https://files.pythonhosted.org/packages/34/92/1a3a29acd08248a34b0e6a94f4e0ed9b8379a4ff471f1668e4dce7bdbaa8/xxhash-3.5.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:685c4f4e8c59837de103344eb1c8a3851f670309eb5c361f746805c5471b8c88", size = 208538 },
+ { url = "https://files.pythonhosted.org/packages/53/ad/7fa1a109663366de42f724a1cdb8e796a260dbac45047bce153bc1e18abf/xxhash-3.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dbd2ecfbfee70bc1a4acb7461fa6af7748ec2ab08ac0fa298f281c51518f982c", size = 216953 },
+ { url = "https://files.pythonhosted.org/packages/35/02/137300e24203bf2b2a49b48ce898ecce6fd01789c0fcd9c686c0a002d129/xxhash-3.5.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:25b5a51dc3dfb20a10833c8eee25903fd2e14059e9afcd329c9da20609a307b2", size = 203594 },
+ { url = "https://files.pythonhosted.org/packages/23/03/aeceb273933d7eee248c4322b98b8e971f06cc3880e5f7602c94e5578af5/xxhash-3.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a8fb786fb754ef6ff8c120cb96629fb518f8eb5a61a16aac3a979a9dbd40a084", size = 210971 },
+ { url = "https://files.pythonhosted.org/packages/e3/64/ed82ec09489474cbb35c716b189ddc1521d8b3de12b1b5ab41ce7f70253c/xxhash-3.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a905ad00ad1e1c34fe4e9d7c1d949ab09c6fa90c919860c1534ff479f40fd12d", size = 415050 },
+ { url = "https://files.pythonhosted.org/packages/71/43/6db4c02dcb488ad4e03bc86d70506c3d40a384ee73c9b5c93338eb1f3c23/xxhash-3.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:963be41bcd49f53af6d795f65c0da9b4cc518c0dd9c47145c98f61cb464f4839", size = 192216 },
+ { url = "https://files.pythonhosted.org/packages/22/6d/db4abec29e7a567455344433d095fdb39c97db6955bb4a2c432e486b4d28/xxhash-3.5.0-cp311-cp311-win32.whl", hash = "sha256:109b436096d0a2dd039c355fa3414160ec4d843dfecc64a14077332a00aeb7da", size = 30120 },
+ { url = "https://files.pythonhosted.org/packages/52/1c/fa3b61c0cf03e1da4767213672efe186b1dfa4fc901a4a694fb184a513d1/xxhash-3.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:b702f806693201ad6c0a05ddbbe4c8f359626d0b3305f766077d51388a6bac58", size = 30003 },
+ { url = "https://files.pythonhosted.org/packages/6b/8e/9e6fc572acf6e1cc7ccb01973c213f895cb8668a9d4c2b58a99350da14b7/xxhash-3.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:c4dcb4120d0cc3cc448624147dba64e9021b278c63e34a38789b688fd0da9bf3", size = 26777 },
+ { url = "https://files.pythonhosted.org/packages/07/0e/1bfce2502c57d7e2e787600b31c83535af83746885aa1a5f153d8c8059d6/xxhash-3.5.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:14470ace8bd3b5d51318782cd94e6f94431974f16cb3b8dc15d52f3b69df8e00", size = 31969 },
+ { url = "https://files.pythonhosted.org/packages/3f/d6/8ca450d6fe5b71ce521b4e5db69622383d039e2b253e9b2f24f93265b52c/xxhash-3.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:59aa1203de1cb96dbeab595ded0ad0c0056bb2245ae11fac11c0ceea861382b9", size = 30787 },
+ { url = "https://files.pythonhosted.org/packages/5b/84/de7c89bc6ef63d750159086a6ada6416cc4349eab23f76ab870407178b93/xxhash-3.5.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:08424f6648526076e28fae6ea2806c0a7d504b9ef05ae61d196d571e5c879c84", size = 220959 },
+ { url = "https://files.pythonhosted.org/packages/fe/86/51258d3e8a8545ff26468c977101964c14d56a8a37f5835bc0082426c672/xxhash-3.5.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:61a1ff00674879725b194695e17f23d3248998b843eb5e933007ca743310f793", size = 200006 },
+ { url = "https://files.pythonhosted.org/packages/02/0a/96973bd325412feccf23cf3680fd2246aebf4b789122f938d5557c54a6b2/xxhash-3.5.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f2f2c61bee5844d41c3eb015ac652a0229e901074951ae48581d58bfb2ba01be", size = 428326 },
+ { url = "https://files.pythonhosted.org/packages/11/a7/81dba5010f7e733de88af9555725146fc133be97ce36533867f4c7e75066/xxhash-3.5.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9d32a592cac88d18cc09a89172e1c32d7f2a6e516c3dfde1b9adb90ab5df54a6", size = 194380 },
+ { url = "https://files.pythonhosted.org/packages/fb/7d/f29006ab398a173f4501c0e4977ba288f1c621d878ec217b4ff516810c04/xxhash-3.5.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:70dabf941dede727cca579e8c205e61121afc9b28516752fd65724be1355cc90", size = 207934 },
+ { url = "https://files.pythonhosted.org/packages/8a/6e/6e88b8f24612510e73d4d70d9b0c7dff62a2e78451b9f0d042a5462c8d03/xxhash-3.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e5d0ddaca65ecca9c10dcf01730165fd858533d0be84c75c327487c37a906a27", size = 216301 },
+ { url = "https://files.pythonhosted.org/packages/af/51/7862f4fa4b75a25c3b4163c8a873f070532fe5f2d3f9b3fc869c8337a398/xxhash-3.5.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:3e5b5e16c5a480fe5f59f56c30abdeba09ffd75da8d13f6b9b6fd224d0b4d0a2", size = 203351 },
+ { url = "https://files.pythonhosted.org/packages/22/61/8d6a40f288f791cf79ed5bb113159abf0c81d6efb86e734334f698eb4c59/xxhash-3.5.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:149b7914451eb154b3dfaa721315117ea1dac2cc55a01bfbd4df7c68c5dd683d", size = 210294 },
+ { url = "https://files.pythonhosted.org/packages/17/02/215c4698955762d45a8158117190261b2dbefe9ae7e5b906768c09d8bc74/xxhash-3.5.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:eade977f5c96c677035ff39c56ac74d851b1cca7d607ab3d8f23c6b859379cab", size = 414674 },
+ { url = "https://files.pythonhosted.org/packages/31/5c/b7a8db8a3237cff3d535261325d95de509f6a8ae439a5a7a4ffcff478189/xxhash-3.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fa9f547bd98f5553d03160967866a71056a60960be00356a15ecc44efb40ba8e", size = 192022 },
+ { url = "https://files.pythonhosted.org/packages/78/e3/dd76659b2811b3fd06892a8beb850e1996b63e9235af5a86ea348f053e9e/xxhash-3.5.0-cp312-cp312-win32.whl", hash = "sha256:f7b58d1fd3551b8c80a971199543379be1cee3d0d409e1f6d8b01c1a2eebf1f8", size = 30170 },
+ { url = "https://files.pythonhosted.org/packages/d9/6b/1c443fe6cfeb4ad1dcf231cdec96eb94fb43d6498b4469ed8b51f8b59a37/xxhash-3.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:fa0cafd3a2af231b4e113fba24a65d7922af91aeb23774a8b78228e6cd785e3e", size = 30040 },
+ { url = "https://files.pythonhosted.org/packages/0f/eb/04405305f290173acc0350eba6d2f1a794b57925df0398861a20fbafa415/xxhash-3.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:586886c7e89cb9828bcd8a5686b12e161368e0064d040e225e72607b43858ba2", size = 26796 },
+ { url = "https://files.pythonhosted.org/packages/c9/b8/e4b3ad92d249be5c83fa72916c9091b0965cb0faeff05d9a0a3870ae6bff/xxhash-3.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:37889a0d13b0b7d739cfc128b1c902f04e32de17b33d74b637ad42f1c55101f6", size = 31795 },
+ { url = "https://files.pythonhosted.org/packages/fc/d8/b3627a0aebfbfa4c12a41e22af3742cf08c8ea84f5cc3367b5de2d039cce/xxhash-3.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:97a662338797c660178e682f3bc180277b9569a59abfb5925e8620fba00b9fc5", size = 30792 },
+ { url = "https://files.pythonhosted.org/packages/c3/cc/762312960691da989c7cd0545cb120ba2a4148741c6ba458aa723c00a3f8/xxhash-3.5.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f85e0108d51092bdda90672476c7d909c04ada6923c14ff9d913c4f7dc8a3bc", size = 220950 },
+ { url = "https://files.pythonhosted.org/packages/fe/e9/cc266f1042c3c13750e86a535496b58beb12bf8c50a915c336136f6168dc/xxhash-3.5.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd2fd827b0ba763ac919440042302315c564fdb797294d86e8cdd4578e3bc7f3", size = 199980 },
+ { url = "https://files.pythonhosted.org/packages/bf/85/a836cd0dc5cc20376de26b346858d0ac9656f8f730998ca4324921a010b9/xxhash-3.5.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:82085c2abec437abebf457c1d12fccb30cc8b3774a0814872511f0f0562c768c", size = 428324 },
+ { url = "https://files.pythonhosted.org/packages/b4/0e/15c243775342ce840b9ba34aceace06a1148fa1630cd8ca269e3223987f5/xxhash-3.5.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:07fda5de378626e502b42b311b049848c2ef38784d0d67b6f30bb5008642f8eb", size = 194370 },
+ { url = "https://files.pythonhosted.org/packages/87/a1/b028bb02636dfdc190da01951d0703b3d904301ed0ef6094d948983bef0e/xxhash-3.5.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c279f0d2b34ef15f922b77966640ade58b4ccdfef1c4d94b20f2a364617a493f", size = 207911 },
+ { url = "https://files.pythonhosted.org/packages/80/d5/73c73b03fc0ac73dacf069fdf6036c9abad82de0a47549e9912c955ab449/xxhash-3.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:89e66ceed67b213dec5a773e2f7a9e8c58f64daeb38c7859d8815d2c89f39ad7", size = 216352 },
+ { url = "https://files.pythonhosted.org/packages/b6/2a/5043dba5ddbe35b4fe6ea0a111280ad9c3d4ba477dd0f2d1fe1129bda9d0/xxhash-3.5.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:bcd51708a633410737111e998ceb3b45d3dbc98c0931f743d9bb0a209033a326", size = 203410 },
+ { url = "https://files.pythonhosted.org/packages/a2/b2/9a8ded888b7b190aed75b484eb5c853ddd48aa2896e7b59bbfbce442f0a1/xxhash-3.5.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3ff2c0a34eae7df88c868be53a8dd56fbdf592109e21d4bfa092a27b0bf4a7bf", size = 210322 },
+ { url = "https://files.pythonhosted.org/packages/98/62/440083fafbc917bf3e4b67c2ade621920dd905517e85631c10aac955c1d2/xxhash-3.5.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:4e28503dccc7d32e0b9817aa0cbfc1f45f563b2c995b7a66c4c8a0d232e840c7", size = 414725 },
+ { url = "https://files.pythonhosted.org/packages/75/db/009206f7076ad60a517e016bb0058381d96a007ce3f79fa91d3010f49cc2/xxhash-3.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a6c50017518329ed65a9e4829154626f008916d36295b6a3ba336e2458824c8c", size = 192070 },
+ { url = "https://files.pythonhosted.org/packages/1f/6d/c61e0668943a034abc3a569cdc5aeae37d686d9da7e39cf2ed621d533e36/xxhash-3.5.0-cp313-cp313-win32.whl", hash = "sha256:53a068fe70301ec30d868ece566ac90d873e3bb059cf83c32e76012c889b8637", size = 30172 },
+ { url = "https://files.pythonhosted.org/packages/96/14/8416dce965f35e3d24722cdf79361ae154fa23e2ab730e5323aa98d7919e/xxhash-3.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:80babcc30e7a1a484eab952d76a4f4673ff601f54d5142c26826502740e70b43", size = 30041 },
+ { url = "https://files.pythonhosted.org/packages/27/ee/518b72faa2073f5aa8e3262408d284892cb79cf2754ba0c3a5870645ef73/xxhash-3.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:4811336f1ce11cac89dcbd18f3a25c527c16311709a89313c3acaf771def2d4b", size = 26801 },
+ { url = "https://files.pythonhosted.org/packages/d4/f6/531dd6858adf8877675270b9d6989b6dacfd1c2d7135b17584fc29866df3/xxhash-3.5.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:bfc8cdd7f33d57f0468b0614ae634cc38ab9202c6957a60e31d285a71ebe0301", size = 31971 },
+ { url = "https://files.pythonhosted.org/packages/7c/a8/b2a42b6c9ae46e233f474f3d307c2e7bca8d9817650babeca048d2ad01d6/xxhash-3.5.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e0c48b6300cd0b0106bf49169c3e0536408dfbeb1ccb53180068a18b03c662ab", size = 30801 },
+ { url = "https://files.pythonhosted.org/packages/b4/92/9ac297e3487818f429bcf369c1c6a097edf5b56ed6fc1feff4c1882e87ef/xxhash-3.5.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fe1a92cfbaa0a1253e339ccec42dbe6db262615e52df591b68726ab10338003f", size = 220644 },
+ { url = "https://files.pythonhosted.org/packages/86/48/c1426dd3c86fc4a52f983301867463472f6a9013fb32d15991e60c9919b6/xxhash-3.5.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:33513d6cc3ed3b559134fb307aae9bdd94d7e7c02907b37896a6c45ff9ce51bd", size = 200021 },
+ { url = "https://files.pythonhosted.org/packages/f3/de/0ab8c79993765c94fc0d0c1a22b454483c58a0161e1b562f58b654f47660/xxhash-3.5.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eefc37f6138f522e771ac6db71a6d4838ec7933939676f3753eafd7d3f4c40bc", size = 428217 },
+ { url = "https://files.pythonhosted.org/packages/b4/b4/332647451ed7d2c021294b7c1e9c144dbb5586b1fb214ad4f5a404642835/xxhash-3.5.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a606c8070ada8aa2a88e181773fa1ef17ba65ce5dd168b9d08038e2a61b33754", size = 193868 },
+ { url = "https://files.pythonhosted.org/packages/f4/1c/a42c0a6cac752f84f7b44a90d1a9fa9047cf70bdba5198a304fde7cc471f/xxhash-3.5.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:42eca420c8fa072cc1dd62597635d140e78e384a79bb4944f825fbef8bfeeef6", size = 207403 },
+ { url = "https://files.pythonhosted.org/packages/c4/d7/04e1b0daae9dc9b02c73c1664cc8aa527498c3f66ccbc586eeb25bbe9f14/xxhash-3.5.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:604253b2143e13218ff1ef0b59ce67f18b8bd1c4205d2ffda22b09b426386898", size = 215978 },
+ { url = "https://files.pythonhosted.org/packages/c4/f4/05e15e67505228fc19ee98a79e427b3a0b9695f5567cd66ced5d66389883/xxhash-3.5.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:6e93a5ad22f434d7876665444a97e713a8f60b5b1a3521e8df11b98309bff833", size = 202416 },
+ { url = "https://files.pythonhosted.org/packages/94/fb/e9028d3645bba5412a09de13ee36df276a567e60bdb31d499dafa46d76ae/xxhash-3.5.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:7a46e1d6d2817ba8024de44c4fd79913a90e5f7265434cef97026215b7d30df6", size = 209853 },
+ { url = "https://files.pythonhosted.org/packages/02/2c/18c6a622429368274739372d2f86c8125413ec169025c7d8ffb051784bba/xxhash-3.5.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:30eb2efe6503c379b7ab99c81ba4a779748e3830241f032ab46bd182bf5873af", size = 413926 },
+ { url = "https://files.pythonhosted.org/packages/72/bb/5b55c391084a0321c3809632a018b9b657e59d5966289664f85a645942ac/xxhash-3.5.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:c8aa771ff2c13dd9cda8166d685d7333d389fae30a4d2bb39d63ab5775de8606", size = 191156 },
+ { url = "https://files.pythonhosted.org/packages/86/2b/915049db13401792fec159f57e4f4a5ca7a9768e83ef71d6645b9d0cd749/xxhash-3.5.0-cp39-cp39-win32.whl", hash = "sha256:5ed9ebc46f24cf91034544b26b131241b699edbfc99ec5e7f8f3d02d6eb7fba4", size = 30122 },
+ { url = "https://files.pythonhosted.org/packages/d5/87/382ef7b24917d7cf4c540ee30f29b283bc87ac5893d2f89b23ea3cdf7d77/xxhash-3.5.0-cp39-cp39-win_amd64.whl", hash = "sha256:220f3f896c6b8d0316f63f16c077d52c412619e475f9372333474ee15133a558", size = 30021 },
+ { url = "https://files.pythonhosted.org/packages/e2/47/d06b24e2d9c3dcabccfd734d11b5bbebfdf59ceac2c61509d8205dd20ac6/xxhash-3.5.0-cp39-cp39-win_arm64.whl", hash = "sha256:a7b1d8315d9b5e9f89eb2933b73afae6ec9597a258d52190944437158b49d38e", size = 26780 },
+ { url = "https://files.pythonhosted.org/packages/ab/9a/233606bada5bd6f50b2b72c45de3d9868ad551e83893d2ac86dc7bb8553a/xxhash-3.5.0-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:2014c5b3ff15e64feecb6b713af12093f75b7926049e26a580e94dcad3c73d8c", size = 29732 },
+ { url = "https://files.pythonhosted.org/packages/0c/67/f75276ca39e2c6604e3bee6c84e9db8a56a4973fde9bf35989787cf6e8aa/xxhash-3.5.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fab81ef75003eda96239a23eda4e4543cedc22e34c373edcaf744e721a163986", size = 36214 },
+ { url = "https://files.pythonhosted.org/packages/0f/f8/f6c61fd794229cc3848d144f73754a0c107854372d7261419dcbbd286299/xxhash-3.5.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e2febf914ace002132aa09169cc572e0d8959d0f305f93d5828c4836f9bc5a6", size = 32020 },
+ { url = "https://files.pythonhosted.org/packages/79/d3/c029c99801526f859e6b38d34ab87c08993bf3dcea34b11275775001638a/xxhash-3.5.0-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5d3a10609c51da2a1c0ea0293fc3968ca0a18bd73838455b5bca3069d7f8e32b", size = 40515 },
+ { url = "https://files.pythonhosted.org/packages/62/e3/bef7b82c1997579c94de9ac5ea7626d01ae5858aa22bf4fcb38bf220cb3e/xxhash-3.5.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:5a74f23335b9689b66eb6dbe2a931a88fcd7a4c2cc4b1cb0edba8ce381c7a1da", size = 30064 },
+ { url = "https://files.pythonhosted.org/packages/c2/56/30d3df421814947f9d782b20c9b7e5e957f3791cbd89874578011daafcbd/xxhash-3.5.0-pp39-pypy39_pp73-macosx_10_15_x86_64.whl", hash = "sha256:531af8845aaadcadf951b7e0c1345c6b9c68a990eeb74ff9acd8501a0ad6a1c9", size = 29734 },
+ { url = "https://files.pythonhosted.org/packages/82/dd/3c42a1f022ad0d82c852d3cb65493ebac03dcfa8c994465a5fb052b00e3c/xxhash-3.5.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ce379bcaa9fcc00f19affa7773084dd09f5b59947b3fb47a1ceb0179f91aaa1", size = 36216 },
+ { url = "https://files.pythonhosted.org/packages/b2/40/8f902ab3bebda228a9b4de69eba988280285a7f7f167b942bc20bb562df9/xxhash-3.5.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd1b2281d01723f076df3c8188f43f2472248a6b63118b036e641243656b1b0f", size = 32042 },
+ { url = "https://files.pythonhosted.org/packages/db/87/bd06beb8ccaa0e9e577c9b909a49cfa5c5cd2ca46034342d72dd9ce5bc56/xxhash-3.5.0-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:9c770750cc80e8694492244bca7251385188bc5597b6a39d98a9f30e8da984e0", size = 40516 },
+ { url = "https://files.pythonhosted.org/packages/bb/f8/505385e2fbd753ddcaafd5550eabe86f6232cbebabad3b2508d411b19153/xxhash-3.5.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:b150b8467852e1bd844387459aa6fbe11d7f38b56e901f9f3b3e6aba0d660240", size = 30108 },
+]
+
+[[package]]
+name = "yarl"
+version = "1.20.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "idna" },
+ { name = "multidict" },
+ { name = "propcache" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3c/fb/efaa23fa4e45537b827620f04cf8f3cd658b76642205162e072703a5b963/yarl-1.20.1.tar.gz", hash = "sha256:d017a4997ee50c91fd5466cef416231bb82177b93b029906cefc542ce14c35ac", size = 186428 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cb/65/7fed0d774abf47487c64be14e9223749468922817b5e8792b8a64792a1bb/yarl-1.20.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:6032e6da6abd41e4acda34d75a816012717000fa6839f37124a47fcefc49bec4", size = 132910 },
+ { url = "https://files.pythonhosted.org/packages/8a/7b/988f55a52da99df9e56dc733b8e4e5a6ae2090081dc2754fc8fd34e60aa0/yarl-1.20.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2c7b34d804b8cf9b214f05015c4fee2ebe7ed05cf581e7192c06555c71f4446a", size = 90644 },
+ { url = "https://files.pythonhosted.org/packages/f7/de/30d98f03e95d30c7e3cc093759982d038c8833ec2451001d45ef4854edc1/yarl-1.20.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0c869f2651cc77465f6cd01d938d91a11d9ea5d798738c1dc077f3de0b5e5fed", size = 89322 },
+ { url = "https://files.pythonhosted.org/packages/e0/7a/f2f314f5ebfe9200724b0b748de2186b927acb334cf964fd312eb86fc286/yarl-1.20.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62915e6688eb4d180d93840cda4110995ad50c459bf931b8b3775b37c264af1e", size = 323786 },
+ { url = "https://files.pythonhosted.org/packages/15/3f/718d26f189db96d993d14b984ce91de52e76309d0fd1d4296f34039856aa/yarl-1.20.1-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:41ebd28167bc6af8abb97fec1a399f412eec5fd61a3ccbe2305a18b84fb4ca73", size = 319627 },
+ { url = "https://files.pythonhosted.org/packages/a5/76/8fcfbf5fa2369157b9898962a4a7d96764b287b085b5b3d9ffae69cdefd1/yarl-1.20.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:21242b4288a6d56f04ea193adde174b7e347ac46ce6bc84989ff7c1b1ecea84e", size = 339149 },
+ { url = "https://files.pythonhosted.org/packages/3c/95/d7fc301cc4661785967acc04f54a4a42d5124905e27db27bb578aac49b5c/yarl-1.20.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bea21cdae6c7eb02ba02a475f37463abfe0a01f5d7200121b03e605d6a0439f8", size = 333327 },
+ { url = "https://files.pythonhosted.org/packages/65/94/e21269718349582eee81efc5c1c08ee71c816bfc1585b77d0ec3f58089eb/yarl-1.20.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1f8a891e4a22a89f5dde7862994485e19db246b70bb288d3ce73a34422e55b23", size = 326054 },
+ { url = "https://files.pythonhosted.org/packages/32/ae/8616d1f07853704523519f6131d21f092e567c5af93de7e3e94b38d7f065/yarl-1.20.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dd803820d44c8853a109a34e3660e5a61beae12970da479cf44aa2954019bf70", size = 315035 },
+ { url = "https://files.pythonhosted.org/packages/48/aa/0ace06280861ef055855333707db5e49c6e3a08840a7ce62682259d0a6c0/yarl-1.20.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:b982fa7f74c80d5c0c7b5b38f908971e513380a10fecea528091405f519b9ebb", size = 338962 },
+ { url = "https://files.pythonhosted.org/packages/20/52/1e9d0e6916f45a8fb50e6844f01cb34692455f1acd548606cbda8134cd1e/yarl-1.20.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:33f29ecfe0330c570d997bcf1afd304377f2e48f61447f37e846a6058a4d33b2", size = 335399 },
+ { url = "https://files.pythonhosted.org/packages/f2/65/60452df742952c630e82f394cd409de10610481d9043aa14c61bf846b7b1/yarl-1.20.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:835ab2cfc74d5eb4a6a528c57f05688099da41cf4957cf08cad38647e4a83b30", size = 338649 },
+ { url = "https://files.pythonhosted.org/packages/7b/f5/6cd4ff38dcde57a70f23719a838665ee17079640c77087404c3d34da6727/yarl-1.20.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:46b5e0ccf1943a9a6e766b2c2b8c732c55b34e28be57d8daa2b3c1d1d4009309", size = 358563 },
+ { url = "https://files.pythonhosted.org/packages/d1/90/c42eefd79d0d8222cb3227bdd51b640c0c1d0aa33fe4cc86c36eccba77d3/yarl-1.20.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:df47c55f7d74127d1b11251fe6397d84afdde0d53b90bedb46a23c0e534f9d24", size = 357609 },
+ { url = "https://files.pythonhosted.org/packages/03/c8/cea6b232cb4617514232e0f8a718153a95b5d82b5290711b201545825532/yarl-1.20.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:76d12524d05841276b0e22573f28d5fbcb67589836772ae9244d90dd7d66aa13", size = 350224 },
+ { url = "https://files.pythonhosted.org/packages/ce/a3/eaa0ab9712f1f3d01faf43cf6f1f7210ce4ea4a7e9b28b489a2261ca8db9/yarl-1.20.1-cp310-cp310-win32.whl", hash = "sha256:6c4fbf6b02d70e512d7ade4b1f998f237137f1417ab07ec06358ea04f69134f8", size = 81753 },
+ { url = "https://files.pythonhosted.org/packages/8f/34/e4abde70a9256465fe31c88ed02c3f8502b7b5dead693a4f350a06413f28/yarl-1.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:aef6c4d69554d44b7f9d923245f8ad9a707d971e6209d51279196d8e8fe1ae16", size = 86817 },
+ { url = "https://files.pythonhosted.org/packages/b1/18/893b50efc2350e47a874c5c2d67e55a0ea5df91186b2a6f5ac52eff887cd/yarl-1.20.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:47ee6188fea634bdfaeb2cc420f5b3b17332e6225ce88149a17c413c77ff269e", size = 133833 },
+ { url = "https://files.pythonhosted.org/packages/89/ed/b8773448030e6fc47fa797f099ab9eab151a43a25717f9ac043844ad5ea3/yarl-1.20.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d0f6500f69e8402d513e5eedb77a4e1818691e8f45e6b687147963514d84b44b", size = 91070 },
+ { url = "https://files.pythonhosted.org/packages/e3/e3/409bd17b1e42619bf69f60e4f031ce1ccb29bd7380117a55529e76933464/yarl-1.20.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7a8900a42fcdaad568de58887c7b2f602962356908eedb7628eaf6021a6e435b", size = 89818 },
+ { url = "https://files.pythonhosted.org/packages/f8/77/64d8431a4d77c856eb2d82aa3de2ad6741365245a29b3a9543cd598ed8c5/yarl-1.20.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bad6d131fda8ef508b36be3ece16d0902e80b88ea7200f030a0f6c11d9e508d4", size = 347003 },
+ { url = "https://files.pythonhosted.org/packages/8d/d2/0c7e4def093dcef0bd9fa22d4d24b023788b0a33b8d0088b51aa51e21e99/yarl-1.20.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:df018d92fe22aaebb679a7f89fe0c0f368ec497e3dda6cb81a567610f04501f1", size = 336537 },
+ { url = "https://files.pythonhosted.org/packages/f0/f3/fc514f4b2cf02cb59d10cbfe228691d25929ce8f72a38db07d3febc3f706/yarl-1.20.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8f969afbb0a9b63c18d0feecf0db09d164b7a44a053e78a7d05f5df163e43833", size = 362358 },
+ { url = "https://files.pythonhosted.org/packages/ea/6d/a313ac8d8391381ff9006ac05f1d4331cee3b1efaa833a53d12253733255/yarl-1.20.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:812303eb4aa98e302886ccda58d6b099e3576b1b9276161469c25803a8db277d", size = 357362 },
+ { url = "https://files.pythonhosted.org/packages/00/70/8f78a95d6935a70263d46caa3dd18e1f223cf2f2ff2037baa01a22bc5b22/yarl-1.20.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:98c4a7d166635147924aa0bf9bfe8d8abad6fffa6102de9c99ea04a1376f91e8", size = 348979 },
+ { url = "https://files.pythonhosted.org/packages/cb/05/42773027968968f4f15143553970ee36ead27038d627f457cc44bbbeecf3/yarl-1.20.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:12e768f966538e81e6e7550f9086a6236b16e26cd964cf4df35349970f3551cf", size = 337274 },
+ { url = "https://files.pythonhosted.org/packages/05/be/665634aa196954156741ea591d2f946f1b78ceee8bb8f28488bf28c0dd62/yarl-1.20.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fe41919b9d899661c5c28a8b4b0acf704510b88f27f0934ac7a7bebdd8938d5e", size = 363294 },
+ { url = "https://files.pythonhosted.org/packages/eb/90/73448401d36fa4e210ece5579895731f190d5119c4b66b43b52182e88cd5/yarl-1.20.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:8601bc010d1d7780592f3fc1bdc6c72e2b6466ea34569778422943e1a1f3c389", size = 358169 },
+ { url = "https://files.pythonhosted.org/packages/c3/b0/fce922d46dc1eb43c811f1889f7daa6001b27a4005587e94878570300881/yarl-1.20.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:daadbdc1f2a9033a2399c42646fbd46da7992e868a5fe9513860122d7fe7a73f", size = 362776 },
+ { url = "https://files.pythonhosted.org/packages/f1/0d/b172628fce039dae8977fd22caeff3eeebffd52e86060413f5673767c427/yarl-1.20.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:03aa1e041727cb438ca762628109ef1333498b122e4c76dd858d186a37cec845", size = 381341 },
+ { url = "https://files.pythonhosted.org/packages/6b/9b/5b886d7671f4580209e855974fe1cecec409aa4a89ea58b8f0560dc529b1/yarl-1.20.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:642980ef5e0fa1de5fa96d905c7e00cb2c47cb468bfcac5a18c58e27dbf8d8d1", size = 379988 },
+ { url = "https://files.pythonhosted.org/packages/73/be/75ef5fd0fcd8f083a5d13f78fd3f009528132a1f2a1d7c925c39fa20aa79/yarl-1.20.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:86971e2795584fe8c002356d3b97ef6c61862720eeff03db2a7c86b678d85b3e", size = 371113 },
+ { url = "https://files.pythonhosted.org/packages/50/4f/62faab3b479dfdcb741fe9e3f0323e2a7d5cd1ab2edc73221d57ad4834b2/yarl-1.20.1-cp311-cp311-win32.whl", hash = "sha256:597f40615b8d25812f14562699e287f0dcc035d25eb74da72cae043bb884d773", size = 81485 },
+ { url = "https://files.pythonhosted.org/packages/f0/09/d9c7942f8f05c32ec72cd5c8e041c8b29b5807328b68b4801ff2511d4d5e/yarl-1.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:26ef53a9e726e61e9cd1cda6b478f17e350fb5800b4bd1cd9fe81c4d91cfeb2e", size = 86686 },
+ { url = "https://files.pythonhosted.org/packages/5f/9a/cb7fad7d73c69f296eda6815e4a2c7ed53fc70c2f136479a91c8e5fbdb6d/yarl-1.20.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:bdcc4cd244e58593a4379fe60fdee5ac0331f8eb70320a24d591a3be197b94a9", size = 133667 },
+ { url = "https://files.pythonhosted.org/packages/67/38/688577a1cb1e656e3971fb66a3492501c5a5df56d99722e57c98249e5b8a/yarl-1.20.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b29a2c385a5f5b9c7d9347e5812b6f7ab267193c62d282a540b4fc528c8a9d2a", size = 91025 },
+ { url = "https://files.pythonhosted.org/packages/50/ec/72991ae51febeb11a42813fc259f0d4c8e0507f2b74b5514618d8b640365/yarl-1.20.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1112ae8154186dfe2de4732197f59c05a83dc814849a5ced892b708033f40dc2", size = 89709 },
+ { url = "https://files.pythonhosted.org/packages/99/da/4d798025490e89426e9f976702e5f9482005c548c579bdae792a4c37769e/yarl-1.20.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:90bbd29c4fe234233f7fa2b9b121fb63c321830e5d05b45153a2ca68f7d310ee", size = 352287 },
+ { url = "https://files.pythonhosted.org/packages/1a/26/54a15c6a567aac1c61b18aa0f4b8aa2e285a52d547d1be8bf48abe2b3991/yarl-1.20.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:680e19c7ce3710ac4cd964e90dad99bf9b5029372ba0c7cbfcd55e54d90ea819", size = 345429 },
+ { url = "https://files.pythonhosted.org/packages/d6/95/9dcf2386cb875b234353b93ec43e40219e14900e046bf6ac118f94b1e353/yarl-1.20.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4a979218c1fdb4246a05efc2cc23859d47c89af463a90b99b7c56094daf25a16", size = 365429 },
+ { url = "https://files.pythonhosted.org/packages/91/b2/33a8750f6a4bc224242a635f5f2cff6d6ad5ba651f6edcccf721992c21a0/yarl-1.20.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:255b468adf57b4a7b65d8aad5b5138dce6a0752c139965711bdcb81bc370e1b6", size = 363862 },
+ { url = "https://files.pythonhosted.org/packages/98/28/3ab7acc5b51f4434b181b0cee8f1f4b77a65919700a355fb3617f9488874/yarl-1.20.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a97d67108e79cfe22e2b430d80d7571ae57d19f17cda8bb967057ca8a7bf5bfd", size = 355616 },
+ { url = "https://files.pythonhosted.org/packages/36/a3/f666894aa947a371724ec7cd2e5daa78ee8a777b21509b4252dd7bd15e29/yarl-1.20.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8570d998db4ddbfb9a590b185a0a33dbf8aafb831d07a5257b4ec9948df9cb0a", size = 339954 },
+ { url = "https://files.pythonhosted.org/packages/f1/81/5f466427e09773c04219d3450d7a1256138a010b6c9f0af2d48565e9ad13/yarl-1.20.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:97c75596019baae7c71ccf1d8cc4738bc08134060d0adfcbe5642f778d1dca38", size = 365575 },
+ { url = "https://files.pythonhosted.org/packages/2e/e3/e4b0ad8403e97e6c9972dd587388940a032f030ebec196ab81a3b8e94d31/yarl-1.20.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:1c48912653e63aef91ff988c5432832692ac5a1d8f0fb8a33091520b5bbe19ef", size = 365061 },
+ { url = "https://files.pythonhosted.org/packages/ac/99/b8a142e79eb86c926f9f06452eb13ecb1bb5713bd01dc0038faf5452e544/yarl-1.20.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:4c3ae28f3ae1563c50f3d37f064ddb1511ecc1d5584e88c6b7c63cf7702a6d5f", size = 364142 },
+ { url = "https://files.pythonhosted.org/packages/34/f2/08ed34a4a506d82a1a3e5bab99ccd930a040f9b6449e9fd050320e45845c/yarl-1.20.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c5e9642f27036283550f5f57dc6156c51084b458570b9d0d96100c8bebb186a8", size = 381894 },
+ { url = "https://files.pythonhosted.org/packages/92/f8/9a3fbf0968eac704f681726eff595dce9b49c8a25cd92bf83df209668285/yarl-1.20.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:2c26b0c49220d5799f7b22c6838409ee9bc58ee5c95361a4d7831f03cc225b5a", size = 383378 },
+ { url = "https://files.pythonhosted.org/packages/af/85/9363f77bdfa1e4d690957cd39d192c4cacd1c58965df0470a4905253b54f/yarl-1.20.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:564ab3d517e3d01c408c67f2e5247aad4019dcf1969982aba3974b4093279004", size = 374069 },
+ { url = "https://files.pythonhosted.org/packages/35/99/9918c8739ba271dcd935400cff8b32e3cd319eaf02fcd023d5dcd487a7c8/yarl-1.20.1-cp312-cp312-win32.whl", hash = "sha256:daea0d313868da1cf2fac6b2d3a25c6e3a9e879483244be38c8e6a41f1d876a5", size = 81249 },
+ { url = "https://files.pythonhosted.org/packages/eb/83/5d9092950565481b413b31a23e75dd3418ff0a277d6e0abf3729d4d1ce25/yarl-1.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:48ea7d7f9be0487339828a4de0360d7ce0efc06524a48e1810f945c45b813698", size = 86710 },
+ { url = "https://files.pythonhosted.org/packages/8a/e1/2411b6d7f769a07687acee88a062af5833cf1966b7266f3d8dfb3d3dc7d3/yarl-1.20.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:0b5ff0fbb7c9f1b1b5ab53330acbfc5247893069e7716840c8e7d5bb7355038a", size = 131811 },
+ { url = "https://files.pythonhosted.org/packages/b2/27/584394e1cb76fb771371770eccad35de400e7b434ce3142c2dd27392c968/yarl-1.20.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:14f326acd845c2b2e2eb38fb1346c94f7f3b01a4f5c788f8144f9b630bfff9a3", size = 90078 },
+ { url = "https://files.pythonhosted.org/packages/bf/9a/3246ae92d4049099f52d9b0fe3486e3b500e29b7ea872d0f152966fc209d/yarl-1.20.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f60e4ad5db23f0b96e49c018596707c3ae89f5d0bd97f0ad3684bcbad899f1e7", size = 88748 },
+ { url = "https://files.pythonhosted.org/packages/a3/25/35afe384e31115a1a801fbcf84012d7a066d89035befae7c5d4284df1e03/yarl-1.20.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:49bdd1b8e00ce57e68ba51916e4bb04461746e794e7c4d4bbc42ba2f18297691", size = 349595 },
+ { url = "https://files.pythonhosted.org/packages/28/2d/8aca6cb2cabc8f12efcb82749b9cefecbccfc7b0384e56cd71058ccee433/yarl-1.20.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:66252d780b45189975abfed839616e8fd2dbacbdc262105ad7742c6ae58f3e31", size = 342616 },
+ { url = "https://files.pythonhosted.org/packages/0b/e9/1312633d16b31acf0098d30440ca855e3492d66623dafb8e25b03d00c3da/yarl-1.20.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:59174e7332f5d153d8f7452a102b103e2e74035ad085f404df2e40e663a22b28", size = 361324 },
+ { url = "https://files.pythonhosted.org/packages/bc/a0/688cc99463f12f7669eec7c8acc71ef56a1521b99eab7cd3abb75af887b0/yarl-1.20.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e3968ec7d92a0c0f9ac34d5ecfd03869ec0cab0697c91a45db3fbbd95fe1b653", size = 359676 },
+ { url = "https://files.pythonhosted.org/packages/af/44/46407d7f7a56e9a85a4c207724c9f2c545c060380718eea9088f222ba697/yarl-1.20.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1a4fbb50e14396ba3d375f68bfe02215d8e7bc3ec49da8341fe3157f59d2ff5", size = 352614 },
+ { url = "https://files.pythonhosted.org/packages/b1/91/31163295e82b8d5485d31d9cf7754d973d41915cadce070491778d9c9825/yarl-1.20.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:11a62c839c3a8eac2410e951301309426f368388ff2f33799052787035793b02", size = 336766 },
+ { url = "https://files.pythonhosted.org/packages/b4/8e/c41a5bc482121f51c083c4c2bcd16b9e01e1cf8729e380273a952513a21f/yarl-1.20.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:041eaa14f73ff5a8986b4388ac6bb43a77f2ea09bf1913df7a35d4646db69e53", size = 364615 },
+ { url = "https://files.pythonhosted.org/packages/e3/5b/61a3b054238d33d70ea06ebba7e58597891b71c699e247df35cc984ab393/yarl-1.20.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:377fae2fef158e8fd9d60b4c8751387b8d1fb121d3d0b8e9b0be07d1b41e83dc", size = 360982 },
+ { url = "https://files.pythonhosted.org/packages/df/a3/6a72fb83f8d478cb201d14927bc8040af901811a88e0ff2da7842dd0ed19/yarl-1.20.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1c92f4390e407513f619d49319023664643d3339bd5e5a56a3bebe01bc67ec04", size = 369792 },
+ { url = "https://files.pythonhosted.org/packages/7c/af/4cc3c36dfc7c077f8dedb561eb21f69e1e9f2456b91b593882b0b18c19dc/yarl-1.20.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:d25ddcf954df1754ab0f86bb696af765c5bfaba39b74095f27eececa049ef9a4", size = 382049 },
+ { url = "https://files.pythonhosted.org/packages/19/3a/e54e2c4752160115183a66dc9ee75a153f81f3ab2ba4bf79c3c53b33de34/yarl-1.20.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:909313577e9619dcff8c31a0ea2aa0a2a828341d92673015456b3ae492e7317b", size = 384774 },
+ { url = "https://files.pythonhosted.org/packages/9c/20/200ae86dabfca89060ec6447649f219b4cbd94531e425e50d57e5f5ac330/yarl-1.20.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:793fd0580cb9664548c6b83c63b43c477212c0260891ddf86809e1c06c8b08f1", size = 374252 },
+ { url = "https://files.pythonhosted.org/packages/83/75/11ee332f2f516b3d094e89448da73d557687f7d137d5a0f48c40ff211487/yarl-1.20.1-cp313-cp313-win32.whl", hash = "sha256:468f6e40285de5a5b3c44981ca3a319a4b208ccc07d526b20b12aeedcfa654b7", size = 81198 },
+ { url = "https://files.pythonhosted.org/packages/ba/ba/39b1ecbf51620b40ab402b0fc817f0ff750f6d92712b44689c2c215be89d/yarl-1.20.1-cp313-cp313-win_amd64.whl", hash = "sha256:495b4ef2fea40596bfc0affe3837411d6aa3371abcf31aac0ccc4bdd64d4ef5c", size = 86346 },
+ { url = "https://files.pythonhosted.org/packages/43/c7/669c52519dca4c95153c8ad96dd123c79f354a376346b198f438e56ffeb4/yarl-1.20.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:f60233b98423aab21d249a30eb27c389c14929f47be8430efa7dbd91493a729d", size = 138826 },
+ { url = "https://files.pythonhosted.org/packages/6a/42/fc0053719b44f6ad04a75d7f05e0e9674d45ef62f2d9ad2c1163e5c05827/yarl-1.20.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:6f3eff4cc3f03d650d8755c6eefc844edde99d641d0dcf4da3ab27141a5f8ddf", size = 93217 },
+ { url = "https://files.pythonhosted.org/packages/4f/7f/fa59c4c27e2a076bba0d959386e26eba77eb52ea4a0aac48e3515c186b4c/yarl-1.20.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:69ff8439d8ba832d6bed88af2c2b3445977eba9a4588b787b32945871c2444e3", size = 92700 },
+ { url = "https://files.pythonhosted.org/packages/2f/d4/062b2f48e7c93481e88eff97a6312dca15ea200e959f23e96d8ab898c5b8/yarl-1.20.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3cf34efa60eb81dd2645a2e13e00bb98b76c35ab5061a3989c7a70f78c85006d", size = 347644 },
+ { url = "https://files.pythonhosted.org/packages/89/47/78b7f40d13c8f62b499cc702fdf69e090455518ae544c00a3bf4afc9fc77/yarl-1.20.1-cp313-cp313t-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8e0fe9364ad0fddab2688ce72cb7a8e61ea42eff3c7caeeb83874a5d479c896c", size = 323452 },
+ { url = "https://files.pythonhosted.org/packages/eb/2b/490d3b2dc66f52987d4ee0d3090a147ea67732ce6b4d61e362c1846d0d32/yarl-1.20.1-cp313-cp313t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8f64fbf81878ba914562c672024089e3401974a39767747691c65080a67b18c1", size = 346378 },
+ { url = "https://files.pythonhosted.org/packages/66/ad/775da9c8a94ce925d1537f939a4f17d782efef1f973039d821cbe4bcc211/yarl-1.20.1-cp313-cp313t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f6342d643bf9a1de97e512e45e4b9560a043347e779a173250824f8b254bd5ce", size = 353261 },
+ { url = "https://files.pythonhosted.org/packages/4b/23/0ed0922b47a4f5c6eb9065d5ff1e459747226ddce5c6a4c111e728c9f701/yarl-1.20.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:56dac5f452ed25eef0f6e3c6a066c6ab68971d96a9fb441791cad0efba6140d3", size = 335987 },
+ { url = "https://files.pythonhosted.org/packages/3e/49/bc728a7fe7d0e9336e2b78f0958a2d6b288ba89f25a1762407a222bf53c3/yarl-1.20.1-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7d7f497126d65e2cad8dc5f97d34c27b19199b6414a40cb36b52f41b79014be", size = 329361 },
+ { url = "https://files.pythonhosted.org/packages/93/8f/b811b9d1f617c83c907e7082a76e2b92b655400e61730cd61a1f67178393/yarl-1.20.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:67e708dfb8e78d8a19169818eeb5c7a80717562de9051bf2413aca8e3696bf16", size = 346460 },
+ { url = "https://files.pythonhosted.org/packages/70/fd/af94f04f275f95da2c3b8b5e1d49e3e79f1ed8b6ceb0f1664cbd902773ff/yarl-1.20.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:595c07bc79af2494365cc96ddeb772f76272364ef7c80fb892ef9d0649586513", size = 334486 },
+ { url = "https://files.pythonhosted.org/packages/84/65/04c62e82704e7dd0a9b3f61dbaa8447f8507655fd16c51da0637b39b2910/yarl-1.20.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:7bdd2f80f4a7df852ab9ab49484a4dee8030023aa536df41f2d922fd57bf023f", size = 342219 },
+ { url = "https://files.pythonhosted.org/packages/91/95/459ca62eb958381b342d94ab9a4b6aec1ddec1f7057c487e926f03c06d30/yarl-1.20.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:c03bfebc4ae8d862f853a9757199677ab74ec25424d0ebd68a0027e9c639a390", size = 350693 },
+ { url = "https://files.pythonhosted.org/packages/a6/00/d393e82dd955ad20617abc546a8f1aee40534d599ff555ea053d0ec9bf03/yarl-1.20.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:344d1103e9c1523f32a5ed704d576172d2cabed3122ea90b1d4e11fe17c66458", size = 355803 },
+ { url = "https://files.pythonhosted.org/packages/9e/ed/c5fb04869b99b717985e244fd93029c7a8e8febdfcffa06093e32d7d44e7/yarl-1.20.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:88cab98aa4e13e1ade8c141daeedd300a4603b7132819c484841bb7af3edce9e", size = 341709 },
+ { url = "https://files.pythonhosted.org/packages/24/fd/725b8e73ac2a50e78a4534ac43c6addf5c1c2d65380dd48a9169cc6739a9/yarl-1.20.1-cp313-cp313t-win32.whl", hash = "sha256:b121ff6a7cbd4abc28985b6028235491941b9fe8fe226e6fdc539c977ea1739d", size = 86591 },
+ { url = "https://files.pythonhosted.org/packages/94/c3/b2e9f38bc3e11191981d57ea08cab2166e74ea770024a646617c9cddd9f6/yarl-1.20.1-cp313-cp313t-win_amd64.whl", hash = "sha256:541d050a355bbbc27e55d906bc91cb6fe42f96c01413dd0f4ed5a5240513874f", size = 93003 },
+ { url = "https://files.pythonhosted.org/packages/01/75/0d37402d208d025afa6b5b8eb80e466d267d3fd1927db8e317d29a94a4cb/yarl-1.20.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:e42ba79e2efb6845ebab49c7bf20306c4edf74a0b20fc6b2ccdd1a219d12fad3", size = 134259 },
+ { url = "https://files.pythonhosted.org/packages/73/84/1fb6c85ae0cf9901046f07d0ac9eb162f7ce6d95db541130aa542ed377e6/yarl-1.20.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:41493b9b7c312ac448b7f0a42a089dffe1d6e6e981a2d76205801a023ed26a2b", size = 91269 },
+ { url = "https://files.pythonhosted.org/packages/f3/9c/eae746b24c4ea29a5accba9a06c197a70fa38a49c7df244e0d3951108861/yarl-1.20.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f5a5928ff5eb13408c62a968ac90d43f8322fd56d87008b8f9dabf3c0f6ee983", size = 89995 },
+ { url = "https://files.pythonhosted.org/packages/fb/30/693e71003ec4bc1daf2e4cf7c478c417d0985e0a8e8f00b2230d517876fc/yarl-1.20.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:30c41ad5d717b3961b2dd785593b67d386b73feca30522048d37298fee981805", size = 325253 },
+ { url = "https://files.pythonhosted.org/packages/0f/a2/5264dbebf90763139aeb0b0b3154763239398400f754ae19a0518b654117/yarl-1.20.1-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:59febc3969b0781682b469d4aca1a5cab7505a4f7b85acf6db01fa500fa3f6ba", size = 320897 },
+ { url = "https://files.pythonhosted.org/packages/e7/17/77c7a89b3c05856489777e922f41db79ab4faf58621886df40d812c7facd/yarl-1.20.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d2b6fb3622b7e5bf7a6e5b679a69326b4279e805ed1699d749739a61d242449e", size = 340696 },
+ { url = "https://files.pythonhosted.org/packages/6d/55/28409330b8ef5f2f681f5b478150496ec9cf3309b149dab7ec8ab5cfa3f0/yarl-1.20.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:749d73611db8d26a6281086f859ea7ec08f9c4c56cec864e52028c8b328db723", size = 335064 },
+ { url = "https://files.pythonhosted.org/packages/85/58/cb0257cbd4002828ff735f44d3c5b6966c4fd1fc8cc1cd3cd8a143fbc513/yarl-1.20.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9427925776096e664c39e131447aa20ec738bdd77c049c48ea5200db2237e000", size = 327256 },
+ { url = "https://files.pythonhosted.org/packages/53/f6/c77960370cfa46f6fb3d6a5a79a49d3abfdb9ef92556badc2dcd2748bc2a/yarl-1.20.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ff70f32aa316393eaf8222d518ce9118148eddb8a53073c2403863b41033eed5", size = 316389 },
+ { url = "https://files.pythonhosted.org/packages/64/ab/be0b10b8e029553c10905b6b00c64ecad3ebc8ace44b02293a62579343f6/yarl-1.20.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:c7ddf7a09f38667aea38801da8b8d6bfe81df767d9dfc8c88eb45827b195cd1c", size = 340481 },
+ { url = "https://files.pythonhosted.org/packages/c5/c3/3f327bd3905a4916029bf5feb7f86dcf864c7704f099715f62155fb386b2/yarl-1.20.1-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:57edc88517d7fc62b174fcfb2e939fbc486a68315d648d7e74d07fac42cec240", size = 336941 },
+ { url = "https://files.pythonhosted.org/packages/d1/42/040bdd5d3b3bb02b4a6ace4ed4075e02f85df964d6e6cb321795d2a6496a/yarl-1.20.1-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:dab096ce479d5894d62c26ff4f699ec9072269d514b4edd630a393223f45a0ee", size = 339936 },
+ { url = "https://files.pythonhosted.org/packages/0d/1c/911867b8e8c7463b84dfdc275e0d99b04b66ad5132b503f184fe76be8ea4/yarl-1.20.1-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:14a85f3bd2d7bb255be7183e5d7d6e70add151a98edf56a770d6140f5d5f4010", size = 360163 },
+ { url = "https://files.pythonhosted.org/packages/e2/31/8c389f6c6ca0379b57b2da87f1f126c834777b4931c5ee8427dd65d0ff6b/yarl-1.20.1-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:2c89b5c792685dd9cd3fa9761c1b9f46fc240c2a3265483acc1565769996a3f8", size = 359108 },
+ { url = "https://files.pythonhosted.org/packages/7f/09/ae4a649fb3964324c70a3e2b61f45e566d9ffc0affd2b974cbf628957673/yarl-1.20.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:69e9b141de5511021942a6866990aea6d111c9042235de90e08f94cf972ca03d", size = 351875 },
+ { url = "https://files.pythonhosted.org/packages/8d/43/bbb4ed4c34d5bb62b48bf957f68cd43f736f79059d4f85225ab1ef80f4b9/yarl-1.20.1-cp39-cp39-win32.whl", hash = "sha256:b5f307337819cdfdbb40193cad84978a029f847b0a357fbe49f712063cfc4f06", size = 82293 },
+ { url = "https://files.pythonhosted.org/packages/d7/cd/ce185848a7dba68ea69e932674b5c1a42a1852123584bccc5443120f857c/yarl-1.20.1-cp39-cp39-win_amd64.whl", hash = "sha256:eae7bfe2069f9c1c5b05fc7fe5d612e5bbc089a39309904ee8b829e322dcad00", size = 87385 },
+ { url = "https://files.pythonhosted.org/packages/b4/2d/2345fce04cfd4bee161bf1e7d9cdc702e3e16109021035dbb24db654a622/yarl-1.20.1-py3-none-any.whl", hash = "sha256:83b8eb083fe4683c6115795d9fc1cfaf2cbbefb19b3a1cb68f6527460f483a77", size = 46542 },
+]
+
+[[package]]
+name = "zipp"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276 },
+]
+
+[[package]]
+name = "zstandard"
+version = "0.23.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi", marker = "platform_python_implementation == 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ed/f6/2ac0287b442160a89d726b17a9184a4c615bb5237db763791a7fd16d9df1/zstandard-0.23.0.tar.gz", hash = "sha256:b2d8c62d08e7255f68f7a740bae85b3c9b8e5466baa9cbf7f57f1cde0ac6bc09", size = 681701 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/55/bd0487e86679db1823fc9ee0d8c9c78ae2413d34c0b461193b5f4c31d22f/zstandard-0.23.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bf0a05b6059c0528477fba9054d09179beb63744355cab9f38059548fedd46a9", size = 788701 },
+ { url = "https://files.pythonhosted.org/packages/e1/8a/ccb516b684f3ad987dfee27570d635822e3038645b1a950c5e8022df1145/zstandard-0.23.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fc9ca1c9718cb3b06634c7c8dec57d24e9438b2aa9a0f02b8bb36bf478538880", size = 633678 },
+ { url = "https://files.pythonhosted.org/packages/12/89/75e633d0611c028e0d9af6df199423bf43f54bea5007e6718ab7132e234c/zstandard-0.23.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77da4c6bfa20dd5ea25cbf12c76f181a8e8cd7ea231c673828d0386b1740b8dc", size = 4941098 },
+ { url = "https://files.pythonhosted.org/packages/4a/7a/bd7f6a21802de358b63f1ee636ab823711c25ce043a3e9f043b4fcb5ba32/zstandard-0.23.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b2170c7e0367dde86a2647ed5b6f57394ea7f53545746104c6b09fc1f4223573", size = 5308798 },
+ { url = "https://files.pythonhosted.org/packages/79/3b/775f851a4a65013e88ca559c8ae42ac1352db6fcd96b028d0df4d7d1d7b4/zstandard-0.23.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c16842b846a8d2a145223f520b7e18b57c8f476924bda92aeee3a88d11cfc391", size = 5341840 },
+ { url = "https://files.pythonhosted.org/packages/09/4f/0cc49570141dd72d4d95dd6fcf09328d1b702c47a6ec12fbed3b8aed18a5/zstandard-0.23.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:157e89ceb4054029a289fb504c98c6a9fe8010f1680de0201b3eb5dc20aa6d9e", size = 5440337 },
+ { url = "https://files.pythonhosted.org/packages/e7/7c/aaa7cd27148bae2dc095191529c0570d16058c54c4597a7d118de4b21676/zstandard-0.23.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:203d236f4c94cd8379d1ea61db2fce20730b4c38d7f1c34506a31b34edc87bdd", size = 4861182 },
+ { url = "https://files.pythonhosted.org/packages/ac/eb/4b58b5c071d177f7dc027129d20bd2a44161faca6592a67f8fcb0b88b3ae/zstandard-0.23.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:dc5d1a49d3f8262be192589a4b72f0d03b72dcf46c51ad5852a4fdc67be7b9e4", size = 4932936 },
+ { url = "https://files.pythonhosted.org/packages/44/f9/21a5fb9bb7c9a274b05ad700a82ad22ce82f7ef0f485980a1e98ed6e8c5f/zstandard-0.23.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:752bf8a74412b9892f4e5b58f2f890a039f57037f52c89a740757ebd807f33ea", size = 5464705 },
+ { url = "https://files.pythonhosted.org/packages/49/74/b7b3e61db3f88632776b78b1db597af3f44c91ce17d533e14a25ce6a2816/zstandard-0.23.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:80080816b4f52a9d886e67f1f96912891074903238fe54f2de8b786f86baded2", size = 4857882 },
+ { url = "https://files.pythonhosted.org/packages/4a/7f/d8eb1cb123d8e4c541d4465167080bec88481ab54cd0b31eb4013ba04b95/zstandard-0.23.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:84433dddea68571a6d6bd4fbf8ff398236031149116a7fff6f777ff95cad3df9", size = 4697672 },
+ { url = "https://files.pythonhosted.org/packages/5e/05/f7dccdf3d121309b60342da454d3e706453a31073e2c4dac8e1581861e44/zstandard-0.23.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:ab19a2d91963ed9e42b4e8d77cd847ae8381576585bad79dbd0a8837a9f6620a", size = 5206043 },
+ { url = "https://files.pythonhosted.org/packages/86/9d/3677a02e172dccd8dd3a941307621c0cbd7691d77cb435ac3c75ab6a3105/zstandard-0.23.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:59556bf80a7094d0cfb9f5e50bb2db27fefb75d5138bb16fb052b61b0e0eeeb0", size = 5667390 },
+ { url = "https://files.pythonhosted.org/packages/41/7e/0012a02458e74a7ba122cd9cafe491facc602c9a17f590367da369929498/zstandard-0.23.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:27d3ef2252d2e62476389ca8f9b0cf2bbafb082a3b6bfe9d90cbcbb5529ecf7c", size = 5198901 },
+ { url = "https://files.pythonhosted.org/packages/65/3a/8f715b97bd7bcfc7342d8adcd99a026cb2fb550e44866a3b6c348e1b0f02/zstandard-0.23.0-cp310-cp310-win32.whl", hash = "sha256:5d41d5e025f1e0bccae4928981e71b2334c60f580bdc8345f824e7c0a4c2a813", size = 430596 },
+ { url = "https://files.pythonhosted.org/packages/19/b7/b2b9eca5e5a01111e4fe8a8ffb56bdcdf56b12448a24effe6cfe4a252034/zstandard-0.23.0-cp310-cp310-win_amd64.whl", hash = "sha256:519fbf169dfac1222a76ba8861ef4ac7f0530c35dd79ba5727014613f91613d4", size = 495498 },
+ { url = "https://files.pythonhosted.org/packages/9e/40/f67e7d2c25a0e2dc1744dd781110b0b60306657f8696cafb7ad7579469bd/zstandard-0.23.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:34895a41273ad33347b2fc70e1bff4240556de3c46c6ea430a7ed91f9042aa4e", size = 788699 },
+ { url = "https://files.pythonhosted.org/packages/e8/46/66d5b55f4d737dd6ab75851b224abf0afe5774976fe511a54d2eb9063a41/zstandard-0.23.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:77ea385f7dd5b5676d7fd943292ffa18fbf5c72ba98f7d09fc1fb9e819b34c23", size = 633681 },
+ { url = "https://files.pythonhosted.org/packages/63/b6/677e65c095d8e12b66b8f862b069bcf1f1d781b9c9c6f12eb55000d57583/zstandard-0.23.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:983b6efd649723474f29ed42e1467f90a35a74793437d0bc64a5bf482bedfa0a", size = 4944328 },
+ { url = "https://files.pythonhosted.org/packages/59/cc/e76acb4c42afa05a9d20827116d1f9287e9c32b7ad58cc3af0721ce2b481/zstandard-0.23.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:80a539906390591dd39ebb8d773771dc4db82ace6372c4d41e2d293f8e32b8db", size = 5311955 },
+ { url = "https://files.pythonhosted.org/packages/78/e4/644b8075f18fc7f632130c32e8f36f6dc1b93065bf2dd87f03223b187f26/zstandard-0.23.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:445e4cb5048b04e90ce96a79b4b63140e3f4ab5f662321975679b5f6360b90e2", size = 5344944 },
+ { url = "https://files.pythonhosted.org/packages/76/3f/dbafccf19cfeca25bbabf6f2dd81796b7218f768ec400f043edc767015a6/zstandard-0.23.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca", size = 5442927 },
+ { url = "https://files.pythonhosted.org/packages/0c/c3/d24a01a19b6733b9f218e94d1a87c477d523237e07f94899e1c10f6fd06c/zstandard-0.23.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d20fd853fbb5807c8e84c136c278827b6167ded66c72ec6f9a14b863d809211c", size = 4864910 },
+ { url = "https://files.pythonhosted.org/packages/1c/a9/cf8f78ead4597264f7618d0875be01f9bc23c9d1d11afb6d225b867cb423/zstandard-0.23.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ed1708dbf4d2e3a1c5c69110ba2b4eb6678262028afd6c6fbcc5a8dac9cda68e", size = 4935544 },
+ { url = "https://files.pythonhosted.org/packages/2c/96/8af1e3731b67965fb995a940c04a2c20997a7b3b14826b9d1301cf160879/zstandard-0.23.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:be9b5b8659dff1f913039c2feee1aca499cfbc19e98fa12bc85e037c17ec6ca5", size = 5467094 },
+ { url = "https://files.pythonhosted.org/packages/ff/57/43ea9df642c636cb79f88a13ab07d92d88d3bfe3e550b55a25a07a26d878/zstandard-0.23.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:65308f4b4890aa12d9b6ad9f2844b7ee42c7f7a4fd3390425b242ffc57498f48", size = 4860440 },
+ { url = "https://files.pythonhosted.org/packages/46/37/edb78f33c7f44f806525f27baa300341918fd4c4af9472fbc2c3094be2e8/zstandard-0.23.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:98da17ce9cbf3bfe4617e836d561e433f871129e3a7ac16d6ef4c680f13a839c", size = 4700091 },
+ { url = "https://files.pythonhosted.org/packages/c1/f1/454ac3962671a754f3cb49242472df5c2cced4eb959ae203a377b45b1a3c/zstandard-0.23.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8ed7d27cb56b3e058d3cf684d7200703bcae623e1dcc06ed1e18ecda39fee003", size = 5208682 },
+ { url = "https://files.pythonhosted.org/packages/85/b2/1734b0fff1634390b1b887202d557d2dd542de84a4c155c258cf75da4773/zstandard-0.23.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b69bb4f51daf461b15e7b3db033160937d3ff88303a7bc808c67bbc1eaf98c78", size = 5669707 },
+ { url = "https://files.pythonhosted.org/packages/52/5a/87d6971f0997c4b9b09c495bf92189fb63de86a83cadc4977dc19735f652/zstandard-0.23.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473", size = 5201792 },
+ { url = "https://files.pythonhosted.org/packages/79/02/6f6a42cc84459d399bd1a4e1adfc78d4dfe45e56d05b072008d10040e13b/zstandard-0.23.0-cp311-cp311-win32.whl", hash = "sha256:f2d4380bf5f62daabd7b751ea2339c1a21d1c9463f1feb7fc2bdcea2c29c3160", size = 430586 },
+ { url = "https://files.pythonhosted.org/packages/be/a2/4272175d47c623ff78196f3c10e9dc7045c1b9caf3735bf041e65271eca4/zstandard-0.23.0-cp311-cp311-win_amd64.whl", hash = "sha256:62136da96a973bd2557f06ddd4e8e807f9e13cbb0bfb9cc06cfe6d98ea90dfe0", size = 495420 },
+ { url = "https://files.pythonhosted.org/packages/7b/83/f23338c963bd9de687d47bf32efe9fd30164e722ba27fb59df33e6b1719b/zstandard-0.23.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b4567955a6bc1b20e9c31612e615af6b53733491aeaa19a6b3b37f3b65477094", size = 788713 },
+ { url = "https://files.pythonhosted.org/packages/5b/b3/1a028f6750fd9227ee0b937a278a434ab7f7fdc3066c3173f64366fe2466/zstandard-0.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e172f57cd78c20f13a3415cc8dfe24bf388614324d25539146594c16d78fcc8", size = 633459 },
+ { url = "https://files.pythonhosted.org/packages/26/af/36d89aae0c1f95a0a98e50711bc5d92c144939efc1f81a2fcd3e78d7f4c1/zstandard-0.23.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0e166f698c5a3e914947388c162be2583e0c638a4703fc6a543e23a88dea3c1", size = 4945707 },
+ { url = "https://files.pythonhosted.org/packages/cd/2e/2051f5c772f4dfc0aae3741d5fc72c3dcfe3aaeb461cc231668a4db1ce14/zstandard-0.23.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12a289832e520c6bd4dcaad68e944b86da3bad0d339ef7989fb7e88f92e96072", size = 5306545 },
+ { url = "https://files.pythonhosted.org/packages/0a/9e/a11c97b087f89cab030fa71206963090d2fecd8eb83e67bb8f3ffb84c024/zstandard-0.23.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d50d31bfedd53a928fed6707b15a8dbeef011bb6366297cc435accc888b27c20", size = 5337533 },
+ { url = "https://files.pythonhosted.org/packages/fc/79/edeb217c57fe1bf16d890aa91a1c2c96b28c07b46afed54a5dcf310c3f6f/zstandard-0.23.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72c68dda124a1a138340fb62fa21b9bf4848437d9ca60bd35db36f2d3345f373", size = 5436510 },
+ { url = "https://files.pythonhosted.org/packages/81/4f/c21383d97cb7a422ddf1ae824b53ce4b51063d0eeb2afa757eb40804a8ef/zstandard-0.23.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:53dd9d5e3d29f95acd5de6802e909ada8d8d8cfa37a3ac64836f3bc4bc5512db", size = 4859973 },
+ { url = "https://files.pythonhosted.org/packages/ab/15/08d22e87753304405ccac8be2493a495f529edd81d39a0870621462276ef/zstandard-0.23.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:6a41c120c3dbc0d81a8e8adc73312d668cd34acd7725f036992b1b72d22c1772", size = 4936968 },
+ { url = "https://files.pythonhosted.org/packages/eb/fa/f3670a597949fe7dcf38119a39f7da49a8a84a6f0b1a2e46b2f71a0ab83f/zstandard-0.23.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:40b33d93c6eddf02d2c19f5773196068d875c41ca25730e8288e9b672897c105", size = 5467179 },
+ { url = "https://files.pythonhosted.org/packages/4e/a9/dad2ab22020211e380adc477a1dbf9f109b1f8d94c614944843e20dc2a99/zstandard-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9206649ec587e6b02bd124fb7799b86cddec350f6f6c14bc82a2b70183e708ba", size = 4848577 },
+ { url = "https://files.pythonhosted.org/packages/08/03/dd28b4484b0770f1e23478413e01bee476ae8227bbc81561f9c329e12564/zstandard-0.23.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:76e79bc28a65f467e0409098fa2c4376931fd3207fbeb6b956c7c476d53746dd", size = 4693899 },
+ { url = "https://files.pythonhosted.org/packages/2b/64/3da7497eb635d025841e958bcd66a86117ae320c3b14b0ae86e9e8627518/zstandard-0.23.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:66b689c107857eceabf2cf3d3fc699c3c0fe8ccd18df2219d978c0283e4c508a", size = 5199964 },
+ { url = "https://files.pythonhosted.org/packages/43/a4/d82decbab158a0e8a6ebb7fc98bc4d903266bce85b6e9aaedea1d288338c/zstandard-0.23.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9c236e635582742fee16603042553d276cca506e824fa2e6489db04039521e90", size = 5655398 },
+ { url = "https://files.pythonhosted.org/packages/f2/61/ac78a1263bc83a5cf29e7458b77a568eda5a8f81980691bbc6eb6a0d45cc/zstandard-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a8fffdbd9d1408006baaf02f1068d7dd1f016c6bcb7538682622c556e7b68e35", size = 5191313 },
+ { url = "https://files.pythonhosted.org/packages/e7/54/967c478314e16af5baf849b6ee9d6ea724ae5b100eb506011f045d3d4e16/zstandard-0.23.0-cp312-cp312-win32.whl", hash = "sha256:dc1d33abb8a0d754ea4763bad944fd965d3d95b5baef6b121c0c9013eaf1907d", size = 430877 },
+ { url = "https://files.pythonhosted.org/packages/75/37/872d74bd7739639c4553bf94c84af7d54d8211b626b352bc57f0fd8d1e3f/zstandard-0.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:64585e1dba664dc67c7cdabd56c1e5685233fbb1fc1966cfba2a340ec0dfff7b", size = 495595 },
+ { url = "https://files.pythonhosted.org/packages/80/f1/8386f3f7c10261fe85fbc2c012fdb3d4db793b921c9abcc995d8da1b7a80/zstandard-0.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:576856e8594e6649aee06ddbfc738fec6a834f7c85bf7cadd1c53d4a58186ef9", size = 788975 },
+ { url = "https://files.pythonhosted.org/packages/16/e8/cbf01077550b3e5dc86089035ff8f6fbbb312bc0983757c2d1117ebba242/zstandard-0.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:38302b78a850ff82656beaddeb0bb989a0322a8bbb1bf1ab10c17506681d772a", size = 633448 },
+ { url = "https://files.pythonhosted.org/packages/06/27/4a1b4c267c29a464a161aeb2589aff212b4db653a1d96bffe3598f3f0d22/zstandard-0.23.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d2240ddc86b74966c34554c49d00eaafa8200a18d3a5b6ffbf7da63b11d74ee2", size = 4945269 },
+ { url = "https://files.pythonhosted.org/packages/7c/64/d99261cc57afd9ae65b707e38045ed8269fbdae73544fd2e4a4d50d0ed83/zstandard-0.23.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2ef230a8fd217a2015bc91b74f6b3b7d6522ba48be29ad4ea0ca3a3775bf7dd5", size = 5306228 },
+ { url = "https://files.pythonhosted.org/packages/7a/cf/27b74c6f22541f0263016a0fd6369b1b7818941de639215c84e4e94b2a1c/zstandard-0.23.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:774d45b1fac1461f48698a9d4b5fa19a69d47ece02fa469825b442263f04021f", size = 5336891 },
+ { url = "https://files.pythonhosted.org/packages/fa/18/89ac62eac46b69948bf35fcd90d37103f38722968e2981f752d69081ec4d/zstandard-0.23.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6f77fa49079891a4aab203d0b1744acc85577ed16d767b52fc089d83faf8d8ed", size = 5436310 },
+ { url = "https://files.pythonhosted.org/packages/a8/a8/5ca5328ee568a873f5118d5b5f70d1f36c6387716efe2e369010289a5738/zstandard-0.23.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ac184f87ff521f4840e6ea0b10c0ec90c6b1dcd0bad2f1e4a9a1b4fa177982ea", size = 4859912 },
+ { url = "https://files.pythonhosted.org/packages/ea/ca/3781059c95fd0868658b1cf0440edd832b942f84ae60685d0cfdb808bca1/zstandard-0.23.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c363b53e257246a954ebc7c488304b5592b9c53fbe74d03bc1c64dda153fb847", size = 4936946 },
+ { url = "https://files.pythonhosted.org/packages/ce/11/41a58986f809532742c2b832c53b74ba0e0a5dae7e8ab4642bf5876f35de/zstandard-0.23.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:e7792606d606c8df5277c32ccb58f29b9b8603bf83b48639b7aedf6df4fe8171", size = 5466994 },
+ { url = "https://files.pythonhosted.org/packages/83/e3/97d84fe95edd38d7053af05159465d298c8b20cebe9ccb3d26783faa9094/zstandard-0.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a0817825b900fcd43ac5d05b8b3079937073d2b1ff9cf89427590718b70dd840", size = 4848681 },
+ { url = "https://files.pythonhosted.org/packages/6e/99/cb1e63e931de15c88af26085e3f2d9af9ce53ccafac73b6e48418fd5a6e6/zstandard-0.23.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:9da6bc32faac9a293ddfdcb9108d4b20416219461e4ec64dfea8383cac186690", size = 4694239 },
+ { url = "https://files.pythonhosted.org/packages/ab/50/b1e703016eebbc6501fc92f34db7b1c68e54e567ef39e6e59cf5fb6f2ec0/zstandard-0.23.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fd7699e8fd9969f455ef2926221e0233f81a2542921471382e77a9e2f2b57f4b", size = 5200149 },
+ { url = "https://files.pythonhosted.org/packages/aa/e0/932388630aaba70197c78bdb10cce2c91fae01a7e553b76ce85471aec690/zstandard-0.23.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d477ed829077cd945b01fc3115edd132c47e6540ddcd96ca169facff28173057", size = 5655392 },
+ { url = "https://files.pythonhosted.org/packages/02/90/2633473864f67a15526324b007a9f96c96f56d5f32ef2a56cc12f9548723/zstandard-0.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fa6ce8b52c5987b3e34d5674b0ab529a4602b632ebab0a93b07bfb4dfc8f8a33", size = 5191299 },
+ { url = "https://files.pythonhosted.org/packages/b0/4c/315ca5c32da7e2dc3455f3b2caee5c8c2246074a61aac6ec3378a97b7136/zstandard-0.23.0-cp313-cp313-win32.whl", hash = "sha256:a9b07268d0c3ca5c170a385a0ab9fb7fdd9f5fd866be004c4ea39e44edce47dd", size = 430862 },
+ { url = "https://files.pythonhosted.org/packages/a2/bf/c6aaba098e2d04781e8f4f7c0ba3c7aa73d00e4c436bcc0cf059a66691d1/zstandard-0.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:f3513916e8c645d0610815c257cbfd3242adfd5c4cfa78be514e5a3ebb42a41b", size = 495578 },
+ { url = "https://files.pythonhosted.org/packages/fb/96/4fcafeb7e013a2386d22f974b5b97a0b9a65004ed58c87ae001599bfbd48/zstandard-0.23.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3aa014d55c3af933c1315eb4bb06dd0459661cc0b15cd61077afa6489bec63bb", size = 788697 },
+ { url = "https://files.pythonhosted.org/packages/83/ff/a52ce725be69b86a2967ecba0497a8184540cc284c0991125515449e54e2/zstandard-0.23.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:0a7f0804bb3799414af278e9ad51be25edf67f78f916e08afdb983e74161b916", size = 633679 },
+ { url = "https://files.pythonhosted.org/packages/34/0f/3dc62db122f6a9c481c335fff6fc9f4e88d8f6e2d47321ee3937328addb4/zstandard-0.23.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fb2b1ecfef1e67897d336de3a0e3f52478182d6a47eda86cbd42504c5cbd009a", size = 4940416 },
+ { url = "https://files.pythonhosted.org/packages/1d/e5/9fe0dd8c85fdc2f635e6660d07872a5dc4b366db566630161e39f9f804e1/zstandard-0.23.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:837bb6764be6919963ef41235fd56a6486b132ea64afe5fafb4cb279ac44f259", size = 5307693 },
+ { url = "https://files.pythonhosted.org/packages/73/bf/fe62c0cd865c171ee8ed5bc83174b5382a2cb729c8d6162edfb99a83158b/zstandard-0.23.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1516c8c37d3a053b01c1c15b182f3b5f5eef19ced9b930b684a73bad121addf4", size = 5341236 },
+ { url = "https://files.pythonhosted.org/packages/39/86/4fe79b30c794286110802a6cd44a73b6a314ac8196b9338c0fbd78c2407d/zstandard-0.23.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:48ef6a43b1846f6025dde6ed9fee0c24e1149c1c25f7fb0a0585572b2f3adc58", size = 5439101 },
+ { url = "https://files.pythonhosted.org/packages/72/ed/cacec235c581ebf8c608c7fb3d4b6b70d1b490d0e5128ea6996f809ecaef/zstandard-0.23.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:11e3bf3c924853a2d5835b24f03eeba7fc9b07d8ca499e247e06ff5676461a15", size = 4860320 },
+ { url = "https://files.pythonhosted.org/packages/f6/1e/2c589a2930f93946b132fc852c574a19d5edc23fad2b9e566f431050c7ec/zstandard-0.23.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:2fb4535137de7e244c230e24f9d1ec194f61721c86ebea04e1581d9d06ea1269", size = 4931933 },
+ { url = "https://files.pythonhosted.org/packages/8e/f5/30eadde3686d902b5d4692bb5f286977cbc4adc082145eb3f49d834b2eae/zstandard-0.23.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8c24f21fa2af4bb9f2c492a86fe0c34e6d2c63812a839590edaf177b7398f700", size = 5463878 },
+ { url = "https://files.pythonhosted.org/packages/e0/c8/8aed1f0ab9854ef48e5ad4431367fcb23ce73f0304f7b72335a8edc66556/zstandard-0.23.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:a8c86881813a78a6f4508ef9daf9d4995b8ac2d147dcb1a450448941398091c9", size = 4857192 },
+ { url = "https://files.pythonhosted.org/packages/a8/c6/55e666cfbcd032b9e271865e8578fec56e5594d4faeac379d371526514f5/zstandard-0.23.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:fe3b385d996ee0822fd46528d9f0443b880d4d05528fd26a9119a54ec3f91c69", size = 4696513 },
+ { url = "https://files.pythonhosted.org/packages/dc/bd/720b65bea63ec9de0ac7414c33b9baf271c8de8996e5ff324dc93fc90ff1/zstandard-0.23.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:82d17e94d735c99621bf8ebf9995f870a6b3e6d14543b99e201ae046dfe7de70", size = 5204823 },
+ { url = "https://files.pythonhosted.org/packages/d8/40/d678db1556e3941d330cd4e95623a63ef235b18547da98fa184cbc028ecf/zstandard-0.23.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:c7c517d74bea1a6afd39aa612fa025e6b8011982a0897768a2f7c8ab4ebb78a2", size = 5666490 },
+ { url = "https://files.pythonhosted.org/packages/ed/cc/c89329723d7515898a1fc7ef5d251264078548c505719d13e9511800a103/zstandard-0.23.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:1fd7e0f1cfb70eb2f95a19b472ee7ad6d9a0a992ec0ae53286870c104ca939e5", size = 5196622 },
+ { url = "https://files.pythonhosted.org/packages/78/4c/634289d41e094327a94500dfc919e58841b10ea3a9efdfafbac614797ec2/zstandard-0.23.0-cp39-cp39-win32.whl", hash = "sha256:43da0f0092281bf501f9c5f6f3b4c975a8a0ea82de49ba3f7100e64d422a1274", size = 430620 },
+ { url = "https://files.pythonhosted.org/packages/a2/e2/0b0c5a0f4f7699fecd92c1ba6278ef9b01f2b0b0dd46f62bfc6729c05659/zstandard-0.23.0-cp39-cp39-win_amd64.whl", hash = "sha256:f8346bfa098532bc1fb6c7ef06783e969d87a99dd1d2a5a18a892c1d7a643c58", size = 495528 },
+]
+
+[package.optional-dependencies]
+cffi = [
+ { name = "cffi", marker = "platform_python_implementation == 'PyPy'" },
+]